{"id":"5111","text":"\"\"\"\n# Getting Started\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport re\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\ndata = pd.read_csv('..\/input\/all-space-missions-from-1957\/Space_Corrected.csv')\ndata\n\"\"\"\n# Preprocessing\n\"\"\"\ndata.drop([data.columns[0], data.columns[1], 'Location', 'Detail'], axis=1, inplace=True)\ndata\ndata.columns\ndata.columns = ['Company Name', 'Datum', 'Status Rocket', 'Rocket', 'Status Mission']\n\"\"\"\n## Missing Values\n\"\"\"\ndata.isnull().sum()\ndata['Rocket'].unique()\nfor value in data['Rocket']:\n    print(type(value))\ndata['Rocket'] = data['Rocket'].astype(str).apply(lambda x: x.replace(',', '')).astype(np.float32)\ndata['Rocket'] = data['Rocket'].fillna(data['Rocket'].mean())\ndata.isnull().sum()\n\"\"\"\n## Encoding\n\"\"\"\ndata\ndef get_year_from_date(date):\n    year = re.search(r'[^,]*$', date).group(0)\n    year = re.search(r'^\\s[^\\s]*', year).group(0)\n    return np.int16(year)\ndef get_month_from_date(date):\n    month = re.search(r'^[^0-9]*', date).group(0)\n    month = re.search(r'\\s.*$', month).group(0)\n    return month.strip()\n    \ndata['Year'] = data['Datum'].apply(get_year_from_date)\ndata['Month'] = data['Datum'].apply(get_month_from_date)\ndata.drop('Datum', axis=1, inplace=True)\ndata\ndata['Status Mission'].unique()\ndata['Status Mission'] = data['Status Mission'].apply(lambda x: x if x == 'Success' else 'Failure')\nencoder = LabelEncoder()\n\ndata['Status Mission'] = encoder.fit_transform(data['Status Mission'])\ndata\nmonth_ordering = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\ndata['Status Rocket'].unique()\nstatus_ordering = ['StatusRetired', 'StatusActive']\n# Given some data, a column of that data, and an ordering of the values in that column,\n# perform ordinal encoding on the column and return the result.\n\ndef ordinal_encode(data, column, ordering):\n    return data[column].apply(lambda x: ordering.index(x))\ndata['Month'] = ordinal_encode(data, 'Month', month_ordering)\ndata['Status Rocket'] = ordinal_encode(data, 'Status Rocket', status_ordering)\ndata\ndef onehot_encode(data, column):\n    dummies = pd.get_dummies(data[column])\n    data = pd.concat([data, dummies], axis=1)\n    data.drop(column, axis=1, inplace=True)\n    return data\ndata = onehot_encode(data, 'Company Name')\ndata\n\"\"\"\n## Scaling\n\"\"\"\ny = data['Status Mission']\nX = data.drop('Status Mission', axis=1)\nscaler = MinMaxScaler()\n\nX = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\nX\n\"\"\"\n# Training\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)\ny.sum() \/ len(y)\ninputs = tf.keras.Input(shape=(60,))\nx = tf.keras.layers.Dense(16, activation='relu')(inputs)\nx = tf.keras.layers.Dense(16, activation='relu')(x)\noutputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n\nmodel = tf.keras.Model(inputs=inputs, outputs=outputs)\n\n\nmodel.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=[tf.keras.metrics.AUC(name='auc')]\n)\n\n\nbatch_size=32\nepochs=35\n\nhistory = model.fit(\n    X_train,\n    y_train,\n    validation_split=0.2,\n    batch_size=batch_size,\n    epochs=epochs\n)\nplt.figure(figsize=(14, 10))\n\nepochs_range = range(1, epochs + 1)\ntrain_loss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.plot(epochs_range, train_loss, label=\"Training Loss\")\nplt.plot(epochs_range, val_loss, label=\"Validation Loss\")\n\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.legend('upper right')\n\nplt.show()\nnp.argmin(val_loss)\nmodel.evaluate(X_test, y_test)","meta":"{'source': 'AI4Code', 'id': '09775e224936f6'}"}
{"id":"36911","text":"\"\"\"\n# 1- Linear Regression\n\"\"\"\n#Imports\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\n# Data prep\nX_numpy, y_numpy = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=4)\n\n# cast to float Tensor\nX = torch.from_numpy(X_numpy.astype(np.float32))\ny = torch.from_numpy(y_numpy.astype(np.float32))\ny = y.view(y.shape[0], 1) #to make it column\n\nn_samples, n_features = X.shape\n# Create the model\n\nmodel = nn.Linear(n_features, 1)\n# Calculate loss and  define the optimizer\nlearning_rate = 0.01\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n# Training \nnum_epochs = 100\nfor epoch in range(num_epochs):\n    # Forward pass and loss\n    y_predicted = model(X)\n    loss = criterion(y_predicted, y)\n    \n    # Backward pass and update\n    loss.backward()\n    optimizer.step()\n\n    # zero grad before new step\n    optimizer.zero_grad()\n\n    if (epoch+1) % 10 == 0:\n        print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')\n# Plot\npredicted = model(X).detach().numpy()\n\nplt.plot(X_numpy, y_numpy, 'ro')\nplt.plot(X_numpy, predicted, 'b')\nplt.show()\n\"\"\"\n# 2- Logistic Regression\n\"\"\"\n# Imports\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n# Data prep\n\nbc = datasets.load_breast_cancer()\nX, y = bc.data, bc.target\n\nn_samples, n_features = X.shape\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)\n# scale\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\nX_train = torch.from_numpy(X_train.astype(np.float32))\nX_test = torch.from_numpy(X_test.astype(np.float32))\ny_train = torch.from_numpy(y_train.astype(np.float32))\ny_test = torch.from_numpy(y_test.astype(np.float32))\n\ny_train = y_train.view(y_train.shape[0], 1)\ny_test = y_test.view(y_test.shape[0], 1)\n# Create custom model\n# Linear model f = wx + b , sigmoid at the end\nclass Model(nn.Module):\n    def __init__(self, n_input_features):\n        super(Model, self).__init__()\n        self.linear = nn.Linear(n_input_features, 1)\n\n    def forward(self, x):\n        y_pred = torch.sigmoid(self.linear(x))\n        return y_pred\n\nmodel = Model(n_features)\n# Calculate loss and  define the optimizer\nnum_epochs = 100\nlearning_rate = 0.01\ncriterion = nn.BCELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n# Training \nfor epoch in range(num_epochs):\n    # Forward pass and loss\n    y_pred = model(X_train)\n    loss = criterion(y_pred, y_train)\n\n    # Backward pass and update\n    loss.backward()\n    optimizer.step()\n\n    # zero grad before new step\n    optimizer.zero_grad()\n\n    if (epoch+1) % 10 == 0:\n        print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')\n# Test\nwith torch.no_grad():\n    y_predicted = model(X_test)\n    y_predicted_cls = y_predicted.round()\n    acc = y_predicted_cls.eq(y_test).sum() \/ float(y_test.shape[0])\n    print(f'accuracy: {acc.item():.4f}')","meta":"{'source': 'AI4Code', 'id': '43f52404cd99c9'}"}
{"id":"82907","text":"\"\"\"\n#### This is fork of https:\/\/www.kaggle.com\/code1110\/janestreet-faster-inference-by-xgb-with-treelite beautifull notebook on how to make faster prediction with xgb!! <br>\n\n#### I'm using PurgedGroupTimeSeriesSplit for validation with multitarget.\n\"\"\"\n\"\"\"\n# Install treelite\n\"\"\"\n!pip --quiet install ..\/input\/treelite\/treelite-0.93-py3-none-manylinux2010_x86_64.whl\n!pip --quiet install ..\/input\/treelite\/treelite_runtime-0.93-py3-none-manylinux2010_x86_64.whl\n\"\"\"\n# Imports \ud83d\udeec\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport os, sys\nimport gc\nimport math\nimport random\nimport pathlib\nfrom tqdm import tqdm\nfrom typing import List, NoReturn, Union, Tuple, Optional, Text, Generic, Callable, Dict\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, QuantileTransformer\nfrom sklearn.decomposition import PCA\nfrom sklearn import linear_model\nimport operator\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom tqdm import tqdm\n\n# treelite\nimport treelite\nimport treelite_runtime \n\n# visualize\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport seaborn as sns\nfrom matplotlib_venn import venn2\nfrom matplotlib import pyplot\nfrom matplotlib.ticker import ScalarFormatter\nsns.set_context(\"talk\")\nstyle.use('fivethirtyeight')\npd.options.display.max_columns = None\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n# PurgedGroupTimeSeriesSplit\n\"\"\"\nfrom sklearn.metrics import roc_auc_score\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection._split import _BaseKFold, indexable, _num_samples\nfrom sklearn.utils.validation import _deprecate_positional_args\nclass PurgedGroupTimeSeriesSplit(_BaseKFold):\n    \"\"\"Time Series cross-validator variant with non-overlapping groups.\n    Allows for a gap in groups to avoid potentially leaking info from\n    train into test if the model has windowed or lag features.\n    Provides train\/test indices to split time series data samples\n    that are observed at fixed time intervals according to a\n    third-party provided group.\n    In each split, test indices must be higher than before, and thus shuffling\n    in cross validator is inappropriate.\n    This cross-validation object is a variation of :class:`KFold`.\n    In the kth split, it returns first k folds as train set and the\n    (k+1)th fold as test set.\n    The same group will not appear in two different folds (the number of\n    distinct groups has to be at least equal to the number of folds).\n    Note that unlike standard cross-validation methods, successive\n    training sets are supersets of those that come before them.\n    Read more in the :ref:`User Guide <cross_validation>`.\n    Parameters\n    ----------\n    n_splits : int, default=5\n        Number of splits. Must be at least 2.\n    max_train_group_size : int, default=Inf\n        Maximum group size for a single training set.\n    group_gap : int, default=None\n        Gap between train and test\n    max_test_group_size : int, default=Inf\n        We discard this number of groups from the end of each train split\n    \"\"\"\n\n    @_deprecate_positional_args\n    def __init__(self,\n                 n_splits=5,\n                 *,\n                 max_train_group_size=np.inf,\n                 max_test_group_size=np.inf,\n                 group_gap=None,\n                 verbose=False\n                 ):\n        super().__init__(n_splits, shuffle=False, random_state=None)\n        self.max_train_group_size = max_train_group_size\n        self.group_gap = group_gap\n        self.max_test_group_size = max_test_group_size\n        self.verbose = verbose\n\n    def split(self, X, y=None, groups=None):\n        \"\"\"Generate indices to split data into training and test set.\n        Parameters\n        ----------\n        X : array-like of shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n        y : array-like of shape (n_samples,)\n            Always ignored, exists for compatibility.\n        groups : array-like of shape (n_samples,)\n            Group labels for the samples used while splitting the dataset into\n            train\/test set.\n        Yields\n        ------\n        train : ndarray\n            The training set indices for that split.\n        test : ndarray\n            The testing set indices for that split.\n        \"\"\"\n        if groups is None:\n            raise ValueError(\n                \"The 'groups' parameter should not be None\")\n        X, y, groups = indexable(X, y, groups)\n        n_samples = _num_samples(X)\n        n_splits = self.n_splits\n        group_gap = self.group_gap\n        max_test_group_size = self.max_test_group_size\n        max_train_group_size = self.max_train_group_size\n        n_folds = n_splits + 1\n        group_dict = {}\n        u, ind = np.unique(groups, return_index=True)\n        unique_groups = u[np.argsort(ind)]\n        n_samples = _num_samples(X)\n        n_groups = _num_samples(unique_groups)\n        for idx in np.arange(n_samples):\n            if (groups[idx] in group_dict):\n                group_dict[groups[idx]].append(idx)\n            else:\n                group_dict[groups[idx]] = [idx]\n        if n_folds > n_groups:\n            raise ValueError(\n                (\"Cannot have number of folds={0} greater than\"\n                 \" the number of groups={1}\").format(n_folds,\n                                                     n_groups))\n\n        group_test_size = min(n_groups \/\/ n_folds, max_test_group_size)\n        group_test_starts = range(n_groups - n_splits * group_test_size,\n                                  n_groups, group_test_size)\n        for group_test_start in group_test_starts:\n            train_array = []\n            test_array = []\n\n            group_st = max(0, group_test_start - group_gap - max_train_group_size)\n            for train_group_idx in unique_groups[group_st:(group_test_start - group_gap)]:\n                train_array_tmp = group_dict[train_group_idx]\n                \n                train_array = np.sort(np.unique(\n                                      np.concatenate((train_array,\n                                                      train_array_tmp)),\n                                      axis=None), axis=None)\n\n            train_end = train_array.size\n \n            for test_group_idx in unique_groups[group_test_start:\n                                                group_test_start +\n                                                group_test_size]:\n                test_array_tmp = group_dict[test_group_idx]\n                test_array = np.sort(np.unique(\n                                              np.concatenate((test_array,\n                                                              test_array_tmp)),\n                                     axis=None), axis=None)\n\n            test_array  = test_array[group_gap:]\n            \n            \n            if self.verbose > 0:\n                    pass\n                    \n            yield [int(i) for i in train_array], [int(i) for i in test_array]\n\"\"\"\n# Config \ud83d\udd27\n\"\"\"\nSEED = 42 # Happy new year!\n# INPUT_DIR = '..\/input\/jane-street-market-prediction\/'\nSTART_DATE = 85\nINPUT_DIR = '..\/input\/janestreet-save-as-feather\/'\nTRADING_THRESHOLD = 0.502 # 0 ~ 1: The smaller, the more aggressive\n\"\"\"\n# Load Data and Data Preprocessing\n\n\"\"\"\nos.listdir(INPUT_DIR)\n%%time\n\ndef load_data(input_dir=INPUT_DIR):\n    train = pd.read_feather(pathlib.Path(input_dir + 'train.feather'))\n    #features = pd.read_feather(pathlib.Path(input_dir + 'features.feather'))\n    #example_test = pd.read_feather(pathlib.Path(input_dir + 'example_test.feather'))\n    #ss = pd.read_feather(pathlib.Path(input_dir + 'example_sample_submission.feather'))\n    return train\ntrain = load_data(INPUT_DIR)\n# reduce train\ntrain = train.query(f'date > {START_DATE}')\ntrain.fillna(train.mean(),inplace=True)\ntrain = train[train['weight'] != 0]\n# features\nfeatures = train.columns[train.columns.str.startswith('feature')].values.tolist()\nprint('{} features used'.format(len(features)))\n# target\ntrain['action'] = (train['resp'] > 0).astype('int')\nf_mean = np.mean(train[features[1:]].values,axis=0)\n\"\"\"\n# Model\ud83d\udcaa\n\"\"\"\nparams = {'n_estimators': 473, 'max_depth': 7, 'min_child_weight': 6, \n 'learning_rate': 0.015944928866056352, 'subsample': 0.608128483148888, \n 'gamma': 0, 'colsample_bytree': 0.643875232059528,'objective':'binary:logistic',\n'eval_metric': 'auc','tree_method': 'gpu_hist', 'random_state': 42,} \n\nparams_1 = {'n_estimators': 494, 'max_depth': 8, 'min_child_weight': 6, 'learning_rate': 0.009624384025871735, \n            'subsample': 0.8328412036014541, 'gamma': 0, 'colsample_bytree': 0.715303237773365,\n           'objective':'binary:logistic', 'eval_metric': 'auc','tree_method': 'gpu_hist', 'random_state': 42,}\ntraining = True\nimport pickle\n\nif training:\n    import time\n    import gc\n    resp_cols = ['resp_1', 'resp_2', 'resp_3', 'resp', 'resp_4']\n    X = train[features].values\n    #y = train['action'].values\n    y = np.stack([(train[c] > 0).astype('int') for c in resp_cols]).T #Multitarget\n    groups = train['date'].values\n    models = []\n    scores = []\n\n    cv = PurgedGroupTimeSeriesSplit(\n        n_splits=4,\n        group_gap=20,\n    )\n    for t in tqdm(range(y.shape[1])):\n        yy = y[:,t]\n        for i, (train_index, valid_index) in enumerate(cv.split(\n                X,\n                yy,\n                groups=groups)):\n            print(f'Target {t} Fold {i} started at {time.ctime()}')\n            X_train, X_valid = X[train_index], X[valid_index]\n            y_train, y_valid = yy[train_index], yy[valid_index]\n            model = xgb.XGBClassifier(**params_1, n_jobs = -1)\n            model.fit(X_train, y_train, \n                    eval_set=[(X_valid, y_valid)], eval_metric='auc',\n                    verbose=100, callbacks = [xgb.callback.EarlyStopping(rounds=300,save_best=True)])\n            pred = model.predict(X_valid)\n            score = roc_auc_score(y_valid,pred)\n            model.save_model(f'my_model_{t}_{i}.model')\n            pickle.dump(model, open(f'my_model_{t}_{i}.pkl', \"wb\"))\n            models.append(model)\n            scores.append(score)\n            del score, model\n        print(scores)\n        del X_train, X_valid, y_train, y_valid\n        rubbish = gc.collect()\n\"\"\"\n# Compile with Treelite\nSimply follow the tutorial: https:\/\/treelite.readthedocs.io\/en\/latest\/tutorials\/first.html\n\"\"\"\n# pass to treelite\nif training:\n    model_0 = treelite.Model.load('my_model_0_3.model', model_format='xgboost')\n    model_1 = treelite.Model.load('my_model_1_3.model', model_format='xgboost')\n    model_2 = treelite.Model.load('my_model_2_3.model', model_format='xgboost')\n    model_3 = treelite.Model.load('my_model_3_3.model', model_format='xgboost')\n    model_4 = treelite.Model.load('my_model_4_3.model', model_format='xgboost')\nif training:\n    m = [model_0,model_1,model_2,model_3,model_4]\n    for j,i in enumerate(m):\n        toolchain = 'gcc'\n        i.export_lib(toolchain=toolchain, libpath=f'.\/mymodel_{j}.so',\n                     params={'parallel_comp': 32}, verbose=True)\n# predictor from treelite\nif training:\n    predictor_0 = treelite_runtime.Predictor(f'.\/mymodel_{0}.so', verbose=True)\n    predictor_1 = treelite_runtime.Predictor(f'.\/mymodel_{1}.so', verbose=True)\n    predictor_2 = treelite_runtime.Predictor(f'.\/mymodel_{2}.so', verbose=True)\n    predictor_3 = treelite_runtime.Predictor(f'.\/mymodel_{3}.so', verbose=True)\n    predictor_4 = treelite_runtime.Predictor(f'.\/mymodel_{4}.so', verbose=True)\n\"\"\"\n# \ud83c\udff9Submission\ud83c\udfaf\n\"\"\"\nimport janestreet\nenv = janestreet.make_env() # initialize the environment\niter_test = env.iter_test() # an iterator which loops over the test set\nf = np.median \nindex_features = [n for n in range(1,(len(features) + 1))]\nfor (test_df, pred_df) in tqdm(iter_test):\n    \n    if test_df['weight'].item() > 0:\n        \n        \n        x_tt = test_df.values[0][index_features].reshape(1,-1)\n            \n        if np.isnan(x_tt[:, 1:].sum()):\n            x_tt[:, 1:] = np.nan_to_num(x_tt[:, 1:]) + np.isnan(x_tt[:, 1:]) * f_mean\n        \n        # inference with treelite\n        batch = treelite_runtime.Batch.from_npy2d(x_tt)\n        pred_0 = predictor_0.predict(batch)\n        pred_1 = predictor_1.predict(batch)\n        pred_2 = predictor_2.predict(batch)\n        pred_3 = predictor_3.predict(batch)\n        pred_4 = predictor_4.predict(batch)\n        \n        # Prediction\n        pred = np.stack([pred_0,pred_1,pred_2,pred_3,pred_4],axis=0).T\n        pred = f(pred)\n        pred_df.action = int(pred >= TRADING_THRESHOLD)\n        \n    else:\n         pred_df['action'].values[0] = 0\n    env.predict(pred_df)\n\"\"\"\n# If this notebook helped Please do Upvote \ud83d\udc98\ud83d\udc99\u2705\n\n## Part 2 getting ready with feature selction!!! \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '983be5f1810ce2'}"}
{"id":"69916","text":"import os\nimport pandas as pd\nimport numpy as np\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport contextily as ctx\nfrom mpl_toolkits.basemap import Basemap\n\"\"\"\nHello!\n\nI am going to analyze this Autrailian fire dataset that was obtained by a satellite to visually see how the deadly fires have evlolved mainly using the matplotlib library.\nLet's first load the dataset.\n\"\"\"\ndf1=pd.read_csv('..\/input\/fires-from-space-australia-and-new-zeland\/fire_nrt_M6_96619.csv')\n\"\"\"\nA quick peek at the dataset shows that the severity of the fires was represented as \"brightness\" and each point has latitude and longitude tagged with the times that the datasets were acquired. The 'hours' when the data points were acquired also can be differentiated by looking at the \"daynight\" column (D represent daytime and N represents nighttime). We are going to visually plot the brightness data on the 'actual' map of Austrailia.\n\"\"\"\ndf1.head()\ndf1.dtypes\n\"\"\"\nWe\u2019re going to import the image sub-package of matplotlib, which handles matplotlib\u2019s image manipulations.\nI also uploaded the Austrailian map image file to this kernel.\n\"\"\"\nimport matplotlib.image as mpimg\naus_img=mpimg.imread('\/kaggle\/input\/mappng\/map.png')\n\"\"\"\nTo map brightness values in the map, I first converted latitude, longitude and brightness datatypes to \"values\" to use them with \"Basemap\" toolkit.\nLat_0 and lon_0 arguments in the \"Basemap\" represent the OZMIDLAT and OZMIDLON values respectively for Austrailia.\n\"\"\"\nlat = df1['latitude'].values\nlon = df1['longitude'].values\nbrg = df1['brightness'].values\n\nfig = plt.figure(figsize = (10, 10))\nm = Basemap(projection = 'lcc', resolution='c', lat_0 =-27.6, lon_0 = 134.35,width=5E6, height=4E6)\nm.shadedrelief()\nm.drawcoastlines(color='gray')\nm.drawcountries(color='gray')\nm.drawstates(color='gray')\n\nm.scatter(lon, lat, c= brg,latlon=True,cmap='Reds', alpha=0.6)\nplt.colorbar(label=r'$Brightness$')\n\n\"\"\"\nThis is a nice looking map with the brightness level represented as shown in the colorbar.\nHowever, this is the whole data set that has no time information (no time specific)\n\"\"\"\n\"\"\"\nTo get some time specific information, let's differentiate daytime and nighttime brightness data. To do that we apply \"isin\" function to the pandas dataframe.\n\"\"\"\ndf1_night=df1.loc[df1['daynight'].isin(['N'])]\ndf1_day=df1.loc[df1['daynight'].isin(['D'])]\n\"\"\"\nThen, the same mapping proceudre as above. The red and blue points on the map represent the daytime and nighttime brightness datasets, respectively.\n\"\"\"\nlat_d = df1_day['latitude'].values\nlon_d = df1_day['longitude'].values\nbrg_d = df1_day['brightness'].values\n\nlat_n = df1_night['latitude'].values\nlon_n = df1_night['longitude'].values\nbrg_n = df1_night['brightness'].values\n\nfig = plt.figure(figsize = (10, 10))\nm = Basemap(projection = 'lcc', resolution='c', lat_0 =-27.6, lon_0 = 134.35,width=5E6, height=4E6)\nm.shadedrelief()\nm.drawcoastlines(color='gray')\nm.drawcountries(color='gray')\nm.drawstates(color='gray')\n\nm.scatter(lon_d, lat_d, c= brg_d, latlon=True,cmap='Reds', alpha=0.6)\nplt.colorbar(label='Daytime  Brightness')\n\nm.scatter(lon_n, lat_n, c= np.array(brg_n),latlon=True,cmap='Blues', alpha=0.6)\nplt.colorbar(label='Nighttime  Brightness')\n\"\"\"\nIt is not easy to see with the two colors overlapped with each other, but we can see that there are points with either red or blue colors. \n\"\"\"\n\"\"\"\nBefore we jump into looking at the data as a function of 'data acquisition time\" , let's take a look at the \"high brightness\" data points to see which area had been affected with intense fires. I made \"450\" as a thresold for the brightness level to decide if the fire was intense or not.\n\"\"\"\ndf1_hot=df1[df1['brightness']>450]\nlat_hot=df1_hot['latitude'].values\nlon_hot=df1_hot['longitude'].values\nbrg_hot=c=df1_hot['brightness'].values\n\n\nfig = plt.figure(figsize = (10, 10))\nm = Basemap(projection = 'lcc', resolution='c', lat_0 =-27.6, lon_0 = 134.35,width=5E6, height=4E6)\nm.shadedrelief()\nm.drawcoastlines(color='gray')\nm.drawcountries(color='gray')\nm.drawstates(color='gray')\n\nm.scatter(lon_hot,lat_hot,c=brg_hot, latlon=True,cmap='Reds', alpha=0.6)\nplt.colorbar(label='Daytime  Brightness')\n\n\"\"\"\nFrom this, we can see that the South-east part of Austrailia (around Sydney) had experienced very intense fires.\n\"\"\"\n\"\"\"\nNow, time to look at the data in a time domain. We will use \"matplotlib.animation\" for the animation. Becuase looking at each date will take failry long, I will only look at datasets with a 10 day interval.\n\"\"\"\nimport matplotlib\nfrom matplotlib.animation import FuncAnimation\nfrom matplotlib import animation, rc\n\ntime=df1['acq_date'].values\n\n#Putting basemap as a frame\nfig = plt.figure(figsize=(10, 10))\n\nm = Basemap(projection = 'lcc', resolution='c', lat_0 =-27.6, lon_0 = 134.35,width=5E6, height=4E6)\nm.shadedrelief()\nm.drawcoastlines(color='gray')\nm.drawcountries(color='gray')\nm.drawstates(color='gray')\n\n#Getting unique data values as we have multiple rows assoicated with each date\nuniq_time=np.unique(time)\n\n#showing the start date\ndate_text = plt.text(-170, 80, uniq_time[0],fontsize=15)\n\n#very first data to show-brigtness data sets that were obatined on the first acquisition date\ndata=df1[df1['acq_date'].str.contains(uniq_time[0])]\ncmap = plt.get_cmap('Reds')\nxs, ys = data['longitude'].values, data['latitude'].values\nscat=m.scatter(xs,ys,c=data['brightness'].values,cmap=cmap, latlon=True, alpha=0.6)\nplt.colorbar(label='Fire Brightness')\n\n#We will get numbers starting from 0 to the size of the dataframe spaced by \"10\" as it will take very long to generate animation for all data points.\n#Basically we will look at the datasets with a 10-day interval.\nempty_index=[]\nfor i in range(1,len(uniq_time),10):\n    empty_index.append(i)    \n    \ndef update(i):\n    current_date = uniq_time[i]\n    data=df1[df1['acq_date'].str.contains(uniq_time[i])]\n    xs, ys = m(data['longitude'].values, data['latitude'].values)\n    X=np.c_[xs,ys]\n    scat.set_offsets(X)\n    date_text.set_text(current_date)\n    \nani = matplotlib.animation.FuncAnimation(fig, update, interval=50,frames=empty_index)\n\n#trying to diplay animation with HTML\nfrom IPython.display import HTML\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#Exporting the animation to show up correctly on Kaggle kernel. However, this creates an additional unwanted figure at the bottom.\n#Let's ignore for this time\n\nimport io\nimport base64\n\nfilename = 'animation.gif'\n\nani.save('animation.gif', writer='imagemagick', fps=1)\n\nvideo = io.open(filename, 'r+b').read()\nencoded = base64.b64encode(video)\nHTML(data='''<img src=\"data:image\/gif;base64,{0}\" type=\"gif\" \/>'''.format(encoded.decode('ascii')))\n\"\"\"\nThere is no clear trend in these fires but at least as we approached the new year (2020) the fires are mostly contained along the east coast of Austrailia.\nUnfortuantely the intensity of the fires do not seem to have been suppressed as time progresses.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '80983462780669'}"}
{"id":"26829","text":"\"\"\"\n**INTRODUCTION TO PYTHON: I WILL SHARE MY OWN EXPERIENCE HERE TO LEARN TOGETHER AND TEACH OTHER POEPLE.\n\n**\n\"\"\"\n\n\n\n\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns #data visualization\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\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\n\n\ndata = pd.read_csv(\"..\/input\/pokemon-project\/pokemon.csv\") #we used pandas library here to read dataset from csv file\n\ndata.info() # to see information about data\n\n#correlation map\n# to see and find relations between features in data we use correlation map\n#we will use seaborn library here to see on \"heatmap\"\n\ndata.corr() # to see correlation between features in data\n#correlation map\nf,ax = plt.subplots(figsize=(18, 18))\nsns.heatmap(data.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)\nplt.show()\n\n#we used \"heatmap\" feature from seaborn library here to make previous table heatmap here\n#check python seaborn library basics if you dont know how it works\n\ndata.head(10)\n#if you leave empty inside of pharantheses its gonna be first 5 data as default\n\"\"\"\n**1. INTRODUCTION TO PYTHON**\n\"\"\"\n\"\"\"\nIn this project i will explain subject and then i will use that explaned subject with the example.\nMATPLOTLIB\n\nMatplot is a python library that help us to plot data. The easiest and most basic plots are line, scatter and histogram plots.\n\nLine plot is better when x axis is time.\nScatter is better when there is correlation between two variables\nHistogram is better when we need to see distribution of numerical data.\nCustomization: Colors,labels,thickness of line, title, opacity, grid, figsize, ticks of axis and linestyle\n\"\"\"\n# Lets start with the line plot in this instance\n\n# Line Plot\n# color = color, label = label, linewidth = width of line, alpha = opacity, grid = grid, linestyle = sytle of line\ndata.Speed.plot(kind = 'line', color = 'g',label = 'Speed',linewidth=1,alpha = 0.5,grid = True,linestyle = ':')\ndata.Defense.plot(color = 'r',label = 'Defense',linewidth=1, alpha = 0.5,grid = True,linestyle = '-.')\nplt.legend(loc='upper right')     # legend = puts label into plot\nplt.xlabel('x axis')              # label = name of label\nplt.ylabel('y axis')\nplt.title('Line Plot')            # title = title of plot\nplt.show()\n#Lets use scatter plot in this example\n\n# Scatter Plot \n# x = attack, y = defense\ndata.plot(kind='scatter', x='Attack', y='Defense',alpha = 0.5,color = 'red')\nplt.xlabel('Attack')              # label = name of label\nplt.ylabel('Defense')\nplt.title('Attack Defense Scatter Plot')            # title = title of plot\nplt.show()\n#if you dont use \"plt.show()\" end of the code you will also get this output: 'Text(0.5, 1.0, 'Attack Defense Scatter Plot')'\n#And now lets use histogram plot in this example\n\n# Histogram\n# bins = number of bar in figure\ndata.Speed.plot(kind = 'hist',bins = 50,figsize = (12,12))\nplt.show()\n# clf() = cleans it up again you can start a fresh\ndata.Speed.plot(kind = 'hist',bins = 50)\nplt.clf()\n# We cannot see plot due to clf()\n\"\"\"\n\n**DICTIONARY**\n\nWhy do we need dictionary?\n\n* It has 'key' and 'value'\n* Faster than lists \n* What is key and value. Example:\n* dictionary = {'spain' : 'madrid'}\n* Key is spain.\n* Values is madrid. \n\nIt's that easy. \nLets practice some other properties like keys(), values(), update, add, check, remove key, remove all entries and remove dicrionary.\n\"\"\"\n#create dictionary and look its keys and values\ndictionary = {'spain' : 'madrid','usa' : 'vegas'}\nprint(dictionary.keys())\nprint(dictionary.values())\n# Keys have to be immutable(duragan) objects like string, boolean, float, integer or tubles\n# List is not immutable\n# Keys are unique\ndictionary['spain'] = \"barcelona\"    # how to update existing entry\nprint(dictionary)\ndictionary['france'] = \"paris\"       # how to Add new entry\nprint(dictionary)\ndel dictionary['spain']              # how to remove entry with key 'spain'\nprint(dictionary)\nprint('france' in dictionary)        # how to check include or not\ndictionary.clear()                   # how to remove all entries in dict\nprint(dictionary)\n# In order to run all code you need to take comment this line\ndel dictionary          # delete entire dictionary     \nprint(dictionary)       # it gives error because dictionary is deleted\n\"\"\"\n**PANDAS\n**\n\nWhat do we need to know about pandas?\n\nCSV: comma - separated values\n\"\"\"\ndata = pd.read_csv(\"..\/input\/pokemon-project\/pokemon.csv\")\nseries = data['Defense']        # data['Defense'] = series\nprint(type(series))\n\ndata_frame = data[['Defense']]  # data[['Defense']] = data frame\nprint(type(data_frame))\n\n\n#pandas 2 cesit data turunden olusuyor 1. si series 2. si data_frame(aslinda bir tane daha var ama kullanilmiyor o.)\nprint(data_frame)\nprint(series)\n\"\"\"\n**DIFFERENCE BETWEEN SERIES AND DATA FRAME\n**\n\nSeries is a type of list in pandas which can take integer values, string values, double values and more. ... Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data.\n\"\"\"\n\"\"\"\n\nBefore continuing with pandas, we need to learn logic, control flow and filtering. \n\n* Comparison operator: ==, <, >, <= \n* Boolean operators: and, or ,not \n* Filtering pandas\n\"\"\"\n# Comparison operator\nprint(3 > 2)\nprint(3!=2)\n# Boolean operators\nprint(True and False)# When you use \"and\" output will be false\nprint(True or False)# if you use \"or\" output will be the True\n# 1 - Filtering Pandas data frame\nx = data['Defense']>200     # There are only 3 pokemons who have higher defense value than 200\n#if you wanna se as dataframe\ndata[x]#this gives you only true indexes\n\n# 2 - Filtering pandas with logical_and\n# There are only 2 pokemons who have higher defence value than 200 and higher attack value than 100\ndata[np.logical_and(data['Defense']>200, data['Attack']>100 )]\n\"\"\"\n**WHILE and FOR LOOPS\n**\nLets learn the most basic while and for loops together.\n\"\"\"\n# Stay in loop if condition( i is not equal 5) is true\ni = 0\nwhile i != 5 :# until i is not equal to 5 increase the i(\"!= it means not equal\")\n    print('i is: ',i)\n    i +=1\nprint(i,' is equal to 5')\n# Stay in loop if condition( i is not equal 5) is true\nlis = [1,2,3,4,5]\nfor i in lis:\n    print('i is: ',i)\nprint('')#alt alta yazdigimiz icin kodlar karismasin diye arala bosluk birakiyoruz(Turkish explanation)\n         #we leave a blank between codes to make view clean(English explanation)\n# Enumerate index and value of list(yani burada listenin indekslerine ulasmak istiyoruz enumurate o demek.)(0. index 1. index...)\n# index : value = 0:1, 1:2, 2:3, 3:4, 4:5\nfor index, value in enumerate(lis):\n    print(index,\" : \",value)\nprint('')   \n\n# For dictionaries\n# We can use for loop to achive key and value of dictionary. We learnt key and value at dictionary part.\ndictionary = {'spain':'madrid','france':'paris'}\nfor key,value in dictionary.items():#dictionary_item bize hem key hem de value yi veriyor\n    print(key,\" : \",value)          #dictionary_item gives us key and value together\nprint('')\n\n# For pandas we can achieve index and value\nfor index,value in data[['Attack']][0:1].iterrows(): #[0:1] ile ilk elemani aliyoruz data icindeki 0 ile 1. index arasindaki yani\n                                                     #[0:1] it means youre taking firs value from data\n    print(index,\" : \",value)\n\"\"\"\nIn this part, we learned:\n\n* how to import csv file\n* plotting line,scatter and histogram\n* basic dictionary features\n* basic pandas features like filtering that is actually something always used and main for being data scientist\n* While and for loops\n\"\"\"\n\"\"\"\n**2. PYTHON DATA SCIENCE TOOLBOX**\n\"\"\"\n\"\"\"\nUSER DEFINED FUNCTION\nWhat we need to know about functions:\n\ndocstrings: documentation for functions. Example: \n\nfor f(): \n\n\"\"\"This is docstring for documentation of function f\"\"\"\n\ntuble: sequence of immutable python objects. \n\ncant modify values \n\ntuble uses paranthesis like tuble = (1,2,3) \n\nunpack tuble into several variables like a,b,c = tuble\n\"\"\"\n# example of what we learn above\ndef tuble_ex():\n    \"\"\" return defined t tuble\"\"\"\n    t = (1,2,3)\n    return t\na,b,c = tuble_ex()\nprint(a,b,c)\n\"\"\"\nSCOPE\nWhat we need to know about scope:\n\nglobal: defined main body in script\n\nlocal: defined in a function\n\nbuilt in scope: names in predefined built in scope module such as print, len \n\nLets make some basic examples\n\"\"\"\n# guess print what\nx = 2\ndef f():\n    x = 3\n    return x\nprint(x)      # x = 2 global scope\nprint(f())    # x = 3 local scope\n# What if there is no local scope\nx = 5\ndef f():\n    y = 2*x        # there is no local scope x\n    return y\nprint(f())         # it uses global scope x\n# First local scopesearched, then global scope searched, if two of them cannot be found lastly built in scope searched.\n# How can we learn what is built in scope\nimport builtins\ndir(builtins)\n\"\"\"\n\n\nNESTED FUNCTION\n\nfunction inside function.\n\nThere is a LEGB rule that is search local scope, enclosing function, global and built in scopes, respectively.\n\"\"\"\n#nested function\ndef square():\n    \"\"\" return square of value \"\"\"\n    def add():\n        \"\"\" add two local variable \"\"\"\n        x = 2\n        y = 3\n        z = x + y\n        return z\n    return add()**2\nprint(square())\n\"\"\"\nDEFAULT and FLEXIBLE ARGUMENTS\n\nDefault argument example: \ndef f(a, b=1):\n  \"\"\" b = 1 is default argument\"\"\"\n\n# default arguments\ndef f(a, b = 1, c = 2):\n    y = a + b + c\n    return y\nprint(f(5))\n# what if we want to change default arguments\nprint(f(5,4,3))Flexible argument example: \ndef f(*args):\n \"\"\" *args can be one or more\"\"\"\n\ndef f(** kwargs)\n \"\"\" **kwargs is a dictionary\"\"\"\n\n\nlets write some code to practice\n\"\"\"\n# default arguments\ndef f(a, b = 1, c = 2):\n    y = a + b + c\n    return y\nprint(f(5))\n# what if we want to change default arguments\nprint(f(5,4,3))\n# flexible arguments *args\ndef f(*args):\n    for i in args:\n        print(i)\nf(1)\nprint(\"\")\nf(1,2,3,4)\n# flexible arguments **kwargs that is dictionary\ndef f(**kwargs):\n    \"\"\" print key and value of dictionary\"\"\"\n    for key, value in kwargs.items():               # If you do not understand this part turn for loop part and look at dictionary in for loop\n        print(key, \" \", value)\nf(country = 'spain', capital = 'madrid', population = 123456)\n\"\"\"\nLAMBDA FUNCTION\n\nFaster way of writing function\n\"\"\"\n# lambda function\nsquare = lambda x: x**2     # where x is name of argument\nprint(square(4))\ntot = lambda x,y,z: x+y+z   # where x,y,z are names of arguments\nprint(tot(1,2,3))\n\"\"\"\nANONYMOUS FUNCT\u0130ON\n\nLike lambda function but it can take more than one arguments.\n\n* map(func,seq) : applies a function to all the items in a list\n\"\"\"\nnumber_list = [1,2,3]\ny = map(lambda x:x**2,number_list)\nprint(list(y))\n\"\"\"\nITERATORS\n\niterable is an object that can return an iterator\n\niterable: an object with an associated iter() method \n\nexample: list, strings and dictionaries\n\niterator: produces next value with next() method\n\"\"\"\n# iteration example\nname = \"ronaldo\"\nit = iter(name)\nprint(next(it))    # print next iteration\nprint(*it)         # print remaining iteration\n# zip example\nlist1 = [1,2,3,4]\nlist2 = [5,6,7,8]\nz = zip(list1,list2)\nprint(z)\nz_list = list(z)\nprint(z_list)\nun_zip = zip(*z_list)\nun_list1,un_list2 = list(un_zip) # unzip returns tuble\nprint(un_list1)\nprint(un_list2)\nprint(type(un_list2))\n\"\"\"\nLIST COMPREHENS\u0130ON\n\nOne of the most important topic of this kernel \n\nWe use list comprehension for data analysis often. \n\nlist comprehension: collapse for loops for building lists into a single line \n\nEx: num1 = [1,2,3] and we want to make it num2 = [2,3,4]. This can be done with for loop. However it is unnecessarily long. We can make it one line code that is list comprehension.\n\"\"\"\n# Example of list comprehension\nnum1 = [1,2,3]\nnum2 = [i + 1 for i in num1 ]\nprint(num2)\n\n\"\"\"\n[i + 1 for i in num1 ]: list of comprehension \ni +1: list comprehension syntax \nfor i in num1: for loop syntax \ni: iterator \nnum1: iterable object\n\n\"\"\"\n# Conditionals on iterable\nnum1 = [5,10,15]\nnum2 = [i**2 if i == 10 else i-5 if i < 7 else i+5 for i in num1]\nprint(num2)\n# lets return pokemon csv and make one more list comprehension example\n# lets classify pokemons whether they have high or low speed. Our threshold is average speed.\nthreshold = sum(data.Speed)\/len(data.Speed)\ndata[\"speed_level\"] = [\"high\" if i > threshold else \"low\" for i in data.Speed]\ndata.loc[:10,[\"speed_level\",\"Speed\"]] # we will learn loc more detailed later\n\"\"\"\nUp to now, we learned\n* User defined function\n* Scope\n* Nested function\n* Default and flexible arguments\n* Lambda function\n* Anonymous function\n* Iterators\n* List comprehension\n\"\"\"\n\"\"\"\n**3.CLEANING DATA**\n\"\"\"\n\"\"\"\n\n\nDIAGNOSE DATA for CLEANING\n\nWe need to diagnose and clean data before exploring. \n\nUnclean data:\n\n* Column name inconsistency like upper-lower case letter or space between words\n* missing data\n* different language\n\n\n\"\"\"\n#We will use head, tail, columns, shape and info methods to diagnose data\n\ndata = pd.read_csv('..\/input\/pokemon-project\/pokemon.csv')\ndata.head()  # head shows first 5 rows\n# tail shows last 5 rows\ndata.tail()\n# columns gives column names of features\ndata.columns\n# shape gives number of rows and columns in a tuble\ndata.shape\n# info gives data type like dataframe, number of sample or row, number of feature or column, feature types and memory usage\ndata.info()\n\"\"\"\n**EXPLORATORY DATA ANALYSIS\n**\nvalue_counts(): Frequency counts \noutliers: the value that is considerably higher or lower from rest of the data\n\n* Lets say value at 75% is Q3 and value at 25% is Q1.\n* Outlier are smaller than Q1 - 1.5(Q3-Q1) and bigger than Q3 + 1.5(Q3-Q1). (Q3-Q1) = IQR \n* We will use describe() method. Describe method includes:\n* count: number of entries\n* mean: average of entries\n* std: standart deviation\n* min: minimum entry\n* 25%: first quantile\n* 50%: median or second quantile\n* 75%: third quantile\n* max: maximum entry\n\nWhat is quantile?\n\n* 1,4,5,6,8,9,11,12,13,14,15,16,17\n* The median is the number that is in middle of the sequence. In this case it would be 11.\n* The lower quartile is the median in between the smallest number and the median i.e. in between 1 and 11, which is 6.\n* The upper quartile, you find the median between the median and the largest number i.e. between 11 and 17, which will be 14 according to the question above.\n\"\"\"\n# For example lets look frequency of pokemom types\nprint(data['Type 1'].value_counts(dropna =False))  # if there are nan values that also be counted\n# As it can be seen below there are 112 water pokemon or 70 grass pokemon\n# For example max HP is 255 or min defense is 5\ndata.describe() #ignore null entries\n\"\"\"\n**VISUAL EXPLORATORY DATA ANALYSIS\n**\n* Box plots: visualize basic statistics like outliers, min\/max or quantiles\n\"\"\"\n# For example: compare attack of pokemons that are legendary  or not\n# Black line at top is max\n# Blue line at top is 75%\n# Red line is median (50%)\n# Blue line at bottom is 25%\n# Black line at bottom is min\n# There are no outliers\ndata.boxplot(column='Attack',by = 'Legendary')\n\"\"\"\n\n\n**TIDY DATA**\n\nWe tidy data with melt(). Describing melt is confusing. Therefore lets make example to understand it.\n\"\"\"\n# Firstly I create new data from pokemons data to explain melt nore easily.\ndata_new = data.head()    # I only take 5 rows into new data\ndata_new\n\n# lets melt\n# id_vars = what we do not wish to melt\n# value_vars = what we want to melt\nmelted = pd.melt(frame=data_new,id_vars = 'Name', value_vars= ['Attack','Defense'])\nmelted\n\"\"\"\n**PIVOTING DATA\n**\n\nReverse of melting.\n\"\"\"\n# Index is name\n# I want to make that columns are variable\n# Finally values in columns are value\nmelted.pivot(index = 'Name', columns = 'variable',values='value')\n\"\"\"\n**CONCATENATING DATA\n**\n\nWe can concatenate two dataframe\n\"\"\"\n# Firstly lets create 2 data frame\ndata1 = data.head()\ndata2= data.tail()\nconc_data_row = pd.concat([data1,data2],axis =0,ignore_index =True) # axis = 0 : adds dataframes in row\nconc_data_row\ndata1 = data['Attack'].head()\ndata2= data['Defense'].head()\nconc_data_col = pd.concat([data1,data2],axis =1) # axis = 0 : adds dataframes in row\nconc_data_col\n\"\"\"\n**DATA TYPES\n**\n\nThere are 5 basic data types: object(string),booleab, integer, float and categorical. \nWe can make conversion data types like from str to categorical or from int to float \nWhy is category important:\n\n* make dataframe smaller in memory\n* can be utilized for anlaysis especially for sklear(we will learn later)\n\"\"\"\ndata.dtypes\n# lets convert object(str) to categorical and int to float.\ndata['Type 1'] = data['Type 1'].astype('category')\ndata['Speed'] = data['Speed'].astype('float')\n# As you can see Type 1 is converted from object to categorical\n# And Speed ,s converted from int to float\ndata.dtypes\n\"\"\"\n**MISSING DATA and TESTING WITH ASSERT\n**\n\nIf we encounter with missing data, what we can do:\n\n* leave as is\n* drop them with dropna()\n* fill missing value with fillna()\n* fill missing values with test statistics like mean \n* Assert statement: check that you can turn on or turn off when you are done with your testing of the program\n\n\n\"\"\"\n# Lets look at does pokemon data have nan value\n# As you can see there are 800 entries. However Type 2 has 414 non-null object so it has 386 null object.\ndata.info()\n# Lets chech Type 2\ndata[\"Type 2\"].value_counts(dropna =False)\n# As you can see, there are 386 NAN value\n# Lets drop nan values\ndata1=data   # also we will use data to fill missing value so I assign it to data1 variable\ndata1[\"Type 2\"].dropna(inplace = True)  # inplace = True means we do not assign it to new variable. Changes automatically assigned to data\n# So does it work ?\n#  Lets check with assert statement\n# Assert statement:\nassert 1==1 # return nothing because it is true\n# In order to run all code, we need to make this line comment\n# assert 1==2 # return error because it is false\nassert  data['Type 2'].notnull().all() # returns nothing because we drop nan values\n\ndata[\"Type 2\"].fillna('empty',inplace = True)\n\nassert  data['Type 2'].notnull().all() # returns nothing because we do not have nan values\n\n# # With assert statement we can check a lot of thing. For example\n# assert data.columns[1] == 'Name'\n# assert data.Speed.dtypes == np.int\n\"\"\"\nIn this part, we learn:\n\n* Diagnose data for cleaning\n* Exploratory data analysis\n* Visual exploratory data analysis\n* Tidy data\n* Pivoting data\n* Concatenating data\n* Data types\n* Missing data and testing with assert\n\"\"\"\n\"\"\"\n**4. PANDAS FOUNDATION**\n\n**REVIEW of PANDAS\n**\n\nAs you notice, I do not give all idea in a same time. Although, we learn some basics of pandas, we will go deeper in pandas.\nsingle column = series\nNaN = not a number\ndataframe.values = numpy\n\n\n**BUILDING DATA FRAMES FROM SCRATCH\n**\n\n* We can build data frames from csv as we did earlier.\n* Also we can build dataframe from dictionaries\n* zip() method: This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.\n* Adding new column\n* Broadcasting: Create new column and assign a value to entire column\n\"\"\"\n# data frames from dictionary\ncountry = [\"Spain\",\"France\"]\npopulation = [\"11\",\"12\"]\nlist_label = [\"country\",\"population\"]\nlist_col = [country,population]\nzipped = list(zip(list_label,list_col))\ndata_dict = dict(zipped)\ndf = pd.DataFrame(data_dict)\ndf\n# Add new columns\ndf[\"capital\"] = [\"madrid\",\"paris\"]\ndf\n# Broadcasting\ndf[\"income\"] = 0 #Broadcasting entire column\ndf\n\"\"\"\n**VISUAL EXPLORATORY DATA ANALYSIS\n**\n\n* Plot\n* Subplot\n* Histogram:\n    *bins: number of bins\n    *range(tuble): min and max values of bins\n    *normed(boolean): normalize or not\n    *cumulative(boolean): compute cumulative distribution\n\"\"\"\n# Plotting all data \ndata1 = data.loc[:,[\"Attack\",\"Defense\",\"Speed\"]]\ndata1.plot()\n# it is confusing\n# subplots\ndata1.plot(subplots = True)\nplt.show()\n\n# scatter plot  \ndata1.plot(kind = \"scatter\",x=\"Attack\",y = \"Defense\")\nplt.show()\n# hist plot  \ndata1.plot(kind = \"hist\",y = \"Defense\",bins = 50,range= (0,250),normed = True)\n# histogram subplot with non cumulative and cumulative\nfig, axes = plt.subplots(nrows=2,ncols=1)\ndata1.plot(kind = \"hist\",y = \"Defense\",bins = 50,range= (0,250),normed = True,ax = axes[0])\ndata1.plot(kind = \"hist\",y = \"Defense\",bins = 50,range= (0,250),normed = True,ax = axes[1],cumulative = True)\nplt.savefig('graph.png')\nplt\n\"\"\"\n**STATISTICAL EXPLORATORY DATA ANALYSIS\n**\n\nI already explained it at previous parts. However lets look at one more time.\n\n* count: number of entries\n* mean: average of entries\n* std: standart deviation\n* min: minimum entry\n* 25%: first quantile\n* 50%: median or second quantile\n* 75%: third quantile\n* max: maximum entry\n\"\"\"\ndata.describe()\n\"\"\"\n**INDEXING PANDAS TIME SERIES\n**\n\n* datetime = object\n* parse_dates(boolean): Transform date to ISO 8601 (yyyy-mm-dd hh:mm:ss ) format\n\"\"\"\ntime_list = [\"1992-03-08\",\"1992-04-12\"]\nprint(type(time_list[1])) # As you can see date is string\n# however we want it to be datetime object\ndatetime_object = pd.to_datetime(time_list)\nprint(type(datetime_object))\n# close warning\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# In order to practice lets take head of pokemon data and add it a time list\ndata2 = data.head()\ndate_list = [\"1992-01-10\",\"1992-02-10\",\"1992-03-10\",\"1993-03-15\",\"1993-03-16\"]\ndatetime_object = pd.to_datetime(date_list)\ndata2[\"date\"] = datetime_object\n# lets make date as index\ndata2= data2.set_index(\"date\")\ndata2\n# Now we can select according to our date index\nprint(data2.loc[\"1993-03-16\"])\nprint(data2.loc[\"1992-03-10\":\"1993-03-16\"])\n\"\"\"\n**RESAMPLING PANDAS TIME SERIES\n**\n\nResampling: statistical method over different time intervals\nNeeds string to specify frequency like \"M\" = month or \"A\" = year\nDownsampling: reduce date time rows to slower frequency like from daily to weekly\nUpsampling: increase date time rows to faster frequency like from daily to hourly\nInterpolate: Interpolate values according to different methods like \u2018linear\u2019, \u2018time\u2019 or index\u2019\nhttps:\/\/pandas.pydata.org\/pandas-docs\/stable\/generated\/pandas.Series.interpolate.html\n\"\"\"\n# We will use data2 that we create at previous part\ndata2.resample(\"A\").mean()\n# Lets resample with month\ndata2.resample(\"M\").mean()\n# As you can see there are a lot of nan because data2 does not include all months\n\n# In real life (data is real. Not created from us like data2) we can solve this problem with interpolate\n# We can interpolete from first value\ndata2.resample(\"M\").first().interpolate(\"linear\")\n# Or we can interpolate with mean()\ndata2.resample(\"M\").mean().interpolate(\"linear\")\n\"\"\"\n**MANIPULATING DATA FRAMES WITH PANDAS\n**\n\n**INDEXING DATA FRAMES**\n\n* Indexing using square brackets\n* Using column attribute and row label\n* Using loc accessor\n* Selecting only some columns\n* \n\"\"\"\n# read data\ndata = pd.read_csv('..\/input\/pokemon-project\/pokemon.csv')\ndata= data.set_index(\"#\")\ndata.head()\n\n\n# indexing using square brackets\ndata[\"HP\"][1]\n# using column attribute and row label\ndata.HP[1]\n# using loc accessor\ndata.loc[1,[\"HP\"]]\n# Selecting only some columns\ndata[[\"HP\",\"Attack\"]]\n\"\"\"\n**SLICING DATA FRAME\n**\n\n* Difference between selecting columns\n* Series and data frames\n* Slicing and indexing series\n* Reverse slicing\n* From something to end\n\"\"\"\n# Difference between selecting columns: series and dataframes\nprint(type(data[\"HP\"]))     # series\nprint(type(data[[\"HP\"]]))   # data frames\n# Slicing and indexing series\ndata.loc[1:10,\"HP\":\"Defense\"]   # 10 and \"Defense\" are inclusive\n# Reverse slicing \ndata.loc[10:1:-1,\"HP\":\"Defense\"]\n# From something to end\ndata.loc[1:10,\"Speed\":]\n\"\"\"\n**FILTERING DATA FRAMES\n**\n\nCreating boolean series Combining filters Filtering column based others\n\"\"\"\n# Creating boolean series\nboolean = data.HP > 200\ndata[boolean]\n# Combining filters\nfirst_filter = data.HP > 150\nsecond_filter = data.Speed > 35\ndata[first_filter & second_filter]\n# Filtering column based others\ndata.HP[data.Speed<15]\n\"\"\"\n**TRANSFORMING DATA\n**\n\n* Plain python functions\n* Lambda function: to apply arbitrary python function to every element\n* Defining column using other columns\n\"\"\"\n# Plain python functions\ndef div(n):\n    return n\/2\ndata.HP.apply(div)\n# Or we can use lambda function\ndata.HP.apply(lambda n : n\/2)\n# Defining column using other columns\ndata[\"total_power\"] = data.Attack + data.Defense\ndata.head()\n\"\"\"\n**INDEX OBJECTS AND LABELED DATA\n**\n\nindex: sequence of label\n\"\"\"\n# our index name is this:\nprint(data.index.name)\n# lets change it\ndata.index.name = \"index_name\"\ndata.head()\n# Overwrite index\n# if we want to modify index we need to change all of them.\ndata.head()\n# first copy of our data to data3 then change index \ndata3 = data.copy()\n# lets make index start from 100. It is not remarkable change but it is just example\ndata3.index = range(100,900,1)\ndata3.head()\n\n# We can make one of the column as index. I actually did it at the beginning of manipulating data frames with pandas section\n# It was like this\n# data= data.set_index(\"#\")\n# also you can use \n# data.index = data[\"#\"]\n\"\"\"\n**HIERARCHICAL INDEXING\n**\n\nSetting indexing\n\"\"\"\n# lets read data frame one more time to start from beginning\ndata = pd.read_csv(\"..\/input\/pokemon-project\/pokemon.csv\")\ndata.head()\n# As you can see there is index. However we want to set one or more column to be index\n\n\n# Setting index : type 1 is outer type 2 is inner index\ndata1 = data.set_index([\"Type 1\",\"Type 2\"]) \ndata1.head(100)\n# data1.loc[\"Fire\",\"Flying\"] # howw to use indexes\n\"\"\"\n**PIVOTING DATA FRAMES\n**\n\npivoting: reshape tool\n\"\"\"\ndic = {\"treatment\":[\"A\",\"A\",\"B\",\"B\"],\"gender\":[\"F\",\"M\",\"F\",\"M\"],\"response\":[10,45,5,9],\"age\":[15,4,72,65]}\ndf = pd.DataFrame(dic)\ndf\n# pivoting\ndf.pivot(index=\"treatment\",columns = \"gender\",values=\"response\")\n\"\"\"\n\n\nSTACKING and UNSTACKING DATAFRAME\n\n\n* deal with multi label indexes\n* level: position of unstacked index\n* swaplevel: change inner and outer level index position\n\"\"\"\ndf1 = df.set_index([\"treatment\",\"gender\"])\ndf1\n# lets unstack it\n# level determines indexes\ndf1.unstack(level=0)\ndf1.unstack(level=1)\n# change inner and outer level index position\ndf2 = df1.swaplevel(0,1)\ndf2\n\"\"\"\n**MELTING DATA FRAMES\n**\n\n* Reverse of pivoting\n\"\"\"\ndf\n# df.pivot(index=\"treatment\",columns = \"gender\",values=\"response\")\npd.melt(df,id_vars=\"treatment\",value_vars=[\"age\",\"response\"])\n\n\n\"\"\"\n**ATEGORICALS AND GROUPBY**\n\"\"\"\n# We will use df\ndf\n# according to treatment take means of other features\ndf.groupby(\"treatment\").mean()   # mean is aggregation \/ reduction method\n# there are other methods like sum, std,max or min\n# we can only choose one of the feature\ndf.groupby(\"treatment\").age.max()\n# Or we can choose multiple features\ndf.groupby(\"treatment\")[[\"age\",\"response\"]].min()\ndf.info()\n# as you can see gender is object\n# However if we use groupby, we can convert it categorical data. \n# Because categorical data uses less memory, speed up operations like groupby\n#df[\"gender\"] = df[\"gender\"].astype(\"category\")\n#df[\"treatment\"] = df[\"treatment\"].astype(\"category\")\n#df.info()","meta":"{'source': 'AI4Code', 'id': '315effe6373b56'}"}
{"id":"974","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n%matplotlib inline\nimport matplotlib.pyplot as plt # visualization\n!pip install seaborn as sns -q # visualization with seaborn v0.11.1\nimport seaborn as sns # visualization\nimport missingno as msno # missing values pattern visualization\n\nimport warnings # supress warnings\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n\nimport math\n\n\nplt.style.use('bmh')\n\n# set pandas display option\npd.set_option('display.max_columns',None)\npd.set_option('display.max_rows',None)\n\n# Load the data \nBooks_df = pd.read_csv('..\/input\/book-recommendation-dataset\/Books.csv')\nRatings_df = pd.read_csv('..\/input\/book-recommendation-dataset\/Ratings.csv')\nUsers_df = pd.read_csv('..\/input\/book-recommendation-dataset\/Users.csv')\n# display the dataset\nRatings_df.head().style.set_caption('Sample of Ratings data')\n\"\"\"\n# Summarize the dataset\n\"\"\"\n# dimension of dataset\nprint(f'''\\t  Book_df shape is {Books_df.shape}\n          Ratings_df shape is {Ratings_df.shape}\n          Users_df shape is {Users_df.shape}''')\ndef missing_zero_values_table(df):\n    mis_val=df.isnull().sum()\n    mis_val_percent=round(df.isnull().mean().mul(100),2)\n    mz_table=pd.concat([mis_val,mis_val_percent],axis=1)\n    mz_table=mz_table.rename(\n    columns={df.index.name:'col_name',0:'Missing Values',1:'% of Total Values'})\n    mz_table['Data_type']=df.dtypes\n    mz_table=mz_table.sort_values('% of Total Values',ascending=False)\n    print(f\"Your selected dataframe has \"+str(df.shape[1])+\" columns and \"+str(df.shape[0])+\" Rows.\\n\"\n         \"There are \"+str(mz_table[mz_table.iloc[:,1] != 0].shape[0])+\n          \" columns that have missing values.\")\n    return mz_table.reset_index()\nmissing_zero_values_table(Users_df)\nmissing_zero_values_table(Ratings_df)\nmissing_zero_values_table(Books_df)\n\"\"\"\nCheck outlier data in **Age** and **Book-Rating** column  \n\"\"\"\nf,ax=plt.subplots(1,2,figsize=(18,8))\nsns.boxplot(y='Book-Rating', data=Ratings_df,ax=ax[0])\nax[0].set_title('Find outlier data in Rating Book column')\nsns.boxplot(y='Age', data=Users_df,ax=ax[1])\nax[1].set_title('Find outlier data in Age column')\nprint(sorted(Users_df.Age.unique()))\n\"\"\"\nAge : 244 :))\n\"\"\"\n\"\"\"\nOk we have Outlier data in Age    \nso must be fixed it   \n\"\"\"\n\"\"\"\nOK let's find our unique value in Location column \n\"\"\"\nUsers_df.Location.unique()\nlen(Users_df.Location.unique())\n\"\"\"\n57339 unique Value it's really hard to understand  \nso use regex and create column country\n\"\"\"\nBooks_df['Book-Author'].describe()\n\"\"\"\nSay us Miss [Agatha Christie](https:\/\/www.biography.com\/writer\/agatha-christie) is top in Books data frame\n\"\"\"\nprint(Books_df['Year-Of-Publication'].unique().tolist())\n\"\"\"\nYear of publication **2037** !!  \n'**Gallimard**' , '**DK Publishing Inc**' , type of sum year is **string**  \n\"\"\"\n1.0 - (np.count_nonzero(Ratings_df)\/float(Ratings_df.size))\n\"\"\"\n15 percent sparse\n\"\"\"\nsorted(Ratings_df['Book-Rating'].unique())\n\"\"\"\n0 is an invalid number in the rated books  \nand rating value must be 1 to 10\n\"\"\"\nRatings_df.shape[0]\nusersCount=Users_df.shape[0]\nbooksCount=Books_df.shape[0]\nprint(f'Users : {usersCount}')\nprint(f'Books : {booksCount}')\nprint(f'Total : {usersCount*booksCount}')\n\"\"\"\nUsers rated **1149780** books, but there are **271360** books        \nso users did not rate all books      \nand users participation that rated make two question   \n1. Are the books they rated part of the book's data frame ?  \n2. Are the users they rated part of the user's data frame ?  \n\n\n\"\"\"\nratings_new = Ratings_df[Ratings_df.ISBN.isin(Books_df.ISBN)]\nratings_new = ratings_new[Ratings_df['User-ID'].isin(Users_df['User-ID'])]\nprint(\"Users or books aren't in dataset\")\nprint(f'Total : {Ratings_df.shape[0] - ratings_new.shape[0]}')\nsparsity = round(1.0 - len(ratings_new)\/float(usersCount*booksCount),6)\nsparsity\n\"\"\"\nAge column has 39 percent null data   \nand age column has outlier data   \nand I can don't use Cosine Similarity   \nso let's do it together  \nif any things it's not correct I'm really become happy to tell me \n\"\"\"\n\"\"\"\n# Visualization and Modeling\n\"\"\"\n\"\"\"\n**Steps**\n1. rename columns names :))\n2. Create country column to analyze better \n3. Fill Na value in  Country column \n4. Some data in Country Column has Misspellings \n5. Create rating_Avg and number_of_rating to analyze better\n6. users more in which countries\n7. Age column has outlier data \n8. Fill Na value in Age column \n9. Fill Na value in Book data frame's Author column \n10. Fill Na value in Book data frame's Publisher column \n11. Book data frame's Year of Publication column has two string value and some integer value  type is string\n12. Book data frame's Year of Publication has outlier data \n13. Fill Na value in Book data frame's Year of Publication \n14. join three data frames together\n15. Delete user and book columns they rated but aren't in the dataset\n16. Rating_book value must be 1 to 10\n17. drop three unhelpful columns 'Image-URL-S', 'Image-URL-M', 'Image-URL-L' \n\"\"\"\nRatings_df.rename(columns={'User-ID':'user_id','Book-Rating':'book_rating'},inplace=True)\nUsers_df.rename(columns={'User-ID':'user_id'},inplace=True)\nBooks_df.rename(columns={'Book-Title':'Book_Title','Book-Author':'Book_Author',\n                         'Year-Of-Publication':'Year_Of_Publication'},inplace=True)\n\"\"\"\n**Country Column**\n\"\"\"\nUsers_df['Country']='Iran'\nfor i in Users_df:\n    Users_df['Country']=Users_df.Location.str.extract(r'\\,+\\s?(\\w*\\s?\\w*)\\\"*$')   \nlen(Users_df.Country.unique())\nUsers_df.isnull().sum()\n\"\"\"\n368 of users Country column is Nan so must be fill it \n\"\"\"\nUsers_df.loc[Users_df.Country.isnull(),'Country']='other'\n\"\"\"\nSo I don't have any idea Location column has 57339 unique value    \nfor this I use Regex and create country column   \nbut we have [195 Countries in the World !!](https:\/\/www.worldometers.info\/geography\/how-many-countries-are-there-in-the-world\/)  \nBut it's better than 57339 unique Location value :))  \n\n\"\"\"\npd.crosstab(Users_df.Country,Ratings_df.book_rating).T.style.background_gradient()\n\"\"\"\nSome data has Misspellings \n\"\"\"\nUsers_df['Country'].replace(['','alachua','america','austria','autralia','cananda','geermany','italia','united kindgonm','united sates','united staes','united state','united states','us'],\n                           ['other','usa','usa','australia','australia','canada','germany','italy','united kingdom','usa','usa','usa','usa','usa'],inplace=True)\n\"\"\"\nCreate Column 'count rate'   \nuser participation in rated   \nand even users rated the books zero   \n\"\"\"\n\"\"\"\nRating Average and\n\"\"\"\n# Create column Count_All_Rate\nRatings_df['Count_All_Rate']=Ratings_df.groupby('ISBN')['user_id'].transform('count')\n\"\"\"\n**Country and Users**\n\"\"\"\ncm=sns.light_palette('green',as_cmap=True)\npopular=Users_df.Country.value_counts().to_frame()[:10]\npopular.rename(columns={'Country':'Count_Users_Country'},inplace=True)\npopular.style.background_gradient(cmap=cm)\n\"\"\"\nIn the below chart there is one row has named 'other' it's mean    \nlocation is Nan, or regex it's not able to read\n\"\"\"\n\"\"\"\n**Age Columns**\n\"\"\"\n\"\"\"\nIn the plot and in the unique value   \nwe understand we have outlier data   \nso for outlier data I convert it to Nan value  \n\"\"\"\n# outlier data became NaN\nUsers_df.loc[(Users_df.Age > 100 ) | (Users_df.Age < 5),'Age']=np.nan\nUsers_df.Age.plot.hist(bins=20,edgecolor='black',color='red')\nround(Users_df.Age.skew(axis=0,skipna=True),3)\n\"\"\"\nAge has **positive Skewness** (right tail)      \nso we I have one idea to fill Na value from **Median**   \nfor this we don't like to fill Na value **just for one range of age** for handle it I use **country column** to fill Na \n\"\"\"\n# Series of users data live in which country \ncountryUsers = Users_df.Country.value_counts()\ncountry=countryUsers[countryUsers>=5].index.tolist()\n# Range of Age users in country register in this library and had participation\nRangeOfAge = Users_df.loc[Users_df.Country.isin(country)][['Country','Age']].groupby('Country').agg(np.mean).to_dict()\n\nfor k,v in RangeOfAge['Age'].items():\n    Users_df.loc[(Users_df.Age.isnull())&(Users_df.Country== k),'Age'] = v\n    \nUsers_df.isnull().sum()\n\"\"\"\nPOF again we have 330 null Value   \nfor fill in it   \nAge has **positive Skewness** (right tail)        \nso we I have one idea to fill Na value from **Median**     \n\"\"\"\nmedianAge = int(Users_df.Age.median())\nUsers_df.loc[Users_df.Age.isnull(),'Age']=medianAge\nUsers_df.isnull().sum()\n\"\"\"\n**Book Author** column has **Nan** value\n\"\"\"\nBooks_df[Books_df.Book_Author.isnull()]\nBooks_df.loc[(Books_df.ISBN=='9627982032'),'Book_Author']='other'\n\"\"\"\n**Publisher column has Nan value**\n\"\"\"\nBooks_df[Books_df.Publisher.isnull()]\nBooks_df.loc[(Books_df.ISBN=='193169656X'),'Publisher']='other'\nBooks_df.loc[(Books_df.ISBN=='1931696993'),'Publisher']='other'\n\"\"\"\n**Year of Publication**\n\"\"\"\nBooks_df[Books_df.Year_Of_Publication=='Gallimard']\nBooks_df[Books_df.Year_Of_Publication=='DK Publishing Inc']\nBooks_df.loc[Books_df.ISBN=='2070426769','Year_Of_Publication']=2003\nBooks_df.loc[Books_df.ISBN=='2070426769','Book_Author']='Gallimard'\nBooks_df.loc[Books_df.ISBN=='0789466953','Year_Of_Publication']=2000\nBooks_df.loc[Books_df.ISBN=='0789466953','Book_Author']='DK Publishing Inc'\nBooks_df.loc[Books_df.ISBN=='078946697X','Year_Of_Publication']=2000\nBooks_df.loc[Books_df.ISBN=='078946697X','Book_Author']='DK Publishing Inc'\nBooks_df.Year_Of_Publication=Books_df.Year_Of_Publication.astype(np.int32)\nprint(sorted(Books_df.Year_Of_Publication.unique()))\n\"\"\"\nYears of publication after 2021 and 0 it's not normal   \nso must be converted to Nan value\n\"\"\"\nBooks_df.loc[(Books_df.Year_Of_Publication>=2021)|(Books_df.Year_Of_Publication==0),'Year_Of_Publication']=np.NAN\nBooks_df.isnull().sum()\nauthor=Books_df[Books_df.Year_Of_Publication.isnull()].Book_Author.unique().tolist()\nRangeYearOfPublication = Books_df.loc[Books_df.Book_Author.isin(author)][['Book_Author','Year_Of_Publication']].groupby('Book_Author').agg(np.mean).round(0).to_dict()\nmeanYear=round(Books_df.Year_Of_Publication.mean())\nauthorNanYear={}\nauthorYear={}\nfor k,v in RangeYearOfPublication['Year_Of_Publication'].items():\n    if math.isnan(v) != True:\n        authorYear[k]=v\n    else:\n        authorNanYear[k] = meanYear\nlen(authorNanYear.keys())\n\"\"\"\n1355 authors don't have a year of publication and the average of them is Nan   \nand I forced filling Nan value with mean of all year of publication authors\n\"\"\"\nlen(authorYear.keys())\n# for k,v in authorYear.items():\n#     Books_df.loc[(Books_df.Year_Of_Publication.isnull())&(Books_df.Book_Author== k),'Year_Of_Publication'] = v\n\"\"\"\n1959 authors don't have year of publication of them books    \nand they return value   \nbut it's take long time to fill Nan value   \nI would like to find a fast way :))  \nbut now I don't know   \nif you know please tell me in the comment  \n\"\"\"\n\"\"\"\nThis method it's not helpful     \nI must find another way      \n\"\"\"\nBooks_df.loc[Books_df.Year_Of_Publication.isnull(),'Year_Of_Publication'] = round(Books_df.Year_Of_Publication.mean())\n\"\"\"\nI don't like this method, but I force to use this solution\n\"\"\"\n\"\"\"\n**new Ratings_book dataset**\n\"\"\"\nratings_new = Ratings_df[Ratings_df.ISBN.isin(Books_df.ISBN)]\nratings_new = ratings_new[ratings_new.user_id.isin(Users_df.user_id)]\n\"\"\"\nSeparate 1 to 10 and 0 rated value\n\"\"\"\nratings_0 = ratings_new[ratings_new.book_rating ==0]\nratings_1to10 = ratings_new[ratings_new.book_rating !=0]\n# Create column Rating average \nratings_1to10['rating_Avg']=ratings_1to10.groupby('ISBN')['book_rating'].transform('mean')\n# Create column Rating sum\nratings_1to10['rating_sum']=ratings_1to10.groupby('ISBN')['book_rating'].transform('sum')\nratings_0.shape[0]\nratings_1to10.shape[0]\nratings_1to10.head()\ndataset=Users_df.copy()\ndataset=pd.merge(dataset,ratings_1to10,on='user_id')\ndataset=pd.merge(dataset,Books_df,on='ISBN')\ndef skew_test(df):\n    col = df.skew(axis = 0, skipna = True)\n    val = df.skew(axis = 0, skipna = True) \n    sk_table = pd.concat([col, val], axis = 1)\n    sk_table = sk_table.rename(\n    columns = {0 : 'skewness'})\n    print (\"Your selected dataframe has \" + str(df.shape[1]) + \" columns and \" + str(df.shape[0]) + \" Rows.\\n\"      \n        \"There are \" + str(sk_table.shape[0]) +\n          \" columns that have skewed values - Non Gaussian distribution.\")\n    return sk_table.drop([1], axis = 1).sort_values('skewness',ascending = False).reset_index()\nskk = skew_test(dataset)\nskk.style.background_gradient(cmap='Blues')\nfig, ax = plt.subplots(figsize=(18,8))\nsns.countplot(data=ratings_1to10,x='book_rating',ax=ax)\nprint(dataset.columns.tolist())\n\"\"\"\nWe don't need 3 columns : 'Image-URL-S', 'Image-URL-M', 'Image-URL-L'\n\"\"\"\ndataset=dataset[['user_id', 'Location', 'Age', 'Country', 'ISBN', 'book_rating', 'rating_Avg','rating_sum', 'Count_All_Rate', 'Book_Title', 'Book_Author', 'Year_Of_Publication', 'Publisher']]\nmissing_zero_values_table(dataset)\n\"\"\"\nOk everything's ok  \n\"\"\"\n\"\"\"\n# Simple Popularity based Recommendation System\n\"\"\"\ncm=sns.light_palette('red',as_cmap=True)\n# count all rate means include users rated 0 to book\npopular=dataset.groupby(['Book_Title','Count_All_Rate','rating_Avg','rating_sum']).size().reset_index().sort_values(['rating_sum','rating_Avg',0],\n                                                                                                            ascending=[False,False,True])[:20]\npopular.rename(columns={0:'Count_Rate'},inplace=True)\npopular.style.background_gradient(cmap=cm)\n\"\"\"\nThere are 20 most popular books in dataset  \nand they bought and rated it\n\"\"\"\n\"\"\"\nWhat !!  \nWhy it's recommended 'Wild Animus' book   \navg rate is low, but sum rate is high    \nthis is one problem of that    \nDo you know how can I fix this bug ??  \nIf you know say in the comment box  \n\"\"\"\n\"\"\"\n# Collaborative Filtering \n\"\"\"\n\"\"\"\nI don't have great knowledge, but I try to create best :))\n\"\"\"\n\"\"\"\nThe First step is to find  persons who are similar to user  \nso must be calculated distance   \nand distance can calculate by those methods    \n1. Manhattan distance \n2. Euclidean distance\n3. Minkowski distance\n\"\"\"\ndataset.head()\ndef manhattan(rating1,rating2):\n    \"Computes the Manhattan distance. Both rating1 and rating2 are dictionaries\"\n    user1=dict(zip(dataset.loc[dataset.user_id==rating1].Book_Title,dataset.loc[dataset.user_id==rating1].book_rating))\n    user2=dict(zip(dataset.loc[dataset.user_id==rating2].Book_Title,dataset.loc[dataset.user_id==rating2].book_rating))\n    distance = 0\n    for key in user1:\n        if key in user2:\n            distance += abs(user1[key] - user2[key])\n    return distance\nprint(f'Manhattan distance between user number 8 and 11676 : {manhattan(8,11676)}')\ndef euclidean(rating1,rating2):\n    \"Computes the Euclidean distance. Both rating1 and rating2 are dictionaries\"\n    user1=dict(zip(dataset.loc[dataset.user_id==rating1].Book_Title,dataset.loc[dataset.user_id==rating1].book_rating))\n    user2=dict(zip(dataset.loc[dataset.user_id==rating2].Book_Title,dataset.loc[dataset.user_id==rating2].book_rating))\n    distance = 0\n    for key in user1:\n        if key in user2:\n            distance += math.pow(abs(user1[key]-user2[key]),2)\n    return math.sqrt(distance)\nprint(f'Euclidean distance between user number 8 and 11676 : {euclidean(8,11676)}')  \n\ndef minkowski(rating1,rating2,r):\n    \"\"\"Computes the Minkowski distance. Both rating1 and rating2 are dictionaries\"\"\"\n    user1=dict(zip(dataset.loc[dataset.user_id==rating1].Book_Title,dataset.loc[dataset.user_id==rating1].book_rating))\n    user2=dict(zip(dataset.loc[dataset.user_id==rating2].Book_Title,dataset.loc[dataset.user_id==rating2].book_rating))\n    distance = 0\n    for key in user1:\n        if key in user2:\n            distance += math.pow(abs(user1[key]-user2[key]),r)\n    return math.pow(distance,1\/r)\nprint(f'Minkowski distance between user number 8 and 11676 : {minkowski(8,11676,2)}') \n\"\"\"\nDataset has a lot of users had rated lower than ten books   \nand  users don't paid attention to some books  \nso I will drop it  \n\"\"\"\ncounts1 = ratings_1to10['user_id'].value_counts()\nratings_1to10 = ratings_1to10[ratings_1to10['user_id'].isin(counts1[counts1 >= 100].index)]\ncounts = ratings_1to10['book_rating'].value_counts()\nratings_1to10 = ratings_1to10[ratings_1to10['book_rating'].isin(counts[counts >= 100].index)]\ndataset.user_id.unique().tolist()[500]\ndef computeNearestNeighbor(username):\n    \"\"\"Creates a sorted list of users based on their distance \n    to username \"\"\"\n    #users = list(dataset.user_id.unique())\n    users=dataset.user_id.unique().tolist()[:500]\n    distances = []\n    for user in users:\n        if user != username:\n            distance = manhattan(user,username)\n            distances.append((distance,user))\n    # sort based on distance -- closest first\n    distances.sort()\n    return distances\ncomputeNearestNeighbor(192762)\ndef recommend(username):\n    \"\"\"Give list of recommendations\"\"\"\n    # first find nearest neighbor\n    nearest=computeNearestNeighbor(username)[0][1]\n    recommendations=[]\n    # now find bands neighbor rated that user didn't\n    neighborRatings = dataset.loc[dataset.user_id==nearest].Book_Title.tolist()\n    userRatings = dataset.loc[dataset.user_id==username].Book_Title.tolist()\n    for artist in neighborRatings:\n        if not artist in userRatings:\n            recommendations.append((artist,int(dataset[(dataset.Book_Title==artist) & (dataset.user_id==nearest)].book_rating)))\n    return sorted(recommendations,key=lambda artistTuple : artistTuple[1],reverse=True)\nprint(recommend(192762))\n\"\"\"\nIt shows us Manhattan distance between user 192762 with 500 other users distance to suggest book   \nand it's not helpful for high count users   \nso must find another solution   \n\"\"\"\n\"\"\"\n<hr>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '01d759dd91e914'}"}
{"id":"16372","text":"# 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\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nimport warnings as w\nw.filterwarnings(\"ignore\")\ndf = pd.read_csv('\/kaggle\/input\/breast-cancer-csv\/breastCancer.csv')\ndf\ndf.head(10)\ndf.shape\ndf.describe()\ndf.info()\ndf.columns\nprint(df['class'].value_counts()\/6.99)\ndf['class'].value_counts()\n\"\"\"\nWe can see here that our data is imbalanced.As the class 2 data is about 65% and class 4 is 34.5%.\n\"\"\"\n\"\"\"\nLet's Check if there are any missing values present in the dataset.\n\"\"\"\nc = {col:df[df[col] == \"?\"].shape[0] for col in df.columns}\nc\n\"\"\"\nHere we can see there are some missing values present in the 'bare_nucleoli' feature.\n\"\"\"\nimport numpy as np\nfor i in range(df.shape[1]):\n    for j in range(df.shape[0]):\n        if(df.iloc[j,i]=='?'):\n            df.iloc[j,i]=np.NaN\nlist(df['bare_nucleoli'].mode())\ndf[\"bare_nucleoli\"]=df[\"bare_nucleoli\"].apply(lambda x: 1.0 if pd.isnull(x) else x)\ndf.corr()\nfig1 = plt.figure(figsize=(10,8))\nsns.heatmap(df.corr(),annot=True,cmap='YlGnBu',vmax=1.0,vmin=-1.0)\nfig2 = plt.figure(figsize=(6,6))\nsns.pairplot(df.iloc[:,1:],hue='class',palette='Set2')\n\"\"\"\n**Applying the Train and Test split for splitting the data for applying the models.**\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(df.iloc[:,1:-1],df.iloc[:,-1])\nprint(X_train,\"\\n\")\nprint(X_test,\"\\n\")\nprint(y_train,\"\\n\")\nprint(y_test,\"\\n\")\nprint(\"The dimension of X_train is : \",X_train.shape,\"\\n\")\nprint(\"The dimension of X_test is : \",X_test.shape,\"\\n\")\nprint(\"The dimension of y_train is : \",y_train.shape,\"\\n\")\nprint(\"The dimension of y_test is : \",y_test.shape,\"\\n\")\n\"\"\"\n**Applying the K Nearest Neighbour algorithm**\n\"\"\"\nerror_rate = []\nfor i in range(1,40):\n    knn = KNeighborsClassifier(n_neighbors=i)\n    knn.fit(X_train,y_train)\n    pred = knn.predict(X_test)\n    error_rate.append(np.mean(pred != y_test))\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40), error_rate,'o--')\nplt.ylabel('Error Rate')\nplt.xlabel('K')\n\"\"\"\n***As we can see in above Error rate vs k plot the optimal values for k is 4.***\n\"\"\"\nmodel1 = KNeighborsClassifier(n_neighbors=4).fit(X_train,y_train)\nfig3, axs = plt.subplots(figsize=(5,5))\nplot_confusion_matrix(model1,X_test,y_test,ax=axs)\nprint(classification_report(model1.predict(X_train),y_train))\nprint(classification_report(model1.predict(X_test),y_test))\nprint(accuracy_score(y_test,pred))\n\"\"\"\n**Applying the GaussianNB Algorithm.**\n\"\"\"\ngaussnb = GaussianNB()\ngaussnb.fit(X_train,y_train)\ngaussnbpred = gaussnb.predict(X_test)\ngaussnbresults = confusion_matrix(y_test,gaussnbpred)\ngaussnbacc_score = accuracy_score(y_test,gaussnbpred)\nprint(\"The accuracy of NaiveBayes model is : %0.4f \", gaussnbacc_score)\nprint(\"The confusion matrix is :\\n\", gaussnbresults)\nfig4, axs = plt.subplots(figsize=(5,5))\nplot_confusion_matrix(gaussnb,X_test,y_test,ax=axs)\nprint(classification_report(y_test,gaussnbpred))\n\"\"\"\n**Applying Logistic Regression Model.**\n\"\"\"\nlogreg = LogisticRegression()\nlogreg.fit(X_train,y_train)\nlogpred = logreg.predict(X_test)\nlogacc_score = accuracy_score(y_test,logpred)\nlogresults = confusion_matrix(y_test,logpred)\nprint(\"The accuracy of Logistic Regression is : %0.4f\", logacc_score)\nprint(\"The confusion matrix is : \\n \", logresults )\nfig5, axs = plt.subplots(figsize=(5,5))\nplot_confusion_matrix(logreg,X_test,y_test,ax=axs)\nprint(classification_report(y_test,logpred))\n\"\"\"\n1. After Applying all the Models like Knn,Logitic Regression & GaussianNB we have all the confusion matrix plot and the classification report of the models. \n2. From the above we choose the most accurate algorithm.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1dd8952759046b'}"}
{"id":"49705","text":"from IPython.core.display import display, HTML, Javascript\nhtml_contents = \"\"\"\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <link rel=\"stylesheet\" href=\"https:\/\/www.w3schools.com\/w3css\/4\/w3.css\">\n        <link rel=\"stylesheet\" href=\"https:\/\/fonts.googleapis.com\/css?family=Raleway\">\n        <link rel=\"stylesheet\" href=\"https:\/\/fonts.googleapis.com\/css?family=Oswald\">\n        <link rel=\"stylesheet\" href=\"https:\/\/fonts.googleapis.com\/css?family=Open Sans\">\n        <link rel=\"stylesheet\" href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/font-awesome\/4.7.0\/css\/font-awesome.min.css\">\n        <style>\n        .title-section{\n            font-family: \"Oswald\", Arial, sans-serif;\n            font-weight: bold;\n            color: \"#6A8CAF\";\n            letter-spacing: 6px;\n        }\n        hr { border: 1px solid #E58F65 !important;\n             color: #E58F65 !important;\n             background: #E58F65 !important;\n           }\n        body {\n            font-family: \"Open Sans\", sans-serif;\n            }\n        <\/style>\n    <\/head>\n<\/html>\n\"\"\"\n\nHTML(html_contents)\n\"\"\"\n# <span class=\"title-section w3-xxlarge\" id=\"codebook\">Technical Analysis Indicators<\/span>\n\n- Here are some simple indexes to analyze the charts. some can even be used as features to a model.\n- Ta-lib is very good and very helpful library for calculating various indexes, but kernel doesn't support.\n- Enjoy the short scripts to obtain them! \n\nBased on: https:\/\/www.kaggle.com\/youhanlee\/simple-quant-features-using-python\n\nThis notebook follows the ideas presented in my \"Initial Thoughts\" [here][1]. \n\n[1]: https:\/\/www.kaggle.com\/c\/g-research-crypto-forecasting\/discussion\/284903\n\"\"\"\n\"\"\"\n____\n\n#### <center>All baselines in the series \ud83d\udc47<\/center>\n\n| CV + Model | Hyperparam Optimization  | Time Series Models | Feature Engineering |\n| --- | --- | --- | --- |\n| [Neural Network Starter](https:\/\/www.kaggle.com\/yamqwe\/purgedgrouptimeseries-cv-with-extra-data-nn) | [MLP + AE](https:\/\/www.kaggle.com\/yamqwe\/bottleneck-encoder-mlp-keras-tuner)        | [LSTM](https:\/\/www.kaggle.com\/yamqwe\/time-series-modeling-lstm) | \u23f3Technical Analysis |\n| [LightGBM Starter](https:\/\/www.kaggle.com\/yamqwe\/purgedgrouptimeseries-cv-with-extra-data-lgbm)     | [LightGBM](https:\/\/www.kaggle.com\/yamqwe\/purged-time-series-cv-lightgbm-optuna)     | [Wavenet](https:\/\/www.kaggle.com\/yamqwe\/time-series-modeling-wavenet) | \u23f3Time Series Agg | \n| [Catboost Starter](https:\/\/www.kaggle.com\/yamqwe\/purgedgrouptimeseries-cv-extra-data-catboost)      | [Catboost](https:\/\/www.kaggle.com\/yamqwe\/purged-time-series-cv-catboost-gpu-optuna) | [Multivariate-Transformer [written from scratch]](https:\/\/www.kaggle.com\/yamqwe\/time-series-modeling-multivariate-transformer) | \u23f3Target Engineering |\n| [XGBoost Starter](https:\/\/www.kaggle.com\/yamqwe\/xgb-extra-data)                                            | [XGboost](https:\/\/www.kaggle.com\/yamqwe\/purged-time-series-cv-xgboost-gpu-optuna) | |\u23f3Neutralization |\n| [Supervised AE [Janestreet 1st]](https:\/\/www.kaggle.com\/yamqwe\/1st-place-of-jane-street-adapted-to-crypto) | [Supervised AE [Janestreet 1st]](https:\/\/www.kaggle.com\/yamqwe\/1st-place-of-jane-street-keras-tuner) | |\u23f3Quant's Volatility Features |\n| [Transformer)](https:\/\/www.kaggle.com\/yamqwe\/let-s-test-a-transformer)                                     | [Transformer](https:\/\/www.kaggle.com\/yamqwe\/sh-tcoins-transformer-baseline)  | |\u23f3Fourier Analysis \n| [TabNet Starter](https:\/\/www.kaggle.com\/yamqwe\/tabnet-cv-extra-data)                                       |  |  | \u23f3Wavelets | \n| [Reinforcement Learning (PPO) Starter](https:\/\/www.kaggle.com\/yamqwe\/g-research-reinforcement-learning-starter) |  |  \n\n____\n\"\"\"\n\"\"\"\n# <span class=\"title-section w3-xxlarge\" id=\"codebook\">Kaggle's G-Research Crypto Forecasting<\/span>\nIn this competition, we need to forecast returns of cryptocurrency assets. Full description [here][1]. This is a very challenging time series task as seen by looking at the sample data below.\n\n[1]: https:\/\/www.kaggle.com\/c\/g-research-crypto-forecasting\/overview\n\"\"\"\nimport os\nimport pandas as pd\nimport plotly.graph_objects as go\ndata_path = '..\/input\/g-research-crypto-forecasting\/'\ncrypto_df = pd.read_csv( data_path + 'train.csv')\nbtc = crypto_df[crypto_df[\"Asset_ID\"] == 1].set_index(\"timestamp\")\nbtc_mini = btc.iloc[-200:]\nfig = go.Figure(data = [go.Candlestick(x = btc_mini.index, open = btc_mini['Open'], high = btc_mini['High'], low = btc_mini['Low'], close = btc_mini['Close'])])\nfig.show()\n\"\"\"\n# <span class=\"title-section w3-xxlarge\" id=\"codebook\">Initialize Environment<\/span>\n\"\"\"\nimport os\nimport gc\nimport traceback\nimport numpy as np\nimport pandas as pd\nimport datatable as dt\nimport gresearch_crypto\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\ndata_path = '..\/input\/g-research-crypto-forecasting\/'\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nwarnings.simplefilter(action='ignore', category=pd.core.common.SettingWithCopyWarning)\n    \nplt.style.use('bmh')\nplt.rcParams['figure.figsize'] = [14, 8]  # width, height\n\"\"\"\n# Loading the Competition Data\n\nIn the real competition data, the number of datapoints per day (that is per \"group\") is not constant as it was in the spoofed data. We need to confirm that the time series split respects that there are different counts of samples in the the days. We load the data and reduce memory footprint.\n\"\"\"\n# Memory saving function credit to https:\/\/www.kaggle.com\/gemartin\/load-data-reduce-memory-usage\ndef reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.\n    \"\"\"\n    start_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n\n    for col in df.columns:\n        col_type = df[col].dtype.name\n\n        if col_type not in ['object', 'category', 'datetime64[ns, UTC]']:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) \/ start_mem))\n\n    return df\nINC2021 = 0\nINC2020 = 0\nINC2019 = 0\nINC2018 = 0\nINC2017 = 0\nINCCOMP = 1\nINCSUPP = 0\n\norig_df_train = pd.read_csv(data_path + 'train.csv')\nsupp_df_train = pd.read_csv(data_path + 'supplemental_train.csv')\ndf_asset_details = pd.read_csv(data_path  + 'asset_details.csv').sort_values(\"Asset_ID\")\n\nextra_data_files = {0: '..\/input\/cryptocurrency-extra-data-binance-coin', 2: '..\/input\/cryptocurrency-extra-data-bitcoin-cash', 1: '..\/input\/cryptocurrency-extra-data-bitcoin', 3: '..\/input\/cryptocurrency-extra-data-cardano', 4: '..\/input\/cryptocurrency-extra-data-dogecoin', 5: '..\/input\/cryptocurrency-extra-data-eos-io', 6: '..\/input\/cryptocurrency-extra-data-ethereum', 7: '..\/input\/cryptocurrency-extra-data-ethereum-classic', 8: '..\/input\/cryptocurrency-extra-data-iota', 9: '..\/input\/cryptocurrency-extra-data-litecoin', 11: '..\/input\/cryptocurrency-extra-data-monero', 10: '..\/input\/cryptocurrency-extra-data-maker', 12: '..\/input\/cryptocurrency-extra-data-stellar', 13: '..\/input\/cryptocurrency-extra-data-tron'}\n\ndef load_training_data_for_asset(asset_id):\n    dfs = []\n    if INCCOMP: dfs.append(orig_df_train[orig_df_train[\"Asset_ID\"] == asset_id].copy())\n    if INCSUPP: dfs.append(supp_df_train[supp_df_train[\"Asset_ID\"] == asset_id].copy())\n    if INC2017 and os.path.exists(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2017) + '.csv'): dfs.append(pd.read_csv(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2017) + '.csv'))\n    if INC2018 and os.path.exists(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2018) + '.csv'): dfs.append(pd.read_csv(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2018) + '.csv'))\n    if INC2019 and os.path.exists(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2019) + '.csv'): dfs.append(pd.read_csv(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2019) + '.csv'))\n    if INC2020 and os.path.exists(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2020) + '.csv'): dfs.append(pd.read_csv(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2020) + '.csv'))\n    if INC2021 and os.path.exists(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2021) + '.csv'): dfs.append(pd.read_csv(extra_data_files[asset_id] + '\/full_data__' + str(asset_id) + '__' + str(2021) + '.csv'))\n    df = pd.concat(dfs, axis = 0) if len(dfs) > 1 else dfs[0]\n    df['date'] = pd.to_datetime(df['timestamp'], unit = 's')\n    df = df.sort_values('date')\n    return df\n\ndef load_data_for_all_assets():\n    dfs = []\n    for asset_id in list(extra_data_files.keys()): dfs.append(load_training_data_for_asset(asset_id))\n    return pd.concat(dfs)\n\ntrain = load_data_for_all_assets().sort_values('timestamp').set_index(\"timestamp\")\ntest = pd.read_csv(data_path + 'example_test.csv')\nsample_prediction_df = pd.read_csv(data_path + 'example_sample_submission.csv')\nprint(\"Loaded all data!\")\n\"\"\"\n# <span class=\"title-section w3-xxlarge\" id=\"codebook\">Feature Engineering<\/span>\n\"\"\"\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport lightgbm as lgb\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error\nplt.style.use('seaborn')\nsns.set(font_scale=2)\nimport warnings; warnings.filterwarnings('ignore')\ntrain_data = train.copy()\ntrain_data['date'] = pd.to_datetime(train_data['date'])\ndf = train_data.loc[train_data['Asset_ID'] == 1]\nN=100\n\ndf['timestamp'] = df['date']\ndf.set_index(df['timestamp'], inplace=True)\ndf.drop('timestamp', axis=1, inplace=True)\n\nconvertion={\n    'Open':'first',\n    'High':'max',\n    'Low':'min',\n    'Close':'mean',\n    'Volume':'sum',    \n}\nds_df = df.resample('W').apply(convertion)\n\"\"\"\n# Moving average\n\"\"\"\n\"\"\"\n> An example of two moving average curves\nIn statistics, a moving average (rolling average or running average) is a calculation to analyze data points by creating series of averages of different subsets of the full data set. It is also called a moving mean (MM)[1] or rolling mean and is a type of finite impulse response filter.\n\nref. https:\/\/en.wikipedia.org\/wiki\/Moving_average\n\"\"\"\n\"\"\"\n## Moving average\n\"\"\"\n\"\"\"\n- Moving average is simple\n\"\"\"\n\n\nds_df['rolling_mean' + str(N) + '_' + str(5)] = ds_df.Close.rolling(window=5).mean()\nds_df['rolling_mean' + str(N) + '_' + str(10)] = ds_df.Close.rolling(window=10).mean()\n\n\n\nfig = go.Figure(go.Candlestick(x=ds_df.index,open=ds_df['Open'],high=ds_df['High'],low=ds_df['Low'],close=ds_df['Close']))\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.update_yaxes(type=\"log\")\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close'))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['rolling_mean' + str(N) + '_' + str(5)], mode='lines', name='MEAN_5' + str(N),line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['rolling_mean' + str(N) + '_' + str(10)], mode='lines', name='MEAN_10' + str(N), line=dict(color='#555555', width=2)))\nfig.show()\n\"\"\"\n## Exponential Moving Average\n\"\"\"\n\"\"\"\n> An exponential moving average (EMA), also known as an exponentially weighted moving average (EWMA),[5] is a first-order infinite impulse response filter that applies weighting factors which decrease exponentially.\n\nref. https:\/\/en.wikipedia.org\/wiki\/Moving_average#Exponential_moving_average\n\"\"\"\newma = pd.Series.ewm\nds_df['rolling_ema_'+ str(N)]  = ds_df.Close.ewm(min_periods=N, span=N).mean()\n\n\nds_df['rolling_ema_' + str(N)] = ds_df.Close.ewm(min_periods=10, span=10).mean()\n\n\n\nfig = go.Figure(go.Candlestick(x=ds_df.index,open=ds_df['Open'],high=ds_df['High'],low=ds_df['Low'],close=ds_df['Close']))\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.update_yaxes(type=\"log\")\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close'))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['rolling_ema_' + str(N)], mode='lines', name='EMA_10',line=dict(color='royalblue', width=2)))\nfig.show()\n\"\"\"\n# MACD\n- MACD: (12-day EMA - 26-day EMA)\n\"\"\"\n\"\"\"\n> Moving average convergence divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages of prices. The MACD is calculated by subtracting the 26-day exponential moving average (EMA) from the 12-day EMA\n\nref. https:\/\/www.investopedia.com\/terms\/m\/macd.asp\n\"\"\"\nds_df['close_5EMA'] = ewma(ds_df[\"Close\"], span=5).mean()\nds_df['close_2EMA'] = ewma(ds_df[\"Close\"], span=2).mean()\n\nds_df['MACD'] = ds_df['close_5EMA'] - ds_df['close_2EMA']\n\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close', line=dict(color='#555555', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['MACD'], mode='lines', name='MACD_26_12',line=dict(color='royalblue', width=2)))\nfig.show()\n\"\"\"\n## Bollinger Band\n\"\"\"\n\"\"\"\n> Bollinger Bands are a type of statistical chart characterizing the prices and volatility over time of a financial instrument or commodity, using a formulaic method propounded by John Bollinger in the 1980s. Financial traders employ these charts as a methodical tool to inform trading decisions, control automated trading systems, or as a component of technical analysis. Bollinger Bands display a graphical band (the envelope maximum and minimum of moving averages, similar to Keltner or Donchian channels) and volatility (expressed by the width of the envelope) in one two-dimensional chart.\n\nref. https:\/\/en.wikipedia.org\/wiki\/Bollinger_Bands\n\"\"\"\nwindow = 7\nno_of_std = 2\n\nds_df[f'MA_{window}MA'] = ds_df['Close'].rolling(window=window).mean()\nds_df[f'MA_{window}MA_std'] = ds_df['Close'].rolling(window=window).std() \nds_df[f'MA_{window}MA_BB_high'] = ds_df[f'MA_{window}MA'] + no_of_std * ds_df[f'MA_{window}MA_std']\nds_df[f'MA_{window}MA_BB_low'] = ds_df[f'MA_{window}MA'] - no_of_std * ds_df[f'MA_{window}MA_std']\n\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close', line=dict(color='#555555', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_high'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_low'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.show()\nwindow = 15\nno_of_std = 2\n\nds_df[f'MA_{window}MA'] = ds_df['Close'].rolling(window=window).mean()\nds_df[f'MA_{window}MA_std'] = ds_df['Close'].rolling(window=window).std() \nds_df[f'MA_{window}MA_BB_high'] = ds_df[f'MA_{window}MA'] + no_of_std * ds_df[f'MA_{window}MA_std']\nds_df[f'MA_{window}MA_BB_low'] = ds_df[f'MA_{window}MA'] - no_of_std * ds_df[f'MA_{window}MA_std']\n\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close', line=dict(color='#555555', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_high'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_low'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.show()\nwindow = 30\nno_of_std = 2\n\nds_df[f'MA_{window}MA'] = ds_df['Close'].rolling(window=window).mean()\nds_df[f'MA_{window}MA_std'] = ds_df['Close'].rolling(window=window).std() \nds_df[f'MA_{window}MA_BB_high'] = ds_df[f'MA_{window}MA'] + no_of_std * ds_df[f'MA_{window}MA_std']\nds_df[f'MA_{window}MA_BB_low'] = ds_df[f'MA_{window}MA'] - no_of_std * ds_df[f'MA_{window}MA_std']\n\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df['Close'],mode='lines',name='Close', line=dict(color='#555555', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_high'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'MA_{window}MA_BB_low'], mode='lines', name=f'BB_high',line=dict(color='royalblue', width=2)))\nfig.show()\n\"\"\"\n# RSI\n\"\"\"\n\"\"\"\n> The Relative Strength Index (RSI), developed by J. Welles Wilder, is a momentum oscillator that measures the speed and change of price movements. The RSI oscillates between zero and 100. Traditionally the RSI is considered overbought when above 70 and oversold when below 30. Signals can be generated by looking for divergences and failure swings. RSI can also be used to identify the general trend.\n\nref. https:\/\/www.fidelity.com\/learning-center\/trading-investing\/technical-analysis\/technical-indicator-guide\/RSI\n\"\"\"\ndef rsiFunc(prices, n=14):\n    deltas = np.diff(prices)\n    seed = deltas[:n+1]\n    up = seed[seed>=0].sum()\/n\n    down = -seed[seed<0].sum()\/n\n    rs = up\/down\n    rsi = np.zeros_like(prices)\n    rsi[:n] = 100. - 100.\/(1.+rs)\n\n    for i in range(n, len(prices)):\n        delta = deltas[i-1] # cause the diff is 1 shorter\n\n        if delta>0:\n            upval = delta\n            downval = 0.\n        else:\n            upval = 0.\n            downval = -delta\n\n        up = (up*(n-1) + upval)\/n\n        down = (down*(n-1) + downval)\/n\n\n        rs = up\/down\n        rsi[i] = 100. - 100.\/(1.+rs)\n\n    return rsi\nrsi_6 = rsiFunc(ds_df['Close'].values, 6)\nrsi_14 = rsiFunc(ds_df['Close'].values, 14)\nrsi_20 = rsiFunc(ds_df['Close'].values, 20)\nds_df['rsi_6'] = rsi_6\nds_df['rsi_14'] = rsi_14\nds_df['rsi_20'] = rsi_20\n\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'rsi_6'], mode='lines', name=f'rsi_6',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'rsi_14'], mode='lines', name=f'rsi_14',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'rsi_20'], mode='lines', name=f'rsi_20',line=dict(color='royalblue', width=2)))\nfig.show()\n\"\"\"\n# Volume Moving Avreage\n\"\"\"\n\"\"\"\n> A Volume Moving Average is the simplest volume-based technical indicator. Similar to a price moving average, a VMA is an average volume of a security (stock), commodity, index or exchange over a selected period of time. Volume Moving Averages are used in charts and in technical analysis to smooth and describe a volume trend by filtering short term spikes and gaps.\n\nref. https:\/\/www.marketvolume.com\/analysis\/volume_ma.asp\n\"\"\"\nds_df['VMA_7MA'] = ds_df['Volume'].rolling(window=7).mean()\nds_df['VMA_15MA'] = ds_df['Volume'].rolling(window=15).mean()\nds_df['VMA_30MA'] = ds_df['Volume'].rolling(window=30).mean()\nds_df['VMA_60MA'] = ds_df['Volume'].rolling(window=60).mean()\nfig = go.Figure()\nfig.update_layout(title='Bitcoin Price', yaxis_title='BTC')\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'VMA_7MA'], mode='lines', name=f'VMA_7MA',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'VMA_15MA'], mode='lines', name=f'VMA_15MA',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'VMA_30MA'], mode='lines', name=f'VMA_30MA',line=dict(color='royalblue', width=2)))\nfig.add_trace(go.Scatter(x=ds_df.index, y=ds_df[f'VMA_60MA'], mode='lines', name=f'VMA_60MA',line=dict(color='royalblue', width=2)))\nfig.show()\n\"\"\"\n# More to come..\n\"\"\"\n\"\"\"\n# <span class=\"title-section w3-xxlarge\">References<\/span>\n\n<span id=\"f1\">1.<\/span> [Initial baseline notebook](https:\/\/www.kaggle.com\/julian3833)<br>\n<span id=\"f2\">2.<\/span> [Competition tutorial](https:\/\/www.kaggle.com\/cstein06\/tutorial-to-the-g-research-crypto-competition)<br>\n<span id=\"f3\">3.<\/span> [Competition Overview](https:\/\/www.kaggle.com\/c\/g-research-crypto-forecasting\/overview)<\/span><br>\n<span id=\"f4\">4.<\/span> [My Initial Ideas for this competition](https:\/\/www.kaggle.com\/c\/g-research-crypto-forecasting\/discussion\/284903)<\/span><br>\n<span id=\"f5\">5.<\/span> [My post notebook about cross validation](https:\/\/www.kaggle.com\/yamqwe\/let-s-talk-validation-grouptimeseriessplit)<\/span><br>\n<span id=\"f5\">6.<\/span> [Chris original notebook from SIIM ISIC](https:\/\/www.kaggle.com\/cdeotte\/triple-stratified-kfold-with-tfrecords)<\/span><br>\n\n<span class=\"title-section w3-large w3-tag\">WORK IN PROGRESS! \ud83d\udea7<\/span>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5b7abb6c254593'}"}
{"id":"88895","text":"\"\"\"\n# Exploring Trending Youtube Video Statistics for the U.S.\n\nGrowing up watching YouTube shaped a lot of my interests and humor. I still remember the early days when nigahiga's How To Be Gangster and ALL YOUR BASE ARE BELONG TO US was peak comedy. So I thought it would be fun to see the state of YouTube and what's popular now.\n\"\"\"\n\"\"\"\n## Loading Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator \n\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport seaborn as sb\n\n%matplotlib inline\nrcParams['figure.figsize'] = 8, 6\nsb.set()\n\"\"\"\n## Reading and Cleaning Data\n\"\"\"\n# Read in dataset\n\nvids = pd.read_csv('..\/input\/youtube-new\/USvideos.csv')\n\n# Add category names\nvids['category'] = np.nan\n\nvids.loc[(vids[\"category_id\"] == 1),\"category\"] = 'Film & Animation'\nvids.loc[(vids[\"category_id\"] == 2),\"category\"] = 'Autos & Vehicles'\nvids.loc[(vids[\"category_id\"] == 10),\"category\"] = 'Music'\nvids.loc[(vids[\"category_id\"] == 15),\"category\"] = 'Pets & Animals'\nvids.loc[(vids[\"category_id\"] == 17),\"category\"] = 'Sports'\nvids.loc[(vids[\"category_id\"] == 19),\"category\"] = 'Travel & Events'\nvids.loc[(vids[\"category_id\"] == 20),\"category\"] = 'Gaming'\nvids.loc[(vids[\"category_id\"] == 22),\"category\"] = 'People & Blogs'\nvids.loc[(vids[\"category_id\"] == 23),\"category\"] = 'Comedy'\nvids.loc[(vids[\"category_id\"] == 24),\"category\"] = 'Entertainment'\nvids.loc[(vids[\"category_id\"] == 25),\"category\"] = 'News & Politics'\nvids.loc[(vids[\"category_id\"] == 26),\"category\"] = 'How-To & Style'\nvids.loc[(vids[\"category_id\"] == 27),\"category\"] = 'Education'\nvids.loc[(vids[\"category_id\"] == 28),\"category\"] = 'Science & Technology'\nvids.loc[(vids[\"category_id\"] == 29),\"category\"] = 'Nonprofits & Activism'\n\n# Add like, dislike, commment ratios\nvids['like_pct'] = vids['likes'] \/ (vids['dislikes'] + vids['likes']) * 100\nvids['dislike_pct'] = vids['dislikes'] \/ (vids['dislikes'] + vids['likes']) * 100\nvids['comment_pct'] = vids['comment_count'] \/ vids['views'] * 100\n\n# Order by Views\nvids.sort_values('views', ascending = False, inplace = True)\n\n# Remove Duplicate Videos\nvids.drop_duplicates(subset = 'video_id', keep = 'first', inplace = True)\nvids.head()\n\"\"\"\nAfter removing videos with the same id, we see there are now only 6,351 videos to analyze. These 6,351 videos should reflect the row with the highest view count for the video.\n\nI also created the variables like_pct, dislike_pct, and comment_pct. Like_pct and dislike_pct are calculated as the ratio of likes\/dislikes relating to the total number of likes\/dislikes on the video. Comment_pct is the the % of comments left on the video relative to the total number of views. I thought that these ratios were more intuitive, rather than having every one relating to the total number of views.\n\"\"\"\n\"\"\"\n## Summary Statistics and Top Trending\n\"\"\"\npd.options.display.float_format = \"{:,.0f}\".format\nvids.describe().iloc[:,1:5]\n\"\"\"\nThe average number of views for a trending video was ~2M, with a standard deviation of ~7M. Interestingly, the minimum number of views was 559 and the maximum was ~225M. This is a pretty broad range. Makes you wonder how YouTube selects which videos are trending. It doesn't really make sense to me that there is a video with 0 likes, dislikes, and comments that is trending.\n\nI'd like now to see the Top 10 Videos by Views, Likes, Dislikes, and Comments.\n\"\"\"\n\"\"\"\n### Top 10 Videos\n#### Top 10 Videos By Views\n\"\"\"\npd.options.display.float_format = \"{:,.2f}\".format\n\ntop10_vids = vids.nlargest(10, 'views')\ndisplay(top10_vids.iloc[:, [2,3,7,16]])\n\"\"\"\n#### Top 10 Videos By Likes\n\"\"\"\ntop10_vids = vids.nlargest(10, 'likes')\ntop10_vids.iloc[:, [2,3,7,8,17,16]]\n\"\"\"\n#### Top 10 Videos By Dislikes\n\"\"\"\ntop10_vids = vids.nlargest(10, 'dislikes')\ntop10_vids.iloc[:, [2,3,7,9,18,16]]\n\"\"\"\n#### Top 10 Videos By Comments\n\"\"\"\ntop10_vids = vids.nlargest(10, 'comment_count')\ntop10_vids.iloc[:, [2,3,7,10,19,16]]\n\"\"\"\n### Correlation Heatmap\n\"\"\"\ncorr = vids[['views', 'likes', 'dislikes', 'comment_count', 'like_pct', 'dislike_pct', 'comment_pct']].corr()\nsb.heatmap(corr, annot = True, fmt = '.2f', center = 1)\nplt.show()\n\"\"\"\nReading this heatmap, we note that views has a high correlation with likes -- not so much dislikes. Comment_count and likes\/dislikes have strong correlation as well, but comment_count does not have a particularly strong correlation with views.\n\"\"\"\n\"\"\"\n### Bottom 10 Videos by Views\n\nI'm curious what the trending videos with low views actually are. Seeing below, it appears that they are pretty randomly assorted. Not sure why they are on the trending list, and YouTube is decidedly not transparent with its algorithm. Perhaps they are getting a high ratio of shares?\n\"\"\"\nbot10_vids = vids.nsmallest(10, 'views')\nbot10_vids.iloc[:, [2,3,7,8,9,10,16]]\n\"\"\"\n### Top 10 Channels\n\nLet's take a look at the top 10 channels that appear the most frequently on the trending videos list. They're comprised of late night shows and channels otherwise run by companies, not individual YouTubers.\n\"\"\"\ntop10_chan = vids['channel_title'].value_counts()\ntop10_chan = top10_chan[1:10].to_frame()\ntop10_chan.columns = ['number of videos']\n\ntop10_chan\n\"\"\"\n## Category Analysis\n\"\"\"\ncategories = vids['category'].value_counts().to_frame()\ncategories['index'] = categories.index\ncategories.columns = ['count', 'category']\ncategories.sort_values('count', ascending = True, inplace = True)\n\nplt.barh(categories['category'], categories['count'], color='#007ACC')\nplt.xlabel('Count')\nplt.title('Number of Trending Videos Per Category')\nplt.show()\n\"\"\"\n### Averages Per Category\n\"\"\"\nvids_cat = vids[['category','views', 'likes', 'dislikes', 'comment_count', 'like_pct', 'dislike_pct', 'comment_pct']]\nvids_cat_groups = vids_cat.groupby(vids_cat['category'])\nvids_cat_groups = vids_cat_groups.mean()\nvids_cat_groups['category'] = categories.index\n\nvids_cat_groups.sort_values('views', ascending = True, inplace = True)\nplt.barh(vids_cat_groups['category'], vids_cat_groups['views'], color='#007ACC')\nplt.xlabel('Average # Views')\nplt.title('Average Number of Views Per Video By Category')\nplt.show()\nvids_cat_groups.sort_values('comment_count', ascending = True, inplace = True)\nplt.barh(vids_cat_groups['category'], vids_cat_groups['comment_count'], color='#007ACC')\nplt.xlabel('Average # Comments')\nplt.title('Average Number of Comments Per Video By Category')\nplt.show()\nvids_cat_groups.sort_values('likes', ascending = True, inplace = True)\nplt.barh(vids_cat_groups['category'], vids_cat_groups['likes'], color='#007ACC')\nplt.xlabel('Average # Likes')\nplt.title('Average Number of Likes Per Video By Category')\nplt.show()\nvids_cat_groups.sort_values('dislikes', ascending = True, inplace = True)\nplt.barh(vids_cat_groups['category'], vids_cat_groups['dislikes'], color='#007ACC')\nplt.xlabel('Average # Dislikes')\nplt.title('Average Number of Dislikes Per Video By Category')\nplt.show()\n\"\"\"\nWhen it comes to averages, People & Blogs and Science & Technology contend for the highest enagement levels, swapping for spot 1 and 2 for highest average number of likes, dislikes, and comments.\n\"\"\"\n\"\"\"\n### Distributions Per Category\n\"\"\"\nplt.figure(figsize = (16, 10))\n\nsb.boxplot(x = 'category', y = 'like_pct', data = vids, palette = 'Pastel1')\nplt.xticks(rotation=45)\nplt.xlabel('')\nplt.ylabel('% Likes', fontsize = 14)\nplt.title('Boxplot of % Likes on a Video By Category', fontsize = 16)\nplt.show()\nplt.figure(figsize = (16, 10))\n\nsb.boxplot(x = 'category', y = 'dislike_pct', data = vids, palette = 'Pastel1')\nplt.xticks(rotation=45)\nplt.xlabel('')\nplt.ylabel('% Likes', fontsize = 14)\nplt.title('Boxplot of % Dislikes on a Video By Category', fontsize = 16)\nplt.show()\nplt.figure(figsize = (16, 10))\n\nsb.boxplot(x = 'category', y = 'comment_pct', data = vids, palette = 'Pastel1')\nplt.xticks(rotation=45)\nplt.xlabel('')\nplt.ylabel('% Comments', fontsize = 14)\nplt.title('Boxplot of % Comments on a Video By Category', fontsize = 16)\nplt.show()\n\"\"\"\nUnsurprisingly, News & Politics is the most controversial category, with a higher median and larger spread of dislikes\/likes. Along with Gaming, it is also more frequently commented on.\n\"\"\"\n\"\"\"\n## Title Wordcloud\n\"\"\"\ntext = \" \".join(title for title in vids.title)\n# print(\"{} words total\".format(len(text)))\n\nplt.figure(figsize = (10, 12))\ntitle_cloud = WordCloud(background_color = \"white\").generate(text)\nplt.imshow(title_cloud, interpolation = 'bilinear')\nplt.axis('off')\nplt.show()\n\"\"\"\nMovie trailers and music videos seem particularly popular.\n\"\"\"\n\"\"\"\n## Tags Wordcloud\n\"\"\"\ntext = \" \".join(tags for tags in vids.tags)\n# print(\"{} words total\".format(len(text)))\n\nplt.figure(figsize = (10, 12))\ntag_cloud = WordCloud(background_color = \"white\").generate(text)\nplt.imshow(tag_cloud, interpolation = 'bilinear')\nplt.axis('off')\nplt.show()\n\"\"\"\nFunny videos, talk shows, movies, and Star Wars in particular are notable tags.\n\"\"\"\n\"\"\"\n## Time Trends\n\"\"\"\nfrom datetime import datetime\n\n# Reformat publish_time\nvids['publish_time'] = vids['publish_time'].str[:10]\n\n# Reformat trending_date\nyear = vids['trending_date'].str[:2]\nmonth = vids['trending_date'].str[-2:]\ndate = vids['trending_date'].str[:-3].str[3:]\nvids['trending_date'] = '20' + year + '-' + month + '-' + date\n\nvids['publish_time'] = pd.to_datetime(vids['publish_time'])\nvids['trending_date'] = pd.to_datetime(vids['trending_date'])\nvids['publish_trend_lag'] = vids['trending_date'] - vids['publish_time']\ntimehist = plt.hist(vids['publish_trend_lag'].dt.days, bins = 30, range = (0, 30))\nplt.xlabel('Days')\nplt.title('Number of Days Between Video Publishing Date and Trending Date')\nplt.xticks(np.arange(0, 30, 3))\nplt.show()\n\"\"\"\nVideos tend to trend within a week of publication, and never on the day-of. As time passes past the publication date, we see it is increasingly rare for a video to start trending.\n\"\"\"\n\"\"\"\n#### Thank you!\n\nHope this was an enjoyable read.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a3082f04cec23e'}"}
{"id":"47518","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport datetime\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.compose import ColumnTransformer\n\"\"\"\n# Project set up \n\n\n## Training , Testing data split\n\nWe need a way to split the data into training and testing data . Training data is used for our machine learning models so that they can learn the right paramters for the task at hand.Testing data will be used to test how well our model can perform in data it hasn't seen before. In essence how well the model generalize to new data.\n\nNormally any machine learning engineer\/data scientist would use some sort of model valdation techinque . Typically it would be cross valdation that is usually [k fold](https:\/\/www.youtube.com\/watch?v=TIgfjmp-4BA).\n\nBut dealing with time seris data is different and shouldn't use a method that select training, validation, and testing data sets by selecting randomly selected samples of the data for each of these categories in a time-agnostic way\n\n\nReferences:\n\nhttps:\/\/towardsdatascience.com\/time-series-nested-cross-validation-76adba623eb9\nhttps:\/\/hub.packtpub.com\/cross-validation-strategies-for-time-series-forecasting-tutorial\/\nhttps:\/\/medium.com\/@samuel.monnier\/cross-validation-tools-for-time-series-ffa1a5a09bf9\n\"\"\"\n\"\"\"\n## Selecting a Performance Measure \nI'll be using the following three metrics to evaluate models:\n* Root Mean Squared Logarithmic Error(RMSLE)\n* Mean Square Error (MSE)\n* Mean Absolute Error (MAE)\n\"\"\"\n\"\"\"\n## Feature Engineering with Time Seris data\n\n\n**What's the purpose of feature engineering?**\nThe goal of feature engineering is to provide strong and ideally simple relationships between new input features and the output feature for the supervised learning algorithm to model.\n\nIn effect, we are are moving complexity.\n\nComplexity exists in the relationships between the input and output data. In the case of time series, there is no concept of input and output variables; we must invent these too and frame the supervised learning problem from scratch.\n\n\n\nDate Time Features: these are components of the time step itself for each observation.\nLag Features: these are values at prior time steps.\nWindow Features: these are a summary of values over a fixed window of prior time steps.\n\n\nFeature Engineering is different when you're are dealing with time seris data.Netherless we can still generate features that can prove indcative for our models . Such as indicating days of the week , the month that it happen and allso year . Deciding what features you want to generate will depend on the dataset and common knowledge is . It doesn't make sense if your data only happens in one year span to generate year as a feature or months but maybe on certain weekdays the event that you're trying to predict happens more often than the others \n\nSimilarly, we can extract a number of features from the date column. Here\u2019s a complete list of features that we can generate:\n![](https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2019\/11\/time-features.png)\n\n\n\n\n\"\"\"\ndf=pd.read_csv('..\/input\/covidglobalcompetition\/covid-global-forcast.csv',parse_dates=[\"Date\"])\ndf[\"Province\/State\"]=df[\"Province\/State\"].fillna(\"\")\ndf=df.sort_values(by=[\"Date\",\"Country\/Region\",\"Province\/State\"])\ndf[\"Location\"]=df[\"Country\/Region\"] +\"\/\"+ df[\"Province\/State\"]\nindex=pd.MultiIndex.from_frame(df[[\"Location\",\"Date\"]])\ndf=df.set_index(index,drop=False)\ndf=df.drop(columns=[\"Country\/Region\",\"Province\/State\",\"Lat\",\"Long\"])\n# Active Case = confirmed - deaths - recovered\ndf['Active'] = df['# ConfirmedCases'] - df['# Fatalities'] - df['# Recovered_cases']\n\ndf[\"Day\"]=df[\"Date\"].dt.day\ndf[\"Day of the week\"]= df[\"Date\"].dt.weekday\ndays =[\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \n                         \"Friday\", \"Saturday\", \"Sunday\"] \ndays_dict={x:days[x] for x in range(len(days))}\ndf[\"Day of the week\"]=df[\"Day of the week\"].map(days_dict)\npandemic_date=datetime.datetime.strptime(\"11 March 2020\",\"%d %B %Y\")\ndf[\"Days after\/before the pandemic\"]=df[\"Date\"] - pandemic_date\ndf.head(10)\n\n\"\"\"\n# Lag features\n\nThe simplest approach is to predict the value at the next time (t+1) given the value at the previous time (t-1). The supervised learning problem with shifted values looks as follows:\n\nThe Pandas library provides the shift() function to help create these shifted or lag features from a time series dataset. Shifting the dataset by 1 creates the t-1 column, adding a NaN (unknown) value for the first row. The time series dataset without a shift represents the t+1.\n\nshow exemples\n\nHere, we were able to generate lag one feature for our series. But why lag one? Why not five or seven? To answer this let us understand it better below.\n\nThe lag value we choose will depend on the correlation of individual values with its past values.\n\nIf the series has a weekly trend, which means the value last Monday can be used to predict the value for this Monday, you should create lag features for seven days. Getting the drift?\n\"\"\"\n\"\"\"\n## <a >Autocorrelation and Partial Autocorrelation<\/a>\n* Autocorrelation - The autocorrelation function (ACF) measures how a series is correlated with itself at different lags.\n* Partial Autocorrelation - The partial autocorrelation function can be interpreted as a regression of the series against its past lags.  The terms can be interpreted the same way as a standard  linear regression, that is the contribution of a change in that particular lag while holding others constant. \n\n*  As all lags are either close to 1 or at least greater than the confidence interval, they are statistically significant.\n\nSource: [Quora](https:\/\/www.quora.com\/What-is-the-difference-among-auto-correlation-partial-auto-correlation-and-inverse-auto-correlation-while-modelling-an-ARIMA-series)\n\n\n\"\"\"\n#https:\/\/machinelearningmastery.com\/gentle-introduction-autocorrelation-partial-autocorrelation\/\nfrom statsmodels.graphics.tsaplots import plot_acf,plot_pacf\nplot_acf(df[\"# Fatalities\"], lags=10)\nplot_pacf(df[\"# Fatalities\"], lags=10)\nplot_acf(df[\"# ConfirmedCases\"], lags=10)\nplot_pacf(df[\"# ConfirmedCases\"], lags=10)\ndf[\"Lag_1_fatalities\"]=df.groupby(level=0)[\"# Fatalities\"].shift(1)\ndf[\"Lag_1_confirmed_cases\"]=df.groupby(level=0)[\"# ConfirmedCases\"].shift(1)\ndf=df.dropna()\nfrom category_encoders.hashing import HashingEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\ny=df[\"# Fatalities\"].values\n\n\ndf=df.drop(columns=[\"# Fatalities\",\"Date\"])\n\n\nce_hash=HashingEncoder(cols = [\"Location\"])\ntransformer = ColumnTransformer(transformers=[('cat', OneHotEncoder(), [\"Day of the week\"]),(\"label\",ce_hash,[\"Location\"])])\nX=transformer.fit_transform(df)\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=21)\n\n\n\ndef RMSLE(predictions,actual_values):\n    # root mean squared logarithmic error.\n    number_of_predictions=np.shape(predictions)[0]\n    predictions=np.log(predictions+1)\n    actual_values=np.log(actual_values+1)\n    squared_differences=np.power(np.subtract(predictions,actual_values),2)\n    total_sum=np.sum(squared_differences)\n    avg_squared_diff=total_sum\/number_of_predictions\n    rmsle=np.sqrt(avg_squared_diff)\n    return rmsle\nfrom sklearn.linear_model import Lasso,Ridge\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import * \n\nmodels = []\nmodels.append(('LASSO', Lasso()))\nmodels.append(('DF', DecisionTreeRegressor()))\nmodels.append(('RF', RandomForestRegressor())) # Ensemble method - collection of many decision trees\nmodels.append(('SVR', SVR(gamma='auto'))) # kernel = linear\n\n# Evaluate each model in turn\nRMSLE_results = []\nMAE_results=[]\nMSE_results=[]\nnames = []\nfor name, model in models:\n    names.append(name)\n    model.fit(X_train,y_train)\n    predictions=model.predict(X_test)\n    RMSLE_results.append(RMSLE(predictions,y_test))\n    MAE_results.append(mean_absolute_error(predictions,y_test))\n    MSE_results.append(mean_squared_error(predictions,y_test))\nprint(\"Models Performance:\")\nfor name,rsmle,mae,mse in zip(names,RMSLE_results,MAE_results,MSE_results):\n    print(f\"Model Name:{name}\\n RMSLE:{rmsle}\\n MAE:{mae} \\n MSE:{mse}\\n\")\n\"\"\"\nhttps:\/\/pyflux.readthedocs.io\/en\/latest\/dyn_lin.html\nhttps:\/\/alkaline-ml.com\/pmdarima\/auto_examples\/index.html#id1\nhttps:\/\/www.quora.com\/What-is-the-most-useful-Python-library-for-time-series-and-forecasting\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '578c6c4a770d5c'}"}
{"id":"1494","text":"\"\"\"\n### Problem Description : \n   A retail company \u201cABC Private Limited\u201d wants to understand the customer purchase behaviour(specifically, purchase amount) \nagainst various products of different categories. They have shared purchase summary of various customers for selected \nhigh volume products from last month.\n\n   The data set also contains customer demographics (age, gender, marital status, city_type, stay_in_current_city), \nproduct details (product_id and product category) and Total purchase_amount from last month.\n\n   Now, they want to build a model to predict the purchase amount of customer against various products which will help \nthem to create personalized offer for customers against different products.\n\"\"\"\n\"\"\"\n\nMore data beats clever algorithms, but better data beats more data\n-Peter Norvig\n\"\"\"\n\"\"\"\n#### Goal\n    Our Goal is to predict the purchase amount a client is expected to spend on this day.\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\ntrain = pd.read_csv(\"\/kaggle\/input\/black-friday-predictions\/train.csv\")\ntest = pd.read_csv(\"\/kaggle\/input\/black-friday-predictions\/test.csv\")\nprint(train.shape)\nprint(test.shape)\n\ntrain.head()\n\"\"\"\n#### Observations\n- Occupation , Product_Category_1 , Product_Category_2, Product_Category_3 values are masked\n- No information about stores\n- Few information related to products which are product id and the product that falls under different product category\n- We have some information related to the Customer such as Age,Gender,Occupation and Maritial_status\n\n\"\"\"\n\"\"\"\n#### Assumptions\n- We make some assumptions before start,We'll analyse the given features that influence amount spend by customer\n- <b>Occupation<\/b> - People with higher income spend more \n- <b>Marital_Status<\/b> - People who are single spend more\n- <b>City_Category<\/b> - People from urban city or top tier city spend more because of their higher income level\n- <b>Age<\/b> - People who are below 30 years spend more on gadgets and other electronics stuff\n\"\"\"\nsns.distplot(train['Purchase'])\nprint(\"Skewness : {}\".format(train['Purchase'].skew()))\nprint(\"Kurtosis : {}\".format(train.Purchase.kurt()))\n# The distribution is moderately skewed\nprint(train['Purchase'].describe())\nprint(train[train['Purchase'] == train['Purchase'].min()].shape[0])\nprint(train[train['Purchase'] == train['Purchase'].max()].shape[0])\n\"\"\"\nObservations : \n* Minimum price of the Item is 12 and max to 23961.\n* Median value (8047) is lower than mean value (9263) \n\n\n\"\"\"\n\"\"\"\n### Data Cleaning\n\"\"\"\ntrain.isnull().sum()\ntest.isnull().sum()\n# Let's analyse the missing value\n# Only this predictors Product_Category_2 & Product_Category_3 has missing values this might be due to that products did not fall under these two categories\ntrain[train['Product_Category_2'].isnull()]['Product_ID'].value_counts()\n# We analyse firt two top products\nprint(train[train['Product_ID']=='P00255842']['Product_Category_2'].value_counts(dropna=False))\nprint(train[train['Product_ID']=='P00278642']['Product_Category_2'].value_counts(dropna=False))\ntrain[train['Product_Category_3'].isnull()]['Product_ID'].value_counts()\n# We analyse firt two top products\nprint(train[train['Product_ID']=='P00265242']['Product_Category_3'].value_counts(dropna=False))\nprint(train[train['Product_ID']=='P00058042']['Product_Category_3'].value_counts(dropna=False))\n# Our guess is correct that product doesn't fall under these categories, so it is safe to fill 0\ntrain['Product_Category_2'].fillna(0,inplace=True)\ntest['Product_Category_2'].fillna(0,inplace=True)\ntrain['Product_Category_3'].fillna(0,inplace=True)\ntest['Product_Category_3'].fillna(0,inplace=True)\n# we remove '+' character\ntrain['Stay_In_Current_City_Years'] = train['Stay_In_Current_City_Years'].replace(\"4+\",\"4\")\ntest['Stay_In_Current_City_Years'] = test['Stay_In_Current_City_Years'].replace(\"4+\",\"4\")\n\ntrain['Age'] = train['Age'].replace('55+','56-100')\ntest['Age'] = test['Age'].replace('55+','56-100')\n\"\"\"\n#### Feature Transformation\n\"\"\"\n# Product ID has so many unique values that won't help us but there is a pattern on product formation. We will split first 4 \n# characters this might be some sellers name or for some identification they kept on it\ntrain['Product_Name'] = train['Product_ID'].str.slice(0,4)\ntest['Product_Name'] = test['Product_ID'].str.slice(0,4)\nsns.countplot(train['Product_Name'])\ntrain.groupby('Product_Name')['Purchase'].describe().sort_values('count',ascending=False)\n\"\"\"\n#### Feature Creation\n\"\"\"\n\"\"\"\n##### We'll check purchase of the items based on the available category. My assumption is that if an item available in all the category, there are very high chances that the item is more visible to the user. Let's analys this fact\n\"\"\"\n# Items which are only fall under Product_Category_1 list\npd_cat_1_purchase = train[(train['Product_Category_2'] == 0) & (train['Product_Category_3']==0)]['Purchase']\nprint(\"Total no. of Sold Items in Product_Category_1 {}\".format(pd_cat_1_purchase.shape[0]))\nprint(\"Mean value {}\".format(pd_cat_1_purchase.mean()))\nprint(\"Median value {}\".format(pd_cat_1_purchase.median()))\n\n\n# Items which are available in any two category\npd_cat_2_purchase = train[np.logical_xor(train['Product_Category_2'],train['Product_Category_3'])]['Purchase']\nprint(\"Total no. of Sold Items in Product_Category_1 & any one of the other two category {}\".format(pd_cat_2_purchase.shape[0]))\nprint(\"Mean value is {}\".format(pd_cat_2_purchase.mean()))\nprint(\"Median value is {}\".format(pd_cat_2_purchase.median()))\n# Items which are available in all category\npd_cat_all_purchase = train[(train['Product_Category_2'] != 0) & (train['Product_Category_3']!=0)]['Purchase']\nprint(\"Total no. of Sold Items in all Category {}\".format(pd_cat_all_purchase.shape[0]))\nprint(\"Mean value is {}\".format(pd_cat_all_purchase.mean()))\nprint(\"Median value is {}\".format(pd_cat_all_purchase.median()))\n\"\"\"\nyou can see that in all category split where the median is greater than mean. That means most of the richer people purchased the product which comes falls all category. So We'll create a new feature for category split and assign a weight to that. \n\"\"\"\ntrain['Category_Weight'] = 0\ntrain.loc[pd_cat_1_purchase.index,'Category_Weight'] = 1\ntrain.loc[pd_cat_2_purchase.index,'Category_Weight'] = 2\ntrain.loc[pd_cat_all_purchase.index,'Category_Weight'] = 3\n\n# Each user has purchased atleast 6 items.\n# Based on the count  we'll create a new variable called Frequent_Buyers which holds 1 for Users who purchased more than 100 items\n# and 0 for less than 100 items\ntrain['Frequent_Buyers'] = train.groupby('User_ID')['User_ID'].transform(lambda x : 1 if x.count() > 100 else 0)\ntest['Frequent_Buyers'] = test.groupby('User_ID')['User_ID'].transform(lambda x : 1 if x.count() > 100 else 0)\ntrain.drop(['Product_ID','User_ID'],inplace=True,axis=1)\ntest.drop(['Product_ID','User_ID'],inplace=True,axis=1)\ntrain['Age'].value_counts()\nsns.barplot(train['Age'],train['Age'].value_counts().values)\n\"\"\"\n* teenagers or student shows more interest than other ages\n* 72% of \"0-17\" doing the same occupation(probably they are student)\n\"\"\"\n# We'll create a new feature for Student\ntrain['IsStudent'] = 1 * (train['Age']=='0-17')\ntest['IsStudent'] = 1 * (test['Age']=='0-17')\n# Based on our income we spend more, so we'll order occupation by mean value of the purchase and we use the same order for test data also.\norder_occupation_by_purchase = train.groupby('Occupation')['Purchase'].describe().sort_values('mean',ascending=False)['mean'].index\ntrain['Occupation']\nmap_occupation = {k: v for v, k in enumerate(order_occupation_by_purchase)}\nmap_occupation\ntrain['Occupation'] = train['Occupation'].apply(lambda x: map_occupation[x])\ntest['Occupation'] = test['Occupation'].apply(lambda x: map_occupation[x])\n\"\"\"\n#### Extraordinary Data Analysis\n\"\"\"\ncorrIndex = train.corr().nlargest(10,'Purchase')['Purchase'].index\ncorr = train[corrIndex].corr()\nplt.figure(figsize=(16,8))\nax = sns.heatmap(corr,annot=True,cmap=\"YlGnBu\")\nbottom, top = ax.get_ylim()\nax.set_ylim(bottom + 0.5, top - 0.5)\nplt.show()\n# There is no satisifactory correlation feature so we will avoid using Linear model.\nf,ax = plt.subplots(1,2,figsize=(10,6))\nsns.countplot(train['Gender'],ax=ax[0])\nsns.barplot('Gender','Purchase',data=train,ax=ax[1])\n\"\"\"\nMen was the most shown interest on black friday sales. On plot 2, Eventhough women are less in count but they spent almost equal money spent by men\n\"\"\"\nf,ax = plt.subplots(1,2,figsize=(10,6))\nsns.countplot(train['City_Category'],ax=ax[0])\nsns.barplot('City_Category','Purchase',data=train,ax=ax[1])\n\n# Customer from city B has purchased more items.\n# Customer from city C has spent higher Amount Eventhough B has purchased more items.","meta":"{'source': 'AI4Code', 'id': '02c7e612bbc663'}"}
{"id":"126841","text":"# 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 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\n\"\"\"\n### Here we are going to do Deep learning for FashionMnist dataset with Pytorch.\n## Let's import the required libraries\n\"\"\"\nimport torch\nimport torchvision\nfrom torchvision.utils import make_grid\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torchvision.datasets import FashionMNIST\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data import random_split\nfrom torchvision.transforms import ToTensor\nimport torch.nn as nn\nimport torch.nn.functional as F\n%matplotlib inline\n\"\"\"\n### Downloading dataset from torchvision API and transform it to pytorch tensor[](http:\/\/)\n\"\"\"\ndataset = FashionMNIST(root='data\/', download=True, transform = ToTensor())\ntest = FashionMNIST(root='data\/', train=False, transform = ToTensor())\nprint(len(dataset))\nval_size = 10000\ntrain_size = 50000\ntrain_ds, valid_ds = random_split(dataset, [train_size, val_size])\nprint(len(train_ds), len(valid_ds))\n\"\"\"\n### Loading data for training using Dataloader and Also plotting the data using make_grid function and also using permute to rearrange the images shape. Because pytorch image shape is like(1, 28, 28) but for matplot lib it expects the shape to be (28,28,1)\n\"\"\"\nbatch_size = 128\ntrain_dl = DataLoader(train_ds, batch_size, shuffle=True, num_workers=4, pin_memory=True)\nvalid_dl = DataLoader(valid_ds, batch_size*2, shuffle=False, num_workers=4, pin_memory=True)\ntest_dl = DataLoader(test, batch_size*2, num_workers=4, pin_memory=True)\nfor images,_ in train_dl:\n    print(\"image_size: \", images.shape)\n    plt.figure(figsize=(16,8))\n    plt.axis('off')\n    plt.imshow(make_grid(images, nrow=16).permute(1,2,0))\n    break\n    \n\"\"\"\n## Defining accuracy\n\"\"\"\ndef accuracy(output, labels):\n    _, preds = torch.max(output, dim=1)\n    return torch.tensor(torch.sum(preds==labels).item()\/ len(preds))\n    \nclass MNISTModel(nn.Module):\n    def __init__(self, in_size, out_size):\n        super().__init__()\n        ## Hidden Layer\n        self.linear1 = nn.Linear(in_size, 16)\n        self.linear2 = nn.Linear(16, 32)\n        self.linear3 = nn.Linear(32, out_size)\n        \n    def forward(self, xb):\n        out = xb.view(xb.size(0), -1)\n        ## First layer\n        out = self.linear1(out)\n        out = F.relu(out)\n        ## Second Layer\n        out = self.linear2(out)\n        out = F.relu(out)\n        ## Third Layer\n        out = self.linear3(out)\n        out = F.relu(out)\n        return out\n    \n    def training_step(self, batch):\n        image, label = batch\n        out = self(image)\n        loss = F.cross_entropy(out, label)\n        return loss\n    \n    def validation_step(self, batch):\n        image, label = batch\n        out = self(image)\n        loss = F.cross_entropy(out, label)\n        acc = accuracy(out, label)\n        return {'val_loss': loss, 'val_acc': acc}\n    \n    def validation_epoch_end(self, outputs):\n        losses = [loss['val_loss'] for loss in outputs]\n        epoch_loss = torch.stack(losses).mean()\n        batch_accs = [x['val_acc'] for x in outputs]\n        epoch_acc = torch.stack(batch_accs).mean()\n        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}\n    \n    def epoch_end(self, epoch, result):\n        print(\"Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}\".format(epoch, result['val_loss'], result['val_acc']))\n\"\"\"\n## Connecting to GPU\n\"\"\"\ntorch.cuda.is_available()\ndef find_device():\n    if torch.cuda.is_available():\n        return torch.device('cuda')\n    else:\n        return torch.device('cpu')\n\ndevice = find_device()\ndevice\n\"\"\"\nConverting data to device\n\"\"\"\ndef to_device(data, device):\n    if isinstance(data, (tuple, list)):\n        return [to_device(x, device) for x in data]\n    return data.to(device, non_blocking=True)\nclass DeviceLoader():\n    def __init__(self, dl, device):\n        self.dl = dl\n        self.device = device\n        \n    def __iter__(self):\n        for b in self.dl:\n            yield to_device(b, self.device)\n    \n    def __len__(self):\n        return len(self.dl)\ntrain_loader = DeviceLoader(train_dl, device)\nvalid_loader = DeviceLoader(valid_dl, device)\ntest_loader = DeviceLoader(test_dl, device)\n\"\"\"\n## Train Model\n\"\"\"\ndef evaluate(model, val_loader):\n    outputs = [model.validation_step(batch) for batch in val_loader]\n    return model.validation_epoch_end(outputs)\n\ndef fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):\n    history = []\n    optimizer = opt_func(model.parameters(), lr)\n    for epoch in range(epochs):\n        # Training Phase \n        for batch in train_loader:\n            loss = model.training_step(batch)\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n        # Validation phase\n        result = evaluate(model, val_loader)\n        model.epoch_end(epoch, result)\n        history.append(result)\n    return history\ninput_size = 784\nnum_classes = 10\nmodel = MNISTModel(input_size, out_size=num_classes)\nto_device(model, device)\nhistory = [evaluate(model, valid_loader)]\nhistory\n\"\"\"\n# Fitting model\n\"\"\"\nhistory += fit(5, 0.5, model, train_loader, valid_loader)\n\nlosses = [x['val_loss'] for x in history]\nplt.plot(losses, '-x')\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.title('Loss vs. No. of epochs');\n\"\"\"\n# Prediction on Samples\n\"\"\"\ndef predict_image(img, model):\n    xb = to_device(img.unsqueeze(0), device)\n    yb = model(xb)\n    _, preds  = torch.max(yb, dim=1)\n    return preds[0].item()\nimg, label = test[0]\nplt.imshow(img[0], cmap='gray')\nprint('Label:', dataset.classes[label], ', Predicted:', dataset.classes[predict_image(img, model)])\nevaluate(model, test_loader)\n\nsaved_weights_fname='fashion-feedforward.pth'\n\ntorch.save(model.state_dict(), saved_weights_fname)\n","meta":"{'source': 'AI4Code', 'id': 'e93dff927f55bc'}"}
{"id":"74395","text":"\"\"\"\n# About H2O\nMachine Learning PLatform used in here is H2O, which is a Fast, Scalable, Open source application for machine\/deep learning. \nBig names such as PayPal, Booking.com, Cisco are using H2O as the ML platform.\nThe speciality of h2o is that it is using in-memory compression to handles billions of data rows in memory, even in a small cluster.\nIt is easy to use APIs with R, Python, Scala, Java, JSON as well as a built in web interface, Flow\nYou can find more information here: https:\/\/www.h2o.ai\n\n\"\"\"\n    import h2o\n    from IPython import get_ipython\n    import jupyter\n    import matplotlib.pyplot as plt\n    from pylab import rcParams\n    import numpy as np # linear algebra\n    import pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n    import os\n    from h2o.estimators.deeplearning import H2OAutoEncoderEstimator, H2ODeepLearningEstimator\n\n    h2o.init(max_mem_size = 2) # initializing h2o server\n    h2o.remove_all()\n\"\"\"\n# Loading the Dataset\nH2O also have a frame like pandas. So most of the data handling parts can be done using H2OFrame instead of DataFrame\n\"\"\"\n    creditData = pd.read_csv(\"..\/input\/creditcard.csv\") # read data using pandas\n    # creditData_df = h2o.import_file(r\"File_Path\\creditcard.csv\") # H2O method\n    creditData.describe()\n\"\"\"\n## About the Dataset\nThe Dataset contains 284,807 transactions in total. From that 492 are fraud transactions. So the data itself is highly imbalanced. It contains only numeric input variable. The traget variable is 'Class'\n\"\"\"\n    print(\"Few Entries: \")\n    print(creditData.head())\n    print(\"Dataset Shape: \", creditData.shape)\n    print(\"Maximum Transaction Value: \", np.max(creditData.Amount))\n    print(\"Minimum Transaction Value: \", np.min(creditData.Amount))\n    # Turns python pandas frame into an H2OFrame\n    creditData_h2o  = h2o.H2OFrame(creditData)\n    # check if there is any null values\n    # creditData.isnull().sum() # pandas method\n    creditData_h2o.na_omit() # h2o method\n    creditData_h2o.nacnt() # no missing values found\n\"\"\"\n# Data Visualization\n\"\"\"\n        # Let's plot the Transaction class against the Frequency\n        labels = ['normal','fraud']\n        classes = pd.value_counts(creditData['Class'], sort = True)\n        classes.plot(kind = 'bar', rot=0)\n        plt.title(\"Transaction class distribution\")\n        plt.xticks(range(2), labels)\n        plt.xlabel(\"Class\")\n        plt.ylabel(\"Frequency\")\n    fraud = creditData[creditData.Class == 1]\n    normal = creditData[creditData.Class == 0]\n    # Amount vs Class\n    f, (ax1, ax2) = plt.subplots(2,1,sharex=True)\n    f.suptitle('Amount per transaction by class')\n\n    ax1.hist(fraud.Amount, bins = 50)\n    ax1.set_title('Fraud List')\n\n    ax2.hist(normal.Amount, bins = 50)\n    ax2.set_title('Normal')\n\n    plt.xlabel('Amount')\n    plt.ylabel('Number of Transactions')\n    plt.xlim((0, 10000))\n    plt.yscale('log')\n    plt.show()\n    # time vs Amount\n    f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)\n    f.suptitle('Time of transaction vs Amount by class')\n\n    ax1.scatter(fraud.Time, fraud.Amount)\n    ax1.set_title('Fraud List')\n\n    ax2.scatter(normal.Time, normal.Amount)\n    ax2.set_title('Normal')\n\n    plt.xlabel('Time (in seconds)')\n    plt.ylabel('Amount')\n    plt.show()\n    #plotting the dataset considering the class\n    color = {1:'red', 0:'yellow'}\n    fraudlist = creditData[creditData.Class == 1]\n    normal = creditData[creditData.Class == 0]\n    fig,axes = plt.subplots(1,2)\n\n    axes[0].scatter(list(range(1,fraudlist.shape[0] + 1)), fraudlist.Amount,color='red')\n    axes[1].scatter(list(range(1, normal.shape[0] + 1)), normal.Amount,color='yellow')\n    plt.show()\n\"\"\"\nThe *Time* variable is not giving an impact on the model prediction,. This can be figure out from data visualization. \nBefore moving on to the trainig part, we need to figure out which variables are important and which are not. \nSo we can drop the unwanted variables.\n\"\"\"\n    features= creditData_h2o.drop(['Time'], axis=1)\n\"\"\"\n# Split the Frame\n\"\"\"\n    # 80% for the training set and 20% for the testing set\n    train, test = features.split_frame([0.8])\n    print(train.shape)\n    print(test.shape)\n    #train.describe()\n    #test.describe()\n    train_df = train.as_data_frame()\n    test_df = test.as_data_frame()\n\n    train_df = train_df[train_df['Class'] == 0]\n    train_df = train_df.drop(['Class'], axis=1)\n\n    Y_test_df = test_df['Class']\n\n    test_df = test_df.drop(['Class'], axis=1)\n\n    train_df.shape\n    train_h2o = h2o.H2OFrame(train_df) # converting to h2o frame\n    test_h2o = h2o.H2OFrame(test_df)\n    x = train_h2o.columns\n\"\"\"\n# Anomaly Detection\nI used an anomaly detection technique for the dataset. \nAnomaly detection is a technique to identify unusual patterns that do not confirm to the expected behaviors. Which is called outliers. \nIt has many applications in business from fraud detection in credit card transactions to fault detection in operating environments.\nMachine learning approaches for Anomaly detection;\n1.     K-Nearest Neighbour\n2.     Autoencoders - Deep neural network\n3.     K-means\n4.     Support Vector Machine\n5.     Naive Bayes\n\n\"\"\"\n\"\"\"\n# Autoencoders\nSo as the algorithm I chose **Autoencoders**, which is a deep learning, unsupervised ML algorithm. \n\"Autoencoding\" is a data compression algorithm, which takes the input and going through a compressed representation and gives the reconstructed output. \n\n\"\"\"\n\"\"\"\nwhen  building the model, \n4 fully connected hidden layers were chosen with, [14,7,7,14] number of nodes for each layer.\nFirst two for the encoder and last two for the decoder.\n\"\"\"\n    anomaly_model = H2ODeepLearningEstimator(activation = \"Tanh\",\n                                   hidden = [14,7,7,14],\n                                   epochs = 100,\n                                   standardize = True,\n                                    stopping_metric = 'MSE', # MSE for autoencoders\n                                    loss = 'automatic',\n                                    train_samples_per_iteration = 32,\n                                    shuffle_training_data = True,     \n                                   autoencoder = True,\n                                   l1 = 10e-5)\n    anomaly_model.train(x=x, training_frame = train_h2o)\n\"\"\"\n## Variable Importance\nIn H2O there is a special way of analysing the variables which gave more impact on the model.\n\"\"\"\n    anomaly_model._model_json['output']['variable_importances'].as_data_frame()\n    # plotting the variable importance\n    rcParams['figure.figsize'] = 14, 8\n    #plt.rcdefaults()\n    fig, ax = plt.subplots()\n\n    variables = anomaly_model._model_json['output']['variable_importances']['variable']\n    var = variables[0:15]\n    y_pos = np.arange(len(var))\n\n    scaled_importance = anomaly_model._model_json['output']['variable_importances']['scaled_importance']\n    sc = scaled_importance[0:15]\n\n    ax.barh(y_pos, sc, align='center', color='green', ecolor='black')\n    ax.set_yticks(y_pos)\n    ax.set_yticklabels(variables)\n    ax.invert_yaxis()\n    ax.set_xlabel('Scaled Importance')\n    ax.set_title('Variable Importance')\n    plt.show()\n    # plotting the loss\n    scoring_history = anomaly_model.score_history()\n    %matplotlib inline\n    rcParams['figure.figsize'] = 14, 8\n    plt.plot(scoring_history['training_mse'])\n    #plt.plot(scoring_history['validation_mse'])\n    plt.title('model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n\"\"\"\n## Evaluating the Testing set\nTesting set has both normal and fraud transactions in it.\nFrom this training method, The model will learn to identify the pattern of the input data.\n If an anomalous test point does not match the learned pattern, the autoencoder will likely have a high error rate in reconstructing this data, indicating anomalous data.\nSo that we can identify the anomalies of the data.\nTo calculate the error, it uses **Mean Squared Error**(MSE)\n\"\"\"\n    test_rec_error = anomaly_model.anomaly(test_h2o) \n    # anomaly is a H2O function which calculates the error for the dataset\n    test_rec_error_df = test_rec_error.as_data_frame() # converting to pandas dataframe\n\n    # plotting the testing dataset against the error\n    test_rec_error_df['id']=test_rec_error_df.index\n    rcParams['figure.figsize'] = 14, 8\n    test_rec_error_df.plot(kind=\"scatter\", x='id', y=\"Reconstruction.MSE\")\n    plt.show()\n    # predicting the class for the testing dataset\n    predictions = anomaly_model.predict(test_h2o)\n\n    error_df = pd.DataFrame({'reconstruction_error': test_rec_error_df['Reconstruction.MSE'],\n                            'true_class': Y_test_df})\n    error_df.describe()\n    # reconstruction error for the normal transactions in the testing dataset\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    rcParams['figure.figsize'] = 14, 8\n    normal_error_df = error_df[(error_df['true_class']== 0) & (error_df['reconstruction_error'] < 10)]\n    _ = ax.hist(normal_error_df.reconstruction_error.values, bins=10)\n    # reconstruction error for the fraud transactions in the testing dataset\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    rcParams['figure.figsize'] = 14, 8\n    fraud_error_df = error_df[error_df['true_class'] == 1]\n    _ = ax.hist(fraud_error_df.reconstruction_error.values, bins=10)\n\"\"\"\n### ROC Curve\n\"\"\"\n    from sklearn.metrics import (confusion_matrix, precision_recall_curve, auc,\n                                 roc_curve, recall_score, classification_report, f1_score,\n                                 precision_recall_fscore_support)\n    fpr, tpr, thresholds = roc_curve(error_df.true_class, error_df.reconstruction_error)\n    roc_auc = auc(fpr, tpr)\n\n    plt.title('Receiver Operating Characteristic')\n    plt.plot(fpr, tpr, label='AUC = %0.4f'% roc_auc)\n    plt.legend(loc='lower right')\n    plt.plot([0,1],[0,1],'r--')\n    plt.xlim([-0.001, 1])\n    plt.ylim([0, 1.001])\n    plt.ylabel('True Positive Rate')\n    plt.xlabel('False Positive Rate')\n    plt.show();\n\"\"\"\n### Precision and Recall\nSince the data is highly unbalanced, it cannot be measured only by using accuracy.\nPrecision vs Recall was chosen as the matrix for the classification task.\n\n**Precision**: Measuring the relevancy of obtained results. \n[ True positives \/ (True positives + False positives)]\n\n**Recall**: Measuring how many relevant results are returned.\n[ True positives \/ (True positives + False negatives)]\n\n\n\n\n\n\"\"\"\n\"\"\"\n**True Positives** - Number of actual frauds predicted as frauds\n\n**False Positives** - Number of non-frauds predicted as frauds\n\n**False Negatives** - Number of frauds predicted as non-frauds.\n\n\"\"\"\n    precision, recall, th = precision_recall_curve(error_df.true_class, error_df.reconstruction_error)\n    plt.plot(recall, precision, 'b', label='Precision-Recall curve')\n    plt.title('Recall vs Precision')\n    plt.xlabel('Recall')\n    plt.ylabel('Precision')\n    plt.show()\n\"\"\"\nWe need to find a better threshold that can seperate the anomalies from normals. This can be done by getting the intersection of the **Precision\/Recall vs Threshold** graph\n\"\"\"\n    plt.plot(th, precision[1:], label=\"Precision\",linewidth=5)\n    plt.plot(th, recall[1:], label=\"Recall\",linewidth=5)\n    plt.title('Precision and recall for different threshold values')\n    plt.xlabel('Threshold')\n    plt.ylabel('Precision\/Recall')\n    plt.legend()\n    plt.show()\n    # plot the testing set with the threshold\n    threshold = 0.01\n    groups = error_df.groupby('true_class')\n    fig, ax = plt.subplots()\n\n    for name, group in groups:\n        ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='',\n                label= \"Fraud\" if name == 1 else \"Normal\")\n    ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors=\"r\", zorder=100, label='Threshold')\n    ax.legend()\n    plt.title(\"Reconstruction error for different classes\")\n    plt.ylabel(\"Reconstruction error\")\n    plt.xlabel(\"Data point index\")\n    plt.show();\n\"\"\"\n### Confusion Matrix\n\"\"\"\n    import seaborn as sns\n    LABELS = ['Normal', 'Fraud']\n    y_pred = [1 if e > threshold else 0 for e in error_df.reconstruction_error.values]\n    conf_matrix = confusion_matrix(error_df.true_class, y_pred)\n    plt.figure(figsize=(12, 12))\n    sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt=\"d\");\n    plt.title(\"Confusion matrix\")\n    plt.ylabel('True class')\n    plt.xlabel('Predicted class')\n    plt.show()\n\n\"\"\"\n### Classification Report\n      \n\"\"\"\n    csr = classification_report(error_df.true_class, y_pred)\n    print(csr)","meta":"{'source': 'AI4Code', 'id': '88d612b5d09e0f'}"}
{"id":"39953","text":"\"\"\"\n# **Project Objective and Brief**\n\n## *In this project, rule-based and Deep-Learning algorithms are used with an aim to first appropriately detect different type of emotions contained in a collection of Tweets and then accurately predict the overall emotions of the Tweets is done.*\n\"\"\"\n\"\"\"\n## **Preprocessor is a preprocessing library used for tweet data written in Python.While building Machine Learning systems based on tweet data, a preprocessing is required. This library makes it easy to clean, parse or tokenize the tweets.The same is imported here.** \n\"\"\"\n!pip install tweet-preprocessor 2>\/dev\/null 1>\/dev\/null\n\"\"\"\n## **Importing Libraries**\n\"\"\"\nimport preprocessor as pcr\nimport numpy as np \nimport pandas as pd \nimport emoji\nimport keras\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers.recurrent import LSTM\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.embeddings import Embedding\nfrom sklearn import preprocessing,  model_selection\nfrom keras.preprocessing import sequence, text\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nimport plotly.express as px\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tokenizers import Tokenizer, models \nfrom tensorflow.keras.layers import SpatialDropout1D\n\"\"\"\n# **Data preparation**\n\"\"\"\ndf_data_1 = pd.read_csv(\"..\/input\/tweetscsv\/Tweets.csv\")\ndf_data_1.head()\ndf_data = df_data_1[[\"tweet_id\",\"airline_sentiment\",\"text\"]]\ndf_data.head()\n\"\"\"\n#  **Correcting Spelling of data**\n\"\"\"\ndata_spell = pd.read_csv(\"..\/input\/spelling\/aspell.txt\",sep=\":\",names=[\"correction\",\"misspell\"])\ndata_spell.misspell = data_spell.misspell.str.strip()\ndata_spell.misspell = data_spell.misspell.str.split(\" \")\ndata_spell = data_spell.explode(\"misspell\").reset_index(drop=True)\ndata_spell.drop_duplicates(\"misspell\",inplace=True)\nmiss_corr = dict(zip(data_spell.misspell, data_spell.correction))\n\n#Sample of the dict\n{v:miss_corr[v] for v in [list(miss_corr.keys())[k] for k in range(20)]}\ndef correct_spell(v):\n    for a in v.split(): \n        if a in miss_corr.keys(): \n            v = v.replace(a, miss_corr[a]) \n    return v\n\ndf_data[\"clean_content\"] = df_data.text.apply(lambda a : correct_spell(a))\n\"\"\"\n# **Using a Python library for expanding and creating common English contractions in text**\n\"\"\"\ncontract = pd.read_csv(\"..\/input\/contractions\/contractions.csv\")\ncont_dict = dict(zip(contract.Contraction, contract.Meaning))\ndef contract_to_meaning(v): \n  \n    for a in v.split(): \n        if a in cont_dict.keys(): \n            v = v.replace(a, cont_dict[a]) \n    return v\n\ndf_data.clean_content = df_data.clean_content.apply(lambda a : contract_to_meaning(a))\n\"\"\"\n# **Removal of URLs and Mentions from dataset**\n\"\"\"\npcr.set_options(pcr.OPT.MENTION, pcr.OPT.URL)\npcr.clean(\"hello guys @alx #sport\ud83d\udd25 1245 https:\/\/github.com\/s\/preprocessor\")\ndf_data[\"clean_content\"]=df_data.text.apply(lambda a : pcr.clean(a))\n\"\"\"\n# **Removal of Punctuations and Emojis from dataset**\n\"\"\"\ndef punct(v): \n  \n    punct = '''()-[]{};:'\"\\,<>.\/@#$%^&_~'''\n  \n    for a in v.lower(): \n        if a in punct: \n            v = v.replace(a, \" \") \n    return v\n\npunct(\"test @ #ldfldlf??? !! \")\ndf_data.clean_content = df_data.clean_content.apply(lambda a : ' '.join(punct(emoji.demojize(a)).split()))\ndef text_cleaning(v):\n    v = correct_spell(v)\n    v = contract_to_meaning(v)\n    v = pcr.clean(v)\n    v = ' '.join(punct(emoji.demojize(v)).split())\n    \n    return v\ntext_cleaning(\"isn't \ud83d\udca1 adultry @ttt good bad ... ! ? \")\n\"\"\"\n# **Removing empty comments from dataset**\n\"\"\"\ndf_data = df_data[df_data.clean_content != \"\"]\ndf_data.airline_sentiment.value_counts()\n\"\"\"\n# **Data Modeling**\n\"\"\"\n\"\"\"\n## **Encoding the data and train, test and split it**\n\"\"\"\nid_for_sentiment = {\"neutral\":0, \"negative\":1,\"positive\":2}\ndf_data[\"sentiment_id\"] = df_data['airline_sentiment'].map(id_for_sentiment)\ndf_data.head()\nencoding_label = LabelEncoder()\nencoding_integer = encoding_label.fit_transform(df_data.sentiment_id)\n\nencoding_onehot = OneHotEncoder(sparse=False)\nencoding_integer = encoding_integer.reshape(len(encoding_integer), 1)\nY = encoding_onehot.fit_transform(encoding_integer)\nX_train, X_test, y_train, y_test = train_test_split(df_data.clean_content,Y, random_state=1995, test_size=0.2, shuffle=True)\n\"\"\"\n# **LSTM: Long short-term memory** \n\n### **It is an artificial recurrent neural network (RNN) architecture used in the field of deep learning.**\n\"\"\"\n# using keras tokenizer here\ntkn = text.Tokenizer(num_words=None)\nmaximum_length = 160\nEpoch = 15\ntkn.fit_on_texts(list(X_train) + list(X_test))\nX_train_pad = sequence.pad_sequences(tkn.texts_to_sequences(X_train), maxlen=maximum_length)\nX_test_pad = sequence.pad_sequences(tkn.texts_to_sequences(X_test), maxlen=maximum_length)\nt_idx = tkn.word_index\nembedding_dimension = 160\nlstm_out = 250\n\nmodel_sql = Sequential()\nmodel_sql.add(Embedding(len(t_idx) +1 , embedding_dimension,input_length = X_test_pad.shape[1]))\nmodel_sql.add(SpatialDropout1D(0.2))\nmodel_sql.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))\nmodel_sql.add(keras.layers.core.Dense(3, activation='softmax'))\n#adam rmsprop \nmodel_sql.compile(loss = \"categorical_crossentropy\", optimizer='adam',metrics = ['accuracy'])\nprint(model_sql.summary())\nsize_of_batch = 32\n\"\"\"\n# **LSTM Model**\n\"\"\"\nmodel_sql.fit(X_train_pad, y_train, epochs = Epoch, batch_size=size_of_batch,validation_data=(X_test_pad, y_test))\ndef get_emotion(model_sql,text_1):\n    text_1 = text_cleaning(text_1)\n    #tokenize\n    tweet = tkn.texts_to_sequences([text_1])\n    tweet = sequence.pad_sequences(tweet, maxlen=maximum_length, dtype='int32')\n    emotion = model_sql.predict(tweet,batch_size=1,verbose = 2)\n    emo = np.round(np.dot(emotion,100).tolist(),0)[0]\n    rslt = pd.DataFrame([id_for_sentiment.keys(),emo]).T\n    rslt.columns = [\"sentiment\",\"percentage\"]\n    rslt=rslt[rslt.percentage !=0]\n    return rslt\ndef result_plotting(df):\n    #colors=['#D50000','#000000','#008EF8','#F5B27B','#EDECEC','#D84A09','#019BBD','#FFD000','#7800A0','#098F45','#807C7C','#85DDE9','#F55E10']\n    #fig = go.Figure(data=[go.Pie(labels=df.sentiment,values=df.percentage, hole=.3,textinfo='percent',hoverinfo='percent+label',marker=dict(colors=colors, line=dict(color='#000000', width=2)))])\n    #fig.show()\n    clrs={'neutral':'rgb(213,0,0)','negative':'rgb(0,0,0)',\n                    'positive':'rgb(0,142,248)'}\n    col={}\n    for i in rslt.sentiment.to_list():\n        col[i]=clrs[i]\n    figure = px.pie(df, values='percentage', names='sentiment',color='sentiment',color_discrete_map=col,hole=0.3)\n    figure.show()\n\"\"\"\n# **Result of LSTM**\n\"\"\"\n\"\"\"\n### Paragraph-1\n\"\"\"\nrslt =get_emotion(model_sql,\"Had an absolutely brilliant day \u00f0\u0178\u02dc\u0081 loved seeing an old friend and reminiscing\")\nresult_plotting(rslt)\n\"\"\"\n# **Result of LSTM**\n\"\"\"\n\"\"\"\n### Paragraph-2\n\"\"\"\nrslt =get_emotion(model_sql,\"The pain my heart feels is just too much for it to bear. Nothing eases this pain. I can\u2019t hold myself back. I really miss you\")\nresult_plotting(rslt)\n\"\"\"\n# **Result of LSTM**\n\"\"\"\n\"\"\"\n### Paragraph-3\n\"\"\"\nrslt =get_emotion(model_sql,\"I hate this game so much,It make me angry all the time \")\nresult_plotting(rslt)\n\"\"\"\n# **LSTM with GloVe 6B 200d word embedding**\n### **GloVe algorithm is an extension to the word2vec method for efficiently learning word vectors**\n\"\"\"\ndef data_reading(file):\n    with open(file,'r') as z:\n        word_vocabulary = set() \n        word_vector = {}\n        for line in z:\n            line_1 = line.strip() \n            words_Vector = line_1.split()\n            word_vocabulary.add(words_Vector[0])\n            word_vector[words_Vector[0]] = np.array(words_Vector[1:],dtype=float)\n    print(\"Total Words in DataSet:\",len(word_vocabulary))\n    return word_vocabulary,word_vector\nvocabulary, word_to_index =data_reading(\"..\/input\/glove-global-vectors-for-word-representation\/glove.6B.200d.txt\")\nmatrix_embedding = np.zeros((len(t_idx) + 1, 200))\nfor word, i in t_idx.items():\n    vector_embedding = word_to_index.get(word)\n    if vector_embedding is not None:\n        matrix_embedding[i] = vector_embedding\nembedding_dimension = 200\nlstm_out = 250\n\nmodel_lstm = Sequential()\nmodel_lstm.add(Embedding(len(t_idx) +1 , embedding_dimension,input_length = X_test_pad.shape[1],weights=[matrix_embedding],trainable=False))\nmodel_lstm.add(SpatialDropout1D(0.2))\nmodel_lstm.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))\nmodel_lstm.add(keras.layers.core.Dense(3, activation='softmax'))\n#adam rmsprop \nmodel_lstm.compile(loss = \"categorical_crossentropy\", optimizer='adam',metrics = ['accuracy'])\nprint(model_lstm.summary())\nsize_of_batch = 32\n\"\"\"\n# **LSTM with GloVe Model**\n\"\"\"\nmodel_lstm.fit(X_train_pad, y_train, epochs = Epoch, batch_size=size_of_batch,validation_data=(X_test_pad, y_test))\n\"\"\"\n# **Result of LSTM GloVe**\n\"\"\"\n\"\"\"\n### Paragraph-1\n\"\"\"\nrslt =get_emotion(model_lstm,\"Had an absolutely brilliant day \u00f0\u0178\u02dc\u0081 loved seeing an old friend and reminiscing\")\nresult_plotting(rslt)\n\"\"\"\n# **Result of LSTM GloVe**\n\"\"\"\n\"\"\"\n### Paragraph-2\n\"\"\"\nrslt =get_emotion(model_lstm,\"The pain my heart feels is just too much for it to bear. Nothing eases this pain. I can\u2019t hold myself back. I really miss you\")\nresult_plotting(rslt)\n\"\"\"\n# **Result of LSTM GloVe**\n\"\"\"\n\"\"\"\n### Paragraph-3\n\"\"\"\nrslt =get_emotion(model_lstm,\"I hate this game so much,It make me angry all the time \")\nresult_plotting(rslt)\n\"\"\"\n# **Conclusion**\n\n\n\"\"\"\n\"\"\"\n**Algorithms used to detect different types of emotion from paragraph are**\n\n**1- LSTM (Long Short Term Memory)**-It is an artificial recurrent neural network (RNN) architecture used in the field of deep learning.\n**2- LSTM GloVe- GloVe algorithm is an extension to the word2vec method for efficiently learning word vectors.**\n\nIt has been concluded that using LSTM algorithm it is easier to classify the Tweets and a more accurate result is obtained.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4990ea5b1acd90'}"}
{"id":"2655","text":"\"\"\"\n**Some Cooking Ideas for Tonight**\n\n* The idea is to create some new recipes when people are looking for something to eat at home\n* Build some ingredients set for each cuisine and randomly choose the ingredients\n\"\"\"\n# 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 in \n\n#Libraries import\nimport pandas as pd\nimport numpy as np\nimport csv as csv\nimport json\nimport re\nimport random #Used to randomly choose ingredients\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nwith open('..\/input\/train.json', 'r') as f:\n    train = json.load(f)\ntrain_raw_df = pd.DataFrame(train)\n\nwith open('..\/input\/test.json', 'r') as f:\n    test = json.load(f)\ntest_raw_df = pd.DataFrame(test)\n\"\"\"\n**Some Basic Data Cleaning**\n\"\"\"\n# Remove numbers and only keep words\n# substitute the matched pattern\n# update the ingredients\ndef sub_match(pattern, sub_pattern, ingredients):\n    for i in ingredients.index.values:\n        for j in range(len(ingredients[i])):\n            ingredients[i][j] = re.sub(pattern, sub_pattern, ingredients[i][j].strip())\n            ingredients[i][j] = ingredients[i][j].strip()\n    re.purge()\n    return ingredients\n\n#remove units\np0 = re.compile(r'\\s*(oz|ounc|ounce|pound|lb|inch|inches|kg|to)\\s*[^a-z]')\ntrain_raw_df['ingredients'] = sub_match(p0, ' ', train_raw_df['ingredients'])\n# remove digits\np1 = re.compile(r'\\d+')\ntrain_raw_df['ingredients'] = sub_match(p1, ' ', train_raw_df['ingredients'])\n# remove non-letter characters\np2 = re.compile('[^\\w]')\ntrain_raw_df['ingredients'] = sub_match(p2, ' ', train_raw_df['ingredients'])\n\ny_train = train_raw_df['cuisine'].values\ntrain_ingredients = train_raw_df['ingredients'].values\ntrain_ingredients_update = list()\nfor item in train_ingredients:\n    item = [x.lower().replace(' ', '+') for x in item]\n    train_ingredients_update.append(item)\nX_train = [' '.join(x) for x in train_ingredients_update]\n# Create the dataframe for creating new recipes\nfood_df = pd.DataFrame({'cuisine':y_train\n              ,'ingredients':train_ingredients_update})\n\"\"\"\n**Randomly choose ingredients for the desired cuisine**\n\"\"\"\n# the randomly picked function\ndef random_generate_recipe(raw_df, food_type, num_ingredients):\n    if food_type not in raw_df['cuisine'].values:\n        print('Food type is not existing here')\n    food_ingredients_lst = list()\n    [food_ingredients_lst.extend(recipe) for recipe in raw_df[raw_df['cuisine'] == food_type]['ingredients'].values] \n    i = 0\n    new_recipe, tmp = list(), list()\n    while i < num_ingredients:\n        item = random.choice(food_ingredients_lst)\n        if item not in tmp:\n            tmp.append(item)\n            new_recipe.append(item.replace('+', ' '))\n            i+=1\n        else:\n            continue\n    recipt_str = ', '.join(new_recipe)\n    print('The new recipte for %s can be: %s' %(food_type, recipt_str))\n    return new_recipe\n#Say you want some chinese food and you want to only have 10 ingredients in it\nrandom_generate_recipe(food_df, 'chinese', 10)\n\"\"\"\n*This more sounds like some Japanese food*\n\"\"\"\n#Say you want some indian food and you want to only have 12 ingredients in it\nrandom_generate_recipe(food_df, 'indian', 12)\n#Say you want some french food and you want to only have 8 ingredients in it\nrandom_generate_recipe(food_df, 'french', 12)","meta":"{'source': 'AI4Code', 'id': '0511fc218c4b1c'}"}
{"id":"127502","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndataset = pd.read_csv('..\/input\/Salary_Data.csv')\ndataset.head()\ndataset.info()\nX = pd.DataFrame(dataset, index= range(30), columns=['YearsExperience'])\nX.info()\nX.head()\ny = dataset.loc[: , 'Salary']\ny.head()\nplt.scatter(X , y , color = 'yellow')\n\"\"\"\n**THE ABOVE SCATTER PLOT IS SHOWING A LINEAR RELATIOSHOIP BETWEEN X AND y, SO HERE WE CAN APPLY SIMPLE LINEAR REGRESSION MODEL AS ONLY ONE INDEPENDENT VARIABLE IS THERE **\n\"\"\"\n##Splitting the dataset into train test\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = (1\/3), random_state = 0 )\nX_train.info(), X_test.info()\n##Fitting the regression model on the training set\nfrom sklearn.linear_model import LinearRegression\n\nregressor = LinearRegression()\n\nregressor.fit(X_train, y_train)\n\n##Predicting the y variables\ny_predict = regressor.predict(X_test)\ny_predict\n##Visualising the training dataset\nplt.scatter(X_train, y_train, color = 'orange')\nplt.plot(X_train, regressor.predict(X_train), color = 'pink' )\nplt.title('Training Dataset')\nplt.xlabel('Experience')\nplt.ylabel('Salary')\nregressor.coef_\n regressor.intercept_\n##Visualising the test dataset\nplt.scatter(X_test, y_test, color = 'green')\nplt.plot(X_train, regressor.predict(X_train), color = 'red')\nplt.title('Test Dataset')\nplt.xlabel('Experience')\nplt.ylabel('Salary')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'ea83b6cd05caf6'}"}
{"id":"126651","text":"! conda install -y hvplot=0.5.2 bokeh==1.4.0\n! conda install -y -c conda-forge sklearn-contrib-py-earth\n\"\"\"\n# Global Surrogates Models\nMany classes of models can be difficult to explain. For Tree Ensembles, while it may be easy to describe the rationale for a single trees outputs, it may be much harder to describe how the prediction of many trees are combined by fitting on on errors and weighting thousands of threes. Similarly for neural networks, while the final layer may be linear, it may difficult to convey to domain experts how features- in some easily understood units of measurement- are scaled then combined and projected to make a prediction.  The challenge is that there may be a set of applications where we may benefit greatly from these styles of model but may look to or be required to explain our predictions to users based on regulations, a need for user feedback or for user buy-in.  \n\nI the case of neural network models, the motivations may be most evident.  Neural network models can benefit from large distributed online training across petabytes of data. In the Federated Learning context, it may be the best-suited model for learning non-linear features for prediction as there is a well-understood body of research into how to train models in this complex environment.  The challenge we far may then face is how to extract explanations from this largely black-box model.\n  \nUsing Global Surrogates Models, we try to 'imitate' a black-box model with a highly explainable model to provide explanations. In some cases, these highly non-linear explainable models may not scale well to the data or the learning environment and may be poorly suited to robustly fit the noise in the data. We may also have deployed black-box models historically, which we are now looking to explain and so need a way of understanding what is taking place on the decision surface of the black-box model for the purpose of prototyping and data collections in order to replace the model.  Using a Global Surrogates Model, we look to fit the predictions of the black-box model and analyze the properties of the explainable model to provide insight into the black-box model.  \n\"\"\"\n\"\"\"\n# Data\n\"\"\"\n\"\"\"\nFor our examples in this notebook, we are going to be looking at the Boston Housing Dataset, which is a simple, well-understood dataset provided by default in the Scikit-learn API. The goal here is not to find a good model, but to be able to describe any chosen class of model.  For this reason, we will not be discussing why we choose a particular model or its hyperparameters, and we are not going to be looking into methods for cross-validation.  \n\"\"\"\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport numpy as np\nfrom toolz.curried import map, pipe, compose_left, partial\nfrom typing import Union, Tuple, List, Dict\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport warnings\nfrom abc import ABCMeta\nfrom itertools import chain\nfrom operator import add\nimport holoviews as hv\nimport pandas as pd\nimport hvplot.pandas\nfrom sklearn.datasets import load_digits, load_boston\nimport tensorflow as tf\nfrom functools import reduce\n\nhv.extension('bokeh')\ndata = load_boston()\nprint(data.DESCR)\n\"\"\"\n# Model\n\"\"\"\n\"\"\"\nI have opted to make use of the Dense Feed-forward Neural Network (DNN) with four hidden neurons and a Selu activation function. The actual properties of this black-box model are not necessary, and in fact, we are going to look to overfit to the data slightly, to provide a slightly greater challenge in our trying to explain this model's decision surface. \n\"\"\"\nEPOCHS = 50\n\nclass FFNN(tf.keras.Model):\n    def __init__(self, layers = (4, )):\n        super(FFNN, self).__init__()\n        \n        self.inputs = tf.keras.layers.InputLayer((3, 3))\n        self.dense = list(map(lambda units: tf.keras.layers.Dense(units, activation='selu'), layers))\n        self.final = tf.keras.layers.Dense(1, activation='linear')\n        \n    def call(self, inputs):\n        \n        return reduce(lambda x, f: f(x), [inputs, self.inputs, *self.dense, self.final])\n    \n@tf.function\ndef train_step(inputs, labels):\n    with tf.GradientTape() as tape:\n        predictions = model(inputs)\n        \n        loss = tf.keras.losses.mse(predictions, label)\n    gradients = tape.gradient(loss, model.trainable_variables)\n    optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\"\"\"\nThe only transformation I have opted to do is to take the log of our housing price target to make our assumption about our conditional distribution being symmetric, more realistic. \n\"\"\"\npd.Series(data.target).hvplot.kde(xlabel='Log-Target Value')\ntrain_ds = tf.data.Dataset.from_tensor_slices((tf.convert_to_tensor(data.data.astype('float32')),\n                                               tf.convert_to_tensor(np.log(data.target.astype('float32'))))).batch(32)\nmodel = FFNN()\nmodel.compile(loss='mse')\n\noptimizer = tf.keras.optimizers.Adam()\nfor epoch in range(EPOCHS):\n    for sample in train_ds:\n        inputs, label = sample\n        gradients = train_step(inputs, label)\n        \ny_pred = model(data.data.astype('float32')).numpy()\nmodel.summary()\n\"\"\"\n## Decision tree\n\"\"\"\n\"\"\"\nWhile Decision Tree's maybe poor surrogate models for many classes of Black-box model, they are highly interpretable and intuitive for domain experts. Post-hoc explanations can often face a trade-off between interpretability, compute and faithfulness, forcing us to choose approaches which best mirror the tradeoffs we are willing to make.  Many people have been exposed to similar, structured reasoning and while our decision tree may not approximate the reasoning process taken by our original model and be particularly faithful, the interpretability of our decision tree may form a good starting point in building trust with domain experts for complex black-box models. \n\"\"\"\nfrom sklearn import tree\nimport matplotlib.pyplot as plt\nclf = tree.DecisionTreeRegressor(max_depth=4, min_weight_fraction_leaf=0.15)\nclf = clf.fit(data.data, y_pred)\nplt.figure(figsize=(30,7))\ndot_data = tree.plot_tree(clf, max_depth=4, fontsize=12, feature_names=data.feature_names, filled=True, rounded=True)\n\"\"\"\n## 'non-linear' Linear Model\n\"\"\"\n\"\"\"\nI have before written about my enthusiasm for Linear Models as an interpretable and flexible framework for modelling. What many people don't realize with linear models is that they can be super non-linear, you just need to be able to generate, select and constrain your feature-set in order to appropriately cope with the collinearity in your basis.  Here, we can have tremendous control over the explanations we provide, and while I would recommend starting with an explainable model rather than trying to do Post-hox explanations, Generalized Additive Models and similar classes of model can provide excellent surrogate models for describing the decision-space learned by a black-box model.  \n\nHere I use a Multivariate Adaptive Regression Spline Model to learn features from the data which help describe the decision surface of my black-box DNN. \n\"\"\"\nfrom pyearth import Earth\nearth = Earth(max_degree=2, allow_linear=True, feature_importance_type='gcv')\n\nearth.fit(data.data, y_pred, xlabels=data.feature_names.tolist())\nprint(earth.summary())\n\"\"\"\nHere, I can get some notion of feature importances in approximating my model which may be valuable in data collections or feature engineering. \n\"\"\"\nprint(earth.summary_feature_importances())\n(pd.DataFrame([earth._feature_importances_dict['gcv']], columns=data.feature_names, index=['Features'])\n .hvplot.bar(title=\"'Non-linear' Linear Model Global Approximation Feature Importances\")\n .opts(xrotation=45, ylabel='Importance'))\n\"\"\"\nThe main application I may see this used in is scenario in which we believe we can benefit from stochastic optimization on a large noisy dataset using Deep Learning but would like to distill those insights using a subset of the data using our MARS model. One may opt, in some contexts, to improve stability of the fit using some spatial weighting matrix, to control for soem regions being poorly cpatured by the surrogate model due to mismatches in the learning capacity of particular surrogate models can cause entire regions of the decisions surface to have correlated errors. \n\"\"\"\n\"\"\"\n# Conclusions\nOne advantage of Suggorate Models is that you can quite easily sample any additional data you may need to describe the black-box model. This can be useful for subsampling the data but may be dangerous in regions where there is poor data coverage as the model may provide degenerate predictions due to overfitting.  \n\nGlobal Surrogates are a blunt tool to model explainability, with some very specific use-cases. When using Global Surrogate models, it may be critical in planning a project to evaluate why a black-box model is being used at all if it can be well approximated by an explainable model.  The quality of the approximation and the distributional assumptions made when fitting the model are critical and must be tracked closely.  If you match poorly surrogates and black-box models, you may have very misleading results. That being said, this can be a fast and simple-to-implement heuristic to guide later methods. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e8ebf31aa52f0e'}"}
{"id":"109814","text":"\"\"\"\n# **A\/B TESTING**\n \n **What is A\/B Testing?**\n\nThe A\/B test is a hypothesis test in which two-sample user experiences are tested. In other words, A\/B testing is a way to compare two versions of a single variable, typically by testing a subject's response to variant A against variant B, and determining which of the two variants is more effective.\n\n\n\"\"\"\nfrom PIL import Image \nImage.open(\"..\/input\/ab-testing-pic\/ab-testing-picc.png\")\n\"\"\"\n **A\/B Testing with Business Problem**\n\n***Business Problem***\n\nThe company recently introduced a new bid type, average bidding,\nas an alternative to the current type of bidding called maximum bidding.\n\nOne of our client decided to test this new feature and wants to do\nan A\/B test to see if average bidding brings more returns than maximum bidding.\n\n***The Story of the Data Set***\n\nThere are two separate data sets, the Control and the Test group.\n\n***Variables***\n* Impression: Number of ad views\n* Click: Number of clicks on the displayed ad\n* Purchase: The number of products purchased after clicked ads\n* Earning: Earnings after the purchased products\n\"\"\"\n\"\"\"\n**Required Modules and Libraries**\n\"\"\"\n!pip install openpyxl\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels.stats.api as sms\nfrom scipy.stats import ttest_1samp, shapiro, levene, ttest_ind   \nfrom statsmodels.stats.proportion import proportions_ztest\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', 10)\npd.set_option('display.float_format', lambda x: '%.5f' % x)\ndf_c = pd.read_excel(\"..\/input\/ab-testing\/ab_testing.xlsx\",sheet_name=\"Control Group\")\ndf_t = pd.read_excel(\"..\/input\/ab-testing\/ab_testing.xlsx\",sheet_name=\"Test Group\")\n\"\"\"\n**Defining the hypothesis of the A\/B test**\n\nH0: There is no statistically significant difference the returns\n of the Maximum Bidding (control) and Average Bidding (test) options.\n \nH1: There is statistically significant difference the returns\n of the Maximum Bidding (control) and Average Bidding (test) options.\n \n After the hypotheses are defined, the normality assumption and variance\n homogeneity are checked.In this direction, \n the normality assumption control is performed first.\n\"\"\"\ndf_c[\"Purchase\"].mean()      #Let's observe the purchase mean of control group.\n\ndf_t[\"Purchase\"].mean()      #Let's observe the purchase mean of test group.\ndata=[df_c[\"Purchase\"],df_t[\"Purchase\"]]\nplt.boxplot(data);           #Let's see the boxplot grafic of purchases mean.\n#Let's see the histogram grafic of purchases for both control and test group.\nplt.figure(figsize=[10,5])\nn, bins, patches = plt.hist(x=df_c[\"Purchase\"], bins=10, color='#5F9EA0')\nplt.xlabel('Purchase',fontsize=15)\nplt.ylabel('Frequency',fontsize=15)\nplt.title('Purchase of Control Group',fontsize=15)\nplt.show()\nplt.figure(figsize=[10,5])\nn, bins, patches = plt.hist(x=df_t[\"Purchase\"], bins=10, color='#3D59AB')\nplt.xlabel('Purchase',fontsize=15)\nplt.ylabel('Frequency',fontsize=15)\nplt.title('Purchase of Test Group',fontsize=15)\nplt.show()\n\"\"\"\n**Normality Assumption Control**\n\nH0: The assumption of normality is provided.\n\nH1: The assumption of normality is not provided.\n\"\"\"\n\ntest_stat, pvalue = shapiro(df_c[\"Purchase\"])\nprint('Test Stat = %.4f, p-value = %.4f' % (test_stat, pvalue))\n#Test Stat = 0.9773, p-value = 0.5891\n\ntest_stat, pvalue = shapiro(df_t[\"Purchase\"])\nprint('Test Stat = %.4f, p-value = %.4f' % (test_stat, pvalue))\n#TTest Stat = 0.9589, p-value = 0.1541\n\"\"\"\n p-value is less than 0.05, H0 is rejected.\n \n p-value is not less than 0.05, H0 can not rejected.\n \n So in this case, H0 can not rejected and the assumption of normality is provided.\n\"\"\"\n\"\"\"\n**Variance Homogeneity Control**\n\n H0: The variances are homogeneous.\n \n H1: The variances are not homogeneous.\n\"\"\"\ntest_stat, pvalue = levene(df_t[\"Purchase\"],\n                           df_c[\"Purchase\"])\n\nprint('Test Stat = %.4f, p-value = %.4f' % (test_stat, pvalue))\n#Test Stat = 2.6393, p-value = 0.1083\n\"\"\"\n So in this case, H0 can not rejected and the variances are homogeneous.\n\"\"\"\n\"\"\"\n**Because of the assumptions provided, non parametric test called two-sample t-test will be used.**\n\"\"\"\ntest_stat, pvalue = ttest_ind(df_t[\"Purchase\"],\n                              df_c[\"Purchase\"],\n                              equal_var=True)\n\nprint('Test Stat = %.4f, p-value = %.4f' % (test_stat, pvalue))\n# Test Stat = 0.9416, p-value = 0.3493\n\"\"\"\nSo at the end, H0 can not rejected. We can infer that there is no statistically\n\nsignificant difference the returns of the Maximum Bidding (control) and\n\nAverage Bidding (test) options.\n\"\"\"\n\"\"\"\n**Using Two-Sample Rate Test**\n\nH0: There is no statistically significant difference between the maximum bidding click-through rate and the average\n\nbidding click-through rate.\n\nH1: There is statistically significant difference between the maximum bidding click-through rate and the average \n\nbidding click-through rate\n\"\"\"\nMaks_succ_count=df_c[\"Click\"].sum()     #204026\nAve_succ_count=df_t[\"Click\"].sum()      #158701\n\nMaks_rev_count=df_c[\"Impression\"].sum()  #4068457\nAve_rev_count=df_t[\"Impression\"].sum()   #4820496\n\n\ntest_stat, pvalue = proportions_ztest(count=[Maks_succ_count, Ave_succ_count],\n                                      nobs= [df_c[\"Impression\"].sum(),\n                                            df_t[\"Impression\"].sum()])\nprint('Test Stat = %.4f, p-value = %.4f' % (test_stat, pvalue))\n\"\"\"\nTest Stat = 129.3305, p-value = 0.0000\n\np-value is less than 0.05, H0 is rejected.According to Two-Sample Rate Test, There is statistically\n\nsignificant difference between the maximum bidding click-through rate and the average bidding click-through rate\n\"\"\"\n\"\"\"\n\nConsequently, two sample t-test were used primarily to see if there was a significant difference between the returns between the two groups. And it was concluded that there was no significant difference between the two groups. However, in this problem, two sample rate test were applied on request via ad viewing and click-through rates. As a result of the two sample rate test,there was a statistically significant difference between the click-through and ad viewing rates. So, we can say that different results can be obtained as a result of the tests used by considering different purposes and different variables.Therefore, it is necessary first of all to express the purpose in the best way and select the appropriate test methods.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c9ce8f2cf6c544'}"}
{"id":"17154","text":"\"\"\"\n# Sa\u00edda\n\nPara imprimir alguma coisa na tela, utilizamos a _built-in function_ **_print_**\n\"\"\"\nprint('Matheus Tenorio')\n\"\"\"\n### Note que o print deve possuir parenteses\n\"\"\"\n\"\"\"\nNote que o valor passado como argumento da fun\u00e7\u00e3o est\u00e1 entre aspas.\nQuando um texto est\u00e1 entre aspas, isto \u00e9 uma _string_. \nUma string pode estar entre aspas simples ('') ou aspas duplas (\"\")\n\"\"\"\n'Matheus Tenorio' # String com aspas simples\n\"Matheus Tenorio\" # String com aspas duplas\n\"\"\"\n# Coment\u00e1rios\nUm coment\u00e1rio \u00e9 uma parte do c\u00f3digo (ou do script) que n\u00e3o ser\u00e1 executado. \\\nOs coment\u00e1rios s\u00e3o \u00fateis para impedir, de forma f\u00e1cil, que parte do c\u00f3digo seja executado, seja para testes, para eliminar um bug, ou at\u00e9 para descobrir onde est\u00e1 o bug.\nTamb\u00e9m s\u00e3o utilizados para fazer anota\u00e7\u00f5es como no c\u00f3digo acima.\nOs coment\u00e1rios podem ser de uma linha, utilizando o s\u00edmbolo cerquilha (#).\nTudo ap\u00f3s o cerquilha ser\u00e1 considerado um coment\u00e1rio\n\"\"\"\nprint('Matheus Tenorio')\n# print('Idade: 24')\n# Esta linha n\u00e3o ser\u00e1 executada bem como a linha acima\n\"\"\"\nPara fazer um coment\u00e1rio de muitas linhas podemos utilizar aspas triplas (''' ''')\n\"\"\"\nprint('Matheus Tenorio') # coment\u00e1rio de uma linha\n'''\nComent\u00e1rio de muitas linhas\nprint('Idade: 24')\nEsta linha n\u00e3o ser\u00e1 executada bem como a linha acima\n'''\n\"\"\"\nComo pode ser visto no exemplo acima, as aspas triplas tamb\u00e9m s\u00e3o considerados strings de v\u00e1rias linhas\n\"\"\"\nprint('''Meu nome \u00e9 Matheus Tenorio\nMinha Idade \u00e9 24 anos''')\n\"\"\"\n# Erros\n\nQuando alguma coisa d\u00e1 errada no script, o interpretador Python interrompe a execu\u00e7\u00e3o do programa e imprime uma mensagem de erro\n\"\"\"\nprint('Matheus Tenorio')\nprint('Idade: 24 anos')\nprint('Altura: 1,80cm')\n\"\"\"\nVamos dar uma olhada na mensagem de erro impressa:\n```Shell\n---------------------------------------------------------------------------\nNameError                                 Traceback (most recent call last)\n<ipython-input-12-72bcea0f1f9d> in <module>\n      1 print('Matheus Tenorio')\n      2 print('Idade: 24 anos')\n----> 3 pritn('Altura: 1,80cm')\n\nNameError: name 'pritn' is not defined\n```\nA primeira linha mostra o tipo do erro. Neste caso foi `NameError` que indica um erro de sintaxe. Mais precisamente a fun\u00e7\u00e3o `print` foi escrita errada (`pritn`)\nNas pr\u00f3ximas linhas \u00e9 mostrado em qual linha o erro ocorreu. Isto \u00e9 \u00fatil para encontrar o erro em um script com muitas linhas.\n\"\"\"\n\"\"\"\n# Vari\u00e1veis\n\nEm Python, as vari\u00e1veis s\u00e3o declaradas da seguinte forma:\n\"\"\"\nage = 24\n\"\"\"\nPerceba que n\u00e3o precisamos definir o tipo da vari\u00e1vel, pois Python \u00e9 dinamicamente tipada.\nIsto quer dizer que uma vari\u00e1vel possui o tipo do dado que ela est\u00e1 armazenando no momento.\nDiferente de outras linguagens como: C, C++, Java, Rust, em que todas as vari\u00e1veis possuem um tipo na sua declara\u00e7\u00e3o e n\u00e3o podem ser alterados depois, em Python as vari\u00e1veis possuem o tipo do dado que recebem, podendo esse tipo ser alterado depois da declara\u00e7\u00e3o.\n\"\"\"\nage = 24          # O tipo da vari\u00e1vel age, no momento, \u00e9 um inteiro\nage = 'Ola Mundo' # O tipo da vari\u00e1vel age passa a ser uma string\n\"\"\"\nNote tamb\u00e9m que a vari\u00e1vel \u00e9 criada no momento em que a atribui\u00e7\u00e3o \u00e9 feita, isto \u00e9, no momento em que um valor \u00e9 dado para ela `age = 24`.\nDesta forma, a cria\u00e7\u00e3o de uma vari\u00e1vel sempre possui uma atribui\u00e7\u00e3o.\nPara criar uma vari\u00e1vel sem valor, podemos utilizar a palavra-chave `None`\n\"\"\"\nage = None\n\"\"\"\nA palavra-chave `None` representa o valor nulo do Python. Assim, a vari\u00e1vel `age` existe mas n\u00e3o possui valor.\n\"\"\"\nage = None\nage1 = 0\nage == age1\n\"\"\"\nPerceba que o valor nulo `None` \u00e9 diferente do inteiro 0. \nNa vari\u00e1vel `age` n\u00e3o existe valor armazenado, enquanto na vari\u00e1vel `age1` existe um valor, o inteiro zero\n\"\"\"\n\"\"\"\n# Regras de nomeclatura de vari\u00e1veis\nExiste alguns nomes que s\u00e3o permitidos para os nomes das vari\u00e1veis, enquanto outros nomes s\u00e3o pro\u00edbidos.\n\nOs nomes permitidos possuem as seguintes regras:\n1. Deve come\u00e7ar com **letra min\u00fascula**, ou com **letra mai\u00fascula** ou com **underline** (\\_)\n2. Pode possuir **n\u00fameros**, por\u00e9m **n\u00e3o pode iniciar** com n\u00fameros\n3. Os \u00fanicos simbolos permitidos s\u00e3o: **letras min\u00fascula**, **letra mai\u00fascula**, **underline**, **n\u00fameros**\n\"\"\"\nage = 24\nAge = 24\n_age = 24\nmy_age = 24\nage23 = 24\n_24 = 24\na2 = 24\n\"\"\"\nOs nomes pro\u00edbidos possuem as seguintes regras:\n1. Qualquer nome que quebre uma, ou mais, regras dos nomes permitidos\n2. Palavras-chave do Python\n\"\"\"\n2age = 24    # Quebra as regras 1 e 2 dos nomes permitidos\nage@new = 24 # Quebra a regra 3 dos nomes permitidos\nfor = 23     # Regra 2 dos nomes proibidos\n\"\"\"\n# Convens\u00e3o dos nomes das vari\u00e1veis\nO nome das vari\u00e1veis seguem uma convens\u00e3o de nomes chamada **snake_case**.\nNessa convens\u00e3o as vari\u00e1veis seguem o seguinte formato:\n> Todas as letras s\u00e3o min\u00fasculas e as palavras compostas s\u00e3o separadas por underline (\\_)\n\nA convens\u00e3o de nomes \u00e9 uma forma da comunidade padronizar a formata\u00e7\u00e3o (visual) do c\u00f3digo. \nIsto quer dizer que \u00e9 apenas uma escolha da comunidade. N\u00e3o \u00e9 obrigat\u00f3rio, mas \u00e9 recomendado\n\"\"\"\nmy_age = 24 # snake_case -> Recomendado para vari\u00e1veis\nmyAge = 24  # camelCase -> Poss\u00edvel, mas n\u00e3o recomendado para vari\u00e1veis\nMyAge = 24  # CamelCase -> Poss\u00edvel, mas n\u00e3o recomendado para vari\u00e1veis\n\"\"\"\n# Entrada\nPara obter dados provenientes dos usu\u00e1rios, podemos utilizar a _built-in function_ `input`.\nAssim como a fun\u00e7\u00e3o `print` est\u00e1 relacionada com a sa\u00edda de dados, a fun\u00e7\u00e3o `input` est\u00e1 relacionada com a entrada de dados.\n\"\"\"\nage = input()\n\"\"\"\nO retorno da fun\u00e7\u00e3o `input` consiste nos dados digitados pelo usu\u00e1rio. Este retorno \u00e9 sempre do tipo `string`.\nPara adicionar um promt (uma frase, ou palavra, que vem antes da entrada de dados) basta adicionar uma string como argumento da fun\u00e7\u00e3o `input`\n\"\"\"\nage = input('Qual a sua idade? ')\n\"\"\"\n# Tipos b\u00e1sicos\n\nAqui vamos ver os tipos b\u00e1sicos em Python, qualquer outro tipo \u00e9 uma composi\u00e7\u00e3o deles. Outro ponto importante \u00e9 que todos os tipos s\u00e3o objetos.\n\nPrimeiro, vamos ver a diferen\u00e7a entre valor e tipo:\n\n* Valor: \u00c9 o dado;\n* Tipo: \u00c9 a classifica\u00e7\u00e3o do tipo.\n\nEm Python, existe a fun\u00e7\u00e3o 'type', a qual retorna o tipo do dado.\n\"\"\"\n\"\"\"\nOs tipos b\u00e1sicos s\u00e3o:\n\n* Boleano - bool;\n* Inteiro - int;\n* Real - float;\n* Complexo - complex;\n* String - str.\n\nE todos s\u00e3o object.\n\"\"\"\ntype(True)\ntype(82)\ntype(4.0)\ntype(1 + 1j)\ntype(\"Macei\u00f3\")\n\"\"\"\nAl\u00e9m disso, podemos tamb\u00e9m converter um tipo em outro. Existe algumas limita\u00e7\u00f5es como n\u00e3o \u00e9 poss\u00edvel converter qualquer string em int ou float. Para isso, basta utilizar a palavra reservada de cada tipo.\n\n   * bool(arg)\n   * int(arg)\n   * float(arg)\n   * complex(arg)\n   * str(agr)\n\nEm especial o int(arg), pode converter uma base al\u00e9m da decimal. Ou seja, a fun\u00e7\u00e3o de convers\u00e3o tem como padr\u00e3o a base 10, por\u00e9m \u00e9 poss\u00edvel converter para outra base utilizando int(arg,base=10).\n\"\"\"\nint('1010', 2) # Bin\u00e1ria\nint('a', 16) # Hexadecimal\n\"\"\"\nVale lembrar que para os boleanos, temos que o valor 0 (zero) indica false, enquanto qualquer outro valor indica verdadeiro.\n\"\"\"\nbool('1')\nbool(0.1)\nbool('0.0')\nbool('0')\nbool(0)\nbool(0.0)\n\"\"\"\nRode o c\u00f3digo acima para ver cada sa\u00edda.\n\"\"\"\n\"\"\"\n# String\n\nString \u00e9 uma sequ\u00eancia de caracteres e um objeto iter\u00e1vel(Veja tabela ASCII).\n\"\"\"\nstr1 = 'Edge'\nstr2 = \"Edge\"\n\"\"\"\n## Operadores\n\nAs string cont\u00e9m diversos operadores\n\nCompara\u00e7\u00e3o - Utiliza como base a tabela ASCII:\n\n   * Igualdade (==)\n   * Diferente (!=)\n   * Maior que (>)\n   * Menor que (<)\n   * Maior ou igual que (>=)\n   * Menor ou igual que (<=)\n\nAritm\u00e9trico:\n\n   * Soma (+)\n   * Multiplica\u00e7\u00e3o (*)\n\nAtribui\u00e7\u00e3o:\n\n   * Atribui\u00e7\u00e3o (=)\n   * Atribui\u00e7\u00e3o com soma (+=)\n   * Atribui\u00e7\u00e3o com Multiplica\u00e7\u00e3o (*=)\n\nConjunto:\n\n   * Pertence (in)\n   * N\u00e3o pertence (not in)\n\"\"\"\nstring1 = 'abcd'\nstring2 = \"abc\"\n\n# Igualdade\nprint( string1 == string2 )\n# Diferente\nprint( string1 != string2 )\n# Maior que\nprint( string1 > string2 )\n# Menor que\nprint( string1 < string2 )\n\n# Soma de strings (Concatena\u00e7\u00e3o)\nprint( string1 + string2 )\n# Multiplica\u00e7\u00e3o\nprint( 5 * string1 )\n\n# Atribui\u00e7\u00e3o\nstring3 = string2 + string1\nprint(string3)\n\n# Pertence\nprint( string2 in string1 )\n\"\"\"\nAl\u00e9m dos operadores, as strings possuem um conjunto de m\u00e9todos - https:\/\/docs.python.org\/2.5\/lib\/string-methods.html. Vamos abordar alguns deles aqui como transformar todos os caracteres em 'caixa baixa' ou 'caixa alta' e separa em substring a partir de um padr\u00e3o.\n\"\"\"\nphrase = 'Que desastre! At\u00e9 minhas fraquezas s\u00e3o mais fortes que eu!'\nprint(phrase.lower())\nprint(phrase.upper())\nprint(phrase.split(' '))\n\"\"\"\n# Condicionais\nPara executar um trecho de c\u00f3digo de acordo com uma condi\u00e7\u00e3o, podemos utilizar os condicionais. Em Python, temos 3 palavras-chaves para a utiliza\u00e7\u00e3o de condicionais: `if`, `else` e `elif`. A estrutura `if` pode ser utilizado sozinho ou em conjunto com o `elif` e com o `else`. A sintaxe do `if` \u00e9 a seguinte:\n```\nif <condi\u00e7\u00e3o>:\n    <code>\n```\nAp\u00f3s a palavra-chave `if` temos uma condi\u00e7\u00e3o `<condi\u00e7\u00e3o>` e o s\u00edmbolo dois pontos `:`, para determinar o final das condi\u00e7\u00f5es. \nNa pr\u00f3xima linha \u00e9 definido o corpo do `if`, sempre indentado. O corpo do `if` termina quando a indenta\u00e7\u00e3o termina.\n\"\"\"\nage = input()\nage = int(age)\nprint('Sua idade \u00e9 %d' % age)\n\n# 0 <= idade <= 18 -> 'Voc\u00ea \u00e9 crian\u00e7a'\n# 18 < idade <= 50 -> 'Voc\u00ea \u00e9 adulto'\n# 50 < idade       -> 'Voc\u00ea \u00e9 idoso'\n\nif 0 <= age and age <= 18:\n    print('Voc\u00ea \u00e9 crian\u00e7a')\nif 18 < age and age <= 50:\n    print('Voc\u00ea \u00e9 adulto')\nif 50 < age:\n    print('Voc\u00ea \u00e9 idoso')\n\"\"\"\nA estrutura `else` \u00e9 sempre utilizada em conjunto com a estrutura `if`. Isto que dizer que o `else` come\u00e7a assim que o corpo do `if` termina. A estrutura `else` possui a seguinte sintaxe:\n```\nif <condi\u00e7\u00e3o>:\n    <code>\nelse:\n    <code>\n```\nNote que ap\u00f3s a palavra-chave `else` n\u00e3o existe condi\u00e7\u00e3o, somente o s\u00edmbolo dois pontos `:`. Isto ocorre porque a estrutura `else` representa o c\u00f3digo executado, quando a condi\u00e7\u00e3o do `if` \u00e9 falsa. O corpo do `else` segue a mesma linha do corpo do `if`.\n\"\"\"\nage = input()\nage = int(age)\nprint('Sua idade \u00e9 %d' % age)\n\n# 0 <= idade <= 18 -> 'Voc\u00ea \u00e9 crian\u00e7a'\n# 18 < idade <= 50 -> 'Voc\u00ea \u00e9 adulto'\n# 50 < idade       -> 'Voc\u00ea \u00e9 idoso'\n\nif 0 <= age and age <= 18:\n    print('Voc\u00ea \u00e9 crian\u00e7a')\nelse:\n    if age <= 50:\n        print('Voc\u00ea \u00e9 adulto')\n    else:\n        print('Voc\u00ea \u00e9 idoso')\n\"\"\"\nPara criar v\u00e1rias condi\u00e7\u00f5es, podemos unir as ideias do `if` e do `else`. No Python, utilizamos a estrutura `elif`. Essa estrutura \u00e9 sempre acompanhada do `if` ou de outro `elif`. Isto quer dizer que podemos ter v\u00e1rios `elif` acompanhados do mesmo `if`. A sintaxe do `elif` \u00e9 a seguinte:\n```\nif <condi\u00e7\u00e3o1>:\n    <code>\nelif <condi\u00e7\u00e3o2>:\n    <code>\nelif <condi\u00e7\u00e3o3>:\n    <code>\nelse:\n    <code>\n```\nComo pode ser visto, a sintaxe do `elif` \u00e9 parecida com a sintaxe do `if`: palavra-chave `elif`, seguida de uma condi\u00e7\u00e3o, seguido do s\u00edmbolo dois pontos `:`, seguido do corpo do `elif` na pr\u00f3xima linha (indentado). A estrutura `else` no final \u00e9 opcional, enquanto a estrutura `if` no inicio \u00e9 obrigat\u00f3rio.\n\"\"\"\nage = input()\nage = int(age)\nprint('Sua idade \u00e9 %d' % age)\n\n# 0 <= idade <= 18 -> 'Voc\u00ea \u00e9 crian\u00e7a'\n# 18 < idade <= 50 -> 'Voc\u00ea \u00e9 adulto'\n# 50 < idade       -> 'Voc\u00ea \u00e9 idoso'\n\nif 0 <= age and age <= 18:\n    print('Voc\u00ea \u00e9 crian\u00e7a')\nelif age <= 50:\n    print('Voc\u00ea \u00e9 adulto')\nelse:\n    print('Voc\u00ea \u00e9 idoso')\n\"\"\"\n# Operador Tern\u00e1rio\nExiste uma forma mais resumida de implementar os condicionais, em apenas uma linha. Estes \u00e9 o operador tern\u00e1rio. A origem do nome \u00e9 porque esse operador \u00e9 um dos poucos operadores que recebem 3 argumentos. Desta forma, o nome operador tern\u00e1rio \u00e9 sempre associado a este operador que avalia uma condi\u00e7\u00e3o e retorna uma express\u00e3o dependendo da condi\u00e7\u00e3o avaliada. A sintaxe do operador tern\u00e1rio em Python \u00e9 a seguinte:\n```\nvar = <express\u00e3o verdadeira> if <condi\u00e7\u00e3o> else <express\u00e3o falsa>\n```\nNote que a sintaxe do operador \u00e9 bem parecida com a linguagem natural:\n> Retorne `<express\u00e3o verdadeira>` se a condi\u00e7\u00e3o `<condi\u00e7\u00e3o>` for verdadeira, caso contr\u00e1rio retorne `<express\u00e3o falsa>`\n\"\"\"\nage = input()\nage = int(age)\nprint('Sua idade \u00e9 %d' % age)\n\n# 0 <= idade <= 18 -> 'Voc\u00ea \u00e9 crian\u00e7a'\n# 18 < idade <= 50 -> 'Voc\u00ea \u00e9 adulto'\n# 50 < idade       -> 'Voc\u00ea \u00e9 idoso'\n\nage_range = 'crian\u00e7a' if 0 <= age <= 18 else ('adulto' if age <= 50 else 'idoso')\nprint('Voc\u00ea \u00e9 ' + age_range)\n\"\"\"\n# Cole\u00e7\u00f5es\nEm python, temos o conceito de cole\u00e7\u00f5es. Um cole\u00e7\u00e3o, como sugere o nome, \u00e9 um conjunto de elementos relacionados, que podem possuir, ou n\u00e3o, o mesmo tipo.\nTemos 4 tipos principais de cole\u00e7\u00f5es: \n1. Lista\n1. Tupla\n1. Conjunto (Set)\n1. Dicion\u00e1rio\n\"\"\"\n\"\"\"\n# Lista\nA lista \u00e9 uma cole\u00e7\u00e3o sequencial indexada. Sequ\u00eancial porque a ordem importa no momento que os itens s\u00e3o armazenados e indexada por utilizar indices n\u00famericos para obter os itens armazenados na lista. Por consequ\u00eancia, os itens da lista s\u00e3o acessados e modificados por indices n\u00famericos, sendo estes indices correspondentes as posi\u00e7\u00f5es, nas quais os itens est\u00e3o armazenados na lista. A lista corresponderia ao array de outras linguagens, mas com a vantagem de aceitar diversos tipos. A sintaxe da lista \u00e9 a seguinte:\n\n```\n<nome_da_variavel> = [<item1>, <item2>, <item3>, ..., <itemN>]\n```\nO `<nome_da_vari\u00e1vel>` representa o nome da vari\u00e1vel que vai armazenar a lista. A lista \u00e9 sempre delimitada por colchetes `[]`. Desta forma, tudo que estiver dentro dos colchetes ser\u00e1 um item da lista. Os `<item1>`, `<item2>`, `<item3>` e `<itemN>`, correspondem aos itens da lista. Perceba que os itens da lista s\u00e3o separados por v\u00edrgula `,`. Caso a lista possua apenas um item n\u00e3o \u00e9 necess\u00e1rio a v\u00edrgula, apenas o item.\n\"\"\"\nguests = ['Matheus', 'Luana', 'Lucas', 'Alfredo', 'J\u00e9ssica']\n\"\"\"\n## Indexa\u00e7\u00e3o\nPara acessar um item, ou modifica-lo, utilizamos a indexa\u00e7\u00e3o. A indexa\u00e7\u00e3o \u00e9 uma opera\u00e7\u00e3o que retorna um item de uma lista, de acordo com o indice que voc\u00ea utilizar.\nO python possui dois tipos de indexa\u00e7\u00e3o: a __indexa\u00e7\u00e3o normal__ e a __indexa\u00e7\u00e3o reversa__.\n\n### Indexa\u00e7\u00e3o Normal\nA sintaxe da indexa\u00e7\u00e3o normal (tamb\u00e9m chamada de forward indexing) \u00e9 a seguinte:\n```\n<itemN> = <var_list>[<indexN>]\n<var_list>[<indexN>] = <new_itemN>\n```\nA vari\u00e1vel que cont\u00e9m a lista \u00e9 `<var_list>` e para indexar um valor utilizamos: os colchetes `[]` ap\u00f3s a vari\u00e1vel e um inteiro (pode ser uma constante ou uma vari\u00e1vel do tipo inteiro) representando o indice `<indexN>`. Vamos analizar as duas linhas da sintaxe mostrada:\n1. Na primeira linha existe um acesso ao item na posi\u00e7\u00e3o `<indexN>`, da lista `<var_list>`. O retorno deste item \u00e9 armazenado na vari\u00e1vel `<itemN>`;\n1. Na segunda linha existe uma modifica\u00e7\u00e3o na posi\u00e7\u00e3o `<indexN>`, da lista `<var_list>`. Na posi\u00e7\u00e3o `<indexN>` ser\u00e1 atribuido o item `<new_itemN>`.\n\nNa indexa\u00e7\u00e3o normal, os indices come\u00e7am por zero. Isso quer dizer que para obter o primeiro item, utilizamos o indice 0, para obter o segundo elemento o indice 1 e assim por diante. Resumindo, para indexar o n-\u00e9simo item de uma lista, temos que utilizar o indice `(n-1)`\n\"\"\"\nprint(guests)\nfirst_guest = guests[0]\nsecond_guest = guests[1]\n\nprint('O primeiro convidado \u00e9: %s' % (first_guest))\nprint('O segundo convidado \u00e9: %s' % (second_guest))\n\"\"\"\n### Indexa\u00e7\u00e3o Reversa\nEm Python, diferente de outras linguagens de programa\u00e7\u00e3o, existe uma outra forma de indexar listas, chamada indexa\u00e7\u00e3o reversa. Na indexa\u00e7\u00e3o reversa os posi\u00e7\u00f5es dos items s\u00e3o acessados na ordem reversa, isto \u00e9, de tr\u00e1s pra frente. Para utilizar esta indexa\u00e7\u00e3o utlizamos a mesma sintaxe da indexa\u00e7\u00e3o normal, por\u00e9m com os indices negativos e come\u00e7ando por -1. Assim, o \u00faltimo item da lista \u00e9 indexado com o indice -1, o pen\u00faltimo \u00e9 indexado com o indice -2 e assim por diante. Resumindo, para acessar o n-\u00e9simo item, da direita para a esquerda, utilizamos o indice `-n`.\n\"\"\"\nprint(guests)\nlast_guest = guests[-1]\nlast_but_one_guest = guests[-2]\n\nprint('O \u00faltimo convidado \u00e9: %s' % (last_guest))\nprint('O pen\u00faltimo convidado \u00e9: %s' % (last_but_one_guest))\n\"\"\"\nPara indexar itens no in\u00edcio da lista utilizamos a indexa\u00e7\u00e3o normal, j\u00e1 para indexar itens no final da lista utilizamos a indexa\u00e7\u00e3o reversa\n> - Inicio -> Normal\n> - Final -> Reversa\n\n## *Slicing* (Fatiamento)\nEm Python, temos uma forma simplificada de obter uma sublista, chamada *slicing* (ou fatiamento). O *slicing* pode ser feito em qualquer cole\u00e7\u00e3o sequencial indexada, tal como: conjuntos e strings. A sintaxe \u00e9 bem parecida com a indexa\u00e7\u00e3o, por\u00e9m o resultado \u00e9 diferente: enquanto na indexa\u00e7\u00e3o \u00e9 retornado um item de uma lista, no *slicing* \u00e9 retornado uma lista totalmente nova e independente da lista original. Formalizando, o *slicing* retorna uma nova cole\u00e7\u00e3o, do mesmo tipo da cole\u00e7\u00e3o original, por\u00e9m independente dessa. Por exemplo: o slicing de uma string retorna uma nova string e independente da string original. A sintaxe do *slicing* \u00e9 a seguinte:\n```\n<sublist> = <var_list>[<s>:<e>]\n```\nA vari\u00e1vel que cont\u00e9m a lista \u00e9 `<var_list>` e para fazer o *slicing* vamos utlizar: os colchetes `[]` ap\u00f3s a vari\u00e1vel e dentro dos colchetes vamos utilizar dois inteiros (pode ser constantes ou vari\u00e1veis do tipo inteiro) separados por dois pontos `:`. O primeiro inteiro dentro dos colchetes `<s>` representa a posi\u00e7\u00e3o inicial, enquanto o segundo inteiro dentro dos colchetes `<e>` representa a posi\u00e7\u00e3o final. Assim a nova lista, que ser\u00e1 atribu\u00edda a vari\u00e1vel `<sublist>`, ser\u00e1 composta por todos os itens, dentro do intervalo `[<s>, <e>)`, da lista `<var_list>`. Perceba que o item presente na posi\u00e7\u00e3o `<e>` n\u00e3o ser\u00e1 inclu\u00eddo na nova lista. Os itens presentes ser\u00e3o os itens da posi\u00e7\u00e3o: `<s>`, `(<s>+1)`, `(<s>+2)` at\u00e9 o item na posi\u00e7\u00e3o `(<e>-1)`.\n\"\"\"\nprint(guests)\nprint(f'Os dois primeiros itens s\u00e3o: {guests[0:2]}')\nprint(f'O 3\u00ba, 4\u00ba e 5\u00ba itens s\u00e3o: {guests[2:5]}')\n\"\"\"\nTamb\u00e9m podemos utilizar indices negativos no *slicing*. Eles funcionam da mesma forma como na indexa\u00e7\u00e3o reversa.\n\"\"\"\nprint(guests)\nprint(f'Os dois primeiros itens s\u00e3o: {guests[-5:-3]}')\nprint(f'O 3\u00ba e 4\u00ba itens s\u00e3o: {guests[-3:-1]}')\n\"\"\"\nPodemos omitir um dos indices no *slicing*, ou todos. \n- Se o indice omitido for o primeiro, ent\u00e3o a nova lista come\u00e7ar\u00e1 no in\u00edcio da lista original. \n- Se o indice omitido for o segundo, ent\u00e3o a nova lista terminar\u00e1 no final da lista original.\n- Se ambos os indices forem omitidos, ent\u00e3o a nova lista ser\u00e1 igual a lista original.\n\nIsto \u00e9 \u00fatil para obter sublistas importantes:\n1. Os `n` primeiros itens de uma lista `<var_list>`:\n```\n<var_list>[:n]\n```\n2. Os `n` \u00faltimos itens de uma lista `<var_list>`:\n```\n<var_list>[-n:]\n```\n\nVamos analizar cada caso:\n1. O primeiro indice est\u00e1 omitido, ent\u00e3o o come\u00e7o da nova lista ser\u00e1 o come\u00e7o da lista original. O segundo indice indica que a nova lista termina antes do indice `n`, ou seja, vai at\u00e9 o item no indice `(n-1)`, que \u00e9 o n-\u00e9simo item. Portanto, a nova lista come\u00e7a no come\u00e7o da lista original e termina no n-\u00e9simo item, isto quer dizer que estamos obtendo o `n` primeiros itens da lista.\n2. O primeiro \u00edndice indica que a nova lista come\u00e7a no indice `-n`, ou seja, o n-\u00e9simo item de tr\u00e1s pra frete (da direita para a esquerda), j\u00e1 que a indexa\u00e7\u00e3o reversa come\u00e7a com -1. O segundo indice est\u00e1 omitido, ent\u00e3o o final da nova lista ser\u00e1 o final da lista original. Portanto, a nova lista come\u00e7a no n-\u00e9simo \u00faltimo elemento e termina no final da lista original, isto quer dizer que estamos obtendo os `n` \u00faltimos itens da lista.\n\"\"\"\nprint(guests[:])\nprint(f'Os dois primeiros itens s\u00e3o: {guests[:2]}')\nprint(f'Os tr\u00eas \u00faltimos itens s\u00e3o: {guests[-3:]}')\n\"\"\"\n## Operadores\nExistem dois operadores importantes que podem ser utilizados nas listas: `in` e `del`.\n\n### Operador `in`\nO operador `in` \u00e9 utilizado para verificar a rela\u00e7\u00e3o de pertinencia entre itens e listas. A sintaxe deste operador \u00e9 a seguinte:\n```\n<itemN> in <var_list>\n```\nEssa express\u00e3o \u00e9 utlizada para verificar se o item `<itemN>` pertence \u00e0 lista `<var_list>`. \nAinda podemos ser verificado se o `<itemN>` n\u00e3o pertence \u00e0 lista `<var_list>`, utilizando a palavra-chave `not` na frente do operador `in`. A sintaxe \u00e9 da seguinte forma:\n```\n<itemN> not in <var_list>\n```\n\n### Operador `del`\nO operador `del` \u00e9 utilizado para excluir um item de uma lista, tendo a seguinte sintaxe:\n```\ndel <var_list>[n]\n```\nO n-\u00e9simo item da lista `<var_list>` ser\u00e1 exclu\u00eddo. Para remover a lista `<var_list>` podemos utilizar a seguinte sintaxe:\n```\ndel <var_list>\n```\n\"\"\"\nguests = ['Matheus', 'Luana', 'Lucas', 'Alfredo', 'J\u00e9ssica']\n\nprint(guests)\ndel guests[1] # Exclui o segundo elemento da lista guests\nprint(guests)\ndel guests    # Exclui a lista guests\nprint(guests)\n\"\"\"\n## *Built-in Functions*\nExistem 4 *built-in functions* que podem ser utilizadas em listas:\n1. `type` -> utilizada para obter o tipo da lista (deve retornar `list`)\n1. `len` -> utilizado para obter o tamanho da lista\n1. `max` -> utilizado para obter o item de maior valor da lista\n1. `min` -> utilizado para obter o item de menor valor da lista\n\"\"\"\nnumbers = [ 3, 94,  2, 94, 72, 58, 72, 52]\nprint(type(numbers))\nprint(type(numbers) == list)\nprint(len(numbers))\nprint(max(numbers))\nprint(min(numbers))\n\"\"\"\n## M\u00e9todos\nA lista \u00e9 uma classe e, por isso, tem m\u00e9todos. Alguns dos principais m\u00e9todos da lista ser\u00e3o mostrados a seguir:\n1. `append` -> Adiciona um item no final da lista. Recebe um parametro: o item que ser\u00e1 adicionado. Retorna `None`;\n1. `insert` -> Adiciona um item, em uma posi\u00e7\u00e3o espec\u00edfica da lista. Recebe dois parametros: o primeiro parametro \u00e9 o indice onde o item, do segundo parametro, ser\u00e1 inserido na lista. Retorna `None`;\n1. `remove` -> Remove o item de uma lista, utilizando o pr\u00f3prio item. Recebe um parametro: o item que ser\u00e1 removido. Retorna `None`;\n1. `pop` -> Remove um item, em uma posi\u00e7\u00e3o espec\u00edfica da lista, se n\u00e3o for espec\u00edficado a posi\u00e7\u00e3o \u00e9 removido o \u00faltimo item da lista. Recebe um parametro: o indice do item que ser\u00e1 removido. Retorna o item foi removido;\n1. `index` -> Retorna o indice de um item da lista. Recebe um parametro: o item que se deseja obter o indice. Retorna o indice do item passado como argumento;\n1. `count` -> Conta a ocorrencia de um item em uma lista. Recebe um parametro: o item que se deseja contar as ocorrencias. Retorna a ocorrencia do item passado como argumento;\n1. `sort` -> Organiza a lista em ordem crescente. N\u00e3o recebe parametros. Retorna `None`;\n1. `reverse` -> Inverte a ordem da lista. N\u00e3o recebe parametros. Retorna `None` (Uma outra maneira de fazer esta opera\u00e7\u00e3o e retornar uma nova lista \u00e9 `<var_list>[::-1]`)\n1. `copy` -> Cria uma nova lista (c\u00f3pia) indenpedente da lista original (modifica\u00e7\u00f5es na nova lista n\u00e3o afeta a lista original). N\u00e3o recebe parametros. Retorna a nova lista criada;\n1. `clear` -> Limpa uma lista, tornando-a uma lista vazia (sem itens, ou de tamanho zero). N\u00e3o recebe parametros. Retorna `None`.\n1. `extend` -> Concatena uma lista a outra lista. Recebe um parametro: a lista que vai ser concatenada. Retorna `None`.\n\"\"\"\nguests = ['Matheus', 'Luana', 'Lucas', 'Alfredo', 'J\u00e9ssica', 'Rodrigo', 'Ely', 'Jo\u00e3o']\n\nguests.append('Carol')\nprint(f'convidados: {guests}')\n\nguests.insert(1, 'Adriana')\nprint(f'convidados: {guests}')\n\nguests.remove('Lucas')\nprint(f'convidados: {guests}')\n\nname = guests.pop()\nprint(f'nome: {name}, convidados: {guests}')\n\nname = guests.pop(3)\nprint(f'nome: {name}, convidados: {guests}')\n\nindex = guests.index('Luana')\nprint(f'indice: {index}')\n\nguests[-1] = 'Alfredo'\ntimes = guests.count('Alfredo')\nprint(f'vezes: {times}')\n\nguests.sort()\nprint(f'convidados: {guests}')\n\nguests.reverse()\nprint(f'convidados: {guests}')\n\nother_guests = guests.copy()\nprint(f'outros convidados: {other_guests}, convidados: {guests}')\n\nguests2 = guests\nguests.clear()\nprint(f'outros convidados: {other_guests}, convidados 2: {guests2}, guests: {guests}')\n\nguests.append('Franciele')\nguests.append('Fabio')\nprint(guests)\nguests.extend(other_guests)\nprint(f'outros convidados: {other_guests}, convidados: {guests}')\n\"\"\"\n## *Built-in function* map\nNo Python, temos a *built-in function* `map`, utilizada para transformar cada elemento da lista, de acordo com uma fun\u00e7\u00e3o definida pelo desenvolvedor. No exemplo abaixo, vamos calcular a raiz quadrada de cada elemento da lista `numbers`, utilizando a *built-in function* `map` e a fun\u00e7\u00e3o `math.sqrt`.\n\nA *built-in function* `map` recebe dois parametros:\n1. Uma fun\u00e7\u00e3o que recebe um parametro. Essa fun\u00e7\u00e3o vai ser mapeada em cada item da lista;\n1. A lista onde a fun\u00e7\u00e3o ser\u00e1 mapeada.\n\"\"\"\nimport math\n\nnumbers = [ 3, 94,  2, 39, 72, 58, 75, 52]\n\nsquare_roots = list(map(math.sqrt, numbers))\nprint(square_roots)\n\"\"\"\n## *Built-in function* filter\nNo Python, temos a *built-in function* `filter`, utilizada para filtrar os elementos da lista, de acordo com uma fun\u00e7\u00e3o definida pelo desenvolvedor. Esta fun\u00e7\u00e3o, chamada de filtro, deve receber um parametro. Este parametro representa um item da lista. Se esta fun\u00e7\u00e3o retornar `True`, ent\u00e3o o elemento recebido permanece na lista. se a fun\u00e7\u00e3o retornar `False`, ent\u00e3o o elemento \u00e9 retirado da lista. \u00c9 importante salientar que \u00e9 gerada uma nova lista, com o filtro aplicado.\nNo exemplo abaixo, vamos filtrar os elementos \u00edmpares da lista `numbers`, isto \u00e9, vamos manter o elementos pares. Para isso, vamos definir uma fun\u00e7\u00e3o filtro `is_even`, que verifica se o argumento \u00e9 par, e vamos utilizar a *built-in function* `filter`.\n\nA *built-in function* `filter` recebe dois parametros:\n1. Uma fun\u00e7\u00e3o filtro, que recebe um parametro. Essa fun\u00e7\u00e3o vai ser aplicada em cada item da lista;\n1. A lista onde a fun\u00e7\u00e3o filtro ser\u00e1 aplicada.\n\"\"\"\ndef is_even(x):\n    return (x % 2) == 0\n\nnumbers = [ 3, 94,  2, 39, 72, 58, 75, 52]\n\neven = list(filter(is_even, numbers))\nprint(even)\n\"\"\"\n# Tupla\n\nAs demais estruturas acima permitem que seja alterada, ou seja, \u00e9 poss\u00edvel alterar os valores internos. Esta estrutura n\u00e3o permite altera\u00e7\u00e3o, imut\u00e1vel, dos itens ap\u00f3s a constru\u00e7\u00e3o. Ela \u00e9 interessante para ser utilizadas em conjunto com set, pois eles necessitam que os dados sejam imut\u00e1veis e na chave de um dicion\u00e1rio.\n\"\"\"\n# Cria\u00e7\u00e3o de tuplas\ntlp1 = (82,'edge',2+1j, True)\ntlp2 = (1,)\nvar1 = (1) # N\u00e3o \u00e9 uma tupla\ntlp3 = tuple([1,2])\n\n# Tamanho da tupla\nlen(tlp1)\n\n# Acessar os valores a partir dos \u00edndeces\nprint(tlp1[2])\nprint(tlp1[-2])\n\n# - Slice\nprint(tlp1[1:3])\n\n# - Casting\nlist1 = list(tlp1)\nset1 = set(tlp1)\n\n# Juntar tuplas\nprint( tlp1 + tlp2 )\n\"\"\"\n# Conjunto (Set)\n\nUm set ou conjunto \u00e9 uma estrutura de dados que n\u00e3o permite a repeti\u00e7\u00e3o de elementos.\n\"\"\"\n# Cria\u00e7\u00e3o de set\nset1 = set([1,2,3,2])\nset2 = {1,2,3,2}\nset3 = set()\nvar1 = {} # N\u00e3o \u00e9 um set\n\n# Tamanho de um set\nlen(set1)\n\n# Verificar se um item est\u00e1 no set\nprint( 1 in set1 )\nprint( 1 not in set1 )\n\n# - Adi\u00e7\u00e3o de item(s)\nset1.add(6)\nset2.update([5,4,7,10])\nset1.union(set2) # Este m\u00e9todo s\u00f3 funciona para set\n\n# Remo\u00e7\u00e3o do primeiro item\nset1.pop() # Remove o primeiro\nset1.remove(2)\nset1.clear() # Remove todos os itens\n\"\"\"\n# Dicion\u00e1rio\n\nEssa estrutura tem o conceito chave - valor, ou seja, a partir de uma chave tem um valor\/objeto. Por exemplo, na nossa sociedade temos o CPF que a partir desse n\u00famero podemos identificar a pessoa (Nome,Data de Nascimento, ...).\n\"\"\"\n# Cria\u00e7\u00e3o de um dicion\u00e1rio Create a dictionary\ndic1 = {}\ndic2 = dict()\ndic3 = {\n    1: 'abc',\n    'a': 'd'\n}\ndic4 = {\n\t1: 1,\n\t1: 'a'\n}\n# Adi\u00e7\u00e3o de uma nova chave\ndic3[10] = '10'\n\n# Tamanho\nlen(dic3)\n\n# Acessar os valores a partir das chaves\nprint(dic3[1])\n\n# Remo\u00e7\u00e3o de uma chave\ndel dic3[10]\n\n# Verifica se a chave est\u00e1 no dicion\u00e1rio\nprint(1 in dic3)\n\n# Pegar todas as chaves\nprint(dic3.keys())\n\n# Pegar todas os valores\nprint(dic3.values())\n\n# Pegar todas as chave\/valor\nprint(dic3.items())","meta":"{'source': 'AI4Code', 'id': '1f52872cfa4c81'}"}
{"id":"17851","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom sklearn.impute import SimpleImputer # missing data imputing\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score, precision_score\nimport matplotlib.pyplot as plt\n\nimport xgboost as xgb\nimport lightgbm as lgb\n\nimport os\nprint(os.listdir(\"..\/input\"))\n# read train and test data\ndata_train = pd.read_csv('..\/input\/train.csv')\ndata_test = pd.read_csv('..\/input\/test.csv')\n\"\"\"\n# A glance at the data\n\"\"\"\ndata_train.head()\ndata_test.head()\n# check column datatypes\ndata_train.info()\n\"\"\"\n# Data processing\n\"\"\"\n\"\"\"\n## Handle missing values\n\"\"\"\n# check for missing values\nprint(\"Missing Values in data_train: \", data_train.isnull().sum(), sep = \"\\n\")\nprint()\nprint(\"Missing Values in data_test: \", data_test.isnull().sum(), sep = \"\\n\")\n# check age distribution in both datasets\nplt.subplot(1, 2, 1)\ndata_train.Age.hist()\nplt.xlabel('Age (data_train)')\nplt.ylabel('# of passengers')\n\nplt.subplot(1, 2, 2)\ndata_test.Age.hist()\nplt.xlabel('Age (data_test)')\nplt.ylabel('# of passengers')\n\n# Ages are continuously distributed with a single mode. Filling the missing values\n# with the most frequent value is appropriate.\n\n# fill missing values for Age with the most frequent value\nimp_age = SimpleImputer(missing_values = np.nan, strategy='most_frequent')\n\n# for data_train\nimp_age.fit(data_train[['Age']])\ndata_train['Age'] = imp_age.transform(data_train[['Age']])\n\n# for data_test\nimp_age.fit(data_test[['Age']])\ndata_test['Age'] = imp_age.transform(data_test[['Age']])\n# check cabin info in both datasets\nprint(\"Cabin values in data_train: \", data_train.Cabin.unique().size)\nprint()\nprint(\"Cabin values in data_test: \", data_test.Cabin.unique().size)\n\n# Cabin has many discrete values. Adding a new discrete value \"Unknown\" to this\n# category will not have significant impact.\n\n# fill missing values for Cabin with \"Unknown\"\ndata_train.Cabin.fillna(\"Unknown\", inplace = True)\ndata_test.Cabin.fillna(\"Unknown\", inplace = True)\n# check embark info in data_train\nprint(data_train.Embarked.value_counts())\n\n# Only 3 categories found in this column. Missing values are filled by the\n# most frequent value.\ndata_train.Embarked.fillna(\"S\", inplace = True)\n# check fair info in data_test\ndata_test.Fare.hist()\nplt.xlabel('Fare (data_test)')\nplt.ylabel('# of passengers')\n\n# A large amount of passangers didn't pay their fare.\n# The missing values in the Fare column are filled by 0.\ndata_test.Fare.fillna(0, inplace = True)\n# Check the missing values again after imputing\nprint(\"Missing Values in data_train: \", data_train.isnull().sum(), sep = \"\\n\")\nprint()\nprint(\"Missing Values in data_test: \", data_test.isnull().sum(), sep = \"\\n\")\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\n\"\"\"\n## Pclass and Survive\n\"\"\"\n# visulize the relationship between pclass and survive\npclass_survive_crosstbl = pd.crosstab(data_train.Pclass, data_train.Survived)\n\n# print(pclass_survive_crosstbl)\n\npassanger_num_pclass = pclass_survive_crosstbl.sum(axis = 1)\n\n# calculate survivor rate for each pclass\npclass_survive_crosstbl = pclass_survive_crosstbl.divide(passanger_num_pclass, axis = 0).round(2)\n\npclass_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('pclass (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Title and Survive\n\"\"\"\n# extract titles for the passengers\ntitle_train = data_train.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\ntitle_test = data_test.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\n\nprint(title_train.unique())\nprint()\nprint(title_test.unique())\nprint()\n\n# merge the titles by social status\ntitle_to_replace = {'Mrs': 'Ordinary_female', 'Miss': 'Ordinary_female', \n                    'Mme': 'Ordinary_female', 'Ms': 'Ordinary_female', \n                    'Mlle': 'Ordinary_female', 'Mr': 'Ordinary_male', \n                    'Master': 'Ordinary_male', 'Capt': 'Official', \n                    'Major': 'Official', 'Dr': 'Official', \n                    'Col': 'Official', 'Rev': 'Official', \n                    'Don': 'Noble_male', 'Jonkheer': 'Noble_male', \n                    'Sir': 'Noble_male', 'Dona': 'Noble_female', \n                    'Lady': 'Noble_female', 'Countess': 'Noble_female'}\n# add title column in data_train\ndata_train['Title'] = title_train.map(title_to_replace)\ndata_test['Title'] = title_test.map(title_to_replace)\n\n# check if the Tile column matches the Name column\nprint(data_train[['Name', 'Title']].head())\nprint()\nprint(data_test[['Name', 'Title']].head())\n\n# remove the Name column\ndata_train = data_train.drop('Name', axis = 1)\ndata_test = data_test.drop('Name', axis = 1)\n# visulize the relationship between Title and survive\ntitle_survive_crosstbl = pd.crosstab(data_train.Title, data_train.Survived)\n\n# print(title_survive_crosstbl)\n\npassanger_num_title = title_survive_crosstbl.sum(axis = 1)\n\n# calculate survivor rate for each title\ntitle_survive_crosstbl = title_survive_crosstbl.divide(passanger_num_title, axis = 0).round(2)\n\ntitle_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Title (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Sex and Survive\n\"\"\"\n# visulize the relationship between sex and survive\nsex_survive_crosstbl = pd.crosstab(data_train.Sex, data_train.Survived)\n\n# print(sex_survive_crosstbl)\n# calculate survivor rate for each sex\nsex_survive_crosstbl = sex_survive_crosstbl.divide(sex_survive_crosstbl.sum(axis = 1), axis = 0)\n\nsex_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Sex (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Sex and Survive\n\"\"\"\n# Segment the Age column\nage_qcut_train = pd.cut(data_train.Age, [0, 20, 40, 60, 80])\nage_qcut_test = pd.cut(data_test.Age, [0, 20, 40, 60, 80])\n\n# encode the age bins for data_train\nle = LabelEncoder()\nle.fit(age_qcut_train)\ndata_train['Age_bins'] = le.transform(age_qcut_train)\n\n# for data_test\ndata_test['Age_bins'] = le.transform(age_qcut_test)\n\n # visulize the relationship between age and survive\nage_survive_crosstbl = pd.crosstab(data_train.Age_bins, data_train.Survived)\n# print(age_survive_crosstbl)\n# calculate survivor rate for each age\nage_survive_crosstbl = age_survive_crosstbl.divide(age_survive_crosstbl.sum(axis = 1), axis = 0)\nage_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Age_bins (data_train)')\nplt.ylabel('Survival Rate')\nplt.xticks(np.arange(0, 4), ('0~20', '20~40', '40~60', '60~80'))\n\"\"\"\n## Family Size and Survive\n\"\"\"\n# create new family size column by combining SibSp and Parch column\ndata_train['famsz'] = data_train.SibSp + data_train.Parch + 1\ndata_test['famsz'] = data_test.SibSp + data_test.Parch + 1\n\n# visulize the relationship between famsz and survive\nfamsz_survive_crosstbl = pd.crosstab(data_train.famsz, data_train.Survived)\n\n# print(famsz_survive_crosstbl)\n# calculate survivor rate for each famsz\nfamsz_survive_crosstbl = famsz_survive_crosstbl.divide(famsz_survive_crosstbl.sum(axis = 1), axis = 0)\n\nfamsz_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Family Size (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Fare and Survive\n\"\"\"\n# calculate fare\/person\ndata_train['FarePP'] = data_train['Fare'] \/ data_train['famsz']\ndata_test['FarePP'] = data_test['Fare'] \/ data_test['famsz']\n\n# Segment the FarePP column\nfarepp_qcut_train = pd.cut(data_train.FarePP, [0, 5, 10, 20, 30, 600], include_lowest = True)\nfarepp_qcut_test = pd.cut(data_test.FarePP, [0, 5, 10, 20, 30, 600], include_lowest = True)\n\nfarepp_qcut_train.value_counts()\n# encode the farepp bins for data_train\nle = LabelEncoder()\nle.fit(farepp_qcut_train)\ndata_train['FarePP_bins'] = le.transform(farepp_qcut_train)\n\n# for data_test\ndata_test['FarePP_bins'] = le.transform(farepp_qcut_test)\n# visulize the relationship between farepp and survive\nfarepp_survive_crosstbl = pd.crosstab(data_train.FarePP_bins, data_train.Survived)\n\n# print(farepp_survive_crosstbl)\n# calculate survivor rate for each farepp\nfarepp_survive_crosstbl = farepp_survive_crosstbl.divide(farepp_survive_crosstbl.sum(axis = 1), axis = 0)\n\nfarepp_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('FarePP_bins (data_train)')\nplt.ylabel('Survival Rate')\nplt.xticks(np.arange(0, 5), ('0~5', '5~10', '10~20', '20~30', '30~600'))\n\"\"\"\n## Deck and Survive\n\"\"\"\n# Extract Deck info from the Cabin column\ndata_train['Deck'] = data_train.Cabin.str.slice(0,1)\ndata_test['Deck'] = data_test.Cabin.str.slice(0,1)\n\n# visulize the relationship between deck and survive\ndeck_survive_crosstbl = pd.crosstab(data_train.Deck, data_train.Survived)\n\n# calculate survivor rate for each deck\ndeck_survive_crosstbl = deck_survive_crosstbl.divide(deck_survive_crosstbl.sum(axis = 1), axis = 0)\n\ndeck_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Deck (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Embark and Survive\n\"\"\"\n# visulize the relationship between embark and survive\nembark_survive_crosstbl = pd.crosstab(data_train.Embarked, data_train.Survived)\n\n# calculate survivor rate for each embark\nembark_survive_crosstbl = embark_survive_crosstbl.divide(embark_survive_crosstbl.sum(axis = 1), axis = 0)\n\nembark_survive_crosstbl.plot(kind = \"bar\", stacked = True)\nplt.xlabel('Embark (data_train)')\nplt.ylabel('Survival Rate')\n\"\"\"\n## Drop non-informative or redundant columns\n\"\"\"\n# drop non-informative or redundant columns\nPassengerId_train = data_train.PassengerId\nPassengerId_test = data_test.PassengerId\n\ndata_train = data_train.drop(['PassengerId', 'Age', 'Ticket', 'Fare', 'Cabin', 'FarePP'], axis = 1)\ndata_test = data_test.drop(['PassengerId', 'Age', 'Ticket', 'Fare', 'Cabin', 'FarePP'], axis = 1)\n# check processed data (train)\ndata_train.head()\n# check processed data (test)\ndata_test.head()\n\"\"\"\n## One Hot Encoding\n\"\"\"\n# one hot encoding for Pclass\nPclass_one_hot_train = pd.get_dummies(data_train['Pclass'], prefix='Pclass')\nPclass_one_hot_test = pd.get_dummies(data_test['Pclass'], prefix='Pclass')\n\n# one hot encoding for Sex\nSex_one_hot_train = pd.get_dummies(data_train['Sex'], prefix='Sex')\nSex_one_hot_test = pd.get_dummies(data_test['Sex'], prefix='Sex')\n\n# one hot encoding for SibSp\nSibSp_one_hot_train = pd.get_dummies(data_train['SibSp'], prefix='SibSp')\nSibSp_one_hot_test = pd.get_dummies(data_test['SibSp'], prefix='SibSp')\n\n# one hot encoding for Parch\nParch_one_hot_train = pd.get_dummies(data_train['Parch'], prefix='Parch')\nParch_one_hot_test = pd.get_dummies(data_test['Parch'], prefix='Parch')\n\n# one hot encoding for Embarked\nEmbarked_one_hot_train = pd.get_dummies(data_train['Embarked'], prefix='Embarked')\nEmbarked_one_hot_test = pd.get_dummies(data_test['Embarked'], prefix='Embarked')\n\n# one hot encoding for Title\nTitle_one_hot_train = pd.get_dummies(data_train['Title'], prefix='Title')\nTitle_one_hot_test = pd.get_dummies(data_test['Title'], prefix='Title')\n\n# one hot encoding for Age_bins\nAge_bins_one_hot_train = pd.get_dummies(data_train['Age_bins'], prefix='Age_bins')\nAge_bins_one_hot_test = pd.get_dummies(data_test['Age_bins'], prefix='Age_bins')\n\n# one hot encoding for famsz\nfamsz_one_hot_train = pd.get_dummies(data_train['famsz'], prefix='famsz')\nfamsz_one_hot_test = pd.get_dummies(data_test['famsz'], prefix='famsz')\n\n# one hot encoding for FarePP_bins\nFarePP_bins_one_hot_train = pd.get_dummies(data_train['FarePP_bins'], prefix='FarePP_bins')\nFarePP_bins_one_hot_test = pd.get_dummies(data_test['FarePP_bins'], prefix='FarePP_bins')\n\n# one hot encoding for Deck\nDeck_one_hot_train = pd.get_dummies(data_train['Deck'], prefix='Deck')\nDeck_one_hot_test = pd.get_dummies(data_test['Deck'], prefix='Deck')\n\n# join the data frames\n# for data_train\none_hot_train = pd.concat([Pclass_one_hot_train, Sex_one_hot_train, SibSp_one_hot_train,\n                           Parch_one_hot_train, Embarked_one_hot_train, Title_one_hot_train,\n                           Age_bins_one_hot_train, famsz_one_hot_train, FarePP_bins_one_hot_train,\n                          Deck_one_hot_train, data_train.Survived], axis = 1, sort = False)\n\n# for data_test\none_hot_test = pd.concat([Pclass_one_hot_test, Sex_one_hot_test, SibSp_one_hot_test,\n                           Parch_one_hot_test, Embarked_one_hot_test, Title_one_hot_test,\n                           Age_bins_one_hot_test, famsz_one_hot_test, FarePP_bins_one_hot_test,\n                          Deck_one_hot_test], axis = 1, sort = False)\n# check if the columns are same between one_hot_train and one_hot_test\nset(list(one_hot_train)) ^ set(list(one_hot_test))\n# check the one hot encoded data (train)\n# no Deck_T  & Title_Noble_male in data_test\none_hot_train = one_hot_train.drop('Deck_T', axis = 1)\none_hot_train = one_hot_train.drop('Title_Noble_male', axis = 1)\n\nprint(one_hot_train.shape)\none_hot_train.head()\n# check the one hot encoded data (test)\n# no Parch_9 in the data_train\none_hot_test = one_hot_test.drop('Parch_9', axis = 1)\n\nprint(one_hot_test.shape)\none_hot_test.head()\n\"\"\"\n# Model Building\n\"\"\"\n# split data_train\ny = one_hot_train.Survived\nX = one_hot_train.drop('Survived', axis=1)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 12)\n\"\"\"\n## XGBoost and Parameter Tuning\n\"\"\"\n# xgboost parameter tuning (RandomizedSearchCV)\n\nparams_xgb = {'min_child_weight': range(5,10),\n           'gamma': [i\/10.0 for i in range(0,10, 2)],\n           'subsample': [i\/10.0 for i in range(5, 10)],\n           'colsample_bytree': [i\/10.0 for i in range(5, 10)],\n           'max_depth': range(5,10),\n           'n_estimators': [400, 600, 1000, 1500],\n           'learning_rate': [0.1, 0.01, 0.001]}\n\nmy_xgb = xgb.XGBClassifier(silent = 1, nthread = 1)\n\n# split train for parameter tuning\nskf = StratifiedKFold(n_splits = 5, shuffle = True, random_state = 12)\n\n# tuning with random search\nrandom_search_xgb = RandomizedSearchCV(my_xgb, param_distributions = params_xgb,\n                                   n_iter = 10,\n                                   scoring = 'accuracy', n_jobs = 4,\n                                   cv = skf.split(X_train,y_train),\n                                   verbose = False, random_state = 12)\n\n# predict with tuned xgboost\nrandom_search_xgb.fit(X_train, y_train)\npredictions_xgb = random_search_xgb.predict(X_test)\n\n# accuracy check\naccuracy_xgb = accuracy_score(y_test, predictions_xgb)\n\nprecision_xgb = precision_score(y_test, predictions_xgb)\n\nprint('Accuracy (xgb): ', accuracy_xgb)\nprint('Precision (xgb): ', precision_xgb)\nprint('Best Parameters (xgb): ', random_search_xgb.best_params_)\n\"\"\"\n## LightGBM and Parameter Tuning\n\"\"\"\n# lgbm parameter tuning (RandomizedSearchCV)\n\nparams_lgbm = {'max_depth' : range(5,10),\n               'num_leaves': [2**i for i in range(5, 10)],\n               'max_bin': [100, 300, 500],\n               'subsample_for_bin': [50, 100, 200],\n               'min_child_weight': range(5,10),\n               'min_child_samples': range(5,10),\n               'min_split_gain': [i\/10.0 for i in range(0, 10)],\n               'colsample_bytree': [i\/10.0 for i in range(5, 10)],\n               'n_estimators': [400, 600, 1000, 1500],\n               'subsample': [i\/10.0 for i in range(5, 10)]}\n\nmy_lgbm = lgb.LGBMClassifier(boosting_type = 'dart', objective = 'binary', nthread = 1,\n                             learning_rate = 0.01, scale_pos_weight = 1.1,\n                             num_class = 1, metric = 'accuracy')\n\nrandom_search_lgbm = RandomizedSearchCV(my_lgbm, param_distributions = params_lgbm,\n                                   n_iter = 10,\n                                   scoring = 'accuracy', n_jobs = 4,\n                                   cv = skf.split(X_train,y_train),\n                                   verbose = False, random_state = 12)\n\n# predict with tuned lgbm\nrandom_search_lgbm.fit(X_train, y_train)\npredictions_lgbm = random_search_lgbm.predict(X_test)\n\n# classification_report(y_test, predictions)\naccuracy_lgbm = accuracy_score(y_test, predictions_lgbm)\nprecision_lgbm = precision_score(y_test, predictions_lgbm)\n\nprint('Accuracy: ', accuracy_lgbm)\nprint('Precision: ', precision_lgbm)\nprint('Best Parameters (lgbm): ', random_search_lgbm.best_params_)\n\"\"\"\n## Final Prediction\n\"\"\"\n# make prediction for data_test\npredictions_xgb_test = random_search_xgb.predict(one_hot_test)\n\npredictions_xgb_test_df = pd.DataFrame({'PassengerId': PassengerId_test,\n                                         'Survived': predictions_xgb_test})\n\n# write the results\npredictions_xgb_test_df.to_csv('titanic_submission.csv', sep=',', index = False)","meta":"{'source': 'AI4Code', 'id': '209abb22b48eaf'}"}
{"id":"72706","text":"# 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\n!pwd\nimport matplotlib.pyplot as plt\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\n\"\"\"\n## 1. Reading the data\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/chennai-water-management\/chennai_reservoir_levels.csv',\n                parse_dates=['Date'], dayfirst=True)\n#df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y')\ndf.head()\ndf.dtypes\ndf.isnull().sum()\ndf.Date.dt.year.min(), df.Date.dt.year.max()\nfig = make_subplots(rows=2, cols=2,\n                   subplot_titles=['Poondi (in mcft)',\n                                  'Redhills (in mcft)',\n                                  'Chembarambakkam (in mcft)',\n                                  'Cholavaram (in mcft)'])\n\nfig.add_trace(go.Scatter(x=df.Date, y=df.POONDI, name='Poondi'), row=1, col=1)\nfig.add_trace(go.Scatter(x=df.Date, y=df.REDHILLS, name='Redhills'), row=1, col=2)\nfig.add_trace(go.Scatter(x=df.Date, y=df.CHEMBARAMBAKKAM, name='Chembarambakkam'), row=2, col=1)\nfig.add_trace(go.Scatter(x=df.Date, y=df.CHOLAVARAM, name='Cholavaram'), row=2, col=2)\n\nfig.update_layout(title_text = \"Water availability in Chennai's four major reserviours {}-{}\".format(df.Date.dt.year.min(), df.Date.dt.year.max()))\n\nfig.show()\ndf_tidy = df.melt(id_vars = ['Date'], var_name='Resoviour', value_name='Water_Level')\ndf_tidy.head()\nimport plotly.express as px\n\npx.line(df_tidy,\n       x='Date',\n       y='Water_Level',\n        facet_col=\"Resoviour\",\n        facet_col_wrap=2,\n        color='Resoviour',\n       title=\"Water availability in Chennai's four major reserviours {}-{}\".format(df.Date.dt.year.min(), df.Date.dt.year.max()))\nfig = px.line(df.melt(id_vars=['Date'],var_name='Resoviour',value_name='Water_Level'), \n              x=\"Date\", \n              y=\"Water_Level\", \n              color=\"Resoviour\",                  \n              facet_col=\"Resoviour\",\n              facet_col_wrap=1,\n              height=1000\n             )\nfig.update_yaxes(matches=None)\nfig.show()\n\"\"\"\n**Inference:**\n- We could clearly see that evey year there is a decremental phase and a replenishment phase (mainly during october to december)\n- There was a very bad water scarcity phase seen during 2004.\n- We can also see a bad phase during 2014-15 but there was to water availability in two reservoirs (Redhills and Chembarambakkam) and so it was a savior.\n- Now coming to recent times, the data shows that there is no water availability in any of the four major reservoirs.\n\"\"\"\n\"\"\"\n## 2. Look at the overall water levels\n\n\"\"\"\ndf['total'] = df.drop(columns='Date').sum(axis=1)\ndf.head()\npx.line(df,\n       x='Date',\n       y='total',\n       title='Total water availability from all four resoviours in mcft')\n\"\"\"\n## 3. Rainfall Levels\n\"\"\"\nrain_df = pd.read_csv('\/kaggle\/input\/chennai-water-management\/chennai_reservoir_rainfall.csv',\n                     parse_dates=['Date'], dayfirst=True)\nrain_df.head()\nrain_df.dtypes\npx.line(rain_df.melt(id_vars=['Date'], var_name='Resoviour', value_name='Rainfall'),\n      x='Date',\n      y='Rainfall',\n      facet_col='Resoviour',\n      facet_col_wrap=2,\n      color='Resoviour')\n\nrain_df['YearMonth'] = pd.to_datetime(rain_df.Date.dt.year.astype(str)+rain_df.Date.dt.month.astype(str), format='%Y%m')\nrain_df.head()\nrain_df.YearMonth.value_counts()\nrain_df['total'] = rain_df.drop(columns=['Date', 'YearMonth']).sum(axis=1)\nrain_df.head()\n\"\"\"\n## 4. Add a season column and use it as color in the bar plot\n\"\"\"\nrain_df.groupby('YearMonth').total.sum().reset_index()\npx.bar(rain_df.groupby('YearMonth').total.sum().reset_index(),\n       x='YearMonth',\n       y='total',\n      #color='season'\n      )\n\"\"\"\n## 4. Total Yearly rainfall\n\"\"\"\nrain_df['Year'] = pd.to_datetime(rain_df.Date.dt.year.astype(str), format='%Y')\nrain_df.head()\nmonthly_rain_df = rain_df.groupby('YearMonth').total.sum().reset_index()\nmonthly_rain_df\n# Creating Season column\nmonth_to_season = {1: 'winter', 2: 'winter', 3: 'summer', 4: 'summer', 5: 'summer', 6: 'monsoon', 7: 'monsoon', 8: 'monsoon', 9: 'monsoon',\n 10: 'post-monsoon', 11: 'post-monsoon', 12: 'post-monsoon'}\nmonthly_rain_df['season'] = monthly_rain_df.YearMonth.dt.month.map(month_to_season) \nmonthly_rain_df\npx.bar(monthly_rain_df,\n      x='YearMonth',\n      y='total',\n      color='season',\n      title='Yearly rainfall in the four major resoviour regions in mm'\n      )\n\"\"\"\n## 5. Water Shortage estimation\n\"\"\"\npx.bar(df.query(\"Date.dt.month== 3 and Date.dt.day== 1\"),\n       x='Date',\n       y='total',\n       title='Availability of water in total at the beginning of summer')","meta":"{'source': 'AI4Code', 'id': '85da8294136eb5'}"}
{"id":"95250","text":"import pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\ndf=pd.read_csv('..\/input\/chinese-mnist-digit-recognizer\/chineseMNIST.csv')\ndf.head()\ncols=df.columns.tolist()\ncols.remove(\"label\")\ncols.remove(\"character\")\nX=df[cols]\ny=df[\"character\"]\ndf['label'].replace(100, 11, inplace=True)\ndf['label'].replace(1000, 12, inplace=True)\ndf['label'].replace(10000, 13, inplace=True)\ndf['label'].replace(100000000, 14, inplace=True)\nX = df.drop(['label', 'character'], axis = 1)\nY = df['label']\nX=X.values\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 42)\nfrom numpy import mean\nfrom numpy import std\nfrom matplotlib import pyplot\nfrom sklearn.model_selection import KFold\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.utils import to_categorical\n\"\"\"\nBASELINE MODEL\n\"\"\"\ndef load_dataset():\n  # load dataset\n  (trainX, trainY), (testX, testY) = (X_train,Y_train),( X_test, Y_test)\n  # reshape dataset to have a single channel\n  trainX = trainX.reshape((trainX.shape[0], 64, 64, 1))\n  testX = testX.reshape((testX.shape[0], 64, 64, 1))\n  # one hot encode target values\n  trainY = to_categorical(trainY)\n  testY = to_categorical(testY)\n  return trainX, trainY, testX, testY\n  # scale pixels\ndef prep_pixels(train, test):\n  # convert from integers to floats\n  train_norm = train.astype('float32')\n  test_norm = test.astype('float32')\n  # normalize to range 0-1\n  train_norm = train_norm \/ 255.0\n  test_norm = test_norm \/ 255.0\n  # return normalized images\n  return train_norm, test_norm\ndef define_model():\n  model = Sequential()\n  model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  input_shape=(64, 64, 1)))\n  model.add(MaxPooling2D((2, 2)))\n  model.add(Flatten())\n  model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))\n  model.add(Dense(15, activation='softmax'))\n  # compile model\n  opt = SGD(lr=0.01, momentum=0.9)\n  model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n  return model\ndef evaluate_model(dataX, dataY, n_folds=5):\n  scores, histories = list(), list()\n  # prepare cross validation\n  kfold = KFold(n_folds, shuffle=True, random_state=1)\n  # enumerate splits\n  for train_ix, test_ix in kfold.split(dataX):\n  # define model\n    model = define_model()\n    # select rows for train and test\n    trainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix],dataY[test_ix]\n    # fit model\n    history = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX,testY), verbose=0)\n    # evaluate model\n    _, acc = model.evaluate(testX, testY, verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    # append scores\n    scores.append(acc)\n    histories.append(history)\n  return scores, histories\n# plot diagnostic learning curves\ndef summarize_diagnostics(histories):\n  for i in range(len(histories)):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(histories[i].history['loss'], color='blue', label='train')\n    pyplot.plot(histories[i].history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(histories[i].history['accuracy'], color='blue', label='train')\n    pyplot.plot(histories[i].history['val_accuracy'], color='orange', label='test')\n  pyplot.show()\n# summarize model performance\ndef summarize_performance(scores):\n  # print summary\n  print('Accuracy: mean=%.3f std=%.3f, n=%d'% (mean(scores)*100, std(scores)*100,\n  len(scores)))\n  # box and whisker plots of results\n  pyplot.boxplot(scores)\n  pyplot.show()\n  # run the test harness for evaluating a model\ndef run_test_harness():\n    # load dataset\n  trainX, trainY, testX, testY = load_dataset()\n  # prepare pixel data\n  trainX, testX = prep_pixels(trainX, testX)\n  # evaluate model\n  scores, histories = evaluate_model(trainX, trainY)\n  # learning curves\n  summarize_diagnostics(histories)\n  # summarize estimated performance\n  summarize_performance(scores)\n  # entry point, run the test harness\nrun_test_harness()\n\"\"\"\nBaseline + Increasing Dropout + Batch Norm\n\"\"\"\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import BatchNormalization\ndef load_dataset():\n  # load dataset\n  (trainX, trainY), (testX, testY) = (X_train,Y_train),( X_test, Y_test)\n  # reshape dataset to have a single channel\n  trainX = trainX.reshape((trainX.shape[0], 64, 64, 1))\n  testX = testX.reshape((testX.shape[0], 64, 64, 1))\n  # one hot encode target values\n  trainY = to_categorical(trainY)\n  testY = to_categorical(testY)\n  return trainX, trainY, testX, testY\n  # scale pixels\ndef prep_pixels(train, test):\n  # convert from integers to floats\n  train_norm = train.astype('float32')\n  test_norm = test.astype('float32')\n  # normalize to range 0-1\n  train_norm = train_norm \/ 255.0\n  test_norm = test_norm \/ 255.0\n  # return normalized images\n  return train_norm, test_norm\ndef define_model():\n  model = Sequential()\n  model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same', input_shape=(64,64,1)))\n  model.add(BatchNormalization())\n  model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same'))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D((2, 2)))\n  model.add(Dropout(0.2))\n  model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same'))\n  model.add(BatchNormalization())\n  model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same'))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D((2, 2)))\n  model.add(Dropout(0.3))\n  model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same'))\n  model.add(BatchNormalization())\n  model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform',\n  padding='same'))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D((2, 2)))\n  model.add(Dropout(0.4))\n  model.add(Flatten())\n  model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n  model.add(BatchNormalization())\n  model.add(Dropout(0.5))\n  model.add(Dense(15, activation='softmax'))\n  # compile model\n  opt = SGD(lr=0.001, momentum=0.9)\n  model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n  return model\n\ndef evaluate_model(dataX, dataY, n_folds=5):\n  scores, histories = list(), list()\n  # prepare cross validation\n  kfold = KFold(n_folds, shuffle=True, random_state=1)\n  # enumerate splits\n  for train_ix, test_ix in kfold.split(dataX):\n  # define model\n    model = define_model()\n    # select rows for train and test\n    trainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix],dataY[test_ix]\n    # fit model\n    history = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX,testY), verbose=0)\n    # evaluate model\n    _, acc = model.evaluate(testX, testY, verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    # append scores\n    scores.append(acc)\n    histories.append(history)\n  return scores, histories\n# plot diagnostic learning curves\ndef summarize_diagnostics(histories):\n  for i in range(len(histories)):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(histories[i].history['loss'], color='blue', label='train')\n    pyplot.plot(histories[i].history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(histories[i].history['accuracy'], color='blue', label='train')\n    pyplot.plot(histories[i].history['val_accuracy'], color='orange', label='test')\n  pyplot.show()\n# summarize model performance\ndef summarize_performance(scores):\n  # print summary\n  print('Accuracy: mean=%.3f std=%.3f, n=%d'% (mean(scores)*100, std(scores)*100,\n  len(scores)))\n  # box and whisker plots of results\n  pyplot.boxplot(scores)\n  pyplot.show()\n  # run the test harness for evaluating a model\ndef run_test_harness():\n    # load dataset\n  trainX, trainY, testX, testY = load_dataset()\n  # prepare pixel data\n  trainX, testX = prep_pixels(trainX, testX)\n  # evaluate model\n  scores, histories = evaluate_model(trainX, trainY)\n  # learning curves\n  summarize_diagnostics(histories)\n  # summarize estimated performance\n  summarize_performance(scores)\n  # entry point, run the test harness\nrun_test_harness()","meta":"{'source': 'AI4Code', 'id': 'aed95fedf38012'}"}
{"id":"114339","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport plotly.express as px\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\n\n\ndata = pd.read_csv('..\/input\/palmer-archipelago-antarctica-penguin-data\/penguins_size.csv')\ndata.head()\ndata.shape\ndata.columns\ndata.info()\n\"\"\"\nThe dataset consists of 7 columns.\n\n* species: penguin species (Chinstrap, Ad\u00e9lie, or Gentoo)\n* culmen_length_mm: culmen length \n* culmen_depth_mm: culmen depth \n* flipper_length_mm: flipper length \n* body_mass_g: body mass \n* island: island name (Dream, Torgersen, or Biscoe) \n* sex: penguin sex\n\n**culmen length & depth :**\n\nThe culmen is the upper ridge of a bird's beak\n\n![](https:\/\/image.shutterstock.com\/z\/stock-vector-diagram-showing-parts-of-penguin-illustration-461548348.jpg)\n\"\"\"\n# Different types of species we have\n# Number of data points we have for each species.\nprint(\"Number of data points in each species\")\ndata['species'].value_counts().plot(kind = 'bar')\ndata['species'].value_counts()\n\"\"\"\n'Adelie' has most datapoints\n\"\"\"\n# Checking the percentage of missing values\nprint(\"Missing Values\")\n100*data.isnull().sum()\/len(data)\n\"\"\"\n***We have 5 columns which have missing values out of which 1 is categorical feature rest can be imputed** \n\"\"\"\n\"\"\"\n# Columns to be imputed\n\n* culmen_length_mm\n* culmen_depth_mm\n* flipper_length_mm\n* body_mass_g\n\"\"\"\ncol = ['culmen_depth_mm','culmen_length_mm','flipper_length_mm','body_mass_g']\nfor column in col:\n    data[column].fillna(data[column].median(),inplace = True)\ndata['sex'] = data['sex'].fillna('MALE')\nsns.set_style('whitegrid')\nsns.FacetGrid(data, hue =\"species\", size =4)\\\n   .map(plt.scatter,\"culmen_length_mm\",\"culmen_depth_mm\")\\\n   .add_legend();\nplt.show()\n\"\"\"\n# **Observations**\n\"\"\"\n\"\"\"\n* Using culmen_depth_mm and culmen_length_mm features, we can distinguish Adeline from others.\n* Seperating Chinstrap and Gentoo is a bit harder as they have some overlap points.\n\"\"\"\nplt.close();\nsns.set_style(\"whitegrid\");\nsns.pairplot(data, hue='species', size=4);\nplt.show()\n\"\"\"\n# **Observations**\n\"\"\"\n\"\"\"\n* culmen_length_mm and flipper_length_mm are the most useful features to identify various types of penguins\n* Gentoo can easily identified(linear seperable), Adeline and Chinastrap are quite hard as they have some overlapping points.\n\"\"\"\nsns.boxplot(x = 'species', y='culmen_length_mm', data = data)\nplt.show()\nsns.violinplot(x='species', y = 'culmen_depth_mm', data= data)\nplt.show()\nsns.swarmplot(x='species', y='flipper_length_mm', data = data)\nplt.show()\nsns.FacetGrid(data, hue=\"species\", height=6,)\\\n   .map(sns.kdeplot, \"body_mass_g\",shade=True)\\\n   .add_legend()\nplt.show()\n\"\"\"\n# Multivariate probability density, contour plot\n\"\"\"\nsns.jointplot(x=\"culmen_length_mm\", y=\"flipper_length_mm\",data = data, kind=\"kde\", height=7, space=0)\nsns.catplot(x=\"species\", y=\"culmen_depth_mm\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\n# Observation\n\"\"\"\n\"\"\"\n* In all the three species Male penguins are more than females and chinstrap species have highest culmen_depth.\n* The important observation which we can see is that there is three types of sex in Gentoo species, the third species is a '.' which could have entered by mistake. Let's look into it and see what we can do with it.\n\"\"\"\ndata[data['sex']=='.']\n\"\"\"\nLet's take a look into island feature to check which type of sex dominates in Biscoe island so that we can change this particular value to that.\n\"\"\"\nsns.catplot(x=\"island\", y=\"culmen_length_mm\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\nMale is the gender which dominates in both island feature and species feature therefore I will be replacing it with Male only.\n\"\"\"\ndata.loc[336,'sex'] = 'MALE'\nsns.catplot(x=\"species\", y=\"culmen_length_mm\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\n# Observation\n\"\"\"\n\"\"\"\nChinstrap have highest culmen length in both male and female sex\n\"\"\"\nsns.catplot(x=\"species\", y=\"culmen_depth_mm\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\n# Observation\n\"\"\"\n\"\"\"\nIn male category chinstrap have highest culmen depth\n\nIn Female category there is a fight between Adelie and Chinstrap but I think Adelie is winner\n\"\"\"\nsns.catplot(x=\"species\", y=\"flipper_length_mm\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\n# Observation\n\nGentoo have highest flipper length in both category\n\"\"\"\nsns.catplot(x=\"species\", y=\"body_mass_g\", hue=\"sex\", data=data,\n                height=6, kind=\"bar\", palette=\"muted\")\n\"\"\"\n# Observation\n\nGentoo have highest body weight in both male and female\n\"\"\"\nfig = sns.barplot(data= data['island'].value_counts().reset_index(), x='island', y='index')\nfig.set(xlabel='', ylabel='ISLANDS')\nplt.show()\n\"\"\"\n# Observation\n\nBiscoe Island contains maximum number of penguins\n\"\"\"\n\"\"\"\n# Island contains which species and how many\n\"\"\"\n# Total number of species \ndata.species.value_counts()\n\"\"\"\nLet's First go with Biscoe as it contains maximum number of penguins\n\"\"\"\ndf = data[data.island=='Biscoe']\nprint(df.species.value_counts())\ndf.species.value_counts().plot(kind='bar')\n\"\"\"\n# Observation\n\nThere are in total 344 penguins and out of which\n\n124 are Gentoo species\n68 Chinstrap\n152 Adelie\n\"\"\"\n\"\"\"\nAccording to the above graph and stats it's clear that **all the Gentoo penguins are in Biscoe island**\n\nAnd there is no Chinstrap penguins in Biscoe island\n\"\"\"\n\"\"\"\n# Let's proceed with Dream Island\n\"\"\"\ndf = data[data.island=='Dream']\nprint(df.species.value_counts())\ndf.species.value_counts().plot(kind='bar')\n\"\"\"\n# Observation\n\n**All the Chinstrap penguins live in Dream island and there is no Gentoo penguins in Dream island**\n\"\"\"\n\"\"\"\n# Torgersen Island\n\"\"\"\ndf = data[data.island=='Torgersen']\nprint(df.species.value_counts())\ndf.species.value_counts().plot(kind='bar')\n\"\"\"\n# Observation\n\n**Torgersen island Contains only Adelie penguins**\n\"\"\"\n\"\"\"\n# Concluding Observations from above insights\n\"\"\"\n\"\"\"\n* All chinstrap penguins live in Dream Island\n* All Gentoo penguins live in Biscoe Island\n* Adelie penguins are distributed everywhere\n* Torgersen Island contains only one type of penguin which is Adelie\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd227eb004706fc'}"}
{"id":"67857","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport math\nimport random\nimport pickle\nimport itertools\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix, label_ranking_average_precision_score, label_ranking_loss, coverage_error \n\nfrom sklearn.utils import shuffle\n\nfrom scipy.signal import resample\n\nimport matplotlib.pyplot as plt\n\nnp.random.seed(42)\n\nimport pickle\nfrom sklearn.preprocessing import OneHotEncoder\n\n\n\n\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Conv1D, MaxPooling1D, Softmax, Add, Flatten, Activation# , Dropout\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\n\n\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import confusion_matrix\nimport math\nimport random\nimport pickle\nimport itertools\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nnp.random.seed(42)\nimport tensorflow as tf\nimport tensorflow.keras as keras\n\n\"\"\"\n1.  # DATA ACQUISITION *\n\"\"\"\nprint(os.getcwd())\nmit_test_data = pd.read_csv(\"..\/input\/heartbeat\/mitbih_test.csv\", header=None)\nmit_train_data = pd.read_csv(\"..\/input\/heartbeat\/mitbih_train.csv\", header=None)\n\"\"\"\n# PRODUCE BALANCED DATASET train_df , test_df *\n\"\"\"\n# There is a huge difference in the balanced of the classes.\n# Better choose the resample technique more than the class weights for the algorithms.\nfrom sklearn.utils import resample\n\ndf_1=mit_train_data[mit_train_data[187]==1]\ndf_2=mit_train_data[mit_train_data[187]==2]\ndf_3=mit_train_data[mit_train_data[187]==3]\ndf_4=mit_train_data[mit_train_data[187]==4]\ndf_0=(mit_train_data[mit_train_data[187]==0]).sample(n=20000,random_state=42)\n\ndf_1_upsample=resample(df_1,replace=True,n_samples=20000,random_state=123)\ndf_2_upsample=resample(df_2,replace=True,n_samples=20000,random_state=124)\ndf_3_upsample=resample(df_3,replace=True,n_samples=20000,random_state=125)\ndf_4_upsample=resample(df_4,replace=True,n_samples=20000,random_state=126)\n\ntrain_df=pd.concat([df_0,df_1_upsample,df_2_upsample,df_3_upsample,df_4_upsample])\n\n\ndf_11=mit_test_data[mit_train_data[187]==1]\ndf_22=mit_test_data[mit_train_data[187]==2]\ndf_33=mit_test_data[mit_train_data[187]==3]\ndf_44=mit_test_data[mit_train_data[187]==4]\ndf_00=(mit_test_data[mit_train_data[187]==0]).sample(n=20000,random_state=42)\n\ndf_11_upsample=resample(df_1,replace=True,n_samples=20000,random_state=123)\ndf_22_upsample=resample(df_2,replace=True,n_samples=20000,random_state=124)\ndf_33_upsample=resample(df_3,replace=True,n_samples=20000,random_state=125)\ndf_44_upsample=resample(df_4,replace=True,n_samples=20000,random_state=126)\n\ntest_df=pd.concat([df_00,df_11_upsample,df_22_upsample,df_33_upsample,df_44_upsample])\n\n\nequilibre=train_df[187].value_counts()\nprint(equilibre)\nprint(\"ALL Train data\")\nprint(\"Type\\tCount\")\nprint((mit_train_data[187]).value_counts())\nprint(\"-------------------------\")\nprint(\"ALL Test data\")\nprint(\"Type\\tCount\")\nprint((mit_test_data[187]).value_counts())\n\nprint(\"ALL Balanced Train data\")\nprint(\"Type\\tCount\")\nprint((train_df[187]).value_counts())\nprint(\"-------------------------\")\nprint(\"ALL Balanced Test data\")\nprint(\"Type\\tCount\")\nprint((train_df[187]).value_counts())\n\"\"\"\n# ONE HOT Encoding *\n\"\"\"\n#One hot encoding for categorical target\n#Since we will be using neural networks for our classification model, \n#our output classes need to be turned into a numerical representation. We use one hot encoding (from sklearn package) to do this.\n\n\n\n#train_target = mit_train_data[187]\n#train_target = train_target.values.reshape(87554,1)\ntrain_target = train_df[187]\ntrain_target = train_target.values.reshape(100000,1)\n\n\n\n\n#one hot encode train_target\n\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn import preprocessing\n# TODO: create a OneHotEncoder object, and fit it to all of X\n\n# 1. INSTANTIATE\nenc = preprocessing.OneHotEncoder()\n\n# 2. FIT\nenc.fit(train_target)\n\n# 3. Transform\nonehotlabels = enc.transform(train_target).toarray()\nonehotlabels.shape\n\ntarget = onehotlabels\n#remove ground truth labels from training df\n#train\/test split\n\n\nfrom sklearn.model_selection import train_test_split\n\n#X = mit_train_data\nX = train_df\nX = X.drop(axis=1,columns=187)\n\nX_train, X_valid, Y_train, Y_valid = train_test_split(X,target, test_size = 0.25, random_state = 36)\nX_train = np.asarray(X_train)\nX_valid = np.asarray(X_valid)\nY_train = np.asarray(Y_train)\nY_valid = np.asarray(Y_valid)\n\n#X_train.reshape((1, 2403, 187))\nX_train = np.expand_dims(X_train, axis=2)\nX_valid = np.expand_dims(X_valid, axis=2)\nprint(X_train.shape)\nprint(Y_train.shape)\n# 2,403 training heartbeats and 802 validation heartbeats \n# for a 75:25 train-test split. \n\"\"\"\n# 1 MODEL NN\n\"\"\"\n# MODEL 1 https:\/\/www.kaggle.com\/freddycoder\/heartbeat-categorization\n# Separate features and targets\n\nfrom keras.utils import to_categorical\n\nprint(\"--- X ---\")\n# X = mit_train_data.loc[:, mit_train_data.columns != 187]\nX = train_df.loc[:, mit_train_data.columns != 187]\nprint(X.head())\nprint(X.info())\n\nprint(\"--- Y ---\")\n# y = mit_train_data.loc[:, mit_train_data.columns == 187]\ny = train_df.loc[:, mit_train_data.columns == 187]\ny = to_categorical(y)\n\nprint(\"--- testX ---\")\n#testX = mit_test_data.loc[:, mit_test_data.columns != 187]\ntestX = test_df.loc[:, mit_test_data.columns != 187]\nprint(testX.head())\nprint(testX.info())\n\nprint(\"--- testy ---\")\n#testy = mit_test_data.loc[:, mit_test_data.columns == 187]\ntesty = test_df.loc[:, mit_test_data.columns == 187]\ntesty = to_categorical(testy)\n# Keras model to make prediction\n\n#The number of epochs is a hyperparameter that defines the number times that the learning algorithm will work through the entire training dataset.\n#The batch size is a hyperparameter that defines the number of samples to work through before updating the internal model parameters.\n# softmax is used to categorize \n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\n\nmodel = Sequential()\n\nmodel.add(Dense(50, activation='relu', input_shape=(187,)))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.compile(optimizer='Adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.fit(X, y, epochs=10)\n\nprint(\"Evaluation: \")\nmse, acc = model.evaluate(testX, testy)\nprint('mean_squared_error :', mse)\nprint('accuracy:', acc)\n\"\"\"\n# ARDUINO SAMPLES\n\"\"\"\n\"\"\"\n# USE IF SAMPLES ARE IN A MATRIX FORM\n\"\"\"\ntest= pd.read_csv(\"..\/input\/arduino3a\/AS3.txt\", header=None)\ntest\n\nplt.plot(test.iloc[100,:])\n\"\"\"\n## Normalizing Arduino Samples\n\"\"\"\n# NORMALIZING TEST DATA AMPLITUDE\nfrom sklearn.preprocessing import MinMaxScaler\n# load the dataset and print the first 5 rows\n# prepare data for normalization\nvalues = test.values\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaler = scaler.fit(values)\nnormalized = scaler.transform(values)\n\ndfnormalized = pd.DataFrame(normalized)\ndfnormalized.index = [x for x in range(1, len(dfnormalized.values)+1)]\nplt.plot(dfnormalized.iloc[30,:])\n\"\"\"\n## Predicing Category\n\"\"\"\n# category= model.predict_classes(test) #not Normalized\ncategory= model.predict_classes(dfnormalized) #Normalized\nplt.plot(category)\n\"\"\"\n## Mean of Category\n\"\"\"\nnp.mean(category)\n\"\"\"\n# USE IF SAMPLES ARE IN A ROW\n\"\"\"\ntest = pd.read_csv(\"..\/input\/arduinorow1a\/test44.txt\", header=None)\n#test = pd.read_csv(\"..\/input\/arduinorow2a\/marnelakis.txt\", header=None)\n#test = test.iloc[0,0:len(test.T)-1] # Remove last line cause it might be a Nan\ntest = pd.DataFrame(test)\ntest=test.T\n\n\"\"\"\n## Normalize samples\n\"\"\"\n# NORMALIZING TEST DATA AMPLITUDE\nfrom sklearn.preprocessing import MinMaxScaler\n# load the dataset and print the first 5 rows\n# prepare data for normalization\nvalues = test.values\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaler = scaler.fit(values)\nnormalized = scaler.transform(values)\nnormalized = pd.DataFrame(normalized) \nnormalized\n## TESTING FOR ONE X\n#x=0\n#normalized = pd.DataFrame(normalized.T) ## CAUTION!!! needs to run only once \n#normtest=normalized.iloc[0, 0+x:187+x] \n#normtest=pd.DataFrame(normtest)\n#category = model.predict_classes(normtest.T)\n#category\ncategory= pd.DataFrame()\ncategory=category.dropna()\nlst_seq = np.arange(0,len(normalized.T)-190)\nfor x in lst_seq:\n    normtest=normalized.iloc[0, 0+x:187+x] \n    normtest=pd.DataFrame(normtest)\n    category[x] = model.predict_classes(normtest)\ncategory\ncategory\n\"\"\"\n## MEAN OF CATEGORIES\n\"\"\"\nnp.mean(category.T)\n\"\"\"\n## PLOT OF CATEGORIES\n\"\"\"\nplt.plot(category.T)\n\"\"\"\n## Display frequency of each predicted category as evaluated by model\n\"\"\"\ncategory = pd.DataFrame(category)\ntemp1= category.iloc[0,:].value_counts()\nprint(\"Categories vs Value Count\")\nprint(temp1)\nprint(\"Categories vs Frequency\")\nprint(temp1\/(len(category.T)))\n\"\"\"\n## 2. NEW MODEL CNN\n\"\"\"\n\"\"\"\n## https:\/\/www.kaggle.com\/gregoiredc\/arrhythmia-on-ecg-classification-using-cnn\n\"\"\"\ntarget_train=train_df[187]\ntarget_test=test_df[187]\ny_train=to_categorical(target_train)\ny_test=to_categorical(target_test)\nX_train=train_df.iloc[:,:186].values\nX_test=test_df.iloc[:,:186].values\n#for i in range(len(X_train)):\n#    X_train[i,:186]= add_gaussian_noise(X_train[i,:186])\nX_train = X_train.reshape(len(X_train), X_train.shape[1],1)\nX_test = X_test.reshape(len(X_test), X_test.shape[1],1)\ndef network(X_train,y_train,X_test,y_test):\n    \n\n    im_shape=(X_train.shape[1],1)\n    inputs_cnn=Input(shape=(im_shape), name='inputs_cnn')\n    conv1_1=Convolution1D(64, (6), activation='relu', input_shape=im_shape)(inputs_cnn)\n    conv1_1=BatchNormalization()(conv1_1)\n    pool1=MaxPool1D(pool_size=(3), strides=(2), padding=\"same\")(conv1_1)\n    conv2_1=Convolution1D(64, (3), activation='relu', input_shape=im_shape)(pool1)\n    conv2_1=BatchNormalization()(conv2_1)\n    pool2=MaxPool1D(pool_size=(2), strides=(2), padding=\"same\")(conv2_1)\n    conv3_1=Convolution1D(64, (3), activation='relu', input_shape=im_shape)(pool2)\n    conv3_1=BatchNormalization()(conv3_1)\n    pool3=MaxPool1D(pool_size=(2), strides=(2), padding=\"same\")(conv3_1)\n    flatten=Flatten()(pool3)\n    dense_end1 = Dense(64, activation='relu')(flatten)\n    dense_end2 = Dense(32, activation='relu')(dense_end1)\n    main_output = Dense(5, activation='softmax', name='main_output')(dense_end2)\n    \n    \n    model = Model(inputs= inputs_cnn, outputs=main_output)\n    model.compile(optimizer='adam', loss='categorical_crossentropy',metrics = ['accuracy'])\n    \n    \n    callbacks = [EarlyStopping(monitor='val_loss', patience=8),\n             ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]\n\n    history=model.fit(X_train, y_train,epochs=30,callbacks=callbacks, batch_size=32,validation_data=(X_test,y_test))\n    model.load_weights('best_model.h5')\n    return(model,history)\ndef evaluate_model(history,X_test,y_test,model):\n    scores = model.evaluate((X_test),y_test, verbose=0)\n    print(\"Accuracy: %.2f%%\" % (scores[1]*100))\n    \n    print(history)\n    fig1, ax_acc = plt.subplots()\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.xlabel('Epoch')\n    plt.ylabel('Accuracy')\n    plt.title('Model - Accuracy')\n    plt.legend(['Training', 'Validation'], loc='lower right')\n    plt.show()\n    \n    fig2, ax_loss = plt.subplots()\n    plt.xlabel('Epoch')\n    plt.ylabel('Loss')\n    plt.title('Model- Loss')\n    plt.legend(['Training', 'Validation'], loc='upper right')\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.show()\n    target_names=['0','1','2','3','4']\n    \n    y_true=[]\n    for element in y_test:\n        y_true.append(np.argmax(element))\n    prediction_proba=model.predict(X_test)\n    prediction=np.argmax(prediction_proba,axis=1)\n    cnf_matrix = confusion_matrix(y_true, prediction)\nfrom keras.layers import Dense, Convolution1D, MaxPool1D, Flatten, Dropout\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras.layers.normalization import BatchNormalization\nimport keras\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nmodel,history=network(X_train,y_train,X_test,y_test)\nevaluate_model(history,X_test,y_test,model)\ny_pred=model.predict(X_test)\ndf1 = pd.DataFrame()\ncategory= pd.DataFrame()\ncategory=category.dropna()\nlst_seq = np.arange(0,len(normalized.T)-190)\nfor x in lst_seq:\n    temp=normalized.iloc[0,0+x:186+x]\n    temp=pd.DataFrame(temp) \n    temp=temp.values\n    temp=temp.reshape(1,186,1)\n    category=pd.DataFrame(model.predict(temp))\n    df = pd.DataFrame(category)\n    df1=df1.append(df)\n    \ncategory=df1\n\"\"\"\n## Mean of each Catecory\n\"\"\"\ncategory=pd.DataFrame(category)\ncategory\ncat1=category[0].mean()\ncat2=category[1].mean()\ncat3=category[2].mean()\ncat4=category[3].mean()\ncat5=category[4].mean()\ncat1\n\ncat2\ncat3\ncat4\ncat5\n\"\"\"\n# 3. MODEL RNN LSTM GRU\n\"\"\"\n\"\"\"\n# 3.1 USE IF SAMPLES ARE IN A ROW\n\"\"\"\ntest = pd.read_csv(\"..\/input\/arduinorow1a\/test44.txt\", header=None)\ntest = test.iloc[0,0:len(test.T)-1] # Remove last line cause it might be a Nan\ntest = pd.DataFrame(test)\n# NORMALIZING TEST DATA AMPLITUDE\nfrom sklearn.preprocessing import MinMaxScaler\n# load the dataset and print the first 5 rows\n# prepare data for normalization\nvalues = test.values\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaler = scaler.fit(values)\nnormalized = scaler.transform(values)\nnormalized = pd.DataFrame(normalized)\nnormalized\n\"\"\"\n# MODEL LSTM RNN\n\"\"\"\n\"\"\"\n## https:\/\/machinelearningmastery.com\/sequence-classification-lstm-recurrent-neural-networks-python-keras\/\n## https:\/\/www.hindawi.com\/journals\/jhe\/2019\/6320651\/\n## https:\/\/www.mathworks.com\/help\/signal\/examples\/classify-ecg-signals-using-long-short-term-memory-networks.html\n##\n\"\"\"\nfrom keras.datasets import imdb\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Bidirectional\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\n# fix random seed for reproducibility\nnp.random.seed(7)\n# MODEL 1 https:\/\/www.kaggle.com\/freddycoder\/heartbeat-categorization\n# Separate features and targets\n\nfrom keras.utils import to_categorical\n\nprint(\"--- X ---\")\n# X = mit_train_data.loc[:, mit_train_data.columns != 187]\nX = train_df.loc[:, mit_train_data.columns != 187]\nprint(X.head())\nprint(X.info())\n\nprint(\"--- Y ---\")\n# y = mit_train_data.loc[:, mit_train_data.columns == 187]\ny = train_df.loc[:, mit_train_data.columns == 187]\ny = to_categorical(y)\n\nprint(\"--- testX ---\")\n#testX = mit_test_data.loc[:, mit_test_data.columns != 187]\ntestX = test_df.loc[:, mit_test_data.columns != 187]\nprint(testX.head())\nprint(testX.info())\n\nprint(\"--- testy ---\")\n#testy = mit_test_data.loc[:, mit_test_data.columns == 187]\ntesty = test_df.loc[:, mit_test_data.columns == 187]\ntesty = to_categorical(testy)\n# create the model.\nfrom keras.callbacks import History \nhistory = History()\nembedding_vecor_length = 187\nmodel = Sequential()\n#model = Bidirectional(model)\n\nmodel.add(Embedding(100000, embedding_vecor_length, input_length=187))\nmodel.add(LSTM(187))\nmodel.add(Dense(5, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\nhistory = model.fit(X, y, validation_data=(testX, testy), epochs=3, batch_size=8)\n\n\n#Dropout is a powerful technique for combating overfitting in your LSTM models \n#model = Sequential()\n#model.add(Embedding(1000, embedding_vecor_length, input_length=187))\n#model.add(LSTM(50, dropout=0.001, recurrent_dropout=0.001))\n#model.add(Dense(5, activation='softmax'))\n#model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n#print(model.summary())\n#history = model.fit(X, y, validation_data=(testX, testy), epochs=50, batch_size=128)\n\n\n\n## SAVE MODEL ##\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"1model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"1model.h5\")\nprint(\"Saved model to disk\")\n\"\"\"\n## Evaluate Model\n\"\"\"\n\"\"\"\nmse, acc = model.evaluate(testX, testy)\nprint('mean_squared_error :', mse)\nprint('accuracy:', acc)\n\"\"\"\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n# The history for the validation dataset is labeled test by convention as it is indeed a test dataset for the model.\n#The plots can provide an indication of useful things about the training of the model, such as:\n#*It\u2019s speed of convergence over epochs (slope).\n#*Whether the model may have already converged (plateau of the line).\n#*Whether the mode may be over-learning the training data (inflection for validation line)\n\"\"\"\n## \u0391ccuracy and prediction scores\n\"\"\"\ny_pred = model.predict(testX, batch_size=1000)\n\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix, label_ranking_average_precision_score, label_ranking_loss, coverage_error \n\nprint(classification_report(testy.argmax(axis=1), y_pred.argmax(axis=1)))\n\"\"\"\n## Predict category of Arduino sample\n\"\"\"\ncategory= pd.DataFrame()\ncategory=category.dropna()\nlst_seq = np.arange(0,len(normalized.T)-190)\nfor x in lst_seq:\n    normtest=normalized.iloc[0, 0+x:187+x] \n    normtest=pd.DataFrame(normtest)\n    category[x] = model.predict_classes(normtest.T)\ncategory\n\"\"\"\n## MEAN OF CATEGORIES\n\"\"\"\nnp.mean(category.T)\n\"\"\"\n## PLOT OF CATEGORIES\n\"\"\"\nplt.plot(category.T)\n\"\"\"\n## Display frequency of each predicted category as evaluated by model\n\"\"\"\ncategory = pd.DataFrame(category)\ntemp1= category.iloc[0,:].value_counts()\nprint(\"Categories vs Value Count\")\nprint(temp1)\nprint(\"Categories vs Frequency\")\nprint(temp1\/(len(category.T)))\n\"\"\"\n# LOAD MODEL \n\"\"\"\njson_file = open(\"..\/working\/model.json\", 'r')\nmodel_json = json_file.read() \njson_file.close()\n\nfrom keras.models import model_from_json\nmodel = model_from_json(model_json)\nmodel.load_weights(\"..\/working\/model.h5\")\n\n#model.compile(loss='binary_crossentropy', optimizer='adam')\n#prediction = model.predict(x_test, batch_size=2048)[0].flatten()","meta":"{'source': 'AI4Code', 'id': '7ceb313365326a'}"}
{"id":"114982","text":"# 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\nsegReport_df = pd.read_csv(\"..\/input\/traffic-flow-data-in-ho-chi-minh-city-viet-nam\/segment_reports.csv\", index_col=\"_id\", \n                            parse_dates=[\"updated_at\"])\nsegment_df = pd.read_csv(\"..\/input\/traffic-flow-data-in-ho-chi-minh-city-viet-nam\/segments.csv\", index_col=\"_id\",\n                         parse_dates=[\"created_at\", \"updated_at\"])\n\"\"\"\n## Transformation magic\n\"\"\"\nfrom math import ceil\n\ndef transform_LOS(segment_id, velocity):\n    max_velocity = segment_df.loc[segment_id, \"max_velocity\"]\n    if max_velocity is None:\n        max_velocity = 50\n    \n    # Transform to label\n    labels = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]\n    threshold = 35\n    if max_velocity >= 70:\n        threshold = 45\n    elif max_velocity >= 60:\n        threshold = 40\n\n    t = max(threshold - velocity, 0)\n    return labels[min(ceil(t \/ 5), 5)]\n\ndef transform_report(row):\n    \"\"\"\n    @Params:\n        dt: Timestamp object of Pandas\n    @Return:\n        dict: {\"date\", \"period_{hour}_{00|30}\"}\n    \"\"\"\n    LOS = transform_LOS(row[\"segment_id\"], row[\"velocity\"])\n    dt = row[\"updated_at\"]\n    intervals = list(range(24))\n    h = dt.hour\n    m = \"00\" if dt.minute < 30 else \"30\"\n    p_name = f\"period_{h}_{m}\"\n    return dt.date(), dt.weekday(), p_name, LOS\n\"\"\"\n## Do it!\n\"\"\"\ndates = []\nweekdays = []\np_names = []\nLOSes = []\n\nfor _, row in segReport_df.iterrows():\n    date, weekday, p_name, LOS = transform_report(row)\n    dates.append(date)\n    weekdays.append(weekday)\n    p_names.append(p_name)\n    LOSes.append(LOS)\n\nsegReport_df[\"date\"] = dates\nsegReport_df[\"weekday\"] = weekdays\nsegReport_df[\"period\"] = p_names\nsegReport_df[\"LOS\"] = LOSes\n\"\"\"\n## Divide into periods may cause a period has many LOS labels, so need to mitigate this by setting a major label\n\"\"\"\ndef major_voting(labels):\n    unique_labels = set(labels)\n    count_labels = [labels.count(label) for label in unique_labels]\n\n    sorted_labels = sorted(zip(unique_labels, count_labels), key=lambda x: x[1])\n    if len(sorted_labels) > 1 and sorted_labels[0][1] == sorted_labels[1][1]:\n        print(\"Oh no, many majors?\")\n    return sorted_labels[0][0]\n\ndef mean_voting(labels):\n    l = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]\n    values = {\"A\":0, \"B\":1, \"C\":2, \"D\":3, \"E\":4, \"F\":5}\n    mean = sum(values[label] for label in labels) \/ len(labels)\n    return l[min(round(mean), 5)]\ncompress_LOS = segReport_df.groupby(by=[\"segment_id\", \"date\", \"weekday\", \"period\"])[\"LOS\"].apply(list)\ncompress_LOS = pd.DataFrame(compress_LOS).reset_index()\ncompress_LOS[\"LOS\"] = compress_LOS[\"LOS\"].apply(mean_voting)\n\"\"\"\n## Now the data should be good (maybe)\n\"\"\"\ncompress_LOS","meta":"{'source': 'AI4Code', 'id': 'd34e39c3cd562e'}"}
{"id":"100578","text":"import numpy as np\nimport pandas as pd\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nfrom sklearn.linear_model import LinearRegression\nfrom tqdm import tqdm_notebook as tqdm\n\nfrom sklearn.metrics import mean_squared_log_error\n\"\"\"\n## Load and preview Data\n\"\"\"\ntrain = pd.read_csv('\/kaggle\/input\/covid19-global-forecasting-week-1\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/covid19-global-forecasting-week-1\/test.csv')\nss = pd.read_csv('\/kaggle\/input\/covid19-global-forecasting-week-1\/submission.csv')\ntrain[['Country\/Region', 'Province\/State']] = train[['Country\/Region', 'Province\/State']].fillna('None')\ntest[['Country\/Region', 'Province\/State']] = test[['Country\/Region', 'Province\/State']].fillna('None')\ntrain.head()\ntrain.shape\ntest.head()\nss.head()\nprint(ss.shape)\ntrain['Country\/Region'].value_counts(dropna=False)\ntrain['Province\/State'].value_counts(dropna=False)\n\"\"\"\n## Exclude leaking data\n\"\"\"\ntrain['Date'].max(), test['Date'].min()\nvalid = train[train['Date'] >= test['Date'].min()]\ntrain = train[train['Date'] < test['Date'].min()]\n\"\"\"\n## Build a simple model\n\"\"\"\nlog_target = True\nplot = False\n\ntest['ConfirmedCases'] = np.nan\ntest['Fatalities'] = np.nan\n\ncountries = train['Country\/Region'].unique()\ntest_countries = test['Country\/Region'].unique()\n\npredictions = []\nfor c in tqdm(countries):\n    train_df = train[train['Country\/Region'] == c]\n    provinces = train_df['Province\/State'].unique()\n    \n    if c in test_countries:\n        test_df = test[test['Country\/Region'] == c]\n        test_provinces = test_df['Province\/State'].unique()\n    \n        for p in provinces:\n            train_df_p = train_df[train_df['Province\/State'] == p]\n            test_df_p = test_df[test_df['Province\/State'] == p]\n            \n            confirmed = train_df_p['ConfirmedCases'].values[-10:]\n            fatalities = train_df_p['Fatalities'].values[-10:]\n\n            if log_target:\n                confirmed = np.log1p(confirmed)\n                fatalities = np.log1p(fatalities)\n\n            if np.sum(confirmed) > 0:            \n                x = np.arange(len(confirmed)).reshape(-1, 1)\n                x_test = len(confirmed) + np.arange(len(test_df_p)).reshape(-1, 1)\n                \n                model = LinearRegression()\n                model.fit(x, confirmed)\n                p_conf = model.predict(x_test)\n                p_conf = np.clip(p_conf, 0, None)\n                p_conf = p_conf - np.min(p_conf) + confirmed[-1]\n                if log_target:\n                    p_conf = np.expm1(p_conf)\n                test.loc[(test['Country\/Region'] == c) & (test['Province\/State'] == p), 'ConfirmedCases'] = p_conf\n                \n                model = LinearRegression()\n                model.fit(x, fatalities)\n                p_fatal = model.predict(x_test)\n                p_fatal = np.clip(p_fatal, 0, None)\n                p_fatal = p_fatal - np.min(p_fatal) + fatalities[-1]\n                if log_target:\n                    p_fatal = np.expm1(p_fatal)\n                test.loc[(test['Country\/Region'] == c) & (test['Province\/State'] == p), 'Fatalities'] = p_fatal\n                \n                if plot:\n                    plt.figure();\n                    plt.plot(x, confirmed);\n                    plt.plot(x, fatalities);\n                    plt.plot(x_test, p_conf);\n                    plt.plot(x_test, p_fatal);\n                    plt.title(c + ', ' + p);\n            \ntest[['ConfirmedCases', 'Fatalities']] = test[['ConfirmedCases', 'Fatalities']].fillna(0)\n\"\"\"\n# Evaluate predictions\n\"\"\"\nvalid.sort_values(['Country\/Region', 'Province\/State', 'Date'], inplace=True)\npreds = test.sort_values(['Country\/Region', 'Province\/State', 'Date'])\npreds = valid[['Country\/Region', 'Province\/State', 'Date']].merge(preds, on=['Country\/Region', 'Province\/State', 'Date'], how='left')\n\nscore_c = np.sqrt(mean_squared_log_error(valid['ConfirmedCases'].values, preds['ConfirmedCases']))\nscore_f = np.sqrt(mean_squared_log_error(valid['Fatalities'].values, preds['Fatalities']))\n\nprint(f'score_c: {score_c}, score_f: {score_f}, mean: {np.mean([score_c, score_f])}')\npd.concat([valid.reset_index().drop('index', axis=1), \n           preds.reset_index()[['ConfirmedCases', 'Fatalities']].rename({'ConfirmedCases': 'ConfirmedCases_p', 'Fatalities': 'Fatalities_p'}, axis=1)], axis=1)\nvalid.shape, preds.shape\nplt.figure(figsize=(12, 8))\nplt.plot([0, 70000], [0, 70000], 'black')\nplt.plot(preds['ConfirmedCases'], valid['ConfirmedCases'], '.')\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.grid()\n\nplt.figure(figsize=(12, 8))\nplt.plot([0, 3500], [0, 3500], 'black')\nplt.plot(preds['Fatalities'], valid['Fatalities'], 'r.')\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.grid()\n\"\"\"\n## Prepare submission\n\"\"\"\nsubmission = test[['ForecastId', 'ConfirmedCases', 'Fatalities']]\nsubmission.to_csv('submission.csv', index=False)\nprint(submission.shape)\nsubmission.head()","meta":"{'source': 'AI4Code', 'id': 'b8d65889b76055'}"}
{"id":"42218","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nimport seaborn as sns\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        url = os.path.join(dirname, filename)\n        print(url)\n\n# Any results you write to the current directory are saved as output.\nimport os\nimport sys\nimport requests\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.metrics import plot_roc_curve\nfrom sklearn.metrics import accuracy_score, classification_report\n\n# I Just need the Close\n# url='\/kaggle\/input\/dataset-tree\/Tree Training Dataset.csv'\n\ndef read_data(url):\n\n    data = pd.read_csv(url)\n    \n    # sort the values by symbol and then date\n#     data.sort_values(by = ['symbol','datetime'], inplace = True)\n    cols = ['Date','Price','Open','High','Low','Vol.','Change']\n    data = data[cols]\n    \n#     top_row = pd.DataFrame({'Date':['June 22, 2020'], 'Price':[0], 'Open':[0], 'High':[0],'Low':[0],'Vol.':[0],'Change':[0]})\n#     top_row = pd.DataFrame({'Date':['June 22, 2020']})\n    \n#     # Concat with old DataFrame and reset the Index.\n#     data = pd.concat([top_row, data]).reset_index(drop = True)\n\n    send_data = data.loc[:,:].values\n    \n    return cols, data, send_data\n    \ndef add_change_in_price(data):\n    # calculate the change in price\n    data['change'] = data['Price'].diff()\n    return data\ncols, price_data, array_data = read_data(url)\n# price_data = add_change_in_price(price_data)\nprint('Features are:', cols)\nprice_data = price_data.iloc[::-1]\nprint(price_data)\nprint(price_data.shape)\nfor i in range (len(cols)):\n    print(type(price_data[cols[i]][5]))\ndef calculate_rsi(data):\n    # Calculate the 14 day RSI\n    n = 14\n\n    # First make a copy of the data frame twice\n    up_df, down_df = data[['Change']].copy(), data[['Change']].copy()\n\n    # # For up days, if the change is less than 0 set to 0.\n    up_df.loc['Change'] = up_df.loc[(up_df['Change'] < 0), 'Change'] = 0\n\n    # # For down days, if the change is greater than 0 set to 0.\n    down_df.loc['Change'] = down_df.loc[(down_df['Change'] > 0), 'Change'] = 0\n\n    # # We need change in price to be absolute.\n    down_df['Change'] = down_df['Change'].abs()\n\n    # # Calculate the EWMA (Exponential Weighted Moving Average), meaning older values are given less weight compared to newer values.\n    ewma_up = up_df['Change'].transform(lambda x: x.ewm(span = n).mean())\n    ewma_down = down_df['Change'].transform(lambda x: x.ewm(span = n).mean())\n\n    # # Calculate the Relative Strength\n    relative_strength = ewma_up \/ ewma_down\n\n    # # Calculate the Relative Strength Index\n    relative_strength_index = 100.0 - (100.0 \/ (1.0 + relative_strength))\n\n    # # Add the info to the data frame.\n    data['down_days'] = down_df['Change']\n    data['up_days'] = up_df['Change']\n    data['RSI'] = relative_strength_index\n\n    # print(price_data.shape)\n\n    # price_data\n    return data\nprice_data = calculate_rsi(price_data)\n\n# Display the head.\nprice_data.head(30)\ndef calculate_stos(data):\n    # Calculate the Stochastic Oscillator\n    n = 14\n\n    # Make a copy of the high and low column.\n    low_14, high_14 = data['Low'].copy(), data['High'].copy()\n\n    # low_14 = low_14.apply(pd.to_numeric, errors='coerce')\n    # high_14 = high_14.apply(pd.to_numeric, errors='coerce')\n\n    # # # Group by symbol, then apply the rolling function and grab the Min and Max.\n    # low_14 = low_14.transform(lambda x: x.rolling(window = n).min())\n    # high_14 = high_14.transform(lambda x: x.rolling(window = n).max())\n    high_14 = high_14.rolling(n).max()\n    low_14 = low_14.rolling(n).min()\n\n    # # # # Calculate the Stochastic Oscillator.\n    k_percent = 100 * ((data['Price'] - low_14) \/ (high_14 - low_14))\n\n    # # # Add the info to the data frame.\n    data['low_14'] = low_14\n    data['high_14'] = high_14\n    data['k_percent'] = k_percent\n    return data\n\nprice_data = calculate_stos(price_data)\n# Display the head.\nprice_data.tail(1)\ndef calculate_william_r(data):\n    # Calculate the Williams %R\n    n = 14\n\n    # Make a copy of the high and low column.\n    # low_14, high_14 = price_data['Low'].copy(), price_data['High'].copy()\n\n    # # Group by symbol, then apply the rolling function and grab the Min and Max.\n    # low_14 = low_14.transform(lambda x: x.rolling(window = n).min())\n    # high_14 = high_14.groupby('symbol')['high'].transform(lambda x: x.rolling(window = n).max())\n    low_14, high_14 = data['Low'].copy(), data['High'].copy()\n\n    high_14 = high_14.rolling(n).max()\n    low_14 = low_14.rolling(n).min()\n\n    # # Calculate William %R indicator.\n    r_percent = ((high_14 - data['Price']) \/ (high_14 - low_14)) * - 100\n\n    # # Add the info to the data frame.\n    data['r_percent'] = r_percent\n    return data\nprice_data = calculate_william_r(price_data)\n# Display the head.\nprice_data.head(14)\ndef calculate_macd(data):\n    # Calculate the MACD\n    ema_26 = data['Price'].transform(lambda x: x.ewm(span = 26).mean())\n    ema_12 = data['Price'].transform(lambda x: x.ewm(span = 12).mean())\n    macd = ema_12 - ema_26\n    print(price_data.shape)\n    # Calculate the EMA\n    ema_9_macd = macd.ewm(span = 9).mean()\n\n    # # Store the data in the data frame.\n    data['MACD'] = macd\n    data['MACD_EMA'] = ema_9_macd\n    \n    return data\nprice_data = calculate_macd(price_data)\n# Print the head.\nprice_data.head(30)\ndef calculate_price_roc(data):\n    # Calculate the Price Rate of Change\n    n = 9\n\n    # Calculate the Rate of Change in the Price, and store it in the Data Frame.\n    data['Price_Rate_Of_Change'] = data['Price'].transform(lambda x: x.pct_change(periods = n))\n    \n    return data\n    \nprice_data = calculate_price_roc(price_data)\n# Print the first 30 rows\nprice_data.head(33)\n# Create a column we wish to predict\ndef create_prediction(data):\n    # Group by the `Symbol` column, then grab the `Close` column.\n    price_groups = data['Price']\n\n    # Apply the lambda function which will return -1.0 for down, 1.0 for up and 0.0 for no change.\n    price_groups = price_groups.transform(lambda x : np.sign(x.diff()))\n\n    # add the data to the main dataframe.\n    data['Prediction'] = price_groups\n\n    # for simplicity in later sections I'm going to make a change to our prediction column. To keep this as a binary classifier I'll change flat days and consider them up days.\n    data.loc[data['Prediction'] == 0.0] = 1.0\n    \n    return data\n\n# OPTIONAL CODE: Dump the data frame to a CSV file to examine the data yourself.\n# price_data.to_csv('final_metrics.csv')\nprice_data = create_prediction(price_data)\n# print the head\nprice_data.tail(10)\n\n# We need to remove all rows that have an NaN value.\nprint('Before NaN Drop we have {} rows and {} columns'.format(price_data.shape[0], price_data.shape[1]))\n\n# Any row that has a `NaN` value will be dropped.\nprice_data = price_data.dropna()\n\n# Display how much we have left now.\nprint('After NaN Drop we have {} rows and {} columns'.format(price_data.shape[0], price_data.shape[1]))\n\n# Print the head.\nprice_data.head()\nfeatures = ['RSI','low_14','high_14','k_percent','r_percent','MACD','MACD_EMA','Price_Rate_Of_Change']\ncollection = ['Date','RSI','low_14','high_14','k_percent','r_percent','MACD','MACD_EMA','Price_Rate_Of_Change']\ntarget = ['Prediction']\nx_collect = price_data[collection]\nx_data = price_data[features]\ny_data = price_data[target]\nx_collect\n\nprice_data.shape\ntop_row = pd.DataFrame({'Date':['June 22, 2020'],'RSI':[0],'low_14':[0], 'high_14':[0],'k_percent':[0],\n                        'r_percent':[0],'MACD':[0],'MACD_EMA':[0],'Price_Rate_Of_Change':[0]})\n    \nprice_data1 = price_data\nprice_data1 = price_data1.iloc[::-1]\n\n# Concat with old DataFrame and reset the Index.\ndf = price_data1[collection]\n\n# df.drop(df.tail(1).index,inplace=True)\ndf = pd.concat([top_row, df])\n# df = df.iloc[::-1]\nprint(df.shape)\ndf\ndf = df.iloc[::-1]\ndf\ndf = df[features]\nmy = df.loc[:,:].values\nmy\ndg = pd.DataFrame(my)\n# dg = dg.iloc[::-1]\ndg\ndg\n# dg = dg.reindex(index=dg.index[::-1])\n# dg = dg.iloc[::-1]\n\n# dg.loc[278:278,:]\n# price_data.loc[1:1,:]\nprice_data\ndg = dg.iloc[::-1]\ndg.head(5)\nprice_data1 = price_data\nprice_data1 = price_data1.iloc[::-1]\n\n# price_data1[features] = dg\n\nprice_data1.head(5)\n# 52.182112\t1671.7\t1761.0\t66.517357\t-33.482643\t3.448006\t3.101512\t\nx_data\ny_data\nplot_data = pd.DataFrame(x_data)\nplot_data[\"Pre\"] = y_data\nsns.pairplot(plot_data, hue='Pre', palette='OrRd')\ndef split_data(x1, y1):\n    # Split X and y into X_\n    X_train, X_test, y_train, y_test = train_test_split(x1, y1, random_state = 0)\n    return X_train, X_test, y_train, y_test\n\ndef apply_randomforest(x, y):\n    # Create a Random Forest Classifier\n    rand_frst_clf = RandomForestClassifier(n_estimators = 200, oob_score = True, criterion = \"gini\", random_state = 0)\n    \n    X_train, X_test, y_train, y_test = split_data(x, y)\n    # Fit the data to the model\n    rand_frst_clf.fit(X_train, y_train)\n\n    # Make predictions\n    y_pred = rand_frst_clf.predict(X_test)\n    \n    correct = accuracy_score(y_test, y_pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    \n    return correct, y_pred\npred_score, y_pred = apply_randomforest(x_data, y_data)\ny_pred\ncount = np.zeros(price_data.shape[0])\n# add=0\nfor i in range (price_data.shape[0]):\n    count[i] = i\n# count\nx_array = x_data.loc[:,:].values\n\nfor i in range (x_array.shape[1]):\n    plt.scatter(x_array[:,i], count)\n# plt.scatter(y_data, count)\n\"\"\"\nApplying PCA\n\"\"\"\nfrom sklearn.decomposition import PCA\npca_ml1 = PCA(n_components=4)\npca_fit = pca_ml1.fit_transform(x_data)\n\npca_df = pd.DataFrame(data = pca_fit\n             , columns = ['pc1', 'pc2', 'pc3', 'pc4'])\npca_df.head(5)\nsns.pairplot(pca_df)\nplt.show()\n\"\"\"\nThe correlogram is an array of scatterplots, for each pair of principal components. The dimension of this array of graphs is obviously equal to the number of elements in the dataframe.\n\nAlong the diagonal Seaborn plots by default the histogram of the relevant variable, in our case the distribution of values of the principal components.\n\nTo learn some more about the data, let\u2019s use the additional information about the labels associated with the spectra\n\"\"\"\npca_df[\"Pre\"] = y_data\nsns.pairplot(pca_df, hue='Pre', palette='OrRd')\n\ncount.shape\npca_fit[:,1].shape\nrf_pca_pred_score, rf_pca_pred = apply_randomforest(pca_df, y_data)\ndef apply_knn(x, y):\n    from sklearn.neighbors import KNeighborsClassifier\n    model = KNeighborsClassifier(n_neighbors=3)\n    \n    X_train, X_test, y_train, y_test = split_data(x, y)\n    # Train the model using the training sets\n    \n    model.fit(X_train,y_train)\n\n    #Predict Output\n    pred = model.predict(X_test)\n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    return correct, pred\nknn_pred_score, pred = apply_knn(x_data, y_data)\ndef apply_NB(x, y):\n    from sklearn.naive_bayes import GaussianNB\n    \n    model = GaussianNB()\n    \n    X_train, X_test, y_train, y_test = split_data(x, y)\n    \n    # Train the model using the training sets\n    model.fit(X_train,y_train)\n\n    #Predict Output\n    pred = model.predict(X_test)\n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    return correct, pred\nNB_pred_score, pred = apply_NB(x_data, y_data)\ndef apply_lda(x, y):\n#     from sklearn.lda import LDA\n    \n#     model = LDA()\n    \n    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n    model = LinearDiscriminantAnalysis()\n\n    X_train, X_test, y_train, y_test = split_data(x, y)\n    \n    print(X_train.shape)\n    print(y_train.shape)\n    \n    # Train the model using the training sets\n    model.fit(X_train,y_train.values.ravel())\n#     model.fit(X_train,y_train)\n#     model.fit(X_train)\n    lda_fit = model.transform(X_train)\n    lda_fit=0\n    \n    #Predict Output\n    pred = model.predict(X_test)\n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n\n    \n    return correct, lda_fit, pred\nlda_pred_score, lda_fit, lda_pred = apply_lda(x_data, y_data)\ndef apply_LG(x, y):\n    \n    from sklearn.linear_model import LinearRegression\n\n    model = LinearRegression()\n\n    X_train, X_test, y_train, y_test = split_data(x, y)\n    \n    # Train the model using the training sets\n    model.fit(X_train,y_train)\n#     LG_fit = model.fit(X_train,y_train).transform(X_train)\n    \n    #Predict Output\n    pred = model.predict(X_test)\n#     correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n#     print('Correct Prediction (%): ', correct)\n#     return correct, pred\n    return y_test, pred\n# LG_pred_score, LG_pred = apply_LG(x_data, y_data)\ny_te, LG_pred = apply_LG(x_data, y_data)\nLG_pred\n# correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n#     print('Correct Prediction (%): ', correct)\n\ndef apply_svm(x, y):\n    from sklearn.pipeline import make_pipeline\n    from sklearn.preprocessing import StandardScaler\n    from sklearn.svm import SVC\n\n    X_train, X_test, y_train, y_test = split_data(x, y)\n    \n    # Train the model using the training sets\n#     model = make_pipeline(StandardScaler(), SVC(gamma='auto'))\n    model = SVC()\n    model.fit(X_train, y_train)\n    \n    #Predict Output\n    pred = model.predict(X_test)\n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    return correct, pred\nsvm_pred_score, svm_pred = apply_svm(x_data, y_data)\nsvm_pred_score\n\"\"\"\nApplying Decision Tree\n\"\"\"\ndef apply_decisiontree(x, y):\n    from sklearn import tree\n    \n    X_train, X_test, y_train, y_test = split_data(x, y)\n    \n    # Train the model using the training sets\n    model = tree.DecisionTreeClassifier()\n    model.fit(X_train, y_train)\n    tree.plot_tree(model)\n    \n    #Predict Output\n    pred = model.predict(X_test)\n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    return correct, pred\ndt_pred_score, dt_pred = apply_decisiontree(x_data, y_data)\ndt_pred_score\nplot_data = price_data.tail(50)\nplot_data\ndef apply_randomforest_test(x, y):\n    # Create a Random Forest Classifier\n    rand_frst_clf = RandomForestClassifier(n_estimators = 200, oob_score = False, criterion = \"gini\", random_state = 0)\n    \n    X_train, X_test, y_train, y_test = split_data(x, y)\n    # Fit the data to the model\n    rand_frst_clf.fit(X_train, y_train)\n\n    # Make predictions\n    pred = rand_frst_clf.predict(X_test)\n    \n    correct = accuracy_score(y_test, pred, normalize = True) * 100.0\n    print('Correct Prediction (%): ', correct)\n    \n    return correct, pred\n\ny11 = price_data.tail(1)[features]\ny11\nprice_data.tail(2)\ny11 = x_data.loc[2:2,:]\n# rsi=52.182112 low_14=1671.7 high_14=1761.0 k_percent=66.517357 r_percent=-33.482643 MACD=3.448006 MACD_EMA=3.101512 Price_roc=0.018595\ny11\nprice_data.head(15)\nz_score, z_pred = apply_randomforest_test(x_data, y_data)\nz_score\ncount_lda_pred = np.zeros(lda_pred.shape)\nfor i in range (lda_pred.shape[0]):\n    count_lda_pred[i] = i \nplt.scatter(lda_pred, count_lda_pred)\nplot_data = pd.DataFrame(x_data)\nplot_data['Prediction'] = y_data\n\n# sns.relplot(x='Change', y='Prediction',  data=price_data)\n# sns.catplot(x='Date', y='Prediction',  data=plot_data)\nsns.regplot(x='RSI', y='Prediction',  data=plot_data)\nsns.regplot(x='r_percent', y='Prediction',  data=plot_data)\n\ng = sns.FacetGrid(price_data, hue=\"Prediction\", hue_kws={\"marker\": [\"^\", \"v\"]})\n# g = sns.FacetGrid(plot_data, col=\"Prediction\", row=\"Date\")\ng.map(plt.scatter, \"RSI\", \"r_percent\", alpha=.7)\ng.add_legend();\nsns.pairplot(plot_data, hue='Prediction', palette='OrRd')\ng = sns.FacetGrid(plot_data, col=\"Prediction\", height=4, aspect=.5)\ng.map(sns.barplot, \"RSI\", \"r_percent\");\nx_data.loc[2:2,:]\n# rsi=52.182112 low_14=1671.7 high_14=1761.0 k_percent=66.517357 r_percent=-33.482643 MACD=3.448006 MACD_EMA=3.101512 Price_roc=0.018595\nprice_data.tail()","meta":"{'source': 'AI4Code', 'id': '4dd1b4900fefdc'}"}
{"id":"29409","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom sklearn.impute import SimpleImputer # Simple Imputer to fill in missing data\nfrom sklearn.ensemble import RandomForestRegressor # Random forest model\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n## Goal\nGiven a list of passengers, the objective is to predict which passengers survived the sinking of the Titanic.\n\"\"\"\n# The first step is reading in the provided training and the testing datasets\ntrain = pd.read_csv('..\/input\/train.csv')\ntest = pd.read_csv('..\/input\/test.csv')\n\"\"\"\nTo explore the data, we can print the first few lines and see what categories of information are provided for each passenger.\n\"\"\"\n# print first few lines of data\ntrain.head()\n# identify the classes with null values and get the quantity of cells lacking information\nmissing_counts = train.isnull().sum()\nprint(missing_counts[missing_counts>0])\n\"\"\"\n### Resolving missing values\nThe three features which have missing values are *Age*, *Cabin*, and *Embarked*. I am going to make a large assumption and jump to the conclusion that I don't care about the specific cabin someone booked, or the location from which they embarked upon the vessel. This judgement call is not supported by any statistics, but I am subjectively deciding that the *Cabin* and *Embarked* features have a negligible impact on a person's chances of surviving the Titanic.\n\"\"\"\n# drop the identified columns from training and testing data\nreduced_train = train.drop(['Cabin','Embarked'], axis=1)\nreduced_test = test.drop(['Cabin','Embarked'], axis=1)\n# print last few lines from reduced training dataset\nreduced_train.tail()\n\"\"\"\n### Resolving the *Age* feature\nI do not want to assume that the *Age* feature is unimportant to a given person's odds of survival because we know from historical accounts (and the movie) that women and children were prioritized passengers on the lifeboats. Therefore we might expect a correlation between age and probability of surviving. In this kernel, the simple imputer from sklearn will be applied to fill in missing *Age* values with the average age.\n\"\"\"\n# Imputing the Age feature\n# compute the mean ages - force them to be integers\navg_train_age = int(reduced_train.Age.mean())\navg_test_age = int(reduced_test.Age.mean())\n# perform the imputation\ntrain_imputer = SimpleImputer(strategy='constant',fill_value=avg_train_age)\nimputed_train = train_imputer.fit_transform(reduced_train)\ntest_imputer = SimpleImputer(strategy='constant',fill_value=avg_test_age)\nimputed_test = test_imputer.fit_transform(reduced_test)\n\n# convert back to dataframes\ntrain_new = pd.DataFrame(imputed_train,index=imputed_train[:,0],columns=reduced_train.columns)\ntest_new = pd.DataFrame(imputed_test,index=imputed_test[:,0],columns=reduced_test.columns)\n\n# print last few lines from new imputed training dataset\ntrain_new.tail()\n\"\"\"\n### Dropping additional features\nAfter some thought, I elected to drop the *Name* feature as familial connections are established via the *SibSp* and *Parch* features, and names are also keyed in many different ways. The *Ticket* feature was also dropped as I do not expect a significant relationship between the ticket number and a person's chance of survival\n\"\"\"\n# Dropping the Name feature and the Ticket feature\ntrain_small = train_new.drop(['Name','Ticket'], axis=1)\ntest_small = test_new.drop(['Name','Ticket'],axis=1)\n\n# printing last few lines\ntrain_small.tail()\n\"\"\"\n### To remove the last string feature, the *Sex* category will be made binary (1 for female, 0 for male)\n\"\"\"\n# numerically encoding the Sex feature\ntrain_small['Sex'] = train_small['Sex'].map( {'female' : 1, 'male' : 0} ).astype(int)\ntest_small['Sex'] = test_small['Sex'].map( {'female' : 1, 'male' : 0} ).astype(int)\n\n# printing last few lines\ntrain_small.tail()\n\"\"\"\n### Using the training data to fit a model\nThis cleaned up and reduced training data will be used to fit a Random Tree. At this time the Random Tree Regressor is being used for convenience and simplicity.\n\"\"\"\n# break out data into x and y components\nx_features = ['PassengerId','Pclass','Sex','Age','SibSp','Parch','Fare']\ntrain_x = train_small[x_features]\ntest_x = test_small[x_features]\n\ntrain_y = train_small['Survived']\n\n# implementing the random forest\nforest_model = RandomForestRegressor(random_state=1)\nforest_model.fit(train_x, train_y)\n\ntest_pred = forest_model.predict(test_x)\n\"\"\"\n### Have to write the output of the model to a csv with the PassengerId tags as well\nFirst the output will be rounded, made binary, and converted to integers as survival is binary (either you survive or you don't). Then the csv will be written with the rounded values.\n\"\"\"\n# round and make predictions an array of integers\ntest_pred = np.round(test_pred).astype(int)\n\n# create submission dataframe then convert to csv\nsubmission = pd.DataFrame({\n        \"PassengerId\" : test_x[\"PassengerId\"],\n        \"Survived\": test_pred\n    })\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '3601af114d65a8'}"}
{"id":"128261","text":"\"\"\"\n# **What are differences of job contents among different jobs? **\n\n\nNo matter if you already have worked with data or plan to step into this field,  I think you all may be curious about what are the differences in job contents among different job positions! Knowing this can help you better blueprint your future and find the position that fits your capability & interest & strength the most. Especially for people who haven't learned about this, they might get confused with so many titles, such like analysts, scientists, engineers etc, therefore a deep insight of how these titles differ will be quite helpful (instead of looking at the salary ^^). We might have general ideas of what people with these jobs do, but let's dive into the Kaggle's survey data to see if our intuitions are the same as the fact (I assume all respondents are honest and serious about this survey) !!\n\n## Help prepare for your next move!\n\nMy idea is to use the survey data, and give the insights of what it looks like in different jobs. For those who haven't but prepare to step into this field, they could learn what they could prepare and which skills are most needed so as to expand their skill set. For those who have worked in this field, but prepare to either stay or switch to other positions, they could also have a self-check and see if they really like the job content of that job title in bigger picture, and plan their career path!\n\n## The questions I would like to explore:\n1. What percentage of time do people spend on coding? (Reason: especially for whose who are amateurs and lack of coding background, they can better evaluate themselves and improve in the correct direction towards different occupations in data.)\n2. Distribution of how long people have used coding skill to analyze data for different jobs? (Reason: Well, after knowing the coding, we can take a closer look to see the distribution of how many years people have in analyzing data with code in different occupations )\n3. Do people have machine learning experience? (Reason: Once we have learned about general coding requirements in different occupation, we defnitely want to know if machine learning is a must!)\n4. How many years of machine learning experience do people have in different jobs? (Reason: to get a more comprehensive picture of the machine learning experience distribution.)\n5. What types of data do people work with in different jobs? (Reason: SImple and direct, we wanna see what type of data people usually work with.)\n6. Find out the activities that make up an important part of role at work? (Reason: Is data work all about coding?! NO! In our real work, we have a lot of other things to do, so i wanna check out the important activities invovled at work, this should differ from job to job. It's good to improve your soft skills in the meantime!!)\n7. During a typical data project at work, approximately where and how much of your time is devoted to? (Reason: We already know the main acitivities at work, but what about that in a data project?? and then i also wanna know what makes up the time in a data project!!)\n8. Percentage of time people spend on exploring model insights? (Reason: You get your model! Don't you wanna explore the insights of it to be able to better interpret it to non-technical audience? How much time you need on this part?)\n9. What's the primary tool people use at work? (Reason: We have talked about all the experience, the work, the activities, the time allocations, and it makes you excited! And then you wanna learn and prepare for getting that job, and it comes to a simple question: what tools you need to master to be an eligible candidate?!)\n10. Through which category people have their training on machine learning? (Reason: We all need to carry on learning and growing, and how and where people learn after they start their career?)\n11. How to evaluate if your current education background is enough for the occupation? (Reason: If you would like to have a long-term plan to see if you need further education for career goal, check it out!)\n12. Are you young enough? Interested in knowing the age distribution among different jobs? (Reason: People may say they are still young, so they are not worried about things, or some group of people complain they are too old to become something, wanna see how old your peers are?)\n\"\"\"\nimport os\nprint(os.listdir(\"..\/input\"))\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n## Data Loading and scope definition\n\nDue to the fact that in this analysis, I would like to focus on difference of job contents amaong different job titles, therefore, I will only consider the respondents who have a clear job title. For those who don't selected \"Others\" or \"Not employed\" or \"Students\", it's quite hard and unfair to be included in this analysis.\n\"\"\"\nmcr = pd.read_csv(\"..\/input\/multipleChoiceResponses.csv\", low_memory=False).iloc[1:, :]\nCONSIDERED_JOB_TITLE = ['Business Analyst', 'Chief Officer', 'Consultant',\n       'DBA\/Database Engineer', 'Data Analyst', 'Data Engineer',\n       'Data Journalist', 'Data Scientist', 'Developer Advocate',\n       'Manager', 'Marketing Analyst','Principal Investigator', 'Product\/Project Manager',\n       'Research Assistant', 'Research Scientist', 'Salesperson',\n       'Software Engineer', 'Statistician']\nmcr_jobs = mcr.loc[mcr[\"Q6\"].isin(CONSIDERED_JOB_TITLE)]\n\"\"\"\n## Gerneral look at distribution of job titles among all qualified respondents\n\nAs we expect, due to the nature of Kaggle, we can imagine that data scientist are the most.\n\"\"\"\nplt.figure(figsize=(18, 10))\nmcr_jobs[\"Q6\"].value_counts().plot(kind='bar')\n_ = plt.style.use('ggplot')\n_ = plt.title(\"Number of respondents in each job title\")\n_ = plt.xlabel(\"Job title\")\n_ = plt.ylabel(\"Counts\")\n\"\"\"\n## How much time do they code?!\n\nSince I am a data scientist, and I know in my daily work, except for writing codes, I also need to have meetings with different stakeholders. I think it's the same for other data scientist. But if you are not a meeting guy, and you want to work in data, you definitely want to know which occupation requires less meeting time. Let's take a look at how much time people in different occupations spend in coding! \n\n### Results are not very surprising:\n1. As the result presents, for occupations that are quite technical, like data scientist, data engineer, software engineers, most of them spend at least half of their time in coding! \n2. For managers, chiefs and salesperson, they spend least of time in coding, which is quite common sense. Their focus is not coding but business, strategy etc.\n3. And analysts are looking like positions in between, on the one hand, they will analyze the data and find insights, and on the other hand, they work closely with business and engineers. \n\"\"\"\nCODING_TIME = ['0% of my time', '1% to 25% of my time',\n       '25% to 49% of my time','50% to 74% of my time', \n       '75% to 99% of my time', '100% of my time']\n\nmcr_jobs[[\"Q6\", \"Q23\"]]\\\n        .dropna().groupby([\"Q6\", \"Q23\"]).size()\\\n        .groupby(\"Q6\").apply(lambda x: 100 * x \/ float(x.sum()))\\\n        .unstack(1)[CODING_TIME]\\\n        .plot(kind=\"bar\", stacked=True, figsize=(18, 10), \n              fontsize=15, colormap=plt.get_cmap(\"tab20\")\n             )\n\nplt.style.use(\"ggplot\")\nplt.title(\"Percentage of time on coding for different jobs\", fontsize=20)\nplt.ylabel(\"Percentage of Time on Coding\", fontsize=15)\nplt.xlabel(\"Job Titles\", fontsize=15)\nplt.legend(loc=\"center left\", bbox_to_anchor=(1.0, 0.5), fontsize=14)\nplt.show()\n\"\"\"\n## How long have people been writing code to analyze data?\n\nAfter knowing much time they need to spend on coding, i would like to know the experience they have to analyze data with code. And I would like to see if some positions require loads of coding experience.\n\n### Wanna get to principal\/chief\/higher position? it will take time! (From the first question, they seem have no time for coding now, but probably most of them have been through it):\n1. As we can see, for some positions, especially high level positions, like chief\/principal, althgough right now, it looks like they are not coding, based on the figure below, most of them have lots of years of coding experience. It's quite easy to understand, a good leader should be very familiar to the work, and thus be able to lead and plan the project.\n2. Don't be afraid! Most of people have similar experience as you! We could see that most of people in these technical positions have less than 5 years of using code to analyze data.\n\"\"\"\nCODING_YEAR = ['I have never written code and I do not want to learn',\n        'I have never written code but I want to learn', '< 1 year', '1-2 years', \n        '3-5 years', '5-10 years', '10-20 years', '20-30 years', \n        '30-40 years', '40+ years']\nmcr_code_year = mcr_jobs[[\"Q6\", \"Q24\"]]\\\n        .groupby([\"Q6\", \"Q24\"])\\\n        .size()\\\n        .to_frame(\"counts\")\\\n        .unstack(1)\\\n        .fillna(0)\nmcr_code_year = mcr_code_year[\"counts\"][CODING_YEAR]\nmcr_code_year = mcr_code_year.apply(lambda x: ((x \/ mcr_code_year.sum(axis=1)) * 100).round(0))\nplt.figure(figsize=(20, 10))\nsns.heatmap(mcr_code_year, annot=True)\n_ = plt.title(\"Percentage of how many years of experience people have to use coding skill to analyze data for different jobs\")\n_ = plt.xlabel(\"Years of experience\")\n_ = plt.ylabel(\"Job titles\")\n\"\"\"\n## Is machine learning experience important to your work?\n\nWe all talk about machine learning every single day, but is having machine learning a must?!\n\n### Wanna be data scientist, you'd better know it:\n1. For occupations like data scientist, statistician and research scientist, there is no doubt that they have experience since they constantly use them and develop new models and algorithms.\n2. For positions like chief or principal, similarly to coding experience, they also have learned machine learning for quite long time. It's not hard to understand, since they need to fully understand how models\/algorithms work so as to better interpret them to non-technical groups and lead a project (especially a huge one).\n3. If you are only into being analysts, you can spend less time on learning machine learning!\n\n\"\"\"\nML_YEARS = ['I have never studied machine learning and I do not plan to',\n        'I have never studied machine learning but plan to learn in the future',\n        '< 1 year', '1-2 years', '2-3 years', '3-4 years', '4-5 years', '5-10 years', \n        '10-15 years', '20+ years']\nmcr_ml_year = mcr_jobs[[\"Q6\", \"Q25\"]]\\\n        .groupby([\"Q6\", \"Q25\"])\\\n        .size()\\\n        .to_frame(\"counts\")\\\n        .unstack(1)\\\n        .fillna(0)\nmcr_ml_year = mcr_ml_year[\"counts\"][ML_YEARS]\n# create features for ml and non-ml\n\nno_ml = mcr_ml_year.iloc[:, :2].sum(axis=1).values\nwith_ml = mcr_ml_year.iloc[:, 2:].sum(axis=1).values\nmcr_ml_year_bi = pd.DataFrame(index=CONSIDERED_JOB_TITLE)\nmcr_ml_year_bi[\"No machine learning\"] = no_ml\nmcr_ml_year_bi[\"With machine learning\"] = with_ml\n\nmcr_ml_year_bi = mcr_ml_year_bi.apply(lambda x: ((x \/ mcr_ml_year_bi.sum(axis=1)) * 100).round(0))\\\n                            .stack()\\\n                            .reset_index()\\\n                            .rename(columns={\"level_0\": \"Q6\", \"level_1\": \"Q25\", 0: \"percentage\"})\n\nsns.catplot(x=\"Q6\", y='percentage', hue='Q25', height=12, data=mcr_ml_year_bi, kind='bar', palette=\"muted\")\n_ = plt.xticks(rotation=90)\n_ = plt.title(\"Percentage of positions having machine learning experience\")\nmcr_ml_year_multi = mcr_ml_year.apply(lambda x: ((x \/ mcr_ml_year.sum(axis=1)) * 100).round(0))\nplt.figure(figsize=(20, 10))\nsns.heatmap(mcr_ml_year_multi, annot=True)\n_ = plt.title(\"Percentage of people's ML experience in different job positions\")\n_ = plt.xlabel(\"Years of experience\")\n_ = plt.ylabel(\"Job titles\")\n\"\"\"\n## What type of data do people work with?\n\nHere we take a glimpse at the different data type that people in different occupations work with! Although this can be significantly impacted by the industry you are in, we stilll can get some insights out of it!\n\n### We all use numeric data:\n1. Apparently, most of people regardless of occupation are working with numeric data. \n2. Categorical, text, tabular and time series are also common!\n3. Tecnical positions have more chance to explore more type of data.\n\"\"\"\nDATA_TYPE_LIST = ['Audio Data', 'Categorical Data', 'Genetic Data',\n       'Geospatial Data', 'Image Data', 'Numerical Data', 'Sensor Data',\n       'Tabular Data', 'Text Data', 'Time Series Data', 'Video Data',\n       'Other Data']\nmcr_data_type = mcr_jobs.filter(regex=\"^(?!.*TEXT)(Q31)\").fillna(0)\nori_list = mcr_data_type.columns.tolist()\n\nfor col in mcr_data_type:\n    mcr_data_type[col] = mcr_data_type[col].apply(lambda x: 1 if x!=0 else 0)\n    \nmcr_data_type = mcr_data_type.rename(columns=dict(zip(ori_list, DATA_TYPE_LIST)))\nmcr_data_type = mcr_data_type.merge(mcr_jobs[[\"Q6\"]], left_index=True, right_index=True)\nsum_datatype = mcr_data_type.groupby(\"Q6\")[DATA_TYPE_LIST].sum().T\nfig, ax = plt.subplots(nrows=6, ncols=3, sharex=True, sharey=True, figsize=(20, 30))\nn = 1\nfor job in sum_datatype:\n    plt.subplot(6, 3, n)\n    sum_datatype[job].plot(kind=\"bar\", title=job, fontsize=8)\n    n +=1\nplt.subplots_adjust(hspace = 1)\nplt.show()\n\"\"\"\n## Which activity makes up an important part of role at work?\n\nThere are many types of activities at work, and we would like to take a deeper look at which activities are important to which occupations. Once we know this, we can have a more complete picture of what job content they have.\n\n### You can have lots of ideas, but understand your data first!!!\n1. We can have a lot of ideas, but before buiding something from scratch, you have to spend time collecting, cleaning, analyzing and understanding your data!\n2. Engineers live with building infrastructure & service! Scientists and analysts can create hundreds of models, but they all need to place to run (especially if your company wants to productionize it), data engineers\/database engineer build the foundation for you!\n3. Build prototypes or experiment machine learning models are the first-go! Before putting things in production, they need prototypes to prove the feasibility.\n\"\"\"\nACTIVITIES = [\"Understand data\", \"Build service\", \n              \"Build infrastructure\", \"Build prototype\", \n              \"Advanced research\", \"Not related\", \"Other\"]\n\nmcr_activity = mcr_jobs.filter(regex=\"^(?!.*TEXT)(Q11)\").fillna(0)\nactivity_list = mcr_activity.columns.tolist()\nmcr_activity = mcr_activity.rename(columns=dict(zip(activity_list, ACTIVITIES)))\nfor col in mcr_activity:\n    mcr_activity[col] = mcr_activity[col].apply(lambda x: 1 if x!=0 else 0)\nmcr_activity = mcr_activity.merge(mcr_jobs[[\"Q6\"]], left_index=True, right_index=True)\ntransposed_activities = mcr_activity.groupby(\"Q6\")[ACTIVITIES].sum().T\nfull_activity = [\"Analyze and understand data to influence product or business decisions\",\n                \"Build and\/or run a machine learning service that operationally improves my product or workflows\",\n                \"Build and\/or run the data infrastructure that my business uses for storing, analyzing, and operationalizing data\",\n                \"Build prototypes to explore applying machine learning to new areas\",\n                \"Do research that advances the state of the art of machine learning\",\n                \"None of these activities are an important part of my role at work\",\n                \"Others\"]\ncolors = [\"Red\", \"Blue\", \"Purple\", \"Grey\", \"Yellow\", \"Green\", \"Pink\"]\nfor col, act in zip(colors, full_activity):\n    print( col + \"  ->  \" + act)\nfig, ax = plt.subplots(nrows=6, ncols=3, sharex=True, sharey=True, figsize=(20, 20))\nn = 1\nfor job in transposed_activities:\n    plt.subplot(6, 3, n)\n    transposed_activities[job].plot(kind=\"bar\", title=job, fontsize=6)\n    n +=1\nplt.subplots_adjust(hspace = 1)\nplt.show()\n\n\"\"\"\n## How the time is distributed in data project?\n\nIn a general data project, where do you spend your most time on?\n\n### From the last question, we know collecting and cleaning are very important part in the role. But they are always not EASY to do! \n1. Collecting and cleaning data are time consuming.\n2. Seeing 'putting model into production' just takes very little time (around 5% on average), this can explain the fact that most of our experiements\/exploration\/models will not impact the real world since the project will die before this stage. And putting the model into production really means something!\n\"\"\"\nWORK_DETAILS = ['Gathering data', 'Cleaning data', \n            'Visualizing data', 'Model building\/model selection', \n            'Putting the model into production', \n            'Finding insights in the data and communicating with stakeholders']\nmcr_time = mcr_jobs.filter(regex=(\"^(?!.*TEXT)(Q6|Q34)\"), axis=1)\\\n                .dropna()\nmcr_time.columns = [\"Q6\"] + WORK_DETAILS\nmcr_time[WORK_DETAILS] = mcr_time[WORK_DETAILS].astype(float)\nmcr_time.groupby(\"Q6\").agg(np.mean)\\\n    .plot.barh(stacked=True, figsize=(20, 10), fontsize=15)\n\nplt.title(\"Average time percentage devoted on data projects for different titles\", fontsize=20)\nplt.ylabel(\"Job Titles\", fontsize=15)\nplt.xlabel(\"Time percentage\", fontsize=15)\nplt.legend(loc=\"center left\", bbox_to_anchor=(1.0, 0.5), fontsize=14)\nplt.show()\n\"\"\"\n## How much time you have on exploring model insights?\n\nThis is usually the part coming after obtaining the result! A deep and clear insight of the model can help improve the communication between business and technique very much!\n\n### Wanna tell a better story? Spend more time on exploring insights:\n1. Chief officers & pricipals & managers need to spend more time on it to tell a better story.\n2. Data scientists and statisticians need to gain more insights to help themselves evaluate, analyze and improve the result!\n\"\"\"\nmcr_insight = mcr_jobs[[\"Q6\", \"Q46\"]]\\\n                        .dropna()\\\n                        .groupby([\"Q6\", \"Q46\"])\\\n                        .size()\\\n                        .unstack(1)\\\n                        .fillna(0)\n\nmcr_insight = mcr_insight.apply(lambda x: (x \/ mcr_insight.sum(axis=1) * 100).round(0))\n\nplt.figure(figsize=(20, 10))\nsns.heatmap(mcr_insight, cmap=\"YlGnBu\")\n\n_ = plt.title(\"Distribution of percentage of time people have on exploring model insights.\")\n_ = plt.xlabel(\"Slots\")\n_ = plt.ylabel(\"Job titles\")\n\"\"\"\n## Here it is, what tools are they primarily using at work?\n\nYou know all their work from a macro perspective, now it comes down to the ground, what tools do they use at work? If you wanna be in this occupation but haven't learned the tools that they all use, better start learning it! FYI, this counts are quite rough and i have to say not very accurate since it's extracted from free form responses, but the result at least tells something.\n\n### Jupyter dominates!!\n1. Jupyter are very widely used nowadays.\n2. Python, excel and Rstudio are coming after! We can aware that for the occupations that need storytelling or interpretation, Rstudio are very popular! It's not hard to understand since R is a very nice tool for visualization. \n3. Excel are still popular. And they are even more popular among data scientist!! hope it is because my mistake in transforming data :)\n\"\"\"\njob_index = mcr_jobs.index\nmcr_ffr = pd.read_csv(\"..\/input\/freeFormResponses.csv\", low_memory=False).filter(regex=\"Q12\").iloc[job_index, :]\ndrop_cols = mcr_ffr.columns.tolist()\nTOOLS = ['jupyter', 'python', 'pycharm', 'anaconda', 'matlab', 'rstudio', 'visual studio', 'excel', 'docker', 'sql'\n    , 'bash', 'spark', 'scala', 'emacs', 'tensor', 'torch', 'scikit', 'xgb', 'hadoop', 'jupyterlab', 'cloudera'\n, 'c++', 'tableau', 'pandas', 'keras', 'ide', 'orange', 'colab', 'aws', 'mxnet', 'databricks', 'spyder', 'java',\n'h2o', 'slack', 'zeppelin', 'sas', 'spss', 'nltk', 'powerbi']\n\nmcr_ffr[\"summary\"] = mcr_ffr.apply(lambda x: set([i for i in x if i is not np.nan]), axis=1)\nmcr_ffr[\"summary\"] = mcr_ffr[\"summary\"].apply(lambda x: [i.lower() for i in x])\nmcr_ffr = mcr_ffr[mcr_ffr[\"summary\"].apply(lambda x: len(x)) == 1]\nfor t in TOOLS:\n    mcr_ffr[t] = 0\n    \nfor idx, r in mcr_ffr.iterrows():\n    for t in TOOLS:\n        if t in r['summary'][0]:\n            mcr_ffr.set_value(idx, t, 1)\n            \ndrop_cols = drop_cols + [\"summary\"]\nmcr_tool = mcr_ffr.merge(mcr_jobs[['Q6']], right_index=True, left_index=True)\\\n        .drop(drop_cols, axis=1)\nfig, ax = plt.subplots(nrows=6, ncols=3, sharex=True, sharey=True, figsize=(20, 20))\nn = 1\nfor job in CONSIDERED_JOB_TITLE:\n    sub_job = mcr_tool[mcr_tool[\"Q6\"] == job]\n    txt = \",\".join(sub_job[TOOLS].sum(axis=0).sort_values(ascending=False).index)\n    plt.subplot(6, 3, n)\n    wordcloud = WordCloud(colormap=\"Reds\", width=900, height=480,\n                      normalize_plurals=False).generate(txt)\n    plt.imshow(wordcloud, interpolation='bilinear')\n    plt.title(job)\n    plt.axis(\"off\")\n    n +=1\nplt.subplots_adjust(hspace = 0.2)\nplt.show()\n\"\"\"\n### How many language tools people use primarily?\n\nLooks like most of people have only one main tool to use, quite disappointed at the result, but probably after some more corrections and better data wrangling, should get better and more accurate result!\n\"\"\"\nmcr_tool[\"num_tools\"] = mcr_tool.iloc[:, :-1].apply(lambda x: sum(x), axis=1)\nmcr_num_tool = mcr_tool[[\"num_tools\", \"Q6\"]]\npal = sns.cubehelix_palette(10, rot=-.25, light=1)\ng = sns.FacetGrid(mcr_num_tool, row=\"Q6\", hue=\"Q6\", aspect=15, height=1, palette=pal)\n\ng.map(sns.kdeplot, \"num_tools\", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)\ng.map(sns.kdeplot, \"num_tools\", clip_on=False, color=\"w\", lw=2, bw=.2)\ng.map(plt.axhline, y=0, lw=2, clip_on=False)\n\ndef label(x, color, label):\n    ax = plt.gca()\n    ax.text(0, .2, label, fontweight=\"bold\", color=color,\n            ha=\"left\", va=\"center\", transform=ax.transAxes)\n\ng.map(label, \"num_tools\")\ng.fig.subplots_adjust(hspace=.25)\n\ng.set_titles(\"\")\ng.set(yticks=[])\ng.despine(bottom=True, left=True)\n\"\"\"\n## Where do they train on machine learning?\n\nYou have known the work acitivities, the coding requirement, and the tool they use at work. But learning never stops, and we are curious where they learn and train their machine leanring skills?\n\n### You should believe in and rely on yourselves!!!\n1. Self-taught and online courses are most commonly ways people train their machine learning skill. Nowadays, we can easily get free online resources and learn everything online and by yourself, as long as you have strong learning ability, you can do a good job as well!\n2. Data scientists are working while learning!! I can also feel the same that through doing a project, I learn a lot along with the process.\n\"\"\"\nTRAIN_CAT = [\"Self-taught\", \"Online courses\", \"Work\", \"University\", \"Kaggle competitions\", \"Other\"]\nmcr_train = mcr_jobs.filter(regex=\"^(?!.*TEXT)(Q35|Q6)\").dropna(axis=0)\nmcr_train.columns = [\"Q6\"] + TRAIN_CAT\nmcr_train[TRAIN_CAT] = mcr_train[TRAIN_CAT].astype(float)\n\nmcr_train.groupby(\"Q6\").mean()\\\n        .plot(kind=\"bar\", stacked=True, \n              figsize=(18, 10), fontsize=15, \n              colormap=plt.get_cmap(\"tab20\"))\n\nplt.title(\"Percentage of training on ML fell on different categories\", fontsize=20)\nplt.ylabel(\"Percentage\", fontsize=15)\nplt.xlabel(\"Job Titles\", fontsize=15)\nplt.legend(loc=\"center left\", bbox_to_anchor=(1.0, 0.5), fontsize=14)\nplt.show()\n\"\"\"\n## What kind of education background do they have?\nIf you want to evaluate yourself and think long-term of yourself in the career development at a certain stage, look at the education background most people have in that occupation.\n\n### Good! PhD is not a MUST-HAVE for data scientist!?\n1. Most of people have Master's degree. Should be sufficient for most of jobs.\n2. Would like to end up high? PhD might help!\n3. Researches really need high education background!\n4. Data Engineers\/DBA engineers prefer practical over academical.\n\"\"\"\nEDU_BACKGROUND = [\"Bachelor\u2019s degree\", \"Master\u2019s degree\", \"Doctoral degree\", \n                  \"Professional degree\", \"Some college\/university study without earning a bachelor\u2019s degree\",\n                  \"No formal education past high school\"]\n\nmcr_job_edu = mcr_jobs[[\"Q6\", \"Q4\"]]\\\n        .groupby([\"Q6\", \"Q4\"])\\\n        .size()\\\n        .to_frame(\"counts\")\\\n        .unstack(1)\\\n        .fillna(0)\nmcr_job_edu = mcr_job_edu['counts'][EDU_BACKGROUND]\nmcr_job_edu = mcr_job_edu.apply(lambda x: ((x \/ mcr_job_edu.sum(axis=1)) * 100).round(0))\nplt.figure(figsize=(20, 10))\nsns.heatmap(mcr_job_edu, cmap=\"Oranges\", annot=True)\n\n_ = plt.title(\"Distribution of percentage of education background people have in different occupations.\")\n_ = plt.xlabel(\"Educations\")\n_ = plt.ylabel(\"Job titles\")\n\"\"\"\n## Age distribution in different job occupations\n\nIn order better visualize this, I randomly sampled their age based on the range they select using np.random.randint. \n\n### Interesting facts:\n1. Most of research assistants are quite young, however, research scientists' ages are more sparsed. Probably, assistants will become scientists later, so, keey working!!\n2. It needs time to become principals, probably because it requires years of experience. However, Chief officers look more achievable at younger age, probably due to the fact that there are a lot of talented people in start-ups etc. \n3. 25-40 looks like the main forces!!\n\"\"\"\nmcr_age = mcr_jobs[[\"Q6\", \"Q2\"]]\nrandom_sampled_age = mcr_age[\"Q2\"].apply(lambda x: np.random.randint(int(x.split(\"-\")[0]), int(x.split(\"-\")[1])) \n                                                  if (len(x.split(\"-\")) == 2) else 80)\nmcr_age[\"age\"] = random_sampled_age\nplt.figure(figsize=(30, 15))\nsns.swarmplot(x=\"Q6\", y=\"age\", hue=\"Q2\",\n              palette=\"RdBu\", data=mcr_age)\n_ = plt.xticks(rotation=90)\n_ = plt.title(\"Age distribution among different job occupations\")\n_ = plt.xlabel(\"Job titles\")\n_ = plt.ylabel(\"Age\")\n\"\"\"\n# Future work and to be done:\n1. Get more insights through digging deeper, for example, check the impact of industry\/country\/age\/etc on the job content for different occupations\n2. Suggest a path or doing what can lead you to be a good ** for different occupations\n3. Trying to explore columns and responds to make up a final story to submit.\n4. Structure the functions and clean the codes to make it more efficient and reusable.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ebf4475abff738'}"}
{"id":"25484","text":"# 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, explained_variance_score, r2_score \nfrom sklearn.metrics import mean_poisson_deviance, mean_gamma_deviance, accuracy_score\nfrom xgboost import XGBRegressor\ndf_bitcoin = pd.read_csv('..\/input\/all-cryptocurrencies-price-20152021\/Bitcoin\/BTC-USD.csv')\ndf_bitcoin.head()\ndf_bitcoin.shape\nmissing_values=pd.DataFrame(df_bitcoin.isna().sum().sort_values(ascending=False),columns=['Missing_values'])\nmissing_values['%']=(missing_values.Missing_values\/2193)*100\nmissing_values\ndf_dogecoin = pd.read_csv('..\/input\/all-cryptocurrencies-price-20152021\/Dogecoin\/DOGE-USD.csv')\ndf_dogecoin.head()\nmissing_values2=pd.DataFrame(df_dogecoin.isna().sum().sort_values(ascending=False),columns=['Missing_values'])\nmissing_values2['%']=(missing_values.Missing_values\/2193)*100\nmissing_values2\ndf_ethereum = pd.read_csv('..\/input\/all-cryptocurrencies-price-20152021\/Ethereum\/ETH-USD.csv')\ndf_ethereum.head()\nmissing_values3=pd.DataFrame(df_ethereum.isna().sum().sort_values(ascending=False),columns=['Missing_values'])\nmissing_values3['%']=(missing_values.Missing_values\/2193)*100\nmissing_values3\ndf_cardano = pd.read_csv('..\/input\/all-cryptocurrencies-price-20152021\/Cardano\/ADA-USD.csv')\nmissing_values4=pd.DataFrame(df_ethereum.isna().sum().sort_values(ascending=False),columns=['Missing_values'])\nmissing_values4['%']=(missing_values.Missing_values\/2193)*100\nmissing_values4.head()\nfor col in df_bitcoin.columns:\n    print(type(col))\n\"\"\"\n# Converting the Date column to datetime\n\"\"\"\ndf_bitcoin['Date']=pd.to_datetime(df_bitcoin['Date'])\ndf_dogecoin['Date']=pd.to_datetime(df_dogecoin['Date'])\ndf_ethereum['Date']=pd.to_datetime(df_ethereum['Date'])\ndf_cardano['Date']=pd.to_datetime(df_cardano['Date'])\ndf_bitcoin.head()\n\"\"\"\n# Trend followed by closing price\n\"\"\"\nfig = plt.figure(figsize = (16,7))\n\nplt.plot(df_bitcoin.Date,df_bitcoin.Close,color='purple')\nplt.plot(df_dogecoin.Date,df_dogecoin.Close,color='red')\nplt.plot(df_ethereum.Date,df_ethereum.Close,color='violet')\nplt.plot(df_cardano.Date,df_cardano.Close,color='yellow')\n\nplt.title('Closing Price Trend')\nplt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])\nplt.show()\n\"\"\"\n# Volume Trend\n\"\"\"\nfig = plt.figure(figsize = (17,11))\n\nplt.subplot(2,2,1)\nplt.plot(df_bitcoin.Date,df_bitcoin.Volume,color='purple')\nplt.title('Bitcoin')\n\n\nplt.subplot(2,2,2)\nplt.plot(df_dogecoin.Date,df_dogecoin.Volume,color='red')\nplt.title('Dogecoin')\n\nplt.subplot(2,2,3)\n\nplt.plot(df_ethereum.Date,df_ethereum.Volume,color='blue')\nplt.title('Ethereum')\n\n\nplt.subplot(2,2,4)\n\nplt.plot(df_cardano.Date,df_cardano.Volume,color='violet')\nplt.title('Cardano')\n\nfig.tight_layout()\n\"\"\"\n# Analysis of Closing price over the last two years\n\"\"\"\ntwo_year_bitcoin=df_bitcoin[df_bitcoin.Date>'2019-09']\ntwo_year_dogecoin=dogecoin=df_dogecoin[df_dogecoin.Date>'2019-09']\ntwo_year_ethereum=df_ethereum[df_ethereum.Date>'2019-09']\ntwo_year_cardano=df_cardano[df_cardano.Date>'2019-09']\nfig = plt.figure(figsize = (16,7))\n\nplt.plot(two_year_bitcoin.Date,two_year_bitcoin.Close,color='purple')\nplt.plot(two_year_dogecoin.Date,two_year_dogecoin.Close,color='red')\nplt.plot(two_year_ethereum.Date,two_year_ethereum.Close,color='blue')\nplt.plot(two_year_cardano.Date,two_year_cardano.Close,color='violet')\nplt.title('Closing Price over 2 years')\nplt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])\nplt.show()\n\"\"\"\n# Trend followed by Volume over the last two years\n\"\"\"\nfig = plt.figure(figsize = (16,7))\n\nplt.plot(two_year_bitcoin.Date,two_year_bitcoin.Volume,color='purple')\nplt.plot(two_year_dogecoin.Date,two_year_dogecoin.Volume,color='red')\nplt.plot(two_year_ethereum.Date,two_year_ethereum.Volume,color='blue')\nplt.plot(two_year_cardano.Date,two_year_cardano.Volume,color='violet')\n\nplt.title('Volume over two years')\nplt.legend(['Bitcoin','Dogecoin','Ethereum','Cardano'])\nplt.show()\n\"\"\"\n# Comparion between open and closing price for Cryptocurrencies\n\n\"\"\"\nfig = plt.figure(figsize = (17,17))\n\nplt.subplot(4, 1, 1)\nplt.plot(two_year_bitcoin.Date,two_year_bitcoin['Close'],color='purple')\nplt.plot(two_year_bitcoin.Date,two_year_bitcoin['Open'],color='red')\nplt.legend(['Closing','Open'])\nplt.title('Bitcoin')\n\nplt.subplot(4, 1, 2)\nplt.plot(two_year_dogecoin.Date,two_year_dogecoin['Close'],color='red')\nplt.plot(two_year_dogecoin.Date,two_year_dogecoin['Open'],color='green')\nplt.legend(['Closing','Open'])\nplt.title('Dogecoin')\n\nplt.subplot(4, 1, 3)\nplt.plot(two_year_ethereum.Date,two_year_ethereum['Close'],color='black')\nplt.plot(two_year_ethereum.Date,two_year_ethereum['Open'],color='green')\nplt.legend(['Closing','Open'])\nplt.title('Ethereum')\n\nplt.subplot(4, 1, 4)\nplt.plot(two_year_cardano.Date,two_year_cardano['Close'],color='green')\nplt.plot(two_year_cardano.Date,two_year_cardano['Open'],color='purple')\nplt.legend(['Closing','Open'])\nplt.title('Cardano')\n\n\nfig.tight_layout()\n\"\"\"\n# Daily Change of Cryptocurrency\n\"\"\"\nfig = plt.figure(figsize = (15,10))\n\nplt.subplot(2, 2, 1)\nplt.plot(df_bitcoin.Date,df_bitcoin['Adj Close'].pct_change(),color='purple')\nplt.title('Bitcoin')\n\nplt.subplot(2, 2, 2)\nplt.plot(df_dogecoin.Date,df_dogecoin['Adj Close'].pct_change(),color='red')\nplt.title('Dogecoin')\n\nplt.subplot(2, 2, 3)\nplt.plot(df_ethereum.Date,df_ethereum['Adj Close'].pct_change(),color='yellow')\nplt.title('Ethereum')\n\nplt.subplot(2, 2, 4)\nplt.plot(df_cardano.Date,df_cardano['Adj Close'].pct_change(),color='green')\nplt.title('Cardano')\n\n\nfig.tight_layout()\n\"\"\"\n# Density plots for daily return\n\"\"\"\nfig = plt.figure(figsize = (15,10))\n\nplt.subplot(2, 2, 1)\nsns.distplot(df_bitcoin['Adj Close'].pct_change(),kde=True,color='blue')\nplt.xlabel('Daily Return')\nplt.ylabel('Daily Return')\nplt.title('Bitcoin')\n\nplt.subplot(2, 2, 2)\nsns.distplot(df_dogecoin['Adj Close'].pct_change(),color='red')\nplt.xlabel('Daily Return')\nplt.ylabel('Daily Return')\nplt.title('Dogecoin')\n\nplt.subplot(2, 2, 3)\nsns.distplot(df_ethereum['Adj Close'].pct_change(),color='purple')\nplt.xlabel('Daily Return')\nplt.ylabel('Daily Return')\nplt.title('Ethereum')\n\nplt.subplot(2, 2, 4)\nsns.distplot(df_cardano['Adj Close'].pct_change(),color='green')\nplt.title('Cardano')\nplt.xlabel('Daily Return')\nplt.ylabel('Daily Return')\n\nfig.tight_layout()\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\n\n\"\"\"\n# Bitcoin Predictions\n\"\"\"\nfinal_df=df_bitcoin[['Date','Close']]\nfinal_df=final_df[final_df.Date>'2020-09']\nfinal_df.head()\nfig = plt.figure(figsize = (10,10))\nplt.plot(final_df.Date,final_df.Close,color='purple')\nplt.title('Close Price History')\nplt.xlabel('Date',fontsize=18)\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n# New Dataframe with only the Closed column\n\"\"\"\nfinal_df=final_df.set_index('Date')\ndata=final_df.filter(['Close'])\ndata.head()\ndata.isna().sum()\ndata=data.dropna(subset=['Close'])\ndata.shape\ndataset=data.values\ntraining_data_len=int(np.ceil(len(dataset)*0.8))\ntraining_data_len\n\"\"\"\n# Scale the Data\n\"\"\"\nmms=MinMaxScaler(feature_range=(0,1))\nscaled_data=mms.fit_transform(dataset)\n\"\"\"\n# Creating a Training dataset\n\"\"\"\ntrain_data=scaled_data[0:training_data_len ,:]\nlen(train_data)\nX_train=[]\ny_train=[]\n\nfor i in range(60,len(train_data)):\n    X_train.append(train_data[i-60:i,0])\n    y_train.append(train_data[i,0])\nX_train,y_train=np.array(X_train),np.array(y_train)\nX_train=np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))\nX_train.shape\n\"\"\"\n# LSTM Model\n\"\"\"\nmodel=Sequential()\nmodel.add(LSTM(128,return_sequences=True,input_shape=(X_train.shape[1],1)))\nmodel.add(LSTM(64,return_sequences=False))\nmodel.add(Dense(25))\nmodel.add(Dense(1))\nmodel.compile(optimizer='adam',loss='mean_squared_error')\nmodel.fit(X_train, y_train, batch_size=1, epochs=1)\n\"\"\"\n# Train the model\n\n\"\"\"\n\"\"\"\n# Test Data set\n\"\"\"\ntest_data=scaled_data[training_data_len-60:621:,:]\n\nX_test=[]\ny_test=dataset[training_data_len:,:]\n\nfor i in range(60,len(test_data)):\n    X_test.append(test_data[i-60:i,0])\nX_test=np.array(X_test)\nX_test=np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))\nX_test.shape\n\"\"\"\n# Predicted Price\n\"\"\"\npredictions=model.predict(X_test)\npredictions=mms.inverse_transform(predictions)\ntrain=data[:training_data_len]\nvalid=data[training_data_len:]\nvalid['Predictions']=predictions\ntrain\n\nplt.figure(figsize=(15,15))\nplt.title('Model')\n\nplt.xlabel('Date',fontsize=16)\nplt.ylabel('Closed Price ',fontsize=16)\n\nplt.plot(train['Close'])\nplt.plot(valid[['Close','Predictions']])\n\nplt.legend(['Train','Validation','Predictions'])\nplt.show()","meta":"{'source': 'AI4Code', 'id': '2eeb0024e9cede'}"}
{"id":"121387","text":"# 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        file = 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\n\"\"\"\nImporting necessary libraries.\n\"\"\"\nfrom tensorflow.keras.layers import Input, Dense, Flatten\nfrom keras import Model\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\n\"\"\"\nAs we are using VGG16 architecture, it expects the size of 224 by 224(Although, you can set your own size). We will set image size.\n\"\"\"\nimage_size = [224, 224]\nvgg = VGG16(input_shape = image_size + [3], weights = 'imagenet', include_top =  False)\n\"\"\"\nThe first argument is the shape of input image plus **3**(as image is colured[RBG], for black_and_white add **1**).\nThe second one is the weights eqaul to imagenet. And,\nas we know it gives 1000 outputs. Third one excludes the top layer.\n\"\"\"\nfor layer in vgg.layers:\n    layer.trainable = False\n\"\"\"\nSome of the layers of VGG16 are already trained. To train them again is not a good practice. Thereby making it False\n\"\"\"\nfrom glob import glob\nfolders = glob('\/kaggle\/input\/tomato\/New Plant Diseases Dataset(Augmented)\/train\/*')\nfolders\n\n\"\"\"\nFlattening the output layer\n\"\"\"\nx = Flatten()(vgg.output)\nprediction = Dense(len(folders), activation = 'softmax')(x)\nmodel = Model(inputs = vgg.input, outputs = prediction)\nmodel.summary()\n\"\"\"\nCompiling the model\n\"\"\"\nmodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n\"\"\"\nGenerating more images\n\"\"\"\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_data_gen = ImageDataGenerator(rescale = 1.\/255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)\ntest_data_gen = ImageDataGenerator(rescale = 1.\/255)\ntrain_set = train_data_gen.flow_from_directory('\/kaggle\/input\/tomato\/New Plant Diseases Dataset(Augmented)\/train\/', target_size = (224,224), batch_size = 32, class_mode = 'categorical')\ntest_set = test_data_gen.flow_from_directory('\/kaggle\/input\/tomato\/New Plant Diseases Dataset(Augmented)\/valid\/', target_size = (224,224), batch_size = 32, class_mode = 'categorical')\n\"\"\"\nFitting the model\n\"\"\"\nmod = model.fit_generator(\n  train_set,\n  validation_data=test_set,\n  epochs=10,\n  steps_per_epoch=len(train_set),\n  validation_steps=len(test_set)\n)\nimport matplotlib.pyplot as plt\nplt.plot(mod.history['loss'], label='train loss')\nplt.plot(mod.history['val_loss'], label='val loss')\nplt.legend()\nplt.show()\n\n\nplt.plot(mod.history['accuracy'], label='train accuracy')\nplt.plot(mod.history['val_accuracy'], label='val_accuracy')\nplt.legend()\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'df4942e17ee880'}"}
{"id":"71132","text":"\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:270%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nTabular Playground Series - Oct 2021\n<\/div>\n\"\"\"\n\"\"\"\n<a><img src=\"https:\/\/i.ibb.co\/PWvpT9F\/header.png\" alt=\"header\" border=\"0\" width=800 height=400><\/a>\n\"\"\"\nimport pandas as pd, numpy as np, os, matplotlib.pyplot as plt, seaborn as sns\nimport datatable as dt\nimport warnings\nimport random\nwarnings.filterwarnings('ignore')\npd.set_option('max_columns',None)\nimport gc\n#import cudf #only works when gpu on\nfrom sklearn.metrics import roc_auc_score,auc, roc_curve\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingClassifier\nimport plotly.figure_factory as ff\nimport plotly.express as px\n\nfrom time import time\nimport pprint\nimport joblib\nfrom functools import partial\nimport lightgbm as lgb\nfrom sklearn.model_selection import KFold, StratifiedKFold\nPLOT = False\n\n#notebook setup\ndef seed_everything(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n\n    \nTARGET = 'target'\nFOLD = 5\nSEED = 69\nN_ESTIMATORS=10000\nDEVICE = 'CPU'\nEVAL_METRIC = \"AUC\"\n\nSTUDY_TIME = 60*60*8\nseed_everything(SEED)\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#dd4124;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nNote: Upvote is Free!!!\n<\/div>\n\"\"\"\n%time\n\n#import data\ntrain = dt.fread(r\"..\/input\/d\/ankitkalauni\/tps-october-2021-dataset\/train.csv\").to_pandas()\ntest = dt.fread(r\"..\/input\/d\/ankitkalauni\/tps-october-2021-dataset\/test.csv\").to_pandas()\n\n# train.columns = ['f1', 'f2', 'f3', 'f4', 'f5', 'target', 'f6',\n#        'f7', 'f8', 'f9', 'f10', 'f11',\n#        'f12', 'f13', 'f14', 'f15', 'f16',\n#        'f17', 'f18', 'f19', 'f20','f21']\n\n# test.columns = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6',\n#        'f7', 'f8', 'f9', 'f10', 'f11',\n#        'f12', 'f13', 'f14', 'f15', 'f16',\n#        'f17', 'f18', 'f19', 'f20','f21']\n\n\nsample_submission = pd.read_csv('..\/input\/tabular-playground-series-oct-2021\/sample_submission.csv')\n\ntrain[TARGET] = train[TARGET].astype('int64') \nprint('Train Shape: ',train.shape)\ntrain.tail(10).reset_index(drop=True)\nprint('Test Shape: ',test.shape)\ntest.head(10)\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nPreprocessing\n<\/div>\n\n___\n\"\"\"\n#setup for preprocessing\nX = train.drop(TARGET, axis=1)\ny = train[TARGET]\nX_test = test\n\n#delete the old datframes from the memory\ndel train, test\ngc.collect()\n# helper functions\ndef get_auc(y_true, y_hat):\n    fpr, tpr, _ = roc_curve(y_true, y_hat)\n    score = auc(fpr, tpr)\n    return score\n#best parameters searched using optuna \nhist_params = {'l2_regularization': 1.3244040135051264e-10,\n               'early_stopping': 'True',\n               'learning_rate': 0.0366777965884429, \n               'max_iter': 10000, \n               'max_depth': 3, \n               'max_bins': 129, \n               'min_samples_leaf': 13449, \n               'max_leaf_nodes': 68}\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nTrain-set KDE Plot\n<\/div>\n\"\"\"\nif PLOT == True:\n    X_data = [X.f1,  X.f2,  X.f3,  X.f4,  X.f5,  X.f6,  X.f7,  X.f8,  X.f9,  X.f10,  X.f11,  X.f12,  X.f13,  X.f14,  X.f15,  X.f16,  X.f17,  X.f18,  X.f19,  X.f20, X.f21]\n    group_labels = X.columns.to_list()\n    fig = ff.create_distplot(X_data, group_labels, bin_size=0.3, show_hist=False, show_rug=False)\n    fig.show()\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nTest-set KDE Plot\n<\/div>\n\"\"\"\nif PLOT == True:\n    _data = [X_test.f1,  X_test.f2,  X_test.f3,  X_test.f4,  X_test.f5,  X_test.f6,  X_test.f7,  X_test.f8,  X_test.f9,  X_test.f10,  X_test.f11,  X_test.f12,  X_test.f13,  X_test.f14,  X_test.f15,  X_test.f16,  X_test.f17,  X_test.f18,  X_test.f19,  X_test.f20, X_test.f21]\n    fig = ff.create_distplot(_data, group_labels, bin_size=0.3, show_hist=False, show_rug=False)\n    fig.show()\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nTrain-set Heatmap Plot\n<\/div>\n\"\"\"\nif PLOT == True:\n    #correlation between all models pred\n    data = np.corrcoef(X_data)\n    fig=px.imshow(data,x=group_labels, y=group_labels)\n\n    fig.show()\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nTest-set Heatmap Plot\n<\/div>\n\"\"\"\nif PLOT == True:\n    #correlation between all models pred\n    data = np.corrcoef(_data)\n    fig=px.imshow(data,x=group_labels, y=group_labels)\n\n    fig.show()\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nHistGBM\n<\/div>\n\"\"\"\n\"\"\"\n# Histogram-based Gradient Boosting Classification Tree.\n\nThis estimator is much faster than\n:class:`GradientBoostingClassifier<sklearn.ensemble.GradientBoostingClassifier>`\nfor big datasets (n_samples >= 10 000). The input data ``X`` is pre-binned\ninto integer-valued bins, which considerably reduces the number of\nsplitting points to consider, and allows the algorithm to leverage\ninteger-based data structures. For small sample sizes,\n:class:`GradientBoostingClassifier<sklearn.ensemble.GradientBoostingClassifier>`\nmight be preferred since binning may lead to split points that are too\napproximate in this setting.\n\nThis implementation is inspired by\n`LightGBM <https:\/\/github.com\/Microsoft\/LightGBM>`_.\n\n## note:\n\n  This estimator is still **experimental** for now: the predictions\n  and the API might change without any deprecation cycle. To use it,\n  you need to explicitly import ``enable_hist_gradient_boosting``::\n\n    >>> # explicitly require this experimental feature\n    >>> from sklearn.experimental import enable_hist_gradient_boosting  # noqa\n    >>> # now you can import normally from ensemble\n    >>> from sklearn.ensemble import HistGradientBoostingClassifier\n\n\"\"\"\n\"\"\"\n[Tutorial Gradient Boosting - StatQuest](https:\/\/www.youtube.com\/embed\/3CC4N4z3GJc)\n\"\"\"\n#check of all the columns in train is in test set\nassert X.columns.to_list() == X_test.columns.to_list()\n\nmeta_pred_tmp = []\nscores_tmp = []\n\n# create cv\nkf = StratifiedKFold(n_splits=50, shuffle=True, random_state=1)\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(X, y)):\n    # create train, validation sets\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n    \n    model = HistGradientBoostingClassifier(**hist_params)\n    model.fit(X_train, y_train)\n    # validation prediction\n    pred_valid = model.predict_proba(X_valid)[:,1]\n    \n    score = get_auc(y_valid, pred_valid)\n    scores_tmp.append(score)\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*20)\n    \n    # test prediction based on oof_set\n    y_hat = model.predict_proba(X_test)[:,1]\n    meta_pred_tmp.append(y_hat)\n# print overall validation scores\nprint(f\"Overall Validation Score | Meta: {np.mean(scores_tmp)}\")\nprint('::'*20)\n#average meta predictions over each fold\nmeta_predictions = np.mean(np.column_stack(meta_pred_tmp), axis=1)\n\n# create submission file\nstacked_submission = sample_submission.copy()\nstacked_submission[TARGET] = meta_predictions\nstacked_submission.to_csv('.\/HistGBM.csv', index=False)\n\"\"\"\n<div style=\"color:White; display:fill; border-radius:5px;background-color:#336b87;font-size:170%;font-family:sans-serif;letter-spacing:0.5px;text-align: center\">\nHistGBM Prediction KDE Plot\n<\/div>\n\"\"\"\nif PLOT == True:\n    plot = pd.concat([X_test,stacked_submission[TARGET]],axis=1)\n\n    pred = [plot.f1,  plot.f2,  plot.f3,  plot.f4,  plot.f5,  plot.f6,  plot.f7,  plot.f8,  plot.f9,  plot.f10,  plot.f11,  plot.f12,  plot.f13,  plot.f14,  plot.f15,  plot.f16,  plot.f17,  plot.f18,  plot.f19,  plot.f20, plot.f21, plot.target]\n    group_labels = plot.columns.to_list()\n    fig = ff.create_distplot(pred, group_labels, bin_size=0.3, show_hist=False, show_rug=False)\n    fig.show()","meta":"{'source': 'AI4Code', 'id': '82d7c67f9f217e'}"}
{"id":"79935","text":"# 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 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\ndf = pd.read_csv('..\/input\/data-exploration\/avgratings.csv')\ndf.count()\n\"\"\"\nFor this part, I'll be using Surprise SVD\n\"\"\"\nfrom surprise import Reader, Dataset, SVD\n\"\"\"\nStart reading in ratings data\n\"\"\"\nreader = Reader()\ndata = Dataset.load_from_df(df[['user_id', 'venue_id', 'rating']], reader)\n\n\"\"\"\nCreate SVD object and start training!\n\"\"\"\nsvd = SVD()\ntrainset = data.build_full_trainset()\nsvd.fit(trainset)\n\"\"\"\nSave model to file\n\"\"\"\nfrom surprise import dump\nfile_name = 'movie_svd_model'\ndump.dump(file_name, algo=svd)","meta":"{'source': 'AI4Code', 'id': '92c5dd13e0c72a'}"}
{"id":"97056","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport cv2\nimport time\nimport random \nimport pickle \nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.callbacks import TensorBoard\n\n\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\ndata_dir =\"\/kaggle\/input\/cat-and-dog\/training_set\/training_set\"\ncategories = [\"dogs\" ,\"cats\"]\nfor category in categories:\n    path = os.path.join(data_dir,category)\n    for img in os.listdir(path):\n        img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)\n        plt.imshow(img_array, cmap=\"gray\")\n        break\n        \n    break\nprint(img_array.shape)\n\"\"\"\n**Normalization**\n\"\"\"\nimg_size = 50\nnew_array = cv2.resize(img_array, (img_size,img_size))\nplt.imshow(new_array, cmap=\"gray\")\ntraining_data =[]\n\ndef create_training_data():\n    for category in categories:\n        path = os.path.join(data_dir,category)\n        class_num = categories.index(category)\n        for img in os.listdir(path):\n            try:\n                img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)\n                new_array = cv2.resize(img_array, (img_size,img_size))\n                training_data.append([new_array, class_num])\n            except Exception as e:\n                pass\ncreate_training_data()\n       \n\nprint(len(training_data))\ntest_dir = \"\/kaggle\/input\/cat-and-dog\/test_set\/test_set\"\n\ndef prepare(test_dir):\n    for category in categories:\n        path = os.path.join(test_dir,category)\n        class_num = categories.index(category)\n        for img in os.listdir(path):\n            try:\n                img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)\n                new_array = cv2.resize(img_array, (img_size,img_size))\n                training_data.append([new_array, class_num])\n            except Exception as e:\n                pass\n    return new_array.reshape(-1, img_size, img_size,1)\n    \nrandom.shuffle(training_data)\nx =[]\ny =[]\nfor features, label in training_data:\n    x.append(features)\n    y.append(label)\n    \nx =np.array(x).reshape(-1, img_size,img_size,1)\nNAME =\"Cats_vs_Dogs{}\".format(int(time.time()))\ntensorboard = TensorBoard(log_dir='log\/{}'.format(NAME))\npickle_out = open(\"x.pickle\",\"wb\")\npickle.dump(x,pickle_out)\npickle_out.close()\n\npickle_out = open(\"y.pickle\",\"wb\")\npickle.dump(y,pickle_out)\npickle_out.close()\nx = pickle.load(open(\"x.pickle\",\"rb\"))\ny = pickle.load(open(\"y.pickle\",\"rb\"))\n\nx=np.array(x\/255.0)\ny=np.array(y)\n\nmodel = Sequential()\n\nmodel.add( Conv2D(64, (3,3), input_shape = x.shape[1:]) )\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2,2) ) )\n\nmodel.add(Conv2D(64, (3,3)))\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(64))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss=\"binary_crossentropy\",\n         optimizer=\"adam\",\n         metrics=['accuracy'])\n\nmodel.fit(x, y, batch_size=32, epochs=15, validation_split=0.1, callbacks=[tensorboard])\nmodel.save('cat-and-dog_cnn')\npred = model.predict([prepare(test_dir)])\nprint(categories[int(pred[0][0])])","meta":"{'source': 'AI4Code', 'id': 'b23c9c111ae8e2'}"}
{"id":"44857","text":"\"\"\"\nhttps:\/\/github.com\/qubvel\/efficientnet\n\nEfficientNets rely on AutoML and compound scaling to achieve superior performance without compromising resource efficiency. The AutoML Mobile framework has helped develop a mobile-size baseline network, EfficientNet-B0, which is then improved by the compound scaling method to obtain EfficientNet-B1 to B7.\n\n\n![](https:\/\/raw.githubusercontent.com\/tensorflow\/tpu\/master\/models\/official\/efficientnet\/g3doc\/params.png)\n\n\n\"\"\"\n!pip install efficientnet\nimport math, re, os\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\n\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications import ResNet50, InceptionResNetV2, DenseNet201, ResNet50V2\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\n# import efficientnet.tfkeras as efn\nfrom tensorflow.keras.applications import ResNet50\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint\n\nimport efficientnet.tfkeras as efn\n\"\"\"\n# TPU\n\"\"\"\nAUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\"\"\"\nCompetition data access\n\nTPUs read data directly from Google Cloud Storage (GCS). This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. If you have multiple datasets attached to the notebook, you can pass the name of a specific dataset to the get_gcs_path function. The name of the dataset is the name of the directory it is mounted in. Use !ls \/kaggle\/input\/ to list attached datasets.\n\"\"\"\n# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\n\"\"\"\n# Configuration\n\"\"\"\nINPUT = \"\/kaggle\/input\/journey-springfield\"\nTRAIN_DIR = \"\/kaggle\/input\/journey-springfield\/train\/simpsons_dataset\"\nTEST_DIR = \"\/kaggle\/input\/journey-springfield\/testset\/testset\"\n\nEPOCHS = 25\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIM_Z = 784\n\"\"\"\n## Get test image titles\n\"\"\"\ndf = pd.read_csv(\"\/kaggle\/input\/journey-springfield\/sample_submission.csv\")\ntest_files = df[\"Id\"].values\n\"\"\"\n## Prepare data\n\ntest_classes - need to predict classes ({\"class_name\": 1,....\")\n\ntrain_classes - need to associate a image with classes ({1:\"class_name\",  .......})\n\ntrain_path - train image path to TPU \n\ntrain_labels - classes to TPU (one hot encoded ) \n\ntest_paths - test image path to TPU\n\"\"\"\ntest_classes = {k:v for v, k in zip(sorted(os.listdir(TRAIN_DIR)), range(42))}\ntrain_classes = {v:k for v, k in zip(sorted(os.listdir(TRAIN_DIR)), range(42))}\n\ndirs = sorted(os.listdir(TRAIN_DIR))\ntrain_paths = np.array(([GCS_DS_PATH + \"\/train\/simpsons_dataset\/\" + i + \"\/\" +  j for i in dirs for j in os.listdir(TRAIN_DIR + \"\/\" + i)]))\ntmp_labels = np.array([train_classes[j.split(\"\/\")[-2]] for j in train_paths])\n\ntrain_labels = np.zeros((train_paths.shape[0], 42))\nfor i in range(train_paths.shape[0]):\n    train_labels[i, tmp_labels[i]] = 1\nprint(train_paths.shape)\n\ntest_paths = np.array(([GCS_DS_PATH + \"\/testset\/testset\/\" +  i for i in test_files]))\n\n# train_paths, valid_paths, train_labels, valid_labels = train_test_split(\n#     train_paths, train_labels, test_size=0.1, random_state=2020)\n\"\"\"\nLabels must be integer not float\n\"\"\"\ntrain_labels = train_labels.astype(int)\n\"\"\"\n# Dataset\n\"\"\"\ndef decode_image(filename, label=None, image_size=(IM_Z, IM_Z)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_png(bits, channels=3)\n    image = tf.cast(image, tf.float32) \/ 255.0\n    image = tf.image.resize(image, image_size)\n    \n#     print(label)\n    if label is None:\n        return image\n    else:\n        return image, label\n\ndef data_augment(image, label=None):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n#     image = tf.image.adjust_brightness(image, delta=0.2)\n#     image = tf.image.adjust_contrast(image,2)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\ntrain_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((train_paths, train_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    .cache()\n    .map(data_augment, num_parallel_calls=AUTO)\n    .repeat()\n    .shuffle(512)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\n# valid_dataset = (\n#     tf.data.Dataset\n#     .from_tensor_slices((valid_paths, valid_labels))\n#     .map(decode_image, num_parallel_calls=AUTO)\n#     .batch(BATCH_SIZE)\n#     .cache()\n#     .prefetch(AUTO)\n# )\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(test_paths)\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n)\nLR_START = 0.00001\nLR_MAX = 0.0001 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 15\nLR_SUSTAIN_EPOCHS = 3\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) \/ LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\n# rng = [i for i in range(EPOCHS)]\n# y = [lrfn(x) for x in rng]\n# plt.plot(rng, y)\n# print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))\n\"\"\"\n# Models\n\"\"\"\n\"\"\"\nCreate  EfficientNetB7 model\n\"\"\"\nwith strategy.scope():\n    basem = efn.EfficientNetB7(weights=\"imagenet\", include_top=False, input_shape=(IM_Z, IM_Z, 3))\n    basem.trainable = False\n    model_efnB7 = tf.keras.Sequential([\n            basem,\n            L.GlobalAveragePooling2D(),\n            L.Flatten(name=\"flatten\"),\n            L.Dense(256, activation=\"relu\"),\n            L.Dropout(0.5),\n            L.Dense(42, activation='softmax')\n    ])\n    \n    opt = Adam(lr=1e-4, decay=1e-4 \/ EPOCHS)\n\n    model_efnB7.compile(\n        optimizer=opt,\n        loss = 'categorical_crossentropy',\n        metrics=['categorical_accuracy']\n    )\n    model_efnB7.summary()\n\"\"\"\nTrain EfficientNetB7 model\n\"\"\"\nSTEPS_PER_EPOCH = train_labels.shape[0] \/\/ BATCH_SIZE \n\nhistory = model_efnB7.fit(\n    train_dataset, \n    epochs=EPOCHS, \n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n    \n#     validation_data=valid_dataset\n)\n\"\"\"\nCreate EfficientNetB6 model\n\"\"\"\n# with strategy.scope():\n#     model_efnB6 = tf.keras.Sequential([\n#             efn.EfficientNetB6(weights=\"imagenet\", include_top=False, input_shape=(IM_Z, IM_Z, 3)),\n\n#             L.GlobalAveragePooling2D(),\n#             L.Flatten(name=\"flatten\"),\n#             L.Dense(256, activation=\"relu\"),\n#             L.Dropout(0.5),\n#             L.Dense(42, activation='softmax')\n#     ])\n    \n#     opt = Adam(lr=1e-4, decay=1e-4 \/ EPOCHS)\n\n#     model_efnB6.compile(\n#         optimizer=opt,\n#         loss = 'categorical_crossentropy',\n#         metrics=['categorical_accuracy']\n#     )\n# #     model.summary()\n\"\"\"\nTrain EfficientNetB6 model\n\"\"\"\n# STEPS_PER_EPOCH = train_labels.shape[0] \/\/ BATCH_SIZE \n\n# history = model_efnB6.fit(\n#     train_dataset, \n#     epochs=EPOCHS, \n#     steps_per_epoch=STEPS_PER_EPOCH,\n#     callbacks=[lr_callback],\n# #     validation_data=valid_dataset\n# )\n\"\"\"\n# Predict\n\"\"\"\n# prob = (model_efnB7.predict(test_dataset, verbose=1) + model_efnB6.predict(test_dataset, verbose=1))\/2\nprob = model_efnB7.predict(test_dataset, verbose=1)\ndf.Expected = np.array([test_classes[i] for i in np.argmax(prob, axis=1)])\ndf\ndf.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '52a001ced5d674'}"}
{"id":"112189","text":"\"\"\"\n### This is a Starter Notebook for Stock Price Prediction using Linear Regression\n\n\n\"\"\"\n\"\"\"\n### About the Dataset - \nThe dataset has around 60 features which includes features extracted from OHLC, other index prices such as QQQ(Nasdaq-100 ETF) & S&P 500, technical Indicators such as Bollinger bands, EMA(Exponential Moving Averages, Stocastic %K oscillator, RSI etc)\n\nFurthermore, I have created lagged features from previous day price data as we know previous day prices affect the future stock price. \n\nThen, the data has date features which specifies, if its a leap year, if its month start or end, Quarter start or end, etc. \n\n\nAll of these features have something to offer for forcasting. Some tells us about the trend, some gives us a signal if the stock is overbought or oversold, some portrays the strength of the price trend.\n\n\"\"\"\n\"\"\"\n\nIn this notebook, I will analyse the data and create a basic Linear regression model to forecast Stock Prices. \nIn future notebooks, I will use other algorithms like Random Forest, XGBoost and LSTM for this task. \n\n\"\"\"\n\"\"\"\nI will also create a Notebook explaining how I have extracted this data using only OHLC(Open High Low Close) data.\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nimport numpy as np\nimport seaborn as sns\nimport os\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import cross_val_score, train_test_split, GridSearchCV\nfrom sklearn.feature_selection import RFECV, SelectFromModel, SelectKBest\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import metrics\n%matplotlib inline\n\n\"\"\"\n### Load the data\n\nI will use the Apple Stock Data for this notebook\n\"\"\"\nStock = pd.read_csv('..\/input\/us-stock-market-data-60-extracted-features\/AAPL.csv',  index_col=0)\n\ndf_Stock = Stock\ndf_Stock = df_Stock.rename(columns={'Close(t)':'Close'})\ndf_Stock.head()\ndf_Stock.tail(5)\ndf_Stock.shape\ndf_Stock.columns\n\"\"\"\n### Plot Time Series chart for AAPL\n\"\"\"\ndf_Stock['Close'].plot(figsize=(10, 7))\nplt.title(\"Stock Price\", fontsize=17)\nplt.ylabel('Price', fontsize=14)\nplt.xlabel('Time', fontsize=14)\nplt.grid(which=\"major\", color='k', linestyle='-.', linewidth=0.5)\nplt.show()\n\"\"\"\nRemove some of the columns which are not required\n\"\"\"\ndf_Stock = df_Stock.drop(columns='Date_col')\n\"\"\"\n### Test Train Set\n\"\"\"\n\"\"\"\nClose_forecast is the column that we are trying to predict here which is the price for the next day. \n\"\"\"\ndef create_train_test_set(df_Stock):\n    \n    features = df_Stock.drop(columns=['Close_forcast'], axis=1)\n    target = df_Stock['Close_forcast']\n    \n\n    data_len = df_Stock.shape[0]\n    print('Historical Stock Data length is - ', str(data_len))\n\n    #create a chronological split for train and testing\n    train_split = int(data_len * 0.88)\n    print('Training Set length - ', str(train_split))\n\n    val_split = train_split + int(data_len * 0.1)\n    print('Validation Set length - ', str(int(data_len * 0.1)))\n\n    print('Test Set length - ', str(int(data_len * 0.02)))\n\n    # Splitting features and target into train, validation and test samples \n    X_train, X_val, X_test = features[:train_split], features[train_split:val_split], features[val_split:]\n    Y_train, Y_val, Y_test = target[:train_split], target[train_split:val_split], target[val_split:]\n\n    #print shape of samples\n    print(X_train.shape, X_val.shape, X_test.shape)\n    print(Y_train.shape, Y_val.shape, Y_test.shape)\n    \n    return X_train, X_val, X_test, Y_train, Y_val, Y_test\nX_train, X_val, X_test, Y_train, Y_val, Y_test = create_train_test_set(df_Stock)\n\"\"\"\n### Prediction using Linear Regression\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\n\nlr = LinearRegression()\nlr.fit(X_train, Y_train)\nprint('LR Coefficients: \\n', lr.coef_)\nprint('LR Intercept: \\n', lr.intercept_)\n\"\"\"\n### Evaluation\n\"\"\"\nprint(\"Performance (R^2): \", lr.score(X_train, Y_train))\ndef get_mape(y_true, y_pred): \n    \"\"\"\n    Compute mean absolute percentage error (MAPE)\n    \"\"\"\n    y_true, y_pred = np.array(y_true), np.array(y_pred)\n    return np.mean(np.abs((y_true - y_pred) \/ y_true)) * 100\n\"\"\"\n### Predict for the test dataset\n\"\"\"\nY_train_pred = lr.predict(X_train)\nY_val_pred = lr.predict(X_val)\nY_test_pred = lr.predict(X_test)\nprint(\"Training R-squared: \",round(metrics.r2_score(Y_train,Y_train_pred),2))\nprint(\"Training Explained Variation: \",round(metrics.explained_variance_score(Y_train,Y_train_pred),2))\nprint('Training MAPE:', round(get_mape(Y_train,Y_train_pred), 2)) \nprint('Training Mean Squared Error:', round(metrics.mean_squared_error(Y_train,Y_train_pred), 2)) \nprint(\"Training RMSE: \",round(np.sqrt(metrics.mean_squared_error(Y_train,Y_train_pred)),2))\nprint(\"Training MAE: \",round(metrics.mean_absolute_error(Y_train,Y_train_pred),2))\n\nprint(' ')\n\nprint(\"Validation R-squared: \",round(metrics.r2_score(Y_val,Y_val_pred),2))\nprint(\"Validation Explained Variation: \",round(metrics.explained_variance_score(Y_val,Y_val_pred),2))\nprint('Validation MAPE:', round(get_mape(Y_val,Y_val_pred), 2)) \nprint('Validation Mean Squared Error:', round(metrics.mean_squared_error(Y_train,Y_train_pred), 2)) \nprint(\"Validation RMSE: \",round(np.sqrt(metrics.mean_squared_error(Y_val,Y_val_pred)),2))\nprint(\"Validation MAE: \",round(metrics.mean_absolute_error(Y_val,Y_val_pred),2))\n\nprint(' ')\n\nprint(\"Test R-squared: \",round(metrics.r2_score(Y_test,Y_test_pred),2))\nprint(\"Test Explained Variation: \",round(metrics.explained_variance_score(Y_test,Y_test_pred),2))\nprint('Test MAPE:', round(get_mape(Y_test,Y_test_pred), 2)) \nprint('Test Mean Squared Error:', round(metrics.mean_squared_error(Y_test,Y_test_pred), 2)) \nprint(\"Test RMSE: \",round(np.sqrt(metrics.mean_squared_error(Y_test,Y_test_pred)),2))\nprint(\"Test MAE: \",round(metrics.mean_absolute_error(Y_test,Y_test_pred),2))\n\"\"\"\nWe have a decent Mean Absolute error but not great. I will create further tuned models in later notebooks. This is just to get you started with the dataset.\n\"\"\"\ndf_pred = pd.DataFrame(Y_val.values, columns=['Actual'], index=Y_val.index)\ndf_pred['Predicted'] = Y_val_pred\ndf_pred = df_pred.reset_index()\ndf_pred.loc[:, 'Date'] = pd.to_datetime(df_pred['Date'],format='%Y-%m-%d')\ndf_pred\n\"\"\"\n### Plot Predicted vs Actual Prices on Time Series plot\n\"\"\"\ndf_pred[['Actual', 'Predicted']].plot()\n\"\"\"\nOverall the Predictions looks good for the test data! \n\"\"\"\n\"\"\"\n### Future Notebooks\n\nI will create a Notebook explaining how I have extracted this data using only OHLC(Open High Low Close) data and a custom pipeline\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ce219b447714ca'}"}
{"id":"71789","text":"\"\"\"\n<div style=\"width:100%;text-align: center;\"> <img align=middle src=\"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcQfrEUPl6MA-wBBVSQr86WCOrG1uNtqn_NEKQ&usqp=CAU\" alt=\"Heat beating\" style=\"margin-top:3rem;\"> <\/div>\n\"\"\"\n\"\"\"\n--------------------------------------\nWith the growth of speach freedom and various forms of communacation certain groups of people\/agenceis want to promote thier own perspective of the world. Unfortunetley, in doing so sometimes they are trying to manipulate people opinions by generating fake news. It is done to make people believe in what can promote interest of news generating agencies.\n\nFrom the perspective of the users it is important to understand wether they can trust the news or they should be suspicous of it to avoid becoming a victim of some sort of scum or disinformation.\n\"\"\"\n\"\"\"\n--------------------------------------\n**Dataset**: In this project we deal with fake and real news dataset.   \n**Dataset\nResearch question**: The main question we wanted to answer is: wheather the given news is a true news or a fake one?  \n**Methods and Findings**:  To answer to this question we have created a base model using logistic regression method. The base model serves as a reference for the further improvement by the LSTM-model. However, the results of the base model were surprisingly good. Hence, we initiated a detailed exploratory analysis of the data which revealed that there are some problems in the way the data has been formed.\n\"\"\"\n\"\"\"\n# Reading the data\n\"\"\"\n\"\"\"\nOur dataset consists of two parts: fake and true news datasets. The respective number of news in each dataset is $23481, 21417$.\n\nIn the concatinated dataset there are $2$ categories of labels to classify the news as either true or false based on the news content.\n\"\"\"\nimport pandas as pd\n\ndata_true = pd.read_csv('..\/input\/fake-and-real-news-dataset\/True.csv')\ndata_fake = pd.read_csv('..\/input\/fake-and-real-news-dataset\/Fake.csv')\n\ndata_true['label'] = 1\ndata_fake['label'] = 0\ndata = pd.concat([data_true, data_fake], axis = 0)\ndata = data.sample(frac=1).reset_index(drop=True)\n\nprint(data_true.shape), print(data_fake.shape), print(data.shape)\ndata_true.head()\ndata_fake.head()\nprint(\"Total number of news: \", len(data))\nprint(\"Number of true news: \", len(data_true))\nprint(\"Number of fake news: \", len(data_fake))\n\"\"\"\nThere are almost an equal quantity of fake vs. true news.\n\"\"\"\nX_text = data['text']\ny_label = data['label']\n\"\"\"\n# Base model\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX, X_test, y, y_test = train_test_split(X_text, y_label, test_size=0.2, random_state=13) # split to train and test data\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=13) # split to train and validation data\ny_train.mean()\n\"\"\"\nThe mean of the labels in the train data shows that if we use a model that naively assigns to each observation $1$ i.e. classifies every news as 'fake' we would classify $48$ percent of the news correctly.\n\nLet's try to improve this accuracy.\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntfv = TfidfVectorizer()\ntfv.fit(X_train)\n\nX_train_tfv = tfv.transform(X_train)\nX_valid_tfv = tfv.transform(X_val)\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import log_loss\n\nlr = LogisticRegression()\nlr.fit(X_train_tfv, y_train)\nlr_preds = lr.predict(X_valid_tfv)\nlr_preds_proba = lr.predict_proba(X_valid_tfv)\n\nprint(\"The prediction accuracy is {0}\".format(np.mean(y_val==lr_preds)))\nprint(\"The loss is {0}\".format(round(log_loss(y_val, lr_preds_proba), 2)))\n\"\"\"\n# Data exploration\n\"\"\"\n\"\"\"\nThe high prediction accuracy for the base model surprised me and made me suspicous about the data. Let's investigate it to see wheather there are any peculiarities in the data.\n\nIn particular at this moment we should find out if there is some feature that helps to easily differentiate between true and fake data. Now we will try to see if:\n- There is a significant difference between the words usage in true vs fake news.\n- There is a significant difference between the lenghts of the text in true vs fake news.\n- There is a significant difference of topics of the true vs fake news.\n\"\"\"\nfrom collections import defaultdict\nfrom nltk.corpus import stopwords\n\nstopwords = stopwords.words('english')\n\n\n# create a corpuse of words in the data.\ndef create_corpuse(data, column_name):\n    words_by_frequency = defaultdict(int)\n\n    for title in data['{0}'.format(column_name)]:\n        for word in title.lower().split(' '):\n            if word not in stopwords:\n                words_by_frequency[word] += 1\n\n    return sorted(words_by_frequency.items(), key=lambda x: x[1], reverse=True)\n\ncounter_words_title_true = create_corpuse(data_true, 'title')\ncounter_words_title_fake = create_corpuse(data_fake, 'title')\n\ncounter_words_text_true = create_corpuse(data_true, 'text')\ncounter_words_text_fake = create_corpuse(data_fake, 'text')\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# plot the most frequent words in the data.\ndef most_frequent_words_barplot(true_words, fake_words, part = 'titles'):\n    fig, ax = plt.subplots(1, 2, figsize = (16, 8)) \n    sns.barplot(x=[x[1] for x in true_words[:30]], y =[x[0] for x in true_words[:30]], palette='Blues', ax = ax[0])\n    sns.barplot(x=[x[1] for x in fake_words[:30]], y =[x[0] for x in fake_words[:30]], palette='Reds', ax = ax[1])\n\n    ax[0].title.set_text(\"30 most common words in true news articles {0}\".format(part))\n    ax[1].title.set_text(\"30 most common words in fake news articles {0}\".format(part))\n# Most frequent words in titles of true vs fake news.\nmost_frequent_words_barplot(counter_words_title_true, counter_words_title_fake)\n# Most frequent words in texts of true vs fake news.\nmost_frequent_words_barplot(counter_words_text_true, counter_words_text_fake)\n\"\"\"\nThe two plots above don't show any apparent difference between the titles of the news. The same can be said for the text. Though I noticed that the true news text mentiones the 'reuters'-as a source for the news quite frequentley.\n\"\"\"\n\"\"\"\nLet's see if there is a difference between the lengths of the text in the true\/fake news.\n\"\"\"\n# get number of words in the data\ndef text_length(text):\n    word_count = 0\n    for word in text.split(\" \"):\n        word_count += 1\n    return word_count\n\ntrue_words_count = data_true['text'].apply(text_length)\nfake_words_count = data_fake['text'].apply(text_length)\n\nwords_count = pd.DataFrame({'True': true_words_count, 'Fake': true_words_count})\n\nplt.figure(figsize=(10, 6))\nwords_count.boxplot()\nplt.xlabel('News category')\nplt.ylabel('Distribution of words in the news text')\n\"\"\"\nSurprisingly fake news have more words than true ones. Hypothetically, this can be explained by the desire of fake news to convince the audience in their reliablity and hence, they use more words and tricks to do it. However, at the same the true news should give an extensive explanation of their articles to the audience. Hence, some mystery occures here.\n\"\"\"\ntrue_duplicated = data_true['text'].duplicated()\nfake_duplicated = data_fake['text'].duplicated()\n\nsum(true_duplicated), sum(fake_duplicated)\n\"\"\"\nTo partly resolve this phenomenon we looked at the presence of the duplicated texts and found out that there are over $6000$ dupliacte text in the fake news. \n\"\"\"\n\"\"\"\nNumber of unique words can be investigated too.\n\"\"\"\nnum_unique_words_true = len(counter_words_text_true)\nnum_unique_words_fake = len(counter_words_text_fake)\n\nplt.figure(figsize=(10, 6))\nsns.barplot(y=[num_unique_words_true, num_unique_words_fake], x=['True', 'Fake'], palette='Reds')\nplt.xlabel('News category')\nplt.ylabel('Number of unique words in news text')\n\"\"\"\nAgain fake news use more unique tokens than the true news. This can be connected with the fact that fake news use lots of external links to twitter users and web-sites (as we found out below).\n\"\"\"\n\"\"\"\nA good idea is to investigate to which sources news refer to. In particular we will look at the usage of twitter or some external web-site links. In addition to this we can look if some other news agencies names are used apart of 'reuters'.\n\"\"\"\nimport re\n\n# get the number of 'element' in the data\ndef find_text_elements(data, column_name, element):\n    count_element = 0\n    re_element = re.compile(element)\n    for text in data['{0}'.format(column_name)]:\n        count_element += len(re.findall(re_element, text.lower()))\n    return count_element\ntrue_twitter_user_names = find_text_elements(data_true, 'text', element = '@[0-9A-Za-z]*')\nfake_twitter_user_names = find_text_elements(data_fake, 'text', element = '@[0-9A-Za-z]*')\n\nplt.figure(figsize=(10, 6))\nsns.barplot(y=[true_twitter_user_names, fake_twitter_user_names], x=['True', 'Fake'], palette='Reds')\nplt.xlabel('News category')\nplt.ylabel('Number of twitter users in news text')\n\"\"\"\nIt seems to be the case that the fake news are using\/citing twitter far more extensively than the true news. So, there seems to be a bias in the data.\n\"\"\"\ntrue_sites_web_links = find_text_elements(data_true, 'text', element = 'http|www\\\\.|\\\\.com')\nfake_sites_web_links = find_text_elements(data_fake, 'text', element = 'http|www\\\\.|\\\\.com')\n\n\nplt.figure(figsize=(10, 6))\nsns.barplot(y=[true_sites_web_links, fake_sites_web_links], x=['True', 'Fake'], palette='Reds')\nplt.xlabel('News category')\nplt.ylabel('Number of web-link references in news text')\n\"\"\"\nAgain the fake news refer to different web-sites far more often than the true news.\n\"\"\"\n\"\"\"\nWhat popular news agencies the news use?\n\"\"\"\n# some popular news agencies names randomly chosen by me\narticles = {'the washington post': [0, 0], 'cnn': [0, 0], 'bbc': [0, 0], 'reuters': [0, 0], \n            'fox news': [0, 0], 'the new york times': [0, 0], 'nbc': [0, 0]}\nfor key, _ in articles.items():\n    true_value = find_text_elements(data_true, 'text', element=key)\n    fake_value = find_text_elements(data_fake, 'text', element=key)\n    articles[key] = true_value, fake_value\n    \narticles\narticles_count = pd.DataFrame(articles)\n\n\nplt.figure(figsize=(10, 6))\narticles_count.T.plot(kind='barh', colormap='autumn')\nplt.xlabel('Number of times the articles are mentioned');\nplt.legend(['True', 'Fake']);\n\"\"\"\nWe see that fake news reffer to wildly known news aggencies more frequently than the true news. I think, this can be partly explained by the desire of those fake news to be seem more reliable by mentioning the famous agencies names even if they are connected to the essence of the article only remotley. \nFrom another point I suppose, that the true news are represnted by those famous agencies and they rarely want to share the spotlight by mentioning a competitive agency as their source. Instead they use their reporters to get the reliable news.\n\nAt the same time the things are not so clear with 'reuters'. So, an assumption is that either 'reuters' is very reliable news agency and the others are not or the data should be biased. The latter will partly explain the high prediction results for the base model.\n\"\"\"\n\"\"\"\n# Model evaluation\n\"\"\"\n\"\"\"\nThough during the exploratory analysis we saw that the data seems to be biased in the way it is formed we decided to create an LSTM-model too to see if it captures the underlying features better than the simple logistic regression.\n\nNote that we are not doing any data cleaning in this case becuase already by the nature of the data peculiarities we would expect to get a model with quite high prediction accuracy.\n\"\"\"\nfrom tensorflow import keras\n\nnum_words = 10000\n\ntokenizer = keras.preprocessing.text.Tokenizer(num_words=num_words+1)\ntokenizer.fit_on_texts(X_train)\n\nX_train_seq = tokenizer.texts_to_sequences(X_train)\nX_val_seq = tokenizer.texts_to_sequences(X_val)\nX_train_padded = keras.preprocessing.sequence.pad_sequences(X_train_seq,\n                                                    maxlen=200,\n                                                    padding='post',\n                                                    truncating='post')\nX_val_padded = keras.preprocessing.sequence.pad_sequences(X_val_seq,\n                                                    maxlen=200,\n                                                    padding='post',\n                                                    truncating='post')\nX_train_padded.shape, len(y_train)\nX_val_padded.shape, len(y_val)\nmodel = keras.Sequential([\n    keras.layers.Embedding(num_words+1, 16, input_length=200),\n    keras.layers.Bidirectional(keras.layers.LSTM(64)),\n    keras.layers.Dense(16, activation='relu'),\n    keras.layers.Dense(1, activation='sigmoid')\n])\n\nmodel.compile(loss='binary_crossentropy', metrics=['accuracy'],\n             optimizer='adam')\n\nhistory = model.fit(X_train_padded, y_train, \n                    validation_data=(X_val_padded, y_val), epochs = 10)\nfig, ax = plt.subplots(1, 2, figsize=(10, 4))\nax[0].plot(history.history['accuracy'])\nax[0].plot(history.history['val_accuracy'])\n\nax[1].plot(history.history['loss'])\nax[1].plot(history.history['val_loss'])\n\nax[0].set_title('Model accuracy')\nax[0].set_ylabel('accuracy')\nax[0].set_xlabel('epoch')\nax[0].legend(['train', 'val'])\n\nax[1].set_title('Model loss')\nax[1].set_ylabel('loss')\nax[1].set_xlabel('epoch')\nax[1].legend(['train', 'val'])\n\"\"\"\nThe model starts to slightly overfit at the $5$th epoch.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '840d249e6e2c06'}"}
{"id":"97659","text":"\"\"\"\n# **Water Quality using Random Forest Classification - Knightbearr**\n\"\"\"\n\"\"\"\n# **Workflow**\n\n1. Data Collection\n2. Data Cleaning & Checking\n3. EDA\n4. Splitting Data\n5. Oversampling model\n6. Modeling\n7. Prediction Score\n\n\nnote : Sorry if my english is bad, and sorry if i had a mistake. thanks in advance!\n\"\"\"\n\"\"\"\n# **Import Libraries**\n\nimport the module that we want to use for this research.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import mutual_info_regression\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn import preprocessing\nfrom sklearn import metrics\nfrom imblearn.over_sampling import SMOTE\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n### **Setup Libraries**\n\"\"\"\npd.set_option('display.width', 150)\npd.set_option('display.max_columns', 12)\n\nplt.style.use(\"seaborn-whitegrid\")\n\nsns.set_theme(\n    color_codes=True, \n    style='darkgrid', \n    palette='deep', \n    font='sans-serif'\n)\n\"\"\"\n# **Load The Dataset**\n\nLoad the dataset that we want to research\n\"\"\"\nwater_data = pd.read_csv('..\/input\/water-potability\/water_potability.csv')\n\"\"\"\n# **Clean and Checking the Data**\n\nwe must check the data every time we want to make a model, because this is the important thing, if you suddenly meet a bad dataset, wether you want it or not, you must clean the data.\n\"\"\"\n# Checking the first 5 rows of data\nwater_data.head()\n# Checking the last 5 rows of data\nwater_data.tail()\n# Getting the statistical measure info\nwater_data.describe()\n# Getting the information about the dataset\nwater_data.info()\n# Chechking the null data\nwater_data.isnull().sum()\n# Checking the shape of data\nwater_data.shape\n\"\"\"\n**First**, we overcome the null values in the ph column first, and we know that the **ph values less than 6.5 and more than 8.5 are not suitable** for consumption, and the **range of pH that is within the WHO standard is 6.52 - 6.83** , and also we have obtained statistical info from the data above, that the **mean value at pH is 7** which is still within the scope of water that is safe for drinking by humans, so we will fill this empty ph value with the mean value of this ph to improve our model\n\"\"\"\n# Create a new variable named meanPh to hold the value of mean in ph\nmeanPh = water_data['ph'].mean()\n\n# Fill the blank\/null data ph with value of meanPh\nwater_data['ph'] = water_data['ph'].fillna(meanPh)\n\n# Check the null value and print\nprint(f'Null Value : {water_data.ph.isnull().sum()}\\n')\n\n# Check the data ph\nwater_data['ph']\n\"\"\"\n**Now**, we overcome the null value in sulfate, and we know that **Sulfate is one of the important ions in the availability of water** because of its important effect for humans when it is available in large quantities. **The maximum sulfate limit in water is about 250 mg\/L** for water for human consumption. if we see the statistics info above, **the mean of the Sulfate is 333mg\/L**, which mean, that's not good for consumption, and we know that, why the mean value is 333ml\/L? this happens because there are so many null values.\n\"\"\"\n# Created a new variable named waterSulfate tohold the value\nwaterSulfate = (water_data.Sulfate.mean() - water_data.Sulfate.min())\n\n# Fill the blank\/null dataSulfate with the value of waterSulfate\nwater_data['Sulfate'] = water_data['Sulfate'].fillna(waterSulfate)\n\n# Check the null value and print\nprint(f'Null Value : {water_data.Sulfate.isnull().sum()}')\n\n# Check the data Sulfate\nwater_data['Sulfate']\n\"\"\"\n**And last**, we deal with Trihalomethanes, what are Trihalomethanes ? **Trihalomethanes (THMs) are among the most dangerous chemical compounds** that find their way into the water supply. The concentration of THM in drinking water varies according to the level of organic matter in the water, the amount of chlorine required to treat the water, and the temperature of the treated water. **THM levels up to 80 ppm are considered safe** in drinking water. and if we see the statistical measure above, we can see the max value of thm is so high almost doubled value of thm, which that means is bad for consume.\n\n\"\"\"\n# Created a new variable named waterTrihalomethanes to hold the value\nwaterTrihalomethanes = water_data.Trihalomethanes.mean()\n\n# Fill the blank\/null data Trihalomethanes with the value of waterTrihalomethanes\nwater_data['Trihalomethanes'] = water_data['Trihalomethanes'].fillna(waterTrihalomethanes)\n\n# Check the null value and print\nprint(f'Null Value : {water_data.Trihalomethanes.isnull().sum()}')\n\n# Check the data Sulfate\nwater_data['Trihalomethanes']\n\"\"\"\n**Checking again**\n\"\"\"\n# Checking data and print\nprint(f'Isnull ? :\\n{water_data.isnull().sum()}\\n')\n\n# Checking data and print\nprint(f'Is all the data is True ? :\\n{water_data.any()}\\n')\n\n# Count the value and print\nprint(f'Potability :\\n{water_data.Potability.value_counts()}\\n')\n\n# Check the shape and print\nprint(f'Data Shape : {water_data.shape}')\n# Getting the statistical measure info\nwater_data.describe()\n\"\"\"\n# **EDA**\n\nanalyze and investigate data sets and summarize their main characteristics, often employing data visualization methods.\n\"\"\"\n# Make a correlation data to knowing Value Strength and Direction of Linear Relationship\ncorr = water_data.corr()\ncorr\n# Checking the structure of the data\nsample = water_data.sample(11, random_state=42).T\nsample\n# Constructing a heatmap to understand the correlation\nplt.figure(figsize=(12, 10))\n\nsns.heatmap(\n    corr, \n    cbar=True, \n    square=True, \n    fmt='.1f', \n    annot=True,\n    annot_kws={'size': 8},\n    cmap='YlGnBu'\n)\n\nplt.plot()\n\"\"\"\nYou see that? that's terrible, there's no one data that have a good correlation with the Potability.\n\"\"\"\n# Create Regression Plot\nsns.regplot(\n    x=water_data.Hardness, \n    y=water_data.Potability, \n    data=water_data\n)\n\nplt.show()\n# Create a histogram plot\nwater_data.hist(figsize=(12,12))\nplt.show()\n\"\"\"\n**Coefficient of Variation**\n\nThe coefficient of variation is a measure of variance that can be used to compare a data distribution that has different units.\n\n* **The higher the Coefficient of Variation** = the wider the data you have compared to the average data (more difficult to predict)\n* **The Lower Coefficient of Variation** = The narrower the data you have compared to the Average data (Easier to predict)\n\"\"\"\n# Coefficient of Potability\ncovPota = ((water_data['Potability'].std()\/water_data['Potability'].mean()) * 100)\nprint(f'Coefficient Of Variation Potability : {covPota}%')\n\"\"\"\nas you can see the output above, the coefficient of variation is so high, which mean, is so difficult to predict \n\"\"\"\n# Getting the Mutual Information about the data\nX = water_data.copy()\ny = X.pop('Potability')\n\n# All discrete features should now have integer dtypes\ndiscreateFeatures = X.dtypes == int\n# Make a function\ndef makeMiScores(X, y, discreateFeatures):\n    miScores = mutual_info_regression(X, y, discrete_features=discreateFeatures)\n    miScores = pd.Series(miScores, name='MI Scores', index=X.columns)\n    miScores = miScores.sort_values(ascending=False)\n    return miScores\n\nmiScores = makeMiScores(X, y, discreateFeatures)\nmiScores # show a features with their MI scores\n# And now bar plot to make comparisons easier\ndef plotMiScores(scores):\n    scores = scores.sort_values(ascending=True)\n    width = np.arange(len(scores))\n    ticks = list(scores.index)\n    plt.barh(width, scores)\n    plt.yticks(width, ticks)\n    plt.title(\"Mutual Information Scores\")\n\n# Figuring the plot and plotting\nplt.figure(dpi=100, figsize=(6, 3))\nplotMiScores(miScores)\n\"\"\"\nData visualization is a great follow-up to a utility ranking. as we can see the **Hardness, Conductivity, Organic, Turbidity, Solids, and ph have a mutual information** with Potability.\n\"\"\"\n\"\"\"\n# **Splitting the Data**\n\ndivide the data and split it using train test split module from sklearn.\n\"\"\"\n# Divide the data\nX = water_data.drop(['Potability'], axis=1)\ny = water_data['Potability']\n# Splitting Data\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=.3, random_state=42\n)\n# Checking the Target\ny_train.value_counts()\n# Checking the Target\ny_test.value_counts()\n\"\"\"\n# **Upsampling the Target**\n\nupsampling the target using SMOTE, upsampling the target, because we can see the portability and not portability data is have a  huge difference.\n\"\"\"\nsm = SMOTE(random_state=42)\nX_train_res, Y_train_res = sm.fit_resample(X_train, y_train)\n\"\"\"\n# **Train and Fit the model**\n\nTrain and fit the model using **RandomForestClassifier** Algorithm. and **Pipelines** are a simple way to keep your data preprocessing and modeling code organized. Specifically, a pipeline bundles preprocessing and modeling steps so you can use the whole bundle as if it were a single step.\n\"\"\"\npipe = Pipeline([\n    ('scaler', StandardScaler()),\n    ('transformer', QuantileTransformer(\n        random_state=42)\n    ),\n    ('model', RandomForestClassifier(\n        n_estimators=620, \n        min_samples_leaf=1, \n        random_state=42))\n])\n\npipe.fit(X_train_res, Y_train_res)\n# Train Predict\npred_train = pipe.predict(X_train_res)\nprint(metrics.classification_report(Y_train_res, pred_train))\n# Test Predict\npred_test = pipe.predict(X_test)\nprint(metrics.classification_report(y_test, pred_test))\n\"\"\"\n> # **That's it! don't forget to give me feedback and upvote if you like it! thanks in advance!**\n\"\"\"\n\"\"\"\n## **Here's my another notebook that i made:**\n\n**Data Analysist and Visualization:**\n\n- [World Covid Vaccination](https:\/\/www.kaggle.com\/knightbearr\/data-visualization-world-vaccination-knightbearr)\n- [Netflix Time Series Visualization](https:\/\/www.kaggle.com\/knightbearr\/netflix-visualization-time-series-knightbearr)\n- [Taiwan Weight Stock Analysist](https:\/\/www.kaggle.com\/knightbearr\/taiwan-weight-stock-index-analysis-knightbearr)\n\n**Regression and Classification:**\n\n- [S&P 500 Companies](https:\/\/www.kaggle.com\/knightbearr\/pricesales-eda-rfr-knightbearr)\n- [Credit Card Fraud Detection](https:\/\/www.kaggle.com\/knightbearr\/credit-card-fraud-detection-knightbearr)\n- [Car Price V3](https:\/\/www.kaggle.com\/knightbearr\/car-price-v3-xgbregressor-knightbearr)\n- [House Price Iran](https:\/\/www.kaggle.com\/knightbearr\/house-price-iran-knightbearr)\n\n**Deep Learning:**\n\n- [Rock Paper Scissors](https:\/\/www.kaggle.com\/knightbearr\/rock-paper-scissors-knightbearr)\n\n**Some Python Code:**\n\n- [Python Cheat Sheet](https:\/\/www.kaggle.com\/knightbearr\/python-cheat-sheet-knightbearr)\n- [22 Python Progam](https:\/\/www.kaggle.com\/knightbearr\/22-simple-python-program-knightbearr)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b34ab5e029e7b8'}"}
{"id":"23814","text":"# 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 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\n\"\"\"\n## CONTEXT\n#### Hi, I am currently pursuing PGP in Data Science. Recently we were assigned with a project on regression and hypothesis by our Statistics department. While looking for a dataset relevant to my project, I stumbled upon this one.\n\n## CONTENT\n#### This dataset captures the details of how CO2 emissions by a vehicle can vary with the different features. The dataset has been taken from Canada        Government official open data website. This is a compiled version. This contains data over a period of 7 years.\n#### There are total 7385 rows and 12 columns. There are few abbreviations that has been used to describe the features. I am listing them out here. The      same can be found in the Data Description sheet.\n\n## Model\n#### 4WD\/4X4 = Four-wheel drive\n#### AWD = All-wheel drive\n#### FFV = Flexible-fuel vehicle\n#### SWB = Short wheelbase\n#### LWB = Long wheelbase\n#### EWB = Extended wheelbase\n\n## Transmission\n#### A = Automatic\n#### AM = Automated manual\n#### AS = Automatic with select shift\n#### AV = Continuously variable\n#### M = Manual\n#### 3 - 10 = Number of gears\n\n## Fuel type\n#### X = Regular gasoline\n#### Z = Premium gasoline\n#### D = Diesel\n#### E = Ethanol (E85)\n#### N = Natural gas\n\n## Fuel Consumption\n#### City and highway fuel consumption ratings are shown in litres per 100 kilometres (L\/100 km) - the combined rating (55% city, 45% hwy) is shown in        L\/100 km and in miles per gallon (mpg)\n\n## CO2 Emissions\n#### The tailpipe emissions of carbon dioxide (in grams per kilometre) for combined city and highway driving\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n### Reading the CSV file\n\"\"\"\nfile = \"\/kaggle\/input\/co2-emission-by-vehicles\/CO2 Emissions_Canada.csv\"\ndf = pd.read_csv(file)\n\"\"\"\n### Checking the information from the dataset.\n\"\"\"\ndf.head()\n\"\"\"\n### Having a clear look at attributes.\n\"\"\"\ndf.info()\n\"\"\"\n####  There are 7385 entries of data and 12 columns. There are 7 numerical variables and 5 categorical variables in the dataset.\n\"\"\"\n\"\"\"\n### Understanding the distributions of data attributes.\n\"\"\"\ndf.describe(include='all')\n\"\"\"\n### Plotting the histogram of all numerical features.\n\"\"\"\ndf.hist(figsize=(20,10),bins=50)\ndf.isna().sum()\n\"\"\"\n#### There are no missing values in the dataset.\n\"\"\"\ndf['Transmission'].unique()\n\"\"\"\n### replacing similar labels with single label.\n\"\"\"\ndf['Transmission'] = np.where(df['Transmission'].isin(['A4','A5','A6','A7','A8','A9','A10']),\"Automatic\",df['Transmission'])\ndf['Transmission'] = np.where(df['Transmission'].isin([\"AM5\", \"AM6\", \"AM7\", \"AM8\", \"AM9\"]),\"Automated Manual\",df['Transmission'])\ndf['Transmission'] = np.where(df['Transmission'].isin([\"AS4\", \"AS5\", \"AS6\", \"AS7\", \"AS8\", \"AS9\", \"AS10\"]),\"Automatic with Select Shift\",df['Transmission'])\ndf['Transmission'] = np.where(df['Transmission'].isin([\"AV\", \"AV6\", \"AV7\", \"AV8\", \"AV10\"]),\"Continuously Variable\",df['Transmission'])\ndf['Transmission'] = np.where(df['Transmission'].isin([\"M5\", \"M6\", \"M7\"]),\"Manual\",df['Transmission'])\ndf['Transmission'].unique()\nsns.distplot(df['CO2 Emissions(g\/km)'])\nsns.violinplot(df['CO2 Emissions(g\/km)'])\nplt.figure(figsize=(20,5))\ndf.groupby(['Make'])['Make'].count().sort_values(ascending=False).plot(kind='bar')\n\"\"\"\n#### We can see high frequency in FORD,CHEVROLET and BMW brands which are dominant in our dataset.\n\"\"\"\ndf.groupby(['Model'])['Model'].count().sort_values(ascending=False).head(10)\n\"\"\"\n#### These are the 10 top most frequent vehicle models in our dataset.\n\"\"\"\nplt.figure(figsize=(15,5))\ndf.groupby(['Vehicle Class'])['Vehicle Class'].count().sort_values().plot(kind='bar')\nplt.tight_layout()\nplt.xticks(fontsize=8,rotation=45)\n\"\"\"\n#### From this plot we can see that lots of vehicles are SUV-SMALL,MID-SIZE and COMPACT type and VAN_CARGO is very less frequnent vehicle.\n\"\"\"\nplt.figure(figsize=(15,5))\ndf.groupby(['Cylinders'])['Cylinders'].count().sort_values(ascending=False).plot(kind='bar')\n\"\"\"\n#### It looks like 4 and 6 Cylinders vehicles are mostly used ones.\n\"\"\"\ndf.groupby(['Transmission'])['Transmission'].count().sort_values(ascending=False).plot(kind='bar')\n\"\"\"\n#### Automatic with Select Shift type is the most frequent in Transmission.\n\"\"\"\ndf.groupby(['Fuel Type'])['Fuel Type'].count().sort_values(ascending=False).plot(kind='bar')\n\"\"\"\n### Fuel type\n#### X = Regular gasoline, Z = Premium gasoline, D = Diesel, E = Ethanol (E85), N = Natural gas\n#### Gasoline is most used type of Fuel and Natural gas is the least used type of fuel\u26fd.\n\"\"\"\nplt.figure(figsize=(20,5))\ndf.groupby(['Make'])['CO2 Emissions(g\/km)'].mean().sort_values(ascending=False).plot(kind='bar')\nplt.ylabel('CO2 Emissions(g\/km)')\n\"\"\"\n#### We can see most of the costly brand cars are also emmitting lot of carbon emissions and brands like Honda and Smart are least carbon emitting vehicles.\n\"\"\"\nplt.figure(figsize=(10,3))\ndf.groupby(['Vehicle Class'])['CO2 Emissions(g\/km)'].mean().sort_values(ascending=False).plot(kind='bar')\nplt.xticks(fontsize=8)\nplt.ylabel(\"CO2 Emissions(g\/km)\")\n\"\"\"\n#### VAN-Passenger vehicles are the top most carbon emitting type of vehicle and Station Wagon-Small is the least Carbon emitting type of vehicle.\n\"\"\"\nplt.figure(figsize=(15,3))\ndf.groupby(['Engine Size(L)'])['CO2 Emissions(g\/km)'].median().sort_values(ascending=True).plot(kind='bar')\nplt.xlabel('Engine Size')\nplt.ylabel('CO2 Emissions(g\/km)')\n\"\"\"\n#### We can observe as Engine size increase CO2 emissions are also rising.\n\"\"\"\ndf.groupby(['Cylinders'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.ylabel('CO2 Emissions(g\/km)')\n\"\"\"\n#### We can observe as increase in number of cylinders Carbon emissions are also increasing.\n\"\"\"\ndf.groupby(['Transmission'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.ylabel('CO2 Emissions(g\/km)')\n\"\"\"\n#### From the plot Automatic Transmission Type vehicles emitt a large amount of carbon dioxide.\n\"\"\"\ndf.groupby(['Fuel Type'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.ylabel('CO2 Emissions(g\/km)')\n\"\"\"\n#### We see that Natural gas emitts less amount of carbon emissions and Ethanol emitts large amount of carbon emissions.\n\"\"\"\nplt.figure(figsize=(25,5))\ndf.groupby(['Fuel Consumption City (L\/100 km)'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.xticks(rotation=90, horizontalalignment='center', fontweight='light', fontsize='7')\nplt.ylabel(\"CO2 Emissions(g\/km)\")\n\"\"\"\n#### We can observe as fuel consumtion of vehivles on city roads increases carbon emissions also increase.\n\"\"\"\nplt.figure(figsize=(20,5))\ndf.groupby(['Fuel Consumption Hwy (L\/100 km)'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.xticks(rotation=90, horizontalalignment='center', fontweight='light', fontsize='7')\nplt.ylabel(\"CO2 Emissions(g\/km)\")\n\"\"\"\n#### Even on highway as fuel consumtion of vechiles increses carbon emissions also increases.\n\"\"\"\nplt.figure(figsize=(20,5))\ndf.groupby(['Fuel Consumption Comb (mpg)'])['CO2 Emissions(g\/km)'].mean().sort_values().plot(kind='bar')\nplt.xticks(rotation=90, horizontalalignment='center', fontweight='light', fontsize='7')\nplt.ylabel(\"CO2 Emissions(g\/km)\")\n\"\"\"\n#### As per gallon number of miles a vehicle travels increases carbon emissions decreases. It implies that less fuel consumption vehicles emitt less carbon emissions.\n\"\"\"\nsns.scatterplot(df['Fuel Consumption City (L\/100 km)'],df['CO2 Emissions(g\/km)'],hue=df['Fuel Type'])\n\"\"\"\n#### Fuel consumption of vehicles on city roads is positively corealated with Carbon emissions.\n\"\"\"\nsns.scatterplot(df['Fuel Consumption Hwy (L\/100 km)'],df['CO2 Emissions(g\/km)'],hue=df['Fuel Type'])\n\"\"\"\n#### Fuel consumption of vehicles on highway is positively corelated with cabon emissions.\n\"\"\"\nsns.scatterplot(df['Fuel Consumption Comb (L\/100 km)'],df['CO2 Emissions(g\/km)'],hue=df['Engine Size(L)'])\n\"\"\"\n#### We can see that Large size Engines consumes more fuel and emitt large amount of carbon emissions.\n\"\"\"\nsns.scatterplot(df['Fuel Consumption Comb (mpg)'],df['CO2 Emissions(g\/km)'],hue=df['Engine Size(L)'])\n\"\"\"\n#### As number of miles a vehicle can travel with one gallon increases carbon Emissions decreases. Fuel Consumption Comb (mpg) is negatively corelated with CO2 Emissions.\n\"\"\"\nplt.figure(figsize=(8,6))\nsns.boxplot(df['Fuel Type'],df['CO2 Emissions(g\/km)'])\nsns.pointplot(df['Cylinders'],df['CO2 Emissions(g\/km)'])\ncorr = df.corr()\nplt.figure(figsize=(10,8))\nsns.heatmap(corr,annot=True)\n\"\"\"\n#### From the corelation plot we can see all the features are positively corelated with carbon emissions except Fuel Consumption Comb (mpg) which is negatively corelated with carbon emissions.\n#### We can see that Fuel Consumption Comb (L\/100 km) is highly corelated with Fuel Consumption City (L\/100 km) and Fuel Consumption Hwy (L\/100 km) with corelation of 0.99 and 0.98 respectively. It shows that Fuel Consumption Comb (L\/100 km) is redundant feature and we can drop this column from the dataset.\n\"\"\"\n\"\"\"\n### One hot Encoding of Features Fuel Type and Transmission.\n\"\"\"\nFt = pd.get_dummies(df['Fuel Type'],drop_first=True,prefix='Fuel')\ndf = df.drop(['Fuel Type'],axis=1)\ndf = pd.concat([df,Ft],axis=1)\nTr = pd.get_dummies(df['Transmission'],drop_first=True)\ndf = df.drop(['Transmission'],axis=1)\ndf = pd.concat([df,Tr],axis=1)\ndf.head()\n\"\"\"\n#### Dropping the redundant feature Fuel Consumption Comb (L\/100 km)\n\"\"\"\nX = df.drop(['CO2 Emissions(g\/km)','Fuel Consumption Comb (L\/100 km)'],axis=1)\ny = df['CO2 Emissions(g\/km)']\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)\nx_train.head()\n\"\"\"\n### Encoding the remaining categorical Features with category_encoders.\n\"\"\"\ncat_cols = ['Make','Model','Vehicle Class']\nimport category_encoders as ce\ntarget_enc = ce.CatBoostEncoder(cols = cat_cols)\ntarget_enc.fit(x_train[cat_cols],y_train)\ntrain_enc = target_enc.transform(x_train[cat_cols])\ntest_enc = target_enc.transform(x_test[cat_cols])\ntrain_enc.head()\nx_train = x_train.drop(['Make','Model','Vehicle Class'],axis=1)\nx_test = x_test.drop(['Make','Model','Vehicle Class'],axis=1)\nx_train = pd.concat([x_train,train_enc],axis=1)\nx_test = pd.concat([x_test,test_enc],axis=1)\nx_train.head()\nx_test.head()\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nbest_features = SelectKBest(score_func=chi2)\nfit = best_features.fit(x_train,y_train)\nbest = pd.DataFrame(fit.scores_,columns=['scores'])\nbest['var'] = x_train.columns\nbest.sort_values(by='scores' ,ascending=False)\n\"\"\"\n#### These scores show us which features are important for our model. It seems that model type  and make are the most important features.\n\"\"\"\n\"\"\"\n### Scaling the features for further usage of data in models.\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nxs_train = scaler.fit_transform(x_train)\nxs_test = scaler.fit_transform(x_test)\n\"\"\"\n## Linear Regression Model\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression()\nmodel1 = lr.fit(x_train,y_train)\ny_pred1 = model1.predict(x_test) \nfrom sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error\nr2_score(y_test,y_pred1)\nmse = mean_squared_error(y_test,y_pred1)\nmse\nrmse = np.sqrt(mse)\nrmse\nmae = mean_absolute_error(y_test,y_pred1)\nmae\n\"\"\"\n#### Our linear regression model performs best on the test set with 99% accuracy and mean absolute error of 3.\n\"\"\"\n\"\"\"\n## KNeighbors Regressor model\n\"\"\"\nfrom sklearn.neighbors import KNeighborsRegressor\nknn = KNeighborsRegressor(n_neighbors=3)\nmodel2 = knn.fit(xs_train,y_train)\ny_pred2 = model2.predict(xs_test)\nr2_score(y_test,y_pred2)\nmean_squared_error(y_test,y_pred2)\n\"\"\"\n#### KNeighbors model also performs better with 98.5% accuracy.\n\"\"\"\n\"\"\"\n## Support Vector Regressor model\n\"\"\"\nfrom sklearn.svm import LinearSVR\nsvr = LinearSVR()\nmodel3 = svr.fit(xs_train,y_train)\ny_pred3 = model3.predict(xs_test)\nr2_score(y_test,y_pred3)\nmean_squared_error(y_test,y_pred3)\n\"\"\"\n#### Linear SVR model also performs better with 98.8% accuracy.\n\"\"\"\n\"\"\"\n## Decision Tree Regresor Model\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\ndtree = DecisionTreeRegressor()\nmodel4 = dtree.fit(x_train,y_train)\ny_pred4 = model4.predict(x_test)\nr2_score(y_test,y_pred4)\nmean_squared_error(y_test,y_pred4)\n\"\"\"\n#### Decision tree model performs amazingly well with 99% accuracy.\n\"\"\"\n\"\"\"\n## Random Forest Regressor model\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nrf = RandomForestRegressor(n_estimators=100)\nmodel5 = rf.fit(x_train,y_train)\ny_pred5 = model5.predict(x_test)\nr2_score(y_test,y_pred5)\nmean_squared_error(y_test,y_pred5)\n\"\"\"\n#### Random Forest Regressor model performs exceptionally well than any ohter model so far with 99.3% accuracy and with only 22.3 mean squarred error which is less than all models.\n\"\"\"\n\"\"\"\n## Gradient Booosting Regressor Model\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingRegressor\ngb = GradientBoostingRegressor()\nmodel6 = gb.fit(x_train,y_train)\ny_pred6 = model6.predict(x_test)\nr2_score(y_test,y_pred6)\nfrom sklearn.ensemble import AdaBoostRegressor\nada = AdaBoostRegressor()\nmodel7 = ada.fit(x_train,y_train)\ny_pred7 = model7.predict(x_test)\nr2_score(y_test,y_pred7)\nmean_squared_error(y_test,y_pred7)\n\"\"\"\n#### Boosting models also done a good job predicting the target variable on test set.\n\"\"\"\n\"\"\"\n### We see that all our models are performing well in predicting the carbon emissions from vehicles. From the Observations we can see that 95% of the vehicles generate carbon emissions between 133.5(g\/km) to 367.5(g\/km). Most influencing factors that increase carbon emissions are fuel consumption of vehicle. Vehicles with good mileage generate less amount of carbon dioxide. Even the Top brands does not do any good they even stay top in emitting carbon emissions. With large Engine sizes and more number of Cylinders of heavy vechiles more carbon emissions are observed.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2bc99b33263908'}"}
{"id":"9659","text":"\"\"\"\n## Introduction\n\nAs this is my first competition that I'm \"seriously\" competing in (actually more trying to really learn all the ins and outs of different Neural Network architectures and how to apply them to NLP), and I've learned a lot from several kernels posted on this competition, I thought that I should share some learned experience as well.\n\nThe code below is intended to do a hyperparameter search over some defined model using hyperopt. It splits the training set up into a set to train the model on and a holdout set to test the model on. I'm optimising on the F1 score of the test set, so as to gauge how it would perform on the leaderboard in this competition. From the couple of runs that I submitted the configuration found as optimal by the model, the (optimized) F1 score returned by the model and the leaderboard matched very closely, so I feel like this could be a good way of testing the performance of your model. However, I didn't make an exhaustive study of this so I might have just gotten lucky on my couple of tries, so no guarantee that this will also work for you :).\n\n**Important Note** : This notebook is not intended to run on a kaggle kernel, since the time it will take to run the entire grid search (depending on the number of `max_evals` you pass to `hyperopt.fmin` of course) will take more time than the kernels on Kaggle will allow. What I did is open a google cloud account (you get 300 USD free, so that's pretty sweet), and I used the following instance from the marketplace to run this notebook on: http:\/\/jetware.io\/appliances\/aise\/tensorflow110_keras22_python36_cuda92_notebook-180916. You can also create an instance yourself of course, but this marketplace solution makes it very easy to use GPUs on the Google Cloud Platform (trust me, I tried to create my own instance and was happy to find this instance after a couple of hours of frustration, but maybe that's just me).\n\n### Credits \n\nA lot of the code below is borrowed from other kernels, for which I have to thank the amazing authors, these are:\n>  https:\/\/www.kaggle.com\/gmhost\/gru-capsule (including the comments from @theoviel)\n\n>  https:\/\/www.kaggle.com\/c\/quora-insincere-questions-classification\/discussion\/74214\n\n>  https:\/\/www.kaggle.com\/shujian\/single-rnn-with-4-folds-clr\n\n>  https:\/\/www.kaggle.com\/theoviel\/improve-your-score-with-text-preprocessing-v2\n\n>  https:\/\/www.kaggle.com\/suicaokhoailang\/beating-the-baseline-with-one-weird-trick-0-691\n\n>  https:\/\/www.kaggle.com\/inspector\/keras-hyperopt-example-sketch\n\n>  https:\/\/www.kaggle.com\/spirosrap\/bilstm-attention-kfold-clr-extra-features-capsule\n\nApologies if I missed your contribution (there's a lot of amazing kernels out there), please notify me in the comments and I will update the credits :).\n\n\nAll of the below is probably pretty basic for many people here, but I thought I'd just share it for other to learn from. And perhaps I made a couple of mistakes and I'll learn from someone seeing this kernel :). Anyhow, hope it helps\n\"\"\"\nimport sklearn\nimport tensorflow as tf\nimport numpy as np\nimport keras\nimport pandas as pd\n\nimport seaborn as sns\nsns.set_style('whitegrid')\n\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\nfrom sklearn import metrics\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D, LSTM, GRU\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate\nfrom keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D, BatchNormalization\nfrom keras.optimizers import *\nfrom keras.initializers import *\nfrom keras.activations import *\nfrom keras.callbacks import *\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints, optimizers, layers\n\nimport datetime\nimport timeit\n\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.recurrent import LSTM\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nimport re\nimport gc\n## some config values \nmax_features = 95000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 70 # max number of words in a question to use\nembed_size = 300\nrun_name = 'LSTM_GTU_Attention_class_balance'\ntrain_df = pd.read_csv(\"..\/input\/train.csv\")\n\ndef clean_text(train_df):\n    print(\"Cleaning text data...\")\n\n    mispell_dict = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\",\"he'll\": \"he will\", \"he's\": \"he is\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \"how'll\": \"how will\", \"how's\": \"how is\",  \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \"I'll've\": \"I will have\",\"I'm\": \"I am\", \"I've\": \"I have\", \"i'd\": \"i would\", \"i'd've\": \"i would have\", \"i'll\": \"i will\",  \"i'll've\": \"i will have\",\"i'm\": \"i am\", \"i've\": \"i have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\",\"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\",\"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \"so've\": \"so have\",\"so's\": \"so as\", \"this's\": \"this is\",\"that'd\": \"that would\", \"that'd've\": \"that would have\", \"that's\": \"that is\", \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \"weren't\": \"were not\", \"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\",  \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \"where've\": \"where have\", \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who's\": \"who is\", \"who've\": \"who have\", \"why's\": \"why is\", \"why've\": \"why have\", \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\",\"y'all'd've\": \"you all would have\",\"y'all're\": \"you all are\",\"y'all've\": \"you all have\",\"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \"you're\": \"you are\", \"you've\": \"you have\", \"colour\": \"color\", \"centre\": \"center\", \"favourite\": \"favorite\", \"travelling\": \"traveling\", \"counselling\": \"counseling\", \"theatre\": \"theater\", \"cancelled\": \"canceled\", \"labour\": \"labor\", \"organisation\": \"organization\", \"wwii\": \"world war 2\", \"citicise\": \"criticize\", \"youtu \": \"youtube \", \"Qoura\": \"Quora\", \"sallary\": \"salary\", \"Whta\": \"What\", \"narcisist\": \"narcissist\", \"howdo\": \"how do\", \"whatare\": \"what are\", \"howcan\": \"how can\", \"howmuch\": \"how much\", \"howmany\": \"how many\", \"whydo\": \"why do\", \"doI\": \"do I\", \"theBest\": \"the best\", \"howdoes\": \"how does\", \"mastrubation\": \"masturbation\", \"mastrubate\": \"masturbate\", \"mastrubating\": 'masturbating', \"pennis\": \"penis\", \"Etherium\": \"Ethereum\", \"narcissit\": \"narcissist\", \"bigdata\": \"big data\", \"2k17\" : \"2017\", \"2k18\": \"2018\", \"qouta\": \"quota\", \"exboyfriend\" : \"ex boyfriend\", \"airhostess\" : \"air hostess\", \"whst\": \"what\", \"watsapp\": \"whatsapp\", \"demonitisation\": \"demonetization\", \"demonitization\": \"demonetization\", \"demonetisation\": \"demonetization\"}\n\n    def _get_mispell(mispell_dict):\n        mispell_re = re.compile(\"(%s)\" % \"|\".join(mispell_dict.keys()))\n        return mispell_dict, mispell_re\n\n    mispellings, mispellings_re = _get_mispell(mispell_dict)\n    def replace_typical_misspell(text):\n        def replace(match):\n            return mispellings[match.group(0)]\n        return mispellings_re.sub(replace, text)\n\n    # Lower the text\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.lower()\n\n    # Clean numbers\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"[0-9]{5,}\", r\"#####\")\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"[0-9]{4}\", r\"####\")\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"[0-9]{3}\", r\"###\")\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"[0-9]{2}\", r\"##\")\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"[0-9]*\\.[0-9]*\", r\"##\")\n\n    # Clean spellings\n    train_df[\"question_text\"] = train_df[\"question_text\"].apply(lambda x: replace_typical_misspell(x))\n    \n    # Clean the text\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"([^\\w\\s\\'\\\"])\", r\" \\1 \")\n    train_df[\"question_text\"] = train_df[\"question_text\"].str.replace(r\"\\s{2,}\", r\" \")\n    \n    return train_df\n\ntrain_df = clean_text(train_df)\ndef data(train_df):\n    \n    #train_df = pd.read_csv(\"input\/train_clean.csv\")\n\n    X = train_df[\"question_text\"].values\n    y = train_df[\"target\"].values\n     \n    ## Tokenize the sentences\n    tokenizer = Tokenizer(num_words=max_features)\n    tokenizer.fit_on_texts(list(X))\n    X = tokenizer.texts_to_sequences(X)\n\n    ## Pad the sentences \n    X = pad_sequences(X, maxlen=maxlen)\n    \n    # Make a small train test split to somehow evaluate the model accuracy. \n    # As this data is noisy and this won't be the same as the test set in the \n    # competition, I'm not really sure if this is a great idea, but we'll run with it\n    \n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 42, \\\n                                                        shuffle = True, stratify = y)\n    \n    ###\n    # Embedding loading\n    ###\n    \n    #####\n    ### GLOVE\n    #####\n    \n    word_index = tokenizer.word_index\n    \n    print(\"Loading GloVe embedding...\")\n    \n    EMBEDDING_FILE = \"..\/input\/embeddings\/glove.840B.300d\/glove.840B.300d.txt\"\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype=\"float32\")\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE))\n\n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = -0.005838499,0.48782197\n    embed_size = all_embs.shape[1]\n\n    # word_index = tokenizer.word_index\n    nb_words = min(max_features, len(word_index))\n    embedding_matrix_glove = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for word, i in word_index.items():\n        if i >= max_features: continue\n        embedding_vector = embeddings_index.get(word)\n        if embedding_vector is not None: embedding_matrix_glove[i] = embedding_vector\n    \n    del embeddings_index, all_embs, emb_mean, emb_std, nb_words, embedding_vector\n    \n    print(\"GloVe embedding loaded...\")\n    \n    ######\n    ### PARAGRAM Embedding\n    ######\n    \n    print(\"Loading Paragram embedding...\")\n    \n    EMBEDDING_FILE = \"..\/input\/embeddings\/paragram_300_sl999\/paragram_300_sl999.txt\"\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype=\"float32\")\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors=\"ignore\") if len(o)>100)\n\n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = -0.0053247833,0.49346462\n    embed_size = all_embs.shape[1]\n    #print(emb_mean,emb_std,\"para\")\n\n    # word_index = tokenizer.word_index\n    nb_words = min(max_features, len(word_index))\n    embedding_matrix_para = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for word, i in word_index.items():\n        if i >= max_features: continue\n        embedding_vector = embeddings_index.get(word)\n        if embedding_vector is not None: embedding_matrix_para[i] = embedding_vector\n    \n    del embeddings_index, all_embs, emb_mean, emb_std, nb_words, embedding_vector \n    print(\"Paragram embedding loaded...\")\n    \n    print(\"Concatenating embedding matrices...\")\n    \n    embedding_matrix = np.mean([embedding_matrix_para, embedding_matrix_glove], axis = 0)\n    \n    del embedding_matrix_para, embedding_matrix_glove\n    \n    print(\"Data loading done...\")\n    \n    return X_train, X_test, y_train, y_test, embedding_matrix #, max_features, maxlen, embed_size    \n\n\n\"\"\"\n## Extra model definitions\n\"\"\"\n####\n# Extra classes for the training\n####\n\nclass Attention(Layer):\n    def __init__(self, step_dim,\n                 W_regularizer=None, b_regularizer=None,\n                 W_constraint=None, b_constraint=None,\n                 bias=True, **kwargs):\n        self.supports_masking = True\n        self.init = initializers.get(\"glorot_uniform\")\n\n        self.W_regularizer = regularizers.get(W_regularizer)\n        self.b_regularizer = regularizers.get(b_regularizer)\n\n        self.W_constraint = constraints.get(W_constraint)\n        self.b_constraint = constraints.get(b_constraint)\n\n        self.bias = bias\n        self.step_dim = step_dim\n        self.features_dim = 0\n        super(Attention, self).__init__(**kwargs)\n\n    def build(self, input_shape):\n        assert len(input_shape) == 3\n\n        self.W = self.add_weight((input_shape[-1],),\n                                 initializer=self.init,\n                                 name='{}_W'.format(self.name),\n                                 regularizer=self.W_regularizer,\n                                 constraint=self.W_constraint)\n        self.features_dim = input_shape[-1]\n\n        if self.bias:\n            self.b = self.add_weight((input_shape[1],),\n                                     initializer='zero',\n                                     name='{}_b'.format(self.name),\n                                     regularizer=self.b_regularizer,\n                                     constraint=self.b_constraint)\n        else:\n            self.b = None\n\n        self.built = True\n\n    def compute_mask(self, input, input_mask=None):\n        return None\n\n    def call(self, x, mask=None):\n        features_dim = self.features_dim\n        step_dim = self.step_dim\n\n        eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n                        K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n        if self.bias:\n            eij += self.b\n\n        eij = K.tanh(eij)\n\n        a = K.exp(eij)\n\n        if mask is not None:\n            a *= K.cast(mask, K.floatx())\n\n        a \/= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n        a = K.expand_dims(a)\n        weighted_input = x * a\n        return K.sum(weighted_input, axis=1)\n\n    def compute_output_shape(self, input_shape):\n        return input_shape[0],  self.features_dim\n\nclass CyclicLR(Callback):\n    \"\"\"This callback implements a cyclical learning rate policy (CLR).\n    The method cycles the learning rate between two boundaries with\n    some constant frequency, as detailed in this paper (https:\/\/arxiv.org\/abs\/1506.01186).\n    The amplitude of the cycle can be scaled on a per-iteration or \n    per-cycle basis.\n    This class has three built-in policies, as put forth in the paper.\n    \"triangular\":\n        A basic triangular cycle w\/ no amplitude scaling.\n    \"triangular2\":\n        A basic triangular cycle that scales initial amplitude by half each cycle.\n    \"exp_range\":\n        A cycle that scales initial amplitude by gamma**(cycle iterations) at each \n        cycle iteration.\n    For more detail, please see paper.\n\n    # Example\n        ```python\n            clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n                                step_size=2000., mode='triangular')\n            model.fit(X_train, Y_train, callbacks=[clr])\n        ```\n\n    Class also supports custom scaling functions:\n        ```python\n            clr_fn = lambda x: 0.5*(1+np.sin(x*np.pi\/2.))\n            clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n                                step_size=2000., scale_fn=clr_fn,\n                                scale_mode='cycle')\n            model.fit(X_train, Y_train, callbacks=[clr])\n        ```    \n    # Arguments\n        base_lr: initial learning rate which is the\n            lower boundary in the cycle.\n        max_lr: upper boundary in the cycle. Functionally,\n            it defines the cycle amplitude (max_lr - base_lr).\n            The lr at any cycle is the sum of base_lr\n            and some scaling of the amplitude; therefore \n            max_lr may not actually be reached depending on\n            scaling function.\n        step_size: number of training iterations per\n            half cycle. Authors suggest setting step_size\n            2-8 x training iterations in epoch.\n        mode: one of {triangular, triangular2, exp_range}.\n            Default 'triangular'.\n            Values correspond to policies detailed above.\n            If scale_fn is not None, this argument is ignored.\n        gamma: constant in 'exp_range' scaling function:\n            gamma**(cycle iterations)\n        scale_fn: Custom scaling policy defined by a single\n            argument lambda function, where \n            0 <= scale_fn(x) <= 1 for all x >= 0.\n            mode paramater is ignored \n        scale_mode: {'cycle', 'iterations'}.\n            Defines whether scale_fn is evaluated on \n            cycle number or cycle iterations (training\n            iterations since start of cycle). Default is 'cycle'.\n    \"\"\"\n\n    def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode=\"triangular\",\n                 gamma=1., scale_fn=None, scale_mode=\"cycle\"):\n        super(CyclicLR, self).__init__()\n\n        self.base_lr = base_lr\n        self.max_lr = max_lr\n        self.step_size = step_size\n        self.mode = mode\n        self.gamma = gamma\n        if scale_fn == None:\n            if self.mode == \"triangular\":\n                self.scale_fn = lambda x: 1.\n                self.scale_mode = \"cycle\"\n            elif self.mode == \"triangular2\":\n                self.scale_fn = lambda x: 1\/(2.**(x-1))\n                self.scale_mode = \"cycle\"\n            elif self.mode == \"exp_range\":\n                self.scale_fn = lambda x: gamma**(x)\n                self.scale_mode = \"iterations\"\n        else:\n            self.scale_fn = scale_fn\n            self.scale_mode = scale_mode\n        self.clr_iterations = 0.\n        self.trn_iterations = 0.\n        self.history = {}\n\n        self._reset()\n\n    def _reset(self, new_base_lr=None, new_max_lr=None,\n               new_step_size=None):\n        \"\"\"Resets cycle iterations.\n        Optional boundary\/step size adjustment.\n        \"\"\"\n        if new_base_lr != None:\n            self.base_lr = new_base_lr\n        if new_max_lr != None:\n            self.max_lr = new_max_lr\n        if new_step_size != None:\n            self.step_size = new_step_size\n        self.clr_iterations = 0.\n\n    def clr(self):\n        cycle = np.floor(1+self.clr_iterations\/(2*self.step_size))\n        x = np.abs(self.clr_iterations\/self.step_size - 2*cycle + 1)\n        if self.scale_mode == \"cycle\":\n            return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(cycle)\n        else:\n            return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(self.clr_iterations)\n\n    def on_train_begin(self, logs={}):\n        logs = logs or {}\n\n        if self.clr_iterations == 0:\n            K.set_value(self.model.optimizer.lr, self.base_lr)\n        else:\n            K.set_value(self.model.optimizer.lr, self.clr())        \n\n    def on_batch_end(self, epoch, logs=None):\n\n        logs = logs or {}\n        self.trn_iterations += 1\n        self.clr_iterations += 1\n\n        self.history.setdefault(\"lr\", []).append(K.get_value(self.model.optimizer.lr))\n        self.history.setdefault(\"iterations\", []).append(self.trn_iterations)\n\n        for k, v in logs.items():\n            self.history.setdefault(k, []).append(v)\n\n        K.set_value(self.model.optimizer.lr, self.clr())\n# Data loading...\n\nX_train, X_test, y_train, y_test, embedding_matrix = data(train_df)\n\"\"\"\n## Hyperopt Model\n\"\"\"\n# Model based on hyperopt since I'm going crazy\nimport hyperopt\nfrom hyperopt import hp, fmin, tpe, hp, STATUS_OK, Trials\n# for better class weights see : https:\/\/datascience.stackexchange.com\/questions\/13490\/how-to-set-class-weights-for-imbalanced-classes-in-keras\nfrom sklearn.utils import class_weight\nimport json\n\n# hp.choice('dense_layers', np.arange(20, 80, 5, dtype=int))\n\nspace = {'k_folds' : 3,\n         'dropout_1d_rate' : hp.uniform('dropout_1d_rate', 0, 1),\n         'use_LSTM_layer' : hp.choice('use_LSTM_layer', [{'use_layer' : 'no'}, \\\n                                                         {'use_layer' : 'yes', \\\n                                                          'LSTM_layers' : hp.quniform('LSTM_layers', 20, 80, 13),\n                                                          'dropout_rate_lstm' : hp.uniform('dropout_rate_lstm', 0, 1)}]),\n         'use_GRU_layer' : hp.choice('use_GRU_layer', [{'use_layer' : 'no'}, \\\n                                                       {'use_layer' : 'yes', \\\n                                                        'GRU_layers' : hp.quniform('GRU_layers', 20, 80, 13),\n                                                        'dropout_rate_gru' : hp.uniform('dropout_rate_gru', 0, 1)}]),\n         'dense_layers' : hp.quniform('dense_layers', 20, 80, 13),\n         'dropout_rate_dense' : hp.uniform('dropout_rate_dense', 0, 1),\n         'batch_size' : hp.choice('batch_size', [512, 1024, 2048]),\n         'epochs' : hp.choice('epochs', [2,3,4])\n         #,'random_seed' : # leave random seed tuning for last...\n        }\n\n# https:\/\/datascience.stackexchange.com\/questions\/13490\/how-to-set-class-weights-for-imbalanced-classes-in-keras\nclass_weights = class_weight.compute_class_weight('balanced',\n                                                  np.unique(y_train),\n                                                  y_train)\n\ndef f1_smart(y_true, y_pred):\n    args = np.argsort(y_pred)\n    tp = y_true.sum()\n    fs = (tp - np.cumsum(y_true[args[:-1]])) \/ np.arange(y_true.shape[0] + tp - 1, tp, -1)\n    res_idx = np.argmax(fs)\n    return 2 * fs[res_idx], (y_pred[args[res_idx]] + y_pred[args[res_idx + 1]]) \/ 2\n\n###\n# REASONING : So as I've seen in the CV vs LB score on this competition, it seems that having more \n# epochs and more folds definitely increases the CV accuracy and loss, but gives a very variable\n# score on the LB. So the idea is to see which configuration quite quickly gives a good loss\/accuracy, \n# and then try that out on the LB\n\n# What is a good metric to measure the loss by? Accuracy of the here defined test function is probably\n# not too bad, because it's truly a holdout (the test set that has been split out), \n# but maybe it should be a bit bigger than 10% (made it 15%)\n\n# Version 2 (which includes switching on and off of layers, and is posted to kaggle)\n# changes the above concern by not optimizing on the accuracy but on the F1 from the hold \n# out test set, which is far closer to what happens on Kaggle.\n\ndef objective(params):\n\n    max_features = 95000 \n    maxlen = 70 \n    embed_size = 300\n    \n    print('Currently searching over : {}'.format(params))\n    \n    ###\n    # kfolds\n    ###\n    \n    kfold = StratifiedKFold(n_splits=params['k_folds'], random_state=10, shuffle=True)\n    \n    ###\n    # define model, model based on a comment in the discussion section, which I couldn't\n    # find anymore, so thanks someone!\n    ###\n    \n    K.clear_session()       \n    inp = Input(shape=(maxlen,))\n    x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp)\n    x = SpatialDropout1D(rate = params['dropout_1d_rate'])(x)\n    if params['use_LSTM_layer']['use_layer'] == 'yes':\n        x = Bidirectional(CuDNNLSTM(units = int(round(params['use_LSTM_layer']['LSTM_layers'])), return_sequences=True, \n                                    kernel_initializer=glorot_normal(seed=12300), recurrent_initializer=orthogonal(gain=1.0, seed=10000)))(x)\n        #x = Dropout(rate = params['use_LSTM_layer']['dropout_rate_lstm'])(x)\n    if params['use_GRU_layer']['use_layer'] == 'yes':\n        x = Bidirectional(CuDNNGRU(units = int(round(params['use_GRU_layer']['GRU_layers'])), return_sequences=True, \n                                   kernel_initializer=glorot_normal(seed=12300), recurrent_initializer=orthogonal(gain=1.0, seed=10000)))(x)\n        #x = Dropout(rate = params['use_GRU_layer']['dropout_rate_gru'])(x)\n\n    x = Attention(maxlen)(x)\n    x = Dense(units = int(round(params['dense_layers'])), activation=\"linear\", kernel_initializer=glorot_normal(seed=12300))(x)\n    x = Dropout(rate = params['dropout_rate_dense'])(x)\n    x = BatchNormalization()(x)\n    #x = Activation(\"relu\")(x)\n    x = Dense(1, activation=\"sigmoid\")(x)\n    model = Model(inputs=inp, outputs=x)\n    # Use all GPUs\n    model.compile(loss=\"binary_crossentropy\", optimizer=Adam(), \\\n                  metrics = [\"accuracy\"])\n\n    filepath=\"weights_best.h5\"\n    # Checkpoint not really necessary since it only improves the run time at this moment\n    #checkpoint = ModelCheckpoint(filepath, monitor=\"val_loss\", verbose=2, save_best_only=True, mode=\"min\")\n    reduce_lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.6, patience=1, min_lr=0.0001, verbose=2)\n    earlystopping = EarlyStopping(monitor=\"val_loss\", min_delta=0.001, patience=2, verbose=2, mode=\"auto\")\n    callbacks = [earlystopping, reduce_lr]\n    \n    ###\n    # Apply the folds over the model\n    ###\n\n    for i, (train_index, valid_index) in enumerate(kfold.split(X_train, y_train)):\n        Xk_train, Xk_val, Yk_train, Yk_val = X_train[train_index], X_train[valid_index], y_train[train_index], y_train[valid_index]\n\n        print(\"Currently in fold {}\/{}\".format(i+1, params['k_folds']))\n        model.fit(Xk_train, Yk_train, batch_size=params['batch_size'], epochs=params['epochs'], \\\n                           validation_data=(Xk_val, Yk_val), callbacks=callbacks, class_weight=class_weights)\n        #model.load_weights(filepath) \n\n    score, acc = model.evaluate(X_test, y_test, verbose=0)\n    \n    # Also add f1 and find optimal threshold,\n    # this way we can compute f1 and optimize for that...\n    \n    pred_val_y = model.predict([X_test], batch_size=params['batch_size'], verbose=0)\n    f1, threshold = f1_smart(np.squeeze(y_test), np.squeeze(pred_val_y))\n    \n    print('Accuracy : {:5f}, Optimal F1 : {:5f}, at threshold : {:5f}'.format(acc, f1, threshold))\n    \n    ### Save to file what we've just done...\n    # I know this is redundant since we're already saving trials, but I had a notebook\n    # crash om me sometimes and this saves the intermediate results, so definitely helps\n    \n    ## https:\/\/stackoverflow.com\/questions\/33054527\/python-3-5-typeerror-a-bytes-like-object-is-required-not-str-when-writing-t\n    with open(\"run_{}.txt\".format(run_name),\"a\") as f:\n        print(params, file=f)\n        print('\\n Accuracy : {}, F1 : {}, optimal threshold : {}'.format(acc, f1, threshold), file = f)  \n        f.close() \n    \n    return {\"loss\": -f1, \"status\": STATUS_OK, \"model\": model} # \"loss\" : -acc\n\ntrials = Trials()\n\nbest = fmin(objective, space, algo=tpe.suggest, trials=trials, max_evals=1) #200\n\nprint(hyperopt.space_eval(space, best))\nprint(trials.best_trial)\nimport hyperopt\nprint(hyperopt.space_eval(space, best))\nprint(trials.best_trial)\n# remove the keras model since this one does not play nicely with the pickle\n# cleaned_trials_trials = []\n# for trial in trials.trials:\n#     del trial['result']['model']\n#     cleaned_trials_trials.append(trial)\n# from https:\/\/github.com\/hyperopt\/hyperopt\/issues\/267\n# & https:\/\/github.com\/hyperopt\/hyperopt\/wiki\/FMin\n# for some nice postprocesing and plotting of the results see:\n# https:\/\/medium.com\/district-data-labs\/parameter-tuning-with-hyperopt-faa86acdfdce\n\n# Just saving the results here which should be interprable from the results\n# can't pickle the whole trials file because it contains Keras models and \n# those can't be pickled apparently :((((\n\n# import pickle\n\n# trials_trials = trials.trials\n# trials_losses = trials.losses()\n# trials_statuses = trials.statuses()\n\n# pickle.dump([cleaned_trials_trials, trials_losses, trials_statuses, space], open(\"hyperopt_result_{:%Y-%m-%d %H:%M:%S}.p\".format(datetime.datetime.now()), \"wb\"))\n# # trials = pickle.load(open(\"myfile.p\", \"rb\")) # for later reloading if necessary\n# file = open(\"results_{:%Y-%m-%d %H:%M:%S}.txt\".format(datetime.datetime.now()),\"w\") \n# print(hyperopt.space_eval(space, best), file = file) \n# print(trials.best_trial, file = file)\n\n# file.close() ","meta":"{'source': 'AI4Code', 'id': '11c9a58cc86448'}"}
{"id":"128843","text":"\"\"\"\nThis is a component of a larger project [Cat-A-Logger](https:\/\/github.com\/screamatthewind\/cat-a-logger) on github   \nSee this [Short Slide Presentation](https:\/\/github.com\/screamatthewind\/cat-a-logger\/blob\/main\/Slide%20Presentation%20-%20Short.pdf)\n\"\"\"\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\n# from subprocess import check_output\n# print(check_output([\"ls\", \"..\/input\"]).decode(\"utf8\"))\nINPUT_BACKGROUND_FILES = '..\/input\/stanford-background-dataset\/images'\nINPUT_FOREGROUND_FILES = '..\/input\/augmented-cats-and-dogs'\n\nOUTPUT_DATASET_ID = 'random-backgrounds-for-cats-and-dogs'\nOUTPUT_DATASET_NAME = 'Random Backgrounds for Cats and Dogs'\nOUTPUT_PATH = '.\/output'\n\n# kaggle_secrets not supported by Google Cloud Platform for Kaggle(Beta) at this time\n# from kaggle_secrets import UserSecretsClient\n# user_secrets = UserSecretsClient()\n#API_TOKEN = user_secrets.get_secret(\"Crop Cats and Cogs YOLOv3\")\n\nUSER_ID = 'KAGGLE-USERNAME' # use your own username\nAPI_TOKEN = 'KAGGLE-API-TOKEN' # use your own kaggle api key\n\n# same size is used in Augment Cats and Dogs\nMIN_SCALE = 0.2\nMAX_SCALE = 0.5\n\nrun_limit = 100\nimport os\nif not os.path.exists(OUTPUT_PATH):\n    os.makedirs(OUTPUT_PATH)\nimport cv2\nimport numpy as np\n\n# scale image by scale_factor, keep aspect ratio\ndef scale_image(image, scale_factor):\n    \n    image = np.array(image)\n    image = cv2.resize(image, (0,0), fx=scale_factor, fy=scale_factor)\n\n    image = Image.fromarray(image)\n    \n    return image\nimport random\nfrom PIL import Image, ImageDraw, ImageOps\nimport matplotlib.pyplot as plt\n\nbackground_path, background_dir, background_files = next(os.walk(INPUT_BACKGROUND_FILES))\nforeground_path, foreground_dir, foreground_files = next(os.walk(INPUT_FOREGROUND_FILES))\n\nfor i in range(run_limit):\n\n    random_background_image_num = random.randrange(len(background_files))\n    random_foreground_image_num = random.randrange(len(foreground_files))\n\n    background_image_filename = background_path + '\/' + background_files[random_background_image_num]\n    foreground_image_filename = foreground_path + '\/' + foreground_files[random_foreground_image_num]\n\n    background_image = Image.open(background_image_filename)\n    foreground_image = Image.open(foreground_image_filename)\n\n    if 'neg' in foreground_image_filename:\n        background_image = ImageOps.grayscale(background_image)\n        background_image = ImageOps.invert(background_image)\n                \n    elif 'bw' in foreground_image_filename:\n        background_image = ImageOps.grayscale(background_image)\n\n    # composite randomly scaled forground image at random position on random background image\n    scale_factor = random.uniform(MIN_SCALE, MAX_SCALE)\n    foreground_image = scale_image(foreground_image, scale_factor)\n\n    # paste foreground image onto background image at random position\n    foreground_image_width, foreground_image_height = foreground_image.size\n    background_image_width, background_image_height = background_image.size\n\n    x_max_pos = background_image_width - foreground_image_height\n    y_max_pos = background_image_height - foreground_image_height\n    \n    x_pos_factor = random.uniform(0, 1)\n    y_pos_factor = random.uniform(0, 1)\n    \n    x_new_pos = int(x_max_pos * x_pos_factor)\n    y_new_pos = int(y_max_pos * y_pos_factor)\n    \n    background_image = background_image.convert('RGBA') # make images have same number of color channels\n    background_image.paste(foreground_image, (x_new_pos, y_new_pos), foreground_image) # 3rd parm is mask\n\n    # draw bounding box \n    draw = ImageDraw.Draw(background_image)\n    draw.rectangle(((x_new_pos, y_new_pos), (x_new_pos + foreground_image_width, y_new_pos + foreground_image_height)), outline=(255, 0, 0), width = 3)\n\n    # save composite image\n    filename = os.path.basename(foreground_image_filename)\n    fname, ext = os.path.splitext(filename) \n\n    background_image = background_image.convert('RGB') \n    background_image.save(OUTPUT_PATH + '\/' + fname  + '-final.jpg', 'jpeg')\n    \n    # plt.imshow(background_image)   \n    # plt.show()\n    \n    # plt.imshow(foreground_image)   \n    # plt.show()\n! python -m pip install --index-url https:\/\/test.pypi.org\/simple\/ --no-deps kaggle_uploader-screamatthewind\n# Google Cloud Plaform for Kaggle(Beta) does not support \/usr\/lib modules at this time \n# Save Output Dataset\n\nimport time\nimport os\n\nfrom kaggle_uploader import kaggle_uploader \n\nprint(\"Saving Images\")\nstart_time = time.time()\n\n# kaggle_secrets are not supported by Google Cloud Platform for Kaggle(Beta) at this time\n# from kaggle_secrets import UserSecretsClient\n# user_secrets = UserSecretsClient()\n# api_secret = user_secrets.get_secret(\"Crop Cats and Cogs YOLOv3\")\n\nkaggle_uploader.resources = []\nkaggle_uploader.init_on_kaggle(USER_ID, API_TOKEN)\nkaggle_uploader.base_path = OUTPUT_PATH\nkaggle_uploader.title = OUTPUT_DATASET_NAME\nkaggle_uploader.dataset_id = OUTPUT_DATASET_ID\nkaggle_uploader.user_id = USER_ID\n\nfor filename in os.listdir(kaggle_uploader.base_path):\n    kaggle_uploader.add_resource(filename, filename)\n    \nkaggle_uploader.update(\"new version\")\n\nrun_time = time.time()-start_time\nprint('Done Saving Images - Total Time: {:.1f}'.format(run_time) + ' Secs')\n\n# If you get an error during update, it is typically because of an invalid api key, bad username, \n# or the dataset does not exist.  This code does not create datasets.  It updates existing ones","meta":"{'source': 'AI4Code', 'id': 'ed0013c573bfd5'}"}
{"id":"29335","text":"\"\"\"\n## Import packages\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nos.chdir('\/kaggle\/input\/jane-street-market-prediction\/')\nimport janestreet\nos.chdir('\/kaggle\/working')\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nimport shap\nimport tqdm\n\"\"\"\n## Load data files\n\"\"\"\nsample_prediction_df = pd.read_csv('\/kaggle\/input\/jane-street-market-prediction\/example_sample_submission.csv', encoding = 'utf-8-sig')\nfeatures = pd.read_csv('\/kaggle\/input\/jane-street-market-prediction\/features.csv', encoding = 'utf-8-sig')\ntest_data = pd.read_csv('\/kaggle\/input\/jane-street-market-prediction\/example_test.csv', encoding = 'utf-8-sig')\ntrain_data = pd.read_csv('\/kaggle\/input\/jane-street-market-prediction\/train.csv', encoding = 'utf-8-sig')\n\"\"\"\n## EDA\n\"\"\"\nprint(train_data.shape)\ntrain_data.head()\nprint(features.shape)\nfeatures.head()\nprint(test_data.shape)\ntest_data.head()\nprint(sample_prediction_df.shape)\nsample_prediction_df.head()\ntrain_data.describe()\nprint('Number of rows in data:', train_data.shape[0])\ncolumns_in_train_data_nan = pd.DataFrame(train_data.isna().sum()).rename(columns = {0:'Number of NaNs'}).sort_values(by = ['Number of NaNs'], ascending = False)\ncolumns_in_train_data_nan['% NaNs'] = (columns_in_train_data_nan['Number of NaNs']\/train_data.shape[0]) * 100\ncolumns_in_train_data_nan[columns_in_train_data_nan['Number of NaNs']>100000]\n# Fill NaNs with mean of column:\ntrain_data.fillna(train_data.mean(), inplace = True)\npd.DataFrame(train_data['date'].unique()).describe().rename(columns = {0:'Number of days'})\n\"\"\"\nThe data contains 500 days for trading\n\"\"\"\nprint('Number of rows with weight 0:',train_data[train_data['weight']==0].shape[0])\nprint('Number of rows with weight non-zero:',train_data[train_data['weight']!=0].shape[0])\n\"\"\"\nTrades with weight = 0 were intentionally included in the dataset for completeness, although such trades will not contribute towards the scoring evaluation\n\"\"\"\nfeatures[features==True].count(axis = 1).plot()\n\"\"\"\nfeature_0 is the only feature without any true tag\n\"\"\"\ntrain_data.groupby(['date']).size().reset_index().rename(columns = {0: '# Trades in a day'}).plot('date','# Trades in a day', title = 'Trades in a day [1-500]')\n# Correlation analysis from <https:\/\/www.kaggle.com\/isaienkov\/jane-street-market-prediction-fast-understanding>\n\n# Correlation\ncorr_high_columns = []\ncols = train_data.columns.tolist()\nfor i in range(0, len(cols)):\n    for j in range(i+1, len(cols)):\n        if abs(train_data[cols[i]].corr(train_data[cols[j]])) > 0.95:\n            corr_high_columns = corr_high_columns + [cols[i], cols[j]]\ncorr_high_columns = list(set(corr_high_columns))\nprint('Number of columns:', len(corr_high_columns))\ncorr_high_columns\n#Correlation matrix\nf = plt.figure(\n    figsize=(22, 22)\n)\n\nplt.matshow(\n    train_data[corr_high_columns].corr(), \n    fignum=f.number\n)\n\nplt.title('Correlation matrix - for corr above 0.9')\nplt.xticks(\n    range(train_data[corr_high_columns].shape[1]), \n    train_data[corr_high_columns].columns, \n    fontsize=14, \n    rotation=90\n)\n\nplt.yticks(\n    range(train_data[corr_high_columns].shape[1]), \n    train_data[corr_high_columns].columns, \n    fontsize=14\n)\n\ncb = plt.colorbar()\ncb.ax.tick_params(\n    labelsize=14\n)\n\"\"\"\n## Modelling\n\"\"\"\n#Action metric created using: <https:\/\/www.kaggle.com\/hamditarek\/market-prediction-xgboost-with-gpu-fit-in-1min>\n# Create action metric\n# train_data['action'] = ((train_data['weight'].values * train_data['resp'].values) > 0).astype('int')\ntrain_data['action'] = ((train_data['weight'].values * (train_data['resp_1'] + train_data['resp_2'] + train_data['resp_3'] + train_data['resp_4']).values)\/4 > 0).astype('int')\n\ntrain_data_for_model = train_data[train_data['weight'] != 0]\n# train_data_for_model = train_data.copy(deep = True)\n\nX_train = train_data_for_model.loc[:, train_data_for_model.columns.str.contains('feature')]\ny_train = train_data_for_model.loc[:, 'action']\nprint(X_train.shape)\nX_train.head()\nprint(y_train.shape)\nprint(y_train.sum())\ny_train.head()\ndel columns_in_train_data_nan, train_data, features, test_data, train_data_for_model, corr_high_columns\nimport gc\ngc.collect()\nfeatures = [c for c in X_train.columns if 'feature' in c]\nclf = xgb.XGBClassifier(use_label_encoder=False,\n    n_estimators=1000,\n    max_depth=10,\n    learning_rate=0.06,\n    subsample=0.9,\n    colsample_bytree=0.7,\n    random_state=42,\n    tree_method='gpu_hist'  # Treats numerical variable as bins (makes process much faster)\n)\n%time clf.fit(X_train[features], y_train)\nimport pickle\npickle.dump(clf, open('Jane_Street_forecasting_weight_xgboost_model_v1.sav','wb'))\n# filename = '..\/input\/jane-street-pred-model-weights\/Jane_Street_forecasting_weight_xgboost_model_v1.sav'\n# clf = pickle.load(open(filename, 'rb'))\ndef normalize_data(df):\n#     return (df-df.min())\/(df.max()-df.min())\n      return (df-df.mean())\/df.std()\n    \ndf_train = normalize_data(X_train[features])\n# import tensorflow as tf\n# from keras.layers import Activation, Dense\n\n# model = tf.keras.models.Sequential()\n\n# model.add(tf.keras.layers.LSTM(\n#     len(features), \n#     activation='relu', \n#     input_shape=(1, len(features)), \n#     return_sequences=True))\n\n# model.add(tf.keras.layers.Dropout(0.02))\n\n# model.add(Dense(50, activation='swish',input_shape=(len(features), )))\n\n# model.add(tf.keras.layers.Dense(1, activation=\"sigmoid\"))\n\n# model.compile(loss=tf.keras.losses.BinaryCrossentropy(), \n#                 optimizer=tf.optimizers.Adam(learning_rate=0.05),\n#                 metrics=[\"accuracy\"])\n# model.summary()\n# from tensorflow.keras.callbacks import EarlyStopping\n# model.fit(df_train,\n#             epochs = 1,\n#             batch_size = 10000,\n#             verbose = 1,\n#             callbacks = [EarlyStopping(monitor='loss', verbose=1, patience=10)])\n\"\"\"\n## Feature importance\n\"\"\"\n# plot feature importance using built-in function\nfrom numpy import loadtxt\nfrom xgboost import XGBClassifier\nfrom xgboost import plot_importance\nfrom matplotlib import pyplot\nfig, ax = plt.subplots(figsize=(20,30))\nplot_importance(clf, ax = ax)\npyplot.show()\n#SHAP plots\n# Create object that can calculate shap values\nexplainer = shap.TreeExplainer(clf)\n\ndf = X_train.sample(n=1000)\n# calculate shap values. This is what we will plot.\nshap_values = explainer.shap_values(df)\n\n# Make plot\nshap.summary_plot(shap_values, df)\n\"\"\"\nFeatures 39, 64 & 20 strictly increase the action probability. The other features may be dependent on each other. Dimensionality reduction is required to train a better model.\n\"\"\"\n\"\"\"\n## Prediction\n\"\"\"\nenv = janestreet.make_env() # initialize the environment\niter_test = env.iter_test() # an iterator which loops over the test set\n\n# count = 0\nfor (test_df, sample_prediction_df) in iter_test:\n    if test_df['weight'].item() > 0:\n        X_test = test_df.loc[:, features]\n        X_test = X_test.fillna(0)\n#         print(X_test.shape)\n        y_preds = clf.predict(X_test)\n        sample_prediction_df.action = y_preds.astype(int)\n    else:\n        sample_prediction_df.action = 0\n    env.predict(sample_prediction_df)","meta":"{'source': 'AI4Code', 'id': '35e674be618613'}"}
{"id":"8429","text":"\"\"\"\n### Upvote if you like my notebook, Your support and encouragement are greatly appreciated!!!\n\n### Suggestions and Criticisms are welcomed !!\n\n### Thank you!\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n### Importing necessary modules and Reading the data\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(16,6)})\nsns.set(style='whitegrid')\nfrom itertools import cycle\ncolor_cycle = cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'])\ncalender = pd.read_csv('\/kaggle\/input\/m5-forecasting-accuracy\/calendar.csv')\nsales_train_validation = pd.read_csv('\/kaggle\/input\/m5-forecasting-accuracy\/sales_train_validation.csv')\nsell_prices = pd.read_csv('\/kaggle\/input\/m5-forecasting-accuracy\/sell_prices.csv')\nsample_submission = pd.read_csv('\/kaggle\/input\/m5-forecasting-accuracy\/sample_submission.csv')\nsales_train_validation.sample(5)\ncalender.sample(3)\nprint(sales_train_validation.shape)\nprint(calender.shape)\n\"\"\"\n### Visualizing department level sales\n\"\"\"\ndept_df = sales_train_validation.dept_id.value_counts().rename_axis('dept').reset_index(name='count')\nsns.barplot(x='dept', y='count', data=dept_df, palette='gist_gray')\nplt.title('Department level Sales')\nplt.show()\n\"\"\"\n### Visualizing state level Sales\n\"\"\"\nstate_df = sales_train_validation.state_id.value_counts().rename_axis('state').reset_index(name='count')\nsns.barplot(x='state', y='count', data=state_df, palette='gist_gray')\nplt.title('State level Sales')\nplt.show()\n\"\"\"\n### Visualizing Sales by Category\n\"\"\"\ncat_df = sales_train_validation.cat_id.value_counts().rename_axis('cat').reset_index(name='count')\nsns.barplot(x='cat', y='count', data=cat_df, palette='gist_gray')\nplt.title('Sales by Category')\nplt.show()\n\"\"\"\n### Visualizing Sales by Category and State\n\"\"\"\nsales_train_validation['sales'] = sales_train_validation.sum(axis=1)\nsns.barplot(x='cat_id', y='sales', data=sales_train_validation, hue='state_id', color=next(color_cycle))\nplt.title('Sales by Category and State')\nplt.show()\n\"\"\"\n### Visualizing Sales by State and Category\n\"\"\"\nsns.barplot(x='state_id', y='sales', data=sales_train_validation, hue='cat_id', color=next(color_cycle))\nplt.title('Sales by State and Category')\nplt.show()\n\"\"\"\n### Categorywise sales by different stores\n\"\"\"\nsns.barplot(x='store_id', y='sales', data=sales_train_validation, hue='cat_id', color=next(color_cycle))\nplt.title('Categorywise sales by different stores')\nplt.show()\n\"\"\"\n### Looking at Sales of Random Items\n\"\"\"\nday_cols = [col for col in sales_train_validation.columns if 'd_' in col]\nsales_train_validation.sort_values('sales', ascending=False)[day_cols].sample(5)\nrandom_items = ['FOODS_3_090_CA_3_validation','FOODS_3_661_CA_1_validation','FOODS_3_377_TX_3_validation']\nfig, axes = plt.subplots(3,1,figsize=(16,12), sharex=True)\naxes = axes.flatten()\naxx=0\nfor item in random_items:\n    sales_train_validation.loc[sales_train_validation.id==item][day_cols].T.plot(color=next(color_cycle), ax=axes[axx], label='sales')\n    axes[axx].set_title(item)\n    axx+=1\nplt.suptitle('Plotting random item sales')\nplt.show()\n\"\"\"\n### Time series of Sales across the States\n\"\"\"\n# Yearly sales in all the stores\nmean_sales_CA = sales_train_validation[sales_train_validation.state_id=='CA'][day_cols].mean(axis=0).reset_index().set_index(calender[0:1913]['date'])\nmean_sales_CA = mean_sales_CA.drop('index', axis=1)\nmean_sales_CA.index = pd.to_datetime(mean_sales_CA.index)\nmean_sales_CA.columns = ['mean_sale_items']\n\nmean_sales_TX = sales_train_validation[sales_train_validation.state_id=='TX'][day_cols].mean(axis=0).reset_index().set_index(calender[0:1913]['date'])\nmean_sales_TX = mean_sales_TX.drop('index', axis=1)\nmean_sales_TX.index = pd.to_datetime(mean_sales_TX.index)\nmean_sales_TX.columns = ['mean_sale_items']\n\nmean_sales_WI = sales_train_validation[sales_train_validation.state_id=='WI'][day_cols].mean(axis=0).reset_index().set_index(calender[0:1913]['date'])\nmean_sales_WI = mean_sales_WI.drop('index', axis=1)\nmean_sales_WI.index = pd.to_datetime(mean_sales_WI.index)\nmean_sales_WI.columns = ['mean_sale_items']\n\n# Plotting sale of items in all three cities\nfig, (ax1,ax2,ax3) = plt.subplots(3,1, figsize=(18,16), sharex=True)\n\nax1.plot(mean_sales_CA, label='sales - CA', color=next(color_cycle))\nax1.legend(loc='upper left')\n\nax2.plot(mean_sales_TX, label='sales - TX', color=next(color_cycle))\nax2.legend(loc='upper left')\n\nax3.plot(mean_sales_WI, label='sales - WI', color=next(color_cycle))\nax3.legend(loc='upper left')\nplt.title('Yearly sales of all goods across states')\nplt.tight_layout()\nplt.show() \n\"\"\"\n### Plotting the moving avrage sales across the states\n\n\"\"\"\n# Plotting the moving avrage\nfig, ax = plt.subplots(figsize=(18,6))\nax.plot(mean_sales_CA.rolling(window=80).mean(), label='moving average sales CA', color=next(color_cycle))\nax.plot(mean_sales_TX.rolling(window=80).mean(), label='moving average sales TX', color=next(color_cycle))\nax.plot(mean_sales_WI.rolling(window=80).mean(), label='moving average sales WI', color=next(color_cycle))\nplt.legend()\nplt.title('Moving average sales of the ctates')\nplt.show()\n\"\"\"\n### Consolidated monthly mean of sales across States\n\"\"\"\n# Monthly sales across the states\nmean_sales_CA['month'] = pd.DatetimeIndex(mean_sales_CA.index).month_name()\nmean_sales_CA['weekday_name'] = pd.DatetimeIndex(mean_sales_CA.index).weekday_name\n\nmean_sales_TX['month'] = pd.DatetimeIndex(mean_sales_TX.index).month_name()\nmean_sales_TX['weekday_name'] = pd.DatetimeIndex(mean_sales_TX.index).weekday_name\n\nmean_sales_WI['month'] = pd.DatetimeIndex(mean_sales_WI.index).month_name()\nmean_sales_WI['weekday_name'] = pd.DatetimeIndex(mean_sales_WI.index).weekday_name\n\nnew_order = ['January','February','March','April','May','June','July','August','September','October','November','December']\n\nmean_sales_CA_grouped = mean_sales_CA.groupby(['month']).mean().reindex(new_order, axis=0)\nmean_sales_TX_grouped = mean_sales_TX.groupby(['month']).mean().reindex(new_order, axis=0)\nmean_sales_WI_grouped = mean_sales_WI.groupby(['month']).mean().reindex(new_order, axis=0)\n\nfig, ax = plt.subplots(figsize=(18,6))\n\nax.plot(mean_sales_CA_grouped, label='mothly sales in CA', c='red', linewidth=4)\nax.plot(mean_sales_TX_grouped, label='mothly sales in TX', c='green', linewidth=4)\nax.plot(mean_sales_WI_grouped, label='mothly sales in WI', c='blue', linewidth=4)\n\nax.legend(loc='upper right')\nplt.title('Consolidated monthly sales across States')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Consolidated weekly sales acrosss states\n\"\"\"\nnew_order = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']\nmean_sales_CA_grouped = mean_sales_CA.groupby(['weekday_name']).sum().reindex(new_order, axis=0)\nmean_sales_TX_grouped = mean_sales_TX.groupby(['weekday_name']).sum().reindex(new_order, axis=0)\nmean_sales_WI_grouped = mean_sales_WI.groupby(['weekday_name']).sum().reindex(new_order, axis=0)\nfig, ax = plt.subplots(figsize=(18,6))\nax.plot(mean_sales_CA_grouped, label='weekly sales in CA')\nax.plot(mean_sales_TX_grouped, label='weekly sales in TX')\nax.plot(mean_sales_WI_grouped, label='weekly sales in WI')\nplt.title('Consolidated weekly sales acrosss states')\nplt.legend()\nplt.show()\n\"\"\"\n### Specific on Hobbey item sales in California\n\"\"\"\n# Hobbey item sales in California\nfig, axes = plt.subplots(3, 1, figsize=(16,12), sharex=True)\naxes = axes.flatten()\naxx = 0\nfor cat in sales_train_validation.cat_id.unique():\n    sales = sales_train_validation[(sales_train_validation.cat_id==cat) & (sales_train_validation.state_id=='CA')][day_cols].T.\\\n    mean(axis=1).reset_index().set_index(calender[0:1913]['date']).drop('index', 1)\n    sales.columns = ['sales_CA_'+str(cat)]\n    sales.index = pd.to_datetime(sales.index)\n    sales.plot(color=next(color_cycle), ax=axes[axx])\n    axx += 1\nplt.suptitle('Hobbey item sales in California')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Looking at mean sales of all the stores\n\"\"\"\n# Sales by store\nsales_train_validation = pd.read_csv('\/kaggle\/input\/m5-forecasting-accuracy\/sales_train_validation.csv')\nsales_by_store = sales_train_validation.groupby(['store_id']).mean().T\nsales_by_store = sales_by_store.set_index(calender[0:1913]['date'])\nsales_by_store.index = pd.to_datetime(sales_by_store.index)\n\nfig,ax = plt.subplots()\nfor col in sales_by_store.columns:\n    sales_by_store[col].plot(color=next(color_cycle), label='avg sales '+str(col), ax=ax)\nplt.title('Mean sales across the shops')\nplt.show()\n\"\"\"\n### Moving average sales of all stores: better visualization, window=100\n\"\"\"\n# moving average sales in all the 10 shops\nimport matplotlib.dates as mdates\n\nsales_rolling = sales_by_store.rolling(100).mean()\nfig,ax = plt.subplots(figsize=(18,7))\nfor col in sales_by_store.columns:\n    sales_rolling[col].plot( label='avg sales '+str(col), ax=ax, color=next(color_cycle), linewidth=1)\n#ax.xaxis.set_major_locator(mdates.YearLocator())\n#ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))\nplt.title('moving average sales across the shops')\nplt.legend(fontsize=12)\nplt.show()\n\"\"\"\n### Visualizing monthly trends across the stores\n\n\"\"\"\nsales_by_store['month'] = pd.DatetimeIndex(sales_by_store.index).month_name()\nsales_by_store['weekdays'] = pd.DatetimeIndex(sales_by_store.index).weekday_name\n\n# Monthly sales across the stores\nnew_order = ['January','February','March','April','May','June','July','August','September','October','November','December']\nmonthly_store_sales = sales_by_store.groupby(['month']).mean().reindex(new_order, axis=0)\nfig, axes = plt.subplots(5,2,figsize=(18,12), sharex=True)\naxes = axes.flatten()\naxx = 0\nfor col in monthly_store_sales.columns[0:11]:\n    monthly_store_sales[col].plot(color=next(color_cycle), ax=axes[axx])\n    axes[axx].set_title(str(col))\n    axx+=1\nplt.suptitle('Monthly trend in different stores')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Weekly trends across the stores\n\"\"\"\n# Weekly sales across the stores\nnew_order = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']\nweekly_store_sales = sales_by_store.groupby(['weekdays']).mean().reindex(new_order, axis=0)\nfig, axes = plt.subplots(5,2,figsize=(18,12), sharex=True)\naxes = axes.flatten()\naxx = 0\nfor col in weekly_store_sales.columns[0:11]:\n    weekly_store_sales[col].plot(color=next(color_cycle), ax=axes[axx])\n    axes[axx].set_title(str(col))\n    axx+=1\nplt.suptitle('Weekly trend in different stores')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Yearly trends across the stores\n\"\"\"\n#new_order = ['January','February','March','April','May','June','July','August','September','October','November','December']\n#monthly_store_sales = sales_by_store.groupby(['month']).mean().reindex(new_order, axis=0)\nfig, axes = plt.subplots(5,2,figsize=(18,12), sharex=True)\naxes = axes.flatten()\naxx = 0\nfor col in monthly_store_sales.columns[0:11]:\n    sales_by_store[col].plot(color=next(color_cycle), ax=axes[axx])\n    axes[axx].set_title(str(col))\n    axx+=1\nplt.suptitle('Yearly trend in different stores')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Monthly and weekly trends by Categories\n\"\"\"\n# Trend in sales of items\nfor cat in sales_train_validation.cat_id.unique():\n    df = sales_train_validation[sales_train_validation.cat_id==cat][day_cols].\\\n    T.mean(axis=1).reset_index().set_index(calender[0:1913]['date']).drop('index', 1)\n    df.columns = ['mean_sales']\n    df.index = pd.to_datetime(df.index)\n    df['month'] = pd.DatetimeIndex(df.index).month_name()\n    df['weekday_name'] = pd.DatetimeIndex(df.index).weekday_name\n\n\n    fig, (ax1,ax2) = plt.subplots(2,1,figsize=(16,8))\n    sns.boxplot(x='month', y='mean_sales', data=df, ax=ax1)\n    ax1.set_title('monthly trend')\n    sns.boxplot(x='weekday_name', y='mean_sales', data=df, ax=ax2)\n    ax2.set_title('weekly trend')\n    plt.suptitle('Trend across ' + str(cat))\n    # plt.tight_layout()\n    plt.show()\n\"\"\"\n### Detecting trends for all the stores\n\"\"\"\n# Detect trend\nimport matplotlib.dates as mdates\ndef detect_trend(X_df):\n    coefficients, residuals, _, _, _ = np.polyfit(range(len(X_df)), X_df, 1, full=True)\n    mse = residuals[0]\/len(X_df)\n    nrmse = np.sqrt(mse)\/(X_df.max()-X_df.min())\n    \n    print('slope = ', str(float(coefficients[0])))\n    print('nrmse = ', str(float(nrmse)))\n    \n    fig, ax = plt.subplots(figsize=(9,5))\n    new_df = pd.DataFrame([coefficients[0]*x+coefficients[1] for x in range(len(X_df))], columns=['trend'])    \n    new_df = new_df.reset_index().set_index(calender[0:1913]['date']).drop('index', 1)\n    X_df.plot(color=next(color_cycle), ax=ax, label='Original')\n    new_df.plot(ax=ax, color='red', linewidth=4)\n    ax.legend()\n    plt.show()\n    \nfor col in sales_by_store.columns:\n    X_df = sales_by_store[col].reset_index().set_index(calender[0:1913]['date']).drop('date', 1)\n    detect_trend(X_df)\n\"\"\"\n### Efforts from a humble beginner!\n\n### To be continued!\n\n### Cast an upvote if it was useful!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0f985517b38f25'}"}
{"id":"138030","text":"#libraries\nimport numpy as np # linear algebra\nimport keras\nfrom keras.models import load_model\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Activation\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport os\nprint(os.listdir(\"..\/input\/Sign-language-digits-dataset\"))\n\n# load data\nX = np.load(\"..\/input\/Sign-language-digits-dataset\/X.npy\")\nY = np.load(\"..\/input\/Sign-language-digits-dataset\/Y.npy\")\n\nprint(\"Samples :\", X.shape[0])\n#sample image\nplt.imshow(X[345], cmap = \"gray\")\nplt.show()\n#split train and test \nx_train, x_test, y_train, y_test = train_test_split(X,Y, test_size = .33, shuffle = True)\n\nx_train =  x_train.reshape(-1,64,64,1)\nx_test =  x_test.reshape(-1,64,64,1)\n\nprint(\"x_train shape:\", x_train.shape)\nprint(\"x_test shape:\", x_test.shape)\nprint(\"y_train shape:\", y_train.shape)\nprint(\"y_test shape:\", y_test.shape)\n\"\"\"\n**Create Model**\n\"\"\"\nbatch_size = 128\nepoch = 20\ninput_shape = (64,64,1)\nnum_classes = 10\n\nmodel = Sequential()\nmodel.add(Conv2D(64,(4,4), input_shape = input_shape))\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size = (4,4)))\n\nmodel.add(Conv2D(64,(5,5)))\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size = (4,4)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128,activation = \"relu\"))\nmodel.add(Dropout(0.25))\n\nmodel.add(Dense(num_classes, activation = \"softmax\"))\n\n\nmodel.summary()\n#compile\nmodel.compile(loss = keras.losses.categorical_crossentropy,\n             optimizer = keras.optimizers.Adadelta(),\n             metrics = [\"accuracy\"])\n#fit\nmodel.fit(x_train,y_train,\n         batch_size = batch_size,\n         epochs = epoch,\n         verbose = 1,\n         validation_data = (x_test,y_test))\nscore = model.evaluate(x_test, y_test, verbose = 0)\n\nprint(\"Test Loss: \", score[0])\nprint(\"Test Accucary: \", score[1])\n#save model\nmodel.save(\"..your_path\/your_model.h5\")\n\n#load model\nmodel_test = load_model(\"..your_path\/your_model.h5)\n\"\"\"\n**Trying  Model**\n\"\"\"\nclasses = [\"9\", \"0\", \"7\", \"6\", \"1\", \"0\", \"4\",\"3\", \"2\", \"5\"]\n\n#index for test data 0 ~ 680\nindex = 254\nplt.imshow(x_test[index].reshape(64,64), cmap = \"gray\")\ny_test[index]\n#predict\ntest = x_test[index].reshape(1,64,64,1)\npre = model.predict(test, batch_size = 1)\n#pre = model_test(test, batch_size = 1) with loaded model\n\nprint(\"Prediction: \", np.round(pre, 0))\nprint(\"Real value: \", y_test[index])\nprint(\"Number: \",classes[np.argmax(pre)])","meta":"{'source': 'AI4Code', 'id': 'fdb7c34f6f7ce5'}"}
{"id":"108378","text":"\"\"\"\n## CNN-Convolution Neural Network\n\"\"\"\n\"\"\"\nWhen we enter into the world of computer vision we have to understand how a computer understands an image. A colored image has three channels and a 2D data in each channel. When the image size increases Machine learning start suffering from the curse of dimensionality, in order to overcome from this Deep learning comes up with a special type of Feedforward neural network known as CNN- Convolutional Neural Network.\n\"\"\"\n# 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 in \n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n#  Load pre-shuffled MNIST data into train and test sets\nimport matplotlib.pyplot as plt\n%matplotlib inline\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\nplt.imshow(X_train[0])\nnum_pixels = X_train.shape[1] * X_train.shape[2]\nX_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')\nX_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')\nX_train = X_train \/ 255\nX_test = X_test \/ 255\n\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\n\"\"\"\nNow Create a model in Deep learning using Keras,\n\"\"\"\ndef baseline_model():\n    model = Sequential()\n    model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal',\n    activation='relu'))\n    model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))\n    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n    return model\n\"\"\"\nNow Build and run the model.\n\"\"\"\n#build the model\nmodel = baseline_model()\n# Fit the model\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200,\nverbose=2)\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=0)\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))\n\"\"\"\n# Conv1D\nImport the libraries,\n\"\"\"\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import Embedding\nfrom keras.layers import Conv1D, GlobalMaxPooling1D\nfrom keras.datasets import imdb\n\"\"\"\nLoad Data,\n\"\"\"\n#  Load pre-shuffled MNIST data into train and test sets\nimport matplotlib.pyplot as plt\n%matplotlib inline\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n# set parameters:\nmax_features = 5000\nmaxlen = 784\nbatch_size = 32\nembedding_dims = 50\nfilters = 250\nkernel_size = 3\nhidden_dims = 250\nepochs = 2\nnum_pixels = X_train.shape[1] * X_train.shape[2]\n#num_pixels 28*28=784\nnum_pixels = X_train.shape[1] * X_train.shape[2]\n#num_pixels 28*28=784\nX_train = X_train.reshape(X_train.shape[0],num_pixels).astype('float32')\nX_test = X_test.reshape(X_test.shape[0],num_pixels).astype('float32')\nX_train.shape\nX_train = X_train \/ 255\nX_test = X_test \/ 255\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1] \ny_train.shape\nprint('x_train shape:', X_train.shape)\nprint('x_test shape:', X_test.shape)\nprint('Build model...')\nmodel = Sequential()\nmodel.add(Embedding(max_features,\n                    embedding_dims,\n                    input_length=maxlen))\nmodel.add(Conv1D(filters,\n                 kernel_size,\n                 padding='valid',\n                 activation='relu',\n                 strides=1))\n# we use max pooling:\nmodel.add(GlobalMaxPooling1D())\n# We project onto a single unit output layer, and squash it with a sigmoid:\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='categorical_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\nmodel.fit(X_train, y_train,\n          batch_size=batch_size,\n          epochs=epochs,\n          validation_data=(X_test, y_test))\n\"\"\"\n# Conv2D\nLoad Libraries,\n\"\"\"\n#But this is not CNN its simple multi perceptron that are working as a CNN classifier\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K\nK.set_image_dim_ordering('th')\nimport matplotlib.pyplot as plt\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n%matplotlib inline\nplt.imshow(X_train[0])\nimport numpy \n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n# load data\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n# reshape to be [samples][channels][width][height]\nX_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')\nX_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')\n# normalize inputs from 0-255 to 0-1\nX_train = X_train \/ 255\nX_test = X_test \/ 255\n# one hot encode outputs\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\nplt.imshow(X_train[2232,0,:,:])\ndef baseline_model():\n# create model\n    model = Sequential()\n    model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.2))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu'))\n    model.add(Dense(num_classes, activation='softmax'))\n    # Compile model\n    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n    return model\nmodel = baseline_model()\n# Fit the model\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=0)\nprint(\"CNN Error: %.2f%%\" % (100-scores[1]*100))\n\"\"\"\nArticle : http:\/\/www.machineintellegence.com\/cnn-convolution-neural-network\/\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c7381e799e377a'}"}
{"id":"127212","text":"\"\"\"\n# Imports\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\nimport re\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\nplt.rcParams['figure.figsize'] = 20, 15\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder\nfrom sklearn.ensemble import RandomForestClassifier\nfrom keras.models import Sequential\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.layers import Dense, Embedding, LSTM, SpatialDropout1D, Dropout\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.preprocessing.text import one_hot\nfrom sklearn.model_selection import train_test_split\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\n\"\"\"\n# Preprocessing\n\"\"\"\ndf = pd.read_csv('..\/input\/twitter-and-reddit-sentimental-analysis-dataset\/Reddit_Data.csv')\ndf.dropna(inplace=True)\ndf.category.value_counts(normalize=True)\ndf = df.sample(n=10000).reset_index(drop=True)\ndf.category.value_counts(normalize=True)\ndf.columns = ['Comment', 'Category']\ndf\nX, y = df.iloc[:,:-1],df.iloc[:,-1]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nprint(f'X_train, X_test, y_train, y_test shapes are {X_train.shape, X_test.shape, y_train.shape, y_test.shape}')\nallwords = \" \".join([com for com in df.Comment])\nwc = WordCloud().generate(allwords)\nplt.imshow(wc,interpolation='bilinear')\nplt.axis('off')\nnew = df.Comment.apply(lambda x:len(x))\nplt.hist(new)\n# Vocab size\nvocab_size = 5000\n\ndef preprocess(messages, sentence_length=60):\n    # Stemming\n    ps = PorterStemmer()\n    corpus = []\n    for i in range(len(messages)):\n        review = re.sub('^a-zA-Z', ' ', messages[i])\n        review = review.lower()\n        review = review.split()\n        review = [ps.stem(word) for word in review if word not in stopwords.words('english')]\n        review = ' '.join(review)\n        corpus.append(review) \n    # Oen hot coding\n    oh_repr = [one_hot(sent, vocab_size) for sent in corpus]\n\n    padded_seq = pad_sequences(oh_repr, maxlen=sentence_length)\n    return padded_seq\npadded_seq = preprocess(X_train.Comment.reset_index(drop=True))\npadded_seq.shape\n\"\"\"\n# Model\n\"\"\"\nno_of_features = 200\nsent_len=60\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, no_of_features, input_length=sent_len))\nmodel.add(LSTM(100, return_sequences=True))\nmodel.add(Dropout(.2))\nmodel.add(LSTM(100))\nmodel.add(Dropout(.2))\nmodel.add(Dense(3,activation='softmax'))\nmodel.compile(optimizer=Adam(.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\n# Add callbacks\nfilepath = '.\/Sentiment.h5'\ncheckpoint = ModelCheckpoint(filepath, save_best_only=True, verbose=1)\nearlystop = EarlyStopping(patience=5, verbose=1)\n#csvlg = CSVLogger('mylogs.csv', separator=',', append=False)\n\ncallback_list = [earlystop, checkpoint]\n\nenc = LabelEncoder()\ny = enc.fit_transform(y_train)\n\nX, y = np.array(padded_seq), np.array(y)\nhistory = model.fit(X, y, validation_split=.2, epochs=30, batch_size=32, callbacks=callback_list)\ndef plot_history(history):\n    plt.plot(history['loss'], label='Original loss')\n    plt.plot(history['val_loss'], label='Validation loss')\n    plt.plot(history['accuracy'], label='Original accuracy')\n    plt.plot(history['val_accuracy'], label='Validation accuracy')\n    plt.legend()\nplot_history(history.history)\nmodel.evaluate(preprocess(X_test.Comment.reset_index(drop=True)), enc.transform(y_test))\n\"\"\"\n# TextBlob\n\"\"\"\ndef polarity(text):\n    return TextBlob(text).sentiment.polarity\ndef subjectivity(text):\n    return TextBlob(text).sentiment.subjectivity\n    \n\ndf['polarity'] = df.Comment.apply(polarity)\ndf['subjectivity'] = df.Comment.apply(subjectivity)\ndf\nX, y = df.iloc[:,-2:],df.iloc[:,-3]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nprint(f'X_train, X_test, y_train, y_test shapes are {X_train.shape, X_test.shape, y_train.shape, y_test.shape}')\nX[:5], y[:5]\nclassifier = RandomForestClassifier()\nclassifier.fit(X_train, y_train)\n\npreds = classifier.predict(X_test)\npreds\naccuracy_score(y_test,preds)","meta":"{'source': 'AI4Code', 'id': 'e9f184e7453bdf'}"}
{"id":"100821","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\ndata = pd.read_csv(\"..\/input\/athlete_events.csv\")\ndata.info()\ndata.head()\ndata.corr()\n# Correletaion map\nf,ax=plt.subplots(figsize=(10,10))\nsns.heatmap(data.corr(),annot=True,linewidths=.5,fmt=\".2f\",ax=ax)\nplt.show()\n# Also we can see from here weight and height is directly proportional\n# Learn what is there as properties in data.\ndata.columns\ndata.head()\n# Line plot I took first 800 data because all data includes 271116 and this is very big to analyze\ndata.Height[0:800].plot(kind = 'line', color = 'g',label = 'Height',linewidth=1,alpha = 0.7,grid = True,linestyle = ':')\ndata.Weight[0:800].plot(color=\"red\",figsize=(8,8),label=\"Weight\",linewidth=1,alpha=0.7,grid=True,linestyle=\":\")\nplt.legend()\nplt.xlabel(\"Athletes\")\nplt.ylabel(\"Height and Weight\")\nplt.title(\"Line Plot\")\nplt.show()\n\n\n\n\n\n# Scatter Plot\ndata.plot(kind='scatter', x=\"Height\", y=\"Weight\",alpha = 0.7,color = 'red')\nplt.xlabel('Height')              # label = name of label\nplt.ylabel('Weight')\nplt.title('Height Weight Scatter Plot')   \nplt.show()\nprint(\" max height of athletes is \",data.Height.max(),\" cm\")\nprint(\" max weight of athletes is \",data.Weight.max(),\" kg\")\nprint(\" min height of athletes is \",data.Height.min(),\" cm\")\nprint(\" min weight of athletes is \",data.Weight.min(),\" kg\")\n\n\n\n\n# histogram \ndata.Height.plot(kind = 'hist',bins = 50,figsize = (12,12))\nplt.show()\n#these are just for learning and practice\ndictionary = {'Turkey' : ['istanbul','ankara'],'Usa' : ['Las_vegas''New_york']}\nprint(dictionary.keys())\nprint(dictionary.values())\ndictionary['Turkey'] = [\"bal\u0131kesir\",\"bursa\"]    # update existing entry\nprint(dictionary)\ndictionary['france'] = [\"paris\",\"lille\"]       # Add new entry\nprint(dictionary)\ndel dictionary['france']              # remove entry with key 'spain'\nprint(dictionary)\nprint('Turkey' in dictionary)        # check include or not\ndictionary.clear()                   # remove all entries in dict\nprint(dictionary)\nseries_name = data['Name']        # data['Defense'] = series\nprint(type(series_name))\ndata_frame = data[['Age']]  # data[['Defense']] = data frame\nprint(type(data_frame))\nx = data['Height']>220    \ndata[x]\ny=data[\"Weight\"]>200\nprint(\"max height and weight\")\ndata[y]\ndata[(data['Height']>200) & (data['Weight']>150)]\nfor index,value in data[['Height']][0:8].iterrows():\n    print(index,\" : \",value)\n\"\"\"\nAll analysis is this and thanks for everything that read or review\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b94d32f6733801'}"}
{"id":"43353","text":"\"\"\"\n## 1. Install libraries\n\"\"\"\n!python3 -m pip install --upgrade pip\n!pip install seaborn==0.11.0\n!python3 -m pip install pandas\n!python3 -m pip install matplotlib\n!python3 -m pip install seaborn\n!python3 -m pip install sklearn\n\"\"\"\n## 2. Import libraries\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\"\"\"\n## 3. Load Dataset\n\"\"\"\ndf = pd.read_csv(\"https:\/\/raw.githubusercontent.com\/ojjy\/datascience\/master\/heart_failure_clinic\/heart_failure_clinical_records_dataset.csv\")\ndf.head(5)\n\"\"\"\n## 4. Data Explorary Analysis\n\"\"\"\ndf['age'] = df['age'].astype(int)\ndf.tail(5)\ndf.shape\ndf.isnull().sum()\ndf.info()\ndf['anaemia'].value_counts()\ndf['diabetes'].value_counts()\ndf['sex'].value_counts()\ndf['smoking'].value_counts()\ndf['DEATH_EVENT'].value_counts()\ndf[(df['anaemia']==1)&(df['diabetes']==1)&(df['smoking']==1)]\nplt.figure(figsize=(15,10))\nsns.countplot(x='age', data=df)\nfig, axes = plt.subplots(2, 3, figsize=(15, 10))\nsns.countplot(x=df['anaemia'], data=df, ax=axes[0,0])\nsns.countplot(x=df['diabetes'], data=df, ax=axes[0,1])\nsns.countplot(x=df['high_blood_pressure'], data=df, ax=axes[0,2])\nsns.countplot(x=df['sex'], data=df, ax=axes[1,0])\nsns.countplot(x=df['smoking'], data=df, ax=axes[1,1])\nsns.countplot(x=df['DEATH_EVENT'], data=df, ax=axes[1,2])\n\"\"\"\n## 5. Split data\n\"\"\"\nx=df.drop('DEATH_EVENT', axis=1)\ny=df['DEATH_EVENT']\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\nprint(f\"x_train: {x_train.shape}\")\nprint(f\"x_test: {x_test.shape}\")\nprint(f\"y_train: {y_train.shape}\")\nprint(f\"y_test: {y_test.shape}\")\naccuracy_list=[]\nmodel_list=[]\n\"\"\"\n## 6. Modeling\n\"\"\"\n\"\"\"\n### 6-1. AdaBoost\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nada_clf = AdaBoostClassifier(n_estimators=500, learning_rate=0.01, random_state=0)\nada_model = ada_clf.fit(x_train, y_train)\ny_pred_ada = ada_model.predict(x_test)\nada_acc = accuracy_score(y_test, y_pred_ada)\naccuracy_list.append(round(ada_acc*100, 2))\nmodel_list.append(\"AdaBoost\")\nround(ada_acc*100, 2)\nada_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_ada)\n\"\"\"\n### 6-2. XGBoost\n\"\"\"\n!pip install xgboost\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nxgb_clf = XGBClassifier(n_estimators=500, learning_rate=0.01, random_state=0)\nxgb_model=xgb_clf.fit(x_train, y_train)\ny_pred_xgb = xgb_model.predict(x_test)\nxgb_acc = accuracy_score(y_test, y_pred_xgb)\naccuracy_list.append(round(xgb_acc*100, 2))\nmodel_list.append(\"XGBoost\")\nround(xgb_acc*100, 2)\nxgb_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_xgb)\n\"\"\"\n### 6-3. GradientBoost\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\ngrb_clf = GradientBoostingClassifier(max_depth=2, random_state=1)\ngrb_model = grb_clf.fit(x_train, y_train)\ny_pred_grb = grb_model.predict(x_test)\ngrb_acc = accuracy_score(y_test, y_pred_grb)\naccuracy_list.append(round(grb_acc*100, 2))\nmodel_list.append(\"GradientBoost\")\nround(grb_acc*100, 2)\ngrb_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_grb)\n\"\"\"\n### 6-4. Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nlog_reg = LogisticRegression()\nlog_reg_model = log_reg.fit(x_train, y_train)\ny_pred_log = log_reg_model.predict(x_test)\nlog_reg_acc = accuracy_score(y_test, y_pred_log)\naccuracy_list.append(round(log_reg_acc*100,2))\nmodel_list.append(\"Logistic Regression\")\nround(log_reg_acc*100,2)\nlog_reg.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_log)\n\"\"\"\n### 6-5. Support Vector Machine\n\"\"\"\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nsv_clf = SVC()\nsv_clf.fit(x_train, y_train)\ny_pred_sv = sv_clf.predict(x_test)\nsv_clf_acc = accuracy_score(y_test, y_pred_sv)\naccuracy_list.append(round(sv_clf_acc*100, 2))\nmodel_list.append(\"SVC\")\nround(sv_clf_acc*100, 2)\nsv_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_sv)\n\"\"\"\n### 6-6. KNN\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nkn_clf = KNeighborsClassifier(n_neighbors=6)\nkn_clf.fit(x_train, y_train)\ny_pred_kn = kn_clf.predict(x_test)\nkn_clf_acc = accuracy_score(y_test, y_pred_kn)\naccuracy_list.append(round(kn_clf_acc*100, 2))\nmodel_list.append('KNN')\nround(kn_clf_acc*100, 2)\nkn_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_kn)\n\"\"\"\n### 6-7. Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\ndt_clf = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0, criterion='entropy')\ndt_clf.fit(x_train, y_train)\ny_pred_dt = dt_clf.predict(x_test)\ndt_clf_acc = accuracy_score(y_test, y_pred_dt)\naccuracy_list.append(round(dt_clf_acc*100, 2))\nmodel_list.append('Decision Tree')\nround(dt_clf_acc*100, 2)\ndt_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_dt)\n\"\"\"\n### 6-8. Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nr_clf = RandomForestClassifier(max_features=0.5, max_depth=15, random_state=1)\nr_clf.fit(x_train, y_train)\ny_pred_r = r_clf.predict(x_test)\nr_clf_acc = accuracy_score(y_test, y_pred_r)\naccuracy_list.append(round(r_clf_acc*100, 2))\nmodel_list.append(\"Random Forest\")\nround(r_clf_acc*100, 2)\nr_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_r)\n!pip install lightgbm\n\"\"\"\n### 6-8. lightgbm\n\"\"\"\nfrom lightgbm import LGBMClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nlgb_clf = LGBMClassifier(max_depth=2, random_state=4)\nlgb_clf.fit(x_train,y_train)\ny_pred_lgb = lgb_clf.predict(x_test)\nlgb_clf_acc = accuracy_score(y_test, y_pred_lgb)\naccuracy_list.append(round(lgb_clf_acc*100, 2))\nmodel_list.append('LGBM')\nround(lgb_clf_acc*100, 2)\nlgb_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_lgb)\n\"\"\"\n### 6-9. CatBoost\n\"\"\"\n!pip install catboost\nfrom catboost import CatBoostClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix\ncat_clf = CatBoostClassifier()\ncat_clf.fit(x_train,y_train)\ny_pred_cat = cat_clf.predict(x_test)\ncat_clf_acc = accuracy_score(y_test, y_pred_cat)\naccuracy_list.append(round(cat_clf_acc*100, 2))\nmodel_list.append('CatBoost')\nround(cat_clf_acc*100, 2)\ncat_clf.score(x_test, y_test)\nconfusion_matrix(y_test, y_pred_cat)\n\"\"\"\n## 7. Compared with models\n\"\"\"\naccuracy_list\nmodel_list\ndataset = pd.DataFrame({'x':model_list, 'y':accuracy_list})\ndataset\nplt.rcParams['figure.figsize']=20,8\nplt.xlabel('Classifier Models', fontsize = 20)\nplt.ylabel('% of Accuracy', fontsize = 20)\nplt.bar(model_list, accuracy_list)\nfor i, v in enumerate(model_list):\n    plt.text(v, accuracy_list[i], accuracy_list[i],  # \uc88c\ud45c (x\ucd95 = v, y\ucd95 = y[0]..y[1], \ud45c\uc2dc = y[0]..y[1])\n             fontsize='large',\n             horizontalalignment='center',  # horizontalalignment (left, center, right)\n             verticalalignment='bottom')    # verticalalignment (top, center, bottom)","meta":"{'source': 'AI4Code', 'id': '4fde40ebca14a5'}"}
{"id":"75528","text":"\"\"\"\n**Brief Information:** One of the biggest e-commerce company in Turkey called \"Trendyol\" (www.trendyol.com) sells books online. This dataset is scraped from their ranked mostly liked books page. We will analyse the books, authors, prices, publishers, sellers and their ranks to understand why they are the most liked ones.\n\"\"\"\n#importing libraries\nimport requests\nimport pandas as pd\nimport numpy as np\nfrom bs4 import BeautifulSoup\nimport re\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n#importing data\ndata= pd.read_excel('..\/input\/booksdata\/books2.xlsx')\ndata\ndata.info()\n\"\"\"\nWe don't have any missing values. Price is not float, so we should change this.\n\"\"\"\nfor i in range(data.shape[0]):\n    data[\"Price\"][i]= data[\"Price\"][i][:-2].replace(\",\",\".\")\ndata[\"Price\"]= data[\"Price\"].astype(float)\ndata[\"Price\"]\n\"\"\"\n### Numeric Values Statistics\n\"\"\"\ndata.describe()\n\"\"\"\nSeller ranks are around 9 which is good to know. Prices have high standard deviation 5 turkish lira to 197. \n\"\"\"\n#correlation and visualization\nprint(data.corr())\nsns.regplot(data[\"Price\"], data[\"Seller Rank\"])\nplt.show()\n\"\"\"\nTheir correlation is not high and significant.\n\"\"\"\n#histograms and scatter plots\nsns.pairplot(data)\n\"\"\"\nPrice histogram shows us there is a high price value (an outlier), and the others have less standard deviation without it. We can see this from the boxplot below.\n\"\"\"\nplt.figure(figsize = (6, 4))\nsns.boxplot(data[\"Price\"])\n#printing the outlier's features\nfrom scipy import stats\nz = np.abs(stats.zscore(data[\"Price\"]))\ndata.loc[data[\"Price\"][(z > 2)].index]\ndata.loc[data[\"Price\"][(z < 2)].index][\"Price\"].describe()\n\"\"\"\nThe mean of prices decreased to 20 and the standar deviation decreased from 19 to 9 which is expected.\n\"\"\"\n\"\"\"\n### Price vs Seller Effect\n\"\"\"\ndata2= data[data.Seller.isin(data[\"Seller\"].value_counts().index[:10])]\nplt.figure(figsize = (14, 10))\nax = sns.boxplot(x=\"Seller\", y=\"Price\", data=data2)\nplt.setp(ax.artists, alpha=.5, linewidth=2, edgecolor=\"k\")\nplt.xticks(rotation=45)\n\"\"\"\n### Categorical Features Visualization\n\"\"\"\nsns.barplot(data[\"Author\"].value_counts().index[:10],data[\"Author\"].value_counts().values[:10] )\nplt.xticks(rotation=90)\nplt.grid(alpha=0.2)\nplt.title(\"Authors' Rate\")\nplt.show()\nsns.barplot(data[\"Publisher\"].value_counts().index[:10],data[\"Publisher\"].value_counts().values[:10] )\nplt.xticks(rotation=90)\nplt.grid(alpha=0.2)\nplt.title(\"Publishers' Rate\")\nplt.show()\n\"\"\"\nFor authors and publishers, there is no by far the leading.\n\"\"\"\nsns.barplot(data[\"Seller\"].value_counts().index[:10],data[\"Seller\"].value_counts().values[:10] )\nplt.xticks(rotation=90)\nplt.grid(alpha=0.2)\nplt.title(\"Sellers' Rate\")\nplt.show()\n\"\"\"\nAs we can see, the publisher named \"K\u0131rm\u0131z\u0131 Kedi Kitapevi\" has the majority in all different options.\n\"\"\"\n#let's visualize it\n\na= list(data[\"Seller\"].value_counts().values[:10] \/data.shape[0])\na.append(1-np.sum(list(data[\"Seller\"].value_counts().values[:10] \/data.shape[0])))\nb= list(data[\"Seller\"].value_counts().index[:10])\nb.append(\"Other\")\n\nplt.rcParams[\"figure.figsize\"] = (25,15)\ntheme = plt.get_cmap('hsv')\n\nexplode = (0.1,0,0,0,0,0,0,0,0,0,0)  \n\nfig1, ax1 = plt.subplots()\ntheme = plt.get_cmap('jet')\nax1.set_prop_cycle(\"color\", [theme(1. * i \/ len(a)) for i in range(len(a))])\n\nax1.pie(a, explode=explode, labels=b, autopct='%1.1f%%',\n        shadow=True, startangle=90, textprops={'fontsize': 16})\nax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.\nplt.title(\"Sellers' Total Rate\", fontsize=20)\nplt.show()\n\"\"\"\nConclusion: After analysing all features, authors & publishlers have no dominant one comparing the others. Prices are around 20 turkish liras with 9 standard deviation. Also dataset proved us the most significant thing we see is the seller of books is 'K\u0131rm\u0131z\u0131 Kedi Kitabevi' with %65 possibility. Seller is the feature we should consider about.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8ace67808f63cb'}"}
{"id":"103224","text":"\"\"\"\n# A deep learning of Deep Learning\n![dl.jpeg](attachment:dl.jpeg)\n*Pic Credits: Getty*\n\n**Deep Learning (DL)** is progressing by leaps and bounds at a phenomenally fast pace with so much new research, papers, ideas, models being developed throughout the world. The last few years have seen a lot of solutions being built using deep learning methods and frameworks and this is expected to only increase in the future.\n\nThis notebook analyses the deep learning practitioners from the [2019 Kaggle ML & DS Survey](https:\/\/www.kaggle.com\/c\/kaggle-survey-2019) to understand patterns, get insights, learn challenges and maybe even answer some questions regarding the current and future landscape of deep learning:\n\n* Who are these deep learning practitioners? Are they concentrated in a certain geography or age or background?\n* Are deep learning practitioners very different from other machine learning practitioners? Do they have a different career path or have different salaries?\n* Does deep learning require a lot of money and resources? Are the tools, products and languages used very different requiring special skills?\n* What does the future of deep learning hold for us? Will it significantly change industries or even modeling and solutioning methods?   \n\n...and many more.\n\n**P.S.**: The insights shared in this notebook are based on the 2019 Kaggle Survey data only and not all of them necessarily would be similar in the real world.\n\"\"\"\n\"\"\"\n# Setup\nWe will be using the [2019 Kaggle ML & DS Survey data](https:\/\/www.kaggle.com\/c\/kaggle-survey-2019\/data). Since there is no direct question to flag a person as a DL practitioner or not, we will be using responses to *Q24: Which of the following ML algorithms do you use on a regular basis?* with options:\n- Linear or Logistic Regression\n- Decision Trees or Random Forests\n- Gradient Boosting Machines (xgboost, lightgbm, etc)\n- Bayesian Approaches\n- Evolutionary Approaches\n- **Dense Neural Networks (MLPs, etc)**\n- **Convolutional Neural Networks**\n- **Generative Adversarial Networks**\n- **Recurrent Neural Networks**\n- **Transformer Networks (BERT, gpt-2, etc)**\n\nA DL practitioner is tagged as someone who has selected at least one of the last 5 options. This will be the subset of data used the most.   \nA non-DL practitioner is tagged as someone who has selected at least one of the first 5 options and not selected any of the last 5 options.   \n\nThere are some who have not answered this question or have answered **None** or have answered **Other**. Since there is no concrete information about them to classify correctly, we will be eliminating them for the purpose of this analysis.\n\n![ml-dl.jpg](attachment:ml-dl.jpg)\n\"\"\"\n## importing packages\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport pycountry\n\nfrom bokeh.io import output_notebook, show\nfrom bokeh.layouts import column, row\nfrom bokeh.models import LinearAxis\nfrom bokeh.palettes import Spectral11\nfrom bokeh.plotting import figure\nfrom bokeh.models.ranges import Range1d\n\nfrom plotly import graph_objects as go\n\noutput_notebook()\n\n## reading data\ndf = pd.read_csv(\"\/kaggle\/input\/kaggle-survey-2019\/multiple_choice_responses.csv\", skiprows=[1])\ndf_2018 = pd.read_csv(\"\/kaggle\/input\/kaggle-survey-2018\/freeFormResponses.csv\", skiprows=[1])\n\n## creating numeric feature for salary\ndict_salary = dict({\"$0-999\": 500, \"1,000-1,999\": 1500, \"2,000-2,999\": 2500,\n                    \"3,000-3,999\": 3500, \"4,000-4,999\": 4500, \"5,000-7,499\": 6250,\n                    \"7,500-9,999\": 8750, \"10,000-14,999\": 12500, \"15,000-19,999\": 17500,\n                    \"20,000-24,999\": 22500, \"25,000-29,999\": 27500, \"30,000-39,999\": 35000,\n                    \"40,000-49,999\": 45000, \"50,000-59,999\": 55000, \"60,000-69,999\": 65000,\n                    \"70,000-79,999\": 75000, \"80,000-89,999\": 85000, \"90,000-99,999\": 95000,\n                    \"100,000-124,999\": 112500, \"125,000-149,999\": 137500, \"150,000-199,999\": 175000,\n                    \"200,000-249,999\": 225000, \"250,000-299,999\": 275000, \"300,000-500,000\": 400000,\n                    \"> $500,000\": 500000})\ndf[\"salary\"] = df.Q10.map(dict_salary)\n\n## creating numeric feature for expense\ndict_expense = dict({\"$0 (USD)\": 0, \"$1-$99\": 50, \"$100-$999\": 550, \"$1000-$9,999\": 5500,\n                     \"$10,000-$99,999\": 55000, \"> $100,000 ($USD)\": 100000})\ndf[\"expense\"] = df.Q11.map(dict_expense)\n\n## tagging practitioner types\ndf[\"practitioner_type\"] = \"Non-DL Practitioner\"\ndf.loc[~(df.Q24_Part_6.isna() & df.Q24_Part_7.isna() & df.Q24_Part_8.isna() & df.Q24_Part_9.isna() & df.Q24_Part_10.isna()), \"practitioner_type\"] = \"DL Practitioner\"\ndf.loc[(df.Q24_Part_1.isna() & df.Q24_Part_2.isna() & df.Q24_Part_3.isna() & df.Q24_Part_4.isna() & df.Q24_Part_5.isna() &\n        df.Q24_Part_6.isna() & df.Q24_Part_7.isna() & df.Q24_Part_8.isna() & df.Q24_Part_9.isna() & df.Q24_Part_10.isna()), \"practitioner_type\"] = \"Unknown\"\n\n## splitting dataset by type\ndf_dl = df[df.practitioner_type == \"DL Practitioner\"]\ndf_nondl = df[df.practitioner_type == \"Non-DL Practitioner\"]\ndf_dl_nondl = df[df.practitioner_type != \"Unknown\"]\n\n\"\"\"\nLet's just quickly check the number of practitioners in the final dataset.\n\"\"\"\nv = figure(plot_width = 700, plot_height = 300, x_range = np.unique(df.practitioner_type.values), title = \"Practitioner Distribution\")\nv.vbar(x = np.unique(df.practitioner_type.values), top = df.practitioner_type.value_counts().sort_index().values, width = 0.9, color = Spectral11[1], legend_label = \"# Participants\")\nv.legend.location = \"top_center\"\nv.legend.click_policy = \"hide\"\n\nshow(v)\n\n\"\"\"\nWe have about **7.1K DL practitioners** and **5.7K non-DL practitioners** in the survey. The **remaining 6.9K** will not be used.\n\"\"\"\n\"\"\"\n# 1 Age and Education no bar for Deep Learning!\n\"\"\"\nv = figure(plot_width = 700, plot_height = 300, x_range = np.unique(df_dl.Q1.values), title = \"Age Distribution\")\nv.vbar(x = np.unique(df_dl.Q1.values), top = df_dl.Q1.value_counts().sort_index().values, width = 0.9, color = Spectral11[1], legend_label = \"# DL Practitioners\")\nv.line(np.unique(df_dl.Q1.values), df_dl.Q1.value_counts().sort_index().values * 100 \/ df_dl_nondl.Q1.value_counts().sort_index().values, color = Spectral11[10], legend_label = \"% DL Practitioners\", y_range_name=\"Percentages\")\nv.extra_y_ranges = {\"Percentages\": Range1d(start = 20, end = 80)}\nv.add_layout(LinearAxis(y_range_name = \"Percentages\"), \"right\")\nv.legend.location = \"top_right\"\nv.legend.click_policy = \"hide\"\n\nshow(v)\n\n\"\"\"\n* We see that about **50%-55%** of practitioners in Data Science work in Deep Learning across all age-groups. So whether you are a college student or a working professional or maybe even retired and looking to get your hands into some new technology and innovation, deep learning is independent of age!\n* This resonates with the fact that a lot of successful DL practitioners as well as many top Kagglers are **self-taught** in this field. And something that can be learned through motivation, effort and time has no constraint on age.\n\"\"\"\nv = figure(plot_width = 700, plot_height = 400, x_range = np.unique(df_dl.Q4.values), title = \"Education Distribution\")\nv.vbar(x = np.unique(df_dl.Q4.values), top = df_dl.Q4.value_counts().sort_index().values, width = 0.9, color = Spectral11[1], legend_label = \"# DL Practitioners\")\nv.line(np.unique(df_dl.Q4.values), df_dl.Q4.value_counts().sort_index().values * 100 \/ df_dl_nondl.Q4.value_counts().sort_index().values, color = Spectral11[10], legend_label = \"% DL Practitioners\", y_range_name=\"Percentages\")\nv.extra_y_ranges = {\"Percentages\": Range1d(start = 20, end = 80)}\nv.add_layout(LinearAxis(y_range_name = \"Percentages\"), \"right\")\nv.legend.location = \"top_right\"\nv.legend.click_policy = \"hide\"\nv.xaxis.major_label_orientation = 145\n\nshow(v)\n\n\"\"\"\n* This again clearly shows that there are DL practitioners across varying levels of education (and invariably age too).\n* A lot of this could be due to the fact that the modern research in DL is widely available on the internet leading to the **democratization of information**.\n\n> Deep Learning is for anyone and everyone\n\"\"\"\n\"\"\"\n# 2 Gender Inequality\n\"\"\"\nv = figure(plot_width = 700, plot_height = 300, x_range = np.unique(df_dl.Q2.values), title = \"Gender Distribution\")\nv.vbar(x = np.unique(df_dl.Q2.values), top = df_dl.Q2.value_counts().sort_index().values, width = 0.9, color = Spectral11[8], legend_label = \"# DL Practitioners\")\nv.line(np.unique(df_dl.Q2.values), df_dl.Q2.value_counts().sort_index().values * 100 \/ df_dl_nondl.Q2.value_counts().sort_index().values, color = Spectral11[1], legend_label = \"% DL Practitioners\", y_range_name=\"Percentages\")\nv.extra_y_ranges = {\"Percentages\": Range1d(start = 20, end = 80)}\nv.add_layout(LinearAxis(y_range_name = \"Percentages\"), \"right\")\nv.legend.location = \"top_right\"\nv.legend.click_policy = \"hide\"\n\nshow(v)\n\n\"\"\"\n* There is a clear gap between the **43% of females** vs **57% of males** in Data Science who work in Deep Learning. But, the number of female respondants to the survey are much lower than men and this percentage may not be very reliable.\n* You could also go through the [Geek Girls Rising notebook](https:\/\/www.kaggle.com\/parulpandey\/geek-girls-rising-myth-or-reality) that explores the female responses in detail by [Parul Pandey](https:\/\/www.kaggle.com\/parulpandey).\n\n> A balanced ensemble of females and males can lead to wonders\n\"\"\"\n\"\"\"\n# 3 Egypt, Iran and Romania rise as unexpected winners\n\"\"\"\n## mapping country codes\ndef get_country_code(country_name):\n    \"\"\"\n    Mapping country name to 3-digit country code.\n    \"\"\"\n    \n    if country_name == \"Russia\":\n        country_name = \"Russian Federation\"\n    if country_name == \"South Korea\":\n        country_name = \"Korea, Republic of\"\n    if country_name == \"Hong Kong (S.A.R.)\":\n        country_name = \"Hong Kong\"\n    if country_name == \"Taiwan\":\n        country_name = \"Taiwan, Province of China\"    \n    if country_name == \"Republic of Korea\":\n        country_name = \"Democratic People's Republic of Korea\"\n    if country_name == \"Iran, Islamic Republic of...\":\n        country_name = \"Iran, Islamic Republic of\"\n    \n    country_data = pycountry.countries.get(name=country_name)\n    \n    if country_data is None:\n        country_data = pycountry.countries.get(official_name=country_name)\n    \n    if country_data is None:\n        return np.nan\n    return country_data.alpha_3\n\ndf_dl_country = pd.DataFrame(df_dl.Q3.value_counts()).reset_index().rename(columns={\"index\": \"country\", \"Q3\": \"dl_count\"})\ndf_dl_country[\"country_code\"] = df_dl_country.country.apply(lambda x: get_country_code(x))\n\nf = go.Figure(data=go.Choropleth(\n    locations=df_dl_country.country_code,\n    z=df_dl_country.dl_count,\n    locationmode=\"ISO-3\",\n    text=df_dl_country.country,\n    colorscale=\"Blues\",\n    autocolorscale=False,\n    marker_line_width=0.5,\n    colorbar_tickprefix=\"#\",\n    colorbar_title=\"# DL Practitioners\"\n))\n\nf.update_layout(\n    title={\n        \"text\": \"Global # DL Practitioners\",\n        \"y\":0.9,\n        \"x\":0.475,\n        \"xanchor\": \"center\",\n        \"yanchor\": \"top\"}\n)\n\nf.show()\n\"\"\"\nThe top-10 countries with largest number of DL practitioners:\n\"\"\"\ndf_dl_country.sort_values(\"dl_count\", ascending=False).head(10)\n\"\"\"\n* **India, US, Japan, Brazil and China**, the usual suspects, lead the list of DL practitioners. It is very intuitive and expected due to the population of the countries and corresponding number of active users on Kaggle.\n\nInstead, let's look at the % of DL practitioners within each country among those in Data Science. The results are very different.\n\"\"\"\ndf_dl_nondl_country = pd.DataFrame(df_dl_nondl.Q3.value_counts()).reset_index().rename(columns={\"index\": \"country\", \"Q3\": \"dl_nondl_count\"})\ndf_dl_nondl_country[\"country_code\"] = df_dl_nondl_country.country.apply(lambda x: get_country_code(x))\ndf_dl_nondl_country = df_dl_nondl_country.merge(df_dl_country[[\"country_code\", \"dl_count\"]], how=\"left\", on=\"country_code\")\ndf_dl_nondl_country[\"dl_percentage\"] = round(df_dl_nondl_country.dl_count * 100 \/ df_dl_nondl_country.dl_nondl_count)\n\nf = go.Figure(data=go.Choropleth(\n    locations=df_dl_nondl_country.country_code,\n    z=df_dl_nondl_country.dl_percentage,\n    locationmode=\"ISO-3\",\n    text=df_dl_nondl_country.country,\n    colorscale=\"Blues\",\n    autocolorscale=False,\n    marker_line_width=0.5,\n    colorbar_ticksuffix=\"%\",\n    colorbar_title=\"% DL Practitioners\"\n))\n\nf.update_layout(\n    title={\n        \"text\": \"Global % DL Practitioners\",\n        \"y\":0.9,\n        \"x\":0.475,\n        \"xanchor\": \"center\",\n        \"yanchor\": \"top\"}\n)\n\nf.show()\n\"\"\"\nThe top-10 countries with largest proportion of DL practitioners among those in Data Science:\n\"\"\"\ndf_dl_nondl_country.sort_values(\"dl_percentage\", ascending=False).head(10)\n\"\"\"\n* **Egypt! \ud83c\uddea\ud83c\uddec Iran! \ud83c\uddee\ud83c\uddf7 Romania! \ud83c\uddf7\ud83c\uddf4** A large proportion of practitioners in Data Science in these countries are working in Deep Learning. Looking at the top-10 list, there are many unexpected names. It is wonderful to see DL being adopted in so many countries across continents.\n* If we consider at least 100 respondants to Q24 from a country to be reliable enough data, we have **Taiwan \ud83c\uddf9\ud83c\uddfc, China \ud83c\udde8\ud83c\uddf3 and Turkey \ud83c\uddf9\ud83c\uddf7** who have the largest proportion of DL practitioners.\n* Just for comparison, India has 56% and US has 48% and they are much lower in the list.\n\n> You might want to relocate to Egypt if you are a DL enthusiast.\n\"\"\"\n\"\"\"\n# 4 Research and Engineering are the recipes for Deep Learning\n\"\"\"\ndf_dl_role = pd.DataFrame(df_dl.Q5.value_counts()).reset_index().rename(columns={\"index\": \"Role\", \"Q5\": \"dl_count\"})\ndf_dl_nondl_role = pd.DataFrame(df_dl_nondl.Q5.value_counts()).reset_index().rename(columns={\"index\": \"Role\", \"Q5\": \"dl_nondl_count\"})\n\ndf_dl_role = df_dl_role.merge(df_dl_nondl_role)\ndf_dl_role[\"dl_percentage\"] = df_dl_role.dl_count * 100 \/ df_dl_role.dl_nondl_count\ndf_dl_role.sort_values(\"dl_percentage\", ascending=False, inplace=True)\n\nf = figure(x_range=df_dl_role.Role.values, plot_width=700, plot_height=300, title=\"Role Distribution\")\nf.vbar(x=df_dl_role.Role.values, top=df_dl_role.dl_count.values, width=0.9, color=Spectral11[9], legend_label=\"# DL Practitioners\")\nf.line(df_dl_role.Role.values, df_dl_role.dl_percentage.values, color=Spectral11[1], legend_label=\"% DL Practitioners\", y_range_name=\"Percentages\")\nf.extra_y_ranges = {\"Percentages\": Range1d(start=20, end=80)}\nf.add_layout(LinearAxis(y_range_name=\"Percentages\"), \"right\")\nf.legend.location=\"top_right\"\nf.legend.click_policy=\"hide\"\nf.xaxis.major_label_orientation=145\nshow(f)\n\"\"\"\n* Deep Learning requires a lot of research and implementation and the plot above is a great confirmation of the same. People in roles of **Research Scientist, Software Engineer and Data Scientist** are almost twice as likely **(>60%)** to be working in DL compared to those in roles of **Business Analyst, Statistician and Data Analyst (~35%)**.\n* In today's world, most DL projects in the industry require skills of research as well engineering together for success. Defining, transforming and pipelining a data science problem into a deep learning framework is as important and crucial as implementing, productionizing and solutioning of the problem. They go hand-in-hand like two sides of a coin.\n\n> Deep Learning has to be learnt and done hands-on\n\"\"\"\n\"\"\"\n# 5 Income and Expenses don't change\n\"\"\"\nimport seaborn as sns\nf = sns.FacetGrid(df_dl_nondl, col=\"practitioner_type\")\nf.map(plt.hist, \"salary\")\nf.add_legend()\nplt.show()\nbp = sns.boxplot(x=\"practitioner_type\", y=\"salary\", data=df_dl_nondl, palette=\"Set2\").set_title(\"Salary Distribution\")\nimport seaborn as sns\nf = sns.FacetGrid(df_dl_nondl, col=\"practitioner_type\")\nf.map(plt.hist, \"expense\")\nf.add_legend()\nplt.show()\nbp = sns.boxplot(x=\"practitioner_type\", y=\"expense\", data=df_dl_nondl, palette=\"Set3\").set_title(\"Expense Distribution\")\n\"\"\"\n* The salary distribution as well as the statistical measures like mean, median, quartiles and variance are almost identical between DL practitioners and non-DL practitioners.\n* The expenses made for work has a very similar distribution as well.\n\n> Deep Learning is for the passionate\n\"\"\"\n\"\"\"\n# 6 Blogs, Coursera and YouTube are a goldmine of information\n\"\"\"\nmedia_list = {\n    \"Twitter\": sum(~df_dl.Q12_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"HackerNews\": sum(~df_dl.Q12_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"Reddit\": sum(~df_dl.Q12_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"Kaggle\": sum(~df_dl.Q12_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"Forums\": sum(~df_dl.Q12_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"YouTube\": sum(~df_dl.Q12_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Podcasts\": sum(~df_dl.Q12_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"Blogs\": sum(~df_dl.Q12_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"Journals\": sum(~df_dl.Q12_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"Slack\": sum(~df_dl.Q12_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q12_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q12_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_media = pd.DataFrame.from_dict(media_list, orient=\"index\", columns=[\"media_percentage\"]).reset_index().rename(columns={\"index\": \"media\"})\ndf_dl_media.sort_values(\"media_percentage\", ascending=False, inplace=True)\n\nplatform_list = {\n    \"Udacity\": sum(~df_dl.Q13_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"Coursera\": sum(~df_dl.Q13_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"edX\": sum(~df_dl.Q13_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"DataCamp\": sum(~df_dl.Q13_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"DataQuest\": sum(~df_dl.Q13_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"Kaggle\": sum(~df_dl.Q13_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Fast.ai\": sum(~df_dl.Q13_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"Udemy\": sum(~df_dl.Q13_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"LinkedIn\": sum(~df_dl.Q13_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"University\": sum(~df_dl.Q13_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q13_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q13_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_platform = pd.DataFrame.from_dict(platform_list, orient=\"index\", columns=[\"platform_percentage\"]).reset_index().rename(columns={\"index\": \"platform\"})\ndf_dl_platform.sort_values(\"platform_percentage\", ascending=False, inplace=True)\n\nf1 = figure(x_range=df_dl_media.media, plot_width=700, plot_height=400, title=\"Media Distribution\")\nf1.vbar(x=df_dl_media.media, top=df_dl_media.media_percentage, width=0.9, color=Spectral11[6], legend_label=\"% Media Usage\")\nf1.legend.location=\"top_right\"\nf1.legend.click_policy=\"hide\"\nf1.xaxis.major_label_orientation=145\n\nf2 = figure(x_range=df_dl_platform.platform, plot_width=700, plot_height=400, title=\"Platform Distribution\")\nf2.vbar(x=df_dl_platform.platform, top=df_dl_platform.platform_percentage, width=0.9, color=Spectral11[6], legend_label=\"% Platform Usage\")\nf2.legend.location=\"top_right\"\nf2.legend.click_policy=\"hide\"\nf2.xaxis.major_label_orientation=145\n\nshow(column(f1, f2))\n\"\"\"\n* Let's ignore the Kaggle bars since these are already biased with Kaggle users. **~65% of DL practitioners read blogs, followed by ~60% who do Coursera courses**. And why not? Both are extremely rich sources of information and a lot of the latest developments in DL are shared and discussed here.\n* [Andrew Ng](https:\/\/en.wikipedia.org\/wiki\/Andrew_Ng), one of the biggest figures in AI co-founded [Coursera](https:\/\/www.coursera.org\/) and as of 2019, the two most popular courses on the platform is, without surprise, [Machine Learning](https:\/\/www.coursera.org\/learn\/machine-learning) and [Deep Learning](https:\/\/www.coursera.org\/learn\/neural-networks-deep-learning). Well, of course everyone is going to be on Coursera!\n* It is probably one of the first set of material that any DL practitioner should study.\n\n> Knowledge is power\n\"\"\"\n\"\"\"\n# 7 The deadly combo of Jupyter + Colab + Python\n\"\"\"\nide_list = {\n    \"Jupyter\": sum(~df_dl.Q16_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"RStudio\": sum(~df_dl.Q16_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"PyCharm\": sum(~df_dl.Q16_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"Atom\": sum(~df_dl.Q16_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"MATLAB\": sum(~df_dl.Q16_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"VisualStudio\": sum(~df_dl.Q16_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Spyder\": sum(~df_dl.Q16_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"Vim\": sum(~df_dl.Q16_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"Notepad++\": sum(~df_dl.Q16_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"SublimeText\": sum(~df_dl.Q16_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q16_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q16_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_ide = pd.DataFrame.from_dict(ide_list, orient=\"index\", columns=[\"ide_percentage\"]).reset_index().rename(columns={\"index\": \"ide\"})\ndf_dl_ide.sort_values(\"ide_percentage\", ascending=False, inplace=True)\n\nnotebook_list = {\n    \"KaggleNotebooks\": sum(~df_dl.Q17_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"GoogleColab\": sum(~df_dl.Q17_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"MicrosoftAzureNotebooks\": sum(~df_dl.Q17_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"GoogleCloudNotebooks\": sum(~df_dl.Q17_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"Paperspace\/Gradient\": sum(~df_dl.Q17_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"FloydHub\": sum(~df_dl.Q17_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Binder\/JupyterHub\": sum(~df_dl.Q17_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"IBMWatsonStudio\": sum(~df_dl.Q17_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"CodeOcean\": sum(~df_dl.Q17_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"AWSNotebooks\": sum(~df_dl.Q17_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q17_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q17_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_notebook = pd.DataFrame.from_dict(notebook_list, orient=\"index\", columns=[\"notebook_percentage\"]).reset_index().rename(columns={\"index\": \"notebook\"})\ndf_dl_notebook.sort_values(\"notebook_percentage\", ascending=False, inplace=True)\n\nlanguage_list = {\n    \"Python\": sum(~df_dl.Q18_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"R\": sum(~df_dl.Q18_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"SQL\": sum(~df_dl.Q18_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"C\": sum(~df_dl.Q18_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"C++\": sum(~df_dl.Q18_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"Java\": sum(~df_dl.Q18_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Javascript\": sum(~df_dl.Q18_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"TypeScript\": sum(~df_dl.Q18_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"Bash\": sum(~df_dl.Q18_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"MATLAB\": sum(~df_dl.Q18_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q18_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q18_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_language = pd.DataFrame.from_dict(language_list, orient=\"index\", columns=[\"language_percentage\"]).reset_index().rename(columns={\"index\": \"language\"})\ndf_dl_language.sort_values(\"language_percentage\", ascending=False, inplace=True)\n\nf1 = figure(x_range=df_dl_ide.ide, plot_width=700, plot_height=400, title=\"IDE Distribution\")\nf1.vbar(x=df_dl_ide.ide, top=df_dl_ide.ide_percentage, width=0.9, color=Spectral11[3], legend_label=\"% IDE Usage\")\nf1.legend.location=\"top_right\"\nf1.legend.click_policy=\"hide\"\nf1.xaxis.major_label_orientation=145\n\nf2 = figure(x_range=df_dl_notebook.notebook, plot_width=700, plot_height=400, title=\"Notebook Distribution\")\nf2.vbar(x=df_dl_notebook.notebook, top=df_dl_notebook.notebook_percentage, width=0.9, color=Spectral11[3], legend_label=\"% Notebook Usage\")\nf2.legend.location=\"top_right\"\nf2.legend.click_policy=\"hide\"\nf2.xaxis.major_label_orientation=145\n\nf3 = figure(x_range=df_dl_language.language, plot_width=700, plot_height=400, title=\"Language Distribution\")\nf3.vbar(x=df_dl_language.language, top=df_dl_language.language_percentage, width=0.9, color=Spectral11[3], legend_label=\"% Language Usage\")\nf3.legend.location=\"top_right\"\nf3.legend.click_policy=\"hide\"\nf3.xaxis.major_label_orientation=145\n\nshow(column(f1, f2, f3))\n\"\"\"\n* The numbers say it all. A whopping **>95% of DL practitioners use Python**, and combined with **>80% of Jupyter** and **>40% of Colab**, these easily form the most popular and convenient set of tools available today.\n* Almost every popular library in DL is based in Python so the 5% folks who are not Python users might be missing the bus.\n\n> Using the latest and best can give an upper edge\n\"\"\"\n\"\"\"\n# 8 GPU usage on the rise\n\"\"\"\nhardware_list = {\n    \"CPUs\": sum(~df_dl.Q21_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"GPUs\": sum(~df_dl.Q21_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"TPUs\": sum(~df_dl.Q21_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q21_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q21_Part_5.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_hardware = pd.DataFrame.from_dict(hardware_list, orient=\"index\", columns=[\"hardware_percentage\"]).reset_index().rename(columns={\"index\": \"hardware\"})\ndf_dl_hardware.sort_values(\"hardware_percentage\", ascending=False, inplace=True)\n\nmodel_list = {\n    \"DenseNN\": sum(~df_dl.Q24_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"CNN\": sum(~df_dl.Q24_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"GAN\": sum(~df_dl.Q24_Part_8.isna()) * 100 \/ df_dl.shape[0],\n    \"RNN\": sum(~df_dl.Q24_Part_9.isna()) * 100 \/ df_dl.shape[0],\n    \"TransformerNetworks\": sum(~df_dl.Q24_Part_10.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q24_Part_11.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q24_Part_12.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_model = pd.DataFrame.from_dict(model_list, orient=\"index\", columns=[\"model_percentage\"]).reset_index().rename(columns={\"index\": \"model\"})\ndf_dl_model.sort_values(\"model_percentage\", ascending=False, inplace=True)\n\ntool_list = {\n    \"AutoAugmentation\": sum(~df_dl.Q25_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"AutoFeatureSelection\": sum(~df_dl.Q25_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"AutoModelSelection\": sum(~df_dl.Q25_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"AutoModelArchitectureSearch\": sum(~df_dl.Q25_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"AutoHyperparameterTuning\": sum(~df_dl.Q25_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"AutoML\": sum(~df_dl.Q25_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q25_Part_7.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q25_Part_8.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_tool = pd.DataFrame.from_dict(tool_list, orient=\"index\", columns=[\"tool_percentage\"]).reset_index().rename(columns={\"index\": \"tool\"})\ndf_dl_tool.sort_values(\"tool_percentage\", ascending=False, inplace=True)\n\nf1 = figure(x_range=df_dl_hardware.hardware, plot_width=700, plot_height=400, title=\"Hardware Distribution\")\nf1.vbar(x=df_dl_hardware.hardware, top=df_dl_hardware.hardware_percentage, width=0.9, color=Spectral11[0], legend_label=\"% Hardware Usage\")\nf1.legend.location=\"top_right\"\nf1.legend.click_policy=\"hide\"\nf1.xaxis.major_label_orientation=145\n\nf2 = figure(x_range=df_dl_model.model, plot_width=700, plot_height=400, title=\"Model Distribution\")\nf2.vbar(x=df_dl_model.model, top=df_dl_model.model_percentage, width=0.9, color=Spectral11[0], legend_label=\"% Model Usage\")\nf2.legend.location=\"top_right\"\nf2.legend.click_policy=\"hide\"\nf2.xaxis.major_label_orientation=145\n\nf3 = figure(x_range=df_dl_tool.tool, plot_width=700, plot_height=400, title=\"Tool Distribution\")\nf3.vbar(x=df_dl_tool.tool, top=df_dl_tool.tool_percentage, width=0.9, color=Spectral11[0], legend_label=\"% Tool Usage\")\nf3.legend.location=\"top_right\"\nf3.legend.click_policy=\"hide\"\nf3.xaxis.major_label_orientation=145\n\nshow(column(f1, f2, f3))\n\"\"\"\n* The GPU usage is close to the CPU usage due to the fact that running DL models can require a **lot of computing power** and GPUs help in scaling horizontally.\n* **CNN is the most popular model** used by DL practitioners.\n* AutoML techniques are widely used for structured data without DL models. They are not yet mature to deal with data that is unstructured and to automatically work with DL methods and architectures.\n\n> Upgrading to GPU is worth it\n\"\"\"\n\"\"\"\n# 9 CNN breakthrough in Image Classification\n\"\"\"\ncv_list = {\n    \"Regular Methods\": sum(~df_dl.Q26_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"Image Segmentation\": sum(~df_dl.Q26_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"Object Detection\": sum(~df_dl.Q26_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"Image Classification\": sum(~df_dl.Q26_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"Image Generation\": sum(~df_dl.Q26_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q26_Part_6.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q26_Part_7.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_cv = pd.DataFrame.from_dict(cv_list, orient=\"index\", columns=[\"cv_percentage\"]).reset_index().rename(columns={\"index\": \"cv\"})\ndf_dl_cv.sort_values(\"cv_percentage\", ascending=False, inplace=True)\n\nf = figure(x_range=df_dl_cv.cv, plot_width=700, plot_height=400, title=\"Computer Vision techniques Distribution\")\nf.vbar(x=df_dl_cv.cv, top=df_dl_cv.cv_percentage, width=0.9, color=Spectral11[8], legend_label=\"% Computer Vision techniques Usage\")\nf.legend.location=\"top_right\"\nf.legend.click_policy=\"hide\"\nf.xaxis.major_label_orientation=145\n\nshow(f)\n\"\"\"\n* One of the biggest use-cases of DL models in the industry is on image\/video data. With the ability to process raw pixel data of images to build solutions that are capable of matching human performance and even beating it in some cases, **Image Classification** is making breakthroughs in many ways.\n* Earlier we saw CNN as the most popular algorithm being used and not surprisingly, **CNNs** are also the most frequent method used for image classification problems.\n* **Image Segmentation** and **Object Detection** are slowly but surely catching up. They are a bit more complex in nature, but the annual [Open Images](https:\/\/opensource.google\/projects\/open-images-dataset) dataset and competition on Kaggle is helping its development.\n\n> DL models are improving with every passing day\n\"\"\"\n\"\"\"\n# 10 A new era of NLP is coming\n\"\"\"\nnlp_list = {\n    \"Word Embeddings\": sum(~df_dl.Q27_Part_1.isna()) * 100 \/ df_dl.shape[0],\n    \"Sequence Models\": sum(~df_dl.Q27_Part_2.isna()) * 100 \/ df_dl.shape[0],\n    \"Contextualized Embeddings\": sum(~df_dl.Q27_Part_3.isna()) * 100 \/ df_dl.shape[0],\n    \"Language Models\": sum(~df_dl.Q27_Part_4.isna()) * 100 \/ df_dl.shape[0],\n    \"None\": sum(~df_dl.Q27_Part_5.isna()) * 100 \/ df_dl.shape[0],\n    \"Other\": sum(~df_dl.Q27_Part_6.isna()) * 100 \/ df_dl.shape[0]\n}\n\ndf_dl_nlp = pd.DataFrame.from_dict(nlp_list, orient=\"index\", columns=[\"nlp_percentage\"]).reset_index().rename(columns={\"index\": \"nlp\"})\ndf_dl_nlp.sort_values(\"nlp_percentage\", ascending=False, inplace=True)\n\nf = figure(x_range=df_dl_nlp.nlp, plot_width=700, plot_height=400, title=\"NLP techniques Distribution\")\nf.vbar(x=df_dl_nlp.nlp, top=df_dl_nlp.nlp_percentage, width=0.9, color=Spectral11[8], legend_label=\"% NLP techniques Usage\")\nf.legend.location=\"top_right\"\nf.legend.click_policy=\"hide\"\nf.xaxis.major_label_orientation=145\n\nshow(f)\n\"\"\"\n* Word Embeddings like **TFIDF, Word2Vec and Glove** were the go-to approaches when working on NLP problems and are still being used. But a lot has changed in recent years.\n* Language models like **BERT, XLNET and GPT-2** are models that are performing exceptionally well on various problems using textual data. These are new and it's adoption is expected to increase in the coming years.\n* One of the drawbacks of the newer language models are it's scoring latency which might be a reason it may not easily be adopted in real-time production systems. This could improve in the future too.\n\n> NLP models are understanding human languages better\n\"\"\"\n\"\"\"\n# Overall Summary\nWe've seen a variety of outputs for Deep Learning practitioners through slicing\/dicing of the data with numerous comparisons, results, questions and probable reasonings. Here's a summary of the key insights:\n\n* **Deep Learning is everywhere:** Deep Learning is being practised across ages, education levels and geographies. Egypt, Iran and Romania have the highest proportion of DL practitioners among those building Data Science models.\n* **Male Dominance:** Females have lower participation and prominence than men. Having more data to support or accept this is required.\n* **Research + Engineering ensemble:** Research and Engineering are strongly correlated to working in the DL space. These areas of expertise are the essential components for building successing solutions in the industry.\n* **Passion not Money:** Salary and Expenditure is consistent irrespective of the type of work.\n* **Online Content:** Blogs, Coursera and YouTube are the top-3 sources that are used by DL practitioners. A lot of the latest content is available at these online sources and most for free.\n* **Python all the way:** Python is and seems to be the favourite language of DL practitioners. And it doesn't seem to be changing anytime soon.\n* **Computing power:** GPUs are becoming a dire need for running DL models. TPUs haven't yet reached the scale of availability and adoption compared to GPUs. It will take time to establish a set of libraries and a community that can help run many of the DL workflows.\n* **Unstructured Victories:** CNNs made a big breakthrough in image processing and since then DL has been widely used to solve computer vision problems. New pre-trained language models like BERT that use transformer architecture are making waves recently due to their improved performance over traditional approaches. These are expected to be adopted more especially if it's scoring latency can be enhanced.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'bdad4fac56a701'}"}
{"id":"3381","text":"\"\"\"\nHi, guys.\n\nThis is my first join the Kaggle competition and write code in python (I used R before, and my best score in this competition also is made by R). So, I hope you all can help me to correct my error and misunderstanding of any concept and process (especially the stacking ensemble part).\n\nIn this note book, I try to roughly implement the whole workflow. here is the composition of my code:\n\n[1]. import and load data\n\n[2]. Data Cleansing \n\n[3]. EDA\n\n[4]. Feature Engineering\n\n[5]. Modeling selection \n\n[6]. Ensemble Generation\n\n\nHere is a wired question I find: in the grid search part, I use 'random_state' or 'seed' to control the Randomness, but I find the best parameter is lightly different each time.\n\"\"\"\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\n\n# load data set\ndf_train = pd.read_csv('..\/input\/titanic\/train.csv')\ndf_train.head()\ndf_test = pd.read_csv('..\/input\/titanic\/test.csv')\ndf_test.head()\n# remove the \"Survived\" column in \"df_train\" and join bind two sets\ndf = pd.concat([df_train.drop(\"Survived\", axis=1), df_test])\ndf.head()\n# remove all string columns: \"Name\", \"Ticket\", \"Cabin\"\ndf = df.drop([\"Name\", \"Ticket\", \"Cabin\"], axis = 1)\ndf.head()\n\"\"\"\n# Data Cleansing\n\"\"\"\n# check missing value\ndf.isna().sum()\n# deal with NA in Age\ndf[df.Age.isna()]\n# there are many rows contain NA in Age columns and I use the median Age to replace the NA\ndf.Age = df.Age.fillna(df.Age.median())\n\n# deal with NA in Fare\ndf[df.Fare.isna()]\n# it is a 3th class passenger and there is strongly relationship between Fare and Class,so I use the mean(Fare) in 3th class to replace the missing value\ndf.Fare = df.Fare.fillna(df.Fare[df.Pclass ==3].median())\n\n# deal with NA in Embarked\ndf[df.Embarked.isna()]\n# the Embarked is independent, so I use mode to replace the NA\ndf.Embarked = df.Embarked.fillna(df.Embarked.mode()[0])\n# check missing value again\ndf.isna().sum()\n# update the df_train\ndf_train.Age = df.Age[0:len(df_train)]\ndf_train.Fare = df.Fare[0:len(df_train)]\ndf_train.Embarked = df.Embarked[0:len(df_train)]\n\"\"\"\n# EDA\nIn the EDA part, I have two tasks:\n\nFirst, check all variables' distribution.\n\nSecond, check the relationship between survived and other variables in df_train\n\"\"\"\n# Pclass\nind = list(set(df.Pclass))\ncount = df.groupby(\"Pclass\").count().Sex\ncount0 = df_train[df_train.Survived == 0].groupby(\"Pclass\").count().Sex\ncount1 = df_train[df_train.Survived == 1].groupby(\"Pclass\").count().Sex\n\n# distrubition\nplt.bar(ind, count)\nplt.ylim(0,750)\nplt.show()\n\n# relationship\np0 = plt.bar(ind, count0)\np1 = plt.bar(ind, count1, bottom = count0)\nplt.ylim(0,750)\nplt.legend((p0[0], p1[0]), ('Not Survived','Survived'))\nplt.show()\n# Sex\nind = sorted(list(set(df.Sex)))\ncount = df.groupby(\"Sex\").count().Pclass\ncount0 = df_train[df_train.Survived == 0].groupby(\"Sex\").count().Survived\ncount1 = df_train[df_train.Survived == 1].groupby(\"Sex\").count().Survived\n\n# distrubition\nplt.bar(ind, count)\nplt.ylim(0,900)\nplt.show()\n\n# relationship\np0 = plt.bar(ind, count0)\np1 = plt.bar(ind, count1, bottom = count0)\nplt.ylim(0,900)\nplt.legend((p0[0], p1[0]), ('Not Survived','Survived'))\nplt.show()\n# Age\n#distribution\nplt.boxplot(df.Age)\nplt.show()\n\n#relationship\np0 = plt.hist(df_train.Age[df_train.Survived == 0], width = 5, alpha = 0.5)\np1 = plt.hist(df_train.Age[df_train.Survived == 1], width = 5, alpha = 0.5)\nplt.legend(('Not Survived','Survived'))\nplt.show()\n# SibSp\nind = list(set(df.SibSp))\ncount = df.groupby(\"SibSp\").count().Pclass\n\n# distrubition\nplt.bar(ind, count)\nplt.ylim(0,900)\nplt.show()\n\n# relationship\nsib = df_train.groupby(['SibSp','Survived']).agg(total=('Pclass', 'size'))\nsib[\"Percentage\"] = sib \/ sib.groupby(level=0).sum() *100\nsib\n# Parch\nind = list(set(df.Parch))\ncount = df.groupby(\"Parch\").count().Pclass\n\n# distrubition\nplt.bar(ind, count)\nplt.ylim(0,900)\nplt.show()\n\n# relationship\npar = df_train.groupby(['Parch','Survived']).agg(total=('Pclass', 'size'))\npar[\"Percentage\"] = par \/ par.groupby(level=0).sum() *100\npar\n# Fare\n#distribution\nplt.boxplot(df.Fare)\nplt.show()\n\n#relationship\np1 = plt.hist(df_train.Fare[df_train.Survived == 0], bins = 20, alpha = 0.5)\np2 = plt.hist(df_train.Fare[df_train.Survived == 1], bins = 20, alpha = 0.5)\nplt.legend(('Not Survived','Survived'))\nplt.show()\n# Embarked\nind = sorted(list(set(df.Embarked)))\ncount = df.groupby(\"Embarked\").count().Pclass\ncount0 = df_train[df_train.Survived == 0].groupby(\"Embarked\").count().Survived\ncount1 = df_train[df_train.Survived == 1].groupby(\"Embarked\").count().Survived\n\n# distrubition\nplt.bar(ind, count)\nplt.ylim(0,900)\nplt.show()\n\n# relationship\np0 = plt.bar(ind, count0)\np1 = plt.bar(ind, count1, bottom = count0)\nplt.ylim(0,900)\nplt.legend((p0[0], p1[0]), ('Not Survived','Survived'))\nplt.show()\n\"\"\"\n# Feature Engineering\n\"\"\"\n#Encode Features\n#Sex 0: female, 1: male\ndf.Sex = df.Sex.replace(\"female\", 0)\ndf.Sex = df.Sex.replace(\"male\", 1)\n\n#Embarked 0:C, 1:Q, 2:S\ndf.Embarked = df.Embarked.replace(\"C\",0)\ndf.Embarked = df.Embarked.replace(\"Q\",1)\ndf.Embarked = df.Embarked.replace(\"S\",2)\n#genearate dummy variables for Pclass, SibSp, Parch, and Embarked\ndf_dummy = pd.get_dummies(df, columns = ['Pclass', 'SibSp', 'Parch', 'Embarked'])\n# create train and test sets\ntrain_x = df_dummy[0:len(df_train)]\ntrain_y = df_train.Survived\ntrain_x\n# check the feature inportance by randomforest\nmodel_rf = RandomForestRegressor()\nmodel_rf.fit(train_x, train_y)\n\nind =  model_rf.feature_importances_.argsort()\nplt.barh(train_x.columns[ind], model_rf.feature_importances_[ind])\n# some Prach and SibSp dummy variables are low importance and only exist in the train set or test set. So, I plan to encode them and reduce the number of feature\n# in SibSp, 0: 0 ,1: 1, 2: 2+\n# in Parch, 0: 0, 1: 1, 2: 2+\ndf.loc[df.SibSp >= 2, 'SibSp'] = 2\ndf.loc[df.Parch >= 2, 'Parch'] = 2\n\ndf.head()\n#repeat. geneate dummy variables and create train and test sets\ndf_dummy = pd.get_dummies(df, columns = ['Pclass', 'SibSp', 'Parch', 'Embarked'])\n\n# create train and test sets\ntrain_x = df_dummy[0:len(df_train)]\ntrain_y = df_train.Survived\ntest_x = df_dummy[len(df_train):]\n\"\"\"\n# Model Selection\n\"\"\"\n# model list used in this case\nmodels = [\"Random Forest\", \"Xgboost\", \"Extra Randomized Trees\"]\nscores = []\n# Grid Search\n# Random Forset\ngrid_rf = {\n    \"n_estimators\": np.linspace(100,1000,5, dtype = int),\n    \"max_depth\": [3,5,7],\n    \"max_features\": [2,3,4,5,6,7,8,9],\n    \"min_samples_leaf\": [3,5,7],\n    \"min_samples_split\":[3,5,7],\n    \"random_state\": [2020,2021]\n}\n\nmodel_rf = RandomForestClassifier()\nsearch_rf = GridSearchCV(estimator = model_rf, \n                         param_grid = grid_rf, \n                         cv = 5,\n                         n_jobs = -1,\n                         verbose = 2)\n# do not run this code in your local PC, it is time consuming\nsearch_rf.fit(train_x, train_y)\n# find the best parameters\nbest_rf = search_rf.best_params_\nbest_rf\n# it seems RandomForestRegressor cannot accept the dict type parameters, so I have to rewrite the best parameters\nfinal_rf =  RandomForestClassifier(**best_rf)\nfinal_rf.fit(train_x, train_y)\npred_rf = final_rf.predict(test_x)\npred_rf\n# Xgboost\ngrid_xgb = {\n    'booster': ['gbtree', 'gblinear'],\n    'objective': ['binary:logistic'],\n    'subsample': [0.6,0.7,0.8,0.9],\n    'colsample_bytree': [0.6,0.7,0.8,0.9],\n    'eta': [0.05,0.1,0.2,0.3],\n    'max_depth': [3,5,7],\n    'seed': [2021,2022],\n    'eval_metric': ['logloss']\n}\n\n\nmodel_xgb = xgb.XGBClassifier()\nsearch_xgb = GridSearchCV(estimator = model_xgb, \n                         param_grid = grid_xgb, \n                         cv = 5,\n                         n_jobs = -1,\n                         verbose = 2)\n# do not run this code in your local PC, it is time consuming\nsearch_xgb.fit(train_x, train_y)\n# find the best parameters\nbest_xgb = search_xgb.best_params_\nbest_xgb\n# final xgboost model\nfinal_xgb = xgb.XGBClassifier(**best_xgb)\nfinal_xgb.fit(train_x, train_y)\npred_xgb = final_xgb.predict(test_x)\npred_xgb\n# Extra Randomized Trees. this part is very simular with random forest, so I copy my code to here\ngrid_ert = {\n    \"n_estimators\": np.linspace(100,1000,5, dtype = int),\n    \"max_depth\": [3,5,7],\n    \"max_features\": [2,3,4,5,6,7,8,9],\n    \"min_samples_leaf\": [3,5,7],\n    \"min_samples_split\":[3,5,7],\n    \"random_state\": [2020,2021]\n}\n\nmodel_ert = ExtraTreesClassifier()\nsearch_ert = GridSearchCV(estimator = model_ert, \n                         param_grid = grid_ert, \n                         cv = 5,\n                         n_jobs = -1,\n                         verbose = 2)\n# do not run this code in your local PC, it is time consuming\nsearch_ert.fit(train_x, train_y)\n# find the best parameters\nbest_ert = search_ert.best_params_\nbest_ert\n# final Extra Randomized Trees model\nfinal_ert =  ExtraTreesClassifier(**best_ert)\nfinal_ert.fit(train_x, train_y)\npred_ert = final_ert.predict(test_x)\npred_ert\n\"\"\"\n# Ensemble Generation\n\"\"\"\n# a majority vote ensemble\ndef ensumble_majority(trainx, trainy, testx):\n    final_rf =  RandomForestClassifier(**best_rf)\n    final_rf.fit(trainx, trainy)\n    pred_rf = final_rf.predict(testx)\n    \n    final_ert =  ExtraTreesClassifier(**best_ert)\n    final_ert.fit(trainx, trainy)\n    pred_ert = final_rf.predict(testx)\n    \n    final_xgb = xgb.XGBClassifier(**best_xgb)\n    final_xgb.fit(trainx, trainy)\n    pred_xgb = final_xgb.predict(testx)\n    \n    collection = pd.DataFrame({'pred_rf':pred_rf,'pred_ert':pred_ert,'pred_xgb':pred_xgb})\n    collection['sum'] = collection.sum(axis = 1)\n    collection.loc[collection['sum'] > 1.5, 'pred'] = 1\n    collection.loc[collection['sum'] < 1.5, 'pred'] = 0\n    \n    return(collection.pred)\n    \npred = ensumble_majority(train_x, train_y, test_x)\n\nres = pd.DataFrame({'PassengerId':test_x.PassengerId, 'Survived': pred})\nres.to_csv('result.csv', index=False)\n# a simple ensemble can use the majority vote rule, but here I try to build a simple stacking ensemble.\n# I use random forest and Extra Randomized Trees as basic models, and choose xgboost as the second layer models\n\ndef ensemble_stacking(trainx, trainy, testx):\n    '''\n    this function is to ensemble three models' predictions: random forest, extra randomized trees, and xgboost\n    '''\n    # first, split the train set into two equal parts.\n    px1,px2, py1, py2 = train_test_split(trainx, trainy, random_state= 2021, test_size=0.5)\n    \n    # second, train basic models by the two sets.\n    # random forest\n    final_rf =  RandomForestClassifier(**best_rf)\n    final_rf.fit(px1,py1)\n    pred_rf = final_rf.predict(px2)\n    \n    \n    # extra randomize trees\n    final_ert =  ExtraTreesClassifier(**best_ert)\n    final_ert.fit(px2,py2)\n    pred_ert = final_ert.predict(px1)\n    \n    # third, combind the two basic models predictions and as a new feature add into the original train set.\n    # it means to create a new train setand the new set = original train set + tow basic models' predictions\n    \n    new_x = pd.concat([px1, px2])\n    new_y = pd.concat([py1, py2])\n    feature = np.concatenate([pred_ert,pred_rf])\n    new_x['feature'] = feature\n    \n    # finally, train xgboost model by the new set and make the final prediction.\n    \n    final_xgb = xgb.XGBClassifier(**best_xgb)\n    final_xgb.fit(train_x, train_y)\n    pred_xgb = final_xgb.predict(test_x)\n    pred_xgb\n    \n    return(pred_xgb)\n# call ensemble function\npred = ensemble_stacking(train_x, train_y, test_x)\nres = pd.DataFrame({'PassengerId':test_x.PassengerId, 'Survived': pred})\nres.to_csv('result_stacking.csv', index=False)\n\"\"\"\nThank you for viewing my notebook!\nI want to share some of my experiences here.\n\n[1] more try, more findings. I check every model I used in this competition. I find some models can get better scores and parts of models' predictions are better than the ensemble result. (In R, I try more than 10 models, but in Python, I just choose 3 models.)\n\n[2] string columns are very important. In my code, I delete all string columns because I don't know how to deal with them. But I notice that many high score notebooks extract information from the string columns and generate features finally. So, I guess that is why I cannot reach the top 10% :(\n\n[3] Generating FEATURES! I think the most important step in the whole process is to determine features. The quality of features determines your score's mean value, and the rest parts, like grid search and ensemble, are the sd of your score. Therefore, if you want to get a higher score, pay more attention to your features.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '065d82911bdc21'}"}
{"id":"130728","text":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os, gc\nimport cudf\nimport pandas as pd\nimport numpy as np\nimport cupy as cp\nimport janestreet\nimport xgboost as xgb\nfrom hyperopt import hp, fmin, tpe, Trials\nfrom hyperopt.pyll.base import scope\nfrom sklearn.metrics import roc_auc_score, roc_curve\n\n\n\nfrom sklearn.model_selection import GroupKFold\nimport matplotlib.pyplot as plt\nfrom tqdm.notebook import tqdm\nfrom joblib import dump, load\n\nimport tensorflow as tf\ntf.random.set_seed(2212)\nimport tensorflow.keras.backend as K\nimport tensorflow.keras.layers as layers\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\n\nTEST = True\n# weighted average as per Donate et al.'s formula\n# https:\/\/doi.org\/10.1016\/j.neucom.2012.02.053\n# [0.0625, 0.0625, 0.125, 0.25, 0.5] for 5 fold\ndef weighted_average(a):\n    w = []\n    n = len(a)\n    for j in range(1, n + 1):\n        j = 2 if j == 1 else j\n        w.append(1 \/ (2**(n + 1 - j)))\n    return np.average(a, weights = w)\nfrom sklearn.model_selection._split import _BaseKFold, indexable, _num_samples\nfrom sklearn.utils.validation import _deprecate_positional_args\n\n# https:\/\/github.com\/getgaurav2\/scikit-learn\/blob\/d4a3af5cc9da3a76f0266932644b884c99724c57\/sklearn\/model_selection\/_split.py#L2243\nclass GroupTimeSeriesSplit(_BaseKFold):\n    \"\"\"Time Series cross-validator variant with non-overlapping groups.\n    Provides train\/test indices to split time series data samples\n    that are observed at fixed time intervals according to a\n    third-party provided group.\n    In each split, test indices must be higher than before, and thus shuffling\n    in cross validator is inappropriate.\n    This cross-validation object is a variation of :class:`KFold`.\n    In the kth split, it returns first k folds as train set and the\n    (k+1)th fold as test set.\n    The same group will not appear in two different folds (the number of\n    distinct groups has to be at least equal to the number of folds).\n    Note that unlike standard cross-validation methods, successive\n    training sets are supersets of those that come before them.\n    Read more in the :ref:`User Guide <cross_validation>`.\n    Parameters\n    ----------\n    n_splits : int, default=5\n        Number of splits. Must be at least 2.\n    max_train_size : int, default=None\n        Maximum size for a single training set.\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from sklearn.model_selection import GroupTimeSeriesSplit\n    >>> groups = np.array(['a', 'a', 'a', 'a', 'a', 'a',\\\n                           'b', 'b', 'b', 'b', 'b',\\\n                           'c', 'c', 'c', 'c',\\\n                           'd', 'd', 'd'])\n    >>> gtss = GroupTimeSeriesSplit(n_splits=3)\n    >>> for train_idx, test_idx in gtss.split(groups, groups=groups):\n    ...     print(\"TRAIN:\", train_idx, \"TEST:\", test_idx)\n    ...     print(\"TRAIN GROUP:\", groups[train_idx],\\\n                  \"TEST GROUP:\", groups[test_idx])\n    TRAIN: [0, 1, 2, 3, 4, 5] TEST: [6, 7, 8, 9, 10]\n    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a']\\\n    TEST GROUP: ['b' 'b' 'b' 'b' 'b']\n    TRAIN: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] TEST: [11, 12, 13, 14]\n    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 'b' 'b' 'b']\\\n    TEST GROUP: ['c' 'c' 'c' 'c']\n    TRAIN: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\\\n    TEST: [15, 16, 17]\n    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 'b' 'b' 'b' 'c' 'c' 'c' 'c']\\\n    TEST GROUP: ['d' 'd' 'd']\n    \"\"\"\n    @_deprecate_positional_args\n    def __init__(self,\n                 n_splits=5,\n                 *,\n                 max_train_size=None\n                 ):\n        super().__init__(n_splits, shuffle=False, random_state=None)\n        self.max_train_size = max_train_size\n\n    def split(self, X, y=None, groups=None):\n        \"\"\"Generate indices to split data into training and test set.\n        Parameters\n        ----------\n        X : array-like of shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n        y : array-like of shape (n_samples,)\n            Always ignored, exists for compatibility.\n        groups : array-like of shape (n_samples,)\n            Group labels for the samples used while splitting the dataset into\n            train\/test set.\n        Yields\n        ------\n        train : ndarray\n            The training set indices for that split.\n        test : ndarray\n            The testing set indices for that split.\n        \"\"\"\n        if groups is None:\n            raise ValueError(\n                \"The 'groups' parameter should not be None\")\n        X, y, groups = indexable(X, y, groups)\n        n_samples = _num_samples(X)\n        n_splits = self.n_splits\n        n_folds = n_splits + 1\n        group_dict = {}\n        u, ind = np.unique(groups, return_index=True)\n        unique_groups = u[np.argsort(ind)]\n        n_samples = _num_samples(X)\n        n_groups = _num_samples(unique_groups)\n        for idx in np.arange(n_samples):\n            if (groups[idx] in group_dict):\n                group_dict[groups[idx]].append(idx)\n            else:\n                group_dict[groups[idx]] = [idx]\n        if n_folds > n_groups:\n            raise ValueError(\n                (\"Cannot have number of folds={0} greater than\"\n                 \" the number of groups={1}\").format(n_folds,\n                                                     n_groups))\n        group_test_size = n_groups \/\/ n_folds\n        group_test_starts = range(n_groups - n_splits * group_test_size,\n                                  n_groups, group_test_size)\n        for group_test_start in group_test_starts:\n            train_array = []\n            test_array = []\n            for train_group_idx in unique_groups[:group_test_start]:\n                train_array_tmp = group_dict[train_group_idx]\n                train_array = np.sort(np.unique(\n                                      np.concatenate((train_array,\n                                                      train_array_tmp)),\n                                      axis=None), axis=None)\n            train_end = train_array.size\n            if self.max_train_size and self.max_train_size < train_end:\n                train_array = train_array[train_end -\n                                          self.max_train_size:train_end]\n            for test_group_idx in unique_groups[group_test_start:\n                                                group_test_start +\n                                                group_test_size]:\n                test_array_tmp = group_dict[test_group_idx]\n                test_array = np.sort(np.unique(\n                                              np.concatenate((test_array,\n                                                              test_array_tmp)),\n                                     axis=None), axis=None)\n            yield [int(i) for i in train_array], [int(i) for i in test_array]\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection._split import _BaseKFold, indexable, _num_samples\nfrom sklearn.utils.validation import _deprecate_positional_args\n\n# modified code for group gaps; source\n# https:\/\/github.com\/getgaurav2\/scikit-learn\/blob\/d4a3af5cc9da3a76f0266932644b884c99724c57\/sklearn\/model_selection\/_split.py#L2243\nclass PurgedGroupTimeSeriesSplit(_BaseKFold):\n    \"\"\"Time Series cross-validator variant with non-overlapping groups.\n    Allows for a gap in groups to avoid potentially leaking info from\n    train into test if the model has windowed or lag features.\n    Provides train\/test indices to split time series data samples\n    that are observed at fixed time intervals according to a\n    third-party provided group.\n    In each split, test indices must be higher than before, and thus shuffling\n    in cross validator is inappropriate.\n    This cross-validation object is a variation of :class:`KFold`.\n    In the kth split, it returns first k folds as train set and the\n    (k+1)th fold as test set.\n    The same group will not appear in two different folds (the number of\n    distinct groups has to be at least equal to the number of folds).\n    Note that unlike standard cross-validation methods, successive\n    training sets are supersets of those that come before them.\n    Read more in the :ref:`User Guide <cross_validation>`.\n    Parameters\n    ----------\n    n_splits : int, default=5\n        Number of splits. Must be at least 2.\n    max_train_group_size : int, default=Inf\n        Maximum group size for a single training set.\n    group_gap : int, default=None\n        Gap between train and test\n    max_test_group_size : int, default=Inf\n        We discard this number of groups from the end of each train split\n    \"\"\"\n\n    @_deprecate_positional_args\n    def __init__(self,\n                 n_splits=5,\n                 *,\n                 max_train_group_size=np.inf,\n                 max_test_group_size=np.inf,\n                 group_gap=None,\n                 verbose=False\n                 ):\n        super().__init__(n_splits, shuffle=False, random_state=None)\n        self.max_train_group_size = max_train_group_size\n        self.group_gap = group_gap\n        self.max_test_group_size = max_test_group_size\n        self.verbose = verbose\n\n    def split(self, X, y=None, groups=None):\n        \"\"\"Generate indices to split data into training and test set.\n        Parameters\n        ----------\n        X : array-like of shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n        y : array-like of shape (n_samples,)\n            Always ignored, exists for compatibility.\n        groups : array-like of shape (n_samples,)\n            Group labels for the samples used while splitting the dataset into\n            train\/test set.\n        Yields\n        ------\n        train : ndarray\n            The training set indices for that split.\n        test : ndarray\n            The testing set indices for that split.\n        \"\"\"\n        if groups is None:\n            raise ValueError(\n                \"The 'groups' parameter should not be None\")\n        X, y, groups = indexable(X, y, groups)\n        n_samples = _num_samples(X)\n        n_splits = self.n_splits\n        group_gap = self.group_gap\n        max_test_group_size = self.max_test_group_size\n        max_train_group_size = self.max_train_group_size\n        n_folds = n_splits + 1\n        group_dict = {}\n        u, ind = np.unique(groups, return_index=True)\n        unique_groups = u[np.argsort(ind)]\n        n_samples = _num_samples(X)\n        n_groups = _num_samples(unique_groups)\n        for idx in np.arange(n_samples):\n            if (groups[idx] in group_dict):\n                group_dict[groups[idx]].append(idx)\n            else:\n                group_dict[groups[idx]] = [idx]\n        if n_folds > n_groups:\n            raise ValueError(\n                (\"Cannot have number of folds={0} greater than\"\n                 \" the number of groups={1}\").format(n_folds,\n                                                     n_groups))\n\n        group_test_size = min(n_groups \/\/ n_folds, max_test_group_size)\n        group_test_starts = range(n_groups - n_splits * group_test_size,\n                                  n_groups, group_test_size)\n        for group_test_start in group_test_starts:\n            train_array = []\n            test_array = []\n\n            group_st = max(0, group_test_start - group_gap - max_train_group_size)\n            for train_group_idx in unique_groups[group_st:(group_test_start - group_gap)]:\n                train_array_tmp = group_dict[train_group_idx]\n                \n                train_array = np.sort(np.unique(\n                                      np.concatenate((train_array,\n                                                      train_array_tmp)),\n                                      axis=None), axis=None)\n\n            train_end = train_array.size\n \n            for test_group_idx in unique_groups[group_test_start:\n                                                group_test_start +\n                                                group_test_size]:\n                test_array_tmp = group_dict[test_group_idx]\n                test_array = np.sort(np.unique(\n                                              np.concatenate((test_array,\n                                                              test_array_tmp)),\n                                     axis=None), axis=None)\n\n            test_array  = test_array[group_gap:]\n            \n            \n            if self.verbose > 0:\n                    pass\n                    \n            yield [int(i) for i in train_array], [int(i) for i in test_array]\n\"\"\"\n# Preprocessing\n\"\"\"\nprint('Loading...')\ntrain = cudf.read_csv('\/kaggle\/input\/jane-street-market-prediction\/train.csv')\nfeatures = [c for c in train.columns if 'feature' in c]\n#     features.remove('feature_43')\n\nprint('Filling...')\ntrain1 = train.to_pandas()\n\ntrain = train1.query('date > 85').reset_index(drop = True) \ntrain = train.query('weight > 0').reset_index(drop = True)\ntrain[features] = train[features].fillna(method = 'ffill').fillna(0)\ntrain['action'] = ((train['resp_1'] > 0) & (train['resp_2'] > 0) & (train['resp_3'] > 0) & (train['resp_4'] > 0) & (train['resp'] > 0)).astype('int')\n\nresp_cols = ['resp', 'resp_1', 'resp_2', 'resp_3', 'resp_4']\n\nX = train[features].values\ny = np.stack([(train[c] > 0).astype('int') for c in resp_cols]).T\nsw = np.mean(np.abs(train[resp_cols].values), axis = 1)\nn_splits = 5\ngroup_gap = 31\n\"\"\"\n# Training\n\"\"\"\ndef create_ae_mlp(num_columns, num_labels, hidden_units, dropout_rates, ls = 1e-2, lr = 1e-3):\n    \n    inp = tf.keras.layers.Input(shape = (num_columns, ))\n    x0 = tf.keras.layers.BatchNormalization()(inp)\n    \n    encoder = tf.keras.layers.GaussianNoise(dropout_rates[0])(x0)\n    encoder = tf.keras.layers.Dense(hidden_units[0])(encoder)\n    encoder = tf.keras.layers.BatchNormalization()(encoder)\n    encoder = tf.keras.layers.Activation('swish')(encoder)\n    \n    decoder = tf.keras.layers.Dropout(dropout_rates[1])(encoder)\n    decoder = tf.keras.layers.Dense(num_columns, name = 'decoder')(decoder)\n\n    x_ae = tf.keras.layers.Dense(hidden_units[1])(decoder)\n    x_ae = tf.keras.layers.BatchNormalization()(x_ae)\n    x_ae = tf.keras.layers.Activation('swish')(x_ae)\n    x_ae = tf.keras.layers.Dropout(dropout_rates[2])(x_ae)\n\n    out_ae = tf.keras.layers.Dense(num_labels, activation = 'sigmoid', name = 'ae_action')(x_ae)\n    \n    x = tf.keras.layers.Concatenate()([x0, encoder])\n    x = tf.keras.layers.BatchNormalization()(x)\n    x = tf.keras.layers.Dropout(dropout_rates[3])(x)\n    \n    for i in range(2, len(hidden_units)):\n        x = tf.keras.layers.Dense(hidden_units[i])(x)\n        x = tf.keras.layers.BatchNormalization()(x)\n        x = tf.keras.layers.Activation('swish')(x)\n        x = tf.keras.layers.Dropout(dropout_rates[i + 2])(x)\n        \n    out = tf.keras.layers.Dense(num_labels, activation = 'sigmoid', name = 'action')(x)\n    \n    model = tf.keras.models.Model(inputs = inp, outputs = [decoder, out_ae, out])\n    model.compile(optimizer = tf.keras.optimizers.Adam(learning_rate = lr),\n                  loss = {'decoder': tf.keras.losses.MeanSquaredError(), \n                          'ae_action': tf.keras.losses.BinaryCrossentropy(label_smoothing = ls),\n                          'action': tf.keras.losses.BinaryCrossentropy(label_smoothing = ls), \n                         },\n                  metrics = {'decoder': tf.keras.metrics.MeanAbsoluteError(name = 'MAE'), \n                             'ae_action': tf.keras.metrics.AUC(name = 'AUC'), \n                             'action': tf.keras.metrics.AUC(name = 'AUC'), \n                            }, \n                 )\n    \n    return model\nparams = {'num_columns': len(features), \n          'num_labels': 5, \n          'hidden_units': [96, 96, 896, 448, 448, 256], \n          'dropout_rates': [0.03527936123679956, 0.038424974585075086, 0.42409238408801436, 0.10431484318345882, 0.49230389137187497, 0.32024444956111164, 0.2716856145683449, 0.4379233941604448], \n          'ls': 0, \n          'lr':1e-3, \n         }\nif not TEST:\n    scores = []\n    batch_size = 4096\n    gkf = PurgedGroupTimeSeriesSplit(n_splits = n_splits, group_gap = group_gap)\n    for fold, (tr, te) in enumerate(gkf.split(train['action'].values, train['action'].values, train['date'].values)):\n        ckp_path = f'JSModel_{fold}.hdf5'\n        model = create_ae_mlp(**params)\n        ckp = ModelCheckpoint(ckp_path, monitor = 'val_action_AUC', verbose = 0, \n                              save_best_only = True, save_weights_only = True, mode = 'max')\n        es = EarlyStopping(monitor = 'val_action_AUC', min_delta = 1e-4, patience = 10, mode = 'max', \n                           baseline = None, restore_best_weights = True, verbose = 0)\n        history = model.fit(X[tr], [X[tr], y[tr], y[tr]], validation_data = (X[te], [X[te], y[te], y[te]]), \n                            sample_weight = sw[tr], epochs = 100, batch_size = batch_size, callbacks = [ckp, es], verbose = 0)\n        hist = pd.DataFrame(history.history)\n        score = hist['val_action_AUC'].max()\n        print(f'Fold {fold} ROC AUC:\\t', score)\n        scores.append(score)\n\n        K.clear_session()\n        del model\n        rubbish = gc.collect()\nif not TEST:\n    print('Weighted Average CV Score:', weighted_average(scores))\ndef reduce_mem_usage(props):\n    start_mem_usg = props.memory_usage().sum() \/ 1024**2 \n    print(\"Memory usage of properties dataframe is :\",start_mem_usg,\" MB\")\n    NAlist = [] # Keeps track of columns that have missing values filled in. \n    for col in props.columns:\n        if props[col].dtype != object:  # Exclude strings\n            \n            # Print current column type\n            # print(\"******************************\")\n            # print(\"Column: \",col)\n            # print(\"dtype before: \",props[col].dtype)\n            \n            # make variables for Int, max and min\n            IsInt = False\n            mx = props[col].max()\n            mn = props[col].min()\n            \n            # Integer does not support NA, therefore, NA needs to be filled\n            if not np.isfinite(props[col]).all(): \n                NAlist.append(col)\n                props[col].fillna(mn-1,inplace=True)  \n                   \n            # test if column can be converted to an integer\n            asint = props[col].fillna(0).astype(np.int64)\n            result = (props[col] - asint)\n            result = result.sum()\n            if result > -0.01 and result < 0.01:\n                IsInt = True\n\n            \n            # Make Integer\/unsigned Integer datatypes\n            if IsInt:\n                if mn >= 0:\n                    if mx < 255:\n                        props[col] = props[col].astype(np.uint8)\n                    elif mx < 65535:\n                        props[col] = props[col].astype(np.uint16)\n                    elif mx < 4294967295:\n                        props[col] = props[col].astype(np.uint32)\n                    else:\n                        props[col] = props[col].astype(np.uint64)\n                else:\n                    if mn > np.iinfo(np.int8).min and mx < np.iinfo(np.int8).max:\n                        props[col] = props[col].astype(np.int8)\n                    elif mn > np.iinfo(np.int16).min and mx < np.iinfo(np.int16).max:\n                        props[col] = props[col].astype(np.int16)\n                    elif mn > np.iinfo(np.int32).min and mx < np.iinfo(np.int32).max:\n                        props[col] = props[col].astype(np.int32)\n                    elif mn > np.iinfo(np.int64).min and mx < np.iinfo(np.int64).max:\n                        props[col] = props[col].astype(np.int64)    \n            \n            # Make float datatypes 32 bit\n            else:\n                props[col] = props[col].astype(np.float32)\n            \n            # Print new column type\n            # print(\"dtype after: \",props[col].dtype)\n            # print(\"******************************\")\n    \n    # Print final result\n    print(\"___MEMORY USAGE AFTER COMPLETION:___\")\n    mem_usg = props.memory_usage().sum() \/ 1024**2 \n    print(\"Memory usage is: \",mem_usg,\" MB\")\n    print(\"This is \",100*mem_usg\/start_mem_usg,\"% of the initial size\")\n    return props, NAlist\n\n\n\nif TEST:\n    train, _ = reduce_mem_usage(train1)\n    exclude = set([2,5,19,26,29,36,37,43,63,77,87,173,262,264,268,270,276,294,347,499])\n    train = train[~train.date.isin(exclude)]\n\n    features = [c for c in train.columns if 'feature' in c]\n\n    f_mean = train[features[1:]].mean()\n    train[features[1:]] = train[features[1:]].fillna(f_mean)\n\n    train = train[train.weight>0]\n\n\n    train['action'] = ((train['resp'].values) > 0).astype('int')\n    train['action1'] = ((train['resp_1'].values) > 0).astype('int')\n    train['action2'] = ((train['resp_2'].values) > 0).astype('int')\n    train['action3'] = ((train['resp_3'].values) > 0).astype('int')\n    train['action4'] = ((train['resp_4'].values) > 0).astype('int')\n\n\n    X = train.loc[:, train.columns.str.contains('feature')].values\n    y = train.loc[:, 'action'].astype('int').values\n\n    X_ = X\n    y_ = train.loc[:, 'action3'].astype('int').values\n    \n    clf1 = xgb.XGBClassifier(\n      n_estimators=100,\n      max_depth=11,\n      learning_rate=0.05,\n      subsample=0.90,\n      colsample_bytree=0.7,\n      missing=-999,\n      random_state=21,\n      tree_method='gpu_hist',  # THE MAGICAL PARAMETER\n      reg_alpha=10,\n      reg_lambda=10,\n    )\n\n\n    clf1.fit(X_, y_)\n    \n    clf2 = xgb.XGBClassifier(\n      n_estimators=100,\n      max_depth=11,\n      learning_rate=0.05,\n      subsample=0.90,\n      colsample_bytree=0.7,\n      missing=-999,\n      random_state=210,\n      tree_method='gpu_hist',  # THE MAGICAL PARAMETER\n      reg_alpha=10,\n      reg_lambda=10,\n    )\n\n\n    clf2.fit(X_, y_)\n    \n    clf3 = xgb.XGBClassifier(\n      n_estimators=100,\n      max_depth=11,\n      learning_rate=0.05,\n      subsample=0.90,\n      colsample_bytree=0.7,\n      missing=-999,\n      random_state=2010,\n      tree_method='gpu_hist',  # THE MAGICAL PARAMETER\n      reg_alpha=10,\n      reg_lambda=10,\n    )\n\n\n    clf3.fit(X_, y_)\nif TEST:\n    inp = tf.keras.layers.Input(shape = len(features))\n\n    model4 = create_ae_mlp(**params)\n    model4.load_weights('..\/input\/jsmodelesade\/JSModel_3 (1).hdf5')\n    out4 = model4(inp)\n\n    model5 = create_ae_mlp(**params)\n    model5.load_weights('..\/input\/jsmodelesade\/JSModel_4 (1).hdf5')\n    out5 = model5(inp)\n    \n    model6 = create_ae_mlp(**params)\n    model6.load_weights('..\/input\/jsmodelesade\/JSModel_4_1212.hdf5')\n    out6 = model6(inp)\n    \n    model7 = create_ae_mlp(**params)\n    model7.load_weights('..\/input\/jsmodelesade\/JSModel_4_1214.hdf5')\n    out7 = model7(inp)\n\n    out = (out4[-1] + out5[-1]+out6[-1] + out7[-1]) \/ 4\n\n    model = tf.keras.models.Model(inputs = inp, outputs = out)\n    model.call = tf.function(model.call, experimental_relax_shapes = True)\n    model.summary()\n\"\"\"\n# Example Test Prediction\n\"\"\"\n# example_test = pd.read_csv('..\/input\/jane-street-market-prediction\/example_test.csv')\n# example_test = example_test.query('weight > 0').reset_index(drop = True)\n# example_test[features] = example_test[features].fillna(method = 'ffill').fillna(0)\n# test_preds = np.mean(model.predict(example_test[features], batch_size = 4096), axis = 1)\n# opt_th = test_preds.mean()\n# print(opt_th)\n\"\"\"\n# Submission\n\"\"\"\nif TEST:\n    from numba import njit\n\n    @njit\n    def fast_fillna(array, values):\n        if np.isnan(array.sum()):\n            array = np.where(np.isnan(array), values, array)\n        return array\n    env = janestreet.make_env()\n    env_iter = env.iter_test()\n    opt_th = 0.51\n    tmp = np.zeros(len(features))\n    for (test_df, pred_df) in tqdm(env_iter):\n        if test_df['weight'].item() > 0:\n            x_tt = test_df.loc[:, features].values\n            x_tt[0, :] = fast_fillna(x_tt[0, :], tmp)\n            tmp = x_tt[0, :]\n            pred = ((np.mean(model(x_tt, training = False).numpy(), axis = 1)+(clf1.predict_proba(x_tt)[0][1]+clf2.predict_proba(x_tt)[0][1]+clf3.predict_proba(x_tt)[0][1])\/3))\/2\n            pred_df.action = np.where(pred >= opt_th, 1, 0).astype(int)\n        else:\n            pred_df.action = 0\n        env.predict(pred_df)","meta":"{'source': 'AI4Code', 'id': 'f065909e61180c'}"}
{"id":"15445","text":"\"\"\"\n## Problem Definition \/ Goals\nOur goals in this analysis are:\n\n> Need to perform clustering to summarize customer segments\n\n> Given the customer routine spending, can we predict at which segment a customer can be associated?\n\"\"\"\n\"\"\"\n## 3. Features\n\nThe features of this dataset are divided in three macro categories:\n\n**People**\n\n* ID: Customer's unique identifier\n* Year_Birth: Customer's birth year\n* Education: Customer's education level\n* Marital_Status: Customer's marital status\n* Income: Customer's yearly household income\n* Kidhome: Number of children in customer's household\n* Teenhome: Number of teenagers in customer's household\n* Dt_Customer: Date of customer's enrollment with the company\n* Recency: Number of days since customer's last purchase\n* Complain: 1 if customer complained in the last 2 years, 0 otherwise\n\n**Products**\n\n* MntWines: Amount spent on wine in last 2 years\n* MntFruits: Amount spent on fruits in last 2 years\n* MntMeatProducts: Amount spent on meat in last 2 years\n* MntFishProducts: Amount spent on fish in last 2 years\n* MntSweetProducts: Amount spent on sweets in last 2 years\n* MntGoldProds: Amount spent on gold in last 2 years\n\n\n**Promotion**\n\n* NumDealsPurchases: Number of purchases made with a discount\n* AcceptedCmp1: 1 if customer accepted the offer in the 1st campaign, 0 otherwise\n* AcceptedCmp2: 1 if customer accepted the offer in the 2nd campaign, 0 otherwise\n* AcceptedCmp3: 1 if customer accepted the offer in the 3rd campaign, 0 otherwise\n* AcceptedCmp4: 1 if customer accepted the offer in the 4th campaign, 0 otherwise\n* AcceptedCmp5: 1 if customer accepted the offer in the 5th campaign, 0 otherwise\n* Response: 1 if customer accepted the offer in the last campaign, 0 otherwise\n\n**Place**\n\n* NumWebPurchases: Number of purchases made through the company\u2019s web site\n* NumCatalogPurchases: Number of purchases made using a catalogue\n* NumStorePurchases: Number of purchases made directly in stores\n* NumWebVisitsMonth: Number of visits to company\u2019s web site in the last month\n\"\"\"\n\"\"\"\n## Preparing the tools\n\nLet's import the main libraries\n\"\"\"\n# 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 pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'x-large',\n          'figure.figsize': (15, 5),\n         'axes.labelsize': '18',\n         'axes.titlesize':'24',\n         'xtick.labelsize':'12',\n         'ytick.labelsize':'12'}\npylab.rcParams.update(params)\n\n# Models from Scikit-Learn\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import MinMaxScaler\n\n# Model evaluation\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom sklearn.metrics import plot_roc_curve\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\/customer-personality-analysis'):\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\ndata = pd.read_csv(os.path.join(dirname, filename), sep='\\t', parse_dates=['Dt_Customer'])\n\"\"\"\n# Data Exploration\n\nIn this section we are going to analyze our data in order to visualize and compare features and their values, try to look at the creation of new features if necessary and look for other kind of pre-processing needs as normalization, transformation and so on.\n\nThe following questions can guide our EDA:\n\n* Which kind of customer tends to accept promotions at first offer? A the second \/ third and so on...?\n* Which kind of customer make more web visit of the web?\n* Which kind of customer make more purchases with discounts?\n* What is the best place (web\/store) in which customer spends more?\n* What is the average age of the enrolled customer?\n* Who complain more? Customer with High Education or Low Education? Aged people or young?\n\nIn update...\n\nAdd description of the features added, preprocessing and so on...\n\"\"\"\n\"\"\"\n## Let's start\n\nLet's discover the dataset structure and compute some new feature\n\"\"\"\ndata.info()\n\"\"\"\nSome columns could be converted in categorical type and we can add more information to this data. Let's work with features\n\"\"\"\ndf_copy = data.copy()\n\"\"\"\n### Feature Engineering\nWhat we've done:\n* Aggregated some Education categories\n* Aggregated some Marital Status categories\n* Computed a new feature: the fidelity years (customer's loyalty years)\n* Computed a new feature: the age of the customers\n* Computed a new feature: Sum up the kid and teen of customers as unique feature Children\n* Computed a new feature: If a customer has or not a child\n* Computed a new feature: Sum of all expenditures in different categories of products\n\n\"\"\"\ndef campaign_acceptance(row):\n    toReturn = row\n    campaigns = ['AcceptedCmp1', 'AcceptedCmp2', 'AcceptedCmp3', 'AcceptedCmp4', 'AcceptedCmp5', 'Response']\n    toReturn['accepted'] = 0\n    if row[campaigns].any() == 1:\n        toReturn['accepted'] = 1\n    \n    return pd.Series(toReturn, index=list(toReturn.keys()))\n# There are too much redundant value for Education\ndf_copy['Education'].replace({'Basic': 'Undergraduate', '2n Cycle': 'Undergraduate'}, inplace=True)\n\n# The same for Marital Status\ndf_copy['Marital_Status'].replace({'Absurd': 'Single', 'YOLO': 'Single',\n                                    'Alone': 'Single', 'Widow': 'Single', 'Together': 'Couple'}, inplace=True)\n\n# Let's see the customers fidelity years and their age\ndf_copy['fidelity_years'] = df_copy['Dt_Customer'].dt.year - df_copy['Year_Birth']\ndf_copy['age'] = datetime.now().year - df_copy['Year_Birth']\n\n# sum up the kid and teen as children\ndf_copy['children'] = df_copy['Kidhome'] + df_copy['Teenhome']\ndf_copy['has_child'] = df_copy['children'] > 0\n\n# Calculate total amount of expenses in different kind of products\ndf_copy['total_spend'] = df_copy['MntWines'] + df_copy['MntFruits'] + df_copy['MntMeatProducts'] +\\\n                        df_copy['MntFishProducts'] + df_copy['MntSweetProducts'] + df_copy['MntGoldProds']\n\n# Let's aggregate the acceptance of compaigns in one feature\ndf_copy = df_copy.apply(campaign_acceptance, axis=1)\n\n# Let's convert the strings in categories\nfor label, content in df_copy.items():\n    if pd.api.types.is_string_dtype(content):\n        df_copy[label] = content.astype('category').cat.as_ordered()\n        \n# Remove the NaN values from Income\ndf_copy['Income'].dropna(inplace=True)\n\"\"\"\nMoreover it seems there are columns without a description and with only one value, we are going to remove those columns\n\"\"\"\ndf_copy = df_copy.drop(['Z_Revenue', 'Z_CostContact'], axis=True)\ndf_copy.columns\ndf_copy['accepted'].value_counts()\n\"\"\"\n### Discovering Insights\n\"\"\"\n\"\"\"\nThe company has a lot of Graduate customers follower by PhD people. From the point of view of civil status they are mostly in couple (married and together)\n\"\"\"\nfig, (ax1, ax2) = plt.subplots(figsize=(20, 10), ncols=2)\ngrouped = df_copy.groupby('Education').count().reset_index()\n\nsns.countplot(ax=ax1, x=\"Education\", data=df_copy, palette= sns.color_palette(\"hls\", 4))\n\nsns.countplot(ax=ax2, x='Marital_Status', data=df_copy, palette= sns.color_palette(\"hls\", 4))\n\nax2.set_xlabel('Marital Status')\nax2.set_title('Civil Status of Customers')\nax1.set_title('Education status of customers')\nax1.set_ylabel('Count');\nax2.set_ylabel('Count');\nhas_child_perc = df_copy[df_copy['has_child'] == True].shape[0] \/ df_copy.shape[0]\nhas_nochild_perc = df_copy[df_copy['has_child'] == False].shape[0] \/ df_copy.shape[0]\nfig, ax = plt.subplots(figsize=(10, 10))\n# Anche qui vedere la percentuale di quanti hanno i figli\n\nsns.barplot(x=['Has Child', 'No Child'], y= [has_child_perc, has_nochild_perc], \n            palette = sns.color_palette('hls', 2));\nax.set_ylabel('Percentage of customers')\nax.set_title(f'The {round(has_child_perc, 2) * 100}% of customers has children');\n\"\"\"\nLess than 1% of customers complain about company services, but we can see that in this little pool of customer graduate and in-couple people tend to complain more.\n\"\"\"\n# Complain in the last 2 years\ncomplain = df_copy[df_copy['Complain'] == 1]\n\nfig, (ax1, ax2) = plt.subplots(figsize=(20, 10), ncols=2)\n\ned_compl_perc = complain.groupby('Education').count()['ID'] \/ df_copy.shape[0] * 100\nmarital_compl_perc = complain.groupby('Marital_Status').count()['ID'] \/ df_copy.shape[0] * 100\n\nsns.barplot(ax=ax1, x = ed_compl_perc.index, y = ed_compl_perc.values, palette = sns.color_palette('hls', 4))\nsns.barplot(ax=ax2, x = marital_compl_perc.index, y = marital_compl_perc.values, \n            palette = sns.color_palette('hls', 4));\n\nax2.set_xlabel('Marital Status')\nax2.set_title('Civil Status of Customers')\nax1.set_title('Education status of customers')\nax1.set_ylabel('Percentage of complain customers');\nprint(f'Percentage of complaining cutomers: {round((complain.shape[0] \/ df_copy.shape[0]) * 100, 2)}%')\n\"\"\"\nAlso the acceptance rate seems to be very low, but even though the acceptance rate is very low for all campaigns, it seems that people \"gave up\" at the last campaign. In few words, it seems that the last campaign was more effective.\n\"\"\"\ncampaigns = {\n    'Campaign': ['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Last'],\n    'Acceptance Rate': [(df_copy[df_copy['AcceptedCmp1'] == 1].shape[0] \/ df_copy.shape[0]) * 100,\n                       (df_copy[df_copy['AcceptedCmp2'] == 1].shape[0] \/ df_copy.shape[0]) * 100,\n                       (df_copy[df_copy['AcceptedCmp3'] == 1].shape[0] \/ df_copy.shape[0]) * 100,\n                       (df_copy[df_copy['AcceptedCmp4'] == 1].shape[0] \/ df_copy.shape[0]) * 100,\n                       (df_copy[df_copy['AcceptedCmp5'] == 1].shape[0] \/ df_copy.shape[0]) * 100,\n                       (df_copy[df_copy['Response'] == 1].shape[0] \/ df_copy.shape[0]) * 100]\n}\nfig, (ax1, ax2) = plt.subplots(figsize=(20, 10), ncols=2, sharex=True)\n\noffers = np.array([1, 2, 3, 4, 5])\nsns.barplot(ax=ax1, x = campaigns['Campaign'], y = campaigns['Acceptance Rate'], palette = sns.color_palette('hls', 6))\n#for offer in offers:\n#    sns.barplot(x = offer, y = (df_copy[df_copy['AcceptedCmp' + str(offer)] == 1].shape[0] \/ df_copy.shape[0]) * 100)\nsns.lineplot(ax=ax2, x = campaigns['Campaign'], y= campaigns['Acceptance Rate'], markers=True, dashes=False)    \n\nfig.suptitle('Campaigns Acceptance Rate', fontsize=24)\nax1.set_ylabel('Acceptance rate')\nax1.set_xlabel('Campaigns')\nax2.set_xlabel('Campaigns');\n\"\"\"\nIn general only the 27% of customers joined to the promoted campaigns\n\"\"\"\nfig, ax = plt.subplots(figsize=(7, 7))\n#define data\nslices = [df_copy[df_copy['accepted'] == 1].shape[0], \n          df_copy[df_copy['accepted'] == 0].shape[0]]\n\nlabels = ['Accepted', 'Rejected']\n\n#define Seaborn color palette to use\ncolors = sns.color_palette('pastel')[0:2]\n\n#create pie chart\nax.pie(slices, labels = labels, colors = colors, autopct='%.0f%%');\nax.set_title('Campaign Joined People');\n\"\"\"\ncustomers purchases frequency seems to be high, on average 49 days pass from one purchase to the next one.\n\"\"\"\ndf_copy['Recency'].describe()\n\"\"\"\nWe are going to work more on this feature in the next chunks. \n\"\"\"\n\"\"\"\nCustomers focus their purchases mainly on meat products\n\"\"\"\nfig, ax = plt.subplots(figsize=(10, 10))\n\nlabels = ['Meat', 'Fish', 'Sweet', 'Gold']\nvalues = [df_copy['MntMeatProducts'].mean(), df_copy['MntFishProducts'].mean(),\n         df_copy['MntSweetProducts'].mean(), df_copy['MntGoldProds'].mean()]\n\nsns.barplot(x = labels, y=values, palette = sns.color_palette('hls', 4))\n\nax.set_xlabel('Products')\nax.set_ylabel('Average Expenditure ($)')\nax.set_title('Average expenditure by products');\n\"\"\"\nNow we can see some outliers from the point of view of Income, so we are going to remove them\n\"\"\"\ndf_copy = df_copy[df_copy['Income'] < 120000]\ndf_copy['Income'].describe()\n\"\"\"\nCustomers are centered around 50K dollars of annual Income. I guess that customers are mostly middle class people.\n\"\"\"\nfig, ax = plt.subplots(figsize=(15, 10))\nsns.histplot(df_copy['Income'], stat='density');\ndf_copy['total_spend'].describe()\nfig, ax = plt.subplots(figsize=(15, 10))\nsns.histplot(df_copy['total_spend'], stat='density')\n\nax.set_xlabel('Total Expenditures($)');\n\"\"\"\nTotal expenditure is concentrated around an average value of 600+ dollars with a high level of standard deviation. Thus, we can ipotize the presence of very loyal customers and just occasional customers.\n\"\"\"\n\"\"\"\nLet's try to compute the purchases made in a store or on the web in percentage.\n\"\"\"\ned_group = df_copy.groupby('Education').sum().reset_index()\ndef compute_percentage_purchases(row, group):\n    toReturn = row\n    toReturn['WebPerc'] = 0\n    toReturn['StorePerc'] = 0\n    \n    # Get Total web and store purchases\n    total_web_purchases = group['NumWebPurchases'].sum()\n    total_store_purchases = group['NumStorePurchases'].sum()\n    \n    if row['Education'] == 'Graduation':\n        # Divide the customer store and web purchases by the total\n        toReturn['WebPerc'] = row['NumWebPurchases'] \/ total_web_purchases\n        toReturn['StorePerc'] = row['NumStorePurchases'] \/ total_store_purchases\n    \n    if row['Education'] == 'Undergraduate':\n        toReturn['WebPerc'] = row['NumWebPurchases'] \/ total_web_purchases\n        toReturn['StorePerc'] = row['NumStorePurchases'] \/total_store_purchases\n    \n    if row['Education'] == 'PhD':\n        toReturn['WebPerc'] = row['NumWebPurchases'] \/ total_web_purchases\n        toReturn['StorePerc'] = row['NumStorePurchases'] \/ total_store_purchases\n        \n    if row['Education'] == 'Master':\n        toReturn['WebPerc'] = row['NumWebPurchases'] \/total_web_purchases\n        toReturn['StorePerc'] = row['NumStorePurchases'] \/ total_store_purchases\n    \n    return pd.Series(toReturn, index = list(toReturn.keys()))\ndf_copy = df_copy.apply(compute_percentage_purchases, group = ed_group, axis=1)\n#df_copy['NumStorePurchasesPerc'] = df_copy['NumStorePurchases'] \/ ed_group['NumWebPurchases']\n# Let'se the mean of the computed value\ned_group = df_copy.groupby('Education').mean().reset_index()\n\"\"\"\nThere aren't very difference between the percentage of web and store purchases by education level, for example Graduation category has the similar percentage both for store and web. Maybe this problem is due to the unbalanced level in Education categories.\n\n**Question for readers:** Can be sampling a good solution in this case?\n\"\"\"\nfig, (ax1, ax2) = plt.subplots(figsize=(20, 10), ncols = 2)\n\nsns.barplot(ax=ax1, x = ed_group['Education'], y = ed_group['StorePerc'], palette = sns.color_palette('hls', 4));\nsns.barplot(ax=ax2, x = ed_group['Education'], y = ed_group['WebPerc'], palette = sns.color_palette('hls', 4));\n\nax1.set_ylabel('Purchases Percentage in Store')\nax1.set_title('Store')\nax2.set_ylabel('Purchases Percentage on Web')\nax2.set_title('Web')\nplt.suptitle('Percentage Purchases by Education level', fontsize=24);\n\"\"\"\n## Cluster\n\nWe are going to clusterize our customers as goal of the notebook and to discover other insights\n\"\"\"\ndf_copy.dropna(inplace=True)\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import MinMaxScaler\n# define the attribute to cluster ['age', 'children', 'total_spend', 'Income']\ncluster_features = ['age', 'children', 'total_spend', 'Income'] #['children', 'total_spend', 'Income', 'WebPerc', 'StorePerc']\ntoCluster = df_copy[cluster_features]\n# Normalization\nscaler = MinMaxScaler()\ntoCluster[cluster_features] = scaler.fit_transform(toCluster)\n# Elbow method to select the right number of cluster\nK = range(1,10)\ndistortions = []\nfor k in K:\n    kmeanModel = KMeans(n_clusters=k)\n    kmeanModel.fit(toCluster)\n    distortions.append(kmeanModel.inertia_)\nplt.figure(figsize=(16,8))\nplt.plot(K, distortions, 'bx-')\nplt.xlabel('k')\nplt.ylabel('Distortion')\nplt.title('The Elbow Method showing the optimal k')\nplt.show()\nclusters = KMeans(n_clusters = 4, random_state=42)\nlabels = clusters.fit_predict(toCluster)\ndf_copy['cluster'] = labels\ndf_copy['cluster'].value_counts()\ndf_copy.groupby('cluster').mean()\nfig, ax = plt.subplots(figsize=(15, 10))\n\ndf_copy = df_copy[df_copy['Income'] < 200000]\n\n\nx_axis = 'Income'\ny_axis = 'total_spend'\nsns.scatterplot(x = df_copy[df_copy['cluster'] == 0][x_axis],\n                y = df_copy[df_copy['cluster'] == 0][y_axis], \n            palette='salmon', legend = 'auto')\n\nsns.scatterplot(x= df_copy[df_copy['cluster'] == 1][x_axis], \n                y = df_copy[df_copy['cluster'] == 1][y_axis], \n            palette='blue', legend = 'auto')\n\nsns.scatterplot(x= df_copy[df_copy['cluster'] == 2][x_axis], \n                y = df_copy[df_copy['cluster'] == 2][y_axis], \n            palette='green', legend = 'auto')\n\nsns.scatterplot(x= df_copy[df_copy['cluster'] == 3][x_axis], \n                y = df_copy[df_copy['cluster'] == 3][y_axis], \n            palette='red', legend = 'auto')\n\nlinedf = pd.DataFrame({'x': df_copy['Income'].values,'y': np.full(df_copy.shape[0], 1400)})\nplt.plot(linedf['x'], linedf['y'], color='blue', linestyle='dashed')\n#sns.lineplot(x = 'x', y = 'y', data = linedf, palette = 'salmon')\n\nlinedf2 = pd.DataFrame({'x': df_copy['Income'].values,'y': np.full(df_copy.shape[0], 800)})\nplt.plot(linedf2['x'], linedf2['y'], color='salmon', linestyle='dashed')\n#sns.lineplot(x = 'x', y = 'y', data = linedf2, palette = 'red')\n\nax.set_title(\"Income vs Total amount spent\")\nax.set_xlabel('Income')\nax.set_ylabel('Total Spent')\nax.legend(['Rich Class', 'Middle Class', '0', '1', '2', '3']);\n\"\"\"\nIt is interesting to note how rich people (people with high annual income) tends to overlap with middle class people and in few cases with poor class. Indeed, it is possible to note different samples with high annual income and low total expenditure in products and, on the other side, samples with low annual income with high total spending. In few words, here we have a depiction of different behaviors and habits between rich and poor people, where true rich people tend to handle and hold their money for investments (we can ipotize) and poor people that are not able to manage money and tend to spend more to show off their no-poor condition. A classic example is Warren Buffet, he is a multi-bilionare but he lives in the same house bought in 1950s years and he don't spend its money if it not necessary, instead in a lot of cases poorer class tend to live beyond their means. We can have more evidence by the following charts, where are compared the cluster 3 containing people with a highest mean of annual income and cluster 1 containing people with the lowest annual income in mean.\n\"\"\"\ncluster1 = df_copy[df_copy['cluster'] == 3]\ncluster1 = cluster1[cluster1['age'] < 120]\ncluster2 = df_copy[df_copy['cluster'] == 1]\ncluster2 = cluster2[cluster2['age'] < 120]\n\nfig, (ax1, ax2) = plt.subplots(figsize=(15, 20), nrows=2)\n\nsns.regplot(ax=ax1, x = cluster1['age'], y = cluster1['total_spend'])\nsns.regplot(ax=ax2, x = cluster2['age'], y = cluster2['total_spend'])\n\nfrom scipy import stats\n        \nslope1, intercept2, r_value2, pv2, se2= stats.linregress(cluster1['age'], cluster1['total_spend'])\nslope2, intercept2, r_value2, pv2, se2 = stats.linregress(cluster2['age'], cluster2['total_spend']) \nprint(slope1, slope2)\n\"\"\"\nThe total spend of rich people has a decreasing trend as well as the age increase with a negative slope of -0.09, instead the poor people have a slightly opposite behaviour. This means rich people at age increasing tend to save their money, meanwhile poor people increase their expenditures.\n\n**Note:** Of course, it is a my opinion, I'm really far to offend someone. It is just what I'm reading from analyzed data and it is just an attempt to show a my intuition in light of the above chart. Is it my reasoning linear and according with the shown charts?\n\n\"\"\"\n\"\"\"\n### Let's add more features to our customers\n\nI want to segment the customer by different features as age, fidelity years, income and recency days. I borrowed from the linked notebook: *[Customer Personality Analysis with Python](https:\/\/thecleverprogrammer.com\/2021\/02\/08\/customer-personality-analysis-with-python\/)*.\n\"\"\"\n#Create Age segment\ncut_labels_Age = ['Young', 'Adult', 'Mature', 'Senior']\ncut_bins = [0, 30, 45, 65, 120]\ndf_copy['age_group'] = pd.cut(df_copy['age'], bins=cut_bins, labels=cut_labels_Age)\n\ncut_labels_Age = ['0-30', '30-45', '45-65', '65+']\ncut_bins = [0, 30, 45, 65, 120]\ndf_copy['age_range'] = pd.cut(df_copy['age'], bins=cut_bins, labels=cut_labels_Age)\n\n#Create Income segment\ncut_labels_Income = ['Low income', 'Low to medium income', 'Medium to high income', 'High income']\ndf_copy['Income_group'] = pd.qcut(df_copy['Income'], q=4, labels=cut_labels_Income)\n\n#Create Fidelity segment. The time the customer is client\ncut_labels_Seniority = ['New customers', 'Discovering customers', 'Experienced customers', 'Old customers']\ndf_copy['Fidelity_group'] = pd.qcut(df_copy['fidelity_years'], q=4, labels=cut_labels_Seniority)\n\n# Create Recency segment. Recency is some sort of purchases frequency\ncut_labels_Recency = ['High Frequency', 'Normal Frequency', 'Low Frequency', 'Occasional']\ndf_copy['Recency_group'] = pd.qcut(df_copy['Recency'], q=4, labels=cut_labels_Recency)\n#data=data.drop(columns=['Age','Income','Seniority'])\nfig, ax = plt.subplots(figsize=(20, 20), nrows=2, ncols=2)\nax1 = ax[0][0]\nax2 = ax[0][1]\nax3 = ax[1][0]\nax4 = ax[1][1]\n\nsns.countplot(ax = ax1, x = df_copy['age_group'], palette = sns.color_palette('hls', 4))\nax1.set_xlabel('Age Group')\n\nsns.countplot(ax = ax2, x = df_copy['Income_group'], palette = sns.color_palette('hls', 4))\nax2.set_xlabel('Income Group')\n\nsns.countplot(ax = ax3, x = df_copy['Fidelity_group'], palette = sns.color_palette('hls', 4))\nax3.set_xlabel('Fidelity Group')\n\nsns.countplot(ax = ax4, x = df_copy['Recency_group'], palette = sns.color_palette('hls', 4))\nax4.set_xlabel('Recency Group');\n\"\"\"\nLet's suppose the company is promoting discounts campaign. The below chart show us possible target that could partecipate to campaign, in particular is possible to focus more effort on young and adult people with low income.\n\"\"\"\nincome_age = pd.crosstab(df_copy['age_group'], df_copy['Income_group']).reset_index()\nincome_age['total'] = income_age['Low income'] + income_age['Low to medium income'] + income_age['Medium to high income'] + income_age['High income']\nincome_age['low-perc'] = round(income_age['Low income'] \/ income_age['total'], 2)\nincome_age['lowmed-perc'] = round(income_age['Low to medium income'] \/ income_age['total'], 2)\nincome_age['medhigh-perc'] = round(income_age['Medium to high income'] \/ income_age['total'], 2)\nincome_age['high-perc'] = round(income_age['High income'] \/ income_age['total'], 2)\nincome_young_dict = {\n    'age_group': 'Young',\n    'income': ['low-income', 'low-med-income', 'med-high-income', 'high-income'],\n    'percentage': [income_age[income_age['age_group'] == 'Young']['low-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Young']['lowmed-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Young']['medhigh-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Young']['high-perc'].values[0],]\n}\n\nincome_adult_dict = {\n    'age_group': 'Adult',\n    'income': ['low-income', 'low-med-income', 'med-high-income', 'high-income'],\n    'percentage': [income_age[income_age['age_group'] == 'Adult']['low-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Adult']['lowmed-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Adult']['medhigh-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Adult']['high-perc'].values[0],]\n}\n\nincome_mature_dict = {\n    'age_group': 'Mature',\n    'income': ['low-income', 'low-med-income', 'med-high-income', 'high-income'],\n    'percentage': [income_age[income_age['age_group'] == 'Mature']['low-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Mature']['lowmed-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Mature']['medhigh-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Mature']['high-perc'].values[0],]\n}\n\nincome_senior_dict = {\n    'age_group': 'Senior',\n    'income': ['low-income', 'low-med-income', 'med-high-income', 'high-income'],\n    'percentage': [income_age[income_age['age_group'] == 'Senior']['low-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Senior']['lowmed-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Senior']['medhigh-perc'].values[0],\n                  income_age[income_age['age_group'] == 'Senior']['high-perc'].values[0],]\n}\n\nfactor_df = pd.DataFrame(income_young_dict).append(pd.DataFrame(income_adult_dict), ignore_index=True)\\\n            .append(pd.DataFrame(income_mature_dict), ignore_index=True).append(pd.DataFrame(income_senior_dict), ignore_index=True)\nsns.catplot(x='age_group', y='percentage', hue='income', data=factor_df, kind='bar', palette=sns.color_palette('hls', 4),\n           height=8, aspect=1.5);\ncluster = df_copy[df_copy['cluster'] == 0]\n\ncluster['age_group'].mode().values[0], cluster['age_range'].mode().values[0], cluster['Income_group'].mode().values[0], cluster['Fidelity_group'].mode().values[0], cluster['Recency_group'].mode().values[0]\ncluster = df_copy[df_copy['cluster'] == 1]\n\ncluster['age_group'].mode().values[0], cluster['age_range'].mode().values[0], cluster['Income_group'].mode().values[0], cluster['Fidelity_group'].mode().values[0], cluster['Recency_group'].mode().values[0]\ncluster = df_copy[df_copy['cluster'] == 2]\n\ncluster['age_group'].mode().values[0], cluster['age_range'].mode().values[0], cluster['Income_group'].mode().values[0], cluster['Fidelity_group'].mode().values[0], cluster['Recency_group'].mode().values[0]\ncluster = df_copy[df_copy['cluster'] == 3]\n\ncluster['age_group'].mode().values[0], cluster['age_range'].mode().values[0], cluster['Income_group'].mode().values[0], cluster['Fidelity_group'].mode().values[0], cluster['Recency_group'].mode().values[0]\n\"\"\"\nThus, the company have four kind of customers:\n* Mature custmomers (45 - 65 years old) middle class, old customer with a normal frequency of purchases (Cash Cow)\n* Adult customers (30 - 45 years old) low income, new customer with a high level of frequency purchases (Opportunity)\n* Mature customers similar to the first one except for the annual income, that in this case is low to medium\n* Mature customers with high income but low frequency of purchases. They are very experienced customers.\n\"\"\"\n\"\"\"\n## Prepare data for modelling\n\"\"\"\ndf_copy.head().T\n\"\"\"\nWe can drop some columns because they were used to compute other columns and are redundant\n\"\"\"\ndf_copy = df_copy.drop(['ID', 'Year_Birth', 'Kidhome',\n                        'Teenhome', 'Dt_Customer'], axis=1)\n# This will turn all the strings value into category values\ndf_copy['has_child'] = df_copy['has_child'].astype('category').cat.as_ordered()\nfor label, content in df_copy.items():\n    if pd.api.types.is_string_dtype(content):\n        df_copy[label] = content.astype('category').cat.as_ordered()\n\n# Turn categorical variables into numbers\nfor label, content in df_copy.items():\n    if not pd.api.types.is_numeric_dtype(content):\n        # Turn categories into numbers and add + 1\n        df_copy[label] = pd.Categorical(content).codes + 1\ntoScale = ['Income', 'Recency', 'MntWines', 'MntFruits', 'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts', 'MntGoldProds',\n          'NumDealsPurchases', 'NumWebPurchases', 'NumCatalogPurchases', 'NumStorePurchases', 'NumWebVisitsMonth',\n          'fidelity_years', 'age', 'children', 'total_spend', 'WebPerc', 'StorePerc']\n\nscaler = MinMaxScaler()\ndf_copy[toScale] = scaler.fit_transform(df_copy[toScale])\nnp.random.seed(42)\n\nX = df_copy.drop('cluster', axis=1)\ny = df_copy['cluster']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0)\n\nlr_model = LogisticRegression(solver='liblinear')\nknn_model = KNeighborsClassifier()\nrf_model = RandomForestClassifier()\n\n\nmodels = {\n    'LogisticRegression': lr_model,\n    'KNeighborsClassifier': knn_model,\n    'RandomForestClassifier': rf_model\n}\n\nfor name, model in models.items():\n    model.fit(X_train, y_train)\n    print(name, ', score:', model.score(X_test, y_test))\n\"\"\"\nSince our Random Forest model provides the best scores so far with default parameters, we can proceed towars the cross-validation. From results the model doesn't seem to soffer the overfitting.\n\"\"\"\n# Cross validation on the best model\nfrom sklearn.model_selection import cross_val_score\n\nbest_clf = models['RandomForestClassifier']\n\ncv_acc = cross_val_score(best_clf, X, y, cv=5, scoring='accuracy')\n\ncv_acc\n# Helper function for plotting feature importance\ndef plot_features(columns, importances, n=20):\n    df = (pd.DataFrame({'features': columns, \n                        'feature_importances': importances})\n          .sort_values('feature_importances', ascending=False)\n          .reset_index(drop=True))\n    \n    fig, ax = plt.subplots(figsize=(10, 10))\n    \n    ax.barh(df['features'][:n], df['feature_importances'][:n])\n    ax.set_ylabel('Features')\n    ax.set_xlabel('Feature importance')\n    ax.invert_yaxis()\n    \nplot_features(X.columns, best_clf.feature_importances_)\n\"\"\"\nSo, we can predict the customer segment with high accuracy given its purchases behaviors. Moreover, from the above chart we can see the best attributes impacting the prediction\n\"\"\"\n\"\"\"\n## Conclusion\nI propose again the main goals of this analysis\n> Need to perform clustering to summarize customer segments\n\nThe customer segments defined are the following:\n* Mature custmomers (45 - 65 years old) middle class, experienced customer with a normal frequency of purchases, we can consider this kind of customer as a **Cash Cow**, due to their loyalty and constant expenditures\n* Adult customers (30 - 45 years old) low income, new customer with a high level of frequency purchases, we can consider them as an opportunity to grow the company income making the right campaign for them.\n* Mature customers similar to the first one except for the annual income, that in this case is low to medium\n* Mature customers with high income but low frequency of purchases. They are very experienced customers, they tends to save their money it could be difficult to get more from them.\n\n> Given the customer routine spending, can we predict at which segment a customer can be associated?\n\nIt is possible to predict the customer segment given its expenditure routine. In this way, it is possible to run more specific campaigns for each kind of customers.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1c30130fad637b'}"}
{"id":"91668","text":"\"\"\"\n# Hello : )\n## Welcome to my notebook\n### By Reading my notebook you will get . . .\n\n    - The roughly analysis of this dataset\n    - Simple Data Cleaning technique\n    - Some statistic technique to deal with each datatype\n    - Some colorful visualize \n    - Good start point if you want to play this dataset\n    - My Code (I hope it clean enough to use in other dataset)\n    - My thanks :)\n    \n\"\"\"\n\"\"\"\n## Feel free to <font color=deepskyblue> FORK  <\/font> this notebook, Please  <font color=deepskyblue> UPVOTE !! <\/font> if it's helpful to you  <font color=deepskyblue> : ) <\/font>\n\"\"\"\n\"\"\"\n## Ready ? Let's go !!\n\"\"\"\n\"\"\"\n![imglink](https:\/\/flightitineraryforvisa.com\/wp-content\/uploads\/2018\/12\/Hotel-Booking-1280x720.jpg)\n\n(Image taken from [imglink](https:\/\/flightitineraryforvisa.com\/wp-content\/uploads\/2018\/12\/Hotel-Booking-1280x720.jpg))\n\"\"\"\n\"\"\"\n## Import some useful libraries\n\"\"\"\nimport pandas as pd    ## library for playing with dataframe\nimport numpy as np    ## library for dealing with array & numeric value\nimport matplotlib.pyplot as plt   ## Visualize library\nimport seaborn as sns \n\n## make notebook more clean by not show the warning\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n## make dataframe show only 2 digits float \npd.options.display.float_format = '{:.2f}'.format\n\n\n%matplotlib inline\n\"\"\"\n## Read the dataset\n\"\"\"\ndata = pd.read_csv('..\/input\/hotel-booking-demand\/hotel_bookings.csv')\ndata.head()\ndata.columns\n\"\"\"\n# Visualization\n\"\"\"\n\"\"\"\n## Hotel\n\"\"\"\nplt.rcParams['figure.figsize'] = 10,10\nlabels = data['hotel'].value_counts().index.tolist()\nsizes = data['hotel'].value_counts().tolist()\nexplode = (0, 0.2)\ncolors = ['indianred','khaki']\n\nplt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',\n        shadow=False, startangle=30)\nplt.axis('equal')\nplt.tight_layout()\nplt.title(\"How many type of hotel in this dataset\", fontdict=None, position= [0.48,1], size = 'xx-large')\nplt.show()\n\"\"\"\n## lead time\n\n    Number of days that elapsed between the entering date of the booking into the PMS and the arrival date\n\"\"\"\nplt.rcParams['figure.figsize'] = 15,6\nplt.hist(data['lead_time'].dropna(), bins=30,color = 'paleturquoise' )\n\nplt.ylabel('Count')\nplt.xlabel('Time (days)')\nplt.title(\"Lead time distribution \", fontdict=None, position= [0.48,1.05], size = 'xx-large')\nplt.show()\n\"\"\"\n## is_canceled\n\n    Value indicating if the booking was canceled (1) or not (0)\n\"\"\"\nplt.rcParams['figure.figsize'] = 15,8\n\nheight = data['is_canceled'].value_counts().tolist()\nbars =  ['Not Cancel','Cancel']\ny_pos = np.arange(len(bars))\ncolor = ['lightgreen','salmon']\nplt.bar(y_pos, height , width=0.7 ,color= color)\nplt.xticks(y_pos, bars)\nplt.xticks(rotation=90)\nplt.title(\"How many booking was cancel\", fontdict=None, position= [0.48,1.05], size = 'xx-large')\nplt.show()\n\n\"\"\"\n## Stays in Week Night vs Weekend Night\n\n    Number of weekend nights (Saturday or Sunday) the guest stayed or booked to stay at the hotel\n    \n    Number of week nights (Monday to Friday) the guest stayed or booked to stay at the hotel\n\"\"\"\nplt.rcParams['figure.figsize'] = 15,6\n\nplt.hist(data['stays_in_week_nights'][data['stays_in_week_nights'] < 10].dropna(), \n         bins=8,alpha = 1,color = 'lemonchiffon',label='Stays in week night' )\n\nplt.hist(data['stays_in_weekend_nights'][data['stays_in_weekend_nights'] < 10].dropna(),\n         bins=8, alpha = 0.5,color = 'blueviolet',label='Stays in weekend night' )\n\nplt.ylabel('Count')\nplt.xlabel('Time (days)')\nplt.title(\"Stays in Week Night vs Weekend Night \", fontdict=None, position= [0.48,1.05], size = 'xx-large')\nplt.legend(loc='upper right')\nplt.show()\n\"\"\"\n## Agent\n\n    ID of the travel agency that made the booking\n\"\"\"\n\nplt.rcParams['figure.figsize'] =10,10\nsizes = data['agent'].value_counts()[:8].tolist() + [len(data) - sum(data['agent'].value_counts()[:8].tolist())]\nlabels = [\"Agent \" + str(string) for string in data['agent'].value_counts()[:8].index.tolist()] + [\"Other\"]\n\nexplode = (0.18,0.11,0.12,0,0,0,0,0,0,0,0)\ncolors =  ['royalblue','mediumaquamarine','moccasin'] +['linen']*7 + ['oldlace']\n\nplt.pie(sizes, explode = explode, colors = colors ,labels=labels, autopct='%1.1f%%',\n        shadow=False, startangle=96)\nplt.axis('equal')\nplt.tight_layout()\nplt.title(\"Who is the best agent\", fontdict=None, position= [0.5,1], size = 'xx-large')\n\nplt.show()\n\"\"\"\n## ADR\n\n    Average Daily Rate as defined by dividing the sum of all lodging transactions by the total number of staying nights\n\"\"\"\nprint(\"The highest value is : \", data['adr'].max())\nprint(\"The lowest value is : \", data['adr'].min())\n\"\"\"\n    Seem like it has large gap between the highest value and the lowest,\n    let ignore outlier first   : )\n    I will use the simple remove outlier technique such as 1.5IQR\n[Dealing with Outlier](https:\/\/towardsdatascience.com\/ways-to-detect-and-remove-the-outliers-404d16608dba)\n\"\"\"\nQ1 = data['adr'].quantile(0.25)\nQ3 = data['adr'].quantile(0.75)\nIQR = Q3 - Q1\n\nlower_bound = (Q1 - 1.5 * IQR)\nupper_bound = (Q3 + 1.5 * IQR)\nwithout_outlier = data[(data['adr'] > lower_bound ) & (data['adr'] < upper_bound)]\nplt.boxplot(without_outlier['adr'],  notch=True,  # notch shape\n                         patch_artist=True,\n                   boxprops=dict(facecolor=\"sandybrown\", color=\"black\"),)\nplt.ylabel('ADR')\nplt.title(\"Box plot for Average Daily Rate \", fontdict=None, position= [0.48,1.05], size = 'xx-large')\n\nplt.show()\n\"\"\"\n## Reserve Room Type\n\"\"\"\n\"\"\"\n    Code of room type reserved. Code is presented instead of designation for anonymity reasons.\n\"\"\"\nplt.rcParams['figure.figsize'] = 15,8\n\nheight = data['reserved_room_type'].value_counts().tolist()\nbars =  data['reserved_room_type'].value_counts().index.tolist()\ny_pos = np.arange(len(bars))\ncolor= ['c']+['paleturquoise']*10\nplt.bar(y_pos, height , width=0.7 ,color= color)\nplt.xticks(y_pos, bars)\nplt.ylabel('Count')\nplt.xlabel('Roomtype')\nplt.title(\"How many reserves in each type of room\", fontdict=None, position= [0.48,1.05], size = 'xx-large')\nplt.show()\n\n\"\"\"\n## Is Cancel ? \n\"\"\"\ndata.is_canceled.value_counts()\nplt.rcParams['figure.figsize'] = 10,10\nlabels = ['Not','Cancel']\nsizes = data['is_canceled'].value_counts().tolist()\nexplode = (0, 0.2)\ncolors = ['dodgerblue','tomato']\n\nplt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',\n        shadow=False, startangle=190)\nplt.axis('equal')\nplt.tight_layout()\nplt.title(\"How many bookings were cancel\", fontdict=None, position= [0.48,1], size = 'xx-large')\nplt.show()\n\"\"\"\n## Select data to feed to the model\n\"\"\"\ninput_information = data[['hotel','lead_time','stays_in_week_nights','stays_in_weekend_nights','adults','reserved_room_type','adr'\n                          ,'is_canceled']]\ninput_information.shape\n## Binary encoding the categorical data\n\ninput_information = pd.get_dummies(data=input_information)\ninput_information.shape\nY_train = input_information[\"is_canceled\"]\nX_train = input_information.drop(labels = [\"is_canceled\"],axis = 1)\n\"\"\"\n## Random Forest\n\"\"\"\n\"\"\"\n    Here I just applied default Random Forest without any tuning \n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import  cross_val_score,GridSearchCV\n\nRfclf = RandomForestClassifier(random_state=15)\nRfclf.fit(X_train, Y_train)\nclf_score = cross_val_score(Rfclf, X_train, Y_train, cv=10)\nprint(clf_score)\nclf_score.mean()\n\"\"\"\n## Extract Knowledge from model\n\"\"\"\nRfclf_fea = pd.DataFrame(Rfclf.feature_importances_)\nRfclf_fea[\"Feature\"] = list(X_train) \nRfclf_fea.sort_values(by=0, ascending=False).head()\ng = sns.barplot(0,\"Feature\",data = Rfclf_fea.sort_values(by=0, ascending=False)[0:5], palette=\"Pastel1\",orient = \"h\")\ng.set_xlabel(\"Weight\")\ng = g.set_title(\"Random Forest\")\n\"\"\"\n\nFeel free to folk this kernel.\n\nI hope my notebook may help you as start point for this dataset.\n\nYou **upvote** will help me a lot :)\n\nThanks\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a82abf700e26d5'}"}
{"id":"120803","text":"\"\"\"\n<h1>ASL Recognition using Keras CNN<\/h1>\n<p>In this notebook, we will train a Keras Deep Learning model to recognize American Sign Language<\/p>\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/miro.medium.com\/max\/4800\/1*DrbLUMbhtehEgEl8Kj5v9Q.png\">\n\"\"\"\nfrom tensorflow import keras\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score,precision_score,recall_score\nfrom sklearn.metrics import ConfusionMatrixDisplay\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nimport cv2\nfeatures = []\nlabels = []\n#reading file locations\n#From the locations read, consider only 1100 out of 3000 to reduce dataset size\nclasses = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\nfor i in range(len(classes)):\n    file_list = glob.glob(\"\/kaggle\/input\/asl-alphabet\/asl_alphabet_train\/asl_alphabet_train\/\" + classes[i] + \"\/*.jpg\")\n    for item in range(1100):\n        features.append(file_list[item])\n        labels.append([i])\nprint(\"Dataset Feature size : \",len(features))\nprint(\"Dataset labels size : \",len(labels))\n#Shuffle the array\nfeatures,labels = shuffle(features,labels,random_state=0)\ntrain_features = []\ntrain_labels = []\nvalidation_features = []\nvalidation_labels = []\n\nfor i in features:\n    train_features.append(cv2.imread(i,cv2.IMREAD_COLOR))\n    train_features[-1] = np.reshape(train_features[-1],[200,200,3])\n\nfor i in labels:\n    train_labels.append(i)\n\ntrain_features,validation_features,train_labels,validation_labels = train_test_split(train_features,train_labels,test_size=0.3)\nprint(\"Train data : \",len(train_features),len(train_labels))\nprint(\"Validation data : \",len(validation_features),len(validation_labels))\ndel features\ndel labels\ndel file_list\nalpha = [chr(c) for c in range(65,91)]\nun,count = np.unique(train_labels,return_counts=True)\nj=1\nplt.figure(figsize=(100,100))\nfor i in un:\n    plt.subplot(7,4,j)\n    plt.imshow(train_features[np.where(train_labels == np.array(i))[0][0]])\n    plt.axis('off')\n    plt.title(alpha[i],fontdict=dict({'fontsize' : 100}))\n    j=j+1\nmodel = keras.Sequential()\n\nmodel.add(keras.layers.Conv2D(32,(3,3),activation=\"relu\",padding=\"same\",input_shape=(200,200,3)))\nmodel.add(keras.layers.Conv2D(32,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.MaxPooling2D(3,3))\n\nmodel.add(keras.layers.Conv2D(64,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.Conv2D(64,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.MaxPooling2D(3,3))\n\nmodel.add(keras.layers.Conv2D(128,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.Conv2D(128,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.MaxPooling2D(3,3))\n\nmodel.add(keras.layers.Conv2D(256,(3,3),activation=\"relu\",padding=\"same\"))\nmodel.add(keras.layers.Conv2D(256,(3,3),activation=\"relu\",padding=\"same\"))\n\nmodel.add(keras.layers.Flatten())\n\nmodel.add(keras.layers.Dense(1568,activation=\"relu\"))\nmodel.add(keras.layers.Dropout(0.5))\n\nmodel.add(keras.layers.Dense(26,activation=\"softmax\"))\n\nopt = keras.optimizers.Adam(learning_rate=0.0001)\nmodel.compile(optimizer=opt,loss=\"sparse_categorical_crossentropy\",metrics=['accuracy'])\nmodel.summary()\ntrain_features = np.array(train_features)\ntrain_labels = np.array(train_labels) \nvalidation_features = np.array(validation_features)\nvalidation_labels = np.array(validation_labels)\nhistory = model.fit(train_features,\n          train_labels,\n          epochs=10, \n          validation_data = (validation_features,validation_labels))\n# Get training and test loss histories\ntraining_loss = history.history['loss']\ntest_loss = history.history['val_loss']\ntrain_acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\n#Create count of the number of epochs\nepoch_count = range(1, len(training_loss) + 1)\n\n# Visualize metrics\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\nplt.plot(epoch_count, training_loss)\nplt.plot(epoch_count, test_loss)\nplt.legend(['Train Loss', 'Test Loss'])\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\n\nplt.subplot(1,2,2)\nplt.plot(epoch_count, train_acc)\nplt.plot(epoch_count, val_acc)\nplt.legend(['Train Accuracy', 'Validation Accuracy'])\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.show()\ndel train_features\ndel train_labels\n\"\"\"\n<h1>Model Evaluation<\/h1>\n\"\"\"\ny_pred = np.argmax(model.predict(validation_features),1)\nprint(\"Precision : {:.2f} %\".format(precision_score(y_pred,validation_labels,average='macro')))\nprint(\"Recall    : {:.2f} %\".format(precision_score(y_pred,validation_labels,average='macro')))\nprint(\"F1 Score  : {:.2f} %\".format(precision_score(y_pred,validation_labels,average='macro')))\n\"\"\"\n<h1>Confusion Matrix<\/h1>\n\"\"\"\nplt.figure(figsize=(50,50))\ncm = confusion_matrix(validation_labels, y_pred.reshape(-1,1))\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm,\n                               display_labels=alpha)\nfig, ax = plt.subplots(figsize=(15,15))\ndisp.plot(ax=ax)","meta":"{'source': 'AI4Code', 'id': 'de3b0342fd6f91'}"}
{"id":"15218","text":"\"\"\"\n# KMeans- Exerc\u00edcios\n\"\"\"\n\"\"\"\n<font color=blue><b> Data Science do Zero<\/b><\/font><br>\n www.minerandodados.com.br  \n\"\"\"\n\"\"\"\n1) Importe as bibliotecas para visualiza\u00e7\u00e3o de dados e clustering.\n\"\"\"\nfrom sklearn.cluster import KMeans\nimport pandas as pd\nimport numpy as np\n\"\"\"\n2) Leia a base de dados **iris.csv** localizada no diretorio **datasets** e crie um Dataframe.\n\"\"\"\ndf = pd.read_csv(\"..\/input\/iris-flower-dataset\/IRIS.csv\")\ndf.head()\n\"\"\"\n3) Armazene apenas as **features e seus dados** na vari\u00e1vel train.\n\"\"\"\ntrain = df.species\n\"\"\"\n5) Armazene os dados de classes na vari\u00e1vel classes.\n\"\"\"\nclasses = df.drop('species', axis=1)\n\"\"\"\n6) Utilizando o c\u00f3digo abaixo, crie uma fun\u00e7\u00e3o que fa\u00e7a o **calculo da dist\u00e2ncia euclidiana entre dois vetores**.\n\"\"\"\n# Fun\u00e7\u00e3o que retorna a dist\u00e2ncia eucludiana de dois vetores de duas dimens\u00f5es.\nfrom sklearn.neighbors import DistanceMetric\ndef calcula_distancia(x,c):\n    dist = DistanceMetric.get_metric('euclidean')\n    return dist.pairwise(x,c)\n\"\"\"\n7) Utilizando a fun\u00e7\u00e3o **calcula_distancia** fa\u00e7a:\n\"\"\"\n\"\"\"\n- Calcule a dist\u00e2ncia entre os vetores **v1 e v2** abaixo\n> v1 = [[1.2,1,2.1,1]]<br>\n> v2 = [[1,1.9,5.4,3.2]]\n\"\"\"\nv1 = [[1.2,1,2.1,1]]\nv2 = [[1,1.9,5.4,3.2]]\n\ncalcula_distancia(v1,v2)\n\"\"\"\n- Calcule a dist\u00e2ncia entre os vetores **v3 e v4** abaixo e explique o retorno\n> v3 = [[0.5,0,2.1,1.5]]<br>\n> v4 = [[0.5,0,2.1,1.5]]\n\"\"\"\nv3 = [[0.5,0,2.1,1.5]]\nv4 = [[0.5,0,2.1,1.5]]\n\ncalcula_distancia(v3,v4)\n\"\"\"\n8) Inst\u00e2ncie o algoritmo Kmeans com o n\u00famero de clusters **igual ao n\u00famero de classes** da sua base de dados e execute o algoritmo KMeans.\n\"\"\"\nkmeans = KMeans(n_clusters=3)\n\"\"\"\n09) Imprima os valores dos **centroides**.\n\"\"\"\nkmeans.fit(classes)\ncentros = kmeans.cluster_centers_\ncentros\n\"\"\"\n10) Selecione **tr\u00eas amostras da base de dados e calcule a dist\u00e2ncia euclidiana entre as amostras de dados e cada um dos valores de centroids**.\n\"\"\"\n\"\"\"\n- DICA: Use um la\u00e7o for...\n\"\"\"\nimport random\nclasses[34:35]\nfor i in range(1,4):\n    num = round(random.uniform(1,50),0)\n    num_int = int(num)\n    print(\"Para a amostra de dado n\u00famero n\u00famero \", num_int,\" a dist\u00e2ncia para os centros \u00e9 de: \", calcula_distancia(classes[(num_int-1):num_int],centros))\n    print(\"\\n\")\n\"\"\"\n11) Gere a **tabela de dist\u00e2ncia** e verifique os valores atrav\u00e9s do m\u00e9todo fit_transform().\n\"\"\"\ndistancia = kmeans.fit_transform(classes)\ndistancia\n\"\"\"\n12) Utilizando o m\u00e9todo **predict()** defina novos valores de dados e fa\u00e7a a predi\u00e7\u00e3o.\n\"\"\"\nimport seaborn as sns\n\"\"\"\nVou gerar os gr\u00e1ficos da distribui\u00e7\u00e3o de tamanhos. Assim posso gerar valores aleatorios denrto dessas distribui\u00e7\u00f5es para fazer um m\u00e9todo predict a partir de dados gerados aleatoriamente.\n\"\"\"\nsns.kdeplot(classes.sepal_length,shade=True )\nsns.kdeplot(classes.sepal_width,shade=True )\nsns.kdeplot(classes.petal_length,shade=True )\nsns.kdeplot(classes.petal_width,shade=True )\nX = []\nnum1 = random.uniform(4,8)\nX.append(num1)\nnum2 = random.uniform(1.5,4.5)\nX.append(num2)\nnum3 = random.uniform(0,8)\nX.append(num3)\nnum4 = random.uniform(0,3)\nX.append(num4)\nX = np.array(X).reshape(1,4)\nX\ncalcula_distancia(X,centros)\n\"\"\"\nPercebi que o indice 0 corresponde a classe 2, o indice 1 corresponde a classe 0 e o indice 2 corresponde a classe 1. Ao gerar valores aleatorios varias vezes, pode-se ver isso**\n\"\"\"\nprint(kmeans.predict(X))\ni = 0\nwhile i < 10:\n    X = []\n    num1 = random.uniform(4,8)\n    X.append(num1)\n    num2 = random.uniform(1.5,4.5)\n    X.append(num2)\n    num3 = random.uniform(0,8)\n    X.append(num3)\n    num4 = random.uniform(0,3)\n    X.append(num4)\n    X = np.array(X).reshape(1,4)\n    print(\"Dado\", i+1, \"gerado: \", X,\"Distancia para os centros de: \", calcula_distancia(X,centros),\" Classifica\u00e7\u00e3o prevista: \", kmeans.predict(X))\n    i = i + 1\n\"\"\"\nComo pode ser visto no while acim. O indice 0 corresponde a classe 2, o indice 1 corresponde a classe 0 e o indice 2 corresponde a classe 1. Ao gerar valores aleatorios varias vezes, pode-se ver isso\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1bcb84b6a81ce3'}"}
{"id":"37633","text":"\"\"\"\n# Introduction\n\nIn this notebook, you will learn how to create your first graph with **networkx** and then jump to an example to see how graph theory can help you solve a real-life problem \n\"\"\"\n\"\"\"\n# Creating a network\n\"\"\"\n\"\"\"\nA **graph** (or a network) consists of a set of nodes and a set of edges. Edges connect one node to anothers. We are dealing with a **simple graph in this notebook**, one edge has exactly two endpoints and two points has at most one adjacent edge. An edge can have directions or not. An edge can have a **weight** (a positive real number) associated with it. \n\nA real-life example of a graph is the map system. Houses are nodes, route from one house to another is the edge, and weight is distance. Sometimes, all roads are two-way, we call this an **undirected** graph. If the road is one-way, we call it a **directed** graph.\n\nWe are going to create a visual of a undirected weighted graph (with edge weights).\n\"\"\"\nimport networkx as nx # The graph library\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom IPython.display import Image #For image\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings('ignore')\nG = nx.Graph() #Initialize\n\n#Creating set of nodes\nnodes = [\"A\", \"B\", \"C\", \"D\", \"E\",\"F\"]\nfor node in nodes:\n    G.add_node(node)\n\n#Creating a set of edges\nedges = {\"A\": [(\"B\",7), (\"C\",9), (\"F\",14)], #edges AB, AC, AF with weight 7, 9, 14 respectively\n         \"B\": [(\"A\",7),(\"C\",10), (\"D\",15)],\n         \"C\": [(\"A\",9), (\"B\",10), (\"D\",11), (\"F\",2)],\n         \"D\": [(\"B\",15), (\"C\",11), (\"E\",6)],\n         \"E\": [(\"D\",6), (\"F\",9)],\n         \"F\": [(\"A\",14), (\"C\",2), (\"E\",9)]\n        }\n\n#Add edges with direction to graph G\nfor node in edges.keys():\n    neighbors = edges[node]\n    for neighbor_node in neighbors:\n        G.add_edge(node, neighbor_node[0],weight=neighbor_node[1]) #Source node, node, weight\n\"\"\"\nIt's hard to put weight on edges using networkx, so I will just draw it with out label. \n\"\"\"\n#Graph edge with edge weight label is hard!\n#Let do it with out weight label\nnx.draw(G, with_labels=True, node_color=\"#1cf0c7\", \n        node_size=1500, alpha=0.7, font_weight=\"bold\", pos=nx.circular_layout(G)) #Adding pos make it look cleaner\n#Displays edges and edge weights of graph G\nprint(\"All the edges of G:\", G.edges)\nprint(\"Weight on edge FE:\", G.edges[('F', 'E')])\nprint(\"Neighbor node of F:\", ['F']) \n\"\"\"\n# Dijkstra's algorithm (shortest path)\n\npronounce: Diekstra\n\n**Dijkstra's algorithm** (or Dijkstra's Shortest Path First algorithm, SPF algorithm) is an algorithm for finding the shortest paths between nodes in a graph. A description of the algorithm can be found [here](https:\/\/www.geeksforgeeks.org\/dijkstras-shortest-path-algorithm-greedy-algo-7\/).\n\nBelow is a gif that sum of the process of finding the shortest path from node 1 to node 5.  (Source: wiki image)\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/5\/57\/Dijkstra_Animation.gif\">\n\"\"\"\n\"\"\"\nObserve that, there are many path from $1$ to $5$, but the shortest one is $1->3->6->5$ since the total distance is $9+2+9=20$\n\nSimilarly, we will use the graph created above and find the shortest path from A to E. It is a little bit hard to see, but A is equivalent to node 1, B is 2, C is 3, D is 4, and E is 5. Use your imagination to verify that these two graph are the same!\n\"\"\"\nnx.draw(G, with_labels=True, node_color=\"#1cf0c7\", \n        node_size=1500, alpha=0.7, font_weight=\"bold\", pos=nx.circular_layout(G)) #Adding pos make it look cleaner\n\"\"\"\nBelow are two set of codes which find the shortest path with weighted version (or all edge weight is 1) and with unweighted version\n\"\"\"\n#with no weight\nprint(\"Is there a path from A to E in graph G: \", nx.has_path(G, \"A\", \"E\"))\nprint(\"Shortest path from A to E not considering the weight: \",nx.shortest_path(G, \"A\", \"E\")) \nprint(\"Number of edges to get there (distance): \",nx.shortest_path_length(G, \"A\", \"E\"))\n\n#with weight\nprint(\"************************************************************\")\nprint(\"Dijkstra path from A to E: \",nx.dijkstra_path(G, \"A\", \"E\"))\nprint(\"The distance of that path\",nx.dijkstra_path_length(G, \"A\", \"E\"))\n\"\"\"\n## Centrality\n\nCentrality describes the influence\/importance of nodes in the graph. There are three metrics \n\n* **Degree-centrality**: The number of edges attached to a node divide by the maximum edges a node can have\n* **Closeness-centrality**: The reciprocal of the sum of the distances to all other nodes in the network \n* **Betweenness-centrality**: The number of shortest paths between all node pairs the node lies on divided by the maximum number of shortest-paths any one node in the network lies on.\n* **Eigenvalue-centrality**: An iterative algorithm that assigns relative influence to a node based on the number and importance of connected nodes. It can be very computationally expensive to compute for large networks. Google's PageRank algorithm is a variation of eigenvalue-centrality.\n\nAll of these metrics basically tell how important a node is. \n\"\"\"\nls ..\/input\/facebook\/facebook_network.png\nImage(filename = \"..\/input\/facebook\/facebook_network.png\")\n\"\"\"\nLet's create a same graph but with no weight\n\"\"\"\nG = nx.Graph() #Initialize\n\n#Creating Nodes\nnodes = [\"A\", \"B\", \"C\", \"D\", \"E\",\"F\"]\nfor node in nodes:\n    G.add_node(node)\n    \n#Adding edges\nedges = {\"A\": [(\"B\"), (\"C\"), (\"F\")],\n         \"B\": [(\"A\"),(\"C\"), (\"D\")],\n         \"C\": [(\"A\"), (\"B\"), (\"D\"), (\"F\")],\n         \"D\": [(\"B\"), (\"C\"), (\"E\")],\n         \"E\": [(\"D\"), (\"F\")],\n         \"F\": [(\"A\"), (\"C\"), (\"E\")]\n        }\n\nfor node in edges.keys():\n    neighbors = edges[node]\n    for neighbor_node in neighbors:\n        G.add_edge(node, neighbor_node) #Source node, node, weight\n        \nnx.draw(G, with_labels=True, node_color=\"#1cf0c7\", \n        node_size=1500, alpha=0.7, font_weight=\"bold\", pos=nx.circular_layout(G))\n\"\"\"\nCalculate the centrality of each nodes.\n\"\"\"\ndegrees = nx.degree_centrality(G)\ncloseness = nx.closeness_centrality(G)\nbetweeness = nx.betweenness_centrality(G)\neigs = nx.eigenvector_centrality(G)\n\ncentrality = pd.DataFrame([degrees, closeness, betweeness, eigs]).transpose()\ncentrality.columns = [\"degrees\", \"closeness\", \"betweeness\", \"eigs\"]\ncentrality = centrality.sort_values(by='eigs', ascending=False)\ncentrality\n\"\"\"\n# Application\n\nImagine that we want to design an online bookstore that has a recommendation feature for the user. There are two main keys: users and items. We have to choose which key is the node and which is the edge of our graph. If we choose the user as the node, we are using **User-Based Collaborative Filtering**. If we choose items as the nodes, we are using **Item-Based Collaborative Filtering**\n\n**User base:** When recommending items to a user whether they be books, music, movies, restaurants or other consumer products one is typically trying to find the preferences of other users with similar tastes who can provide useful suggestions for the user in question. With this, examining the relationships amongst users and their previous preferences can help identify which users are most similar to each other\n\n**Item base:** Alternatively, one can examine the relationships between the items themselves.\n\"\"\"\n\"\"\"\n# Example: Book Recommendation\n\nWe are going to create the a book recommendation using items base. The weight is already provided from the data\n\"\"\"\nls ..\/input\/edge-data\/books_data.edgelist\n#This data set contains node(book), its neighbors (similar book), and similarity score (weight)\ndf = pd.read_csv('..\/input\/edge-data\/books_data.edgelist', names=['source', 'target', 'weight'], delimiter=' ')\ndf.head()\n\"\"\"\nNote that the weight here represent the similarity of any two books\n\"\"\"\n#Load second data which has more detail\nmeta = pd.read_csv('..\/input\/edge-data\/books_meta.txt', sep='\\t')\nmeta.head()\n\"\"\"\nNote that **Clustering Coefficient** is s a measure of the degree to **which nodes in a graph tend to cluster together**. Evidence suggests that in most real-world networks, and in particular social networks, nodes tend to create tightly knit groups characterised by a relatively high density of ties; this likelihood tends to be greater than the average probability of a tie randomly established between two nodes (Holland and Leinhardt, 1971 Watts and Strogatz, 1998).\n\nThe (Local) **clustering coefficient** formula for a directed graph is:\n$$C_{i}={\\frac  {|\\{e_{{jk}}:v_{j},v_{k}\\in N_{i},e_{{jk}}\\in E\\}|}{k_{i}(k_{i}-1)}}$$\nwhere\n* $e_{jk}$ is edge between nodes $v_j$ and $v_k$\n* $N_{i}$ is the neighbor of node $v_i$\n* $k_i$ is the number neighbor nodes of $v_i$. Note that there are $k_{i}(k_{i}-1)$  links that could exist among the vertices within the neighbourhood $N_i$\nFor a undirected graph, just multiply the formula by 2. More about it [here](https:\/\/en.wikipedia.org\/wiki\/Clustering_coefficient).\n\"\"\"\n#Type your preference book here\nGOT = meta[meta.Title.str.contains('Harry Potter and the Order of the Phoenix')]\nGOT\n\"\"\"\nThe code bellow will \n\n1) Identify the node correspond to the book\n\n2) Find its neighbors and sort by weight. \n\n3) Display the top ten books\n\"\"\"\nrec_dict = {}\nid_name_dict = dict(zip(meta.ASIN, meta.Title))\nfor row in GOT.index:\n    book_id = GOT.ASIN[row]\n    book_name = id_name_dict[book_id]\n    most_similar = df[(df.source==book_id)\n                      | (df.target==book_id)\n                     ].sort_values(by='weight', ascending=False).head(10)\n    most_similar['source_name'] = most_similar['source'].map(id_name_dict)\n    most_similar['target_name'] = most_similar['target'].map(id_name_dict)\n    recommendations = []\n    for row in most_similar.index:\n        if most_similar.source[row] == book_id:\n            recommendations.append((most_similar.target_name[row], most_similar.weight[row]))\n        else:\n            recommendations.append((most_similar.source_name[row], most_similar.weight[row]))\n    rec_dict[book_name] = recommendations\n    print(\"Recommendations for:\", book_name)\n    for r in recommendations:\n        print(r)\n    print('\\n')\n\"\"\"\n### References\nAll about drawing graph [here](https:\/\/qxf2.com\/blog\/drawing-weighted-graphs-with-networkx\/)\n\nHow weight between two books is calculated: [Association Rules Generation from Frequent Itemsets](http:\/\/rasbt.github.io\/mlxtend\/user_guide\/frequent_patterns\/association_rules\/#example-1-generating-association-rules-from-frequent-itemsets)\n\nThere are also alternative approaches to [recommendations systems](https:\/\/www.researchgate.net\/publication\/256458336_Basic_Approaches_in_Recommendation_Systems)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '454fe6f3d0452a'}"}
{"id":"38346","text":"\"\"\"\n*****Hotel Booking Prediction - with Data Analysis and Logistic Regression***\n\nImporting the Libraries:\nTo access the data, which is available in CSV, and further manipulate it, we'll use **pandas**. To do operations on the data, we'll use **numpy**.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\"\"\"\nImporting the dataset.\n\"\"\"\ndata = pd.read_csv('\/kaggle\/input\/hotel-booking-demand\/hotel_bookings.csv')\n\"\"\"\n**Analysing the Data**\n\nLet's first have a look at the dataset and let's try to get an essence of the information it contains.\n\"\"\"\ndata.head(10)\ndata.shape\n\"\"\"\nWe can see that there are 32 features (columns) and 119390 records (rows) in our dataset.\n\nOur main objective with this data is to predict if the booking would be made by a customer, provided if they make a reservation within the constraints of out data.\n\nSince, we have defined our objective, let's see which all features (columns) won't be any use to us for finding the objective.\n\nUpon inspecting, we can see that the following features won't be useful for our objective:\n1. hotel - It doesn't matter which type of hotel they make a reservation, the main objective is to see if they make ANY type of reservation at all or not\n2. agent - The agent that got the reservation for us won't matter\n3. company - Same logic goes for company as for the agent\n4. reservation_status_date - We have other features (like: arrival_date_week_number, arrival_date_day_of_month etc) that gives us the same information\n\nHence all these 4 columns need to be dropped from the data.\n\"\"\"\ndata.drop(inplace=True, axis=1, labels=['agent', 'company','hotel','reservation_status_date'])\n\"\"\"\nNote:\n* inplace = True - The changes will be reflected in the original dataframe\n* axis = 1 - inferring that the columns are to be dropped\n* labels = [...] - The names of the columns that need to be dropped\n\n*P.S. Dropping of these columns is just based on my intution and hence you can probably use all of these columns and decide to drop some other, or maybe none. Therefore, it's recommended to play with the data and have an iterative approach to solving the problem*\n\"\"\"\n\"\"\"\nIt will be interesting to have a look at all the unique values that every column contains\n\"\"\"\ncols = data.columns\nfor i in cols:\n    print('\\n',i,'\\n',data[i].unique(),'\\n','-'*80)\n\"\"\"\nLet's check for any null values, if there are any, in the remaining dataset.\n\"\"\"\ndata.isnull().sum()\n\"\"\"\nAs it can bee seen, only 'country' column has null values. We can deal with this by choosing one of the following methods:\n1. Replacing the null values with the most frequent value in the column (In this case, it would be the most frequent country).\n2. Deeting the records (rows) which contains the null values\n3. Developing a model to predict the null values from existing data.\n\nAll the above mentioned solutions are good solutions for a dataset of this many records. I decided to choose the 1st solution as it is the most easily implemented solution.\n\"\"\"\ndata.fillna(data.mode().iloc[0], inplace=True)\n\"\"\"\nNote: 'mode()', will replace the 'NaN's with most frequent value in the column.\n\nLet's check again for the null values and have a look at how our data looks now\n\"\"\"\ndata.isnull().sum()\ndata.head()\n\"\"\"\nAs we can see, there are only 28 features left, after we removed 4 columns from our data and there are no null values left in our data.\n\nLet's now seperate the dependant and independant variables from each other. The independant variable, which we eventually need to predict, would be the 'is_cancelled' column as it tells us if the that particular reservation was cancelled or not. If the reservations was cancelled, the 'is_cancelled' column would hold the value '1' for that particular record, otherwise it would hold the value '0'.\n\"\"\"\nX = data.iloc[:,1:]\ny = data.iloc[:,0]\n\"\"\"\nNow, we can see that our data doesn't only have numerical values but it also has strings as values. Machine Learning models, since they work with distances such as Euclidean, Manhattan, Minkowski etc, which all require nuumeric values to be accessed, required all the values to be numerics. Hence, we convert all the categorical variables (columns with string values) to numeric representations. And to do that, we will be using One Hot Encoder.\n\"\"\"\n# Importing relevant libraries\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import make_column_transformer\n#Implementing Column Transformer\nct = make_column_transformer(\n    (OneHotEncoder(),['meal','distribution_channel','reservation_status','country','arrival_date_month','market_segment','deposit_type','customer_type', 'reserved_room_type','assigned_room_type' ]), remainder = 'passthrough'\n    )\n\"\"\"\nHere, the Column Transformer is given the One Hot Encoder and the list of all categorical columns. Now, we simply need to apply fit and transform to our independant variables.\n\"\"\"\nX = ct.fit_transform(X).toarray()\n\"\"\"\nPlease note that 'X' is no longer a dataframe, it has been changed to numpy array and the number of columns has also been increased from 28 to 256. This is because the One Hot Encoder has converted each unique value of every categorical variable to its dedicated column.\n\"\"\"\nX\ny\n\"\"\"\nPerfect.\n\nNow, we need to split our data into training and test sets.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\"\"\"\nNote: We are spliting the training and test set with 20% records in the test set and remaining 80% in the training. You can play with this number if you think it will have serious impact on the prediction rate.\n\nAnother important note to make here is that we just saw the number of features exploding from just 28 to 256. That's a huge number. Generally, more number of features in any dataset leads to the [curse of dimensionality](https:\/\/en.wikipedia.org\/wiki\/Curse_of_dimensionality). It simply means that our model will have too many unncessary information to process, which will eventually hamper its processing time and efficiency.\n\nTo avoid the curse of dimensionality, we use something known as [Dimensionality Reduction](https:\/\/en.wikipedia.org\/wiki\/Dimensionality_reduction) algorithms. One of the most used one is known as [PCA - Principal Component Analysis](https:\/\/en.wikipedia.org\/wiki\/Principal_component_analysis). We are going to use the same. However, one small requirement of PCA is that the data it is applied on should have a sandar scale. Which can be achieved by sklearn's [Standard Scalar](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.preprocessing.StandardScaler.html) function as follows\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\nprint(\"X_train ---------->\\n\", X_train, \"\\nX_test -------->\\n\", X_test)\n\"\"\"\nAs you can see, now all the values are in a standardised scale.\n\nNow, we can safely implement PCA.\n\"\"\"\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 100)\nX_train = pca.fit_transform(X_train)\nX_test = pca.transform(X_test)\nexplained_variance = pca.explained_variance_ratio_\n\"\"\"\nPlease note that upon running the PCA for the first time, set 'n_components' to 'None' and then evaluate the 'explained_variance' variable for choosing the optimal number of n_components. In this case, 100 should be fine.\n\nNow, we are finally done with everything else except fitting the Logistic Regression model on our data. Let's do that now.\n\n**Logistic Regression**\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state = 0, max_iter=1000)\nclassifier.fit(X_train, y_train)\n\"\"\"\nNow, let's see how our model performs on the test data\n\"\"\"\ny_pred = classifier.predict(X_test)\n\"\"\"\nTo calculate the accuracy of our model, the simplest way is to construct a confusion matrix\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\ncm\n\"\"\"\nAccuracy can be calculated as:\n\n14917 + 8932 (Total number of correct predictions) \/ 14917 + 8932 + 17 + 12 (Total number of predictions) \n\n= 23849 \/ 23878 * 100 \n\n= 99.87%\n\nThat's a GREAT accuracy rate.\n\nBUT\n\nThis certainly is overfitted. Having such a high accuracy on any dataset should always ring bells since most of the times, it's an indication of our model being overfitted.\nI'll try to improve the accuracy to a realistic score, but for now, the basics are all set up.\n\n\n**Hope this was useful. Please leave suggestions, mistakes or any other tips in the comments. \n**\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '469f5d24321950'}"}
{"id":"36043","text":"\"\"\"\n# Topic Modelling on NeurIPS Papers\n\nIn this notebook, we will explore a dataset containing more than 9,000 documents, which are papers from <br>\nThe Conference and Workshop on Neural Information Processing Systems (abbreviated as NeurIPS and formerly NIPS). <br>\nIt is a machine learning and computational neuroscience conference. <br>\n<br>\nWe will conduct LDA topic modelling on these papers, and explore the groups in an interative manner.\n\nTable of Content\n* Environment Setup\n* Load and Preprocess Data\n* Word Cloud\n* LDA Topic Modelling\n* Result Visualisation\n* Further Study\n\"\"\"\n\"\"\"\n<a id=\"#section-1\"><\/a>\n# Environment Setup\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n<a id=\"#section-2\"><\/a>\n# Load and Preprocess Data\n\"\"\"\ndf = pd.read_csv('..\/input\/nips-papers-1987-2019-updated\/papers.csv')\ndf\n\"\"\"\nA quick look on missing data. <br>\nIn this notebook we will focus on topic-modelling on `full_text`[](http:\/\/) column only, which has no missing data. <br>\nGood to go.\n\"\"\"\nimport seaborn as sns\n\nsns.heatmap(df.isna())\n\"\"\"\nPreprocess the `full_text` column with a series of functions. <br>\nThe operations are quite obvious from their function names so not to be repeated here. <br>\nLemmatization instead of Port Stemmer is used to preserve more meaningful full words from the documents. <br>\nNoun is used as the part of speech in lemmatization.\n\"\"\"\n%%time\n# 2min 30s\nimport nltk\nfrom gensim.parsing.preprocessing import strip_tags, strip_punctuation, strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short, preprocess_string\n\nlemmatizer = nltk.stem.wordnet.WordNetLemmatizer()\n\ndf['full_text'] = df['full_text'].astype('str')\ndf['full_text_tokenized'] = df['full_text'].apply(lambda text: preprocess_string(text, [\n    strip_tags, \n    strip_punctuation, \n    strip_multiple_whitespaces, \n    strip_numeric, \n    remove_stopwords, \n    strip_short, \n    lemmatizer.lemmatize, \n    lambda x: x.lower()\n]))\ndf['full_text_tokenized'].sample(n=20)\n\"\"\"\nA quick look on tokenized documents' lengths\n\"\"\"\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12, 4))\ndf['full_text_tokenized_len'] = df['full_text_tokenized'].apply(lambda text: len(text))\nsns.histplot(df[df['full_text_tokenized_len'] > 0]['full_text_tokenized_len'], log_scale=True)\nplt.show()\n\"\"\"\n<a id=\"#section-3\"><\/a>\n# Word Cloud\nNext, the typical word cloud. <br>\nNot surpisingly, machine learning, processing system, neural network, information processing, reinforcement learning, loss function are some common terms.\n\"\"\"\n%%time\n# 2min 50s\nfrom wordcloud import WordCloud\n\nlong_string = ' '.join([' '.join(words) for words in df['full_text_tokenized'].values])\nwordcloud = WordCloud(width=800, height=400)\nwordcloud.generate(long_string)\nwordcloud.to_image()\n\"\"\"\n<a id=\"#section-4\"><\/a>\n# LDA Topic Modelling\n\nWe will go through the following steps:\n* Create a \"dictionary\" containing all unique words in all documents\n* Create a \"corpus\". Each document will be converted into a bag of words, e.g. [(0, 1), (1, 1), (4, 2), ...]. <br> \nEach tuple means (word index, word occurrence in the document)\n* Train the LDA model. Tune hyper-parameter `passes` and `iterations` until most documents are \"converged\"\n* Visualise the result, exploring different groups of documents\n\"\"\"\n%%time\n# 30s\nimport gensim\n\ndictionary = gensim.corpora.Dictionary(df['full_text_tokenized'].values)\ndictionary.filter_extremes(no_below=20, no_above=0.5)\n%%time\n# 13.2s\ncorpus = [dictionary.doc2bow(doc) for doc in df['full_text_tokenized'].values]\nprint(f'Number of unique tokens: {len(dictionary):,}')\nprint(f'Number of documents: {len(corpus):,}')\n%%time \n# 13mins\nimport logging\nfrom gensim.models.ldamulticore import LdaMulticore\n\n# Take too much time for kaggle save version. Set it to True during development.\nenable_debug = False\n\nif enable_debug:\n    for handler in logging.root.handlers[:]:\n        logging.root.removeHandler(handler)\n    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s')\n    logger = logging.getLogger()\n    logger.setLevel(logging.DEBUG)\n\nmodel = LdaMulticore(corpus, num_topics=10, id2word=dictionary, passes=40, iterations=100)\n\nif enable_debug:\n    logger.setLevel(logging.WARNING)    \n\"\"\"\n`passess` and `iterations` are tuned to be high enough so that most of the documents are converged at the last pass.\nBelow are some logs when running the cell in DEBUG logging mode:\n\n> 2021-03-15 15:28:37,074 : DEBUG : 1666\/2000 documents converged within 100 iterations <br>\n2021-03-15 15:28:40,471 : DEBUG : 1509\/2000 documents converged within 100 iterations <br>\n2021-03-15 15:28:42,532 : DEBUG : 1454\/2000 documents converged within 100 iterations <br>\n2021-03-15 15:28:46,568 : DEBUG : 1489\/2000 documents converged within 100 iterations <br>\n2021-03-15 15:28:49,296 : DEBUG : 1265\/1680 documents converged within 100 iterations <br>\n\"\"\"\n\"\"\"\n<a id=\"#section-5\"><\/a>\n# Result Visualisation\n\nHere comes the fruit. <br>\nWe will use gensim model's `print_topics` function to see popular terms in each group. <br>\nAlso, pyLDAvis will be used to see the groups in a graph. <br>\n\"\"\"\nmodel.print_topics(num_topics=10)\n%%time\nimport pyLDAvis\nimport pyLDAvis.gensim\n\nprep_display = pyLDAvis.gensim.prepare(model, corpus, dictionary)\npyLDAvis.display(prep_display)\n\"\"\"\n<a id=\"#section-6\"><\/a>\n# Further Study\n\nHere are some possible directions to study the dataset further:\n* Change `num_topics` from 10 to 20, 50, etc to explore more detailed papers groupings\n* Compare and contrast the resulted groups using other simlarity algorithms such as TF-IDF, LSA\n\"\"\"\n\"\"\"\n# Thank you for reading\n\nLet me know your thoughts in the comments below :D \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4261c72830e52c'}"}
{"id":"132174","text":"\"\"\"\n# Project: Medical Appointment No Shows\n\n**!this is a WIP!**\n\nThis is my second real project related to my Udacity's nanodegree and its purpose is only to:\n- wrangling the data\n- make analysis based on my questions\n- draw conclusions about my findings\n\nI choose this problem because: \n- I live in Brazil and this motivate's me \n- This problem is on Kaggle so\n  - I can get inspiration in other kernel's as I'm starting in this area\n  - I can publish my first kernel\n  - I'm publishing as a public kernel and that point already cover the step four of the project **\"Share your findings\"**\n\n\n## Table of Contents\n<ul>\n<li>\n    <a href=\"#intro\">1. Introduction<\/a>\n    <ul>\n        <li><a href=\"#first-impressions\">1.1. First impressions<\/a><\/li>\n        <li><a href=\"#questions\">1.2. Questions<\/a><\/li>\n    <\/ul>\n<\/li>\n<li>\n    <a href=\"#wrangling\">2. Data Wrangling<\/a>\n    <ul>\n        <li><a href=\"#general-properties\">2.1. General Properties<\/a><\/li>\n        <li><a href=\"#data-cleaning\">2.2. Data Cleaning<\/a><\/li>\n    <\/ul>\n<\/li>\n<li>\n    <a href=\"#eda\">3. Exploratory Data Analysis<\/a>\n    <ul>\n        <li>\n            <a href=\"#age\">3.1. Age<\/a>\n        <\/li>\n        <li>\n            <a href=\"#waiting-days\">3.2. Waiting days<\/a>\n            <ul>\n                <li><a href=\"#analysing-the-decrease-after-a-month\">3.2.1. Analysing the decrease after a month<\/a><\/li>\n            <\/ul>\n        <\/li>\n        <li>\n            <a href=\"#received-sms\">3.3. Received sms<\/a>\n        <\/li>\n        <li>\n            <a href=\"#appointment-week-day\">3.4. Appointment week day<\/a>\n        <\/li>\n        <li>\n            <a href=\"#gender\">3.5. Gender<\/a>\n        <\/li>\n        <li>\n            <a href=\"#neighbourhood\">3.6. Neighbourhood<\/a>\n        <\/li>\n        <li>\n            <a href=\"#patient-id\">3.7. Patient Id<\/a>\n        <\/li>\n        <li>\n            <a href=\"#answering-questions\">3.8. Answering questions<\/a>\n        <\/li>\n    <\/ul>\n<\/li>\n<li><a href=\"#conclusions\">4. Conclusion<\/a><\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id='intro'><\/a>\n## 1. Introduction\n\nThis analysis consist in explore a dataset containing aproximately 100k medial appointments from the Brazilian public health system known as [SUS (Single Health System)](https:\/\/en.wikipedia.org\/wiki\/Sistema_%C3%9Anico_de_Sa%C3%BAde). We're gonna explore the [*no-show appointments dataset*](https:\/\/www.kaggle.com\/joniarroba\/noshowappointments) dataset using this variables:\n\n- **PatientId:** Identification of a patient \n- **AppointmentID:** Identification of each appointment \n- **Gender:** Male or Female \n- **DataMarcacaoConsulta:** The day of the actuall appointment, when they have to visit the doctor \n- **DataAgendamento:** The day someone called or registered the appointment\n- **Age:** How old is the patient \n- **Neighbourhood:** Where the appointment takes place\n- [**Scholarship:**](https:\/\/en.wikipedia.org\/wiki\/Bolsa_Fam%C3%ADlia) True or False, indicates if the patient is in the *Bolsa Familia* program\n- **Hipertension:** True or False\n- **Diabetes:** True or False \n- **Alcoholism:** True or False \n- **Handcap:** True or False \n- **SMS_received:** 1 or more messages sent to the patient \n- **No-show** \"No\" indicates if the patient showed up to their appointment and \"Yes\" if they didn't show up\n\nWe're aiming to find possible reasons for patient no-showing at the scheduled appointments.\n\"\"\"\n# first let's load our data\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\ndf = pd.read_csv(\"..\/input\/medicalappointmentnoshown\/KaggleV2-May-2016.csv\")\ndf.head(5)\n# let's see from which period theese appointments are\ndf.AppointmentDay.min(), df.AppointmentDay.max()\n# then let's see the shape of our data\ndf.shape\n# and get general numeric attributes\ndf.describe()\n\"\"\"\n<a id=\"first-impressions\"><\/a>\n### 1.1. First impressions\n\nFirst of all, we can notice that:\n- We have 110k+ rows and 14 columns in this dataset (as explained on the challenge overview)\n- I want to check if the patientId is duplicated since I don't know if they can have more than one appointment\n- Depending on the analysis, maybe the **PatientId**, **AppointmentID** and **Neighbourhood** be useless for the analysis\n- It's important to highlight that the **No-show** column value **Yes** means that the pacient didn't show at the appointment\n\nAlso we can already draw some assumptions:\n- there are more than 100k appointments scheduled in a period of ~2 months and that's really impressive\n- most of the patients have about 37 yeas old with almost no scholarship (9%)\n- in mean \n  - 19% of the patients have hipertension\n  - 7% of the patients have diabetes\n  - 3% of the patients suffers from alcoholism\n  - 2% of the patients are handicapped\n  \nI'll analyse the **\"No-Show\"** as my dependent variable since to me it's the most important one and it's strongly related to what we want to discover here.\n\nAnd I'll use all dataset variables in my analysis, I just want to check on the **Data wrangling** stage if we really need the:\n- Patient id\n- Appointment id\n- Neighbourhood\n\nSince it look's like this variables are not that important for this analysis.\n\n<a id=\"questions\"><\/a>\n### 1.2. Questions\n\nThe main questions I want to answer are:\n- Based on the variables we have, what is the most relevant factor that is influencing the patient to no showing the medical appointment?\n- There are any relation on these variables that can lead us to a more specific group of patients?\n- The day of the week of the appointment influences the patient no showing?\n- The waiting time of the patient between the schedule day and the appointment day influences it's no showing?\n- There are patients no showing in appointments on the same day?\n\n<a id='wrangling'><\/a>\n## 2. Data Wrangling\n\nIn this section the data will be analysed and cleaned, dealing with missing values or weird values.\nAlso we're gonna explore in a deeper lever in a way that maybe we can formulate more questions.\n\n<a id=\"general-properties\"><\/a>\n### 2.1. General Properties\n\nHere we're gonna explore our dataset properties checking for:\n- What kind of variables we need to:\n  - convert the data type\n  - drop from the dataset\n- Check for duplicates\n- Check for weird values (outliers)\n- Gather more information about a specific variable\n- Check if we need to create more columns with usefull data for the exploration\n\"\"\"\n# checking column information for missing values and strange types\ndf.info()\n# checking for general data duplicates\ndf.duplicated().sum(), df.PatientId.duplicated().sum(), df.AppointmentID.duplicated().sum()\n# checking all possible values on some columns\nprint(df.Gender.unique())\nprint(sorted(df.Age.unique()))\nprint(sorted(df.Neighbourhood.unique()))\nprint(df.Scholarship.unique())\nprint(df.Hipertension.unique())\nprint(df.Diabetes.unique())\nprint(df.Alcoholism.unique())\nprint(df.Handcap.unique())\nprint(df.SMS_received.unique())\nprint(df['No-show'].unique())\n\"\"\"\nIt looks like we have a good dataset: \n- no missing lines \n- we discover that indeed we need the **Patient ID** since it seems some patients try to make new appointments\n- there are no weird values on most columns\n\nBut we'll need to do some cleaning here:\n- we need to fix some data typings\n  - ScheduledDay and AppointmentDay makes sense to be a date\/datetime type\n  - No-Show makes sense to be a boolean\n  - PatientId makes sense to be converted as string to prevent from being applied as a numerical operation since it represents the patient identification\n- **Appointment ID** seems to not be usefull for this analysis\n- **Handcap** variable have values beyond True and False, and we can see [here](https:\/\/www.kaggle.com\/joniarroba\/noshowappointments\/discussion\/29699#229356) that this occurs because the handcap field represents the number of patient disabilities\n\nAnd we can also make more questions:\n- On the problem summary they don't mention on which location we're analysing, I've thought that we're analysing data from several cities from Brazil, but it seams that we're seing a specific region\n  - We can see [here](https:\/\/www.kaggle.com\/joniarroba\/noshowappointments\/discussion\/38330#) that this dataset contains appointments from *Vit\u00f3ria - ES* in Brazil and this turns out to be even more impressive that there are more than 100k schedulled in a ~2 month period in 2016\n  \nNow we can analyse also the neighbourhood data either!\n\n<a id=\"data-cleaning\"><\/a>\n### 2.2. Data Cleaning\n\nHere we're need to:\n- remove useless columns\n- rename the columns to use easier names during the exploration while fixing typos\n- format patient id column to string\n- format all date related columns to the correct type\n- remove the weird age value that is less than zero\n- format the handicap field correctly, since we only want to know if the patient is handicap and not how many disabilities they have\n- add new columns\n  - appointment_week_day: to show what day of the week the appointment was scheduled\n  - appointment_waiting_time: waiting time to the appointment\n\"\"\"\n# let's remove some useless columns\n# I think the appointmentID is useless for this analysis\ndf.drop(['AppointmentID'], axis=1, inplace=True)\ndf.columns\n# renaming all columns to simpler names for our exploration\ndf.rename(columns={'PatientId': 'patient_id', 'ScheduledDay': 'scheduled_day', 'AppointmentDay': 'appointment_day', 'SMS_received': 'received_sms', 'No-show': 'no_show', 'Handcap': 'handicap' }, inplace=True)\ndf.rename(columns=lambda x: x.lower(), inplace=True)\ndf.columns\n# formatting the patient_id column as string\ndf.patient_id = df.patient_id.apply(lambda patient: str(int(patient)))\n# formatting the date time 'scheduled_day' and 'appointment_day' columns\n# i'm just testing different forms of time conversion here\ndf.scheduled_day = pd.to_datetime(df.scheduled_day)\ndf.appointment_day = df.appointment_day.apply(np.datetime64)\n\ndf.scheduled_day.head(1), df.appointment_day.head(1)\n# formatting the 'no_show' column with lower cases\ndf.no_show = df.no_show.map({ 'No': 'no', 'Yes': 'yes' })\n\ndf.no_show.unique()\n# discart the ages bellow zero\ndf = df.query('age >= 0')\nprint(sorted(df.age.unique()))\n# remove the weird values from handcap variable\ndf.loc[df.handicap > 1, 'handicap'] = 1\ndf.handicap.unique()\n# creating the first column \"appointment_week_day\"\ndf['appointment_week_day'] = df.appointment_day.map(lambda day: day.day_name())\ndf.appointment_week_day.head()\n# creating the second column \"appointment_waiting_time\"\ndf[\"appointment_waiting_days\"] = df.appointment_day - df.scheduled_day\ndf.appointment_waiting_days.head()\n# well it seams that some are treated on the same day that they scheduled\n# we can prevent that weird value by calculating the the \"absolute value\" of this column\n# and then converting the \"time\" to \"days\"\ndf.appointment_waiting_days = df.appointment_waiting_days.abs().dt.days\ndf.appointment_waiting_days.head(10)\n# let's see how our data looks like after all cleanning\ndf.head(5)\n\"\"\"\nIt seams we have all the data we need to start exploring and answer the questions.\n\n<a id='eda'><\/a>\n## 3. Exploratory Data Analysis\n\nFirst, let's review all questions that I want to answer:\n\n- Based on the variables we have, what is the most relevant factor that is influencing the patient to no showing the medical appointment?\n- There are any relation on these variables that can lead us to a more specific group of patients?\n- The day of the week of the appointment influences the patient no showing?\n- The waiting time of the patient between the schedule day and the appointment day influences it's no showing?\n- There are patients no showing in appointments on the same day?\n\nLet's:\n- analyse our data\n- mix them up\n- get assumptions along the way\n- answer our questions\n\"\"\"\n# first let's re-see our dataset description\ndf.describe()\n# and plot basic histogram charts\ndf.hist(figsize=(15, 8));\n\"\"\"\n- most of the patients \n  - are bellow 60 years old\n  - doesn't suffer from alcoholism\/diabetes\/hipertension\n  - are not handicapped\n  - doesn't received a reminder sms\n  - aren't in the \"Bolsa familia\" program\n  - doesn't missed the appointment\n\nI think in this case the **age** is the most relevant variable that we can analyse, since it's the only one that have a better distribution between the amount of patients.\n\nAlso we can check out the **appointment_waiting_days** since it's one of the most relevant variables that we can mix up. \n\nAnd the **received_sms** since it is a 75 percentile and is the variable that have the most difference between the other boolean variables.\n\nI'll se this variables one by one a mix them up with our categorical variables:\n- appointment_week_day\n- gender\n- neighbourhood\n- patient_id\n\"\"\"\ndef show_no_show_trend(dataset, attribute, fit_reg = True):\n    '''Prints a chart with no_show_rate explanation\n    Syntax: show_no_show_trend(dataframe, attribute), where:\n        attribute = the string representing the attribute;\n        dataframe = the current dataframe;\n    '''\n    return sns.lmplot(data = dataset, x = attribute, y = 'no_show_rate', fit_reg = fit_reg, legend = True, height=8, aspect=2)    \n\ndef show_attribute_statistics(attribute, dataframe, scale = 0.06, sorter = False, verticalLabel = False):\n    '''Prints basic statistics from the attribute also plotting the basic chart. \n    Syntax: show_attribute_statistics(dataframe, attribute), where:\n        attribute = the string representing the attribute;\n        dataframe = the current dataframe;\n        scale = what's the scale you want to converto;\n        sorter = array representing the sort reindex;\n    '''\n    \n    # grouping by the patients by attribute and see if there is any interesting data related to their no showing\n    # also stripping unwanted attributes with crosstab - https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/api\/pandas.crosstab.html\n    dataset = pd.crosstab(index = dataframe[attribute], columns = dataframe.no_show).reindex(sorter).reset_index() if sorter else pd.crosstab(index = dataframe[attribute], columns = dataframe.no_show).reset_index()\n    \n    # replacing all none values with zero, since it's the count of patients on that categorie\n    dataset['no'].fillna(value=0, inplace=True)\n    dataset['yes'].fillna(value=0, inplace=True)\n\n    # let's also record the rate of no-showing base on the attribute\n    dataset[\"no_show_rate\"] = dataset['yes'] \/ (dataset['no'] + dataset['yes'])\n    dataset.no_show_rate.fillna(value=0.0, inplace=True)\n\n    dataset[\"no_show_rate_value\"] = dataset[\"no_show_rate\"] * 100 \n    dataset.no_show_rate_value.fillna(value=0.0, inplace=True)\n    \n    # plotting our data\n    plt.figure(figsize=(30, 10))\n\n    # scale data if needed\n    dataset['no'] = dataset['no'] * scale\n    dataset['yes'] = dataset['yes'] * scale\n\n    # line chart\n    plt.plot(dataset.no_show_rate_value.values, color=\"r\")\n\n    # bar chart\n    plt.bar(dataset[attribute].unique(), dataset['no'].values, bottom = dataset['yes'].values)\n    plt.bar(dataset[attribute].unique(), dataset['yes'].values)\n\n    # configs\n    if (verticalLabel):\n        plt.xticks(rotation='vertical')\n        \n    plt.subplots_adjust(bottom=0.15)\n    plt.xlabel(attribute, fontsize=16)\n    plt.ylabel(f\"amount of patients (scaled 1 to {scale * 100}%)\", fontsize=16)\n    plt.legend([\"not attended rate\", \"attended\", \"not attended\"], fontsize=14)\n\n    plt.title(\"amount of patient by no show appointment groupped by %s\" % attribute)\n\n    plt.show();\n    \n    return dataset\n\"\"\"\n<a id=\"age\"><\/a>\n### 3.1. Age\n\"\"\"\nage_dataset = show_attribute_statistics(\"age\", df);\nshow_no_show_trend(age_dataset, \"age\");\n\"\"\"\nThrough the charts above, it becomes evident that the **no-showing rate decreases as older the person is**.\n\nIt reaches higher rates when the patient is a baby\/child maybe because:\n- parents or guardians may have difficulties bringing the child to the appointment\n- or maybe because there was a long wait until the attendance (but we'll se more about that later)\n\nWe have one outlier in ~120 years old patients, but we can ignore that case since we have only one patient.\n\n<a id=\"waiting-days\"><\/a>\n### 3.2. Waiting days\n\"\"\"\nappointment_waiting_days_dataset = show_attribute_statistics(\"appointment_waiting_days\", df)\nshow_no_show_trend(appointment_waiting_days_dataset, \"appointment_waiting_days\")\n\"\"\"\nIn the age case, maybe it's nicer if we can group that data, since we have a large amount of distribution between the points.\n\nSo I'll group by based on the user [tsilveira](https:\/\/www.kaggle.com\/tsilveira\/applying-heatmaps-for-categorical-data-analysis) on his kernel and using the cut method explained on [this article](https:\/\/www.analyticsvidhya.com\/blog\/2016\/01\/12-pandas-techniques-python-data-manipulation\/)\n\nSo I'll categorize the data in these groups:\n\n| waiting time | days |\n| -- | -- |\n| same day | 0 |\n| week | 1 - 7 |\n| month | 8 - 30 |\n| quarter | 31 - 90 |\n| semester | 91 - 180 |\n| a lot of time | > 180 |\n\"\"\"\ncategories = pd.Series(['same day: 0', 'week: 1-7', 'month: 8-30', 'quarter: 31-90', 'semester: 91-180', 'a lot of time: >180'])\ndf['waiting_days_categories'] = pd.cut(df.appointment_waiting_days, bins = [-1, 0, 7, 30, 90, 180, 500], labels=categories)\nwaiting_days_categories_dataset = show_attribute_statistics(\"waiting_days_categories\", df, 0.005)\nshow_no_show_trend(waiting_days_categories_dataset, \"waiting_days_categories\", False)\n\"\"\"\nThrough the chart above, it becomes evident that the **no-showing rate increases as times goes by until it reach a quarter**.\n\nIt reaches lower rates when the patient is attended on the same day that this may happen depending on the urgency or even if they go to the health center withou any scheduling.\n\nOne interesting thing is the fact of the rate start decreasing after a quarter of waiting time.\n\nWe can get the group of patients that are attended on the same day and analyse it's differences from patients from other groups.\n\n<a id=\"analysing-the-decrease-after-a-month\"><\/a>\n#### 3.2.1. Analysing the decrease after a month\n\nJust to see what's de difference between the semester group from others, let's split our data in groups:\n- Attended on \n  - same day\n  - between a week and a month\n  - quarter\n  - after a quarter (90 days)\n\"\"\"\n# splitting data in groups\nsame_day_category = df[df.waiting_days_categories == categories[0]]\nshort_period_category = df.query(f\"waiting_days_categories in ['{categories[1]}', '{categories[2]}']\")\nquarter_category = df[df.waiting_days_categories == categories[3]]\nlong_period_category = df[df.appointment_waiting_days > 90]\n\nsame_day_category.waiting_days_categories.unique(), short_period_category.waiting_days_categories.unique(), quarter_category.waiting_days_categories.unique(),  long_period_category.waiting_days_categories.unique()\nprint(\"Same day \\n\", same_day_category.mean(numeric_only=True))\nprint(\"\\n\")\nprint(\"Short period \\n\", short_period_category.mean(numeric_only=True))\nprint(\"\\n\")\nprint(\"Quarter \\n\", quarter_category.mean(numeric_only=True))\nprint(\"\\n\")\nprint(\"Long period \\n\", long_period_category.mean(numeric_only=True))\n\"\"\"\nBased on the findings above we can see the differences between the groups:\n\n|              | Attended on the same day | Attended in a short period (week - month) | Attended in a period of 31-90 days (quarter) | Attended in a long period (> 90 days) |\n| ------------ | ------------------------ | ----------------------------------------- | -------------------------------------------- | ------------------------------------- |\n| Average age  | 35 years                 | 38 years                                  | 37 years                                     | **58 years**                          |\n| Scholarship  | **~10%**                 | ~9%                                       | ~6%                                          | ~7%                                   |\n| Hipertension | ~18%                     | ~21%                                      | ~15%                                         | **~57%**                              |\n| Diabetes     | ~7%                      | 7%~                                       | ~4%                                          | **~14%**                              |\n\nFrom this analysis we can conclude that the drastic drop on the no-show rating from the period longer than a quarter probably is **due to being an older public** who require regular medical follow-up and tend to schedule more appointments.\n\n<a id=\"received-sms\"><\/a>\n### 3.3. Received sms\n\nLet's check out the received sms attribute\n\"\"\"\nreceived_sms_dataset = show_attribute_statistics(\"received_sms\", df, 0.005)\nshow_no_show_trend(received_sms_dataset, \"received_sms\")\n\"\"\"\nWell, we don't have a greater difference as we can see on the chart above, only **~1% of the no-show rate** of difference between the received \/ not received sms. \n\nSo this attribute may not be that relevant to conclude something about this data.\n\nWe can continue through the variables:\n- appointment_week_day\n- gender\n- neighbourhood\n- patient_id\n\nInvestigating it's relations with no-show.\n\n<a id=\"appointment-week-day\"><\/a>\n### 3.4. Appointment week day\n\"\"\"\nappointment_week_day_dataset = show_attribute_statistics(\"appointment_week_day\", df, 0.005, ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])\nshow_no_show_trend(appointment_week_day_dataset, \"appointment_week_day\", False)\n\"\"\"\nThrough the chart above, we can see that the **no-showing rate increases during the week as soon as it starts**, and **we have a small drop on Thursday** but it keeps growing until the weekend.\n\nIt reaches lower rates when the patient is attended on thursdays but most of the time, the data is consistent between week days.\n\n<a id=\"gender\"><\/a>\n### 3.5. Gender\n\"\"\"\ngender_dataset = show_attribute_statistics(\"gender\", df, 0.001)\nshow_no_show_trend(gender_dataset, \"gender\", False)\n\"\"\"\nThrough the chart above, we can see that we have a large amount of female patients.\n\nWe can assume that in this context that women tend to care more about their health than man due to the massive difference from the consultants as we can see [here](https:\/\/www.everydayhealth.com\/columns\/health-answers\/why-men-dont-go-to-the-doctor\/) and the rate of no-showing rate of men is smaller than women.\n\nSo woman and men have a similar no-showing proportion.\n\n<a id=\"neighbourhood\"><\/a>\n### 3.6. Neighbourhood\n\"\"\"\nneighbourhood_dataset = show_attribute_statistics(\"neighbourhood\", df, 0.06, False, True);\nneighbourhood_no_show_trend = show_no_show_trend(neighbourhood_dataset, \"neighbourhood\", False)\nneighbourhood_no_show_trend.set_xticklabels(rotation='vertical')\n\"\"\"\nWell, we can't see too well our data, let's plot a better chart\n\"\"\"\ndf_groupped_by_neighborhood = df.groupby(['neighbourhood', 'no_show']).count().unstack().patient_id\ndf_groupped_by_neighborhood[\"sum\"] = df_groupped_by_neighborhood['no'] + df_groupped_by_neighborhood['yes']\ndf_groupped_by_neighborhood.sort_values(by=\"sum\", inplace=True)\ndf_groupped_by_neighborhood.dropna(inplace=True)\n\n# plotting our data\nplt.figure(figsize=(20, 30))\n\n# bar chart\nplt.barh(df_groupped_by_neighborhood.index, df_groupped_by_neighborhood['no'].values)\nplt.barh(df_groupped_by_neighborhood.index, df_groupped_by_neighborhood['yes'].values)\n\n# configs\nplt.xlabel(\"amount of patients\")\nplt.ylabel(\"neighbourhood\")\nplt.legend([\"attended\", \"not attended\"])\n\nplt.title(\"amount of patient by no show appointment groupped by neighbourhood\")\n\nplt.show();\n\"\"\"\nAs we can see, the **Jardim Camburi** is the one with most of the appointments in the state.\n\n**Jardim Camburi** is the [most populous neighbourhood from \"Esp\u00edrito Santo\"](https:\/\/pt.wikipedia.org\/wiki\/Jardim_Camburi)\n\nJust to finish our analysis about the neighbourhood, let's check out its relation with the no-show attribute.\n\"\"\"\n# getting all neighbourhoods data from patients that no-showed groupped by waiting days categories\ndf_no_shows_by_neighbourhood_waiting_days_categories = df.query('no_show == \"yes\"').groupby(['neighbourhood', 'waiting_days_categories']).count().patient_id.fillna(value=0).unstack()\ndf_no_shows_by_neighbourhood_waiting_days_categories.head()\n\"\"\"\nFor this analysis, we want to check out the relation between the neighbourhood and waiting days categorie group.\n\nIn order to do that maybe it's best if we use a [heatmap](https:\/\/matplotlib.org\/gallery\/images_contours_and_fields\/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py), since we can compare the values between two categories\n\nAlso it's nice to normalize all data\n\"\"\"\n# normalizing values from the dataframe you can check out the method for this here: https:\/\/stackoverflow.com\/a\/31480994\ndf_no_shows_by_neighbourhood_waiting_days_categories = df_no_shows_by_neighbourhood_waiting_days_categories.div(df_no_shows_by_neighbourhood_waiting_days_categories.sum(axis=1), axis=0)\ndf_no_shows_by_neighbourhood_waiting_days_categories.head()\n# converting the normalized values to percentage\ndf_no_shows_by_neighbourhood_waiting_days_categories = (df_no_shows_by_neighbourhood_waiting_days_categories * 100).round(2)\ndf_no_shows_by_neighbourhood_waiting_days_categories.head()\n# get all necessary data for plotting\nneighbourhoods = df_no_shows_by_neighbourhood_waiting_days_categories.index\nwaiting_days_categories = df_no_shows_by_neighbourhood_waiting_days_categories.columns.values\n\nno_show_values_by_neighbourhood = np.array(df_no_shows_by_neighbourhood_waiting_days_categories.values)\n\nneighbourhoods, waiting_days_categories\n# plot the heatmap\nfigure, axes = plt.subplots(figsize=(60, 60))\naxes.imshow(no_show_values_by_neighbourhood)\n\n# show all the ticks\naxes.set_xticks(np.arange(len(waiting_days_categories)))\naxes.set_yticks(np.arange(len(neighbourhoods)))\n\n# show all tick labels\naxes.set_xticklabels(waiting_days_categories)\naxes.set_yticklabels(neighbourhoods)\n\n# Rotate the tick labels and set their alignment.\nplt.setp(axes.get_xticklabels(), rotation=90, ha=\"right\", rotation_mode=\"anchor\")\n\n# Loop over data dimensions and create text annotations.\nfor i in range(len(neighbourhoods)):\n   for j in range(len(waiting_days_categories)):\n       axes.text(j, i, no_show_values_by_neighbourhood[i, j], ha=\"center\", va=\"center\", color=\"w\")\n\naxes.set_title(\"no-show by neighbourhoods and waiting categories\")\nfigure.tight_layout()\nplt.show()\n\"\"\"\nAs we can see in the charts above in general the no-showing rate increases as the waiting gets longer for most of neighborhood.\n\nWe have a small rate difference for each local, some neighborhoods have higher no-showing rates even for short waiting times (ex: Ilha do Boi and Comdusa).\n\nSince we don't have enough data we can't investigate further for the reasons on such occurrences.\n\n<a id=\"patient-id\"><\/a>\n### 3.7. Patient Id\n\nIn this section, we're digging up on patients that re-scheduled their appointments.\n\nFirst let's filter our duplicated patients by its `no_show` and order them.\n\"\"\"\ndf_duplicated_patients = df[df.patient_id.duplicated() == True].groupby(['patient_id', 'no_show']).no_show.count().unstack()\ndf_duplicated_patients.fillna(0, inplace=True)\ndf_duplicated_patients[\"sum\"] = df_duplicated_patients['no'] + df_duplicated_patients['yes']\ndf_duplicated_patients[\"no_show_rate\"] = df_duplicated_patients['yes'] \/ (df_duplicated_patients['no'] + df_duplicated_patients['yes'])\ndf_duplicated_patients[\"no_show_rate_value\"] = df_duplicated_patients[\"no_show_rate\"] * 100\ndf_duplicated_patients.sort_values(by=\"sum\", inplace=True)\ndf_duplicated_patients.dropna(inplace=True)\n\ndf_duplicated_patients.head()\ndf_duplicated_patients.describe()\n\"\"\"\nWow, there's a lot of patients! \n\nAs we can see in the statistics above:\n- Most of patients are showing at their appointments but we have **~20%** of no_showing rate\n- There are patients that maybe just missed the appointment and re-scheduled\n- We have patients that are on the 86th consulting meaning that is a regular patient\n\nWe can group the duplicated patients on groups just like we did on the waiting days categorization section:\n\n- 1 appointment\n- 2 to 5 appointments\n- 6 to 20 appointments\n- 21 to 40 appointments\n- 41 to 60 appointments\n- \\> 60 appointments\n\"\"\"\nduplicated_categories = pd.Series(['1', '2-5', '6-20', '21-40', '41-60', '>60'])\ndf_duplicated_patients['appointments_count_category'] = pd.cut(df_duplicated_patients['sum'], bins = [-1, 1, 5, 20, 40, 60, 500], labels=duplicated_categories)\ndf_duplicated_patients.head()\n# see the distribution of the categories vs the no showing rate\nshow_no_show_trend(df_duplicated_patients, \"appointments_count_category\", False)\n# check the rate of not attending by groups\ndf_duplicated_patients_group_by_category = df_duplicated_patients.groupby('appointments_count_category')\npatients_attended = df_duplicated_patients_group_by_category.no.sum()\npatients_not_attended = df_duplicated_patients_group_by_category.yes.sum()\n\npatients_not_attended \/ (patients_attended + patients_not_attended)\n\"\"\"\nFinally we can conclude that:\n\nIn patients that have duplicated appointments:\n- The rate of not attending is higher on patients that schedule from 1 to 20 appointments **~21%**\n- This rate drastically drop from patients on the **> 21 appointment group** to **~10%** and patients **> 41 appointments** this rate drops even further to **~3%** since they seems to be regular patients\n\n<a id=\"answering-questions\"><\/a>\n### 3.8. Answering questions\n\n#### Based on the variables we have, what is the most relevant factor that is influencing the patient to no showing the medical appointment?\n\nThere isn't a clear conclusin here, we actually see a lot of interesting insights analysing:\n- Age\n- Waiting days\n- Received Sms\n- Appointment week day\n- Gender\n- Neighbourhood\n- Duplicated patients\n\nWe only can discart the **received sms** since the difference is not meaningfull to reach any conclusion.\n\nBut all other variables have great relevance that may influences the patient to no showing.\n\nMaybe we can in a further analysis mix them up to find a more interesting pattern.\n\n#### There are any relation on these variables that can lead us to a more specific group of patients?\n\nYes, we found some specific group of patients:\n\n- Age \n  - younger patients tend to no-showing\n- Waiting days\n  - elder patients tend to schedule their appointments for long periods of waiting days\n- Neighbourhood\n  - we found some places that have a more frequent no-showing rate that could be further analysed\n- Duplicated patients\n  - the group of patients that have from 1 to 20 appointments scheduled\n\n#### The day of the week of the appointment influences the patient no showing?\n\nActually not that much, there is a very subtle decrease of the no-showing rate for patients that attend on **Thursdays**\n\n#### The waiting time of the patient between the schedule day and the appointment day influences it's no showing?\n\nYes, most of the patients are attended on the same day having the lowest no-show rate.\n\nAfter that the no-showing rate grows until reach a quarter (~90 days) of waiting, after that the rate start dropping.\n\n#### There are patients no showing in appointments on the same day?\n\nYes, but is one of the lowest rate of no-showing rate of the groups.\n\n<a id='conclusions'><\/a>\n## 4. Conclusion\n\nThis analysis had as purpose to perform an analysis of a database of medical consultations, containing more than 100k appointments which approximately **30%** of the patients have not attended.\n\nThe notebook had the purpose of gather some insights on the possible causes of this missing appointments.\n\nI would also like to leave a warning that it is not possible to affirm any veracity of the provided statements and statistical validity of the data but the insights obtained through this analysis can, so instead, inform and direct in-depth research on the subject in order to validate the causes of the missing appointments and find more conclusive insights.\n\nWe find some interesting insights analysing the attributes, summing up:\n\n### Dataset\/Analysis limitations\n\nDuring our entire report we faced limitations and challenges.\n\n- Some informations are not clear in the description of the dataset and you can only find that missing piece by looking out on the forum on some posts\n- We do not have confirmations of where the data comes from, even though it is public services that the author clarified [here](https:\/\/www.kaggle.com\/joniarroba\/noshowappointments\/discussion\/28825161646)\n- There is no guarantee that the patientsID are being exposed correctly or even if is an anonymous one\n- We don't have acess on how many health units share the same patient databse may causing some inconsistency on the data provided, maybe we have the same patient with different IDs or general data\n- Some informations about the columns of the dataset was outdated, for example, the **handicap** is documented as \"True\/False\" variable but in the dataset it represents the amount of disabilites of the patients\n- The lack of more data on the dataset about some variables like **neighbourhood** don't permit we do a in-depth analysis to really give any conclusion about the no-show rate since there are a huge difference associating the displacement habits of each patient and the socioeconomic characteristics of each neighborhood\n- There are a few inconsistences on the dataset that need to be verified for example, negative age values and weird scheduling dates\n- The analysis was limited to categorize the patient waiting time \/ amount of appointments and analysing the mix of the attributes and I have a limited math skill so its not possible to provide relevant insights that could lead us to a relevant conclusion\n\n### Age\n\nThe no-showing rate of age decresases as older the person is. \n\nIt reaches higher rates when the patient is a **baby\/child** and the lowest rates when the patient is around **96 years old.**\n\nThe higher rates may occur because:\n- parents or guardians may have difficulties bringing the child to the appointment\n- there was a long wait until the attendance (but we'll se more about that later)\n\nAnd the lower rates may occur because:\n- we're dealing with older population meaning that as times goes by people tend to visit and be present at health appointments\n\n### Waiting days\n\nWe groupped the waiting days in categories:\n\n| waiting time | days |\n| -- | -- |\n| same day | 0 |\n| week | 1 - 7 |\n| month | 8 - 30 |\n| quarter | 31 - 90 |\n| semester | 91 - 180 |\n| a lot of time | > 180 |\n\nThe no-showing rate increases as time goes by until it reach a quarter.\n\nIt reaches lower rates when the patient is attended on the same day and start decreasing after a quarter of waiting time.\n\nWe can see on the table bellow the characteristics of patients splitted by the groups.\n\n|              | Attended on the same day | Attended in a short period (week - month) | Attended in a period of 31-90 days (quarter) | Attended in a long period (> 90 days) |\n| ------------ | ------------------------ | ----------------------------------------- | -------------------------------------------- | ------------------------------------- |\n| Average age  | 35 years                 | 38 years                                  | 37 years                                     | **58 years**                          |\n| Scholarship  | **~10%**                 | ~9%                                       | ~6%                                          | ~7%                                   |\n| Hipertension | ~18%                     | ~21%                                      | ~15%                                         | **~57%**                              |\n| Diabetes     | ~7%                      | 7%~                                       | ~4%                                          | **~14%**                              |\n\nFrom this analysis we can conclude that the drastic drop on the no-show rating from the period longer than a quarter probably is **due to being an older public** who require regular medical follow-up and tend to schedule more appointments.\n\n### Received Sms\n\nWe didn't found any relevant aspect that can bring a consistent insight by analysing this attribute.\n\nOnly that patients that have received sms have they're no-show rate **increased** in **~10%** related to patients that haven't received any reminder.\n\n### Appointment week day\n\nThe no-showing rate increases during the week as soon as it starts.\n\nBut we have a small drop on **Thursdays** but is not that significant compared to all other weekdays.\n\n### Gender\n\nThere is a big difference on the amount of woman attending to consultations compared to the men.\n\nWe have a large amount of female patients, assuming the context that women tend to care more about their health than man due to the massive difference from the consultants as we can see [here](https:\/\/www.everydayhealth.com\/columns\/health-answers\/why-men-dont-go-to-the-doctor\/). \n\nBut woman and men have a similar no-showing proportion.\n\n### Neighbourhood\n\nSince we're analysing data from *Vit\u00f3ria - ES* we can see that **Jardim Camburi** is the one with most of the appointments in the state and actually is the [most populous neighbourhood from \"Esp\u00edrito Santo\"](https:\/\/pt.wikipedia.org\/wiki\/Jardim_Camburi).\n\nThe no-showing rate increases as the waiting gets longer for most of neighborhood.\n\nWe have a small rate difference for each local, some neighborhoods have higher no-showing rates even for short waiting times (ex: Ilha do Boi and Comdusa).\n\nSince we don't have enough data we can't investigate further for the reasons on such occurrences.\n\n### Duplicated patients\n\nWe checked out patients that have more than one appointment having a no-show rate of **~20%** in this cases.\n\nThe rate of not attending is higher on patients that schedule from 1 to 20 appointments **~21%**\n\nThis rate drastically drop from patients on the **> 21 appointment group** to **~10%** and patients **> 41 appointments** this rate drops even further to **~3%**\n\nThis rate drastically drop from patients on the **> 21 appointment group** to **~10%** and patients **> 41 appointments** this rate drops even further to **~3%** since they seems to be regular patients\n\n## References\n\n- Wikipedia - Sistema \u00danico de Sa\u00fade (SUS). https:\/\/en.wikipedia.org\/wiki\/Sistema_%C3%9Anico_de_Sa%C3%BAde. Accessed in April, 2018.\n- Dataset release - neighbourhood region information. https:\/\/www.kaggle.com\/joniarroba\/noshowappointments\/discussion\/38330#. Accessed in April, 2018.\n- Kaggle - Applying heatmaps for categorical data analysis. https:\/\/www.kaggle.com\/tsilveira\/applying-heatmaps-for-categorical-data-analysis. Accessed in April, 2018.\n- Kaggle - Predicting Show-Up\/No-Show. https:\/\/www.kaggle.com\/somrikbanerjee\/predicting-show-up-no-show.\n- Kaggle - EDA Medical Appointment No-show. https:\/\/www.kaggle.com\/lbronchal\/eda-medical-appointment-no-show.\n- Kaggle - Fundamental Data Analysis. https:\/\/www.kaggle.com\/tigerli1997\/fundamental-data-analysis.\n- Analytics Vidhya - 12 Useful Pandas Techniques in Python for Data Manipulation. https:\/\/www.analyticsvidhya.com\/blog\/2016\/01\/12-pandas-techniques-python-data-manipulation\/.\n- Everyday Health - 60 Percent of Men Don\u2019t Go to the Doctor: Here\u2019s Why. https:\/\/www.everydayhealth.com\/columns\/health-answers\/why-men-dont-go-to-the-doctor\/.\n- Wikipedia - Jardim Camburi. https:\/\/pt.wikipedia.org\/wiki\/Jardim_Camburi.\n- Matplotlib - Creating annotated heatmaps. https:\/\/matplotlib.org\/gallery\/images_contours_and_fields\/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py.\n\"\"\"\nfrom subprocess import call\ncall(['python', '-m', 'nbconvert', 'Investigate_a_Dataset.ipynb'])","meta":"{'source': 'AI4Code', 'id': 'f3222cf34cfb7a'}"}
{"id":"81400","text":"# 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\n\"\"\"\n### Hi! My name is Alex and this is my first notebook in order to show you my approach to this problem. As this is my first notebook I will try to state clearly my hypothesis so we can discuss in the comments. I hope you can enjoy it as much as I enjoyed while I was writting this! :D\n\"\"\"\n\"\"\"\n# Import data\n\n\"\"\"\nheart = pd.read_csv(\"\/kaggle\/input\/heart-failure-prediction\/heart.csv\")\n\"\"\"\n### See the first five rows of the dataset to see if the data has been loaded well\n\"\"\"\nheart.head()\n\"\"\"\n### At first sight we can conclude there are 5 categorical data. Which are Sex, ChestPainType, RestingECG, ExerciseAngina and ST_Slope\n### Let's see if the target variable is skewed. If so we have to use other techniques such as undersampling or oversampling.\n\"\"\"\nheart[\"HeartDisease\"].value_counts()\n\"\"\"\n### Due to the fact the results are balanced (nearly 50% each one) we do not need to use those techniques :)\n\n### Let's see info of the columns in order to get some insights of the dataset such as **null entries** or which columns have **categorical data**\n\"\"\"\nheart.info()\n\"\"\"\n### At this point we can conclude there are no null entries on the dataset. This doesn't mean that there is not null data because sometimes people can use different values to represent missing data, and Pandas will not recognize that :\\ . But not everything is lost! We can use different methods to differentiate those points. Here I would like to start the EDA, and plot different graphs to have a wider view of the dataset\n\n## *Exploratory Data Analysis*\n\n### First let's import Seaborn to make the plots\n\"\"\"\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(11.7,8.27)}) #Bigger images\n\"\"\"\n# Correlation matrix\n\n### With the correlation matrix we can see the relationship between the different variables. The number has a range between 1 and -1 and represents if there is a **linear** relationship between two variables. It is important to remember that shows only **linear** relationships becuase a correlation of zero doesn't mean there is no relationship, it just shows there is no **linear** relationship.\n\n### It is important to remember that this matrix is simetric so the info of the upper diagonal is the same as the one in the lower diagonal.\n\"\"\"\nsns.heatmap(heart.corr(),cmap=\"YlGnBu\")\n\"\"\"\n### In order to see the relation between the different variables I will use a pairplot.\n\"\"\"\nsns.pairplot(heart,hue=\"HeartDisease\")\n\"\"\"\n### With hue we can change the color regarding heart disease. With this plots we can see that oldpeak and restingBP has very long tails. This sometimes can be a symptom of data that has been loaded incorrectly or extreme values used to represent missing data.\n### Let's see the box plots to see more clearly the outliers.\n\"\"\"\n\"\"\"\n## Outliers\n\"\"\"\n\"\"\"\n### Using boxplots it's easy and fast to see the outliers as it represents those points clearly on the plot.\n\"\"\"\nsns.boxplot(data=heart)\n\"\"\"\n### With a quick research we can see some values with RestingBP near zero, which is not possible. Also there are some values with\n### Cholesterol near zero which is not possible also. Let's analizy how many of them are and how we can [impute](https:\/\/en.wikipedia.org\/wiki\/Imputation_(statistics)) them.\n### Here I will replace the RestingBP equal zero with the median as this is more resistant to outliers that the mean\n### Let's search the values with RestingBP equal zero.\n\"\"\"\nsns.boxplot(y=\"RestingBP\",data=heart)\n\"\"\"\n### Let's search tthe outlier\n\"\"\"\nheart[heart[\"RestingBP\"]<50]\n\"\"\"\n### Here we see the entry do not has RestingBP Cholesterol and FastingBS. I will drop it because it is one entry in one thousand. If \n### we had more data to represent we should use a method to imputate the values.\n\n### Now let's search the values with zero value of Cholesterol.\n\"\"\"\nsns.boxplot(y=\"Cholesterol\",data=heart)\nheart[heart[\"Cholesterol\"]==0]\n\"\"\"\n### Almost 10% of the dataset has this value missing. Before making assumptions I will see which is the distribution of HeartDisease within these points. Then I will justify a method to impute the values.\n\"\"\"\nheart[heart[\"Cholesterol\"]==0][\"HeartDisease\"].value_counts()\n\"\"\"\n### Here we can see that the 88% of the entries here has a heart disease so this is highly skewed. In order to impute skewed data I will use the median of the values of Cholesterol with heart disease. I will do this because nearly all the entries have heart disease and the median of this values is resistant to outliers.\n\"\"\"\n\"\"\"\n### This line of code gives me the non zero values of cholesterol with heart disease.\n\"\"\"\nmask = (heart[\"Cholesterol\" ]!= 0) & (heart[\"HeartDisease\"] == 1)\nheart.loc[mask][\"Cholesterol\"].median()\n\"\"\"\n### I will impute with this value.\n\"\"\"\nheart.loc[heart[\"Cholesterol\"]==0,\"Cholesterol\"] = heart.loc[mask][\"Cholesterol\"].median()\n\n\"\"\"\n### Let's see how the distribution is modified and if the correlation between heart disease and cholesterol has changed\n\"\"\"\nsns.pairplot(data=heart,hue=\"HeartDisease\")\n\"\"\"\n### Here we can see that the distribution of Cholesterol has changed and also the correlation. From having a negative correlation with heart disease now it is positive. This makes sense as this is one of the first estimators a doctor uses to suggest further analysis.\n\"\"\"\nheart.corr()[\"Cholesterol\"][\"HeartDisease\"]\n\"\"\"\n### Before finishing the EDA I will transform the categorical data into dummy variables. This means that the categorical data such as Sex, that has Male of Female values will be transformed into Sex_M and Sex_F with 0 or 1 with the corresponding entry. This is useful in distance based algorithms because those kind of algorithms needs the data to be normalized. The problem with this is that we are increasing the dimension of the dataset. If we are dealing with heavy datasets after this we should use some PCA to reduce the dimensionality.\n\"\"\"\n\"\"\"\n### I will get the name of the columns with categorical type.\n\"\"\"\ncat_cols = heart.select_dtypes(\"object\").columns.to_list()\ncat_cols\nheart_dummy = pd.get_dummies(heart)\n\"\"\"\n### Let's see how we increased the dimensions of the dataset.\n\"\"\"\nheart_dummy.head()\nlen(heart_dummy.columns),len(heart.columns)\n\"\"\"\n# Tree based algorithm\n### Let's use the models to compare the scores in our treated data!\n### First import the libraries\n#### Disclaimer: *Personally I don't like to import everything before starting the notebook because it seems too many information to somebody that is starting like me. I prefer to import as I am going to use in order to see clearly where I will use it.*\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n### First let's separate the data into X and y.\n\"\"\"\nX = heart_dummy.drop(axis=1,labels=\"HeartDisease\")\ny = heart_dummy[\"HeartDisease\"]\n\"\"\"\n### Split the data into train and test.\n\"\"\"\nx_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=10)\n\"\"\"\n### I will use gridsearch to optimize hyperparameters and prevent overfitting over the training set.\n\"\"\"\nStimator = DecisionTreeClassifier(criterion=\"entropy\",random_state = 101)\ngrid = {\"max_depth\" : [1,2,3,4,5,6,7,8,9]}\ngso = GridSearchCV(Stimator,grid,cv=5)\n\"\"\"\n### As we are dealing with tree based algorithms we do not need to normalize the data! So let's train.\n\"\"\"\ngso.fit(x_train,y_train)\ny_pred = gso.predict(x_test)\n\"\"\"\n### Let's see the score of the model and the confusion matrix\n\"\"\"\nfrom sklearn.metrics import confusion_matrix,accuracy_score,plot_confusion_matrix\nconfusion_matrix(y_test,y_pred)\nplot_confusion_matrix(gso,x_test,y_test)\naccuracy_score(y_test,y_pred)\n\"\"\"\n### Let's see the depth of the tree.\n\"\"\"\ngso.best_params_\nStimator_forest = RandomForestClassifier(criterion=\"entropy\")\n#To optimize information gain\ngrid_forest = {\"n_estimators\" : [1000,2000,3000,4000,5000]}\ngso_forest = GridSearchCV(Stimator_forest,grid_forest,cv = 5)\ngso_forest.fit(x_train,y_train)\ny_predforest = gso_forest.predict(x_test)\naccuracy_score(y_test,y_predforest)\ngso_forest.best_params_\n\"\"\"\n### Let's try with a XGBClassifier\n\"\"\"\nStimator_XGBC = XGBClassifier(use_label_encoder=False,n_estimators=2000)\nStimator_XGBC.fit(x_train,y_train)\ny_predXGBC = Stimator_XGBC.predict(x_test)\naccuracy_score(y_test,y_predXGBC)\n\"\"\"\n# Distance Based Algorithm\n### Let's import the libraries we are going to use\n\"\"\"\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaled_x_train = scaler.fit_transform(x_train)\nscaled_x_test = scaler.transform(x_test)\nStimator_svc = SVC(kernel=\"rbf\")\ngrid_svc = {\"gamma\":[0.001,0.01,0.1,1,10],\"C\":[0.1,1,10,100,1000]}\ngso_svc = GridSearchCV(Stimator_svc,grid_svc,cv = 5)\ngso_svc.fit(scaled_x_train,y_train)\ny_predsvc = gso_svc.predict(scaled_x_test)\naccuracy_score(y_test,y_predsvc)\n\nStimator_logreg = LogisticRegression()\ngrid_logreg = {\"C\" : [0.1,1,10,100,1000]}\ngso_logreg = GridSearchCV(Stimator_logreg,grid_logreg,cv=5)\ngso_logreg.fit(scaled_x_train,y_train)\ny_predlogreg = gso_logreg.predict(scaled_x_test)\naccuracy_score(y_test,y_predlogreg)\n\"\"\"\n# Finished\n### To sum up, the model with best accuracy score was SVC. It can be optimized but at this point I will stop here.\n### Thanks for reading! Finally, I would like to now how would you had replaced the entries with 0 cholesterol value and. of course, if you liked the post!\n# Have a great day!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9565deaaeeb452'}"}
{"id":"1345","text":"!pip install catboost\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm_notebook as tqdm\nfrom sklearn.model_selection import train_test_split,StratifiedKFold\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score,f1_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.ensemble import BaggingClassifier\nfrom catboost import CatBoostClassifier\nfrom scipy.stats import norm, skew\nfrom scipy.special import boxcox1p\nimport lightgbm as lgb\nfrom mlens.ensemble import SuperLearner\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport pandas as pd \nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import f1_score\nfrom bayes_opt import BayesianOptimization\nfrom sklearn.model_selection import train_test_split\n\n%matplotlib inline\ntrain = pd.read_csv('..\/input\/train_LZdllcl.csv')\ntest = pd.read_csv('..\/input\/test_2umaH9m.csv')\ntrain.head()\ntrain.describe()\ntrain.isnull().sum()\ntrain.dtypes\ntrain['recruitment_channel'].value_counts()\ntrain['education'].value_counts()\nplt.matshow(train.corr())\nplt.show()\nf, ax = plt.subplots(figsize=(10, 8))\ncorr = train.corr()\nsns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True),\n            square=True, ax=ax)\n\"\"\"\n> **NAN Imputation**\n\"\"\"\nplt.hist(train[train['KPIs_met >80%'] == 0]['previous_year_rating'])\nplt.show()\nplt.hist(train[train['KPIs_met >80%'] == 1]['previous_year_rating'])\nplt.show()\nprev_rating_Three = train[(train['previous_year_rating'].isnull())][train['KPIs_met >80%'] == 0]['employee_id']\n\nfor empId in tqdm(prev_rating_Three):\n    train.loc[train['employee_id']==empId,'previous_year_rating'] = 3.0\n    \nprev_rating_Three = test[(test['previous_year_rating'].isnull())][test['KPIs_met >80%'] == 0]['employee_id']\n\nfor empId in tqdm(prev_rating_Three):\n    test.loc[test['employee_id']==empId,'previous_year_rating'] = 3.0\nprev_rating_Five = train[(train['previous_year_rating'].isnull())][train['KPIs_met >80%'] == 1]['employee_id']\n\nfor empId in tqdm(prev_rating_Five):\n    train.loc[train['employee_id']==empId,'previous_year_rating'] = 5.0\n    \nprev_rating_Five = test[(test['previous_year_rating'].isnull())][test['KPIs_met >80%'] == 1]['employee_id']\n\nfor empId in tqdm(prev_rating_Five):\n    test.loc[test['employee_id']==empId,'previous_year_rating'] = 5.0\ntrain['education'] = train['education'].fillna('notGiven')\ntest['education'] = test['education'].fillna('notGiven')\nX = train.drop(columns=['employee_id','is_promoted'])\ny = train['is_promoted']\ntest.drop(columns=['employee_id'],inplace=True)\n\"\"\"\n> **Feature Engineering**\n\"\"\"\nX.head()\nX['no_of_trainings'].unique()\ntrain.plot.hexbin('is_promoted','age',gridsize=15)\ndef binAge(x):\n    age=''\n    if (x<26):\n        age='young'\n    elif (x>=26 and x<=36):\n        age='medium'\n    else:\n        age='old'\n    return age\n\ndef binAgeTwo(x):\n    age=''\n    if (x<=30):\n        age='young'\n    else:\n        age='medium'\n    return age\nX['age_bin_Two'] = X['age'].apply(binAgeTwo)\nX['age_bin'] = X['age'].apply(binAge)\n\ntest['age_bin_Two'] = test['age'].apply(binAgeTwo)\ntest['age_bin'] = test['age'].apply(binAge)\nX['frac_train'] = X['no_of_trainings']\/10\ntest['frac_train'] = test['no_of_trainings']\/10\nX['crit_score'] = ((X['previous_year_rating']*X['KPIs_met >80%'] + X['previous_year_rating']*X['awards_won?'] + X['previous_year_rating']*X['frac_train'] ) * (20) + X['avg_training_score'])\/400\ntest['crit_score'] = ((test['previous_year_rating']*test['KPIs_met >80%'] + test['previous_year_rating']*test['awards_won?'] + test['previous_year_rating']*test['frac_train'] ) * (20) + test['avg_training_score'])\/400   \nsns.boxplot(y,X['crit_score'])\n\"\"\"\n> **Preparing Data for Training**\n\"\"\"\n\"\"\"\n> **Data PreProcessing**\n\"\"\"\ncontVar = set(X.columns) - set(['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two'])  \ncontVar = list(contVar)\nflag = 1\niter = 0\nwhile(flag!=0):\n    iter = iter + 1\n    if(iter > 20):\n        break\n    skewed_feats = X[contVar].apply(lambda x: skew(x.dropna())).sort_values(ascending=False)\n    #print(\"\\nSkew in numerical features: \\n\")\n    skewness = pd.DataFrame({'Skew' :skewed_feats})\n    print(skewness[np.abs(skewness['Skew'])>0.75])\n    skewnessBox = skewness[(skewness.Skew)>0.75]\n    skewnessSquare = skewness[(skewness.Skew)<-0.75]\n    if(skewnessBox.shape[0] == 0 and skewnessSquare.shape[0] == 0):\n        flag = 0\n    #print(\"There are {} skewed numerical features to Box Cox transform\".format(skewnessBox.shape[0]))\n    #print(\"There are {} skewed numerical features to Square transform\".format(skewnessSquare.shape[0]))\n    skewed_features1 = skewnessBox.index\n    skewed_features2 = skewnessSquare.index\n    #print(skewed_features1)\n    #print(skewed_features2)\n    lam = 0.15\n    for feat in skewed_features1:\n        X[feat] = boxcox1p(X[feat], lam)\n        test[feat] = boxcox1p(test[feat], lam)\n    for feat in skewed_features2:\n        X[feat] = np.square(X[feat])\n        test[feat] = np.square(test[feat])\nX_dummies = X.copy()\nX_dummies = pd.get_dummies(X,columns=['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two'])    \ntest_dummies = pd.get_dummies(test,columns=['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two'])    \nXstand = X_dummies.copy()\nXmin = X_dummies.copy()\nXrob = X_dummies.copy()\n\nteststand = test_dummies.copy()\ntestmin = test_dummies.copy()\ntestrob = test_dummies.copy()\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler,RobustScaler\n\nstandScl = StandardScaler()\nminScl = MinMaxScaler()\nrobScl = RobustScaler()\n\nXstand[contVar] = standScl.fit_transform(X[contVar])\nXmin[contVar] = minScl.fit_transform(X[contVar])\nXrob[contVar] = robScl.fit_transform(X[contVar])\n\nteststand[contVar] = standScl.transform(test[contVar])\ntestmin[contVar] = minScl.transform(test[contVar])\ntestrob[contVar] = robScl.transform(test[contVar])\ndef scoreOfModel(clf,X,y,flag,shuffleBool=False,nFolds=12):\n    score = 0\n    finalPreds = np.zeros(23490)\n    #trainPreds = np.zeros(54808)\n    folds = StratifiedKFold(n_splits=nFolds, shuffle=shuffleBool, random_state=42)\n    train_pred = cross_val_predict(clf, X, y, cv=12,method='predict_proba')\n    for fold_, (trn_idx, val_idx) in tqdm(enumerate(folds.split(X,y))):\n        X_train,X_val = X.loc[trn_idx,:],X.loc[val_idx,:]\n        #X_train,X_val = X[trn_idx],X[val_idx]\n        y_train,y_val = y[trn_idx],y[val_idx]\n        clf.fit(X_train,y_train)\n        yPreds = clf.predict(X_val)\n        score += f1_score(y_val,yPreds)\n        if(flag==0):\n            finalPreds += clf.predict(teststand)\n        elif (flag==1):\n            finalPreds += clf.predict(testmin)\n        elif(flag==2):\n            finalPreds += clf.predict(testrob)\n        elif(flag==3):\n            p = clf.predict_proba(test)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        print(\"**********\"+ str(score\/(1+fold_)) + \"******************Iteration \"+str(fold_)+\" Done****************\")    \n    return str(score\/nFolds),(train_pred),(finalPreds\/nFolds)\n\ndef scoreOfModelTwo(clf,X,y,X_val,y_val):\n    clf.fit(X,y)\n    yPreds = clf.predict(X_val)\n    score = f1_score(y_val,yPreds)\n    finalPreds = clf.predict(test)\n    return str(score),(finalPreds)\n\n\ndef scoreOfModelLGB(clfr,X,y,flag,shuffleBool=False,nFolds=12):\n    score = 0\n    finalPreds = np.zeros(23490)\n    #trainPreds = np.zeros(54808)\n    folds = StratifiedKFold(n_splits=nFolds, shuffle=shuffleBool, random_state=42)\n    train_pred = cross_val_predict(clfr, X, y, cv=12,method='predict_proba')\n    for fold_, (trn_idx, val_idx) in tqdm(enumerate(folds.split(X,y))):\n        X_train,X_val = X.loc[trn_idx,:],X.loc[val_idx,:]\n        #X_train,X_val = X[trn_idx],X[val_idx]\n        y_train,y_val = y[trn_idx],y[val_idx]\n        clf = clfr.fit(X_train,y_train)\n        yPreds = clf.predict(X_val)\n        score += f1_score(y_val,yPreds)\n        if(flag==0):\n            p = clf.predict_proba(teststand)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        elif (flag==1):\n            p = clf.predict_proba(testmin)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        elif(flag==2):\n            p = clf.predict_proba(testrob)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        elif(flag==3):\n            p = clf.predict_proba(test)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        elif(flag==4):\n            p = clf.predict_proba(test_dummies)\n            #q = clf.predict_proba(X)    \n            for k in range(len(p)):\n                finalPreds[k] += p[k][0]\n            #for l in range(len(q)):\n            #    trainPreds[l] += q[l][0]\n        print(\"**********\"+ str(score\/(1+fold_)) + \"******************Iteration \"+str(fold_)+\" Done****************\")    \n    return str(score\/nFolds),(train_pred),(finalPreds\/nFolds)\n\ncatClf2 = CatBoostClassifier(learning_rate = 0.0353,iterations = 1500,eval_metric='F1',cat_features=['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two'])    \nclfDummies1 = lgb.LGBMClassifier(max_depth= 7, learning_rate=0.07532, n_estimators=402, num_leaves= 28, reg_alpha=2.154 , reg_lambda= 1.028)\nclfDummies2 = lgb.LGBMClassifier(max_depth= 10, learning_rate=0.1, n_estimators=308, num_leaves= 30, reg_alpha=1.0 , reg_lambda= 0.1)\nclfStand1 = lgb.LGBMClassifier(max_depth= 4, learning_rate=0.1, n_estimators=635, num_leaves= 30, reg_alpha=1.0 , reg_lambda= 0.1)\nclfmin1 = lgb.LGBMClassifier(max_depth= 4, learning_rate=0.1, n_estimators=635, num_leaves= 30, reg_alpha=1.0 , reg_lambda= 0.1)\n\nscr_clfDummies1,trainclfDummies1Preds,catclfDummies1Preds = scoreOfModelLGB(clfDummies1,X_dummies,y,4)\nscr_clfDummies2,trainclfDummies2Preds,catclfDummies2Preds = scoreOfModelLGB(clfDummies2,X_dummies,y,4)\nscr_clfStand1,trainclfStand1Preds,catclfStand1Preds = scoreOfModelLGB(clfStand1,Xstand,y,0)\nscr_clfmin1,trainclfmin1Preds,catclfmin1Preds = scoreOfModelLGB(clfmin1,Xmin,y,1)\nscr_catClf2,traincatClf2Preds,catClf2Preds = scoreOfModel(catClf2,X,y,3)\nstackedDF = pd.DataFrame({'dummiesOne' : trainclfDummies1Preds[:,0], 'dummiesTwo' : trainclfDummies2Preds[:,0],\n                          'standOne' : trainclfStand1Preds[:,0], 'minOne' : trainclfmin1Preds[:,0],\n                          'catClf' : traincatClf2Preds[:,0]\n                         })\n\nstackedTest = pd.DataFrame({'dummiesOne' : catclfDummies1Preds , 'dummiesTwo' : catclfDummies2Preds,\n                          'standOne' : catclfStand1Preds, 'minOne' : catclfmin1Preds,\n                          'catClf' : catClf2Preds\n                         })\nstackedDF.head()\nf, ax = plt.subplots(figsize=(10, 8))\ncorr = stackedDF.corr()\nsns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True),\n            square=True, ax=ax)\nstackedTest.head()\n\"\"\"\n**PARAMETER TUNING**\n\"\"\"\n# #bounds on different parameters \n# param_to_be_optimized = {'iterations':(600,1500),'learning_rate':(0.03,0.05),'depth':(3,10),\n#                         'l2_leaf_reg':(2,21)}\n\n\n# def param_handler_to_optimize(iterations,learning_rate,depth,l2_leaf_reg):\n#     \"\"\"\n#     To handle integer type parameters:\n    \n#     \"\"\"\n#     thread_count=-1\n#     iterations = int(iterations)\n#     depth = int(depth) #int type params\n#     #border_count = int(border_count)\n#     #ctr_border_count = int(ctr_border_count)\n    \n#     param = {\n#     'iterations': iterations,  # the maximum depth of each tree\n#     'learning_rate': learning_rate,  # the training step for each iteration\n#     'silent': True,  # logging mode - quiet\n#     'depth':depth,\n#     'l2_leaf_reg':l2_leaf_reg,\n#     #'border_count':border_count,\n#     #'thread_count':thread_count,\n#     'task_type':'GPU',\n#     'loss_function': 'CrossEntropy',  # error evaluation for multiclass training\n#     'cat_features':['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two']  \n#     }\n#     return func_to_be_optimized(param)\n\n# def func_to_be_optimized(param):\n    \n#     model = CatBoostClassifier(**param)    \n#     score = 0\n#     #finalPreds=np.zeros(23490)\n#     folds = StratifiedKFold(n_splits=12, shuffle=False, random_state=42)\n#     for fold_, (trn_idx, val_idx) in tqdm(enumerate(folds.split(X,y))):\n#         X_train,X_val = X.loc[trn_idx,:],X.loc[val_idx,:]\n#         y_train,y_val = y[trn_idx],y[val_idx]\n#         model.fit(X_train,y_train)\n#         yPreds = model.predict(X_val)\n#         score += f1_score(y_val,yPreds)\n#     return (score\/12)\n\n\n\n# optimizer = BayesianOptimization(\n#     f=param_handler_to_optimize,\n#     pbounds=param_to_be_optimized,\n#     random_state=1,\n# )\n# optimizer.maximize(\n#     init_points=3,\n#     n_iter=75,\n# )\n#------------------------------------------------------------------------------------------------\n#bounds on different parameters \n# param_to_be_optimized = {'C':(0.001,20000)\n#                         }\n\n# def param_handler_to_optimize(C):\n#     \"\"\"\n#     To handle integer type parameters:\n    \n#     \"\"\"\n   \n#     param = {\n#     'C':C,\n#     #'max_depth':max_depth\n#     #'C':C,\n#     'solver':'liblinear'\n#     }\n#     return func_to_be_optimized(param)\n\n\n# param_to_be_optimized = {'max_depth': (2, 15),'learning_rate': (0.001, 0.5),'n_estimators': (10, 1000), \n#                          'num_leaves': (2,50),'reg_alpha': (0.01, 10),'reg_lambda': (0, 3)}                                          \n\n# def param_handler_to_optimize(max_depth,learning_rate,n_estimators,num_leaves,reg_alpha,reg_lambda):\n#     \"\"\"\n#     To handle integer type parameters:\n    \n#     \"\"\"\n#     #thread_count=-1\n#     max_depth = int(max_depth)\n#     n_estimators = int(n_estimators) #int type params\n#     num_leaves = int(num_leaves)  \n#     #border_count = int(border_count)\n#     #ctr_border_count = int(ctr_border_count)\n    \n#     param = {\n#     'max_depth' : max_depth,  # the maximum depth of each tree\n#     'learning_rate' : learning_rate,  # the training step for each iteration\n#     'n_estimators' : n_estimators,  # logging mode - quiet\n#     'num_leaves' : num_leaves,\n#     'reg_alpha' : reg_alpha,\n#     'reg_lamda' : reg_lambda,\n#     #'border_count':border_count,\n#     #'thread_count':thread_count,\n# #     'task_type':'GPU',\n# #     'loss_function': 'CrossEntropy',  # error evaluation for multiclass training\n# #     'cat_features':['previous_year_rating','department','region','education','gender','recruitment_channel','KPIs_met >80%','awards_won?','age_bin','age_bin_Two']  \n#     }\n#     return func_to_be_optimized(param)\n\n# def func_to_be_optimized(param):\n    \n#     #model = lgb.LGBMClassifier(**param)    \n#     train_pred_opt = cross_val_predict(LogisticRegression(**param), stackedDFL2, y, cv=12,method='predict_proba')\n#     train_pred_optTweaked = train_pred_opt[:,0]\n#     thresholds = np.linspace(0.01, 0.99, 50)\n#     mcc = np.array([f1_score(y, train_pred_optTweaked<thr) for thr in thresholds])\n#     #best_threshold = thresholds[mcc.argmax()]\n#     return (mcc.max())\n\n# optimizer = BayesianOptimization(\n#     f=param_handler_to_optimize,\n#     pbounds=param_to_be_optimized,\n#     random_state=1,\n# )\n# optimizer.maximize(\n#     init_points=3,\n#     n_iter=75,\n# )\n\"\"\"\n> **STACKING**\n\"\"\"\nmetaLearner = RandomForestClassifier(max_depth=5,n_estimators =116) \n\nmetaLearner.fit(stackedDF,y)\npadRF = metaLearner.predict_proba(stackedDF)\npadRFTweaked = padRF[:,0]\n\nthresholds = np.linspace(0.01, 0.99, 50)\nmcc = np.array([f1_score(y, padRFTweaked<thr) for thr in thresholds])\nplt.plot(thresholds, mcc)\nbest_threshold = thresholds[mcc.argmax()]\nprint(mcc.max())\nprint(best_threshold)\n# metaLearner = LogisticRegression(solver='liblinear',C=1.931)\n# metaLearner.fit(stackedDF,y)\n# padLR = metaLearner.predict_proba(stackedDF)\n# padLRtest = metaLearner.predict_proba(stackedTest)\n\n# padLR = cross_val_predict(metaLearner, stackedDF, y, cv=12,method='predict_proba')\n# padLRTweaked = padLR[:,0]\n\n# thresholds = np.linspace(0.01, 0.99, 50)\n# mcc = np.array([f1_score(y, padTweaked<thr) for thr in thresholds])\n# plt.plot(thresholds, mcc)\n# best_threshold = thresholds[mcc.argmax()]\n# print(mcc.max())\n# print(best_threshold)\n\n# metaLearner = lgb.LGBMClassifier(learning_rate=0.07149459085784728,\n#  max_depth= 4,\n#  n_estimators= 10,\n#  num_leaves= 49,\n#  reg_alpha= 9.71326474211533,\n#  reg_lambda= 0.36594150409622384) \n\n# metaLearner.fit(stackedDF,y)\n# padLGBM = metaLearner.predict_proba(stackedDF)\n# padLGBMtest = metaLearner.predict_proba(stackedTest)\n\n# padLGBM = cross_val_predict(metaLearner, stackedDF, y, cv=12,method='predict_proba')\n\n# padLGBMTweaked = padLGBM[:,0]\n\n# thresholds = np.linspace(0.01, 0.99, 50)\n# mcc = np.array([f1_score(y, padLGBMTweaked<thr) for thr in thresholds])\n# plt.plot(thresholds, mcc)\n# best_threshold = thresholds[mcc.argmax()]\n# print(mcc.max())\n# print(best_threshold)\n\n# stackedDFL2 = pd.DataFrame({'padRF' : padRF[:,0], 'padLR' : padLR[:,0],\n#                           'padLGBM' : padLGBM[:,0]\n#                          })\n\n# stackedTestL2 = pd.DataFrame({'padRF' : padRFtest[:,0] , 'padLR' : padLRtest[:,0],\n#                           'padLGBM' : padLGBMtest[:,0]\n#                          })\n\n#metaLearner = LogisticRegression(solver='liblinear',C=optimizer.max['params']['C'])\n# metaLearner = LogisticRegression(C=0.6064701322378264) \n\n# metaLearner.fit(stackedDFL2,y)\n# padRF2 = metaLearner.predict_proba(stackedDFL2)\n# padRF2Tweaked = padRF2[:,0]\n# #padRF2 = cross_val_predict(metaLearner, stackedDFL2, y, cv=12,method='predict_proba')\n# #padRF2Tweaked = padRF2[:,0]\n\n# thresholds = np.linspace(0.01, 0.99, 50)\n# mcc = np.array([f1_score(y, padRF2Tweaked<thr) for thr in thresholds])\n# plt.plot(thresholds, mcc)\n# best_threshold = thresholds[mcc.argmax()]\n# print(mcc.max())\n# print(best_threshold)\n\"\"\"\n**Predictions**\n\"\"\"\nsampleShuffle = pd.read_csv('..\/input\/sample_submission_M0L0uXE.csv')\npad = metaLearner.predict_proba(stackedTest)\npadTweaked = pad[:,0]\n\nsampleShuffle['is_promoted'] = padTweaked<best_threshold\nsampleShuffle['is_promoted'] = np.where(sampleShuffle['is_promoted']==False,0,1)\nsampleShuffle.to_csv('submissionShuffle.csv',index=False)\nfrom IPython.display import HTML\nimport pandas as pd\nimport numpy as np\nimport base64\n\n# function that takes in a dataframe and creates a text link to  \n# download it (will only work for files < 2MB or so)\ndef create_download_link(df, title = \"Download CSV file\", filename = \"submissionShuffle.csv\"):  \n    csv = df.to_csv(index=False)\n    b64 = base64.b64encode(csv.encode())\n    payload = b64.decode()\n    html = '<a download=\"{filename}\" href=\"data:text\/csv;base64,{payload}\" target=\"_blank\">{title}<\/a>'\n    html = html.format(payload=payload,title=title,filename=filename)\n    return HTML(html)\n\n# create a random sample dataframe\ndf = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))\n\n# create a link to download the dataframe\ncreate_download_link(sampleShuffle)","meta":"{'source': 'AI4Code', 'id': '028203c05df8f4'}"}
{"id":"120670","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf = pd.read_csv('..\/input\/phenotype-genotype-integrator\/PheGenI.csv')\ndf.sample(5)\ndf.info()\ndf['P-Value']\n\"\"\"\n# Converting P-Value column\n\"\"\"\n\"\"\"\nP-Values have both float and object types\n\"\"\"\npv = df['P-Value'][df['P-Value'].apply(lambda x: isinstance(x, str))]\npv = pv.str.split('-')\npv = pd.to_numeric(pv.apply(lambda x: x[0][:-1])) * 10 ** (-pd.to_numeric(pv.apply(lambda x: x[1]), downcast='float'))\npv\ndf['P-Value'][pv.index] = pv.values\ndf['P-Value']\npd.to_numeric(df['P-Value'])\ndf['P-Value'][df['P-Value'].apply(lambda x: isinstance(x, str))]\ndf['P-Value'].sort_values()\ndf['P-Value'].sort_values().reset_index()['P-Value'][:].plot(figsize=(15,7))\ndf['P-Value'].sort_values().reset_index()['P-Value'][:134000].plot(figsize=(15,7))\n\"\"\"\n# Analysis\n\"\"\"\ndf['Trait'].unique().size\ndf.groupby('Context').count().sort_values('Gene', ascending=False)\n\"\"\"\nBelow is the diagram describing various SNP types.\n\"\"\"\n\"\"\"\n<img src=\"SNP types.jpg\"\/>\n\"\"\"\n\"\"\"\n1. The \u201cNear Gene\u201d region includes the mRNA region of the gene as well as arbitrary regions of 2K nucleotides upstream and 0.5K nucleotides down stream to allow for potential regulatory regions. (https:\/\/www.ncbi.nlm.nih.gov\/books\/NBK44455\/)\n2. UTR-5 is the region that is directly upstream from the initiation codon which is transcribed to mRNA but not translated to Protein. UTR-3 is similar at downstream.\n3. A SNP will be classified as \u201csplice-site\u201d if the SNP\u2019s position is one or two bases before the start of an exon or If the SNP is located one or two bases following the end of an exon.\n\n\"\"\"\nplt.figure(figsize=(15,5))\nsns.countplot(x='Context', data=df, order=df['Context'].value_counts().index)\ndf[(df['Gene'] == df['Gene 2'])].groupby('Context').count().sort_values('Gene', ascending=False)\n\"\"\"\nIf Gene and Gene 2 names are same then SNP is not between two genes.\n\"\"\"\n(df['Gene'] == df['Gene 2']).sum()\nplt.figure(figsize=(15,5))\nsns.countplot(x='Context', data=df[(df['Gene'] == df['Gene 2'])], order=df['Context'].value_counts().index)\ndf[(df['Gene'] != df['Gene 2'])].groupby('Context').count().sort_values('Gene', ascending=False)\ndf[(df['P-Value']>0) & (df['P-Value']<10**-300)].sort_values(by='P-Value')\n\"\"\"\nP value less than 5x10^-8 is commonly accepted as threshold. (https:\/\/en.wikipedia.org\/wiki\/Genome-wide_significance)\n\"\"\"\ndf_p = df[df['P-Value'] < 5 * 10 ** -8]\ndf_p.groupby('Trait').count().sort_values('P-Value', ascending=False).head(10)\ndf_p.groupby('Trait').count().sort_values('P-Value', ascending=False)['Gene'].plot(figsize=(18,7))\ndf_p['Trait'].unique().size\ntraits = df_p.groupby('Trait').count().sort_values('P-Value', ascending=False).index\ntraits[:50]\n\"\"\"\n# Genes by Trait\n\"\"\"\n\"\"\"\nFunction to search traits\n\"\"\"\nimport difflib\nmatches = difflib.get_close_matches('atherosclerosis', traits, n=15, cutoff=.4)\nmatches\ndef genes_by_trait(trait):\n    temp = df_p[df_p['Trait']==trait]\n    return set(temp['Gene']).union(set(temp['Gene 2']))\nlen(genes_by_trait('Body Mass Index'))\nlist_1 = ['Blood Pressure', 'Stroke', 'Diabetes Mellitus','Diabetes Mellitus, Type 2','Diabetes Mellitus, Type 1', 'Myocardial Infarction', 'Atherosclerosis', 'Plaque, Atherosclerotic']\nfactors_paired = [(i,j) for i in list_1 for j in list_1]\ncommon_genes = []\n\nfor i,j in factors_paired:\n    common_genes.append(len(genes_by_trait(i).intersection(genes_by_trait(j))))\ncommon_genes = np.array(common_genes).reshape(len(list_1),len(list_1))\ncommon_genes = pd.DataFrame(common_genes, index=list_1, columns=list_1)\ncommon_genes\nplt.figure(figsize=(15,5))\ncommon_genes.style.background_gradient(cmap='YlOrRd', axis=0)\ncommon_genes = genes_by_trait('Stroke').intersection(genes_by_trait('Diabetes Mellitus')).intersection(genes_by_trait('Blood Pressure'))\nprint(len(common_genes))\ncommon_genes\nmatches = difflib.get_close_matches('inflammatory bowel', traits, n=15, cutoff=.4)\nmatches\nlist_2 = ['Multiple Sclerosis', 'Psoriasis', 'Lupus Erythematosus, Systemic', 'Crohn Disease', 'Inflammatory Bowel Diseases', 'Diabetes Mellitus, Type 1']\nfactors_paired = [(i,j) for i in list_2 for j in list_2]\ncommon_genes = []\n\nfor i,j in factors_paired:\n    common_genes.append(len(genes_by_trait(i).intersection(genes_by_trait(j))))\ncommon_genes = np.array(common_genes).reshape(len(list_2),len(list_2))\ncommon_genes = pd.DataFrame(common_genes, index=list_2, columns=list_2)\ncommon_genes\nplt.figure(figsize=(15,5))\ncommon_genes.style.background_gradient(cmap='YlOrRd', axis=0)\n\"\"\"\nGene information from https:\/\/www.ensembl.org\/index.html\n\"\"\"\nimport requests, sys\nimport pprint\n\nserver = \"https:\/\/rest.ensembl.org\"\next = \"\/phenotype\/gene\/homo_sapiens\/GCKR?include_associated=0\"\n     \nr = requests.get(server+ext, headers={ \"Content-Type\" : \"application\/json\"})\n     \nif not r.ok:\n    r.raise_for_status()\n    sys.exit()\n     \ndecoded = r.json()\npprint.pprint(decoded)","meta":"{'source': 'AI4Code', 'id': 'ddf83df766a6ca'}"}
{"id":"69483","text":"\"\"\"\n# GridSearchCV:\n\n  GridSearchCV is a library function that is a member of sklearn's model_selection package. It helps to loop through predefined hyperparameters and fit your estimator (model) on your training set. So, in the end, you can select the best parameters from the listed hyperparameters.\n  \n![](https:\/\/imgur.com\/HSh9mej.png)\n\n# Gradient Boosting Classifier:\n  \n  Gradient boosting is a machine learning technique for regression and classification problems that produce a prediction model in the form of an ensemble of weak prediction models\n  \n![](https:\/\/imgur.com\/aPnHLAE.png)\n\"\"\"\n# 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 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\ndf = pd.read_csv('\/kaggle\/input\/factors-affecting-campus-placement\/Placement_Data_Full_Class.csv')\nprint(df)\ndf.isnull().sum()\ndf = df.fillna(0)\ndf\ndf.isnull().sum()\n\nx = df.drop('status', axis=1)\nx.head(10)\ny = df['status']\ny.head(10)\n\"\"\"\n# Label Encoding\n\"\"\"\n\nfrom sklearn import preprocessing \nlabel_encoder = preprocessing.LabelEncoder()  \nx= x.apply(label_encoder.fit_transform)\nprint(x)\ny= label_encoder.fit_transform(y)\nprint(y)\n\"\"\"\n# Train and Test Split\n\"\"\"\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state= 109)\n\"\"\"\n#  GradientBoostingClassifier and GridSearchCV\n\"\"\"\n#Build Model with GradientBoostingClassifier and GridSearchCV\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import StandardScaler\n#separating numerical and categorical col\nnumerical_col = ['ssc_p', 'hsc_p', 'degree_p', 'etest_p', 'mba_p']\ncategorical_col = ['gender', 'ssc_b', 'hsc_b', 'hsc_s', 'degree_t', 'workex', 'specialisation']\n#Creating Pipeline to Missing Data \n\n#inpute numerical missing data with median\nnumerical_transformer = make_pipeline(SimpleImputer(strategy='median'),\n                                      StandardScaler())\n\n#inpute categorical data with the most frequent value of the feature and make one hot encoding\ncategorical_transformer = make_pipeline(SimpleImputer(strategy='most_frequent'),\n                                        OneHotEncoder(handle_unknown='ignore'))\n\npreprocessor = ColumnTransformer(transformers=[('num', numerical_transformer, numerical_col),\n                                               ('cat', categorical_transformer, categorical_col)])\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\n\nclf = Pipeline([\n    ('preprocessor', preprocessor),\n    ('model', GradientBoostingClassifier())])\n#Using GradientBoostingClassifier with GridSearchCV to get better parameters\n\nparam_grid = {'model__learning_rate':[0.001, 0.01, 0.1], \n              'model__n_estimators':[100, 150, 200, 300, 350, 400]}\n\n#param_grid = {'model__learning_rate':[0.1], \n#              'model__n_estimators':[150]}\n\n#use recall score\ngrid = GridSearchCV(clf, param_grid, cv=10, scoring='accuracy', n_jobs=-1)\ngrid.fit(x_train, y_train)\ngrid.best_params_\nfrom sklearn.metrics import classification_report,confusion_matrix\npredictions = grid.predict(x_test)\nprint(confusion_matrix(y_test,predictions))\nprint(classification_report(y_test,predictions))\n\"\"\"\n# Plotting\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.countplot(x=\"degree_t\", data=df, hue='specialisation')\nplt.title(\"Candidate degree vs Placement\")\nplt.xlabel(\"Courses in degree\")\nplt.ylabel(\"Number of candidate\")\nplt.show()\ndf.plot.scatter(x='salary', y='mba_p',title='Candidate Performance')\ndf['salary'].plot.hist()\ndf['status'].value_counts().sort_index().plot.bar()\ndf.drop(['sl_no','ssc_p','hsc_p','etest_p'], axis=1).plot.line(title='Candidate Performance')\n\"\"\"\n***Pros:***\n\n* Exhaustive search, will find the absolute best way to tune the hyperparameters based on the training set.\n* Easy to find the optimal hyperparameters of a model which results in the most 'accurate' predictions. \n* More \u201cefficient\u201d use of data as every observation is used for both training and testing.\n\n***Cons:***\n\n* Time-consuming and danger of overfitting.\n* That when it comes to dimensionality, it suffers when evaluating the number of hyperparameters grows exponentially.\n\"\"\"\n\"\"\"\n# References:\n\n1. [https:\/\/medium.com\/better-programming\/comparing-grid-and-randomized-search-methods-in-python-cd9fe9c3572d](http:\/\/)\n2. https:\/\/medium.com\/@kesarimohan87\/model-selection-using-cross-validation-and-gridsearchcv-8756aac1e9d7\n3. https:\/\/medium.com\/datadriveninvestor\/an-introduction-to-grid-search-ff57adcc0998\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7fdff7485bffa6'}"}
{"id":"87434","text":"\"\"\"\n# Data Analysis and Forecasting of sales\nBook selling dataset by guftugu was given and they have placed home delivery information of books for more than an year. I have tried small data analysis and this notebook will be updated with time so stay tuned. I am planning to use machine learning so that i can help with better understanding of data and may be we can predict future sales.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom fbprophet import Prophet\n\nimport os\nBASE_DIR = '\/kaggle\/input\/gufhtugu-publications-dataset-challenge\/'\nfile_name = BASE_DIR + 'GP Orders - 2.csv'\ndf = pd.read_csv(file_name, encoding='cp1252')\ndf\n\"\"\"\nHere, We are visualizing the success of deliveries in the data set. How many orders were sucessful?\n\"\"\"\nplt.hist(df['Order Status'])\nprint('No of Completed Orders: ', len(df[df['Order Status'] == 'Completed']))\nprint('No of Returned Orders: ', len(df[df['Order Status'] == 'Returned']))\nprint('No of Canceled Orders: ', len(df[df['Order Status'] == 'Canceled']))\nplt.show()\n\"\"\"\nTop 10 cities having maximum order. For now, karachi has most no of orders. In future, we can relate it to no of population so that we can calculate the popularity of guftgu city wise. It will tell us where we need to work hard.\n\"\"\"\nmax_orders_per_city = dict({(city, len(df[df['City (Billing)'] == city]))\n                          for city in df['City (Billing)'].unique()})\ntop_orders_per_city = sorted(max_orders_per_city.items(), key=lambda x:x[1], reverse=True)[:10]\ntop_orders_per_city\n\"\"\"\nReturned orders by top 10 cities. Karachi is leading here too.\n\"\"\"\nreturned_orders = df[df['Order Status'] == 'Returned']\nreturned_per_city = dict({(city, len(returned_orders[returned_orders['City (Billing)'] == city]))\n                          for city in returned_orders['City (Billing)'].unique()})\ntop_returned_per_city = sorted(returned_per_city.items(), key=lambda x:x[1], reverse=True)[:10]\ntop_returned_per_city\n\"\"\"\nConverting date to python datetime object so that i can handle it for time series sale.\n\"\"\"\ndf[\"Order Date\"] = df[\"Order Date\"].apply(datetime.strptime, args=('%m\/%d\/%Y %H:%M',))\nfor i in range(len(df)):\n    df.loc[i, 'Order Date'] = df.loc[i, 'Order Date'].date()\n\"\"\"\nHere, I am going to create a dataframe that will have no of orders each day. I will try time series forcasting that can help me to predict no of orders that can happen in future on any day\n\"\"\"\ndates = df['Order Date'].unique()\norders_pre_date = [len(df[df['Order Date'] == date]) for date in dates]\ndf2 = pd.DataFrame(list(zip(dates, orders_pre_date)), \n               columns =['ds', 'y'])\ndf2 = df2.sort_values(['ds']).reset_index(drop=True)\ndf2\n\"\"\"\nHere is graph of no of orders on each day\n\"\"\"\nplt.figure(figsize=(20,10))\nplt.plot(df2['ds'], df2['y'])\n\"\"\"\nI am going to check my dataset on facebook's opensource time series forcasting library that will help us to predict no of orders in future.\n\"\"\"\nm = Prophet()\nm.fit(df2)\nfuture = m.make_future_dataframe(periods=10)\nforecast = m.predict(future)\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\nm.plot(forecast)\n\"\"\"\n**Forecasting is not much better. Will try different methods**\n\n# ****WORK IN PROGRESS****\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a054517445bd88'}"}
{"id":"82840","text":"\"\"\"\n<link rel=\"preconnect\" href=\"https:\/\/fonts.gstatic.com\">\n<link href=\"https:\/\/fonts.googleapis.com\/css2?family=Hachi+Maru+Pop&display=swap\" rel=\"stylesheet\">\n<link href=\"https:\/\/raw.githubusercontent.com\/twilson63\/istyle\/master\/amblin.css\" rel=\"stylesheet\">\n<div style=\"width:100%;text-align:center;font-family: 'Hachi Maru Pop', cursive;\">\n    <h1>House Prices: Advanced Regression Techniques<\/h1>\n<\/div>\n<br><br>\n\nMain objectives are;\n\n1. Frame the problem and look at the big picture.\n2. Get the data.\n3. Explore the data to gain insights.\n4. Prepare the data to better expose the underlying data patterns to Machine Learning algorithms.\n5. Explore many different models and shortlist the best ones.\n6. Fine-tune your models and combine them into a great solution.\n7. Present your solution.\n\n# Frame the Problem\n\n*  **Define the objective.**\n\nThe goal is to accurately predict house prices. You will pair your machine learning skills using [Ames Housing dataset](http:\/\/www.amstat.org\/publications\/jse\/v19n3\/decock.pdf).\n\n\n* **What are the current solutions\/workarounds (if any)?**\n\nThe current solution can be seen in [this](https:\/\/www.kaggle.com\/c\/house-prices-advanced-regression-techniques\/notebooks).\n\n\n* **How should you frame this problem (supervised\/unsupervised, online\/offline, etc.)?**\n\nSupervised, offline (batch), model-based learning.\n\n\n* **How should performance be measured?**\n\nSubmissions are evaluated on [Root-Mean-Squared-Error (RMSE)](https:\/\/en.wikipedia.org\/wiki\/Root-mean-square_deviation).\n\n\n* **What would be the minimum performance needed to reach the business objective?**\n\nThere is no minimum performance to reach the business objective, however, we can compare our results with [leaderboard](https:\/\/www.kaggle.com\/c\/house-prices-advanced-regression-techniques\/leaderboard).\n\n\n* **What are comparable problems? Can you reuse experience or tools?**\n\nSince this is my second competition contribution in Kaggle, I don't have any script to use. However, I can use some techniques from [my first notebook](https:\/\/www.kaggle.com\/onurserbetci\/end-to-end-titanic-project).\n\n# Import Relevant Libraries\n\nNow, we can import necessary libraries.\n\n\"\"\"\n# Main\nimport pandas as pd\nimport numpy as np\n\n# EDA and Data Vizualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nfrom plotly.offline import init_notebook_mode, iplot, plot\ninit_notebook_mode(connected=True)\nimport plotly.figure_factory as ff\n\n# Feature Engineering\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler, scale, RobustScaler, robust_scale, OrdinalEncoder\nfrom scipy.stats import skewtest, skew, shapiro, boxcox\nfrom sklearn.decomposition import PCA\n\n# Machine Learning\nfrom IPython.display import display, Markdown\nfrom sklearn.svm import LinearSVR, SVR\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet, SGDRegressor, RidgeCV, LassoCV, ElasticNetCV\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import AdaBoostRegressor, RandomForestRegressor, GradientBoostingRegressor, BaggingRegressor\nfrom sklearn.base import clone\nfrom tqdm import tqdm\n\nprint('Imported Successfully!')\n\"\"\"\n# Get the Data\n\nWe'll use `pandas` package for reading `.csv` file.\n\"\"\"\ntrain = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\nsubmission = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\ndf = pd.concat([train,submission]).set_index('Id')\nprint(f'df shape: {df.shape}\\ntrain shape: {train.shape}\\ntest shape: {submission.shape}')\n\"\"\"\nWe can check how much memory each variables are using in megabytes:\n\"\"\"\nprint(f'train.csv: \\n{(df.memory_usage(deep=True)\/(10**6)).sort_values(ascending=False)}\\n\\ntest.csv: \\n{(submission.memory_usage(deep=True)\/(10**6)).sort_values(ascending=False)}')\n\"\"\"\nAs we have the data now, we should create test dataset in order to avoid from data snooping.\n\"\"\"\neda,_=train_test_split(df, test_size=.2, random_state=42)\neda.shape\n\"\"\"\n# Explore the data (EDA)\n\nWe should get information about each attribute. Decide whether it is useful or not. There is lot of features, we should try to automate processes.\n\"\"\"\n# Creat price categories\nlabels=['Lower','Medium','Higher']\neda.loc[:,'price_cat'] = pd.qcut(eda.loc[:,'SalePrice'], 3, labels=labels)\n\n# Aplly log transformation to target for getting normalized results\neda['SalePrice_log'] = np.log(eda['SalePrice'])\n\n# EDA\ndef _inspect_cat_col(col):\n    _print_missing_values(col)\n    print(f'Count of each category for {col}:\\n')\n    print(eda[col].value_counts())\n    \ndef _print_missing_values(col):\n    print(f'Number of missing values: {eda[col].isnull().sum()}, Percentage: {eda[col].isnull().sum()\/len(eda[col].isnull())}\\n')\n\ndef _draw_pie_chart(col):\n    pd.set_option('mode.chained_assignment', None)\n    labels=['Lower','Medium','Higher']\n    \n\n    fig = make_subplots(rows=1, cols=3, specs=[[{'type':'domain'}, {'type':'domain'},{'type':'domain'}]], subplot_titles = labels)\n    for i,lb in enumerate(labels):\n        eda_price_labeled = eda[eda.price_cat==lb]\n        eda_price_counted = pd.DataFrame(eda_price_labeled.groupby(col)[col].count()).rename(columns={\n            col:'Count'}).reset_index()\n        fig.add_trace(go.Pie(values=eda_price_counted.Count, labels=eda_price_counted[col], name=lb),1,i+1)\n    fig.update_layout(title_text=f'{col} class distribution for each sale price bins')\n    iplot(fig)\n    \ndef _draw_violin_chart(col,price_log=False):\n    price_column_name = 'SalePrice_log' if price_log else 'SalePrice'\n    fig = go.Figure()\n\n    for cat in eda[col].unique():\n        fig.add_trace(go.Violin(x=eda[col][eda[col] == cat],\n                                y=eda[price_column_name][eda[col] == cat],\n                                name=str(cat),\n                                box_visible=True,\n                                meanline_visible=True))\n\n    iplot(fig)\n    \ndef _draw_pairplot(col,log_price=False,log_col=False, reciprocal_col=False):\n    price_column_name = 'SalePrice_log' if log_price else 'SalePrice'\n    if log_col:\n        log_column_name = col + '_log'\n        eda[log_column_name] = np.log(eda[col])\n        col = log_column_name\n    \n    ax = sns.pairplot(eda.loc[:,[col,price_column_name]], height=4, aspect=1.5, kind='reg')\n    ax.fig.suptitle(f'{col} VS {price_column_name}', y=1.05)\n    _print_missing_values(col)\n    print(f\"Correlation: {eda.loc[:,[col,price_column_name]].corr().iloc[0,1]}\")\n    plt.show()\n    \ndef _create_distplot_log(eda,col):\n    fig = ff.create_distplot([eda[col]],[col])\n    fig2 = ff.create_distplot([np.log(eda[col])],[col+'_log'])\n    iplot(fig)\n    print('After log tranformation')\n    iplot(fig2)\n\ndef automated_eda_report(eda):\n    for ind, current_col in enumerate(list(eda)):\n        if current_col in ['SalePrice','SalePrice_log','price_cat']:\n            continue\n        print(f'Current column is {current_col}')\n        print(f'Type of current columns is {label_map[current_col]}')\n        if label_map[current_col] == 'Categorical':\n            _inspect_cat_col(current_col)\n            _draw_pie_chart(current_col)\n            _draw_violin_chart(current_col)\n        elif label_map[current_col] == 'Ordinal Numerical' or label_map[current_col] == 'Ordinal Categorical':\n            print(f'Desriptive Stats Results for {current_col}:\\n')\n            print(eda[current_col].describe())\n            _draw_pairplot(current_col,log_price=True)\n            \n# Feature Engineering\n\ndef _print_done(col, trans):\n    print(f'PERFECTLY DONE! --> {trans} applied on {col}!')\n    \ndef _log_transformation(df_selected, col):\n    df_selected[col+'_trnsfrm'] = np.where(df_selected[col]!=0,\n                                           np.log(df_selected[col]), 0)\n    return df_selected\n\ndef _scale_log_transformation(df_selected, col):\n    df_selected[col+'_trnsfrm'] = scale(np.where(df_selected[col]!=0, \n                                                 np.log(df_selected[col]), 0))\n    return df_selected\n\ndef _scale_transformation(df_selected, col):\n    df_selected[col+'_trnsfrm'] = scale(df_selected[col])\n    return df_selected\n    \ndef _boxcox_transformation(df_selected, col):\n    if np.any(df_selected[col]==0):\n        data=df_selected[col]\n        posdata = data[data > 0]\n        bcdata, lam = boxcox(posdata)\n        if lam <= 0:\n            x = df_selected[col]\n        else:\n            x = np.empty_like(data)\n            x[data > 0] = bcdata\n            x[data == 0] = -1\/lam\n    else:\n        x,_ = boxcox(df_selected[col])\n    df_selected[col+'_trnsfrm'] = x\n    return df_selected\n\ndef _get_transformation_score(df, transformation_fuction, col):\n    df_trns=df.copy()\n    transformation_fuction(df_trns, col)\n    return shapiro(df_trns[col+'_trnsfrm'])[0]\n    \ndef _apply_best_transformation(df,col):\n    df_test = df.copy()\n    base_score = shapiro(df_test[col])[0]\n    \n    log_score = _get_transformation_score(df, _log_transformation, col)\n    scale_log_score = _get_transformation_score(df, _scale_log_transformation, col)\n    scale_score = _get_transformation_score(df, _scale_transformation, col)\n    boxcox_score = _get_transformation_score(df, _boxcox_transformation, col)\n    \n    arr = {'Do nothing':base_score,_log_transformation:log_score,\n           _scale_log_transformation:scale_log_score,\n           _scale_transformation:scale_score,\n           _boxcox_transformation:boxcox_score}\n    \n    # Select best tranformation with higher score\n    best_tranform_func = max(arr, key=arr.get)\n    if best_tranform_func == 'Do nothing':\n        return df\n    else:\n        return best_tranform_func(df, col)\n    \ndef _basic_fill(df_selected, col, cat=False):\n    df_selected[col] = df_selected.loc[:,col].fillna(df_selected.loc[:,col].value_counts().idxmax()) if cat else df_selected.loc[:,col].fillna(df_selected.loc[:,col].median())\n\ndef _custom_encoder(df_selected, col, col_type):\n    _col_df = np.array(df_selected.loc[:,col]).reshape(-1,1)\n    if col_type == 'Categorical':\n        enc = OneHotEncoder(sparse=False)\n    elif col_type == 'Ordinal Categorical':\n        enc = OrdinalEncoder()\n    else:\n        raise Exception(f'Cannot encode, check the {col} column!')\n    _col_enc = enc.fit_transform(_col_df)\n    temp = pd.DataFrame(_col_enc,index=df_selected.index)\n    temp.columns= enc.get_feature_names([col]) if col_type == 'Categorical' else [col+'_ord_trnsfrm']\n    df_selected=pd.concat([df_selected,temp], axis=1)\n    df_selected.drop(col, axis=1, inplace=True)\n    return df_selected\n\ndef automated_feature_engineering(df_or, label_map):\n    df = df_or.copy()\n    for col in list(df):\n        if col=='SalePrice':\n            continue\n        type_of_col = label_map[col]\n        _cat = True if (type_of_col == 'Categorical') or (type_of_col == 'Ordinal Categorical') else False\n        if df[col].isnull().sum() > 0:\n            _basic_fill(df, col, cat=_cat)\n        if _cat:\n            df=_custom_encoder(df, col, type_of_col)\n        elif type_of_col == 'Ordinal Numerical':\n            _apply_best_transformation(df,col)\n        else:\n            raise Exception(f'Unrecognized type of column! Please check the {col} column!')\n    return df\n\"\"\"\nI realized there are more of columns that not distributed equally or has lot of missing values. Maybe I can handle them in one, because they are taking so much times. Let's say if columns has more than 75% missing values or one feature's category is more than 75%, we are going to drop this attribute. \n\"\"\"\nthreshold_miss = len(eda)*0.75\nthreshold_distr = len(eda)*0.75\nfor col in eda:\n    if (eda[col].value_counts().iloc[0] >= threshold_distr or eda[col].isnull().sum() >= threshold_miss) and col != 'SalePrice':\n        eda.drop(col,axis=1,inplace=True)\nprint('Preview after dropping')\ndisplay(eda.head())\ndef next_col(last):\n    print(f'Next column is {[eda.iloc[:,ind+1].name for ind,col in enumerate(list(eda)) if col==last][0]}')\n\"\"\"\nWe should label each feature as categorical or numerical. We'll automate this as much as we can, however it should be applying in under supervision\n\"\"\"\nprint('All colum names after drop unnecessary ones:\\n')\nprint(list(eda))\ndef label_attrs(eda, target_col):\n    col_dict={}\n    for col in list(eda):\n        if col=='price_cat':\n            continue\n        class_name=type(eda[col].iloc[0]).__name__\n        if class_name == 'str':\n            col_dict.update({col: 'Categorical'})\n        elif class_name == 'float64':\n            col_dict.update({col:'Ordinal Numerical'})\n        elif eda[col].nunique() < len(eda)*.02:\n            if np.abs(eda[col].corr(eda[target_col])) > .15:\n                col_dict.update({col:'Ordinal Categorical'})\n            else:\n                col_dict.update({col: 'Categorical'})\n        else:\n            col_dict.update({col:'Ordinal Numerical'})\n    return col_dict\n\nprint('After automated labeling:\\n')\nlabel_map=label_attrs(eda, 'SalePrice')\nprint(label_map)\n%%javascript\nIPython.OutputArea.auto_scroll_threshold = 9999;\nplt.rcParams.update({'figure.max_open_warning': 0})\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\nautomated_eda_report(eda)\n\"\"\"\n# Feature Engineering\nFirst, we need to drop unuseful features as we did explanatory data anaylsis part. \n\"\"\"\n\"\"\"\n### Neighborhood\nIt provide us the neighborhood of each property.\n* Graphs would not be explanatory for the feature such has lot of category like this. We should try different approach if we don't want to lose information about neighborhood of house. We can categorize all as 3 whether they area expensive area or not.\n\"\"\"\neda_Neighborhood=eda.loc[:,['Neighborhood','price_cat']] # Use eda for getting price_cat column\neda_Neighborhood['count']=1\neda_Neighborhood=eda_Neighborhood.groupby(['Neighborhood','price_cat']).sum()\neda_Neighborhood.fillna(0,inplace=True)\nrows=[]\nfor neighborhood, counts in eda_Neighborhood.unstack().iterrows():\n    flg_dict={\n        'Neighborhood':neighborhood,\n        'Group':counts.idxmax()[1]\n    }\n    rows.append(flg_dict)\nneighborhood_map = pd.DataFrame(rows)\nneighborhood_map.set_index('Neighborhood',inplace=True)\ndisplay(neighborhood_map.head())\ndf_Neighborhood=df.copy()\nfor _,group in neighborhood_map.iterrows():\n    for ind,row in df_Neighborhood.iterrows():\n        if row['Neighborhood'] == group.name:\n            df_Neighborhood.loc[ind,'Neighborhood'] = group.values[0]\n# Drop below threshold like we did in EDA\nthreshold_miss = len(df_Neighborhood)*0.75\nthreshold_distr = len(df_Neighborhood)*0.75\ndf_drop = df_Neighborhood.copy()\nfor col in df_drop:\n    if (df_drop[col].value_counts().iloc[0] >= threshold_distr or df_drop[col].isnull().sum() >= threshold_miss) and col != 'SalePrice':\n        df_drop.drop(col,axis=1, inplace=True)\nprint('Completed!\\nPreview after dropping')\ndisplay(df_drop.head())\n\"\"\"\n### Automated Feature Engineering\n\"\"\"\nimport warnings\nwarnings.filterwarnings('ignore')\ndf_preprocessed=automated_feature_engineering(df_drop, label_map)\nsubmission_transformed=df_preprocessed[df_preprocessed.SalePrice.isnull()]\ndf_before_ml = df_preprocessed[~df_preprocessed.SalePrice.isnull()]\ny=df_before_ml[['SalePrice']]\nX=df_before_ml.drop('SalePrice',axis=1)\nX=scale(X)\ny=np.log(y)\nX_train,X_test, y_train, y_test = train_test_split(X,y,test_size=.2,random_state=42)\n%%time\n\n\nregressors = [\n    LinearSVR(random_state=42),DecisionTreeRegressor(random_state=42),RandomForestRegressor(random_state=42),\n    LinearRegression(),AdaBoostRegressor(random_state=42),\n    AdaBoostRegressor(LinearRegression()),BaggingRegressor(LinearRegression(),n_estimators=50),\n    Ridge(),GradientBoostingRegressor(random_state=42),\n    Lasso(),ElasticNet(),SGDRegressor()\n]\nscores={}\n\ntqdm()\nfor reg in tqdm(regressors):\n    reg.fit(X_train, y_train)\n    preds = reg.predict(X_test)\n    scores.update({\n        reg:np.sqrt(mean_squared_error(y_test,preds))\n    }) \nfor f,sc in scores.items():\n    display(Markdown(f'RMSE score of {f}={sc}'))\nbest_reg = list(scores)[np.argmin(list(scores.values()))]\ndisplay(Markdown(f'**Best regressor is {best_reg}**'))\nfor model_with_cv in [RidgeCV(), LassoCV(random_state=42), ElasticNetCV(random_state=42)]:\n    model_with_cv.fit(X,y)\n    res=f'$r^2$ of {model_with_cv}={model_with_cv.score(X,y)}'\n    display(Markdown(res))\ngbr = clone(best_reg)\ngbr.fit(X_train, y_train)\ngbr_preds = gbr.predict(X_test)\nr2_score(y_test, gbr_preds)\nfrom sklearn.inspection import permutation_importance\nimp = permutation_importance(gbr,X,y, n_repeats=10, random_state=42)\nimportance_df=pd.Series(imp.importances_mean).sort_values(ascending=False).to_frame().rename({0:'importance'},axis=1)\nimportance_df['cumsum']=importance_df.cumsum()\ndisplay(importance_df)\ngood_features=list(importance_df.loc[:importance_df['cumsum'].idxmax(),:].index)\nX_feature_extraction = X[:,good_features]\nprint(X_feature_extraction.shape)\nX_train,X_test, y_train, y_test = train_test_split(X_feature_extraction,y,test_size=.2,random_state=42)\ngbr.fit(X_train, y_train)\ngbr_preds = gbr.predict(X_test)\nprint(np.sqrt(mean_squared_error(y_test, gbr_preds)))\npca = PCA(n_components='mle')\n\narr_pca=pca.fit_transform(X_feature_extraction)\nX_pca = pd.DataFrame(arr_pca, columns=['PCA'+str(i) for i in range(arr_pca.shape[1])])\n\ngraph_var = pca.explained_variance_ratio_\n\nfig = go.Figure(data=[\n    go.Bar(name='Explained Variance', x=np.arange(len(graph_var)), y=graph_var*100)\n])\nfig.add_trace(go.Scatter(x=np.arange(1,len(graph_var)+1), \n                         y=np.cumsum(graph_var)*100,\n                         mode='lines',\n                         name='Cumulated Explained Variance'))\n# Change the bar mode\nfig.update_layout(barmode='stack')\n\nprint(f'Dataset has total feature of {X_feature_extraction.shape[1]}')\nprint(f'Total explained variance: {np.sum(pca.explained_variance_ratio_)*100}% with n_components={pca.n_components_}')\nfig.show()\ngbr = RidgeCV(scoring='neg_root_mean_squared_error').fit(X_pca,y)\nrmse=f'**RMSE score of {gbr}={gbr.score(X_pca,y)}**'\ndisplay(Markdown(rmse))\nX_train,X_test, y_train, y_test = train_test_split(X_pca,np.log(y), test_size=.2, random_state=42)\ngbr = Ridge(random_state=42)\ngbr.fit(X_train, y_train)\ngbr_preds = gbr.predict(X_test)\nrmse = np.sqrt(mean_squared_error(y_test, gbr_preds))\ndisplay(Markdown(f'**RMSE = {rmse}**'))\nr2=f'**$r^2$ of {gbr}={r2_score(y_test,gbr_preds)}**'\ndisplay(Markdown(r2))\nsns.distplot(np.log(y))\nsubmission_transformed.drop(columns = 'SalePrice', inplace=True)\nsubmission_transformed.index\nsub=scale(pca.transform(submission_transformed.iloc[:,good_features]))\nres=gbr.predict(sub)\nprice_predicted=pd.DataFrame(np.exp(np.exp(res)),index=submission_transformed.index).rename({0:'SalePrice'},axis=1)\ndisplay(price_predicted)\nprice_predicted.to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': '9814d96542a840'}"}
{"id":"44141","text":"\"\"\"\n### B\u00fcy\u00fck Veri Analizine Giri\u015f Part-2\n\"\"\"\n\"\"\"\n### \u0130sim Soyisim: Tayyip Mert Denizgez\n### Numara: 160201036\n### E-Posta: tdenizgez@gmail.com\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n### Load Data\n\"\"\"\nsales_train = pd.read_csv(\"..\/input\/competitive-data-science-predict-future-sales\/sales_train.csv\")\nitems = pd.read_csv(\"..\/input\/competitive-data-science-predict-future-sales\/items.csv\")\n\nsales_train.head()\nsales_train.tail()\nitems.head()\nitems=items.drop(\"item_name\",axis=1)\nitems.head()\ntrain_data = pd.merge(sales_train, items, on='item_id')\ntrain_data.head()\ntrain = train_data\n\"\"\"\n### Preprocess\n\"\"\"\n#Outlier De\u011ferleri Kald\u0131rd\u0131k\ntrain = train[train.item_price<100000]\ntrain = train[train.item_cnt_day<1001]\nmedian = train[(train.shop_id==32)&(train.item_id==2973)&(train.date_block_num==4)&(train.item_price>0)].item_price.median()\ntrain.loc[train.item_price<0, 'item_price'] = median\nimport datetime\ntrain_data.date = train_data.date.apply(lambda x:datetime.datetime.strptime(x, \"%d.%m.%Y\"))\ntrain_data.head()\ngrouped = pd.DataFrame(train_data.groupby(['shop_id', 'date_block_num','item_id'])['item_cnt_day'].sum().reset_index())\ntotal_item_cnt_mounth = grouped.groupby('date_block_num')['item_cnt_day'].sum()\n#Total Shop Count:60\n#Total Mounth Count:34\n\"\"\"\n### Verinin G\u00f6rselle\u015ftirilmesi\n\"\"\"\nfrom math import ceil\nfig, axes = plt.subplots(nrows=5, ncols=2, sharex=True, sharey=True, figsize=(16,20))\nnum_graph = 10\nid_per_graph = ceil(grouped.shop_id.max() \/ num_graph)\ncount = 0\nfor i in range(5):\n    for j in range(2):\n        sns.pointplot(x='date_block_num', y='item_cnt_day', hue='shop_id', data=grouped[np.logical_and(count*id_per_graph <= grouped['shop_id'], grouped['shop_id'] < (count+1)*id_per_graph)], ax=axes[i][j])\n        count += 1\nprint(total_item_cnt_mounth.head())\ntotal_item_cnt_mounth_np = total_item_cnt_mounth.to_numpy()\ntotal_item_cnt_mounth_np\nmounths = np.arange(34)\nmounths\nplt.plot(mounths,total_item_cnt_mounth_np)\nplt.xlabel('Mounth')\nplt.ylabel('Total Sale Count')\nplt.show()\n\"\"\"\n### 11-12 ve 23-24. aylarda sat\u0131\u015flar\u0131n peek yapt\u0131\u011f\u0131n\u0131 g\u00f6r\u00fcyoruz. Bu da demek oluyor ki m\u00fc\u015fteriler y\u0131l sonlar\u0131nda daha fazla \u00fcr\u00fcn almaktad\u0131r. \n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nX_train, X_test, y_train, y_test = train_test_split(mounths,total_item_cnt_mounth_np, test_size = 1\/3, random_state = 123, shuffle=1)\nX_train = X_train.reshape(-1, 1)\nX_test = X_test.reshape(-1, 1)\ny_train = y_train.reshape(-1, 1)\ny_test = y_test.reshape(-1, 1)\nprint(X_train.shape,X_test.shape,y_train.shape,y_test.shape)\nmodel = LinearRegression()\nmodel.fit(X_train, y_train)\nmodel.score(X_train,y_train)\nmodel.predict([[34]])\n\"\"\"\n### Liner Regresyon Modelimize g\u00f6re bir sonraki ayda yap\u0131lacak toplam \u00fcr\u00fcn sat\u0131\u015f\u0131 79248 olacakt\u0131r\n\"\"\"\npred = model.predict(X_test)\ndf = pd.DataFrame({'Actual': y_test.flatten(), 'Predicted': pred.flatten()})\ndf\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nmse = mean_squared_error(y_test, pred)\nmse\nrmse = sqrt(mean_squared_error(y_test, pred))\nrmse","meta":"{'source': 'AI4Code', 'id': '51635faddeaebe'}"}
{"id":"136516","text":"\"\"\"\n# DATA VISUALIZATION & DATA AGGREGATION WITH PYTHON & SQL\n[Muhammad Rifki](https:\/\/www.linkedin.com\/in\/muhammadrifki\/) - January 2021\n\"\"\"\n\"\"\"\nThe objective of this notebook is merely an exercise to showcase some required skills for a Business Intelligence like SQL query and Python language. Thus, I do some simple data visualization & aggregation of e-commerce in Brazil.\n\"\"\"\n# Standard libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport glob\nimport plotly.express as px\nimport os\nimport warnings\n\n# Local server SQL database\nimport sqlite3 as sq\n\n# Setting of Large numbers format\npd.options.display.float_format = '{:,.2f}'.format\n\n# Set data frame display max 10 rows\npd.set_option('display.max_rows', 10)\n\n# Warning is suppressed\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n# Set-up a connection to a newly named project1.db\ncon = sq.connect('project1.db')\ncur = con.cursor()\n# Get the count of customers_dataset table\ncur.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='..\/input\/brazilian-ecommerce\/olist_customers_dataset.csv' OR name='customers_dataset' ''')\n\n# If the count is 1, then customers_dataset table already exists\nif cur.fetchone()[0]==1 : {\n\tprint('Table already created.')\n}\nelse: # Read all files from csv to db format\n    path = '..\/input\/brazilian-ecommerce'\n    all_files = glob.glob(path + \"\/*.csv\")\n    for file in all_files: # For all files in our directory\n        df = pd.read_csv(file, index_col=0) # Read each CSV file\n        df.to_sql(file, con) # Create the read file as a table in the database.\n# Get the count of customers_dataset table\ncur.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='customers_dataset' ''')\n\n# If the count is 1, then customers_dataset table already renamed\nif cur.fetchone()[0]==1:\n\tprint('Table already renamed.')\n\nelse:\n    # Rename all tables\n    rename_tables_query1 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_customers_dataset.csv\" RENAME TO \"customers_dataset\"'\n    rename_tables_query2 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_geolocation_dataset.csv\" RENAME TO \"geolocation_dataset\"'\n    rename_tables_query3 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_orders_dataset.csv\" RENAME TO \"orders_dataset\"'\n    rename_tables_query4 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_order_items_dataset.csv\" RENAME TO \"order_items_dataset\"'\n    rename_tables_query5 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_order_payments_dataset.csv\" RENAME TO \"order_payments_dataset\"'\n    rename_tables_query6 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_order_reviews_dataset.csv\" RENAME TO \"order_reviews_dataset\"'\n    rename_tables_query7 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_products_dataset.csv\" RENAME TO \"products_dataset\"'\n    rename_tables_query8 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/olist_sellers_dataset.csv\" RENAME TO \"sellers_dataset\"'\n    rename_tables_query9 = 'ALTER TABLE \"..\/input\/brazilian-ecommerce\/product_category_name_translation.csv\" RENAME TO \"product_category_name_translation\"'\n\n    # The function read_sql takes a query string and a database connection, and performs the query.\n    rename_tables1 = pd.read_sql(rename_tables_query1, con)\n    rename_tables2 = pd.read_sql(rename_tables_query2, con)\n    rename_tables3 = pd.read_sql(rename_tables_query3, con)\n    rename_tables4 = pd.read_sql(rename_tables_query4, con)\n    rename_tables5 = pd.read_sql(rename_tables_query5, con)\n    rename_tables6 = pd.read_sql(rename_tables_query6, con)\n    rename_tables7 = pd.read_sql(rename_tables_query7, con)\n    rename_tables8 = pd.read_sql(rename_tables_query8, con)\n    rename_tables9 = pd.read_sql(rename_tables_query9, con)\n# Read all table names\ntable_list = [a for a in cur.execute(\"SELECT name FROM sqlite_master WHERE type = 'table'\")]\n\n# Table list\nprint(table_list)\n# Write a SQL query of Total Orders and Total Sales\nq1 = (\n      'SELECT count(a.order_id) AS Total_Orders, '\n      '       sum(b.price + b.freight_value) AS Total_Sales '\n      'FROM orders_dataset AS a '\n      'INNER JOIN order_items_dataset AS b '\n      'ON a.order_id = b.order_id '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr1 = pd.read_sql(q1, con)\nr1\n# Write a SQL query of Orders by Time\nq2 = (\n      'SELECT strftime(\"%Y-%m\", order_approved_at) AS date, '\n      '       COUNT(order_id) AS order_qty '\n      'FROM orders_dataset '\n      'GROUP BY date '\n      'ORDER BY date '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr2 = pd.read_sql(q2, con)\nr2.head(5)\n# Plotting orders by time data \nfig1 = px.bar(r2, x=\"date\", y=\"order_qty\", orientation='v', title='Orders by Date in Brazilian E-Commerce (2016-2018)')\nfig1.show()\n# Write a SQL query of Sales by Time\nq3 = (\n      'SELECT strftime(\"%Y-%m\", a.order_approved_at) AS date, '\n      '       SUM(b.price) AS sales '\n      'FROM orders_dataset AS a '\n      'INNER JOIN order_items_dataset AS b '\n      'ON a.order_id = b.order_id '\n      'GROUP BY date '\n      'ORDER BY date '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr3 = pd.read_sql(q3, con)\nr3.head(5)\n# Plotting sales by time data \nfig2 = px.line(r3, x=\"date\", y=\"sales\", title='Sales by Time in Brazilian E-Commerce (2016-2018)')\nfig2.show()\n# Write a SQL query of Selling Product Categories Quantity\nq4 = (\n      'SELECT a.product_category_name_english AS product, '\n      '       COUNT(b.product_category_name) AS qty '\n      'FROM product_category_name_translation AS a '\n      'INNER JOIN products_dataset AS b '\n      'ON a.product_category_name = b.product_category_name '\n      'GROUP BY product '\n      'ORDER BY qty DESC '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr4 = pd.read_sql(q4, con)\nr4_top = r4.head(5)\nr4_top\n# Plotting selling product categories quantity data\nfig3 = px.bar(r4_top, x=\"qty\", y=\"product\", orientation='h', barmode=\"group\", title='Top 5 Selling Product Categories in Brazilian E-Commerce (2016-2018)')\nfig3.update_layout(yaxis={'categoryorder':'total ascending'})\nfig3.show()\n# Write a SQL query of Sellers by City\nq5 = (\n      'WITH temp_sellers AS '\n      '( '\n      '      SELECT a.seller_city AS seller_city, '\n      '      COUNT(b.order_id) AS sales_qty, '\n      '      COUNT(b.order_id) * 100.0 \/ SUM(COUNT(b.order_id)) OVER () AS temp_sales_percentage '\n      '      FROM sellers_dataset AS a '\n      '      INNER JOIN order_items_dataset AS b '\n      '      ON a.seller_id = b.seller_id '\n      '      GROUP BY seller_city '\n      '      ORDER BY sales_qty DESC '\n      ') '\n      'SELECT seller_city, '\n      '       sales_qty, '\n      '       printf(\"%.2f\", temp_sales_percentage) AS sales_percentage '\n      'FROM temp_sellers '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr5 = pd.read_sql(q5, con)\nr5_top = r5.head(5)\nr5_top\n# Plotting selling sellers by city data\nfig4 = px.bar(r5_top, x=\"sales_qty\", y=\"seller_city\", orientation='h', hover_data=['sales_percentage'], color='sales_percentage', title='Top 5 Sellers by City in Brazilian E-Commerce (2016-2018)')\nfig4.update_layout(yaxis={'categoryorder':'total ascending'})\nfig4.show()\n# Write a SQL query of Customers by City\nq6 = (\n      'WITH temp_customer AS '\n      '( '\n      '      SELECT a.customer_city AS customer_city, '\n      '      COUNT(b.order_id) AS order_qty, '\n      '      COUNT(b.order_id) * 100.0 \/ SUM(COUNT(b.order_id)) OVER () AS temp_order_percentage '\n      '      FROM customers_dataset AS a '\n      '      INNER JOIN orders_dataset AS b '\n      '      ON a.customer_id = b.customer_id '\n      '      GROUP BY customer_city '\n      '      ORDER BY order_qty DESC '\n      ') '\n      'SELECT customer_city, '\n      '       order_qty, '\n      '       printf(\"%.2f\", temp_order_percentage) AS order_percentage '\n      'FROM temp_customer '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr6 = pd.read_sql(q6, con)\nr6_top = r6.head(5)\nr6_top\n# Plotting selling customer by city data\nfig5 = px.bar(r6_top, x=\"order_qty\", y=\"customer_city\", orientation='h', hover_data=['order_percentage'], color='order_percentage', title='Top 5 Customers by City in Brazilian E-Commerce (2016-2018)')\nfig5.update_layout(yaxis={'categoryorder':'total ascending'})\nfig5.show()\n# Write a SQL query of Average, Max, and Min Products\nq7 = (\n      'SELECT AVG(price) AS Average_Price, '\n      '       MAX(price) AS Max_Price, '\n      '       MIN(price) AS Min_Price '\n      'FROM order_items_dataset '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr7 = pd.read_sql(q7, con)\nr7\nq8 = (\n      'WITH average_time AS '\n      '( '\n      '     SELECT julianday(order_estimated_delivery_date) - julianday(order_delivered_customer_date) AS delivery_time '\n      '     FROM orders_dataset '\n      '     WHERE order_status = \"delivered\" '\n      ') '\n      'SELECT AVG(delivery_time) AS \"Average_Delivery_Time_Interval_(Estimated_vs_Actual)\" '\n      'FROM average_time '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr8 = pd.read_sql(q8, con)\nr8\n# Write a SQL query of Delivery Interval (Estimated vs Actual) per Month\nq9 = (\n      'WITH average_time AS '\n      '( '\n      '     SELECT strftime(\"%Y-%m\", order_delivered_customer_date) AS date, '\n      '            julianday(order_estimated_delivery_date) - julianday(order_delivered_customer_date) AS delivery_time, '\n      '            COUNT(order_id) AS qty'\n      '     FROM orders_dataset '\n      '     WHERE order_status = \"delivered\" '\n      '     GROUP BY date '\n      '     ORDER BY date '\n      ') '\n      'SELECT date AS Date, delivery_time AS Day, qty AS Qty '\n      'FROM average_time '\n      )\n\n# Convert the SQL query to Pandas data Frame\nr9 = pd.read_sql(q9, con)\nr9\n# Plotting Delivery Interval (Estimated vs Actual) per Month data \nfig6 = px.bar(r9, x=\"Date\", y=\"Day\", orientation='v', hover_data=['Qty'], color='Qty', title='Delivery Interval (Estimated vs Actual) per Month in<br>Brazilian E-Commerce (2016-2018)')\nfig6.show()\n# Close connection to Database\ncon.close()","meta":"{'source': 'AI4Code', 'id': 'faecf7c816fd8c'}"}
{"id":"38509","text":"\"\"\"\n\u5728 [Pneumonia Detection by VGG16](https:\/\/www.kaggle.com\/whitelee\/pneumonia-detection-by-vgg16) \u4e2d\u6211\u5011\u900f\u904e Transfer Learning \u7684\u4f5c\u6cd5 fine-tune VGG16 model \u53d6\u5f97\u4e86\u4e0d\u932f\u7684\u9810\u6e2c\u7d50\u679c (F1 Score \u7d04 0.93 ~ 0.94)\uff0c\u5f8c\u7e8c\u4f5c\u4e86\u8a31\u591a\u5617\u8a66 (\u5c0d\u5f71\u50cf\u4f5cBlur, Shapern \u6216 Morphology \u8655\u7406\u3001\u63db model \u7b49) \u4e0d\u904e\u90fd\u7121\u6cd5\u53d6\u5f97\u7a81\u7834\u3002\n\n\u5728\u5617\u8a66\u904e\u7a0b\u4e2d\u63a5\u89f8\u5230 `CAM (Class Activation Mapping)` \u9019\u500b\u5be6\u4f5c\uff0cCAM \u53ef\u4ee5\u7528\u4f86 `\u5e6b\u52a9\u6211\u5011\u7406\u89e3\u5716\u7247\/\u5f71\u50cf\u4e2d\u90a3\u500b\u90e8\u4efd\u662f\u8b93 CNN \u4f5c\u51fa\u6700\u7d42\u6c7a\u7b56\u7684\u4f9d\u64da`\u3002\nCAM \u6700\u65e9\u7531 Bolei Zhou \u7b49\u4eba\u65bc2016\u5e74\u5728 [Learning Deep Features for Discriminative Localization](https:\/\/arxiv.org\/abs\/1512.04150) \u8ad6\u6587\u4e2d\u63d0\u51fa\uff0c2017\u5e74Selvaraju et al.\u7b49\u4eba\u5247\u63d0\u51fa\u6539\u826f\u7248\u672c [Grad-CAM](https:\/\/arxiv.org\/abs\/1610.02391) \u4ee5\u514b\u670d CAM \u5728 CNN \u7d50\u69cb\u4e0a\u7684\u9650\u5236\u3002\n\nGrad-CAM \u7684\u6982\u5ff5\u662f\u900f\u904e\u53cd\u5411\u50b3\u64ad (Back Propagation) \u63a8\u7b97\u5404\u985e\u5225\u5c0d\u5716\u7247\u4e2d\u5404\u90e8\u4f4d\u7684\u68af\u5ea6\u503c(Gradient) \u4f5c\u70ba\u6b0a\u91cd\uff0c\u4ee5\u7e6a\u88fd\u985e\u5225\u7684heatmap\u3002\n\u60f3\u5c0d Grad-CAM \u6709\u591a\u4e00\u9ede\u4e86\u89e3\u7684\u53ef\u53c3\u8003\u9019\u7bc7 [\u6587\u7ae0](https:\/\/medium.com\/%E6%89%8B%E5%AF%AB%E7%AD%86%E8%A8%98\/grad-cam-introduction-d0e48eb64adb)\u3002\n\n\u6211\u60f3 CAM \u53ef\u4ee5\u63d0\u4f9b\u5169\u500b\u5f88\u6709\u50f9\u503c\u7684\u7528\u9014:\n1. \u85c9 CAM \u4f5c\u70ba debug \u4f9d\u64da\uff0c\u627e\u51fa\u5c0d\u6a21\u578b\u6709\u5e6b\u52a9\u4e4b\u5716\u7247\u8655\u7406\u65b9\u5f0f (\u56e0\u70ba\u770b\u5b8cheatmap\u7d50\u679c\u5f8c\u4f9d\u7136\u6c92\u4ec0\u9ebc\u65b9\u5411\uff0c\u76ee\u524d\u6c92\u6709\u5617\u8a66\uff1b\u82e5\u770b\u5b8c\u672c\u6587\u6709\u4ec0\u9ebcidea\u6b61\u8fce\u5206\u4eab)\u3002\n2. \u5728\u5be6\u969b\u61c9\u7528\u4e0a\uff0c\u4ea6\u63d0\u4f9b heatmap \u544a\u77e5\u4f7f\u7528\u8005 model \u6c7a\u7b56\u7684\u90e8\u4f4d\uff0c\u4ee5\u5354\u52a9\u4f7f\u7528\u8005\u6c7a\u5b9a\u662f\u5426\u63a5\u53d7 model \u7684\u5224\u65b7\u3002\n\n\u4ee5\u4e0b\u5c55\u793a Fine-tune ResNet \u6a21\u578b\uff0c\u4e26\u5957\u7528 CAM \u7522\u751f TP \/ FP \/ TN \/ FN \u4e4b heatmap \u89c0\u5bdf\u6a21\u578b\u7684\u6c7a\u7b56\u4f9d\u64da\u3002\n\"\"\"\n!rm .\/*.hdf5\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mimg\nimport seaborn as sns\n%matplotlib inline\nfrom sklearn.metrics import confusion_matrix\n\nimport cv2\nimport os\nimport glob\n\"\"\"\n### \u8cc7\u6599\u524d\u8655\u7406\n\"\"\"\n# Input data files are available in the \"..\/input\/\" directory.\nINPUT_PATH = \"..\/input\/pneumonia-detection\/chest_xray\"\n\n# List the files in the input directory.\nprint(os.listdir(INPUT_PATH))\nbase_dir = INPUT_PATH\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'val')\ntest_dir = os.path.join(base_dir, 'test')\n\ntrain_0_dir = os.path.join(train_dir, 'Normal'.upper())\ntrain_1_dir = os.path.join(train_dir, 'Pneumonia'.upper())\n\nval_0_dir = os.path.join(val_dir, 'Normal'.upper())\nval_1_dir = os.path.join(val_dir, 'Pneumonia'.upper())\n\ntest_0_dir = os.path.join(test_dir, 'Normal'.upper())\ntest_1_dir = os.path.join(test_dir, 'Pneumonia'.upper())\n\ndef get_data_list():\n    train_0_list = [os.path.join(train_0_dir, fn) for fn in os.listdir(train_0_dir)]\n    train_1_list = [os.path.join(train_1_dir, fn) for fn in os.listdir(train_1_dir)]\n    val_0_list = [os.path.join(val_0_dir, fn) for fn in os.listdir(val_0_dir)]\n    val_1_list = [os.path.join(val_1_dir, fn) for fn in os.listdir(val_1_dir)]\n    test_0_list = [os.path.join(test_0_dir, fn) for fn in os.listdir(test_0_dir)]\n    test_1_list = [os.path.join(test_1_dir, fn) for fn in os.listdir(test_1_dir)]\n\n    # list dir numbers\n    print('total picture numbers in train_0_dir: ', len(train_0_list))\n    print('total picture numbers in train_1_dir: ', len(train_1_list))\n    print('total picture numbers in val_0_dir: ', len(val_0_list))\n    print('total picture numbers in val_1_dir: ', len(val_1_list))\n    print('total picture numbers in test_0_dir: ', len(test_0_list))\n    print('total picture numbers in test_1_dir: ', len(test_1_list))\n\n    return (train_0_list, train_1_list, val_0_list, val_1_list, test_0_list, test_1_list)\n(train_0_list, train_1_list, val_0_list, val_1_list, test_0_list, test_1_list) = get_data_list()\n\"\"\"\n###### Move images from train to val list to increase validation set\n\n\u6211\u5011\u89c0\u5bdf\u5230 `\u8abf\u6574 validation set \u4e2d 0 (mv_cnt_0) \u8207 1 (mv_cnt_1) \u7684\u6bd4\u4f8b\u5c0d\u6a21\u578b\u7684\u9810\u6e2c\u80fd\u529b\u6703\u7522\u751f\u5f71\u97ff` \uff0c\u5927\u81f4\u4e0a\u4f86\u8aaa (mv_cnt_0, mv_cnt_1) \u70ba (300, 300) \u6642 F1 score \u8868\u73fe\u8f03\u4f73\uff0c\u8b8a\u66f4\u70ba (200, 400) \u6642\u6703\u6709\u66f4\u597d\u7684 Recall\uff1b\u9019\u4e5f\u8aaa\u660e\u4e86 Validation set \u53ca Validation \u7b56\u7565\u8a2d\u8a08\u7684\u91cd\u8981\u6027\u3002\n\"\"\"\nimport random \n(mv_cnt_0, mv_cnt_1) = (300, 300)\n\nif len(val_0_list) < mv_cnt_0:\n    mv_list_0 = random.sample(train_0_list, mv_cnt_0)\n    mv_list_1 = random.sample(train_1_list, mv_cnt_1)\n    train_0_list = [fn for fn in train_0_list if not fn in mv_list_0]\n    train_1_list = [fn for fn in train_1_list if not fn in mv_list_1]\n    val_0_list += mv_list_0\n    val_1_list += mv_list_1\n    \n    print('total picture numbers in train_0_dir: ', len(train_0_list))\n    print('total picture numbers in train_1_dir: ', len(train_1_list))\n    print('total picture numbers in val_0_dir: ', len(val_0_list))\n    print('total picture numbers in val_1_dir: ', len(val_1_list))\n    print('total picture numbers in test_0_dir: ', len(test_0_list))\n    print('total picture numbers in test_1_dir: ', len(test_1_list))\n\"\"\"\nPreprocess images with the following operations and create dataset\n* resize to 224*224\n* Only capture (y1, y2, x1, x2) = (top,top+200, left,left+200) (left, top) = (15, 40) to focus on lung part only\n\"\"\"\n(left, top) = (15, 40)\n(y1, y2, x1, x2) = (top,top+200, left,left+200)\ndef image_resize(img_path):\n    # print(dataset.shape)\n    \n    im = cv2.imread(img_path)\n    im = cv2.resize(im, (224,224))\n    if im.shape[2] == 1:\n        # np.dstack(): Stack arrays in sequence depth-wise (along third axis).\n        # https:\/\/docs.scipy.org\/doc\/numpy\/reference\/generated\/numpy.dstack.html\n        im = np.dstack([im, im, im])\n        \n        # ----------------------------------------------------------------------------------------\n        # cv2.cvtColor(): The function converts an input image from one color space to another. \n        # [Ref.1]: \"cvtColor - OpenCV Documentation\"\n        #     - https:\/\/docs.opencv.org\/2.4\/modules\/imgproc\/doc\/miscellaneous_transformations.html\n        # [Ref.2]: \"Python\u8ba1\u7b97\u673a\u89c6\u89c9\u7f16\u7a0b- \u7b2c\u5341\u7ae0 OpenCV\" \n        #     - https:\/\/yongyuan.name\/pcvwithpython\/chapter10.html\n        # ----------------------------------------------------------------------------------------\n    x_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n    x_image = x_image[y1:y2, x1:x2]\n    x_image = cv2.resize(x_image, (150,150))\n    # Normalization\n    # x_image = x_image.astype(np.float32)\/255.\n    return x_image\n\"\"\"\n======== Show pictures after being resized=====\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mimg\n%matplotlib inline\nimport cv2\nimport numpy as np\nfn_list_0 = train_0_list[:4]\nfn_list_1 = train_1_list[:4]\n\nfig, ax = plt.subplots(2, 4, figsize=(20,10))\nfor i, axi in enumerate(ax.flat):\n    img_path = None\n    if i < 4:\n        img_path = fn_list_0[i]\n    else:\n        img_path = fn_list_1[i-4]\n    img = image_resize(img_path)#.astype(np.uint8)\n    axi.imshow(img, cmap='bone')\n    axi.set_title(img_path.split('\/')[-1])\n    axi.set(xticks=[], yticks=[])\n\"\"\"\nMake datasets for train, val and test \n\"\"\"\ndef create_dataset(img_path_list_0, img_path_list_1, return_fn = False):\n    # list of the paths of all the image files\n    normal = img_path_list_0\n    pneumonia = img_path_list_1\n\n    # --------------------------------------------------------------\n    # Data-paths' format in (img_path, label) \n    # labels : for [ Normal cases = 0 ] & [ Pneumonia cases = 1 ]\n    # --------------------------------------------------------------\n    normal_data = [(image, 0) for image in normal]\n    pneumonia_data = [(image, 1) for image in pneumonia]\n\n    image_data = normal_data + pneumonia_data\n\n    # Get a pandas dataframe for the data paths \n    image_data = pd.DataFrame(image_data, columns=['image', 'label'])\n#     print(image_data.head(5))\n    # Shuffle the data \n    image_data = image_data.sample(frac=1., random_state=100).reset_index(drop=True)\n    \n    # Importing both image & label datasets...\n    (x_images, y_labels) = ([image_resize(image_data.iloc[i][0]) for i in range(len(image_data))], \n                         [image_data.iloc[i][1] for i in range(len(image_data))])\n\n    # Convert the list into numpy arrays\n    x_images = np.array(x_images)\n    y_labels = np.array(y_labels)\n    \n    print(\"Total number of images: \", x_images.shape)\n    print(\"Total number of labels: \", y_labels.shape)\n    \n    if not return_fn:\n        return (x_images, y_labels)\n    else:\n        return (x_images, y_labels, image_data.image.values)\n# Import train dataset...\n(x_train, y_train) = create_dataset(train_0_list, train_1_list)\n\nprint(x_train.shape)\nprint(y_train.shape)\n# Import val dataset...\n(x_val, y_val) = create_dataset(val_0_list, val_1_list)\n\"\"\"\nApply ResNet50 module of keras for training & prediction\n\n\u5728\u6b64\u6211\u5011 `\u4f7f\u7528 ResNet50 \u5728 Keras \u7684\u5be6\u4f5c (\u4f7f\u7528 TensorFlow 1.x \u7248\u672c\u70ba backend) \u4f86\u8a13\u7df4`\uff1b\u4e8b\u5be6\u4e0a ResNet50 \u5728\u8a13\u7df4\u904e\u7a0b\u4e2d\u7684\u6578\u503c\u4e26\u4e0d\u662f\u5f88\u6b63\u5e38\uff0c\u4f46\u8dd1\u4f86\u7d50\u679c\u4e0d\u6bd4 VGG16 \u5dee\uff0c\u4e14\u672c\u7bc7\u91cd\u9ede\u5728 CAM\uff0c\u770b\u500c\u82e5\u6709\u8208\u8da3\u53ef\u4ee5 folk \u6b64 notebook \u904e\u53bb\u6539\u6210VGG16\u8a66\u8a66\u770b\u3002\n\"\"\"\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2\n# base_model = ResNet50(weights='..\/input\/keras-pretrained-models\/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', input_shape=(150, 150, 3), include_top = False, pooling = 'avg')\n# base_model = VGG16(weights='..\/input\/keras-pretrained-models\/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5', input_shape=(150, 150, 3), include_top = False)\nbase_model = InceptionResNetV2(weights='..\/input\/keras-pretrained-models\/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5', \n                   input_shape=(150, 150, 3), include_top = False)\nbase_model.summary()\n# create data generator (without data augment)\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport keras.backend as K\n\n# rescale all image by 1\/255 \ndata_batch_size = 20\n\ndef get_f1(y_true, y_pred): #taken from old keras source code\n    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n    precision = true_positives \/ (predicted_positives + K.epsilon())\n    recall = true_positives \/ (possible_positives + K.epsilon())\n    f1_val = 2*(precision*recall)\/(precision+recall+K.epsilon())\n    return f1_val\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\ndef get_pred_score(y_true, y_pred):\n    mat = confusion_matrix(y_true, y_pred)\n    print(mat)\n\n    plt.figure(figsize=(8,6))\n    sns.heatmap(mat, square=False, annot=True, fmt ='d', cbar=True, annot_kws={\"size\": 16})\n    plt.title('0 : Normal   1 : Pneumonia', fontsize = 20)\n    plt.xticks(fontsize = 16)\n    plt.yticks(fontsize = 16)\n    plt.xlabel('predicted value', fontsize = 20)\n    plt.ylabel('true value', fontsize = 20)\n    plt.show()\n\n    tn, fp, fn, tp = mat.ravel()\n    print('\\ntn = {}, fp = {}, fn = {}, tp = {} '.format(tn, fp, fn, tp))\n\n    precision = tp\/(tp+fp)\n    recall = tp\/(tp+fn)\n    accuracy = (tp+tn)\/(tp+tn+fp+fn)\n    f1_score = 2. * precision * recall \/ (precision + recall)\n    f2_score = 5. * precision * recall \/ (4. * precision + recall)\n\n    print(\"Test Recall of the model \\t = {:.4f}\".format(recall))\n    print(\"Test Precision of the model \\t = {:.4f}\".format(precision))\n    print(\"Test Accuracy of the model \\t = {:.4f}\".format(accuracy))\n    print(\"Test F1 score of the model \\t = {:.4f}\".format(f1_score))\n    print(\"Test F2 score of the model \\t = {:.4f}\".format(f2_score))\nfrom keras import layers, models, Model\nfrom keras import optimizers\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n# Import train dataset...\n(x_test, y_test, test_fns) = create_dataset(test_0_list, test_1_list, return_fn=True)\n\"\"\"\n### Add dense layer on top of conv_base \n\n\u8207 [Pneumonia Detection by VGG16](https:\/\/www.kaggle.com\/whitelee\/pneumonia-detection-by-vgg16) \u7684\u5be6\u4f5c\u4e0d\u540c\uff0c\u5728\u6b64\u6211\u5011\u4f7f\u7528 `\u51fd\u6578\u5f0f\u7684\u5beb\u6cd5\u4f86\u5efa\u7acb Model` \uff0c\u800c\u975e\u5c07 base_model \u9472\u5728 Sequential \u4e2d\uff1b\u5982\u6b64\u4e00\u4f86\u5f8c\u7e8c\u5728 CAM \u5be6\u4f5c\u4e2d\u8f03\u5bb9\u6613\u627e\u5230 last_conv_layer \u3002\n\"\"\"\nx = base_model.output\n# x = layers.GlobalAveragePooling2D()(x)\nx = layers.Flatten()(x)\nx = layers.Dense(512, activation = 'relu')(x)\nx = layers.Dropout(0.5)(x)\nx = layers.Dense(1, activation='sigmoid')(x)\nmodel = Model(base_model.input,x)\n\"\"\"\n\u82e5\u8a2d\u5b9a trainable \u70ba False\uff0c \u5247 Fine-tune \u53c3\u6578\u70ba 0 \u500b\uff0c\u9019\u662f\u6bd4\u8f03\u5947\u602a\u7684\u5730\u65b9\uff0c\u56e0\u6b64\u6211\u5011\u4e0d\u66f4\u6539trainable\u8a2d\u5b9a\uff0c\u7dad\u6301 492 \u500b\u53c3\u6578\uff1b\u4f46 492 \u500b\u53c3\u6578\u4f7f\u5f97\u6bcf\u500b epoch \u7684\u8a13\u7df4\u6642\u9593\u9577\u9054 42 \u79d2 (\u76f8\u8f03 VGG16 \u6bcf\u500b epoch \u70ba19\u79d2)\uff1b\u82e5\u4f7f\u7528 TF 2.0 \u70ba backend \u5247\u5728\u8a2d\u5b9a trainable \u5f8c Fine-tune \u53c3\u6578\u8b8a\u6210 4 \u500b\uff0c\u8a13\u7df4\u6642\u9593\u7e2e\u6e1b\uff0c\u4f46\u9810\u6e2c\u80fd\u529b\u4e0b\u964d\u8a31\u591a\u3002\n\"\"\"\n# # Freezing a layer or set of layers means preventing their weights from being updated during training.\n# freezing_layer = None\n# model.trainable = False\nprint('This is the number of trainable weights: ', len(model.trainable_weights))\n# for layer in reversed(model.layers):\n#     # check to see if the layer has a 4D output\n#     if len(layer.output_shape) == 4:\n#         freezing_layer = layer.name\n#         break\n# print('Freezing layer = ', freezing_layer)\n# set_trainable = False\n# for layer in model.layers:\n#     if layer.name == freezing_layer:\n#         set_trainable = True\n#       # set trainable = True for layers after block5_conv1\n#     if set_trainable:\n#         layer.trainable = True\n#         print(layer.name)\n#     else:\n#         layer.trainable = False\n# print('This is the number of trainable weights after freezing the conv base:', len(model.trainable_weights))\nmodel.summary()\n# show trainable weights\n# [x.name for x in model.trainable_weights]\n# use ImageGenerator to generate more training data\ntrain_datagen = ImageDataGenerator(\n    rescale=1.\/255,  # Rescales all images by 1\/255\n    rotation_range = 10,\n    width_shift_range = 0.2, height_shift_range = 0.2,\n    fill_mode = 'nearest', shear_range = 0.2,\n    zoom_range = 0.2, horizontal_flip=False, \n)\ntrain_datagen.fit(x_train)\nval_datagen = ImageDataGenerator(rescale=1.\/255) #validation set no need to augment\nval_datagen.fit(x_val)\n\ntrain_generator = train_datagen.flow(x_train, y_train, batch_size=32) #increase batch size to 32\nval_generator = val_datagen.flow(x_val, y_val, batch_size=32) #increase batch size to 32\ndefault_lr = 1e-4 \nadp_optimizer = optimizers.RMSprop(lr=default_lr, rho=0.9, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer=adp_optimizer, loss=\"binary_crossentropy\", metrics=[\"accuracy\", get_f1])\n\"\"\"\n\u8a2d\u5b9a call back \u4fdd\u7559\u6700\u4f73 val_loss \u4e4b\u6b0a\u91cd\u503c\n\"\"\"\n# Define a checkpoint callback for method2:\ncheckpoint_name = 'Weights-m2-{epoch:03d}--{val_loss:.5f}.hdf5'\ncheckpoint2 = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 1, save_best_only = True, mode ='auto')\nes = EarlyStopping(monitor='val_loss', patience=5)\ncallbacks_list2 = [checkpoint2]\n\"\"\"\n\u8a13\u7df4\u671f\u9593\u53ef\u770b\u5230\u6700\u4f73\u7684 val_loss \u964d\u70ba 0\uff0c\u6216\u8a31\u662f\u6709overfit\u7684\u73fe\u8c61\u767c\u751f... \u4e0d\u904e\u767c\u751f\u5728 validation set \u4e0a\u662f\u6bd4\u8f03\u5c11\u898b\uff1b\u8b80\u8005\u6709\u8208\u8da3\u53ef\u4ee5\u8abf\u5927 validation set \u7684\u7e3d\u91cf\u8dd1\u8dd1\u770b\u3002\n\"\"\"\nhistory = model.fit_generator(train_generator, steps_per_epoch=100, epochs=30, validation_data=val_generator, validation_steps=20, callbacks=callbacks_list2)\nimport matplotlib.pyplot as plt\n\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nepochs = range(1, len(acc)+1)\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nf1 = history.history['get_f1']\nval_f1 = history.history['val_get_f1']\n\nplt.plot(epochs, acc, 'bo', label='Train Acc')\nplt.plot(epochs, val_acc, 'b', label='Validation Acc')\nplt.title('Accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, f1, 'bo', label='Train F1')\nplt.plot(epochs, val_f1, 'b', label='Validation F1')\nplt.title('F1 score')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Train Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Loss')\nplt.legend()\nplt.figure()\n\nplt.show()\n\"\"\"\n==== Prepare test data for prediction ===\n\"\"\"\ntest_data = []\ntest_labels = []\nfor (test_img, label) in zip(x_test, y_test):\n    test_data.append(test_img.astype(np.float32)\/255)\n    test_labels.append(label)\n\ntest_data = np.array(test_data)\ntest_labels = np.array(test_labels)\n\nprint(\"Total number of test examples: \", test_data.shape)\nprint(\"Total number of labels:\", test_labels.shape)\ndef predict(model, test_data):\n    pred_prob = model.predict(test_data, batch_size=data_batch_size)\n    pred_res = np.asarray([1 if x > 0.5 else 0 for x in [x[0] for x in pred_prob]]) \n    return (pred_res, [x[0] for x in pred_prob])\n# Load best weight of model\nfrom pathlib import Path\nw_fnl = [str(fn) for fn in Path('.\/').glob('Weights-m2-*.hdf5')]\nw_fnl.sort(reverse=True)\nwights_file = w_fnl[0] # choose the best checkpoint \nmodel.load_weights(wights_file) # load it\nmodel.compile(optimizer=adp_optimizer, loss=\"binary_crossentropy\", metrics=[\"accuracy\", get_f1])\n(y_pred, y_pred_prob) = predict(model, test_data)\nget_pred_score(test_labels, y_pred)\n\"\"\"\n### Extract false case for advanced analysis\n\n\u8a13\u7df4\u5b8c Model \u4ee5\u5f8c\uff0c\u53d6\u51fa TN, TP, FN, FP \u7684 case \u4f86\u5957\u7528 CAM \uff0c\u89c0\u5bdf\u5176 heatmap \u72c0\u6cc1\u3002\n\"\"\"\npred_result = pd.DataFrame({'imgPath': test_fns, 'label': test_labels, 'pred': y_pred, 'pred_prob': y_pred_prob})\npred_result['fn'] = pred_result.imgPath.apply(lambda ip: ip.split('\/')[-1])\npred_result.head()\nfalse_result = pred_result[pred_result.pred != pred_result.label]\ntrue_0_fns = pred_result[(pred_result.pred == pred_result.label) & (pred_result.label == 0)].fn.values\ntrue_1_fns = pred_result[(pred_result.pred == pred_result.label) & (pred_result.label == 1)].fn.values\nfalse_0_fns = false_result[false_result.label == 0].fn.values\nfalse_1_fns = false_result[false_result.label == 1].fn.values\nprint(true_0_fns.shape, true_1_fns.shape, false_0_fns.shape, false_1_fns.shape)\n\"\"\"\n### Apply CAM to one FN case\n\"\"\"\n# image_path = os.path.join(test_0_dir, false_0_fns[0])\nfn = false_0_fns[1]\nfolder = test_0_dir\nimage_path = os.path.join(folder, fn)\nprint(image_path)\n# img = image.load_img(image_path, target_size=(224, 224))\nimg = image_resize(image_path)\nimg = img.astype(np.float32)\/255\nimg_x = np.expand_dims(img, axis=0)\nimg_x.shape\n\"\"\"\n### Grad-CAM\n\n\u6b64 Grad-CAM \u7684\u5be6\u4f5c\u662f\u53c3\u8003 [\u9019\u7bc7\u6587\u7ae0](https:\/\/www.pyimagesearch.com\/2020\/03\/09\/grad-cam-visualize-class-activation-maps-with-keras-tensorflow-and-deep-learning\/) \u7684\uff1b\u4e3b\u8981\u5dee\u5225\u5728\u65bc\u8a72\u6587\u4ee5 TF 2.0 \u70ba backend\uff0c\u800c\u6211\u5011\u4f7f\u7528 TF 1.x\u3002\n\n\u770b\u500c\u5011\u82e5\u662f Google `Deeplearning CAM` \u6703\u770b\u5230\u6709\u8a31\u591a\u4e0d\u540c\u7684 CAM \u5be6\u4f5c\u65b9\u5f0f\uff0c\u4f46\u539f\u7406\u5927\u540c\u5c0f\u7570\uff0c`\u90fd\u662f\u8a08\u7b97\u67d0\u500b\u985e\u5225(\u901a\u5e38\u662f\u6a5f\u7387\u6700\u5927\u7684\u985e\u5225)\u7684\u6700\u7d42 output \u95dc\u65bc model \u4e2d\u6700\u5f8c\u4e00\u500b conv2d \u5c64\u4e4b\u68af\u5ea6\u503c\u4f5c\u70ba\u5716\u50cf\u5404\u90e8\u4f4d\u7684\u6b0a\u91cd` \u4f86\u7e6a\u5236heatmap\uff1b\u5dee\u5225\u5728\u65bc\u5982\u4f55\u5c0dheatmap\u4f5cnormalize\u4f7f\u5176\u66f4\u80fd\u7a81\u986f\u51fa\u91cd\u8981\u7684\u6c7a\u7b56\u90e8\u4f4d\u3002\n\"\"\"\nfrom keras.models import Model\nimport tensorflow as tf\nimport keras.backend as K\n\nclass GradCAM:\n    def __init__(self, model, classIdx=0, layerName=None):\n        # store the model, the class index used to measure the class\n        # activation map, and the layer to be used when visualizing\n        # the class activation map\n        self.model = model\n        self.classIdx = classIdx\n        self.layerName = layerName\n        self.sess = tf.compat.v1.Session()\n        # if the layer name is None, attempt to automatically find\n        # the target output layer\n        if self.layerName is None:\n            self.layerName = self.find_target_layer()\n\n    def find_target_layer(self):\n        # \u5c0b\u627e\u6700\u5f8c\u4e00\u5c64Conv layer\n        # attempt to find the final convolutional layer in the network\n        # by looping over the layers of the network in reverse order\n        for layer in reversed(self.model.layers):\n            # check to see if the layer has a 4D output\n            if len(layer.output_shape) == 4:\n                # model\u4e2d\u51fa\u73fe\u7684\u6700\u5f8c\u4e00\u500b\u8f38\u51fa\u7dad\u5ea6\u70ba4\u7684\u5c64\u5373\u5c0b\u627e\u76ee\u6a19\n                return layer.name\n        # otherwise, we could not find a 4D layer so the GradCAM\n        # algorithm cannot be applied\n        raise ValueError(\"Could not find 4D layer. Cannot apply GradCAM.\")\n\n    def compute_heatmap(self, image, eps=1e-8):\n        # construct our gradient model by supplying (1) the inputs\n        # to our pre-trained model, (2) the output of the (presumably)\n        # final 4D layer in the network, and (3) the output of the\n        # softmax activations from the model\n#         gradModel = Model(\n#             inputs=[self.model.inputs],\n#             outputs=[self.model.get_layer(self.layerName).output,\n#                 self.model.output])\n            # record operations for automatic differentiation\n        \n        pred = self.model.predict(image)\n        predictions = self.model.output\n        # model \u5c0d\u8f38\u5165\u4f5c\u5b8c\u9810\u6e2c\u5f8c\u53d6\u51fa\u8981\u7e6a\u5236heatmap\u7684\u985e\u5225\uff0c\u56e0\u6211\u5011\u7684model\u70ba\u4e8c\u5143\u5206\u985e\uff0c\u6545classIdx\u56fa\u5b9a\u70ba0\n        loss = predictions[:, self.classIdx]\n        convOutputs = self.model.get_layer(self.layerName).output\n\n        # \u7528 gradients \u51fd\u5f0f\u8a08\u7b97\u68af\u5ea6\u503c\u4f5c\u70ba\u5f8c\u9762\u756bheatmap\u7684\u6b0a\u91cd\n        # use automatic differentiation to compute the gradients\n        grads = K.gradients(loss, convOutputs)[0]\n\n        pooled_grads = K.mean(grads, axis=(0, 1, 2))\n        iterate = K.function([self.model.input],[pooled_grads, convOutputs[0]])\n        (pooled_grads_value, conv_layer_output_value) = iterate([image])\n        for i in range(512):\n            # \u5c0dconv layer\u7684\u8f38\u51fa\u4e58\u4e0a\u6b0a\u91cd\u4ee5\u4f5c\u70ba\u7e6a\u5236heatmap\u7684raw data\n            conv_layer_output_value[:, :, i] *= pooled_grads_value[i]\n        \n        heatmap = np.mean(conv_layer_output_value, axis=-1)\n        # grab the spatial dimensions of the input image and resize\n        # the output class activation map to match the input image\n        # dimensions\n        (w, h) = (image.shape[2], image.shape[1])\n        # heatmap = cv2.resize(cam.numpy(), (w, h))\n        heatmap = cv2.resize(heatmap, (w, h))\n        # \u6b63\u898f\u5316 heatmap\u7684raw data\u4f7f\u503c\u843d\u57280~255\u4e4b\u9593(image data\u7684\u5408\u7406\u7bc4\u570d)\n        # normalize the heatmap such that all values lie in the range\n        # [0, 1], scale the resulting values to the range [0, 255],\n        # and then convert to an unsigned 8-bit integer\n        numer = heatmap - np.min(heatmap)\n        denom = (heatmap.max() - heatmap.min()) + eps\n        heatmap = numer \/ denom\n        heatmap = (heatmap * 255).astype(\"uint8\")\n        # return the resulting heatmap to the calling function\n        return (heatmap, pred)\n\n    def overlay_heatmap(self, heatmap, image, alpha=0.5,\n        colormap=cv2.COLORMAP_VIRIDIS):\n        # apply the supplied color map to the heatmap and then\n        # overlay the heatmap on the input image\n        heatmap = cv2.applyColorMap(heatmap, colormap)\n        output = cv2.addWeighted(image, alpha, heatmap, 1 - alpha, 0)\n        # return a 2-tuple of the color mapped heatmap and the output,\n        # overlaid image\n        return (heatmap, output)\n\"\"\"\n\u63a5\u4e0b\u4f86\u5148\u5617\u8a66\u5c0d\u55ae\u5f35\u8f38\u5165\u7e6a\u5236heatmap\uff0c\u89c0\u5bdf\u7e6a\u5236\u53ca\u8207\u539f\u5716\u4e4b\u758a\u5408\u6548\u679c\n\"\"\"\ncam = GradCAM(model)\n(heatmap, _) = cam.compute_heatmap(img_x)\nimg = image_resize(image_path)\nprint(heatmap.shape, type(heatmap))\nprint(img[:, :, 0].shape, type(img[:, :, 0]))\n\"\"\"\n\u5c07 heatmap \u8207\u539f\u59cb\u5716\u578b\u758a\u5408\uff0calpha \u503c\u4f7f\u75280.2 (\u8d8a\u9ad8\u7684 alpha \u503c\u6703\u8b93\u539f\u5716\u8d8a\u6e05\u6670\uff0cheatmap\u8d8a\u6a21\u7cca)\n\"\"\"\n(heatmap, output) = cam.overlay_heatmap(np.dstack([heatmap, heatmap, heatmap]), img, alpha=0.2)\nplt.imshow(heatmap) # show heatmap\n\"\"\"\n\u6211\u5011\u4f7f\u7528 VIRIDIS \u8272\u968e\u4f86\u7e6a\u5236 Heatmap\uff0c\u8d8a\u4eae\u8655(\u91d1\u9ec3\u8272)\u8868\u793a\u6b0a\u91cd\u503c\u8d8a\u9ad8\n\n![CV2\u4e2d\u7684\u5e38\u7528\u8272\u968e](https:\/\/www.pyimagesearch.com\/wp-content\/uploads\/2020\/03\/keras_gradcam_colormap.png)\n\u5716\u7247\u51fa\u8655\uff1ahttps:\/\/www.pyimagesearch.com\/wp-content\/uploads\/2020\/03\/keras_gradcam_colormap.png\n\"\"\"\nplt.imshow(output) # \u758a\u5408\u5716\n\"\"\"\n\u7531\u758a\u5408\u5716\u53ef\u4ee5\u770b\u51fa\u91d1\u9ec3\u8272\u4e26\u672a\u5f88\u597d\u7684\u6db5\u84cb\u80ba\u90e8\u5340\u57df\uff0c\u5f88\u6709\u53ef\u80fd\u56e0\u6c92\u6709\u6db5\u84cb\u5230\u75c5\u7076\u800c\u8aa4\u5224\n\"\"\"\n\"\"\"\n### List heatmaps of TP \/ TN \/ FP \/ FN cases \n\n\u5404 case \u53d6\u51fa 15 \u5f35\u539f\u59cb\u5716\u4f86\u7e6a\u5236 heatmap\uff0c\u89c0\u5bdf\u5224\u65b7\u932f\u8aa4\u4e4b case \u662f\u5426\u662f\u56e0 model \u7528\u4e86\u932f\u8aa4\u7684\u90e8\u4efd\u4f5c\u6c7a\u7b56\u3002\n\"\"\"\n# Create global CAM class\ncam = GradCAM(model)\ndef get_heatmap_with_pic(base_dir, fn, cam_model=cam):\n#     print(fn)\n    image_path = os.path.join(base_dir, fn)\n    title1 = fn\n    img = image_resize(image_path)\n    img_nz = img.astype(np.float32)\/255\n    img_x = np.expand_dims(img_nz, axis=0)\n    (heatmap, pred_prob) = cam_model.compute_heatmap(img_x)\n    (heatmap, output) = cam_model.overlay_heatmap(np.dstack([heatmap, heatmap, heatmap]), img, alpha=0.2)\n    title2 = 'pred_prob: {}'.format(pred_prob)\n    title3 = 'combined'\n    return (img, title1, heatmap, title2, output, title3)\n# \u4f7f\u7528 subplots \u5c07\u539f\u59cb\u5716\u3001heatmap\u53ca\u758a\u5408\u5716\u4e26\u6392\u5448\u73fe\ndef draw_heatmap_on_plt(base_dir, fn_list, cat='tp', cam_model=cam):\n    # Draw heatmap for true cases\n    pics_per_row = 2\n    cols = 3 * pics_per_row\n    rows = int(len(fn_list) \/ pics_per_row)\n    fig, ax = plt.subplots(rows, cols, figsize=(cols*5,rows*5))\n    for i, axi in enumerate(ax.flat):\n        title = ''\n        show_img = None\n        idx = i % 3\n        if idx == 0:\n            (img, title1, heatmap, title2, superimposed_img, title3) = get_heatmap_with_pic(base_dir, fn_list[int(i \/ 3)])\n            show_img = img\n            title = '{} ({})'.format(title1, cat)\n        elif idx == 1:\n            show_img = heatmap\n            title = title2\n        else:\n            show_img = superimposed_img\n            title = title3\n        axi.imshow(show_img, cmap='bone')\n        axi.set_title(title)\n        axi.set(xticks=[], yticks=[])\nimport datetime\ndisp_num = 15 #\u6bcf\u500b\u985e\u5225\u53d615\u5f35\u539f\u5716\npic_sec = 20 # \u756b\u4e00\u5f35 heatmap \u7d04\u898120\u79d2(\u4ee5kaggle\u7684notebook\u898f\u683c)\ndisp_cnt = min(disp_num, len(true_0_fns))\nprint('Will take around {} secs from {}'.format(disp_cnt*pic_sec, str(datetime.datetime.now())))\ndraw_heatmap_on_plt(test_0_dir, true_0_fns[:disp_cnt], 'tn')\ndisp_cnt = min(disp_num, len(true_1_fns))\nprint('Will take around {} secs from {}'.format(disp_cnt*pic_sec, str(datetime.datetime.now())))\ndraw_heatmap_on_plt(test_1_dir, true_1_fns[:disp_cnt], 'tp')\n\"\"\"\n1. \u7531TN\u53caTP\u7684\u5716\u5f62\u53ef\u4ee5\u89c0\u5bdf\u5230\u7406\u60f3\u7684 heatmap \u4eae\u8655\u61c9\u7531\u5716\u7247\u4e2d\u9593\u5448\u5713\u5f62\u5c55\u958b\uff0c\u6216\u662f\u5728\u4e2d\u9593\u5f62\u6210\u67f1\u72c0\uff0c\u5f62\u6210\u4e2d\u9593\u4eae\u5169\u908a\u6697\u5716\u5f62\u3002\n1. \u4e8b\u5be6\u4e0a\u6a21\u578b\u5c0d\u90e8\u4efd TP case \u7684\u6c7a\u7b56\u5340\u57df\u4e5f\u4e0d\u662f\u5f88\u7406\u60f3(\u96d6\u4eae\u8655\u7531\u4e2d\u9593\u5c55\u958b\u4f46\u4ea6\u6709\u6db5\u84cb\u4e0d\u8db3\u60c5\u6cc1)\uff0c\u4f46\u56e0Test set \u4e2d positive\u6bd4\u4f8b\u4e5f\u8f03\u9ad8\uff0c\u4e5f\u4e0d\u6392\u9664\u6709\u6b6a\u6253\u6b63\u8457\u7684\u73fe\u8c61\u3002\n\"\"\"\ndisp_cnt = min(disp_num, len(false_0_fns))\nprint('Will take around {} secs from {}'.format(disp_cnt*pic_sec, str(datetime.datetime.now())))\ndraw_heatmap_on_plt(test_0_dir, false_0_fns[:disp_cnt], 'fn')\ndisp_cnt = min(disp_num, len(false_1_fns))\nprint('Will take around {} secs from {}'.format(disp_cnt*pic_sec, str(datetime.datetime.now())))\ndraw_heatmap_on_plt(test_1_dir, false_1_fns[:disp_cnt], 'fp')\n\"\"\"\n1. \u7531 FN \u53ca FP \u5716\u5f62\u7684 heatmap \u53ef\u4ee5\u770b\u51fa\u591a\u534a\u662f\u4eae\u8655\u504f\u5728\u89d2\u843d\u6216\u662f\u660e\u986f\u907a\u6f0f\u80ba\u90e8\u67d0\u5340\u57df\uff0c\u7576\u4f7f\u7528\u8005\u770b\u5230\u9019\u6a23\u7684heatmap\u6216\u8a31\u61c9\u8a72\u8003\u616e\u662f\u5426\u63a5\u53d7\u6a21\u578b\u5224\u65b7\u7d50\u679c\n1. \u6709\u4e9b heatmap \u6db5\u84cb\u826f\u597d\u4f46\u4ecd\u7136\u8aa4\u5224\u7684 case \u6216\u8a31\u61c9\u518d\u6aa2\u8996\u539f\u5716\u6a94\u770b\u662f\u5426\u6709\u9700\u8981\u8abf\u6574label(\u5224\u5b9a\u7d50\u679c)\n\"\"\"\n\"\"\"\n### \u7d50\u8a9e\n\n\u7531\u4ee5\u4e0a CASE \u7684 heatmap \u89c0\u5bdf\uff0c\u5927\u591a\u6578\u7684CASE\u7684\u4eae\u5340\u90fd\u9084\u5408\u7406(\u81ea\u8a8d\u70ba)\uff0c\u7576\u7136\u6db5\u84cb\u5ea6\u662f\u5426\u8db3\u5920\u53ef\u80fd\u8981\u52a0\u5165Domain\u5c08\u5bb6\u7684\u5224\u65b7\u624d\u6bd4\u8f03\u6e96\u78ba\u3002\u4f46\u6211\u5011\u76f8\u4fe1\u5728\u6574\u500b\u8cc7\u6599\u5206\u6790\u904e\u7a0b\u7684\u5404\u500b\u90e8\u4efd\u90fd\u53ef\u7531 CAM \u7372\u5f97\u5e6b\u52a9\uff1bHeatmap \u63d0\u4f9b\u4e86\u53ef\u8996\u5316\u7684\u6c7a\u7b56\u8cc7\u8a0a\u8b93\u958b\u767c\u4eba\u54e1\u53ef\u4ee5\u5c0d\u6a21\u578b\u7684\u6548\u80fd\u6709\u53e6\u4e00\u7a2e\u9762\u5411\u7684\u89c0\u5bdf(\u4f8b\u5982\u6a21\u578b\u662f\u771f\u7684\u5224\u65b7\u51fa\u4f86\u7684\u9084\u662f\u731c\u5c0d\u7684)\uff0c\u4f7f\u7528\u8005\u4e5f\u53ef\u7531\u4eae\u5340\u77e5\u9053\u6a21\u578b\u5224\u65b7\u4f9d\u64da\u662f\u5426\u5408\u7406\uff0c\u751a\u81f3\u53ef\u4ee5\u4f5c\u70ba\u56de\u982d\u6aa2\u8996\u8cc7\u6599(input)\u54c1\u8cea\u7684\u53c3\u8003\u3002\n\n\u4ee5\u4e0a\u662f\u5c0f\u5f1f\u9019\u9663\u5b50\u7684\u5b78\u7fd2\u5206\u4eab\uff0c\u5404\u4f4d\u770b\u500c\u82e5\u6709\u4efb\u4f55\u60f3\u6cd5\u6216\u5efa\u8b70\u4e5f\u6b61\u8fce\u63d0\u51fa\u8a0e\u8ad6\uff5e\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '46ea97de01a644'}"}
{"id":"83932","text":"######### IMPORT ########\nimport pickle\nfrom itertools import cycle\nfrom time import time\nfrom tqdm.auto import tqdm\nimport shutil\nfrom pathlib import Path\n\n# Pandas, Numpy\nimport pandas as pd\nimport numpy as np\nfrom numpy import interp\nfrom matplotlib import pyplot as plt\npd.set_option(\"display.max_columns\", None)\n\n# Model evaluation\nfrom sklearn.metrics import plot_confusion_matrix, roc_auc_score,  auc, \\\n    precision_recall_fscore_support, classification_report, roc_curve, plot_roc_curve\n\n# Sklearn pipeline\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn import set_config\nfrom sklearn.pipeline import Pipeline\nset_config(display = 'diagram')\n\n\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import train_test_split\n\nfrom catboost import CatBoostClassifier, CatBoostRegressor\n\nfrom sklearn.svm import SVR\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\ndata_train = pd.read_csv('..\/input\/commonlitreadabilityprize\/train.csv')\ndata_test = pd.read_csv('..\/input\/commonlitreadabilityprize\/test.csv')\ndata_sample_submission = pd.read_csv('..\/input\/commonlitreadabilityprize\/sample_submission.csv')\ndata_sample_submission\ndata_train\ndata_test\ndata_train.describe(percentiles=[0.01, 0.05, 0.25, 0.75, 0.95, 0.99])\ndata_train['target'].hist(bins=30)\ndata_train['standard_error'].hist(bins=30)\n(data_train['target'] - data_train['standard_error']).hist(bins=30)\n(data_train['target'] + data_train['standard_error']).hist(bins=30)\ndata_test\n\"\"\"\n## Explore\n\"\"\"\ndata_train['license'].value_counts()\ndata_train['excerpt'][0]\n\"\"\"\n## Build pipeline process\n\"\"\"\n######## SUPPORTING CLASSES ########\nclass PipelineLogger(object):\n    def __init__(self):\n        pass\n        \n    def log_start(self):\n        self.start_time = time()\n        print(f'======== {self.__class__.__name__} - START ========')\n        return None\n        \n    def log_finish(self):\n        self.duration = time() - self.start_time\n        print(f'======== {self.__class__.__name__} - FINISH =======> Take: {self.duration:.6f}(s)')\n\nclass featureUnion(FeatureUnion):\n    def _hstack(self, Xs):\n        cols = [X.columns.tolist() for X in Xs]\n        dtypes = []\n        for X in Xs:\n            dtypes.append([str(X[col].dtype) for col in X])\n        cols = np.hstack(cols)\n        dtypes = np.hstack(dtypes)\n        data = pd.DataFrame(super()._hstack(Xs), columns = cols)\n        print('====Converting columns types====')\n        for col, dtype in tqdm(zip(cols, dtypes)):\n            data[col] = data[col].astype(dtype)\n        return data\n\nclass columnTransformer(ColumnTransformer):\n    def _hstack(self, Xs):\n        cols = [X.columns.tolist() for X in Xs]\n        dtypes = []\n        for X in Xs:\n            dtypes.append([str(X[col].dtype) for col in X])\n        cols = np.hstack(cols)\n        dtypes = np.hstack(dtypes)\n        data = pd.DataFrame(super()._hstack(Xs), columns = cols)\n        print('====Converting columns types====')\n        for col, dtype in tqdm(zip(cols, dtypes)):\n            data[col] = data[col].astype(dtype)\n        return data\n\nclass ExperimentBase(BaseEstimator):\n    def evaluate(self, X_test, y_test):\n        print('Evaluating model')\n        print(classification_report(y_true=y_test, y_pred=self.predict(X_test)))\n        metrics = self.auc_report(X_test, y_test)\n        metrics['precision'], metrics['recall'], metrics['f1_score'], metrics['support'] = precision_recall_fscore_support(y_test, self.predict(X_test))\n        return metrics\n    \n    def auc_report(self, X, y_true):\n        classes = self.classes_\n        y_pred_classes = self.predict_proba(X)\n        n_classes = len(classes)\n\n        lw = 2\n        for i in range(len(classes)):\n            print(f\"\"\"{classes[i]}: {roc_auc_score(y_true=(y_true==classes[i]).astype(int), y_score=y_pred_classes[:,i])}\"\"\")\n\n        # Compute ROC curve and ROC area for each class\n        fpr = dict()\n        tpr = dict()\n        roc_auc = dict()\n\n        for i in range(n_classes):\n            fpr[i], tpr[i], _ = roc_curve(y_true=(y_true==classes[i]).astype(int), y_score=y_pred_classes[:,i])\n            roc_auc[i] = auc(fpr[i], tpr[i])\n\n        all_fpr = np.unique(np.concatenate([fpr[i] for i in range(len(classes))]))\n\n        # Then interpolate all ROC curves at this points\n        mean_tpr = np.zeros_like(all_fpr)\n        for i in range(len(classes)):\n            mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n        # Finally average it and compute AUC\n        mean_tpr \/= n_classes\n\n        fpr[\"macro\"] = all_fpr\n        tpr[\"macro\"] = mean_tpr\n        roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n        # Plot all ROC curves\n        plt.figure()\n\n        plt.plot(fpr[\"macro\"], tpr[\"macro\"],\n                 label='macro-average ROC curve (area = {0:0.2f})'\n                       ''.format(roc_auc[\"macro\"]),\n                 color='navy', linestyle=':', linewidth=4)\n\n        colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\n        for i, color in zip(range(n_classes), colors):\n            plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n                     label='ROC curve of class {0} (area = {1:0.2f})'\n                     ''.format(classes[i], roc_auc[i]))\n\n        plt.plot([0, 1], [0, 1], 'k--', lw=lw)\n        plt.xlim([0.0, 1.0])\n        plt.ylim([0.0, 1.05])\n        plt.xlabel('False Positive Rate')\n        plt.ylabel('True Positive Rate')\n        plt.title('Some extension of Receiver operating characteristic to multi-class')\n        plt.legend(loc=\"lower right\")\n        plt.show()\n        metrics = {\n            'macro_auc': roc_auc[\"macro\"]\n        }\n        for i in range(n_classes):\n            metrics[f'auc_{classes[i]}'] = roc_auc[i]\n        return metrics\n    \nclass simpleImputer(SimpleImputer):\n    def fit(self, X, y=None):\n        self._cols = X.columns.tolist()\n        self._dtypes = [str(X[col].dtype) for col in X.columns]\n        super().fit(X, y)\n        return self\n        \n    def transform(self, X):\n        X_ = super().transform(X)\n        data = pd.DataFrame(X_, columns = self._cols)\n        for col, dtype in tqdm(zip(self._cols, self._dtypes)):\n            data[col] = data[col].astype(dtype)\n        return data\n######## DONE SUPPORTING CLASSES ########\n('max_imputor', simpleImputer(strategy='constant', fill_value='unk'))\nclass TextLowerer(BaseEstimator, TransformerMixin, PipelineLogger):\n    def __init__(self, columns):\n        super().__init__()\n        self.columns = columns\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def transform(self, X):\n        X_ = X[self.columns].copy()\n        for c in X_.columns:\n            X_[c] = X_[c].apply(lambda x: x.lower())\n        return X_\n\nclass TextSpliter(BaseEstimator, TransformerMixin, PipelineLogger):\n    def __init__(self, columns, spliters):\n        super().__init__()\n        self.spliters = spliters\n        self.columns = columns\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def transform(self, X):\n        X_ = X[self.columns].copy()\n        for col in self.columns:\n            X_[col] = X_[col].str.replace(pat='(:|\/|_|-)',repl=' ', regex=True)\n        return X_\n    \nclass PassThroughExcept(BaseEstimator, TransformerMixin, PipelineLogger):\n    def __init__(self, col_except_func):\n        super().__init__()\n        self.col_except_func = col_except_func\n        \n    def fit(self, X, y=None):\n        self.except_cols = self.col_except_func(X)\n        return self\n    \n    def transform(self, X):\n        self.log_start()\n        X_ = X[[c for c in X.columns if c not in self.except_cols]]\n        self.log_finish()\n        return X_\ndata_train\ndata_train['url_legal'].str.replace(pat='(:|\/|_|-)',repl=' ', regex=True)\npd.Series(dtype='object')\nclass TextCombinator(BaseEstimator, TransformerMixin, PipelineLogger):\n    def fit(self, X, y=None):\n        self.cols = X.columns.to_list()\n        return self\n    \n    def transform(self, X):\n        X_ = X.copy()\n        X_['comb_text'] = ''\n        for c in self.cols:\n            X_['comb_text'] += ' ' + X[c]\n        return X_['comb_text']\nSVR()\npl_preprocess = Pipeline(steps=[\n    ('unk_imputing', simpleImputer(strategy='constant', fill_value='unk')),\n    ('text_lowering', TextLowerer(columns=['url_legal', 'license', 'excerpt'])),\n    ('feature_processing', featureUnion(transformer_list=[\n        ('text_spliting', TextSpliter(columns=['url_legal', 'license'], spliters=[':', '\/', '_', '-'])),\n        ('pass_through', PassThroughExcept(col_except_func=lambda X: [c for c in X.columns if c in ['url_legal', 'license']]))\n    ])),\n    ('combine_text', TextCombinator()),\n    ('vect', CountVectorizer(ngram_range=(1,1), max_df=0.9, max_features=None)), \n    ('tfidf', TfidfTransformer()),\n    ('clf', SVR(kernel= \"rbf\",gamma='scale',C=2))\n    \n])\npl_preprocess\npl_preprocess.fit(data_train.drop(columns=['target', 'standard_error']), data_train.target)\ndata_train\ndata_test\ndata_test_copy = data_test.copy()\ndata_test_copy['target'] = pl_preprocess.predict(data_test)\ndata_test_copy\ndata_test_copy[['id', 'target']].to_csv('submission.csv',index=False)\ndata_train_copy = data_train.copy()\ndata_train_copy['pred'] = pl_preprocess.predict(data_train.drop(columns=['target', 'standard_error']))\n\ndata_train_copy\nfrom sklearn.metrics import mean_squared_error\nmean_squared_error(data_train_copy['target'], data_train_copy['pred'], squared=False)\n\"\"\"\nTrain's rmse ~ 0.269 is much much lower than submission score (~ 0.750)\n\n=> Could be overfitting\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9a03ce5e8c7c2b'}"}
{"id":"2482","text":"\"\"\"\n# Predicting The Sales of Video Games [WIP]\n![Arcade](https:\/\/images.unsplash.com\/photo-1513528473392-f3fffb1b31a9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44845c69fe4febae451d4133ccb7518b&auto=format&fit=crop&w=750&q=80)\n\n\"\"\"\n\"\"\"\nThe purpose of this experiment is to practice Univariate and Multivariate EDA. \n\"\"\"\n#Libraries\/Dependices\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\n\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nfrom fastai.structured import *\nfrom fastai.column_data import *\nnp.set_printoptions(threshold=50, edgeitems=20)\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n\nPATH = \"..\/input\/Video_Games_Sales_as_at_22_Dec_2016.csv\"\ndf_Games = pd.read_csv(\"..\/input\/Video_Games_Sales_as_at_22_Dec_2016.csv\", index_col=0)\ndf_Games.head(30)\ndf_Games.info()\ndf_Games.describe()\n\"\"\"\n## EDA Time!\n\"\"\"\n\"\"\"\nGlobal Sales\n\"\"\"\nsns.distplot(df_Games['Global_Sales'], kde=False)\n\"\"\"\nYear of Release\n\"\"\"\nsns.distplot(df_Games['Year_of_Release'].dropna())\n\"\"\"\nCritic Score\n\"\"\"\nsns.distplot(df_Games['Critic_Score'].dropna())\n\"\"\"\nPlatforms\n\"\"\"\nplt.figure(figsize=(12,8))\nsns.countplot(df_Games['Platform'].sort_index())\n\"\"\"\nGenres\n\"\"\"\nplt.figure(figsize=(14,8))\nsns.countplot(df_Games['Genre'].sort_index())\n\"\"\"\nPublishers\n\"\"\"\n\"\"\"\nDevelopers\n\"\"\"\nplt.figure(figsize=(12,8))\nsns.countplot(df_Games['Developer'].dropna(), order = df_Games['Developer'].value_counts().iloc[:40].index)\nplt.xticks(rotation=90);\n\"\"\"\nLets try and get an understanding of what variables have good correlations each other.\n\"\"\"\n\"\"\"\nLets try and find the genre with the most sales [A BIT LATER AS ITS Multivariate analysis]\n\"\"\"\nsales_genres = df_Games[['Genre', 'Global_Sales']]\nsales_genres.head()","meta":"{'source': 'AI4Code', 'id': '04b6b119011db1'}"}
{"id":"106121","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n**Loading datasets**\n\"\"\"\ndata_train = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ndata_test = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n\nprint(data_train.shape)\ndata_train.head()\nprint(data_test.shape)\ndata_test.head()\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\ndef fateOf(feature):\n    survived = data_train[data_train['Survived']==1][feature].value_counts()\n    dead = data_train[data_train['Survived']==0][feature].value_counts()\n    df = pd.DataFrame ([survived, dead])\n    df.index = ['Survived','Dead']\n    df.plot(kind = 'bar', stacked= True, figsize=(10,5))\n    \n\"\"\"\nsex_mapping = {\"male\": 0, \"female\": 1}\n\nfor data_train['Sex'] in data_train:\n    if data_train['Sex'] == 'male':\n        data_train['Sex'] = 0\n    else:\n        data_train['Sex'] == '1'\n\"\"\"\ndata_train[\"Age\"].fillna(data_train.Age.mean(), inplace = True)\ndata_test[\"Age\"].fillna(data_train.Age.mean(), inplace = True)\ndata_test[\"Fare\"].fillna(data_train.Fare.mean(), inplace = True)\na = data_train.pop('Survived')\na.head()\nx = list(data_train.dtypes[data_train.dtypes != object].index)\ny = list(data_test.dtypes[data_test.dtypes != object].index)\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nmodel = KNeighborsClassifier(n_neighbors = 5)\nmodel.fit(data_train[x],a)\nprint (accuracy_score(a, model.predict(data_train[x])))\ntarget = data_test[y]\nprediction = model.predict(target)\nsubmission = pd.DataFrame({\n        \"PassengerId\": data_test[\"PassengerId\"],\n        \"Survived\": prediction\n    })\n\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'c2f37e763d88cd'}"}
{"id":"42723","text":"import pandas as pd\n\n# testing Kaggle output folder (since sometimes it bugged and need to be restarted)\n\nx = pd.DataFrame({'x','y'})\nx.to_csv('tes.csv')\n!pip install --upgrade efficientnet tensorflow_addons tensorflow\n!pip install -q efficientnet\nimport efficientnet.tfkeras as efn\nimport re\nimport os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split    \n\nprint(tf.__version__)\nos.listdir('\/kaggle\/input\/shopee-product-detection-student\/')\ntrain_path = \"\/kaggle\/input\/shopee-product-detection-student\/train\/train\/train\/\"\ntest_path= \"\/kaggle\/input\/shopee-product-detection-student\/test\/test\/test\/\"\nbroken_fnames = []\nfor label in os.listdir(train_path):\n    label_path = train_path + label + '\/'\n    for filename in os.listdir(label_path):\n        if len(filename) > 36:\n            print(label_path + filename)\n            broken_fnames.append(label_path + filename)\n            #finding broken file name\nprint()\nfor filename in os.listdir(test_path):\n    if len(filename) > 36:\n        print(test_path + filename)\n        broken_fnames.append(test_path + filename)\n        \nf = open('broken-file-names.txt', 'w')\n#creates broken file texts.\nf.write('\\n'.join(broken_fnames))\nf.close()\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nIMAGE_SIZE = (400, 400)\nBATCH_SIZE = 128\nSEED = 48\n\ndef get_set():\n    train_path = \"\/kaggle\/input\/shopee-product-detection-student\/train\/train\/train\/\"\n    test_path= \"\/kaggle\/input\/shopee-product-detection-student\/test\/test\/\"\n\n    train_gen = ImageDataGenerator(rescale=1.\/255., \n                                    validation_split=0.25,\n                                    width_shift_range=0.2,\n                                    height_shift_range=0.2,\n                                    shear_range=0.2,\n                                    zoom_range=0.1)\n    train_set = train_gen.flow_from_directory(train_path, target_size=IMAGE_SIZE, \\\n                                              batch_size=BATCH_SIZE, seed=SEED, \\\n                                              subset='training')\n    val_set = train_gen.flow_from_directory(train_path, target_size=IMAGE_SIZE, \\\n                                            batch_size=BATCH_SIZE, seed=SEED, \\\n                                            subset='validation')\n\n    test_gen = ImageDataGenerator(rescale=1.\/255)\n    test_set = train_gen.flow_from_directory(test_path, target_size=IMAGE_SIZE, \\\n                                             batch_size=BATCH_SIZE, seed=SEED, \\\n                                             shuffle=False, class_mode=None)\n    \n    return train_set, val_set, test_set\n\ntrain_set, val_set, test_set = get_set()\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\n\nbase = InceptionV3(input_shape = (400, 400, 3), \n                    include_top = False, \n                    weights ='imagenet')\nbase.trainable = False\nmodel = tf.keras.Sequential([\n        base,\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(1024, activation='relu'),\n        tf.keras.layers.Dropout(0.2),\n        tf.keras.layers.Dense(42, activation='softmax')\n    ])\nmodel.compile(\n    optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4, beta_1=0.9, beta_2=0.999, amsgrad=False),\n    loss = 'categorical_crossentropy',\n    metrics=['acc']\n    )\nmodel.summary()\n# Alternate model (using InceptionV3 until layer mixed10)\nlast_layer = pre_trained_model.get_layer('mixed10')\nprint('last layer output shape: ', last_layer.output_shape)\nlast_output = last_layer.output\n\n# Adding dense layer\nx = layers.Flatten()(last_output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\nx = layers.Dense(1024, activation='relu')(x)\n# Add a dropout rate of 0.2\nx = layers.Dropout(0.2)(x)                  \n# Add a final sigmoid layer for classification\nx = layers.Dense  (42, activation='softmax')(x)           \n\nmodel1 = Model( pre_trained_model.input, x) \n\nmodel1.compile(optimizer ='adam', \n              loss = 'categorical_crossentropy', \n              metrics = ['acc'])\nmodel1.summary()\n\"\"\"\n# I only use epoch = 1 only for demonstration, the epoch I used for my late submission are 3\n\"\"\"\nEPOCHS = 1\n\nhist = model.fit(train_set, epochs=EPOCHS, \n                 validation_data=val_set, shuffle=True)\n\n# Running model only for demonstration since the model are pretty large\n# And it could crash the kaggle output if saved \n\n#model.save('model-InceptionV3-SHOPEE-1.hdf5')\ndef generate_prediction(model, save_name):\n    subm = pd.read_csv('\/kaggle\/input\/shopee-product-detection-student\/test.csv')\n    subm = subm.sort_values(by='filename')\n    \n    fnames = sorted(os.listdir('\/kaggle\/input\/shopee-product-detection-student\/test\/test\/test\/'))\n    unbroken_index = np.where(np.vectorize(len)(np.array(fnames)) == 36)[0]\n    \n    y_pred = model.predict(test_set)\n    pred = y_pred.argmax(axis=1)\n    pred = pred[unbroken_index]\n    subm['category'] = pred\n    \n    #adding zero padding (from 1 to 01)\n    subm['category'] = subm['category'].apply(lambda x: '{0:0>2}'.format(x)) \n    \n    #saving the prediction into csv file\n    subm.to_csv(save_name, index=False)\n    return subm\nsubm = generate_prediction(model, 'kaggle_submission.csv')\nsubm\n\"\"\"\n# Xception model\n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications import xception\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nIMAGE_SIZE = (299, 299)\nBATCH_SIZE = 128\nSEED = 48\n\ndef get_set():\n    train_path = \"\/kaggle\/input\/shopee-product-detection-student\/train\/train\/train\/\"\n    test_path= \"\/kaggle\/input\/shopee-product-detection-student\/test\/test\/\"\n\n    train_gen = ImageDataGenerator(rescale=1.\/255., \n                                    validation_split=0.25,\n                                    width_shift_range=0.2,\n                                    height_shift_range=0.2,\n                                    shear_range=0.2,\n                                    zoom_range=0.1)\n    train_set = train_gen.flow_from_directory(train_path, target_size=IMAGE_SIZE, \\\n                                              batch_size=BATCH_SIZE, seed=SEED, \\\n                                              subset='training')\n    val_set = train_gen.flow_from_directory(train_path, target_size=IMAGE_SIZE, \\\n                                            batch_size=BATCH_SIZE, seed=SEED, \\\n                                            subset='validation')\n\n    test_gen = ImageDataGenerator(rescale=1.\/255)\n    test_set = train_gen.flow_from_directory(test_path, target_size=IMAGE_SIZE, \\\n                                             batch_size=BATCH_SIZE, seed=SEED, \\\n                                             shuffle=False, class_mode=None)\n    \n    return train_set, val_set, test_set\n\ntrain_set, val_set, test_set = get_set()\nbase_model = tf.keras.applications.Xception(input_shape=(299,299,3),weights=\"imagenet\", include_top=False)\nbase_model.trainable = False\nmodel = tf.keras.Sequential([\n        base_model,\n    tf.keras.layers.GlobalAveragePooling2D(),\n    tf.keras.layers.Dense(1042, activation='relu'),\n    tf.keras.layers.Dropout(0.2),\n    tf.keras.layers.Dense(42, activation='softmax')\n        ])\nmodel.compile(\n    optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4, beta_1=0.9, beta_2=0.999, amsgrad=False),\n    loss = 'categorical_crossentropy',\n    metrics=['acc']\n    )\nmodel.summary()\n\n\nEPOCHS = 3\n\nhist = model.fit(train_set, epochs=EPOCHS, \n                 validation_data=val_set, shuffle=True)","meta":"{'source': 'AI4Code', 'id': '4eb11e450c4288'}"}
{"id":"17018","text":"\"\"\"\n# Guide to Google Cloud Training, Ensembling & Learning Learning Rates\n\nThe objectives of this kernel are to first provide a quick overview of the steps I followed to set up virtual machine (VM) instance on Google Cloud Platform, to download the required competition files, to train the models, how I changed the parameters to obtain the public score of <0.45, and also how to leave the instance running upon exiting the terminal.\n\nIn particular, this will be my **last public kernel (with scores) until the competition ends**. The end of the competition is in about a month, and I figured that some insights on the tweeks to the existing training scripts could help those who have yet to make some sort of breakthrough at this point. \n\n\nBest regards,\n\nWei Hao\n\"\"\"\n\"\"\"\n# Google Cloud Platform\n\nGoogle Cloud Platform (GCP), offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search and YouTube.[1] Alongside a set of management tools, it provides a series of modular cloud services including computing, data storage, data analytics and machine learning. Registration requires a credit card or bank account details. Google Cloud Platform provides infrastructure as a service, platform as a service, and serverless computing environments.\n\nIn April 2008, Google announced App Engine, a platform for developing and hosting web applications in Google-managed data centers, which was the first cloud computing service from the company. The service became generally available in November 2011. Since the announcement of App Engine, Google added multiple cloud services to the platform.\n\nGoogle Cloud Platform is a part of Google Cloud, which includes the Google Cloud Platform public cloud infrastructure, as well as G Suite, enterprise versions of Android and Chrome OS, and application programming interfaces (APIs) for machine learning and enterprise mapping services.\n\n**Source:** Wikipedia\n\"\"\"\n\"\"\"\n## Free Credits\n\nIf you are a first time user, you can get around 300 USD free credits to play around with, which I personally feel is quite decent! To-date, I've only used 100 USD, since Jan 2020. \n\"\"\"\n\"\"\"\n## Compute Engine\n\nCompute Engine delivers configurable virtual machines running in Google\u2019s data centers with access to high-performance networking infrastructure and block storage. It caters to:\n- Select the right VM for your needs, whether general purpose, or workload optimized, in predefined or custom machine sizes\n- Integrate compute with other Google Cloud services such as AI\/ML and data analytics\n- Make reservations to help ensure your applications have the capacity they need as they scale. Save money just for running compute with sustained-use discounts, and achieve greater savings when you use committed-use discounts\n\n**Source:** https:\/\/cloud.google.com\/compute\n\"\"\"\nfrom IPython.display import Image\n\"\"\"\n## Launching and Navigating the Virtual Machine (VM) Instance\n\nOnce you have created your VM instance with the desired CPU & GPU resources, go to 'VM Instances' and you should see something like this:\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/google_cloud_compute_engine_launch_vm.png')\n\"\"\"\nOnce you are able to see that, click on the dropdown icon beside SSH and click 'Open in broswer window' (see above). A console like the following should appear:\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/google_cloud_vm.png')\n\"\"\"\nYou can refer to https:\/\/github.com\/Kaggle\/kaggle-api, where the README describes the CLI and API commands required to download the competition data and files into the VM's directory.\n\"\"\"\n\"\"\"\n# Model Training - Parameter Tuning\n\nFor model training, I am using GreatGameDota's script found at https:\/\/www.kaggle.com\/greatgamedota\/xception-classifier-w-ffhq-training-lb-537.\n\"\"\"\n\"\"\"\n## Epochs, Factor, Learning Rates & Patience (IMPORTANT EXPERIMENTAL NOTES)\n\nI've tried various learning rates `lr` (0.001, 0.0015, 0.002, 0.004), `epochs` (10, 12, 20, 42), `patience` (2, 5, 7) and `factor` (0.1, 0.2, 0.5, 0.7). The result from these is the score of 0.50480 for the Xception single model, and 0.43846 for the Resnext + Xception esemble. Further tweeking of these parameters do help increase the public LB score by a bit. Also, yet interestingly, as the score of the single model Xception decreases, the higher scoring esembles have equal weights, i.e. 0.5 for Resnext and 0.5 for Xception. \n\nFeel free to tweek these parameters further! Note that the total time for each run of 30 epochs or more on Google Cloud Compute took **more than 20 hours**. So it may be wise to plan your parameters properly based on the insights gathered from past trainings!\n\"\"\"\n\"\"\"\n## Some Xception (Single Model) Training Outputs\n\"\"\"\n!ls ..\/input\/deepfake-kernel-data\n\"\"\"\n### Learning Rate: 0.0015, Epochs: 42, Patience: 5\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/lr_15e-2_epochs_42_patience_5.png')\n\"\"\"\n### Learning Rate: 0.002, Epochs: 10, Patience: 5\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/lr_2e-3_epochs_10_patience_5.png')\n\"\"\"\n### Learning Rate: 0.002, Epochs: 20, Patience: 5\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/lr_2e-3_epochs_20_patience_5.png')\n\"\"\"\n### Learning Rate: 0.004, Epochs: 12, Patience: 2\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/lr_4e-3_epochs_12_patience_2.png')\n\"\"\"\n### Learning Rate: 0.004, Epochs: 30, Patience: 2\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/lr_4e-3_epochs_30_patience_2.png')\n\"\"\"\n## Some Training Outputs in the VM\n\"\"\"\nImage('..\/input\/deepfake-kernel-data\/google_cloud_vm_deepfake_training_screenshot.png')\n\"\"\"\n# Running the Instance in the Backend with Screen\n\"\"\"\n\"\"\"\nTo leave the VM instance running in the backend, you can use `screen`. For installation details and how to execute it, instructions can be found in the source link below, and at https:\/\/stackoverflow.com\/questions\/48221807\/google-cloud-instance-terminate-after-close-browser.\n\nScreen or GNU Screen is a terminal multiplexer. In other words, it means that you can start a screen session and then open any number of windows (virtual terminals) inside that session. Processes running in Screen will continue to run when their window is not visible even if you get disconnected.\n\n**Source:** https:\/\/linuxize.com\/post\/how-to-use-linux-screen\/\n\"\"\"\n\"\"\"\n# Resnext & Xception Ensemble\n\n- The following have been taken from https:\/\/www.kaggle.com\/khoongweihao\/xception-resnext-ensemble-inference\n\"\"\"\n\"\"\"\n## Resnext Model\n\"\"\"\nimport os, sys, time\nimport cv2\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ntest_dir = \"\/kaggle\/input\/deepfake-detection-challenge\/test_videos\/\"\n\ntest_videos = sorted([x for x in os.listdir(test_dir) if x[-4:] == \".mp4\"])\nframe_h = 5\nframe_l = 5\nlen(test_videos)\nprint(\"PyTorch version:\", torch.__version__)\nprint(\"CUDA version:\", torch.version.cuda)\nprint(\"cuDNN version:\", torch.backends.cudnn.version())\ngpu = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu\nimport sys\nsys.path.insert(0, \"\/kaggle\/input\/blazeface-pytorch\")\nsys.path.insert(0, \"\/kaggle\/input\/deepfakes-inference-demo\")\nfrom blazeface import BlazeFace\nfacedet = BlazeFace().to(gpu)\nfacedet.load_weights(\"\/kaggle\/input\/blazeface-pytorch\/blazeface.pth\")\nfacedet.load_anchors(\"\/kaggle\/input\/blazeface-pytorch\/anchors.npy\")\n_ = facedet.train(False)\nfrom helpers.read_video_1 import VideoReader\nfrom helpers.face_extract_1 import FaceExtractor\n\nframes_per_video = 64 #frame_h * frame_l\nvideo_reader = VideoReader()\nvideo_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video)\nface_extractor = FaceExtractor(video_read_fn, facedet)\ninput_size = 224\nfrom torchvision.transforms import Normalize\n\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\nnormalize_transform = Normalize(mean, std)\ndef isotropically_resize_image(img, size, resample=cv2.INTER_AREA):\n    h, w = img.shape[:2]\n    if w > h:\n        h = h * size \/\/ w\n        w = size\n    else:\n        w = w * size \/\/ h\n        h = size\n\n    resized = cv2.resize(img, (w, h), interpolation=resample)\n    return resized\n\n\ndef make_square_image(img):\n    h, w = img.shape[:2]\n    size = max(h, w)\n    t = 0\n    b = size - h\n    l = 0\n    r = size - w\n    return cv2.copyMakeBorder(img, t, b, l, r, cv2.BORDER_CONSTANT, value=0)\nimport torch.nn as nn\nimport torchvision.models as models\n\nclass MyResNeXt(models.resnet.ResNet):\n    def __init__(self, training=True):\n        super(MyResNeXt, self).__init__(block=models.resnet.Bottleneck,\n                                        layers=[3, 4, 6, 3], \n                                        groups=32, \n                                        width_per_group=4)\n        self.fc = nn.Linear(2048, 1)\ncheckpoint = torch.load(\"\/kaggle\/input\/deepfakes-inference-demo\/resnext.pth\", map_location=gpu)\n\nmodel = MyResNeXt().to(gpu)\nmodel.load_state_dict(checkpoint)\n_ = model.eval()\n\ndel checkpoint\ndef predict_on_video(video_path, batch_size):\n    try:\n        # Find the faces for N frames in the video.\n        faces = face_extractor.process_video(video_path)\n\n        # Only look at one face per frame.\n        face_extractor.keep_only_best_face(faces)\n        \n        if len(faces) > 0:\n            # NOTE: When running on the CPU, the batch size must be fixed\n            # or else memory usage will blow up. (Bug in PyTorch?)\n            x = np.zeros((batch_size, input_size, input_size, 3), dtype=np.uint8)\n\n            # If we found any faces, prepare them for the model.\n            n = 0\n            for frame_data in faces:\n                for face in frame_data[\"faces\"]:\n                    # Resize to the model's required input size.\n                    # We keep the aspect ratio intact and add zero\n                    # padding if necessary.                    \n                    resized_face = isotropically_resize_image(face, input_size)\n                    resized_face = make_square_image(resized_face)\n\n                    if n < batch_size:\n                        x[n] = resized_face\n                        n += 1\n                    else:\n                        print(\"WARNING: have %d faces but batch size is %d\" % (n, batch_size))\n                    \n                    # Test time augmentation: horizontal flips.\n                    # TODO: not sure yet if this helps or not\n                    #x[n] = cv2.flip(resized_face, 1)\n                    #n += 1\n\n            if n > 0:\n                x = torch.tensor(x, device=gpu).float()\n\n                # Preprocess the images.\n                x = x.permute((0, 3, 1, 2))\n\n                for i in range(len(x)):\n                    x[i] = normalize_transform(x[i] \/ 255.)\n\n                # Make a prediction, then take the average.\n                with torch.no_grad():\n                    y_pred = model(x)\n                    y_pred = torch.sigmoid(y_pred.squeeze())\n                    return y_pred[:n].mean().item()\n\n    except Exception as e:\n        print(\"Prediction error on video %s: %s\" % (video_path, str(e)))\n\n    return 0.5\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef predict_on_video_set(videos, num_workers):\n    def process_file(i):\n        filename = videos[i]\n        y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video)\n        return y_pred\n\n    with ThreadPoolExecutor(max_workers=num_workers) as ex:\n        predictions = ex.map(process_file, range(len(videos)))\n\n    return list(predictions)\nspeed_test = False  # you have to enable this manually\nif speed_test:\n    start_time = time.time()\n    speedtest_videos = test_videos[:5]\n    predictions = predict_on_video_set(speedtest_videos, num_workers=4)\n    elapsed = time.time() - start_time\n    print(\"Elapsed %f sec. Average per video: %f sec.\" % (elapsed, elapsed \/ len(speedtest_videos)))\npredictions = predict_on_video_set(test_videos, num_workers=4)\nsubmission_df_resnext = pd.DataFrame({\"filename\": test_videos, \"label\": predictions})\nsubmission_df_resnext.to_csv(\"submission_resnext.csv\", index=False)\n\"\"\"\n## Xception Model\n\"\"\"\n!pip install ..\/input\/deepfake-xception-trained-model\/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet\ntest_dir = \"\/kaggle\/input\/deepfake-detection-challenge\/test_videos\/\"\n\ntest_videos = sorted([x for x in os.listdir(test_dir) if x[-4:] == \".mp4\"])\nlen(test_videos)\ngpu = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu\nimport sys\nsys.path.insert(0, \"\/kaggle\/input\/blazeface-pytorch\")\nsys.path.insert(0, \"\/kaggle\/input\/deepfakes-inference-demo\")\nfrom blazeface import BlazeFace\nfacedet = BlazeFace().to(gpu)\nfacedet.load_weights(\"\/kaggle\/input\/blazeface-pytorch\/blazeface.pth\")\nfacedet.load_anchors(\"\/kaggle\/input\/blazeface-pytorch\/anchors.npy\")\n_ = facedet.train(False)\nfrom helpers.read_video_1 import VideoReader\nfrom helpers.face_extract_1 import FaceExtractor\n\nframes_per_video = 64 # originally 4\n\nvideo_reader = VideoReader()\nvideo_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video)\nface_extractor = FaceExtractor(video_read_fn, facedet)\ninput_size = 150\nfrom torchvision.transforms import Normalize\n\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\nnormalize_transform = Normalize(mean, std)\ndef isotropically_resize_image(img, size, resample=cv2.INTER_AREA):\n    h, w = img.shape[:2]\n    if w > h:\n        h = h * size \/\/ w\n        w = size\n    else:\n        w = w * size \/\/ h\n        h = size\n\n    resized = cv2.resize(img, (w, h), interpolation=resample)\n    return resized\n\n\ndef make_square_image(img):\n    h, w = img.shape[:2]\n    size = max(h, w)\n    t = 0\n    b = size - h\n    l = 0\n    r = size - w\n    return cv2.copyMakeBorder(img, t, b, l, r, cv2.BORDER_CONSTANT, value=0)\n!ls ..\/input\/deepfake-xception-trained-model\n!ls ..\/input\/deepfake-kernel-data\nfrom pytorchcv.model_provider import get_model\nmodel = get_model(\"xception\", pretrained=False)\nmodel = nn.Sequential(*list(model.children())[:-1]) # Remove original output layer\n\nclass Pooling(nn.Module):\n  def __init__(self):\n    super(Pooling, self).__init__()\n    \n    self.p1 = nn.AdaptiveAvgPool2d((1,1))\n    self.p2 = nn.AdaptiveMaxPool2d((1,1))\n\n  def forward(self, x):\n    x1 = self.p1(x)\n    x2 = self.p2(x)\n    return (x1+x2) * 0.5\n\nmodel[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d((1,1)))\n\nclass Head(torch.nn.Module):\n  def __init__(self, in_f, out_f):\n    super(Head, self).__init__()\n    \n    self.f = nn.Flatten()\n    self.l = nn.Linear(in_f, 512)\n    self.d = nn.Dropout(0.5)\n    self.o = nn.Linear(512, out_f)\n    self.b1 = nn.BatchNorm1d(in_f)\n    self.b2 = nn.BatchNorm1d(512)\n    self.r = nn.ReLU()\n\n  def forward(self, x):\n    x = self.f(x)\n    x = self.b1(x)\n    x = self.d(x)\n\n    x = self.l(x)\n    x = self.r(x)\n    x = self.b2(x)\n    x = self.d(x)\n\n    out = self.o(x)\n    return out\n\nclass FCN(torch.nn.Module):\n  def __init__(self, base, in_f):\n    super(FCN, self).__init__()\n    self.base = base\n    self.h1 = Head(in_f, 1)\n  \n  def forward(self, x):\n    x = self.base(x)\n    return self.h1(x)\n\nnet = []\nmodel = FCN(model, 2048)\nmodel = model.cuda()\nmodel.load_state_dict(torch.load('..\/input\/deepfake-kernel-data\/model_50epochs_lr0001_patience5_factor01_batchsize32.pth')) # new, updated\nnet.append(model)\n\"\"\"\n### Prediction Loop\n\"\"\"\ndef predict_on_video(video_path, batch_size):\n    try:\n        # Find the faces for N frames in the video.\n        faces = face_extractor.process_video(video_path)\n\n        # Only look at one face per frame.\n        face_extractor.keep_only_best_face(faces)\n        \n        if len(faces) > 0:\n            # NOTE: When running on the CPU, the batch size must be fixed\n            # or else memory usage will blow up. (Bug in PyTorch?)\n            x = np.zeros((batch_size, input_size, input_size, 3), dtype=np.uint8)\n\n            # If we found any faces, prepare them for the model.\n            n = 0\n            for frame_data in faces:\n                for face in frame_data[\"faces\"]:\n                    # Resize to the model's required input size.\n                    # We keep the aspect ratio intact and add zero\n                    # padding if necessary.                    \n                    resized_face = isotropically_resize_image(face, input_size)\n                    resized_face = make_square_image(resized_face)\n\n                    if n < batch_size:\n                        x[n] = resized_face\n                        n += 1\n                    else:\n                        print(\"WARNING: have %d faces but batch size is %d\" % (n, batch_size))\n                    \n                    # Test time augmentation: horizontal flips.\n                    # TODO: not sure yet if this helps or not\n                    #x[n] = cv2.flip(resized_face, 1)\n                    #n += 1\n\n            if n > 0:\n                x = torch.tensor(x, device=gpu).float()\n\n                # Preprocess the images.\n                x = x.permute((0, 3, 1, 2))\n\n                for i in range(len(x)):\n                    x[i] = normalize_transform(x[i] \/ 255.)\n#                     x[i] = x[i] \/ 255.\n\n                # Make a prediction, then take the average.\n                with torch.no_grad():\n                    y_pred = model(x)\n                    y_pred = torch.sigmoid(y_pred.squeeze())\n                    return y_pred[:n].mean().item()\n\n    except Exception as e:\n        print(\"Prediction error on video %s: %s\" % (video_path, str(e)))\n\n    return 0.5\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef predict_on_video_set(videos, num_workers):\n    def process_file(i):\n        filename = videos[i]\n        y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video)\n        return y_pred\n\n    with ThreadPoolExecutor(max_workers=num_workers) as ex:\n        predictions = ex.map(process_file, range(len(videos)))\n\n    return list(predictions)\nspeed_test = False\nif speed_test:\n    start_time = time.time()\n    speedtest_videos = test_videos[:5]\n    predictions = predict_on_video_set(speedtest_videos, num_workers=4)\n    elapsed = time.time() - start_time\n    print(\"Elapsed %f sec. Average per video: %f sec.\" % (elapsed, elapsed \/ len(speedtest_videos)))\n%%time\nmodel.eval()\npredictions = predict_on_video_set(test_videos, num_workers=4)\nsubmission_df_xception = pd.DataFrame({\"filename\": test_videos, \"label\": predictions})\nsubmission_df_xception.to_csv(\"submission_xception.csv\", index=False)\nsubmission_df_resnext.head()\nsubmission_df_xception.head()\n\"\"\"\n## Ensemble of Resnext & Xception\n\n- Resnext single model public score: 0.46441\n- Xception single model public score: 0.50480\n\"\"\"\nsubmission_df = pd.DataFrame({\"filename\": test_videos})\nsubmission_df[\"label\"] = 0.51*submission_df_resnext[\"label\"] + 0.5*submission_df_xception[\"label\"]\nsubmission_df.to_csv(\"submission.csv\", index=False)\n\"\"\"\n### Thanks for checking this out and I hope it will help in some way. May Gauss bless us all.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1f0ecced08104b'}"}
{"id":"5603","text":"!pip install icevision[all]\n!pip install torch_optimizer\n!pip install wandb -U\n\"\"\"\nThis notebook uses [IceVision](https:\/\/github.com\/airctic\/icevision) object detection library.\n\nFor final submission efficientdet_d5 model was trained on 512x512 image size and also pretrained on provided separate image dataset.\n\n[Inference notebook](https:\/\/www.kaggle.com\/nikitautin\/35th-place-efficientdet-inference)\n\"\"\"\nimport os\nimport functools\nimport numpy as np\nimport pandas as pd\nimport torch_optimizer as optim\nimport torchvision.transforms as T\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom icevision.all import *\nfrom tqdm.contrib.concurrent import process_map\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint, Callback\nfrom kaggle_secrets import UserSecretsClient\nfrom torch.distributions.beta import Beta\nfrom operator import itemgetter\nfrom PIL import Image\nfrom icevision.metrics import Metric\nfrom scipy.optimize import linear_sum_assignment\nuser_secrets = UserSecretsClient()\nwandb_key = user_secrets.get_secret(\"wandb-key\")\n\n!wandb login $wandb_key\npl.seed_everything(42)\nFRAME_RANGE = 4\nVALID_PERCENT = 0.2\nSIZE = (256, 256)\nCLASSES_NUM = 2\nIMPACT_CLASS = 2\npath = Path('\/kaggle\/input\/nfl-impact-detection')\ntrain_video_path = path\/'train'\nvideo_labels = pd.read_csv(path\/'train_labels.csv').fillna(0)\nvideo_labels.head(2)\n\"\"\"\nSet impact label for helmets at range of 4 frames from labeled impact:\n\"\"\"\nvideo_labels_with_impact = video_labels[video_labels['impact'] > 0]\nfor index, row in tqdm(video_labels_with_impact.iterrows(), total=len(video_labels_with_impact)):\n    frames = np.arange(-FRAME_RANGE, FRAME_RANGE + 1) + row.frame\n    indexes = video_labels.query('video == @row.video and frame in @frames and label == @row.label').index\n    video_labels.loc[indexes, 'impact'] = 1\nvideo_labels['image_name'] = video_labels['video'].str.replace('.mp4', '') + '_' + video_labels['frame'].astype(str) + '.png'\nvideo_labels = video_labels[video_labels.groupby('image_name')['impact'].transform('sum') > 0].reset_index(drop=True)\nvideo_labels['impact'] = video_labels['impact'].astype(int) + 1\nvideo_labels.head()\nvideo_names = np.random.permutation(video_labels.video.unique())\nvalid_video_len = int(len(video_names) * VALID_PERCENT)\nvideo_valid = video_names[:valid_video_len]\nvideo_train = video_names[valid_video_len:]\nimages_valid = video_labels[video_labels.video.isin(video_valid)].image_name.unique()\nimages_train = video_labels[video_labels.video.isin(video_train)].image_name.unique()\ndef make_images(video_name, video_dir, video_labels, out_dir, only_with_impact=True, impact_cls=IMPACT_CLASS):\n    vidcap = cv2.VideoCapture(str(video_dir\/video_name))\n    frame = 0\n    while True:\n        read, img = vidcap.read()\n        if not read:\n            break\n        frame += 1\n        if only_with_impact:\n            query_str = 'video == @video_name and frame == @frame and impact == @impact_cls'\n            boxes = video_labels.query(query_str)\n            if len(boxes) == 0:\n                continue\n        image_path = f'{out_dir}\/{video_name}'.replace('.mp4', f'_{frame}.png')\n        _ = cv2.imwrite(image_path, img)\ntrain_images_path = Path('\/kaggle\/working\/train_images')\ntrain_images_path.mkdir()\n\"\"\"\nCreate images using frames with impact labels:\n\"\"\"\nmake_images_part = functools.partial(make_images, video_dir=train_video_path, video_labels=video_labels, out_dir=train_images_path)\nprocess_map(make_images_part, os.listdir(train_video_path), max_workers=2);\nlen(os.listdir(train_images_path))\nclass HelmetParser(parsers.FasterRCNN, parsers.FilepathMixin, parsers.SizeMixin):\n    def __init__(self, df, source):\n        self.df = df\n        self.source = source\n\n    def __iter__(self):\n        yield from self.df.itertuples()\n\n    def __len__(self):\n        return len(self.df)\n\n    def imageid(self, o) -> Hashable:\n        return o.image_name\n\n    def filepath(self, o) -> Union[str, Path]:\n        return self.source\/o.image_name\n\n    def image_width_height(self, o) -> Tuple[int, int]:\n        return get_image_size(self.filepath(o))\n\n    def labels(self, o) -> List[int]:\n        return [o.impact]\n\n    def bboxes(self, o) -> List[BBox]:\n        return [BBox.from_xywh(o.left, o.top, o.width, o.height)]\nparser = HelmetParser(video_labels, train_images_path)\ndata_splitter = FixedSplitter([images_train, images_valid])\ntrain_rs, valid_rs = parser.parse(data_splitter=data_splitter, autofix=True)\nshow_records(train_rs[:1], display_label=True, figsize=(10, 10), ncols=1)\ntrain_tfms = tfms.A.Adapter([tfms.A.HorizontalFlip(p=0.5),\n                             tfms.A.RGBShift(), tfms.A.RandomBrightnessContrast(),\n                             tfms.A.Blur(blur_limit=(1, 3), p=0.5),\n                             tfms.A.OneOrOther(tfms.A.RandomSizedBBoxSafeCrop(*SIZE), tfms.A.Resize(*SIZE), p=0.5),\n                             tfms.A.Normalize()])\nvalid_tfms = tfms.A.Adapter([tfms.A.Resize(*SIZE), tfms.A.Normalize()])\ntrain_ds = Dataset(train_rs, train_tfms)\nvalid_ds = Dataset(valid_rs, valid_tfms)\n\"\"\"\nSample from train dataset:\n\"\"\"\nsamples = [train_ds[0] for _ in range(6)]\nshow_samples(samples, ncols=3, denormalize_fn=denormalize_imagenet, display_label=False, figsize=(30,30))\n\"\"\"\nSample from validation dataset:\n\"\"\"\nsamples = [valid_ds[0] for _ in range(3)]\nshow_samples(samples, ncols=3, denormalize_fn=denormalize_imagenet, display_label=False, figsize=(30,30))\ntrain_dl = efficientdet.train_dl(train_ds, batch_size=32, num_workers=2, shuffle=True)\nvalid_dl = efficientdet.valid_dl(valid_ds, batch_size=32, num_workers=2, shuffle=False)\n\"\"\"\nSample train batch:\n\"\"\"\nbatch, samples = next(iter(train_dl))\nshow_samples(samples[:6], ncols=3, denormalize_fn=denormalize_imagenet, display_label=False, figsize=(30,30))\nmodel = efficientdet.model(model_name=\"tf_efficientdet_d3\", num_classes=CLASSES_NUM, img_size=SIZE)\nclass MixUp:\n    def __init__(self, alpha=20.0, min_w=0.4, max_w=0.6):\n        self.distrib = Beta(tensor(alpha), tensor(alpha))\n        self.min_w = min_w\n        self.max_w = max_w\n    \n    def __call__(self, batch):\n        x, y = batch\n        batch_size = x.shape[0]\n        device = x.device\n        self.lam = self.distrib.sample((batch_size,)).squeeze().to(device)\n        self.lam = torch.clip(self.lam, self.min_w, self.max_w)\n        self.shuffle = torch.randperm(batch_size, device=device)\n        classes = y['cls']\n        bbox = y['bbox']\n        dims = len(x.shape)\n        return (torch.lerp(x, x[self.shuffle], self.unsqueeze(self.lam, dims - 1, -1)),\n                {\n                  'bbox': list(map(torch.cat, zip(bbox, itemgetter(*self.shuffle)(bbox)))),\n                  'cls': list(map(torch.cat, zip(classes, itemgetter(*self.shuffle)(classes))))\n                }\n               )\n    \n    def unsqueeze(self, x, n, dim):\n        for _ in range(n):\n            x = x.unsqueeze(dim)\n        return x\n\"\"\"\nFor metric implementation [this notebook](https:\/\/www.kaggle.com\/nvnnghia\/evaluation-metrics) was used.\n\"\"\"\nclass F1Metric(Metric):\n    def __init__(self, detection_threshold):\n        self._records, self._preds = [], []\n        self.detection_threshold = detection_threshold\n\n    def _reset(self):\n        self._records.clear()\n        self._preds.clear()\n\n    def accumulate(self, records, preds):\n        self._records.extend(records)\n        self._preds.extend(preds)\n\n    def finalize(self) -> Dict[str, float]:\n        gt_boxes = []\n        for s in self._records:\n            gt_boxes.append(list(map(lambda b: np.array(b.xyxy), \n                                     np.array(s[\"bboxes\"])[np.array(s[\"labels\"]) == IMPACT_CLASS])))\n        pred_boxes = []\n        for p in self._preds:\n            pred_boxes.append(list(map(lambda b: np.array(b.xyxy),\n                                       np.array(p[\"bboxes\"])[\n                                           (np.array(p[\"scores\"]) >= self.detection_threshold)\n                                           & (np.array(p[\"labels\"]) == IMPACT_CLASS)\n                                       ]\n                                      )))\n        \n        tps, fps, fns = [], [], []\n        for i in range(len(gt_boxes)):\n            tp, fp, fn = self.precision_calc(gt_boxes[i], pred_boxes[i])\n            tps.append(tp)\n            fps.append(fp)\n            fns.append(fn)\n\n        tp = np.sum(tps)\n        fp = np.sum(fps)\n        fn = np.sum(fns)\n        precision = tp \/ (tp + fp + 1e-6)\n        recall =  tp \/ (tp + fn + 1e-6)\n        f1_score = 2 * (precision*recall ) \/(precision + recall + 1e-6)\n        \n        self._reset()\n        return {\"f1\": f1_score}\n    \n    @property\n    def name(self) -> str:\n        return self.__class__.__name__ + str(self.detection_threshold)\n    \n    def iou(self, bbox1, bbox2):\n        bbox1 = list(map(float, bbox1))\n        bbox2 = list(map(float, bbox2))\n\n        (x0_1, y0_1, x1_1, y1_1) = bbox1\n        (x0_2, y0_2, x1_2, y1_2) = bbox2\n\n        # get the overlap rectangle\n        overlap_x0 = max(x0_1, x0_2)\n        overlap_y0 = max(y0_1, y0_2)\n        overlap_x1 = min(x1_1, x1_2)\n        overlap_y1 = min(y1_1, y1_2)\n\n        # check if there is an overlap\n        if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:\n            return 0\n\n        # if yes, calculate the ratio of the overlap to each ROI size and the unified size\n        size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)\n        size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)\n        size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)\n        size_union = size_1 + size_2 - size_intersection\n\n        return size_intersection \/ size_union\n    \n    def precision_calc(self, gt_boxes, pred_boxes):\n        cost_matix = np.ones((len(gt_boxes), len(pred_boxes)))\n        for i, box1 in enumerate(gt_boxes):\n            for j, box2 in enumerate(pred_boxes):\n                iou_score = self.iou(box1, box2)\n\n                if iou_score < 0.35:\n                    continue\n                else:\n                    cost_matix[i,j]=0\n\n        row_ind, col_ind = linear_sum_assignment(cost_matix)\n        fn = len(gt_boxes) - row_ind.shape[0]\n        fp = len(pred_boxes) - col_ind.shape[0]\n        tp = 0\n        for i, j in zip(row_ind, col_ind):\n            if cost_matix[i,j] == 0:\n                tp += 1\n            else:\n                fp += 1\n                fn += 1\n        return tp, fp, fn\nclass LightModel(efficientdet.lightning.ModelAdapter):\n    def __init__(self, lr, epochs, dl_len, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.mixup = MixUp()\n        self.save_hyperparameters('lr', 'epochs', 'dl_len')\n        \n    def training_step(self, batch, batch_idx):\n        self.mixuped = self.mixup(batch[0])\n        return super().training_step((self.mixuped, batch[1]), batch_idx)\n    \n    def configure_optimizers(self):\n        optimizer =  optim.RAdam(self.parameters(), lr=self.hparams.lr, weight_decay=0.1)\n        scheduler = {\n            'scheduler': torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,\n                                                                    self.hparams.dl_len * self.hparams.epochs,\n                                                                    self.hparams.lr \/ 100),\n            'interval': 'step',\n            'frequency': 1,\n        }\n        return [optimizer], [scheduler]\nmetrics = [F1Metric(0.3)]\nlight_model = LightModel(1e-2, 5, len(train_dl), model, metrics=metrics)\nwandb_logger = WandbLogger(name='effdet_d3', project='NFL', log_model=True)\nlr_monitor = LearningRateMonitor(logging_interval='step')\n\ntrainer = pl.Trainer(max_epochs=5, gpus=1, precision=16,\n                     callbacks=[lr_monitor],\n                     logger=wandb_logger,\n                     log_every_n_steps=1,\n                     flush_logs_every_n_steps=10,\n                     auto_lr_find=False\n                    )\n# lr_finder = trainer.tuner.lr_find(light_model, train_dl, valid_dl)\n# fig = lr_finder.plot(suggest=True)\n# fig.show()\ntrainer.fit(light_model, train_dl, valid_dl)\n\"\"\"\nMixup augmentation samples:\n\"\"\"\nimgs = light_model.mixuped[0].permute(0, 2, 3, 1).cpu().numpy()\npx.imshow(denormalize_imagenet(imgs[:3]), facet_col=0)\n!rm -rf \/kaggle\/working\/train_images\/*","meta":"{'source': 'AI4Code', 'id': '0a620e540137b0'}"}
{"id":"9734","text":"\"\"\"\n# **LBGM**\n* LightGBM is a gradient boosting framework that uses tree based learning algorithms. It is designed to be distributed and efficient with the following advantages:\n* Faster training speed and higher efficiency (6 times faster than XGBoost)\n* Lower memory usage.\n* Better accuracy.\n* Support of parallel, distributed, and GPU learning.\n* Capable of handling large-scale data.\n\"\"\"\n\"\"\"\n\n### **<span>Dataset Structure<\/span>**\n\n> **train.csv** - The training set\n> \n> 1.  timestamp - A timestamp for the minute covered by the row.\n> 2.  Asset_ID - An ID code for the cryptoasset.\n> 3.  Count - The number of trades that took place this minute.\n> 4.  Open - The USD price at the beginning of the minute.\n> 5.  High - The highest USD price during the minute.\n> 6.  Low - The lowest USD price during the minute.\n> 7.  Close - The USD price at the end of the minute.\n> 8.  Volume - The number of cryptoasset u units traded during the minute.\n> 9.  VWAP - The volume-weighted average price for the minute.\n> 10. Target - 15 minute residualized returns. See the 'Prediction and Evaluation section of this notebook for details of how the target is calculated.\n> 11. Weight - Weight, defined by the competition hosts [here](https:\/\/www.kaggle.com\/cstein06\/tutorial-to-the-g-research-crypto-competition)\n> 12. Asset_Name - Human readable Asset name.\n> \n>\n> **example_test.csv** - An example of the data that will be delivered by the time series API.\n> \n> **example_sample_submission.csv** - An example of the data that will be delivered by the time series API. The data is just copied from train.csv.\n> \n> **asset_details.csv** - Provides the real name and of the cryptoasset for each Asset_ID and the weight each cryptoasset receives in the metric.\n> \n> **supplemental_train.csv** - After the submission period is over this file's data will be replaced with cryptoasset prices from the submission period. In the Evaluation phase, the train, train supplement, and test set will be contiguous in time, apart from any missing data. The current copy, which is just filled approximately the right amount of data from train.csv is provided as a placeholder.\n>\n> - \ud83d\udccc There are 14 coins in the dataset\n>\n> - \ud83d\udccc There are 4 years  in the [full] dataset\n\"\"\"\n\"\"\"\n# **Importing Libraries**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom lightgbm import LGBMRegressor\nimport gresearch_crypto\nimport traceback\nimport time\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nfrom sklearn.model_selection import GridSearchCV\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n### **Importing Data**\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## **Loading Data**\n\"\"\"\npath = \"\/kaggle\/input\/g-research-crypto-forecasting\/\"\ndf_train = pd.read_csv(path + \"train.csv\")\ndf_test = pd.read_csv(path + \"example_test.csv\")\ndf_asset_details = pd.read_csv(path + \"asset_details.csv\")\ndf_supp_train = pd.read_csv(path + \"supplemental_train.csv\")\n# Checking Train data \ndf_train.head()\ndf_train.shape\n# Checking Test data set\ndf_test.head()\ndf_test.shape\n\"\"\"\n* By visualising Train and Test data set (train.csv) except contains less rows.\n\"\"\"\n\"\"\"\n### **EDA**\n* Let's continue describing and analyzing the data \n\"\"\"\ndf_train.describe()\n# Checking Test data sets\ndf_test.describe()\ndf_train.isnull().sum()\ndf_test.isnull().sum()\n\"\"\"\n* seems like the VWAP column has NaN values we will check it later\n\"\"\"\ndf_train.info()\ndf_test.info()\n\"\"\"\n* By checking train data and test data there is some missing values in train data set\n\"\"\"\n\"\"\"\n## Timestamp\n* We define a helper function that will turn a date format into a timestamp to use for indexing.\n\"\"\"\ndf_asset_details\n\"\"\"\n* There are total 14 unque coins\n\"\"\"\ndf_supp_train\ndf_supp_train.info()\ndf_supp_train.isnull().sum()\n# auxiliary function, from datetime to timestamp\ntotimestamp = lambda s: np.int32(time.mktime(datetime.strptime(s, \"%d\/%m\/%Y\").timetuple()))\n\"\"\"\n### ****Checking Time range****\n\"\"\"\ndf_train.Asset_ID.unique()\ndf_train.Asset_ID.value_counts()\n\"\"\"\n**Bitcoin**\n\"\"\"\ndf_train[df_train['Asset_ID'] == 1].set_index(\"timestamp\")\nbtc = df_train[df_train['Asset_ID'] == 1].set_index(\"timestamp\")\ndatetime.fromtimestamp(btc.index[0])\n# Starting Date Time\n# %A= day,%B = Month, %d = month number, %Y  = Year,%I =hours , %M =minutes starting date, %S = seconds\ndatetime.fromtimestamp(btc.index[0]).strftime(\"%A, %B %d, %Y  %I: %M: %S\")\n# Above function store in a starting date formate\nbeg_btc = datetime.fromtimestamp(btc.index[0]).strftime(\"%A, %B %d, %Y  %I: %M: %S\")\n# Ending Date time\ndatetime.fromtimestamp(btc.index[-1]).strftime(\"%A, %B %d, %Y %I : %M : %S\")\nend_btc = datetime.fromtimestamp(btc.index[-1]).strftime(\"%A, %B %d, %Y %I : %M : %S\")\nprint('Bitcoin data goes from ', beg_btc, ' to ', end_btc)\n\"\"\"\n# Selecting 4-Coins\n* Bitcoin  = btc\n* Etherium = eth\n* Binance  = bnb\n* Cardano  = ada\n\"\"\"\n## Checking Time Range\nbtc = df_train[df_train[\"Asset_ID\"]==1].set_index(\"timestamp\") # Asset_ID = 1 for Bitcoin\neth = df_train[df_train[\"Asset_ID\"]==6].set_index(\"timestamp\") # Asset_ID = 6 for Ethereum\nbnb = df_train[df_train[\"Asset_ID\"]==0].set_index(\"timestamp\") # Asset_ID = 0 for Binance Coin\nada = df_train[df_train[\"Asset_ID\"]==3].set_index(\"timestamp\") # Asset_ID = 3 for Cardano\n\nbeg_btc = datetime.fromtimestamp(btc.index[0]).strftime(\"%A, %B %d, %Y %I:%M:%S\") \nend_btc = datetime.fromtimestamp(btc.index[-1]).strftime(\"%A, %B %d, %Y %I:%M:%S\") \nbeg_eth = datetime.fromtimestamp(eth.index[0]).strftime(\"%A, %B %d, %Y %I:%M:%S\") \nend_eth = datetime.fromtimestamp(eth.index[-1]).strftime(\"%A, %B %d, %Y %I:%M:%S\")\nbeg_bnb = datetime.fromtimestamp(eth.index[0]).strftime(\"%A, %B %d, %Y %I:%M:%S\") \nend_bnb = datetime.fromtimestamp(eth.index[-1]).strftime(\"%A, %B %d, %Y %I:%M:%S\")\nbeg_ada = datetime.fromtimestamp(eth.index[0]).strftime(\"%A, %B %d, %Y %I:%M:%S\") \nend_ada = datetime.fromtimestamp(eth.index[-1]).strftime(\"%A, %B %d, %Y %I:%M:%S\")\n\nprint('Bitcoin data goes from ', beg_btc, ' to ', end_btc) \nprint('Ethereum data goes from ', beg_eth, ' to ', end_eth)\nprint('Binance coin data goes from ', beg_bnb, ' to ', end_bnb) \nprint('Cardano data goes from ', beg_ada, ' to ', end_ada)\n\"\"\"\n* Here we have 4-Years of data range 2018-2021\n\"\"\"\n\"\"\"\n# Checking corelation of each individual coin\n* By using heatmap\n\"\"\"\n\"\"\"\n#### **Btc**\n\"\"\"\nplt.figure(figsize=(8,6))\nsns.heatmap(btc[['Count','Open','High','Low','Close','Volume','VWAP','Target']].corr(), \n            vmin=-1.0, vmax=1.0, annot=True, cmap='coolwarm', linewidths=0.1)\nplt.show()\n\"\"\"\n# Checking candle chart b\/w 2-coins Btc,Eth\n\"\"\"\nbtc.iloc[-1440:]\n\"\"\"\n# Checking candle stick for Etherium for last 24 hrs\n\"\"\"\neth.iloc[-1440:]\n# Checking 1 day candle stick chart 24hrs = 1440 mins\nbtc_mini = btc.iloc[-1440:]\neth_mini = eth.iloc[-1440:]\n\n# index = timestamp,\nfig = go.Figure(data=[go.Candlestick(x=btc_mini.index, open=btc_mini['Open'], high=btc_mini['High'], low=btc_mini['Low'], close=btc_mini['Close'])])\nfig.update_xaxes(title_text=\"$\")\nfig.update_yaxes(title_text=\"Index\")\nfig.update_layout(title=\"Bitcoin Price, Last 24 hours\")\nfig.show()\n\nfig = go.Figure(data=[go.Candlestick(x=eth_mini.index, open=eth_mini['Open'], high=eth_mini['High'], low=eth_mini['Low'], close=eth_mini['Close'])])\nfig.update_xaxes(title_text=\"$\")\nfig.update_yaxes(title_text=\"Index\")\nfig.update_layout(title=\"Ethereum Price,Last 24 hours\")\nfig.show()\n\"\"\"\n* We can Observe the corelation b\/w two coins\n\"\"\"\n\"\"\"\n# Ploting the Btc & Etherium\n\"\"\"\nf = plt.figure(figsize=(15,4))\n\n# fill NAs for BTC and ETH\nbtc = btc.reindex(range(btc.index[0],btc.index[-1]+60,60),method='pad')\neth = eth.reindex(range(eth.index[0],eth.index[-1]+60,60),method='pad')\n\nax = f.add_subplot(121)\nplt.plot(btc['Close'], color='yellow', label='BTC')\nplt.legend()\nplt.xlabel('Time (timestamp)')\nplt.ylabel('Bitcoin')\n\nax2 = f.add_subplot(122)\nax2.plot(eth['Close'], color='purple', label='ETH')\nplt.legend()\nplt.xlabel('Time (timestamp)')\nplt.ylabel('Ethereum')\n\nplt.tight_layout()\nplt.show()\n\"\"\"\n* We can also confirm through another visual observation that, within the 4 recent years, BTC and ETH prices are correlated.\n\"\"\"\n\"\"\"\n# Coin corelation for 1-weak\n\"\"\"\ndata =df_train[-10080:]\ncheck = pd.DataFrame()\nfor i in data.Asset_ID.unique():\n    check[i] = data[data.Asset_ID==i]['Target'].reset_index(drop=True) \n    \nplt.figure(figsize=(10,8))\nsns.heatmap(check.dropna().corr(), vmin=-1.0, vmax=1.0, annot=True, cmap='coolwarm', linewidths=0.1)\nplt.show()\n\"\"\"\n* Interestingly, in the last 1-weak we have several coins that are highly correlated with one another.\n\"\"\"\n\"\"\"\n# Feature Extraction\n* we add some features for our future predection\n\"\"\"\ndef hlco_ratio(df): \n    return (df['High'] - df['Low'])\/(df['Close']-df['Open'])\ndef upper_shadow(df):\n    return df['High'] - np.maximum(df['Close'], df['Open'])\ndef lower_shadow(df):\n    return np.minimum(df['Close'], df['Open']) - df['Low']\n\ndef get_features(df):\n    df_feat = df[['Count', 'Open', 'High', 'Low', 'Close', 'Volume', 'VWAP']].copy()\n    df_feat['Upper_Shadow'] = upper_shadow(df_feat)\n    df_feat['hlco_ratio'] = hlco_ratio(df_feat)\n    df_feat['Lower_Shadow'] = lower_shadow(df_feat)\n    return df_feat\n\"\"\"\n# Splitting\n\"\"\"\n# Training data set\ntrain_data = df_train\ntrain_data\ndef get_Xy_and_model_for_asset(df_train, asset_id):\n    df = df_train[df_train[\"Asset_ID\"] == asset_id]\n    \n    df = df.sample(frac=0.2)\n    df_proc = get_features(df)\n    df_proc['y'] = df['Target']\n    df_proc.replace([np.inf, -np.inf], np.nan, inplace=True)\n    df_proc = df_proc.dropna(how=\"any\")\n    \n    \n    X = df_proc.drop(\"y\", axis=1)\n    y = df_proc[\"y\"]   \n    model = LGBMRegressor()\n    model.fit(X, y)\n    return X, y, model\n\n\nXs = {}\nys = {}\nmodels = {}\n\nfor asset_id, asset_name in zip(df_asset_details['Asset_ID'], df_asset_details['Asset_Name']):\n    print(f\"Training model for {asset_name:<16} (ID={asset_id:<2})\")\n    X, y, model = get_Xy_and_model_for_asset(train_data, asset_id)       \n    try:\n        Xs[asset_id], ys[asset_id], models[asset_id] = X, y, model\n    except: \n        Xs[asset_id], ys[asset_id], models[asset_id] = None, None, None \n\"\"\"\n# Hyperparam Tuning\n* We will perform GridSearch for each LGBM model of 14 coins.\n\"\"\"\nparameters = {\n    # 'max_depth': range (2, 10, 1),\n    'num_leaves': range(21, 161, 10),\n    'learning_rate': [0.1, 0.01, 0.05]\n}\n\nnew_models = {}\nfor asset_id, asset_name in zip(df_asset_details['Asset_ID'], df_asset_details['Asset_Name']):\n    print(\"GridSearchCV for: \" + asset_name)\n    grid_search = GridSearchCV(\n        estimator=get_Xy_and_model_for_asset(df_train, asset_id)[2], # bitcoin\n        param_grid=parameters,\n        n_jobs = -1,\n        cv = 5,\n        verbose=True\n    )\n    grid_search.fit(Xs[asset_id], ys[asset_id])\n    new_models[asset_id] = grid_search.best_estimator_\n    grid_search.best_estimator_\n# Checking the Model interface\nfor asset_id, asset_name in zip(df_asset_details['Asset_ID'], df_asset_details['Asset_Name']):\n    print(f\"Tuned model for {asset_name:<1} (ID={asset_id:})\")\n    print(new_models[asset_id])\n\"\"\"\n# Submission\n\"\"\"\nenv = gresearch_crypto.make_env()\niter_test = env.iter_test()\n\nfor i, (df_test, df_pred) in enumerate(iter_test):\n    for j , row in df_test.iterrows():        \n        if new_models[row['Asset_ID']] is not None:\n            try:\n                model = new_models[row['Asset_ID']]\n                x_test = get_features(row)\n                y_pred = model.predict(pd.DataFrame([x_test]))[0]\n                df_pred.loc[df_pred['row_id'] == row['row_id'], 'Target'] = y_pred\n            except:\n                df_pred.loc[df_pred['row_id'] == row['row_id'], 'Target'] = 0\n                traceback.print_exc()\n        else: \n            df_pred.loc[df_pred['row_id'] == row['row_id'], 'Target'] = 0  \n    \n    env.predict(df_pred)","meta":"{'source': 'AI4Code', 'id': '11ea5361d8e710'}"}
{"id":"46501","text":"\"\"\"\n## Introduciton:\n### This is the second part of the project. In this part, I am going to construct the prediction model with Neural Network and try to optimize it.\n\"\"\"\nimport pandas as pd \nimport numpy as np\ndt = pd.read_csv(\"\/kaggle\/input\/simulated-bank-customer-data\/CUST_ASSET_DATA.csv\")\nind1 = dt[dt[\"AGE\"].isna()].index\nind2 = dt[dt[\"BRANCH_DIST\"].isna()].index\nind = pd.Series((list(ind1)+list(ind2))).unique()\ndt = dt.drop(index = ind)\n# preprocessing of data\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import r2_score\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nfrom keras.layers import Dropout\n\"\"\"\n### Since this is a time series data, we hope to use the current data to predict the total assets of the next period. I use current TOTAL_ASSET as one of the features and the next TOTAL_ASSET as y. Using first 11 month as traing data and the 12th month as testing data. Like following picture.\n![123.jpg](attachment:123.jpg)\n\"\"\"\ncolumns = [\"AGE\",\"GENDER\",\"CITY\",\"BRANCH_DIST\",\"ACTIVE_WEB_CUST\",\"SECURITY_ACC\",\n           \"INTERACT_AMT_A\",\"INTERACT_AMT_B\",\"TOTAL_ASSET_X\",\"TOTAL_ASSET_y\"]\n\ndt2 = pd.DataFrame(np.array(dt[[\"AGE\",\"GENDER\",\"CITY\",\"BRANCH_DIST\",\n          \"ACTIVE_WEB_CUST_1\",\"SECURITY_ACC_1\",\"INTERACT_AMT_A_1\",\n          \"INTERACT_AMT_B_1\",\"TOTAL_ASSET_1\",\"TOTAL_ASSET_2\"]]),columns = columns)\n\nfor i in range(2,12):\n    dt1 = pd.DataFrame(np.array(dt[[\"AGE\",\"GENDER\",\"CITY\",\"BRANCH_DIST\",\n                           \"ACTIVE_WEB_CUST_\"+str(i),\"SECURITY_ACC_\"+str(i),\n                           \"INTERACT_AMT_A_\"+str(i),\"INTERACT_AMT_B_\"+str(i),\n                           \"TOTAL_ASSET_\"+str(i),\"TOTAL_ASSET_\"+str(i+1)]])\n                       ,columns = columns)\n    Train_dt = pd.concat([dt2,dt1])\n\nTest_dt = pd.DataFrame(np.array(dt[[\"AGE\",\"GENDER\",\"CITY\",\"BRANCH_DIST\",\n          \"ACTIVE_WEB_CUST_12\",\"SECURITY_ACC_12\",\"INTERACT_AMT_A_12\",\n          \"INTERACT_AMT_B_12\",\"TOTAL_ASSET_12\",\"TOTAL_ASSET_13\"]]),columns = columns)\nTrain_dt\nTest_dt\n\"\"\"\n### Now we got 198026 traing data and 99013 testing data. Before we construct our model, we have to transform our nominal features into nominal codes.\n\"\"\"\nnominal = [\"AGE\",\"GENDER\",\"CITY\",\"BRANCH_DIST\",\"ACTIVE_WEB_CUST\",\"SECURITY_ACC\"]\n\nTrain_dt = Train_dt.copy()\nfor label in nominal:\n    Train_dt[label] = LabelEncoder().fit_transform(Train_dt[label])\n    \nTest_dt = Test_dt.copy()\nfor label in nominal:\n    Test_dt[label] = LabelEncoder().fit_transform(Test_dt[label])\nX_train, y_train,X_test,y_test = Train_dt.iloc[:,0:9],Train_dt.iloc[:,9:10],Test_dt.iloc[:,0:9],Test_dt.iloc[:,9:10]\n\nX_train=np.array(X_train).reshape(-1,9)\nX_test=np.array(X_test).reshape(-1,9)\ny_train=np.array(y_train).reshape(-1,1)\ny_test=np.array(y_test).reshape(-1,1)\n\nimport tensorflow as tf\nX_train = tf.constant(X_train, tf.float32)\nX_test = tf.constant(X_test, tf.float32)\ny_train = tf.constant(y_train, tf.float32)\ny_test = tf.constant(y_test, tf.float32)\n\"\"\"\n### Now we are going to construct our model with NN.\n\"\"\"\n#Plotting acc and loss plot.\nimport keras\nclass LossHistory(keras.callbacks.Callback):\n    def on_train_begin(self, logs={}):\n        self.losses = {'batch':[], 'epoch':[]}\n        self.accuracy = {'batch':[], 'epoch':[]}\n        self.val_loss = {'batch':[], 'epoch':[]}\n        self.val_acc = {'batch':[], 'epoch':[]}\n\n    def on_batch_end(self, batch, logs={}):\n        self.losses['batch'].append(logs.get('loss'))\n        self.accuracy['batch'].append(logs.get('accuracy'))\n        self.val_loss['batch'].append(logs.get('val_loss'))\n        self.val_acc['batch'].append(logs.get('val_accuracy'))\n\n    def on_epoch_end(self, batch, logs={}):\n        self.losses['epoch'].append(logs.get('loss'))\n        self.accuracy['epoch'].append(logs.get('accuracy'))\n        self.val_loss['epoch'].append(logs.get('val_loss'))\n        self.val_acc['epoch'].append(logs.get('val_accuracy'))\n\n    def loss_plot(self, loss_type):\n        iters = range(len(self.losses[loss_type]))\n        # loss\n        plt.plot(iters, self.losses[loss_type], 'g', label='train loss')\n        if loss_type == 'epoch':\n            # val_loss\n            plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')\n        plt.grid(True)\n        plt.xlabel(loss_type)\n        plt.ylabel(\"loss\")\n        plt.legend(loc=\"upper right\")\n        plt.show()\nann=Sequential()\nann.add(Dense(64, input_dim=9, activation='relu'))\nann.add(Dense(32, input_dim=64, activation='relu'))\nann.add(Dense(units=1, kernel_initializer='normal', activation='linear'))\nann.compile(loss='mean_squared_error', optimizer='adam',metrics=['accuracy'])\nhistory = LossHistory() # call the class we built \nann.fit(X_train, y_train, epochs=300, batch_size=8000, \n        validation_data=(X_test, y_test),callbacks=[history],\n        verbose=1, shuffle=False)\nhistory.loss_plot('epoch')\n\"\"\"\n### It seems that loss function converge very quickly \n\"\"\"\ny_pred_test = ann.predict(X_test)\ny_train_pred =ann.predict(X_train)\nprint(\"The R2 score on the ANNTrain set is:\\t{:0.3f}\".format(r2_score(y_train, y_train_pred)))\nprint(\"The R2 score on the ANNTest set is:\\t{:0.3f}\".format(r2_score(y_test, y_pred_test)))\ny_pred = y_pred_test[0:50] \ny_origin = y_test[0:50]\n\nX = range(0,50)\nplt.plot(X,y_pred,label = \"prediction\",color = \"red\")\nplt.plot(X,y_origin,label = \"origin\",color = \"blue\")\nplt.legend()\nplt.xlabel(\"customer\")\nplt.ylabel(\"amount\")\nAnswer = np.array(dt[\"TOTAL_ASSET_13\"]).reshape(-1,1)\nprint(\"MSE of Prediction: \"+str((((np.array(y_pred_test).reshape(-1,1)-Answer)**2)\/len(dt)).sum()))\n\"\"\"\n### Now we reset the epoch to 50 time and construct the model again.\n\"\"\"\nann=Sequential()\nann.add(Dense(64, input_dim=9, activation='relu'))\nann.add(Dense(32, input_dim=64, activation='relu'))\nann.add(Dense(units=1, kernel_initializer='normal', activation='linear'))\nann.compile(loss='mean_squared_error', optimizer='adam',metrics=['accuracy'])\nhistory = LossHistory() # call the class we built \nann.fit(X_train, y_train, epochs=50, batch_size=8000, \n        validation_data=(X_test, y_test),callbacks=[history],\n        verbose=1, shuffle=False)\ny_pred_test = ann.predict(X_test)\ny_train_pred =ann.predict(X_train)\nprint(\"The R2 score on the ANNTrain set is:\\t{:0.3f}\".format(r2_score(y_train, y_train_pred)))\nprint(\"The R2 score on the ANNTest set is:\\t{:0.3f}\".format(r2_score(y_test, y_pred_test)))\nAnswer = np.array(dt[\"TOTAL_ASSET_13\"]).reshape(-1,1)\nprint(\"MSE of Prediction: \"+str((((np.array(y_pred_test).reshape(-1,1)-Answer)**2)\/len(dt)).sum()))\n\"\"\"\n### After we set the epoch to 50 times, we get the better R-square and MSE. I infer that the model is overfitted if we set the hyper parameter to 200.\n\"\"\"\nann.save('my_model.h5') # save the model for further research","meta":"{'source': 'AI4Code', 'id': '55af498fcc88e1'}"}
{"id":"62255","text":"\"\"\"\n## Task 2 : Prediction using Unsupervised ML\n\n* From the given \u2018Iris\u2019 dataset, predict the optimum number of clusters and represent it visually.<br>\n\n> ##### **By:** Rutuja Vaidya\n> ##### **Technique used:** UnSupervised ML: K-Means\n> ##### **Language used:** Python\n\"\"\"\n\"\"\"\n### Importing libraries and Data set\n\"\"\"\n#importing libraries\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.cluster import KMeans\n\nimport warnings\nwarnings.filterwarnings('ignore')\n# loading data\ntry:\n    iris_data = pd.read_csv('..\/input\/iris-dataset\/Iris.csv')\n    print(\"Data loaded Successfully!!\\n\")\n    iris_data.info()\nexcept:\n    print(\"Can't Load data\")\n\"\"\"\nWe can conclude from above information:\n1.   All Columns are Filled i.e. There is no Null value present\n2.   Iris Data contains 6 columns out of which :<br>\n  **`Id`** column is unique.<br>\n  **`Species`** is the Target<br>\n  **`SepalLengthCm`, `SepalWidthCm`, `PetalLengthCm`, `PetalWidthCm`** are Features<br>\n\"\"\"\n# check the data by printing first 5 lines\niris_data.head()\n\"\"\"\n> Target **`Species`** has categorical values\n\nLet's check its unique values\n\"\"\"\niris_data['Species'].value_counts()\niris_data['Species']\n\"\"\"\n### Exploratory Analysis\n\"\"\"\n# Let's first see the features\niris_data.describe()\nplt.figure(figsize=(10,6))\nax = sns.boxplot(data=iris_data.drop('Id',axis=1), orient=\"h\", palette=\"Set2\")\n# let's chechk correlation between numeric columns\ncorr = iris_data.drop('Id',axis=1).corr()\nmask = np.triu(np.ones_like(corr, dtype=np.bool))\nheatmap = sns.heatmap(corr, mask=mask, vmin=-1, vmax=1, annot=True)\nheatmap.set_title('Correlation Heatmap', fontdict={'fontsize':12}, pad=12);\n\"\"\"\n> The Sepal Width and Length are not correlated The Petal Width and Length are highly correlated\n\"\"\"\n# Correlation of Sepal Length-Width\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='SepalLengthCm',y='SepalWidthCm',hue='Species',data=iris_data)\n# Correlation of Petal Length-Width\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='PetalLengthCm',y='PetalWidthCm',hue='Species',data=iris_data)\n\"\"\"\nFrom above Two graphs, we can see that\n* Sepal Length and Width have low correlation   \n* Petal Length and Width have high correlation\n\n\"\"\"\n# Let's bivariate relation between each pair of features by Ploting the PairPlot\nsns.pairplot(iris_data, hue=\"Species\", size=3.2)\n\"\"\"\n>From the pairplot, we can see that the `Iris-setosa` species is separataed from the other two across all feature combinations\n\"\"\"\ndef ViolinPlot(X,Y1,Y2,data):\n  plt.figure(figsize=(15,10))\n  plt.subplot(1,2,1)\n  sns.violinplot(x=X,y=Y1,data=iris_data)\n  plt.title(Y1)\n  plt.subplot(1,2,2)\n  sns.violinplot(x=X,y=Y2,data=iris_data)\n  plt.title(Y2)\nViolinPlot(\"Species\",\"PetalLengthCm\",\"PetalWidthCm\",iris_data)\nViolinPlot(\"Species\",\"SepalLengthCm\",\"SepalWidthCm\",iris_data)\n\"\"\"\nSome Violin Plot is long, there might be outlier. <br>\nLet's check Box plot\n\"\"\"\nplt.figure(figsize=(15,10))\nplt.subplot(2,2,1)\nsns.boxplot(x='Species',y='PetalLengthCm',data=iris_data)\nplt.subplot(2,2,2)\nsns.boxplot(x='Species',y='PetalWidthCm',data=iris_data)\nplt.subplot(2,2,3)\nsns.boxplot(x='Species',y='SepalLengthCm',data=iris_data)\nplt.subplot(2,2,4)\nsns.boxplot(x='Species',y='SepalWidthCm',data=iris_data)\n\"\"\"\n> We can see some Outliers\n\"\"\"\n\"\"\"\n#### Label Encoding of Target Variable\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\niris_data['Species'] = le.fit_transform(iris_data['Species'])\niris_data['Species']\n\"\"\"\n### Predicting Optimal Values for K\n\"\"\"\n# As given problem is of classification problem, we can use K-Means Algorithm for finding the Optimal k value\n\nfrom sklearn.cluster import KMeans\n\nx = iris_data.iloc[:, [0, 1, 2, 3, 4]].values\nwcss = []\n\nfor i in range(1, 11):\n    kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\n    kmeans.fit(x)\n    wcss.append(kmeans.inertia_)\n\nplt.figure(figsize=(13,8))\nplt.plot(range(1, 11), wcss,marker='o')\nplt.title('The elbow method',size=15)\nplt.xlabel('Number of clusters',size=12)\nplt.ylabel('WCSS',size=12) #within cluster sum of squares\nplt.show()\n\n\"\"\"\n>From K= 1 to K= 2, there is large drop<br>\n>From K= 2 to K= 3, there is slight drop<br>\n> After K= 3, slop is almost constant\n\nHence, value of **`K=3`**  implies an Optimal Value of K-Clusters\n\"\"\"\n# Predicting the values using Kmeans Algorithm\nkmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\npredictions = kmeans.fit_predict(x)\n#Predicted Values\npredictions\n#centroids\nkmeans.cluster_centers_\n#visualising the predicted clusters on basic all 4 features\nFeatures = ['Sepal Length','Sepal Width','Petal Length','Petal Width']\nplt.figure(figsize=(18,14))\nfor i in range(1,5):\n    plt.subplot(2,2,i)\n    plt.scatter(x[predictions == 0,0], x[predictions == 0,i], s=50, c = '#c718f2', label = 'Iris-setosa' )\n    plt.scatter(x[predictions == 1,0], x[predictions == 1,i], s=50, c = '#2140ed', label = 'Iris-vergiscolor' )\n    plt.scatter(x[predictions == 2,0], x[predictions == 2,i], s=50, c = '#2cb510', label = 'Iris-virginica' )\n    #centroids of the clusters\n    plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,i], s = 120, c = 'red', label = 'Centroids')\n    plt.title(Features[i-1],size=16)\n    plt.xlabel('Id',size=12)\n    plt.ylabel(iris_data.columns[i],size=12)\n    plt.legend()\nplt.suptitle('Clusters w.r.t Features',fontsize=20)\n\"\"\"\n#### From above graphs and Elbow Curve, we can see at `K = 3`, we get Optimal Clusters. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '72b92c7880f94e'}"}
{"id":"122699","text":"\"\"\"\nIn this notebook we will be using a LSTM network to create a model to predict whether a news is fake or not.\n\nI have also solved the same problem using Tf-Idf you can refer to this link and have a look.\nhttps:\/\/github.com\/sid26ranjan\/fake-news-classifier\n\nMake sure you have enabled GPU in accelerator to speed up the training process and try various methods to achieve a different accuracy.\n\nI have tried to explain the things that i have used in the notebook.feedbacks and suggestions are most welcomed.\n\nPlease upvote if you find this notebook useful.\n\n\n\"\"\"\nimport pandas as pd\ndata=pd.read_csv('..\/input\/fake-news\/train.csv')\n\ndata.head()\n\n#we will be using the title column for our prediction\n#checking for null values in the dataset\n\ndata.isnull().sum()\ndata.shape\n#we will use the title column so other columns will be of no use\n\ndata=data.drop(['text','author','id'],axis=1)\n#there are some  null values in the title column also\n\ndata.isnull().sum()\n#as title is the only column is the what we are using if it contains NaN values we have to drop it.\n\ndata=data.dropna()\ndata.isnull().sum()\ndata.shape\ndata.head()\nX=data['title']\ny=data['label']\nX.shape\n#importing all necessary modules that we will be using to build our LSTM neural network\n\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.preprocessing.text import one_hot\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dense\n#we dropped some rows as there were nan values so reset index will make it uniform\n\nX=X.reset_index()\nX=X.drop(['index'],axis=1)\nX.tail()\n#as we dropped some rows so to make the dataframe in order\ny=y.reset_index()\ny=y.drop(['index'],axis=1)\ny.tail()\n# importing nltk,stopwords and porterstemmer we are using stemming on the text we have and stopwords will help in removing the stopwords in the text\n\n#re is regular expressions used for identifying only words in the text and ignoring anything else\nimport nltk\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\n\nps = PorterStemmer()\ncorpus = []\n#each row of the dataset is considered here.everything except the alphabets are removed ,stopwords are also being removed here .the text is converted in lowercase letters and stemming is performed\n#lemmatisation can also be used here at the end a corpus of sentences is created\nfor i in range(0, len(X)):\n    review = re.sub('[^a-zA-Z]', ' ',X['title'][i])\n    review = review.lower()\n    review = review.split()\n    \n    review = [ps.stem(word) for word in review if not word in stopwords.words('english')]\n    review = ' '.join(review)\n    corpus.append(review)\ncorpus[30]\n#vocabulary size\nvoc_size=5000\n#performing onr hot representation\n\nonehot_repr=[one_hot(words,voc_size)for words in corpus] \nlen(onehot_repr[0])\nlen(onehot_repr[700])\n#specifying a sentence length so that every sentence in the corpus will be of same length\n\nsent_length=25\n\n#using padding for creating equal length sentences\n\n\nembedded_docs=pad_sequences(onehot_repr,padding='pre',maxlen=sent_length)\nprint(embedded_docs)\n#Creating model\n\nfrom tensorflow.keras.layers import Dropout\nembedding_vector_features=40\nmodel=Sequential()\nmodel.add(Embedding(voc_size,embedding_vector_features,input_length=sent_length))\nmodel.add(Dropout(0.3))\nmodel.add(LSTM(200))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(1,activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\n\nimport numpy as np\nX_final=np.array(embedded_docs)\ny_final=np.array(y)\nX_final.shape,y_final.shape\n#splitting the data for training and testing the model\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_final, y_final, test_size=0.10, random_state=42)\nmodel.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=20,batch_size=64)\n#loading test dataset for prediction\n\ntest=pd.read_csv('..\/input\/fake-news\/test.csv')\ntest.head()\n#null values in the test dataset\n\ntest.isnull().sum()\n#using the title column only as we did in the train dataset\n\ntest=test.drop(['text','id','author'],axis=1)\ntest.head()\ntest.isnull().sum()\ntest.fillna('fake fake fake',inplace=True)\n\n#the solution file that can be submitted in kaggle expects it to have 5200 rows so we can't drop rows in the test dataset\ntest.shape\n#creating corpus for the test dataset exactly the same as we created for the training dataset\n\ncorpus_test = []\nfor i in range(0, len(test)):\n    review = re.sub('[^a-zA-Z]', ' ',test['title'][i])\n    review = review.lower()\n    review = review.split()\n    \n    review = [ps.stem(word) for word in review if not word in stopwords.words('english')]\n    review = ' '.join(review)\n    corpus_test.append(review)\n#creating one hot representation for the test corpus\n\nonehot_repr_test=[one_hot(words,voc_size)for words in corpus_test] \n#padding for the test dataset\nsent_length=25\n\nembedded_docs_test=pad_sequences(onehot_repr_test,padding='pre',maxlen=sent_length)\nprint(embedded_docs_test)\nX_test=np.array(embedded_docs_test)\n#making predictions for the test dataset\n\ncheck=model.predict_classes(X_test)\ncheck\ncheck.shape\ntest.shape\nsubmit_sample=pd.read_csv('..\/input\/fake-news\/submit.csv')\nsubmit_sample.head()\ntype(check)\ncheck[0]\nval=[]\nfor i in check:\n    val.append(i[0])\n#inserting our predicted values in the submission file\n\nsubmit_sample['label']=val\nsubmit_sample.head()\n#saving the submission file\n\nsubmit_sample.to_csv('submission.csv',index=False)\n\"\"\"\nif this notebook was helpful please upvote.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e19a2386bd8f56'}"}
{"id":"55460","text":"\"\"\"\n# Importing Libraries\n\"\"\"\nimport pandas as pd\nimport os\nimport plotly.express as px \nimport datetime as dt\n\nimport plotly.offline as offline\nimport plotly.graph_objs as go\n\noffline.init_notebook_mode()\n\nimport numpy as np\n\nimport matplotlib\n\"\"\"\n# Data shaping\n\"\"\"\n#Data acquisition\u3000and Merge\nfiles = os.listdir('..\/input\/among-us-dataset')\ndf = pd.concat([pd.read_csv('..\/input\/among-us-dataset\/' + f) for f in files ])\ndf = df.reset_index(drop=True)\n    \n#replace \u300c-\u300d\nfor column in [\"Task Completed\", \"Imposter Kills\"]:\n    df[column] .replace(\"-\", 0, inplace=True)\n    \ndf[\"Time to complete all tasks\"] .replace(\"-\", \"00m 00s\", inplace=True)\n    \n#replace int\nfor column in [\"Task Completed\", \"Imposter Kills\"]:\n    df[column] = df[column].astype(int)\n    \n#replace float\nfor column in [\"Game Length\",\"Time to complete all tasks\"]:\n    times = []\n    for time in df[column]:\n        td_time = dt.timedelta(minutes=int(time[:2]), seconds=int(time[4:6]))\n        times.append(td_time.total_seconds())\n    df[column] = times\n    \n#create new columns\ndf[\"kill_pace\"] = df[\"Game Length\"]\/df[\"Imposter Kills\"]  \ndf[\"task_time\"] = [df[\"Game Length\"][i] if df[\"Time to complete all tasks\"][i] == 0 else df[\"Time to complete all tasks\"][i] for i in range(len(df))]\ndf[\"task_pace\"] = df[\"task_time\"]\/df[\"Task Completed\"] \ndf[\"sabo_pace\"] = df[\"Game Length\"]\/df[\"Sabotages Fixed\"] \ndf[\"sabo_pace\"].replace(float(\"inf\"), 0, inplace=True)\n\n#split data\ndf_crew = df[df['Team'] == 'Crewmate']\ndf_imp = df[df['Team'] == 'Imposter']\ndf_imp_win = df[(df[\"Team\"]==\"Imposter\") & (df[\"Outcome\"]==\"Win\")].sample(n=200)\ndf_imp_loss = df[(df[\"Team\"]==\"Imposter\") & (df[\"Outcome\"]==\"Loss\")].sample(n=200)\ndf_crew_win = df[(df[\"Team\"]==\"Crewmate\") & (df[\"Outcome\"]==\"Win\")].sample(n=780)\ndf_crew_loss = df[(df[\"Team\"]==\"Crewmate\") & (df[\"Outcome\"]==\"Loss\")].sample(n=780)\n\n\ndf.head()\n\"\"\"\n# Make histgram (definition)\n\"\"\"\ndef make_histogram(win_data, loss_data, title_, xtitle, ytitle):\n    trace1 = go.Histogram(\n            x = win_data,\n            name = \"Imposter_win\",\n            marker = dict(color='#33D7E9'), #FFD7E9\n            opacity = 0.75\n    )\n    trace2 = go.Histogram(\n            x = loss_data,\n            name = \"Imposter_loss\",\n            marker = dict(color='#EB89B5'),\n            opacity = 0.75\n    )\n\n    layout = go.Layout(\n        title = title_,\n        xaxis = dict(title=xtitle),\n        yaxis = dict(title=ytitle),\n    )\n\n    fig = dict(data=[trace1, trace2], layout=layout)\n\n    return offline.iplot(fig)\n\"\"\"\n# Optimal Game Length to win\n\"\"\"\ndf_imp_win_len = pd.concat([df_imp_win[\"Game Length\"],df_crew_loss[\"Game Length\"]],axis=0)\ndf_imp_loss_len = pd.concat([df_imp_loss[\"Game Length\"], df_crew_win[\"Game Length\"]],axis=0)\nmake_histogram(df_imp_win_len, df_imp_loss_len, \"Inposter Game Length\", \"time(second)\", \"battle count\")\n\"\"\"\nInposters tend to lose beyond 15 minutes.\n\"\"\"\n\"\"\"\n# Optimal kill pace to win\n\"\"\"\nmake_histogram(df_imp_win[\"kill_pace\"], df_imp_loss[\"kill_pace\"], \"Inposter Kill Time\", \"time(second)\", \"battle count\")\n\"\"\"\nIf imposters don't kill at least once every 5 minutes, imposters are more likely to lose.\n\"\"\"\n\"\"\"\n# Task pace to win\n\"\"\"\nmake_histogram(df_crew_loss[\"task_pace\"], df_crew_win[\"task_pace\"], \"Crewmate Task Pace\", \"time(second)\", \"battle count\")\n\"\"\"\nThe pace of completing tasks has little to do with winning or losing.\n\"\"\"\n\"\"\"\n# Sabotage Pace to win\n\"\"\"\nsabo_pace_win = df_crew_loss[df_crew_loss[\"sabo_pace\"] != 0][\"sabo_pace\"]\nsabo_pace_loss = df_crew_win[df_crew_win[\"sabo_pace\"] != 0][\"sabo_pace\"]\nmake_histogram(sabo_pace_win, sabo_pace_loss, \"Crewmate Sabotages Fixed Pace\", \"time(second)\", \"battle count\")\n\"\"\"\nIf imposters do not sabotage at a pace of more than the number of people in 15 minutes, imposters are more likely to lose.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6636d7e248da79'}"}
{"id":"12576","text":"\"\"\"\n## **1. Principal Component Analysis**\n\"\"\"\n\"\"\"\n### **Make sample data**\n<br>\n\n**make_blobs parameter(default)**\n- n_features(20): number of independent variables\n- n_samples(100): number of total sample data\n- centers(3): number of cluster\n- cluster_std(1.0): cluster standard deviation\n- center_box(-10.0, 10.0): bounding box of cluster\n- shuffle(True): whether to shuffle numbers\n\"\"\"\nfrom sklearn.datasets import make_blobs\n\nX1, Y1 = make_blobs(n_features = 4,\n                    n_samples = 100,\n                    centers = 4,\n                    random_state = 4,\n                    cluster_std = 2)\n\"\"\"\n### **Check result**\n\n- X1: total sample data\n- Y1: allocated cluster per data\n\"\"\"\nprint(X1[:5])\nprint(Y1[:5])\n\"\"\"\n### **Declare & Apply PCA**\n\"\"\"\nfrom sklearn import decomposition\nimport pandas as pd\n\n# class declaration for PCA\npca = decomposition.PCA(n_components = 4, # number of PC\n                        random_state = 4) # SEED\n\n# transformation X1 data\n# fit_transform > data will be transformated based on X1\npc = pca.fit_transform(X1)\n\npc_df = pd.DataFrame(data = pc,\n                     columns = ['PC1', 'PC2', 'PC3', 'PC4'])\n\n# check result\npc_df['Cluster'] = Y1\npc_df.head()\n\"\"\"\n### **Scree plot(Visualization)**\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\ndef scree_plot(pca):\n    # explained_variance_ratio_: percentage of variance by PC factor\n    num_components = len(pca.explained_variance_ratio_)\n    ind = np.arange(num_components)\n    vals = pca.explained_variance_ratio_\n    \n    ax = plt.subplot()\n    # np.cumsum: calculate the cumulative sum of elements\n    cumvals = np.cumsum(vals)\n    # bar plot\n    ax.bar(ind, vals, color = ['#00da75', '#f1c40f',  '#ff6f15', '#3498db'])\n    # line plot\n    ax.plot(ind, cumvals, color = '#c0392b')\n    \n    for i in range(num_components):\n        # annotate at screeplot\n        ax.annotate(r\"%s\" % ((str(vals[i]*100)[:3])),\n                    (ind[i], vals[i]),\n                    va = \"bottom\",\n                    ha = \"center\",\n                    fontsize = 13)\n     \n    ax.set_xlabel(\"PC\")\n    ax.set_ylabel(\"Variance\")\n    plt.title('Scree plot')\n\nscree_plot(pca)\n\"\"\"\n## **2. K-Means Clustering**\n\"\"\"\n\"\"\"\n### **Make sample data**\n\"\"\"\nx, y = make_blobs(n_samples = 100,\n                  centers = 3,\n                  n_features = 2,\n                  random_state = 42)\n\ndf = pd.DataFrame(dict(x = x[:, 0],\n                       y = x[:, 1],\n                       label = y))\n\npoints = df.drop('label',\n                 axis = 1)\npoints.head()\n\"\"\"\n### **Assign data**\n\"\"\"\nfrom sklearn.cluster import KMeans\n\n# class declaration for K-means\nkmeans = KMeans(n_clusters = 3, # number of centroid(= cluster)\n                random_state = 42) # SEED\n\n# assign data to each cluster\nkmeans.fit(x)\nlabels = kmeans.labels_\n\n# enter new cluster at dataframe\nnew_series = pd.Series(labels)\ndf['clusters'] = new_series.values\ndf.head(15)\n\"\"\"\n### **Calculate centroid**\n\"\"\"\ndef get_centroids(df, column_header):\n    new_centroids = df.groupby(column_header).mean()\n    return new_centroids\n\n# calculate centroid\ncentroids = get_centroids(df, 'clusters')\n\n# check result\ndf.groupby('clusters').mean()\n\"\"\"\n### **Result visualization**\n\"\"\"\ndef plot_clusters(df, column_header, centroids):\n    colors = {0 : 'red', 1 : 'cyan', 2 : 'yellow'}\n    fig, ax = plt.subplots()\n\n    # centroid\n    ax.plot(centroids.iloc[0].x, centroids.iloc[0].y, \"ok\") \n    ax.plot(centroids.iloc[1].x, centroids.iloc[1].y, \"ok\")\n    ax.plot(centroids.iloc[2].x, centroids.iloc[2].y, \"ok\")\n\n    # all data\n    grouped = df.groupby(column_header)\n\n    for key, group in grouped:\n        group.plot(ax = ax,\n                 kind = 'scatter',\n                 x = 'x',\n                 y = 'y',\n                 label = key,\n                 color = colors[key])\n    plt.show()\n\nplot_clusters(df, 'clusters', centroids)\n# elbow methods\nsum_of_squared_distances = []\nK = range(1, 15)\n\nfor k in K:\n    km = KMeans(n_clusters = k)\n    km = km.fit(points)\n    # inertia_: the degree to which the data included in the group is spread\n    sum_of_squared_distances.append(km.inertia_)\n\nplt.plot(K, sum_of_squared_distances, 'bx-')\nplt.xlabel('k')\nplt.ylabel('Sum of squared distances')\nplt.title('Elbow Method For Optimal k')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '17039777f3db34'}"}
{"id":"70944","text":"# 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\n#data load and look up\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('\/kaggle\/input\/insurance\/insurance.csv')\ndata.head()\ndata.describe()\ndata.info()\ndata.isnull().sum() #there is no missing data()\n\"\"\"\nI like to see correlation of features. \n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ncorrelation = data.corr()\nplt.figure()\nsns.heatmap(correlation, annot = True)\n\"\"\"\nthere is no clear relationship between numerical features. Let's include categorical features in the game!\n\"\"\"\ndata_categ = data.select_dtypes(include=object)\ndata_categ.head()\n#converting categorical data\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\nfor col in data_categ.head():\n    data[col]=le.fit_transform(data_categ[col])\ndata.head()\ndata.info()\n\"\"\"\n# Linaer Regression\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nX = data.iloc[:,:-1].values\ny = data.iloc[:,-1].values\n\nx_train, x_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state = 42)\nlinReg=LinearRegression()\nlinReg.fit(x_train,y_train)\nfrom sklearn.metrics import r2_score\n\ny_pred=linReg.predict(x_test)\nprint(r2_score(y_test,y_pred))\n\"\"\"\nr2score not bad. Let's see other methods\n\"\"\"\nfrom sklearn.preprocessing import PolynomialFeatures\n\npoly = PolynomialFeatures(degree=2)\nx_poly = poly.fit_transform(X)\n\nx_train1, x_test1, y_train1, y_test1 = train_test_split(x_poly,y, test_size=0.2, random_state = 42)\npolyLR = linReg.fit(x_train1,y_train1)\n\ny_pred1 = polyLR.predict(x_test1)\nprint(r2_score(y_test1,y_pred))\nprint(polyLR.score(x_test1,y_test))\n\"\"\"\nNow we have obtained better score. As you see above, you can use both method. r2 score and score is the same****\n\"\"\"\n\"\"\"\n# Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\ntree_reg = DecisionTreeRegressor()\ntree_reg.fit(x_train,y_train)\n\nprint(tree_reg.score(x_test,y_test))\n\"\"\"\n**Random Forest**\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nrf_reg = RandomForestRegressor()\nrf_reg.fit(x_train,y_train)\n\nprint(rf_reg.score(x_test,y_test))","meta":"{'source': 'AI4Code', 'id': '827fb2675ee2de'}"}
{"id":"39110","text":"\"\"\"\n# Introduction:\n\nThis notebook is a response to the dataset task 'Business Analysis with EDA & Statistics'. The task details is as follows:\n\n> You're a marketing analyst and you've been told by the Chief Marketing Officer that recent marketing campaigns have not been as effective as they were expected to be. You need to analyze the data set to understand this problem and propose data-driven solutions.\n\nThis notebook will contain the following sections:\n* Section 01: Exploratory Data Analysis\n\n* Section 02: Statistical Analysis\n\n* Section 03: Data Visualization\n\n* Section 04: CMO Recommendations\n\n\"\"\"\n# 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)\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime, timedelta, date\nimport statsmodels.formula.api as smf \nimport scipy\nfrom scipy import stats\nfrom sklearn.datasets import make_classification\nfrom sklearn.ensemble import RandomForestClassifier\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\nmkt = pd.read_csv(\"\/kaggle\/input\/marketing-data\/marketing_data.csv\")\n\"\"\"\n# Section 01: Exploratory Data Analysis\n\nIn this section, we will answer the following questions:\n1. Are there any null values or outliers? How will you wrangle\/handle them?\n2. Are there any variables that warrant transformations?\n3. Are there any useful variables that you can engineer with the given data?\n4. Do you notice any patterns or anomalies in the data? Can you plot them?\n\"\"\"\n\"\"\"\n**1. Are there any null values or outliers? How will you wrangle\/handle them?**\n\nWe start by checking for missing data in the dataset\n\"\"\"\nmkt.isna().sum()\n\"\"\"\nThere are 24 customers that are missing 'Income' data, and none of the other columns contain any missing data.\n\nWe will plot all the variables for visualization before performing any data wrangling on missing data & outliers, to ensure a hollistic approach.\n\"\"\"\n\"\"\"\nBefore that, we will have to perform some transformations on the variables \"Income\" and \"Dt_Customer\". The main reason being that the syntax of the data contained are not suitable for statistical analysis (currency formatting & date formatting). The following transformations will be done:\n1. Income: We rename the column to remove leading & trailing spaces. We will also reformat the data values to remove dollar sign and commas\n2. Dt_Customer: We convert the values to represent 'days since joining' by subtracting the date joined from today's date.\n\"\"\"\n# Income\nmkt = mkt.rename(columns={' Income ':'Income'})\nmkt['Income'] = mkt['Income'].replace({'\\$': '', ',': ''}, regex=True)\nmkt['Income'] = pd.to_numeric(mkt['Income'])\n\n# Dt_Customer\ntoday = datetime.now()\nmkt['Dt_Customer']= pd.to_datetime(mkt['Dt_Customer'])\nmkt['Dt_Customer'] = (today - mkt['Dt_Customer']).dt.days\n\"\"\"\nThen, we will plot each variable to visualize the distribution of the data and identify any outliers or imbalanced classes.\n\nWe will plot boxplots for quantitative variables and barplots (of value counts) for qualitative, categorical and binary (yes\/no) variables\n\"\"\"\nf, axs = plt.subplots(7,4,figsize=(15,30))\nmkt['Year_Birth'].plot(kind='box', ax=axs[0,0])\naxs[0,0].title.set_text('Year_Birth')\nmkt['Education'].value_counts().plot(kind='bar',ax=axs[0,1])\naxs[0,1].title.set_text('Education')\nmkt['Marital_Status'].value_counts().plot(kind='bar',ax=axs[0,2])\naxs[0,2].title.set_text('Marital_Status')\nmkt['Income'].plot(kind='box', ax=axs[0,3])\naxs[0,3].title.set_text('Income')\nmkt['Kidhome'].value_counts().plot(kind='bar',ax=axs[1,0])\naxs[1,0].title.set_text('Kidhome')\nmkt['Teenhome'].value_counts().plot(kind='bar',ax=axs[1,1])\naxs[1,1].title.set_text('Teenhome')\nmkt['Dt_Customer'].plot(kind='box', ax=axs[1,2])\naxs[1,2].title.set_text('Dt_Customer')\nmkt['Recency'].plot(kind='box', ax=axs[1,3])\naxs[1,3].title.set_text('Recency')\nmkt['MntWines'].plot(kind='box', ax=axs[2,0])\naxs[2,0].title.set_text('MntWines')\nmkt['MntFruits'].plot(kind='box', ax=axs[2,1])\naxs[2,1].title.set_text('MntFruits')\nmkt['MntMeatProducts'].plot(kind='box', ax=axs[2,2])\naxs[2,2].title.set_text('MntMeatProducts')\nmkt['MntFishProducts'].plot(kind='box', ax=axs[2,3])\naxs[2,3].title.set_text('MntFishProducts')\nmkt['MntSweetProducts'].plot(kind='box', ax=axs[3,0])\naxs[3,0].title.set_text('MntSweetProducts')\nmkt['MntGoldProds'].plot(kind='box', ax=axs[3,1])\naxs[3,1].title.set_text('MntGoldProds')\nmkt['NumDealsPurchases'].plot(kind='box', ax=axs[3,2])\naxs[3,2].title.set_text('NumDealsPurchases')\nmkt['NumWebPurchases'].plot(kind='box', ax=axs[3,3])\naxs[3,3].title.set_text('NumWebPurchases')\nmkt['NumCatalogPurchases'].plot(kind='box', ax=axs[4,0])\naxs[4,0].title.set_text('NumCatalogPurchases')\nmkt['NumStorePurchases'].plot(kind='box', ax=axs[4,1])\naxs[4,1].title.set_text('NumStorePurchases')\nmkt['NumWebVisitsMonth'].plot(kind='box', ax=axs[4,2])\naxs[4,2].title.set_text('NumWebVisitsMonth')\nmkt['AcceptedCmp3'].value_counts().plot(kind='bar',ax=axs[4,3])\naxs[4,3].title.set_text('AcceptedCmp3')\nmkt['AcceptedCmp4'].value_counts().plot(kind='bar',ax=axs[5,0])\naxs[5,0].title.set_text('AcceptedCmp4')\nmkt['AcceptedCmp5'].value_counts().plot(kind='bar',ax=axs[5,1])\naxs[5,1].title.set_text('AcceptedCmp5')\nmkt['AcceptedCmp1'].value_counts().plot(kind='bar',ax=axs[5,2])\naxs[5,2].title.set_text('AcceptedCmp1')\nmkt['AcceptedCmp2'].value_counts().plot(kind='bar',ax=axs[5,3])\naxs[5,3].title.set_text('AcceptedCmp2')\nmkt['Response'].value_counts().plot(kind='bar',ax=axs[6,0])\naxs[6,0].title.set_text('Response')\nmkt['Complain'].value_counts().plot(kind='bar',ax=axs[6,1])\naxs[6,1].title.set_text('Complain')\nmkt['Country'].value_counts().plot(kind='bar',ax=axs[6,2])\naxs[6,2].title.set_text('Country')\n\nf.delaxes(axs[6][3])\nf.tight_layout()\nplt.show()\n\"\"\"\nFrom the variable plots, we identify the following regarding the variables:\n* Year_Birth: Some significant outliers are present on the lower spectrum. These datapoints are likely false as these people would be well over 100 years old\n* Marital_Status: There are 3 categories 'Alone', 'YOLO' and 'Absurd'\u00a0which are not valid marital statuses, with very low number of customers in each\n* Income: There are some significant outliers on the upper bound, with one outlier > 600,000\n* Kidhome & Teenhome: The number of customers with 2 kid \/ teenager at home is very low, causing the classes to be very imbalanced. It may make more sense to convert the variables into binary variables indicating presence or absence of kid \/ teen\n* Amount Spent on Categories: The outliers for these categories are all acceptable & valid values of purchases, and shall be kept as is\n* Number of Touchpoint Visits: The outliers for these categories are all acceptable & valid values, and shall be kept as is\n* Campaign Responses: It can be observed that campaigns 1, 3, 4 and 5 performed similarly, whereas campaign 2 performed poorly. The latest campaign (under variable 'Response') had the best performance\n* Complain: Very few customers have filed any complaints\n* Country: Most of the customers are from Spain, and there is a very small group of customers from Mexico\n\"\"\"\n\"\"\"\nWith this information, we can handle the missing data discovered above.\n\nSince there is also a far outlier for 'Income' of > 600,000, we will impute the missing data as well as this outlier with the median value of 'Income', which is not affected by outliers in the dataset\n\"\"\"\nmkt.loc[mkt.Income.isna(),'Income'] = mkt.Income.median()\nmkt.loc[mkt.Income > 600000,'Income'] = mkt.Income.median()\n\"\"\"\nNext, we will handle the outliers discussed in the previous section by either rectifying, removing or retaining them. We will handle the following outliers:\n\n* Year_Birth: Significant outliers on the lower spectrum to be imputed with mean (calculated excluding these values)\n* Marital_Status: Customer data in the 3 categories 'Alone', 'YOLO' and 'Absurd' to be removed\n* Kidhome & Teenhome: New features to be created, converting these variables into binary variables\n\n\"\"\"\n# Marital_Status\nmkt = mkt[~mkt.Marital_Status.isin(['Alone','YOLO','Absurd'])]\n\n# Year_Birth\nmkt.loc[mkt.Year_Birth < 1920,'Year_Birth'] = round(mkt[mkt.Year_Birth > 1920].Year_Birth.mean())\n\n# Kidhome\nmkt['HasKid'] = np.where(mkt['Kidhome'] > 0, 1, 0)\n\n# Teenhome\nmkt['HasTeen'] = np.where(mkt['Teenhome'] > 0, 1, 0)\n\"\"\"\nWe will plot the variables against to visualize the changes that have been made. We will also plot the 2 new variables 'HasKid' and 'HasTeen'\n\"\"\"\nf, axs = plt.subplots(8,4,figsize=(15,30))\nmkt['Year_Birth'].plot(kind='box', ax=axs[0,0])\naxs[0,0].title.set_text('Year_Birth')\nmkt['Education'].value_counts().plot(kind='bar',ax=axs[0,1])\naxs[0,1].title.set_text('Education')\nmkt['Marital_Status'].value_counts().plot(kind='bar',ax=axs[0,2])\naxs[0,2].title.set_text('Marital_Status')\nmkt['Income'].plot(kind='box', ax=axs[0,3])\naxs[0,3].title.set_text('Income')\nmkt['Kidhome'].value_counts().plot(kind='bar',ax=axs[1,0])\naxs[1,0].title.set_text('Kidhome')\nmkt['Teenhome'].value_counts().plot(kind='bar',ax=axs[1,1])\naxs[1,1].title.set_text('Teenhome')\nmkt['Dt_Customer'].plot(kind='box', ax=axs[1,2])\naxs[1,2].title.set_text('Dt_Customer')\nmkt['Recency'].plot(kind='box', ax=axs[1,3])\naxs[1,3].title.set_text('Recency')\nmkt['MntWines'].plot(kind='box', ax=axs[2,0])\naxs[2,0].title.set_text('MntWines')\nmkt['MntFruits'].plot(kind='box', ax=axs[2,1])\naxs[2,1].title.set_text('MntFruits')\nmkt['MntMeatProducts'].plot(kind='box', ax=axs[2,2])\naxs[2,2].title.set_text('MntMeatProducts')\nmkt['MntFishProducts'].plot(kind='box', ax=axs[2,3])\naxs[2,3].title.set_text('MntFishProducts')\nmkt['MntSweetProducts'].plot(kind='box', ax=axs[3,0])\naxs[3,0].title.set_text('MntSweetProducts')\nmkt['MntGoldProds'].plot(kind='box', ax=axs[3,1])\naxs[3,1].title.set_text('MntGoldProds')\nmkt['NumDealsPurchases'].plot(kind='box', ax=axs[3,2])\naxs[3,2].title.set_text('NumDealsPurchases')\nmkt['NumWebPurchases'].plot(kind='box', ax=axs[3,3])\naxs[3,3].title.set_text('NumWebPurchases')\nmkt['NumCatalogPurchases'].plot(kind='box', ax=axs[4,0])\naxs[4,0].title.set_text('NumCatalogPurchases')\nmkt['NumStorePurchases'].plot(kind='box', ax=axs[4,1])\naxs[4,1].title.set_text('NumStorePurchases')\nmkt['NumWebVisitsMonth'].plot(kind='box', ax=axs[4,2])\naxs[4,2].title.set_text('NumWebVisitsMonth')\nmkt['AcceptedCmp3'].value_counts().plot(kind='bar',ax=axs[4,3])\naxs[4,3].title.set_text('AcceptedCmp3')\nmkt['AcceptedCmp4'].value_counts().plot(kind='bar',ax=axs[5,0])\naxs[5,0].title.set_text('AcceptedCmp4')\nmkt['AcceptedCmp5'].value_counts().plot(kind='bar',ax=axs[5,1])\naxs[5,1].title.set_text('AcceptedCmp5')\nmkt['AcceptedCmp1'].value_counts().plot(kind='bar',ax=axs[5,2])\naxs[5,2].title.set_text('AcceptedCmp1')\nmkt['AcceptedCmp2'].value_counts().plot(kind='bar',ax=axs[5,3])\naxs[5,3].title.set_text('AcceptedCmp2')\nmkt['Response'].value_counts().plot(kind='bar',ax=axs[6,0])\naxs[6,0].title.set_text('Response')\nmkt['Complain'].value_counts().plot(kind='bar',ax=axs[6,1])\naxs[6,1].title.set_text('Complain')\nmkt['Country'].value_counts().plot(kind='bar',ax=axs[6,2])\naxs[6,2].title.set_text('Country')\nmkt['HasKid'].value_counts().plot(kind='bar',ax=axs[6,3])\naxs[6,3].title.set_text('HasKid')\nmkt['HasTeen'].value_counts().plot(kind='bar',ax=axs[7,0])\naxs[7,0].title.set_text('HasTeen')\n\nf.delaxes(axs[7][1])\nf.delaxes(axs[7][2])\nf.delaxes(axs[7][3])\nf.tight_layout()\nplt.show()\n\"\"\"\nFrom this, it can be seen that we have successfully removed extreme outliers, and some sparse classes mentioned above\n\"\"\"\n\"\"\"\n**2. Are there any variables that warrant transformations?**\n\nTransformations have already been done above for columns 'Dt_Customer' and 'Income' to ensure they are useable for statistical analysis. The following transformations will be done:\n\n* Income: Column renamed to remove leading & trailing spaces. We also reformatted the data values to remove dollar sign and commas\n* Dt_Customer: Values converted to represent 'days since joining' by subtracting the date joined from today's date.\n\"\"\"\n\"\"\"\n**3. Are there any useful variables that you can engineer with the given data?**\n\nIn the previous section, we have already engineered new features 'HasKid' and 'HasTeen'\n\nAdditionally , we will perform the following feature engineering steps to prepare the data for statistical analysis:\n1. Creating dummy variables for each qualitative variables so that they can be used in performing statistical modelling.\n2. Perform min-max scaling on all quantitative variables to standardize them\n\nThe standardized variables will be stored in a separate variable, so that the initial variable values are still easily accessible\n\"\"\"\nmkt_dummy = pd.get_dummies(mkt, columns=['Education', 'Marital_Status', 'Kidhome', 'Teenhome', \n                'Country'], drop_first=True, prefix=['Education', 'Marital_Status', \n                'Kidhome', 'Teenhome', 'Country'], prefix_sep='_')\n\"\"\"\nWe then perform scaling of variables, and storing the values in a new dataframe 'mkt_scale'\n\"\"\"\ndef norm_func(i):\n    x = (i-i.min())\t\/ (i.max()-i.min())\n    return (x)\n\nmkt_scale = norm_func(mkt_dummy.iloc[:,:]) \n\"\"\"\n**4. Do you notice any patterns or anomalies in the data? Can you plot them?**\n\nThere are some anomalies in the data that have been pointed out in while handling outliers, including:\n* Year_Birth: Some significant outliers are present on the lower spectrum. These datapoints are likely false as these people would be well over 100 years old\n* Marital_Status: There are 3 categories 'Alone', 'YOLO' and 'Absurd' which are not valid marital statuses, with very low number of customers in each\n* Country: There are only 3 entries for customers from Mexico, and this may skew results related to this variable\n\nThe plots have already been included in the outlier analysis section, and will not be presented again here\n\n\"\"\"\n\"\"\"\n# Section 02: Statistical Analysis\n\nIn this section, we perform statistical analysis to answer the following questions. For each question, we will provide a brief explanation of the findings, suitable for non-technical users:\n\n1. What factors are significantly related to the number of store purchases?\n2. Does US fare significantly better than the Rest of the World in terms of total purchases?\n3. Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above average amount on gold in the last 2 years would have more in store purchases. Justify or refute this statement using an appropriate statistical test\n4. Fish has Omega 3 fatty acids which are good for the brain. Accordingly, do \"Married PhD candidates\" have a significant relation with amount spent on fish? What other factors are significantly related to amount spent on fish? (Hint: use your knowledge of interaction variables\/effects)\n5. Is there a significant relationship between geographical regional and success of a campaign?\n\"\"\"\n\"\"\"\n**1. What factors are significantly related to the number of store purchases?**\n\nFor this, we will build a multiple linear regression model to predict the number of store purchases. Based on the coefficients of the model, we will be able to plot & determine the most significant factors (positive and negative) related to the number of store purchases.\n\"\"\"\nml1 = smf.ols('NumStorePurchases ~ Year_Birth+Income+Dt_Customer+Recency+MntWines+MntFruits+MntMeatProducts+\\\n              MntFishProducts+MntSweetProducts+MntGoldProds+NumDealsPurchases+NumWebPurchases+NumCatalogPurchases\\\n              +NumWebVisitsMonth+AcceptedCmp3+AcceptedCmp4+AcceptedCmp5+AcceptedCmp1+AcceptedCmp2+Response+\\\n              Complain+Education_Basic+Education_Graduation+Education_Master+Education_PhD+\\\n              Marital_Status_Married+Marital_Status_Single+Marital_Status_Together+Marital_Status_Widow+\\\n              Kidhome_1+Kidhome_2+Teenhome_1+Teenhome_2+Country_CA+Country_GER+Country_IND+Country_ME+Country_SA\\\n              +Country_SP+Country_US', data=mkt_scale).fit()\n\nml1.summary()\n\"\"\"\nWe will plot the parameter coefficients to visualize the effect of each parameter on the variable 'NumStorePurchases'\n\"\"\"\nparams = ml1.params.sort_values(ascending=False)\nplt.figure(figsize=(15, 4)) \nplt.bar(params.index, params)\nplt.xticks(rotation=90)\nplt.title('Variable Scores')\nplt.xlabel('Variable')\nplt.ylabel('Coefficient')\nplt.show()\n\"\"\"\nWe will arbitrarily use -0.1 and 0.1 as the cutoff for coefficients, in order to narrow down the important factors\n\"\"\"\nparam_narrow = params[params>0.1].append(params[params<-0.1])\nparam_narrow=param_narrow[~(param_narrow.index=='Intercept')]\nplt.figure(figsize=(8, 4)) \nplt.bar(param_narrow.index, param_narrow)\nplt.xticks(rotation=90)\nplt.title('Variable Scores')\nplt.xlabel('Variable')\nplt.ylabel('Coefficient')\nplt.show()\n\"\"\"\nFrom the chart, we conclude that the 7 factors above are most significantly related to number of store purchases. Among the 7 factors, \n* Positive Effect: 'MntWines', 'NumWebPurchases', 'NumDealsPurchases', 'Income' and 'MntFruits' have a positive effect on the number of store purchases in decreasing order. This means that as the values of these variables increase, the number of store purchases also increases, with 'MntWines' having the largest effect on number of store purchases\n* Negative Effect: On the other hand, 'NumCatalogPurchases' and 'NumWebVisitsMonth' have a negative effect on the number of store purchases in decreasing order. This means that as the values of these variables increase, the number of store purchases decreases, with 'NumWebVisitsMonth' having the largest negative effect on number of store purchases\n\nOverall, it can be inferred that the selection of wines and fruits, as well as the attractive deals attract customers to make store purchases. Besides that, customers with higher income also tend to make more store purchases.\n\nOn the other hand, customers who tend to make catalog purchases are less likely to make purchases in the store.\n\nHowever, there are 2 contrasting factors, 'NumWebPurchases' and 'NumWebVisitsMonth' which are both website related but have opposing effects on the number of store purchases. This is a factor that should be further studied by the CMO and marketing team, and it is worth noting that 'NumWebVisitsMonth' only captures the past month's data, whereas 'NumWebPurchases' and 'NumStorePurchases' both seemingly capture the lifetime data of the customer. \n\nThus, it can be hypothesized that the store has been promoting their website on advertisements \/ social media lately, driving customers to switch from regular store purchases to website purchase, whereas customers who historically make many purchases on the website are loyal customers of the store, and tend to make in store purchases as well.\n\"\"\"\n\"\"\"\n**2. Does US fare significantly better than the Rest of the World in terms of total purchases?**\n\nFor this, we will tabulate the total purchases of each country. Then, we will visualize this information for US as compared to the rest of the world.\n\nIf necessary, we will perform hypothesis testing to determine if it is statistically significant that US fares better than the rest of the world in terms of total purchases\n\"\"\"\ntotal_purchase = mkt.loc[:,['NumDealsPurchases','NumWebPurchases','NumCatalogPurchases','NumStorePurchases','Country']]\ntotal_purchase = total_purchase.groupby('Country').sum().sum(axis=1)\n\ntotal_purchase = total_purchase.sort_values(ascending=False)\nplt.figure(figsize=(8, 4)) \nplt.bar(total_purchase.index, total_purchase)\nplt.bar('US',total_purchase['US'])\nplt.xticks(rotation=90)\nplt.title('Total Purchases Across Countries')\nplt.xlabel('Country')\nplt.ylabel('Total Purchases')\nplt.show()\n\"\"\"\nFrom this, we can clearly see that the US is second to last in terms of total purchases, only ahead of Mexico. Thus. US definitely does not fare better than the rest of the world in terms of total purchases.\n\nLet's take a look if the US fares better in terms of average purchases per customer\n\"\"\"\nnumber_cust = mkt.loc[:,['Country']]\nnumber_cust = number_cust.value_counts()\n\nave_purchase = (total_purchase \/ number_cust.to_numpy()).sort_values(ascending=False)\n\nplt.figure(figsize=(8, 4)) \nplt.bar(ave_purchase.index, ave_purchase)\nplt.bar('US',ave_purchase['US'])\nplt.xticks(rotation=90)\nplt.title('Average Purchases Across Countries')\nplt.xlabel('Country')\nplt.ylabel('Average Purchases')\nplt.show()\n\n\"\"\"\nFrom this, we can also see that the US does not fare better than the rest of the world, being significantly behind Mexico in terms of average purchases per customer, and very close to all the other countries\n\nLet's take a look if the US fares better in terms of total purchases amounts. For this, we will total the values in the 6 columns 'MntWines, MntFruits, MntMeatProducts, MntFishProducts, MntSweetProducts and MntGoldProds\n\"\"\"\ntotal_value = mkt.loc[:,['MntWines','MntFruits','MntMeatProducts','MntFishProducts','MntSweetProducts','MntGoldProds','Country']]\ntotal_value = total_value.groupby('Country').sum().sum(axis=1)\ntotal_value = total_value.sort_values(ascending=False)\n\nplt.figure(figsize=(8, 4)) \nplt.bar(total_value.index, total_value)\nplt.bar('US',total_value['US'])\nplt.xticks(rotation=90)\nplt.title('Total Purchase Value Across Countries')\nplt.xlabel('Country')\nplt.ylabel('Total Purchase Value')\nplt.show()\n\"\"\"\nSimilar to total purchases, US is also second to last in terms of total purchase value, only ahead of Mexico. Thus. US definitely does not fare better than the rest of the world in terms of total purchase value.\n\nLet's take a look if the US fares better in terms of average purchase value per customer\n\"\"\"\nave_value = (total_value \/ number_cust.to_numpy()).sort_values(ascending=False)\n\nplt.figure(figsize=(8, 4)) \nplt.bar(ave_value.index, ave_value)\nplt.bar('US',ave_value['US'])\nplt.xticks(rotation=90)\nplt.title('Average Purchase Value Across Countries')\nplt.xlabel('Country')\nplt.ylabel('Average Purchase Value')\nplt.show()\n\"\"\"\nAgain, we see that the US does not fare better than the rest of the world, being significantly behind Mexico in terms of average purchase value per customer, and very close to all the other countries\n\nThus, we can conclude with certainty that US does not fare better than the rest of the world in terms of total purchases.\n\"\"\"\n\"\"\"\n**3. Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above average amount on gold in the last 2 years would have more in store purchases. Justify or refute this statement using an appropriate statistical test**\n\nFor this, we will first tabulate the data (number of in store purchases) for 2 populations, those with above average spend on gold, and those with average or lower spending on gold.\n\nThen, we will perform a T test for population means to determine if there is statistical evidence to support the claim that people who spend above average amount on gold also has more in store purchases\n\n\n\"\"\"\n\"\"\"\nWe first set up the hypothesis test:\n\nHo: Store purchases of people who spend more on gold <= Store purchases of people who spend less on gold \n\nHa: Store purchases of people who spend more on gold > Store purchases of people who spend less on gold\n\nNext, we check if the 2 samples have equal variances\n\"\"\"\ngold_purchase = mkt.loc[:,['MntGoldProds','NumStorePurchases']]\ngold_purchase['AboveAvg'] = np.where(gold_purchase['MntGoldProds'] > gold_purchase['MntGoldProds'].mean(),'Above','Below')\n\n# Preparing data for gold buyers & non gold buyers\ngold_buyers = gold_purchase[gold_purchase.AboveAvg=='Above'].loc[:,'NumStorePurchases']\nnon_buyers = gold_purchase[gold_purchase.AboveAvg=='Below'].loc[:,'NumStorePurchases']\n\nprint(scipy.stats.levene(gold_buyers,non_buyers))\n\n\"\"\"\nBased on the results, P-value is very small, thus reject the null hypothesis that the variances are equal. \n\nThus, we will perform 2 sample T-Test for Unequal Variances\n\"\"\"\nfrom scipy.stats import ttest_ind  \n    \ndef t_test(x,y,alternative='equal'):\n        _, double_p = ttest_ind(x,y,equal_var = False)\n        if alternative == 'equal':\n            pval = double_p\n        elif alternative == 'greater':\n            if np.mean(x) > np.mean(y):\n                pval = double_p\/2.\n            else:\n                pval = 1.0 - double_p\/2.\n        elif alternative == 'less':\n            if np.mean(x) < np.mean(y):\n                pval = double_p\/2.\n            else:\n                pval = 1.0 - double_p\/2.\n        return pval\n\nprint(\"At 0.05 significance level, \\n\")    \n    \n# Two tailed T-Test\np = t_test(gold_buyers,non_buyers,alternative='equal')\nif p > 0.05:\n    print(\"For 2-tailed test:\\nWith P-Val of\", p, \"we fail to reject the null hypothesis. Population means are equal\\n\")\nelse:\n    print(\"For 2-tailed test:\\nWith P-Val of\", p, \"null hypothesis is rejected. Population means are not equal\\n\")\n\n# One tailed T-Test\np2 = t_test(gold_buyers,non_buyers,alternative='greater')\nif p2 > 0.05:\n    print(\"For 1-tailed test:\\nWith P-Val of\", p2, \"we fail to reject the null hypothesis. \\nStore purchases of people who spend more on gold < Store purchases of people who spend less\")\nelse:\n    print(\"For 1-tailed test:\\nWith P-Val of\", p2, \"null hypothesis is rejected. \\nStore purchases of people who spend more on gold > Store purchases of people who spend less\")\n\n\"\"\"\nBased on the hypothesis test, we can conclude that store purchases of people who spend more on gold is greater than store purchases of people who spend less on gold. Thus, the supervisor's claim is justified.\n\"\"\"\n\"\"\"\n**4. Fish has Omega 3 fatty acids which are good for the brain. Accordingly, do \"Married PhD candidates\" have a significant relation with amount spent on fish? What other factors are significantly related to amount spent on fish? (Hint: use your knowledge of interaction variables\/effects)**\n\nFor this, we will build a multiple linear regression model to predict the amount spent on fish products. We will be using the standardized variables, so each variable is scaled from 0 to 1. Based on the coefficients of the model, we will be able to plot & determine the most significant factors (positive and negative) related to the amount spent on fish products, and identify if married PhD candidates is a strong factor.\n\"\"\"\nml2 = smf.ols('MntFishProducts ~ Year_Birth+Income+Dt_Customer+Recency+MntWines+MntFruits+MntMeatProducts+\\\n              MntSweetProducts+MntGoldProds+NumDealsPurchases+NumWebPurchases+NumCatalogPurchases+\\\n              NumWebVisitsMonth+NumStorePurchases+AcceptedCmp3+AcceptedCmp4+AcceptedCmp5+AcceptedCmp1+\\\n              AcceptedCmp2+Response+Complain+Education_Basic+Education_Graduation+Education_Master+Education_PhD\\\n              +Marital_Status_Married+Marital_Status_Single+Marital_Status_Together+Marital_Status_Widow+\\\n              HasKid+HasTeen+Country_CA+Country_GER+Country_IND+Country_ME+Country_SA\\\n              +Country_SP+Country_US+Marital_Status_Married*Education_PhD', data=mkt_scale).fit()\n\nml2.summary()\n\"\"\"\nWe will plot the parameter coefficients to visualize the effect of each parameter on the variable 'MntFishProducts'\n\"\"\"\nparams = ml2.params.sort_values(ascending=False)\nplt.figure(figsize=(15, 4)) \nplt.bar(params.index, params)\nplt.xticks(rotation=90)\nplt.title('Variable Scores')\nplt.xlabel('Variable')\nplt.ylabel('Coefficient')\nplt.show()\n\"\"\"\nWe will arbitrarily use -0.1 and 0.1 as the cutoff for coefficients, in order to narrow down the important factors. We will also plot the coefficient of the interaction term 'Marital_Status_Married:Education_PhD' for comparison\n\"\"\"\nparam_narrow = params[params>0.1].append(params[params<-0.1])\nparam_narrow=param_narrow[~(param_narrow.index=='Intercept')]\nparam_narrow.append(params[params.index=='Marital_Status_Married:Education_PhD'])\nplt.figure(figsize=(8, 4)) \nplt.bar(param_narrow.index, param_narrow)\nplt.bar('Marital_Status_Married:Education_PhD',params[params.index=='Marital_Status_Married:Education_PhD'])\nplt.xticks(rotation=90)\nplt.title('Variable Scores')\nplt.xlabel('Variable')\nplt.ylabel('Coefficient')\nplt.show()\n\"\"\"\nBased on the model, the factors that are significantly related to the amount spent on fish are: 'MntSweetProducts', 'MntFruits', 'MntMeatProducts', 'NumCatalogPurchases', 'MntGoldProds' and 'Country_ME'.\n\nThis means that customers who tend to spend on other products will also spend on fish products. Interestingly, Customers in Mexico also tend to buy more fish\n\nIn comparison, the interaction term of Married PhD customers have a very low coefficient. Thus, it does not have a significant relationship with the amount spent on fish.\n\"\"\"\n\"\"\"\n**5. Is there a significant relationship between geographical regional and success of a campaign?**\n\nFor this, we will fit a random forest classifier to the data, to predict response to the various campaigns (6 different models will be fit). The algorithm will rate each feature importance with a coefficient, based on the reduction effect on entropy. \n\nWe will plot the feature importance scores, and then the feature importance scores for the country variables will be studied to determine if there is a significant relationship to campaign success.\n\nNote that logistic regression was tried, but the model did not converge for many of the campaigns, thus we are taking this approach instead.\n\"\"\"\n# Target variable \"Response\", which is also the latest campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','Response'],axis=1)\ny = mkt_scale.Response\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Latest Campaign \"Response\"')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n# Target variable \"AcceptedCmp5\", which is the fifth campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','AcceptedCmp5'],axis=1)\ny = mkt_scale.AcceptedCmp5\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Campaign 5')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n# Target variable \"AcceptedCmp4\", which is the fourth campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','AcceptedCmp4'],axis=1)\ny = mkt_scale.AcceptedCmp4\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Campaign 4')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n# Target variable \"AcceptedCmp3\", which is the third campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','AcceptedCmp3'],axis=1)\ny = mkt_scale.AcceptedCmp3\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Campaign 3')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n# Target variable \"AcceptedCmp2\", which is the second campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','AcceptedCmp2'],axis=1)\ny = mkt_scale.AcceptedCmp2\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Campaign 2')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n# Target variable \"AcceptedCmp1\", which is the first campaign ran\n\nX = mkt_scale.drop(['ID','HasKid','HasTeen','AcceptedCmp1'],axis=1)\ny = mkt_scale.AcceptedCmp1\n# define the model\nmodel = RandomForestClassifier(n_estimators=100, criterion=\"entropy\")\n# fit the model\nmodel.fit(X, y)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nplt.figure(figsize=(15, 4)) \nplt.bar(X.columns[:-7], importance[:-7])\nplt.bar(X.columns[-7:], importance[-7:])\nplt.xticks(rotation=90)\nplt.title('Feature Importance for Campaign 1')\nplt.xlabel('Feature')\nplt.ylabel('Coefficient')\nplt.show()\n\"\"\"\nBased on the feature importance plots for each of the campaigns, it can be observed that the \"Country\" variables (in orange) tend to have very small coefficients, meaning that they are less important in predicting campaign success as compared to other features\n\nWe can further verify this by plotting the campaign acceptance rate across different countries.\n\"\"\"\ncampaign = mkt.loc[:,['Response','AcceptedCmp1','AcceptedCmp2','AcceptedCmp3','AcceptedCmp4','AcceptedCmp5','Country']]\ncampaign = campaign.groupby('Country').mean()\n\nf, axs = plt.subplots(3,2,figsize=(15,8))\ncampaign['Response'].plot(kind='bar', ax=axs[0,0])\naxs[0,0].title.set_text('Acceptance % of Latest Campaign')\ncampaign['AcceptedCmp5'].plot(kind='bar', ax=axs[0,1])\naxs[0,1].title.set_text('Acceptance % of Campaign 5')\ncampaign['AcceptedCmp4'].plot(kind='bar', ax=axs[1,0])\naxs[1,0].title.set_text('Acceptance % of Campaign 4')\ncampaign['AcceptedCmp3'].plot(kind='bar', ax=axs[1,1])\naxs[1,1].title.set_text('Acceptance % of Campaign 3')\ncampaign['AcceptedCmp2'].plot(kind='bar', ax=axs[2,0])\naxs[2,0].title.set_text('Acceptance % of Campaign 2')\ncampaign['AcceptedCmp1'].plot(kind='bar', ax=axs[2,1])\naxs[2,1].title.set_text('Acceptance % of Campaign 1')\n\nf.tight_layout()\nplt.show()\n\"\"\"\nFrom the plot above, we can see that the acceptance rate (%) of each campaign across the various countries tend to be quite low and rather uniform. Thus, it makes sense and further supports our conclusion that \"Country\" is not a significant feature to predict campaign success.\n\nNote that the dataset only contains 3 customer datapoints for Mexico, thus the acceptance rate appears to be high (i.e. If 1 customer accepts the campaign, success rate would already be at 33%)\n\"\"\"\n\"\"\"\n# Section 03: Data Visualization\nIn this section, we will present data visualizations to answer the following questions:\n\n1. Which marketing campaign is most successful?\n2. What does the average customer look like for this company?\n3. Which products are performing best?\n4. Which channels are underperforming?\n\"\"\"\n\"\"\"\n**1. Which marketing campaign is most successful?**\n\nFor this, we will plot the takeup rate for all campaigns\n\"\"\"\ncampaign_takeup = mkt.loc[:,['Response','AcceptedCmp1','AcceptedCmp2','AcceptedCmp3','AcceptedCmp4','AcceptedCmp5']]\n\ncampaign_takeup = campaign_takeup.melt()\ncampaign_takeup = pd.crosstab(campaign_takeup[\"variable\"], campaign_takeup[\"value\"]).sort_values(0)\n\ncols = list(campaign_takeup.columns)\na, b = cols.index(0), cols.index(1)\ncols[b], cols[a] = cols[a], cols[b]\ncampaign_takeup = campaign_takeup[cols]\n\ncampaign_takeup.columns = \"Yes\",\"No\"\ncampaign_takeup.plot.bar(stacked=True)\nplt.title('Acceptance of Marketing Campaigns')\nplt.xlabel('Campaign')\nplt.ylabel('Acceptance')\nplt.legend(title='Response',loc='upper right')\nplt.show()\n\"\"\"\nThe graph above displays the acceptance rates of the various campaigns, in descending order\n\nBased on the graph, we can conclude that the most recent campaign is the most successful one.\n\"\"\"\n\"\"\"\n**2. What does the average customer look like for this company?**\n\nWe will average across each qualitative variables, and take the modal category of all categorical variables to obtain the average customer for this company\n\"\"\"\naverage_cust = mkt.drop('ID',axis=1).mean()\naverage_cust = pd.DataFrame(average_cust)\naverage_cust.loc['Dt_Customer',:] = str(datetime.today() - timedelta(days = average_cust.loc['Dt_Customer',0]))\nmodal = mkt.drop('ID',axis=1).mode().transpose().loc[['Country','Education','Marital_Status']]\naverage_cust = average_cust.append(modal)\nprint(average_cust)\n\"\"\"\nOn average, a customer looks like this, divided into several categories:\n\nDemographic:\n* Born between 1968 and 1969\n* Income: $51,959\n* 0.44 kids and 0.51 teens at home, for an average of 1 dependent at home\n* Married\n* Graduated (likely high school)\n* From Spain\n\nLoyalty:\n* Became a customer on 10-07-2013\n* Last made a purchase 49 days ago\n\nExpenditure in last 2 years:\n* Wine: 304.03\n* Fruits: 26.30\n* Meat: 167.11\n* Fish: 37.45\n* Sweet: 27.11\n* Gold: 43.90\n\nChannels:\n* Deals Purchases: 2.32\n* Web Purchases: 4.08\n* Catalog Purchases: 2.66\n* Store Purchases: 5.79\n* Number of Web Visits in past month: 5.32\n\nInteractions:\n* Complains: 0.01\n* Accepted latest campaign: 0.15\n* Accepted Campaign 1: 0.064\n* Accepted Campaign 2: 0.013\n* Accepted Campaign 3: 0.073\n* Accepted Campaign 4: 0.075\n* Accepted Campaign 5: 0.073\n\"\"\"\n\"\"\"\n**3. Which products are performing best?**\n\nWe will plot a bar plot for each of the products, based on the amount sold in the last 2 years\n\"\"\"\nproducts = mkt.loc[:,['MntWines','MntFruits','MntMeatProducts','MntFishProducts','MntSweetProducts','MntGoldProds']]\nproducts = products.sum().sort_values(ascending=False)\n\nplt.bar(products.index,products)\nplt.xticks(rotation=90)\nplt.title('Product Performance in last 2 years')\nplt.xlabel('Product Category')\nplt.ylabel('Number Sold')\nplt.show()\n\"\"\"\nBased on the chart, we can see that wine performed the best, with the highest number of items sold, followed by meat products. On the other hand, Gold, Fish, Sweet and Fruits products are les popular, with similar number of items sold\n\"\"\"\n\"\"\"\n**4. Which channels are underperforming?**\n\nWe will plot a bar plot for each of the products, based on the interactions in the last 2 years. Number of web visits will not be included as data is only available for the past month \n\"\"\"\nchannels = mkt.loc[:,['NumDealsPurchases','NumWebPurchases','NumCatalogPurchases','NumStorePurchases']]\nchannels = channels.sum().sort_values(ascending=False)\n\nplt.bar(channels.index,channels)\nplt.xticks(rotation=90)\nplt.title('Channel Performance in last 2 years')\nplt.xlabel('Channel')\nplt.ylabel('Number of Products Sold')\nplt.show()\n\"\"\"\nBased on the chart, we can see that most customers preferred purchasing in physical stores, as it has the most number of items sold. This is followed by online website, catalog, and deals.\u00a0Deals is the most underperforming channel\n\"\"\"\n\"\"\"\n# Section 04: CMO Recommendations\n\nBased on the findings in the sections above, we provide the following data driven recommendations:\n\n1. Regional Market Recommendations:\n    * Mexico presents as an interested market with willingness to pay, as they have the highest average purchase quantities & purchase values, despite the company having low market penetration in the country.\n\n2. Channel Recommendations:\n    * CMO should relook at website strategy. As shown in the exploratory data analytics, there is large interest in website as shown by high number of visits in the last month. However, this is not being converted into sales as the average number of website purchases in the past 2 years is lower than the average visits in a single month.\n\n3. Product Recommendations:\n    * There is a large appetite for wine & meat products from the company, thus the company can try to diversify and bring in more premium products in these categories to further drive sales. Additionally, there are some customers with very high income values ( > 100k ) who may be interested in these products.\n\n4. Campaign Recommendations:\n    * Future campaigns should try to emulate and repeat features in latest campaign ran by the company as it performed very well, with highest takeup rate of 14% compared to the average campaign takeup rate of 7%. \n    * Since there is no strong relationship between geographical regional and success of a campaign, future campaigns can be piloted at a smaller scale on 1\/2 countries to find out what works and what doesn't, before rolling out to other countries. This will help to save cost on failed campaigns as well as increase agility in campaign rollouts\n    \n5. Customer Loyalty Recommendations:\n    * CMO should consider some loyalty program or rewards for members to increase stickiness & purchase frequency. This is because engagement within members is rather low, as many have been members for over a year, but median recency (days since last purchase) is approximately 50 days. Considering the store has a large variety of fresh products (Fruits, Fish & Meat), they would prefer weekly \/ biweekly visits of customers\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '48042f97e714c9'}"}
{"id":"45498","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport datetime as dt\n\npd.set_option(\"display.max_columns\", 500) \npd.set_option(\"display.max_rows\", 200)\nplt.rcParams['figure.figsize'] = [15, 6]\nsns.set_style(\"darkgrid\")\n!pip install pandas-profiling\n\"\"\"\n# 1. Basic Pandas\n\"\"\"\n# Load data to pandas\n\nonline_sales = pd.read_csv('\/kaggle\/input\/uisummerschool\/Online_sales.csv', sep=',')\nonline_sales.head()\n\"\"\"\n### 1.1 Show and assigning value\n\"\"\"\n# Menampilkan beberapa kolom\nonline_sales [['Date', 'Product SKU', 'Quantity', 'Revenue', 'Tax']]\n# Menyimpan data ke variabel baru\ntest = online_sales [['Date', 'Product SKU', 'Quantity', 'Revenue', 'Tax']]\n\n# Tidak menampilkan output\n\ntest\n# Jika setelah disimpan divariabel lalu ingin ditampilkan \ntest.head(10)\n# head bagian atas, tail bagian bawah data (sesuai kolom di csv)\n\"\"\"\n### 1.2 Filter and selection\n\"\"\"\n# Melakukan filter berdasarkan nilai suatu kolom\n# Misal ambil data dengan Product SKU bernilai GGOENEBQ079099\n# Cara 1\ncondition1= online_sales['Product SKU'] == 'GGOENEBQ079099'\n\nonline_sales[ (condition1) ]\n# online_sales[online_sales['Product SKU'] == 'GGOENEBQ079099']\n\n\ncondition2= online_sales['Quantity'] > 2\nonline_sales[ (condition1) & (condition2)]\n# Cara 2\n# Ingin mengambil data \nonline_sales.query('Quantity > 10').head(5)\n\"\"\"\n### 1.3 Create or update colomn\n\"\"\"\ntest = online_sales [['Date', 'Product SKU', 'Quantity', 'Revenue', 'Tax', 'Delivery']]\n## Kolom baru\ntest['Net_Income'] = test['Revenue'] - test['Tax'] - test['Delivery']\ntest.head()\n## Update kolom yg ada berdasar kondisi\n\nkondisi = test['Tax'].isnull() \n# bisa juga menggunakan >, <, == nilai tertentu \n# kondisi= test['Quantity'] > 2\n\ntest.loc[kondisi, ['Tax']] = 1\n\"\"\"\n### 1.4 Group by Data\n\"\"\"\n# Group by untuk aggregasi\n\ntest = online_sales.groupby(['Date'])['Quantity'].sum().reset_index()\ntest.head()\n#Group by multiple kolom\ntest = online_sales.groupby(['Date', 'Product SKU'])['Quantity'].sum().reset_index()\ntest.head()\nonline_sales.head(3)\n# Agregasi beberapa tipe\ntest = online_sales.groupby(['Date']).agg({'Quantity': 'sum',\n                                                      'Revenue': 'sum',\n                                                      'Tax': 'sum',\n                                                      'Product SKU': 'count',\n                                                      'Transaction ID': 'count',\n                                                     }).reset_index()\ntest.head()\n\"\"\"\n### 1.5 Sorting Data\n\"\"\"\n#Sort data berdasar quantity descending\nonline_sales.sort_values(by=['Quantity'], ascending = False).head(15)\n\"\"\"\n### 1.6 Mengganti nama kolom atau mendelete kolom\n\"\"\"\ntest.head(3)\ntest.rename(index=str, columns={\"Quantity\": \"Total Quantity\", \"Revenue\": \"Total Revenue\"}, inplace = True)\n\ntest.drop(columns=['Product SKU', 'Transaction ID'], inplace = True)\ntest.head()\n\"\"\"\n# 2. Our Challenge\n\"\"\"\n\"\"\"\nKita memiliki data penjualan online hingga 30 november 2017, Pak Bos meminta untuk melakukan prediksi \nberapa penjualan kita untuk 2 minggu ke depan (1 Desember -14 Desember)\nDari data penjualan online :\n1. Olah data hingga mendapat total revenue per hari [sudah]\n2. Tambahkan data yang akan diprediksi [sudah]\n3. Persiapan data prediksi dan training\n4. Training dan testing (modelling)\n\n\"\"\"\n## Tahap 1 Olah data hingga mendapat total revenue per hari\nonline_sales = online_sales = pd.read_csv('\/kaggle\/input\/uisummerschool\/Online_sales.csv')\nbackup = online_sales.copy() ##untuk debugging pengajar, tak usah dihiraukan\n\ndaily_online_revenue = online_sales.groupby(['Date'])['Revenue'].sum().reset_index()\ndaily_online_revenue.tail()\n## Plot\n\ng = sns.lineplot(data = daily_online_revenue, x= 'Date', y = 'Revenue')     \ndaily_online_revenue.info()\ndaily_online_revenue['Date'] = daily_online_revenue['Date'].astype(str)\ndaily_online_revenue['Date'] = pd.to_datetime(daily_online_revenue['Date'])\ng = sns.lineplot(data = daily_online_revenue, x= 'Date', y = 'Revenue')     \n## Tahap 2 Tambahkan data yang akan diprediksi\nadd_data = [['2017-12-01', 0], ['2017-12-02', 0], ['2017-12-03', 0],\n            ['2017-12-04', 0], ['2017-12-05', 0], ['2017-12-06', 0],\n            ['2017-12-07', 0], ['2017-12-08', 0], ['2017-12-09', 0],\n            ['2017-12-10', 0], ['2017-12-11', 0], ['2017-12-10', 0],\n            ['2017-12-13', 0], ['2017-12-14', 0]\n           ] \n  \n# Create the pandas DataFrame \nadd_data_df = pd.DataFrame(add_data, columns = ['Date', 'Revenue']) \nadd_data_df['Date'] = add_data_df['Date'].astype(str)\nadd_data_df['Date'] = pd.to_datetime(add_data_df['Date'])\n\n\ndaily_online_revenue = daily_online_revenue.append(add_data_df)\ndf_rev = daily_online_revenue.copy()  ##untuk evaluasi pemateri\n\ndaily_online_revenue.tail(20)\n## 3 Persiapan data prediksi dan training\ndef preprocess (dataset):\n    processed_dataset = dataset.copy()\n    for i in range(1,6):\n        processed_dataset[\"d-\"+str(i)+\"_rev\"] = dataset.shift(i, axis=0)[\"Revenue\"]\n#     processed_dataset = processed_dataset.fillna(0)\n    processed_dataset = processed_dataset.dropna()\n\n    return processed_dataset\n\n## Add feature \ndaily_online_revenue = preprocess(daily_online_revenue).set_index('Date')\ndaily_online_revenue\n\n# If you want to submit, please change the value to \"2017-11-30\" \"2017-11-16\"\nend_of_training_date = \"2017-11-30\" \n\ntrain_data = daily_online_revenue.loc[:end_of_training_date]\ntest_data = daily_online_revenue.loc[end_of_training_date:]\ntest_data = daily_online_revenue.iloc[1:]\ntrain_data\n# Pisahkan kolom yang ingin diprediksi (biasa disebut label menjadi y), dan variabel lain menjadi x\nx_train = train_data [['d-1_rev','d-2_rev','d-3_rev','d-4_rev','d-5_rev']]\ny_train = train_data [['Revenue']]\n\nx_test = test_data [['d-1_rev','d-2_rev','d-3_rev','d-4_rev','d-5_rev']]\ny_test = test_data [['Revenue']]\n## Split train and test\ndef split_train_test(dataset, end_of_training_date):\n    \n    # training_data =\n    training_data = dataset.loc[:end_of_training_date]\n    # testing_data = \n    testing_data = dataset.loc[end_of_training_date:]\n    testing_data = testing_data.iloc[1:]\n    return training_data, testing_data\n## Split label and predictor\ndef split_label_and_predictor(train_or_test_data):\n    \n    # x_data =\n    x_data = train_or_test_data [['d-1_rev','d-2_rev','d-3_rev','d-4_rev','d-5_rev']]\n    # y_data = \n    y_data = train_or_test_data [['Revenue']]\n    return x_data, y_data\nfrom sklearn.ensemble import RandomForestRegressor\n\ndef fit(x_train, y_train):\n    model = RandomForestRegressor(random_state=1)  #14045\n    model.fit(x_train, y_train)\n    return model\n\ndef predict(model, x_test):\n    y_pred = model.predict(x_test)\n    return y_pred\n\nmodel = fit(x_train, y_train)\n\n\nx_test = x_test.reset_index().drop(columns=['Date'])\nx_test\nfor i in y_pred[:5]:\n    print(i)\n# Predict the model\ndf_rev2 = df_rev.copy()\nn_iteration = len(x_test)\nresult = []\nfor i in range(n_iteration):\n    y_pred = predict(model, pd.DataFrame(x_test.iloc[i]).transpose())\n    result.append(y_pred[0])\n    df_rev2.loc[df_rev2[\"Date\"]==x_test.index[i],\"Revenue\"] = y_pred\n    \n    # Repeat the whole process, except for model fitting\n    daily_online_revenue = preprocess(df_rev2).set_index('Date')\n    _, testing_data = split_train_test(daily_online_revenue,end_of_training_date)\n    x_test, _ = split_label_and_predictor(testing_data)\nresult\ny_test\ny_test = y_test.tail(14)\nprint(len(y_test))\n# THIS IS FOR VALIDATION PURPOSE\n# Prediction vs Actual\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\ncomparison = pd.DataFrame({\"Prediction\":result,\"Actual\":y_test['Revenue']})\ncomparison.index = y_test.index\nerror = sqrt(mean_squared_error(comparison[\"Actual\"], comparison[\"Prediction\"]))\nprint(\"Error Score (RMSE) = {}\".format(round(error,2)))\n\nhistorical = pd.DataFrame(y_train).rename(columns={\"Revenue\":\"Actual\"}).tail(14)\n\npd.concat([historical,comparison],sort=True).plot();\n# Save the result to CSV for submission\nformatted_result = pd.DataFrame(result).reset_index().rename(columns={\"index\":\"Id\",0:\"Revenue\"})\ndisplay(formatted_result)\n\n# Uncomment the code below if you want to save the result\nformatted_result[['Id', 'Revenue']].to_csv(\"result.csv\",index=False)","meta":"{'source': 'AI4Code', 'id': '53d957b29720f8'}"}
{"id":"90000","text":"\"\"\"\n# IRIS SPECIES \n\"\"\"\n\"\"\"\n# \n\"\"\"\n\"\"\"\n# TASK : \n#         To Predict the species of the iris flower.\n\"\"\"\n\"\"\"\nImporting necessary libraries:\n\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy as sp\nimport os\nimport graphviz \nimport preprocessing \n\n\"\"\"\n# IMPORTING THE DATA\n\"\"\"\ndataset = pd.read_csv('..\/input\/iris\/Iris.csv')\n\"\"\"\n# DISPLAYING THE TOP 5 RECORDS USING HEAD\n\"\"\"\ndataset.head()\ndataset.info()\ndataset.shape   # displaying the number of rows and columns\ndataset.columns   # displaying all the columns\ndataset.count()  #count the values\ndataset.describe()  #describe the data\ndataset.isnull().sum()\ndataset.value_counts\niris=dataset\n\"\"\"\n# VISUALIZATION USING DIFFERENT PLOTS\n\"\"\"\n\"\"\"\n# SCATTER PLOT:\n\"\"\"\n# We will make a scatterplot of two of the four Iris features \n\n\niris.plot(kind=\"scatter\", x=\"SepalLengthCm\", y= \"SepalWidthCm\")\n\"\"\"\n# JOINT PLOT:\n\"\"\"\n## we can do it also with the seaborn library\n\n## A seaborn jointplot shows bivariate scatterplots and univariate histograms in the \n# same figure\n\nsns.jointplot( data=iris,x=\"SepalLengthCm\", y=\"SepalWidthCm\", size=5)\n\"\"\"\n# DENSITY PLOT : KDE\n\"\"\"\n## we can do it also with the seaborn library\n\n## A seaborn kdeplot shows density scatterplots and univariate histograms in the \n# same figure\n\nsns.kdeplot(data= iris, x=\"SepalLengthCm\", y=\"SepalWidthCm\", size=5)\n\"\"\"\n# FACET GRID:\n\"\"\"\nsns.FacetGrid(iris, hue=\"Species\", palette=\"husl\",size=5) \\\n   .map(plt.scatter, \"SepalLengthCm\", \"SepalWidthCm\") \\\n   .add_legend()\n\"\"\"\n# BOXPLOT\n\"\"\"\nsns.boxplot(x=\"Species\", y=\"PetalLengthCm\", data=iris)\n\"\"\"\n# VIOLIN PLOT:\n\"\"\"\nsns.violinplot(data=iris, x=\"Species\", y=\"PetalWidthCm\",\n                palette=\"rocket\")\n\"\"\"\n# PAIR PLOT:\n\"\"\"\nsns.pairplot(iris.drop(\"Id\", axis=1), \n             hue =\"Species\",palette= \"husl\", size=3) \n \ndataset.tail()\n\"\"\"\n# HEATMAP\n\"\"\"\nplt.figure(figsize=(12,8)) \nsns.heatmap(dataset.corr(), annot=True, cmap='Dark2_r', linewidths = 2)\nplt.show()\nplt.figure(figsize=(25,15))\n\nplt.subplot(2,2,1)\nsns.histplot(dataset['SepalLengthCm'], color = 'red', kde = True).set_title('SepalLengthCm Interval and Counts')\n\nplt.subplot(2,2,2)\nsns.histplot(dataset['SepalWidthCm'], color = 'green', kde = True).set_title('SepalWidthCm Interval and Counts')\n\nplt.subplot(2,2,3)\nsns.histplot(dataset['PetalLengthCm'], kde = True, color = 'blue').set_title('PetalLengthCm Interval and Counts')\n\nplt.subplot(2,2,4)\nsns.histplot(dataset['PetalWidthCm'], kde = True, color = 'black').set_title('PetalWidthCm Interval and Counts')\n\"\"\"\n# DATA VISUALIZATION USING BAR\n\"\"\"\nplt.figure(figsize=(20,15))\nplt.subplot(2,2,1)\nsns.barplot(x = 'Species', y = 'SepalLengthCm', data = dataset, palette=\"cubehelix\")\nplt.subplot(2,2,2)\nsns.barplot(x = 'Species', y = 'SepalWidthCm', data = dataset, palette=\"Oranges\")\nplt.subplot(2,2,3)\nsns.barplot(x = 'Species', y = 'PetalLengthCm', data = dataset, palette=\"Oranges\")\nplt.subplot(2,2,4)\nsns.barplot(x = 'Species', y = 'PetalWidthCm', data = dataset, palette=\"cubehelix\")\nplt.figure(figsize=(20,15))\nplt.subplot(2,2,1)\nsns.distplot(dataset['SepalLengthCm'], color=\"red\").set_title('SepalLength Interval')\nplt.subplot(2,2,2)\nsns.distplot(dataset['SepalWidthCm'], color=\"green\").set_title('SepalWidth Interval')\nplt.subplot(2,2,3)\nsns.distplot(dataset['PetalLengthCm'], color=\"blue\").set_title('PetalLength Interval')\nplt.subplot(2,2,4)\nsns.distplot(dataset['PetalWidthCm'], color=\"black\").set_title('PetalWidth Interval')\n\"\"\"\n# Conclusion: \n\nIn this notebook, I examined Iris Species Dataset. Firstly, I made Exploratory Data Analysis, then I Visualize the data to Predict the species of the iris flower using different plots .\n\nIf you have questions, please comment them. I will try to explain if you don't understand.\nIf you liked this notebook, please let me know :)\nThank you for your time. Cheers!!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a51297b0114783'}"}
{"id":"30341","text":"from tensorflow import lite\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport numpy as np\nimport pandas as pd\nimport random, os\nimport shutil\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.metrics import categorical_accuracy, AUC\nfrom sklearn.model_selection import train_test_split\n\n!pip install tensorflow-addons==0.9.1\nimport tensorflow_addons\nfrom tensorflow_addons.metrics import F1Score, CohenKappa\n# Add an additional column, mapping to the type\ndf = pd.read_csv('..\/input\/diabetic-retinopathy-224x224-gaussian-filtered\/train.csv')\n\ndiagnosis_dict_binary = {\n    0: 'No_DR',\n    1: 'DR',\n    2: 'DR',\n    3: 'DR',\n    4: 'DR'\n}\n\ndiagnosis_dict = {\n    0: 'No_DR',\n    1: 'Mild',\n    2: 'Moderate',\n    3: 'Severe',\n    4: 'Proliferate_DR',\n}\n\n\ndf['binary_type'] =  df['diagnosis'].map(diagnosis_dict_binary.get)\ndf['type'] = df['diagnosis'].map(diagnosis_dict.get)\ndf.head()\ndf['type'].value_counts().plot(kind='barh')\ndf['binary_type'].value_counts().plot(kind='barh')\n# Split into stratified train, val, and test sets\ntrain_intermediate, val = train_test_split(df, test_size = 0.15, stratify = df['type'])\ntrain, test = train_test_split(train_intermediate, test_size = 0.15 \/ (1 - 0.15), stratify = train_intermediate['type'])\n\nprint(train['type'].value_counts(), '\\n')\nprint(test['type'].value_counts(), '\\n')\nprint(val['type'].value_counts(), '\\n')\n\n# Create working directories for train\/val\/test\nbase_dir = ''\n\ntrain_dir = os.path.join(base_dir, 'train')\nval_dir = os.path.join(base_dir, 'val')\ntest_dir = os.path.join(base_dir, 'test')\n\nif os.path.exists(base_dir):\n    shutil.rmtree(base_dir)\n\nif os.path.exists(train_dir):\n    shutil.rmtree(train_dir)\nos.makedirs(train_dir)\n\nif os.path.exists(val_dir):\n    shutil.rmtree(val_dir)\nos.makedirs(val_dir)\n\nif os.path.exists(test_dir):\n    shutil.rmtree(test_dir)\nos.makedirs(test_dir)\n\n# Copy images to respective working directory\nsrc_dir = '..\/input\/diabetic-retinopathy-224x224-gaussian-filtered\/gaussian_filtered_images\/gaussian_filtered_images\/'\nfor index, row in train.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(train_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)\n\nfor index, row in val.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(val_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)\n\nfor index, row in test.iterrows():\n    diagnosis = row['type']\n    binary_diagnosis = row['binary_type']\n    id_code = row['id_code'] + \".png\"\n    srcfile = os.path.join(src_dir, diagnosis, id_code)\n    dstfile = os.path.join(test_dir, binary_diagnosis)\n    os.makedirs(dstfile, exist_ok = True)\n    shutil.copy(srcfile, dstfile)\n\n# Setting up ImageDataGenerator for train\/val\/test \n\ntrain_path = 'train'\nval_path = 'val'\ntest_path = 'test'\n\ntrain_batches = ImageDataGenerator(rescale = 1.\/255).flow_from_directory(train_path, target_size=(224,224), shuffle = True)\nval_batches = ImageDataGenerator(rescale = 1.\/255).flow_from_directory(val_path, target_size=(224,224), shuffle = True)\ntest_batches = ImageDataGenerator(rescale = 1.\/255).flow_from_directory(test_path, target_size=(224,224), shuffle = False)\n\n\"\"\"\n# 8 Layer CNN\n\"\"\"\n# Building the model\n\nmodel = tf.keras.Sequential([\n    layers.Conv2D(16, (3,3), padding=\"same\", input_shape=(224,224,3), activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(32, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n \n    layers.Conv2D(64, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(64, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(128, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(128, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(256, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(2,2)),\n    layers.BatchNormalization(),\n    \n    layers.Conv2D(256, (3,3), padding=\"same\", activation = 'relu'),\n    layers.MaxPooling2D(pool_size=(1,1)),\n    layers.BatchNormalization(),\n    \n    layers.Flatten(),\n    layers.Dense(32, activation = 'relu'),\n    layers.Dropout(0.15),\n    layers.Dense(2, activation = 'softmax')\n])\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(lr = 1e-5),\n              loss=tf.keras.losses.BinaryCrossentropy(),\n              metrics=['acc','AUC',tensorflow_addons.metrics.F1Score(num_classes=2, average='weighted'),tensorflow_addons.metrics.CohenKappa(num_classes=5)])\n\nhistory = model.fit(train_batches,\n                    epochs=12,\n                    validation_data=val_batches)\nacc = model.evaluate_generator(test_batches, verbose=1)\nprint(\"Accuracy: \", acc[1])\nplt.subplot(1,2,1)\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.ylabel('acc')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='lower right')\n\nplt.subplot(1,2,2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='lower right')\n","meta":"{'source': 'AI4Code', 'id': '37c6de38d0ba4e'}"}
{"id":"104075","text":"\"\"\"\n# HUBMAP GPU Inference Phase\n\"\"\"\n\"\"\"\n### References\n\n\n[Getting Started: TPUs + Cassava Leaf Disease](https:\/\/www.kaggle.com\/jessemostipak\/getting-started-tpus-cassava-leaf-disease)\n\n[CutMix and MixUp on GPU\/TPU](https:\/\/www.kaggle.com\/cdeotte\/cutmix-and-mixup-on-gpu-tpu)\n\n[Getting started with 100+ flowers on TPU](https:\/\/www.kaggle.com\/mgornergoogle\/getting-started-with-100-flowers-on-tpu)\n\n[Triple Stratified KFold with TFRecords](https:\/\/www.kaggle.com\/cdeotte\/triple-stratified-kfold-with-tfrecords)\n\"\"\"\n\"\"\"\nsome codes from \n\n[[HuBMAP] Keras-Pipeline (Training+Inference)](https:\/\/www.kaggle.com\/joshi98kishan\/hubmap-keras-pipeline-training-inference)\n\n[Pytorch FCN-Resnet50](https:\/\/www.kaggle.com\/leighplt\/pytorch-fcn-resnet50)\n\"\"\"\n\"\"\"\n### other notebooks\n\n[Make Tfrecords of 512x512 or other tiles](https:\/\/www.kaggle.com\/itsuki9180\/make-tfrecords-of-512x512-or-other-tiles)\n\n[HUBMAP TPU Train Phase](https:\/\/www.kaggle.com\/itsuki9180\/hubmap-tpu-train-phase)\n\nHUBMAP GPU Inference Phase (This notebook)\n\"\"\"\nimport math, re, os, gc\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Model, load_model\nfrom keras.utils.generic_utils import get_custom_objects\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\n\nprint(\"Tensorflow version \" + tf.__version__)\nimport os, gc\nimport numpy as np \nimport pandas as pd \nimport cv2\nimport glob\nimport numba\nimport pathlib\nfrom tqdm.notebook import tqdm\nimport tifffile as tiff\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\n# For reading tiff images in parts \nimport rasterio\nfrom rasterio.windows import Window\n\nimport warnings\nwarnings.filterwarnings('ignore')\nIMAGE_SIZE = [512, 512]\nDIM = IMAGE_SIZE[0]\nEFUN = 3\nFOLDS = 4\ndata_path = '\/kaggle\/input\/'\npath_submission_file = os.path.join(data_path, 'hubmap-kidney-segmentation\/sample_submission.csv')\n\n\"\"\"\n# Build Model\n\"\"\"\n\"\"\"\n# EfficientUNet(using efficientnet as encoder)\n\nmost of codes from [zhoudaxia233\/EfficientUnet](https:\/\/github.com\/zhoudaxia233\/EfficientUnet).\n\nand see also [qubvel\/efficientnet](https:\/\/github.com\/qubvel\/efficientnet).\n\"\"\"\nimport re\nfrom collections import namedtuple\nfrom tensorflow.keras import layers\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nimport math\nimport numpy as np\n\nGlobalParams = namedtuple('GlobalParams', ['batch_norm_momentum', 'batch_norm_epsilon', 'dropout_rate', 'num_classes',\n                                           'width_coefficient', 'depth_coefficient', 'depth_divisor', 'min_depth',\n                                           'drop_connect_rate'])\nGlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields)\n\nBlockArgs = namedtuple('BlockArgs', ['kernel_size', 'num_repeat', 'input_filters', 'output_filters', 'expand_ratio',\n                                     'id_skip', 'strides', 'se_ratio'])\nBlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields)\n\nIMAGENET_WEIGHTS = {\n\n    'efficientnet-b0': {\n        'name': 'efficientnet-b0_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b0_imagenet_1000.h5',\n        'md5': 'bca04d16b1b8a7c607b1152fe9261af7',\n    },\n\n    'efficientnet-b1': {\n        'name': 'efficientnet-b1_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b1_imagenet_1000.h5',\n        'md5': 'bd4a2b82f6f6bada74fc754553c464fc',\n    },\n\n    'efficientnet-b2': {\n        'name': 'efficientnet-b2_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b2_imagenet_1000.h5',\n        'md5': '45b28b26f15958bac270ab527a376999',\n    },\n\n    'efficientnet-b3': {\n        'name': 'efficientnet-b3_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b3_imagenet_1000.h5',\n        'md5': 'decd2c8a23971734f9d3f6b4053bf424',\n    },\n\n    'efficientnet-b4': {\n        'name': 'efficientnet-b4_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b4_imagenet_1000.h5',\n        'md5': '01df77157a86609530aeb4f1f9527949',\n    },\n\n    'efficientnet-b5': {\n        'name': 'efficientnet-b5_imagenet_1000.h5',\n        'url': 'https:\/\/github.com\/qubvel\/efficientnet\/releases\/download\/v0.0.1\/efficientnet-b5_imagenet_1000.h5',\n        'md5': 'c31311a1a38b5111e14457145fccdf32',\n    }\n\n}\n\n\ndef round_filters(filters, global_params):\n    \"\"\"Round number of filters.\"\"\"\n    multiplier = global_params.width_coefficient\n    divisor = global_params.depth_divisor\n    min_depth = global_params.min_depth\n    if not multiplier:\n        return filters\n\n    filters *= multiplier\n    min_depth = min_depth or divisor\n    new_filters = max(min_depth, int(filters + divisor \/ 2) \/\/ divisor * divisor)\n    # Make sure that round down does not go down by more than 10%.\n    if new_filters < 0.9 * filters:\n        new_filters += divisor\n    return int(new_filters)\n\n\ndef round_repeats(repeats, global_params):\n    \"\"\"Round number of repeats.\"\"\"\n    multiplier = global_params.depth_coefficient\n    if not multiplier:\n        return repeats\n    return int(math.ceil(multiplier * repeats))\n\n\ndef get_efficientnet_params(model_name, override_params=None):\n    \"\"\"Get efficientnet params based on model name.\"\"\"\n    params_dict = {\n        # (width_coefficient, depth_coefficient, resolution, dropout_rate)\n        # Note: the resolution here is just for reference, its values won't be used.\n        'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n        'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n        'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n        'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n        'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n        'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n        'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n        'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n    }\n    if model_name not in params_dict.keys():\n        raise KeyError('There is no model named {}.'.format(model_name))\n\n    width_coefficient, depth_coefficient, _, dropout_rate = params_dict[model_name]\n\n    blocks_args = [\n        'r1_k3_s11_e1_i32_o16_se0.25', 'r2_k3_s22_e6_i16_o24_se0.25',\n        'r2_k5_s22_e6_i24_o40_se0.25', 'r3_k3_s22_e6_i40_o80_se0.25',\n        'r3_k5_s11_e6_i80_o112_se0.25', 'r4_k5_s22_e6_i112_o192_se0.25',\n        'r1_k3_s11_e6_i192_o320_se0.25',\n    ]\n    global_params = GlobalParams(\n        batch_norm_momentum=0.99,\n        batch_norm_epsilon=1e-3,\n        dropout_rate=dropout_rate,\n        drop_connect_rate=0.2,\n        num_classes=1000,\n        width_coefficient=width_coefficient,\n        depth_coefficient=depth_coefficient,\n        depth_divisor=8,\n        min_depth=None)\n\n    if override_params:\n        global_params = global_params._replace(**override_params)\n\n    decoder = BlockDecoder()\n    return decoder.decode(blocks_args), global_params\n\n\nclass BlockDecoder(object):\n    \"\"\"Block Decoder for readability.\"\"\"\n\n    @staticmethod\n    def _decode_block_string(block_string):\n        \"\"\"Gets a block through a string notation of arguments.\"\"\"\n        assert isinstance(block_string, str)\n        ops = block_string.split('_')\n        options = {}\n        for op in ops:\n            splits = re.split(r'(\\d.*)', op)\n            if len(splits) >= 2:\n                key, value = splits[:2]\n                options[key] = value\n\n        if 's' not in options or len(options['s']) != 2:\n            raise ValueError('Strides options should be a pair of integers.')\n\n        return BlockArgs(\n            kernel_size=int(options['k']),\n            num_repeat=int(options['r']),\n            input_filters=int(options['i']),\n            output_filters=int(options['o']),\n            expand_ratio=int(options['e']),\n            id_skip=('noskip' not in block_string),\n            se_ratio=float(options['se']) if 'se' in options else None,\n            strides=[int(options['s'][0]), int(options['s'][1])]\n        )\n\n    @staticmethod\n    def _encode_block_string(block):\n        \"\"\"Encodes a block to a string.\"\"\"\n        args = [\n            'r%d' % block.num_repeat,\n            'k%d' % block.kernel_size,\n            's%d%d' % (block.strides[0], block.strides[1]),\n            'e%s' % block.expand_ratio,\n            'i%d' % block.input_filters,\n            'o%d' % block.output_filters\n        ]\n        if 0 < block.se_ratio <= 1:\n            args.append('se%s' % block.se_ratio)\n        if block.id_skip is False:\n            args.append('noskip')\n        return '_'.join(args)\n\n    def decode(self, string_list):\n        \"\"\"Decodes a list of string notations to specify blocks inside the network.\n        Args:\n          string_list: a list of strings, each string is a notation of block.\n        Returns:\n          A list of namedtuples to represent blocks arguments.\n        \"\"\"\n        assert isinstance(string_list, list)\n        blocks_args = []\n        for block_string in string_list:\n            blocks_args.append(self._decode_block_string(block_string))\n        return blocks_args\n\n    def encode(self, blocks_args):\n        \"\"\"Encodes a list of Blocks to a list of strings.\n        Args:\n          blocks_args: A list of namedtuples to represent blocks arguments.\n        Returns:\n          a list of strings, each string is a notation of block.\n        \"\"\"\n        block_strings = []\n        for block in blocks_args:\n            block_strings.append(self._encode_block_string(block))\n        return block_strings\n\n\nclass Swish(layers.Layer):\n    def __init__(self, name=None, **kwargs):\n        super().__init__(name=name, **kwargs)\n\n    def call(self, inputs, **kwargs):\n        return tf.nn.swish(inputs)\n\n    def get_config(self):\n        config = super().get_config()\n        config['name'] = self.name\n        return config\n\n\ndef SEBlock(block_args, **kwargs):\n    num_reduced_filters = max(\n        1, int(block_args.input_filters * block_args.se_ratio))\n    filters = block_args.input_filters * block_args.expand_ratio\n\n    spatial_dims = [1, 2]\n\n    try:\n        block_name = kwargs['block_name']\n    except KeyError:\n        block_name = ''\n\n    def block(inputs):\n        x = inputs\n        x = layers.Lambda(lambda a: K.mean(a, axis=spatial_dims, keepdims=True))(x)\n        x = layers.Conv2D(\n            num_reduced_filters,\n            kernel_size=[1, 1],\n            strides=[1, 1],\n            kernel_initializer=conv_kernel_initializer,\n            padding='same',\n            name=block_name + 'se_reduce_conv2d',\n            use_bias=True\n        )(x)\n\n        x = Swish(name=block_name + 'se_swish')(x)\n\n        x = layers.Conv2D(\n            filters,\n            kernel_size=[1, 1],\n            strides=[1, 1],\n            kernel_initializer=conv_kernel_initializer,\n            padding='same',\n            name=block_name + 'se_expand_conv2d',\n            use_bias=True\n        )(x)\n\n        x = layers.Activation('sigmoid')(x)\n        out = layers.Multiply()([x, inputs])\n        return out\n\n    return block\n\n\nclass DropConnect(layers.Layer):\n\n    def __init__(self, drop_connect_rate, **kwargs):\n        super().__init__(**kwargs)\n        self.drop_connect_rate = drop_connect_rate\n\n    def call(self, inputs, **kwargs):\n        def drop_connect():\n            keep_prob = 1.0 - self.drop_connect_rate\n\n            # Compute drop_connect tensor\n            batch_size = tf.shape(inputs)[0]\n            random_tensor = keep_prob\n            random_tensor += tf.random.uniform([batch_size, 1, 1, 1], dtype=inputs.dtype)\n            binary_tensor = tf.floor(random_tensor)\n            output = tf.math.divide(inputs, keep_prob) * binary_tensor\n            return output\n\n        return K.in_train_phase(drop_connect(), inputs, training=None)\n\n    def get_config(self):\n        config = super().get_config()\n        config['drop_connect_rate'] = self.drop_connect_rate\n        return config\n\n\ndef conv_kernel_initializer(shape, dtype=K.floatx()):\n    \"\"\"Initialization for convolutional kernels.\n    The main difference with tf.variance_scaling_initializer is that\n    tf.variance_scaling_initializer uses a truncated normal with an uncorrected\n    standard deviation, whereas here we use a normal distribution. Similarly,\n    tf.contrib.layers.variance_scaling_initializer uses a truncated normal with\n    a corrected standard deviation.\n    Args:\n        shape: shape of variable\n        dtype: dtype of variable\n    Returns:\n        an initialization for the variable\n    \"\"\"\n    kernel_height, kernel_width, _, out_filters = shape\n    fan_out = int(kernel_height * kernel_width * out_filters)\n    return tf.random.normal(\n        shape, mean=0.0, stddev=np.sqrt(2.0 \/ fan_out), dtype=dtype)\n\n\ndef dense_kernel_initializer(shape, dtype=K.floatx()):\n    init_range = 1.0 \/ np.sqrt(shape[1])\n    return tf.random.uniform(shape, -init_range, init_range, dtype=dtype)\n\n\ndef MBConvBlock(block_args, global_params, idx, drop_connect_rate=None):\n    filters = block_args.input_filters * block_args.expand_ratio\n    batch_norm_momentum = global_params.batch_norm_momentum\n    batch_norm_epsilon = global_params.batch_norm_epsilon\n    has_se = (block_args.se_ratio is not None) and (0 < block_args.se_ratio <= 1)\n\n    block_name = 'blocks_' + str(idx) + '_'\n\n    def block(inputs):\n        x = inputs\n\n        # Expansion phase\n        if block_args.expand_ratio != 1:\n            expand_conv = layers.Conv2D(filters,\n                                        kernel_size=[1, 1],\n                                        strides=[1, 1],\n                                        kernel_initializer=conv_kernel_initializer,\n                                        padding='same',\n                                        use_bias=False,\n                                        name=block_name + 'expansion_conv2d'\n                                        )(x)\n            bn0 = layers.BatchNormalization(momentum=batch_norm_momentum,\n                                            epsilon=batch_norm_epsilon,\n                                            name=block_name + 'expansion_batch_norm')(expand_conv)\n\n            x = Swish(name=block_name + 'expansion_swish')(bn0)\n\n        # Depth-wise convolution phase\n        kernel_size = block_args.kernel_size\n        depthwise_conv = layers.DepthwiseConv2D(\n            [kernel_size, kernel_size],\n            strides=block_args.strides,\n            depthwise_initializer=conv_kernel_initializer,\n            padding='same',\n            use_bias=False,\n            name=block_name + 'depthwise_conv2d'\n        )(x)\n        bn1 = layers.BatchNormalization(momentum=batch_norm_momentum,\n                                        epsilon=batch_norm_epsilon,\n                                        name=block_name + 'depthwise_batch_norm'\n                                        )(depthwise_conv)\n        x = Swish(name=block_name + 'depthwise_swish')(bn1)\n\n        if has_se:\n            x = SEBlock(block_args, block_name=block_name)(x)\n\n        # Output phase\n        project_conv = layers.Conv2D(\n            block_args.output_filters,\n            kernel_size=[1, 1],\n            strides=[1, 1],\n            kernel_initializer=conv_kernel_initializer,\n            padding='same',\n            name=block_name + 'output_conv2d',\n            use_bias=False)(x)\n        x = layers.BatchNormalization(momentum=batch_norm_momentum,\n                                      epsilon=batch_norm_epsilon,\n                                      name=block_name + 'output_batch_norm'\n                                      )(project_conv)\n        if block_args.id_skip:\n            if all(\n                    s == 1 for s in block_args.strides\n            ) and block_args.input_filters == block_args.output_filters:\n                # only apply drop_connect if skip presents.\n                if drop_connect_rate:\n                    x = DropConnect(drop_connect_rate)(x)\n                x = layers.add([x, inputs])\n\n        return x\n\n    return block\n\n\ndef freeze_efficientunet_first_n_blocks(model, n):\n    mbblock_nr = 0\n    while True:\n        try:\n            model.get_layer('blocks_{}_output_batch_norm'.format(mbblock_nr))\n            mbblock_nr += 1\n        except ValueError:\n            break\n\n    all_block_names = ['blocks_{}_output_batch_norm'.format(i) for i in range(mbblock_nr)]\n    all_block_index = []\n    for idx, layer in enumerate(model.layers):\n        if layer.name == all_block_names[0]:\n            all_block_index.append(idx)\n            all_block_names.pop(0)\n            if len(all_block_names) == 0:\n                break\n    n_blocks = len(all_block_index)\n\n    if n <= 0:\n        print('n is less than or equal to 0, therefore no layer will be frozen.')\n        return\n    if n > n_blocks:\n        raise ValueError(\"There are {} blocks in total, n cannot be greater than {}.\".format(n_blocks, n_blocks))\n\n    idx_of_last_block_to_be_frozen = all_block_index[n - 1]\n    for layer in model.layers[:idx_of_last_block_to_be_frozen + 1]:\n        layer.trainable = False\n\n\ndef unfreeze_efficientunet(model):\n    for layer in model.layers:\n        layer.trainable = True\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.utils import get_file\n\n__all__ = ['get_model_by_name', 'get_efficientnet_b0_encoder', 'get_efficientnet_b1_encoder',\n           'get_efficientnet_b2_encoder', 'get_efficientnet_b3_encoder', 'get_efficientnet_b4_encoder',\n           'get_efficientnet_b5_encoder', 'get_efficientnet_b6_encoder', 'get_efficientnet_b7_encoder']\n\n\ndef _efficientnet(input_shape, blocks_args_list, global_params):\n    batch_norm_momentum = global_params.batch_norm_momentum\n    batch_norm_epsilon = global_params.batch_norm_epsilon\n\n    # Stem part\n    model_input = layers.Input(shape=input_shape)\n    x = layers.Conv2D(\n        filters=round_filters(32, global_params),\n        kernel_size=[3, 3],\n        strides=[2, 2],\n        kernel_initializer=conv_kernel_initializer,\n        padding='same',\n        use_bias=False,\n        name='stem_conv2d'\n    )(model_input)\n\n    x = layers.BatchNormalization(\n        momentum=batch_norm_momentum,\n        epsilon=batch_norm_epsilon,\n        name='stem_batch_norm'\n    )(x)\n\n    x = Swish(name='stem_swish')(x)\n\n    # Blocks part\n    idx = 0\n    drop_rate = global_params.drop_connect_rate\n    n_blocks = sum([blocks_args.num_repeat for blocks_args in blocks_args_list])\n    drop_rate_dx = drop_rate \/ n_blocks\n\n    for blocks_args in blocks_args_list:\n        assert blocks_args.num_repeat > 0\n        # Update block input and output filters based on depth multiplier.\n        blocks_args = blocks_args._replace(\n            input_filters=round_filters(blocks_args.input_filters, global_params),\n            output_filters=round_filters(blocks_args.output_filters, global_params),\n            num_repeat=round_repeats(blocks_args.num_repeat, global_params)\n        )\n\n        # The first block needs to take care of stride and filter size increase.\n        x = MBConvBlock(blocks_args, global_params, idx, drop_connect_rate=drop_rate_dx * idx)(x)\n        idx += 1\n\n        if blocks_args.num_repeat > 1:\n            blocks_args = blocks_args._replace(input_filters=blocks_args.output_filters, strides=[1, 1])\n\n        for _ in range(blocks_args.num_repeat - 1):\n            x = MBConvBlock(blocks_args, global_params, idx, drop_connect_rate=drop_rate_dx * idx)(x)\n            idx += 1\n\n    # Head part\n    x = layers.Conv2D(\n        filters=round_filters(1280, global_params),\n        kernel_size=[1, 1],\n        strides=[1, 1],\n        kernel_initializer=conv_kernel_initializer,\n        padding='same',\n        use_bias=False,\n        name='head_conv2d'\n    )(x)\n\n    x = layers.BatchNormalization(\n        momentum=batch_norm_momentum,\n        epsilon=batch_norm_epsilon,\n        name='head_batch_norm'\n    )(x)\n\n    x = Swish(name='head_swish')(x)\n\n    x = layers.GlobalAveragePooling2D(name='global_average_pooling2d')(x)\n\n    if global_params.dropout_rate > 0:\n        x = layers.Dropout(global_params.dropout_rate)(x)\n\n    x = layers.Dense(\n        global_params.num_classes,\n        kernel_initializer=dense_kernel_initializer,\n        activation='softmax',\n        name='head_dense'\n    )(x)\n\n    model = models.Model(model_input, x)\n\n    return model\n\n\ndef get_model_by_name(model_name, input_shape, classes=1000, pretrained=False):\n    \"\"\"Get an EfficientNet model by its name.\n    \"\"\"\n    blocks_args, global_params = get_efficientnet_params(model_name, override_params={'num_classes': classes})\n    model = _efficientnet(input_shape, blocks_args, global_params)\n\n    try:\n        if pretrained:\n            weights = IMAGENET_WEIGHTS[model_name]\n            weights_path = get_file(\n                weights['name'],\n                weights['url'],\n                cache_subdir='models',\n                md5_hash=weights['md5'],\n            )\n            model.load_weights(weights_path)\n    except KeyError as e:\n        print(\"NOTE: Currently model {} doesn't have pretrained weights, therefore a model with randomly initialized\"\n              \" weights is returned.\".format(e))\n\n    return model\n\n\ndef _get_efficientnet_encoder(model_name, input_shape, pretrained=False):\n    model = get_model_by_name(model_name, input_shape, pretrained=pretrained)\n    encoder = models.Model(model.input, model.get_layer('global_average_pooling2d').output)\n    encoder.layers.pop()  # remove GAP layer\n    return encoder\n\n\ndef get_efficientnet_b0_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b0', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b1_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b1', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b2_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b2', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b3_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b3', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b4_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b4', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b5_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b5', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b6_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b6', input_shape, pretrained=pretrained)\n\n\ndef get_efficientnet_b7_encoder(input_shape, pretrained=False):\n    return _get_efficientnet_encoder('efficientnet-b7', input_shape, pretrained=pretrained)\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras import models\n\n\n__all__ = ['get_efficient_unet_b0', 'get_efficient_unet_b1', 'get_efficient_unet_b2', 'get_efficient_unet_b3',\n           'get_efficient_unet_b4', 'get_efficient_unet_b5', 'get_efficient_unet_b6', 'get_efficient_unet_b7',\n           'get_blocknr_of_skip_candidates']\n\n\ndef get_blocknr_of_skip_candidates(encoder, verbose=False):\n    \"\"\"\n    Get block numbers of the blocks which will be used for concatenation in the Unet.\n    :param encoder: the encoder\n    :param verbose: if set to True, the shape information of all blocks will be printed in the console\n    :return: a list of block numbers\n    \"\"\"\n    shapes = []\n    candidates = []\n    mbblock_nr = 0\n    while True:\n        try:\n            mbblock = encoder.get_layer('blocks_{}_output_batch_norm'.format(mbblock_nr)).output\n            shape = int(mbblock.shape[1]), int(mbblock.shape[2])\n            if shape not in shapes:\n                shapes.append(shape)\n                candidates.append(mbblock_nr)\n            if verbose:\n                print('blocks_{}_output_shape: {}'.format(mbblock_nr, shape))\n            mbblock_nr += 1\n        except ValueError:\n            break\n    return candidates\n\n\ndef DoubleConv(filters, kernel_size, initializer='glorot_uniform'):\n\n    def layer(x):\n\n        x = Conv2D(filters, kernel_size, padding='same', use_bias=False, kernel_initializer=initializer)(x)\n        x = BatchNormalization()(x)\n        x = Activation('relu')(x)\n        x = Conv2D(filters, kernel_size, padding='same', use_bias=False, kernel_initializer=initializer)(x)\n        x = BatchNormalization()(x)\n        x = Activation('relu')(x)\n\n        return x\n\n    return layer\n\n\ndef UpSampling2D_block(filters, kernel_size=(3, 3), upsample_rate=(2, 2), interpolation='bilinear',\n                       initializer='glorot_uniform', skip=None):\n    def layer(input_tensor):\n\n        x = UpSampling2D(size=upsample_rate, interpolation=interpolation)(input_tensor)\n\n        if skip is not None:\n            x = Concatenate()([x, skip])\n\n        x = DoubleConv(filters, kernel_size, initializer=initializer)(x)\n\n        return x\n    return layer\n\n\ndef Conv2DTranspose_block(filters, kernel_size=(3, 3), transpose_kernel_size=(2, 2), upsample_rate=(2, 2),\n                          initializer='glorot_uniform', skip=None):\n    def layer(input_tensor):\n\n        x = Conv2DTranspose(filters, transpose_kernel_size, strides=upsample_rate, padding='same')(input_tensor)\n\n        if skip is not None:\n            x = Concatenate()([x, skip])\n\n        x = DoubleConv(filters, kernel_size, initializer=initializer)(x)\n\n        return x\n\n    return layer\n\n\n# noinspection PyTypeChecker\ndef _get_efficient_unet(encoder, out_channels=2, block_type='upsampling', concat_input=True):\n    MBConvBlocks = []\n\n    skip_candidates = get_blocknr_of_skip_candidates(encoder)\n\n    for mbblock_nr in skip_candidates:\n        mbblock = encoder.get_layer('blocks_{}_output_batch_norm'.format(mbblock_nr)).output\n        MBConvBlocks.append(mbblock)\n\n    # delete the last block since it won't be used in the process of concatenation\n    MBConvBlocks.pop()\n\n    input_ = encoder.input\n    head = encoder.get_layer('head_swish').output\n    blocks = [input_] + MBConvBlocks + [head]\n\n    if block_type == 'upsampling':\n        UpBlock = UpSampling2D_block\n    else:\n        UpBlock = Conv2DTranspose_block\n\n    o = blocks.pop()\n    o = UpBlock(512, initializer=conv_kernel_initializer, skip=blocks.pop())(o)\n    o = UpBlock(256, initializer=conv_kernel_initializer, skip=blocks.pop())(o)\n    o = UpBlock(128, initializer=conv_kernel_initializer, skip=blocks.pop())(o)\n    o = UpBlock(64, initializer=conv_kernel_initializer, skip=blocks.pop())(o)\n    if concat_input:\n        o = UpBlock(32, initializer=conv_kernel_initializer, skip=blocks.pop())(o)\n    else:\n        o = UpBlock(32, initializer=conv_kernel_initializer, skip=None)(o)\n    o = Conv2D(out_channels, (1, 1), padding='same', kernel_initializer=conv_kernel_initializer, activation=\"sigmoid\")(o)\n\n    model = models.Model(encoder.input, o)\n\n    return model\n\n\ndef get_efficient_unet_b0(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B0 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B0 model\n    \"\"\"\n    encoder = get_efficientnet_b0_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b1(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B1 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B1 model\n    \"\"\"\n    encoder = get_efficientnet_b1_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b2(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B2 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B2 model\n    \"\"\"\n    encoder = get_efficientnet_b2_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b3(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B3 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B3 model\n    \"\"\"\n    encoder = get_efficientnet_b3_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b4(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B4 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B4 model\n    \"\"\"\n    encoder = get_efficientnet_b4_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b5(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B5 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B5 model\n    \"\"\"\n    encoder = get_efficientnet_b5_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b6(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B6 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B6 model\n    \"\"\"\n    encoder = get_efficientnet_b6_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\n\n\ndef get_efficient_unet_b7(input_shape, out_channels=2, pretrained=False, block_type='transpose', concat_input=True):\n    \"\"\"Get a Unet model with Efficient-B7 encoder\n    :param input_shape: shape of input (cannot have None element)\n    :param out_channels: the number of output channels\n    :param pretrained: True for ImageNet pretrained weights\n    :param block_type: \"upsampling\" to use UpSampling layer, otherwise use Conv2DTranspose layer\n    :param concat_input: if True, input image will be concatenated with the last conv layer\n    :return: an EfficientUnet_B7 model\n    \"\"\"\n    encoder = get_efficientnet_b7_encoder(input_shape, pretrained=pretrained)\n    model = _get_efficient_unet(encoder, out_channels, block_type=block_type, concat_input=concat_input)\n    return model\nEFNS = [get_efficient_unet_b0, get_efficient_unet_b1, get_efficient_unet_b2, get_efficient_unet_b3, \n        get_efficient_unet_b4,get_efficient_unet_b5, get_efficient_unet_b6, get_efficient_unet_b7]\ndef EfficientUnet(efun=0):\n    model = EFNS[efun]((512, 512, 3),out_channels=1, pretrained=False, block_type='transpose', concat_input=True)\n    return model    \ndef dice_coef(y_true, y_pred):\n    y_true_f = tf.reshape(y_true,[-1])\n    y_pred_f = tf.reshape(y_pred,[-1])\n    intersection = tf.reduce_sum(y_true_f * y_pred_f)\n    return (2. * intersection + smooth) \/ (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\n\ndef dice_coef_loss(y_true, y_pred):\n    return 1.-dice_coef(y_true, y_pred)\nlr = 1e-3\n\ndef get_model(efun=0):\n    model = EfficientUnet(efun)\n    opt = tf.keras.optimizers.Adam(lr)\n    metrics = [\"acc\"]\n    model.compile(loss=dice_coef_loss, optimizer=opt, metrics=metrics)\n    return model\n\nmodelset = []\nfor i in range(FOLDS):\n    model = get_model(EFUN)\n    model.load_weights(f\"..\/input\/hubmapeffnetb3ns\/fold-{i}.h5\")\n    modelset.append(model)\n\n\"\"\"\n# Inference\n\"\"\"\n# https:\/\/www.kaggle.com\/leighplt\/pytorch-fcn-resnet50\ndef make_grid(shape, window=256, min_overlap=32):\n    \"\"\"\n        Return Array of size (N,4), where N - number of tiles,\n        2nd axis represente slices: x1,x2,y1,y2 \n    \"\"\"\n    x, y = shape\n    nx = x \/\/ (window - min_overlap) + 1\n    x1 = np.linspace(0, x, num=nx, endpoint=False, dtype=np.int64)\n    x1[-1] = x - window\n    x2 = (x1 + window).clip(0, x)\n    ny = y \/\/ (window - min_overlap) + 1\n    y1 = np.linspace(0, y, num=ny, endpoint=False, dtype=np.int64)\n    y1[-1] = y - window\n    y2 = (y1 + window).clip(0, y)\n    slices = np.zeros((nx,ny, 4), dtype=np.int64)\n    \n    for i in range(nx):\n        for j in range(ny):\n            slices[i,j] = x1[i], x2[i], y1[j], y2[j]    \n    return slices.reshape(nx*ny,4)\n\n@numba.njit()\ndef rle_numba(pixels):\n    size = len(pixels)\n    points = []\n    if pixels[0] == 1: points.append(0)\n    flag = True\n    for i in range(1, size):\n        if pixels[i] != pixels[i-1]:\n            if flag:\n                points.append(i+1)\n                flag = False\n            else:\n                points.append(i+1 - points[-1])\n                flag = True\n    if pixels[-1] == 1: points.append(size-points[-1]+1)    \n    return points\n\ndef rle_numba_encode(image):\n    pixels = image.flatten(order = 'F')\n    points = rle_numba(pixels)\n    return ' '.join(str(x) for x in points)\nidentity = rasterio.Affine(1, 0, 0, 0, 1, 0)\n\n# WINDOW is the size of the tile to be read by rasterio\nWINDOW = 512\n\n# Tiles will have some overlap\nMIN_OVERLAP = 32\n\n# Tiles will be resized to NEW_SIZE, which is the size of the image\n# on which, we have trained our model.\nNEW_SIZE = 512\np = pathlib.Path(os.path.join(data_path, 'hubmap-kidney-segmentation'))\nsubm = {}\n\nfor i, filename in tqdm(enumerate(p.glob('test\/*.tiff')), \n                        total = len(list(p.glob('test\/*.tiff')))):\n    \n    print(filename)\n    # save GPU quota\n    if len(list(p.glob('test\/*.tiff')))==5 and i==0:\n        dataset = rasterio.open(filename.as_posix(), transform = identity)\n        slices = make_grid(dataset.shape, window=WINDOW, min_overlap=MIN_OVERLAP)\n        preds = np.zeros(dataset.shape, dtype=np.uint8)\n        subm[i] = {'id':filename.stem, 'predicted': rle_numba_encode(preds)}\n        break\n    dataset = rasterio.open(filename.as_posix(), transform = identity)\n    slices = make_grid(dataset.shape, window=WINDOW, min_overlap=MIN_OVERLAP)\n    preds = np.zeros(dataset.shape, dtype=np.uint8)\n    \n    for (x1,x2,y1,y2) in slices:\n        image = dataset.read([1,2,3],\n                    window=Window.from_slices((x1,x2),(y1,y2)))\n        image = np.moveaxis(image, 0, -1)\n        \n        image = tf.image.convert_image_dtype(image, \n                                 tf.float32)\n        image = cv2.resize(image.numpy(), (NEW_SIZE, NEW_SIZE))\n        image = np.expand_dims(image, 0)\n        pred = 0\n        for k in range(FOLDS):\n            pred += np.squeeze(modelset[k].predict(image,verbose=0)) \/ FOLDS\n        \n        pred = cv2.resize(pred, (WINDOW, WINDOW))\n        preds[x1:x2,y1:y2] = (pred > 0.5).astype(np.uint8)\n            \n    subm[i] = {'id':filename.stem, 'predicted': rle_numba_encode(preds)}\n    del preds\n    gc.collect();\nsubmission = pd.DataFrame.from_dict(subm, orient='index')\nsubmission.to_csv('submission.csv', index=False)\n\nsubmission.head()","meta":"{'source': 'AI4Code', 'id': 'bf2a29d1a85757'}"}
{"id":"66781","text":"# \u5bfc\u5165\u5fc5\u8981\u7684\u5305\nimport tensorflow as tf\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPool2D\nfrom tensorflow.keras.layers import concatenate\nfrom tensorflow.keras.layers import ReLU\n\n# \u6838\u521d\u59cb\u5316\nkernel_init = tf.keras.initializers.glorot_uniform()\n\n# \u504f\u7f6e\u521d\u59cb\u5316\nbias_init = tf.keras.initializers.Constant(value=0.2)\n\n\n# \u751f\u6210\u6f5c\u6df1\u6a21\u5757\uff08Inception Module\uff09\u7684\u51fd\u6570\ndef inception_module(x,\n                     filters_1x1,\n                     filters_3x3_reduce,\n                     filters_3x3,\n                     filters_5x5_reduce,\n                     filters_5x5,\n                     filters_pool_proj,\n                     name=None):\n    \"\"\"\n    \u751f\u6210GoogleNet\u7684\u6f5c\u6df1\u6a21\u5757\n    \u8fd9\u91cc\u6709\u56db\u4e2a\u8f93\u5165x,\u6d88\u89e3\u503c\u5f97\u662f\u8f93\u5165\u4e3ax\u7684\u6a21\u5757\n    Args:\n        x: \u4e0a\u4e00\u5c42\u8f93\u5165\n        filters_1x1:          1\u00d71\u5377\u79ef\u6838\u6570\u91cf\n        filters_3x3_reduce:   \u6d88\u89e3\u964d\u7ef43x3\u5377\u79ef\u76841\u00d71\u5377\u79ef\u6838\u6570\u91cf\n        filters_3x3:          3\u00d73\u5377\u79ef\u6838\u6570\u91cf\n        filters_5x5_reduce:   \u6d88\u89e3\u964d\u7ef45x5\u5377\u79ef\u76841\u00d71\u5377\u79ef\u6838\u6570\u91cf\n        filters_5x5:          5\u00d75\u5377\u79ef\u6838\u6570\u91cf\n        filters_pool_proj:    \u6d88\u89e3\u964d\u7ef4\u6700\u5927\u6c60\u5316\u76841\u00d71\u5377\u79ef\u6838\u6570\u91cf\n        name:                 \u6f5c\u6df1\u6a21\u5757\u540d\u79f0\n\n    Returns\n        \u751f\u6210\u7684\u6f5c\u6df1\u6a21\u5757\u5806\u53e0\u5408\u5e76\u7279\u5f81\u56fe\n    \"\"\"\n    # \u53ef\u4ee5\u5c06Relu\u5199\u5728conv2D\u6216\u8005\u5355\u72ec\u4f5c\u4e3a\u4e00\u5c42\n    # 1\u00d71\u5377\u79ef,\u4e8c\u884c\u7b2c\u56db\u4e2a\n    conv_1x1 = Conv2D(filters_1x1,\n                      (1, 1),\n                      padding='same',\n                      activation='relu',\n                      kernel_initializer=kernel_init,\n                      bias_initializer=bias_init)(x)\n    conv_1x1 = BatchNormalization()(conv_1x1)\n\n    # \u6d88\u89e3\u964d\u7ef43x3\u5377\u79ef\u76841\u00d71\u5377\u79ef\uff0c\u4e00\u884c\u7b2c\u4e8c\u4e2a\n    conv_1x1_for_3x3 = Conv2D(filters_3x3_reduce,\n                      (1, 1),\n                      padding='same',\n                      activation='relu',\n                      kernel_initializer=kernel_init,\n                      bias_initializer=bias_init)(x)\n    conv_1x1_for_3x3 = BatchNormalization()(conv_1x1_for_3x3)\n\n    # 3x3\u5377\u79ef\uff0c\u4e8c\u884c\u7b2c\u4e8c\u4e2a\n    conv_3x3 = Conv2D(filters_3x3,\n                      (3, 3),\n                      padding='same',\n                      activation='relu',\n                      kernel_initializer=kernel_init,\n                      bias_initializer=bias_init)(conv_1x1_for_3x3)\n    conv_3x3 = BatchNormalization()(conv_3x3)  # \u4e3a\u4e86\u907f\u514d\u68af\u5ea6\u6d88\u5931\n\n    # \u6d88\u89e3\u964d\u7ef45x5\u5377\u79ef\u76841\u00d71\u5377\u79ef\uff0c\u4e00\u884c\u7b2c\u4e8c\u4e2a\n    conv_1x1_for_5x5 = Conv2D(filters_5x5_reduce,\n                      (1, 1),\n                      padding='same',\n                      activation='relu',\n                      kernel_initializer=kernel_init,\n                      bias_initializer=bias_init)(x)\n    conv_1x1_for_5x5 = BatchNormalization()(conv_1x1_for_5x5)\n\n    # 5x5\u5377\u79ef\uff0c\u4e8c\u884c\u7b2c\u4e09\u4e2a\n    conv_5x5 = Conv2D(filters_5x5, (5, 5),\n                      padding='same',\n                      activation='relu',\n                      kernel_initializer=kernel_init,\n                      bias_initializer=bias_init)(conv_1x1_for_5x5)\n    conv_5x5 = BatchNormalization()(conv_5x5)\n\n    # \u6700\u5927\u6c60\u5316\uff0c\u4e00\u884c\u7b2c\u4e00\u4e2a\n    pool = MaxPool2D((3, 3), strides=(1, 1), padding='same')(x)\n\n    # \u6d88\u89e3\u964d\u7ef4\u6700\u5927\u6c60\u5316\u76841\u00d71\u5377\u79ef\uff0c\u4e8c\u884c\u7b2c\u4e00\u4e2a\n    pool_proj = Conv2D(filters_pool_proj,\n                       (1, 1),\n                       padding='same',\n                       activation='relu',\n                       kernel_initializer=kernel_init,\n                       bias_initializer=bias_init)(pool)\n    pool_proj = BatchNormalization()(pool_proj)\n\n    # \u5806\u53e0\u5408\u5e76\uff0c\u6700\u540e\n    output = concatenate([conv_1x1, conv_3x3, conv_5x5, pool_proj], axis=3, name=name)\n\n    return output\n\"\"\"\n\u5b9a\u4e49GoogleNet\u6a21\u578b\n\"\"\"\n# \u5bfc\u5165\u5fc5\u987b\u7684\u5305\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\n\n\n# \u5b9a\u4e49 GoogleNet\u7c7b\nclass GoogleNet:\n    @staticmethod\n    def build(width, height, channel, classes):\n        \"\"\"\n        \u6839\u636e\u8f93\u5165\u6837\u672c\u7684\u7ef4\u5ea6\uff08width\u3001height\u3001channel\uff09\uff0c\u5206\u7c7b\u6570\u91cf\u521b\u5efaGoogleNet\u7f51\u7edc\u6a21\u578b\n        Args:\n            width:   \u8f93\u5165\u6837\u672c\u7684\u5bbd\u5ea6\n            height:  \u8f93\u5165\u6837\u672c\u7684\u9ad8\u5ea6\n            channel: \u8f93\u5165\u6837\u672c\u7684\u901a\u9053\n            classes: \u5206\u7c7b\u6570\u91cf\n\n        Returns:\n           GoogleNet\u7f51\u7edc\u6a21\u578b\u5bf9\u8c61\n\n        \"\"\"\n\n        input_layer = Input(shape=(width, height, channel))\n\n        # \u6838\u521d\u59cb\u5316\n        kernel_init = tf.keras.initializers.glorot_uniform()\n\n        # \u504f\u7f6e\u521d\u59cb\u5316\n        bias_init = tf.keras.initializers.Constant(value=0.2)\n\n        # \u5377\u79ef\n        x = Conv2D(64,\n                   (7, 7),\n                   padding='same',\n                   strides=(2, 2),\n                   activation='relu',\n                   name='conv_1_7x7\/2')(input_layer)\n        x = BatchNormalization()(x)\n\n        # \u6700\u5927\u6c60\u5316\n        x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_1_3x3\/2')(x)\n\n        # \u5377\u79ef\n        x = Conv2D(64,\n                   (1, 1),\n                   padding='same',\n                   strides=(1, 1),\n                   activation='relu',\n                   name='conv_2a_3x3\/1')(x)\n        x = BatchNormalization()(x)\n\n        # \u5377\u79ef\n        x = Conv2D(192,\n                   (3, 3),\n                   padding='same',\n                   strides=(1, 1),\n                   activation='relu',\n                   name='conv_2b_3x3\/1')(x)\n        x = BatchNormalization()(x)\n\n        # \u6700\u5927\u6c60\u5316\n        x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_2_3x3\/2')(x)\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=64,\n                             filters_3x3_reduce=96,\n                             filters_3x3=128,\n                             filters_5x5_reduce=16,\n                             filters_5x5=32,\n                             filters_pool_proj=32,\n                             name='inception_3a')\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=128,\n                             filters_3x3_reduce=128,\n                             filters_3x3=192,\n                             filters_5x5_reduce=32,\n                             filters_5x5=96,\n                             filters_pool_proj=64,\n                             name='inception_3b')\n\n        # \u6700\u5927\u6c60\u5316\n        x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_3_3x3\/2')(x)\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=192,\n                             filters_3x3_reduce=96,\n                             filters_3x3=208,\n                             filters_5x5_reduce=16,\n                             filters_5x5=48,\n                             filters_pool_proj=64,\n                             name='inception_4a')\n\n\n        # \u8f85\u52a9\u5206\u7c7b\u5668\n        x1 = AveragePooling2D((5, 5), strides=3)(x)\n        x1 = Conv2D(128, (1, 1), padding='same', activation='relu')(x1)\n        x1 = Flatten()(x1)\n        x1 = Dense(1024, activation='relu')(x1)\n        x1 = Dropout(0.3)(x1)\n        x1 = Dense(classes, activation='softmax', name='auxilliary_output_1')(x1)\n\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=160,\n                             filters_3x3_reduce=112,\n                             filters_3x3=224,\n                             filters_5x5_reduce=24,\n                             filters_5x5=64,\n                             filters_pool_proj=64,\n                             name='inception_4b')\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=128,\n                             filters_3x3_reduce=128,\n                             filters_3x3=256,\n                             filters_5x5_reduce=24,\n                             filters_5x5=64,\n                             filters_pool_proj=64,\n                             name='inception_4c')\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=112,\n                             filters_3x3_reduce=144,\n                             filters_3x3=288,\n                             filters_5x5_reduce=32,\n                             filters_5x5=64,\n                             filters_pool_proj=64,\n                             name='inception_4d')\n\n\n        # \u8f85\u52a9\u5206\u7c7b\u5668\n        x2 = AveragePooling2D((5, 5), strides=3)(x)\n        x2 = Conv2D(128, (1, 1), padding='same', activation='relu')(x2)\n        x2 = Flatten()(x2)\n        x2 = Dense(1024, activation='relu')(x2)\n        x2 = Dropout(0.3)(x2)\n        x2 = Dense(classes, activation='softmax', name='auxilliary_output_2')(x2)\n\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=256,\n                             filters_3x3_reduce=160,\n                             filters_3x3=320,\n                             filters_5x5_reduce=32,\n                             filters_5x5=128,\n                             filters_pool_proj=128,\n                             name='inception_4e')\n\n        # \u6700\u5927\u6c60\u5316\n        x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_4_3x3\/2')(x)\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=256,\n                             filters_3x3_reduce=160,\n                             filters_3x3=320,\n                             filters_5x5_reduce=32,\n                             filters_5x5=128,\n                             filters_pool_proj=128,\n                             name='inception_5a')\n\n        # \u6f5c\u6df1\u6a21\u5757\n        x = inception_module(x,\n                             filters_1x1=384,\n                             filters_3x3_reduce=192,\n                             filters_3x3=384,\n                             filters_5x5_reduce=48,\n                             filters_5x5=128,\n                             filters_pool_proj=128,\n                             name='inception_5b')\n\n        # \u5168\u5c40\u5e73\u5747\u6c60\u5316\n        x = GlobalAveragePooling2D(name='avg_pool_5_3x3\/1')(x)\n\n        # \u968f\u673a\u5931\u6d3b\n        x = Dropout(0.40)(x)\n\n        # \u5168\u8fde\u63a5\n        x = Dense(classes, activation='softmax', name='output')(x)\n\n        # \u521b\u5efaGoogleNet\u6a21\u578b\n        return Model(input_layer, [x, x1, x2], name='inception_v1')\n        # return Model(input_layer, x, name='inception_v1')\n\n\n# \u6d4b\u8bd5GoogleNet\u7c7b\u5b9e\u4f8b\u5316\u5e76\u8f93\u51faGoogleNet\u6a21\u578b\u7684\u6982\u8981\u4fe1\u606f\nif __name__ == \"__main__\":\n    model = GoogleNet.build(width=224, height=224, channel=3, classes=196)\n    print(model.summary())\n\"\"\"\ntraining\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# \u8bad\u7ec3\u65e5\u5fd7\u7ed8\u56fe\u7c7b\nclass HistoryGraph:\n    def __init__(self, history, epochs, title, file_path):\n        # \u8bad\u7ec3\u65e5\u5fd7\n        self.history = history\n        # \u8bad\u7ec3\u8d9f\u6570\n        self.epochs = epochs\n        # \u56fe\u6807\u9898\n        self.title = title\n        # \u56fe\u50cf\u5b58\u76d8\u6587\u4ef6\u8def\u5f84\u540d\n        self.file_path = file_path\n\n    def draw(self):\n        figure, (ax1, ax2) = plt.subplot(1, 2, figsize=(12, 4))\n        figure.suptitle(self.title, fontsize=12)\n        figure.subplots_adjust(top=0.85, wspace=0.3)\n        epoch_list = list(range(1, self.epochs + 1))\n        ax1.plot(epoch_list,\n                 self.history.history['accuracy'],\n                 label='Train Accuracy'\n                 )\n        ax1.plot(epoch_list,\n                 self.history, history['accuracy'],\n                 label='Validation Accuracy', )\n        ax1.set_xticks(np.arange(0, self.epochs + 1, 5))\n        ax1.set_ylabel(\"Accuracy Value\")\n        ax1.set_xlabel(\"Epoch #\")\n        ax1.set_title(\"Accuracy\")\n        ax1.legend(loc=\"best\")\n\n        ax2.plot(epoch_list, self.history.history[\"loss\"], label=\"Training Loss\")\n        ax2.plot(epoch_list, self.history.history[\"val_loss\"], label=\"Validation Loss\")\n        ax2.set_xticks(np.arange(0, self.epochs + 1, 5))\n        ax2.set_ylabel(\"Loss Value\")\n        ax2.set_xlabel(\"Epoch #\")\n        ax2.set_title(\"Loss\")\n        ax2.legend(loc=\"best\")\n        plt.savefig(self.file_path)\n        plt.close()\n\n\n# \u8bad\u7ec3\u65e5\u5fd7\u7ed8\u56fe\u7c7b(\u652f\u6301Inception v1\u7684\u4e24\u4e2a\u65c1\u8def\u5206\u7c7b\u5668)\nclass HistoryGraphV1:\n    def __init__(self, history, epochs, title, file_path):\n        # \u8bad\u7ec3\u65e5\u5fd7\n        self.history = history\n        # \u8bad\u7ec3\u8d9f\u6570\n        self.epochs = epochs\n        # \u56fe\u6807\u9898\n        self.title = title\n        # \u56fe\u50cf\u5b58\u76d8\u6587\u4ef6\u8def\u5f84\u540d\n        self.file_path = file_path\n\n    def draw(self):\n        figure, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\n        figure.suptitle(self.title, fontsize=12)\n        figure.subplots_adjust(top=0.85, wspace=0.3)\n\n        epoch_list = list(range(1, self.epochs + 1))\n        ax1.plot(epoch_list,\n                 self.history.history['output_accuracy'],\n                 label='Train Accuracy'\n                 )\n        ax1.plot(epoch_list,\n                 self.history.history['val_output_accuracy'],\n                 label='Validation Accuracy', )\n        ax1.set_xticks(np.arange(0, self.epochs + 1, 5))\n        ax1.set_ylabel(\"Accuracy Value\")\n        ax1.set_xlabel(\"Epoch #\")\n        ax1.set_title(\"Accuracy\")\n        ax1.legend(loc=\"best\")\n\n        ax2.plot(epoch_list, self.history.history[\"output_loss\"], label=\"Training Loss\")\n        ax2.plot(epoch_list, self.history.history[\"val_output_loss\"], label=\"Validation Loss\")\n        ax2.set_xticks(np.arange(0, self.epochs + 1, 5))\n        ax2.set_ylabel(\"Loss Value\")\n        ax2.set_xlabel(\"Epoch #\")\n        ax2.set_title(\"Loss\")\n        ax2.legend(loc=\"best\")\n        plt.savefig(self.file_path)\n        plt.close()\n# \u5bfc\u5165\u5fc5\u8981\u7684\u5305\nimport os\n\nfrom tensorflow.keras.callbacks import Callback\n\n\n# \u6a21\u578b\u5b58\u76d8\u68c0\u67e5\u70b9\uff0c\u6bcf\u8bad\u7ec310\u8d9f\u4fdd\u5b58\u4e00\u6b21\u6a21\u578b\nclass EpochCheckpoint(Callback):\n    def __init__(self, output_path, every=10, start_at=0):\n        # \u8c03\u7528\u7236\u7c7b\u7684\u6784\u9020\u51fd\u6570\n        super(Callback, self).__init__()\n        self.output_path = output_path  # \u6a21\u578b\u4fdd\u5b58\u76ee\u5f55\n        # \u95f4\u9694\u8d9f\u6570\n        self.every = every\n        # \u8d77\u59cb\u8d9f\u6570\uff08\u5f53\u524d\u8d9f\u6570\uff09\n        self.start_epoch = start_at\n\n    def on_epoch_end(self, epoch, logs={}):\n        # \u68c0\u67e5\u662f\u5426\u8981\u5411\u78c1\u76d8\u4fdd\u5b58\u6a21\u578b\n        if (self.start_epoch + 1) % self.every == 0:\n            p = os.path.sep.join([self.output_path,\n                                  \"epoch_{}.h5\".format(self.start_epoch + 1)])\n            self.model.save(p, overwrite=True)\n        # \u589e\u52a0\u5185\u90e8\u7684\u8d9f\u6570\u8ba1\u6570\u5668\n        self.start_epoch += 1\nfrom tensorflow.keras.optimizers import SGD, Adam, Adamax\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport math\n\n# \u8bad\u7ec3\u6837\u672c\u5168\u8def\u5f84\u6587\u4ef6\u540d\u79f0\ntrain_dirs = '\/kaggle\/input\/stanford-car-dataset-by-classes-folder\/car_data\/car_data\/train'\n# \u6d4b\u8bd5\u6837\u672c\u5168\u8def\u5f84\u6587\u4ef6\u540d\u79f0\ntest_dirs ='\/kaggle\/input\/stanford-car-dataset-by-classes-folder\/car_data\/car_data\/test'\n\nMODEL_FILE = \"\/kaggle\/working\/googlenet.h5\"\n\nOUTPUT_PATH = \"\/kaggle\/working\"\n\n# \u521d\u59cb\u5316\u4f18\u5316\u5668\nepochs = 50\nbatch_size = 64\ninitial_lrate = 0.01\n\n\n#  \u968f\u8bad\u7ec3\u8d9f\u6570\u964d\u4f4e\u5b66\u4e60\u7387\ndef decay(epoch, steps=100):\n    initial_lrate = 0.01\n    drop = 0.96\n    epochs_drop = 8\n    lrate = initial_lrate * math.pow(drop, math.floor((1 + epoch) \/ epochs_drop))\n    return lrate\n\n\n# \u521d\u59cb\u5316\u5b66\u4e60\u8c03\u5ea6\u5668\nlr_scheduler = LearningRateScheduler(decay, verbose=1)\n\n\n# \u6784\u9020\u7528\u4e8e\u6570\u636e\u589e\u5f3a\u7684\u8bad\u7ec3\u56fe\u50cf\u751f\u6210\u5668\ntrain_datagen = ImageDataGenerator(rotation_range=20,\n                                   zoom_range=0.15,\n                                   width_shift_range=0.2,  # randomly shift images horizontally (fraction of total width)\n                                   height_shift_range=0.2, # randomly shift images vertically (fraction of total height))\n                                   shear_range=0.15,\n                                   horizontal_flip=True,\n                                   rescale=1.\/255,\n                                   fill_mode=\"nearest\")  \n\nval_datagen = ImageDataGenerator(rescale=1.\/255)\n\n\ntrainGen = train_datagen.flow_from_directory(\n        train_dirs,\n        target_size=(224, 224),\n        batch_size=batch_size,\n        shuffle=True)\n\nvalGen = val_datagen.flow_from_directory(\n        test_dirs,\n        target_size=(224, 224),      \n        batch_size=batch_size,\n        shuffle=True)\n\n\nopt = SGD(lr=initial_lrate, momentum=0.9, nesterov=False)\n#opt = Adamax()\nmodel = GoogleNet.build(width=224, height=224, channel=3, classes=196)\n\nmodel.compile(loss=[\"categorical_crossentropy\",\n                    \"categorical_crossentropy\",\n                    \"categorical_crossentropy\"],\n              loss_weights=[1.0, 0.3, 0.3],\n              optimizer=opt,\n              metrics=[\"accuracy\"])\n\n\n\n# 8\u3001\u6784\u9020\u8bad\u7ec3\u56de\u8c03\u5217\u8868\uff0c\u8fd9\u91cc\u4e3b\u8981\u662f\u7ed8\u56fe\u56de\u8c03\u548c\u5b66\u4e60\u901f\u7387\u8c03\u6574\u56de\u8c03\n\ncallbacks = [\n    EpochCheckpoint(OUTPUT_PATH, every=10, start_at=0),\n    lr_scheduler]\n\nhistory = model.fit_generator(trainGen,\n                              steps_per_epoch=8144 \/\/ batch_size,\n                              epochs=epochs,\n                              validation_data=valGen,\n                              validation_steps=8041 \/\/ batch_size,\n                              max_queue_size=batch_size * 2,\n                              callbacks=callbacks,\n                              verbose=1)\n# 10\u3001\u5c06\u8bad\u7ec3\u5f97\u5230\u7684\u6a21\u578b\u4fdd\u5b58\u5230\u6587\u4ef6\nprint(\"[\u4fe1\u606f] \u4fdd\u5b58\u6a21\u578b...\")\nmodel.save(MODEL_FILE, overwrite=True)\n\"\"\"\n\u521b\u5efa\u7ed8\u56fe\u7c7b\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\nt = f.suptitle('320182359_Dc GoogleNet Training Performance', fontsize=12)\nf.subplots_adjust(top=0.85, wspace=0.3)\n\nepoch_list = list(range(1,51))\nax1.plot(epoch_list, history.history['output_accuracy'], label='Train Accuracy')\nax1.plot(epoch_list, history.history['val_output_accuracy'], label='Validation Accuracy')\nax1.set_xticks(np.arange(0, 51, 5))\nax1.set_ylabel('Accuracy Value')\nax1.set_xlabel('Epoch #')\nax1.set_title('Accuracy')\nl1 = ax1.legend(loc=\"best\")\n\nax2.plot(epoch_list, history.history['output_loss'], label='Train Loss')\nax2.plot(epoch_list, history.history['val_output_loss'], label='Validation Loss')\nax2.set_xticks(np.arange(0, 51, 5))\nax2.set_ylabel('Loss Value')\nax2.set_xlabel('Epoch #')\nax2.set_title('Loss')\nl2 = ax2.legend(loc=\"best\")","meta":"{'source': 'AI4Code', 'id': '7b0b66dd107f5a'}"}
{"id":"23448","text":"\"\"\"\n# Imports\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\"\"\"\n# Load dataset\n\"\"\"\ntrain = pd.read_csv('..\/input\/tabular-playground-series-aug-2021\/train.csv')\ntest = pd.read_csv('..\/input\/tabular-playground-series-aug-2021\/test.csv')\nprint('train shape:',train.shape)\nprint('test shape:',test.shape)\ntrain.head()\n# Train data\nX=train.drop(columns = ['loss','id'])\ny=train['loss'].values\n\n# Test data\nX_test=test.drop(columns = ['id'])\nprint('Train set:', X.shape)\nprint('Test set:', X_test.shape)\n\"\"\"\n# Train Catboost model\n\"\"\"\nfrom catboost import CatBoostRegressor\n\nmodel = CatBoostRegressor(random_state = 44,\n                         thread_count = 4,\n                         verbose = False,\n                         loss_function = 'RMSE',\n                         eval_metric = 'RMSE',\n                         od_type = \"Iter\",\n                         early_stopping_rounds = 500,\n                         iterations = 10000,\n                         task_type = \"CPU\")\nmodel.fit(X, y, verbose=0)\n\"\"\"\n# Model performance\n\"\"\"\nfrom sklearn import metrics\n\nprint('R2 score: ', model.score(X, y))\npredicted = model.predict(X)\nrmse = metrics.mean_squared_error(y, predicted, squared=False)\nprint('RMSE: ', rmse)\n\"\"\"\n# Prediction\n\"\"\"\ny_pred = model.predict(X_test)\n\"\"\"\n# Submission\n\"\"\"\npreds = pd.read_csv(\"..\/input\/tabular-playground-series-aug-2021\/sample_submission.csv\")\npreds.loss = y_pred\npreds.head()\npreds.to_csv('submission_catboost_101.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '2b263fe970224e'}"}
{"id":"20669","text":"\"\"\"\n# Don't Forget To UpVote :)\n\"\"\"\n# 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 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\nimport matplotlib.pyplot as plt\nplt.style.use('dark_background')\ndata = pd.read_csv('\/kaggle\/input\/insurance\/insurance.csv')\ndata.head()\ndata.shape\ndata.describe(include = 'all')\nimport seaborn as sns\nsns.pairplot(data)\ndata.hist(by = 'sex', column = 'charges')\ndata.hist(by = 'smoker', column = 'charges')\ndata.groupby(data['children']).count()\ndata.groupby(data['region']).count()\ndata.groupby(data['smoker']).count()\nsns.boxplot(x = 'sex', y = 'age', data = data)\nsns.boxplot(x= 'sex' , y = 'charges', data = data)\nsns.boxplot(x= 'sex' , y = 'bmi', data = data)\ndata.corr()\nimport matplotlib.pyplot as plt\ncorr_new_train=data.corr()\nplt.figure(figsize=(5,15))\nsns.heatmap(corr_new_train[['charges']].sort_values(by=['charges'],ascending=False).head(30),annot_kws={\"size\": 16},vmin=-1, cmap='PiYG', annot=True)\nsns.set(font_scale=2)\ndata['sex'] = pd.get_dummies(data['sex'],drop_first = True )\ndata['smoker'] = pd.get_dummies(data['smoker'],drop_first = True )\n#data['region'] = pd.get_dummies(data['region'],drop_first = True )\n\n#new_data = pd.get_dummies(data['region'],drop_first = True )\n#data = pd.concat([new_data,data], axis = 1)\ndata.head()\ndata['region'] = pd.get_dummies(data['region'])\nplt.style.use('dark_background')\nfig, axes = plt.subplots(4, 2,figsize=(20,80))\nfig.subplots_adjust(hspace=0.2)\ncolors=[plt.cm.prism_r(each) for each in np.linspace(0, 1, len(data.columns))]\nfor i,ax,color in zip(data.columns,axes.flatten(),colors):\n    sns.regplot(x=data[i], y=data[\"charges\"], fit_reg=True,marker='o',scatter_kws={'s':50,'alpha':0.8},color=color,ax=ax)\n    plt.xlabel(i,fontsize=12)\n    plt.ylabel('charges',fontsize=12)\n    ax.set_yticks(np.arange(100,90001,10000))\n    ax.set_title('charges'+' - '+str(i),color=color,fontweight='bold',size=20)\n\"\"\"\n# Predictive Analysis\n\"\"\"\nX = data.iloc[:,:-1].values\ny = data.iloc[:,-1].values\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nfrom sklearn.tree import DecisionTreeRegressor\nclf1 = DecisionTreeRegressor()\nclf1.fit(X_train,y_train)\npred = clf1.predict(X_test)\nclf1.score(X_test,y_test)\nfrom sklearn import metrics\nmetrics.scorer.r2_score(pred,y_test)\nsns.set(style = 'darkgrid', color_codes = True)\n\n\nwith sns.axes_style('white'):\n    sns.jointplot(x = y_test, y = pred, kind = 'reg', color = 'k')\nfrom xgboost import XGBRegressor\n\nmy_model = XGBRegressor(n_estimators=10000, learning_rate=0.12, n_job= 2)\nmy_model.fit(X_train, y_train,\n             early_stopping_rounds=10, \n             eval_set=[(X_train, y_train)], \n             verbose=1)\ny_head=my_model.predict(X_test)\nprint('-'*10+'XGBRegressor'+'-'*10)\nprint('R square Accuracy: ',metrics.scorer.r2_score(y_test,y_head))\nprint('Mean Absolute Error Accuracy: ',metrics.scorer.mean_absolute_error(y_test,y_head))\nprint('Mean Squared Error Accuracy: ',metrics.scorer.mean_squared_error(y_test,y_head))\nsns.set(style = 'darkgrid', color_codes = True)\n\n\nwith sns.axes_style('white'):\n    sns.jointplot(x = y_test, y = y_head, kind = 'reg', color = 'k')","meta":"{'source': 'AI4Code', 'id': '25ec1358cd5283'}"}
{"id":"72505","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style='whitegrid', palette='muted')\nimport warnings\nwarnings.simplefilter(\"ignore\")\nnp.random.seed(99)\n\"\"\"\n# Load Data\n\"\"\"\ntrain = pd.read_csv('..\/input\/titanic\/train.csv')\ntest = pd.read_csv('..\/input\/titanic\/test.csv')\n\"\"\"\n# EDA\n\"\"\"\n# useful functions\n\ndef get_NaN(df):\n    N = df.shape[0]\n    ndf = pd.DataFrame({'any NaN': df.apply(lambda x: x.isna().any()),  \n                        '# NaN': df.apply(lambda x: x.isna().sum()), \n                        '% NaN': df.apply(lambda x: x.isna().sum() \/ N * 100),\n                        '# unique': df.apply(lambda x: x.nunique())\n                        })\n    ndf['% NaN'] = np.round(ndf['% NaN'], 1)\n    return ndf\n        \n        \ndef plot_dist(df, feat):\n    fig, ax = plt.subplots(1, 2, figsize=(18,4))\n    for i, n in enumerate(['no', 'yes']):\n        y = df[df['Survived']==i][feat]\n        sns.distplot(y, ax=ax[0], label=n)\n        sns.distplot(np.log1p(y), ax=ax[1], label=n)\n    ax[0].legend()\n    ax[1].legend()\n    ax[1].set_xlabel(f'log1p {feat}')\n\"\"\"\n## <p style='color:blue'> General Information <\/p>\n\"\"\"\ntrain.info()\ntrain.head()\n\"\"\"\n## <p style='color:blue'> Missing Values <\/p>\n\"\"\"\n# train set\nget_NaN(train)\n# test set\nget_NaN(test)\n\"\"\"\n## <p style='color:blue'> Target <\/p>\n\"\"\"\nsns.countplot(train['Survived']);\n\ntrain['Survived'].value_counts() \/ len(train)\n\"\"\"\n## <p style='color:blue'> Categorical Features <\/p>\n\"\"\"\n# Pclass\nsns.countplot(x='Pclass', hue='Survived', data=train);\n# Sex\nsns.countplot(x='Sex', hue='Survived', data=train);\n# Embarked\nsns.countplot(x='Embarked', hue='Survived', data=train);\n\"\"\"\n## <p style='color:blue'> Numerical Features <\/p>\n\"\"\"\n# Age\nplot_dist(train, 'Age')\n# SibSp\nsns.countplot(x='SibSp', hue='Survived', data=train);\n# Parch\n# fig, ax = plt.subplots(figsize=(18,4))\nsns.countplot(x='Parch', hue='Survived', data=train);\n# Fare\nplot_dist(train, 'Fare')\n\"\"\"\n# Features Engineering\n\"\"\"\n# Ticket\n# Get the number of components separated by \"space\" in the ticket name\ntrain['Ticket'] = train['Ticket'].apply(lambda x: len(x.split(' ')))\ntest['Ticket'] = test['Ticket'].apply(lambda x: len(x.split(' ')))\nsns.countplot(x='Ticket', hue='Survived', data=train);\n# Cabin\n\n# Define NaN as a new category (n)\ntrain['Cabin'].fillna('N', inplace=True)\ntest['Cabin'].fillna('N', inplace=True)\n\n# Get the first letter of the cabin name\ntrain['Cabin'] = train['Cabin'].apply(lambda x: x[0])\ntest['Cabin'] = test['Cabin'].apply(lambda x: x[0])\nsns.countplot(x='Cabin', hue='Survived', data=train);\n# Data Imputation\n\n# Age\nmed = train['Age'].median()\ntrain['Age'].fillna(med, inplace=True)\ntest['Age'].fillna(med, inplace=True)\n\n# Fare (test data)\nmed = test['Fare'].median()\ntest['Fare'].fillna(med, inplace=True)\n\"\"\"\n# Label Encoding\n\"\"\"\ncols = ['Sex', 'Ticket', 'Cabin', 'Embarked']\nfor col in cols:\n    encoding = {j:i for i,j in enumerate(train[col].unique())}\n    train[col] = train[col].map(encoding).values\n    test[col] = test[col].map(encoding).values\ntrain.head()\n\"\"\"\n# Correlation\n\"\"\"\ncorr = train.corr()\ncorr.style.background_gradient(cmap='coolwarm').set_precision(2)\n\"\"\"\n# One Hot Encoding\n\"\"\"\ncols = ['Ticket', 'Cabin', 'Embarked']\n\n# copy features\nfor col in cols:\n    train[f'{col}_LE'] = train[col]\n    test[f'{col}_LE'] = test[col]\n\ntrain = pd.get_dummies(train, columns=cols)\ntest = pd.get_dummies(test, columns=cols)\ntrain.columns\n# correlation\ncorr = train.corr()\ncorr.style.background_gradient(cmap='coolwarm').set_precision(2)\n\"\"\"\n# Models\n\"\"\"\n# target\ny_train = train['Survived']\n\n# features\nX_train = train.drop(['Survived'], axis=1)\nX_test = test\nlen(X_train.columns), len(X_test.columns)\n[i for i in X_train.columns if i not in X_test.columns]\n\"\"\"\n## <p style='color:blue'> Logistic Regression <\/p>\n\"\"\"\n# drop some features\nX_train.drop(['PassengerId', 'Name', 'Cabin_8', 'Embarked_3'], axis=1, inplace=True)\nX_test.drop(['PassengerId', 'Name'], axis=1, inplace=True)\n\n# scale features\nfor col in X_train.columns:\n    min_ = X_train[col].min()\n    max_ = X_test[col].max()\n    intv = max_ - min_\n    X_train[col] = (X_train[col] - min_) \/ intv\n    X_test[col] = (X_test[col] - min_) \/ intv\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\ndef CV_Logistic_Regression(X_train, y_train, X_test, n_folds=5):\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = 99)\n    \n    # Create oof sets for prediction storage.\n    oof_train = np.zeros(X_train.shape[0])\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n    \n    # Emptly list to store accuracy for each fold\n    fold_acc = []\n\n    for ifold, (tr_index, val_index) in enumerate(kf.split(X = X_train, y = y_train)):\n\n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[tr_index,:]\n        X_val = X_train.iloc[val_index,:]\n        y_tr = y_train[tr_index]\n        y_val = y_train[val_index]\n\n        # Train model\n        model = LogisticRegression(random_state=0).fit(X_tr, y_tr)\n\n        # Predict validation and test data and store them in oof sets.\n        proba_val = model.predict_proba(X_val)[:,1]\n        oof_train[val_index] = np.where(proba_val>0.5, 1, 0)\n        proba_test = model.predict_proba(X_test)[:,1]\n        oof_test[:, ifold] = np.where(proba_test>0.5, 1, 0)\n        \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[val_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n\n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc = round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n    \n    return oof_train, oof_test, acc\noof_train_LogReg, oof_test_LogReg, acc_LogReg = CV_Logistic_Regression(X_train, y_train, X_test)\n\"\"\"\n## <p style='color:blue'> Support Vector Machine (SVM) <\/p>\n\"\"\"\nfrom sklearn.svm import SVC\ndef CV_SVM(X_train, y_train, X_test, n_folds=5):\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = 99)\n    \n    # Create oof sets for prediction storage.\n    oof_train = np.zeros(X_train.shape[0])\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n    \n    # Emptly list to store accuracy for each fold\n    fold_acc = []\n\n    for ifold, (tr_index, val_index) in enumerate(kf.split(X = X_train, y = y_train)):\n\n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[tr_index,:]\n        X_val = X_train.iloc[val_index,:]\n        y_tr = y_train[tr_index]\n        y_val = y_train[val_index]\n\n        # Train model\n        model = SVC()\n        model.fit(X_tr, y_tr)\n\n        # Predict validation and test data and store them in oof sets.\n        oof_train[val_index] = model.predict(X_val)\n        oof_test[:, ifold] = model.predict(X_test)\n        \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[val_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n\n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc =round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n    \n    return oof_train, oof_test, acc\noof_train_SVM, oof_test_SVM, acc_SVM = CV_SVM(X_train, y_train, X_test)\n\"\"\"\n## <p style='color:blue'> Decision Tree <\/p>\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\ndef CV_Decision_Tree(X_train, y_train, X_test, n_folds=5):\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = 99)\n    \n    # Create oof sets for prediction storage.\n    oof_train = np.zeros(X_train.shape[0])\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n    \n    # Emptly list to store accuracy for each fold\n    fold_acc = []\n\n    for ifold, (tr_index, val_index) in enumerate(kf.split(X = X_train, y = y_train)):\n\n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[tr_index,:]\n        X_val = X_train.iloc[val_index,:]\n        y_tr = y_train[tr_index]\n        y_val = y_train[val_index]\n\n        # Train model\n        model = DecisionTreeClassifier(random_state=0)\n        model.fit(X_tr, y_tr)\n\n        # Predict validation and test data and store them in oof sets.\n        oof_train[val_index] = model.predict(X_val)\n        oof_test[:, ifold] = model.predict(X_test)\n        \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[val_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n\n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc = round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n    \n    return oof_train, oof_test, acc\noof_train_DecisionTree, oof_test_DecisionTree, acc_DecisionTree = CV_Decision_Tree(X_train, y_train, X_test)\n\"\"\"\n### <p style='color:blue'> Random Forest <\/p>\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\ndef CV_Random_Forest(X_train, y_train, X_test, n_folds=5):\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = 99)\n    \n    # Create oof sets for prediction storage.\n    oof_train = np.zeros(X_train.shape[0])\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n    \n    # Emptly list to store accuracy for each fold\n    fold_acc = []\n\n    for ifold, (tr_index, val_index) in enumerate(kf.split(X = X_train, y = y_train)):\n\n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[tr_index,:]\n        X_val = X_train.iloc[val_index,:]\n        y_tr = y_train[tr_index]\n        y_val = y_train[val_index]\n\n        # Train model\n        model = RandomForestClassifier(max_depth=5, random_state=0)\n        model.fit(X_tr, y_tr)\n\n        # Predict validation and test data and store them in oof sets.\n        oof_train[val_index] = model.predict(X_val)\n        oof_test[:, ifold] = model.predict(X_test)\n        \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[val_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n\n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc = round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n    \n    return oof_train, oof_test, acc\noof_train_RandomForest, oof_test_RandomForest, acc_RandomForest = CV_Random_Forest(X_train, y_train, X_test)\n\"\"\"\n## <p style='color:blue'> Artificial Neural Networks <\/p>\n\"\"\"\nimport tensorflow as tf\ndef build_model(Nfeatures):\n    tf.keras.backend.clear_session()\n    # set random seed for reproducibility\n    tf.random.set_seed(99)\n\n    # define a model\n    model = tf.keras.Sequential()\n\n    # add the first hidden layer\n    model.add(tf.keras.layers.Dense(units = 8, activation = 'linear', input_dim = Nfeatures))\n    \n#     # add regularization\n#     model.add(tf.keras.layers.Dropout(0.2))\n\n#     # add the second hidden layer\n#     model.add(tf.keras.layers.Dense(units = 16, activation = 'linear'))\n    \n#     # add regularization\n#     model.add(tf.keras.layers.Dropout(0.2))\n    \n    # add the output layer\n    model.add(tf.keras.layers.Dense(units = 1, activation = 'sigmoid'))\n\n    # compile the model\n    model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) \n    \n    return model\nmodel = build_model(X_train.shape[1])\nmodel.summary()\ndef CV_ANN(X_train, y_train, X_test, n_folds=5, seed=99):\n    \n    # Kfold split\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = seed)\n\n    # Create oof sets for prediction storage.\n    oof_train = np.zeros((X_train.shape[0]))\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n    \n    # Save all models validation accuracy\n    fold_acc = []\n    \n    # Define early stopping\n    earlystop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)\n        \n    for ifold, (train_index, valid_index) in enumerate(kf.split(X=X_train, y=y_train)):\n        \n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[train_index,:]\n        X_val = X_train.iloc[valid_index,:]\n        y_tr = y_train[train_index]\n        y_val = y_train[valid_index]\n        \n        # Restart model\n        model = build_model(X_tr.shape[1])\n        \n        # Train model\n        model.fit(\n            X_tr,\n            y_tr,\n            batch_size = 8,\n            epochs = 100,\n            validation_data = (X_val, y_val),\n            verbose = 0,\n            callbacks = [earlystop])\n        \n        # Prediction on validation data and store them in oof (out of folds) sets\n        oof_train[valid_index] = np.where(model.predict(X_val)[:,0]>0.5, 1, 0)\n        oof_test[:, ifold] = np.where(model.predict(X_test)[:,0]>0.5, 1, 0)\n        \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[valid_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n             \n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc = round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n\n    return oof_train, oof_test, acc\noof_train_ANN, oof_test_ANN, acc_ANN = CV_ANN(X_train, y_train, X_test)\n\"\"\"\n## <p style='color:blue'> Gradient Boosted Trees with LGBM <\/p>\n\"\"\"\nimport lightgbm as lgb\ndef CV_LGBM(X_train, y_train, X_test, n_folds=5, early_stop=None):\n    kf = StratifiedKFold(n_splits = n_folds, shuffle = True, random_state = 99)\n    \n    # Create oof sets for prediction storage.\n    oof_train = np.zeros(X_train.shape[0])\n    oof_test = np.zeros((X_test.shape[0], n_folds))\n\n    gbm_history, fi, fold_acc = {}, [], []\n    \n    for ifold, (tr_index, val_index) in enumerate(kf.split(X = X_train, y = y_train)):\n\n        # Create train and validation sets based on KFold indices.\n        X_tr = X_train.iloc[tr_index,:]\n        X_val = X_train.iloc[val_index,:]\n        y_tr = y_train[tr_index]\n        y_val = y_train[val_index]\n\n        dtrain = lgb.Dataset(X_tr, y_tr)\n        dvalid = lgb.Dataset(X_val, y_val)\n\n        # Train LightGBM model\n        params ={\n            'task': 'train',\n            'boosting': 'gbdt',\n            'nthread': 2,\n            'objective': 'binary',\n            'metrics': 'binary',\n            'learning_rate': 0.01,\n            'num_leaves': 7,\n            'max_depth': 20,\n            'min_data_in_leaf': 100,\n            'seed': 0,\n            'feature_fraction': 0.8,\n            'bagging_fraction': 0.6,\n            'bagging_freq': 1,\n            'verbose': -1}\n        model = lgb.train(params = params, train_set = dtrain, evals_result = gbm_history, \n                          num_boost_round = 100000, valid_sets = [dtrain, dvalid], \n                          early_stopping_rounds = early_stop, verbose_eval = 0)\n\n        # Predict validation and test data and store them in oof sets.\n        proba_train = model.predict(X_val, num_iteration = model.best_iteration)\n        oof_train[val_index] = np.where(proba_train > 0.5, 1, 0)\n        proba_test = model.predict(X_test, num_iteration = model.best_iteration)\n        oof_test[:, ifold] = np.where(proba_test > 0.5, 1, 0)\n\n        # feature importance\n        fi.append(model.feature_importance())\n    \n        # Accuracy\n        acc = accuracy_score(y_val, oof_train[val_index])\n        \n        print('FOLD: {} \\t Acc: {:.3f}'.format(ifold, acc))\n            \n        fold_acc.append(acc)\n             \n    print(f'\\nMEAN Acc\\t: {round(np.mean(fold_acc), 3)}')\n    acc = round(accuracy_score(y_train, oof_train), 3)\n    print(f'ACTUAL Acc\\t: {acc}')\n    print(f'STD Acc\\t\\t: {round(np.std(fold_acc), 3)}')\n    \n    return oof_train, oof_test, acc, fi\n# drop one-hot-encoding\ndropf = ['Ticket_0', 'Ticket_1', 'Ticket_2', 'Cabin_0', 'Cabin_1', 'Cabin_2', 'Cabin_3', 'Cabin_4', 'Cabin_5',\n         'Cabin_6', 'Cabin_7', 'Embarked_0', 'Embarked_1', 'Embarked_2']\noof_train_LGBM, oof_test_LGBM, acc_LGBM, fi = CV_LGBM(X_train.drop(dropf, axis=1), \n                                            y_train, X_test.drop(dropf, axis=1), \n                                            early_stop=200)\nusecols = [f for f in X_train.columns if f not in dropf]\nImp_feats = {}\nmean_vals = np.mean(fi,axis=0)\nfor col, val in zip(usecols, mean_vals):\n    Imp_feats.update({col: val})\ndata = pd.Series(Imp_feats).sort_values(ascending=False)\nfig, ax = plt.subplots(figsize=(18,12))\nsns.barplot(data.values, data.index, ax=ax)\nax.set_title('Features Importance');\n\"\"\"\n# Summary\n\"\"\"\nresults = {\n    'Logistic_Regression': acc_LogReg,\n    'SVM': acc_SVM,\n    'Decision Tree': acc_DecisionTree,\n    'Random Forest': acc_RandomForest,\n    'Neural Networks': acc_ANN,\n    'LGBM': acc_LGBM\n}\npd.Series(results)\n\"\"\"\n# Submission\n\"\"\"\nsubmit = pd.read_csv('..\/input\/titanic\/gender_submission.csv')\nsubmit.head()\npred = np.mean(oof_test_LGBM, axis=1)\nsubmit['Survived'] = np.where(pred>0.5, 1, 0)\nsubmit.head()\n# save\nsubmit.to_csv(\"pred.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '85731e76cd8ce2'}"}
{"id":"17765","text":"\"\"\"\n# NFL Rules Wordcloud\n\"\"\"\nfrom wordcloud import WordCloud\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\negg_mask = np.array(Image.open('..\/input\/externalnfl\/egg.png'))\npunter_mask = np.array(Image.open('..\/input\/externalnfl\/punter.png'))\nwith open('..\/input\/externalnfl\/rules_nlp.txt', 'r') as txt:\n    rules = ' '.join([line for line in txt]).title()\nwc = WordCloud(background_color='white', max_words=2000, mask=egg_mask)\nwc.generate(rules)\nwc.to_file('ball_rule_word_cloud.png')\nwc.to_image()\nwc = WordCloud(background_color='white', max_words=2000, mask=punter_mask)\nwc.generate(rules)\nwc.to_file('punter_rule_word_cloud.png')\nwc.to_image()","meta":"{'source': 'AI4Code', 'id': '2073a494359682'}"}
{"id":"36656","text":"import pandas as pd\ntrain = pd.read_csv('\/kaggle\/input\/titanic\/train.csv', index_col=0)\ntest = pd.read_csv('\/kaggle\/input\/titanic\/test.csv', index_col=0)\n\"\"\"\n# data analysis\n\"\"\"\ntrain.groupby(['Sex', 'Survived']).size() * 100 \/ len(train)\n\"\"\"\nThe value shown above are in percentage.\nA lot of male died (52%). A lot of female survived (26%).\nHence by answering `male=died` and `female=survived` we can expect that it will be around 52+26 = 78 percent correct.\n\nTo improve our score, there are two things that need to be done:\n1. Find the survived males (12%)\n2. Find the died females (9%)\n\"\"\"\n\"\"\"\n## 1. Find the survived males (12%)\n\"\"\"\n\"\"\"\n- Can't find anything significant\/interesting so far.\n\"\"\"\n\"\"\"\n## 2. Find the died females (9%)\n\"\"\"\n\"\"\"\n### 2.1. Pclass\n\"\"\"\nfemale = train[train.Sex=='female']\nfemale.groupby('Pclass').Survived.mean() * 100\n\"\"\"\nFemales on `Pclass=3` have 50% chance of surviving. Let's dig deeper to find which one is died.\n\"\"\"\n\"\"\"\nIn [part 1 of this notebook](https:\/\/www.kaggle.com\/thariqnugrohotomo\/without-machine-learning), we use the family size (`SubSp+Parch`) feature to find out which female is died. We'll use it again here.\n\"\"\"\nclass3_female = female[female.Pclass==3].copy()\nclass3_female['fam'] = class3_female.SibSp + class3_female.Parch\nclass3_female.groupby('fam').Survived.mean() * 100\n\"\"\"\nThe result is still hold. \n\nWhen female's `fam`$\\leq3$, she has greater chance of surviving (51% until 83%). But when`fam`$\\gt3$, then the chance is dropping ($\\leq37.5$%).\n\n**But**, how about different `Pclass`?\n\"\"\"\nnonclass3_female = female[female.Pclass!=3].copy()\nnonclass3_female['fam'] = nonclass3_female.SibSp + nonclass3_female.Parch\nnonclass3_female.groupby('fam').Survived.mean() * 100\n\"\"\"\nWhen `Pclass` is not `3`, then the family size doesn't matter anymore. They have a very high chance of surviving.\n\"\"\"\n\"\"\"\n# Answering\n\"\"\"\n\"\"\"\nBased on the obsevations above, we'll use the following pseudocode:\n```python\nif male:\n    return 0\nif female:\n    if Pclass==3 and fam>3:\n        return 0\n    else:\n        return 1\n```\n\"\"\"\ntest['fam'] = test.SibSp + test.Parch\ndef predict(passenger:pd.Series):\n    if passenger.Sex == 'male':\n        return 0\n    else: # female\n        if passenger.Pclass==3 and passenger.fam>3:\n            return 0\n        else:\n            return 1\nanswer = [int(predict(test.iloc[i])) for i in range(len(test))]\nanswer = pd.DataFrame(answer, index=test.index, columns=['Survived'])\nanswer.to_csv('submission.csv')\nanswer","meta":"{'source': 'AI4Code', 'id': '437bc55a625459'}"}
{"id":"64580","text":"# 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 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\nr=pd.read_csv('\/kaggle\/input\/windows-store\/msft.csv',parse_dates=['Date'])\nr.head()\nr[['people_ratings']]=r[['No of people Rated']]\ndel r['No of people Rated']\nr.head()\nr.info()\nr.isnull().sum()\n#identifying the missing row\nd=r[r['Name'].isnull()]\nd\n#dropping missing row\nr.dropna(inplace=True)\nr.isnull().sum()\nr.tail()\nr['Rating'].value_counts()\/len(r)\n\"\"\"\nMost of the apps have a rating of 4(approx 24%)\n\"\"\"\nr['Category'].value_counts()\/len(r)\n\"\"\"\nMost of the apps are of Music(approx 14%) and Books(approx 13%) Category.\n\"\"\"\n#denoting non free values as paid\nr.loc[r['Price'] != 'Free', 'Price'] = 'Paid' \nr['Price'].value_counts()\/len(r)*100\n\"\"\"\nMajority of the apps are free(97%)\n\"\"\"\n#finding highest rated apps in each category\nr[r['Rating']>=1.0].groupby(['Category']).max()\n\"\"\"\nSince books,business and developer tools category contains the highest rated apps which are paid so it is seen that price doesn't affect the app rating it is generally determined by app performance.\n\"\"\"\n#mean rating and no of people rated in each category\nr.groupby('Category')[['Rating','people_ratings']].mean()\n\"\"\"\nGovernment and politics category have the highest mean rating.\n\nMultimedia Design category have the highest no of people_ratings.\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly\nplotly.offline.init_notebook_mode(connected = True)\nsns.barplot('Price','Rating',data=r)\nplt.title(\"Distribution of Apps\")\n\"\"\"\nRating of free is more because of more number of free apps.\n\"\"\"\n#finding majority of paid and free apps in each category\nplt.figure(figsize=(20,10))\nfig=px.scatter(r,'Category',color='Price')\nfig.show()\n\"\"\"\nIn this graph it is depicted that most of the paid apps exist in Books,Business and Developer tools categories.\n\"\"\"\n#displaying proporations of total ratings of people of each category\nfig=px.pie(r,values='people_ratings',names='Category',title=\"Distribution of Categories according to user's ratings\")\nfig.show()\n#finding rating trend of apps given by users in each category\nplt.figure(figsize=(30,20))\nsns.lineplot('Category','people_ratings',data=r,hue='Rating',marker='o',legend=False)\nplt.xticks(rotation=90)\nplt.legend(title='Ratings',loc='upper right',labels=[1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0])\nplt.title('Distribution of Categories based on rating count given by users',fontsize=13)\nfig = px.scatter(r, x=\"Rating\", y=\"people_ratings\", \n                 color=\"Category\", \n                 hover_data=['people_ratings','Rating','Category','Price'], \n                 title = \"Visualization of each app features of Window Store\")\nfig.show()\n\"\"\"\nFrom the above graph we can say that what are the user's feedback based on all features of dataset of each app.\n\"\"\"\n#setting date as index for time series analysis\nr=r.set_index('Date')\nr['Month']=r.index.month\nr['Year']=r.index.year\nr['Day']=r.index.day\n#determining most number of downloads per year\nfig=px.pie(r,values='people_ratings',names='Year',title='Number of ratings on yearly basis')\nfig.show()\n\"\"\"\nSince 2016 has most number of user ratings so it has been confirmed that 2016 has the more number of app downloads as ratings are only given by the user after downloading the app and using it.\n\"\"\"\nfig=px.pie(r,values='people_ratings',names='Month',title='Number of ratings on monthly basis')\nfig.show()\n\"\"\"\n10 means October month has most number of ratings so most number of downloads.\n\"\"\"\nfig=px.pie(r,values='people_ratings',names='Day',title='Number of ratings on daily basis')\nfig.show()\n\"\"\"\nDay 30 i.e.end of the month has the most number of ratings so most number of downloads.\n\"\"\"\n\"\"\"\n**If you like this notebook do upvote it.**\n\nDo provide your valuable feedback.\n\nDo checkout my other notebooks at https:\/\/www.kaggle.com\/tmchls\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '77246bbb731d35'}"}
{"id":"877","text":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport datetime\n\nfrom collections import defaultdict\n\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\nfrom sklearn.linear_model import LinearRegression\n\nfrom sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error\n\nfrom skopt import gp_minimize\nfrom skopt.space import Real, Integer\n\nfrom graphviz import Digraph\nfrom IPython.display import SVG\n\nimport warnings\n\nfrom lightgbm import LGBMRegressor\n# fix the date in a dataframe (pandas does not read it in correctly by default), set it as index\ndef fix_date(df):\n    df['Date'] = pd.to_datetime(df['Date'], format=\"%d\/%m\/%Y\")\n    df.set_index('Date', drop=False, inplace=True)\n    df['dayofyear'] = df['Date'].dt.dayofyear\n# The main rainfall effect model\n\ndef rainfall_effect(\n    # data parameters\n    rain_series, # pd series where index is date and value is amount of rain which fell that day\n    start_date = None,\n    end_date = None,\n    # simulation parameters\n    fraction_retained = 0.9, # fraction of water retained each day (vs. fraction that is carried away elsewhere - pooling, transpiration, etc.)\n    first_day_flow = 0.004, # what fraction of the rain takes effect on the first day\n    funnel_start_width = 0.0, # when 0, funnel is cone-shaped; when large, funnel is closer to cyllinder-shaped.\n    time_gap = 0, # integer(days) - how long does it take even the first water to reach the area of interest\n):\n    # calculate default start and end date\n    if start_date is None:\n        start_date = rain_series.first_valid_index()\n    if end_date is None:\n        end_date = rain_series.last_valid_index()\n    \n    # calculate flow speed per \"funnel unit\"\n    first_day_area = funnel_start_width+1.0\n    flow_speed = first_day_flow\/first_day_area\n    \n    # total rain \"taking effect\" on a given day\n    rain_effect = defaultdict(int)\n    \n    # process rain coming in each day\n    current_date = start_date\n    while current_date <= end_date:\n        rain = 0\n        if current_date in rain_series.index:\n            rain = rain_series[current_date]\n        \n        # start with explicit 0 for each input date      \n        if current_date not in rain_effect:\n            rain_effect[current_date] = 0\n            \n        # iterate through upcoming days and calculate effect of rain which reaches the body *on that day*\n        retained_remaining = rain # this variable keeps track of the effect of retention\/drainage (but ignores actual outflow)\n        # effectively,it is used to infer how much water is left which originated on a given \"daily level\" of the funnel.\n        total_water_remaining = rain # actual amount of rain remaining \"un-claimed\"\n        current_area_factor = first_day_area\n        rain_effect_date = current_date + datetime.timedelta(int(time_gap))\n        while retained_remaining >= 0.01 and total_water_remaining >= 0.01 and rain_effect_date <= end_date:\n            water_out = current_area_factor*flow_speed*retained_remaining\n            water_out = min(water_out, total_water_remaining)\n        \n            # update totals\n            rain_effect[rain_effect_date] += water_out\n            total_water_remaining -= water_out\n            \n            # update running state variables\n            retained_remaining *= fraction_retained\n            total_water_remaining *= fraction_retained\n            current_area_factor += 2\n            rain_effect_date += datetime.timedelta(1)\n            \n        current_date += datetime.timedelta(1)\n    \n    return rain_effect\n# error metric: global error variance\ndef global_error_var(correct, pred):\n    return (correct-pred).var(ddof=0)\ndef local_error_var(correct, pred):\n    return (correct-pred).rolling(10).var(ddof=0).mean()\n# Helper functions to be able to define more elaborate priors for gp_optimize than just \"uniform\" and \"loguniform\"\n \n# reverse a log-uniform prior so that bigger values are more likely \ndef make_inverse_loguniform_prior(name, lower=None, upper=None):\n    \n    if lower is None:\n        lower = 0 + np.finfo(float).eps\n    if upper is None:\n        upper = 1 - np.finfo(float).eps\n        \n    def convert(x):\n        return upper-x\n    \n    dimension = Real(0 + np.finfo(float).eps, upper-lower, name=name, prior='log-uniform')\n    \n    return convert, dimension\n\n# set up a dimension such that the resulting converted variable will have a logistic distribution \n# with given s, mu, and lower\/upper bounds.\ndef make_logit_prior(name, s = 1, m = 0, lower=None, upper=None):\n\n    # (0+np.finfo(float).eps)\n    \n    # x should be between 0 and 1\n    def convert_using_logit(x):\n        return m+np.log(x\/(1-x))*s\n    \n    lower_x = 0 + np.finfo(float).eps\n    if lower is not None:\n        lower += np.finfo(float).eps\n        lower_x = 1\/(1+np.exp((m-lower)\/s))\n    upper_x = 1 - np.finfo(float).eps\n    if upper is not None:\n        upper -= np.finfo(float).eps\n        upper_x = 1\/(1+np.exp((m-upper)\/s))\n    \n    dimension = Real(lower_x, upper_x, name=name)\n    \n    return convert_using_logit, dimension\n# wrap rain effect calculation into a format which can be plugged into gp_optimize, with custom priors.\ndef make_rain_func_and_dimensions(\n    rain_series, \n    retained_prior = None,\n    flow_prior = None,\n    width_prior = None,\n    lag_prior = None,\n    verbose=True\n):\n    # TODO: take  in priors?..\n    \n    # How to convert given input variable (generate defaults if not provided in parameters)\n    if retained_prior is None:\n        # retained_conv, retained_dim = make_inverse_loguniform_dim('fraction_retained')\n        retained_conv, retained_dim = make_logit_prior('fraction_retained', s=0.3, m=0.9, lower=0.0, upper=1.0)\n    else:\n        retained_conv, retained_dim = retained_prior\n        \n    if flow_prior is None:\n        # we set the lower bound to 0.0001 for practical reasons: lower values don't make much of a cumulative effect, \n        # but they do take a long time to compute because the effect of each day's rainfall is spread out over many more days.\n        flow_conv, flow_dim = make_logit_prior('first_day_flow', s=0.05, m=0.01, lower=0.0001, upper=1.0) #m=0.1, s=0.1?\n    else:\n        flow_conv, flow_dim = flow_prior\n        \n    if width_prior is None:\n        width_conv, width_dim = make_logit_prior('funnel_start_width', s=40.0, m=180.0, lower=0.0) # m=270?\n    else:\n        width_conv, width_dim = width_prior\n    \n    if lag_prior is None:\n        lag_conv = lambda x: x\n        lag_dim = Integer(0,10, name='time_gap')\n    else:\n        lag_conv, lag_dim = lag_prior\n    \n    conversions = [retained_conv, flow_conv, width_conv, lag_conv]\n    dimensions = [retained_dim, flow_dim, width_dim, lag_dim]\n    \n    def convert(x):\n        return [conversions[i](x_i) for (i, x_i) in enumerate(x)]\n    \n    def calc_rain_from_vector(x):\n        fraction_retained, first_day_flow, funnel_start_width, time_gap = convert(x)\n        \n        if verbose:\n            print('inputs:', fraction_retained, first_day_flow, funnel_start_width, time_gap)\n            \n        return pd.Series(rainfall_effect(\n            # data parameters\n            rain_series,\n            # simulation parameters\n            fraction_retained = fraction_retained,\n            first_day_flow = first_day_flow,\n            funnel_start_width = funnel_start_width,\n            time_gap=time_gap\n        ))\n\n    return calc_rain_from_vector, dimensions, convert\n# use Baysian optimization with linear regresssion to fit ML model of rain effects, plus any set of linear-effect parameters.\ndef fit_rain_effects(\n    # inputs\n    rains_df, \n    ground_truth, \n    make_rain_func=make_rain_func_and_dimensions,\n    additional_fields=None, # additional fields to throw into linear regression\n    # options\n    error_func = global_error_var,\n    spinup=30, # TODO: use?..\n    verbose=True,\n    nrandom=20,\n    ntotal=100,\n    x0=None, # optional input point(s) to try for gp_minimize; e.g. best overall results of previous runs\n):\n    calcs = []\n    rain_names = []\n    converts = []\n    all_dims = []\n    dims_per_rain = 0\n    for rain_name, rain_series in rains_df.iteritems():\n        calc, dims, convert = make_rain_func(rain_series, verbose=verbose)\n        dims_per_rain = len(dims)\n        calcs.append(calc)\n        converts.append(convert)\n        rain_names.append(rain_name)\n        all_dims += dims\n        \n    reg_fields =rain_names\n    if additional_fields is not None:\n        reg_fields += list(additional_fields.columns)\n    \n    optimal_error = None\n    optimal_linreg = None\n    optimal_n = None\n    \n    def calculate_error(x):\n        prediction_frame = ground_truth.to_frame(name='ground_truth')\n        \n        for i, rain_calc in enumerate(calcs):\n            if(verbose):\n                print(rain_names[i])\n            rain_result = rain_calc(x[dims_per_rain*i:dims_per_rain*(i+1)])\n            prediction_frame[rain_names[i]] = rain_result\n            prediction_frame.loc[(prediction_frame['ground_truth'].notnull()) & (prediction_frame[rain_names[i]].isnull()), rain_names[i]] = 0\n\n        if additional_fields is not None:\n            prediction_frame[list(additional_fields.columns)] = additional_fields\n                \n        without_nulls = prediction_frame.dropna().copy()\n        \n        reg = LinearRegression().fit(without_nulls[reg_fields], without_nulls['ground_truth'])\n        if verbose:\n            print('rescale parameters:', reg.coef_, reg.intercept_)\n\n        without_nulls['pred'] = reg.predict(without_nulls[reg_fields])\n        \n        error = error_func(without_nulls['ground_truth'], without_nulls['pred'])\n        if verbose:\n            print('error value:', error)\n            print()\n            \n        nonlocal optimal_error, optimal_linreg, optimal_n\n        if optimal_error is None or error < optimal_error:\n            optimal_error = error\n            optimal_linreg = reg\n            optimal_n = len(without_nulls)\n        \n        return error\n        \n    res = gp_minimize(\n        calculate_error,  # function to minimize\n        all_dims,             # dimension configuration\n        acq_func=\"gp_hedge\",    # acquisition function (PI = optimize probability of reducing error; 'gp_hedge' - guess\/vary)\n        n_calls=ntotal,      # number of evaluations of f\n        n_random_starts=nrandom, # first n calls are random (avoid local minima) \n        x0=x0, # input points to definitely try\n    )  \n    \n    additional_names = []\n    if additional_fields is not None:\n        additional_names = list(additional_fields.columns)\n    \n    return generate_prediction_function(rain_names, additional_names, res, converts, optimal_linreg, optimal_n)\n# Calculate BIC from error variance (making the gaussian assumption)\ndef get_bic(errvar, n, k):\n    return n*np.log(errvar) + k*np.log(n)\n# given the outputs of a rain effect model fit, return a function which will generate the predictions based on that model.\ndef generate_prediction_function(rain_names, additional_field_names, fit_result, conversions, optimal_linreg, training_n, verbose=True):\n    \n    # get converted parameters for rain effect calculations\n    dims_per_rain = len(fit_result.x)\/\/len(conversions)\n    all_rain_params = []\n    for i, convert in enumerate(conversions):\n        params = convert(fit_result.x[dims_per_rain*i:dims_per_rain*(i+1)])\n        all_rain_params.append(params)\n    \n    if verbose:\n        for name, params in zip(rain_names, all_rain_params):\n            print(f'Parameters for {name}: {params}')\n        print('Scaling:')\n        for name, coef in zip(rain_names+additional_field_names, optimal_linreg.coef_):\n            print(f'  {name}: {coef}')\n        print(f'Translation parameter: {optimal_linreg.intercept_}')\n        print(f'raw gp_minimize parameters: {fit_result.x}')\n        print(f'error value: {fit_result.fun}')\n        print(f'BIC (assuming error metric is error variance): {get_bic(fit_result.fun, training_n, len(fit_result.x)+len(optimal_linreg.coef_)+1)}')\n    \n    # function to generate prediction from trained parameters\n    def predict_from_rain(rain_fields, additional_fields=None):\n        pred_df = pd.DataFrame(index=rain_fields.index)\n        \n        for rain_name, rain_params in zip(rain_names, all_rain_params): \n            rain_series = rain_fields[rain_name]\n            fraction_retained, first_day_flow, funnel_start_width, time_gap = rain_params\n            rain_pred = pd.Series(rainfall_effect(\n                rain_series,\n                fraction_retained = fraction_retained, \n                first_day_flow = first_day_flow,\n                funnel_start_width = funnel_start_width,\n                time_gap = time_gap,\n            ))\n            pred_df[rain_name] = rain_pred\n            \n        if additional_fields is not None:\n            pred_df[list(additional_fields.columns)] = additional_fields\n            \n        pred_df.dropna(inplace=True)\n        return pd.Series(optimal_linreg.predict(pred_df), index=pred_df.index)\n            \n    return predict_from_rain\n\ndef get_expected_inputs(input_data, dayofyear):\n    week_rolling_mean = input_data.rolling(7, center=True).mean()\n    expectations = defaultdict(list)\n    variances = defaultdict(list)\n    for d in range(365):\n        nearby_days = np.arange(d-3, d+3)%365+1\n        near_data = week_rolling_mean[dayofyear.isin(nearby_days)]\n        for field in week_rolling_mean.columns:\n            expectations[field].append(near_data[field].mean())\n            variances[field].append(near_data[field].var())\n    \n    for field in week_rolling_mean.columns:\n        expectations[field].append(expectations[field][-1])# hack to do  *something* about leap years.\n        variances[field].append(variances[field][-1])\n    return expectations, variances\ndef gen_inputs_with_expectations(input_data, days_to_predict, expected_means):\n    expected_data = input_data.append(pd.DataFrame(index=days_to_predict))\n    expected_data['dayofyear'] = expected_data.index.dayofyear\n    for field in input_data.columns:\n        exp_df = pd.DataFrame(expected_means[field], index=range(1, 367), columns=[field+'_expected'])\n        expected_data = expected_data.join(exp_df, on='dayofyear')\n        expected_data[field] = expected_data[field].where(~expected_data.index.isin(list(days_to_predict)), expected_data[field+'_expected'])\n    return expected_data\n\"\"\"\n## Hello\n\nSo I rushed my competition submission (made the last changes literally 3 minutes before the deadline...) so I kind of bungled the implementation of my lake prediction. But I wanted to prove to myself that my model was viable, and it seems like it is if I actually do the math right and combine the components correctly.\n\nSo here it is. If you're curious about what my general model is doing (the `fit_rain_effects` function), briefly: it's a model of how rainfall on a particular day takes effect over the subsequent days, which has four physically-meaningful parameters and the emerget property of generating an $\\frac{x}{e^x}$ distribution. Plus some linear regression with other arbitrary parameters thrown in on top. All fit to the data using Bayesian optimization.\n\nOh yes, also, when forecasting, I use a sort of smoothed average of the rain and temperature one would expect to see on that day of year as inputs to the model.\n\nIf you want more detail, you'll have to read the code or wait until I figure out what the actual rules are about publishing submissions. Sorry. Hopefully the bits I do expain are still interesting too.\n\"\"\"\n\"\"\"\n## Bilancino\n\"\"\"\n\"\"\"\n### Data Overview\n\"\"\"\nbilancino=pd.read_csv('..\/input\/acea-water-prediction\/Lake_Bilancino.csv')\nfix_date(bilancino)\n\nrain_fields = ['Rainfall_S_Piero', 'Rainfall_Mangona', 'Rainfall_S_Agata', 'Rainfall_Cavallina', 'Rainfall_Le_Croci']\n\n# The mean flow out of the lake (Flow_Rate) yesterday\nbilancino['flow_mean_yesterday'] = bilancino['Flow_Rate'].rolling(2).mean()\n\nbilancino['delta_level'] = bilancino['Lake_Level'].diff()\n\n\nbilancino['temp_30'] = bilancino['Temperature_Le_Croci'].rolling(30).mean()\nbilancino['temp_120'] = bilancino['Temperature_Le_Croci'].rolling(90).mean()\nbilancino['temp_180'] = bilancino['Temperature_Le_Croci'].rolling(180).mean()\n\n\nbilancino.columns\nfig, axes = plt.subplots(4, figsize=(15,10))\n\nfor r in rain_fields:\n    bilancino[r].rolling(120).sum().plot(ax=axes[0])\n    \nbilancino['Temperature_Le_Croci'].plot(ax=axes[1])\n\nbilancino['Lake_Level'].plot(ax=axes[2])\n\nbilancino['Flow_Rate'].plot(ax=axes[3])\n    \nfor ax in axes:\n    ax.legend()\ntrain_cutoff = datetime.date(2016,1,1)\nb_train = bilancino[:train_cutoff].copy()\nb_test = bilancino[train_cutoff+datetime.timedelta(1):]\n\"\"\"\n### 1. Dependencies and model\n\"\"\"\nlake_graph = Digraph(graph_attr={'ranksep':'1'})\n\nlake_graph.node('R', 'Rainfall')\nlake_graph.node('T', 'Temperature')\nlake_graph.node('F', 'Flow out of dam', shape='octagon', color='blue')\nlake_graph.node('L', 'Lake Level', shape='octagon', color='green')\n\nlake_graph.edge('R', 'L', color='green')\nlake_graph.edge('T', 'L', color='green')\nlake_graph.edge('F', 'L', color='green')\nlake_graph.edge('L', 'F', color='blue')\n\nlake_graph\n\"\"\"\nThe Bilancino lake is an interesting case, because its behavior depends on a man-made and human-operated structure - the dam that created the lake.\n\nThe level of water in the lake depends on the flow out of the dam, but the flow out of the dam also depends on the lake level. Specifically, the lake level determines the amount of pressure created, and therefore the strengt of the flow.\n\nAccording to the challenge description, water is let out of the dam quickly at certain times, and allowed to collect at other times.\n\nFurther, the data indicates that the flow spikes drastically when the lake level goes over a certain point - This seems to be the dam's spillway being activated. According to [this site](http:\/\/cmcgruppo.com\/cmc\/en\/project\/bilancino-dam\/), the spillway has an automatic flap gate. This means that the gate opens wider when pressure increases, which makes the interaction even more complicated.\n\"\"\"\n\"\"\"\n#### Modeling change in lake level\n\nIn my previous experimentation, I found that two of the rainfall fields contain most of the information: `Rainfall_Mangona` and `Rainfall_Cavallina`. This makes sense: `Rainfall_Cavallina` is the closest location to the lake iteslf, and `Rainfall_Mangona` is located over the Sieve river, before the rver flows into the lake. Therefore, `Rainfall_Mangona` captures information about water which enters the lake via the river.\n\nThe new component here is how flow rate affects lake level: the amount of water that leaves the lake via the dam (or more precisely, *the amount that left yesterday*) is proportional to the subsequent reduction in lake level. So unlike the temerature parameters, **The parameters of flow in the linear regression actually have a direct physical meaning**. Specifically, the scaling coefficient tells us how to convert between flow rate and (change in) lake level.\n\"\"\"\nb_pred_func=fit_rain_effects(\n    rains_df = b_train[['Rainfall_Mangona', 'Rainfall_Cavallina']], \n    ground_truth = b_train['delta_level'], \n    additional_fields = b_train[['flow_mean_yesterday', 'Temperature_Le_Croci','temp_30', 'temp_120', 'temp_180']],\n    nrandom=3,\n    ntotal=10,\n    verbose=False, \n    x0=[\n        [0.15233691562216556, 0.8854084902188695, 0.9999999999999998, 1, 0.13666937295698817, 0.9979837155391087, 0.14202766104040032, 0],\n        [0.0474258731775668, 0.9999999974825013, 0.570952205261587, 1, 0.3850443032078931, 0.45805440829961064, 0.545042159616547, 0],\n    ]\n)\n\"\"\"\nThis model predicts **lake level** based on **temperature, rainfall, and flow out of the lake**.\n\nBut when forecasting, we won't actually know the flow out of the lake - it's one of the variables we need to predict! So instead of using the returned prediction function with flow as input, we can use just move the flow effect to the other side of the equation, and predict the **cumulative change in water level as a result of weather inputs, including the water that subsequently flows out of the dam**\n\n$$\\text{Lake_Level} = C+\\text{Mangona_effect}*S_\\text{RM}+\\text{Cavallina_effect}*S_\\text{RM}+\n(\\sum{\\text{Temp_var_i}*S_i}) - \\text{Flow_Rate}*S_F\n$$\n\n$$\\text{Lake_Level} +\\text{Flow_Rate}*S_F =  C+\\text{Mangona_effect}*S_\\text{RM}+\\text{Cavallina_effect}*S_\\text{RM}+\n(\\sum{\\text{Temp_var_i}*S_i})\n$$\n\n(For clarity about whether water is flowing out or in, I inverted the $S_F$ paraameter from what it is in the linear regression - so it is around 0.007 instead of -0.007)\n\"\"\"\nflow_lake_conversion = 0.007661467849044978\n\n# predict cumulative level delta + flow effect based on model of lake level\n# (using parameters trained in the model above)\ndef predict_cum_delta(input_df):\n    Rainfall_Mangona_prediction = pd.Series(rainfall_effect(\n        input_df['Rainfall_Mangona'],\n        fraction_retained = 2.220446049250313e-16, \n        first_day_flow = 1.0, \n        funnel_start_width = 191.42948720854787, \n        time_gap = 1,\n    ))\n\n    Rainfall_Cavallina_prediction = pd.Series(rainfall_effect(\n        input_df['Rainfall_Cavallina'],\n        fraction_retained = 0.7595424520378065, \n        first_day_flow = 0.0015911180194193453, \n        funnel_start_width = 187.22633570423756, \n        time_gap = 0,\n    ))\n    pred_cum_delta = 0.005862430953008586*Rainfall_Mangona_prediction+\\\n    1.4547492793031174*Rainfall_Cavallina_prediction+\\\n    0.0039183372980673425*input_df['Temperature_Le_Croci']+\\\n    -0.0015752030857040245*input_df['temp_30']+\\\n    -0.008107915323914416*input_df['temp_120']+\\\n    0.0048819421510388206*input_df['temp_180']+\\\n    -0.010936677349591556\n    return pred_cum_delta, Rainfall_Mangona_prediction, Rainfall_Cavallina_prediction\n\ncum_delta, rm, rc = predict_cum_delta(bilancino)\n\"\"\"\nWe can then compare predictions to reality by adding the true delta-level and flow rate parameter, with the flow rate scaled according to the model:\n\"\"\"\ntrue_cum_delta =(bilancino['delta_level']+bilancino['flow_mean_yesterday']*flow_lake_conversion)\nfig, ax1 = plt.subplots(figsize=(15, 3))\ntrue_cum_delta.plot(label='True cumulative change')\ncum_delta[:train_cutoff].plot(alpha=0.7, label='Predicted cumulative change(training data)')\ncum_delta[train_cutoff:].plot(alpha=0.7, label='Predicted cumulative change(test data)', color='red')\nplt.legend()\nplt.xlim(datetime.date(2010,1,1))\nplt.show()\n\"\"\"\nAnd then we can calculate a **cumulative sum** of the true and predicted deltas to see what would happen if water kept coming in the lake, but would magically never leave via the dam:\n\"\"\"\nfig, ax1 = plt.subplots(figsize=(15, 3))\n\ntrue_cum_delta[cum_delta.first_valid_index():].cumsum().plot(label='True cumulative level')\ncum_delta.cumsum().plot(label='Predicted cumulative level')\nplt.legend()\nplt.xlim(datetime.date(2004,1,1))\nplt.title('Cumulative lake level predicted based on actual rain\/temp data')\nplt.show()\n\"\"\"\n#### Modeling flow out of lake\n\nAs I mentioned above, the flow out of the lake is a complex process which depends on several factors, including human behavior.\n\nI tentatively separated it into three typess of flow:\n- \"normal\" flow\n- \"drain\" flow, when the water is being drained from the lake through the dam's intake process\n- \"spillway\" flow, when the lake level is high enough that the spillway is active.\n\nMy manual guess about when each happens is shown below:\n(lake level is on one axis, in dashed lines, and flow rate is on anoter, in a solid line)\n\"\"\"\n# label specific types of flow\n\n# dates when \"intake\" (from the lake into the river) seems to happen\nstart_intake = 180# pd.to_datetime(datetime.date(2008, 7, 1)).dayofyear\nend_intake = pd.to_datetime(datetime.date(2008, 11, 1)).dayofyear\n\nbilancino.loc[(bilancino['dayofyear'] >= start_intake) & (bilancino['dayofyear'] <= end_intake), 'flow_type']='intake'\n\n# spillway is active\n# bilancino.loc[bilancino['Flow_Rate'] > 7.8, 'flow_type']='spillway'\nbilancino.loc[bilancino['Lake_Level'] > 251.5, 'flow_type']='spillway'\n\nfig, ax1 = plt.subplots(figsize=(15, 5))\nax2 = ax1.twinx()\nbilancino['Lake_Level'].plot(ax=ax1, color='orange', linestyle='dashed')\nbilancino.where(bilancino['flow_type']=='intake')['Lake_Level'].plot(ax=ax1, color='blue', linestyle='dashed')\nbilancino.where(bilancino['flow_type']=='spillway')['Lake_Level'].plot(ax=ax1, color='red', linestyle='dashed')\nbilancino['Flow_Rate'].plot(ax=ax2, color='orange', label='normal flow')\nbilancino.where(bilancino['flow_type']=='intake')['Flow_Rate'].plot(ax=ax2, color='blue', label='draining')\nbilancino.where(bilancino['flow_type']=='spillway')['Flow_Rate'].plot(ax=ax2, color='red', label='spillway')\nplt.legend()\nplt.show()\n\n\"\"\"\nHowever, I found it very hard to fit parameters to expeted flow rates in each case. There seems to be a lot of non-linearity in the relationships; additionally, the relationship potentially changes in the last two years - the scatterplot below shows the relationship between flow rate and lake level; we can clearly see two greenish-yellow lines that do not conform to the pattern. these represent spillway flow after 2018 - it appears that the spillway started activating eariler. Again, human behavior makes things less predictable.\n\nFor this reason, I chose to cut off the training dataset at 2016, and focus on prediciting 2017. We can also see what happens to the subsequent years, and whether this shift changes things.\n\"\"\"\nplt.scatter(bilancino['Lake_Level'],bilancino['Flow_Rate'], marker='x',c=bilancino['Date'].dt.year)\nplt.show()\n\"\"\"\nBecause this is a complex and piecewise relationship, decision trees, and specifically boosted forests (aka LGBM) are a good fit.\n\nI generated some derived features for the LGBM which capture my beliefs about the important pieces of this puzzle:\n- my best guess about when draining typically starts, ends, and how it ramps up (just from eyeballing the data)\n- stats about the last 60 days of lake level - because I suspect there is some inertia in the system, possibly due to the flap gate.\n\"\"\"\nlgbm_input = bilancino[['Lake_Level']].copy() #, 'dayofyear'\n\n # from lake level analysis above\n\nlgbm_input['effective_level'] = bilancino['Lake_Level']+bilancino['flow_mean_yesterday']*flow_lake_conversion\nlgbm_input.drop('Lake_Level',axis=1, inplace=True)\nlgbm_input['rolling_min'] = lgbm_input['effective_level'].rolling(60).min()\nlgbm_input['rolling_max'] = lgbm_input['effective_level'].rolling(60).max()\nlgbm_input['rolling_mean'] = lgbm_input['effective_level'].rolling(60).mean()\n\nintake_start = 160 # Nth day in year\nrampup_end = 220\nintake_end = 360 # end_intake  # stop \"intake\" drain\nintake_rampup = bilancino['dayofyear']\nintake_rampup = (intake_rampup-intake_start)\/(rampup_end-intake_start)\nintake_rampup[(bilancino['dayofyear']<intake_start) | (bilancino['dayofyear']>intake_end)] = 0\nintake_rampup[(bilancino['dayofyear']>rampup_end) & (bilancino['dayofyear']<=intake_end)] = 1\n\nlgbm_input['intake_rampup'] = intake_rampup\n\nlgbm_test_cutoff = datetime.date(2017, 1, 1)\nlgbm_input = lgbm_input.loc[:lgbm_test_cutoff].copy()\nlgbm_flow_rate = bilancino.loc[:lgbm_test_cutoff, 'Flow_Rate']\n\n\nX_train = lgbm_input.loc[:train_cutoff]\ny_train = lgbm_flow_rate[:train_cutoff]\nX_test = lgbm_input.loc[train_cutoff:]\ny_test = lgbm_flow_rate[train_cutoff:]\n\nreg = LGBMRegressor().fit(X_train, y_train)\n\nfig, ax1 = plt.subplots(figsize=(15, 5))\n\nbilancino['Flow_Rate'].plot(ax=ax1)\nax1.plot(X_train.index,reg.predict(X_train), label='LGBM prediction(training data)')\nax1.plot(X_test.index,reg.predict(X_test), label='LGBM prediction(test data)')\nplt.xlim(None, lgbm_test_cutoff)\nplt.legend()\nplt.show()\ntrain_pred = pd.Series(reg.predict(X_train), index=X_train.index)\ntest_pred = pd.Series(reg.predict(X_test), index=X_test.index)\n\nprint('train error variance:',(train_pred-bilancino['Flow_Rate']).var(),'\\ntest error variance:', (test_pred-bilancino['Flow_Rate']).var())\n\"\"\"\n### 2. Forecasting\n\"\"\"\n\"\"\"\nForecasting is tricky because of the feedback loop between flow and lake level.\n\nFor this reason, I am using a custom procedure to integrate the cumulative-delta predictions and the LGBM's flow predictions:\n1. predict **cumulative delta-level** for all dates\n2. For each date in the dataset (in order), repeat the following:\n    - take the previous date's lake level (real for day 1, predicted for the rest of the time period)\n    - add the delta-level generated in step 1\n    - use this \"effective lake level\" as input to the LGBM (it was actually trained on these values)\n    - Take the flow predicted by the LGBM, and calculate the reduction in lake level (by multiplying by the conversion factor known from the rain-effect model); subtract the result from the \"effective lake level\" to get the actual lake level\n\"\"\"\nexp_means, exp_vars = get_expected_inputs(\n    b_train[['Rainfall_Mangona', 'Rainfall_Cavallina', 'Temperature_Le_Croci']], b_train['dayofyear'])\nexp_inputs = gen_inputs_with_expectations(\n    b_train[['Rainfall_Mangona', 'Rainfall_Cavallina', 'Temperature_Le_Croci']],\n    b_test.index,\n    exp_means\n)\n\nexp_inputs['temp_30'] = exp_inputs['Temperature_Le_Croci'].rolling(30).mean()\nexp_inputs['temp_120'] = exp_inputs['Temperature_Le_Croci'].rolling(90).mean()\nexp_inputs['temp_180'] = exp_inputs['Temperature_Le_Croci'].rolling(180).mean()\n\nexp_inputs.loc[train_cutoff:,'flow_mean_yesterday'] = 0\npred_cum_delta, rm, rc=predict_cum_delta(exp_inputs)\nfig, ax1 = plt.subplots(figsize=(15, 3))\n\ntrue_cum_delta[cum_delta.first_valid_index():].cumsum().plot(label='True cumulative level')\npred_cum_delta.cumsum()[:train_cutoff].plot(label='Predicted cumulative level(train data)')\npred_cum_delta.cumsum()[train_cutoff:].plot(label='Predicted cumulative level(expected rain\/temp)')\nplt.legend()\nplt.xlim(datetime.date(2004,1,1))\nplt.title('Cumulative lake level predicted based on expected rain\/temp')\nplt.show()\ncurrent_lake_level = b_train.iloc[-1]['Lake_Level'] # start with last lake level in the training dataset\nlevel_history = list(b_train.iloc[-60:]['Lake_Level']) # history so we can always get the min\/max\/mean of the last 60\n\nflow_predictions = {}\nlevel_predictions = {}\n\nfor date in b_test.index:\n    # calculate LGBM inputs\n    effective_lake_level = current_lake_level+pred_cum_delta[date]\n    min_60 = min(level_history[-60:])\n    max_60 = max(level_history[-60:])\n    mean_60 = np.mean(level_history[-60:])\n    intake_rampup_factor=0\n    if rampup_end < date.dayofyear < intake_end:\n        intake_rampup_factor = 1\n    elif intake_start < date.dayofyear:\n        intake_rampup_factor = (date.dayofyear-intake_start)\/(rampup_end-intake_start)\n    \n    # predict\n    pred_flow = reg.predict([[\n        effective_lake_level,\n        min_60,\n        max_60,\n        mean_60,\n        intake_rampup_factor]])[0]\n    pred_level = effective_lake_level -(pred_flow*flow_lake_conversion)\n    \n    level_predictions[date] = pred_level\n    flow_predictions[date] = pred_flow\n    \n    # update state\n    level_history.append(pred_level)\n    current_lake_level = pred_level\n    \n\nfig, ax1 = plt.subplots(figsize=(15, 3))\n\nb_test['Lake_Level'].plot()\npd.Series(level_predictions).plot(label='Predicted lake level')\nplt.legend()\nplt.title('Lake Level predictions')\nplt.show()\nprint('Lake Level:')\nprint('MAE(all years):', mean_absolute_error(b_test['Lake_Level'],pd.Series(level_predictions)))\nprint('MAE(one year):', mean_absolute_error(b_test.loc[:datetime.date(2017,1,1),'Lake_Level'],pd.Series(level_predictions).loc[:datetime.date(2017,1,1)]))\nprint('RMSE(all years):', mean_squared_error(b_test['Lake_Level'],pd.Series(level_predictions), squared=False))\nprint('RMSE(one year):', mean_squared_error(b_test.loc[:datetime.date(2017,1,1),'Lake_Level'],pd.Series(level_predictions).loc[:datetime.date(2017,1,1)], squared=False))\nfig, ax1 = plt.subplots(figsize=(15, 3))\n\nb_test['Flow_Rate'].plot()\npd.Series(flow_predictions).plot(legend='Predicted dam flow rate')\n\nplt.title('Flow Rate predictions')\nplt.legend()\nplt.show()\nprint('Flow Rate:')\nprint('MAE(all years):', mean_absolute_error(b_test['Flow_Rate'],pd.Series(flow_predictions)))\nprint('MAE(one year):', mean_absolute_error(b_test.loc[:datetime.date(2017,1,1),'Flow_Rate'],pd.Series(flow_predictions).loc[:datetime.date(2017,1,1)]))\nprint('RMSE(all years):', mean_squared_error(b_test['Flow_Rate'],pd.Series(flow_predictions), squared=False))\nprint('RMSE(one year):', mean_squared_error(b_test.loc[:datetime.date(2017,1,1),'Flow_Rate'],pd.Series(flow_predictions).loc[:datetime.date(2017,1,1)], squared=False))\n\"\"\"\nWe can see that the lake level predictions capture the general pattern relatively well, but are a lot smoother than reality, especially right around the rainy winter season. This is because of my choice of input for the forecasting part of the  model: historical data averaged over a week and then averaged again. Because the lake + dam system is sensitive to spikes in the rain, and because rain data tends to be so spiky, taking the average doesn't capture the behavior as well as it does for other water bodies.\n\nIn fact, we can see that the predicted flow never goes into the \"spillway\" behavior - precisely because spillways are *designed* in large part for mitigating sudden spikes in rain.\n\nWe also see that the LGBM tends to produce much more gradual declines in flow than in reality, whereas in the real world, the flow almost seems to switch between several different levels.\n\nHaving more information about the dam and its operation might help make a more precise model. For example, just having the dates and ramp-up procedure for water intake might help isolate that effect, and analyze the other effects in more detail.\n\"\"\"\n\"\"\"\n### Using real rain\/temperature\nIn order to see the effect of using averaged expected inputs, I re-ran the prediction with the **actual** rain and temperature values. \n\"\"\"\npred_cum_delta, rm, rc = predict_cum_delta(bilancino)\ncurrent_lake_level = b_train.iloc[-1]['Lake_Level'] # start with last lake level in the training dataset\nlevel_history = list(b_train.iloc[-60:]['Lake_Level']) # history so we can always get the min\/max\/mean of the last 60\n\nflow_predictions = {}\nlevel_predictions = {}\n\nfor date in b_test.index:\n    # calculate LGBM inputs\n    effective_lake_level = current_lake_level+pred_cum_delta[date]\n    min_60 = min(level_history[-60:])\n    max_60 = max(level_history[-60:])\n    mean_60 = np.mean(level_history[-60:])\n    intake_rampup_factor=0\n    if rampup_end < date.dayofyear < intake_end:\n        intake_rampup_factor = 1\n    elif intake_start < date.dayofyear:\n        intake_rampup_factor = (date.dayofyear-intake_start)\/(rampup_end-intake_start)\n    \n    # predict\n    pred_flow = reg.predict([[\n        effective_lake_level,\n        min_60,\n        max_60,\n        mean_60,\n        intake_rampup_factor]])[0]\n    pred_level = effective_lake_level -(pred_flow*flow_lake_conversion)\n    \n    level_predictions[date] = pred_level\n    flow_predictions[date] = pred_flow\n    \n    # update state\n    level_history.append(pred_level)\n    current_lake_level = pred_level\n    \n\nfig, ax1 = plt.subplots(figsize=(15, 3))\n\nb_test['Lake_Level'].plot()\npd.Series(level_predictions).plot(label='Predicted lake level')\nplt.legend()\nplt.show()\nfig, ax1 = plt.subplots(figsize=(15, 5))\n\nb_test['Flow_Rate'].plot()\nbilancino.where(bilancino['flow_type']=='spillway').loc[train_cutoff:,'Flow_Rate'].plot(color='red', label='Flow Rate (spillway)')\npd.Series(flow_predictions).plot(alpha=0.8, label='Predicted flow rate')\nplt.legend()\nplt.show()\n\"\"\"\nThe shape of the predictions is much closer to reality now, and the flow predictions even produce plausible spillway spikes in mostly the right places. \n\nThere are still a couple of interesting discrepancies, mostly with the flow spillway spikes. In the graph above, I highlighted in red the parts of flow which should correspond with the spillway being active (the same as the red parts on the flow + lake level graph at the beginning of the \"modeling flow\" section). These are sections where the lake level is above a certain level, above which the spillway seems to activate according to the trainign data. The vertical part of the hockey stick on the flow vs. level scatter plot.\n\nThe LGBM's decision on when to spike the flow matches my lake level-based prediction pretty well; in fact, there are  a couple of places  where my red highlighting and the LGBM agree, even though the LGBM did not \"know\" about my heuristic, but the data disagrees:\n\n- Most prominently, right around the start of 2018 and also the end of 2019, there are spikes in real data which neither the LGBM nor my Lake Level based heuristic anticipated. These correspond to the outliers I pointed out on the scatter plot: In these years, the spillway seems to be behaving differently than in the training data.\n- There are also a couple of small places where the opposite happens: the spillway ought to be active according to my heuristic, and the LGBM predicts a relatively high flow, but in reality the flow does not spike. The most noteable one is around early 2017, where the LGBM created a very narrow spike exactly where my heuristic highlighted a very tiny red spot.\n\nBut overall, having realistic rain predictions allows the model to match the real behavior much closer. For this particular water body, it might make sense to come up with a different way of capturing expected rain which doesn't rely on smoothing; for exampe, use the known means and variances of rain on a given day to actually generate random rain data. Though that would still not capture patters where rainy days are often clumped together, producing an extended spike of inflowing water. And of course, any such approximation wouldn't be able to predict *exactly when* the spikes would happen without making actual weather predictions.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '01ac7f9619219e'}"}
{"id":"136563","text":"\"\"\"\n# **Udemy - Paid or Free?**\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\nIt is rightly said by 'Benjamin Franklin' that 'An investment in knowledge pays the best interest'. This notebook comprises of an educational platform known as udemy that aimes at educating professional adults and students. It was developed in May 2010 and ever since it has successfully provided numerous courses belonging to various subjects. Udemy has not only catered to its english speaking students but also embraced over 65 languages so that language would not be a barrier for all the enthusiastic students world wide. In this notebook we look closely at the various courses that are offered by Udemy, the popularity of certain courses\/subject as well as the factors that influence the price of these courses.\n\"\"\"\n\"\"\"\nKindly provide an upvote if this notebook was useful. Also I would greatly appreciate any feedback or suggeston for improvement. Thank-you :)\n\"\"\"\n# 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)\nimport seaborn as sns\nsns.set_style('whitegrid')\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport datetime as dt\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\n\"\"\"\n# **Data Loading**\n\"\"\"\ntrain = pd.read_csv('..\/input\/udemy-courses\/udemy_courses.csv')\ntrain.head()\nrow = train.shape[0]\ncol = train.shape[1]\nprint(\"The number of rows within the dataset are {} and the number of columns are {}\".format(row,col))\n\"\"\"\n# **Data Cleaning**\n\"\"\"\ntrain.info()\n\"\"\"\nIn our dataset we have features of type: Boolean(1), Float(1), Integer(5) and Object\/String(5). Thus we have a total of 12 features.\n\"\"\"\ntrain.isnull().sum()\n\"\"\"\nSince all the values of each feature are present we do not need to deal with missing values.\n\"\"\"\ndates = []\nfor i in train['published_timestamp']:\n    datess=dt.datetime.strptime(i, '%Y-%m-%dT%H:%M:%SZ')\n    dates.append(datess)\n\ntrain['time'] = dates\ntrain['year'] = train['time'].dt.year\ntrain.head()\ntrain.drop('published_timestamp',axis=1,inplace=True)\n\"\"\"\n# **Data Analysis**\n\"\"\"\n\nFree = train[train['is_paid'] == 0]\nFree.shape\n\nPaid = train[train['is_paid'] == 1]\nPaid.shape\ncolumns = train['subject'].unique()\ncolumns\n\"\"\"\n* What are the best free and paid courses by subject?\n\"\"\"\nfor x in columns:\n    maxr = Free[Free['subject'] == x]['num_subscribers'].max()\n    course = Free[(Free['num_subscribers'] == maxr)]['course_title'].unique()\n    print(\"-----------------------------------------------------------------------------------\")\n    print(\"The best free course offered by udemy for {} is \\n{} with {} subscribers\\n\".format(x,course[0],maxr))\n\nfor x in columns:\n    maxr = Paid[Paid['subject'] == x]['num_subscribers'].max()\n    course = Paid[(Paid['num_subscribers'] == maxr)]['course_title'].unique()\n    print(\"-----------------------------------------------------------------------------------\")\n    print(\"The best paid course offered by udemy for {} is \\n{} with {} subscribers\\n\".format(x,course[0],maxr))\n\n\"\"\"\n* What are the most popular courses?\n\"\"\"\n\nprint(\"The top 5 most popular courses with respect to subcribers are:\\n\")\npopular = train.sort_values(['num_subscribers'],ascending=False).head()['course_title'].unique()\ni = 0\nwhile i<len(popular):\n    print(popular[i])\n    i = i+1\n\"\"\"\n* What are the most engaging courses?\n\"\"\"\ntrain['engagment']  = train['num_subscribers'] * train['num_reviews']\nprint(\"The top 5 most engaging courses with respect to subcribers and reviews are are:\\n\")\nengaging = train.sort_values(['engagment'],ascending=False).head()['course_title'].unique()\ni = 0\nwhile i<len(engaging):\n    print(engaging[i])\n    i = i+1\n\"\"\"\n* Which courses offer the best cost benefit?\n\"\"\"\npriceprefect = train[(train['price']<=train['price'].mean()) & (train['engagment']>=train['engagment'].mean())].sort_values(('engagment'),ascending=False)['course_title'].head(1).unique()[0]\nprint(\"The best course that offers cost benefit is\",priceprefect)\n\"\"\"\n* Which were the most popular courses according to the year they were published?\n\"\"\"\nyears = train['year'].unique()\n\nfor x in years:\n    maxr = train[train['year'] == x]['num_subscribers'].max()\n    course = train[(train['num_subscribers'] == maxr)]['course_title'].unique()\n    print(\"-----------------------------------------------------------------------------------\")\n    print(\"The best course offered by udemy in {} was \\n{} with {} subscribers\\n\".format(x,course[0],maxr))\n    \n\"\"\"\n# **Data Visualization**\n\"\"\"\nsns.countplot('is_paid',data=train)\n\"\"\"\nThe number of paid courses are comparatively more than that of the free courses \n\"\"\"\n\"\"\"\n**Relationship between Subject, Level and Price**\n\"\"\"\nsns.countplot('is_paid',hue='subject',data=train)\n\"\"\"\nA variety of free courses are available for the topic of 'Web Development'. \nLikewise for paid courses there are a variety of course based on 'Business Finance'\n\"\"\"\nsns.countplot('is_paid',hue='level',data=train)\nplt.legend(loc='upper left')\n\"\"\"\nAll types of courses are available for paid courses, whereas there are no expert level courses available for free.\n\"\"\"\nplt.figure(figsize=(8,5))\nsns.countplot('subject',hue='level',data=train)\n\"\"\"\nEach subject have all levels of courses. However there are certain subjects that provide majority courses of a certain level. \nBusiness Finance, Graphic Design and Web Development offer many courses that consists of all the levels.\nMusical Instruments offers a major amount of Beginner level courses.\nAll the subjects have very few expert level courses. \n\"\"\"\ntrain.price.hist(bins=10)\nplt.xlabel(\"Price\")\nplt.title(\"Price range and its frequency\")\n\"\"\"\nThe most purchased courses cost 25$\n\"\"\"\nplt.figure(figsize=(10,5))\nsns.barplot('subject','price',hue='level',data=Paid)\n\"\"\"\nBy comparing all the graphs we notice that the expert level of many subjects costs quite a lot than any other levels of each subject. Thus we can say that this could probably be a factor so as to why many users have not purchased the expert level courses. On the other hand the cost of the courses that serve to all levels and beginner level are very reasonable and popular among users .  \n\"\"\"\n\"\"\"\n**Relationship between Number of Subscribers, Number of Reviews, Subject and Level**\n\"\"\"\nsns.lmplot('num_subscribers','num_reviews',data=train)\n\"\"\"\nThere is a positive\/direct relationship between the number of subscribers and reviews. If we look closely we realise that there are certain outliers within the graph. It is always advisable to deal with these outliers before we train a model for prediction.\n\"\"\"\ntable1 = pd.pivot_table(train, values=['num_subscribers','num_reviews'], index=['is_paid'],aggfunc=np.sum)\ntable1\ntable1.plot(kind='bar')\n\"\"\"\nWe create a pivot table to calculate the total number of subcribers and review present in the free as well as paid courses. We observe that there are more number of subcribers and reviews for paid courses.\n\"\"\"\nplt.figure(figsize=(10,5))\nsns.barplot('subject','num_subscribers',hue='level',data=train)\n\"\"\"\nAll the courses and levels belonging to Web Development have a many subcribers. This is then followed by the Graphic Design that offers all levels and then by the beginner level of the Business Finance.  \n\"\"\"\nplt.figure(figsize=(10,5))\nsns.barplot('subject','num_reviews',hue='level',data=train)\n\"\"\"\nThe most reviews were posted for the course of Web Development.\n\"\"\"\n\"\"\"\n**Relationship between Number of Lectures, Content Duration, Subject and Level**\n\"\"\"\nsns.lmplot('num_lectures','content_duration',data=train)\n\"\"\"\nThere is a positive\/direct relationship between the number of subscribers and reviews. If we look closely with every increase in the number of lectures there is a positive increase in the content duration. However there also exist an amount of outliers.\n\"\"\"\ntable2 = pd.pivot_table(train, values=['num_lectures','content_duration'], index=['is_paid'],aggfunc=np.sum)\ntable2\ntable2.plot(kind='bar')\n\"\"\"\nWe create a pivot table to calculate the total length of the lectures and the number of lectures present in the free as well as paid courses. We observe that there are more number of lectures for paid courses.\n\"\"\"\nplt.figure(figsize=(10,5))\nsns.barplot('subject','content_duration',hue='level',data=train)\n\"\"\"\nThe most content were posted for the course of Web Development. We also observe that there is a very high error rate present in the expert level of the Graphic Design subject.\n\"\"\"\n\"\"\"\n**Relationship between Year of post, Subject and Number of Subcribers**\n\"\"\"\nsns.countplot('year',data=train)\n\"\"\"\nIn the year 2016 there were the most courses that were posted on udemy. \n\"\"\"\ntable3 = pd.pivot_table(train, values=['num_subscribers'], index=['year'],columns=['subject'],aggfunc=np.sum)\ntable3\ntable3.plot(kind='bar',figsize=(10,5))\ntable4 = pd.pivot_table(train, values=['num_lectures'], index=['year'],columns=['subject'],aggfunc=np.sum)\ntable4\ntable4.plot(kind='bar',figsize=(8,5))\n\"\"\"\nWe observe that Web Development courses was the first to begin in the year of 2011 with minimum number of subcribers, it grew popularity in the year 2015 due to which udemy found it beneficial to increase the number of lectures which they did in the year of 2016. In the year 2012 they introduced two other subjects which were Graphic Design and Musical Instruments, these courses did not gain as must popularity among users, therefore the number of lectures increased at a slow pace. In 2013 Business Finance courses were introduced as they gained positive response from the users, the number of additional lectures increased moderately.\n\"\"\"\nplt.figure(figsize=(10,5))\nsns.barplot('year','price',data=train,estimator=np.sum)\n\"\"\"\n# **Summary of observation**\n\"\"\"\n\"\"\"\n* \tThere are many users that have purchased online udemy courses.\n* \tBusiness Finance and Web Development are the most popular subject.\n* \tThere are very few expert level courses among the available paid courses and none among the free courses.\n* \tUsers prefer those courses that cater to  \u2018All Levels\u2019 because they prove to be financially feasible as well as udemy has a wide range of such courses.\n* \t There are a maximum number of subscribers, review, lectures and duration for the paid courses. We observe an error in the duration of free courses that shows only 685.33 Hrs for 6639 lectures which is not possible.\n* \tThe most lectures and duration of these lectures posted belongs to Web Development \u2013 All Levels.\n* \tThere are a high number of posts in the year 2016 that belongs to the courses of Web Development in response to its increasing popularity.\n* \tThe revenue earned in the year 2016 was the highest among the 7 years.\n\n\"\"\"\n\"\"\"\n# **Data Modeling**\n\"\"\"\n\"\"\"\nFor the purpose of Data Modeling we need to split our data into training and test set.Once the split is done we can put our data into various models and check each the precision of each model. We select the model with the highest precision score.\n\"\"\"\nfrom sklearn.model_selection import train_test_split \nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report, confusion_matrix\nmodel = train\nmodel.describe()\n\"\"\"\nWe notice that the minium number of lectures and their duration is 0 which is not possible, thus we need to eliminate that record. \n\"\"\"\nid = model[model['num_lectures'] == 0].index.values[0]\nmodel.drop(id,axis=0,inplace=True)\nmodel.info()\n\"\"\"\nIn the following dataset we have 1 boolean and 2 categorical features for optimum solution it is always desirable to convert these into numeric features. Also we do not need certain features such as title, url and time. Thus we drop these features.\n\"\"\"\nmodel.drop(['course_title','url','time'],axis=1,inplace=True)\ndef fun(val): \n  \n    if val == 0: \n        return 0\n    else: \n        return 1\n    \nmodel['is_paid'] = model['is_paid'].apply(fun)\ndef lev(val): \n  \n    if val == 'All Levels': \n        return 0\n    elif val == 'Intermediate Level': \n        return 1\n    elif val == 'Beginner Level': \n        return 2\n    else:\n        return 3\n    \nmodel['level'] = model['level'].apply(lev)\ndef sub(val): \n  \n    if val == 'Business Finance': \n        return 0\n    elif val == 'Graphic Design': \n        return 1\n    elif val == 'Musical Instruments': \n        return 2\n    else:\n        return 3\n    \nmodel['subject'] = model['subject'].apply(sub)\ndef year(val): \n  \n    if val == 2017: \n        return 6\n    elif val == 2016: \n        return 5\n    elif val == 2015: \n        return 4\n    elif val == 2014: \n        return 3\n    elif val == 2013: \n        return 2\n    elif val == 2012: \n        return 1\n    else:\n        return 0\n    \nmodel['year'] = model['year'].apply(year)\n\"\"\"\nWe convert the year feature into simple values that can be used for prediction. \n\"\"\"\nX = model.drop(['course_id','is_paid'],axis=1)\ny = model['is_paid']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=101)\n\"\"\"\n# **1. Logistic Regression**\n\"\"\"\n#Import Packages \nfrom sklearn.linear_model import LogisticRegression\n#Object creation and fitting of training set\nlmodel = LogisticRegression()\nlmodel.fit(X_train,y_train)\n#Creation of a prediction variable\nlpredictions = lmodel.predict(X_test)\n#Accuracy Matrix\nprint(\"Confusion Matrix\")\nprint(confusion_matrix(y_test,lpredictions))\n\nlscore = round((lmodel.score(X_test, y_test)*100),2)\nprint (\"\\nModel Score:\",lscore,\"%\")\n\"\"\"\n# **2. K-Nearest Neighbour**\n\"\"\"\n#Import Packages \nfrom sklearn.neighbors import KNeighborsClassifier\nkmodel = KNeighborsClassifier(n_neighbors=3)\nkmodel.fit(X_train,y_train)\n#Creation of a prediction variable\nkpredictions = kmodel.predict(X_test)\n#Accuracy Matrix\nprint(\"Confusion Matrix\")\nprint(confusion_matrix(y_test,kpredictions))\n\nkscore = round((kmodel.score(X_test, y_test)*100),2)\nprint (\"\\nModel Score:\",kscore,\"%\")\n\"\"\"\n# **3.Decision Tree**\n\"\"\"\n#Import Packages \nfrom sklearn.tree import DecisionTreeClassifier\n#Object creation and fitting of training set\ndmodel = DecisionTreeClassifier()\ndmodel.fit(X_train,y_train)\n#Creation of a prediction variable\ndprediction = dmodel.predict(X_test)\n#Accuracy Matrix\nprint(\"Confusion Matrix\")\nprint(confusion_matrix(y_test,dprediction))\n\ndscore = round((dmodel.score(X_test, y_test)*100),2)\nprint (\"\\nModel Score:\",dscore,\"%\")\n\"\"\"\n# **4.Random Forest**\n\"\"\"\n#Import Packages \nfrom sklearn.ensemble import RandomForestClassifier\n#Object creation and fitting of training set\nrmodel = RandomForestClassifier(n_estimators=100)\nrmodel.fit(X_train,y_train)\n#Creation of a prediction variable\nrprediction = rmodel.predict(X_test)\n\n#Accuracy Matrix\nprint(\"Confusion Matrix\")\nprint(confusion_matrix(y_test,rprediction))\n\nrscore = round((rmodel.score(X_test, y_test)*100),2)\nprint (\"\\nModel Score:\",rscore,\"%\")\n\"\"\"\n# **5.Support Vector Machine**\n\"\"\"\n#Import Packages \nfrom sklearn.svm import SVC\n#Object creation and fitting of training set\nsmodel = SVC()\nsmodel.fit(X_train,y_train)\n#Creation of a prediction variable\nsprediction = smodel.predict(X_test)\n#Accuracy Matrix\nprint(\"Confusion Matrix\")\nprint(confusion_matrix(y_test,sprediction))\n\nsscore = round((smodel.score(X_test, y_test)*100),2)\nprint (\"\\nModel Score:\",sscore,\"%\")\n\"\"\"\n# **Conclusion**\n\"\"\"\ndata = [['Logistic Regression',lscore],['K-Nearest Neighbour',kscore],\n        ['Decision Tree',dscore],['Random Forest',rscore],['Support Vector Machine',sscore]]\nfinal = pd.DataFrame(data,columns=['Algorithm','Precision'],index=[1,2,3,4,5])\nprint(\"The results of Data Modeling are as follows:\\n \")\nprint(final)\n\"\"\"\nAmong all the algorithms we notice that Decision Tree and Random Forest are of utmost precision. Therefore we can use either one of them to predict the price of the courses.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fb04340f94dd1c'}"}
{"id":"87540","text":"\"\"\"\n\n<h1 style='background:#2cab6c; border:0; color:white'><center>Importing Libraries<\/center><\/h1>\n\"\"\"\nimport os\n\nimport numpy as np\nimport cv2 as cv\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nfrom pathlib import Path\nfrom tqdm import tqdm\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Paths, files<\/center><\/h1>\n\"\"\"\n# Paths to the base directories\/files of the dataset\nbase_dir = Path('\/kaggle\/input\/cassava-leaf-disease-classification')\ntrain_img_dir = f'{base_dir}\/train_images'\ntest_img_dir = f'{base_dir}\/test_images'\n# Read train csv and json files with labels mapped to disease names\ntrain_df = pd.read_csv(f'{base_dir}\/train.csv')\ndisease_mapping = pd.read_json(f'{base_dir}\/label_num_to_disease_map.json', typ='series')\n# Create lists with all train and test images\ntrain_images = os.listdir(f'{base_dir}\/train_images\/')\ntest_images = os.listdir(f'{base_dir}\/test_images\/')\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Labels Mapping, Training Dataset<\/center><\/h1>\n\"\"\"\n# Convert mapping to dict\nmapping_dict = disease_mapping.to_dict()\n# Show dict\nmapping_dict\n\"\"\"\nAs you can see, the dataset contains 5 classes\n\"\"\"\n# Show first 10 lines of train dataset\ntrain_df.head(10)\n\"\"\"\nWe can see the name of the images and their class labels here. The labels are represented as numbers, but for convenience we can replace them with the appropriate names.\n\"\"\"\n# Let's check for any missing values in the train labels\nmissing = train_df.isnull().sum()\nall_value = train_df.count()\n\nmissing_df = pd.concat([missing, all_value], axis=1, keys=['Missing Val.', 'All Val.'])\nmissing_df\n\"\"\"\nYou can see that there are no missing in the data.\n\"\"\"\n# Let's replace numeric labels in dataset with disease names\ntrain_df = train_df.replace(mapping_dict)\n# Show first 10 lines of train dataset with replaced labels\ntrain_df.head(10)\n# Let's count the num of training samples for each label\nlabel_counts = train_df['label'].value_counts().reset_index()\nlabel_counts.columns = ['Label', 'Num. of Observations']\n\n# Create Pie Chart\nfig = px.pie(label_counts,\n             names='Label', values='Num. of Observations',\n             labels=mapping_dict,\n             title='Percentage Distribution of Labels in the Training Dataset')\nfig.show()\n\"\"\"\nYou can see that the dataset contains a significant class imbalance, where most of the images are of the Cassava Mosaic Disease (CMD) class.\n\nThe dataset contains only 12% of the data with images of healthy leaves, while all other images are for diseased leaves.\n\"\"\"\n# Let's check if the dataset contains duplicate images\nunique_idx = train_df['image_id'].nunique()\n\nif unique_idx == len(train_df):\n    print('There are no duplicate image indices in the training dataset.')\nelse:\n    print(f'There are {len(train_df) - unique_idx} duplicate image indices in the training dataset.')\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Training Image Dataset<\/center><\/h1>\n\"\"\"\n# Let's check how many images are in the training dataset\nprint(f'{len(train_images)} training images contains dataset.')\n# Let's check the resolution of the images to make sure they're all standardized\nimgs_shape = []\n\nfor img in tqdm(train_images):\n    image = cv.imread(f'{base_dir}\/train_images\/{img}')\n    imgs_shape.append(image.shape)\n    \nprint(f'The training set contains the following unique image shapes: {set(imgs_shape)}')\n\"\"\"\nWe can see that all the images have the same shape: 600 by 800 pixels with 3 channels.\n\"\"\"\n# Let's break the training dataset into separate lists with images for each class\nhealthy_imgs = train_df[train_df['label'] == 'Healthy']['image_id'].to_list()\ncmd_imgs = train_df[train_df['label'] == 'Cassava Mosaic Disease (CMD)']['image_id'].to_list()\ncgm_imgs = train_df[train_df['label'] == 'Cassava Green Mottle (CGM)']['image_id'].to_list()\ncbsd_imgs = train_df[train_df['label'] == 'Cassava Brown Streak Disease (CBSD)']['image_id'].to_list()\ncbb = train_df[train_df['label'] == 'Cassava Bacterial Blight (CBB)']['image_id'].to_list()\n\"\"\"\nNext, we will implement a couple of helper functions for displaying images and their color histograms.\n\"\"\"\ndef show_img(imgs_list, title):\n    \"\"\"Function for displaying images\n    \n    Args:\n        img_list (list): a list that contains the names of the image files\n        title (str): class label name\n    \"\"\"\n    images = [np.random.choice(imgs_list) for i in range(6)]\n    \n    plt.figure(figsize=(12, 12))\n    plt.suptitle(title, fontsize=24)\n    \n    for i in range(6):\n        plt.subplot(3, 3, i+1)\n        img = plt.imread(f'{train_img_dir}\/{images[i]}')\n        plt.imshow(img, cmap='gray')\n        plt.axis('off')\n    \n    plt.tight_layout()\ndef show_hist(imgs_list, title):\n    \"\"\"Function to display a random image from a dataset and its histogram of color channels\n    \n    Args:\n        img_list (list): a list that contains the names of the image files\n        title (str): class label name\n    \"\"\"\n    image = np.random.choice(imgs_list)\n    \n    fig = plt.figure(figsize=(12, 12))\n    \n    fig.add_subplot(1, 2, 1)\n    \n    img = plt.imread(f'{train_img_dir}\/{image}')\n    \n    plt.title(title)\n    plt.imshow(img, cmap='gray')\n    plt.axis('off')\n    \n    print(f'Image dimensions: {img.shape[0], img.shape[1]}',\n          f'Max pixel value: {img.max()}',\n          f'Min pixel value: {img.min()}',\n          f'Mean pixel value: {round(img.mean())}',\n          f'Standard deviation: {round(img.std())}', sep='\\n')\n    \n    fig.add_subplot(1, 2, 2)\n    \n    plt.hist(img[:, :,  0].ravel(), bins=256, color='red', alpha=0.5)\n    plt.hist(img[:, :,  1].ravel(), bins=256, color='green', alpha=0.5)\n    plt.hist(img[:, :,  2].ravel(), bins=256, color='blue', alpha=0.5)\n    \n    plt.xlabel('Intensity Value')\n    plt.ylabel('Count')\n    plt.legend(['Red Channel', 'Green Channel', 'Blue Channel'])\n    \n    plt.show()\ndef get_rgb_image(image_idx):\n    \"\"\"Function for getting a NumPy Array of an image and converting it from BGR to RGB\n    \n    Args:\n        image_idx (str): image file name\n        \n    Returns:\n        ndarray: NumPy Array of an image\n    \"\"\"\n    img = cv.imread(f'{train_img_dir}\/{image_idx}')\n    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n    return img\ndef get_histograms_data(imgs_list):\n    \"\"\"Function for getting median values of color channels of input images\n    \n    Args:\n        img_list (list): a list that contains the names of the image files\n        \n    Returns:\n        list: a list that contains the median values of the color channels of images\n    \"\"\"\n    img = [get_rgb_image(image_idx) for image_idx in imgs_list]\n    \n    red_values = [np.mean(img[idx][:, :, 0]) for idx in range(len(img))]\n    green_values = [np.mean(img[idx][:, :, 1]) for idx in range(len(img))]\n    blue_values = [np.mean(img[idx][:, :, 2]) for idx in range(len(img))]\n    all_mean_values = [np.mean(img[idx]) for idx in range(len(img))]\n    \n    return [red_values, green_values, blue_values, all_mean_values]\ndef show_box_plot(imgs_list, title):\n    \"\"\"Function for displaying box-plots of histogram of color channels of images\n    \n    Args:\n        img_list (list): a list that contains the names of the image files\n        title (str): class label name\n    \"\"\"\n    fig_data = []\n    hist_data = get_histograms_data(imgs_list)\n    \n    for i, name in zip(range(3), ['Red', 'Green', 'Blue']):\n        mark = go.Box(y=hist_data[i],\n                      name=name,\n                      boxpoints='all',\n                      marker_color=name)\n        fig_data.append(mark)\n    \n    fig = go.Figure(fig_data)\n    fig.update_layout(title_text=f'{title} - Distribution of Pixel Values')\n    fig.show()\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Test Image Dataset<\/center><\/h1>\n\"\"\"\n# Let's check how many images the test dataset contains\nprint(f'The training set contains {len(test_images)} image.')\n\"\"\"\nAs you can see, the test case contains only one image. Therefore, when training the model, we will need to split the training dataset into test and validation.\n\nAlso, as stated in the description of the Kaggle competition, the test set contains 15k images, and it becomes available only after we send our notebook for scoring.\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Healthy<\/center><\/h1>\n\"\"\"\nshow_img(healthy_imgs, 'Healthy')\nshow_hist(healthy_imgs, 'Healthy')\nshow_box_plot(healthy_imgs, 'Healthy')\n\"\"\"\nWe can see the following distribution of median values for pixel intensities:\n\n- Red: 108\n- Green: 126\n- Blue: 80\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Cassava Mosaic Disease (CMD)<\/center><\/h1>\n\"\"\"\nshow_img(cmd_imgs, 'Cassava Mosaic Disease (CMD)')\nshow_hist(cmd_imgs, 'Cassava Mosaic Disease (CMD)')\nshow_box_plot(cmd_imgs[:5000], 'Cassava Mosaic Disease (CMD)')\n\"\"\"\nFor this class, we only used the first 5000 images.\n\nWe can see the following distribution of median values for pixel intensities:\n\n- Red: 109\n- Green: 128\n- Blue: 79\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Cassava Green Mottle (CGM)<\/center><\/h1>\n\"\"\"\nshow_img(cgm_imgs, 'Cassava Green Mottle (CGM)')\nshow_hist(cgm_imgs, 'Cassava Green Mottle (CGM)')\nshow_box_plot(cgm_imgs, 'Cassava Green Mottle (CGM)')\n\"\"\"\nWe can see the following distribution of median values for pixel intensities:\n\n- Red: 113\n- Green: 128\n- Blue: 85\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Cassava Brown Streak Disease (CBSD)<\/center><\/h1>\n\"\"\"\nshow_img(cbsd_imgs, 'Cassava Brown Streak Disease (CBSD)')\nshow_hist(cbsd_imgs, 'Cassava Brown Streak Disease (CBSD)')\nshow_box_plot(cbsd_imgs, 'Cassava Brown Streak Disease (CBSD)')\n\"\"\"\nWe can see the following distribution of median values for pixel intensities:\n\n- Red: 106\n- Green: 123\n- Blue: 72\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Cassava Bacterial Blight (CBB)<\/center><\/h1>\n\"\"\"\nshow_img(cbb, 'Cassava Bacterial Blight (CBB)')\nshow_hist(cbb, 'Cassava Bacterial Blight (CBB)')\nshow_box_plot(cbb, 'Cassava Bacterial Blight (CBB)')\n\"\"\"\nWe can see the following distribution of median values for pixel intensities:\n\n- Red: 102\n- Green: 117\n- Blue: 66\n\"\"\"\n\"\"\"\n<h1 style='background:#2cab6c; border:0; color:white'><center>Conclusion<\/center><\/h1>\n\"\"\"\n\"\"\"\nThe dataset contains 21397 images. There are 5 class labels in total, including 4 disease labels and one plant health label. From EDA we see that the training labels are highly imbalanced: more than 60% of the training labels are in the CMD class, and only about 5% of them are in the CBB class. So far, we cannot predict how an imbalance in the dataset will affect the accuracy of the classification model.\n\nThe size of the images is 600 by 800 pixels. In training, we will reduce the size of the images to train the model more efficiently.\n\nAlso, by analyzing the histograms of color channels, we see that diseases are always accompanied by obvious discrepancies in color. Namely:\n\n- CGM class images have the highest median values of RGB channels;\n- CBB class images have the lowest median values of RGB channels.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a08261f856f6e7'}"}
{"id":"68889","text":"\"\"\"\n# A.Paste String \n\"\"\"\n\"\"\"\n# 1.f String\n\"\"\"\nage = 20\nname = \"Python\"\n\nsendtence = f\"I am {name}. I am {age} years old\"\nsendtence\n\"\"\"\n# 2.using + \n\"\"\"\nage = 20\nname = \"Python\"\n\nsendtence = \"I am \" + name +\". I am \" + str(age) + \" years old\"\nsendtence\n\"\"\"\n# 3.% format \n\"\"\"\nage = 20\nname = \"Python\"\n\nsendtence = \"I am %s. I am %s years old.\" % (name, age)\nsendtence\n\"\"\"\n# 4.str.format\n\"\"\"\nage = 20\nname = \"Python\"\n\nsendtence = \"I am %s. I am %s years old.\".format(name, age)\nsendtence\n\"\"\"\n# B.Paste List\n\"\"\"\n\"\"\"\n# 1.join (list -> string)\n\"\"\"\nwords = ['I', 'am', 'a', 'student']\nsentence = \" \".join(words)\nsentence\nfolderName = \"newFolder\"\nfileName = \"newFile\"\npathList = [folderName,fileName]\n\nfilePath = \"\/\".join(pathList)\nfilePath\n\"\"\"\n# 2.split (string -> list)\n\"\"\"\nlistSentence = sentence.split()\nprint(listSentence)\nlistFilePath = filePath.split(\"\/\")\nlistFilePath","meta":"{'source': 'AI4Code', 'id': '7ed76616c55ab2'}"}
{"id":"4317","text":"\"\"\"\n# \u671f\u672b\u5831\u544a\n#### \u7d44\u54e1: \u5ed6\u54c1\u745c\u3001\u80e1\u7b46\u52dd\n\"\"\"\n\"\"\"\n## 1.Dataset\u7c21\u4ecb\n#### \u9019\u500b\u8cc7\u6599\u96c6\u6536\u96c6\u4e86\u5f9e2007\u5e74\u8d77\u6fb3\u6d32\u5404\u5730\u5929\u6c23\u7ad9\u7684\u6c23\u8c61\u8cc7\u6599\uff0c\u5305\u542b\u4eca\u5929\u662f\u5426\u964d\u96e8\u3001\u964d\u96e8\u91cf\u3001\u84b8\u767c\u91cf\u3001\u65e5\u7167\u3001\u4e0d\u540c\u6642\u6bb5\u7684\u98a8\u901f\u8207\u98a8\u5411\u3001\u4e0d\u540c\u6642\u6bb5\u7684\u6eab\u5ea6\u4ee5\u53ca\u660e\u5929\u662f\u5426\u964d\u96e8...\u7b49\u7b49\u4e0d\u540c\u8cc7\u6599\u3002\n\n#### \u7db2\u5740:https:\/\/www.kaggle.com\/jsphyg\/weather-dataset-rattle-package\n\"\"\"\n# data analysis and wrangling\nimport pandas as pd\nimport numpy as np\nimport random as rnd\n# machine learning\nfrom sklearn import tree\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import metrics\n# visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\"\"\"\n## 2.\u554f\u984c\u5b9a\u7fa9\n#### \u6839\u64da\u4eca\u5929\u7684\u5404\u7a2e\u6c23\u8c61\u8cc7\u6599\uff0c\u8a13\u7df4\u4e00\u500b\u6a21\u578b\u9810\u6e2c\u6fb3\u6d32\u660e\u5929\u6703\u4e0d\u6703\u4e0b\u96e8\u3002\n\"\"\"\n#read in\npd_data = pd.read_csv('..\/input\/weatherAUS.csv')\npd_data.shape\n\"\"\"\n## 3.\u8cc7\u6599\u524d\u8655\u7406\n#### 3.1 \u9996\u5148\u5c07\u6709\u7f3a\u5931\u7684\u5217\u522a\u9664\uff0c\u907f\u514d\u8cc7\u6599\u4e0d\u8db3\u96e3\u4ee5\u9810\u6e2c\u3002\n\n\n\"\"\"\n#drop NAN\npd_data=pd_data.dropna(how='any')\nprint(pd_data.shape)\n\"\"\"\n\n#### 3.2 \u6211\u5011\u8a8d\u70ba\u65e5\u671f\u3001\u5730\u9ede\u90fd\u4e0d\u662f\u5f71\u97ff\u660e\u65e5\u662f\u5426\u6703\u4e0b\u96e8\u7684\u56e0\u7d20\uff0c\u56e0\u6b64\u5c07'Date','Location'\u522a\u9664\u3002\n#### 'WindGustDir', 'WindDir9am', 'WindDir3pm'\u70ba\u98a8\u5411\uff0c\u5206\u7531\u65bc\u662f\u4ee5\u6587\u5b57\u8868\u793a\uff0c\u96e3\u8f49\u63db\u6210\u6578\u5b57\uff0c\u56e0\u6b64\u5728\u6b64\u5148\u4e0d\u8003\u616e\u3002\n#### 'RISK_MM'\u662f\u6c23\u8c61\u5c40\u7d66\u51fa\u7684\u660e\u5929\u96e8\u91cf\u4f30\u8a08\uff0c\u57fa\u672c\u4e0a\u5c31\u662f\u6211\u5011\u8981\u7684\u7d50\u679c\uff0c\u82e5\u5c07\u6b64\u884c\u52a0\u5165\u6703overfitting\uff0c\u6545\u522a\u9664\u3002\n\n\"\"\"\n#drop something column\ndrop_columns_list = ['WindGustDir', 'WindDir9am', 'WindDir3pm','Date','Location','RISK_MM']\npd_data = pd_data.drop(drop_columns_list, axis=1)\nprint(pd_data.shape)\npd_data.head()\n#change yes\/no to 1\/0\npd_data['RainToday'].replace({'No':0,'Yes':1},inplace=True)\npd_data['RainTomorrow'].replace({'No':0,'Yes':1},inplace=True)\npd_data.head()\n\"\"\"\n#### 3.3 RainToday\u539f\u672c\u7531Yes\/No\u7d44\u6210\uff0c\u5c07\u5176\u6539\u70baYes=1,No=0\n####    \u5c07\u8cc7\u6599\u5206\u6210\u8a13\u7df4Train\u8207\u6e2c\u8a66Test\u90e8\u5206\uff0cTrain\u5360\u4e8655000\u7b46\uff0cTest\u67091420\u7b46\uff0c\u4e26\u628a\u8981\u5f97\u51fa\u7684\u7d50\u679c\u5207\u51fa\u4f86\u3002\n\"\"\"\n#Task: Split the data into train and test\ntrain_y = pd_data['RainTomorrow'].head(55000)\ntest_y= pd_data['RainTomorrow'].tail(1420)\ntrain_x = pd_data.head(55000).drop(['RainTomorrow'], axis=1)\ntest_x= pd_data.tail(1420).drop(['RainTomorrow'], axis=1)\nprint(train_y.head())\nprint(train_x.head())\n\"\"\"\n## 4.\u6a21\u578b\n\n### 4.1 Decision tree\n\"\"\"\nimport graphviz \ndtree=tree.DecisionTreeClassifier(max_depth=3)\ndtree=dtree.fit(train_x,train_y)\ndot_data = tree.export_graphviz(dtree, \n                filled=True, \n                feature_names=list(train_x),\n                class_names=['No rain','rain'],\n                special_characters=True)\ngraph = graphviz.Source(dot_data)  \n\ngraph\n#\u4e0d\u540c\u8cc7\u6599\u8207\u7d50\u679c\u7684\u95dc\u806f\u6027\ndtree.feature_importances_\n\n#\u628a\u8a13\u7df4\u597d\u7684\u6a21\u578b\u5957\u7528\u5230\u6e2c\u8a66\u6578\u64da\npredict_y = dtree.predict(test_x)\npredict_y\n#\u8a08\u7b97\u8a13\u7df4\u6578\u64da\u8207\u6e2c\u8a66\u6578\u64da\u7684\u6b63\u78ba\u7387\nfrom sklearn.metrics import accuracy_score\nacc_log = dtree.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_log)\nx=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % x)\n#test\n#\u6e2c\u8a66\u4e0d\u540c\u7684\u53c3\u6578\uff0c\u767c\u73fe\u4e26\u6c92\u6709\u592a\u5927\u6539\u8b8a\n#for i in range(400,601,5):    \n    \"\"\"dtree=tree.DecisionTreeClassifier(min_samples_split=1000,min_samples_leaf =570)\n    dtree=dtree.fit(train_x,train_y)\n    predict_y = dtree.predict(test_x)\n    x=accuracy_score(test_y, predict_y)\n    print('%d' % i,'test accuracy: %.5f'  %x)\"\"\"\n#auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('max_depth=3 auc: %.5f' % metrics.auc(fpr, tpr))\n\"\"\"\n#### 4.1.1 \u6e2c\u8a66\u4e0d\u540cmax_depth\u7684\u6b63\u78ba\u7387\n\"\"\"\ntree_train_acc=[]   #\u8a13\u7df4\u6a21\u578b\u5957\u7528\u5230\u8a13\u7df4\u6578\u64da\u7684\u6b63\u78ba\u7387\ntree_test_acc=[]    #\u8a13\u7df4\u6a21\u578b\u5957\u7528\u5230\u6e2c\u8a66\u6578\u64da\u7684\u6b63\u78ba\u7387\ntree_depth=[]       #\u4e0d\u540c\u7684max_depth\n\nfor i in range (2,20):\n    dtree=tree.DecisionTreeClassifier(max_depth=i)\n    dtree=dtree.fit(train_x,train_y)\n    acc_log = dtree.score(train_x, train_y)\n    print('max_depth=%d ' % i,'training accuracy: %.5f' % acc_log)\n    \n    predict_y = dtree.predict(test_x)    \n    X=accuracy_score(test_y, predict_y)\n    print('\\t\\ttest accuracy: %.5f' % X)\n    \n    tree_train_acc.append(acc_log)\n    tree_test_acc.append(X)\n    tree_depth.append(i)\n    \nplt.plot(tree_depth,tree_train_acc,'b', label=\"training accuracy\")\nplt.plot(tree_depth,tree_test_acc,'r', label=\"test accuracy\")\nplt.ylabel('accuracy (%)')\nplt.xlabel('max depth ')\nplt.legend()\nplt.show()\n\nbest_depth = tree_depth[tree_test_acc.index(max(tree_test_acc))]\nprint (\"max depth: \", best_depth)\nprint (\"best test accuracy: %.5f\"% max(tree_test_acc))\n\"\"\"\n\u5f9e\u4e0a\u5716\u53ef\u4ee5\u770b\u51fa\uff0c\u8a13\u7df4\u6578\u64da\u7684\u6b63\u78ba\u7387\u96a8\u8457max_depth\u7684\u589e\u52a0\u800c\u4e0a\u5347\uff0c\u4f46\u662f\u6e2c\u8a66\u6578\u64da\u7684\u6b63\u78ba\u7387\u4e0d\u6703\u3002max_depth=7\u6642\uff0c\u6e2c\u8a66\u6578\u64da\u7684\u6b63\u78ba\u7387\u9054\u5230\u6700\u9ad8\uff0c\u7d04\u7565\u70ba0.86479%\u3002\u6240\u4ee5\u53ef\u4ee5\u8a8d\u5b9amax_depth=7\u6642\u7684\u6a21\u578b\u8f03\u597d\uff0cmax_depth>7\u7684\u6a21\u578b\u6703\u6709overfitting\u7684\u73fe\u8c61\u3002\n\"\"\"\n#dtree=tree.DecisionTreeClassifier(max_depth=7)\n#dtree=dtree.fit(train_x,train_y)\n#predict_y = dtree.predict(test_x)\n#X=accuracy_score(test_y, predict_y)\n#print('max_depth=7 test accuracy: %.5f' % X)\n#\u6a21\u578b\u8a55\u50f9 auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('max_depth=7 auc: %.5f' % metrics.auc(fpr, tpr))\n\"\"\"\nauc>0.5 \u8868\u793a\u6a21\u578b\u9810\u6e2c\u6bd4\u96a8\u6a5f\u731c\u6e2c\u6e96\u78ba\n\"\"\"\n# \u4ea4\u53c9\u9a57\u8b49 cross validation \nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nscores = cross_val_score(dtree,train_x,train_y,cv=5,scoring='accuracy')\n\n# \u8a08\u7b97\u5e73\u5747\u503c\u8207\u6a19\u6e96\u5dee\nprint('average of Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n#### 4.2 Decision tree\u7d50\u679c\u89c0\u5bdf\n1. 3\u5c64\u7684\u6c7a\u7b56\u6a39\u53ef\u4ee5\u670983.6%\u7684\u6b63\u78ba\u7387\u3002\n2. 7\u5c64\u7684\u6c7a\u7b56\u6a39\u7684\u9810\u6e2c\u6b63\u78ba\u7387\u6700\u9ad8\uff0c\u670986.5%\u3002\n\"\"\"\n\"\"\"\n## 5.\u4e0d\u540c\u7684\u6a21\u578b\n### 5.1 logistic regression\n\"\"\"\n# logistic regression\n\nlogreg = LogisticRegression()\nlogreg = logreg.fit(train_x, train_y)\npredict_y = logreg.predict(test_x)\nacc_log = logreg.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_log)\n\npredict_y =logreg.predict(test_x)\nX=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % X)\n\n#auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('auc: %.5f' % metrics.auc(fpr, tpr))\n\n#Cross validation\nscores = cross_val_score(logreg,train_x,train_y,cv=5,scoring='accuracy')\n# \u8a08\u7b97Cross validation\u7684\u5e73\u5747\u503c\u8207\u6a19\u6e96\u5dee\nprint('average of Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n# Support Vector Machines\n#\u904b\u7b97\u6642\u9593\u592a\u9577\n'''\nsvc = SVC(gamma='auto',C=0.1,kernel=\"linear\", probability=True)\nsvc.fit(train_x, train_y)\npredict_y= svc.predict(test_x)\nacc_svc = svc.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_svc)\n\npredict_y =svc.predict(test_x)\nX=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % X)'''\n\"\"\"\n\n### 5.2 knn\n\"\"\"\n# knn\n\nknn = KNeighborsClassifier(n_neighbors = 10)\nknn.fit(train_x, train_y)\npredict_y = knn.predict(test_x)\nacc_knn = knn.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_knn)\n\npredict_y =knn.predict(test_x)\nX=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % X)\n\n#auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('auc: %.5f' % metrics.auc(fpr, tpr))\n\n#Cross validation\nscores = cross_val_score(knn,train_x,train_y,cv=5,scoring='accuracy')\nprint('average of Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n### 5.3 Gaussian Naive Bayes\n\"\"\"\n# Gaussian Naive Bayes\n\ngaussian = GaussianNB()\ngaussian.fit(train_x, train_y)\npredict_y = gaussian.predict(test_x)\nacc_gaussian = gaussian.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_gaussian)\n\npredict_y =gaussian.predict(test_x)\nX=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % X)\n\n#auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('auc: %.5f' % metrics.auc(fpr, tpr))\n\n#Cross validation\nscores = cross_val_score(gaussian,train_x,train_y,cv=5,scoring='accuracy')\nprint('average of Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n## 6.\u5f8c\u7e8c\u5de5\u4f5c\n1. \u4f7f\u7528Random forest \n2. \u5c07\u98a8\u5411\u7684\u8cc7\u6599\u3001\u4e14\u5c07\u65e5\u671f\u8f49\u63db\u6210\u5b63\u7bc0\uff0c\u91cd\u65b0\u52a0\u5165\u8a13\u7df4\u6a21\u578b\u4e2d\uff0c\u78ba\u8a8d\u662f\u5426\u6709\u66f4\u597d\u7684\u7d50\u679c\u3002\n3. \u53ef\u4ee5\u5c07Location\u91cd\u65b0\u52a0\u5165\u8a13\u7df4\u6a21\u578b\uff0c\u9810\u6e2c\u5404\u5730\u9ede\u660e\u5929\u662f\u5426\u964d\u96e8\u3002\n\n(\u8a3b\uff1a\u300c\u5f8c\u7e8c\u5de5\u4f5c\u300d\u662f\u53e3\u982d\u5831\u544a\u6642\u9084\u672a\u5b8c\u6210\u7684\u5de5\u4f5c)\n\n\"\"\"\n\"\"\"\n### 6.1 Random Forest\n\"\"\"\n\"\"\"\n#### 6.1.1 \u8a08\u7b97n_estimators=1000\u7684\u60c5\u6cc1\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nrdf = RandomForestClassifier(bootstrap=True, n_estimators=1000, max_depth=7)\nrdf.fit(train_x, train_y)  \nacc_log = rdf.score(train_x, train_y)\nprint('training accuracy: %.5f' % acc_log)\n\npredict_y =rdf.predict(test_x)\nX=accuracy_score(test_y, predict_y)\nprint('test accuracy: %.5f' % X)\n#auc\nfpr, tpr, thresholds = metrics.roc_curve(test_y, predict_y, pos_label=1)\nprint('auc: %.5f' % metrics.auc(fpr, tpr))\n\n#Cross validation\n#\u904b\u7b97\u6642\u9593\u592a\u9577\n'''scores = cross_val_score(rdf,train_x,train_y,cv=5,scoring='accuracy')\nprint(scores)\nprint('Cross validation: %.5f'%scores.mean())'''\n\"\"\"\n#### 6.1.2 \u6c7a\u5b9a\u6700\u4f73\u7684n_estimators\n\"\"\"\n#Parameters:\u6c7a\u5b9a\u6700\u4f73\u7684n_estimators\n#\u76ee\u524d\u53ea\u7b97\u5230n_estimators=256\uff0c\u592a\u5927\u9700\u8981\u6642\u9593\u904e\u9577\n\nfrom sklearn import model_selection, metrics\n\ndef scorer(model, X,  train_y):\n    preds = model.predict(X)\n    return metrics.accuracy_score( train_y, preds)\n\nn_estimators = [1,2,4,8,16,32,64,128, 256]  ## try different n_estimators\ncv_results = []\n\nfor estimator in n_estimators:\n    rf = RandomForestClassifier(n_estimators=estimator)\n    acc = model_selection.cross_val_score(rf, train_x,  train_y, cv=5, scoring=scorer)\n    cv_results.append(acc.mean())\nline1= plt.plot(n_estimators, cv_results, 'b', label=\"cross validated accuracy\")\nplt.ylabel('accuracy')\nplt.xlabel('n_estimators')\nplt.legend()\nplt.show()\n\"\"\"\n\u5f9e\u76ee\u524d\u7684\u7d50\u679c\u53ef\u77e5\uff0c\u5728n_estimators=256\u4ee5\u5167\uff0c\u6b63\u78ba\u7387\u6709\u4e0a\u5347\u7684\u8da8\u52e2\uff0c\u800c\u4e14n_estimators\u8d8a\u5927\uff0c\u4e0a\u5347\u8da8\u52e2\u8d8a\u7de9\u3002\u4f46\u662f\u56e0\u70ba\u8a08\u7b97\u6642\u9593\u7684\u554f\u984c\uff0cn_estimators>256\u7684\u60c5\u6cc1\u66ab\u6642\u4e0d\u8a08\u7b97\u3002\n\"\"\"\nbest_n_estimators = n_estimators[cv_results.index(max(cv_results))]\nprint (\"best_n_estimators: \", best_n_estimators)\nprint (\"best accuracy: \", max(cv_results))\n\"\"\"\n#### 6.1.3 random forest\u7d50\u679c\u89c0\u5bdf\n\u548c\u4f7f\u7528Decision tree\u76f8\u6bd4\uff0crandom forest\u6c92\u6709\u63d0\u9ad8\u6b63\u78ba\u7387\u3002\n\"\"\"\n\"\"\"\n### 6.2 \u5c07\u5730\u9ede\u8003\u616e\u9032\u53bb\n\n\"\"\"\npd_data = pd.read_csv('..\/input\/weatherAUS.csv')\npd_data=pd_data.dropna(how='any')\nprint(pd_data.shape)\n\ndrop_columns_list = ['WindGustDir', 'WindDir9am', 'WindDir3pm','Date','Sunshine','RISK_MM']\npd_data = pd_data.drop(drop_columns_list, axis=1)\nprint(pd_data.shape)\n\npd_data['RainToday'].replace({'No':0,'Yes':1},inplace=True)\npd_data['RainTomorrow'].replace({'No':0,'Yes':1},inplace=True)\ngroupbyLocation=pd_data.groupby('Location')\nprint(groupbyLocation.size().sort_values(ascending=False))\n\n\"\"\"\n#### 6.2.1 \u628a\u5730\u9ede\u8f49\u70ba\u6578\u5b57\n\"\"\"\npd_data['Location'] = pd_data['Location'].map( {'Darwin':0,'Perth':1,'Brisbane':2,'MelbourneAirport':3,\n                                                'PerthAirport':4,'SydneyAirport':5,'Watsonia':6,'Mildura':7,\n                                                'MountGambier':8,'NorfolkIsland':9,'Cairns':10,'Townsville':11,\n                                                'WaggaWagga':12,'AliceSprings':13,'Nuriootpa':14,'Hobart':15,\n                                                'Moree':16,'Melbourne':17,'Portland':18,'Woomera':19,\n                                                'Sydney':20,'Sale':21,'CoffsHarbour':22,'Williamtown':23,\n                                                'Canberra':24,'Cobar':25} ).astype(int)\ntrain_y=pd_data['RainTomorrow']\ntrain_x=pd_data.drop(['RainTomorrow'], axis=1)\ndtree=tree.DecisionTreeClassifier(max_depth=7)\ndtree=dtree.fit(train_x,train_y)\nscores = cross_val_score(dtree,train_x,train_y,cv=5,scoring='accuracy')\nprint(scores)\nprint('average of Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n#### 6.2.2 Logistic Regression\n\"\"\"\n#Logistic Regression\nlogreg = LogisticRegression()\nlogreg.fit(train_x, train_y)\n\n#Cross validation\nscores = cross_val_score(dtree,train_x,train_y,cv=5,scoring='accuracy')\nprint('Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n#### 6.2.3 knn\n\"\"\"\n#knn\nknn = KNeighborsClassifier(n_neighbors = 10)\nknn.fit(train_x, train_y)\n\n#Cross validation\nscores = cross_val_score(knn,train_x,train_y,cv=5,scoring='accuracy')\nprint('Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n#### 6.2.4 Gaussian Naive Bayes\n\"\"\"\n#Gaussian Naive Bayes\ngaussian = GaussianNB()\ngaussian.fit(train_x, train_y)\n#Cross validation\nscores = cross_val_score(gaussian,train_x,train_y,cv=5,scoring='accuracy')\nprint('Cross validation: %.5f'%scores.mean())\nprint('standard deviation of Cross validation: %.5f'%scores.std(ddof=1))\n\"\"\"\n#### 6.2.5 \u5c07\u5730\u9ede\u8003\u616e\u9032\u53bb\u7684\u7d50\u679c\u89c0\u5bdf\n\u6b63\u78ba\u7387\u4e26\u6c92\u6709\u63d0\u5347\u3002\n\"\"\"\n\"\"\"\n## 7.\u5c0f\u7d50\n\n1.\u6211\u5011\u5617\u8a66\u4f7f\u7528\u5404\u7a2e\u6a21\u578b\u9810\u6e2c\uff0c\u9810\u6e2c\u6e96\u78ba\u5ea6\u90fd\u80fd\u9054\u523080%\u4ee5\u4e0a\u3002\n\n2.\u5404\u500b\u6a21\u578b\u7684auc\u90fd\u5927\u65bc0.7\uff0c\u6709\u4e9b\u6a21\u578b\u53ef\u90540.8\u4ee5\u4e0a\uff0c\u8868\u793a\u4f7f\u7528\u9019\u4e9b\u6a21\u578b\u9810\u6e2c\u300c\u660e\u5929\u662f\u5426\u964d\u96e8\u7684\u6b63\u78ba\u7387\u300d\u90fd\u6bd4\u4e82\u731c\u7684\u7d50\u679c\u4f86\u5f97\u597d\u3002\n\"\"\"\n\"\"\"\n## 8.\u5fc3\u5f97\n#### \u5ed6\u54c1\u745c:\n#### \u611f\u89ba\u8ab2\u7a0b\u6642\u9593\u6709\u9ede\u5c11\uff0c\u5e0c\u671b\u53ef\u4ee5\u7528\u66f4\u591a\u6642\u9593\u5728\u5e36\u7a0b\u5f0f\u7684\u90e8\u5206\uff0c\u96d6\u7136\u539f\u7406\u5f88\u91cd\u8981\uff0c\u4f46\u8b1b\u89e3\u904e\u5927\u6982\u5f8c\u61c9\u8a72\u53ef\u4ee5\u900f\u904e\u81ea\u5b78\u4f86\u5b8c\u6210\uff1b\u800c\u7a0b\u5f0f\u7684\u90e8\u5206\u5c31\u7b97\u4e0d\u592a\u61c2\u539f\u7406\u4e5f\u53ef\u4ee5\u4e0a\u624b\uff0c\u4f46\u9700\u8981\u66f4\u591a\u6b21\u7df4\u7fd2\u624d\u80fd\u627e\u51fa\u554f\u984c\u3002\u9019\u6b21\u5b78\u5230\u7684\u6771\u897f\u5f88\u6709\u8da3\uff0c\u96fb\u8166\u53ef\u4ee5\u76f4\u63a5\u5f15\u7528\u51fd\u5f0f\u5eab\u771f\u7684\u592a\u65b9\u4fbf\u4e86\uff0c\u5e7e\u4e4e\u4e0d\u9700\u8981\u4e86\u89e3\u539f\u7406\u5c31\u53ef\u4ee5\u4f7f\u7528\u3002\u4e5f\u5b78\u5230Git\u8ddfKaggle\u9084\u6709Jupyter notebook\u7684\u7528\u6cd5\uff0c\u4ee5\u5f8c\u6703\u66f4\u6df1\u5165\u5b78\u7fd2\uff0c\u5e0c\u671b\u53ef\u4ee5\u5728\u539f\u672c\u7684\u79d1\u7cfb\u4e0a\u904b\u7528\u3002\n#### \u80e1\u7b46\u52dd:\n#### \u8ab2\u7a0b\u5167\u5bb9\u5f88\u6709\u8da3\u4e5f\u5f88\u5be6\u7528\uff0c\u4e4b\u524d\u5b8c\u5168\u6c92\u6709\u63a5\u89f8\u904e\u76f8\u95dc\u7684\u9818\u57df\uff0c\u4f46\u662f\u5728\u4e00\u500b\u79ae\u62dc\u5167\u8981\u4e86\u89e3\u6a5f\u5668\u5b78\u7fd2\u4ee5\u53capython\u7684\u8ab2\u7a0b\u5167\u5bb9\uff0c\u6211\u89ba\u5f97\u6709\u4e9b\u8a31\u56f0\u96e3\u3002\u7e73\u4ea4\u4f5c\u696d\u6642\u9593\u5ef6\u5f8c\u4e4b\u5f8c\uff0c\u6211\u53ef\u4ee5\u6709\u66f4\u591a\u6642\u9593\u6642\u4f5c\u8207\u601d\u8003\u8ab2\u7a0b\u5167\u5bb9\u3002\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0809ffb9cb8604'}"}
{"id":"95470","text":"\"\"\"\nThis is an introduction to machine learning, python and pandas. Outline is as follows:\n* Examine the columns and range of the data\n* Visualize some data\n* Brainstorm  some ideas for machine learning as applied to this data\n* Manipulate the data (create new columns, massage data) toward that end.\n*  Apply some machine learning algrorithms and evaulate effectiveness if any\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output\n\n# Try prophet as seen in https:\/\/www.kaggle.com\/samuelbelko\/predicting-prices-of-avocados\nfrom fbprophet import Prophet\n# Not sure what this does - show graphs in line?\n%matplotlib inline\n\n\n# From the above, I have the data for this dataset. Read it in, and do some simple examinations\ndata = pd.read_csv('..\/input\/Jan20_NDXT.csv')\n\n# First 10 records\ndata.head()\n\n\n\n\n# Info on the columns - For some reason if I do this in the above, I only see output for one of them so \n# I do separately\ndata.info()\n\n#Desc\n# Not alot of data, but we are just playing around for now, let's look at max\/min and if there are any \n# null values\ndata.describe()\n\"\"\"\nVolume is all 0 so might as well drop that.\nI don't know the difference between close and adjusted close so I will drop adjusted close too.\nVolatility might be a predictor so I want to calculate the daily max-min and also the close-open (signed)\nWondering if certain months are important so also want to add a column which is the month \nTODO - drop unneeded columns, add new calculated columns\n\"\"\"\ndata['DailyDif'] = data['NDXT Close'] - data['NDXT Open']\ndata['DailyRange'] = data['NDXT High'] - data['NDXT Low']\ndata.drop(columns=['NDXT Volume','NDXT Close','NDXT High','NDXT Low','NDXT Adj Close'], inplace=True)\ndata.head()\n#I want to convert the date to something Pandas likes\ndata['Date'] = pd.to_datetime(data['Date'], format='%m\/%d\/%Y')\ndata.head()\n #Plot theh open price versus time\ndata.plot(x='Date', y='NDXT Open', kind=\"line\")\n#Next I want to create a column called month. So I tried this\n# data['Month'] = data['Date'].month\n# But that didn't work, even though I looked up python datetime and it supports that property\n# The error I got said that 'object' did not have the property 'month' so i guess i need some kind of\n# cast. So i try\n# data['Data'].astype(datetime) but that doesn't work, it says it doesn't recognize datetime\n# Finally I use data.info() to dump the columns and their types and i see that Date is of type\n# datetime64. But no matter what I did, I couldn't get it ti work. Finally I found some example where\n# I see someone refer to a dt property. Now it works - see below\ndata.info()\n# Use dt property to access the actual date time properties\ndata['Month'] = data['Date'].dt.month\ndata.head()\n\"\"\"\nI want to try this Prophet which I saw in the avocado price kernal\n\"\"\"\npdata = data[['Date', 'NDXT Open']].reset_index(drop=True)\npdata = pdata.rename(columns={'Date':'ds', 'NDXT Open':'y'})\npdata.head()\n\nm = Prophet()\nm.fit(pdata)\nfuture = m.make_future_dataframe(periods=365)\nforecast = m.predict(future)\nfig1 = m.plot(forecast)\n\"\"\"\nHey look at my prediction!!! It says the nasdaq is going to keep going up! Buy! Buy! Buy!\nOkay, I just sunk all our savings into Nasdaq. Now is a good time to try the prediction again starting at 2017\n\n\n\"\"\"\npdata = pdata[pdata.ds.dt.year < 2017]\npdata.tail()\nm = Prophet()\nm.fit(pdata)\nfuture = m.make_future_dataframe(periods=365)\nforecast = m.predict(future)\nfig1 = m.plot(forecast)\n\"\"\"\nWell this was fun. Not sure what I learned. But it was easy to run Prophet and maybe it would be more interesting to try over a longer date range. But next time I want to go back to my dataframe and try some of the standard ML algorithms\nI want to manipulate the data into the following:\n\nOne row per month (summarize over days):\nDate\nMonth (1-12)\nMonth closing price\nGain\/loss for the month\nMaximum max-min\nAverage max-min\nSame for the previous month\nSame for the previous previous month\nSo I guess I need to look at how pandas does grouping!!\n\"\"\"\ndata.describe(include='all')\n#I can see that I have unique dates (good) but not values for every row. So let's look at those.\n\n\n\ndata.loc[data['NDXT Open'].isnull()]\ndata = data.loc[data['NDXT Open'].isnull()==False]\ndata.describe(include='all')","meta":"{'source': 'AI4Code', 'id': 'af4a2d9fe93aae'}"}
{"id":"42986","text":"import pandas as pd\nimport numpy as np\nimport ast\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.ticker as ticker\nimport squarify as sq\n\nfrom IPython.display import display, HTML\n\ndisplay(HTML(data=\"\"\"\n<style>\n    div#notebook-container    { width: 95%; }\n    div#menubar-container     { width: 65%; }\n    div#maintoolbar-container { width: 99%; }\n<\/style>\n\"\"\"))\ndata = pd.read_csv('..\/input\/tmdbset\/main.csv')\n\"\"\"\n# **Data Inspection**\n\"\"\"\ndata.head(3)\ndata.tail(3)\ndata.info()\n\"\"\"\n# **Data Tidying**\n\"\"\"\ndata_processed = data.copy()\n\"\"\"\n## Dropping unnecessary columns\n\"\"\"\ndata_processed.drop(columns=['adult','backdrop_path','homepage','poster_path','popularity','video',\n                'status', 'imdb_id'], inplace=True)\ndata_processed.info()\n\"\"\"\n## Handling empty data\n\"\"\"\ndata_processed.belongs_to_collection = data_processed.belongs_to_collection.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else pd.NA)\ndata_processed.spoken_languages\t= data_processed.spoken_languages.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else pd.NA)\n#data_processed.loc[data_processed.spoken_languages.apply(lambda x: len(x)) == 0, 'spoken_languages'] = pd.NA\ndata_processed.genres = data_processed.genres.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else pd.NA)\n#data_processed.loc[data_processed.genres.apply(lambda x: len(x)) == 0, 'genres'] = pd.NA\ndata_processed.production_companies = data_processed.production_companies.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else pd.NA)\n#data_processed.loc[data_processed.production_companies.apply(lambda x: len(x)) == 0, 'production_companies'] = pd.NA\ndata_processed.production_countries= data_processed.production_countries.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else pd.NA)\n#data_processed.loc[data_processed.production_countries.apply(lambda x: len(x)) == 0, 'production_countries'] = pd.NA\ndata_processed.loc[data_processed.revenue == 0, 'revenue'] = pd.NA\ndata_processed.loc[data_processed.budget == 0, 'budget'] = pd.NA\ndata_processed.info()\n\"\"\"\n## Changing the scale of budgets\/revenue to number of millions\n\"\"\"\ndata_processed.budget = data_processed.budget\/1000000\ndata_processed.revenue = data_processed.revenue\/1000000\n\"\"\"\n## Converting columns to appropriate types\n\"\"\"\ndata_processed.info()\ndata_processed.original_language = data_processed.original_language.astype('category')\ndata_processed.release_date = data_processed.release_date.astype('datetime64')\ndata_processed.id = data_processed.id.astype('Int32')\ndata_processed.runtime = data_processed.runtime.astype('Int16')\ndata_processed.budget = pd.to_numeric(data_processed.budget, errors='coerce')\ndata_processed.revenue = pd.to_numeric(data_processed.revenue, errors='coerce')\ndata_processed.info()\n\"\"\"\n## Adjusting budgets\/revenue to account for inflation\n\"\"\"\ndata_processed.drop(data_processed.loc[(data_processed.release_date.dt.year < 1960) | (data_processed.release_date.dt.year > 2019)].index,inplace=True)\ndata_processed.drop(data_processed.loc[data_processed.release_date.isna()].index, inplace=True)\ninflation = pd.read_csv('..\/input\/top-movies-19602020\/CPI.csv', index_col='observation_date', parse_dates=True)\n\ninflation = inflation.resample('A',kind='period').mean()\n\ncpi_dict = {}\nfor x,y in zip(inflation.index.year, inflation.CPIAUCSL):\n    cpi_dict[x] = round(y,2)\n    \ndata_processed.budget = data_processed.apply(lambda x: x.budget * (cpi_dict[2020] \/ cpi_dict[x.release_date.year]), axis=1)\ndata_processed.revenue = data_processed.apply(lambda x: x.revenue * (cpi_dict[2020] \/ cpi_dict[x.release_date.year]),axis=1)\ndata_processed.budget = data_processed.budget.apply(lambda x: round(x,2) if isinstance(x, float) else pd.NA)\ndata_processed.revenue = data_processed.revenue.apply(lambda x: round(x,2) if isinstance(x, float) else pd.NA)\n\"\"\"\n## Adding ROI,Decade, and Month column\n\"\"\"\ndata_processed['roi'] = data_processed.apply(lambda x: x.revenue - x.budget, axis=1)\ndata_processed.roi = pd.to_numeric(data_processed.roi, errors='coerce')\n\ndata_processed['decade'] = (data_processed.release_date.dt.year \/\/ 10) * 10\ndata_processed['month'] = data_processed.release_date.dt.month\n\"\"\"\n# **Which Genres are associated with the most ROI? (1960-2019)**\n\"\"\"\ndef get_assoc_roi_per_genre(df, groupby):\n    df = df.explode('genres')\n    df.genres = df.genres.apply(lambda x: [x[key] for key in x.keys()][1] if isinstance(x, dict) else pd.NA)\n    df.loc[df.genres=='Science Fiction','genres'] = 'Sci Fi'\n\n    df = pd.DataFrame(df.groupby(groupby).roi.sum())\n    return df\ndf_roi = data_processed[['roi','genres']].copy()\n\ndf_roi = get_assoc_roi_per_genre(df_roi, 'genres')\n\ndf_roi = df_roi.sort_values('roi',ascending=False)\ndf_roi\nfig, ax = plt.subplots()\nfig.set_size_inches(20,10)\n\nmini= min(df_roi.roi)\nmaxi= max(df_roi.roi)\nnorm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)\ncolors = [matplotlib.cm.cool(norm(value)) for value in df_roi.roi]\n\nsq.plot(sizes=df_roi.roi, label=df_roi.index, ax=ax,ec='black', lw=2,color=colors, text_kwargs={'size':15})\n\nax.axis('off')\nfig.suptitle('Genres associated with the Most ROI - 1960-2019',y=.96, size=35)\nplt.show()\n\"\"\"\n# **How have genres associations with ROI changed throughout the decades? (1960s-2010s)**\n\"\"\"\ndf_roi_dec = data_processed[['roi','genres','decade']].copy()\n\ndf_roi_dec = get_assoc_roi_per_genre(df_roi_dec, ['decade', 'genres'])\n\ndf_roi_dec.drop(df_roi_dec.loc[df_roi_dec.roi < 1, 'roi'].index, inplace=True)\n\ndf_roi_dec = df_roi_dec.sort_values('roi',ascending=True)\nfig, axes = plt.subplots(3,2)\nfig.set_size_inches(30,25)\naxes=axes.flatten()\n\nfor ax,decade in zip(axes, range(1960, 2011, 10)):\n    mini= min(df_roi_dec.loc[decade, 'roi'])\n    maxi= max(df_roi_dec.loc[decade, 'roi'])\n    norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)\n    colors = [matplotlib.cm.cool(norm(value)) for value in df_roi_dec.loc[decade, 'roi']]\n\n    sq.plot(sizes=df_roi_dec.loc[decade, 'roi'], label=df_roi_dec.loc[decade, 'roi'].index.get_level_values(0),\n            ax=ax,ec='black', lw=2,color=colors, text_kwargs={'size':15})\n    ax.axis('off')\n    ax.set_title(str(decade)+'s',size=30)\n    \nfig.suptitle('Genres associated with the Most ROI per decade',x =.5,y=.94, size=40)\nplt.show()\n\"\"\"\n## **Ranking of genres associated with ROI across the decades**\n\"\"\"\ndef create_ranking_chart(df, onlyshow=''):\n    fig,ax = plt.subplots()\n    fig.set_size_inches(31,16)\n\n    for x in df.genres.unique():  \n        sns.lineplot(data=df[df.genres == x], x='decade', y='ranks', ax=ax,\n                     markers=['h'],markeredgecolor='black',markeredgewidth=3,style='genres',lw=8,label=x,legend=False,markersize=35)\n\n    for x in range(1960, 2011, 10):\n        for y in range(1,20):\n            ax.annotate(y, (x,y),xytext=(0, -1), textcoords='offset points', ha='center', va='center',size = 15, weight='bold',\n                        label = df.loc[(df.decade == x) & (df.ranks == y), 'genres'].iat[0],color='white')\n\n    for line, name in zip(ax.lines, df.loc[df.decade == 1960, 'genres']):\n        y = line.get_ydata()[0]\n        x = line.get_xdata()[0]\n        ax.annotate(name,(x,y),xytext=(-25, 0), textcoords='offset points', ha='right',va='center', size=15,label=name)\n        y = line.get_ydata()[-1]\n        x = line.get_xdata()[-1]\n        ax.annotate(name,(x,y),xytext=(25, 0), textcoords='offset points', ha='left',va='center', size=15,label=name)\n        \n    if not isinstance(onlyshow, str):    \n        for elem in ax.lines + ax.texts:\n            if elem.get_label() not in onlyshow:\n                elem.set_visible(False)\n\n\n    formatter = ticker.FormatStrFormatter('%ds')\n    y = range(1960,2011,10)\n    labels = [formatter(x) for x in y]\n    ax.set_xticks(range(1960,2011,10))\n    ax.set_xticklabels(labels)\n\n    ax.set_yticks([])\n    ax.set_ylabel(ylabel='Rank', size=30, labelpad=10)\n    ax.set_xlabel(xlabel='Decades', size=30,labelpad=20)\n    ax.set_axisbelow(True)\n    ax.tick_params(axis='both',labelsize=20)\n    ax.grid('x')\n    ax.margins(x=.10)\ndef create_ranking(df):\n    df = df.unstack(level=0)\n    df.columns = df.columns.droplevel(0)\n    df = df.rank(na_option='top').sort_values(1960).reset_index().melt(id_vars='genres', value_name='ranks')\n    return df\ndf_roi_dec = data_processed[['roi','genres','decade']].copy()\n\ndf_roi_dec = get_assoc_roi_per_genre(df_roi_dec, ['decade', 'genres'])\n\ndf_roi_rank = create_ranking(df_roi_dec)\ncreate_ranking_chart(df_roi_rank)\n\"\"\"\n## **Top 5 Genres with the most Stable Association with ROI throughout the decades**\n\"\"\"\ndf_roi_dec = data_processed[['roi','genres','decade']].copy()\n\ndf_roi_dec = get_assoc_roi_per_genre(df_roi_dec, ['decade', 'genres'])\n\ndf_roi_rank = create_ranking(df_roi_dec)\ndf_roi_rank.groupby('genres').ranks.describe().sort_values('std')\nshow = df_roi_rank.groupby('genres').ranks.describe().sort_values('std').head(5).index\ncreate_ranking_chart(df_roi_rank, show)\n\"\"\"\n## **Top 5 Genres with the Most Variable association with ROI throughout the decades**\n\"\"\"\ndf_roi_dec = data_processed[['roi','genres','decade']].copy()\n\ndf_roi_dec = get_assoc_roi_per_genre(df_roi_dec, ['decade', 'genres'])\n\ndf_roi_rank = create_ranking(df_roi_dec) \nshow = df_roi_rank.groupby('genres').ranks.describe().sort_values('std').tail(5).index\ncreate_ranking_chart(df_roi_rank, show)\ndata_processed.sort_values('roi')\n\"\"\"\n## **What is the best\/worst month to release a movie?**\n\"\"\"\ndf_month = data_processed[['id', 'month', 'roi']].copy()\ndf_month.groupby('month').roi.describe().sort_values('mean')\n\"\"\"\n## **What is the best\/worst month to release a low-budget movie?**\n\"\"\"\ndf_month_low = data_processed.loc[data_processed.budget <= 5,['id', 'month', 'roi']].copy()\ndf_month_low['std'] = df_month_low.groupby('month').roi.transform('std')#.describe().sort_values(['count', 'mean'], ascending=[True, False])\ndf_month_low['mean'] = df_month_low.groupby('month').roi.transform('mean')\ndf_month_low.apply(lambda x: x if (True) else False, axis=1)\ndf_month_low.info()\ndf_month_low = df_month_low.loc[(df_month_low.roi > (df_month_low['mean'] - (df_month_low['std'] * 2))) & (df_month_low.roi < (df_month_low['mean'] + (df_month_low['std']*2)))].sort_values('roi')\ndf_month_low.groupby('month').roi.describe()\ndf_month_low","meta":"{'source': 'AI4Code', 'id': '4f392fb076ed3a'}"}
{"id":"35333","text":"\"\"\"\n## **Set-up and importing**\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestClassifier\n\"\"\"\n## **Initilizing seed and random values**\n\"\"\"\n\n\nseed_value = 44\nos.environ['PYTHONHASHSEED']=str(seed_value)\n\n# Set `python` built-in pseudo-random generator at a fixed value\nrandom.seed(seed_value)\n\n# Set `numpy` pseudo-random generator at a fixed value\nnp.random.seed(seed_value)\ndata_file =\"..\/input\/predictive-maintenance\/ai4i2020.csv\" \ndata = pd.read_csv(data_file)\ntrain_data,test_data = train_test_split(data, test_size = 0.33, random_state = seed_value)\ntrain_data.to_csv('train.csv',index=0)\ntest_data.to_csv('test.csv',index=0)\ndata.head()\n\"\"\"\n## **Binary Classification** \n\"\"\"\nX=train_data.iloc[:,3:8]\nY=train_data.iloc[:,8]\nX_test=test_data.iloc[:,3:8]\nY_test=test_data.iloc[:,8]\nprint(X.shape)\nprint(Y.shape)\nclf = RandomForestClassifier(max_depth=2, random_state=seed_value)\nclf = clf.fit(X, Y)\nprediction=clf.predict(X_test)\nprint(confusion_matrix(Y_test,prediction))\nprint(\"Random Forest model accuracy(in %):\", metrics.accuracy_score(Y_test, prediction)*100)\nclassification_report(Y_test,prediction)\nsgd = make_pipeline(SGDClassifier(max_iter=1000, tol=1e-3),)\nsgd.fit(X, Y)\npre=sgd.predict(X_test)\nprint(confusion_matrix(Y_test,pre))\nprint(\"SGD model accuracy(in %):\", metrics.accuracy_score(Y_test, pre)*100)\nclassification_report(Y_test,pre)\ngnb = GaussianNB()\ngnb.fit(X, Y) \ny_pred = gnb.predict(X_test)\nfrom sklearn import metrics\nprint(\"Gaussian Naive Bayes model accuracy(in %):\", metrics.accuracy_score(Y_test, y_pred)*100)\nclassification_report(Y_test,y_pred)\n\"\"\"\n## **Multi-classification**\n* Classfiying Machine Failure Type \n\"\"\"\ndata[\"Type\"]=data[\"Type\"].map( {'S':0 , 'M':1, 'L':2} )\ndata['TWF'] = data['TWF'].replace(1, \"TWF\", regex=True)\ndata['TWF'] = data['TWF'].replace(0, \"\", regex=True)\ndata['HDF'] = data['HDF'].replace(1, \"HDF\", regex=True)\ndata['HDF'] = data['HDF'].replace(0, \"\", regex=True)\ndata[\"PWF\"] = data['PWF'].replace(1,\"PWF\",regex=True)\ndata[\"PWF\"] = data['PWF'].replace(0,\"\",regex=True)\ndata[\"OSF\"] = data['OSF'].replace(1,\"OSF\",regex=True)\ndata[\"OSF\"] = data['OSF'].replace(0,\"\",regex=True)\ndata[\"RNF\"] = data['RNF'].replace(1,\"RNF\",regex=True)\ndata[\"RNF\"] = data['RNF'].replace(0,\"\",regex=True)\n'''data.loc[data[\"TWF\"] == 1, [\"TWF\"]] = \"TWF\"\ndata.loc[data[\"HDF\"] == 1, [\"HDF\"]] = \"HDF\"\ndata.loc[data[\"PWF\"] == 1, [\"PWF\"]] = \"PWF\"\ndata.loc[data[\"OSF\"] == 1, [\"OSF\"]] = \"OSF\"\ndata.loc[data[\"RNF\"] == 1, [\"RNF\"]] = \"RNF\"\ndata[\"class\"] = data[\"TWF\"] + data[\"HDF\"]+data[\"PWF\"]+data[\"OSF\"]+data[\"RNF\"]'''\ndata[\"class\"] = data[\"TWF\"] + data[\"HDF\"]+data[\"PWF\"]+data[\"OSF\"]+data[\"RNF\"]\nmulti_class_data= data[data['class'].str.len()> 1]\nmulti_class_data=multi_class_data.drop([\"TWF\",\"HDF\",\"PWF\",\"OSF\",\"RNF\"],axis=1)\n\nmulti_class_data[\"class\"].unique()\nmulti_class_data.head()\nx=multi_class_data.iloc[:200,3:8]\ny=multi_class_data.iloc[:200,9]\nx_test=multi_class_data.iloc[200:,3:8]\ny_test=multi_class_data.iloc[200:,9]\nclf = RandomForestClassifier(max_depth=2, random_state=seed_value)\nclf = clf.fit(x, y)\nprediction=clf.predict(x_test)\nprint(confusion_matrix(y_test,prediction))\nprint(\"Multi-class : Random Forest model accuracy(in %):\", metrics.accuracy_score(y_test, prediction)*100)\nclassification_report(y_test,prediction)\nsgd = make_pipeline(SGDClassifier(max_iter=1000, tol=1e-3),)\nsgd.fit(x, y)\npre=sgd.predict(x_test)\nprint(\"Multi-class : SGD model accuracy(in %):\", metrics.accuracy_score(y_test, pre)*100)\nclassification_report(y_test,pre)\ngnb = GaussianNB()\ngnb.fit(x, y) \ny_pred = gnb.predict(x_test)\nfrom sklearn import metrics\nprint(\"Multi-class : Gaussian Naive Bayes model accuracy(in %):\", metrics.accuracy_score(y_test, y_pred)*100)\nclassification_report(y_test,y_pred)\nfrom sklearn.datasets import make_blobs\nfrom pandas import DataFrame\nx, y = make_blobs(n_samples=200, centers=3, n_features=2,random_state=44)\nclassfication_data = DataFrame(dict(x1=x[:,0], x2=x[:,1], label=y))\nclassfication_data.head()\ntrain_data,test_data = train_test_split(classfication_data, test_size = 0.33, random_state = seed_value)\nx=train_data.iloc[:,:2]\ny=train_data.iloc[:,2]\nx_test=test_data.iloc[:,:2]\ny_test=test_data.iloc[:,2]\nclf = RandomForestClassifier(max_depth=2, random_state=seed_value)\nclf = clf.fit(x, y)\nprediction=clf.predict(x_test)\nprint(confusion_matrix(y_test,prediction))\nprint(\"Multi-class : Random Forest model accuracy(in %):\", metrics.accuracy_score(y_test, prediction)*100)\nclassification_report(y_test,prediction)\n#data.tail(50)\nsgd = make_pipeline(SGDClassifier(max_iter=1000, tol=1e-3),)\nsgd.fit(x, y)\npre=sgd.predict(x_test)\nprint(\"Multi-class : SGD model accuracy(in %):\", metrics.accuracy_score(y_test, pre)*100)\nclassification_report(y_test,pre)\n\ngnb = GaussianNB()\ngnb.fit(x, y) \ny_pred = gnb.predict(x_test)\nfrom sklearn import metrics\nprint(\"Multi-class : Gaussian Naive Bayes model accuracy(in %):\", metrics.accuracy_score(y_test, y_pred)*100)\nclassification_report(y_test,y_pred)","meta":"{'source': 'AI4Code', 'id': '411b03467e13e7'}"}
{"id":"75992","text":"\"\"\"\n<h1>Data Analysis of Heart Disease <\/h1>\n\"\"\"\n\"\"\"\n<h2>Import Required Modules<\/h2>\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set(color_codes=True)  # visualization tool\n\n\nfrom sklearn.linear_model import LinearRegression\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n<h2>Read Data<\/h2>\n\"\"\"\ndf=pd.read_csv(\"..\/input\/heart.csv\")\ntype(df)\ndf.head()\ndf.tail()\ndf.shape\ndf.describe()\ndf.info()\n\"\"\"\n<h3>Data Cleaning<\/h3>\n\"\"\"\n\"\"\"\n**Count the number ofmissing values in the DataFrame**\n\"\"\"\n#count the number of missing values in each columns\ndf.isna().sum()\ndf.columns\ndf.dtypes\ndf.corr()\n\"\"\"\n<h2>Data Visualization<\/h2>\n\"\"\"\n#subplots\ndf.plot(subplots=True,figsize=(18,18))\nplt.show()\n#visualize the correlation\nplt.figure(figsize=(15,10))\nsns.heatmap(df.iloc[:,0:15].corr(), annot=True,fmt=\".0%\")\nplt.show()\n#create a pair plot\nsns.pairplot(df.iloc[:,0:8],hue=\"cp\")\nplt.show()\nfig=plt.figure(figsize=(20,15))\nax=fig.gca()\ndf.hist(ax=ax)\nplt.show()\nfig=plt.figure(figsize=(20,10))\nsns.boxplot(data = df,notch = True,linewidth = 2.5, width = 0.50)\nplt.show()\n# histogram subplot with non cumulative and cumulative \nfig,axes=plt.subplots(nrows=2,ncols=1)\n\ndf.plot(kind='hist',y='age',bins=50,range=(0,100),density=True,ax=axes[0])\ndf.plot(kind='hist',y='age',bins=50,range=(0,100),density=True,ax=axes[1],cumulative=True)\nplt.show()\nprint(df['sex'].value_counts(dropna=False))\nsns.barplot(x='sex',y='age',data=df)\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.sex, data=df, kind=\"kde\");\nsns.swarmplot(x = 'sex', y = 'age', data = df)\nplt.show()\ndf['age']=df['age']\nbins=[29,47,55,61,77]\nlabels=[\"Young Adult\",\"Early Adult\",\"Adult\",\"Senior\"]\ndf['age_group']=pd.cut(df['age'],bins,labels=labels)\nfig=plt.figure(figsize=(20,5))\nsns.barplot(x='age_group',y='sex',data=df)\nplt.show()\n\nfig=plt.figure(figsize=(20,5))\nsns.violinplot(x ='age_group', y = 'sex', data = df)\nplt.show()\n#sns.set_style('whitegrid')\n\nfig=plt.figure(figsize=(20,5))\nsns.violinplot(x ='age_group', y = 'trestbps', data = df)\nplt.show()\nfig=plt.figure(figsize=(20,5))\nsns.violinplot(x = 'age_group', y = 'chol', data = df)\nplt.show()\nfig=plt.figure(figsize=(20,15))\nsns.violinplot(x = 'age_group', y = 'thalach', data = df)\nplt.show()\ngrp =df.groupby(\"age\")\nx= grp[\"chol\"].agg(np.mean)\ny=grp[\"trestbps\"].agg(np.mean)\nz=grp[\"thalach\"].agg(np.mean)\nplt.figure(figsize=(16,5))\nplt.plot(x,'ro',color='r')\nplt.xticks(rotation=90)\nplt.title(\"Age wise Chol\")\nplt.xlabel(\"Age\")\nplt.ylabel(\"Chol\")\nplt.show()\nplt.figure(figsize=(16,5))\nplt.plot(y,'r--',color='b')\nplt.xticks(rotation=90)\nplt.title(\"Age wise Trestbps\")\nplt.xlabel(\"Age\")\nplt.ylabel(\"Trestbps\")\nplt.show()\nplt.figure(figsize=(16,5))\nplt.plot(z,\"g^\",color='g')\nplt.xticks(rotation=90)\nplt.xlabel(\"Age\")\nplt.ylabel(\"Thalach\")\nplt.show()\n\nfig=plt.figure(figsize=(20,5))\nsns.violinplot(x ='age', y = 'trestbps', data = df)\nplt.show()\nax = df.trestbps.plot.kde()\nax = df.chol.plot.kde()\nax = df.thalach.plot.kde()\nax.legend()\nplt.show()\n#xticks -> chol min,mean,max \n#yticks -> trestbps min,mean,max\nfiltered_class1=df[(df.chol>246) & (df.trestbps>131) & (df.sex==0)]\nfiltered_class4=df[(df.chol>246) & (df.trestbps>131) & (df.sex==1)]\nfig=plt.figure(figsize=(20,15))\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class1)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class4)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\",col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=df)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\n\n\n\n##########################################################################################################################################\nfiltered_class2=df[(df.chol>246) & (df.thalach>149) & (df.sex==0)]\nfiltered_class5=df[(df.chol>246) & (df.thalach>149) & (df.sex==1)]\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class2)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=df)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class5)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\n############################################################################################################################################\nfiltered_class3=df[(df.trestbps>131) & (df.thalach>149) & (df.sex==0)]\nfiltered_class6=df[(df.trestbps>131) & (df.thalach>149) & (df.sex==1)]\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class3)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=df)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",markers=[\"o\",\"*\",\"x\",'s'],data=filtered_class6)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\n\nfiltered_class1=df[(df.chol>246) & (df.trestbps>131) & (df.sex==0) & (df.age>60)]\nfiltered_class4=df[(df.chol>246) & (df.trestbps>131) & (df.sex==1) & (df.age>60)]\n\nfig=plt.figure(figsize=(20,15))\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class1)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\",col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",data=df)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"trestbps\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class4)\ng = (g.set_axis_labels(\"chol\", \"trestbps\").set(xlim=(120, 600), ylim=(90, 240),xticks=[120, 246, 600], yticks=[90, 131, 240]).fig.subplots_adjust(wspace=.02))\n\n##########################################################################################################################################\nfiltered_class2=df[(df.chol>246) & (df.thalach>149) & (df.sex==0) & (df.age>60)]\nfiltered_class5=df[(df.chol>246) & (df.thalach>149) & (df.sex==1) & (df.age>60)]\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class2)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",data=df)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"chol\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class5)\ng = (g.set_axis_labels(\"chol\", \"thalach\").set(xlim=(120, 600), ylim=(65, 220),xticks=[120, 246, 600], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\n############################################################################################################################################\nfiltered_class3=df[(df.trestbps>131) & (df.thalach>149) & (df.sex==0) &(df.age>60)]\nfiltered_class6=df[(df.trestbps>131) & (df.thalach>149) & (df.sex==1) & (df.age>60)]\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class3)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\",height=5,aspect=.7, x_jitter=.1,palette=\"Set1\",data=df)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\ng = sns.lmplot(x=\"trestbps\", y=\"thalach\", hue=\"cp\", col=\"sex\", height=4, aspect=.7, x_jitter=.1,palette=\"Set1\",data=filtered_class6)\ng = (g.set_axis_labels(\"trestbps\", \"thalach\").set(xlim=(85, 220), ylim=(65, 220),xticks=[85, 131, 220], yticks=[65, 149, 220]).fig.subplots_adjust(wspace=.02))\n\n\nprint(df['cp'].value_counts(dropna=False))\nfig=plt.figure(figsize=(20,5))\nsns.swarmplot(x = 'age', y = 'chol', data = df)\nplt.show()\nfig=plt.figure(figsize=(20,5))\nsns.swarmplot(x = 'cp', y = 'age', data = df)\nplt.show()\nfig=plt.figure(figsize=(20,5))\nsns.swarmplot(x = 'age', y = 'thalach', data = df)\nplt.show()\nfig=plt.figure(figsize=(10,5))\nsns.swarmplot(x=\"sex\", y=\"age\",hue=\"cp\", data=df)\nplt.show()\nfig=plt.figure(figsize=(20,5))\nsns.violinplot(x = 'sex', \n               y = 'age', \n               data = df, \n               inner = None, \n               )\n\nsns.swarmplot(x = 'sex', \n              y = 'age', \n              data = df, \n              color = 'k', \n              alpha = 0.7)\n\nplt.title('sex by age')\nplt.show()\n#barplot\nsns.barplot(x='cp',y='age',data=df)\nplt.show()\nfig=plt.figure(figsize=(10,5))\nsns.violinplot(x = 'age_group', y = 'cp', data = df)\nplt.show()\n#boxplot\ndf.boxplot(column='age', by='cp')\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.cp, data=df, kind=\"kde\");\n# histogram subplot with non cumulative and cumulative\n\nfig,axes=plt.subplots(nrows=2,ncols=1)\ndf.plot(kind=\"hist\",y=\"trestbps\",bins=50, range=(0,250),normed=True,ax=axes[0])\ndf.plot(kind=\"hist\",y=\"trestbps\",bins=50, range=(0,250),normed=True,ax=axes[1],cumulative=True)\nplt.savefig('graph.png')\nplt.show()\n#boxplot\ndf.boxplot(column='trestbps',by='age', figsize=(18,18))\nplt.show()\n# Scatter Plot\n#age vs. trestbps\ndf.plot(kind='scatter',x='age',y='trestbps',alpha=0.5,color='r')\nplt.xlabel('age') # label = name of label\nplt.ylabel('trestbps')\nplt.title('Age-trestbps Scatter Plot')  # title = title of plot\nplt.show()\n#jointplot\nsns.jointplot(x=\"trestbps\", y=\"age\", data=df);\n#jointplot hex\n\nwith sns.axes_style(\"white\"):\n    sns.jointplot(x=df.age, y=df.trestbps, kind=\"hex\", color=\"k\");\n#scatter plot\nf, ax = plt.subplots(figsize=(6.5, 6.5))\nsns.despine(f, left=True, bottom=True)\nage_group = [\"Young Adult\",\"Middle-Aged Adults\",\"Old Adults\"]\nsns.scatterplot(x=\"age\", y=\"trestbps\",\n                hue=\"age\",\n                palette=\"ch:r=-.2,d=.3_r\",\n                hue_order=age_group,\n                sizes=(1, 8), linewidth=0,\n                data=df, ax=ax)\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.trestbps, data=df, kind=\"kde\");\n#barplot\nplt.figure(figsize=(15,10))\nsns.barplot(x='age',y='trestbps',data=df)\nplt.show()\n# histogram subplot with non cumulative and cumulative\n\nfig,axes=plt.subplots(nrows=2,ncols=1)\ndf.plot(kind=\"hist\",y=\"chol\",bins=50, range=(0,250),normed=True,ax=axes[0])\ndf.plot(kind=\"hist\",y=\"chol\",bins=50, range=(0,250),normed=True,ax=axes[1],cumulative=True)\nplt.savefig('graph.png')\nplt.show()\n#barplot\nplt.figure(figsize=(15,10))\nsns.barplot(x='age',y='chol',data=df)\nplt.show()\n#boxplot\ndf.boxplot(column='chol',by='age',figsize=(18,18))\nplt.show()\n#jointplot\nsns.jointplot(x=\"age\", y=\"chol\", data=df);\n#scatter plot\nf, ax = plt.subplots(figsize=(6.5, 6.5))\nsns.despine(f, left=True, bottom=True)\nage_group = [\"Young Adult\",\"Middle-Aged Adults\",\"Old Adults\"]\nsns.scatterplot(x=\"age\", y=\"chol\",\n                hue=\"age\",\n                palette=\"ch:r=-.2,d=.3_r\",\n                hue_order=age_group,\n                sizes=(1, 8), linewidth=0,\n                data=df, ax=ax)\nplt.show()\n#jointplot\nwith sns.axes_style(\"white\"):\n    sns.jointplot(x=df.age, y=df.chol, kind=\"hex\", color=\"k\");\n#jointplot\nsns.jointplot(x=df.age, y=df.chol, data=df, kind=\"kde\");\nprint(df['fbs'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='fbs',y='age',data=df)\nplt.show()\n#box plot\ndf.boxplot(column='age',by='fbs')\nplt.show()\nprint(df['restecg'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='restecg',y='age',data=df)\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.restecg, data=df, kind=\"kde\");\n#boxplot\ndf.boxplot(column='age',by='restecg')\nplt.show()\n# histogram subplot with non cumulative and cumulative\n\nfig,axes=plt.subplots(nrows=2,ncols=1)\ndf.plot(kind=\"hist\",y=\"thalach\",bins=50, range=(0,250),normed=True,ax=axes[0])\ndf.plot(kind=\"hist\",y=\"thalach\",bins=50, range=(0,250),normed=True,ax=axes[1],cumulative=True)\nplt.savefig('graph.png')\nplt.show()\n#barplot\nplt.figure(figsize=(18,18))\nsns.barplot(x='age',y='thalach',data=df)\nplt.show()\n#boxplot\ndf.boxplot(column='thalach', by='age',figsize=(18,18))\nplt.show()\n#scatter plot\nf, ax = plt.subplots(figsize=(6.5, 6.5))\nsns.despine(f, left=True, bottom=True)\nage_group = [\"Young Adult\",\"Middle-Aged Adults\",\"Old Adults\"]\nsns.scatterplot(x=\"age\", y=\"thalach\",\n                hue=\"age\",\n                palette=\"ch:r=-.2,d=.3_r\",\n                hue_order=age_group,\n                sizes=(1, 8), linewidth=0,\n                data=df, ax=ax)\nplt.show()\n#jointplot\nsns.jointplot(x=\"thalach\", y=\"age\", data=df);\n#jointplot\nwith sns.axes_style(\"white\"):\n    sns.jointplot(x=df.age, y=df.thalach, kind=\"hex\", color=\"k\");\n#jointplot\nsns.jointplot(x=df.age, y=df.thalach, data=df, kind=\"kde\");\nprint(df['exang'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='exang',y='age', data=df)\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.exang, data=df, kind=\"kde\");\n#boxplot\ndf.boxplot(column='age',by='exang')\nplt.show()\nprint(df['ca'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='ca',y='age',data=df)\nplt.show()\n#boxplot\ndf.boxplot(column='age',by='ca', figsize=(10,10))\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.ca, data=df, kind=\"kde\");\nprint(df['thal'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='thal',y='age',data=df)\nplt.show()\n#boxplot\ndf.boxplot(column='age',by='thal',figsize=(10,10))\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.thal, data=df, kind=\"kde\");\nprint(df['target'].value_counts(dropna=False))\n#barplot\nsns.barplot(x='target',y='age',data=df)\nplt.show()\n\n#boxplot\ndf.boxplot(column='age',by='target')\nplt.show()\n#jointplot\nsns.jointplot(x=df.age, y=df.target, data=df, kind=\"kde\");\n#barplot\nsns.barplot(x='cp',y='thalach',data=df)\nplt.show()\n#boxplot\ndf.boxplot(column='thalach',by='cp', figsize=(10,10))\nplt.show()\n#jointplot\nsns.jointplot(x=df.cp, y=df.thalach, data=df, kind=\"kde\");\n#barplot\nsns.barplot(x='target',y='thalach',data=df)\nplt.show()\n#jointplot\nsns.jointplot(x=df.target, y=df.thalach, data=df, kind=\"kde\");\n#boxplot\ndf.boxplot(column='thalach',by='target', figsize=(7,7))\nplt.show()\nnew_df=df.iloc[:,[0,1,3,4,7]]\nnew_df.head()\n\"\"\"\n**pd.plotting.scatter_matrix:\n**\n* green: female and red: male\n* c: color\n* figsize: figure size\n* diagonal: histohram of each features\n* alpha: opacity\n* s: size of marker\n* marker: marker type\n\"\"\"\ncolor_list = ['red' if i==1 else 'green' for i in new_df.loc[:,'sex']]\npd.plotting.scatter_matrix(new_df.loc[:, new_df.columns != 'sex'],\n                                       c=color_list,\n                                       figsize= [15,15],\n                                       diagonal='hist',\n                                       alpha=0.5,\n                                       s = 200,\n                                       marker = '*',\n                                       edgecolor= \"black\")\nplt.show()\nf,ax1 = plt.subplots(figsize =(20,10))\nsns.pointplot(x='age',y='trestbps',data=df,color='lime',alpha=0.8)\nsns.pointplot(x='age',y='chol',data=df,color='red',alpha=0.8)\nsns.pointplot(x='age',y='thalach',data=df,color='blue',alpha=0.8)\nplt.text(35,0.4,'age-trestbps',color='lime',fontsize = 15,style = 'italic')\nplt.text(40,0.5,'age-chol',color='red',fontsize = 16,style = 'italic')\nplt.text(45,0.6,'age-thalach',color='blue',fontsize = 17,style = 'italic')\nplt.xlabel('age',fontsize = 15,color='blue')\nplt.ylabel('values',fontsize = 15,color='blue')\nplt.title('trestbps  -  chol - thalach',fontsize = 20,color='blue')\nplt.grid()\ndf.cp.dropna(inplace = True)\nlabels = df.cp.value_counts().index\ncolors = ['green','yellow','orange','red']\nexplode = [0,0,0,0]\nsizes = df.cp.value_counts().values\n\n# visual cp\nplt.figure(0,figsize = (7,7))\nplt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%')\nplt.title('Target People According to Chestpain Type',color = 'blue',fontsize = 15)\n\"\"\"\n**<h1>Filtering<\/h1>**\n\n\"\"\"\n#female\ndf[(df['sex']==0) & (df['age']>50) & (df['ca']>0) & (df['chol']>=160) & (df['cp']>=1) & \n   (df['trestbps']>=140) & (df['fbs']==1) & (df['thalach']>=120)& (df['target']==1)] \n#female - ca\ndf[(df['sex']==0) & (df['age']>65) & (df['ca']>0)]\n#female - ca - describe\ndf[(df['sex']==0) & (df['age']>65) & (df['ca']>0)].describe()\n#female - chol\ndf[(df['sex']==0) & (df['age']>65) & (df['chol']>=246)] \n##female - chol - describe\ndf[(df['sex']==0) & (df['age']>65) & (df['chol']>=246)].describe() \n#female - cp\ndf[(df['sex']==0) & (df['age']>65) & (df['cp']>=1)] \n#female - cp -describe\ndf[(df['sex']==0) & (df['age']>65) & (df['cp']>=1)].describe()\n#female - trestbps\ndf[(df['sex']==0) & (df['age']>65) & (df['trestbps']>=140)] \n#female - trestbps -describe\ndf[(df['sex']==0) & (df['age']>65) & (df['trestbps']>=140)].describe()\n#female - fbs\ndf[(df['sex']==0) & (df['age']>65) & (df['fbs']==1)] \n#female - fbs - describe\ndf[(df['sex']==0) & (df['age']>65) & (df['fbs']==1)].describe()\n#female - thalach\ndf[(df['sex']==0) & (df['age']>65) & (df['thalach']>=120)] \n#female - thalach -describe\ndf[(df['sex']==0) & (df['age']>65) & (df['thalach']>=120)].describe()\n#female - target\ndf[(df['sex']==0) & (df['age']>65) & (df['target']==1)] \n#female - target -describe\ndf[(df['sex']==0) & (df['age']>65) & (df['target']==1)].describe() \n#female - exang\ndf[(df['sex']==0) & (df['age']>65) & (df['exang']==1)] \n#female - exang - describe\ndf[(df['sex']==0) & (df['age']>65) & (df['exang']==1)].describe()\n#male\ndf[(df['sex']==1) & (df['age']>65) & (df['ca']>0) & (df['chol']>=160) & (df['cp']>=1) & \n   (df['trestbps']>=140)& (df['fbs']==1) & (df['thalach']>=120) & (df['target']==1)] \n#male - ca\ndf[(df['sex']==1) & (df['age']>65) & (df['ca']>0)] \n#male - ca - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['ca']>0)].describe()\n#male - chol\ndf[(df['sex']==1) & (df['age']>65) & (df['chol']>=160)] \n#male - chol - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['chol']>=160)].describe()\n#male - cp\ndf[(df['sex']==1) & (df['age']>65) & (df['cp']>=1)] \n#male - cp - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['cp']>=1)].describe()\n#male - trestbps\ndf[(df['sex']==1) & (df['age']>65) & (df['trestbps']>=140)]\n#male - trestbps - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['trestbps']>=140)].describe()\n#male- fbs\ndf[(df['sex']==1) & (df['age']>65) & (df['fbs']==1)] \n#male- fbs - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['fbs']==1)].describe()\n#male - thalach\ndf[(df['sex']==1) & (df['age']>65) & (df['thalach']>=120)] \n#male - thalach - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['thalach']>=120)].describe()\n#male - target\ndf[(df['sex']==1) & (df['age']>65) & (df['target']==1)] \n#male - target - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['target']==1)].describe() \n#male - exang\ndf[(df['sex']==1) & (df['age']>65) & (df['ca']>0) & (df['exang']==1)] \n#male - exang - describe\ndf[(df['sex']==1) & (df['age']>65) & (df['ca']>0) & (df['exang']==1)].describe() \n#general\ndf[(df['age']>60) & (df['chol']>=160) & (df['cp']>=1) & \n   (df['trestbps']>=140) & (df['fbs']==1) & (df['thalach']>=120) & (df['target']==1) & (df['exang']==1)] \nx=df['age']>65\ndf[x]\nx=df['age']>65\ndf[x].describe()\n\"\"\"\nReferences:\n\nhttps:\/\/www.kaggle.com\/kanncaa1\/data-sciencetutorial-for-beginners\n\nhttps:\/\/www.kaggle.com\/kanncaa1\/feature-selection-and-data-visualization\n\nhttps:\/\/www.kaggle.com\/kanncaa1\/seaborn-tutorial-for-beginners\n\nhttps:\/\/www.kaggle.com\/kanncaa1\/plotly-tutorial-for-beginners\n\"\"\"\n\"\"\"\n# CONCLUSION\nThank you for your votes and comments\n<br> **EDA and Data Visualization Titanic ** https:\/\/www.kaggle.com\/nidaguler\/eda-and-data-visualization-titanic\/\n<br> **Titanic Survival Detection using Machine Learning** https:\/\/www.kaggle.com\/nidaguler\/titanic-survival-detection-using-machine-learning\n<br> **EDA and Data Visualization NY Airbnb** https:\/\/www.kaggle.com\/nidaguler\/eda-and-data-visualization-ny-airbnb\n<br> **Data Visualization World Happiness Report 2015** https:\/\/www.kaggle.com\/nidaguler\/data-visualization-world-happiness-report-2015\n<br> **Forest Fires in Brazil** https:\/\/www.kaggle.com\/nidaguler\/forest-fires-in-brazil\n<br>**If you have any question or suggest, I will be happy to hear it.**\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8bad8321e535d4'}"}
{"id":"74891","text":"\"\"\"\n# Fake Job Postings\n\nSorry for my English please \/\\\n\n## Data\n\nFeatures list (`Variable`: Definition):\n\n- `job_id`: Unique Job ID<br>\n- `title`: The title of the job ad entry<br>\n- `location`: Geographical location of the job ad<br>\n- `department`: Corporate department (e.g. sales)<br>\n- `salary_range`: Indicative salary range (e.g. $50,000-60,000)<br>\n- `company_profile`: A brief company description<br>\n- `description`: The details description of the job ad<br>\n- `requirements`: Enlisted requirements for the job opening<br>\n- `benefits`: Enlisted offered benefits by the employer<br>\n- `telecommuting`: True for telecommuting positions<br>\n- `has_company_logo`: True if company logo is present<br>\n- `has_questions`: True if screening questions are present<br>\n- `employment_type`: Full-type, Part-time, Contract, etc<br>\n- `required_experience`: Executive, Entry level, Intern, etc<br>\n- `required_education`: Doctorate, Master\u2019s Degree, Bachelor, etc<br>\n- `industry`: Automotive, IT, Health care, Real estate, etc<br>\n- `function`: Consulting, Engineering, Research, Sales etc<br>\n- `fraudulent`: target - Classification attribute\n\"\"\"\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport string\nfrom tqdm import tqdm\nfrom collections import Counter\nfrom itertools import tee\n\nfrom IPython.display import display\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.sparse import hstack as sparse_hstack\nimport pandas as pd\n\nimport matplotlib.pyplot as plt; plt.rcParams['figure.dpi'] = 100\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns; sns.set()\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport eli5\n# statistic methods\ndef tconfint(sample, alpha=0.05):\n    '''Confidence interval based on Student t distribution.'''\n    mean = np.mean(sample)\n    S = np.std(sample, ddof=1)\n    n = len(sample)\n\n    t = stats.t.ppf(1 - alpha \/ 2, n - 1)\n    left_boundary = mean - t * S \/ np.sqrt(n)\n    right_boundary = mean + t * S \/ np.sqrt(n)\n\n    return left_boundary, right_boundary\n\n\ndef tconfint_diff(sample1, sample2, alpha=0.05):\n    '''Confidence interval based on Student t distribution for\n    the difference in means of two samples.'''\n    mean1 = np.mean(sample1)\n    mean2 = np.mean(sample2)\n    s1 = np.std(sample1, ddof=1)\n    s2 = np.std(sample2, ddof=1)\n    n1 = len(sample1)\n    n2 = len(sample2)\n\n    sem1 = np.var(sample1) \/ (n1 - 1)\n    sem2 = np.var(sample2) \/ (n2 - 1)\n    semsum = sem1 + sem2\n    z1 = (sem1 \/ semsum) ** 2 \/ (n1 - 1)\n    z2 = (sem2 \/ semsum) ** 2 \/ (n2 - 1)\n    dof = 1 \/ (z1 + z2)\n\n    t = stats.t.ppf(1 - alpha \/ 2, dof)\n    left_boundary = (mean1 - mean2) - t * np.sqrt((s1 ** 2) \/ n1 + (s2 ** 2) \/ n2)\n    right_boundary = (mean1 - mean2) + t * np.sqrt((s1 ** 2) \/ n1 + (s2 ** 2) \/ n2)\n\n    return left_boundary, right_boundary\n\n\ndef bootstrap_statint(sample, stat=np.mean, n_samples=5000, alpha=0.05):\n    '''Statistical interval for a `stat` of a `sample` calculation\n    using bootstrap sampling mechanism. `stat` is a numpy function\n    like np.mean, np.std, np.median, np.max, np.min, etc.'''\n    indices = np.random.randint(0, len(sample), (n_samples, len(sample)))\n    samples = sample[indices]\n\n    stat_scores = stat(samples, axis=1)\n    boundaries = np.percentile(stat_scores, [100 * alpha \/ 2, 100 * (1 - alpha \/ 2)])\n    return boundaries\n\n\ndef bootstrap_statint_diff(sample1, sample2, stat=np.mean, n_samples=5000, alpha=0.05):\n    '''Statistical interval for a difference in `stat` of two samples\n    calculation using bootstrap sampling mechanism. `stat` is a numpy\n    function like np.mean, np.std, np.median, np.max, np.min, etc.'''\n    indices1 = np.random.randint(0, len(sample1), (n_samples, len(sample1)))\n    indices2 = np.random.randint(0, len(sample2), (n_samples, len(sample2)))\n    samples1 = sample1[indices1]\n    samples2 = sample2[indices2]\n\n    stat_scores1 = stat(samples1, axis=1)\n    stat_scores2 = stat(samples2, axis=1)\n    stat_scores_diff = stat_scores1 - stat_scores2\n    boundaries = np.percentile(stat_scores_diff, [100 * alpha \/ 2, 100 * (1 - alpha \/ 2)])\n    return boundaries\n\n\ndef proportion_confint(sample, alpha=0.05):\n    '''Wilson\\'s \u0441onfidence interval for a proportion.'''\n    p = np.mean(sample)\n    n = len(sample)\n\n    z = stats.norm.ppf(1 - alpha \/ 2)\n    left_boundary = 1 \/ (1 + z ** 2 \/ n) * (p + z ** 2 \/ (2 * n) \\\n                                            - z * np.sqrt(p * (1 - p) \/ n + z ** 2 \/ (4 * n ** 2)))\n    right_boundary = 1 \/ (1 + z ** 2 \/ n) * (p + z ** 2 \/ (2 * n) \\\n                                             + z * np.sqrt(p * (1 - p) \/ n + z ** 2 \/ (4 * n ** 2)))\n\n    return left_boundary, right_boundary\n\n\ndef proportions_diff_confint_ind(sample1, sample2, alpha=0.05):\n    '''Confidence interval for the difference of two independent proportions.'''\n    z = stats.norm.ppf(1 - alpha \/ 2)\n    p1 = np.mean(sample1)\n    p2 = np.mean(sample2)\n    n1 = len(sample1)\n    n2 = len(sample2)\n\n    left_boundary = (p1 - p2) - z * np.sqrt(p1 * (1 - p1) \/ n1 + p2 * (1 - p2) \/ n2)\n    right_boundary = (p1 - p2) + z * np.sqrt(p1 * (1 - p1) \/ n1 + p2 * (1 - p2) \/ n2)\n\n    return left_boundary, right_boundary\n\n\ndef permutation_test_ind(sample1, sample2, max_permutations=None, alternative='two-sided'):\n    '''Permutation test for two independent samples.'''\n    if alternative not in ('two-sided', 'less', 'greater'):\n        raise ValueError('Alternative not recognized, should be \\'two-sided\\', \\'less\\' or \\'greater\\'.')\n\n    t_stat = np.mean(sample1) - np.mean(sample2)\n\n    joined_sample = np.hstack((sample1, sample2))\n    n1 = len(sample1)\n    n = len(joined_sample)\n\n    if max_permutations:\n        index = list(range(n))\n        indices = set([tuple(index)])\n        for _ in range(max_permutations - 1):\n            np.random.shuffle(index)\n            indices.add(tuple(index))\n\n        indices = [(index[:n1], index[n1:]) for index in indices]\n    else:\n        indices = [(list(index), list(filter(lambda i: i not in index, range(n)))) \\\n                    for index in itertools.combinations(range(n), n1)]\n\n    zero_distr = [joined_sample[list(i[0])].mean() - joined_sample[list(i[1])].mean() \\\n                  for i in indices]\n\n    if alternative == 'two-sided':\n        p_value = sum([abs(x) >= abs(t_stat) for x in zero_distr]) \/ len(zero_distr)\n\n    if alternative == 'less':\n        p_value = sum([x <= t_stat for x in zero_distr]) \/ len(zero_distr)\n\n    if alternative == 'greater':\n        p_value = sum([x >= t_stat for x in zero_distr]) \/ len(zero_distr)\n\n    return t_stat, p_value\n\n\ndef proportions_ztest_ind(sample1, sample2, alternative='two-sided'):\n    '''Z-test for two independent proportions.'''\n    if alternative not in ('two-sided', 'less', 'greater'):\n        raise ValueError('Alternative not recognized, should be \\'two-sided\\', \\'less\\' or \\'greater\\'.')\n\n    p1 = np.mean(sample1)\n    p2 = np.mean(sample2)\n    n1 = len(sample1)\n    n2 = len(sample2)\n\n    P = (p1 * n1 + p2 * n2) \/ (n1 + n2)\n    z_stat = (p1 - p2) \/ np.sqrt(P * (1 - P) * (1 \/ n1 + 1 \/ n2))\n\n    if alternative == 'two-sided':\n        p_value = 2 * (1 - stats.norm.cdf(np.abs(z_stat)))\n\n    if alternative == 'less':\n        p_value = stats.norm.cdf(z_stat)\n\n    if alternative == 'greater':\n        p_value = 1 - stats.norm.cdf(z_stat)\n\n    return z_stat, p_value\n\n\ndef cramers_v(contingency_table):\n    '''Cramer\\'s V coefficient.'''\n    n = np.sum(contingency_table)\n    ct_nrows, ct_ncols = contingency_table.shape\n    if n < 40 or np.sum(contingency_table < 5) \/ (ct_nrows * ct_ncols) > 0.2:\n        raise ValueError('Contingency table isn\\'t suitable for Cramers\\'s V coefficient calculation.')\n\n    chi2, p_value = stats.chi2_contingency(contingency_table)[:2]\n    corr = np.sqrt(chi2 \/ (n * (min(ct_nrows, ct_ncols) - 1)))\n    return corr, p_value\n\"\"\"\n## First look\n\nThe dataset:\n\"\"\"\ndata = pd.read_csv('..\/input\/real-or-fake-fake-jobposting-prediction\/fake_job_postings.csv')\ndata.head(10)\ndata.info()\n\"\"\"\nThere are many NA-values in the table and there are features that have to be preprocessed for further usage. Let's save names of each feature-type and work on complex ones.\n\"\"\"\nbin_features = ['telecommuting', 'has_company_logo', 'has_questions']\ncat_features = ['department', 'employment_type', 'required_experience', \n                'required_education', 'industry', 'function']\n\ntext_features = ['title', 'company_profile', 'description', 'requirements', 'benefits']\ncomplex_features = ['location', 'salary_range']\n\"\"\"\nAnd drop `job_id`, it's useless.\n\"\"\"\ndata.drop('job_id', axis=1, inplace=True)\n\"\"\"\n## Feature preparation\n\n### Text features\n\nFeatures that describe textual components of a job post:\n\"\"\"\ndata[text_features].head()\n\"\"\"\nAdding indicators of specified values (there is no NA-values in `title`):\n\"\"\"\nfor feature_name in text_features[1:]:\n    unspec_feature_name = f'{feature_name}_specified'\n    data[unspec_feature_name] = (~data[feature_name].isna()).astype('int')\n    bin_features += [unspec_feature_name]\ndata.head()[text_features + bin_features[-4:]]\n\"\"\"\nFilling NA-values with an empty string:\n\"\"\"\nfor feature_name in text_features[1:]:\n    data[feature_name].fillna('', inplace=True)\n\"\"\"\nNow we have to clean our texts from punctuation marks and stop-words, and apply stemming:\n\"\"\"\n# nltk.download('stopwords')\n# nltk.download('punkt')\nnltk_supported_languages = ['hungarian', 'swedish', 'kazakh', 'norwegian',\n                            'finnish', 'arabic', 'indonesian', 'portuguese',\n                            'turkish', 'azerbaijani', 'slovene', 'spanish',\n                            'danish', 'nepali', 'romanian', 'greek', 'dutch',\n                            'tajik', 'german', 'english', 'russian',\n                            'french', 'italian']\n# stop words list\nstop_words = set(stopwords.words(nltk_supported_languages))\n# stemmer\nporter = PorterStemmer()\ndef preprocess_texts(texts):\n    '''Returns a list of clean and word-stemmed strings.'''\n    preprocessed_texts = []\n    for text in tqdm(texts):\n        # punctuation marks cleaning\n        text = ''.join([sym.lower() for sym in text if sym.isalpha() or sym == ' '])\n        \n        # tokenization\n        tokenized_text = word_tokenize(text)\n        \n        # stop words cleaning\n        tokenized_text_wout_sw = [word for word in tokenized_text if word not in stop_words]\n        \n        # stemming\n        tokenized_text_wout_sw_stem = [porter.stem(word) for word in tokenized_text_wout_sw]\n        \n        # saving result\n        preprocessed_texts += [' '.join(tokenized_text_wout_sw_stem)]\n    \n    return preprocessed_texts\n%%time\nfor feature_name in text_features:\n    data[feature_name] = preprocess_texts(data[feature_name])\n\ndata[text_features].head()\n\"\"\"\nDone! Now move on to complex features.\n\"\"\"\n\"\"\"\n### Complex features\n\n#### `location`\n\nThe main structure of `location`'s values is `Country, State, City`:\n\"\"\"\nlocation = data['location'].copy()\nlocation.head(15)\n\"\"\"\nLet's divide and extract these elements. We will use them as a categorical features in the future.\n\"\"\"\nlocation_splitted = list(location.str.split(', ').values)\nlocation_splitted[:15]\n\"\"\"\nFilling in missing values (we will use `'Unspecified'` word to replace NA-values for all categorical features):\n\"\"\"\nfor loc_ind, loc in enumerate(location_splitted):\n    if loc is np.nan:\n        location_splitted[loc_ind] = ['Unpecified'] * 3\n    else:\n        for el_ind, el in enumerate(loc):\n            if el == '':\n                loc[el_ind] = 'Unpecified'\nlocation_splitted[:15]\n\"\"\"\nBut there are some troubles:\n\"\"\"\nany([len(loc) > 3 for loc in location_splitted])\nany([len(loc) < 3 for loc in location_splitted])\n\"\"\"\nNot all values of `location` were described in 3 elements. Let's look at unusual values:\n\"\"\"\nfor loc_ind, loc in enumerate(location_splitted):\n    if len(loc) > 3:\n        print(loc_ind, loc)\nfor loc_ind, loc in enumerate(location_splitted):\n    if len(loc) < 3:\n        print(loc_ind, loc)\n\"\"\"\nTo resolve these problems a strange move have to be undertaken due to this oddity:\n\"\"\"\nlocation_splitted[0] is list\ntype(location_splitted[0])\nlocation_splitted = list(map(lambda loc: list(loc), location_splitted))\n\"\"\"\nMost of the problems arose due to the refinement of the position at the third element using a comma. Let's resolve it simply (and supplement values in which only the country is specified):\n\"\"\"\nfor loc_ind, loc in enumerate(location_splitted):\n    if len(loc) > 3:\n        location_splitted[loc_ind] = loc[:2] + [', '.join(loc[2:])]\n    if len(loc) < 3:\n        location_splitted[loc_ind] += ['Unpecified'] * 2\n\"\"\"\nAlright:\n\"\"\"\nany([len(loc) != 3 for loc in location_splitted])\n\"\"\"\nNow let's add new features to the dataset table and remove the old one from it:\n\"\"\"\ndata_location = pd.DataFrame(location_splitted, columns=['country', 'state', 'city'])\ndata_location.head(15)\n# complementing the list of categorical features\ncat_features += ['country', 'state', 'city']\ndata = pd.concat([data, data_location], axis=1)\ndata.head()\ndata.drop('location', axis=1, inplace=True)\n\"\"\"\n#### `salary_range`\n\nNow we need to do something with the `salary_range` column because we can't work with it as with a categorical feature:\n\"\"\"\nsalary_range = data.salary_range.copy()\nsalary_range.head(15)\n\"\"\"\nFilling in the missing values with a `0-0` value (in the future we will create an indicator for the unspecified data):\n\"\"\"\nsalary_range.fillna('0-0', inplace=True)\n\"\"\"\nAnd splitting them:\n\"\"\"\nsalary_range_sep = list(salary_range.str.split('-').values)\nsalary_range_sep[:5]\n\"\"\"\nChecking for unusual values:\n\"\"\"\nfor range_ind, s_range in enumerate(salary_range_sep):\n    if len(s_range) < 2 or len(s_range) > 2:\n        print(range_ind, s_range)\n\"\"\"\nAnd fixing it:\n\"\"\"\nsalary_range_sep[5538] = ['40000', '40000']\n\"\"\"\nNot all gained values are numerical:\n\"\"\"\nerror_range_inds = []\nfor range_ind, s_range in enumerate(salary_range_sep):\n    min_value, max_value = s_range\n    if not min_value.isdigit() or not max_value.isdigit():\n        print(range_ind, (min_value, max_value))\n        error_range_inds += [range_ind]\n\"\"\"\nSomebody specified some kind of dates instead of salary range, let's replace these values with a `['0', '0']`:\n\"\"\"\nfor range_ind in error_range_inds:\n    salary_range_sep[range_ind] = ['0', '0']\n\"\"\"\nSaving results into a `pandas.DataFrame` object:\n\"\"\"\ndata_salary_range = pd.DataFrame(np.array(salary_range_sep, dtype='int64'), \n                                 columns=['min_salary', 'max_salary'])\ndata_salary_range.head(15)\n\"\"\"\nAdding a column for marking specified salary ranges:\n\"\"\"\ndata_salary_range['salary_specified'] = ((data_salary_range.min_salary != 0) | \n                                         (data_salary_range.max_salary != 0)).astype('int64')\ndata_salary_range.head(15)\n# creating the list of numerical features names and complementing the list of binary ones\nnum_features = ['min_salary', 'max_salary']\nbin_features += ['salary_specified']\n\"\"\"\nAnd saving results into the original table:\n\"\"\"\ndata = pd.concat([data, data_salary_range], axis=1)\ndata.head()\ndata.drop('salary_range', axis=1, inplace=True)\n\"\"\"\n### Other features\n\nWe still have NA-values in other columns:\n\"\"\"\ndata.info()\n\"\"\"\nBut the rest features are categorical so we will fill the missing values using `'Unspecified'` value:\n\"\"\"\ndata.fillna('Unspecified', inplace=True)\ndata.info()\n\"\"\"\n## Analysis\n\"\"\"\n\"\"\"\nLet's look at the distribution of the target feature:\n\"\"\"\nplt.figure(figsize=(6, 4))\nax = sns.countplot(data.fraudulent)\nplt.title('The distribution of the target feature (fraudulent)')\nfor p in ax.patches:\n    ax.annotate(p.get_height(), (p.get_x()+0.33, p.get_height()))\n\nplt.show()\n\"\"\"\nClasses are not balanced, so we have to use oversampling\/undersampling and calculate \\[not-only-accuracy\\] metrics (ROC AUC, etc.) to estimate our models in the future.\n\nDistributions of `fraudulent` for the binary features:\n\"\"\"\nfig = plt.figure(figsize=(25, 30))\nouter = gridspec.GridSpec(4, 2, wspace=0.2, hspace=0.1)\n\nfor feature_ind, feature_name in enumerate(bin_features):\n    inner = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=outer[feature_ind], \n                                             wspace=0.5, hspace=0.7)\n    \n    ax = plt.Subplot(fig, outer[feature_ind])\n    ax.set_title(f'The distribution of fraudulent for each {feature_name}\\'s class')\n    ax.axis('off')\n    fig.add_subplot(ax)\n    \n    for feature_class in [0, 1]:\n        ax = plt.Subplot(fig, inner[feature_class])\n        feature_cl_vc = data[data[feature_name] == feature_class].fraudulent.value_counts().sort_index()\n        if len(feature_cl_vc) == 2:\n            feature_cl_vc.index = ['non-fraudulent', 'fraudulent']\n        else:\n            feature_cl_vc.index = ['fraudulent']\n        \n        ax.pie(feature_cl_vc.values, labels=feature_cl_vc.index, autopct='%1.1f%%')\n        ax.set_title(f'{feature_name} = {feature_class}')\n        fig.add_subplot(ax)\n\nfig.suptitle('Distributions of fraudulent for the binary features')\nfig.subplots_adjust(top=0.95)\nfig.show()\n\"\"\"\nLook's like those who post fraudulent posts more often don't have company logo\/company profile and more often indicate in their posts that there will be no screening questions at the survey. Also fraudulent post writers less often specify salary and more often offer remote employment.\n\"\"\"\n\"\"\"\nThe distributions of fraudulent for `description_specified` feature looks strange because there is only one record in the table that have an unspecified description and it's fraudulent:\n\"\"\"\ncont_table = pd.crosstab(data.fraudulent, data.description_specified)\nprint('Contingency table (fraudulent x description_specified):')\ndisplay(cont_table)\n\"\"\"\nLet's check how some of the binary features may be related:\n\"\"\"\ndef show_feature1_x_feature2_info(feature_name1, feature_name2, figsize=(12, 4), is_binxcat=False):\n    '''Shows info about a combination of two binary\/categorical features.'''\n    cont_table = pd.crosstab(data[feature_name1], data[feature_name2]).fillna(0)\n    prop_table = pd.pivot_table(data, index=feature_name1, columns=feature_name2, \n                                values='fraudulent', aggfunc=np.mean).fillna(0)\n    \n    corr, p = cramers_v(cont_table.values)\n    \n    if is_binxcat:\n        fig, axes = plt.subplots(2, 1, figsize=figsize, sharex=True)\n    else:\n        fig, axes = plt.subplots(1, 2, figsize=figsize)\n    \n    sns.heatmap(cont_table, annot=True, fmt='d', ax=axes[0])\n    axes[0].set_title(f'Contingency table:')\n    if is_binxcat:\n        axes[0].set_xlabel('')\n    \n    sns.heatmap(prop_table, annot=True, ax=axes[1])\n    axes[1].set_title(f'Proportion of fraudulent posts:')\n    \n    fig_title = f'{feature_name1} x {feature_name2} (Correlation: {round(corr, 4)}, p-value: {round(p, 4)}))'\n    if is_binxcat:\n        fig.suptitle(fig_title, y=1.05, x=0.45)\n    else:\n        fig.suptitle(fig_title, y=1.05)\n    \n    fig.show()\nshow_feature1_x_feature2_info('has_company_logo', 'company_profile_specified')\n\"\"\"\nThe largest one of these probabilities of being fraudulent have posts without company's profile and logo, the smallest - posts that have them.\n\"\"\"\nshow_feature1_x_feature2_info('benefits_specified', 'has_questions')\n\"\"\"\nThe largest one of these probabilities of being fraudulent have posts with specified benefits and without announcement of any questions during interview.\n\"\"\"\nshow_feature1_x_feature2_info('telecommuting', 'has_questions')\n\"\"\"\nThe largest one of these probabilities of being fraudulent have posts that offer remote work and promise an interview without questions.\n\"\"\"\nshow_feature1_x_feature2_info('telecommuting', 'benefits_specified')\n\"\"\"\nThe largest one of these probabilities of being fraudulent have posts that offer remote work and don't specify any benefits.\n\"\"\"\nshow_feature1_x_feature2_info('benefits_specified', 'salary_specified')\n\"\"\"\nThe largest one of these probabilities of being fraudulent have posts that include specified benefits and specified salaries.\n\nLet's compare proportions of fraudulent posts for `has_questions` and `salary_specified` classes (0 and 1):\n\"\"\"\nround_confint = lambda confint: list(map(lambda lim: round(lim, 4), confint))\ndef print_stats_for_proportions(feature_name):\n    fraudulent_0 = data[data[feature_name] == 0].fraudulent\n    fraudulent_1 = data[data[feature_name] == 1].fraudulent\n    \n    prop_0 = round(np.mean(fraudulent_0), 4)\n    prop_1 = round(np.mean(fraudulent_1), 4)\n    prop_0_confint = round_confint(proportion_confint(fraudulent_0))\n    prop_1_confint = round_confint(proportion_confint(fraudulent_1))\n    \n    bigger_prop, smaller_prop = (fraudulent_0, fraudulent_1) if prop_0 > prop_1 else (fraudulent_1, fraudulent_0)\n    props_diff = round(np.mean(bigger_prop) - np.mean(smaller_prop), 4)\n    props_diff_confint = round_confint(proportions_diff_confint_ind(bigger_prop, smaller_prop))\n    z_test_p = proportions_ztest_ind(fraudulent_0, fraudulent_1)[1]\n    \n    print(f'Feature: {feature_name}\\n======')\n    print(f'Proportion of fraudulent posts for 0: {prop_0}')\n    print(f'Proportion of fraudulent posts for 1: {prop_1}')\n    print(f'Confidence interval for the proportion of fraudulent posts for 0: {prop_0_confint}')\n    print(f'Confidence interval for the proportion of fraudulent posts for 1: {prop_1_confint}')\n    print(f'Difference in these proportions: {props_diff}')\n    print(f'Confidence interval for the difference in these proportions: {props_diff_confint}')\n    print(f'Z-test result: {z_test_p} (p-value)')\nprint_stats_for_proportions('has_questions')\nround((0.0331 \/ 0.0284) * 100, 1)\n\"\"\"\nThe chance to meet a fraudulent post among posts that don't announce any questions is at least 116.5% higher than the chance to meet it among posts that do it.\n\"\"\"\nprint_stats_for_proportions('salary_specified')\nround((0.0273 \/ 0.0427) * 100, 1)\n\"\"\"\nWhen you browse posts with specified salaries it's at least 63.9% higher chance to meet a fraudulent one than when you check posts without specified salaries.\n\"\"\"\n\"\"\"\nLet's look at the categorical features:\n\"\"\"\nfor feature_name in cat_features:\n    print(f'Count of {feature_name}\\'s unique values: {data[feature_name].unique().shape[0]}')\n\"\"\"\nIt will be difficult to make any kind of plot for every categorical feature due to the number of classes in most of them. Let's plot ones that have fewer amount of classes (`plotly` charts fit better for this):\n\"\"\"\ndef plot_cat_feature_distribution(feature_name):\n    '''Makes a plotly chart with categorical feature\\'s distribution.'''\n    feature_0f = data[data.fraudulent == 0][feature_name].value_counts()\n    feature_1f = data[data.fraudulent == 1][feature_name].value_counts()\n    \n    fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]], \n                        subplot_titles=['non-fraudulent', 'fraudulent'])\n    fig.add_trace(go.Pie(labels=feature_0f.index, \n                         values=feature_0f.values), \n                  row=1, col=1)\n    fig.add_trace(go.Pie(labels=feature_1f.index, \n                         values=feature_1f.values), \n                  row=1, col=2)\n    \n    fig.update_layout(title_text=f'The distribution of {feature_name}')\n    fig.show()\nplot_cat_feature_distribution('employment_type')\nplot_cat_feature_distribution('required_experience')\nplot_cat_feature_distribution('required_education')\nfunc_meanfr_pt = pd.pivot_table(data, index='function', values='fraudulent', \n                                aggfunc=np.mean).sort_values(by='fraudulent', ascending=False)\nfunc_meanfr_pt.columns = ['Proportion of fraudulent posts']\nprint('Top-15 function\\'s values with the biggest proportions of fraudulent posts:')\ndisplay(func_meanfr_pt.head(15))\ncountry_meanfr_pt = pd.pivot_table(data, index='country', values='fraudulent', \n                                   aggfunc=np.mean).sort_values(by='fraudulent', ascending=False)\ncountry_meanfr_pt.columns = ['Proportion of fraudulent posts']\nprint('Top-15 country\\'s values with the biggest proportions of fraudulent posts:')\ndisplay(country_meanfr_pt.head(15))\n\"\"\"\nLet's check how some of categorical and binary features may be related:\n\"\"\"\nshow_feature1_x_feature2_info('employment_type', 'required_experience', (18, 5))\nshow_feature1_x_feature2_info('benefits_specified', 'required_education', (14, 4.5), True)\nshow_feature1_x_feature2_info('has_questions', 'required_education', (14, 4.5), True)\n\"\"\"\nNow let's look at the numerical features (salary info):\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(15, 7))\n\nfor ind, feature_name in enumerate(num_features):\n    sns.boxplot(y=feature_name, x='fraudulent', data=data[data.salary_specified == 1], ax=axes[ind])\n    axes[ind].set_ylim([-1e4, 2e5])\n    axes[ind].set_xticklabels(['non-fraudulent', 'fraudulent'])\n    axes[ind].set_title(f'Distributions of specified {feature_name}')\n\nfig.suptitle('Distributions of min_salary and max_salary')\nfig.show()\n\"\"\"\nThose who write fake job posts often offer slightly lower salaries... Let's look at differencies between min and max salaries:\n\"\"\"\ndiff_salary = data[data.salary_specified == 1]['max_salary'] - data[data.salary_specified == 1]['min_salary']\nplt.figure(figsize=(5, 5))\nsns.boxplot(y=diff_salary, x='fraudulent', data=data[data.salary_specified == 1])\nplt.ylim([-1e4, 1e5])\nplt.xticks([0, 1], ['non-fraudulent', 'fraudulent'])\nplt.ylabel('Difference')\nplt.title('Distribution of difference between\\n min and max salary')\nplt.show()\n\"\"\"\nThere is a difference in medians, let's calculate them and some descriptive statistics (there is no sense in compairing means because there are too many outliers here):\n\"\"\"\nspecified_salaries = data[data.salary_specified == 1][num_features]\nspecified_salaries['difference'] = diff_salary\nspecified_salaries['fraudulent'] = data.fraudulent\nspecified_salaries.head()\n\"\"\"\nWe can't use Mann\u2013Whitney U test for distributions comparison because -\n\"\"\"\nnp.sum(np.unique(specified_salaries.min_salary, return_counts=True)[1] > 10)\nnp.sum(np.unique(specified_salaries.max_salary, return_counts=True)[1] > 10)\n\"\"\"\n\\- so we will use Permutation test:\n\"\"\"\ndef print_stats_for_salary(feature_name):\n    '''Calculates statistics for fraudulent and non-fraudulent salary-feature.'''\n    np.random.seed(42)\n    feature_0f = specified_salaries[specified_salaries.fraudulent == 0][feature_name]\n    feature_1f = specified_salaries[specified_salaries.fraudulent == 1][feature_name]\n    \n    med_0f = np.median(feature_0f)\n    med_1f = np.median(feature_1f)\n    med_0f_confint = bootstrap_statint(feature_0f.values, stat=np.median)\n    med_1f_confint = bootstrap_statint(feature_1f.values, stat=np.median)\n    \n    bigger_med, smaller_med = (feature_0f, feature_1f) if med_0f > med_1f else (feature_1f, feature_0f)\n    med_diff = np.median(bigger_med) - np.median(smaller_med)\n    med_diff_confint = bootstrap_statint_diff(bigger_med.values, smaller_med.values, stat=np.median)\n    perm_test_p = permutation_test_ind(feature_0f, feature_1f, max_permutations=5000)[1]\n    \n    print(f'Feature: {feature_name}\\n======')\n    print(f'Median of {feature_name} in non-fraudulent posts: {med_0f}')\n    print(f'Median of {feature_name} in fraudulent posts:     {med_1f}')\n    print(f'Statistical interval for the median of {feature_name} in non-fraudulent posts: {med_0f_confint}')\n    print(f'Statistical interval for the median of {feature_name} in fraudulent posts:     {med_1f_confint}')\n    print(f'Difference in these medians: {med_diff}')\n    print(f'Statistical interval for the difference in these medians: {med_diff_confint}')\n    print(f'Permutation test result: {perm_test_p} (p-value)')\nprint_stats_for_salary('min_salary')\nprint_stats_for_salary('max_salary')\nprint_stats_for_salary('difference')\n\"\"\"\nDifferencies between `min_salary`'s medians of 0 and 1 `fraudulent` groups are much more significant than between `max_salary`'s and `different`'s ones. But there isn't difference in distributions for any of them. \n\nLet's compare mean count of words and distributions of lenghts of each textual feature for groups of 0 and 1 `fraudulent`:\n\"\"\"\nfig, axes = plt.subplots(3, 2, figsize=(15, 18))\n\ntext_features_gen = iter(text_features)\n\nfor row in range(3):\n    for col in range(2):\n        try:\n            feature_name = next(text_features_gen)\n        except StopIteration:\n            break\n        \n        if feature_name == 'title':\n            feature_values_0f = data[(data.fraudulent == 0)][feature_name].astype(str)\n            feature_values_1f = data[(data.fraudulent == 1)][feature_name].astype(str)\n        else:\n            feature_values_0f = data[(data.fraudulent == 0) & data[f'{feature_name}_specified']][feature_name].astype(str)\n            feature_values_1f = data[(data.fraudulent == 1) & data[f'{feature_name}_specified']][feature_name].astype(str)\n\n        fv_0f_len = feature_values_0f.str.split(' ').apply(len)\n        fv_1f_len = feature_values_1f.str.split(' ').apply(len)\n        \n        sns.distplot(fv_0f_len, label='non-fraudulent', ax=axes[row, col])\n        sns.distplot(fv_1f_len, label='fraudulent', ax=axes[row, col])\n        axes[row, col].set_title(f'The distribution of {feature_name}\\'s count of words')\n        axes[row, col].legend()\n        \nfig.suptitle('Distributions of count of words for each text feature', y=0.92)\nfig.show()\ndef print_stats_for_texts(feature_name):\n    '''Calculates statistics for fraudulent and non-fraudulent count of words in feature\\'s texts.'''\n    if feature_name == 'title':\n        feature_values_0f = data[(data.fraudulent == 0)][feature_name].astype(str)\n        feature_values_1f = data[(data.fraudulent == 1)][feature_name].astype(str)\n    else:\n        feature_values_0f = data[(data.fraudulent == 0) & data[f'{feature_name}_specified']][feature_name].astype(str)\n        feature_values_1f = data[(data.fraudulent == 1) & data[f'{feature_name}_specified']][feature_name].astype(str)\n    \n    lens_0f = feature_values_0f.str.split(' ').apply(len)\n    lens_1f = feature_values_1f.str.split(' ').apply(len)\n    \n    mean_lens_0f = round(np.mean(lens_0f), 4)\n    mean_lens_1f = round(np.mean(lens_1f), 4)\n    mean_lens_0f_confint = round_confint(tconfint(lens_0f.values))\n    mean_lens_1f_confint = round_confint(tconfint(lens_1f.values))\n    \n    bigger_mean, smaller_mean = (lens_0f, lens_1f) if mean_lens_0f > mean_lens_1f else (lens_1f, lens_0f)\n    mean_diff = round(np.mean(bigger_mean) - np.mean(smaller_mean), 4)\n    \n    mean_diff_confint = round_confint(tconfint_diff(bigger_mean.values, smaller_mean.values))\n    perm_test_p = permutation_test_ind(lens_0f, lens_1f, max_permutations=5000)[1]\n    \n    print(f'Feature: {feature_name}\\n======')\n    print(f'Mean of {feature_name}\\'s count of words in non-fraudulent posts: {mean_lens_0f}')\n    print(f'Mean of {feature_name}\\'s count of words in fraudulent posts:     {mean_lens_1f}')\n    print(f'Confidence interval for the mean of {feature_name}\\'s count of words in non-fraudulent posts: {mean_lens_0f_confint}')\n    print(f'Confidence interval for the mean of {feature_name}\\'s count of words in fraudulent posts:     {mean_lens_1f_confint}')\n    print(f'Difference in these means: {mean_diff}')\n    print(f'Confidence interval for the difference in these means: {mean_diff_confint}')\n    print(f'Permutation test result: {perm_test_p} (p-value)')\nfor feature_name in text_features:\n    print_stats_for_texts(feature_name)\n    print()\n\"\"\"\nLet's create two new numerical features for `company_profile`'s and `requirements`'s count of words (because their distributions are probably different, as well as `title`'s, but the maximum difference in means of 0.4 of a word not very noticeable in terms of logic):\n\"\"\"\ndata['company_profile_count_of_words'] = data['company_profile'].astype(str).str.split(' ').apply(len)\ndata['requirements_count_of_words'] = data['requirements'].astype(str).str.split(' ').apply(len)\ndata.head()[['company_profile_count_of_words', 'requirements_count_of_words']]\nnum_features += ['company_profile_count_of_words', 'requirements_count_of_words']\n\"\"\"\nNow we are ready to fit models.\n\"\"\"\n\"\"\"\n## Transforming features and fitting models\n\"\"\"\n\"\"\"\nFirstly let's increase the count of 1 `fraudulent` records in the dataset using oversampling:\n\"\"\"\ndata_1f = data[data.fraudulent == 1]\noriginal_data = data.copy()\ndata = pd.concat([data] + [data_1f] * 7, axis=0)\nplt.figure(figsize=(6, 4))\nax = sns.countplot(data.fraudulent)\nplt.title('The distribution of the target feature (fraudulent)')\nfor p in ax.patches:\n    ax.annotate(p.get_height(), (p.get_x()+0.33, p.get_height()))\n\nplt.show()\n\"\"\"\nCross-validation splitter:\n\"\"\"\nskf = StratifiedKFold(n_splits=4, random_state=42)\n\"\"\"\nDividing features and targets:\n\"\"\"\nX, y = data.drop('fraudulent', axis=1), data.fraudulent\n\"\"\"\nNumerical features have to be scaled, categorical features have to be transformed into sets of binary ones and text features have to be vectorized (I'm using TF-IDF method):\n\"\"\"\nnum_transformer = Pipeline(steps=[('scaler', StandardScaler())])\ncat_transformer = Pipeline(steps=[('onehot', OneHotEncoder(handle_unknown='ignore'))])\ntext_transformer = Pipeline(steps=[('tfidf', TfidfVectorizer(ngram_range=(1, 2)))])\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', num_transformer, num_features),\n        ('cat', cat_transformer, cat_features),\n        *[(feature_name, text_transformer, feature_name) \n          for feature_name in text_features]\n    ]\n)\n\"\"\"\nWe'll start with a logistic regression model (default parameters):\n\"\"\"\nlog_reg_pipe = Pipeline(steps=[('preprocessor', preprocessor),\n                               ('classifier', LogisticRegression())])\n%%time\ncv_scores = cross_validate(log_reg_pipe, X, y, return_train_score=True, cv=skf, \n                           scoring=['accuracy', 'roc_auc'], n_jobs=-1)\n\nprint(f'Accuracy on train part: {cv_scores[\"train_accuracy\"]}, mean: {cv_scores[\"train_accuracy\"].mean()}')\nprint(f'Accuracy on test part:  {cv_scores[\"test_accuracy\"]}, mean: {cv_scores[\"test_accuracy\"].mean()}')\nprint(f'ROC AUC on train part: {cv_scores[\"train_roc_auc\"]}, mean: {cv_scores[\"train_roc_auc\"].mean()}')\nprint(f'ROC AUC on test part:  {cv_scores[\"test_roc_auc\"]}, mean: {cv_scores[\"test_roc_auc\"].mean()}')\n\"\"\"\nI think we can stop at this point. Maybe the dataset wasn't assembled correctly or there are too few records in it... Or maybe I've done something wrong, but the data is too easy to classify. Or maybe everything is alright? Let's check model's weights:\n\"\"\"\n%%time\nfeature_names = num_features.copy()\n\nnum_features_scaled = StandardScaler().fit_transform(data[num_features])\nX = num_features_scaled\n\nfeature_names += bin_features\nX = np.hstack([X, data[bin_features]])\n\n\nfor feature_name in cat_features:\n    encoder = OneHotEncoder()\n    encoded_feature = encoder.fit_transform(data[feature_name].values.reshape(-1, 1))\n    \n    X = sparse_hstack([X, encoded_feature])\n    f_names = list(map(lambda cat: f'{feature_name}:{cat}', encoder.categories_[0]))\n    feature_names += f_names\n\nfor feature_name in text_features:\n    vectorizer = TfidfVectorizer(ngram_range=(1, 2))\n    vectorized_feature = vectorizer.fit_transform(data[feature_name])\n    \n    X = sparse_hstack([X, vectorized_feature])\n    sorted_phrases = [pair[0] for pair in list(sorted(vectorizer.vocabulary_.items(), \n                                                      key=lambda pair: pair[1]))]\n    f_names = list(map(lambda phrase: f'{feature_name}:{phrase}', sorted_phrases))\n    feature_names += f_names\nX.shape[1], len(feature_names)\nlog_reg = LogisticRegression(random_state=42, n_jobs=-1).fit(X, y)\n\"\"\"\nWeights x feature names:\n\"\"\"\neli5.explain_weights(log_reg, feature_names=feature_names, top=(30, 30))\n\"\"\"\nI think everything is pretty good though... \n\nThe `country` value with the biggest positive weight is `MY`, which is top-1 country in \"Proportion of fraudulent posts\" table (for the `country` feature, value of proportion - 0.571429). The country with the smallest count of fraudulent posts is `GR`:\n\"\"\"\noriginal_data[original_data.country == 'MY'].fraudulent.value_counts().sort_index()\noriginal_data[original_data.country == 'GR'].fraudulent.value_counts().sort_index()\n\"\"\"\nUsing info about weights we can figure out which values of a feature are associated with the biggest and the smallest proportions of fraudulent posts:\n\"\"\"\noriginal_data[original_data.industry == 'Accounting'].fraudulent.value_counts().sort_index()\noriginal_data[original_data.industry == 'Internet'].fraudulent.value_counts().sort_index()\n\"\"\"\nAnd we can also conclude that fraudulent post writers often start writing `London` (and many other city names) using the lowercase letter:\n\"\"\"\noriginal_data[original_data.city == 'london'].fraudulent.value_counts().sort_index()\noriginal_data[original_data.city == 'London'].fraudulent.value_counts().sort_index()\noriginal_data[original_data.city == 'chicago'].fraudulent.value_counts().sort_index()\noriginal_data[original_data.city == 'Chicago'].fraudulent.value_counts().sort_index()","meta":"{'source': 'AI4Code', 'id': '89ac821d05e187'}"}
{"id":"125307","text":"# 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, shutil\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\n# unziping the train zip and test zip file after copying them to the working folder \n# remember in kaggle input folder have been given only read only acess by the admin\n# hence we copy in the working folder and then complete our job\n!rm -rf .\/train .\/cats_and_dogs_small .\/train.zip .\/cats_and_dogs_small_2.h5 .\/cats_and_dogs_small_1.h5\n# making the copy of the test and train dir from the input dir since it is read-only\n!ls -lrt\n# !cp \/kaggle\/input\/dogs-vs-cats\/test1.zip \/kaggle\/working\n# !unzip \/kaggle\/working\/test1.zip \n!cp \/kaggle\/input\/dogs-vs-cats\/train.zip \/kaggle\/working\n!unzip \/kaggle\/working\/train.zip\n!cd \/kaggle\/working\n# use this block wisely\n# checking the contents of my working directory\n# use this wisely\nfor dirname, _, filenames in os.walk('\/kaggle\/working'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \n!ls -lrt\n\"\"\"\nFirst lets make the small dataset we will be working with. Because here our goal is to work with a smaller dataset  create a new\ndataset containing three subsets: a training set with 1,000 samples of each class, a validation set with 500 samples of each class, and a test set with 500 samples of each class. The original datset consists 25,000 images of dogs and cats (12,500 from each class) and is 543 MB (compressed). But since our goal is to use a smaller dataset we will resist the temptation of using it.\n\"\"\"\n!cd \/kaggle\/working\n!ls -lrt\n# first lets set the base paths and make the necessary directories for working out our problem\noriginal_dataset_dir = '\/kaggle\/working'\nbase_dir = '\/kaggle\/working\/cats_and_dogs_small'\nos.mkdir(base_dir)\ntrain_dir = os.path.join(base_dir,'train')\nos.mkdir(train_dir)\nvalidation_dir = os.path.join(base_dir, 'validation')\nos.mkdir(validation_dir)\ntest_dir = os.path.join(base_dir, 'test')\nos.mkdir(test_dir)\n\"\"\"\nCheck using the console the directories at this stage.\n\nDo a 'cd \/cats_and_dogs_small' and then run the next block.\n\"\"\"\n# gives you the content of the newly made folder\n!ls -lrt\n\n\"\"\"\nNow go to console opnce again and then do a 'cd ..'\n\"\"\"\n# now lets make the cats and dogs directories in them for housing the cats and the dogs images\ntrain_cats_dir = os.path.join(train_dir, 'cats')\nos.mkdir(train_cats_dir)\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\nos.mkdir(train_dogs_dir)\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nos.mkdir(validation_cats_dir)\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\nos.mkdir(validation_dogs_dir)\ntest_cats_dir = os.path.join(test_dir, 'cats')\nos.mkdir(test_cats_dir)\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\nos.mkdir(test_dogs_dir)\n\"\"\"\nNow go and check from the console if the directories are made. How ? \nIf you know unix you know how.\n\"\"\"\n# Now we will be copying the actual data from the base directory to the working directories\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(train_cats_dir, fname)\n    shutil.copyfile(src, dst)\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000, 1500)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(validation_cats_dir, fname)\n    shutil.copyfile(src, dst)\nfnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(test_cats_dir, fname)\n    shutil.copyfile(src, dst)\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(train_dogs_dir, fname)\n    shutil.copyfile(src, dst)\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000, 1500)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(validation_dogs_dir, fname)\n    shutil.copyfile(src, dst)\nfnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n    src = os.path.join(os.path.join(original_dataset_dir,'train'), fname)\n    dst = os.path.join(test_dogs_dir, fname)\n    shutil.copyfile(src, dst)\n\"\"\"\nNow lets check the length of the dat if they are being properly transferred.\n\"\"\"\n# checking the that data have been properly copied or not\nprint('total training cat images:', len(os.listdir(train_cats_dir)))\nprint('total training dog images:', len(os.listdir(train_dogs_dir)))\nprint('total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('total validation dog images:', len(os.listdir(validation_dogs_dir)))\nprint('total test cat images:', len(os.listdir(test_cats_dir)))\nprint('total test dog images:', len(os.listdir(test_dogs_dir)))\n# Now for ease of use I will do something\n# since the train folder contains too many images which we don't need I will delete it.\n!rm -rf .\/train\n!rm -rf .\/train.zip\n\"\"\"\nOkay Now we have the required dataset. Now I will start with the actual chapter. And before doing that I will actual save the version because saving the file commits the file in kaggle\/working. And if you don't their is good chance you can loose the files.\n\"\"\"\n\"\"\"\n# DOG vs CAT classifier using a ConvNet\n\nWe previously built a small ConvNet for MNIST dataset. We wil go ahead with a similar structure for our networkover here too only since we are dealing with a bigger images and a more complex problem , so we will make our network larger than last time by just adding another pair of Conv2D and MaxPooling2D layers. This serves both to augment the capacity of the network and to further reduce the size of the feature maps so they aren\u2019t overly large when you reach the Flatten layer. Here, because you start from inputs of size 150 \u00d7 150 (a somewhat arbitrary choice), you end up with feature maps of size 7 \u00d7 7 just before the Flatten layer. \n\nAlso Note The depth of the feature maps progressively increases in the network(from 32 to 128), whereas the size of the feature maps decreases (from 148 \u00d7 148 to 7 \u00d7 7). This is a pattern you\u2019ll see in almost all convnets.\n\nBecause you\u2019re attacking a binary-classification problem, you\u2019ll end the network with a single unit (a Dense layer of size 1) and a sigmoid activation. This unit will encode the probability that the network is looking at one class or the other.\n\nOkay now lets start with defining the network\n\"\"\"\n# defining the network\n# importing the layers and models sub- module from keras library\nfrom keras import layers,models\n\nmodel = models.Sequential() # using a sequentail class to make the model\n\n# defining the first layer which will be a Convulational layer with a feature map size 32 (filters) over a filter of 3 x 3 \n# and the input shape will be that of size (150,150,3) which encodes the length breadth and channels of the input image.\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(150, 150, 3)))\n# just like last time the second layer will be a maxpooling layer of size (2,2) which will agressively downsample \n# the output of the conv layer\nmodel.add(layers.MaxPooling2D((2, 2)))\n# we will be repeating the same thing for a few times with a increasing \n# feature map learning new features from existing features\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\n# downsampling again in the fourth layer\nmodel.add(layers.MaxPooling2D((2, 2)))\n# repeating same two steps\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n# and one final time\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Now lets define the classifier\n# and we start with a flatten layer transforming the output of the base from a 3D Tensor to 1D tensor\nmodel.add(layers.Flatten())\n# followed by a dense layer with 512 nodes \nmodel.add(layers.Dense(512, activation='relu'))\n# ending with sigmoid activated 1 noded classifing final layer\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\n# checking the model Summary Now\nmodel.summary()\n\n\"\"\"\nFor the compilation step, you\u2019ll go with the RMSprop optimizer, as usual. Because you ended the network with a single sigmoid unit, you\u2019ll use binary crossentropy as the loss .\n\"\"\"\n# compiling the network\n\nfrom keras import optimizers\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(lr=1e-4),\n              metrics=['acc'])\n\"\"\"\n# Data preprocessing\n\nAs you know by now, data should be formatted into appropriately preprocessed floatingpoint tensors before being fed into the network. Currently, the data sits on a drive as JPG files, so the steps for getting it into the network are roughly as follows:\n1.  Read the picture files.\n2.  Decode the JPEG content to RGB grids of pixels.\n3.  Convert these into floating-point tensors.\n4.  Rescale the pixel values (between 0 and 255) to the [0, 1] interval (as you know, neural networks prefer to deal with small input values).\n\n\nIt may seem a bit daunting, but fortunately Keras has utilities to take care of these steps automatically. Keras has a module with image-processing helper tools, located at keras.preprocessing.image. In particular, it contains the class ImageDataGenerator, which lets you quickly set up Python generators that can automatically turn image files on disk into batches of preprocessed tensors. This is what you\u2019ll use here. \n\"\"\"\n# Using ImageDataGenerator to read images from directories\n# if you don't know about generators go check it in the generators in python documentation\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1.\/255)\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n                                                    target_size=(150, 150),\n                                                    batch_size=20,\n                                                    class_mode='binary')\nvalidation_generator = test_datagen.flow_from_directory(validation_dir,\n                                                        target_size=(150, 150),\n                                                        batch_size=20,\n                                                        class_mode='binary')\n\n\"\"\"\nLet\u2019s look at the output of one of these generators: it yields batches of 150 \u00d7 150 RGB images (shape (20, 150, 150, 3)) and binary labels (shape (20,)). There are 20 samples in each batch (the batch size). Note that the generator yields these batches indefinitely: it loops endlessly over the images in the target folder. For this reason, you need to break the iteration loop at some point.\n\"\"\"\n# checking the shape of the output from this generators\nfor data_batch, labels_batch in train_generator:\n    print('data batch shape:', data_batch.shape)\n    print('labels batch shape:', labels_batch.shape)\n    break\n\"\"\"\nLet\u2019s fit the model to the data using the generator. You do so using the fit_generator method, the equivalent of fit for data generators like this one. It expects as its first argument a Python generator that will yield batches of inputs and targets indefinitely, like this one does. Because the data is being generated endlessly, the Keras model needs to know how many samples to draw from the generator before declaring an epoch over. This is the role of the steps_per_epoch argument: after having drawn steps_per_epoch batches from the generator\u2014that is, after having run for steps_per_epoch gradient descent steps\u2014the fitting process will go to the next epoch. \n\nJust remember it is nothing but the number of batches and batch size is the number of samples in the batches. The relationship actually goes as train_length \/\/ batch_size\n\nIn this case, batches are 20 samples, so it will take 100 batches until you see your target of 2,000 samples.\n\nWhen using fit_generator, you can pass a validation_data argument, much as with the fit method. It\u2019s important to note that this argument is allowed to be a data generator, but it could also be a tuple of Numpy arrays. If you pass a generator as validation_data, then this generator is expected to yield batches of validation data endlessly; thus you should also specify the validation_steps argument, which tells the process how many batches to draw from the validation generator for evaluation. \n\"\"\"\n# Fitting the model using a batch generator\nhistory = model.fit_generator(train_generator,\n                              steps_per_epoch=100,\n                              epochs=30,\n                              validation_data=validation_generator,\n                              validation_steps=50)\n# now we will be doing something we haven't done previously\n# its a simple practice but it is a good practice.\n# So lets save our model\nmodel.save('cats_and_dogs_small_1.h5')\n\"\"\"\nLet\u2019s plot the loss and accuracy of the model over the training and validation data during training.\n\"\"\"\n# Displaying curves of loss and accuracy during training\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\n\"\"\"\nThese plots are characteristic of overfitting. The training accuracy increases linearly over time, until it reaches nearly 100%, whereas the validation accuracy stalls at 70\u201372%. The validation loss reaches its minimum after only five epochs and then stalls, whereas the training loss keeps decreasing linearly until it reaches nearly 0. Because you have relatively few training samples (2,000), overfitting will be your number-one concern. You already know about a number of techniques that can help mitigate overfitting, such as dropout and weight decay (L2 regularization). We\u2019re now going to work with a new one, specific to computer vision and used almost universally when processing images with deep-learning models: data augmentation. \n\"\"\"\n\"\"\"\n# Using data augmentation\nOverfitting is caused by having too few samples to learn from, rendering you unable to train a model that can generalize to new data. Given infinite data, your mode would be exposed to every possible aspect of the data distribution at hand: you would\nnever overfit. Data augmentation takes the approach of generating more training data from existing training samples, by augmenting the samples via a number of random transformations that yield believable-looking images. The goal is that at training time, your model will never see the exact same picture twice. This helps expose the model to more aspects of the data and generalize better. In Keras, this can be done by configuring a number of random transformations to be performed on the images read by the ImageDataGenerator instance. Let\u2019s get started with an example. \n\"\"\"\ndatagen = ImageDataGenerator(rotation_range=40,\n                             width_shift_range=0.2,\n                             height_shift_range=0.2,\n                             shear_range=0.2,\n                             zoom_range=0.2,\n                             horizontal_flip=True,\n                             fill_mode='nearest')\n\"\"\"\nThese are just a few of the options available (for more, see the Keras documentation).\n\n* rotation_range is a value in degrees (0\u2013180), a range within which to randomly rotate pictures.\n* width_shift and height_shift are ranges (as a fraction of total width orheight) within which to randomly translate pictures vertically or horizontally.\n* shear_range is for randomly applying shearing transformations.\n* zoom_range is for randomly zooming inside pictures.\n* horizontal_flip is for randomly flipping half the images horizontally\u2014relevant when there are no assumptions of horizontal asymmetry (for example,real-world pictures).\n* fill_mode is the strategy used for filling in newly created pixels, which canappear after a rotation or a width\/height shift.\n\nLet\u2019s look at the augmented images\n\n\"\"\"\n# checking the augmented images by plotting them using matplotlib\n# after converting them into tensors and then augmenting them\nfrom keras.preprocessing import image\n\nfnames = [os.path.join(train_cats_dir, fname) for fname in os.listdir(train_cats_dir)]\n\nimg_path = fnames[20]\nimg = image.load_img(img_path, target_size=(150, 150))\n\nx = image.img_to_array(img)\nx = x.reshape((1,) + x.shape)\n\ni = 0\nfor batch in datagen.flow(x, batch_size=1):\n    plt.figure(i)\n    imgplot = plt.imshow(image.array_to_img(batch[0]))\n    i += 1\n    if i % 4 == 0:\n        break\nplt.show()\n\"\"\"\nI guess now we all understand what data augmentation stands for.\n\nNow if we train a new network using this data-augmentation configuration, the network will never see the same input twice. But the inputs it sees are still heavily intercorrelated, because they come from a small number of original images\u2014you can\u2019t produce new information, you can only remix existing information. As such, this may not be enough to completely get rid of overfitting. To further fight overfitting, you\u2019ll also add a Dropout layer to your model, right before the densely connected classifier.\n\nSo come on lets configure a new network again with data augmentation.\n\"\"\"\n# defining the new network\n\nmodel = models.Sequential() # calling the sequential class\n\n# making the convnet just as before\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu',\n                        input_shape=(150, 150, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n# model.add(layers.BatchNormalization())\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# defining the classifier same as before\nmodel.add(layers.Flatten())\n# adding the dropout layer as discussed \nmodel.add(layers.Dropout(0.5))\n# adding a batch normalization layer to normalize\n# the flactuations in the output analysis curve\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(lr=1e-4),\n              metrics=['acc'])\n\n# checking in the model summary\n\nmodel.summary()\n\"\"\"\nLet\u2019s train the network using data augmentation and dropout.\n\"\"\"\nimport math\nBATCH_SIZE=40\n\nTRAINING_SIZE = 2000\n\nVALIDATION_SIZE = 1000\n\n# We take the ceiling because we do not drop the remainder of the batch\ncompute_steps_per_epoch = lambda x: int(math.ceil(1. * x \/ BATCH_SIZE))\n\nsteps_per_epoch = compute_steps_per_epoch(TRAINING_SIZE)\nval_steps = compute_steps_per_epoch(VALIDATION_SIZE)\nprint(steps_per_epoch,val_steps)\n# creating the data augmentation generator classes\n\ntrain_datagen = ImageDataGenerator(rescale=1.\/255,\n                                   rotation_range=40,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True,)\n\n# note that we don't apply data augmentation to the test because that will be useless\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\n# and defining the training generator\n\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n                                                    target_size=(150, 150),\n                                                    batch_size=32,\n                                                    class_mode='binary')\n\n# and defining the validation generator\n\nvalidation_generator = test_datagen.flow_from_directory(validation_dir,\n                                                        target_size=(150, 150),\n                                                        batch_size=32,\n                                                        class_mode='binary')\n\n# training the new model\n\nhistory = model.fit_generator(train_generator,\n                              steps_per_epoch=50,\n                              epochs=100,\n                              validation_data=validation_generator,\n                              validation_steps=25)\n\"\"\"\nLet\u2019s save the model\n\"\"\"\n# saving the second model\n\nmodel.save('cats_and_dogs_small_2.h5')\n\"\"\"\nAnd let\u2019s plot the results again. \n\"\"\"\n# ploting the graphs \n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\"\"\"\nBy using regularization techniques even further, and by tuning the network\u2019s parameters (such as the number of filters per convolution layer, or the number of layers in the network), you may be able to get an even better accuracy, likely up to 86% or 87%. So keep trying, also try using batch normalization, it may prove good in order to reduce the fluctuations in the analysis curve.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e676e2b1d9f6c1'}"}
{"id":"104947","text":"\"\"\"\n# Titanic notebook\n\"\"\"\n\"\"\"\n### Imports\n\"\"\"\nimport pandas as pd\nimport numpy as np \nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n### Load data and create train and test data\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntest = pd.read_csv(\"..\/input\/titanic\/test.csv\")\ntrain.head()\nX = pd.get_dummies(train[[\"Sex\", \"Embarked\"]]).join(train[[\"Pclass\",\"SibSp\",\"Parch\",\"Age\"]].replace(np.nan, 50))\ny = train[\"Survived\"].to_numpy()\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nX_train.head()\n\"\"\"\n### Create the model\n\"\"\"\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Dense(50),\n    tf.keras.layers.Dense(50, activation=\"relu\"),\n    tf.keras.layers.Dense(1, activation=\"sigmoid\")\n])\n\"\"\"\n### Compile the model\n\"\"\"\nmodel.compile(\n    optimizer='nadam', \n    metrics=[tf.keras.metrics.BinaryAccuracy()], \n    loss=tf.keras.losses.BinaryCrossentropy()\n             )\n\"\"\"\n### Train the model\n\"\"\"\nearly_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=20)\nmodel_checkpoint_cb = tf.keras.callbacks.ModelCheckpoint(\"Titanic_model.h5\", save_best_only=True)\nmodel.fit(X_train, y_train, epochs=100, validation_split=0.2, callbacks=[early_stopping_cb, model_checkpoint_cb])\n\"\"\"\n### Evaluate the model\n\"\"\"\nmodel = tf.keras.models.load_model(\"Titanic_model.h5\")\nmodel.evaluate(X_test, y_test)\n\"\"\"\n### Preparation for the outing and make the predict\n\"\"\"\nX_final_test = pd.get_dummies(test[[\"Sex\", \"Embarked\"]]).join(test[[\"Pclass\",\"SibSp\",\"Parch\", \"Age\"]].replace(np.nan, 25)).to_numpy()\ny_final_test = np.round(model.predict(X_final_test))\nreturn_ = pd.DataFrame(test[\"PassengerId\"]).join(pd.DataFrame(data=y_final_test, columns=[\"Survived\"], dtype=np.int8)).to_csv(\"out.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': 'c0d18756ac4dd0'}"}
{"id":"138064","text":"\"\"\"\n# Simple Anomaly detection with H2O in Python\n\n### About dataset: \nThis data is a collection of metrics of various students a state of India. The goal was to gather as much information possible to determine if a given student would continue his\/her schooling or dropout. Future dropout rates and ways to minimize this, was the ultimate goal of the data collection.\n\nWe would want Autoencoding and Anomaly detction from H2O, to differentiate the data between students who dropped out and of those who did not. \n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport h2o\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler,RobustScaler,Normalizer\nfrom h2o.estimators.deeplearning import H2OAutoEncoderEstimator\nfrom pylab import rcParams\nrcParams['figure.figsize']=15,10\nstudent=pd.read_csv('..\/input\/studentDropIndia_20161215.csv', sep=',')\nstudent.isnull().any()\n\"\"\"\nAs shown above, *total_toilets *and *establishment_year* have Null values\n\"\"\"\n#student.dtypes\n#student[pd.isnull(student).any(axis=1)]\n\"\"\"\n## Basic exploratory data analysis\n\"\"\"\n\"\"\"\n### Fill NA with 0\n\"\"\"\nstudent=student.fillna(0)\n\"\"\"\n### Print correlation matrix\n\"\"\"\nf,ax = plt.subplots(figsize=(18, 18))\nsns.heatmap(student.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)\n\"\"\"\n### Students' Marks in Math is absolutely correlated with Science \n\"\"\"\nlabels = ['continue', 'drop']\nsizes = [student['continue_drop'].value_counts()[0],\n         student['continue_drop'].value_counts()[1]\n        ]\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)\nax1.axis('equal')\nplt.title('Continue vs Dropout Pie Chart', fontsize=20)\nplt.show()\n\"\"\"\n95.3% Students continued in school, whereas 4.7% dropped\n\"\"\"\n\"\"\"\n### List column\n\"\"\"\npredictors=list(range(0,15))\nprint(student.shape)\n\"\"\"\n### H2O cannot use columns with character datatype. Creating Dummy variables instead\n\"\"\"\ncols_to_transform = [ 'continue_drop','gender','caste','guardian','internet' ]\nstudent = pd.get_dummies( student,columns = cols_to_transform )\nstudent.head()\n\"\"\"\n### Dropping student_id column\n\"\"\"\nstudent = student.drop('student_id', 1)\n\"\"\"\n### Ensuring all the columns are of numeric datatype\n\"\"\"\nstudent.dtypes\n\"\"\"\n### Standardize input data\n\"\"\"\n# Copy the original dataset\nscaled_features = student.copy()\n\n# Extract column names to be standardized\ncol_names = ['mathematics_marks','english_marks','science_marks',\n             'science_teacher','languages_teacher','school_id',\n             'total_students','total_toilets','establishment_year'#,\n             #'gender_F','gender_M','caste_BC','caste_OC','caste_SC',\n             #'caste_ST','guardian_father','guardian_mixed','guardian_mother',\n            # 'guardian_other','internet_False','internet_True'\n            ]\n\n# Standardize the columns and re-assingn to original dataframe\nfeatures = scaled_features[col_names]\nscaler = RobustScaler().fit_transform(features.values)\nfeatures = pd.DataFrame(scaler, index=student.index, columns=col_names)\nscaled_features [col_names] = features\nscaled_features.head()\n\"\"\"\n### Split dataset - dropped students as 'test' and continued students as 'train'\n\"\"\"\n#student = student.astype(object)\n\ntrain=scaled_features.loc[scaled_features['continue_drop_continue'] == 1]\ntest=scaled_features.loc[scaled_features['continue_drop_drop'] == 1]\n\"\"\"\n## H2O Autoencoding and Anomaly detection\n\"\"\"\n# removing the continue_drop_continue and continue_drop_drop columns from training data\npredictors.remove(9)\npredictors.remove(10)\ntrain.columns[predictors]\n\"\"\"\n### Starting H2O cluster\n\"\"\"\nh2o.init(nthreads=-1, enable_assertions = False)\n\"\"\"\n### Convert panda dataframe to H2O dataframe\n\"\"\"\ntrain.hex=h2o.H2OFrame(train)\ntest.hex=h2o.H2OFrame(test)\n\"\"\"\n### Create AutoEncoder Model\n\"\"\"\nmodel=H2OAutoEncoderEstimator(activation=\"Tanh\",\n                              hidden=[120],\n                              ignore_const_cols=False,\n                              epochs=100\n                             )\n\"\"\"\n### Train the model with training dataset\n\"\"\"\nmodel.train(x=predictors,training_frame=train.hex)\n\"\"\"\n### Print the output in JSON format\n\"\"\"\nmodel._model_json['output']\n\"\"\"\n### Get anomalous values\n\"\"\"\ntest_rec_error=model.anomaly(test.hex)\ntrain_rec_error=model.anomaly(train.hex)\n\"\"\"\n### Convert output to dataframe\n\"\"\"\ntest_rec_error_df=test_rec_error.as_data_frame()\ntrain_rec_error_df=train_rec_error.as_data_frame()\nfinal = pd.concat([train_rec_error_df, train_rec_error_df])\n\"\"\"\n### Calculate top whisker value\n\"\"\"\nboxplotEdges=final.quantile(.75)\niqr = np.subtract(*np.percentile(final, [75, 25]))\ntop_whisker=boxplotEdges[0]+(1.5*iqr)\ntop_whisker\n\"\"\"\n### Add id column to dataframe \n\"\"\"\ntrain_rec_error_df['id']=train_rec_error_df.index\ntest_rec_error_df['id']=test_rec_error_df.index + 18200 #Count of train data\n\"\"\"\n### Scatter plot with top whisker\n\"\"\"\nplt.figure(figsize=[10,20])\nplt.scatter(train_rec_error_df['id'],train_rec_error_df['Reconstruction.MSE'],label='Continued Students',s=1)\nplt.axvline(x=18200,linewidth=1)\nplt.scatter(test_rec_error_df['id'],test_rec_error_df['Reconstruction.MSE'],label='Dropped Students',s=1)\nplt.axhline(y=top_whisker,linewidth=1, color='r')\nplt.legend()\n\"\"\"\nwithout continue_drop_continue and continue_drop_drop columns the method doesn't work :(\n\"\"\"\n\"\"\"\n## Output:\n\nWe have trained the model to detel the students who continued in school. From the graph you can see ***all the students who dropped*** have been correctly classfifed as **Outliers**\n\"\"\"\nh2o.cluster().shutdown()\n\"\"\"\n## Reference :\nhttps:\/\/charleshsliao.wordpress.com\/2017\/06\/26\/denoise-with-auto-encoder-of-h2o-in-python-for-mnist\/\nhttp:\/\/benalexkeen.com\/feature-scaling-with-scikit-learn\/\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fdc39a35c0bba5'}"}
{"id":"23149","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport os\nprint('-------------------------')\nprint('all files:')\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nprint('-------------------------')\n\"\"\"\n# Create a GT Teacher network\n\"\"\"\ninput_dim = 10\nnn_depth = 4\nnn_width = 4\noutput_dim = 1\n\nleaky_relu_alpha = 0.3\ninputs = keras.Input(shape=(None, input_dim), name='input')\n\nx = layers.Dense(nn_width, name='FC_1')(inputs)\nx = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_1')(x)\n\nfor k in range(nn_depth-1):\n    x = layers.Dense(nn_width, name='FC_%d' %(k+2))(x)\n    x = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_%d' %(k+2))(x)\n\noutputs = layers.Dense(output_dim, name='output')(x)\n\nmodel_name = 'FCN_%dx%d_GT_model' %(nn_depth, nn_width)\nGT_model = keras.Model(inputs=inputs, outputs=outputs, name=model_name)\nGT_model.summary()\n\nGT_model.compile(optimizer=\"adam\", loss=\"mse\")\n\"\"\"\n# create a generator that will create data based on teacher GT network\n\"\"\"\nclass UniformDataGenerator(keras.utils.Sequence):\n    def __init__(self, teacher_model, input_dim=10, num_batches_per_epoch=1, batch_size=64):\n        self.teacher_model = teacher_model\n        self.input_dim = input_dim\n        self.batch_size = batch_size\n        self.num_batches_per_epoch = num_batches_per_epoch\n\n    def __len__(self):\n        return self.num_batches_per_epoch\n\n    def __getitem__(self, idx):\n        batch_x = -1.0 + 2.0 * np.random.rand(self.batch_size, self.input_dim)\n        batch_y = self.teacher_model.predict(batch_x)\n        return batch_x, batch_y\n    \nnum_batches_per_epoch = 1\nbatch_size = 32\n\ntrain_datagen = UniformDataGenerator(GT_model, input_dim=input_dim, num_batches_per_epoch=num_batches_per_epoch, batch_size=batch_size)\nvalid_datagen = UniformDataGenerator(GT_model, input_dim=input_dim, num_batches_per_epoch=num_batches_per_epoch, batch_size=batch_size)\n\"\"\"\n# Test the generator\n\"\"\"\ntest_generator = False\n\nif test_generator:\n    batch_1 = train_datagen[0]\n    batch_2 = train_datagen[42]\n\n    print('batch 1 shapes: (X.shape = %s, y.shape = %s)' %(batch_1[0].shape, batch_1[1].shape))\n    #print('batch 1 X: \\n%s' %(batch_1[0]))\n    #print('batch 1 y: \\n%s' %(batch_1[1]))\n\n    print('X batch 1 (mean, std) = \\n (%s, \\n  %s)' %(batch_1[0].mean(axis=0), batch_1[0].std(axis=0)))\n    print('y batch 1 (mean, std) = \\n (%s, %s)' %(batch_1[1].mean(axis=0), batch_1[1].std(axis=0)))\n    \n    print('batch 2 shapes: (X.shape = %s, y.shape = %s)' %(batch_2[0].shape, batch_2[1].shape))\n    #print('batch 2 X: \\n%s' %(batch_2[0]))\n    #print('batch 2 y: \\n%s' %(batch_2[1]))\n    \n    print('X batch 2 (mean, std) = \\n (%s, \\n  %s)' %(batch_2[0].mean(axis=0), batch_2[0].std(axis=0)))\n    print('y batch 2 (mean, std) = \\n (%s, %s)' %(batch_2[1].mean(axis=0), batch_2[1].std(axis=0)))\n\n\"\"\"\n# Create a student network\n\"\"\"\nstudent_nn_depth = 1\nstudent_nn_width = 4\n\nleaky_relu_alpha = 0.3\ninputs = keras.Input(shape=(None, input_dim), name='input')\n\nx = layers.Dense(student_nn_width, name='FC_1')(inputs)\nx = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_1')(x)\n\nfor k in range(student_nn_depth-1):\n    x = layers.Dense(student_nn_width, name='FC_%d' %(k+2))(x)\n    x = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_%d' %(k+2))(x)\n\noutputs = layers.Dense(nn_width, name='output')(x)\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\nstudent_model = keras.Model(inputs=inputs, outputs=outputs, name=model_name)\nstudent_model.summary()\n\nstudent_model.compile(optimizer=\"adam\", loss=\"mse\")\n\"\"\"\n# fit the student network and plot learning curve\n\"\"\"\nnum_train_iterations = 1000\n\nhistory = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\ntrain_loss = history.history['loss']\nvalid_loss = history.history['val_loss']\nbatch_index = np.arange(len(train_loss))\n\nplt.figure(figsize=(20,8))\nplt.plot(batch_index, train_loss, color='k')\nplt.plot(batch_index, valid_loss, color='b')\nplt.xlabel('iteration', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(['train', 'valid'], fontsize=20)\n\"\"\"\n# Train many small student networks\n\"\"\"\ndef create_FCN(input_dim, output_dim, nn_depth, nn_width, model_name, leaky_relu_alpha=0.3):\n    \n    # input\n    inputs = keras.Input(shape=(None, input_dim), name='input')\n    \n    # first hiddent layer\n    x = layers.Dense(nn_width, name='FC_1')(inputs)\n    x = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_1')(x)\n    \n    # rest of hidden layers\n    for k in range(nn_depth-1):\n        x = layers.Dense(nn_width, name='FC_%d' %(k+2))(x)\n        x = layers.LeakyReLU(alpha=leaky_relu_alpha, name='LReLU_%d' %(k+2))(x)\n\n    # output\n    outputs = layers.Dense(output_dim, name='output')(x)\n\n    # assemble the model\n    FCN_model = keras.Model(inputs=inputs, outputs=outputs, name=model_name)\n    \n    return FCN_model\nstudent_nn_depth = 2\nstudent_nn_width = 2\n\nnum_random_inits = 20\nnum_train_iterations = 500\n\ntraining_results = {}\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n\"\"\"\n# Show all learning curves overlaid \n\"\"\"\n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\nylim_max = 1.1 * learning_curve_matrix.max()\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\n\nstudent_nn_depth = 2\nstudent_nn_width = 3\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\nstudent_nn_depth = 3\nstudent_nn_width = 2\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\n\"\"\"\n# train many \"correct size\" student networks\n\"\"\"\nstudent_nn_depth = 3\nstudent_nn_width = 3\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\n\nstudent_nn_depth = 3\nstudent_nn_width = 4\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\nstudent_nn_depth = 4\nstudent_nn_width = 3\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\nstudent_nn_depth = 4\nstudent_nn_width = 4\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\n\"\"\"\n# Train many large student networks\n\"\"\"\nstudent_nn_depth = 5\nstudent_nn_width = 5\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\nstudent_nn_depth = 6\nstudent_nn_width = 6\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);\nstudent_nn_depth = 8\nstudent_nn_width = 8\n\nmodel_name = 'FCN_%dx%d_student_model' %(student_nn_depth, student_nn_width)\ntraining_results[model_name] = []\n\nfor k in range(num_random_inits):\n    curr_model_name = '%s_%d' %(model_name, k+1)\n    print('training \"%s\"' %(curr_model_name))\n    \n    # create model\n    student_model = create_FCN(input_dim, output_dim, student_nn_depth, student_nn_width, curr_model_name)\n    #student_model.summary()\n    student_model.compile(optimizer=\"adam\", loss=\"mse\")\n    \n    # train model\n    history = student_model.fit(train_datagen, epochs=num_train_iterations, validation_data=valid_datagen, verbose=0)\n    \n    # store learning curves\n    curr_learning_curves = {}\n    curr_learning_curves['num_batches'] = num_batches_per_epoch * np.arange(num_train_iterations)\n    curr_learning_curves['num_samples'] = batch_size * curr_learning_curves['num_batches']\n    curr_learning_curves['train_loss']  = np.array(history.history['loss'])\n    curr_learning_curves['valid_loss']  = np.array(history.history['val_loss'])\n\n    training_results[model_name].append(curr_learning_curves)\n    \n    \n# collect all learning curves for the same model in the same matrix\nlearning_curve_matrix = np.zeros((len(training_results[model_name]), training_results[model_name][0]['valid_loss'].shape[0]))\nfor k, curr_learning_curves in enumerate(training_results[model_name]):\n    learning_curve_matrix[k, :] = curr_learning_curves['valid_loss']\n    \nnum_batches_vec = training_results[model_name][0]['num_batches']\nnum_samples_vec = training_results[model_name][0]['num_samples']\n\n# show all learning curves\nplt.figure(figsize=(15,25))\nplt.subplots_adjust(left=0.06, bottom=0.06, right=0.94, top=0.94, hspace=0.1, wspace=0.1)\nplt.suptitle(model_name, fontsize=24)\n\nplt.subplot(4,1,1)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\nplt.ylim(0,ylim_max)\n\nplt.subplot(4,1,2)\nplt.plot(num_batches_vec, learning_curve_matrix.T, color='b', alpha=0.6)\nplt.plot(num_batches_vec, learning_curve_matrix.mean(axis=0), color='k', label='average')\nplt.plot(num_batches_vec, learning_curve_matrix.max(axis=0), color='r', label='worst')\nplt.plot(num_batches_vec, learning_curve_matrix.min(axis=0), color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,3)\nplt.plot(num_batches_vec[:100], learning_curve_matrix[:,:100].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[:100], learning_curve_matrix.mean(axis=0)[:100], color='k', label='average')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.max(axis=0)[:100], color='r', label='worst')\nplt.plot(num_batches_vec[:100], learning_curve_matrix.min(axis=0)[:100], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20)\n\nplt.subplot(4,1,4)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix[:,-100:].T, color='b', alpha=0.6)\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.mean(axis=0)[-100:], color='k', label='average')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.max(axis=0)[-100:], color='r', label='worst')\nplt.plot(num_batches_vec[-100:], learning_curve_matrix.min(axis=0)[-100:], color='g', label='best')\nplt.xlabel('batch index', fontsize=20)\nplt.ylabel('MSE', fontsize=20)\nplt.legend(fontsize=20);","meta":"{'source': 'AI4Code', 'id': '2a8fff3f10119d'}"}
{"id":"27707","text":"# 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\ndata= pd.read_csv('\/kaggle\/input\/fraudulent-claim-on-cars-physical-damage\/training data\/training data.csv')\ndata.head()\ndata.isna().sum()\ndata.marital_status.dtypes\ndata.marital_status = data.marital_status.fillna(0.00)\ndata.isna().sum()\ndata.witness_present_ind = data.witness_present_ind.fillna(data.witness_present_ind.mean())\ndata.claim_est_payout.dtypes\ndata.claim_est_payout = data.claim_est_payout.fillna(data.claim_est_payout.mean())\ndata.age_of_vehicle=data.age_of_vehicle.fillna(data.age_of_vehicle.mean())\n\"\"\"\n**which gender has done  more fraud ?**\n\"\"\"\ndata[data.fraud== 1].groupby('gender').count()['fraud'].sort_values(ascending = False)\n\"\"\"\n**How many people with annual income greater than 40000 did fraud claims ?**\n\"\"\"\ndata.fraud.dtypes\ndata[(data.marital_status == 1.0 )&( data.annual_income > 40000 ) & (data.fraud==1)].count()[0]\n\"\"\"\n**which accident site have more fraud claims when orderd online from a female driver with age greater than 40 ?**\n\"\"\"\ndata[(data.channel== 'Online')&(data.gender == 'F')&(data.age_of_driver>40)& (data.fraud==1)].groupby('accident_site').count().iloc[:,0].sort_values(ascending = False)\ny =  data.fraud\n\ny.head()\ndata\ndata.iloc[:,10:-10]\ndata.dtypes\ndata.claim_date =  pd.to_datetime(data.claim_date)\ndata[['Month']] = pd.DataFrame(data.claim_date.dt.month)\ndata[['day']] = pd.DataFrame(data.claim_date.dt.day)\ndata[['year']] = pd.DataFrame(data.claim_date.dt.year)\ndata.drop(columns=[\"claim_date\"],inplace=True)\ndata.isna().sum()\ndata.columns\ndata.iloc[:,10:-10]\ndata.head()\nnom=[2,8,10,11,15,21]\nordi=[19]\nfrom sklearn.preprocessing import OneHotEncoder , OrdinalEncoder\nfrom sklearn.compose  import make_column_transformer\n\ntrans =  make_column_transformer((OneHotEncoder(sparse =False),nom),\n                                (OrdinalEncoder(),ordi),\n                                remainder='passthrough')\ntrans\nfrom sklearn.neighbors import KNeighborsClassifier as knn \n\nmodel =  knn(n_neighbors = 5)\n\nmodel\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn import set_config\n\nset_config(display = 'diagram')\n\npipe = make_pipeline(trans,model)\n\npipe\nx = data.drop(columns =['fraud'])\n\nx.head()\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.3)\npipe.fit(x_train,y_train)\npred= pipe.predict(x_test)\nfrom sklearn.metrics import accuracy_score\n\naccuracy_score(pred,y_test)*100","meta":"{'source': 'AI4Code', 'id': '32ffc4483aa224'}"}
{"id":"22227","text":"\"\"\"\n<img src=\"https:\/\/wallpapercave.com\/wp\/upmtCfm.jpg\" style=\"width:800px;height:400px;\">\n\"\"\"\n\"\"\"\n# Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n# Information About Data\n\"\"\"\npoke = pd.read_csv(\"\/kaggle\/input\/pokemon\/Pokemon.csv\")\npoke.head(7)\n# Show some statistics about dataset\npoke.describe()\npoke.info()\n# I search NaN values\npoke.isnull().any()\npoke.columns  # Shows that we have which columns\n# Correlation map\nplt.rcParams['figure.figsize']=(15,8)\nhm=sns.heatmap(poke[[ 'Name', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense',\n       'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary']].corr(), annot = True, linewidths=1, cmap='Blues')\nhm.set_title(label='Correlation Map', fontsize=20)\nhm;\n\"\"\"\n# Graphics\n\"\"\"\nsns.jointplot(x=\"Sp. Atk\", y=\"Speed\", data=poke);\npoke.Attack.plot(kind='hist',bins = 15, figsize=(5,5))\nplt.show()\nsns.boxplot(x=\"HP\", data=poke);\npoke['Generation'].value_counts() # It gives how many are there generation numbers\nthreshold = sum(poke.Attack)\/len(poke.Attack)\nprint(threshold)\npoke[\"attack_level\"] = [\"powerful\" if i > threshold else \"weakness\" for i in poke.Attack]\npoke.loc[:10,[\"attack_level\",\"Attack\"]]\nfig, axs = plt.subplots(2, 2, figsize = (12,12)) #plt.subplots() first two arguements are the number\n# of rows and then the number of columns. The [figsize =] adjusts the size of the final output of graphs.\n# See point and link 2 \n\nax1 = plt.subplot2grid((8,8), (0,0), rowspan=3, colspan=3) \nax2 = plt.subplot2grid((8,8), (4,0), rowspan=3, colspan=3)\nax3 = plt.subplot2grid((8,8), (0, 4), rowspan=3, colspan=3)\nax4 = plt.subplot2grid((8,8), (4, 4), rowspan=3, colspan=3)\n\n# ^Each one of the above ax commands positions each graph spot within a grid. \n# For a better understanding see point and link 4\n\n\nfig.tight_layout() # To understand how this works see point and link 3\n\nax1.set_title(\"Plot1: HP and Attack\", fontsize =18)\nax2.set_title(\"Plot2: HP and Attack\", fontsize =18)\nax3.set_title(\"Plot3: HP and Attack\", fontsize =18)\nax4.set_title(\"Plot4: HP and Attack\", fontsize =18)\n\n# ^The above code purely sets the title of each graph and the fontsize\n\n\n\n# Plot 1\nsns.regplot(x='HP', y='Attack', \n              data=poke, ax=ax1) #x_bins = 12, fit_reg = True, ci = 95, \n              #color = 'red', marker =\"^\", ax=ax1) \n# Notice the x and y are set columns of the poke dataset. The [ax =]\n# is added because we have subplots and Python needs to know where to put this graph.\n# But this graph has no customization, just the bare bones. \n\n\n# Plot 2 \nsns.regplot(x='HP', y='Attack', \n              data=poke, fit_reg = False, color = 'green', marker =\"^\", ax=ax2)\n# We're going to add some parameters. We'll add a [color =], [fit_reg =],\n# [marker =] command to our function. The [color =] command let's us control the color \n# of the graph and the points. The [fit_reg =] command allows use to turn on\/off the linear\n# regression and just see the points. The default is True, unless we change it to False.\n# The final addition is the [marker =] command, this changes the marker used on the graph to \n# mark the points.\n\n\n# Plot 3\nsns.regplot(x='HP', y='Attack', \n              data=poke, fit_reg = True, x_bins = 6, color = 'orange', ax=ax3)\n# We're going to add some parameters still. Now we're adding the [x_bins =] command, and changing\n# [fit_reg =] to True. The [x_bins =] commands seperates our data into bins, the number given is the number\n# of bins the data is sepperated into. The [x_bins =] command also gives a confidence interval\n# to the bins. This confidence interval is the verticle line running through the point. \n# The default is confidence interval is 95%, but that can be changed if needed. So in this plot\n# we have 6 points each with a confidence interval, and linear regression running through\n# our data. \n\n\n# Plot 4\nsns.regplot(x='HP', y='Attack', \n              data=poke, fit_reg = False, x_bins = 12, ci = 99, color = 'red', ax=ax4)\n# I like what we did with the last graph, so I'm going to add to that. But I don't like\n# the line running through the data, I want the graph to be red, I want more bins, and I \n# want the confidence on each point to be 99% percent instead of 95%. To do this I turned\n# [fit_reg =] to False, [color =] to 'red', [x_bins =] to 12, and introduced a new command, \n# the [ci =] command. This command sets the confidence interval of both the bins AND the line.\n# In this exampe we don't have a linear fit to the data, so the [ci =] will only effect the bins.\n\n\n\nplt.show()\n\"\"\"\nVisualize distribution of Attack variable with Seaborn distplot() function\nSeaborn distplot() function flexibly plots a univariate distribution of observations.\n\"\"\"\nf, ax = plt.subplots(figsize=(10,8))\nx = poke['Attack']\nax = sns.distplot(x, bins=10)\nplt.show()\nf, ax = plt.subplots(figsize=(8, 6))\nsns.stripplot(x=\"Sp. Def\", y=\"Defense\", data=poke)\nplt.show()\n\"\"\"\n**Some kind of Hexagon Chart**\n\"\"\"\nsns.jointplot(x='Defense', y='Speed', data=poke, color ='yellow', kind ='hex', \n              size = 8.0)\nplt.show()\n\"\"\"\n**Some kind of Pie Chart**\n\"\"\"\npoke['Type 1'].unique()\nfig = plt.figure(figsize=(15,15))\n\nfig.add_subplot(211)\npoke['Type 1'].value_counts().plot(kind='pie', \n                                       autopct='%1.1f%%',\n                                       pctdistance=1.0)\n\nfig.add_subplot(212)\npoke['Type 2'].value_counts().plot(kind='pie', \n                                       autopct='%1.1f%%',\n                                       pctdistance=1.0)\n\nplt.show()\n\"\"\"\n**Some kind of Violin Plot**\n\"\"\"\nf, ax = plt.subplots(figsize=(8, 6))\nsns.violinplot(x=poke[\"Sp. Def\"])\nplt.show()\n\"\"\"\n# WHAT WE DID \n\"\"\"\n\"\"\"\nBriefly, We defined our data. Data is examined by us.We did import the libraries we will use so that we checked which have columns.We reached some kind of statistical graphics and including information in that graph.We compared each feature and we analyzed them. \n\n\nTHANKS FOR YOUR REVIEW. HAVE A GOOD DAY\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '28e93a34f3b152'}"}
{"id":"131533","text":"\"\"\"\n# Background\n\"\"\"\n\"\"\"\n*The task is to predict which passangers survived the 1912 Titanic shipwreck given passanger information such as Age, Sex, Class etc.*\n\"\"\"\n\"\"\"\n# Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.ensemble import RandomForestClassifier\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\n# Data\n\"\"\"\n# Read the data\nX_train_full = pd.read_csv('..\/input\/titanic\/train.csv', index_col='PassengerId')\nX_test_full = pd.read_csv('..\/input\/titanic\/test.csv', index_col='PassengerId')\n\n# Number of rows and columns\nprint(X_train_full.shape)\nprint(X_test_full.shape)\n\n# First 5 entries\nX_train_full.head()\n\"\"\"\n**Check for missing values**\n\"\"\"\n# Count null values\nprint(X_train_full.isnull().sum())\nprint('')\nprint(X_test_full.isnull().sum())\n\"\"\"\n**Labels and features**\n\"\"\"\n# Labels\ny = X_train_full.Survived\n\n# Features\nX_train_full.drop(['Survived'], axis=1, inplace=True)\n\"\"\"\n# Feature engineering\n\"\"\"\n\"\"\"\n**Title feature**\n\"\"\"\n# Extract titles from 'Name' column\nX_train_full['Title']=0\nX_train_full['Title']=X_train_full.Name.str.extract('([A-Za-z]+)\\.')\n\n# Cross tabulation\npd.crosstab(X_train_full.Title,X_train_full.Sex).T\n# Raplace rare titles by 'Rare'\nX_train_full['Title'].replace(['Capt','Col','Countess','Don','Dr','Jonkheer','Lady','Major',\n                           'Master','Miss','Mlle','Mme','Mr','Mrs','Ms','Rev','Sir'],\n                           ['Rare','Rare','Rare','Rare','Rare','Rare','Rare',\n                            'Rare','Master','Miss','Rare','Rare','Mr','Mrs','Rare',\n                            'Rare','Rare'],inplace=True)\n\n# Median age in each group\nX_train_full.groupby('Title')['Age'].median()\n# Countplot\nsns.countplot(x=\"Title\",\n                   hue=\"Survived\", \n                   data=pd.concat([X_train_full,y],axis=1),\n                   palette = 'Blues_d')\n# Assign missing age values to be median within each group\nX_train_full.loc[(X_train_full.Age.isnull())&(X_train_full.Title=='Master'),'Age']=3.5\nX_train_full.loc[(X_train_full.Age.isnull())&(X_train_full.Title=='Miss'),'Age']=21\nX_train_full.loc[(X_train_full.Age.isnull())&(X_train_full.Title=='Mr'),'Age']=30\nX_train_full.loc[(X_train_full.Age.isnull())&(X_train_full.Title=='Mrs'),'Age']=34.5\nX_train_full.loc[(X_train_full.Age.isnull())&(X_train_full.Title=='Rare'),'Age']=44.5\n\n# Check there are not missing values\nX_train_full.Age.isnull().sum()\n\"\"\"\n**Repeat for test data**\n\"\"\"\n# Repeat feature engineering for test data\nX_test_full['Title']=0\nX_test_full['Title']=X_test_full.Name.str.extract('([A-Za-z]+)\\.') # extract titles\n\n# Raplace rare titles by 'Rare'\nX_test_full['Title'].replace(['Capt','Col','Countess','Don','Dr','Jonkheer','Lady','Major',\n                           'Master','Miss','Mlle','Mme','Mr','Mrs','Ms','Rev','Sir','Dona'],\n                           ['Rare','Rare','Rare','Rare','Rare','Rare','Rare',\n                            'Rare','Master','Miss','Rare','Rare','Mr','Mrs','Rare',\n                            'Rare','Rare','Rare'],inplace=True)\n\n# Assign missing age values to be median within each group\nX_test_full.loc[(X_test_full.Age.isnull())&(X_test_full.Title=='Master'),'Age']=3.5\nX_test_full.loc[(X_test_full.Age.isnull())&(X_test_full.Title=='Miss'),'Age']=21\nX_test_full.loc[(X_test_full.Age.isnull())&(X_test_full.Title=='Mr'),'Age']=30\nX_test_full.loc[(X_test_full.Age.isnull())&(X_test_full.Title=='Mrs'),'Age']=34.5\nX_test_full.loc[(X_test_full.Age.isnull())&(X_test_full.Title=='Rare'),'Age']=44.5\n\n# Check there are not missing values\nX_test_full.Age.isnull().sum()\n\"\"\"\n**HasCabin feature**\n\"\"\"\n# Identify passangers with a recorded Cabin\nX_train_full['HasCabin']=X_train_full['Cabin'].notnull()\n\n# Repeat for test data\nX_test_full['HasCabin']=X_test_full['Cabin'].notnull()\n# Countplot\nsns.countplot(x=\"HasCabin\",\n                   hue=\"Survived\", \n                   data=pd.concat([X_train_full,y],axis=1),\n                   palette = 'Blues_d')\n\"\"\"\n# Feature selection\n\"\"\"\n# Select categorical columns to include in model\ncategorical_cols = ['Pclass', 'Sex', 'Embarked', 'HasCabin'] # Including 'Title' makes model worse\n\n# Select numerical columns to include in model\nnumerical_cols = ['Age', 'Fare', 'SibSp', 'Parch']\n\n# Keep selected columns only\nmy_cols = categorical_cols + numerical_cols\nX_train = X_train_full[my_cols].copy()\nX_test = X_test_full[my_cols].copy()\n\"\"\"\n# Preprocessing data\n\"\"\"\n# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='median')\n\n# Preprocessing for categorical data\ncategorical_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))\n    ])\n\n# Bundle preprocessing for numerical and categorical data\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', numerical_transformer, numerical_cols),\n        ('cat', categorical_transformer, categorical_cols)\n    ])\n\n# Data preprocessing pipeline\nmy_pipeline = Pipeline(steps=[('preprocessor', preprocessor)])\n\n# Transform the data\nX_train = my_pipeline.fit_transform(X_train)\n\"\"\"\n# Grid Search\n\"\"\"\n# Parameters grid\ngrid = {'n_estimators': [100, 125, 150, 175, 200, 225, 250], \n        'max_depth': [4, 6, 8, 10, 12]}\n\n# Random Forest Classifier\nclf=RandomForestClassifier(random_state=0)\n\n# Grid Search with 4-fold cross validation\ngrid_model = GridSearchCV(clf,grid,cv=4)\n\n# Train classifier with optimal parameters\ngrid_model.fit(X_train,y)\n\"\"\"\n**Results from Grid Search**\n\"\"\"\nprint(\"\\n The best parameters across ALL searched params:\\n\",grid_model.best_params_)\nprint(\"\\n The best score across ALL searched params:\\n\",grid_model.best_score_)\n\"\"\"\n# Predictions\n\"\"\"\n# Preprocess test data and fit model\nX_test_preprocessed=my_pipeline.transform(X_test)\npreds_test = grid_model.predict(X_test_preprocessed)\n\n# Save predictions to file\noutput = pd.DataFrame({'PassengerId': X_test.index,\n                       'Survived': preds_test})\n\n# Check format\noutput.head()\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'f1f3a5a07edfee'}"}
{"id":"135818","text":"from urllib import parse\nQueryString = \"\uc548\ub155\ud558\uc138\uc694\"\n\"\"\"\n# Value Encoding (quote)\n\"\"\"\nencodedValue = parse.quote(QueryString)\nencodedValue\n\"\"\"\n# Value Decoding (unquote)\n\"\"\"\ndecodedValue = parse.unquote(encodedValue) \ndecodedValue","meta":"{'source': 'AI4Code', 'id': 'f9b0bd9e0db7e6'}"}
{"id":"92908","text":"\"\"\"\n# Titanic Dataset: Your model is already pretty good \n## ...and it's certainly better than the top 150 \"models\".\n\n\nSo you've just joined Kaggle and, whether through the Kaggle ML courses, an ML book or because its reputation precedes it, you've tried your hand at the famous Titanic dataset. Perhaps you've tried a few things and you've managed to increase your model's categorization accuracy score ever so slightly.\n\nMy first score was 0.75598 and after 12 new attempts, I managed to get 0.77990 (there was a 13th new attempt, didn't go too well...).\n\n#### Not particularly impressive right? \n\nAt the time of writing, there are about 155 Kaggle teams appearing in the public leaderboard with a perfect score of 1.00000 (notice the five 0s, these models must be at least 0.999995 accurate if there's any rounding going on). \n\nHow did they do it? There are a lot of novices at the top, novices just like you and me. Do they just have a knack, a gift for ML? Why are you wasting your time with this notebook when you could have a look at some of theirs? (OK, I'll answer that one right off the bat: These notebooks are mostly identical and none of them show you how to get a score of 1.00000 from the data on Kaggle)\n\n#### What if I told you your latest model, nay, your very first attempt at a model is\/was already pretty good and better than the top 150 or so \"models\". How could this be? How could I possibly know this?\n\nLet's look at a maritime disaster from a parallel dimension...\n\"\"\"\n\"\"\"\n## <center>-- The Tatinac disaster --<\/center>\n\nUp until the early morning hours of 15 April 1912, the RMS Titanic and RMS Tatinac differed in name only. The passengers on both ships were identical to each other in every way, shape or form...that is, until evacuation begun, then something utterly bizzare happened in the Tatinac universe...people formed orderly queues. As on the RMS Titanic, cries rang out \"Women and children first\" and on that basis, people queued. Unfortunetaly, when the last woman and child under the age of 15 got onto the lifeboats, there suddenly weren't any boat...and so all men sank with the ship, having humbly accepted their fate. \n\n    \u00af\\_(\u30c4)_\/\u00af\n\n#### Let us now take the Titanic dataset and transform it into the Tatinac dataset, including a survivor column in the test set.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\ntatinac_train = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntatinac_test = pd.read_csv(\"..\/input\/titanic\/test.csv\")\n\n#let's start from a blank slate, with no survival...how bleak...\ntatinac_train[\"Survived\"] = 0 #this changes the values in the pre-existing column \"Survived\" to 0.\ntatinac_test[\"Survived\"] = 0 #this adds a new column \"Survived\" to the test set.\n\n#To reiterate, in the Tatinac universe, all women and children (under 15) survive.\ntatinac_train.loc[(tatinac_train[\"Sex\"]==\"female\") | (tatinac_train[\"Age\"]<15),\"Survived\"] = 1 \ntatinac_test.loc[(tatinac_test[\"Sex\"]==\"female\") | (tatinac_test[\"Age\"]<15), \"Survived\"] = 1\n#There are few men for which age is not given, we will assume for now they were all 15 or older.\n\"\"\"\nThis is what the data for the Tatinac disaster looks like. Eyeballing it, the pattern quickly becomes fairly obvious.\n\"\"\"\n#This is what the data for the Tatinac disaster looks like.\ntatinac_train.head(20)\n\"\"\"\nIt will not come as a suprise to anyone that any model, even a simple one, that picks up on the all female and all under 15 pattern in the data will do exceptionally well. Armed with the gift of foresight, let's just use a simple decision tree.\n\n(As with the Titanic dataset, we do need to do a little preprocessing on the data. Don't worry if this next cell is unclear, just skip to the next cell. I have borrowed this section from Aurelien Geron's excellent 'Hands-On Machine Learning with Scikit-Learn, Keras and Tensorflow'. This is not vital to understand the point of this notebook)\n\"\"\"\n#preprocessing start...\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.pipeline import Pipeline, FeatureUnion\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n    def __init__(self, attribute_names):\n        self.attribute_names = attribute_names\n    def fit(self, X, y=None):\n        return self\n    def transform(self, X):\n        return X[self.attribute_names]\n\nnum_pipeline = Pipeline([\n    ('select', DataFrameSelector([\"Age\",\"Fare\"])),\n    ('imputer',SimpleImputer(strategy=\"median\")),\n])\n\ncat_pipeline = Pipeline([\n    ('select', DataFrameSelector([\"Pclass\",\"Sex\",\"SibSp\"])),\n    ('imputer',SimpleImputer(strategy=\"most_frequent\")),\n    ('onehot', OneHotEncoder(sparse='False')),\n])\n\npreprocess_pipeline = FeatureUnion(transformer_list=[\n        (\"num_pipeline\", num_pipeline),\n        (\"cat_pipeline\", cat_pipeline),\n    ])\n##...preprocessing end...phew, now back to the good stuff.\n\"\"\"\nNow we fit our preprocessed Tatinac dataset to a simple decision tree classifier.\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz \nimport graphviz ##we will want to visualize the tree we've created.\n\ntt = tatinac_train.copy(deep=True)\n\nX_train = preprocess_pipeline.fit_transform(tt)\ny_train = tatinac_train[\"Survived\"]\n\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train, y_train)\n\"\"\"\nLet's see how well our model did.\n\"\"\"\nfrom sklearn.metrics import accuracy_score\n\nX_test = preprocess_pipeline.fit_transform(tatinac_test.drop(\"Survived\", axis=1))\ny_test = tatinac_test[\"Survived\"]\ny_pred = dtc.predict(X_test)\n\nprint(\"categorization accuracy score:\",accuracy_score(y_pred,y_test))\n\n##have a look at your decision tree in your output folder...makes a lot sense doesn't it?\nvisual = graphviz.Source(export_graphviz(dtc,class_names=True))\nvisual.render(\"imageA\")\n\"\"\"\n#### So it IS possible to get an accuracy of 1.00000 after all!?\n\nWait a minute, even in the Tatinac universe reality is a little more complex. Remember we have men who's age is not given. Each of them could be on either side of 15. Let's revisit those few cases and asign them a random chance of survival. There's just a few of them, so it shouldn't change the logic of the training or test set considerably.\n\"\"\"\nimport random\n\n#Every man who's age is not known is randomly assigned a survival value (i.e. Some we assume to be under 15, others not so)\ntatinac_train.loc[(tatinac_train[\"Sex\"]==\"male\") & (tatinac_train[\"Age\"].isna()), \"Survived\"] = random.choice([0,1])\ntatinac_test.loc[(tatinac_test[\"Sex\"]==\"male\") & (tatinac_test[\"Age\"].isna()), \"Survived\"] = random.choice([0,1])\n#We repeat all the same steps as earlier, now that values have been updated.\nX_train = preprocess_pipeline.fit_transform(tatinac_train.drop(\"Survived\", axis=1))\ny_train = tatinac_train[\"Survived\"]\n\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train, y_train)\n\nX_test = preprocess_pipeline.fit_transform(tatinac_test.drop(\"Survived\", axis=1))\ny_test = tatinac_test[\"Survived\"]\ny_pred = dtc.predict(X_test)\n\nprint(\"categorization accuracy score:\", accuracy_score(y_pred,y_test))\n\n##The decision tree is very likely exactly the same. If not, it'll be at the very least functionally identical.\nvisual = graphviz.Source(export_graphviz(dtc,class_names=True))\nvisual.render(\"imageB\")\n\"\"\"\n#### Ouch, that took a turn...\n\nJust by integrating age uncertainty the categorization accuracy score falls to a value of around 0.85 (note: occasionally one gets lucky and gets 0.95. Respectable, but a farcry from 1). The model arrived at was the same (how could it be any different?) and yet because of age uncertainty, we can't do much better than this.\n\nOk, so maybe you're not entirely convinced yet. Maybe the models that get 1.00000 are doing something clever and age is just not the right metric to focus on due to the various NaN entries. Alright, let's make age perfectly predictable again and focus on sex.\n\"\"\"\n#Reverting the survival value of men of unknown age back to 0.\ntatinac_train.loc[(tatinac_train[\"Sex\"]==\"male\") & (tatinac_train[\"Age\"].isna()), \"Survived\"] = 0\ntatinac_test.loc[(tatinac_test[\"Sex\"]==\"male\") & (tatinac_test[\"Age\"].isna()), \"Survived\"] = 0\n\"\"\"\nLet's now create an example dataset relating events nearly as improbable as our original Tatinac disaster. Let us say, that the test set contains one counterexample: one adult man survived. He was next in the queue and got on right before the cutoff. The first entry in our test dataset is a man, he is our lone male survivor.\n\"\"\"\ntatinac_test.loc[0,\"Survived\"]=1 ##the one lucky survivor\ntatinac_test.head()\n#We repeat all the same steps as earlier, now that values have been updated. \nX_train = preprocess_pipeline.fit_transform(tatinac_train.drop(\"Survived\", axis=1))\ny_train = tatinac_train[\"Survived\"]\n\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train, y_train)\n\nX_test = preprocess_pipeline.fit_transform(tatinac_test.drop(\"Survived\", axis=1))\ny_test = tatinac_test[\"Survived\"]\ny_pred = dtc.predict(X_test)\n\nprint(\"categorization accuracy score:\",accuracy_score(y_pred,y_test))\n\n##The decision tree is STILL functionally identical!\nvisual = graphviz.Source(export_graphviz(dtc,class_names=True))\nvisual.render(\"imageC\")\n\"\"\"\n#### What?! 0.99761?! \n\nThat certainly doesn't round to 1 if we're considering five decimals! Not even close. \n\nNotice that all it took was just ONE exception in the test set. One single exception. If that's all it takes not to get a clean 1.00000 prediction for this ever-so-slightly modified Tatinac dataset, imagine how much lower maximum categorization accuracy is going to be for the Titanic dataset! Let's add a few more exceptions to get a sense how quickly an otherwise perfect prediction loses in accuracy.\n\"\"\"\ntatinac_test.loc[1,\"Survived\"]=0 ##the second entry is a woman. Sadly she now falls overboard.\ntatinac_test.loc[2,\"Survived\"]=1 ##the third entry is a man. Floats on top a door.\ntatinac_test.loc[3,\"Survived\"]=1 ##There's enough space on the door for two people.\ntatinac_test.loc[4,\"Survived\"]=0 ##But not for the original three.\n\ntatinac_test.head()\n##We haven't changed the training dataset this time so we can just power ahead with the test data preprocessing and prediction.\nX_test = preprocess_pipeline.fit_transform(tatinac_test.drop(\"Survived\", axis=1))\ny_test = tatinac_test[\"Survived\"]\ny_pred = dtc.predict(X_test)\n\nprint(\"categorization accuracy score:\",accuracy_score(y_pred,y_test))\n\n##You get the gist...\nvisual = graphviz.Source(export_graphviz(dtc,class_names=True))\nvisual.render(\"imageD\")\n\"\"\"\n#### Only 5 miserable examples running counter to the Tatinac's disaster's orderly evacuation and the prediction is already down to 0.988?!\n\nNow you're truly wondering how anyone can possibly get 1.00000 on the Titanic dataset.\n\nPerhaps they somehow got a hold of the survivor column for the test set (hidden on Kaggle for very very good reason!) and in an act of excusable silliness, ran the test set through the fitting phase of their model instead of the training set, thus perhaps overfitting? Oh dear!\n\nThat's too forgiving an explanation and it doesn't even work. Let's give that a try (obviously, never do this in any other context)\n\"\"\"\ndtc = DecisionTreeClassifier()\ndtc.fit(X_test, y_test) #training with the test set. Bad, terrible, no good practice!\n\nX_test = preprocess_pipeline.fit_transform(tatinac_test.drop(\"Survived\", axis=1))\ny_test = tatinac_test[\"Survived\"]\ny_pred = dtc.predict(X_test)\n\nprint(\"categorization accuracy score:\",accuracy_score(y_pred,y_test))\n\n##Yes, even with the test set, it all just stays the same!\nvisual = graphviz.Source(export_graphviz(dtc,class_names=True))\nvisual.render(\"imageE\")\n\"\"\"\n#### We still don't get 1.00000! \n\nThis is because, even though we are plugging in the test set to predict the test set, we are asking the model to derive some simple rules, not copy the data exactly, so our simple decision tree will continue learning that women and boys under age 15, strongly tended to survive, while the men didn't. We could push our model to overfit by increasing the number of nodes in our decision tree, but that won't even get us to 1.00000 (again, this is not advice anyway, this is the opposite of what you'd normally do, you want a model to generalize well which is incidentally another reason 1.0000 is never a desirable score, the only other scenario where you get 1.00000 is one where you're data is too simple to necessitate ML)\n\n#### So what IS happening? \n\nWell, in case it isn't obvious yet, each and every single one of these 150 or so teams simply submitted the test with the correct survivor column attached, that they have somehow found online (I didn't look for it and neither should you!). Given that the sinking of the RMS Titanic is something that actually happened, one should be able to find this information out and turn it into the test set.\n\nThe problem here isn't just the cheating, nothing is gained from simply submitting the answers. You cannot even replicate this dishonest strategy for any other dataset (so it isn't even 'clever' cheating). Those who do it arrest their potential growth as MLers on Kaggle. What a shame!\n\n#### Think about your prediction again. Whether you've got 0.75 or higher, you're doing great. \n\nKeep it up, try a few things. Go learn some more ML tricks and try again. A seemingly small increment, is a leap in your knowledge of ML. Quickly move on to other datasets. Maybe come back to the Titanic dataset from time to time. Whatever you do, DO NOT get disheartened by the fact you're not getting anything near 1.00000 or 0.98804, these are illusory results.\n\nIf you look for the holy grail of models in the various 'winning' dataset notebooks, you'll quickly notice a lot of notebooks look suspiciously the same (because they are) and they mostly cover a lot of data visualization (which is nice, but that's probably not why you were looking at them in the first place, right?).\n\n#### So what is the highest legitimate categorical accuracy score?\n\nIt is near impossible to tell where the dividing line between legitimate and fake is, but some notebooks below 0.85 look legit (this is a wild guess based on some circumstantial evidence, it could be a little higher). Don't worry too much about it. Try to improve your score, then move on to other datasets. <bold>You're doing great don't get discouraged!<\/bold>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'aa80165499903d'}"}
{"id":"25616","text":"\"\"\"\nThis notebook contains process of data exploration and visualization that helps me to make inference on deciding which of the 2 ridesharing company is better for consumer point of view.\n\n**Objective**: To compare the fare between Lyft and Uber\n\nTime frame: 26th Nov 2018 to 19th Dec 2018 (24 days)\n\nLocation: Boston, MA\n\"\"\"\nimport pandas as pd\nGLstats = pd.read_csv('..\/input\/uber-lyft-cab-prices\/cab_rides.csv')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\nsns.set_style('whitegrid')\nf, axes = plt.subplots (2,1, figsize=(4,6))\n\n#histogram\nx=['Uber','Lyft']\ny = [GLstats.cab_type[(GLstats.cab_type)=='Uber'].count(),\\\n     GLstats.cab_type[(GLstats.cab_type)=='Lyft'].count()]\n\nvis1= sns.barplot(x,y,palette='Accent',ax=axes[0])\nvis1.set(xlabel='Cab Type',ylabel='Number of cab')\n\n\nfor p in vis1.patches:\n             vis1.annotate(\"%.f\" % p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=11, color='gray', xytext=(0, 20),\n                 textcoords='offset points')\n\n\n#Pie\nNcab_type = [GLstats.cab_type[(GLstats.cab_type)=='Uber'].count(),\\\n             GLstats.cab_type[(GLstats.cab_type)=='Lyft'].count()]\n     \ncab_type = ['Uber','Lyft']\n\nplt.pie(Ncab_type, labels=cab_type, startangle=90, autopct='%.1f%%')\n\n\nplt.show()\n\"\"\"\nUber gets a more rides compared to Lyft in this particular dataset\n\"\"\"\nTaxi=GLstats[GLstats.name == 'Taxi'].index\nGLstats.drop(Taxi , inplace=True)\nvis1=sns.scatterplot(x=GLstats.distance,y=GLstats.price,data=GLstats, hue=GLstats.cab_type, hue_order=cab_type,alpha=0.3, legend='full')\n\"\"\"\nBefore showing a general price vs distance chart, drop 'Taxi' from Uber cabs as they use a different fare structure (in the dataset Taxi fare is always 0 USD)\nBased on the chart above, it can be observed that Lyft has a lower minimum fare compared to Uber, at the same time Lyft has higher maximum fare. Also, Uber travel distances are generally higher than Lyft.\n\"\"\"\n\"\"\"\nWe also know there is a 'surge multiplier' factor in Lyft, where the fare is multiplied by a certain rate during rush hours.\n\nWhen prices surge , Uber does not show a multiplier and instead quotes only the higher price up front. Lyft marks up its Prime Time pricing with a percentage: If the rate is 50 percent, a fare that would normally be USD10 costs USD15.\n[[source](https:\/\/www.nytimes.com\/2019\/04\/17\/technology\/personaltech\/uber-vs-lyft.html)]\nThis will be verified with the visualization below:\n\"\"\"\nvis1=sns.scatterplot(x=GLstats.distance,y=GLstats.surge_multiplier,data=GLstats, hue=GLstats.cab_type, hue_order=cab_type)\n\"\"\"\nLet's make a quick investigation on the surge trend for Lyft:\n\"\"\"\nLyftOnly=GLstats[GLstats.cab_type == 'Lyft']\nA=LyftOnly.groupby(['name','surge_multiplier'],as_index=False).count()\nA\n\"\"\"\nExcept \"Shared\" type Lyft, most of the Lyft cbs shows a similar number of \"surge multiplier\" occurence. Chart below will show a rough idea on the occurence rate.\n\"\"\"\nA[:][22:29]\nB=A[22:29]['id']\nSurge = B\n     \nSurge_Factor = ['1.0x','1.25x','1.5x','1.75x','2.0x','2.5x','3.0x']\n\nvis1= sns.barplot(x=Surge_Factor,y=B)\nvis1.set(xlabel='Surge Multiplier',ylabel='Number of times')\n\ntotal=sum(B\/100)\nfor p in vis1.patches:\n     height = p.get_height()\n     vis1.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.4f}%'.format(height\/total),\n            ha=\"center\") \n\nplt.show()\n\"\"\"\nAbout 92% of the time, surge does not happen. about 4% 1.25x surge multiplier happens to the fare, 2% for 1.5x surge multiplier and so on. In this case I will multiply the surge multiplier to the initial estimated fare, to show the actual price for Lyft rides.\n\"\"\"\nGLstats2=GLstats.copy()\n\nfor i in (list(GLstats2.index.values)):\n    if GLstats2.cab_type[i]=='Uber': \n        pass\n    elif (GLstats2.cab_type[i]=='Lyft') & (GLstats2.surge_multiplier[i]!=1.0):\n        GLstats2.price[i]=(GLstats.price[i] * GLstats2.surge_multiplier[i])\ng, axes = plt.subplots (1,2, figsize=(16,6))\n\nvis1=sns.scatterplot(x=GLstats.distance,y=GLstats.price,data=GLstats, hue=GLstats.cab_type, hue_order=cab_type,alpha=0.3, ax=axes[0])\n\nvis2=sns.scatterplot(x=GLstats2.distance,y=GLstats2.price,data=GLstats2, hue=GLstats2.cab_type, hue_order=cab_type, alpha=0.3,ax=axes[1])\n\nvis1.set(xlim=(-0.5, 8.5))\nvis1.set(ylim=(-5, 200))\nvis2.set(xlim=(-0.5, 8.5))\nvis2.set(ylim=(-5, 200))\nvis1.set(xlabel='Distance in Miles',ylabel='Price in USD')\nvis1.set(xlabel='Distance in Miles',ylabel='Price in USD')\n\n\naxes[0].set_title('Estimated Fare')\naxes[1].set_title('Actual Fare charged')\n\nplt.ioff()\n\"\"\"\nAfter multiplying with the surge multiplier, Lyft fare shows higher range of fare. Does this means Uber has a better fare rate? The answer is No. I'll prove it in the coming visualizations.\nFirst, let's break down into the types of rides both companies have. As we know there are normal rides, carpool rides, SUV rides, luxury rides etc....each has a different rate.\n\"\"\"\nh, axes = plt.subplots (1,2, figsize=(12,4))\n\nUx=GLstats.name[GLstats.cab_type=='Uber'].unique()\nLx=GLstats.name[GLstats.cab_type=='Lyft'].unique()\nUy = GLstats.name[GLstats.name=='UberXL'].count(),GLstats.name[GLstats.name=='Black'].count(),\\\n     GLstats.name[GLstats.name=='UberX'].count(),GLstats.name[GLstats.name=='WAV'].count(),\\\n     GLstats.name[GLstats.name=='Black SUV'].count(),GLstats.name[GLstats.name=='UberPool'].count()\n\nLy=GLstats.name[GLstats.name=='Shared'].count(),GLstats.name[GLstats.name=='Lux'].count(),\\\n     GLstats.name[GLstats.name=='Lyft'].count(),GLstats.name[GLstats.name=='Lux Black XL'].count(),\\\n     GLstats.name[GLstats.name=='Lyft XL'].count(),GLstats.name[GLstats.name=='Lux Black'].count()\n\nvis1= sns.barplot(Ux,Uy,palette='Accent',ax=axes[0])\nvis2= sns.barplot(Lx,Ly,palette='Accent',ax=axes[1])\n\naxes[0].set_title('Number of Uber Rides')\naxes[1].set_title('Number of Lyft Rides')\nplt.ioff()\n\"\"\"\nThe dataset has equal number of ride types for both company, with Uber having roughly 5000 more rides than Lyft for each category. Next we will look at the fare for each category.\n\"\"\"\nLyftOnly2=GLstats2[GLstats2.cab_type == 'Lyft']\nUberOnly=GLstats2[GLstats2.cab_type == 'Uber']\n\ng, axes = plt.subplots (1,2, figsize=(16,6))\n\nvis1=sns.scatterplot(x=LyftOnly2.distance,y=LyftOnly2.price,data=LyftOnly2, hue=LyftOnly.name, ax=axes[1])\nvis2=sns.scatterplot(x=UberOnly.distance,y=UberOnly.price,data=UberOnly, hue=UberOnly.name, ax=axes[0])\n\nvis1.set(xlim=(-0.5, 8.5))\nvis1.set(ylim=(-5, 200))\nvis2.set(xlim=(-0.5, 8.5))\nvis2.set(ylim=(-5, 200))\nvis1.set(xlabel='Distance in Miles',ylabel='Price in USD')\nvis2.set(xlabel='Distance in Miles',ylabel='Price in USD')\n\n\naxes[1].set_title('Lift Fare vs Distance by car type')\naxes[0].set_title('Uber Fare vs Distance by car type')\nplt.ioff()\n\"\"\"\nUnfortunately the chart looks a little messy and it is difficult to compare, so let's further break down the types of rides.\nBased on some online results, we can say the following for both competiting company rides:\n\n**Lyft vs Uber**\n* Lyft ordinary ride fare is comparable to UberX\n* Lux Black XL is comparable to Black SUV\n* Lyft XL is comparable to UberXL\n* Shared is comparable to UberPool\n\nAt the same time, we will join the intersection of Lyft and Uber rides that shares the same time frame (timestamp) and source & destination. This way it is a fair comparison as we are comparing the exact time\/weather\/traffic condition from both company.\n\n\"\"\"\nJoin_TDS=UberOnly.merge(LyftOnly2, how='inner',on=['time_stamp','destination','source'])\nJoin_TDS = Join_TDS.drop(columns=[\"id_x\",\"product_id_x\",\"id_y\",\"product_id_y\",\"surge_multiplier_x\",\"surge_multiplier_y\"])\n\"\"\"\nFurther drop other rides that are hard to compare:\nWAV= wheelchar accessible (Uber) that is not specified in Lyft\nUber Black which I am not sure to compare with Lyft Lux or Lyft Lux Black\n\"\"\"\nA=Join_TDS[Join_TDS.name_x == 'WAV'].index\nJoin_TDS.drop(A , inplace=True)\nA=Join_TDS[Join_TDS.name_x == 'Black'].index\nJoin_TDS.drop(A , inplace=True)\nA=Join_TDS[Join_TDS.name_y == 'Lux'].index                \nJoin_TDS.drop(A , inplace=True)\nA=Join_TDS[Join_TDS.name_y == 'Lux Black'].index                \nJoin_TDS.drop(A , inplace=True)\n\ng, axes = plt.subplots (1,2, figsize=(16,6))\n\nU1=['UberX','Black SUV','UberXL','UberPool']\nL1=['Lyft','Lux Black XL','Lyft XL','Shared']\n\nvis1=sns.scatterplot(x=Join_TDS.distance_x,y=Join_TDS.price_x,data=Join_TDS,hue='name_x',hue_order=U1,ax=axes[0])\nvis2=sns.scatterplot(x=Join_TDS.distance_y,y=Join_TDS.price_y,data=Join_TDS,hue='name_y',hue_order=L1,ax=axes[1])\n\nvis1.set(xlim=(-0.2, 7))\nvis1.set(ylim=(-5, 200))\nvis2.set(xlim=(-0.2, 7))\nvis2.set(ylim=(-5, 200))\nvis1.set(xlabel='Distance in Miles',ylabel='Price in USD')\nvis2.set(xlabel='Distance in Miles',ylabel='Price in USD')\nvis1.set_title('Grab Ride')\nvis2.set_title('Lyft Ride')\n\nplt.ioff()\n\"\"\"\nIt looks like our first observation still stands, Lyft has a bigger range of fare rate, at the same time lower minumum charge. Let's zoom both chart to the majority data located, which is price below 50 USD\n\"\"\"\nsns.set_style('whitegrid')\ng, axes = plt.subplots (2,2, figsize=(14,10))\n\n\nU1=['UberX','Black SUV','UberXL','UberPool']\nL1=['Lyft','Lux Black XL','Lyft XL','Shared']\n\nvis1=sns.scatterplot(x=Join_TDS.distance_x,y=Join_TDS.price_x,data=Join_TDS,hue='name_x',hue_order=U1,ax=axes[1,0])\nvis2=sns.scatterplot(x=Join_TDS.distance_y,y=Join_TDS.price_y,data=Join_TDS,hue='name_y',hue_order=L1,ax=axes[1,1])\n\nvis1.set(xlim=(-0.2, 7))\nvis1.set(ylim=(-5, 50))\nvis2.set(xlim=(-0.2, 7))\nvis2.set(ylim=(-5, 50))\nvis1.set(xlabel='Distance in Miles',ylabel='Price in USD')\nvis2.set(xlabel='Distance in Miles',ylabel='Price in USD')\n\n\n\nUx=['UberX', 'Black SUV', 'UberXL', 'UberPool']\nLx=['Lyft', 'Lux Black XL', 'Lyft XL', 'Shared']\nUy = Join_TDS.name_x[Join_TDS.name_x=='UberX'].count(),Join_TDS.name_x[Join_TDS.name_x=='Black SUV'].count(),\\\n     Join_TDS.name_x[Join_TDS.name_x=='UberXL'].count(),Join_TDS.name_x[Join_TDS.name_x=='UberPool'].count()\n\nLy=Join_TDS.name_y[Join_TDS.name_y=='Lyft'].count(),Join_TDS.name_y[Join_TDS.name_y=='Lux Black XL'].count(),\\\n     Join_TDS.name_y[Join_TDS.name_y=='Lyft XL'].count(),Join_TDS.name_y[Join_TDS.name_y=='Shared'].count()\n\nvis3= sns.barplot(Ux,Uy,ax=axes[0,0])\n\nvis4= sns.barplot(Lx,Ly,ax=axes[0,1])\n\n\nfor p in vis3.patches:\n             vis3.annotate(\"%.2f\" % p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=10, color='gray', xytext=(0, 6),\n                 textcoords='offset points')\nfor p in vis4.patches:\n             vis4.annotate(\"%.2f\" % p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=10, color='gray', xytext=(0, 6),\n                 textcoords='offset points')\n        \nplt.ioff()\n\n\naxes[0,0].set_title('Number of Uber Rides')\naxes[0,1].set_title('Number of Lyft Rides')\nplt.ioff()\n\n\nplt.legend(bbox_to_anchor=(0.8,0.25))\n\nplt.ioff()\n\"\"\"\nFor shared ride (\"Shared\" for Lyft and \"Uberpool' for Uber), Lyft has a cheaper rate compared to Uber.\nFor other rides, both sides looks similar pretty similar and it is difficult to tell which one is cheaper yet.\nSo, a boxplot of price per mile travelled vs ride type is plotted:\n\"\"\"\nlist(Join_TDS.columns.values)\nA = Join_TDS[['time_stamp',\n 'destination','source',\n'distance_x', 'cab_type_x', 'price_x', 'name_x']]\n\nA.columns=['time_stamp',\n 'destination','source',\n'distance', 'cab_type', 'price', 'name']\n\nB = Join_TDS[['time_stamp',\n 'destination','source',\n'distance_y', 'cab_type_y', 'price_y', 'name_y']]\n\nB.columns=['time_stamp',\n 'destination','source',\n'distance', 'cab_type', 'price', 'name']\nFPM=A.append(B)\nFPM['fare_per_mile']= round(FPM.price\/FPM.distance,2)\nO1=['UberX', 'Black SUV', 'UberXL', 'UberPool', 'Lyft', 'Lux Black XL',\n        'Lyft XL','Shared']\n\nimport matplotlib as mpl\nsns.set_style('darkgrid')\nplt.figure(figsize=(10, 8))\n\nvis1 = sns.boxplot( data = FPM, x = 'name', y = 'fare_per_mile', \\\n                   showfliers=False, hue='cab_type',order=O1,palette='Set3')\n\n\nvis1.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())\nvis1.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())\n\nvis1.set_title('Fare($) Per Mile')\nvis1.set(xlabel='Cab Type',ylabel='Fare ($) Per Mile')\n\nvis1.grid(b=True, which='major', color='w', linewidth=1)\nvis1.grid(b=True, which='minor', color='w', linewidth=0.5)\nplt.ioff()\n\n\"\"\"\nLyft has a better rate for carpool category.\nLyft XL has a slightly lower fare per mile than UberXL.\nUber Black SUV shows lower rate than Lyft Black XL.\nLyft ordinary ride and UberX has similar rates, in which Lyft is better up till 3rd quarter of sample.\n\nNext let's look at the time factor that might affect the availability and fare for the rides\n\"\"\"\nimport datetime\n#convert 13digit time stamp to datetime format\nGLstats2['time']= pd.to_datetime(GLstats2['time_stamp'], unit='ms')\n#extract hours only\nGLstats2['hour']= GLstats2['time'].dt.hour\nGLstats2['fare_per_mile']= round(GLstats2.price\/GLstats2.distance,2)\n\n#drop unwanted rows that is not comparable\nA=GLstats2[GLstats2.name == 'WAV'].index\nGLstats2.drop(A , inplace=True)\nA=GLstats2[GLstats2.name == 'Black'].index\nGLstats2.drop(A , inplace=True)\nA=GLstats2[GLstats2.name == 'Lux'].index                \nGLstats2.drop(A , inplace=True)\nA=GLstats2[GLstats2.name == 'Lux Black'].index                \nGLstats2.drop(A , inplace=True)\nLyftOnly=GLstats2[GLstats2.cab_type == 'Lyft']\nUberOnly=GLstats2[GLstats2.cab_type == 'Uber']\n\nvis1 = sns.distplot(LyftOnly.hour, bins=24,kde=False, color='blue')\nvis2 = sns.distplot(UberOnly.hour, bins=24,kde=False,color='yellow')\n\nplt.xticks(range(0, 25,2))\nplt.legend(title='cab type', loc='upper left', labels=['Lyft','Uber'],bbox_to_anchor=(1,1))\nvis1.set(ylabel='Number of rides')\n\n\nplt.ioff()\n\"\"\"\nFrom the distribution we can say that the trend of rides are similar for both company, with Uber having more rides than Lyft.\n\"\"\"\nvis1 = sns.lineplot(x=GLstats2.hour, y=GLstats2.fare_per_mile,\\\n                    data=GLstats2, hue=GLstats2.name,err_style=None)\n\nplt.xticks(range(0, 25,2))\nvis1.set(xlabel='Hour of day',ylabel='Fare ($) per mile')\nplt.legend(title='cab type', loc='upper left', labels=['Lyft Shared', 'Lyft','Lyft Lux Black XL','Lyft XL',\\\n                                                     'UberXL','UberX','Uber Black SUV','UberPool'],bbox_to_anchor=(1,1))\n\nplt.ioff()\n\"\"\"\nThis hourly chart gives us the following info:\n\n*From Top*\n* **First two pair lines:** The average fare for Lyft Lux Black XL has a less deviation with respect to hour of the day compared to Uber Black SUV\n* **2nd line pair:** The average fare per mile for UberXL is more expensive than Lyft XL rides\n* **3rd line pair:** Lyft ordinary ride beats UberX ordinary ride in terms of average fare\n* **Final pair:** Lyft Shared ride which average about 3USD is cheaper than UberPool that averages above 5USD.\n\n**So far, I infer Lyft rides has a better rate compared to Uber for this particular dataset.**\n\nFuture work: \nDay of the week factor\nTraffic condition of the given area are not compared exactly, only time is common\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2f2ada63b8ad0b'}"}
{"id":"111080","text":"\"\"\"\n## Cyber Data Analysis\n\nThe data is a dummy data. Data generated using website. \n\nlink: https:\/\/www.generatedata.com\/\n\"\"\"\n# for some basic operations\nimport numpy as np \nimport pandas as pd\n\n# for visualizations\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# for interactive visualizations\nimport plotly.offline as py\nfrom plotly.offline import init_notebook_mode, iplot\nimport plotly.graph_objs as go\n\n\nimport seaborn as sns\nimport plotly.express as px\n\"\"\"\n## EDA\n\n* Since the data is generated. There is no error in the data regarding its values. We don't need to clean the data too much.\n\"\"\"\ncyber_csv = pd.read_csv(\"\/kaggle\/input\/cybercrime\/cyber.csv\")\n#Top 5 Datas\ncyber_csv.head()\n# Correlations between Data\n\nplt.rcParams['figure.figsize'] = (15, 12)\nsns.heatmap(cyber_csv.corr(), cmap='gray', annot=True)\nplt.show()\n\"\"\"\nThe features are not correlated to each other . Its good. WHY?\nThe conversation will clear this.\nlink: https:\/\/datascience.stackexchange.com\/questions\/24452\/in-supervised-learning-why-is-it-bad-to-have-correlated-features\n\"\"\"\n\"\"\"\n# BoxPlot Charts\n\"\"\"\nimport plotly.graph_objects as go\n# Set notebook mode to work in offline\nimport plotly.offline as pyo\npyo.init_notebook_mode()\n\nfig = go.Figure()\nfig.add_trace(go.Box(y = cyber_csv['Personal'], name='Personal'))\nfig.add_trace(go.Box(y = cyber_csv['Social'], name='Social'))\nfig.add_trace(go.Box(y = cyber_csv['Technical'], name='Technical'))\nfig.add_trace(go.Box(y = cyber_csv['Motivation'], name='Motivation'))\n\nfig.show()\n\"\"\"\nGained Informations:\n\n1. The median value for each feature is different\n2. The max, min values are the same for all parameters\n3. More peoples seems to be more technical, motivated and deep personal traits\n4. They are less social\n\n# Pair Plot\n\"\"\"\nsns.pairplot(cyber_csv)\n\"\"\"\n* Since the features are in the same range of from 0-10. There is no need to do normalization\n\"\"\"\n\"\"\"\n# Using PCA to reduce the dimension of data\n\"\"\"\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\n\npca.fit(cyber_csv)\nvalues = pca.transform(cyber_csv)\n\nx = values[0:,:1]\ny = values[0:,1:2]\n\"\"\"\n# UnSupervised Learning\n\"\"\"\ndef plot_scatter(x1,x2):\n    plt.scatter(x1, x2)\n\n    plt.xlabel('component 1')\n    plt.ylabel('component 2')\n    \n    plt.show()\nplt.rcParams[\"figure.figsize\"] = [10, 5]\nplot_scatter(x,y)\nX = values\nfrom sklearn.cluster import KMeans\n\n# Fnding the right number of K values\n\nsum_squred_distance = []\nK = range(1,15)\nfor k in K:\n    kmeans = KMeans(n_clusters=k, random_state=0).fit(X)\n    sum_squred_distance.append(kmeans.inertia_)\nplt.plot(K, sum_squred_distance, 'bx-')\nplt.xlabel('k')\nplt.ylabel('Sum_of_squared_distances')\nplt.title('Elbow Method For Optimal k')\nplt.show()\n\"\"\"\n* In the plot above the elbow is at k=3 indicating the optimal k for this dataset is 3\n\"\"\"\nkmeans = KMeans(n_clusters=3, random_state=0).fit(X)\n\"\"\"\n# Visualizing KMeans clustering\n\"\"\"\nlabels_ = kmeans.labels_\ncolors = {}\n\ncolors[0] = 'b'\ncolors[1] = 'r'\ncolors[2] = 'm'\n\n#Build the color vaectore for each data frame point\ncvec = [colors[label] for label in labels_]\n\nplt.xlabel('Component 1')\nplt.ylabel('Component 2')\n\n#for construction of the legend of the plot\nr = plt.scatter(x,y, color='r');\nb = plt.scatter(x,y, color='b');\nm = plt.scatter(x,y, color='m');\n\n#Plotting DATE in X-axis and no_of_activities in Y-axis\nplt.figure(figsize =(10, 5))\nplt.scatter(x,y,c = cvec)\n\n#Building the legend\nplt.legend((r,b,m),('label 0','label 1', 'label 2'))\nplt.xticks(rotation=90)\n\nplt.xlabel('Component 1')\nplt.ylabel('Component 2')\n    \nplt.show()\n\"\"\"\n* Now me have three set of people\n* Lets add the second cluster to suspect\n\"\"\"\nX_df = pd.DataFrame()\nX_df['component1'] = values[0:,:1].tolist()\nX_df['component2'] = values[0:,1:2].tolist()\n\nX_df['Target'] = 0\n\nfor v in X_df[kmeans.labels_==1].index:\n    X_df['Target'][v] = 1\n\"\"\"\n# Perform Supervised Learning in Labeled Data\n\"\"\"\nX_df.head()\n# Making Feature and target\n\nX = values\nY = X_df['Target']\n\nfrom sklearn.model_selection import train_test_split\n\n#make the x for train and test (also called validation data) \nxtrain,xtest,ytrain,ytest = train_test_split(X,Y,train_size=0.80,random_state=42)\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\nclf = LogisticRegression()\nclf.fit(xtrain, ytrain)\n\ny_predict = clf.predict(xtest)\n\naccuracy_score(ytest, y_predict)\n\"\"\"\n# More Analysis Coming\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'cc1e4fda5ab098'}"}
{"id":"102271","text":"\"\"\"\n[![Open In Colab](https:\/\/colab.research.google.com\/assets\/colab-badge.svg)](https:\/\/colab.research.google.com\/drive\/1RN93yQ0kqAwlgAQZLVs9fAezk_5DryAd?usp=sharing)\n\"\"\"\n\"\"\"\n# Set Up\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom pandas_profiling import ProfileReport\nfrom numpy import percentile\nfrom scipy import stats\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import StackingRegressor\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.linear_model import RidgeCV\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\"\"\"\n# Data Analysis and Preprocessing\n\"\"\"\n# pandas couldn't identify the type of the following two columns\nrecs_df = pd.read_csv(\"..\/input\/residential-energy-consumption-survey\/recs2009_public.csv\",dtype={\"NOCRCASH\":\"object\",\"NKRGALNC\":\"object\"})\n\"\"\"\nWe take advantage of pandas profiling to get an overview of the data and a quick analysis. Due to the large size of the report, I chose minimal report without correlation calculations. I commented the following lines, since the report was too large for Google Colab to save.\n\"\"\"\n# profile = ProfileReport(recs_df, title=\"RECS Dataset Profile\",minimal=True)\n# profile.to_notebook_iframe()\n# profile.to_file(\"recs_report.html\")\n\"\"\"\nSome important insights from a glance at the report:\n\n* over 900 columns, high dimensional data --> curse-of-dimensionality a great concern\n\n* many columns with almost constant values (zeros for example) --> redundant columns\n\n* no missing values reported (missing values are most likely already imputetd by the center who did the survey)\n\n* many columns with skewed distribution, must keep an eye on these when doing regression\n\"\"\"\n\"\"\"\n## Target Variable Analysis\n\"\"\"\nrecs_df['KWH'].hist()\n\"\"\"\nwe can see that the distribution is a bit skewed. Since our end goal is to predict this value, and it's continuous, we need a regression model. However, based on linear regression assumptions, we ideally want our target variable and predictors be normally distributed. \n\"\"\"\n\"\"\"\n## Correlations\n\"\"\"\n\"\"\"\nWe will have a look at the correlation among variables in our dataset.\n\"\"\"\ndef get_high_corr_df(df,positive_threshold=0.4):\n  corr = df.corr().stack().reset_index().drop_duplicates()\n  corr.columns = ['FEATURE_1', 'FEATURE_2', 'CORRELATION']\n  high_corr = corr[((corr['FEATURE_1'] != corr['FEATURE_2'] ) & ((corr['CORRELATION'] >= positive_threshold) | (corr['CORRELATION'] <= positive_threshold*-1)))]\n  return high_corr\nhigh_corr = get_high_corr_df(recs_df)\nhigh_corr[((high_corr['FEATURE_1'] == 'KWH'))]\n\"\"\"\nThere is a perfect correlation of 1 between KWH and BTUEL. If we have a look at the codebook provided on the website, we'll see that they are representing the same thing (total electricity site usage), but in different units (one in kw\/h and the other one in thousand BTU). Furthermore, there are columns that show categories of KWH such as electricity usage for air-conditioning. I personally think, we should drop these columns for training a prediction model, otherwise they would serve a data-leak or cheating for the model. They are part of our target variable.\n\"\"\"\nKWH_cheat_columns = [c for c in recs_df.columns if ((\"KWH\" in c and len(c)>3) or \"BTUEL\" in c) ]\nrecs_df.drop(columns=KWH_cheat_columns,inplace=True)\n\"\"\"\ndrop id, unique value\n\"\"\"\nrecs_df.drop(columns=[\"DOEID\"],inplace=True)\n\"\"\"\ndrop the imputation flag columns, extra information that (I personally think) is irrelevant to prediction. Moreover, mostly zeros and also no noticable correlation found with \"KWH\" \n\"\"\"\nimputation_columns = [c for c in recs_df.columns if c.startswith(\"Z\")]\nrecs_df.drop(columns=imputation_columns,inplace=True)\n\"\"\"\nthere are some columns that almost have a constant value, such as DOLKEROTH with mostly zeros, or AGEHHMEMCAT11 with mostly -2.\n\nFirst, we'll find these columns.\n\"\"\"\ncolumns_with_constant_values = []\nfor c in recs_df.columns:\n  value_frequencies = recs_df[c].value_counts(normalize=True)\n  if value_frequencies.max()>=0.85:\n    columns_with_constant_values.append(c)\nprint(columns_with_constant_values)\nprint(len(columns_with_constant_values))\n\"\"\"\nThen, see if any of them have a meaningful correlation with our target variable.\n\"\"\"\nhigh_corr[((high_corr['FEATURE_1'] == 'KWH') & (high_corr['FEATURE_2'].isin(columns_with_constant_values)))]\n\"\"\"\nWe'll drop the redundant columns.\n\"\"\"\nrecs_df.drop(columns=columns_with_constant_values,inplace=True)\n\"\"\"\nnow, we look for highly correlated (close to 1 or -1) pairs. If such pairs exist perhaps we could get rid of one of the variables, and reduce number of columns for building a model.\n\"\"\"\nhigh_corr = get_high_corr_df(recs_df) #calculate again, after deleting so many columns\nredundant_sets=[]\nfor i,row in high_corr[(high_corr['CORRELATION']>=0.90)|(high_corr['CORRELATION']<=-0.90)].iterrows():\n  f1 = row['FEATURE_1']\n  f2 = row['FEATURE_2']\n  fset = {f1,f2}\n  belongs_to_sets = []\n  for j in range(len(redundant_sets)):\n    if len(redundant_sets[j].intersection(fset))!=0:  \n      belongs_to_sets.append(j)\n\n  if len(belongs_to_sets)==0:\n    redundant_sets.append(fset)\n  elif len(belongs_to_sets)==1:\n    redundant_sets[belongs_to_sets[0]].update(fset)\n  else:\n    sets_to_merge = [redundant_sets[j] for j in belongs_to_sets]\n    for sm in sets_to_merge:\n      redundant_sets.remove(sm)\n      fset.update(sm)\n    redundant_sets.append(fset)\n  \nfor s in redundant_sets:\n  print(s)\n\"\"\"\nwe can see from the names of each group that the values are highly related, and we can just use one of them as the representor of that group. for example, for the {'PELHOTWA', 'ELWATER'} pair, most people chose \"not applicable\" for the first one, and 0 (not electricity used for heating water) for the second one. So when they don't use it, they don't pay for it. the same information. we can just use one.\n\"\"\"\nfor s in redundant_sets:\n  s.pop()\n  recs_df.drop(columns=list(s),inplace=True)\nsns.heatmap(recs_df.corr())\n\"\"\"\nEven after removing redundant columns, there is still noticable correlation between some columns in data. When using linear regression, we ideally want the predictors to have no correlation with each other.\n\"\"\"\n\"\"\"\n## Noise and Outliers\n\"\"\"\n\"\"\"\nLinear Regression is sensitive to outliers and we must take care of them before building a prediction model.\n\nStrategy for dealing with outliers: If the number of outliers found for a column make up less than 1% of the rows, remove the rows, else replace the outliers with mean.\n\nInitially, the threshold was higher (I tried a range of values from 20% to 1%). I noticed that even with a low threshold as much as 2%, we would still lose about 25% of the rows after outlier removal. So in order not to lose too much data, I used the afromentioned strategy. I think it's not ideal, but a quick and general solution for now.\n\"\"\"\nrows = set()\nfor c,column in recs_df.iteritems():\n  if column.dtype=='object':\n    continue\n\n  q25, q75 = percentile(column, 25), percentile(column, 75)\n  iqr = q75 - q25\n  cut_off = iqr * 1.5\n  lower, upper = q25 - cut_off, q75 + cut_off\n  outliers = recs_df[(recs_df[c] < lower) | (recs_df[c] > upper)] \n  if len(outliers)>0:\n    percentage = outliers.shape[0]\/recs_df.shape[0]*100\n    print('%s #outliers: %d %d%%' % (c,outliers.shape[0],percentage))\n    if percentage<1:\n      recs_df.drop(index=outliers.index,inplace=True)\n\n    else:\n      recs_df[c].where(((recs_df[c] < lower) | (recs_df[c] > upper)),recs_df[c].mean())\nrecs_df.shape[0]\n\"\"\"\n## Skewness\n\"\"\"\n\"\"\"\nPandas profiling revealed that distribution of a lot of columns are higly skewed. Therefore the normality assumption for linear regression will be violated. We will detect skewed columns and try to transform into a normal distribution witn log transformation. The rule of thumb is if the skewness is not within [-1,1] range that the distribution is skewed. But in the profiling report, I noticed almost no column has a perfect normal distribuion and most have skewness around 2-3. So I set the threshold a bit higher in order not to transform too many columns and completely transform the data.\n\"\"\"\nfor c in recs_df.columns:\n  if recs_df[c].dtype=='object':\n    continue\n  skew = recs_df[c].skew()\n  if skew>2 or skew<-2:\n    print('%s skew before transforamtion: %f' % (c,skew))\n    recs_df[c] = np.log(recs_df[c] + 1 - min(recs_df[c]))\n    print('%s skew after log transforamtion: %f' % (c,recs_df[c].skew()))\n\"\"\"\n## Scaling\n\"\"\"\n\"\"\"\nThe unit of the values in the columns are not uniform. Some came from multi-answer questions so only have a categorical value. Some have continues values with large numbers. \n\nHowever, we will not use nueral networks or linear models sensitive to unscaled data.So we don't have to worry about this much for now. (Also, linear regression makes no assumption about the scale of the variables).\n\n\n\"\"\"\n\"\"\"\n## Train Test Sets\n\"\"\"\nX = recs_df.loc[:,recs_df.columns!='KWH'].copy()\ny = recs_df['KWH'].copy()\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n\"\"\"\n## Dealing with Categorical Values\n\"\"\"\n\"\"\"\nFor dealing with categorical values, we'll use label encoding. We will fit the encoder only on training set so we don't leak any information to test set and help the models cheat!\n\"\"\"\ncategorical_columns = [c for c in recs_df.columns if recs_df[c].dtype=='object']\nfor c in categorical_columns:\n  print(c)\n  encoder = LabelEncoder()\n  encoder.fit(X_train[c].values)\n  X_train[c] = encoder.transform(X_train[c])\n  X_test[c] = encoder.transform(X_test[c])\n\"\"\"\n# Prediction \n\"\"\"\n\"\"\"\nWe'll first try two separate regression models to predict KWH. Then we'll see if we can improve the prediction by stacking the two and building an ensemble model. \n\"\"\"\nfrom sklearn.linear_model import LinearRegression\n\nestimators = [('lgbm', GradientBoostingRegressor(random_state=42,max_depth=5)),\n              ('lr', LinearRegression()),\n              ('rc', RidgeCV())]\n\nstack = StackingRegressor(estimators=estimators[:-1],final_estimator=estimators[-1][1])\nprint(\"Individual resutls:\")\nfor estimator in estimators:\n  print(\"model: %s, score: %f\" %(estimator[0],estimator[1].fit(X_train, y_train).score(X_test, y_test)))\n  \nprint(\"################\\nEnsemble result\")\nstack.fit(X_train, y_train).score(X_test, y_test)","meta":"{'source': 'AI4Code', 'id': 'bbf76cb6ae499b'}"}
{"id":"95956","text":"\"\"\"\n# \uc791\uc5c5\ud6151 \uc720\ud615 \uc608\uc81c \ud480\uc774 \n\"\"\"\n\"\"\"\n### mrcars \ub370\uc774\ud130\uc14b\uc758 qsec \uceec\ub7fc\uc744 \ucd5c\uc18c\ucd5c\ub300\ucc99\ub3c4(Min-Max Scale)\ub85c \ubcc0\ud658\ud55c \ud6c4 0.5\ubcf4\ub2e4 \ud070 \uac12\uc744 \uac00\uc9c0\ub294 \ub808\ucf54\ub4dc \uc218\ub97c \uad6c\ud558\uc2dc\uc624.\n\"\"\"\n\"\"\"\n### DataUrl = https:\/\/raw.githubusercontent.com\/Datamanim\/dataq\/main\/mtcars.csv\n\"\"\"\nimport pandas as pd\nDataUrl = 'https:\/\/raw.githubusercontent.com\/Datamanim\/dataq\/main\/mtcars.csv'\ndf = pd.read_csv(DataUrl)\ndf\ndf['qsec']\nfrom sklearn.preprocessing import MinMaxScaler\n'''\nExamples\n |  --------\n |  >>> from sklearn.preprocessing import MinMaxScaler\n |  >>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]\n |  >>> scaler = MinMaxScaler()\n |  >>> print(scaler.fit(data))\n |  MinMaxScaler()\n |  >>> print(scaler.data_max_)\n |  [ 1. 18.]\n |  >>> print(scaler.transform(data))\n |  [[0.   0.  ]\n |   [0.25 0.25]\n |   [0.5  0.5 ]\n |   [1.   1.  ]]\n |  >>> print(scaler.transform([[2, 2]]))\n |  [[1.5 0. ]]\n '''\ndata = df['qsec'].values.reshape(-1,1)\ndata\nscaler = MinMaxScaler()\nscaler.fit(data)\ny = scaler.transform(data)\ny\nprint(y>0.5)\nprint((y>0.5).sum())\n\"\"\"\n### mrcars \ub370\uc774\ud130\uc14b\uc758 qsec \uceec\ub7fc\uc744 \ucd5c\uc18c\ucd5c\ub300\ucc99\ub3c4(Min-Max Scale)\ub85c \ubcc0\ud658\ud55c \ud6c4 0.5\ubcf4\ub2e4 \ud070 \uac12\uc744 \uac00\uc9c0\ub294 \ub808\ucf54\ub4dc \uc218\ub294 9\uac1c\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b0309e49cca52c'}"}
{"id":"38974","text":"\"\"\"\n# Introduction\n## Data\n* The input data comprises of files within the folders with class labels as their name.\n* The textual data are emails written from one journalist to another or to their source, regarding a story.\n* Emails can be seen labelled under multiple classes which would mislead the model.\n\n# Methodology\n* To clean our data and obtain some meaningful insights, we first need to make sure our data is properly labelled and stored\n* To do so:\n    1. Read the text from each file and while doing so, make sure we are not reading duplicate data.\n    2. Load the textual data into DataFrame for easier analysis.\n    3. Clean the raw text by:\n        * Removing special characters, punctuations, pronouns, stopwords.\n        * Tokeizing each data point, i.e segmenting text into sentences and further into words.\n        * Normalize the text by converting it into lower case.\n        * Extract the lemma for each word. Ex: Lemma(swimming) -> swim.\n\"\"\"\n#------------------------------------------Libraries---------------------------------------------------------------#\n####################################################################################################################\n#-------------------------------------Boiler Plate Imports---------------------------------------------------------#\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n#---------------------------------------Text Processing------------------------------------------------------------#\nimport regex\nfrom wordcloud import WordCloud\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import WordPunctTokenizer\nfrom string import punctuation\nfrom nltk.stem import WordNetLemmatizer\n#####################################################################################################################\n\"\"\"\n## Read Data from the '.txt' files\n\"\"\"\nnames = []\nbase = '\/kaggle\/input\/topic-modelling-on-emails\/Data\/'\nwith os.scandir(base) as entries:\n    for entry in entries:\n        if(entry.is_file() == False):\n            names.append(entry.name)\nnames\nnames.sort()\nfiles = {}\nunique = []\nfor name in names:\n    path = base + name+'\/'\n    x = []\n    with os.scandir(path) as entries:\n        for entry in entries:\n            if(entry.is_file()):\n                x.append(entry.name)\n    files[name] = x\n    files[name].sort()\nfor k, v in files.items():\n    print(k, len(v))\n\"\"\"\n* We now know how many files are labelled under each class. Our job now is to remove the data points that are labelled under other classes. Ex: 14147.txt is labelled under 'Crime', 'Entertainment' and 'Science', so we will be removing the entry from 'Entertainment' and 'Science'.\n* The risk here is that we might have removed the entry from a correctly labelled class. Ex: 14147.txt may be labelled as 'Science' initially and was repeated in other classes, by removing it from 'Science' we are mislabelling the data as 'Crime'.\n* But 'Science' already contains the most no. of entries, making it easier for us to train the model for that particular class. Hence, our approach doesn't affect the analysis.\n\"\"\"\nnames\nfor i in range(len(names)):\n    x = files[names[i]]\n    for j in x:\n        for k in range(i+1, len(names)):\n            key = names[k]\n            if j in files[key]:\n                files[key].remove(j)\nfor k, v in files.items():\n    print(k, len(v))\n\"\"\"\n* From the above result it is clearly implied that the class 'Entertainment' had no data unique to its class. \n* By not considering it, we are also eliminating any variance that can be caused by the duplicate data.\n\"\"\"\ndata = {}\ni = 0\n\nfor genre in files.keys() :\n    texts = files[genre]\n    for text in texts:\n        if text in files[genre]:\n            path = base + genre + '\/' + text\n            with open(path, \"r\", encoding = \"latin1\") as file:\n                data[i] = file.readlines()\n                i = i+1\n            data[i-1] = [\" \".join(data[i-1]), genre] \n\ndata = pd.DataFrame(data).T\nprint(data.shape)\ndata.columns = ['Text', 'Class']\ndata.head()\ndata.info()\ndata.isna().sum()\n\"\"\"\nThere still exists few duplicate texts which might have been the result of poor data management or sending the same mail multiple times.\n\"\"\"\nunique = list(data.Text.unique())\nlen(unique)\ndic = dict(data)\nuni = {}\ni = 0\nfor k in range(len(list(dic['Text']))):\n    if dic['Text'][k] in unique:\n        uni[i] = [dic['Text'][k], dic['Class'][k]]\n        unique.remove(dic['Text'][k])\n        i += 1\ndata = pd.DataFrame(uni).T\nprint(data.shape)\ndata.columns = ['Text', 'Class']\ndata.head()\nplt.figure(figsize=(10,5))\nax = sns.countplot(data.Class, palette = sns.color_palette(\"mako\"))\ndef make_wordcloud(words,title):\n    cloud = WordCloud(width=1920, height=1080,max_font_size=200, max_words=300, background_color=\"white\").generate(words)\n    plt.figure(figsize=(20,20))\n    plt.imshow(cloud, interpolation=\"gaussian\")\n    plt.axis(\"off\") \n    plt.title(title, fontsize=60)\n    plt.show()\n\"\"\"\nNow that we managed to load our data frame, we can move to the next step, i.e cleaning the data.\n\"\"\"\nwordnet_lemmatizer = WordNetLemmatizer()\n\nstop = stopwords.words('english')\n\nfor punct in punctuation:\n    stop.append(punct)\n\ndef filter_text(text, stop_words):\n    word_tokens = WordPunctTokenizer().tokenize(text.lower())\n    filtered_text = [regex.sub(u'\\p{^Latin}', u'', w) for w in word_tokens if w.isalpha() and len(w) > 3]\n    filtered_text = [wordnet_lemmatizer.lemmatize(w, pos=\"v\") for w in filtered_text if not w in stop_words] \n    return \" \".join(filtered_text)\ndata[\"filtered_text\"] = data.Text.apply(lambda x : filter_text(x, stop)) \ndata.head()\n\"\"\"\nWe can now find some useful insights into the data set by constructing wordclouds and find term frequencies in each class.\n\n### Crime\n\"\"\"\nall_text = \" \".join(data[data.Class == \"Crime\"].filtered_text) \nmake_wordcloud(all_text, \"Crime\")\n\"\"\"\n### Top 10 words in the Crime Category\n\"\"\"\ncount = pd.DataFrame(all_text.split(), columns = ['words'])\ntop_10 = count[count['words'].isin(list(count.words.value_counts()[:10].index[:10]))]\nplt.figure(figsize=(10,5))\nsns.barplot(x = top_10.words.value_counts().index,\n            y = top_10.words.value_counts(), palette = sns.color_palette(\"mako\"))\n\"\"\"\n### Politics\n\"\"\"\nall_text = \" \".join(data[data.Class == \"Politics\"].filtered_text) \nmake_wordcloud(all_text, \"Politics\")\n\"\"\"\n### Top 10 words in the Politics Category\n\"\"\"\ncount = pd.DataFrame(all_text.split(), columns = ['words'])\ntop_10 = count[count['words'].isin(list(count.words.value_counts()[:10].index[:10]))]\nplt.figure(figsize=(10,5))\nsns.barplot(x = top_10.words.value_counts().index,\n            y = top_10.words.value_counts(), palette = sns.color_palette(\"mako\"))\n\"\"\"\n### Science\n\"\"\"\nall_text = \" \".join(data[data.Class == \"Science\"].filtered_text) \nmake_wordcloud(all_text, \"Science\")\n\"\"\"\n### Top 10 words in the Science Category\n\"\"\"\ncount = pd.DataFrame(all_text.split(), columns = ['words'])\ntop_10 = count[count['words'].isin(list(count.words.value_counts()[:10].index[:10]))]\nplt.figure(figsize=(10,5))\nsns.barplot(x = top_10.words.value_counts().index,\n            y = top_10.words.value_counts(), palette = sns.color_palette(\"mako\"))\ndata['Class'].value_counts()\n\"\"\"\n# Oversampling The Data\n\"\"\"\ndata=data.groupby('Class',as_index = False,group_keys=False).apply(lambda s: s.sample(1095,replace=True))\nplt.figure(figsize=(10,5))\nax = sns.countplot(data.Class, palette = sns.color_palette(\"mako\"))\n\"\"\"\n# XLNET\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport seaborn as sns\nimport transformers\n\nimport nltk\nimport re\n\n\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, roc_auc_score, roc_curve\n\nplt.style.use('seaborn')\nprint(tf.__version__)\nprint(tf.config.list_physical_devices('GPU'))\nfrom transformers import TFXLNetModel, XLNetTokenizer\nxlnet_model = 'xlnet-large-cased'\nxlnet_tokenizer = XLNetTokenizer.from_pretrained(xlnet_model)\nnumber_of_classes = 1 #len(names)\nnumber_of_classes\ndef create_xlnet(mname):\n    \"\"\" Creates the model. It is composed of the XLNet main block and then\n    a classification head its added\n    \"\"\"\n    # Define token ids as inputs\n    word_inputs = tf.keras.Input(shape=(120,), name='word_inputs', dtype='int32')\n\n    # Call XLNet model\n    xlnet = TFXLNetModel.from_pretrained(mname)\n    xlnet_encodings = xlnet(word_inputs)[0]\n\n    # CLASSIFICATION HEAD \n    # Collect last step from last hidden state (CLS)\n    doc_encoding = tf.squeeze(xlnet_encodings[:, -1:, :], axis=1)\n    # Apply dropout for regularization\n    doc_encoding = tf.keras.layers.Dropout(.1)(doc_encoding)\n    # Final output \n    outputs = tf.keras.layers.Dense(number_of_classes, activation='sigmoid', name='outputs')(doc_encoding)\n\n    # Compile model\n    model = tf.keras.Model(inputs=[word_inputs], outputs=[outputs])\n    model.compile(optimizer=tf.keras.optimizers.Adam(lr=2e-5), loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])\n\n    return model\nxlnet = create_xlnet(xlnet_model)\nxlnet.summary()\nfrom sklearn import preprocessing\n\nle = preprocessing.LabelEncoder()\ny = le.fit_transform(data['Class'])\ntext = data['filtered_text']\nlabels = data['Class']\n\n\nX_train, X_test, y_train, y_test = train_test_split(text, y, test_size=0.15, random_state=196)\ndef get_inputs(text, tokenizer, max_len=512):\n    \"\"\" Gets tensors from text using the tokenizer provided\"\"\"\n    inps = [tokenizer.encode_plus(t, max_length=max_len, pad_to_max_length=True, add_special_tokens=True) for t in text]\n    inp_tok = np.array([a['input_ids'] for a in inps])\n    ids = np.array([a['attention_mask'] for a in inps])\n    segments = np.array([a['token_type_ids'] for a in inps])\n    return inp_tok, ids, segments\ndef warmup(epoch, lr):\n    \"\"\"Used for increasing the learning rate slowly, this tends to achieve better convergence.\n    However, as we are finetuning for few epoch it's not crucial.\n    \"\"\"\n    return max(lr +1e-6, 2e-5)\n\ndef plot_metrics(pred, true_labels):\n    \"\"\"Plots a ROC curve with the accuracy and the AUC\"\"\"\n    acc = accuracy_score(true_labels, np.array(pred.flatten() >= .5, dtype='int'))\n    fpr, tpr, thresholds = roc_curve(true_labels, pred)\n    auc = roc_auc_score(true_labels, pred)\n\n    fig, ax = plt.subplots(1, figsize=(8,8))\n    ax.plot(fpr, tpr, color='red')\n    ax.plot([0,1], [0,1], color='black', linestyle='--')\n    ax.set_title(f\"AUC: {auc}\\nACC: {acc}\");\n    return fig\ninp_tok, ids, segments = get_inputs(X_train, xlnet_tokenizer)\ncallbacks = [\n    tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=4, min_delta=0.02, restore_best_weights=True),\n    tf.keras.callbacks.LearningRateScheduler(warmup, verbose=0),\n    tf.keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', factor=1e-6, patience=2, verbose=0, mode='auto', min_delta=0.001, cooldown=0, min_lr=1e-6)\n]\nhist = xlnet.fit(x=inp_tok, y=y_train, epochs=4, batch_size=2, validation_split=.15, callbacks=callbacks)\n\"\"\"\n# Testing\n\"\"\"\ninp_tok, ids, segments = get_inputs(X_test, xlnet_tokenizer)\npreds = xlnet.predict(inp_tok, verbose=True)\n#plot_metrics(preds, y_test);\npred_analysis_df = pd.DataFrame({'tweet':X_test.values, 'pred':preds.flatten(), 'real':y_test})\npred_analysis_df['rounded'] = np.array(pred_analysis_df['pred'] > 0.5, dtype='int')\ndiff = pred_analysis_df[pred_analysis_df['real'] != pred_analysis_df['rounded']]\n#change to see other examples\nidx = 44\n\ntweet, real, pred = diff.iloc[idx, [0,2,3]]\nprint(tweet)\nprint(\"PRED: \" + str(pred))\nprint(\"REAL: \" + str(real))\n# tweets = dataf_test['clean']\n\n# inp_tok, ids, segments = get_inputs(tweets, xlnet_tokenizer)\npreds = xlnet.predict(inp_tok, verbose=True)\n# dataf_test['target'] = preds\n# dataf_test['target'] = np.array(dataf_test['target'] >= 0.5, dtype='int')\n# dataf_test[['id', 'target']].to_csv('submission.csv', index=False)\nxlnet.save_weights(\"xlnet.h5\")","meta":"{'source': 'AI4Code', 'id': '47c9e508b5ee10'}"}
{"id":"9557","text":"\"\"\"\n#          Epileptic Seizures Prediction Using Machine Learning Methods\n\"\"\"\n\"\"\"\n# name:\u0648\u0639\u062f \u062e\u0627\u0644\u062f \u0627\u0644\u0639\u0646\u0632\u064a \n\"\"\"\n\"\"\"\n![image.png](attachment:37d84446-34ab-4d5f-b3c7-5dafe945b5cc.png)](http:\/\/)\n\"\"\"\n\"\"\"\n# Features\n\"\"\"\n\"\"\"\n# Read and Show Dataset\n* The original dataset from the reference consists of 5 different folders, each with 100 files, with each file representing a single subject\/person. Each file is a recording of brain activity for 23.6 seconds.\n\n\n* The corresponding time-series is sampled into 4097 data points. Each data point is the value of the EEG recording at a different point in time. So we have total 500 individuals with each has 4097 data points for 23.5 seconds.\n\n\n* We divided and shuffled every 4097 data points into 23 chunks, each chunk contains 178 data points for 1 second, and each data point is the value of the EEG recording at a different point in time.\n\n\n* So now we have 23 x 500 = 11500 pieces of information(row), each information contains 178 data points for 1 second(column), the last column represents the label y {1,2,3,4,5}.\n\n\n* The response variable is y in column 179, the Explanatory variables X1, X2, ..., X178\n\n* The response variable is y in column 179, the Explanatory variables X1, X2, ..., X178, y contains the category of the 178-dimensional input vector. Specifically, y in {1, 2, 3, 4, 5}:\n\n5 - eyes open, means when they were recording the EEG signal of the brain the patient had their eyes open.\n\n4 - eyes closed, means when they were recording the EEG signal the patient had their eyes closed.\n\n3 \u2013 Yes, they identify where the region of the tumor was in the brain and recording the EEG activity from the healthy brain area.\n\n2 - They recorder the EEG from the area where the tumor was located.\n\n1 - Recording of seizure activity.\n\n\nAll subjects falling in classes 2, 3, 4, and 5 are subjects who did not have epileptic seizure. Only subjects in class 1 have epileptic seizure.\n\"\"\"\n\"\"\"\n#  Importing the libraries\n\"\"\"\n%%html\n<style>\n@import url('https:\/\/fonts.googleapis.com\/css?family=Ewert|Roboto&effect=3d|ice|');\nbody {background-color: gainsboro;} \na {color: #37c9e1; font-family: 'Roboto';} \nh1 {color: #37c9e1; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;} \nh2, h3 {color: slategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;}\nh4 {color: #818286; font-family: 'Roboto';}\nspan {font-family:'Roboto'; color:black; text-shadow: 5px 5px 5px #aaa;}  \ndiv.output_area pre{font-family:'Roboto'; font-size:110%; color:lightblue;}      \n<\/style>\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np \nimport pandas as pd \nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nsns.set_style(\"whitegrid\")\nplt.style.use(\"fivethirtyeight\")\nfrom sklearn.linear_model import LogisticRegression \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score , classification_report\nimport seaborn as sns\nclasses=['healthy','Un-healthy']\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import svm\nfrom sklearn import metrics\n\"\"\"\n# Loading the data\n\"\"\"\nEpilepsy=pd.read_csv('..\/input\/epilepticseizures\/data.csv')\nEpilepsy.drop('Unnamed: 0',axis=1,inplace=True)\nEpilepsy.head()\n\"\"\"\n# 1. Exploratory Data Analysis (EDA)\n\"\"\"\nEpilepsy.info()\nEpilepsy.shape\ny = Epilepsy.iloc[:,178].values\ny\n\"\"\"\nTo make this a binary problem, let's turn the non-seizure classes 0 while maintaining the seizure as 1.\n\"\"\"\ny[y>1]=0\ny\ncols = Epilepsy.columns\ntgt = Epilepsy.y\ntgt[tgt>1]=0\nax = sns.countplot(tgt,label=\"Count\")\nnon_seizure, seizure = tgt.value_counts()\nprint('The number of trials for the non-seizure class is:', non_seizure)\nprint('The number of trials for the seizure class is:', seizure)\nEpilepsy.isna().sum()\nEpilepsy.describe()\n\"\"\"\n# 2. Correlation Matrix\n\"\"\"\nEpilepsy.corr()\nfeatures_mean= list(Epilepsy.columns[1:11])\nprint(features_mean)\ncorr = Epilepsy[features_mean].corr() \nplt.figure(figsize=(12,8))\nsns.heatmap(corr, cbar = True,  square = True, annot=True, fmt= '.2f',annot_kws={'size': 12},\n           xticklabels= features_mean, yticklabels= features_mean,\n           cmap= 'coolwarm')\n\"\"\"\n# 3. Data Processing\n\"\"\"\n\"\"\"\n# Perform Feature Standerd Scalling\nStandardize features by removing the mean and scaling to unit variance\n\nThe standard score of a sample x is calculated as:\n\nz = (x - u) \/ s\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\n\nprediction_var = ['X1', 'X2', 'X3', 'X4', 'X5']\ntrain, test = train_test_split(Epilepsy, test_size = 0.3)\n# we can check their dimension \nprint(train.shape)\nprint(test.shape)\n\"\"\"\n# 4. Applying machine learning algorithms\n\"\"\"\ntrain_X = train[prediction_var]\ntrain_y=train.y\ntest_X= test[prediction_var]\ntest_y =test.y\nmodel=RandomForestClassifier(n_estimators=100)\nmodel.fit(train_X,train_y)\nprediction=model.predict(test_X)\nfrom sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score , classification_report\nimport seaborn as sns\nclasses=['healthy','Un-healthy']\n\ndef print_score(clf, X_train, y_train, X_test, y_test, train=True):\n    if train:\n        pred = clf.predict(X_train)\n        print(\"Train Result:\\n================================================\")\n        print(f\"Accuracy Score: {accuracy_score(y_train, pred) * 100:.2f}%\")\n        print(\"_______________________________________________\")\n        print(\"Classification Report:\", end='')\n        print(f\"\\tPrecision Score: {precision_score(y_train, pred) * 100:.2f}%\")\n       # recall=recall_score(y_train, pred) \n        print(f\"\\t\\t\\tRecall Score: {recall_score(y_train, pred) * 100:.2f}%\")\n        print(f\"\\t\\t\\tF1 score: {f1_score(y_train, pred) * 100:.2f}%\")\n        print(\"_______________________________________________\")\n        print(f\"Confusion Matrix: \\n {confusion_matrix(y_train, pred)}\\n\")\n        \n    elif train==False:\n        pred = clf.predict(X_test)\n        print(\"Test Result:\\n================================================\")        \n        print(f\"Accuracy Score: {accuracy_score(y_test, pred) * 100:.2f}%\")\n        print(\"_______________________________________________\")\n        print(\"Classification Report:\", end='')\n        print(f\"\\tPrecision Score: {precision_score(y_test, pred) * 100:.2f}%\")\n        print(f\"\\t\\t\\tRecall Score: {recall_score(y_test, pred) * 100:.2f}%\")\n        print(f\"\\t\\t\\tF1 score: {f1_score(y_test, pred) * 100:.2f}%\")\n        print(\"_______________________________________________\")\n        sns.heatmap(confusion_matrix(y_test, pred), annot= True, cmap='YlGnBu',fmt = 'g')\n        print(classification_report(y_test,pred))\n        cm=(confusion_matrix(y_test,pred))\n       # ax.xaxis.set_label_position('top')\n        plt.tight_layout()\n        plt.title('Confusion matrix for Decision Tree Model', y = 1.1)\n        plt.ylabel('Actual label')\n        plt.xlabel('Predicted label')\n        plt.show()\n        total = sum(sum(cm))\n        acc = (cm[0, 0] + cm[1, 1]) \/ total\n        sensitivity = cm[0, 0] \/ (cm[0, 0] + cm[0, 1])\n        specificity = cm[1, 1] \/ (cm[1, 0] + cm[1, 1])\n       # print(cm)\n\n        FP = cm.sum(axis=0) - np.diag(cm)  \n        FN = cm.sum(axis=1) - np.diag(cm)\n        TP = np.diag(cm)\n        TN = cm.sum() - (FP + FN + TP)\n\n        FP = FP.astype(float)\n        FN = FN.astype(float)\n        TP = TP.astype(float)\n        TN = TN.astype(float)\n\n        # Sensitivity, hit rate, recall, or true positive rate\n        TPR = TP\/(TP+FN)\n        print('Sensitivity (TPR) : ',TPR)\n        # Specificity or true negative rate\n        TNR = TN\/(TN+FP) \n        print('Specificity (TNR) : ',TNR)\n        # Overall accuracy\n        print(\" Overall accuracy\")\n        ACC = (TP+TN)\/(TP+FP+FN+TN)\n        print('Accuracy : ',ACC)\n        print(\"Accuracy: {:.4f}\".format(acc))\n        print(\"Average Sensitivity: {:.4f}\".format(sensitivity))\n        print(\"Average Specificity: {:.4f}\".format(specificity))\n        print('\\n')\n        \n        conf_matrix=cm\n        print(\"=========================================\")\n        # save confusion matrix and slice into four pieces\n        TP = conf_matrix[1][1]\n        TN = conf_matrix[0][0]\n        FP = conf_matrix[0][1]\n        FN = conf_matrix[1][0]\n        print('True Positives:', TP)\n        print('True Negatives:', TN)\n        print('False Positives:', FP)\n        print('False Negatives:', FN)\n\n        # calculate accuracy\n        conf_accuracy = (float (TP+TN) \/ float(TP + TN + FP + FN))\n\n        # calculate mis-classification\n        conf_misclassification = 1- conf_accuracy\n\n        # calculate the sensitivity\n        conf_sensitivity = (TP \/ float(TP + FN))\n        # calculate the specificity\n        conf_specificity = (TN \/ float(TN + FP))\n\n        # calculate precision\n        conf_precision = (TN \/ float(TN + FP))\n        # calculate f_1 score\n        conf_f1 = 2 * ((conf_precision * conf_sensitivity) \/ (conf_precision + conf_sensitivity))\n        print('-'*50)\n        print(f'Accuracy: {round(conf_accuracy,2)}') \n        print(f'Mis-Classification: {round(conf_misclassification,2)}') \n        print(f'Sensitivity: {round(conf_sensitivity,2)}') \n        print(f'Specificity: {round(conf_specificity,2)}') \n        print(f'Precision: {round(conf_precision,2)}')\n        print(f'f_1 Score: {round(conf_f1,2)}')\n\"\"\"\n# Function to plot ROC and Precision Recall Curve for combination of all models\n\"\"\"\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\ndef plotting(true,pred):\n    fig,ax=plt.subplots(1,2,figsize=(15,5))\n    precision,recall,threshold = precision_recall_curve(true,pred[:,1])\n    ax[0].plot(recall,precision,'g--')\n    ax[0].set_xlabel('Recall')\n    ax[0].set_ylabel('Precision')\n    ax[0].set_title(\"Average Precision Score : {}\".format(average_precision_score(true,pred[:,1])))\n    fpr,tpr,threshold = roc_curve(true,pred[:,1])\n    ax[1].plot(fpr,tpr)\n    ax[1].set_title(\"AUC Score is: {}\".format(auc(fpr,tpr)))\n    ax[1].plot([0,1],[0,1],'k--')\n    ax[1].set_xlabel('False Positive Rate')\n    ax[1].set_ylabel('True Positive Rate')\nfrom sklearn.model_selection import train_test_split\n\nX = Epilepsy.drop('y', axis=1)\ny = Epilepsy.y\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\"\"\"\nNow we've got our data split into training and test sets, it's time to build a machine learning model.\n\nWe'll train it (find the patterns) on the training set.\n\nAnd we'll test it (use the patterns) on the test set.\n\nWe're going to try different machine learning models:\n\n1-Logistic Regression\n\n2-K-Nearest Neighbours Classifier\n\n3-Support Vector machine\n\n4-Decision Tree Classifier\n\n5-Random Forest Classifier\n\n6-XGBoost Classifier\n\"\"\"\n\"\"\"\n# 1. K-nearest neighbors\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn_classifier = KNeighborsClassifier()\nknn_classifier.fit(X_train, y_train)\n\nprint_score(knn_classifier, X_train, y_train, X_test, y_test, train=True)\nprint_score(knn_classifier, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n# 2. Decision Tree Classifier\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\n\n\ntree = DecisionTreeClassifier(random_state=42)\ntree.fit(X_train, y_train)\n\nprint_score(tree, X_train, y_train, X_test, y_test, train=True)\nprint_score(tree, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n# 3. Support Vector machine\n\"\"\"\nfrom sklearn.svm import SVC\n\n\nsvm_model = SVC(kernel='rbf', gamma=0.1, C=1.0, probability=True)\nsvm_model.fit(X_train, y_train)\n\nprint_score(svm_model, X_train, y_train, X_test, y_test, train=True)\nprint_score(svm_model, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n# *4*MLP neural network classifier**\n\"\"\"\nfrom sklearn.neural_network import MLPClassifier\nNN=MLPClassifier(hidden_layer_sizes=(10,50),momentum=0.9,solver='sgd',random_state=42)\n               \nNN.fit(X_train, y_train)\n\nprint_score(NN, X_train, y_train, X_test, y_test, train=True)\nprint_score(NN, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n# 5. Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\n\nrand_forest = RandomForestClassifier(n_estimators=1000, random_state=42)\nrand_forest.fit(X_train, y_train)\n\nprint_score(rand_forest, X_train, y_train, X_test, y_test, train=True)\nprint_score(rand_forest, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n#  6. XGBoost Classifer\n\"\"\"\nfrom xgboost import XGBClassifier\n\nxgb = XGBClassifier()\nxgb.fit(X_train, y_train)\n\nprint_score(xgb, X_train, y_train, X_test, y_test, train=True)\nprint_score(xgb, X_train, y_train, X_test, y_test, train=False)\n\"\"\"\n# 7- naive_bayes\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nnb = GaussianNB()\nnb.fit(X_train, y_train)\n\nprint_score(nb, X_train, y_train, X_test, y_test, train=True)\nprint_score(nb, X_train, y_train, X_test, y_test, train=False)  \n\"\"\"\n# ROC\nReceiver operator characteristic, used very commonly to assess the quality of models for binary classification.\n\nWe will look at at three different classifiers here, a strongly regularized one and two with weaker regularization. The heavily regularized model has parameters very close to zero and is actually worse than if we would pick the labels for our holdout samples randomly.\n\"\"\"\ncolors = ['r', 'g', 'b', 'y', 'k', 'c', 'm', 'brown', 'r']\nlw = 1\nCs = [1e-6, 1e-4, 1e0]\n\nplt.figure(figsize=(12,6))\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve for different classifiers')\n\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n\nlabels = []\nfor idx, C in enumerate(Cs):\n    clf = LogisticRegression(C = C)\n    clf.fit(X_train, y_train)\n    print(\"C: {}, parameters {} and intercept {}\".format(C, clf.coef_, clf.intercept_))\n    fpr, tpr, _ = roc_curve(y_test, clf.predict_proba(X_test)[:,1])\n    roc_auc = auc(fpr, tpr)\n    plt.plot(fpr, tpr, lw=lw, color=colors[idx])\n    labels.append(\"C: {}, AUC = {}\".format(C, np.round(roc_auc, 4)))\n\nplt.legend(['random AUC = 0.5'] + labels)","meta":"{'source': 'AI4Code', 'id': '11a288e43d49fb'}"}
{"id":"138512","text":"\"\"\"\n**Q1**\n\nFrom 100 people, 30 of them have blood type A, 38 have blood type O, 24 have blood type B, 8 have blood type AB.\nWe want to visualize this data here:\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\nLet's create a bar plot first:\n\"\"\"\nblood_type = ['A','O','B','AB']\nfrequency = [30, 38, 24, 8]\nfig= plt.figure(figsize=(5,3), dpi=100)\nax = fig.add_axes([0, 0, 0.8, 0.8])\nax.bar(blood_type, frequency, color='#f5b402')\n\"\"\"\nNow let's see it on a pie chart:\n\"\"\"\nfig= plt.figure(figsize=(5,5), dpi=100)\nax = fig.add_axes([0, 0, 0.8, 0.8])\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']\nax.pie(frequency, labels = blood_type, colors=colors, autopct='%1.1f%%')\n\"\"\"\n**Q2**\n\nLet's drow a scatter plot for the data given below:\n\"\"\"\nx= [5,7,8,7,2,17,2,9,4,11,12,9,6]\ny= [99,86,87,88,111,86,103,87,94,78,77,85,86]\nfig= plt.figure(figsize=(5,3), dpi=100)\nax = fig.add_axes([0, 0, 0.8, 0.8])\nplt.scatter(x, y, alpha=0.5)\nax.set_title('scatter plot')\nax.set_xlabel('X')\nax.set_ylabel('Y')\n\"\"\"\n**Q3**\n\nLet's draw a graph from a normal distribution, with 300 point, mu=170 and sigma=10:\n\"\"\"\nnormal = np.random.normal(170, 10, 300)\nfig= plt.figure(figsize=(5,3), dpi=100)\nax = fig.add_axes([0, 0, 0.8, 0.8])\nplt.hist(x=normal, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)\nplt.xlabel('Value')\nplt.ylabel('Frequency')\nplt.title( 'Histogram')","meta":"{'source': 'AI4Code', 'id': 'fea2ea12a3a7fc'}"}
{"id":"82547","text":"\"\"\"\n# Method chaining reference\n\nThis is the referenc component of the \"Method chaining\" section of the Advanced Pandas tutorial. For the workbook component, click [here](https:\/\/www.kaggle.com\/residentmario\/method-chaining-workbook).\n\"\"\"\nimport pandas as pd\npd.set_option('max_rows', 5)\nwine = pd.read_csv(\"..\/input\/wine-reviews\/winemag-data-130k-v2.csv\", index_col=0)\nramen = pd.read_csv(\"..\/input\/ramen-ratings\/ramen-ratings.csv\", index_col=0)\nramen\n\"\"\"\n## Why method chaining?\n\nMethod chaining is the last topic we will cover in this first track of the Advanced Pandas tutorial. It is also the only section of this tutorial which is a technique or a pattern, not a function or variable.\n\nMethod chaining is a methodology for performing operations on a `DataFrame` or `Series` that emphasizes continuity. To demonstrate what I mean, here's a data cleaning and dropping operation (which you should be familiar with from the last section) done two different ways:\n\"\"\"\nstars = ramen['Stars']\nna_stars = stars.replace('Unrated', None).dropna()\nfloat_stars = na_stars.astype('float64')\nfloat_stars.head()\n\n(ramen['Stars']\n     .replace('Unrated', None)\n     .dropna()\n     .astype('float64')\n     .head())\n\"\"\"\nIn the first statement we assign data to temporary variables, creating new ones as we go further and further along. In the second statement, written in the method chaining style, we instead \"chain\" our operations, one after the other, all on the same original `DataFrame`.\n\nMost `pandas` operations can written in a method chaining style, and in the last couple years or so `pandas` has added more and more tools for making these sorts of statements easier to write. This paradigm comes to us from the R programming language&mdash;specifically, the `dpyler` module, part of the \"Tidyverse\".\n\nMethod chaining is advantageous for several reasons. One is that it lessens the need for creating and mentally tracking temporary variables. Another is that it emphasizes a correctly structured interative approach to working with data, where each operation is a \"next step\" after the last. Debugging is easy: just comment out operations that don't work until you get to one that does, and then start stepping forward again. And it looks kind of cool. =)\n\nFor a deeper exploration of why method chaining, read the [Method Chaining Section of the Modern Pandas Tutorial](https:\/\/tomaugspurger.github.io\/method-chaining.html) (written by a `pandas` core dev).\n\"\"\"\n\"\"\"\n## Assign and pipe\n\nNow that we've learned all these ways of manipulating data with `pandas`, we're ready to take advantage of method chaining to write clear, clean data manipulation code. Now I'll introduce three additional methods useful for coding in this style.\n\"\"\"\nwine.head()\n\"\"\"\nThe first of these is `assign`. The `assign` method lets you create new columns or modify old ones inside of a `DataFrame` inline. For example, to fill the `region_1` field with the `province` field wherever the `region_1` is null (useful if we're mixing in our own categories), we would do:\n\"\"\"\nwine.assign(\n    region_1=wine.apply(lambda srs: srs.region_1 if pd.notnull(srs.region_1) else srs.province, \n                        axis='columns')\n)\n\"\"\"\nWhich is equivalent to:\n\n    wine['region_1'] = wine['region_1'].apply(\n        lambda srs: srs.region_1 if pd.notnull(srs.region_1) else srs.province, \n        axis='columns'\n    )\n\nYou can modify as many old columns and create as many new ones as you'd like with `assign`, but it does have the limitation that the column being modified must not have any reserved characters like periods (`.`) or spaces (` `) in the name.\n\nThe next method to know is `pipe`. `pipe` is a little mind-bending: it lets you perform an operation on the entire `DataFrame` at once, and replaces the current `DataFrame` which the output of your `pipe`.\n\nFor example, one way to change the give the `DataFrame` index a new name would be to do:\n\"\"\"\ndef name_index(df):\n    df.index.name = 'review_id'\n    return df\n\nwine.pipe(name_index)\n\"\"\"\n`pipe` is a power tool: it comes in handy when you're performing _very_ intricate operations on your `DataFrame`. You won't need it often, but it'll be super useful when you do.\n\nThat concludes this tutorial! Bravo!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '978f2e9995f8d9'}"}
{"id":"96345","text":"\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Salary Prediction with Machine Learning\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Salary Prediction with Machine Learning<\/span><\/h1>\n\nThis dataset was originally taken from the StatLib library which is maintained at Carnegie Mellon University. This is part of the data that was used in the 1988 ASA Graphics Section Poster Session. The salary data were originally from Sports Illustrated, April 20, 1987. The 1986 and career statistics were obtained from The 1987 Baseball Encyclopedia Update published by Collier Books, Macmillan Publishing Company, New York.\n\"\"\"\n\"\"\"\n![expected-salary-at-08-31-2016.jpg](attachment:8cb1b7af-96ac-4981-bd24-7586e05c2896.jpg)\n\"\"\"\n\"\"\"\n- A data frame with 322 observations of major league players on the following 20 variables.\n- AtBat: Number of times at bat in 1986\n- Hits: Number of hits in 1986\n- HmRun: Number of home runs in 1986\n- Runs: Number of runs in 1986\n- RBI: Number of runs batted in in 1986\n- Walks: Number of walks in 1986\n- Years: Number of years in the major leagues\n- CAtBat: Number of times at bat during his career\n- CHits: Number of hits during his career\n- CHmRun: Number of home runs during his career\n- CRuns: Number of runs during his career\n- CRBI: Number of runs batted in during his career\n- CWalks: Number of walks during his career\n- League: A factor with levels A and N indicating player\u2019s league at the end of 1986\n- Division: A factor with levels E and W indicating player\u2019s division at the end of 1986\n- PutOuts: Number of put outs in 1986\n- Assists: Number of assists in 1986\n- Errors: Number of errors in 1986\n- Salary: 1987 annual salary on opening day in thousands of dollars\n- NewLeague: A factor with levels A and N indicating player\u2019s league at the beginning of 1987\n\n**Number of Observation Units: 322**\n\n**Variable Number: 20**\n\n\n\"\"\"\n\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Data Preprocessing\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Data Preprocessing<\/span><\/h1>\n\n\"\"\"\nimport numpy as np\nimport pandas as pd \nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import scale \nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import model_selection\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn import neighbors\nfrom sklearn.svm import SVR\n\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\ndf = pd.read_csv(\"..\/input\/hitters\/Hitters.csv\")\ndf.head()\ndef check_df(dataframe, head=5):\n    print(\"\u26e4 Shape \u26e4\")\n    print(dataframe.shape)\n    print(\"\u26e4 Types \u26e4\")\n    print(dataframe.dtypes)\n    print(\"\u26e4 Head \u26e4\")\n    print(dataframe.head(head))\n    print(\"\u26e4 Tail \u26e4\")\n    print(dataframe.tail(head))\n    print(\"\u26e4 NA \u26e4\")\n    print(dataframe.isnull().sum())\n    print(\"\u26e4 Quantiles \u26e4\")\n    print(dataframe.quantile([0, 0.05, 0.50, 0.95, 0.99, 1]).T)\n    \ncheck_df(df)\ndf.nunique() # Number of unique observations in variables\ndf[\"League\"].value_counts()  #categorical variable\ndf.League.value_counts().plot.barh();\ndf[\"NewLeague\"].value_counts()\ndf.NewLeague.value_counts().plot.barh();\ndf[\"Division\"].value_counts()\ndf.Division.value_counts().plot.barh();\ndf[\"Salary\"].max()\ndf[\"Salary\"].min()\nimport seaborn as sns\nsns.distplot(df.Salary);\ndf.corr()\nf, ax = plt.subplots(figsize= [15,15])\nsns.heatmap(df.corr(), annot=True, fmt=\".2f\", ax=ax, cmap = \"magma\" )\nax.set_title(\"Correlation Matrix\", fontsize=20)\nplt.show()\ndf.sort_values(\"CHits\",ascending = False)\n\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Means\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Means<\/span><\/h1>\n\"\"\"\ndf.groupby(\"League\").agg({\"Salary\": \"mean\"})\ndf.groupby(\"NewLeague\").agg({\"Salary\": \"mean\"})\ndf.groupby(\"Division\").agg({\"Salary\": \"mean\"})\ndf.groupby(\"CRBI\").agg({\"Salary\": \"mean\"})\ndf.groupby(\"CRuns\").agg({\"Salary\": \"mean\"})\ndf.groupby([\"League\",\"Years\"]).agg({\"Salary\": \"mean\"})\ndf.groupby([\"NewLeague\",\"Years\"]).agg({\"Salary\": \"mean\"})\ndf.groupby([\"Division\",\"Years\"]).agg({\"Salary\": \"mean\"})\ndf.groupby(\"League\").agg({\"Errors\": \"mean\"})\ndf.groupby(\"League\").agg({\"CAtBat\": \"mean\"})\n\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Max\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Max<\/span><\/h1>\n\"\"\"\ndf.groupby(\"League\").agg({\"CHits\": \"max\"})\ndf.groupby(\"Division\").agg({\"CHits\": \"max\"})\ndf.groupby(\"League\").agg({\"Hits\": \"max\"})\ndf.groupby(\"League\").agg({\"AtBat\": \"max\"})\ndf.groupby(\"League\").agg({\"Years\": \"max\"})\ndf.groupby(\"League\").agg({\"Errors\": \"max\"})\ndf.groupby(\"League\").agg({\"PutOuts\": \"max\"})\ndf.groupby(\"League\").agg({\"Assists\": \"max\"})\ndf.groupby(\"Years\").agg({\"CAtBat\": \"max\"})\ndf.groupby([\"League\", \"Years\"]).agg({\"CAtBat\": \"max\"})\n\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Feature Extraction\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Feature Extraction<\/span><\/h1>\n\"\"\"\ndf[\"OrtCAtBat\"] = df[\"CAtBat\"] \/ df[\"Years\"]\ndf[\"OrtCHits\"] = df[\"CHits\"] \/ df[\"Years\"]\ndf[\"OrtCHmRun\"] = df[\"CHmRun\"] \/ df[\"Years\"]\ndf[\"OrtCruns\"] = df[\"CRuns\"] \/ df[\"Years\"]\ndf[\"OrtCRBI\"] = df[\"CRBI\"] \/ df[\"Years\"]\ndf[\"OrtCWalks\"] = cwalks = df[\"CWalks\"] \/ df[\"Years\"]\ndf.head()\ndf = df.drop(['AtBat','Hits','HmRun','Runs','RBI','Walks','Assists','Errors',\"PutOuts\",'League','NewLeague', 'Division'], axis=1)\ndf.head()\ndf.isnull().sum()\nimport missingno as msno\nmsno.bar(df);\ndf_missing = df[df[\"Salary\"].isnull()].head()\ndf_missing\nfrom sklearn.impute import KNNImputer\nimputer = KNNImputer(n_neighbors = 4)\ndf_filled = imputer.fit_transform(df)\n#We fill in the missing observations with the KNN method.\ndf = pd.DataFrame(df_filled,columns = df.columns)\ndf.isnull().sum()\nimport seaborn as sns\nsns.boxplot(x = df[\"Salary\"]);\ndf[\"Salary\"].describe()\nfor feature in df:\n\n    Q1 = df[feature].quantile(0.25)\n    Q3 = df[feature].quantile(0.75)\n    IQR = Q3-Q1\n    upper = Q3 + 1.5*IQR\n    lower = Q1 - 1.5*IQR\n\n    if df[(df[feature] > upper) | (df[feature] < lower)].any(axis=None):\n        print(feature,\"yes\")\n        print(df[(df[feature] > upper) | (df[feature] < lower)].shape[0])\n    else:\n        print(feature, \"no\")\nQ1 = df.Salary.quantile(0.25)\nQ3 = df.Salary.quantile(0.75)\nIQR = Q3-Q1\nlower = Q1 - 1.5*IQR\nupper = Q3 + 1.5*IQR\ndf.loc[df[\"Salary\"] > upper,\"Salary\"] = upper\nimport seaborn as sns\nsns.boxplot(x = df[\"Salary\"]);\nfrom sklearn.neighbors import LocalOutlierFactor\nlof =LocalOutlierFactor(n_neighbors= 10)\nlof.fit_predict(df)\ndf_scores = lof.negative_outlier_factor_\nnp.sort(df_scores)[0:30]\n\nthreshold = np.sort(df_scores)[7]\nthreshold\noutlier = df_scores > threshold\ndf = df[outlier]\ndf.shape\n\"\"\"\n<a id = \"1\"><\/a><h1 id=\"Machine Learning Methods\"><span class=\"label label-default\" style=\"background-color:#f5c0c0; font-size:30px; \ncolor: Black; \">Machine Learning Methods<\/span><\/h1>\n\"\"\"\n\"\"\"\n<a id = \"1\"><\/a><br>\n## 1 . KNN\n\"\"\"\ny = df[\"Salary\"]\nX = df.drop(\"Salary\",axis=1)\nX.head()\nimport statsmodels.api as sm\nfrom sklearn.feature_selection import RFE\n#Backward Elimination\ncols = list(X.columns)\npmax = 1\nwhile (len(cols)>0):\n    p= []\n    X_1 = X[cols]\n    X_1 = sm.add_constant(X_1)\n    model = sm.OLS(y,X_1).fit()\n    p = pd.Series(model.pvalues.values[1:],index = cols)      \n    pmax = max(p)\n    feature_with_p_max = p.idxmax()\n    if(pmax>0.05):\n        cols.remove(feature_with_p_max)\n    else:\n        break\nselected_features_BE = cols\nprint(selected_features_BE)\n\n#https:\/\/towardsdatascience.com\/feature-selection-with-pandas-e3690ad8504b\nX = df[selected_features_BE]\nX.head()\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n                                                    test_size=0.20, \n                                                    random_state=46)\nknn_model = KNeighborsRegressor().fit(X_train, y_train)\ny_pred = knn_model.predict(X_test)\nknn_base = np.sqrt(mean_squared_error(y_test, y_pred))\nknn_base\n\"\"\"\n#  Model Tuning\n\"\"\"\nknn_params = {\"n_neighbors\": np.arange(2,30,1)}\n\nknn_model = KNeighborsRegressor()\n\nknn_cv_model = GridSearchCV(knn_model, knn_params, cv = 10).fit(X_train, y_train)\nknn_cv_model.best_params_\n\"\"\"\n# Final Model Tuning\n\"\"\"\nknn_tuned = KNeighborsRegressor(**knn_cv_model.best_params_).fit(X_train, y_train)\ny_pred = knn_tuned.predict(X_test)\nknn_final = np.sqrt(mean_squared_error(y_test, y_pred))\nknn_final\n\"\"\"\n<a id = \"1\"><\/a><br>\n## 2 . SVR\n\"\"\"\nsvr_model = SVR().fit(X_train, y_train)\ny_pred = svr_model.predict(X_test)\nsvr_base = np.sqrt(mean_squared_error(y_test, y_pred))\nsvr_base\n\"\"\"\n# Model Tuning\n\"\"\"\nsvr_model = SVR() \n\nsvr_params = {\"C\": [0.01,0.001, 0.2, 0.1,0.5,0.8,0.9,1, 10, 100, 500,1000]}\n\nsvr_cv_model = GridSearchCV(svr_model, svr_params, cv = 10, n_jobs = -1, verbose =  2).fit(X_train, y_train)\nsvr_cv_model.best_params_\nsvr_tuned = SVR(**svr_cv_model.best_params_).fit(X_train, y_train)\n\"\"\"\n# Final Model Tuning\n\"\"\"\ny_pred = svr_tuned.predict(X_test)\nsvr_final = np.sqrt(mean_squared_error(y_test, y_pred))\nsvr_final\n\"\"\"\n<a id = \"1\"><\/a><br>\n## 3 . CART\n\"\"\"\ncart_model = DecisionTreeRegressor()\ncart_model.fit(X_train, y_train)\ny_pred = cart_model.predict(X_test)\ncart_base = np.sqrt(mean_squared_error(y_test, y_pred))\ncart_base\n\"\"\"\n# Model Tuning\n\"\"\"\ncart_model = DecisionTreeRegressor()\ncart_params = {\"max_depth\": [2,3,4,5,10,20,100, 1000],\n              \"min_samples_split\": [2,10,5,30,50,10]}\ncart_cv_model = GridSearchCV(cart_model, cart_params, cv = 10, n_jobs = -1, verbose =  2).fit(X_train, y_train)\ncart_cv_model.best_params_\ncart_tuned = DecisionTreeRegressor(**cart_cv_model.best_params_).fit(X_train, y_train)\ny_pred = cart_tuned.predict(X_test)\ncart_final = np.sqrt(mean_squared_error(y_test, y_pred))\ncart_final\n\"\"\"\n<a id = \"1\"><\/a><br>\n## 4 . Random Forests\n\"\"\"\nrf_model = RandomForestRegressor(random_state = 42).fit(X_train, y_train)\ny_pred = rf_model.predict(X_test)\nrf_base = np.sqrt(mean_squared_error(y_test, y_pred))\nrf_base\n\"\"\"\n# Model Tuning\n\"\"\"\nrf_params = {\"max_depth\": [5,10,None],\n            \"max_features\": [2,5,10],\n            \"n_estimators\": [100, 500, 900],\n            \"min_samples_split\": [2,10,30]}\nrf_cv_model = GridSearchCV(rf_model, rf_params, cv = 10, n_jobs = -1, verbose = 2).fit(X_train , y_train)\nrf_cv_model.best_params_\nrf_tuned = RandomForestRegressor(**rf_cv_model.best_params_).fit(X_train, y_train)\ny_pred = rf_tuned.predict(X_test)\nrf_final = np.sqrt(mean_squared_error(y_test, y_pred))\nrf_final\nrf_tuned.feature_importances_\nImportance = pd.DataFrame({'Importance':rf_tuned.feature_importances_*100}, \n                          index = ['CRuns', 'CWalks', 'OrtCAtBat', 'OrtCHits', 'OrtCRBI', 'OrtCWalks'])\n\nImportance.sort_values(by = 'Importance', \n                       axis = 0, \n                       ascending = True).plot(kind = 'barh', \n                                              color = 'r', )\n\nplt.xlabel('Variable Importance')\nplt.gca().legend_ = None","meta":"{'source': 'AI4Code', 'id': 'b0f5f21e8e285b'}"}
{"id":"128064","text":"\"\"\"\n# pyStackNet on Kaggle\n\"\"\"\n\"\"\"\nThis kernel aims at exposing a working implentation of pyStackNet inside kaggle. The original pyStackNet does not work straightforward and some modifications are necessary to make it run in Kaggle. \nThis includes small modifications in the code that I uploaded on https:\/\/gitlab.com\/YannBerthelot\/kaggle_pystacknet.git\n\nAll credit goes to the original authors of StackNet and pyStackNet.\nhttps:\/\/github.com\/h2oai\/pystacknet\nhttps:\/\/github.com\/kaz-Anova\/StackNet\n\"\"\"\n\"\"\"\nPlease comment and\/or like if this kernel helped you so that others can see it.\n\"\"\"\n\"\"\"\n## Classic start\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport re\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nimport os\nprint(os.listdir(\"..\/input\"))\n\"\"\"\n## pyStackNet installation\n\"\"\"\n\"\"\"\ndon't forget to turn internet \"On\" in the kernel settings.\n\"\"\"\n!git clone https:\/\/gitlab.com\/YannBerthelot\/kaggle_pystacknet.git\nprint(os.listdir(\"kaggle_pystacknet\/pystacknet\"))\n!pip install \"kaggle_pystacknet\/pystacknet\"\nimport pystacknet\n\"\"\"\n## Titanic basic example\n\"\"\"\n\"\"\"\n*because I can't do better*\n\"\"\"\ntrain=pd.read_csv(\"..\/input\/train.csv\")\ntest=pd.read_csv(\"..\/input\/test.csv\")\ndef feature_engineering(df):\n    df[\"Cabin\"]=df[\"Cabin\"].fillna(\"C\")\n    deck = {\"A\": 1, \"B\": 2, \"C\": 3, \"D\": 4, \"E\": 5, \"F\": 6, \"G\": 7, \"U\": 8}\n    df['Deck'] = df['Cabin'].map(lambda x: re.compile(\"([a-zA-Z]+)\").search(x).group())\n    mean = df[\"Age\"].mean()\n    std = df[\"Age\"].std()\n    is_null = df[\"Age\"].isnull().sum()\n    rand_age = np.random.randint(mean - std, mean + std, size = is_null)\n\n    age_slice = df[\"Age\"].copy()\n    age_slice[np.isnan(age_slice)] = rand_age\n    df[\"Age\"] = age_slice\n    df[\"Age\"] = df[\"Age\"].astype(int)\n    df[\"Embarked\"]=df['Embarked'].fillna(\"S\")\n    \n    df[\"Siblings\"]=df[\"SibSp\"]+df[\"Parch\"]\n    df=df.drop([\"Name\",\"Ticket\",\"SibSp\",\"Parch\",\"PassengerId\",\"Cabin\",\"Fare\"],axis=1)\n    return(df)\n\ntrain=feature_engineering(train)\ntest=feature_engineering(test)\nX=train.drop(\"Survived\",axis=1)\nY=train[\"Survived\"]\nfrom sklearn.model_selection import train_test_split\n\nx, x_test, y, y_test = train_test_split(X, Y, test_size=0.20, random_state=42,shuffle=True)\n\nX_oh=pd.get_dummies(X)\n\ntest_oh=pd.get_dummies(test)\ntest_oh[\"Deck_T\"]=0\n\"\"\"\n## pyStackNet\n\"\"\"\n\"\"\"\nIncluding LGBM implementation in pystacknet for your pleasure\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, ExtraTreesClassifier, ExtraTreesRegressor, GradientBoostingClassifier,GradientBoostingRegressor\nfrom sklearn.linear_model import LogisticRegression, Ridge\nfrom sklearn.decomposition import PCA\nfrom lightgbm import LGBMClassifier\nmodels=[ \n            \n            [RandomForestClassifier (n_estimators=100, criterion=\"entropy\", max_depth=5, max_features=0.5, random_state=1),\n             ExtraTreesClassifier (n_estimators=100, criterion=\"entropy\", max_depth=5, max_features=0.5, random_state=1),\n             GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, max_features=0.5, random_state=1),\n             LogisticRegression(random_state=1),\n             LGBMClassifier()],\n            [RandomForestClassifier (n_estimators=100, criterion=\"entropy\", max_depth=5, max_features=0.5, random_state=1),\n             ExtraTreesClassifier (n_estimators=100, criterion=\"entropy\", max_depth=5, max_features=0.5, random_state=1),\n             GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, max_features=0.5, random_state=1),\n             LogisticRegression(random_state=1),\n             LGBMClassifier()],           \n            \n            ]\nfrom pystacknet.pystacknet import StackNetClassifier\n\nmodel=StackNetClassifier(models, metric=\"auc\", folds=5,\n\trestacking=False,use_retraining=True, use_proba=True, \n\trandom_state=12345,n_jobs=1, verbose=1)\n\nmodel.fit(X_oh,Y)\noutput=model.predict_proba(test_oh)\n\"\"\"\n## Output preparation\n\"\"\"\noutput=pd.DataFrame(output).rename(index=str, columns={\"index\": \"PassengerId\", 0: \"Survived\"})\n\noutput=output.reset_index()\n\noutput=output.rename(columns={\"index\":\"PassengerId\"})\n\noutput[\"PassengerId\"]=output[\"PassengerId\"].astype(\"int\")+892\n\noutput[\"Survived\"]=(output[output.columns[output.shape[1]-1]]>0.5).apply(int)\n\noutput=output[[\"PassengerId\",\"Survived\"]]\n\"\"\"\n### IMPORTANT : due to the number of folders we created, commit will fail if we don't erase them. So let's do some cleaning\n\"\"\"\nimport shutil\nshutil.rmtree(\"kaggle_pystacknet\")\n\"\"\"\n## Output for submission\n\"\"\"\noutput.to_csv(\"results.csv\",index=False,header=True)","meta":"{'source': 'AI4Code', 'id': 'eb9a1a7bb3e8e1'}"}
{"id":"121732","text":"\"\"\"\n## Creating training df for \"Coleridge - Show US the data\" competition\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport json\nimport seaborn as sns\nimport re\nno_of_examples = None #reducing the number for experimentation, using None for final code (applied on papers dict generation only)\n\ntrain_path = '..\/input\/coleridgeinitiative-show-us-the-data\/train.csv'\ntrain = pd.read_csv(train_path)\n\ntrain_folder = '..\/input\/coleridgeinitiative-show-us-the-data\/train'\npapers = {}\nfor paper_id in train[:no_of_examples]['Id'].unique():\n    with open(f'{train_folder}\/{paper_id}.json', 'r') as f:\n        paper = json.load(f)\n        papers[paper_id] = paper\ntrain.describe()\n#creating a dataframe with papers info and text divided into sections\n\ndf_list = []\n\nfor paper_id in train[:no_of_examples]['Id'].unique():\n    \n    for count, s in enumerate(papers[paper_id]):\n        extended_train = {}\n        \n        extended_train['Id'] = paper_id\n        extended_train['pub_title'] = train.loc[train.Id == paper_id, 'pub_title']\n        extended_train['dataset_title'] = train.loc[train.Id == paper_id, 'dataset_title']\n        extended_train['dataset_label'] = train.loc[train.Id == paper_id, 'dataset_label']\n        extended_train['cleaned_label'] = train.loc[train.Id == paper_id, 'cleaned_label']\n        \n        extended_train['section_title'] = s['section_title']\n        extended_train['section_number'] = count\n        extended_train['text'] = s['text']\n        \n        df_list.append(pd.DataFrame(extended_train))\n        \ndf_extended = pd.concat(df_list, ignore_index = True)\ndf_extended = df_extended.sort_values(['Id', 'section_number'])\ndf_extended.shape\ndf_extended\n#adding cleaned_text column\n\ndef clean_text(txt):\n    return re.sub('[^A-Za-z0-9]+', ' ', str(txt).lower())\n\ndf_extended['cleaned_text'] = df_extended['text'].apply(clean_text)\n#adding a column indicating if a cleaned label is in the cleaned text with bool\ndf_extended['label_match'] = df_extended.apply(lambda x:x.cleaned_label in x.cleaned_text, axis =1)\ndf_extended.groupby('dataset_title').dataset_label.unique().apply(len)\ndf_extended.groupby('dataset_title').cleaned_label.unique().apply(len)\ndf_extended.head()\ndf_extended.to_pickle(\"coleridge_train_extended.pkl\")","meta":"{'source': 'AI4Code', 'id': 'dfe73e46b86006'}"}
{"id":"14233","text":"\"\"\"\n## [1. Custom Callback Definition and Use](#callback) ##\n## [2. Import Needed Modules](#import) ##\n## [3. Create code for Custom Callback](#code) ## \n## [4. Define Support Functions](#functions) ##\n## [5. Input an Image and get image shape](#image) ## \n## [6. Read in Image files and Create Train-Test_Valid Data Frames](#data) ## \n## [7. Evaluate train_df class sample balance](#balance) ## \n## [8. Create train, test and validation generators](#generators) ## \n## [9. Show Training Image Samples](#show) ## \n## [10. Create the Model](#model) ## \n## [11. Instantiate Callback and Train the Model](#train) ## \n## [12. Plot Training Data, Evaluate and Save the Model](#plot) ##\n## [13. Make Predictions on Test Set and Create Confusion Matrix and Classification Report](#predict) ##\n## [14. How to use trained model for classification](#classify) ##\n\"\"\"\n\"\"\"\n<a id=\"callback\"><\/a>\n# <center>Custom Callback Definition and Use<\/center>\n\"\"\"\n\"\"\"\n### **This notebook contains a custom callback you may wish to copy and use  \nIt is a combination of the Keras callbacks Reduce Learning Rate on Plateau,  \nEarly Stopping and Model Checkpoint but eliminates some of the limitations  \nof each. In addition it provides an easier to read summary of the model's  \nperformance at the end of each epoch. It also provides a handy feature  \nthat enables you to set the number of epochs to train for until a message  \nasks if you wish to halt training on the current epoch by entering H or  \nto enter an integer which will determine how many more epochs to run  \nbefore the message appears again. This is very useful if you are training  \na model and decide the metrics are satisfactory and you want to end  \nthe model training early. Note the callback always returns your model  \nwith the weights set to those of the epoch which had the highest performance  \non the metric being monitored (accuracy or validation accuracy)  \nThe callback initially monitors training accuracy and will adjust the learning  \nrate based on that until the accuracy reaches a user specified threshold  \nlevel. Once that level of training accuracy is achieved the callback switches  \nto monitoring validation loss and adjusts the learning rate based on that.  \nthe callback is of the form:  \ncallbacks=[LRA(model, base_model, patience, stop_patience, threshold,factor, dwell,\n              batches, initial_epoch, epochs, ask_epoch )]    \n **where:**\n - **model** is your compiled model  \n - **base_model** is the name of your base_model if you are doing transfer learning.  \n      for example you might have in your model  \n      base_model=tf.keras.applications.EfficientNetB1(include_top=False, weights=\"imagenet\",input_shape=img_shape, pooling='max')\n      base_model.trainabel=False   During training you will be asked if you want to do fine tuning  \n      If you enter F to the query, the base_model will be set to trainable by the callback\n      If you are not doing transfer learning set base_model==None\n - **patience** is an integer that determines many consecutive epochs can occur before the learning rate\n   will be adjusted (similar to patience parameter in Reduce Learning Rate on Plateau)\n \n - **stop_patience** is an integer that determines hom many consecutive epochs for which the\n   learning rate was adjusted but no improvement in the monitored metric occurred before\n   training is halted(similar to patience parameter in early stopping)\n \n - **threshold** is a float that determines the level that training accuracy must achieve\n   before the callback switches over to monitoring validation loss. This  is useful for\n   cases where the validation loss in early epochs tends to vary widely and can cause\n   unwanted behavior when using the conventional Keras callbacks\n - **factor** is a float that determines the new learning rate by the equation lr=lr*factor.\n   (similar to the factor parameter in Reduce Learning Rate on Plateau)\n - **dwell** is a boolean. It is used in the callback as part of an experiment on training\n   models. If on a given epoch the metric being monitored fails to improve it means\n   your model has moved to a location on the surface of Nspace (where N is the number\n   of trainable parameters) that is NOT as favorable (poorer metric performance) than\n   the position in Nspace you were in for the previous epoch. If dwell is set to True\n   the callback loads the model with the weights from the previous (better metric value)\n   epoch. Why move to a worse place if the place you were in previously was better. Then\n   the learning rate is reduced for the next epoch of training. If dwell is set to false\n   this action does not take place.\n - **batches** is an integer. It should be set to a value of \n   batches=int(number of traing samples\/batch_size). During training the callback provides\n   information during an epoch of the form\n   'processing batch of batches  accuracy= accuracy  loss= loss where batch is the current \n    batch being processs, batches is as described above, accuracy is the current training\n    accuracy and loss is the current loss. Typically the message would appear as\n    processing batch 25 of 50  accuracy: 54%  loss: .04567. As each batch is processed\n    these values are changed.    \n - **initial_epoch** is an integer. Typically set this to zero Itis used in the information\n    printed out for each epoch. In the case where you train the model say with the\n    basemodel weights frozen say you train for 10 epochs. Then you want to fine tune\n    the model and train for more eppochs for the second training session you would\n    reinstantiate the callback and set initial_epoch=10.\n - **epochs** an integer value for the number of epochs to train\n - **ask_epoch** is either set to an integer value or None. If set to an integer it denotes\n    the epoch number at which user input is requested. If the user enter H training is\n    halted. If the user inters an integer it represents how many more epochs to run\n    before you are asked for the user input again. If the user enters F the base_model\n    is made trainable If ask_epoch is set to None the\n    user is NOT asked to provide any input. This feature is handy is when training your model\n    and the metrics are either unsatisfactory and you want to stop training, or for the case\n    where your metrics are satisfactory and there is no need to train any further. Note\n    you model is always set to the weights for the epoch that had the beset metric\n    performance. So if you halt the training you can still use the model for predictions.  \n      \n### ** Example of Use:\n callbacks=[LRA(model=my_model, base_model=base_model, patience=1,stop_patience=3,  \n            threshold=.9, factor=.5, dwell=True,batches=85, initial_epoch=0 , epochs=20, ask_epoch=5)]\n this implies:\n - your model is my_model\n - base_model is the name of your base_model if you are doing transfer learning\n - after 1 epoch of no improvement the learning rate will be reduced\n - after 3 consecutive adjustment of the leaarning rate with no metric improve training terminates\n - once the training accuracy reaches 90% the callback adjust learning rate based on validation loss\n - when the learning rate is adjust the new learning rate is .5 X learning rate\n - if the current epoch's metric value did not improve, the weights for the prior epoch are loaded\n   and the learning rate is reduced\n - 85 batches of data are run to complete an epoch \n - the initial epoch is 0\n - train for 20 epochs\n - after the fifth epoch you will be asked if you want to halt training by entering H or enter \n   an integer denoting how many more epochs to run before you will be prompted again or enter\n   F to make the base_model=trainable\n\"\"\"\n\"\"\"\n<a id=\"import\"><\/a>\n# <center>Import Need Modules<\/center>\n\"\"\"\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.layers import Dense, Activation,Dropout,Conv2D, MaxPooling2D,BatchNormalization, Flatten\nfrom tensorflow.keras.optimizers import Adam, Adamax\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Model, load_model, Sequential\nimport numpy as np\nimport pandas as pd\nimport shutil\nimport time\nimport cv2 as cv2\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\nimport seaborn as sns\nsns.set_style('darkgrid')\nfrom PIL import Image\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom IPython.core.display import display, HTML\n# stop annoying tensorflow warning messages\nimport logging\nlogging.getLogger(\"tensorflow\").setLevel(logging.ERROR)\nprint ('modules loaded')\n\"\"\"\n<a id=\"functions\"><\/a>\n# <center>Define Needed Support Functions<\/center>\n\"\"\"\n\"\"\"\n### Define a function to show example training images\n\"\"\"\ndef show_image_samples(gen ):\n    t_dict=gen.class_indices\n    classes=list(t_dict.keys())    \n    images,labels=next(gen) # get a sample batch from the generator \n    plt.figure(figsize=(20, 20))\n    length=len(labels)\n    if length<25:   #show maximum of 25 images\n        r=length\n    else:\n        r=25\n    for i in range(r):\n        plt.subplot(5, 5, i + 1)\n        image=images[i]\/255\n        plt.imshow(image)\n        index=np.argmax(labels[i])\n        class_name=classes[index]\n        plt.title(class_name, color='blue', fontsize=12)\n        plt.axis('off')\n    plt.show()\ndef show_images(tdir):\n    classlist=os.listdir(tdir)\n    length=len(classlist)\n    columns=5\n    rows=int(np.ceil(length\/columns))    \n    plt.figure(figsize=(20, rows * 4))\n    for i, klass in enumerate(classlist):    \n        classpath=os.path.join(tdir, klass)\n        imgpath=os.path.join(classpath, '1.jpg')\n        img=plt.imread(imgpath)\n        plt.subplot(rows, columns, i+1)\n        plt.axis('off')\n        plt.title(klass, color='blue', fontsize=12)\n        plt.imshow(img)\n    \n\"\"\"\n### Define  a function to print text in RGB foreground and background colors\n\"\"\"\ndef print_in_color(txt_msg,fore_tupple,back_tupple,):\n    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple \n    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)\n    rf,gf,bf=fore_tupple\n    rb,gb,bb=back_tupple\n    msg='{0}' + txt_msg\n    mat='\\33[38;2;' + str(rf) +';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) +'m' \n    print(msg .format(mat), flush=True)\n    print('\\33[0m', flush=True) # returns default print color to back to black\n    return\n\"\"\"\n<a id=\"code\"><\/a>\n# <center>Define code for custom callback<\/center>\n\"\"\"\nclass LRA(keras.callbacks.Callback):\n    def __init__(self,model, base_model, patience,stop_patience, threshold, factor, dwell, batches, initial_epoch,epochs, ask_epoch):\n        super(LRA, self).__init__()\n        self.model=model\n        self.base_model=base_model\n        self.patience=patience # specifies how many epochs without improvement before learning rate is adjusted\n        self.stop_patience=stop_patience # specifies how many times to adjust lr without improvement to stop training\n        self.threshold=threshold # specifies training accuracy threshold when lr will be adjusted based on validation loss\n        self.factor=factor # factor by which to reduce the learning rate\n        self.dwell=dwell\n        self.batches=batches # number of training batch to runn per epoch\n        self.initial_epoch=initial_epoch\n        self.epochs=epochs\n        self.ask_epoch=ask_epoch\n        self.ask_epoch_initial=ask_epoch # save this value to restore if restarting training\n        # callback variables \n        self.count=0 # how many times lr has been reduced without improvement\n        self.stop_count=0        \n        self.best_epoch=1   # epoch with the lowest loss        \n        self.initial_lr=float(tf.keras.backend.get_value(model.optimizer.lr)) # get the initiallearning rate and save it         \n        self.highest_tracc=0.0 # set highest training accuracy to 0 initially\n        self.lowest_vloss=np.inf # set lowest validation loss to infinity initially\n        self.best_weights=self.model.get_weights() # set best weights to model's initial weights\n        self.initial_weights=self.model.get_weights()   # save initial weights if they have to get restored \n        \n    def on_train_begin(self, logs=None):        \n        if self.base_model != None:\n            status=base_model.trainable\n            if status:\n                msg=' initializing callback starting training with base_model trainable'\n            else:\n                msg='initializing callback starting training with base_model not trainable'\n        else:\n            msg='initialing callback and starting training'                        \n        print_in_color (msg, (244, 252, 3), (55,65,80)) \n        msg='{0:^8s}{1:^10s}{2:^9s}{3:^9s}{4:^9s}{5:^9s}{6:^9s}{7:^10s}{8:10s}{9:^8s}'.format('Epoch', 'Loss', 'Accuracy',\n                                                                                              'V_loss','V_acc', 'LR', 'Next LR', 'Monitor','% Improv', 'Duration')\n        print_in_color(msg, (244,252,3), (55,65,80)) \n        self.start_time= time.time()\n        \n    def on_train_end(self, logs=None):\n        stop_time=time.time()\n        tr_duration= stop_time- self.start_time            \n        hours = tr_duration \/\/ 3600\n        minutes = (tr_duration - (hours * 3600)) \/\/ 60\n        seconds = tr_duration - ((hours * 3600) + (minutes * 60))\n\n        self.model.set_weights(self.best_weights) # set the weights of the model to the best weights\n        msg=f'Training is completed - model is set with weights from epoch {self.best_epoch} '\n        print_in_color(msg, (0,255,0), (55,65,80))\n        msg = f'training elapsed time was {str(hours)} hours, {minutes:4.1f} minutes, {seconds:4.2f} seconds)'\n        print_in_color(msg, (0,255,0), (55,65,80))   \n        \n    def on_train_batch_end(self, batch, logs=None):\n        acc=logs.get('accuracy')* 100  # get training accuracy \n        loss=logs.get('loss')\n        msg='{0:20s}processing batch {1:4s} of {2:5s} accuracy= {3:8.3f}  loss: {4:8.5f}'.format(' ', str(batch), str(self.batches), acc, loss)\n        print(msg, '\\r', end='') # prints over on the same line to show running batch count        \n        \n    def on_epoch_begin(self,epoch, logs=None):\n        self.now= time.time()\n        \n    def on_epoch_end(self, epoch, logs=None):  # method runs on the end of each epoch\n        later=time.time()\n        duration=later-self.now \n        lr=float(tf.keras.backend.get_value(self.model.optimizer.lr)) # get the current learning rate\n        current_lr=lr\n        v_loss=logs.get('val_loss')  # get the validation loss for this epoch\n        acc=logs.get('accuracy')  # get training accuracy \n        v_acc=logs.get('val_accuracy')\n        loss=logs.get('loss')        \n        if acc < self.threshold: # if training accuracy is below threshold adjust lr based on training accuracy\n            monitor='accuracy'\n            if epoch ==0:\n                pimprov=0.0\n            else:\n                pimprov= (acc-self.highest_tracc )*100\/self.highest_tracc\n            if acc>self.highest_tracc: # training accuracy improved in the epoch                \n                self.highest_tracc=acc # set new highest training accuracy\n                self.best_weights=self.model.get_weights() # traing accuracy improved so save the weights\n                self.count=0 # set count to 0 since training accuracy improved\n                self.stop_count=0 # set stop counter to 0\n                if v_loss<self.lowest_vloss:\n                    self.lowest_vloss=v_loss\n                color= (0,255,0)\n                self.best_epoch=epoch + 1  # set the value of best epoch for this epoch              \n            else: \n                # training accuracy did not improve check if this has happened for patience number of epochs\n                # if so adjust learning rate\n                if self.count>=self.patience -1: # lr should be adjusted\n                    color=(245, 170, 66)\n                    lr= lr* self.factor # adjust the learning by factor\n                    tf.keras.backend.set_value(self.model.optimizer.lr, lr) # set the learning rate in the optimizer\n                    self.count=0 # reset the count to 0\n                    self.stop_count=self.stop_count + 1 # count the number of consecutive lr adjustments\n                    self.count=0 # reset counter\n                    if self.dwell:\n                        self.model.set_weights(self.best_weights) # return to better point in N space                        \n                    else:\n                        if v_loss<self.lowest_vloss:\n                            self.lowest_vloss=v_loss                                    \n                else:\n                    self.count=self.count +1 # increment patience counter                    \n        else: # training accuracy is above threshold so adjust learning rate based on validation loss\n            monitor='val_loss'\n            if epoch ==0:\n                pimprov=0.0\n            else:\n                pimprov= (self.lowest_vloss- v_loss )*100\/self.lowest_vloss\n            if v_loss< self.lowest_vloss: # check if the validation loss improved \n                self.lowest_vloss=v_loss # replace lowest validation loss with new validation loss                \n                self.best_weights=self.model.get_weights() # validation loss improved so save the weights\n                self.count=0 # reset count since validation loss improved  \n                self.stop_count=0  \n                color=(0,255,0)                \n                self.best_epoch=epoch + 1 # set the value of the best epoch to this epoch\n            else: # validation loss did not improve\n                if self.count>=self.patience-1: # need to adjust lr\n                    color=(245, 170, 66)\n                    lr=lr * self.factor # adjust the learning rate                    \n                    self.stop_count=self.stop_count + 1 # increment stop counter because lr was adjusted \n                    self.count=0 # reset counter\n                    tf.keras.backend.set_value(self.model.optimizer.lr, lr) # set the learning rate in the optimizer\n                    if self.dwell:\n                        self.model.set_weights(self.best_weights) # return to better point in N space\n                else: \n                    self.count =self.count +1 # increment the patience counter                    \n                if acc>self.highest_tracc:\n                    self.highest_tracc= acc\n        msg=f'{str(epoch+1):^3s}\/{str(self.epochs):4s} {loss:^9.3f}{acc*100:^9.3f}{v_loss:^9.5f}{v_acc*100:^9.3f}{current_lr:^9.5f}{lr:^9.5f}{monitor:^11s}{pimprov:^10.2f}{duration:^8.2f}'\n        print_in_color (msg,color, (55,65,80))\n        if self.stop_count> self.stop_patience - 1: # check if learning rate has been adjusted stop_count times with no improvement\n            msg=f' training has been halted at epoch {epoch + 1} after {self.stop_patience} adjustments of learning rate with no improvement'\n            print_in_color(msg, (0,255,255), (55,65,80))\n            self.model.stop_training = True # stop training\n        else: \n            if self.ask_epoch !=None:\n                if epoch + 1 >= self.ask_epoch:\n                    if base_model.trainable:\n                        msg='enter H to halt training or an integer for number of epochs to run then ask again'\n                    else:\n                        msg='enter H to halt training ,F to fine tune model, or an integer for number of epochs to run then ask again'\n                    print_in_color(msg, (0,255,255), (55,65,80))\n                    ans=input('')\n                    if ans=='H' or ans=='h':\n                        msg=f'training has been halted at epoch {epoch + 1} due to user input'\n                        print_in_color(msg, (0,255,255), (55,65,80))\n                        self.model.stop_training = True # stop training\n                    elif ans == 'F' or ans=='f':\n                        if base_model.trainable:\n                            msg='base_model is already set as trainable'\n                        else:\n                            msg='setting base_model as trainable for fine tuning of model'\n                            self.base_model.trainable=True\n                        print_in_color(msg, (0, 255,255), (55,65,80))\n                        msg='{0:^8s}{1:^10s}{2:^9s}{3:^9s}{4:^9s}{5:^9s}{6:^9s}{7:^10s}{8:^8s}'.format('Epoch', 'Loss', 'Accuracy',\n                                                                                              'V_loss','V_acc', 'LR', 'Next LR', 'Monitor','% Improv', 'Duration')\n                        print_in_color(msg, (244,252,3), (55,65,80))                         \n                        self.count=0\n                        self.stop_count=0                        \n                        self.ask_epoch = epoch + 1 + self.ask_epoch_initial \n                        \n                    else:\n                        ans=int(ans)\n                        self.ask_epoch +=ans\n                        msg=f' training will continue until epoch ' + str(self.ask_epoch)                         \n                        print_in_color(msg, (0, 255,255), (55,65,80))\n                        msg='{0:^8s}{1:^10s}{2:^9s}{3:^9s}{4:^9s}{5:^9s}{6:^9s}{7:^10s}{8:10s}{9:^8s}'.format('Epoch', 'Loss', 'Accuracy',\n                                                                                              'V_loss','V_acc', 'LR', 'Next LR', 'Monitor','% Improv', 'Duration')\n                        print_in_color(msg, (244,252,3), (55,65,80)) \n\"\"\"\n### Define a function to plot the training data\n\"\"\"\ndef tr_plot(tr_data, start_epoch):\n    #Plot the training and validation data\n    tacc=tr_data.history['accuracy']\n    tloss=tr_data.history['loss']\n    vacc=tr_data.history['val_accuracy']\n    vloss=tr_data.history['val_loss']\n    Epoch_count=len(tacc)+ start_epoch\n    Epochs=[]\n    for i in range (start_epoch ,Epoch_count):\n        Epochs.append(i+1)   \n    index_loss=np.argmin(vloss)#  this is the epoch with the lowest validation loss\n    val_lowest=vloss[index_loss]\n    index_acc=np.argmax(vacc)\n    acc_highest=vacc[index_acc]\n    plt.style.use('fivethirtyeight')\n    sc_label='best epoch= '+ str(index_loss+1 +start_epoch)\n    vc_label='best epoch= '+ str(index_acc + 1+ start_epoch)\n    fig,axes=plt.subplots(nrows=1, ncols=2, figsize=(20,8))\n    axes[0].plot(Epochs,tloss, 'r', label='Training loss')\n    axes[0].plot(Epochs,vloss,'g',label='Validation loss' )\n    axes[0].scatter(index_loss+1 +start_epoch,val_lowest, s=150, c= 'blue', label=sc_label)\n    axes[0].set_title('Training and Validation Loss')\n    axes[0].set_xlabel('Epochs')\n    axes[0].set_ylabel('Loss')\n    axes[0].legend()\n    axes[1].plot (Epochs,tacc,'r',label= 'Training Accuracy')\n    axes[1].plot (Epochs,vacc,'g',label= 'Validation Accuracy')\n    axes[1].scatter(index_acc+1 +start_epoch,acc_highest, s=150, c= 'blue', label=vc_label)\n    axes[1].set_title('Training and Validation Accuracy')\n    axes[1].set_xlabel('Epochs')\n    axes[1].set_ylabel('Accuracy')\n    axes[1].legend()\n    plt.tight_layout\n    #plt.style.use('fivethirtyeight')\n    plt.show()\n\n\"\"\"\n### define a function to create confusion matrix and classification report\n\"\"\"\ndef print_info( test_gen, preds, print_code, save_dir, subject ):\n    class_dict=test_gen.class_indices\n    labels= test_gen.labels\n    file_names= test_gen.filenames \n    error_list=[]\n    true_class=[]\n    pred_class=[]\n    prob_list=[]\n    new_dict={}\n    error_indices=[]\n    y_pred=[]\n    for key,value in class_dict.items():\n        new_dict[value]=key             # dictionary {integer of class number: string of class name}\n    # store new_dict as a text fine in the save_dir\n    classes=list(new_dict.values())     # list of string of class names     \n    errors=0      \n    for i, p in enumerate(preds):\n        pred_index=np.argmax(p)         \n        true_index=labels[i]  # labels are integer values\n        if pred_index != true_index: # a misclassification has occurred\n            error_list.append(file_names[i])\n            true_class.append(new_dict[true_index])\n            pred_class.append(new_dict[pred_index])\n            prob_list.append(p[pred_index])\n            error_indices.append(true_index)            \n            errors=errors + 1\n        y_pred.append(pred_index)    \n    if print_code !=0:\n        if errors>0:\n            if print_code>errors:\n                r=errors\n            else:\n                r=print_code           \n            msg='{0:^28s}{1:^28s}{2:^28s}{3:^16s}'.format('Filename', 'Predicted Class' , 'True Class', 'Probability')\n            print_in_color(msg, (0,255,0),(55,65,80))\n            for i in range(r):                \n                split1=os.path.split(error_list[i])                \n                split2=os.path.split(split1[0])                \n                fname=split2[1] + '\/' + split1[1]\n                msg='{0:^28s}{1:^28s}{2:^28s}{3:4s}{4:^6.4f}'.format(fname, pred_class[i],true_class[i], ' ', prob_list[i])\n                print_in_color(msg, (255,255,255), (55,65,60))\n                #print(error_list[i]  , pred_class[i], true_class[i], prob_list[i])               \n        else:\n            msg='With accuracy of 100 % there are no errors to print'\n            print_in_color(msg, (0,255,0),(55,65,80))\n    if errors>0:\n        plot_bar=[]\n        plot_class=[]\n        for  key, value in new_dict.items():        \n            count=error_indices.count(key) \n            if count!=0:\n                plot_bar.append(count) # list containg how many times a class c had an error\n                plot_class.append(value)   # stores the class \n        fig=plt.figure()\n        fig.set_figheight(len(plot_class)\/3)\n        fig.set_figwidth(10)\n        plt.style.use('fivethirtyeight')\n        for i in range(0, len(plot_class)):\n            c=plot_class[i]\n            x=plot_bar[i]\n            plt.barh(c, x, )\n            plt.title( ' Errors by Class on Test Set')\n    y_true= np.array(labels)        \n    y_pred=np.array(y_pred)\n    if len(classes)<= 30:\n        # create a confusion matrix \n        cm = confusion_matrix(y_true, y_pred )        \n        length=len(classes)\n        if length<8:\n            fig_width=8\n            fig_height=8\n        else:\n            fig_width= int(length * .5)\n            fig_height= int(length * .5)\n        plt.figure(figsize=(fig_width, fig_height))\n        sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False)       \n        plt.xticks(np.arange(length)+.5, classes, rotation= 90)\n        plt.yticks(np.arange(length)+.5, classes, rotation=0)\n        plt.xlabel(\"Predicted\")\n        plt.ylabel(\"Actual\")\n        plt.title(\"Confusion Matrix\")\n        plt.show()\n    clr = classification_report(y_true, y_pred, target_names=classes)\n    print(\"Classification Report:\\n----------------------\\n\", clr)\n\"\"\"\n### define a function to save the model and the associated class_dict.csv file\n\"\"\"\ndef saver(save_path, model, model_name, subject, accuracy,img_size, scalar, generator):\n    print ('the save path is: ', save_path)\n    # first save the model\n    save_id=str (model_name +  '-' + subject +'-'+ str(acc)[:str(acc).rfind('.')+3] + '.h5')\n    model_save_loc=os.path.join(save_path, save_id)\n    model.save(model_save_loc)\n    print_in_color ('model was saved as ' + model_save_loc, (0,255,0),(55,65,80)) \n    # now create the class_df and convert to csv file    \n    class_dict=generator.class_indices \n    height=[]\n    width=[]\n    scale=[]\n    for i in range(len(class_dict)):\n        height.append(img_size[0])\n        width.append(img_size[1])\n        scale.append(scalar)\n    Index_series=pd.Series(list(class_dict.values()), name='class_index')\n    Class_series=pd.Series(list(class_dict.keys()), name='class') \n    Height_series=pd.Series(height, name='height')\n    Width_series=pd.Series(width, name='width')\n    Scale_series=pd.Series(scale, name='scale by')\n    class_df=pd.concat([Index_series, Class_series, Height_series, Width_series, Scale_series], axis=1)    \n    csv_name='class_dict.csv'\n    csv_save_loc=os.path.join(save_path, csv_name)\n    class_df.to_csv(csv_save_loc, index=False) \n    print_in_color ('class csv file was saved as ' + csv_save_loc, (0,255,0),(55,65,80)) \n    return model_save_loc, csv_save_loc\n\"\"\"\n### define a function that uses the trained model and the\n### class_dict.csv file to predict images\n\"\"\"\ndef predictor(sdir, csv_path,  model_path, averaged=True, verbose=True):    \n    # read in the csv file\n    class_df=pd.read_csv(csv_path)    \n    class_count=len(class_df['class'].unique())\n    img_height=int(class_df['height'].iloc[0])\n    img_width =int(class_df['width'].iloc[0])\n    img_size=(img_width, img_height)    \n    scale=class_df['scale by'].iloc[0] \n    image_list=[]\n    # determine value to scale image pixels by\n    try: \n        s=int(scale)\n        s2=1\n        s1=0\n    except:\n        split=scale.split('-')\n        s1=float(split[1])\n        s2=float(split[0].split('*')[1])\n    path_list=[]\n    paths=os.listdir(sdir)    \n    for f in paths:\n        path_list.append(os.path.join(sdir,f))\n    if verbose:\n        print (' Model is being loaded- this will take about 10 seconds')\n    model=load_model(model_path)\n    image_count=len(path_list) \n    image_list=[]\n    file_list=[]\n    good_image_count=0\n    for i in range (image_count):        \n        try:\n            img=cv2.imread(path_list[i])\n            img=cv2.resize(img, img_size)\n            img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)            \n            good_image_count +=1\n            img=img*s2 - s1             \n            image_list.append(img)\n            file_name=os.path.split(path_list[i])[1]\n            file_list.append(file_name)\n        except:\n            if verbose:\n                print ( path_list[i], ' is an invalid image file')\n    if good_image_count==1: # if only a single image need to expand dimensions\n        averaged=True\n    image_array=np.array(image_list)    \n    # make predictions on images, sum the probabilities of each class then find class index with\n    # highest probability\n    preds=model.predict(image_array)    \n    if averaged:\n        psum=[]\n        for i in range (class_count): # create all 0 values list\n            psum.append(0)    \n        for p in preds: # iterate over all predictions\n            for i in range (class_count):\n                psum[i]=psum[i] + p[i]  # sum the probabilities   \n        index=np.argmax(psum) # find the class index with the highest probability sum        \n        klass=class_df['class'].iloc[index] # get the class name that corresponds to the index\n        prob=psum[index]\/good_image_count  # get the probability average         \n        # to show the correct image run predict again and select first image that has same index\n        for img in image_array:  #iterate through the images    \n            test_img=np.expand_dims(img, axis=0) # since it is a single image expand dimensions \n            test_index=np.argmax(model.predict(test_img)) # for this image find the class index with highest probability\n            if test_index== index: # see if this image has the same index as was selected previously\n                if verbose: # show image and print result if verbose=1\n                    plt.axis('off')\n                    plt.imshow(img) # show the image\n                    print (f'predicted species is {klass} with a probability of {prob:6.4f} ')\n                break # found an image that represents the predicted class      \n        return klass, prob, img, None\n    else: # create individual predictions for each image\n        pred_class=[]\n        prob_list=[]\n        for i, p in enumerate(preds):\n            index=np.argmax(p) # find the class index with the highest probability sum\n            klass=class_df['class'].iloc[index] # get the class name that corresponds to the index\n            image_file= file_list[i]\n            pred_class.append(klass)\n            prob_list.append(p[index])            \n        Fseries=pd.Series(file_list, name='image file')\n        Lseries=pd.Series(pred_class, name= 'species')\n        Pseries=pd.Series(prob_list, name='probability')\n        df=pd.concat([Fseries, Lseries, Pseries], axis=1)\n        if verbose:\n            length= len(df)\n            print (df.head(length))\n        return None, None, None, df\n\"\"\"\n### define a function tha takes in a dataframe df, and integer max_size and a string column\n### and returns a dataframe where the number of samples for any class specified by column\n### is limited to max samples\n\"\"\"\ndef trim (df, max_size, min_size, column):\n    df=df.copy()\n    original_class_count= len(list(df[column].unique()))\n    print ('Original Number of classes in dataframe: ', original_class_count)\n    sample_list=[] \n    groups=df.groupby(column)\n    for label in df[column].unique():        \n        group=groups.get_group(label)\n        sample_count=len(group)         \n        if sample_count> max_size :\n            strat=group[column]\n            samples,_=train_test_split(group, train_size=max_size, shuffle=True, random_state=123, stratify=strat)            \n            sample_list.append(samples)\n        elif sample_count>= min_size:\n            sample_list.append(group)\n    df=pd.concat(sample_list, axis=0).reset_index(drop=True)\n    final_class_count= len(list(df[column].unique())) \n    if final_class_count != original_class_count:\n        print ('*** WARNING***  dataframe has a reduced number of classes' )\n    balance=list(df[column].value_counts())\n    print (balance)\n    return df\n\"\"\"\n### define a function that takes in a dataframe, and integers max_samples, min_samples. \nit uses the function trim to set the maximum number of samples in a class defined by the string column to max_samples.\nif the number of samples is less than min_samples the class is eliminated from the dataset. If some classes have\nless than max_samples, then augmented images are created for that class  and stored in the working_dir so the class\nwill have max_samples of images.  After augmentation an aug_df is created for the augmented images in the\nworking_dir. The aug_df is then merged with the original train_df to produce a new train_df that has exactly\nmax_sample images in each class thus creating a balanced training set.\n\"\"\"\ndef balance(train_df,max_samples, min_samples, column, working_dir, image_size):\n    train_df=train_df.copy()\n    train_df=trim (train_df, max_samples, min_samples, column)    \n    # make directories to store augmented images\n    aug_dir=os.path.join(working_dir, 'aug')\n    if os.path.isdir(aug_dir):\n        shutil.rmtree(aug_dir)\n    os.mkdir(aug_dir)\n    for label in train_df['labels'].unique():    \n        dir_path=os.path.join(aug_dir,label)    \n        os.mkdir(dir_path)\n    # create and store the augmented images  \n    total=0\n    gen=ImageDataGenerator(horizontal_flip=True,  rotation_range=20, width_shift_range=.2,\n                                  height_shift_range=.2, zoom_range=.2)\n    groups=train_df.groupby('labels') # group by class\n    for label in train_df['labels'].unique():  # for every class               \n        group=groups.get_group(label)  # a dataframe holding only rows with the specified label \n        sample_count=len(group)   # determine how many samples there are in this class  \n        if sample_count< max_samples: # if the class has less than target number of images\n            aug_img_count=0\n            delta=max_samples-sample_count  # number of augmented images to create\n            target_dir=os.path.join(aug_dir, label)  # define where to write the images    \n            aug_gen=gen.flow_from_dataframe( group,  x_col='filepaths', y_col=None, target_size=image_size,\n                                            class_mode=None, batch_size=1, shuffle=False, \n                                            save_to_dir=target_dir, save_prefix='aug-', color_mode='rgb',\n                                            save_format='jpg')\n            while aug_img_count<delta:\n                images=next(aug_gen)            \n                aug_img_count += len(images)\n            total +=aug_img_count\n    print('Total Augmented images created= ', total)\n    # create aug_df and merge with train_df to create composite training set ndf\n    if total>0:\n        aug_fpaths=[]\n        aug_labels=[]\n        classlist=os.listdir(aug_dir)\n        for klass in classlist:\n            classpath=os.path.join(aug_dir, klass)     \n            flist=os.listdir(classpath)    \n            for f in flist:        \n                fpath=os.path.join(classpath,f)         \n                aug_fpaths.append(fpath)\n                aug_labels.append(klass)\n        Fseries=pd.Series(aug_fpaths, name='filepaths')\n        Lseries=pd.Series(aug_labels, name='labels')\n        aug_df=pd.concat([Fseries, Lseries], axis=1)\n        train_df=pd.concat([train_df,aug_df], axis=0).reset_index(drop=True)\n   \n    print (list(train_df['labels'].value_counts()) )\n    return train_df \n\"\"\"\n<a id=\"image\"><\/a>\n# <center>Input an image and get the shape<\/center>\n\"\"\"\nimg_path=r'..\/input\/youssef-farouk-nslkdd-8020\/Youssef_Farouk_NSLKDD\/Train_16000\/Anomaly\/Train-20_DoS1.png'\nimg=plt.imread(img_path)\nprint (img.shape)\nimshow(img)\n\n\"\"\"\n<a id=\"data\"><\/a>\n# <center>Define preprocess function to read in image file and create dataframes<\/center>\n\"\"\"\ndef preprocess (sdir, trsplit, vsplit):\n    filepaths=[]\n    labels=[]    \n    classlist=os.listdir(sdir)\n    for klass in classlist:\n        classpath=os.path.join(sdir,klass)\n        flist=os.listdir(classpath)\n        for f in flist:\n            fpath=os.path.join(classpath,f)\n            filepaths.append(fpath)\n            labels.append(klass)\n    Fseries=pd.Series(filepaths, name='filepaths')\n    Lseries=pd.Series(labels, name='labels')\n    df=pd.concat([Fseries, Lseries], axis=1)            \n    dsplit=vsplit\/(1-trsplit)\n    strat=df['labels']\n    train_df, dummy_df=train_test_split(df, train_size=trsplit, shuffle=True, random_state=123, stratify=strat)\n    strat=dummy_df['labels']\n    valid_df, test_df= train_test_split(dummy_df, train_size=dsplit, shuffle=True, random_state=123, stratify=strat)\n    print('train_df length: ', len(train_df), '  test_df length: ',len(test_df), '  valid_df length: ', len(valid_df))\n     # check that each dataframe has the same number of classes to prevent model.fit errors\n    trcount=len(train_df['labels'].unique())\n    tecount=len(test_df['labels'].unique())\n    vcount=len(valid_df['labels'].unique())\n    if trcount < tecount :         \n        msg='** WARNING ** number of classes in training set is less than the number of classes in test set'\n        print_in_color(msg, (255,0,0), (55,65,80))\n        msg='This will throw an error in either model.evaluate or model.predict'\n        print_in_color(msg, (255,0,0), (55,65,80))\n    if trcount != vcount:\n        msg='** WARNING ** number of classes in training set not equal to number of classes in validation set' \n        print_in_color(msg, (255,0,0), (55,65,80))\n        msg=' this will throw an error in model.fit'\n        print_in_color(msg, (255,0,0), (55,65,80))\n        print ('train df class count: ', trcount, 'test df class count: ', tecount, ' valid df class count: ', vcount) \n        ans=input('Enter C to continue execution or H to halt execution')\n        if ans =='H' or ans == 'h':\n            print_in_color('Halting Execution', (255,0,0), (55,65,80))\n            import sys\n            sys.exit('program halted by user')            \n    print(list(train_df['labels'].value_counts()))\n    return train_df, test_df, valid_df\n    \nsdir=r'..\/input\/youssef-farouk-nslkdd-8020\/Youssef_Farouk_NSLKDD\/Train_16000'\ntrsplit=.9\nvsplit=.05\ntrain_df, test_df, valid_df= preprocess(sdir,trsplit, vsplit)\n\"\"\"\n<a id=\"balance\"><\/a>\n# <center>Determne train df class sample balance and adjust if necessary<\/center>\n\"\"\"\n\"\"\"\n### The train data set is  balanced. However it is very large. Use the trim function\n### to reduce sampls per class to 2000.\n\"\"\"\nmax_samples= 2000\nmin_samples=0\ncolumn='labels'\nworking_dir = r'.\/'\nimg_size=(128,128)\ntrain_df=trim(train_df, max_samples, min_samples, column)\n\"\"\"\n### The train_df dataframe is now balanced with 2000 samples per class\n\"\"\"\n\"\"\"\n<a id=\"generators\"><\/a>\n# <center>Create train, test and validation generators<\/center>\n\"\"\"\nchannels=3\nbatch_size=40\nimg_shape=(img_size[0], img_size[1], channels)\nlength=len(test_df)\ntest_batch_size=sorted([int(length\/n) for n in range(1,length+1) if length % n ==0 and length\/n<=80],reverse=True)[0]  \ntest_steps=int(length\/test_batch_size)\nprint ( 'test batch size: ' ,test_batch_size, '  test steps: ', test_steps)\ndef scalar(img):    \n    return img  # EfficientNet expects pixelsin range 0 to 255 so no scaling is required\ntrgen=ImageDataGenerator(preprocessing_function=scalar, horizontal_flip=True)\ntvgen=ImageDataGenerator(preprocessing_function=scalar)\nmsg='                                                              for the train generator'\nprint(msg, '\\r', end='') \ntrain_gen=trgen.flow_from_dataframe( train_df, x_col='filepaths', y_col='labels', target_size=img_size, class_mode='categorical',\n                                    color_mode='rgb', shuffle=True, batch_size=batch_size)\nmsg='                                                              for the test generator'\nprint(msg, '\\r', end='') \ntest_gen=tvgen.flow_from_dataframe( test_df, x_col='filepaths', y_col='labels', target_size=img_size, class_mode='categorical',\n                                    color_mode='rgb', shuffle=False, batch_size=test_batch_size)\nmsg='                                                             for the validation generator'\nprint(msg, '\\r', end='')\nvalid_gen=tvgen.flow_from_dataframe( valid_df, x_col='filepaths', y_col='labels', target_size=img_size, class_mode='categorical',\n                                    color_mode='rgb', shuffle=True, batch_size=batch_size)\nclasses=list(train_gen.class_indices.keys())\nclass_count=len(classes)\ntrain_steps=int(np.ceil(len(train_gen.labels)\/batch_size))\n\"\"\"\n<a id=\"show\"><\/a>\n# <center>Display some training images\/center>\n\"\"\"\nshow_image_samples(train_gen)\n\"\"\"\n<a id=\"model\"><\/a>\n# <center>Create and Compile the Model<\/center>\n\"\"\"\nmodel_name='EfficientNetB3'\nbase_model=tf.keras.applications.EfficientNetB3(include_top=False, weights=\"imagenet\",input_shape=img_shape, pooling='max') \nx=base_model.output\nx=keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)\nx = Dense(256, kernel_regularizer = regularizers.l2(l = 0.016),activity_regularizer=regularizers.l1(0.006),\n                bias_regularizer=regularizers.l1(0.006) ,activation='relu')(x)\nx=Dropout(rate=.45, seed=123)(x)        \noutput=Dense(class_count, activation='softmax')(x)\nmodel=Model(inputs=base_model.input, outputs=output)\nmodel.compile(Adamax(learning_rate=.001), loss='categorical_crossentropy', metrics=['accuracy']) \n\"\"\"\n<a id=\"train\"><\/a>\n# <center>Instantiate the Custom Callback and train the model<\/center>\n\"\"\"\nepochs =40\npatience= 1 # number of epochs to wait to adjust lr if monitored value does not improve\nstop_patience =3 # number of epochs to wait before stopping training if monitored value does not improve\nthreshold=.9 # if train accuracy is < threshhold adjust monitor accuracy, else monitor validation loss\nfactor=.5 # factor to reduce lr by\ndwell=True # experimental, if True and monitored metric does not improve on current epoch set  modelweights back to weights of previous epoch\nfreeze=False # if true free weights of  the base model\nask_epoch=5# number of epochs to run before asking if you want to halt training\nbatches=train_steps\ncallbacks=[LRA(model=model,base_model= base_model,patience=patience,stop_patience=stop_patience, threshold=threshold,\n                   factor=factor,dwell=dwell, batches=batches,initial_epoch=0,epochs=epochs, ask_epoch=ask_epoch )]\nhistory=model.fit(x=train_gen,  epochs=epochs, verbose=0, callbacks=callbacks,  validation_data=valid_gen,\n               validation_steps=None,  shuffle=False,  initial_epoch=0)\n\"\"\"\n<a id=\"plot\"><\/a>\n# <center>Plot training data, evaluate and save the model<\/center>\n\"\"\"\ntr_plot(history,0)\nsubject='patterns'\nacc=model.evaluate( test_gen, verbose=1, steps=test_steps, return_dict=False)[1]*100\nmsg=f'accuracy on the test set is {acc:5.2f} %'\nprint_in_color(msg, (0,255,0),(55,65,80))\ngenerator=train_gen\nscale = 1\nmodel_save_loc, csv_save_loc=saver(working_dir, model, model_name, subject, acc, img_size, scale,  generator)\n\"\"\"\n<a id=\"predict\"><\/a>\n# <center>Make predictions on test set, create Confusion Matrix and Classification Report<\/center>\n\"\"\"\nprint_code=0\npreds=model.predict(test_gen, steps=test_steps, verbose=1) \nprint_info( test_gen, preds, print_code, working_dir, subject )  ","meta":"{'source': 'AI4Code', 'id': '19ff5d4d48441c'}"}
{"id":"78875","text":"# 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\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')\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\n\ntrain=pd.read_csv('\/kaggle\/input\/titanic\/train.csv',header=0)\ntest=pd.read_csv('\/kaggle\/input\/titanic\/test.csv',header=0)\n\n\"\"\"\n# Feature Engineering\n\"\"\"\n# I expect that having other people to think about will \n# affect someone's chance of survival\ntrain[\"Alone\"] = train[\"Parch\"] == 0\ntrain[\"Relatives\"] = train[\"Parch\"] + train[\"SibSp\"]\n\ntest[\"Alone\"] = test[\"Parch\"] == 0\ntest[\"Relatives\"] = test[\"Parch\"] + test[\"SibSp\"]\n\ntrain.sample(5)\nmedian = train['Age'].median()\ntrain['Age'].fillna(median, inplace = True)\ntest['Age'].fillna(median, inplace = True)\n\nbins = [0, 2, 12, 17, 60, np.inf]\nlabels = ['baby', 'child', 'teenager', 'adult', 'elderly']\nage_groups = pd.cut(train.Age, bins, labels = labels)\ntrain['AgeGroup'] = age_groups\n\nage_groups = pd.cut(test.Age, bins, labels = labels)\ntest['AgeGroup'] = age_groups\nsns.barplot(x=\"AgeGroup\", y=\"Survived\", data=train)\nplt.show()\nmedian = train['Fare'].median()\ntrain['Fare'].fillna(median, inplace = True)\ntest['Fare'].fillna(median, inplace = True)\nfrom sklearn.preprocessing import KBinsDiscretizer\n\ncontinuous = ['Age', 'Fare']\n\nfig, axs = plt.subplots(1, len(continuous),figsize=(len(continuous) * 6,6))\n\nfor ind,feature in enumerate(continuous):\n    bin_feature = feature + 'Bin'\n    est = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='uniform')\n    est.fit(train[[feature]])\n    train[bin_feature] = est.transform(train[[feature]])\n    test[bin_feature]= est.transform(test[[feature]])\n    sns.barplot(x=bin_feature, y=\"Survived\", data=train, ax = axs[ind])\n    \ntrain\nfrom sklearn.preprocessing import LabelEncoder\n\ncategorical = ['Sex', 'AgeBin','FareBin','AgeGroup']\nfor feature in categorical:\n    label = LabelEncoder()\n    print(feature)\n    label.fit(train[feature])\n    train[feature] = label.transform(train[feature])\n    test[feature] = label.transform(test[feature])\ntrain\nfeatures = ['Sex', 'Pclass', 'SibSp', 'Parch', 'Embarked', 'Alone', 'Relatives', 'FareBin']\nfig, axs = plt.subplots(1, len(features),figsize=(len(features) * 6,6))\nfor ind, x in enumerate(features):\n\n    g = sns.countplot(\n        data=train, ax = axs[ind],\n        x=x,  palette=\"dark\", alpha=.6\n    )\nfeatures = ['Sex', 'Pclass', 'SibSp', 'Parch', 'Embarked', 'Alone', 'Relatives', 'FareBin']\nfig, axs = plt.subplots(1, len(features),figsize=(len(features) * 6,6))\nfor ind, x in enumerate(features):\n    print('Survival Probability by', x)\n    print(train[[x, \"Survived\"]].groupby(x, as_index=False).mean()) \n    print()\n    print()\n\n    sns.barplot(x, y=\"Survived\", data=train, ax = axs[ind])\n    \n\"\"\"\nWe learn that \n - Being alone reduces survival probability but having too many relatives reduces chances\n - Women are a lot more likely to survive\n - The rich are more likely to survive (position of rooms like in the movie?)\n - Where you got on board affects survival probability\n \n## Questions\n - Do the ports of embarkation correlate with class? Do the poor people come from S? Are Embarked and Pclass collinear?\n\"\"\"\n# Collinearity of Port and class\none_hot_train = pd.get_dummies(train[[\"Pclass\", \"Embarked\"]],  columns=[\"Pclass\", \"Embarked\"])\ncorr = one_hot_train.corr()\n\ncmap = sns.diverging_palette(210, 20, as_cmap=True)\nsns.heatmap(corr, cmap=cmap,\n            square=True, linewidths=.5)\n\ncorr\n\"\"\"\nNo, looks like a very weak correlation between port and pclass.\n\"\"\"\ncorr = pd.get_dummies(train[[\"FareBin\", \"Pclass\"]], columns=[\"FareBin\", \"Pclass\"]).corr()\n\ncmap = sns.diverging_palette(210, 20, as_cmap=True)\nsns.heatmap(corr, cmap=cmap,\n            square=True, linewidths=.5)\n\ncorr\nmain_features = ['Sex',\"Relatives\",'AgeBin',\"FareBin\"]\nX_test = test[main_features]\nX_train = train[main_features]\ny_train = train['Survived']\n\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.ensemble import VotingClassifier, RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nensemble = [\n    (\"RandomForestClassifier\", RandomForestClassifier(max_leaf_nodes=10)), \n    (\"KNeighborsClassifier\", KNeighborsClassifier(n_neighbors=3)),\n    (\"SVM Classifier\",make_pipeline(StandardScaler(), SVC(gamma='auto')))\n]\n\nvoting = VotingClassifier(ensemble, voting='hard')\n\ncv_results = cross_validate(voting, X_train, y_train, cv=5)\nprint(cv_results['test_score'].mean())\n\nvoting.fit(X_train, y_train)\ny_pred = voting.predict(X_test)\noutput = pd.DataFrame({'PassengerId': test.PassengerId, 'Survived': y_pred.astype(int)})\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '90e8ebf21af0c0'}"}
{"id":"23021","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\nAuthor: Bernhard Pfahringer , ID: 1234567\n\"\"\"\niris = pd.read_csv('..\/input\/Iris.csv')\niris.head()\n\"\"\"\nGet some more info about the data:\n\"\"\"\niris.info()\n\"\"\"\nPlotting distributions is always a good idea\n\"\"\"\nimport seaborn as sns\nsns.pairplot(data=iris, hue='Species', palette='Set2')\n\n\"\"\"\nSplit the data into X and Y, input and output, and then into training and test set\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx = iris.iloc[:, 1:-1]\ny = iris.iloc[:, 5]\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\nprint(x_train.shape, y_train.shape)\n\"\"\"\nImport a standard learning algorithm, instantiate it, and train it on the training data\n\"\"\"\nfrom sklearn.svm import SVC\nmodel=SVC()\nmodel.fit(x_train, y_train)\n\"\"\"\nUse the model to predict for the test data, and check a few prediction manually\n\"\"\"\npred = model.predict(x_test)\nprint(pred[:5])\nprint(y_test[:5])\n\"\"\"\nThat looked ok, but how good is the model?\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, classification_report\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\"\"\"\nThat went well, a perfect result :-)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2a542214c48e67'}"}
{"id":"129084","text":"import pandas as pd\nimport numpy as np\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport transformers\nfrom transformers import *\nfrom sklearn import metrics\nfrom sklearn.model_selection import KFold\n\n\nprint('Transformers version: ', transformers.__version__)\nprint('Tensorflow version: ', tf.__version__)\n\"\"\"\n# Import Data\n\"\"\"\ndata_dir = '\/kaggle\/input\/nlp-getting-started\/'\ntrain_df = pd.read_csv(data_dir+'train.csv')\ntest_df = pd.read_csv(data_dir+'test.csv')\ntrain_df = train_df.sample(n=len(train_df), random_state=42)\nsample_submission = pd.read_csv(data_dir+'sample_submission.csv')\nprint(train_df['target'].value_counts())\ntrain_df.head(2)\n\"\"\"\n# Data Prep Functions\n\"\"\"\nfrom nltk.tokenize.treebank import TreebankWordTokenizer\ntree_tokenizer = TreebankWordTokenizer()\ndef get_tree_tokens(x):\n    x = tree_tokenizer.tokenize(x)\n    x = ' '.join(x)\n    return x\ntrain_df.text = train_df.text.apply(get_tree_tokens)\ntest_df.text = test_df.text.apply(get_tree_tokens)\n# from: https:\/\/www.kaggle.com\/utsavnandi\/roberta-using-huggingface-tf-implementation\ndef to_tokens(input_text, tokenizer):\n    output = tokenizer.encode_plus(input_text, max_length=90, pad_to_max_length=True)\n    return output\n\ndef select_field(features, field):\n    return [feature[field] for feature in features]\n\nimport re\ndef clean_tweet(tweet):\n    # Removing the @\n    #tweet = re.sub(r\"@[A-Za-z0-9]+\", ' ', tweet)\n    # Removing the URL links\n    #tweet = re.sub(r\"https?:\/\/[A-Za-z0-9.\/]+\", ' ', tweet)\n    # Keeping only letters\n    #tweet = re.sub(r\"[^a-zA-Z.!?']\", ' ', tweet)\n    # Removing additional whitespaces\n    tweet = re.sub(r\" +\", ' ', tweet)\n    return tweet\n\ndef preprocess_data(tokenizer, train_df, test_df):\n    train_text = train_df['text'].apply(clean_tweet)\n    test_text = test_df['text'].apply(clean_tweet)\n    train_encoded = train_text.apply(lambda x: to_tokens(x, tokenizer))\n    test_encoded = test_text.apply(lambda x: to_tokens(x, tokenizer))\n\n    #create attention masks\n    input_ids_train = np.array(select_field(train_encoded, 'input_ids'))\n    attention_masks_train = np.array(select_field(train_encoded, 'attention_mask'))\n\n    input_ids_test = np.array(select_field(test_encoded, 'input_ids'))\n    attention_masks_test = np.array(select_field(test_encoded, 'attention_mask'))\n\n    # concatonate masks\n    train_X = [input_ids_train, attention_masks_train]\n    test_X = [input_ids_test, attention_masks_test]\n    #OHE target\n    train_y = tf.keras.utils.to_categorical(train_df['target'].values.reshape(-1, 1))\n\n    return train_X, train_y, test_X\n\"\"\"\n# Function to load models\n\"\"\"\n# code from https:\/\/github.com\/huggingface\/transformers\n# Transformers has a unified API\n# for 10 transformer architectures and 30 pretrained weights.\n#          Model          | Tokenizer          | Pretrained weights shortcut\ndef load_pretrained_model(model_class='bert', model_name='bert-base-cased', task='binary', learning_rate=3e-5, epsilon=1e-8, lower_case=False):\n  MODEL_CLASSES = {\n    \"bert\": (BertConfig, TFBertForSequenceClassification, BertTokenizer),\n    \"xlnet\": (XLNetConfig, TFXLNetForSequenceClassification, XLNetTokenizer),\n    \"xlm\": (XLMConfig, TFXLMForSequenceClassification, XLMTokenizer),\n    \"roberta\": (RobertaConfig, TFRobertaForSequenceClassification, RobertaTokenizer),\n    \"distilbert\": (DistilBertConfig, TFDistilBertForSequenceClassification, DistilBertTokenizer),\n    \"albert\": (AlbertConfig, TFAlbertForSequenceClassification, AlbertTokenizer),\n    #\"xlmroberta\": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer), No tensorflow version yet\n  }\n  model_metrics = [\n        tf.keras.metrics.TruePositives(name='tp'),\n        tf.keras.metrics.FalsePositives(name='fp'),\n        tf.keras.metrics.TrueNegatives(name='tn'),\n        tf.keras.metrics.FalseNegatives(name='fn'), \n        tf.keras.metrics.BinaryAccuracy(name='accuracy'),\n        tf.keras.metrics.Precision(name='precision'),\n        tf.keras.metrics.Recall(name='recall'),\n        tf.keras.metrics.AUC(name='auc'),\n  ]\n\n  \n  config_class, model_class, tokenizer_class = MODEL_CLASSES[model_class]\n\n  config = config_class.from_pretrained(model_name, num_labels=2, finetuning_task=task)\n\n\n  model = model_class.from_pretrained(model_name)\n  optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=epsilon, clipnorm=1.0)\n  loss = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n  metric = tf.keras.metrics.BinaryAccuracy('accuracy')\n  model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])\n  #model.summary()\n\n  tokenizer = tokenizer_class.from_pretrained(model_name, lower_case = lower_case)\n\n  return config, model, tokenizer\n\"\"\"\n# Train Model\n\"\"\"\n# load model, process data for model\n_, _, tokenizer = load_pretrained_model(model_class='roberta', model_name='roberta-base', learning_rate=2e-5, lower_case=False)\ntrain_X, train_y, test_X = preprocess_data(tokenizer=tokenizer, train_df=train_df, test_df=test_df)\n\n\nkf = KFold(n_splits=6)\ntest_preds = []\ni = 0\nfor train_idx, test_idx in kf.split(train_X[0]):\n    i+=1\n    if i not in [1, 5]: #only do 2 folds to save time\n        continue\n    train_split_X = [train_X[i][train_idx] for i in range(len(train_X))]\n    test_split_X = [train_X[i][test_idx] for i in range(len(train_X))]\n\n    train_split_y = train_y[train_idx]\n    test_split_y = train_y[test_idx]\n    #create class weights to account for inbalance\n    positive = train_df.iloc[train_idx, :].target.value_counts()[0]\n    negative = train_df.iloc[train_idx, :].target.value_counts()[1]\n    pos_weight = positive \/ (positive + negative)\n    neg_weight = negative \/ (positive + negative)\n\n    class_weight = [{0:pos_weight, 1:neg_weight}, {0:neg_weight, 1:pos_weight}]\n\n    K.clear_session()\n    config, model, tokenizer = load_pretrained_model(model_class='roberta', model_name='roberta-base', learning_rate=2e-5, lower_case=False)\n\n    # fit, test model\n    model.fit(train_split_X, train_split_y, batch_size=64, epochs=3, class_weight=class_weight, validation_data=(test_split_X, test_split_y))\n\n    val_preds = model.predict(test_split_X, batch_size=32, verbose=1)\n    val_preds = np.argmax(val_preds, axis=1).flatten()\n    print(metrics.accuracy_score(train_df.iloc[test_idx, :].target.values, val_preds))\n\n    preds1 = model.predict(test_X, batch_size=32, verbose=1)\n    test_preds.append(preds1)\n\"\"\"\n# Output Predictions\n\"\"\"\ntest_preds2 = np.average(test_preds, axis=0)\ntest_preds3 = np.argmax(test_preds2, axis=1).flatten()\nsample_submission['target'] = test_preds3\nsample_submission['target'].value_counts()\nsample_submission.to_csv('new_submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'ed701735147992'}"}
{"id":"52373","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\npd.set_option('display.max_columns', 80)\npd.set_option('display.max_rows', 80)\n\n\nfrom scipy import stats\nfrom scipy.stats import norm\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Visualization Libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n\n# Model building libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import Imputer\n\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import mean_absolute_error\n\n# Any results you write to the current directory are saved as output.\ntrain = pd.read_csv('..\/input\/train.csv')\ntest = pd.read_csv('..\/input\/test.csv')\ntrain.head(10)\ntrain.columns\n# Analysing the dependent variable:\ntrain['SalePrice'].describe()\nsns.distplot(train['SalePrice'] , fit=norm)\ntrain['SalePrice'] = np.log(train['SalePrice'])\nsns.distplot(train['SalePrice'] , fit=norm)\n# Finding missing value % for each column\n\npercent_missing = train.isnull().sum() * 100 \/ len(train)\nmissing_value_df = pd.DataFrame({'column_name': train.columns,\n                                 'percent_missing': percent_missing})\n\nmissing_value_df.sort_values('percent_missing', ascending = False)\n\"\"\"\n> Missing % of these predictors: PoolQC(71), MiscFeature(73), Alley(5), Fence(72)  >80%\n\"\"\"\ncorr_mat = train.corr()\n\nf, ax = plt.subplots(figsize=(14, 12))\nsns.heatmap(corr_mat, vmax=.8, square=True)\n\"\"\"\nVariables highly correlated to SalePrice\n- OverallQual\n- TotalBsmtSF\n- GrLivArea\n- GarageCars\/GarageArea\n- YearBuilt\n- FullBath\n\"\"\"\ntrain.columns.get_loc('Fence')\n# Dropping these columns: PoolQC(72), MiscFeature(74), Alley(6), Fence(73)  >80% (less correlated and missing value % is high)\ntrain.drop(train.columns[[6,72,73,74]], axis=1, inplace=True)\ntest.drop(test.columns[[6,72,73,74]], axis=1, inplace=True)\n\"\"\"\nAnalysing the top (correlated) variables:\n\"\"\"\n# Overall Quality - rating from 1 to 10\nf, ax = plt.subplots(figsize=(10, 8))\nfig = sns.boxplot('OverallQual', y=\"SalePrice\", data=train)\nfig.axis(ymin=10, ymax=14);\n\"\"\"\nTop outlier: Houses with a rating of 10 but the sale prices are lower than average sale price of house with rating 5\nLet's remove this\n\"\"\"\ntrain = train.drop(train[(train['OverallQual'] == 10)& (train['SalePrice'] <12.3)].index)\n# TotalBsmtSF : Total square feet of basement area\nfig, ax = plt.subplots()\nax.scatter(train['TotalBsmtSF'], train['SalePrice'])\nplt.show()\n\"\"\"\nMore the basement area, more is the sale price\n\"\"\"\n# GrLivArea : Above grade (ground) living area square feet\nfig, ax = plt.subplots()\nax.scatter(train['GrLivArea'], train['SalePrice'])\nplt.show()\n\"\"\"\nMore the living area, more is the sale price\n\"\"\"\n# GarageCars\/GarageArea: both are highly correlated to each other. let's check only one\n\n# GarageCars - Size of garage in car capacity from 0 to 4\nf, ax = plt.subplots(figsize=(10, 8))\nfig = sns.boxplot('GarageCars', y=\"SalePrice\", data=train)\nfig.axis(ymin=10, ymax=14);\n\"\"\"\nSalePrice is maximum for garage car capacity of 3. It decreases for the capacity of 4\n\"\"\"\n# YearBuilt: Original construction date\nf, ax = plt.subplots(figsize=(10, 8))\nfig = sns.boxplot('YearBuilt', y=\"SalePrice\", data=train)\nfig.axis(ymin=10, ymax=14);\n# FullBath: Full bathrooms above grade: from 0 to 3\n\nf, ax = plt.subplots(figsize=(10, 8))\nfig = sns.boxplot('FullBath', y=\"SalePrice\", data=train)\nfig.axis(ymin=10, ymax=14);\n\"\"\"\n**Imputing Missing Values**\n\"\"\"\ndata = pd.concat((train, test)).reset_index(drop=True)\nlen(data)\ntrain_rows = train.shape[0]\ntest_rows = test.shape[0]\npercent_missing = data.isnull().sum() * 100 \/ len(data)\n\nmissing_value_df = pd.DataFrame({'column_name': data.columns,\n                                 'percent_missing': percent_missing})\n\nmissing_value_df[missing_value_df['percent_missing']>0].sort_index()\ndata[\"FireplaceQu\"] = data[\"FireplaceQu\"].fillna(\"None\")\ndata['LotFrontage'].describe()\ndata[\"LotFrontage\"] = data[\"LotFrontage\"].fillna(data['LotFrontage'].mean())\nfor col in ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']:\n    data[col] = data[col].fillna('None')\nfor col in ['GarageYrBlt', 'GarageArea', 'GarageCars']:\n    data[col] = data[col].fillna(0)\nfor col in ['BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual', 'BsmtCond']:\n    data[col] = data[col].fillna('None')\nfor col in ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath']:\n    data[col] = data[col].fillna(0)\ndata['MasVnrType'] = data['MasVnrType'].fillna('None')\ndata['MasVnrArea'] = data['MasVnrArea'].fillna(0)\ndata['Electrical'] = data['Electrical'].fillna(data['Electrical'].mode()[0])\ndata['Exterior1st'].mode()[0]\ndata['Exterior2nd'].mode()[0]\nfor col in ['Exterior1st', 'Exterior2nd']:\n    data[col] = data[col].fillna(data['Exterior2nd'].mode()[0])\ndata['Functional'].mode()[0]\ndata['Functional'] = data['Functional'].fillna(data['Functional'].mode()[0])\ndata['KitchenQual'] = data['KitchenQual'].fillna(data['KitchenQual'].mode()[0])\ndata['MSZoning'] = data['MSZoning'].fillna(data['MSZoning'].mode()[0])\ndata = data.drop(['Utilities'], axis=1)\ndata['SaleType'] = data['SaleType'].fillna(data['SaleType'].mode()[0])\npercent_missing = data.isnull().sum() * 100 \/ len(data)\n\nmissing_value_df = pd.DataFrame({'column_name': data.columns,\n                                 'percent_missing': percent_missing})\n\nmissing_value_df[missing_value_df['percent_missing']>0].sort_index()\ndata.columns\n# Converting few numerical variables to categorical\ndata['MSSubClass'] = data['MSSubClass'].apply(str)\ndata['OverallCond'] = data['OverallCond'].astype(str)\n\n\n\ndata['YrSold'] = data['YrSold'].astype(str)\ndata['MoSold'] = data['MoSold'].astype(str)\ndata['Heating'] = data['Heating'].astype(str)\nfrom sklearn.preprocessing import LabelEncoder\ncols = ('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond', \n        'ExterQual', 'ExterCond','HeatingQC',  'KitchenQual', 'BsmtFinType1', \n        'BsmtFinType2', 'Functional', 'BsmtExposure', 'GarageFinish', 'LandSlope','RoofStyle','SaleCondition',\n        'LotShape', 'PavedDrive', 'Street', 'CentralAir', 'MSSubClass', 'OverallCond', 'RoofMatl', 'SaleType',\n        'YrSold', 'MoSold', 'BldgType', 'Condition1', 'Condition2', 'Electrical', 'Exterior1st', 'Exterior2nd', \n        'Foundation', 'GarageType','Heating', 'HouseStyle', 'LotConfig', 'LandContour', 'MasVnrType', 'Neighborhood','MSZoning')\n# process columns, apply LabelEncoder to categorical features\nfor c in cols:\n    lbl = LabelEncoder() \n    lbl.fit(list(data[c].values)) \n    data[c] = lbl.transform(list(data[c].values))\n# shape        \nprint('Shape all_data: {}'.format(data.shape))\ntrain = data[data['Id']<=1460]\ntest = data[data['Id']>1460]\ny = train['SalePrice']\nX = train.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object'])\ntrain_X, test_X, train_y, test_y = train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25)\nrfr = RandomForestRegressor(n_estimators = 100, random_state = 42)\nrfr.fit(train_X, train_y);\npredictions = rfr.predict(test_X)\nprint(\"Mean Absolute Error : \" + str(mean_absolute_error(predictions, test_y)))\ntest = test.drop(['SalePrice'], axis=1)\npredictions_RF = rfr.predict(test)\n\"\"\"\n**XGBoost**\n\"\"\"\nmy_imputer = Imputer()\ntrain_X = my_imputer.fit_transform(train_X)\ntest_X = my_imputer.transform(test_X)\ntest_Z = my_imputer.transform(test)\nXGB = XGBRegressor()\n# Add silent=True to avoid printing out updates with each cycle\nXGB.fit(train_X, train_y, verbose=False)\npredictions = XGB.predict(test_X)\nprint(\"Mean Absolute Error : \" + str(mean_absolute_error(predictions, test_y)))\n# Tuning XGBoost model\nXGB1 = XGBRegressor(n_estimators=1000, learning_rate=0.05)\nXGB1.fit(train_X, train_y, early_stopping_rounds=5, \n             eval_set=[(test_X, test_y)], verbose=False)\npredictions = XGB1.predict(test_X)\nprint(\"Mean Absolute Error : \" + str(mean_absolute_error(predictions, test_y)))\npredictions_XGB = XGB1.predict(test_Z)\nSaleP = pd.Series(np.exp(predictions_XGB))\ntest['SalePrice'] = SaleP\n\nsubmission1 = test[['Id', 'SalePrice']]\nsubmission1.to_csv('..\/submission1.csv')","meta":"{'source': 'AI4Code', 'id': '606113038286ca'}"}
{"id":"136754","text":"\"\"\"\n# In this topic I would like to show you a different methods of visualisation and it's types.\n\nNot so long ago I had a conversation with a \"very good\" data scientist about visualizations and its usage in the projects. And he argued a lot that he can do anything without it and visualization process is a lack of time and does not deserve his attention. Hmmmm....\n\n**Is it really so? And do a data scientists need visualization at all?**\n\nI like to answer to this question with an example that was invented by the **talented mathematician Francis Encombe in 1973 year.** With this example, he wanted to show the importance of visualization for data analysis and the effect of data on statistical indicators. \n\nThe point is that he came up with several random samples that have the same statistical indicators.\n\n![random_samples.jpg](attachment:random_samples.jpg)\n\"\"\"\n\"\"\"\nSo as you can see above the dataFrame has 4 random samples. And if we calculate a statistics for each individual sample we will get the same result for each of them:\n\n* Sample Mean for ***x*** = 9\n* Sample Variance of ***x*** = 11\n* Sample Mean for ***y*** =11.5\n* Sample Variance of ***y*** = 4.125\n* Correlation between ***x*** and ***y*** = 0.816\n\nIf you don't trust me try your own! \n\n**And so is it really all 4 random samples are the same?**\n\n\"\"\"\n\"\"\"\n# Nope!\n\n![1.jpg](attachment:1.jpg)\n\nAnd I found many of such examples where you can find a lot of funny examples https:\/\/www.autodeskresearch.com\/publications\/samestats\n\nSo from this point I will immerse you into the world of data visualization and show you with examples and what you should use (and what should not, but you can if you want). So let's go!\n\"\"\"\n\"\"\"\n# Python's libriaries for data visualization\n\n![libs.jpg](attachment:libs.jpg)\n\n\nI will point out a list of libriaries that I use the most time. Here are they:\n   * **[matplotlib](http:\/\/matplotlib.org\/3.1.1\/contents.html)** - the most classical libriary (hello from 90's :)\n            1. This is the first data visualization libriary in Python.\n            2. Very Very flexible and powerfull. It is relatively simple to use for complete beginners.\n            3. Styles from 90's.\n            4. Exist wrappers - pandas and seaborn.\n   * **[seaborn](http:\/\/seaborn.pydata.org\/)** \n            1. Based on matplotlib libriary.\n            2. Complex visualizations for couple of lines of code.\n            3. Very attractive styles (by default and tuned).\n            4. And if you want to add or change something you need to know matplotlib.\n   * **[plotly (+dash)](http:\/\/dash.plot.ly\/)** - my favourite \n            1. Very interactive data visualizations.\n            2. Relatively simple API and you can tune it for your own needs.\n            3. Beatiful default styles for graphs.\n            4. You can use dash for building and encoding your visualizations into different web applications.\n   * **[ggpolot](http:\/\/ggplot2.tidyverse.org\/reference\/)**\n            1. Based on ggplot2 from R's language libriary.\n            2. The Grammar of graphics Zen: complex component layers.\n            3. It is easy tu use than matplotlib but it is less flexible.\n   * **[bokeh](http:\/\/bokeh.pydata.org\/en\/latest\/)**\n            1. Same The Grammar of graphics Zen like in ggplot.\n            2. Very interactive visualizations.\n            3. Very complex API (not flexible).\n            4. Complex (very hard) libriary to use. But if you will know it you can do anything.\n   * **[pygal](http:\/\/www.pygal.org\/en\/stable\/documentation\/)**\n            1. Interactivity in visualizations.\n            2. Graphs in SVG formats (it is not a good solution for the big data frames).\n            3. Simple API that you can use. \n\"\"\"\n\"\"\"\n# Visualization examples and codes\n## *Matplotlib review*\n\"\"\"\n# if you dont have the libriaries show above you can upload it by using \n# pip install seaborn\n# pip install plotly\n# pip install ggplot\n# pip install matplotlib\n# pip install future\nfrom __future__ import (absolute_import, division, print_function, \n                        unicode_literals)\n# turn off warnings\nimport warnings\nwarnings.simplefilter('ignore')\n\n# inline visualizations \n%pylab inline\n# turn the visualization into SVG format\n%config InlineBackend.figure_format = 'svg'\n# and lets resize default size of graphs\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 6,5\n\n# and last point lets import libriaries for working with data and data manipulation\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\"\"\"\nLets upload dataframe with which we will be working. I choose a dataset with videogame information (ranks, sales, regions and etc.) from one of the **[Kaggle's datasets](http:\/\/www.kaggle.com\/rush4ratio\/video-game-sales-with-ratings).** There is some empty data that will be deleted from the dataset. So lets go!\n\"\"\"\n# I forgot the path on Kagle so lets find out where we are now:\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\ndf = pd.read_csv('\/kaggle\/input\/video_games_sales.csv')\nprint(df.shape)\ndf.info()\n# As you see there are not all data for \"Critic_Score\", \"Critic_count\", \"Developer\" and \"Rating\" \n# Usually I delete it (but not always)\ndf = df.dropna()\nprint(df.shape)\ndf.info()\n# As mentiod from df.info() not all features have an appropriate data-type. Change it to the another data-type\ndf['User_Score'] = df.User_Score.astype('float64')\ndf['Year_of_Release'] = df.Year_of_Release.astype('int64')\ndf['User_Count'] = df.User_Count.astype('int64')\ndf['Critic_Count'] = df.Critic_Count.astype('int64')\ndf.head()\n# I think I will analyze not all features. In this dataframe we have 6825 rows and 16 columns(features)\n# Lets leave features that are the most meaningfull\nmeaningfull_cols = ['Name', 'Platform', 'Year_of_Release', 'Genre', 'Global_Sales',\n                    'Critic_Score', 'Critic_Count', 'User_Score', 'User_Count', 'Rating']\n\ndf[meaningfull_cols].head(5)\n\"\"\"\nLet's start with the simplest and often convenient way to visualize data from <code>**Pandas DataFrame**<\/code> the usage of the <code>**plot**<\/code> function. \nFor example let's create a **Sales** graph in different **Countries** by the **Year_of_release**. First of all let's filter out only the columns we need, then \ncalculate the total sales by year and then call the <code>**plot**<\/code> function without any arguments for the final dataframe.\n\nAnd I want to point out that <code>**Pandas Libriary**<\/code> already have wrapper for the <code>**Matplotlib Libriary**<\/code>\n\"\"\"\n[x for x in df.columns if 'Sales' in x]\n# And I want to mention that NA_Sales stands for North_American_Sales and not for NA as you could think \ndf1 = df[[x for x in df.columns if 'Sales' in x] + ['Year_of_Release']].groupby('Year_of_Release').sum()\ndf1.head()\ndf1.plot();\n\"\"\"\nIn this case we focused on displaying sales trends in different regions. \nUsing the <code>**kind**<\/code> argument parameter you can change the type of the chart to any other (bar chart, pie chart and etc.)\n<code>**Matplotlib libriary**<\/code> allows you to make any kind of chart customization. On the chart you can change almost anything, \nbut you need to go through documentation for the purpose you need and find necessary parameters. \n\nFor example the <code>**rot**<\/code> parameter is responsible for the slope of the labels on the x-axis and the <code>**figsize = (x, y)**<\/code>\nyou can resize you chart to any size.\n\"\"\"\ndf1.plot(kind = 'bar', rot = 45, figsize = (10, 5));\n\"\"\"\nTo show both the dynamics of sales and their breakdown by market you should use a **Stacked Bar Chart**.\n\"\"\"\ndf1[list(filter(lambda x: x != 'Global_Sales', df1.columns))].plot(kind = 'bar', rot = 45, stacked = True, figsize = (10, 5));\n# stacked parameter is for visibility\ndf1[list(filter(lambda x: x != 'Global_Sales', df1.columns))].plot(kind = 'area', rot = 45, stacked = False, figsize = (10, 5));\n\"\"\"\n### Histograms in matplotlib\nHistograms are very well suited for visualizing **various kinds of distributions.** On below examples I will show distribution of critic scores in the dataframe.\nHistograms in matplotlib are relatively simple to plot. You need just select a feature you want to plot (for example **Critic_Score**) and add a method <code>**.hist()**<\/code>\n\"\"\"\ndf.Critic_Score.hist(figsize = (10, 5));\n\"\"\"\nThe more beautiful way:\n\"\"\"\nax = df.Critic_Score.hist(figsize = (10, 5));\nax.set_title('Critic Score distribution');\nax.set_xlabel('Critic Score');\nax.set_ylabel('Games');\n# You can choose the number of bins for the distribution by calling it bins = #\nax = df.Critic_Score.hist(figsize = (10, 5), bins = 25);\nax.set_title('Critic Score distribution');\nax.set_xlabel('Critic Score');\nax.set_ylabel('Games');\n\"\"\"\n# *Seaborn libriary review*\n\nSeaborn libriary is just an API of high level based on matplotlib libriary. Seaborn includes more attractive default styles and its customization for the charts. \nSeaborn libriary also have different complex styles and types of visualizations than you can do with a several rows of code (in mathplotlib it will be messy).\n\nThe first complex chart is <code>**pair plot (scatter plot matrix)**<\/code>. This type of chart helps us to see the different types of correlation between values and \nits distributions. So let's see it.\n\"\"\"\nimport seaborn as sns\n%config InlineBackend.figure_format = 'png'\nsns_plot = sns.pairplot(df[['Global_Sales', 'User_Score', 'Critic_Score']]);\n# you can save the chart by\n# sns_plot.savefig('#name_of_chart.png')\n# Also seaborn can visualize distribution of quantitative value in different ways\n# Joint_plot - is a hybrid of scatter_plot and histogram. \n# Lets see how it works on two values Critic_Score and User_Score\nsns.jointplot(x = 'Critic_Score', y = 'User_Score', data = df, kind = 'scatter');\nsns.jointplot( x = 'Critic_Score', y = 'User_Score', data = df, kind = 'reg');\n\"\"\"\nAlso what I really like in seaborn's libriary is **heatmap** diagrams. It is really powerfull and from this feature we can gain a lot of insights.\nUsing the heatmap we can see how for example Rates are varies from platform to platform. \n\"\"\"\nplatform_gender_sales = df.pivot_table(index = 'Platform', columns = 'Genre', values = 'Global_Sales', aggfunc = sum).fillna(0).applymap(float)\nplatform_gender_sales.head()\nsns.heatmap(platform_gender_sales, annot = True, fmt = '.0f', linewidths = 0.7);\n\"\"\"\nSo as you can see a seaborn is very powerfull libriary. Using this you can create any type of charts (box plots, histograms, line charts, distribution or correlation chart, scatter plot and etc.). If you want more examples you can read a documentation of every libriary. Links to the documentations I have placed in the beggining of this tutorial. \n\nAnd lastly I want to show you how to work in my favourite libriary called <code>**Plotly**<\/code>. It is a really powerfull libriary that I have ever seen among Python libriaries for visualization purposes. Let's see how it works and what kind of things you can possibly do using **Plotly**\n\"\"\"\n\"\"\"\n# *Plotly review* \n![](http:\/\/)Plotly is an open-source libriariy which allows to create different **interactive** charts. The advantage of interactive charts is that you can see any quantitative value by pointing a mouse cursor on the chart and increase or decrease a scale of the chart. Let's see how it works on practice!\n\n## I dont know why but Kaggle notebook do not appropriately show the Plotly output. If you want to see it simply download this notebook. Sorry.\n\"\"\"\nfrom plotly.offline import init_notebook_mode, iplot\nimport plotly\nimport plotly.graph_objs as go\n\ninit_notebook_mode(connected = True)\nglobal_sales_df = df.groupby('Year_of_Release')[['Global_Sales']].sum()\nglobal_sales_df.head(5)\nreleased_years_df = df.groupby('Year_of_Release')[['Name']].count()\nreleased_years_df.head(5)\nyears_df = global_sales_df.join(released_years_df)\nyears_df.columns = ['Global_Sales', 'Number_of_Games']\nyears_df.head()\n\"\"\"\nIn <code>**Plotly**<\/code> the visualization is constructed by the Figure object, which consists from data (an array of lines, called **traces**) and from design \/ style for which the layout object is responsible. In simple cases you can call the <code>**iplot**<\/code> function and just plot the data from its **traces**. Let see it on the example:\n\"\"\"\n# declare a trace which is an array and specify the design\n# go.Scatter - specifies type of chart\n# trace0 simply just declaring a firts line on the graph\ntrace0 = go.Scatter(\n    # what should be on x-axis\n    x = years_df.index,\n    # what should be on y-axis\n    y = years_df.Global_Sales,\n    # Title for the Chart\n    name = 'Global Sales'\n)\n# declare a second Scatter (second line on the graph)\ntrace1 = go.Scatter(\n    # Specify x-axis\n    x = years_df.index,\n    # and y-axis\n    y = years_df.Number_of_Games,\n    # Title of the chart\n    name = 'Number of games released'\n)\n\n# collect all the traces (arrays) in separate dataframe\ndata = [trace0, trace1]\n# choosing a single title\nlayout = {'title': 'Statistics of video games'}\n# Plotting the figure\nfig = go.Figure(data = data, layout = layout)\n\niplot(fig, show_link = False)\n# if you want to save your graph just use the next code\n# plotly.offline.plot(fig, filename = 'years_stats_sales.#specify_format_after_dot', show_link = False);\n\"\"\"\nAlso Plotly is best suitable solution for visualizing such data as market share, prices, segments, distributions and etc. Let's see on market share of game platforms, calculated by quantity of games released and its sales for the all time. The best suited graphs are bar chart or pie chart. I will plot a bar chart beacuse it is easily to read.\n\"\"\"\nplatform_sales_global_df = df.groupby('Platform')[['Global_Sales']].sum()\nreleased_df = df.groupby('Platform')[['Name']].count()\nplatforms_df = platform_sales_global_df.join(released_df)\nplatforms_df.columns = ['Global_Sales', 'Number_of_Games']\nplatforms_df.sort_values('Global_Sales', inplace = True)\nplatforms_df = platforms_df.apply(lambda x: 100 * x \/ platforms_df.sum(), axis = 1)\nplatforms_df.head()\n# Finally lets plot the data on chart\n\n# again create a traces where specify the chart type and its axis\ntrace0 = go.Bar(\n    x = platforms_df.index,\n    y = platforms_df.Global_Sales,\n    name = 'Global Sales',\n    orientation = 'v'\n)\n\ntrace1 = go.Bar(\n    x = platforms_df.index,\n    y = platforms_df.Number_of_Games,\n    name = 'Number of games released',\n    orientation = 'v'\n)\n\ndata = [trace0, trace1]\nlayout = {'title': 'Platforms share'}\n\nfig = go.Figure(data = data, layout = layout)\n\niplot(fig, show_link = False)\n# We can interactively represent the dependency between mean User_Score and Critic_Score and its influence on Global_Sales\n# To do it we need to join two tables with scores and sales\nscores_genres = df.groupby('Genre')[['Critic_Score', 'User_Score']].mean()\nsales_genres = df.groupby('Genre')[['Global_Sales']].sum()\ngenres_sales = scores_genres.join(sales_genres)\n\ngenres_sales.head()\n# So finally plot the data on char. I choose a scatter plot because it will show dependencies\ntrace0 = go.Scatter(\n            x = genres_sales.Critic_Score,\n            y = genres_sales.User_Score,\n            mode = 'markers+text',\n            text = genres_sales.index)\n\ndata = [trace0]\nlayout = {'title': 'Influence of User and Critic Scores on Sales'}\n\nfig = go.Figure(data = data, layout = layout)\niplot(fig, show_link = False)\n# From this scatter plot we can modify it and create a bubble chart which will show the amount of sales that was calculated before\ngenres_sales.index\ntrace0 = go.Scatter(\n    x = genres_sales.Critic_Score,\n    y=genres_sales.User_Score,\n    mode = 'markers+text',\n    text = genres_sales.index,\n    marker = dict(\n        size = 1\/10*genres_sales.Global_Sales,\n        color = [\n            'aqua', 'azure', 'beige', 'lightgreen',\n            'lavender', 'lightblue', 'pink', 'salmon',\n            'wheat', 'ivory', 'silver'\n        ]\n    )\n)\n\ndata = [trace0]\nlayout = {\n    'title': 'Influence of User and Critic Scores on Sales',\n    'xaxis': {'title': 'Critic Score'},\n    'yaxis': {'title': 'User Score'}\n}\n\nfig = go.Figure(data=data, layout=layout)\n\niplot(fig, show_link=False)\n\"\"\"\nSo this is it. I wanted to show you how you can use different libriaries on visualization process and gain a powerfull insights from it. It is your choice which of you should use, but the best of them is Plotly libriary which I use on daily basis. Besides this if you want to be real expert there are d3.js libriary for JavaScript. It is also very powerfull and using it you can create a lot of different charts in different manner. \n\nHope that this tutorial will help you in future. \nThank you!\n\nP.S. If you found grammar mistakes in my English, sorry. I didn't have a practice for a long time.\n     Best to you all and thank you!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fb5c482689df8f'}"}
{"id":"73416","text":"import pandas as pd\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom sklearn.metrics import accuracy_score\nimport os\nimport scipy.io\nimport math\n\nfrom sklearn.utils import shuffle\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\nfrom tensorflow.keras.applications import resnet50\nfrom keras.preprocessing import image\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nfrom keras.applications.imagenet_utils import preprocess_input, decode_predictions\n\nimport tensorflow as tf\nfrom keras.preprocessing import image\n\nfrom sklearn.model_selection import train_test_split\n\nfrom scipy import spatial\nfrom tqdm import tqdm\n\nimport gc\nresnet50_model = resnet50.ResNet50(weights='imagenet')\nstyles = pd.read_csv('\/kaggle\/input\/fashion-product-images-dataset\/fashion-dataset\/styles.csv', error_bad_lines=False)\n\nshirts = styles[styles['articleType'].isin(['Shirts'])]\ntshirts = styles[styles['articleType'].isin(['Tshirts'])]\npants =  styles[styles['articleType'].isin(['Track Pants','Shorts', 'Trunk', 'Trousers', 'Track Pants', 'Tights', 'Lounge Pants', 'Lounge Shorts', 'Leggings', 'Jeans', 'Jeggings'])]\n# np.unique(styles['articleType'])\nshirts, tshirts, pants = shirts['id'].to_numpy(), tshirts['id'].to_numpy(), pants['id'].to_numpy()\nshirts.shape, tshirts.shape, pants.shape\n\"\"\"\n# Constants\n\"\"\"\nimage_path = '\/kaggle\/input\/fashion-product-images-dataset\/fashion-dataset\/images\/'\n\nIMG_SIZE = 224\nLIMIT_IMAGES = 2000\nNUM_OUTPUTS = 3\n\"\"\"\n# Load Image Files\n\"\"\"\ndef load_imgs(names):\n    imgs = []\n    for i, image_name in enumerate(tqdm(names)):\n#         if i% 50 == 0 :\n#             print(f\"Loading Image {i}\")\n        try:\n            img = image.load_img(f'{image_path}{image_name}.jpg', target_size=(IMG_SIZE, IMG_SIZE))\n        except:\n            img = None\n        if img is None:\n            continue\n        img = np.array(img)\n        imgs.append(img)\n    return np.array(imgs)\nprint(\"Loading Images...\")\nprint(\"Shirts\")\nshirt_images = load_imgs(shirts[:LIMIT_IMAGES])\ngc.collect()\nprint(\"TShirts\")\ntshirt_images = load_imgs(tshirts[:LIMIT_IMAGES])\ngc.collect()\nprint(\"Pants\")\npant_images = load_imgs(pants[:LIMIT_IMAGES])\ngc.collect()\nprint(\"Done\")\nshirt_images.shape, tshirt_images.shape, pant_images.shape\ntrain_shirt_images, test_shirt_images, _, _ = train_test_split(shirt_images, np.repeat(0, shirt_images.shape[0]), test_size = 0.2)\ntrain_shirt_images.shape, test_shirt_images.shape\ntrain_tshirt_images, test_tshirt_images, _, _ = train_test_split(tshirt_images, np.repeat(0, tshirt_images.shape[0]), test_size = 0.2)\ntrain_tshirt_images.shape, test_tshirt_images.shape\ntrain_pant_images, test_pant_images, _, _ = train_test_split(pant_images, np.repeat(0, pant_images.shape[0]), test_size = 0.2)\ntrain_pant_images.shape, test_pant_images.shape\ngc.collect()\ndef get_vectors(imgs):\n    processed_batch = preprocess_input(imgs, mode=\"caffe\")\n    return resnet50_model.predict(processed_batch)\n\ndef get_average_vector(imgs):\n    vectors = get_vectors(imgs)\n    print(vectors.shape)\n    return np.mean(vectors, axis=0)\n\ndef closeness(a, b):\n#     print(a.shape)\n#     print(b.shape)\n    return 1 - spatial.distance.cosine(a, b)\n\ndef closest(vector, compared_to):\n    best = -5\n    best_idx = -1\n#     print(compared_to.shape)\n    for i, cmp in enumerate(compared_to):\n        c = closeness(vector, cmp)\n        if c > best:\n            best_idx = i\n            best = c\n    return best_idx, best\n\ndef b_closest(vectors, compared_to):\n    return np.array([closest(vector, compared_to)[0] for vector in vectors])\n# Get Test And Train Sets\ntrain_X = np.concatenate((train_shirt_images, train_tshirt_images, train_pant_images), axis = 0)\ntrain_Y = np.repeat((0, 1, 2), (train_shirt_images.shape[0], train_tshirt_images.shape[0], train_pant_images.shape[0]), axis = 0)\n\ntrain_vecs = get_vectors(train_X)\ngc.collect()\ntest_X = np.concatenate((test_shirt_images, test_tshirt_images, test_pant_images), axis = 0)\ntest_Y = np.repeat((0, 1, 2), (test_shirt_images.shape[0], test_tshirt_images.shape[0], test_pant_images.shape[0]), axis = 0)\n\ntest_vecs = get_vectors(test_X)\ngc.collect()\nfrom sklearn.metrics import confusion_matrix, classification_report\n\"\"\"\n# Average Model\n\"\"\"\nshirt_vector = get_average_vector(train_shirt_images)\ntshirt_vector = get_average_vector(train_tshirt_images)\npant_vector = get_average_vector(train_pant_images)\ngc.collect()\npred_classes = decode_predictions(np.expand_dims(shirt_vector, axis=0), top=3)\npred_classes\npred_classes = decode_predictions(np.expand_dims(tshirt_vector, axis=0), top=3)\npred_classes\npred_classes = decode_predictions(np.expand_dims(pant_vector, axis=0), top=3)\npred_classes\ntest_vector = np.array([shirt_vector, tshirt_vector, pant_vector])\n\ntrain_predictions = b_closest(train_vecs, test_vector)\n\ntrain_accuracy = accuracy_score(train_Y, train_predictions)\nprint(f\"In Sample Accuracy: {train_accuracy}\")\n\ntest_predictions = b_closest(test_vecs, test_vector)\n\ntest_accuracy = accuracy_score(test_Y, test_predictions)\nprint(f\"Out Of Sample Accuracy: {test_accuracy}\")\ngc.collect()\n\"\"\"\n# NN To Classify\n\"\"\"\nimport pandas\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\n\ntrainx, trainy = shuffle(train_vecs, train_Y)\n# trainx = np.expand_dims(trainx, axis=1)\ntrainx.shape, trainy.shape\ndef baseline_model():\n    # create model\n    model = Sequential()\n    model.add(Dense(8, input_dim=1000, activation='relu'))\n    model.add(Dense(3, activation='softmax'))\n    # Compile model\n    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n    return model\nestimator = KerasClassifier(build_fn=baseline_model, epochs=200, batch_size=5, verbose=0)\nkfold = KFold(n_splits=10, shuffle=True)\nclassify_model = estimator.fit(trainx, trainy)\npreds = estimator.predict(train_vecs)\nacc = accuracy_score(train_Y, preds)\nprint(f\"In sample Accuracy: {acc}\")\npreds = estimator.predict(test_vecs)\nacc = accuracy_score(test_Y, preds)\nprint(f\"Out of sample Accuracy: {acc}\")\nestimator.model.save('\/kaggle\/working\/keras-vlarge-963.h5')\n\"\"\"\n# ADA to classify\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn import metrics\nabc = AdaBoostClassifier(n_estimators=400, learning_rate=1)\nabcm = abc.fit(trainx, trainy)\npreds = abc.predict(train_vecs)\nacc = accuracy_score(train_Y, preds)\nprint(f\"In sample Accuracy: {acc}\")\n\nprint(classification_report(train_Y, preds))\n\npreds = abc.predict(test_vecs)\nacc = accuracy_score(test_Y, preds)\nprint(f\"Out of sample Accuracy: {acc}\")\n\nprint(classification_report(test_Y, preds))\nimport pickle\npickle.dump(abc, open('\/kaggle\/working\/ada-vvlarge-964.pickle', 'wb'))\ngc.collect()\n\"\"\"\n# DL for classify\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader, WeightedRandomSampler\n\nfrom sklearn.preprocessing import MinMaxScaler    \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, classification_report\ntrainx, trainy = shuffle(train_vecs, train_Y)\ntrainx.shape, trainy.shape\ntx, vx, ty, vy = train_test_split(trainx, trainy, test_size = 0.2)\ntestx, testy = test_vecs.copy(), test_Y.copy()\ntx.shape, ty.shape, vx.shape, vy.shape, testx.shape, testy.shape\nscaler = MinMaxScaler()\ntx = scaler.fit_transform(tx)\nvx = scaler.transform(vx)\ntestx = scaler.transform(testx)\n\ntx.shape, ty.shape, vx.shape, vy.shape, testx.shape, testy.shape\nEPOCHS = 300\nBATCH_SIZE = 100\nLEARNING_RATE = 0.00007\nNUM_FEATURES = 1000\nNUM_CLASSES = NUM_OUTPUTS\nclass MulticlassClassification(nn.Module):\n    def __init__(self, num_feature, num_class):\n        super(MulticlassClassification, self).__init__()\n        \n        self.layer_1 = nn.Linear(num_feature, 512)\n        self.layer_2 = nn.Linear(512, 128)\n        self.layer_3 = nn.Linear(128, 64)\n        self.layer_out = nn.Linear(64, num_class) \n        \n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(p=0.2)\n        self.batchnorm1 = nn.BatchNorm1d(512)\n        self.batchnorm2 = nn.BatchNorm1d(128)\n        self.batchnorm3 = nn.BatchNorm1d(64)\n        \n    def forward(self, x):\n        x = self.layer_1(x)\n        x = self.batchnorm1(x)\n        x = self.relu(x)\n        \n        x = self.layer_2(x)\n        x = self.batchnorm2(x)\n        x = self.relu(x)\n        x = self.dropout(x)\n        \n        x = self.layer_3(x)\n        x = self.batchnorm3(x)\n        x = self.relu(x)\n        x = self.dropout(x)\n        \n        x = self.layer_out(x)\n        \n        return x\ngc.collect()\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\ntorch_model = MulticlassClassification(num_feature = NUM_FEATURES, num_class=NUM_CLASSES)\ntorch_model.to(device)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(torch_model.parameters(), lr=LEARNING_RATE)\nprint(torch_model)\ndef multi_acc(y_pred, y_test):\n    y_pred_softmax = torch.log_softmax(y_pred, dim = 1)\n    _, y_pred_tags = torch.max(y_pred_softmax, dim = 1)    \n    \n    correct_pred = (y_pred_tags == y_test).float()\n    acc = correct_pred.sum() \/ len(correct_pred)\n    \n    acc = torch.round(acc) * 100\n    \n    return acc\naccuracy_stats = {\n    'train': [],\n    \"val\": []\n}\nloss_stats = {\n    'train': [],\n    \"val\": []\n}\nclass ClassifierDataset(Dataset):\n    \n    def __init__(self, X_data, y_data):\n        self.X_data = X_data\n        self.y_data = y_data\n        \n    def __getitem__(self, index):\n        return self.X_data[index], self.y_data[index]\n        \n    def __len__ (self):\n        return len(self.X_data)\n\n\ntrain_dataset = ClassifierDataset(torch.from_numpy(tx).float(), torch.from_numpy(ty).long())\nval_dataset = ClassifierDataset(torch.from_numpy(vx).float(), torch.from_numpy(vy).long())\ntest_dataset = ClassifierDataset(torch.from_numpy(testx).float(), torch.from_numpy(testy).long())\ntrain_loader = DataLoader(dataset=train_dataset,\n                          batch_size=BATCH_SIZE\n)\nval_loader = DataLoader(dataset=val_dataset, batch_size=1)\ntest_loader = DataLoader(dataset=test_dataset, batch_size=1)\nprint(\"Begin training.\")\nfor e in tqdm(range(1, EPOCHS+1)):\n    # TRAINING\n    train_epoch_loss = 0\n    train_epoch_acc = 0\n    torch_model.train()\n    for X_train_batch, y_train_batch in train_loader:\n        X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device)\n        optimizer.zero_grad()\n        \n        y_train_pred = torch_model(X_train_batch)\n        \n        train_loss = criterion(y_train_pred, y_train_batch)\n        train_acc = multi_acc(y_train_pred, y_train_batch)\n        \n        train_loss.backward()\n        optimizer.step()\n        \n        train_epoch_loss += train_loss.item()\n        train_epoch_acc += train_acc.item()\n        \n        \n    # VALIDATION    \n    with torch.no_grad():\n        \n        val_epoch_loss = 0\n        val_epoch_acc = 0\n        \n        torch_model.eval()\n        for X_val_batch, y_val_batch in val_loader:\n            X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device)\n            \n            y_val_pred = torch_model(X_val_batch)\n                        \n            val_loss = criterion(y_val_pred, y_val_batch)\n            val_acc = multi_acc(y_val_pred, y_val_batch)\n            \n            val_epoch_loss += val_loss.item()\n            val_epoch_acc += val_acc.item()\n            loss_stats['train'].append(train_epoch_loss\/len(train_loader))\n    loss_stats['val'].append(val_epoch_loss\/len(val_loader))\n    accuracy_stats['train'].append(train_epoch_acc\/len(train_loader))\n    accuracy_stats['val'].append(val_epoch_acc\/len(val_loader))\n                              \n    \n    print(f'Epoch {e+0:03}: | Train Loss: {train_epoch_loss\/len(train_loader):.5f} | Val Loss: {val_epoch_loss\/len(val_loader):.5f} | Train Acc: {train_epoch_acc\/len(train_loader):.3f}| Val Acc: {val_epoch_acc\/len(val_loader):.3f}')\ny_pred_list = []\nwith torch.no_grad():\n    torch_model.eval()\n    for X_batch, _ in test_loader:\n        X_batch = X_batch.to(device)\n        y_test_pred = torch_model(X_batch)\n        y_pred_softmax = torch.log_softmax(y_test_pred, dim = 1)\n        _, y_pred_tags = torch.max(y_pred_softmax, dim = 1)\n        y_pred_list.append(y_pred_tags.cpu().numpy())\ny_pred_list = [a.squeeze().tolist() for a in y_pred_list]\nprint(classification_report(testy, y_pred_list))\npickle.dump(scaler, open('\/kaggle\/working\/torch-vvlarge.scaler.pickle', 'wb'))\ntorch.save(torch_model.state_dict(), '\/kaggle\/working\/torch-vvlarge.dict')\ngc.collect()\n\"\"\"\n# New Model\n\"\"\"\ntrainx2, trainy2 = shuffle(train_vecs, train_Y)\ntrainx2.shape, trainy2.shape\ntx2, vx2, ty2, vy2 = train_test_split(trainx, trainy, test_size = 0.2)\ntestx2, testy2 = test_vecs.copy(), test_Y.copy()\ntx2.shape, ty2.shape, vx2.shape, vy2.shape, testx2.shape, testy2.shape\nscaler = MinMaxScaler()\ntx2 = scaler.fit_transform(tx2)\nvx2 = scaler.transform(vx2)\ntestx2 = scaler.transform(testx2)\n\ntx2.shape, ty2.shape, vx2.shape, vy2.shape, testx2.shape, testy2.shape\nEPOCHS = 300\nBATCH_SIZE = 100\nLEARNING_RATE = 0.00007\nNUM_FEATURES = 1000\nNUM_CLASSES = NUM_OUTPUTS\ngc.collect()\nclass MulticlassClassification2(nn.Module):\n    def __init__(self, num_feature, num_class):\n        super(MulticlassClassification2, self).__init__()\n        \n        self.layer_1 = nn.Linear(num_feature, 512)\n        self.layer_2 = nn.Linear(512, 128)\n        self.layer_3 = nn.Linear(128, 256)\n        self.layer_4 = nn.Linear(256, 64)\n        self.layer_out = nn.Linear(64, num_class) \n        \n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(p=0.2)\n        self.batchnorm1 = nn.BatchNorm1d(512)\n        self.batchnorm2 = nn.BatchNorm1d(128)\n        self.batchnorm3 = nn.BatchNorm1d(256)\n        self.batchnorm4 = nn.BatchNorm1d(64)\n        \n    def forward(self, x):\n        x = self.layer_1(x)\n        x = self.batchnorm1(x)\n        x = self.relu(x)\n        \n        x = self.layer_2(x)\n        x = self.batchnorm2(x)\n        x = self.relu(x)\n        x = self.dropout(x)\n        \n        x = self.layer_3(x)\n        x = self.batchnorm3(x)\n        x = self.relu(x)\n        x = self.dropout(x)\n        \n        x = self.layer_4(x)\n        x = self.batchnorm4(x)\n        x = self.relu(x)\n        x = self.dropout(x)\n        \n        x = self.layer_out(x)\n        \n        return x\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\ntorch_model2 = MulticlassClassification2(num_feature = NUM_FEATURES, num_class=NUM_CLASSES)\ntorch_model2.to(device)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(torch_model2.parameters(), lr=LEARNING_RATE)\nprint(torch_model2)\n\n\n\ndef multi_acc(y_pred, y_test):\n    y_pred_softmax = torch.log_softmax(y_pred, dim = 1)\n    _, y_pred_tags = torch.max(y_pred_softmax, dim = 1)    \n    \n    correct_pred = (y_pred_tags == y_test).float()\n    acc = correct_pred.sum() \/ len(correct_pred)\n    \n    acc = torch.round(acc) * 100\n    \n    return acc\n\naccuracy_stats = {\n    'train': [],\n    \"val\": []\n}\nloss_stats = {\n    'train': [],\n    \"val\": []\n}\nclass ClassifierDataset(Dataset):\n    \n    def __init__(self, X_data, y_data):\n        self.X_data = X_data\n        self.y_data = y_data\n        \n    def __getitem__(self, index):\n        return self.X_data[index], self.y_data[index]\n        \n    def __len__ (self):\n        return len(self.X_data)\n\n\ntrain_dataset2 = ClassifierDataset(torch.from_numpy(tx2).float(), torch.from_numpy(ty2).long())\nval_dataset2 = ClassifierDataset(torch.from_numpy(vx2).float(), torch.from_numpy(vy2).long())\ntest_dataset2 = ClassifierDataset(torch.from_numpy(testx2).float(), torch.from_numpy(testy2).long())\n\ntrain_loader2 = DataLoader(dataset=train_dataset2,\n                          batch_size=BATCH_SIZE\n)\nval_loader2 = DataLoader(dataset=val_dataset2, batch_size=1)\ntest_loader2 = DataLoader(dataset=test_dataset2, batch_size=1)\nprint(\"Begin training.\")\nfor e in tqdm(range(1, EPOCHS+1)):\n    gc.collect()\n    # TRAINING\n    train_epoch_loss = 0\n    train_epoch_acc = 0\n    torch_model2.train()\n    for X_train_batch, y_train_batch in train_loader2:\n        X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device)\n        optimizer.zero_grad()\n        \n        y_train_pred = torch_model2(X_train_batch)\n        \n        train_loss = criterion(y_train_pred, y_train_batch)\n        train_acc = multi_acc(y_train_pred, y_train_batch)\n        \n        train_loss.backward()\n        optimizer.step()\n        \n        train_epoch_loss += train_loss.item()\n        train_epoch_acc += train_acc.item()\n        \n        \n    # VALIDATION    \n    with torch.no_grad():\n        \n        val_epoch_loss = 0\n        val_epoch_acc = 0\n        \n        torch_model2.eval()\n        for X_val_batch, y_val_batch in val_loader:\n            X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device)\n            \n            y_val_pred = torch_model2(X_val_batch)\n                        \n            val_loss = criterion(y_val_pred, y_val_batch)\n            val_acc = multi_acc(y_val_pred, y_val_batch)\n            \n            val_epoch_loss += val_loss.item()\n            val_epoch_acc += val_acc.item()\n            loss_stats['train'].append(train_epoch_loss\/len(train_loader))\n    loss_stats['val'].append(val_epoch_loss\/len(val_loader))\n    accuracy_stats['train'].append(train_epoch_acc\/len(train_loader))\n    accuracy_stats['val'].append(val_epoch_acc\/len(val_loader))\n                              \n    gc.collect()\n    print(f'Epoch {e+0:03}: | Train Loss: {train_epoch_loss\/len(train_loader):.5f} | Val Loss: {val_epoch_loss\/len(val_loader):.5f} | Train Acc: {train_epoch_acc\/len(train_loader):.3f}| Val Acc: {val_epoch_acc\/len(val_loader):.3f}')\ny_pred_list = []\nwith torch.no_grad():\n    torch_model2.eval()\n    for X_batch, _ in test_loader2:\n        X_batch = X_batch.to(device)\n        y_test_pred = torch_model2(X_batch)\n        y_pred_softmax = torch.log_softmax(y_test_pred, dim = 1)\n        _, y_pred_tags = torch.max(y_pred_softmax, dim = 1)\n        y_pred_list.append(y_pred_tags.cpu().numpy())\ny_pred_list = [a.squeeze().tolist() for a in y_pred_list]\n\nprint(classification_report(testy, y_pred_list))\nimport pickle\npickle.dump(scaler, open('\/kaggle\/working\/torch-2-vlarge.scaler.pickle', 'wb'))\ntorch.save(torch_model2.state_dict(), '\/kaggle\/working\/torch-2-vlarge.dict')\ngc.collect()\ndef load_img(names):\n    print(names)\n    imgs = []\n    for i, image_name in enumerate(names):\n        if i% 50 == 0 :\n            print(f\"Loading Image {i}\")\n        img = image.load_img(f'\/kaggle\/input\/vernacular-set\/{image_name}.jpeg', target_size=(IMG_SIZE, IMG_SIZE))\n        if img is None:\n            continue\n        img = np.array(img)\n        imgs.append(img)\n    return np.array(imgs)\npred_imgs = load_img(list(range(1,17)))\npred_imgs.shape\ngc.collect()\npred_vecs = get_vectors(pred_imgs)\npreds = abc.predict(pred_vecs)\nmap_to_names = lambda x: map(lambda y: \"Shirt\" if y == 0 else \"T-Shirt\" if y == 1 else \"Pant\", x)\npred_results = list(zip(map_to_names([0,1,0,0,0,0,1,0,1,1,1,0,2,2,0,0]), map_to_names(preds)))\nprint(pred_results)\nfor result, image in zip(pred_results, pred_imgs):\n    plt.figure()\n    plt.title(f\"Actual: {result[0]} | Predicted: {result[1]}\")\n    plt.imshow(image)\n    \ngc.collect()","meta":"{'source': 'AI4Code', 'id': '87111a04084c46'}"}
{"id":"119434","text":"# 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 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objs as go\ndata=pd.read_csv('\/kaggle\/input\/dataisbeautiful\/r_dataisbeautiful_posts.csv')\ndata.head()\n\"\"\"\nFind the total number of null values in the dataset\n\"\"\"\ndata.isnull().sum()\n\"\"\"\nShape of the dataset\n\"\"\"\ndata.shape\n\"\"\"\nCheck the unique values present in the high null columns\n\"\"\"\nprint('Unique values in author_flair_text',data['author_flair_text'].unique(),'\\n')\nprint('Unique values in removed_by',data['removed_by'].unique(),'\\n')\nprint('Unique values in total_awards_received',data['total_awards_received'].unique(),'\\n')\nprint('Unique values in awarders',data['awarders'].unique(),'\\n')\n\"\"\"\nauthor_flair_text and awarders columns values can't be determined by the present values in the column. Hence dropping these columns is the best approach.\n\"\"\"\ndata=data.drop(['author_flair_text','awarders'],axis=1)\ndata.head()\n\"\"\"\nFill the NaN values present in the dataset\n\"\"\"\nnan_replacements = { \"removed_by\": 'unknown', \"title\": 'unknown','total_awards_received':0.0}\ndata = data.fillna(nan_replacements)\ndata\ndata.info()\n\"\"\"\nConvert created_utc to proper format\n\"\"\"\ndata['formatted_created_utc']=pd.to_datetime(data['created_utc'],unit='s')\ndata\n\"\"\"\nCheck unique authors\n\"\"\"\n\nauthor=data['author'].value_counts().head()\nauthor_count=pd.DataFrame(author.items(), columns=['Name','Count'])\nauthor_count\n\"\"\"\nPlot depicting the top 5 people which have posted maximum to Reddit\n\"\"\"\nfig=px.bar(author_count,x='Name',y='Count')\nfig.show()\n\"\"\"\nPlot the number of awards received by authors\n\"\"\"\nnumber_of_awards_received=data['total_awards_received'].value_counts()\nnumber_of_awards_received_df=pd.DataFrame(number_of_awards_received.items(),columns=['Award Count','Author Count'])\nnumber_of_awards_received_df=number_of_awards_received_df.iloc[1:,:]\nfigure=px.bar(number_of_awards_received_df,x='Award Count',y='Author Count')\nfigure.show()\n\n\"\"\"\nValue of score of post on Reddit\n\"\"\"\nprint('Minimum score = ',data['score'].min(),' and maximum score = ',data['score'].max())\nprint('Unique values in score column is : ',data['score'].unique())\ndata['score'].value_counts()\n\"\"\"\nPlotting of score column\n\"\"\"\nsns.kdeplot(data.score)\nplt.xlabel(\"Score\")\nplt.ylabel(\"Freq\")\n\"\"\"\nGetting most popular post based on num_comments, score.\n\"\"\"\nmost_pop_num_comments=data.sort_values('num_comments',ascending=False)[['title','score','author','full_link','num_comments']].head()\nfig2=px.bar(most_pop_num_comments,x='title',y='num_comments',title='Best Reddit Post based on maximum number of comments',hover_data=['author', 'full_link'])\nfig2.show()\nmost_pop_score=data.sort_values('score',ascending=False)[['title','score','author','full_link','num_comments']].head()\nfig3=px.bar(most_pop_score,x='title',y='score',title='Best Reddit Post based on maximum score',hover_data=['author', 'full_link'])\nfig3.show()\n\"\"\"\nPosts which are for over 18\n\"\"\"\nprint(data['over_18'].value_counts())\nfrom datetime import datetime\ndata['Day']=data['formatted_created_utc'].dt.day\ndata['Month']=data['formatted_created_utc'].dt.month\ndata['Year']=data['formatted_created_utc'].dt.year\ndata['date_utc']=data['formatted_created_utc'].dt.date\ndata.head()\n\"\"\"\nNumber of post posted on each date\n\"\"\"\npost_posted_everday=data.groupby('date_utc')['title'].count().reset_index()\npost_posted_everday\n\"\"\"\nMaximum number of post dates\n\"\"\"\nmax_post_posting_date=post_posted_everday.sort_values(by='title',ascending=False).rename(columns={'title':'Post Count'}).head(10)\nfig4=px.bar(max_post_posting_date,x='date_utc',y='Post Count',title='Post Count based on date')\nfig4.show()\n\"\"\"\nNumber of Reddit post in a year\n\"\"\"\npost_in_years=data.groupby('Year')['title'].count().reset_index().rename(columns={'title':'Post Count'})\npost_in_years=post_in_years.sort_values(by='Post Count',ascending=False)\nfig5=px.bar(post_in_years,x='Year',y='Post Count',title='Post Count based on years')\nfig5.show()\n\"\"\"\nNumber of post based on months\n\"\"\"\npost_in_months=data.groupby('Month')['title'].count().reset_index().rename(columns={'title':'Post Count'})\npost_in_months=post_in_months.sort_values(by='Post Count',ascending=False)\nfig6=px.bar(post_in_months,x='Month',y='Post Count',title='Post Count based on months')\nfig6.show()\n\"\"\"\nPost count based on number of days\n\"\"\"\npost_in_days=data.groupby('Day')['title'].count().reset_index().rename(columns={'title':'Post Count'})\npost_in_days=post_in_days.sort_values(by='Post Count',ascending=False)\nfig7=px.bar(post_in_days,x='Day',y='Post Count',title='Post Count based on days')\nfig7.show()\n\"\"\"\nNumber of post based on days and months\n\"\"\"\npost_in_days_months=data.groupby(['Month','Day'])['id'].count().reset_index().rename(columns={'id':'Post Count'})\npost_in_days_months=post_in_days_months.sort_values(by='Post Count',ascending=False)\nfig8=px.bar(post_in_days_months,x='Day',y='Post Count',title='Post Count based on days and months', color='Month')\nfig8.show()\nplt.figure(figsize=(15,10))\nax = sns.boxplot(data=post_in_days_months, x='Month', y='Post Count', \n                 showfliers=False, color='yellow', linewidth=2\n                )\n\nsns.despine(offset=10, trim=True)\nax.set(xlabel='Month', ylabel='Posts')\nplt.title('Distribution of monthly post from 2012 till 2020', size=15)\nplt.show()\n\n\"\"\"\nNumber of post based on month and year\n\"\"\"\npost_in_months_year=data.groupby(['Month','Year'])['title'].count().reset_index().rename(columns={'title':'Post Count'})\npost_in_months_year=post_in_months_year.sort_values(by='Post Count',ascending=False)\nfig9=px.bar(post_in_months_year,x='Year',y='Post Count',title='Post Count based on days', color='Month')\nfig9.show()\ndata.to_csv('submission1.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'dbae29fb1aa193'}"}
{"id":"39138","text":"\"\"\"\n# Store Sales - Time series Forecasting\ud83d\udcc8\ud83d\udcc9\n\"\"\"\n\"\"\"\n### This notebook includes Data cleaning, exploratory data analysis,data visualization among different factors of the data.\n### Main technique I used is Recurrent Neural Networks which is LSTM.\n\"\"\"\n\"\"\"\n# Importing Essential Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\nsns.set_style('darkgrid')\nimport os\n\"\"\"\n# Load the dataset\n\"\"\"\ndf_holi = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/holidays_events.csv')\ndf_oil = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/oil.csv')\ndf_stores = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/stores.csv')\ndf_test = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/test.csv')\ndf_train = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/train.csv')\ndf_transactions = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/transactions.csv')\n\"\"\"\n# Exploratory Data Analysis (Analyzing and cleaning)\n\"\"\"\n\"\"\"\nThere are different types of files in this task, so instead of playing with each dataset let's create a function which will tell us all required characteristics of the particular data(file).\n\nCharacteristcs are\n- Data (first 5 records)\n- Shape of the data\n- Essential information \n- Columns in the data\n- Desciption (Statistical)\n- Datatypes of columns\n- Presence of null values\n- N\/A values form the dataset\n\"\"\"\n# function related basic eda \ndef eda_basic(df):\n    print(\"\\n >> Data <<\\n\\n\")\n    print(df.head())\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Shape <<\")\n    print(df.shape)\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Info <<\")\n    print(df.info())\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Columns <<\")\n    print(df.columns)\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Description <<\")\n    print(df.describe())\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Dataypes <<\")\n    print(df.dtypes)\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> Null values <<\")\n    print(df.isnull().sum())\n    print(\"\\n======================================\\n\")\n    print(\"\\n >> N\/A values <<\")\n    print(df.isna().sum())\n    print(\"\\n======================================\\n\")\n#     print(df.value_counts())\nprint(\"Basi EDA of holidays_event dataset\\n\")\neda_basic(df_holi)\nprint(\"Basi EDA of oil dataset\\n\")\neda_basic(df_oil)\nprint(\"Basi EDA of Stores dataset\\n\")\neda_basic(df_stores)\nprint(\"Basi EDA of train dataset\\n\")\neda_basic(df_train)\nprint(\"Basi EDA of test dataset\\n\")\neda_basic(df_test)\nprint(\"Basi EDA of transactions dataset\\n\")\neda_basic(df_transactions)\n\"\"\"\n**Date** is very important factor in the dataset\n\"\"\"\ndef date_form(df):\n    df['date'] = pd.to_datetime(df['date'], format = \"%Y-%m-%d\")\n#     df.head()\n    \n\"\"\"\n### Applying this function to all datas which contains a **Date** column\n\"\"\"\n\"\"\"\nExcept **Stores** dataset each data cotains **Date** column.\n\"\"\"\n# Applying data_from function to dataset\ndate_form(df_holi)\ndate_form(df_oil)\ndate_form(df_train)\ndate_form(df_test)\ndate_form(df_transactions)\n# df_holi.head()\n# df_oil.head()\n# df_train.head()\n# df_test.head()\n# df_transactions.head()\n\"\"\"\n# Visualization \n\"\"\"\n\"\"\"\nHere we can look through some variables and see some dependencies. Firstly, let's check the **dependency of the oil from the date**\n\"\"\"\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(20,10))\ndf_oil.plot.line(x=\"date\", y=\"dcoilwtico\", color=\"b\", ax=axes, rot=0)\nplt.title(\"Dependency of the oil from the data\")\nplt.show()\n\"\"\"\nAs we have so much rows in out dataset, it will be easier to group data, as example, by week or month. The aggregation will be made by **mean**\n\"\"\"\ndef grouped(df,key,freq,col):\n    df_grouped = df.groupby([pd.Grouper(key=key, freq=freq)]).agg(mean = (col, 'mean'))\n    df_grouped = df_grouped.reset_index()\n    return df_grouped\n\"\"\"\nGrouped data on transactions dataset\n\"\"\"\ndf_grouped_trans_w = grouped(df_transactions, 'date', 'w', 'transactions')\ndf_grouped_trans_w\n\"\"\"\nAnd, for better forecasting we'll add **time** column to our dataframe.\n\"\"\"\ndef add_time(df, key, freq, col):\n    df_grouped = grouped(df, key,freq, col)\n    df_grouped['time'] = np.arange(len(df_grouped.index))\n    column_time = df_grouped.pop('time')\n    df_grouped.insert(1, 'time', column_time)\n    return df_grouped\n\"\"\"\nSo, now we can check the results of grouping on the example of **df_train (grouped by weeks on sales, after that, mean was counted).**\n\"\"\"\ndf_grouped_train_w = add_time(df_train, 'date', 'W', 'sales')\ndf_grouped_train_m = add_time(df_train, 'date', 'M', 'sales')\ndf_grouped_train_w.head()\ndf_grouped_train_m.head()\n\"\"\"\nPlots based on **Linear Regression**\n\"\"\"\nfig, axes = plt.subplots(nrows=3, ncols=1, figsize=(30,20))\n\n# Transactions(weekly)\naxes[0].plot('date', 'mean', data=df_grouped_train_w, color='grey', marker='o')\naxes[0].set_title(\"Transactions (grouped by week)\", fontsize=20)\n\n# Sales (weekly)\naxes[1].plot('time', 'mean', data=df_grouped_train_w, color='0.75')\naxes[1].set_title('Sales (grouped by week)', fontsize=20)\n\n# Linear regression\naxes[1] = sns.regplot(x='time',\n                     y='mean',\n                     data = df_grouped_train_w,\n                     scatter_kws = dict(color='0.75'),\n                     ax = axes[1])\n\n# Sales (Monthly)\naxes[2].plot('time', 'mean', data=df_grouped_train_m, color='0.75')\naxes[2].set_title('Sales [grouped by Month]', fontsize=20)\n\n# Linear Regression\naxes[2] = sns.regplot(x='time',\n                     y = 'mean',\n                     data = df_grouped_train_m,\n                     scatter_kws = dict(color='0.75'),\n                     line_kws={\"color\": \"red\"},\n                     ax = axes[2])\n\nplt.show()\n\"\"\"\n## Lag feature\n\nLag features are values at prior timesteps that are considered useful because they are created on the assumption that what happened in the past can influence or contain a sort of intrinsic information about the future. For example, it can be beneficial to generate features for sales that happened in previous days at 4:00 p.m. if you want to predict similar sales at 4:00 p.m. the next day.\n\"\"\"\ndef add_lag(df, key, freq, col, lag):\n    df_grouped = grouped(df, key, freq, col)\n    name = 'Lag_' + str(lag)\n    df_grouped['Lag'] = df_grouped['mean'].shift(lag)\n    return df_grouped\ndf_grouped_train_w_lag1 = add_lag(df_train, 'date', 'W', 'sales',1)\ndf_grouped_train_m_lag1= add_lag(df_train, 'date', 'W', 'sales',1)\n\ndf_grouped_train_w_lag1.head()\n\"\"\"\nSo lag features let us fit curves to lag plots where each observation in a series is plotted against the previous observation. Let's build same plots, but with 'lag' feature:\n\"\"\"\nfig,axes = plt.subplots(nrows = 2, ncols=1, figsize=(30,20))\naxes[0].plot('Lag', 'mean', data=df_grouped_train_w_lag1,color=\"0.75\",linestyle=(0,(1,10)))\naxes[0].set_title('Sales (grouped by week)', fontsize=20)\naxes[0] = sns.regplot(x='Lag',\n                     y='mean',\n                     data = df_grouped_train_w_lag1,\n                     scatter_kws= dict(color='0.75'),\n                     ax = axes[0])\n\naxes[1].plot('Lag', 'mean', data=df_grouped_train_m_lag1, color=\"0.75\",linestyle=(0,(1,10)))\naxes[1].set_title(\"Sales (groupes by month)\", fontsize=20)\naxes[1] = sns.regplot(x='Lag',\n                     y='mean',\n                     data = df_grouped_train_m_lag1,\n                     scatter_kws = dict(color='0.75'),\n                     line_kws={'color':'red'},\n                     ax = axes[1])\n\nplt.show()\n\"\"\"\nExploring and visualizing the data int statistical aspect\n\"\"\"\ndef plot_stats(df, column, ax,color,angle):\n    count_classes = df[column].value_counts()\n    ax = sns.barplot(x=count_classes.index, y=count_classes, ax=ax, palette=color)\n    ax.set_title(column.upper(), fontsize=20)\n    for tick in ax.get_xticklabels():\n        tick.set_rotation(angle)\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15,5))\nfig.autofmt_xdate()\nfig.suptitle(\"Stats of df_holidays\".upper())\nplot_stats(df_holi, \"type\", axes[0], \"pastel\", 45)\nplot_stats(df_holi, \"locale\", axes[1], \"rocket\", 45)\nplt.show()\n\"\"\"\ncount values of some columns of df_stores\n\"\"\"\nfig, axes = plt.subplots(nrows = 4, ncols=1, figsize=(20,40))\nplot_stats(df_stores, \"city\", axes[0], \"mako_r\", 45)\nplot_stats(df_stores, \"state\", axes[1], \"rocket_r\", 45)\nplot_stats(df_stores, \"type\", axes[2], \"magma\", 0)\nplot_stats(df_stores, \"cluster\", axes[3], \"viridis\", 0)\n\"\"\"\nLet's **plot pie** chart for **'family'** of **df_train**\n\"\"\"\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(20,10))\ncount_classes = df_train['family'].value_counts()\nplt.title(\"Stats of df_train\".upper())\ncolors = ['#ff9999','#66b3ff','#99ff99',\n          '#ffcc99', '#ffccf9', '#ff99f8', \n          '#ff99af', '#ffe299', '#a8ff99',\n          '#cc99ff', '#9e99ff', '#99c9ff',\n          '#99f5ff', '#99ffe4', '#99ffaf']\n\nplt.pie(count_classes, \n        labels = count_classes.index, \n        autopct='%1.1f%%',\n        shadow=True, \n        startangle=90, \n        colors=colors)\n\nplt.show()\n\"\"\"\n# Forecasting the model\n\"\"\"\n\"\"\"\nLet'focus on the **family** factor\n\"\"\"\n\"\"\"\n# Data Preprocessing\n\"\"\"\ndf_train[\"family\"].nunique(dropna=True)\ndf_test.head()\n# dropping the onpromotion coz it won't be used\n\ntrain_data = df_train.copy().drop(['onpromotion'], axis=1)\ntest_data = df_test.copy().drop(['onpromotion'], axis=1)\n\"\"\"\n#### Encoding the family feature\n\"\"\"\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nordinal_encoder = OrdinalEncoder(dtype=int)\ntrain_data[['family']] = ordinal_encoder.fit_transform(train_data[['family']])\ntest_data[['family']] = ordinal_encoder.transform(test_data[['family']])\ntrain_data\n#counting number of days\nn_o_days_train=train_data[\"date\"].nunique(dropna = False) \nprint('number of day train:',n_o_days_train)\n\n# number of store\nn_o_stores_train=train_data[\"store_nbr\"].nunique(dropna = False) \nprint('number of stores train:',n_o_stores_train)\n\n# number of family\nn_o_families_train=train_data[\"family\"].nunique(dropna = False) \nprint('number of family\/type of prod train:',n_o_families_train)\n##counting the number of days\nn_o_days_test=test_data[\"date\"].nunique(dropna = False) \nprint('number of day test:',n_o_days_test)\n\n# number of store\nn_o_stores_test=test_data[\"store_nbr\"].nunique(dropna = False) \nprint('number of stores test:',n_o_stores_test)\n\n# number of family\nn_o_families_test=test_data[\"family\"].nunique(dropna = False) \nprint('number of family\/type of prod test:',n_o_families_test)\n\"\"\"\nThe data need to be re-organized as discrete-time data (days)\n date as timestamp\/time-series input, store number and family as columns and sales is the numerical data of interest for RNN\n\"\"\"\npivoted_train = train_data.pivot(index=['date'], columns=['store_nbr', 'family'], values='sales')\npivoted_train.head()\n\"\"\"\nLet's check store number 1 and product number 0\n\"\"\"\npivoted_train[1][0]\n\"\"\"\n## Splitting the data into train and validation\n\"\"\"\ntrain_samples = int(n_o_days_train*0.95)\ntrain_samples\ntrain_samples_df = pivoted_train[:train_samples]\ntrain_samples_df\nvalid_samples_df = pivoted_train[train_samples:]\nvalid_samples_df\n\"\"\"\n### Scaling the data\n\"\"\"\nminmax = MinMaxScaler()\nminmax.fit(train_samples_df)\n\nscaled_train_samples = minmax.transform(train_samples_df)\nscaled_val_samples = minmax.transform(valid_samples_df)\nscaled_train_samples[10:]\nscaled_val_samples[10:]\n\n\"\"\"\nsliding window for converting series to sample to be used with supervised learning algorithm\n\"\"\"\n# n_past --> no. of past observations\n# n_future --> no.of past observations\n\ndef split_series(series, n_past, n_future):\n    X, y = list(), list()\n    for window_start in range(len(series)):\n        past_end = window_start + n_past\n        future_end = past_end + n_future\n        if future_end > len(series):\n            break\n            \n        # slicing past and future\n        past, future = series[window_start:past_end,:], series[past_end:future_end,:]\n        X.append(past)\n        y.append(future)\n    \n    return np.array(X), np.array(y)\n\nn_past =16\nn_future = 16\nn_features = n_o_stores_train * n_o_families_train # num of features\n\"\"\"\nNow converting the data via split_series function\n\"\"\"\nX_train, y_train = split_series(scaled_train_samples, n_past, n_future)\nX_val, y_val = split_series(scaled_val_samples, n_past, n_future)\nprint('X_train.shape',X_train.shape)\nprint('y_train.shape',y_train.shape)\nprint('X_val.shape',X_val.shape)\nprint('y_val.shape',y_val.shape)\n\"\"\"\n# Traning the model - LSTM\n\"\"\"\nfrom tensorflow.keras.layers import LSTM, Dense, Embedding\nfrom tensorflow.keras.layers import Dropout, BatchNormalization, TimeDistributed\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nmodel = Sequential()\n\nmodel.add(LSTM(units=256, return_sequences=True,input_shape=[n_past, n_features]))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\nmodel.add(LSTM(units=128, return_sequences=True))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\n#TimeDistributed layer\nmodel.add(TimeDistributed(Dense(n_features)))\n\nmodel.compile(loss=\"mae\", optimizer=Adam(learning_rate=0.001), metrics=['mae'])\nmodel.summary()\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='val_mae', \n                           min_delta=0.0001,\n                           patience=100,\n                           restore_best_weights=True)\n\nepochs= 1000\n\nmodel_history = model.fit(X_train, y_train, \n                          validation_data=(X_val, y_val),\n                          epochs = epochs,\n                          callbacks = [early_stop],\n                          batch_size=512,\n                          shuffle=True)\nplt.plot(model.history.history['loss'])\nplt.plot(model.history.history['val_mae'])\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend(['Train', 'Validation'])\nplt.show()\n\"\"\"\nFrom above graph we can say that model trained well!\n\"\"\"\nX_test_pred = scaled_val_samples[-n_past:,:].reshape((1, n_past, n_features))\nprint(X_test_pred.shape)\nscaled_test_predict = model.predict(X_test_pred)\nscaled_test_predict.shape\nX_train_pred = scaled_train_samples[-n_past:,:].reshape((1, n_past, n_features))\nprint(X_train_pred.shape)\nscaled_train_predict = model.predict(X_test_pred)\nscaled_train_predict.shape\n# Inverse transform from the previous min max scaler\ny_predict = pd.DataFrame(minmax.inverse_transform(scaled_test_predict.reshape((n_future, n_features))),columns=valid_samples_df.columns)\ny_predict\npivoted_test = test_data.pivot(index=['date'], columns=['store_nbr', 'family'], values=None)\npivoted_test\npivoted_test.values\npivoted_train.values\n\"\"\"\n# Submitting resulting csv file for Kaggle competition\n\"\"\"\nsubmission = pd.read_csv('..\/input\/store-sales-time-series-forecasting\/sample_submission.csv')\n# submission\n## mapping ypredict to pivoted test data\nfor day_ith, day_ith_pred in y_predict.iterrows():\n    #day_ith iteration, 16 days in totals\n    #day_ith_pred, predicted data of 9 stores, 33 classes of good for each day\n    #Iterate over DataFrame rows as (index, Series) pairs.\n#     print(n_samples_per_day)\n    # n_samples_per_day number of \n    for n_samples_per_day in range(len(day_ith_pred)): ## iterating the number of sample, from 0 to 1781, for 16 days\n#         print(pivoted_test.iloc[[day_ith], [n_samples_per_day]])\n        sample_id = pivoted_test.iloc[[day_ith], [n_samples_per_day]].values[0][0] #total number of samples\n        values= max(0,day_ith_pred.values[n_samples_per_day]) #price that is negative will be set to 0\n        submission.at[sample_id, 'sales'] = values\nsubmission\nsubmission.to_csv('submission.csv')\n\"\"\"\n## Thank You!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '480da401e9a773'}"}
{"id":"76749","text":"\"\"\"\n# European Football Clubs Google Keywords Rankings\n\nThe most popular European Football clubs are some of the most searched keywords in many places. This is a quick overview of the domains that rank for those clubs' keywords. \n\n## Methodology\n\n- **Club selection:** I got the top clubs from the Wikipedia list, containing all [clubs that won at least one UEFA championship](https:\/\/en.wikipedia.org\/wiki\/List_of_UEFA_club_competition_winners)\n- **Keyword selection:** Every club name was appended with the word \"football\" to make it explicit and clear that it is the club and not the city (where applicable). I also did the same for seven of the top languages (based on the top seven countries who's clubs won the most championships). As a result the same keyword was requested seven times.  \nExample:\n'real madrid football', 'real madrid f\u00fatbol', 'real madrid fu\u00dfball', 'milan football, 'milan f\u00fatbol', 'milan fu\u00dfball', etc.\n\n- **Resulting data set:**  \nclubs: 79  \nlanguages: 7  \nqueries: 79 x 7 = 553  \nresults: 10 x 553 = 5,530  \n\"\"\"\n\"\"\"\n### Packages and versions\n\"\"\"\nimport advertools as adv\nimport pandas as pd\npd.options.display.max_columns = None\nfrom plotly.tools import make_subplots\nimport plotly.graph_objs as go\nimport plotly\nfrom plotly.offline import iplot, init_notebook_mode\ninit_notebook_mode()\n\nprint('Package         Version')\nprint('=' * 25)\nfor package in [plotly, pd, adv]:\n    print(f'{package.__name__:<15}', ': ', package.__version__, sep='')\n\"\"\"\n### Generating the data\nThe following code was used to generate the dataset.  \nFirst we get two tables from the Wikpedia article and save them as CSV files: \n\"\"\"\n# page = 'https:\/\/en.wikipedia.org\/wiki\/List_of_UEFA_club_competition_winners'\n# column_key = pd.read_html(page)[0]\n# column_key = column_key.rename(columns={0: 'abbreviation', 1: 'tournament'})\n# column_key.to_csv('column_key.csv', index=False)\n# clubs = pd.read_html(page)[1]\n# clubs.to_csv('clubs.csv', index=False)\n\"\"\"\n`column_key` is a table that simply lists the abbreviations in the bigger table and their expansions.\n\"\"\"\ncolumn_key = pd.read_csv('..\/input\/column_key.csv')\ncolumn_key\n\"\"\"\n`clubs` is the DataFrame that we will be working with, and below is a sample.\n\"\"\"\nclubs = pd.read_csv('..\/input\/clubs.csv')\nclubs.head(10)\n\"\"\"\nA quick exploration of the data set. \n\"\"\"\ntop_countries = (clubs\n                 .groupby('Country')\n                 .agg({'Total': 'sum'})\n                 .sort_values('Total', ascending=False)\n                 .reset_index()\n                 .head(10))\ntop_countries\n(clubs\n .groupby(['Country'])\n .agg({'Club': 'count', 'Total': 'sum'})\n .sort_values('Club', ascending=False)\n .reset_index()\n .head(9)\n .set_axis(['country', 'num_clubs', 'total_wins'], axis=1, inplace=False)\n .assign(wins_per_club=lambda df: df['total_wins'].div(df['num_clubs']))\n .style.background_gradient(high=0.2))\n\n\n\"\"\"\n* More English teams won tournaments than any other country, while Spanish teams won more tournaments per club (and more tournaments overall). \n\nThe names of the clubs will be used to run the requests to Google.\n\"\"\"\nclubs_list = clubs['Club'].str.lower().tolist()\nclubs_list[:10]\n\"\"\"\n`lang_football` is a simple dictionary listting the seven languages, and the word 'football' in that language. \n\"\"\"\nlang_football = {'en': 'football',\n                 'fr': 'football',\n                 'de': 'fu\u00dfball',\n                 'es': 'f\u00fatbol',\n                 'it': 'calcio',\n                 'pt-BR': 'futebol',\n                 'nl': 'voetbal'}\nlang_football\n\"\"\"\nThe code in the following cell generates the data set. There is some setup that needs to be done if you want to run the code yourself.\n\n1. [Create a custom search engine.](https:\/\/cse.google.com\/cse\/) At first, you might be asked to enter a site to search. Enter any domain, then go to the control panel and remove it. Make sure you enable \"Search the entire web\" and image search. You will also need to get your search engine ID, which you can find on the control panel page.\n2. [Enable the custom search API.](https:\/\/console.cloud.google.com\/apis\/library\/customsearch.googleapis.com) The service will allow you to retrieve and display search results from your custom search engine programmatically. You will need to create a project for this first.\n3. [Create credentials for this project](https:\/\/console.developers.google.com\/apis\/api\/customsearch.googleapis.com\/credentials) so you can get your key.\n4. [Enable billing for your project](https:\/\/console.cloud.google.com\/billing\/projects) if you want to run more than 100 queries per day. The first 100 queries are free; then for each additional 1,000 queries, you pay USD $5.\n\nThe [`advertools`](https:\/\/github.com\/eliasdabbas\/advertools) function `serp_goog` can take several possible parameters to customize the search query, and for this one we will be using two only: \n\n* `q`: The query we are searching for. Note that this can be a list of queries, and the looping is done for you, as in this case. \n* `hl`: The interface language (human-language). This tells Google to return results for a user who is using a computer\/browser in this specific interface language. Like all other parameters of the function, `hl` can also be provided as a list of languages. When running hundreds of queries I like to split them into a few chunks, just in case something goes wrong (a connection error for example). But you can actually generate the whole data set with one function call. \n\"\"\"\n# cx = 'YOUR_CX_FROM_GOOGLE'\n# key = 'YOUR_GOOGLE_DEV_KEY'\n\n# serp_dfs = []\n# for lang, q in lang_football.items():\n#     temp_serp = adv.serp_goog(cx=cx, key=key, \n#                               hl=lang,\n#                               q=[club + ' ' + q for club in clubs_list])\n#     serp_dfs.append(temp_serp)\n\n# serp_clubs = pd.concat(serp_dfs, sort=False)\n# serp_clubs.to_csv('serp_clubs.csv', index=False)\nserp_clubs = pd.read_csv('..\/input\/serp_clubs.csv', parse_dates=['queryTime'])\nprint(serp_clubs.shape)\nserp_clubs.head()\n\"\"\"\nI think it's a good idea to have the country of each club, and the club itself, as separate columns so we can group and analyze by country and club.  \nWe first create the `club_country` dictionary, which simply maps the clubs to their respective countries from our `clubs` DataFrame.  \nThen we create our regular expression to remove all the 'football' words. This way we can get the corresponding country for each extracted club. The same dictionary can be used to extract clubs. \n\"\"\"\nclub_country = {club.lower(): country.lower() for club, country in zip(clubs['Club'], clubs['Country'])}\nfootball_multi = '|'.join([' ' + football for football in lang_football.values()])\n\nserp_clubs['country'] = [club_country[club].title()\n                         for club in serp_clubs['searchTerms'].str.replace(football_multi, '')]\nserp_clubs['club'] = serp_clubs['searchTerms'].str.replace(football_multi, '').str.title()\nserp_clubs[['searchTerms', 'country', 'club']].sample(10)\n\"\"\"\n## Top domains\n\"\"\"\nprint('unique domains:', serp_clubs['displayLink'].nunique())\nprint('number of results:', serp_clubs.__len__())\nserp_clubs['displayLink'].value_counts().reset_index()[:10]\n\"\"\"\nAs you can see the top domains ranking for these keywords are dominated by Wikipedia. This is is not surprising, because the keywords are quite generic. Also, these are the top domains for the whole data set. It would be better to check the same for each language, country, or club, to get a more meaningful summary. \n\n#### Top domains for Barcelona:\n\"\"\"\nserp_clubs[serp_clubs['club']=='Barcelona']['displayLink'].value_counts().reset_index()[:10]\n\"\"\"\n#### Top domains for German keywords:\n\"\"\"\nserp_clubs[serp_clubs['hl']=='de']['displayLink'].value_counts().reset_index()[:10]\n\"\"\"\n#### Top domains for Italian clubs:\n\"\"\"\nserp_clubs[serp_clubs['country']=='Italy']['displayLink'].value_counts().reset_index()[:10]\n\"\"\"\nEither Italian sites need to focus on their SEO or Italian teams are extremely popular in other languages! \nThe above can be run for any other parameter, or combination of parameters as well.  \n\nI think it's also good to see if there are certain URLs that are dominant. The `link` column shows the actual landing page that the user will be directed to. \n\"\"\"\nserp_clubs['link'].value_counts().reset_index()[:10]\n\"\"\"\nIt seems seven is the highest number of appearances on SERPs for any particular URL. So we don't have any dominant landing pages, as we do with domains.  \n\n\"\"\"\n\"\"\"\n## Top-level domains (TLDs)\n\nSince we are researching clubs that belong to national leagues, and we are also searching in different languages, it might be interesting as well to check for the most used TLDs. Are they mostly .com or is there a big percentage that is on a local domain?\n\n[`advertools`](https:\/\/github.com\/eliasdabbas\/advertools) provides the `extract_urls` function among other `extract_` functions that help in getting data on hashtags, mentions, URLs, and more. In our case we would be interested in the `top_tlds` key in the resulting dictionary:\n\"\"\"\nadv.extract_urls(serp_clubs['link'])['top_tlds'][:10]\n\"\"\"\nWe can also expand this to see totals, percentages, cumulative sums, and cumulative percentages for each of the TLDs in our data set: \n\"\"\"\n(pd.DataFrame({\n    'tld': [x[0] for x in  adv.extract_urls(serp_clubs['link'])['top_tlds']],\n    'freq': [x[1] for x in  adv.extract_urls(serp_clubs['link'])['top_tlds']]\n}).assign(percentage=lambda df: df['freq'].div(df['freq'].sum()),\n          cumsum=lambda df: df['freq'].cumsum(), \n          cum_perc=lambda df: df['cumsum'].div(df['freq'].sum()))\n .head(15)\n .style.format({'percentage': '{:.2%}', 'cumsum': '{:,}', 'cum_perc': '{:.2%}'}))\n\"\"\"\n## Word frequency \nChecking the most commonly used words in a text list can help us in understanding what this list is about. A simple way is to use the `word_frequency` function from `advertools`.\n\nHere I check the word counts in the titles of those pages: \n\"\"\"\nadv.word_frequency(serp_clubs['title'],\n                   rm_words=adv.stopwords['english'].union(['-', '|', '  ', ''])).head(10)\n\"\"\"\nNothing surprising here. Mostly the generic words that you would expect to see.  \nThe same can be done by getting a subset of the data set, for example, these are the most used words in titles in Dutch: \n\"\"\"\nadv.word_frequency(serp_clubs[serp_clubs['hl']=='nl']['title'],\n                   rm_words=adv.stopwords['english'].union(['-', '|', '  ', ''])).head(10)\n\"\"\"\nSome websites don't expose their snippets to search engines, and it's good to see if we have a lot of those: \n\"\"\"\nserp_clubs['snippet'].isna().sum(), serp_clubs['title'].isna().sum()\nserp_clubs[serp_clubs['snippet'].isna()]['displayLink'].value_counts()\n\"\"\"\nOnly three domains are doing this, on a total of thirty one landing pages. Not a big issue.  \nWe can also check if there are any interesting words used in the snippets:\n\"\"\"\nadv.word_frequency(serp_clubs['snippet'].fillna(''),\n                   rm_words=adv.stopwords['english'].union(['-', '|', '  ','\u00b7', '', 'de'])).head(15)\n\"\"\"\nWord counts in snippets in English:\n\"\"\"\nadv.word_frequency(serp_clubs[serp_clubs['hl']=='en']['snippet'].fillna(''),\n                   rm_words=adv.stopwords['english'].union(['-', '|', '  ','\u00b7', '', 'de'])).head(15)\n\"\"\"\nNow it is a bit more specific, and you might want to dig deeper and see which domains focus on what kind of words; statistics, results, fixtures, etc.  \nCounting words can also be in the form of short phrases. For example, here we count the 2-word phrases used in the snippets of all SERPs for Liverpool.  \nWe only have to specify the `phrase_len` parameter to any length we want. \n\"\"\"\nadv.word_frequency(serp_clubs[serp_clubs['club']=='Liverpool']['snippet'].fillna(''),\n                   phrase_len=2,\n                   rm_words=adv.stopwords['english'].union([ '|', '', 'de'])).head(20)\n\"\"\"\n## Competitiveness: number of available results\nAs you know it's also very important to know how competitive your keywords are. One of the measures is how many pages are eligible to appear for a particular keyword. More pages usually means more competition, but not necessarily. A small number of domains might be doing very high quality\/aggressive SEO, which would make it more competitive. But the number is still a good measure, because usually if a keyword is worth competing for, it is usually a popular topic and many websites would be writing about it. \n\n#### Total results by keyword:\n\"\"\"\n(serp_clubs\n .drop_duplicates(['searchTerms'])\n .groupby('searchTerms', as_index=False)\n .agg({'totalResults': 'sum'})\n .sort_values('totalResults', ascending=False)\n .reset_index(drop=True)\n [:10]\n .style.format({'totalResults': '{:,}'}))\n\"\"\"\n#### Total results by club (across all languages):\n\"\"\"\n(serp_clubs\n .drop_duplicates(['searchTerms'])\n .groupby('club', as_index=False)\n .agg({'totalResults': 'sum'})\n .sort_values('totalResults', ascending=False)\n .reset_index(drop=True)\n [:10]\n .style.format({'totalResults': '{:,}'}))\n\"\"\"\nGood luck trying to rank for any of those keywords! \n\n## Top domains per language\n\"\"\"\nfig = make_subplots(1, 7, print_grid=False, shared_yaxes=True)\nfor i, lang in enumerate(serp_clubs['hl'].unique()[:7]):\n    df = serp_clubs[serp_clubs['hl']==lang]\n    \n    fig.append_trace(go.Bar(y=df['displayLink'].value_counts().values[:8], \n                            x=df['displayLink'].value_counts().index.str.replace('www.', '')[:8],\n                            name=lang,\n                            orientation='v'), row=1, col=i+1)\n\n\nfig.layout.margin = {'b': 150, 'r': 30}\nfig.layout.legend.orientation = 'h'\nfig.layout.legend.y = -0.5\nfig.layout.legend.x = 0.15\nfig.layout.title = 'Top Domains by Language of Search'\nfig.layout.yaxis.title = 'Number of Appearances on SERPs'\nfig.layout.plot_bgcolor = '#eeeeee'\nfig.layout.paper_bgcolor = '#eeeeee'\niplot(fig)\nfig = make_subplots(1, 7, shared_yaxes=True, print_grid=False)\nfor i, country in enumerate(serp_clubs['country'].unique()[:7]):\n    if country in top_countries['Country'][:7].values:\n        df = serp_clubs[serp_clubs['country']==country]\n\n        fig.append_trace(go.Bar(y=df['displayLink'].value_counts().values[:8], \n                                x=df['displayLink'].value_counts().index.str.replace('www.', '')[:8],\n                                name=country,\n                                orientation='v'), row=1, col=i+1)\n\nfig.layout.margin = {'b': 150, 'r': 0}\nfig.layout.legend.orientation = 'h'\nfig.layout.legend.y = -0.5\nfig.layout.legend.x = 0.15\nfig.layout.title = 'Top Domains by Country of Club'\nfig.layout.yaxis.title = 'Number of Appearances on SERPs'\nfig.layout.plot_bgcolor = '#eeeeee'\nfig.layout.paper_bgcolor = '#eeeeee'\niplot(fig)\n\"\"\"\nIn the last two charts a higher number of appearances shows that for that language, there is more concentration of ranking in a few domains. \n\n## SERP summary\/visualization\n\nFinally, we can visually summarize the results by showing which domain appeared, on each position, and how many times each. The follosing function is copied from a recipe I created to [visualize and summarize SERPs.](https:\/\/www.kaggle.com\/eliasdabbas\/coffee-and-cafe-search-engine-rankings-on-google)\n\"\"\"\ndef plot_serps(df, opacity=0.1, num_domains=10, width=None, height=700):\n    \"\"\"\n    df: a DataFrame resulting from running advertools.serp_goog\n    opacity: the opacity of the markers [0, 1]\n    num_domains: how many domains to plot\n    \"\"\"\n    top_domains = df['displayLink'].value_counts()[:num_domains].index.tolist()\n    top_df = df[df['displayLink'].isin(top_domains)]\n    top_df_counts_means = (top_df\n                       .groupby('displayLink', as_index=False)\n                       .agg({'rank': ['count', 'mean']})\n                       .set_axis(['displayLink', 'rank_count', 'rank_mean'],\n                                 axis=1, inplace=False))\n    top_df = (pd.merge(top_df, top_df_counts_means)\n          .sort_values(['rank_count', 'rank_mean'],\n                       ascending=[False, True]))\n    rank_counts = (top_df\n               .groupby(['displayLink', 'rank'])\n               .agg({'rank': ['count']})\n               .reset_index()\n               .set_axis(['displayLink', 'rank', 'count'],\n                         axis=1, inplace=False))\n    num_queries = df['queryTime'].nunique()\n    fig = go.Figure()\n    fig.add_scatter(x=top_df['displayLink'].str.replace('www.', ''),\n                    y=top_df['rank'], mode='markers',\n                    marker={'size': 35, 'opacity': opacity},\n                    showlegend=False)\n    fig.layout.height = 600\n    fig.layout.yaxis.autorange = 'reversed'\n    fig.layout.yaxis.zeroline = False\n    fig.add_scatter(x=rank_counts['displayLink'].str.replace('www.', ''),\n                y=rank_counts['rank'], mode='text',\n                marker={'color': '#000000'},\n                text=rank_counts['count'], showlegend=False)\n    for domain in rank_counts['displayLink'].unique():\n        rank_counts_subset = rank_counts[rank_counts['displayLink']==domain]\n        fig.add_scatter(x=[domain.replace('www.', '')],\n                        y=[11], mode='text',\n                        marker={'size': 50},\n                        text=str(rank_counts_subset['count'].sum()))\n        fig.add_scatter(x=[domain.replace('www.', '')],\n                        y=[12], mode='text',\n                        text=format(rank_counts_subset['count'].sum() \/ num_queries, '.1%'))\n        fig.add_scatter(x=[domain.replace('www.', '')],\n                        y=[13], mode='text',\n                        marker={'size': 50},\n                        text=str(round(rank_counts_subset['rank']\n                                       .mul(rank_counts_subset['count'])\n                                       .sum() \/ rank_counts_subset['count']\n                                       .sum(),2)))\n#     fig.layout.title = ('Google Search Results Rankings<br>keyword(s): ' + \n#                         ', '.join(list(df['searchTerms'].unique()[:5])) + \n#                         str(df['queryTime'].nunique()) + ' Football (Soccer) Queries')\n    fig.layout.hovermode = False\n    fig.layout.yaxis.autorange = 'reversed'\n    fig.layout.yaxis.zeroline = False\n    fig.layout.yaxis.tickvals = list(range(1, 14))\n    fig.layout.yaxis.ticktext = list(range(1, 11)) + ['Total<br>appearances','Coverage', 'Avg. Pos.'] \n    fig.layout.height = height\n    fig.layout.width = width\n    fig.layout.yaxis.title = 'SERP Rank (number of appearances)'\n    fig.layout.showlegend = False\n    fig.layout.paper_bgcolor = '#eeeeee'\n    fig.layout.plot_bgcolor = '#eeeeee'\n    return fig\nfig = plot_serps(serp_clubs, opacity=0.05)\nfig.layout.title = 'SERPs for \"<club_name> football\" (79 clubs)'\niplot(fig)\nfig = plot_serps(serp_clubs[serp_clubs['hl']=='es'], opacity=0.15)\nfig.layout.title = 'SERPs for \"<club_name> f\u00fatbol\" in Spanish (79 clubs)'\niplot(fig)\nfig = plot_serps(serp_clubs[serp_clubs['hl']=='en'], opacity=0.15)\nfig.layout.title = 'SERPs for \"<club_name> football\" in English (79 clubs)'\niplot(fig)\nfig = plot_serps(serp_clubs[serp_clubs['hl']=='de'], opacity=0.15)\nfig.layout.title = 'SERPs for \"<club_name> fu\u00dfball\" in German (79 clubs)'\niplot(fig)\nfig = plot_serps(serp_clubs[serp_clubs['club']=='Liverpool'], opacity=0.15, num_domains=15)\nfig.layout.title = 'SERPs for \"liverpool football\"'\niplot(fig)\n\"\"\"\nMany other options can be explored: \n* Try with other more specific keywords. <club_name> tickets, results, transfers, etc. \n* Summarize\/visualize other combinations of languages, clubs, countries. \n* Try other search parameters like user geo-location, search type, etc.\n\n## Further resources for getting, visualizing, and analyzing Google SERPs:\n\n\n* [A tutorial on how to use the `serp_goog`](https:\/\/www.kaggle.com\/eliasdabbas\/search-engine-results-pages-serps-research) function and how the different parameters work: \n* [Analyze flights and tickets SERPs](https:\/\/www.semrush.com\/blog\/analyzing-search-engine-results-pages\/) (article on SEMrush)\n* [Analyze Google and YouTube SERPs for the same keywords](https:\/\/www.kaggle.com\/eliasdabbas\/recipes-keywords-ranking-on-google-and-youtube)\n* [Documentation of the `serp_goog` function](https:\/\/advertools.readthedocs.io\/en\/master\/advertools.html#module-advertools.serp)\n* [Text analysis for online marketing](https:\/\/www.semrush.com\/blog\/text-analysis-for-online-marketers) is a tutorial to explains the `word_freq` function and what can be done to count words on an absolute and weighted basis. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8d0423e7dace1d'}"}
{"id":"29780","text":"\"\"\"\n# Using R and Python in a Kaggle Kernel \n\nOne should normally think that it is possible to use `R` within `python` on a Kaggle Kernel by simply typing `!pip install rpy2`. However this outputs the following error. \n\"\"\"\n!pip install rpy2\n\"\"\"\nNotice that `R` is not installed inside the anaconda environment. So we could use the `subprocess` library to execute a conda shell command, that is, \n\"\"\"\nimport subprocess\nsubprocess.run('conda install -c conda-forge r-base', shell=True)\n\"\"\"\nNow, we just simply type the usual command to install `rpy2`\n\"\"\"\n!pip install rpy2\n\"\"\"\nand verify by importing the module. \n\"\"\"\nimport rpy2 ","meta":"{'source': 'AI4Code', 'id': '36b71e75465ca2'}"}
{"id":"104231","text":"\"\"\"\n# Predicting Genetic Biomarker in Brain Tumor. \n\n## This Notebook only contains EDA and training data prep\n\n#### Problem \nIn this competition you will predict the genetic subtype of glioblastoma using MRI (magnetic resonance imaging) scans to train and test your model to detect for the presence of MGMT promoter methylation.\n\n#### Glossary \n\n- MGMT promoter methylation  - The presence of a specific genetic sequence in the tumor known as MGMT promoter methylation has been shown to be a favorable predictive factor and a strong predictor of responsiveness to chemotherapy.\n- Radio genomics - the field of predicting the genetics of the cancer through imaging\n- Types of mpMRI scans:\n    - Fluid Attenuated Inversion Recovery (FLAIR)\n    - T1-weighted pre-contrast (T1w)\n    - T1-weighted post-contrast (T1Gd)\n    - T2-weighted (T2)\n\n\n\n#### Notebooks Referred. \n- https:\/\/www.kaggle.com\/ayuraj\/train-brain-tumor-as-video-classification-w-b\n- https:\/\/www.kaggle.com\/ihelon\/brain-tumor-eda-with-animations-and-modeling\n- https:\/\/www.kaggle.com\/smoschou55\/advanced-eda-brain-tumor-data\/comments#Main-Competition-Workflow\n\"\"\"\nimport os\nimport re \nimport glob\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport seaborn as sns\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# Pydicom related imports\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport SimpleITK as sitk\n\n# Deep learning packages\nimport tensorflow as tf\n\n# For gif creation\nimport imageio\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n## Data Visualization\n\nThe training data contains 585 values each corresponding to a patient\/subject. \nEach row is marked with target MGMT_value for each subject (BraTS21ID) in the training data (e.g. the presence of MGMT promoter methylation).\nFrom the training set 307 subjects reported presence of MGMT promoter, and 278 reported absence. \nThe imbalance in the training data set is acceptable. \n\n\"\"\"\ntrain_df = pd.read_csv('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train_labels.csv')\nprint('Number of rows: ', len(train_df))\ntrain_df['MGMT_value'].value_counts()\nplt.figure(figsize=(5, 5))\nprint(train_df.MGMT_value.value_counts())\nsns.countplot(data=train_df, x=\"MGMT_value\");\n\"\"\"\nLet us look at the volume of training data.\n\"\"\"\ntrain_files = glob.glob('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/*\/*\/*')\nprint(f'There are {len(train_files)} dicom files in the training data')\ntest_files = glob.glob('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/test\/*\/*\/*')\nprint(f'There are {len(test_files)} dicom files in the test data')\ndf_train_labels = pd.read_csv('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train_labels.csv')\ndf_train_labels = df_train_labels.rename(columns={'BraTS21ID': 'PatientId'})\ndf_train_labels['PatientId'] = [format(x, '05d') for x in df_train_labels.PatientId]\ndf_train_labels['PatientId'] = df_train_labels['PatientId'].astype(str)\ndf_train_labels.describe()\npatients = glob.glob('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/*')\nprint(f'There are {len(patients)} patients in the training data')\npatients = glob.glob('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/test\/*')\nprint(f'There are {len(patients)} patients in the test data')\nkeys = ['FLAIR', 'T1w', 'T1wCE', 'T2w']\n\nlabel_dict = {\n    'FLAIR': [],\n    'T1w': [],\n    'T1wCE': [],\n    'T2w': []\n}\n\nlabel_dict_counts = {}\n\nfor filename in tqdm(train_files):\n    \n    scan = filename.split('\/')[-2]\n    \n    if scan=='FLAIR':\n        label_dict['FLAIR'].append(filename)\n        \n    elif scan=='T1w':\n        label_dict['T1w'].append(filename)\n\n    elif scan=='T1wCE':\n        label_dict['T1wCE'].append(filename)\n\n    else:\n        label_dict['T2w'].append(filename)\n    \nfor key in keys:\n    label_dict_counts[key] = len(label_dict[key])\n\nvalues = label_dict_counts.values()\nsns.barplot(x=keys, y=list(values))\n# Number of files per patient per Key.\ntrain_folders = '..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/'\ndf_patient_records_train = pd.DataFrame(columns=['PatientId'] + keys)\ndf_patient_records_train.set_index('PatientId')\nfor f in tqdm(os.listdir(train_folders)):\n    patientId = f\n    df_patient_records_train = df_patient_records_train.append({'PatientId': patientId, 'FLAIR': 0, 'T1w': 0, 'T1wCE': 0, 'T2w' : 0}, ignore_index=True)\n    for key in keys:\n        patientId_key_path = f'..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/{patientId}\/{key}\/*.dcm'\n        df_patient_records_train.loc[df_patient_records_train['PatientId'] == patientId, [key]] = len(glob.glob(patientId_key_path))\ndf_patient_records_train.head()\n# Number of files per patient per Key.\ntest_folders = '..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/test\/'\ndf_patient_records_test = pd.DataFrame(columns=['PatientId'] + keys)\ndf_patient_records_test.set_index('PatientId')\nfor f in tqdm(os.listdir(test_folders)):\n    patientId = f\n    df_patient_records_test = df_patient_records_test.append({'PatientId': patientId, 'FLAIR': 0, 'T1w': 0, 'T1wCE': 0, 'T2w' : 0}, ignore_index=True)\n    for key in keys:\n        patientId_key_path = f'..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/test\/{patientId}\/{key}\/*.dcm'\n        df_patient_records_test.loc[df_patient_records_test['PatientId'] == patientId, [key]] = len(glob.glob(patientId_key_path))\ndf_patient_records_test.head()\nfor key in keys:\n    df_patient_records_train[key] = df_patient_records_train[key].astype(int)\ndf_patient_records_train['PatientId'] = df_patient_records_train['PatientId'].astype(str)\ndf_patient_records_train[\"TotalFiles\"] = df_patient_records_train[keys].sum(axis=1)\nassert df_patient_records_train.TotalFiles.sum() == len(train_files)\ndf_patient_records_train.head()\nfor key in keys:\n    df_patient_records_test[key] = df_patient_records_test[key].astype(int)\ndf_patient_records_test['PatientId'] = df_patient_records_test['PatientId'].astype(str)\ndf_patient_records_test[\"TotalFiles\"] = df_patient_records_test[keys].sum(axis=1)\nassert df_patient_records_test.TotalFiles.sum() == len(test_files)\ndf_patient_records_test.head()\ndf_patient_records_train = pd.merge(df_patient_records_train, df_train_labels, on=['PatientId'])\ndf_patient_records_train.head()\ndf_patient_records_train.sort_values(by='TotalFiles', ascending=False).head(50)[keys].plot(kind='bar',figsize=(20, 8), stacked=True)\ndf_patient_records_test.sort_values(by='TotalFiles', ascending=False).head(50)[keys].plot(kind='bar',figsize=(20, 8), stacked=True)\nboxprops = dict(linestyle='-', linewidth=4, color='r')\nmedianprops = dict(linestyle='-', linewidth=4, color='b')\ndf_patient_records_train[keys].plot(kind='box', figsize=(10, 4), showfliers=True, showmeans=True,\n                boxprops=boxprops,\n                medianprops=medianprops)\nplt.suptitle(\"Distribution of files per patient\")\nplt.xlabel(\"Types\")\nplt.ylabel(\"Count of files\")\n\"\"\"\n- The images that belong to T2w are higher in number, the images that belong to T1wcE are lowest in number\n- More outliers observed for T1wCE Kind\n\"\"\"\nboxprops = dict(linestyle='-', linewidth=4, color='r')\nmedianprops = dict(linestyle='-', linewidth=4, color='b')\ndf_patient_records_test[keys].plot(kind='box', figsize=(10, 4), showfliers=True, showmeans=True,\n                boxprops=boxprops,\n                medianprops=medianprops)\nplt.suptitle(\"Distribution of files per patient\")\nplt.xlabel(\"Types\")\nplt.ylabel(\"Count of files\")\nboxprops = dict(linestyle='-', linewidth=4, color='r')\nmedianprops = dict(linestyle='-', linewidth=4, color='b')\ndf_patient_records_train['TotalFiles'].plot(kind='box', figsize=(8, 5), showfliers=True, showmeans=True,\n                boxprops=boxprops,\n                medianprops=medianprops)\nplt.suptitle(\"Distribution of Total files per patient\")\nboxprops = dict(linestyle='-', linewidth=4, color='r')\nmedianprops = dict(linestyle='-', linewidth=4, color='b')\ndf_patient_records_test['TotalFiles'].plot(kind='box', figsize=(8, 5), showfliers=True, showmeans=True,\n                boxprops=boxprops,\n                medianprops=medianprops)\nplt.suptitle(\"Distribution of Total files per patient\")\nround(pd.DataFrame.from_dict(label_dict_counts, orient='index')\/len(train_files)*100, 2).plot(kind='bar')\nplt.suptitle(\"Percentage Data by Type\")\nplt.xlabel(\"Types\")\nplt.ylabel(\"Percentage\")\ndf_patient_records_train.describe()\n\"\"\"\n### Read DICOM images\n\"\"\"\n# Reference: https:\/\/www.kaggle.com\/xhlulu\/siim-covid-19-convert-to-jpg-256px\ndef ReadMRI(path, voi_lut = True, fix_monochrome = True):\n    \n    # Original from: https:\/\/www.kaggle.com\/raddar\/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data \/ np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data\n\ndef resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        if (im.size != (size, size)):\n            im = im.resize((size, size), resample)\n    return im\ndata = ReadMRI(train_files[1])\nprint('Shape of data: ', data.shape)\nplt.rcdefaults()\nplt.figure(figsize=(5, 5))\nplt.imshow(data, cmap='gray');\n\"\"\"\n### Animate MRI images for a patient\n\"\"\"\npatientIds = os.listdir('..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train')\npatientId = np.random.choice(patientIds)\nkey = np.random.choice(keys)\n\noutput_dir_path_train = '\/kaggle\/working\/output\/images\/train' \nos.makedirs(output_dir_path_train, exist_ok=True)\n\noutput_dir_path_test = '\/kaggle\/working\/output\/images\/test' \nos.makedirs(output_dir_path_test, exist_ok=True)\n\ndef convert_dicom_to_png(patientId, key, ds_type = 'train'):\n    if ds_type == 'train':\n        mgmt_value = df_patient_records_train.loc[df_patient_records_train['PatientId'] == patientId][\"MGMT_value\"].item()\n    files_path = f'..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/{ds_type}\/{patientId}\/{key}\/*.dcm'\n#     print(len(files_path))\n    for file in glob.glob(files_path):\n        file_name = file.split('\/')[-1].split('.')[0]\n        img_data = ReadMRI(file)\n        # skipping blank images\n        if (np.count_nonzero(img_data) > 0):\n            img_data = resize(img_data, size=224)\n            if \"train\" == ds_type:\n                os.makedirs(f'{output_dir_path_train}\/{patientId}\/{key}', exist_ok=True)\n                img_data.save(f'{output_dir_path_train}\/{patientId}\/{key}\/{file_name}-{mgmt_value}.png')\n            else:\n                os.makedirs(f'{output_dir_path_test}\/{patientId}\/{key}', exist_ok=True)\n                img_data.save(f'{output_dir_path_test}\/{patientId}\/{key}\/{file_name}.png')\n\nconvert_dicom_to_png(patientId, key)\nanim_file = 'brain_scan.gif'\nwith imageio.get_writer(anim_file, mode='I') as writer:\n    filenames = glob.glob(f'{output_dir_path_train}\/{patientId}\/{key}\/Image*.png')\n    filenames = sorted(filenames)\n    for filename in filenames:\n        image = imageio.imread(filename)\n        writer.append_data(image)\n!pip install git+https:\/\/github.com\/tensorflow\/docs\nimport tensorflow_docs.vis.embed as embed\nprint(f'Showing Animated gif for patient: {patientId}, for key: {key}')\nembed.embed_file(anim_file)\n\"\"\"\n### Visualize Images per type\n\"\"\"\npatient_path = f'..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/{patientId}\/{key}'\nfor p in list(df_patient_records_train.sample(n=5).PatientId):\n    for i, key in enumerate(keys, 1):\n        patient_path = f'..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/train\/{p}\/'\n        t_paths = sorted(glob.glob(os.path.join(patient_path, key, \"*\")), key=lambda x: int(x[:-4].split(\"-\")[-1]))\n        data = ReadMRI(t_paths[int(len(t_paths)*0.5)])\n        plt.subplot(1, 4, i)\n        plt.imshow(data, cmap=\"gray\")\n        plt.title(f\"{key}\", fontsize=12)\n        plt.axis(\"off\")\n    mgmt_value = df_patient_records_train.loc[df_patient_records_train['PatientId'] == p][\"MGMT_value\"]\n    plt.suptitle(f\"MGMT_value: {mgmt_value.item()}, patient Id: {p}\", fontsize=12)\n    plt.show()\n\"\"\"\n## Convert DICOM to Images\n\"\"\"\nfor patientId in tqdm(list(df_patient_records_train.PatientId)[:100]):\n    for key in keys:\n        convert_dicom_to_png(patientId, key)\n        \n        \nfor patientId in tqdm(list(df_patient_records_test.PatientId)[:100]):\n    for key in keys:\n        convert_dicom_to_png(patientId, key, 'test')\ndf_patient_records_train.to_csv(f'{output_dir_path_train}\/train.csv')\ndf_patient_records_test.to_csv(f'{output_dir_path_test}\/test.csv')\n%%time\n!mkdir \/kaggle\/tmp\n!tar -zcf train.tar.gz -C \".\/output\/images\/train\" .\n!tar -zcf test.tar.gz -C \".\/output\/images\/test\" .\n!rm -r .\/output","meta":"{'source': 'AI4Code', 'id': 'bf7887c0d0640e'}"}
{"id":"126320","text":"# 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)\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\nimport tensorflow as tf\n\nfrom sklearn.model_selection import train_test_split as tts\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\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\ndf_crop = pd.read_csv('..\/input\/crop-recommendation-dataset\/Crop_recommendation.csv')\ndf_crop.head()\ndf_crop.isna().sum()\ndf_crop['label'].unique()\nlabel_encode = LabelEncoder()\n\ndf_crop['label'] = label_encode.fit_transform(df_crop['label'])\ncrop_category = {index : label for index, label in enumerate(label_encode.classes_)}\ncrop_category\ndf_crop\nX = df_crop.drop('label', axis = 1)\ny = df_crop['label']\nX\ny\nX_train, X_test, y_train, y_test = tts(X, y, train_size = 0.8)\nX_train.shape\ninputs = tf.keras.Input(shape = (7, ))\nx = tf.keras.layers.Dense(64, activation = 'relu')(inputs)\n# x = tf.keras.layers.Dense(64, activation = 'relu')(x)\noutputs = tf.keras.layers.Dense(22, activation = 'softmax')(x)\n\nmodel = tf.keras.Model(inputs, outputs)\n\nmodel.compile(\n    optimizer = 'adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics = 'accuracy'\n)\n\nbatch_size = 128\nepochs = 89\n\nhistory = model.fit(\n    X_train,\n    y_train,\n    validation_split = 0.2,\n    batch_size = batch_size,\n    epochs = epochs\n)\nplt.figure(figsize = (20, 10))\n\nplt.plot(range(epochs), history.history['loss'], label = 'Training loss')\nplt.plot(range(epochs), history.history['val_loss'], label = 'Validation loss')\n\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\nmodel.evaluate(X_test, y_test)\n\"\"\"\n# Please give feedback and upvote my notebook if you like this\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e847d4f4baa9d0'}"}
{"id":"17185","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport collections\ndata = pd.read_csv('\/kaggle\/input\/trump-tweets\/trumptweets.csv')\ndata.head()\ntrump_tweets = data['content']\nstring_trump = \"\"\nfor string in trump_tweets.values:\n    string_trump += string + \".\"\n \nimport nltk\n\nwords = set(nltk.corpus.words.words())\n\nstring_trump = \" \".join(w for w in nltk.wordpunct_tokenize(string_trump) if w.lower() in words or not w.isalpha())\nimport re\nstring_trump = re.sub(r'\\W+', ' ', string_trump)\nvectorizer = CountVectorizer(min_df=0, lowercase=True)\nvectorizer.fit(trump_tweets)\ntrump_voc = vectorizer.vocabulary_\n\"\"\"\nUsing favorite numbers we will asses authority value.\n\"\"\"\nfor index,row in data.iterrows():\n    for word in nltk.word_tokenize(row['content']):\n        if word in trump_voc:\n            trump_voc[word] += trump_voc[word] * (row['favorites'] + 0.01)\n        \ndf_trump = pd.DataFrame.from_dict(trump_voc,orient = 'index',columns=['count'])\ndf_trump = df_trump.reset_index()\ndf_trump.columns = ['word','count']\ndf_trump = df_trump.sort_values('count',ascending = False)\ntrump_most_val_str = \"\"\nfor index,row in df_trump.iterrows():\n    if row['count'] == float(\"inf\") or row['count'] > 10**24:\n        trump_most_val_str += \" \" + row['word']\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\nwordcloud = WordCloud(width = 1000, height = 500).generate(trump_most_val_str)\nplt.figure(figsize=(15,8))\nplt.imshow(wordcloud)\nplt.axis(\"off\")\nplt.savefig(\"your_file_name\"+\".png\", bbox_inches='tight')\nplt.show()\nplt.close()\n\"\"\"\nSo these are the words that are mostly used and getting likes. We see that political and economic parameters that are put into process are valuable\n\"\"\"\n\"\"\"\n# Generate tweets from Most liked words\n\"\"\"\nimport markovify\nfav_tweets = \"\"\nfor index,row in data.sort_values('favorites',ascending = False).head(100).iterrows():\n    fav_tweets += row['content'] + \".\"\n    \ntext_model = markovify.Text(fav_tweets)\nfor i in range(5):\n    x = text_model.make_short_sentence(200,tries = 100)\n    print(x)","meta":"{'source': 'AI4Code', 'id': '1f64df799da23e'}"}
{"id":"122936","text":"\"\"\"\n        N \u00baUsp: 11871326\n        Data: 08\/09\/2020\n\"\"\"\n\"\"\"\n# Primeiramente, importaremos tudo o que vamos precisar:\n\"\"\"\nimport pandas as pd\nimport sklearn\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nfrom sklearn import preprocessing as prep\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nimport numpy as np\n\"\"\"\n# Em seguida, importamos os dados do csv:\n\"\"\"\nnomes = [\"Age\", \"Workclass\", \"fnlwgt\", \"Education\", \"Education-Num\", \"Martial Status\",\n            \"Occupation\", \"Relationship\", \"Race\", \"Sex\", \"Capital Gain\", \"Capital Loss\",\n            \"Hours per week\", \"Country\", \"Target\"]\n\ntrain_data = pd.read_csv(\"..\/input\/adult-pmr3508\/train_data.csv\", names = nomes,\n        sep= r'\\s*,\\s*',\n        engine= 'python',\n        na_values= \"?\")\n\ntrain_data = train_data.iloc[1:]\ntrain_data.shape\ntrain_data.head()\nnomes = [\"Id\", \"Age\", \"Workclass\", \"fnlwgt\", \"Education\", \"Education-Num\", \"Martial Status\",\n            \"Occupation\", \"Relationship\", \"Race\", \"Sex\", \"Capital Gain\", \"Capital Loss\",\n            \"Hours per week\", \"Country\", \"Target\"]\ntest_data = pd.read_csv(\"..\/input\/adult-pmr3508\/test_data.csv\", names = nomes,\n        sep= r'\\s*,\\s*',\n        engine= 'python',\n        na_values= \"?\")\n\ntest_data.shape\ntest_data.head()\n\"\"\"\n# Agora vamos analizar os dados, atrav\u00e9s de graficos, para ver quais devem ser descartados para a predi\u00e7\u00e3o:  \n\"\"\"\nplt.title('Age')\nplt.ylabel('Adults')\nplt.xlabel('Age')\nplot_data = train_data[\"Age\"].value_counts()\nplot_data.plot(kind = \"line\", sharex=False)\n#plt.legend()\nplt.show()\nplot_data = train_data[\"Workclass\"].value_counts().copy()\nplot_data.plot(kind = \"bar\", fontsize=12)\nplt.title('Workclass')\nplt.ylabel('Adults')\nplt.show()\nplot_data = train_data[\"Education\"].value_counts().copy()\nplot_data.plot(kind = \"bar\", fontsize=10)\nplt.title('Education')\nplt.ylabel('Adults')\nplt.show()\n\"\"\"\nVale notar aqui que h\u00e1 uma vers\u00e3o numrica desssa feature, \"Education-Num\" que ser\u00e1 mais util na predi\u00e7\u00e3o\n\"\"\"\nplot_data = train_data[\"Martial Status\"].value_counts().copy()\nplot_data.plot(kind = \"bar\")\nplt.title('Martial Status')\nplt.ylabel('Adults')\nplt.show()\n\nplot_data = train_data[\"Occupation\"].value_counts().copy()\nplot_data.plot(kind = \"bar\", fontsize=10)\n\nplt.title('Occupation')\nplt.ylabel('Adults')\nplt.show()\nplot_data = train_data[\"Relationship\"].value_counts().copy()\nplot_data.plot(kind = \"pie\", fontsize=8, ylabel=\"\")\nplt.title('Relationship')\nplt.show()\nplot_data = train_data[\"Race\"].value_counts().copy()\nplot_data.plot(kind = \"pie\", legend=True, fontsize=0, ylabel=\"\")\n\nplt.title('Race')\nplt.show()\nplot_data = train_data[\"Sex\"].value_counts().copy()\nplot_data.plot(kind = \"pie\", ylabel=\"\", autopct='%1.0f%%', radius=1)\n\nplt.title('Sex')\nplt.show()\nplot_data = train_data[\"Country\"].value_counts().copy()\n\nus_data = plot_data[0]\nmex_data = plot_data[1]\nothers_data = 0\ni = 2\nwhile i < len(plot_data): \n    others_data += plot_data[i]\n    i += 1\n    \nx = ['United States', 'Mexico','Others']\ny = [us_data, mex_data, others_data]\n\nplt.bar(x, y)\nplt.title('Countries (US | Mex | Others)')\nplt.show()\n    \nplot_data.iloc[2:].plot(kind = \"bar\", fontsize=8)\n\nplt.title('Countries (Others)')\nplt.ylabel('Adults')\nplt.show()\n\"\"\"\n**Conclus\u00f5es:**\n1. A feature \"Country\" deve ser descartada, uma vez que US \u00e9 a esmagadora maioria     \n2. A feature \"fnlwgt\", por n\u00e3o ter nenhuma const\u00e2ncia ou rela\u00e7\u00e3o com a predi\u00e7\u00e3o, tamb\u00e9m ser\u00e1 descartada\n3. Ser\u00e1 utilizada a feature \"Education-Num\" e n\u00e3o a \"Education\", pois j\u00e1 est\u00e1 com valores num\u00e9ricos\n\"\"\"\n\"\"\"\n# Compararemos agora alguns dados em rela\u00e7\u00e3o \u00e0 feature \"income\":\n\"\"\"\ndef bar_plot(data, hue, by=\"Target\", size=20, normalize_by_index = True):\n    index = data[by].unique()\n    \n    columns = data[hue].unique()\n  \n    data_to_plot = pd.DataFrame({'index': index})\n    \n    for column in columns:\n        temp = []\n        for unique in index:\n            filtered_data = data[data[by] == unique]\n            filtered_data = filtered_data[filtered_data[hue] == column]\n            \n            temp.append(filtered_data.shape[0])\n        data_to_plot = pd.concat([data_to_plot, pd.DataFrame({column: temp})], axis = 1)\n        \n    data_to_plot = data_to_plot.set_index('index', drop = True)\n    \n    if normalize_by_index:\n        for row in index:\n            data_to_plot.loc[row] = data_to_plot.loc[row].values\/data_to_plot.loc[row].values.sum()\n    \n    ax = data_to_plot.plot.bar(rot=0, figsize = (14,7), alpha = 0.9, cmap = 'Wistia', xlabel=\"\", fontsize=size)\nbar_plot(train_data, 'Education')\nbar_plot(train_data, 'Race')\nbar_plot(train_data, 'Sex')\n\"\"\"\nAo comparar as features \"Race\" e \"Sex\" com \"income\", \u00e9 poss\u00edvel perceber as desigualdades existentes entre brancos e negros e homens e mulheres na quest\u00e3o da renda. J\u00e1 na feature \"Education\" pode-se notar que a renda \u00e9 de certa forma distribuida proporcionalmente \u00e0 quantidade de cada grupo, e n\u00e3o que quanto mais estudo maior a renda, como muitos pensam.\n\"\"\"\n\"\"\"\n# Analizemos agora os dados faltantes:\n\"\"\"\ntrain_data.isnull().sum()\n\"\"\"\nNota-se que as features \"Workclass\", \"Occupation\" e \"Country\" concentram os dados faltantes\n\n# Assim, iremos substituir esses dados pela moda nas respectivas features:\n\"\"\"\nmoda_workclass = train_data['Workclass'].describe().top\ntrain_data['Workclass'] = train_data['Workclass'].fillna(moda_workclass)\n\nmoda_occupation = train_data['Occupation'].describe().top\ntrain_data['Occupation'] = train_data['Occupation'].fillna(moda_occupation)\n\nmoda_country = train_data['Country'].describe().top\ntrain_data['Country'] = train_data['Country'].fillna(moda_country)\nmoda_workclass = test_data['Workclass'].describe().top\ntest_data['Workclass'] = test_data['Workclass'].fillna(moda_workclass)\n\nmoda_occupation = test_data['Occupation'].describe().top\ntest_data['Occupation'] = test_data['Occupation'].fillna(moda_occupation)\n\nmoda_country = test_data['Country'].describe().top\ntest_data['Country'] = test_data['Country'].fillna(moda_country)\n\"\"\"\n# Nesse momento transformaremos os dados n\u00e3o-num\u00e9ricos em dados num\u00e9ricos:\n\"\"\"\ntrain_data = train_data.apply(prep.LabelEncoder().fit_transform)\ntest_data = test_data.apply(prep.LabelEncoder().fit_transform)\n\ntrain_data.head()\n\n\"\"\"\n# Nesse ponto vamos dividir os dados em X e Y para posteriormente coloc\u00e1-los no classificador:\n\"\"\"\nfeatures = [\"Age\", \"Workclass\", \"Education\", \"Occupation\", \"Race\", \"Capital Gain\", \"Capital Loss\", \"Hours per week\"]\n\nx_train = train_data[features]\ny_train = train_data.Target\n\nx_test = test_data[features]\ny_test = test_data.Target\n\"\"\"\n# Fazemos ent\u00e3o a valida\u00e7\u00e3o cruzada desses dados:\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors = 5)\n\nscores = cross_val_score(knn, x_train, y_train, cv=10)\nscores.mean()\n\"\"\"\n# Encontraremos o melhor valor para o hyperpar\u00e2metro K: \n\"\"\"\ninf = 1\nsup = 35\n\nscores_media = []\naux = 0\nk_max = 0\n\ni = 0\nfor k in range(inf, sup):\n    knn = KNeighborsClassifier(n_neighbors = k)\n    scores = cross_val_score(knn, x_train, y_train, cv=10)\n    scores_media.append(scores.mean())\n\n    if scores_media[i] > aux:\n        k_max = k\n        aux = scores_media[i]\n\n    i = i + 1\n\nx = np.arange(1, sup)\n\nknn = KNeighborsClassifier(n_neighbors = k_max)\n\nscores = cross_val_score(knn, x_train, y_train, cv=10)\ny = scores.mean()\n\nplt.figure(figsize=(10, 5))\nplt.plot(x, scores_media, '--', color = 'red', linewidth = 2)\nplt.plot(k_max, y, 'o')\n\nplt.xlabel('K')\nplt.ylabel('Acur\u00e1cia')\nplt.title('Acur\u00e1cia da predi\u00e7\u00e3o  X  Valor de K')\n\nprint(k_max)\n\"\"\"\nAssim, vimos que o valor ideal para K \u00e9 20\n\"\"\"\n\"\"\"\n# Finalmente, colocaremos esses dados no classificador Knn e observar sua acur\u00e1cia:\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors = 20)\n\nscores = cross_val_score(knn, x_train, y_train, cv=10)\nscore = scores.mean()\n\nprint('Acur\u00e1cia para k = {0} : {1:2.2f}%'.format(k_max, 100 * score))\nknn.fit(x_train, y_train)\npredict_knn = knn.predict(x_test)\n\"\"\"\n# Portanto, ap\u00f3s analizar e preparar os dados e trein\u00e1-los no modelo KNN, obtivemos como melhor resultado 81% de acur\u00e1cia na predi\u00e7\u00e3o, o que \u00e9 um valor bastante aceit\u00e1vel no caso.\n\"\"\"\n\"\"\"\n# Finalmente, vamos transformar de volta os valores num\u00e9ricos da feature \"Income\" a <=50K e >50K\n# Ent\u00e3o escreveremos a predi\u00e7\u00e3o no csv:\n\"\"\"\nvalores_originais = {0: '<=50K', 1: '>50K'}\npredicao = np.array([valores_originais[i] for i in predict_knn], dtype=object)\n\nsubmission = pd.DataFrame()\n\nprint(len(test_data.index), len(predicao))\n\nsubmission[0] = test_data.index\nsubmission[1] = predicao\nsubmission.columns = ['Id', 'Income']\n\nsubmission.to_csv('final_results.csv',index = False)","meta":"{'source': 'AI4Code', 'id': 'e20b9e3faa116a'}"}
{"id":"31747","text":"import warnings                       # to hide warnings if any\nwarnings.filterwarnings('ignore')\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n#loading libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n#reading data set\ndf = pd.read_csv('..\/input\/data.csv')\ndf.head()\n#removing unnecessary columns\ndf = df.drop(['id', 'Unnamed: 32'], axis = 1)\ndf.head()\ndf.shape\ndf.dtypes\n#check wheter any of the columns contain null values\ndf.isnull().sum()\n\"\"\"\nConverting the diagnosis value of M and B  to a numerical value <br\/>\nM (Malignant) = 1<br\/>\nB (Benign) = 0\n\"\"\"\ndef diagnosis_value(diagnosis):\n    if diagnosis == 'M':\n        return 1\n    else:\n        return 0\n\ndf['diagnosis'] = df['diagnosis'].apply(diagnosis_value)\nsns.lmplot(x = 'radius_mean', y= 'texture_mean', hue = 'diagnosis',data = df)\nsns.lmplot(x='smoothness_mean', y = 'compactness_mean', data = df, hue = 'diagnosis')\n#loading libraries\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nX = np.array(df.iloc[:,1:])\ny = np.array(df['diagnosis'])\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.33, random_state = 42)\nknn = KNeighborsClassifier(n_neighbors = 13)\nknn.fit(X_train,y_train)\nknn.score(X_test,y_test)\n#Performing cross validation\nneighbors = []\ncv_scores = []\nfrom sklearn.model_selection import cross_val_score\n#perform 10 fold cross validation\nfor k in range(1,51,2):\n    neighbors.append(k)\n    knn = KNeighborsClassifier(n_neighbors = k)\n    scores = cross_val_score(knn,X_train,y_train,cv=10, scoring = 'accuracy')\n    cv_scores.append(scores.mean())\n    \n\n#Misclassification error versus k\nMSE = [1-x for x in cv_scores]\n\n#determining the best k\noptimal_k = neighbors[MSE.index(min(MSE))]\nprint('The optimal number of neighbors is %d ' %optimal_k)\n\n#plot misclassification error versus k\n\nplt.figure(figsize = (10,6))\nplt.plot(neighbors, MSE)\nplt.xlabel('Number of neighbors')\nplt.ylabel('Misclassification Error')\nplt.show()\n","meta":"{'source': 'AI4Code', 'id': '3a709a48900086'}"}
{"id":"127132","text":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns \nsns.set()\nfrom scipy import misc\nimport imageio as im\nimport os\nimport warnings\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\nimport itertools\nwarnings.filterwarnings('ignore')\n%config InlineBackend.figure_format = 'retina'\npath = \"\/kaggle\/input\/shapes\/shapes\/\"\nos.chdir(path)\nos.getcwd()\nimg = im.imread('circles\/drawing(1).png')\nplt.imshow(img, cmap='gray')\ndef make_labels(directory, data=[], y_hat=[], label=0):\n    for root, dirs, files in os.walk(directory):\n        for file in files:\n            img = im.imread(directory+file)\n            data.append(img)\n        y_hat = [label] * len(data)\n    return np.array(data), np.array(y_hat)\ncircles, y_circles = [], []\ncircles, y_circles = make_labels('circles\/', data=circles, y_hat=y_circles)\n\nsquares, y_squares = [], []\nsquares, y_squares = make_labels('squares\/', data=squares, y_hat=y_squares, label=1)\n\ntriangles, y_triangles = [], []\ntriangles, y_triangles = make_labels('triangles\/', data=triangles, y_hat=y_triangles, label=2)\nprint(circles.shape, squares.shape, triangles.shape)\nprint(y_circles.shape, y_squares.shape, y_triangles.shape)\nX, y = np.vstack((circles, squares, triangles)), np.hstack((y_circles, y_squares, y_triangles)).reshape(-1, 1)\nX.shape, y.shape\nimport tensorflow as tf\n\nconfig = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) \nsess = tf.Session(config=config) \nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\n \n# AlexNet-like\ndef createModel(input_shape, nclasses):\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=input_shape))\n    model.add(Conv2D(32, (3, 3), activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n \n    model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n \n    model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n \n    model.add(Flatten())\n    model.add(Dense(512, activation='relu')) # we can drop \n    model.add(Dropout(0.5))                  # this layers\n    model.add(Dense(512, activation='relu'))\n    model.add(Dropout(0.5))\n    model.add(Dense(nclasses, activation='softmax'))\n         \n    return model\nmodel = createModel(img.shape, nclasses=3)\nmodel_gen = createModel(img.shape, nclasses=3)\nmodel.summary()\nfrom sklearn.preprocessing import OneHotEncoder\n\noh = OneHotEncoder()\noh.fit(y)\ny_hot = oh.transform(y)\n\nfrom keras.utils.np_utils import to_categorical\n\ny_cat = to_categorical(y)\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y_hot, test_size=.2, random_state=42)\nx_train, x_test, y_cat_train, y_cat_test = train_test_split(X, y_cat, test_size=.2, random_state=42)\n%%time\nbatch_size = 40\nepochs = 60\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel_gen.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n \nhistory = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, \n                   validation_data=(X_test, y_test))\n\nscores = model.evaluate(X_test, y_test)\nprint(f'Logloss = {scores[0]: .5f} \\nAccuracy = {scores[1]: .2f}')\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# we can use image augmentation\n# basically it needs to redifine for normal actual scores like 0.9 of accuracy and more\ndatagen = ImageDataGenerator(\n    featurewise_center=True,\n    featurewise_std_normalization=True,\n    rotation_range=12,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=False)\ndatagen.fit(x_train)\n%%time\nepochs=120\nhistory_generator = model_gen.fit_generator(datagen.flow(x_train, y_cat_train, batch_size=batch_size),\n                    epochs=epochs, \n                    validation_data=(x_test, y_cat_test))\nscores = model_gen.evaluate(x_test, y_cat_test)\nprint(f'Logloss = {scores[0]: .5f} \\nAccuracy = {scores[1]: .2f}')\n# https:\/\/www.kaggle.com\/danbrice\/keras-plot-history-full-report-and-grid-search\ndef plot_history(history):\n    loss_list = [s for s in history.history.keys() if 'loss' in s and 'val' not in s]\n    val_loss_list = [s for s in history.history.keys() if 'loss' in s and 'val' in s]\n    acc_list = [s for s in history.history.keys() if 'acc' in s and 'val' not in s]\n    val_acc_list = [s for s in history.history.keys() if 'acc' in s and 'val' in s]\n    \n    if len(loss_list) == 0:\n        print('Loss is missing in history')\n        return \n    \n    ## As loss always exists\n    epochs = range(1,len(history.history[loss_list[0]]) + 1)\n    \n    ## Loss\n    plt.figure(1)\n    for l in loss_list:\n        plt.plot(epochs, history.history[l], 'b', label='Training loss (' + str(str(format(history.history[l][-1],'.5f'))+')'))\n    for l in val_loss_list:\n        plt.plot(epochs, history.history[l], 'g', label='Validation loss (' + str(str(format(history.history[l][-1],'.5f'))+')'))\n    \n    plt.title('Loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend()\n    \n    ## Accuracy\n    plt.figure(2)\n    for l in acc_list:\n        plt.plot(epochs, history.history[l], 'b', label='Training accuracy (' + str(format(history.history[l][-1],'.5f'))+')')\n    for l in val_acc_list:    \n        plt.plot(epochs, history.history[l], 'g', label='Validation accuracy (' + str(format(history.history[l][-1],'.5f'))+')')\n\n    plt.title('Accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.show()\n    \ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        title='Normalized confusion matrix'\n    else:\n        title='Confusion matrix'\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.show()\n    \n## multiclass or binary report\n## If binary (sigmoid output), set binary parameter to True\ndef full_multiclass_report(model,\n                           x,\n                           y_true,\n                           classes,\n                           batch_size=32,\n                           binary=False):\n\n    # 1. Transform one-hot encoded y_true into their class number\n    if not binary:\n        y_true = np.argmax(y_true,axis=1)\n    \n    # 2. Predict classes and stores in y_pred\n    y_pred = model.predict_classes(x, batch_size=batch_size)\n    \n    # 3. Print accuracy score\n    print(\"Accuracy : \"+ str(accuracy_score(y_true,y_pred)))\n    \n    print(\"\")\n    \n    # 4. Print classification report\n    print(\"Classification Report\")\n    print(classification_report(y_true,y_pred,digits=5))    \n    \n    # 5. Plot confusion matrix\n    cnf_matrix = confusion_matrix(y_true,y_pred)\n    print(cnf_matrix)\n    plot_confusion_matrix(cnf_matrix,classes=classes)\nplot_history(history)\nfull_multiclass_report(model,\n                       X_test,\n                       y_test,\n                       ['circles', 'squares', 'triangles'])\n\"\"\"\n### N.B. : this is due to the wrong settings in the datagenerator\n\"\"\"\nplot_history(history_generator)\nfull_multiclass_report(model_gen,\n                       X_test,\n                       y_test,\n                       ['circles', 'squares', 'triangles'])","meta":"{'source': 'AI4Code', 'id': 'e9d06dc6c40d63'}"}
{"id":"83611","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ninput_data_dir = \"..\/input\/bangalore-accident-data\"\ninput_data_file = \"bangalore-cas-alerts.csv\"\ninput_data_path = os.path.join(input_data_dir, input_data_file)\ndf = pd.read_csv(input_data_path)\ndf.head()\ndf.shape\ndf.dropna(inplace=True) \n# Dropping the missing values\ndf.isnull().sum()\n# Checking for null values\ndf =df.rename(columns = {'deviceCode_deviceCode':'DeviceCode',\n        'deviceCode_location_latitude':'Latitude',\n        'deviceCode_location_longitude' : 'Longitude',\n        'deviceCode_location_wardName':'WardName',\n        'deviceCode_pyld_alarmType':'AlarmType',\n        'deviceCode_pyld_speed':'Speed',\n        'deviceCode_time_recordedTime_$date':'RecordedDateTime'})\ndf = df[~df.duplicated()]\ndf.shape\n\"\"\"\n55341 rows were dupicated.\n\"\"\"\nfor i in df.columns:\n    print(i,df[i].nunique())\n    \n# getting the unique values in the data\n\"\"\"\nNoticable numbers : We have 4 types of Device Code, 50 ward Names, 7 kinds of Alarm Type\n\"\"\"\nplt.figure(figsize=[15,6])\ndf.WardName.value_counts().plot(kind='bar')\nplt.title('No. of Alarms in each ward')\nplt.show()\n# We have 2 wards names are other and Other. combining all as one\ndf.WardName = df.WardName.replace({'other':'Other'})\ndf.WardName.nunique()\n\"\"\"\nWe need to find the proper wardname for ward names mentioned as Other. Since, the ward name is determined based on Lat and Long, we'll use lat and lon to find the ward names of 'Other' category.\n\nWe are keeping non-Other Ward name as train dataset and Other category Ward name as test.. Using KNN, we are finding the Ward names mentioned as Other.\n\"\"\"\nXtrain = df[['Latitude','Longitude']][df.WardName != 'Other']\nytrain = df.WardName[df.WardName != 'Other']\nXtest = df[['Latitude','Longitude']][df.WardName == 'Other']\nytest = df.WardName[df.WardName == 'Other']\nXtrain.shape, ytrain.shape, Xtest.shape, ytest.shape\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=1,weights='distance')\nknn.fit(Xtrain,ytrain)\nypred = knn.predict(Xtest)\n\"\"\"\nThe numbers of neighbours is given as 1 because\n\nFrom the data we can see that the ward names are based on latitude and longitude and the range of latitude and longitude is very less and a large number of classes to cluster, a small k value helps us to create boundaries that are more sharper. \n\"\"\"\ndf.WardName.value_counts().head()\ndf.WardName[df.WardName =='Other'] = ypred\n# the results of knn which is in ypred is assigned to ward names categorized as Other\ndf.WardName.value_counts().head()\nplt.figure(figsize=[15,6])\nplt.subplot(1,2,1)\ndf.WardName.value_counts().head(10).plot(kind='bar')\nplt.title('Most Dangerous Wards')\n\nplt.subplot(1,2,2)\ndf.WardName.value_counts().tail(10).plot(kind='bar')\nplt.title('Most Safe Wards')\nplt.show()\n\"\"\"\nThe most dangerous wards belongs to places (Whitefield, Marathahalli) where IT companies are more. It's obversed that increase in IT parks leads to traffic in bangalore. \n\nFrom the Alarm types, we can combines few alarm types into one. For eg:\n    \n1. FCW and UFCW can be combined into FCW as both belong to collision (FCW-back and UFCW-forward)\n2. LDWL and LDWR can be combined as LDW\n\"\"\"\ndf.AlarmType = df.AlarmType.replace({'UFCW':'FCW','LDWL':'LDW','LDWR':'LDW'})\ndf.AlarmType.value_counts()\nplt.figure(figsize=[15,6])\ndf.AlarmType.value_counts().plot(kind='bar')\nplt.show()\n\"\"\"\nFCW is the most Alert Type that has been received. LDW is the least which means that turn signals are properly indicated. \n\"\"\"\ndata = df.WardName.value_counts().head(10)\nward = data.index\nward_top = df[df.WardName.isin(ward)]\nplt.figure(figsize=[15,6])\nsns.countplot(x=ward_top.WardName,hue=ward_top.AlarmType)\nplt.title('Distribution of Alarm Type in most dangerous wards')\nplt.show()\n\"\"\"\nThis graph tells us that more than moving, maximum alert has raised only during slow motion of cars which is during traffic hours. This indicates that not many accidents in bangalore are caused by overspeeding. \n\nPCW alerts is high on Kadugodi, Hagadur which indicates that pedestrians have to be careful when crossing roads \n\nOverspeeding alert are high in Hudi area.\n\"\"\"\nplt.figure(figsize=[15,6])\nsns.kdeplot(df.Speed,shade=True,color='y')\nplt.axvline(df.Speed.mean(),linestyle='dashed',linewidth='2',color='k',label=df.Speed.mean())\nplt.legend(loc='best')\nplt.title('Average Speed of the buses from 6AM to 6PM')\nplt.show()\nfig, axes = plt.subplots(3, 2, figsize=(20,10))\n\n\nsns.kdeplot(df.Speed[df.AlarmType=='PCW'],shade=True,ax=axes[0][0])\naxes[0][0].axvline(df.Speed[df.AlarmType=='PCW'].mean(),linestyle='dashed',color='k',label='PCW '+str(df.Speed[df.AlarmType=='PCW'].mean()))\naxes[0][0].legend(loc='best')\n\n\n\nsns.kdeplot(df.Speed[df.AlarmType=='FCW'],color='g',shade=True,ax=axes[0][1])\naxes[0][1].axvline(df.Speed[df.AlarmType=='FCW'].mean(),linestyle='dashed',color='k',label='FCW '+str(df.Speed[df.AlarmType=='FCW'].mean()))\naxes[0][1].legend(loc='best')\n\n\n\nsns.kdeplot(df.Speed[df.AlarmType=='Overspeed'],color='y',shade=True,ax=axes[1][0])\naxes[1][0].axvline(df.Speed[df.AlarmType=='Overspeed'].mean(),linestyle='dashed',color='k',label='Overspeed '+str(df.Speed[df.AlarmType=='Overspeed'].mean()))\naxes[1][0].legend(loc='best')\n\n\nsns.kdeplot(df.Speed[df.AlarmType=='HMW'],color='cyan',shade=True,ax=axes[1][1])\naxes[1][1].axvline(df.Speed[df.AlarmType=='HMW'].mean(),linestyle='dashed',color='k',label='HMW '+str(df.Speed[df.AlarmType=='HMW'].mean()))\naxes[1][1].legend(loc='best')\n\n\nsns.kdeplot(df.Speed[df.AlarmType=='LDW'],color='m',shade=True,ax=axes[2][0])\naxes[2][0].axvline(df.Speed[df.AlarmType=='LDW'].mean(),linestyle='dashed',color='k',label='LDW '+str(df.Speed[df.AlarmType=='LDW'].mean()))\naxes[2][0].legend(loc='best')\nplt.show()\n\"\"\"\nGraph was each type of alert has been drawn and it tells us overspeeding is not a cause for many accidents. On an average the speed of buses comes to around 22km\/hr\n\"\"\"\n\"\"\"\nObservations\n\n1. Data is provided only for the month of Feb,Mar,Apr,Jun,Jul\n2. Data is only for the year 2018\n3. Data is provided only between the time of 6AM to 6PM.\n\"\"\"\n\"\"\"\nFrom the Time stamp, we can see that the date and time is in UTC zone. As the time stamp ends with Z. Lets convert it to IST\n\"\"\"\ndf.RecordedDateTime = df.RecordedDateTime.map(lambda x : pd.Timestamp(x, tz='Asia\/Kolkata'))\ndf['Month'] = df.RecordedDateTime.dt.month_name()\ndf['Year'] = df.RecordedDateTime.dt.year\ndf['Date'] = df.RecordedDateTime.dt.day\ndf['Weekday'] = df.RecordedDateTime.dt.day_name()\ndf.Month.unique()\ndf.Year.unique()\ndf.Date.unique()\ndf['Hour'] = df.RecordedDateTime.dt.hour\ndf.Hour.unique()\nplt.figure(figsize=[15,6])\ndf.Month.value_counts().plot(kind='bar')\nplt.show()\nplt.figure(figsize=[15,6])\ndf.Weekday.value_counts().plot(kind='bar')\nplt.show()\nhr = df.Hour.value_counts().sort_index()\nhr.index\nplt.figure(figsize=[15,6])\nplt.bar(hr.index, hr.values)\nplt.xticks(np.arange(1,25))\nplt.title('No. of Alert on hourly basis')\nplt.show()\ndf.groupby('WardName')['Hour'].value_counts().sort_values(ascending=False).head(50)\ndf.groupby('WardName')['AlarmType'].value_counts().sort_values(ascending=False).head(50)\n\"\"\"\n#### Prescriptions to passengers based on observations\n\n1. Passengers should try to avoid using the most dangerous wards during the peak times(7-8 and 15-16) on weekdays.\n2. All the vehicles should have a proper gap between them especially duting traffic or slow movements of vehicles so that we can avoid the collision of vehicles for which the maximum alerts are raised.\n3. Pedestrians should be careful while crossing roads mainly in the areas of Kadugodi, Hagadur. \n4. Drivers should have a control on speed in the Hudi area as many alerts has been raised for Overspeeding. \n\"\"\"\n\"\"\"\n#### Prescriptions on improving the traffic conditions in Bangalore\n\n1. Minimum 3sec gap between vehicles to avoid collision. Strict rules to fine drivers who violate this rule would result in reducing FCW alerts. \n2. From the hours provided, we can have shift timing work in office so that vehicles are equally distributed on all hours  on roads which will lead to less traffic or we can provide work from home options. \n3. Following the traffic rules such a speed control and traffic signals so that pedestrians can be safe. Fine drivers who violate traffic rules and max speed limit to avoid PCW. Provide foot over bridge for road crossing. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '99731f5433ae40'}"}
{"id":"80947","text":"\"\"\"\n**This is the training code of this kernel https:\/\/www.kaggle.com\/a763337092\/pytorch-resnet-starter-inference?scriptVersionId=52736172\nUpvote if it helps!!!**\n\"\"\"\nimport os\nimport time\nimport pickle\nimport random\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.metrics import log_loss, roc_auc_score\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom torch.nn.modules.loss import _WeightedLoss\nimport torch.nn.functional as F\n\npd.set_option('display.max_columns', 100)\npd.set_option('display.max_rows', 100)\n\nDATA_PATH = '..\/input\/jane-street-market-prediction\/'\n\n# GPU_NUM = 8\nBATCH_SIZE = 8192# * GPU_NUM\nEPOCHS = 200\nLEARNING_RATE = 1e-3\nWEIGHT_DECAY = 1e-5\nEARLYSTOP_NUM = 3\nNFOLDS = 5\n\nTRAIN = True\nCACHE_PATH = '.\/'\n\ntrain = pd.read_csv(f'{DATA_PATH}\/train.csv')\n\ndef save_pickle(dic, save_path):\n    with open(save_path, 'wb') as f:\n    # with gzip.open(save_path, 'wb') as f:\n        pickle.dump(dic, f)\n\ndef load_pickle(load_path):\n    with open(load_path, 'rb') as f:\n    # with gzip.open(load_path, 'rb') as f:\n        message_dict = pickle.load(f)\n    return message_dict\n\nclass EarlyStopping:\n    def __init__(self, patience=7, mode=\"max\", delta=0.001):\n        self.patience = patience\n        self.counter = 0\n        self.mode = mode\n        self.best_score = None\n        self.early_stop = False\n        self.delta = delta\n        if self.mode == \"min\":\n            self.val_score = np.Inf\n        else:\n            self.val_score = -np.Inf\n\n    def __call__(self, epoch_score, model, model_path):\n\n        if self.mode == \"min\":\n            score = -1.0 * epoch_score\n        else:\n            score = np.copy(epoch_score)\n\n        if self.best_score is None:\n            self.best_score = score\n            self.save_checkpoint(epoch_score, model, model_path)\n        elif score < self.best_score: #  + self.delta\n            self.counter += 1\n            # print('EarlyStopping counter: {} out of {}'.format(self.counter, self.patience))\n            if self.counter >= self.patience:\n                self.early_stop = True\n        else:\n            self.best_score = score\n            # ema.apply_shadow()\n            self.save_checkpoint(epoch_score, model, model_path)\n            # ema.restore()\n            self.counter = 0\n\n    def save_checkpoint(self, epoch_score, model, model_path):\n        if epoch_score not in [-np.inf, np.inf, -np.nan, np.nan]:\n            # print('Validation score improved ({} --> {}). Saving model!'.format(self.val_score, epoch_score))\n            # if not DEBUG:\n            torch.save(model.state_dict(), model_path)\n        self.val_score = epoch_score\n\ndef seed_everything(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\nseed_everything(seed=42)\n\nfeat_cols = [f'feature_{i}' for i in range(130)]\n\nif TRAIN:\n    train = train.loc[train.date > 85].reset_index(drop=True)\n\n    train['action'] = (train['resp'] > 0).astype('int')\n    train['action_1'] = (train['resp_1'] > 0).astype('int')\n    train['action_2'] = (train['resp_2'] > 0).astype('int')\n    train['action_3'] = (train['resp_3'] > 0).astype('int')\n    train['action_4'] = (train['resp_4'] > 0).astype('int')\n    valid = train.loc[(train.date >= 450) & (train.date < 500)].reset_index(drop=True)\n    train = train.loc[train.date < 450].reset_index(drop=True)\ntarget_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4']\n\nif TRAIN:\n    df = pd.concat([train[feat_cols], valid[feat_cols]]).reset_index(drop=True)\n    f_mean = df.mean()\n    f_mean = f_mean.values\n    np.save(f'{CACHE_PATH}\/f_mean_online.npy', f_mean)\n\n    train.fillna(df.mean(), inplace=True)\n    valid.fillna(df.mean(), inplace=True)\nelse:\n    f_mean = np.load(f'{CACHE_PATH}\/f_mean_online.npy')\n\n##### Making features\n# https:\/\/www.kaggle.com\/lucasmorin\/running-algos-fe-for-fast-inference\/data\n# eda:https:\/\/www.kaggle.com\/carlmcbrideellis\/jane-street-eda-of-day-0-and-feature-importance\n# his example:https:\/\/www.kaggle.com\/gracewan\/plot-model\ndef fillna_npwhere_njit(array, values):\n    if np.isnan(array.sum()):\n        array = np.where(np.isnan(array), values, array)\n    return array\n\nclass RunningEWMean:\n    def __init__(self, WIN_SIZE=20, n_size=1, lt_mean=None):\n        if lt_mean is not None:\n            self.s = lt_mean\n        else:\n            self.s = np.zeros(n_size)\n        self.past_value = np.zeros(n_size)\n        self.alpha = 2 \/ (WIN_SIZE + 1)\n\n    def clear(self):\n        self.s = 0\n\n    def push(self, x):\n\n        x = fillna_npwhere_njit(x, self.past_value)\n        self.past_value = x\n        self.s = self.alpha * x + (1 - self.alpha) * self.s\n\n    def get_mean(self):\n        return self.s\n\nif TRAIN:\n    all_feat_cols = [col for col in feat_cols]\n\n    train['cross_41_42_43'] = train['feature_41'] + train['feature_42'] + train['feature_43']\n    train['cross_1_2'] = train['feature_1'] \/ (train['feature_2'] + 1e-5)\n    valid['cross_41_42_43'] = valid['feature_41'] + valid['feature_42'] + valid['feature_43']\n    valid['cross_1_2'] = valid['feature_1'] \/ (valid['feature_2'] + 1e-5)\n\n    all_feat_cols.extend(['cross_41_42_43', 'cross_1_2'])\n\n##### Model&Data fnc\nclass SmoothBCEwLogits(_WeightedLoss):\n    def __init__(self, weight=None, reduction='mean', smoothing=0.0):\n        super().__init__(weight=weight, reduction=reduction)\n        self.smoothing = smoothing\n        self.weight = weight\n        self.reduction = reduction\n\n    @staticmethod\n    def _smooth(targets:torch.Tensor, n_labels:int, smoothing=0.0):\n        assert 0 <= smoothing < 1\n        with torch.no_grad():\n            targets = targets * (1.0 - smoothing) + 0.5 * smoothing\n        return targets\n\n    def forward(self, inputs, targets):\n        targets = SmoothBCEwLogits._smooth(targets, inputs.size(-1),\n            self.smoothing)\n        loss = F.binary_cross_entropy_with_logits(inputs, targets,self.weight)\n\n        if  self.reduction == 'sum':\n            loss = loss.sum()\n        elif  self.reduction == 'mean':\n            loss = loss.mean()\n\n        return loss\n\nclass MarketDataset:\n    def __init__(self, df):\n        self.features = df[all_feat_cols].values\n\n        self.label = df[target_cols].values.reshape(-1, len(target_cols))\n\n    def __len__(self):\n        return len(self.label)\n\n    def __getitem__(self, idx):\n        return {\n            'features': torch.tensor(self.features[idx], dtype=torch.float),\n            'label': torch.tensor(self.label[idx], dtype=torch.float)\n        }\n\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.batch_norm0 = nn.BatchNorm1d(len(all_feat_cols))\n        self.dropout0 = nn.Dropout(0.2)\n\n        dropout_rate = 0.2\n        hidden_size = 256\n        self.dense1 = nn.Linear(len(all_feat_cols), hidden_size)\n        self.batch_norm1 = nn.BatchNorm1d(hidden_size)\n        self.dropout1 = nn.Dropout(dropout_rate)\n\n        self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size)\n        self.batch_norm2 = nn.BatchNorm1d(hidden_size)\n        self.dropout2 = nn.Dropout(dropout_rate)\n\n        self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size)\n        self.batch_norm3 = nn.BatchNorm1d(hidden_size)\n        self.dropout3 = nn.Dropout(dropout_rate)\n\n        self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size)\n        self.batch_norm4 = nn.BatchNorm1d(hidden_size)\n        self.dropout4 = nn.Dropout(dropout_rate)\n\n        self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols))\n\n        self.Relu = nn.ReLU(inplace=True)\n        self.PReLU = nn.PReLU()\n        self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True)\n        # self.GeLU = nn.GELU()\n        self.RReLU = nn.RReLU()\n\n    def forward(self, x):\n        x = self.batch_norm0(x)\n        x = self.dropout0(x)\n\n        x1 = self.dense1(x)\n        x1 = self.batch_norm1(x1)\n        # x = F.relu(x)\n        # x = self.PReLU(x)\n        x1 = self.LeakyReLU(x1)\n        x1 = self.dropout1(x1)\n\n        x = torch.cat([x, x1], 1)\n\n        x2 = self.dense2(x)\n        x2 = self.batch_norm2(x2)\n        # x = F.relu(x)\n        # x = self.PReLU(x)\n        x2 = self.LeakyReLU(x2)\n        x2 = self.dropout2(x2)\n\n        x = torch.cat([x1, x2], 1)\n\n        x3 = self.dense3(x)\n        x3 = self.batch_norm3(x3)\n        # x = F.relu(x)\n        # x = self.PReLU(x)\n        x3 = self.LeakyReLU(x3)\n        x3 = self.dropout3(x3)\n\n        x = torch.cat([x2, x3], 1)\n\n        x4 = self.dense4(x)\n        x4 = self.batch_norm4(x4)\n        # x = F.relu(x)\n        # x = self.PReLU(x)\n        x4 = self.LeakyReLU(x4)\n        x4 = self.dropout4(x4)\n\n        x = torch.cat([x3, x4], 1)\n\n        x = self.dense5(x)\n\n        return x\n\ndef train_fn(model, optimizer, scheduler, loss_fn, dataloader, device):\n    model.train()\n    final_loss = 0\n\n    for data in dataloader:\n        optimizer.zero_grad()\n        features = data['features'].to(device)\n        label = data['label'].to(device)\n        outputs = model(features)\n        loss = loss_fn(outputs, label)\n        loss.backward()\n        optimizer.step()\n        if scheduler:\n            scheduler.step()\n\n        final_loss += loss.item()\n\n    final_loss \/= len(dataloader)\n\n    return final_loss\n\ndef inference_fn(model, dataloader, device):\n    model.eval()\n    preds = []\n\n    for data in dataloader:\n        features = data['features'].to(device)\n\n        with torch.no_grad():\n            outputs = model(features)\n\n        preds.append(outputs.sigmoid().detach().cpu().numpy())\n\n    preds = np.concatenate(preds).reshape(-1, len(target_cols))\n\n    return preds\n\ndef utility_score_bincount(date, weight, resp, action):\n    count_i = len(np.unique(date))\n    # print('weight: ', weight)\n    # print('resp: ', resp)\n    # print('action: ', action)\n    # print('weight * resp * action: ', weight * resp * action)\n    Pi = np.bincount(date, weight * resp * action)\n    t = np.sum(Pi) \/ np.sqrt(np.sum(Pi ** 2)) * np.sqrt(250 \/ count_i)\n    u = np.clip(t, 0, 6) * np.sum(Pi)\n    return u\n\nif TRAIN:\n    train_set = MarketDataset(train)\n    train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)\n    valid_set = MarketDataset(valid)\n    valid_loader = DataLoader(valid_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)\n\n    start_time = time.time()\n    for _fold in range(NFOLDS):\n        print(f'Fold{_fold}:')\n        seed_everything(seed=42+_fold)\n        torch.cuda.empty_cache()\n        device = torch.device(\"cuda:0\")\n        model = Model()\n        model.to(device)\n        # model = nn.DataParallel(model)\n\n        optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n        # optimizer = Nadam(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n        # optimizer = Lookahead(optimizer=optimizer, k=10, alpha=0.5)\n        scheduler = None\n        # scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=0.1, div_factor=1e3,\n        #                                                 max_lr=1e-2, epochs=EPOCHS, steps_per_epoch=len(train_loader))\n        # loss_fn = nn.BCEWithLogitsLoss()\n        loss_fn = SmoothBCEwLogits(smoothing=0.005)\n\n        model_weights = f\"{CACHE_PATH}\/online_model{_fold}.pth\"\n        es = EarlyStopping(patience=EARLYSTOP_NUM, mode=\"max\")\n        for epoch in range(EPOCHS):\n            train_loss = train_fn(model, optimizer, scheduler, loss_fn, train_loader, device)\n\n            valid_pred = inference_fn(model, valid_loader, device)\n            valid_auc = roc_auc_score(valid[target_cols].values, valid_pred)\n            valid_logloss = log_loss(valid[target_cols].values, valid_pred)\n            valid_pred = np.median(valid_pred, axis=1)\n            valid_pred = np.where(valid_pred >= 0.5, 1, 0).astype(int)\n            valid_u_score = utility_score_bincount(date=valid.date.values, weight=valid.weight.values,\n                                                   resp=valid.resp.values, action=valid_pred)\n            print(f\"FOLD{_fold} EPOCH:{epoch:3} train_loss={train_loss:.5f} \"\n                      f\"valid_u_score={valid_u_score:.5f} valid_auc={valid_auc:.5f} \"\n                      f\"time: {(time.time() - start_time) \/ 60:.2f}min\")\n            es(valid_auc, model, model_path=model_weights)\n            if es.early_stop:\n                print(\"Early stopping\")\n                break\n        # torch.save(model.state_dict(), model_weights)\n    if True:\n        valid_pred = np.zeros((len(valid), len(target_cols)))\n        for _fold in range(NFOLDS):\n            torch.cuda.empty_cache()\n            device = torch.device(\"cuda:0\")\n            model = Model()\n            model.to(device)\n            model_weights = f\"{CACHE_PATH}\/online_model{_fold}.pth\"\n            model.load_state_dict(torch.load(model_weights))\n\n            valid_pred += inference_fn(model, valid_loader, device) \/ NFOLDS\n        auc_score = roc_auc_score(valid[target_cols].values, valid_pred)\n        logloss_score = log_loss(valid[target_cols].values, valid_pred)\n\n        valid_pred = np.median(valid_pred, axis=1)\n        valid_pred = np.where(valid_pred >= 0.5, 1, 0).astype(int)\n        valid_score = utility_score_bincount(date=valid.date.values, weight=valid.weight.values, resp=valid.resp.values,\n                                             action=valid_pred)\n        print(f'{NFOLDS} models valid score: {valid_score}\\tauc_score: {auc_score:.4f}\\tlogloss_score:{logloss_score:.4f}')","meta":"{'source': 'AI4Code', 'id': '949eeec3679d36'}"}
{"id":"62632","text":"\"\"\"\n1. \u0412\u0438\u043a\u043e\u043d\u0430\u0442\u0438 \u043a\u043b\u0430\u0441\u0438\u0444\u0456\u043a\u0430\u0446\u0456\u044e \u043d\u0430\u0431\u043e\u0440\u0443 \u0434\u0430\u043d\u0438\u0445 \"Sonar classification\" (\nhttps:\/\/archive.ics.uci.edu\/ml\/machine-learning-databases\/ionosphere\/).\n\n2. \u0420\u043e\u0437\u0440\u043e\u0431\u0438\u0442\u0438 \u043c\u043e\u0434\u0435\u043b\u0456 \u0442\u0440\u0438 \u043c\u043e\u0434\u0435\u043b\u0456\n\u2022 \u0434\u0435\u0440\u0435\u0432\u043e \u0440\u0456\u0448\u0435\u043d\u044c;\n\u2022 \u0431\u0435\u0433\u0456\u043d\u0433 \u0434\u0435\u0440\u0435\u0432 \u0440\u0456\u0448\u0435\u043d\u044c;\n\u2022 \u0432\u0438\u043f\u0430\u0434\u043a\u043e\u0432\u0438\u0439 \u043b\u0456\u0441;\n\n3. \u041f\u0440\u043e\u0432\u0435\u0441\u0442\u0438 \u043e\u0431\u0447\u0438\u0441\u043b\u044e\u0432\u0430\u043b\u044c\u043d\u0456 \u0435\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u0438 \u0437 \u0440\u0456\u0437\u043d\u0438\u043c\u0438 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438\n\u043c\u043e\u0434\u0435\u043b\u0435\u0439 \u0442\u0430 \u0437\u043d\u0430\u0439\u0442\u0438 \u043e\u043f\u0442\u0438\u043c\u0430\u043b\u044c\u043d\u0443 \u043a\u043e\u043d\u0444\u0456\u0433\u0443\u0440\u0430\u0446\u0456\u044e \u0437 \u043d\u0430\u0439\u0431\u0456\u043b\u044c\u0448\u043e\u044e \u0442\u043e\u0447\u043d\u0456\u0441\u0442\u044e\n\u043a\u043b\u0430\u0441\u0438\u0444\u0456\u043a\u0430\u0446\u0456\u0457\n\"\"\"\n\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestClassifier, BaggingClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import tree\nimport pandas as pd\nimport seaborn as sns\nimport graphviz\nimport random\n\n# \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u043a\u043e\u043b\u043e\u043d\u043e\u043a\ncolumns = [f'prop_{str(i)}' for i in range(1, 35)] + ['class']\n\n# \u0441\u0447\u0438\u0442\u044b\u0432\u0430\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\ndata = pd.read_csv('..\/input\/ionosphere\/ionosphere.csv', delimiter=',', names=columns)\n\ndf = pd.DataFrame(data) # \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u0430 DataFrame\ndf.head(10)\ndf.loc[df['class'] == 'g', 'class'] = 1\ndf.loc[df['class'] == 'b', 'class'] = 0\ndf.head(10)\n# \u043d\u0430\u0431\u043e\u0440 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u0443\u0434\u0443\u0442 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u0432\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438\ninformation = df.loc[:,columns[3:-1]]\nresearch = df['class'] # \u043d\u0430\u0431\u043e\u0440 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043b\u044f \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u044b\u0445 \u043c\u043e\u0434\u0435\u043b\u0435\u0439\n\n# \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445 , \u0441\u043e\u0437\u0434\u0430\u044e\u0442\u0441\u044f 4 \"\u043f\u043e\u0440\u0446\u0438\u0438\" \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438\nX_train, X_test, Y_train, Y_test = train_test_split(information, research, test_size=0.4, random_state=0)\nY_train = Y_train.astype('int')\nY_test = Y_test.astype('int')\n#\u0414\u0440\u0435\u0432\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0439\nclf = DecisionTreeClassifier(max_depth=10)\nclf.fit(X_train, Y_train)\nY_pred = clf.predict(X_test) \ndec_tree_score = clf.score(X_test, Y_test)\nprint('\u0414\u0435\u0440\u0435\u0432\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0439: ', dec_tree_score)\n\ndot_data = tree.export_graphviz(clf, out_file=None, feature_names=information.columns, \n                                class_names=['good', 'bad'], filled=True, rounded=True,  \n                                special_characters=True)\ngraph = graphviz.Source(dot_data)  \ngraph\n#\u0411\u0435\u0433\u0433\u0438\u043d\u0433 \u0434\u0435\u0440\u0435\u0432\u044c\u0435\u0432 \u0440\u0435\u0448\u0435\u043d\u0438\u044f\ntrees_amount = 500\nclf = BaggingClassifier(DecisionTreeClassifier(), n_estimators=trees_amount, max_samples=50, \n                        bootstrap=True, n_jobs=-1)\nclf.fit(X_train, Y_train)\nY_pred = clf.predict(X_test) \nbag_score = clf.score(X_test, Y_test)\nprint('\u0411\u0435\u0433\u0433\u0438\u043d\u0433 \u0434\u0435\u0440\u0435\u0432\u044c\u0435\u0432 \u0440\u0435\u0448\u0435\u043d\u0438\u044f: ', bag_score)\n\nrandom_tree_number = random.randint(0, trees_amount - 1)\nestimator = clf.estimators_[random_tree_number]  # \u0438\u0437\u0432\u043b\u0435\u0447\u044c \u043e\u0434\u043d\u043e \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u043e\u0435 \u0434\u0435\u0440\u0435\u0432\u043e\ndot_data = tree.export_graphviz(estimator, out_file=None, feature_names=information.columns, \n                                class_names=['good', 'bad'], filled=True, rounded=True,  \n                                special_characters=True, precision=2)\ngraph = graphviz.Source(dot_data)  \ngraph\n# \u0421\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0439 \u043b\u0435\u0441\ntrees_amount = 100\n\nclf = RandomForestClassifier(n_estimators=trees_amount, max_depth=5, random_state=0)\nclf = clf.fit(X_train, Y_train) \nY_pred = clf.predict(X_test) \nrand_frst_score = clf.score(X_test, Y_test) \nprint('\u0421\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0439 \u043b\u0435\u0441: ',rand_frst_score) \n\nrandom_tree_number = random.randint(0, trees_amount - 1)\nestimator = clf.estimators_[random_tree_number]  # \u0438\u0437\u0432\u043b\u0435\u0447\u044c \u043e\u0434\u043d\u043e \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u043e\u0435 \u0434\u0435\u0440\u0435\u0432\u043e\ndot_data = tree.export_graphviz(estimator, out_file=None, feature_names=information.columns, \n                                class_names=['good', 'bad'], filled=True, rounded=True,  \n                                special_characters=True, precision=2)\ngraph = graphviz.Source(dot_data)  \ngraph\n\"\"\"\n\u0412\u044b\u0432\u043e\u0434:\n\n\u0412 \u0434\u0430\u043d\u043d\u043e\u0439 \u043b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u0435 \u043c\u044b \u0440\u0430\u0431\u043e\u0442\u0430\u043b\u0438 \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 ionospehere. \u042d\u0442\u0438 \u0434\u0430\u043d\u043d\u044b\u0435 \u0438\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u0431\u044b\u043b\u0438 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u044b \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u0440\u0430\u0434\u0430\u0440\u043e\u0432, \u0441\u043e\u0441\u0442\u043e\u044f\u0449\u0435\u0439 \u0438\u0437 16 \u0432\u044b\u0441\u043e\u043a\u043e\u0447\u0430\u0441\u0442\u043e\u0442\u043d\u044b\u0445 \u0430\u043d\u0442\u0435\u043d\u043d \u0441 \u0441\u0443\u043c\u043c\u0430\u0440\u043d\u043e\u0439 \u043c\u043e\u0449\u044c\u043d\u043e\u0441\u0442\u044c\u044e \u043e\u043a\u043e\u043b\u043e 6.4 \u043a\u0412. \u0426\u0435\u043b\u044c\u044e \u0431\u044b\u043b\u0438 \u0441\u0432\u043e\u0431\u043e\u0434\u043d\u044b\u0435 \u044d\u043b\u0435\u043a\u0442\u0440\u043e\u043d\u044b \u0432 \u0438\u043e\u043d\u043e\u0441\u0444\u0435\u0440\u0435. \"\u0425\u043e\u0440\u043e\u0448\u0438\u0439\" \u0440\u0430\u0434\u0430\u0440 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u043b \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043e\u0431 \u044d\u043b\u0435\u043a\u0442\u0440\u043e\u043d\u044b\u0445 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u043d\u043e\u0439 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0432 \u0438\u043e\u043d\u043e\u0441\u0444\u0435\u0440\u0435, \"\u043f\u043b\u043e\u0445\u043e\u0439\" - \u0442\u0435, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043f\u0440\u043e\u0445\u043e\u0434\u0438\u043b\u0438 \u0441\u043a\u0432\u043e\u0437\u044c \u0438\u043e\u043d\u043e\u0441\u0444\u0435\u0440\u0443.\n\n\u0414\u0430\u043d\u043d\u044b\u0435 ionospehere \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442 \u0432 \u0441\u0435\u0431\u0435 351 \u0437\u0430\u043f\u0438\u0441\u044c \u0441 34 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u043c\u0438 \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430\u043c\u0438 \u0438 1 \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u043e\u043c \"\u043a\u043b\u0430\u0441\u0441\u0430\" ('g' - good, 'b' - bad).\n\n\u0411\u044b\u043b\u0438 \u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u044b \u0442\u0440\u0438 \u043c\u043e\u0434\u0435\u043b\u0438:\u0414\u0435\u0440\u0435\u0432\u043e \u0440\u0435\u0448\u0435\u043d\u0438\u0439, \u0411\u0435\u0433\u0433\u0438\u043d\u0433 \u0434\u0435\u0440\u0435\u0432\u044c\u0435\u0432 \u0440\u0435\u0448\u0435\u043d\u0438\u044f, \u0421\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0439 \u043b\u0435\u0441.\n\n\u0414\u043b\u044f \u0442\u0435\u043a\u0443\u0449\u0435\u0433\u043e \u043d\u0430\u0431\u043e\u0440\u0430 \u0434\u0430\u043d\u043d\u044b\u0445, \u043d\u0430\u0438\u0431\u043e\u043b\u044c\u0448\u0443\u044e \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c \u0438\u043c\u0435\u043b \u0421\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0439 \u043b\u0435\u0441.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '736b10d8dce241'}"}
{"id":"125193","text":"\"\"\"\n## Simple Beginner kernel using logistic regression\n\"\"\"\n\"\"\"\n### Imports\n\"\"\"\nimport pandas as pd \nimport numpy as np\ntrain=pd.read_csv(\"..\/input\/train.csv\")\ntest=pd.read_csv(\"..\/input\/test.csv\")\ntrain.head()\ntrain.drop(['Name'],axis=1,inplace=True)\ntrain.head()\ntrain.columns\ntrain.index\nsample_sub=pd.read_csv(\"..\/input\/gender_submission.csv\")\nsample_sub.head()\ntrain.head()\ntest.head()\ntest.drop(['Name'],axis=1,inplace=True)\ntest.head()\n\"\"\"\n### Checking for null values\n\"\"\"\ntrain.isnull().sum()\ntrain.index\ntest.isnull().sum()\n\"\"\"\n### Dropping columns with too much null values and non required data\n\"\"\"\ntrain.drop(['Cabin'],axis=1,inplace=True)\ntest.drop(['Cabin'],axis=1,inplace=True)\ntest.drop(['Ticket'],axis=1,inplace=True)\ntrain.drop(['Ticket'],axis=1,inplace=True)\ntrain.drop(['PassengerId'],axis=1,inplace=True)\ntest.drop(['PassengerId'],axis=1,inplace=True)\ntest.head()\ntrain.head()\n\"\"\"\n### Visualization\n\"\"\"\nimport seaborn as sns\nsns.countplot(x='Survived',hue='Sex',data=train)\nsns.countplot(x='Survived',hue='Parch',data=train)\nsns.countplot(x='Survived',hue='SibSp',data=train)\nsns.countplot(x='Survived',hue='Pclass',data=train)\n\"\"\"\n### transformation\n\"\"\"\ntrain.isnull().sum()\ntest.isnull().sum()\ntrain['Age'].mean()\n\"\"\"\n### Replacing null values by mean of the vaues of column data\n\"\"\"\ntrain['Age'].fillna((train['Age'].mean()), inplace=True)\ntest['Age'].fillna((test['Age'].mean()), inplace=True)\ntest['Fare'].fillna((test['Fare'].mean()), inplace=True)\n\"\"\"\n#### Dropping null values from train\n\"\"\"\ntrain.dropna()\ntest.isnull().sum()\ntrain.columns\ntrain.head()\ntest.head()\n\"\"\"\n### Transforming instead of skewing\n\"\"\"\nPclass=pd.get_dummies(train['Pclass'],drop_first=True)\nPclass1=pd.get_dummies(test['Pclass'],drop_first=True)\nSex=pd.get_dummies(train['Sex'],drop_first=True)\nSex1=pd.get_dummies(test['Sex'],drop_first=True)\nEmbarked=pd.get_dummies(train['Embarked'],drop_first=True)\nEmbarked1=pd.get_dummies(test['Embarked'],drop_first=True)\n\"\"\"\n### Joining newly created dummy data columns \n\"\"\"\ntrain=pd.concat([train,Pclass,Sex,Embarked],axis=1)\ntest=pd.concat([test,Pclass1,Sex1,Embarked1],axis=1)\n\"\"\"\n### Dropping old columns\n\"\"\"\ntrain.drop(['Sex','Embarked','Pclass'],axis=1,inplace=True)\ntest.drop(['Sex','Embarked','Pclass'],axis=1,inplace=True)\ntrain.head()\ntest.head()\nsample_sub.head()\n\"\"\"\n## Modelling\n\"\"\"\nfrom sklearn.model_selection import train_test_split\ny=train['Survived']\ny.head()\nX=train.drop('Survived',axis=1)\nX.head()\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)\n\"\"\"\n### Fitting the data into model\n\"\"\"\n\"\"\"\n##### Model 1\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlogmodel = LogisticRegression()\nlogmodel.fit(X_train,y_train)\npredictions = logmodel.predict(X_test)\nfrom sklearn.metrics import classification_report\nclassification_report(y_test,predictions)\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_test,predictions)\n(145+67)\/(41+67+15+145)\n\"\"\"\n##### Model 2\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score\ngbk = GradientBoostingClassifier()\ngbk.fit(X_train, y_train)\ny_pred = gbk.predict(X_test)\nacc_gbk = round(accuracy_score(y_pred, y_test) * 100, 2)\nprint(acc_gbk)\n\"\"\"\napprox 79% accuracy\n\"\"\"\n\"\"\"\n## Predicting \n\"\"\"\ntest.head()\ntest.isnull().sum()\npredictions1 = gbk.predict(test)\nsample_sub['Survived']= predictions1\nsample_sub.to_csv(\"submit.csv\", index=False)\nsample_sub.head()\n\"\"\"\n### Please comment how to improve the accuracy i am new \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e64b96dadb7e00'}"}
{"id":"116144","text":"\"\"\"\n# Dask Delayed\n\nThese functions do simple operations like add two numbers together, but they sleep for a random amount of time to simulate real work.\n\"\"\"\nimport time\nimport random\nimport dask\n\n\n@dask.delayed\ndef inc(x):\n    time.sleep(random.random())\n    return x + 1\n\n@dask.delayed\ndef dec(x):\n    time.sleep(random.random())\n    return x - 1\n\ndef add(x, y):\n    time.sleep(random.random())\n    return x + y\n%%time\nx = inc(1)\ny = dec(2)\nz = add(x, y)\nz\n%%time\nz.compute()\nz.visualize()\n\"\"\"\n# Dask natively scales Python\n\nDask provides advanced parallelism for analytics, enabling performance at scale for the tools you love\n\"\"\"\nimport os\nimport time\n\n\nimport dask\nimport dask.array as da\nimport dask.dataframe as dd\nimport numpy as np\nprint(dask.__version__)\nprint(np.__version__)\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n# Reading Dask DataFrame\n\nRead CSV files into a Dask.DataFrame: This parallelizes the `pandas.read_csv()`:\n- `blocksize=25e7`: 250MB chunks\n- `dtype`: Dask don't explore all the data, sometime it mismatch the dtypes\n\"\"\"\ndtype = {\n    'fine_grained_location': 'float64', \n    'officer_id':'object', \n    'county_fips': 'float64'\n}\n\nddf = dd.read_csv(\n    \"\/kaggle\/input\/stanford-open-policing-project-texas\/TX_2010_onwards.csv\", \n#     blocksize=\"25MB\", \n    dtype=dtype, \n    low_memory=False,\n    assume_missing=True\n)\n\n# ddf = ddf.map_partitions(cudf.from_pandas)  # convert pandas partitions into cudf partitions\n\nddf\n%%time\nddf.head()\n\"\"\"\n# What is this Dask Dataframe?\nA large, virtual dataframe divided along the index into multiple Pandas dataframes:\n\"\"\"\nddf.map_partitions(len).compute()\n%%time\nddf.map_partitions(type).compute()\n\"\"\"\n# Dask DataFrame Shape\n\"\"\"\n%%time\nlen(ddf)\n%%time\nddf.shape[0].compute()\nddf_rows = ddf.shape[0].compute()\nddf_col = ddf.shape[1]\nprint(f\"Number of rows: {ddf_rows}\")\nprint(f\"Number of columns: {ddf_col}\")\n\"\"\"\n# Missing Values\n\"\"\"\n%%time\n(ddf.isna().sum().compute() \/ ddf_rows) * 100\n\"\"\"\n# Drop Columns\n\"\"\"\ncolumns = [\n    'police_department', 'driver_age_raw', 'driver_age', 'search_type_raw', \n    'search_type', 'is_arrested'\n]\nprint(f\"Number of columns before removing columns: {ddf.shape[1]}\")\n\nddf = ddf.drop(columns, axis=1)\n\nprint(f\"Number of columns After removing columns: {ddf.shape[1]}\")\n(ddf.isna().sum().compute() \/ ddf_rows) * 100\n\"\"\"\n# Drop Rows\n\"\"\"\nprint(ddf_rows)\nddf = ddf.dropna(how='any')\nprint(ddf.shape[0].compute())\n(ddf.isna().sum().compute() \/ ddf_rows) * 100\n\"\"\"\n# Drop_duplicates Rows\n\"\"\"\n# print(ddf.shape[0].compute())\n# ddf = ddf.drop_duplicates()\n# print(ddf.shape[0].compute())\n# print(ddf.shape[0].compute())\n# ddf = ddf.drop_duplicates(subset=['id'])\n# print(ddf.shape[0].compute())\nddf['id'].nunique().compute()\n\"\"\"\n# Dask DataFrame info\n\"\"\"\nnon_object_col = ddf.columns[(ddf.dtypes != object) & (ddf.dtypes != bool)].to_list()\nddf[non_object_col]\nddf.info()\n# Describe shows only numerical columns\nddf[non_object_col].describe(percentiles=[.25, .5, .75, .85, .9]).compute()\n\"\"\"\n# Analysing some columns\n\"\"\"\n# for column in ddf.columns:\n#     print(f\"{column}: Number of unique values {ddf[column].nunique().compute()}\")\n#     print(\"_______________________________________________\\n\")\nddf.columns\nddf['contraband_found'].value_counts().compute()\nddf['stop_outcome'].value_counts().compute()\nddf['driver_race'].value_counts().compute()\nddf['driver_gender'].value_counts().compute()\nddf['state'].value_counts().compute()\n# State contains only one value\nddf = ddf.drop('state', axis=1)\nddf['county_name'].value_counts().compute()\nmontgomery = ddf[ddf['county_name'].str.contains('Montgomery')]\nmontgomery_county_fips = montgomery.groupby('driver_race').driver_gender.agg(['count'])\nmontgomery.groupby('driver_race').driver_gender.count().compute()\n# montgomery_county_fips.visualize()\n# montgomery_county_fips.compute()\n\"\"\"\n# Dask Arrays\n\"\"\"\nimport numpy as np\nimport dask.array as da\na_np = np.arange(1, 50, 3)\na_np\na_da = da.arange(1, 50, 3, chunks=5)\na_da\nprint(a_da.dtype)\nprint(a_da.shape)\na_da.visualize()\n(a_da ** 2).visualize()\nprint(a_da.chunks)\nprint(a_da.chunksize)\nx = da.random.random(20, chunks=5)\nx\nresult = x.sum()\nresult\nresult.visualize()\nresult.compute()\nx = da.random.random(size=(15, 15), chunks=(10, 5))\nx\nprint(x.chunks)\nprint(x.chunksize)\nresult = (x + x.T).sum()\nresult\nresult.visualize()\nresult.compute()\nx = da.random.random(size=(20_000, 20_000), chunks=(2_000, 2_000))\nx\nresult = (x + x.T).sum()\nresult\nresult.compute()","meta":"{'source': 'AI4Code', 'id': 'd59b7cbd1e13b1'}"}
{"id":"73948","text":"# libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'figure.max_open_warning': 0})\nimport seaborn as sns\nimport sklearn.preprocessing as pre\nimport sklearn.model_selection as ms\n\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", category=DeprecationWarning)\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n### 1.1 Read data\n\"\"\"\n# read training data\ntrain=pd.read_csv('..\/input\/machine-learning-24-hrs-hackathon\/train_SJC.csv')\ntest=pd.read_csv('..\/input\/machine-learning-24-hrs-hackathon\/Test_SJC.csv')\n# display first rows (transposed)\ndf=train\ndf.head(6).T\ntrain.shape , test.shape\n# basis statistics: nominal features \ndf.describe(include=['object']).T\ndf = train\ndf=df.rename(columns={\"Unnamed: 0\":\"ClaimNumber\",\"Unnamed: 1\":\"DateTimeOfAccident\",\"Unnamed: 3\":\"Age\",\"Unnamed: 4\":\"Gender\",\"Unnamed: 5\":\"MaritalStatus\",\"Unnamed: 6\":\"DependentChildren\",\"Unnamed: 8\":\"WeeklyWages\",\"Unnamed: 9\":\"PartTimeFullTime\",\"Unnamed: 10\":\"HoursWorkedPerWeek\",\"Unnamed: 12\":\"ClaimDescription\",\"Unnamed: 13\":\"InitialIncurredCalimsCost\",\"Unnamed: 14\":'UltimateIncurredClaimCost'},inplace=False)\ndf=df.drop([0,1])\ndf.head()\ndf.info()\n\"\"\"\n### 1.2 Count and replace missing values\n\"\"\"\ndf['HoursWorkedPerWeek'].fillna(df['HoursWorkedPerWeek'].median(),inplace=True)\ndf['InitialIncurredCalimsCost'] = pd.to_numeric(df['InitialIncurredCalimsCost'],errors = 'coerce')\ndf['UltimateIncurredClaimCost'] = pd.to_numeric(df['UltimateIncurredClaimCost'],errors = 'coerce')\ndf['HoursWorkedPerWeek'] = pd.to_numeric(df['HoursWorkedPerWeek'],errors = 'coerce')\ndf['Age'] = pd.to_numeric(df['Age'],errors = 'coerce')\ndf['WeeklyWages'] = pd.to_numeric(df['WeeklyWages'],errors = 'coerce')\ndf['DaysWorkedPerWeek'] = pd.to_numeric(df['DaysWorkedPerWeek'],errors = 'coerce',downcast='integer')\ndf['DependentsOther'] = pd.to_numeric(df['DependentsOther'],errors = 'coerce',downcast='integer')\n\ndf['DependentChildren'] = pd.to_numeric(df['DependentChildren'],errors = 'coerce')\ndf.info()\n\"\"\"\n# missing value treatment\n\"\"\"\ndf['WeeklyWages'].fillna(df['WeeklyWages'].mean(),inplace=True)\ndf['MaritalStatus']=df['MaritalStatus'].fillna(\"s\")\ndf['HoursWorkedPerWeek'].fillna(df['HoursWorkedPerWeek'].median(),inplace=True)\n\"\"\"\n### 1.3 Basic feature engineering\n\"\"\"\n\n# Some date features\ndf['YearOfAccident']  = pd.DatetimeIndex(df['DateTimeOfAccident']).year\ndf['MonthOfAccident']  = pd.DatetimeIndex(df['DateTimeOfAccident']).month\ndf['DayOfAccident']  = pd.DatetimeIndex(df['DateTimeOfAccident']).day\ndf['WeekdayOfAccident']  = pd.DatetimeIndex(df['DateTimeOfAccident']).day_name()\ndf['HourOfAccident']  = pd.DatetimeIndex(df['DateTimeOfAccident']).hour\ndf['YearReported']  = pd.DatetimeIndex(df['DateReported']).year\n\n# Reporting delay in weeks \ndf['DaysReportDelay'] = pd.DatetimeIndex(df['DateReported']).date - pd.DatetimeIndex(df['DateTimeOfAccident']).date\ndf['DaysReportDelay'] = (df['DaysReportDelay']  \/ np.timedelta64(1, 'D')).astype(int)\ndf['WeeksReportDelay'] = np.floor(df['DaysReportDelay'] \/ 7.).astype(int)\ndf['WeeksReportDelay'] = np.clip(df['WeeksReportDelay'], a_max=55, a_min=None)\n\n# drop unneccessary columns\ndf.drop(['ClaimNumber','DateTimeOfAccident','DaysReportDelay','DateReported','WeekdayOfAccident'],axis=1,inplace=True)\ndf.shape\n\"\"\"\n### 1.4 Skewness and claim costs (transform, analyze)\n\"\"\"\n# Skewness of the numerical feature distributions\nprint(df.skew())\n# The log1p function applies log(1+x) to all elements of the column\ndf[\"LogUltimateIncurredClaimCost\"] = np.log1p(df[\"UltimateIncurredClaimCost\"])\ndf[\"LogInitialIncurredCalimsCost\"] = np.log1p(df[\"InitialIncurredCalimsCost\"])\n\n# plot distribution: claim costs (log)\nplt.subplots(figsize=(10, 6))\nsns.distplot(df.LogUltimateIncurredClaimCost, kde=False, label='Ultimate',bins=100)\nsns.distplot(df.LogInitialIncurredCalimsCost, kde=False, label='Initial', bins=100)\nplt.xlabel('claim costs (log)')\nplt.legend()\nplt.show()\n# search for frequent initial costs and calculate some statistics for ultimate costs (mean)\ndf['UltimateIncurredClaimCost'].groupby(df['InitialIncurredCalimsCost']).agg(['mean','median','min','count']).query('count >= 2000')\n# Average cost factor Ultimate \/ Initial\ndf.UltimateIncurredClaimCost.sum() \/ df.InitialIncurredCalimsCost.sum()\n\"\"\"\nThe average ultimate costs of frequent low initial costs (500,1000,1500,3500) are by a factor of 2 to 3 higher and thus remarkably higher than average (1.40). \n\nLet's see if there is a pattern in the scatter plot inital vs. ultimate costs:\n\"\"\"\n# Scatter plot: claim costs (log)\nplt.subplots(figsize=(10, 7))\nsns.scatterplot(data=df, x=\"LogInitialIncurredCalimsCost\",y=\"LogUltimateIncurredClaimCost\")\nplt.show()\n# Scatter plot: zoom into claim costs (log)\nplt.subplots(figsize=(10, 7))\nsns.scatterplot(data=df.query('LogInitialIncurredCalimsCost > 6 and LogInitialIncurredCalimsCost < 12 and LogUltimateIncurredClaimCost < 12'), x=\"LogInitialIncurredCalimsCost\",y=\"LogUltimateIncurredClaimCost\")\nplt.show()\n\"\"\"\n### 1.5 Visualize numerical features\n\"\"\"\n# Generate a list of numerical variables, remove claim cost variables\nnum_list = [c for c in df.columns if((df[c].dtype != np.object) and not \"Cost\" in c)] \n# plot histograms\nfor name in num_list:\n    f, ax = plt.subplots(figsize=(10, 5))\n    nbins = min(df[name].value_counts().count(),70)\n    plt.hist(data=df, x=name, bins=nbins)\n    plt.xlabel(name)\n    plt.show()\n# List of features with to many different values\nnum_list_bins =['Age','InitialIncurredCalimsCost','DaysWorkedPerWeek']\n\n# plot binned plot boxplots for 'LogUltimateIncurredClaimCost'\nfor name in num_list_bins:\n    f, ax = plt.subplots(figsize=(14, 5))\n    df['bin_'] = pd.cut(df[name], 8)\n    sns.boxplot(x='bin_', y='LogUltimateIncurredClaimCost', data=df)\n    plt.xlabel(name)\n    plt.show()\n\ndf.drop(['bin_'],axis=1,inplace=True)\n\"\"\"\n### 1.6 Correlations\n\"\"\"\n# calcuate correlation matrix\ncorrmat = df.corr()\n\n# Draw the heatmap \nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corrmat, annot=True, square=True, cmap='RdYlGn')\nplt.show()\n\"\"\"\n### 1.7 Visualize categorical features\n\"\"\"\n\"\"\"\n# gender\n\"\"\"\n# Generate a list of categorical variables and remove those with too many different values (e.g. 'ClaimDescription')\n# plot distributi\nsns.countplot(x=\"Gender\",data=df)\nplt.show()\n#  plot boxplots for 'LogUltimateIncurredClaimCost'\nsns.boxplot(x=\"Gender\", y=\"LogUltimateIncurredClaimCost\", data=df)\nplt.show()\n\"\"\"\n# partimefulltime\n\"\"\"\nsns.countplot(x=\"PartTimeFullTime\",data=df)\nplt.show()\nsns.boxplot(x=\"PartTimeFullTime\", y=\"LogUltimateIncurredClaimCost\", data=df)\nplt.show()\nle=pre.LabelEncoder()\nlist_df=['Gender','MaritalStatus','PartTimeFullTime']\nfor x in list_df:\n  df[x]=le.fit_transform(df[x].astype(str))\n\ndf.info()\n\"\"\"\n### 1.8 Very basic text processing\n\nIs there predictive power in claim descriptions? Let's get a first impression.\n\"\"\"\n# dispay claim description of a) the most severe claims ...\nvars = ['UltimateIncurredClaimCost','ClaimDescription']\ndf[vars].sort_values(by='UltimateIncurredClaimCost', ascending=False).head(8)\n# ... and b) the least severe claims\ndf[vars].sort_values(by='UltimateIncurredClaimCost', ascending=True).head(8)\n# search for some words and create new features\ntext = ['NECK','BACK','KNEE','FINGER','EYE','STRUCK','HAMMER','LADDER','STAIR','FELT','TRAUMA']\nfor name in text:\n    df['CD_' + name] = np.where( (df['ClaimDescription'].str.find(name) < 0), 0, 1)\n\n# some two or tree word features\ndf['CD_FOREIGN_BODY'] = np.where( (df['ClaimDescription'].str.find('FOREIGN BODY') < 0), 0, 1)\ndf['CD_BACK_STRAIN']  = np.where( (df['ClaimDescription'].str.find('BACK STRAIN') < 0), 0, 1)\ndf['CD_SOFT_TISSUE_'] = np.where( (df['ClaimDescription'].str.find('SOFT TISSUE INJURY') < 0), 0, 1)\ndf['CD_WORKPLACE_STRESS'] = np.where( (df['ClaimDescription'].str.find('WORKPLACE STRESS') < 0), 0, 1)\ndf['CD_LOWER_BACK_STRAIN'] = np.where( (df['ClaimDescription'].str.find('LOWER BACK STRAIN') < 0), 0, 1)\n\n# body side, lacerated\/laceration:\ndf['CD_LEFT_RIGHT'] = np.where( ((df['ClaimDescription'].str.find('LEFT') < 0) & (df['ClaimDescription'].str.find('RIGHT') < 0)), 0, 1)\ndf['CD_LACERAT_'] = np.where( (df['ClaimDescription'].str.find('LACERAT') < 0), 0, 1)\ndf['UltimateIncurredClaimCost'].groupby(df['CD_LACERAT_']).agg(['count','median','mean'])\n\"\"\"\nThe claim descriptions seem to be predictive and should be continued using modern natural language processing techniques (NLP)and PCA.\n\"\"\"\n\"\"\"\n### 1.9 Treatment of extreme outliers\n\"\"\"\n# Print the most expensive claim amounts\nvars = ['UltimateIncurredClaimCost']\nprint(df[vars].sort_values(by='UltimateIncurredClaimCost', ascending=False).head(8))\n\ndf['UltimateIncurredClaimCost'] = np.where(df['UltimateIncurredClaimCost'] > 1000000, 1000000., df['UltimateIncurredClaimCost']) * 1.000\ndf['UltimateIncurredClaimCost'].mean() \n\"\"\"\n### 1.10 Define target: UltimateIncurredClaimCost\n\"\"\"\n# To avoid confusion (e.g. log or untransformed), we give the target a new name: loss\ndf['loss'] = df[\"UltimateIncurredClaimCost\"]\n# drop unneccessary columns\ndf['UltimateIncurredClaimCost'].mean() \n\ndf.info()\nle=pre.LabelEncoder()\nlist_df=['Gender','MaritalStatus','PartTimeFullTime']\nfor x in list_df:\n  df[x]=le.fit_transform(df[x].astype(str))\ndf.info()\ndf.shape\n\"\"\"\n<a id=\"ch2\"><\/a>\n## 2.  Data preperation for modeling\n\"\"\"\n\"\"\"\n### Feature engineering test data\n\n\n\"\"\"\n# read test data\ntest=pd.read_csv('..\/input\/machine-learning-24-hrs-hackathon\/Test_SJC.csv')\nprint('Number of rows and columns:', test.shape)\ntest.head()\ntest.isnull().sum()\ntest['InitialIncurredCalimsCost'] = pd.to_numeric(test['InitialIncurredCalimsCost'],errors = 'coerce')\ntest['HoursWorkedPerWeek'] = pd.to_numeric(test['HoursWorkedPerWeek'],errors = 'coerce',downcast='integer')\ntest['WeeklyWages'] = pd.to_numeric(test['WeeklyWages'],errors = 'coerce',downcast='integer')\ntest['Age'] = pd.to_numeric(test['Age'],errors = 'coerce')\ntest['DaysWorkedPerWeek'] = pd.to_numeric(test['DaysWorkedPerWeek'],errors = 'coerce',downcast='integer')\ntest['DependentChildren'] = pd.to_numeric(test['DependentChildren'],errors = 'coerce')\ntest['DependentsOther'] = pd.to_numeric(test['DependentsOther'],errors = 'coerce',downcast='integer')\nle=pre.LabelEncoder()\nlist_df=['Gender','MaritalStatus','PartTimeFullTime']\nfor x in list_df:\n  df[x]=le.fit_transform(df[x].astype(str))\n\ntest['MaritalStatus']=test['MaritalStatus'].fillna(\"s\")\ntest.info()\nle=pre.LabelEncoder()\nlist_df=['Gender','MaritalStatus','PartTimeFullTime']\nfor x in list_df:\n  test[x]=le.fit_transform(test[x].astype(str))\n\n# Some date features\ntest['YearOfAccident']  = pd.DatetimeIndex(test['DateTimeOfAccident']).year\ntest['MonthOfAccident']  = pd.DatetimeIndex(test['DateTimeOfAccident']).month\ntest['DayOfAccident']  = pd.DatetimeIndex(test['DateTimeOfAccident']).day\ntest['WeekdayOfAccident']  = pd.DatetimeIndex(test['DateTimeOfAccident']).day_name()\ntest['HourOfAccident']  = pd.DatetimeIndex(test['DateTimeOfAccident']).hour\ntest['YearReported']  = pd.DatetimeIndex(test['DateReported']).year\n\n# Reporting delay in weeks \ntest['DaysReportDelay'] = pd.DatetimeIndex(test['DateReported']).date - pd.DatetimeIndex(test['DateTimeOfAccident']).date\ntest['DaysReportDelay'] = (test['DaysReportDelay']  \/ np.timedelta64(1, 'D')).astype(int)\ntest['WeeksReportDelay'] = np.floor(test['DaysReportDelay'] \/ 7.).astype(int)\ntest['WeeksReportDelay'] = np.clip(test['WeeksReportDelay'], a_max=55, a_min=None)\n\n# drop unneccessary columns\ntest.drop(['ClaimNumber','DateTimeOfAccident','DaysReportDelay','DateReported','WeekdayOfAccident'],axis=1,inplace=True)\ntest.shape\n# Very basis text processing: claim description features\n\n# create new features for some \"cheap\" or \"expensive\" words \nfor name in text:\n    test['CD_' + name] = np.where( (test['ClaimDescription'].str.find(name) < 0), 0, 1)\n\n# some two or tree word features\ntest['CD_FOREIGN_BODY'] = np.where( (test['ClaimDescription'].str.find('FOREIGN BODY') < 0), 0, 1)\ntest['CD_BACK_STRAIN']  = np.where( (test['ClaimDescription'].str.find('BACK STRAIN') < 0), 0, 1)\ntest['CD_SOFT_TISSUE_'] = np.where( (test['ClaimDescription'].str.find('SOFT TISSUE INJURY') < 0), 0, 1)\ntest['CD_WORKPLACE_STRESS'] = np.where( (test['ClaimDescription'].str.find('WORKPLACE STRESS') < 0), 0, 1)\ntest['CD_LOWER_BACK_STRAIN'] = np.where( (test['ClaimDescription'].str.find('LOWER BACK STRAIN') < 0), 0, 1)\n\n# body side, lacerated\/laceration:\ntest['CD_LEFT_RIGHT'] = np.where( ((test['ClaimDescription'].str.find('LEFT') < 0) & (test['ClaimDescription'].str.find('RIGHT') < 0)), 0, 1)\ntest['CD_LACERAT_'] = np.where( (test['ClaimDescription'].str.find('LACERAT') < 0), 0, 1)\ntest.info()\nle=pre.LabelEncoder()\nlist_df=['Gender','MaritalStatus','PartTimeFullTime']\nfor x in list_df:\n  test[x]=le.fit_transform(test[x].astype(str))\n\n\"\"\"\n### 2.2 One-hot-Encoding (nominal features to dummies) \n\"\"\"\n# combine, drop claim description and get dummies\ndf_all = pd.concat([df.assign(role=\"train\"), test.assign(role=\"test\")])\ndf_all.drop(['ClaimDescription'],axis=1,inplace=True)\ndf_all.drop(['UltimateIncurredClaimCost'],axis=1,inplace=True)\ndf_all.drop(['LogUltimateIncurredClaimCost'],axis=1,inplace=True)\n\ndf_all = pd.get_dummies(df_all)\n\n# seperate\ntest_dummies, df_dummies = df_all[df_all[\"role_test\"].eq(1)], df_all[df_all[\"role_train\"].eq(1)]\ndf_dummies.drop(['role_test','role_train'],axis=1,inplace=True)\ntest_dummies.drop(['role_test','role_train','loss'],axis=1,inplace=True)\ndf_dummies.shape\n\"\"\"\n### 2.3  Create modeling data sets\n\"\"\"\nseed = 1234\n\n# split data in feature matrix X and label y for training and validation\nX = df_dummies.drop(['loss'], axis=1)\ny = df_dummies['loss']\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.25, random_state=seed)\nX_test = test_dummies\nprint(X_train.shape)\nprint(X_val.shape)\nprint(y_train.shape)\nprint(y_val.shape)\npip  install xgboost\n\"\"\"\n<a id=\"ch3\"><\/a>\n## 3. Boosting Models, Validation, Scoring\n\nWe restrict ourselves here to gradient boosted regression tree models. They do not require scaling and are known to be well suited for contests with tabular data. When treating 'ClaimDescription' with NLP methods, this may change towards artificial neural networks.\n\"\"\"\n!pip install lightgbm\n!pip install catboost\n# libraries\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nfrom catboost import CatBoostRegressor\nimport time\n#import shap \n\"\"\"\n### 3.1 CatBoost (with default settings)\n\"\"\"\n# CatBoostRegressor (Default values)\ntic = time.time()\nCGB = CatBoostRegressor(logging_level='Silent')    \nCGB.fit(X_train, y_train)\nprint(\"time (sec):\" + \"%6.0f\" % (time.time() - tic))\n\n# Validation MSE\nresult = np.sqrt(mean_squared_error(y_val, CGB.predict(X_val)))\n#result = mean_squared_error(np.expm1(y_val), np.expm1(CGB.predict(X_val)))\nprint(\"MSE:\" + \"%6.2f\" % result)\n# CatBoost: Plot feature importance\n(pd.Series(CGB.feature_importances_, index=X.columns).nlargest(20).plot(kind='barh'))  \nplt.show()\n\"\"\"\n### 3.2 lightGBM: Hyperparametertuning\n\"\"\"\n# LGBMRegressor: Hyperparameter tuning with RandomizedSearchCV\ntic = time.time()\nparam_grid ={'learning_rate': [0.02,0.025], 'n_estimators': [500], 'num_leaves': [30,40,50],'feature_fraction': [0.7]} \nLGB_random_search = RandomizedSearchCV(LGBMRegressor(),param_grid, scoring='neg_mean_squared_error', cv=4,  n_iter=5, random_state=seed)\nLGB_random_search.fit(X_train,y_train)\nprint(\"Best parameters:\",LGB_random_search.best_params_)\nLGB = LGBMRegressor(**LGB_random_search.best_params_)    \nLGB.fit(X_train, y_train)\nprint(\"time (sec):\" + \"%6.0f\" % (time.time() - tic))\n\n# Validation MSE\nresult = np.sqrt(mean_squared_error(y_val, LGB.predict(X_val)))\n#result = mean_squared_error(np.expm1(y_val), np.expm1(LGB.predict(X_val)))\nprint(\"MSE:\" + \"%6.2f\" % result)\n# lightGBM: Plot feature importance\n(pd.Series(LGB.feature_importances_, index=X.columns).nlargest(20).plot(kind='barh'))  \nplt.show()\n\"\"\"\n### 3.3 XGBoost: Hyperparametertuning\n\"\"\"\n# XGBRegressor: Hyperparameter tuning with RandomizedSearchCV\ntic = time.time()\nparam_grid ={'learning_rate': [0.02,0.025], 'max_depth': [3,4,5],'n_estimators': [100],'colsample_bytree': [0.5], 'subsample': [0.4], 'tree_method': [\"hist\"] } \nXGB_random_search = RandomizedSearchCV(XGBRegressor(),param_grid, scoring='neg_mean_squared_error', cv=4,  n_iter=5, random_state=seed)\nXGB_random_search.fit(X_train,y_train)\nprint(\"Best parameters:\",XGB_random_search.best_params_)\nXGB = XGBRegressor(**XGB_random_search.best_params_)    \nXGB.fit(X_train, y_train)\nprint(\"time (sec):\" + \"%6.0f\" % (time.time() - tic))\n\n# Validation MSE\nresult = np.sqrt(mean_squared_error(y_val, XGB.predict(X_val)))\n#result = mean_squared_error(np.expm1(y_val), np.expm1(XGB.predict(X_val)))\nprint(\"RMSE:\" + \"%6.2f\" % result)\n# XGBoost: Plot feature importance\n(pd.Series(XGB.feature_importances_, index=X.columns).nlargest(20).plot(kind='barh'))  \nplt.show()\nfrom sklearn.linear_model import Ridge\nridge = Ridge()\nridge.fit(X_train,y_train)\nprint(\"Train data :\",ridge.score(X_train,y_train))\nprint(\"Test data :\",ridge.score(X_val,y_val))\npred = ridge.predict(X_val)\nprint(np.sqrt(mean_squared_error(y_val, pred)))\n\"\"\"\n### 3.5 Model blend and scoring\n\"\"\"\n# Validation MSE (Blend of LightGBM and XGBoost)\npredictions_val = 0.5*(LGB.predict(X_val)+XGB.predict(X_val))\nresult = np.sqrt(mean_squared_error(y_val, predictions_val))\nprint(\"MSE:\" + \"%6.2f\" % result)\n# Scoring: Make predictions on test data and write submission file: LGB + XGB\npredictions = XGB.predict(X_test)\ndf_test_pred = pd.DataFrame({'UltimateIncurredClaimCost':predictions})\ndf_test_pred.to_csv('submission.csv',index=False)\ndf_test_pred.head()\nsub=pd.read_csv('..\/input\/machine-learning-24-hrs-hackathon\/sample_submission.csv')\nsub['UltimateIncurredClaimCost'] = 0.5*(LGB.predict(X_test)+XGB.predict(X_test))\nsub.to_csv('submission_cgb.csv', index = False)\nsub.head(5)\nprint(np.mean(sub['UltimateIncurredClaimCost']))","meta":"{'source': 'AI4Code', 'id': '880d930e6315d8'}"}
{"id":"12845","text":"# 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\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt \n%matplotlib inline \nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\"\"\"\n# Load the data\n\"\"\"\ntrain_data = pd.read_csv('..\/input\/loan-prediction-analytics-vidhya\/train_ctrUa4K.csv')\ntest_data = pd.read_csv('..\/input\/loan-prediction-analytics-vidhya\/test_lAUu6dG.csv')\ntrain = train_data.copy()\ntest = test_data.copy()\ntrain.head()\ntest.head()\n\"\"\"\n# Missing values \n\"\"\"\ntrain.isna().sum()\ntest.isna().sum()\ntrain.info()\ntrain.drop(columns='Loan_ID',inplace =True)\ntest.drop(columns='Loan_ID',inplace =True)\n#train.drop('Loan_Status',axis=1,inplace=True)\ntrain['Credit_History']=train['Credit_History'].astype(str)\ntest['Credit_History']=test['Credit_History'].astype(str)\n\ncat_cols=[]\nnum_cols=[]\n\nfor col in train.columns:\n    if train[col].dtypes=='object':\n        cat_cols.append(col)\n        \nfor col in train.columns:\n    if train[col].dtypes!='object':\n        num_cols.append(col)\n        \nprint(cat_cols)\nprint(num_cols)\ni=1\nplt.figure(figsize=(15,20))\nfor col in cat_cols:\n    plt.subplot(4,2,i)\n    sns.countplot(train[col])\n    i=i+1\nplt.show()\ntrain['Loan_Status'].value_counts(normalize=True)\ni=1\nplt.figure(figsize=(15,20))\nfor col in num_cols:\n    plt.subplot(2,2,i)\n    sns.distplot(train[col])\n    i=i+1\n    \nplt.show()\n   \ni=1\nplt.figure(figsize=(20,18))\nfor col in num_cols:\n    plt.subplot(4,2,i)\n    sns.boxplot(train[col])\n    i=i+1\n    \nplt.show()\n   \ndef remove_outlier(col):\n    sorted(col)\n    Q1,Q3=np.percentile(col,[25,75])\n    IQR=Q3-Q1\n    lower_range= Q1-(1.5 * IQR)\n    upper_range= Q3+(1.5 * IQR)\n    return lower_range, upper_range\nlr,ur=remove_outlier(train['ApplicantIncome'])\nprint('Lower Range :',lr,'\\nUpper Range :',ur)\ntrain['ApplicantIncome']=np.where(train['ApplicantIncome']>ur,ur,train['ApplicantIncome'])\ntrain['ApplicantIncome']=np.where(train['ApplicantIncome']<lr,lr,train['ApplicantIncome'])\nlr,ur=remove_outlier(train['LoanAmount'])\nprint('Lower Range :',lr,'\\nUpper Range :',ur)\ntrain['LoanAmount']=np.where(train['LoanAmount']>ur,ur,train['LoanAmount'])\ntrain['LoanAmount']=np.where(train['LoanAmount']<lr,lr,train['LoanAmount'])\nlr,ur=remove_outlier(train['CoapplicantIncome'])\nprint('Lower Range :',lr,'\\nUpper Range :',ur)\ntrain['CoapplicantIncome']=np.where(train['CoapplicantIncome']>ur,ur,train['CoapplicantIncome'])\ntrain['CoapplicantIncome']=np.where(train['CoapplicantIncome']<lr,lr,train['CoapplicantIncome'])\nlr,ur=remove_outlier(train['Loan_Amount_Term'])\nprint('Lower Range :',lr,'\\nUpper Range :',ur)\ntrain['Loan_Amount_Term']=np.where(train['Loan_Amount_Term']>ur,ur,train['Loan_Amount_Term'])\ntrain['Loan_Amount_Term']=np.where(train['Loan_Amount_Term']<lr,lr,train['Loan_Amount_Term'])\ntrain['Married'].fillna(train['Married'].mode()[0], inplace = True)\ntest['Married'].fillna(test['Married'].mode()[0], inplace = True)\ntrain[\"Gender\"].fillna(train[\"Gender\"].mode()[0], inplace = True)\ntest[\"Gender\"].fillna(test[\"Gender\"].mode()[0], inplace = True)\ntrain['Dependents'].fillna(train['Dependents'].mode()[0], inplace = True) \ntest['Dependents'].fillna(test['Dependents'].mode()[0], inplace = True)\ntrain['Self_Employed'].fillna(train['Self_Employed'].mode()[0], inplace = True) \ntest['Self_Employed'].fillna(test['Self_Employed'].mode()[0], inplace = True)\ntrain['Credit_History'].fillna(train['Credit_History'].mode()[0], inplace = True) \ntest['Credit_History'].fillna(test['Credit_History'].mode()[0], inplace = True)\ntrain[\"LoanAmount\"].fillna(train[\"LoanAmount\"].median(), inplace = True) \ntest[\"LoanAmount\"].fillna(test[\"LoanAmount\"].median(), inplace = True)\ntrain[\"Loan_Amount_Term\"].fillna(train[\"Loan_Amount_Term\"].median(), inplace = True) \ntest[\"Loan_Amount_Term\"].fillna(test[\"Loan_Amount_Term\"].median(), inplace = True)\n# Checking for missing values after preprocessing\ntrain.isna().sum()\ntest.isna().sum()\ni=1\nplt.figure(figsize=(20,18))\nfor col in num_cols:\n    plt.subplot(4,2,i)\n    sns.boxplot(train[col])\n    i=i+1\n    \nplt.show()\n# Encoding Categorical Columns\nfrom sklearn.preprocessing import LabelEncoder\n\nle= LabelEncoder()\n\nfor col in cat_cols:\n    train[col]= le.fit_transform(train[col])\ntrain.head()\n#Scaling Numerical Columns\nfrom sklearn.preprocessing import StandardScaler\n\nss= StandardScaler()\n\ntrain[num_cols]= ss.fit_transform(train[num_cols].values)\ny= train['Loan_Status']\nX= train.drop('Loan_Status', axis=1)\nfrom sklearn.model_selection import train_test_split,GridSearchCV\nX_train, X_test, y_train,y_test= train_test_split(X,y,test_size= 0.3, stratify=y, random_state=42)\n# Building our Model\nfrom sklearn import svm\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nimport xgboost as xgb\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom sklearn.metrics import roc_auc_score,roc_curve,classification_report,confusion_matrix,plot_confusion_matrix\nvalue= [LogisticRegression(), RandomForestClassifier(), AdaBoostClassifier(), KNeighborsClassifier(), XGBClassifier(),GradientBoostingClassifier()]\n\nkey= ['LogisticRegression', 'RandomForsetClassifier', 'AdaBoostClassifier',  'KNeighborsClassifier', 'XGBClassifier','GradientBoostingClassifier']\n\nmodels= dict(zip(key,value))\naccuracy_scores=[]\nfor key,value in models.items():\n    value.fit(X_train,y_train)\n    y_pred= value.predict(X_test)\n    accuracy= accuracy_score(y_test, y_pred)\n    accuracy_scores.append(accuracy)\n    print(key)\n    print(accuracy)\ntest.head()\ntest=test.fillna(test.median())\ncat_cols1=[]\nnum_cols1=[]\n\nfor col in test.columns:\n    if test[col].dtypes=='object':\n        cat_cols1.append(col)\n        \nfor col in test.columns:\n    if test[col].dtypes!='object':\n        num_cols1.append(col)\n        \nprint(cat_cols1)\nprint(num_cols1)\nfrom sklearn.preprocessing import LabelEncoder\n\nle= LabelEncoder()\n\nfor col in cat_cols1:\n    test[col]= le.fit_transform(test[col])\nfrom sklearn.preprocessing import StandardScaler\n\nss= StandardScaler()\n\ntest[num_cols1]= ss.fit_transform(test[num_cols1].values)\ntest.head()\nfrom sklearn.linear_model import LogisticRegression\nlr=LogisticRegression()\nlr.fit(X_train, y_train)\ny_pred=lr.predict(test)\nsample_submission=pd.read_csv(r'..\/input\/loan-prediction-analytics-vidhya\/sample_submission_49d68Cx.csv')\nsample_submission['Loan_Status']=y_pred\nstatus={1: 'Y', 0: 'N'}\nsample_submission['Loan_Status']=sample_submission['Loan_Status'].map(status)\nsample_submission.head()\nsample_submission.to_csv(r'C:\\DATA file\\Hackathon data.csv')\n\"\"\"\n# #The Logistic Regression algorithm is the most accurate: approximately 84.8%\n\"\"\"\n\"\"\"\nPlease share your comment and UPVOTE ME !!!\nHAVE A NICE DAY !!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1775a15f737832'}"}
{"id":"93816","text":"\"\"\"\nHello!!\n\nHere We will perform some data mining useful for market basket analysis. The methods we will use are **Apriori** and **Association Rule Mining**. More over we are using the-bread-basket dataset provided. We will perform the data mining task in step-by-step traditional method. Let's do it.\n\n\"\"\"\n# 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\n\"\"\"\n# **Step 1 : Reading the Data**\n\nFirstly we would fetch the data from the bread basket.csv file and read it in the dataframe df using the read_csv() method.\n\n\"\"\"\n#setting up coding environment with necessary imports...\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom mlxtend.frequent_patterns import apriori, association_rules \n\n#reading the dataset in the dataframe\n\ndf = pd.read_csv('..\/input\/the-bread-basket\/bread basket.csv')\n\n#checking the top few data  \ndf.head(10)\n\"\"\"\n# **Step 2 : Understanding the Data**\n\nAs we have fetched data, now its time to understand the data.\n* We will check the data summary using **df.describe()**\n* Also we will check the datatype of each column by **df.info()**\n\"\"\"\n# getting the statistical summary of the data\ndf.describe()\n#understanding the data and its data types\ndf.info()\n\"\"\"\n# **Step 3 : Checking the Data for Missing Values**\n\nHere we are checking the data for any missing values in any columns. **missing_value_count** list shows the same. The result shows no missing values in any columns.\n\n\"\"\"\n#get no. of missing data points per column if any\n\nmissing_values_count = df.isnull().sum()\n\n#checking the missing values in all columns if any\nmissing_values_count[0:4]\ndf.groupby(['Transaction'])\ndf\n#df.head()\n\"\"\"\n# **Step 4 : Cleaning the Data**\n\nNow cleaning the data in columns. First we check the distinct items and cleaning any preceding and trailing whitespaces if any.\n\"\"\"\ndf.Item.unique()\n#removing trailing and preceding whitespaces in item column   \ndf['Item']=df['Item'].str.strip()\n\"\"\"\n# **Step 4 : Data Selection & Transformation**\n\nAfter cleaning the data, we will perform the data selection. Here we will prepare the data as per the need of Frequent Itemset and Association mining process.\n\nHere data is firstly grouped by transaction to collect various item occurances in each transaction.\n\nAfter that we are creating a pivot table with transaction as index and items as columns to map the items with transcations. During this we are placing 0 for items which are not in perticular transcation.\n\"\"\"\ngrouped_df = df.groupby(['Transaction','Item'])['Item'].count().reset_index(name='Count')\n\nbasket_df = grouped_df.pivot_table(index='Transaction', columns='Item', values='Count', aggfunc='sum').fillna(0)\n\"\"\"\nAs some items may have more than one occurances in a transaction, we are transforming data by applying the hot encoding. After applying this data will be suitable for concerned libraries\n\"\"\"\n# Defining the hot encoding function to make the data suitable for the concerned libraries \ndef hot_encode(x): \n    if(x<= 0): \n        return 0\n    if(x>= 1): \n        return 1\n# Encoding the datasets \nbasket_encoded = basket_df.applymap(hot_encode) \nbasket_df = basket_encoded \n\nbasket_df\n\"\"\"\nIn above table, each column is a unique item. If item present in transaction then value 1 is shown else 0. This transformed data is now useful to apply mining.\n\"\"\"\n\"\"\"\n# **Step 5 : Data Mining**\n\nHere we are performing data mining by applying the apriori and association_rules algorithm imported from **mlxtend.frequent_patterns** library. \n\n> We have set some parameters of the algorithm as follows\n\nFor Apriori : **Min support = 0.01**\n\nFor Association Rules : **Min. confidence = 0.25**\n\n\n\"\"\"\n# Building the model with min support = 0.01 (1%)\nfrq_items = apriori(basket_df, min_support = 0.01, use_colnames = True)\nfrq_items\n\"\"\"\nAbove results shows the frequent Itemsets fulfilling necessary conditions of mining algorithm.\nNow the block below shows the Association Rule Mining with necessary parameters set in the model. Output is collected in the variable *rules*\n\"\"\"\n# Collecting the inferred rules in a dataframe \nrules = association_rules(frq_items, metric =\"confidence\", min_threshold = 0.25) \nrules = rules.sort_values(['confidence', 'lift'], ascending =[False, False]) \nrules.reset_index()\n\"\"\"\n# **Step 6 : Model Evaluation Plots**\n\nAs we have performed Association Rule Mining for Bread Basket Analysis, we would like to check the relations between various algorithm parameters. Following are the plots showing the same.\n\"\"\"\n# SUPPORT Vs CONFIDENCE\n\nplt.scatter(rules['support'], rules['confidence'], alpha=0.5)\nplt.xlabel('support')\nplt.ylabel('confidence')\nplt.title('Support vs Confidence')\nplt.show()\n# SUPPORT Vs LIFT\n\n\nplt.scatter(rules['support'], rules['lift'], alpha=0.5)\nplt.xlabel('support')\nplt.ylabel('lift')\nplt.title('Support vs Lift')\nplt.show()\n# LIFT Vs CONFIDENCE\n\n\nfit = np.polyfit(rules['lift'], rules['confidence'], 1)\nfit_fn = np.poly1d(fit)\nplt.plot(rules['lift'], rules['confidence'], 'yo', rules['lift'], \n fit_fn(rules['lift']))\n\"\"\"\nSo, Here this conclude the apriori and association rule mining task. To explore more you can try with various values of algorithm parameters and check the difference in the results.\n\nShare your valuable feedbacks.\n\nThanks in advance.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ac3215b53eb182'}"}
{"id":"16289","text":"\"\"\"\n<img src=\"https:\/\/i.imgur.com\/fOeJmu3.jpg\" width=\"600px\">\n\"\"\"\n\"\"\"\n# Introduction\n\nHello everyone! In this project, I will try to finetune roBERTa base to predict the sentiment of a tweet. Capturing sentiment in language is important in these times where decisions and reactions are created and updated in seconds. Building machine learning models to understand the sentiment behind a tweet can help drive decisions by many parties and leverage the large amount of information on Twitter. \n\nI will use **PyTorch XLA** (PyTorch for TPUs) and **huggingface transformers** for this project.\n\"\"\"\n\"\"\"\n## Set up PyTorch-XLA\n\n* These few lines of code sets up PyTorch XLA for us.\n* We need PyTorch XLA to help us train PyTorch models on TPU.\n\"\"\"\n!curl https:\/\/raw.githubusercontent.com\/pytorch\/xla\/master\/contrib\/scripts\/env-setup.py -o pytorch-xla-env-setup.py\n!python pytorch-xla-env-setup.py --version nightly --apt-packages libomp5 libopenblas-dev\n!export XLA_USE_BF16=1\n\"\"\"\n## Install and import libraries\n\n* We will import several different packages and libraries required for different parts of the project. For example, we import <code>numpy<\/code> and <code>pandas<\/code> for data manipulation, <code>torch<\/code> and <code>torch_xla<\/code> for modeling, and <code>plotly<\/code> for visualization.\n\"\"\"\n!pip install -q colored\n!pip install -q transformers\nimport os\nimport gc\nimport re\n\nimport time\nimport colored\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom colored import fg, bg, attr\n\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\n\nfrom torch.multiprocessing import Pipe, Process\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom tqdm.notebook import tqdm\nfrom sklearn.utils import shuffle\nfrom transformers import RobertaModel, RobertaTokenizer\n\nimport torch_xla.core.xla_model as xm\nimport torch_xla.distributed.parallel_loader as pl\nimport torch_xla.distributed.xla_multiprocessing as xmp\n\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.sequence import pad_sequences as pad\n\"\"\"\n## Define hyperparameters and load data\n\n* Here, we define the required hyperparameters such as the training batch size, learning rate, train\/val split, etc.\n* We also load the training and tessting data required for the project using the read_csv function (from <code>pandas<\/code>)\n\"\"\"\nEPOCHS = 20\nSPLIT = 0.8\nMAXLEN = 48\nDROP_RATE = 0.3\nnp.random.seed(42)\n\nOUTPUT_UNITS = 3\nBATCH_SIZE = 384\nLR = (4e-5, 1e-2)\nROBERTA_UNITS = 768\nVAL_BATCH_SIZE = 384\nMODEL_SAVE_PATH = 'sentiment_model.pt'\ntest_df = pd.read_csv('..\/input\/tweet-sentiment-extraction\/test.csv')\ntrain_df = pd.read_csv('..\/input\/tweet-sentiment-extraction\/train.csv')\ntest_df.head()\ntrain_df.head()\n\"\"\"\n## Define PyTorch Dataset\n\n* Now we define a PyTorch Dataset which will help us feed data to the roBERTa model for training and inference.\n* We remove leading and trailing whitespaces using .strip(), tokenize the values using huggingface, and pad the tokens using keras.\n\"\"\"\nclass TweetDataset(Dataset):\n    def __init__(self, data, tokenizer):\n        self.data = data\n        self.text = data.text\n        self.tokenizer = tokenizer\n        self.sentiment = data.sentiment\n        self.sentiment_dict = {\"positive\": 0, \"neutral\": 1, \"negative\": 2}\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, i):\n        start, finish = 0, 2\n        pg, tg = 'post', 'post'\n        tweet = str(self.text[i]).strip()\n        tweet_ids = self.tokenizer.encode(tweet)\n\n        attention_mask_idx = len(tweet_ids) - 1\n        if start not in tweet_ids: tweet_ids = start + tweet_ids\n        tweet_ids = pad([tweet_ids], maxlen=MAXLEN, value=1, padding=pg, truncating=tg)\n\n        attention_mask = np.zeros(MAXLEN)\n        attention_mask[1:attention_mask_idx] = 1\n        attention_mask = attention_mask.reshape((1, -1))\n        if finish not in tweet_ids: tweet_ids[-1], attention_mask[-1] = finish, start\n            \n        sentiment = [self.sentiment_dict[self.sentiment[i]]]\n        sentiment = torch.FloatTensor(to_categorical(sentiment, num_classes=3))\n        return sentiment, torch.LongTensor(tweet_ids), torch.LongTensor(attention_mask)\n\"\"\"\n## Define roBERTa-base model\n\n* Now, we get to the interesting part: modeling! roBERTa base is a pretrained language model by Facebook AI.\n* We will use roBERTa with pretrained weights and add a (Dropout + Dense) head to to use it as a text classifier.\n\"\"\"\nclass Roberta(nn.Module):\n    def __init__(self):\n        super(Roberta, self).__init__()\n        self.softmax = nn.Softmax(dim=1)\n        self.drop = nn.Dropout(DROP_RATE)\n        self.roberta = RobertaModel.from_pretrained(model)\n        self.dense = nn.Linear(ROBERTA_UNITS, OUTPUT_UNITS)\n        \n    def forward(self, inp, att):\n        inp = inp.view(-1, MAXLEN)\n        _, self.feat = self.roberta(inp, att)\n        return self.softmax(self.dense(self.drop(self.feat)))\n\"\"\"\n## Define tokenizer\n\n* Here we simply define the RobertaTokenizer from huggingface which we use to generate tokens from words.\n\"\"\"\nmodel = 'roberta-base'\ntokenizer = RobertaTokenizer.from_pretrained(model)\n\"\"\"\n## Define cross entropy and accuracy\n\n* Here we implement categorical cross entropy and accuracy functions in PyTorch.\n* CEL is the loss function which is commonly used in classification tasks and helps us finetune roBERTa's weights.\n\"\"\"\ndef cel(inp, target):\n    _, labels = target.max(dim=1)\n    return nn.CrossEntropyLoss()(inp, labels)*len(inp)\n\ndef accuracy(inp, target):\n    inp_ind = inp.max(axis=1).indices\n    target_ind = target.max(axis=1).indices\n    return (inp_ind == target_ind).float().sum(axis=0)\n\"\"\"\n## Train model on all 8 TPU cores\n\n* Now, we will train the roBERTa base model to classify tweet sentiments.\n* We define a simple training loop in PyTorch to train the model and validate it after each epoch.\n* We parallelize the training on all 8 TPU cores using <code>xmp.spawn<\/code> from PyTorch XLA (distributes training).\n* We aslo use <code>DistributedSampler<\/code> and <code>ParallelLoader<\/code> to parallelize data sampling and model training.\n\"\"\"\nm = Roberta(); print(m)\ndel m; gc.collect()\ndef print_metric(data, batch, epoch, start, end, metric, typ):\n    t = typ, metric, \"%s\", data, \"%s\"\n    if typ == \"Train\": pre = \"BATCH %s\" + str(batch-1) + \"%s  \"\n    if typ == \"Val\": pre = \"\\nEPOCH %s\" + str(epoch+1) + \"%s  \"\n    time = np.round(end - start, 1); time = \"Time: %s{}%s s\".format(time)\n    fonts = [(fg(211), attr('reset')), (fg(212), attr('reset')), (fg(213), attr('reset'))]\n    xm.master_print(pre % fonts[0] + \"{} {}: {}{}{}\".format(*t) % fonts[1] + \"  \" + time % fonts[2])\nglobal val_losses; global train_losses\nglobal val_accuracies; global train_accuracies\n\ndef train_fn(train_df):\n    train_df = shuffle(train_df)\n    train_df = train_df.reset_index(drop=True)\n\n    split = np.int32(SPLIT*len(train_df))\n    val_df, train_df = train_df[split:], train_df[:split]\n\n    val_df = val_df.reset_index(drop=True)\n    val_dataset = TweetDataset(val_df, tokenizer)\n    val_sampler = DistributedSampler(val_dataset, num_replicas=8,\n                                     rank=xm.get_ordinal(), shuffle=True)\n    \n    val_loader = DataLoader(val_dataset, batch_size=VAL_BATCH_SIZE,\n                            sampler=val_sampler, num_workers=0, drop_last=True)\n\n    train_df = train_df.reset_index(drop=True)\n    train_dataset = TweetDataset(train_df, tokenizer)\n    train_sampler = DistributedSampler(train_dataset, num_replicas=8,\n                                       rank=xm.get_ordinal(), shuffle=True)\n\n    train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE,\n                              sampler=train_sampler, num_workers=0, drop_last=True)\n\n    device = xm.xla_device()\n    network = Roberta().to(device)\n    optimizer = Adam([{'params': network.dense.parameters(), 'lr': LR[1]},\n                      {'params': network.roberta.parameters(), 'lr': LR[0]}])\n\n    val_losses, val_accuracies = [], []\n    train_losses, train_accuracies = [], []\n    \n    start = time.time()\n    xm.master_print(\"STARTING TRAINING ...\\n\")\n\n    for epoch in range(EPOCHS):\n\n        batch = 1\n        network.train()\n        fonts = (fg(48), attr('reset'))\n        xm.master_print((\"EPOCH %s\" + str(epoch+1) + \"%s\") % fonts)\n\n        val_parallel = pl.ParallelLoader(val_loader, [device]).per_device_loader(device)\n        train_parallel = pl.ParallelLoader(train_loader, [device]).per_device_loader(device)\n        \n        for train_batch in train_parallel:\n            train_targ, train_in, train_att = train_batch\n            \n            network = network.to(device)\n            train_in = train_in.to(device)\n            train_att = train_att.to(device)\n            train_targ = train_targ.to(device)\n\n            train_preds = network.forward(train_in, train_att)\n            train_loss = cel(train_preds, train_targ.squeeze(dim=1))\/len(train_in)\n            train_accuracy = accuracy(train_preds, train_targ.squeeze(dim=1))\/len(train_in)\n\n            optimizer.zero_grad()\n            train_loss.backward()\n            xm.optimizer_step(optimizer)\n            \n            end = time.time()\n            batch = batch + 1\n            acc = np.round(train_accuracy.item(), 3)\n            print_metric(acc, batch, None, start, end, metric=\"acc\", typ=\"Train\")\n\n        val_loss, val_accuracy, val_points = 0, 0, 0\n\n        network.eval()\n        with torch.no_grad():\n            for val_batch in val_parallel:\n                targ, val_in, val_att = val_batch\n\n                targ = targ.to(device)\n                val_in = val_in.to(device)\n                val_att = val_att.to(device)\n                network = network.to(device)\n            \n                val_points += len(targ)\n                pred = network.forward(val_in, val_att)\n                val_loss += cel(pred, targ.squeeze(dim=1)).item()\n                val_accuracy += accuracy(pred, targ.squeeze(dim=1)).item()\n        \n        end = time.time()\n        val_loss \/= val_points\n        val_accuracy \/= val_points\n        acc = xm.mesh_reduce('acc', val_accuracy, lambda x: sum(x)\/len(x))\n        print_metric(np.round(acc, 3), None, epoch, start, end, metric=\"acc\", typ=\"Val\")\n    \n        xm.master_print(\"\")\n        val_losses.append(val_loss); train_losses.append(train_loss.item())\n        val_accuracies.append(val_accuracy); train_accuracies.append(train_accuracy.item())\n\n    xm.master_print(\"ENDING TRAINING ...\")\n    xm.save(network.state_dict(), MODEL_SAVE_PATH); del network; gc.collect()\n\n    metric_names = ['val_loss_', 'train_loss_', 'val_acc_', 'train_acc_']\n    metric_lists = [val_losses, train_losses, val_accuracies, train_accuracies]\n    \n    for i, metric_list in enumerate(metric_lists):\n        for j, metric_value in enumerate(metric_list):\n            torch.save(metric_value, metric_names[i] + str(j) + '.pt')\nFLAGS = {}\ndef _mp_fn(rank, flags): train_fn(train_df)\nxmp.spawn(_mp_fn, args=(FLAGS,), nprocs=8, start_method='fork')\n\"\"\"\n## Visualize loss and accuracy over time\n\n* We now visualize how the loss and accuracy of the model change over time.\n* We can see that the model eventually converges to around 80% accuracy towards the end.\n\"\"\"\nval_losses = [torch.load('val_loss_{}.pt'.format(i)) for i in range(EPOCHS)]\ntrain_losses = [torch.load('train_loss_{}.pt'.format(i)) for i in range(EPOCHS)]\nval_accuracies = [torch.load('val_acc_{}.pt'.format(i)) for i in range(EPOCHS)]\ntrain_accuracies = [torch.load('train_acc_{}.pt'.format(i)) for i in range(EPOCHS)]\nfig = go.Figure()\n\nfig.add_trace(go.Scatter(x=np.arange(1, len(val_losses)+1),\n                         y=val_losses, mode=\"lines+markers\", name=\"val\",\n                         marker=dict(color=\"hotpink\", line=dict(width=.5,\n                                                                color='rgb(0, 0, 0)'))))\n\nfig.add_trace(go.Scatter(x=np.arange(1, len(train_losses)+1),\n                         y=train_losses, mode=\"lines+markers\", name=\"train\",\n                         marker=dict(color=\"mediumorchid\", line=dict(width=.5,\n                                                                     color='rgb(0, 0, 0)'))))\n\nfig.update_layout(xaxis_title=\"Epochs\", yaxis_title=\"Cross Entropy\",\n                  title_text=\"Cross Entropy vs. Epochs\", template=\"plotly_white\", paper_bgcolor=\"#f0f0f0\")\n\nfig.show()\nfig = go.Figure()\n\nfig.add_trace(go.Scatter(x=np.arange(1, len(val_accuracies)+1),\n                         y=val_accuracies, mode=\"lines+markers\", name=\"val\",\n                         marker=dict(color=\"hotpink\", line=dict(width=.5,\n                                                                color='rgb(0, 0, 0)'))))\n\nfig.add_trace(go.Scatter(x=np.arange(1, len(train_accuracies)+1),\n                         y=train_accuracies, mode=\"lines+markers\", name=\"train\",\n                         marker=dict(color=\"mediumorchid\", line=dict(width=.5,\n                                                                     color='rgb(0, 0, 0)'))))\n\nfig.update_layout(xaxis_title=\"Epochs\", yaxis_title=\"Accuracy\",\n                  title_text=\"Accuracy vs. Epochs\", template=\"plotly_white\", paper_bgcolor=\"#f0f0f0\")\n\nfig.show()\n\"\"\"\n## Load model\n\n* We now load the model to evaluate its performance.\n\"\"\"\nnetwork = Roberta()\nnetwork.load_state_dict(torch.load('sentiment_model.pt'))\n\"\"\"\n## Sample sentiment prediction\n\n* We will now see how the model performs on sample comments.\n* It appears to classify sentiment pretty accurately in these simple examples.\n\"\"\"\ndevice = xm.xla_device()\nnetwork = network.to(device)\n\ndef predict_sentiment(tweet):\n    pg, tg = 'post', 'post'\n    tweet_ids = tokenizer.encode(tweet.strip())\n    sent = {0: 'positive', 1: 'neutral', 2: 'negative'}\n\n    att_mask_idx = len(tweet_ids) - 1\n    if 0 not in tweet_ids: tweet_ids = 0 + tweet_ids\n    tweet_ids = pad([tweet_ids], maxlen=MAXLEN, value=1, padding=pg, truncating=tg)\n\n    att_mask = np.zeros(MAXLEN)\n    att_mask[1:att_mask_idx] = 1\n    att_mask = att_mask.reshape((1, -1))\n    if 2 not in tweet_ids: tweet_ids[-1], att_mask[-1] = 2, 0\n    tweet_ids, att_mask = torch.LongTensor(tweet_ids), torch.LongTensor(att_mask)\n    return sent[np.argmax(network.forward(tweet_ids.to(device), att_mask.to(device)).detach().cpu().numpy())]\npredict_sentiment(\"It does not look good now ...\")\npredict_sentiment(\"I want to know more about your product.\")\npredict_sentiment(\"I have done something good today and so should you :D\")","meta":"{'source': 'AI4Code', 'id': '1db03f2b4c1f9b'}"}
{"id":"60487","text":"\"\"\"\n**By using the output of this notebook, you are accepting the [competition rules](https:\/\/www.kaggle.com\/c\/vinbigdata-chest-xray-abnormalities-detection\/rules).**\n\n\n**This is originally from https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-png-256x256 by @xhlulu, I just modified a bit to save metadata for test images**\n\n## References\n\n- Monochrome fix and scaling: https:\/\/www.kaggle.com\/raddar\/convert-dicom-to-np-array-the-correct-way\n- Resizing and saving image: https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-image\n\"\"\"\nimport os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    # Original from: https:\/\/www.kaggle.com\/raddar\/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data \/ np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data\ndef resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    \n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        im = im.resize((size, size), resample)\n    \n    return im\nimage_id = []\ndim0 = []\ndim1 = []\n\n#for split in ['train', 'test']:\nfor split in ['test']:\n    load_dir = f'..\/input\/vinbigdata-chest-xray-abnormalities-detection\/{split}\/'\n    save_dir = f'\/kaggle\/tmp\/{split}\/'\n\n    os.makedirs(save_dir, exist_ok=True)\n\n    for file in tqdm(os.listdir(load_dir)):\n        # set keep_ratio=True to have original aspect ratio\n        xray = read_xray(load_dir + file)\n        #im = resize(xray, size=256)  \n        #im.save(save_dir + file.replace('dicom', 'png'))\n        \n        image_id.append(file.replace('.dicom', ''))\n        dim0.append(xray.shape[0])\n        dim1.append(xray.shape[1])\nfile_list = os.listdir(load_dir)\nfrom joblib import Parallel, delayed\n\ndef load_meta(load_dir: str, file: str):\n    xray = read_xray(load_dir + file, False, False)\n    image_id = file.replace('.dicom', '')\n    height, width = xray.shape[:2]\n    return image_id, height, width\n\nprint(f\"total {len(file_list)}\")\nn_jobs = 16\nresults = Parallel(n_jobs, verbose=1)(\n    delayed(load_meta)(load_dir, filename) for filename in file_list)\ntest_meta = pd.DataFrame(results, columns=[\"image_id\", \"dim0\", \"dim1\"])\ntest_meta.to_csv(\"test_meta.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '6f780da5889ddd'}"}
{"id":"8820","text":"# Importing Data \n# Visualization and comments\n# Feature Engineering -- Encoding catorigical column ,genrating new features and Feature Selection \n# Modelling\n# Ensambling \n\n!pip install autoviz\n\nimport pandas as pd \nimport numpy as np \n\n## for Plottng and Visualization\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport pandas_profiling\nfrom autoviz.AutoViz_Class import AutoViz_Class\nimport graphviz  # to visualse the decesion tree\nfrom yellowbrick.contrib.classifier import DecisionViz\nfrom mlxtend.plotting import plot_decision_regions\n\n## To apply NN\nfrom keras import  models\nfrom keras.layers import Dense\n\n# For encoding  categorical data\nimport category_encoders as ce\n\n\n## scikit Library for models and Feature Engineering\nfrom sklearn.model_selection import train_test_split\n# models\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import tree\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn import preprocessing\nfrom  sklearn.preprocessing import StandardScaler \nfrom sklearn.feature_selection import SelectFromModel\n\n\n\ndata=pd.read_csv('..\/input\/titanic\/train.csv')\ntest_data=pd.read_csv('..\/input\/titanic\/test.csv')\nX_train, X_valid, y_train, y_valid = train_test_split( data.drop(columns=\"Survived\"), data.Survived, test_size=0.1, random_state=42)\nprint(\"This is how our data looks like\")\nX_train.head()\n# SibSp is the number of Siblings\/Spouses on board\n# Parch is the number of parents\/children on board\n# Pclass is the 1=1st , 2nd=2 and 3rd=3\n\"\"\"\n# Data Visualization\n\"\"\"\nreport = pandas_profiling.ProfileReport(X_train)\ndisplay(report)\n# More Visualization \nAV = AutoViz_Class()\n \n# Let's now visualize the plots generated by AutoViz.\nreport_2 = AV.AutoViz('..\/input\/titanic\/train.csv')\n\"\"\"\n### Some Commets after exploring our data :\n\n\n##### Caterogrocal Columns: Embarked, Capin, Sex, Name and Ticket\n##### Ticket coloumn  has a high cardinality but not all distinct so there are more than one person with the same ticket and they may have any kind of a relationship helped in their survival..let's see\n##### Fare column has a wide range from 0 to 512 with high variance \n##### From the corrolation Matrix , there is a negative corrolation between class and survival \n##### We can make a use of the capin col as I noticed for example that passnegers of  class 3 were in F,G and E capins\n##### There is a strong corrolation between Class and Fare which makes sense\n##### There are aloooot of missing values from age col but we can infer it from the title in the name col \n##### There are also many missing values in Fare col , we can fill it using the negative relationhip between Fare and Class \n##### 68% of survivors were females despite that 64% of passengers were males\n\n\n\n\"\"\"\n\"\"\"\n# Feature Engineering\n##### I. Encoding Categorical Columns \n\"\"\"\n# encode sex column into 0 for female and 1 for male \nsex_enc=preprocessing.LabelEncoder()\nX_train[\"Sex_enc\"]=sex_enc.fit_transform(X_train[\"Sex\"])\nX_valid[\"Sex_enc\"]= sex_enc.transform(X_valid[\"Sex\"])\ntest_data[\"Sex_enc\"]=sex_enc.transform(test_data[\"Sex\"])\n\n\n#to avoid the model of creating a bais, standard scale Fare cus it has large scale \nFare_std_scaler=StandardScaler()\nX_train[\"std_Fare\"]=Fare_std_scaler.fit_transform(np.array(X_train.Fare).reshape(-1,1))\nX_valid[\"std_Fare\"]=Fare_std_scaler.transform(np.array(X_valid.Fare).reshape(-1,1))\ntest_data[\"std_Fare\"]=Fare_std_scaler.transform(np.array(test_data.Fare).reshape(-1,1))\n\n# Generate a family col and we will see if it is uselful\nX_train[\"Family\"]=X_train[\"SibSp\"]+X_train[\"Parch\"]\nX_valid[\"Family\"]=X_valid[\"SibSp\"]+X_valid[\"Parch\"]\ntest_data[\"Family\"]=test_data[\"SibSp\"]+test_data[\"Parch\"]\n\n## encode_Family\nFamily_enc_tar=ce.TargetEncoder(X_train[\"Embarked\"])\nX_train[\"Family_enc_tar\"]=Family_enc_tar.fit_transform(X_train[\"Family\"],y_train)\nX_valid[\"Family_enc_tar\"]= Family_enc_tar.transform(X_valid[\"Family\"])\ntest_data[\"Family_enc_tar\"]=Family_enc_tar.transform(test_data[\"Family\"])\n\n# encode the ticket using targetencoding to see if the holders of the same ticket number have any relationship helped them to survive together\n\nTicket_enc =ce.TargetEncoder(X_train[\"Ticket\"])\nX_train[\"Ticket_enc\"]=Ticket_enc.fit_transform(X_train[\"Ticket\"],y_train)\nX_valid[\"Ticket_enc\"]=Ticket_enc.transform(X_valid[\"Ticket\"])\ntest_data[\"Ticket_enc\"]=Ticket_enc.transform(test_data[\"Ticket\"])\n\n# fill nan values with the most major category('S') then Encode Embarked col\nX_train[\"Embarked\"].fillna(value='S',inplace=True)\nEmbar_enc=preprocessing.LabelEncoder()\nX_train[\"Embarked_enc\"]=Embar_enc.fit_transform(X_train[\"Embarked\"])\nX_valid[\"Embarked_enc\"]= Embar_enc.transform(X_valid[\"Embarked\"])\ntest_data[\"Embarked_enc\"]=Embar_enc.transform(test_data[\"Embarked\"])\n\n# try to encode Embarked col with Target encoder to see directly if there is a relationship btween where you embarkd and your survival \nEmbar_enc_tar=ce.TargetEncoder(X_train[\"Embarked\"])\nX_train[\"Embarked_enc_tar\"]=Embar_enc_tar.fit_transform(X_train[\"Embarked\"],y_train)\nX_valid[\"Embarked_enc_tar\"]= Embar_enc_tar.transform(X_valid[\"Embarked\"])\ntest_data[\"Embarked_enc_tar\"]=Embar_enc_tar.transform(test_data[\"Embarked\"])\n\n# Extract Capin Letter and fill nan values based on class \n#X_train[\"Cabin_letter\"]=X_train[\"Cabin\"].str.extract(pat = '([A-Z])')\n#print (X_train.groupby(\"Cabin_letter\").Pclass.describe() )\n\n# Create new title column to help us infer age and standardze the values\nX_train[\"Title\"]=X_train[\"Name\"].str.split(',',expand=True)[1].str.split('.',expand=True)[0]\nX_valid[\"Title\"]=X_valid[\"Name\"].str.split(',',expand=True)[1].str.split('.',expand=True)[0]\ntest_data[\"Title\"]=test_data[\"Name\"].str.split(',',expand=True)[1].str.split('.',expand=True)[0]\n\n## Target encode the title column\nTitle_enc_tar=ce.TargetEncoder(X_train[\"Title\"])\nX_train[\"Title_enc_tar\"]=Title_enc_tar.fit_transform(X_train[\"Title\"],y_train)\nX_valid[\"Title_enc_tar\"]= Title_enc_tar.transform(X_valid[\"Title\"])\ntest_data[\"Title_enc_tar\"]=Title_enc_tar.transform(test_data[\"Title\"])\n\n\n## fill Nan values of Age\navg_age_per_title=X_train.groupby(\"Title\").Age.mean()\nintermediate_df_train=X_train[X_train.Age.isnull()]\nintermediate_df_train.Age=avg_age_per_title[intermediate_df_train.Title].values.astype(int)\nX_train.Age.fillna(intermediate_df_train.Age,inplace=True)\n\nintermediate_df_valid=X_valid[X_valid.Age.isnull()]\nintermediate_df_valid.Age=avg_age_per_title[intermediate_df_valid.Title].values.astype(int)\nX_valid.Age.fillna(intermediate_df_valid.Age,inplace=True)\n\nintermediate_df_test=test_data[test_data.Age.isnull()]\nintermediate_df_test.Age=avg_age_per_title[intermediate_df_test.Title].values.astype(int)\ntest_data.Age.fillna(intermediate_df_test.Age,inplace=True)\n\n\n\nAge_std_scaler=StandardScaler()\nX_train[\"std_Age\"]=Age_std_scaler.fit_transform(np.array(X_train.Age).reshape(-1,1))\nX_valid[\"std_Age\"]=Age_std_scaler.transform(np.array(X_valid.Age).reshape(-1,1))\ntest_data[\"std_Age\"]=Age_std_scaler.transform(np.array(test_data.Age).reshape(-1,1))\n\n\n## deopping unneeded cols.\nX_train1=X_train.drop(columns=['Name','Cabin','Ticket','Sex','Age','Ticket','Fare','Embarked','Title','Family'])\nX_valid1=X_valid.drop(columns=['Name','Cabin','Ticket','Sex','Age','Ticket','Fare','Embarked','Title','Family'])\ntest_data1=test_data.drop(columns=['Name','Cabin','Ticket','Sex','Age','Ticket','Fare','Embarked','Title','Family'])\n\"\"\"\n##### II.Feature Selection  using L1 penality \n\"\"\"\nlog_reg = LogisticRegression(penalty='l1',solver='liblinear',C=0.05).fit(X_train1, y_train)\nselector = SelectFromModel(log_reg, prefit=True)\nX_new = selector.transform(X_train1)\nX_train_selected_features=pd.DataFrame(selector.inverse_transform(X_new),columns=X_train1.columns)\nX_valid_selected_features=X_valid1.copy()\ntest_data_selected_features=test_data1.copy()\nfor i in X_train_selected_features.columns:\n    if X_train_selected_features[i].mean()==0:\n        X_train_selected_features.drop(columns=i,inplace=True)\n        X_valid_selected_features.drop(columns=i,inplace=True)\n        test_data_selected_features.drop(columns=i,inplace=True)\n        \n        \nprint(\"So here is the set of the selected Features ..... \\n \\n\",X_train_selected_features.columns)\n\"\"\"\n## Learning our models\n##### First, I will start learning using one  or two features just to have get some insight\n\"\"\"\n# helping Function\ndef to_np_arr(arr):\n    return np.array(arr).reshape(-1,1)\n\n\n\nmodel_gender=tree.DecisionTreeClassifier(max_depth=5)\nmodel_gender.fit(to_np_arr(X_train_selected_features.Sex_enc),to_np_arr(y_train))\nmodel_gender_score= model_gender.score(to_np_arr(X_train_selected_features.Sex_enc),to_np_arr(y_train))\nvalid_gender=model_gender.score(to_np_arr(X_valid_selected_features.Sex_enc),to_np_arr(y_valid))\n\nmodel_age=tree.DecisionTreeClassifier(max_depth=5)\nmodel_age.fit(to_np_arr(X_train_selected_features.std_Age),to_np_arr(y_train))\n#tree.plot_tree(model_gender)\nmodel_age_score= model_gender.score(to_np_arr(X_train_selected_features.std_Age),to_np_arr(y_train))\nvalid_age=model_gender.score(to_np_arr(X_valid_selected_features.std_Age),to_np_arr(y_valid))\n\n\nmodel_class=tree.DecisionTreeClassifier(max_depth=5)\nmodel_class.fit(to_np_arr(X_train_selected_features.Pclass),to_np_arr(y_train))\nmodel_class_score= model_class.score(to_np_arr(X_train_selected_features.Pclass),to_np_arr(y_train))\nvalid_class=model_gender.score(to_np_arr(X_valid_selected_features.Pclass),to_np_arr(y_valid))\n\nprint(\"Training Accurcy for gender only model is \\n \\n Training Acc:\",model_gender_score,\"\\n Valid Acc:\",valid_class,\" \\n \\n Training Acc for Age only model is \\n\",\"\\n Training Acc\",model_age_score,\"\\n Valid Acc:\",valid_age,\" \\n \\nTraining Acc for PClass only model is \\n \",\"\\n Training Acc\",model_class_score,\"\\n valid acc :\",valid_class)\n\"\"\"\n##### Looks like as we predicted Passeneger Gender has a lot to do with their Survival!  \n###### Lets see that more \n\"\"\"\nfn=['Sex_enc']  \ncn=['NOT_Survived',\"Survived\"]  #sorted ascending numerically so notsurvived=0 first \nfig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (2,2), dpi=300)\ntree.plot_tree(model_gender,\n               feature_names = fn, \n               class_names=cn,\n               filled = True);\nfig.savefig('imagename.png')\n\"\"\"\n#### knowing that Female is encoded withh 0 and male with 1 ,  The previous fig shows that the model predicts high survival for females \n\"\"\"\n\"\"\"\n#### Two-Feature model\n\"\"\"\ngender_class=[\"Pclass\",\"Sex_enc\"]\nmodel2=tree.DecisionTreeClassifier(max_depth=6)\nmodel2.fit(X_train_selected_features[gender_class],to_np_arr(y_train))\nmodel2_score= model2.score(X_train_selected_features[gender_class],to_np_arr(y_train))\nvalid_model2=model2.score(X_valid_selected_features[gender_class],to_np_arr(y_valid))\n\nprint(\"Training Acc for the two-Features model is \",model2_score,\"\\nValidation Acc: \",valid_model2 ,\"\\nOk..This is the best till now!!\")\n\n# This plot shows the  decision boundary for the social class and age  for tree of depth=10\nX_=X_train_selected_features[gender_class].to_numpy()\nplot_decision_regions(X_,to_np_arr(y_train).flatten(), clf=model2, legend=2)\n\n# Adding axes annotations\nplt.xlabel('P_Class')\nplt.ylabel('Gender')\nplt.title('model')\nplt.show()\n\"\"\"\nThe above visualization of the decision boundary shows that survival favors female of class 1\n\"\"\"\n\"\"\"\n# All Features Models\n### I.DecisionTreeClassifier\n\"\"\"\nparameters = {\n    \"max_depth\": [3, 5, 7, 9, 11, 13],\n}\n\nmodel_desicion_tree = tree.DecisionTreeClassifier(\n    random_state=1,\n    class_weight='balanced',\n)\n\nmodel_desicion_tree = GridSearchCV(\n    model_desicion_tree, \n    parameters, \n    cv=30,\n    scoring='accuracy',\n)\nmodel_desicion_tree.fit(X_train_selected_features,to_np_arr(y_train))\nprint(\"chosen param is \",model_desicion_tree.best_params_,\"Training Acc when applying chosen params\",model_desicion_tree.best_score_)\nprint(\"Validation acc : \", model_desicion_tree.score(X_valid_selected_features,to_np_arr(y_valid)))\n\"\"\"\n* ## Aloooot Better whoooohooo \n\"\"\"\n\"\"\"\n### II.RandomForestClassifier\n\"\"\"\nparameters = {\n    \"n_estimators\": [5, 10, 15, 20, 25], \n    \"max_depth\": [3, 5, 7, 9, 11, 13],\n}\nrf_model=GridSearchCV(RandomForestClassifier( random_state=0),parameters,cv=30,scoring='accuracy')\nrf_model.fit(X_train_selected_features,to_np_arr(y_train))\nprint(\"chosen params are \",rf_model.best_params_,\"Training Acc when applying chosen params\",rf_model.best_score_)\nprint(\"Validation acc : \", rf_model.score(X_valid_selected_features,to_np_arr(y_valid)))\n\"\"\"\n#### Better *Dancing and praying it will do the same on the test set\n\"\"\"\n\"\"\"\n### III.NN\n\"\"\"\nmodel_NN = models.Sequential()\nmodel_NN.add(Dense(60, activation='relu'))\nmodel_NN.add(Dense(40, activation='relu'))\nmodel_NN.add(Dense(20, activation='relu'))\nmodel_NN.add(Dense(10, activation='relu'))\nmodel_NN.add(Dense(1, activation='sigmoid'))\nmodel_NN.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nhistory=model_NN.fit(X_train_selected_features,to_np_arr(y_train),epochs=150, batch_size=10) \nplt.plot(history.history[\"accuracy\"])\nplt.xlabel(\"number of Iterations\")\nplt.ylabel(\"accuracy\")\nplt.title(\"accuracy vs iterations \")\n\n\n# evaluate the keras model\n_, accuracy = model_NN.evaluate(X_valid_selected_features,to_np_arr(y_valid))\nprint('Accuracy on Validation Set: %.2f' % (accuracy*100))\n\"\"\"\n### IV. Logistic Regression\n\"\"\"\npreprocessor=preprocessing.PolynomialFeatures(degree=1)\nfs_poly_train=preprocessor.fit_transform(X_train_selected_features)\nfs_poly_valid=preprocessor.transform(X_valid_selected_features)\n\nlog_model = LogisticRegression(random_state=0 ,penalty='l2',C=0.1).fit(fs_poly_train, to_np_arr(y_train))\nprint(\"Training acc of logistic regression model with first degree \",log_model.score(fs_poly_train,to_np_arr(y_train)))\nprint(\"\\nValidation Acc:\",log_model.score(fs_poly_valid, to_np_arr(y_valid)))\n\"\"\"\n### Let's finish with \n##### V. Support Support Vector Classification \n\"\"\"\nparameters={\n    \"C\":[0.1 ,1, 10 ],\n    \"degree\":[1 ,2 ,3 ],\n       \n    \n}\n\n#model_SVC_pred=GridSearchCV(SVC(kernel='linear'),parameters,cv=5,scoring='accuracy')\nmodel_SVC_pred=SVC(C= 1, degree= 3, gamma=1, kernel= 'linear')\nmodel_SVC_pred.fit(X_train_selected_features,to_np_arr(y_train))\nmodel_SVC_pred_score=model_SVC_pred.score(X_train_selected_features,to_np_arr(y_train))\nvalid_acc_svc=model_SVC_pred.score(X_valid_selected_features,to_np_arr(y_valid))\n#print(\"chosen params are \",model_SVC_pred.best_params_,\"Training Acc when applying chosen params\",model_SVC_pred.best_score_)\nprint(\"Training Acc:\",model_SVC_pred_score,\"\\n Validation Acc:\" ,valid_acc_svc)\n\n\"\"\"\n# Ensembling Classifier\n(learn a weighted average of each one of them , get them working together, get higher Acc , Hopfully)\n\n\"\"\"\ntree_pred_train = model_desicion_tree.predict(X_train_selected_features)\nrf_train_pred = rf_model.predict(X_train_selected_features)\nnn_pred_train = model_NN.predict_classes(X_train_selected_features)\nlog_train_pred = log_model.predict(preprocessor.transform(X_train_selected_features))\nsvc_train_pred=model_SVC_pred.predict(X_train_selected_features)\n\nall_models_train=pd.DataFrame({\"tree_pred_train\":tree_pred_train,\"rf_train_pred\":rf_train_pred,\"nn_pred_train\":nn_pred_train.flatten(),\"log_train_pred\":log_train_pred,'svc':svc_train_pred},index=X_train_selected_features.index)\n\n\ntree_pred_valid = model_desicion_tree.predict(X_valid_selected_features)\nrf_valid_pred = rf_model.predict(X_valid_selected_features)\nnn_pred_valid = model_NN.predict_classes(X_valid_selected_features)\nlog_valid_pred = log_model.predict(preprocessor.transform(X_valid_selected_features))\nsvc_valid_pred=model_SVC_pred.predict(X_valid_selected_features)\n\nall_models_valid=pd.DataFrame({\"tree_pred_valid\":tree_pred_valid,\"rf_valid_pred\":rf_valid_pred,\"nn_pred_valid\":nn_pred_valid.flatten(),\"log_valid_pred\":log_valid_pred,'svc':svc_valid_pred})\n#all_models_pred.join(pd.Series({'nn_pred_train':nn_pred_train})[0])\n#mean_train_pred = np.round((rf_train_pred + SVC_train_pred + tree_pred_train + log_train_pred ) \/ 4)\n## Creating a data frame of the prev predictions \n\n\nparameters={\"degree\":[1,2,3,4,5],\"gamma\":[1, 0.1, 0.001, 0.0001, 'auto'],\"kernel\":['linear', 'poly', 'rbf']}\n\n#Ensamling_pred=GridSearchCV(SVC(C=0.01),parameters,cv=5,scoring='accuracy')\nEnsamling_pred=SVC(C= 0.01,kernel='linear',gamma=1)\nEnsamling_pred.fit(all_models_train, to_np_arr(y_train))\nEnsamling_pred_score=Ensamling_pred.score(all_models_train,to_np_arr(y_train))\n#print(\"chosen params are \",Ensamling_pred.best_params_,\"Training Acc when applying chosen params\",Ensamling_pred.best_score_)\nvalid_score_Ensambling=Ensamling_pred.score(all_models_valid,to_np_arr(y_valid))\nprint(\"\\n Training Score\",Ensamling_pred_score,\"\\nValidation Acc:\",valid_score_Ensambling)\n# Let's look at the coeff of the last model \n\nweighted_avg=Ensamling_pred.coef_\nprint(\"coeff of Decision Tree Model\",weighted_avg[0][0])\nprint(\"coeff of Random Forest Model\",weighted_avg[0][1])\nprint(\"coeff of NN  Model\",weighted_avg[0][2])\nprint(\"coeff of Logestic Regression Model\",weighted_avg[0][3])\nprint(\"coeff of SVC Model\",weighted_avg[0][4])\n\n\n\"\"\"\n\n1. #### From the previous coeffs, the biggest contribution belongs to  Random Forest\n\"\"\"\n\"\"\"\n# Output\n\"\"\"\ntree_pred_test= model_desicion_tree.predict(test_data_selected_features)\nrf_test_pred = rf_model.predict(test_data_selected_features)\nnn_pred_test = model_NN.predict_classes(test_data_selected_features)\nlog_test_pred = log_model.predict(preprocessor.transform(test_data_selected_features))\nsvc_test_pred=model_SVC_pred.predict(test_data_selected_features)\n\nall_models_test=pd.DataFrame({\"tree_pred_valid\":tree_pred_test,\"rf_valid_pred\":rf_test_pred,\"nn_pred_valid\":nn_pred_test.flatten(),\"log_valid_pred\":log_test_pred,'svc':svc_test_pred})\nypred_test=Ensamling_pred.predict(all_models_test)\nsub_file=pd.DataFrame({\"PassengerId\":test_data.PassengerId,\"Survived\":ypred_test},dtype=np.int64)\n\nsub_file.to_csv(\"sub_file.csv\",index=False)\n\"\"\"\n### Achieved 0.78225 on Test Data \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '104e08dddcd2fd'}"}
{"id":"78221","text":"# Import Libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# Import Dataset\ndataset = pd.read_csv('https:\/\/archive.ics.uci.edu\/ml\/'\n            'machine-learning-databases\/breast-cancer-wisconsin\/breast-cancer-wisconsin.data', header=None)\nheader = ['Sample_code_number',\n         'Clump_Thickness',\n         'Uniformity_of_Cell_Size',\n         'Uniformity_of_Cell_Shape',\n         'Marginal_Adhesion',\n         'Single_Epithelial_Cell_Size',\n         'Bare_Nuclei',\n         'Bland_Chromatin',\n         'Normal_Nucleoli',\n         'Mitoses',\n         'Class']\ndataset.columns = header\n# There is few empty or garbage character in the dataset\ndataset['Bare_Nuclei'] = dataset['Bare_Nuclei'].replace(r'\\?', np.nan, regex=True)\nX = dataset.iloc[:,1:-1].values\ny = dataset.iloc[:,-1].values\ndataset.head(n=5)\n\"\"\"\nThis is breast cancer dataset, where we will predict the tumor is benign or malignant (2 for benign, 4 for malignant).\n\"\"\"\n# Dataset sanity check\ndataset.info()\n# Check Missing value\nprint(\"Number of Missing value\")\nfor col in dataset.columns:\n    print('\\t%s: %d' %(col, dataset[col].isna().sum()))\n\"\"\"\nThis dataset is having 11 features and 699 observations. All the features are scale between 1 to 10. So no need of feature scaling. There is missing value in Bare_Nuclei\n\"\"\"\n# Handling Missing value\nfrom sklearn.impute import SimpleImputer\nSI = SimpleImputer(strategy='mean')\nSI.fit(X[:,5:6])\nX[:,5:6] = SI.transform(X[:,5:6])\n# Split the dataset into train and test\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n# Apply logistic regression on train dataset\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state=0)\nclassifier.fit(X_train,y_train)\n# Apply logistic regression on test dataset\ny_pred = classifier.predict(X_test)\nnp.concatenate((y_test.reshape(len(y_test),1), y_pred.reshape(len(y_pred),1)),1)\n# Evaluate the model performance\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test,y_pred)\nprint(cm)\nprint(f'Accuracy score is {accuracy_score(y_test,y_pred)}')\n\"\"\"\nLet test with unknown data\nClump Thickness = 5\nUniformity of Cell Size = 8 \nUniformity of Cell Shape = 5\nMarginal Adhesion =  4\nSingle Epithelial Cell Size = 3  \nBare Nuclei =  4\nBland Chromatin = 2\nNormal Nucleoli = 4\nMitoses = 1\n\"\"\"\n# Check the new result\nclassifier.predict([[5,8,5,4,3,4,2,4,1]])","meta":"{'source': 'AI4Code', 'id': '8fbfffd9a7faec'}"}
{"id":"132102","text":"\"\"\"\n# Preprocessing\n-------------------\n\nThis part of the notebook focuses on preprocessing data.\n\"\"\"\n\"\"\"\n## Importing libraries\n\"\"\"\nimport pickle\nimport os\n\nimport keras\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import SpatialDropout1D, LSTM, Conv1D, Dense, GlobalMaxPooling1D, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\n\n\nos.chdir('\/kaggle\/input\/electrical-power-quality-meter-dataset')\nprint(os.listdir('.'))\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\n\"\"\"\n## Loading and cleaning data\n\"\"\"\ndata = pd.read_csv('power-quality-meter.csv')\n\n# Dropping Phase angle values as they have little effect\ninput_data = data.drop(['Date','Time','Cos Phi AN Avg','Cos Phi BN Avg','Cos Phi CN Avg','Cos Phi Total Avg'], axis = 1)\ninput_data.drop(input_data.columns[0], inplace=True, axis=1)\n\n# Dropping outliers\ninput_data = input_data[(np.abs(stats.zscore(input_data)) < 3).all(axis=1)]\n\nprint(list(input_data.columns.values))\n\n# Dump a pickle of dataset labels\nwith open('\/kaggle\/working\/labels.pickle', \"wb+\") as pickle_out:\n    pickle.dump(list(input_data.columns.values), pickle_out)\n\n\"\"\"\n## Preprocessing and conversion to supervised learning problem\n\"\"\"\n# Scaling data\nscaler = StandardScaler()\nscaler.fit(input_data[:3*len(input_data)\/\/4]) # 0.75 because train_size is 75% of given data\ncopy = scaler.transform(input_data)\n\ntimestep = 10\n\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n    n_vars = 1 if type(data) is list else data.shape[1]\n    df = pd.DataFrame(data)\n    cols, names = list(), list()\n\n    for i in range(n_in, 0, -1):\n        cols.append(df.shift(i))\n        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n\n    for i in range(0, n_out):\n        cols.append(df.shift(-i))\n        if i == 0:\n            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n        else:\n            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n\n    agg = pd.concat(cols, axis=1)\n    agg.columns = names\n\n    if dropnan:\n        agg.dropna(inplace=True)   \n        \n    return agg\n\ntrain = series_to_supervised(copy).values\nprint(np.array(train).shape)\n\"\"\"\n## Train-test split and dump data\n\"\"\"\nX_train = []\ny_train = []\n\nfor i in range(timestep, len(input_data)-1):\n    X_train.append(train[i-timestep:i, :len(input_data.columns)])\n    y_train.append(train[i-timestep, len(input_data.columns):])\n    \nX_train, y_train = np.array(X_train), np.array(y_train)\n\ndata_dump = X_train, y_train\n\nwith open(\"\/kaggle\/working\/data.pickle\",\"wb+\") as pickle_out:\n    pickle.dump(data_dump, pickle_out)\n\nwith open(\"\/kaggle\/working\/scaler.pickle\",\"wb+\") as pickle_out:\n    pickle.dump(scaler, pickle_out)\n\"\"\"\n# Training\n------------------\nThis section of the kernel focuses on training and validating the model\n\"\"\"\n\"\"\"\n## Load preprocessed data\n\"\"\"\nwith open(\"\/kaggle\/working\/data.pickle\", \"rb\") as f:\n    X_train, y_train = pickle.load(f)\n\"\"\"\n## Define and compile model\n\"\"\"\nmodel = Sequential()\nmodel.add(LSTM(512, activation = 'tanh', recurrent_activation = 'sigmoid', recurrent_dropout = 0, unroll = False, use_bias = True, return_sequences = True, input_shape=(X_train.shape[1],X_train.shape[2])))\nmodel.add(LSTM(256, activation = 'tanh', recurrent_activation = 'sigmoid', recurrent_dropout = 0, unroll = False, use_bias = True, return_sequences = True))\nmodel.add(GlobalMaxPooling1D())\nmodel.add(Dense(1024))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(X_train.shape[2]))\n\nmodel.compile(loss = 'mae', optimizer = Adam(lr = 1e-3))\n\"\"\"\n## Fit model\n\"\"\"\n# Model checkpoint callback to save model with lowest validation loss\ncp_callbacks = ModelCheckpoint(filepath = \"\/kaggle\/working\/model.h5\", monitor = \"val_loss\", mode = 'min', save_best_only = True, verbose = 1)\n\n# Fit model\nhistory = model.fit(X_train, y_train, epochs = 90, batch_size = 256, validation_split = 0.25, callbacks = [cp_callbacks])\n\"\"\"\n## Validation of data\n\"\"\"\nmodel = tf.keras.models.load_model(\"\/kaggle\/working\/model.h5\")\n\nvalidation_target = y_train[3*len(X_train)\/\/4:]\nvalidation_predictions = []\nerror = []\n\n# index of first validation input\ni = 3*len(X_train)\/\/4\n\nwhile len(validation_predictions) < len(validation_target) - 1:\n  p = model.predict(X_train[i].reshape(1, X_train.shape[1], X_train.shape[2]))[0] \n  i += 1\n  error.append(mean_absolute_error(p,y_train[i]))\n\n  # update the predictions list\n  validation_predictions.append(p)\n\"\"\"\n## Plot mean absolute error\n\"\"\"\nfig = plt.figure()\nfig.set_size_inches(18.5, 10.5)\nfig.suptitle('Mean Absolute Error', size=20)\nplt.plot(error, label='Error')\nplt.xticks(fontsize=18)\nplt.ylim(0, 10)\nplt.legend(prop={'size': 20})\nplt.show()\n\"\"\"\n## Plot predicted vs actual values for all parameters\n\"\"\"\nwith open('\/kaggle\/working\/scaler.pickle', 'rb') as f:\n    scaler = pickle.load(f)\n    \nwith open('\/kaggle\/working\/labels.pickle', 'rb') as f:\n    labels = pickle.load(f)\n\nfor i in range(validation_target.shape[1]):\n    fig = plt.figure()\n    fig.set_size_inches(18.5, 10.5)\n    fig.suptitle(\"Fig \"+str(i+1)+\": Predicted and actual values for \"+labels[i], size=30)\n    plt.plot(scaler.inverse_transform(validation_target)[:, i], label='Actual')\n    plt.plot(scaler.inverse_transform(np.array(validation_predictions))[:, i], '--', label='Predicted')\n    plt.xticks(fontsize=18)\n    plt.yticks(fontsize=18)\n    plt.legend(prop={'size': 20})\n    plt.show()\n\"\"\"\n# Conclusion\n\nThat's it for the kernel. Feel free to fork and edit, download the model and use it from the outputs. Enjoy yourself.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f301e0c4f61846'}"}
{"id":"118169","text":"\"\"\"\n<font size='5'><b>1. Importa\u00e7\u00e3o dos dados<\/b><\/font> <br>\nPrimeiramente, importamos a biblioteca pandas para facilmente ler os conte\u00fados csv de teste e de treino.\n\"\"\"\nimport pandas as pd\ndados_de_teste = pd.read_csv(\"..\/input\/adult-pmr3508\/test_data.csv\", na_values=\"?\")\ndados_de_teste.head()\ndados_de_treino = pd.read_csv(\"..\/input\/adult-pmr3508\/train_data.csv\", na_values=\"?\")\ndados_de_treino.head()\n\"\"\"\nAntes de analisar os dados faltantes com cuidado, pode valer a pena eliminar diretamente os indiv\u00edduos com dados faltantes de forma a fazer gr\u00e1ficos de an\u00e1lise realistas.\n\"\"\"\ndados_de_treino = dados_de_treino.dropna()\ndados_de_teste = dados_de_teste.dropna()\n\"\"\"\n<font size='5'><b>2. An\u00e1lise de dados<\/b><\/font> <br>\nImportando as bibliotecas necess\u00e1rias:\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\nimport seaborn as sns\nimport matplotlib as plt\n\"\"\"\nPrimeiramente, iremos an\u00e1lisar a correla\u00e7\u00e3o entre as vari\u00e1veis num\u00e9ricas. Como nos interessamos no atributo \"income\", j\u00e1 o transformaremos em num\u00e9rico. \n\"\"\"\ndados_de_treino['income'] = LabelEncoder().fit_transform(dados_de_treino['income'])\nsns.heatmap(dados_de_treino.corr(), annot = True)\n\"\"\"\n\u00c9 muito claro observando a coluna \"income\" que os atributos Id e fnlwgt n\u00e3o influenciam relevantemente a nossa vari\u00e1vel de interesse. Retiremos portanto elas dos dados.\n\"\"\"\ndados_de_treino = dados_de_treino.drop(columns=[\"Id\", \"fnlwgt\"])\ndados_de_teste = dados_de_teste.drop(columns=[\"Id\", \"fnlwgt\"])\n\"\"\"\nNovo heatmap:\n\"\"\"\nsns.heatmap(dados_de_treino.corr(), annot = True)\n\"\"\"\n<font size='4'><b>2.1 Gr\u00e1ficos e estat\u00edsticas<\/b><\/font> <br>\nPrimeiramente, vejamos quantos porcento dos dados de interesse s\u00e3o maiores que 50k (indicado por 1) e menores (0):\n\"\"\"\ndados_de_treino['income'].value_counts()\/dados_de_treino['income'].count() * 100\n\"\"\"\nPartamos para a an\u00e1lise gr\u00e1fica. O m\u00e9todo principal que ultilizaremos para facilitar a interpreta\u00e7\u00e3o dos dados \u00e9 a continuiza\u00e7\u00e3o destes atrav\u00e9s da m\u00e9dia. Quanto mais pr\u00f3ximo de 1, mais indiv\u00edduos com o atributo observado possuem sal\u00e1rio anual >50k, enquanto quanto mais pr\u00f3ximo de 0, menos t\u00eam. Primeiro, a an\u00e1lise por sexo:\n\"\"\"\ndados_de_treino.groupby(['sex'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por sexo\")\ndados_de_treino['sex'].value_counts()\/dados_de_treino['sex'].count() * 100\n\"\"\"\nVemos que os homens tem uma tend\u00eancia maior a ter sal\u00e1rios altos do que mulheres, embora mais homens tenham sido analisados, indicando um poss\u00edvel vi\u00e9s dos dados.\n\"\"\"\ndados_de_treino.groupby(['race'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por ra\u00e7a\")\ndados_de_treino['race'].value_counts()\/dados_de_treino['race'].count() * 100\n\"\"\"\nO gr\u00e1fico parece indicar que brancos e asi\u00e1ticos tem maiores tend\u00eancias a ganhar sal\u00e1rios altos, por\u00e9m os dados est\u00e3o concentrados em pessoas brancas, o que novamente pode indicar vi\u00e9s.\n\"\"\"\ndados_de_treino.groupby(['native.country'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por pa\u00eds de origem\")\ndados_de_treino['native.country'].value_counts()\/dados_de_treino['income'].count() * 100\n\"\"\"\nEm primeira an\u00e1lise, o gr\u00e1fico parece justo, bem distribuido. Por\u00e9m quando olhamos para a concentra\u00e7\u00e3o de dados do pa\u00eds de origem, encontramos uma concentra\u00e7\u00e3o enorme nos Estados Unidos, o que pode comprometer a credibilidade dos outros dados.\n\"\"\"\ndados_de_treino.groupby(['education'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por n\u00edvel educacional\")\ndados_de_treino.groupby(['education.num'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por anos de estudo\")\ndados_de_treino['education'].value_counts()\/dados_de_treino['education'].count() * 100\n\"\"\"\nAnalisamos n\u00edvel educacional e anos de estudo juntos pois s\u00e3o dados muito intimamente relacionados. A an\u00e1lise dos dados tamb\u00e9m parece indicar o j\u00e1 esperado, niveis educacionais maiores e mais anos de estudo profissional tendem a proporcionar melhores chances de um alto sal\u00e1rio.\n\"\"\"\ndados_de_treino.groupby(['marital.status'])['income'].aggregate('mean').plot(kind='bar', ylabel=\"m\u00e9dia de income\", title=\"Tend\u00eancia a sal\u00e1rio >50k por status de relacionamento\")\ndados_de_treino['marital.status'].value_counts()\/dados_de_treino['marital.status'].count() * 100\n\"\"\"\nPodemos ver que os tipos de casamento que possivelmente tornam mais lucrativas as familias s\u00e3o o casamento civil e o \"Married-AF-spouse\". Analisando as frequ\u00eancias de cada atributo no entanto vemos que este segundo talvez n\u00e3o seja um dado confi\u00e1vel, visto que ele \u00e9 observado em apenas 0,07% dos indiv\u00edduos.\n\"\"\"\nidades = list(set(dados_de_treino['age'].to_list())) #retira valores duplicados\nmedias_income = dados_de_treino.groupby(['age'])['income'].aggregate('mean').to_list()\nplt.pyplot.title(\"M\u00e9dia de sal\u00e1rio >50k por idade\")\nplt.pyplot.xlabel(\"age\")\nplt.pyplot.ylabel(\"M\u00e9dia de income\")\nplt.pyplot.scatter(x=idades, y=medias_income)\ndados_de_treino['age'].value_counts().sort_index()[40:72]\n\"\"\"\nA an\u00e1lise das idades parece indicar que pessoas de por volta de 50 anos tendem a ter melhores sal\u00e1rios. H\u00e1 certas idades na faixa dos 75-85 anos que parecem superar as de 50 por\u00e9m, observando atentamente, vemos que o n\u00famero de casos destas idades \u00e9 muito pequeno e provavelmente se tratam de outliers.\n\"\"\"\ndados_de_treino.groupby(['workclass'])['income'].aggregate('mean').plot(kind='bar', title=\"Tend\u00eancia a sal\u00e1rio >50k por tipo de emprego\")\ndados_de_treino['workclass'].value_counts()\/dados_de_treino['workclass'].count() * 100\n\"\"\"\nSimilar aos pa\u00edses de origem, os dados parecem at\u00e9 bem distribu\u00eddos por\u00e9m a inspe\u00e7\u00e3o da frequ\u00eancia de cada tipo poss\u00edvel revela que h\u00e1 concentra\u00e7\u00e3o na \u00e1rea privada. A tend\u00eancia maior de pessoas auto-empregadas pode ser contestada portanto devido \u00e0 sua baixa frequ\u00eancia nos dados.\n\"\"\"\nhoras = list(set(dados_de_treino['hours.per.week'].to_list())) #retira valores duplicados\nmedias_income = dados_de_treino.groupby(['hours.per.week'])['income'].aggregate('mean').to_list()\nprint(medias_income.index(max(medias_income))+1) #valor de idade que possu\u00ed maior m\u00e9dia\nplt.pyplot.title(\"M\u00e9dia de sal\u00e1rio >50k por horas de trabalho na semana\")\nplt.pyplot.scatter(x=horas, y=medias_income)\ndados_de_treino['hours.per.week'].value_counts().sort_index()[40:99]\n\"\"\"\nPor fim, vendo o atributo de horas de trabalho por semana, vemos que a tend\u00eancia geral de pico \u00e9 em torno de 50 horas por semana, contando, similarmente \u00e0 an\u00e1lise das idades, com alguns outliers, como no caso dos 61 anos de idade, que possu\u00ed m\u00e9dia muito superior \u00e0s outras, mas porque conta com apenas duas apari\u00e7\u00f5es no dataset, como visto na an\u00e1lise.\n\"\"\"\n\"\"\"\n<font size='5'><b>3. Tratamento de dados<\/b><\/font> <br>\n<font size='3'><b>3.1 Dados faltantes<\/b><\/font> <br>\nAgora que analisamos que atributos podem estar enviesados, vejamos quais deles possuem lacunas e o que devemos fazer com elas: \n\"\"\"\ndados_de_treino = pd.read_csv(\"..\/input\/adult-pmr3508\/train_data.csv\", na_values=\"?\")\ndados_de_treino['income'] = LabelEncoder().fit_transform(dados_de_treino['income'])\ndados_de_treino = dados_de_treino.drop(columns=[\"Id\", \"fnlwgt\"])\ndados_de_treino.isna().sum()\ndados_de_teste = pd.read_csv(\"..\/input\/adult-pmr3508\/test_data.csv\", na_values=\"?\")\ndados_de_teste = dados_de_teste.drop(columns=[\"Id\", \"fnlwgt\"])\ndados_de_teste.isna().sum()\n\"\"\"\nComo vimos, o atributo native.country tem grandes chances de ser enviesado e portanto deve ser retirado\n\"\"\"\ndados_de_treino = dados_de_treino.drop(columns=[\"native.country\"])\ndados_de_teste = dados_de_teste.drop(columns=[\"native.country\"])\n\"\"\"\nAntes de decidir o que fazer com os outros, vale a pena transformar os dados n\u00e3o-num\u00e9ricos em num\u00e9ricos e ver sua correla\u00e7\u00e3o com o income. Caso ela seja baixa podemos j\u00e1 retir\u00e1-los sem precisar pensar se a substitui\u00e7\u00e3o pela moda \u00e9 uma op\u00e7\u00e3o melhor.\n\"\"\"\ndados_de_treino = dados_de_treino.apply(lambda col: LabelEncoder().fit_transform(col.astype(str)), axis=0, result_type='expand')\ndados_de_teste = dados_de_teste.apply(lambda col: LabelEncoder().fit_transform(col.astype(str)), axis=0, result_type='expand')\nsns.heatmap(dados_de_treino.corr()[\"income\"].to_frame(), annot = True)\n\"\"\"\nVemos portanto que tanto occupation quanto workclass pouco influenciam em nossa vari\u00e1vel de interesse, e assim podemos nos desvencilhar delas. Por inspe\u00e7\u00e3o, vemos tamb\u00e9m que os atributos race e education podem ser retirados tamb\u00e9m.\n\"\"\"\ndados_de_treino = dados_de_treino.drop(columns=[\"workclass\", \"education\", \"occupation\", \"race\"])\ndados_de_teste = dados_de_teste.drop(columns=[\"workclass\", \"education\", \"occupation\", \"race\"])\ndados_de_teste.isna().sum()\n\"\"\"\nAssim ficam nossos dados de treino e teste:\n\"\"\"\ndados_de_treino.head()\ndados_de_teste.head()\n\"\"\"\n<font size='5'><b>4. Cria\u00e7\u00e3o do modelo e sele\u00e7\u00e3o de par\u00e2metros<\/b><\/font> <br>\nPrimeiramente, separemos nossos dados em \"x\" (atributos dispon\u00edveis) e \"y\" (vari\u00e1vel de interesse):\n\"\"\"\ndados_de_treino_y = dados_de_treino[\"income\"]\ndados_de_treino_x = dados_de_treino.drop(columns=[\"income\"]).values\n\"\"\"\nPara a decis\u00e3o do par\u00e2metro k, necess\u00e1rio na implementa\u00e7\u00e3o do algoritmo knn, utilizaremos do m\u00e9todo de valida\u00e7\u00e3o cruzada 10-fold iteradamente, analisando valores de k de 15 a 40, por serem de tamanho adequado para nossos dados, e encontraremos qual deles gera melhor resultado, olhando a pontua\u00e7\u00e3o m\u00e9dia fornecida pela valida\u00e7\u00e3o de cada k. Importando as bibliotecas necess\u00e1rias:\n\"\"\"\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nmax_score = 0\nmax_k = 0\nfor k in range(15,40):\n    estimador = KNeighborsClassifier(n_neighbors = k)\n    scores = cross_val_score(estimador, dados_de_treino_x, dados_de_treino_y, cv=10)\n    if scores.mean() > max_score:\n        max_k = k\n        max_score = scores.mean()\nprint(\"Max k:\", max_k, \"max score m\u00e9dio:\", max_score)\n\"\"\"\nO valor de k que gera melhores resultados portanto \u00e9 24. Com isso, conseguimos criar o classificador utilizando a biblioteca sklearn.\n\"\"\"\nestimador = KNeighborsClassifier(n_neighbors=24)\nestimador = estimador.fit(dados_de_treino_x, dados_de_treino_y)\nprevisao = estimador.predict(dados_de_teste.values)\nprevisao_str = []\nfor i in previsao:\n    if i == 1:\n        previsao_str.append(\">50K\")\n    else:\n        previsao_str.append(\"<=50K\")\n\"\"\"\nPor fim, devemos carregar nossos resultados num arquivo csv. \n\"\"\"\ndf_submissao = pd.DataFrame({\"Id\": range(len(previsao)), \"income\": previsao_str})\ndf_submissao.to_csv(\"submissao.csv\", index = False)","meta":"{'source': 'AI4Code', 'id': 'd9653c1995c15e'}"}
{"id":"110937","text":"\"\"\"\n# Taxi New York\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom geopy import distance\nimport os\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble.forest import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.datasets import make_regression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\n\"\"\"\n## Data loading\n\"\"\"\n#train = pd.read_csv(\".\/input\/nyc-taxi-trip-duration\/train.csv\")\n#test = pd.read_csv(\".\/input\/nyc-taxi-trip-duration\/test.csv\")\n#sample = pd.read_csv(\".\/input\/nyc-taxi-trip-duration\/sample_submission.csv\")\nimport os\ntrain = pd.read_csv(\"..\/input\/train.csv\")\ntest = pd.read_csv(\"..\/input\/test.csv\")\n#sample = pd.read_csv(\"..\/input\/sample_submission.csv\")\n\"\"\"\n## data exploration\n\"\"\"\ntrain.shape,test.shape\ntrain.head(10)\ntest.head(10)\ntest.describe()\ntrain.describe()\ntrain.isna().sum()\ntest.isna().sum()\nplt.subplots(figsize=(18,7))\nplt.title(\"Outliers\")\ntrain.boxplot()\n\"\"\"\n## data cleaning\n\"\"\"\ntrain[['trip_duration']].boxplot()\ntrain[['trip_duration']].boxplot(vert=False)\ntrain[['pickup_longitude','dropoff_longitude']].boxplot()\ntrain = train.loc[train['dropoff_longitude']> -75]\ntrain = train.loc[train['pickup_longitude']> -75]\ntrain[['pickup_longitude','dropoff_longitude']].boxplot()\ntrain = train.loc[train['dropoff_longitude']< -73]\ntrain = train.loc[train['pickup_longitude']< -73]\ntrain[['pickup_longitude','dropoff_longitude']].boxplot()\ntrain[['pickup_latitude','dropoff_latitude']].boxplot()\ntrain = train.loc[train['dropoff_latitude']>40.5]\ntrain = train.loc[train['pickup_latitude']>40.5]\ntrain[['pickup_latitude','dropoff_latitude']].boxplot()\ntrain = train.loc[train['dropoff_latitude']<41]\ntrain = train.loc[train['pickup_latitude']<41]\ntrain[['pickup_latitude','dropoff_latitude']].boxplot()\n\"\"\"\n## Make more data\n\"\"\"\n\"\"\"\n### Creat column for Day of the week, minute, hour, day and month\n\"\"\"\ntrain['pickup_datetime']= pd.to_datetime(train.pickup_datetime, format='%Y-%m-%d %H:%M:%S')\ntrain['day_of_the_date']=train.pickup_datetime.dt.dayofweek\ntrain['month'] = train.pickup_datetime.dt.month\ntrain['day'] = train.pickup_datetime.dt.day\ntrain['hour'] = train.pickup_datetime.dt.hour\ntrain['minute'] = train.pickup_datetime.dt.minute\ntrain.head(5)\ntest['pickup_datetime']= pd.to_datetime(test.pickup_datetime, format='%Y-%m-%d %H:%M:%S')\ntest['day_of_the_date']=test.pickup_datetime.dt.dayofweek\ntest['month'] = test.pickup_datetime.dt.month\ntest['day'] = test.pickup_datetime.dt.day\ntest['hour'] = test.pickup_datetime.dt.hour\ntest['minute'] = test.pickup_datetime.dt.minute\ntest.head(5)\n\"\"\"\n### Calculate the distance between pickup point and dropoff point\n\"\"\"\ndef distancer(row):\n    coords_1 = (row['pickup_latitude'], row['pickup_longitude'])\n    coords_2 = (row['dropoff_latitude'], row['dropoff_longitude'])\n    return distance.distance(coords_1, coords_2).km\n\ntrain['distance'] = train.apply(distancer, axis=1)\ntest['distance'] = test.apply(distancer, axis=1)\ntrain.head()\ntest.head()\n\"\"\"\n## Log trip duration\n\"\"\"\ntrain['trip_duration_log']=np.log(train['trip_duration'].values)\nplt.hist(train['trip_duration_log'],bins=50)\n\"\"\"\n## Features selection\n\"\"\"\ntrain.columns,test.columns\ninput_columns=['day_of_the_date', 'month', 'day', 'hour','distance', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude']\ny=train['trip_duration_log']\nX=train[input_columns]\nX_test=test[input_columns]\nX_train, X_valid, y_train, y_valid = train_test_split(X,y, test_size=0.2, random_state=42)\nX_train.shape, X_valid.shape, y_train.shape, y_valid.shape\n\"\"\"\n## Entrainement\n\"\"\"\n# n_estimators=19, min_samples_split=2, min_samples_leaf=4, max_features='auto', bootstrap=True, verbose=2\nrfr = RandomForestRegressor(n_estimators=100,min_samples_leaf=3, min_samples_split=15, n_jobs=-1, max_features=\"auto\")\nrfr.fit(X_train, y_train)\ncv_scores = cross_val_score(rfr, X_train, y_train, cv=5)\nfor i in range (len (cv_scores)):\n    cv_scores[i]=np.sqrt(abs(cv_scores[i]))\nprint(np.mean(cv_scores))\n\"\"\"\n## Submission\n\"\"\"\ntrain_pred=rfr.predict(X_test)\ntrain_pred\nlen(train_pred)\nmy_submission = pd.DataFrame({'id':test.id, 'trip_duration':np.exp(train_pred)})\nmy_submission.to_csv('sub.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'cbd83a6c0d11a8'}"}
{"id":"109319","text":"\"\"\"\nClassify pigmented skin lesions dermatoscopic images from HAM10k https:\/\/www.nature.com\/articles\/sdata2018161 into 7 diagnosis\n\n\"\"\"\n# IMPORT MODULES\nimport sys\nfrom os.path import join\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.python.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.python.keras.preprocessing.image import load_img, img_to_array\n#from tensorflow.python.keras.applications import ResNet50\n\nfrom keras import models, regularizers, layers, optimizers, losses, metrics\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils, to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras.applications import ResNet50\n\nimport os\nprint(os.listdir(\"..\/input\"))\nPATH = \"..\/input\/dermmel\/DermMel\/\"\nprint(os.listdir(PATH))\n# Check content of the dirs\n\nPATHtrain = PATH + 'train_sep\/'\nprint(len(os.listdir(PATHtrain)), \" TRAIN Directories of photos\")\nLabels = os.listdir(PATHtrain)\nsig = 0\nfor label in sorted(Labels):\n    print(label,len(os.listdir(PATHtrain + label +'\/')))\n    sig = sig + len(os.listdir(PATHtrain + label +'\/'))\n\nprint(\"Total TRAIN photos \", sig)\nprint(\"_\"*50)\n\nPATHvalid = PATH + 'valid\/'\nprint(len(os.listdir(PATHvalid)), \" VALID Directories of photos\")\nLabels = os.listdir(PATHvalid)\nsig = 0\nfor label in sorted(Labels):\n    print(label,len(os.listdir(PATHvalid + label +'\/')))\n    sig = sig + len(os.listdir(PATHvalid + label +'\/'))\n\nprint(\"Total Validation photos \", sig)\nprint(\"_\"*50)\n\nPATHtest = PATH + 'test\/'\nprint(len(os.listdir(PATHtest)), \" TEST Directories of photos\")\nLabels = os.listdir(PATHtest)\nsig = 0\nfor label in sorted(Labels):\n    print(label,len(os.listdir(PATHtest + label +'\/')))\n    sig = sig + len(os.listdir(PATHtest + label +'\/'))\n\nprint(\"Total Testing photos \", sig)\nprint(\"_\"*50)\n# Check the photos and their labels \n\nTestNum = 8\ndiag = 'Melanoma'\n\nimage_dir = PATHtrain +'\/'+diag+'\/'\nimg_name = os.listdir(image_dir)[TestNum]\nimg_path = image_dir+str(img_name)\nimg = image.load_img(img_path, target_size=(224, 224))\nimgplot = plt.imshow(img)\nprint(\"TRAIN \",diag,\" photo number \", TestNum)\nplt.show()\n\nimage_dir = PATHvalid +'\/'+diag+'\/'\nimg_name = os.listdir(image_dir)[TestNum]\nimg_path = image_dir+str(img_name)\nimg = image.load_img(img_path, target_size=(224, 224))\nimgplot = plt.imshow(img)\nprint(\"VALID \",diag,\" photo number \", TestNum)\nplt.show()\n\nimage_dir = PATHtest +'\/'+diag+'\/'\nimg_name = os.listdir(image_dir)[TestNum]\nimg_path = image_dir+str(img_name)\nimg = image.load_img(img_path, target_size=(224, 224))\nimgplot = plt.imshow(img)\nprint(\"TEST \",diag,\" photo number \", TestNum)\nplt.show()\n\n# Convoluted Base MODEL\n\nconv_base = ResNet50(weights='imagenet',\ninclude_top=False,\ninput_shape=(224, 224, 3))\n\nprint(conv_base.summary())\n# MODEL\n\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1024, activation='relu',kernel_regularizer=regularizers.l2(0.001)))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(2, activation='sigmoid'))\n\nprint(model.summary())\n# Make the conv_base NOT trainable:\n\nfor layer in conv_base.layers[:]:\n   layer.trainable = False\n\nprint('conv_base is now NOT trainable')\n\"\"\"\nfor i, layer in enumerate(conv_base.layers):\n   print(i, layer.name, layer.trainable)\n\"\"\"\n# Compile frozen conv_base + my top layer\n\nmodel.compile(optimizer=optimizers.Adam(lr=1e-4),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nprint(\"model compiled\")\nprint(model.summary())\n# Prep the Train Valid and Test directories for the generator\n\ntrain_dir = PATHtrain\nvalidation_dir = PATHvalid\ntest_dir = PATHtest\nbatch_size = 20\ntarget_size=(224, 224)\n\n#train_datagen = ImageDataGenerator(rescale=1.\/255)\ntrain_datagen = ImageDataGenerator(rescale=1.\/255,\n                                   rotation_range=40,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True,\n                                   vertical_flip=True,\n                                   fill_mode='nearest')\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,target_size=target_size,batch_size=batch_size)\nvalidation_generator = test_datagen.flow_from_directory(\n    validation_dir,target_size=target_size,batch_size=batch_size)\ntest_generator = test_datagen.flow_from_directory(\n    test_dir,target_size=target_size,batch_size=batch_size)\nprint(train_generator.class_indices)\nprint(validation_generator.class_indices)\nprint(test_generator.class_indices)\n\"\"\"\nIt\u2019s necessary to freeze the convolution base of the conv base in order to\nbe able to train a randomly initialized classifier on top. For the same reason, it\u2019s only\npossible to fine-tune the top layers of the convolutional base **once the classifier on top\nhas already been trained**. If the classifier isn\u2019t already trained, then the error signal\npropagating through the network during training will be too large, and the representations\npreviously learned by the layers being fine-tuned will be destroyed\n\n**Below, first train with no limit to lr - with conv_base frozen - only  my top layers**\n\n**Then, unfreeze last model conv block , recompile and train all with LOW lr=1e-5**\n\"\"\"\n# Short training ONLY my top layers \n#... so the conv_base weights will not be destroyed by the random intialization of the new weights\n\nhistory = model.fit_generator(train_generator,\n                              epochs=50,\n                              steps_per_epoch = 10682 \/\/ batch_size,\n                              validation_data = validation_generator,\n                              validation_steps = 3562 \/\/ batch_size)\n\"\"\"\n# Make last block of the conv_base trainable:\n\nfor layer in conv_base.layers[:143]:\n   layer.trainable = False\nfor layer in conv_base.layers[143:]:\n   layer.trainable = True\n\nprint('Last block of the conv_base is now trainable')\n\"\"\"\n\"\"\"\nfor i, layer in enumerate(conv_base.layers):\n   print(i, layer.name, layer.trainable)\n\"\"\"\n\"\"\"\n# Compile frozen conv_base + UNfrozen top block + my top layer ... SLOW LR\n\nmodel.compile(optimizer=optimizers.Adam(lr=1e-5),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nprint(\"model compiled\")\nprint(model.summary())\n\"\"\"\n\"\"\"\n# Long training with fine tuning\n\nhistory = model.fit_generator(train_generator,\n                              epochs=8,\n                              steps_per_epoch = 10682 \/\/ batch_size,\n                              validation_data = validation_generator,\n                              validation_steps = 3562 \/\/ batch_size)\n\"\"\"\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'r', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'r', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\ntest_loss, test_acc = model.evaluate_generator(test_generator, steps= 3561 \/\/ batch_size, verbose=1)\nprint('test acc:', test_acc)\n# SAVE or LOAD model (Keras - all batteries included: architecture, weights, optimizer, last status in training, etc.)\n# YOU supply this model.h5 file from previous training session(s) - expected as a data source by Kaggle\n\n# SAVE model\nmodel.save('MelanomaResNetFeatExtract.h5')\nprint(\"MelanomaResNetFeatExtract.h5 was saved\")\n\n# LOAD model\n#del model\n#model = load_model('..\/input\/weather-v9\/modelWeatherV10.h5')\n#print(\"modelWeatherV10.h5 was loaded\")","meta":"{'source': 'AI4Code', 'id': 'c8e9b23fbb3728'}"}
{"id":"85093","text":"\"\"\"\n### Introduction\n\n\n\"\"\"\n\"\"\"\nWelcome to you for this Cycle GAN kernel. Coded by me S\u00e9mi Ben Hsan (SBH) .Machine Learning Intern at TalTech - Tallinn University of Technology . This kernel includes and advanced implementation of Cycle GAN with some visuals and tricks to improve the model performance , programmed in a professional way ( The SBH style ) and explained in detail . I am waiting for your votes, opinions and comments ... If you use parts of this notebook in your scripts\/notebooks, giving some kind of credit would be very much appreciated :) You can for instance link back to this notebook. Thanks!\n\n\"\"\"\n\"\"\"\n### Plan\n\"\"\"\n\"\"\"\n0. Importations\n1. Redefining Dataset\n2. Generator Architecture\n3. Model Blocks\n4. Full Generator\n5. Discriminator Architecture\n6.  Discriminator Code\n7. Discriminator Loss\n8. Generator Loss\n\n  8.1 Adversarial Loss\n\n  8.2 Identity loss\n\n  8.3 Cycle Consistency Loss\n\n  8.4 Full Generator Loss\n\n9. CycleGAN Training\n10. Main \n\n  10.1 Loading Data\n\n  10.2 Visuals\n\n  10.3.Prepare Model\n11. Tricks And improvements\n\"\"\"\n\"\"\"\n### 0. IMPORTATIONS\n\"\"\"\nimport glob\nimport random\nimport os\nfrom PIL import Image\nimport torch\nfrom torch import nn\nfrom tqdm.auto import tqdm\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\ntorch.manual_seed(0)\n\"\"\"\n### 1. Redefining Dataset\n\"\"\"\n\"\"\"\nPyTorch supports two classes, which are torch.utils.data.Dataset and torch.utils.data.DataLoader, to facilitate loading dataset and to make mini-batch without large effort. Let's use them now as below  in order to load our Monet and Real Photos \n\"\"\"\nclass ImageDataset(Dataset):\n    def __init__(self,MONET_FILENAMES,PHOTO_FILENAMES, transform=None): \n        self.transform = transform\n        self.PHOTO_FILENAMES = PHOTO_FILENAMES\n        self.MONET_FILENAMES = MONET_FILENAMES\n        if len(self.MONET_FILENAMES) > len (self.PHOTO_FILENAMES):\n            self.MONET_FILENAMES, self.PHOTO_FILENAMES = self.PHOTO_FILENAMES, self.MONET_FILENAMES\n        self.new_perm()\n\n    def new_perm(self):\n        self.randperm = torch.randperm(len(self.PHOTO_FILENAMES))[:len(self.MONET_FILENAMES)]\n    def __getitem__(self, index):     \n        item_MONET_FILENAMES = self.transform(Image.open(self.MONET_FILENAMES[index % len(self.MONET_FILENAMES)]))\n        item_PHOTO_FILENAMES = self.transform(Image.open(self.PHOTO_FILENAMES[self.randperm[index]]))\n        if item_MONET_FILENAMES.shape[0] != 3: \n            item_MONET_FILENAMES = item_MONET_FILENAMES.repeat(3, 1, 1)\n        if item_PHOTO_FILENAMES.shape[0] != 3: \n            item_PHOTO_FILENAMES = item_PHOTO_FILENAMES.repeat(3, 1, 1)\n        if index == len(self) - 1:\n            self.new_perm()\n        return (item_MONET_FILENAMES - 0.5) * 2, (item_PHOTO_FILENAMES - 0.5) * 2\n\n    def __len__(self):\n        return min(len(self.MONET_FILENAMES), len(self.PHOTO_FILENAMES))\n\"\"\"\n### 2. Generator Architecture \n\"\"\"\n\"\"\"\n\nThe generator is responsible for generating images from a specific domain. CycleGAN architecture has two generators, in this context we will have one generator that will take photos and generate Monet paints, and the other generator will take Monet paintings and generate photos.\n\nBellow, we have the architecture of the original CycleGAN generator , ours have some changes to improve performance on this task.\n\n\"\"\"\n\"\"\"\nDiagram of a CycleGAN generator: composed of encoding blocks, residual blocks, and then decoding blocks.\n\"\"\"\n\"\"\"\n![Cycle Gan.PNG](data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAA98AAAHICAYAAABXv1m6AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7J0FmBtJkrb\/u1uGYbLHzMzMzMzMzMzMzMzMPGPG8aCHmZlxd2\/hljf+ekOuHlmu7pZb0F3tyJnvaUuqSqlCWal8MyIj\/9+\/\/\/1vMZlMJpPJZDKZTCaTyRQ7\/b\/\/\/Oc\/YjKZTCaTyWQymUwmkyl2Mvg2mUwmk8lkMplMJpMpxjL4NplMJpPJZDKZTCaTKcb6f2LFihUrVqxYsWLFihUrVqxYiWkx+LZixYoVK1asWLFixYoVK1ZiXAy+rVixYsWKFStWrFixYsWKlRgXg28rVqxYsWLFihUrVqxYsWIlxsXg24oVK1asWLFixYoVK1asWIlxMfi2YsWKFStWrFixYsWKFStWYlwMvq1YsWLFihUrVqxYsWLFipUYF4NvK1asWLFixYoVK1asWLFiJcbF4NuKFStWrFixYsWKFStWrFiJcTH4tmIlHZb\/\/Oc\/8q9\/\/Uv+8Y9\/mEwmk8lkSgX985\/\/1N9jK1asWHGLwbdPCp33v\/\/9bwWqpMQxfu3o+ez8WP3973\/Xvzy2krKC7f7v\/\/5P\/vjHP5pMJpPJZEoF\/elPf9Kx2e1SEhun+nlsmlhxx+WMWf\/617\/qdVqxEk4x+PZB4Qb\/\/e9\/L++99568++678s477+hfL33++efyt7\/9zZedHJ3XE088IUuWLJHHH39c4dFKygo\/CH\/5y1+03ZhMJpPJZIq\/\/vCHP9w2UIaX\/7PPPtMxaug49ZNPPtExSXqCca7h66+\/lr1798qiRYvkm2++uf6KFStJF4NvHxQ6tP3790v58uWlVKlSUrJkSf3rpX79+snbb7\/ty86eH6rFixdL7ty5tSPjsZWUFYNvk8lkMplSV7cLfAPS3377rfTu3VtKlChx0zi1TJkyUrNmTenRo4fMnz9fgRyPMWMVvxa+19dff11at24tOXLkkDfeeOP6K1asJF0Mvn1Q6KBWrlwpv\/nNb+RXv\/qVZMiQQbJmzeqp9u3ba2fgx87++++\/lxkzZsh9990n06ZN08dWUlYMvk0mk8lkSl3dLvDNmOOLL76QatWqyX\/\/93\/rOC579uwKpYhx6x133CF33XWXPPDAA1KhQgU5duyYjlM4149ecBxjL730ktSpU0ev7eWXX77+ihUrSReDbx8UF77vvPNO7bC4wemwvETIuV87MoPv6BWDb5PJZDKZUle3I3z\/7Gc\/k4ULF+r1\/\/nPf9axCGvf33\/\/fTl69KjUqlVLARwgnzdvnr7G+X4rBt9WUloMvn1QXPhmxrBy5cry5ptvXn8l6QKA0+kj\/k3nRmfhZuF0n\/cq7vHusXyGpI7nNfc4t+6kOlP3s7nn8LkIWUoOvt3PFPw+oZ\/J\/ezuZwh+L97H65z0Vrhug2+TyWQymVJPtyN8\/\/znP5fly5fflH8IO\/Ac66THjx8v9957r5QuXVpOnjzpmeOHOt0xqztO5LnESvBYL6kxIuVWjqXwvPt53OPJU5QcfCf2PqGF49zxKSX42lFin8uKP4vBtw8KN2xK4Jsb97nnntNEbdy4zC6SBOOxxx6TK1euyFtvveV5U\/OYG5\/kbZx\/6dIlTYDGGh2vZG68D8k0nn32WTl79qwmTeM9eb\/ECmDILOjVq1fl3Llz8uKLL+o506dPTxS+6ZS++uoreeGFF+TChQt6LtfDZwoufB6ef+211\/R9uEY+n3vddPxJdeDpoXB9Bt8mk8lkMqWeDL69x5eMyTp16iR33323\/v3www+vHxEoHPe73\/1Ox3GXL1\/WcSj\/\/t\/\/\/d+b6nQL7\/fRRx\/JM888I+fPn5enn35aPvjgA0\/7cyxj0KeeeirhWM71+swUPvMPP\/yggM2YlbEka7wZ9yYF34zD+AxPPvmknsfx2Cn0PRjn85prB66TJaScw2cE9BO7biv+KwbfPigphW\/CfegUevbsKa+88oosXbpU14RXqlRJw9ebN28uO3bsuCHkh06KxwcPHtTz6tWrp4neqlevrueuXr1aPdQcjwDZ3bt3S69evfS9SKxB59uuXTtZtmyZAjWf3y2AMeds3bpV6+N6mPls1KiRjBgxQjp37qzXGQzfdDj8gJ06dUqGDh2qx\/KZeJ+2bdvKxo0bdaKAujmWTmr06NH6GpMGrCsiyQfncN1nzpzRY9Nz4bsx+DaZTCaTKfVk8O0NjIxPDh06JHnz5tXwc5wjHIvwggOiU6ZM0XEqY1bUrFkzmTNnjkJv8LgS+3733XeyZcsWHUMS1l6uXDn927VrV9mzZ4++Tt04Yz799FNZt26djkE5hmRw\/O3WrZts2rRJx6jU6X4exouA9cSJE6Vx48Y6zmXs2rFjRxk3bpw+DoVv3ufjjz+WtWvX6uQCyeZ4H8bUQ4YMUagGsCm8B22FY6iPpMns+tOkSRMpWrSo1K5dW8Gf46ykj2Lw7YMSDN90QG5CtWDR8bkdBcW9mekQOK9FixZ6Y\/fv318mTZqknc4vf\/lLKVKkiJw+fVo7Cgqd5YoVKyR\/\/vy6JqdLly4aCg4M169fX\/Lly6fecI6nfjpYspPTgQLgc+fOleHDh2snky1bNhkwYIDO5Lmfiw5k1apVWj8J4jiHzOZ0OHw+OuHf\/va3CfDNeXwm1gmRQZPPO2zYMO3QWFNUt25dyZMnT8L6IuzA3poAeqZMmWTkyJEK3ST8qFq1qv4w4Jl3rze9FoNvk8lkMplSVwbf3sDoAi1juJ\/85Ceyb98+HZdhKzeUm3ElY1DqYlzKv0niNmjQoAQPsTtGJIydsWjOnDk14zpjUZ6rUaOGlC1bVt+Lzwh48zzjU8ahjCdnzZqlY9VChQpp\/URguk4pPicOL8AcL32VKlVkwoQJOubkfRiTMsYOhm8+E5593odrAOxnz54tGzZskDFjxkjx4sV1PEoEJ+\/B8QD\/L37xCwV56udaChcurMc1bNhQnWmJ2dKK\/4rBtw+KC99AKUBJB0SHESxuVkJnXKjkJqXjp0PgPGCbmUU8xHiuCSGnc2PNTZ8+fbSj4RzCW+gYCP0GcAnDAYKRG7LOjwneZcKAgOyCBQvqzCKdGmFCX375pYYJMWt3\/\/33q5ebjoNOjE6VzqpAgQKyfv16rZ\/62B+Rcxo0aHCD55tz6MTovOgU8d5TP5+X93r++ed1NhTvOSHvdGTAN\/Vw3UwW0KnyuelAUbCnP70Wrs\/g22QymUym1JPBtzcwYhM8w3iqyY5O4jVsxbgOzzBjU8a2QDYeYkQkJfCK4waQZXzIe1y8eFEyZsyo48oDBw7omJF6GFcy5sPhQt0cj3ccZwyOLELH+cw4hRgbE\/HJWJKxJmDMeJrziOLMnDmzOnVY7ki9fLd8NsbJOIBc+OZ6GR\/zOfhMgDPvw3iWcTCQvX37dsmVK5dGcvK+2MKFbwAfGzLmZzkmXn7G3rdDG7qdisG3D4oL32w1xs0JVNIxBYvOhDAVNxQnGL7pNB599NEbElq4dXKj49GmE6TzpLO75557NLSGDikUUt2OFIAfO3asQjreZdZiu4Vj6LTWrFmj8M3MJh0M0IuXm46ZMHAgOrhDISxo8uTJej0ufPM5CSvnOUJvgHc6W0QHR8dIZ4pNAHM+L\/DNNWErwszpfF273C7F4NtkMplMptSVwXfi8M04cuDAgQrfREzyGIAlAhKnDhGP7ngPMYbFkfLggw\/K4MGDFbAZV7Zq1Up3A+rbt6\/n2mge837uOnOysRNezhgpeIwL4LNkkfqbNm2qdRFpytgTx9fOnTsVoN3COBcHEM4hF755H8bDHTp00OhSwuRpA9TlXgd1Ek6PV5tIUsanwfBNJCjjYSvptxh8+6C4oMzNTYfEuusTJ07cINYxMyvodvJ0NnT8nMMsIV7qYACl0+CmB57pLFkTTqcAdNNhMKvo1Ym5BVgnlJ26WTcemqmS85iNZBaRMCDWsNCxEqZDJzl\/\/nzt9ILrB7ZDE67xGehk6ZCYQaTDpAN0xXsT2kPYEt5\/OkY6UI6lHkLmudbEriO9FoNvk8lkMplSVwbficM3kY+smwa+FyxYoDBNDiHGiCVLltRxb\/B4DxFODgiT04eEaUAr4eMPPfSQ7N27N1Fbu2NeljdyLGvKg8GbwufF+40zi7EtYygSpfGYNd5EhgaPo91ozuCEa7wPY3HCx\/mco0aN0nFq8DVwXQA9oeV42Hnf4LBzPPW3m8PodisG3z4oLnwTjl2xYkXN+MgNHiw6gWCY5S8dvwvfhHRznFv4Nx0Fnmlm3+hAmK0jsRodAMnNeN\/EOk7CYFhLTZgPs5NAcmihc6M+3oNMkni6gWI6PpJdhBZgO3SrMaCe8HU6Y8J0eE\/W3ASrQoUK2mHh+cfr7cI3a9bp0EM72NuhGHybTCaTyZS6Mvj2HkMyBiWsGgj96U9\/qmHaeLGBa8a6Dz\/8sK7VDh3vMQbGqUPEJWHfr776qjp4AF0cPomN9xjPArrkDgLWcTiFFj4TY2XCyIk0ZUzMOURWspSRc4LH0YnBN6HiWbJk0etgmaXXNXBtJF8D6DnHhW8SxbGjD3VbSb\/F4NsHJRi+3WzndGjBCi08R8cfLnzTCXLzk5yCDoAwdY7xqpsSCt90sqHFhW9CeOhg6JjpbAgpwrMeWhKDb2ZG6YjxbBOuw2ynl7heOl4A3ODb4NtkMplMptSUwbf3GJLxCV5mQJe10exMw\/FEdjIGJJQcsA0d5+FVRkRSAqiALp5p4NtNYOZVXPjGo54UfBMl6q7hxmFEVvJf\/epXut4bx1cwFCcG32zjy9gY0CeRXOg1uNfx2WefqeOKzxwM34zHDb7TdzH49kHxgu\/kyq3CNx0IHR+h5HQ0rM0GfBPrOFk7Q9gP68lZkx28DobCeWRRZ5sEsj2S4I3Okm0f3LBzfpCC6we2ge7gNd98JkLRAXiSU7AOnfNCRedFXfw1+Db4NplMJpMptWXwfeMYkseAJXtfM4ZkvEcOIELQXUAGvhnDAamhYz1X7niPcWKxYsV0vMdYlNe8Cu8J1ALK1E9ot1uPWwBhwsLJhE6kJWMoJgUY55KgLTTsnHE0Xmq89y588z4sy+R9CCs\/fPiwPhf82V3x+Xl\/ZPB9exWDbx+UYPimA2Cmj5vWS25Hwl86\/nDhm39zPtuQ0THRgdIZ0AG49Qa\/BxDM1glAMdnEyXTuvo7oxAgDp2Nt06aNziASDj5z5kxNdkGGdep3OyBEh8V2DiR8c+GbayeLObOarNW5du1awvHBn4l63McG3wbfJpPJZDKltm5X+CYBLg6c4DEeYuyJ84awccZ6hF8zxmPMyHgTCGfHHXaqIRTdPc9rvIdw\/PTs2VPHuiRTc3ezCT4eUTdh5Iw9yWu0ePFiPTf48zHmJMcQY0cmBPhMjI0JEwfIWVPOOe7xXB9OJjzcLnzzPONjsrITuj516lRdyx48RkXu+7rXYfB9exWDbx8UF765uQmZoaPCk+wlOj9mG7mp6fhvBb7pAFg\/w3sAzSNGjFCoBpoRWSbpuFi\/TafDLCBADBiz5yEdG8eRpZFQdDoRQsyZ+aMT4z2pg7UwhPWQDZ3Py48TYTokpqAuJhlc+KaDYlsHslgyKQCc81k5h\/eiw2Kmko7cBXODb4Nvk8lkMplSW7cjfLOGG0cO4zrCq\/FgE7J98uRJdcow5mRsSFQkW3UxluN8d9ziOpvwHhP2DcwyruMv41925Tl27JjalXElGcepD0AGqvkcHI\/9SUbMuBUPNWNpgJ7ExYSF79q1S49xx5KrVq3SsSmfizqpm\/HslClTdEzMeJfxL+cwPuV6WAtOQmAXvhlHcx7rz1nvzXtxPa4DinMJeadO3o\/6uW6D79urGHz7oHAjA6p0RghAJcGEl1gfjWecTolOn5lFnmefweCbmX\/TGZL8jHXeQDedBlDNOhzW4ADmJDIjNIikZ3RKzEbSqfCZOBbw5TmO51hmHqmPMB2gnw4YKHcLHQxblAHGeM3paNiKjPAczmN\/R94XDzkdLZ+Jz0rHSafOeazX4fPgUWeiAJh3Z085nplPXuczET5Px3a7FfdHjI7eZDKZTCZT\/HU7wTeACaACkYzv2C\/bHZuyLptxIc8DqoznGEsCpMGFMRzebzzPjE+pg6282LqLZGUANuNFkvYyDuV4nDsrVqxQAEck4WUsTDg44eOMD8lazmdkXElSN+phjIhXu127dhpVSm4hxpObN29O8HAD7AC3u50Y18FWtoxdCxUqpEspeR\/gnHG0W\/B2A9eMj7kOksQxPgbWgXvswHiXiQLXyURiNz4Hy0ANvtN3Mfj2QeHGBHKBTjodxM3rpc6dO+uacM4BQpl1o3N55plnbvgB4N94ypmZA2JJoEZxOxsSm9FRuGu26WjwPgP2boeH8LKTWI3Qc0CYz1a4cGFp3bq1er\/5DKHvy9pvZgKpk7r5fAA5M6Qku6BjoyN1O2Xeh\/ekQ6bTpHPiPN4L4GerMT5vcEeMh5xQIBK78dztVgy+TSaTyWRKXd0u8M04C4AEZIFtxmeuFxkRSt6yZUv1+O7fv1\/hlLGml20ATzzLW7du1SS9eKmpD9jt1auXOpMY57nFHe8wfmT\/bI7jPcmRxP7hTAowPqTwfoxbWVvOZ2WMy+dkvAjwsxYcxxJ1ck385fPgjWarXLfuZs2ayZYtW3Q8y17ejEXdcTTFfR+iTrt3767vwzUwjicyk2vjXPd9sAf18vkZz\/K8lfRbDL59ULgJ6WgIo6Ej9+rgXdEBcdNzDn+BX0TnEQyhvE7HQCfDOW7HROE4HvM8nSlrsekI3eOC6+HfvA+v8f50PpzDe9KxhhaOR1wPnQ1AzXl8Do5HvMZj6nUL57h2wAYk6wDWqcM91q2ba+U4PgN\/ee52K9jK\/U5MJpPJZDLFX7cTfCc17sAOjMkYrzGO5NikCvUxRmXcS1bwt99+W8eWeKQZ44Wez\/HUy\/F4k1lXzvvyeULtz7GMNakLTzjjScK\/3TGu12dzx8REb1I318Lnoy7Gmbwvx4QW930YQ+O84lyO5dzgz8U18TzHuuNZK+m3GHz7pHAjIjqFpBR6w7rneRX3Na9j3OdC6w49zi23ciwlseOD5VV4Pvg899zQklw96b1gF4Nvk8lkMplST7cLfLvFa4zm6lbHZe6xoXUkVm7l+MSODff44GPdf7uPg4v7fDjvk9jzVtJfMfi2YiUdFjp4g2+TyWQymVJPtxt8W7FiJfli8G3FSjosBt8mk8lkMqWuDL6tWLESWgy+rVhJh8Xg22QymUym1JXBtxUrVkKLwbcVK+mwGHybTCaTyZS6Mvi2YsVKaDH4tmIlHRaDb5PJZDKZUlcG31asWAktBt9WrKTDYvBtMplMJlPqyuDbihUrocXg24qVdFgMvk0mk8lkSl0ZfFuxYiW0GHxbsZIOi8G3yWQymUypK4NvK1ashBaDbytW0mEx+DaZTCaTKXVl8G3FipXQYvBtxUo6LAbfJpPJZDKlrgy+rVixElpSCN\/\/cf7\/tyOnQ\/n3P9OpnGvTa3Su1YoVnxWDb5PJZDKZUlcG32m7\/If\/nLH+vxyeSa\/6t3N9XCPXGt1ynQU9GSo9yOVAR1EuKYNvvsyvX5d\/vn9B\/vnu2fSp987JPz98LPAFRL3BWrES22LwbTKZTCZT6srgO+0WYPSf\/\/6HfPjD2\/LcZ1fl2c8eS5d6\/vPH5dPffyD\/Up6JUvnPf+Tff\/le\/vnJU94MlR70nqP3L8p\/\/vqHqAN4yuDb+QL\/9cVL8o+Xd8vfX9iSPvXiVp1ckH\/9QxuZFSt+KgbfJpPJZDKlrgy+024Bvv\/hwPc7374iZ94+IKfTqc69c1jedq6RiYaoFQdG\/\/3n7+Qfbz\/qzVDpRS\/vlP\/85fu0Bt+75O\/Pb0qfcoz+z\/cMvq34sxh8m0wmk8mUujL4TrvFhe+3v31ZTr+1X069tS9d6uw7B+Wtb17Wa41aSYDvR7wZKl1os\/z9pR0G33GVwbcVHxeDb5PJZDKZUlcG32m3GHxHUFz4fut2gO\/vDL7jJoNvKz4uBt8mk8lkMqWuDL7TbjH4jqAYfEdUDL4Tk8G3FR8Xg2+TyWQymVJXBt9ptxh8R1AMviMqBt+JyeDbio+LwbfJZDKZTKkrg++0Wwy+IygG3xEVg+\/EZPBtxcfF4NtkMplMptSVwXfaLQbfERSD74iKwXdiMvi24uNi8G0ymUwmU+rK4DvtFoPvCIrBd0TF4DsxGXxb8XEx+DaZTCaTKXVl8J12i8F3BMXgO6Ji8J2YDL6t+LgYfJv8rt\/97nfy\/fffy7vvvisvvPCCPP\/882HpxRdflI8\/\/lh++OEHz3rTqvi83333nV7vlStX5NFHH5XnnntObeB1vMlkSvsy+E67xeA7gmLwHVEx+E5MBt9WfFwMvk1+F\/D9zTffyOzZs6Vhw4ZSr169G1S3bl1V6PONGjWSPXv2KMhSh1fdaVHffvutnDt3Tnr16iXVqlWTMmXK6L+\/\/PJLz+NNJlPal8F32i0G3xEUg++IisF3YjL4tuLjYvBt8rtc+O7bt69kzpxZHn74YVWGDBnkvvvuk1\/96lfy61\/\/Wh588EHJmDFjwutZsmSRlStX+g6+H3vsMWnSpIleX\/369WXChAmybds283ybTD6WwXfaLQbfERSD74iKwXdiMvi24uNi8G3yuwBnAPqDDz6QV199VV5++WUVIehLlixJAO\/Dhw9rqLn7Osd++umnvoJWrnXu3Llyxx13SMuWLTV8\/pNPPpGvv\/7a83iTyeQPGXyn3WLwHUEx+I6oGHwnJoNvKz4uBt+m9CCgFIgGwgnLRl988YVs3bpVQRVP99WrVxVS3dc5lvXTfvF68zk\/\/\/xzGTJkiPzkJz9Rrz3XyHX75RpMJpO3DL7TbjH4jqAYfEdUDL4Tk8G3FR8Xg29TehWAvXPnTrnzzjs1HP2pp566wcsNsOL5xgv+0UcfKZjzF4\/5448\/Lq+88kpCSDp\/eY3nqAeQ5zgStvGaWycwTyI0vOqswUY8JiHaE088oZ5qzgkFZs4DpPksTz75pIr6eU+ug+P5rLx327Zt5b\/\/+79l9erV8vrrr8ubb74pH374odaHqIv3feONN+TZZ5\/Va+HvW2+9lQDr7vvyb96Dz+t60KmLz8tnoG7enzo5BhHiz2d56aWX5JlnnpHXXntN3w87cP4777yjn9O93s8+++ym6+Xf7jW5NuX9iEzgc7h2d4\/nOOris7qfmcd8D9gg+JpMJj\/K4DvtFoPvCIrBd0TF4DsxGXxb8XEx+DalVyUH3wDe6dOnNXx7zZo1cu3aNZk3b540aNBAChUqJN27d1dPM\/XwGuHerVu3llKlSkm+fPl0vfX8+fMVHoPfk1D3Dh06yCOPPCInTpyQ4cOHS61ataRIkSKa+I33AIwBWs4BMgHedevWSYsWLaRkyZJSvHhx\/RwzZ87Uzw00Hzx4ULp27Sr58+eX\/\/qv\/9KkcX369NG17nw26qMuwHT37t3So0cPTchWuHBh\/ctxPM\/r7uf96quvNOlcmzZt5MiRIwqzkydP1s9brFgxmTRpkh4PVJPUrV27djopsGzZMl13XqFCBb3W\/fv362ckEdygQYOkdOnSUrRoUb1ejn3\/\/fcTrhfxPQDyixcv1vcmaRzX3LhxY1m4cKFOQriTGlwTtqxTp45+n7z\/9OnTtW5sMWzYMH3vYFg3mfwmg++0Wwy+IygG3xEVg+\/EZPBtxcfF4NuUXhUOfAOjDzzwgILumDFjFKqBX6Cyd+\/eCnV4gQFxIJZs6gBvz549pUSJEpIpUyaZOnWqemuBS7zChIU\/9NBDemyzZs0UKKmrc+fOkiNHDk30NmXKFD0HYMRrDMRny5ZNIXTw4MEyatQo6dKli1SqVEk2bNigkAwct2rVSuvA8w3gNm\/eXCcPxo4dq++P13nWrFkK+gUKFFAwHjBggLRv314\/P0C9YMEC9SRzPNfHZMH999+vkwQcj63Kli0rVatW1c\/JMXxG3o\/kdUA44NutWzfp1KmTvk+5cuX082HHKlWq6PXynnny5NH6mBzANlwv4rvAjrly5VL7jBgxQkaPHq2TD3x2Jgrefvtt\/YyI5QM\/+9nPtF7Oy549u35GvifO5bsO\/u5NJr\/J4DvtFoPvCIrBd0TF4DsxGXxb8XEx+DalVyUH3+7rrAkHwGvUqKEeVSDyzJkz6u3G48vfcePGKSDjGcaLC+Ru3LhRfvvb30rFihXl\/PnzCWHXAwcO1CRvQPLEiRM1OznHE549Z84cfT9gFS8xIIqXF5AHgHft2qVQDmzjHcfji6eXzw0EX7p0SYEb+J4xY4ZeE5+Pul1IBWjx3PP58MrjVecvHmgmF3Lnzi0nT57U66fORYsWqY04D+AGxnlfrokwcK6L4\/BMs9YcLzpeeD4foed8DtbUcw1EBRw\/flzee+89PXfkyJGacR5bEH7vAj+TBffcc49OJmBTIgwAfK4F7z5Z6Zl04DNy7Zs3b1ZvPxMUwD3ecT4j3xMh9cHfu8nkRxl8p91i8B1BMfiOqBh8JyaDbys+LgbfpvSqcOGb14E9wq0BVQDahT4ECAPcrNXmeQCS51lzDGwCrUAv57nwfffdd2uINuuRgVeOx\/NLqDUgmjNnTtm0aZPCN3BOHUDqlStXtA6O5304F3Ecz7FuG4\/4\/\/zP\/2iYOp\/NPYbX8ND\/8pe\/1EkEdz26+3kB4n79+ulEA6HevE8wfOOtZ8sy1mjzWTnX\/RwufP\/85z+X5cuXKyy718S6b6Ce9yVMnfM5h9dOnTqlXmomI5g44D0vXLigAM17AvHUzbGI6yEawfXa8xqfw4VvvieWCBAKz\/Hu9xT8vZtMfpTBd9otBt8RFIPviIrBd2Iy+Lbi42LwbUqvChe+77rrLilfvnySHlQXfjkH6AMiAWlCq4FWvMqAowvfeLEBXeDRrYPzgcZGjRrpOUAv9QLFhLrzOfAqHzp0KGGdtQvPnM9fPOh4hoFv1zNMHRxHYrWaNWvKvffeq2vZ3fNcUR+TBMAwHmQ8zUA0n4P3JpEb1xR8DqJ+F74BbOCY93Vfw1NPSDuv7dixQ+3jvkZ4e8GCBTVcnfN4PwCfyQbOwTvPuvhgkcWd9eKEuXM+7+XCN55yIgG43uDPaDL5XQbfabcYfEdQDL4jKgbficng24qPi8G3Kb3Khevk4Jvw5+rVq2tm7+DzgwVYA8l4poFe1nmz5pkQbjzWhGqHA9+AKmu08T6z9prn+RyEarM+ms9CKDvAyhpoPjP1AtJJwTd\/H330UQ395jPxOd33deUew\/vgiWZNNV5q4Jv3ZS033vPQ85KDb+pgnTavkbwt+DXs4YL59u3bFaaXLl2qNuMzEK5OJECwsmbNquviiSoI9Xxz7YS7B3+PJlN6kMF32i0G3xEUg++IisF3YjL4tuLjYvBtSq8CAsOFb9Z7e8E3xxOKzlpsQrWBWzcZWeXKldWDDGgD33iSUwLfQDXeYhK7TZgwQScC8ubNq3XgAcYTzmdNDr5ZA01CNc5NDL4JA+f13\/zmNxoS73q+8ZaTyCya8I284HvVqlWSIUMGTdpG2PnFixdvEiHqeLixC3Zz4ZsJD76nUK++yeR3GXyn3WLwHUEx+I6oGHwnJoNvKz4uBt+m9CogMFL4BizXrl2rAAlsA6rsX816ao5njTUh5JHANwJiAUq8vIScs3UXmb\/xEFeoUEHrTgq+OY+144A75xB2zvNu\/QiQJeSbsHOytPPZ4g3fHMv5rOlm3TfJ5rguL1E34t8G36b0LoPvtFsMviMoBt8RFYPvxGTwbcXHxeDblF4VDfjmOfazxluMx9ZNYkY9vNaxY0cF6Ujgm+epMxg4Oe\/AgQO6jzVh2MnBN68BzrzG+moyswO6LqRyDB78oUOHyoMPPqhgz2flfeIJ31wHa9PZRxzvN159jgmGaWzBc65NkMG3Kb3L4DvtFoPvCIrBd0TF4DsxGXxb8XEx+DalV0UDvtnCC28yEIzXGHikDvdcsnxHGnZOKDZ1kz3dBXvq2rJli67PJglbcvBNPZxLBnQ82yRw27t3r34e6uNzUB8gDMyznRrnxhu+8b5TF1uwYSNCz9lyzQ0v5y8e\/GnTpun6dJ5DBt+m9C6D77RbDL4jKAbfERWD78Rk8G3Fx8Xg25Re5QJyJPCNt3jMmDEKy5UqVdKttObOnavbfZEhnfMiCTsHXoFM9v1mLTkADHj2799f15eTgAyI5rMmB9+I19mTnLXoTBg0bNhQevTooX+ZKAC82Zebz0F9qQHfnMNEQ6dOnTThGq8TXUAIP39JtMZWbCtWrDD4Nt02MvhOu8XgO4Ji8B1RMfhOTAbfVnxcDL5N6VV4goFBwqzZ2or9qIOhjdf37dun8FyvXj0F1+DzESB57do1BV6AGmhmvXSDBg3Ue8zWWiRFAxQBTY4fPny4QuXgwYM1U7lbF+8NqLI9Gdm8AXZAFBAmoVuFChX0s\/B5EbAPeLvh4+jdd9+V3r17a8I0PNmh8O0CPq+xRp3Py57j1EuoN5+XNeWuHZgwYN9uQsAHDRqk9bt1BYvjmBygLmyG7dzXAHO2BeM1QuWDXwO2gWleA9rd1\/jc7J0+Z84cBXcmQNjuDBvj6V+\/fr1ml+d6+KyAO9nRuXaytLuf32RKLzL4TrvF4DuCYvAdUTH4TkwG31Z8XAy+TelVQCnw5m4BBrAFgyr\/BgIBRDfsOfh89xiAkTrwuALiQDr1Ic6jDuTWz3MuiAdDIq\/xmOepj788z\/u6z7GmHK8wEAzwBtfr1kH9vMbncp8PfQ+OoT5C2klqRr08Dr1O9\/PwPAr+vMGiXq6JOjg\/+H1T8hp\/eexeCyDOdQPcPHY\/p3s81wrkh9rDZEovMvhOu8XgO4Ji8B1RMfhOTAbfVnxcDL5NpuQF7AXL65hoiLqjCZex\/rzRkvs5\/fBZTaZYyOA77RaD7wiKwXdExeA7MRl8W\/FxMfg2mUwmkyl1ZfCddovBdwTF4DuiYvCdmAy+rfi4GHybTCaTyZS6MvhOu8XgO4Ji8B1RMfhOTAbfVnxcDL5NJpPJZEpdGXyn3WLwHUEx+I6oGHwnJoNvKz4uBt8mk8lkMqWuDL7TbjH4jqAYfEdUDL4Tk8G3FR8Xg2+TyWQymVJXBt9ptxh8R1AMviMqBt+JyeDbio+LwbfJZDKZTKkrg++0Wwy+IygG3xEVg+\/EZPBtxcfF4NtkMplMptSVwXfaLQbfERSD74iKwXdiMvi24uNi8G0ymUwmU+rK4DvtFoPvCIrBd0TF4DsxGXxb8XEx+DaZTCaTKXVl8J12i8F3BMXgO6Ji8J2YDL6t+LgYfJtMJpPJlLoy+E67xeA7gmLwHVEx+E5MBt9WfFwMvk0mk8lkSl0ZfKfdYvAdQTH4jqgYfCcmg28rPi4G3yaTyWQypa4MvtNuMfiOoBh8R1QMvhOTwbcVHxeDb5PJZDKZUlcG32m3GHxHUAy+IyoG34kpHvDt2PE\/\/\/xr+ta\/\/hb1Rmsl+WLwbTKZTCZT6ioa8P0fZwz1Twec\/u6Mp9Kr\/vGvvzv6hwJxvIrBdwTF4DuiYvCdmGIN306d\/\/nT144dn0+\/+vJF+df37yqEW4lvMfg2mUwmkyl1FQ34Bkw\/\/8NH8u63r6Vbvffd6\/Ltn77UiYZ4FYPvCIrBd0TF4DsxxQG+\/\/3tW\/L3F7elXzmN9p8fPS7\/+fufrl+0lXgVg2+TyWQymVJXkcO3A4gOfL\/0+ZNy9u2D6VPvHJLz7x6Rz37\/ofzb4DvqMvhOqQy+46+4wPeb3u+dXvTCVvnnh1fkP38z+I53Mfg2mUwmkyl1FS34fuGzx2+CqvQkAPzT373vwHf81scbfEdQDL4jKgbficngO3IZfKdaMfg2mUwmkyl1ZfAdngy+YyeD75TK4Dv+MviOXAbfqVYMvk0mk8lkSl0ZfIcng+\/YyeA7pTL4jr8MviOXwXeqFYNvk8lkMplSVwbf4cngO3Yy+E6pDL7jL4PvyGXwnWrF4NtkMplMptSVwXd4MviOnQy+UyqD7\/jL4DtyGXynWjH4NplMJpMpdWXwHZ4MvmMng++UyuA7\/jL4jlwG36lWDL5NJpPJZEpdGXyHJ4Pv2MngO6Uy+I6\/DL4jl8F3qhWDb5PJZDKZUlcG3+HJ4Dt2MvhOqQy+4y+D78hl8J1qxeDbZDKZTKbUlcF3eDL4jp0MvlMqg+\/4y+A7chl8p1ox+DaZTCaTKXVl8B2eDL5jJ4PvlMrgO\/4y+I5cBt+pVgy+TSaTyWRKXRl8hyeD79jJ4DulMviOvwy+I5fBd6oVg2+TyWQymVJXBt\/hyeA7djL4TqkMvuMvg+\/IZfCdasXg22QymUym1JXBd3gy+I6dDL5TKoPv+MvgO3IZfKdaMfg2mUwmkyl1ZfAdngy+YyeD75TK4Dv+MviOXAbfqVYMvk0mk8lkSl0ZfIcng+\/YyeA7pTL4jr8MviOXwXeqFYNvk8lkMplSVwbf4cngO3Yy+E6pDL7jL4PvyGXwnWrF4NtkMplMptSVwXd4MviOnQy+UyqD7\/jL4DtyGXynWjH4NplMJpMpdWXwHZ4MvmMng++UyuA7\/jL4jlwG36lWDL5NJpPJZEpdGXyHJ4Pv2MngO6Uy+I6\/DL4jl8F3qhWDb5PJZDKZUlcG3+HJ4Dt2MvhOqQy+4y+D78hl8J1qxeDbZDKZTKbUlcF3eDL4jp0MvlMqg+\/4y+A7chl8p1ox+DaZTCaTKXVl8B2eDL5jJ4PvlMrgO\/4y+I5cBt+pVgy+TSaTyWRKXRl8hyeD79jJ4DulMviOvwy+I5fBd6oVg2+TyWQymVJXBt\/hyeA7djL4TqkMvuMvg+\/IZfCdasXg22QymUym1JXBd3gy+I6dDL5TKoPv+MvgO3IZfKdaMfg2mUwmkyl1ZfAdngy+YyeD75TK4Dv+MviOXAbfqVYMvk0mk8lkSl0ZfIcng+\/YyeA7pTL4jr8MviNXPOCb74ab4t9Oh51exfVpGwy\/HYYL379Dv\/u9\/JDOxTVyrV42iFS3g\/0Q1+l1\/dHSbWNHj2uPpm4XO3pdezTl9Z7pUV7XboqeDL7Dk8F37GTwnVIZfMdfBt+RK+bw7Xwvzvfz7+\/fk39\/946jt9Onvn\/3+s0fA\/h2Bl9vf\/aDvPLxD\/LyR9+nS73y0Q\/y2ic\/xGSgCUh99s3v0rX90KvO9X313e9iOoHx5bfp345vfhpjOzr68Evs6P3+6UXvfP6DfP+Dtw2iIez4utNneL13etJbTt\/vdf2m6MngOzwZfMdOBt8plcF3\/GXwHbliDd+ODf\/zj\/\/T7+kfr+5ztDd96s1jDoC\/71xv+D9K4cL39w70PPnOd3LouW9l\/7PpUweca7v05ncxGawD9IDAiZe83zu96PSr38knXzvQGIMJDIQd3\/v8d3Loee\/3Ty+6+Pp38lmM7chk08F0fD+jS298J99+\/ztPG0RDfD9POP0ifYfX+6cHHXBEvxirtmgKyOA7PBl8x04G3ymVwXf8ZfAduWIO3\/+W\/\/z9L\/LPd0457+fcJF6fIR2IiQU8+xqCHmYJG74dIL369ney6+lvZNuT6VM7nvpGzr\/xrXwXI\/gmcgBo9Hrv9CImFz7+6ncxiR5ATAK9\/ekP6bodojOvfiefxhi+X\/rwe9l5G9gxlvCNHR93+kX6Dq\/3Tw\/a7lzb2de+NfiOsQy+w5PBd+xk8J1SGXzHXwbfkcvgOyoy+I5MBt+Ry+A7OjL4jo4MviOXwXd8ZPAdngy+YyeD75TK4Dv+MviOXAbfUZHBd2Qy+I5cBt\/RkcF3dGTwHbniBd+09w++\/CHd6kNHn3\/j3NMe144MvsOTwXfsZPCdUhl8x18G35HL4DsqMviOTAbfkcvgOzoy+I6ODL4jVzzgm7rPOe+x+5lvZNczX6dL7bn2jbaVxPpGg+\/wZPAdOxl8p1QG3\/GXwXfkMviOigy+I5PBd+Qy+I6ODL6jI4PvyBUv+OY9eC+vz+B3bXdEGzH4jlwG37GTwXdKZfAdfxl8Ry6D76jI4DsyGXxHLoPv6MjgOzoy+I5cBt\/RkcF3dGTwHTsZfKdUBt\/xl8F35DL4jooMviOTwXfkMviOjgy+oyOD78hl8B0dGXxHRwbfsZPBd0pl8B1\/GXxHLoPvqMjgOzIZfEcug+\/oyOA7OjL4jlwG39GRwXd0ZPAdOxl8p1QG3\/GXwXfkMviOigy+I5PBd+Qy+I6ODL6jI4PvyGXwHR0ZfEdHBt+xk8F3SmXwHX8ZfEcug++oyOA7Mhl8Ry6D7+jI4Ds6MviOXAbf0ZHBd3Rk8B07GXynVAbf8ZfBd+Qy+I6KDL4jk8F35DL4jo4MvqMjg+\/IZfAdHRl8R0cG37GTwXdKZfAdfxl8Ry6D76jI4DsyGXxHLoPv6MjgOzoy+I5cBt\/RkcF3dGTwHTsZfKdUBt\/xl8F35DL4jooMviOTwXfkMviOjgy+oyOD78hl8B0dGXxHRwbfsZPBd0pl8B1\/GXxHLoPvqMjgOzIZfEcug+\/oyOA7OjL4jlwG39GRwXd0ZPAdOxl8p1QG3\/GXwXfkMviOigy+I5PBd+Qy+I6ODL6jI4PvyGXwHR0ZfEdHBt+xk8F3SmXwHX8ZfEcug++oyOA7Mhl8Ry6D7+jI4Ds6MviOXAbf0ZHBd3Rk8B07GXynVAbf8ZfBd+Qy+I6KDL4jk8F35DL4jo4MvqMjg+\/IZfAdHRl8R0cG37GTwXdKZfAdfxl8Ry6D76jI4DsyGXxHLoPv6MjgOzoy+I5cBt\/RkcF3dGTwHTsZfKdUBt\/xl8F35DL4jooMviOTwXfkMviOjgy+oyOD78hl8B0dGXxHRwbfsZPBd0pl8B1\/GXxHLoPvqMjgOzIZfEcug+\/oyOA7OjL4jlwG39GRwXd0ZPAdOxl8p1QG3\/GXwXfkMviOigy+I5PBd+Qy+I6ODL6jI4PvyGXwHR0ZfEdHBt+xk8F3SmXwHX8ZfEcug++oyOA7Mhl8Ry6D7+jI4Ds6MviOXAbf0ZHBd3Rk8B07GXynVAbf8ZfBd+Qy+I6KDL4jk8F35DL4jo4MvqMjg+\/IZfAdHRl8R0cG37GTwXdKZfAdfxl8Ry6D76jI4DsyGXxHLoPv6MjgOzoy+I5cBt\/RkcF3dGTwHTsZfKdUBt\/xl8F35DL4jooMviOTwXfkMviOjgy+oyOD78hl8B0dGXxHRwbfsZPBd0pl8B1\/GXxHLoPvqMjgOzIZfEcug+\/oyOA7OjL4jlwG39GRwXd0ZPAdOxl8p1QG3\/GXwXfkMviOigy+I5PBd+Qy+I6ODL6jI4PvyGXwHR0ZfEdHBt+xk8F3SmXwHX8ZfEcug++oyOA7Mhl8Ry6D7+jI4Ds6MviOXAbf0ZHBd3Rk8B07GXynVAbf8ZfBd+Qy+I6KDL4jk8F35DL4jo4MvqMjg+\/IZfAdHRl8R0cG37GTwXdKZfAdfxl8Ry6D76jI4DsyGXxHLoPv6MjgOzoy+I5cBt\/RkcF3dGTwHTsZfKdUBt\/xl8F35DL4jooMviOTwXfkMviOjgy+oyOD78hl8B0dGXxHRwbfsZPBd0pl8B1\/GXxHLoPvqMjgOzIZfEcug+\/oyOA7OjL4jlwG39GRwXd0ZPAdOxl8p1QG3\/GXT+D7b89tkv97doP837UN8tdnNzqPN+rzPPfnZ9bLn55ep3\/d5+Mqn8A3NvyrYx9siLAVz\/EX2\/3xqXXyF+ev2tfj\/FjLD\/C99YmvZcvjX8nmq184\/\/7qx+eufimbrnwmmx\/73Hn9S30u9NxYyw\/wjV22OvbDXtgp+LlNju2wIa+5to23fAPf2Myx0Y925HHgOdqgtkXaqGNXz\/NjLN\/At9oscP8G2p1z315\/bvNjX6QJO\/oDvq\/b0WmLCXa8\/hz223j5U7UnfSf29a4jNjL4jo78BN8n39wrj76+R3Xyjb36GD3iPD7x6i45\/sou\/bfXubGWwXfsZPCdUhl8x18+gG\/gEMh++\/g8ubJpnLx+ZLbCNpD43iPz5cDCgbJmYhe5uHGs\/MkByLgDuE\/gGxt+cmaxXN0yQa7tmiJ\/dGwIhH91cbmcXjNS1k3uJidWDJXfP75GbetVRyyV1uEbsFl\/4UOZtfOKTN5wUlaefEsHmgwqZ2y\/JL0nr5L+M9bLggPX9DmvOmKptA7fOjh37LXo0HMyYe0JmbfvqcCA3BmcLzn6ogyeu1W6j12srzFYDwzgveuKlfwC39hxybGX1Fa0RyYueG75I6\/J8EW7pfu4JTJ6+QHZeOmTVLGjX+AbWMRm3M\/Tt55PmPxZdfptx36HpMf4pTJi8R5Zf\/GjVAFwv8A3UL3q1FsydfNZmbrlrNPuPlU7rj33vrbRnhOWydD5O9SuCuAedcRKBt\/RkV\/gG8g+\/spOWffoYlmyb6bsfGytPPLabgXx9c5zYxYOlpHzBsjaEwsdAN+tx3vVEysZfMdOBt8plcF3\/OUD+AYGV43vLJVL5JES+bJK1ZL5ZNnoDvLE1gnSuVEFKZw7s+TLnkHKF80lc4a0kq8vrfCsJ2ZK4\/CtkxcOZJ9YMUwaVy0mJQtkk3KFc8rg9rXluT1TZWKvxvpcwZwPS5E8maVn8yry1YVleo5XfbFSWoZvBt4M0uu06S05C5aUHAVKSOkajWXKptMKjbkKl5ZMuQpIppz5pWiFWs6A87gCUTzBJy3DNxMXgE3XUQskT9Gykj1fMSlQqrJ0HjlXB+cV67eRLHkKycPZ8zq2LS5tB06WdRc+iPtAPa3Dt+tJ7D99vRQqU02y5SsqeYuVk+a9xjht8YzUbt1LsuYtIg\/nyCdZcheShp0GyZqz7ypketUXK6V1+HYngkYu3islKteT7PmLSa5CpaRO2z46kda0x0hto5ly5pPMuQtKtaadHHB8K1XsmJbhW+3o2GTyhlNSrlZzvXdzFioplRq0lbl7n5D2Q2foc\/SLmZ3+sUK9VrLi0dfU9njGveqMtgy+oyM\/wPejb+yRw89vkw4DWkr+Ynkkd6EcUrpqcZm5cbzM3jxRCpfOL1md8SIqVbmYTFw+XI68uN2zrljJ4Dt2MvhOqdIZfLse279cW69\/UyOUN1mlcfgmLPrMmpFSNE8WaVKtuKyZ0EXG92gkDSoVkboVCkuH+uXl\/LoxCpFDO9R2jsssBxcN9KwrZkrj8E3be+PIHGlXr6yUK5JTFg5vK6vGdZaqJfNK69qlpXa5grJtRi95Yd90mT2opTx0352yeFR7DUP3qi9WSqvwzQBz05XPpevoBfJgpuxSq1UP6T5usZSt1VQqOoNMhZzOg2XmzssyaM5myVe8glRu2F6WHX8lroP1tAzfACOQDRgWLV9Tuo9fLM16jpJiFWtL4bLVHVs2k3Grj8pMB3xqte6pMDRswU4hhNqrvlgprcM30DJj+0UpVLaaFChZUbqNXSTtBk9TEC9RpZ4Ud0By6IIdMnPHZWnSbbg8lDmHRmQw8eFVX6yU1uGb+3L+\/qelfJ0WCt3th0yXrmMWSL4SFbQtYs8+U1fLLOeebj1gktx174PSYdgs2XjlU8\/6YqW0Dt9Mji078arUbtNbsuYpJC16j3Xa5EKdYKNvzFusvHQeNU9m7bqiE220x6Y9Rsc1ssXgOzryA3zj4R69cJA8lOkBqduqugya1kvqtKwuVRtUkALF80qTTvVk5ZF5CuKV6pSV0lWcMeXxBZ51xUp+hm8mN9wognhHDISjtArfsOBfrgVY8K+wYLyjc5NVOoJvoJF1tK8dmqX66tLy6+tsvY9PNaV5+N4o0\/o3c6Axl3xxYan875Nr5bsrK2Xe0NaSNeO9cnz5UAcS12oI9TvH50nDykVlXI+G8W3caRy+CdE\/unSI1KtYWI4uGyLfX10lv3t8tZxbN1ryZH1IJvVpojYFtvk7sF1NqVYqn3z32Mq4tte0Ct8MMNdd+FBKV28kNVp0k9Vn3tHB46LDz6nXEc\/OqlNv6nOEpfebtlbyFCkrM7ZdjCs8pmX4Jvy5df+J6u1eevxl2XDxYw1TbTtwinoXhznAiO04jrB0oIgJDcJ9veqLldI6fNPGCOEt7MA3Ib7rL3wka8+9J32dNpcxWx7p5gDkuvMf6HFrzr4nVRt3lAr1WjvPfehZX6yU1uGbyYjhC3dJ0Qo1te1hM2w5btURyZAlpzTrMVLtynGEThPxkr9ERf13vKARpXX4pn+jHRavVMdpewvVPtzbc\/Y8IQ9myqYRA2vOvqOTl9iYCI0MWXNrNEa8wvgNvqMjP8A367kr1S0n5aqXlMPPb5VjL++QvU9ukMr1ykmWnJlk31MbNSSdNd8zNoyTfEVz6994gqSf4XvXY2tl7YkFsueJ9Y5td6Y5AE+r8I0D7OUDM+RVhwW\/ubxC2dDruNRTuoLvjfIHBxQ7NCgnubM8KAPb1tR1tR+eWug8vyYA4h7nxV0+gO8RXepJi5ql5PvHVulj9MjKYdK5cUV5dveUhGM\/O7dEBrSpobYG0oPrianSOHwzMbFnXj9pVbu0XNo0NpBYzWl\/rJfv3bKa7J7bVwE90GbXyJZpPTQM\/cOTC\/U5rzpjobQL31\/qwLFwueoKkEAizzPIbNRlqDToOEA2XPr4uof8M5m0\/lGFzLErDsXV45iW4Rv7YCvCUYFuPOHYZsTivVK7VU+ZvuX89fXfX8rKk29Kk+7DpXqzLnqsV32xkh\/gu9Pw2VK+bkuZ6wAO8IOmbT4nNVt0l9HLDgSWOzhgQ\/vsMHSGFK9cV5dMeNUXK\/kBvgfO2iRlajaRCWuOO49Zo\/yFLD7ygtPuusqAGev1GO7pDZc+kd6TV2qIP+vsDb5\/FG1v4rpHpGTVBjJ4zhadPNP+0ukjqzXpLF1Hz9c2y7EbL38ig+dukXseyKgTl\/GKCvIDfNOm3DXy8\/c\/I3P3Pqn3LLZD5BHhHp+25ZwsPfby9bYZ3yU5foHvImUKStPO9fXfwCHqNaaTNGxXW446gOEeu\/LwXClRoYiMXTxEPbnB9cRSfobv4bP66SRG+VqlZfzS4bLh1BI59NzWVFk776W0Ct\/Adus6pSVHpvt1uSfRvB8442tlwTThCU9H8E1WabyLhPUWyJFRPbIATd9W1TUs+uPTi\/QYr3PjKh\/A96IRbXU9N7NGbvg+oE3SsG+vrEw49oOTCxxILykjHVgHLoPrial84Plm4qdp9eKyZXpP+eFqYBLjD0+skef3TpOPaIvPbkxosxN6NZJKxfPIFxeWGXw7wvONV6xqk05SuWE7WXL0pevPfylzdj\/u6GrCQJKB0pC5W9UjPnnjKR0kBdcVS6Vl+MYuXUbNk4Klq1yPCAhkkF7x6OuaMAwvrTsAxb5VmnSUuu36qvfRq75YKa3DN+1pwMwNmldg5JJ9alcG4XgSCTVn4oLHGq1x\/gNdw8zyCKI1vOqLldI8fDvQOGbFIYVGwBpbBUD7Y5m5\/bJGZ9A+eY7JtibdR2go9cpT2Nfg2xX3MUtFCNUnimX16XfUPkyusXZ+0aHntS1y7IaLH2l4\/4OZswfWfV9\/PtbyA3xjCyYamawoVqmuFCpTVep3HCCzdz2mk7mlqjXUsP7MOfPpsidsG8\/fFuQX+K7XuqaUqlJcE609+kYACDedXS6rji24AbLnbp2s68KnrB5lnu8wNXhaL8mc42GFb9bTl6laQkP71z2y6IaJjdRSWoVvxuAsm82V+QFp6vwtXySn9GpRNcCCZxYp13idFz+lM\/j+4epqaVOnjNSrWESe3T1VM3J3alhBapTJL\/3bVJddc\/oqMBI2DeSkiic8rcO3o2u7p6jNOju2279ggHpugUUAG7vRcAk5J9laGadDADC96oqZfLDmm4iLwe1r6STQ6gmd5dvLK9V+LnTz78\/OLVXbFcmdSUP3mZWLZ5tM02u+ncH6kHnbNNla467DdN0t3rLAAB3Y+VJDpMevPqYD0TI1mwYGnppYyLveaCstwzdexVk7H9P13YRB4yVbf\/FDHXRiP+zIQH7R4eelTf9JOnnRe0r81yr7Yc03XrAKdVtpwr8+jo0CiekC27MhwAd4JEcBSyLaD5mhkO5VX6yU1uEbe+FBrNu2rxSrGAiZXnPuPbWva0fa7IpH35A+k1dJllwFpVHXoeoFj1eiMJTW4Zv7Fmhs1XeCTqzR1sh1QRtM6BsdmwLlg2Zv1gmMas26aFRGvCYx\/ADf\/L6QY4BcF0zykq+hTI0m0qDTIM3jUKN5V+k2eqG06jdR8pesJLXb9NKJS6+6YiU\/wDceWKA6d8Ec0qxLA1m0e7oCN2uV3XXKhEsvPzhHGnWoK8UrFNF\/e9UVK\/kdvnMVyC4Ld02TaWvHSMuejaVEhcJSpX556Texm66nP\/LCtlTzhKd1+K5euoC8cnCmrJ\/czWHB8tdZsMaPLOgclzogng7hmyRXTauV0JBpXQN+eLZsmtpdvwg84h0blNew3y\/JLo1X1znPq76YKY3DN\/rfp9bKyVXDdcYIeAQcg+2EXfF2F3agcYLTGbz\/6IIbzo+50jh8I+z19M5J0q91dc0W\/+7x+TdEB9A5bJ7WQ4rny6ITRm8cmR33TiCtwrer1afflo5DZ0qRCrWky+j5Cj3uawww8YKXdaA7d5EyMmTutrhv85SW4RsxIB+xaI9CY4kq9WW5M3h07cNfABEPI2uXCVFffuI1HcCH1hNLpXX4RtiESZ5KDdvpJIXrpXVfZ8ICCHooc06p3rybLDr8gk5yBNcRa6V1+Ea0OQ3Xb9ld13MvPPSsArf7OuuUNdw8bxGdUGNrPDfCJV5K6\/CNsCNLIBp0HKQAPmnDSYVJ93VC04ct3KnJ1wDJmTuuaH9p2c5\/FJM65BRhUo3IH8L2WYqTv0QFyZQjn05KYjOO6zRiri6BIOLKq65YyQ\/wDfDhgR01f6CCdYcBrXSN96k3fzxm19V1UqNJZSlUKr8Mm9VX9j+z6YY6Yi2\/w3eeQjll\/cnFun\/6vqc3yswN4zSRXb4iuaRExSLSc3RH2XJ+hSZmizeAp3X4xhELr+BAfOPoHNl4nQXZaahD\/XKyZ24\/+fz8UnWKxZcF0zl8Y0yy3fE8ht+\/oL80q1FSyNDNmmZCEL69vCK+0OMD+KYh0ljfOjZHM3KHJisge+DhJYPlzOqRuo916Osxlw\/gGzGrhgf8hb3T5PdPrLnh5iYHwRPbJ8qJ5UN1P\/W\/ODaM782f9uFbPThn3nEGmk+q1wyYdF\/Dw8MavRGLdsvUTWdk7TnCWOMLPGkdvhmkM3hcePBZDae80RtLyDlwvlv3p152\/NXrXvH4TV4gP8A3wnaLHaiese2S8+8bJ3lopyQOG7lkjyw+8qI+jrcd\/QDfiImKJc69TMg+YdE32NEBbe5l9vmmzepSiVSwY1qHbwRsk\/V89s7Hbkqmxn3M\/T5i8W6FdI6Npx39AN9M1BIV0LLPOP1doe1tcu7xKo07SPk6LbWdYjM01rm3cxQsIRPXnoirHf0A30A2Xm68r+zpvdWBQCAx+BgSsU1ZM1qW7Jul4B3P9d4o3cC3A9bYmkgCQvznbZ8izbs1lJwFsunERrfh7WXrhZVxBXC\/wDdja8bcoSxYJHdmaV2njOyd308Ts3nVFRulZ\/i+vs7WfZ1\/E25OUqut03vqmuZCuTPJhQ1jbvBIxlw+gO9gAeI0XjfknOfIyE3jRnjJDb6TFjbkxseG7kQPtgS4sSH24695vr3FgIfBEVDzI9jw3Fc6sFQ5gyUNvYzz4Cgtw3eC1H6BcFQ3PJXnsZVrP00kdiWQOOym82Mov8C3K+zjZUfs96MdP1N7h54bS\/kFvl0F29G1ldrReezakXvaPN9Jyw0zZyLNtRV25PENdnSOCT03VvIFfDugzVaBJE1kghL7YEsmLVhTjy0DdvxShi\/arZ7v6VvP63Ne9cVCvoDvEAGHrAN3Q855jr\/HnefIeA44GnyHr2D4Dn3txGu75cC1zbJozwyp1rCC3J\/xPmnSuZ7Bt6NQ+A5+LYEFTy3U6NPKJfJInmwPyfkNo284Lra6jeAbKfA4AIRX99OzizUc\/YV908zznYS+OL9UE7C9uG+62g07u3bEhmsmdJGlozt4nhsz+Qi+sRUTFOznfXXr+Bu2EwPKmW17bPM46dakUsA7HnJ+LOUX+GYASbKrIfO3qbeHAbq+5gyEdJud3VelTps+Gqaa8Foc5Bf4Bm5YS9t51HzdRxmbua9hLyII+k5dIx2GzgzxjsdefoJvBud4zNoNni7Ttp7TUFX3NQbprLNloE4IPwP64HNjLT\/BNwBDO2s9YLJM3nhSM05zL+trTlvFk0vSqyqN2gfaahyBx2\/wDVh3HbNQxq85FvCAX4\/+wcbYNbAtWV1NYhevyCA\/wDd26zF+iWTJU0g6jpitfaAL2wEQD+ykQfh5rdY9JVehkpoV3auuWMmP8L1s\/ywZPrufbL+0KiEMWuHbAe9NZ5ZJ615NFRa9zo2V0it8Y1d3soPQ\/0W7Z8jQGX1uOi6W8iN8IzhGWdA5jujdtRO7yEsHZtx0XOyUjuBbIefJtTKmewMZ0bmebjsWCt\/BcgGSLwYI8jomJvIhfPdrVV3Xf7N9Fg31m0sr5Jldk3WLMUL4l481+E5MtDM6glkDW0rFYrllyaj2mqzu60vLNZv8jAHNpXCuTNKjWWVLuJaIAMRRS\/dLsUp1pHab3pq9e82Zd3Xt7YCZG6VYxdq69pHBEQMnrzpiIb\/AN0BDVm4ycZeoXE9txiQGa+rx5tRu3UsThXUaPkcHnF51xEr+gu8ANDbuNlyzI\/ecsFSWHH1R7ThrxxVp1HmIZM1TWJp0HR73SQy\/wTftrHX\/SRr623H4LA0zDywxeUJa9p0gmXMV0D3TA5MYBt+JCe828M3926rfeJ2AxI4kCew4bJYmrAS+LeHajeJ3AuAmwVqOAiWk29hFOskbfMzCQ89J9eZd1YbunurBr8dafoXvSnXKSP3WNWXBzmly8Npm2fPkBpmxfpwmCWOf78UG32Fr0ooRUqtZVdl2caXn664I9QfCmfDwej1WSqvwzXLjYZ3q6DZjyTlXiUrFsRjfyNN0BN8IiP783FIHbFbov5ndQF7HIsAbAHc9kXGRz+CbRvz64dkyult93Q5rbPcGsmBYGymRP6vULldQExiQvM7r3JjJZ2HnADi5BRaMaCu1yxeUzo0qytwhrTSZXWXHplP7NUvYfszr\/FjJT2HnDNaHL9yp+wTnK15et9Cp07a35CpcSgfp7H3LMfEaYCK\/wDfC+83AvGGnwTpR0aDTQN1DPUfB4poRvcf4pTpoj5d3zJXvws6d9rXsxCvSovc4BXCSh7UeMEnyl6zotMsKGj1AlEG87egn+EbYkWznHYbM0PZXqUEbaTNwsk6wkdSuRe+xNyW2i4f8Bt\/YkUSU3cculsLlamgSsbaDpkjZ2s10YoMJIU0eFkc7+gG+kbbBM+\/KyKX7dEI3tK0xIdSq73jddYMtGON9T\/sRvgkrJzN37ebVpGDJ\/JqRu+PAVpoNvXrjSjJr0wRdH+51bqzkZ\/g+9PxW2fPE+gSoxtMdeowrXiPCwOu1WCmtwjdj7s\/OLpGvLi5XvuNxYizoOsgMviOAb9fIiNkMMkifWzdaPnW+BE1oxTGOgG7Wfu+c3UfT0APgXvXFRD6Db2yJfchovtCBRxIU3HfXbzRr\/KWNY3XvamztdW7M5DP4RkxiMCl0YNFAqV46v9qwVtkCcnDhQPnuSmAbsrhOAjnyC3wjBkqBPYEvSfVmXeSOu++TBzPnUC8ZHm88jRzjdW6s5Cf4RkxOkNm304g5kilnfvnNnXdL+bqtdOIinmGpwfIbfCM8ZGw7RGZuvGK\/ufMeKVG1ge5jzf7VgbW38W2LfoNvRETLagd+gJsCpSrLb+66RwqWqSqD525VL2NgCUn87egn+Ea0N+7fsSsOa3bz3951r+QqXFrbJxNB6tGNY9\/oF\/hGADfRAywn0d+QIADnee5nogbWnH3nJs94rOVH+Gafb9Yisw91yx6N5Z7775b7M9wnrXo2kTXHFwTWgycBkLGQn+HbDdvn32wnNmnlCA1Bx8bunuqsoT\/28g5NwDZ28RDneO+6YqG0Ct\/IZUH+TZI1dnAis3lgrH19y19Y8NRCXYL82uFZN9URO6Uz+A4WgE0yNSBxTLcGGuqL0Xn++T1TZVC7WlK5RF79Qpj18KojJvIhfAPXL+6fLsM71ZX8OTJKpgfvkXoVCsvRpUN0zYTbwOMmv3m+HTGr9sWFZbJweFspWSCbZHnoXilXJKesm9RN13rj9Y5nyDnyH3x\/omtqi1aoLfc8+LBkzJpb9w0mVJWBkcF3EnJsg43mOLaq32GAZMiWW+57KLMUKltdbRqawTte8h98B5JZLT7ygjTvNUbDo+99KJPkK1FRw\/k3XiK8N\/6TGH6Eb6Bx5ak3dZs29lvGjrkKlZbu45Y4wPPRdW+twXdyAhiB7+7jl6i3GzuyXVu7IdPVvjoZZPCdpCavP6nbszHpw\/1LX6hybEvEEFnR2U\/d69xYyY\/wDSieeDWw9zee7vudcU7GLA9J3VY1ZOn+WQ5A\/piILV7yM3wHiy3cGrarrXadvXmiHHlxu4I324\/1m9BNM543bF8nrvZNy\/AdLFiweY2SMqFnI3n3xDzlQELN2YlocPtaUjxfVjm7dpTnubFROoZvYObbKytl3\/z+Ur9iEWlUpZicXDlcNk\/rKTVK55eaZQpoprsvLwb2+\/aqIybyGXz\/7vHVsn\/+AE1cUMOx2YbJ3eXc+tHSuXEFKVs4h0zp21Q+OLnQ89yYyVdrvgMTQUz4tKpdOsFmZ5wbfXyvRlK6UA7p2ayKvHFkjh7nVUes5Bf4Zn0eW4016zVas86yt\/eY5Qek37S1UrRibQfGazkAuSvgvQ3yXMRafoFvBpN4b4Yu2KGwTdg565XHrjwslRq11\/Wi7uAyngnrkN\/WfDOBMWHtcfUwso8yYebYkVwEWXIXkvod+muYL9tkedURK\/kKvq\/bceaOS1LGuZeJHmAiY+yKQ7rvPNs6VW3SUebvf1qP86wjRvIbfHO\/zt37hFRq0FayOsBdr31\/jcBoO3CKhu9XqNtSZu9+LK5LcvwI38MXBiZ167brK4uPPK9e8DVn31MgL1WtkeQsVFLX0XudGyv5Eb53P75Oeo3tLIVK5pMKNUvL7E0TZNraMVKxdhkpUbGojJjTXw48s9nz3FgpvcA3Exerj82Xpp3rKWj3HttFpq8bK9UbVZIsOTJpdAHbvQXvsR5r+QW+SWy8d14\/ZUGWe55ePVK2zugl1UrlUxbcMKW7sqDXubFROoZvV2RAf37PNGlbt6w8eO8d8tB9d2pG9Kd2THJeW+V5TkzlM\/j++PQiaVKtmGO\/MvLYlvEK40DiZ+eWyMpxnXSz+hkDm3ueGzP5LOEa0QF9W1WTUgWz697y7EHPrBvh5jwumieLZmYkK7pXHbGSbxKuOSAzYOYG9eq06jdBlj\/yug6O8IRP33pBKjZoI9kdKMdDYQnXbhYexOUnXtNJi1LVG2omaWB845VPZeWpt6TzyLmaKKxVv4nOID2+sOMv+P5K2x2gwwTG6GUHZP2Fj9SOrJfvN32tZk+u1bKHwo5XHbGSn+AbCMQ+bPPExI+uqT3\/vtoWzyOPszp2JDkgz3nVESv5Db6xY7Meo+Th7Hml79TVuoYZm5GJf9Sy\/ZKvRAXJkb+4hlUbfCcu2t2g2ZsVspkMGr54t+ZyeChLTilWsY6MXn5QozG8zo2V\/Ajfc7ZMksIOGLbt21yzm7vbixEqTRh61lyZBK+417mxUnqBbzzarP3efmm19BzVUbLlzqJh\/bkKZJepa0brHuqEpnudGyv5Bb5xxpKQ+9ldU9QJlvH+uyTTg3c7\/y4lT26fqMmO45tz6TaAbwz+8enFMm9oa7nv7t9K1gz3KjQCjwCQ1zkxlc\/gm62xji0doknVgG4Nj2atxLUNut77qgPkhxcP8jw3ZvKZ55t1Jbvm9NFM8SxxwIaaDND5y+Mvzi2V+cPaOP82z7eXCJucuvmczNxxWdYTjqpbwRAa+JWCOYmbSBiG59Y83zeLQffas+\/JiMV7ZNWpN9Wb6NoPWzKJMW3LORkyd5t5vpOQ6\/keNGeLrvlmoiLBjk4bBYQWHHxGek5YlioeW\/+EnQf28+4\/Y70sP\/Gq2o37NmDHr\/Qx4dLtBk3TdbfedcRGfoNvlkAMW7hLlh57Se1GO3TbJLZbdfotadJtRMDGBt+Jym13Cw5ekzI1msgvfvUbueeBjNKk+3Dd0QBbxvO3BfkRvjeeXiqL9kx3fre23rDVGP8+9NwWGbd4iKzDO+txbqyUXuAbjzbr5YHsaWvGSLGyheS3d\/1GGneoK5vPLtftxuIf0u8P+IZZ4Bdyfc0b0loeuOcOyZ7xflk+poN87IzLWVrLMV7nxkbpGL6BG7y0lzeNky6NK0rpgtl1zfLQjnWkfNFcmob+2u4pCettveqIiXwA39iDTejfe2S+vHxghrx5dI56aWm8eMKf3TNVHt82QZPVEc4R1zXzyCfwjV0+PrNIbci2YiyDwLtNeAvPMePGPvNsO6ZbHTgdgFc9sVJah2\/AkNA\/wk9n73xMt4ZhbTJeW0IApzlAzlZZDI6AckA8XgNMlNbhG1vg8SIMepZjP7L3EpoPbC87\/qomr5uy8bSumSebrzt496orVvILfONNJFkddqQ9kogJ25LQiuembDyjbZS9llPDjn6Bb2zDNnfszT93z5N6f2PbVafedp57XKZuOqPbthFJwPPxjGRBfoFvJndoe9y72M21F+1v7t4nHTue1ft7xck39HmdVDP4TlS0s7XOPU0kVd12\/TQfRvb8ge0X6TexocG3hwDC1\/fo+uPN55YrWG+7uEofH391l2w9v0JWHJoryw\/OkS3Ov10o96wrRkov8I2dgWzC+guUyCtVG1SUtn2aSZGyBTWkf8aG8bL3yQ2e58ZKfoFvok1JEJ3Agp3ryjCXBZ2\/T++cLL93eNHr3NgoHcM3oPjEtom6yJ44f8J7AUpCzdmvmuda1iql+1VzrFcdMZEP4Js90h9ZOVw6NSwvVUrmlfb1ysmBhQMUIEd3a6DrlvNkfUi3zdo7r79CpVc9MZMP4JsJjCd3TNIbmxwDDSoVkdUTuuiExYqxnTTTeYEcGaWMY0uSsH2tWyLEN3FdWofvVafe0szcJarWl\/wlK0mjLkNl1q7HZNyqI1K6emMNTc2au5BmP2erGLxA8UzQlNbhmwE6ydQqNmgreYuXlwr1Wuu6byYs2IIoT5EykjFbbilUuop6IZnAiOfkBfIDfAPS41YdlerNu6kdS1VvJH2nrXUg8bK07jdR8peoKA9nzyO5C5MsbPH1pE3xtaMf4Btv7NTNZ3VdMtnNydfA\/skkAewyap5u3fZwjrySq2AJ3UqQ\/dNTw45pHb6xCcDN+vjC5arrFmPtBk\/TXR\/6TlmtOTAy5cgnOfIXk+a9RmuUBrb3qisW8iN8MyHUe8oqTZyYp1g5bX9Nug3Xe5rlERPWHNdJX69zYyU\/wDeeVrYOGzl\/oFSsXVaKlSssjTrUlSX7ZjnQPUeqNawouQrk0HDzWs2rysLd09VD61VXrJRe4Jvw\/RbdGkq+Ynmk+8gOsvXCSp3IWH5orjRoV1vyFM6pW7vF0\/vtF\/gmQhfma1qteAILAuSsA29StbjzWmG5tmuK57mxUTqDb+DFDecl1PfZ3VNl7cSu6uEmRJrnEd5u1nxP7ddUZzzi6nFM4\/BNxm08slVL5pPmNUrIhF6NZECbGpo1vnvTytKhfjlZNLKdA5KdpVuTSlK5RJ44Zwl0lMbhm\/ZE1EB\/x25sKzaiSz0Z16OhA+BFNfqiZc1SMql3Y7XhkPa1JVfmB2T7zF5xXwaRVuGbwSUeMtZ5k7W3cqP2OtAsU6OxNHSgsXjlugrcDNxb9h2v+ys36DhQB5nx9DimZfjG0zV92wWFHJKDET5Zq1VPqegAeNUmnaRc7Ra6xzI2ZA0zxwGY8Q6XTuvwjUcMT2LZWs0Uchp3G6bZ4pn8wZ4kDAPAsWMNZ5BOQsBhC3Zo+\/WqL1ZK6\/DNfUmG+FqtekiBkpWlvnO\/Nu46TIo5AO7ak7XL2JEdDB7MlF3XMKeGHdMyfBMejTeb5JN5ipTVRH+NHUhk4oK\/Jas1lIadBjl2XKR7+rOlYNfR8wOe2zhNZPgRvkcu3qt7zJNwbeK6R3UiksgC1oFXqNdKStdoopEvXufGSn6Ab9YYz1g\/TrLnzSo1m1aR9v1bOH8rS9PO9aVyvXJSu0U1GTStl\/Qa01nKVi+px7AW3KuuWMnP8H3yjb3q8XZD9\/uO76oJ7A5c25wQ1s\/2bXi8h8zoI73Hdnae864rFkqr8O3uMPRXR\/z7WYcBl4\/tKM\/vnZbAgrwOCz7jMCDjc4PvCOAbY75yYKYKkMHLTeh5YvsnswE7Cdni6nFM6\/Dt2GLu0NZSplAObYyEYnx0apFM7NVYcmS6X\/dG1xBpx9YksqtZtoBOYsTXhmkbvgk3Zws7siqundhF2xmzbGRXLJons4a8fH5uqXYAH51aKJ0bVpDGVYvp+vp47vWdVuGbASbh0SRSq1C3lXp0Nl35VCZvOKWQCJDP3\/e0DugJs+w8cp56xlkTHk94TMvwTXh+x2Gz1Cs7af1JTRa0+MiL0sQBHiIG+kxepTbGXkA6GX2b9xytg06v+mKltA7fQAte7sJlq2kisHUXPpCVDvyQ5Zzs5mSVJuQXSF90+AUH0pvrxBBh6V71xUppHb6B6FFL92vyqu5jF8mq029rkjU8tVlyF1RvOLBDaC87GxCtUbxSXV0OEU\/vd1qHb5bWEBpdyoFsdihgzTz38cjFeyRLrgIa3YL9iABimU6dtn01qR39ZLzCpv0F34EtxUhCOXDWJvWAB9bMB7YZY633zO2XpUXvsdft6lVHbOQH+Ab8ajWrKiUqFNGQaLzgJFerXLecZM7xsGw4tUThkW2yxi0eKnmL5JJZmyZ41hUr+Rm+d15dKyuPztdwfd1W7KmN+jf0OCAcG+95Yv1Nr8VSaRW+ccK+tH+6oxka2QzHwHo8f9Oxzjj8iwtLFcRDX4ud0hF8A38kVxvUvpaUd27wgW1ranZuDA4oesEhz6lCno+pfADfeGqb1yypMIjtSK7Glm0NKhfRUH7Xbp+eXaLeXWzNbJJXfTFRGodvspuztKFlrdJyceNYDXGhA2Cj\/6bVS8i6yV31OWyI3TZN7aGZ0D84uUCf86ozFkq78P2lwkvhstXVq6hbiDmDITL4VmvaSSo3bHc9RDqQJGfi2kcUytliJ56esrQM3xsufaxh+ni1V54kydoXCpIMMPHiAuSAN9AI9OCFrN68q4b6e9UXK\/kBvjsNny3l67TQUF\/aV6DNnZDSNRrL0Pnb9bFOGDltkr2VydIN+HjVFyv5Ab5peySzIoQXu9ImmVgrWbWB9Bi3RJ\/jPqft9pq0XPf+Jp+DwfeP4p6duO4Rx2b1ZfCcLZq\/gXuYtfNEBLXuP0lzEXAsfwfO3iT3PviwLDz0rLbR0PpiIb\/AN+0KuOZ3hT6Svo92SrtkYmjR4edk0aHndAJoxSMkWIxvFIZf4LtImQLStFM9XeNNQrATr+2Wdv1aqOebtd+AIWLtd4mKRWTs4iG6bZZXfbGQn+F73JKhUrRsQalYp6xMWDZcDj67WSHbazsx186hz8dSaRW+GW\/3a11dyhbOKYPa1ZSrWycoC3otMcbhBZTH0\/GVruAb42Fc1nFnf\/h+KZY3ixTK9bCM6dZA3jgyW9cxY3hmOeJr5BClefjeJDMHtpBKxfOoxxabBUB7sYbqf3NphR4DlOMR79qkogzvVEfD\/OM2ieEDz\/fx5UN1b\/kTzl8A+y\/X1jvtc5WGvZBxkceExBCZsXBEW11HT0Z5g+8fPd\/lajfX0F7W0ALkDH7m7HlcZu++Gsg+68A3A3Y8aqzFxTMezwFSWoZvPN\/tBk1Vjy1bswUGlZ87\/35VZu0MJLRi0M5Ak+Rrddr0ltqte6mtveqLldI6fG9y2lfvSSt1HS0eRxcaWY88a+flwFIHx46IQXzTHiN1Tfgax75e9cVKaR++P9ds+3izRyzaretnWRqBzdjve8mxl\/SxO4nRfugMyVmwhAKRwfePou2xM0Gp6xMWbHVHrgvaJXZc6MAix+gkhmPjHhOWyr0PZbq+JMfg2xVebdrZiCV7pEzNJlKkfE1dN8+kGTZkOUnGbHl07TwTk0uOvKj3uFddsZJf4LtawwpSoVZpBW3d6soBw41nlsnKI\/MTQqPx1i7eM0NBffKqkQ6kx3Ndsn\/he9DUXvJw1gySp1BOedDhmvI1S2nkALbG9m5Iute58VBahW8cYESTZslwr5TIl9VhwUzKgq87LIiTNsCC8U1wfKPSIXy3qVtGGlYupsnBZg9uKSXyZ5W82TLIhJ6N1PMIAAGOXnXERT6A7yubx0nJ\/Nmkd8uq2lgBaxqq\/nXszAQGWc6PLBks+XNklCWj2nnWFTOl9TXfjq3ePTFPujSqKPUrFVF7EtJCBAG2QxyjuQe2T5L82TNKj2aV9XE8ozDS8ppvQLH35JXycPZ8mnSNUF8AkkETYiDJMWSixWOL55ss1JrV16POWCgtwzcDRZJbkbG3SuOOsuDA0wrkTGL8aMNA2P7guVslW74iamcG8V71xUp+WPPNhE\/RCrV1QD5792MJ3sZgOxKpgUcyc64C0qTbsATvY7yU1uEbG5F1n6iVIhVqObY6oUshAMdgOwJEtFv2ra7qtNtAkiuDb1fYiUiVBp0GSZ5i5WX4ol3qpaXfC7ajwvj2SzopWbxSnYRIIa86oy0\/wDe\/JSMW75b7M2bVfb0DSeryayg\/+TBIvNbC+Te\/LRmz5dYoonhHBfkBvoHrSatGycPOGLvL0Day4\/LqBNjGu82\/8YTvfGytdBnWTnIWyC4Ld03zrCtW8jN8D57WS3IVzCErD8+VaevGauRAxqwPScXaZWTWxkB2cyDc69x4KK3CNw6wJtWKS62yBeXdR+bLnMGtlAXhlXHdGwZ2cHpspY7Fvc6PvdIhfLerV1aaViuhcAjMkHRtVNf6UrFYbgXKWQNbytM7JgtrbvmC8DRa2PmNYsP5dZO7SQXHZroWOSSbOQnFlo3uIMXzZdXU\/QB68OsxVxqHb9oUkxUnV49Q+2HHj04uvOFGx4bsn06EQSXndRJCeIXExFJpFb4RA0VCAdn2JXfhMppFmnDUhNedQSaD+RotuknWPEWk18TlCkA8H1xPLJWW4TswgfGFY7clkrtIGSlRpb6us\/0RZAJ7LXcZNV+BsUrjDjqREc\/JC5TW4Rs7AjMDZ22WgmWqapIrJoKCvbEAZN9paxw7FpQSletreDq2D64n1krr8B2w41cyetlBTQCY27Eje1MH369MaAxfuEvyFisneYqW01wETLAF1xNrpXn4duyIzZigKFu7ud7b07acVdu5x9BeJ6w9ocnschUqJZM2PHo9Uig+kxh+gG8mJ7BfiSr1ZN6+pzQSiGVL3N\/3Z8yiz607\/6FOTrbuP1Gy5yuq27p51RUr+QG+CTM\/8sJ26Ty4jeQrmls6DmylWbmDj2Ff6ta9mkqewrkcAG+bCuuS\/Q3fuQvlkHWPLFLIxnbDZ\/WTMg7j4A1v2K62esLZ3u3Yyzs814PHUmkdvutWKKw5qog+ZYzNbk1sL1ayQIAFieZ1WTC+IJ6O4ZsEV66XEajByIQdVHAMX7pgDhnfo5Fc3jT2ekK2OBrdB\/CNPfDSknCNVPw0zODXAceFI9rJ\/GFtNKt33CMJ0jh8u8JObx+bK7vn9gvMsgW1M9rkocWDNMT\/hb3T9Ni4TgI5SsvwjRhkMvgZu\/KwM8A8f8NAnAEme323GzRN1z6uOfNu3PaxdZWW4Rsx2AamSUTHetvgrXJ4De9P55Fzpd3g6Qre8RqcByutw7crAJvBd58pqxNyELiv0S77TFmlXjMyo8crvDdYaR2+XQGJC5y2NmDmxuvJ1H60FRMWrKFv1XeCttkAUMa3TaZ1+HZF\/0f27SHztsvS46\/c0Oa459mOkfXfJBILTATFz46+gO9Ln+guGc17jdF2pvlDnPsYrzfJ7IBz7nE0evlBTVo3ZdPpG+77WMsP8I3wbrN92PztU9SrHQqA+5\/eJD1GdpDRCwYFEobFMeQc+R2+gez1jy7WcH5sTbTBzitrnNd6a7g\/27iRRX7SihGy4\/Iaz3pipbQO3\/UqFElYOgsL\/unp9ZrdfHS3+ur4wiFLVPTlTeOUGb3qio3SM3xfXZUA1YRS8wX84ID2+fWjZXKfplK3QiFpVr2EAibgE1pfzOQD+EYK4I7NWJscOjmBrfGGM6OkqfxDXo+5fALf7g1P+1K4DrITdmM2Dhu6nUPwufFQWodvBowMihhoalhl0ECdQRDwiDecv6kBPGkdvhF2wjbAY6iNsOv6ix+q\/eLt8XblF\/jWgbja8Uu1W\/BrATt+FLAjoBPHAborv8D3DXZU6PnRVrTPwP3Muvr4eWqD5Rf4TsqOPM8SEwAyYMf49o3+8Hx\/opEB5Lrg3uUexk5sOTZs\/k61Kfcxz5GrgC0Ep2w0+E5MbIlFeLmX55V14GTrxnOr65PjuBUWShfwfdKB7+vPaVi\/Y28mPPCIs5Ub+6nnL5Zb+ozvGrBxUB2xVJqH74oB+HafZ5zt5l+6sGGMw4JNlAXZmQjPeHAdsVU6g2+82MB3s+ol1biJAc23Djji9Z43tLXOggR\/OTGXT+A7Tcsn8J3WlfbhO23LD\/Cd1uUX+E7r8gt8p3X5Bb7TsvwB359K+yGBpH59pq7WJU6hxzCJwZ7qDTsPkZyFSmooeugxsZSf4Dsty9fwPb23husHw3eo8ISzpduwWX1l4JQeBt+OgG92FqrvwDdORK9jYEa83ZccFpzSt6k8t3eq53GxUTqCb0D7f59aK71aVJWezatoRrvEwngD4QfrNHM3+7\/x2Ou4mMjgO3IZfEdFBt+RyeA7chl8R0cG39GRwXfk8gN849kmZ0jtNr11v35yYxC5EnwMy5pqNO8mWfMW0UzobOcW\/HqsZfAdHfkZvkfNHyTlqpeSLedWeL6ONBT99d1y+IVtsu\/pjZ7HxEppFb7xbpOPCiW2LBY+BMBhwS\/OL9VcV17HxUbpCr4dgz+zXhOtAdWJzXakutIRfLvr6VFoWHVMlY7gGxuyvh4b8jee4efpAb4JA2QgRbgvwlsRr7DfdAHf2M+xGWHnhKgGwi\/jF1qZfuDbDQO+bseQUOBYKz3BtxtOnVp2TC\/wrUt23L5Rl+3Ex45+gG\/3d4NtGIct2CGTN5zUvi\/4mNm7H9etLvtMXSMrT73pHB\/fpTnpDb51D\/BXd6mnln\/Hy0PrZ\/g+\/Pw22f34et1D3ev11FZahW\/G1V9cWKbb9wLYXsekrtIRfCPABaOjeELMLSmdwDf2JWTj8a0TdN38F+eX6QyS17FRVzqBb2zIum8SrrEM4pMziwPr6OPUdtMDfOOtWHz4eU0stGD\/M3HNeJ4e4JsBJx4d9g6etvmcrDz5VmASI04D9fQC37Q51o7O2HZB95tf4Qzq47luOb3AN\/Zi3fesHZd1O7Llx1\/VvdbjtW45PcE365rn7nlcxq0+KkuPvaxb5MXDjn6Ab6QA7vR\/mjPEAfHQ193XApOSX8XtXnaVnuAb0N51dZ0mZNt4aqkcvLY5bpm5\/QzfrKV3t2zzej21lVbhG2csHu+4J4MOW+kMvn2hdATf7F+d\/eH7pHKJPDJjQHN55eDM+CSvS0fwzX7g+XNkkCK5M8vQjnXkwobRCuRex0db6QG+2SKmfseBkiFrLilbq5luOcZz8fB+pwv4dgadbEuE\/djiiYzdulVWnLw86QW+GZyzz3yGrLk1M3LjrsN0O6jQUNZYKT3BN+HAGbPl0S3w6rXrJ+NXHb1hm8FYKj3BN8BdoFRlvbfZknHEot2y7sKHnsdGU36B77Su9ATfbD\/Wd0I3efDh+6V8zdIyaGpP2ff0prhApZ\/hO60rrcJ32pfBd\/yVjuD7tcOzZHCHWrJ\/QX+5uHGsXHLEugle8zonakpH8P35uSUOdNeW5WM7yssHZsjhxYPk07OLPY+PttIDfOPp7jN5lTTvNVoWHHhGek9aIbN2XomLlyK9wDew3bDTIN3mafzqo7q1W\/C2ZLFUevJ8LzvxqtRv31+3HQO8Ry7ZG5gI8jg+2kpP8L3i0TcUutkGj7Y5dP4OWf7Ia57HR1vpCb5XnXpLWvQao\/tULz7yvAyatUkWH37B89hoyuA7OkpP8E0m9Onrx0nLHo1k+cE5ui3WyiPzNPzc6\/hoyuA7djL4TqluU\/hmbe1nDvQ8s2uyvHFktnoaCU8gVMHr+KjKZ\/ANIGIvQvmDH2Mzws6\/urRcs8yT4AAbxiVk2ofwjd2ICnDtiA1JCogNv3ZsyL8J20fxCpXxG3zjXQQWA+GCX6lXkT2XV59+W\/\/yeNOVzwNeW4Pvm+SuAdXQU8c+hFMC2YSds586Wzyp\/TRcOvbhqciP8K3tDzs6bZDHhOkT0rv23PuyxoFtwn3ZMxjFawmEH+E7cB+zddt1Ozr3LfsvM6G2+vQ7alO1o9MmQ9fjxkp+hO9QO9I2yeYdsOPbGjUQTzumN\/jGrrpmHvvG4XfFlR\/hOxAmvTvBo81fwPvIi9vl4LNb5MAzm+WYAx0cE6913+kdvl0brzo6Xyc02FeddfVex0ZbfofvgANsqTyxbaK8eXSO\/P46C3odG13dpvD93WMrZcOU7lK3QmHp0ayKrJ3UNT4eW+Qz+AYS3zw2R57YPjEBvJ\/dPVVGda0vY3s0lNNrRmqWea9zYyafwTd246Y+tHiQ\/NGBax6\/dWyuLBjeVoZ3ritbZ\/SKX\/sLkm\/g+zoojlt1RFY8+roOhoDtwXO3SoOOgzQTLZlp4wU6rvwE39hm8ZEXZNL6kwG4dh5P23peGnUZ4miojFp64Dp0x3ddo9\/gG\/usOv2WjFl+0IGZz\/Tx7N1XpUWfcVK\/\/QBtk4BPvO3oN\/jGPhsufaTRFhuvBOy14OA1aT9kutTvMED6TFmt0JgadvQTfGMfJnsGzNygf3lMuHnXMQsdOw7ULN70lfG0Y3qD78VHX5QJa47rcggmL+JlSz\/C9\/FXdsriPTNk26VVCoVA4Nytk6Rlj8bSfUQHWXNsgYKi17mx0u0A35vPrZCSlYtpSL\/a+fjCOE1s+Be+cbb+4cm1snFqd6laMq\/0al5V1kzsoo4wr+Ojq9sUvgGhrTN7SYcG5RWItjn\/JnGYwffNwrM9uU9TWTyqvXq1Pzq9SFrWLCVF8mQObGJfobACuNe5MZOP4Js2RRK1LdN7SrcmleWHq6t1D3rWyBfM+bA0dDrM0gVzyKZpPZzj4juJ4Rf4xrMINFZv1kXm7nlC4YYEYdnzF5PcRcrousaGnQbL8hOvxcWz48ov8M1kBR6wtgOnSIehM9TbverUm1KmZlPJmD2PlKhSX0pUriejFSg\/96wjVvITfBMNQNvrMmq+NOw82IGajzRioHbrXvJwjrxSqnojKVCykgyes1XB3KuOWMlP8A28YJ\/ek1dK5UbtFQ7x0rbqO0Ey5cwvxSrVlRwFSkiviSvU3l51xEp+g2\/syIRPiSr11IYk\/esxfqmuly9ctrrkLlxaOg6frREF8YLGdAPfjr2IZmnWc5RkzVNYKjZoIx2GObaM0+SaH+F7zfEF0qBtLVm4c5qCN1BY0AGbAsWd35mKRaROy+qy8fRSz3NjpdsBvsmIXrZaSek8uI3M2TxRZm4cLwee3RxzAPe755tI0+2zekvLWqWUBXc4\/35y26Q4RPDepvBN+C8AxLZkeG0JmyaM2uD7Zn1wcoG0qVNG9i8YoCHTu2b3lVyZH5ATK4bJywdnyuD2tWVir8bx9dr6CL65iWlfHRuUl0Uj2sq3V1bK0zsmS4NKRWRS7yby6qGZsm5yN6lZpoCGoMdl6cN1+QW+Gez0nLBME6stPPisDjKbOgMiEoSRLGz0sgNStEJtmbntknpvveqIhXwD31e\/VK931SadZNCcLTqgHDx3mya14jHrapt0GyGNuwx1wPwjzzpiJT\/BtxtxUalBW+kxYaljx\/dk7MojDuCUUSCnbRKFUal+W1l\/PvaJrYLlN\/gGEivWb6Oe7rXXs+0XrVhbmvYYpRNsACSTarTVeEEj8ht8Ex1Qr0N\/BxBH6\/KRefuekgr1Wkv15l1lxvZL0m\/6Onk4e159LV6RQekFvplsw75MWJav29Jpo+el16TlMnnjqbjY0o\/wPX3dWKndvKqGQB9\/ZZd6YbPkzKTe8Pk7pkj5mqUUDE+96X1+LHQ7rPlmomPvkxs0tJ9tyUhwFxz+Hyv5P+x8k47PCT3HKYvXGyeYuzw0drpN4RtQxLiAkau4waPP4Pu9R+ZL46rF5OCigRqi0b91DalSIq+G7jN5sXp8ZwfAa2nDZdN6rzqiLh\/Cd6MqxWTF2I56k6+\/Dttn147USaA3jsyRUgWzy\/uPzo\/rJIaf4LvziLnSoNNADS9feuwVB7zLqveRgfvyR1+X0jUay+jlB+LqcfQLfLNeceHB56R8nRYydEEgeRXe2iLla8rKU28p4DBIJ7Jg5ck3PeuIlfwF31\/qxE\/Jqg2kz9TVugQCby0extm7riqYj19zTIpXrqvJ17zqiJX8Bd+BSQzs1HnUPE2wxuRawdJVZMyKQ46NP9TM8US2MGlk8J241l\/8WKo17SytB0zSe3fE4j0afdFv2lptq4sOPyf3PpRJQ\/rdNeGxlj\/hO5BHJHhNNxO59I3YkWghflvcnCM3nhsb+RG+J60cKTWbVFH4PvTcFslbJLdUb1TJgcEdsvOxNVK3VXUZt3hI3NYko9sBvoFs1tC76+gD8j42mkoPCdcYo7v5mBh\/qzyOi65uU\/hOVfkMvklM17tlVenbqpqsndhFyhfNJbMHtdQZoq8uLpfJvZvIpD5N4rufns\/CzrHVjAEtpF6FQrJ5ag9pXqOk2vOdE\/N0QoMM57XKFZBvL69wjveuJxbyC3yTLGjE4r0KPd3HLZYmPUZKltwFdaCOZ2Lm9ksa8jt96wXzfHsIaGTf6Tpt++iWQ51GzJFchUpJ+6Ez1QNJRm48to06D1Uo8qojVvJV2LkzOCcJGNuIlavdXLqNXSQFy1SVJt2GK0DyGlvd4Rlfe+4DzzpiJb95vplQa9VvghQpV0N6T16h92\/15t1k4aHn1I5kOC9YumrAY2vwnaiwI1EXeYqWlf4z1mkYf5kaTWT2rsfUjuQmIASdBHbm+U5cAPbEdY9oewPCecxuBc16jZYe45doREG8l+T4Eb6X7J0pFWuXkV5jOqnuz3CvjF8yVPf0Xv\/oYqnWqKLM2jg+5h7ZYN0O8J1aSg\/wnToy+I6\/fAbfgOOp1SOkYeWiUjRPZmlXr6y8dmiWJl776NQi6dW8iuyd39\/z3JjJZwnXmFFjP2\/WlZTIn9UB7YJyZMlg+fMz6zViYGC7mjJ3aOs4JXr4UX6BbwbfrK0lqVXOgiUlW76igTW3Djgy+MRry1ZZS46+pJ4JrzpiIb\/At5uwjskKvLTYj0iBeXuf1OeXHHlR6rbrK4Nmb45r5ADyW8I1BuYztl1Ury12LFaxjkxa\/6jakTXgddr0lh7jlmi79Do\/VvITfCNAkARWpR1QzJa3qBQqU1WGOcCtdnTua+xIjgKSiHmdHyv5Db6JIlh6\/BWpUL+1Y8cikq94Bek1cZnakYnJ5r3GSOOuQxXE4zWJ4Uf4ZvlSqWoNZc7uJ7QPHL\/6mEZesLSJiY1arXrI8jhHs\/gRvg9c2yyDpvaSImUKSO6COaRh+zqy\/5nA2uM5WyZKg7a1ZfWxBZ7nxkoG37GTwXdKlY7hG48j3tiPTy9SDy3\/\/osDO2wtBiw+smKYfHJmcUKogVcdtyLqJ5M14QteryfIh\/CNzS5vGifHlw3Vf+uaCMdmhEyzv\/cX55d6nhss9\/sAOFGo3Qnz4DmgnteT9KT7yvO9Sa+HRHVP75gkR5cOkSe3T7y+vnujvnZ27SidyODaveoIVrANOT607fLY3bIs9LVQ+QW+8dwC33P2PC4jFu3R0EpCfhnAA9tz9jyhilZSIerUEMNkPEV+gW83URghqAwqhy\/clZC4DhsSWjl5wykNQY9Gwjrej2gF3fLN4\/Vg+SvhWmASg+zHkzaclGGOHVlXCyy61zx+zXEN64\/GJJD7fiQcTG6LI1\/Bt17XFwqNU7eck2ELdsqUTadl3fnA+m6umb3mlx5\/2bFj8m0oOQXq\/ELrTa5\/8Bt8c4\/RF9IOsSMQSV9JGLWbqJLQfb0Xk7n2cEQ9tPOk7OhH+CbHQLWmXRxbvai\/I2TcJ+fAhDUnNKEdURhEE2BXr\/NjIT\/CN2uO1z6yyAHtSTJzwzhNBEaIOfC97eIq3eP78AvbPM8NFsc\/8voeOfHqrsD5b9wYRs3rhFjzGsc86rwefH6w0gt8c72HntsqW86v0MfYZ99TG3Wd\/filQ2Xdo4t1nX3oeSlRsH2JWvA6BvkFvhkvs4SWnEvuuPvtY3Nlz7x+cnLVCPnYYUG2S\/Y691YEx1A\/HMh7wDRex6Vr+OaiPzy1UOYOaSUXN4zRjNPfXl6pnttCuTJJucI5Zc7gVvK5A46JGyh8sVfz7rn95KmdkzxfT5APw86HdKgtO2f38Xw9HAGgNOwX9k2TvfP6y+HFg3VPPZ5zAdGFRtaWb57eU\/8dWk+C\/BZ2\/tRamdyniUzt10wnM1KyngQbMuGBBx2A3ze\/v1zbNUUnlHjePY62fGbNCJnQq3HSExiO\/ALfDJoZWLKtmG73EmPv9vJHXtfwYdaXe73uyi\/wDVADhIRL95u2LubebQb9QED\/6es9Xw+WH8POm3QfrjkIYu3d5nubsf2ihhWHA41+CzsnpLd5r7HXvduxgxq+NybuWJ+f3ISa3+B7k2PHjsNnSb32\/dXTnVw7iUTUTZ9IREJSfbAf4bvbmEWakJLfF5aQEEXQqPMQvU6eIxnglE2nYmrfUPkRvhftmSGNO9bV\/aa9Xg9HgN+JV3fLkn2zZMLSYTJ780SFeCCQ1zgG2N51dZ0Mn91PFu6anuQa8vQC32zRNnH5COk6rK2CMZMYfcZ1lTyFckqegjmkaoMKsvzA7AQbpVRMclA\/kyiDpvXS7eO8jkN+gW\/AmzH41a0TFIy\/vrhcOjeqIAVyPiwVi+WWmQNbqDPW69xbEeP97xzAZynp1a3jdXzudVy6hm9mHc6sHSkD29XSPapJenVg4UDJlz2DLB3dQTZP6yFt65aV8+tHJwl6GBOgCYhF+d561\/ly+7SspmnrvepJkM\/gm2zn1cvkl2n9m6stbnVNMmDId8H+eTRyJj6K5M4sNZw6WUP+5YVl6sHFvnjS+7aqLt2aVtJwbK\/6VD5c892+fjlNuva9c40853VsUiLagC3dWtQsKYVzZ3Ls+LCULZxTRnetL+8\/skDtR73YkuzzZKTH7l51ufLNmu8rn2soJYmEZm6\/rDDudVxywjup3vJkRPZvtuHCi+lVjys\/wTch+SWr1Ndtc0ge5HVccmLgGY79qJ9EWtWadHbOS3qw6j\/4\/lhD9klyldL18eHakUmSgbM26lIBHnvV5cp38H3pE6lQt5UUr1RX19emBGrCtSP9xYglezW7f3LRGH6DbyYx6rXvpzkciGDher2OS1LY0ekbQ+12kxwQJaEgYJrUBJ4f4XvU0v2a8I8tK6s0ai8ZsuaWMSsPaxtjWUmhstXM8x2Gpq0dI\/mK5lZgTgkE4uE+6kBJm95NJXehHJI9TxbJWSC7VKhVWus88sL2gEf29d2yygF81pcPndknGUBMH\/CNV7tBm1rSe2xnte0yB7SLli2otlq4a5rUaVFNWvdqmqTdeQ0bY8NE9foezZjOd1m6SnHH5olHKvgFvs+uGyVdGleSp3ZM0nExzsT8OTLKmgldNAFyk6rF5fLmcYnyjevRTo4DgW2iXEd2qSfrp3RLYvvgdAzfhIATUkAm7hf2TtPQc7bMql+piHx+bolqQNuasnV6z0RBD2N\/dGqhvHJwprxywJHz99VEdHr1SP0CNzgG96orQT6D7y8uLFXPd7cmleTj04vVi+uGNbtKKtQeGGQP9crF81zPmj5IIwSYdQLE5w5prWHr1EP2dJ5vV7+sQqpXfSofer7Z55u90Z932iI3ZLD96Aw022ISUP7WsbnSuWEFqVYqn6x2Ogxm1sb1aCh5sj7k2KyivHN8ntaDhnasIxnvv0vr9qrLlZ8834RFFyhVRfrPXK+DdQZ\/QLnKeZ1BNQPExEIrGaQvOvK8esAStPcJTw1dsFPylagoY5Yf8qzLlZ\/ge9Wpt6VJ9xFSoV4rTWoVsN+PNsRbzXFJQdCq02\/J3H1PBtnQ237Tt1\/UNfnlHbhKDqr86PnuMGyWJlqb61zrzXb8XCElqetec+49mbf\/qWTtOHPnZWk7cKrkKVI22WgPP3q+e09ZpcnAZu64pI+97Zg4TBLuP\/\/A00F2dORhx1kONBE9cM8DGbVur7pc+dHzTVj0vQ8+LFM3n9H26WlH+kaP8xHHkw09OTvOdp4nIuiBh7Pp5IlXXciP8E3SyTYDJstDWXLKXfc9KC37TtDfGX5POo+cK1WbdpZlx1\/xPDdFcupNrm\/0I3yT5by0Mw4eMKVHYNsrB4oJCw8WgOd1LsK7O3nlSLnn\/rsVNKeuGS1DpveWkpWKSs782RwgHKt1spUW8FmqcjEZMLmHArtXfSi9wDfXXLJSMRmzYLDaceCUnrqunjX0R17cLhNXjJTK9co5\/\/aGZaCbsPVNZ5fLukcWawK89SeX3CTC19ccX+jU30MKly6gWeu96kN+gW+2Su7auKK8uG+6\/P7x1dKkWnGpU76QOmXff3SBcsc+hxcTYxmiSFnCDOu9fGBGoiz48v4ZcmH9GK1vxbhO8ocnE3MipnPPN7H8hJlj+BPLh8lD990py0Z3UINjyH6tq8uuuX0TNRDg2KNZZbnrt7+Se+78tTx47x2SwanDS\/fe9Rv55c9\/JmsndfWsK0E+g2\/2P2e2CDt0d4QdgelgEdLhdS4CPFc6jbBuhULaaJnoAD7J7M1ERcn8WWX+sDa65uKri8vSJXwDwZ+eXawe6VplCzg3eX+5umV8gv2e2j5JbZMULF\/ZPE6qlMyrkRXYlGUU2JLQFhK4sY84HQJediZL0hN8s+4Trw5hzDkKFFev6uQNj8rkjSdVUzaekhnbzl\/3\/HhDCgPR4pXqyK9\/e5f85s575M57HpC77n3QU7+54275+S9+JaOXHvCsy5Vf4JuBN3BDojD2Via8ctTSfQn2Q9O2nJXFR57XwbpXHQiAuS9DZvn1HXfJHffcL3fe623DO+6+T37xy19L2ZrN0hd8O9eioHLgmtRu01s94MMW7HDaYrAdz+g2WUwIedWBBs\/ZKhmy5ArY0bFVonZ0bPzLX\/9WkwyG47H1E3xjH5Z3NO0xUicyBs7edMM9DUjO2X1V7e1VB2I9c5bchdSOv70rcTtyr\/\/yN3c4f+93YDXpJRd+g2\/uV7YYazd4uuTIX0z6Tlt9ox03nZaZ2y\/q\/Z\/Yvcg2hLkLl9a+8bd33Zu4HZ3nf\/WbOx3dkWT0jB\/hm0mL1WfelZWn3nT+vq3t0\/0t4bmVJ99I9h4MV5ofwmnX1JdU\/+hH+Aa4p64erVDceWgbWbR7hoaPJ2j\/bNn\/9CbPc9HRl7Zr2HrxCkX0OIAT7XlivbTu2UT3DAfI9z+zSZbun3XbwXe1hpWkZfdGsvrofKnRpLJu47bzyhrntR0yZtFgDT1PLApAJzZWjZJsebI49\/AvnXv6Tp3kuFl3yd0O0\/B6wZL50gV8P7pyuDr\/Di0eJOcdOH7gnjuUO+BElnJ2aFBOX8Oz7XU+Y252KLr7jl8rD8KSXhz4kGMz6ka3LXwzU4HXelSXelKuSE4peD22\/4NHFyi4XNo4Vno2ryKXNo3VL8CzDge+t8\/sLdky3qeh0mO7N9QvbMHwtrIwRON7NpJSBbLJuhTCN1BDR\/qfSIE86p7vZTpJQagzocyE7WPLYM0a1NLzXAQMzhvaWsOu8d66tia8g6RjG6d2lyol8sisgS3l9SOz9SZgwuRW4Ru7BSuiElX43qShKDMGNFcb4qkm3IW1Jq798Ig3rlpc26VXHejc+tHq9T62fKh6yN0EdUxkPLZ5vDSqUlQGtKmh68D5C3wT\/eFVl6tQ+A7HhqkC384gaPSyA7ovNZ6JDNlyy8PZ80qmHPkCyplfM0\/P3\/d0ovDNILXL6AVyf8asGqLZpNsI3V6rvTNobT\/kRjXoOFAezpFX39OrLleh8P273wE\/PyrUJreiqMK3M8BbdfptqdW6l9ouQ9Zcar+HXfs5ypKnsK6JTQq+SdaWv0Ql9XyxxpS1nwz6Q22IB6lEZaffrd08ycElCoXvaNnPVfQTrn0hjboMVds95AD0TXZ0YLBmi+5JQuP0bRd02zzsWL1ZV7WXlx3xeleo21Lba3KJx1z4\/uEH9EPU7OcqmvCtycCc62nZb4J6vrmnM4bYMXPuglLcaUNJ2ZFJkMqNOqgdyzt2YusyLzu2GzRNqjbuoACZVH3o9Cvfylfffq92jLYNUbThm3bRdfRCyZq3SMCO2fLcaEfHvmTtTgq+WeNcr8MA7RuxeYve47zt6Dxmq8K77ntIl1941YXCgW9s+\/332DllbTXa8E2OCiJaSF53U\/SU8zi5fixcUQ9edqIV5u9\/RqMSvI5D8YZvEnhpWPJ1hYJWOFrmAHHluuUka65M8nC2DJLF+ZvNGTsnyAG\/eduneJ576s196sGt0biy1G9TU720biI1Pg\/A3XFgK8mRL5sMn9Nfw9BLVCySYvhmLOMq2sUZQUUdvvF2T1g+XPIXyyP5i+aWvEVyyfilw9RmhIk37lBXOg1qneh3R6j+mmMLpGKdsvKAwzRMcvQY2UF6j+ksfcZ2SRBh7b1Gd5J6rWpIoSjCd9i2jgF8490e0r62MmCxvFmkUvE8yiNwIkuP29UtK49vm+B5LsKRtXtuX8mS4V5lQXiPHYpCOXCBw4esLWep7m0L3wivI4m98LwCiGSZBqhJ9PXkjkm6BvxLBy4Tm+1wQ4bxlhMivWRUe11Mj0ecLy1YfJGdGlZQmPSqK0GJwPfnn38uX331VYSdqVOcOqMJ30QJkOV887SezrX1UG0K0RPbJnqeiwDKHbN6S+3yhXTLsmBvLPYFEDdN6yElCzgdaqc6CqGsxU8JfP\/pT39SG\/7f\/\/1fovAYVokmfDuizV1wbvDEbEhIOknoEpsEQkQfECazdHR7+eHqarUdzwP32JD1Ks2ql9DJixY1S0mG+24NvrEXbe+zzz7TwVBinSTPxx++v1Jv4sBZm6TnxOWOVkgvNOlH9Z26RgEzsfDKQMjwx9Kyzzj1nveevErX7DL4uWFdo6OZOy5rgp2xKw571uUqFL4ZSH7wwQfy7rvvynfffZeiQaWraMM3IbrsW4vtEmwYZL8+U1bLlI2nkxwMAi5sB5U9X1HdM5wkboFw\/xttuM6xaztnsF6hXutkB63B8I29vv76a3nrrbe0P4zEfq6iDt\/O9Y5eflBt5mVHQqnZ0i0pLxkTHONXHZWCpSpLFQcKWY\/vZUdCe\/tMXS15i5XX17zqcuXC97dOu3v++eflk08+iYr9XEUXvoHGL2Xc6qPSa\/JKbzs69+eQ+dt1ssPrfITN2Nu\/dPVGUqZmE5m184qnHWm31HXvQ5mSnFxCp17+Rl5\/6x1tg5Hew16KOnw71zpl0xltd152xL59p63V607sXuS7AASrNu6oE5yAKDYL7Rvdts\/kHTDvVRcKB74Bb35r3n77bb3nvY5JStGG7y4j5+kk7qydrOv2PiYa4vti0ojJInbuSMqO8Ybvow7EHbi2RfY8uSEBem9VOy6v1qRgI+b2lxEOIKv493WNdLT90irPc9ExB0gAyPwOHK17ZNENIepAJeuPOw9uI\/mK5lJ4xDObUvj+29\/+pjakHUY0XvQosYBv9\/qnrRkjnYe0kUkrR+rWboSTA9b9JnXXcHEmMbzOR9Qxa9ME3Qqucae6moHeXQrgikkYvOzUz3HRgG\/sy71Ou03W1jGAbxiN7OarxndWR9gzOycrxzF+ftr5N2vAk9q1ScfZDgsuGNZWtwteMbaTHh\/KgYzhPzi5UAa1q3Ube74dwzLbcdIBvndOzNMQXQwDtADb\/BvxbwzrVQfCoHhop\/Vv5sBNSYUgL1gnKzge3pOrht\/02g1KBL7fe+89OX36tOzatUuefvpp\/XGicwB2bqljcI6NJnxzrQAzEM6abFL1Yw\/C0WlYPJ9UeDPfAxMTeL6b1yihoeYkVvsRHgOJ1nbM7q0Anj97hhTD9\/\/+7\/\/Ks88+K3v37pWTJ0\/K+++\/ryD+j3\/84xZtGD34Rm7SOdogkzfkH8CGRAWw\/oTn\/\/R00tur0b6YUatXsbDMHtRSPj27JKHdut8RM3iE1uTO+qA8eO+dSXrSkZfnm0EntsOGzz33nALl3\/\/+94SojNSAbwaNDFoYqLAOD8\/BmrPvKUwT\/ghE8xqDxURhjzqc19m+qH6H\/uoxm7v3SU9YZ2se1kfP2HbppteCFQrfDNTfeecdOXXqlKxa5fyonTghb775pk4I3epAPprwjaeR62RAzV7U2G716XfUboRb8hx\/AZ3EJi8QrykQOgP6rHkKK9B4QSHvg2en9YDJN70WqlD4xlZXr16V7du3y+7du+XatWsK4t9++622RS9bJaVowjfCBoAMkxnYkQmfdeev29F5jjapoJOMHRUI523VPYSZ+KBthh7Hc2NXHdE92JNa+4xc+P7esdHly5dl3759snXrVnnsscfko48+km+++SZF9nMVbfjmemhv3L8sFwnY8YMf7eg8Hwj9TcKOWkdg\/3qgsdOIOY7Nbg7lpY7JG09LuTotPO0cLDzfL7\/2hhw9elQ2b3YGtk5fyD3t3sNetrkVRRu+3Qkh2h12XO3Ykb9kkF9P3+jYUkHa4z51pXU438VUB+KZxGjRe6xTx3s32ZHHbGlWuWF7PT74tWCFA9\/oyy+\/1N\/rLVu26O8Nk0Y8F869Hm34HrvyiOQvWcm5J7cFbOa0K+warFB7uArY73ONDBo4c6Muj0pM\/aatlY5DZ+p+7MMX7k5T8A2YkVWcbcLGLhoii3ZPl71PbdQw5kCmcW8AC5Ym63KOP\/z8NjnogCFh6GTlJiwaQAYek8pMzmsrDs3Vtcx1W1aXGevH3QDW1H\/gmc3qmc2ZP7tkyPJQiuGb8Qx2fOaZZ7QNnj9\/XictGTP+85\/\/DM9Lm0iJBXxjm1kbx+v3wkQJ0Kxebud7AcCPOXZPyrauOHfyqpG6npvJEWwaegzPLd4zU1p0b5SMbcOHb8aTx48fl\/3798urr76q7Zex5U2MEwP4ZmksuwSRGJtxdwC8AwyCM5bnkhp\/I15nx6zZg1tK02olNHN66DGM9Vk+u2JsR+f9BifBRukYvrloLr5V7dIa458UICYnAJI14nx5gDyPQ4+h\/vcfna9bjoW+doMSgW86UTxmo0aNkmrVqkmfPn0UxD\/++GOFRxpoWCDuvB5N+KaB\/tkBQ8KZSY42rFMd3TKMBvul08iOLhnsgORKz3NdAYeXN42VXi2qapbzT04H9lcPPoYIg30L+iuAA+p4d4Nfv0FJrPlmgMTAvX79+tK0aVOZN2+ePP744\/LHP\/5RbezaMEk7Rhm+ETfuhycXysrxnXVN9uElgxSOAe\/N03solLudgZewN1Eck3o31jB9EreFHo+nmzXg1Urn0zUptwrfFDpDfoz69u0r1atXlxEjRsjhw4d18MkPEvrzn\/+cLEhGE75VzgBn7fn3FerYMqtJt+GauIqB5cS1JzT5FQOkm0IGQ8SgES86XmAS6HgNSgHMhQefVQ9u6GvBCoVvhF1ee+01mTp1qpQpU0batGkjixcvlieeeEJtGG6oZXThO6BNVz7VkOe2g6ZJ7da9ZPbuqwojhFqydzqDzsQGmK54HUgaMGujDsTV5qHHOLDDGkn2zA19LVRea77p83bu3ClNmjSROnXqyLhx4+TYsWP6fLD9krMhijZ8I9rQvH1PScfhsx079lZPoQK5016Izlh3Ibzs3dg7sMf1mQDMhJxDHUw06ZZ3ydQXvOabPvDixYvSu3dvvYcHDhyo9gQib9V+rqIN34h7b+mxl6Tr6AVSt21fGTp\/u2x02ugGxy54vrm\/w7Ej4DlmxUGZuO4R\/R5Cz+ExMMkuBsnV5675fvmVV2TGjBn6W9y6dWtZunSpPPnkkwmTGOHcw16KNnwj7jcmL3pMWKr7U\/eatFw2OPCNXQbN2aJrmJObvEGAIJm9iUigLXudw72vk5ZJ1BcufGM\/+kTAm9\/qhg0byoQJE3TSkgiipNpqtOF72YlXpf3QGVK6RhPpMX6J3tPYIkEbTur96nUubQpbV2vSyYHBnLoM4sFM2a8rR4iyy30PZdYlEGkNvhHrgkm61a5fC01y1rBdHRk1b6BsObdCwQ7PKMCn0BcEYa54HlgDEvFQN+1cP2GbsDUnFsqSvTMVxL3OdUUI9ZRVo3T9ctMuDTzXiO99coP0GNlRsubOLAOn9lSPeegxrpJa8804kHa2YsUKbX8dOnSQ5cuX60QQ45zgMeOtlFjAN97ocjVKSds+zRS2vY4JV0yQTFk9ygHsGZ7wzfdI2P\/ms8s9X3d1K\/DN2JGxZffu3XV8Pnr0aHn00Uf13nYnO3RsDutEGb6PLhsitcsV1OXGXq+HKxxen51donnEcCre9LojHG1kPP8yiajqdA3frLO9sGGM1KtQWLNr46n1Oi4cATnUB8wAUV6QxHOJvXaDEoFvt3HipejXr5\/cd999kiNHDilfvrwMGTJEHnnkEf0h+utf\/6odQqKdgfN8NOGbUIuza0dJw8pFpXnNklK6UHYNQ2eygcZHqPPx5UM9zw0WtiMc48X90xW0Q6MNaKR40VkacGbNSG3Awa\/foCTgG9twMzOTmTVrVsmYMaMULFhQB\/J0sHh2CU93Z9w8S5Thm8kaQlSa1Sih67YRs2d4vxEZ+FdP6Kx28TofaRt06vns3FLN2Og1OeF6wF9wXt8yvVeyM3le8I1NmPlloNmsWTN56KGHJGfOnFKuXDmFoAsXLqh3glBBfrS8BgUoqp5vZ3C5\/uKH0qLPOPUUkkU7d5HSsuTYyzro6ThslmbXVphOxrPFQIkBuusN8hqM81xirwXLC74R8EOIFQPJ+++\/Xx5++GEpXLiwtG\/fXtavX68QhA2T8qRFE77dawZOipSrIUUr1tE1ooSQYgcmIzQM0gFwHnvVESxsg2ct4GX0GISr\/b7yfi1EXvBNu\/r0U2dQum2b2o02mCdPHgXJ6dOnqzeXUMFwvLnRDjunfQHebJFVqGx1yVW4tPSeslLbIbBYqlpD9XCFb8dPr3vVvG1F2w\/HjsHwTf+HbfCAt2jRQh588EHJnj27\/pYMHz5cJzKwb3L3cLCiDd\/YkURW2AuPI2rdf5LCHZNsRSvUlm5jFiYJJ65oawl2dP7tdYzaMZHXguXCt3sPT5w4UX+LM2fOLEWLFpV27drJunXr5I033ki4h0PBMClFG75pQ0zQ4NWnb8Rutdv0kjVn39VJoCqNOmhuBiIKkuvPsA\/tVicwsJXH8bTFxF5zFS58I2z3xRdfaLRQ2bJl9fc6b968Uq9ePZk5c6ZOWnKvh3rDow3fwxfuksJlq8nd92dwADqXrpPPnr94gkh6qJNgHudiCybPRizerRn1i1Wqox70Ucv26aRQsEYt26\/9RaEy1dIkfANdeFTJhA04P\/jwA47ulzyFc2qY95RVo3V\/bQCa8ORgEEOHn9+qWbJLViwiNZtWkYxZH9Ls2YRFj182TLfDou7Q84KlXlyn\/i3nV8jmc8v184QeQ32Ex8\/ZOkn3o+Zx6DGukku4hg25j1evXq1tL0uWLFKkSBHp2LGjRr8wJifazwXEcEqs4BubVm9cWUhMFxySf6vie8bGCd7zRI7hu0jsdXSra77hF8aWjRs31rER9uZ3fdq0aXqv4yT721\/\/T\/71p28c+D7hOW5NiWCYSsVya1I12CJZTktCjOfhScbjXq\/DNtTPeDzx90nH8I2BPndAZXyPRtK9aWX1GhIm\/Ycn12qIAQJUgsMPkhPHATQYVfd0c84NnO99vLcco797Tv7197\/KP\/\/xD\/VqB4vGyc3ODNzPfvYz+a\/\/+i\/51a9+pQOoihUryoIFC+T111\/XzoCwdM65AcajDN+EO7N\/OfvWvXtivnRtUkmOXPfasik93uxJfZqEbUNEaAaTGXxH2DJg08D34L6WZH0vbJF\/fHBZ\/vmX399kPwRYM6jctGmT\/OIXv5D\/+Z\/\/kZ\/+9Kdy9913S65cuaRXr14648bMJvYODqtWO0YRvrkOPNJzB7fSNdvP7JoiC0e01SUK3z22UiccFo9sp9ngv3NAPNy29KPdnL+OHd0lFO5rSU5eOFJbv7RH\/vblG\/IPpy2G2pBOkPDfypUry3\/\/93+rDX\/zm9\/o4IjOcsmSJfLKK6+o54KBPj9ewd6gaMI3AxuSn5EMCO8Y8MNgfcnRF3VQyWus0Z6JJ9YZOHrVEaoAYN+4njE5cA+WDmSdgeiZV76Sr7751hkcfqc2cIVdCDkncuAnP\/mJ2pD7+d5779UfHCDo7NmzCRMZDC5ps679ognfXB8Zkeu26yd12vSRWTsuS8X6bRPgG69P\/Y4DNZogMe\/OTXKun0E4detfx3YBiEx6gJ8gznfsd\/T5r+T9z76Vb0Lsh+gHCZ0GfrAfdrzjjjt0cNSqVSuFc7zhibVBbYfYMWrwHYC8Jt1HSvk6LWXG9ovSoOMgDRvHbkRKELLLkgZC0b3q8NJNdnTaezjAHWjDAbs\/+uJX8uHnN7ZDwvUJpSR6wL2Hf\/3rX+tkRtWqVfW3BA9PUvZzFU345nPT7to4UMge5tO3npcOQ2cqJBIyzTIIkl8VLldDH4fbprDZTXZ0\/u11LKLewLFf6LHo5ItfyhdfB+zIfUk02vjx4\/XexX78veeee3RCl0lxlooBj173sJeiDd\/Ysdu4xQ4clpBpm8\/KgBkbdN9vgJw22XPiMk0CyBKJpGwRrBvsSPty7MJjr2O95AXftCts47bNYGE32ir9YbFixRL6Su51Ji7btm2rkRvuvc7x3333vdP3Ou\/l8f4p0exdV9VWbCvWacTsHzVyji5n6DJqnvahXuci2hLRApyfNU8hrYsJOWwZLO7V+Qee0cnOkYv3JjlJF0v4ZpzDuX\/565\/l2kdX1KsdLJJ44QEn+dkvfvlz\/U5+\/oufaQbsfA7EdB\/RXjY4rxPCjBfV9Yov3jtDKtQsLaPmD9T139nzZNV1yHhPl+ybKaWrFJNZGyckuS45VLoOmfqdOoBB9b5f9\/zqazyfJCAekk9+eF\/+8c9\/KECHjnUQY0DuYyIlM2TIoONuxo7c6zgfhg0bppO+LG30HHeHlFjAN3aevm6MlKlaQiMDDj2\/VQE6WEQueJ2bmLAbExdqw+u2VfsmYc9gecE3NknKzrALThwmg\/lNp1\/lXs+UKZM6ybZu2SwfvfmC\/O9LhxIYzR3bplQfnVokwzrWkf5tasjbxwPLkF0OdMU42uvcxOSOsxPG4df\/eh17s9Kz5\/taIIX8ohHtpECOjJowjXBmtmTq2LCCqmfzqvL0zsCm6151hIpG8NqhWZo4jK2jiPnHq47RvY73EmEJf3r9Ufnqi0\/ls88+VQ9EsFhzQsgV4EMYDJ2AO\/DkB4kOgcFo8+bNNbyawQEdMY1di\/NFRhO+WTdPAi93xqhv6+oOfA9W+CbEfmq\/ZrqXOjNBXJtXHaH65vIKObRokLy0f4Z6z6mPulw7JlfPX52G+6e3zspXn76v9vISA3c8jHPmzJGf\/\/znakduciCcx0xoFCpUSCZNmpQQTojHV2c2owjfTCYA2EQNLB\/TSbPHr57YRTPm4\/V2IwtKFcwuH5xckPSkw3W5QM8yCJLdEeKCDV8\/PNvz+FDxmfj+vriyXj5++Yp88vFHN9mPgQ7t8MCBA5I7d261XWg7ZGCEJ4iBEaBJ+2UwRXuMJnwDPISm4t3G+7DikdfVc0CiKgYvhEEWc+Abz0JSg5lgMaCcse2Cc84hZ6DqDLBXH5Xhi3brAMnr+FAxiFrjDHD3XHpFXnn1NQ01DxZrml5++WUN\/8XjTbsLbYN33nmnTqjRRmmDH374obZDBu9RhW\/nsy469LxUatBGhs7foSHh1Zp21mtnbSMD847DZ0n1Zl1k1am3POsIFYNx1pcSvj\/PsT97Aw+as1nDe72ODxWDegar286\/Lk+98Kq8GmI\/xOTOCy+8IAsXLlR70f6C2+Avf\/lLjQ4aMGCAriXjfmcAFezNjSZ885kB7LK1mipwMxhv1mOUruNkoE077T9jvRSvXFeWP\/KqZx2hor0RRYDXjMkjljuwFnxpMnsKBwA2sM0U98GOsy\/LMy\/caD\/a4EsvvaRr50uUKKF2C72HmUxr2bKlRgpxDvc+cOPaz1W04RswJFFa55EBqOk+dpFm08brjR3Hrjys3kcm2MKB74A9PpPhC3dq4kCiYAjpn7f3Kc\/jUeAefldtzRIJhB1feuVHG3IPP\/XUUxrCj81C72EmJPHYEqLO4Jw+ExAP9tKG2jGa8M3a+Jotu2vUAPcufRi7NQDfLDMhXJo9wBceejZsgMaO9KWsYSacnXt82pbznsd6KRS+6c+4L4kkIGLAtW2waKvc6yy1Y3Iy9PfGvdcHDx58fR3+u3L82U90AtTrM9yquLe5bvokbMd100Zpi3pvX\/pEj\/E611UgmuMtjdAiB8HkDaduOoYJDXKK1GzZQ+3L71DoMa5iBd8uHPG9fPDR+3Ly2iHZfmn1DSIR19bzK2Te9qlSvHxh+clPfxIYi\/6P8504\/\/7Zz38qv7nj11KueinNPM45rO+esGy4erdXH5vvwOBOyZU\/ewJ8bzyzTCrVLSfjlgxN0lMdqo2nl8rUNWNk12NrZeWReTJxxQgF0QRATAbkge+Pvn9Xfvf7QDt0x9mh4vf3xRdfVNDmt5n2F3qvEwEIoOMAY6wDiHsBeKzge9zSYVKlfnm5P8N9UqpKManZtPIN6jO+S9jgjPB8s\/0Y6+x3XF4jMzaO10mTpELNg+UF30A2k2leNkaMLclxxbiRScxQxuFez541s\/RqVVNOLB+q41vyQkUC4G8dnSPzhrbRTOUFc2YMsOB1DkQky8Yx5nVuYmK8zbibJcnXdk2VffMH6Hg+nDF8+vZ8OyBH6nhgm3CDSsVRHqlcIo+umUXsj8xaZEDdq45QMQsDhAKbL+ydpmDfsFKRsM9HgM8HFzdLqeJFpZDT8AoUKHCT8ufPr2GWzATRGP\/f\/\/t\/N4jGyvN0BswU410jbOstB4B++P47+fuXr3q+d0oEEDatXkLWOMAIsPVuVU0OOzYAKLkpgPEx3Rvc0qwRkyJ8L3vm9dP99zo1LK\/PMbnhdXyo\/u\/ZTfLkvoXSoFYVyZcvX6ICGgk9v+uuu9RmoTbkZudGByIJz1yzZo2uSfnU6SD++scf5O9vPeq8X+Seb2bZyEI+rFNdTZS2ekIX3bLum8srFMBXjOuoe3gzARGO55s2RJ2dG1dUiL+2e4pGd7CO3Ov4UHFvvH18rrR2fgjz5s4h+fLm8bQfIlz1gQce0B+hYPshnnPbYenSpTVfwaFDh9Sb9uFHn8jlN76WnU+F6QlNQgyKek5wfrgbttOMxmTZLli6qg5iGCCNdSCyUNlqMnXzWYVJrzpCRZ09xi3RLbMYdDfvNUbX7IU3QA0M9Bt0GiTZcueXXE47o615iQEjM+lM9oTaz\/3B4TUiMjp16qTRGoRfvfX2O\/Lah187A5rI7cegkGusUK+VhvJiv2pNOqvnm8gBQKWhcy2sFyXs16uOUFEnoAiwD5m3XcMsy9RorCDodXyoGHQOdc4rVKqi5MjlbTuEXfB0E7XidQ\/TBhkYMSFZq1YtmTVrlvaFgLsmb\/ruB3kravD9lXpldVurvhPUjsB336mrA+HS597X7a4IAWZCw6uOUFEn55JputfE5TJu5RGpULeVJr\/yOt4V5\/F+bFnG9lKZs+WSnInYMVu2bBrixyAy2H6INujew8WLF5ehQ4dqQhwSYTEYZYDpTgZFE76Bxor1W+v9hx27jXHge9BUhWHs0WX0fMlbvLwmBgwPvr\/SOis3aKsQz5722JQ25nU84h4m2gPPMKHGKHN2p82F2I97mN8IbBRqv+DfEeyMl5bfEUCcJU5MpgWDeNTh27l\/sSFZ87Ej4dPcx0AgdmSSiC3ICPEPt2\/TOtv10+0YFx56TvNDMPnpffzN8oJvvNqAC78pwbYNFTYkOsirrXKvM2FEFGCdunWl9+hZuo\/54sOB34HAxGnK+ksmYth3fvTyA9J28FS9v5nMoE4iXMiCTnvxOjdBTjvFxvwuMcnpNYFGWwbAf1z6lPh3Eiv4xsHAfU2oLxMd2XJmlUzZM3oqQ+YH5d4H7pGf\/uzm7+O\/\/pu273wnv\/qFZM2VWZp1aaAC1knaRqK1nPmyyaqjCxTE2ee7VJXiMm3tmFsCRMCb5GuA99DpvaV8rdLqmQ\/fO3tIPvj2bdm2fauGk4eOcVxhC8bdLDEhQoi+MfSaaZf8XjOu7Ny5s0ZmMUHHbw1RlC6IxwK+8Wq37NFYipR1uKFEXs30Xrh0\/hvUpk\/TW7It6\/OJbhg8rbcs2TtDGrStpd9TuB50L\/hm8pvfEi8bu8LO\/LbzuxQ6tqRP\/W+nbf3caXO\/\/fUvdGw8vX8zXUaMs45kzLfi8ETkQmpfv6zyX4WiuZQFXQ5UOe9xZfM4z3MT02EHvLs54+5ndzu\/WxO7StNqxTWB8m0P30AMicK+u0x26WUJ+vri8gR948AOQB2esQLrllloP6BtTTU4ocN1yxcK23OOgNQ3T6+Vu+\/8rXMjBzwRiSl0sBksXgs00sDsHB0Cg8\/169bKxy+c9XzvlOiLC0tlaMc6moH8zNpR0qZuGdk6o6e8uG+abqtGQ2arMK9zExPg16ZOGdkxu4+cWD5M2tcr69xUczTc3Ov4UP3l2ka5unuuFMmf8yabhcq1k5cNkWtDxCCKiY8hgwfJM49fkj+9csTz\/W9FtC3a2PrJ3XR\/wW0ze8nkvk1VrN0+tHiglCmUXZdH\/OHJ8KIHmAFkzTcTGLRBMvAzc3dw0UDP40PFZBF7qrP9W7CtvBSO\/Vwb0g6BICI21m\/YJAcvvyLbnwg\/lDsxMTDCg1O4XHVnUDRexq06InmLlZNpW85pYpyqTToq8ODdBQq96ggVHg1AlERPi5wBJgNNsvgm591ALjzUbtNbfvbzX9xks2AlZz\/k2g\/x446XcvyEiXLs3BOy62qYYeBJiMEe3pzGDmiUrFJfk9aVqdlUBs3eLHN2X5VuYxdKwdJVdKCe7ADzujR8cv\/Tju07yeA5W2XgrM1SwqmbgafX8aHifQbN3qTbFgXby0vJ2dB9nWNpgwzgGRjhDX\/3\/Q\/krU++j1LYeWDSBbjLX6KCDJi5QT1YXUbNl9m7HnNssEHX3RJCTfvyqiNUtDeiBSo3bCc9xi+V0csO6nfj5TULFu0c71wh53v7H6ff+q8QmwXrVu2H14ffEhIPMbBUgIwyfGPHHhOWaYgukxdMfjXrOVon14bOcwbtBUtoYkVAMBygoo3jtaxYr7Xujz518zkH7tto2\/Q6HnEP4yX+1W\/vVPu5CrUfSsp+yLUf4neEqCqWlly5ckU9bS4wRRu+mWwc6NzHD2XOIb0mLtO2yD7z2HHk4j06Kcle8lxrWFE9zncDyNZx+rZGXYbpFmTVm3fVcGrP4z0UCt9MPpCzhgkM+rdgu4bqVuxMu7\/\/4axStWknXUtNH0fb8vpMyYmkky2d35aCZapKmRpNNCcGEVX0c20GTJIqjTsmG43iSgHbsXXSn8V5LZnPGkv45p7Gw5tgdwd2POXYO5zvhGOpB0gnTL1Oyxoyff1YyZIzk8zdNllWHJoj7fo1lxIVi8qyA7M9QS4xEWLNWuflB+fI4Km9pGz1krq23A09T07A93tfvylr167RCTT6OPe6vRRuG6QeJn4BTXJD4LghpBoAjwV8A9WEmrPf+f6nNwb+hogJD69zExOTGFXqO79lk3toFnX29l60Z4bnOnsvecE3kT9MTtAPhto2VEnZWtuV2jowyXP\/3b9VDmGcS+QxS1W9xrdeggW\/vbxCuc+LBRHjdK9zExOfgzE4W5WxhVmjKkV1YgDnmNfxNyodw7crkli9emiWhgcAPj88tsr5ItbJh6cWargAIHLL8N2mhgPfgezfdcoXvDX4dsDp7TPr5L577pJf\/fKXevN6CW8EjTexxul2ABzLTDDrcPmxP3TwoLx\/jXBp7\/e\/VXHNzAgByzXLFJD8OTJK4yrFpJ0DzGxYP75HQ02k5nVuYkqA71l9NFmbC9\/hh\/878L1nnpQolOcmuwULG\/JjTyfpZUOEDTmGTpmoA9bar1q5Qp587IL8+dWjzvtF5vlGzNJ9fm6J9G5RVUoXzCGlCmSXqiXz6Y3L5EWH+uXkjSNztC16nR+qAHyvUm868M2e9dR1cGG48L3Beb\/ZUrdiEcdOP7vJbsEKpx3yuuuRYNBOFstdu\/fKgYsvyY4nwxjwJSN3YM0AMFfhUlKkQi15MFM2HVyz1pskYngawh5gOiLUt9vohVLHgW+8O4ApABQ2fF\/6WMH9l7\/+jdroZx62c+3nDji97Idonxz329\/+VkqWLCndunWTVavXyJEzj8nOaMC383nxtEzZdFpDffEoZsiaW0o5\/8bLik3ZWm3Z8VfDnry4Gb43SYnK9dQL5XV8qALwvVky5cgbsN\/PkrYfNkquDTIBSaQGmZNJ1kTW5LffeS9qnu+AZ4s9kZ9Wry1J\/zLnKqAhpkQV5ChQTGq1cgYxh8OfBOK4tWeD4fuADv6ThW\/nc+AVZs00E0A\/VRt62xH7uQMhL\/shdyCJ15H14HjAWdZEGCZh6NGEb8TnX3HyDY2cyOGANnvv5ytRQfeGx65EF2Bn2pnX+aGij2BJQEXne1D43nTW+TfwvcXzeMQ9TMTHb++6R37yU6efcxSwI+3uR\/sFt0Ev2yH3d4R72E3WtGzZMl12QqilC0zRhm88p0zC4KnOlq+ITv5gT\/pGJohK12isE0Ma3pwM7KmcY36E76H6HQDvnUdEBt\/kWCGChXvUtauX3L4yqXudY35BxFq2XLo1WrvB02TcqqPq7U8pfHPfabLEGet1ApG99QNZ3b\/WtdnkGJnl2DEsG14XbZx+l798T\/ylnXod66VYwzcRk9j8Zw4wA81eIsT8fxzwSfz7cNr+\/wSg+w4Hjgo545rqjStJgeJ5pGCJvHLvA3dL1YYVpULtMpo9fejMPro3tRfIJSbComs2qezA9+wE+AZCbwW+33fge936dTqxyFgltN0Fy+0rva6Z53iNPgHvOBPlPXv2lA0bNuhWWuQRiiV8s\/adTO\/ztk2W8UuHyYZTS+T4K7vUU73q6PwktwXz0pEXgO\/yMmBSAL7rAt\/O30jgm7bFOvnk7IwNk\/1dd9rWL3\/+U8ny0L2a9HlK36YaLcsa7lvxfgPqwPVrh2fpck0cf99cWqHOUHJXvXtiXorgu4Mz7sb5pfDtfD4iWcMLj0\/n8M0MxKk1I3S2pIrTEbD2GyMTskvIM\/AMgIc7gxIN+OaLee\/CJunZrYsDeu11zWyoCF0joRBbFRHO5jZO98Z3f+jx8HTp0kXX6127dk1Dif7z739JtLca+8OTazULORm6uzSu6NizjHrDt8\/srWHpt5qoIFL4ZgLj+aPLZeSQfgrLiQlbsjae8P3gG9y1Izc+nXGNGjV0ayh3b3AS4f3n73+O6lZjLvASvt+reRVtk\/1aVZdV4zrJKwdm6uvhrpmPFL75vljLP6ZHE+nQsrFjq\/Y32c4VW2UxmKS9hdoP8UPFpAXbR5DJm3BLPD3ffv9DVLcaYxC04tE3FLIJsyxbu7lUatBWvRWsD9Uw31sYGEUC37wPns0OQ2dI7abcq611OyIvsZyB7YpI3BJsv+A2SFg60QKzZ8\/WQSrhqt859nsryluNMaieuvmMJraq2KCNRgvUbd9P+k5bq8B4KwPXSOGbQSkRDA3a9pRmLVpLKw\/bIfpBsu4zk+51DyN+5Fl3CzCyjoyQaWbfCXeNxVZjrKXFs9hp+Gyp3Ki92pEM02z1hKcwvPDegFIO34Gwc\/IglHeAs3qDlo4dW3najz4Q7wx28rIf9zBhgCx7IGT60qVLmjMjNFw6mvCNyEVAG2K9NzkIyjn3dI0W3TXEmW3Bwp3AQCmBb41+cd6bBHl8h6h6w5bSMuR+Zk08SeuI6gm2X\/A9zGt169bVbPxkk2cds9e672jDN6LPWnz0Rek9eaXaDztiT\/I4kMwukIQyzHvb6QOiDd\/ch2fOnFFIYWwTbNtg0VbpBxm4Y1cvOzO5QaKmocOGyeTlO2T+vqfCXmqUlIiCqtasS0IeEWCbXBb0idO3XpB8JSo69+TJW+ojmfQgrwZ5DKY538PYFYfDnkxCsYRvJtRWrFgu7dq3k\/rNakv1RpVCVFGqOQLM8hbJpQB+c9v\/L33+oUwPaAZutvwi4RpZymdsGCdt+zrt0AFvwLn9gBYyff049c6S0CsU4pJSNOD7g2\/ekq3bturENhNjXmMdcrMgxoP8XnONoW2QvhInA+2UXC3u5Fro9xAL+MZue55YL+0cuxYtW0jyOd\/LyHkD1duNajStLAt2OOPYWwg7jwV80zbZqjYxOyPszNiIUH9sGty29F539FPn+aJ5s8jAtjWVu4gUZUterzFtcoItzq4bpbBcjRD93Jk0fxfPA9GTejdRlvE6NzEZfCciYOb1w7M0U\/eYbvXlkZXDpGDOhxXyAkmuRqrH8fz60WHPeEQDvv\/mGP2Pr56QTz\/+QD768ENdVxcsEraQvIpBJAMmd2aIBsngibWPDRo0SNh3lOQFzLaR5ODfbBnlfJHRhG9sw\/7UzA59dWm5Qht7nX\/qPGbDeV4jq7zXuYkpUvjGhn94\/ZR89uHbOkgMFXYEokmK0bVrV52h5MZ2O08eE17OYP3IkSNqbyYuErZxc+wYTfgGdrERtvvm8gqNFMCGRF\/w+MsLy\/S1cK8\/UvhmQoV74KPzq+WDF5yB9gfv32RD2iHJ\/Nijmkketx3yl3ZIoiY8jLRDtjQK3Xrnux9+F9WtxtY5A5glx17UJGdk5waY8VCQrIl9bBl8quc7TPCJCL4dcdyKR16TXedflBdfekXXGAeLcF0SCOF9JSqFmV63DTLjyyCSdfJjx47VNoiHkR9xDfF1Bu3fO\/aL5lZjDFBJAobtWP+J7Qi35zFhz6wXJfQyXp5vvifgcfPpl+WJZ1927HWzDbEJk4psvYi93EEQbdBNwMT9zeQjSbFor2RDdtsgg4BYbDW24tHXdH9qPI6spVc7Hn9Fr4dkdktPvBL2IDul8M1nwZu59NjLOnGy7fQL8tRzN9qRZGvkX8ADC1zT9wXfw2Q9ZxC5aNEizYoOMOo6eTzdTht0bYiiDd9cN7ZacvQFXecN9GBHrodtslbRRp17OqmEVMFKCXxzD9N\/BL7D51XbHTs+\/+LLaj\/3HiZ0HPh2Jy\/ce5hoKSJVgnNd0HdyDyeW9Tza8M01rDr9lrYB7mPsR3+GPQOJw95yHj+rAB4WODrHRBu+EX0bv8ckVnPbZ7C418l1gS2D73UmffGW4zXv0aOHrrHlXn\/HuddPPPeZ870nvyVkOCLfAv0XO2mw1CG\/A9t4vmmnI5ful9xFysisHVecY8N\/L5bxsMME3wVRW3Xb9b2+jML7+FDFCr7xzJJ1mr7y3fffkUeePihbL6y8QQD0prPLZNisvrr2mzavXm4HuNXLfddv1ZPda0xnWbp\/lp4DEOPVJlHbvqc36lZgW8+vlG0XV6q3FvDmuMPP31podDTg++Pv35Uvv\/pS22HoWMcVCTuZJGIbLO7v4HudbNy6HGz8eM1fwLHc38E75QSXWMA3QDxwcg\/d65t18GwFN2RGH7UnHm\/WxbfudWtrvmMB37BIYnZ2OYffJiYqmVQPtK1A9Bq\/61mde71j2xayefYgubZrijpIiWAmMjQ8sL1Zrx6aqY7Dib0a617fBRwWZOksnHh69QiN5r28aVzYDjBk8J2IgEbADlB+bPN43TKrRIFs8vaxufoa2e+6NKoo22f2Uk+4Vx2h4jwMPqhdLXl+7zRNdlW\/YuFbgu\/E9vmmcAPTcPF81a5dW294bnw3mQuZPknRj1fHDW+5qTjPRQrfNEAAjUbE\/tQ0WNZ18zhYJA\/DA07D86onMQGeZBvcPbevPLJimAOO5eSd4yRcC9OOSezzjU2Y2WXtDaGnhFEyaELYU9fFr1+vHQA\/YHSeNxXnZohGtnNsSGgMoLtsdAcZ3a2+ruvmOeznvgZA921VLfw13069JHbo1KiCJm4jSyNbwJEM0Ov4xOS1zzcFG5LFkx8ZvAy0P+zHIAjgYYDEjxQZK\/kB9\/LwRCfbeWDtHOCIdxuPN0m+dCDpDLYRr41yBkckV1pw4Jmw4RGvV\/exizVcE2AkcRZ1hAvfiMGR1z7fOvngACBtDDhkMAl8Y0OS\/+HhIaSXSR\/2sOXY4PMRA65owLdCmgOCQEbLvhN0XSjX7tqP14goYH0tmafx+njVEyq8lmSer960swyZu00BvFS1RrLEARmv4xOT1z7f2A\/Rtpj8efjhhxNC1QCeUqVKaZQAa+ywMbDjBTooWvDtgjeTNm0HTdXoATIgu3YMvPapbjVGW+LfXvWEivZGYiz2Y+45Ybl6x8rVbqEZu72OT0zB+3xz3dgDu3APV6pUSe9h7MdfQvNZ70mkjzth4XUPByta8K12dK4Z+3QcMUfDvgESPPlqx+uvYeMazbteh5XkgYd+AmisVL+NrsnHW0lUAm3T6\/jE5O7zjf0AaLL2cg\/z2+HewySgxGsDCIbu8pCcogXf2BF7cb\/i8SZ8n8lH2mHAjoHXuo9brKHn4S\/J+XFJDROSC5z+1s1r4H38zfKC76SEnWmD7J+OV5Exj9tWabtklwbQGbwzMRToH6K7zze5Qwg1J2v8suMvS54iZWXmjssyb\/\/TmsyuWMU6OmHpdW5iwptOVAW\/WW0GTNF7XHd48DjWS7GC7x+LM94M2ecbAW\/HHfhaum+mFCtXSH7+i58rcLPV2H0P3iMN29cW9tfe\/fg6XTPsbk0FDJM1m6RrgPKjzuMfFdhqrE6L6vo3+P2S09TVo6V282qy8vBcGTK9t5SrWdqBxm1hQybwndQ+34x3yP7OfTxo0CD1etMGudf5veFeZ8cIfqvZaswLtkNLLOCbpHVVWZ89qbuGmXcb3l6Gzuir69\/ZZqy\/8zzZ5PlOvM73ElvFVWtUSQZN7SWL98yQ+m1qyuK9MyNKuJZUccfmhw8f1mTR2Jd7nbFl4cKFdcx+7doz8u0nb8sfXz6kY2ivseutChbsdB2UcaIWy5dVXnDgmzH4KwdnarK0ffP762Ov871E4mmAngmCNRO6SJOqxYRE1Lf9mm9Aed+C\/ur5Zjuxzx2IDIZv0sTjLSR0mm2yvOoIFbMkrH9eNqaDAiRe8LFk+r6FLywp+Aa82Y6jXr16Co2ES9evX1\/3swW42QoLWKSjoBF7FuAzQvgGDNn3Du8qXur+barrXtTsSx0s9v0e3qmuDOlQWyHSqy4vAe2zBrXU7IXcDLMGtdDJkbATKCQB33SMf\/rTn2Tu3Lnq2eHHnOQ348aNU88EkxbJ7tMYJfimnWEntheb1q+Z9GpRRa+T0Bm1ofOX14gAKFMoh0YThJPtnA6JulkGsHd+PyEDJBD+2JbxnscnJi\/4xh60MUJP2QaLbJS0Q8KE8NDyo89AnUFQYt4dFA34ZiCuW7+cfkcGO4NoBtNkMcajg5cRsd0VA6dCZarKhDXHww5BBDqHL9ojXUYvUDDtPWWVDtrDXTOOEoNv7AIUsiSESBXaIJMYZOJmEIl3ETBiwB7qYXQVFfh2BujACyH5DADJgtx+yAy9Xtd+eBkZVDbrNVrXK2Nbz7pCxOB+2YnXtL6J6x5x9KgmzaJur+MTkxd8YxMG43hsAUXaIJOPffr0UWAEiOgPk2uDKFrwDRDiWeT6mKho3GWo8+83guwYeI19gclATnSBVz2hor25QD9yyT7dbqxVv4nqdfM6PjEFwzf2wDZEpNDuCIlmAoNJnx07dnjaLykbomjBN0CIvVif27z3WKnWtJNO\/rh2dG3cb\/o6yVGghEZkhOPZ5Bjqbj1gskZhMDHE\/Uy79Do+Mbnwzb0J7JG4j3uY3xKWgTHpg5eW9pncPeylaME3E5BM2pCRu+Pw2brTANm6aYeuLXltyPxtcu9DmWTJsZf0nvWqK1T0ocA2O0xQZ6cRc3XbNq9jvXQr8I3dgB7Am4lJ2ipRaf3799cJXjxoXvd6tOGb+5v9vB\/Onlfuz5BZ8wCQh+DBzDkke76iMmLxHj3G69zE5Ef4BmhZV7x03ywpWbGoerhZt12yUjEZMbu\/7LiyJrCftAPnbBcGVLMt1dGXtisEklytZpMqCueHntt6g0i0VqZaCZmwbJieFwxxSWmJA4O9RneSzWeXy\/R1Y6V9\/xY3bjWWjJKDb8bT3M84FViGyL1OZn7CyhmPA4uMGd1xd3LgTYkVfJdyvgcmIJjoYK\/1YPjuPa6LwvetrPtmvXi34e00A\/26RxdJ77GdZf3JxRFtNZZUwZanT5\/WZWIwDp5vlgKwQwljc6JP\/\/53Z3z+v1\/L39884TluTYkOLBygy2Wf2zNVnaXB8P3S\/unSqEox2X+L8M14G8cZ4+9jS4fIhF6NFOzDmzBIx\/CNgTFOy1qldJ0tSdfY6xtDs1ifTN1NqhW\/pbBzvhggk7oRgAq485c6eD1ZwycC39zYeCEIha5Zs6ZMmDBB9\/qmk+XGD\/emp85I4ZswaUKYZw5oLiM611UwbFC5qEzu3SRBrJFgLUbJAtm0AQLsXnV5iUkMog2wJe9FSIn7mIznyQKoB3xjG4S9mKVs1KiRri1h4oLQfCYusHFYJUrw\/fg2ZxA9pJVM6NlIapcrKGUK59QlEJN6N75uw8Yyumt9TbpGx0DISrjwTfv7o9PmsBdtD\/uxNp+bn+fC+T5C4Rv7MSnB4JLBDxM\/DDaZtGDG1w2xogMNHgR4KRrwzQCSLYea9hh1PaFVcanRsrt6ZJr2HKUChEpXb6zJmhISC3nUFSrXU8kgFuHFBFTd59QTl8ygPxS+GRgyECckjW1cKlSooOsc9+zZoz\/i\/MAzgAy1lZeiAd98\/sFztyjkAN7YqGiFWhpO6tqvaY+RUrt1b8lbtJxm9d1wMbwEbxqR4MAOYiIDu+Fdw448px64MKApFL6xIR6Gffv26VrvJk2ayJIlSzT8lz1aGYSH2iopRQu+2ZYNKKa9FShVWcNSG3YZcoMdG3QcpB4zwkvDHWQrNDrtzbUjf4PtyHPhTAi58P2DYz\/a2NNPP60eW9Yhk8+CXAzByxq8bJWUogXfePTbDJyi93DhstU0q3nDzo4dnXs8YMdR0rDTYLUja5dZbsIkklddwcKO3Lehdky4p7FjGPB55pVv5ZvvftD7lXuY5HNM+rD9GpE+gGC497CXogXf7KvPxBeJEtlXPkvugtLAsVsTpx0m2NGxa8FSVZz2Wkkn2cK5fkQfqnbUv5+rJ\/zHvtG1Y+LfSbjwTTsEvFlih50J92UZE4mruNeZ2EhsUiPa8E37IHKCfdKrNemoiQzZGaKRY0OWgPDarURFIb\/BtwvewFeL7o2kSJmC0rp3U5m3fYocfG5LAHgd6AuGL\/ccwtO7DG2rYcs58mWTOi2rS8dBrRLUYUBLXUuexxkDzds+OWxwRoA+3ly88bwXoAlg8nkeCQMSk4JvxtX8ptDuaIMsbTh48KD+BjFmTNRBk0yJBXxzvYSaY8fN55Zr9viBU3rKzitrFZwr1CwtrXs1uSXbBiZOdijY82\/eA284j\/F+J1dXuPDtji2JVmNCkzwkLHdiKcof\/\/hHfS3BoeiMv\/\/95+\/kH2894jluTYlwmtavVEQjeFn2Sdg5jj+W08KCJJO+tGms57mJiTE4nm7G3\/yb8fcfnoRjHBZ0uMbrnB+VjuEb1z\/7Jk\/u00TKFs4h\/VpXl4wP3C2zB7VU4CmrINRAjR8uOAI1rM399NwSBSAgkrXKe+f3l2PLh8q7j8xPPnTaA75pmHQABw4c0O1xGKQHz7Ld0s3vHBspfNOQyAbIHt5MUOTM9IAmqwMgg8U6ibHdG+psklc9iQnIJOsg74MdWftMBsJ9CwZoXdjV67wEJQLfeLy5uffu3asAyaQFnWfYExduiRJ8X9w4RiMDWN9eOHdmyZrxXqleOv8NNqxXobD0aFZFk0GEu9UaNuNGf2bXZJ3wIWKAteNEEuye10+ubp2gExrJTQQFwzf2wVas9SYkCK8Dg5\/Qdsi\/4wXfq8+8q8BDYjUydN+fMYuuvWM7GLbQQYXL1ZCytZrqelm8PuF6rhmoE6bOelMduDuDL5I8DZy1UcPYWQsNQHqd6yoUvhlMkmvg6NGjsnHjRl3X5HrGUGIDSS9FB76\/kr5T12hIKtuAZcyWWzJmz6PwmGA\/Z5BZrFIdByqHahKx5K7ZFQNw1t+zJpT3YWCKzYYt3KVZzFkfyQDe69xgBcM39qHvY9KRddznzp1TLy2w49rvVmyIogXfeP7Y75j12A\/nyCcPZs5+kx3Jws9a2ckOYBKW71VPqGh7THgwccSED8Lzy9pvPLhsmUWCt+QA1IXv7x07MYm7cuVKjVThfo7Efq6iBd9Ep2jCxFrNNFP8fRkyKxy6diyEHcvX1O0DWWrCfelVT6iwIxEE07ec17aIHQHO8auPyYCZG2XS+pMKjxzndb6r0w58f\/TJZ3LI6QMJKydSJaX3sJeiBd8zt1\/WSbTydVqoZ\/aeBzJokrBCZVw7VlM7VmrY1rknd2p\/l9y1u8JOhFzThrnPWUsPgA6YsUG\/PzzuSfWz4cI3k+JMCuH15l5nDBSunaMN3+sufKDr5bl2bT9OPxhoR4FlIWwzFm5UlStfwfebgYRemixt\/TiZuHyE7HxsrcIuYeNAmBeI8Rxw3Hd8V92mij2+789wryZpK1GpaIJYH165XjnpM66L1htaT2Ki\/l3O8TuvrAl42h1A3HRmqUxaOVK9tXze5AHRG74Zz\/B78\/jjj+vvNSDojnduecwYUmIB39h59paJUqRsAV2nXbRcIQ3j7zqsnZSrXlInSxbunJasPYIFbK85vjBhjffux9fLrE0TnO9\/uCw7MCvh+cQULnzTTplo27x5s0ZVco8Hj81vsHUM4JtoW5xdVUvm1WXDGe6\/S6b2bSqjutSTaiXz6Tj9VhKuwZcfnV6kglcYh7N974GFA5Vl3j4+L5nxdzqGb3fdMgaZM7ilpqkvVSCbbrLevEZJmd6\/ucb6h+Wtvq6PzyyS2YNbyYkVw\/S8z5wvtHvTylKyQHap40DUKAfqCUHwOjdBicA3P\/DAY5Lh0OEU57yIPd\/OtTGbw6wOkDy+ZyP1bj+\/Z9qP2jtNswUC0kC0Vz2hws6atG7hAJkzpLVGDfzu6mqZObCFFM+X1YHRQtK5UUXNrJ5knYnAN95ZPBMudKfchtGBb66B\/bhJGLFoZDudAHpm52THflMTbEgkBlsecGx4a0UCywKI2OjgdMB\/ejow+0b2\/loOzFctlU\/qVSwiR5YOTnYSI9TzTUfIwB0PN+0Q+4XaMJ7wzQAIrwvhk8MdqCMsmv1cCT2fueOSCmBccvRF9cxoWGWYA0zCUpt0Gx4YrDuDTBJo4V3PWcj5EXMGra36TpDlJ17zPNdVKHwzYMRjxo+MO5CMBHai4fkGgBk8kkiIsPA2AybreljXfgyyCXEmI2+43mrEQJTQYLzlARAPTJRgP0C0fJ2W15OGJV2fF3yTvM8N6Y0UdqIF364dlzgD9NbONQM+ZJIOtuPsXVdlzbn3Al7WMO2IzYcv3u0AaT89j2iPrs6gPV\/x8lKwdFWdGCFjcnJeywTP9w+\/03XI2I82GKn9XEULvoFAAIQEdR2GzdQ9qac59yDh9j\/a8TFZffad68AY3mQa9iF7foW6LfW7wlPJ5AUQCpQS8TF0wU61t9f5rvB8f\/DRJwlRAkxcRMuGKFrwjQd6\/YWPNCy\/x\/glurXYtC3nZEaQHdkai+UP3KvJtR9XtFu2JGTyAxBFTILgXWdNNH0jE3p8N17no3Dhm4khN5rgVttqtOEb27FlGfa86TXnPmcPetps6GtJiZwiVZt01kR+LCup1qSTtkuvY70UV\/h2QApo23R2ua6nBrrxcicHcieB9use04PPbpH5O6ZIk071ZMKy4bL62IIfdXyBJl7Dgx2OtxoxGbD76jrpP7GbgjbeWJK21WlZTXI6Y+5Szpi+fb8WsuXc8iTrTMrzzX3uRvWFHRkZRokFfGMPbDxxxQgHuqvptm55i+TWiY3GHevKzA3j5ZgDdF7nhorvVWF+80Rp1bOxfi94wAlpz18sjxQvX0gq1C7tfJ9TkwTwcOGbcSPRBIwr3QmOREsM4JvxNbsNzR\/WWhpXLaYRuxWK5lYWZAnsywdmhM0x8BFO26WjO8ixZUPV0fXVxeWad6lY3izKgjATS3YTH4OnY\/hGhPACKmx8jkf1zJqRcm7daHnRAR7W2\/JauOCNgEIShZ1aPUK9lLvm9JUM990ly8c4P1TXw9hZtJ9k6HASa76jUpw6I0645tgEEEQ0LAAcr777XKjCtSGNlrXOJBfDZoA7NmW\/cMLbAcYBbWrqJAZA6VWHKok131EpUYBvbKJ2dNoY0RDMqgHaTGrwnJcNw820yA3NTF1vpwOmvjePztHM\/eQwIA\/BiM71pJoD4Ux0eJ3vymvNd3IlbvDtDAIZCKpX1Rkwk1kauAFOApBIWHiwHNgJE3jQ8IW7FbYBeQbrJCbKmC2PdHcGsiQeK1K+lkxKZr1oKHxHU9GCb8SkBIPoBQevaSZkF2pC7ac29KjHS0yKMODvMHSmno9HLGfBkhoGO2LRHl2fX7\/DQH3N63xXXmu+o6lowHewHYEeMkszmRENOxLWS2RH427DFb5pjwBOrdY91dtes2V3nchIzpMevObbyw6RKhrw7doGEORayQI9a+djagOe87ZjeLakT2BpRbVmnfV+ZnKN+5t97AfN2SL1Ow6UfMUryKbLSUdjuGu+vWwQDUUDvhPs6NgJOxJx4vZjtNEb7RiwZbh25Fgm6Lh\/Wfqw4pHXdRlF0Yq1pf+MDQ6EjlI7EtLvdT4KF74jUVTg+7odsRkRO0QREMnjerxdMfnA\/ulTN5+9bkuPujxEP8jSACZxmQjqMGSmThJ7HeuleMN3SgXIKag7Ag7xpO5\/elPCczeIYx1g96onVIQ9L90\/Wxq1ryOzNo7X7bSmrB4td99\/l\/Qc3VFGzRsgNZtWkXGLh8hxB8y96kDJrfmORYkFfCPsxyQEWeMX7pouc7ZM0rX0RAcwCZLcZIkrvguAu2G72tJ5cGtdk7\/ukUVSvmZpqdu6hkxeOVJa9mgktZpXTTI7\/a2u+Q6rxAC+3bE43PfC3mkBFlwfYEGiRgMs6H1uqID0J7ZNVGfayVXD1cFG8rWH7rtTd8DaPL2njsXhw8RzYaVj+Ab0CBEnAzQzEIDIn58OrNUGWN49MU9DBJKenbhRhPWyNpe15BgVEC9fJKduFUXoNInHVoztmPQMShqHb0Dw2ysr5NOzi1Ufn1ms14b31n0uVEC0V12hYh3Et07jb1WrlHpqmS0iYzygeG33FH3t8OLBGqad5PZlaRy+aU8kq\/viwlK1D7NkRE0QosLfUPuRDJAOINyZN+pvV6+szBjQXPMNMKHEMgrWszDR9OT2SZL94fs1U31SHUpahW8GOMAiHm8Gf8udwSVeB1c8ZkCToEde02M5J1wPT\/8Z66WKM8Ak1JyBJB6yUtUbqQeXMEEGYuwpzuDL63yUluEbMNQkYI++cd1+ARsSWsm\/b7CfI0Kd8eyGGy6NzfAm9p22RgGAQSYJsvC4MUGCV5x9k9dfTDrMMq3Dt+uNJrma2vF6W1x6zG2LIXbU5GHvKaR71RcqgKlg6crSeVQg03x\/Eo0VLCGjlu7T72Pc6mOSt1g5DaFOCqDSOnwDx4Qv086wk2tHV6F2JAkb92JSHtZgUX\/5ui1133+gcdyqo5KrUEndQgo7sr\/9fRmyXE+El7Qd0zJ80x\/hPWUrNm873nhv03+SlFK932GAI8cwidGoyxB9H6JiaH+t+k3Q7w+vOssFeN\/EJjv9AN\/8TpBcsuPwObo7AfkFMuXIp5EYmlDxuthHnyU7XDOTv151JSa2EOS3ifuaJVRs5Uh\/Evgekv8u\/ADfhIKzrRiZz9Guq2s1KRt\/3edu0BPrdc22V12hwuM6f\/sUadi2tmbi5n3w+BYpXUBD19nzmvXkvcZ0cn4nt3rWgdILfGNrlgQQFo6nn+gEbMRfIg\/ICj9n88SwAFzh+4VtUrZaSRk2s69OloxeMEiKlSusHnS2jCPsvHDp\/Ar2XnUgv8D3e4\/Ml91z+2mibMbPjLUR\/2bnq52z+sh7Di96nRsqok0Zc5PMGxb88uIy6dq4ooa0M8YnIpqcWAuGtUmCjdIhfDPDgUGBkquOYQa3ryUXN47VEGfX4LxGyC9bjR1bNkRh3KuuULFAn5CFDZO7ycmVwyV\/9gwya2ALrRM4JQHZxindFfy9zlelYfjG80pj6dW8iuTN9lDYmu5AoFd9ocIu1N\/DqX94pzpy3mnA2JPviCzgfEd7HSjv2LC8TgB41aFK4\/BN8rPVE7pIoVwPe9orVKynb1C5SBKzZDeKSQyiA2qUzievHpypIS6sJWc2jtcuO+09d5YHNXrAl\/DtDIzIwJ05V0Fdp5wha65kxbHz9j6VJCwHa+TivQqPwxftkiHztsld9z0kXccs0PPZXofB2OhlB52BUuIwn5bhm0gB1nqTvdfLXqFi4Nmi97iw1zUCOBXqtdY1zniEmLio0qSjDjBZe9tr0gqp1KDddXhKfKCZ1uEb8CYTPPbxsluoWA+O3Rlwe9UXKuzDFne0N8CmevOuUqpaQ23LvEYGdNaWM7HkZ\/gG5LqNXSSZcub3tFuoaLfcn4Hr9q4zWMA3oMT68bl7n9AIDOwWWH\/\/pe6I8GCmHIGw3yQgNK3DN+2KNdzh2pFoniy5CwUmJsOEb8KvSdTG\/uAdhs2S7PmLazvkNcKzs+Qp5NwXrPv2rs8P8I23m4z7TbqN0OUdTMz84le\/lt\/ccbfccfd9N4hkdq37T9AJXq+6bpJjF343mMjUBHX82\/ld0eU\/+5\/SCVC+R50oTuI7SevwDeTteXK95CqYQ\/cCD0eZczysGdG96gsVULn84Byp3riSJnTDG5s1d2ZdN47Xlr3DCTsfMLm7JgnzqgP5Gb6xMeHmgDfX3LZPc+k8pE0CdCuAO2K\/7u4j22uiu3AyyVMvGeqJKqjV7P+3997hVlPb3v9fv\/d57z33FLuCiNKkI733DiJdQJDeFKT3Ih2k946iKCAq9oK992Pvvfdy7invqfee8ctnbOY2O2TDYq+VtZPFGM\/zffZeK8lMMpKVzM8cY87ZXKd\/a9ujhf6\/69A6bSBZsWe+9uEn1T+sDBRn+CaQCHOQpQwkD+3WVB67ZkY+BzoxVRjp5\/dsmpRS9JttnvZYkOArLMjg1NThV0\/qo3V\/gmkzh16ogVg+h5WRk\/ANeBNpZN5oot4DPJBjyjH6YtP6gfj\/ltVjpF3DqnL9kpE6Ql1YWUExgBv9AxiArMRpv9NRwD+9b7UCz5PXztILSH\/wsG3zFfPINw0TW2ZdqoMSpCpSncPKCoqGEW5cUjWAQwY9qOg9kO\/dPFkzE0gJGdatmU6hRbp7WBmqmMM358LE\/RP6twv1V1BkTHBfkZkRVl5QpMgwXkG18mfrfYgv2Z6GDe7F8V55ZA\/g67DtneIb+aZi9LamirbrM8oDvJHHFOsS+Uk18s0UOu36jpJTS5wjJ512lvZn3OiBI\/ue6FVuASD69IZt6xRn+GYAITePeZi\/gmIQrLFLrtHITFh5QeWB4X4569zy8rtTz9DIEJ+p5BMVp+8t0bJjVfjjDt+k15Myin\/C\/BYU\/sbvxxOxXXDtQwrtNAABS0RrGYSNMkhJp4HjWI1KcYfvnY99LtPW35yyH9t7fmTO5VQbg\/jdMwI49yG\/5zNLlZHeRGs1m+Nr7VNfv3XXY16XuMM3v08AmOh0mN+CYr7uTgPG5sHeMX6LKm8dUvZpuMCPDHLJ\/aejpXvLLvauCfP5H61xKQnwrYDs3TPAMc+sqetv0sZDxh4gUyBfh97TMQo4X4A9tKyA+K1uuOctTdGfvvFW3ZZsGBorf3PyaXJW6fJy6eRl6tOjlRl3+GaQNtLMGWGbUbhT0sCOsuXOleHlBUR0lnToYVMHyBklT9Mpz8pXLesB\/w6N9K49sFgj4fO3TT9Gv+TkwjfQTRSaAeeYao00ceZRJ+382oc3HdZG2XnfWunYu3Xq83x7147oOf3xS5U9W31bovRZMmX5GE1rpzGjU5820nNol6NOXRZX+IY1CKoS1NMM6FVjdOarm72\/jgMR3WlvXnm5NKxRTvZfldpUY0A9rMJMRqXPOkU5hj7kZOtS94cFiYQfPbCbo\/A9pFtTaV67olQvX0pKnXmylPPgpEaFUlKrUmkVneKJSgLLz14\/95iQ4kTf3S+9i8mccWum9NNO+jiXC\/3WbUv14nGxw7bNV8zh2920f3hys4roKSnUpDMDd2E6Vt9ivyif8h7YNkUHLKDvBWUAlLQS7V44XBtOjjpqfMzhm3MBpGnIcD5kYLnCfMhyGhuOOVL+YeFDfM79t2ZyP73vmC+ce599Xz1\/qLyw98pjPkjinHZOJdOBHNEqBhfa9uDHWpkOE33pqFgfLVLtF5WutXe8qoMHMb\/rqltezE\/NZAAookt5qb7h26M4wzcVQCp9+CXff14lMsx3iHXyKpipZQ5QaWS7mVvu0H7fDHbFZ7ffobPWyvKbngvd1q+4wzfnyfkQ6Xd+pDLu951fLOe+BfjCyguK+5VMgXkeUOFHpjoi3ZrtEVPtLdn7xDHv67jDdx7ofKnnmpofP1Y\/ptoYxO+WUeHpRtJ\/wmKdtYAGPDdi94i5m2TBtXkjoYdt7xR3+OY+yPPj53l+VF8W7kd+8\/hc\/ej5KKzMoLjflx94zvPjEs1gWX\/X6\/q8xMfjrrpOZm+\/+6jXJQnwzbm4yDRiHIfJa2\/UbhG8B5zwtYr7KEX\/sT6zFZABQ+YF9zp9ymnI6NjvMuk6ZLJOY8aAlKwbVgaKPXx7YiR0YA3gU710rfYRZu5pUsGD4vs73zj6CNp+aXT9qe06gNtlc4bkjcztbQ84Apzzt0zT5fR3DtseJR2+x8wbJvVb1NKB0E4542Q59cxTpHyVMgV0nsc0\/B09e3BKaeeI9VwjBoPazfN8eeC5q\/O\/H79wpOzwfEx0PWx7FGf4huuG92gmrepV0kDVaSf9Ws4vfWY+ByIGeoYFOzaurl1fUx13ifJhPere6zyOYc5w9kcdnEG+GfH8Cw\/GC6+D5yB8M+3SC3vn6fRfpOOShz\/4oiYye3gXHVoezb+sm2yYPkCeu+FKBSQcGVZWmFgXwGE\/\/O\/SFPjL98csKxEDruWdJwII6dP+0d0r5MO7l4fq20eOkiIeol98mCfnM7dP97lQJWLAtV\/Oh3OkPzstcGH+w7f0\/eaeCisrTHq\/HS7b78O8ZSn40FOsB1zzRGUnT98oRNLPkHT0MK25\/RWtNKZaQUJatlcxV+l2edu6fR6rshpn+FbpeeSJiiap6GG+Qwx+RZTnWJDnl\/MTgMrfPB+6ZQU\/F6YkDLhWwI\/eueKn1be+fIQP8\/z4slbguadCywrR0f2Yt1\/\/+mGKO3zn6Rc\/4h9Ghl\/t+SvMj3xPf1l8El5WiA6XrX5UXxbNj3EfcC3oRyCb32+oH737lDTnVBvVVL6yi+LHJMA3jRc0stJlBl2565BcudPTrrzPQZFtcLRB5vyi7MsWbNdsi6X7ntLnBVHvWk3b5\/XR99T8ogGaaXS0AdiSAN8IWHMCxJmu6rpHNvsis7+I748WSQ0T5ZJKrVOeefJ\/7+RfP6hEp51753vtI5u0n\/c4D4brNL1ALmhQVQZc0dvTxapLPQ2e1E8Wbp8uNz6zM7ScwsTgd+wj37+HfZm6b+MK33ndXJlZiGDpjGGdNVN5WPem+RyoGt1VNs28VGchottrWFmFydXtVdS5fd8fuw6eg\/DNCWuf72e26hzcuxcOk5dvXKAj0hFZRaSZA92A5dEdFIESAN\/cTKQv4xugcdOMAdpfojCRuh9WTmSKOXzjN\/znoJgWMUZDZD7vwV2bHOG\/4T2ay5yRF6U89kCmFF\/4zqtA58EI4Pi1DuTVZfBEHYW3WZf+OhXOLxqgo0JTAT2uynqaijN8K8x5fnOVaPouM5J7nv8uCfivv\/Y1ZpC0o0ViolDc4dvdf3lQ\/I1Gw\/ATPmTe3iP82G2gDJi4VNcLKy8qxT7y7fx4+DfNfTZu+XWezwaoH0n59fuxhefHrkMna4NaWHlRKf6Rb56NeX4EkonaTt1ws\/qLOaWDz8YWXS\/VKRoBQrYNKzPTij18e35gbIqaTTtIjUZtU9IFTdrLqoMvhZcXEPc2Y4ow2j6ZVQyieHrJ0pphRZYC7ynu+yuW7daMmrAyUCLg+\/BUY66fMf2FgcEOvVvpvN9HqHdr2XTb8iPLiVDJ7\/O9X\/t1kwo+d9MUmbl2gv5Pn+087dE+2qyTSn\/vTCrOfb5dPZx6NTMC0T\/7lZsW5nOgE1mkmjWaVRbMMfjG2QqOL+xQpzOAFXMo06KBc\/V7nxwchZUVmRIA3wxURzQWH312\/2rNHGhSs7z2YwjTnsUjQsuJTDGHb+49Uk9o9CH9\/L+f3qojk1ctd7b079TgCP8N8wB87sgu+iBINe0lE4pz2jmV7kmr92m0gf\/dwFP0xaYfbNPO\/X6RB5TAN\/OpppqmmgnFGb7xw+xtd2mUhf\/p496qxxApV62OThFWwH+egMZR87dqJT2svKgU+7RzDxiZxol+sFSquR87XXqFnFuxuufH3kf4EdgZMHHJUSvVUSju8A0wXnXjszovPw0TRPwYmZyBw4gKNu3ct4AfgZOuQ6ccjjZmBxpR3OGbxsW1d7ymc3HzXCSlfOCU5TowJbDXJOBHYLxNr2Ga+kzjUViZmVbc4Zv3y+ZD70rfsfOk1+jZKYnp1xg5Pqy8oLjXAWwaPRhxn\/EcylSuqQPY8XydsvaAPoPnbL\/Hu4bJTjsHDq\/0gJC+3\/y\/at9CnXe6Qas60q57iyPVo4VsPLgstKyolHj4pnHDEyno+Bm574LyZwZkQ3GOfOezoCeCrcyuRF3cfRdUdlkwh+Abx9Efm5Gzh3VvJkO6NlEBjsh99ot52hjpjtHwwsqMRDGHb1qBxvRtrSP4\/enZbfL5\/Wvk8otbyaKxPUJTphHTZIWVFZliDt9A9LY5g2T5+IvVN3xeMranXHphI3nz4GId6MHvP+YAp\/8IDURh5UWluMI3lRf6GVar31LnpaaCCXwD3TM336ZTgeWl\/f4iKqTZjO6gOMM304zRIEE\/RvxCCm+nAVdIz5EztD\/nEf67\/dW8vsbHk56aAcUdvknp7eH5bMTcjdp\/lj62QCEDWS33YDLoRyrdjIoMtIeVF5XiDt8MXDd05lrp4wEP9xlQzYBqTTpdrHOmrz6YlyLt9yPRyeLwY5zhO68hcr8OuMb0d\/h10LSV2oeYacHouxz0o2uAI+IbVmamFfvItyfuK56RpISnIsb\/SLVhl3cQ6zJnOH3mB0xaJguueUgb7\/iexjwi4\/qcOEqmVhLgmz7clWpW0Gg2UdfV+xdKqy5NFMive4Q08yN1tJHJo1BS4Zt+11NWjJX2vVrli9HMkf87v+gXf6xU8UwqjvANC37rgfaYPq3yWS+PAxsX4D+\/yEB9Yd+80PKiUQ7BNykDH961QmpVOlcqlD5TypY6\/ZgiEnnv5kkpD7iWEcUcvmkBGuTdpMuZo+6JTXlTqHkwvmFG\/yNaipyynz0Qb\/gm02LjzAHaEMS8gj88vlHhm8YeBlgjMu73Hy102mfkxfDyolJs4durGDFYUunzq+uAXkxrM2nVPo0qLtv3lFZAXVq6U7CvbDYUZ\/je+uCHGl0ZNHWFjrQLXF84cLxcSuqjB5BH+E99iP+y68O4wzdposz3yzRsNGDo1GPDpkq3oZMVxgv1Y5bvxSTAN\/di24tHaIMafgS+W\/cYrA0c\/ObD\/Jjt33Tc4ZuGtEmr9krDdj11cDn8ONDzK1PV8T9p6H4\/qi+z\/GxMAnwHxf2Xl0nwuTb2HqnP1Zdh2xYm7mFXptuW66AQ7ulY1yQJ8E26c8lzz5I5GycrLK7au0Cnq+JvXj\/iI5VNOERJhG\/6Yt\/28h655PKeUvKcM1NWp4vbGHx7denPD63WgbXDuC9MDMp9aOvk0PKiUQ7BN3L5\/aQY0K\/7WCKym\/V+3zGHb3wxc1hnaVW3krx8YIH2kRjRs7msmHixDqwWpuMdqCBtxRy+uQfJHGAERVLy371jmU66TwsbjRlMWef33\/ePbtAxCQDxsPKiUpwj34ANfe1I3WMKocsX71SYnH\/1\/Tqg1eZD7xdQXsXz2BWaTCrO8E3aM5DIXMkMFrTkhiekfd9R0mfMlQqRR\/jv\/g80FVj7koaUF5XiDt9UnAdNXal+nLL2Ru3awHzSnQeM1Yhi0I9E01zjRlh5USnu8A2EjFt2rfpx1PwtOpc+GQTNLuynUwRuvo8IY0E\/5jVuWOTbL55xjJKNHxnVnSyWvuMWSJ0WnbSBjUEVC\/rx\/fzGjbDyolAS4ZsxRbqPmCatvfdNyx6DjxDfk0UQtu3RxPso7530y3sp+LkwJQG+meKrbrOa0qxDQ50Ka+H2GdLywsY6QBhTZIXpaNOCRaEkp51rX28P0lJV9n0bz7RzAlpk8YZxX7gYAyyb9e8cg2+\/3GjQRLW5CGFiGcBu8P2L6HPM9GvtG1XV+aO7tayl2QQM139Fv7ahOrAytXm+M6YE9PlmZHPm+caHHZtUlxZ1K+q0BqN6tTzCf6y35IpeHrRnMQPDU9z7fF+x7Bqdt\/e8SjWlRsM2UrpCNe0f2qbXcGnXZ6RPo6TT4Xm+swk9cYZvImDMWXtB47ZyWonSUrt5Z6lQvZ5Uqt1EWvcYEvAf83xfLmOXpj7Pd6YUd\/jGH6RF0+Xh9JLn6pgDFWs2lHLV6mof+iP9eJkMmZH6PN+ZUtzhG\/gjDRr\/nFGqjDasVfbuRX7TrboPzpuX2ufH453nO1OKO3zTGEG6Of2QzypdTqrUaSZV6jaXkuedr4MmklkQ9CPdTXieZqthMgnwjR\/JonIjmJNZxW+6bJVaUqFGgyNUsWYj7e4ULCdKJQG+6Ye8+OrZUq7yeTrVVb3mNeXc8qUUxpmPOqjunramOM93ppRk+PaLiDbTfgHYZBmE6WjTgkWhOA+45hczCcF7BMbCWBBlN\/iVw\/ANeDPY2mNXz5Bb11wRqjs3TJBPD63KrtMTMOAa2QBP7p4lY\/u2kQub1ZAyZ58m1SuU8v6\/IFRbZw8KLScyxRy+EQ06b9yyWBZc1l16t60rVcqWlLJnny4dGlU7wn80cOBrWt9swLXD8iqKzOvNyNIMqFbeA0fgB3is4QFlzSbtf1HT9lKvdVetHGUzwhNn+EY0RDCoT9veI9RPZ5UuL6XKVZHqjdoU9J+nOi0vlMHTV2klPaysqBR3+EZAC\/00SdvHTyXOraADXFVv2PpIP3pwTr96IuZhZUWluMM3wo\/0S2agNX6vZ5epqL9p\/Mho0n4\/1m7eSdr0Hq7ZGDbgWkHhR6YRu2T8Yk0\/pwHjlDPPluoNWnl+bFfAj7WaddSUdCDT4NvJe7c89KFUrd\/Cux+fUr8wv379Nl1l7o57tBH3CNFvPssNQUmAb4CQ6OyCbdOl48WtpUb9KnL6WadKldoVpUGr2keqdR2dVzqsrKiUK\/DNgGpb7lihvp63ZWqo1t20REegD9s+CiUFvhls7ZFd0+W2deNCWfDWtVfo4NJh20ajHIJvIt0MnPbTE5s05QCAfHHfPBnQuaHUrnyuNKheVhrWKFdAzeucrxeESGVYmZEoAfANOOK\/n5\/cLK8cWCgzhnSWLbMGylu3LgnVVw+uDS0nMiUAvhH3I4OtfXzPSll0eQ+ZNexCee3mRfLWwYL+e+e2ZbpOVsce8BRr+PYEPAIxG+99R8YuuVo6DRgrs7fdrRV4Rk7O14FntR8p\/UqzNaIvijt804BB5JB+y0v2PiHdhk6RwdNWasSngP88rbj5eU3nz2bjBUoCfCMq3owYverW32t6Kun7zOF7hB9vev6XAa5CyolKSYBvhF8AQebl7zV6llw0eJJ2KyG7oKAfn9M0XzI4wsqJSkmAb8TvlIYJ7jWmsKJLCX3Ag34kLZ1B2LLZJScJkW+6KTHS\/rQNt2gUfOLKvdKofU9Z4fkrr4\/8kcr2eBhJgG\/ECNtEY29+\/hpZcvVs6Tm0iyzaMVN2Hlp3hJiK7ODvrw0tJyolGb6ZN510cvrK42Pm9ybDoHLN80PVa1iXE77PN4JhYEHq1PzPwNq929XVub6DHIgaXVBOHr16RmhZ0Sin4HunDhBGBPGzQ6s1vYDobX8PvueO6irXLR4hNywbVUA3rRwjH3nQY\/BduPDjW7cu1dG4w5YXixIC305kVrx\/51U6ynm2+3UfTXGHbyf6IQPg9BPVfslZqkQeS7GH78PCX0S0aaBgBOls9+s+mpIC3yrPj0APfqR\/bbb7dR9NSYFvJ4AHKGTu5Gz36z6akgLfTtyDNGTQ6JPnx+J\/NiYBvmnUrVSrsTboEtkev3yPNGzXQ0cox49HCgA3+D6WmAZr531rsw7YR1NS4Zv5vZnTe9HOmXK7B2qAeI\/BF0rzTo1kxurxMmPNkVq5d4EO1hZWXhSKK3zDLbAgdW6CsY9fPVO6t6qlU\/4GORDtXTZaPr53ZWhZ0SiH4BsHf\/ngWu1j++yeuZrCC3xfdnErHcUOMP\/jM1sLiAtkfb6PLnyDj\/Bv2PJiUcLgGx\/SDSJvRPP4+DEx8O1Ven6JQMQDvFFS4BvF1YeJgm9PcfVj0uA7zn5MEnzH0Y9JgG8ygobNXq9dcSof7jdPH3rmSmeKxqDa9h6uDW5hZUWlJMI3UVedbzqL0ddjKanwTf\/tvqO7y+BJ\/XSgOuC797CLpN9lPfJhPCjr850neI9RzB\/ZmZfZ\/Pg1M3Wq34d2TDuCA52yGoTNNfj+4bGNUqtSaZ1jmfmVH901Xad3emD7FPnDk5s1BcEvRrdjO4PvhClh8B1XJQW+C1NeZbP4KpxJgu9Q4b9irrAnDb5DpQBUvH5MGnyHKx5+TBJ8h6t4\/ZgE+CaazcjwI+ZukAo16stvTzld\/u9\/\/kp+c9Kp8rtTzzhCJ59RQruZhJUVlZII33FUUuGbBozBE\/tqX\/prH96kc6r3HNJFpx+74\/UbNA09KBo+wsqKSnGOfNeoUErWTbtEu34+vHOadkF+2IPxIAc6ZTfAmEPwDUAzxdi0wZ2kStkSsnhMD9l55WDp17GB7LtqtLx56xKd8smvj+5ZoS0klnZ+\/MprtAhfFrlyAL51NH58GLIsW0oyfFN5IpWav2HLs6EkwzeRMqI\/2qe2GCvqSYdvIIf+tNnsUxumpMO3+vGJr\/SeLG4\/Jhm+8\/3I6ObF1C0iCfCNn\/Qd4t1vdGViwDVG3V9+47P6OSjm+s72uyZX4BuIpF94NgcC8yvJfb7nrJ8k51cvJ10uaS9Lr5mjIH7RgA5y9QPr5ZoHNhyhfU9ttwHXPAHTEwa0k8plSsjyCb01INu9dW25ccVlR3Bgnq7S6X7DyopGuQTfnohkf3bfKunZpo46\/bySp8lZp\/5Wzj7jJClX6nQ5\/9wzC6ha+bPl\/q1TdLuwMiNRAuAbKKTliP7wr9+yWBspfvZuTG5optB68tpZOkLgczdcKV8\/tC67\/kMJge+\/PLtdvrh\/jbxxcLG8d+dV8uPjeV0fvnxgjTy\/90q5e+METYf5xLtn8WG2U9LjDN9aAQ9UwqlM0lePgYUmrrpBRszdKFPX3aT9HakgZRsi4w3fR0a\/XMWc9MkZm29T\/12xbLeO5M18wMH1s6EkwHeYH6\/x\/Ej\/+dnb7tJ5q8cs2SXzrr5fo2nFAT1JgO9QP3pAs9nz2ZU775PLF+1QMeK0Dv5XDA1rSYDvPD\/6fYkfv5GtD34o8695UMYuvVpGL9gqs7bcKevueP3w4H\/Z+20nAb6DWn3byzJv1yEdVDFseXEoEfDtgR6DgTEo2O4HN2h\/771PbJPbX90jd7x2g+y8d62svGG+9lvedvcqueXF3bp+aFkRKcnwfeC5XTJwfB+peEF5KVn6LPndKb+VkzydfV4JKRWiTn3aZDXlP67wTUD1I49VmGmoevlSUrrEqXLSb34l55x5yhEcmKez5IFtU0PLikY5BN9OzOfGsPI3rbxcJg\/sIC3qVJQxfVrLsnG9ZcXEPgW0duol8vZtS22qsYAA7we3T5Wh3ZpJq3qVZVj3ZnJw9VgPxBdpH\/oq5fKmzapS9mz1I4AZVk5kSgB8A9K\/3z9fpg\/pLG0bVpU+7epp6xvTj9ESV79aWR2f4FzvoTC6dytt6Mhu2kvM4durTG4+9F6B74guTt94UCrWaiynlThHSp9fXacrqtuqi8z1Ku8AUTYrmXGGbyrojOibV\/HO+84NFsZcy2eeU1bOKV9VSpWvIud6fmRu6u0Pf3IEIEWtuMM3\/tj20McFpmADCtff9Yb0GDlDpx1j1GR8Sf\/RPmPny5b7P8i6H+MO3\/iD2QhQ\/ncAo3ePXjppqc7nX+K8CnJOharqU0ZBZ5DF4vBjnOEbf3Avck8Gvxs1b7OcV7GGnHVOOZ1+DH8yfzojomfTj0mEb\/yT7XvtWEoCfAN69DWetW6iNO\/cSOo2ryk9hlyoU16huk0vkFJlSsqZXn2xRoOqMnv9JAXwsLKiUpLhG\/8yf\/eK6+fLmCuHSc2G1aRei1oyYtqlMnL6wCN05aYpFvk+LOrT3zyyXm5ZNUZZkDr3Ff3aHMGBaKWnd25fFlpONMpB+M5L592hk6YTtd27dJSmnDNtFoOw+QVkZj3iGHP4JoMAaOzQuJpc0rGBzB15kfabJ31\/4IWNZWCXxrJxxgDZs2SETBnUURpfUF4bOsLKikwxh28acz69b5X+4Ds3raEATncIfDrukrbSq00dWTSmh1y3aIQsHttTqpYrKSsmXKxR8bDyolJc4dtVJi+dvEymbzioU2XxHZXIui276DzVI+ZskMlrbpShM9fqvN9MtbP+zjeyGi2LM3yTTs4Ivpcv2qmRRcB724MfyZDpq3SAoR4jZmiqJet0uOQyqVK3mUxdf5OmYYaVF5XiDt80XszcfJuMnr9V1h6e+oosiwkr9uic850HXCHjr7pOJqy8XroNnyrnVa6p0+L5YT0bijt8c\/+RYTFizkadDgv\/cK9dues+qVizkbTuOVT9xj3Z+7I5cta55WXorLXFMl96nOGb59vKm1\/U5x7+JB2ae3TlLS9o3+UmnfvK5Qt3yKTV+6TfuIUK4\/3GL9T1sgWXSYTvOCoJ8H3Xm\/tk+Z55UumCCpoSTX\/kll2aSpf+7aVRm3rSuW9bmbT0MpmwZJS07tpMv9tyx8rQsqJSkuEbAeAMpHbbK9fJrLUTdRo3Mg100LWA6PcdVkZUijN8I5fFS9Dr2oXDdeamIAc62YBracK3ExBJmvR\/P7Uly049huIO3y\/ulDVT+ikovnrTQs9\/W3UO6mlDOkmZs0+XAysuV7+yHsP49+tQX2YOv1BH8g4rLxLFHL7\/\/Ox27c5Ag8WeJSPl+0c3etogV88fKpXLlpRZw7touj4+Y5DAeaO6Suv6lXWQwGw2BMUWvp\/8RrY\/\/Km0vXiETgcz8spNCo4zN98upcpVkVlb71QIIs2cOYNHL9gmVeo1l4XXPZxVeIwzfAMtjOZboUYD6dR\/jKy78zVZfetL0rrHEOl86TjZRFTR8zMVd9L2qbR3HTJJGzrCyotKcYdvIHH88uukav2W6rtVB19U33UfPk2adOoja+94TVN+gSJSzlv1GCzNL+qv92tYeVEp7vBN1gpp0LWbdZLGHS+WRdc9oim+g6aukGqeb1fe\/IL6kLEI6AJBdkaNRm2ynkUQd\/jm97rkhiekYbueUqdFZ30mEgWn4YIsliV7n9SGDtYlq4DsjHM9ACeLKFtT4yUZvrnXuAfdb\/qXKcayHxVPAnwDewA201\/teXSz3PrydbLtrlVSv2VtKXN+ae2HTJo5uurauVK9fhVZuGNGllOjkw3f+Xr7RvUv6fyhy4tBcYdvJ5iFQbfjw4I5DN+oOAezKlSxh+9dGtEe07e1TlJPFgHZATvnDZFmtc+XJ3bPygdE0vvnjOgiY711aeQIlhWZYg7ff3p2m+y\/arSM6NFc+3bT8sZ3L924QLtB4Mv\/fnqL+pEMjXs2TZI6lc\/VPioG33kVIFfJbN51gEZveo2epdFHKpJbDr2fX5EEtulrW7V+C01Jz2bEMc7wTcVxw91vSb9xCzQdul7rrjLuqmulZbdBcumkZZqij58VGj2YpJLOgEP8H1ZeVIo7fHOfAS5DZ67R+7B6g1YyYcX10mXwBOnUf6zep1ph99YjpXrQtBVSq1lHTUsPKy8qxR2+XYr55Yt3aqS7Sp2mmi1AdLZB2+76u3XTZe185DPtQ39epZqy9vZX9LuwMqNQ3OEbH9EwSdYPGT\/nX9BQRs7bLMNnr5fy1eup7\/A169IAN2n1XjnlzLO10cjg++jSe8\/z2eLrH5Pel83VBiCelcv2Pa2NR\/g+bLuolBT4vqBhNRk6+ZK80bY9yOZvJw\/IG7et772\/dueD9o5713jf1ZPpq8dpxDxYVlTKGfj2pL4spoHrwpQU+EbZrFsfWzkO30Hh\/P\/3\/Pbibf1IAHyTEt23Q32NxAKHpOyvntJPqpY7Wx7YPlVbkdBnh1ZrH4opgzpk16exj3xvk9vXjdM0\/Ud2TdcWN3z4xDWzdJC\/1ZP76siK+JDviYg3rF5Wvn1kvcG3T1R4Vh98ScHwjFJltG83\/UGJcFNJyksB\/lSmrD2gadMLrnnQIt8+UZkkcjh1\/c3aJ5k+8qTsE7UFKPEV0LPujtc0bZ8IuUW+w0Ukm4yLMpVraX\/5em26SstuA2XDPW\/lpVB7Yp1uw6ZIw3Y9FDTDyolKcYdvJ6Ld864+JNUbtpaTzygpzbpcIjWbttdBAPEhv3kiuaRKn1+zYdYHAow7fDvx3Fu051Fp1KG3nHpWKWnda6icV+kCTT9XPz7xlfqa9HTu1833WeTbL+6pXY9yvx1uPPNEQ+TktTdKyTLn+6YZO1Oq1mshc7ffrfdmWFlRKRHw\/cZejXp3HdhR06Lpn3zzC9do\/+9qdSvp\/NTAOOttuGWZ9gmft3WaRb4zIEaQpxHjbu9vNv3pV5Lg2wnGoWsoIvuUz2HrRasTDL6BnXVT+8nbty0pJod7SgB837t5klxw\/jkya9iF8sDWKbJ+Wn9p17CqfjfFe8iSjv7hPSvk1jVjpWbF0rJhRv\/QsiJTAvp8v3lwiTZg9GlfT+7wQPy2NeOkfaNq0viCctK1RS0d0O7je1fKk7tnyQWeD+lXT\/ZANrM14g7fWiGir\/JDH8llC7dr5PE\/\/+s3XqW8gczf\/YBW2Odf\/YBWQOu37iqrb305P+UyG4o7fCMqlFTGV9z8nEYYf\/Wbk3QgpuFz1uvgazRuENUtW6W2jJ6\/TdcNKycqJQW+AZddj30pG+99S5pfNEB+\/btT5PSS50rfK+bJ8gPPyhrv3iOzoFTZyjJg4tKs+zEp8K1dHTyI2XTfO9Kh72j57cmny8mnl5DOl14hy\/Y9JWtue0Umr94vZ5YqK12HTtFGtrByolJS4JsoLIC9+f73pOfImXLSaWfpHNV0eVhyw+Pes\/E1zQTid92m51AdpyBbjRhJgG8aHrnnGHOAe4z3Br6kEZe+83zPZ2YzqNm0g75j6GISVlZUSgJ80xd5ylVjdPTtUTMHyeKrZ0vvEV2lduMacnaZEnLFghGy+6GNcvX962XwxH5SqWYFWbVvYWhZUSlX4ZuGjlnrJsj6m5d6EL63WAA8ifBNP3Dm\/t40c4B2nc3qgNv5yjH4xonfPLxOp8b68O7lR4jR7BjcikgjTmeKJ6KSWR1lOubwjYjGrprUVxrWKKfD9POXgcHu2jBBwbGRB5D0UcaXDMDGiPFh5USmmMN3XobFDjm45goFbib7r1e1jAzyfMXUYowYX79aGR1JnjnpGbTu9\/vmaeNQWHlRKe7w7ZQHPl\/InO13az9bRpem7zcpwKRa0i986roDWonKVgUTJQG+ET6hog7YMJgV\/cBLnne+VKnTTKrWa64R8YsGT9QoI7AeVkZUSgp8I+dH+nYPnLpcB1zDj6RR0+2BEbtbdR\/kAfrbWW0EQkmBbyf8w+j6TNNGn2\/8yG+Z\/xmpm4EVSd0vDj8mAb6d8I8bAPCCxu2kZJmKHnDXkmres5FIeM0m7WXN7S\/rfZutqRiTAt9tew3V3y5jhjCY55VXH9KZHxhgUYHcexbiNxp+yXhZcv3joWVFpSTAN2nmB1\/cLT2HdpEK1cpJmUrnSo36VWTOxskybeUVUr5KGalW16sr1qkkZSufJ4Mm9pX9T+8ILSsqJRm+D\/7+Wrn+sS1y3SObPW0qIKZ1a9qhoQwY21uueWC9XPvwJrnxmZ2h5USluMI3Ee2vHnIsWJAHmfaXmZsIJu5ZPEI\/sw5AHlZWNMoh+AZ4GC16\/fT+MqxbUwWdoAZ0bqhzvbWqV8mDxkYyqlcLefb6udmFngTAt0vPf87zzS2rx8oLe+dp\/2\/89PDOaTJ\/dDedfuyq8b3lvTuuyn7LUczh2wkfkmVx29or5JGd03XQNTfyIoPaEe2ePbyLvOiBN2n72R6jICnwrfIqjkTNqLAzQnfPUTOl0yVjdJqixXsePRxpzB54o6TAtxPRsl2PfyELdj8kAzy\/dbzkcukxYrr2YXYjyodtF6WSBN9ODsKX7X9KBk9bqRG0bsOm6sjy2x78UP0ctl2UShp8I\/wIPK669SUdHLDLoAk6xdioeVvy0s2zlCbtV9LgG6kfPV\/RBQLfdR06WS4cOF6GzVqvXUqy3aCWBPjmviNtv+mF\/XQcEbriMM4AmQI6N7ovxZzod\/nqdWXuznuz+oxMAnwjIq63vXydzufNYGo7D63T6ceIzM7ZMEn6jOwmXS5pL1OWj5H9z+zQNOmwcqJSkuGbQeq6Dewk7Xu2lHbdWxRQ64uaSolzzpTzq5eTNl2bSdvuzWX07MFZTumPJ3zDKtSxh8KCFxXkwIEXNpJ+HevLqSf9l7RtUEUu9T4P9tZhfKawsqJRTsH3Lvmz5\/CFY7pLidN+J7UrnyuXeXAzdVBHmTG0s4qpn8469bfSs3VtmTGks06j9drNi7ILjwmAb4RPaAn60YNuIuFAI1DOTc1gYT8+vkmB\/OuH1ilUhpURmRIC3wA1febxE35k0DU35gANRfgQ3\/L3ywfXyv\/LZiOQpzjDN5UcJz9UU8kEwOnLTASSfrZUlIqjoh5n+M7zXd4AVnk+\/GUZUR36JNPvGz+6tEv\/OtlS7OH7KH6kwSffj4fe1whknh+zV0F3ij985\/kv1I\/e73er9zvGh\/RNZgYDGjeC62VDSYDvwvxI\/+VtD36sfuTZyHOyOPyYBPjGJ\/x+V9z8vGYDkW5ev0037R8\/ceXevHvQuy9Zh5HkgXJgPZu\/7aTANyL9\/OBL12qklhG56eMNZDMyN9Ni8T2Dr+17art+DisjKiUZvmnMYBq3s0qdIW17tJBew7tKn1Hdpe\/oHjqf+nnnl9YUf\/f9lOVjbZ5vT2SezhvdTc4+4yTtGju6V0uZPriTch\/T\/o7r11ZKnXmydg2FEWcOu1Cj4WFlRaMcgm8EMJJaDlQzqjQR2jcOLpafn9is6eXfPrxeqpUrqSNRAz3FMg1ZAuCblA2A8Pqlo2Th5d1lxcSL8wYO8\/zln1KM0c6XXNFLds0fWmD7yJUQ+OaeO7R1iiwb10v9eHD1WB1UjW4ONBbRmMG0ZExHRsOQjoAeUk5Uii18exUjojXMB6xTYh2OJFJhAm7m7rhHBk9fpX1rGfWXiE+2BhPyK9bw7fljzW0va7\/4vMiXV2n0\/IcPmdaJVMpLxi+UUfO3yrL9TxcbNMYdvvEj6c+MJ0BF3IEMf4kqXrH0Guk\/YbHOX03lvDihMc7wzW8YIFx18Pc6WJjfj3w\/ceUNmo3BAGHMXqANasXkxzjDNz6hwXGF9xvmr9+PDLA2dd1NMnDyVZqRMXvb3Qrg2c7ESAJ8O+EbsizGLN6lXUcYy6HCBQ1k7NLd3u\/5EZ13vn7rbtKwfU\/tthNWRlRKCnwD2Xuf2CYTFo2SQRP6yth5w2T73at0oDV\/FHbrnSul17Ausv6WpQW2j1pJhm8aK6atGie1GleXZh0baX\/5W17crQ0c+57aIS0vbCLDpvTXge1ufSn705DFFb5hwbduW6r17iY1K8iVo7rKO97nnzyuYXrfT+5dqTMM3bbmCv2cfRbMMfh26dJfPrBG9i4bLZ2b1pDhPZrLczfMVbABHqtXOFshyAFQWDmRKgHwTTT7in5tdWTuymVK6Cjn9auVlfmXddNBwrix8TX\/42OmJgsrJzLFHL5poPjj01tly6yB3g\/8vHwfVq9QSkb0bC6\/3z8\/P5OA9SYMaK\/96omOZ\/OejCt8AzxU0Nv1GSl9r1igkVm+57uBU5ZrFILps+gnSv9QRkxeyvy23nbZrLDHGb4BxSHTV0nrnkM1OpvXb\/5LmbP9HmnQtof6jpHj6T9P3+XLFmwvFnCMO3wTlSXy1abXMJ0PnUYKIoxL9z6lA6\/hP+dH7stBHvTkQXp2gSfu8I3PZmy6Tdr2Hi5X7rxPP+NL+tryO2cMhxLnllc\/0r\/24svnHh7DIft+jDN8M0Xg4usfVz\/SYMH9qdlAD32safs8D3k2nl2mkvb5Jo1fAdxbJ6y8KJQk+HaZLfiPKcZIP2cgRe7HctXqqg+JiM\/cckf+eyhbSgJ83\/3mPtn75FZp0q6+nFu+lJT2dF6Fc6R6vcoydcVYjXLTL5x1l149W\/uAL9g+44hyolSS4Rv\/klGw4Zal0qZbc+1PT196Mglueu5qad21mQ50R5q\/83M2FVf4dlm6ZJTuvWq0XNjsAhnctYm8sC+vC+1XD62VelXPk3s3Tcyvi4eVE51yDL79ArQf3TVDererK01rVZD7t07W9GiAEvjOvrMPK+bwDfwRiS1\/zhka8X7rtiUKi6RwVClXUqYO7ihfPLBGGzkYtK5N\/coy0YPHsLIiU8zhm5QX+st3bFxdhng\/eP4nI2PXvKEK2T1a15Hnb8ib\/5sHwdi+baSu9yD4\/rGNWb0v4wrfRGqJ6tRteaG06jFYIzpEZRlwjQFxGIwJiAS4gZ3zKl4gXYdM1ghaNiuZcYZvGip6j57tgXVj2XgPA4B9lT+lWIXq9WXE3I06uvSsrXeonwFwjTh664WVF5XiDt9UuInGMjDdwuse0Ygsqfq9L5utfUX7T1yio0uTjdGk48U66BqjTAOXYeVFpbjDNw0SjC1QvWErmbR6n35GQ2et1YYgoGeR599519wvbXsN1xHQx6\/Yo\/4OKy8qxR2+8ceVOw\/JBU3aydAZa7z78zO918avuE6hkbmp5+9+UKdjZBDFM84+T7Nb8hqEstOwlij49gkI3+r9thnLYeSVm6TfuAV6D66+9aWs+s8pCfBNevmgCX2khFdfBLZ3HVonq\/ctlPa9WknJc8+S8YtGemCYB+CLdszwAP0cmb91WmhZUSnJ8K16Oy+tn4HqLh13sZSpeK4OXLfr\/vXSsksTGTlzoPavt9HOjxRBVgJcDHTcrWUtzYgGuD89tFrqVDlX\/8\/qmF\/5ymH4xuk4lVHsiCxWKlNCloztKRW9B4LBd+HCL7OGXyjtGlWV7x7JGyAM0ZjB6N3A47hL2uio8u\/esUxHPTf4Lij8dfOqMdK1ZU25b+vk\/D7z9POmIaN7q9o6BdnT183WNHSD74IqAN\/dB+UPBnbp5KsUvtff+bpCEZFc5gQmwlu5TlOFoGxW1hMB37UaKXwD1Yv3PCY1GrXRQero00iFkn7KKw48J7Wbd5KeI2fodmHlRaWkwDd9Qhde+7DeX0Rr67a6SC689Aq9N\/Ej65G+Wq\/1RdK6xxCNNoaVF5USA98NWsqkVXu9z5+rz5p07iuNO\/T2fu8f6jqIxo1GHXrpPUkfZqKTYWVGocTAd+O2MmTGatnp\/X6JfpOZwTNwC\/P3qx+\/1IyX9n1GSrlqdfT\/bDVMJhW+EVkENGa4exGRoZFt8EaJgO\/Xb5B6zWtpVJYot87p7YnILBHZM0qeJiNnDNTPC7ZNN\/guogBr5vQmCj5r\/UQdZK1F58ZS0fs7fNoAg+9CRDdOMlFhwY\/vWemxS1upUPpM7ZLMbE33bDT4zrMMwrcTg1gBNeumXSK1K52rw8vft3mSwXchwi9TB3fywLGW+s1Nw+YaM271AJw+FOO9m\/jhndN1uqwJA9odUU6kSgB837jiMunRpo48uGOqQrdbxqBrjLDPyPsM9sAo6Ix6XqeKwbeTg+86LTrrvLUMaEUlqNuwKVKraQcFbrcu38\/acqdUrt1EZm69XT\/7y4pScYfvXqNnyfkX1NeIN7A9d\/s9Oj0badRuPSqWG+5+S0dHbt1ziPraX07USgp8k0Ewb9f9moXB\/Og0YtC31q2nXSU8H\/cZO8+Dxo463Zi\/nKiVFPgmg2D8Vdfp7xsBkWStuPRyIIcGIXxepnJNWX\/X61kFn6TAd42GrWXglKsUqrknaaho2W2ggqNbl3uXEfhPOaOkrLnjFQVLf1lRKQnwjS\/W3P5qgedd3r33qY41QteIOdvu0QZLxh0hcyjbAJ4U+K7ZsJpc2K+t3PGqB4CHRzIn0k3Ee8y8YVKxRjkF8MlXXa6p6fO2GHwXVQA2\/b2X7Z6rqf4MxDbmymFH9K\/PluIO305k9MIwBLsYBR0OrFWptDy8Y5pmqoZtE61OAPhGruXjUQ901k\/rLx\/dszLr0zrlKwHwvX3uYKlV8VwdLIzB6hwQcgPjR+b7blCtrFzY9AKpW6WMjO9v8O0XPiLNhQaMpeN6yef3ry7gQ+7HZ\/bMkT7t60uXZjWlW8va+iAw+M6Tg+9aTdtrNGf0\/G0yfeOt0r7PKIVHoo1uXaI+pPky1zd\/Db7zpPA9apamQQ+evlpTfUfM3STV6rfwKuQ78tfD18A36aqk+FPR9JcTtZIB32u07yejIgOQpKJW9+Cn\/4RF+evljVPwmU7dVrtZRx2kzV9O1EoKfDOXd6f+Y2TcVddqH3DgmwwCP3yTSs3ga\/T9Xnv7KwbfPjn4prGxWZf+2pA2fdOtes817dSnQLcR7l26l5x6VilZdfBF\/a37y4pKSYBv7kcaHIfP2VPRIs0AAIecSURBVJB\/f+E7prFkjnTS9RH9vnuNnq2p5wB4sJwolRT4vnhkV6lUs4JsvPUqBW63DBBnADAGYqtSu6LUb1FLSpQ+04PvqQXKiFq5BN8IyMa3O+5dI2PnDZfNt68olv7eKCnw7UT9mvr5g9um6rTUnx1aXWAQ6ezpBIBvnE3LBunnzFm9dc4g\/UsfXCKUYdtEqgQMuMbc3YMvaiIt6laSVZP6yh+e\/GXyeVqP8Ns9myZJy7oV5eTf\/pfBd0CuhW3Z+N7ax4SpDb5+aJ1+79bRCPieudKvQ305r+RpmpVh8J0nKuJUHAdMXKLpp3VbdZF6bbpKuap1dEAhf0ovUfB+4xZ6lfh22oc5m32W4wzfVNInr9mv0ew6LT3\/tb7IA8Y2UrLM+TJ89oZf1vP8tfiGxxSCLhm\/SAHSX07Uijt84x\/m+e3Qb7SmmuPHWh7onF2moqbpu\/UAm\/V3v3EYJsdZ2nlAZFgQRewyaLznw67qR+5LBgZr2W1QPgDx2ydroGaT9joHs2a5GHzni\/uMEeNp5GEgsHrePcl9WapsZX0G4me37uZD7+pglHy\/NYvzzycBvnm\/XNC4jTY44hf8xvuD7iX4i7EcSOtnELvKtZtqw1u2s4KSAN8MCLblzpVSr3lNadSmrszZOEn7gecv96Dw5uevlnELR0iFqmXlP\/\/rPwy+0xTp54xuzrzqExePlumrrpD1Ny\/R1PNsQ3jS4Psvz27X4OtNK8fINo8F6UpL91kypLML4TkG3y61AIBxEMPw8czlPaJnCx1tuuzZp0uN88+RQR5cPnntrAJAlBUlAL5prHjlwEKZM+IiHS3+x8cLQqE2aHg3K+n7TWqWl0mXWp\/vML1\/51WyccYAGXhhY+8Hv+KI9BbuvRf3zdMU9PrVysgPAT9HrbjCN6IyTh9aUgAZXG3Cihs8aFwvg6at0IqTW491eo6aqSmY\/G8DruUJ\/xH9JmKzYPdDOgURI5oPmrJcP7v1gPR5Vx\/S9H5GUc52dCfu8A34cb8xZRsDrk3bcIuMWbRTBk1dITM335a\/HpX3Vbf+XgcDnLfrUIH032wo7vDNgIlkqdBfHggn6j12yTU6JRYR8Xz49n6\/a+94RTM0ZnrrcH8eWVZ0ijt840cahMhWWXLDEzoK97hl18qQ6atl9Pwtvuj2t5p9wRRZOsCd50fn46iVBPimkZF7jBkLuOd2kSUwZ6NGupmijfsOf2194APpffkcqVizkSw\/8GxoWVEpCfCtfZE92AYEuw7sKKNmDVII9M81TZT25heukXELRkipMiWtz\/dxCN8xlZs\/pfzGZ3Zqqnn1+lWkZOmzPJ+WkAsaVpWJSy4rkHmQDcUZvv\/q1a8BapflTN365QMLZKTHgjBg2VKnS\/XypWRI16by9HVzNCIeLCM65RB849g\/PbNNNkwfIG8cXOL9v1Wd\/t2jGxQO61UtI5tnXioP7ZgmuxcOk85Nq8vlF7fWKG9W53dLAHwrXHs+IVrLiOZMLRZch5uaufFevWmhvOv5MLg8UiUEvhkRnmj2B3evyLsfPZ\/5l\/OZLIIP7l6uA7Fl98cfb\/hGLiJBRYg0QWCSdHR\/30WWAUab73tX181WBRPFGb4RvqAy7gYQIp0X\/zHYVf46ni\/5jmga62TTfyj28I3Uj98o9OT58XPt+sBgV24d\/KaD1930vC7PVpTRKf7wjb7V+y3Pj18e9uMn2lferYMf+f6q\/U+rf7PZmIbiD98oz480lAHV6seHP9F70v\/75V7lfuS5mU0\/JgO+Pz0M3\/31vcFvl+ntyCag6w33qPrZ8+fUdTdL2Sq15Mpd9xXwb9RKAnwjwJD08hue2KrzUgf7Ht\/jgTgQydRYpKYfeHZXgeVRK8nwvfy6K2XJ1bPl4O93a1T7rjf3yrJr58j51cpJl0vay6IdM3V5t0s7ambBwu0zjvB\/lIorfMN0a6ZcooFX6tUwDLwy6dIOUqPCOYdZcKpct3i4XNSipgzt1izLHJNj8M2Q8syj3LTW+XL\/1ikK4y\/snacjcl89f6j8+PgmvQg\/PblZ9i+\/TDo0rib3bp6U3fTzBMB3qiJyi++yOzm9p4TAdyrivsWPgHpYI0eUSgJ8\/wKOjG7+hX72gw2VIQVMr7KEsl05ijN8IyqWzn\/qQ6+y\/kt0zJPnr7yKfF4jR7ZhJxHw7QmfOWDMuxc9P3o+86\/zix+\/KujjLCgZ8H3Yj4eBMc+PeaNJAzpuneL2Y\/zhGz\/ybMxrlHR+DD7\/fmm8zJtT3e\/jKJUE+KZhh2nvmFFj5c3Pa+NtvysWSKP2vWTLofcP+ytvXcYSYfC\/WdvuzPr7JQnwnaqAR\/qIZz81OrnwzfRtlS6oIGPnDdORzskgYPC6hm3qyra7VmkKOmn+RMMbe9917tfW4NsTmblEtBtfUF4e2DZVZ2t66+ASad+oqgZof3hso3ILQbEDKy\/XWZwObZ0cWlY0yiH4RjiTdOnGNctLjQqlZPOsgXL7unHSql4lTTcAboAdWkKI2DLd0+6Fw\/XChJUXiXIIvrmB10zuJ1dNuDh0eWTKEfgmM4MMg4e3T5OeberolGR0nQhbNwrFHb6pVJIK3WfMlTqVziUTFsmyfYcjYocrQVQsp284KDWbdtA0TD4Hy4lKcYdvIIb0VAYVatN7uHQZPEGmrDugfRddAwaVeKYi63zpFdJt2NQC0dxsKCmRb+aQv3zxTml78UjpeMnlMu6q69RveY0VRMjyximgC0SLrpcWiOZmQ0mBb7qGTFx5g3QaMNbz5Qi5bME2WX\/Xm3mwQ0OQJ0BywMSlUqNxW42M831YWVEoKfBNtgpQeNGQSdLW+20Pm7VOZzVw6dKsgx9JpT6vYg1dP1sNa0mAb3zTpFNfOf3s8+S0EqV1DAcGpzynXBXZdG9eFpXLMBg4ZbnO6b9031NHlBOlcg2+r3lwg3Tp30FWXD8vdHlUSjJ873lsq6bzn3H26dKxd2sdZG3A2N7SfXBnr26wOy+rwINtpnkbOvkSadyuntz68rWhZUWh2Ea+PdZ76cYF0qz2+VKlbEnZdDjruWPjajrFr8tERXT95Pv9V43OYiAxx+AbRxKJffPWJTp9E\/1oh3VvJnWrnKcRbhyOc5n6iQvQo3Vt2b98tEbMw8qLRAmA7\/9+eot8\/+gGTdn\/9pHCRcr+5IEdZMqgjqHlRKaYw7e7D8m0CPPbL1ovXz241vvRX6bdImjMYNuwMqNQfAdc+9ar\/HwlC697WKd4Oqd8FR0lmRGnK9SoL2OXXq0wBDhSiWI6HZbNv+ZB\/RxWZhSKM3znQfVbHggOkLNKl5fy1erqgHVEcC4aMlGW7X9afUW0bM1tr0iDNt2lnQeWCjsh5UWluMM3lW8iYQy8dHbZStonFF9yv9EgxD1KCiuVdVJ\/m3cZoNE0YCesvKgUd\/jGj\/iEQf0YNJE0Xn7TzNvfuEMvmbvjHk2b5r6l4YKZDRjtXOenNvjOF77gfqN\/N79l7kP8iE9rNmkn0zcdPDy4Wl43CAYFPPn0EnnRXM+3YWVmWkmAb36v3I\/L9j+lYw70n7BY2vUZqQ0ZfO98xT3ZbegUbSzieRosJ0olAb4Bv1tfulZuev4aHQTsaFp30xKp37K2LNg+PbSsqJRk+KY\/Pb4j2l3O4xjmVL\/o0o7SrmdLuf7xrRr5JhWdqPjFI7tJ886N8vrch5QVheIK364O\/s7tS7WPN\/Xry\/u00kg40yX\/4cnNGvgi4\/SJ3bOkTYMqOhB39sYAyzH4Rm4qpy\/uXyPrpl4ijWqUl1N\/92u5uF09nf7p43tXaovI3JEXSdcWtXTQtaz2tY05fBONfWj7VFkx8WJZMranLD6KZg\/voqN52zzfBcWP+s2Di2XzrEtD\/ZavMT1k4eXdNT2mdmUb7dyJijoVzM4DrpDzazbUaYlW3vKCRnoYdRoIumT8Qu2bR6T2soU7NDIx\/5oHDL4PCz8QVaRy3n\/CEh24btF1j+gUTlXr5Q00RFYB662+9WXt69ju4hFa2QwrLyrFHb5JL2fUeKZ26jZ0qizd+6RGwIg01mza3vNbV5mz\/W6NejMyN9M\/1Wlh8B0UEdm5O+7Vefrb9h6hv9UVNz3n\/Xa36+jnzJs+ec2N+runAYiGIOBy6\/0fGHz7RGMZ\/eEbdeitmrXlDllx8\/M6\/V2TThdLpVqNZMzinerD7Q9\/qqOiA99kuxh8FxT3FRkrvG\/wDdLPvvuN\/\/nNrz7IVGPZ7QKRBPgG\/GasmSBDp\/SXIZMukcGT+hWqHoM7S2md59tGOz8e0cBBuj5zezdsXUfOPPt0KVOxtIxfNFJ2P7hRdj+0UZZeM0cq16ooAyf0sbTzw4IFiYAT4FrrsWCD6uXkzFN+K91b1Vbg\/vieldonfIFXByc7GhYMKyca5SB8OwFARG5JOwduKpQ+Uzo0qiajerWQvu3rS5v6lWXL7IEaffxbNvvaJgC+GaGbUeHLlDxNWterrH3jOzapfoS4YcucfZpMtNHOC4jsikd2TdeR4M869bea+lKYD9s1rCr1q5WVOgbf+aKf57YHP86btmngeI1+UTECFEn1HTR1uVTyYIgBcqh4Mg\/4uecbfPtF1KvbsCkKgqT14hcACCicuv4mqdeqi5AevfDah2XlzS8oABl8HymgmpHNazfvJIuue1Q\/A0DAzZwd9+h0WI096Jm55XbtN9rswks8n3c2+A6I+2\/cst06TRsj7xPdxo\/A9qI9j2oKOg1AE1Zer10lAPQylWrKFoPvAvI3Yoy6crPeh0Ah9yW\/44sGT1Qfj5q\/Vdbe8Zp0Hz5NTjrtrMPwnR14TBJ8u2ci3SFoPPOn7Tvxu2aGiGw\/GxMB32\/sla6XdpSTTv2dnFP2bKnVqLpOOxYm5vo++bSTbLTzIsgBOP28+4\/tLZUuKC8Va5STdj1aSoeLW0v1elWkfa9WmpZOKnpYGVEozvCN3AxY3z3yCwuWK3WGppnDgv06NNB+4Mz5\/fXD60LLiEY5DN9OQDgjdl+\/ZKTOt8z81URsb141Rr54YE3oNpEqAfD9+s2LtIGi1Jmn6OAET+6epUPxP7OnoA5tmezdzE009TysrMgUc\/jmx05r25wRXeTcEqfqlG2PXT1Tuzr4\/YdPaYFbM6Wf1K16nsH3YVFJJHWyVrMOCpA6Z\/LhChGRCT6PmrdFKtRoIF2HTJJLJy+T0udXN\/j2CajpPnyqRmZJ0Qd03DJGO2fkXiK39KslsmvwHS5GiAe+mZeaCBiVc7eMgcMWX\/+YNOnUR6o1aKlTjwHjBt9HysE3c\/YzzVje7zTvN829SRS8fd9ROs8ymS6k\/5K1YfBdUNxzpOhzj9HdBuh2fgTC197xqvQYMU0q1mqkUzPSXeKk0840+A6Iewrfzdx8u3ffjZamnftJp\/5j8+5NBfBfsgSYXrBB2+7auOEvI2olAr7f3CtrDyz24K+yDgw2beVYTS9HzD3t16x1E3R6rAXbLO08HZGGvnT3HBk65RLp6IF3t0GdZOz84bLzvrU673rYNlEp7vDtF3VruspevzSPBWGXmcMu1HRzZnbKXso5OgHgG4eTekA\/5i8fWCsf3r1CwYjP2etc71MC+nzTV+LVmxZJ09oVpFOTGvLGLYu1Xzzp+X45wJw+pFNoOZEpAX2++SHT6DOqd0vt+vDorhl6zwV9iF9pkWO0xZ+e2KQtdWFlRqH49vnOG7yKvnYVazXWeVeprOdVHvNGN2f+1dHzt+pyKppnnlPW4NsnIPEKD3ZIxx9x5SaFagfg+Bc\/kYZevWFr7Qte4YIGGm00+C4oHdBv40GpXKep9B23QGGQ76i840f8vGzfUzqfMv2Yq9RtLrWbdTL4DogxHBbsflBqN++s2Sz+wcEQ9yZwA3RzP9IoRH9wg++C4tnH9GFNO\/fVriPMPU3XCO5F\/KQAfvsr0n3YVKlQvZ42Cv3m5NMMvgPi3pu97S4dw4GxBciyKlctb0yMPmPnyfaHP85PM+c9U+LcCjqgZ7CcKJUE+CYiSx\/jZdfOlYoefPcc2kX7IvMdUXG\/tt29Wpq0byCLds4MLSsq5Rp8M1o8\/gXC9zy6WW54Ypv2+ab\/dzZTzlGS4BsRjHUs+NE9jgW3an09m4GvEwK+Y6cEwDcCDF++cYE0r11Rds4bqkP3B9dh0IK7NkyQO9ePP2JZpIo5fDvhQ\/qV0MeE+QX5HFyHhqE3blmk4xPwUCDzILhOVIorfBPlpqII1JSrWlsjYJcv3H44ypO3DmnopAmOmLNBzipdTiuYpAZSES1QVoSKM3zTj5F0fSKxp55VShh4jQaL\/HU8HxPhWXXLizqo3W9OOlUHHNIsA185USsJA67t8Hxy4cBxOjIyEcfNh94tAIRU5AEe+i3\/+nenHI58Z7cRI+7wndeg9pn0n7BIf6\/4asPdb6h\/3ToAOF0kAMtfn3SKNhzZgGsFhS9oOON5WLLM+dootPj6RwuANQ0dZLt06j9GU85\/e\/Lp2ohhfb5\/Ee8SuoiQaTF\/94Pe7\/dVzb4gTf\/UM8+WrkMnawMaPhsxd5OccXYZzXIJKysqJQG+nRh0bfrqcdLUg+uVN8wPjcDue2qHTFp2uey4Z80Ry6JUrsF3nJQ0+I6PDL6zr4TAN61ARMBJzQcaw1qFGNiOZQBkcFmkSgh8u6yLrx7Ia10L8yHf0epGFkZWxx7wFFv49qSVTKKK+5\/WfoyjF2zTynv+Ot5yKvREaofNWqtRHp1q7HB0NxuKM3y7aXKoQA6atlJadhvoVcDfK7CO8\/HyG5\/REbovGjypQANHNhR3+Eb4ib61dHWgXzID\/fmBkP+Jhm+67x1p1L6nprCS9u8vI2rFHb4RfqKv9\/jlexSw1935egH4ZjnRRqK0zS\/qL1XqNS\/Q5SQbijt8I\/zEQJPTNhyUVj2GaAaLH77Vj55fAe7OA8bqNFo0VPK89JcTlZIB35\/p4HTdh03Rxgx+vzSiMVYGGUMlzjtfugyaKJvve0\/T9\/Pg+\/HQsqJSkuCbaGzeqOe7NBU9LAKr83y\/4S17K9vRWYPvqGTwXVQZfGdfCYFvRBQ2m5HYlJUQ+HYilTyb6eSpKs7wjVxlHED8Je284Dp8R0Vq+YHn8gdmC64TleIN33nCP1QstYIZ0jCBj6l0brz3bVl18Pe6bnCdKJUE+EbcV\/l+9PyF3\/zL8\/z4lWYXkArMOv7lUSsJ8I2Abe7DwvxIoxHLdzzyiSzZ+4SuV3B5tEoCfCPt8qB+5NlYsI+yE89OGoEWenCOH4\/0dTRKCnxXq99C+8TTkOHeG3kZGp\/rnP5kBAHnfcZc6cH3ebJ4j0W+j6osDvR1PDL4jk4G30WVwXf2lSD4jq0SBt9xVdzh+xd5lcajVRy9ZVQss1W5dEoCfOfrqL4pHv+hpMB3vo7ho1\/8mF1fJgW+83UsHzk\/6nohyyNSUuA7X8fyUTH4MRnw\/bkH3uOlcp0mOqYD2RZuGQBOhgap\/YwnwjzqJ51+lo7K7y8jaiUOvmMqg+\/oZPBdVBl8Z18G3+nL4DsjSg58x1OJgu+YKnHwHVMlDr5jqsTBdwyVBPgma2DRnsekQbseUrV+Cxm\/\/LoCmUE0WADko+ZtlrJVa8t\/\/tdvrM93QmXwHZ0Mvosqg+\/sy+A7fRl8Z0QG3+nJ4Dt9GXxnRgbfmZHBd\/pKAnwD13R7WHjtw5pWznSLfvh269BXfvSCrVKtQStZfuOzBZZHLYPvzMjgOzoZfBdVBt\/Zl8F3+jL4zogMvtOTwXf6MvjOjAy+MyOD7\/SVBPhGDsA3H3pfITusGwTrMJbIVfuf0cHYgsujlMF3ZmTwHZ0Mvosqg+\/sy+A7fRl8Z0QG3+nJ4Dt9GXxnRgbfmZHBd\/pKCnzHXQbfmZHBd3Qy+C6qDL6zL4Pv9GXwnREZfKcng+\/0ZfCdGRl8Z0YG3+nL4DszMvjOjAy+o5PBd1Fl8J19GXynL4PvjMjgOz0ZfKcvg+\/MyOA7MzL4Tl8G35mRwXdmZPAdnQy+iyqD7+zL4Dt9GXxnRAbf6cngO30ZfGdGBt+ZkcF3+jL4zowMvjMjg+\/oZPBdVBl8Z18G3+nL4DsjMvhOTwbf6cvgOzMy+M6MDL7Tl8F3ZmTwnRkZfEcng++iyuA7+zL4Tl8G3xmRwXd6MvhOXwbfmZHBd2Zk8J2+DL4zI4PvzMjgOzoZfBdVBt\/Zl8F3+jL4zogMvtOTwXf6MvjOjAy+MyOD7\/Rl8J0ZGXxnRgbf0cngu6gy+M6+DL7Tl8F3RmTwnZ4MvtOXwXdmZPCdGRl8py+D78zI4DszMviOTgbfRZXBd\/Zl8J2+DL4zIoPv9GTwnb4MvjMjg+\/MyOA7fRl8Z0YG35mRwXd0Mvguqgy+sy+D7\/Rl8J0RGXynJ4Pv9GXwnRkZfGdGBt\/py+A7MzL4zowMvqOTwXdRZfCdfRl8py+D74zI4Ds9GXynL4PvzMjgOzMy+E5fBt+ZkcF3ZmTwHZ0Mvosqg+\/sy+A7fRl8Z0QG3+nJ4Dt9GXxnRgbfmZHBd\/oy+M6MDL4zI4Pv6GTwXVQZfGdfBt\/py+A7IzL4Tk8G3+nL4DszMvjOjAy+05fBd2Zk8J0ZGXxHJ4PvosrgO\/sy+E5fBt8ZkcF3ejL4Tl8G35mRwXdmZPCdvgy+MyOD78zI4Ds6GXwXVQbf2ZfBd\/oy+M6IDL7Tk8F3+jL4zowMvjMjg+\/0ZfCdGRl8Z0YG39HJ4LuoMvjOvgy+05fBd0Zk8J2eDL7Tl8F3ZmTwnRkZfKcvg+\/MyOA7MzL4jk4G30WVwXf2ZfCdvgy+MyKD7\/Rk8J2+DL4zI4PvzMjgO30ZfGdGBt+ZkcF3dDL4LqoMvrMvg+\/0ZfCdERl8pyeD7\/Rl8J0ZGXxnRgbf6cvgOzMy+M6MDL6jk8F3UWXwnX0ZfKcvg++MyOA7PRl8py+D78zI4DszMvhOXwbfmZHBd2Zk8B2dDL6LKoPv7MvgO30ZfGdEBt\/pyeA7fRl8Z0YG35mRwXf6MvjOjAy+MyOD7+hk8F1UGXxnXwbf6cvgOyMy+E5PBt\/py+A7MzL4zowMvtOXwXdmZPCdGRl8RyeD76LK4Dv7MvhOXwbfGZHBd3oy+E5fBt+ZkcF3ZmTwnb4MvjMjg+\/MyOA7Ohl8F1UG39mXwXf6MvjOiAy+05PBd\/oy+M6MDL4zI4Pv9GXwnRkZfGdGBt\/RyeC7qDL4zr4MvtOXwXdGZPCdngy+05fBd2Zk8J0ZGXynL4PvzMjgOzMy+I5OBt9FlcF39mXwnb4MvjMig+\/0ZPCdvgy+MyOD78zI4Dt9GXxnRgbfmZHBd3Qy+C6qDL6zL4Pv9GXwnREZfKcng+\/0ZfCdGRl8Z0YG3+nL4DszMvjOjAy+o5PBd1Fl8J19GXynL4PvjMjgOz0ZfKcvg+\/MyOA7MzL4Tl8G35mRwXdmZPAdnQy+iyqD7+zL4Dt9GXxnRAbf6cngO30ZfGdGBt+ZkcF3+jL4zowMvjMjg+\/oZPBdVBl8Z18G3+krcvj2Hp3\/BL7v0+uVq\/rn6wcihW8qDnufy6uM5aIAkYc8+OZcw3yQjhx8H\/TgO2zfuaK7DsN3lNCIH3P5PkTZgO9XP8lrxAAKwo4hF3R\/NuD7vR\/02ZGLfuSc0AMG32nL4DszMviOTgbfRZXBd\/blQY\/Bd5rKAnzLP\/8q\/\/rwYQ9Q98s\/X8tRvX2H\/O9PHx3Xjz9V+KbC8Oz7P8jNL34vB17ITd3k6bF3ftDoapgP0hH+e\/\/LnxROw\/adK8oGNH7w5c85fR+ih9\/8Qb74zvNjiA8yIfz4+qc\/5bwfH3krWvjmPue5yLMjbP+5okfe\/iGyexEZfBt8pyqD7+hk8F1UGXxnXwbf6Stq+PYenESD\/\/3XP3g\/jh9zV3\/9WRsZjuc+TBW+qRx95cHAZ9\/8JJ\/msL747qdIwJGK63ceBHz2bfh+c0Wfe+f3w0\/RQSPX5rsfTgw\/Ao2R+dET+8j93\/PPkXQjccKPX+T4vYi+9PwYdv6ZksG3wXeqMviOTgbfRZXBd\/Zl8J2+Iodvv3GNclnHZ6nCtxOVzVxW2DlnWmH7zRWFnW9UCtt\/rijsfKNQ2L5zSWHnHIXC9p1LCjvnTMrg2+A7VRl8RyeD76LK4Dv7MvhOX1mFbzO\/HS98m0wmk8mUSfnh+7oQcE26OKfrDb4zIoPv6GTwXVQZfGdfBt\/pKwfg+9\/HuPYsP9Y6xWFxh++ff6b\/8NFTHo+1PJeVyrmn4r8T1YeZ8s2J6j+UCf+k4udc9XG2\/BdnAd8M6nbj89\/J\/mLSvue+Df0+UzrwwnfylMF32jL4jk4G30WVwXf2ZfCdvmIK38Dyv\/71r3wBqkHjO5b985\/\/LHQdXqgs\/8c\/\/qHrhEE467j9pPcCPj7LNHxTAfzxxx\/lhx9+UP3000\/HXCes0sh2LPvuu+\/k++8ZaTd8HcphOX+Dy3NdnD\/n7vwc5iPnH9bh\/+A6fMbH3377behyt467VoWtEye5e8cp7HjdOs43wXXcObO8sPuLdfzl8H9wnVyXu7\/4G3b++Mitg5\/C1uE77j\/uQ\/4v7Hr5ywhbJ4niXDjvo50X\/jvWOvgGH7JO2HK+YxmivDj6j4EaP\/76+PTRVz\/J+59\/J+999q188MUP+vnjr9Ev63z41Y\/ectb57vA6PxZYjj744nt5++OvdJ0Pv\/zxcDnBdX44XMb3uk5wP8fSJ57oO19YGr\/Bd2oy+I5OBt9FlcF39mXwnb5iCt+8CN98803Zvn27PP744wrQzgBowPXPf\/6zPPnkk7Jz5055+eWXFbCD9re\/\/U22bdsmY8eO1eVB+Hbl7Nq1S\/bu3asv4WxZpuGbit1rr70ma9eulbvvvlu++uqrAsup9H3zzTdy\/\/33y8aNG+W+++7TbfzrICqbe\/bskbZt28onn3xyRGWRSujXX38t119\/vfrt7bffLrD8RNDHH3+s98vVV18t77zzjvrELcNf+PX1119X\/2zZskX9HubHRx55RFq3bi1PPPFEgTIQ61Oxf+aZZ2T9+vXy8MMPawXev07cxPEeOnRI78HnnnuuwPFyPpzjl19+Kfv27ZN169bJ008\/HeoX7l1+s1dddVXoOfMdzwf8e\/PNN8tnn312xDq5rldffVWfj\/iS36zfj\/gQHz377LN6Lfg9s45\/e8T14j4eMWKE3q\/+Mtz1+uCDD+SGG27QMvg\/eJ8mVV988YXs2LFDrrvuOnnvvfcKnBfnjv9eeeUV9THrfP7550fcq3zmHu7evbs88MADR\/iG5fj4wQcflA0bNuj7KuyZm0RxrrfeequsXr1an1HB8+IzjRL79++XzZs36zph986HH34oCxYskGXLlsmnn35awMf8zzZch61bt8ott9yi1yV4HdKVwXdqMviOTgbfRZXBd\/Zl8J2+YgrfgDKVvbPPPlumTZumkOoMaP3LX\/4iN954o5x33nnSq1cvBSC+DxpQ3rJlS9m0aZMCvB++Wf+vf\/2rLFq0SE466SSpW7euQlVYdDwKyzR8U7mmcnLWWWfJ5ZdfrhVKt4wKDBUhKpGVKlWSZs2ayfPPP39EhYlKDb5s3LixjBkzRrcJVob4jkrrKaecIvXq1VOI95dxIuiFF16Qjh07SsOGDbUxgwq2W8b\/L730kvTt21fOPPNMbejAz0E\/cr369esnderUUZ+6ZW4529CwwX3JNZ0\/f75CvH+9uAlonjJlih4vjV7+4+UeBLxnzZqlv+uuXbsqNPv9ghwQVqlSRRuRwu5RIHDSpEl6D+JDQNS\/zomgAwcOSI0aNaRz587qR7+fuJ8eeughueCCC6RUqVJyxx13hPqR68GzYOTIkUcsd9eL+xc\/t2jRQp566qnQxpAkisabmjVrSqtWreTRRx8tcF78NoHqnj17yjnnnKONPMEGDv5nm4kTJ0rt2rX13g+7l3lWnHvuuXodVq5cecRvPanifhk4cKDeG7xf\/c9A7h3uSaD69NNP12chv9mgf\/jM+4NnHM+L4HL2wXY0Dv3ud7+TPn36aMMv5fvXS1cG36nJ4Ds6GXwXVQbf2ZfBd\/qKKXz\/\/e9\/l2uuuUbhhUo2sI0BrESz7733Xq3wUHEkqgBY++EbgCaNnBZ3AJGoDi9XP1hT5m233Sbnn3++wgIVVV70SYVvQIcGidNOO00rK0A031OhocJy++23q784T6KFrB+sxPAZsK5YsaJGZalQ+StEVByJbJYuXVpKlCihlVcAyV\/GiSAiim3atNFKI5VH5ycq42Qf0PhRtmxZmTx5srz\/\/vtH+Jn1AJmqVavKihUrClRcEevTeDJ48GCtvHJ\/zp07V6+jf724iWjihAkT5NRTT9XfnjtefEPDFlFYoBrgwU\/B+4v\/gZguXbpIu3btFP78vuN\/7luyXYAZfEPjG41sbp0TRUS8K1euLO3bt9cMFUAF\/+FTfrv4r3z58gpG\/G79fnTr8dtlHRo7gtcB2Lzzzjv1N\/7b3\/5WmjZtqllIwXs1qeKdwL3IebmsEs6bv0RahwwZor9hfnf8hv3+Qfj797\/\/vWauTJ8+vUBDE+vib+5x7mWelfyGly9fXmC9JAs\/XXLJJfKb3\/xGM3O4xzhv\/AJ4r1mzRt\/f3Icu6u33IZ95XhDxpoGcBhB\/+azLfc3zkffRr3\/9a+ndu\/cRz4RMyOA7NRl8RyeD76LK4Dv7MvhOXwmCb6AYyAZaAG\/AB3gmeh00wJaK\/\/DhwxVEqfD4jbKIbDRv3lwuuugijcJRycw1+HaVISrjRK6qV6+u4FJYCiUVG6IZVJjC0tbxGdBJgwYRx1q1ahl8H4ZvKoSkULrILtFEKvj4P7g9vp03b15+wxAVWbcMP7PcRY2GDRumDURJhW\/Oh7+k6AOLgDdR2SB4I3xFCj6wQuXd7xfEZ\/zN7x\/\/c08bfLfPh298SkYLEUIayJYuXarPhSCs8JlnAL9htn\/33XcLXAuWA6B0Palfv76uAyDlOnxz3oA20Wxgedy4ceqboP8QfiWVvEmTJppyTmOFW4YvuSa8u8qUKaONcETQTwT45r7iHVOuXDlp0KCBPPbYY0f8jt32\/G55\/+In\/OWWUQ732U033aTP2G7dumlDJfe1wXfxyeA7Ohl8F1UG39mXwXf6Sgh8\/+lPf9JItoM\/Kp27d+9WKA97abI90fEOHTponzMXOccAeCDpsssuU\/im4tS\/f3+t0OcafFPBoTLeo0cPjXARRSACGQaEVHaIalMZpVLpT4+kHMrDZwA8+6E7AD4z+L5PfQ8wL168WNP6qSS6\/p1BwEREzAAaKuWAqb8yyWe6XFDZ5DqSsUDkJ2nwTcQVn3DMZFqQdUFlnAo134dVoPmetHXuMeDPf59yf+I3gJCy6EIBeBt8t9ffNPCHz7hn+J7fJ9kTYfcg3wGcADrZCP7fugPQUaNGaVo7YMXvnkaTXIZvfsP4kSg2aeJknZAyjj\/CfsNvvPGGDBgwQP0NoPvvVQCUxieej5RH32i6SPH8zVX45neOGAuErjQ0SpA5EUzXd+L7a6+9Vrs40V3K33jBPUa0nPcW3SqoC\/CbJ33d4Lv4ZPAdnQy+iyqD7+zL4Dt9xRy+zzjjDI1C8IKkjx6t5MAlg+DwXWGgTMXgyiuv1MgOlSTAHWN9XuwM5NSoUSNNsabCQIohFYZcgW8i\/vgLUYEhkgi8UUkM2xYBTvjMpQn6K9mkEdJfsVq1agqYRCnmzJmjPjuR4Zvzv+eee9R3wCaVduDwaJBCRZT+jYANjR3+yj1\/+Q7QIRuDhhPAAEhIGnzTVxgIIfJFBZvMEiJi3Eth23LunC\/96AEWztXvF36bo0eP1ggilfYXX3xRK\/8nOnzze6UxEf9MnTpVsy6AZZ57fiD0i+eji8ryjHAwg58BccYX4JnBbx7fXnHFFZpenYvwDSTSdQnw5tlGg2+nTp0UvAvzH34CGGl84z3lABPhS\/rY09AEwDP+A89IUthzFb4ZPJHf9V133aUN2viV+5N7BZ+Ebc\/vm98u\/ep5n\/jvQZ4jQ4cO1cwgGs\/JdiPzgve5wXfxyeA7Ohl8F1UG39mXwXf6ijl8M5jLxRdfrH0SeUlTsVy1apW+fAt7WQLPDMBEpZQ0P0YzB3QRKepUjACf2bNna6SNF28uwffJJ5+s\/QwBPHwHjDNyNOBNhSlsWwRQEmWYOXOmVkTxMRUhtmFwJ1LMGYSNSj0VIIPvNpoOTkMOKeSkWeIPIuFUxsMqiHxHRROIBK7feuut\/MopfgYISDOnXz7l4Gf6QiYNvhkciUYzfsNUmvENv1tGMy4MaPANqeYVKlRQ8MEfDmbwJ2BE9BAgxIdAzYkO32RZAID8DyADeGRduJHmw8AH\/zOQH3DIfejShVnG\/zxryTwYNGiQQj0ZL7kM35wr9xRZKNynRMKBvcLAkfuR+3zhwoXaSEY3Cf9vmEahSy+9VCGU7Ct+w\/zNVfj+z\/\/8T70\/aHzknGmgZYYHYDzsGYivnJ94fuJ77km+Z32ecTwrWEbXGxrwWNfgu\/hl8B2dDL6LKoPv7MvgO33FHL6pxDMSOQDJoD8ANS\/1sGnDML5jmYtKADB8h0g3B0CpRF544YUK6LxwgfNcgm98xuA0RB\/5n0qMi2SHVSZdpYc0fholDh48qJ9dJYmKPFPpkPbnBmGjgmTw3UajPtyb+Pm\/\/uu\/FMSD0+X4he+4J6m0Ey2iEs\/3rM92S5Ys0etFKjCVTqCTyHHS4Bu\/4BN8Q2OQ+725+yq4Hd9zvoA0mRpUsN0yfEDaOvcaYMnvHz+SYn2iwzfdEXguMjYAPicSTtqv339BAdg0zLEt4OieC1wDukpwb5IVRESc3z8p6LkM3\/xuiXbjR+5ZGh+4j\/FH2Hb4hN8\/\/ZBJ7f\/oo4\/0e9an0ZLsIbqMkPnBdcBfZLPkKnz\/x3\/8h75r0K9+9SvNumKgOX63Ydtxr+EDxsagkZFGNL5D+IrGcbJb+F27ge5Yx+C7+GXwHZ0Mvosqg+\/sy+A7fSUg8k0aL1EGXr6AOBEZXphhL0u+A1CI0JLyR4UeA3TZhm2BcvqisQ++zzX4BnZIpZwxY4YCIiCOD+n\/SYUpuB0VGSJcpKFSoSTK4CpDVH7Gjx+vlUmuB\/tgff4afLfRtF3uNQZXowLPCNz013ZAE9yOSj2DYNGIRDq5W4+KKn2hifpSHtFGokFJhW9+p4AyIEK6Ob9jIuGAc1jkm\/OkXywp5zQCuT7I+IYoJNO6AYQ0BOEz7mOD77zIN79N0sTpDwsA0UhGGrWLJga3AxbJiGHkaK4X6yF+64AT2QX8pt29mevwzW+OZxz3Eqn2ZFcBy4WdJ79BxhvAz2QEce\/iJ+5ZfsP0o2egNkAcv1JOLsM3wM1vncwBfus8B3lfc\/5h2\/H+4PlGIyN+x5\/4Dz\/xO2aAP5bx+3bvK4PveMjgOzoZfBdVBt\/Zl8F3+oo5fBPRoSLDi9lN6wJcEiHkxRwEZaLeVNCpGNEvnGnJXNSbfqJUTqkokMrL4G2I\/+njxwufqK+bMzhqiwq+OUdSl6m8IHxGhYh+oKSbUtHxV8rxLZV1Bm5i2hcq5Cyn4kh59Lunrz0VS6K2zGtNP2caLIiekSqMDwEr\/\/Hkshx8k4pPpAagwXclS5ZUgCTNNFjJxqekU9PAQUWVBg8qkfiZKCMp\/wyKR\/ScyjoDAVLO1q1btS85\/uYz0BDWiBIHOfgGtons4xfuLSrl\/L5Wr16tKeP++w8R9SeKCGTzO+f8WIfGMyJklIfP8DX3H\/6hkYNGJSK1\/E8UF1\/6y81lOfjmPiSjh+4gTHHHM5O0ZxrRggCJT2nkoAGSRg4HjgAQqcI0JgHlZBpw\/yH+5zsa2oiYcz3prhO8hkmTg2\/GI+C5RiMDfeZ5VtLQQxYA\/vFvwznTiMlvkcHW6DbCPYe4BviVa8K9z32K\/yibz4A9DWvcu2wX199wquL4gW8ad\/ld81unMYLuDDRA8P4OG1iR7RigjWela4Dke94fvKPIluE68I5x9yCNHTxr+b3TMMS1yWQjhsF3ajL4jk4G30WVwXf2ZfCdvhIw4BoRWaLTDJrGy5qWcaITVBbdFGTO6NNN\/1tAktZ1XqgsB8IZxAkAQFS6nKgsEamj7xowSdorcBW1RQXfVF4YgRfQpqJDyjmAQuUP3wA6\/goRgENEhooNFUYqQ1Qy+UvfO\/pBInzjhA+p5OMzwJAKLNfGfzy5LAffAAlATNSLiiaVRiqeNOYQsfYDChV0KqeAKA1BbhnXCCinwg\/84FvuScT\/+JfUTq4r\/SmJnMe1ocPBNw1AbrRzBChy3pwToMy96vcNEVX8SR9Pzo37E3EPM14B0VgilNx7lMFfIomkCZNuzf1JNkEmK+RxFz71j3bO7xXgpnGRtF38xjPQrY+\/uU8Z04EGIpfuyzIaRNxI\/e637u5BGoRo\/ACyuD+552nUS3pDh4Nv+ngz9R2gjR+I\/gPgjDHC79y\/Df6ikYd7mUYy9xzlNwwQ0m2H+zL4G+Z6\/N\/\/+3+1XNbxdzlJqhx88\/sDpvntuS4NnDfPKhqz\/Q1A+I\/3Dc9HGoVd1JtlNEBSHr9z\/28dcd\/RPYDfO\/c8Y5r47+10ZfCdmgy+o5PBd1Fl8J19GXynr5jDN5UV4NtBNhBNyzd9xagEEpUBzFkGzPKiB2KAIMrgewS4U5EHTqm0OtG\/DxAiUk4Fn0oEkQkqYlFb1PBN5YSKDeeCz\/ALgwvRaOH6JSOiMERdiZpR+aRCyfdUrum7x3XYtWtXvhixmmgs\/cDxGY0a+JKU\/bDjykU5+HbjCnDfURl1sEj6OZV40ij5Hp8SGWIaLSqOjOrtymIZwMmUYn4\/I7I3SN2m4QR\/Mzo\/2RrBiFxc5IdvN8839xH3G9PXUaEmfZQGC86Bc8d3nCcjG+MD1nf3JpV5wDzoF\/xApgH3NI1xgBDjPODrsOPKRfnhm98tfsNfNIKRqUKjDUDNNcHP+IasIDIvuA+5H11ZXAMagGgYCfqa8QfYB6BKejtRSFem\/3iSJj98uwgsPgQC6bJEAy+\/ZZdpwvniX+417jvGv3BlsYx0aK4J89n7\/ce9TYMHz2Xgku\/4\/bM\/\/\/EkTfjED9\/4ht8sDUEMokYjBFFwMiXc84pzJnvFdWPy+4DtafwlI8PvP8RvnXudRiPgHqinUc9tm64MvlOTwXd0Mvguqgy+sy+D7\/SVIPh2BoBTSeRlDDRTcQKuSTnnpUxLOS9xoPtYBgDnWp9vP3y7ZVRUqDQz7ywNF25eVSpQTA8DlAM0\/vIKExVN9mV9vgvCN99T+aRiTfSRhgkagbin8DUZCIAnAJNq1Ivtktjn2w\/fbhnpupw7lXKyLOjegd+4T0k3xWdEVP3lFSYgiXWp\/J\/Ifb6D8M33\/AVwAB+i1jS2cR9xLQBB7kF+\/8BOsMww5XqfbwffruGG5xu\/bxrJ+A2TjcFvmOV0FcF\/NFTSoBQsM0z4K5f7fAfhG3E\/0l2ESDWDLfLsw69EvelGhg+PNfuGX9bnOx4y+I5OBt9FlcF39mXwnb4SCN+8JHnBU7knusPgQS4Nkhc96YK81A2+f4FvfEN0lRF4SekjDZ2KNBVIojuk7Lq+7seSwXfh8I2ohALMVN5JNyXiS2WUae+o6NOHMVWAySX45jcJgANyRBWBZrIu6NtJxZqxA6hY+8srTAbfhcM3wo+M0cByAJx+3gAMcycT1SWjxb\/+0XSiwTfvFp5vADO+JeWZ6Cs+JiqLT\/Fnqn440eCbZbwjgGtAm\/fRwIEDNSuI9H4azMnIwA+pQrTBdzxk8B2dDL6LKoPv7MvgO33FFL6JYl9\/\/fUKL6Q105fbbwAyL2\/6MAOTVPipENHfllRy4D0VoxzKBlZJJaSClVT4BtSI\/LuBfag0B9chJdD5jHmmqdTQB5GIZKpgRwWLfbENPqNiGbZeLosUXVL1OX9g2h\/BwT+AjUv1p88nkUjmwKUS6q+kHkuUy2jfXCMicKlGK4tL3ENE+7kHyaQIHi\/nTSW8f\/\/+OuASjV6cF31AGbTP78ejico3AIk\/KYv\/w9bLZQHX9D2mwZGIoh9I8DO+JwWahg5mP6DhjcYiQAk\/p3oPkp7OYHcdOnTQezHVaxR30fBDJhCNCtx7\/sYIfAM0kyFAAyPruUEpWf94ABB\/AZ10uWBgMp6dYeslTfiLhhzgmoa2YGMEy3nfAOhkEPDeYRR0nmX0j8d\/qd6D\/L5pIGYgQZ4xBt\/FI4Pv6GTwXVQZfGdfBt\/pK6bwDZgyQjkQzl8+B42XJZDtxIudUXn\/+Mc\/hq5fmLGuS1vnb7Ys0\/BNhYSKHpU7FFZBoULkltN4QUoqEVqiQP7K57Hk31euVMaPR\/gKuKHCyf\/BSqSrvONjfESknIgPU9ylWuFErIt\/KYu\/ma50ZlocH8fKOfM37Hj99yggDkATETyeRgnWc\/cg2x3PvZsrcud+tHsQH3MP0u0EEAeE6Pedqp8RfqYc9he2n6SKc3G\/T84xzH\/4FthjHbIraOzYv3\/\/cd1vlIPv3HUK+00kUZwXfuEe5PzC\/Mf5shwB4jTikI7O\/8H1jybKcfdg2LVKVwbfqcngOzoZfBdVBt\/Zl8F3+oopfB+vEa0mfZwo9vGAd3FapuH7eEUlhgiOiyRkukJjyhN+peKIr\/kbts6JKirTRG3NL9GKexAA4h4EAsPWMRUu\/Iff8B9+tGfl8Ql\/8Y5xDUHH03iRDRl8pyaD7+hk8F1UGXxnXwbf6StH4BsDwLOVMp4JK274RlSKrCKZHZmvw2V+yY6cn83XRZf5Lz3F1X8G36nJ4Ds6GXwXVQbf2ZfBd\/rKIfhOmsUBvk0mk8lkOpFl8J2aDL6jk8F3UWXwnX0ZfKcvg+9iM4Nvk8lkMpmKVwbfqcngOzoZfBdVBt\/Zl8F3+jL4LjYz+DaZTCaTqXhl8J2aDL6jk8F3UWXwnX0ZfKcvg+9iM4Nvk8lkMpmKVwbfqcngOzoZfBdVBt\/Zl8F3+jL4LjYz+DaZTCaTqXhl8J2aDL6jk8F3UWXwnX1lDb69i5urehn4ftzguxjM4NtkMplMpuJVxuD7y6c8kAIQc0+A7y\/wnVnIOZoZfKdhBt9pmcF3YcoGfP\/wnvowZ\/XaPvnXp0\/Jv\/9h8J1tM\/g2mUwmk6l4lSn4fu2r5+Sh92\/LWT3ywZ3yxR8+MviOQAbfRZXBd\/YVNXzzs\/\/rz\/K\/37+Tu\/rhXfnf\/\/7C8+E\/Dp+zWbYsGfD9s\/yBeVnjII4l9BhNJpPJZCqa0odvrwr1v\/8j3\/\/lG\/nsDx\/mrL74w8fyx7\/9watuR1HfDjeD7zTM4DstM\/guTJHDt5lZdBZ7+PaA94\/ffurpk1jov7\/7PPw4TSaTyWQqojIB32bRmMF3GmbwnZYZfBcmg2+zBFv84fsn+cvHz8vf3rhF\/vb6zcWrNw7KXz550Tsui36bTCaTKXMy+I6vGXynYQbfaZnBd2GKMXyTlgNcHS09x79O2Hp8xwshWI7bjmWosO3N4m3xhm9SvX+Uv3z4lPc78x5uYb+\/rMnb\/0vXyv\/76Km84wo9XpPJZDKZjl\/FBd+uLne0+pt\/nbD13PJgOe57V0881n7iagbfaZjBd1pm8F2YYgzf\/\/jHP+SPf\/yj\/PWvfy30ofe3v\/1N\/vSnPymAsU7Q+I4Xww8\/\/FBg+T\/\/+U\/d7scff5Sff\/5Zty+OF4dZesY1NfhORQbfJpPJZIpGxQXfmaon\/vnPf9Z6IuW5Mjifv\/zlL\/LTTz+pWOdf\/\/qXLkuSGXynYQbfaZnBd2GKMXy\/+uqrMmfOHNm\/f78+XP0PTR6AgPONN94os2fPlvvuu++IhyoPUB66lDFgwAB9OLPdt99+Kw888IDMmzdPBg0aJKNHj5Z169bJK6+8og\/XsIezWTyNa2XwnYoMvk0mk8kUjYoLvl977TWZO3eu7Nu3r9B64oEDB7QeGFZPxAjGsH2XLl3kww8\/1O04p+eff16uuuoqGTFihAwZMkSWLFkijz\/+uAZskhSsMfhOwwy+0zKD78IUY\/g+ePCgnHPOOQrH33zzTYGHHQ\/UrVu3SpUqVaRz587yySefHNHiyfpvv\/22lrF+\/Xp9oH799deydOlSqVy5stSrV0+6d+8u7du3lzJlykjr1q0VyoF0s2SYwXeqMvg2mUwmUzQqLvi+7bbbpHTp0jJq1Cit3wXridu2bZOqVatKp06d5OOPPz6inshnotr169eXoUOHKohzPnv27JE6depI9erVpWvXrnLhhRdKpUqVpFatWrJ7925dJylm8J2GGXynZQbfhSnG8H3LLbfI2WefXeChimjdJBpeu3ZtfSA+\/fTTBVKFMP4HohcvXqwP3nfffVfXufnmmxW8iXg\/+OCDCu20nNK6CcgPHz5cPv3008OlmMXdDL5TlcG3yWQymaJRccH3rbfeqvXEkSNHyldffZVfTyTNnMxI6okEaJ566in5+9\/\/fgR8Uy+86667pESJEnLPPfdokIZ1mzdvLh06dJCbbrpJo+HUIYHuRo0aSYsWLTQzMylm8J2GGXynZQbfhSlB8M1DEaAmOt20aVNtqbz33ntDH6h85oHJA3TatGnab4dW0OnTp2vr5UMPPZT\/oqDc9957T\/r27autnKQamSXDDL5TlcG3yWQymaJRXODb1RMJrjRr1kwzHIHqwuqJHPfgwYOlXbt28v333yuMb968WUqWLKnRb7oush51Dc6T+uSvf\/1rLTNYXlzN4DsNM\/hOywy+C1NC4JuHKg9U+mXzQAW8XV\/wsAcgD8prrrlGzj\/\/fHnjjTc0lYiHL62Vjz32mD5E3XY8rD\/77DN9eLP+M888o9+bxd8MvlOVwbfJZDKZolEc4PvLL7\/UeiLZjA68XV\/wsHoi3z355JNSo0YNBW3qiNQpPvjgA+0f\/t133+lnjL+AONmU\/+f\/\/B+54447QsuMoxl8p2EG32mZwXdhSgB8Dxs2TPvq8GBt27at9s\/euHGjPmTdg9FvDsgYZK1bt24a9XYPSZbxgvA\/NAFzoPyiiy7SdCIe3GbJMHetwyoDxS+Db5PJZDLlvoobvumv7a8nnnfeebJhw4ZC64nUATleBt4Fvun37dYLqyfymQzMsWPH6v4effTRw0vibwbfaZjBd1pm8F2YEgDfDIS2Zs0aadKkiZx11ln6sHQtmf6HozPShngw0vJ5\/fXXa2vm0Yy+QTt27NCHNaNZ8hA2S4YZfKcqg2+TyWQyRaPihm9XT6RL4plnnilXXnnlUeuJHCsZj4wbNHnyZIX0sPWcEfWmmyMDrjHyOaCfFDP4TsMMvtMyg+\/ClAD4PuOMMzQd\/PTTT5eyZcvqw5YHfWHGA3fBggU6uuX777+vke0wA9x4oALqDRo0kN69e8vLL79c6Ppm8TOD71Rl8J3LYuqbsO9NJpMpGypu+PbXE8mO5HuOqzCj7nfDDTcorNMVkaBNmAHkLHv99delV69euj4p6WyfFDP4TsMMvtMyg+\/ClAD4BqIZZXLWrFly7rnnaj+e+++\/v9AHPWnjjG5JFJsXgkslChqQzaiWHTt21Cg5rZqse7TWT7N4mcF3qjL4dgJU6cvHfP+5AK0MJMlUjPwNW24ymUxRq7jhm3oc9cTZs2drPbFu3bpy6NChQo+JFHKmsSVd\/Ysvvih0Pb4niEOfcmbE2bVr1zGj5HEzg+80zOA7LTP4LkwJgG83\/ReVS4Caebt79OghL7zwQoGUch6GDJ62d+9eadiwoY6KzufgQ5LPtFrS2slUEoA3g2fQN9wsWWbwnaoyD990zwBimYKFuVa3b98u69at0woQjWMMkvjDDz+Ebluc4pipQK1du1YBnPMIWy8o1uMZhNw2\/CV1kQjKddddp+cc3C5K0Xjw0ksvyfz58+WJJ544YjnHc\/vtt8vdd9+tfSEtQm4ymaJQccM3YwMxdSzP56VLl2o9kTF\/mL0m2PWQOqDrmsj7ijpEWJCGiPc777yjZTMTztatW7X8JIE3ZvCdhhl8p2UG34UpAfDtn2qMyuTEiROldOnS2u+GFkn3IOThSWWa\/juXXHKJjlgZNNblBcFUY0wtwUAbgHdhKUdm8TaD71SVWfgG4gDrhx9+WCMHzKVK5YRoA\/8zPgNdP6i4xA34iHIwrSCDKwLOVKbC1guK86VBj3EkmJKG82LbZ599VqMuzMDA8yhs2yjk9g9cly9fXq6++uoj1sH\/\/fr102v01ltvpdzQYDKZTMej4oZv\/1Rj1BepB1JPZBoxppJ19UT+ErmmoRj4DptalnWoW\/DMZPtSpUrJli1bCh01Pe5m8J2GGXynZQbfhSlB8M2DHUjmQcqDlsHX5s6dq8DNA5dlpJETzWaexj\/\/+c+HS\/rFiHgDDFSWGTiD1k\/\/aOhmyTKD71SVOfgG+oge89upU6eOwvbKlSs12v3444\/r\/KpEHrp3765dQHIFvknt5nnjnkeALOf2+eefK\/givg\/bNgqlAt9UHnnW0VeRPosG3yaTKQrFBb45BroU0hBKWjn1xDlz5uTXExHZWsyGM2XKFP0+aC7iPWjQIB1niGnIeN6GRceTYAbfaZjBd1pm8F2YEgbfQDJ\/SbWkLzjLd+7cqQDGw5FUUkavpDXTP3Ca2w44Z1TMihUraqWVyijwzfZOPJwNxpNhBt+pKrPwTXpf+\/bttW8dlR8qPQ7s+Mvv9aOPPtKKjYNEosWurzXiswNYRGSZ5cH1+J\/tWZf\/\/ansrmy+c+sgyvBvz2eWs00Qvt22bj+ubLc\/d5xAdv\/+\/TWSTDcYymZ9joHzZ7n7zPqU647BHQff+ZdTtv98AXw+s44T67nlTq4c9nc0+H7zzTf1OtFNB\/j2n58T3\/mPAblzZhnfu\/Niff76j59lfHbb8xe5Mtw58NmdiztPtzx4TCaTKVmKE3y7+h4D6DL+T8mSJbVblKvj3Xnnnfr8p47pHziN7ahTAO5EvEuUKCHr16\/XZxbBHH9dkfplUmDc4DsNM\/hOywy+C1PC4BvjAUnLJFE2Rp6kZZNoNq2ZVDRJN+Lh6H8wAtS0ZPbs2VP+v\/\/v\/9OHMQ\/W0047TUfHdCJNicosD1YD8PibwXeqyhx8A0w0ePG7mzp1qvYl9kMUfx2gIb4DVoke0FWEVL+LL75Ys1OYrgUgYz0qR2PGjNGGMwZXJGJL9Hz\/\/v0KyVSyLr30Uo24u32xHZBPuczpynOCMunT7QAbYKY\/Ng0GbOOHb46L7+nLN336dI3Usw5in6y3bds2hVga9hhNt2rVqjJ+\/HhZtGiRPPfccwrdTGvDFIj8zzEBl4888oiMGzdOn0kXXXSRDgREOQ5AGZti8eLF2gVm5syZmrFDRRGIdo0ZrEv0mhR++i82b95crrjiCt0vy1C68I0POBbG1uB5ynHQDxJfMmARKev4HrB215VtNm3apOfNPvAV2\/Tp00e781ARpoLLeXCMVIIp\/5577tHrxDy8l19+uV4rygsek8lkSpbiBN+YqycyFgbvHN5XPGt5VvEM5b3A88d\/zNQnaBQkIv4f\/\/EfWj+k7FNPPbVAPZGyyPYiDT0JAG7wnYYZfKdlBt+FKcbwDVwDyzzkqKD5H3L8D1Dz4KWCTgWRQZ8YCZ3vguDMA\/bVV1\/VVCMexFRiqXzz1y++ow+4wXcyzOA7VWUOvgE4KiennHKKTrlCZSVsPcTvFthdvny5pqcDyfw\/duxY\/a0CsTSaUSYAynQxADYNbjSiNW7cWCpXrqwg+8Ybb2jGCt8Dr4Ag2wHaVJCAvbfffltmzJihUwdSxrJly2TEiBFSrVo1HZSMhgIH1fzWAW\/Ghpg2bZqC7zPPPJN\/7B9++KE2xnFcwCNwfd555yl8A458pr838E9jAuBJZY5jc5GVLl266HqUQX\/4Nm3ayCuvvJLvE75zsEpqJM8gUvmBYcpBQCtATBnsF39wTjQm4vt04Bsf0sjJcZKiybGyfqVKlbTRg\/PjGUy0n0YAtmefdC2gcYTuBVwXGhbYhmjRqlWr9Hw4fwZ6A+KpAFeoUEHLwQc0JNCgwLUw+DaZkq\/igm+eLTyjVqxYoc+nsHoidUPqiQycxjOeOiB9vjlefz2P9WlY5H3g6olh4tnG9knpA27wnYYZfKdlBt+FKcbwzUONhyMPxMIecO7hCizfdddd+SlCYUYZrE+ZR1MSHqZmecb1NPhORZmFbyDqd7\/7ncLd0eAJUGOQMgCTgRJJ52N7IPiqq65SaCQiTnSUCs\/JJ5+sUWqirKzH4GbAJkBHpYg+eA5g2YZIByDH7AYALQ1nwDERZT5TBn8BcdahsQDg9sM3x0RjAoD79NNP5x878M1AO0AvkMrnli1b6rZEuNk\/5w5806ca8T8Azjp0iyGKjw94JlEBZAReymM9GgaYuoaBfPAH54yvaJQgo4BjY79EaxjngnNhv4Au41UwWwMR9nQj30A8xwkkc5x8vuCCCxTwaZigkYCBKWnUZDnAzHeUiz+Bd\/YPTFMG+wDUaUShoYRjp\/HkzDPPVGBnbAB8gu84v+DxmEym5Km44DvVeqKr3\/EcXLhwoTb6hlmq9cSj7S9uZvCdhhl8p2UG34UpxvB9PMaDkBQjppQAxs1ODOO6G3ynoszCN5kmJ510kkJbGNA5AZSkqBPNZTouYBHgArwAZSLWpG\/zPcAJfBNJdWUCmI0aNdJoNtB34MABhVOAFagGVgFYUpn5TCo0nwFCB3aUDeATNV+zZo1CdCrwDXhyfMAyn9muVatW2vDgUu3D4JtKHVFeUs4BdI6D82EZ0X+gFTgFvjkX4BqoZV2mTySK4yLbbIsP2R\/b4A\/8RPo7KeHAbrrwzX4ph\/Nj\/6SGM1o9x8ExE\/3GVzR80NhBBhFp9GQtsJzGAFIxSeXknIhAMSWkG+iN4wa+y5Qpo5F1ziV4DCaTKdkqLvg+HgOWCdQw2jl\/TxQz+E7DDL7TMoPvwpQj8G12YprBd6rKLHwTOaA\/3DXXXKPgGBbB5DugDuAFMoFE1nXLGaeBKDVgTUTXpbIDa648wI80P5YB1\/TJJsUbEHzxxRcVRElNB9iJjAN97Ovee+\/N3w\/7ZF9E0IE\/YDsMvoHUTMA3wMt4EkCpKwufcfxAMP2qgVxAlenJAFMiwaxDRJ9pEt3UYHzHMZGSzvekdRP5JyIPJKcL3\/iZ8yd1n\/T2gQMHatcAfAVg4x+OjawFRv2lrzkNGzQi0KDB+U+YMEH7RHJPcE5OZB\/QDxyf0E+fxo+NGzdqY4L\/GEwmU\/KVBPg+Uc3gOw0z+E7LDL4Lk8G3WYLN4DtVZQ6+AS5glv7PDJxFP2u+c8sBOj4DbUDqjh07tG8zfYiJQrt16BdNKjLQBpAB0keDb6KulAfAEUkn9RkYZvovIJSyiXwD9KRIu+Phe9LXwyLfADuf2Tdl0X\/QHR9QWhT4JmJNZBooZTllAb2AbM2aNTUFn3M8GnwDwMAysEuqO2nz9J8m8k2mAHCcLnxzbBwT\/baZIYKB5YBkjoeoddeuXdU\/HD99vInmc070m6T\/pLvuNHjQ2EAjAefPNk5cM\/zPcRt8m0y5K4Pv+JrBdxpm8J2WGXwXJoNvswSbwXeqyhx8A2PAJxFrRn0FDIFJB8CIqDTRUmCSfsFAKyOYA7TAF5FuRg8nmnrttddq6vOx4JvygUfStIFW0tHpiwww8z0gSCo74EvqM8fIvkhXBxoZhA3gd32yHXyzHIAkXf2mm27SbRDAyfk5+AZUaWygjzn\/sw7HHYRvyud\/BjFjSkT8wbHT15mINf2gWe9Y8E16Nz6igYJzBGSJngOwHOvxwDcgzTVxMOwE3BPh5lrRaEB5HD\/wzXk6+Ga\/RMVpjAD8GVuD7VnG9WX\/RPqdzxHbkHWADL5NptyWwXd8zeA7DTP4TssMvguTwbdZgs3gO1VlDr4RoAi00jcZoGQ0caCRfr+AJ\/176TPMKOEAHdFtIqdMJUaKM+BOhPqyyy5TIE8VvgFsBvBitHRSnYFo1zea9d3I5UA5wM30ZcAukE8ZgCDg7+CbcwB8Dx48qMdHSjfgTkMBg5oR3ed\/ygY2gVTODVhH9HkPwjf7AIzZHgBnVFw3aBmwTQQaME0l8r1v3z4FXnwDvK9evVobMo437bxcuXLSu3dvTVunbIQ\/aMhgYDTOm30xKByfacBwkW\/K4fqQyv+b3\/xGz4uoN8eL3\/EL15OR4YmK0x+f6DzHySBsNFQYfJtMuS2D7\/iawXcaZvCdlhl8FyaDb7MEm8F3qsosfCPgC7AC+pgztXXr1vlp2YApIApUAmhEU5nXGwAEeklzZrRzQBqwA6oBM1KySe92MA2AAuhuFgO+5y8RalKpGcQNAHXHRFmUScQYeCRlmxRpAJhjdbBIlJZyHdBzfOyf6cY4D6L5THUIbDMHOGVzLk8++aQCJufA9kSOAXjgE0gH7CmPcoFVIBewBYBpMCASzjFyDkT8WU5E2vmAwdpIo6e\/NI0SRKqJvNMAgW9oUGAaMvZNmjflALb4lai\/84MTvmQbjjcopkYD9tmOhhK+w6cMkEdffoCf\/VMOxwfIkwlA4waf3TXiPuB8Sfl3Pmekd\/xB9J5j5Lzpq8+AefjRf4wmkyn5MviOrxl8p2EG32mZwXdhMvg2S7AZfKeqzMM3AsCARgAMUAPC+J\/vWOYAzb8esOpg0y1HfA5+57bjr\/vefRe2vn85+yDC7D8et9wv\/zYcv\/8cguXzvzsH\/7Lguq48hF8AUFemW+6Xv3zkykJsx3mwz+BxBdd35fjLYxnbBeW24S8NEkS5OU4+O7nyWU70nog4DRBsH7Yf53PW92\/vlrv\/\/duaTKbky+A7vmbwnYYZfKdlBt+FyeDbLMFm8J2qooHvoHIBrKI4h0yUGbVvKT9sH3zHKPNkNRC9pzHhaMcS9XGaTKb4yeA7vmbwnYYZfKdlBt+FyeDbLMFm8J2qsgPfptwTME3fe\/pvkyIfjHqbTCaTwXd8zeA7DTP4TssMvguTwbdZgs3gO1UZfJuKLlLx6Rfv7+ttMplMTgbf8TWD7zTM4DstM\/guTAbfZgk2g+9UZfBtMplMpmhk8B1fM\/hOwwy+0zKD78Jk8G2WYDP4TlUG3yaTyWSKRgbf8TWD7zTM4DstM\/guTAbfZgm2+MP3T\/KXj56Rv79yg6fri1ev7tNjMfg2mUwmUyZl8B1fM\/hOwwy+0zKD78Jk8G2WYIs3fHvy4PtPX74tf\/n4OQ98ny0+sX9Pf\/ryrfDjNJlMJpOpiDL4jq8ZfKdhBt9pmcF3YTL4NkuwxR6+D0e\/ST+Ph\/LmmTaZTCaTKVMy+I6vGXynYQbfaZnBd2Ey+DZLsMUfvk0mk8lkym0ZfMfXDL7TMIPvtMzguzAZfJsl2Ay+TSaTyWQqXhl8x9cMvtMwg++0zOC7MBl8myXYDL5NJpPJZCpeGXzH1wy+0zCD77TM4LswGXybJdgMvk0mk8lkKl4ZfMfXDL7TMIPvtMzguzAZfJsl2JIA3z\/HTGHHaDKZTCZTUWXwHV8z+E7DDL7TMoPvwmTwbZZgizt8A7tf\/\/CzfP39z\/JVDPStdyxhx2kymUwmU1Fl8B1fM\/hOwwy+0zKD78Jk8G2WYIs7fP\/08x\/klY9\/lIff\/EEeKmY98tYP8vqnP1n022QymUwZlcF3fM3gOw0z+E7L0oTvvR6kegeXk9ot\/\/rwYe9cDb7Nkmdxhm8g90cPvp9+70e57pnv5Nqni0\/Xebr+2e\/kmfd\/lJ+9Ywo7XpPJZDKZiiKD7\/ga8P0vr47\/3vevyX3v3qQAnou6\/71b5F3vHDnXjJmD73fvDuGnXNE1Hnxf78H3jzGBb5z+p6\/lf757S\/7n2zdyU9+9Kf\/744cZd7iZWTbM4Ds1GXybTCaTKSoZfMfb\/ud\/\/yXf\/ulL+fSn9+WTn97LSX328wfy0\/\/7Xv7n3xm8D\/\/9b\/n337x7+4f3whkqV+RxrvzjL3q+mbSiwbd4BwGUejdtbosb1aLeZskzg+\/UZPBtMplMpqhk8B1vI\/r9vx6U\/o9X389VcX7\/q4HEDPOMcqB3b4fyU67IO78IgrBFhG9nXMhclplZMs3gOzUZfJtMJpMpKhl8J8nCOCAXFLWF7TNXFI2lCd9mZmZxNIPv1GTwbTKZTKaoZPBtZmYWNINvM7McNIPv1GTwbTKZTKaoZPBtZmYWtFjC97\/\/\/W\/517\/+pQIi+Bw0vmc5DzUUto6Z2YlqBt+pyeDbZDKZTFHJ4NvMzCxosYRvHlSvvfaaPPTQQ\/Lpp58qSPgN0P7zn\/8sL774ojzwwAPyzTffHLGOmdmJbAbfqcng22QymUxRyeDbLNXgoAURj2346Fh+SmWd4rZYwvff\/\/53ufLKK6VVq1Zy4403yj\/+8Y\/DS\/LA\/I9\/\/KPccMMNUq9ePZk+fbp89dVXBt9mZj4z+E5NBt8mk8lkikoG3ye2ce3\/+c9\/5mfqhkGhWwfZvRJu+I16rfNTGPOxDv6DGVknzgAeS\/j+61\/\/KpdddpmUL19etm\/fLn\/729\/0e5wNmBPtrlSpkjRt2lQee+wxvanj3sphZpZNM\/hOTQbfJr9+\/vlnVdgyU\/HLXR+7RqakyOD7xLbvv\/9ebr75Zrn66quVZfzQCLfALwQQWb5v3z754YcfDi818xt+++STTzTwevDgQfWb3\/Al0P3mm2\/Ktm3b5JZbbjlinThZYuAbxwLeb7zxhpx\/\/vlSp04dufPOO\/U7A28zs4Jm8J2aTgT4\/vHHH+Wnn34KXZaOKBOlC0KZKscvynLlhi0PE9t8\/fXXWhFKOtxx\/FFd92zLfy3Rd999p9eI80v6dTLlvgy+T2x7\/fXXpU2bNlKuXDm9H\/xASHSWrrXt2rWTEiVKyObNm48LGAH1hx9++IQAdnx13333Sd26daVjx47Kic5o4MAPdFWuXr26suODDz5YoKGjqBaVjxMB30AEjn\/55ZelYcOGUrlyZdm5c6e2cmTCuWZmuWYG36kpk\/ANCPCAfumll+Tpp5+Wp556Sv++8MIL2mgI2GUKGICQjz\/+WJ544gl59913C4Usjufee+\/Vl0fY8qKI42ecDc6Ncr\/88ssj1vnss8\/kmWeeyfeB3w+AE8froOrVV1+V2267Tc+nsPM4HlEGvqbM3\/\/+9+rzsPX84lh4gVP5Wb16df5xuO\/ff\/99LevJJ59Un\/P\/Bx98oCCYieuZaeH\/u+66S31+PMfHeXPP+K8D\/3\/++ed6DYkqsNy\/TdTC\/48++qjcf\/\/9et+98sorsnDhQnn++eezfiwm0\/HK4PvENJ6ZvB8ff\/xxad68uZx77rn6LgKuCRhyT3z44YcydOhQKVOmjEybNk3+8pe\/HNe9wvsnCjCM2t5++231C2N3hRnnw3nhQ2fw3j333CMXXHCBdO\/eXZdTDvbFF1\/IHXfcIZdeeqlyI9Fx6r+ZCMy6Y8m0jxMB31wgXvqdO3eWkiVLyoYNG\/QmtYi3mVm4GXynpkzDNyDas2dPzcxp2bKlilbv\/v37a4Mhrdx+sCmqeOmSpla1alVZvHixfg5bj+Phxd+jR4+MQSLH\/95778nll18uvXr10kbR4DpkJTVu3FgaNWqkY3e0bt1aOnXqpH7guKl0UA5gtW7dOq180J0oEzBFGbyUKXP+\/PkKbGHr+cWx0AhQpUoVmTFjRn4jybfffqvHNXHiRI1O0Opev359PRcqS0BhHAEcUGZMlDlz5hyXT2m0oIGBAU\/dd1yjQ4cOSc2aNfWcAXv\/NlGLe7hv3756H9FA8+yzz8pFF12k15bfU9g2JlNcZPB94hnBQhqeaaS9++67tQ7gh2\/uBxqhp0yZIuecc46+X452nwChPJOL6z7K9P4d0Prh2m+u4YK6hdunH75HjBihkW3KgQN5d\/fu3VsDs2vWrMnPls6EuWPlbyYt1vBdunRpmTdvnjqcFo2yZctqRZMHWnHdhGZmSTCD79SUSfh2EUKgB\/Bbu3atrF+\/XmbPnq0ttYAyn4GZsO2PR7wIiGzSan7dddcVGt0FXBgbo1u3bhkDRPZFtH306NEK9UT6g+vQd+2MM86QQYMGyZYtW1RXXXWVNkzUqFFDP3Ns+IKX5XnnnaeRTc4rWNbxijLeeustrezw\/gAow9bzC0BfunSpvmOIbHOOHN+ePXsUups0aaIVpRUrVug1nDlzplx44YX6mfXiBt9U\/GgA4t47Hp\/SyD127FjZsWNH\/nf4AuAdOXKkbN26VSuN\/m2iFlGNPn36SIsWLbTPHw03DMjaoUMHbSgI28ZkiosMvk8845nLM5j3Ag3RF198cT58A5G8k5YsWSLVqlWT4cOHy0cffZQfEQ8a9w4Q6gfRbFoU+3eNE2Fluv3RcOGPjvvhe9KkSTreF3VcMtB4Z1WsWFEWLVqkjeGZ9BPX8oSD75NOOkkrrLS48z8ATiXpePpEmJmdiGbwnZoyDd9EBYFvnln8z8uXFy3wQtSU7\/2RWJaznV8O5Phb2HJEVJbWaH8f5eD6NAYAjg6+3XK3vn8\/ToUdl9suFfjeu3evnHrqqbJx40bdju843ttvv13hm2c5KeiFwXfY\/t2xORW2DmWGwbdbP6wcIvlE54cNG6awx3r0HyNzoW3btrJ\/\/36FbLcN\/\/PyJ\/XZRb5d+UH593e0dYJy2\/i3c9+7z2FlsDwI326Zf53gd4iuAu3bt89Pvec7\/nKO77zzToHMDbcsKL4\/2nIn1nEKW9eV44dvflOcDwPucH7XXntt\/nomUxxl8H3iGZlXiOvOe23ChAkaTOTdxPOKjF4a6C+55BJ9hwOWhZmD0UzC7\/FYVPvHP7ynAHG\/AdtANw2t\/HXRcQff1KOWLVum3Y+oU5CNxQDc48aN020ynRF9QsL36aefrq3b\/fr108pZhQoV5NZbb7VB1szMjmEG36kpG\/DN9wA3qcpnn322\/s\/3QCwvECLko0aNkvHjx2tfJRdJ5UUNoBJdHTJkiL7AgUBgm2X05wUueUFRFi8HXmhELYlS8jJi\/QYNGkjXrl21TF70RKDpB+6gjLJ4qa1cuVIHh+F7YIuWZ6LBlEXLMuDMvosK35QJ3BExdpUO9u2Hbz6zPuVv2rRJxowZo74h2syxsW\/nU6CalD6mm+QY8QWNHBwjEVw\/fLM+25M5BbBRjjtWyiOtmpQ1Rkjlhc41oF8xFaZdu3Zpme48EP\/jJ\/4iygNMmRqTVnl8w77woTsnKgZkKdA3DbCnfDID8DHXmRZ8RmndvXu3Vjjc\/jg+ovELFizQ+4X9Uhbp+9wzvCtXrVql58y+WN8P33zH+qSg33TTTfqZcvlLVAYfsZzryD6I\/pPCR3cARunFf4A3kRrWd\/vgPn7kkUd0H6QBkq7PgDj4Dn+wHsd4\/fXX63WnwuSuE+WxjvPjiy++qOdAFIjrzTausSMI32z33HPP6X2ED93vxV0bkylOMvg+scxFdXmuYbyfly9frl2aeF\/xPieo6DJ34BneOTzTgDzENrwvXfp1UK5s\/vo\/Fwa0mDsu1nHGdrxTXLkcgysLO9b+Me5tGq\/dMnfsx7LgsTtjnxwn9Vf\/8Tr4xm\/UVXiPAt6850nbx7e8k5xRDscCzPOO4H\/2xznyvgga5+G2cefBe5FzCTtOjGXB64Yv\/L\/3wq5JrOGbliEqALxw+VuqVCn9jkrC0VqKzMxOdDP4Tk1RwTfRXVLJeKkiXnC02BJF5TMPch7I9JnmRQy8XHHFFfo\/cMJyYIqGR\/oY85Khj3WXLl0U8CiDAcUY2RNQ4SXAQx7g5iVPmhvrA2Ann3xyPnwDffTFBnTYxkEUlQOivMCUe6GwHinrAwYMkFq1aimUsT3LgadU4JuGBcrneHmx0bhQu3ZtbQDghQig+eGb9ei\/RWSc8wBOaXgg1QwgBOLYBlE244LQn45joXEDf+JrYNbBN\/DGgGlEtZs1a1YA4jlW\/gL6rE+DAL7Hl6T0kzUA+AbPzy+uO3A+d+5cbYHH1+yL643\/qWBxXhwTZQKRlEsDBCntvNcGDx6sxzVr1iy9f4gycBwcG\/BLmjWReRoX+EzfedLsgFK2pbGHe4vj59y4t\/zwzb3ELCHcR67xh78ANY0OZArQuIIvf\/Ob3+j9y7XlnLhuNPTQiENDAfvn2GjkYQRf7hvuXyLmHAep6VxbyuccuXaUxbWhfBqgWJflHCv95gFp7jX8w3Fzbgx+x3GGwTfHy30BqHOtXEOFyRQ3GXyfWObg0cEW70eem4xZQUCR9zHvO957PLd41gNurkES8T\/PUOpwvG9pnET8z3I3\/TLPYT8Yus8cQ9CC67oIM+9LynX74TuX6n2s\/XOObhv26Y69sGPwm9u\/g2uM34k\/yu4HVwff1G3o9kVdiToG71wyoaib8K5zxv4pn3eFO0f3nf8cMbdf\/3Vw5813fr9hYeu7c6dsd\/xY0O8Y5xNr+ObFTiQAJ3ET0LJ+2mmn6UuaiwJgmJmZHWkG36kpCvgGHsjSIQoIUPIMo7UWCOEFwUOYfqtTp05VcGFAL4CGly2RUQCR9YjQ8oIh2we4cxDL9rwYiNLy4iFSyvZAOfslZRhgYV2Aju8cfHM8wB2wTRkO7qgcAIQOrtkegKbll3KAcuAL2GEZz99U4JvB3oYPH66gBDy6cTsYOIvzCMI3+wOYAVdgEJ8g+rfzHfAISJPuTVR64MCB6nOOER\/R4MH5uMg30MqLl4YNjoXzYJ+ctztW\/ueYODbK4LiAXICQFz3b+88tKMqj1R0\/A7O84LlWRL1ptAA0OS7XqMB9QCWC4+TYOV8aUfAZ37vGCXetqXzQbYD3H34HSjl3UhfZD+XgO4AZ6Gc7P3xzPbkP8PHkyZN1fc6ZbYkc04BBuWzHPQuks3+2Y\/98j785LvrUcf255nymQYSIP2VxTwPh9GNkfXxJH3\/Olwg6nxEZHFRCyb7Ad+yb4+e6unK41xgnAV+iIHxzn3AuNE5R0eG7sGtjMhW3DL5PHHNQxjPNGe8PMpR4X\/LeJUrLIGvu3c47l2dsYebK9AOdM57PfrA72rock\/97uMpt58wBMc9cZ8cq09\/Q4Kyw7\/0WVi7rs53bv\/\/8gG\/eszz3eYdQb6DhmcZi6gFEwnm3OaMMtvVfC8yV6T9Ht27QH+4Yg8vc+rwjgxYsP3hOGOvEGr7daOduYnoqt6StMR8ezuYFfLSLa2Z2oprBd2qKCr5pJAQ6eMGeddZZOlMDqc3ABesRwQWyGcUZyAQKeWATGQYSSXUGrol6A44sI6oJiLI9D32WEyG85pprNGWZ9GsaJnmZA1cIUPL3+QZygNggfAONRLoZQRQgAmY4VvYHOBL5pOWeRgTOkdbkVOCbbXiWI46BqSKJbvISBcSC8A30sh4QB0DzkkKAKxF4Iqf4ghTmM888U7dhudsv50OZHB8RZWCUgdLY74EDB\/Rc8Z\/\/WNkGSMUvLKc8joNrlgp840f2w\/VmXbanTHxHwwORXq69Owei1lxL1sHPVBpoKACq2QZg5ZrhZz4TYQY8AVgaLbgG3BduxHh3DYmic6\/xkifaHoRv9kFKPOu6bUgzp5GbCgp+w5\/cU2RGuPPje2CahgRgHdimOwGNFQA05bMeZXIt8btLnQegOV7uIc4V33Bv8Ptg9H8qnXxPGZwr50dlh98F1xo\/4YcgfHPvMNo50XSiE\/57wGSKkwy+Txxz8MrzyBnvBN4jNHDTnYr3Kt2o\/ANKH232pjBIdcZ+eB\/698dzNxjZDYPqMHOg6AfWwvYftq4zjid4DGEWPNbgdv7jBr5phKeuwnuV9w3f0zWN9yUZVxyjG7iOZUHfYMHjPpp\/saCPj7V+2HL25f\/MsSUGvjGAgpe06wNOFISTMDMzK2gG36kpCvgG4kjlBUwADAfZPHwd+AHbgDlRaIDMiTRdosSANZFAIBkYJ50XAAHKXTq7g2\/61ZLSDAAyBRMRV3dMAI1\/tPNU4Rvx0gP8ADSi9EQ0ORYaPVOFb6aF5KUFMHHMNAxwLIAtgMt+\/PBNFgD+Iv2a\/eAv51dSzQBAGitIr2faSSozlO3fN\/vj+IiukhmAiNBynJyvf13Ed1SCOD98QXmAP63qvNSPNaI25wUo4lcqVpSH+J5KFo0EwCiVMBqN3WBzbnte7FTE8BXnCoQDsFQ0AHa24Z5gG649xwmg07Dizodj5nqQ0ghokyofFXxzDPQfB77ZDn+7delTzvEROQfSge+OHTvq\/+yT46SyyUj4pPrjI46PqdF415OBwHudxhJgG7Bm2yB8c+6cG5Va7nf\/MZhMcZLB94ljPA8BO39QkOc+7weemTyrgEieX3Tp4TsiufQTzhR8h4E2\/wePC4OtWMb7kmOjLOTAFCts\/24\/bpsw+Y8rzILHGvSff99wIWOO0GceBqTBAtDGd2QW8O6ggYP3CdtRJmU7kHcWhO\/g56AFfXys9bHgefj9784pUfCNcfC0hvMyJs2Pyg1O8d8UZmYnuhl8p6ao+nwTBQVS+Mx4FaQVE6njIQw8AHQABulTQCFgBfAhgJLIHi8R4BkgpgzgnIgnsM33fvjm5UlKOP2eASV3TMHIN3DL8fGiclF49sVn4JvlfAb8eMYSdQfEACXKIU3+eODbP+Aa540\/SF3muIn4BuGb\/r\/0XSZaTTSfbRANEQA3PgPeSMEmA4p9s9y\/b94HHB8RZ6CV1HPOjf0AcsH18QvnCJy6feJfrhfHdbQB11gXP5LWD+y6BgMHt5TBcdIlIBX4Zjveb5wnEXJ8xPWifzv3A8dPSjZAiy\/dvjgWGm5OOeUUvX+CkW+Xhs\/15Fz8x3e88M050lgDfFNhY7lbl64SvJfdWC0OvvmffeIvGqVokOCe4nvOkYYjxihgIB2+pxGJrInC4Jv7gTqC6ysfvKYmU1xk8H1imIMyP3wigJF3D2DIZ\/iGdXkHMOUm3ZuoB\/AcDbtPHKwF4RfjuU+Z\/PWbH\/7ccQVhkboI2zK+C32VeU+g4LqF7d+Bs7\/Pc1B+dgszd2yUzbqFHSf74f1Bmj4NxmRTuWwByqDewPuTrm10u6Puy3sjLvDtfEUZ\/E\/gIbbwTSoBfc+IHPkvoHM2J4KjiTZQCcXZZmZmeWbwnZqigm\/\/aOeAIGABkLvB0QAGIIyIOADJi5fteWGxnO0Q3yEihLxgABIig7xY\/GnngD4vJQAJmHFlsW83CBjlEWEEokn9BjB5GZDqS8o6wAd8U7ZL+3UpvQAXoM0z93jg2x\/55i+t1Iycji9cn18\/fOMXQIwKCanurkJAmj4Qx3HxPX4Eaml8ZbnzE+XxmeMDNoloA71E7oE3Us+df92x8j+jwgOh+Jhj5Tv6PwO6nDMVKLZjGfsBXGkEYB2uMzBKtoN\/PfxIYwj+x48uin0s+AbmHfjToELmAsfFMsAZ6GQwOl7uzrdUgLh+LnWeZQ6+8Qn3B\/cKGQcOYDk+IuHsh8oC63H9WY\/MCM6TfXI+VNAcfLM9A9xwXlR0uDdZl2MhkkPUHt\/Q8MP9cTT4pqGBdz0RbKZuoyy24zt3\/3GcQfh2qZxcV+5f9u\/8aTLFSQbfJ4bx\/INLXAO7E6DFs4p3Gu843p8YHEP3K7K8eGbyrKbOFoyAFwW+\/d+74\/JDaGEAGfZ9YfsvrIzjNQeqvGccoPrNgSt+5b1DvYN3MvDtjPciYE5GGINy8z7nvcA7JVX4DvMv5hop3HEd7XpgYcvdd+yT8vg\/lvDNgdKyTas6FZHgCXJz4nhOhIoYjre5v83MfjGD79SUDfgGaoAIwJnviSKybM+ePQrCjOgNrALNRIUZ1wLYBGBITSPNmuccoAkMkg3kj3y7AddYjwg7L3oikKxHn1gilEQgORZe\/AAgDZuAKf2IXTq3g29eDqRpA3IcA8cCDDKg1\/FGvonGEgXl2ImuA1GkJRO5ps9yEL45L6LEACeRfv4nlZk+4Jy7i\/oDk\/RxBuKJCgO9gCCNHIAZcOvgm\/MB6imPclnOfvEHx8pfzoFrQ19ylzoOBBL1xg\/sh+vCctLeOB6i6aRXcy2BSGCRwdXwO5UE0gk5L9ahLNY5Fnzz2cEljQtkf5FSxz5YRgWAypxrUKERAv9wbEScGbCPc6My4Ydv7g+yABjoh8oelROX3k36Pu9S1qNs7lPuIXzN\/YG\/+d7BN58BYs6DBgei5Iy8z1\/KIxpNYwDv5WPBNxF5MhqoTHE\/89vgfqBLRmHwjQ\/IBsH\/+Mx\/LU2muMngO\/fNwZUfuJzxLKe7Fu9qnvVwjVuH9xLvfd63PJt5JgYDiUcrm2dhGHy7bXjPoOC2fqD1myvPgSl2tP2zHu+adIKfbp\/4hbKAYb85OKYewvuIlPMgfPMO4J1AHYh3Eo3TZO\/RaP2nP\/3p8Fp5FtZowP\/BBgrMrRv0sQNyGgyC5s4n6Fs+8z5D\/B9L+DYzM0vPDL5TUybhGwAATIACAJz\/HRQAHbwMgGOit0AEcAKk8iKhtRZYJK0cUGVboo1AHiBCVJa\/RFiBESKEAA8gyyBtPPD5njRvoIuyAGXgjEgzMMWxODADXAEgXlREUgFjAJ2+6IAafbOBUcphVGsAnSgjrfeAJHBFuZwLlYugL4gw05rPwFrAHQIO2S8VDMCbY0YcM8tcf3POjZcs6ef4BYDlXABLfEYjB\/50MAug0sAAWNMQQeMAx8f3NGZQHufOyxuAIwXff23cdSPizjkD9uwDAeL4ghc+vsJnHBOASoo0L23OgZcwWQU0NtCwwTr4jWvJi5Z1qASRcTB8+HBtvHC+onWe82fAGPcd+wVuuV+oUOAXt4x94SumnWM79kUjDteafXHcwDL3IY0Pzs9E3gFhBmWjckJ0mYYB9kFjN+vgOyCahhZ8yjXnelNh4J4mdRJ\/sg\/OnQYG7kHuE\/xDdwGXis56+I0Ucj9808DDvcH5UjYNJ1xrrjNl0IBCv3fuNRpFuDY0nLAO63N\/MoMAjSJs6\/xiMsVRBt+5b4XBLMZzn\/ce7yOeZ\/5oLHBHgyPPeN4LPPOAcd5fPPecUS5Ax\/OZ5z\/PUoxndhAMnbltwpY7qHTHzHOZffLs5js\/mGKF7d+dt78cVxZZbqmYH3DDAB\/jeHgP00DLe4AMLn9GtPMDx0BjNO8X3uc09KYC335\/cOycA2XhDz4HfegaJPjere\/OmzLCzsMdI8vxm8G3mVkOmsF3asokfCMewIAH4n\/3PS8rvuPFxUPYwR3fAVoAHwAEsPCdAxXWBziBNaCDZW5b\/75Yn+\/c+oA45fKZv6zjjoPt2A8vR2CG\/91+OTaW85eXPy8TyqIcxDosZ1+sw3d8dufpxDKOl3278pE7FrbnWJxfwr5jfaCN9DF3fG45cvvnON067vhdmXymXHdMrO\/\/zol1qQABpkS7KSN4LBw714hj4rM7d9Zx\/uB7Xtr4jPNnHXdebp2gz\/ifslnmvmNdykJuH\/5l7pjYFxWioF+DZfq\/Y33XgMOxOD+5Y+Q7lnOeLGM7lju5ffA\/63Ke3L9cBz77y2IflMFndxwsd+W6srlnqQyxT8pw21EG67hjZBnRIjf\/O9s4v5hMcZTBd+4bz2EHVUEjK\/fvf\/+7DrTGvQB8+8GP5bxnidICmAAaDdr+srh\/HASyH56jGM\/EIBg6c2AMVAKXQaN+SKMq2yPKL6zfdWH7xyiH43XlID4fTzSc\/bEdfgwzd540XlAux0kd15lbzvuBc2V5qmnnzijXnSMi+EG5hfkYn3C8rOffhmMIM7dfB+YG32ZmOWgG36kp0\/BdVPEyc4ByPMsKUyrrH2sdt9\/j3Xcmlcr+M3F8DhSJ5DMoGcAXtl6q+8qWz6LcT7bOAbEvp7DlTlwXKjhkcuzbt0+vWdh6JlNcZPBtZmYWNINvM7McNIPv1BQX+DYVvwBw+tYTfcgmeJpSF9eIKDvzphN1sOtkirsMvs3MzIJm8G1mloNm8J2aDL5NToCcS4UOW24qfrlrBIQbeJuSIINvMzOzoBl8m5nloBl8pyaDb5PJZDJFJYNvMzOzoBl8m5nloBl8pyaDb5PJZDJFJYNvMzOzoBl8m5nloMUdvn\/yQBfgBXz3eABeXLre097nvpNnge\/AcZpMJpPJlI4Mvs3MzIJm8G1mloMWZ\/hGwPdLH\/0oD775gzxQzOIYfu8di8G3yWQymTIpg28zM7OgGXybmeWgxR2+XfT7x5\/+ID\/EQBxL2HGaTCaTyVRUGXybmZkFzeDbzCwHLe7wbTKZTCZTrsvg28zMLGgG32ZmOWgG3yaTyWQyFa8Mvs3MzIJm8G1mloNm8G0ymUwmU\/HK4PvEsh9++EEefvjhAnr77bcPLy1+41iiPjbKfOqpp+Sf\/\/zn4W\/Mgj4x+DYzy0Ez+DaZTCaTqXhl8H1iGNf45ZdfPgI6+f\/NN99M6x4A6Ck7nTLc8QVh+6uvvkq53LDjyMSxZdLicDypHIPBt5lZDlqy4PvnGCjsuEwmk8lkKroMvk8M+\/zzzyODvkwA5Z\/\/\/GdtGOBvUc3gOzUz+DYzO0Et7vD9swe8P\/38o\/wYE\/3080+hx2kymUwmU1Fl8J37RnQbsAW6UjFAPdXUb5YVtu7xlJPqMfrLfPzxx\/NhPew4Cjs2\/lIOxr0PiH733Xf6l\/X85Trzl8V6n3zySX55GMftlodtjxV2PNjx+AqjfPbj1g+D6WCZHGNhx8Bf5xP+N\/g2M8tBiz18\/\/yzfPD12\/Lmly97eqlY9ZZ3DB99+17ocZpMJpPJVFQZfOe+AV3BdPPCDADzr+vg9GgwSPlB+CtKOQ4WHQQGje\/9+wmeV9hxhH3nB013XEGQ928T\/EyZfnBlO47DbU\/9MQy+sUz56ssvv8zfR9j6wTJZl+PCjuUTlht8m5nloMUbvol6\/ySvf\/6CHHr3JrnvnQPFqvvfvUVe\/+JFjcaHH6\/JZDKZTMcvg+\/cN2DKD2IYoOWin24ZevbZZ48ARz7zvX97vwVhrqjlYKzjIroOBrGwMh10sn8sDCrDvvODpivDvy\/\/cRZ2LpThYDeV83KWSV\/5zV8u23BNnV+CdiyfsL3Bt5lZDloS4Pu1z59X+L33nRuLUQfk0Ls3G3ybTCaTKeMy+M59A7aC8O3MD3mFrcfnMEB0FoS5opbjN8rwR5fd5zCxzK0ThMqw78Lg25WBcXwcP3\/9\/vEb27tjc2X4j6UwCx4Pn4vqK47B7wdXbmFlOgseA+b3CWbwbWaWg2bwnaoMvk0mk8kUjQy+c9\/8MBk0P1wWFQQzCZR+8x\/3sYASC4PKsO+OB74L268fvp2xPlH7ox1n8HgKK\/9ovmIZ2wTLcZ8LK9NZ8Bgwg28zsxPADL5TlcG3yWQymaKRwfeJYcBVEBYx4M7Btx86\/eZfJ8yCMFfUcoLmIJPyCyvTb2FQeSzQ5HuWs54z\/74K229h\/nTl+UHWb5nwVdgy9ufKLaxMZ8fyCWbwbWaWg2bwnaoMvk0mk8kUjQy+TwxzIBuEriDIAWGs5z6z7tFgEgPm\/Ntgx1sOx\/Hee+8d\/pRnrOsvI6zMDz\/8MP98wo6jsGNzx+GOi\/Wc+eHVLff7jXVJ86Yc99ltH1ae3\/g+7HiC53UsX7njc5+JuPuPMVgm6\/gHXAs7Bv\/+DL7NzHLQDL5TlcG3yWQymaKRwfeJZUCWv58wCoIiEOZfXhgEOnOwyLoOSLHjKQcQBAj96wcBEQsev7\/MsOMI+46\/bju33O+DINz6y3DlsL0rz8GvW36088yErzD\/+pTnpkqjfGeU79bxj+Z+LJ9gBt9mZjloBt+pyuDbZDKZTNHI4NvM7PgtCKu5ZgbfZmY5aAbfqcrg22QymUzRyODbzOz4LCxtO9fM4NvMLAfN4DtVGXybTCaTKRoZfJuZHd386dso18EbM\/g2M8tBM\/hOVQbfJpPJZIpGBt9mZmZBM\/g2M8tBM\/hOVQbfpvTFKKcobFnSlEvnYjIVtwy+zczMgmbwbWaWg2bwnaoyA9\/Ayk8\/\/aQjYn7zzTf5+vrrrwt8ZjnrGdwcKXzy448\/qo++\/fbbfJ\/xP9+xLGy74hbX8\/3335d3331X\/w9bJ0zungluQ383zpe\/x1NeJoSPP\/nkE\/nggw\/0GPz3qTtejuv777\/P+rGZTEmUwbeZmVnQDL7NzHLQDL5TVWbgGyB54IEHpH\/\/\/tK2bVtV69atpUWLFvrXfde5c2ftz2TgUlAOvJlT9IYbbpBRo0ZJ8+bNpVGjRjJw4EDZvHmzzlHKOn4gjIOA1L59+0rDhg21sSVsnTBxD3zxxRfy6aef5p8Tfx955BGpV6+eTJs2TRsfsnm+gPecOXOka9eu8vTTTxdo8HCD4IwZM0a2bNmiI9H6tzWZTEfK4NvMzCxoBt9mZjloBt+pKjPwDaQ89thjMnbsWOnXr5+qVatW8qtf\/Urq16+f\/x0g+cILLxh8B0Qk9fnnn1f\/VatWTRo3biy9e\/eWYcOGSadOnRRGp0yZIh999FHs4JvIfI8ePaR27dry1VdfpXx8wOw111wjw4cPz78f2Pb222+XZs2a6feUnc3zxb\/Tp0\/XRqInn3xSj9Et4xrdc889emwzZsyQjz\/+uMC2JpPpSBl8m5mZBc3g28wsB83gO1Vlrs83kAREAeLolltukVNOOUVWr16d\/x3L4waPcRAR76FDh0qlSpXkyiuvlFdffVXBD599+eWXcuDAAdm9e7f+Hzf\/FRW+2e6KK66QLl266Hn6vyf6TaQ\/2400x4Lvu+++W5o0aSJTp07Vdf3bmkymI2XwbWZmFjSDbzOzHDSD71QVzYBrANjBgwcVvtesWZP\/PZB1\/\/33y6FDh+Sdd96Rm2++WTZu3CgvvfSSpi8DXHxHmvW2bdvk8ccf11RmIAywe\/DBBzX198UXX5R9+\/bptvv375fPPvssH+BIZWYf27dv13Juu+22\/CjlK6+8opFVwOnRRx+VXbt2ydatW+Whhx7KB1v2BQCSdgzwkmK8d+9eBWLXD5h1KPOOO+7QfezcuVOPzaVJA22cy1133aXb79ixQ5dTrh8o3bo0VJQtW1ZhlP7GfuhjfdcH2u0bEHz55Zdlz549uv\/rrrtOj9f5iuVMWcJ5vf766\/k+vf766zW1muMkAwHfcB388Iv\/br31VvU9ZeEX\/ImvNm3apGW9+eabug3HE4Rv\/IKPuU7OX6z72muv6XmyLcdAmXRLIKrPvYJ\/uC4u9Z7t3TlTzu9\/\/3u91hs2bNCIOcfn\/Mk6nD\/lUDYRaq7\/1VdfrefpjoPyKJ\/j47rgE\/zk\/JYufFMG23BtOIf169frsZLVwD6eeeYZvZfYlnXddty\/XAu3T9bluLn\/OEbO290XnAdT03AO+JSGCs6Fdf3HazLFQQbfZmZmQTP4NjPLQTP4TlXZhW9g6fLLL1dYW7x4sfZprly5soIHkEiqcbt27aRbt27SoEEDadOmjaazAz5AIn2hL774YhkxYkR+P2PStCkLoATygJAOHTpomjvl9ezZU9auXavHBKzSB33BggXSp08fXYc0YlLkOV7ghX0B9h07dlSxP46D\/TkgBJbWrVun\/dgpY\/DgwXLRRRfJfffdp8fAuZCazL569eoll156qR4TkA4IOn8AYIDWhAkTpEqVKgqnbllhYv\/33nuv+ojj4vhITWf\/bE95QPDEiRPlwgsv1FR2zpU+5Phq0qRJCqicL5AJuHNdKNtBLP4A6ABvMhdatmyp14xUePZ52WWXyXPPPafnGoRvvmd\/S5Ys0X7RnCPr3HjjjXqcgP2zzz6rfadLlCghJUuW1HOYPHmy7pvtuS+WL1+u15TtaazB\/1wPyiZaTlnXXnttPjizPvcMmQMcJ+des2ZNXZ9GF44V8GY\/3GP062Z9zg2Qxa\/pwjf74B5gnxwf+6BxgetPYw\/Xhy4FNCxRntvuzjvvVL+S4cD58Hvo3r273j+Mo8C5jBw5UgGcc2V9fEC\/eJbVqlVLfeO\/t0ymOMjg28zMLGgG32ZmOWgG36kqu\/ANTAFRpUuXltGjRyuMEHkEBhHAxsBtRP0AZfqLA0tA3BtvvKEgW7duXY1WA2lE\/YAUwI9IKBFBQIe+5cAOkUGAjsg6x0Q0tFy5cjJo0CBdTgQdKARyAHXWBwwpzwETEVeAEUgHtDlO1gGuAFz+J9LJsTDqN8BKtJJjJ0rLPiiDBgAAmDKdPwApIs2AEw0JHKdbVpgAe4ALmCdaTNkAH34FGvEdjQNDhgzRho0VK1boMdKIwXfnnnuurs93NEwAdW+99ZYeC9dn2bJl0rRpUwVeIq6A8Pz58zVqS9kAL3AO+HG+QfgGWoFbGh8YTI1yWYft8An+xoeUV716dYVRGjUAZK4zx1WhQgWZO3eu+pJrwjECm1wHzpdrTQMA\/uQ4gV7WP\/300\/W4WE45CxculIoVK2qjB+fGfoneA69Eo7nXHLhyjJmIfHM\/c3+yPf5if3QnWLVqlTYgsT0+5dw4bsqdNWuWfse9QgMBDQLc61wz7gmuMw0FNBpxTDfddJOcd955ep0onwwH\/Mn+g8dkMhWnDL7NzMyCZvBtZpaDZvCdqrIL30T1iHISkSQ1GCByywAHgAQIIoJH2jbRXcAI0AE6gUWiikA2+2Bd0qHLlCmjcAeouagn0MJy4AbIYR9AEesS6eR7ygBUgR\/gF5Dj\/7POOkuBxkUnAWQi9uecc46mSwN3QCPRW9Ko3X4Qx8A5Ak+AIufCchoP2AcRZXfOHBfAyffAPXDmloWJ4yVqyjnQcEHZfIdfV65cmQ+a+ItoPGWSLs+2rAv4Aqg0CnBONHYAn0Aoxw4ssw0NIwA5gAsIAqos53iZUowMBLajIYFzC8I3UVw\/fHOdSb8mCgzQcyx8x2caEdz1YV2guXz58grTXBvOk\/W4jzhmzpf1AXHuL86Bz7Nnz5bTTjtNAdZBM9CKbzkWtmW\/+Ipjdv8TWT7zzDP12NOFb47NlctfBEDTSEBDDZFrsjS4Bhw\/69GIRNYCjQYs5xrRQEIDjiuDY+P+A7Y5DtbhmIny06Dg\/GcyxU0G32ZmZkEz+DYzy0Ez+E5VxQPfAB0RPj808D\/9hQFW+hWznYNS1gVqXQo3EVf2ARyRgg2sENUGTEgHJ+ILwAGg9MsGAtmHg28XLXXgyr5oEACI2Afw7VKm2Q5Yo3z2A\/yy\/3nz5imMA52kchN5BBaJtAPmlHHBBRcoOKI6deroZ9K43Tm7Bgci6iwH6t2yMHG8TIVF2TRAuOMD0GhQILIMhAJxRLmJ6APRrIOvgGXAjxRtfMU2QDR95zn266+\/XqO0LsKML8giYF\/OX5QD8J599tkKo1HCN2BJf3nKpisA+3J+eOKJJ\/Q643t8SKMJ8E0jh\/MLjQYcy\/jx4\/V6cs6cJ+fGudMQQr\/z3\/72t7o8E\/DNevif+4Fj5jyqVq2q8EzDBcdHZB\/op4EJyOYYGB+ABgKi9SeddJKcf\/75+fcO2R5cF64Vx0R6Ohkc9GnnXNlv8FhMpjjI4NvMzCxoBt9mZjloBt+pqnjgm7RlwMpBA0BBBJnoIOBDdJuoK9AFfAMzDr6BQT98k0Lt4JvvAEC+A5DYFogh2ggUOfgmeu0AjfWJGrMvgIx90A8ZSHPrAIpElB18A4E0FABBRIlJGSbqTJQW6AJ6AX9gl8gmAgSBPs7b+YPjpSyOD5hy0U63X7cOcOogC\/imr7RLFWcdB9+kJvvhG\/B08E0ZRGEdfOM7oJrjJFuA4wOESRkHAkkD98M367N\/\/EhqOg0PhcE3feGJ5HKuHKODbyCyKPBNw0QYfAO13DMcL\/DNuXEfsZz1SPvmWIBvyuIeIoWeFHbuQ\/rD47Pf\/e53GYFvjo8sAsYkYL90b8C\/gDPwDWzTUEDEmoYD7inW4V7nuPl9cC9yLzB2gbt3nMj+wFcOvlkneAwmU5xk8G1mZhY0g28zsxw0g+9UVfzwjfieQceI7BGVBnSAX8CPdY8HvhEQB6SQxk0KOqnrlEGkE\/gGohzM8j1wBiwBy0S0iSwDUQ6+ACZAjX629O12IEoZHCt9lolmEpUnzRvw5VhJfWcdJ7ed8wfie6LlwBjHSfQbMHXL2YZoKVAK3AFsjIwOgLFvysN\/RNQZtI1oKGCYCnxTHo0JwC19w931YhnXh3OmIcGlnXOsACRp52xDeUH4Zl36wzNHOdeJ\/fI9DQts44dvIvXAfmHwzT3AfUQmAX2mAWR3LjR0nHHGGdoQwPHS6HA0+OY6E7HnGIjsc0ycE1B88sknK8CnC9\/cowyyNmDAgPzp4vAHsI8v8QffMUYAjTWkkZPdQdcJzolldMfg+tKXm+\/cveOWsx+Db1NSZPBtZmYWNINvM7McNIPvVBUP+AbEgFVgDPgENpmSifR0UnJTgW8gEiACygAYygCK6Td+ySWXKFwB3wA08Eh\/YKCXlGsi10ROKZdtOA5SwYkmA2H0JydCyr45bqCeAeEYXIvjAsqIbgLuACLRWqAKgKTvOGWSSk9KPBHloK84NvxEJBh4I\/oJYAGJROuJpAKXRNsBN9YhYszAW5TNX75DwB7Qmgp88x3HAwAz+BkNAEAjsAcgcwycB6nd+Atf0F+cPsyFDbhGFwGyAYBcgJsINensXDvWcfDNdkTc+Y4B0Dg2rjPXxME3jR5Eezl\/zpeR2cksIEWba0FmA1kMnMex4JvjGjdunF5b7hnK5frio+OBb+4DzpdGEM4F4X8abhD3NufPfYFv8VeNGjXy4ZtjxU\/cg6TJA+Y0OHDM+J1jcGMdEO3nOPA905bxmXUMvk1JkcG3mZlZ0Ay+zcxy0Ay+U1V08M10ScAQwOm+B7IZlZtoqh++gTEAjTRiQBDwBZSIILZv316BBFgC3EnTBdLYDpAhUk40m8g3UVkAGFADYIjAAjcAOesDsoy07qarAryIqgKqQJ+DTkCZ5cAd6xDtZB1AiOVAFRFT9sNgWazDcZFWzjGRpr1o0SL9HlAFyPif6L4bAM0v9gtYA+1AF34AhgFYtscPACf+AwKJyuMLjotyOU4GowMmaeAAWocOHargybGwD46Lhg2ixUS5HVjyPSDNtaKfNtu76wKQ4jMaQdw5cDychxvYDIgGrEkpByrxD8fKNaZBguvJ8QOf\/M9gYazDeQDTZDsAtAA2DQlcB7IISM3mfDk+GjDIKuA43Pnid8riGFkHWGcQMj98c4zcP6Smcw\/RmIHPOBf8x4B5pHzjE8rhGsycOVOzJTiWIHzTqAO8sz7dGcg0QPTlZ452GgY4DhoUuP+4j\/EVjSIu+s61xmcAO40MjGDuIvpuPzQO0LiAXzhWxPkC+hwT27J\/GoXcdiZTHGXwbWZmFjSDbzOzHDSD71QVDXwj4BpI9I\/gDSQRjQRS\/GADkACMRA4BX+ADwCV6SF9XYAUQc9N2AW9sB2QR5SUVHPCmTGCTcoi8A+ZsAxSyPiBJ5BuIYR0GY2NbouSuTAdH7IeoKiBJhBuoYx23nGPj\/ABeIpMsB5w4Jo4D2HNRWqAP8MUXrOPO24ltKBcAZL8cE8fPYHIAPw0P7NOtRxnsHyglasz+iYgDzixn\/3x2qepuH5TPueAjPrvviY5TBgOCcY38ywBDynHnynmwHvtgOesTbec4+Z\/9cxx8RwMM58D\/nDt\/8QvrIAZkozyuA\/vg+BBRcPzpjoVzwAd8jy85VlL62Y9bh2uIP5yfOH6uO+XiK64dZXOclEEUG19z7mzH+eBX9sNxcj9yjJSD3PGyPfcn9xb3B+J4uM\/YhvuQzzQMUC775lrw190fHDcNIDQicB+yb\/9+uNc5H8rBh+yL3w3lsz2NBNwjwLzbzmSKowy+zczMgmbwbWaWg2bwnaqig++iCLAAPhw8paOwcoiOE20EJFl+rH0d63iOtRylsk5Qx7PN8ZZdVLljCltWmFI5tuM5V3S8xxAU+3GNBGHLMyG3j7Bz4jsgmv7epKc7IA+u59Y9Ht+YTHGTwbeZmVnQDL7NzHLQDL5TVbzgO2qRpksqN9FGAxpTcQgoJ1uB\/v1Ete0+NOWyDL7NzMyCZvBtZpaDZvCdqk4s+CZdmlRe0ocNekzFISLZpKCTbk\/6edg6JlOuyODbzMwsaAbfZmY5aAbfqerEgm9L4zXFQdx\/TmHLTaZckcG3mZlZ0Ay+zcxy0Ay+U9WJBd8mk8lkyp4Mvs3MzIJm8G1mloOWDPh+Qe579yYF4OIS8H\/\/u7cYfJtMJpMp4zL4NjMzC5rBt5lZDlq84Zu005\/krS9elqc\/fkCe+qh49fTHD8qbX77kHZfBt8lkMpkyJ4NvMzOzoBl8m5nloMUevj3Q\/fHnH+T7n76V74pZHMMP3rGEHafJZDKZTEWVwbeZmVnQDL7NzHLQ4g7fefpZITwuCj9Gk8lkMpmKJoNvMzOzoBl8m5nloCUDvk0mk8lkyl0ZfJuZmQXN4NvMLAfN4NtkMplMpuKVwbeZmVnQDL7NzHLQDL5NJpPJZCpeGXybmZkFzeDbzCwHzeDbZDKZTKbilcG3mZlZ0Ay+zcxy0Ay+TSaTyWQqXhl8m5mZBc3g28wsB83g22QymUym4pXBt5mZWdAMvs3MctAMvk0mk8lkKl4ZfJuZmQXN4NvMLAcN+P7b3\/4mf\/rTn0wmk8lkMhWD\/vznPxt8m5mZFTCDbzOzHLR\/\/\/vfCuAmk8lkMpmKV2ZmZmbODL7NzMzMzMzMzMzMzMzMzCI1kf8fBe65uDHiQSsAAAAASUVORK5CYII=)\n\"\"\"\n\"\"\"\n### 3 . Model Blocks\n\"\"\"\n\"\"\"\n\nHere we the building blocks of our models:\n\nContractingBlock (Encoder) block: Apply convolutional filters while also reducing data resolution and increasing features.\n\nExpanding (Decoder) block: Apply convolutional filters while also increasing data resolution and decreasing features.\n\nResidual block: Apply convolutional filters to find relevant data patterns and keeps features constant. We will use here some skip connections in order to get Residual blocks\n\nLet's go to the implementation .... \nFeel free to ask about any line of code\n\"\"\"\nclass ResidualBlock(nn.Module): \n    def __init__(self, input_channels):\n        super(ResidualBlock, self).__init__()\n        self.conv1 = nn.Conv2d(input_channels, input_channels, kernel_size=3, padding=1, padding_mode='reflect')\n        self.conv2 = nn.Conv2d(input_channels, input_channels, kernel_size=3, padding=1, padding_mode='reflect')\n        self.instancenorm = nn.InstanceNorm2d(input_channels)\n        self.activation = nn.ReLU()\n\n    def forward(self, x):\n        original_x = x.clone()\n        x = self.conv1(x)\n        x = self.instancenorm(x)\n        x = self.activation(x)\n        x = self.conv2(x)\n        x = self.instancenorm(x)\n        return original_x + x\nclass ContractingBlock(nn.Module): \n    def __init__(self, input_channels, use_bn=True, kernel_size=3, activation='relu'):\n        super(ContractingBlock, self).__init__()\n        self.conv1 = nn.Conv2d(input_channels, input_channels * 2, kernel_size=kernel_size, padding=1, stride=2, padding_mode='reflect')\n        self.activation = nn.ReLU() if activation == 'relu' else nn.LeakyReLU(0.2)\n        if use_bn:\n            self.instancenorm = nn.InstanceNorm2d(input_channels * 2)\n        self.use_bn = use_bn\n\n    def forward(self, x):\n        x = self.conv1(x)\n        if self.use_bn:\n            x = self.instancenorm(x)\n        x = self.activation(x)\n        return x\n\nclass ExpandingBlock(nn.Module):\n\n    def __init__(self, input_channels, use_bn=True):\n        super(ExpandingBlock, self).__init__()\n        self.conv1 = nn.ConvTranspose2d(input_channels, input_channels \/\/ 2, kernel_size=3, stride=2, padding=1, output_padding=1)\n        if use_bn:\n            self.instancenorm = nn.InstanceNorm2d(input_channels \/\/ 2)\n        self.use_bn = use_bn\n        self.activation = nn.ReLU()\n\n    def forward(self, x):\n        x = self.conv1(x)\n        if self.use_bn:\n            x = self.instancenorm(x)\n        x = self.activation(x)\n        return x\n\"\"\"\nThis layer will be on the top and in the final layers of the models .. It's role is to map the input matrix to desired output channels\n\"\"\"\nclass FeatureMapBlock(nn.Module):\n    def __init__(self, input_channels, output_channels):\n        super(FeatureMapBlock, self).__init__()\n        self.conv = nn.Conv2d(input_channels, output_channels, kernel_size=7, padding=3, padding_mode='reflect')\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x\n\"\"\"\n### 4 . Full Generator\n\"\"\"\nclass Generator(nn.Module):\n    def __init__(self, input_channels, output_channels, hidden_channels=64):\n        super(Generator, self).__init__()\n        self.upfeature = FeatureMapBlock(input_channels, hidden_channels)\n        self.contract1 = ContractingBlock(hidden_channels)\n        self.contract2 = ContractingBlock(hidden_channels * 2)\n        res_mult = 4\n        self.res0 = ResidualBlock(hidden_channels * res_mult)\n        self.res1 = ResidualBlock(hidden_channels * res_mult)\n        self.res2 = ResidualBlock(hidden_channels * res_mult)\n        self.res3 = ResidualBlock(hidden_channels * res_mult)\n        self.res4 = ResidualBlock(hidden_channels * res_mult)\n        self.res5 = ResidualBlock(hidden_channels * res_mult)\n        self.res6 = ResidualBlock(hidden_channels * res_mult)\n        self.res7 = ResidualBlock(hidden_channels * res_mult)\n        self.res8 = ResidualBlock(hidden_channels * res_mult)\n        self.expand2 = ExpandingBlock(hidden_channels * 4)\n        self.expand3 = ExpandingBlock(hidden_channels * 2)\n        self.downfeature = FeatureMapBlock(hidden_channels, output_channels)\n        self.tanh = torch.nn.Tanh()\n\n    def forward(self, x):\n        x0 = self.upfeature(x)\n        x1 = self.contract1(x0)\n        x2 = self.contract2(x1)\n        x3 = self.res0(x2)\n        x4 = self.res1(x3)\n        x5 = self.res2(x4)\n        x6 = self.res3(x5)\n        x7 = self.res4(x6)\n        x8 = self.res5(x7)\n        x9 = self.res6(x8)\n        x10 = self.res7(x9)\n        x11 = self.res8(x10)\n        x12 = self.expand2(x11)\n        x13 = self.expand3(x12)\n        xn = self.downfeature(x13)\n        return self.tanh(xn)\n\"\"\"\n### 5. Discriminator Architecture\n\"\"\"\n\"\"\"\nThe discriminator is responsible for differentiating real images from images that have been generated by a generator model.\n\nBellow, we have the architecture of the original CycleGAN discriminator, again, ours have some changes to improve performance on this task.\n\"\"\"\n\"\"\"\n![Patch GAN.PNG](data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAisAAAEtCAYAAADJHyCoAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAFZgSURBVHhe7Z0FnFXl1odvfnrv9dqBjSKiSCspXdLd3d2dCiIhIaIgIAhIN0hKSkt3N9LdPTPr2\/\/F3tzjsE\/OqeH8n99dF2dm7zNnZs8577PXu971\/uX9j9IKg8FgMBgMRrjGQ1khhBBCCAkXKCuEEEIICWs8kJVokZjbRtw04kboIvqWxNy7L9E3YyTK+NCXiL4VIzH3jZ9HYh78aIQQQkJCTEyMREdHS1RUFIPxSOBvA38jFu5lBZJyf73IvWUhjegbG+TW4YtybUOMXFsrvsXmKLl3\/qbEREFYCCGEhIq7d+\/KjRs35Pr16wyGbeBvxBIW97ISfUbkdl+RW18Y8XnI4t6pwXJh1kU5Nylazk0UHyNGrq67L1E3KSuEEBJKbt68KZcvX2YwnMatW7fioayc+FEuTL9uyEqMjYR4HldXiURdN382QgghIYGywnAX8VhWbsRdVlZSVgghJNRQVhjuIh7Lyk3KCiGEPAZQVhjugrJCWSGEkJBCWWG4C8oKZYUQQkIKZYXhLigrlBVCCAkplBWGu6CsUFYIISSkUFYY7oKyQlkhhJCQQllhuAvKCmWFEEJCCmWF4S4oK5QVQggJKb7IyqVLl+TixYtuA8fZnR8OYf0McX2OOP\/ChQsa58+ffxj42NvHtp6TJ88rUMfaBWWFskIIISHFW1nBQLx7926ZOHGijBgxwjZGjx4t06dPl02bNsnp06dtHyeUce7cOVmzZo1MmDBBli9frh\/bHecuTp48qY8zYMAAadq0qZQvX17KlSsnjRo1kv79+8vKlSvl+PHjtufGDvye8Fj4\/Y0cOVJ27typwuPq2LFjx8qkSZNk69attsdZcezYMZkzZ44eu379eq+FhbJCWSGEkJDiraxgoJw5c6Z88skn8s4779jGu+++Kx988IFkypRJWrRo4dMA6RgYtA8dOiTjxo2TKVOmyK5du2yP8zROnTolvXv3ltSpU0vr1q3lxIkTtsc5C\/ws+Jk6deokGTJkkDfffFNefvnlP8Ubb7whadOmlVatWsm6devc\/vybN2+WypUrS8KECfV3+NVXX8n+\/fttjz1y5Ih+\/aOPPpIkSZLoz3Dw4EHbYxGQmRIlSki6dOlk6NChmmGxO85ZUFYoK4QQElK8lRVkE8aPHy8JEiSQp556Sj7++GMpUKDAw8iXL59kzZpV3n\/\/fXnyySd14G7QoIFmCuwez5M4e\/asrFixQtKkSSPZsmWTRYsW2R7naSDb0aFDB3nppZekRo0a8scff9geZxcY6Ddu3Cg1a9ZUIXnuuedUyqpUqSJNmjTRDEulSpX0c\/jaa6+9JtWqVdNznAkLPj9mzBhJnDix\/N\/\/\/Z\/87W9\/k4wZM8rSpUttj4eYQIL++9\/\/yl\/\/+ldJmjSpnu9MQiBLeD54LpA0yooXQVkhhJDQExdZQRZg1KhRsnfv3oeBKSIMzJhiQWbh3\/\/+tyRKlEh+\/vln28fzJM6cOaOC8sorr2jGBpkdu+M8DV9lBYM8zq1fv74+F5xfsWJFnZJBdgZfRxYIx6xevVrKli0rL7zwgv6uOnbsqNJlJyz4nTZv3lzlJmXKlPovzvnmm2902i328Y6yArHB7xgZHvzu7Y6nrNhIiKdBWSGEkNATF1lBJgC1KXbHoQ5k2bJlOk2BQRV1HFeuXPnTMRi4EVZRKgZRu8EcU08LFy58KCszZsx4eG7sY\/E5SxqcPWZsWUFNh3UeznFWHIvnMXv2bM0W\/etf\/5Lq1avr9FTs46w4cOCAlCpVSrMl+D1gWseuDgVTSjly5FCZ+Pzzz6VIkSLy9NNP67SQ3fSOo6w888wzKivPP\/+8tGnTRo4ePfrI8ZQVGwnxNCgrhBASegIlKxgQDx8+rHUSGNjLlCkjV69e1a9hwF67dq307dtXB3NM7WDqqGDBgjoIz5s3T7MpEAYUwKImAxkMa1BGESsyFZj6sOpNIBmYavr222\/1e2XPnl0Dx+Jz27dv12NwrKOsVK1aVbMg\/fr1k+LFi+vz+Oyzz\/R7YhoG2RDrZ9q3b59O\/2D6Cz\/X\/PnzbeXDCny\/H374QQXrvffeU8lCvUzs41CM+9Zbb0mKFClU8FBXgjoYZFlQGBv7eEdZwe+uZMmSKjeQEfzucI0cj6es2EiIp0FZIYSQ0BMoWcEgjkwCCnEhK5AGZFYgINOmTdP6FgzQeBxME6Go9NVXX9WsBaaPfvnlF8144Hvh+yCr8o9\/\/EOeeOIJnVqBAKA+BMWmEJvFixdLsWLFdJDHY7799ts6TYXHxPdBtmLBggX6vBxlBdMnhQoV0qJgCAXOwffC84C4\/PbbbyoYeN4bNmzQ54Ln0LZtW82c2P3sjoFiYExboTAYMmUJEwLSgOeSP39+\/X6YNsLHWEWF+pwXX3xRf8bYcuEoK3juP\/74o4oZfj\/4vf7+++9\/ygxRVmwkxNOgrBBCSOiJq6xAPDAwOgaEANMRWL0DaUANBgZXfA1yAamAKCRLlkwHYyz9RaAWBNMl\/\/znPzXjsm3bNs2sNGvWTEqXLv0ws4Lz8Xiol0FmBYOzlV3Ac0L2o0+fPpotqVOnjooQngMKXSEPlqxABqxzKlSooAM56kRq1aql56BAuG7durJnzx6VDGRSICrIrGCJsV1WJfbvAmJgBT52PBZZG0gWipHx\/SAdOAafR5EuflbIXuxlzI6yUrRoUVmyZIlmmSBm+L1ipZDj9BFlxUZCPA3KCiGEhJ64yApEZNiwYbo01jFQgwGRgIz85z\/\/0SwICm4x4GPgxBQKPofB2XEQRibmiy++kL\/\/\/e96LvqUYPB2rFmBzDjWrOAxv\/zyy4fZkEGDBqkQWV+HNPXq1UuzK6lSpdIsh6OsQAggTDjOGsRRKIzMCTIVWO2EaSJkV9A\/BgWt+D52GSU8LsQCmZHYsWXLFs3EOGZWUNiL5c8QjLx586p0WV9DrxVknLDiaPjw4fo7sL4WW1aQ8cHvDmIF+cL0ESTS+l6UFRsJ8TQoK4QQEnriIisYzDHQYurFitdff12nafA1LKuFrKD+AwMzxGTHjh3SvXt3zWCgjsTxsTHtg4wIZOXDDz\/UrAo+72o1ECQDPUSQdcEUSOwGb\/iekA\/0e6lXr94jspIlS5aH38cKZDYwbYMMD+QImQucM3jwYJUViI9dLQmarkFukMWJHZAOFBlbU0cQKWRs0CsFzx3FsY5CAsHBMnAICWpwHFcs2ckKxASZKEgept2QaUKNDY6nrNhIiKdBWSGEkNATF1nBKhfICqYwHAMZAQyakAcUi0IWIA0YoCETkBIMuJAVawqjZ8+eWtcCEfBGVvAYqC1BhgQDuGOmBoHvic+h2BffE9NGjrKCrrPWoG4FBv5Zs2aprGCKCFM1+Lkx9QMBw8+O7I7jOQgIDH5mFMpagZ8DzxsZD0xPWd8LzwO\/R0wp4WstW7bUbA1+NgS+BgnDc4DoIFtliZidrODnhGQhC4PfP6QRUggxoazYSIinQVkhhJDQExdZQY1Ely5dNAvhGJiCwKoUDLAQE0sgLFlB7QfqULD6B1NCGNQxdYFpGsiIN7KCgRqPgedjDc7W15yFJSsQLSw\/jr3cF7KCJcqOsgIRgKAgYwTBwDRXbDGCROA542e3Ai3xUUCLc7BM2pIVZJjwvfE9IH0QEjR3swI\/P54f5AiZl27duunjW98ntqzg8\/j94vHxuPhdIWuDomI8J8qKj0FZIYSQ0BPXAltnq4HsAhKAugwsDcadP8QDgy0Ka7t27apZgc6dO\/ssKz169LAdiPE59ENBXQemUxxlxa4pnJ2s4DHw3DHVBblo166dR6uBkNXAdI6jrEByUIMDKUERb\/LkybVjLYTCMfBzIVOF54HsEZZ74zGdyQoCwgJJ+vTTT7UHCzJHkKz06dNTVnwJygohhISeYMoKzkXhKiQB2RRkHaxaFnwdUyMo2PVGVpChQK8RTAOhC2zsbAcGZnwPZF3wvXGuL7KCz6PGBP1eUIeDVTpz587VYx3PdQx8DYWyeAxHWcH3R28VrCzCtNfkyZMfKchFoLAXAgY5ws+H45CZciUrCPyev\/\/+e\/35UL+CehgIEWXFh6CsEEJI6AmmrGBKCBkCDPYYuCEnyARYX8cgjIyFN7IC0cCyZgz8mTNn1ufn+JiYvkFzNxTKYvUSViD5KitYEYRaFpyHjAiyFmhx73iuY2BlEBrN4XEcZQXZFtS2QCSwRBvCheccOyBe2BMJvV8w\/YRVSxAmd7KCwOojLNX+y1\/+ogW+mEqirPgQlBVCCAk9wZQVSAGamGGQtTYkxIAMOcCAjb4omPbAihs8NopvMWhDVvDfkBUMuOgKa03pQEawsggi8uyzz+qUEnYwxjmQISx\/Rm0MZAHTTxjYfZUVK0uDYljU62DVE5rNQWAwzYSsBwLTQ\/i95MmTRzMikC9LVlBsPGTIEJ1OgkSg9gXPx\/H7Owb6wqDtPsQGdT2Y4vFEVvDzQ3QgdzgXtS+UFR+CskIIIaEnmLKCpbnog4JiUgziWDaMpm3oD1K4cGGdGsJjQhIgHtjJGLIBeYCAQEiQlUHhKJbzQlIw0COLgJ2dITMQENSIYOUNzkcmB4M6Gq9BchxXA3krKwgM9OglgykndL1FXQgKg\/F88LPUrl1bV\/HgZ7G64OJjrPjB94JYWP1QsGLK2eaDVuC5\/fTTT\/p9IDeo7cE57mQFgcJhCCB+TsqKj0FZIYSQ0OOtrEA4kElAAScamSHjYXecXSCLgmkMZD8wmGN6AzUbGPSRNcC0ynfffafFpvg8WuFjygfZFUgSzkPRKQpT0Y7e2rgPgz1WHjVu3Fj7nODxIDYItNBHsSpqRPC98TwwnQPRweO3b99eHzv280SbfcgEfkbsquz4dQQyQdjbCBsQQoRQMIxsi9XeHzUiEBgUt6IhHn4mCBKKdNGdFs8f\/WeQGYr92I6Bnw3TSRA7PB9IEj5Gozs8BnrH4LnYnYufAxkftPHHuZgmg\/jg92l3vLOgrFBWCCEkpHgrKxgA0bMEgzmmGTAlYXecq0CHWZyPviWQCBTVQnowsEIc8LgDBw7UQd6xJgRZEUgJpo+Q7UC2xRrsMQBDQiAWY8aM0fb9KDJFUSoyIY5SYAkAalnwtdiZDTwWniOW\/eK5oNbG8etWYMoHzw9CAnHB9BCKeJE9ws+DrAiyGHgsPA4yQKhZQeEsfn48B0+yHHh+q1at0hVEqHfB7x\/n4newceNG\/b3YnWcFZAbfD4HnS1nxIigrhBASeryVFQQGO0gLwtuBD2Gdj0EYAz7+tR7L+pr1ecfBHF\/Dx9b3jj3QW1+3HtfuMaywHsfuawjreSDw33bHIPA16\/tBiBD4b8fzrMfC98J\/u\/vedmE9F7vHsL6Ps7CO9fZ7WkFZoawQQkhI8UVWGJEVlBXKCiGEhBTKCsNdUFYoK4QQElIoKwx3QVmhrBBCSEihrDDcBWWFskIIISGFssJwF5QVygohhIQUygrDXVBWKCuEEBJSKCsMd0FZoawQQkhIoaww3AVlhbJCCCEhhbLCcBeUFcoKIYSEFAxEV65csR2kGAwEZYWyQgghISU6Olru378v9+7dYzBsA38jFpQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVQgghhIQ1lBVCCCGEhDWUFUIIIYSENZQVEp7EGP9DRPsYxrl4DEIIIfEfygoxgRncNn45u0Xubw1hbJOYu\/vkzvGbcnO\/yM19PoZx7t0z9yQmisZCCCHxHcoKMYky\/nfauNbfGr\/vbiGLmBs95P7ZoXJx9hU5N9m41pOM6+ZLGOdeWnJfom8jzWL+iIQQQuIllBVict\/4xZw0rnUf299\/sCLm2ldy59B441rfsL1+3sSlX42f6qrxo1FWCCEkXkNZISaWrPS2\/f0HK1RWDk6Q85QVQgghJpQVYkJZIYQQEp5QVogJZYUQQkh4QlkhJpQVQggh4QllhZhQVgghhIQnlBViQlkhhBASnlBWiAllhRBCSHhCWSEmlBVCSOC4efOmHD58WE6ePCn37xvvN4R4AWWFmFBWCCGB48iRI9K2bVvp2rWrHD16VG7duiX37t2Tu3fvmkcQ4hzKCjGhrBBCAseVK1dk8ODBkj17dsmUKZNMmTJFdu3aJevXrzePIMQ5lBViQlkhhAQOTP1s3rxZSpcuLbNmzZIGDRpI0aJFpWfPnhKj26QT4hzKCjGhrBBCAgeE5NSpU\/LFF1\/Ijh07pEOHDpIrVy5p3LixrF69WqeECHEGZYWYUFYIIYEBdSknTpyQY8eOydKlS6VHjx5Ss2ZNnQrasGGDTgXduXPHPJqQR6GsEBPKCiEkMFy4cEG+\/vprmTdvnpw9e1YyZMggQ4YMkatX8QIlxD2UFWJCWSGEBIbbt2\/LoEGDpGPHjhIdHa1ZFhTc4r8J8QTKCjGhrBBC\/Aumf3777Tfp1auXFtYmSZJEatWqJdWqVZMuXbrIoUOHzCMJcQ1lhZhQVgghcQerftD4Db1UICtY+TNw4EDp3r27FClSRCpXriwjR46U5cuXy\/nz582zCHENZYWYUFYIIXEHhbLDhw+X9u3ba\/EshOT69ety6dIlmTZtmlSsWFH\/mxBvoKwQE8oKISTuILMydOhQSZ48uaRPn15X\/2DJMqRl7969kjdvXmZUiNdQVogJZYUQ4h+2bt2q\/VSWLFmiS5Rz5sypH2P1z86dO9lThXgNZYWYUFYIIf4B0zyjRo2S77\/\/XsaPHy\/lypXTAtuff\/5ZRYUda4m3UFaICWWFEOIfICRbtmyRSpUqSZUqVWTs2LGycOFCWbx4sXkEie9cvnxZFixYIGvXrtVC6kALKGWFmFBWCCH+AyuCsMsyliljiTIGM2ZUHh9wfVu3bi2FChWSX3\/9VY4fP64N\/zDVF4jrTFkhJpQVQoj\/QMO3mzdvyrVr1yQqKsr8LHlcQCE1VnfVqVNHcufOrRtT9uvXT0aPHq1f8zeUFWJCWSGE+BfcYUNamFF5\/MA1xS7a2IgSG1NCVNKkSSPNmjXT7RX8DWWFmFBWCCGEeAayZWfOnJGffvpJRowYoZmVzz\/\/XKXl999\/N4\/yH5QVYkJZIYR4z61bt3Svn127dj1M\/6MJHHZYPn36NKeAHkNQUDtnzhzZt2+f7NmzR1d7oTMxlqwjq3Lu3DnzSP9BWSEmlBVCiHdATrZt26b7\/KCPyoEDB+TIkSOye\/du6d27t4wZM0Y3MeQ00OMDruWNGzekVatWMmHCBM2ufPnll7oHVCB30aasEBPKCiHEO7BzMtrqQ0ywVLlEiRLaAG7SpEn6MZYsX7x4kbsrPyZAVCCo2FIBPXQgqfgbQBE1uhJDTAMFZYWYUFYIId5x+PBhadmypXTt2lVKliwpP\/74o7Rr10769++v00NoDscmcI8PEM\/BgwfrhpTp0qWTpEmTStGiRaVu3boqrJgODBSUFWJCWSGEeAbqUFCbMH36dJ3+qV+\/vhZZYhqoSZMmMmTIEK4CekzAdZw7d64WzUI+UaeyZs0a3TUbfVbQSwd7PqHvCgQ1UFBWiAllhRDiHggI+qegRgED1YoVK3Swwg7L3333nXTu3Fm2b99uHk3iO5AVXNMKFSpoDxUU1GLqB0XUs2bN0g7FmAYK9FQfZYWYUFYIIe6BrKCosnnz5tpTAz02cEeNLrWoUfnjjz8eaQqGegYMcii8xX9zhVD8Ait\/KlasKGXLltUapV9++UV30960aZNOAWJX7UBfU8oKMaGsEELcgzto7AuDlSDJkyfXGhVMCTm7s8Yg1rNnT\/noo4+0xgFFmbgTJ\/EH1KKgVgVt9ceNGydvvPGGZtUgpoGc+nGEskJMKCuEENcg9Y86FWxQWLNmTd1FGbKCu25MEaD\/hiPIsKCOBc3CsJHh\/PnzpVixYtp\/JdDTBsR\/4LriuiOLMnLkSKlVq5Zm1rA0PXYWLVBQVogJZYUQ4hzIBaYDUKMwaNAgSZ06ta76gYBgWgB33bEHLnyMJcyoeUBrdtyhd+jQQQUG4oNaFzQSI+EPrhPqVtAAbuPGjXoNMR0YrCJqygoxoawQQpxjTedAPCAtpUqV0n4qAwcOVAlB743YAxcEB1kUZFawogTTRejPYRXk4k4dBbok\/EGtEbIrENVQTONRVogJZYUQ8mdQj4AlqViyirvob7\/9VtuqN2zYUKd1Fi9eLH369NF+K86AsKC4Fu338TjDhw+XZcuWaYYF52JlEQl\/IKIQVkwJBSub4ghlhZhQVgghfwZTOMWLF1epaNOmjU75oFYlUaJEMnToUO1Wi0yJp3ULaNOOrEyePHlUejA1FIqBj8Q\/KCvEhLJCCPkfaJ2ODemmTJkir732morJ7NmzdQUI+mtgNRCyK5ja8VQ4cGd+9uxZ3Vdm0aJFzKqEKbjuuM6egGsPWQ20dFJWiAllhRDyAAw8qE\/ABnVY8YPeGl9\/\/bVUrVpVBgwYIJMnT5YZM2a43fcHUwbodOq4Cy+E5fjx41pgS8IPXPuZM2dqZ2ILCOaCBQtk7dq1j0gJrvGqVau0\/giZskAJKGWFmFBWCIl0MBBhLx8Uv2K6plu3btpKH3v+YHdlFNQ2aNBAGjdurFkVV8KBQezgwYO6zHXdunUqKIHc6I74BzT3a9GihbbSt\/Z1Qt1Sr169tFD66NGjKpwWuKZYHZQqVSqd2ps6dao+RmypiSuUFWJCWSEk0sGKHhTDIoOCzAn+G1mULFmyqLigYymkA1MErjIqGKiQTcHKETQRg+SgOBcrSkj4AgmBhKJOKW\/evHq90VoffxfIokFKkCnDxxYQmp07d+qSZhRN49+OHTvqHkKQWUexiQuUFWJCWSEkkoFgYAkymrYhEzJs2DApXLiwNgFDXQp21c2dO7cW27orqMUAhnbsGPSOHDmi2RlMLfj7bpv4D8gnVnwhqwYpwWaUKVOm1F46mAbCtcMxdr10ILDou4ICaqz6wh5R77\/\/vq78wt+OP6CsEBPKCiGRDAYi7PPz1ltvaWt11KogI4JOpehQiztu9ERBvxRXWRWAO21MGSxZskQzMqNGjfLboEX8D\/qmYBl6nTp1NCtSt25d3ecJdUtfffWV7unkTDTxeQgLAn8XEFVkYZCBwfnIzPgDygoxoawQEslg0ME0DeTik08+kUaNGmnhJBq49e3bVwcwDECoRXEH7tCx7BnSgo63+\/fvdys4JHRgI0JICjoRf\/PNN7pBJWSlX79+DzMm3mTFLIFBsW3sTIyvUFaICWWFkEgHAwsKKCEqKIzFKiBkRzA9hLtkZF48AYMVpAaPtXr1arl6FS9EEk7gGiGs1VnY4wnZNBTJYrk6RLVevXouu9XifCubgv8OJJQVYkJZiShi7hhxwwjjxRDCiIm6LdF3oiT6pvFW42vcMt507xl\/vwF+s4wErMELnWsxgKEoNleuXLrCw9WgBTFB6h9TPRi4HAn0IEa8B9cExa\/ImiDrtX37dr3GKVKk0KwKlimjNgnL1F0tRUahLVYKoeAaq4ICmT2jrBATykpEcW+98U4zwojBIY17ZxbJlVUX5eJc8TkuLbwrN3b88UBYiN\/AwIMBCKs60KXWWc0JBj5rBVHJkiV1ACThDTJomN7Lly+fpEuXTq8vBBXTfMisFCxYUKeAIKiuZBPXHUuckT1bv369CmugoKwQE8pKRHF3gfH77mFE15DG9Q3rjGt9x3hdG9fMxzg\/JdqQlrsSdZMX2luQEUHb\/GrVqknLli1l5UrjDdIBDFRWwaSz2gNsVIjNDLFaaNq0adqdFoWaKMQl4QdW9owZM0aXpqOR22effSYlSpRQOUGWBP10du3apfVLrjIlmNobP368No\/D6jFcdwhQoKCsEBPKSkRx1xhIbnV75Pcf7Li6cqvxmo6yvX7exPkZxp\/vDfNnIx4BUUEBLMQCwgJZadKkidfTNhjcsDR5xIgRWoTbtm1bbSqGxyPhBeQDm0li2wTUo9SuXVuXF+Nj1Ck1bdpUa1ew0aQ7UNPSqVMnPRa1TXgMPHagoKwQE8pKREFZiXiwwgOrP9BPA70x0FsDmxRCYhC4A\/ckrY8+KlhBhOwMBjtkZ9CbAx1PSfgACUWhNPrfYPUPCqexLB1iib8DSEfnzp31uqGOxRWQHvRSQWZl3rx5+jiYJvRWdL2BskJMKCsRBWUl4kGNAgYotM9HH43Dhw9rTw2k97GKB8uVITDuwMAF8UGRJdrroygXGRrUMQRy8CLegWsEUcH1QX3J1q1b9ZphK4X8+fPrtceUnicre\/B19E\/B8nTUrOBfCG4goawQE8pKREFZiXgw4GClB+oXUBQLQcFmhUjlQzbQKt\/TTenwWKhpQYYGRZoQn9irgkhowV5PEBVca0hL1qxZNSOClvrIpKDIFlk2T5v3WX8\/yNZgBZk7wYkrlBViQlmJKCgrEQv27Jk\/f74OUhhgkEnBElR8Hg3BMBWA6SDUorgqsIwNHguCghVEFJXwY82aNbpiC7UqqFFC1gxF0einA1HB5oOY+nOWIUEmBZkY\/K1YYoJ\/vfkbiQuUFWJCWYkoKCsRC+6cseEcNqpDl1Ks+rB6q+COG\/v\/\/Prrr35rk07CA9QfQU6SJUum9UW41lj1M2vWLC2URWbNmXgg84KeK126dNHlymgOiL+jYIkKoKwQE8pKREFZiVggIahPQI+NMmXK6NTA5s2bdfDB1\/y5nwsJH5AFQVEtCmMhHciooGMtRATXHhkxK2PiCIQEy5qxNBmbUeJ81DlNnDgxoKt\/YkNZISaUlYiCshJxYNBBjQHqSlCPAkHBHj4YtIoWLap9NzytUSHxFwgJxAS9UQoVKqQbTjqTDhyLaZ\/GjRursEBy0fgPq4BQ14SpwmBBWSEmlJWIgrISUUBUcPeMJmBo3GXVleDzqFlBUSymhnC3TB5\/ICG4\/qhTwgogTAM6A8dOmDBBO9tiWTO2YRg5cqSuFsN\/BwvKCjGhrEQUlJWIAnUpKKLEMlX8N6Z5kFWBrGAwQkYFH2PgIo8HqCtBBg19b5zJiHX93YF6F9S0rF27VhsAIjZs2KDSGywoK8SEshJRUFYiBtxBY2DBfi8ojsQSVtQfoNMslioHu1CSBAfIClb\/oJAaq3+wkicuvVDwN4LVQthSASvJgr2TNmWFmFBWIgrKSsSAu1\/s01OkSBFdAYKW+FgVgv4qqFlA91LswEseL9BPBXUliFKlSmm9CTIjyKx5kk0JNygrxISyElFQViIGDEwooMTePViWjNU\/mAbCUmX03kBfFbTMJ48XWJY8ZcoUneJDFgTLk9Gp9qeffoqXfXAoK8SEshJRUFYiCqTwsd0\/lp6ixT6yLahP6d69u0yePFkuX75sHkkeFyAkCMiqdf2xAgjFsa56qoQrlBViQlmJKCgrEQcGLQxYCPRSQSdTrA5Cu3S0yiePP8im4fpDVuPbVBBlhZh4LyvHDzSTfdsayt0rHW2\/7ktQVoIEZSVigZhg+fLChQt1D59Ab0BHiD+grBAT17Jy61IH2b+9oaxeWl1+X1ZDY\/CAAlKlQgpZvrCqnD3W0vi9drI915ugrAQJygohJB7hd1mJufm5RN\/orGH3dV+DshJoXMvK0b1NpF6tj+W5Z5+UN994Wt579zl57dWn5Fnj49QpE8i08aXk+rl2tud6E5SVIOGlrFiva7uvxSUoK4QQT\/C7rFw500bWGnfdpw41t\/26r0FZCTSuZeXe1U6yf0cj6d09t+TJ+a4smFVRxgwvJlUrppQDxudvXmjvl8GMshIkvJAVXNdj+5rK7s0N5P61uGfPHIOyQgjxhDjJCt7EZk8rJ7265ZLuXXLIV0Z0aJNZcud4Rzoa\/04dV1rvyGKf50tQVgKN+5qVu1c7yrk\/WsmMSWWkeeMM0rh+OqlULrlcOd3GuM7+ueumrAQJF7ICKe3eNae+phHdvsghlSukkGqVUkpP47V+aFdj2\/N8CcoKIcQT4iQrMYasjBhSRDJnelPy5UkkrZpllIZ100qWT9+SujXTyPhRJSgr8QbPCmwhJZCWpb9WUWHp0jGbZlXuXO7IzEp8woWs7NpcX4oUel9SJn9FaldPLe1afioVyiaXIgWTSOf2WTXLYneeL0FZIYR4QpxkRd9szrSVaeNLS50aqWXezPJagAlpQQGmP+e4KSuBxjNZgZSsX1lLzv\/RSi6dbC1\/7G8q65bXlF2b6vtlVRBlJUi4kBVcRxRTV6+SUr7rl092b6kvk8aUkp+HF5Nr59r5LYuGoKwQQjwhzrKCgJRgGWv1qqmkbMmkUqVicmNAq2l7rK9BWQk0nsnKmaMtJXvWhNKlU1bZbdyB\/ziwkLyf+AWZN6O83LjQ3vYcb4KyEiQ8qFlBfcqAvp9JiaIfaHZl3Mjicuti3K+xY1BWCHl8wVuvrxEbv8gK4t7Vjrp8da4xaI0YUlhXj\/iz\/wZlJdB4JisYwA7tbizNGqWXjBnekJLFPpB1y2vITWMQ4zRQPMIDWcEU7pUzbWXz73Vk9E\/FZOPqWnLzQju\/ZkwpKxGE8TqMiTKGlHu+R4zxNsXXc\/gTbVyj68b\/XY7yLa4YcTv6weNY+EVWzh9vJRPHlJRVS6rLuT9aaqOwiaNLSI+uOVmzEm\/wTFYwDTBmRHEpbtxtlyv9kZQpmVR6dsspp4+28MtKEcpKkHAjK7iWeD0vnV9FbzxOHW6u\/XRQVL1nawPbc3wJykqgMewgaodxvSeENGJuTZY7f2yXy8uj5fJS8T2WRcudEzck+i5f1I8QY7wA7q22\/f0HM87dnCWjzu+RvIfuS46DvkeJI3dl6fVbYm0K4BdZuXCytUww5KR+7Y9l9PCiuiqoTs00MskQGMpKfMEzWcHKH9QkjRhaRO+4F8+tpMXUKxZVlTusWYk\/eCArm3+vLW1bZpI+PXLr9a5dI43x8adyeHcT23N8CcpKoLlrDGDGC0F\/33gPD03EXOsu19atNa5V3N6\/EVfXRhnXmi\/qR4i5KHJnku3vP5ix68r3UvDALvnrtvvylzjEk9vvStcz98XyUr\/ICjqXnjjYTNq3+lQSvfucpEmVQMb8VExXidgd70tQVgKNa1lB6h+9Vq6fbycHdzaSq2fb6rTfjg31NJuG5ayUlXiEhzUrE0eXlIzp35CkH7woDep8IqcPt9DXu93xvgRlJdA4ykroIuZKD7m2ZqOcNW6+7a6fN3Flhfm6Jn\/moazYX4NgxZbLgyT7\/gO2AuJN\/M2I9qei5JaZWvGLrKBe4ddfKshbbz4jjeunlZzZE2pRHlYR2B3vS1BWAo1rWbl9qYM2f1u7vKasW\/EgBvTNJ6VLJJXli9huP97hRlaw4uf8iVZSuOD7kj9vIu2flOCV\/8j8mRX8ehNCWQk0lJWI4TGTFWRm\/C4raBQ26NsChrBUlDNHW+gcN6aDWLMSn3AtKxigsIwVrfV7fplLhg4spHfauXO+Kz8MKCB7t\/qnuyllJUi4kRVk0SAmqD1DX5ULJ1rLikXVpFL55LJzk\/9uQigrgYayEjFQVlzLCqYHrp1rq5KCKQLcYaOOYdPq2nonTlmJL7iWlXvXOuqgNfCb\/FK7WmqZPLaUSgq6mh7Z00QzL1wNFI9wIStW47+Th5rrdJ9uYmm8lq0NLC8cb2V7ni9BWQk0lJWIgbLiXFbwpjZ3enntxTCwf37tudHjy5xSqviH0r71p7p\/DGUlvuC+wBbX8trZdjJtQhldAdSg7icqK1je6q9GYZSVIOFCVg7sfLAHFF7TQ74vqLtrt2mRSWpWSSVDvitAWYlXUFYiBsqKc1nBnTTeyLJmfksKfPae1K\/9iU4NoCAPK4Mm\/Mx2+\/EH97JiRYwRmOqDkLZunkkzav66zpSVIOFCVjatqS3Zs7xtvK7flppVU0vzxumlbKmkUqjA+9K5fRY5vId7A8UfKCsRA2XF3TRQJ20WVcO462rfKrPx37Wlc7ss2oLdXwMYgrISaDyXFSsgq1HX\/dcgDEFZCRIup4GwRL2tdGibWWpVT61baKB+xd8r\/BCUlUBDWYkYKCvuC2zRghtLl6eMK6XNwooXSaKrReyO9TUoK4HGe1kJRFBWgoSbAtsoQ0Sx\/xNqVLBhZaH8iQ1ZYbv9+AdlJWKgrLiXFQTusFGMt2huJfl5eFE5faSF7XG+BmUl0PgmK7gLR4aF00DxDDeyYsWdyx20Y+3wwYVlx8Z6flnx5RiUlUBDWYkYKCueyYoVGLSssPu6rxEpsnLv3j25ePGibNu2TS5fvizR0eaVCji+ycrl0210R15k1fZsaRDnaYJIkpX79+\/L4cOHNXCtg4qHsoJQIb1pCKnN1+IakSIr1rU+cuSI3L1rCETQoKwEm\/Pnz+u1PnXqVBDfvw0oK97JSqAiUmTlwoUL8uOPP0ratGll5MiRcu7cuSD9wXsvKxjE0Lm2Yb200r1LDhk6sKDuIWN3rKcRSbICQWnQoIGUKlVKpk6dKleuXDG\/EgS8kJVARiTISkxMjA5cNWvWlAoVKsj69etVXvD5wENZCSa4rmPHjpWiRYvKl19+qdcdN6BBgbLif1nBMldvpw4iRVY2bdokqVKlkr\/\/\/e\/y1FNPSf\/+\/eXGjWC8C3snK7iG96911GWsp440174cmCKIfU1xnBWOn3cWkSQrJ0+elDfffFP+8Y9\/yPvvvy\/Dhg0L0gBmQFkJGlFRUTJp0iRJnDixXus0adLonXdwBjHKSjDBzWblypX1\/fuZZ56R2rVry\/Hjx82vBhjKiveycv1cOxk7oriULfWRfP1VLu1+ic9DUNBoqlK55JIzW0LdtXfahNJyzxjodm2qL\/1759VC3diPh4gUWcHd9ogRI+TZZ5\/VN7bXXntNDf369esBHsg8k5XLp9pIxzaZtbfOgD6fSZ6c70jp4h\/KmmU1tHmYdRyu6ZrfamgfFixtx6qS3Zvryz1DaHDNfx5WVO7a7CUUSbJy9epVadmypbz88svy5JNPSrJkyVRYcK0Djpeygtfu2aMtpUKZZNqWYOXiarbHeRuRklk5c+aMlClTRp544gn517\/+JR9\/\/LH8\/vvvcufOHfOoQEFZCSYQUIipdcP53HPPSdOmTWXPnj3mEQGEsuK9rNy+3EFbc2NaYNa0cnLNkBd8HhIzd0Z5qVA2mUwbX1p6fplT6tf5RDasqqWDXaumGbXrbezHQ0SKrGDKB3bep08feeONN+Sf\/\/yn3n337t07wDUsnskKCqezZX5bFs6uKE0bpJM2LTLqktafBhfW+hXruBvn20nThum1mdiMSWWka+dsUqViCu10\/J0hOj275dKut46PjYjEmpUmTZqolEJYcPc9evRonf4LKF7KCjJjENUB\/fLJzCllZcvaOrbHeRuRUrOC1y2mfwoUKKDCgoEsa9assmLFCrl9+7Z5VCCgrAQbvHYnTpwoKVOm1Ov8yiuvqLDs3bvXPCJAUFbcywrS\/8ieLF9YVZuFzTYEZdLYknJod+M\/pf8vGW92Y0YU0ztzZFj+2N9Ufvg2v7RqllHmTC8vzYzBLdJlBeCNDVM\/PXv2lIQJE2qG5cUXX5Rvv\/1W79CQVvY\/HsrK4RaaKYGcNK6XVqZPKC1jjWsaW1awMqxksQ9VVPB51LZAVob\/UEi+6JhVOx1HuqwA3HXv3r1bhQVvanhzQ4bFqlcKGB7ICl7XW36vI9vW19VGcbjGuKnQjsWxjj1svNYXz60sS+dX0dc1pgWRRcOO3I5\/F7EjUmQF4HULYSlcuLDehOBa58+fX1atWhXADAtlJRSgyBY3HUmSJNGbENyMNGzYUA4ePBig928Dyop7Wblypo2MG1lc77ixX0zO7O9I1k\/fks87ZP2TrGBwQv+V\/J+9pxkWvIlt31BX2\/O3bJpR08sHd1JWLG7evCndunWTV199Vf72t7\/pH\/2gQYMCVHTrmaxg08qyJT+SFMleljbNM8n0iaUFu\/KuWlL9T9NANy6012xKs0bpZdnCKrpKCCJbrEgSKVooiRbkUlYeAGHBmxiE5b\/\/\/a9e648++kjf7K5du2Ye5WfcyAqmfSCYRQsnkS+M13HlCin0NZ0ja0LjNVvvT8dCajq1yyLJjb+JT9K8Ki2bZJBTxs0IMjGQ0\/UraxnvA39+fCsiSVYAXre7du2SDBky6HQQhCVz5syyYcOGABXdUlZCBaZzx4wZIx9++KH83\/\/9n95wNm7cWGvVcK39DmXFvazs395QGtb9RBbPryyN6qfVeoTpxh01pnuirv+vLwPesDBArfmtunT7IrumkvH14weaSttWaN2eUY7uafKnx7YiEmUFb1yoaxg4cKC+sf31r3+Vp59+Wvr27RuAolvPZAXSMXNSWTmwo6EhJO10ugebV943rqPjgIT\/RgMx1KcM\/q6AnDveUq81\/laqV0klfXrm0elCx8fW8yJQVgDutrCsFeni\/\/znPyosuCsLWNGtG1mBeKLeDLVniCIF35fTR1tI6lQJNINiHYfrfHRvU+naKZs2kNu9pYEUKvCeTB5XSk4eaqaysm6l827WkSYrAAPV6dOnVVKQYUEEruiWshIq8LrFMvVx48ZJ0qRJH75\/o+j22LFj5lF+hLLiXlYO726iy1c7tc8imTO9KZPHltQmUhXLJdM7NMdjkWmBsFw40ephTw7cmaGW4fzxVrZ324hIlBWAOzFM\/UBYnn\/+eZ0Sev3116Vr165+Lrr1TFbQ1RQdirGzNq4fBqHY19gxrp5pq1NCKLjFx\/gXU4CYHrA7L1JlBWAq4OjRo3r3ZRXdJk+eXAuu\/Z5hcSMrdy53lJ+GFJYuHbNJjaqp9MZjz9YGkirFK7JiUdWHx+H6Y7l6e+NmY\/WS6tpEbt+2hoawJNbeO8MGFaSs2IDX9fbt23WJq1V0+8knn8iaNWv8PCVEWQk1ly5dklGjRmkNC25C8D7erFkz\/xfdUlY8mAY63UaWLawq9et8LB3bZpZVS6pp5mThnEpO36S8jUiVFYA3NjSKQ9Etim1xJ4biWxTd4oXgnykhz2TlzNGWUrrEh5Ize0Jp0SSDfPVFDunbK4\/WNdhlSryNSJYVgLtuTAlBWKyi2\/fee8\/\/RbduZAVZMEwD9eiaU29EkCH7vl8+6dMjt8qm47F3r3SQXt1ySfXKqWT8qAebl476saiu9qtpiM56yootyKatW7dOi24xTYCBLHv27LJy5Uo\/CgtlJRywim5x84EbzgQJEui0r1+Lbikr7mUFq31+mVJWfp1VQS6dbK0ZkpMHmz+8m3YW14w7bhx\/50pHLb5FQZ7dcYhIlhWADApqWFB0+8477+gfPAzdf0W3nskKrlO3z3OosGBqAEW0mNbBZnc3newbgwwKlikjywLZQUbGWTYm0mUF4FqjrgFvZsiwYBDDm5xfi27dyYpxfTBNO2tqWTm6r6m+xndsqKfTQ3bigVb82IF95NCi+jGypcis9O6eWwvtYx9vRSTLCsDrFvUqhQoVelh0my9fPhUW\/3S6payEC1jl+fPPP\/+p6LZRo0Zy6NAh\/9SwUFbcy8ox482sS6ds0qFNZtm\/vZGm+NEsDOl\/u+OtwOoh7COElQTjfy6hqwzsjkNEuqxYQFi6d++uK0cwiCGFjKJbVJ\/HbUrIM1nBHTdWe\/TtlVvrlEYOLaIrvFBk7UxAIK0Y6DB9gOXsqFmy67GCoKw8ANfSyrBYNSxW0a1f+rC4kRVcn2kTS0u7Vp9qLQrqklBcjRsRZ9fOl4h0WQHIjGJKAF2rraLbTz\/9VDZv3uyHolvKSjiB92+8hlF0Czl94YUX\/Fd0S1lxLyvHDzaXNi0+lWeffVISJnxWVwVkyvimThO4qmdAyhirCLauqyNfdcmhb4Z2xyHCSVbw5oE3GPwb7MD3Rb8VCIpVdItOiV9\/\/bW+EHzHM1lBY7DP8iSS3j1ySesWGWXYD4X0OqP3Bvro2J2DOgaIKWqZ0HsFy5md1SaFm6xYv\/PY1yEYgTcvFF3izQyrhDCIffDBB7odQ5yn\/jyQFfRISp0ygbya4Cn56MOXJE3qVyVj+jdk0+ratuf4EuEkK\/idh+pao7AWrdmzZcumgximhVB0C2GNW9EtZcUO\/M5Dca3xPW\/duqWrhFB0i5sQFN3WrVtXC+zjBGXFvaygVmHz73V0BQCafQ0bVEgHJPRmcFWzMnZkcenQOrNsXVtbvvw8u5wz7t7sjkOEi6wgNbt\/\/34pX7685MqVKySRI0eOhx0S\/\/KXv6iwoIalR48e+saGF4X3eCYrKKbMlOENWbW0mgomahl+\/aWCDPm+oE4R2Z0DMVm2oIpMHF1CGqE3y8Qyf1rm7BjhJCtI0Y8fP147j9pdh2BElixZ9E0NAxiuNdLHuPZz5syJ24owN7KCm4yTxrXG1O733+TTmpRRw4rKPONau+qbAsk5tLORFuhi2s+ZlFoRLrKCa41ptrx589peh2BEzpw5dWoAAxiuNW5G0qVLJ1u3bo2DnFJWYrNjxw5p0aKF7TUIVkBEMY2P64zrjQxL+\/bt4yYslBX3soJahQPGG1TLphmkWOEk2nMFyx7Rbt3ueCvio6zAiqdPn67t8CEJ+GMLh0ANC95oMYAFUlYwDYC+OL265dTtFHDdalZLpTVLWMZsd058lRWIX\/369R++qYRL4I0Nd2Jx2qnZjaxg1R5qyrAiCLVJaEnwXb98Mtz4+PSRFrbnILBdRuECiXWqEJ2NXdWrIMJFVnCty5UrF1avaTwXvK6nTZsWh5o0ykpsIPpovGj3Ow9lZMyYUZsG+gxlxb2snDrcQmtW6tX+WN\/Y8AaHu7E6NdO4nAaaMq60DnY7NtTVVQZYzmx3HCJcZAVV+ih+xBsb7oRCEcispE6d+uHdNt7UcEeGPYTw\/AIpKyiOnTWlnDbww6CEZcxNGqTVjItjTx3HwDQQ9pJBtg01EOhw7GzlULhlVjC\/XKJECdvrEIxAZiVFihRam4RrjekBTAVhZUGcalfcyMq9q51kwayK+prGvk4F8r0nKxZXlYzpX9caFrtzEHu2NJBnnnlC9\/qC3Gxe47otf7jICqbckFnJkyeP7XUIRuB1jbYEVsYUWTTcgWNzU8rK\/yKusrJt2zadWrW7BsEK7A2FJnG4zsisYA8hZHsw7eczlBX3srJve0Pd42fJ\/CpSp0ZqHYxmTS0n5Yw7bzQLszsHsWFVbZkzrbwuhVwwq8LDPYTsItxqVkIFvjcGKbyxolYFf+j4t0uXLnLlyhXzKF9wLysQT2RJsKT15oV2WkCNouhLp1prt1JnYoqVIehMjGnBqeNLy\/b1dZ2uFAvHmpVQgQEKhXdYoo43Mwxib7\/9tq4IC3TNyq2LHaRH1xwyenhR7ZmEbBp6IaGGZfG8\/zWFix3xVVZwnUN5rSFLZ8+e1VVBmP6BlEJSN27cGMe9gygrsQnltcb3xQ3lrFmztK8O3r9Rj4ayggMHDphH+Qhlxb2sYPkx9g3JmzuR5Mrxju71U6dGGu214thuP3ZgEMMeIhjkMHi5OjacZCWUoGamX79+D1vwYwBD\/xW80cVtAHMvK8iezJxcVj7N+KZ2NV06v7IubUWvlanjSjmVTdQt4RrjeiPLggyMs1qmcJOVUAJRgYQ+9dRTeq3RYweF1cFYDRR1vbMc2N5AypZKKgXzJ5YM6V7XGiVkTiEiducg4qushBK8bnFHjY621sov3HljzyDfa9AsKCvhBMoIfvnlF21FgMw4ygmqVq0qJ06c4GqgWBEQWYFoYLnyhJ9LSOvmmYzBK7sWXmLe2u54XyLSZcUycrTaT5Qokc5lI6OCu26sIojzH7oHsrJ7c33tm5H4vefl8\/ZZ5MeBBbWVPvproI2+u746ngRl5QEotOvYsaNOC2DwQkYFXYzRpt0vuK1ZefC6Xv1bdd0bqHH9dDq9i0J6Z6u+EHu3NpCXXvq3\/q0M7J\/f7e7MkS4rEJUtW7boVCOmfXDzgWmCRYsW6cAWdygr4QIaeE6ZMkXrZZA9e+mll6RGjRq6YCPu798GlBXXsoJsyMWTrXXX5J2b6ukUATYx2\/x7bb3bdnYHjYwK3vTQJAxvcMsXVdWdm51NJUSyrEBUMMWDBnAYtGDkqFHBJofor+KXP3Q3soKB67whpFi2il2z0SsFAxLupA\/taqTTQs6uHQpvkX3DXkE4D38n+Nju2EiXFUz94C4LooJrjekAXGtkVPwmKsCFrOA1i1U9mLbbaFxvZNSO7Gmi00DIlmAvILvzEHgvwBJ1\/ItiW9zE2B1nRSTLCkQF0zxouW+1IciUKZOKiv\/2\/qKshANoCIeMCmqQcKOJehXsEYT6R79BWXEtK3gjG\/ZDYV0ZgjswNHdDVqV7l5zaf8OZrOAODUshMZVQrXJKKVH0A5lunOdsKiFSZQWigq6l6K2BRnD4Q8cUEAYzrAaJc+3CQ1zLCnZRnjejvC5LH25cb\/RXGfZDQQ00htu9uYFO88Q+D4Wa6LEy5PsCssUQWLRgr1whuSyaU0mnGmIfH8mygpQ\/pn46d+6sGRWIClrtI5sWp5U\/driQFcgliqEbN0injR4njH7wmh43Cjurv6WvXbvzfIlIlRW8bnfu3KnL4v\/9738\/XJK+ePFiP29SSlkJNbjRREE8lqEjS4qpnzp16ujeUH6FsuJaVrAyoHH9tLobK+a2q1ZKqRuf4U1u7bKatucgaldLLd98nVeXOX+W+11ZMLuiNK6XVrMsdsdHoqxAVLCBHUQFRVi488K\/WPUTt2JaO1zLCnpmbFhVS+bOLC+\/TC0rMyaXkemTSmvMmV7OuNtuYjsNhKXO2C\/qc0Nk8e+Phuzgv7F6zNrI0jEiVVasjAq6E6NJFN7U3nrrLenVq1ccaxac4EJW0JG6iSEquXO8I7myJ5RqlVJIjSqptA5tws8PsiZ251mBGxRk2VCbhLb9dsdYEYmygkwotshAqwFICjKlKKZFx1pM9foXykqowOsWNYbIqGD1pvX+jZWkaLHvdygrzmUFU0A3LjyYysFAdnBXY+1wik60eEPD12KfY50HoUG9A5Y4Q1ogPQ3rptWpBbtzIlFW8MaFmhSrbgFZFdxl443OfxkVC9eysn9HI71OY0cW0yxaxgxvyicfv6aRM\/s7WmhrV8vwx\/5m0rNbTs2+ZDXuylcsribf9vlMvuiY1bYvS6TKCkQFGRVHUfnhhx\/k6tUAvSu7kBVMAWF37b3bGsgu4\/VovabxOUirXQYNgdf1\/Wsddbrv9JHmOrWL\/kt2x1oRabKC1y1qFLJmzfqwmBarQpYvX+6HYlo7KCuhAh3FZ86cqTUqyJIio1KtWjX\/FNPaQVlxLiu4c0Ln0rq1PpZa1VJL7eqptbdKXSPQ\/GvQt\/mdTgNhOSRWFmBaAA3DypdOpvPhqFuxOz6SZMUycqzysYppsXQVLfX9U0xrh2tZwd02pgZQMImVXxPHlJRpE8toYJk6Mit2gxgaBvbvnVdy53xH8uR6V2Ybx1Yun1x+HlbU9vhIlBW01Ef3SqvHBkTFr8W0driQFUzz1K35oL9K7Rr\/e00jkEVF\/YrteWtq6zG\/L68h1cwMa\/euOeX4wWa2xyMiSVYgKsieoJgWfXMgKlYxbdy2ynAFZSUUoJh28uTJjxTT7tu3Lw49c9xAWXEtK7\/Oqqipfdw59+mZ52EgY4Kups6WI2PwQz8W1C7gzm308GL6OdQ42B0fKbKCNzT8oaOYFoOWVUzbtWtXLdIKjKgA17KCAerLztm1rqhWtVQy\/5cKutMyYv3KWnrn7eza7d3WUKaNL21IaVXtsbJ4bmU5vNt+wIskWcG1xF1Whw4dHhbTYtsEvxfT2uFMVm5\/rhnS\/r0\/09ckXsfWa7qvEciKYeXXI+cZgSndnNkS6ipAtDHA6sC+vfLIormVnN60RIqs4HWNYtoiRYpojQpEBR1LFy5c6J+l6E6hrAQbvE\/PmDFDl5\/j5gMdp1GjghqlgEJZcSUrnbWlNt6URhv\/tmmRSdoiWmaSTm2z6N2zszcpbyNSZAW1KNjkCtXiyKgkSJDgYTFtQGoXHuI+s4Jly6hLeuXl\/0jRQkmkeuWURqSSBnU+kRWLqrndB8aTiCRZwSAFCYWMWsW0mPYL2NSPIy4yK9s21NVpumULq2oPHbyercDGo8cP2GdKJo0pKdmzJtQMHM5fPK+y9mZZYvwbybKC1y36IFWqVEnvshEopl2yZImfi2ntoKwEE0zlQVSsYlq0l6hVq5b\/i2ntoKw4lxUU0e3eUl+O7muib2AnDzXXpYrnj7fU1vnXzrV95BxfI1JkBWliLG9DRgXNwL766qsAFNPa4VpWrDhrXN9iRT6Q\/TsaGgMQMinInLkuovQmIklWsPLHWoqOhm+Y5guskDrgQlaQJcMSdWQ8sfwYr+cH0Upf18766axbUVM+zfCmcSf5LxWdZo3SS6XyyeXWpUcLqa2IBFlB2h\/7iSVJkkSlNHDFtHZQVoIJsuJo8oYbTdSflS1bVo4ePWp+NcBQVpzLCgrxmjRMJ80ap5faNdPIDwPyy9Jfq8iqJdVkzbIahsjYr+zxJSJFVlA8279\/f8mdO7cMGzYsQMW0dngmK5j6Q0E1+uTYfT2uEUmygmwZNiQsXry4jB071v\/Lk13hYhpo7swKukQZWRTsov7bggevaX1d\/1ZDrjjZdRmZNdywoKgWez+dOtJCBcfZVDAiUjIrqDXDfjTVq1eXFStWBKiY1g7KSjDB1C62QilVqpQWzOOGBNc6KFBWXGdWkOLF9E\/JYh\/ockfMaaOj6dCBhWS+8abHaSDvQGEtGr3t2bNHMyoBK8Z6BM9kJdARaTUr6FSLPUEuXjTeaIKJi8wKak66dsqmWZHmTTLIgL4PXtNYvYc+O84a+vkSkVKzgmt9\/PhxDf90pvUUykowgYDi\/RtF8xCV4NxomlBWnMsKAtkVvLmhwBbdSU8ebK533pgOunKa00DxB\/eyAvF80D+js\/6LjQwxLYA7an9JaSTJSkhxISvIniF7gsJY7LyMbAle04izx1rKncv+y6pFiqyEDspKxEBZcS0rjuEq3RvXoKwEGteyEm1cWwxUc6eX160V1q+sqYKK1SLobordlyEwdud6E5SVIOFCVoIZlJVAQ1mJGCgrnstKIIOyEmhcywp2S0bfnLfefEaSffSyvPjiv6R4kSTSq1suyZThDfl1VgXbjrTeBmUlSFBWIgTKSsRAWfFOVpBdwWoBu31f4hKUlUDjWlaO7W8q3\/TKowXU+O8C+d6TqRNK69TAwtmVtDmgP2oZKCtBwo2s4HUcfaOT\/ouutDcvtlNh9Xf2lLISaCgrEQNlxbms4I0LuyyjKRiWLSLQ5K19q091qmD\/dtettr0JykqgcS0rEBG020dn4q+755Ik778g3b7IrtcbBdboaHvtbNxrlCgrQcKFrGC5MnrqYLPKyWNLaeF8lQrJdcPRSWNLyoXjrWzP8yUoK4GGshIxUFZcywre0NBWGy33u3fJIS2bZNCGYWi9P2VcKRGuBoonuJYVtMbH\/k9Vsamdcb2\/7JxNN7ZDQ7h6xrU\/uLOxFlvbnetNUFaChAtZWbWkuiT94EXtMF2jamqVlImjS8iQ7wrotglb19W1Pc+XoKwEGspKxEBZcSUrxhNbW0e7XLZv\/aksX1hVNyRs0SS9LJlXyelGhr4EZSXQuJYVBGpSDu1urNf8zJEWukM2smpoCIgCW6wisTvPm6CsBAkXsrJwTiVJnuxlzbBgF3UsV759qb02iUuV4hXdLsHuPF+CshJoKCsRA2XFfc0KBrFFcyoab3Cv6AqRVs0y6JSQ3bG+BmUl0LiWFYgpWuqnTP6K\/Ptf\/5QGtT+RAzsa6S68C41rP\/7n4iosdud6E5SVIOFCVjauqiXvJ35Oxo4opjuh16iSSjatriUzJpaWtGlelQ2GoNqd50tQVgINZSVioKy4lxUsWcXuumi9jwxLlYopZOPq2rbH+hqUlUDjWlbQgh1NwdAgbNOa2tK6eSbd92W\/ISwLjDtxyko8w4Ws3DJey9vW19WMSpFCSSR92td1ahdTfxAZf6z6soKyEmjCSVY2UFYCyWMmK38zwq+yguZR29bV1Xnsw7sbS7NG6aR8mY\/kx4GF5NIp+7bcvgRlJdC4lhWs+hnQ5zPtSozdlXduqq\/FttiJd\/a08jJ+FGUlXuFCVtDsb+u6OnLiUHPdNqNH15zazbZj28xy+kgLv\/TTsYKyEmggKwuM3zXev0MXeF1f37DauNbRttfPm7i24a5E3TRHMPI\/VFYmG7\/vLo\/8\/oMZe698JyUP7lDZiEs8tf2O9DxzT+6Z799xlpVff6kgrZpmkIWzK0r71pmlYtlk0rDuJ1K1YgotsPXXUkfKSqBxLSvXz7XTXXXr1kyj1xUDGrZaKF8mmbRqllHGjChGWYlPuJCV7RvqSbVKKfUaTx1fWioYr2lcd2RMIadnjrawPc+XoKwEmijjf\/uM6z0npBFzZ57cPbVXrq2LkqtrjPdhX2NdtNw9d0Ni7lFWHiHmpvGGt8X29x\/MuHh7qcy5dECqHIuS8j5GBSMan7gj62\/efvj2HSdZgYi0aJJBenfPpfULmdK\/oUuZ0Y9h6vhSUqJYEuMNJO5FlwjKSqBxX2CLFT9dO2eT+rU\/1rtubFY335DVMiWTytwZ5eXG+bgXVFNWgoQLWVm2oKq8n\/gFnfrDtf2uXz5dDYasSqqUr8jKxdVsz\/MlKCvEW4K1MTkJLyw\/QfgkK+1aZdI0MWQlZ\/aEcmRPE5UVtGAvVfwDQwyYWYkfuJcVa28gRMzDzz342F9TA5SVIOFGVhK\/97ycONxcl6ojo4bPY8o3RbKXuRqIEBJ04iQrCMxto9dGtixvS8K3npHUKRNIjmwJpVjhJDJralkd4OzO8zYoK4HGtaygh8rpww+WK8eOA9sb6kDmDzGlrAQJF7Kyx7immPopXuQDlZYWjTPI7i0N9DVdq1pqrU2zO8+XoKwQQjwhzrJy40J72WO8kY0fVUIG9c+vXU4Hf1dQU8UXT\/hvK3nKSqBxLSt3DFkZMbSIFCn4vk79obcO9gVC9OuVR6UVUwV253oTlJUg4UJWMJ0HOUFN0vSJZYzXcnWdAsKWCiimR\/2S3Xm+BGWFEOIJcZaVYAVlJdC4lpX71zvpkuXSJT6U4YMLa2M4SCoCy5dRjMnMSjzChaxgFd+8mRVUQlFQCxFFZg3Tu0OMG5GTB5vbnudLUFYIIZ5AWSEm7mtWLhuD2K+zKmrb\/duXOtgeE9egrAQJF7KC64vpH2yZUbxoEm1FAGFBA8BUKRNoc0C783wJygohxBMoK8TEkwJb\/xbT2gVlJUi4kBUIKQppsUQZ2ZSe3XJKmVJJ5fKZNpQVQkhIoKwQE\/eyEoygrAQJF7Ky5rcakjjR89pP5\/zxVnJkT2Pp0OZT7Z+U8O1nDFmpanueL0FZIYR4AmWFmFBWIgoXsnL+j1by0+Ai0qVTNlm\/sqZmV7CVRutmGSVThje0dsnuPF+CshI\/iImJ0bAjOjpaoqKizI8e4Ox4fA7HO3ssEj5Y18oOfD72dcR\/W+GIs897C2WFmFBWIgoXsoJAQfXRvU20cBo9dbCjNgpvMUWElUF25\/gSlJXw5\/bt27J27Vo5ePCg3L171\/zsAzBg7dy5U6ZPn\/5wMLp\/\/74eu3r16oeDHb529uxZWbduncyZM0cWL14sZ86ceURySHiAa37gwAH5\/fff5d69e+ZnH4Briuu7aNEiuXr1ql5bXMejR4\/K5s2b5eLFi+aRov+Nz82dO1eWLl0qx48ff+RvyFMoK8SEshJRuJGVYAVlJfyBVBQsWFDGjRsnV65c+dNdMga1r776Spo1a6aScvr0adm2bZs0aNBAz8HnwOXLl+WHH36Q9OnTS6pUqeTdd9+Vb7\/9Vj9Pwo9Tp07Jl19+KY0bN5Zr1649vOaIO3fuSJ8+faR3795y5MgRuXTpkuzatUtatGghVapU0esPobl165aMHj1acufOLSlSpNBo06aNnD9\/3vwu3kFZISaUlYiCskI8AIPT4cOH5dVXX5UVK1boHTQExLo7PnbsmDRq1EimTJki586dk48\/\/lhefvllef7556V27dp6DB5j+PDhkjdvXv0XwoPsSpkyZTT7QsKPPXv2SI0aNWTAgAFy8+ZNza4gcP2RTcmWLZvMnz9fMyw1a9aUF154QZ544glp0qSJnDx5UkXlt99+k5QpU8pPP\/2kgrJy5Up5++23Zf\/+\/fo34S2UFWJCWYkoKCvEAyAmGzZskNdee03\/XbhwodSvX18GDx6sg9d3330nHTt2lBMnTugdN+QD4pI\/f375+uuvdVC6fv26VKxYUcqWLSuzZs3SY3A8po9wV07CD4hG8eLFdfpmzZo1KqQDBw7UaZ1ff\/1VRRPXDyKDTAr+LhInTiyDBg3Sz0Fc8XdSqlQpGTNmjD7GH3\/8of\/i675AWSEmlJWIgrJCPAB3yLNnz9aBCPKBNP8XX3whO3bs0OkBSMiPP\/74cLoHIANTrlw5lRbciaNOIWPGjJI1a1adLqpbt660bt1aMzYkPIFgZMiQQUaOHCkVKlSQDh066FQPriWme4YOHSoXLlzQYyGtuJaY5pk5c6Zec0wPffjhh5I9e3bN0NSpU0eaN2+udS2sWfEwKCvOoKxEFJQV4gHIfHz\/\/feavn\/99de1FgWFlxhwcGcNWcHdsiOYOqhWrZps2rRJJQb\/pk2bVho2bKgiM23aNEmYMKFMnTr1YQEuCR8gH7169ZK33npL602QJYOc4lpiegjTefgbwHEAmRJMCUFGMdWDa7p9+3Z56qmnNLuCwtrx48dL5syZdUoI00i+QFkhJpSViIKyQjwAqXtMASCzguJY\/Dc+hwEHAxrusLHKxwIDVa1atVRMMGWAAQ2CUqBAAV09gmkhfD5RokQ6cDlmZEh4gKLnpk2b6tRfvnz5JFeuXCorqDWaPHmyVK5c+U\/Td\/jv\/v3769QQsi\/W1OHTTz+tHyPTgtoW\/F20bduWBbaeBmXFGZSViIKyQjwAy04xYC1fvlzvkEuWLCkTJkzQwlqk+a07aQARwV12kSJFpHPnzg+Lcbdu3aqyMm\/ePM3I4O4cmZpJkyb5VGhJAguyJpi2QYZs9+7d8t5772lBNGpT8PmJEyf+qe4EK8Dq1aunIgKRxd8Dsm4vvfSS\/v2glglL1vF3hLoXX1eAUVaICWUloqCsEDdg0IGgoN4EAwzuiDFYYZUPCioxRYA7ZgvICbIsEBPUsQA8Bu7IcTeO+oXq1avroIXHwbmUlfADBdDIgqDIFnVJqFOCfKKYGkW3sfvjQFxz5MihUz34O8E1xd8BHgNTSFWrVlWBrVSpkta8+JpNo6wQE8pKREFZIW7AoIMsCKZrMDhhSgcDGD5etmyZNoJzrD+AmODjUaNGyd69e83PPvg87qwxbdSuXTudMsDdu6+rQkhgwdJiFFVjCTKu+apVq7S+CFNAiNiCCUHBKiBIi1XHgv47mALq16+fXnNkaVC7hL8FX6GsEBPKSkRBWSFxAAOWXVbE7nMW1jnOziXhDa6ZL7Lhr+tNWSEmlJWIgrJCCIlHUFaICWUloqCsEELiEZQVYkJZiSjCRVZWb5Lzk+\/ZXj9v4vzMGMoKIY8xlBViQlmJKO5vFLnzsxE\/hTRuH94gl5fekYvzRC4a\/uRLXFoQLdc2XpPou2wwRsjjCmWFmFBWIoqYG8Zr+5wRp0MaMVGX5N7Fu3LnD8NdjvkWd09HSfSd6xITQ1kh5HGFskJMKCuEEELCE8oKMaGsEEIICU8oK8SEskIIISQ8oawQE8oKIYSQ8ISyQkwoK4QQQsITygoxoawQQggJTygrxISyQgghJDyhrBATygohhJDwhLJCTCgrxHfu3Lkjt27dkvv3jb+jWOBrBw8e1G3jsfsqtpG\/ceOGRlRUlHkUIYQ4h7JCTCgrxHd27Ngh48ePlytXrpif+R9nzpyRqlWryp49e+TcuXPy22+\/yciRI2XUqFGybt06uXz5snkkIYTYQ1khJpQV4jt9+vSRMmXKyNWr+IUbbxvR0ZpFQUBInnvuOdm9e7d8\/\/33kjhxYsmfP7989tlnkjRpUpk\/f76eQwghzqCsEBPKCvGdFi1aSM2aNXWKB8KycOFCnfpBJmXIkCHSq1cvuXjxotSqVUsqV64sp0+fllOnTkmmTJlk4MCB5qMQQog9lBViQlkhvoHsSYUKFaRNmzaydetWqVixovTv31+FZO3atVK0aFE5duyYikz79u01q\/LLL7\/ImDFjJEuWLDJjxgzzkQghxB7KCjGhrBDvgaggkwIBqVevnlSrVk1q166tcoKC2hEjRkjBggV1WgiZlG7dusnHH38sxYoVk2TJkknr1q213oUQQlxBWSEmlBXiPZCQjRs3StasWSVBggSSJk0auXDhgq7yOXnypHTu3Fn69eunUjNgwADJmzev9OjRQ7MpqHHBlBBqWQghxBWUFWJCWSHeg6XKffv2lQwZMkiDBg2kePHiuiro+vXrMm7cOKlTp87DottcuXJJp06d9L8hM5gmSpcuncyZM0c\/RwghzqCsEBPKCvGeu3fvSsmSJbUW5dChQzJs2DBJkiSJHD16VFq1aiXt2rXT7AsoVaqUVKpUSXbu3KnTRC1bttR6lk2bNunXCSHEGZQVYkJZId6Dhm+oPxk9erRmWVBQmyhRIlm8eLE0a9ZMZs+ebR4p2l+lUaNGUqVKFalRo4aULl1ap4MuXbpkHkEIIfZQVogJZYV4D6ZzFi1apJkUgOXJ06dPl3379snmzZt1qscCGRZkVaZOnapTRRCba9eumV8lhBDnUFaICWWFEEJIeEJZISaUFUIIIeEJZYWYUFYIIYSEJ5QVYkJZIYQQEp5QVogJZYUQQkh4QlkhJpQVQggh4QllhZhQVgghhIQnlBViQlkhhBASnlBWiAllhRBCSHhCWSEmlBVCCCHhCWWFmFBWCCGEhCeUFWJCWSGEEBKe2MoKg8FgMBgMRjgGZYXBYDAYDEZYB2WFwWAwGAxGWAdlhcFgMBgMRlgHZYXBYDAYDEZYB2WFwWAwGAxGGEda+X\/NC7TKDelJSgAAAABJRU5ErkJggg==)\n\"\"\"\n\"\"\"\n### 6 . Discriminator Code\n\"\"\"\nclass Discriminator(nn.Module):\n    def __init__(self, input_channels, hidden_channels=64):\n        super(Discriminator, self).__init__()\n        self.upfeature = FeatureMapBlock(input_channels, hidden_channels)\n        self.contract1 = ContractingBlock(hidden_channels, use_bn=False, kernel_size=4, activation='lrelu')\n        self.contract2 = ContractingBlock(hidden_channels * 2, kernel_size=4, activation='lrelu')\n        self.contract3 = ContractingBlock(hidden_channels * 4, kernel_size=4, activation='lrelu')\n        self.final = nn.Conv2d(hidden_channels * 8, 1, kernel_size=1)\n\n    def forward(self, x):\n        x0 = self.upfeature(x)\n        x1 = self.contract1(x0)\n        x2 = self.contract2(x1)\n        x3 = self.contract3(x2)\n        xn = self.final(x3)\n        return xn\n\"\"\"\n### 7. Discriminator Loss \n\"\"\"\n\"\"\"\nFirst, we will going to be implementing the discriminator loss ... Like a classique discriminator loss in a Simple GAN\n\"\"\"\ndef get_disc_loss(real_X, fake_X, disc_X, adv_criterion):\n \n    disc_fake_X_hat = disc_X(fake_X.detach()) # Detach generator in order the fix it's params while training the discriminator\n    disc_fake_X_loss = adv_criterion(disc_fake_X_hat, torch.zeros_like(disc_fake_X_hat))\n    disc_real_X_hat = disc_X(real_X)\n    disc_real_X_loss = adv_criterion(disc_real_X_hat, torch.ones_like(disc_real_X_hat))\n    disc_loss = (disc_fake_X_loss + disc_real_X_loss) \/ 2\n    return disc_loss\n\"\"\"\n### 8 . Generator Loss\n\"\"\"\n\"\"\"\n8.1  Adversarial Loss\n\"\"\"\n\"\"\"\nThe first component of the generator's loss I'm going to implement is its adversarial loss \n\"\"\"\ndef get_gen_adversarial_loss(real_X, disc_Y, gen_XY, adv_criterion):\n    fake_Y = gen_XY(real_X)\n    disc_fake_Y_hat = disc_Y(fake_Y)\n    adversarial_loss = adv_criterion(disc_fake_Y_hat, torch.ones_like(disc_fake_Y_hat))\n    return adversarial_loss, fake_Y\n\"\"\"\n8.2 Identity loss\n\"\"\"\n\"\"\"\nWe'll want to measure the change in an image when you pass the generator an example from the target domain instead of the input domain it's expecting. The output should be the same as the input since it is already of the target domain class. For example, if you put a Monet Photo through a PHOTO -> MONET generator, We'll expect the output to be the same Monet PHOTO because nothing needed to be transformed. It's already a MONET PHOTO! You don't want your generator to be transforming it into any other thing, so you want to encourage this behavior. In encouraging this identity mapping, this will help also to  properly preserve the colors of an image, even when the expected input (here, a MONET PHOTO) was put in. \n\"\"\"\ndef get_identity_loss(real_X, gen_YX, identity_criterion):\n    identity_X = gen_YX(real_X)\n    identity_loss = identity_criterion(identity_X, real_X)\n    return identity_loss, identity_X\n\"\"\"\n8.3 Cycle Consistency Loss\n\"\"\"\n\"\"\"\nThis is used to ensure that when you put an image through one generator, that if it is then transformed back into the input class using the opposite generator, the image is the same as the original input image.Since I've already generated a fake image for the adversarial part,I can now pass that fake image back to produce a full cycle\u2014this loss will encourage the cycle to preserve as much information as possible.\n\"\"\"\ndef get_cycle_consistency_loss(real_X, fake_Y, gen_YX, cycle_criterion):\n    cycle_X = gen_YX(fake_Y)\n    cycle_loss = cycle_criterion(cycle_X, real_X)\n    return cycle_loss, cycle_X\n\"\"\"\n8.4 Full Generator Loss\n\n\"\"\"\n\"\"\"\nFinally, I can put it all together!\n\"\"\"\ndef get_gen_loss(real_P, real_M, gen_PM, gen_MP, disc_P, disc_M, adv_criterion, identity_criterion, cycle_criterion, lambda_identity=0.1, lambda_cycle=10):\n    \n    adv_loss_MP, fake_P = get_gen_adversarial_loss(real_M, disc_P, gen_MP, adv_criterion)\n    adv_loss_PM, fake_M = get_gen_adversarial_loss(real_P, disc_M, gen_PM, adv_criterion)\n    gen_adversarial_loss = adv_loss_MP + adv_loss_PM\n\n    identity_loss_P, identity_P = get_identity_loss(real_P, gen_MP, identity_criterion)\n    identity_loss_M, identity_M = get_identity_loss(real_M, gen_PM, identity_criterion)\n    gen_identity_loss = identity_loss_M + identity_loss_P\n\n    cycle_loss_MP, cycle_P = get_cycle_consistency_loss(real_P, fake_M, gen_MP, cycle_criterion)\n    cycle_loss_PM, cycle_M = get_cycle_consistency_loss(real_M, fake_P, gen_PM, cycle_criterion)\n    gen_cycle_loss = cycle_loss_PM + cycle_loss_PM\n\n    gen_loss = lambda_identity * gen_identity_loss + lambda_cycle * gen_cycle_loss + gen_adversarial_loss\n\n    return gen_loss, fake_P, fake_M\n\"\"\"\n### 9. CycleGAN Training\n\"\"\"\n\"\"\"\nLastly, I can now train  the model and see some of my Monet PHOTO  and some that might not quite look like either! Note that this training will take a long time, so i will desactivate it because i have a very low computational ressources . And I can't wait kaggle TPU xD I'm a bit moody guys xD\n\n\"\"\"\n\"\"\"\nIn order to have a better train performance I'll introduce a learning rate scheduler the \"ReduceLROnPlateau\" scheduler. \n\"\"\"\nfrom skimage import color\nimport numpy as np\nfrom tqdm import tqdm\nplt.rcParams[\"figure.figsize\"] = (10, 10)\n\n\ndef train(save_model=False):\n    mean_generator_loss = 0\n    mean_discriminator_loss = 0\n    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n    cur_step = 0\n    \n    scheduler_discP = torch.optim.lr_scheduler.ReduceLROnPlateau(disc_P_opt,factor=0.1, patience=5, \n                                                       verbose=True)\n    scheduler_discM = torch.optim.lr_scheduler.ReduceLROnPlateau(disc_M_opt,factor=0.1, patience=5, \n                                                       verbose=True)\n    scheduler_gen = torch.optim.lr_scheduler.ReduceLROnPlateau(gen_opt,factor=0.1, patience=5, \n                                                       verbose=True)\n    \n    for epoch in range(n_epochs):\n        losses_P = []\n        losses_M = []\n        losses_gen = []\n        for real_P,real_M in tqdm(dataloader):\n            real_P = nn.functional.interpolate(real_P, size=target_shape)\n            real_M = nn.functional.interpolate(real_M, size=target_shape)\n            cur_batch_size = len(real_P)\n            real_P = real_P\n            real_M = real_M\n        \n\n            ### Update discriminator A ###\n            disc_P_opt.zero_grad() # Zero out the gradient before backpropagation\n            with torch.no_grad():\n                fake_P = gen_MP(real_M)\n            disc_P_loss = get_disc_loss(real_P, fake_P, disc_P, adv_criterion)\n            disc_P_loss.backward(retain_graph=True) # Update gradients\n            disc_P_opt.step() # Update optimizer\n            losses_P.append(disc_P_loss.item())\n\n            ### Update discriminator B ###\n            disc_M_opt.zero_grad() # Zero out the gradient before backpropagation\n            with torch.no_grad():\n                fake_M = gen_PM(real_P)\n            disc_M_loss = get_disc_loss(real_M, fake_M, disc_M, adv_criterion)\n            disc_M_loss.backward(retain_graph=True) # Update gradients\n            disc_M_opt.step() # Update optimizer\n            losses_M.append(disc_M_loss.item())\n\n            ### Update generator ###\n            gen_opt.zero_grad()\n            gen_loss, fake_P, fake_M = get_gen_loss(\n                real_P, real_M, gen_PM, gen_MP, disc_P, disc_M, adv_criterion, recon_criterion, recon_criterion\n            )\n            gen_loss.backward() # Update gradients\n            gen_opt.step() # Update optimizer\n            losses_gen.append(gen_loss.item())\n        mean_loss_disc_M = sum(losses_M)\/len(losses_M)\n        mean_loss_disc_P = sum(losses_P)\/len(losses_P)\n        mean_loss_gen = sum(losses_gen)\/len(losses_gen)\n        scheduler_discP.step(mean_loss_disc_P)\n        scheduler_discM.step(mean_loss_disc_M) \n        scheduler_gen.step(mean_loss_gen) \n\"\"\"\n### 10. Main\n\"\"\"\n\"\"\"\n10.1. Loading Data\n\"\"\"\nimport os\nBASE_PATH = \"..\/input\/gan-getting-started\/\"\ndef prepare_Paths (BASE_PATH) :  # a function to prepare the path names of MONET\/Real photos\n    MONET_PATH = os.path.join(BASE_PATH, \"monet_jpg\")\n    PHOTO_PATH = os.path.join(BASE_PATH, \"photo_jpg\")\n    return MONET_PATH,PHOTO_PATH\nMONET_PATH,PHOTO_PATH  = prepare_Paths (BASE_PATH)\ndef Prepare_list_names(MONET_PATH,PHOTO_PATH) :  # A function to prepare two lists of MONET PHOTO names\n    MONET_FILENAMES = sorted(glob.glob(os.path.join(str(MONET_PATH) + '\/*.jpg')))\n    PHOTO_FILENAMES = sorted(glob.glob(os.path.join(str(PHOTO_PATH) + '\/*.jpg')))\n    return MONET_FILENAMES,PHOTO_FILENAMES\nMONET_FILENAMES,PHOTO_FILENAMES = Prepare_list_names(MONET_PATH,PHOTO_PATH)\n# The set of transformations to do in order to make some data augmentation to help the model avoiding the overfitting \ntarget_shape = 256\nload_shape = 286\ntransform = transforms.Compose([\n    transforms.Resize(load_shape),\n    transforms.RandomCrop(target_shape),\n    transforms.RandomHorizontalFlip(),\n    transforms.ToTensor(),\n])\n\nimport torchvision\ndataset = ImageDataset(MONET_FILENAMES,PHOTO_FILENAMES, transform=transform)\n\"\"\"\n10.2. Visuals\n\"\"\"\nimport cv2\ndef print_folder_statistics(path): # a function to make some stats on the folder of images \n    d_image_sizes = {} \n    for image_name in os.listdir(path):\n        image = cv2.imread(os.path.join(path, image_name))\n        d_image_sizes[image.shape] = d_image_sizes.get(image.shape, 0) + 1 \n    for size, count in d_image_sizes.items(): \n        print(f\"shape: {size}\\tcount: {count}\")\n\n\nprint(f\"Monet images:\")\nprint_folder_statistics(MONET_PATH)\nprint(\"-\" * 10)\nprint(f\"Photo images:\")\nprint_folder_statistics(PHOTO_PATH)\nprint(\"-\" * 10)\nimport math\ndef batch_visualization(path, n_images, is_random=True, figsize=(16, 16)):\n  # a function to visualize the batch of images ... Is_random param to choose weather to plot a random image or not\n    plt.figure(figsize=figsize) \n    \n    w = int(n_images ** .5) \n    h = math.ceil(n_images \/ w)\n    \n    all_names = os.listdir(path) \n    \n    image_names = all_names[:n_images] \n    if is_random:\n        image_names = random.sample(all_names, n_images)\n    \n    for ind, image_name in enumerate(image_names):\n        img = cv2.imread(os.path.join(path, image_name)) \n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  \n        plt.subplot(h, w, ind + 1)\n        plt.imshow(img)\n        plt.axis(\"off\")\n    \n    plt.show()\nbatch_visualization(MONET_PATH, 1, is_random=True, figsize=(5, 5))\n\ndef color_hist_visualization(image_path, figsize=(16, 4)):\n  # a function to plot an image with the histogram of it's RGB colors \n    plt.figure(figsize=figsize)\n    img = cv2.imread(image_path) \n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    plt.subplot(1, 4, 1)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n    colors = [\"red\", \"green\", \"blue\"]\n    for i in range(len(colors)):\n        plt.subplot(1, 4, i + 2) \n        plt.hist(\n            img[:, :, i].reshape(-1),  \n            bins=25,\n            alpha=0.5,\n            color=colors[i],\n            density=True\n        )\n        plt.xlim(0, 255)\n        plt.xticks([]) \n        plt.yticks([])\n    plt.show()\nimg_path = '..\/input\/gan-getting-started\/monet_jpg\/000c1e3bff.jpg'\ncolor_hist_visualization(img_path)\n\nimg_path = '..\/input\/gan-getting-started\/monet_jpg\/05144e306f.jpg'\ncolor_hist_visualization(img_path)\n\nimg_path = '..\/input\/gan-getting-started\/monet_jpg\/16dabe418c.jpg'\ncolor_hist_visualization(img_path)\n\"\"\"\n10.3.Prepare Model\n\"\"\"\n\"\"\"\n10.3.1 Hyperparams Tunning\n\"\"\"\nimport torch.nn.functional as F\n\nadv_criterion = nn.MSELoss()  \nrecon_criterion = nn.L1Loss() \n\nn_epochs = 1\ndim_PHOTO = 3\ndim_MONET = 3\ndisplay_step = 200\nbatch_size = 1\nlr = 0.0002\n# device = 'cuda'\n\"\"\"\n10.3.2 Creating the Generator and Discriminator and initialization\n\"\"\"\ngen_PM = Generator(dim_PHOTO, dim_MONET)\ngen_MP = Generator(dim_MONET, dim_PHOTO)\ngen_opt = torch.optim.Adam(list(gen_PM.parameters()) + list(gen_MP.parameters()), lr=lr, betas=(0.5, 0.999))\ndisc_P = Discriminator(dim_PHOTO)\ndisc_P_opt = torch.optim.Adam(disc_P.parameters(), lr=lr, betas=(0.5, 0.999))\ndisc_M = Discriminator(dim_MONET)\ndisc_M_opt = torch.optim.Adam(disc_M.parameters(), lr=lr, betas=(0.5, 0.999))\n\ndef weights_init(m): # a function to initialise the weights of our model\n    if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n        torch.nn.init.normal_(m.weight, 0.0, 0.02)\n    if isinstance(m, nn.BatchNorm2d):\n        torch.nn.init.normal_(m.weight, 0.0, 0.02)\n        torch.nn.init.constant_(m.bias, 0)\ngen_PM = gen_PM.apply(weights_init)\ngen_MP = gen_MP.apply(weights_init)\ndisc_P = disc_P.apply(weights_init)\ndisc_M = disc_M.apply(weights_init)\n\"\"\"\n10.3.3 Train \n\"\"\"\n# train()\n\"\"\"\n### 11. Tricks And improvements\n\"\"\"\n\"\"\"\nFeel free now to use this kernel and try some of this tips in order to imporve your model score ... \nBest of luck ... \n\nTransformer with residual blocks \n\nResidual connections between Generator and Discriminator \n\nNot using InstanceNorm at the first layer of both generator and discriminator \n\nBetter InstanceNorm layer initialization \n\nTraining a lot longer \n\nBetter Conv layer initialization \n\nResidual connection with Concatenate instead of Add \n\nData augmentations (flips, rotations, and crops) \n\nDiscriminator with label smoothing \n\nUsing external data  \n\nTrain on crops \n\nDecoder with resize-convolution \n\nDifferent number of  transformer blocks \n\nPatch discriminator \n\nLager batch size \n\"\"\"\n\"\"\"\nI'll stop here with this block of tips. Many techniques can be combined to obtain a high quality solution. Don't forget to put an UPvote for SBH to continue updating this notebook with other useful tips\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9c1f4b21f6d8c8'}"}
{"id":"11260","text":"\"\"\"\n# Highlights  \n\n* Different preprocessing methods and their effect on performance and training time.\n* Feature selection methods with anonymous features.\n* Effect of reduced feature sets on model performance.\n* Framework for model evaluation - creating k-folds, pipelines, generating out-of-fold predictions for each model (if needed for stacking).  \n\nReferences:\n1. scikit-learn documentation\n2. [Kaggle's 30 days of ML](https:\/\/www.youtube.com\/playlist?list=PL98nY_tJQXZnP-k3qCDd1hljVSciDV9_N) youtube playlist by [Abhishek Thakur](https:\/\/www.kaggle.com\/abhishek). A must-watch for every beginner. The 'custom_cross_val_predict' function borrows heavily from the content discussed in the playlist.\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nSEED = 2311\n\nimport time\nimport gc\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.ensemble import ExtraTreesClassifier #estimator for feature importances\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.feature_selection import VarianceThreshold\n\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import Normalizer\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\ndata_dir = '..\/input\/tabular-playground-series-nov-2021\/'\n\"\"\"\n**Function for reducing memory usage:** *compress*\n\"\"\"\ndef compress(df):\n    numeric = ['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    \n    start_mem = df.memory_usage().sum() \/ (2 ** 20) #memory in MB\n    \n    for col in df.columns: \n        col_type = df[col].dtypes\n        \n        if col_type in numeric:\n            c_min, c_max = df[col].min(), df[col].max()\n            \n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)\n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    \n    end_mem = df.memory_usage().sum() \/ (2 ** 20)\n    percent_reduction = 100 * (start_mem - end_mem) \/ start_mem\n    \n    print(f'Memory usage decreased from {start_mem:5.2f} Mb to {end_mem:5.2f} Mb ({percent_reduction:.2f}% reduction)')\n    \n    return df\n%%time\ntrain = compress(pd.read_csv(data_dir + 'train.csv'))\n%%time\ntest = compress(pd.read_csv(data_dir + 'test.csv'))\ntrain.head()\ntrain.shape, test.shape\ngc.collect()\n\"\"\"\n# Creating Folds  \nWill be using the same folds for cross validating all models here and in future notebooks.\n\"\"\"\ntrain['fold'] = -1\n#chose to create 6 folds since we have 600k samples, nice and round 100k per fold\nN_SPLITS = 6\n\nskf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)\n\nfor fold, (train_idx, val_idx) in enumerate(skf.split(X=train, y=train.target)):\n    train.loc[val_idx, 'fold'] = fold\ntrain.head()\ntrain.fold.value_counts()\n%%time\ntrain.to_csv('tps-nov21-6folds.csv', index=False)\nfeatures = [f for f in train.columns if f not in ('id', 'target', 'fold')]\ngc.collect()\n\"\"\"\n# Preprocessing + Linear model pipelines\n\"\"\"\nrobust = ('robust', RobustScaler())\nquantile = ('quantile', QuantileTransformer())\nstandard = ('standard', StandardScaler())\nminmax = ('minmax', MinMaxScaler())\nnorm = ('norm', Normalizer())\n\nclf = ('lr', LogisticRegression(solver='liblinear', random_state=SEED))\n\nmodel_dict = {\n    1: Pipeline([robust, clf]),\n    2: Pipeline([quantile, clf]),\n    3: Pipeline([standard, clf]),\n    4: Pipeline([minmax, clf]),\n    5: Pipeline([norm, clf])\n}\ndef custom_cross_val_predict(train, test, features, model):\n    oof_preds = {}\n    test_preds = []\n    scores = []\n    \n    cv_start = time.time()\n    \n    for fold in range(N_SPLITS):\n        xtrain = train[train.fold != fold].reset_index(drop=True)\n\n        xval = train[train.fold == fold].reset_index(drop=True)    \n        val_idx = xval.id.values.tolist()\n        \n        fold_start = time.time()\n        \n        model.fit(xtrain[features], xtrain.target)        \n        val_preds = model.predict_proba(xval[features])[:,1] #out-of-fold predictions      \n        oof_preds.update(dict(zip(val_idx, val_preds)))\n        auc = roc_auc_score(xval.target, val_preds)\n        scores.append(auc)\n        \n        fold_end = time.time()\n        \n        print(f'Fold #{fold}: AUC = {auc:.5f}\\t[Time: {fold_end - fold_start:.2f} secs]')\n        \n        test_preds.append(model.predict_proba(test[features])[:,1])\n        \n    cv_end = time.time()\n    print(f'Average AUC = {np.mean(scores):.5f} with std. dev. = {np.std(scores):.5f}')\n    print(f'[Total time: {cv_end - cv_start:.2f} secs]')\n    \n    oof_preds = pd.DataFrame.from_dict(oof_preds, orient='index').reset_index()\n    test_preds = np.mean(np.column_stack(test_preds), axis=1)\n    \n    return oof_preds, test_preds\n\nfor model_id, model in model_dict.items():\n    print('----- MODEL-' + str(model_id) + ' -----')\n    \n    oof_preds, test_preds = custom_cross_val_predict(train, test, features, model)\n    \n    oof_preds.columns = ['id', 'oof' + str(model_id)] #extracting model number from model_dict key\n    oof_preds.to_csv('oof' + str(model_id) + '.csv', index=False)\n    \n    output = pd.DataFrame({'id': test.id, 'target': test_preds})\n    output.to_csv('submission' + str(model_id) + '.csv', index=False)\n!head submission1.csv\n#can be merged based on 'id' into meta-dataset for stacking model\n!head oof3.csv\n\"\"\"\n1. Applying QuantileTransformer (Model-2) and Normalizer (Model-5) resulted in a drop in performance.  \n2. Applying RobustScaler (Model-1), StandardScaler (Model-3) and MinMaxScaler (Model-4) gave nearly equal AUC but the training time is significantly less with StandardScaler. Our Logistic Regression classifier is able to fit faster when the data is centered (mean = 0) with unit variance.  \n\nBased on these results, **we will stick with StandardScaler for our model pipeline** when we experiment with different feature selection methods.  \n\nAnother point to remember is that this variation in performance may not hold for other datasets and classifiers. In case we see significant improvement in scores for a particular feature set after feature selection, we can come back to this step and experiment with preprocessing again.\n\"\"\"\nmodel = model_dict[3] #StandardScaler() -> LogisticRegression()\ngc.collect()\n\"\"\"\n# [Feature Selection](https:\/\/en.wikipedia.org\/wiki\/Feature_selection)  \n\nMotivation - simplifying the models and reducing training times, by reducing the amount of data to be processed while maintaining relevant information  \nSince the features are anonymous, we cannot apply informed modifications. Thus, we will experiment with some feature selection methods based on the samples themselves.  \nFor different methods, we will end up with (hopefully) different subsets of features. We will evaluate them using the model we selected earlier and compare the performance with the results we have for the complete dataset.\n\nAnother branch of methods to reduce dimensions (a.k.a features) is [feature projection](https:\/\/en.wikipedia.org\/wiki\/Feature_extraction) (a.k.a feature extraction). They involve deriving new features from the original ones to transform the data into fewer dimensions. We will not be exploring these methods here.\n\"\"\"\n\"\"\"\n**Using [VarianceThreshold](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.feature_selection.VarianceThreshold.html#sklearn-feature-selection-variancethreshold)**  \n\nLow variance features can be discarded since they will not have a significant effect on the target variable.\n\"\"\"\nvt_default_selector = VarianceThreshold().fit(train[features]) #default threshold = 0\nfeature_mask = vt_default_selector.get_support() #array of booleans \n\nfeature_mask[:10]\n#extracting list of selected features using the feature mask obtained from SelectFromModel\ndef get_selected_features(feature_mask, input_features):\n    return [b for a, b in zip(feature_mask, input_features) if a]\nvt_default_features = get_selected_features(feature_mask, features)\n\nvt_default_features[:5], vt_default_features[-5:], len(vt_default_features)\n\"\"\"\nThere are no zero-variance features in our original dataset. Hence, no features were discarded. Let us add a threshold to remove low-variance features.\n\"\"\"\nvt_custom_selector = VarianceThreshold(threshold=0.1).fit(train[features])\nfeature_mask = vt_custom_selector.get_support()\nvt_custom_features = get_selected_features(feature_mask, features)\nlen(vt_custom_features)\nprint(f'Dropped features: {sorted(list(set(features) - set(vt_custom_features)))}')\n\"\"\"\n**Using [SelectFromModel](https:\/\/scikit-learn.org\/stable\/modules\/feature_selection.html#feature-selection-using-selectfrommodel)**  \n\nThe estimator calculates feature importances and the transformer selects those above a certain threshold.\n\"\"\"\n\"\"\"\nTree-based feature selection\n\"\"\"\n%%time\ntree_estimator = ExtraTreesClassifier(\n    n_estimators=150, \n    random_state=SEED\n)\n\ntree_estimator.fit(train[features], train.target)\ntree_mean_selector = SelectFromModel(tree_estimator, prefit=True, threshold='mean')\nfeature_mask = tree_mean_selector.get_support()\ntree_mean_features = get_selected_features(feature_mask, features)\nlen(tree_mean_features)\ntree_median_selector = SelectFromModel(tree_estimator, prefit=True, threshold='median')\nfeature_mask = tree_median_selector.get_support()\ntree_median_features = get_selected_features(feature_mask, features)\nlen(tree_median_features)\n\"\"\"\nL1-based (linear model) feature selection\n\"\"\"\n%%time\nlinear_estimator = LinearSVC(C=0.5, penalty=\"l1\", dual=False, random_state=SEED)\nlinear_estimator.fit(train[features], train.target)\nlinear_mean_selector = SelectFromModel(linear_estimator, prefit=True, threshold='mean')\nfeature_mask = linear_mean_selector.get_support()\nlinear_mean_features = get_selected_features(feature_mask, features)\nlen(linear_mean_features)\nlinear_median_selector = SelectFromModel(linear_estimator, prefit=True, threshold='median')\nfeature_mask = linear_median_selector.get_support()\nlinear_median_features = get_selected_features(feature_mask, features)\nlen(linear_median_features)\nfeature_dict = {\n    6: vt_custom_features, #feature scaling models were numbered up to 5. \n    7: tree_mean_features,\n    8: tree_median_features,\n    9: linear_mean_features,\n    10: linear_median_features\n}\nfor fid, features in feature_dict.items():\n    print('----- MODEL-' + str(fid) + ' -----')\n    \n    oof_preds, test_preds = custom_cross_val_predict(train, test, features, model)\n    \n    oof_preds.columns = ['id', 'oof' + str(fid)]\n    oof_preds.to_csv('oof' + str(fid) + '.csv', index=False)\n    \n    output = pd.DataFrame({'id': test.id, 'target': test_preds})\n    output.to_csv('submission' + str(fid) + '.csv', index=False)\n\"\"\"\nWell, our performance has suffered. So what did we achieve?  \n\n* Our 'base model' i.e., Model-3 had an average AUC of 0.74852 and it used the complete dataset.\n* With half the data and in half the time, we have an average AUC of 0.73674 (Model-8)\n* With almost one-fourth the data and in almost one-fourth the time, we have an average AUC of 0.72691 (Model-7)\n\nWe gained time and memory for a slight hit to our performance.  \n(Or a very large hit, depending on your attachment to the public LB :D )\n\"\"\"\n\"\"\"\n**This was an experiment with feature preprocessing and selection.**  \n* I browsed the scikit-learn documentation and chose preprocessing methods which I thought would modify the data in noticeably different ways. You can do the same and choose from several other methods.  \n* My approach was the same for feature selection methods. The chosen methods gave different feature sets depending on their internal mechanism of feature importance. I evaluated the feature selection methods only after pruning the preprocessing experiment. You can choose otherwise.  \n* And finally, all the methods were evaluated with a single classifier (logistic regression). The wide variety of classifiers certainly does not need coverage, hence the lack of focus there. You can choose any other classifier to replicate the experiment.\n\"\"\"\n\"\"\"\n**Time to submit!**  \n(The submission associated with the notebook will be for Model-3)\n\nThe folds dataset, out-of-fold predictions, and test predictions for all the models will be saved with the notebook.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '14a948b9394162'}"}
{"id":"86857","text":"\"\"\"\n## **Please upvote if you like!!!**\n\"\"\"\n\"\"\"\n# BANK LENDING\n\"\"\"\n\"\"\"\n## Task\n\"\"\"\n\"\"\"\nObjective :This is a binary classification where you need predict custusmer will default\n\"\"\"\n#loading_all libraries\nfrom sklearn.metrics import make_scorer, accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import average_precision_score,roc_auc_score\nfrom sklearn.metrics import f1_score,roc_curve,recall_score\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import cross_val_score\nimport matplotlib.pylab as pylab\nimport matplotlib.pyplot as plt\nfrom pandas import get_dummies\nfrom sklearn import metrics\nimport matplotlib as mpl\nfrom scipy import stats\nimport xgboost as xgb\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport warnings\nimport sklearn\nimport scipy\nimport numpy\nimport csv\n#to ignore warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\n\"\"\"\n# Loading the train and test data-set using pandas.read_table\n\n\n\"\"\"\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\ndf_train=pd.read_table('\/kaggle\/input\/xyzcorp-lendingdata\/XYZCorp_LendingData.txt',parse_dates=['issue_d'],low_memory=False)\n#to display the entire dataframe \npd.set_option(\"display.max.columns\", None)\ndf_train.shape\n\"\"\"\n# Data Description:\nTrain.csv : 855969 x 73 [including headers] \n\"\"\"\n#to view top 5 rows of dataframe\ndf_train.head(n=5)\n#to known about the dataframe of featurs\ndf_train.dtypes\n#function to find missing Value\ndef missing_data(df_train):\n    total = df_train.isnull().sum().sort_values(ascending=False)\n    percent = (df_train.isnull().sum()\/df_train.isnull().count()).sort_values(ascending=False)\n    missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n    return(missing_data.head(20))\n#missing_data function on dataset\nmissing_data(df_train)\n#removing top 26 feature with most missing value\ndf_train_new=df_train.drop(['dti_joint','verification_status_joint','annual_inc_joint','il_util','mths_since_rcnt_il',\n'total_bal_il','inq_last_12m','open_acc_6m','open_il_6m','open_il_24m','open_il_12m',\n'open_rv_12m','open_rv_24m','max_bal_bc','all_util','inq_fi','total_cu_tl','desc','mths_since_last_record',\n'mths_since_last_major_derog','mths_since_last_delinq','next_pymnt_d','tot_cur_bal',\n'tot_coll_amt','total_rev_hi_lim','emp_title'],axis=1)\n#imputing the missing value with mean value in revol_util featture\ndf_train_new['revol_util'].fillna(df_train_new['revol_util'].mean(),inplace=True)\nmissing_data(df_train_new)\n#feature enginearing on last_credit_pull_d feature\ndf_train_new['last_credit_pull_d'] = pd.to_datetime(df_train_new['last_credit_pull_d'])\ndf_train_new['Month'] = df_train_new['last_credit_pull_d'].apply(lambda x: x.month)\ndf_train_new['Year'] = df_train_new['last_credit_pull_d'].apply(lambda x: x.year)\ndf_train_new = df_train_new.drop(['last_credit_pull_d'], axis = 1)\n#imputing missing value with mode value \ndf_train_new['Month'].fillna(df_train_new.mode()['Month'][0],inplace=True)\ndf_train_new['Year'].fillna(df_train_new.mode()['Year'][0],inplace=True)\ndf_train_new.shape\nprint(df_train_new['title'].value_counts())\n#to impute missing na value with debt_consolidation because its is most repeted value\ndf_train_new['title'].fillna('Debt consolidation ',inplace=True)\ndf_train_new.dtypes\n#removing\/droping the unwanted features \ndf_train_new = df_train_new.drop(['id'],axis=1)\n\ndf_train_new = df_train_new.drop(['member_id'],axis=1)\n\ndf_train_new = df_train_new.drop(['earliest_cr_line'],axis=1)\n\ndf_train_new = df_train_new.drop(['zip_code'],axis=1)\n\ndf_train_new = df_train_new.drop(['last_pymnt_d'],axis=1)\n\ndf_train_new = df_train_new.drop(['policy_code'],axis=1)\ndf_train_new.head(n=5)\n#replace the categorial to numeric \ndf_train_new=df_train_new.replace(to_replace='10+ years',value=10)\ndf_train_new=df_train_new.replace(to_replace='1 year',value=1)\ndf_train_new=df_train_new.replace(to_replace='2 years',value=2)\ndf_train_new=df_train_new.replace(to_replace='3 years',value=3)\ndf_train_new=df_train_new.replace(to_replace='4 years',value=4)\ndf_train_new=df_train_new.replace(to_replace='5 years',value=5)\ndf_train_new=df_train_new.replace(to_replace='6 years',value=6)\ndf_train_new=df_train_new.replace(to_replace='7 years',value=7)\ndf_train_new=df_train_new.replace(to_replace='8 years',value=8)\ndf_train_new=df_train_new.replace(to_replace='9 years',value=9)\ndf_train_new=df_train_new.replace(to_replace='< 1 year',value=0.5)\ndf_train_new['title'].value_counts()\ncounts = df_train_new['title'].value_counts()\n\ndf_train_new = df_train_new[~df_train_new['title'].isin(counts[counts < 100].index)]\ndf_train_new.head(n=5)\n#to remove all na values throughout the dataset\ndf_train_new = df_train_new.dropna(axis = 0, how ='any') \ndf_train_new['emp_length'].value_counts()\n#dataset for data visulization in tabelau\ndf_train_bin=df_train_new\ndf_train_new.to_csv('Bank Lending.csv')\n\"\"\"\n##  Correlation Matrix\nWhen two sets of data are strongly linked together we say they have a High Correlation.\n\nThe word Correlation is made of Co- (meaning \"together\"), and Relation\n\nCorrelation is Positive when the values increase together, and\nCorrelation is Negative when one value decreases as the other increases\nA correlation is assumed to be linear (following a line).\n\ncorrelation examples\nCorrelation can have a value:\n\n1 is a perfect positive correlation\n0 is no correlation (the values don't seem linked at all)\n-1 is a perfect negative correlation\nThe value shows how good the correlation is (not how steep the line is), and if it is positive or negative.\n\"\"\"\n#correlation matrix\ncorrmat = df_train_new.corr()\nf, ax = plt.subplots(figsize=(10, 8))\nsns.heatmap(corrmat, vmax=.8, square=True);\n\"\"\"\n# Data Visualization\n\nData visualization is the graphic representation of data. It involves producing images that communicate relationships among the represented data to viewers of the images. This communication is achieved through the use of a systematic mapping between graphic marks and data values in the creation of the visualization\n\"\"\"\ndf_train['default_ind'].value_counts().plot.bar()\nsns.countplot('initial_list_status',data=df_train_new,hue='default_ind')\nsns.boxplot('grade','int_rate',data=df_train_new)\nplt.figure(figsize=(10,5))\nsns.distplot(df_train_new['int_rate'])\nplt.show()\nsns.violinplot('default_ind','int_rate',data=df_train_new,bw='scott')\n#plotting histogram of all features\ndf_train_new.hist(figsize=(15,20))\nsns.stripplot('default_ind','annual_inc',data=df_train_new,jitter=True)\nplt.figure(figsize=(15,10))\nsns.catplot(x='verification_status',y='loan_amnt',data=df_train_new,hue='default_ind',height=5,aspect=3,kind='box')\nplt.title('boxplot')\nplt.figure(figsize=(15,10))\nsns.relplot(x='funded_amnt', y='funded_amnt_inv', data=df_train_new,\n            kind='line', hue='term', col='default_ind')\nfig, ax = plt.subplots(1, 3, figsize=(16,5))\n\nsns.distplot(df_train['loan_amnt'], ax=ax[0])\nsns.distplot(df_train['funded_amnt'], ax=ax[1])\nsns.distplot(df_train['funded_amnt_inv'], ax=ax[2])\n\nax[1].set_title(\"Amount Funded by the Lender\")\nax[0].set_title(\"Loan Applied by the Borrower\")\nax[2].set_title(\"Total committed by Investors\")\ndf_train.purpose.value_counts(ascending=False).plot.bar(figsize=(10,5))\nplt.xlabel('purpose'); plt.ylabel('Density'); plt.title('Purpose of loan');\nplt.figure(figsize=(10,5))\ndf_train['issue_year'] = df_train['issue_d'].dt.year\nsns.barplot(x='issue_year',y='loan_amnt',data=df_train)\n# Loan Status \nfig, ax = plt.subplots(1, 2, figsize=(16,5))\ndf_train['default_ind'].value_counts().plot.pie(explode=[0,0.25],labels=['good loans','bad loans'],\n                                             autopct='%1.2f%%',startangle=70,ax=ax[0])\nsns.kdeplot(df_train.loc[df_train['default_ind']==0,'issue_year'],label='default_ind = 0')\nsns.kdeplot(df_train.loc[df_train['default_ind']==1,'issue_year'],label='default_ind = 1')\nplt.xlabel('Year'); plt.ylabel('Density'); plt.title('Yearwise Distribution of defaulter')\ndefaulter = df_train_new.loc[df_train_new['default_ind']==1]\nplt.figure(figsize=(10,10))\nplt.subplot(211)\nsns.boxplot(data=defaulter,x = 'home_ownership',y='loan_amnt',hue='default_ind')\nplt.subplot(212)\nsns.boxplot(data=defaulter,x='Year',y='loan_amnt',hue='home_ownership')\nsns.countplot('verification_status',data=df_train_new,hue='default_ind')\nsns.stripplot('default_ind','total_rec_prncp',data=df_train_new,jitter=True)\nplt.figure(figsize=(25,20))\nsns.factorplot(data=df_train_new,x='verification_status',y='loan_amnt',hue='default_ind')\n# Plotting\nsns.catplot(x='verification_status', y='loan_amnt', data=df_train_new, kind='boxen', aspect=2)\nplt.title('Boxen Plot', weight='bold', fontsize=16)\nplt.show()\ndf_train_new.columns\ndf_train_new.describe()\ndftrain_bin=df_train_new\n\"\"\"\n## Label Encoding \n\"\"\"\nfrom sklearn import preprocessing\n\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['term'])\nlist(le1.classes_)\ndf_train_new['term'] = le1.transform(df_train_new['term'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['grade'])\nlist(le1.classes_)\ndf_train_new['grade'] = le1.transform(df_train_new['grade'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['sub_grade'])\nlist(le1.classes_)\ndf_train_new['sub_grade'] = le1.transform(df_train_new['sub_grade'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['home_ownership'])\nlist(le1.classes_)\ndf_train_new['home_ownership'] = le1.transform(df_train_new['home_ownership'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['verification_status'])\nlist(le1.classes_)\ndf_train_new['verification_status'] = le1.transform(df_train_new['verification_status'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['purpose'])\nlist(le1.classes_)\ndf_train_new['purpose'] = le1.transform(df_train_new['purpose'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['addr_state'])\nlist(le1.classes_)\ndf_train_new['addr_state'] = le1.transform(df_train_new['addr_state'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['application_type'])\nlist(le1.classes_)\ndf_train_new['application_type'] = le1.transform(df_train_new['application_type'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['pymnt_plan'])\nlist(le1.classes_)\ndf_train_new['pymnt_plan'] = le1.transform(df_train_new['pymnt_plan'])\ndf_train_new.head()\nle1 = preprocessing.LabelEncoder()\nle1.fit(df_train_new['initial_list_status'])\nlist(le1.classes_)\ndf_train_new['initial_list_status'] = le1.transform(df_train_new['initial_list_status'])\ndf_train_new.head()\ndf_train_new.dtypes\n\"\"\"\n# Train And Test Split \n\"\"\"\ntrain = df_train_new[df_train_new['issue_d'] < '2015-6-01']\ntest = df_train_new[df_train_new['issue_d'] >= '2015-6-01']\nx_train=train.drop(['default_ind','title','issue_d'],axis=1)\ny_train=train['default_ind']\nx_test=test.drop(['default_ind','title','issue_d'],axis=1)\ny_test=test['default_ind']\n\"\"\"\n# LogisticRegression \n\nLogistic regression is a statistical model that in its basic form uses a logistic function to model a binary dependent variable, although many more complex extensions exist. In regression analysis, logistic regression (or logit regression) is estimating the parameters of a logistic model (a form of binary regression). Mathematically, a binary logistic model has a dependent variable with two possible values, such as pass\/fail which is represented by an indicator variable, where the two values are labeled \"0\" and \"1\". In the logistic model, the log-odds (the logarithm of the odds) for the value labeled \"1\" is a linear combination of one or more independent variables (\"predictors\"); the independent variables can each be a binary variable (two classes, coded by an indicator variable) or a continuous variable (any real value). The corresponding probability of the value labeled \"1\" can vary between 0 (certainly the value \"0\") and 1 (certainly the value \"1\"),\n\"\"\"\nlog =LogisticRegression()\nlog.fit(x_train,y_train)\n#model on train using all the independent values in df\nlog_prediction = log.predict(x_train)\nlog_score= accuracy_score(y_train,log_prediction)\nprint('Accuracy score on train set using Logistic Regression :',log_score)\n\"\"\"\n# confusion matrix\nA confusion matrix is a table that is often used to describe the performance of a classification model (or \u201cclassifier\u201d) on a set of test data for which the true values are known. It allows the visualization of the performance of an algorithm.\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_train, log_prediction)\n\"\"\"\n# AUC \nCompute Area Under the Curve (AUC) using the trapezoidal rule\n\"\"\"\nfrom sklearn import metrics\nfpr, tpr, thresholds = metrics.roc_curve(y_train,log_prediction)\nprint(\"AUC on train using Logistic Regression :\",metrics.auc(fpr, tpr))\n\"\"\"\n# average precision recall score\n\n\"\"\"\nfrom sklearn.metrics import average_precision_score\naverage_precision = average_precision_score(y_train, log_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\n\"\"\"\n# recall score\n\nThe recall is the ratio tp \/ (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples.\n\nThe best value is 1 and the worst value is 0.\n\"\"\"\nfrom sklearn.metrics import recall_score\nprint('recall_score on train set :',recall_score(y_train, log_prediction))\n\"\"\"\n # F1 Score\nCompute the F1 score, also known as balanced F-score or F-measure\n\nThe F1 score can be interpreted as a weighted average of the precision and recall, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score are equal. The formula for the F1 score is:\n\nF1 = 2 * (precision * recall) \/ (precision + recall)\n\"\"\"\nfrom sklearn.metrics import f1_score\nprint('F1_sccore on train set :',f1_score(y_train, log_prediction))\n\"\"\"\n## Classification report\n\"\"\"\nprint(classification_report(y_train,log_prediction))\n#model on test using all the independent values in df\nlog_prediction = log.predict(x_test)\nlog_score= accuracy_score(y_test,log_prediction)\nprint('accuracy score on test using Logisitic Regression :',log_score)\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_test, log_prediction)\nfrom sklearn import metrics\nfpr, tpr, thresholds = metrics.roc_curve(y_test,log_prediction)\nprint(\"AUC on test using Logistic Regression :\",metrics.auc(fpr, tpr))\nfrom sklearn.metrics import average_precision_score\naverage_precision = average_precision_score(y_test, log_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nfrom sklearn.metrics import recall_score\nprint('recall_score on train set :',recall_score(y_test, log_prediction))\nfrom sklearn.metrics import f1_score\nprint('F1_sccore on train set :',f1_score(y_test, log_prediction))\nprint(classification_report(y_test, log_prediction))\n\"\"\"\n## Kfold cross validation\n\"\"\"\nlr = LogisticRegression()\nscores = cross_val_score(lr, x_train, y_train, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n## ROC Curve\n\"\"\"\nlr_prob=log.predict_proba(x_train)\nlr_prob=lr_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, lr_prob)\nprint('auc_score for Logistic Regression(train): ', roc_auc_score(y_train, lr_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - logistic regression')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nlr_prob_test=log.predict_proba(x_test)\nlr_prob_test=lr_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, lr_prob_test)\nprint('auc_score for Logistic Regression(test): ', roc_auc_score(y_test, lr_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - logistic regression')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n# XGBoost Algorithm\n\nXGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way. The same code runs on major distributed environment (Hadoop, SGE, MPI) and can solve problems beyond billions of examples.\n\"\"\"\nxgboost = xgb.XGBClassifier(max_depth=3,n_estimators=300,learning_rate=0.05)\nxgboost.fit(x_train,y_train)\n#XGBoost model on the train set\nXGB_prediction = xgboost.predict(x_train)\nXGB_score= accuracy_score(y_train,XGB_prediction)\nprint('accuracy score on train using XGBoost ',XGB_score)\nconfusion_matrix(y_train, XGB_prediction)\nfpr, tpr, thresholds = metrics.roc_curve(y_train,XGB_prediction)\nprint(\"AUC on train using XGBoost :\",metrics.auc(fpr, tpr))\naverage_precision = average_precision_score(y_train, XGB_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on train set :',recall_score(y_train, XGB_prediction))\nprint('F1_sccore on train set :',f1_score(y_train, XGB_prediction))\nprint('classification Report on  train using XGBoost :')\nprint(classification_report(y_train,XGB_prediction))\n#XGBoost model on the test\nXGB_prediction = xgboost.predict(x_test)\nXGB_score= accuracy_score(y_test,XGB_prediction)\nprint('accuracy score on test using XGBoost :',XGB_score)\nconfusion_matrix(y_test, XGB_prediction)\nfpr, tpr, thresholds = metrics.roc_curve(y_test,XGB_prediction)\nprint(\"AUC on test using XGBoost :\",metrics.auc(fpr, tpr))\naverage_precision = average_precision_score(y_test, XGB_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on test set :',recall_score(y_test, XGB_prediction))\nprint('F1_sccore on test set :',f1_score(y_test, XGB_prediction))\nprint('classification Report on  test using XGBoost :')\nprint(classification_report(y_test,XGB_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nxg_prob=xgboost.predict_proba(x_train)\nxg_prob=xg_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, xg_prob)\nprint('auc_score for Xgboost: (train): ', roc_auc_score(y_train, xg_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - XGBoost ')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nxg_prob_test=xgboost.predict_proba(x_test)\nxg_prob_test=xg_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, xg_prob_test)\nprint('auc_score for Xgboost(test): ', roc_auc_score(y_test, xg_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - XGBoost ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Feature Importance Graph\n\"\"\"\nimport pandas as pd\n%matplotlib inline\n#do code to support model\n#\"data\" is the X dataframe and model is the SKlearn object\n\nfeats = {} # a dict to hold feature_name: feature_importance\nfor feature, importance in zip(x_train.columns, xgboost.feature_importances_):\n    feats[feature] = importance #add the name\/value pair \n\nimportances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini-importance'})\n#plt.figure(figsize=(15,7))\nimportances.sort_values(by='Gini-importance').plot(kind='bar', rot=45,figsize=(15,7))\n\"\"\"\n## Kfold Cross Validation\n\"\"\"\nxg = xgb.XGBClassifier()\nscores = cross_val_score(xg, x_test, y_test, cv=10, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# RandomForestClassifier\nRandom forests or random decision forests are an ensemble learning method for classification, regression and other tasks that operate by constructing a multitude of decision trees at training time and outputting the class that is the mode of the classes (classification) or mean prediction (regression) of the individual trees.Random decision forests correct for decision trees' habit of overfitting to their training set.\n\"\"\"\nrfc2=RandomForestClassifier()\nrfc2.fit(x_train,y_train)\n#model on train using all the independent values in df\nrfc_prediction = rfc2.predict(x_train)\nrfc_score= accuracy_score(y_train,rfc_prediction)\nprint('accuracy Score on train using RandomForest :',rfc_score)\nconfusion_matrix(y_train, rfc_prediction)\nfpr, tpr, thresholds = metrics.roc_curve(y_train,rfc_prediction)\nprint(\"AUC on train using RandomForest :\",metrics.auc(fpr, tpr))\naverage_precision = average_precision_score(y_train, rfc_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on train set :',recall_score(y_train, rfc_prediction))\nprint('F1_sccore on train set :',f1_score(y_train, rfc_prediction))\nprint('classification Report on  train using RandomForest :')\nprint(classification_report(y_train,rfc_prediction))\n#model on test using all the indpendent values in df\nrfc_prediction = rfc2.predict(x_test)\nrfc_score= accuracy_score(y_test,rfc_prediction)\nprint('accuracy score on test using RandomForest ',rfc_score)\nconfusion_matrix(y_test, rfc_prediction)\nfpr, tpr, thresholds = metrics.roc_curve(y_test,rfc_prediction)\nprint(\"AUC on test using RandomForest :\",metrics.auc(fpr, tpr))\naverage_precision = average_precision_score(y_test, rfc_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on test set :',recall_score(y_test, rfc_prediction))\nprint('F1_sccore on train set :',f1_score(y_test, rfc_prediction))\nprint('classification Report on  test using RandomForest :')\nprint(classification_report(y_test,rfc_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nrf_prob=rfc2.predict_proba(x_train)\nrf_prob=rf_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, rf_prob)\nprint('auc_score for Random Forest : (train): ', roc_auc_score(y_train, rf_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - Random Forest :')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nrf_prob_test=rfc2.predict_proba(x_test)\nrf_prob_test=rf_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, rf_prob_test)\nprint('auc_score for Random forest (test): ', roc_auc_score(y_test, rf_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - Random Forest : ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Feature Importance graph\n\"\"\"\nimport pandas as pd\n%matplotlib inline\n#do code to support model\n#\"data\" is the X dataframe and model is the SKlearn object\n\nfeats = {} # a dict to hold feature_name: feature_importance\nfor feature, importance in zip(x_train.columns, rfc2.feature_importances_):\n    feats[feature] = importance #add the name\/value pair \n\nimportances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini-importance'})\n#plt.figure(figsize=(15,7))\nimportances.sort_values(by='Gini-importance').plot(kind='bar', rot=45,figsize=(15,7))\n\"\"\"\n## Kfold Cross Validation\n\"\"\"\nlr = RandomForestClassifier(n_estimators=100)\nscores = cross_val_score(lr, x_train, y_train, cv=3, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# Decision Tree CLassifier\n\nA decision tree is a decision support tool that uses a tree-like model of decisions and their possible consequences, including chance event outcomes, resource costs, and utility. It is one way to display an algorithm that only contains conditional control statements.\n\nDecision trees are commonly used in operations research, specifically in decision analysis, to help identify a strategy most likely to reach a goal, but are also a popular tool in machine learning.\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\ndec=DecisionTreeClassifier()\ndec.fit(x_train,y_train)\n#model on train using all the independent values in df\ndec_prediction = dec.predict(x_train)\ndec_score= accuracy_score(y_train,dec_prediction)\nprint('Accuracy score on train using Decision Tree :',dec_score)\n    print(confusion_matrix(y_train, dec_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_train,dec_prediction)\n    print(\"AUC on train using DecisionTree :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_train, dec_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on train set :',recall_score(y_train, dec_prediction))\n    print('F1_sccore on train set :',f1_score(y_train, dec_prediction))\n    print('classification report on train using Decision tree ',classification_report(y_train,dec_prediction))\n#model on test using all the independent values in df\ndec_prediction = dec.predict(x_test)\ndec_score= accuracy_score(y_test,dec_prediction)\nprint('Accuracy Score on tree using Decision Tree  :',dec_score)\n    print(confusion_matrix(y_test, dec_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_test,dec_prediction)\n    print(\"AUC on test using DecisionTree :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_test, dec_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on test set :',recall_score(y_test, dec_prediction))\n    print('F1_sccore on test set :',f1_score(y_test, dec_prediction))\n    print('classification report on test using Decision tree ',classification_report(y_test,dec_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nrf_prob=dec.predict_proba(x_train)\nrf_prob=rf_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, rf_prob)\nprint('auc_score for decision tree : (train): ', roc_auc_score(y_train, rf_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - decision tre :')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nrf_prob_test=dec.predict_proba(x_test)\nrf_prob_test=rf_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, rf_prob_test)\nprint('auc_score for decision tree (test): ', roc_auc_score(y_test, rf_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - decision tree : ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Kfold Cross Validation\n\"\"\"\nlr = DecisionTreeClassifier()\nscores = cross_val_score(lr, x_train, y_train, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# ExtraTreeClassifier\n\nEach Decision Tree in the Extra Trees Forest is constructed from the original training sample. Then, at each test node, Each tree is provided with a random sample of k features from the feature-set from which each decision tree must select the best feature to split the data based on some mathematical criteria (typically the Gini Index). This random sample of features leads to the creation of multiple de-correlated decision trees.\n\"\"\"\nfrom sklearn.tree import ExtraTreeClassifier\netc=ExtraTreeClassifier()\netc.fit(x_train,y_train)\n#model on train using all the independent values in df\netc_prediction = etc.predict(x_train)\netc_score= accuracy_score(y_train,etc_prediction)\nprint('Accuracy score on train using extratree :',etc_score)\n    print(confusion_matrix(y_train, etc_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_train,etc_prediction)\n    print(\"AUC on train using ExtraTree :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_train, etc_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on train set :',recall_score(y_train, etc_prediction))\n    print('F1_sccore on train set :',f1_score(y_train, etc_prediction))\n    print('classification report on train using Extra tree ',classification_report(y_train,etc_prediction))\n#model on test using all the independent values in df\netc_prediction = etc.predict(x_test)\netc_score= accuracy_score(y_test,etc_prediction)\nprint('Accuracy score on test using extratree :',etc_score)\n    print(confusion_matrix(y_test, etc_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_test,etc_prediction)\n    print(\"AUC on train using ExtraTree :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_test, etc_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on test set :',recall_score(y_test, dec_prediction))\n    print('F1_sccore on test set :',f1_score(y_test, etc_prediction))\n    print('classification report on test using Extra tree ',classification_report(y_test,etc_prediction))\n\"\"\"\n## ROC Curve \n\"\"\"\nrf_prob=etc.predict_proba(x_train)\nrf_prob=rf_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, rf_prob)\nprint('auc_score for Extra tree : (train): ', roc_auc_score(y_train, rf_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - Extra tree :')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nrf_prob_test=etc.predict_proba(x_test)\nrf_prob_test=rf_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, rf_prob_test)\nprint('auc_score for Extra Tree (test): ', roc_auc_score(y_test, rf_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - Extra tree : ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Kfold Cross Validation\n\"\"\"\nlr = ExtraTreeClassifier()\nscores = cross_val_score(lr, x_train, y_train, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# AdaBoostClassifier\n\nAn AdaBoost classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases.\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\nada =AdaBoostClassifier(n_estimators=100)\nada.fit(x_train,y_train)\n#model on train using all the independent values in df\nada_prediction = ada.predict(x_train)\nada_score= accuracy_score(y_train,ada_prediction)\nprint('Accuracy score on train using AdaBoost :',ada_score)\n    print(confusion_matrix(y_train, ada_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_train,ada_prediction)\n    print(\"AUC on train using AdaBoost :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_train, ada_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on train set :',recall_score(y_train, ada_prediction))\n    print('F1_sccore on train set :',f1_score(y_train, ada_prediction))\n    print('classification report on train using Extra tree ',classification_report(y_train,ada_prediction))\n#model on test using all the independent values in df\nada_prediction = ada.predict(x_test)\nada_score= accuracy_score(y_test,ada_prediction)\nprint('accuracy score on test using AdaBoost :',ada_score)\n    print(confusion_matrix(y_test, ada_prediction))\n    fpr, tpr, thresholds = metrics.roc_curve(y_test,ada_prediction)\n    print(\"AUC on test using AdaBoost :\",metrics.auc(fpr, tpr))\n    average_precision = average_precision_score(y_test, ada_prediction)\n    print('Average precision-recall score: {0:0.2f}'.format(average_precision))\n    print('recall_score on test set :',recall_score(y_test, ada_prediction))\n    print('F1_sccore on test set :',f1_score(y_test, ada_prediction))\n    print('classification report on test using Extra tree ',classification_report(y_test,ada_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nrf_prob=ada.predict_proba(x_train)\nrf_prob=rf_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, rf_prob)\nprint('auc_score for ADAboost : (train): ', roc_auc_score(y_train, rf_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) -ADAboost :')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nrf_prob_test=ada.predict_proba(x_test)\nrf_prob_test=rf_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, rf_prob_test)\nprint('auc_score for ADAboost (test): ', roc_auc_score(y_test, rf_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - ADAboost : ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Kfold Cross Validation\n\"\"\"\nlr = AdaBoostClassifier(n_estimators=100)\nscores = cross_val_score(lr, x_train, y_train, cv=3, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n<h3 style='padding: 10px'>Comparison Table (LABEL ENCODING)<\/h2><table border-style:solid; class='table table-striped'> <thead> <tr> <th>Algorithm Used<\/th> <th>Accuracy Score On Train<\/th> <th>Accuracy Score On Test<\/th><\/tr> <\/thead> <tbody> <tr> <th scope='row'>XGBoost Classifier <\/th> <td>0.997<\/td> <td>0.781<\/td><\/tr> \n    <tr> <th scope='row'>Random Forest Classifier<\/th> <td>0.995<\/td> <td>0.391<\/td><\/tr> <tr> \n    <th scope='row'>Logisitic Regresion<\/th> <td>0.996<\/td> <td>0.998\n    <\/td><\/tr> <tr><th scope='row'>Decision Tree Classifier<\/th> <td>1.0<\/td> <td>0.30<\/td><\/tr>\n    <tr><th scope='row'>Extra tree classifier<\/th><td>1.0<\/td><td>0.612<\/td><\/tr>\n    <tr><th scope='row'>ADA boost classifier<\/th><td>0.996<\/td><td>0.862<\/td><\/tr>\n    <\/tbody> <\/table>\n\"\"\"\n\"\"\"\n# Binary Encoding\n\"\"\"\ndf_train_bin=df_train_new\nfrom sklearn.preprocessing import LabelBinarizer\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['term'])\nlist(le1.classes_)\ndf_train_new['term'] = le1.transform(df_train_new['term'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['grade'])\nlist(le1.classes_)\ndf_train_new['grade'] = le1.transform(df_train_new['grade'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['sub_grade'])\nlist(le1.classes_)\ndf_train_new['sub_grade'] = le1.transform(df_train_new['sub_grade'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['home_ownership'])\nlist(le1.classes_)\ndf_train_new['home_ownership'] = le1.transform(df_train_new['home_ownership'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['verification_status'])\nlist(le1.classes_)\ndf_train_new['verification_status'] = le1.transform(df_train_new['verification_status'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['purpose'])\nlist(le1.classes_)\ndf_train_new['purpose'] = le1.transform(df_train_new['purpose'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['addr_state'])\nlist(le1.classes_)\ndf_train_new['addr_state'] = le1.transform(df_train_new['addr_state'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['application_type'])\nlist(le1.classes_)\ndf_train_new['application_type'] = le1.transform(df_train_new['application_type'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['pymnt_plan'])\nlist(le1.classes_)\ndf_train_new['pymnt_plan'] = le1.transform(df_train_new['pymnt_plan'])\ndf_train_new.head()\nle1 = preprocessing.LabelBinarizer()\nle1.fit(df_train_new['initial_list_status'])\nlist(le1.classes_)\ndf_train_new['initial_list_status'] = le1.transform(df_train_new['initial_list_status'])\ndf_train_new.head()\ndf_train_new.dtypes\n\"\"\"\n## Train Test Split \n\"\"\"\ntrain = df_train_new[df_train_new['issue_d'] < '2015-6-01']\ntest = df_train_new[df_train_new['issue_d'] >= '2015-6-01']\ndel df_train_new['issue_d']\nx_train=train.drop(['default_ind','title','issue_d'],axis=1)\ny_train=train['default_ind']\nx_test=test.drop(['default_ind','title','issue_d'],axis=1)\ny_test=test['default_ind']\n\"\"\"\n## Logisitic Regression on Binary encoded Dataset\n\n\"\"\"\nlog =LogisticRegression()\nlog.fit(x_train,y_train)\n#model on train using all the independent values in df\nlog_prediction = log.predict(x_train)\nlog_score= accuracy_score(y_train,log_prediction)\nprint('Accuracy score on train set using Logistic Regression :',log_score)\nprint(confusion_matrix(y_train, log_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_train,log_prediction)\nprint(\"AUC on train using Logistic regression :\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_train, log_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on train set :',recall_score(y_train, log_prediction))\nprint('F1_sccore on train set :',f1_score(y_train, log_prediction))\nprint('classification report on train using Logistic regression  ',\n      classification_report(y_train,log_prediction))\n#model on train using all the independent values in df\nlog_prediction = log.predict(x_test)\nlog_score= accuracy_score(y_test,log_prediction)\nprint('accuracy score on test using Logisitic Regression :',log_score)\nprint(confusion_matrix(y_test, log_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_test,log_prediction)\nprint(\"AUC on test using Logistic regression :\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_test, log_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on test set :',recall_score(y_test, log_prediction))\nprint('F1_sccore on test set :',f1_score(y_test, log_prediction))\nprint('classification report on test using Logistic regression  ',classification_report(y_test,log_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nlr_prob=log.predict_proba(x_train)\nlr_prob=lr_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, lr_prob)\nprint('auc_score for Logistic Regression(train): ', roc_auc_score(y_train, lr_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - logistic regression')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nlr_prob_test=log.predict_proba(x_test)\nlr_prob_test=lr_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, lr_prob_test)\nprint('auc_score for Logistic Regression(test): ', roc_auc_score(y_test, lr_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - logistic regression')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## KFold Cross Validation \n\"\"\"\nlr = LogisticRegression()\nscores = cross_val_score(lr, x_train, y_train, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# XGBoost on Binary Encoded data\n\"\"\"\nxgboost = xgb.XGBClassifier(max_depth=3,n_estimators=300,learning_rate=0.05)\nxgboost.fit(x_train,y_train)\n#XGBoost model on the train set\nXGB_prediction = xgboost.predict(x_train)\nXGB_score= accuracy_score(y_train,XGB_prediction)\nprint('accuracy score on train using XGBoost ',XGB_score)\nprint(confusion_matrix(y_train, XGB_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_train,XGB_prediction)\nprint(\"AUC on train using XGBClassifiers:\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_train, XGB_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on train set :',recall_score(y_train, XGB_prediction))\nprint('F1_sccore on train set :',f1_score(y_train, XGB_prediction))\nprint('classification report on train using XGBoost  ')\nprint(classification_report(y_train,XGB_prediction))\n#XGBoost model on the test\nXGB_prediction = xgboost.predict(x_test)\nXGB_score= accuracy_score(y_test,XGB_prediction)\nprint('accuracy score on test using XGBoost :',XGB_score)\nprint(confusion_matrix(y_test, XGB_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_test,XGB_prediction)\nprint(\"AUC on test using XGBClassifiers:\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_test, XGB_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on test set :',recall_score(y_test, XGB_prediction))\nprint('F1_sccore on test set :',f1_score(y_test, XGB_prediction))\nprint('classification report on test using XGBoost  ')\nprint(classification_report(y_test,XGB_prediction))\n\"\"\"\n## ROC Curve\n\"\"\"\nxg_prob=xgboost.predict_proba(x_train)\nxg_prob=xg_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, xg_prob)\nprint('auc_score for Xgboost: (train): ', roc_auc_score(y_train, xg_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - XGBoost ')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nxg_prob_test=xgboost.predict_proba(x_test)\nxg_prob_test=xg_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, xg_prob_test)\nprint('auc_score for Xgboost(test): ', roc_auc_score(y_test, xg_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - XGBoost ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## Kfold crossValiddation\n\"\"\"\nxg = xgb.XGBClassifier()\nscores = cross_val_score(xg, x_test, y_test, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n# RandomForestclassifier on BinaryEncoded dataset\n\"\"\"\nrfc2=RandomForestClassifier(n_estimators=100)\nrfc2.fit(x_train,y_train)\n#model on train using all the independent values in df\nrfc_prediction = rfc2.predict(x_train)\nrfc_score= accuracy_score(y_train,rfc_prediction)\nprint('accuracy Score on train using RandomForest :',rfc_score)\nprint(confusion_matrix(y_train, rfc_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_train,rfc_prediction)\nprint(\"AUC on train using RandomForest :\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_train, rfc_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on train set :',recall_score(y_train, rfc_prediction))\nprint('F1_sccore on train set :',f1_score(y_train, rfc_prediction))\nprint('classification Report on  train using RandomForest :')\nprint(classification_report(y_train,rfc_prediction))\n#model on test using all the indpendent values in df\nrfc_prediction = rfc2.predict(x_test)\nrfc_score= accuracy_score(y_test,rfc_prediction)\nprint('accuracy score on test using RandomForest ',rfc_score)\nprint(confusion_matrix(y_test, rfc_prediction))\nfpr, tpr, thresholds = metrics.roc_curve(y_test,rfc_prediction)\nprint(\"AUC on test using RandomForest :\",metrics.auc(fpr, tpr))\n\naverage_precision = average_precision_score(y_test, rfc_prediction)\n\nprint('Average precision-recall score: {0:0.2f}'.format(\n      average_precision))\nprint('recall_score on test set :',recall_score(y_test, rfc_prediction))\nprint('F1_sccore on test set :',f1_score(y_test, rfc_prediction))\nprint('classification Report on  test using RandomForest :')\nprint(classification_report(y_test,rfc_prediction))\n\"\"\"\n## ROC Curve \n\"\"\"\nrf_prob=rfc2.predict_proba(x_train)\nrf_prob=rf_prob[:,1]\nfalse_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_train, rf_prob)\nprint('auc_score for Random Forest : (train): ', roc_auc_score(y_train, rf_prob))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(train) - Random Forest :')\nplt.plot(false_positive_rate1, true_positive_rate1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nrf_prob_test=rfc2.predict_proba(x_test)\nrf_prob_test=rf_prob_test[:,1]\nfalse_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, rf_prob_test)\nprint('auc_score for Random forest (test): ', roc_auc_score(y_test, rf_prob_test))\n# Plot ROC curves\nplt.subplots(1, figsize=(5,5))\nplt.title('Receiver Operating Characteristic(test) - Random Forest : ')\nplt.plot(false_positive_rate2, true_positive_rate2)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\"\"\"\n## KcrossFold Validation\n\"\"\"\nlr = RandomForestClassifier(n_estimators=100)\nscores = cross_val_score(lr, x_train, y_train, cv=5, scoring = \"accuracy\")\nprint(\"Scores:\", scores)\nprint(\"Mean:\", scores.mean())\nprint(\"Standard Deviation:\", scores.std())\n\"\"\"\n<h2 style='padding: 10px'>Comparison Table (BINARY ENCODING)<\/h2><table border-style:solid; class='table table-striped'> <thead> <tr> <th>Algorithm Used<\/th> <th>Accuracy Score On Train<\/th> <th>Accuracy Score On Test<\/th><\/tr> <\/thead> <tbody> <tr> <th scope='row'>XGBoost Classifier <\/th> <td>0.997<\/td> <td>0.594<\/td><\/tr> \n    <tr> <th scope='row'>Random Forest Classifier<\/th> <td>0.999<\/td> <td>0.358<\/td><\/tr> <tr> \n    <th scope='row'>Logisitic Regresion<\/th> <td>0.996<\/td> <td>0.998\n    <\/tbody> <\/table>\n\"\"\"\n\"\"\"\n# Conclusion\n\"\"\"\n\"\"\"\nFrom all above analyis we can conclude that after binary encoding of dataset and applying logisitic regression model gives best results with accuracy score 0.996 on train and 0.998 on train. \n\n\nHence logistic model can be used for further predicting.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9f512ab519a767'}"}
{"id":"41646","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport tensorflow as tf\n\nfrom typing import Union\nfrom tqdm.notebook import tqdm\n# reading data\npath_folder = \"..\/input\/m5-forecasting-accuracy\/\"\n\ndf_train_full = pd.read_csv(path_folder + \"sales_train_evaluation.csv\")\ndf_calendar = pd.read_csv(path_folder + \"calendar.csv\")\ndf_prices = pd.read_csv(path_folder + \"sell_prices.csv\")\ndf_sample_submission_original = pd.read_csv(path_folder + \"sample_submission.csv\")\n\"\"\"\n# Code to verify score and public ranking (used to validate model during testing)\nSource: https:\/\/www.kaggle.com\/rohanrao\/m5-how-to-get-your-public-lb-score-rank\n\"\"\"\n## evaluation metric\n## from https:\/\/www.kaggle.com\/c\/m5-forecasting-accuracy\/discussion\/133834 and edited to get scores at all levels\nclass WRMSSEEvaluator(object):\n\n    def __init__(self, train_df: pd.DataFrame, valid_df: pd.DataFrame, calendar: pd.DataFrame, prices: pd.DataFrame):\n        train_y = train_df.loc[:, train_df.columns.str.startswith('d_')]\n        train_target_columns = train_y.columns.tolist()\n        weight_columns = train_y.iloc[:, -28:].columns.tolist()\n\n        train_df['all_id'] = 0  # for lv1 aggregation\n\n        id_columns = train_df.loc[:, ~train_df.columns.str.startswith('d_')].columns.tolist()\n        valid_target_columns = valid_df.loc[:, valid_df.columns.str.startswith('d_')].columns.tolist()\n\n        if not all([c in valid_df.columns for c in id_columns]):\n            valid_df = pd.concat([train_df[id_columns], valid_df], axis=1, sort=False)\n\n        self.train_df = train_df\n        self.valid_df = valid_df\n        self.calendar = calendar\n        self.prices = prices\n\n        self.weight_columns = weight_columns\n        self.id_columns = id_columns\n        self.valid_target_columns = valid_target_columns\n\n        weight_df = self.get_weight_df()\n\n        self.group_ids = (\n            'all_id',\n            'cat_id',\n            'state_id',\n            'dept_id',\n            'store_id',\n            'item_id',\n            ['state_id', 'cat_id'],\n            ['state_id', 'dept_id'],\n            ['store_id', 'cat_id'],\n            ['store_id', 'dept_id'],\n            ['item_id', 'state_id'],\n            ['item_id', 'store_id']\n        )\n\n        for i, group_id in enumerate(tqdm(self.group_ids)):\n            train_y = train_df.groupby(group_id)[train_target_columns].sum()\n            scale = []\n            for _, row in train_y.iterrows():\n                series = row.values[np.argmax(row.values != 0):]\n                scale.append(((series[1:] - series[:-1]) ** 2).mean())\n            setattr(self, f'lv{i + 1}_scale', np.array(scale))\n            setattr(self, f'lv{i + 1}_train_df', train_y)\n            setattr(self, f'lv{i + 1}_valid_df', valid_df.groupby(group_id)[valid_target_columns].sum())\n\n            lv_weight = weight_df.groupby(group_id)[weight_columns].sum().sum(axis=1)\n            setattr(self, f'lv{i + 1}_weight', lv_weight \/ lv_weight.sum())\n\n    def get_weight_df(self) -> pd.DataFrame:\n        day_to_week = self.calendar.set_index('d')['wm_yr_wk'].to_dict()\n        weight_df = self.train_df[['item_id', 'store_id'] + self.weight_columns].set_index(['item_id', 'store_id'])\n        weight_df = weight_df.stack().reset_index().rename(columns={'level_2': 'd', 0: 'value'})\n        weight_df['wm_yr_wk'] = weight_df['d'].map(day_to_week)\n\n        weight_df = weight_df.merge(self.prices, how='left', on=['item_id', 'store_id', 'wm_yr_wk'])\n        weight_df['value'] = weight_df['value'] * weight_df['sell_price']\n        weight_df = weight_df.set_index(['item_id', 'store_id', 'd']).unstack(level=2)['value']\n        weight_df = weight_df.loc[zip(self.train_df.item_id, self.train_df.store_id), :].reset_index(drop=True)\n        weight_df = pd.concat([self.train_df[self.id_columns], weight_df], axis=1, sort=False)\n        return weight_df\n\n    def rmsse(self, valid_preds: pd.DataFrame, lv: int) -> pd.Series:\n        valid_y = getattr(self, f'lv{lv}_valid_df')\n        score = ((valid_y - valid_preds) ** 2).mean(axis=1)\n        scale = getattr(self, f'lv{lv}_scale')\n        return (score \/ scale).map(np.sqrt)\n\n    def score(self, valid_preds: Union[pd.DataFrame, np.ndarray]) -> float:\n        assert self.valid_df[self.valid_target_columns].shape == valid_preds.shape\n\n        if isinstance(valid_preds, np.ndarray):\n            valid_preds = pd.DataFrame(valid_preds, columns=self.valid_target_columns)\n\n        valid_preds = pd.concat([self.valid_df[self.id_columns], valid_preds], axis=1, sort=False)\n\n        group_ids = []\n        all_scores = []\n        for i, group_id in enumerate(self.group_ids):\n            lv_scores = self.rmsse(valid_preds.groupby(group_id)[self.valid_target_columns].sum(), i + 1)\n            weight = getattr(self, f'lv{i + 1}_weight')\n            lv_scores = pd.concat([weight, lv_scores], axis=1, sort=False).prod(axis=1)\n            group_ids.append(group_id)\n            all_scores.append(lv_scores.sum())\n\n        return group_ids, all_scores\n## public LB rank\ndef get_lb_rank(score):\n    \"\"\"\n    Get rank on public LB as of 2020-05-31 23:59:59\n    \"\"\"\n    df_lb = pd.read_csv(\"..\/input\/m5-accuracy-final-public-lb\/m5-forecasting-accuracy-publicleaderboard-rank.csv\")\n\n    return (df_lb.Score <= score).sum() + 1\n\ndef get_ranking_from_submission(submission_original, evaluator, df_sample_submission_original=df_sample_submission_original):\n    submission = submission_original.copy()\n    submission = submission[submission.id.str.contains(\"validation\")]\n    \n    df_sample_submission = df_sample_submission_original.copy()\n    df_sample_submission[\"order\"] = range(df_sample_submission.shape[0])\n\n    submission = submission.merge(df_sample_submission[[\"id\", \"order\"]], on = \"id\").sort_values(\"order\").drop([\"id\", \"order\"], axis = 1).reset_index(drop = True)\n    submission.rename(columns = {\n        \"F1\": \"d_1914\", \"F2\": \"d_1915\", \"F3\": \"d_1916\", \"F4\": \"d_1917\", \"F5\": \"d_1918\", \"F6\": \"d_1919\", \"F7\": \"d_1920\",\n        \"F8\": \"d_1921\", \"F9\": \"d_1922\", \"F10\": \"d_1923\", \"F11\": \"d_1924\", \"F12\": \"d_1925\", \"F13\": \"d_1926\", \"F14\": \"d_1927\",\n        \"F15\": \"d_1928\", \"F16\": \"d_1929\", \"F17\": \"d_1930\", \"F18\": \"d_1931\", \"F19\": \"d_1932\", \"F20\": \"d_1933\", \"F21\": \"d_1934\",\n        \"F22\": \"d_1935\", \"F23\": \"d_1936\", \"F24\": \"d_1937\", \"F25\": \"d_1938\", \"F26\": \"d_1939\", \"F27\": \"d_1940\", \"F28\": \"d_1941\"\n    }, inplace = True)\n\n    groups, scores = evaluator.score(submission)\n\n    score_public_lb = np.mean(scores)\n    score_public_rank = get_lb_rank(score_public_lb)\n\n    for i in range(len(groups)):\n        print(\"Score for group {}: {}\".format(groups[i],round(scores[i], 5)))\n        \n    print(\"\\nPublic LB Score: {}\".format(round(score_public_lb, 5)))\n    print(\"Public LB Rank: {}\".format(score_public_rank))\n    \n    return None\n\"\"\"\n## Approach: 'GROUPED' modelling per store and department data day-by-day approach\n- 70 groups of store + department -> 70 models to build (between 149 and 532 items for each)\n- Inputs (for each store-department combination): previous sales, day + price data (only for the day to predict)\n\nReasons for such division:\n- kaggle notebook doesn't have enough RAM to handle the whole dataset and a correspondingly complex model at once\n- our hypothesis here is that the sale of an item in a store in one of the departments has an impact on a different item in that same department and store (e.g. a customer picks up an item and it reminds him of buying another one close to that item)\n\"\"\"\n\"\"\"\n## Feature engineering\nwe will transpose the day data (calendar and prices) and then stack it to our current input X (or X_reshaped)\n\nOther possible ideas:\n- scale the input data before modelling (only X should be scaled, and Y needs to stay as is) \n- start training when the item is first sold (different timeframes for each items \/ store)\n- average price accross all items for each day to add to the calendar data (to account for nationwide promotions)\n- temperature and weather on each day (e.g. if raining, probably not much visits to the store -> fewer sales)\n\"\"\"\n#global variables\nT_predict = 28\nT_train = 30 #each sample will have 30 days of history (sales and daily data)\ntimeframe = 1*365 + 1 #we consider data from more than 1 year old is too outdated and useless in our modelling\nnodes_initial = 1000\ninitial_learning_param = 0.0004\nepoch_max = 50\ndrop_out = 0.01\n# batch_size = 1 #adding a batch doesn't seem helpful improving the model performance\n\ntest = False\ndef build_features_per_day(df_calendar, timeframe, T_predict, df_prices, dept, store, test=test):\n    '''\n    Create features based on the day, events and each item's price (for the ones in the dept and store)\n    '''\n    df_calendar_edited = calendar_data(df_calendar, timeframe, T_predict, test)\n    df_prices_limited = prices_data(df_prices, df_calendar_edited, dept, store)\n    df_daily_data = pd.merge(df_calendar_edited, df_prices_limited, left_on='wm_yr_wk', right_index=True)\n    df_daily_data = df_daily_data.drop('wm_yr_wk', axis=1)\n    \n    return df_daily_data\n\n\ndef calendar_data(df_calendar, timeframe, T_predict, test):\n    '''\n    Builds the calendar data\n    '''\n    if test:\n        df_calendar_edited = df_calendar.iloc[-timeframe-2*T_predict:-T_predict].copy() ###FOR TESTING COMPARED TO VALIDATION SET\n    else:\n        df_calendar_edited = df_calendar.iloc[-timeframe-T_predict:].copy() ###FOR FINAL EVALUATION\n\n    #one hot encoding on the weekday and event_type_1 (because few values but these should be interesting for high spending days)\n    list_col_one_hot = ['weekday', 'event_type_1']\n    list_drop_or_not = [True, False] #removes one of the weekday to avoid multicollinearity later on\n    for col_one_hot,drop_or_not in zip(list_col_one_hot,list_drop_or_not):\n        df_calendar_edited = pd.concat([df_calendar_edited, pd.get_dummies(df_calendar_edited[col_one_hot], prefix=col_one_hot, drop_first=drop_or_not)], axis=1)\n\n    df_calendar_edited = df_calendar_edited.set_index('d')\n\n    list_col_calendar_keep = ['wm_yr_wk']\n    for col_to_add in list_col_one_hot:\n        list_col_keep_encoded = [col for col in df_calendar_edited.columns if col_to_add in col and col!=col_to_add]\n        list_col_calendar_keep += list_col_keep_encoded\n\n    df_calendar_edited = df_calendar_edited[list_col_calendar_keep]\n    \n    return df_calendar_edited\n\n\ndef prices_data(df_prices, df_calendar_edited, dept, store):\n    '''\n    Builds the pricing data\n    '''\n    #define the prices for each of the weeks\n    df_prices_limited = df_prices[df_prices['wm_yr_wk'].isin(df_calendar_edited['wm_yr_wk'].unique())].copy()\n    df_prices_limited['dept_id'] = df_prices_limited['item_id'].astype(str).str[:-4]\n    df_prices_limited = df_prices_limited[(df_prices_limited['dept_id'] == dept) & (df_prices_limited['store_id'] == store)]\n\n    #get the price for each item on each week in the separated one-hot encoded columns\n    df_prices_limited = pd.concat([df_prices_limited, pd.get_dummies(df_prices_limited[\"item_id\"], prefix=\"\")], axis=1)\n\n    list_col_items_encoded = [col for col in df_prices_limited.columns if col.startswith('_')]\n    for col_item_encoded in list_col_items_encoded:\n        df_prices_limited[col_item_encoded] *= df_prices_limited[\"sell_price\"]\n\n    #remove duplicate weeks\n    df_prices_limited = df_prices_limited[list_col_items_encoded + [\"wm_yr_wk\"]].groupby(\"wm_yr_wk\").sum()\n    \n    return df_prices_limited\n\"\"\"\n## Modeling\n\nSimple FFN (Feed-Forward Network) \n\"\"\"\ndef approach3(df_train_full, df_sample_submission_original=df_sample_submission_original, df_calendar=df_calendar, \\\n              df_prices=df_prices, T_predict=T_predict, T_train=T_train, timeframe=timeframe, \\\n              nodes_initial=nodes_initial, initial_learning_param=initial_learning_param, epoch_max=epoch_max, drop_out=drop_out, \\\n             test=test):\n    '''\n    For each department+store combination (70 groups), get the data input, train a model and edit the submission file for this group\n    Note: we predict T_predict (default=28) days based on samples of T_train (default=365) days from all items\n    '''\n    \n    list_unique_dept_id = list(df_train_full['dept_id'].unique())\n    list_unique_store_id = list(df_train_full['store_id'].unique())\n\n    submission_grouped = df_sample_submission_original.set_index('id')\n    \n    counter = 1\n    for dept in list_unique_dept_id:\n        for store in list_unique_store_id:\n#     for dept, store in zip([list_unique_dept_id[3]], [list_unique_store_id[2]]):\n            print(\"counter:\", counter, \" - DEPARTMENT, STORE:\", dept, store)\n            df_daily_data = build_features_per_day(df_calendar, timeframe, T_predict, df_prices, dept, store)\n            df_train_limited = df_train_full[(df_train_full['dept_id'] == dept) & (df_train_full['store_id'] == store)]\n            \n            submission_grouped = approach_per_store(df_train_limited, submission_grouped, df_daily_data, \\\n                                                    T_predict, T_train, timeframe, nodes_initial, initial_learning_param, \\\n                                                    epoch_max, drop_out, test)\n            counter += 1\n    \n    if test:\n        ###FOR TESTING COMPARED TO VALIDATION SET        \n        get_evaluation(submission_grouped, df_train_full, df_calendar, df_prices)\n    else:\n        #add the numbers for the validation part (in case the evaluation is also based on these values)\n        submission_grouped.iloc[:30490,:] = df_train_full.iloc[:,-T_predict:].values\n        \n    return submission_grouped\n\n\ndef approach_per_store(df_train_limited, submission_grouped, df_daily_data, T_predict, T_train, timeframe, \\\n                       nodes_initial, initial_learning_param, epoch_max, drop_out, test):\n    \n    '''\n    Get the department+store input data, train the model, then predict for the next 28 days and edit the submission\n    '''\n    \n    if test:\n        df_train_grouped = df_train_limited.set_index(\"id\").iloc[:, 5:-28] ###FOR TESTING COMPARED TO VALIDATION SET\n    else:\n        df_train_grouped = df_train_limited.set_index(\"id\").iloc[:, 5:] ###FOR FINAL EVALUATION\n    \n    samples = timeframe - T_train\n    \n    X_reshaped, Y, in_dim, out_dim = make_input_data(df_train_grouped, df_daily_data, samples, timeframe)\n    history, model = build_train_model(X_reshaped, Y, in_dim, out_dim, nodes_initial, initial_learning_param,epoch_max,drop_out)\n    \n    #fill in the evaluation part in the submission file\n    submission_grouped = build_validation_predictions_per_dept_store(model, df_train_grouped, df_daily_data, \\\n                                                                     timeframe, T_train, T_predict, submission_grouped)\n    \n    return submission_grouped\n\n\ndef make_input_data(df_train_grouped, df_daily_data, samples, timeframe):\n    '''\n    Get model input data for the store+department group\n    Sales and days data are combined together the model input\n    '''\n    \n    X_reshaped = []\n    X_part1_sales = []\n    X_part2_days = []\n    Y = []\n\n    for col_index in range(samples):\n        \n        #first type of data: item sales\n        sales_array = df_train_grouped.iloc[:, -(timeframe - col_index):-(samples - col_index)].to_numpy()\n        output_sales_array = df_train_grouped.iloc[:, -(samples - col_index)].to_numpy()\n\n        #second type of data: daily data\n        day_data_array = df_daily_data.iloc[col_index + 1 : col_index + 1 + T_train + 1].transpose().to_numpy()\n        \n        #concatenate both inputs and reshape so that the ML model can handle it\n        concatenation_input_array = np.concatenate([sales_array.reshape(-1),day_data_array.reshape(-1)])\n\n        X_reshaped.append(concatenation_input_array)\n        Y.append(output_sales_array)\n\n    X_reshaped = np.stack(X_reshaped, axis=0)\n    Y = np.stack(Y, axis=0)\n    in_dim = X_reshaped.shape[1]\n    out_dim = Y.shape[1]\n    \n    return X_reshaped, Y, in_dim, out_dim\n\n\ndef build_train_model(X_reshaped, Y, in_dim, out_dim, nodes_initial, initial_learning_param, epoch_max, drop_out):\n    '''\n    Build a model based on the department+store group of data\n    Simple FFN, with a minor dropout to prevent overfitting (the model doesn't overfit much as its capacity is relatively low)\n    '''\n    \n    model = tf.keras.models.Sequential([\n        tf.keras.layers.Dense(nodes_initial, activation='relu', input_dim=in_dim),\n        tf.keras.layers.Dropout(drop_out),\n        tf.keras.layers.Dense(nodes_initial, activation='relu'),\n        tf.keras.layers.Dense(out_dim)\n    ])\n\n    optimizer_model = tf.keras.optimizers.Adam(initial_learning_param)\n    model.compile(loss = 'mse', optimizer = optimizer_model)\n\n    #train model\n    history = model.fit(X_reshaped, Y,epochs=epoch_max)\n    \n    return history, model\n\n\ndef get_evaluation(submission_grouped, df_train_full, df_calendar, df_prices):\n    '''\n    When testing the model, edit the submission file so that the validation rows are the same as the evaluation rows\n    We then use the existing public leaderboard (as it was before the validation data was released) to get the predicted ranking\n    '''\n    \n    #NEEDS TO EDIT submission_grouped (now we edit the \"evaluation\" index and the \"validation\" one needs to be edited to get the evaluation)\n    submission_grouped_full = submission_grouped.copy()\n    submission_grouped_full.iloc[:30490,:] = submission_grouped_full.iloc[30490:,:].values\n    submission_grouped_full.reset_index(inplace=True)\n    \n    #get current ranking (to change when building the final submission)\n    evaluator = WRMSSEEvaluator(df_train_full.iloc[:, :-28], df_train_full.iloc[:, -28:], df_calendar, df_prices)\n    get_ranking_from_submission(submission_grouped_full, evaluator)\n    \n    return None\n\n\ndef build_validation_predictions_per_dept_store(model, df_train_grouped, df_daily_data, timeframe, T_train, T_predict, submission_grouped):\n    '''\n    Edit the submission file based on the predictions for the department and store group\n    '''\n    \n    validation_predictions = predictions(model, df_train_grouped, df_daily_data, timeframe, T_train, T_predict)\n    \n    #update submission (i.e. output file)\n    submission_grouped.loc[df_train_grouped.index,:] = validation_predictions.transpose()\n    \n    return submission_grouped\n\n\ndef predictions(model, df_train_grouped, df_daily_data, timeframe, T_train, T_predict):\n    '''\n    Build predictions arrays based on the model (day by day)\n    Note: we need to roll the T_predict (default=30 days) predicted arrays for both the sales data and the daily data\n    '''\n    \n    validation_predictions = []\n\n    #initialize sales data\n    rolling_sales_data = df_train_grouped.iloc[:, -T_train:].to_numpy().astype(float)\n\n    for prediction_day in range(1,T_predict+1):\n        # prediction_day = 1\n        #prediction_day = 1 is for d_1914, all the way to prediction_day = T_predict (default = 28) for d_1941\n\n\n        #daily data: simple index change\n        rolling_day_data = df_daily_data.iloc[timeframe - T_train + 1 + prediction_day - 2: \\\n                                              timeframe + 1 + prediction_day -1].transpose().to_numpy()\n\n        X_input_for_prediction = np.concatenate([rolling_sales_data.reshape(-1),rolling_day_data.reshape(-1)]).reshape(1,-1)\n\n        p = model.predict(X_input_for_prediction)[0]\n        p[p<0] = 0\n\n        # update the predictions list\n        validation_predictions.append(p)\n\n        #sales data: need to roll using the predicted next day's sales data\n        rolling_sales_data = np.roll(rolling_sales_data.transpose(), -1, axis=0).transpose()\n        rolling_sales_data.transpose()[-1] = p\n\n    validation_predictions = np.stack(validation_predictions, axis=0)\n\n    return validation_predictions\nsubmission_final = approach3(df_train_full)\n# submission_final.to_csv(\"submission_M5_20200620_v2.csv\")\n\"\"\"\n# Other approaches tried:\n\n- item by item: too time-consuming without even using daily data (about 9h to compute with a simple FFN)\n- all items together (not grouping by store and department) with a simple FFN: too memory-heavy and lower performance\n- custom LSTM model (please see below): too time-consuming and lower performance\n    - Past sales -> go through an initial cell: simple RNN or LSTM\n    - The output of 1. and the array of next day data together with the array of price data -> go through a FFN\n    - The output of 2. -> goes through a final Dense layer to predict the next day sales for all items in the group\n\n\"\"\"\ndef make_input_data(df_train_grouped, df_daily_data, samples, timeframe):\n    '''\n    We have 2 inputs to our model, one X_main going through a LSTM cell, the other X_day going through a standard Dense layer\n    The model output to predict is Y\n    '''\n    \n    #get model input data\n    X_main = []\n    X_day = []\n    Y = []\n\n    for col_index in range(samples):\n        # col_index = 335 ###THIS IS JUST FOR TESTING (within the make_input_data function)\n\n        #first type of data: item sales\n        sales_array = df_train_grouped.iloc[:, -(timeframe - col_index):-(samples - col_index)].to_numpy()\n        output_sales_array = df_train_grouped.iloc[:, -(samples - col_index)].to_numpy()\n\n        #second type of data: daily data\n        day_data_array = df_daily_data.iloc[col_index,:].to_numpy()\n        \n        #concatenate both inputs and reshape so that the ML model can handle it\n#         concatenation_input_array = np.concatenate([sales_array.reshape(-1),day_data_array.reshape(-1)])\n        \n        #reshape input sales array\n#         reshape_input_array = sales_array.reshape(-1)\n\n        X_main.append(sales_array)\n        X_day.append(day_data_array)\n        Y.append(output_sales_array)\n\n    X_main = np.stack(X_main, axis=0)\n    X_day = np.stack(X_day, axis=0)\n    Y = np.stack(Y, axis=0)\n    in_dim_main = (X_main.shape[1], X_main.shape[2])\n    in_dim_day = X_day.shape[1]\n    out_dim = Y.shape[1]\n    \n    return X_main, X_day, Y, in_dim_main, in_dim_day, out_dim\n\n\ndef custom_recurrent_model(in_dim_main, in_dim_day, out_dim, nodes_initial):\n    '''\n    Custom LSTM model\n    X_main goes through an LSTM cell\n    X_day goes through a Dense layer\n    Then join together through another Dense layer\n    Then output array\n    '''\n    \n    X_main = Input(in_dim_main)\n    X_day = Input((in_dim_day,))\n    \n    #use recursive model on X_main\n    X_main_edited = LSTM(nodes_initial, dropout=drop_out, recurrent_dropout=drop_out)(X_main)\n    \n    #use a simple Dense layer on the daily data\n    X_day_edited = Dense(nodes_initial, activation = 'relu')(X_day)\n    \n    #combine the two X\n    X = Add()([X_main_edited, X_day_edited])\n    X = Activation('relu')(X)\n    \n    #add another FFN\n    X = Dense(nodes_initial, activation = 'relu')(X)\n    \n    #add one final layer for the output (regression)\n    X = Dense(out_dim)(X)\n    \n    model = Model(inputs=[X_main, X_day], outputs=X, name=\"Custom Reccurent Model\")\n    \n    return model\n\"\"\"\n# Final Ranking:\n- Private LB Score: 0.72949\n- Private LB Rank: 729 \/ 5558 (top 14%)\n\n\n# Evolution of public rankings (for reference)\n\n\n## 1. All items together\n\ndrop_out = 0.2\n- Public LB Score: 1.72354\n- Public LB Rank: 4209\n\ndrop_out = 0.1\n- Public LB Score: 1.35338\n- Public LB Rank: 4103\n\n## 2. Grouped items by store and department\n\ndrop_out = 0.01, learning_rate = 0.0004, per group, 200 nodes\n- Public LB Score: 0.9927\n- Public LB Rank: 3673\n\nadding daily data and increasing capacity (1000 nodes, 50 epochs, no batch size)\n- Public LB Score: 0.85322\n- Public LB Rank: 3546\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4cc2d7ca645412'}"}
{"id":"67158","text":"\"\"\"\n# Import Library\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n# Prepare Traning Data\n\"\"\"\nfilenames = os.listdir(\"..\/input\/train\/train\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\ndf.head()\n\"\"\"\n# See sample image\n\"\"\"\nsample = random.choice(filenames)\nimage = load_img(\"..\/input\/train\/train\/\"+sample)\nplt.imshow(image)\n\"\"\"\n# Build Model\n[Reference](https:\/\/blog.keras.io\/building-powerful-image-classification-models-using-very-little-data.html)\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(256, 256, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# the model so far outputs 3D feature maps (height, width, features)\n\nmodel.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors\nmodel.add(Dense(64))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.summary()\n\"\"\"\n### Prepare Test and Train Data\n\"\"\"\ntrain_df, validate_df = train_test_split(df, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()\n\n# validate_df = validate_df.sample(n=10).reset_index() # use for fast testing code purpose\n# train_df = train_df.sample(n=100).reset_index() # use for fast testing code purpose\n\ntotal_train = train_df.shape[0]\nbatch_size=15\n\"\"\"\n# Traning Generator\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n    horizontal_flip=True,\n    rescale=1.\/255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    rotation_range=20\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"..\/input\/train\/train\/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    batch_size=batch_size\n)\n\"\"\"\n### Validation Generator\n\"\"\"\nvalidation_datagen = ImageDataGenerator(rescale = 1.\/255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"..\/input\/train\/train\/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    batch_size=batch_size\n)\n\"\"\"\n# See sample generated images\n\"\"\"\nplt.figure(figsize=(12, 12))\nfor X_batch, y_batch in train_generator:\n    for i in range(0, 9):\n        plt.subplot(3, 3, i+1)\n        image = X_batch[i]\n        plt.imshow(image)\n    plt.tight_layout()\n    plt.show()\n    break\n\"\"\"\n# Fit Model\n\"\"\"\nmodel.fit_generator(\n    train_generator, \n    epochs=30,\n    validation_data=validation_generator,\n    steps_per_epoch=total_train\/\/batch_size\n)\n\"\"\"\n# Save Model\n\"\"\"\nmodel.save_weights(\"model.h5\")\n\"\"\"\n# Prepare Testing Data\n\"\"\"\ntest_filenames = os.listdir(\"..\/input\/test1\/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\n# test_df = test_df.sample(n=10).reset_index() \nnb_samples = test_df.shape[0]\n\n\"\"\"\n# Create Testing Generator\n\"\"\"\ntest_gen = ImageDataGenerator(rescale=1.\/255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"..\/input\/test1\/test1\/\", \n    x_col='filename',\n    class_mode=None,\n    batch_size=batch_size,\n    shuffle=False\n)\n\"\"\"\n# Predict\n\"\"\"\npredict = model.predict_generator(test_generator, steps=np.ceil(nb_samples\/batch_size)).astype('int64')\ntest_df['category'] = predict\nsample_test = test_df.sample(n=9).reset_index()\nsample_test.head()\nplt.figure(figsize=(12, 12))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\"..\/input\/test1\/test1\/\"+filename, target_size=(256, 256))\n    plt.subplot(3, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')')\nplt.tight_layout()\nplt.show()\n\"\"\"\n# Submission\n\"\"\"\nsubmission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '7bb71ed72acc70'}"}
{"id":"534","text":"# 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\n\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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nfrom sklearn.linear_model import ElasticNet, Lasso,  BayesianRidge, LassoLarsIC\nfrom sklearn.ensemble import RandomForestRegressor,  GradientBoostingRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom sklearn.pipeline import make_pipeline\nPATH = \"..\/input\/tabular-playground-series-jan-2021\/\"\ntrain = pd.read_csv(f\"{PATH}train.csv\",index_col='id')\ntest = pd.read_csv(f\"{PATH}test.csv\",index_col='id')\nsubmission= pd.read_csv(f\"{PATH}sample_submission.csv\",index_col='id')\n\"\"\"\n# Removing outliers\n\n\"\"\"\nfrom scipy import stats\nz = np.abs(stats.zscore(train))\ntrain = train[(z < 3).all(axis=1)]\n\"\"\"\n# Base Models\n\"\"\"\ntrain_c = train.copy()\nX = train_c.iloc[:,:-1].values\ny = train_c.iloc[:,14].values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10,random_state=0)\n\"\"\"\n# Model Stacking\n\n****\n\"\"\"\n\"\"\"\n# XGBoost Regressor\n\n\"\"\"\nmodel_xgb = xgb.XGBRegressor()\n\nmodel_xgb.fit(X_train, y_train, early_stopping_rounds=7, eval_set=[(X_test, y_test)], verbose=1)\n\n\nmodel_xgb_pred = model_xgb.predict(X_test)\nscore_reg = mean_squared_error(y_test, model_xgb_pred, squared=False)\nxgb_pred=model_xgb.predict(test.values)\nprint(f'{score_reg:0.5f}')\n\"\"\"\n# LGBM Regressor\n\n\"\"\"\nmodel_lgb = lgb.LGBMRegressor()\nmodel_lgb.fit(X_train, y_train, early_stopping_rounds=10, eval_set=[(X_test, y_test)], verbose=1)\nmodel_lgb_pred =model_lgb.predict(X_test)\nscore_reg = mean_squared_error(y_test, model_lgb_pred, squared=False)\nlgb_pred=(model_lgb.predict(test.values))\nprint(f'{score_reg:0.5f}')\nmodel_lgb.feature_importances_\ndef rmsle(y, y_pred):\n    mean_squared_error(y, y_pred,squared=False)\n    return print(f'{score_reg:0.5f}')\nprint('RMSLE score on train data:')\nprint(mean_squared_error(y_test, 0.75*model_lgb_pred+0.25*model_xgb_pred, squared=False))\nxgb_pred=model_xgb.predict(test.values)\nlgb_pred=model_lgb.predict(test.values)\nensemble = 0.75*lgb_pred+0.25*xgb_pred\nsubmission['target'] = ensemble\nsubmission.to_csv('model_lgb_xgb.csv')","meta":"{'source': 'AI4Code', 'id': '01045a83643121'}"}
{"id":"114866","text":"\"\"\"\n# Chances of Admission\n\n![](https:\/\/images.pexels.com\/photos\/2566121\/pexels-photo-2566121.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940)\n\nThis is a simple notebook that intends to implement a multiple linear regression model on the features described by the [graduate-admissions dataset](https:\/\/www.kaggle.com\/mohansacharya\/graduate-admissions), in order to predict the probability of admission for the student with said features. The features are GRE Score, TOEFL Score, University Rating, Statement of Purpose and Letter of Recommendation Strength, Undergraduate GPA, Research Experience, and Chance of Admit (all of them quantitative).\n\"\"\"\n\"\"\"\n## Exctacting and checking the data\n\"\"\"\n# 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 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\n\"\"\"\nChoosing the most recent version (1.1)\n\"\"\"\nadmission_df = pd.read_csv('\/kaggle\/input\/graduate-admissions\/Admission_Predict_Ver1.1.csv')\nadmission_df.head()\n\"\"\"\nCleaning column names and dropping the unnecessary \"Serial No.\" column\n\"\"\"\nadmission_df.columns\nadmission_df = admission_df.rename(columns = {'LOR ': 'LOR', 'Chance of Admit ': 'Chance of Admit'}).drop(['Serial No.'], axis = 1)\nadmission_df.columns\n\"\"\"\nChecking for null values\n\"\"\"\nadmission_df.isna().any()\n\"\"\"\nNo null values found. Operating normally\n\"\"\"\n\"\"\"\n## Linear regression\n\nMultiple linear regression is implemented for all features\n\"\"\"\nimport statsmodels.api as sm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\n\nX = admission_df.drop(['Chance of Admit'], axis = 1)\ny = admission_df[['Chance of Admit']]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\nlinear_regression = sm.OLS(y_train, sm.add_constant(X_train)).fit()\n\ny_predict = linear_regression.predict(sm.add_constant(X_test))\n\nprint('R2: ', r2_score(y_test, y_predict))\n\"\"\"\nThe correlation coefficient seems good enough for this model. Proceeding with an example regression prediction\n\"\"\"\nlinear_regression.params\n\"\"\"\nPredicting an entry with the following feature values:\n\nGRE Score: 280  \nTOEFL Score: 100  \nUniversity Rating: 3  \nStatement of Purpose: 3  \nLetter of Recommendation Strength: 5  \nUndergraduate GPA: 9  \nResearch Experience: None (0)  \n\"\"\"\ndef calculate_prediction(gre, toefl, uni_rating, sop, lor, cgpa, research):\n    X_test = [gre, toefl, uni_rating, sop, lor, cgpa, research]\n    \n    result = linear_regression.params[0]\n    \n    for i, x in enumerate(X_test):\n        result += linear_regression.params[i+1] * x\n    \n    return result\n\n\nprediction = calculate_prediction(280, 100, 3, 3, 5, 9, 0)\n\nprint(f'This candidate\\'s chance of being admitted is of {prediction*100:.2f} %')","meta":"{'source': 'AI4Code', 'id': 'd31770d37d3895'}"}
{"id":"12920","text":"# 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\n\"\"\"\n**Importing Libraries**\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n# import warnings filter\nfrom warnings import simplefilter\n# ignore all future warnings\nsimplefilter(action='ignore', category=FutureWarning)\n\"\"\"\n**Loading Dataset**\n\"\"\"\ntrain = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/train.csv')\ntrain.head(5)\ntest = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/test.csv')\ntest.head(2)\nsub = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/sample_submission.csv')\nsub.head(2)\n\"\"\"\n**Shape of Dataset**\n\"\"\"\ntrain.shape\n\"\"\"\n**Looking on some stastical data**\n\"\"\"\ntrain.describe()\n\"\"\"\n**Summary of DataFrame**\n\"\"\"\ntrain.info()\n\"\"\"\n**Checking Missing Values**\n\"\"\"\ntrain.isnull().sum()\n\"\"\"\n**Handling Categorical fetures**\n\"\"\"\ntrain['target'] = train['target'].map({'Class_1':1,'Class_2':2,'Class_3':3,'Class_4':4})\ntrain.head(2)\n\"\"\"\n**Drop Unnecessary Column**\n\"\"\"\ntrain.drop(['id'],axis=1, inplace=True)\ntest.drop(['id'],axis=1, inplace=True)\n\"\"\"\n**Checking Distribution of Dataset**\n\"\"\"\n# let's see how data is distributed for every column\nplt.figure(figsize=(20,25), facecolor='white')\nplotnumber = 1\n\nfor column in train:\n    if plotnumber<= 52:\n        ax = plt.subplot(8,7,plotnumber)\n        sns.distplot(train[column])\n        plt.xlabel(column,fontsize=20)\n    plotnumber+=1\nplt.tight_layout()\n\"\"\"\n**Separting Dependent and Independent column**\n\"\"\"\nX = train.drop(['target'], axis=1)\ny = train['target']\nX.head(2)\n\"\"\"\n**Handling Imbalanced Data**\n\"\"\"\ny.value_counts()\nfrom imblearn.combine import SMOTETomek\nfrom imblearn.under_sampling import NearMiss\n# Implementing Oversampling for Handling Imbalanced \nsmk = SMOTETomek(random_state=42)\nX_res,y_res=smk.fit_resample(X,y)\ny_res.value_counts()\nX_ros.drop(['feature_19','feature_30','feature_31','feature_32','feature_35','feature_38','feature_39','feature_42'], axis=1, inplace=True)\ntest.drop(['feature_19','feature_30','feature_31','feature_32','feature_35','feature_38','feature_39','feature_42'], axis=1, inplace=True)\nX_res.shape\ny.shape\n\"\"\"\n**RandomOverSampler to handle imbalanced data**\n\"\"\"\nfrom imblearn.over_sampling import RandomOverSampler\nos =  RandomOverSampler()\nX_ros, y_ros = os.fit_resample(X, y)\ny_ros.value_counts()\n\"\"\"\n**Under Sampling**\n\"\"\"\nfrom imblearn.under_sampling import NearMiss\nns=NearMiss()\nX_ns,y_ns=ns.fit_resample(X,y)\ny_ns.value_counts()\n\"\"\"\n**Some Other Feature Engineering**\n\"\"\"\nX_res.head(2)\ncol = X_res.columns\nX_res.nunique()\n\"\"\"\n**Feature Selection Using ExtraTreesClassifier**\n\"\"\"\nfrom sklearn.ensemble import ExtraTreesClassifier\nimport matplotlib.pyplot as plt\nmodel=ExtraTreesClassifier()\nmodel.fit(X,y)\nprint(model.feature_importances_)\nranked_features=pd.Series(model.feature_importances_,index=X.columns)\nranked_features.nlargest(10).plot(kind='barh')\nplt.show()\nranked_features.sort_values(ascending=False)\ntemp = []\nfor i in ranked_features.index:\n  if ranked_features[i] > 0.02:\n    temp.append(i)\ndf = X[temp]\ndf.head(2)\ndf_test = test[temp]\ndf_test.head(2)\n\"\"\"\n**Feature Selection using mutual_info_classif**\n\"\"\"\nfrom sklearn.feature_selection import mutual_info_classif\nmutual_info=mutual_info_classif(X,y)\nmutual_data=pd.Series(mutual_info,index=X.columns)\nmutual_data.sort_values(ascending=False)\ntemp = []\nfor i in mutual_data.index:\n  if mutual_data[i] != 0:\n    temp.append(i)\ndf = X[temp]\ndf.head(2)\n\"\"\"\n**Applying PCA**\n\"\"\"\nfrom sklearn.decomposition import PCA\npca = PCA()\nprincipalComponents = pca.fit_transform(X_ros)\nplt.figure()\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('Number of Components')\nplt.ylabel('Variance (%)') #for each component\nplt.title('Explained Variance')\nplt.show()\npca = PCA(n_components=30)\nnew_data = pca.fit_transform(X_ros)\n# This will be the new data fed to the algorithm.\nprincipal_Df = pd.DataFrame(data = new_data)\nprincipal_Df.head(2)\ntest_data = pca.transform(test)\n# This will be the new data fed to the algorithm.\nprincipal_Df_test = pd.DataFrame(data = test_data)\nprincipal_Df_test.head()\n\"\"\"\n**Splitting Dataset into Train and Validation set**\n\"\"\"\n### Only for ANN training\nY = pd.get_dummies(y)\nY.shape\n# Create Train & Test Data\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, y_train, y_val = train_test_split(principal_Df, y_ros, test_size=0.2, random_state=1)  ### Change y with \"Y\" while ANN training\n\"\"\"\n**Standard Scaling**\n\"\"\"\n# Standard Scaling\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_train_scaled = scaler.fit_transform(X_train)\nX_val_scaled = scaler.transform(X_val)\n\"\"\"\n**Robust Scaling**\n\"\"\"\nfrom sklearn.preprocessing import RobustScaler\nscaler = RobustScaler()\nX_train_scaled = scaler.fit_transform(X_train)\nX_val_scaled = scaler.transform(X_val)\n\"\"\"\n**Quantile Transformer**\n\"\"\"\nfrom sklearn.preprocessing import QuantileTransformer\nscaler = QuantileTransformer()\nX_train_scaled = scaler.fit_transform(X_train)\nX_val_scaled = scaler.transform(X_val)\ntest_scaled = scaler.transform(principal_Df_test)\n\"\"\"\n**Importing all Classification Model**\n\"\"\"\n!pip install catboost\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score,confusion_matrix, classification_report\nfrom sklearn.preprocessing import LabelEncoder\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom scipy.stats import randint\nfrom sklearn.model_selection import GridSearchCV\nfrom lightgbm import LGBMClassifier\nfrom imblearn.ensemble import EasyEnsembleClassifier\nclassifiers = [['DecisionTree :',DecisionTreeClassifier()],\n               ['RandomForest :',RandomForestClassifier()], \n               ['Naive Bayes :', GaussianNB()],\n               ['KNeighbours :', KNeighborsClassifier()],\n#                ['SVM :', SVC()],\n#                ['Neural Network :', MLPClassifier()],\n               ['LogisticRegression :', LogisticRegression()],\n               ['ExtraTreesClassifier :', ExtraTreesClassifier()],\n               ['AdaBoostClassifier :', AdaBoostClassifier()],\n               ['GradientBoostingClassifier: ', GradientBoostingClassifier()],\n               ['XGB :', XGBClassifier()],\n               ['LGBM :',LGBMClassifier(objective='multiclass', random_state=5)],\n               ['Easy :',EasyEnsembleClassifier()],\n               ['CatBoost :', CatBoostClassifier(logging_level='Silent')]]\n\npredictions_df = pd.DataFrame()\npredictions_df['actual_labels'] = y_val\n\nfor name,classifier in classifiers:\n    classifier = classifier\n    classifier.fit(X_train_scaled, y_train)\n    predictions = classifier.predict(X_val_scaled)\n    predictions_df[name.strip(\" :\")] = predictions\n    print(name, accuracy_score(y_val, predictions))\nETC = XGBClassifier(tree_method = 'gpu_hist')\nETC.fit(X_train_scaled, y_train)\npredictions = ETC.predict(X_val_scaled)\nprint(\"Accuracy :\", accuracy_score(y_val, predictions))\nprint(\"Confusion Matrix :\", confusion_matrix(y_val, predictions))\nprint(\"Classification :\", classification_report(y_val, predictions))\nfrom sklearn.metrics import log_loss\ny_pred = sclf.predict_proba(X_val_scaled)\nlog_loss(y_val, y_pred)\ny_pred = sclf.predict_proba(test_scaled)\n\"\"\"\n**Hyperparameter Tuning**\n\"\"\"\ngrid = {'max_depth': [3,4,5,7,9],'n_estimators':[100, 200, 300,400, 500],'learning_rate':[0.001,0.01,0.1]}\ngscv = GridSearchCV (estimator = Cat, param_grid = grid, scoring ='accuracy', cv = 5)\ngscv.fit(X_train_scaled, y_train)\nprint(gscv.best_params_)\ntuned_model = CatBoostClassifier(learning_rate= 0.1, max_depth= 5, n_estimators= 300, task_type = \"GPU\",verbose=True)\ntuned_model.fit(X_train_scaled, y_train)\npredictions = tuned_model.predict(X_val_scaled)\naccuracy_score(y_val, predictions)\nADB = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0,max_depth=1, random_state=0)\nXGB = XGBClassifier()\n# ADB.fit(X_train_scaled, y_train)\n# predictions = ADB.predict(X_val_scaled)\n# accuracy_score(y_val, predictions)\n\"\"\"\n**Stacking**\n\"\"\"\n# stacking\nfrom mlxtend.classifier import StackingClassifier\nXGB = XGBClassifier(tree_method = 'gpu_hist')\nRFC = RandomForestClassifier()\nETC = ExtraTreesClassifier()\nsclf=StackingClassifier(classifiers=[RFC,ETC], use_probas=True, meta_classifier=XGB)\nsclf.fit(X_train_scaled, y_train)\npredictions = sclf.predict(X_val_scaled)\naccuracy_score(y_val, predictions)\n\"\"\"\n**Bagging**\n\"\"\"\nfrom sklearn.ensemble import BaggingClassifier\nCat = CatBoostClassifier(verbose=False, task_type = \"GPU\")\nbag_xgb = BaggingClassifier(Cat,\n                            n_estimators=200, max_samples=0.5,\n                            bootstrap=True, random_state=0,oob_score=True, n_jobs=-1)\nbag_xgb.fit(X_train_scaled, y_train)\npredictions = bag_xgb.predict(X_val_scaled)\naccuracy_score(y_val, predictions)\nfrom sklearn.metrics import log_loss\ny_pred = bag_xgb.predict_proba(X_val_scaled)\nlog_loss(y_val, y_pred)\ny_pred = bag_xgb.predict_proba(test_scaled)\nsubmission_cat = pd.DataFrame(y_pred, columns=['Class_1','Class_2','Class_3','Class_4'])\nsubmission_cat['id'] = sub['id']\nsubmission_cat.to_csv('.\/result.csv', index=None)\n\"\"\"\n**Model training using ANN**\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nX_train_scaled.shape\ny_train.shape\ny_val.shape\nmodel = keras.models.Sequential([ \n    keras.layers.Dense(activation=\"relu\", input_dim=50, units=32, kernel_initializer=\"uniform\"),\n    keras.layers.Dense(activation=\"relu\", units=64, kernel_initializer=\"uniform\"),    \n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(activation=\"relu\", units=128, kernel_initializer=\"uniform\"),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(activation=\"relu\", units=256, kernel_initializer=\"uniform\"),\n    keras.layers.Dense(activation=\"softmax\", units=4, kernel_initializer=\"uniform\")\n])\nmodel.summary()\nepochs = 50\nopt = Adam()\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\nhistory = model.fit(X_train_scaled, y_train, batch_size=32, epochs=epochs, validation_data=(X_val_scaled,y_val))\n# summarizing historical accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\ny_pred = model.predict(test)\nsub = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/sample_submission.csv')\nsub[['Class_1','Class_2','Class_3','Class_4']] = y_pred\nsub.head(10)\nsub.to_csv('.\/result.csv', index=None)","meta":"{'source': 'AI4Code', 'id': '17958b40d2ddd6'}"}
{"id":"90335","text":"\"\"\"\n# Libraries\n\"\"\"\n# Use the official tokenization script created by the Google team\n!wget --quiet https:\/\/raw.githubusercontent.com\/tensorflow\/models\/master\/official\/nlp\/bert\/tokenization.py\nimport tensorflow as tf\nimport timeit\n\ndevice_name = tf.test.gpu_device_name()\nif \"GPU\" not in device_name:\n    print(\"GPU device not found\")\nprint('Found GPU at: {}'.format(device_name))\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport tensorflow_hub as hub\n\nimport tokenization\n\n# text processing libraries\nimport re\nimport string\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nfrom sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold, learning_curve\n\n# sklearn \nfrom sklearn import model_selection\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import f1_score, accuracy_score\nfrom sklearn import preprocessing, decomposition, model_selection, metrics, pipeline\nfrom sklearn.model_selection import GridSearchCV,StratifiedKFold,RandomizedSearchCV\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier, GradientBoostingClassifier\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom sklearn.svm import SVC\n\n## scrapping\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\n\n# matplotlib and seaborn for plotting\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\n \nimport warnings\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_rows', 5000)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 10000)\n!pip install tokenization\n\"\"\"\n# Load and Prepare Data\n\"\"\"\n#Training data\ntrain = pd.read_excel('..\/input\/fixed-bdc\/Data BDC - Satria Data 2020\/Data Latih\/Data Latih BDC.xlsx')\nprint('Training data shape: ', train.shape)\ntrain.head()\n# Testing data \ntest = pd.read_excel('..\/input\/fixed-bdc\/Data BDC - Satria Data 2020\/Data Uji\/Data Uji BDC.xlsx')\nprint('Testing data shape: ', test.shape)\ntest.head()\ntrain['text'] = train['judul'] + ' ' + train['narasi']\ntest['text'] = test['judul'] + ' ' + test['narasi']\ntrain_ = train.drop(columns=['ID', 'tanggal', 'text', 'narasi', 'nama file gambar'])\ntest_ = test.drop(columns=['ID', 'tanggal', 'text', 'narasi', 'nama file gambar'])\n\nprint(train_.head())\nprint(test_.head())\n\"\"\"\n# EDA\n\"\"\"\n#Missing values in training set\ntrain_.isnull().sum()\n#Missing values in test set\ntest_.isnull().sum()\ntrain_['label'].value_counts()\n\"\"\"\n# Data Preprocessing\n\"\"\"\n# take copies of the data to leave the originals for BERT\ntrain1 = train_.copy()\ntest1 = test_.copy()\n\"\"\"\n## Scraping\n\"\"\"\n# url = ['https:\/\/turnbackhoax.id\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/2\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/3\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/4\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/5\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/6\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/7\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/8\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/9\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/10\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/11\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/12\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/13\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/14\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/15\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/16\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/17\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/18\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/19\/?s=%5Bbenar%5D',\n#        'https:\/\/turnbackhoax.id\/page\/20\/?s=%5Bbenar%5D',\n#       ]\n# session = requests.Session()\n# vectorizer = TfidfVectorizer()\n# corpus = []\n# term_doc_mtx = None\n# sub='read'\n# links_url = []\n# for u in url:\n#     res = session.get(u)\n#     soup = BeautifulSoup(res.content, 'html.parser')\n#     for a in soup.find_all('a', {\"rel\": \"bookmark\"}):\n#          links_url.append(a.get_text().strip())\n# for x in links_url:\n#     x.replace('[BENAR] ','')\n# new_set = {x.replace('[BENAR] ','') for x in links_url}\n# new_set\n# corpus_df = pd.DataFrame(new_set, columns=['judul'])\n# corpus_df['label'] = 0\n# corpus_df = corpus_df[[\"label\", \"judul\"]]\n# df\n\"\"\"\n### Scrapping's Result\n\"\"\"\ntambah = pd.read_csv('..\/input\/judul-clean\/judul_clean.csv', sep=None)\ndisplay(tambah.head(10))\ntambah.shape\ntrain1.shape\ntrain1 = train1.append(tambah)\ntrain1.shape\ntrain1['label'].value_counts()\n\"\"\"\n**Data cleaning:** In summary, we want to tokenize our text then send it through a round of cleaning where we turn all characters to lower case, remove brackets, URLs, html tags, punctuation, numbers, etc. We'll also remove emojis from the text and remove common stopwords. This is a vital step in the Bag-of-words + linear model\n\"\"\"\n# emoji removal\ndef remove_emoji(text):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    return emoji_pattern.sub(r'', text)\n\n# Applying the de=emojifying function to both test and training datasets\nn = 'judul'\ntrain1[n] = train1[n].apply(lambda x: remove_emoji(x))\ntest1[n] = test1[n].apply(lambda x: remove_emoji(x))\n# Applying a first round of text cleaning techniques\n\ndef clean_text(text):\n    '''Make text lowercase, remove text in square brackets,remove links,remove punctuation\n    and remove words containing numbers.'''\n    text = text.lower() # make text lower case\n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    text = re.sub('\\n', '', text) # remove words conatinaing numbers\n    text = re.sub('\\w*\\d\\w*', '', text)\n    text = re.sub('[\u2018\u2019\u201c\u201d\u2026]', '', text)\n    text = re.sub(r'(\\w)\\1{2,}', r'\\1', text) # remove repeated char\n\n\n    return text\ntrain1.head()\n# text preprocessing function\ndef text_preprocessing(text):\n    \"\"\"\n    Cleaning and parsing the text.\n\n    \"\"\"\n    tokenizer_reg = nltk.tokenize.RegexpTokenizer(r'\\w+')\n    \n    nopunc = clean_text(text)\n    tokenized_text = tokenizer_reg.tokenize(nopunc)\n    remove_stopwords = [w for w in tokenized_text if w not in stopwords.words('indonesian')]\n    combined_text = ' '.join(remove_stopwords)\n    return combined_text\n\n# Applying the cleaning function to both test and training datasets\ntrain1[n] = train1[n].apply(lambda x: text_preprocessing(x))\ntest1[n] = test1[n].apply(lambda x: text_preprocessing(x))\n\n# Let's take a look at the updated text\ntrain1[n].head()\ntrain1.head()\n!pip install sastrawi\nfrom Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory\n\nfactory = StopWordRemoverFactory()\nstopword = factory.get_stop_words()\nstopword.append('yg')\nstopword.append('dengan')\nstopword.append('ia')\nstopword.append('bahwa')\nstopword.append('oleh')\nstopword.append('jadi')\nstopword.append('yth')\nstopword.append('nya')\nstopword.append('dengan')\nstopword.append('dgn')\nstopword.append('dlm')\n#stopword.append('indonesia')\n#stopword.append('orang')\n#stopword.append('tersebut')\n#stopword.append('semua')\nprint(stopword)\ndef remove_stopwords(text, stem=False):\n    tokens = []\n    for token in text.split():\n        if token not in stopword:\n            tokens.append(token)\n    return \" \".join(tokens)\n\ntrain1['stop'] = train1[n].apply(lambda x: remove_stopwords(x))\ntest1['stop'] = test1[n].apply(lambda x: remove_stopwords(x))\nprint('Original text:',train.narasi[1399])\nprint('After Stopwords Removal:',train1.stop[1399])\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nfactory = StemmerFactory()\nstemmer = factory.create_stemmer()\ntrain1['stop'] = train1['stop'].apply(lambda x: stemmer.stem(x))\ntest1['stop'] = test1['stop'].apply(lambda x: stemmer.stem(x))\n\n'''for index, row in train['translate'].iteritems():\n    stem = stemmer.stem(row) #detecting each row\n    train.loc[index, 'stem'] = stem'''\ntrain1.head()\n\"\"\"\n## Remove Duplicates Using Doc2Vec\n\"\"\"\n# gensim modules\nfrom gensim import utils\nfrom gensim.models.doc2vec import LabeledSentence\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom gensim.models import doc2vec\nfrom gensim.test.utils import common_texts\nfrom nltk.tokenize import word_tokenize\nfrom random import shuffle\n\n%%time\n\n## tagged_data for train set\ntagged_data = [TaggedDocument(words=word_tokenize(_d), tags=[str(i)]) for i, _d in enumerate(train1['stop'])]\n## tagged_data for test set\ntagged_data_test = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(test1['stop'])]\n\n## Training Model (PV-DM)\nmax_epochs = 100\nvec_size = 20\nalpha = 0.025\n\n## MODEL FOR TRAIN SET\nmodel = Doc2Vec(size=vec_size,\n                alpha=alpha, \n                min_alpha=0.00025,\n                min_count=1,\n                dm =1)\n  \nmodel.build_vocab(tagged_data)\n\nfor epoch in range(max_epochs):\n    model.train(tagged_data,\n                total_examples=model.corpus_count,\n                epochs=model.iter)\n    # decrease the learning rate\n    model.alpha -= 0.0002\n    # fix the learning rate, no decay\n    model.min_alpha = model.alpha\n    \n\n## MODEL FOR TEST SET\nmodel_test = Doc2Vec(size=vec_size,\n                alpha=alpha, \n                min_alpha=0.00025,\n                min_count=1,\n                dm =1)\n  \nmodel_test.build_vocab(tagged_data_test)\n\nfor epoch in range(max_epochs):\n    model_test.train(tagged_data_test,\n                total_examples=model_test.corpus_count,\n                epochs=model_test.iter)\n    # decrease the learning rate\n    model_test.alpha -= 0.0002\n    # fix the learning rate, no decay\n    model_test.min_alpha = model_test.alpha\n\n# model.save(\"d2v.model\")\n# model_test.save(\"d2v.model\")\n# print(\"Model Saved test\")\n# model= Doc2Vec.load(\".\/d2v.model\")\n# model_test = Doc2Vec.load(\".\/d2v.model_test\")\n\"\"\"\n### Checking Duplicates using Doc2Vec Similarity for train set\n\"\"\"\nduplicat_index = list()\ndouble = list()\ncount = 0\nfor i in range(4231):\n    similar_doc = model.docvecs.most_similar(str(i))\n    if (similar_doc[0][1] > 0.98):\n#         print(tagged_data[i])\n#         print(tagged_data[int(similar_doc[0][0])])\n#         print(similar_doc[0][1])\n        if int(similar_doc[0][0]) not in double: \n            duplicat_index.append(int(similar_doc[0][0]))\n            double.append(int(tagged_data[i][1][0]))\n#         print()\n\n\"\"\"\n### Checking Duplicates using Doc2Vec Similarity for test set\n\"\"\"\nduplicat_index_test = list()\ndouble_test = list()\nfor i in range(len(test1['judul'])):\n    similar_doc = model_test.docvecs.most_similar(str(i))\n    if (similar_doc[0][1] > 0.98):\n#         print(tagged_data[i])\n#         print(tagged_data[int(similar_doc[0][0])])\n#         print(similar_doc[0][1])\n        if int(similar_doc[0][0]) not in double: \n            duplicat_index_test.append(int(similar_doc[0][0]))\n            double_test.append(int(tagged_data[i][1][0]))\n#         print()\ntrain_ori = train1.copy()\ntrain1 = train1[~train1.index.isin(duplicat_index)]\n\n# test_ori = test1.copy()\n# test1 = test1[~test1.index.isin(duplicat_index_test)]\ntrain1.shape, train_ori.shape\ndup_index = train_ori.shape[0] - train1.shape[0]\n# dup_index_test = test_ori.shape[0] - test1.shape[0]\n\nduplicat_percentage = round( dup_index \/ train_ori.shape[0] * 100, 2)\nprint(f'train data has {dup_index} rows that duplicates, that means {duplicat_percentage} percent of the total')\n\n# duplicat_percentage_test = round( dup_index_test \/ test_ori.shape[0] * 100, 2)\n# print(f'test data has {dup_index_test} rows that duplicates, that means {duplicat_percentage_test} percent of the total')\n\"\"\"\n# Counting\n\n\nWe are going to see the diversity of data. How much emoji did train and test set contain? How many symbols & punctuation did train and test set contains? if they have the same proportion that means the train and test set has the same diversity. Also, we use wordcloud to check if the most frequent words are similar between train and test set.\n\"\"\"\n\"\"\"\n**Note : We use train and test set which have not been preprocessed to calculate the proportions**\n\"\"\"\n\"\"\"\n## Cek Emoji\n\"\"\"\ncolumn = 'narasi'\n\nhave_emoji_train_idx = []\nhave_emoji_test_idx = []\n\nfor idx,text in enumerate(train[column]):\n    before = text \n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    after = emoji_pattern.sub(r'', text)\n    if before != after:\n        have_emoji_train_idx.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\n\n\nfor idx,text in enumerate(test[column]):\n    before = text \n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    after = emoji_pattern.sub(r'', text)\n    if before != after:\n        have_emoji_test_idx.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\n\ntrain_emoji_percentage = round(len(have_emoji_train_idx) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(have_emoji_train_idx)} rows that used emoji, that means {train_emoji_percentage} percent of the total ({column})')\n\ntest_emoji_percentage = round(len(have_emoji_test_idx) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(have_emoji_test_idx)} rows that used emoji, that means {test_emoji_percentage} percent of the total ({column})')\n\"\"\"\n## Lower Case\n\"\"\"\nlower_train = list()\nlower_test  = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    before = text\n    after = text.lower() \n\n    if before != after:\n        lower_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    before = text\n    after = text.lower() \n\n    if before != after:\n        lower_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\ntrain_lower_percentage = round(len(lower_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(lower_train)} rows that contains upper case, that means {train_lower_percentage} percent of the total ({column})')\n\ntest_lower_percentage = round(len(lower_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(lower_test)} rows that contains upper case, that means {test_lower_percentage} percent of the total ({column})')\n\"\"\"\n## Square Brackets\n\"\"\"\nsquare_brackets_train = list()\nsquare_brackets_test  = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    before = text\n    after = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    if before != after:\n        square_brackets_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\n\n\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    before = text\n    after = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    if before != after:\n        square_brackets_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nsquare_brackets_percentage = round(len(square_brackets_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(square_brackets_train)} rows that used square_brackets, that means {square_brackets_percentage} percent of the total ({column})')\n\nsquare_brackets_percentage = round(len(square_brackets_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(square_brackets_test)} rows that used square_brackets, that means {square_brackets_percentage} percent of the total ({column})')\n\"\"\"\n## URLs\n\"\"\"\nurls_train = list()\nurls_test  = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    before = text\n    after = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    if before != after:\n        urls_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\n\n\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    before = text\n    after = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    if before != after:\n        urls_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nurls_train_percentage = round(len(urls_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(urls_train)} rows that contains urls, that means {urls_train_percentage} percent of the total ({column})')\n\nurls_test_percentage = round(len(urls_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(urls_test)} rows that contains urls, that means {urls_test_percentage} percent of the total ({column})')\n\"\"\"\n## Html tags\n\"\"\"\nhtml_train = list()\nhtml_test = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    before = text\n    after = re.sub('<.*?>+', '', text) # remove html tags\n    if before != after:\n        html_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    before = text\n    after = re.sub('<.*?>+', '', text) # remove html tags\n    if before != after:\n        html_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nhtml_train_percentage = round(len(html_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(html_train)} rows that contains html tags, that means {html_train_percentage} percent of the total ({column})')\n\nhtml_test_percentage = round(len(html_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(html_test)} rows that contains html tags, that means {html_test_percentage} percent of the total ({column})')\n\"\"\"\n## Punctuation\n\"\"\"\npunc_train = list()\npunc_test = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    before = text\n    after = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    if before != after:\n        punc_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    before = text\n    after = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    if before != after:\n        punc_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\npunc_train_percentage = round(len(punc_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(punc_train)} rows that contains punctuation, that means {punc_train_percentage} percent of the total ({column})')\n\npunc_test_percentage = round(len(punc_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(punc_test)} rows that contains punctuation, that means {punc_test_percentage} percent of the total ({column})')\n\"\"\"\n## Numbers\n\"\"\"\nnum_train = list()\nnum_test = list()\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    before = text\n    text = re.sub('\\n', '', text) # remove words conatinaing numbers\n    text = re.sub('\\w*\\d\\w*', '', text)\n    after = re.sub('[\u2018\u2019\u201c\u201d\u2026]', '', text)\n    if before != after:\n        num_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    before = text\n    text = re.sub('\\n', '', text) # remove words conatinaing numbers\n    text = re.sub('\\w*\\d\\w*', '', text)\n    after = re.sub('[\u2018\u2019\u201c\u201d\u2026]', '', text)\n    if before != after:\n        num_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nnum_train_percentage = round(len(num_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(num_train)} rows that contains numbers, that means {num_train_percentage} percent of the total ({column})')\n\nnum_test_percentage = round(len(num_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(num_test)} rows that contains numbers, that means {num_test_percentage} percent of the total ({column})')\n\"\"\"\n## Repeated Char\n\"\"\"\nrepeat_train = list()\nrepeat_test = list()\n\nfor idx,text in enumerate(train[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    text = re.sub('\\n', '', text) # remove words conatinaing numbers\n    text = re.sub('\\w*\\d\\w*', '', text)\n    text = re.sub('[\u2018\u2019\u201c\u201d\u2026]', '', text)\n    before = text\n    after = re.sub(r'(\\w)\\1{2,}', r'\\1', text)\n    if before != after:\n        repeat_train.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nfor idx,text in enumerate(test[column]):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    text = text.lower() \n    text = re.sub('\\[.*?\\]', '', text) # remove text in square brackets\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text) # remove URLs\n    text = re.sub('<.*?>+', '', text) # remove html tags\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text) # remove punctuation\n    text = re.sub('\\n', '', text) # remove words conatinaing numbers\n    text = re.sub('\\w*\\d\\w*', '', text)\n    text = re.sub('[\u2018\u2019\u201c\u201d\u2026]', '', text)\n    before = text\n    after = re.sub(r'(\\w)\\1{2,}', r'\\1', text)\n    if before != after:\n        repeat_test.append(idx)\n#         print(before)\n#         print(after)\n#         print(idx)\n#         print()\nrepeat_train_percentage = round(len(repeat_train) \/ train.shape[0] * 100, 2)\nprint(f'train data has {len(repeat_train)} rows that contains repeated char, that means {repeat_train_percentage} percent of the total ({column})')\n\nrepeat_test_percentage = round(len(repeat_test) \/ test.shape[0] * 100, 2)\nprint(f'test data has {len(repeat_test)} rows that contains repeated char, that means {repeat_test_percentage} percent of the total ({column})')\n'''from wordcloud import WordCloud\nwc = WordCloud(\n    height=600,repeat=False,width=1400,max_words=1000,stopwords=stopword,\n    colormap='terrain',background_color='white',mode='RGBA'\n).generate(\n    ' '.join(train1['stop'].dropna().astype(str)))\nplt.figure(figsize = (16,16))\nplt.imshow(wc)\nplt.title('Judul Wordcloud')\nplt.axis('off')\nplt.show()'''\n\"\"\"\n# Models\n\nWe try two different approach : bow and tf-idf\n\nModels that we used are :\n1. Logistic Regression\n2. Random Forest\n3. Support Vector\n4. Xgboost\n5. Adaboost\n6. Extratree\n\"\"\"\n\"\"\"\n## Sparse Matrix\n\"\"\"\ncount_vectorizer = CountVectorizer(ngram_range = (1,2), min_df = 1)\ntrain_vectors = count_vectorizer.fit_transform(train1['stop'])\ntest_vectors = count_vectorizer.transform(test1[\"stop\"])\n\n## Keeping only non-zero elements to preserve space \ntrain_vectors.shape\ntfidf = TfidfVectorizer(ngram_range=(1, 2), min_df = 1)\ntrain_tfidf = tfidf.fit_transform(train1['stop'])\ntest_tfidf = tfidf.transform(test1[\"stop\"])\n\ntrain_tfidf.shape\n\"\"\"\n### Logreg\n\"\"\"\nfrom sklearn.model_selection import StratifiedKFold\n\n# Create a StratifiedKFold object\nskf = StratifiedKFold(n_splits=5, shuffle=False, random_state=42)\n%%time\nlogreg_bow = LogisticRegression()\n\nlogreg_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(logreg_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\nlogreg_tfidf = LogisticRegression()\nlogreg_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(logreg_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n### RF\n\"\"\"\n'''from scipy.stats import randint\nforest_clf = RandomForestClassifier()\nparam_distribs = {\n        'n_estimators': randint(low=100, high=300),\n        'max_features': randint(low=8, high=17),\n    }\n\nrnd_forest_clf = RandomizedSearchCV(forest_clf, param_distributions=param_distribs,\n                                n_iter=10, cv=skfold, scoring='f1', random_state=42)\nrnd_forest_clf.fit(train_vectors, train1[\"label\"])\n\n{'max_features': 15, 'n_estimators': 288}''' #malah turun\n%%time\n# Fitting a simple Random Forest on BoW\nRF_bow = RandomForestClassifier(n_estimators=288)\nRF_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(RF_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\n# Fitting a simple Random Forest on TFIDF\nRF_tfidf = RandomForestClassifier(n_estimators=288)\nRF_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(RF_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n### SVC\n\"\"\"\n%%time\nfrom sklearn.svm import SVC\n# Fitting a simple SVC on BoW\nSVC_bow = SVC(probability=True)\nSVC_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(SVC_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\n# Fitting a simple SVC on TFIDF\nSVC_tfidf = SVC(probability=True)\nSVC_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(SVC_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n### XGB\n\"\"\"\n%%time\nXGB_bow = XGBClassifier()\n\nXGB_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(XGB_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\n# Fitting a simple XGB on TFIDF\nXGB_tfidf = XGBClassifier()\nXGB_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(XGB_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n### Adaboost\n\"\"\"\n%%time\nfrom sklearn.tree import DecisionTreeClassifier\n# Fitting a simple AdaBoost on BoW\nada_bow = AdaBoostClassifier(\n                        base_estimator=DecisionTreeClassifier(\n                                                             max_depth=7,\n                                                             min_samples_leaf=5,\n                                                             min_samples_split=10,\n                                                             ),\n                   learning_rate=0.3, n_estimators=2, random_state=42)\nada_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(ada_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\n# Fitting a simple AdaBoost on TFIDF\nada_tfidf = AdaBoostClassifier(\n                        base_estimator=DecisionTreeClassifier(\n                                                             max_depth=5,\n                                                             min_samples_leaf=2,\n                                                             min_samples_split=3,\n                                                             ),\n                            learning_rate=0.3, n_estimators=2, random_state=42)\nada_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(ada_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n### Extra\n\"\"\"\n'''ext_clf = ExtraTreesClassifier()\nparam_grid = {\"max_depth\": [None],\n              \"max_features\": [10, 17],\n              \"min_samples_split\": [2, 3, 10],\n              \"min_samples_leaf\": [1, 3, 10],\n              \"bootstrap\": [False, True],\n              \"n_estimators\" :[50,100,200],\n              \"criterion\": [\"gini\"]}\n\n# Cross validate model with Kfold stratified cross val\nskfold = StratifiedKFold(n_splits=5)\ngrid_ext_clf = GridSearchCV(ext_clf,param_grid, cv=skfold, scoring=\"f1\", n_jobs= 4, verbose = 1)\ngrid_ext_clf.fit(train_vectors, train1[\"label\"])\n\ngrid_ext_clf.best_params_\n\n{'bootstrap': False,\n 'criterion': 'gini',\n 'max_depth': None,\n 'max_features': 17,\n 'min_samples_leaf': 1,\n 'min_samples_split': 2,\n 'n_estimators': 100}\n '''\n%%time\n# Fitting a simple Extra on BoW\next_bow = ExtraTreesClassifier(criterion='gini',\n                               max_features=17,\n                               n_estimators=100,\n                              )\next_bow.fit(train_vectors, train1[\"label\"])\nscores = model_selection.cross_val_score(ext_bow, train_vectors, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n%%time\n# Fitting a simple Extra on TFIDF \next_tfidf = ExtraTreesClassifier()\next_tfidf.fit(train_tfidf, train1[\"label\"])\nscores = model_selection.cross_val_score(ext_tfidf, train_tfidf, train1[\"label\"], cv=skf, scoring=\"f1\")\nscores.mean()\n\"\"\"\n## Cross Validations Analysis\n\"\"\"\n\"\"\"\n### Confusion Matrix\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import StratifiedKFold\ndef cm_analysis():\n    # splitter\n    SEED = 2020\n    f1 = []\n    tra_fold_df = []\n    val_fold_df = []\n    cm = []\n    skf = StratifiedKFold(n_splits=5, shuffle=False, random_state=SEED)\n    # models\n    models = [LogisticRegression(), RandomForestClassifier(n_estimators=288), SVC(probability=True),\n            XGBClassifier(), \n\n            AdaBoostClassifier(\n                base_estimator=DecisionTreeClassifier(max_depth=7, min_samples_leaf=5,min_samples_split=10,),\n                learning_rate=0.3, n_estimators=2, random_state=42),\n\n            ExtraTreesClassifier(criterion='gini',max_features=17,n_estimators=100,)]\n\n\n    for model in models:\n        label = {'mislabeled_1':0, 'true_1':0,'mislabeled_0':0,'true_0':0}\n        score = []\n        for tra_idx, val_idx in skf.split(train1, train1[['label']]):\n\n            X_tra = train1.iloc[tra_idx]\n            X_val = train1.iloc[val_idx]\n            tra_fold_df.append(X_tra)\n            val_fold_df.append(X_val)\n            y_tra = train1.iloc[tra_idx]['label']\n            y_val = train1.iloc[val_idx]['label']\n\n            #### IF YOU WANT YOU TO USE BOW UNCOMMENT THE CODE BELOW, AND THEN COMMENT THE TF-IDF CODE SECTION\n\n            ## BOW ##\n    #         count_vectorizer = CountVectorizer(ngram_range = (1,2), min_df = 1)\n    #         train_vectors = count_vectorizer.fit_transform(X_tra['stop'])\n    #         validasi_vectors = count_vectorizer.transform(X_val['stop']) \n\n            ## TF-IDF ##\n            tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df = 1)\n            train_vectors = tfidf.fit_transform(X_tra['stop'])\n            validasi_vectors = tfidf.transform(X_val[\"stop\"])\n\n            ## TRAINING AND PREDICT\n            model.fit(train_vectors,y_tra)\n            y_pred = model.predict(validasi_vectors)\n    #         print('For zero :',confusion_matrix(y_val, y_pred)[0])\n    #         print('For one :',confusion_matrix(y_val,y_pred)[1])\n\n\n            ## SAVE CM RESULT TO A DICT\n            label['true_0'] += confusion_matrix(y_val,y_pred)[0][0]\n            label['mislabeled_0'] += confusion_matrix(y_val,y_pred)[0][1]\n            label['true_1'] += confusion_matrix(y_val,y_pred)[1][1]\n            label['mislabeled_1'] += confusion_matrix(y_val,y_pred)[1][0]\n\n            ## SAVE THE F1_SCORE FOR EACH FOLD\n            score.append(f1_score(y_val,y_pred,average=None)[1])\n        cm_each = list()\n    #     print(f'f1_score_avg_none:',sum(score)\/5)\n        f1.append(sum(score)\/5)\n    #     print(label)\n        for key,value in label.items():\n    #         print(model,key,round(value\/5))\n            cm_each.append(round(value\/5))\n        cm.append(cm_each)\n\n    cm = pd.DataFrame(cm, columns = ['Mislabeled_1','True_1','Mislabeled_0','True_0'])\n    cm['Model'] = ['logreg','rf','svc','xgb','ada','ext']\n    cm.set_index('Model',inplace=True)\n    cm = cm.astype('int')\n    cm['f1_score'] = f1\n    display(cm.style.background_gradient(cmap='Blues'))\n    return\n\ncm_analysis()\n\"\"\"\n## Ensemble: Stacking\n\"\"\"\next_test_pred = ext_tfidf.predict_proba(test_vectors)[:,1]\nforest_test_pred = RF_tfidf.predict_proba(test_vectors)[:,1]\nxgb_test_pred = XGB_tfidf.predict_proba(test_vectors)[:,1]\n#dt_test_pred = dt_tfidf.predict_proba(test_vectors)[:,1]\nada_test_pred = ada_tfidf.predict_proba(test_vectors)[:,1]\nsvc_test_pred = SVC_tfidf.predict_proba(test_vectors)[:,1]\n#nb_test_pred = NB_tfidf.predict_proba(test_vectors)[:,1]\nlg_test_pred = logreg_tfidf.predict_proba(test_vectors)[:,1]\n\next_train_pred = ext_tfidf.predict_proba(train_vectors)[:,1]\nforest_train_pred = RF_tfidf.predict_proba(train_vectors)[:,1]\nxgb_train_pred = XGB_tfidf.predict_proba(train_vectors)[:,1]\n#dt_train_pred = dt_tfidf.predict_proba(train_vectors)[:,1]\nada_train_pred = ada_tfidf.predict_proba(train_vectors)[:,1]\nsvc_train_pred = SVC_tfidf.predict_proba(train_vectors)[:,1]\n#nb_train_pred = NB_tfidf.predict_proba(train_vectors)[:,1]\nlg_train_pred = logreg_tfidf.predict_proba(train_vectors)[:,1]\next_test_pred = ext_bow.predict_proba(test_vectors)[:,1]\nforest_test_pred = RF_bow.predict_proba(test_vectors)[:,1]\nxgb_test_pred = XGB_bow.predict_proba(test_vectors)[:,1]\n#dt_test_pred = dt_bow.predict_proba(test_vectors)[:,1]\nada_test_pred = ada_bow.predict_proba(test_vectors)[:,1]\nsvc_test_pred = SVC_bow.predict_proba(test_vectors)[:,1]\n#nb_test_pred = NB_bow.predict_proba(test_vectors)[:,1]\nlg_test_pred = logreg_bow.predict_proba(test_vectors)[:,1]\n\next_train_pred = ext_bow.predict_proba(train_vectors)[:,1]\nforest_train_pred = RF_bow.predict_proba(train_vectors)[:,1]\nxgb_train_pred = XGB_bow.predict_proba(train_vectors)[:,1]\n#dt_train_pred = dt_bow.predict_proba(train_vectors)[:,1]\nada_train_pred = ada_bow.predict_proba(train_vectors)[:,1]\nsvc_train_pred = SVC_bow.predict_proba(train_vectors)[:,1]\n#nb_train_pred = NB_bow.predict_proba(train_vectors)[:,1]\nlg_train_pred = logreg_bow.predict_proba(train_vectors)[:,1]\n\"\"\"\n## SAVING EACH MODEL\n\"\"\"\nimport pickle\n# save the model to disk\nrf_bow_model = 'rf_model.sav'\next_bow_model = 'ext_model.sav'\nXGB_bow_model = 'xgb_model.sav'\nada_bow_model = 'ada_model.sav'\nsvc_bow_model = 'svc_model.sav'\nlg_bow_model = 'lg_model.sav'\n\npickle.dump(RF_bow, open(rf_bow_model, 'wb'))\npickle.dump(ext_bow, open(ext_bow_model, 'wb'))\npickle.dump(XGB_bow, open(XGB_bow_model, 'wb'))\npickle.dump(ada_bow, open(ada_bow_model, 'wb'))\npickle.dump(SVC_bow, open(svc_bow_model, 'wb'))\npickle.dump(logreg_bow, open(lg_bow_model, 'wb'))\n\"\"\"\nSize for each model :\n- ext_model = 36.666 kb\n- xgb_model = 503 kb\n- lg_model = 220 kb\n- ada_model = 11 kb\n- rf_model = 37.345 kb\n\"\"\"\nbase_pred = pd.DataFrame({\n    'ext':ext_train_pred.ravel(),\n    'forest':forest_train_pred.ravel(), \n    'xgb':xgb_train_pred.ravel(), \n    'svc':svc_train_pred.ravel(),\n    'ada':ada_train_pred.ravel(),\n    #'lg':lg_train_pred.ravel(),\n    #'nb':nb_train_pred.ravel(),\n    #'dt':dt_train_pred.ravel()\n    \n})\n\ntest_pred = pd.DataFrame({\n    'ext':ext_test_pred.ravel(),\n    'forest':forest_test_pred.ravel(), \n    'xgb':xgb_test_pred.ravel(), \n    'svc':svc_test_pred.ravel(),\n    'ada':ada_test_pred.ravel(),\n    #'lg':lg_test_pred.ravel(),\n    #'nb':nb_test_pred.ravel(),\n    #'dt':dt_test_pred.ravel()\n})\n# Display numerical correlations between features on heatmap\nsns.set(font_scale=2.5)\ncorrelation_train = base_pred.corr()\nmask = np.triu(correlation_train.corr())\nplt.figure(figsize=(10, 10))\nsns_plot = sns.heatmap(correlation_train,\n            annot=True,\n            fmt='.1f',\n            cmap='coolwarm',\n            square=True,\n            mask=mask,\n            linewidths=1, alpha=1)\n\nplt.show()\nsns_plot.get_figure().savefig('tfidf.png',transparent=True)\n#grid={\"C\":np.logspace(-4,4,20), \"penalty\":[\"l1\",\"l2\"]}# l1 lasso l2 ridge\nfinal_model = LogisticRegression(C=0.012742749857031334, penalty='l2')\n#final_model=GridSearchCV(final_model,grid,cv=10)\nfinal_model.fit(base_pred, train1[\"label\"])\n#print(final_model.best_params_)\n\nscores = model_selection.cross_val_score(final_model, base_pred, train1[\"label\"], cv=5, scoring=\"f1\")\nprint('Cross Validation :', scores.mean())\n\n# make prediction using our test data and model\ny_pred = final_model.predict(base_pred)\nprint('')\nprint('###### Logreg Classifier ######')\n\n# evaluating the model\nprint(\"Testing Accuracy :\", accuracy_score(train1[\"label\"], y_pred))\n#print(\"Best Score :\", final_model.best_score_)\nprint('F1-Score :', metrics.f1_score(train1[\"label\"], y_pred))\n#print('Best Params :', final_model.best_params_)\n#print('Best Estimator', final_model.best_estimator_)\n\"\"\"\n## Prediction\n\"\"\"\ntest_read = pd.read_excel('..\/input\/fixed-bdc\/Data BDC - Satria Data 2020\/Data Uji\/Data Uji BDC.xlsx')\ntemplate = pd.read_csv('..\/input\/submission-bdc\/template jawaban BDC.csv')\nfinal_pred = final_model.predict(test_pred)\nsubmission = pd.DataFrame()\nsubmission[\"ID\"] = test_read[\"ID\"]\nsubmission[\"prediksi\"] = final_pred\nsubmission = pd.merge(template['ID'], submission)\nsubmission.to_csv(\"submission.csv\", index=False)\nsub = pd.read_csv('.\/submission.csv')\nsub.prediksi.value_counts()\nrf_pred = RF_bow.predict(test_vectors)\nrf_submit = pd.DataFrame()\nrf_submit[\"ID\"] = test_read[\"ID\"]\nrf_submit[\"prediksi\"] = rf_pred\nrf_submit = pd.merge(template['ID'], submission)\nrf_submit.to_csv(\"rf_submit.csv\", index=False)\nrf_sub = pd.read_csv('.\/rf_submit.csv')\nrf_sub.prediksi.value_counts()","meta":"{'source': 'AI4Code', 'id': 'a5ac7afa948dde'}"}
{"id":"103243","text":"\"\"\"\n### Step1: Import the necessary libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as stats\nimport statsmodels.stats.proportion as stats_pro\n%matplotlib inline\nsns.set(color_codes=True)\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\"\"\"\n### Step2: Read the data as a dataframe\n\"\"\"\ninsurance=pd.read_csv('\/kaggle\/input\/insurance\/insurance.csv')\ninsurance.head()\n\"\"\"\n### Step3: Perform basic EDA which should include the following and print out your insights at every step\n\"\"\"\n\"\"\"\n#### Step3a: Shape of the data\n\"\"\"\nshape_insurance=insurance.shape\nprint('The shape of the dataframe insurance is',shape_insurance,'which means there are',shape_insurance[0],'rows and',shape_insurance[1],'columns.')\n\"\"\"\n#### step 3b. Data type of each attribute\n\"\"\"\n#The data type be found through the info function\ninsurance.info()\n#The data type also be found through the dtype function\nprint('The data type of attribute age is',insurance['age'].dtype)\nprint('The data type of attribute sex is',insurance['sex'].dtype)\nprint('The data type of attribute bmi is',insurance['bmi'].dtype)\nprint('The data type of attribute children is',insurance['children'].dtype)\nprint('The data type of attribute smoker is',insurance['smoker'].dtype)\nprint('The data type of attribute region is',insurance['region'].dtype)\nprint('The data type of attribute charges is',insurance['charges'].dtype)\n\"\"\"\n#### step 3c. Checking the presence of missing values.<br>\n#### There are multiple ways to do it:\n##### 1. Referring the third column in the output of the info() command above. It is clear that there are no null values. Since the total rows are 1338 and all columns mention 1338 as non null values.\n##### 2. Another way to find missing values is leveraging the code isnull on the dataframe\n\"\"\"\nprint('The missing values in the dataframe Insurance are:','\\n',insurance.isnull().sum(),'\\n','which means there are no null values in the dataset')\n\"\"\"\n##### 3. Another way to find missing values is leveraging the code isnull on the individual column in the dataframe\n\"\"\"\n# Another way to find the missing values\nprint('The missing values in the attribute age are',insurance['age'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['sex'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['bmi'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['children'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['smoker'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['region'].isnull().sum())\nprint('The missing values in the attribute age are',insurance['charges'].isnull().sum())\n\n\"\"\"\n#### Step 3.d 5 point summary of numerical attributes.\n\"\"\"\ninsurance.describe().T\ninsurance_5pt=insurance.describe().loc[['min','25%','50%','75%','max'],['age','bmi','children','charges']].T\nprint('The 5 point summary of numerical attribute is:','\\n',insurance_5pt)\n\"\"\"\n1. The range of age is [18,64] with a median of 39. At this point, it doesnt appear that there are any outliars; we will try and confirm the same leveraging box plot.<br>\n2. The range of bmi is [15.96,53.13] with a median of 30.4. At this point, it doesnt appear that there are any outliars; we will try and confirm the same leveraging box plot. <br>\n3. The range of children in [0,5] with a median of 1. There are no values in the 25% percentile and median is 1 which seems to mean that there are few people with more than 2 children <br>\n4. The range of charges is [1121.8,63770.4] with a median of 9382. The difference between median and the maximum value is significant which might mean that there are potential outliars and potentially the data is skewed. We will try and confirm the same leveraging box plot and analysis of skewness.\n\"\"\"\n\"\"\"\n#### Step 3e Distribution of \u2018bmi\u2019, \u2018age\u2019 and \u2018charges\u2019 columns.\n\"\"\"\nplt.hist(insurance['bmi'])\nplt.xlabel('bmi')\nplt.ylabel('count')\nplt.title('Distribution of BMI')\nplt.show()\nplt.hist(insurance['age'])\nplt.xlabel('age')\nplt.ylabel('count')\nplt.title('Distribution of Age')\nplt.show()\nplt.hist(insurance['charges'])\nplt.xlabel('charges')\nplt.ylabel('count')\nplt.title('Distribution of Charges')\nplt.show()\n\"\"\"\n#### 3f. Measure of skewness of \u2018bmi\u2019, \u2018age\u2019 and \u2018charges\u2019 columns\n\"\"\"\nskewness_bmi=round(stats.skew(insurance['bmi']),4)\nskewness_age=round(stats.skew(insurance['age']),4)\nskewness_charges=round(stats.skew(insurance['charges']),4)\n\nprint(' The skewness of bmi is', skewness_bmi,'\\n','The skewness of age is',skewness_age,'\\n','The skewness of charges is',skewness_charges)\n\"\"\"\nbmi has less skewness<br>\nAge has negligent skewness<br>\nCharges seems highly skewed.\n\"\"\"\n\"\"\"\n#### 3g. Checking the presence of outliers in \u2018bmi\u2019, \u2018age\u2019 and \u2018charges columns'\n\"\"\"\nbmi_boxplot=sns.boxplot(insurance['bmi']);\nprint(' As seen in the previous step, skewness is very less for BMI', '\\n','checking if there are any outliars by ploting a box plot.','\\n' ,' As seen in the chart below,There are outliars on the right.','\\n')\nplt.show()\nage_boxplot=sns.boxplot(insurance['age']);\nprint(' As checked in the previous step, there is negligible skewness in age.', '\\n','Checking if there are any outliars by ploting a box plot.','\\n' ,'As seen in the chart below, there doesnt seem to be an outliar.')\nplt.show()\ncharges_boxplot=sns.boxplot(insurance['charges']);\nprint(' As seen in the above step, charges have high skewness.','\\n' ,'Checking if there are any outliars by ploting a box plot.',  '\\n' ,'There are outliars on the right.')\nplt.show()\n\"\"\"\n#### 3h. Distribution of categorical columns (include children) \n\"\"\"\n#The categorical columns are sex,smoker,region,children\n# Distribution of Sex\nsns.countplot(insurance['sex'])\nplt.xlabel('Gender')\nplt.ylabel('count')\nplt.title('Distribution of genders')\nplt.show()\n# Distribution of smoker\nsns.countplot(insurance['smoker'])\nplt.xlabel('smoker')\nplt.ylabel('count')\nplt.title('Distribution of smoker')\nplt.show()\n# Distribution of region\nsns.countplot(insurance['region'])\nplt.xlabel('region')\nplt.ylabel('count')\nplt.title('Distribution of region')\nplt.show()\n# Distribution of children\nsns.countplot(insurance['children'])\nplt.xlabel('children')\nplt.ylabel('count')\nplt.title('Distribution of children')\nplt.show()\n\"\"\"\n#### 3i. Pair plot that includes all the columns of the data frame\n\"\"\"\n#Pair plot doesnt contain display non numeric values. Hence, we will have to convert non numeric columns into numbers. \n#The non-numeric columns are sex, smoke and BMI.\ninsurance_pp=insurance.copy()\ninsurance_pp['sex']=insurance_pp['sex'].astype('category').cat.codes\ninsurance_pp['smoker']=insurance_pp['smoker'].astype('category').cat.codes\ninsurance_pp['region']=insurance_pp['region'].astype('category').cat.codes\nsns.pairplot(insurance_pp);\n\"\"\"\n1. There seem to be a co-relation between charges and age' since charges seems to increase as the age increases. There are few outliars though.\n2. Charges for smoker seem to be higher than non smokers.\n\"\"\"\n\"\"\"\n### 4. Answer the following questions with statistical evidence\n\"\"\"\n\"\"\"\n#### 4.a Do charges of people who smoke differ significantly from the people who don't?\n\"\"\"\n\"\"\"\nstep 1: state the null and alternate hypothesis <br>\nHo = Charges of people who smoke don't differ from the people who don't smoke <br>\nHa = Charges of people who smoke differ from the people who don't smoke\n\"\"\"\n\"\"\"\nstep 2: Decide the signification level <br>\nhere we select alpha = 0.05\n\"\"\"\n\"\"\"\nstep 3: Identify the test statistics <br>\nSince in this scenario, we are comparing 2 samples against each other. Hence we can use two sample t-test for this problem. \n\"\"\"\n\"\"\"\nstep 4: Calculate p value and t statistics\n\"\"\"\nid_smo_charges=np.array(insurance[['charges','smoker']])\nid_smo_charges\n## separating the charges paid by smokers and non-smokers\n\n# identify charges paid by smokers\nsmo_charges = id_smo_charges[:,1]=='yes'\nsmo_charges = id_smo_charges[smo_charges][:,0]\n\n# identify charges paid by non-smoker\nnon_smo_charges = id_smo_charges[:,1]=='no'\nnon_smo_charges = id_smo_charges[non_smo_charges][:,0]\nt_statistics, p_value = stats.ttest_ind(smo_charges,non_smo_charges)\nprint(t_statistics, p_value)\n# p_value < 0.05. Hence, the null hypothesis is rejected.\n# which means that the charges of people who smoke differ significantly from the people who don't smoke.\nprint(' Two sample t-test p-value',p_value, 'is significantly less than alpha (0.05).','\\n' ,'Hence the null hypothesis is rejected.','\\n','Therefore charges of people who smoke differ from charges of people who dont smoke')\n\"\"\"\n#### 4.b Does bmi of males differ significantly from that of females?\n\"\"\"\n\"\"\"\nStep 1: State the null and alternate hypothesis<br>\nNull Hypothesis Ho: BMI of males dont differ significantly from that of females <br>\nAlternate Hypothesis Ha: BMI of males differ significantly from that of females\n\"\"\"\n\"\"\"\nStep 2: Decide the significance level<br>\nFor this problem, the significance level (alpha) selected is 0.05\n\"\"\"\n\"\"\"\nStep 3: Identify the test statistics <br>\nSince in this problem. We are comparing 2 samples against each other. Hence, we can use 2 sample t-test for this problem.\n\"\"\"\n\"\"\"\nStep 4: Compute the test statistics and p value\n\"\"\"\nbmi_sex=np.array(insurance[['bmi','sex']])\nbmi_sex\nbmi_male=bmi_sex[:,1]=='male'\nbmi_male=bmi_sex[bmi_male][:,0]\nbmi_female=bmi_sex[:,1]=='female'\nbmi_female=bmi_sex[bmi_female][:,0]\nt_statistics, p_value = stats.ttest_ind(bmi_male,bmi_female)\nprint(t_statistics,p_value)\n# p-value is greater than alpha (0.05). Hence, we fail to reject the null hypothesis. \n\nprint(' Two sample t-test p-value is',round(p_value,6),'which is more than alpha (0.05).','\\n'' Hence, we fail to reject the null hypothesis; which means that gender has no effect on BMI.')\n\"\"\"\n#### 4.c Is the proportion of smokers significantly different in different genders?\n\"\"\"\n\"\"\"\nStep 1: Define the null hypothesis and alternate hypothesis <br>\nNull hypothesis Ho: proportion of smokers is not significantly different in different genders <br>\nAlternate hypothesis Ha: Proportion of smokers significantly different in different genders\n\"\"\"\n\"\"\"\nStep 2: Establish the significance level <br>\nFor this problem, the significance level selected is 0.05 (alpha = 0.05)\n\"\"\"\n\"\"\"\nStep 3: Identify the test statistics <br>\nSince in this problem, we are comparing proportion of 2 categorical samples. Hence, we can use test of proportion \n\"\"\"\n\"\"\"\nStep 4: Compute the test statistic and p-value\n\"\"\"\n# computing the number of males and females\nmale_count=insurance['sex'].value_counts()[0]\nfemale_count=insurance['sex'].value_counts()[1]\nprint(' The total number of males is',male_count,'\\n','The total number of females is',female_count)\n\n# computing the number of male and female smokers\nmale = insurance['sex']=='male'\nmale_smoker = insurance[male].smoker.value_counts()[1]\nfemale = insurance['sex']=='female'\nfemale_smoker = insurance[female].smoker.value_counts()[1]\nprint(' The male smoker count is',male_smoker,'\\n','The female smoker count is',female_smoker)\nprint(' The proportion of male smoker is',round(male_smoker\/male_count,4),'\\n','The proportion of female smoker is',round(female_smoker\/female_count,4))\ntest_statistics,p_value=stats_pro.proportions_ztest([male_smoker,female_smoker],[male_count,female_count])\n\ntest_statistics,p_value\n\nprint(' The p-value is',round(p_value,4),'which is significantly lower than alpha(0.05).','\\n' ,'Hence, the null hypothesis is rejected.','\\n','Therefore, the proportion of smokers differ significantly in genders.')\n\n\"\"\"\n#### 4.d Is the distribution of bmi across women with no children, one child and two children, the same?\n\"\"\"\n#plotting a bar graph to analyse the distribution of BMI\nsns.boxplot(data=insurance,x=\"children\",y=\"bmi\",hue=\"sex\");\nplt.title('Distribution of BMI')\nplt.show()\n\"\"\"\nReferring the graph, there are few outliars. However, it is difficult to deduce if the BMI across women with children 0,1,2 is the same or not. We will try to analyse this statistically\n\"\"\"\n\"\"\"\nStep 1: Establish the null hypothesis <br>\nNull hypothesis Ho= Distribution of bmi across women with no children, one child and two children is same. <br>\nAlternate hypothesis Ha= Distribution of bmi across women with no children, one child and two children is not same.\n\"\"\"\n\"\"\"\nStep 2: Define the significance level <br>\nFor this problem, the significance level selected is 0.05. Hence alpha = 0.05\n\"\"\"\n\"\"\"\nStep 3: Identify the test statistics <br>\nHere we have 3 groups; i.e. women with children 0,1,2 and we have to analyze whether the BMI for these 3 samples is same or not. Analysis of variance can determine whether the means of these 3 samples are same or different. Hence, the test statistics identified for this problem is One-way ANOVA\n\"\"\"\n\"\"\"\nStep 4: Compute the test statistics\n\"\"\"\n## in this step we will segregate BMI for all females by the number of children (0,1,2)\nbmi_sex=np.array(insurance[['sex','bmi','children']])\n#identify all females\nbmi_female=bmi_sex[bmi_sex[:,0]=='female']\n#bmi for females with 0 children\nz_bmi_female=bmi_female[bmi_female[:,2]==0][:,1]\n#bmifor females with 1 child\no_bmi_female=bmi_female[bmi_female[:,2]==1][:,1]\n#bmi for females with 2 children\nt_bmi_female=bmi_female[bmi_female[:,2]==2][:,1]\nf_stat,p_value=stats.f_oneway(z_bmi_female,o_bmi_female,t_bmi_female)\nprint('The statistics computed is',round(f_stat,4),'and the p-value computed is',round(p_value,4))\nprint(' The p-value is',round(p_value,4),', which is significantly larger than alpha(0.05).','\\n','Hence we fail to reject the null hypothesis.','\\n', 'Therefore, There is no significant evidence to conclude that BMI for women having 0,1 or 2 children is different.')","meta":"{'source': 'AI4Code', 'id': 'bdb627fba494e8'}"}
{"id":"55357","text":"\"\"\"\n![Ads\u0131z.png](attachment:5b9cfc51-041d-4cd4-ae0b-22d0ee4da3d6.png)\n\n<center><h1 style = \"background:black;color:white;border:0;border-radius:3px;font-family:Comic Sans MS\" >\ud83d\udcdc Introduction<\/h1><\/center>\n\n<p style = \"color:black;font-weight:500;text-indent:20px;font-size:16px;font-family:Comic Sans MS\">We will first analyze the data we have in a good way. We'll visualize it later. Then we will refine our model for training. Creating multiple models at once. We will compare the success of these models.<\/p>\n\n<h2 style = \"background:black;color:white;border:0;border-radius:3px;font-family:Comic Sans MS\">\ud83d\udccb Content :<\/h2>\n\n<ul>\n    <li style = \"color:darkgray;font-size:15px\"> <a href = \"#1\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Load and Check Data <\/a> <\/li>\n    <li style = \"color:darkgray;font-size:15px\"> <a href = \"#2\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Variable Description <\/a> <\/li>   \n    <li style = \"color:darkgray;font-size:15px\"> <a href = \"#3\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Basic Data Analysiss <\/a> <ul> \n        <li style = \"color:lightgray\"><a href = \"#4\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> fixed acidity - quality  <\/a><\/li> \n        <li style = \"color:lightgray\"><a href = \"#5\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> volatile acidity - quality <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#6\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> citric acid - quality <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#7\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> residual sugar - quality <\/a><\/li>\n                <li style = \"color:lightgray\"><a href = \"#8\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> chorides - quality <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#9\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> free sulfur dioxide - quality <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#10\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> total sulfur dioxide - quality <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#11\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> density - quality <\/a><\/li>\n                <li style = \"color:lightgray\"><a href = \"#12\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> pH - quality <\/a><\/li>\n                <li style = \"color:lightgray\"><a href = \"#13\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> sulphates - quality <\/a><\/li>\n                <li style = \"color:lightgray\"><a href = \"#14\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> alcohol - quality <\/a><\/li>\n        <\/ul>            \n    <li style = \"color:darkgray;font-size:15px\"> <a href = \"#15\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Missing Value  <\/a> <\/li>\n        <li style = \"color:darkgray;font-size:15px\"> <a href = \"#16\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Visualization <\/a> <ul> \n        <li style = \"color:lightgray\"><a href = \"#17\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> fixed acidity  <\/a><\/li> \n        <li style = \"color:lightgray\"><a href = \"#18\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> volatile acidity <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#19\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> citric acid <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#21\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> residual sugar <\/a><\/li>\n                <li style = \"color:lightgray\"><a href = \"#12\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> chorides <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#23\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> free sulfur dioxide <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#24\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\">total sulfur dioxide <\/a><\/li>\n                    <li style = \"color:lightgray\"><a href = \"#15\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> density <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#26\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\">pH <\/a><\/li>\n                    <li style = \"color:lightgray\"><a href = \"#27\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> sulphates <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#28\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\">alcohol <\/a><\/li>\n                    <li style = \"color:lightgray\"><a href = \"#29\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\">quality <\/a><\/li>\n<\/ul>   \n         <li style = \"color:darkgray;font-size:15px\"> <a href = \"#30\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Skewness Correction <\/a> <ul> \n         <li style = \"color:lightgray\"><a href = \"#31\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> fixed acidity  <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#32\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> residual sugar <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#33\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> free sulfur dioxide <\/a><\/li>\n        <li style = \"color:lightgray\"><a href = \"#34\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\">total sulfur dioxide <\/a><\/li>\n                    <li style = \"color:lightgray\"><a href = \"#35\" style = \"color:black;font-weight:500;font-family:Comic Sans MS\"> alcohol <\/a><\/li>\n<\/ul>  \n             <li style = \"color:darkgray;font-size:15px\"> <a href = \"#36\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Outlier Detection <\/a> <\/li>\n    <li style = \"color:darkgray;font-size:15px\"> <a href = \"#37\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Modeling   <\/a> <ul> <li style = \"color:lightgray\"><a href = \"#38\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\">Import Model Library <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#39\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\">Train - Test Split <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#40\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> Smote <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#41\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\">StandartScaler <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#42\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2460 KNeighborsClassifier <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#43\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2461 GradientBoostingClassifier <\/a><\/li> <li style = \"color:lightgray\"><a href = \"#44\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2462 SVC<\/a><\/li> <li style = \"color:lightgray\"><a href = \"#45\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2463 XGBClassifier<\/a><\/li> <li style = \"color:lightgray\"><a href = \"#46\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2464 CatBoostClassifier<\/a><\/li> <li style = \"color:lightgray\"><a href = \"#47\" style = \"background:white;color:brown;border:0;border-radius:3px;font-family:Impact;font-size:14px\"> \u2465 RandomForestClassifier<\/a><\/li> <\/ul>\n      <li style = \"color:darkgray;font-size:15px\"> <a href = \"#48\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Wrong Predictions <\/a> <\/li>\n        <li style = \"color:darkgray;font-size:15px\"> <a href = \"#49\" style = \"color:black;font-weight:bold;font-family:Comic Sans MS\"> Model Result <\/a> <\/li>\n<\/ul> \n\n\n\"\"\"\n\"\"\"\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS\">\ud83d\udcd6 Import Library<\/h2>\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn.metrics import plot_confusion_matrix\nfrom scipy.stats import norm, boxcox\nfrom collections import Counter\nfrom scipy import stats\n\n# warning library\nimport warnings\nwarnings.filterwarnings(\"ignore\")\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\n\"\"\"\n<a id ='1' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS\">Load and Check Data<\/h2>\n\"\"\"\ndata = pd.read_csv(\"\/kaggle\/input\/red-wine-quality-cortez-et-al-2009\/winequality-red.csv\")\ndata.head()\n# the columns \ndata.columns\nprint(\"Data Shape --> \",data.shape)\ndata.describe()\n\"\"\"\n<a id ='2' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Variable Description<\/h2>\n\n<ol>\n    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>fixed acidity : <\/strong> most acids involved with wine or fixed or nonvolatile (do not evaporate readily) <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>volatile acidity : <\/strong> the amount of acetic acid in wine, which at too high of levels can lead to an unpleasant, vinegar taste<\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>citric acid : <\/strong> found in small quantities, citric acid can add 'freshness' and flavor to wines<\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>residual sugar : <\/strong>the amount of sugar remaining after fermentation stops, it's rare to find wines with less than 1 gram\/liter and <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>chlorides : <\/strong>  the amount of salt in the wine <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>free sulfur dioxide : <\/strong> the free form of SO2 exists in equilibrium between molecular SO2 (as a dissolved gas) and bisulfite ion; it prevents <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>total sulfur dioxide : <\/strong> amount of free and bound forms of S02; in low concentrations, SO2 is mostly undetectable in wine, but at free SO2 <\/p> <\/li>\n    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>density : <\/strong>the density of water is close to that of water depending on the percent alcohol and sugar content <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>ph : <\/strong>  describes how acidic or basic a wine is on a scale from 0 (very acidic) to 14 (very basic); most wines are between 3-4 on the <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>sulphates : <\/strong> a wine additive which can contribute to sulfur dioxide gas (S02) levels, wich acts as an antimicrobial and <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>alcohol sulfur dioxide : <\/strong> the percent alcohol content of the wine <\/p> <\/li>\n            <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS\" > <strong>quality : <\/strong> output variable (based on sensory data, score between 0 and 10) <\/p> <\/li>\n<\/ol>\n\"\"\"\nprint(\"Data Info\")\ndata.info()\n\"\"\"\n<a id ='3' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Basic Data Analysis<\/h2>\n\n<p style = \"color:darkred;font-family:Comic Sans MS;font-weight:bold\" >In this section, we will look at how properties have an effect on the target variable.<\/p> \n\n<ul>\n    <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > fixed acidity - <strong>  quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > volatile acidity -<strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > citric acid - <strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > residual sugar - <strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > chlorides - <strong>  quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > free sulfur dioxide -<strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > total sulfur dioxide - <strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > density - <strong> quality <\/strong> <\/p> <\/li>  \n            <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > pH - <strong>  quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > sulphates -<strong> quality <\/strong> <\/p> <\/li>\n        <li style = \"color:darkgreen\"> <p style = \"color:black;font-family:Comic Sans MS\" > alcohol - <strong> quality <\/strong> <\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='4' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">fixed acidity - quality <\/h4>\n\"\"\"\ndata[[\"fixed acidity\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >We can say that the increase in fixed acidity positively affects the given vote.but it is difficult to make a full conclusion at this stage. <\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='5' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">volatile acidity - quality <\/h4>\n\"\"\"\ndata[[\"volatile acidity\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >here we can make a more precise sentence according to the comment we made above. The decrease in volatile acidity affects the votes positively.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='6' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">cidric acid - quality <\/h4>\n\"\"\"\ndata[[\"citric acid\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >From here, we see that the increase in citric acid positively affected the votes.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='7' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">residual sugar - quality <\/h4>\n\"\"\"\ndata[[\"residual sugar\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >It seems difficult to make an inference about residual sugar from here.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='8' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">chlorides - quality <\/h4>\n\"\"\"\ndata[[\"chlorides\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >The decrease in chlorides positively affects the votes cast.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='9' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">free sulfur dioxide - quality <\/h4>\n\"\"\"\ndata[[\"free sulfur dioxide\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >It doesn't seem easy to comment on free sulfur dioxide either. The 13, 14 levels seem to have been voted well.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='10' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">total sulfur dioxide - quality <\/h4>\n\"\"\"\ndata[[\"total sulfur dioxide\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >It doesn't make sense to comment on total sulfur dioxide. It changed according to the votes. There is no order.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='11' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">density - quality <\/h4>\n\"\"\"\ndata[[\"density\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >The intensity is almost the same in all votes, but there is only a slight decrease. Density drop seems to have a positive effect on the votes.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='12' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">pH - quality <\/h4>\n\"\"\"\ndata[[\"pH\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >We can say that the decrease in pH affects the votes positively.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='13' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">sulphates - quality<\/h4>\n\"\"\"\ndata[[\"sulphates\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >It is clear from here that the increase in sulphates has a positive effect.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='14' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">alcohol - quality<\/h4>\n\"\"\"\ndata[[\"alcohol\",\"quality\"]].groupby([\"quality\"], as_index = False).mean().sort_values(by = \"quality\").style.background_gradient(\"Reds\")\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print;font-weight:bold\" > <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >In general, it can be said that the increase in alcohol ratio affects the votes well.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='15' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Missing Value<\/h2>\n\n<p style = \"color:darkred;font-family:Comic Sans MS;font-weight:bold\" >We will take a look at if there is any missing data in our data. If there are, we will try to eliminate them.<\/p> \n\"\"\"\nprint(\"Do we have data with null in columns?\")\ndata.columns[data.isnull().any()]\ndata.isnull().sum()\n\"\"\"\n<ul>\n    <li style = \"color:darkred;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >we see that there is no missing data in the data.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='16' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Visualization<\/h2>\n\n<p style = \"color:darkgreen;font-family:Comic Sans MS;font-weight:bold\" >In this section, we will visualize our features one by one and make examinations on graphics.<\/p> \n\n<ul>\n    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > fixed acidity <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > volatile acidity <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >citric acid <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > residual sugar <\/p> <\/li>\n            <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >chlorides <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >free sulfur dioxide <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >total sulfur dioxide <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >density <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >pH <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >sulphates <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >alcohol <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >quality <\/p> <\/li>\n<\/ul> \n\"\"\"\n\"\"\"\n<a id ='17' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">fixed acidity<\/h4>\n\"\"\"\nquality = [3,4,5,6,7,8]\nfixedAcidityMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"fixed acidity\"].mean()\n    fixedAcidityMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"fixed acidity\"], color=\"orange\")\nplt.xlabel(\"fixed acidity\")\nplt.ylabel(\"Frequency\")\nplt.title(\"fixed acidity histogram\", color = \"black\", fontweight='bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"fixed acidity\"], fit=norm, color=\"orange\")\nplt.title(\"fixed acidity Distplot\", color = \"black\", fontweight='bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = fixedAcidityMean, palette=\"YlOrBr\")\nplt.title(\"the average value of fixed acidity by quality\", color = \"black\", fontweight='bold', fontsize = 11)\nplt.xlabel(\"fixed acidity\")\nplt.ylabel(\"Frequency\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"fixed acidity\"], palette='YlOrBr')\nplt.title(\"fixed acidity & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:orange;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >Fixed acidity may not have much effect on splitting votes.<\/p> <\/li>\n        <li style = \"color:orange;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >On the 2nd graph, we see that there is a skewness to the right. We need to fix this.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='18' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">volatile acidity<\/h4>\n\"\"\"\nvolatileAcidityMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"volatile acidity\"].mean()\n    volatileAcidityMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"volatile acidity\"], color=\"purple\")\nplt.xlabel(\"volatile acidity\")\nplt.ylabel(\"Frequency\")\nplt.title(\"volatile acidity histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"volatile acidity\"], fit=norm, color=\"purple\")\nplt.title(\"volatile acidity Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = volatileAcidityMean, palette= \"rocket\")\nplt.title(\"the average value of volatile acidity by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"volatile acidity mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"volatile acidity\"], palette='rocket')\nplt.title(\"volatile acidity & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:purple;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >The decrease in volatile acidity seems to affect the votes positively.<\/p> <\/li>\n        <li style = \"color:purple;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine the second graph, we see that the distribution is good.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='19' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">citric acid<\/h4>\n\"\"\"\ncitricAcidMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"citric acid\"].mean()\n    citricAcidMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"citric acid\"], color=\"lightgreen\")\nplt.xlabel(\"citric acid\")\nplt.ylabel(\"Frequency\")\nplt.title(\"citric acid histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"citric acid\"], fit=norm, color=\"green\")\nplt.title(\"citric acid Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = citricAcidMean, palette= \"Greens\")\nplt.title(\"the average value of citric acid by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"citric acid mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"citric acid\"], palette='Greens')\nplt.title(\"citric acid & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:darkgreen;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We can say that the increase in citric acid affects the votes positively.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='21' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">residual sugar<\/h4>\n\"\"\"\nresidualSugarMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"residual sugar\"].mean()\n    residualSugarMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"residual sugar\"], color=\"blue\")\nplt.xlabel(\"residual sugar\")\nplt.ylabel(\"Frequency\")\nplt.title(\"residual sugar histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"residual sugar\"], fit=norm, color=\"blue\")\nplt.title(\"residual sugar Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = residualSugarMean, palette= \"crest\")\nplt.title(\"the average value of residual sugar by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"residual sugar mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"residual sugar\"], palette='crest')\nplt.title(\"residual sugar & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:blue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >The estimate of residual sugar does not seem to have much effect.<\/p> <\/li>\n        <li style = \"color:blue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that there is a skewness towards the right according to the normal distribution.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='22' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">chlorides<\/h4>\n\"\"\"\nchloridesMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"chlorides\"].mean()\n    chloridesMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"chlorides\"], color=\"brown\")\nplt.xlabel(\"chlorides\")\nplt.ylabel(\"Frequency\")\nplt.title(\"chlorides histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"chlorides\"], fit=norm, color=\"brown\")\nplt.title(\"chlorides Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = chloridesMean, palette= \"Set2\")\nplt.title(\"the average value of chlorides by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"chlorides mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"chlorides\"], palette='Set2')\nplt.title(\"chlorides & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:yellow;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that the decrease in chlorides has a positive effect on the votes..<\/p> <\/li>\n        <li style = \"color:yellow;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >If we look at the fourth graph, we see that there are too many outliers. We need to fix these. Otherwise, they will negatively affect our model.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='23' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">free sulfur dioxide<\/h4>\n\"\"\"\nfreeSulfurDioxideMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"free sulfur dioxide\"].mean()\n    freeSulfurDioxideMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"free sulfur dioxide\"], color=\"darkred\")\nplt.xlabel(\"free sulfur dioxide\")\nplt.ylabel(\"Frequency\")\nplt.title(\"free sulfur dioxide histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"free sulfur dioxide\"], fit=norm, color=\"darkred\")\nplt.title(\"free sulfur dioxide Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = freeSulfurDioxideMean, palette= \"OrRd\")\nplt.title(\"the average value of free sulfur dioxide by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"free sulfur dioxide mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"free sulfur dioxide\"], palette='OrRd')\nplt.title(\"free sulfur dioxide & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:brown;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine the gariks here, we see that the graph is tailing to the right, we will correct this below.<\/p> <\/li>\n        <li style = \"color:brown;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >If we look at the fourth graph, we see that there are too many outliers. We need to fix these. Otherwise, they will negatively affect our model.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='24' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">total sulfur dioxide<\/h4>\n\"\"\"\ntotalSulfurDioxideMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"total sulfur dioxide\"].mean()\n    totalSulfurDioxideMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"total sulfur dioxide\"], color=\"#F1E68C\")\nplt.xlabel(\"total sulfur dioxide\")\nplt.ylabel(\"Frequency\")\nplt.title(\"total sulfur dioxide histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"total sulfur dioxide\"], fit=norm, color=\"#F5E68C\")\nplt.title(\"total sulfur dioxide Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = totalSulfurDioxideMean, palette= \"BrBG\")\nplt.title(\"the average value of total sulfur dioxide by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"total sulfur dioxide mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"total sulfur dioxide\"], palette='BrBG')\nplt.title(\"total sulfur dioxide & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:#F1E68C;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine these graphs, we do not see that they have a regular effect on the target variable. It is not easy to draw conclusions.<\/p> <\/li>\n        <li style = \"color:#F1E68C;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >Here we see a skewness to the right.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='25' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">density<\/h4>\n\"\"\"\ndensityMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"density\"].mean()\n    densityMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"density\"], color=\"lightblue\")\nplt.xlabel(\"density\")\nplt.ylabel(\"Frequency\")\nplt.title(\"density histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"density\"], fit=norm)\nplt.title(\"density Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = densityMean, palette= \"ocean\")\nplt.title(\"the average value of density by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"density mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"density\"], palette='ocean')\nplt.title(\"density & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:lightblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >It seems quite difficult to predict the effect on the target variable.<\/p> <\/li>\n        <li style = \"color:lightblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine the scatterplot, we see that it has a normal distribution.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='26' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">pH<\/h4>\n\"\"\"\npHMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"pH\"].mean()\n    pHMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"pH\"], color=\"#00FF00\")\nplt.xlabel(\"pH\")\nplt.ylabel(\"Frequency\")\nplt.title(\"pH histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"pH\"], fit=norm, color = \"#00FF00\")\nplt.title(\"pH Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = pHMean, palette= \"hsv\")\nplt.title(\"the average value of pH by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"pH mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"pH\"], palette='hsv')\nplt.title(\"pH & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:#00FF00;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that the decrease in pH value has a positive effect on the votes.<\/p> <\/li>\n        <li style = \"color:#00FF00;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that the scatterplot has normal, outlier values. We need to identify and remove outliers.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='27' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">sulphates<\/h4>\n\"\"\"\nsulphatesMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"sulphates\"].mean()\n    sulphatesMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"sulphates\"], color=\"plum\")\nplt.xlabel(\"sulphates\")\nplt.ylabel(\"Frequency\")\nplt.title(\"sulphates histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"sulphates\"], fit=norm, color=\"plum\")\nplt.title(\"sulphates Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = sulphatesMean, palette= \"twilight\")\nplt.title(\"the average value of sulphates by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"sulphates mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"sulphates\"], palette='twilight')\nplt.title(\"sulphates & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:plum;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that the higher the value of the sulphates, the more positive the votes are.<\/p> <\/li>\n        <li style = \"color:plum;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We have so many outliers here that we need to remove them.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='28' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">alcohol<\/h4>\n\"\"\"\nalcoholMean = []\n\nfor each in quality:\n    x = data[data[\"quality\"] == each]\n    mean = x[\"alcohol\"].mean()\n    alcoholMean.append(mean)\n\n\nplt.figure(figsize=(13,10))\nplt.subplot(2,2,1)\nplt.hist(data[\"alcohol\"], color=\"#DAA520\")\nplt.xlabel(\"alcohol\")\nplt.ylabel(\"Frequency\")\nplt.title(\"alcohol histogram\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,2)\nsns.distplot(data[\"alcohol\"], fit=norm, color=\"#DAA520\")\nplt.title(\"alcohol Distplot\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(2,2,3)\nsns.barplot(x = quality, y = alcoholMean, palette= \"CMRmap\")\nplt.title(\"the average value of alcohol by quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.xlabel(\"quality\")\nplt.ylabel(\"alcohol mean\")\nplt.subplot(2,2,4)\nsns.boxplot(data['quality'], data[\"alcohol\"], palette='CMRmap')\nplt.title(\"alcohol & quality\", color = \"black\", fontweight= 'bold', fontsize = 11)\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:#DAA520;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When the graph is examined in general, it can be said that the increase in alcohol has a positive effect on the votes.<\/p> <\/li>\n        <li style = \"color:#DAA520;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine the 2nd graph, we see that there is skewness. We will fix this.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='29' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">quality<\/h4>\n\"\"\"\nNumber = data.quality.value_counts().values\nLabel = data.quality.value_counts().index\ncircle = plt.Circle((0,0),0.2,color = \"white\")\nexplodeTuple = (0.0, 0.0, 0.0, 0.3, 0.5, 0.5)\n\nplt.figure(figsize=(13,5))\nplt.subplot(1,2,1)\nsns.countplot(data[\"quality\"])\nplt.xlabel(\"quality\")\nplt.title(\"quality distribution\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.subplot(1,2,2)\nplt.pie(Number, labels = Label,autopct='%1.2f%%', explode=explodeTuple,startangle=60)\np = plt.gcf()\np.gca().add_artist(circle) \nplt.title(\"quality distribution\", color = \"black\", fontweight= 'bold', fontsize = 11)\nplt.legend()\n\n\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:red;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >Here we see the distribution of the votes.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='30' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Skewness Correction<\/h2>\n\n<p style = \"color:darkred;font-family:Comic Sans MS;font-weight:bold\" >In this section, we will try to correct the skewness in some features of our data. We will do this by seeing them through graphs.<\/p>\n\n<ul>\n    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > fixed acidity <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > residual sugar <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >free sulfur dioxide <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >total sulfur dioxide <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >sulphates <\/p> <\/li>\n            \n<\/ul> \n\"\"\"\n\"\"\"\n<a id ='31' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">fixed acidity<\/h4>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"fixed acidity\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"fixed acidity\", mu, \"fixed acidity\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"fixed acidity\"], fit=norm, color=\"orange\")\nplt.title(\"fixed acidity Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"fixed acidity\"], plot = plt)\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:red;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We were down above. On the second graph, we see that there is skewness.<\/p> <\/li>\n<\/ul>\n\"\"\"\ndata[\"fixed acidity\"], lam_fixed_acidity = boxcox(data[\"fixed acidity\"])\n\"\"\"\n<ul>\n    <li style = \"color:red;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We will try to eliminate the skewness here by using box cox.<\/p> <\/li>\n<\/ul>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"fixed acidity\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"fixed acidity\", mu, \"fixed acidity\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"fixed acidity\"], fit=norm, color=\"orange\")\nplt.title(\"fixed acidity Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"fixed acidity\"], plot = plt)\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:red;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >When we examine the previous and current graphics, we see that we have eliminated the skewness at a good level.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='32' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">residual sugar<\/h4>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"residual sugar\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"residual sugar\", mu, \"residual sugar\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"residual sugar\"], fit=norm, color=\"orange\")\nplt.title(\"residual sugar Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"residual sugar\"], plot = plt)\nplt.show()\ndata[\"residual sugar\"], lam_fixed_acidity = boxcox(data[\"residual sugar\"])\n(mu, sigma) = norm.fit(data[\"residual sugar\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"residual sugar\", mu, \"residual sugar\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"residual sugar\"], fit=norm, color=\"orange\")\nplt.title(\"residual sugar Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"residual sugar\"], plot = plt)\nplt.show()\n\"\"\"\n<a id ='33' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">free sulfur dioxide<\/h4>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"free sulfur dioxide\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"free sulfur dioxide\", mu, \"free sulfur dioxide\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"free sulfur dioxide\"], fit=norm, color=\"orange\")\nplt.title(\"free sulfur dioxide Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"free sulfur dioxide\"], plot = plt)\nplt.show()\ndata[\"free sulfur dioxide\"], lam_fixed_acidity = boxcox(data[\"free sulfur dioxide\"])\n(mu, sigma) = norm.fit(data[\"free sulfur dioxide\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"free sulfur dioxide\", mu, \"free sulfur dioxide\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"free sulfur dioxide\"], fit=norm, color=\"orange\")\nplt.title(\"free sulfur dioxide Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"free sulfur dioxide\"], plot = plt)\nplt.show()\n\"\"\"\n<a id ='34' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">total sulfur dioxide<\/h4>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"total sulfur dioxide\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"total sulfur dioxide\", mu, \"total sulfur dioxide\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"total sulfur dioxide\"], fit=norm, color=\"orange\")\nplt.title(\"total sulfur dioxide Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"total sulfur dioxide\"], plot = plt)\nplt.show()\ndata[\"total sulfur dioxide\"], lam_fixed_acidity = boxcox(data[\"total sulfur dioxide\"])\n(mu, sigma) = norm.fit(data[\"total sulfur dioxide\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"total sulfur dioxide\", mu, \"total sulfur dioxide\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"total sulfur dioxide\"], fit=norm, color=\"orange\")\nplt.title(\"total sulfur dioxide Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"total sulfur dioxide\"], plot = plt)\nplt.show()\n\"\"\"\n<a id ='35' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">alcohol<\/h4>\n\"\"\"\n(mu, sigma) = norm.fit(data[\"alcohol\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"alcohol\", mu, \"alcohol\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"alcohol\"], fit=norm, color=\"orange\")\nplt.title(\"alcohol Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"alcohol\"], plot = plt)\nplt.show()\ndata[\"alcohol\"], lam_fixed_acidity = boxcox(data[\"alcohol\"])\n(mu, sigma) = norm.fit(data[\"alcohol\"])\nprint(\"mu {} : {}, sigma {} : {}\".format(\"alcohol\", mu, \"alcohol\", sigma))\nplt.figure(figsize=(10,4))\nplt.subplot(1,2,1)\nsns.distplot(data[\"alcohol\"], fit=norm, color=\"orange\")\nplt.title(\"alcohol Distplot\", color = \"darkred\")\nplt.subplot(1,2,2)\nstats.probplot(data[\"alcohol\"], plot = plt)\nplt.show()\n\"\"\"\n<a id ='36' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Outlier Detection<\/h2>\n\n<p style = \"color:darkred;font-family:Comic Sans MS;font-weight:bold\" >We detect outliers in our data. and we will extract them from the data.<\/p>\n\"\"\"\ndef detect_outliers(df,features):\n    outlier_indices = []\n    \n    for c in features:\n        # 1st quartile\n        Q1 = np.percentile(df[c],25)\n        # 3st quartile\n        Q3 = np.percentile(df[c],75)\n        # IQR\n        IQR = Q3 - Q1\n        # Outlier Step\n        outlier_step = IQR * 1.5\n        # detect outlier and their indeces\n        outlier_list_col = df[(df[c] < Q1 - outlier_step) | (df[c] > Q3 + outlier_step)].index\n        # store indeces \n        outlier_indices.extend(outlier_list_col)\n        \n    outlier_indices = Counter(outlier_indices)\n    multiple_outliers = list(i for i, v in outlier_indices.items() if v > 1.5) \n    \n    return multiple_outliers\nprint(\"number of outliers detected --> \",len(data.loc[detect_outliers(data,data.columns[:-1])]))\ndata.loc[detect_outliers(data,data.columns[:-1])]\ndata = data.drop(detect_outliers(data,data.columns[:-1]),axis = 0).reset_index(drop = True)\n\"\"\"\n<ul>\n    <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We remove the detected outliers from our data.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='37' ><\/a>\n<h2 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Modeling<\/h2>\n\n<p style = \"color:darkblue;font-family:Comic Sans MS;font-weight:bold\" >Now our data is ready for the model. Now we will create our models.<\/p>\n\n<ul>\n    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > Import Model Library <\/p> <\/li>\n        <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" > Train - Test Split <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >Smote <\/p> <\/li>\n                <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >StandardScaler <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >KNeighborsClassifier <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >GradientBoostingClassifier <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >SVC <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >XGBClassifier <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >KNeighborsClassifier <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >CatBoostClassifier <\/p> <\/li>\n                    <li style = \"color:darkred\"> <p style = \"color:black;font-family:Comic Sans MS;font-weight:bold\" >RandomForestClassifier <\/p> <\/li>\n            \n<\/ul> \n\"\"\"\n\"\"\"\n<a id ='38' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Import Model Library<\/h4>\n\"\"\"\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, RandomizedSearchCV\nfrom sklearn.svm import SVC\nfrom scipy.stats import uniform as sp_randFloat\nfrom scipy.stats import randint as sp_randInt  \nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier, VotingClassifier, GradientBoostingClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nfrom sklearn.neighbors import KNeighborsClassifier\nimport collections\nbins = (2, 6.5, 8)\nlabels = [0, 1]\ndata['quality'] = pd.cut(x = data['quality'], bins = bins, labels = labels)\n\"\"\"\n<ul>\n    <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We make the variable quality into 2 variables, 0 and 1.<\/p> <\/li>\n<\/ul>\n\"\"\"\ndata['quality'].value_counts()\n\"\"\"\n<ul>\n    <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >0 --> 1323<\/p> <\/li>\n        <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >1 --> 208<\/p> <\/li>\n        <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We see that there is a big difference between the 2 values. So we see that it is unbalanced. We will fix this.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='39' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Train - Test Split<\/h4>\n\"\"\"\ny = data.quality\nx = data.drop([\"quality\"], axis = 1)\ntest_size = 0.20\nX_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size = test_size, random_state = 206)\n\"\"\"\n<a id ='40' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Smote<\/h4>\n\n<p style = \"color:darkgreen;font-family:Comic Sans MS;font-weight:bold\" >We saw above that our data is an unbalanced data. We fix this with the help of smote.<\/p>\n\"\"\"\nsm = SMOTE(random_state=14)\nX_train_sm, y_train_sm = sm.fit_resample(X_train, Y_train)\nprint(\"Before smote --> \", collections.Counter(Y_train))\nprint(\"After smote --> \", collections.Counter(y_train_sm))\n\"\"\"\n<a id ='41' ><\/a>\n<h4 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">StandardScaler<\/h4>\n\"\"\"\nscaler = StandardScaler()\nX_train_sm = scaler.fit_transform(X_train_sm) \nX_test = scaler.transform(X_test) \nresults = []\n\"\"\"\n<ul>\n    <li style = \"color:darkblue;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >To record our model achievements. We are making a list.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='42' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">KNeighborsClassifier<\/h3>\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors = 2)\nknn.fit(X_train_sm, y_train_sm)\ny_pred = knn.predict(X_test)\ncm = confusion_matrix(Y_test, y_pred)\n\nacc = accuracy_score(Y_test, y_pred)\nscore = knn.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"KNeighborsClassifier Acc : \", acc)\n\nplot_confusion_matrix(knn, X_test, Y_test, cmap= \"Greens\")  \nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:green;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We saw cm matrix. Let's take a look at the bidet classification report<\/p> <\/li>\n<\/ul>\n\"\"\"\nprint(\" \\t \\t  KNN Classification Report\")\nprint(classification_report(Y_test, y_pred))\n\"\"\"\n<a id ='43' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">GradientBoostingClassifier<\/h3>\n\"\"\"\ngbc = GradientBoostingClassifier(max_depth= 6, random_state=2)\ngbc.fit(X_train_sm, y_train_sm)\ny_pred_gbc = gbc.predict(X_test)\ncm_aaa = confusion_matrix(Y_test, y_pred_gbc)\nacc = accuracy_score(Y_test, y_pred_gbc)\nscore = gbc.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"GradientBoostingClassifier Acc : \", acc)\n\nplot_confusion_matrix(gbc, X_test, Y_test, cmap= \"binary\")  \nplt.show()\nprint(\" \\t \\t  GradientBoostingClassifier Classification Report\")\nprint(classification_report(Y_test, y_pred_gbc))\n\"\"\"\n<a id ='44' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">SVC<\/h3>\n\"\"\"\nsvc = SVC()\nsvc.fit(X_train_sm, y_train_sm)\npred_svc = svc.predict(X_test)\n\ncm_svc = confusion_matrix(Y_test, pred_svc)\nacc = accuracy_score(Y_test, pred_svc)\nscore = svc.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"SVC Acc : \", acc)\n\nplot_confusion_matrix(svc, X_test, Y_test, cmap= \"Reds\")  \nplt.show()\nprint(\" \\t \\t  SVC Classification Report\")\nprint(classification_report(Y_test, pred_svc))\n\"\"\"\n<a id ='45' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">XGBClassifier<\/h3>\n\"\"\"\nxgb = XGBClassifier()\nxgb.fit(X_train_sm, y_train_sm)\npred_xgb = xgb.predict(X_test)\n\ncm_aaa = confusion_matrix(Y_test, pred_xgb)\nacc = accuracy_score(Y_test, pred_xgb)\nscore = xgb.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"XGBClassifier Acc : \", acc)\n\nplot_confusion_matrix(xgb, X_test, Y_test, cmap= \"copper\")  \nplt.show()\nprint(\" \\t \\t  XGBClassifier Classification Report\")\nprint(classification_report(Y_test, pred_xgb))\n\"\"\"\n<a id ='46' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">CatBoostClassifier<\/h3>\n\"\"\"\nparameters = {  \n                'depth'         : sp_randInt(4, 10),\n                'learning_rate' : sp_randFloat(),\n                'iterations'    : sp_randInt(10, 100)\n             }\ncat = CatBoostClassifier(iterations=1000, verbose = False, depth=8)\nrandm = RandomizedSearchCV(estimator=cat, param_distributions = parameters, \n                               cv = 2, n_iter = 10, n_jobs=-1)\nrandm.fit(X_train_sm, y_train_sm)\n\npred_cat = randm.predict(X_test)\n\ncm_cat = confusion_matrix(Y_test, pred_cat)\nacc = accuracy_score(Y_test, pred_cat)\nscore = randm.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"Basic KNN Acc : \", acc)\n\nplot_confusion_matrix(randm, X_test, Y_test, cmap= \"hot\")  \nplt.show()\nprint(\" \\t \\t  CatBoostClassifier Classification Report\")\nprint(classification_report(Y_test, pred_cat))\n\"\"\"\n<a id ='47' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">RandomForestClassifier<\/h3>\n\"\"\"\nrf = RandomForestClassifier(max_depth=18, random_state=44, bootstrap = False)\nrf.fit(X_train_sm, y_train_sm)\ny_pred_rf = rf.predict(X_test)\ncm = confusion_matrix(Y_test, y_pred_rf)\n\nacc = accuracy_score(Y_test, y_pred_rf)\nscore = rf.score(X_test, Y_test)\nresults.append(acc)\n\nprint(\"Score : \", score)\nprint(\"RandomForestClassifier Acc : \", acc)\n\nplot_confusion_matrix(rf, X_test, Y_test, cmap= \"pink\")  \nplt.show()\nprint(\" \\t \\t  RandomForestClassifier Classification Report\")\nprint(classification_report(Y_test, y_pred_rf))\n\"\"\"\n<ul>\n    <li style = \"color:green;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We got the best result in Random Forest. Let's take a look at the mistakes we made.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='48' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Wrong Predictions<\/h3>\n\"\"\"\ntest_data = pd.DataFrame()\ntest_data[\"citric acid\"] = data[\"volatile acidity\"][:307]\ntest_data[\"fixed acidity\"] = data[\"fixed acidity\"][:307]\ntest_data[\"y_pred_rf\"] = y_pred_rf\ntest_data[\"Y_test\"] = Y_test.values\n\nplt.figure(figsize=(12,6))\nsns.scatterplot(x=\"citric acid\", y=\"fixed acidity\", hue=\"Y_test\", data=test_data, palette=[\"Black\",\"darkgreen\"])\nplt.title(\"Classifications We Made Wrong\", fontsize = 13, fontweight = \"bold\", color = \"darkred\")\n\ndiff = np.where(y_pred_rf!=Y_test)[0]\nplt.scatter(test_data.iloc[diff,0],test_data.iloc[diff,1],label = \"Wrong Classified\", marker=\"x\",alpha = 0.7, color = \"Red\",s = 300)\nplt.legend()\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:green;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We also took a look at the guesses we made wrong. (For Random Forest)<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id ='49' ><\/a>\n<h3 style = \"background:black;color:white;border:0;font-family:Comic Sans MS;font-weight:bold\">Model Result<\/h3>\n\"\"\"\ndf_result = pd.DataFrame({\"Score\":results, \"ML Models\":[\"KNN\",\"GradientBoostingClassifier\",\n             \"SVC\",\"XGBClassifier\",\"CatBoostClassifier\",\"RandomForestClassifier\"]})\ndf_result.style.background_gradient(\"Greens\")\ng = sns.barplot(\"Score\", \"ML Models\", data = df_result, palette='BrBG')\ng.set_xlabel(\"Score\")\ng.set_title(\"Classifier Model Results\", color = \"Black\")\nplt.show()\n\"\"\"\n<ul>\n    <li style = \"color:green;font-family:Segoe Print\" > <p style = \"color:black;font-family:Comic Sans MS\" >We achieved the highest success in Random Forest with 0.957.<\/p> <\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<p style = \"text-shadow: 12px 12px 2px #333;color:brown;font-family:Segoe Print;font-weight:bold\" > YES, WE HAVE COME TO AN END. THANK YOU<\/p>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '660294bbf7ce34'}"}
{"id":"4510","text":"\"\"\"\n# Analysis of SIIM-ISIC Melanoma Classification Metadata and Images\n\n# Introduction\n\n## The Competition\n\nSkin cancer is common cancer type and despite beign mostly non malignant, due to high case numbers it's pretty serious diasease and can lead serious cases if not detected, treated in time. It's usually diagnosed by eye for primarily and followed by further clinical analysis if needed. Even though the rares outcome is called melanoma it's the most deadly one, so early detection is pretty important. For this task using computer aided diagnosis might be helpful for primarily steps and early detections. Better detection might save thousands of lives.\n\nThis competition might help reaching that goal and I hope it can help people around the world...\n\n## Updates:\n\n### 23\/07\/2020:\n- Added adversarial validation,\n- Updated metadata by removing biased features,\n- Created simplier machine learning model.\n\n### 25\/07\/2020:\n- Added deep learning part\n- Included EfficientNet modelling\n- Ensembled metadata and EffNet predictions\n\n\n## About the Notebook\n\nFirst of all this is **pretty early version of this notebook**, I decided to start part by part before I fully commit my submission, so for now this notebook covers such as:\n\n- EDA of the metadata,\n- Extracting basic image attributes like image size, colors etc.\n- Creating new features from existing data,\n- Design a machine learning model by using these simple features\n- Make predictions using our model and tabular data\n- Deep learning part will be added in future...\n\nI think using metadata for understanding the problem is really important and plus side is we can use it to improve our scores, for now we only going to use tabular data for submissions. This way we can see it's power and it can help us with future CNN modelling. This notebook going to try answer questions like these:\n\n- How's the data looking?\n- Do we have complete dataset?\n- How's the target distribution looking? Is it balanced?\n- What are the effects of scan site on outcome?\n- Does age effects skin lesion type?\n- Is there difference between female and male patients in terms of target?\n- How many unique patient data we have and how many scans they had? Is it important?\n- Is image quality, colors, size have meaningful impact on the outcome?\n- Can we see similar observations when we analyse both train and test dataset, if not why?\n- And much more...\n\n\n\"\"\"\n\"\"\"\n# First Impressions and Getting Tools Ready\n\nLet's buckle up and get our tools ready for our work! We start with importing neccesary libraries. Since we going to do mostly EDA our libraries are going to be related with tabular data and visualization.\n\"\"\"\n!pip install -q efficientnet\n# loading packages\n\nimport pandas as pd\nimport numpy as np\n\n#\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n#\n\nimport seaborn as sns\nimport plotly.express as px\n\n#\n\nimport os\nimport random\nimport re\nimport math\nimport time\n\nfrom tqdm import tqdm\nfrom tqdm.keras import TqdmCallback\n\n\nfrom pandas_summary import DataFrameSummary\n\nimport warnings\n\n\nwarnings.filterwarnings('ignore') # Disabling warnings for clearer outputs\n\n\n\nseed_val = 42\nrandom.seed(seed_val)\nnp.random.seed(seed_val)\n\"\"\"\nWe set some custom styling with our notebook for aesthetics...\n\"\"\"\n# Setting color palette.\norange_black = [\n    '#fdc029', '#df861d', '#FF6347', '#aa3d01', '#a30e15', '#800000', '#171820'\n]\n\n# Setting plot styling.\nplt.style.use('ggplot')\n# Setting file paths for our notebook:\n\nbase_path = '\/kaggle\/input\/siim-isic-melanoma-classification'\ntrain_img_path = '\/kaggle\/input\/siim-isic-melanoma-classification\/jpeg\/train\/'\ntest_img_path = '\/kaggle\/input\/siim-isic-melanoma-classification\/jpeg\/test\/'\nimg_stats_path = '\/kaggle\/input\/melanoma2020imgtabular'\n\"\"\"\n# Loading the Data\n\nWe'll continue by loading metadata we're given. Train data has 8 features, 33126 observations and Test data 5 features, 10982 observations.\n\n#### Train Dataset Consists Of:\n\n1. image name -> the filename of specific image for the train set\n2. patient_id -> identifies the unique patient\n3. sex -> gender of the patient\n4. age_approx -> approx age of the patient at time of scanning\n5. anatom_site_general_challenge -> location of the scan site\n6. diagnosis -> information about the diagnosis\n7. benign_malignant - indicates scan result if it's malignant or benign\n8. target -> same as above but better for modelling since it's binary\n\nAnd the next dataset we going to inspect test. It has same features as train set except for scan results, well that's why it's test set right?!\n\n#### Train Dataset Consists Of:\n\n1. image name -> the filename of specific image for the train set\n2. patient_id -> identifies the unique patient\n3. sex -> gender of the patient\n4. age_approx -> approx age of the patient at time of scanning\n5. anatom_site_general_challenge -> location of the scan site\n\"\"\"\n# Loading train and test data.\n\ntrain = pd.read_csv(os.path.join(base_path, 'train.csv'))\ntest = pd.read_csv(os.path.join(base_path, 'test.csv'))\nsample = pd.read_csv(os.path.join(base_path, 'sample_submission.csv'))\n# Checking train and test columns\/rows.\n\nprint(\n    f'Train data has {train.shape[1]} features, {train.shape[0]} observations and Test data {test.shape[1]} features, {test.shape[0]} observations.\\nTrain features are:\\n{train.columns.tolist()}\\nTest features are:\\n{test.columns.tolist()}'\n)\n# Renaming train\/test columns:\n\ntrain.columns = [\n    'img_name', 'id', 'sex', 'age', 'location', 'diagnosis',\n    'benign_malignant', 'target'\n]\ntest.columns = ['img_name', 'id', 'sex', 'age', 'location']\n# Taking 5 random samples from the train data:\n\ntrain.sample(5)\n# Taking 5 random samples from the test data:\n\ntest.sample(5)\n\"\"\"\n# Missing Values\n\nWe have small portion of missing values for age and sex I think there is no harm if we impute them with the most frequent ones, meanwhile body parts missing on both datasets, we better be set 'unknown' for missing values for this one...\n\"\"\"\n# Checking missing values:\n\ndef missing_percentage(df):\n\n    total = df.isnull().sum().sort_values(\n        ascending=False)[df.isnull().sum().sort_values(ascending=False) != 0]\n    percent = (df.isnull().sum().sort_values(ascending=False) \/ len(df) *\n               100)[(df.isnull().sum().sort_values(ascending=False) \/ len(df) *\n                     100) != 0]\n    return pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n\n\nmissing_train = missing_percentage(train)\nmissing_test = missing_percentage(test)\n\nfig, ax = plt.subplots(1, 2, figsize=(16, 6))\n\nsns.barplot(x=missing_train.index,\n            y='Percent',\n            data=missing_train,\n            palette=orange_black,\n            ax=ax[0])\n\nsns.barplot(x=missing_test.index,\n            y='Percent',\n            data=missing_test,\n            palette=orange_black,\n            ax=ax[1])\n\nax[0].set_title('Train Data Missing Values')\nax[1].set_title('Test Data Missing Values')\n\"\"\"\n## Checking Variables Before Imputing\n\nJust wanted to check variable distribution before we impute the missing ones. Looks like our assumptions were ok, we can continue with imputing...\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 9))\n\n# Creating a grid:\n\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Gender Distribution')\n\nsns.countplot(train.sex.sort_values(ignore_index=True),\n              alpha=0.9,\n              ax=ax1,\n              color='#fdc029',\n              label='Train')\nsns.countplot(test.sex.sort_values(ignore_index=True),\n              alpha=0.7,\n              ax=ax1,\n              color='#171820',\n              label='Test')\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Plot the countplot.\n\nsns.countplot(train.location,\n              alpha=0.9,\n              ax=ax2,\n              color='#fdc029',\n              label='Train',\n              order=train['location'].value_counts().index)\nsns.countplot(test.location,\n              alpha=0.7,\n              ax=ax2,\n              color='#171820',\n              label='Test',\n              order=test['location'].value_counts().index), ax2.set_title(\n                  'Anatom Site Distribution')\n\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Age Distribution')\n\n# Plot the histogram.\n\nsns.distplot(train.age, ax=ax3, label='Train', color='#fdc029')\nsns.distplot(test.age, ax=ax3, label='Test', color='#171820')\n\nax3.legend()\n\nplt.show()\n\"\"\"\n# Imputing Missing Data\n\nLet's fill the missing values with appropriate methods.\n\"\"\"\n# Filling missing anatom site values with 'unknown' tag:\n\nfor df in [train, test]:\n    df['location'].fillna('unknown', inplace=True)\n# Double checking:\n\nids_train = train.location.values\nids_test = test.location.values\nids_train_set = set(ids_train)\nids_test_set = set(ids_test)\n\nlocation_not_overlap = list(ids_train_set.symmetric_difference(ids_test_set))\nn_overlap = len(location_not_overlap)\nif n_overlap == 0:\n    print(\n        f'There are no different body parts occuring between train and test set...'\n    )\nelse:\n    print('There are some not overlapping values between train and test set!')\n# Filling age and sex with appropriate values.\n\ntrain['sex'].fillna(train['sex'].mode()[0], inplace=True)\n\ntrain['age'].fillna(train['age'].median(), inplace=True)\n# Checking missing value counts:\n\nprint(\n    f'Train missing value count: {train.isnull().sum().sum()}\\nTest missing value count: {train.isnull().sum().sum()}'\n)\n\"\"\"\n# Exploring the Data\n\"\"\"\n\"\"\"\n## Scans by Anatom Site\n\nGood... It looks like both datasets shared scanned body parts similary. Let's check it further.\n\"\"\"\n# Train data:\n\ncntstr = train.location.value_counts().rename_axis('location').reset_index(\n    name='count')\n\nfig = px.treemap(cntstr,\n                 path=['location'],\n                 values='count',\n                 color='count',\n                 color_continuous_scale=orange_black,\n                 title='Scans by Anatom Site General Challenge - Train Data')\n\nfig.update_traces(textinfo='label+percent entry')\nfig.show()\n# Test data:\n\ncntste = test.location.value_counts().rename_axis('location').reset_index(\n    name='count')\n\nfig = px.treemap(cntste,\n                 path=['location'],\n                 values='count',\n                 color='count',\n                 color_continuous_scale=orange_black,\n                 title='Scans by Anatom Site General Challenge - Test Data')\n\nfig.update_traces(textinfo='label+percent entry')\nfig.show()\n\"\"\"\n# Body Part Ratio by Gender and Target\n\nLooks like some body parts are more likely to be malignant, head\/neck comes first with followed by oral\/genital and upper extremity. Scanned body part locations are similar in order between males and females with small differences on distribution.\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 9))\n# Creating a grid\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[1, :2])\n# Set the title.\nax1.set_title('Scanned Body Parts - Female')\n\n# Plot:\n\nsns.countplot(\n    train[train['sex'] == 'female'].location.sort_values(ignore_index=True),\n    alpha=0.9,\n    ax=ax1,\n    color='#fdc029',\n    label='Female',\n    order=train['location'].value_counts().index)\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[1, 2:])\n\n# Set the title.\n\nax2.set_title('Scanned Body Parts - Male')\n\n# Plot.\n\nsns.countplot(\n    train[train['sex'] == 'male'].location.sort_values(ignore_index=True),\n    alpha=0.9,\n    ax=ax2,\n    color='#171820',\n    label='Male',\n    order=train['location'].value_counts().index)\n\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[0, :])\n\n# Set the title.\n\nax3.set_title('Malignant Ratio Per Body Part')\n\n# Plot.\n\nloc_freq = train.groupby('location')['target'].mean().sort_values(\n    ascending=False)\nsns.barplot(x=loc_freq.index, y=loc_freq, palette=orange_black, ax=ax3)\n\nax3.legend()\n\nplt.show()\n\"\"\"\n# A General Look With Sunburst Chart\n\nSunburst chart is pretty cool looking fella I'd say. It also giving lots of basic information to us. Let's see...\n\n- Only 2% of our targets are malignant\n- On malignant images males are dominant with 62% \n- Gender wise benign images are more balance 52-48% male female ratio\n- Malignant image scan locations differs based on the patients gender:\n    - Meanwhile the torso is most common location in males it's almost half of the scans meanwhile in females it's 39%\n    - Lower extremity is more common with female scans than males 18% males vs 26% females\n    - Again upper extremity malignant scans is common with females than males (23- 17%)\n- Benign image scan locations more similar between male and female patients.\n\"\"\"\n# Plotting interactive sunburst:\n\nfig = px.sunburst(data_frame=train,\n                  path=['benign_malignant', 'sex', 'location'],\n                  color='sex',\n                  color_discrete_sequence=orange_black,\n                  maxdepth=-1,\n                  title='Sunburst Chart Benign\/Malignant > Sex > Location')\n\nfig.update_traces(textinfo='label+percent parent')\nfig.update_layout(margin=dict(t=0, l=0, r=0, b=0))\nfig.show()\n\"\"\"\n# Age and Scan Result Relations\n\nAge looks pretty decent factor on scan result. Getting malignant scan result with elderly age is more possible than young patients. There is spike for both genders after age of 85, if we look distribution of ages there isn't much of 80+ patients and it can be the reason of this spike but we can safely say it's more likely to be malignant scan after age of 60. We see small bump on age 15-20 for females, again it depends on the scan numbers but still, poor souls...\n\"\"\"\n# Plotting age vs sex vs target:\n\nfig, ax = plt.subplots(1, 2, figsize=(16, 6))\nsns.lineplot(x='age',\n             y='target',\n             data=train,\n             ax=ax[0],\n             hue='sex',\n             palette=orange_black[:2],\n             ci=None)\nsns.boxplot(x='benign_malignant',\n            y='age',\n            data=train,\n            ax=ax[1],\n            hue='sex',\n            palette=orange_black)\n\nplt.legend(loc='lower right')\n\nax[0].set_title('Malignant Scan Frequency by Age')\nax[1].set_title('Scan Results by Age and Sex')\n\nplt.show()\n\"\"\"\n# Age Round Two\n\nWanted to double check age distributions after our previous observations. Age seems evenly distributed on both train and test datasets, we can see small bumps at age 75+ and around 40, these worth investigating.\n\nWe can see again older people are more likely to get malignant scan results. One last thing about age distributions, we see more female patients in younger ages this trend changes with the older patients...\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\n# Plotting age dist vs target and age dist vs datasets\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Age Distribution by Scan Outcome')\n\n# Plot\n\nax1.legend()\n\nsns.kdeplot(train[train['target'] == 0]['age'],\n            shade=True,\n            ax=ax1,\n            color='#171820',\n            label='Benign')\nsns.kdeplot(train[train['target'] == 1]['age'],\n            shade=True,\n            ax=ax1,\n            color='#fdc029',\n            label='Malignant')\n\n# Customizing second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Set the title.\n\nax2.set_title('Age Distribution by Train\/Test Observations')\n\n# Plot.\n\nsns.kdeplot(train.age, label='Train', shade=True, ax=ax2, color='#171820')\nsns.kdeplot(test.age, label='Test', shade=True, ax=ax2, color='#fdc029')\n\nax2.legend()\n\n# Customizing third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Age Distribution by Gender')\n\n# Plot\n\nsns.distplot(train[train.sex == 'female'].age,\n             ax=ax3,\n             label='Female',\n             color='#fdc029')\nsns.distplot(train[train.sex == 'male'].age,\n             ax=ax3,\n             label='Male',\n             color='#171820')\nax3.legend()\n\nplt.show()\n\"\"\"\n# Unique Patients and Their Scan Images\n\nIt looks like we have multiple scan images per patient, actual unique patient counts are much lower than images on both datasets. We can get more information about patients age like when he had his first scan and his last scan. We can get interesting insights like:\n\n- Most of the malignant results are found around first 20 scans. Of course there can be control scans after the diagnosis...\n- Scan numbers are similar in first 100 scans but we have 200+ scan images for **one particular patient** in dataset, it's pretty interesting since we don't have this case in our training data. We should be careful about this and it can effect our model.\n- Most of the malignant cases are under 20 images but in general we can say it's more likely to be malignant result if there are more scan images...\n\"\"\"\nprint(\n    f'Number of unique Patient ID\\'s in train set: {train.id.nunique()}, Total: {train.id.count()}\\nNumber of unique Patient ID\\'s in test set: {test.id.nunique()}, Total: {test.id.count()}'\n)\ntrain['age_min'] = train['id'].map(train.groupby(['id']).age.min())\ntrain['age_max'] = train['id'].map(train.groupby(['id']).age.max())\n\ntest['age_min'] = test['id'].map(test.groupby(['id']).age.min())\ntest['age_max'] = test['id'].map(test.groupby(['id']).age.max())\ntrain['n_images'] = train.id.map(train.groupby(['id']).img_name.count())\ntest['n_images'] = test.id.map(test.groupby(['id']).img_name.count())\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Number of Scans Distribution by Scan Outcome')\n\n# Plot\n\nsns.kdeplot(train[train['target'] == 0]['n_images'],\n            shade=True,\n            ax=ax1,\n            color='#171820',\n            label='Benign')\nsns.kdeplot(train[train['target'] == 1]['n_images'],\n            shade=True,\n            ax=ax1,\n            color='#fdc029',\n            label='Malignant')\n\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Set the title.\n\nax2.set_title('Number of Scans Distribution by Train\/Test Observations')\n\n# Plot\n\nsns.kdeplot(train.n_images, label='Train', shade=True, ax=ax2, color='#171820')\nsns.kdeplot(test.n_images, label='Test', shade=True, ax=ax2, color='#fdc029')\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Malignant Scan Result Frequency by Number of Scans')\n\n# Plot\n\nz = train.groupby('n_images')['target'].mean()\nsns.lineplot(x=z.index, y=z, color='#171820', ax=ax3)\nax3.legend()\n\nplt.show()\n\"\"\"\n# Diagnosis Distribution\n\nThis part we can't use in our model but it's giving us some insights about this disease so we can inspect that too. You can see the details below:\n\"\"\"\ndiag = train.diagnosis.value_counts()\nfig = px.pie(diag,\n             values='diagnosis',\n             names=diag.index,\n             color_discrete_sequence=orange_black,\n             hole=.4)\nfig.update_traces(textinfo='percent+label', pull=0.05)\nfig.show()\n\"\"\"\n# Loading Image Meta Features\n\nThis is the part where we get basic info directly from images themselves.\n\"\"\"\n# Getting image sizes by using os:\n\nfor data, location in zip([train, test], [train_img_path, test_img_path]):\n    images = data['img_name'].values\n    sizes = np.zeros(images.shape[0])\n    for i, path in enumerate(tqdm(images)):\n        sizes[i] = os.path.getsize(os.path.join(location, f'{path}.jpg'))\n\n    data['image_size'] = sizes\n\"\"\"\n# Image Sizes\n\nWe can see some kind of relation between size and target, but is it meaningful? Too soon to say...\n\"\"\"\n# Plotting image sizes:\n\nfig, ax = plt.subplots(1, 2, figsize=(16, 6))\n\nsns.kdeplot(train[train['target'] == 0]['image_size'],\n            shade=True,\n            ax=ax[0],\n            color='#171820',\n            label='Benign')\nsns.kdeplot(train[train['target'] == 1]['image_size'],\n            shade=True,\n            ax=ax[0],\n            color='#fdc029',\n            label='Malignant')\n\nsns.kdeplot(train.image_size,\n            label='Train',\n            shade=True,\n            ax=ax[1],\n            color='#171820')\nsns.kdeplot(test.image_size,\n            label='Test',\n            shade=True,\n            ax=ax[1],\n            color='#fdc029')\n\nax[0].set_title('Scan Image Size Distribution by Scan Outcome')\nax[1].set_title('Scan Image Size Distribution by Train\/Test Observations')\n\nplt.show()\n\"\"\"\n## Getting Image Attributes\n\nYou can get these attributes by using the code below, I commented it out here and imported it as a data becasue it's time consuming process.\n\"\"\"\n#from keras.preprocessing import image\n#\n# for data, location in zip([train, test],[train_img_path, test_img_path]):\n#    images = data['img_name'].values\n#    reds = np.zeros(images.shape[0])\n#    greens = np.zeros(images.shape[0])\n#    blues = np.zeros(images.shape[0])\n#    mean = np.zeros(images.shape[0])\n#    x = np.zeros(images.shape[0], dtype=int)\n#    y = np.zeros(images.shape[0], dtype=int)\n#    for i, path in enumerate(tqdm(images)):\n#        img = np.array(image.load_img(os.path.join(location, f'{path}.jpg')))\n#\n#        reds[i] = np.mean(img[:,:,0].ravel())\n#        greens[i] = np.mean(img[:,:,1].ravel())\n#        blues[i] = np.mean(img[:,:,2].ravel())\n#        mean[i] = np.mean(img)\n#        x[i] = img.shape[1]\n#        y[i] = img.shape[0]\n#\n#    data['reds'] = reds\n#    data['greens'] = greens\n#    data['blues'] = blues\n#    data['mean_colors'] = mean\n#    data['width'] = x\n#    data['height'] = y\n#\n#train['total_pixels']= train['width']*train['height']\n#test['total_pixels']= test['width'].astype(str)*test['height']\n# Loading color data:\n\ntrain_attr = pd.read_csv(\n    os.path.join(img_stats_path, 'train_mean_colorres.csv'))\ntest_attr = pd.read_csv(os.path.join(img_stats_path, 'test_mean_colorres.csv'))\ntrain_attr.head()\ntrain = pd.concat([train, train_attr], axis=1)\ntest = pd.concat([test, test_attr], axis=1)\n\ntrain['res'] = train['width'].astype(str) + 'x' + train['height'].astype(str)\ntest['res'] = test['width'].astype(str) + 'x' + test['height'].astype(str)\n\"\"\"\n# Image Colors and Their Effects on Results\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=3, nrows=3, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('RGB Channels of Benign Images')\n\n# Plot.\n\nsns.distplot(train[train['target'] == 0].reds,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='red',\n             kde=True,\n             ax=ax1,\n             label='Reds')\nsns.distplot(train[train['target'] == 0].greens,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='green',\n             kde=True,\n             ax=ax1,\n             label='Greens')\nsns.distplot(train[train['target'] == 0].blues,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='blue',\n             kde=True,\n             ax=ax1,\n             label='Blues')\n\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[1, :2])\n\n# Set the title.\n\nax2.set_title('RGB Channels of Malignant Images')\n\n# Plot\n\nsns.distplot(train[train['target'] == 1].reds,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='red',\n             kde=True,\n             ax=ax2,\n             label='Reds')\nsns.distplot(train[train['target'] == 1].greens,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='green',\n             kde=True,\n             ax=ax2,\n             label='Greens')\nsns.distplot(train[train['target'] == 1].blues,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='blue',\n             kde=True,\n             ax=ax2,\n             label='Blues')\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[:, 2])\n\n# Set the title.\n\nax3.set_title('Mean Colors by Train\/Test Images')\n\n# Plot\n\nsns.kdeplot(train.mean_colors,\n            shade=True,\n            label='Train',\n            ax=ax3,\n            color='#171820',\n            vertical=True)\nsns.kdeplot(test.mean_colors,\n            shade=True,\n            label='Test',\n            ax=ax3,\n            color='#fdc029',\n            vertical=True)\nax3.legend()\n\nplt.show()\n\"\"\"\n# How are the Image Sizes Affecting Targets in Our Data\n\nWe have important observation here, you can see whole 1920x1080 set in test data which is not present in train data. That can have huge impact on final scores, mind that in your models. You might want to leave out image size related info in your models or regularize your models to smooth that effect. It can cause overfitting because of high correlation between image sizes and target, but these correlation might not be the case in test set (most likely) so keep that in mind.\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=4, nrows=3, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Scan Image Resolutions of Train Set')\n\n# Plot.\n\ntres = train.res.value_counts().rename_axis('res').reset_index(name='count')\ntres = tres[tres['count'] > 10]\nsns.barplot(x='res', y='count', data=tres, palette=orange_black, ax=ax1)\nplt.xticks(rotation=20)\n\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Set the title.\n\nax2.set_title('Scan Image Resolutions of Test Set')\n\n# Plot\n\nteres = test.res.value_counts().rename_axis('res').reset_index(name='count')\nteres = teres[teres['count'] > 10]\nsns.barplot(x='res', y='count', data=teres, palette=orange_black, ax=ax2)\nplt.xticks(rotation=20)\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Scan Image Resolutions by Target')\n\n# Plot.\n\nsns.countplot(x='res',\n              hue='benign_malignant',\n              data=train,\n              order=train.res.value_counts().iloc[:12].index,\n              palette=orange_black,\n              ax=ax3)\nax3.legend()\n\n# Customizing the last grid.\n\nax4 = fig.add_subplot(grid[2, :])\n\n# Set the title.\n\nax4.set_title('Malignant Scan Result Frequency by Image Resolution')\n\n# Plot.\n\nres_freq = train.groupby('res')['target'].mean()\nres_freq = res_freq[(res_freq > 0) & (res_freq < 1)]\nsns.lineplot(x=res_freq.index, y=res_freq, palette=orange_black, ax=ax4)\nax4.legend()\n\nplt.show()\n\"\"\"\n# The Mysterious Images\n\nThe name 'Mystery' comes from Chris Deotte from the comments down below and I decided to investigate them further. In last part we found out a new set of images with the resolution of 1920x1080 and they aren't present in train data at all. So we can assume these images weren't selected randomly for this competition. Down below I'm going to compare them with the rest of data.\n\n* It looks like without the 1920x1080 set mean colors are much more similar between train and test.\n* Again image size distribution gets closer between train and test without the mystery set.\n\n\nGonna check other features and add them here soon...\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 14))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=3, nrows=3, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('RGB Channels of Train Images With \"Mysterious\" Set')\n\n# Plot.\n\nsns.distplot(train.reds,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='red',\n             kde=True,\n             ax=ax1,\n             label='Reds')\nsns.distplot(train.greens,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='green',\n             kde=True,\n             ax=ax1,\n             label='Greens')\nsns.distplot(train.blues,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='blue',\n             kde=True,\n             ax=ax1,\n             label='Blues')\n\nax1.legend()\n\n# Customizing the second grid.\n\nax2 = fig.add_subplot(grid[1, :2])\n\n# Set the title.\n\nax2.set_title('RGB Channels of Test Images Without \"Mysterious\" Set')\n\n# Plot\n\nsns.distplot(test[test['res'] != '1920x1080'].reds,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='red',\n             kde=True,\n             ax=ax2,\n             label='Reds')\nsns.distplot(test[test['res'] != '1920x1080'].greens,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='green',\n             kde=True,\n             ax=ax2,\n             label='Greens')\nsns.distplot(test[test['res'] != '1920x1080'].blues,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='blue',\n             kde=True,\n             ax=ax2,\n             label='Blues')\nax2.legend()\n\n# Customizing the third grid.\n\nax3 = fig.add_subplot(grid[:, 2])\n\n# Set the title.\n\nax3.set_title('Mean Colors by Train\/Test Images Without \"Mysterious\" Set')\n\n# Plot\n\nsns.kdeplot(train.mean_colors,\n            shade=True,\n            label='Train',\n            ax=ax3,\n            color='#171820',\n            vertical=True)\nsns.kdeplot(test[test['res'] != '1920x1080'].mean_colors,\n            shade=True,\n            label='Test',\n            ax=ax3,\n            color='#fdc029',\n            vertical=True)\nax3.legend()\n\n# Customizing the last grid.\n\nax2 = fig.add_subplot(grid[2, :2])\n\n# Set the title.\n\nax2.set_title('RGB Channels of \"Mysterious\" Set')\n\n# Plot\n\nsns.distplot(test[test['res'] == '1920x1080'].reds,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='red',\n             kde=True,\n             ax=ax2,\n             label='Reds')\nsns.distplot(test[test['res'] == '1920x1080'].greens,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='green',\n             kde=True,\n             ax=ax2,\n             label='Greens')\nsns.distplot(test[test['res'] == '1920x1080'].blues,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.3\n             },\n             color='blue',\n             kde=True,\n             ax=ax2,\n             label='Blues')\nax2.legend()\n\nplt.show()\n# Creating a customized chart and giving in figsize etc.\n\n# Plotting age dist vs target and age dist vs datasets\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Scan Image Size Distribution by Train\/Test Observations')\n\n# Plot\n\nax1.legend()\n\nsns.kdeplot(train['image_size'],\n            shade=True,\n            ax=ax1,\n            color='#171820',\n            label='Train')\nsns.kdeplot(test['image_size'],\n            shade=True,\n            ax=ax1,\n            color='#fdc029',\n            label='Test')\n\n# Customizing second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Set the title.\n\nax2.set_title('Scan Image Size Distribution Without \"Mysterious Set\"')\n\n# Plot.\n\nsns.kdeplot(train.image_size,\n            label='Train',\n            shade=True,\n            ax=ax2,\n            color='#171820')\nsns.kdeplot(test[test['res'] != '1920x1080'].image_size,\n            label='Test',\n            shade=True,\n            ax=ax2,\n            color='#fdc029')\nax2.legend()\n\n# Customizing third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Image Size Distribution of Mysterious Images')\n\n# Plot\n\nsns.distplot(test[test['res'] == '1920x1080'].image_size,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.9\n             },\n             color='#FF6347',\n             kde=True,\n             ax=ax3,\n             label='Mysterious Images')\nax3.legend()\n\nplt.show()\n\"\"\"\nI was curious about if these 1920x1080 images belong to high scan patients including 200+ one but it seems these observations are grouped around 10 scans, so it makes things more interesting...\n\"\"\"\n# Creating a customized chart and giving in figsize etc.\n\n# Plotting age dist vs target and age dist vs datasets\n\nfig = plt.figure(constrained_layout=True, figsize=(20, 12))\n\n# Creating a grid\n\ngrid = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)\n\n# Customizing the first grid.\n\nax1 = fig.add_subplot(grid[0, :2])\n\n# Set the title.\n\nax1.set_title('Number of Images Distribution by Train\/Test Observations')\n\n# Plot\n\nax1.legend()\n\nsns.kdeplot(train['n_images'],\n            shade=True,\n            ax=ax1,\n            color='#171820',\n            label='Train')\nsns.kdeplot(test['n_images'],\n            shade=True,\n            ax=ax1,\n            color='#fdc029',\n            label='Test')\n\n# Customizing second grid.\n\nax2 = fig.add_subplot(grid[0, 2:])\n\n# Set the title.\n\nax2.set_title('Scan Image Size Distribution Without \"Mysterious Set\"')\n\n# Plot.\n\nsns.kdeplot(train.n_images,\n            label='Train',\n            shade=True,\n            ax=ax2,\n            color='#171820')\nsns.kdeplot(test[test['res'] != '1920x1080'].n_images,\n            label='Test',\n            shade=True,\n            ax=ax2,\n            color='#fdc029')\nax2.legend()\n\n# Customizing third grid.\n\nax3 = fig.add_subplot(grid[1, :])\n\n# Set the title.\n\nax3.set_title('Number of Images Distribution of Mysterious Images')\n\n# Plot\n\nsns.distplot(test[test['res'] == '1920x1080'].n_images,\n             hist_kws={\n                 'rwidth': 0.75,\n                 'edgecolor': 'black',\n                 'alpha': 0.9\n             },\n             color='#FF6347',\n             kde=True,\n             ax=ax3,\n             label='Mysterious Images')\nax3.legend()\n\nplt.show()\n\"\"\"\nSince we checking this mystery patch of images, let's check other features about them too maybe we can find other factors effecting this test sampling...\n\"\"\"\nfig, ax = plt.subplots(figsize=(20, 6))\n\nsns.kdeplot(test[test['res'] != '1920x1080'].age,\n            shade=True,\n            label='Without Mystery Set',\n            color='#171820',\n            )\nsns.kdeplot(test[test['res'] == '1920x1080'].age,\n            shade=True,\n            label='With Mystery Set',\n            color='#fdc029',\n            )\n\nplt.legend(loc='upper right')\n\nax.set_title('Age Distribution With\/Without Mysterious Set')\n\n\nplt.show()\n\"\"\"\nLooks like our 1920x1080 set images consisting little bit younger patients than the rest. Interesting...\n\"\"\"\n\"\"\"\n# Visual Inspection of Mysterious Image Set\n\nThis is subjective, but when we look at both samples we can see that 1920x1080 images are coming from a 'imaging device' with black circle around the images? In general this isn't the case with the rest of the test image samples... Maybe we can use similar images from previous competitions for predicting this set? I don't know yet but worth to consider I guess...\n\"\"\"\nmystery = test[test['res'] == '1920x1080']\nmystimages = mystery['img_name'].values\n\nnonmystery = test[test['res'] != '1920x1080']\nnonmystimages = nonmystery['img_name'].values\n\nrandom_myst_images = [np.random.choice(mystimages+'.jpg') for i in range(12)]\nrandom_nmyst_images = [np.random.choice(nonmystimages+'.jpg') for i in range(12)]\n\n# Location of test images\nimg_dir = '..\/input\/siim-isic-melanoma-classification\/jpeg\/test'\nplt.figure(figsize=(12,6))\nfor i in range(12):\n    \n    plt.subplot(3, 4, i + 1)\n    img = plt.imread(os.path.join(img_dir, random_myst_images[i]))\n    plt.imshow(img, cmap='gray')\n    plt.axis('off')\n    \nplt.suptitle('Sample Images From Mysterious Test Set', fontsize=14)\nplt.tight_layout()   \n  \nplt.figure(figsize=(12,6))\nfor i in range(12):\n    \n    plt.subplot(3, 4, i + 1)\n    img = plt.imread(os.path.join(img_dir, random_nmyst_images[i]))\n    plt.imshow(img, cmap='gray')\n    plt.axis('off') \n    \nplt.suptitle('Sample Images From Rest of the Test Set', fontsize=14, y=1.05)\nplt.tight_layout()   \n\"\"\"\n# Correlations Between Features\n\"\"\"\n# Display numerical correlations between features on heatmap.\n\nsns.set(font_scale=1.1)\ncorrelation_train = train[['target','age','age_min',\n 'age_max',\n 'n_images',\n 'image_size',\n 'reds',\n 'greens',\n 'blues', \n 'width',\n 'height',\n ]].corr()\nmask = np.triu(correlation_train.corr())\nplt.figure(figsize=(16, 6))\nsns.heatmap(correlation_train,\n            annot=True,\n            fmt='.1f',\n            cmap='coolwarm',            \n            mask=mask,\n            linewidths=1,\n            cbar=False)\n\nplt.show()\n\n\n\"\"\"\n# Modelling Based on Tabular Meta Features\n\"\"\"\n\"\"\"\n## Getting Landscape Attributes from Images\n\nThanks to this great dataset by Marcelo Kittlein [here.](https:\/\/www.kaggle.com\/kittlein\/landscape)\n\"\"\"\n# Loading lanscape data\n\ntrain40 = pd.read_csv('..\/input\/melanoma2020imgtabular\/train40Features.csv')\ntest40 = pd.read_csv('..\/input\/melanoma2020imgtabular\/test40Features.csv')\n\ntrainmet = pd.read_csv('..\/input\/melanoma2020imgtabular\/trainMetrics.csv')\ntestmet = pd.read_csv('..\/input\/melanoma2020imgtabular\/testMetrics.csv')\n# # Dropping duplicate data from lanscape dataset\n\ntrain40.drop(['sex', 'age_approx', 'anatom_site_general_challenge'],\n             axis=1,\n             inplace=True)\n\ntest40.drop(['sex', 'age_approx', 'anatom_site_general_challenge'],\n            axis=1,\n            inplace=True)\n\n# merging both datasets\n\n\ntrain = pd.concat([train, train40, trainmet], axis=1)\ntest = pd.concat([test, test40, testmet], axis=1)\n# checking out new dataset\n\ntrain.head()\n\"\"\"\n# Getting Data Ready For ML Algorithms\n\"\"\"\n# getting dummy variables for gender on train set\n\nsex_dummies = pd.get_dummies(train['sex'], prefix='sex')\ntrain = pd.concat([train, sex_dummies], axis=1)\n\n# getting dummy variables for gender on test set\n\nsex_dummies = pd.get_dummies(test['sex'], prefix='sex')\ntest = pd.concat([test, sex_dummies], axis=1)\n\n# dropping not useful columns\n\ntrain.drop(['sex','res','img_name','id','diagnosis','benign_malignant'], axis=1, inplace=True)\ntest.drop(['sex','res','img_name','id'], axis=1, inplace=True)\n# getting dummy variables for location on train set\n\nanatom_dummies = pd.get_dummies(train['location'], prefix='anatom')\ntrain = pd.concat([train, anatom_dummies], axis=1)\n\n# getting dummy variables for location on test set\n\nanatom_dummies = pd.get_dummies(test['location'], prefix='anatom')\ntest = pd.concat([test, anatom_dummies], axis=1)\n\n# dropping not useful columns\n\ntrain.drop('location', axis=1, inplace=True)\ntest.drop('location', axis=1, inplace=True)\n\"\"\"\n# Loading Modelling Tools\n\"\"\"\n# loading modelling libraries\n\nimport xgboost as xgb\n\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, cross_val_score, cross_validate\nfrom sklearn.metrics import roc_auc_score, roc_curve\n# dividing train set and labels for modelling\n\nX = train.drop('target', axis=1)\ny = train.target\n\"\"\"\n## Setting Cross-Validation and Hold-out Set\n\nCross validation might be enough but I wanted to test our model on data which it never seen before.\n\"\"\"\n# taking holdout set for validating with stratified y\n\nX_train, X_test, y_train, y_test = train_test_split(X,\n                                                    y,\n                                                    test_size=0.2,\n                                                    stratify=y,\n                                                    random_state=42)\n\n# 5 fold stratify for cv\n\ncv = StratifiedKFold(5, shuffle=True, random_state=42)\n# setting model hyperparameters, didn't include fine tuning here because of timing reasons...\n\nxg = xgb.XGBClassifier(\n    n_estimators=750,\n    min_child_weight=0.81,\n    learning_rate=0.025,\n    max_depth=2,\n    subsample=0.80,\n    colsample_bytree=0.42,\n    gamma=0.10,\n    random_state=42,\n    n_jobs=-1,\n)\nestimators = [xg]\n# cross validation scheme\n\ndef model_check(X_train, y_train, estimators, cv):\n    model_table = pd.DataFrame()\n\n    row_index = 0\n    for est in estimators:\n\n        MLA_name = est.__class__.__name__\n        model_table.loc[row_index, 'Model Name'] = MLA_name\n\n        cv_results = cross_validate(est,\n                                    X_train,\n                                    y_train,\n                                    cv=cv,\n                                    scoring='roc_auc',\n                                    return_train_score=True,\n                                    n_jobs=-1)\n\n        model_table.loc[row_index,\n                        'Train roc Mean'] = cv_results['train_score'].mean()\n        model_table.loc[row_index,\n                        'Test roc Mean'] = cv_results['test_score'].mean()\n        model_table.loc[row_index, 'Test Std'] = cv_results['test_score'].std()\n        model_table.loc[row_index, 'Time'] = cv_results['fit_time'].mean()\n\n        row_index += 1\n\n    model_table.sort_values(by=['Test roc Mean'],\n                            ascending=False,\n                            inplace=True)\n\n    return model_table\n\"\"\"\n# Model Results Based on Meta Features\n\nResults are encouraging! It seems little bit overfitting but we might fix that in future by fine tuning. Let's leave it like that for now...\n\"\"\"\n# display cv results\n\nraw_models = model_check(X_train, y_train, estimators, cv)\ndisplay(raw_models)\n# fitting train data\n\nxg.fit(X_train, y_train)\n\n# predicting on holdout set\nvalidation = xg.predict_proba(X_test)[:, 1]\n\n# checking results on validation set\nroc_auc_score(y_test, validation)\n\"\"\"\n# Meta Feature Importances\n\nImage size seems pretty important on our model, but don't forget this can be misleading for final scoring. Don't forget about missing image sizes in test set and size correlation with targets in train data!\n\"\"\"\n# finding feature importances and creating new dataframe basen on them\n\nfeature_importance = xg.get_booster().get_score(importance_type='weight')\n\nkeys = list(feature_importance.keys())\nvalues = list(feature_importance.values())\n\nimportance = pd.DataFrame(data=values, index=keys,\n                          columns=['score']).sort_values(by='score',\n                                                         ascending=False)\nplt.figure(figsize=(16, 10))\nsns.barplot(x=importance.score.iloc[:20],\n            y=importance.index[:20],\n            orient='h',\n            palette='Reds_r')\n\nplt.show()\n\"\"\"\n# First Step: Creating Meta Submission\n\"\"\"\n# predicting on test set\n\npredictions = xg.predict_proba(test)[:, 1]\n# creating submission df\n\n\nmeta_df = pd.DataFrame(columns=['image_name', 'target'])\n\n# assigning predictions on submission df\n\nmeta_df['image_name'] = sample['image_name']\nmeta_df['target'] = predictions\n# creating submission csv file\n\nmeta_df.to_csv('meta_with_img_data.csv', header=True, index=False)\n\n\"\"\"\n### The .csv file above scores ~85% on public LB but our inspections on train\/test data shows it might be overfitting due to image differences, in next step we going try spot these features and make it little more robust...\n\"\"\"\n\"\"\"\n# Adversarial Validation\n\nAlright, since we have high doubts for train test sampling wanted to implement what is called 'Adversarial Validation'. For this we going to replace our targets for both datasets (0 for train and 1 for test), then we going build a classifier which tries to predict which observation belongs to train and which one belongs to test set. If datasets randomly selected from similar roots it should be really hard for the classifier to separate them. But if there is systematic selection differences between train and test sets then classifier should be able to capture this trend. So we want our models score lower for the next section because higher detection rate means higher difference between train and test datasets, so let's get started...\n\n\"\"\"\nadv_train = train.copy()\nadv_train.drop('target', axis=1, inplace=True)\nadv_test = test.copy()\n\nadv_train['dataset_label'] = 0\nadv_test['dataset_label'] = 1\n\nadv_master = pd.concat([adv_train, adv_test], axis=0)\n\nadv_X = adv_master.drop('dataset_label', axis=1)\nadv_y = adv_master['dataset_label']\nadv_X_train, adv_X_test, adv_y_train, adv_y_test = train_test_split(adv_X,\n                                                    adv_y,\n                                                    test_size=0.4,\n                                                    stratify=adv_y,\n                                                    random_state=42)\nxg_adv = xgb.XGBClassifier(\n    random_state=42,\n    n_jobs=-1,\n)\n\n# Fitting train data\n\nxg_adv.fit(adv_X_train, adv_y_train)\n\n# Predicting on holdout set\nvalidation = xg_adv.predict_proba(adv_X_test)[:,1]\ndef plot_roc_feat(y_trues, y_preds, labels, est, x_max=1.0):\n    fig, ax = plt.subplots(1,2, figsize=(16,6))\n    for i, y_pred in enumerate(y_preds):\n        y_true = y_trues[i]\n        fpr, tpr, thresholds = roc_curve(y_true, y_pred)\n        auc = roc_auc_score(y_true, y_pred)\n        ax[0].plot(fpr, tpr, label='%s; AUC=%.3f' % (labels[i], auc), marker='o', markersize=1)\n\n    ax[0].legend()\n    ax[0].grid()\n    ax[0].plot(np.linspace(0, 1, 20), np.linspace(0, 1, 20), linestyle='--')\n    ax[0].set_title('ROC curve')\n    ax[0].set_xlabel('False Positive Rate')\n    ax[0].set_xlim([-0.01, x_max])\n    _ = ax[0].set_ylabel('True Positive Rate')\n    \n    \n    feature_importance = est.get_booster().get_score(importance_type='weight')\n\n    keys = list(feature_importance.keys())\n    values = list(feature_importance.values())\n\n    importance = pd.DataFrame(data=values, index=keys,\n                          columns=['score']).sort_values(by='score',\n                                                         ascending=False)\n    \n    sns.barplot(x=importance.score.iloc[:20],\n            y=importance.index[:20],\n            orient='h',\n            palette='Reds_r', ax=ax[1])\n    ax[1].set_title('Feature Importances')\n\n\"\"\"\n## First Results\n\nWell... It seems our model can seperate train and test set pretty good. This is not good, when we look at our ROC Curve it almost scores 90%, whe should dig this further... So to find the reason behind it we check our model's feature importances and we see image related features are really affecting it. So this confirms our findings in EDA part that train test sets are selected systematically to some degree... In next part we gonna drop some of these features to see if we can rebuild more robust model...\n\"\"\"\nplot_roc_feat(\n    [adv_y_test],\n    [validation],\n    ['Baseline'],\n    xg_adv\n)\n\"\"\"\n## Let's drop image size and number related features to see if it's increase the randomness...\n\"\"\"\nadv_X.drop(['n_images', 'image_size','width','height','total_pixels','reds','blues','greens','mean_colors', 'age_min', 'age_max'], axis=1, inplace=True)\n\n\nadv_X_train, adv_X_test, adv_y_train, adv_y_test = train_test_split(adv_X,\n                                                    adv_y,\n                                                    test_size=0.4,\n                                                    stratify=adv_y,\n                                                    random_state=42)\n\n# fitting train data\n\nxg_adv.fit(adv_X_train, adv_y_train)\n\n# predicting on holdout set\nvalidation = xg_adv.predict_proba(adv_X_test)[:,1]\n\"\"\"\n## Well yeah, it did! The more close our AUC 50% the better, so for now we can continue what we have for now.\n\"\"\"\nplot_roc_feat(\n    [adv_y_test],\n    [validation],\n    ['Baseline'],\n    xg_adv\n)\nX_train.drop(['n_images', 'image_size','width','height','total_pixels','reds','blues','greens','mean_colors', 'age_min', 'age_max'], axis=1, inplace=True)\nX_test.drop(['n_images', 'image_size','width','height','total_pixels','reds','blues','greens','mean_colors', 'age_min', 'age_max'], axis=1, inplace=True)\n\ntest.drop(['n_images', 'image_size','width','height','total_pixels','reds','blues','greens','mean_colors', 'age_min', 'age_max'], axis=1, inplace=True)\n\"\"\"\n# Simplified Meta Predictions\n\nWe're going build our model with less biased features now. I wouldn't recommend submitting these predictions since you have limited submissions. These are for ensembling...\n\"\"\"\nxg= xgb.XGBClassifier(\n    n_estimators=750,\n    learning_rate=0.015,\n    min_child_weight= 218,\n    max_delta_step= 4,\n    max_depth= 2,\n    subsample= 0.751,\n    colsample_bytree= 0.77,\n    gamma= 24,\n    reg_lambda= 11,\n    random_state=42,\n    n_jobs=-1,\n)\n# display cv results\n\nraw_models = model_check(X_train, y_train, [xg], cv)\ndisplay(raw_models)\n# fitting train data\n\nxg.fit(X_train, y_train)\n\npredictions = xg.predict_proba(test)[:, 1]\n\nmeta_df = pd.DataFrame(columns=['image_name', 'target'])\n\n# assigning predictions on submission df\n\nmeta_df['image_name'] = sample['image_name']\nmeta_df['target'] = predictions\n\n# creating submission csv file\n\nmeta_df.to_csv('meta_simplified_img_data.csv', header=True, index=False)\n\n\"\"\"\n# End of Tabular Data Part\n\n### This simple approach including basic info as tabular data with good old ML algoithms gave me LB score of 0.8484! \n\n### Update: Since we spotted some important differences between train and test set I wanted to create less biased version of the meta .csv file so I added it here, it score less but would perform better on the ensembles you make...\n\n\"\"\"\n\"\"\"\n# Machine Learning to Neural Networks\n\nThis part we gonna train more complicated models by using images themselves. For this part I was inspired by AgentAuers's 'Incredible TPUs' [here](https:\/\/www.kaggle.com\/agentauers\/incredible-tpus-finetune-effnetb0-b6-at-once). It's a great notebook and you should check that, again thanks for AgentAuers for letting me use some of his code as baseline for this part of the notebook! Also thanks to Chris Deotte for great datasets with tfrecords! \n\nWe start by importing neccesary packages and setting random seed.\n\"\"\"\n# Importing packages\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\nfrom kaggle_datasets import KaggleDatasets\n\ntf.random.set_seed(seed_val)\n# Loading image storage buckets\n\nGCS_PATH = KaggleDatasets().get_gcs_path('melanoma-384x384')\nfilenames_train = np.array(tf.io.gfile.glob(GCS_PATH + '\/train*.tfrec'))\nfilenames_test = np.array(tf.io.gfile.glob(GCS_PATH + '\/test*.tfrec'))\n# Setting TPU as main device for training, if you get warnings while working with tpu's ignore them.\n\nDEVICE = 'TPU'\nif DEVICE == 'TPU':\n    print('connecting to TPU...')\n    try:        \n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print('Could not connect to TPU')\n        tpu = None\n\n    if tpu:\n        try:\n            print('Initializing  TPU...')\n            tf.config.experimental_connect_to_cluster(tpu)\n            tf.tpu.experimental.initialize_tpu_system(tpu)\n            strategy = tf.distribute.experimental.TPUStrategy(tpu)\n            print('TPU initialized')\n        except _:\n            print('Failed to initialize TPU!')\n    else:\n        DEVICE = 'GPU'\n\nif DEVICE != 'TPU':\n    print('Using default strategy for CPU and single GPU')\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == 'GPU':\n    print('Num GPUs Available: ',\n          len(tf.config.experimental.list_physical_devices('GPU')))\n\nprint('REPLICAS: ', strategy.num_replicas_in_sync)\nAUTO = tf.data.experimental.AUTOTUNE\n\"\"\"\nHere we set config for our next steps. You can play with these but mind the memory sizes with the batches & image sizes.\n\"\"\"\ncfg = dict(\n           batch_size=32,\n           img_size=384,\n    \n           lr_start=0.000005,\n           lr_max=0.00000125,\n           lr_min=0.000001,\n           lr_rampup=5,\n           lr_sustain=0,\n           lr_decay=0.8,\n           epochs=12,\n    \n           transform_prob=1.0,\n           rot=180.0,\n           shr=2.0,\n           hzoom=8.0,\n           wzoom=8.0,\n           hshift=8.0,\n           wshift=8.0,\n    \n           optimizer='adam',\n           label_smooth_fac=0.05,\n           tta_steps=20\n            \n        )\ndef get_mat(rotation, shear, height_zoom, width_zoom, height_shift,\n            width_shift):\n    \n    ''' Settings for image preparations '''\n\n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation \/ 180.\n    shear = math.pi * shear \/ 180.\n\n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1], dtype='float32')\n    zero = tf.constant([0], dtype='float32')\n    rotation_matrix = tf.reshape(\n        tf.concat([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0),\n        [3, 3])\n\n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape(\n        tf.concat([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0),\n        [3, 3])\n\n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape(\n        tf.concat([\n            one \/ height_zoom, zero, zero, zero, one \/ width_zoom, zero, zero,\n            zero, one\n        ],\n                  axis=0), [3, 3])\n\n    # SHIFT MATRIX\n    shift_matrix = tf.reshape(\n        tf.concat(\n            [one, zero, height_shift, zero, one, width_shift, zero, zero, one],\n            axis=0), [3, 3])\n\n    return K.dot(K.dot(rotation_matrix, shear_matrix),\n                 K.dot(zoom_matrix, shift_matrix))\n\n\ndef transform(image, cfg):\n    \n    ''' This function takes input images of [: , :, 3] sizes and returns them as randomly rotated, sheared, shifted and zoomed. '''\n\n    DIM = cfg['img_size']\n    XDIM = DIM % 2  # fix for size 331\n\n    rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n    shr = cfg['shr'] * tf.random.normal([1], dtype='float32')\n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') \/ cfg['hzoom']\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') \/ cfg['wzoom']\n    h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32')\n    w_shift = cfg['wshift'] * tf.random.normal([1], dtype='float32')\n\n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot, shr, h_zoom, w_zoom, h_shift, w_shift)\n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat(tf.range(DIM \/\/ 2, -DIM \/\/ 2, -1), DIM)\n    y = tf.tile(tf.range(-DIM \/\/ 2, DIM \/\/ 2), [DIM])\n    z = tf.ones([DIM * DIM], dtype='int32')\n    idx = tf.stack([x, y, z])\n\n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m, tf.cast(idx, dtype='float32'))\n    idx2 = K.cast(idx2, dtype='int32')\n    idx2 = K.clip(idx2, -DIM \/\/ 2 + XDIM + 1, DIM \/\/ 2)\n\n    # FIND ORIGIN PIXEL VALUES\n    idx3 = tf.stack([DIM \/\/ 2 - idx2[0, ], DIM \/\/ 2 - 1 + idx2[1, ]])\n    d = tf.gather_nd(image, tf.transpose(idx3))\n\n    return tf.reshape(d, [DIM, DIM, 3])\n\ndef prepare_image(img, cfg=None, augment=True):\n    \n    ''' This function loads the image, resizes it, casts a tensor to a new type float32 in our case, transforms it using the function just above, then applies the augmentations.'''\n    \n    img = tf.image.decode_jpeg(img, channels=3)\n    img = tf.image.resize(img, [cfg['img_size'], cfg['img_size']],\n                          antialias=True)\n    img = tf.cast(img, tf.float32) \/ 255.0\n\n    if augment:\n        if cfg['transform_prob'] > tf.random.uniform([1], minval=0, maxval=1):\n            img = transform(img, cfg)\n\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_saturation(img, 0.7, 1.3)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_brightness(img, 0.1)\n\n    return img\n\"\"\"\nThese functions below for reading labeled tfrecords.\n\"\"\"\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'image_name': tf.io.FixedLenFeature([], tf.string),\n        'patient_id': tf.io.FixedLenFeature([], tf.int64),\n        'sex': tf.io.FixedLenFeature([], tf.int64),\n        'age_approx': tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n        'diagnosis': tf.io.FixedLenFeature([], tf.int64),\n        'target': tf.io.FixedLenFeature([], tf.int64),\n        'width': tf.io.FixedLenFeature([], tf.int64),\n        'height': tf.io.FixedLenFeature([], tf.int64)\n    }\n\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    return example['image'], example['target']\n\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'image_name': tf.io.FixedLenFeature([], tf.string),\n        'patient_id': tf.io.FixedLenFeature([], tf.int64),\n        'sex': tf.io.FixedLenFeature([], tf.int64),\n        'age_approx': tf.io.FixedLenFeature([], tf.int64),\n        'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    return example['image'], example['image_name']\n\ndef count_data_items(filenames):\n    n = [\n        int(re.compile(r'-([0-9]*)\\.').search(filename).group(1))\n        for filename in filenames\n    ]\n    return np.sum(n)\ndef getTrainDataset(files, cfg, augment=True, shuffle=True):\n    \n    ''' This function reads the tfrecord train images, shuffles them, apply augmentations to them and prepares the data for training. '''\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n\n    if shuffle:\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n\n    ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    ds = ds.repeat()\n    if shuffle:\n        ds = ds.shuffle(2048)\n    ds = ds.map(lambda img, label:\n                (prepare_image(img, augment=augment, cfg=cfg), label),\n                num_parallel_calls=AUTO)\n    ds = ds.batch(cfg['batch_size'] * strategy.num_replicas_in_sync)\n    ds = ds.prefetch(AUTO)\n    return ds\n\ndef getTestDataset(files, cfg, augment=False, repeat=False):\n    \n    ''' This function reads the tfrecord test images and prepares the data for predicting. '''\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n    if repeat:\n        ds = ds.repeat()\n    ds = ds.map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    ds = ds.map(lambda img, idnum:\n                (prepare_image(img, augment=augment, cfg=cfg), idnum),\n                num_parallel_calls=AUTO)\n    ds = ds.batch(cfg['batch_size'] * strategy.num_replicas_in_sync)\n    ds = ds.prefetch(AUTO)\n    return ds\n\ndef get_model():\n    \n    ''' This function gets the layers inclunding efficientnet ones. '''\n    \n    model_input = tf.keras.Input(shape=(cfg['img_size'], cfg['img_size'], 3),\n                                 name='img_input')\n\n    dummy = tf.keras.layers.Lambda(lambda x: x)(model_input)\n\n    outputs = []\n    \n    x = efn.EfficientNetB2(include_top=False,\n                           weights='noisy-student',\n                           input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                           pooling='avg')(dummy)\n    x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n    outputs.append(x)\n\n    x = efn.EfficientNetB3(include_top=False,\n                           weights='noisy-student',\n                           input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                           pooling='avg')(dummy)\n    x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n    outputs.append(x)\n\n    x = efn.EfficientNetB4(include_top=False,\n                           weights='noisy-student',\n                           input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                           pooling='avg')(dummy)\n    x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n    outputs.append(x)\n\n    x = efn.EfficientNetB5(include_top=False,\n                           weights='noisy-student',\n                           input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                           pooling='avg')(dummy)\n    x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n    outputs.append(x)\n    \n    model = tf.keras.Model(model_input, outputs, name='aNetwork')\n    model.summary()\n    return model\ndef compileNewModel(cfg):\n    \n    ''' Configuring the model with losses and metrics. '''    \n    \n    with strategy.scope():\n        model = get_model()\n\n    with strategy.scope():\n        model.compile(optimizer=cfg['optimizer'],\n                      loss=[\n                          tf.keras.losses.BinaryCrossentropy(\n                              label_smoothing=cfg['label_smooth_fac']),\n                          tf.keras.losses.BinaryCrossentropy(\n                              label_smoothing=cfg['label_smooth_fac']),\n                          tf.keras.losses.BinaryCrossentropy(\n                              label_smoothing=cfg['label_smooth_fac']),\n                          tf.keras.losses.BinaryCrossentropy(\n                              label_smoothing=cfg['label_smooth_fac'])\n                      ],\n                      metrics=[tf.keras.metrics.AUC(name='auc')])\n    return model\n\ndef getLearnRateCallback(cfg):\n    \n    ''' Using callbacks for learning rate adjustments. '''\n    \n    lr_start = cfg['lr_start']\n    lr_max = cfg['lr_max'] * strategy.num_replicas_in_sync * cfg['batch_size']\n    lr_min = cfg['lr_min']\n    lr_rampup = cfg['lr_rampup']\n    lr_sustain = cfg['lr_sustain']\n    lr_decay = cfg['lr_decay']\n\n    def lrfn(epoch):\n        if epoch < lr_rampup:\n            lr = (lr_max - lr_start) \/ lr_rampup * epoch + lr_start\n        elif epoch < lr_rampup + lr_sustain:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_rampup -\n                                                lr_sustain) + lr_min\n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback\n\ndef learnModel(model, ds_train, stepsTrain, cfg, ds_val=None, stepsVal=0):\n    \n    ''' Fitting things together for training '''\n    \n    callbacks = [getLearnRateCallback(cfg)]\n\n    history = model.fit(ds_train,\n                        validation_data=ds_val,\n                        verbose=1,\n                        steps_per_epoch=stepsTrain,\n                        validation_steps=stepsVal,\n                        epochs=cfg['epochs'],\n                        callbacks=callbacks)\n\n    return history\n\"\"\"\nHere we train our model, takes a while but at the end we'll have strong model to make predictions!\n\"\"\"\nds_train = getTrainDataset(\n    filenames_train, cfg).map(lambda img, label: (img, (label, label, label, label)))\nstepsTrain = count_data_items(filenames_train) \/ \\\n    (cfg['batch_size'] * strategy.num_replicas_in_sync)\n\nmodel = compileNewModel(cfg)\nlearnModel(model, ds_train, stepsTrain, cfg)\n\"\"\"\nHere we make predictions using the model we trained. Then we blend them for each EffNet by taking mean. We create csv file for each prediction including blended one.\n\"\"\"\nsteps = count_data_items(filenames_test) \/ \\\n    (cfg['batch_size'] * strategy.num_replicas_in_sync)\nz = np.zeros((cfg['batch_size'] * strategy.num_replicas_in_sync))\nds_testAug = getTestDataset(\n    filenames_test, cfg, augment=True,\n    repeat=True).map(lambda img, label: (img, (z, z, z, z)))\nprobs = model.predict(ds_testAug, verbose=1, steps=steps * cfg['tta_steps'])\nprobs = np.stack(probs)\nprobs = probs[:, :count_data_items(filenames_test) * cfg['tta_steps']]\nprobs = np.stack(np.split(probs, cfg['tta_steps'], axis=1), axis=1)\nprobs = np.mean(probs, axis=1)\n\ntest = pd.read_csv(os.path.join(base_path, 'test.csv'))\ny_test_sorted = np.zeros((5, probs.shape[1]))\ntest = test.reset_index()\ntest = test.set_index('image_name')\n\ni = 0\nds_test = getTestDataset(filenames_test, cfg)\nfor img, imgid in tqdm(iter(ds_test.unbatch())):\n    imgid = imgid.numpy().decode('utf-8')\n    y_test_sorted[:, test.loc[imgid]['index']] = probs[:, i, 0]\n    i += 1\n\nfor i in range(y_test_sorted.shape[0]):\n    submission = sample\n    submission['target'] = y_test_sorted[i]\n    submission.to_csv('submission_model_%s.csv' % i, index=False)\n\nsubmission = sample\nsubmission['target'] = np.mean(y_test_sorted, axis=0)\nsubmission.to_csv('blended_effnets.csv', index=False)\n\"\"\"\n# Ensembling With Meta\n\nHere's the last step. We'll use our blended predictions created by training images and simply metadata created by using tabular data. We ensemble them together with weights and make our final predictions. Feel free to experiment with ensembling. This basic blending increased my LB score a little, you can change lots of things in previous steps to do some experiments, it's fun!\n\"\"\"\neffnet = pd.read_csv('.\/blended_effnets.csv')\nmeta = pd.read_csv('.\/meta_simplified_img_data.csv')\n\n\nsample['target'] = (\n                           \n                           effnet['target'] * 0.9 +\n                           meta['target'] * 0.1 \n                          \n                          )\n\nsample.to_csv('ensembled.csv', header=True, index=False)\n\"\"\"\n# Submission and Some Notes\n\nAgain I wanted to thank to kaggle community for inspiring me for this approach. I'm still learning and working on these notebooks helping me a lot, I hope these can be helpful you too! About the notebook itself next step would be implementing a cross validation scheme and test your predictions on it, if you find sweet spot that both increases your CV and LB scores then you are on the right track! But I'll leave this notebook here for now, thank you all for reading!\n\"\"\"\nsample.head()\n\"\"\"\n\n\n<div align='center'><font size='6' color='#000000'>Final Words<\/font><\/div>\n\n<hr>\n\n<div align='center'><font size='4' color='#000000'>This notebook still in progress and if you have any feedbacks please leave me a comment I'll be reading them for sure and if you liked my work please don't forget to leave an upvote. Thank you for reading!<\/font><\/div>\n\n<hr>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '08602fa7fb66b2'}"}
{"id":"133611","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nimport datetime\nimport os\nprint(os.listdir(\"..\/input\"))\nimport numpy as np\nimport pandas as pd \nfrom collections import defaultdict\nfrom pprint import pprint\nimport xgboost as xgb\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom keras.utils import plot_model\nmatplotlib.rcParams['figure.figsize'] = (8, 6)\n\nimport keras\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nseed = 0\nnp.random.seed(seed)\n\nfrom ann_visualizer.visualize import ann_viz\n\n# Any results you write to the current directory are saved as output.\nstart_time = datetime.datetime.now()\n\ndemographic_cols = ['ncodpers','fecha_alta','ind_empleado','pais_residencia','sexo','age','ind_nuevo','antiguedad','indrel',\n 'indrel_1mes','tiprel_1mes','indresi','indext','conyuemp','canal_entrada','indfall',\n 'tipodom','cod_prov','ind_actividad_cliente','renta','segmento']\n\nnotuse = [\"ult_fec_cli_1t\",\"nomprov\",'fecha_dato']\n\nproduct_col = [\n 'ind_ahor_fin_ult1','ind_aval_fin_ult1','ind_cco_fin_ult1','ind_cder_fin_ult1','ind_cno_fin_ult1','ind_ctju_fin_ult1',\n 'ind_ctma_fin_ult1','ind_ctop_fin_ult1','ind_ctpp_fin_ult1','ind_deco_fin_ult1','ind_deme_fin_ult1',\n 'ind_dela_fin_ult1','ind_ecue_fin_ult1','ind_fond_fin_ult1','ind_hip_fin_ult1','ind_plan_fin_ult1',\n 'ind_pres_fin_ult1','ind_reca_fin_ult1','ind_tjcr_fin_ult1','ind_valo_fin_ult1','ind_viv_fin_ult1','ind_nomina_ult1',\n 'ind_nom_pens_ult1','ind_recibo_ult1']\n\"\"\"\n# Import Data\n\"\"\"\ndf_train = pd.read_csv('..\/input\/datamulticlass-6-withpast2\/DataMulticlass_6_withpast2.csv')\ndf_test = pd.read_csv('..\/input\/testset-withpast3\/TestSet_withpast3.csv')\npd.set_option('display.max_columns', None)\n\"\"\"\n# Clean Data\n\"\"\"\n\"\"\"\n### Filter Data\n\"\"\"\ndef filter_data(df):\n    df = df[df['ind_nuevo'] == 0]\n    df = df[df['antiguedad'] != -999999]\n    df = df[df['indrel'] == 1]\n    df = df[df['indresi'] == 'S']\n    df = df[df['indfall'] == 'N']\n    df = df[df['tipodom'] == 1]\n    df = df[df['ind_empleado'] == 'N']\n    df = df[df['pais_residencia'] == 'ES']\n    df = df[df['indrel_1mes'] == 1]\n    df = df[df['tiprel_1mes'] == ('A' or 'I')]\n    df = df[df['indext'] == 'N']\nfilter_data(df_train)\n\"\"\"\n### Drop unneccessary column\n\"\"\"\ndrop_column = ['ind_nuevo','indrel','indresi','indfall','tipodom','ind_empleado','pais_residencia','indrel_1mes','indext','conyuemp','fecha_alta','tiprel_1mes']\n\ndf_train.drop(drop_column, axis=1, inplace = True)\ndf_test.drop(drop_column, axis=1, inplace = True)\n\"\"\"\n### Add missing income\n\"\"\"\ndf_test[\"renta\"]   = pd.to_numeric(df_test[\"renta\"], errors=\"coerce\")\nunique_prov = df_test[df_test.cod_prov.notnull()].cod_prov.unique()\ngrouped = df_test.groupby(\"cod_prov\")[\"renta\"].median()\n\ndef impute_renta(df):\n    df[\"renta\"]   = pd.to_numeric(df[\"renta\"], errors=\"coerce\")       \n    for cod in unique_prov:\n        df.loc[df['cod_prov']==cod,['renta']] = df.loc[df['cod_prov']==cod,['renta']].fillna({'renta':grouped[cod]}).values\n    df.renta.fillna(df_test[\"renta\"].median(), inplace=True)\n    \nimpute_renta(df_train)\nimpute_renta(df_test)\ndef drop_na(df):\n    df.dropna(axis = 0, subset = ['ind_actividad_cliente'], inplace = True)\n    \ndrop_na(df_train)\n\"\"\"\n### Convert and make dummy\n\"\"\"\n# These column are categories feature, I'll transform them using get_dummy\ndummy_col = ['sexo','canal_entrada','cod_prov','segmento']\ndummy_col_select = ['canal_entrada','cod_prov']\nlimit = int(0.01 * len(df_train.index))\nuse_dummy_col = {}\n\nfor col in dummy_col_select:\n    trainlist = df_train[col].value_counts()\n    use_dummy_col[col] = []\n    for i,item in enumerate(trainlist):\n        if item > limit:\n            use_dummy_col[col].append(df_train[col].value_counts().index[i])   \ndef get_dummy(df):\n    for col in dummy_col_select:\n        for item in df[col].unique(): \n            if item not in use_dummy_col[col]:\n                row_index = df[col] == item\n                df.loc[row_index,col] = np.nan\n    return pd.get_dummies(df, prefix=dummy_col, columns = dummy_col)\n    \ndf_train = get_dummy(df_train)\ndf_test = get_dummy(df_test)\ndef clean_age(df):\n    df[\"age\"]   = pd.to_numeric(df[\"age\"], errors=\"coerce\")\n    max_age = 80 \n\n    df[\"age\"]   = df['age'].apply(lambda x: min(x ,max_age))\n    df[\"age\"]   = df['age'].apply(lambda x: round( x\/max_age, 6))\n\ndef clean_renta(df):\n    max_renta = 1.0e6\n\n    df[\"renta\"]   = df['renta'].apply(lambda x: min(x ,max_renta))\n    df[\"renta\"]   = df['renta'].apply(lambda x: round( x\/max_renta, 6))\n    \ndef clean_antigue(df):\n    df[\"antiguedad\"]   = pd.to_numeric(df[\"antiguedad\"], errors=\"coerce\")\n    df[\"antiguedad\"] = df[\"antiguedad\"].replace(-999999, df['antiguedad'].median())\n    max_antigue = 256\n\n    df[\"antiguedad\"]   = df['antiguedad'].apply(lambda x: min(x ,max_antigue))\n    df[\"antiguedad\"]   = df['antiguedad'].apply(lambda x: round( x\/max_antigue, 6))  \nclean_age(df_train)\nclean_age(df_test)\n\nclean_renta(df_train)\nclean_renta(df_test)\n\nclean_antigue(df_train)\nclean_antigue(df_test)\n\nproduct_col_5 = [col for col in df_train.columns if '_ult1_5' in col]\nproduct_col_4 = [col for col in df_train.columns if '_ult1_4' in col]\nproduct_col_3 = [col for col in df_train.columns if '_ult1_3' in col]\nproduct_col_2 = [col for col in df_train.columns if '_ult1_2' in col]\nproduct_col_1 = [col for col in df_train.columns if '_ult1_1' in col]\n\ndf_train['tot5'] = df_train[product_col_5].sum(axis=1)\ndf_test['tot5'] = df_test[product_col_5].sum(axis=1)\ndf_train['tot4'] = df_train[product_col_4].sum(axis=1)\ndf_test['tot4'] = df_test[product_col_4].sum(axis=1)\ndf_train['tot3'] = df_train[product_col_3].sum(axis=1)\ndf_test['tot3'] = df_test[product_col_3].sum(axis=1)\ndf_train['tot2'] = df_train[product_col_2].sum(axis=1)\ndf_test['tot2'] = df_test[product_col_2].sum(axis=1)\ndf_train['tot1'] = df_train[product_col_1].sum(axis=1)\ndf_test['tot1'] = df_test[product_col_1].sum(axis=1)\nfor col in product_col[2:]:\n    df_train[col+'_past'] = (df_train[col+'_5']+df_train[col+'_4']+df_train[col+'_3']+df_train[col+'_2']+df_train[col+'_1'])\/5\n    df_test[col+'_past'] = (df_test[col+'_5']+df_test[col+'_4']+df_test[col+'_3']+df_test[col+'_2']+df_test[col+'_1'])\/5\nfor pro in product_col[2:]:\n    df_train[pro+'_past'] = df_train[pro+'_past']*(1-df_train[pro+'_5'])\n    df_test[pro+'_past'] = df_test[pro+'_past']*(1-df_test[pro+'_5'])\nfor col in product_col[2:]:\n    for month in range(2,6):\n        df_train[col+'_'+str(month)+'_diff'] = df_train[col+'_'+str(month)] - df_train[col+'_'+str(month-1)]\n        df_test[col+'_'+str(month)+'_diff'] = df_test[col+'_'+str(month)] - df_test[col+'_'+str(month-1)]\n        df_train[col+'_'+str(month)+'_add'] = df_train[col+'_'+str(month)+'_diff'].apply(lambda x: max(x,0))\n        df_test[col+'_'+str(month)+'_add'] = df_test[col+'_'+str(month)+'_diff'].apply(lambda x: max(x,0))\nproduct_col_5_diff = [col for col in df_train.columns if '5_diff' in col]\nproduct_col_4_diff = [col for col in df_train.columns if '4_diff' in col]\nproduct_col_3_diff = [col for col in df_train.columns if '3_diff' in col]\nproduct_col_2_diff = [col for col in df_train.columns if '2_diff' in col]\n\nproduct_col_5_add = [col for col in df_train.columns if '5_add' in col]\nproduct_col_4_add = [col for col in df_train.columns if '4_add' in col]\nproduct_col_3_add = [col for col in df_train.columns if '3_add' in col]\nproduct_col_2_add = [col for col in df_train.columns if '2_add' in col]\n\nproduct_col_all_diff = [col for col in df_train.columns if '_diff' in col]\nproduct_col_all_add = [col for col in df_train.columns if '_add' in col]\ndf_train['tot5_add'] = df_train[product_col_5_add].sum(axis=1)\ndf_test['tot5_add'] = df_test[product_col_5_add].sum(axis=1)\ndf_train['tot4_add'] = df_train[product_col_4_add].sum(axis=1)\ndf_test['tot4_add'] = df_test[product_col_4_add].sum(axis=1)\ndf_train['tot3_add'] = df_train[product_col_3_add].sum(axis=1)\ndf_test['tot3_add'] = df_test[product_col_3_add].sum(axis=1)\ndf_train['tot2_add'] = df_train[product_col_2_add].sum(axis=1)\ndf_test['tot2_add'] = df_test[product_col_2_add].sum(axis=1)\ndf_train.head()\ndf_test.head()\ncols = list(df_train.drop(['target','ncodpers']+product_col_all_diff+product_col_all_add, 1).columns.values)\n\nid_preds = defaultdict(list)\nids = df_test['ncodpers'].values\n\n# predict model \ny_train = pd.get_dummies(df_train['target'].astype(int))\nx_train = df_train[cols]\n\"\"\"\n# Model\n\"\"\"\n# create model\nmodel = Sequential()\nmodel.add(Dense(150, input_dim=len(cols), activation='relu'))\nmodel.add(Dense(22, activation='softmax'))\n# Compile model\nmodel.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=['categorical_accuracy'])\n\nmodel.fit(x_train.as_matrix(), y_train.as_matrix(), validation_split=0.2, nb_epoch=150, batch_size=10)\n#model.fit(x_train.as_matrix(), y_train.as_matrix(), nb_epoch=150, batch_size=10)\n\nx_test = df_test[cols]\nx_test = x_test.fillna(0) \n        \np_test = model.predict(x_test.as_matrix())\n        \nfor id, p in zip(ids, p_test):\n    #id_preds[id] = list(p)\n    id_preds[id] = [0,0] + list(p)\nlen(cols)\nx_train\nmodel.inputs\nmodel.summary()\nmodel.outputs\ncustomer=list(id_preds.keys())\nfraction = 1\nid_preds_combined = {}\n\nfor uid, p in id_preds.items():\n    id_preds_combined[uid] = fraction*np.asarray(id_preds[uid])\n    \nid_preds = id_preds_combined    \n\"\"\"\n# Make submission\n\"\"\"\nusecols = ['ncodpers', 'ind_ahor_fin_ult1', 'ind_aval_fin_ult1', 'ind_cco_fin_ult1',\n       'ind_cder_fin_ult1', 'ind_cno_fin_ult1', 'ind_ctju_fin_ult1',\n       'ind_ctma_fin_ult1', 'ind_ctop_fin_ult1', 'ind_ctpp_fin_ult1',\n       'ind_deco_fin_ult1', 'ind_deme_fin_ult1', 'ind_dela_fin_ult1',\n       'ind_ecue_fin_ult1', 'ind_fond_fin_ult1', 'ind_hip_fin_ult1',\n       'ind_plan_fin_ult1', 'ind_pres_fin_ult1', 'ind_reca_fin_ult1',\n       'ind_tjcr_fin_ult1', 'ind_valo_fin_ult1', 'ind_viv_fin_ult1',\n       'ind_nomina_ult1', 'ind_nom_pens_ult1', 'ind_recibo_ult1']\ndf_recent =  pd.read_csv('..\/input\/train-ver2\/train_ver2.csv',usecols=usecols)\ndf_recent=df_recent[df_recent['ncodpers'].isin(customer)]\ndf_recent.fillna(0, inplace=True)\nsample = pd.read_csv('..\/input\/sample-submission\/sample_submission.csv')\n# check if customer already have each product or not. \nalready_active = {}\nfor row in df_recent.values:\n    row = list(row)\n    id = row.pop(0)\n    active = [c[0] for c in zip(tuple(product_col), row) if c[1] > 0]\n    already_active[id] = active\n\n# add 7 products(that user don't have yet), higher probability first -> train_pred   \ntrain_preds = {}\nfor id, p in id_preds.items():\n    preds = [i[0] for i in sorted([i for i in zip(tuple(product_col), p) if i[0] not in already_active[id]],\n                                  key=lambda i:i [1], \n                                  reverse=True)[:7]]\n    train_preds[id] = preds\n    \ntest_preds = []\nfor row in sample.values:\n    id = row[0]\n    p = train_preds[id]\n    test_preds.append(' '.join(p))\n\nprint(model.summary())\nmodel.save('kerass.model')\nplot_model(model,show_shapes=True, to_file='model1.png')\n#ann_viz(model, title='Neural Network Model')\nsample['added_products'] = test_preds\nsample.to_csv('Keras1.csv', index=False)\nprint(datetime.datetime.now()-start_time)","meta":"{'source': 'AI4Code', 'id': 'f5b68eef00d3f3'}"}
{"id":"33087","text":"\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:SlateBlue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n\n<span style='padding: 10px; font-family:Helvetica; font-size:30px' > Seoul Bike Rents <\/span>\n<\/div>\n\"\"\"\n\"\"\"\n![Bikes-2.jpg](attachment:8a240da6-f22a-4b05-a431-d7cd1cf16ad8.jpg)\n\"\"\"\n\"\"\"\nwelcome to our nootbook about Seoul Bike Rental dataset\n\nin this nootbook we will try to show some insights about the features in this dataset by visualize them, the Exploration will go into **3** steps:\n\n> **1- Univariate Exploration**\n\n> **2- Bivariate Exploration**\n\n> **3- Multivariate Exploration**\n\nalso we will create a **model** that predict the number of bikes rented over 2017 and 2018 in seoul\n\nif you have any suggest,advice or correction please don't hesitate to write it, it will be very helpful for me \n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt \nimport seaborn as sns\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\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n### First, let's take a quick look on the dataset\n\"\"\"\ntrain = pd.read_csv('..\/input\/seoul-bike-rental-ai-pro-iti\/train.csv')\ntest = pd.read_csv('..\/input\/seoul-bike-rental-ai-pro-iti\/test.csv')\nsample_submission = pd.read_csv('..\/input\/seoul-bike-rental-ai-pro-iti\/sample_submission.csv')\n\ntrain.head(2)\ntrain.info()\n\"\"\"\n### now let's preprocess some features before starting\n\"\"\"\ntrain.Date = pd.to_datetime(train.Date, format='%d\/%m\/%Y')\ntrain['year'] = train.Date.dt.year\ntrain['Rainfall(cm)'] = train['Rainfall(mm)'] \/ 10\n#------------------------------------------------------------\ntrain['Seasons'] = train['Seasons'].astype('category')\ntrain['Holiday'] = train['Holiday'].astype('category')\ntrain['Functioning Day'] = train['Functioning Day'].astype('category')\ntrain.info()\ntrain.isnull().sum()\n\"\"\"\n### Here, we can detect outlier's with boxplot\n\"\"\"\ntrain.describe()\nplt.figure(figsize=(15, 5))\n\nsns.boxplot(data = train)\n\nplt.tick_params(axis='x', rotation=30)\n\nplt.yscale('symlog')\n\n\"\"\"\n### as we can see **Rainfall** and **Snowfall** has alot of outliers\n\"\"\"\n\"\"\"\n### great, all set to go\n\"\"\"\n\"\"\"\n## 1- Univariate Exploration\n\"\"\"\n\"\"\"\n### first we will see the distribution of the categorical features \n\"\"\"\nimport plotly.express as px\n%matplotlib inline\nimport cufflinks as cf\n# Make Plotly work in your Jupyter Notebook\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)\nimport plotly.graph_objects as go\n# Use Plotly locally\ncf.go_offline()\n\n\npx.pie(train, names='Seasons', \n       title='categories of  seasons', \n       color_discrete_sequence=px.colors.sequential.Reds, hole=.3)\n\n px.pie(train, names='Holiday', \n        title=('categories of Holidays'), hole=0.5)\n\n px.pie(train, names='Functioning Day', \n        title=('categories of Functioning Day'), hole=0.5)\n\"\"\"\n### now, let's see the numerical features\n\"\"\"\n\"\"\"\n- we wiil see the distribution of the numerical features \n\n- as **ID** isn't important we will not consider it as well as the categorical features **Seasons**, **Holiday** and **Functioning Day**\n\"\"\"\nplt.subplots(3, 3,figsize=(18,10))\n\nplt.subplots_adjust(top=1)\nplt.suptitle(\"Distribution of the numerical features\", fontsize=25) \n\n\nfor i, col in enumerate(train[train.columns[3:-5]]):\n    plt.subplot(3, 3, i+1)\n    sns.distplot(train[col]).set_title(\"{} distribution\".format(col), fontsize=18);\n    plt.tight_layout(pad=3.0)\n\"\"\"\n## 2- Bivariate Exploration\n\"\"\"\n\"\"\"\n### as **y** is the target feature, we will see the correlation between it and all other numerical features by ploting heatmap which represent the **Pearson's Correlation** between each two features\n\"\"\"\nplt.figure(figsize=(15,10))\n\nsns.heatmap(train.corr(),\n            vmin=-1,\n            vmax=1,\n            cmap='RdBu',\n            annot=True);\n\"\"\"\n### let's see the relation between 'y' and the same features with plots\n\"\"\"\nplt.subplots(2, 4,figsize=(18,10))\n\nplt.subplots_adjust(top=1)\nplt.suptitle(\"investigate relation between 'y' and numerical features\", fontsize=25) \n\n\nfor i, col in enumerate(train[train.columns[3:-5]]):\n    plt.subplot(3, 3, i+1)\n    sns.regplot(x = train['y'], y = train[col], line_kws = {'color': 'red'}).set_title(\"{} vs y distribution\".format(col), fontsize=18);\n    plt.tight_layout(pad=3.0)\n   \n\"\"\"\n### now let's see the relation between **y** and the categorical features\n\"\"\"\nfrom plotly.subplots import make_subplots\n\nfig = make_subplots(rows=1, cols=2, specs=[[{\"type\": \"pie\"}, {\"type\": \"pie\"}]])\n\n\nfig.add_trace(go.Pie(labels=train['Holiday'], values=train['y']),\n    row=1, col=1)\n\nfig.add_trace(go.Pie(labels=train['Functioning Day'], values=train['y']),\n    row=1, col=2)\n\nfig.update_traces(hole=.5)\n\nfig.update_layout(height=600, width=800, title_text=\"The count of <b>y<\/b> according to <b>Holidays<\/b> and <b>Functioning days<\/b>\"\n                  ,annotations=[dict(text='Holidays', x=0.17, y=0.5, font_size=15, showarrow=False),\n                                dict(text='Functioning day', x=0.87, y=0.5, font_size=14, showarrow=False)])\nfig.show()\n\n\"\"\"\n### it looks like there is no rented bikes when there is no functioning day, to make sure that it's not a bug in the plot we can see the table using **Groupby**\n\"\"\"\ntrain[train['Functioning Day'] == 'No'].head()\ntrain[train['Functioning Day'] == 'No']['y'].sum()\nplt.figure(figsize=(15, 5))\n\nsns.barplot(data = train, x = 'Seasons', y = 'y', palette = 'Blues').set_title(\"number of bikes rented in each season\", fontsize=18);\n\n\"\"\"\n### we can see the change of some features over time with **Date** feature as follows :\n\"\"\"\nfeatures_for_lp = ['Rainfall(mm)','y','Snowfall (cm)','Solar Radiation (MJ\/m2)','Humidity(%)','Wind speed (m\/s)']\n\nplt.subplots(3, 3,figsize=(18,10))\nplt.subplots_adjust(top=1)\n#plt.suptitle(\"investigate relation between 'y' and numerical features\", fontsize=25) \n\nfor i, col in enumerate(features_for_lp):\n    plt.subplot(3, 2, i+1)\n    sns.lineplot(data = train , x = 'Date', y=train[col]).set_title(\"change of the count of {} over provided years\".format(col), fontsize=18);\n\n    plt.tight_layout(pad=3.0)\n\n\n\"\"\"\n## 3- Multivariate Exploration\n\"\"\"\nsns.barplot(data = train, x = 'year', y = 'y', hue = 'Seasons', palette = 'Reds').set_title(\"Season's rental bikes Frequency for each year\", fontsize=18);\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=[20, 5])\n\nsns.barplot(data = train, x = 'Seasons', y = 'y', hue = 'Functioning Day', palette = 'Reds', ax = axes[0]).set_title(\"Season's rental bikes Frequency for each year\", fontsize=18);\nsns.barplot(data = train, x = 'Seasons', y = 'y', hue = 'Holiday', palette = 'Blues', ax = axes[1]).set_title(\"Season's rental bikes Frequency for each year\", fontsize=18);\n\"\"\"\n### for each season we can see the change of the number of rented bikes based on the variety of some features like **Rainfall** , **Snowfall** , **Solar Radiation** , **Humidity** and **Wind speed**\n\"\"\"\nfeatures_for_fp = ['Rainfall(mm)','Snowfall (cm)','Solar Radiation (MJ\/m2)','Humidity(%)','Wind speed (m\/s)']\n\nfor i, col in enumerate(features_for_fp):\n    g = sns.FacetGrid(data = train, col = 'Seasons', height = 4.5,\n            margin_titles = True);\n    g.map(sns.regplot, col, 'y',scatter = True, fit_reg = True, line_kws = {'color': 'red'});\n\"\"\"\n## 4- ML Implementation\n\"\"\"\ntrain.isnull().sum()\n\"\"\"\nso there is no null values, let's continue\n\"\"\"\ntrain.info()\n\"\"\"\nnow we will do **feature engineering** \n\"\"\"\ntrain.Date = pd.to_datetime(train.Date, format='%d\/%m\/%Y')\ntrain['day'] = train['Date'].dt.day_name()\ntrain['month'] = train['Date'].dt.month_name()\ntrain['year'] = pd.DatetimeIndex(train['Date']).year\ntrain['day_night'] = train['Hour'].apply(lambda x: 'Night' if (x >= 20) or (x<=5) else \"Day\")\n#-------------------------------------------\ntrain[\"weather\"] = train.Seasons.map({'Spring': \" Clear\",\\\n                                        'Summer' : \" Mist \", \\\n                                        'Autumn' : \" Light Rain\", \\\n                                        'Winter' :\" Heavy Rain\" })\n\n# #-------------------------------------------\nhours_binning = []\nfor i in train['Hour']:\n    if i < 8 :\n        hours_binning.append(1)\n    elif i >= 22 :\n        hours_binning.append(2)\n    elif i > 9 and i<18 :\n        hours_binning.append(3)\n    elif i == 8 :\n        hours_binning.append(4)\n    elif i == 9 :\n        hours_binning.append(5)\n    elif i == 20 or i == 21 :\n        hours_binning.append(6)\n    elif i == 19 or i == 18 :\n        hours_binning.append(7)\n        \ntrain['hours_binning'] = hours_binning\n\n# #-------------------------------------------\nday_condition = []\nfor i in train['Humidity(%)']:\n    if i >= 0 and i<= 20 :\n        day_condition.append(\"uncomfortably dry\")\n    elif i >= 21 and i<=60 :\n        day_condition.append(\"comfort\")\n    elif i >= 61 and i<=100 :\n        day_condition.append(\"uncomfortably wet\")\n        \ntrain['day_condition'] = day_condition\n\n# #-------------------------------------------\nbins = [-20,0,25.7,40]\nlabels = ['cold', 'normal', 'hot']\ntrain['temp_binned'] = pd.cut(train['Temperature(\ufffdC)'], bins=bins, labels=labels).astype('object')\n\n# #-------------------------------------------\nbins = [-28,9,13,15.5,17.5,28]\nlabels = ['A bit dry', 'Very comfortable', 'Comfortable','Ok','Very humid']\ntrain['dew_point_binned'] = pd.cut(train['Dew point temperature(\ufffdC)'], bins=bins, labels=labels).astype('object')\npd.set_option('display.max_columns', None)\ntrain.head()\n\"\"\"\nnow we will calculate correlation between **numerical**, **categorical features** and **y**\n\"\"\"\n# train_modified = train.drop(columns = ['y','ID','day_condition','Rainfall(cm)'],axis=1)\n\ntrain_modified = train[['Date', 'Hour', 'Temperature(\ufffdC)', 'Humidity(%)', 'Wind speed (m\/s)','Visibility (10m)', 'Dew point temperature(\ufffdC)',\n        'Solar Radiation (MJ\/m2)', 'Rainfall(mm)', 'Snowfall (cm)', 'Seasons','Holiday', 'Functioning Day', 'day', 'month', 'year', 'day_night',\n        'weather', 'hours_binning', 'temp_binned', 'dew_point_binned']]\n\ny = train['y'].astype('float')\ny =  np.log1p(y)\n\n# define numerical features\nnumerical = train_modified[['Hour', 'Temperature(\ufffdC)', 'Humidity(%)', 'Wind speed (m\/s)','Visibility (10m)', 'Dew point temperature(\ufffdC)',\n                            'Solar Radiation (MJ\/m2)', 'Rainfall(mm)', 'Snowfall (cm)', 'year', 'hours_binning']]\nfrom sklearn.ensemble import ExtraTreesRegressor\n\nETR = ExtraTreesRegressor()\nETR.fit(numerical,y)\nprint(ETR.feature_importances_) #use inbuilt class feature_importances of tree based classifiers\n#plot graph of feature importances for better visualization\nfeat_importances = pd.Series(ETR.feature_importances_, index=numerical.columns)\nfeat_importances.nlargest(15).plot(kind='barh')\nplt.show()\ncolormap = plt.cm.RdBu\nplt.figure(figsize=(22,11))\nplt.title('Pearson Correlation of Features', y=1.05, size=20)\nsns.heatmap(numerical.corr(),linewidths=0.1,vmin= -1.0,vmax=1.0, \n            square=True, cmap=colormap, linecolor='white', annot=True);\n\"\"\"\nnow, to the categorical we will calcaulate **anova** \n\"\"\"\ncategorical = train[['Seasons','Holiday', 'Functioning Day', 'day', 'month', 'day_night','weather', 'temp_binned', 'dew_point_binned','y']]\n\nfrom scipy.stats import f_oneway\n \n# Running the one-way anova test between CarPrice and FuelTypes\n# Assumption(H0) is that FuelType and CarPrices are NOT correlated\n \n# Finds out the Prices data for each FuelType as a list\nfor i in categorical.columns:\n    CategoryGroupLists=categorical.groupby(i)['y'].apply(list)\n\n    # Performing the ANOVA test\n    # We accept the Assumption(H0) only when P-Value > 0.05\n    AnovaResults = f_oneway(*CategoryGroupLists)\n    print('P-Value for Anova {} is: '.format(i), AnovaResults[1], '\\ncorrelated = {} \\n'.format(AnovaResults[1] < 0.05))\ntrain_modified.head(2)\ntrain_modified.info()\ntrain_modified['weather'] = train_modified['weather'].astype(np.object)\ntrain_modified['Functioning Day'] = train_modified['Functioning Day'].astype(np.object)\ntrain_modified['Holiday'] = train_modified['Holiday'].astype(np.object)\ntrain_modified['Seasons'] = train_modified['Seasons'].astype(np.object)\n\nfrom sklearn.model_selection import train_test_split\nfrom catboost import CatBoostRegressor\n\nX_train, X_val, y_train, y_val = train_test_split(train_modified, y, test_size=0.2, random_state=42) \n\n\ncategorical_features_indices = np.where(train_modified.dtypes == np.object)[0]\n\nmodel= CatBoostRegressor(iterations = 4998,\n                         loss_function='RMSE',\n                         learning_rate = 0.01, \n                         depth = 8, \n                         l2_leaf_reg = 2)\n                         #,early_stopping_rounds = 10 )\n\n\nmodel.fit(X_train, y_train,cat_features=categorical_features_indices,eval_set=(X_val, y_val),plot=True)\nprint(model.score(X_train, y_train))\nprint(model.score(X_val, y_val))\nfrom sklearn.metrics import r2_score\n\n#model_predicted = np.exp(model.predict(X_val))\nmodel_predicted = model.predict(X_val)\n\nr2 = r2_score(y_val, model_predicted)\nprint('R2: {:.6f}'.format(r2))\n\"\"\"\nnow preparing test set\n\"\"\"\ntesting = test.copy()\ntesting.columns\ntesting.Date = pd.to_datetime(testing.Date, format='%d\/%m\/%Y')\ntesting['day'] = testing['Date'].dt.day_name()\ntesting['month'] = testing['Date'].dt.month_name()\ntesting['year'] = pd.DatetimeIndex(testing['Date']).year\ntesting['day_night'] = testing['Hour'].apply(lambda x: 'Night' if (x >= 20) or (x<=5) else \"Day\")\n#-------------------------------------------\ntesting[\"weather\"] = testing.Seasons.map({'Spring': \" Clear\",\\\n                                        'Summer' : \" Mist \", \\\n                                        'Autumn' : \" Light Rain\", \\\n                                        'Winter' :\" Heavy Rain\" })\n\n# #-------------------------------------------\nday_condition = []\nfor i in testing['Humidity(%)']:\n    if i >= 0 and i<= 20 :\n        day_condition.append(\"uncomfortably dry\")\n    elif i >= 21 and i<=60 :\n        day_condition.append(\"comfort\")\n    elif i >= 61 and i<=100 :\n        day_condition.append(\"uncomfortably wet\")\n        \ntesting['day_condition'] = day_condition\n# #-------------------------------------------\n\nhours_binning = []\nfor i in testing['Hour']:\n    if i < 8 :\n        hours_binning.append(1)\n    elif i >= 22 :\n        hours_binning.append(2)\n    elif i > 9 and i<18 :\n        hours_binning.append(3)\n    elif i == 8 :\n        hours_binning.append(4)\n    elif i == 9 :\n        hours_binning.append(5)\n    elif i == 20 or i == 21 :\n        hours_binning.append(6)\n    elif i == 19 or i == 18 :\n        hours_binning.append(7)\n\ntesting['hours_binning'] = hours_binning\n\n# #-------------------------------------------\nbins = [-20,0,25.7,40]\nlabels = ['cold', 'normal', 'hot']\ntesting['temp_binned'] = pd.cut(testing['Temperature(\ufffdC)'], bins=bins, labels=labels).astype('object')\n\n# #-------------------------------------------\nbins = [-35,9,13,15.5,17.5,35]\nlabels = ['A bit dry', 'Very comfortable', 'Comfortable','Ok','Very humid']\ntesting['dew_point_binned'] = pd.cut(testing['Dew point temperature(\ufffdC)'], bins=bins, labels=labels).astype('object')\n\ntesting = testing.drop(columns = ['ID','day_condition'],axis=1)\n\nCB_predicted = model.predict(testing)\ntest['y'] = np.exp(CB_predicted)\ntest[['ID', 'y']].to_csv('\/kaggle\/working\/CB_submission.csv', index=False)\n\n\n\"\"\"\n### well, that's it for now, hope this notebook would be helpful \n\"\"\"\nplt.savefig('facetgrid.jpg')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '3cf6596258dff0'}"}
{"id":"81212","text":"\"\"\"\n#Coronavirus: Tales of solidarity from China's virus-hit Wuhan - Wuhan Jiayou\"\n\n\nAs the number of coronavirus infections continues to grow, millions of people have gone into lockdown in Wuhan - the centre of the outbreak - to try to stop the virus spreading. But in this time of isolation some people are determined to raise each others' spirits.\n\nThe neighbours who spread cheer\n\nThe deadly outbreak comes as China celebrates one of the most important dates in its calendar - Lunar New Year.\n\nImagine Christmas and Thanksgiving all rolled into one - typically a time filled with lots of cheer. For many, it's the only chance in a year they have to meet up with their family and exchange gifts of food and money.\n\nIn Wuhan people have been encouraged to stay home to minimise the spread of the virus. But residents in a block of flats found a small way to cheer each other up.\n\nVideos circulating on social media show people shouting \"Wuhan jiayou\" out of their windows- roughly translated to \"Stay strong Wuhan\" or \"Keep on going Wuhan\".\nhttps:\/\/www.bbc.com\/news\/world-asia-china-51276496\n\"\"\"\n\"\"\"\n![](https:\/\/isc.artez.nl\/wp-content\/uploads\/2020\/03\/82118041_861953280923630_3695950724077715456_n.jpg)https:\/\/isc.artez.nl\/events\/invitation-to-sister-city-programme-arnhem-wuhan\/\n\"\"\"\n# 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)\nimport cv2\nimport matplotlib.pyplot as plt\nimport time\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\n\"\"\"\n![](https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcTUV8XJKI2JaipXz3wjwn3XZXxgsBlBimQW6w&usqp=CAU)liberationnews.org\n\"\"\"\n\"\"\"\n#Codes by Valentyn Sichkar  https:\/\/www.kaggle.com\/valentynsichkar\/yolo-v3-with-opencv\/notebook\n\"\"\"\n# Opening file, reading, eliminating whitespaces, and splitting by '\\n', which in turn creates list\nlabels = open('..\/input\/yolo-coco-data\/coco.names').read().strip().split('\\n')  # list of names\n\n# # Check point\n# print(labels)\n\"\"\"\n#\u2018Wuhan stay strong\u2019: city lockdown captured in craft beer - AFP\nhttps:\/\/www.youtube.com\/watch?v=Y-0DdxvrFsU\nWhen the coronavirus emerged in Wuhan and the Chinese city went into a strict 76-day lockdown, Wang Fan resolved to commemorate the turbulent period in the way he knew best -- through beer.\n\"\"\"\n# Defining paths to the weights and configuration file with model of Neural Network\nweights_path = '..\/input\/yolo-coco-data\/yolov3.weights'\nconfiguration_path = '..\/input\/yolo-coco-data\/yolov3.cfg'\n\n# Setting minimum probability to eliminate weak predictions\nprobability_minimum = 0.5\n\n# Setting threshold for non maximum suppression\nthreshold = 0.3\n\"\"\"\n#Loading trained YOLO Objects Detector with the help of 'dnn' library from OpenCV\n\"\"\"\nnetwork = cv2.dnn.readNetFromDarknet(configuration_path, weights_path)\n\n# Getting names of all layers\nlayers_names_all = network.getLayerNames()  # list of layers' names\n\n# # Check point\n# print(layers_names_all)\n# Getting only output layers' names that we need from YOLO algorithm\nlayers_names_output = [layers_names_all[i[0] - 1] for i in network.getUnconnectedOutLayers()]  # list of layers' names\n\n# Check point\nprint(layers_names_output)  # ['yolo_82', 'yolo_94', 'yolo_106']\n\"\"\"\n#Loading input image from file\n\"\"\"\n# Our image initially is in RGB format\n# But now we open it in BGR format as function 'cv2.imread' opens it so\nimage_input = cv2.imread('..\/input\/cusersmarildownloadsstrongjpg\/strong.jpg')\n\n# Getting image shape\nimage_input_shape = image_input.shape\n\n# Check point\nprint(image_input_shape)  # tuple of (917, 1222, 3)\n# Showing RGB image but firstly converting it from BGR format\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 10.0)\nplt.imshow(cv2.cvtColor(image_input, cv2.COLOR_BGR2RGB))\nplt.show()\n\"\"\"\n#Getting blob from input image\n\"\"\"\n# The 'cv2.dnn.blobFromImage' function returns 4-dimensional blob\n# from input image after mean subtraction, normalizing, and RB channels swapping\n# Resulted shape has number of images, number of channels, width and height\n# E.G.: blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size, mean, swapRB=True)\n# Link: https:\/\/www.pyimagesearch.com\/2017\/11\/06\/deep-learning-opencvs-blobfromimage-works\/\nblob = cv2.dnn.blobFromImage(image_input, 1 \/ 255.0, (416, 416), swapRB=True, crop=False)\n\n# Check point\nprint(image_input.shape)  # (917, 1222, 3)\nprint(blob.shape)  # (1, 3, 416, 416)\n# Check point\n# Slicing blob and transposing to make channels come at the end\nblob_to_show = blob[0, :, :, :].transpose(1, 2, 0)\nprint(blob_to_show.shape)  # (416, 416, 3)\n\n# Showing 'blob_to_show'\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 5.0)\nplt.imshow(blob_to_show)\nplt.show()\n\"\"\"\n#Implementing forward pass with our blob and only through output layers\n\"\"\"\n# Calculating at the same time, needed time for forward pass\nnetwork.setInput(blob)  # setting blob as input to the network\nstart = time.time()\noutput_from_network = network.forward(layers_names_output)\nend = time.time()\n\n# Showing spent time for forward pass\nprint('YOLO v3 took {:.5f} seconds'.format(end - start))\n# Check point\nprint(type(output_from_network))  # <class 'list'>\nprint(type(output_from_network[0]))  # <class 'numpy.ndarray'>\n\"\"\"\n#Colours for representing every detected object\n\"\"\"\n# Seed the generator - every time we run the code it will generate by the same rules\n# In this way we can keep specific colour the same for every class\nnp.random.seed(42)\n# randint(low, high=None, size=None, dtype='l')\ncolours = np.random.randint(0, 255, size=(len(labels), 3), dtype='uint8')\n\n# Check point\nprint(colours.shape)  # (80, 3)\nprint(colours[0])  # [102 220 225]\n# Preparing lists for detected bounding boxes, obtained confidences and class's number\nbounding_boxes = []\nconfidences = []\nclass_numbers = []\n# Getting spacial dimension of input image\nh, w = image_input_shape[:2]  # Slicing from tuple only first two elements\n\n# Check point\nprint(h, w)  # 917 1222\n\"\"\"\n#Going through all output layers after feed forward and answer from network\n\"\"\"\nfor result in output_from_network:\n    # Going through all detections from current output layer\n    for detection in result:\n        # Getting class for current object\n        scores = detection[5:]\n        class_current = np.argmax(scores)\n\n        # Getting confidence (probability) for current object\n        confidence_current = scores[class_current]\n\n        # Eliminating weak predictions by minimum probability\n        if confidence_current > probability_minimum:\n            # Scaling bounding box coordinates to the initial image size\n            # YOLO data format keeps center of detected box and its width and height\n            # That is why we can just elementwise multiply them to the width and height of the image\n            box_current = detection[0:4] * np.array([w, h, w, h])\n\n            # From current box with YOLO format getting top left corner coordinates\n            # that are x_min and y_min\n            x_center, y_center, box_width, box_height = box_current.astype('int')\n            x_min = int(x_center - (box_width \/ 2))\n            y_min = int(y_center - (box_height \/ 2))\n\n            # Adding results into prepared lists\n            bounding_boxes.append([x_min, y_min, int(box_width), int(box_height)])\n            confidences.append(float(confidence_current))\n            class_numbers.append(class_current)\n\"\"\"\n#Implementing non maximum suppression of given boxes and corresponding scores\n\"\"\"\n# It is needed to make sure the data type of the boxes is 'int'\n# and the type of the confidences is 'float'\n# https:\/\/github.com\/opencv\/opencv\/issues\/12789\nresults = cv2.dnn.NMSBoxes(bounding_boxes, confidences, probability_minimum, threshold)\n\n# Check point\n# Showing labels of the detected objects\nfor i in range(len(class_numbers)):\n    print(labels[int(class_numbers[i])])\n\n# Saving found labels\nwith open('found_labels.txt', 'w') as f:\n    for i in range(len(class_numbers)):\n        f.write(labels[int(class_numbers[i])])\n\"\"\"\n#Drawing bounding boxes and labels\n\"\"\"\n# Checking if there is at least one detected object\nif len(results) > 0:\n    # Going through indexes of results\n    for i in results.flatten():\n        # Getting current bounding box coordinates\n        x_min, y_min = bounding_boxes[i][0], bounding_boxes[i][1]\n        box_width, box_height = bounding_boxes[i][2], bounding_boxes[i][3]\n\n        # Preparing colour for current bounding box\n        colour_box_current = [int(j) for j in colours[class_numbers[i]]]\n\n        # Drawing bounding box on the original image\n        cv2.rectangle(image_input, (x_min, y_min), (x_min + box_width, y_min + box_height),\n                      colour_box_current, 5)\n\n        # Preparing text with label and confidence for current bounding box\n        text_box_current = '{}: {:.4f}'.format(labels[int(class_numbers[i])], confidences[i])\n\n        # Putting text with label and confidence on the original image\n        cv2.putText(image_input, text_box_current, (x_min, y_min - 7), cv2.FONT_HERSHEY_SIMPLEX,\n                    1.5, colour_box_current, 5)\n\"\"\"\n#Showing RGB image with bounding boxes and labels\n\"\"\"\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 10.0)\nplt.imshow(cv2.cvtColor(image_input, cv2.COLOR_BGR2RGB))\nplt.show()\n#Code by Olga Belitskaya https:\/\/www.kaggle.com\/olgabelitskaya\/sequential-data\/comments\nfrom IPython.display import display,HTML\nc1,c2,f1,f2,fs1,fs2=\\\n'#2B3A67','#42a7f5','Akronim','Smokum',30,15\ndef dhtml(string,fontcolor=c1,font=f1,fontsize=fs1):\n    display(HTML(\"\"\"<style>\n    @import 'https:\/\/fonts.googleapis.com\/css?family=\"\"\"\\\n    +font+\"\"\"&effect=3d-float';<\/style>\n    <h1 class='font-effect-3d-float' style='font-family:\"\"\"+\\\n    font+\"\"\"; color:\"\"\"+fontcolor+\"\"\"; font-size:\"\"\"+\\\n    str(fontsize)+\"\"\"px;'>%s<\/h1>\"\"\"%string))\n    \n    \ndhtml('Thanks Valentyn Sichkar for your script, @mpwolke was Here.' )","meta":"{'source': 'AI4Code', 'id': '9513f3ba38d54e'}"}
{"id":"132964","text":"\"\"\"\nLet's look at the kagglers in each region of the world. We will group countries by regions used by the World Bank: North America, East Asia & Pacific, South Asia, Latin America & Caribbean, Europe & Central Asia, Sub-Saharan Africa, Middle East & North Africa\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nsns.set_style(\"whitegrid\")\nsns.set(font_scale=1.3)\n\nmulti = pd.read_csv(\"..\/input\/kaggle-survey-2018\/multipleChoiceResponses.csv\", header=1)\ncountries = pd.read_csv(\"..\/input\/countries-classification-by-income\/country_classification.tsv\",\n                       sep=\"\\t\")\n# Add country group: developped or developping\ncountries[\"Group\"] = countries[\"Income group\"].apply(lambda x: \"Developped countries\" if x==\"High income\" else \"Developing countries\")\n\nreplacements = {'Egypt, Arab Rep.':'Egypt','Hong Kong SAR, China':'Hong Kong (S.A.R.)',\n'Iran, Islamic Rep.':'Iran, Islamic Republic of...',\"Korea, Dem. People's Rep.\":'Republic of Korea',\n'Russian Federation':'Russia','Korea, Rep.':'South Korea', 'United Kingdom':'United Kingdom of Great Britain and Northern Ireland',\n'United States':'United States of America','Vietnam':'Viet Nam'}\ncountries['Economy'].replace(replacements, inplace=True)\n\n# Add Group, Income Group and Region to multi choice question\n#First rename column\nmulti.rename(columns={\"In which country do you currently reside?\": \"Country\"}, inplace=True)\nfor k in [\"Group\", \"Income group\", \"Region\"]:\n    group_dict = dict(zip(countries.Economy, countries[k]))\n    group_dict['I do not wish to disclose my location'] = \"Undisclosed location\"\n    group_dict['Other'] = \"Other\"\n    multi[k] = multi[\"Country\"].apply(lambda x: group_dict[x])\n#regions = multi[\"Region\"].unique().tolist()\nregions = ['North America',\n 'East Asia & Pacific',\n 'South Asia',\n 'Latin America & Caribbean',\n 'Europe & Central Asia',\n 'Sub-Saharan Africa',\n 'Middle East & North Africa']\nincome_group = multi[\"Income group\"].unique().tolist()\n\"\"\"\nFirst, let's look at the kagglers distribution in the different regions\n\"\"\"\nax = sns.countplot(y=\"Region\", data=multi, order=multi[\"Region\"].value_counts().index,\n                  color=\"darkslateblue\")\nax.set_xlabel(\"Respondents\", labelpad=22)\nax.set_ylabel(\"Region\", labelpad=20)\nax.set_title(\"What region are you from?\", pad=22)\nplt.show()\n\"\"\"\nMost regions are largely dominated by one country: Brazil in Latin America & Caribbean region,  USA in North America, India in South Asia, China in East Asia & Pacific. Europe & Central Asia is dominated by Russia and western european countries. Middle East & North Africa together with Sub-Saharan Africa are underrepresented\n\"\"\"\n\"\"\"\n## Gender\n\"\"\"\nmulti.rename(columns={\"What is your gender? - Selected Choice\": \"Gender\"}, inplace=True)\n\nax = sns.countplot(x=\"Region\", data=multi, hue=\"Gender\", order=multi[\"Region\"].value_counts().index)\nax.set_xlabel(\"Respondents\", labelpad=22)\nax.set_ylabel(\"Count\", labelpad=20)\nax.set_title(\"What is your gender?\", pad=22)\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n## Age\n\"\"\"\nmulti.rename(columns={'What is your age (# years)?': \"Age\"}, inplace=True)\nage_df = pd.crosstab(multi.Age, multi.Region)*100\/pd.crosstab(multi.Age, multi.Region).sum(axis=0)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,10))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,8):\n    r = regions[i-1]\n    y = age_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=age_df.index, y=y, palette=clrs)\n    ax.set_xlabel(\"Age group\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nWe see a similar trend for the regions where kagglers between 22-34 are dominating the scene. The exception is for the South Asia region, basically India, where kagglers are much younger.\n\"\"\"\n\"\"\"\n## Education\n\"\"\"\nmulti.rename(columns={'What is the highest level of formal education that you have attained or plan to attain within the next 2 years?': \"Education\"}, inplace=True)\nmulti[\"Education\"]=multi[\"Education\"].str.replace(\"Some college\/university study without earning a bachelor\u2019s degree\",\"No bachelor's degree\")\nmulti[\"Education\"]=multi[\"Education\"].str.replace(\"No formal education past high school\",\"High school\")\neducation_df = pd.crosstab(multi.Education, multi[\"Region\"])*100\/pd.crosstab(multi.Education, multi[\"Region\"]).sum(axis=0)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,8):\n    r = regions[i-1]\n    y = education_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=education_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 55])\n    ax.set_xlabel(\"Education\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nA Master's degree appears to be the most common degree in the different regions, except for India where more kagglers have or are pursuing a Bachelor's degree. This might be related to the younger age of the kaggling community in India. In Europe & Central Asia, the proportion of Doctoral degree is higher than the Bachelor's degree.  Sub-saharan African is the only region where No formal education past high school make it to the top 3.\n\"\"\"\n\"\"\"\n## Undergraduate major\n\"\"\"\nmulti.rename(columns={'Which best describes your undergraduate major? - Selected Choice': \"Undergraduate major\"}, inplace=True)\nundergrad_major={\"A business discipline \\(accounting, economics, finance, etc.\\)\": \"Business discipline\",\n\"Computer science \\(software engineering, etc.\\)\":\"Computer Science\",\n\"Engineering \\(non-computer focused\\)\":\"Engineering\",\n\"Environmental science or geology\":\"Environmental science\",\n\"Fine arts or performing arts\":\"Fine arts\",\n\"Humanities \\(history, literature, philosophy, etc.\\)\":\"Humanitites\",\n\"Information technology, networking, or system administration\":\"IT\",\n\"Mathematics or statistics\":\"Maths\/Stats\",\n\"Medical or life sciences \\(biology, chemistry, medicine, etc.\\)\":\"Medical\/life sciences\",\n\"Social sciences \\(anthropology, psychology, sociology, etc.\\)\":\"Social sciences\",\n\"Physics or astronomy\":\"Physics\/astro\",\n\"No formal education past high school\":\"High school\",\n\"Some college\/university study without earning a bachelor\u2019s degree\":\"No bachelor's degree\"}\nfor k,v in undergrad_major.items():\n    multi[\"Undergraduate major\"]=multi[\"Undergraduate major\"].str.replace(k,v)\nmajor_df = pd.crosstab(multi[\"Undergraduate major\"], multi[\"Region\"])*100\/pd.crosstab(multi[\"Undergraduate major\"], multi[\"Region\"]).sum(axis=0)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,len(regions)+1):\n    r = regions[i-1]\n    y = major_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=major_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 60])\n    ax.set_xlabel(\"Major\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nA Computer science major is the most common major among kagglers, followed by engineering and maths\/stats.  Maths\/stats major takes second place over engineering in Europe\/Central Asia and Subsaharan Africa\n\"\"\"\n\"\"\"\n## Current role\n\"\"\"\nmulti.rename(columns={'Select the title most similar to your current role (or most recent title if retired): - Selected Choice': \"Current role\"}, inplace=True)\nrole_df = pd.crosstab(multi[\"Current role\"], multi[\"Region\"])*100\/pd.crosstab(multi[\"Current role\"], multi[\"Region\"]).sum(axis=0)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,len(regions)+1):\n    r = regions[i-1]\n    y = role_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=role_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 35])\n    ax.set_xlabel(\"Current role\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nData scientist, software engineer and students are the top 3 roles, except for sub-saharan africa where there are more data analysts than software engineer. Students are the dominant group in East Asia, South Asia, and Sub-Saharan Africa, whereas data scientist is leading (not by much) in North America, Latin America, Europe and Middle East & North Africa.\n\"\"\"\n\"\"\"\n## About money\n\"\"\"\nmulti.rename(columns={'What is your current yearly compensation (approximate $USD)?': \"Salary\"}, inplace=True)\nmulti[\"Salary\"]=multi[\"Salary\"].str.replace(\"I do not wish to disclose my approximate yearly compensation\",\"Undisclosed\")\nordered_salary = ['0-10,000','10-20,000','20-30,000','30-40,000','40-50,000','50-60,000',\n'60-70,000','70-80,000','80-90,000','90-100,000','100-125,000','125-150,000',\n '150-200,000','200-250,000','250-300,000','300-400,000','400-500,000','500,000+','Undisclosed']\nsalary_df = pd.crosstab(multi[\"Salary\"], multi[\"Region\"])*100\/pd.crosstab(multi[\"Salary\"], multi[\"Region\"]).sum(axis=0)\nsalary_df=salary_df.reindex(ordered_salary)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,len(regions)+1):\n    r = regions[i-1]\n    y = salary_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=salary_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 45])\n    ax.set_xlabel(\"Salary\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nWell, most people do not want to disclose their yearly compensation. We see a common trend of decreasing proportion of people as compensation increase. The exception is for North America where we see peaks around 100-150000$.\n\"\"\"\n\"\"\"\nLet's look at the yearly compensations of data scientists in the different regions\n\"\"\"\nmulti_salary = multi[multi[\"Current role\"]==\"Data Scientist\"]\nds_salary_df = pd.crosstab(multi_salary[\"Salary\"], multi_salary[\"Region\"])*100\/pd.crosstab(multi_salary[\"Salary\"], multi_salary[\"Region\"]).sum(axis=0)\nds_salary_df = ds_salary_df.reindex(ordered_salary)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,len(regions)+1):\n    r = regions[i-1]\n    y = ds_salary_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=ds_salary_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 35])\n    ax.set_xlabel(\"Salary\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nIt looks like data scientists earn much more  in North America.\n\"\"\"\n\"\"\"\n## What tool do they usually use?\n\"\"\"\nmulti.rename(columns={'What is the primary tool that you use at work or school to analyze data? (include text response) - Selected Choice': \"Tool\"}, \n             inplace=True)\ntools={'Cloud-based data software & APIs \\(AWS, GCP, Azure, etc.\\)':'Cloud-based',\n       'Basic statistical software \\(Microsoft Excel, Google Sheets, etc.\\)':'Basic SS',\n       'Local or hosted development environments \\(RStudio, JupyterLab, etc.\\)':'Development',\n       'Advanced statistical software \\(SPSS, SAS, etc.\\)':'Advanced SS',\n       'Business intelligence software \\(Salesforce, Tableau, Spotfire, etc.\\)':'BI'}\nfor k,v in tools.items():\n    multi[\"Tool\"]=multi[\"Tool\"].str.replace(k,v)\ntool_df = pd.crosstab(multi[\"Tool\"], multi[\"Region\"])*100\/pd.crosstab(multi[\"Tool\"], multi[\"Region\"]).sum(axis=0)\nnrows, ncols = 3, 3\nfig = plt.figure(figsize=(13,20))\n#fig.subplots_adjust(hspace=2, wspace=0.3)\nfor i in range(1,len(regions)+1):\n    r = regions[i-1]\n    y = tool_df[r]\n    p = np.sort(y.values)[-3]\n    clrs = ['grey' if (x < p) else 'red' for x in y ]\n    ax = fig.add_subplot(nrows, ncols, i)\n    ax = sns.barplot(x=tool_df.index, y=y, palette=clrs)\n    ax.set_ylim([0, 60])\n    ax.set_xlabel(\"Tool\", labelpad=15)\n    ax.set_ylabel(\"Percentage\", labelpad=10)\n    ax.set_title(r, pad=15)\n    plt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()\n\"\"\"\nLocal or hosted development environments are the most popular, followed by basic statistical software.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f49b727cb15aeb'}"}
{"id":"111067","text":"\"\"\"\n# Restaurant Recommendation System\n\"\"\"\n\"\"\"\n## 2. Exploratory Data Analysis (EDA)\n\"\"\"\n\"\"\"\n## Aim\nAfter getting our data ready, we still want to make sense of it. In EDA we look at various plots and actually let the data tell us its story. This step will give us a deeper understanding of data. We'll also try to make data more amenable to modelling. We'll look at various table in database.\n\nWe'll be using matplolib and seaborn to make various plots.\n\"\"\"\n\"\"\"\n### Importing Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport json\nfrom sqlite3 import dbapi2 as sq3\nfrom pathlib import Path\nfrom collections import OrderedDict\n\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\nfrom time import time\nfrom IPython.display import clear_output\nfrom collections import OrderedDict\n\nplt.style.use('ggplot')\n# Functions to work with SQLite db\ndef make_query(sel):\n    \"\"\"Query database\"\"\"\n    c = db.cursor().execute(sel)\n    return c.fetchall()\n\ndef make_frame(list_of_tuples=None, legend=[], query=None):\n    \"\"\"\n    Returns DataFrame from a query or result of query\n    \"\"\"\n    framelist=[]\n    if list_of_tuples is None:\n        if query is None:\n            print(\"Error: No query made\")\n            return\n        list_of_tuples = make_query(query)\n        \n    for i, cname in enumerate(legend):\n        framelist.append((cname,[e[i] for e in list_of_tuples]))\n    return pd.DataFrame.from_dict(OrderedDict(framelist))\n\n# Connect to database\ndb = sq3.connect('..\/input\/yelp-project\/yelp_database.db')\n\"\"\"\n### Reviews Table\n\"\"\"\n# Looking at columns of 'reviews' table\nmake_query(\"PRAGMA table_info(reviews)\")\n%%time\n# Getting pandas DataFrame from db\ndate_df = make_frame(query=\"SELECT stars, date FROM reviews\", legend=['rating', 'date'])\ndate_df.date = pd.to_datetime(date_df.date)\ndate_df.info()\n# Creating new columns in reviews df\ndate_df['day'] = date_df.date.dt.day\ndate_df['month'] = date_df.date.dt.month\ndate_df['year'] = date_df.date.dt.year\ndate_df['hour'] = date_df.date.dt.hour\ndate_df['minute'] = date_df.date.dt.minute\ndate_df['second'] = date_df.date.dt.second\n\ndate_df.head()\nsns.catplot(data=date_df, x='rating', kind='count', aspect=2)\nax = plt.gca()\nax.set(xticks=[0,1,2,3,4,5], title='Rating Distribution')\nax.tick_params('x', labelsize=15)\nax.tick_params('y', labelsize=15)\n\"\"\"\nWe see many most ratings are on the higher scale. Most ratings are either 5 star or 4 star.\n\"\"\"\ng = sns.catplot(data=date_df, x='year', kind='count', aspect=2)\nax = plt.gca()\nax.set_title('Number of reviews by Year')\n\"\"\"\nWe see number of reviews increased exponentially over the years. This could also be an evidence for yelp's popularity over the years.\n\"\"\"\ng = sns.relplot(data=date_df, x='month', y='rating', aspect=2, kind='line')\nax = plt.gca()\nax.set_title('Ratings by Month')\n\"\"\"\nWe see that average rating after faceting on month is minimum for 12th month ~ December. But if we look at the y-scale, change is not so significant to draw a trend.\n\"\"\"\ng = sns.relplot(data=date_df, x='day', y='rating', aspect=2, kind='line')\nax = plt.gca()\nax.set_title('Ratings by Day')\n\"\"\"\nWe see that average rating after faceting on day is max from 5th to 10th day. But if we look at the y-scale, change is not so significant to draw a trend.\n\"\"\"\nsns.catplot(data=date_df, x='hour', aspect=2, kind='count')\nax = plt.gca()\nax.set_title('Review Time')\n\"\"\"\nThis is interesting as we see minimum number of reviews were given during morning and count keeps rising throughout the day which seems intuitive. But maximum number of reviews were given at 2am which is counter intuitive. Why are more people reviewing this late? Is it possible that these are bars where people stay for long but why would drunks care about reviewing? Or are people reviewing after dinner during their commute home? We would have to look at further evidence to draw conclusions.\n\"\"\"\n#Release memory\ndel date_df\n\"\"\"\n### Users Table\n\"\"\"\n#Looking at columns and making a DataFrame from users table\ncols = list(zip(*make_query(\"PRAGMA table_info(users)\")))[1]\nusers_df = make_frame(query='SELECT * FROM users;', legend=cols)\nusers_df.info()\nplt.figure(figsize=(10,5))\nax = plt.gca()\nsns.boxplot(data=users_df, x='review_count', ax=ax)\nplt.xscale('log')\n\"\"\"\nThe boxplot for review count reveals a lot of outliers. There are some users who have written over 10k reviews.\n\"\"\"\n#Type Cast to datetime format\nusers_df.yelping_since = pd.to_datetime(users_df.yelping_since)\nsns.displot(data=users_df, x='yelping_since', aspect=2)\n\"\"\"\nMost people are yelping_since mid 2010s.\n\"\"\"\nsns.displot(data=users_df, x='fans', aspect=2)\nplt.xscale('log')\nplt.yscale('log')\n\"\"\"\nSome users are wildly popular reviewers on yelp. Most people have few or no fans\n\"\"\"\nsns.relplot(data=users_df, x='yelping_since', y='average_stars',alpha=.1, aspect=2)\n\"\"\"\nWe see that reviewers who have been yelping for long have higher avg rating. We can conclude that overtime users become less harsh reviewers.\n\"\"\"\n#Release Memory\ndel users_df\n\"\"\"\n### Businesses table\n\"\"\"\n# Looking at business table's columns and theirdtypes\nmake_query(\"PRAGMA table_info(businesses)\")\n#Getting dataframe from table\nbusiness_df_cols = list(zip(*make_query(\"PRAGMA table_info(businesses)\")))[1]\nbusiness_df = make_frame(query='SELECT * FROM businesses', legend=business_df_cols)\nbusiness_df.head()\nsns.jointplot(data=business_df, x='latitude', y='longitude')\n\"\"\"\nWe see that locations of businesses are concentrated in clusters. These clusters must be big cities. Lets plot these on a map.\n\"\"\"\nBBox = (business_df.longitude.min(),   business_df.longitude.max(), business_df.latitude.min(), business_df.latitude.max())\n\nimg = plt.imread('..\/input\/map-img-for-yelp-business-df\/map(1).png')[:,:,:-1]\nfig, ax = plt.subplots(figsize = (18,14))\nax.scatter(business_df.longitude, business_df.latitude, zorder=1, alpha= 0.1, s=5)\nax.set_title('Plotting Restaurant Locations on Map')\nax.set_xlim(-130,BBox[1])\nax.set_ylim(BBox[2],BBox[3])\nax.imshow(img, zorder=0, extent = BBox, aspect='equal')\n\"\"\"\nWe see our data has businesses from certain cities of U.S. and not all over U.S.\n\"\"\"\ndef plot(feature):\n    plt.figure(figsize=(8, 8))\n    sns.relplot(data=business_df, y='stars', x='review_count', col=feature, alpha=.4)\n\nbool_features = []\nfor tup in make_query(\"PRAGMA table_info(businesses)\"):\n    if tup[2]=='BOOLEAN':\n        bool_features.append(tup[1])\n\nfor feature in bool_features:\n    plot(feature)\n\"\"\"\n- Restaurants with Attire have higher ratings and more higher review count hence more popular than those without Attire.\n- Restaurants with TakeOut, AcceptCreditCard, GoodForKids, Reservation, GoodForGroups, BusinessParking, HasTV, Alcohol, BikeParking, Delivery, OutdoorSeating, WiFi, Ambience, DogsAllowed, GoodForDancing, CoatCheck, CounterService show similar trend.\n- Restaurnts with NoiseLevel also have higher avg ratings, this could be because they are located in prime locations.\n- ByAppointmentOnly restaurants show roughly similar trend to Not ByAppointmentOnly restaurants.\n- Restaurants with Outdoor Seating have better ratings and higher review count than those without OutdoorSeating. Hence restaurants with OutdoorSeating are more popular.\n- Restaurants which are WheelChairAccessible do not perform better than those who aren't.\n- Restaurants with WiFi are also more popular than those without.\n- Some restaurants without TableService have higher reviewCount than those with.\n- Restaurants with Dogs allowed also appear more popular.\n- A\/c to plot, Ambience plays a big role in a restaurants rating and review count. Those with ambience are more popular.\n- Plots for restaurants with HappyHour, DriveThrough, Music, BestNights or AcceptsBitcoin do not differ significantly than those without.\n- Restaurants without DietaryRestrictions are more highly rated than those with. \n- Restaurants with Open24Hours=0 are underrepresented.\n\"\"\"\nplt.figure(figsize=(8,8))\ntop_10_zip = business_df.postal_code.value_counts()[:10]\nsns.barplot(x=top_10_zip.index, y=top_10_zip.values)\nax = plt.gca()\nax.set_title('Most Popular Zip codes')\nax.set_xlabel('Zip Code')\nax.set_ylabel('Count')\n\n\"\"\"\nOur data has most number of businesses from zip code 89109 (Las Vegas). This can be verified on map.\n\"\"\"\ntoprating_df = business_df[business_df[\"stars\"]==5]\ntoprating_df = toprating_df.sort_values('review_count', ascending=False).head(20)\n\nplt.figure(figsize=(15,7))\np = sns.barplot(x='name', y=\"review_count\", data=toprating_df,color=\"b\")\np.set_xticklabels(p.get_xticklabels(), rotation = 90, fontsize = 8)\np.set_title(\"Top 5 star-rated Restuarants sorted by review count\")\np.set(xlabel=\"Restaurant\", ylabel=\"Review Count\")\n\"\"\"\nRestaurant businesses with ratings=5 and highest review counts\n\"\"\"\ndf_restaurants = business_df.name.value_counts().index[:20].tolist()\ndf_top = business_df.loc[business_df['name'].isin(df_restaurants)]\nmean_df = df_top.groupby('name')['stars'].mean()\nmeanrating_df = mean_df.reset_index()\ntopmean_rating_df = meanrating_df.sort_values('stars', ascending=False).head(20)\n\nplt.figure(figsize=(15,7))\np = sns.barplot(x='name', y=\"stars\",data=topmean_rating_df, color=\"b\")\np.set_xticklabels(p.get_xticklabels(), rotation = 90, fontsize = 8)\np.set_title(\"Top 5 star-rated Restaurants sorted by mean of ratings\")\np.set(xlabel=\"Restaurant\", ylabel=\"Rating\")\n\"\"\"\nRestaurant businesses with highest mean scores of ratings, with 20 occurences\n\"\"\"\nplt.figure(figsize=(15,7))\nsns.lineplot(x=business_df[\"stars\"],y=business_df[\"review_count\"],hue=business_df[\"DriveThru\"],ci=80)\nplt.legend(bbox_to_anchor=(1.00, 1), title =\"DriveThru\")\nplt.show()\n\n\"\"\"\nRestaurants with Drive Through have higher ratings and higher review count. Hence are more popular.\n\"\"\"\nplt.figure(figsize=(15,7))\nsns.lineplot(x=business_df[\"stars\"],y=business_df[\"review_count\"],hue=business_df[\"GoodForDancing\"],ci=80)\nplt.legend(bbox_to_anchor=(1.00, 1), title =\"GoodForDancing\")\nplt.show()\n\"\"\"\nRestaurants GoodForDancing also appear more popular.\n\"\"\"\nplt.figure(figsize=(20,10))\nsns.heatmap(business_df.corr(),annot=False)\nplt.show()\n\"\"\"\nWe see some correlations roughly at the centre of heatmap. They could be due to redundant features like a Restaurant with CarParking will most likely have BikeParking, or because high end restaurants have most of the listed features.\n\"\"\"\n\"\"\"\n## Conclusion\n- We studied various plots. \n- Restaurants with TakeOut, AcceptCreditCard, GoodForKids, Reservation, GoodForGroups, BusinessParking, HasTV, Alcohol, BikeParking, Delivery, OutdoorSeating, WiFi, Ambience, DogsAllowed, GoodForDancing, CoatCheck, CounterService, Attire are more popular in general.\n\n\"\"\"\n\"\"\"\n#### Links\n[1. Getting Data Ready](https:\/\/www.kaggle.com\/yashrajwani\/yelp-getting-data-ready)\n\n[3. Restaurant Recommendation](https:\/\/www.kaggle.com\/yashrajwani\/yelp-restaurant-recommendation-system)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'cc1848a7479fd1'}"}
{"id":"6398","text":"import keras\nfrom gensim.models import KeyedVectors\n!wget -P \/root\/input\/ -c \"https:\/\/s3.amazonaws.com\/dl4j-distribution\/GoogleNews-vectors-negative300.bin.gz\"\nEMBEDDING_FILE = '\/root\/input\/GoogleNews-vectors-negative300.bin.gz' # from above\nword2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)\nresult = word2vec.most_similar_cosmul(positive=['actor','woman'], negative=['man'] )\nresult[0]\n\"\"\"\n# Part 2\n\"\"\"\nfrom keras.datasets import imdb\nfrom keras.preprocessing import sequence\n\nmax_features = 10000  # number of words to consider as features\nmaxlen = 500  # cut texts after this number of words (among top max_features most common words)\nbatch_size = 32\n\nprint('Loading data...')\n(input_train, y_train), (input_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(input_train), 'train sequences')\nprint(len(input_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\ninput_train = sequence.pad_sequences(input_train, maxlen=maxlen)\ninput_test = sequence.pad_sequences(input_test, maxlen=maxlen)\nprint('input_train shape:', input_train.shape)\nprint('input_test shape:', input_test.shape)\nfrom keras.layers import Dense, Bidirectional, SimpleRNN, Embedding, Dropout, LSTM\nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping\nes=EarlyStopping(patience=4,min_delta=0.001, mode='max', monitor='val_acc')\nimport matplotlib.pyplot as plt\ndef overfit(history):\n    acc = history.history['acc']\n    val_acc = history.history['val_acc']\n    loss = history.history['loss']\n    val_loss = history.history['val_loss']\n\n    epochs = range(len(acc))\n\n    plt.plot(epochs, acc, 'bo', label='Training acc')\n    plt.plot(epochs, val_acc, 'b', label='Validation acc')\n    plt.title('Training and validation accuracy')\n    plt.legend()\n\n    plt.figure()\n\n    plt.plot(epochs, loss, 'bo', label='Training loss')\n    plt.plot(epochs, val_loss, 'b', label='Validation loss')\n    plt.title('Training and validation loss')\n    plt.legend()\n\n    plt.show()\n\nmetrics=[]\nmodel = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(SimpleRNN(32))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n                    epochs=10,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\n\n\n\n\noverfit(history)\nm=model.evaluate(input_test,y_test)\nprint(m)\nmetrics.append({\"single RNN\": m})\nfrom keras.layers import LSTM\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, 32))\nmodel.add(LSTM(32))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop',\n              loss='binary_crossentropy',\n              metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n                    epochs=10,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\noverfit(history)\nm=model.evaluate(input_test,y_test)\nprint(m)\nmetrics.append({\"small LSTM\": m})\nfrom keras.layers import Dense, Bidirectional, SimpleRNN, Embedding, Dropout\nmodel = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(Bidirectional(LSTM(64, return_sequences=True)))\n\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='rmsprop',\n              loss='binary_crossentropy',\n              metrics=['acc'])\nmodel.summary()\n\nhistory = model.fit(input_train, y_train,\n                    epochs=20,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\n\noverfit(history)\nm=model.evaluate(input_test,y_test)\nprint(m)\nmetrics.append({\"Bi LSTM\": m})\n\nmodel = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(LSTM(128, return_sequences=True))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop',\n              loss='binary_crossentropy',\n              metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n                    epochs=10,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\noverfit(history)\nm=model.evaluate(input_test,y_test)\nprint(m)\nmetrics.append({\"large LSTM\": m})\nplt.title(\"Models Accuracy\")\nplt.bar([list(i)[0] for i in metrics], [list(i.values())[0][1] for i in metrics])\nimport tensorflow\nmodel = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(LSTM(64,dropout=0.2))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=tensorflow.keras.optimizers.Adam(learning_rate=0.00001),\n              loss='binary_crossentropy',\n              metrics=['acc'])\nmodel.summary()\n\nhistory = model.fit(input_train, y_train,\n                    epochs=80,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\n\noverfit(history)\nm=model.evaluate(input_test,y_test)\nimport tensorflow\nes=EarlyStopping(patience=3,min_delta=0.001, mode='max', monitor='val_acc')\nmodel = Sequential()\n\nmodel.add(Embedding(10000,32))\n\nmodel.add(Bidirectional(LSTM(64,dropout=0.2, return_sequences=False)))\n#model.add(Bidirectional(LSTM(32,dropout=0.2, return_sequences=True)))\nmodel.add(Dense(32))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=tensorflow.keras.optimizers.Adam(learning_rate=0.0001),\n              loss='binary_crossentropy',\n              metrics=['acc'])\nmodel.summary()\n\nhistory = model.fit(input_train, y_train,\n                    epochs=40,\n                    batch_size=128,\n                    validation_split=0.2,callbacks=[es])\n\noverfit(history)\nm=model.evaluate(input_test,y_test)\nimport numpy as np\nfrom gensim.test.utils import common_texts\nfrom gensim.models import Word2Vec\ntest_sentences = [\n  \"That movie was absolutely awful\",\n  \"The acting was a bit lacking\",\n  \"The film was creative and surprising\",\n  \"Absolutely fantastic!\",\n  \"This movie is not worth the money\",\n  \"The only positive thing with this movie is the music\"\n]\n\ntext=[]\nfor i in test_sentences:\n    phrase=[]\n    for u in i.split(\" \"):\n        phrase.append(u)\n    text.append(phrase)\nb=tensorflow.keras.datasets.imdb.get_word_index(path=\"imdb_word_index.json\")\n    \n\nvecs=[]\n\nfor i in text:\n    #arr=np.zeros((10))\n    arr=[]\n    for u in range(len(i)):\n        try:\n            mm=i[u].lower()\n            \n            #arr[u]=b[mm]\n            arr.append(b[mm])\n        except:\n            #arr[u]=b['the']\n            arr.append(1)\n    #vecs.append(arr.astype(\"int\"))\n    vecs.append(arr)\n\nvecs=tensorflow.keras.preprocessing.sequence.pad_sequences(vecs, maxlen=10,value=0, padding=\"post\")\nprint(vecs)\npreds=model.predict_classes(vecs)\n\nfor i in range(len(test_sentences)):\n    \n    print(test_sentences[i] + \" : \"+str(preds[i]))","meta":"{'source': 'AI4Code', 'id': '0be4408311d6a3'}"}
{"id":"115902","text":"# 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 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\nimport warnings\nwarnings.filterwarnings('ignore')\ntitanic = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntitanic.head()\n## checking the head of our data set\ntitanic.info()\n## checking info of all columns\ntitanic.shape\n## checking shape of data set\ntitanic.describe()\n## statistical information about numerical variable\n\"\"\"\n# **Data Quality Check**\n\nhandling missing values as well\n\n\"\"\"\nround(100*(titanic.isnull().sum()\/len(titanic)),2)\n## checking missing value percentage in all columns\ntitanic.drop('Cabin',axis=1,inplace=True)\n## cabin almost have 77% of missing values hence remove this column from data set\nage_median = titanic['Age'].median(skipna=True)\ntitanic['Age'].fillna(age_median,inplace=True)\n## as there is 19% of missing values in age column hence it is not a good idea to remove this row wise or column wise hence impute those missing values with the median of age \n\ntitanic = titanic[titanic['Embarked'].isnull()!=True]\n## as embarked has a very small amount of missing values hence remove those rows which have missing values in embarked column \n\ntitanic.shape\n## checking shape after removing null values\n\"\"\"\n# duplicate check\n\"\"\"\ntitanic_dub = titanic.copy()\n## creating copy of the data frame to check duplicate values\ntitanic_dub.shape\n## comparing shapes of two data frames\ntitanic.shape\n## shape of original data frame\n\"\"\"\n# EDA\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n## importing libraries for data visualitation\nplt.figure(figsize=(15,5), dpi=80)\nplt.subplot(1,4,1)\nsns.boxplot(y=titanic['Age'])\nplt.title(\"Outliers in 'Age'\")\n\nplt.subplot(1,4,2)\nax = sns.boxplot(y=titanic['Fare'])\nax.set_yscale('log')\nplt.title(\"Outliers in 'Fare'\")\n\nplt.subplot(1,4,3)\nsns.boxplot(y=titanic['SibSp'])\nplt.title(\"Outliers in 'SibSp'\")\n\n\nplt.subplot(1,4,4)\nsns.boxplot(y=titanic['Parch'])\nplt.title(\"Outliers in 'Parch'\")\n#ax.set_yscale('log')\nplt.tight_layout()\nplt.show()\n\n## plotting all four variables to check for outliers\n## it clearly shows that all four variables has some outliers\n\n\nsns.catplot(x=\"SibSp\", col = 'Survived', data=titanic, kind = 'count', palette='pastel')\nsns.catplot(x=\"Parch\", col = 'Survived', data=titanic, kind = 'count', palette='pastel')\nplt.tight_layout()\nplt.show()\n\n## plotting of sibsp and parch in basis of survived and not survived\n\"\"\"\nsibsp and parch basically tells us that whether a person is accompanied by someone else or not \nso we can make two category by merging them to find whether a single person is acompanied by some one else or not \n\"\"\"\ndef alone(x):\n    if (x['SibSp']+x['Parch']>0):\n        return (1)\n    else:\n        return (0)\ntitanic['Alone'] = titanic.apply(alone,axis=1)\n## creating a function to make one variable which tells us whether a person is single or accompanied by some on the ship\nsns.catplot(x=\"Alone\", col = 'Survived', data=titanic, kind = 'count', palette='pastel')\nplt.show()\n\"\"\"\nit clearly shows that those person who are not alone survived more\n\"\"\"\n## drop parch and sibsp\ntitanic = titanic.drop(['Parch','SibSp'],axis=1)\ntitanic.head()\n\nsns.distplot(titanic['Fare'])\nplt.show()\n\"\"\"\nthere is some skewness in the fare column \nhence removing the skewness using log function\n\"\"\"\nsns.catplot(x=\"Sex\", y=\"Survived\", col=\"Pclass\", data=titanic, saturation=.5, kind=\"bar\", ci=None, aspect=0.8, palette='deep')\nsns.catplot(x=\"Sex\", y=\"Survived\", col=\"Embarked\", data=titanic, saturation=.5, kind=\"bar\", ci=None, aspect=0.8, palette='deep')\nplt.show()\n\n## plotting of survive on basis of pclass\n\"\"\"\nfemales are more likely to be survived\n\"\"\"\nsurvived_0 = titanic[titanic['Survived']==0]\nsurvived_1 = titanic[titanic['Survived']==1]\n## divided our dataset into survived or not survived to check the distribution of age in both the cases \nsurvived_0.shape\n## checking shape of the data set that contains the data of passengers who not survived\nsurvived_1.shape\n## checking shape of the data set that contains the data of passengers who survived\nsns.distplot(survived_0['Age'])\nplt.show()\n## checking distribution of age in not survived data set\nsns.distplot(survived_1['Age'])\nplt.show()\n## checking distribution of age in survived dataset\n\"\"\"\nyoung persons are survived more (age group between 20-40)\n\"\"\"\nsns.boxplot(x='Survived',y='Fare',data=titanic)\nplt.show()\n## checking survival rate on basis of fare\n\"\"\"\nthose who are survived paid more fares\n\"\"\"\n\"\"\"\n# creating dummy variables\n\"\"\"\nPclass_dummy = pd.get_dummies(titanic['Pclass'],prefix='Pclass',drop_first=True)\nPclass_dummy.head()\n## creating dummy variables for pclass\n\n\n## joing dummy variables\ntitanic = pd.concat([titanic,Pclass_dummy],axis=1)\ntitanic.head()\ntitanic.drop('Pclass',axis=1,inplace=True)\n## as there is no use of pclass after joining the columns that contains dummy variables  for pclass\nEmbarked_dummy = pd.get_dummies(titanic['Embarked'],drop_first=True)\nEmbarked_dummy.head()\n## creating dummy variables for embarked and dropping first column\ntitanic = pd.concat([titanic,Embarked_dummy],axis=1)\ntitanic.drop('Embarked',axis=1,inplace=True)\n## joining dummy variables\ntitanic.head()\n## checking head of the data set after joining dummy variables\ndef sex_map(x):\n    if x == 'male':\n        return (1)\n    elif x == 'female':\n        return (0)\ntitanic['Sex'] = titanic['Sex'].apply(lambda x:sex_map(x))\n\n## creating function for convert sex into binary values\n\"\"\"\nSelect variables needed for creating model.\n\"\"\"\ntitanic = titanic[['Survived','Sex','Age','Fare','Alone','Pclass_2','Pclass_3','Q','S']]\n## let's plot one heatmap to check the corelations \nplt.figure(figsize=(10,10))\nsns.heatmap(titanic.corr(),annot=True)\nplt.show()\n\"\"\"\nThere is not much higher co-relations between two variables.\n\"\"\"\n\"\"\"\n# Model Build\n\"\"\"\n\"\"\"\n**XgBoost**\n\nXGBoost is an algorithm that has recently been dominating applied machine learning and Kaggle competitions for structured or tabular data.\n\nXGBoost is an implementation of gradient boosted decision trees designed for speed and performance.\n\nA Gentle Introduction to XGBoost for Applied Machine Learning\n\n**What is XGBoost?**\nXGBoost stands for eXtreme Gradient Boosting.\n\nThe name xgboost, though, actually refers to the engineering goal to push the limit of computations resources for boosted tree algorithms. Which is the reason why many people use xgboost.\n\n\u2014 Tianqi Chen, in answer to the question \u201cWhat is the difference between the R gbm (gradient boosting machine) and xgboost (extreme gradient boosting)?\u201d on Quora\n\nIt is an implementation of gradient boosting machines created by Tianqi Chen, now with contributions from many developers. It belongs to a broader collection of tools under the umbrella of the Distributed Machine Learning Community or DMLC who are also the creators of the popular mxnet deep learning library.\n\nTianqi Chen provides a brief and interesting back story on the creation of XGBoost in the post Story and Lessons Behind the Evolution of XGBoost.\n\nXGBoost is a software library that you can download and install on your machine, then access from a variety of interfaces. Specifically, XGBoost supports the following main interfaces:\n\nCommand Line Interface (CLI).\nC++ (the language in which the library is written).\nPython interface as well as a model in scikit-learn.\nR interface as well as a model in the caret package.\nJulia.\nJava and JVM languages like Scala and platforms like Hadoop.\nXGBoost Features\nThe library is laser focused on computational speed and model performance, as such there are few frills. Nevertheless, it does offer a number of advanced features.\n\n**Model Features**\nThe implementation of the model supports the features of the scikit-learn and R implementations, with new additions like regularization. Three main forms of gradient boosting are supported:\n\nGradient Boosting algorithm also called gradient boosting machine including the learning rate.\nStochastic Gradient Boosting with sub-sampling at the row, column and column per split levels.\nRegularized Gradient Boosting with both L1 and L2 regularization.\n\n**System Features**\nThe library provides a system for use in a range of computing environments, not least:\n\nParallelization of tree construction using all of your CPU cores during training.\nDistributed Computing for training very large models using a cluster of machines.\nOut-of-Core Computing for very large datasets that don\u2019t fit into memory.\nCache Optimization of data structures and algorithm to make best use of hardware.\n\n**Algorithm Features**\nThe implementation of the algorithm was engineered for efficiency of compute time and memory resources. A design goal was to make the best use of available resources to train the model. Some key algorithm implementation features include:\n\nSparse Aware implementation with automatic handling of missing data values.\nBlock Structure to support the parallelization of tree construction.\nContinued Training so that you can further boost an already fitted model on new data.\nXGBoost is free open source software available for use under the permissive Apache-2 license.\n\n**Why Use XGBoost?**\nThe two reasons to use XGBoost are also the two goals of the project:\n\nExecution Speed.\nModel Performance.\n\nReference:[https:\/\/machinelearningmastery.com\/gentle-introduction-xgboost-applied-machine-learning\/](http:\/\/)\n\"\"\"\n## read test data \n\ntitanic_test = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n## check shape and info of titanic_test\n\ntitanic_test.shape\ntitanic_test.info()\n## imputing missing values of age \ntitanic_test['Age'].fillna(age_median,inplace=True)\n## create alone column\ntitanic_test['Alone'] = titanic_test.apply(alone,axis=1)\n## create sex column with binary value 0 for 'female' and 1 for 'male'\ntitanic_test['Sex'] = titanic_test['Sex'].apply(lambda x:sex_map(x))\n## compute dummy encoding in test data \n\nPclass_dummy_test = pd.get_dummies(titanic_test['Pclass'],prefix='Pclass',drop_first=True)\n\ntitanic_test = pd.concat([titanic_test,Pclass_dummy_test],axis=1)\n## compute dummy encoding in test data \n\n\nEmbarked_dummy_test = pd.get_dummies(titanic_test['Embarked'],drop_first=True)\n\ntitanic_test = pd.concat([titanic_test,Embarked_dummy_test],axis=1)\n## let's seperate the target variable and divide train data into train and test (validation data) our actual test data is already seperated\n\ntarget = titanic.pop('Survived')\n\n## define train and test to from train to evaluate our result\n\n## import libraries \nimport sklearn\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test = train_test_split(titanic,target,random_state=42,stratify=target)\n\n## 'stratify' makes sure that both train and test contains same percentage of target '0' and '1'\n\"\"\"\n**Default Xgboost Model**\n\n**some info about the parameters used**\n\nFortunately XGBoost provides a nice way to find the best number of rounds whilst training by **early_stopping_rounds**. Since trees are built sequentially, instead of fixing the number of rounds at the beginning, we can test our model at each step and see if adding a new tree\/round improves performance.\nTo do so, we define a test dataset and a metric that is used to assess performance at each round. If performance haven\u2019t improved for N rounds (N is defined by the variable early_stopping_round), we stop the training and keep the best number of boosting rounds.\n\n**seed**: random seed. It's important to set a seed here, to ensure we are using the same folds for each step so we can properly compare the scores with different parameters.\n\n**metrics**: the metrics to use to evaluate our model, here we use aucpr: Area under the PR curve.\n\n**eval_set** : a list of pairs to evaluate.\n\"\"\"\nimport xgboost as xgb\n\nxgb_clf = xgb.XGBClassifier(objective='binary:logistic',seed=42)\nxgb_clf.fit(X_train,y_train,verbose=True,early_stopping_rounds=10,eval_metric='aucpr',eval_set=[(X_test,y_test)])\nfrom sklearn.metrics import plot_confusion_matrix\nplot_confusion_matrix(xgb_clf,X_test,y_test,values_format='d',display_labels=[\"Not Survived\",\"Survived\"])\nplt.show()\n\n## plot confusion matrix on seperated test set of the train data \n\"\"\"\n# Hyper Parameter Tuning\n\"\"\"\n\"\"\"\n**Optimize Parameter using cross validation and grid search**\n\nsome informations about the parameters used :\n\n**Maximum depth** of a tree. Increasing this value will make the model more complex and more likely to overfit.\nmax_depth is the maximum number of nodes allowed from the root to the farthest leaf of a tree. Deeper trees can model more complex relationships by adding more nodes, but as we go deeper, splits become less relevant and are sometimes only due to noise, causing the model to overfit.\n\n**learning_rate\/ETA** Step size shrinkage used in update to prevents overfitting.\nThe ETA parameter controls the learning rate. It corresponds to the shrinkage of the weights associated to features after each round, in other words it defines the amount of \"correction\" we make at each step (remember how each boosting round is correcting the errors of the previous? if not, check our first tutorial here).\nIn practice, having a lower eta makes our model more robust to overfitting thus, usually, the lower the learning rate, the best. But with a lower eta, we need more boosting rounds, which takes more time to train, sometimes for only marginal improvements.\n\n**gamma** Minimum loss reduction required to make a further partition on a leaf node of the tree (used for pruning)\n\n**lambda** Increasing this value will make model more conservative.\n\n**subsample** corresponds to the fraction of observations (the rows) to subsample at each step. By default it is set to 1 meaning that we use all rows.\n**colsample_bytree** corresponds to the fraction of features (the columns) to use. By default it is set to 1 meaning that we will use all features.\n\nReference [https:\/\/xgboost.readthedocs.io\/en\/latest\/parameter.html](http:\/\/)\n[https:\/\/blog.cambridgespark.com\/hyperparameter-tuning-in-xgboost-4ff9100a3b2f](http:\/\/)\n\"\"\"\n## define my parameters\n\nfrom sklearn.model_selection import GridSearchCV\n\n##ROUND1\n\nparam_grid = {\n               'max_depth':[2,3,4],\n               'learning_rate':[0.1,0.01,0.05],\n               'gamma':[0,0.25,1.0],\n               'reg_lambda':[0,1.0,10.0]\n    \n}\n\noptimal_model1 = GridSearchCV(estimator=xgb.XGBClassifier(objctive='binary:logistic',seed=42,subsample=0.9,colsample_bytree=0.6),\n                              param_grid=param_grid,\n                              scoring='roc_auc',\n                              verbose=0,\n                              n_jobs=10,\n                              cv=5\n                             ).fit(\n                                   X_train,y_train,early_stopping_rounds=10,eval_metric='auc',eval_set=[(X_test,y_test)]\n)\noptimal_model1.best_params_\n\"\"\"\nThose params are end of their range we will explore them more . Hence increase max_depth ,learning rate and gamma.we need to focous on our score so that model will not became overfit. \n\"\"\"\n##ROUND2\nparam_grid = {\n               'max_depth':[5,6,7],\n               'learning_rate':[0.001,0.003,0.005],\n               'gamma':[2.0,5.0,10.0],\n               'reg_lambda':[0,1.0,10.0]\n    \n}\n\noptimal_model2 = GridSearchCV(estimator=xgb.XGBClassifier(objctive='binary:logistic',seed=42,subsample=0.9,colsample_bytree=0.6),\n                              param_grid=param_grid,\n                              scoring='roc_auc',\n                              verbose=0,\n                              n_jobs=10,\n                              cv=5\n                             ).fit(\n                                   X_train,y_train,early_stopping_rounds=10,eval_metric='auc',eval_set=[(X_test,y_test)]\n)\noptimal_model2.best_params_\n\"\"\"\nAgain scale values.\n\"\"\"\n##ROUND3\nparam_grid = {\n               'max_depth':[8,9,10],\n               'learning_rate':[0.0001,0.0003,0.0005],\n               'gamma':[1.25,1.50,1.75],\n               'reg_lambda':[0,1.0,10.0]\n    \n}\n\noptimal_model3 = GridSearchCV(estimator=xgb.XGBClassifier(objctive='binary:logistic',seed=42,subsample=0.9,colsample_bytree=0.6),\n                              param_grid=param_grid,\n                              scoring='roc_auc',\n                              verbose=0,\n                              n_jobs=10,\n                              cv=5\n                             ).fit(\n                                   X_train,y_train,early_stopping_rounds=10,eval_metric='auc',eval_set=[(X_test,y_test)]\n)\noptimal_model3.best_params_\n\"\"\"\nAs score is getting decreased hence select the previous models params .\n\"\"\"\noptimal_model2.best_estimator_\n## hence pick our final params {'gamma': 2.0, 'learning_rate': 0.03, 'max_depth': 7, 'reg_lambda': 0}\n\nxgb_final = optimal_model2.best_estimator_\n\n\n\"\"\"\ncheck on test.\n\"\"\"\ntitanic_test['Survived'] = xgb_final.predict(titanic_test[['Sex', 'Age', 'Fare', 'Alone', 'Pclass_2', 'Pclass_3', 'Q', 'S']])\n\"\"\"\nwe can use others way to tune our hyper parameters.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd524cab56df8c4'}"}
{"id":"91620","text":"\"\"\"\n<a id=\"1.1\"><\/a>\n<h3 style=\"background-color:skyblue;font-family:newtimeroman;font-size:200%;text-align:center\">Drug Recommendation System in Health Care Using Machine Learning<\/h3>\n\n\nThe remarkable technological advancements in the health care industry have improved recently for the betterment of patients\u2019 life and providing better clinical decisions. Applications of machine learning and data mining can change the available data to valuable information that can be used for recommending appropriate drugs by analyzing symptoms of the disease. \n\nA machine learning approach for multi-disease with drug recommendation can be proposed to provide accurate drug recommendations for the patients suffering from various diseases. This approach generates appropriate recommendations for the patients suffering from cardiac, common cold, fever, obesity, optical, and ortho. Supervised machine learning approaches such as Support Vector Machine (SVM), Random Forest, Decision Tree, and K-nearest neighbors can be used for generating recommendations for patients.\n\nhttps:\/\/www.springerprofessional.de\/en\/a-drug-recommendation-system-for-multi-disease-in-health-care-us\/18279852\n\nFor obvious reasons, I can't follow that approach. Since I'm not a DS (and never be one) I just read the files and ran some code cells.\n\"\"\"\n\"\"\"\n![](https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/10\/machine-learning-in-healthcare.jpg)data-flair.training\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.offline as py\nimport plotly.express as px\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\ndf = pd.read_excel('\/kaggle\/input\/medicine-recommendation\/Medicine_description.xlsx')\ndf.head()\n#Code by Savita Nair https:\/\/www.kaggle.com\/savitanair\/hr-analytics\n\nprint(f'Dataset has {len(df.Drug_Name.unique())} unique groups')\nprint('*'*20)\nprint(f'And the top 10 counts are :')\nprint(df.Drug_Name.value_counts().head(10))\nprint('*'*20)\n\nc = df.Drug_Name.value_counts().head(10)\nfig, ax = plt.subplots(1,1,figsize=(12,6))\nax.bar(c.index, c.values, width=0.8, color='y')\nplt.xticks(rotation=45)\n#Code by Savita Nair https:\/\/www.kaggle.com\/savitanair\/hr-analytics\n\nprint(f'Dataset has {len(df.Reason.unique())} unique groups')\nprint('*'*20)\nprint(f'And the top 10 counts are :')\nprint(df.Reason.value_counts().head(10))\nprint('*'*20)\n\nc = df.Reason.value_counts().head(10)\nfig, ax = plt.subplots(1,1,figsize=(12,6))\nax.bar(c.index, c.values, width=0.8, color='r')\nplt.xticks(rotation=45)\n#Code by Savita Nair https:\/\/www.kaggle.com\/savitanair\/hr-analytics\n\nprint(f'Dataset has {len(df.Description.unique())} unique names')\nprint('*'*20)\nprint(f'And the top 10 counts are :')\nprint(df.Description.value_counts().head(10))\nprint('*'*20)\n\nc = df.Description.value_counts().head(10)\nfig, ax = plt.subplots(1,1,figsize=(12,6))\nax.bar(c.index, c.values, width=0.8, color='b')\nplt.xticks(rotation=45)\n#Code by Mohammad Imran Shaikh https:\/\/www.kaggle.com\/shikhnu\/covid19-tweets-eda-visualization-wordcloud\n\nunique_df = pd.DataFrame()\nunique_df['Features'] = df.columns\nunique=[]\nfor i in df.columns:\n    unique.append(df[i].nunique())\nunique_df['Uniques'] = unique\n\nf, ax = plt.subplots(1,1, figsize=(15,7))\n\nsplot = sns.barplot(x=unique_df['Features'], y=unique_df['Uniques'], alpha=0.8)\nfor p in splot.patches:\n    splot.annotate(format(p.get_height(), '.0f'), (p.get_x() + p.get_width() \/ 2., p.get_height()), ha = 'center',\n                   va = 'center', xytext = (0, 9), textcoords = 'offset points')\nplt.title('Bar plot for number of unique values in each column',weight='bold', size=15)\nplt.ylabel('#Unique values', size=12, weight='bold')\nplt.xlabel('Features', size=12, weight='bold')\nplt.xticks(rotation=90)\nplt.show()\n#word cloud\nfrom wordcloud import WordCloud, ImageColorGenerator\ntext = \" \".join(str(each) for each in df.Reason)\n# Create and generate a word cloud image:\nwordcloud = WordCloud(max_words=200,colormap='Reds', background_color=\"black\").generate(text)\nplt.figure(figsize=(10,6))\nplt.figure(figsize=(15,10))\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='Bilinear')\nplt.axis(\"off\")\nplt.figure(1,figsize=(12, 12))\nplt.show()\ndf1 = pd.read_excel('\/kaggle\/input\/medicine-recommendation\/Ratings.xlsx')\ndf1.head()\ndf1 = df1.rename(columns={'Short-form':'form'})\n#Code by Siti K https:\/\/www.kaggle.com\/khotijahs1\/2020-indonesia-university-rank\/comments\n\n#20 Medicine by Rating\ntop_medicine = df1.sort_values(by='Rating', ascending=False)[:20]\nfigure = plt.figure(figsize=(10,6))\nsns.barplot(y=top_medicine.form, x=top_medicine.Rating)\nplt.xticks()\nplt.xlabel('Medicine Rating')\nplt.ylabel('Short-form')\nplt.title('20 Medicines by Rating')\nplt.show()\ndf2 = pd.read_excel('\/kaggle\/input\/medicine-recommendation\/Company_Name.xlsx')\ndf2.head()\ndf2.columns.tolist()\n#Codes by Pooja Jain https:\/\/www.kaggle.com\/jainpooja\/av-guided-hackathon-predict-youtube-likes\/notebook\n\ntext_cols = ['Company_Name','NSE_Symbol', 'Industry']\n\nfrom wordcloud import WordCloud, STOPWORDS\n\nwc = WordCloud(stopwords = set(list(STOPWORDS) + ['|']), random_state = 42)\nfig, axes = plt.subplots(2, 2, figsize=(20, 12))\naxes = [ax for axes_row in axes for ax in axes_row]\n\nfor i, c in enumerate(text_cols):\n  op = wc.generate(str(df2[c]))\n  _ = axes[i].imshow(op)\n  _ = axes[i].set_title(c.upper(), fontsize=24)\n  _ = axes[i].axis('off')\n\n_ = fig.delaxes(axes[3])\ns = (df2.isna().sum()\/df2.shape[0]*100)<50\ndf2_modified = df2[s.index[s].tolist()]\nprint (df2_modified.shape)\ndf2_modified.head()\nplt.rcParams['font.size'] = 14\nfig, ax = plt.subplots(2, 2, figsize=(20,20))\nfor col, ax in zip(['Company_Name','NSE_Symbol','Rating', 'Industry'], ax.flat):\n    dict_ = df2_modified[col].value_counts().head(10).to_dict()\n    if ('Not Available' in dict_.keys()):\n        dict_.pop('Not Available')\n    labels = []\n    for i in dict_.keys():\n        i = i.split(' ')\n        if (len(i) > 6):\n            i[math.ceil(len(i)\/2)-1] += '\\n'\n            labels.append(' '.join(i))\n        else:\n            labels.append(' '.join(i))\n    ax.pie(x=list(dict_.values()), labels=labels, shadow=True, startangle=0)\n    \n    col = (' '.join(col.split('_'))).upper()\n    ax.set_title(col, weight='bold', fontsize=18)\nplt.tight_layout()\nplt.show()\n#Code by Olga Belitskaya https:\/\/www.kaggle.com\/olgabelitskaya\/sequential-data\/comments\nfrom IPython.display import display,HTML\nc1,c2,f1,f2,fs1,fs2=\\\n'#eb3434','#eb3446','Akronim','Smokum',30,15\ndef dhtml(string,fontcolor=c1,font=f1,fontsize=fs1):\n    display(HTML(\"\"\"<style>\n    @import 'https:\/\/fonts.googleapis.com\/css?family=\"\"\"\\\n    +font+\"\"\"&effect=3d-float';<\/style>\n    <h1 class='font-effect-3d-float' style='font-family:\"\"\"+\\\n    font+\"\"\"; color:\"\"\"+fontcolor+\"\"\"; font-size:\"\"\"+\\\n    str(fontsize)+\"\"\"px;'>%s<\/h1>\"\"\"%string))\n    \n    \ndhtml('Be patient. Mar\u00edlia Prata, @mpwolke was Here.' )","meta":"{'source': 'AI4Code', 'id': 'a8150486d4d913'}"}
{"id":"29106","text":"\"\"\"\n## Problem Statement\n\"\"\"\n\"\"\"\nPredict the forest cover type from the given cartographic variables. This study area includes four wilderness areas located in the Roosevelt National Forest of northern Colorado. These areas represent forests with minimal human-caused disturbances, so that existing forest cover types are more a result of ecological processes rather than forest management practices.\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm \nfrom matplotlib import cm\nimport seaborn as sns\nimport os\nprint(os.listdir(\"\/kaggle\/input\/forest-cover-type-kernels-only\"))\nimport zipfile\ntrain_zip = zipfile.ZipFile('\/kaggle\/input\/forest-cover-type-kernels-only\/train.csv.zip')\ntest_zip = zipfile.ZipFile('\/kaggle\/input\/forest-cover-type-kernels-only\/test.csv.zip')\n\ntrain = pd.read_csv(train_zip.open('train.csv'))\ntest = pd.read_csv(test_zip.open('test.csv'))\n\nId = test['Id']\n\"\"\"\nData Exploration and analysis\n\"\"\"\ntrain.head()\ntest.head()\ntrain.info()\n\"\"\"\nThe given dataset cantains 56 features including the target variable Cover_Type, along with 15120 observations and following are the features\n\n* Elevation - Elevation in meters\n* Aspect - Aspect in degrees azimuth\n* Slope - Slope in degrees\n* Horizontal_Distance_To_Hydrology - Horz Dist to nearest surface water features\n* Vertical_Distance_To_Hydrology - Vert Dist to nearest surface water features\n* Horizontal_Distance_To_Roadways - Horz Dist to nearest roadway\n* Hillshade_9am (0 to 255 index) - Hillshade index at 9am, summer solstice\n* Hillshade_Noon (0 to 255 index) - Hillshade index at noon, summer solstice\n* Hillshade_3pm (0 to 255 index) - Hillshade index at 3pm, summer solstice\n* Horizontal_Distance_To_Fire_Points - Horz Dist to nearest wildfire ignition points\n* Wilderness_Area (4 binary columns, 0 = absence or 1 = presence) - Wilderness area designation\n* Soil_Type (40 binary columns, 0 = absence or 1 = presence) - Soil Type designation\n* Cover_Type (7 types, integers 1 to 7) - Forest Cover Type designation\n\nThe wilderness areas are:\n\n* 1 - Rawah Wilderness Area\n* 2 - Neota Wilderness Area\n* 3 - Comanche Peak Wilderness Area\n* 4 - Cache la Poudre Wilderness Area\n\nThe soil types are:\n\n* 1 Cathedral family - Rock outcrop complex, extremely stony.\n* 2 Vanet - Ratake families complex, very stony.\n* 3 Haploborolis - Rock outcrop complex, rubbly.\n* 4 Ratake family - Rock outcrop complex, rubbly.\n* 5 Vanet family - Rock outcrop complex complex, rubbly.\n* 6 Vanet - Wetmore families - Rock outcrop complex, stony.\n* 7 Gothic family.\n* 8 Supervisor - Limber families complex.\n* 9 Troutville family, very stony.\n* 10 Bullwark - Catamount families - Rock outcrop complex, rubbly.\n* 11 Bullwark - Catamount families - Rock land complex, rubbly.\n* 12 Legault family - Rock land complex, stony.\n* 13 Catamount family - Rock land - Bullwark family complex, rubbly.\n* 14 Pachic Argiborolis - Aquolis complex.\n* 15 unspecified in the USFS Soil and ELU Survey.\n* 16 Cryaquolis - Cryoborolis complex.\n* 17 Gateview family - Cryaquolis complex.\n* 18 Rogert family, very stony.\n* 19 Typic Cryaquolis - Borohemists complex.\n* 20 Typic Cryaquepts - Typic Cryaquolls complex.\n* 21 Typic Cryaquolls - Leighcan family, till substratum complex.\n* 22 Leighcan family, till substratum, extremely bouldery.\n* 23 Leighcan family, till substratum - Typic Cryaquolls complex.\n* 24 Leighcan family, extremely stony.\n* 25 Leighcan family, warm, extremely stony.\n* 26 Granile - Catamount families complex, very stony.\n* 27 Leighcan family, warm - Rock outcrop complex, extremely stony.\n* 28 Leighcan family - Rock outcrop complex, extremely stony.\n* 29 Como - Legault families complex, extremely stony.\n* 30 Como family - Rock land - Legault family complex, extremely stony.\n* 31 Leighcan - Catamount families complex, extremely stony.\n* 32 Catamount family - Rock outcrop - Leighcan family complex, extremely stony.\n* 33 Leighcan - Catamount families - Rock outcrop complex, extremely stony.\n* 34 Cryorthents - Rock land complex, extremely stony.\n* 35 Cryumbrepts - Rock outcrop - Cryaquepts complex.\n* 36 Bross family - Rock land - Cryumbrepts complex, extremely stony.\n* 37 Rock outcrop - Cryumbrepts - Cryorthents complex, extremely stony.\n* 38 Leighcan - Moran families - Cryaquolls complex, extremely stony.\n* 39 Moran family - Cryorthents - Leighcan family complex, extremely stony.\n* 40 Moran family - Cryorthents - Rock land complex, extremely stony.\n\"\"\"\nprint(\"The number of traning examples(data points) = %i \" % train.shape[0])\nprint(\"The number of features we have = %i \" % train.shape[1])\nprint(\"The number of traning examples(data points) = %i \" % test.shape[0])\nprint(\"The number of features we have = %i \" % test.shape[1])\n\"\"\"\nLet's check if any of the columns contains NaNs or Nulls so that we can fill those values if they are insignificant or drop them. We may drop a whole column if most of its values are NaNs or fill its value according to its relation with other columns in the dataframe. Nones can also be 0 in some datasets and that is why i am going to use the describe of the train to see if the range of numbers is not reasonable or not. if you are dropping rows with NaNs and you notice that you need to drop a large portion of your dataset then you should think about filling the NaN values or drop a column that has most of its values missing.\n\"\"\"\ntrain.describe()\ntrain.isnull().sum()\n\"\"\"\nIt seems we don't have any NaN or Null value among the dataset we are trying to classify. Let's now discover the correlation matrix for this dataset and see if we can combine features or drop some according to its correlation with the output labels.\n\"\"\"\nf,ax = plt.subplots(figsize=(25, 25))\nsns.heatmap(train.corr(), annot=True, linewidths=.5, fmt= '.3f',ax=ax)\nplt.show()\ntrain.corr()\n\"\"\"\nFrom the above results it seems that soil_Type7 and soil_Type15 doesn't haveany correlation with the output cover_Type so we can easily drop them from the data we have. Also Soil_Type9, Soil_Type36, Soil_Type27, Soil_Type25, Soil_Type8 have weak correlation, but when a feature has a weak correlation tht doesn't mean it is useful cuz combined with other feature it may make a good impact. I choose those columns after experimenting many times with the data i have from the Extratrees, correlation matrix and the heatmap.\n\"\"\"\n#train.drop(['Id'], inplace = True, axis = 1 )\ntrain.drop(['Id','Soil_Type15' , \"Soil_Type7\"], inplace = True, axis = 1 )\ntest.drop(['Id','Soil_Type15' , \"Soil_Type7\"], inplace = True, axis = 1 )\ntrain['HorizontalHydrology_HorizontalFire'] = (train['Horizontal_Distance_To_Hydrology']+train['Horizontal_Distance_To_Fire_Points'])\ntrain['Neg_HorizontalHydrology_HorizontalFire'] = (train['Horizontal_Distance_To_Hydrology']-train['Horizontal_Distance_To_Fire_Points'])\ntrain['HorizontalHydrology_HorizontalRoadways'] = (train['Horizontal_Distance_To_Hydrology']+train['Horizontal_Distance_To_Roadways'])\ntrain['Neg_HorizontalHydrology_HorizontalRoadways'] = (train['Horizontal_Distance_To_Hydrology']-train['Horizontal_Distance_To_Roadways'])\ntrain['HorizontalFire_Points_HorizontalRoadways'] = (train['Horizontal_Distance_To_Fire_Points']+train['Horizontal_Distance_To_Roadways'])\ntrain['Neg_HorizontalFire_Points_HorizontalRoadways'] = (train['Horizontal_Distance_To_Fire_Points']-train['Horizontal_Distance_To_Roadways'])\n\ntrain['Neg_Elevation_Vertical'] = train['Elevation']-train['Vertical_Distance_To_Hydrology']\ntrain['Elevation_Vertical'] = train['Elevation']+train['Vertical_Distance_To_Hydrology']\n\ntrain['mean_hillshade'] =  (train['Hillshade_9am']  + train['Hillshade_Noon'] + train['Hillshade_3pm'] ) \/ 3\n\ntrain['Mean_HorizontalHydrology_HorizontalFire'] = (train['Horizontal_Distance_To_Hydrology']+train['Horizontal_Distance_To_Fire_Points'])\/2\ntrain['Mean_HorizontalHydrology_HorizontalRoadways'] = (train['Horizontal_Distance_To_Hydrology']+train['Horizontal_Distance_To_Roadways'])\/2\ntrain['Mean_HorizontalFire_Points_HorizontalRoadways'] = (train['Horizontal_Distance_To_Fire_Points']+train['Horizontal_Distance_To_Roadways'])\/2\n\ntrain['MeanNeg_Mean_HorizontalHydrology_HorizontalFire'] = (train['Horizontal_Distance_To_Hydrology']-train['Horizontal_Distance_To_Fire_Points'])\/2\ntrain['MeanNeg_HorizontalHydrology_HorizontalRoadways'] = (train['Horizontal_Distance_To_Hydrology']-train['Horizontal_Distance_To_Roadways'])\/2\ntrain['MeanNeg_HorizontalFire_Points_HorizontalRoadways'] = (train['Horizontal_Distance_To_Fire_Points']-train['Horizontal_Distance_To_Roadways'])\/2\n\ntrain['Slope2'] = np.sqrt(train['Horizontal_Distance_To_Hydrology']**2+train['Vertical_Distance_To_Hydrology']**2)\ntrain['Mean_Fire_Hydrology_Roadways']=(train['Horizontal_Distance_To_Fire_Points'] + train['Horizontal_Distance_To_Hydrology'] + train['Horizontal_Distance_To_Roadways']) \/ 3\ntrain['Mean_Fire_Hyd']=(train['Horizontal_Distance_To_Fire_Points'] + train['Horizontal_Distance_To_Hydrology']) \/ 2 \n\ntrain[\"Vertical_Distance_To_Hydrology\"] = abs(train['Vertical_Distance_To_Hydrology'])\n\ntrain['Neg_EHyd'] = train.Elevation-train.Horizontal_Distance_To_Hydrology*0.2\n\n\ntest['HorizontalHydrology_HorizontalFire'] = (test['Horizontal_Distance_To_Hydrology']+test['Horizontal_Distance_To_Fire_Points'])\ntest['Neg_HorizontalHydrology_HorizontalFire'] = (test['Horizontal_Distance_To_Hydrology']-test['Horizontal_Distance_To_Fire_Points'])\ntest['HorizontalHydrology_HorizontalRoadways'] = (test['Horizontal_Distance_To_Hydrology']+test['Horizontal_Distance_To_Roadways'])\ntest['Neg_HorizontalHydrology_HorizontalRoadways'] = (test['Horizontal_Distance_To_Hydrology']-test['Horizontal_Distance_To_Roadways'])\ntest['HorizontalFire_Points_HorizontalRoadways'] = (test['Horizontal_Distance_To_Fire_Points']+test['Horizontal_Distance_To_Roadways'])\ntest['Neg_HorizontalFire_Points_HorizontalRoadways'] = (test['Horizontal_Distance_To_Fire_Points']-test['Horizontal_Distance_To_Roadways'])\n\ntest['Neg_Elevation_Vertical'] = test['Elevation']-test['Vertical_Distance_To_Hydrology']\ntest['Elevation_Vertical'] = test['Elevation'] + test['Vertical_Distance_To_Hydrology']\n\ntest['mean_hillshade'] = (test['Hillshade_9am']  + test['Hillshade_Noon']  + test['Hillshade_3pm'] ) \/ 3\n\ntest['Mean_HorizontalHydrology_HorizontalFire'] = (test['Horizontal_Distance_To_Hydrology']+test['Horizontal_Distance_To_Fire_Points'])\/2\ntest['Mean_HorizontalHydrology_HorizontalRoadways'] = (test['Horizontal_Distance_To_Hydrology']+test['Horizontal_Distance_To_Roadways'])\/2\ntest['Mean_HorizontalFire_Points_HorizontalRoadways'] = (test['Horizontal_Distance_To_Fire_Points']+test['Horizontal_Distance_To_Roadways'])\/2\n\ntest['MeanNeg_Mean_HorizontalHydrology_HorizontalFire'] = (test['Horizontal_Distance_To_Hydrology']-test['Horizontal_Distance_To_Fire_Points'])\/2\ntest['MeanNeg_HorizontalHydrology_HorizontalRoadways'] = (test['Horizontal_Distance_To_Hydrology']-test['Horizontal_Distance_To_Roadways'])\/2\ntest['MeanNeg_HorizontalFire_Points_HorizontalRoadways'] = (test['Horizontal_Distance_To_Fire_Points']-test['Horizontal_Distance_To_Roadways'])\/2\n\ntest['Slope2'] = np.sqrt(test['Horizontal_Distance_To_Hydrology']**2+test['Vertical_Distance_To_Hydrology']**2)\ntest['Mean_Fire_Hydrology_Roadways']=(test['Horizontal_Distance_To_Fire_Points'] + test['Horizontal_Distance_To_Hydrology'] + test['Horizontal_Distance_To_Roadways']) \/ 3 \ntest['Mean_Fire_Hyd']=(test['Horizontal_Distance_To_Fire_Points'] + test['Horizontal_Distance_To_Hydrology']) \/ 2\n\n\ntest['Vertical_Distance_To_Hydrology'] = abs(test[\"Vertical_Distance_To_Hydrology\"])\n\ntest['Neg_EHyd'] = test.Elevation-test.Horizontal_Distance_To_Hydrology*0.2\n\"\"\"\nNow we should seperate the training set from the labels and name them x and y then we will split them into training and test sets to be able to see how well it would do on unseen data which will give anestimate on how well it will do when testing on Kaggle test data. I will use the convention of using 80% of the data as training set and 20% for the test set.\n\"\"\"\ntrain.head()\ntest.head()\ntrain.shape\ntest.shape\nfrom sklearn.model_selection import train_test_split\nx = train.drop(['Cover_Type'], axis = 1)\ny = train['Cover_Type']\n\n\nx_train, x_val, y_train, y_val = train_test_split( x.values, y.values, test_size=0.2, random_state=42 )\nprint(x_train.shape)\nprint(x_val.shape)\nprint(y_train.shape)\nprint(y_val.shape)\n\"\"\"\nIt is important to know if the number of points in the classes are balanced. If the data is skewed then we will not be able to use accuracy as a performance metric since it will be misleading but if it is skewed we may use F-beta score or precision and recall. Precision or recall or F1 score. the choice depends on the problem itself. Where high recall means low number of false negatives , High precision means low number of false positives and F1 score is a trade off between them. You can refere to this article for more about precision and recall http:\/\/scikit-learn.org\/stable\/auto_examples\/model_selection\/plot_precision_recall.html\n\"\"\"\nunique, count= np.unique(y_train, return_counts=True)\nprint(\"The number of occurances of each class in the dataset = %s \" % dict (zip(unique, count) ), \"\\n\" )\n\"\"\"\nIt seems the data points in each class are almost balanced so it will be okay to use accuracy as a metric to measure how well the ML model performs\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_val = scaler.transform(x_val)\n\ntest = scaler.transform(test)\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score\nfrom sklearn.model_selection import GridSearchCV, cross_val_score, RandomizedSearchCV\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier , ExtraTreesClassifier\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom sklearn.linear_model import LogisticRegression\n\"\"\"\n## Select and Initialize Classifiers\n\nI have tried to select various classifiers. The key is a good validation score and if possible the use of a diffferent method\/classifier for the ensembling.\n\"\"\"\nrf_1 = RandomForestClassifier(n_estimators = 200,criterion = 'entropy',random_state = 0)\nrf_1.fit(X=x_train, y=y_train)\n\ny_pred_train_rf_1 = rf_1.predict(x_train)\ny_pred_val_rf_1 = rf_1.predict(x_val)\n\ny_pred_test_rf_1 = rf_1.predict(test)\nrf_2 = RandomForestClassifier(n_estimators = 200,criterion = 'gini',random_state = 0)\nrf_2.fit(X=x_train, y=y_train)\n\ny_pred_train_rf_2 = rf_2.predict(x_train)\ny_pred_val_rf_2 = rf_2.predict(x_val)\n\ny_pred_test_rf_2 = rf_2.predict(test)\net_1 = ExtraTreesClassifier(n_estimators = 200,criterion = 'entropy',random_state = 0)\net_1.fit(X=x_train, y=y_train)\n\ny_pred_train_et_1 = et_1.predict(x_train)\ny_pred_val_et_1 = et_1.predict(x_val)\n\ny_pred_test_et_1 = et_1.predict(test)\net_2 = ExtraTreesClassifier(n_estimators = 200,criterion = 'gini',random_state = 0)\net_2.fit(X=x_train, y=y_train)\n\ny_pred_train_et_2 = et_2.predict(x_train)\ny_pred_val_et_2 = et_2.predict(x_val)\n\ny_pred_test_et_2 = et_2.predict(test)\nlgb = LGBMClassifier(n_estimators = 200,learning_rate = 0.1)\nlgb.fit(X=x_train, y=y_train)\n\ny_pred_train_lgb = lgb.predict(x_train)\ny_pred_val_lgb = lgb.predict(x_val)\n\ny_pred_test_lgb = lgb.predict(test)\nlr_1 = LogisticRegression(solver = 'liblinear',multi_class = 'ovr',C = 1,random_state = 0)\nlr_1.fit(X=x_train, y=y_train)\n\ny_pred_train_lr_1 = lr_1.predict(x_train)\ny_pred_val_lr_1 = lr_1.predict(x_val)\n\ny_pred_test_lr_1 = lr_1.predict(test)\nxgb_1 = XGBClassifier(seed = 0,colsample_bytree = 0.7, silent = 1, subsample = 0.7, learning_rate = 0.1, objective = 'multi:softprob',\n                      num_class = 7,max_depth = 4, min_child_weight = 1, eval_metric = 'mlogloss', nrounds = 200)\nxgb_1.fit(X=x_train, y=y_train)\n\ny_pred_train_xgb_1 = xgb_1.predict(x_train)\ny_pred_val_xgb_1 = xgb_1.predict(x_val)\n\ny_pred_test_xgb_1 = xgb_1.predict(test)\nknn = KNeighborsClassifier(n_neighbors=5)  \n\nknn.fit(x_train, y_train)\n\ny_pred_train_knn = knn.predict(x_train)\ny_pred_val_knn = knn.predict(x_val)\n\ny_pred_test_knn = knn.predict(test)\n## Creating DF from Predections\n\nstack_train = pd.DataFrame([y_pred_train_rf_1,y_pred_train_rf_2,y_pred_train_et_1,y_pred_train_et_2,y_pred_train_lgb,\n                            y_pred_train_lr_1,y_pred_train_xgb_1,y_pred_train_knn])\n\nstack_val = pd.DataFrame([y_pred_val_rf_1,y_pred_val_rf_2,y_pred_val_et_1,y_pred_val_et_2,y_pred_val_lgb,\n                            y_pred_val_lr_1,y_pred_val_xgb_1,y_pred_val_knn])\n\nstack_test = pd.DataFrame([y_pred_test_rf_1,y_pred_test_rf_2,y_pred_test_et_1,y_pred_test_et_2,y_pred_test_lgb,\n                            y_pred_test_lr_1,y_pred_test_xgb_1,y_pred_test_knn])\nprint(stack_train.head())\nprint(stack_val.head())\n\nprint(stack_test.head())\n## Transpose - it will change row into columns and columns into rows\n\nstack_train = stack_train.T\nstack_val = stack_val.T\n\nstack_test = stack_test.T\nprint(stack_train.head())\nprint(stack_val.head())\nprint(stack_test.head())\nprint(stack_train.shape)\nprint(stack_val.shape)\nprint(stack_test.shape)\nstack_test.isnull().sum()\nlr_2 = LogisticRegression(solver = 'liblinear',multi_class = 'ovr',C = 5,random_state = 0)\nlr_2.fit(X=stack_train, y=y_train)\n\nstacked_pred_train = lr_2.predict(stack_train)\nstacked_pred_val = lr_2.predict(stack_val)\n\nstacked_pred_test = lr_2.predict(stack_test)\n#Id = test['Id']\n#test.drop(['Id'], inplace = True, axis = 1 )\n#-final_pred = lr_2.predict(test)\n\n\nsubmission_1 = pd.DataFrame()\nsubmission_1['Id'] = Id\nsubmission_1['Cover_Type'] = stacked_pred_test\nsubmission_1.to_csv('submission_stack.csv', index=False)\nsubmission_1.head(5)\n\"\"\"\n## CatBoostClassifier\n\"\"\"\nfrom catboost import Pool, CatBoostClassifier\n\ncat = CatBoostClassifier()\n\ncat.fit(x_train, y_train)\nprint('Accuracy of classifier on training set: {:.2f}'.format(cat.score(x_train, y_train) * 100))\nprint('Accuracy of classifier on test set: {:.2f}'.format(cat.score(x_val, y_val) * 100))\ncat_predictions = cat.predict(test)\nsubmission_2 = pd.DataFrame()\nsubmission_2['Id'] = Id\nsubmission_2['Cover_Type'] = cat_predictions\nsubmission_2.to_csv('submission.csv', index=False)\nsubmission_2.head(5)\n\"\"\"\n## XGBoostClassifier\n\"\"\"\nXGB = XGBClassifier()\n\nXGB.fit(x_train, y_train)\nprint('Accuracy of classifier on training set: {:.2f}'.format(XGB.score(x_train, y_train) * 100))\nprint('Accuracy of classifier on test set: {:.2f}'.format(XGB.score(x_val, y_val) * 100))\nXGB_predictions = XGB.predict(test)\nsubmission_3 = pd.DataFrame()\nsubmission_3['Id'] = Id\nsubmission_3['Cover_Type'] = XGB_predictions\nsubmission_3.to_csv('submission_XGB.csv', index=False)\nsubmission_3.head(5)\n\"\"\"\n## RandomForestClassifier\n\"\"\"\nRFC = RandomForestClassifier()\n\nRFC.fit(x_train, y_train)\nprint('Accuracy of classifier on training set: {:.2f}'.format(RFC.score(x_train, y_train) * 100))\nprint('Accuracy of classifier on test set: {:.2f}'.format(RFC.score(x_val, y_val) * 100))\nRFC_predictions = RFC.predict(test)\nsubmission_4 = pd.DataFrame()\nsubmission_4['Id'] = Id\nsubmission_4['Cover_Type'] = RFC_predictions\nsubmission_4.to_csv('submission_RFC.csv', index=False)\nsubmission_4.head(5)","meta":"{'source': 'AI4Code', 'id': '357c717cce4128'}"}
{"id":"73867","text":"\"\"\"\n# Decision tree implementation with numpy only\n\n### This notebook is dedicated to understanding Decision Tree algorithm because always there is a group of people who use it without understanding things under the hood\n![tree-img](https:\/\/dodskypict.com\/D\/Dark-Forest-Wallpaper-On-Wallpaper-Hd-17.jpg)\n\"\"\"\n\"\"\"\n# Theory\n\n## In this notebook you will see implementation of classification decision tree. At first, few words about idea that lies under that algorithm\n\n1. <font size=\"3\"><i>During the algorithm work train data will be splitted based on some measurement of how good our split is.\n   For classification problem there are two main indicators: \"gini index\" and \"information entropy\".\n   In this notebook <b>\"information entropy\"<\/b> will be used.<\/i><\/font>\n2. <font size=\"3\"><i>Decision tree is a structure that uses recursive algorithm of fitting, so you should repeat at least <b>what recursion is<\/b>.<\/i><\/font>\n3. <font size=\"3\"><i>If you don't want to be lost every couple of strings you should repeat basics of <b>numpy.array<\/b> creation and <b>basics operations with them<\/b>.<\/i><\/font>\n\n\"\"\"\n\"\"\"\n# 1. Information Entropy\n\n<font size=\"3\"><b>I will tell you nothing about origin of formula because this notebook is not about math. All need resource you will find at the end of notebook. Just take it for granted, there is one interesting formula that shows how chaotic our system is<\/b><\/font>\n<br><br>\n\n<p style=\"text-align: center;\"><font size=\"8\"><b>-$\\sum_{i=1}^{N} P_i log(P_i)$<\/b><\/font><\/p>\n<br><br>\n\n<font size=\"3\">For example suppose we have a system with 4 balls where <b>all balls are green<\/b>. In that case we have only one possible state in our system and our formula would be like this:<\/font>\n<br><br>\n\n<p style=\"text-align: center;\"><font size=\"8\"><b>-$\\sum_{i=1}^{4} 1* log(1)$<\/b><\/font><\/p>\n<br><br>\n\n<font size=\"3\">Because the probability of random pulled ball of being green(our state) is one, our formula will give us zero (this system doesn't give as any information and we certainly know the color of our ball)<\/font> \n<br><br>\n\n<font size=\"3\">Now let's consider system that will give as the largest entropy. Suppose we have a system with 4 balls but now each of them has <b>different color<\/b> (green, red, black and white). Our formula would be like this<\/font> \n<br><br>\n\n<p style=\"text-align: center;\"><font size=\"8\"><b>-$\\sum_{i=1}^{4}$$^1\/_4$ $log$($^1\/_4$)<\/b><\/font><\/p>\n<br><br>\n\n<font size=\"3\">Because of our logarithm has small number and there is a minus at the start of the formula our entropy becomes large<\/font> \n<br><br>\n\n<font size=\"3\">Well, it's enough for understanding. Just remember that our formula give <b>larger<b> value when there are many classes and vice versa when we have a little amount of classes<\/font> \n\"\"\"\n\"\"\"\n# 2. Information gain \n\n<font size=\"4\">After we can calculate entropy we can also calculate information gain<\/font><br><br>\n\n<p style=\"text-align: center;\"><font size=\"5\">I(node) = E(node) - ($\\frac{left}{n}$ * E(left_node) + $\\frac{right}{n}$ * E(right_node))<\/font><\/p><br>\n\n<font size=\"4\">Information gain is a indicator of how much chaos can be reduced by particular split.<br><br>We want to reduce chaos as much as possible, so we will search for split that gives us largest information gain.<br><br>Why we take weighted sum of left and right node? Because if you watch carefully you can observe that not weighted sum will give us situation when samples are splitted one by one<\/font>\n\n\n\n\n\"\"\"\n\"\"\"\n# 3. Recursive approach in the algorithm\n\n<font size=\"4\">We will apply greedy algorithm and the main steps are:<\/font>\n<br>\n1. Take our data\n2. Iterate through all features\n3. In each feature iterate through all values\n4. For each pair feature\/value calculate the entropy and information gain\n5. Find the best pair that give us largest information gain\n6. Split our data by that pair\n7. Give splitted data to left and right node of the tree\n8. Repeat\n\n\"\"\"\nimport numpy as np\ndef entropy(y):\n    cnt = np.bincount(y)\n    # creates an array cnt, cnt[i] = count of entries of number i.\n    \n    probabilities = cnt \/ len(y)\n    # array of probabilities for each state\n        \n    res = -np.sum([p * np.log(p) for p in probabilities if p > 0])\n    # calculating entropy\n    return res\n\n\nclass ClassifyNode:\n    \n    # ClassidyNode class contains child nodes, best threshold and best feature for splitting\n    \n    def __init__(self, feature=None, threshold=None, l_node=None, r_node=None, mark=None):\n        \n        self.feature = feature     \n        # idx of feature for splitting\n        \n        self.threshold = threshold\n        # threshold value for splitting\n        \n        self.l_node = l_node       \n        # left ClassifyNode object \n        \n        self.r_node = r_node       \n        # right ClassifyNode object \n        \n        self.mark = mark           \n        # if it is a leaf node, it gets a class mark \n        \n    def is_leaf_node(self):\n        return self.mark is not None\n        \nclass MyDecisionTreeClassifier:\n    \n    def __init__(self, min_samples_split=2, max_depth=\"inf\", n_feats=None):\n        self.min_samples_split = min_samples_split \n        # min number of samples in node to allow splitting\n        \n        self.max_depth = max_depth\n        # max depth of tree\n        \n        self.n_feats = n_feats\n        # if n_feats < X.shape[1] then choose features randomly\n        \n        self.root = None\n        # root ClassifyNode object\n        \n    def fit(self, X, y):\n        \n        self.n_feats = X.shape[1] if not self.n_feats else min(self.n_feats, X.shape[1])\n        # avoid situation when n_feats > real number of features \n        \n        self.root = self._build_node(X, y)\n        # The first node for splitting\n        \n    \n        \n        \n    def predict(self, X):\n        return np.array([self._traverse_tree(x, self.root) for x in X])\n        # see _traverse_tree function\n    \n    \n    def _traverse_tree(self, x, node):\n        if node.is_leaf_node():\n        # if current node is terminal then return class with biggest occurrence level\n        \n            return node.mark\n        \n        \n        if x[node.feature] <= node.threshold:  \n        # chek feature in this node and compare node threshold with feature value in x \n            \n            return self._traverse_tree(x, node.l_node)\n            # send x to child node until it gets the leaf node\n            \n        return self._traverse_tree(x, node.r_node)\n    \n        \n    \n    \n    \n    def _build_node(self, X, y, depth=0):\n        \n        n_samples, n_features = X.shape \n        # in arrays and Dataframes shapes are in format (n_samples, n_features)\n        \n        n_labels = len(np.unique(y))\n        # array of unique classes\n        \n        # check stopping criteria (max_depth & min_samples_split)\n        \n        if (depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split):\n            leaf_mark = self._most_encountered_mark(y)\n            return ClassifyNode(mark=leaf_mark)\n        \n        \n        feature_idxs = np.random.choice(n_features, self.n_feats, replace=False)\n        # if we decided to choose a subset of features\n        \n        best_feature, best_thresh = self._best_split(X, y, feature_idxs)\n        # see _best_split()\n        \n        left_idxs, right_idxs = self._split(X[:, best_feature], best_thresh)\n        # see _split()\n        \n        left = self._build_node(X[left_idxs, :], y[left_idxs], depth+1)\n        right = self._build_node(X[right_idxs, :], y[right_idxs], depth+1)\n        # after we find best split, we give left data and right data to child nodes\n        \n        return ClassifyNode(best_feature, best_thresh, left, right)\n        \n        \n    def _best_split(self, X, y, feature_idxs):\n        \n        best_information_gain = -1\n        \n        split_idx, split_thresh = None, None\n        \n        for idx in feature_idxs:\n            # for each feature\n            \n            X_column=X[:, idx]\n            # take all values in this features\n\n            thresholds = np.unique(X_column)\n            # drop similar values\n            \n            for threshold in thresholds:\n                # for each unique value\n                \n                gain = self._information_gain(y, X_column, threshold)\n                # see _information_gain()\n                \n                if gain > best_information_gain:\n                    best_information_gain = gain\n                    split_idx = idx\n                    split_thresh = threshold\n                # save information gain in case it better than previous\n                    \n        return split_idx, split_thresh\n    \n    \n    def _information_gain(self, y, X_column, split_thresh):\n        \n        parent_entropy = entropy(y)\n        # see entropy()\n        \n        left_idxs, right_idxs = self._split(X_column, split_thresh)\n        # see _split()\n        \n        if len(left_idxs) == 0 or len(right_idxs) == 0:\n            return 0\n        # check if we splitted nothing\n        \n        n = len(y)\n        n_l, n_r = len(left_idxs), len(right_idxs)\n        # number of samples in left and right nodes\n        \n        entropy_l, entropy_r = entropy(y[left_idxs]), entropy(y[right_idxs])\n        \n        child_entropy = (n_l\/n)*entropy_l + (n_r\/n)*entropy_r\n        # weighted sum of left and right child\n        \n        info_gain = parent_entropy - child_entropy\n        # finally calculated information gain \n        \n        return info_gain\n    \n    \n    def _split(self, X_column, split_thresh):\n        left_idxs = np.argwhere(X_column <= split_thresh).flatten()\n        right_idxs = np.argwhere(X_column > split_thresh).flatten()\n        \n        return left_idxs, right_idxs\n        \n    \n    def _most_encountered_mark(self, y):\n        most_encountered = np.argmax(np.bincount(y))\n        return most_encountered\n\"\"\"\n# Comparing\n\n## Let's compare our algorithm with built-in DecisionTree in sklearn\n\"\"\"\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\n\n\ndef accuracy(y_true, y_pred):\n    accuracy = np.sum(y_true == y_pred)\/len(y_true)\n    return accuracy\n\n\ndata = datasets.load_breast_cancer()\n\nX = data.data\ny = data.target\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\nprint(\"Train shape:\", X_train.shape)\n\nsk_clf = DecisionTreeClassifier(max_depth=100, criterion='entropy', random_state=0)\nmy_clf = MyDecisionTreeClassifier(max_depth=100)\n\nmy_clf.fit(X_train, y_train)\nsk_clf.fit(X_train, y_train)\n\nmy_y_pred = my_clf.predict(X_train)\nsk_y_pred = sk_clf.predict(X_train)\n\nmy_acc = accuracy(y_train, my_y_pred)\nsk_acc = accuracy(y_train, sk_y_pred)\n\nprint(\"Working test on train data\", my_acc)\nprint(\"Working test on train data sklearn\", sk_acc)\n\nmy_y_pred = my_clf.predict(X_test)\nsk_y_pred = sk_clf.predict(X_test)\n\nmy_acc = accuracy(y_test, my_y_pred)\nsk_acc = accuracy(y_test, sk_y_pred)\n\nprint(\"Working test on test data\", my_acc)\nprint(\"Working test on test data sklearn\", sk_acc)\n\"\"\"\n# Compare time of fitting\n\"\"\"\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\n\n\ndef accuracy(y_true, y_pred):\n    accuracy = np.sum(y_true == y_pred)\/len(y_true)\n    return accuracy\n\n\ndata = datasets.load_breast_cancer()\n\nX = data.data\ny = data.target\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\nprint(\"Train shape:\", X_train.shape)\n\nsk_clf = DecisionTreeClassifier(max_depth=100, criterion='entropy', random_state=0)\nmy_clf = MyDecisionTreeClassifier(max_depth=100)\n\n%time my_clf.fit(X_train, y_train)\n%time sk_clf.fit(X_train, y_train)\n\n\"\"\"\n<font size=\"4\"><b>Our algorithm was written without any optimizing so it works much longer<br>\nthan built-in Decision Tree, but it's enough for understanding what's going on<\/b><\/font>\n\"\"\"\n\"\"\"\n# Sources\n1. Infornmation entropy (rus) - https:\/\/www.youtube.com\/watch?v=KMEqfb6KO0c\n2. Information entropy (eng) - https:\/\/www.youtube.com\/watch?v=2s3aJfRr9gE\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '87ead6fad52809'}"}
{"id":"57111","text":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \ndata = pd.read_csv('\/kaggle\/input\/did-it-rain-in-seattle-19482017\/seattleWeather_1948-2017.csv') \ndata.head()\n\"\"\"\n# Data Cleaning\n\"\"\"\n\"\"\"\n### We need to drop particular columns, that we don't need. \n- Date, but we shall extract day, month and year instead\n- PRCP (otherwise it would be a cheating)\n\n\"\"\"\n#1. Drop the PRCP\ndata=data.drop([\"PRCP\"],axis=1)\n\n# 2 Converting object into datetime to extract day, month and year\nfrom datetime import datetime\ndata[\"DATE\"]=pd.to_datetime(data[\"DATE\"], format= \"%Y-%m-%d\")\n\n# Extract day, month and year\ndata[\"DAY\"]=data[\"DATE\"].dt.day\ndata[\"MONTH\"]=data[\"DATE\"].dt.month\ndata[\"YEAR\"]=data[\"DATE\"].dt.year\ndata=data.drop([\"DATE\"], axis=1)\n\n#Rearrange columns\ndata=data[[\"DAY\", \"MONTH\", \"YEAR\", \"TMAX\", \"TMIN\", \"RAIN\"]]\ndata.head()\ndata.tail()\nx=data.iloc[:,:-1].values\ny=data.iloc[:,-1].values\n\"\"\"\n## Encoding \n\"\"\"\n#Label Encoding for RAIN column\nfrom sklearn.preprocessing import LabelEncoder\nle=LabelEncoder()\ny=le.fit_transform(y)\ny\n\"\"\"\n## Splitting the dataset for Training and Test set\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=42)\n\"\"\"\n##  Feature Scaling\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nss=StandardScaler()\nx_train=ss.fit_transform(x_train)\nx_test=ss.transform(x_test)\n\"\"\"\n## Building the ANN\n\"\"\"\n# Importing the Keras libraries and packages\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\n\n# Initialising the ANN\nclassifier = Sequential()\n\n# Adding the input layer and the first hidden layer\nclassifier.add(Dense(units = 32, kernel_initializer = 'uniform', activation = 'relu', input_dim = 5))\n\n# Adding the second hidden layer\nclassifier.add(Dense(units = 16, kernel_initializer = 'uniform', activation = 'relu'))\n\n# Adding the third hidden layer\nclassifier.add(Dense(units = 8, kernel_initializer = 'uniform', activation = 'relu'))\n\n# Adding the output layer\nclassifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))\n\n# Compiling the ANN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting the ANN to the Training set\nclassifier.fit(x_train, y_train, batch_size = 10, epochs = 100)\n\"\"\"\n## Prediction: \n\"\"\"\n\"\"\"\n- Day : 16\n- Month: 11\n- Year: 1992\n- TMAX:54\n- TMIN: 30\n\n\"\"\"\nclassifier.predict(ss.transform([[16,11,1992,54,30]]))>0.5\n\n\"\"\"\n## Predicting the test set results\n\"\"\"\ny_pred=ann.predict(x_test)\ny_pred=(y_pred>0.5)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\n\"\"\"\n## Present Confusion Matrix and Accuracy Score\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm=confusion_matrix(y_test, y_pred)\ncm\naccuracy_score(y_test, y_pred)","meta":"{'source': 'AI4Code', 'id': '696769dbc04e12'}"}
{"id":"60150","text":"import numpy as np\nimport pandas as pd\nimport sqlite3   # Library required to read db file\nimport matplotlib.pyplot as plt\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\n\"\"\"\n## Step 1: Download the data\n\nWe first need to download the latest version of the database from the dropbox folder into the local directory. We will run all our queries against this local db file\n\"\"\"\n!curl -L -o \"\/kaggle\/working\/covid-india.db\" \"https:\/\/www.dropbox.com\/s\/hbe04q6vtzapdam\/covid-india.db?dl=1\"\n\"\"\"\n## Step 2: Access the data\n\nHaving downloaded a local copy of the remote data, we can now run SQL queries against it. \n\nThe Wiki here [https:\/\/github.com\/IBM\/covid19-india-data\/wiki\/States](https:\/\/github.com\/IBM\/covid19-india-data\/wiki\/States) provides the schema (tables, and columns) of the database\n\"\"\"\ndef run_query(querystr: str) -> list:\n    con = sqlite3.connect('\/kaggle\/working\/covid-india.db')\n    cursor = con.cursor()\n    cursor.execute(querystr)\n    data = cursor.fetchall()\n    con.close()\n    return data\n\"\"\"\n## Analysis 1: Daily new cases\n\"\"\"\nquerystr = 'SELECT D1.date AS date, D1.cases_positive as DL, K1.positive_cases AS KL, K2.cases_new AS KA ' + \\\n            'FROM DL_case_info D1 JOIN KL_daily_summary K1 on D1.date == K1.date ' + \\\n            'JOIN KA_case_info K2 ON D1.date == K2.date ORDER BY date'\n\ndata = run_query(querystr)   # the returned data is a list of tuples (date, DL_occupancy, WB_occupancy)\n\ndata = pd.DataFrame(data, columns=['Date', 'DL', 'KL', 'KA'])\ndata.head()\ndata.plot(x='Date', title='Daily new confirmed cases')\n\"\"\"\n## Analysis 2: COVID-19 Bed Occupancy\n\"\"\"\nquerystr = 'SELECT D1.date, D2.hospital_beds_occupied * 100.0 \/ D2.hospital_beds_total AS DL_occupancy, ' + \\\n            'W1.covid19_bed_occupancy AS WB_occupancy FROM DL_case_info D1 JOIN DL_patient_mgmt D2 ON D1.date == D2.date ' + \\\n            'JOIN WB_hospital W1 ON D1.date == W1.date ORDER BY D1.date ASC'\n\ndata = run_query(querystr)   # the returned data is a list of tuples (date, DL_occupancy, WB_occupancy)\n\ndata = pd.DataFrame(data, columns=['Date', 'DL_occupancy', 'WB_occupancy'])\ndata.head()\ndata.plot(x='Date', title='COVID-19 Bed Occupancy in DL and WB')\n\"\"\"\n**This notebook demonstrated a simple workflow of loading the database and executing queries against it to extract the data. You can use this notebook as reference to run more complex queries against the database and model\/analyse\/visualize various aspects of the data**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6ee460bf3173e5'}"}
{"id":"82236","text":"\"\"\"\nIn this short kernel, I am going to show you how to choose the `number of principal components` when using principal component analysis for dimensionality reduction as in MoA Competition \n\"\"\"\n\"\"\"\nFull Post for detailed Explanation :- https:\/\/www.mikulskibartosz.name\/pca-how-to-choose-the-number-of-components\/\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# If you like it, Do Upvote :)\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\n\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\nos.listdir('..\/input\/lish-moa')\ntrain_features = pd.read_csv('..\/input\/lish-moa\/train_features.csv')\ntrain_targets_scored = pd.read_csv('..\/input\/lish-moa\/train_targets_scored.csv')\ntrain_targets_nonscored = pd.read_csv('..\/input\/lish-moa\/train_targets_nonscored.csv')\ntest_features = pd.read_csv('..\/input\/lish-moa\/test_features.csv')\ntrain_features.info()\ntrain_features.head()\nGENES = [col for col in train_features.columns if col.startswith('g-')]\nCELLS = [col for col in train_features.columns if col.startswith('c-')]\nlen(GENES+CELLS)\n\"\"\"\n## Choosing PCA on Genes columns \n\"\"\"\n\"\"\"\nDon\u2019t do it. Don\u2019t choose the number of components manually.Instead of that, use the option that allows you to set the variance of the input that is supposed to be explained by the generated components.\n\"\"\"\n\"\"\"\n### Remember to scale the data to the range between 0 and 1 before using PCA!\nTypically, we want the explained variance to be between 95\u201399%. \n\"\"\"\nfrom sklearn.preprocessing import QuantileTransformer\nfor col in (GENES + CELLS):\n    transformer = QuantileTransformer(random_state=0, output_distribution=\"normal\")\n    vec_len = len(train_features[col].values)\n    vec_len_test = len(test_features[col].values)\n    raw_vec = train_features[col].values.reshape(vec_len, 1)\n    transformer.fit(raw_vec)\n\n    train_features[col] = transformer.transform(raw_vec).reshape(1, vec_len)[0]\n    test_features[col] = transformer.transform(test_features[col].values.reshape(vec_len_test, 1)).reshape(1, vec_len_test)[0]\n    \ndata = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])\n\"\"\"\n### Now we have standardized our Data\n\"\"\"\n\"\"\"\nFrom the Scikit-learn implementation, we can get the information about the explained variance and plot the cumulative variance.\n\"\"\"\npca = PCA().fit(data)\n\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (12,6)\n\nfig, ax = plt.subplots()\nxi = np.arange(1, 773, step=1)\ny = np.cumsum(pca.explained_variance_ratio_)\n\nplt.ylim(0.0,1.1)\nplt.plot(xi, y, marker='o', linestyle='--', color='b')\n\nplt.xlabel('Number of Components')\nplt.xticks(np.arange(0, 750, step=50)) #change from 0-based array index to 1-based human-readable label\nplt.ylabel('Cumulative variance (%)')\nplt.title('The number of components needed to explain variance')\n\nplt.axhline(y=0.95, color='r', linestyle='-')\nplt.text(0.5, 0.85, '95% cut-off threshold', color = 'red', fontsize=16)\n\nax.grid(axis='x')\nplt.show()\n\"\"\"\nOn the plotted chart, we see what number of principal components we need.\n\"\"\"\n\"\"\"\n## In this case, to get 95% of variance explained I need 600 principal components.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '96f051ce680a4e'}"}
{"id":"20469","text":"\"\"\"\n**Data Preprocessing and Feature Engineering (Exploratory Data Analysis)**\n\n1. Studying the feature statistics\n2. Impute missing values (with mean, median, mode)\n3. Aggregation\n4. Sampling\n5. Dimensionality reduction (PCA)\n6. Feature subset selection\n7. Feature creation\n8. Discretization and binarization (with Gini Index \/ Entropy)\n9. Variable transformation and binning\n\"\"\"\n\"\"\"\n**1. Studying the feature statistics**\n\"\"\"\nimport matplotlib.pyplot as plt # data visualisation\nimport seaborn as sb # data visualisation\nimport pandas as pd # dataframes\nimport math # math formulae\n# importing training data\ndf = pd.read_csv('..\/input\/new-york-city-taxi-fare-prediction\/train.csv', nrows = 1_000_000)\ndf.head()\n# removing 'key' column\ndf = df.drop(columns = ['key'])\ndf.head()\n# dimensions of dataset\ndf.shape\n# checking for duplicates\nduplicate_rows = df[df.duplicated()]\nduplicate_rows.shape\n# data type of features and target\ndf.dtypes\n# statistical data for numerical features and target\ndf.describe()\n\"\"\"\nNotes:\n* Negative\/zero fares present\n* Zero passengers trips present\n* Outliers present -> 208 passengers\n* Invalid coordinates -> lat = (90,-90), lon = (180,-180)\n* New York coordinates -> lat = (40.2940,45.0042), lon = (71.4725,79.4554)\n* https:\/\/www.netstate.com\/states\/geography\/ny_geography.htm\n\"\"\"\n# removing invalid coordinates\ndf = df[df['pickup_longitude'] <= -71.4725]\ndf = df[df['pickup_longitude'] >= -79.4554]\n\ndf = df[df['pickup_latitude'] <= 45.0042]\ndf = df[df['pickup_latitude'] >= 40.2940]\n\ndf = df[df['dropoff_longitude'] <= -71.4725]\ndf = df[df['dropoff_longitude'] >= -79.4554]\n\ndf = df[df['dropoff_latitude'] <= 45.0042]\ndf = df[df['dropoff_latitude'] >= 40.2940]\n\ndf.shape\n# removing trips with zero\/negative fares\ndf = df[df['fare_amount'] > 0]\ndf.shape\n# removing trips with zero passengers\ndf = df[df['passenger_count'] > 0]\ndf.shape\n# checking statistical data again\ndf.describe()\n# changing 'pickup_datetime' to datetime data type\ndf['pickup_datetime'] = pd.to_datetime(df['pickup_datetime'], format = '%Y-%m-%d %H:%M:%S %Z')\ndf.dtypes\n\"\"\"\n**2. Input missing values**\n\"\"\"\n# checking for null values\ndf.isnull().sum()\n\"\"\"\nNotes:\n* To fill in null values with mean if any\n\"\"\"\n\"\"\"\n**3. Aggregation**\n\nTo group by:\n* Year\n* Month\n* Hour\n* Number of Passengers\n* Distance\n\"\"\"\n# sorting df by 'pickup_datetime'\ndf = df.sort_values('pickup_datetime')\ndf\n# obtaining year, month and hour attributes from 'pickup_datetime'\ndf['year'] = df['pickup_datetime'].dt.strftime('%Y')\ndf['month'] = df['pickup_datetime'].dt.strftime('%m')\ndf['hour'] = df['pickup_datetime'].dt.strftime('%H')\ndf\n# changing year, month and hour attributes\ndf[['year', 'month', 'hour']] = df[['year', 'month', 'hour']].apply(pd.to_numeric)\ndf.dtypes\n# calculating trip distance using haversine formula\ndef haversine(start_lon, start_lat, end_lon, end_lat):\n    earth_radius = 6371\n    start_lon, start_lat, end_lon, end_lat = map(math.radians, [start_lon, start_lat, end_lon, end_lat])\n    lat_diff = end_lat - start_lat\n    lon_diff = end_lon - start_lon\n    \n    a = pow(math.sin(lat_diff\/2), 2) + math.cos(start_lat) * math.cos(start_lat) * pow(math.sin(lon_diff\/2), 2)\n    c = 2 * math.asin(math.sqrt(a))\n    dist = earth_radius * c\n    \n    return dist\n# adding distance column to dataframe\ndist_array = []\n\nfor i in range(df.shape[0]):\n    plon = df.iloc[i]['pickup_longitude']\n    plat = df.iloc[i]['pickup_latitude']\n    dlon = df.iloc[i]['dropoff_longitude']\n    dlat = df.iloc[i]['dropoff_latitude']\n    dist = haversine(plon, plat, dlon, dlat)\n    dist_array.append(dist)\n    \ndf['distance in kilometres'] = dist_array\ndf\ndf.describe()\n# trips with zero distances\nzero_dist = df[df['distance in kilometres'] == 0]\nzero_dist.shape\n# removing zero distance trips\ndf = df[df['distance in kilometres'] > 0]\ndf.describe()\n# relationship between distance in kilometres and fare_amount\nsb.relplot(data = df, x = 'distance in kilometres', y = 'fare_amount')\n# frequency of fare_amount\ndf['fare_amount'].plot.hist(bins = 100, figsize=(8,2))\n# mean by year\nyearly_mean = df.groupby(['year']).mean()\nyearly_mean\nyears = df['year'].unique()\nsb.barplot(x = years, y = yearly_mean['fare_amount'])\n# mean by month\nmonthly_mean = df.groupby('month').mean()\nmonthly_mean\nmonths = df['month'].unique()\nsb.barplot(x = months, y = monthly_mean['fare_amount'])\n# mean by hour\nhourly_mean = df.groupby('hour').mean()\nhourly_mean\nhours = df['hour'].unique()\nsb.barplot(x = hours, y = hourly_mean['fare_amount'])\n\"\"\"\nNotes:\n* Gradual increase in mean fare amount from 2009 to 2015\n* Mean fare amount increases sharply from 01:00 to 05:00\n* The month which the trip was taken does not seem to impact fare amount\n\"\"\"\n# mean by number of passengers\npass_mean = df.groupby(['passenger_count']).mean()\npass_mean\nnum_of_pass = df['passenger_count'].unique()\nsb.barplot(x = num_of_pass, y = pass_mean['fare_amount'])\n\"\"\"\nNotes:\n* The number of passengers does not seem to impact the fare amount\n\"\"\"\n\"\"\"\n**6. Feature Subset Selection**\n\n* Approaches:\n1. Filter -> Pearson coefficient to measure correlation between features\n2. Wrapper -> Forward selection and backward elimination\n\"\"\"\n# filter approach using Pearson correlation\npearson_corr = df.corr()\nplt.figure(figsize = (10,5))\nsb.heatmap(data = pearson_corr, cmap = \"Reds\", annot = True)\n# listing correlations of features with target\ncorrelations = abs(pearson_corr['fare_amount'])\ncorrelations\n\"\"\"\n**Notes:**\n* Distance has the highest correlation with target with Pearson coefficient of 0.795\n\"\"\"\ndf\n# wrapper method: forward selection\n# estimator: LinearRegression\n# cross-validation: 5-fold\nfrom sklearn.linear_model import LinearRegression\nfrom mlxtend.feature_selection import SequentialFeatureSelector as SFS\n\nX = df.iloc[:,6:]\ny = df.iloc[:,0]\nlinear = LinearRegression()\nsfs = SFS(linear, k_features = 'best', forward = True, floating = False, verbose = 0, cv = 5)\nsfs = sfs.fit(X,y)\n# Best feature at each step\nsfs.subsets_\n# name of top features\nsfs.k_feature_names_\n# cross-validation score\nsfs.k_score_\n\"\"\"\n**Notes**\n* Distance, year and passenger count were identified as better features in this order\n* Cross-validation score: 0.581\n\"\"\"\n# wrapper method: backward selection\n# estimator: LinearRegression\n# cross-validation: 5-fold\nfrom sklearn.linear_model import LinearRegression\nfrom mlxtend.feature_selection import SequentialFeatureSelector as SFS\n\nX = df.iloc[:,6:]\ny = df.iloc[:,0]\nlinear = LinearRegression()\nsfs = SFS(linear, k_features = 'best', forward = False, floating = False, verbose = 0, cv = 5)\nsfs = sfs.fit(X,y)\n# Best feature at each step\nsfs.subsets_\n# name of top features\nsfs.k_feature_names_\n# cross-validation score\nsfs.k_score_\n\"\"\"\n**Notes**\n* Distance, year and passenger count were identified as better features in this order as well\n* Cross-validation score: 0.581\n\"\"\"\n\"\"\"\n**7. Feature Creation**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2580e0cfe50338'}"}
{"id":"26082","text":"\"\"\"\n*Please upvote if you liked this kernel ;)*\n\n*And be sure to check my [WoW Battleground EDA & Prediction](https:\/\/www.kaggle.com\/mandaloreultimate\/world-of-warcraft-bg-eda-prediction\/) as well*\n\"\"\"\n\"\"\"\n![title](https:\/\/i.imgur.com\/ibGU9gL.png)\n\"\"\"\n\"\"\"\nIn this kernel we are going to investigate the life of one of the *World of Warcraft* servers back in 2008, from the Horde faction perspective. I was initially inspired by two great kernels by [Thiago Balbo](https:\/\/www.kaggle.com\/thibalbo) and [33Vito](https:\/\/www.kaggle.com\/tonyliu), both of which were written on **R**, so I challenged myself to do my own research on **Python**, focusing heavily on visualization aspect with the amazing **Plotly** library. All right, let's get started, shall we?\n\"\"\"\n\"\"\"\n# Table of Contents\n* [Preparing the Data](#1)\n  * [Input Files Report](#2)\n  * [Data Cleaning](#3)\n* [Expansions](#4)\n* [Race\/Class Statistics](#5)\n* [Players Activity](#6)\n  * [Throughout the Year](#7)\n  * [Average Day](#8)\n* [Guilds](#9)\n* [Levelling](#10)\n* [PVE](#11)\n  * [Dungeons & Raids](#12)\n  * [Endgame](#13)\n* [PVP](#14)\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nsns.set()\nimport matplotlib.pyplot as plt\n%config InlineBackend.figure_format = 'svg' \n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport gc\n\"\"\"\n# Preparing the Data <a id=\"1\"><\/a>\n\n### Input Files Report <a id=\"2\"><\/a>\n\"\"\"\nprint('%-33s %d' % ('Input files available:', len(os.listdir('..\/input'))))\nfor i in range(34):\n    print('-',end='')\nprint('-')\nfor file in os.listdir(\"..\/input\/\"):\n    unit = 'MB'\n    size = os.stat('..\/input\/' + file).st_size\n    if round(size \/ 2**20, 2) < 0.5:\n        size = round(size \/ 2**10, 2)\n        unit = 'KB'\n    else:\n        size = round(size \/ 2**20, 2)\n    print('%-25s %6.2f %2s' % (file, size, unit))\n\"\"\"\n### Data Cleaning <a id=\"3\"><\/a>\n\nSince the main dataframe file, *wowah_data.csv*, is extremely large, containing over **10 million** records, we will need to use special function to reduce memory usage, unless we want to run out of RAM half the way. And of course, since we are dealing with **big data** here, we will also need to regularly use **del** and *gc.collect()*. The rest of the files aren't that big, so we can read them with the standard function; a bit of data cleaning is required though, as for some reason several locations names contain Chinese symbols. We are also going to add new specific columns to the main dataframe that'll come handy in the future. Note that *char* column name is misleading, as its actually **players' id**, not **characters'** one. I renamed it and created another column for the latter; chars' id was constructed as *race_id+class_id#player_id*. It's obviously not 100% accurate as some players can have several characters with identical race and class, but we are assuming that's not a standard practice so a few mistakes are acceptable.\n\"\"\"\n#Source kernel: https:\/\/www.kaggle.com\/arjanso\/reducing-dataframe-memory-size-by-65\ndef reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) \/ start_mem))\n    \n    return df\n\ndef import_data(file):\n    \"\"\"create a dataframe and optimize its memory usage\"\"\"\n    df = pd.read_csv(file, parse_dates=True, keep_date_col=True)\n    df = reduce_mem_usage(df)\n    return df\nwowah = import_data('..\/input\/wowah_data.csv')\nzones = pd.read_csv('..\/input\/zones.csv', encoding='iso-8859-1')\nlocation_coords = pd.read_csv('..\/input\/location_coords.csv', encoding='iso-8859-1')\nlocations = pd.read_csv('..\/input\/locations.csv', encoding='iso-8859-1')\nwowah.rename({'char': 'player', \n              ' level': 'level',\n              ' race': 'race',\n              ' charclass': 'class',\n              ' zone': 'zone',\n              ' guild': 'guild',\n              ' timestamp': 'timestamp'}, axis=1, inplace=True)\nzones['Zone_Name'].replace({'Dalaran<U+7AF6><U+6280><U+5834>': 'Dalaran Arena'}, inplace=True)\nwowah['zone'].replace({'Dalaran\u7af6\u6280\u5834': 'Dalaran Arena'}, inplace=True)\n\ndef time_transform(x):\n    y = x.split()[0]\n    return y[:-2] + '20' + y[-2:]\n\nwowah['date'] = wowah['timestamp'].apply(time_transform)\nwowah['time'] = wowah['timestamp'].apply(lambda x: x.split()[1][:-4] + '0')\n\nzones_dict = zones[['Zone_Name', 'Type']].set_index(['Zone_Name']).T.to_dict('records')[0]\nwowah['zone_type'] = wowah['zone'].map(zones_dict)\n\nwowah['class_id'] = np.array(pd.factorize(wowah['class'])[0])\nwowah['race_id'] = np.array(pd.factorize(wowah['race'])[0])\nwowah['class_id'] = wowah['class_id'].astype(str)\nwowah['race_id'] = wowah['race_id'].astype(str)\nwowah['sym'] = pd.Series(index = wowah.index, data='#')\nwowah['char'] = wowah[['race_id', 'class_id', 'sym', 'player']].astype(str).sum(axis=1)\nwowah.drop(['race_id', 'class_id', 'sym'], axis=1, inplace=True)\n\nzones['Min_rec_level'].iloc[27] = 25.0\nzones['Max_rec_level'].iloc[27] = 30.0\nprint('Records dataframe size:', wowah.shape)\nprint('Data on {:.0f} players and {:.0f} their charachters available'.format(len(wowah['player'].unique()), len(wowah['char'].unique())))\nwowah.head()\n\"\"\"\nA quick note on other files: *locations.csv* contains some additional information on the zones; the problem is that this file, unlike *zones.csv*, isn't based on the records dataframe, meaning that is lacks a lot of zones mentioned in it and at the same time has info on zones from the expansions beyond *Wrath of the Lich King*. As for *location_coords.csv*, it contains coordinates for the zones from *locations.csv*, which could be *theoretically* used to show players' movement on the global map... if only we had *WoW* shapefile.\n\"\"\"\n\"\"\"\n# Expansions <a id=\"4\"><\/a>\n\nBefore we dive into the records dataframe, let's have a quick look at the *locations.csv*. Although we can't utilize it directly, as already mentioned above, there is some interesting statistic to extract from it, concerning the amount of PVE content each expansions brought, up until *Warlords of Draenor* (wish we could also analyze PVP and levelling content, but its really messed up in the file, unfortunately). So, the plot below shows us that the game is going through a some hard time after *Wrath of the Lich King*, as each new expansion brought notably less dungeons and raids.\n\"\"\"\nloc_df = locations[locations['Location_Type'].isin(['Dungeon', 'Raid'])].pivot_table(columns='Game_Version',\n                                                                            index='Location_Type',\n                                                                            values='Location_Name',\n                                                                            aggfunc=lambda x: x.count())[['WoW','TBC','WLK','CAT','MoP','WoD']]\n\nimport plotly.graph_objects as go\n\nfig = go.Figure(data=[\n    go.Bar(name='Dungeons', x=loc_df.columns, y=loc_df.loc['Dungeon',:]),\n    go.Bar(name='Raids', x=loc_df.columns, y=loc_df.loc['Raid',:])\n])\n\nfig.update_layout(title='Dungeons & Raids\/Expansion', barmode='group')\nfig.show()\ndel loc_df\ngc.collect()\n\"\"\"\n# Race\/Class Statistics <a id=\"5\"><\/a>\n\nAlright, moving on to *wowah.csv*. Let's start with something really simple, like basic statistics concerning players' race\/class preference.\n\"\"\"\nfrom plotly.subplots import make_subplots\n\nrace_stats = wowah.drop_duplicates(['char']).groupby(['race'], as_index=False)['char'].count().sort_values(['char'], ascending=False)\nclass_stats = wowah.drop_duplicates(['char']).groupby(['class'], as_index=False)['char'].count().sort_values(['char'], ascending=False)\n\nrace_colors = ['#dc1c13', '#ea4c46', '#f07470', '#f1959b', '#f6bdc0']\nclass_colors = ['#dc1c13', '#E3342D', '#ea4c46', '#ED605B', '#f07470',\n                '#F17D7B', '#F18586', '#f1959b', '#F4A9AE', '#f6bdc0']\n\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\nfig.add_trace(go.Pie(labels=race_stats['race'],\n                     values=race_stats['char'],\n                     name=\"\",\n                     marker=dict(colors=race_colors, line=dict(color='#ffffff', width=0.5)),\n                     showlegend=False\n                    ),\n              1, 1)\nfig.add_trace(go.Pie(labels=class_stats['class'],\n                     values=class_stats['char'],\n                     name=\"\",\n                     marker=dict(colors=class_colors, line=dict(color='#ffffff', width=0.5)),\n                     textfont=dict(size=11),\n                     showlegend=False),\n              1, 2)\n\nfig.update_traces(hole=.4, hoverinfo=\"value+percent\", textinfo=\"label\")\n\nfig.update_layout(\n    title_text=\"Popularity Charts\",\n    # Add annotations in the center of the donut pies.\n    annotations=[dict(text='Race', x=0.18, y=0.5, font_size=20, showarrow=False),\n                 dict(text='Class', x=0.825, y=0.5, font_size=20, showarrow=False)]\n)\nfig.show()\nrace_class_mix = wowah.drop_duplicates(['char']).pivot_table(values='char',\n                                                             index='race',\n                                                             columns='class',\n                                                     aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int)\n\n_, ax = plt.subplots(1, 1, figsize=(14, 5.5))\nsns.set_context(\"paper\", font_scale=1.4) \nsns.heatmap(race_class_mix, annot=True, cmap='Reds', fmt='g', ax=ax)\nplt.title('Race\/Class Combinations')\nax.set_xticklabels(ax.get_xticklabels(), rotation=0)\nax.set_yticklabels(ax.get_yticklabels(), va='center')\nax.set(ylabel='', xlabel='')\nplt.show()\ndel race_stats\ndel class_stats\ndel race_class_mix\ngc.collect()\n\"\"\"\nSome of the race\/class combinations seem to be missing. The reason is that they are simply restricted, because, well, can you imagine an **Undead Paladin**? See [this page](https:\/\/wow.gamepedia.com\/Class#Class.2C_race_and_class_roles) for all available combos. Combos popularity, obviously, depends on their efficiency, determined by the synergy between racial traits and class needs. There is also a roleplaying aspect, very important for RP-players, who consider only *lore-wise* combinations to not look ridiculous.\n\"\"\"\n\"\"\"\n# Players Activity <a id=\"6\"><\/a>\n\n### Throughout the Year <a id=\"7\"><\/a>\n\nThe best way to study everyday players activity (expressed in unique logins per day) over the course of the whole 2008 would be the **calendar heatmap**, something like the one you got in your Kaggle\/GitHub profile. First of all, let's check if we got information on every single day of 2008.\n\"\"\"\nactivity = wowah.groupby('date')['char'].nunique().to_frame('char').reset_index()\n\nall_dates = pd.Series(pd.date_range('01\/01\/08', freq='D', periods=365))\nall_dates = all_dates.dt.strftime('%m\/%d\/%Y')\n\nmissing_dates = list(set(all_dates) - set(activity['date'].unique()))\nprint('Missing dates:', *(missing_dates), sep='\\n')\n\"\"\"\nApparently not. Assuming there were no troubles with collecting the data, these gaps are most likely maintance days or just server troubles. And right below is your nice heatmap, showing clearly the main trends, like, e.g., there are way more people playing on holidays and weekends.\n\"\"\"\nadd_df = pd.DataFrame(columns=['date', 'char'])\nadd_df['date'] = missing_dates\nadd_df['char'] = 0\n\nactivity = pd.concat([activity, add_df])\nactivity['date'] = pd.to_datetime(activity['date'])\nactivity.sort_values(by=['date'], inplace=True)\nactivity.reset_index(drop=True, inplace=True)\n\n#Source: https:\/\/community.plot.ly\/t\/colored-calendar-heatmap-in-dash\/10907\/9\nimport datetime\n\nstart = activity['date'].iloc[0]\nend = activity['date'].iloc[-1]\n\nd1 = datetime.date(start.year, start.month, start.day)\nd2 = datetime.date(end.year, end.month, end.day)\n\ndelta = d2 - d1\n\ndates_in_year = [d1 + datetime.timedelta(i) for i in range(delta.days+1)] \n#gives me a list with datetimes for each day a year\n\nweekdays_in_year = [6 - i.weekday() for i in dates_in_year] \n#gives [1,2,3,4,5,6,0,1,2,3,4,5,6,\u2026] (ticktext in xaxis dict translates this to weekdays\n\nweeknumber_of_dates = [i.strftime(\"%Gww%V\")[2:] for i in dates_in_year] \n#gives [1,1,1,1,1,1,1,2,2,2,2,2,2,2,\u2026] name is self-explanatory\n\nz = activity['char']\n\ntext = [str(i).replace('-','\/') for i in dates_in_year] \n#gives something like list of strings like \u20182018-01-25\u2019 for each date. Used in data trace to make good hovertext.\ncolorscale=[[False, '#eeeeee'], [True, '#76cf63']]\n\ndata = [go.Heatmap(x = weeknumber_of_dates,\n                   y = weekdays_in_year,\n                   z = z,\n                   text=text,\n                   hoverinfo='text+z',\n                   xgap=3, # this\n                   ygap=3, # and this is used to make the grid-like apperance\n                   showscale=False,\n                   colorscale='Hot',\n                   reversescale=True)]\nlayout = go.Layout(title='Players Activity throughout the Year',\n                   height=230,\n                   width=1000,\n                   yaxis=dict(showline = False, \n                              showgrid = False, \n                              zeroline = False,\n                              tickmode='array',\n                              ticktext=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][::-1],\n                              tickvals=list(range(7))),\n                   xaxis=dict(showline = False, \n                              showgrid = False, \n                              zeroline = False,\n                              tickmode='array',\n                              ticktext=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n                                        'Jul','Aug', 'Sep', 'Oct', 'Nov', 'Dec'],\n                              tickvals=[0, 4, 8, 13, 17, 21, 26, 30, 35, 39, 43, 48]),\n                   font={'size':10, 'color':'#9e9e9e'},\n                   plot_bgcolor=('#fff'),\n                   margin=dict(t=40))\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\"\"\"\nThere is, however, one little problem with that map \u2014 it doesn't demonstrate the difference in activity throughout the year between different levels. Let's study this case, using another type of visualization.\n\"\"\"\nwowah['level_bins'] = pd.cut(wowah['level'], [0, 15, 60, 70, 80])\nlvl_act = wowah.pivot_table(index='date',\n                            columns=['level_bins'],\n                            values='char',\n                            aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int)\nlvl_act.columns = ['1-15', '15-60', '60-70', '70-80']\nlvl_act.reset_index(inplace=True)\n\nall_dates = pd.Series(pd.date_range('01\/01\/08', freq='D', periods=365))\nall_dates = all_dates.dt.strftime('%m\/%d\/%Y')\nmissing_dates = list(set(all_dates) - set(lvl_act['date'].unique()))\n\nadd_df = pd.DataFrame(columns=['date'])\nadd_df['date'] = missing_dates\n\nlvl_act = pd.concat([lvl_act, add_df])\nlvl_act['date'] = pd.to_datetime(lvl_act['date'])\nlvl_act.sort_values(by=['date'], inplace=True)\nlvl_act.reset_index(drop=True, inplace=True)\nlvl_act['date'] = lvl_act['date'].dt.strftime('%m\/%d\/%Y')\n\nfig = go.Figure()\ncolormap = ['purple', 'orange', 'green', 'blue', 'purple']\ncolumns = ['1-15', '15-60', '60-70', '70-80']\nfor color, column in zip(colormap, columns):\n    fig.add_trace(go.Scatter(\n                    x=lvl_act['date'],\n                    y=lvl_act[column],\n                    name=column,\n                    line_color=color,\n                    hoverinfo='name+x+y',\n                    opacity=0.8))\nfig.update_layout(title_text=\"Players Activity over Year\/Levels\", \n                 xaxis=dict(\n                     tickmode='array',\n                     ticktext=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],\n                     tickvals=[1, 31, 60, 91, 121, 152, 182, 213, 244, 274, 304, 335]),\n                  xaxis_rangeslider_visible=True)\nfig.show()\n\"\"\"\nThe plot has a ridge shape, with it peaks at weekends and drops in the middle of the week. On **November 18** first level 80s start appearing, and as we know, *WLK* was released on **November 13**, so it took only **5 days** for the most enthusiastic players to get to the next level cap. We will research players' levelling more closely a bit later.\n\"\"\"\ndel activity\ndel add_df\ndel lvl_act\ngc.collect()\n\"\"\"\n### Average Day <a id=\"8\"><\/a>\n\nLet's delve deeper into players' activity and investigate the average day of the *WoW* server. What's your prime time for raiding and what time is the worst to log in, unless you want to play with yourself?\n\"\"\"\ntmp_df = wowah.groupby(by=['time', 'date'])['char'].nunique().to_frame('char').reset_index()\nday_activity = round(tmp_df.groupby(['time'], as_index=False)['char'].mean())\n\nfor zone_type in ['Arena', 'Battleground', 'City', 'Dungeon']:\n    day_activity[zone_type] = np.array(round((wowah[wowah['zone_type'] == zone_type] \\\n                                                .groupby(by=['time', 'date'])['char'] \\\n                                                .nunique() \\\n                                                .to_frame('char') \\\n                                                .reset_index()).groupby(['time'])['char'].mean()))\nday_activity['Zone'] = np.array(round((wowah[(wowah['zone_type'] == 'Zone') | \n                                               (wowah['zone_type'] == 'Sea') | \n                                               (wowah['zone_type'] == 'Transit')] \\\n                                                .groupby(by=['time', 'date'])['char'] \\\n                                                .nunique() \\\n                                                .to_frame('char') \\\n                                                .reset_index()).groupby(['time'])['char'].mean()))\nday_activity.rename({'char': 'Total', 'time': 'Time'}, axis=1, inplace=True)\n\nfig = go.Figure()\ncolormap = ['red', 'orange', 'green', 'blue', 'purple']\ncolumns = list(day_activity.columns[1:])\nfor color, column in zip(colormap, columns):\n    fig.add_trace(go.Scatter(\n                    x=day_activity['Time'],\n                    y=day_activity[column],\n                    name=column,\n                    line_color=color,\n                    hoverinfo='name+x+y',\n                    opacity=0.8))\nfig.update_layout(title_text=\"Players Activity on average Day\")\nfig.show()\ndel tmp_df\ndel day_activity\ngc.collect()\n\"\"\"\nMost of the players log in somewhere after 18:00 and leave the game by 02:00. 22:40 is the activity peak, while 06:00 is its lowest point. Note how highly **Dungeons** activity resonates with the **Total** one, while the rest seem to be more of less stable. **Arena** is the least popular activity, while **City** and **Battleground** are very close to each other most of the time. My theory is that most of the players participating in PVP just sit in their capitals and use queue to jump into the next match.\n\"\"\"\n\"\"\"\n# Guilds <a id=\"9\"><\/a>\n\nTo get cleaner statistics, we will analyze only characters created in **2008**.\n\"\"\"\nprint('Number of guilds on the server:', len(wowah['guild'].unique())-1)\n\nchars_2008 = wowah.groupby(['char'], as_index=False)['level', 'guild', 'class'].first()\nchars_2008 = chars_2008[(chars_2008['level'] == 1) | ((chars_2008['level'] == 55) & (chars_2008['class'] == 'Death Knight'))]\n\nfirst_joined = wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['guild'] != -1)].groupby(['char'], as_index=False)['guild', 'level'].first()\nprint('Number of players ever joined the guild:', len(first_joined))\n\nnever_joined = wowah[wowah['char'].isin(chars_2008['char'])].groupby(['char'], as_index=False)['guild', 'level'].max()\nprint('Number of players never joined the guild:', len(never_joined))\nnever_joined = never_joined[never_joined['guild'] == -1]\n\"\"\"\nThe ratio seems dramatic, however, most people who \"never joined\" the guild actually just hadn't joined one before 2008 ended. This, obviously, includes a large amount of novices who started their characters at the end of the year. Here are two plots who make this information more clear.\n\"\"\"\nfig = make_subplots(rows=2, cols=1, specs=[[{'type':'xy'}], [{'type':'xy'}]])\n\nfig.add_trace(go.Histogram(x=first_joined['level'],\n                           y=first_joined['char'],\n                           name='First Lvl Joined'), 1, 1)\nfig.add_trace(go.Histogram(x=never_joined['level'],\n                           y=never_joined['char'],\n                           name='Max Lvl Never Joined'), 2, 1)\n\nfig.update_layout(title_text=\"Guild\/No-Guild Players Stats\", \n                  height=1000)\nfig.update_traces(hoverinfo='x+y')\nfig.show()\n\"\"\"\nHuge amount of players join the guild straight on **level 1** \u2014 no doubt, the result of agressive invitation strategy, favored by guilds chasing merely the numbers. However, getting lots of players doesn't immediately form a healthy community, so many of the players recruited on level 1 tend to move to more organised guilds once they figure out the basics of *WoW* social life. Most of players had joined their first guild by the time they reached **level 20**, when they realise they are quite dependent on interaction with other players \u2014 and in guild, it's so easy to get some help with questing, or find a group to run dungeons and battlegrounds, or just get something crafted. There is also a notable increase in 55-60 levels \u2014 which is most likely just Death Knights, who start on **level 55**.\n\nAs for the players who aren't that social, few of them actually got to **level 80** on their own, never joining any of the guild. So, is being in one really necessary for you? What have they got to offer? Let's compare, how do players spend their time depending on whether they are in the guild or not.\n\"\"\"\nwowah['zone_type'].replace({'Zone': 'Levelling',\n                            'Sea': 'Levelling',\n                            'Transit': 'Levelling',\n                            'Event': 'Dungeon', \n                            'Battleground': 'PVP', \n                            'Arena': 'PVP'}, inplace=True)\n\nguild_act = wowah[wowah['guild'] != -1 & (wowah['level'] >= 15)].pivot_table(index='date',\n                                        columns=['guild', 'zone_type'],\n                                        values='char',\n                                        aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int).sum(axis=0).reset_index().groupby(['zone_type'], as_index=False)[0].sum()\n\nno_guild_act = wowah[wowah['guild'] == -1 & (wowah['level'] >= 15)].pivot_table(index='date',\n                                        columns=['guild', 'zone_type'],\n                                        values='char',\n                                        aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int).sum(axis=0).reset_index().groupby(['zone_type'], as_index=False)[0].sum()\n\nact_colors = ['9d44d1', 'ff0000', '007fd7', 'ffb100']\n\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\nfig.add_trace(go.Pie(labels=guild_act['zone_type'],\n                     values=guild_act[0],\n                     name=\"\",\n                     marker=dict(colors=act_colors, line=dict(color='#ffffff', width=0.5)),\n                     showlegend=False\n                    ),\n              1, 1)\n\nfig.add_trace(go.Pie(labels=no_guild_act['zone_type'],\n                     values=no_guild_act[0],\n                     name=\"\",\n                     marker=dict(colors=act_colors, line=dict(color='#ffffff', width=0.5)),\n                     showlegend=False\n                    ),\n              1, 2)\nfig.update_traces(hole=.4, hoverinfo=\"percent\", textinfo=\"label\")\n\nfig.update_layout(\n    title_text=\"Players Activity Comparison [15+ Level]\",\n    annotations=[dict(text='Guild', x=0.175, y=0.5, font_size=20, showarrow=False),\n                 dict(text='No-Guild', x=0.855, y=0.5, font_size=20, showarrow=False)]\n)\nfig.show()\n\"\"\"\nApparently, no-guild players run dungeons as much as those in the guild, most likely not facing any troubles with finding the group (the days of vanilla hardcore PVE are long gone), however, they seem to really neglect the PVP. The reason might be that coordinated groups have an enourmous advantage over those composed of random people, and who are you going to get into your group if not your guildmates?\n\"\"\"\ndel first_joined\ndel never_joined\ndel guild_act\ndel no_guild_act\ngc.collect()\n\"\"\"\n# Levelling <a id=\"10\"><\/a>\n\nLevelling is the major part of your character's life, so be ready to spend quite some time running errands for NPCs, like killing 10 wolves here and collecting 15 something there, before you actually jump into the world of pro-raiding. *WoW* is a model example of an old MMORPG, flooded with such fetch quests, which may become tedious after a hundred of hours. So, how many of the players managed to overcome the burden of this routine?\n\"\"\"\nchar_creation = wowah[wowah['level'] == 1].groupby(['date'], as_index=False)['char'].count()\nlvl_70 = wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['level'] == 70)].drop_duplicates(['char']).groupby(['date'], as_index=False)['char'].count()\nlvl_70['date'] = pd.to_datetime(lvl_70['date'])\nlvl_70 = lvl_70[lvl_70['date'] < datetime.date(2008, 10, 13)]\nlvl_70['date'] = lvl_70['date'].dt.strftime('%m\/%d\/%Y')\nlvl_80 = wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['level'] == 80)].drop_duplicates(['char']).groupby(['date'], as_index=False)['char'].count()\n\nprint('Chars started in 2008:', len(chars_2008))\nprint('Reached level 70 (TBC): {:d} ({:.2f}%)'.format(lvl_70['char'].sum(), lvl_70['char'].sum() \/ len(chars_2008) * 100))\nprint('Reached level 80 (WLK): {:d} ({:.2f}%)'.format(lvl_80['char'].sum(), lvl_80['char'].sum() \/ len(chars_2008) * 100))\n\"\"\"\nSeems that only a handful of the players had actually conquered the challenges of the levelling path (although it's gotten much easier since the good old vanilla) and entered the endgame. Let's compare their number to the whole amount of players who've reached level cap, with veterans of previous years included.\n\"\"\"\nlvl_70_all = wowah[wowah['level'] == 70].drop_duplicates(['char'])\nlvl_70_all['date'] = pd.to_datetime(lvl_70_all['date'])\nlvl_70_all = lvl_70_all[lvl_70_all['date'] < datetime.date(2008, 10, 13)]\nlvl_70_all['date'] = lvl_70_all['date'].dt.strftime('%m\/%d\/%Y')\nlvl_80_all = wowah[wowah['level'] == 80].drop_duplicates(['char'])\n\nprint('TBC endgame community: {:d} ({:.2f}% of total) \/ 2008 players share: {:.2f}%' \\\n      .format(len(lvl_70_all), len(lvl_70_all) \/ len(wowah['char'].unique()) * 100, lvl_70['char'].sum() \/ len(lvl_70_all) * 100))\nprint('WLK endgame community: {:d} ({:.2f}% of total) \/ 2008 players share: {:.2f}%' \\\n      .format(len(lvl_80_all), len(lvl_80_all) \/ len(wowah['char'].unique()) * 100, lvl_80['char'].sum() \/ len(lvl_80_all) * 100))\n\"\"\"\n2008 didn't bring many new players for *The Burning Crusade* endgame, as it was the end of this expansion. On the other hand, the emerging endgame community of the *Wrath of the Lich King* hadn't grown as big yet by the end of the year, however, the share of 2008 novices in it is notably larger. This shows us that *WoW* community was very renewing at the time, bringing a lot of new players with new expansions.\n\"\"\"\nfig = go.Figure()\nfig.add_trace(go.Scatter(\n                x=char_creation['date'],\n                y=char_creation['char'],\n                name='Chars Started',\n                line_color='red',\n                hoverinfo='x+y',\n                opacity=0.8))\nfig.add_trace(go.Scatter(\n                x=lvl_70['date'],\n                y=lvl_70['char'],\n                name='Reached Lvl 70 (TBC)',\n                line_color='green',\n                hoverinfo='x+y',\n                opacity=0.8))\nfig.add_trace(go.Scatter(\n                x=lvl_80['date'],\n                y=lvl_80['char'],\n                name='Reached Lvl 80 (WLK)',\n                line_color='blue',\n                hoverinfo='x+y',\n                opacity=0.8))\nfig.update_layout(title_text=\"Chars Created\/Reached Lvl Cap Chart\", \n                 xaxis=dict(\n                     tickmode='array',\n                     ticktext=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],\n                     tickvals=[1, 31, 60, 91, 121, 152, 182, 213, 244, 274, 304, 335]),\n                  xaxis_rangeslider_visible=True\n                 )\nfig.show()\ndel char_creation\ndel lvl_70\ndel lvl_80\ndel lvl_70_all\ndel lvl_80_all\ngc.collect()\n\"\"\"\nThere is a significant anomaly on 10\/08\/2008, when **4000** new characters were created. An upcoming release of the new expansion on 13\/11\/2008 might've influenced it some way, though this is yet to be investigated...\n\nNow, let's have a look at the most popular levelling path chosen by Horde players. Each zone has a specific range of levels recommended to spend their time in it. On the plot below, **Red** will stand for questing in the zone being under the minimal recommended level (meaning it's rather dangerous to run around there), **Green** \u2014 being prfectly fit into the levels range, **Gray** \u2014 being over the maximum recommended level, resulting in a modest reward, that most likely won't worth the time spent.\n\"\"\"\nfor race in wowah['race'].unique():\n    levelling_zones = wowah[(wowah['zone_type'] == 'Levelling') & (wowah['race'] == race)].pivot_table(index='level',\n                                        columns=['zone_type'],\n                                        values='zone',\n                                        aggfunc=lambda x: x.value_counts().index[0])\n    levelling_zones.columns = ['Levelling']\n    levelling_zones.reset_index(inplace=True)\n    \n    zones_min_rec = zones[zones['Type'].isin(['Zone', 'Transit', 'Sea'])][['Zone_Name', 'Min_rec_level']].set_index(['Zone_Name']).T.to_dict('records')[0]\n    zones_max_rec = zones[zones['Type'].isin(['Zone', 'Transit', 'Sea'])][['Zone_Name', 'Max_rec_level']].set_index(['Zone_Name']).T.to_dict('records')[0]\n\n    levelling_zones['Min_Rec'] = levelling_zones['Levelling'].map(zones_min_rec).astype(int)\n    levelling_zones['Max_Rec'] = levelling_zones['Levelling'].map(zones_max_rec).astype(int)\n\n    levelling_zones['Under'] = -(levelling_zones['level'] < levelling_zones['Min_Rec']).astype(int)\n    levelling_zones['Over'] = (levelling_zones['level'] > levelling_zones['Max_Rec']).astype(int)\n    levelling_zones['Recommended'] = levelling_zones['Under'] + levelling_zones['Over']\n    levelling_zones['Recommended'].replace({-1: 'Under Recommended', 0: 'Recommended', 1: 'Over Recommended'}, inplace=True)\n\n    fig = go.Figure()\n\n    colorsIdx = {'Under Recommended': 'red', 'Recommended': 'green', 'Over Recommended': 'darkgray'}\n    cols = levelling_zones['Recommended'].map(colorsIdx)\n\n    fig.add_trace(go.Scatter(\n                    x=levelling_zones['level'],\n                    y=levelling_zones['Levelling'],\n                    name='',\n                    mode='markers',\n                    text = levelling_zones['Recommended'],\n                    marker=dict(color=cols),\n                    hoverinfo='x+y+text',\n                    opacity=0.8))\n    fig.update_layout(title_text=\"Popular \" + race + \" Levelling Zone\/Level\")\n    fig.update_xaxes(nticks=20)\n    fig.update_yaxes(tickfont=dict(size=10))\n    fig.show()\ndel levelling_zones\ndel zones_min_rec\ndel zones_max_rec\ngc.collect()\n\"\"\"\nWell, we don't see red dots, but got quite a lot of gray ones. That means players tend to stay in some zones for quite some time, going over the recommended level in the result, but not the other way around. Also note how the late zones cover much less levels range in comparison to the early one. As for the race levelling path difference, it's more or less the same with the exception of first 1-2 zones.\n\nAlright, let's say we want to jump into the endgame as soon as possible. How long it's going to take and what should we focus on? Let's learn from the fastest levelling players of the server.\n\"\"\"\nfastest_80 = []\nclasses = wowah['class'].unique()\nfor char_class in classes:\n    fastest_80.append(wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['level'] == 80) & (wowah['class'] == char_class)]['char'].iloc[0])\n\nfig = go.Figure()\ncolormap = ['gray', 'black', 'red', 'orange', 'goldenrod', 'green', 'blue', 'hotpink', 'purple', 'turquoise']\nfor color, char in zip(colormap, fastest_80):\n    hist_80 = wowah[wowah['char'] == char].reset_index(drop=True)\n    hist_80['playtime'] = (hist_80.index + 1) \/ 6\n    hist_80 = hist_80[['level', 'playtime']]\n    fig.add_trace(go.Scatter(\n                    x=hist_80['playtime'],\n                    y=hist_80['level'],\n                    name=wowah[wowah['char'] == char]['class'].iloc[0],\n                    line_color=color,\n                    hoverinfo='name+x+y',\n                    opacity=0.7))\nfig.update_layout(title=\"Fastest Players Levelling\/Playtime (Hours)\")\nfig.show()\ndel fastest_80\ndel hist_80\ngc.collect()\n\"\"\"\n**Death Knight** is the first to hit **level 80**, no surprise here (remember, that he starts from **level 55**). Damage-dealer classes got a considerable advantage over the healer ones, taking much less time to get to the cap. For example, for **Shaman**, it took **twice** the playtime to get to the level 70 compared to **Warlock**. Note how hard it becomes to get the last 10 levels \u2014 around **60 hours**, that's like a single grand RPG! Another thing is that levelling takes long, sure, but in the end players spend way more time on level cap, sometimes **hundreds** of hours. What keeps them playing? We'll find it out in the next section, and now let's have a look at the fastest levelling players weekday activities, comparing them with the average players. Do they prioritize just questing, or spend some time on other things as well?\n\"\"\"\nlvl_70_chars = wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['level'] == 70)]['char']\nlvl_70_levelling = wowah[wowah['char'].isin(lvl_70_chars) & (wowah['zone_type'] != 'City')]\nlvl_70_levelling = lvl_70_levelling[lvl_70_levelling['level'] < 70]\n\nact_list = []\nfor act in ['PVP', 'Dungeon', 'Levelling']:\n    tmp_df = lvl_70_levelling[lvl_70_levelling['zone_type'] == act].pivot_table(index='date', \n                                                                                columns='char', \n                                                                                values='time', \n                                                                            aggfunc=lambda x: x.value_counts().count())\n    act_list.append(tmp_df.fillna(0).sum().sum() \/ (tmp_df.shape[0] * tmp_df.shape[1] - tmp_df.isna().sum().sum()) \/ 6)\n\nfastest_70 = []\nclasses = wowah['class'].unique()\nfor char_class in classes:\n    fastest_70.append(wowah[(wowah['char'].isin(chars_2008['char'])) & (wowah['level'] == 70) & (wowah['class'] == char_class)]['char'].iloc[0])\n\nfast_lvl_70_levelling = wowah[wowah['char'].isin(fastest_70) & (wowah['zone_type'] != 'City')]\nfast_lvl_70_levelling = fast_lvl_70_levelling[fast_lvl_70_levelling['level'] < 70]\n\nfast_act_list = []\nfor act in ['PVP', 'Dungeon', 'Levelling']:\n    tmp_df = fast_lvl_70_levelling[fast_lvl_70_levelling['zone_type'] == act].pivot_table(index='date', \n                                                                                          columns='char', \n                                                                                          values='time', \n                                                                            aggfunc=lambda x: x.value_counts().count())\n    fast_act_list.append(tmp_df.fillna(0).sum().sum() \/ (tmp_df.shape[0] * tmp_df.shape[1] - tmp_df.isna().sum().sum()) \/ 6)\n\ncategories = ['PVP', 'PVE', 'Levelling']\n\nfig = go.Figure()\n\nfig.add_trace(go.Scatterpolar(\n      r=act_list,\n      theta=categories,\n      fill='toself',\n      name='Average'\n))\n\nfig.add_trace(go.Scatterpolar(\n      r=fast_act_list,\n      theta=categories,\n      fill='toself',\n      name='Fastest'\n))\n\nfig.update_layout(\n    title='Levelling Players Everyday Activities',\n  polar=dict(\n    radialaxis=dict(\n      visible=True,\n      range=[0, 8]\n    )),\n  showlegend=True\n)\n\nfig.show()\n\"\"\"\nComparing the fastest levelling players to the average ones, we can see that the first spend more than double of time on quests than the latter, as for PVE and PVP, it's more or less equal \u2014 around an hour a day. Overall, you are expected to spend about **10 hours** every day if you wish to be among the first in the endgame league, and that's not what most can really afford. Average player needs amost half as much time, **6 hours** a day, to get to the level cap. Remember, that this time is distributed rather unequally depending on the weekday.\n\"\"\"\ndel lvl_70_chars\ndel lvl_70_levelling\ndel fastest_70\ndel fast_lvl_70_levelling\ndel act_list\ndel fast_act_list\ngc.collect()\n\"\"\"\n# PVE <a id=\"11\"><\/a>\n\n### Dungeons & Raids <a id=\"12\"><\/a>\n\nJust like zones, dungeons in *WoW* got specific recommended levels ranges and designed around those limitations, so if you are seriously under-levelled, you are going to face really challenging fight. Now, as we can see from the chart below, players actually tend to run **Ragefire Chasm**, **Razorfen Kraul**, **Zul'Farrak** and **Halls of Lightning** under the recommended level. How could we explain this? Well, first of all, developers could overrate the recommended minimum; secondly, there may be some bugs in dungeons that lower-levels utilize to skip some hard parts; and thirdly, lower-levels may run those dungeons with their higher-level friends or guildmates clearing the path for them.\n\"\"\"\ndungeon_stats = wowah[wowah['zone_type'] == 'Dungeon'].pivot_table(index='level',\n                                        columns=['zone_type'],\n                                        values='zone',\n                                        aggfunc=lambda x: x.value_counts().index[0])\ndungeon_stats.columns = ['Dungeon']\ndungeon_stats.reset_index(inplace=True)\ndungeon_stats = dungeon_stats.iloc[1:,:]\n\nzones_min_rec = zones[zones['Type'] == 'Dungeon'][['Zone_Name', 'Min_rec_level']].set_index(['Zone_Name']).T.to_dict('records')[0]\nzones_max_rec = zones[zones['Type'] == 'Dungeon'][['Zone_Name', 'Max_rec_level']].set_index(['Zone_Name']).T.to_dict('records')[0]\n\ndungeon_stats['Min_Rec'] = dungeon_stats['Dungeon'].map(zones_min_rec).astype(int)\ndungeon_stats['Max_Rec'] = dungeon_stats['Dungeon'].map(zones_max_rec).astype(int)\n\ndungeon_stats['Under'] = -(dungeon_stats['level'] < dungeon_stats['Min_Rec']).astype(int)\ndungeon_stats['Over'] = (dungeon_stats['level'] > dungeon_stats['Max_Rec']).astype(int)\ndungeon_stats['Recommended'] = dungeon_stats['Under'] + dungeon_stats['Over']\n\n#dungeon_stats['Recommended'] = (dungeon_stats['level'] >= dungeon_stats['Min_Rec']) & (dungeon_stats['level'] <= dungeon_stats['Max_Rec'])\n\nfig = go.Figure()\n\ncolorsIdx = {-1: 'red', 0: 'green', 1: 'darkgray'}\ncols = dungeon_stats['Recommended'].map(colorsIdx)\n\nfig.add_trace(go.Scatter(\n                    x=dungeon_stats['level'],\n                    y=dungeon_stats['Dungeon'],\n                    name='',\n                    mode='markers',\n    marker=dict(color=cols),\n                    hoverinfo='x+y',\n                    opacity=0.8))\nfig.update_layout(title_text=\"Popular Dungeon\/Level\")\n#fig.update_layout(title_text=\"Popular Dungeon\/Level\", width=740, height=480)\nfig.update_xaxes(nticks=10)\n#fig.update_yaxes(tickfont=dict(size=10))\nfig.show()\ndel dungeon_stats\ndel zones_min_rec\ndel zones_max_rec\ngc.collect()\n\"\"\"\n### Endgame <a id=\"13\"><\/a>\n\nOnce you reach the level cap, you enter the realm of the endgame. The quests are far behind, and you can now delve into the world of pro-PVE\/PVP. As mentioned above, this period in fact proves to be the main part of your character's life, so you could as well call it not the end, but rather the *true* beginning of your path.\n\nA quick note on the charts below: *The World* stands for the activities that don't fall under PVP, PVE our sitting in the capital. These may include daily quests, getting factions reputation, new mounts, resources, in short, doing all the stuff you missed while rushing to your level cap.\n\"\"\"\n#had to put a specific number of a row, where TBC era ends, as other, more elegant options take hours to compute\ntbc_cap = wowah[wowah['level'] == 70].reset_index().iloc[: 6034346, :]\ntbc_act = tbc_cap.pivot_table(index='date',\n                    columns=['zone_type'],\n                    values='char',\n                    aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int).sum(axis=0).reset_index().groupby(['zone_type'], as_index=False)[0].sum()\n\nwlk_cap = wowah[wowah['level'] == 80]\nwlk_act = wlk_cap.pivot_table(index='date',\n                    columns=['zone_type'],\n                    values='char',\n                    aggfunc=lambda x: x.value_counts().count()).fillna(0).astype(int).sum(axis=0).reset_index().groupby(['zone_type'], as_index=False)[0].sum()\ntbc_act['zone_type'].replace({'Levelling': 'The World'}, inplace=True)\nwlk_act['zone_type'].replace({'Levelling': 'The World'}, inplace=True)\n\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\nfig.add_trace(go.Pie(labels=tbc_act['zone_type'],\n                     values=tbc_act[0],\n                     name=\"\",\n                     marker=dict(colors=act_colors, line=dict(color='#ffffff', width=0.5)),\n                     showlegend=False, textfont=dict(size=11)\n                    ),\n              1, 1)\n\nfig.add_trace(go.Pie(labels=wlk_act['zone_type'],\n                     values=wlk_act[0],\n                     name=\"\",\n                     marker=dict(colors=act_colors, line=dict(color='#ffffff', width=0.5)),\n                     showlegend=False, textfont=dict(size=11)\n                    ),\n              1, 2)\n# Use `hole` to create a donut-like pie chart\nfig.update_traces(hole=.4, hoverinfo=\"percent\", textinfo=\"label\")\n\nfig.update_layout(\n    title_text=\"Players Endgame Activity\",\n    # Add annotations in the center of the donut pies.\n    annotations=[dict(text='TBC', x=0.185, y=0.5, font_size=20, showarrow=False),\n                 dict(text='WLK', x=0.82, y=0.5, font_size=20, showarrow=False)]\n)\nfig.show()\ndel tbc_cap\ndel wlk_cap\ndel tbc_act\ndel wlk_act\ngc.collect()\n\"\"\"\nAs we can see, at the end of *The Burning Crusade* era PVP was as popular among **level 70** players as running raids and dungeons; however, at the start of *Wrath of the Lich King* fresh **level 80s** focus primarily on running dungeons - obviously, to get the new gear for upcoming dungeons. So, if you prefer PVP over PVE content, be ready to see the significant decrease of activity on battlegrounds whenever new expansion comes out.\n\"\"\"\n\"\"\"\n# PVP <a id=\"14\"><\/a>\n\"\"\"\nwowah['zone_type'] = wowah['zone'].map(zones_dict)\nbgs = wowah[wowah['zone_type'].isin(['Battleground'])].groupby(['zone'], as_index=False)['char'].count().sort_values(by=['char'], ascending=False)\narenas = wowah[wowah['zone_type'].isin(['Arena'])].groupby(['zone'], as_index=False)['char'].count().sort_values(by=['char'], ascending=False)\n\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'xy'}, {'type':'xy'}]])\nfig.add_trace(go.Bar(x=arenas['zone'],\n                     y=arenas['char'],\n                     name=\"Arenas\",\n                     showlegend=False\n                    ),\n              1, 1)\nfig.add_trace(go.Bar(x=bgs['zone'],\n                     y=bgs['char'],\n                     name=\"Battlegrounds\",\n                     showlegend=False),\n              1, 2)\n\nfig.update_layout(title=\"Arenas & Battlegrounds Popularity\")\nfig.show()\n\"\"\"\n**Dalaran Arena** couldn't boast of a popularity in 2008 as it was just brought by *WLK*, in 2008-10-14. As for The **Ring of Valor** and **Strand of the Ancients**, they actually proved to be a failure and were completely removed from the game later.\n\"\"\"\ndel bgs\ndel arenas\ngc.collect()\n\"\"\"\n*To be continued...*\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '300b414c4bcd58'}"}
{"id":"46064","text":"\"\"\"\n# Import Library\n\"\"\"\n\"\"\"\n* number of training samples: 8000  (4000 cat - 4000 dog)\n* number of validation samples: 1600 (800 cat - 800 dog)\n\"\"\"\nimport numpy as np\nimport pandas as pd \nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Flatten, Dense,GlobalAveragePooling2D\nfrom keras import applications\nfrom pathlib import Path\nfrom keras.models import model_from_json\nfrom keras.callbacks import ModelCheckpoint, History\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nimport matplotlib.pyplot as plt\nimport random\nimport os\n\"\"\"\n# Preparing data\n\"\"\"\nimport zipfile\nwith zipfile.ZipFile(\"..\/input\/dogs-vs-cats\/train.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"train\")\n\nwith zipfile.ZipFile(\"..\/input\/dogs-vs-cats\/test1.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"test1\")\ntrain_directory = \"train\/train\/\"\ntest_directory  = \"test1\/test1\/\"\n# See sample image\nfilenames = os.listdir(train_directory)\nsample = random.choice(filenames)\nprint(sample)\nimage = load_img(train_directory + sample)\nplt.imshow(image)\n# 8000 train samples\n# 1600 validation samples\nimport shutil\nsource_dir = 'train\/'\ndef copy_files(prefix_str, range_start, range_end, target_dir):\n    image_paths = []\n    for i in range(range_start, range_end):\n        image_path = os.path.join(source_dir,'train', prefix_str + '.'+ str(i)+ '.jpg')\n        image_paths.append(image_path)\n    dest_dir = os.path.join( 'data', target_dir, prefix_str)\n    os.makedirs(dest_dir)\n\n    for image_path in image_paths:\n        shutil.copy(image_path,  dest_dir)\n\ncopy_files('dog', 0, 4000, 'train')\ncopy_files('cat', 0, 4000, 'train')\ncopy_files('dog', 4000, 4800,'validation')\ncopy_files('cat', 4000, 4800, 'validation')\n# All data, 12500 cat, 12500 dog\nsource_dir = 'train\/'\ndef copy_files(prefix_str, range_start, range_end, target_dir):\n    image_paths = []\n    for i in range(range_start, range_end):\n        image_path = os.path.join(source_dir,'train', prefix_str + '.'+ str(i)+ '.jpg')\n        image_paths.append(image_path)\n    dest_dir = os.path.join( 'Alldata', target_dir, prefix_str)\n    if not os.path.exists(dest_dir):\n        os.makedirs(dest_dir)\n\n    for image_path in image_paths:\n        shutil.copy(image_path,  dest_dir)\n\ncopy_files('dog', 0, 12500, 'train')\ncopy_files('cat', 0, 12500, 'train')\n#remove train folder\nif  os.path.exists('train'):\n    #os.removedirs(\"train\")\n    shutil.rmtree(\"train\") \n# dimensions of our images.\nimg_width, img_height = 96, 96\nIMG_SHAPE = (img_width, img_height, 3)\n\ntrain_data_dir = 'data\/train'\nvalidation_data_dir = 'data\/validation'\n\nnb_train_samples = 8000\nnb_validation_samples = 1600\nepochs = 5\nbatch_size = 32\n\"\"\"\n# Preparing Library\n\"\"\"\n#Learning curves\ndef Polt_history(hist):\n    acc = hist.history['accuracy']\n    val_acc = hist.history['val_accuracy']\n\n    loss = hist.history['loss']\n    val_loss = hist.history['val_loss']\n    print(\"Accuracy = %0.3f\" % (acc[epochs-1]*100),  \", val_acc = %0.3f\" % (val_acc[epochs-1]*100))\n    print(\"loss     = %0.3f\" % loss[epochs-1], \", val_loss= %0.3f\" % val_loss[epochs-1])\n    plt.figure(figsize=(8, 8))\n    plt.subplot(2, 1, 1)\n    plt.plot(acc, label='Training Accuracy')\n    plt.plot(val_acc, label='Validation Accuracy')\n    plt.legend(loc='lower right')\n    plt.ylabel('Accuracy')\n    plt.ylim([min(plt.ylim()),1])\n    plt.title('Training and Validation Accuracy')\n\n    plt.subplot(2, 1, 2)\n    plt.plot(loss, label='Training Loss')\n    plt.plot(val_loss, label='Validation Loss')\n    plt.legend(loc='upper right')\n    plt.ylabel('Cross Entropy')\n    plt.ylim([0,1.0])\n    plt.title('Training and Validation Loss')\n    plt.xlabel('epoch')\n    plt.show()\n# Model predict\ndef ResNet50_predict(Model,Test_dir):  \n    test_filenames = []\n    for file in os.listdir(Test_dir):   \n        test_filenames.append(os.path.join(Test_dir,file))  \n\n    test_df = pd.DataFrame({\n        'filename': test_filenames\n    })\n\n    test_datagen = ImageDataGenerator(rescale=1.\/255)\n    test_generator=test_datagen.flow_from_dataframe(\n                dataframe=test_df,\n                x_col=\"filename\",\n                y_col=None,\n                batch_size=50,\n                seed=42,\n                shuffle=False,\n                class_mode=None,\n                target_size=(img_height,img_width))\n    \n    nb_test_samples = len(test_df)\n    test_steps=nb_test_samples \/\/ 50\n    pred=Model.predict_generator(test_generator,\n                    steps=test_steps,\n                    verbose=1)\n    \n    pred = [1 if p[0] > 0.5 else 0 for p in pred]\n    print (pred[:12])\n    #predicted_class_indices=np.argmax(pred,axis=1)\n    predicted_class_indices=np.argmax(pred)\n\n    #len(predicted_class_indices)\n    #print(predicted_class_indices[:12])\n    return pred,test_df\n    #return predicted_class_indices,test_df\n#testing known data in train folder: on 25000 image \ndef Test_Model_known_Data(Model):\n    print(\"Testing cats....\")\n    model_pred_cat,test_df  = ResNet50_predict(Model,\"Alldata\/train\/cat\") #0\n    print(\"Testing dogs....\")\n    model_pred_dog,test_df  = ResNet50_predict(Model,\"Alldata\/train\/dog\") #1\n\n    #print result\n    model_true_cat  = len(test_df) - sum (model_pred_cat)\n    model_true_dog  = sum (model_pred_dog)\n    model_true      = model_true_cat + model_true_dog\n    # model result\n    print(\"  model result\")\n    print(\"cat accuracy  = %2.3f\" % (model_true_cat \/len(test_df) *100))\n    print(\"dog accuracy  = %2.3f\" % (model_true_dog \/len(test_df) *100))\n    print(\"Total accuracy= %2.3f\" % (model_true \/(2*len(test_df)) *100))\n# Plot predict image output\n%matplotlib inline\n#import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\ndef Plot_predict(predicted_class_indices,Test_dir,test_df):\n    # Parameters for our graph; we'll output images in a 4x4 configuration\n    nrows = 12\n    ncols = 4\n    pic_index = 0 # Index for iterating over images\n    # Set up matplotlib fig, and size it to fit 4x4 pics\n    fig = plt.gcf()\n    fig.set_size_inches(ncols*4, nrows*4)\n\n    for i, img_path in enumerate(test_df.filename[:48]):\n        # Set up subplot; subplot indices start at 1\n        sp = plt.subplot(nrows, ncols, i + 1)\n        sp.axis('Off') # Don't show axes (or gridlines)\n\n        #img = mpimg.imread(img_path, target_size=(256, 256))Test_dir\n        img = load_img( img_path, target_size=(150,150))\n        plt.imshow(img) \n        result = predicted_class_indices[i]\n        if (result == 1 ):\n            name = 'Dog'\n        else :\n            name = 'Cat'\n        plt.title( name )\n# Save Submission to csv file\ndef Save_Submission(predict,model,mod,test_df):\n    if not os.path.exists(mod):\n        os.makedirs(mod)\n        \n    test_df['category'] = predict\n    submission_df = test_df.copy()\n    #submission_df['id'] = submission_df['filename'].str.split('.').str[0]\n    submission_df['id'] = submission_df['filename'].str.split('.').str[0].str.split('\/').str[1]\n    submission_df['label'] = submission_df['category']\n    submission_df.drop(['filename', 'category'], axis=1, inplace=True)\n    submission_df.index += 1 \n    submission_df.to_csv( mod + '\/submission_AM_'+ mod +'.csv', index=True)\n\n    #plt.figure(figsize=(10,5))\n    submission_df['label'].value_counts().plot.bar()\n    plt.title(\"(Test data , \"+mod + \" )\")\n\"\"\"\n# Model 1\n\"\"\"\n# build the ResNet50 network\nbase_model = applications.ResNet50(input_shape=IMG_SHAPE,\n                      weights='..\/input\/resnet50\/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', \n                      include_top=False) #, pooling='average', weights='imagenet')\nprint(\"base_model.layers\", len(base_model.layers)) #175\n\n#Freeze the convolutional base\n#for layer in base_model.layers[:100]:\n#    layer.trainable = False\nfor layer in base_model.layers:\n    layer.trainable = True\n# build a classifier model to put on top of the convolutional model\ntop_model = Sequential()\ntop_model.add(Flatten(input_shape=base_model.output_shape[1:]))\ntop_model.add(Dense(256, activation='relu'))\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(1, activation='sigmoid'))\n\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(top_model)\n\nbase_model.summary()\ntop_model.summary()\nmodel.summary()\n# prepare data augmentation configuration\ntrain_datagen = ImageDataGenerator(\n                rescale=1.\/255,\n                shear_range=0.2,\n                zoom_range=0.2,\n                horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow_from_directory(\n                train_data_dir,\n                target_size=(img_height, img_width),\n                batch_size=batch_size,\n                seed=42,\n                class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n                validation_data_dir,\n                target_size=(img_height, img_width),\n                batch_size=batch_size,\n                seed=42,\n                class_mode='binary')#binary  categorical\nif not os.path.exists('model'):\n    os.makedirs(\"model\")    \nlearningRate = 1e-4\n# compile the model with a SGD\/momentum optimizer and a very slow learning rate.\nmodel.compile(loss='binary_crossentropy',  #categorical_crossentropy\n              #optimizer=optimizers.SGD(lr=learningRate, momentum=0.9),\n              optimizer=optimizers.RMSprop(lr=learningRate),\n              metrics=['accuracy'])\n\ncheckpointer = ModelCheckpoint(filepath='model\/model.weights.best_ResNet50_1.hdf5', \n                               verbose=1, save_best_only=True)\n# fine-tune the model\nhist = model.fit_generator(\n        train_generator,\n        samples_per_epoch=nb_train_samples,\n        epochs=epochs,\n        validation_data=validation_generator,\n        validation_steps=nb_validation_samples \/\/ batch_size,\n        callbacks=[checkpointer] )\n# Save neural network structure and weights\nmodel_structure = model.to_json()\nf = Path(\"model\/model_structure_ResNet50.json\")\nf.write_text(model_structure)\nmodel.save_weights(\"model\/model_weights_ResNet50_1.h5\")\n\"\"\"\nModel output: Learning curves\n\"\"\"\nPolt_history(hist)\nplt.savefig('model\/hist.png')\n\"\"\"\n# Testing model 1\n\"\"\"\n\"\"\"\n* Testing model 1: on 25000 image \n\"\"\"\n#testing known data in train folder\nTest_Model_known_Data(model)\n\"\"\"\n* Testing model 1: on 12500 image (test data)\n\"\"\"\n#testing unknown data in test folder\npredict,test_df =ResNet50_predict(model,test_directory)\nPlot_predict(predict,test_directory,test_df)\nplt.savefig('model\/predicted.png')\n\"\"\"\n# Continue train: fine tune model \n\"\"\"\n# compile the model with a SGD\/momentum optimizer and a very slow learning rate.\nlearningRate=1e-5\nmodel.compile(loss='binary_crossentropy',  #categorical_crossentropy\n              #optimizer=optimizers.SGD(lr=learningRate, momentum=0.9),\n              optimizer=optimizers.RMSprop(lr=learningRate),\n              metrics=['accuracy'])\n\ncheckpointer = ModelCheckpoint(filepath='model\/model.weights.best_ResNet50_2.hdf5',\n                               verbose=1, save_best_only=True)\n\n# fine-tune the model\nhist_2 = model.fit_generator(\n        train_generator,\n        samples_per_epoch=nb_train_samples,\n        epochs=epochs,\n        validation_data=validation_generator,\n        validation_steps=nb_validation_samples \/\/ batch_size,\n        callbacks=[checkpointer])\n# Save neural network weights\nmodel.save_weights(\"model\/model_weights_ResNet50_2.h5\")\n#Learning curves\nPolt_history(hist_2)\nplt.savefig('model\/hist_2.png')\n\"\"\"\n# Testing model 1\n\"\"\"\n\"\"\"\n* Testing model: on 25000 image \n\"\"\"\n#testing known data in train folder\nTest_Model_known_Data(model)\n#testing unknown data in test folder\npredict,test_df =ResNet50_predict(model,test_directory)\nSave_Submission(predict,model,\"model\",test_df)\n\"\"\"\n# Plot sample of predicted result\n\"\"\"\nPlot_predict(predict,test_directory,test_df)\nplt.savefig('model\/predicted_2.png')\n\"\"\"\n#  Model 2 \n\"\"\"\nif not os.path.exists('model2'):\n    os.makedirs(\"model2\")   \n# build the ResNet50 network\nbase_model2 = applications.ResNet50(input_shape=IMG_SHAPE,\n                      weights='..\/input\/resnet50\/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', \n                      include_top=False) #, pooling='average', weights='imagenet')\nprint(\"base_model.layers= \", len(base_model2.layers)) #155\n\n#Feature extraction\n#Freeze the convolutional base\n#for layer in base_model2.layers[:100]:\n#    layer.trainable = False\nfor layer in base_model2.layers:\n    layer.trainable = True    \n# build a classifier model to put on top of the convolutional model\ntop_model2 = Sequential()\ntop_model2.add(GlobalAveragePooling2D())\ntop_model2.add(Dense(1, activation='sigmoid'))\n\nmodel2 = Sequential()\nmodel2.add(base_model2)\nmodel2.add(top_model2)\n\nmodel2.summary()\nlearningRate=1e-4\nmodel2.compile(loss='binary_crossentropy',  #categorical_crossentropy\n              optimizer=optimizers.RMSprop(lr=learningRate),\n              #optimizer=optimizers.SGD(lr=learningRate, momentum=0.9),\n              metrics=['accuracy'])\n\ncheckpointer = ModelCheckpoint(filepath='model2\/model2.weights.best_ResNet50_1.hdf5', \n                               verbose=1, save_best_only=True)\n\n# fine-tune the model\nhist2 = model2.fit_generator(\n        train_generator,\n        samples_per_epoch=nb_train_samples,\n        epochs=epochs,\n        validation_data=validation_generator,\n        validation_steps=nb_validation_samples \/\/ batch_size,\n        callbacks=[checkpointer])\n# Save neural network structure and weights\nmodel2_structure = model2.to_json()\nf = Path(\"model2\/model2_structure_ResNet50.json\")\nf.write_text(model2_structure)\nmodel2.save_weights(\"model2\/model2_weights_ResNet50.h5\")\nPolt_history(hist2)\nplt.savefig('model2\/hist2.png')\n\"\"\"\n# Testing model 2\n\"\"\"\n\"\"\"\n* Testing model 2: on 25000 image \n\"\"\"\n# Load neural network structure and weights\n#model2.load_weights(\"model2\/model2.weights.best_ResNet50_1.hdf5\")\n#testing known data in train folder\nTest_Model_known_Data(model2)\n\"\"\"\n* Testing model 2: on 12500 image (test data)\n\"\"\"\n#testing unknown data in test folder\npredict2,test_df =ResNet50_predict(model2,test_directory)\nSave_Submission(predict2,model2,\"model2\",test_df)\nPlot_predict(predict2,test_directory,test_df)\nplt.savefig('model2\/predicted2.png')\n\"\"\"\n## Fine tune model 2\n\"\"\"\nlearningRate=1e-5\n# Load neural network structure and weights\n#model2.load_weights(\"model2\/model2_weights_ResNet50.h5\")\n\nmodel2.compile(loss='binary_crossentropy',  #categorical_crossentropy\n              optimizer=optimizers.RMSprop(lr=learningRate),\n              #optimizer=optimizers.SGD(lr=learningRate, momentum=0.9),\n              metrics=['accuracy'])\n\ncheckpointer = ModelCheckpoint(filepath='model2\/model2.weights.best_ResNet50_2.hdf5', \n                               verbose=1, save_best_only=True)\n\n# fine-tune the model\nhist2_2 = model2.fit_generator(\n        train_generator,\n        samples_per_epoch=nb_train_samples,\n        epochs=epochs,\n        validation_data=validation_generator,\n        validation_steps=nb_validation_samples \/\/ batch_size,\n        callbacks=[checkpointer])\nmodel2.save_weights(\"model2\/model2_weights_ResNet50_2.h5\")\nPolt_history(hist2_2)\nplt.savefig('model2\/hist2_2.png')\n\"\"\"\n* Testing model 2: on 25000 image \n\"\"\"\n# Load neural network structure and weights\n#model2.load_weights(\"model2\/model2.weights.best_ResNet50_2.hdf5\")\n#testing known data in train folder\nTest_Model_known_Data(model2)\n#cat accuracy  = 95.136\n#dog accuracy  = 98.304\n#Total accuracy= 96.720\n\"\"\"\n* Testing model 2: on 12500 image (test data)\n\"\"\"\n#testing unknown data in test folder\npredict2,test_df =ResNet50_predict(model2,test_directory)\nSave_Submission(predict2,model2,\"model2\",test_df)\nPlot_predict(predict2,test_directory,test_df)\nplt.savefig('model2\/predicted2_2.png')\n#remove test folder\nif  os.path.exists('test1'):\n    shutil.rmtree(\"test1\") \nif  os.path.exists('data'):\n    shutil.rmtree(\"data\")\nif  os.path.exists('Alldata'):\n    shutil.rmtree(\"Alldata\") \n    \nfile1 = \"model\/model.weights.best_ResNet50_1.hdf5\"\nfile2 = \"model\/model.weights.best_ResNet50_2.hdf5\"\nfile3 = \"model\/model_weights_ResNet50_1.h5\"\nfile4 = \"model2\/model2.weights.best_ResNet50_1.hdf5\"\nfile5 = \"model2\/model2.weights.best_ResNet50_2.hdf5\"\nfile6 = \"model2\/model2_weights_ResNet50.h5\"\n\nif  os.path.isfile(file1):\n    os.remove(file1)    \nif  os.path.isfile(file2):\n    os.remove(file2) \nif  os.path.isfile(file3):\n    os.remove(file3) \nif  os.path.isfile(file4):\n    os.remove(file4) \nif  os.path.isfile(file5):\n    os.remove(file5) \nif  os.path.isfile(file6):\n    os.remove(file6) ","meta":"{'source': 'AI4Code', 'id': '54e6a34909556f'}"}
{"id":"7559","text":"\"\"\"\n# \u5bfc\u5165\u7b2c\u4e09\u65b9\u5e93\n\"\"\"\nimport os\nimport cv2\nimport ast\nimport json\nimport subprocess\nfrom glob import glob\nfrom tqdm.notebook import tqdm\nfrom pprint import pprint\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom IPython.display import Video\n\"\"\"\n### \u53c2\u6570\u8bbe\u7f6e\n\"\"\"\n# Root of input\nINPUT_PATH = '..\/input\/tensorflow-great-barrier-reef'\nHEIGHT = 720 # image height\nWIDTH  = 1280 # image width\n\"\"\"\n# \u8f93\u5165\u6570\u636e\n\"\"\"\ndf_train = pd.read_csv(INPUT_PATH + '\/train.csv')\ndisplay(df_train)\nprint(df_train.info())\nfor video_id in df_train['video_id'].unique():\n    print(f'video_id: {video_id}')\n    print(f'w   annotations:  {sum(df_train[df_train[\"video_id\"]==video_id][\"annotations\"] == \"[]\")}')\n    print(f'w\/o annotations:  {sum(df_train[df_train[\"video_id\"]==video_id][\"annotations\"] != \"[]\")}\\n')\n# \u5c06'annotations'\u7684\u7c7b\u578b\u4ecestr\u66f4\u6539\u4e3alist\ndf_train['annotations'] = df_train['annotations'].apply(ast.literal_eval) # str -> list\n# \u6dfb\u52a0\u5217\u7684\u56fe\u50cf\u8def\u5f84\u548c\u6570\u91cf\u7684\u76d2\u5b50\ndf_train['image_path'] = INPUT_PATH + '\/train_images\/video_' + df_train['video_id'].astype(str) + '\/' + df_train['video_frame'].astype(str) + \".jpg\"\ndf_train['num_bboxes'] = df_train['annotations'].apply(lambda x: len(x))\ndisplay(df_train)\nmax_num_bboxes = max(df_train['num_bboxes'])\nindexes = df_train[df_train['num_bboxes']==max_num_bboxes].index.values\nprint(f'Maximum number of bboxes in an image: {max_num_bboxes}')\ndisplay(df_train.iloc[indexes])\n# indexes[0] \u548c indexes[1] \u662f\u8fde\u7eed\u7684\u5e27\nindexes = [indexes[0], indexes[2]]\n\"\"\"\n# \u8303\u4f8b\u56fe\u7247\n\"\"\"\ndef get_bboxes(annotations):\n    \"\"\"\n    annotations: list of annotations\n    return: bboxes as [x_min, y_min, x_max, y_max]\n    \"\"\"\n    if len(annotations)==0:\n        return []\n    boxes = pd.DataFrame(annotations, columns=['x', 'y', 'width', 'height']).astype(np.int32).values\n    # [x_min, y_min, w, h] -> [x_min, y_min, x_max, y_max]\n    boxes[:, 2] = boxes[:, 0] + boxes[:, 2]\n    boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n    return boxes   \n\ndef plot_img_and_bbox(img_path, anntations):\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    fig, ax = plt.subplots(1, 1, figsize=(16,10))\n    if len(annotations)>0:\n        bboxes = get_bboxes(annotations)\n        for i, box in enumerate(bboxes):\n            # pur bbox on image\n            cv2.rectangle(img,\n                          (box[0], box[1]),\n                          (box[2], box[3]),\n                          color = (255, 0, 0),\n                          thickness = 2)\n            # numbering\n            ax.text(box[0], box[1]-5, i+1, color='red')\n\n    ax.set_axis_off()\n    ax.imshow(img)\n\n\ndef zoom_bbox(img_path, annotations):\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    bboxes = get_bboxes(annotations)\n    \n    col = 6\n    row = np.ceil(len(bboxes)\/\/6).astype(int)\n    fig, ax = plt.subplots(row, col, figsize=(16,9))\n    cnt = 0\n    for i in range(row):\n        if cnt >= len(bboxes):\n            break\n        for j in range(col):\n            bbox = bboxes[cnt]\n            sliced_img = img[bbox[1]:bbox[3], bbox[0]:bbox[2]]\n            ax[i,j].imshow(sliced_img)\n            ax[i,j].set_title(cnt+1, color='red')\n            ax[i,j].set_axis_off()\n            cnt += 1\n    plt.show() \nsamples = df_train.iloc[indexes].copy()\nfor idx, row in samples.iterrows():\n    img_path    = row['image_path']\n    annotations = row['annotations']\n    print('image_id:', row['image_id'])\n    # plot image with bboxes\n    plot_img_and_bbox(img_path, annotations)\n    # plot zoom of bboxes\n    zoom_bbox(img_path, annotations)\n\"\"\"\n# \u5236\u4f5c\u89c6\u9891\n\u751f\u6210300\u5e27\u89c6\u9891\u56f4\u7ed5\u56fe\u50cf\u4e0e\u6700\u5927\u6570\u91cf\u7684bboxes\u3002\n\n\"\"\"\ndef get_img_with_annotations(img_path, annotations):\n    img = cv2.imread(img_path)\n    video_id = img_path.split('\/')[-2].split('_')[-1]\n    frame_id = img_path.split('\/')[-1].split('.')[0]\n    img_id = video_id + '-' + frame_id\n    #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    if len(annotations)>0:\n        bboxes = get_bboxes(annotations)\n        for i, box in enumerate(bboxes):\n            # put bbox\n            cv2.rectangle(img,\n                          (box[0], box[1]),\n                          (box[2], box[3]),\n                          color = (0, 0, 255),\n                          thickness = 2)\n    # put image_id, #bbox\n    cv2.putText(img,\n                f'image_id: {img_id}, #bbox: {len(annotations)}',\n                org = (30, 50), \n                color = (0, 0, 255), \n                fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n                fontScale=1.0,\n                thickness=3)\n    \n    return img\n\ndef make_video(df, video_id, start_frame, end_frame, fps=15, width=WIDTH, height=HEIGHT):\n    '''\n    df          : DataFrame\n    video_id    : 0, 1, or 2\n    start_frame : video_frame at start of video\n    num_frame   : video_frame at end of video\n    return      : path to video\n    '''\n    video_path = f'video_{video_id}_{start_frame}_to_{end_frame}.mp4' # video after encode\n    tmp_path = 'tmp_' + video_path # video before encode (removed after encode)\n    video = cv2.VideoWriter(tmp_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))\n    \n    df = df[df['video_id']==video_id].reset_index(drop=True)\n    start_idx = df[df['video_frame']==start_frame].index[0]\n    end_idx   = df[df['video_frame']==end_frame].index[0]\n    df = df.iloc[start_idx:end_idx]\n    for idx, row in tqdm(df.iterrows(), total=len(df)):\n        image_path  = row['image_path']\n        annotations = row['annotations']\n        frame = get_img_with_annotations(image_path, annotations)\n        video.write(frame)\n    \n    video.release()\n    \n    if os.path.exists(video_path):\n        os.remove(video_path)\n    \n    # encode by ffmpeg command \n    subprocess.run(\n        ['ffmpeg', \n         '-i', tmp_path, \n         '-loglevel', 'quiet', \n         '-crf', '18', \n         '-preset', 'veryfast', \n         '-vcodec', 'libx264', \n         video_path]\n    )\n    os.remove(tmp_path)\n    \n    return video_path\nvideo_paths = []\nfor idx in indexes:\n    video_id    = df_train.loc[idx, 'video_id']\n    start_frame = df_train.loc[idx, 'video_frame'] - 100 # peek before 100 frames\n    end_frame   = df_train.loc[idx, 'video_frame'] + 200 # peek after 200 frames\n    print(f'video_id: {video_id}, video_frame: {start_frame} to {end_frame}')\n    print('Create video ...')\n    video_path = make_video(df_train,\n                            video_id=video_id,\n                            start_frame=start_frame,\n                            end_frame=end_frame)\n    video_paths.append(video_path)\n\"\"\"\n### \u7b2c\u4e00\u4e2a\u89c6\u9891\n\"\"\"\nVideo(video_paths[0], width=WIDTH*0.7, height=HEIGHT*0.7)\n\"\"\"\n<span style=\"font-size: 120%;\">The change from id=1-9071 to 9072 (around at 3 sec in this video) is small but the number of bboxes jumps up from 4 to 7 as shown below, so some starfishes are not annotated in id=1-9071. <\/span>\n\"\"\"\nimg_ids = ['1-9071', '1-9072']\nfig, ax = plt.subplots(1, 2, figsize=(20,10))\nfor i, img_id in enumerate(img_ids):\n    img_path    = df_train[df_train['image_id'].str.contains(img_id)]['image_path'].values[0]\n    annotations = df_train[df_train['image_id'].str.contains(img_id)]['annotations'].values[0]\n    img = get_img_with_annotations(img_path, annotations)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    ax[i].imshow(img)\n    ax[i].set_axis_off()\nplt.show()\n\"\"\"\n### \u7b2c\u4e8c\u4e2a\u89c6\u9891\n\"\"\"\nVideo(video_paths[1], width=WIDTH*0.7, height=HEIGHT*0.7)\n\"\"\"\n\u7c7b\u4f3c\u5730\uff0c\u5728id=2-5715\u548c5721\u4e4b\u95f4\uff0cbbox\u7684\u6570\u91cf\u4ece5\u4e2a\u66f4\u6539\u4e3a8\u4e2a\n\"\"\"\nimg_ids = ['2-5715', '2-5721']\nfig, ax = plt.subplots(1, 2, figsize=(20,10))\nfor i, img_id in enumerate(img_ids):\n    img_path    = df_train[df_train['image_id'].str.contains(img_id)]['image_path'].values[0]\n    annotations = df_train[df_train['image_id'].str.contains(img_id)]['annotations'].values[0]\n    img = get_img_with_annotations(img_path, annotations)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    ax[i].imshow(img)\n    ax[i].set_axis_off()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '0e13e3e8ffcdd7'}"}
{"id":"11445","text":"# 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\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        break\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\n\"\"\"\n# Lib Imports\n\"\"\"\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimport glob\n\nfrom keras.applications import Xception\nfrom keras.applications.xception import preprocess_input\n\"\"\"\n# Random Image Show\n\"\"\"\nim_frame = Image.open('..\/input\/expertclass\/Trainset\/Trainset\/Hoegaarden\/Hoegaarden_309.png')\nnp_frame = np.array(im_frame)\n\nplt.imshow(np_frame)\n\"\"\"\n# Loading functions\n\"\"\"\nimport fnmatch\nfrom tqdm import tqdm\n\ndef get_img_paths(root_paths, format_ = 'png'):\n    if root_paths.__class__ not in (list, tuple, set):\n        root_paths = [root_paths]\n    \n    paths = []\n    labels = []\n    for path in root_paths:\n        p, l = _get_img_paths(path, format_)\n        paths += p\n        labels += l\n    \n    paths_df = pd.DataFrame({'filename':paths, 'class':labels})\n    return paths_df\n\ndef _get_img_paths(root_path, format_ = 'png'):\n    paths = []\n    labels = []\n    for dirname, _, filenames in os.walk(root_path):\n        for filename in fnmatch.filter(filenames, f'*.{format_}'):\n            paths.append(os.path.join(dirname, filename))\n            labels.append(dirname.split('\/')[-1])\n    return paths, labels\n\ndef load_images(paths):\n    imgs = []\n    img_labels = []\n    for path in tqdm(paths):    \n        imgs.append(np.array(Image.open(path)))\n        img_labels.append(path.split('\/')[-2])\n    \n    return tuple(imgs), tuple(img_labels)\n#load all data in order to make k-fold with entire data (train + test)\ntrain_path = '..\/input\/expertclass\/Trainset\/Trainset\/'\ntest_path = '..\/input\/expertclass\/Testset\/Testset\/'\nload_images_df = get_img_paths([train_path, test_path])\nload_images_df\ndef img_to_array(load_images_df,augmentation_factor = 2, augment = True):    \n    \n    if augment == False:\n        augmentation_factor = 1\n        train_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)\n    else:\n        train_datagen = ImageDataGenerator(\n            channel_shift_range = 10,\n            shear_range = 0.2,\n            zoom_range = 0.2,\n            horizontal_flip = False,\n            rotation_range = 45,\n            vertical_flip = False,\n            preprocessing_function = preprocess_input,    \n        )\n\n    batch_gen = train_datagen.flow_from_dataframe(\n        load_images_df,\n        #color_mode = 'grayscale',\n        target_size = (299,299),\n        shuffle = False,\n        class_mode = 'raw',\n        batch_size = len(load_images_df) + 1\n    )\n\n\n    X, y = [], []\n    for _ in range(augmentation_factor):\n        X_, y_ = batch_gen[0]\n        X.append(X_)\n        y.append(y_.flatten())\n\n    X, y = np.vstack(X), np.hstack(y)\n    return X, y\n\"\"\"\n# Create Visual Features\n\"\"\"\nfeature_extractor = Xception(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    pooling='avg',\n    classifier_activation=\"softmax\",\n    input_shape = (299,299,3)\n)\nX, y = img_to_array(load_images_df,augmentation_factor = 3, augment = False)\ni = np.random.choice(range(len(X)))\nprint(y[i])\nplt.imshow(X[i])\nX_features = feature_extractor.predict(X)\nX_features = X_features.reshape(X_features.shape[0], np.prod(X_features.shape[1:]))\nimport sklearn\nsklearn.__version__\n\"\"\"\n# Modelling\n\"\"\"\nfrom sklearn.decomposition import PCA, KernelPCA\nfrom sklearn.ensemble import RandomForestClassifier, StackingClassifier, AdaBoostClassifier, BaggingClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import QuantileTransformer, StandardScaler, RobustScaler, MinMaxScaler\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.utils.class_weight import compute_sample_weight\nfrom sklearn.metrics import log_loss\n\nimport matplotlib.pyplot as plt\npca = PCA(1000).fit(X_features)\nplt.plot(np.arange(0, len(pca.explained_variance_ratio_)),pca.explained_variance_ratio_.cumsum())\nplt.title('cumulative explained variance vs n_components')\nprint(np.argmin(abs(pca.explained_variance_ratio_.cumsum() - 0.8)))\nprint(f'explained variance: {pca.explained_variance_ratio_.sum()}')\ndel pca\ndnn = MLPClassifier(\n    (64,), verbose = 0, validation_fraction = 0.2, tol = 1e-5, early_stopping = True, learning_rate = 'constant',n_iter_no_change = 15, learning_rate_init = 5e-3, alpha = 2e-4, max_iter = 200, batch_size = 'auto')\n\nfinal_estimator = BaggingClassifier(dnn, n_estimators = 50, max_samples = 1.0, max_features = 1.0)\n\nmodel_pipeline = Pipeline(\n    steps = [                \n        ('scaler2', StandardScaler()),        \n        ('model', final_estimator)\n    ]\n\n)\nsample_weight = compute_sample_weight('balanced',y)\nmodel_pipeline.fit(X_features, y)\npreds_path = '..\/input\/expertclass\/Prediction\/Prediction\/'\nX_pred, _ = img_to_array(get_img_paths(preds_path), augment = False)\nX_pred_features = feature_extractor.predict(X_pred)\n\"\"\"\n## Check Greatest losses\n\"\"\"\ntrain_proba_preds = model_pipeline.predict_proba(X_features)\ntrain_preds = model_pipeline.predict(X_features)\nlosses = np.array([log_loss(y[i:i+1],train_proba_preds[i:i+1], labels = model_pipeline.classes_) for i in range(len(y))])\n\nindexes = np.argsort(losses,)[::-1]\nn = 20\nfig,ax = plt.subplots(np.ceil(n\/5).astype(int),5)\nfor i in range(n):\n    ax[i\/\/5, i%5].imshow(X[indexes[i]])\n    ax[i\/\/5, i%5].set_title(y[indexes[i]] +'-' + train_preds[indexes[i]] +' '+ str(round(np.max(train_proba_preds[indexes[i]])*100, 2)) + '%')\nplt.subplots_adjust(left = -2, bottom = -3)\nprint('Greatest losses (\"True label\" - \"Predicted label\" \"predicted proba\")')\n\"\"\"\n## Make predictions\n\"\"\"\npreds = model_pipeline.predict(X_pred_features)\nproba_preds = model_pipeline.predict_proba(X_pred_features)\n\nfig,ax = plt.subplots(8,5)\nfor i in range(X_pred.shape[0]):\n    ax[i\/\/5, i%5].imshow(X_pred[i])\n    ax[i\/\/5, i%5].set_title(preds[i] +' '+ str(round(np.max(proba_preds[i])*100, 2)) + '%')\nplt.subplots_adjust(left = -2, bottom = -3)\nname_mapper = {\n    'Budweiser':0,\n    'Hoegaarden':1,\n    'Leffe':2,\n    'Stella':3,\n    'Others':4    \n}\n\n#sort submissions\nids = (\n    get_img_paths(preds_path)['filename']\n    .apply(\n        lambda x: int((x.split('\/')[-1].split('.')[0])))\n    .values\n)\n\npd.DataFrame({'ID':ids,'Class':preds}).replace(name_mapper).set_index('ID').to_csv(f'submission_{pd.to_datetime(\"now\").date()}.csv')","meta":"{'source': 'AI4Code', 'id': '14fab25c225067'}"}
{"id":"76577","text":"import pandas as pd\nimport numpy as np\nimport math\nimport datetime\nfrom fastai.tabular.all import *\n# from fastai.tabular import *\nfrom fastai.imports import *\nfrom fastai.metrics import error_rate\n#from fastai.callbacks import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import Normalizer\nimport scipy.stats as spstats\npath = '\/kaggle\/input\/predict-volcanic-eruptions-ingv-oe\/'\noutput_path = '\/kaggle\/output\/kaggle\/working\/modles\/'\n\"\"\"\n**The below dataframe consist of the segment ID and the target value i.e. the time left for the volcano to erupt.\nFor each of the segment ID's we have been provided with a csv file with 10 mins of logs of readings belonging to 10 different sensors.**\n\"\"\"\ntrain = pd.read_csv(path+\"train.csv\")\ntrain\nsample_submission = pd.read_csv(\"..\/input\/predict-volcanic-eruptions-ingv-oe\/sample_submission.csv\")\nsample_submission\ntrain['time_to_eruption'].describe()\ntrain_readings = glob.glob(path+\"train\/*\")\nlen(train_readings)\ntest_readings = glob.glob(path+\"test\/*\")\nlen(test_readings)\ntrain_readings[0]\nsensor_file = pd.read_csv(train_readings[0])\nsensor_file\n\"\"\"\nFor each segment ID, we have got 10 sensors and 60001 readings from each one of them.\n\"\"\"\n\"\"\"\n### Feature Creation\n\"\"\"\ndef create_features(df,signal,seg_id,sensor_id):\n    f = np.fft.fft(signal)\n    f_real = np.real(f)\n    df.loc[seg_id, f'{sensor_id}_sum']       = signal.sum()\n    df.loc[seg_id, f'{sensor_id}_mean']      = signal.mean()\n    df.loc[seg_id, f'{sensor_id}_std']       = signal.std()\n    df.loc[seg_id, f'{sensor_id}_var']       = signal.var() \n    df.loc[seg_id, f'{sensor_id}_max']       = signal.max()\n    df.loc[seg_id, f'{sensor_id}_min']       = signal.min()\n    df.loc[seg_id, f'{sensor_id}_skew']      = signal.skew()\n    df.loc[seg_id, f'{sensor_id}_mad']       = signal.mad()\n    df.loc[seg_id, f'{sensor_id}_kurtosis']  = signal.kurtosis()\n    df.loc[seg_id, f'{sensor_id}_quantile99']= np.quantile(signal, 0.99)\n    df.loc[seg_id, f'{sensor_id}_quantile95']= np.quantile(signal, 0.95)\n    df.loc[seg_id, f'{sensor_id}_quantile85']= np.quantile(signal, 0.85)\n    df.loc[seg_id, f'{sensor_id}_quantile75']= np.quantile(signal, 0.75)\n    df.loc[seg_id, f'{sensor_id}_quantile55']= np.quantile(signal, 0.55)\n    df.loc[seg_id, f'{sensor_id}_quantile45']= np.quantile(signal, 0.45) \n    df.loc[seg_id, f'{sensor_id}_quantile25']= np.quantile(signal, 0.25) \n    df.loc[seg_id, f'{sensor_id}_quantile15']= np.quantile(signal, 0.15) \n    df.loc[seg_id, f'{sensor_id}_quantile05']= np.quantile(signal, 0.05)\n    df.loc[seg_id, f'{sensor_id}_quantile01']= np.quantile(signal, 0.01)\n    df.loc[seg_id, f'{sensor_id}_fft_real_mean']= f_real.mean()\n    df.loc[seg_id, f'{sensor_id}_fft_real_std'] = f_real.std()\n    df.loc[seg_id, f'{sensor_id}_fft_real_max'] = f_real.max()\n    df.loc[seg_id, f'{sensor_id}_fft_real_min'] = f_real.min()\n    df.loc[seg_id, f'{sensor_id}_fft_real_median'] = np.median(f_real)\n    df.loc[seg_id, f'{sensor_id}_fft_real_skew'] = spstats.skew(f_real)\n    df.loc[seg_id, f'{sensor_id}_fft_real_kurtosis'] = spstats.kurtosis(f_real)\n    \n    return df\n\"\"\"\n####  Create features for Training Data\n\"\"\"\ntrain = pd.read_csv(path+'train.csv')\ntrain_df = pd.DataFrame()\ntrain_df['segment_id'] = train.segment_id\ntrain_df = train_df.set_index('segment_id')\n\nj=0\nfor seg in train.segment_id:\n    signals = pd.read_csv(path+f'train\/{seg}.csv')\n    if j%500 == 0:\n        print(j)\n    for i in range(1, 11):\n        sensor_id = f'sensor_{i}'\n        train_df = create_features(train_df, signals[sensor_id].fillna(0), seg, sensor_id,)\n    j+=1    \ntrain_df = pd.merge(train_df.reset_index(), train, on=['segment_id'], how='left').set_index('segment_id')\ntrain_df\ntrain_df = train_df.reset_index()\ny = train_df['time_to_eruption']\ntrain_df = train_df.drop(['segment_id'], axis = 1)\ntrain_df\n\"\"\"\n#### Create features for Test Data\n\"\"\"\ntest = pd.read_csv(path+'sample_submission.csv')\ntest_df = pd.DataFrame()\ntest_df['segment_id'] = test.segment_id\ntest_df = test_df.set_index('segment_id')\n\nj=0\nfor seg in test.segment_id:\n    signals = pd.read_csv(path+f'test\/{seg}.csv')\n    if j%500 == 0:\n        print(j)\n    for i in range(1, 11):\n        sensor_id = f'sensor_{i}'\n        test_df = create_features(test_df, signals[sensor_id].fillna(0), seg, sensor_id,)\n    j+=1 \ntest_df\ntest_df = test_df.reset_index()\ntest_set = test_df\ntest_df = test_df.drop(['segment_id'], axis = 1)\ntest_df\ntest_df\ntrain_df.columns\nfor i in list(train_df.columns):\n    print(i)\ncont_names = list(train_df.columns)\n#removing time to eruption column\ncont_names.pop()\ncont_names\ncat_names = []\nprocs = [Categorify, FillMissing, Normalize]\nsplits = RandomSplitter(valid_pct=0.2)(range_of(train_df))\nto = TabularPandas(train_df, procs=[Categorify, FillMissing,Normalize],\n                   cat_names = cat_names,\n                   cont_names = cont_names,\n                   y_names='time_to_eruption',\n                   splits=splits)\ndls = to.dataloaders(bs=64)\ndls.show_batch()\nlearn = tabular_learner(dls, layers=[200,100], metrics=mae, ps=[0.001,0.01], emb_drop=0.01)\nlearn.model\nlearn.lr_find(suggestions=True)\nlearn.model_dir='\/kaggle\/working\/' \nlearn.fit_one_cycle(50,0.33113112449646,cbs=SaveModelCallback(monitor='mae', comp=np.less, fname=\"stage-1\"))\nlearn.load('stage-1')\ntest_df\ndl = learn.dls.test_dl(test_df)\npreds = learn.get_preds(dl=dl)\npreds[0]\ntest_preds = []\nfor i in np.array(preds[0]):\n#     print(i[0])\n    test_preds.append(i[0])\ntest\ntest['time_to_eruption'] = test_preds\ntest\ntest.to_csv('submission.csv', index=False)\n\"\"\"\n## Work in Progress\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8cbb39d0c6b19b'}"}
{"id":"117544","text":"\"\"\"\n# Topics\n1. About Iris dataset\n2. Exploring the Iris dataset\n3. iris data visualization\n4. Supervised learning on Iris dataset\n\"\"\"\n\"\"\"\n# 1. About  iris Dataset\n\"\"\"\nfrom IPython.display import Image\nImage('..\/input\/iris-measurement\/iris_measurements.png')\n\"\"\"\n- The iris dataset contains the following data\n     - 50 samples of 3 different species of iris (150 samples total)\n- Measurements: sepal length, sepal width, petal length, petal width\n     - The format for the data: (sepal length, sepal width, petal length, petal width)\n\"\"\"\n\"\"\"\n# 2. Exploring the iris datset\n\n\"\"\"\n# importing required modules\nimport numpy as np\nimport pandas as pd\n# importing visualization maodules\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nfrom mpl_toolkits import mplot3d\nfrom sklearn.tree import plot_tree\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score,KFold,StratifiedKFold\n# importing MachineLearning Algorithms\nfrom sklearn.preprocessing import LabelEncoder,MinMaxScaler,StandardScaler\nfrom sklearn.linear_model import LinearRegression,Ridge,Lasso\nfrom sklearn.naive_bayes import MultinomialNB,BernoulliNB,GaussianNB\nfrom sklearn.linear_model import LogisticRegression,PassiveAggressiveClassifier\nfrom sklearn.svm import SVC,SVR\nfrom sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor\n# importing ensembling algorithms\nfrom sklearn.ensemble import RandomForestRegressor,RandomForestClassifier,AdaBoostClassifier,ExtraTreesClassifier,GradientBoostingClassifier,BaggingClassifier\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import KNeighborsClassifier,KNeighborsRegressor,RadiusNeighborsClassifier\nfrom sklearn.decomposition import PCA,TruncatedSVD\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# overview of the data\n### Reading the iris dataset\ndata=pd.read_csv('..\/input\/iris\/Iris.csv')\ndata.head(3)\n# checking whether our dataset has any null values\nprint(data.isnull().sum())\n\"\"\"\n# 3. iris data visualization\n1. We will visualize the data using seaborn,matplotlib,plotly\n\"\"\"\nsns.pairplot(data.drop(['Id'],axis=\"columns\"),hue='Species')\nplt.show()\nfig=plt.figure(figsize=(20,20))\ndata.drop(['Id'],axis=\"columns\").plot(kind=\"kde\",subplots=True,ax=plt.gca())\nplt.show()\nfig=plt.figure(figsize=(15,15))\ndata.drop(['Id'],axis=\"columns\").plot(kind=\"hist\",subplots=True,ax=plt.gca())\nplt.title(' histogram plotting of all the data')\nplt.show()\nfig=plt.figure(figsize=(10,10))\nax=plt.gca()\ndata.drop(['Id'],axis=\"columns\").hist(edgecolor='black', linewidth=1.2,ax=ax)\nplt.title('histogram plotting of numerical data in iris dataset')\nplt.show()\ndef plot_scatter(feature1,feature2,title):\n    fig=px.scatter(data,x=feature1,y=feature2,color='Species',title=title,hover_data=['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm',\n       'Species'],template=\"plotly_dark\")\n    fig.show()\nplot_scatter(feature1='SepalLengthCm',feature2='SepalWidthCm',title='SepalLengthCm vs SepalWidthCm')\nplot_scatter(feature1='PetalLengthCm',feature2='PetalWidthCm',title='PetalLengthCm vs PetalWidthCm')\nplot_scatter(feature1='SepalLengthCm',feature2='PetalLengthCm',title='SepalLengthCm vs PetalLengthCm')\nplot_scatter(feature1='SepalWidthCm',feature2='PetalWidthCm',title='SepalWidthCm vs PetalWidthCm')\ndef plot_bar(feature1,feature2,title):\n    fig=px.bar(data,x=feature1,y=feature2,color='Species',title=title,hover_data=['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm',\n       'Species'],template=\"plotly_dark\")\n    fig.show()\nplot_bar(feature1='SepalLengthCm',feature2='PetalWidthCm',title='SepalLengthCm vs PetalWidthCm')\nplot_bar(feature1='SepalWidthCm',feature2='PetalLengthCm',title='SepalWidthCm vs PetalLengthCm')\nplot_bar(feature1='PetalLengthCm',feature2='SepalWidthCm',title='PetalLengthCm vs SepalWidthCm')\nplot_bar(feature1='PetalWidthCm',feature2='SepalLengthCm',title='PetalWidthCm vs SepalLengthCm')\ndef pie_chart_rep(values,names,title):\n    fig = px.pie(data, values=values, names=names, title=title,template=\"plotly_dark\")\n    fig.update_layout()\n    fig.show()\npie_chart_rep(values='SepalLengthCm',names='Species',title='pie representation of SepalLengthCm and Species')\npie_chart_rep(values='SepalWidthCm',names='Species',title='pie representation of SepalWidthCm and Species')\npie_chart_rep(values='PetalLengthCm',names='Species',title='pie representation of PetalLengthCm and Species')\npie_chart_rep(values='PetalWidthCm',names='Species',title='pie representation of PetalWidthCm and Species')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=data.Species, y=data.SepalLengthCm,mode='markers', name='SepalLengthCm'))\nfig.add_trace(go.Scatter(x=data.Species, y=data.SepalWidthCm,mode='markers', name='SepalWidthCm'))\nfig.add_trace(go.Scatter(x=data.Species, y=data.PetalLengthCm,mode='markers', name='PetalLengthCm'))\nfig.add_trace(go.Scatter(x=data.Species, y=data.PetalWidthCm,mode='markers', name='PetalWidthCm'))\nfig.update_layout(template=\"plotly_dark\",title='specifying the species based on SepalLengthCm')\nfig.show()               \nfig=plt.figure(figsize=(10,10))\nplt.subplot(2,2,1)\nsns.swarmplot(x='Species',y='PetalLengthCm',data=data)\nplt.legend()\nplt.subplot(2,2,2)\nsns.swarmplot(x='Species',y='PetalWidthCm',data=data)\nplt.legend()\nplt.subplot(2,2,3)\nsns.swarmplot(x='Species',y='SepalLengthCm',data=data)\nplt.legend()\nplt.subplot(2,2,4)\nsns.swarmplot(x='Species',y='SepalWidthCm',data=data)\nplt.legend()\nplt.show()\n\"\"\"\n# 4. Supervised learning on Iris dataset\n **Supervised learning:** Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs. It infers a function from labeled training data consisting of a set of training examples.Supervised learning is divided into Regression and Classification.\n-  **Regression:** Regression is the process of finding a model or function for distinguishing the data into continuous real values instead of using classes or discrete values. It can also identify the distribution movement depending on the historical data. Because a regression predictive model predicts a quantity, therefore, the skill of the model must be reported as an error in those predictions\n-   **Classification:** Classification is the process of finding or discovering a model or function which helps in     -separating the data into multiple categorical classes i.e. discrete values. In classification, data is categorized under different labels according to some parameters given in input and then the labels are predicted for the data.\n\n\n##### Before we go into Supervised learning we must know something called feature engineering:\n- Feature Selection is one of the core concepts in machine learning which hugely impacts the performance of your model. The data features that you use to train your machine learning models have a huge influence on the performance you can achieve.\n- Irrelevant or partially relevant features can negatively impact model performance.\n- Feature selection and Data cleaning should be the first and most important step of your model designing.\n\nHow to select features and what are Benefits of performing feature selection before modeling your data?\n\n1. Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise.\n\n2. Improves Accuracy: Less misleading data means modeling accuracy improves.\n\n3. Reduces Training Time: fewer data points reduce algorithm complexity and algorithms train faster.\n\n\nAlso, we must know two terms (\nfeature_names ---> feature_names are variables that are used to determine the classification process in this iris dataset we use SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm as feature_names\nand \ntarget ---> the target variables are the output variable in this dataset we use Species as target\n)\n\"\"\"\n\"\"\"\n### Label Encoding for Species target variable\n\"\"\"\n# we convert the categorial data into numerical data using LabelEncoder()\nle=LabelEncoder()\ndata['SpeciesCategory']=le.fit_transform(data['Species'])\nlabel={0:'Iris-setosa',1:'Iris-versicolor',2:'Iris-virginica'}\n\"\"\"\n- we will look at some of the most used machine learning supervised classifier algorithms such as\n    - KNN Classifier\n    - RadiusNeighborsClassifier\n    - SVM Classifier\n    - Naive-Bayes Classifier\n    - DecisionTreeClassifier\n    - RandomForestClassifier\n    - LogisticRegressor\n\"\"\"\n\"\"\"\n# To process supervised learning algorithms\n\"\"\"\n\"\"\"\n- step1: we will first split the data into training and testing data and will divide in 7:3 ratio\n- step2: And now we will train the model using X_train and y_train with fit() function\n- step3: we will predict the X_test data using predict() function \n- step4: and then we'll find the accuracy of trained and predicted data using score() function\n\"\"\"\n# we choose feature_names and target values from the data and split the data into train and test data\nX=data.drop(['Species','SpeciesCategory'],axis='columns')\ny=data['SpeciesCategory']\nX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0,test_size=0.3)\n\"\"\"\n# KNN Classifier\n- K-Nearest Neighbors (KNN) is one of the simplest algorithms used in Machine Learning for regression and classification problem. KNN algorithms use data and classify new data points based on similarity measures (e.g. distance function). Classification is done by a majority vote to its neighbors. The data is assigned to the class which has the nearest neighbors. As you increase the number of nearest neighbors, the value of k, accuracy might increase.\n\"\"\"\n#Classification using KNeighborsClassifier and we will take nearest neighbors as 5\nknn_clf=KNeighborsClassifier(n_neighbors=5)\nknn_clf.fit(X_train,y_train)\nprint(\"the predicted values of X_test are {}\".format(knn_clf.predict(X_test)))\nprint(\"the accuracy score of trained data for KNN classifier is {}\".format(knn_clf.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for KNN classifier is {}\".format(knn_clf.score(X_test,knn_clf.predict(X_test))))\n# plotting KNN for iris dataset\nfig=px.scatter(data,x='PetalLengthCm',y='PetalWidthCm',color='Species',title='PetalLengthCm vs PetalWidthCm in KNN Classifier',size='PetalWidthCm',hover_data=['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm','Species'],template=\"plotly_dark\")\nfig.show()\n\"\"\"\n######  if we see plotting PetalLengthCm vs PetalWidthCm gives some good visualization we could easily identify our species based on PetalLengthCm vs PetalWidthCm through visualization also there is no outliers in those features\n\"\"\"\n# plotting accuracy for a range of numbers \naccuracy=[]\nn_neighbors_range=range(1,10)\nfor i in n_neighbors_range:\n    knn_clf=KNeighborsClassifier(n_neighbors=i)\n    knn_clf.fit(X_train,y_train)\n    accuracy.append(knn_clf.score(X_train,y_train))\npx.line(n_neighbors_range,accuracy,title='n_neighbors_range vs accuracy',template='plotly_dark')\n\"\"\"\n###### also after plotting n_neighbors_range to accuracy shows that for any value of n_neighbors we are getting an accuracy of 1.\n\"\"\"\n\"\"\"\n# RadiusNeighborsClassifier\n- **RadiusNeighborsClassifier:** RadiusNeighborsClassifier implements learning based on the number of neighbors within a fixed radius 'r' of each training point, where 'r' is a floating-point value specified by the user.\n- It is very much similar to KNN classifier only difference we commonly consider is, in KNN Classifier we use n_neighbors as a key factor but in RadiusNeighborsClassifier we use radius as a key factor it classifier the data based on a radius value given. \n\"\"\"\nradius_clf=RadiusNeighborsClassifier(radius=10)\nradius_clf.fit(X_train,y_train)\nprint(\"the predicted values of X_test are {}\".format(radius_clf.predict(X_test)))\nprint(\"the accuracy score of trained data for radius neighbors classifier is {}\".format(radius_clf.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for radius neighbors  classifier is {}\".format(radius_clf.score(X_test,radius_clf.predict(X_test))))\naccuracy=[]\nradius_range=range(1,20)\nfor i in radius_range:\n    radius_clf=RadiusNeighborsClassifier(radius=i)\n    radius_clf.fit(X_train,y_train)\n    accuracy.append(radius_clf.score(X_train,y_train))\npx.line(radius_range,accuracy,title='radius vs accuracy',template='plotly_dark')\n\"\"\"\n###### we could see the accuracy values changes with radius value\n\"\"\"\n\"\"\"\n# SVM Classifier\n-  \u201cSupport Vector Machine\u201d (SVM) is a supervised machine learning algorithm which can be used for both classification or regression challenges. However,  it is mostly used in classification problems. In the SVM algorithm, we plot each data item as a point in n-dimensional space (where n is number of features you have) with the value of each feature being the value of a particular coordinate. Then, we perform classification by finding the hyper-plane that differentiates the two classes very well.\n\n\n\"\"\"\nsvm_clf=SVC()\nsvm_clf.fit(X_train,y_train)\nprint(\"the predicted values of X_test are {}\".format(svm_clf.predict(X_test)))\nprint(\"the accuracy score of trained data for SVM is {}\".format(svm_clf.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for SVM is {}\".format(svm_clf.score(X_test,svm_clf.predict(X_test))))\n# plotting accuracy for a range of numbers \naccuracy=[]\nc=range(1,10)\nfor i in c:\n    svm_clf=KNeighborsClassifier(n_neighbors=i)\n    svm_clf.fit(X_train,y_train)\n    accuracy.append(svm_clf.score(X_train,y_train))\npx.line(n_neighbors_range,accuracy,title='Regularization factor(C) vs accuracy',template='plotly_dark')\n\"\"\"\n###### also after plotting n_neighbors_range to accuracy shows that for any value of n_neighbors we are getting an accuracy of 1.\n\"\"\"\n\"\"\"\n# Naive-Bayes Classifier\n- we apply Naive-Bayes Classifier for three types of Naive-Bayes:\n\n    - Gaussian: It is used in classification and it assumes that features follow a normal distribution.\n    - Multinomial: It is used for discrete counts. \n    - Bernoulli: The binomial model is useful if your feature vectors are binary (i.e. zeros and ones).\n- Naive Bayes is a probabilistic machine learning model which is used as a classifier. It comes under Supervised learning algorithms.\n- The intuition behind this algorithm is Bayes theorem. Bayes theorem tells the probability of an event occurring given the probability of another event that has been already occurred. Below is the mathematical equation of Bayes theorem.\n\"\"\"\nmnb=MultinomialNB()\nbnb=BernoulliNB()\ngnb=GaussianNB()\nmnb.fit(X_train,y_train)\nbnb.fit(X_train,y_train)\ngnb.fit(X_train,y_train)\nprint(\"the accuracy score of trained data for MultinomialNB is {}\".format(mnb.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for MultinomialNB is {}\".format(mnb.score(X_test,mnb.predict(X_test))))\nprint(\"the accuracy score of trained data for BernoulliNB is {}\".format(bnb.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for BernoulliNB is {}\".format(bnb.score(X_test,bnb.predict(X_test))))\nprint(\"the accuracy score of trained data for GaussianNB is {}\".format(gnb.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for GaussianNB is {}\".format(gnb.score(X_test,gnb.predict(X_test))))\n\"\"\"\n# DecisionTreeClassifer\n- **Decision Tree :** Decision tree is the most powerful and popular tool for classification and prediction. A Decision tree is a flowchart like tree structure, where each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label.\n- The strengths of decision tree methods are:\n   - Decision trees are able to generate understandable rules.\n   - Decision trees perform classification without requiring much computation.\n   - Decision trees are able to handle both continuous and categorical variables.\n   - Decision trees provide a clear indication of which fields are most important for prediction or classification.\n\n\n\"\"\"\ndec_tree=DecisionTreeClassifier(max_depth=10)\ndec_tree.fit(X_train,y_train)\nprint(\"predicted data is:\",svm_clf.predict(X_test))\nprint(\"the accuracy score of trained data for DecisionTreeClassifier is {}\".format(svm_clf.score(X_train,y_train)))\nprint(\"the accuracy score of test and predicted data for DecisionTreeClassifier is {}\".format(svm_clf.score(X_test,svm_clf.predict(X_test))))\nfrom sklearn import tree\nfig=plt.figure(figsize=(10,10))\n_=tree.plot_tree(dec_tree,feature_names=data.PetalLengthCm,class_names=data.Species,filled=True)\nplt.title('DecisionTreeClassifier for PetalLengthCm vs Species')\nfig.show()\n\"\"\"\n- Above Decision tree Classifies data based on MSE(Mean Squared Error) and 'gini' value\n- A tree can be \u201clearned\u201d by splitting the source set into subsets based on an attribute value test. This process is repeated on each derived subset in a recursive manner called recursive partitioning. The recursion is completed when the subset at a node all has the same value of the target variable, or when splitting no longer adds value to the predictions. \n\"\"\"\n# plotting accuracy for a range of numbers \naccuracy=[]\nmax_depth=range(1,10)\nfor i in max_depth:\n    dec_tree=KNeighborsClassifier(n_neighbors=i)\n    dec_tree.fit(X_train,y_train)\n    accuracy.append(dec_tree.score(X_test,svm_clf.predict(X_test)))\npx.line(max_depth,accuracy,title='max_depth of the tree vs accuracy',template='plotly_dark')\n\"\"\"\n######  also after plotting max_depth to accuracy shows that for any value of n_neighbors we are getting an accuracy of 1.\n\"\"\"\n\"\"\"\n# RandomForestClassifier\n**RandomForestClassifier:** Random forest is a supervised learning algorithm which is used for both classification as well as regression. But however, it is mainly used for classification problems. As we know that a forest is made up of trees and more trees means more robust forest. Similarly, random forest algorithm creates decision trees on data samples and then gets the prediction from each of them and finally selects the best solution by means of voting. It is an ensemble method which is better than a single decision tree because it reduces the over-fitting by averaging the result.\n- We can understand the working of Random Forest algorithm with the help of following steps \u2212\n\n   - Step 1 \u2212 First, start with the selection of random samples from a given dataset.\n\n   - Step 2 \u2212 Next, this algorithm will construct a decision tree for every sample. Then it will get the prediction result from every decision tree.\n\n   - Step 3 \u2212 In this step, voting will be performed for every predicted result.\n\n   - Step 4 \u2212 At last, select the most voted prediction result as the final prediction result.\n\"\"\"\nforest_clf=RandomForestClassifier(n_estimators=5)\nforest_clf.fit(X_train,y_train)\nprint(\"the predicted values are:\",forest_clf.predict(X_test))\nprint(\"the accuracy score of trained data for DecisionTreeClassifier is\",forest_clf.score(X_train,y_train))\nprint(\"the accuracy score of tested and predicted data for DecisionTreeClassifier is\",forest_clf.score(X_test,forest_clf.predict(X_test)))\nfig=plt.figure(figsize=(10,10))\n_=tree.plot_tree(forest_clf.estimators_[3],feature_names=data.PetalLengthCm,class_names=data.Species)\nplt.title(\"random forest tree PetalLengthCm vs PetalLengthCm\")\nplt.show()\n\"\"\"\n######  Above Decision tree Classifies data based on MSE(Mean Squared Error) and 'gini' value\n\"\"\"\n# plotting accuracy for a range of numbers \naccuracy=[]\nn_estimators=range(1,10)\nfor i in n_estimators:\n    forest_clf=RandomForestClassifier(n_estimators=5)\n    forest_clf.fit(X_train,y_train)\n    accuracy.append(forest_clf.score(X_test,forest_clf.predict(X_test)))\npx.line(n_estimators,accuracy,title='n_estimators of the random forest classifier vs accuracy',template='plotly_dark')\n\"\"\"\n###### also after plotting n_estimators to accuracy shows that for any value of n_estimators we are getting an accuracy of 1.\n\"\"\"\n\"\"\"\n# LogisticRegression\n- Types of Logistic Regression\n    - Generally, logistic regression means binary logistic regression having binary target variables, but there can be two more categories of target variables that can be predicted by it. Based on those number of categories, Logistic regression can be divided into following types:\n\n    - **Binary or Binomial:** In such a kind of classification, a dependent variable will have only two possible types either 1 and 0. \n    - **Multinomial:** In such a kind of classification, dependent variable can have 3 or more possible unordered types or the types having no quantitative significance.\n    - **Ordinal:** In such a kind of classification, dependent variable can have 3 or more possible ordered types or the types having a quantitative significance. For example, these variables may represent \u201cpoor\u201d or \u201cgood\u201d, \u201cvery good\u201d, \u201cExcellent\u201d and each category can have the scores like 0,1,2,3.\n ### For this iris dataset we will use Multinomial types of LogisticRegression\n\"\"\"\nlog_reg=LogisticRegression(C=100)\nlog_reg.fit(X_train,y_train)\nprint(\"the predicted values are:\",log_reg.predict(X_test))\nprint(\"the accuracy score of trained data for DecisionTreeClassifier is\",log_reg.score(X_train,y_train))\nprint(\"the accuracy score of tested and predicted data for DecisionTreeClassifier is\",log_reg.score(X_test,log_reg.predict(X_test)))\nC_range=range(1,200)\naccuracy=[]\nfor n in C_range:\n    log_reg=LogisticRegression(C=n)\n    log_reg.fit(X_train,y_train)\n    accuracy.append(log_reg.score(X_test,log_reg.predict(X_test)))\npx.line(C_range,accuracy,title='Regularization factor(C) of the tree vs accuracy',template='plotly_dark')\n\"\"\"\n###### also after plotting Regularization factor(C) to accuracy shows that for any value of n_neighbors we are getting an accuracy of 1.\n\"\"\"\n\"\"\"\n<h1>***********  Please <font color='red'>UPVOTE<\/font color> if you like my work  ****************\n\"\"\"\n\"\"\"\n<h1><font color='brown'>                   Thank you!!!!!!!!!!!!!!!!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd845a1e02d5ea4'}"}
{"id":"283","text":"\"\"\"\nHello! This is the very first notebook I will have written in kaggle. I have tried to make a simple neural network to predict whether or not a banking crisis will occur in a given country in a given year. Although the network is simple, it is over 90% accurate in its predictions, and does not tend to severly under-predict banking crises (note the confusion matrix). This neural network was constructed with the help of examples from the book \"Neural Network Projects with Python\" by James Loy, and some lines are taken directly from there. I know this isn't a data visualization tool, but I hope you find some interest in it. Thanks!\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\ndf = pd.read_csv('..\/input\/africa-economic-banking-and-systemic-crisis-data\/african_crises.csv')\n\n# converting into useful numbers\n\ndf['banking_crisis'] = df['banking_crisis'].replace('crisis',np.nan)\ndf['banking_crisis'] = df['banking_crisis'].fillna(1)\ndf['banking_crisis'] = df['banking_crisis'].replace('no_crisis',np.nan)\ndf['banking_crisis'] = df['banking_crisis'].fillna(0)\n\n# removing unneccesary data\n\ndf.drop(['cc3','country'], axis=1, inplace=True)\n\n# scaling the data\n\ndf_scaled = preprocessing.scale(df)\ndf_scaled = pd.DataFrame(df_scaled, columns=df.columns)\ndf_scaled['banking_crisis'] = df['banking_crisis']\ndf = df_scaled\n\n# defining the input data, X, and the desired results, y \n\nX = df.loc[:,df.columns != 'banking_crisis']\ny = df.loc[:, 'banking_crisis']\n\n# breaking data into training data, validation data, and test data\n\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2)\nX_train, X_val, y_train, y_val = train_test_split(X_train,y_train, test_size = 0.2)\n\n# constructing a simple Multilayer Perceptron\n\nmodel = Sequential()\nmodel.add(Dense(32,activation = 'relu', input_dim = 11))\nmodel.add(Dense(16, activation = 'relu'))\nmodel.add(Dense(1, activation = 'sigmoid'))\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\n# training the network\n\nmodel.fit(X_train, y_train, epochs=200)\n\n# scoring it on the data it trained on as well as test data\n\nscores = model.evaluate(X_train, y_train)\nprint (\"Training Accuracy: %.2f%%\\n\" % (scores[1]*100))\n\nscores = model.evaluate(X_test, y_test)\nprint (\"Testing Accuracy: %.2f%%\\n\" % (scores[1]*100))\n\n# plotting the confusion matrix\n\ny_test_pred = model.predict_classes(X_test)\nc_matrix = confusion_matrix(y_test,y_test_pred)\nax = sns.heatmap(c_matrix, annot=True, xticklabels=['No Banking Crisis','Banking Crisis'], yticklabels=['No Banking Crisis','Banking Crisis'], cbar=False, cmap='Blues')\nax.set_xlabel(\"Prediction\")\nax.set_ylabel(\"Actual\")","meta":"{'source': 'AI4Code', 'id': '0088cd0b45e666'}"}
{"id":"131961","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n# graphs\nimport matplotlib.pyplot as plt\n# import seaborn as sns; sns.set()\n%matplotlib inline\nfrom matplotlib.pyplot import rcParams\nrcParams['figure.figsize'] = 16, 9\n# read csv\ncal = pd.read_csv('..\/input\/m5-forecasting-accuracy\/calendar.csv', index_col='date', parse_dates=True)\nspr = pd.read_csv('..\/input\/m5-forecasting-accuracy\/sell_prices.csv')\neva = pd.read_csv('..\/input\/m5-forecasting-accuracy\/sales_train_evaluation.csv')\ndf01 = eva.loc[:, 'd_1':].sum()\ndf02 = eva.groupby('state_id').sum()\ndf03 = eva.groupby('store_id').sum()\ndf04 = eva.groupby('cat_id').sum()\ndf05 = eva.groupby('dept_id').sum()\ndf06 = eva.groupby(['state_id', 'cat_id']).sum()\ndf07 = eva.groupby(['state_id', 'dept_id']).sum()\ndf08 = eva.groupby(['store_id', 'cat_id']).sum()\ndf09 = eva.groupby(['store_id', 'dept_id']).sum()\n\n# FOODS_3_090 as an example for lower level\ndf10 = eva[eva['item_id']=='FOODS_3_090'].groupby('item_id').sum()\ndf11 = eva[eva['item_id']=='FOODS_3_090'].groupby('state_id').sum()\ndf12 = eva[eva['item_id']=='FOODS_3_090'].drop(['id', 'dept_id','cat_id', 'state_id'], axis=1).set_index(['item_id','store_id'])\n\"\"\"\n# Graph for level 01 and 02\n* Sales volume has been going up since 2011.\n* We see five days of Christmas with low sales volume. It implies Walmart closes stores on Christmas.\n* CA has largest sales volume among three states but the CA includes four stores whereas others three each.\n\"\"\"\nfig = plt.figure()\n\nax1 = fig.add_subplot(2, 2, 1)\nax2 = fig.add_subplot(2, 2, 2, ylim=[-1000, 30000])\nax3 = fig.add_subplot(2, 2, 3, ylim=[-1000, 30000])\nax4 = fig.add_subplot(2, 2, 4, ylim=[-1000, 30000])\n\nt = cal.index[0:1941]\n\nc1,c2,c3,c4 = 'blue','green','red','black'\nl1,l2,l3,l4 = 'LV1', 'LV2 CA', 'LV2 TX', 'LV2 WI'\n\nax1.plot(t, df01, color=c1, label=l1)\nax2.plot(t, df02.loc['CA'], color=c2, label=l2)\nax3.plot(t, df02.loc['TX'], color=c3, label=l3)\nax4.plot(t, df02.loc['WI'], color=c4, label=l4)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\n\"\"\"\n# Graph for level 3\n* We can see jumps in WI_1 and WI_2 when it spent two years.\n* We also see a jump in CA_2 in mid-2016.\n\"\"\"\nfig = plt.figure()\n\nax1 = fig.add_subplot(5, 2, 1)\nax2 = fig.add_subplot(5, 2, 2)\nax3 = fig.add_subplot(5, 2, 3)\nax4 = fig.add_subplot(5, 2, 4)\nax5 = fig.add_subplot(5, 2, 5)\nax6 = fig.add_subplot(5, 2, 6)\nax7 = fig.add_subplot(5, 2, 7)\nax8 = fig.add_subplot(5, 2, 8)\nax9 = fig.add_subplot(5, 2, 9)\nax10 = fig.add_subplot(5, 2, 10)\n\nt = cal.index[0:1941]\nidx = df03.index\n\nc1,c2,c3 = 'blue','green','red'\n\nax1.plot(t, df03.loc[idx[0]], color=c1, label=idx[0])\nax2.plot(t, df03.loc[idx[1]], color=c1, label=idx[1])\nax3.plot(t, df03.loc[idx[2]], color=c1, label=idx[2])\nax4.plot(t, df03.loc[idx[3]], color=c1, label=idx[3])\nax5.plot(t, df03.loc[idx[4]], color=c2, label=idx[4])\nax6.plot(t, df03.loc[idx[5]], color=c2, label=idx[5])\nax7.plot(t, df03.loc[idx[6]], color=c2, label=idx[6])\nax8.plot(t, df03.loc[idx[7]], color=c3, label=idx[7])\nax9.plot(t, df03.loc[idx[8]], color=c3, label=idx[8])\nax10.plot(t, df03.loc[idx[9]], color=c3, label=idx[9])\n\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\nax10.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\ndel idx\n\"\"\"\n* Here we see 28 days moving average.\n* There are some stores with stable sales growth such as CA_1, CA_4 and TX_3.\n* We also see some stores reaching plateau such as CA_3.\n* We see interesting patterns of sales volume change in CA_2, WI_1 and WI_2.\n* Some seems to have seasonality and some move at random.\n\"\"\"\nfig = plt.figure()\n\nax1 = fig.add_subplot(5, 2, 1)\nax2 = fig.add_subplot(5, 2, 2)\nax3 = fig.add_subplot(5, 2, 3)\nax4 = fig.add_subplot(5, 2, 4)\nax5 = fig.add_subplot(5, 2, 5)\nax6 = fig.add_subplot(5, 2, 6)\nax7 = fig.add_subplot(5, 2, 7)\nax8 = fig.add_subplot(5, 2, 8)\nax9 = fig.add_subplot(5, 2, 9)\nax10 = fig.add_subplot(5, 2, 10)\n\nt = cal.index[0:1941]\nidx = df03.index\n\nc1,c2,c3 = 'blue','green','red'\n\nax1.plot(t, df03.loc[idx[0]].rolling(28).mean(), color=c1, label=idx[0])\nax2.plot(t, df03.loc[idx[1]].rolling(28).mean(), color=c1, label=idx[1])\nax3.plot(t, df03.loc[idx[2]].rolling(28).mean(), color=c1, label=idx[2])\nax4.plot(t, df03.loc[idx[3]].rolling(28).mean(), color=c1, label=idx[3])\nax5.plot(t, df03.loc[idx[4]].rolling(28).mean(), color=c2, label=idx[4])\nax6.plot(t, df03.loc[idx[5]].rolling(28).mean(), color=c2, label=idx[5])\nax7.plot(t, df03.loc[idx[6]].rolling(28).mean(), color=c2, label=idx[6])\nax8.plot(t, df03.loc[idx[7]].rolling(28).mean(), color=c3, label=idx[7])\nax9.plot(t, df03.loc[idx[8]].rolling(28).mean(), color=c3, label=idx[8])\nax10.plot(t, df03.loc[idx[9]].rolling(28).mean(), color=c3, label=idx[9])\n\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\nax10.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\ndel idx\ndf03.mean(axis=1)\nfig = plt.figure()\n\nax1 = fig.add_subplot(2, 2, 1)\nax2 = fig.add_subplot(2, 2, 2)\nax3 = fig.add_subplot(2, 2, 3)\n\nt = cal.index[0:1941]\nidx = df04.index\n\nc1,c2,c3 = 'blue','green','red'\n\nax1.plot(t, df04.loc[idx[0]], color=c1, label=idx[0])\nax2.plot(t, df04.loc[idx[1]], color=c2, label=idx[1])\nax3.plot(t, df04.loc[idx[2]], color=c3, label=idx[2])\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\ndel idx\nfig = plt.figure()\n\nax1 = fig.add_subplot(4, 2, 1)\nax2 = fig.add_subplot(4, 2, 2)\nax3 = fig.add_subplot(4, 2, 3)\nax4 = fig.add_subplot(4, 2, 5)\nax5 = fig.add_subplot(4, 2, 6)\nax6 = fig.add_subplot(4, 2, 7)\nax7 = fig.add_subplot(4, 2, 8)\n\nt = cal.index[0:1941]\nidx = df05.index\n\nc1,c2,c3 = 'blue','green','red'\n\nax1.plot(t, df05.loc[idx[0]], color=c1, label=idx[0])\nax2.plot(t, df05.loc[idx[1]], color=c1, label=idx[1])\nax3.plot(t, df05.loc[idx[2]], color=c1, label=idx[2])\nax4.plot(t, df05.loc[idx[3]], color=c2, label=idx[3])\nax5.plot(t, df05.loc[idx[4]], color=c2, label=idx[4])\nax6.plot(t, df05.loc[idx[5]], color=c3, label=idx[5])\nax7.plot(t, df05.loc[idx[6]], color=c3, label=idx[6])\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\ndel idx\nfig = plt.figure()\n\nax1 = fig.add_subplot(3, 3, 1)\nax2 = fig.add_subplot(3, 3, 2)\nax3 = fig.add_subplot(3, 3, 3)\nax4 = fig.add_subplot(3, 3, 4)\nax5 = fig.add_subplot(3, 3, 5)\nax6 = fig.add_subplot(3, 3, 6)\nax7 = fig.add_subplot(3, 3, 7)\nax8 = fig.add_subplot(3, 3, 8)\nax9 = fig.add_subplot(3, 3, 9)\n\nt = cal.index[0:1941]\nc1,c2,c3 = 'blue','green','red'\nl1,l2,l3 = 'FOODS', 'HOBBIES', 'HOUSEHOLD'\nl4,l5,l6 = 'CA_', 'TX_', 'WI_'\n\nax1.plot(t, df06.loc[('CA', 'FOODS')], color=c1, label=l4 + l1)\nax2.plot(t, df06.loc[('CA', 'HOBBIES')], color=c2, label=l4 + l2)\nax3.plot(t, df06.loc[('CA', 'HOUSEHOLD')], color=c3, label=l4 + l3)\nax4.plot(t, df06.loc[('TX', 'FOODS')], color=c1, label=l5+l1)\nax5.plot(t, df06.loc[('TX', 'HOBBIES')], color=c2, label=l5+l2)\nax6.plot(t, df06.loc[('TX', 'HOUSEHOLD')], color=c3, label=l5+l3)\nax7.plot(t, df06.loc[('WI', 'FOODS')], color=c1, label=l6+l1)\nax8.plot(t, df06.loc[('WI', 'HOBBIES')], color=c2, label=l6+l2)\nax9.plot(t, df06.loc[('WI', 'HOUSEHOLD')], color=c3, label=l6+l3)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\nfig = plt.figure()\n\nax1 = fig.add_subplot(3, 3, 1)\nax2 = fig.add_subplot(3, 3, 2)\nax3 = fig.add_subplot(3, 3, 3)\nax4 = fig.add_subplot(3, 3, 4)\nax5 = fig.add_subplot(3, 3, 5)\nax6 = fig.add_subplot(3, 3, 6)\nax7 = fig.add_subplot(3, 3, 7)\nax8 = fig.add_subplot(3, 3, 8)\nax9 = fig.add_subplot(3, 3, 9)\n\nt = cal.index[0:1941]\nc1,c2,c3 = 'blue','green','red'\nl1,l2,l3 = 'FOODS_1', 'HOBBIES_1', 'HOUSEHOLD_1'\nl4,l5,l6 = 'CA_', 'TX_', 'WI_'\n\nax1.plot(t, df07.loc[('CA', l1)], color=c1, label=l4 + l1)\nax2.plot(t, df07.loc[('CA', l2)], color=c2, label=l4 + l2)\nax3.plot(t, df07.loc[('CA', l3)], color=c3, label=l4 + l3)\nax4.plot(t, df07.loc[('TX', l1)], color=c1, label=l5+l1)\nax5.plot(t, df07.loc[('TX', l2)], color=c2, label=l5+l2)\nax6.plot(t, df07.loc[('TX', l3)], color=c3, label=l5+l3)\nax7.plot(t, df07.loc[('WI', l1)], color=c1, label=l6+l1)\nax8.plot(t, df07.loc[('WI', l2)], color=c2, label=l6+l2)\nax9.plot(t, df07.loc[('WI', l3)], color=c3, label=l6+l3)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\nfig = plt.figure()\n\nax1 = fig.add_subplot(3, 3, 1)\nax2 = fig.add_subplot(3, 3, 2)\nax3 = fig.add_subplot(3, 3, 3)\nax4 = fig.add_subplot(3, 3, 4)\nax5 = fig.add_subplot(3, 3, 5)\nax6 = fig.add_subplot(3, 3, 6)\nax7 = fig.add_subplot(3, 3, 7)\nax8 = fig.add_subplot(3, 3, 8)\nax9 = fig.add_subplot(3, 3, 9)\n\nt = cal.index[0:1941]\nc1,c2,c3 = 'blue','green','red'\nl1,l2,l3 = 'FOODS', 'HOBBIES', 'HOUSEHOLD'\nl4,l5,l6 = 'CA_1', 'TX_1', 'WI_1'\n\nax1.plot(t, df08.loc[(l4, l1)], color=c1, label=l4+l1)\nax2.plot(t, df08.loc[(l4, l2)], color=c2, label=l4+l2)\nax3.plot(t, df08.loc[(l4, l3)], color=c3, label=l4+l3)\nax4.plot(t, df08.loc[(l5, l1)], color=c1, label=l5+l1)\nax5.plot(t, df08.loc[(l5, l2)], color=c2, label=l5+l2)\nax6.plot(t, df08.loc[(l5, l3)], color=c3, label=l5+l3)\nax7.plot(t, df08.loc[(l6, l1)], color=c1, label=l6+l1)\nax8.plot(t, df08.loc[(l6, l2)], color=c2, label=l6+l2)\nax9.plot(t, df08.loc[(l6, l3)], color=c3, label=l6+l3)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\nfig = plt.figure()\n\nax1 = fig.add_subplot(3, 3, 1)\nax2 = fig.add_subplot(3, 3, 2)\nax3 = fig.add_subplot(3, 3, 3)\nax4 = fig.add_subplot(3, 3, 4)\nax5 = fig.add_subplot(3, 3, 5)\nax6 = fig.add_subplot(3, 3, 6)\nax7 = fig.add_subplot(3, 3, 7)\nax8 = fig.add_subplot(3, 3, 8)\nax9 = fig.add_subplot(3, 3, 9)\n\nt = cal.index[0:1941]\nc1,c2,c3 = 'blue','green','red'\nl1,l2,l3 = 'FOODS_3', 'HOBBIES_2', 'HOUSEHOLD_2'\nl4,l5,l6 = 'CA_1', 'TX_1', 'WI_1'\n\nax1.plot(t, df09.loc[(l4, l1)], color=c1, label=l4+l1)\nax2.plot(t, df09.loc[(l4, l2)], color=c2, label=l4+l2)\nax3.plot(t, df09.loc[(l4, l3)], color=c3, label=l4+l3)\nax4.plot(t, df09.loc[(l5, l1)], color=c1, label=l5+l1)\nax5.plot(t, df09.loc[(l5, l2)], color=c2, label=l5+l2)\nax6.plot(t, df09.loc[(l5, l3)], color=c3, label=l5+l3)\nax7.plot(t, df09.loc[(l6, l1)], color=c1, label=l6+l1)\nax8.plot(t, df09.loc[(l6, l2)], color=c2, label=l6+l2)\nax9.plot(t, df09.loc[(l6, l3)], color=c3, label=l6+l3)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\n\"\"\"\n* We see stable sales volumen in FOODS_1 in WI since 2011, but we do see jumps in FOODS_2 and FOODS_3 in WI.\n* Other than FOODS_2 in WI, we see stable demand in FOODS. On the other hand, we see spikes in HOBBIES.\n\"\"\"\n\"\"\"\n# Single product level\n* Above we see aggregated data and here and below we see separated data in single products.\n* Below wee see a lot of sales lacks probely according to seasonality whereas we often see stable sales in aggregated level.\n* Predicting lower level sales one by one would be a tough project.\n\"\"\"\nfig = plt.figure()\n\nax1 = fig.add_subplot(2, 2, 1)\nax2 = fig.add_subplot(2, 2, 2)\nax3 = fig.add_subplot(2, 2, 3)\nax4 = fig.add_subplot(2, 2, 4)\n\nt = cal.index[0:1941]\n\nc1,c2,c3,c4 = 'blue','green','red','black'\nl1,l2,l3,l4 = 'LV10', 'LV11 CA', 'LV11 TX', 'LV11 WI'\n\nax1.plot(t, df10.T, color=c1, label=l1)\nax2.plot(t, df11.loc['CA'], color=c2, label=l2)\nax3.plot(t, df11.loc['TX'], color=c3, label=l3)\nax4.plot(t, df11.loc['WI'], color=c4, label=l4)\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()\nfig = plt.figure()\n\nax1 = fig.add_subplot(5, 2, 1)\nax2 = fig.add_subplot(5, 2, 2)\nax3 = fig.add_subplot(5, 2, 3)\nax4 = fig.add_subplot(5, 2, 4)\nax5 = fig.add_subplot(5, 2, 5)\nax6 = fig.add_subplot(5, 2, 6)\nax7 = fig.add_subplot(5, 2, 7)\nax8 = fig.add_subplot(5, 2, 8)\nax9 = fig.add_subplot(5, 2, 9)\nax10 = fig.add_subplot(5, 2, 10)\n\nt = cal.index[0:1941]\nc1,c2,c3 = 'blue','green','red'\nidx = eva['store_id'].unique()\nitem = 'FOODS_3_090'\n\nax1.plot(t, df12.loc[(item, idx[0])], color=c1, label=item + idx[0])\nax2.plot(t, df12.loc[(item, idx[1])], color=c1, label=item + idx[1])\nax3.plot(t, df12.loc[(item, idx[2])], color=c1, label=item + idx[2])\nax4.plot(t, df12.loc[(item, idx[3])], color=c1, label=item + idx[3])\nax5.plot(t, df12.loc[(item, idx[4])], color=c2, label=item + idx[4])\nax6.plot(t, df12.loc[(item, idx[5])], color=c2, label=item + idx[5])\nax7.plot(t, df12.loc[(item, idx[6])], color=c2, label=item + idx[6])\nax8.plot(t, df12.loc[(item, idx[7])], color=c3, label=item + idx[7])\nax9.plot(t, df12.loc[(item, idx[8])], color=c3, label=item + idx[8])\nax10.plot(t, df12.loc[(item, idx[9])], color=c3, label=item + idx[9])\n\nax1.legend(loc = 'upper left')\nax2.legend(loc = 'upper left')\nax3.legend(loc = 'upper left')\nax4.legend(loc = 'upper left')\nax5.legend(loc = 'upper left')\nax6.legend(loc = 'upper left')\nax7.legend(loc = 'upper left')\nax8.legend(loc = 'upper left')\nax9.legend(loc = 'upper left')\nax10.legend(loc = 'upper left')\n\nfig.tight_layout() \nplt.show()","meta":"{'source': 'AI4Code', 'id': 'f2c0534c7c1d41'}"}
{"id":"34899","text":"\"\"\"\n# **Firstly, let's import all necessary libraries**\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport random\nfrom scipy import stats\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.metrics import mean_squared_error,roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold,StratifiedKFold\nfrom xgboost import XGBRegressor\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom sklearn import preprocessing\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\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# **Reading dataset as train, test and submit**\n\"\"\"\ntrain = pd.read_csv('..\/input\/30-days-of-ml\/train.csv')\ntest  = pd.read_csv('..\/input\/30-days-of-ml\/test.csv')\nsubmit = pd.read_csv('..\/input\/30-days-of-ml\/sample_submission.csv')\n\"\"\"\n# **Let's observe our data**\n\"\"\"\ntrain.head()\ntrain.tail()\ntest.head()\ntest.tail()\ntrain.info()\ntest.info()\ntrain.isnull().sum()\ntest.isnull().sum()\n\"\"\"\nAs you see code below (*train.isnull().sum()*), we don't have any null value.\n\"\"\"\ntrain.describe()\ncategorical_cols=['cat'+str(i) for i in range(10)]\ncontinous_cols=['cont'+str(i) for i in range(14)]\nprint(categorical_cols)\nprint(32*\"----\") \nprint(continous_cols)\n\"\"\"\n# Data Visualization\n\"\"\"\n\"\"\"\n## Distribution of Continuous Features  \n\"\"\"\ni = 1\nplt.figure()\nfig, ax = plt.subplots(7, 2,figsize=(20, 24))\nfor feature in continous_cols:\n    plt.subplot(7, 2,i)\n    sns.histplot(train[feature],color=\"blue\", kde=True,bins=100, label='train')\n    sns.histplot(test[feature],color=\"olive\", kde=True,bins=100, label='test')\n    plt.xlabel(feature, fontsize=9); plt.legend()\n    i += 1\n\"\"\"\n## Distribution of Categorical Features  \n\"\"\"\ni = 1\nplt.figure()\nfig, ax = plt.subplots(5, 2,figsize=(28, 44))\nfor feature in categorical_cols:\n    plt.subplot(5, 2,i)\n    sns.histplot(train[feature],color=\"blue\", label='train')\n    sns.histplot(test[feature],color=\"olive\", label='test')\n    plt.xlabel(feature, fontsize=9); plt.legend()\n    i += 1\nplt.show()\n\"\"\"\n## Heat Map\n\"\"\"\ncorr = train[continous_cols+['target']].corr()\ncorr.style.background_gradient(cmap='coolwarm').set_precision(2)\n\"\"\"\n# Data Encoding\n\"\"\"\ntrain.drop(\"id\", axis=1, inplace=True)\ntest.drop(\"id\", axis=1, inplace=True)\nx = train.drop(['target'], axis=1)\ny = train['target']\nX_test = test.copy()\nordinal_encoder = OrdinalEncoder()\nx[categorical_cols] = ordinal_encoder.fit_transform(x[categorical_cols])\nX_test[categorical_cols] = ordinal_encoder.transform(X_test[categorical_cols])\nx.head()\n# train test split\nfrom sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(x, y,test_size=0.2, random_state=50)\n\"\"\"\n# Application of Xgboost \n\"\"\"\nxgb_params = {'objective': 'reg:squarederror',\n              'n_estimators': 10000,\n              'learning_rate': 0.036,\n              'subsample': 0.926,\n              'colsample_bytree': 0.118,\n              'grow_policy':'lossguide',\n              'max_depth': 3,\n              'booster': 'gbtree', \n              'reg_lambda': 45.1,\n              'reg_alpha': 34.9,\n              'random_state': 42,\n              'reg_lambda': 0.00087,\n              'reg_alpha': 23.132}\n\nmodel_XGB = XGBRegressor(**xgb_params)\nmodel_XGB.fit(X_train, y_train) \npred_XGB = model_XGB.predict(X_valid)\nprint(mean_squared_error(y_valid, pred_XGB, squared=False))\n\"\"\"\nParameters were taken from https:\/\/www.kaggle.com\/miladagdam\/30-days-of-ml-xgboost\n\"\"\"\n\"\"\"\n# Let's submit to the competition\n\"\"\"\npred = model_XGB.predict(X_test)\n# Save the predictions to a CSV file\nsubmit['target']=pred\nsubmit.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '40435f2c86e28e'}"}
{"id":"18554","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nheart_data = pd.read_csv('..\/input\/heart-disease-uci\/heart.csv')\nheart_data.head()\ny = heart_data['target']\nX = heart_data.drop('target', axis = 1)\nX.head()\nX.describe()\ny.value_counts()\n\"\"\"\nLets split our data\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n# keep in mind that we want to use scaler on a training data not on a test data. so before scaling we need to split our data\n\n#we will use a standart scaler to scale the features for preprocessing\n\nscaler = StandardScaler()\nscale = scaler.fit(X_train)\n#print(scale.mean_)\n#print(scale.scale_)\nX_train = scale.transform(X_train)\n\nX_test = scale.transform(X_test)\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train)\npred = model.predict(X_test)\nscore = accuracy_score(y_test, pred)\nscore\nconfusion_matrix(y_test, pred)\ntn, tp, fn, fp = confusion_matrix(y_test, pred).ravel()\n(tn, tp, fn, fp)\nmatrix = classification_report(y_test, pred)\nprint('Classification report \\n', matrix)","meta":"{'source': 'AI4Code', 'id': '21e2ededa4a7f2'}"}
{"id":"133643","text":"'''General Header for Python Operations'''\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport seaborn as sns\nimport warnings\nimport os\n\n# set graphics and print options\n%matplotlib inline\nplt.style.use('ggplot')\nplt.rcParams[\"figure.figsize\"] = (15,20)\npd.set_option('precision', 3)\nnp.set_printoptions(precision=3)\n\n# hide warnings\nwarnings.filterwarnings('ignore')\n\n# print input files for dataset\nfiles_dict = {}\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        files_dict[filename.split('.')[0]] = os.path.join(dirname, filename)\n        print(files_dict[filename.split('.')[0]])\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\n\"\"\"\n- train.csv - the training data, one product (id) per row, with the associated features (feature_*) and class label (target)\n\n- test.csv - the test data; you must predict the probability the id belongs to each class\n\n- sample_submission.csv - a sample submission file in the correct format\n\"\"\"\n# Import Datasets\ndata_dict = {}\nfor file in files_dict.keys():\n    data_dict[file] = pd.read_csv(files_dict[file])\n\n#Examine Data\nfor df in data_dict.keys():\n    print(f'\\n {df}')\n    display(data_dict[df].head())\n    display(data_dict[df].info())\n# Check For NaN's\ntrain_df = data_dict['train']\nprint('Any Features with NaN?')\nany(train_df.isna().sum() > 0)\n\"\"\"\n# EDA\n\"\"\"\n# Check Balance of training set classes\ntrain_df.groupby('target').describe()\n\"\"\"\nThe classes are highly imbalanced. Classes 3 and 4 are extremely under represented. Models where initially built having undersampled the majorities to even out the data set but resulted in a data set that was too small. So, training should be done on the data as is.\n\"\"\"\n# check feature cadinality\nfor col in train_df.columns:\n    print(f'{col}: {train_df[col].nunique()} unique values.')\n# Look at descriptive stats for each column\nfor col in train_df.columns[:-1]:\n    tmp = train_df[col].describe()\n    tmp = [tmp['mean'],tmp['50%'],tmp['std'],tmp['min'],tmp['max']]\n    print(f'{col}: Mean {tmp[0]:0.4f}, Med: {tmp[1]:0.4f}, Std: {tmp[2]:0.4f}, Range: ({tmp[3]}, {tmp[4]})')\n\"\"\"\nAll values are non-negative and appear to be badly skewed right\n\"\"\"\n# check normality of features\nfor col in train_df.columns[:-1]:\n    print(f'{col}: SW test p-value = {stats.shapiro(train_df[col]).pvalue}')\n\"\"\"\nNone of the features are normally distributed\n\"\"\"\n# Examine Hist of all features\n_= train_df[train_df.columns[1:-1]].hist(figsize=(15,40), layout=(15,5), bins=40)\n\"\"\"\nAs expected, the data is all skewed right, so we'll transform it via Box-Cox method.\n\"\"\"\n# Examine Hist of all features with power transforms and iterate to find best by hand\n_= train_df[train_df.columns[1:-1]].pow(1\/2.).hist(figsize=(15,40), layout=(15,5), bins=40)\n\"\"\"\nNone of them look great, but the square root is as good as any other transform.\n\nLooking at correlation between features...\n\"\"\"\n# Examine intra-feature correlations\nm = train_df[train_df.columns[1:-1]].corr()\nmsk = np.triu(np.ones_like(m, dtype=bool))\nplt.figure(figsize=(20,20))\n_=sns.heatmap(m, mask = msk, cmap = 'coolwarm', annot=False, cbar=False)\n\n\"\"\"\nLooks like there are some highly correlated features, so we'll look at performing pca.\n\"\"\"\n# Examine singular values\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import PowerTransformer\n\nsclr = PowerTransformer(method='yeo-johnson', standardize=True)\n\npca = PCA().fit(sclr.fit_transform(train_df[train_df.columns[1:-1]]))\nplt.figure(figsize=(10,7))\nplt.plot(np.arange(1,len(train_df.columns[1:-1])+1),np.cumsum(pca.explained_variance_ratio_))\nplt.hlines(0.95, *plt.xlim(), colors='k', linestyles='dotted', alpha = 0.5)\nplt.ylabel('Cumulative Explained Var Ratio')\nplt.xlabel('Number of Components')\n_= plt.title('PCA of Raw Features', fontweight='bold')\n\"\"\"\nThere are roughly 68 components required to explain 95% of the variance in the data, so we'll use PCA to eliminate the extra feature count.\n\"\"\"\n# Find number of components to explain 95% of var\npca = PCA(n_components=0.95).fit(sclr.fit_transform(train_df[train_df.columns[1:-1]]))\nprint(f'95% Var Number of Components: {pca.n_components_}, Explained Variance: {np.sum(pca.explained_variance_ratio_)}')\n\"\"\"\n# Prepare Data for ML\n\n### Cap data since it's all non-negative and skrewed right\n\"\"\"\n# Cap data at 99th percentile\ntrain_df[train_df.columns[1:-1]].clip(upper = train_df[train_df.columns[1:-1]].quantile(0.99), axis = 1, inplace = True)\n\"\"\"\n### Encode the Target\n\"\"\"\n# Encode Target variable\nfrom sklearn.preprocessing import LabelEncoder\ntarget_le = LabelEncoder()\ntrain_df['target_enc'] = target_le.fit_transform(train_df['target'])\n# Save raw feature column names\nraw_cols = list(train_df.columns[1:-2])\n\"\"\"\n## Perform Yeo-Johnson Transform, Standardization, PCA on transformed data, separate out features and target, split in to train and validation sets\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\npca_tr = PCA(n_components=70)\n\n# Separate Targets and Features\nX = pd.DataFrame(pca_tr.fit_transform(sclr.fit_transform(train_df[raw_cols])))\nX_test = pd.DataFrame(pca_tr.fit_transform(sclr.fit_transform(data_dict['test'][raw_cols])))\ny = train_df['target_enc']\n\n\nprint(f'X shape: {X.shape}')\nprint(f'y shape: {y.shape}')\nprint()\n\n# Stratified train validation split\nX_train, X_val, y_train, y_val = train_test_split(X, y, stratify=y, random_state= 42, test_size=0.20)\nprint(f'X Train {X_train.shape}')\nprint(f'X Val {X_val.shape}')\nprint(f'X Test {X_test.shape}')\nprint(f'y Train {y_train.shape}')\nprint(f'y Val {y_val.shape}')\n# Check Category Percentages from stratification\nprint('Original Splits:')\nprint(y.value_counts() \/ len(y), '\\n')\nprint('Training Splits:')\nprint(y_train.value_counts() \/ len(y_train), '\\n')\nprint('Validation Splits:')\nprint(y_val.value_counts() \/ len(y_val), '\\n')\n\"\"\"\n# Model Selection\nThe competition metric is log loss.\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import log_loss, accuracy_score\nimport joblib\n\ndef clfr_perfomance(y_true,X_, model):\n    print(f'Accuracy: {accuracy_score(y_true,model.predict(X_)):0.4f}')\n    print(f'Log Loss Function: {log_loss(y_true,model.predict_proba(X_)):0.4f}')\n\"\"\"\nSince we need to predict class probablies, find all the classifiers with predict_proba function in sklearn\n\"\"\"\nfrom sklearn.utils import all_estimators\n\nestimators = all_estimators()\n\nfor name, class_ in estimators:\n    if hasattr(class_, 'predict_proba'):\n        print(name)\n\"\"\"\n## Setup Gridsearch with crossvalidation to opt hyperparams\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom xgboost import XGBClassifier\n\nmdls = {'rf': RandomForestClassifier(n_jobs=-1),\n       'gbc': GradientBoostingClassifier(),\n       'mlp': MLPClassifier()}\n\nprms = {'rf': {'n_estimators': [2**i for i in range(3,8)],\n               'max_depth':  [8,16,32,64,None]},\n        'gbc': {'n_estimators': [250,500],\n               'max_depth':  [1,5,9],\n               'learning_rate': [0.001,0.01,0.1]},\n        'mlp': {'hidden_layer_sizes': [(10,),(50,),(100,),(200,)],\n               'activation': ['logistic','tanh','relu'],\n               'learning_rate': ['constant','invscaling','adaptive']}\n        \n        }\n\"\"\"\n# Train Models for Evaluation\n\"\"\"\ndef train_model(key,models,params):\n    print('Training model: {}'.format(key))\n    gs_cv = GridSearchCV(models[key],params[key], cv = 5,\n                         scoring='neg_log_loss', n_jobs = -1, verbose=1)\n    best_est = gs_cv.fit(X_train, y_train)\n    print('Best Estimator: {}'.format(best_est.best_params_))\n    print('Best Estimator Score: {}'.format(best_est.best_score_))\n    joblib.dump(best_est.best_estimator_,'{}_tr.pkl'.format(key))\n\"\"\"\n# Train random forest\ntrain_model('rf',mdls,prms)\n\"\"\"\n\"\"\"\nTraining model: rf <br>\nFitting 5 folds for each of 25 candidates, totalling 125 fits<br>\nBest Estimator: {'max_depth': 16, 'n_estimators': 128}<br>\nBest Estimator Score: -1.7731683449052305<br>\n\n\"\"\"\n\"\"\"\n# Train multilayer perceptron classifier\ntrain_model('mlp',mdls,prms)\n\n\"\"\"\n\"\"\"\nTraining model: mlp <br>\nFitting 5 folds for each of 36 candidates, totalling 180 fits<br>\nBest Estimator: {'activation': 'tanh', 'hidden_layer_sizes': (10,), 'learning_rate': 'invscaling'}<br>\nBest Estimator Score: -1.7609277700753556<br>\n\"\"\"\n\"\"\"\nfrom sklearn.model_selection import cross_val_score\nmlp = MLPClassifier(activation='tanh',hidden_layer_sizes = (10,),\n                    learning_rate='invscaling')\ncv_mlp = cross_val_score(mlp, X_train,y_train, scoring='neg_log_loss', cv = 10)\nprint(f'CV Score for MLP min: {np.min(-cv_mlp)}, max: {np.max(-cv_mlp)}, mean: {np.mean(-cv_mlp)}, median: {np.median(-cv_mlp)}')\n\"\"\"\n\"\"\"\n\nCV Score for MLP min: 1.7457966814685377, max: 1.756144311735689, mean: 1.7520049992817097, median: 1.7515735323667034\n\"\"\"\n\"\"\"\n# Train gradient boosted tree classifier\ntrain_model('gbc',mdls,prms)\n\"\"\"\n\"\"\"\nTraining model: gbc <br>\nFitting 5 folds for each of 18 candidates, totalling 90 fits <br>\n*Did not converge in a reasonable amount of time*\n\"\"\"\n\"\"\"\n# Final Model Training and Optimization\nThe multilayer perceptron performed the best, so we will use a Keras MLP as the final model\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.losses import SparseCategoricalCrossentropy\n\n# Define the model\nmodel = Sequential()\nmodel.add(Dense(70, input_dim = 70, activation='tanh', name='input'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation='relu', name = 'hidden'))\nmodel.add(Dense(9, activation='sigmoid', name = 'output')) \nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])  \n\nmodel.summary()\n\"\"\"\n### Callbacks\n\"\"\"\nfrom keras.callbacks import EarlyStopping,ReduceLROnPlateau\nlr_dec = ReduceLROnPlateau(monitor='loss')\nes_callback = EarlyStopping(monitor='loss', restore_best_weights=True)\n\"\"\"\n### Train Model\n\"\"\"\nfrom sklearn.preprocessing import OneHotEncoder\nohc = OneHotEncoder(sparse=False)\n\n# fit model\nnp.random.seed(42)\nhist = model.fit(X_train.values,ohc.fit_transform(y_train.values.reshape(-1,1)),verbose = 1,\n                 epochs=200,callbacks=[lr_dec, es_callback])\n\"\"\"\n## Check Validation Score\n\n\"\"\"\nmodel.evaluate(x=X_val.values,y=ohc.fit_transform(y_val.values.reshape(-1,1)))\n\"\"\"\n## Create Submission\n\"\"\"\nX_test['id'] = data_dict['test']['id']\nsub_df = data_dict['sample_submission']\nsub_df['id'] = X_test['id']\npred = model.predict(X_test.drop(columns=['id']))\nsub_df[[x for x in sub_df.columns if x != 'id']] = pred \n#sub_df.set_index(columns = 'id', inplace=True)\nsub_df.head()\nsub_df.set_index('id', drop=True).head()\n# write submission to file\nsub_df.set_index('id', drop=True).to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': 'f5c359492885e9'}"}
{"id":"99451","text":"\"\"\"\n## Importing Required Libraries\n\"\"\"\nimport numpy as np                   # For creating matrices and for number operations\nimport pandas as pd                  # For manipulating and reading data\nimport matplotlib.pyplot as plt      # for ploting graphs\nimport seaborn as sns                # To plot heatmaps\nimport warnings                      # Hide warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n## Loading Dataset\n\"\"\"\ndf = pd.read_csv(\"\/kaggle\/input\/titanic\/train.csv\")\ndf.head()\ndf.info()\nplt.figure(figsize = (10 , 5))\nsns.heatmap(df.corr() , annot = True , cmap = \"coolwarm\" , )   # Heatmap of correlations accross columns\nplt.figure(figsize = (15 , 8))\nsns.heatmap(df.isnull() , cmap = \"coolwarm\" , yticklabels = False)\nsns.set_style(\"darkgrid\")\nsns.countplot(data = df , x = \"Survived\")  # Value_counts of target column\ndf[\"First\"] = df[\"Name\"].apply(lambda x : x.split(\",\")[1].split(\".\")[0])\ndf.head()\ndf[\"First\"].dtype\ndf.info()\ndf[\"First\"].value_counts()\nrest = [\" Dr\" , \" Rev\" , \" Major\" , \" Mlle\" , \" Col\" , \" Don\" , \" Lady\" , \" Sir\" , \" Capt\" , \" Ms\" , \" Jonkheer\" , \" Mme\" , \" the Countess\"]\ndf[\"First\"].isna().sum()\ndf[\"First\"].loc[df[\"First\"].isin(rest)] = \"rest\"\ndf[\"First\"][3]\ndf[\"First\"].value_counts()\ndf.isna().sum() , len(df)  # Checking for null values\ntest = pd.read_csv(\"\/kaggle\/input\/titanic\/test.csv\")    # Loading test dataset\ntest.head()\ntest.info()\ntest.isna().sum() , len(test)  # Checking for null values\ntest[\"First\"] = test[\"Name\"].apply(lambda x : x.split(\",\")[1].split(\".\")[0])\ntest[\"First\"].loc[test[\"First\"].isin(rest)] = \"rest\"\ntest[\"First\"].value_counts()\ntest[\"First\"].loc[test[\"First\"] == \" Dona\"] = \"rest\"\ntest[\"First\"].value_counts()\n# Droping Cabin columns as it has more percentage of missing values\n\ndf.drop([\"Cabin\"] , axis = 1 , inplace = True)        \ntest.drop([\"Cabin\"] , axis = 1 , inplace = True)\ndf.info()\n# Droping columns with unique values as they are not useful\n\ndf.drop([\"PassengerId\" , \"Name\"] , axis = 1 , inplace = True)\nids = test[\"PassengerId\"]\ntest.drop([\"PassengerId\" , \"Name\"] , axis = 1 , inplace = True)\n# Getting all the categorical columns\n\ncats = df.select_dtypes(include=\"object\").columns\ncats\n# Getting all Integer columns\n\nints = df.select_dtypes(exclude=\"object\").columns\nints\n\"\"\"\n## Filling Missing Values\n\"\"\"\nfor i in df.columns:\n    print(f\"The number of unique values in {i} column is\/are {len(df[i].unique())}\")\n    print(\"\\n\")\n    print(f\"The unique values in {i} column is\/are {df[i].unique()}\")\n    print(\"\\n\")\n    print(f\"The value counts for each value in {i} column is\/are :  \\n{df[i].value_counts()}\")\n    print(\"\\n\\n\")\n    print(\"*\"*100)\n    print(\"\\n\\n\")\n# Drpoing ticket column as it has more unique values\n\ndf.drop([\"Ticket\"] , axis = 1 , inplace = True)\ntest.drop([\"Ticket\"] , axis = 1 , inplace = True)\ndf.isna().sum()\ntest.isna().sum()\nsns.countplot(data = df , x =  \"Embarked\")\n# Filling Embarked missing values with the mode.\n\ndf[\"Embarked\"].fillna(\"S\" , inplace = True)\nsns.countplot(data = df , x =  \"Embarked\")\n# Filling missing intergeral values with the median as mean encounters with outliners\n\ndf[\"Age\"].fillna(df[\"Age\"].median() , inplace = True)\ntest[\"Age\"].fillna(df[\"Age\"].median() , inplace = True)\ntest[\"Fare\"].fillna(df[\"Fare\"].median() , inplace = True)\ndf.isna().sum()\ntest.isna().sum()\ndf.head()\ntest.head()\n\"\"\"\n## Data Visualization\n\"\"\"\nsns.set_style(\"darkgrid\")\nplt.figure(figsize = (10 , 10))\nsns.pairplot(data = df)\n# Defining Group by survival function for better visualization\n\ndef grouping(x , hue = \"Age\"):\n    res = df.groupby(df[x]).mean()\n    res = res.reset_index()\n    print(f\"Grouping by {x} with DataFrame : \\n \")\n    print(res)\n    print(\"\\n\")\n    if x in [\"Pclass\" , \"SibSp\" , \"Parch\"]:\n        plt.figure(figsize = (12 , 5))\n        sns.barplot(data = res , x = x , y = \"Survived\" , hue = hue)\n        plt.show()\n    else:\n        plt.figure(figsize = (12 , 5))\n        sns.histplot(data = res , x = \"Survived\" , y = x , cbar = True , cmap = \"coolwarm\")\n        plt.show()\n    print(\"\\n\\n\")\ngrouping(\"Pclass\" , \"Age\")\ngrouping(\"Age\")\ngrouping(\"SibSp\" , \"Parch\")\ngrouping(\"Parch\" , \"Pclass\")\ngrouping(\"Fare\")\nsns.histplot(data = df , x = \"Age\" , kde = True , hue = \"Sex\" , bins = 20)\nsns.kdeplot(data = df , x = \"Age\" , hue = \"Survived\")\nsns.kdeplot(data = df , x = \"Age\" , hue = \"Pclass\")\nsns.histplot(data = df , x = \"Fare\" , kde = True , bins = 20 , hue = \"Pclass\")\nsns.kdeplot(data = df , x = \"Fare\" , hue = \"Sex\")\nsns.kdeplot(data = df , x = \"Fare\" , hue = \"Survived\")\n\"\"\"\n### Countplots\n\"\"\"\nsns.countplot(data = df , x = \"First\" , hue = \"Survived\")\nsns.countplot(data = df , x = \"Pclass\" , hue = \"Sex\")  # Pclass 3 has more males\nsns.countplot(data = df , x = \"Sex\" , hue = \"Survived\")  # Males has more rate of survival\nplt.figure()\nsns.countplot(data = df , x = \"SibSp\" , hue = \"Sex\")\nplt.figure()\nsns.countplot(data = df , x = \"Parch\" , hue = \"Sex\")\nplt.figure()\nsns.countplot(data = df , x = \"SibSp\" , hue = \"Survived\")\nplt.figure()\nsns.countplot(data = df , x = \"Parch\" , hue = \"Survived\")\nplt.figure()\nsns.countplot(data = df , x = \"SibSp\" , hue = \"Pclass\")\nplt.figure()\nsns.countplot(data = df , x = \"Parch\" , hue = \"Pclass\")\n\"\"\"\n### Boxplots\n\"\"\"\nsns.boxplot(data = df , x = \"First\" , y = \"Age\" , hue = \"Survived\")\nsns.boxplot(data = df , x = \"Pclass\" , y = \"Age\" , hue = \"Survived\")\nsns.boxplot(data = df , x = \"Sex\" , y = \"Age\" , hue = \"Pclass\")\nsns.boxplot(data = df , x = \"Pclass\" , y = \"Fare\" , hue = \"Survived\")\nsns.boxplot(data = df , x = \"Sex\" , y = \"Fare\" , hue = \"Pclass\")\n\"\"\"\n## Data Preprocessing\n\"\"\"\n# Getting rid of skewness in train set\n\ndf[\"Age\"] = np.log(df[\"Age\"] + 1)\ndf[\"Fare\"] = np.log(df[\"Fare\"] + 1)\n# Getting rid of skewness in test set\n\ntest[\"Age\"] = np.log(test[\"Age\"] + 1)\ntest[\"Fare\"] = np.log(test[\"Fare\"] + 1)\n# Creating dummie variables for categorical columns , droping the first_column\n\ndf = pd.get_dummies(df , columns = [\"Sex\" , \"Pclass\" , \"Embarked\" , \"First\"] , prefix = [\"Sex\" , \"Pclass\" , \"Embarked\" , \"First\"] , drop_first = True)\ntest = pd.get_dummies(test , columns = [\"Sex\" , \"Pclass\" , \"Embarked\" , \"First\"] , prefix = [\"Sex\" , \"Pclass\" , \"Embarked\" , \"First\"] , drop_first = True)\ndf.head()\ntest.head()\n\"\"\"\n## Train Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX = df.drop([\"Survived\"] , axis = 1)\ny = df[\"Survived\"]\nX_train , X_test , y_train , y_test = train_test_split(X , y , test_size = 0.2 , random_state = 42)\nlen(X_train) , len(X_test) , len(y_train) , len(y_test)\n\"\"\"\n## Feature Scaling\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler1 = StandardScaler()\nX_train[[\"Age\" , \"Fare\"]] = scaler1.fit_transform(X_train[[\"Age\" , \"Fare\"]])\nX_test[[\"Age\" , \"Fare\"]] = scaler1.transform(X_test[[\"Age\" , \"Fare\"]])\ntest[[\"Age\" , \"Fare\"]] = scaler1.transform(test[[\"Age\" , \"Fare\"]])\nX_train.head()\ntest.head()\n\"\"\"\n## Importing libraries for model fitting\n\"\"\"\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\nfrom sklearn.metrics import confusion_matrix , roc_auc_score , f1_score , accuracy_score , classification_report , roc_curve , auc , plot_roc_curve\nfrom sklearn.model_selection import cross_val_score\nmodels = []\nmodels.append(['XGBClassifier', XGBClassifier(learning_rate = 0.1 , objective = 'binary:logistic' , random_state = 42 , eval_metric='mlogloss')])\nmodels.append(['AdaBoostClassifier', AdaBoostClassifier(random_state = 42)])\nmodels.append(['RandomForest', RandomForestClassifier(random_state = 42)])\nmodels.append(['Logistic Regression', LogisticRegression(random_state = 42)])\nmodels.append(['KNeigbors', KNeighborsClassifier()])\n\"\"\"\n## Model Evaluation\n\"\"\"\ndef metrics(model , X_train , y_train , X_test , y_test , params = False):\n    \n    model[1].fit(X_train , y_train)\n    preds = model[1].predict(X_test)\n    accuracies = cross_val_score(estimator = model[1], X = X_train , y = y_train, cv = 10)\n    cm = confusion_matrix(y_test , preds)\n    cf = classification_report(y_test , preds)\n    roc = roc_auc_score(y_test , model[1].predict_proba(X_test)[: , 1])\n    fpr, tpr, thresholds = roc_curve(y_test, preds)\n    ac = auc(fpr, tpr)\n    f1 = f1_score(y_test , preds)\n    \n    \n    print(\"\\n\")\n    print(model[0])\n    \n    print(\"\\n\")\n    if params:\n        print(f\"Best Parameters are : \\n\" , model[1].best_params_)\n        print(\"\\n\")\n        \n    print(f\"Confusion matrix : \\n\")\n    plt.figure(figsize = (8, 5))\n    sns.heatmap(cm, cmap = 'coolwarm', annot = True, annot_kws = {'fontsize': 20})\n    plt.show()\n    print(\"\\n\")\n    \n    print(f\"Training score : {model[1].score(X_train , y_train):.4f}\")\n    print(\"\\n\") \n    \n    print(f\"Test Score : {model[1].score(X_test , y_test):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"K-fold accuracy : {np.mean(accuracies):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"Standard Deviation of Accuracies in k-fold : {np.std(accuracies):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"ROC AUC Score: {roc:.4f}\")\n    print('\\n')\n    \n    print(f\"F1 Score: {f1:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"AUC : {ac:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"Classification report : \\n\\n{cf}\")\n    print(\"\\n\")\n\n    plt.figure(figsize = (8, 5))\n    plot_roc_curve(model[1], X_test, y_test , color = '#FF4500')\n    plt.plot([0, 1], [0, 1], linestyle = '--', color = '#7CFC00')\n    plt.show()\n    print(\"\\n\")\n    print(\"*\"*100)\n    \n    print(\"\\n\\n\")\n    \n    sam = []\n    sam.append(model[0])\n    sam.append(model[1].score(X_train , y_train))\n    sam.append(model[1].score(X_test , y_test))\n    sam.append(np.mean(accuracies))\n    sam.append(np.std(accuracies))\n    sam.append(roc)\n    sam.append(f1)\n    sam.append(ac)\n    \n    return sam\n    \n    \npre_final = []\nfor i in models:\n    sam = metrics(i , X_train , y_train , X_test , y_test)\n    pre_final.append(sam)\npre_final\n\"\"\"\n## Model Evaluation Visualization\n\"\"\"\nme = pd.DataFrame(pre_final , columns = [\"Model\" , \"Train Score\" , \"Test Score\" , \"K-fold Accuracy\" , \"K-fold Std\" , \"ROC_AUC\" , \"F1 Score\" , \"AUC Score\"])\n\nme.sort_values(by = [\"K-fold Accuracy\" , \"F1 Score\" , \"ROC_AUC\" , \"AUC Score\" , \"Train Score\" , \"Test Score\"] , inplace = True , ascending = False)\nme = me.reset_index(drop = True)\nme\nplt.figure(figsize = (10 , 5))\nsns.barplot(y = \"Model\" , x = \"ROC_AUC\" , data = me)\nplt.title(\"Model Comparision based on ROC_AUC\");\nplt.figure(figsize = (10 , 5))\nsns.barplot(y = \"Model\" , x = \"F1 Score\" , data = me)\nplt.title(\"Model Comparision based on F1 Score\");\nplt.figure(figsize = (10 , 5))\nsns.barplot(y = \"Model\" , x = \"AUC Score\" , data = me)\nplt.title(\"Model Comparision based on AUC Score\");\n\"\"\"\n## Model Evaluation with Grid SearchCV\n\"\"\"\n\"\"\"\nNot fitting XGB , Ada Boost as it already comes with best parameters\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\n\n\ngrid_xgb = {\"n_estimators\" : [100 , 200 , 300]}\n\n\ngrid_ada = {\"n_estimators\" : [50 , 100 , 200]}\n\n\ngrid_random = {\"n_estimators\" : [150 , 200 , 250],\n              \"bootstrap\" : [True , False] , \n              \"max_features\" : ['auto', 'sqrt'] , \n              \"min_samples_leaf\" : [2, 4] , \n              \"class_weight\" : [\"balanced\", \"balanced_subsample\"]}\n\n\ngrid_linear = {\"max_iter\" : [100 , 150] , \n              \"solver\" : [\"liblinear\"] , \n              \"multi_class\" : [\"ovr\"]}\n\n\ngrid_neighbor = {\"n_neighbors\" : [5 , 7 , 10] , \n                \"algorithm\" : [\"auto\", \"ball_tree\", \"kd_tree\", \"brute\"]} \n\nxgb = metrics(['XGBClassifier', GridSearchCV(XGBClassifier(learning_rate = 0.1, objective = 'binary:logistic' , random_state = 42 , eval_metric='mlogloss') , param_grid = grid_xgb, cv = 5, verbose = 0)] ,  X_train , y_train , X_test , y_test , params = True )\nada = metrics(['AdaBoostClassifier', GridSearchCV(AdaBoostClassifier(random_state = 42) , param_grid = grid_ada , cv = 5 , verbose = 0 )] , X_train , y_train , X_test , y_test , params = True)\nrandom = metrics(['RandomForest', GridSearchCV(RandomForestClassifier(random_state = 42) , param_grid = grid_random, cv = 5, verbose = 0 , scoring = \"f1\")] ,  X_train , y_train , X_test , y_test , params = True )\nlinear = metrics(['Logistic Regression', GridSearchCV(LogisticRegression(random_state = 42) , param_grid = grid_linear, cv = 5, verbose = 0 )] ,  X_train , y_train , X_test , y_test , params = True )\nknn = metrics(['KNeigbors', GridSearchCV(KNeighborsClassifier() , param_grid = grid_neighbor, cv = 10, verbose = 0)] , X_train , y_train , X_test , y_test , params = True)\nfinal = [xgb , ada , random , linear , knn]\nfinal\n\"\"\"\n## GridsearchCV Model Visualization\n\"\"\"\nme # Without Gridsearchcv\n# With gridsearch CV\n\nmef = pd.DataFrame(final , columns = [\"Model\" , \"Train Score\" , \"Test Score\" , \"K-fold Accuracy\" , \"K-fold Std\" , \"ROC_AUC\" , \"F1 Score\" , \"AUC Score\"])\n\nmef.sort_values(by = [\"K-fold Accuracy\" , \"F1 Score\" , \"ROC_AUC\" , \"AUC Score\" , \"Train Score\" , \"Test Score\"] , inplace = True , ascending = False)\nmef = mef.reset_index(drop = True)\nmef\ndef feature_importance(model , X_train , y_train):\n    model[1].fit(X_train , y_train)\n    features = model[1].feature_importances_\n    print(model[0])\n    print(\"\\n\")\n    print(f\"Feature importance list : \\n\" , features)\n    print(\"\\n\")\n    plt.figure(figsize = (15 , 8))\n    sns.barplot(X_train.columns.tolist() , features)\n    plt.show()\n    print(\"\\n\")\n    print(\"*\"*100)\n    print(\"\\n\")\ndef linear_coeffs(model , X_train , y_train):\n    model[1].fit(X_train , y_train)\n    features = model[1].coef_\n    print(model[0])\n    print(\"\\n\")\n    print(f\"Feature importance list : \\n\" , features)\n    print(\"\\n\")\n    plt.figure(figsize = (15 , 8))\n    sns.barplot(X_train.columns.tolist() , features.ravel())\n    plt.show()\n    print(\"\\n\")\n    print(\"*\"*100)\n    print(\"\\n\")\nfeature_importance([\"XGBClassifier\" , XGBClassifier(learning_rate = 0.1, objective = 'binary:logistic' , random_state = 42 , eval_metric='mlogloss')] , X_train , y_train)\nfeature_importance([\"Randomforest Classifier\" , RandomForestClassifier(random_state = 42 , bootstrap = False, class_weight = 'balanced', max_features = 'auto', min_samples_leaf = 4 , n_estimators = 200 )] , X_train , y_train)\nlinear_coeffs([\"Logestic Regressor\" , LogisticRegression(max_iter = 100,  multi_class = 'ovr',  random_state = 42,  solver = 'liblinear')] , X_train , y_train)\n\"\"\"\n## Evaluation on the Test Dataset\n\"\"\"\ntest\ntest.info()\ntest.isna().sum()\nclf_linear = LogisticRegression(random_state = 42)\nclf_linear.fit(X_train , y_train)\nlinear_preds = clf_linear.predict(test)\nlinear_preds\ndata_linear = {\"PassengerId\" : ids , \n       \"Survived\" : linear_preds}\nfinal_linear = pd.DataFrame(data_linear, columns = [\"PassengerId\" , \"Survived\"])\nfinal_linear.head(10)\nfinal_linear[\"Survived\"].value_counts()\nclf_xgb = XGBClassifier(learning_rate = 0.1, objective = 'binary:logistic' , random_state = 42 , eval_metric='mlogloss')\nclf_xgb.fit(X_train , y_train)\nxgb_preds = clf_xgb.predict(test)\nxgb_preds\ndata_xgb = {\"PassengerId\" : ids , \n       \"Survived\" : xgb_preds}\n\nfinal_xgb = pd.DataFrame(data_xgb, columns = [\"PassengerId\" , \"Survived\"])\nfinal_xgb.head(10)\nfinal_xgb[\"Survived\"].value_counts()\nfinal_xgb.to_csv(\"Titanic_linear_1.csv\" , index = False)","meta":"{'source': 'AI4Code', 'id': 'b6be07ae120b24'}"}
{"id":"64859","text":"# 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)\nimport matplotlib.pyplot as plt\n%matplotlib inline\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\n\"\"\"\n# **Titanic Data**\n\"\"\"\ntrain_data = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntest_data = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n\"\"\"\n# **Features' Selection and Engineering**\n\"\"\"\n# Features Selection\nfeatures = ['Pclass','Sex','SibSp','Parch','Fare','Age']\n\n# from sklearn.preprocessing import StandardScaler\n# sc = StandardScaler()\n# sc.fit_transform(features[4,5])\n# x_test = sc.fit_transform()\n\nx = pd.get_dummies(train_data[features])\nx_test = pd.get_dummies(test_data[features])\ny = train_data[\"Survived\"]\n\n# handlin NaN in Fare and Age\nx['Fare'].fillna(x['Fare'].mode()[0], inplace=True)\nx_test['Fare'].fillna(x_test['Fare'].mode()[0], inplace=True)\n\n# Handling NaN in Age\nx['Age'].fillna(x['Age'].mode()[0], inplace=True)\nx_test['Age'].fillna(x_test['Age'].mode()[0], inplace=True)\n\n# Algorithm Tuning\nfrom scipy.stats import uniform as sp_rand\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparam_grid = {'alpha': sp_rand()}\nmodel = Ridge()\nrsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)\nrsearch.fit(x,y)\nprint(rsearch)\n\"\"\"\n# Ensemble Model\n\"\"\"\n# the Model)\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier(n_estimators=10,criterion='entropy',n_jobs=-1, random_state=42)\nrfc.fit(x,y)\ny_pred = rfc.predict(x_test)\ny_pred\nplt.hist(y_pred)\n# The accuracy score as shown by from kaggle report is 0.77511\n\"\"\"\n# Logistic Regression Model\n\"\"\"\n# # plotting a contour map with logreg using the Visualising the Training set results\n# from matplotlib.colors import ListedColormap\n# X_set, y_set = x, y\n# X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step =\n# 0.01),\n# np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\n# plt.contourf(X1, X2, logreg.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n# alpha = 0.75, cmap = ListedColormap(('red', 'green')))\n# plt.xlim(X1.min(), X1.max())\n# plt.ylim(X2.min(), X2.max())\n# for i, j in enumerate(np.unique(y_set)):\n#     plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n# c = ListedColormap(('red', 'green'))(i), label = j)\n# plt.title('Logistic Regression (Training set)')\n# plt.xlabel('Pclass and Parch')\n# plt.ylabel('Survived')\n# plt.legend()\n\n# to save the output: i.e the prediction\noutput = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': y_pred})\noutput.to_csv('submission3.csv', index=False)\nprint(\"Your submission was successfully saved!\")\n# women = train_data.loc[train_data.Sex == 'female'][\"Survived\"]\n# rate_women = sum(women)\/len(women)\n\n# print(\"% of women who survived:\", rate_women)","meta":"{'source': 'AI4Code', 'id': '77a0d31e75dd56'}"}
{"id":"19411","text":"\"\"\"\n### [Context of this work : D\u00e9fi IA](https:\/\/www.kaggle.com\/c\/defi-ia-insa-toulouse\/leaderboard)\n\nThis edition of the D\u00e9fi IA pertains to NLP. The task is straightforward: assign the correct **job category** to a **job description**.\n\n### Desciption\n\nThe approach used here to make the model **fair** is to use as many descriptions of jobs of both sexes.\nThis is similar to when you have an unbalanced dataset, and you decide to reduce the number of samples in each class to the minimum sample.\n\n### Results of this notebook\n\n|Metric       |precision       |recall       |f1-score       |support       |\n|:-:    |:-:    |:-:    |:-:    |--:    |\n|accuracy       |       |       |0.80       |2423       |\n|macro avg       |0.81       |0.80       |0.80       |2423       |\n|weighted avg       |0.81       |0.80       |0.80       |2423       |\n|fairness predict       |       |       |       |2.817007881684417       |\n|fairness valid       |       |       |       |2.8221477674508764       |\n\n\"\"\"\n\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\n\n## History\n\n2018 was a breakthrough year in NLP. Transfer learning, particularly models like Allen AI's ELMO, OpenAI's Open-GPT, and Google's BERT allowed researchers to smash multiple benchmarks with minimal task-specific fine-tuning and provided the rest of the NLP community with pretrained models that could easily (with less data and less compute time) be fine-tuned and implemented to produce state of the art results. Unfortunately, for many starting out in NLP and even for some experienced practicioners, the theory and practical application of these powerful models is still not well understood.\n\n\"\"\"\n\"\"\"\n## What is Bert ?\n\n**BERT** (Bidirectional Encoder Representations from Transformers), released in late 2018, is the model we will use in this notebook to provide readers with a better understanding of and practical guidance for using transfer learning models in NLP. \n\n**BERT** is a method of pretraining language representations that was used to create models that NLP practicioners can then download and use for free. You can either use these models to extract high quality language features from your text data, or you can fine-tune these models on a specific task (classification, entity recognition, question answering, etc.) with your own data to produce state of the art predictions.\n\nThis notebook will explain how you can modify and fine-tune BERT to create a powerful NLP model that quickly gives you state of the art results. \n\n\"\"\"\n\"\"\"\n\n## Advantages of Fine-Tuning\n\n\"\"\"\n\"\"\"\n\nI will use Bert to train a text classifier. Specifically, we will take the pre-trained Bert model, add an untrained layer of neurons on the end, and train the new model for our classification task. Why do this rather than train a train a specific deep learning model (a CNN, BiLSTM, etc.) that is well suited for the specific NLP task you need? \n\n1. **Quicker Development**\n\n    * First, the pre-trained Bert model weights already encode a lot of information about our language. As a result, it takes much less time to train our fine-tuned model - it is as if we have already trained the bottom layers of our network extensively and only need to gently tune them while using their output as features for our classification task. In fact, the authors recommend only 2-4 epochs of training for fine-tuning Bert on a specific NLP task (compared to the hundreds of GPU hours needed to train the original Bert model or a LSTM from scratch!). \n\n2. **Less Data**\n\n    * In addition and perhaps just as important, because of the pre-trained weights this method allows us to fine-tune our task on a much smaller dataset than would be required in a model that is built from scratch. A major drawback of NLP models built from scratch is that we often need a prohibitively large dataset in order to train our network to reasonable accuracy, meaning a lot of time and energy had to be put into dataset creation. By fine-tuning Bert, we are now able to get away with training a model to good performance on a much smaller amount of training data.\n\n3. **Better Results**\n\n    * Finally, this simple fine-tuning procedure (typically adding one fully-connected layer on top of Bert and training for a few epochs) was shown to achieve state of the art results with minimal task-specific adjustments for a wide variety of tasks: classification, language inference, semantic similarity, question answering, etc. Rather than implementing custom and sometimes-obscure architetures shown to work well on a specific task, simply fine-tuning BERT is shown to be a better (or at least equal) alternative.\n\n\"\"\"\n\"\"\"\n\n### A Shift in NLP\n\nThis shift to transfer learning parallels the same shift that took place in computer vision a few years ago. \n\nCreating a good deep learning network for computer vision tasks can take millions of parameters and be very expensive to train. Researchers discovered that deep networks learn hierarchical feature representations (simple features like edges at the lowest layers with gradually more complex features at higher layers). Rather than training a new network from scratch each time, the lower layers of a trained network with generalized image features could be copied and transfered for use in another network with a different task. It soon became common practice to download a pre-trained deep network and quickly retrain it for the new task or add additional layers on top - vastly preferable to the expensive process of training a network from scratch. For many, the introduction of deep pre-trained language models in 2018 (ELMO, BERT, ULMFIT, Open-GPT, etc.) signals the same shift to transfer learning in NLP that computer vision saw.\n\nLet's get started!\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('..\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport os\nimport pickle\nfrom matplotlib import pyplot as plt\n\"\"\"\nUse of GPU\n\"\"\"\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\";\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\";\n\"\"\"\n### Import ktrain\n\n**[Ktrain](https:\/\/github.com\/amaiya\/ktrain)** is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. \n\nInspired by ML framework extensions like fastai and ludwig, ktrain is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners. With only a few lines of code, ktrain allows you to easily and quickly.\n\"\"\"\n!pip -q install ktrain\nimport ktrain\nfrom ktrain import text\n\"\"\"\n# 2. Loading Defi IA Dataset\n\n\"\"\"\n\"\"\"\nWe'll use [Defi IA dataset for job classification](https:\/\/www.kaggle.com\/c\/defi-ia-insa-toulouse\/data) dataset for single sentence classification. It's a set of sentences labeled as 28 jobs classes. The data has been retrieved from [CommonCrawl](https:\/\/www.wikiwand.com\/en\/Common_Crawl). The latter has been famously used to train OpenAI's GPT-3 model. The data is therefore representative of what can be found on the English speaking part of the Internet, and thus contains a certain amount of bias. One of the goals of this competition is to design a solution that is both accurate as well as fair, as explained in the Evaluation section.\n\n\"\"\"\nDATA_PATH = \"..\/input\/defi-ia-insa-toulouse\"\ntrain_df = pd.read_json(DATA_PATH+\"\/train.json\").set_index('Id')\ntest_df = pd.read_json(DATA_PATH+\"\/test.json\").set_index('Id')\ntrain_label = pd.read_csv(DATA_PATH+\"\/train_label.csv\").set_index('Id')\ncategories_string = pd.read_csv(DATA_PATH+\"\/categories_string.csv\")\n# template_submissions = pd.read_csv(DATA_PATH+\"\/template_submissions.csv\").set_index('Id')\nnames = categories_string['0'].to_dict()\njobs = train_label['Category']\njobs = jobs.map(names)\njobs = jobs.rename('job')\ngenders = train_df[\"gender\"]\npeople = pd.concat((jobs, genders), axis='columns')\npeople.head()\n\"\"\"\n### Split data\nSplit data into train and validation data\n\"\"\"\ntrain = people[[\"gender\", \"job\"]].reset_index(   # need to keep the index as a column\n        ).groupby([\"gender\", \"job\"]                  # split by \"group\"\n        ).apply(lambda x: x.sample(500, replace=True) # in each group, do the random split\n        ).reset_index(drop=True              # index now is group id - reset it\n        ).set_index(\"Id\")                 # reset the original index\nval = people.drop(train.index)[[\"gender\", \"job\"]].reset_index(   # need to keep the index as a column\n        ).groupby([\"gender\", \"job\"]                  # split by \"group\"\n        ).apply(lambda x: x.sample(50, replace=True) # in each group, do the random split\n        ).reset_index(drop=True              # index now is group id - reset it\n        ).set_index(\"Id\")                 # reset the original index\n\ntrain = train.sample(frac=1.)\ntrain.head()\n\"\"\"\n### Remove duplicated\n\n\"\"\"\nprint(train.shape, val.shape)\ntrain = train[~train.index.duplicated(keep='first')]\nval = val[~val.index.duplicated(keep='first')]\nprint(train.shape, val.shape)\ntrain_df.head()\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\ntrain[\"text\"] = train_df.loc[train.index][\"description\"].values\nval[\"text\"] = train_df.loc[val.index][\"description\"].values\ntrain.head()\n\"\"\"\n### Load pre-trained model\n\nWe will use **distilbert-base-uncased**\n\"\"\"\nmodel_name = \"distilbert-base-uncased\"\nt = text.Transformer(model_name, maxlen=125)\ntrn = t.preprocess_train(train[\"text\"].values, train[\"job\"].values)\nvl = t.preprocess_test(val[\"text\"].values, val[\"job\"].values)\nimport gc\n\ngc.collect()\n\"\"\"\n### Model and Learner\n\"\"\"\nmodel = t.get_classifier()\nlearner = ktrain.get_learner(model, train_data=trn, val_data=vl, batch_size=64)\n\"\"\"\n### Model summary\n\"\"\"\nmodel.summary()\n\"\"\"\n### Hyperparmeter learning rate\n\nSimulating training for different learning rates... this may take a few moments...\n\"\"\"\nlearner.lr_find(max_epochs=3, suggest=True, show_plot=True)\n\"\"\"\n### Suggestion\n\nSuggest learning\n\"\"\"\nlearner.lr_plot(suggest=True)\n\"\"\"\n### Fit one cylcle\n\nFit one cycle on 5 epochs\n\"\"\"\nlearner.fit_onecycle(5e-5, 5)\n\"\"\"\n### Visualize fit results\n\"\"\"\nlearner.history.history.keys()\nlearner.plot()\nplt.plot(learner.history.history['accuracy'])\nplt.plot(learner.history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\n\"\"\"\n## Model Performance\n\"\"\"\ncorr = learner.validate(class_names=t.get_classes())\n\"\"\"\n### View model top losses\n\"\"\"\nlearner.view_top_losses(n=3, preproc=t)\nprint(val.loc[val.index[1223]][\"text\"])\nprint(val.loc[val.index[1431]][\"text\"])\npredictor = ktrain.get_predictor(learner.model, preproc=t)\npredictor.predict(\"She also teaches an after-hours Krav Maga class for interested Freelancers and she's loosely affiliated with the Russian mob. With her livelihood up in smoke, \\\n                  she wants answers. The Russians want answers, and it feels like not everyone is being completely honest.\")\npd.DataFrame(predictor.predict_proba('After working for three months in a Google lab in the USA. He is now a cloud computing engineer at IBM.').reshape(1, -1),\n            columns=np.array(predictor.get_classes()))\npredictor.save(\".\/output\/fairness\")\nload_predictor = ktrain.load_predictor(\".\/output\/fairness\")\n\"\"\"\n### reload the predictor\nreloaded_predictor = ktrain.load_predictor('.\/output\/predictor_ktrain')\n\"\"\"\n!pip install -q git+https:\/\/github.com\/amaiya\/eli5@tfkeras_0_10_1\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\npredictor.explain(\"She also teaches an after-hours Krav Maga class for interested Freelancers and she's loosely affiliated with the Russian mob. With her livelihood up in smoke, she wants answers. \\\nThe Russians want answers, and it feels like not everyone is being completely honest.\")\npredictor.explain(\"He was also the editor of the Sunday Datebook for 14 years during a 34-year newspaper career at the San Francisco Chronicle.\\\nHe has worked on \u201cThe Voice\u201d at the Marsh Theater with David Ford, Ann Randolph and Mark Kenward for the last two years. \\\n                  The full piece will be present at the Marsh San Francisco on May 10.\")\nprops = predictor.predict_proba(val[\"text\"].values)\nprops.shape\ndef get_nd(arr):\n    return np.array([arr==i for i in np.array(predictor.get_classes())])        \ndef reverse_job(df):\n    return df.replace({j:i for i,j in names.items()})\npreds = predictor.predict(val[\"text\"].values)\npreds[:5]\nval[\"job_pred\"] = preds\nval.sample(20).head(10)\ncounts = val[['job_pred', 'gender']].groupby(['job_pred', 'gender']).size().unstack('gender')\ncounts['disparate_impact'] = counts[['M', 'F']].max(axis='columns') \/ counts[['M', 'F']].min(axis='columns')\ncounts\ncounts[\"disparate_impact\"].mean()\ncounts = val[['job', 'gender']].groupby(['job', 'gender']).size().unstack('gender')\ncounts['disparate_impact'] = counts[['M', 'F']].max(axis='columns') \/ counts[['M', 'F']].min(axis='columns')\ncounts[\"disparate_impact\"].mean()","meta":"{'source': 'AI4Code', 'id': '2383c8fda7cfba'}"}
{"id":"85953","text":"\"\"\"\n## Import Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\"\"\"\n## Import Data\nThe dataset contains all available data for more than 800,000 consumer loans issued from 2007 to 2015 by Lending Club: a large US peer-to-peer lending company. There are several different versions of this dataset. We have used a version available on kaggle.com. You can find it here: https:\/\/www.kaggle.com\/wendykan\/lending-club-loan-data\/version\/1\nWe divided the data into two periods because we assume that some data are available at the moment when we need to build Expected Loss models, and some data comes from applications after. Later, we investigate whether the applications we have after we built the Probability of Default (PD) model have similar characteristics with the applications we used to build the PD model.\n\"\"\"\nloan_data_backup = pd.read_csv('\/kaggle\/input\/loan-data-2007-2014\/loan_data_2007_2014\/loan_data_2007_2014.csv')\nloan_data = loan_data_backup.copy()\n\"\"\"\n## Explore Data\n\"\"\"\nloan_data.head()\npd.options.display.max_columns = None\npd.options.display.max_rows = None\n# Sets the pandas dataframe options to display all columns\/ rows.\nloan_data.head()\nloan_data.columns.values\n# Displays all column names.\nloan_data.info()\n# Displays column names, complete (non-missing) cases per column, and datatype per column.\n\"\"\"\n## Preprocessing - I\n\"\"\"\n\"\"\"\n## Preprocessing few continuous variables\n\"\"\"\nloan_data['emp_length'].unique()\nloan_data['emp_length_int'] = loan_data['emp_length'].str.replace('\\+ years', '')\nloan_data['emp_length_int'] = loan_data['emp_length_int'].str.replace('< 1 year', str(0))\nloan_data['emp_length_int'] = loan_data['emp_length_int'].str.replace('n\/a', str(0))\nloan_data['emp_length_int'] = loan_data['emp_length_int'].str.replace('years', '')\nloan_data['emp_length_int'] = loan_data['emp_length_int'].str.replace('year', '')\ntype(loan_data['emp_length_int'][0])\nloan_data['emp_length_int'] = pd.to_numeric(loan_data['emp_length_int'])\ntype(loan_data['emp_length_int'][0])\nloan_data['term'].unique()\nloan_data['term_int'] = loan_data['term'].str.replace('\\+ months', '')\nloan_data['term_int'] = loan_data['term'].str.replace('months', '')\ntype(loan_data['term_int'][0])\nloan_data['term_int'] = pd.to_numeric(loan_data['term_int'])\nloan_data['earliest_cr_line'].head()\nloan_data['earliest_cr_line_date'] = pd.to_datetime(loan_data['earliest_cr_line'], format = '%b-%y')\nloan_data['earliest_cr_line_date'] = loan_data['earliest_cr_line_date'].mask(loan_data['earliest_cr_line_date'].dt.year > 2017, \n                                         loan_data['earliest_cr_line_date'] - pd.offsets.DateOffset(years=100))\ntype(loan_data['earliest_cr_line_date'][0])\nloan_data['mths_since_earliest_cr_line'] = round((pd.to_datetime('2017-12-01') - loan_data['earliest_cr_line_date'])\/np.timedelta64(1, 'M'))\nloan_data['mths_since_earliest_cr_line'].describe()\nloan_data.loc[:, ['earliest_cr_line', 'earliest_cr_line_date', 'mths_since_earliest_cr_line']][loan_data['mths_since_earliest_cr_line'] < 0]\nloan_data['issue_d'].head()\nloan_data['issue_date'] = pd.to_datetime(loan_data['issue_d'], format = '%b-%y')\n#loan_data['issue_date'] = loan_data['issue_date'].mask(loan_data['issue_date'].dt.year > 2017, loan_data['issue_date'] - pd.offsets.DateOffset(years=100))\nloan_data['issue_date'].head()\nloan_data['mths_since_issue_d'] = round(pd.to_numeric((pd.to_datetime('2017-12-01') - loan_data['issue_date']) \/ np.timedelta64(1, 'M')))\nloan_data['mths_since_issue_d'].describe()\n\"\"\"\n## Creating Dummy variables\n\"\"\"\nloan_data_dummies = [pd.get_dummies(loan_data['grade'], prefix= 'grade', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['sub_grade'], prefix= 'sub_grade', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['home_ownership'], prefix= 'home_ownership', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['verification_status'], prefix= 'verification_status', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['loan_status'], prefix= 'loan_status', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['purpose'], prefix= 'purpose', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['addr_state'], prefix= 'addr_state', prefix_sep = \":\"),\n                     pd.get_dummies(loan_data['initial_list_status'], prefix= 'initial_list_status', prefix_sep = \":\")]\nloan_data_dummies = pd.concat(loan_data_dummies, axis = 1)\ntype(loan_data_dummies)\nloan_data = pd.concat([loan_data, loan_data_dummies], axis = 1)\nloan_data.columns\n\"\"\"\n## Checking for missing values\n\"\"\"\nloan_data.isnull().sum()\nloan_data['total_rev_hi_lim'].fillna(loan_data['funded_amnt'], inplace = True)\nloan_data['annual_inc'].fillna(loan_data['annual_inc'].mean(), inplace=True)\nloan_data['mths_since_earliest_cr_line'].fillna(0, inplace = True) \nloan_data['acc_now_delinq'].fillna(0, inplace = True) \nloan_data['total_acc'].fillna(0, inplace = True) \nloan_data['pub_rec'].fillna(0, inplace = True) \nloan_data['open_acc'].fillna(0, inplace = True) \nloan_data['inq_last_6mths'].fillna(0, inplace = True) \nloan_data['delinq_2yrs'].fillna(0, inplace = True) \nloan_data['emp_length_int'].fillna(0, inplace = True) \n\"\"\"\n## Defining Dependent variable\n\"\"\"\n\"\"\"\n### Good\/bad(default) definition, Default and non-default accounts\n\"\"\"\nloan_data['loan_status'].unique()\nloan_data['loan_status'].value_counts()\/loan_data['loan_status'].count()\nloan_data['good_bad'] = np.where(loan_data['loan_status'].isin(['Charged Off', 'Default',\n                                                                   'Does not meet the credit policy. Status:Charged Off',\n                                                                   'Late (31-120 days)']), 0, 1)\nloan_data['good_bad'].value_counts()\n\"\"\"\n## Train\/Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nloan_data_inputs_train, loan_data_inputs_test, loan_data_targets_train, loan_data_targets_test = train_test_split(loan_data.drop('good_bad', axis = 1), loan_data['good_bad'], test_size = 0.2, random_state = 42)\n\"\"\"\n## Weight of Evidence Calculation\n\"\"\"\n\"\"\"\nSince data preparation binning will be same for both training and test data, combining both dataframes to a list so that changes can be applied uniformly.\n\"\"\"\ndata_cleaner = [loan_data_inputs_train, loan_data_inputs_test]\n\"\"\"\n### Weight of Evidence Calculation for 1 variable\n\"\"\"\nloan_data_inputs_train['grade'].unique()\ndf1 = pd.concat([loan_data_inputs_train['grade'], loan_data_targets_train], axis = 1)\ndf1.head()\ndf1.groupby(df1.columns.values[0], as_index = False)[df1.columns.values[1]].count()\ndf1.groupby(df1.columns.values[0], as_index = False)[df1.columns.values[1]].mean()\ndf1 = pd.concat([df1.groupby(df1.columns.values[0], as_index = False)[df1.columns.values[1]].count(),\n                 df1.groupby(df1.columns.values[0], as_index = False)[df1.columns.values[1]].mean()], axis = 1)\ndf1.head()\ndf1 = df1.iloc[: , [0, 1, 3]]\ndf1.columns = [df1.columns.values[0], 'n_obs', 'prop_good']\ndf1['prop_n_obs'] = df1['n_obs'] \/ df1['n_obs'].sum()\ndf1['n_good'] = df1['prop_good'] * df1['n_obs']\ndf1['n_bad'] = (1 - df1['prop_good']) * df1['n_obs']\ndf1.head()\ndf1['prop_n_good'] = df1['n_good'] \/ df1['n_good'].sum()\ndf1['prop_n_bad'] = df1['n_bad'] \/ df1['n_bad'].sum()\ndf1.head()\ndf1['WoE'] = np.log(df1['prop_n_good'] \/ df1['prop_n_bad'])\ndf1.head()\ndf1 = df1.sort_values(['WoE'])\ndf1 = df1.reset_index(drop = True)\ndf1.head()\n\"\"\"\nCalculating the diff in proportion of good\/bad as we move across categories\n\"\"\"\ndf1['diff_prop_good'] = df1['prop_good'].diff().abs()\ndf1['diff_WoE'] = df1['WoE'].diff().abs()\ndf1\ndf1['IV'] = (df1['prop_n_good'] - df1['prop_n_bad']) * df1['WoE']\ndf1['IV'] = df1['IV'].sum()\ndf1\n\"\"\"\n### Automating WOE calculation\n\"\"\"\ndef woe_discrete(df, discrete_variable_name, good_bad_variable_df):\n    df = pd.concat([df[discrete_variable_name], good_bad_variable_df], axis = 1)\n    df = pd.concat([df.groupby(df.columns.values[0], as_index = False)[df.columns.values[1]].count(),\n                    df.groupby(df.columns.values[0], as_index = False)[df.columns.values[1]].mean()], axis = 1)\n    df = df.iloc[: , [0, 1, 3]]\n    df.columns = [df.columns.values[0], 'n_obs', 'prop_good']\n    df['prop_n_obs'] = df['n_obs'] \/ df['n_obs'].sum()\n    df['n_good'] = df['prop_good'] * df['n_obs']\n    df['n_bad'] = (1 - df['prop_good']) * df['n_obs']\n    df['prop_n_good'] = df['n_good'] \/ df['n_good'].sum()\n    df['prop_n_bad'] = df['n_bad'] \/ df['n_bad'].sum()\n    df['WoE'] = np.log(df['prop_n_good'] \/ df['prop_n_bad'])\n    df = df.sort_values(['WoE'])\n    df = df.reset_index(drop = True)\n    df['diff_prop_good'] = df['prop_good'].diff().abs()\n    df['diff_WoE'] = df['WoE'].diff().abs()\n    df['IV'] = (df['prop_n_good'] - df['prop_n_bad']) * df['WoE']\n    df['IV'] = df['IV'].sum()\n    return(df)\ndf_temp = woe_discrete(loan_data_inputs_train, 'grade', loan_data_targets_train)\ndf_temp\n\"\"\"\n### Preprocessing discrete variables: Visualising results\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\ndef plot_by_woe(df_WOE, rotation_of_xaxis_labels = 90):\n    # reading the first column from the WOE dataset, and coercing to string\n    x = np.array(df_WOE.iloc[:, 0].apply(str))\n    y = df_WOE['WoE']\n    plt.figure(figsize = (18, 6))\n    plt.plot(x, y, marker = 'o', linestyle = '--', color = 'k')\n    plt.xlabel(df_WOE.columns[0])\n    plt.ylabel('Weight of Evidence')\n    plt.title('Weight of Evidence by' + df_WOE.columns[0])\n    plt.xticks(rotation = rotation_of_xaxis_labels)\nplot_by_woe(df_temp)\n\"\"\"\n### Preprocessing Discrete Variables: Creating dummy variables, Part 1\n\"\"\"\ndf_temp = woe_discrete(loan_data_inputs_train, 'home_ownership', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nOther, none and any categories represent very few observations. We combine them to not lose the info they bring. Combining underrepresented categories. They are combined w\/ the riskiest category w\/ enough number of observations. In this case: rent\n\"\"\"\nfor dataset in data_cleaner:  \n    dataset['home_ownership:RENT_OTHER_ANY_NONE'] = sum([dataset['home_ownership:RENT'], \n                                                            dataset['home_ownership:OTHER'], \n                                                            dataset['home_ownership:ANY'],\n                                                            dataset['home_ownership:NONE']])\n\"\"\"\n#### Address State\n\"\"\"\nloan_data_inputs_train['addr_state'].unique()\ndf_temp = woe_discrete(loan_data_inputs_train, 'addr_state', loan_data_targets_train )\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nThere are fewer than 50 states in the results. There are no borrowers from 1 of the states. (North Dakota)\n\"\"\"\nfor dataset in data_cleaner: \n    if ['addr_state:ND'] in dataset.columns.values:\n        pass\n    else:\n        dataset['addr_state:ND'] = 0\n\"\"\"\nWeight of evidence is not calculated for 2 states. There are no bads. The first two states have very few observations. These can be clubbed w\/ the next riskiest category\n\"\"\"\nplot_by_woe(df_temp.iloc[2: -2, :])\n\"\"\"\nNevada has a lower WOE than the states after. It could be clubbed with the low proportion states we had excluded. The state with no records (North Dakota) can be included here. This would be a conservative approach to take. For states with unknown values, assignin them the worst WOE value. The first dummy variable will include NE, IA, NV, FL, HI and AL. The states at the end will include WV, NH, WY, DC, ME and ID. Plotting the remaining states: \n\n\"\"\"\nplot_by_woe(df_temp.iloc[6: -6, :])\n\"\"\"\nNY and CA have the highest number of observations. Most borrowers. These can be in a separate category dummy of their own. \nThe other states can be in one category\/ grouped together. But leaving out NY and CA because these need to be in a separate category. \n\nNM and VA could be combined\nOK, TN, MO, LA, MD, NC could be combined to one. \nThese can't be combined together because they are separated by NY. (10% of observations come from NY)\n\nUT, KY, AZ and NJ can be comibined into one category. They have similar WOE and neither has very high number of values. \n\nAR, MI, PA, OH and MN have similar WOE. RI, MA, DE, SD and IN belong to one category. \nGA, WA and OR belong together. WI and MT need to be combined.\n\nTX, IL and CT. have similar WOE but Texas has too many values. It can stay a separate category. \nIL and CT can be combined\n\nKS, SC, CO, VT, AK and MS combined into one category\nThey have very high WOE but too few observations. This makes WoE less reliable. They can be combined together.\n\"\"\"\nfor dataset in data_cleaner: \n    dataset['addr_state:NE_IA_NV_FL_HI_AL'] = sum([dataset['addr_state:NE'], dataset['addr_state:IA'],\n                                                     dataset['addr_state:NV'], dataset['addr_state:FL'], \n                                                     dataset['addr_state:HI'], dataset['addr_state:AL']])\n    \n    dataset['addr_state:NM_VA'] = sum([dataset['addr_state:NM'], dataset['addr_state:VA']])\n    \n    dataset['addr_state:OK_TN_MO_LA_MD_NC'] = sum([dataset['addr_state:OK'], dataset['addr_state:TN'],\n                                                     dataset['addr_state:MO'], dataset['addr_state:LA'], \n                                                     dataset['addr_state:MD'], dataset['addr_state:NC']])\n    \n    dataset['addr_state:UT_KY_AZ_NJ'] = sum([dataset['addr_state:UT'], dataset['addr_state:KY'],\n                                                     dataset['addr_state:AZ'], dataset['addr_state:NJ']])\n    \n    dataset['addr_state:AR_MI_PA_OH_MN']= sum([dataset['addr_state:AR'], dataset['addr_state:MI'],\n                                                  dataset['addr_state:PA'], dataset['addr_state:OH'], \n                                                  dataset['addr_state:MN']])\n    \n    dataset['addr_state:RI_MA_DE_SD_IN']= sum([dataset['addr_state:RI'], dataset['addr_state:MA'],\n                                                  dataset['addr_state:DE'], dataset['addr_state:SD'],\n                                                  dataset['addr_state:IN']])\n    \n    dataset['addr_state:GA_WA_OR'] = sum([dataset['addr_state:GA'], dataset['addr_state:WA'], \n                                          dataset['addr_state:OR']])\n    \n    dataset['addr_state:WI_MT'] = sum([dataset['addr_state:WI'], dataset['addr_state:MT']])\n    \n    dataset['addr_state:IL_CT'] = sum([dataset['addr_state:IL'], dataset['addr_state:CT']])\n    \n    dataset['addr_state:KS_SC_CO_VT_AK_MS'] = sum([dataset['addr_state:KS'], dataset['addr_state:SC'],\n                                                     dataset['addr_state:CO'], dataset['addr_state:VT'], \n                                                     dataset['addr_state:AK'], dataset['addr_state:MS']])\n    \n    dataset['addr_state:WV_NH_WY_DC_ME_ID'] = sum([dataset['addr_state:WV'], dataset['addr_state:NH'],\n                                                     dataset['addr_state:WY'], dataset['addr_state:DC'], \n                                                     dataset['addr_state:ME'], dataset['addr_state:ID']])\n\"\"\"\n#### verification_status\n\"\"\"\nloan_data_inputs_train['verification_status'].unique()\ndf_temp = woe_discrete(loan_data_inputs_train, 'verification_status', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nThe WOE of all these values is sufficiently different. All categories have enough observations. This variable can remain as is. The lowest WOE belongs to verified. That can become the reference category\n\"\"\"\n\"\"\"\n#### purpose\n\"\"\"\nloan_data_inputs_train['purpose'].unique()\ndf_temp = woe_discrete(loan_data_inputs_train, 'purpose', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nDebt consolidation and credit card can remain a separate value. It has too many values. \n\n\"\"\"\n#dataset['purpose:debt_consolidation']\n#dataset['purpose:credit_card']\nfor dataset in data_cleaner: \n    dataset['purpose:educ__sm_b__wedd__ren_en__mov__house'] = sum([dataset['purpose:educational'], \n                                                                       dataset['purpose:small_business'],\n                                                                       dataset['purpose:wedding'], \n                                                                       dataset['purpose:renewable_energy'],\n                                                                       dataset['purpose:moving'], \n                                                                       dataset['purpose:house']])\n    dataset['purpose:oth__med__vacation'] = sum([dataset['purpose:other'], \n                                                     dataset['purpose:medical'],\n                                                     dataset['purpose:vacation']])\n    dataset['purpose:major_purch__car__home_impr'] = sum([dataset['purpose:major_purchase'],\n                                                              dataset['purpose:car'],\n                                                              dataset['purpose:home_improvement']])\n\"\"\"\n#### initial_list_status\n\"\"\"\nloan_data_inputs_train['initial_list_status'].unique()\ndf_temp = woe_discrete(loan_data_inputs_train, 'initial_list_status', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nThere are only 2 categories and they both bins have enough values- no need to combine these. \n\"\"\"\n\"\"\"\n### Preprocessing Continuous Variables: Automating Calculations and Visualizing Results\n\"\"\"\ndef woe_ordered_continuous(df, discrete_variabe_name, good_bad_variable_df):\n    df = pd.concat([df[discrete_variabe_name], good_bad_variable_df], axis = 1)\n    df = pd.concat([df.groupby(df.columns.values[0], as_index = False)[df.columns.values[1]].count(),\n                    df.groupby(df.columns.values[0], as_index = False)[df.columns.values[1]].mean()], axis = 1)\n    df = df.iloc[:, [0, 1, 3]]\n    df.columns = [df.columns.values[0], 'n_obs', 'prop_good']\n    df['prop_n_obs'] = df['n_obs'] \/ df['n_obs'].sum()\n    df['n_good'] = df['prop_good'] * df['n_obs']\n    df['n_bad'] = (1 - df['prop_good']) * df['n_obs']\n    df['prop_n_good'] = df['n_good'] \/ df['n_good'].sum()\n    df['prop_n_bad'] = df['n_bad'] \/ df['n_bad'].sum()\n    df['WoE'] = np.log(df['prop_n_good'] \/ df['prop_n_bad'])\n    #df = df.sort_values(['WoE'])\n    #df = df.reset_index(drop = True)\n    df['diff_prop_good'] = df['prop_good'].diff().abs()\n    df['diff_WoE'] = df['WoE'].diff().abs()\n    df['IV'] = (df['prop_n_good'] - df['prop_n_bad']) * df['WoE']\n    df['IV'] = df['IV'].sum()\n    return df\n\"\"\"\n### Preprocessing Continuous Variables: Creating Dummy Variables\n\"\"\"\n\"\"\"\n#### Term\n\"\"\"\nloan_data_inputs_train['term_int'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'term_int', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\nfor dataset in data_cleaner:\n    dataset['term:36'] = np.where((dataset['term_int'] == 36), 1, 0)\n    dataset['term:60'] = np.where((dataset['term_int'] == 60), 1, 0)\n\"\"\"\n#### Employment Length\n\"\"\"\nloan_data_inputs_train['emp_length_int'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'emp_length_int', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\n0 years of emplyment can be separate category. 1 year of employment\n2-4\n5-6\n7-9\n10\n\"\"\"\nfor dataset in data_cleaner: \n    dataset['emp_length:0'] = np.where(dataset['emp_length_int'].isin([0]), 1, 0)\n    dataset['emp_length:1'] = np.where(dataset['emp_length_int'].isin([1]), 1, 0)\n    dataset['emp_length:2-4'] = np.where(dataset['emp_length_int'].isin(range(2, 5)), 1, 0)\n    dataset['emp_length:5-6'] = np.where(dataset['emp_length_int'].isin(range(5, 7)), 1, 0)\n    dataset['emp_length:7-9'] = np.where(dataset['emp_length_int'].isin(range(7, 10)), 1, 0)\n    dataset['emp_length:10'] = np.where(dataset['emp_length_int'].isin([10]), 1, 0)\n\"\"\"\n#### Months since Issue\n\"\"\"\nloan_data_inputs_train['mths_since_issue_d'].unique()\n\"\"\"\nThis variable has too many values to use as is. It can be converted to categorical using the cut function\n\"\"\"\nloan_data_inputs_train['mths_since_issue_factor'] = pd.cut(loan_data_inputs_train['mths_since_issue_d'], 50)\nloan_data_inputs_train['mths_since_issue_factor'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'mths_since_issue_factor', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nThe first three bins need to be kept separate from the rest of the categories. They have higher WOEs than the rest of the categories. Plotting the remaining bins to see which ones can be binned together:\n\"\"\"\nplot_by_woe(df_temp.iloc[3:, :])\n\"\"\"\nThe first 4 bins have similar weights of evidence (41.4, 48.6]. The next two categories can be grouped together.(48.6, 52.2]. The next 7 variables have similar WOE and can be grouped together (52.2, 64.8]. \n\nThe rest of the values have highly varying values. This is a warning to check their bin sizes. Usually small bin sizes could contribute to such variation. These can be combined into one dummy variable till there is an upward trend, and the rest of them together. (64.8, 84.60] & (84.60, Inf)\n\"\"\"\nfor dataset in data_cleaner: \n    dataset['mths_since_issue_d:<38'] = np.where(dataset['mths_since_issue_d'].isin(range(38)), 1, 0)\n    dataset['mths_since_issue_d:38-39'] = np.where(dataset['mths_since_issue_d'].isin(range(38, 40)), 1, 0)\n    dataset['mths_since_issue_d:40-41'] = np.where(dataset['mths_since_issue_d'].isin(range(40, 42)), 1, 0)\n    dataset['mths_since_issue_d:42-48'] = np.where(dataset['mths_since_issue_d'].isin(range(42, 49)), 1, 0)\n    dataset['mths_since_issue_d:49-52'] = np.where(dataset['mths_since_issue_d'].isin(range(49, 53)), 1, 0)\n    dataset['mths_since_issue_d:53-64'] = np.where(dataset['mths_since_issue_d'].isin(range(53, 65)), 1, 0)\n    dataset['mths_since_issue_d:65-84'] = np.where(dataset['mths_since_issue_d'].isin(range(65, 85)), 1, 0)\n    dataset['mths_since_issue_d:>84'] = np.where(dataset['mths_since_issue_d'].isin(range(85, int(dataset['mths_since_issue_d'].max()))), 1, 0)\n\"\"\"\n#### interest rate\n\"\"\"\nloan_data_inputs_train['int_rate'].unique()\nloan_data_inputs_train['int_rate_factor'] = pd.cut(loan_data_inputs_train['int_rate'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'int_rate_factor', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nLargely the relationship of interest rate w\/ WOE is monotonic. The boundaries of the bins will not have an impact on the monotonicity of this relationship. \n\nIdentifying cases where WOE differs significantly from the previous categories (huge jumps or lows).\nThe first ten bins have very large WOEs have low bin size. They can be combined together. This is till 9.548. \nThen the bins till 12.025 see a reduction in WOE.The other points where a huge change in WOE is seen are 15.74, 20.281, 23.583. \n\nThe bins after that have some variation but have very small bin sizes. \n\nFor a continuous variables, the condition will not look up a list. Instead we will use greater than\/less than conditions. \n\"\"\"\nfor dataset in data_cleaner: \n    dataset['int_rate:<9.548'] = np.where((dataset['int_rate'] <= 9.548), 1, 0)\n    dataset['int_rate:9.548-12.025'] = np.where((dataset['int_rate'] > 9.548) & (dataset['int_rate'] <= 12.025), 1, 0)\n    dataset['int_rate:12.025-15.74'] = np.where((dataset['int_rate'] > 12.025) & (dataset['int_rate'] <= 15.74), 1, 0)\n    dataset['int_rate:15.74-20.281'] = np.where((dataset['int_rate'] > 15.74) & (dataset['int_rate'] <= 20.281), 1, 0)\n    dataset['int_rate:>20.281'] = np.where((dataset['int_rate'] > 20.281), 1, 0)\n\"\"\"\n#### Funded amount\n\"\"\"\nloan_data_inputs_train['funded_amnt_factor'] = pd.cut(loan_data_inputs_train['funded_amnt'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'funded_amnt_factor', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nConsecutive intervals have very different weights of evidence. All of these variations are around a trend that is almost horizontal. Also, the IV of the variable is low. This is variable with weak predictive power (WoE varies greatly, and there is no association w\/ the independent variable. )\n\nThis variable can be left out of the model. \n\"\"\"\n\"\"\"\n#### months since credit line\n\"\"\"\nloan_data_inputs_train['mths_since_earliest_cr_line'].unique()\nloan_data_inputs_train['mths_since_earliest_cr_line_factor'] = pd.cut(loan_data_inputs_train['mths_since_earliest_cr_line'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'mths_since_earliest_cr_line_factor', loan_data_targets_train)\ndf_temp\nloan_data_inputs_train['mths_since_earliest_cr_line'].min()\nplot_by_woe(df_temp)\nplot_by_woe(df_temp.iloc[6:, :])\nfor dataset in data_cleaner: \n    dataset['mths_since_earliest_cr_line:<140'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(140)), 1, 0)\n    dataset['mths_since_earliest_cr_line:141-164'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(140, 165)), 1, 0)\n    dataset['mths_since_earliest_cr_line:165-247'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(165, 248)), 1, 0)\n    dataset['mths_since_earliest_cr_line:248-270'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(248, 271)), 1, 0)\n    dataset['mths_since_earliest_cr_line:271-352'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(271, 353)), 1, 0)\n    dataset['mths_since_earliest_cr_line:>352'] = np.where(dataset['mths_since_earliest_cr_line'].isin(range(353, int(dataset['mths_since_earliest_cr_line'].max()))), 1, 0)\n\"\"\"\n#### Installment\n\"\"\"\nloan_data_inputs_train['installment'].unique()\nloan_data_inputs_train['installment_factor'] = pd.cut(loan_data_inputs_train['installment'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'installment_factor', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nInstallement has very low IV, and a highly erratic WoE graph. \n\"\"\"\n\"\"\"\n#### Delinquency in the last 2 years\n\"\"\"\nloan_data_inputs_train['delinq_2yrs'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'delinq_2yrs', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nMost accounts have 0 delinquencies. They can remain in a separate category. Then the values from 1-3 delinquencies. The bins after that have very few values, so they can all be clubbed together. \n\"\"\"\nfor dataset in data_cleaner: \n    dataset['delinq_2yrs:0'] = np.where((dataset['delinq_2yrs'] == 0), 1, 0)\n    dataset['delinq_2yrs:1-3'] = np.where((dataset['delinq_2yrs'] >= 1) & (dataset['delinq_2yrs'] <= 3), 1, 0)\n    dataset['delinq_2yrs:>=4'] = np.where((dataset['delinq_2yrs'] >= 9), 1, 0)\n\"\"\"\n#### Inquiries in the last 6 months\n\"\"\"\nloan_data_inputs_train['inq_last_6mths'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'inq_last_6mths', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\n\"\"\"\nThe values equal to 0 need to be a separate category. Bins from 1-3 can be combined. Then the next cutoff can be around 6. The rest of the bins have very few values and can be combined together. \n\"\"\"\nfor dataset in data_cleaner: \n    dataset['inq_last_6mths:0'] = np.where((dataset['inq_last_6mths'] == 0), 1, 0)\n    dataset['inq_last_6mths:1-2'] = np.where((dataset['inq_last_6mths'] >= 1) & (dataset['inq_last_6mths'] <= 2), 1, 0)\n    dataset['inq_last_6mths:3-6'] = np.where((dataset['inq_last_6mths'] >= 3) & (dataset['inq_last_6mths'] <= 6), 1, 0)\n    dataset['inq_last_6mths:>6'] = np.where((dataset['inq_last_6mths'] > 6), 1, 0)\n\"\"\"\n#### Number of trades\n\"\"\"\nloan_data_inputs_train['open_acc'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'open_acc', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\nfor dataset in data_cleaner: \n    dataset['open_acc:0'] = np.where((dataset['open_acc'] == 0), 1, 0)\n    dataset['open_acc:1-3'] = np.where((dataset['open_acc'] >= 1) & (dataset['open_acc'] <= 3), 1, 0)\n    dataset['open_acc:4-12'] = np.where((dataset['open_acc'] >= 4) & (dataset['open_acc'] <= 12), 1, 0)\n    dataset['open_acc:13-17'] = np.where((dataset['open_acc'] >= 13) & (dataset['open_acc'] <= 17), 1, 0)\n    dataset['open_acc:18-22'] = np.where((dataset['open_acc'] >= 18) & (dataset['open_acc'] <= 22), 1, 0)\n    dataset['open_acc:23-25'] = np.where((dataset['open_acc'] >= 23) & (dataset['open_acc'] <= 25), 1, 0)\n    dataset['open_acc:26-30'] = np.where((dataset['open_acc'] >= 26) & (dataset['open_acc'] <= 30), 1, 0)\n    dataset['open_acc:>=31'] = np.where((dataset['open_acc'] >= 31), 1, 0)\n\"\"\"\n#### Number of public records\n\"\"\"\nloan_data_inputs_train['pub_rec'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'pub_rec', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\nfor dataset in data_cleaner: \n    dataset['pub_rec:0-2'] = np.where((dataset['pub_rec'] >= 0) & (dataset['pub_rec'] <= 2), 1, 0)\n    dataset['pub_rec:3-4'] = np.where((dataset['pub_rec'] >= 3) & (dataset['pub_rec'] <= 4), 1, 0)\n    dataset['pub_rec:>=5'] = np.where((dataset['pub_rec'] >= 5), 1, 0)\n\"\"\"\n#### Number of accounts\n\"\"\"\nloan_data_inputs_train['total_acc'].unique()\nloan_data_inputs_train['total_acc_factor']= pd.cut(loan_data_inputs_train['total_acc'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'total_acc_factor', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\nfor dataset in data_cleaner: \n    dataset['total_acc:<=27'] = np.where((dataset['total_acc'] <= 27), 1, 0)\n    dataset['total_acc:28-51'] = np.where((dataset['total_acc'] >= 28) & (dataset['total_acc'] <= 51), 1, 0)\n    dataset['total_acc:>=52'] = np.where((dataset['total_acc'] >= 52), 1, 0)\n\"\"\"\n#### Accounts now delinquent\n\"\"\"\nloan_data_inputs_train['acc_now_delinq'].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'acc_now_delinq', loan_data_targets_train)\ndf_temp\nplot_by_woe(df_temp)\nfor dataset in data_cleaner: \n    dataset['acc_now_delinq:0'] = np.where((dataset['acc_now_delinq'] == 0), 1, 0)\n    dataset['acc_now_delinq:>=1'] = np.where((dataset['acc_now_delinq'] >= 1), 1, 0)\n\"\"\"\n#### Annual income\n\"\"\"\n\"\"\"\nThis variable can have only positive values and has values running upto millions.\n\"\"\"\nloan_data_inputs_train['annual_inc_factor'] = pd.cut(loan_data_inputs_train['annual_inc'], 50)\n# Here we do fine-classing: using the 'cut' method, we split the variable into 50 categories by its values.\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'annual_inc_factor', loan_data_targets_train)\n# We calculate weight of evidence.\ndf_temp\n\"\"\"\nThere are a large number of values in the first interval (~94% of values). In this case, it might be worthwhile to split the variable into more classes. Eg. 100\n\"\"\"\nloan_data_inputs_train['annual_inc_factor'] = pd.cut(loan_data_inputs_train['annual_inc'], 100)\n# Here we do fine-classing: using the 'cut' method, we split the variable into 100 categories by its values.\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'annual_inc_factor', loan_data_targets_train)\n# We calculate weight of evidence.\ndf_temp\n\"\"\"\nThis makes things better, but still the first category ends up with 60% of observations. This is logical, because there are very few people with high incomes. We can increate one dummy variable for rich , while exploring the rest of the categories separately. Let the cutoff for rich start at the 3rd bin (144693.64). \n\"\"\"\n\"\"\"\nInitial examination shows that there are too few individuals with large income and too many with small income. Hence, we are going to have one category for more than 150K, and we are going to apply our approach to determine the categories of everyone with 140k or less.\n\"\"\"\n# Initial examination shows that there are too few individuals with large income and too many with small income.\n# Hence, we are going to have one category for more than 150K, and we are going to apply our approach to determine\n# the categories of everyone with 140k or less.\nloan_data_inputs_train_temp = loan_data_inputs_train.loc[loan_data_inputs_train['annual_inc'] <= 140000, : ]\n#loan_data_temp = loan_data_temp.reset_index(drop = True)\n#loan_data_inputs_train_temp\nloan_data_inputs_train_temp[\"annual_inc_factor\"] = pd.cut(loan_data_inputs_train_temp['annual_inc'], 50)\nloan_data_inputs_train_temp[\"annual_inc_factor\"].unique()\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'annual_inc_factor', \n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\ndf_temp\nplot_by_woe(df_temp) \n# WoE is monotonically increasing with income, so we split income in 12 categories\nfor dataset in data_cleaner: \n    dataset['annual_inc:<20K'] = np.where((dataset['annual_inc'] <= 20000), 1, 0)\n    dataset['annual_inc:20K-30K'] = np.where((dataset['annual_inc'] > 20000) & (dataset['annual_inc'] <= 30000), 1, 0)\n    dataset['annual_inc:30K-40K'] = np.where((dataset['annual_inc'] > 30000) & (dataset['annual_inc'] <= 40000), 1, 0)\n    dataset['annual_inc:40K-50K'] = np.where((dataset['annual_inc'] > 40000) & (dataset['annual_inc'] <= 50000), 1, 0)\n    dataset['annual_inc:50K-60K'] = np.where((dataset['annual_inc'] > 50000) & (dataset['annual_inc'] <= 60000), 1, 0)\n    dataset['annual_inc:60K-70K'] = np.where((dataset['annual_inc'] > 60000) & (dataset['annual_inc'] <= 70000), 1, 0)\n    dataset['annual_inc:70K-80K'] = np.where((dataset['annual_inc'] > 70000) & (dataset['annual_inc'] <= 80000), 1, 0)\n    dataset['annual_inc:80K-90K'] = np.where((dataset['annual_inc'] > 80000) & (dataset['annual_inc'] <= 90000), 1, 0)\n    dataset['annual_inc:90K-100K'] = np.where((dataset['annual_inc'] > 90000) & (dataset['annual_inc'] <= 100000), 1, 0)\n    dataset['annual_inc:100K-120K'] = np.where((dataset['annual_inc'] > 100000) & (dataset['annual_inc'] <= 120000), 1, 0)\n    dataset['annual_inc:120K-140K'] = np.where((dataset['annual_inc'] > 120000) & (dataset['annual_inc'] <= 140000), 1, 0)\n    dataset['annual_inc:>140K'] = np.where((dataset['annual_inc'] > 140000), 1, 0)\n\n\"\"\"\n#### Months since last delinquency\n\"\"\"\nloan_data_inputs_train['mths_since_last_delinq'].unique()\n\"\"\"\nThis variable has null values. The binning exercise should not consider those. However, instead  of dropping these variables, we can introduce a new dummy variable that takes on a value 1 when the value is nan and 0 when its not. Examining the WoE of the remaining values:\n\"\"\"\nloan_data_inputs_train_temp = loan_data_inputs_train[pd.notnull(loan_data_inputs_train['mths_since_last_delinq'])]\nloan_data_inputs_train_temp['mths_since_last_delinq_factor'] = pd.cut(loan_data_inputs_train_temp['mths_since_last_delinq'], 50)\n\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'mths_since_last_delinq_factor', \n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\n# We calculate weight of evidence.\ndf_temp\nplot_by_woe(df_temp, 90)\n\"\"\"\nWeight of evidence for the first category is considerably lower than the next one. So that can be a separate category (0-3]. The next jumps in WoE happen around 30 an then 56. The values after 56 have very few observations in each bin and hence can be combined together. \n\"\"\"\nfor dataset in data_cleaner: \n    dataset['mths_since_last_delinq:Missing'] = np.where((dataset['mths_since_last_delinq'].isnull()), 1, 0)\n    dataset['mths_since_last_delinq:0-3'] = np.where((dataset['mths_since_last_delinq'] >= 0) & (dataset['mths_since_last_delinq'] <= 3), 1, 0)\n    dataset['mths_since_last_delinq:4-30'] = np.where((dataset['mths_since_last_delinq'] >= 4) & (dataset['mths_since_last_delinq'] <= 30), 1, 0)\n    dataset['mths_since_last_delinq:31-56'] = np.where((dataset['mths_since_last_delinq'] >= 31) & (dataset['mths_since_last_delinq'] <= 56), 1, 0)\n    dataset['mths_since_last_delinq:>=57'] = np.where((dataset['mths_since_last_delinq'] >= 57), 1, 0)\n\"\"\"\n#### Debt to income ratio\n\"\"\"\nloan_data_inputs_train['dti'].unique()\nloan_data_inputs_train['dti'].max()\n# dti\nloan_data_inputs_train['dti_factor'] = pd.cut(loan_data_inputs_train['dti'], 50)\n# Here we do fine-classing: using the 'cut' method, we split the variable into 100 categories by its values.\ndf_temp = woe_ordered_continuous(loan_data_inputs_train, 'dti_factor', loan_data_targets_train)\n# We calculate weight of evidence.\ndf_temp\nplot_by_woe(df_temp, 90)\n\"\"\"\nThe variable has a largely downward trend around WoE. But there are very few values greater than 35.\n\"\"\"\nloan_data_inputs_train_temp = loan_data_inputs_train.loc[loan_data_inputs_train['dti'] <= 35, : ]\nloan_data_inputs_train_temp['dti_factor'] = pd.cut(loan_data_inputs_train_temp['dti'], 50)\n# Here we do fine-classing: using the 'cut' method, we split the variable into 50 categories by its values.\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'dti_factor',\n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\n# We calculate weight of evidence.\ndf_temp\nplot_by_woe(df_temp, 90)\nfor dataset in data_cleaner: \n    dataset['dti:<=1.4'] = np.where((dataset['dti'] <= 1.4), 1, 0)\n    dataset['dti:1.4-3.5'] = np.where((dataset['dti'] > 1.4) & (dataset['dti'] <= 3.5), 1, 0)\n    dataset['dti:3.5-7.7'] = np.where((dataset['dti'] > 3.5) & (dataset['dti'] <= 7.7), 1, 0)\n    dataset['dti:7.7-10.5'] = np.where((dataset['dti'] > 7.7) & (dataset['dti'] <= 10.5), 1, 0)\n    dataset['dti:10.5-16.1'] = np.where((dataset['dti'] > 10.5) & (dataset['dti'] <= 16.1), 1, 0)\n    dataset['dti:16.1-20.3'] = np.where((dataset['dti'] > 16.1) & (dataset['dti'] <= 20.3), 1, 0)\n    dataset['dti:20.3-21.7'] = np.where((dataset['dti'] > 20.3) & (dataset['dti'] <= 21.7), 1, 0)\n    dataset['dti:21.7-22.4'] = np.where((dataset['dti'] > 21.7) & (dataset['dti'] <= 22.4), 1, 0)\n    dataset['dti:22.4-35'] = np.where((dataset['dti'] > 22.4) & (dataset['dti'] <= 35), 1, 0)\n    dataset['dti:>35'] = np.where((dataset['dti'] > 35), 1, 0)\n\"\"\"\n#### mths_since_last_record\n\"\"\"\nloan_data_inputs_train['mths_since_last_record'].unique()\n\"\"\"\nThis is variable with null values. \n\"\"\"\nloan_data_inputs_train_temp = loan_data_inputs_train[pd.notnull(loan_data_inputs_train['mths_since_last_record'])]\nloan_data_inputs_train_temp['mths_since_last_record_factor'] = pd.cut(loan_data_inputs_train_temp['mths_since_last_record'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'mths_since_last_record_factor',\n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\ndf_temp\nplot_by_woe(df_temp, 90)\n# Categories: 'Missing', '0-2', '3-20', '21-31', '32-80', '81-86', '>86'\nfor dataset in data_cleaner: \n    dataset['mths_since_last_record:Missing'] = np.where((dataset['mths_since_last_record'].isnull()), 1, 0)\n    dataset['mths_since_last_record:0-2'] = np.where((dataset['mths_since_last_record'] >= 0) & (dataset['mths_since_last_record'] <= 2), 1, 0)\n    dataset['mths_since_last_record:3-20'] = np.where((dataset['mths_since_last_record'] >= 3) & (dataset['mths_since_last_record'] <= 20), 1, 0)\n    dataset['mths_since_last_record:21-31'] = np.where((dataset['mths_since_last_record'] >= 21) & (dataset['mths_since_last_record'] <= 31), 1, 0)\n    dataset['mths_since_last_record:32-80'] = np.where((dataset['mths_since_last_record'] >= 32) & (dataset['mths_since_last_record'] <= 80), 1, 0)\n    dataset['mths_since_last_record:81-86'] = np.where((dataset['mths_since_last_record'] >= 81) & (dataset['mths_since_last_record'] <= 86), 1, 0)\n    dataset['mths_since_last_record:>86'] = np.where((dataset['mths_since_last_record'] > 86), 1, 0)\nloan_data_inputs_train['mths_since_last_record:>86'].isnull().sum()\n\n\"\"\"\n### Total Revolving Limit\n\"\"\"\nloan_data_inputs_train['total_rev_hi_lim'].unique()\nloan_data_inputs_train_temp = loan_data_inputs_train[pd.notnull(loan_data_inputs_train['total_rev_hi_lim'])]\nloan_data_inputs_train_temp['total_rev_hi_lim_factor'] = pd.cut(loan_data_inputs_train_temp['total_rev_hi_lim'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'total_rev_hi_lim_factor',\n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\ndf_temp\n\"\"\"\nThis 99% of observations lie in the first bin, we need to dissect this into further bins to calculate WoE. \n\"\"\"\nloan_data_inputs_train_temp = loan_data_inputs_train.loc[loan_data_inputs_train['total_rev_hi_lim'] <= 200000, : ]\nloan_data_inputs_train_temp['total_rev_hi_lim_factor'] = pd.cut(loan_data_inputs_train_temp['total_rev_hi_lim'], 50)\ndf_temp = woe_ordered_continuous(loan_data_inputs_train_temp, 'total_rev_hi_lim_factor',\n                                 loan_data_targets_train[loan_data_inputs_train_temp.index])\ndf_temp\nplot_by_woe(df_temp, 90)\nfor dataset in data_cleaner:\n    dataset['total_rev_hi_lim:Missing'] = np.where((dataset['total_rev_hi_lim'].isnull()), 1, 0)\n    dataset['total_rev_hi_lim:<=5K'] = np.where((dataset['total_rev_hi_lim'] <= 5000), 1, 0)\n    dataset['total_rev_hi_lim:5K-10K'] = np.where((dataset['total_rev_hi_lim'] > 5000) & (dataset['total_rev_hi_lim'] <= 10000), 1, 0)\n    dataset['total_rev_hi_lim:10K-20K'] = np.where((dataset['total_rev_hi_lim'] > 10000) & (dataset['total_rev_hi_lim'] <= 20000), 1, 0)\n    dataset['total_rev_hi_lim:20K-30K'] = np.where((dataset['total_rev_hi_lim'] > 20000) & (dataset['total_rev_hi_lim'] <= 30000), 1, 0)\n    dataset['total_rev_hi_lim:30K-40K'] = np.where((dataset['total_rev_hi_lim'] > 30000) & (dataset['total_rev_hi_lim'] <= 40000), 1, 0)\n    dataset['total_rev_hi_lim:40K-55K'] = np.where((dataset['total_rev_hi_lim'] > 40000) & (dataset['total_rev_hi_lim'] <= 55000), 1, 0)\n    dataset['total_rev_hi_lim:55K-95K'] = np.where((dataset['total_rev_hi_lim'] > 55000) & (dataset['total_rev_hi_lim'] <= 95000), 1, 0)\n    dataset['total_rev_hi_lim:>95K'] = np.where((dataset['total_rev_hi_lim'] > 95000), 1, 0)\n            \n             \n\"\"\"\n## Saving Output\n\"\"\"\nloan_data_inputs_train.to_csv('loan_data_inputs_train.csv')\nloan_data_targets_train.to_csv('loan_data_targets_train.csv')\nloan_data_inputs_test.to_csv('loan_data_inputs_test.csv')\nloan_data_targets_test.to_csv('loan_data_targets_test.csv')","meta":"{'source': 'AI4Code', 'id': '9da81726718155'}"}
{"id":"115280","text":"\"\"\"\n\n# NBA 2020\/2021 Fantasy Draft Kit\n\nStarting from the 19\/20 stats and the 20\/21 projections, visualise and sort the data. Find the z-scores and display, to help you make better choices.\n\nTODO:\n- Track all the teams as they are picked\n- Calculate the expected performance of your current team, both in absolute projected score and relative position\n- Find a better way to do this live\n- Find a way to swap between DataFrames in the interact widget\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\n\nfrom ipywidgets import interact, fixed\npd.set_option(\"display.max_rows\", 1000)\n\"\"\"\n### Load and format the input data\n\"\"\"\nprojections = pd.read_csv(\"\/kaggle\/input\/nba-9cat-stats-and-projections-20202021\/projections.csv\")\nstats = pd.read_csv(\"\/kaggle\/input\/nba-9cat-stats-and-projections-20202021\/stats.csv\")\nCATEGORIES = [\"FG%\", \"FT%\", \"3PM\", \"REB\", \"AST\", \"STL\", \"BLK\", \"TO\", \"PTS\"]\nCOLS = [\"name\", \"positions\", \"GP\", \"MIN\", \"A\/TO\", *CATEGORIES]\ndef format_table(df):\n    numerics = df.columns.drop([\"name\", \"positions\"])\n    for col in numerics:\n        df[col] = df[col].astype(float)\n    df = df[COLS].copy()\n    df[\"team\"] = [None]*len(df)\n    return df\nprojections = format_table(projections)\nprojections.head()\n# Z-scores\ndef get_zscores_df(df):\n    zscores_df = df.drop(columns=CATEGORIES)\n    for col in CATEGORIES:\n        zscores_df[col] = round((df[col]-df[col].mean())\/df[col].std(ddof=0),2)\n    return zscores_df[COLS + [\"team\"]]\n\ndef cross_out(row):\n    \"\"\"cross out taken players\"\"\"\n    if row[\"team\"] is not None:\n        return ['text-decoration: line-through' for _ in row]\n    else:\n        return ['' for _ in row]\n\n\ndef display_table(df):\n    display(df.style.background_gradient(cmap=CMAP, subset=CATEGORIES)\n            .set_precision(2).apply(cross_out, axis=1))\nzscores_df = get_zscores_df(projections)\ndef sort(df, column, position):\n    if position != \"ALL\":\n        df = df[df.positions.apply(lambda x: position in x)]\n    if column != \"OVERALL\":\n        df = df.sort_values(by=column, ascending=False)\n    return display(df.style.background_gradient(cmap=CMAP, subset=CATEGORIES)\n            .set_precision(2).apply(cross_out, axis=1))  \nCMAP=sns.diverging_palette(5, 250, as_cmap=True)\n# interact(sort, df=[(\"projections\", projections), (\"zscores\",zscores_df)], column=CATEGORIES)\ninteract(sort, df=fixed(zscores_df), column=[\"OVERALL\", *CATEGORIES],\n         position=[\"ALL\", \"PG\", \"SG\", \"PF\", \"SF\", \"C\"])","meta":"{'source': 'AI4Code', 'id': 'd3e827397cb16d'}"}
{"id":"123592","text":"# 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf_stores = pd.read_csv('\/kaggle\/input\/retaildataset\/stores data-set.csv')\ndf_stores.head()\ndf_features = pd.read_csv('\/kaggle\/input\/retaildataset\/Features data set.csv')\ndf_features.head()\ndf_sales = pd.read_csv('\/kaggle\/input\/retaildataset\/sales data-set.csv')\ndf_sales.head()\ndf_stores_features = df_stores.merge(right = df_features, on = 'Store')\n\ndf_merge = df_stores_features.merge(right = df_sales, on = ['Store', 'Date', 'IsHoliday'])\ndf_merge.sample(10)\ndf_merge.info()\ndf_merge.describe()\n\"\"\"\n#### Converting date column into datetime\n\"\"\"\ndf_merge['Date'] = pd.to_datetime(df_merge['Date'])\ndf_temp = df_merge.copy(deep=True)\ndf_temp['MarkDown'] = df_temp['MarkDown1'] + df_temp['MarkDown2'] +df_temp['MarkDown3'] +df_temp['MarkDown4'] + df_temp['MarkDown5']\ndf_temp.drop(['MarkDown1', 'MarkDown2', 'MarkDown3', 'MarkDown4', 'MarkDown5'], inplace = True, axis = 1)\nfig, ax = plt.subplots(figsize=(20,12))\nsns.heatmap(df_temp.corr(),annot=True)\n# df_temp.head\ndf_merge[['Date', 'Temperature', 'Fuel_Price', 'CPI', 'Unemployment', \n    'MarkDown1', 'MarkDown2', 'MarkDown3', 'MarkDown4', 'MarkDown5']].plot(x='Date', subplots=True, figsize=(20,15))\nplt.show()\n\"\"\"\n### Cumulative Weekly Sales Plot\n\"\"\"\ndf_temp = df_merge.groupby('Date').sum()['Weekly_Sales'].reset_index()\nfig, ax = plt.subplots(figsize=(20,12))\nax.plot('Date', 'Weekly_Sales', data=df_temp)\ndf_merge.Date.apply(lambda x: x.month)\ndf_temp = df_merge.groupby(df_merge.Date.apply(lambda x: x.month)).sum()['Weekly_Sales'].reset_index()\nplt.figure(figsize=(10, 5))\nsns.barplot(x=df_temp.Date,y=df_temp.Weekly_Sales)\nplt.title(\"Month wise Sales\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Sales\")\n\"\"\"\n### Performance Based on Stores\n\"\"\"\ndf_temp = df_merge.groupby('Type').sum()['Weekly_Sales'].reset_index()\nfig, ax = plt.subplots(figsize=(20,12))\nax.bar('Type', 'Weekly_Sales', data=df_temp)","meta":"{'source': 'AI4Code', 'id': 'e3493dcadcf389'}"}
{"id":"77110","text":"\"\"\"\n# Train a Quadcopter How to Fly\n#  Using Reinforcement Learing\n## By Yosry Negm\n\n<br><hr><br>\nThis Project introduces how to Design an agent to fly a quadcopter, and then train it using a reinforcement learning algorithm.\n\"\"\"\n\"\"\"\n## <font color='grey'>Preparation and importing libraries<\/font>\n\"\"\"\nimport warnings\nwarnings.filterwarnings('ignore')\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport random\nimport csv\nimport numpy as np\nimport sys\nimport pandas as pd\n\"\"\"\n## <font color='grey'>Declerations of utility routines<\/font>\n\"\"\"\n# function to 3D plot the changes in the quadcopter position\nfrom mpl_toolkits.mplot3d import Axes3D\ndef quadcopter_3d_plot(results, vars=['x', 'y', 'z'], title=''):\n    x = results[vars[0]]\n    y = results[vars[1]]\n    z = results[vars[2]]\n    c = results['time']\n    \n    fig = plt.figure(figsize=(8, 4), dpi=100)\n    ax = plt.axes(projection='3d')\n    cax = ax.scatter(x, y, z, c=c, cmap='YlGn')\n    ax.set(xlabel=vars[0], ylabel=vars[1], zlabel=vars[2], title=title)\n    fig.colorbar(cax, label='Time step (s)', pad=0.1, aspect=40)\n    plt.show();\n    \n# function to 3D plot the path of the Quadcopter\n\ndef show_flight_path(results, target=None):\n    results = np.array(results)\n    \n    ax = plt.axes(projection='3d')\n    ax.plot3D(results[:,0], results[:,1], results[:,2], 'gray')\n    if not target is None:\n        ax.scatter([target[0]], [target[1]], [target[2]], c='r', marker='o', s=30, label='Destination')\n    ax.scatter(results[0,0], results[0,1], results[0,2], c='g', marker='x', s=30, label='Starting Point')\n    ax.scatter(results[-1,0], results[-1,1], results[-1,2], c='b', marker='x', s=30, label='Ending point')\n    ax.legend()\n\"\"\"\n## <font color='grey'>Warm up<\/font>\n\"\"\"\n\nclass Basic_Agent():\n    def __init__(self, task):\n        self.task = task\n    \n    def act(self):\n        new_thrust = random.gauss(450., 25.)\n        return [new_thrust + random.gauss(0., 1.) for x in range(4)]\n\"\"\"\nThe code below lets the agent select actions to control the quadcopter.  \nThe `labels` list below annotates statistics that are saved while running the simulation.  All of this information is saved in a text file `data.txt` and stored in the dictionary `results`.  \n\"\"\"\nimport os\nfrom shutil import copyfile\npath=os.getcwd()\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\nos.makedirs('.\/agents\/')\n\ncopyfile(src = \"..\/input\/reinforcementlearingfiles\/task.py\", dst = \".\/task.py\")\ncopyfile(src = \"..\/input\/reinforcementlearingfiles\/physics_sim.py\", dst = \".\/physics_sim.py\")\ncopyfile(src = \"..\/input\/agents\/agent.py\", dst = \".\/agents\/agent.py\")\ncopyfile(src = \"..\/input\/agents\/policy_search.py\", dst = \".\/agents\/policy_search.py\")\ncopyfile(src = \"..\/input\/reinforcementlearingfiles\/data.txt\", dst = \".\/data.txt\")\ncopyfile(src = \"..\/input\/reinforcementlearingfiles\/requirements.txt\", dst = \".\/requirements.txt\")\ncopyfile(src = \"..\/input\/reinforcementlearingfiles\/rewards.txt\", dst = \".\/rewards.txt\")\nfrom task import Task\n\nruntime = 10.                                     # time limit of the episode\ninit_pose = np.array([0., 0., 13., 0., 0., 18.])  # initial pose\ninit_velocities = np.array([0., 8., 10.])         # initial velocities\ninit_angle_velocities = np.array([0., 77., 31.])   # initial angle velocities\nfile_output = '.\/data.txt'                         # file name for saved results\n\n# Setup\ntask = Task(init_pose, init_velocities, init_angle_velocities, runtime)\nagent = Basic_Agent(task)\ndone = False\nlabels = ['time', 'x', 'y', 'z', 'phi', 'theta', 'psi', 'x_velocity',\n          'y_velocity', 'z_velocity', 'phi_velocity', 'theta_velocity',\n          'psi_velocity', 'rotor_speed1', 'rotor_speed2', 'rotor_speed3', 'rotor_speed4']\nresults = {x : [] for x in labels}\n\n# Run the simulation, and save the results.\nwith open(file_output, 'w') as csvfile:\n    writer = csv.writer(csvfile)\n    writer.writerow(labels)\n    while True:\n        rotor_speeds = agent.act()\n        _, _, done = task.step(rotor_speeds)\n        to_write = [task.sim.time] + list(task.sim.pose) + list(task.sim.v) + list(task.sim.angular_v) + list(rotor_speeds)\n        for ii in range(len(labels)):\n            results[labels[ii]].append(to_write[ii])\n        writer.writerow(to_write)\n        if done:\n            break\n\"\"\"\nThe code below visualizes how the position of the quadcopter evolved during the simulation.\n\"\"\"\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.plot(results['time'], results['x'], label='x')\nplt.plot(results['time'], results['y'], label='y')\nplt.plot(results['time'], results['z'], label='z')\nplt.legend()\n_ = plt.ylim()\n\"\"\"\nThe next code cell visualizes the velocity of the quadcopter.\n\"\"\"\nplt.plot(results['time'], results['x_velocity'], label='x_hat')\nplt.plot(results['time'], results['y_velocity'], label='y_hat')\nplt.plot(results['time'], results['z_velocity'], label='z_hat')\nplt.legend()\n_ = plt.ylim()\n\"\"\"\nNext, we can plot the Euler angles (the rotation of the quadcopter over the $x$-, $y$-, and $z$-axes),\n\"\"\"\nplt.plot(results['time'], results['phi'], label='phi')\nplt.plot(results['time'], results['theta'], label='theta')\nplt.plot(results['time'], results['psi'], label='psi')\nplt.legend()\n_ = plt.ylim()\n\"\"\"\nbefore plotting the velocities (in radians per second) corresponding to each of the Euler angles.\n\"\"\"\nplt.plot(results['time'], results['phi_velocity'], label='phi_velocity')\nplt.plot(results['time'], results['theta_velocity'], label='theta_velocity')\nplt.plot(results['time'], results['psi_velocity'], label='psi_velocity')\nplt.legend()\n_ = plt.ylim()\n\"\"\"\nFinally, we can use the code cell below to print the agent's choice of actions.  \n\"\"\"\nplt.plot(results['time'], results['rotor_speed1'], label='Rotor 1 revolutions \/ second')\nplt.plot(results['time'], results['rotor_speed2'], label='Rotor 2 revolutions \/ second')\nplt.plot(results['time'], results['rotor_speed3'], label='Rotor 3 revolutions \/ second')\nplt.plot(results['time'], results['rotor_speed4'], label='Rotor 4 revolutions \/ second')\nplt.legend()\n_ = plt.ylim()\n\"\"\"\nWhen specifying a task, we will derive the environment state from the simulator.  The code below prints the values of the following variables at the end of the simulation:\n- `task.sim.pose` (the position of the quadcopter in ($x,y,z$) dimensions and the Euler angles),\n- `task.sim.v` (the velocity of the quadcopter in ($x,y,z$) dimensions), and\n- `task.sim.angular_v` (radians\/second for each of the three Euler angles).\n\"\"\"\n# the pose, velocity, and angular velocity of the quadcopter at the end of the episode\nprint(task.sim.pose)\nprint(task.sim.v)\nprint(task.sim.angular_v)\n\"\"\"\n### In adition, the following 3D plot visualize the changes in the Quadcopter position\n\"\"\"\nquadcopter_3d_plot(results, vars=['x', 'y', 'z'])\n\"\"\"\n### Also, the following is a  3D plot to visualize the four rotors speed changes\n\"\"\"\nquadcopter_3d_plot(results, vars=['rotor_speed1', 'rotor_speed2', 'rotor_speed3'])\n\"\"\"\nIn `task.py`, we use the 6-dimensional pose of the quadcopter to construct the state of the environment at each timestep.  However, when amending any more tasks, we could expand the size of the state vector by including the velocity information.  Also we can use any combination of the pose, velocity, and angular velocity.\n\n## The Task\n\nThe `__init__()` method in `task.py` is used to initialize several variables that are needed to specify the task.  \n- The simulator is initialized as an instance of the `PhysicsSim` class (from `physics_sim.py`).  \n- Inspired by the methodology in the original DDPG paper, we make use of action repeats.  For each timestep of the agent, we step the simulation `action_repeats` timesteps.  If you are not familiar with action repeats, please read the **Results** section in [the DDPG paper](https:\/\/arxiv.org\/abs\/1509.02971).\n- We set the number of elements in the state vector.  For the sample task, we only work with the 6-dimensional pose information.  To set the size of the state (`state_size`), we must take action repeats into account.  \n- The environment will always have a 4-dimensional action space, with one entry for each rotor (`action_size=4`). You can set the minimum (`action_low`) and maximum (`action_high`) values of each entry here.\n- The sample task in this provided file is for the agent to reach a target position.  We specify that target position as a variable.\n\nThe `reset()` method resets the simulator.  The agent should call this method every time the episode ends.  we can see an example of this in the code below.\n\nThe `step()` method is perhaps the most important.  It accepts the agent's choice of action `rotor_speeds`, which is used to prepare the next state to pass on to the agent.  Then, the reward is computed from `get_reward()`.  The episode is considered done if the time limit has been exceeded, or the quadcopter has travelled outside of the bounds of the simulation.\n\nIn the next section, we will show how to test the performance of an agent on this task.\n\"\"\"\n\"\"\"\n## The Agent\n\nThe agent given in `agents\/policy_search.py` uses a very simplistic linear policy to directly compute the action vector as a dot product of the state vector and a matrix of weights. Then, it randomly perturbs the parameters by adding some Gaussian noise, to produce a different policy. Based on the average reward obtained in each episode (`score`), it keeps track of the best set of parameters found so far, how the score is changing, and accordingly tweaks a scaling factor to widen or tighten the noise.\n\nThe code below explains how the agent performs on the task.\n\"\"\"\nfrom agents.policy_search import PolicySearch_Agent\nfrom task import Task\n\nnum_episodes = 2000\ntarget_pos = np.array([13., 8., 77.])\ntask = Task(target_pos=target_pos)\nagent = PolicySearch_Agent(task) \nrewards = []\nlabels = ['episode', 'total_reward']\nresults = {x : [] for x in labels}\nbest_flight_path = []\nfor i_episode in range(1, num_episodes+1):\n    state = agent.reset_episode() # start a new episode\n    flight_path = [ state ]\n    while True:\n        action = agent.act(state) \n        next_state, reward, done = task.step(action)\n        agent.step(reward, done)\n        state = next_state\n        flight_path.append(state)\n        if done:\n            rewards += [agent.score]\n            to_write = [i_episode] + [max(rewards)]\n            for k in range(len(labels)):\n                results[labels[k]].append(to_write[k])                 \n            print(\"\\rEpisode = {:4d}, score = {:7.3f} (best = {:7.3f}), noise_scale = {}\".format(\n                i_episode, agent.score, agent.best_score, agent.noise_scale), end=\"\")  # [debug]\n            rewards.append(np.mean(results['total_reward']))\n            if agent.score >= max(rewards):\n                best_flight_path = flight_path                \n            break\n    sys.stdout.flush()\n\"\"\"\nThis agent should <b>perform very poorly<\/b> on this task.  And that's where you come in! <font color='red'> As shown below :-<\/b>\n\"\"\"\n# avrage  of the last 10 episodes\nperformance = np.mean(rewards[-10:])\nprint(performance)\n\"\"\"\n## Define the Task, Design the Agent, and Train Your Agent!\n\nNow we will amend `task.py` to specify a task of our choosing.  If we're unsure what kind of task to specify, we may like to teach our quadcopter to takeoff, hover in place, land softly, or reach a target pose.  \n\nAfter specifying our task, we will use the agent in `agents\/policy_search.py` as a template to define our new agent in `agents\/agent.py`.  we can borrow whatever we need from the that agent, including ideas on how you might modularize our code (using helper methods like `act()`, `learn()`, `reset_episode()`, etc.).\n\nNote that it is **highly unlikely** that the first agent and task that you specify will learn well.  You will likely have to tweak various hyperparameters and the reward function for your task until you arrive at reasonably good behavior.\n\nAs you develop your agent, it's important to keep an eye on how it's performing. Use the code above as inspiration to build in a mechanism to log\/save the total rewards obtained in each episode to file.  If the episode rewards are gradually increasing, this is an indication that your agent is learning.\n\"\"\"\n\"\"\"\n## <font color='blue'>Take Off <\/font> Task\n\"\"\"\n\"\"\"\n\n\nfrom agents.agent import DDPG\nfrom task import Task,Task_TakeOff\n\nnum_episodes = 2000\ntarget_pos = np.array([0., 0., 0.])\ninit_pos = np.array([0., 0., 0.])\ntask = Task_TakeOff(init_pose=init_pos, target_pos=target_pos)\nrewards = []\nlabels = ['episode', 'total_reward']\nresults = {x : [] for x in labels}\nagent = DDPG(task) \n\nbest_flight_path = []\nfor i_episode in range(1, num_episodes+1):\n    state = agent.reset_episode() # start a new episode\n    num_steps = 0\n    flight_path = [ state ]\n    while True:\n        action = agent.act(state) \n        next_state, reward, done = task.step(action)\n        agent.step(action, reward, next_state, done)\n        state = next_state\n        flight_path.append(state)\n        if done:\n            rewards += [agent.get_score()]\n            to_write = [i_episode] + [max(rewards)]\n            for k in range(len(labels)):\n                results[labels[k]].append(to_write[k])            \n            print(\"Episode = {:4d}, steps={:4d} reward = {:9.3f} (best = {:9.3f})  \".format(\n                i_episode, agent.num_steps, agent.get_score(), max(rewards)), end=\"\\r\")  # [debug]\n            rewards.append(np.mean(results['total_reward']))\n            if agent.get_score() >= max(rewards):\n                best_flight_path = flight_path                \n            break\n            \n    sys.stdout.flush()\n    \n    \"\"\"\n\"\"\"\n## Ploting rewards for Take Off Task\n\"\"\"\nplt.plot(results['episode'], results['total_reward'])\n_ = plt.ylim()\n\"\"\"\n## Average of the last 10 episodes\n\"\"\"\n# avrage  of the last 10 episodes\nperformance = np.mean(rewards[-10:])\nprint(performance)\n\"\"\"\n## <font color='blue'>Hover <\/font> Task\n\"\"\"\n\"\"\"\nfrom agents.agent import DDPG\nfrom task import Task_Hover\n\n\n# the values below gives the quadcopter different starting positions.\nruntime = 5.                                     # time limit of the episode\ninit_pose = np.array([0., 0., 0., 0., 0., 0.])  # initial pose\ninit_velocities = np.array([0., 0., 0.])         # initial velocities\ninit_angle_velocities = np.array([0., 0., 0.])   # initial angle velocities\nfile_output = 'rewards.txt'                      # file name for saved results\n\nnum_episodes = 2000\ntarget_pos = np.array([0., 0., 0.])\ntask = Task(target_pos=target_pos)\nagent = DDPG(task) \nrewards = []\nlabels = ['episod', 'total_reward']\nresults = {x : [] for x in labels}\n\nwith open(file_output, 'w') as csvfile:\n    writer = csv.writer(csvfile)\n    writer.writerow(labels)  \n    best_total_reward = 0\n    for i_episode in range(1, num_episodes+1):\n        state = agent.reset_episode() # start a new episode\n        total_reward = 0\n        while True:\n            action = agent.act(state) \n            next_state, reward, done = task.step(action)\n            total_reward += reward\n            if total_reward > best_total_reward:\n                best_total_reward = total_reward\n            agent.step(action, reward, next_state, done)\n            state = next_state\n            if done:\n                to_write = [i_episode] + [total_reward]\n                for ii in range(len(labels)):\n                    results[labels[ii]].append(to_write[ii])\n                writer.writerow(to_write)\n                print(\"\\rEpisode = {:4d}, total_reward = {:7.3f} (best = {:7.3f})\".format(\n                    i_episode, total_reward, best_total_reward), end=\"\")\n                rewards.append(np.mean(results['total_reward']))\n                break\n        sys.stdout.flush()\n        \n        \"\"\"\n\"\"\"\n## Ploting rewards for Hover Task\n\"\"\"\n\"\"\"\nplt.plot(results['episod'], results['total_reward'])\n_ = plt.ylim()\n\n\"\"\"\n\"\"\"\n## Average of the last 10 episodes\n\"\"\"\n# avrage  of the last 10 episodes\nperformance = np.mean(rewards[-10:])\nprint(performance)\n\"\"\"\n## Reflections\n\nI have chosen two tasks to train my designed agent, they are <b><font color='green'> Take-off task<\/font><\/b> and <b><font color='green'> Hover task<\/font><\/b> . I designed the reward function in both cases to <b>preserve the clipping of rewards between -1 and +1<\/b> trying to to<b> maximize the penality<\/b> whenever the distance between the pose and target of the quadcopter is large or the agent has run out of time.\n\n\"\"\"\n\"\"\"\nIn this project, I chose to use<font color='green'><b> Actor-Critic Algorithm <\/b><\/font>to train my dsigned agent on the prposed tasks. It works better for me after tuning the algorithm hyper parameter such as \nchoosing discount factor (<font color='green'><b>gamma<\/b><\/font>) equal to 0.99 and <font color='green'><b>epislon<\/b><\/font> equal to 0.01 for <b>soft update of target parameters<\/b>.<br>\nI build the model by<b> two nural networks <\/b>one for the <u>actor<\/u> and the other one for the <u>crictic<\/u> with  <font color='green'><b>ReLu<\/b><\/font> activation function in the hidden layers and <font color='green'><b>Sigmoid <\/b><\/font>activation function in the output layer in each.<br>\n- <b><u>The Neural Network of the Actor<\/u><\/b> :-<br>\n    -  Dense :  32 hidden units Layer ,Two Layers with 64 hidden units each , 128 hidden units Layer (All with <b>ReLu<\/b> activation function) and Batch Normalization. \n    -  Dropout: 3 with keep_prob = 0.5 .\n    -  Output : on Layer with units equal to the action size with <b>Sigmoid<\/b> activation function.<br>\n- <b><u>The Neural Network of the Critic<\/u><\/b>:-<br>\n    - <b><u>State <\/u>:<\/b> <br>\n        -  Dense :  32 hidden units Layer , 64 hidden units Layer, 128 hidden units Layer (All with <b>ReLu<\/b> activation function) and Batch Normalization. \n        -  Dropout: 3 with keep_prob = 0.5.<br>\n    - <b><u>Action <\/u>:<\/b><br>\n        -  Dense : Two Layers with 64 hidden units each, 128 hidden units Layer (All with <b>ReLu<\/b> activation function) and Batch Normalization. \n        -  Dropout: 3 with keep_prob = 0.5.<br>\n- <p>When building this architecture, I put into consideration imporving policy gradient with a critic i.e running the policy over generating samples then fit the model to estimate the return and therefore, improving the policy.The used algorithms seems to be stable and simple despite of there is no shared features between the actor and the critic so I made it to work in Batch to get lower variance with virtue of critic trying to get rewards sooner as possible to obtain better performance.<\/p>\n\"\"\"\n\"\"\"\nTraining the agent to fly the Quadcopter wasn't easy task, It took me extra time and lots of trail and error ,gussing and numerous tuning phases of the hyperparamers of the algorithm and the architecture as well as trying different intial states and redesigning the reward function several times until got gradual learning curve and better performance as indicated from the mean of the last 10 episodes.\n\"\"\"\n\"\"\"\nFirst of all it was an excited experience for me, especially I am interested in the programming of autonomous vehicles. The project was a great chance to have hands and dig into field\nmore practically,The hardest part I faced was really how to define and design tasks it tooks me time to think about them also I found some difficulty in tuning the parameters and reward function to get better performance as well as inspecting the architecture serveral times.Plotting results was so easy and the project in general goes smooth with me.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8da30f53fae978'}"}
{"id":"138140","text":"%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom bokeh.io import show,output_notebook\nfrom bokeh.layouts import column\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource, HoverTool, CustomJS, TextInput\noutput_notebook()\n\"\"\"\n# Public EDA\n\"\"\"\ndef process_df(df):\n    df['SubmissionDate'] = pd.to_datetime(df['SubmissionDate'])\n    df['Rank'] = df['Score'].rank()\n    df['Rank'] = df['Rank'].max() - df['Score'].rank() + 1\n    df['SubmissionDays'] = (df['SubmissionDate'].max() - df['SubmissionDate']).dt.days\n    firstScoreDate = df.groupby('Score')['SubmissionDate'].transform('min')\n    uniqueScore = df.groupby('Score')['SubmissionDate'].transform('count') == 1\n    df['color'] = 'red'\n    df.loc[uniqueScore, 'color'] = 'blue'\n    df.loc[firstScoreDate < df['SubmissionDate'], 'color'] = 'yellow'\n# Load data and prepare position for teams\n\nleaderboard_public = pd.read_csv('..\/input\/jane-street-market-prediction-leaderboards\/jane-street-market-prediction-publicleaderboard.csv')\n\nprocess_df(leaderboard_public)\nleaderboard_public.head()\n# Check distributions of scores\n\nleaderboard_public['Score'].plot.hist(bins=50, color='green', figsize=(10,3));\n# count of unique cases and ratio of unique cases\n\nleaderboard_public['Score'].nunique(), leaderboard_public['Score'].nunique() \/ len(leaderboard_public)\n# count of cases with Score > 10000 and ratio of unique cases with Score > 10000\n\ntopscores = leaderboard_public[leaderboard_public['Score'] > 10000]['Score']\n\nlen(topscores), topscores.nunique(), topscores.nunique() \/ len(topscores)\n# Check distributions of top scores\n\nleaderboard_public.where(leaderboard_public['Score']>10000)['Score'].plot.hist(bins=50, color='green', figsize=(10,3));\n# unique days\nleaderboard_public['SubmissionDays'].unique()\n# Check distributions of SubmissionDays\n\nleaderboard_public['SubmissionDays'].plot.hist(bins=25, color='green', figsize=(10,3), xlim=(leaderboard_public['SubmissionDays'].max(), leaderboard_public['SubmissionDays'].min()));\n# scatter of Date and Score\nleaderboard_public.plot.scatter(x='SubmissionDate', y='Score', c='color', alpha=0.3, figsize=(10,10));\n# top 20 the most frequent scores\nleaderboard_public['Score'].value_counts().head(20)\n# scatter of Date and Rank\nleaderboard_public.plot.scatter(x='SubmissionDate', y='Rank', c='color', alpha=0.3, figsize=(10,10), ylim=(leaderboard_public['Rank'].max(), leaderboard_public['Rank'].min()));\n\"\"\"\n# 2021-03-05 (First Private LB)\n\"\"\"\n# Load data and prepare position for teams\n\nprivate1 = pd.read_csv('..\/input\/jane-street-market-prediction-leaderboards\/jane-street-market-prediction-20200305.csv')\n\nprocess_df(private1)\nprivate1.head()\n# Check distributions of scores\n\nprivate1['Score'].plot.hist(bins=50, color='green', figsize=(10,3));\n# count of unique cases and ratio of unique cases\n\nprivate1['Score'].nunique(), private1['Score'].nunique() \/ len(private1)\n# count of cases with Score > 4000 and ratio of unique cases with Score > 4000\n\ntopscores = private1[private1['Score'] > 4000]['Score']\n\nlen(topscores), topscores.nunique(), topscores.nunique() \/ len(topscores)\n# top 20 the most frequent scores\nprivate1['Score'].value_counts().head(20)\n\"\"\"\n# Private\/Public results\n\"\"\"\nprivate1['PastScore'] = private1['TeamId'].map(leaderboard_public.set_index('TeamId')['Score'])\nprivate1['PastRank'] = private1['TeamId'].map(leaderboard_public.set_index('TeamId')['Rank'])\nprivate1['PastSubmissionDate'] = private1['TeamId'].map(leaderboard_public.set_index('TeamId')['SubmissionDate'])\nprivate1['PastSubmissionDays'] = private1['TeamId'].map(leaderboard_public.set_index('TeamId')['SubmissionDays'])\n# scatter of New\/Past Scores\nprivate1.plot.scatter(x='PastScore', y='Score', c='color', alpha=0.3, figsize=(10,10));\n# scatter of New\/Past Rank\nprivate1.plot.scatter(x='PastRank', y='Rank', c='color', alpha=0.3, figsize=(10,10), ylim=(private1['Rank'].max(), private1['Rank'].min()), xlim=(private1['PastRank'].max(), private1['PastRank'].min()));\n# scatter of Past Submission Date \/ Score\nprivate1.plot.scatter(x='SubmissionDate', y='Score', c='color', alpha=0.3, figsize=(10,10));\nprivate1['PastScoreMin'] = private1['PastScore'].cummin()\nprivate1['PastRankMax'] = private1['PastRank'].cummax()\nprivate1['PastSubmissionDaysMax'] = private1['SubmissionDays'].cummax()\n\nprivate1.head()\n# What is minimum score public Score you should have for getting high score\nprivate1.plot(x='Score', y='PastScoreMin');\n# What is minimum score public Rank you should have for getting high rank\nprivate1.plot(x='Score', y='PastRankMax', ylim=(private1['PastRankMax'].max()+200, private1['PastRankMax'].min()-200));\n# What is maximum days for getting high score?\nprivate1.plot(x='Score', y='PastSubmissionDaysMax');\n\"\"\"\n# Corr matrixes\n\"\"\"\n# Corr matrix\nprivate1[['Score', 'PastScore']].corr()\n# Corr matrix\nprivate1[['Rank', 'PastRank']].corr()\n# Corr matrix\nprivate1[['Score', 'PastSubmissionDays']].corr()\n# Bokeh visualization of Private\/Public Scores\n\nsource = ColumnDataSource(private1)\nsource_visible = ColumnDataSource(private1)\n\nplot = figure(\n    x_axis_label = \"Public Score\",\n    y_axis_label = \"Private Score\",\n    tools=\"pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset\",\n    plot_width=800,\n    plot_height=1000,\n)\nplot.circle(x=\"PastScore\",y=\"Score\",source = source_visible, radius=3, alpha=0.5, color='color')\nplot.text(x='PastScore',y='Score', text='TeamName',source  = source_visible,\n       text_baseline=\"middle\", text_align=\"left\", text_font_size='8pt', text_font='Arial', alpha=0.5)\n\nhover = HoverTool(tooltips = [\n    ('Team', '@TeamId \/ @TeamName'), \n    ('Public Score\/ Private Score', '@PastScore{i} \/ @Score{i}')])\nplot.add_tools(hover)\n\ncallback = CustomJS(args=dict(source_visible=source_visible,\n              source=source), code=\"\"\"\n        var f = cb_obj.value\n        var data = source.data;\n        \n        var data_visible = {'SubmissionDate': [], TeamId':[], 'TeamName': [], 'Score': [], 'PastScore': [], 'color': []}\n        \n        for (var i = 0; i < data['TeamId'].length; i++) {\n            if (data['TeamName'][i].includes(f)) {\n                data_visible['SubmissionDate'].push(data['SubmissionDate'][i])\n                data_visible['TeamId'].push(data['TeamId'][i])\n                data_visible['TeamName'].push(data['TeamName'][i])\n                data_visible['Score'].push(data['Score'][i])\n                data_visible['PastScore'].push(data['PastScore'][i])\n                data_visible['color'].push(data['color'][i])\n            }\n        }\n        \n        source_visible.data = data_visible\n        source_visible.change.emit();\n    \"\"\")\n\ntext_input = TextInput(value=\"\", title=\"Filter by TeamName:\")\ntext_input.js_on_change(\"value\", callback)\n\nshow(column(text_input, plot))\nprivate1.groupby('TeamId').size().value_counts()\n\"\"\"\n# Latest Private LB (2021-03-17)\n\"\"\"\n# Load data and prepare position for teams\n\nprivate2 = pd.read_csv('..\/input\/jane-street-market-prediction-leaderboards\/jane-street-market-prediction-20210317.csv')\n\nprocess_df(private2)\nprivate2.head()\n# Check distributions of scores\n\nprivate2['Score'].plot.hist(bins=50, color='green', figsize=(10,3));\n# top 20 the most frequent scores\nprivate2['Score'].value_counts().head(20)\n\"\"\"\n# First\/Last Private Analysis\n\"\"\"\nprivate1['LastScore'] = private1['TeamId'].map(private2.set_index('TeamId')['Score'])\nprivate1['LastRank'] = private1['TeamId'].map(private2.set_index('TeamId')['Rank'])\n\nprivate1['ScoreDiff'] =  private1['LastScore'] - private1['Score']\nprivate1['RankDiff'] =  private1['LastRank'] - private1['Rank']\n# How many teams have decreased Score?\n(private1['ScoreDiff']<0).sum()\n# scatter of First\/Last Scores\nprivate1.plot.scatter(x='Score', y='LastScore', c='color', alpha=0.3, figsize=(10,10));\n# scatter of First\/Last Rank\nprivate1.plot.scatter(x='Rank', y='LastRank', c='color', alpha=0.3, figsize=(10,10), ylim=(private1['LastRank'].max(), private1['LastRank'].min()), xlim=(private1['Rank'].max(), private1['Rank'].min()));\n# scatter of LastScore\/Diff\nprivate1.plot.scatter(x='LastScore', y='ScoreDiff', c='color', alpha=0.3, figsize=(10,10));\n# RankDiff distribution\nprivate1['RankDiff'].plot.hist(bins=200, figsize=(15,3))\n# ScoreDiff distribution\nprivate1['ScoreDiff'].plot.hist(bins=200, figsize=(15,3))\nprivate1['ScoreDiff'].apply(['min', 'mean', 'median', 'max'])\n# Teams with highest diff (looks like the had some failed kernels in the first run)\nprivate1.sort_values('ScoreDiff', ascending=False).head(20)\n# Teams with lowest diff (looks like the have some failed kernels in the last run)\nprivate1.sort_values('ScoreDiff', ascending=False).tail(20)\n# Top 200 ScoreDiff distribution\nprivate1['ScoreDiff'].head(200).plot.hist(bins=20, figsize=(15,3))\nprivate1['ScoreDiff'].head(200).apply(['min', 'mean', 'median', 'max'])\nprivate1.sort_values('LastRank').head(50)\n\"\"\"\n# Naive score prediction after 12 reruns (6 months = 24 weeks = 12 runs) :)\n\"\"\"\nrolling_mean = private1['ScoreDiff'].rolling(50, center=True, min_periods=1).mean()\nrolling_std = private1['ScoreDiff'].rolling(50, center=True, min_periods=1).std()\nhigh_level = rolling_mean + 0.5*rolling_std\nlow_level = rolling_mean - 0.5*rolling_std\n\nprivate1['ScoreDiff_cutted'] = private1['ScoreDiff']\nprivate1.loc[private1['ScoreDiff'] > high_level, 'ScoreDiff_cutted'] = high_level[private1['ScoreDiff'] > high_level]\nprivate1.loc[private1['ScoreDiff'] < low_level, 'ScoreDiff_cutted'] = low_level[private1['ScoreDiff'] < low_level]\nprivate1.loc[private1['ScoreDiff_cutted'].isnull(), 'ScoreDiff_cutted'] = 0\n\nprivate1['Score12runs'] = np.maximum(private1['Score'].fillna(0), private1['LastScore'].fillna(0) - private1['ScoreDiff_cutted'])  + 12 * private1['ScoreDiff_cutted']\nprivate1.sort_values('Score12runs', ascending=False).head(50).style.bar(subset=['Rank', 'LastRank', 'Score', 'LastScore', 'Score12runs'], color='#d65f5f')\n# scatter of First\/Predicted Scores\nprivate1.plot.scatter(x='Score', y='Score12runs', c='color', alpha=0.3, figsize=(10,10));","meta":"{'source': 'AI4Code', 'id': 'fde94b954fdf1f'}"}
{"id":"1822","text":"\"\"\"\n**Hello Visitor,**\n\n**This is one of my first attempts at making a detailed and well thought out kernels, hope you gain some insights from it and find it useful! Do upvote and share it if you like it! :)**\n\n\n***This kernel has covered 4 topics:***\n- Basic Introduction\n- EDA\n- Feature Engineering\n- Model Building\n\n**The name of the competition is Tabular Playground Series - Apr 2021**\n\n**The tag line is Synthanic - You're going to need a bigger boat**\n\n\n\n![Titanic Ship Credits:Canoe1967\/wikipeida.org](https:\/\/www.marineinsight.com\/wp-content\/uploads\/2010\/10\/titanic.jpg)\n\n**The competition description:**\n\n\nKaggle competitions are incredibly fun and rewarding, but they can also be intimidating for people who are relatively new in their data science journey. In the past, we've launched many Playground competitions that are more approachable than our Featured competitions and thus, more beginner-friendly.\n\nIn order to have a more consistent offering of these competitions for our community, we're trying a new experiment in 2021. We'll be launching month-long tabular Playground competitions on the 1st of every month and continue the experiment as long as there's sufficient interest and participation.\n\nThe goal of these competitions is to provide a fun, and approachable for anyone, tabular dataset. These competitions will be great for people looking for something in between the Titanic Getting Started competition and a Featured competition. If you're an established competitions master or grandmaster, these probably won't be much of a challenge for you. We encourage you to avoid saturating the leaderboard.\n\nFor each monthly competition, we'll be offering Kaggle Merchandise for the top three teams. And finally, because we want these competitions to be more about learning, we're limiting team sizes to 3 individuals.\n\nThe dataset is used for this competition is synthetic but based on a real dataset (in this case, the actual Titanic data!) and generated using a CTGAN. The statistical properties of this dataset are very similar to the original Titanic dataset, but there's no way to \"cheat\" by using public labels for predictions. How well does your model perform on truly private test labels?\n\n\n**Task at hand:**\n\nYour task is to predict whether or not a passenger survived the sinking of the Synthanic (a synthetic, much larger dataset based on the actual Titanic dataset). For each PasengerId row in the test set, you must predict a 0 or 1 value for the Survived target.\n\nYour score is the percentage of passengers you correctly predict. This is known as accuracy.\n\n\n**Other things to Note:**\n\n**Points** : This competition does not award ranking points\n\n**Tiers** : This competition does not count towards tiers\n\n\n**Little bit about the Titanic:**\n\nTitanic, in full Royal Mail Ship (RMS) Titanic, British luxury passenger liner that sank on April 14\u201315, 1912, during its maiden voyage, en route to New York City from Southampton, England, killing about 1,500 passengers and ship personnel. One of the most famous tragedies in modern history, it inspired numerous stories, several films, and a musical and has been the subject of much scholarship and scientific speculation.\n\n![The Real Titanic](https:\/\/cdn.britannica.com\/68\/185468-050-C0D53622\/Titanic-iceberg-British-15-1912.jpg)\n\"\"\"\n# Importing the basic libariries \n# We will import the others later this is just to get the analysis started :P\n\nimport os\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport warnings\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nimport seaborn as sns\n\npd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)\nwarnings.filterwarnings('ignore')\n\"\"\"\n# **Importing the data**\n\"\"\"\n# Importing the data \n\ntrain_df = pd.read_csv('\/kaggle\/input\/tabular-playground-series-apr-2021\/train.csv')\ntest_df = pd.read_csv('\/kaggle\/input\/tabular-playground-series-apr-2021\/test.csv')\n\"\"\"\n**Number of Rows and Columns**\n\"\"\"\nprint('Rows and Columns in train dataset:', train_df.shape)\nprint('Rows and Columns in test dataset:', test_df.shape)\n\"\"\"\n**Numbers of missing values**\n\"\"\"\nprint('Missing values in train dataset:', sum(train_df.isnull().sum()))\nprint('Missing values in test dataset:', sum(test_df.isnull().sum()))\n\"\"\"\n**Missing values per columns in train and test dataset**\n\"\"\"\nprint('Missing values per columns in train dataset')\nfor col in train_df.columns:\n    temp_col = train_df[col].isnull().sum()\n    print(f'{col}: {temp_col}')\nprint()\nprint('Missing values per columns in test dataset')\nfor col in test_df.columns:\n    temp_col = test_df[col].isnull().sum()\n    print(f'{col}: {temp_col}')\n\"\"\"\n**Top 5 rows in the train dataset**\n\"\"\"\ntrain_df.head()\n\"\"\"\n**The data contains the following information:**\n\n1. Pclass - a proxy for socio-economic status (SES) where 1st = Upper, 2nd = Middle and 3rd = Lower.\n2. Sex - male and female.\n3. Age - fractional if it less than 1 and age estimation in the form of xx.5.\n4. SibSp - number of siblings \/ spouses aboard the Synthanic; siblings are brother, sister, stepbrother and stepsister and spouses are husband and wife (mistresses and fianc\u00e9s were ignored).\n5. Parch - # of parents \/ children aboard the Synthanic; parents are mother and father; child are daughter, son, stepdaughter and stepson. Some children travelled only with a nanny, therefore Parch is 0 for them.\n6. Fare - the paassenger fare.\n7. Cabin - the cabin number.\n8. Emarked - port of embarkation where C is Cherbourg, Q is Queenstown and S is Southampton.\n9. Ticket - ticket number.\n10. Name - passengers name.\n11. Survived - target variable where 0 is not survived and 1 is survived\n\n\n**Variable Notes**\n* **pclass**: A proxy for socio-economic status (SES)\n * 1st = Upper\n * 2nd = Middle\n * 3rd = Lower\n\n\n* **age**: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5\n\n\n* **sibsp**: The dataset defines family relations in this way...\n * Sibling = brother, sister, stepbrother, stepsister\n * Spouse = husband, wife (mistresses and fianc\u00e9s were ignored)\n \n\n* **parch**: The dataset defines family relations in this way...\n * Parent = mother, father\n * Child = daughter, son, stepdaughter, stepson\n * Some children travelled only with a nanny, therefore parch=0 for them.\n \n \n \n**Types Of Features**\n- Categorical Features:\n   - A categorical variable is one that has two or more categories and each value in that feature can be categorised by them.For example, gender is a categorical variable having two categories (male and female). Now we cannot sort or give any ordering to such variables. They are also known as Nominal Variables.\n   - Categorical Features in the dataset: Sex,Embarked.\n\n- Ordinal Features:\n   - An ordinal variable is similar to categorical values, but the difference between them is that we can have relative ordering or sorting between the values. For eg: If we have a feature like Height with values Tall, Medium, Short, then Height is a ordinal variable. Here we can have a relative sort in the variable.\n   - Ordinal Features in the dataset: PClass\n\n- Continous Feature:\n   - A feature is said to be continous if it can take values between any two points or between the minimum or maximum values in the features column.\n   - Continous Features in the dataset: Age\n\"\"\"\n\"\"\"\n# **Analysis**\n\"\"\"\n\"\"\"\nThe first thing we are going to check is the distribution of the target feature. It's important to know if the class is balanced or not. If so, we would probably have to handle it.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 5), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\n\nbackground_color = \"#f6f5f5\"\n\n# background_color = \"#f6f5f5\"\ncolumn = 'Survived'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\nax0 = fig.add_subplot(gs[0, 0])\nfor s in [\"right\", \"top\"]:\n    ax0.spines[s].set_visible(False)\nax0.set_facecolor(background_color)\nax0.tick_params(axis = \"y\", which = \"both\", left = False)\nax0.text(-1, 83, 'Survival Rate on the training data', color='black', fontsize=7, ha='left', va='bottom', weight='bold')\n# ax0.text(-1, 82, 'Survival Rate ', color='#292929', fontsize=5, ha='left', va='top')\n# ax0.text(1.18, 73.3, 'for age and fare', color='#292929', fontsize=4, ha='left', va='bottom')\nax0_sns = sns.barplot(ax=ax0, x=temp_train['index'], y=temp_train[column]\/1000, zorder=2)\nax0_sns.set_xlabel(\"Survived\",fontsize=5, weight='bold')\nax0_sns.set_ylabel('')\nax0.yaxis.set_major_formatter(ticker.PercentFormatter())\nax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax0_sns.tick_params(labelsize=5)\nax0_sns.legend(['Survived', 'Not Survived'], ncol=2, facecolor=background_color, edgecolor=background_color, fontsize=4, bbox_to_anchor=(-0.26, 1.3), loc='upper left')\nleg = ax0_sns.get_legend()\nleg.legendHandles[0].set_color('#eeb977')\nleg.legendHandles[1].set_color('lightgray')\n\"\"\"\n#### **Obeservations :**\n- #### There are 57,226 of Synthanic passengers not survived \n- #### 42,774 survived the accident\n- #### Converted to survival rate of 57.2% for not survived and 42.8% for survived\n\"\"\"\n\"\"\"\n# **Checking the Null Values :**\n\"\"\"\nnan_data = (train_df.isna().sum().sort_values(ascending=False) \/ len(train_df) * 100)[:6]\nnan_data_1 = pd.DataFrame(data = nan_data,columns=[\"Missing % \"]).reset_index()\na4_dims = (11.7, 8.27)\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(2, 2), facecolor='#f6f5f5')\ngs = fig.add_gridspec(1, 1)\ngs.update(wspace=0.4, hspace=0.8)\n\nbackground_color = \"#f6f5f5\"\n\ncolumn = 'Missing % '\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = nan_data_1\nax0 = fig.add_subplot(gs[0, 0])\nfor s in [\"right\", \"top\"]:\n    ax0.spines[s].set_visible(False)\nax0.set_facecolor(background_color)\n\nax0.tick_params(axis = \"y\", which = \"both\", left = False)\nax0.text(-1, 5, '% of Missing values for Training Data', color='black', fontsize=7, ha='left', va='bottom', weight='bold')\n# ax0.text(-1, 5, 'Survival Rate ', color='#292929', fontsize=5, ha='left', va='top')\nax0_sns = sns.barplot(ax=ax0, x=temp_train['index'], y=temp_train[column], zorder=2 )\nax0_sns.set_xlabel(\"Column Names\",fontsize=4, weight='bold')\nax0_sns.set_ylabel(\"Percentage\",fontsize=4, weight='bold')\nax0.yaxis.set_major_formatter(ticker.PercentFormatter())\nax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax0_sns.tick_params(labelsize=2)\n\n\n\"\"\"\n# **Now comparing the data between the Training and the Test data!**\n\nThis section will try to explore and compare features in the train and test dataset. It should be noted that some features are not the same between train and test dataset as can be seen more detail on each sub-sections.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 5), facecolor='#f6f5f5')\ngs = fig.add_gridspec(4, 3)\ngs.update(wspace=0.4, hspace=0.8)\n\nbackground_color = \"#f6f5f5\"\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\n\ncolumn = 'Pclass'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax0 = fig.add_subplot(gs[0, 0])\nfor s in [\"right\", \"top\"]:\n    ax0.spines[s].set_visible(False)\nax0.set_facecolor(background_color)\nax0.tick_params(axis = \"y\", which = \"both\", left = False)\nax0.text(-1.2, 88, 'Features comparison', color='black', fontsize=7, ha='left', va='bottom', weight='bold')\nax0.text(-1.2, 87, 'Comparing features distribution between train and test dataset', color='#292929', fontsize=5, ha='left', va='top')\nax0_sns = sns.barplot(ax=ax0, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax0_sns.set_xlabel(\"Ticket Class\",fontsize=5, weight='bold')\nax0_sns.set_ylabel('')\nax0.yaxis.set_major_formatter(ticker.PercentFormatter())\nax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax0_sns.tick_params(labelsize=5)\nax0_sns.legend(ncol=2, facecolor=background_color, edgecolor=background_color, fontsize=4, bbox_to_anchor=(0.46, 1.22))\n\ncolumn = 'Sex'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax1 = fig.add_subplot(gs[0, 1])\nfor s in [\"right\", \"top\"]:\n    ax1.spines[s].set_visible(False)\nax1.set_facecolor(background_color)\nax1.legend(prop={'size': 3})\nax1.tick_params(axis = \"y\", which = \"both\", left = False)\nax1_sns = sns.barplot(ax=ax1, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax1_sns.set_xlabel('Sex', fontsize=5, weight='bold')\nax1_sns.set_ylabel('')\nax1.yaxis.set_major_formatter(ticker.PercentFormatter())\nax1_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax1_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax1_sns.tick_params(labelsize=5)\nax1_sns.get_legend().remove()\n\ncolumn = 'Age'\nax3 = fig.add_subplot(gs[0, 2])\nfor s in [\"right\", \"top\"]:\n    ax3.spines[s].set_visible(False)\nax3.set_facecolor(background_color)\nax3.legend(prop={'size': 3})\nax3.tick_params(axis = \"y\", which = \"both\", left = False)\nax3_sns = sns.kdeplot(ax=ax3, x=train_df['Age'], zorder=2, shade=True)\nax3_sns = sns.kdeplot(ax=ax3, x=test_df['Age'], zorder=2, shade=True)\nax3_sns.set_xlabel('Age', fontsize=5, weight='bold')\nax3_sns.set_ylabel('')\nax3_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax3_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax3_sns.tick_params(labelsize=5)\nax3_sns.get_legend().remove()\n\ncolumn = 'SibSp'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax4 = fig.add_subplot(gs[1, 0])\nfor s in [\"right\", \"top\"]:\n    ax4.spines[s].set_visible(False)\nax4.set_facecolor(background_color)\nax4.legend(prop={'size': 3})\nax4.tick_params(axis = \"y\", which = \"both\", left = False)\nax4_sns = sns.barplot(ax=ax4, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax4_sns.set_xlabel('Siblings \/ spouse', fontsize=5, weight='bold')\nax4_sns.set_ylabel('')\nax4.yaxis.set_major_formatter(ticker.PercentFormatter())\nax4_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax4_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax4_sns.tick_params(labelsize=5)\nax4_sns.get_legend().remove()\n\ncolumn = 'Parch'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax5 = fig.add_subplot(gs[1, 1])\nfor s in [\"right\", \"top\"]:\n    ax5.spines[s].set_visible(False)\nax5.set_facecolor(background_color)\nax5.legend(prop={'size': 3})\nax5.tick_params(axis = \"y\", which = \"both\", left = False)\nax5_sns = sns.barplot(ax=ax5, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax5_sns.set_xlabel('Parents \/ children', fontsize=5, weight='bold')\nax5_sns.set_ylabel('')\nax5.yaxis.set_major_formatter(ticker.PercentFormatter())\nax5_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax5_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax5_sns.tick_params(labelsize=5)\nax5_sns.get_legend().remove()\n\ncolumn = 'Fare'\nax6 = fig.add_subplot(gs[1, 2])\nfor s in [\"right\", \"top\"]:\n    ax6.spines[s].set_visible(False)\nax6.set_facecolor(background_color)\nax6.legend(prop={'size': 3})\nax6.tick_params(axis = \"y\", which = \"both\", left = False)\nax6_sns = sns.kdeplot(ax=ax6, x=train_df['Fare'], zorder=2, shade=True)\nax6_sns = sns.kdeplot(ax=ax6, x=test_df['Fare'], zorder=2, shade=True)\nax6_sns.set_xlabel('Fare', fontsize=5, weight='bold')\nax6_sns.set_ylabel('')\nax6_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax6_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax6_sns.tick_params(labelsize=5)\nax6_sns.get_legend().remove()\n\ntrain_df[\"Cabin\"] = train_df[\"Cabin\"].fillna(\"No\")\ntrain_df[\"Cabin_code\"] = train_df[\"Cabin\"].str[0]\ntest_df[\"Cabin\"] = test_df[\"Cabin\"].fillna(\"No\")\ntest_df[\"Cabin_code\"] = test_df[\"Cabin\"].str[0]\n\ncolumn = 'Cabin_code'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax7 = fig.add_subplot(gs[2, 0])\nfor s in [\"right\", \"top\"]:\n    ax7.spines[s].set_visible(False)\nax7.set_facecolor(background_color)\nax7.legend(prop={'size': 3})\nax7.tick_params(axis = \"y\", which = \"both\", left = False)\nax7_sns = sns.barplot(ax=ax7, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax7_sns.set_xlabel('Cabin', fontsize=5, weight='bold')\nax7_sns.set_ylabel('')\nax7.yaxis.set_major_formatter(ticker.PercentFormatter())\nax7_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax7_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax7_sns.tick_params(labelsize=5)\nax7_sns.get_legend().remove()\n\ntrain_df[\"Embarked\"] = train_df[\"Embarked\"].fillna(\"N\")\ntest_df[\"Embarked\"] = test_df[\"Embarked\"].fillna(\"N\")\n\ncolumn = 'Embarked'\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\ntemp_train['source'] = 'train'\ntemp_test = pd.DataFrame(test_df[column].value_counts()).reset_index(drop=False)\ntemp_test['source'] = 'test'\ntemp_combine = pd.concat([temp_train, temp_test], axis=0)\nax8 = fig.add_subplot(gs[2, 1])\nfor s in [\"right\", \"top\"]:\n    ax8.spines[s].set_visible(False)\nax8.set_facecolor(background_color)\nax8.legend(prop={'size': 3})\nax8.tick_params(axis = \"y\", which = \"both\", left = False)\nax8_sns = sns.barplot(ax=ax8, x=temp_combine['index'], y=temp_combine[column]\/1000, zorder=2, hue=temp_combine['source'])\nax8_sns.set_xlabel('Port', fontsize=5, weight='bold')\nax8_sns.set_ylabel('')\nax8.yaxis.set_major_formatter(ticker.PercentFormatter())\nax8_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax8_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax8_sns.tick_params(labelsize=5)\nax8_sns.get_legend().remove()\n\nplt.show()\n\"\"\"\n**Pclass**\n\n1. Proportions between each classes are different in the train and test:\n 1. Class 3 in train dataset contributes 40% while in test dataset, it has a contribution above 60%.\n 2. Class 2 is at a very low of 10% in test dataset while in train dataset, it contributes around 30%.\n 3. Class 1 in the train and test dataset are quite the same but it is higher in the train dataset.\n\n\n**Sex**\n\n1. Proportions between each classes are different in the train and test:\n - female contributed more than 40% in train dataset while in test dataset female only contributed 30% of total dataset.\n - male contributed more than 50% in the train and test dataset.\n\n\n**Age**\n\n1. Distribution between train and test dataset are different especially on range of 15-40.\n2. There are missing value in the train and test dataset, they are 3,292 and 3,487, respectively.\n\n\n**SibSp**\n\n1. Number of siblings \/ spouses can be categorize into 7 categories, this feature can be treated as a continuous or categorical and see how the model performed.\n2. There is 10% differences on passenger that travel with 1 sibbling \/ spose between train and test dataset.\n3. The highest \/ maximum number of sibblings \/ spouses that is going aboard with the passengers is 8 people and the lowest is traveling without any sibblings \/ spouses.\n4. Most of Synthanic passenger don't travel with their sibblings \/ sposes.\n\n\n**Parch**\n\n1. Number of parents \/ children can be categorize into 8 categories, this feature can also be treated as a continuous or categorical.\n2. The highest number of parents \/ children is 8 people and the lowest is 0 meaning the passengers is traveling without their parents \/ childrens.\n3. This features strenghten the idea that most of the Synthanic passengers are traveling alone.\n\n\n**Fare**\n\n1. Fare distribution between train and test dataset are quite resemble each other, though it's not perfect especially in the lower fare.\n2. The highest fare in train dataset is 744.66 while in test dataset is 680.7.\n3. The lowest fare in test dataset is 0.05 and 0.68 in the train dataset.\n4. The average fare is 43.9 in train dataset and 45.4 in test dataset, not a far gap between them.\n5. Missing value in this feature are 134 in train dataset and 133 in test dataset.\n\n\n**Cabin**\n\n1. Cabin numbers can extracted by taking the first letter in the feature.\n2. Be aware that this feature has the highest number of missing value of 67,866 in train dataset and 70,831 in test dataset, meaaning it's almost 70% of the information are missing. A new cabin category N is created to address passengers without cabin number.\n3. Cabin can be categorize into 9 categories, this feature can be treated as a continuous or categorical and see how the model performed.\n4. There is quite a distinct imbalance data between train and test dataset in cabin C.\n \n\n**Embarked**\n\n1. A new embarked category N is created to address passengers without port of Embarkation.\n2. Most of Synthanic passengers are embarked from Southampton which contributes almost 70% of the passengers.\n3. There are 205 missing values in train dataset and 277 missing values in the test dataset.\n\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 4)\ngs.update(wspace=0.4, hspace=0.8)\n\nbackground_color = \"#f6f5f5\"\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ncolumn = 'Sex'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax2 = fig.add_subplot(gs[0, 2])\nfor s in [\"right\", \"top\"]:\n    ax2.spines[s].set_visible(False)\nax2.set_facecolor(background_color)\nax2.tick_params(axis = \"y\", which = \"both\", left = False)\nax2.text(-1, 35, 'Survival Rate for Males and Females', color='black', fontsize=4, ha='left', va='bottom', weight='bold')\nax2_sns = sns.barplot(ax=ax2, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax2_sns.set_xlabel('')\nax2_sns.set_ylabel('')\nax2.yaxis.set_major_formatter(ticker.PercentFormatter())\nax2_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax2_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax2_sns.tick_params(labelsize=5)\nplt.show()\n\"\"\"\nFemale has higher chance to survived at 31.2% compared to male, this may also be the result of lifeboat priority for female than male.\nMale has survival rate at 11.5% which is a far below Female.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 4)\ngs.update(wspace=0.4, hspace=0.8)\n\ncolumn = 'Pclass'\ncolor_map = ['#eeb977', 'lightgray', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax1 = fig.add_subplot(gs[0, 1])\nfor s in [\"right\", \"top\"]:\n    ax1.spines[s].set_visible(False)\nax1.set_facecolor(background_color)\nax1.tick_params(axis = \"y\", which = \"both\", left = False)\nax1.text(-1, 20, 'Survival Rate for Different Ticket Classes', color='black', fontsize=4, ha='left', va='bottom', weight='bold')\nax1_sns = sns.barplot(ax=ax1, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax1_sns.set_xlabel(\"Ticket Class\",fontsize=5, weight='bold')\nax1_sns.set_ylabel('')\nax1.yaxis.set_major_formatter(ticker.PercentFormatter())\nax1_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax1_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax1_sns.tick_params(labelsize=5)\n\"\"\"\n**Pclass**\n\nTicket class 1 has the highest chance to survived with survival rate at 17.6% followed by class 2 with 15% and class 3 with 10.1%.\nHigher ticket class has a higher chance to survived, this may be a result of lifeboat priority based on ticket class.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 3)\ngs.update(wspace=0.4, hspace=0.8)\n\n\ncolumn = 'Embarked'\ncolor_map = ['lightgray' for _ in range(4)]\ncolor_map[3] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax8 = fig.add_subplot(gs[2, 2])\nfor s in [\"right\", \"top\"]:\n    ax8.spines[s].set_visible(False)\nax8.set_facecolor(background_color)\nax8.tick_params(axis = \"y\", which = \"both\", left = False)\nax8.text(-1, 25, 'Survival Rate for Different Embarkmet Ports', color='black', fontsize=4, ha='left', va='bottom', weight='bold')\nax8_sns = sns.barplot(ax=ax8, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax8_sns.set_xlabel(\"Port\",fontsize=5, weight='bold')\nax8_sns.set_ylabel('')\nax8.yaxis.set_major_formatter(ticker.PercentFormatter())\nax8_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax8_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax8_sns.tick_params(labelsize=5)\n\"\"\"\n**Embarked**\n\n- Passengers that embarked from Southampton have the highest chance to survived which is above 20%.\n- The second highest survival rate are passengers that embarked from Cherbourg with 15% survival rate.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\n\ncolumn = 'Cabin_code'\ncolor_map = ['lightgray' for _ in range(9)]\ncolor_map[7] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax7 = fig.add_subplot(gs[1, 1])\nfor s in [\"right\", \"top\"]:\n    ax7.spines[s].set_visible(False)\nax7.set_facecolor(background_color)\nax7.tick_params(axis = \"y\", which = \"both\", left = False)\nax7.text(0, 25, 'Survival Rate for Different Cabins', color='black', fontsize=5, ha='left', va='bottom', weight='bold')\nax7_sns = sns.barplot(ax=ax7, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax7_sns.set_xlabel(\"Cabin\",fontsize=5, weight='bold')\nax7_sns.set_ylabel('')\nax7.yaxis.set_major_formatter(ticker.PercentFormatter())\nax7_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax7_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax7_sns.tick_params(labelsize=5)\n\"\"\"\n**Cabin**\n\n- There are many missing values in the cabin number which it hard to make an analysis on the survival rate.\n- Passengers with unknown cabin (N) has the highest survival rate which is above 20% compared to others.\n- Passengers with cabin C has the second highest survival rate that is above 5%.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\n\ncolumn = 'Fare'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax6 = fig.add_subplot(gs[2, 0])\nfor s in [\"right\", \"top\"]:\n    ax6.spines[s].set_visible(False)\nax6.set_facecolor(background_color)\nax6.tick_params(axis = \"y\", which = \"both\", left = False)\nax6.text(-2, .037, 'Survival Rate for Fares', color='black', fontsize=6, ha='left', va='bottom', weight='bold')\nax6_sns = sns.kdeplot(ax=ax6, x=train_df[train_df['Survived']==1]['Fare'], zorder=2, shade=True)\nax6_sns = sns.kdeplot(ax=ax6, x=train_df[train_df['Survived']==0]['Fare'], zorder=2, shade=True)\nax6_sns.set_xlabel(\"Fare\",fontsize=5, weight='bold')\nax6_sns.set_ylabel('')\nax6_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax6_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax6_sns.tick_params(labelsize=5)\n\"\"\"\n**Fare**\n\n- Consistent with ticket class, passengers with lower fare have a lower chance to survived.\n- It's expected that passengers that buy a low fare get a lower ticket class but further analysis will be needed to explore more.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\n\ncolumn = 'Parch'\ncolor_map = ['lightgray' for _ in range(8)]\ncolor_map[0] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax5 = fig.add_subplot(gs[1, 1])\nfor s in [\"right\", \"top\"]:\n    ax5.spines[s].set_visible(False)\nax5.set_facecolor(background_color)\nax5.tick_params(axis = \"y\", which = \"both\", left = False)\nax5.text(0, 33, 'Survival Rate for Parch', color='black', fontsize=6, ha='left', va='bottom', weight='bold')\nax5_sns = sns.barplot(ax=ax5, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax5_sns.set_xlabel(\"Parents \/ children\",fontsize=5, weight='bold')\nax5_sns.set_ylabel('')\nax5.yaxis.set_major_formatter(ticker.PercentFormatter())\nax5_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax5_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax5_sns.tick_params(labelsize=5)\n\"\"\"\n**Parch**\n\n- As stated earlier, that most of the passengers in Synthanic are travel alone, this also make the survival rate for passenger that travel without parents \/ children are higher.\n- Survival rate for passengers that travel without parents \/ children is almost 30% which is almost the same with the survival rate for passenger that travel without siblings \/ spouses.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\ncolumn = 'SibSp'\ncolor_map = ['lightgray' for _ in range(7)]\ncolor_map[0] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax4 = fig.add_subplot(gs[1, 1])\nfor s in [\"right\", \"top\"]:\n    ax4.spines[s].set_visible(False)\nax4.set_facecolor(background_color)\nax4.tick_params(axis = \"y\", which = \"both\", left = False)\nax4.text(0, 33, 'Survival Rate for SibSp', color='black', fontsize=6, ha='left', va='bottom', weight='bold')\nax4_sns = sns.barplot(ax=ax4, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax4_sns.set_xlabel(\"Siblings \/ spouses\",fontsize=5, weight='bold')\nax4_sns.set_ylabel('')\nax4.yaxis.set_major_formatter(ticker.PercentFormatter())\nax4_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax4_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax4_sns.tick_params(labelsize=5)\n\"\"\"\n**SibSp**\n\n- Most of the passengers in Synthanic are travel alone, this make the survival rate for passengers without siblings \/ spouses higher than passengers with siblings \/ spouses.\n- Survival rate for passengers without siblings \/ spouses are more than 30%.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 6), facecolor='#f6f5f5')\ngs = fig.add_gridspec(3, 2)\ngs.update(wspace=0.4, hspace=0.8)\n\ncolumn = 'Age'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax3 = fig.add_subplot(gs[1, 0])\nfor s in [\"right\", \"top\"]:\n    ax3.spines[s].set_visible(False)\nax3.set_facecolor(background_color)\nax3.tick_params(axis = \"y\", which = \"both\", left = False)\nax3.text(-2, .037, 'Survival Rate for Age', color='black', fontsize=6, ha='left', va='bottom', weight='bold')\n\nax3_sns = sns.kdeplot(ax=ax3, x=train_df[train_df['Survived']==1]['Age'], zorder=2, shade=True)\nax3_sns = sns.kdeplot(ax=ax3, x=train_df[train_df['Survived']==0]['Age'], zorder=2, shade=True)\nax3_sns.set_xlabel(\"Age\",fontsize=5, weight='bold')\nax3_sns.set_ylabel('')\nax3_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax3_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax3_sns.tick_params(labelsize=5)\n\n\"\"\"\n**Age**\n\nPassengers with age 15-40 have a lower chance to survived while older passengers at age 40 and above have a higher probability to survived, this may also due to lifeboat priority for older people.\n\"\"\"\nplt.rcParams['figure.dpi'] = 300\nfig = plt.figure(figsize=(5, 5), facecolor='#f6f5f5')\ngs = fig.add_gridspec(4, 3)\ngs.update(wspace=0.4, hspace=0.8)\n\nbackground_color = \"#f6f5f5\"\n\ncolumn = 'Survived'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = pd.DataFrame(train_df[column].value_counts()).reset_index(drop=False)\nax0 = fig.add_subplot(gs[0, 0])\nfor s in [\"right\", \"top\"]:\n    ax0.spines[s].set_visible(False)\nax0.set_facecolor(background_color)\nax0.tick_params(axis = \"y\", which = \"both\", left = False)\nax0.text(-1, 83, 'Survival Rate', color='black', fontsize=7, ha='left', va='bottom', weight='bold')\nax0.text(-1, 82, 'Survival rate on each individual feature', color='#292929', fontsize=5, ha='left', va='top')\nax0.text(1.18, 73.3, 'for age and fare', color='#292929', fontsize=4, ha='left', va='top')\nax0_sns = sns.barplot(ax=ax0, x=temp_train['index'], y=temp_train[column]\/1000, zorder=2)\nax0_sns.set_xlabel(\"Survived\",fontsize=5, weight='bold')\nax0_sns.set_ylabel('')\nax0.yaxis.set_major_formatter(ticker.PercentFormatter())\nax0_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax0_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax0_sns.tick_params(labelsize=5)\nax0_sns.legend(['Survived', 'Not Survived'], ncol=2, facecolor=background_color, edgecolor=background_color, fontsize=4, bbox_to_anchor=(-0.26, 1.3), loc='upper left')\nleg = ax0_sns.get_legend()\nleg.legendHandles[0].set_color('#eeb977')\nleg.legendHandles[1].set_color('lightgray')\n\ncolumn = 'Pclass'\ncolor_map = ['#eeb977', 'lightgray', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax1 = fig.add_subplot(gs[0, 1])\nfor s in [\"right\", \"top\"]:\n    ax1.spines[s].set_visible(False)\nax1.set_facecolor(background_color)\nax1.tick_params(axis = \"y\", which = \"both\", left = False)\nax1_sns = sns.barplot(ax=ax1, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax1_sns.set_xlabel(\"Ticket Class\",fontsize=5, weight='bold')\nax1_sns.set_ylabel('')\nax1.yaxis.set_major_formatter(ticker.PercentFormatter())\nax1_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax1_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax1_sns.tick_params(labelsize=5)\n\ncolumn = 'Sex'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax2 = fig.add_subplot(gs[0, 2])\nfor s in [\"right\", \"top\"]:\n    ax2.spines[s].set_visible(False)\nax2.set_facecolor(background_color)\nax2.tick_params(axis = \"y\", which = \"both\", left = False)\nax2_sns = sns.barplot(ax=ax2, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax2_sns.set_xlabel(\"Sex\",fontsize=5, weight='bold')\nax2_sns.set_ylabel('')\nax2.yaxis.set_major_formatter(ticker.PercentFormatter())\nax2_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax2_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax2_sns.tick_params(labelsize=5)\n\ncolumn = 'Age'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax3 = fig.add_subplot(gs[1, 0])\nfor s in [\"right\", \"top\"]:\n    ax3.spines[s].set_visible(False)\nax3.set_facecolor(background_color)\nax3.tick_params(axis = \"y\", which = \"both\", left = False)\nax3_sns = sns.kdeplot(ax=ax3, x=train_df[train_df['Survived']==1]['Age'], zorder=2, shade=True)\nax3_sns = sns.kdeplot(ax=ax3, x=train_df[train_df['Survived']==0]['Age'], zorder=2, shade=True)\nax3_sns.set_xlabel(\"Age\",fontsize=5, weight='bold')\nax3_sns.set_ylabel('')\nax3_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax3_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax3_sns.tick_params(labelsize=5)\n\ncolumn = 'SibSp'\ncolor_map = ['lightgray' for _ in range(7)]\ncolor_map[0] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax4 = fig.add_subplot(gs[1, 1])\nfor s in [\"right\", \"top\"]:\n    ax4.spines[s].set_visible(False)\nax4.set_facecolor(background_color)\nax4.tick_params(axis = \"y\", which = \"both\", left = False)\nax4_sns = sns.barplot(ax=ax4, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax4_sns.set_xlabel(\"Siblings \/ spouses\",fontsize=5, weight='bold')\nax4_sns.set_ylabel('')\nax4.yaxis.set_major_formatter(ticker.PercentFormatter())\nax4_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax4_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax4_sns.tick_params(labelsize=5)\n\ncolumn = 'Parch'\ncolor_map = ['lightgray' for _ in range(8)]\ncolor_map[0] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax5 = fig.add_subplot(gs[1, 2])\nfor s in [\"right\", \"top\"]:\n    ax5.spines[s].set_visible(False)\nax5.set_facecolor(background_color)\nax5.tick_params(axis = \"y\", which = \"both\", left = False)\nax5_sns = sns.barplot(ax=ax5, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax5_sns.set_xlabel(\"Parents \/ children\",fontsize=5, weight='bold')\nax5_sns.set_ylabel('')\nax5.yaxis.set_major_formatter(ticker.PercentFormatter())\nax5_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax5_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax5_sns.tick_params(labelsize=5)\n\ncolumn = 'Fare'\ncolor_map = ['#eeb977', 'lightgray']\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax6 = fig.add_subplot(gs[2, 0])\nfor s in [\"right\", \"top\"]:\n    ax6.spines[s].set_visible(False)\nax6.set_facecolor(background_color)\nax6.tick_params(axis = \"y\", which = \"both\", left = False)\nax6_sns = sns.kdeplot(ax=ax6, x=train_df[train_df['Survived']==1]['Fare'], zorder=2, shade=True)\nax6_sns = sns.kdeplot(ax=ax6, x=train_df[train_df['Survived']==0]['Fare'], zorder=2, shade=True)\nax6_sns.set_xlabel(\"Fare\",fontsize=5, weight='bold')\nax6_sns.set_ylabel('')\nax6_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax6_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax6_sns.tick_params(labelsize=5)\n\ncolumn = 'Cabin_code'\ncolor_map = ['lightgray' for _ in range(9)]\ncolor_map[7] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax7 = fig.add_subplot(gs[2, 1])\nfor s in [\"right\", \"top\"]:\n    ax7.spines[s].set_visible(False)\nax7.set_facecolor(background_color)\nax7.tick_params(axis = \"y\", which = \"both\", left = False)\nax7_sns = sns.barplot(ax=ax7, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax7_sns.set_xlabel(\"Cabin\",fontsize=5, weight='bold')\nax7_sns.set_ylabel('')\nax7.yaxis.set_major_formatter(ticker.PercentFormatter())\nax7_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax7_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax7_sns.tick_params(labelsize=5)\n\ncolumn = 'Embarked'\ncolor_map = ['lightgray' for _ in range(4)]\ncolor_map[3] = '#eeb977'\nsns.set_palette(sns.color_palette(color_map))\ntemp_train = train_df.groupby(column)['Survived'].sum()\nax8 = fig.add_subplot(gs[2, 2])\nfor s in [\"right\", \"top\"]:\n    ax8.spines[s].set_visible(False)\nax8.set_facecolor(background_color)\nax8.tick_params(axis = \"y\", which = \"both\", left = False)\nax8_sns = sns.barplot(ax=ax8, x=temp_train.index, y=temp_train\/1000, zorder=2)\nax8_sns.set_xlabel(\"Port\",fontsize=5, weight='bold')\nax8_sns.set_ylabel('')\nax8.yaxis.set_major_formatter(ticker.PercentFormatter())\nax8_sns.grid(which='major', axis='x', zorder=0, color='#EEEEEE')\nax8_sns.grid(which='major', axis='y', zorder=0, color='#EEEEEE')\nax8_sns.tick_params(labelsize=5)\n\"\"\"\n## Final EDA Observations\n\n**Survived**\n\nThere are 57,226 of Synthanic passengers not survived and 42,774 survived the accident, converted to survival rate of 57.2% for not survived and 42.8% for survived.\n\n\n**Pclass**\n\n- Ticket class 1 has the highest chance to survived with survival rate at 17.6% followed by class 2 with 15% and class 3 with 10.1%.\n- Higher ticket class has a higher chance to survived, this may be a result of lifeboat priority based on ticket class.\n\n\n**Sex**\n\n- Female has higher chance to survived at 31.2% compared to male, this may also be the result of lifeboat priority for female than male.\n- Male has survival rate at 11.5% which is a far below Female.\n\n\n**Age**\n\n- Passengers with age 15-40 have a lower chance to survived while older passengers at age 40 and above have a higher probability to survived, this may also due to lifeboat priority for older people.\n\n\n**SibSp**\n\n- Most of the passengers in Synthanic are travel alone, this make the survival rate for passengers without siblings \/ spouses higher than passengers with siblings \/ spouses.\n- Survival rate for passengers without siblings \/ spouses are more than 30%.\n\n\n**Parch**\n\n- As stated earlier, that most of the passengers in Synthanic are travel alone, this also make the survival rate for passenger that travel without parents \/ children are higher.\n- Survival rate for passengers that travel without parents \/ children is almost 30% which is almost the same with the survival rate for passenger that travel without siblings \/ spouses.\n\n\n**Fare**\n\n- Consistent with ticket class, passengers with lower fare have a lower chance to survived.\n- It's expected that passengers that buy a low fare get a lower ticket class but further analysis will be needed to explore more.\n\n\n**Cabin**\n\n- There are many missing values in the cabin number which it hard to make an analysis on the survival rate.\n- Passengers with unknown cabin (N) has the highest survival rate which is above 20% compared to others.\n- Passengers with cabin C has the second highest survival rate that is above 5%.\n\n\n**Embarked**\n\n- Passengers that embarked from Southampton have the highest chance to survived which is above 20%.\n- The second highest survival rate are passengers that embarked from Cherbourg with 15% survival rate.\n\"\"\"\n\"\"\"\n# Model\n\"\"\"\n\"\"\"\n**CatBoost** is a machine learning algorithm that uses gradient boosting on decision trees. It is available as an open source library.\n\nCatBoost supports training on GPUs.\n\nTraining on GPU is non-deterministic, because the order of floating point summations is non-deterministic in this implementation.\n\nChoose the implementation for more details on the parameters that are required to start training on GPU.\n\n\nhttps:\/\/catboost.ai\/docs\/concepts\/python-reference_catboostclassifier.html#python-reference_catboostclassifier\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom catboost import CatBoostClassifier, Pool\nfrom sklearn.model_selection import  StratifiedKFold\nfrom sklearn import metrics\nctypes = {\n    'Survived':np.int8,\n    'Pclass':np.int8,\n    'Name':np.str,\n    'Embarked':np.str,  \n    'SibSp':np.int8,\n    'Parch':np.int8,\n}\n\n           \ntrain = pd.read_csv('..\/input\/tabular-playground-series-apr-2021\/train.csv',dtype=ctypes,index_col='PassengerId')\ntest = pd.read_csv('..\/input\/tabular-playground-series-apr-2021\/test.csv',dtype=ctypes,index_col='PassengerId')\nsubmission = pd.read_csv('..\/input\/tabular-playground-series-apr-2021\/sample_submission.csv',dtype=ctypes,index_col='PassengerId')\ntrain['Embarked'] = train['Embarked'].fillna('No')\ntest['Embarked'] = test['Embarked'].fillna('No')\n\ntrain['Cabin'] = train['Cabin'].fillna('_')\ntest['Cabin'] = test['Cabin'].fillna('_')\n\ntrain.Ticket = train.Ticket.map(lambda x:str(x).split()[0] if len(str(x).split()) > 1 else 'X')\ntest.Ticket = test.Ticket.map(lambda x:str(x).split()[0] if len(str(x).split()) > 1 else 'X')\n\ntrain['CabinType'] = train['Cabin'].apply(lambda x:x[0])\ntest['CabinType'] = test['Cabin'].apply(lambda x:x[0])\n\ntrain['Age'].fillna(round(train['Age'].mean()), inplace=True,)\ntest['Age'].fillna(round(test['Age'].mean()), inplace=True,)\ntrain['Age'] = train['Age'].apply(round)\ntest['Age'] = test['Age'].apply(round)\ntrain['Age'] = train['Age'].astype(np.int8)\ntest['Age'] = test['Age'].astype(np.int8)\n\n\ntrain['Fare'].fillna(round(train['Fare'].mean()), inplace=True,)\ntest['Fare'].fillna(round(test['Fare'].mean()), inplace=True,)\n\ntrain['FirstName'] = train['Name'].apply(lambda x:x.split(', ')[0])\ntrain['SecondName'] = train['Name'].apply(lambda x:x.split(', ')[1])\n\ntest['FirstName'] = test['Name'].apply(lambda x:x.split(', ')[0])\ntest['SecondName'] = test['Name'].apply(lambda x:x.split(', ')[1])\n\ntrain['n'] = 1\ntest['n'] = 1\n\ngb = train.groupby('FirstName')\ndf_names = gb['n'].sum()\ntrain['SameFirstName'] = train['FirstName'].apply(lambda x:df_names[x])\n\ngb = test.groupby('FirstName')\ndf_names = gb['n'].sum()\ntest['SameFirstName'] = test['FirstName'].apply(lambda x:df_names[x])\n\ntrain['SameFirstName'] = train['SameFirstName'].apply(lambda x:-1 if x>10 else x)\ntest['SameFirstName'] = test['SameFirstName'].apply(lambda x:-1 if x>10 else x)\n\ntrain_female = train[train.Sex=='female']\ntrain_male = train[train.Sex=='male']\ncolumns = ['Pclass',  'Age','Embarked','Parch','SibSp','Fare','CabinType','Ticket','SameFirstName']\ncat_features = ['Pclass','Embarked','CabinType','Ticket',]\n\nmodels_f = []\nnum_folds=9\nfolds = StratifiedKFold(n_splits=num_folds, shuffle=True, random_state=2021) # create folds \nX_train = train_female[columns]\ny_train = train_female['Survived']\nfor n_fold, (train_idx, valid_idx) in enumerate (folds.split(X_train,  y_train)):\n    train_X, train_y = X_train.iloc[train_idx], y_train.iloc[train_idx]\n    valid_X, valid_y = X_train.iloc[valid_idx], y_train.iloc[valid_idx]\n    dataset = Pool(train_X, train_y, cat_features)\n    evalset = Pool(valid_X, valid_y, cat_features)\n    model_female = CatBoostClassifier(\n        task_type=\"GPU\", \n        depth=7,\n        max_ctr_complexity=5,\n        #border_count=1024, \n        iterations=50000,\n        od_wait=500,od_type='Iter',       \n        #l2_leaf_reg=0.01,\n        learning_rate=0.0035,\n        min_data_in_leaf=3\n    \n        )\n    model_female.fit(dataset, plot=False, verbose=500,eval_set=evalset)\n    models_f.append(model_female)\n    y_pred_female = model_female.predict(train_female[columns])\n    print(metrics.accuracy_score(train_female['Survived'], y_pred_female))\ncolumns = ['Pclass',  'Age','Embarked','Parch','SibSp','Fare','CabinType','Ticket']\ncat_features = ['Pclass','Embarked','CabinType','Ticket']\n\nmodels_m = []\nnum_folds=9\nfolds = StratifiedKFold(n_splits=num_folds, shuffle=True, random_state=2021) # create folds \nX_train = train_male[columns]\ny_train = train_male['Survived']\nfor n_fold, (train_idx, valid_idx) in enumerate (folds.split(X_train,  y_train)):\n    train_X, train_y = X_train.iloc[train_idx], y_train.iloc[train_idx]\n    valid_X, valid_y = X_train.iloc[valid_idx], y_train.iloc[valid_idx]\n    dataset = Pool(train_X, train_y, cat_features)\n    evalset = Pool(valid_X, valid_y, cat_features)\n    model_male = CatBoostClassifier(\n        task_type=\"GPU\", \n        depth=6,\n        max_ctr_complexity=15,\n        #border_count=1024, \n        iterations=50000,\n        od_wait=400,od_type='Iter',       \n        #l2_leaf_reg=0.01,\n        learning_rate=0.04,\n        min_data_in_leaf=3\n        )\n    model_male.fit(dataset, plot=False, verbose=500,eval_set=evalset)\n    models_m.append(model_male)\n    y_pred_male = model_male.predict(train_male[columns])\n    print(metrics.accuracy_score(train_male['Survived'], y_pred_male))\n    \n%%time\ncolumns = ['Pclass',  'Age','Embarked','Parch','SibSp','Fare','CabinType','Ticket','SameFirstName']\nm_columns_f = []\nfor idx,m in enumerate(models_f):\n    new_column = 'fm_{}'.format(idx)\n    m_columns_f.append(new_column)\n    test[new_column] = m.predict(test[columns])\n    print(new_column, end=' ')\nprint()\nm_columns_m = []\ncolumns = ['Pclass',  'Age','Embarked','Parch','SibSp','Fare','CabinType','Ticket']\nfor idx,m in enumerate(models_m):\n    new_column = 'm_{}'.format(idx)\n    m_columns_m.append(new_column)\n    test[new_column] = m.predict(test[columns])\n    print(new_column, end=' ')\ndef vote(r, columns):\n    ones = 0\n    zeros = 0\n    for i in columns:\n        if r[i]==0:\n            zeros+=1\n        else:\n            ones+=1\n    if ones>zeros:\n        return 1\n    else:\n        return 0\n\ntest['model_female'] = test.apply(lambda x:vote(x,m_columns_f),axis=1)\ntest['model_male'] = test.apply(lambda x:vote(x,m_columns_m),axis=1)\ndef _s(r):\n    if r.Sex=='male':\n        return r.model_male\n    else:\n        return r.model_female\n    \nsubmission['Survived'] = test.apply(lambda x:_s(x),axis=1)\nsubmission.to_csv('result.csv')\nsubmission['Survived'].mean(), train['Survived'].mean()\n\"\"\"\n**If there are any suggesion for the notebook please comment, that would be helpful. Also please upvote if you liked it! Thank you!!**\n\nSome of my other works:\n\nhttps:\/\/www.kaggle.com\/udbhavpangotra\/tps-apr21-eda-model\nhttps:\/\/www.kaggle.com\/udbhavpangotra\/heart-attacks-extensive-eda-and-visualizations\nhttps:\/\/www.kaggle.com\/udbhavpangotra\/what-do-people-use-youtube-for-in-great-britain\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0375373b0c5c04'}"}
{"id":"104776","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n# Kaggle Titanic \n### Logistic Regression with Python\n\"\"\"\n\"\"\"\n## Step - 1: Frame The Problem \n\nThe sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships.\n\nOne of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.\n\nIn this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy.\n\"\"\"\n\"\"\"\n## Step - 2: Obtain the Data\n\"\"\"\n\"\"\"\n### Import Libraries\n\"\"\"\n!pwd\n!pip install -q  missingno\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport missingno as ms\n%matplotlib inline\n!ls -l\n\"\"\"\nPandas provides two important data types with in built functions to be able to provide extensive capability to handle the data.The datatypes include Series and DataFrames.\n\"\"\"\n\"\"\"\nPandas provides ways to read or get the data from various sources like read_csv,read_excel,read_html etc.The data is read and stored in the form of DataFrames.\n\"\"\"\n!wget -q https:\/\/www.dropbox.com\/s\/8grgwn4b6y25frw\/titanic.csv\n!ls -l\ndata = pd.read_csv(\"..\/input\/train.csv\")\ndata.head(3)\n#to get the last 5 entries of the data\ndata.tail(5)\ntype(data)\ndata.shape\n\"\"\"\nwe have 891 rows and 12 columns\n\"\"\"\ndata.info()\ndata.isnull().sum()\ndata.info()\ndata.describe()\n\"\"\"\nThe statistics shows the variable Age has 177 missing values\n\n\"\"\"\n\"\"\"\n## Step - 3: Analyse the Data\n\"\"\"\nms.matrix(data)\ndata.info()\n\"\"\"\nWe can observe that there are missing values in 'Age', 'Cabin' and 'Embarked'. Lets continue\n\"\"\"\n\"\"\"\n#### Visualization of data with Seaborn\n\"\"\"\nsns.set_style('whitegrid')\nsns.countplot(x='Survived',data=data,palette='RdBu_r')\n\"\"\"\nThe target variable is the Survived column such that if survival = 1, the passenger is alive, otherwise dead.\n\n\"\"\"\n\"\"\"\nThe graph shows the number of dead passengers are higher than the survivals by more than 1\/3.\n\"\"\"\nsns.set_style('whitegrid')\nsns.countplot(x='Survived',hue='Sex',data=data,palette='RdBu_r')\n\"\"\"\nThe above graph also illustrates that female passangers survived by more than 50% of their counterpart male passangers. Thus very few females are dead as compared to males (about 20% of the males who succumbed during the accident) \n\"\"\"\nsns.set_style('whitegrid')\nsns.countplot(x='Survived',hue='Pclass',data = data,palette='rainbow')\n\"\"\"\nPassangers who are onboarded in the lower class had lower chance of survivial and thus around 375 people died from third class while only less than 175 people are dead from both second and third class. This is presumably correct as passangers with higher status are likely to be rescued or are given first priority of safety.  \n\"\"\"\nsns.distplot(data['Fare'])\n#KDE?\n\"\"\"\nThe graph is highly skewed to the left. Most of the passengers pay cheaper tickets and a very few people bought expensive tickets.  \n\"\"\"\ndata['Fare'].hist(color = 'green', bins = 40, figsize = (8,3))\ndata.corr()\nsns.heatmap(data.corr(),cmap='coolwarm')\nplt.title('data.corr()')\nsns.swarmplot\nsns.swarmplot(x='Pclass',y='Age',data=data,palette='Set1')\n\"\"\"\nThe balched feature at the middle shows us more people are concentrated within the rangeof that age\n\"\"\"\ndata['Age'].hist(bins = 40, color = 'darkred', alpha = 0.8)\n\"\"\"\nHere the histogram shows bimodal distribution of age, though age of the passangers seems to concentrate between 15 and 35 years of age. \n\"\"\"\n\"\"\"\n## Step - 4: Feature Engineering\n\nWe want to fill the missing values of the age in the dataset with the average age value for each of the classes. This is called data imputation.\n\"\"\"\ndata.info()\nplt.figure(figsize=(12, 7))\nsns.boxplot(x='Pclass',y='Age',data=data,palette='winter')\ndata['Age'].fillna(28, inplace=True)\ndata['Age'].median()\nms.matrix(data)\ndata['Cabin'].value_counts()\n\"\"\"\nApplying the function.\n\"\"\"\ndata.info()\ndata.drop('Cabin',axis=1, inplace=True)\ndata.head()\ndata['Embarked'].value_counts()\ndata.dropna(inplace = True) # dropping missing embarked.\nms.matrix(data)\ndata.info()\n\"\"\"\n## Converting Catagorical Features\n\nWe'll need to convert categorical features to dummy variables using pandas! Otherwise our machine learning algorithm won't be able to directly take in those features as inputs.\n\"\"\"\ndata['Sex'].value_counts()\nsex = pd.get_dummies(data['Sex'],drop_first=True)\nsex.head()\ndata['Embarked'].value_counts()\nembark = pd.get_dummies(data['Embarked'],drop_first=True)\nembark.head(10)\nsex.head()\nold_data = data.copy()\ndata.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)\ndata.head()\n\ndata = pd.concat([data,sex,embark],axis=1)\ndata.dropna(inplace = True) # dropping missing embarked.data.info()\ndata.info()\ndata.describe()\n\"\"\"\n## Step - 5:Model Selection\n\"\"\"\n\"\"\"\n### Building a Logistic Regression model\n\"\"\"\nX = data.drop('Survived',axis=1)\ny = data['Survived']\ny.shape\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y \n                                                    , test_size=0.20, \n                                                    random_state=42)\nX_test.shape\nlen(y_test)\n178\/889\nX.describe()\nX_train.describe()\ny_train.describe()\nfrom sklearn.linear_model import LogisticRegression\n\n# Build the Model.\nlogmodel = LogisticRegression()\nlogmodel.fit(X_train,y_train) # this is where training happens\nlogmodel.coef_\nlogmodel.intercept_\npredict =  logmodel.predict(X_test)\npredict[:5]\ny_test[:5]\n\"\"\"\nLet's move on to evaluate our model.\n\"\"\"\n\"\"\"\n## Step - 6 : Evaluation\n\"\"\"\n\"\"\"\n### Evaluation\nWe can check precision, recall, f1 - score using classification report!\n\"\"\"\n\"\"\"\n#### Confusion Matrix\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, classification_report\n\"\"\"\n#### Confusion \n\nTrue positive | False positive,\n____|____\n|\nFalse negative | True negative\n\"\"\"\nfrom sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test,predict))\nprint(confusion_matrix(y_test, predict))\n\"\"\"\n#### Precision Score\n\"\"\"\n\"\"\"\nThe precision is the ratio tp \/ (tp + fp) where tp is the number of true positives and fp the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative.\n\nThe best value is 1 and the worst value is 0.\n\"\"\"\nfrom sklearn.metrics import precision_score\nprint(precision_score(y_test,predict))\n\"\"\"\n#### Recall score\n\"\"\"\n\"\"\"\nThe recall is the ratio tp \/ (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples.\n\nThe best value is 1 and the worst value is 0.\n\"\"\"\nfrom sklearn.metrics import recall_score\nprint(recall_score(y_test,predict))\n\"\"\"\n#### f_score\n\"\"\"\n\"\"\"\nThe F1 score can be interpreted as a weighted average of the precision and recall, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score are equal. The formula for the F1 score is: F1 = 2 * (precision * recall) \/ (precision + recall)\n\"\"\"\nfrom sklearn.metrics import f1_score\nprint(f1_score(y_test,predict))\n\"\"\"\nTo get all the above metrics at one go, use the following function:\n\"\"\"\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test,predict))\n\"\"\"\n## Step - 7 : Predict on New Cases\n\"\"\"\n\"\"\"\n### Prediction on Test Data From Kaggle\n\"\"\"\nprod_data=pd.read_csv('..\/input\/test.csv')\nprod_data.info()\nms.matrix(prod_data)\n\"\"\"\n### Data Cleaning\n\"\"\"\n\"\"\"\nThere are inconsistencies in test data.We can use the same graph functions that are used to visualize the train data for test data as well.We use the same data cleaning techniques like removing the cabin column and applying impute_age function on age column on test data.\nBut we cannot remove any rows because kaggle wants same number of rows in submission csv also. So we fill the missing values in fare with mean.\n\"\"\"\nprod_data['Age'].fillna(28, inplace=True)\nms.matrix(prod_data)\nprod_data.drop('Cabin', axis = 1, inplace= True)\nms.matrix(prod_data)\nprod_data.fillna(prod_data['Fare'].mean(),inplace=True)\nprod_data.info()\nms.matrix(prod_data)\nsex = pd.get_dummies(prod_data['Sex'], drop_first=False)\nembark = pd.get_dummies(prod_data['Embarked'], drop_first=False)\nsex = pd.get_dummies(prod_data['Sex'], drop_first=False)\nembark = pd.get_dummies(prod_data['Embarked'], drop_first=False)\n\n\n\n\nprod_data.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)\nprod_data = pd.concat([prod_data,sex,embark],axis=1)\nprod_data.head()\nprod_data.drop([\"female\", 'C'], axis = 1, inplace = True)\nprod_data.head()\nprod_data.info()\nprod_data['Fare'].fillna(prod_data['Fare'].median(), inplace = True)\nprod_data.info()\npredict1=logmodel.predict(prod_data)\npredict1\ndf1=pd.DataFrame(predict1,columns=['Survived'])\ndf2=pd.DataFrame(prod_data['PassengerId'],columns=['PassengerId'])\ndf2.head()\nresult = pd.concat([df2,df1],axis=1)\nresult.head()\nresult.to_csv('result.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'c07fd0ea2f219d'}"}
{"id":"61367","text":"\"\"\"\n# <center>Finding communities in social networks<\/center>\n## <center>Unsupervised and semi-supervised clustering of friends<\/center>\n### <center>Pavel Bogdanov - Software University<\/center>\n\"\"\"\n\"\"\"\n### Abstract\nWe use unweighed undirected graphs to represent connections between people and visualize the clustering between them. Different metrics are used to compare optimal and hierarchical community detection methods. In addition, we explore a semi-supervised location-based approach with label propagation. Finally, we do graph embedding with Node2Vec and use k-means for clustering.\n\"\"\"\n\"\"\"\n### Intro\nHave you ever been in a situation where you introduce your work friends to your old highschool friends and you realize how different those two groups are? Even though they're both your friends, they have no common topics to talk about. Now imagine trying to plan the seating of a wedding. With each friend you consider it becomes increasingly difficult to keep track who's friends with whom and in what group he belong to. This is where unsupervised machine learning comes in. We can simply take a bunch of Facebook friendlists and let the algorithms do all the work for us.\n\n#### Loading dependencies\n\"\"\"\n%matplotlib inline\n!pip install ForceAtlas2\n!pip install node2vec\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport random\nimport re\nimport itertools\nimport os\nimport pickle\nfrom collections import Counter\n\n\nimport networkx as nx\nimport cairocffi\nfrom igraph.drawing.text import TextDrawer\nimport igraph as ig\nimport forceatlas2\nimport community\nfrom node2vec import Node2Vec\n\nfrom geopy import distance\nfrom geopy.geocoders import Nominatim\nfrom geopy.extra.rate_limiter import RateLimiter\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.manifold import TSNE\n\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport ipywidgets as widgets\nfrom ipywidgets import interact, Layout\n\nimport warnings\nME = 'Aaron Wise'\nwarnings.simplefilter('ignore')\n\"\"\"\n### The Data\n\n#### Data aquisition\nYou might be wondering how I aquired all of these friendlists I talk about. Does Facebook have some sort of API that allows us to do just that? It used to, but now in order to make it work you need to have an app and each of your friends needs to give permission to that app. So I must have used a scraper, right? Well yes, but actually no. If I did, I'd infringe Facebook's community standards and probably get blocked. So what, I copied all of these friendlists by hand? Yes, yes I did.\n\n#### Reading the data\nThe data is in a dict-like structure with nodes and edges as keys and (list of) facebook profiles as values.\n\"\"\"\nwith open(\"..\/input\/facebook-friends\/friends.txt\", encoding=\"UTF8\") as file:\n    friends = file.read()\nprint(friends[:123])\nmy_friends_list = re.findall(r'Node\\n\\n(.*)', friends)\nprint('Count of nodes:', len(my_friends_list))\nassert len(my_friends_list) == len(set(my_friends_list)), 'Duplicates detected!'\n\"\"\"\n311 of the people in the dataset are my friends.\n\"\"\"\nprint('Count of nodes with no information:', len(re.findall(r'NA\\n', friends)))\n\"\"\"\n177 of those friends didn't show their friendlist so we have no direct information about their friends.\n\"\"\"\n\"\"\"\n#### Data preprocessing\n\"\"\"\n\"\"\"\nLet's format the data into something more readable, like a pandas dataframe.\n\"\"\"\nsplitted_friends = re.split(r'Node\\n\\n(.*)', friends)\nedge_dict = {}\nnode = None\nfor i in splitted_friends:\n    if splitted_friends.index(i) % 2 == 1:\n        node = i\n    else:\n        edge_dict[node] = i\nprint('Count of elements in dict:', len(edge_dict))\nedge_frame = pd.DataFrame.from_dict(edge_dict, orient='index', columns=['target'])\nedge_frame = edge_frame.reset_index().rename(columns={\"index\": \"source\"})\nedge_frame.head()\n\"\"\"\nEach profile in the `target` column is separated by two new lines.\n\"\"\"\nedge_frame = edge_frame[1::]\nedge_frame.target = edge_frame.target.str.split('\\n\\n')\nedge_frame.head()\n\"\"\"\nNow we can transform the dataframe into a source-target format.\n\"\"\"\nrows = list()\nfor row in edge_frame[['source', 'target']].iterrows():\n    r = row[1]\n    for target in r.target:\n        rows.append((r.source, target))\n\nedge_frame = pd.DataFrame(rows, columns=['source', 'target'])\nedge_frame.head()\nassert len(my_friends_list) == len(edge_frame.source.unique()), 'Records missmatch!'\n\"\"\"\nClean it up a little.\n\"\"\"\nedge_frame = edge_frame[~edge_frame.target.isin(['', 'Edges', 'NA'])].reset_index(drop=True)\nedge_frame.head()\nlen(edge_frame)\n\"\"\"\nThere is more than just the name we can get from each profile. Every bit of information can help us in the clustering process.\n\"\"\"\npattern = r'(?P<relationship>Add Friend|Friend\\nFriends|Friend Request Sent|Acquaintance\\nFriends|Respond to Friend Request)\\n(?P<target>.*)(?P<num_friends>\\n\\d*,?\\d*|\\n.*)?(?P<description>.*)?'\nregex_frame = edge_frame.target.str.extractall(pattern).reset_index()\nregex_frame.tail()\n\"\"\"\nWe can see there is a slight missmatch in the count of the original index with the new one. That means that we missed some records.\n\"\"\"\nmissed_records = edge_frame[~edge_frame.index.isin(regex_frame.level_0)]\nmissed_records.head()\nmissed_records.count()\n\"\"\"\nWe need to modify our regex a bit to catch these records.\n\"\"\"\nmiss_pattern = r'(?P<target>.*)\\n(?P<num_friends>\\d*,?\\d*|\\n.*)?(?P<description>.*)'\nmissed_records = missed_records.target.str.extractall(miss_pattern).reset_index()\nmissed_records.head()\ncombined_regex = pd.concat(objs=[regex_frame, missed_records], sort=False).reset_index(drop=True)\n\"\"\"\nAnd now to check again if there are still records we missed.\n\"\"\"\nmiss_again = edge_frame[~edge_frame.index.isin(combined_regex.level_0)]\nprint('Count of missed records: ', len(miss_again))\n\"\"\"\nThat's a small enough number to be ignored so we can remove these 13 records.\n\"\"\"\nedge_frame = edge_frame[edge_frame.index.isin(combined_regex.level_0)]\nedge_frame.tail()\ncombined_regex.tail()\n\"\"\"\nNow they should be equal in length.\n\"\"\"\nlen(edge_frame) == len(combined_regex)\n\"\"\"\nWe can merge the two so that we can see `source` and `target` in the same dataframe.\n\"\"\"\nedge_frame = pd.merge(left=edge_frame, right=combined_regex, left_on=edge_frame.index, right_on=combined_regex.level_0)\nedge_frame.head()\n\"\"\"\nDrop unused columns.\n\"\"\"\nedge_frame = edge_frame.drop(columns=['key_0', 'target_x', 'level_0', 'match', ])\nedge_frame = edge_frame.rename(columns={'target_y': 'target'})\nedge_frame.head()\n\"\"\"\nRearange the columns for aesthetics.\n\"\"\"\nedge_frame = edge_frame[['source', 'target', 'relationship', 'description', 'num_friends']]\nedge_frame.head()\n\"\"\"\nCheck how much missing values we have.\n\"\"\"\nprint('NA values: \\n\\n', edge_frame.source.isna().value_counts(), '\\n\\n',\n      edge_frame.target.isna().value_counts(), '\\n\\n',\n      edge_frame.description.isna().value_counts(), '\\n\\n',\n      edge_frame.relationship.isna().value_counts())\n\"\"\"\nThe `target` column can't have NA values so we have to remove these records.\n\"\"\"\nedge_frame = edge_frame[edge_frame.target.notna()]\n\"\"\"\nThe rest of them can be empty.\n\"\"\"\nedge_frame.description = edge_frame.description.fillna(' ')\nedge_frame.relationship = edge_frame.relationship.fillna(' ')\n\"\"\"\nWe skipped the `num_friends` column for now because we're going to use it as numeric later.\n\"\"\"\nprint('NA values: \\n\\n', edge_frame.source.isna().value_counts(), '\\n\\n',\n      edge_frame.target.isna().value_counts(), '\\n\\n',\n      edge_frame.description.isna().value_counts(), '\\n\\n',\n      edge_frame.relationship.isna().value_counts())\n\"\"\"\nBut we have a problem. We don't have a unique ID for each profile. That means that if we only look at the names, it will appear as though the most popular people are the ones with the most common name.\n\"\"\"\nedge_frame.target.value_counts().head(20)\n\"\"\"\nIf we take for example the most common name in the dataframe(excluding mine) we will see it's obviously not the same person.\n\"\"\"\nedge_frame[edge_frame.target == 'Ivan Ivanov'].head()\n\"\"\"\nWe already checked my friends for duplicates so we know they are unique to each other. Let's concentrate on their friends in the `target` column.\n\"\"\"\nnode_frame = edge_frame[['target', 'relationship', 'description', 'num_friends']].rename(columns={'target': 'node'})\nnode_frame.head()\n\"\"\"\nFirst we need to separate my friends from other friends with the same name.\n\"\"\"\nfriend_nodes = node_frame[node_frame.node.isin(my_friends_list)]\nfriend_nodes.relationship.value_counts()\nfriend_nodes = friend_nodes[friend_nodes.relationship != 'Add Friend']\nlen(friend_nodes.node.unique())\n\"\"\"\nThen we will give each of my friends a unique ID.\n\"\"\"\nfriend_nodes['node_id'] = friend_nodes.groupby('node').ngroup()\nfriend_nodes.head()\n\"\"\"\nAnd transfer that ID to the `node_frame` such that only my friends will have an ID.\n\"\"\"\nnode_frame['node_id'] = friend_nodes.node_id\nnode_frame.tail()\n\"\"\"\nHere's the tricky part. For some of the records we can't know if they are the same person or not. We simply don't have enough information. So we will give a unique ID to the ones with more information and remove the one where we don't have enough.\n\"\"\"\nnot_friend_nodes = node_frame[node_frame.node_id.isna()]\nnot_friend_nodes.tail()\n\"\"\"\nThe way we're going to differentiate between the friends is by combining all the information we have about them into a single unique string.\n\"\"\"\nnot_friend_nodes = not_friend_nodes.fillna(' ')\nnot_friend_nodes['unique_string'] = not_friend_nodes.node + not_friend_nodes.relationship + not_friend_nodes.description + not_friend_nodes.num_friends\nnot_friend_nodes.tail()\n\"\"\"\nAnd then we can add to the sequence of node ID's we have by looking at the unique string.\n\"\"\"\nnot_friend_nodes.node_id = not_friend_nodes.groupby('unique_string').ngroup() + len(friend_nodes.node_id.unique())\nnot_friend_nodes.tail()\n\"\"\"\nBut that's not enough. Two people with the same common name can still have for example 2 mutual friends with me and live in the same city or study in the same university. So we're going to take only the ones with `num_friends` greater than some number.\n\"\"\"\nnot_friend_nodes.num_friends = not_friend_nodes.num_friends.str.strip()\nnot_friend_nodes.num_friends = not_friend_nodes.num_friends.str.replace(',', '')\nnot_friend_nodes.num_friends = pd.to_numeric(not_friend_nodes.num_friends, errors='coerce')\nnot_friend_nodes.dtypes\n\"\"\"\nI checked the topmost duplicated names on Facebook and did not find different people with the same amount of mutual friends larger than 5. So this is going to be our threshold. Naturally we also need to remove all friends with no description, because we can't differentiate between them as well.\n\"\"\"\nnot_friend_nodes = not_friend_nodes[(not_friend_nodes.num_friends > 5) | \\\n                                    ((not_friend_nodes.num_friends.isna()) & (not_friend_nodes.description!=' '))]\n\"\"\"\nUnfortunately there is no workaround for a case like this, where both the person's name and his description are common, but these records are not that likely and should not affect the final clustering.\n\"\"\"\nnot_friend_nodes[(not_friend_nodes.node=='Ivan Ivanov') & (not_friend_nodes.description=='Varna, Bulgaria')]\n\"\"\"\nNow to combine these ID's with my friends.\n\"\"\"\nnode_frame.node_id = node_frame.node_id.fillna(not_friend_nodes.node_id)\nnode_frame.tail()\n\"\"\"\nAnd finally move up to the original `edge_frame` we were using.\n\"\"\"\nedge_frame['node_id'] = node_frame.node_id\nedge_frame = edge_frame[edge_frame.node_id.notna()]\n\"\"\"\nWe need to give the `source` column an ID as well.\n\"\"\"\nfriend_ids = friend_nodes[['node', 'node_id']].drop_duplicates()\nedge_frame = pd.merge(edge_frame, friend_ids, left_on='source', right_on='node')\nedge_frame = edge_frame.rename(columns={'node_id_y': 'source_id', 'node_id_x': 'target_id'})\nedge_frame = edge_frame.drop(columns=['num_friends', 'relationship', 'node'])\nedge_frame.target_id = edge_frame.target_id.astype('int')\nedge_frame.head()\n\"\"\"\nCheck to see if we have any duplicates.\n\"\"\"\nedge_frame[edge_frame.duplicated(keep=False)].head()\n\"\"\"\nThere is no way to know if these are just the same person with multiple profiles or it's an entirely diferent person, so we will remove them just in case.\n\"\"\"\nedge_frame = edge_frame.drop_duplicates(keep=False)\n\"\"\"\nIn conclusion:\n\"\"\"\nprint('Number of friends that showed their friendlist: ', len(edge_frame.source.unique()))\nprint('Number of usable connections: ', len(edge_frame))\n\"\"\"\n#### Visualising the data\n\"\"\"\n\"\"\"\nWe're going to start simple. Let's do an ego graph that shows only my friends with no additional filtering.\n\"\"\"\nego_frame = edge_frame.copy()\nego_frame = ego_frame[ego_frame.target_id.isin(friend_ids.node_id)]\nego_G = nx.from_pandas_edgelist(df=ego_frame, source='source_id', target='target_id')\nprint(nx.info(ego_G))\nplt.figure(figsize=(30, 30))\nspring_layout = nx.spring_layout(ego_G, seed=42)\n\nnx.draw_networkx_nodes(ego_G, spring_layout, node_color='r', edgecolors='k')\nnx.draw_networkx_edges(ego_G, spring_layout, alpha=0.7)\n\nplt.title('Ego graph with spring layout', fontdict={'fontsize': 40})\nplt.axis('off')\nplt.show()\n\"\"\"\nWe can immediately see 3 major cluster forming even without doing any machine learning. That's good, but we also see a lot of lonely nodes, with just a single edge, connected to me. There's no way of knowing which cluster they belong to at this moment so to make the graph more clear we can simply hide them. And to make the clusters stand out more we can hide my edges too. Note that the nodes and edges we hide are still in the graph affecting the rest of the nodes, we simply don't visualize them.\n\nAs an extra piece of information, we can separate the nodes for which we have a friendlist and the ones for which we don't. That way we can see if the clustering works for nodes with missing information.\n\"\"\"\n# have friendlist\ninfo_nodes = list(ego_frame.source_id.unique())\n\n# don't have friendlist but are connected to my friends\nmystery_nodes = list(ego_frame[~ego_frame.target_id.isin(ego_frame.source_id)].target_id.unique())\n\n# don't have friendlist and are not connected to my friends\nno_info_nodes = [node for node in dict(ego_G.degree).keys() if ego_G.degree[node] < 2]\nplt.figure(figsize=(30, 30))\n\nmy_id = edge_frame[edge_frame.source==ME].source_id.unique()[0]\nnodelist = [n for n in info_nodes if (not n==my_id) and (n not in no_info_nodes)]\nnx.draw_networkx_nodes(ego_G, spring_layout, nodelist=nodelist, node_color='r', edgecolors='k')\nnodelist = [n for n in mystery_nodes if n not in no_info_nodes]                       # yes I know it's not gonna visualize\nnx.draw_networkx_nodes(ego_G, spring_layout, nodelist=nodelist, node_color='r', edgecolors='k', node_shape='$\ud83e\udd14$')\nedgelist = [e for e in ego_G.edges if my_id not in e]\nnx.draw_networkx_edges(ego_G, spring_layout, edgelist=edgelist, alpha=0.7)\n\nplt.title('Ego graph with spring layout (filtered)', fontdict={'fontsize': 40})\nplt.legend(['Information node', 'Mystery node'], fontsize=30)\nplt.axis('off')\nplt.show()\n\"\"\"\nThat's better. We can see that even with missing information about half of the nodes, the other half compensates and forms some nice clusters. Now let's try and actually separate them by color.\n\n### Optimal community detection methods\n\n#### Clauset-Newman-Moore\n\nClauset-Newman-Moore greedy modularity maximization works like this: Initially, every node belongs to its own community, then, at each step, the algorithm repeatedly merges pairs of communities together and chooses the merger for which the resulting modularity is the largest. The algorithm stops when all the nodes in the network are in a single community after (count of nodes \u2212 1) steps of merging. What we get at the end is the communities with the best modularity score.\n\"\"\"\nclauset_newman_moore = nx.community.greedy_modularity_communities(ego_G)\n\"\"\"\nA nice way of pairing node color with a different shade of the same color for the edges:\n\"\"\"\ndef get_paired_color_palette(size):\n    palette = []\n    for i in range(size*2):\n        palette.append(plt.cm.Paired(i))\n    return palette\nplt.figure(figsize=(30, 30))\nclusters_count = len(clauset_newman_moore)\nlight_colors = get_paired_color_palette(clusters_count)[0::2]\ndark_colors = get_paired_color_palette(clusters_count)[1::2]\n\nfor i in range(clusters_count):\n    nodelist = [n for n in ego_G.nodes if (n not in no_info_nodes) & (n in list(clauset_newman_moore[i]))]\n    edgelist = [e for e in ego_G.edges if (my_id not in e) and (e[0] in list(clauset_newman_moore[i]) or e[1] in list(clauset_newman_moore[i]))]\n    node_color = [light_colors[i] for _ in range(len(nodelist))]\n    edge_color = [dark_colors[i] for _ in range(len(edgelist))]\n    nx.draw_networkx_nodes(ego_G, spring_layout, nodelist=nodelist, node_color=node_color, edgecolors='k')                                                                                                           \n    nx.draw_networkx_edges(ego_G, spring_layout, edgelist=edgelist, alpha=1\/clusters_count, edge_color=edge_color)\n\nplt.title('Ego graph with Clauset-Newman-Moore clustering', fontdict={'fontsize': 40})\nplt.axis('off')\nplt.show()\n\"\"\"\nLooks like this algorithm is a good start, but we can see a few smaller clusters that are not separated from the larger ones. \n\n#### Louvain\n\nThe [Louvain](https:\/\/arxiv.org\/pdf\/0803.0476.pdf) method of community detection also uses a greedy approach and initially assigns each node to an individual community. However, instead of a search over all edges, the Louvain method executes a local search over the edges of each node. Each node is combined with the neighbour that most increases its modularity. This process of reassigning communities is repeated over several iterations, until modularity is increased. Once this first-phase allocation of communities is determined, the Louvain method joins nodes within a community into supernodes. The inner iteration is then repeated over these supernodes. The steps of the inner and outer iterations are executed repeatedly until the number of communities is suitably small and the modularity cannot be increased any further.\n\"\"\"\nlouvain = community.best_partition(ego_G, random_state=42)\nplt.figure(figsize=(30, 30))\nclusters_count = len(set(louvain.values()))\nlight_colors = get_paired_color_palette(clusters_count)[0::2]\ndark_colors = get_paired_color_palette(clusters_count)[1::2]\n\nfor i in set(louvain.values()):\n    nodelist = [n for n in ego_G.nodes if (louvain[n]==i) and (n not in no_info_nodes)]\n    edgelist = [e for e in ego_G.edges if (my_id not in e) and ((louvain[e[0]]==i) or (louvain[e[1]]==i))]\n    node_color = [light_colors[i] for _ in range(len(nodelist))]\n    edge_color = [dark_colors[i] for _ in range(len(edgelist))]\n    nx.draw_networkx_nodes(ego_G, spring_layout, nodelist=nodelist, node_color=node_color, edgecolors='k')                                                                                                           \n    nx.draw_networkx_edges(ego_G, spring_layout, edgelist=edgelist, alpha=1\/clusters_count, edge_color=edge_color)\n\nplt.title('Ego graph with Louvain clustering', fontdict={'fontsize': 40})\nplt.axis('off')\nplt.show()\n\"\"\"\nWe can see one additional cluster, but it doesn't differentiate between the small communities inside it. This is a known drawback of modularity, as it suffers a resolution limit and is unable to detect smaller communities in graphs.\n\nNetworkx has a couple more community finding algorithms but we will come back to them later. First we will test one more methods from the `igraph` library.<br>\nThere doesn't seem to be a way to make it communicate with networkx so we will have to export the graph in a format that igraph can read.\n\"\"\"\nlabels = edge_frame[['target_id', 'target']].set_index('target_id').to_dict()['target']\nfor key, value in friend_ids.set_index('node_id').to_dict()['node'].items():\n    labels[key] = value\nego_labels = {k:v for k, v in labels.items() if k in ego_G.nodes}\nego_G.add_nodes_from([(k, {'name': v}) for k, v in ego_labels.items()])\nnx.write_gml(ego_G, 'ego_G.gml')\nego_g = ig.Graph.Read_GML('ego_G.gml')\nprint(nx.info(ego_G), '\\n')\nprint(ego_g.summary())\n# fixes mojibake bug\nfor i in range(len(ego_g.vs['name'])):\n    ego_g.vs[i]['name'] = ego_labels[int(ego_g.vs[i]['label'])]\n\"\"\"\n#### Infomap\nFinds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.\nThe core of the algorithm follows closely the Louvain method: neighboring nodes are joined into modules, which subsequently are joined into supermodules and so on. First, each node is assigned to its own module. Then, in random sequential order, each node is moved to the neighboring module that results in the largest decrease of the [**map equation**](https:\/\/arxiv.org\/pdf\/0906.1405.pdf). If no move results in a decrease of the map equation, the node stays in its original module. This procedure is repeated, each time in a new random sequential order, until no move generates a decrease of the map equation.\n\"\"\"\ninfomap = ego_g.community_infomap(trials=100)\nig.plot(infomap, layout=ego_g.layout(layout='fr'), mark_groups=False, vertex_size=8, vertex_label=None)\n\"\"\"\nGreat, this time we have a lot more clusters, but we can't compare the graphs just by looking at them! We can evaluate the algorithms by the following metrics:\n\n**Modularity** is the most popular measure of the structure of networks. It is the fraction of the edges that fall within the given groups minus the expected fraction if edges were distributed at random. Networks with high modularity have dense connections between the nodes within clusters but sparse connections between nodes in different clusters.\n\n**The coverage** of a clustering is given as the fraction of the weight of all intra-cluster edges with respect to the total weight of all edges in the whole graph. Higher values of coverage mean that there are more edges inside the clusters than edges linking different clusters, which translates to a better clustering.\n\n**Performance** counts the number of internal edges in a cluster along with the edges that don\u2019t exist between the cluster\u2019s nodes and other nodes in the graph. Higher values indicate that a cluster is both internally dense and externally sparse and, therefore, a better cluster.\n\"\"\"\n# need to transform all the graphs in the same format for the below function to work\nclusters = []\nfor cluster in range(len(set(louvain.values()))):\n    cluster_list = []\n    for k, v in louvain.items():\n        if v == cluster:            \n            cluster_list.append(k)\n    clusters.append(cluster_list)\nlouvain = clusters\n\nego_g.vs['membership'] = infomap.membership\nclusters = []\nfor i in range(len(infomap.sizes())):\n    cluster = []\n    for vertex in ego_g.vs:        \n        if vertex['membership'] == i:\n            cluster.append(int(vertex['label']))\n    clusters.append(cluster)\ninfomap, clusters = clusters, None\nalgorithms = ['clauset_newman_moore', 'louvain', 'infomap']\nfig = go.Figure(data=[\n    go.Bar(name='Modularity', x=algorithms, y=[nx.community.modularity(ego_G, eval(algorithm)) for algorithm in algorithms]),\n    go.Bar(name='Coverage', x=algorithms, y=[nx.community.coverage(ego_G, eval(algorithm)) for algorithm in algorithms]),\n    go.Bar(name='Performance', x=algorithms, y=[nx.community.performance(ego_G, eval(algorithm)) for algorithm in algorithms])])\n\nfig.update_layout(barmode='group',\n                  title=go.layout.Title(text='Comparison of metrics between clustering algorithms', xref=\"paper\"))\nfig.show()\n\"\"\"\nIt looks like each algorithm has its advantages and disadvantages. CNM has the highest coverage, but Louvain has higher modularity and performance score. Even though they both aim to maximize the modularity score, Louvain appears to do better, which makes sense as the algorithm was developed by improving the already existing CNM. Infomap on the other hand doesn't rely on modularity and instead uses the map equation as a scoring function which gives it the highest performance score of them all.\n\nAll these graphs are great, but how are we to evaluate the communities if we can't even see people's names? Let's make an interactive graph, that let's us decide for ourselves if the clustering is correct.<br>\nFirst, we can clean up each person's description into something more readable.\n\"\"\"\ndescription_frame = edge_frame.copy()\ndescription_frame.description = description_frame.description.str.replace(r'.*at ', ' ')\ndescription_frame.description = description_frame.description.str.strip()\ndescription_frame.description.value_counts().head()\n\"\"\"\nThen we can remove all the descriptions that don't give us any information.\n\"\"\"\nstop_word = ['mutual friends', 'friends', 'Facebook', 'Self-Employed']\ndescription_frame = description_frame[~description_frame.description.isin(stop_word)]\ndescription_frame.description.value_counts().head()\n\"\"\"\nAnd since almost all of the people in my Ego graph have no description, we can assign the three most common descriptions from each person's friendlist as his own.\n\"\"\"\nfor node in ego_G.nodes:\n    ego_G.nodes[node]['top'] = list(description_frame.description[(description_frame.target_id!=my_id) & (description_frame.source_id==node)].value_counts()[:3].keys())\n\"\"\"\nWhile we're at it, why not add a few more layouts.\n\"\"\"\nkamada_kawai_layout = nx.kamada_kawai_layout(ego_G)\nforce_atlas_2 = forceatlas2.forceatlas2_networkx_layout(ego_G, niter=1000)\n\"\"\"\nWe're going to reuse this function further in the notebook, so we'll add some additional functionality that won't be usable at this moment.\n\"\"\"\n# fix node attributes\ndef interactive_clustering(hide=True,\n                           attributes=False,\n                           search=None,\n                           layout='spring_layout',\n                           clustering='clauset_newman_moore',\n                           k=32,\n                           node_attr='top'):\n    \n    # hides single-edge nodes\n    if hide:\n        nodelist = [n for n in ego_G.nodes if (n not in no_info_nodes) and (not n==my_id)]\n        edgelist = [e for e in ego_G.edges if (my_id not in e) and ((e[0] not in no_info_nodes) and (e[1] not in no_info_nodes))]\n    else:\n        nodelist = [n for n in ego_G.nodes]\n        edgelist = [e for e in ego_G.edges]\n    \n    # edges\n    edge_x = []\n    edge_y = []\n    pos=eval(layout)\n    for edge in edgelist:\n        x0, y0 = pos[edge[0]]\n        x1, y1 = pos[edge[1]]\n        edge_x.append(x0)\n        edge_x.append(x1)\n        edge_x.append(None)\n        edge_y.append(y0)\n        edge_y.append(y1)\n        edge_y.append(None)\n    edge_trace = go.Scatter(x=edge_x,\n                            y=edge_y,\n                            line=dict(width=0.5, color='#888'),\n                            hoverinfo='none',\n                            mode='lines')   \n    # nodes\n    node_x = []\n    node_y = []\n    for node in nodelist:\n        x, y = pos[node]\n        node_x.append(x)\n        node_y.append(y)    \n    node_trace = go.Scatter(x=node_x,\n                            y=node_y,\n                            mode='markers',\n                            hoverinfo='text',\n                            marker=dict(showscale=False,\n                                        colorscale='hsv',\n                                        size=10,\n                                        line_width=2))\n    \n    # clustering, attributes preparation\n    cluster_dict = {}\n    cluster_attr = {}\n    counter = Counter()\n    c = eval(clustering)\n    # if it's hierarchical clustering\n    if len(c) > 307:\n        for cluster in range(len(c[k-1])):\n            for node in c[k-1][cluster]:\n                cluster_dict[node] = cluster+1\n                if attributes:\n                    if ego_G.nodes[node][node_attr]:\n                        counter[ego_G.nodes[node][node_attr][0]] += 1\n            cluster_attr[cluster+1] = [i[0] for i in counter.most_common(3)]\n            counter.clear()\n    # if it's optimal clustering\n    else:\n        for cluster in range(len(c)):\n            for node in c[cluster]:\n                cluster_dict[node] = cluster+1\n                if attributes:\n                    if ego_G.nodes[node][node_attr]:\n                        counter[ego_G.nodes[node][node_attr][0]] += 1\n            cluster_attr[cluster+1] = [i[0] for i in counter.most_common(3)]\n            counter.clear()\n    \n    # colors, names, attributes\n    node_text = []\n    node_colors = []\n    for node_id in nodelist:\n        node_colors.append(cluster_dict[node_id])\n        if attributes:\n            node_text.append(f\"{labels[node_id]} - \u2116{cluster_dict[node_id]}\\\n            <br>Node attributes:<br>{ego_G.nodes[node_id][node_attr]}\\\n            <br>Cluster attributes:<br>{cluster_attr[cluster_dict[node_id]]}\")\n        else:\n            node_text.append(f\"{labels[node_id]} - \u2116{cluster_dict[node_id]}\")\n    node_trace.marker.color = node_colors\n    node_trace.text = node_text\n    \n    # actual fig drawing\n    fig = go.Figure(data=[edge_trace, node_trace],\n                    layout=go.Layout(width=600,\n                                     height=600,\n                                     title=f'Ego graph with {clustering} clustering',\n                                     titlefont_size=16,\n                                     showlegend=False,\n                                     hovermode='closest',\n                                     margin=dict(b=20,l=5,r=5,t=40),\n                                     annotations=[dict(text=\"P. Bogdanov - Software University\",\n                                                       showarrow=False,\n                                                       xref=\"paper\",\n                                                       yref=\"paper\",\n                                                       x=0.005,\n                                                       y=-0.002 )],\n                                     xaxis=dict(showgrid=False,\n                                                zeroline=False,\n                                                showticklabels=False),\n                                     yaxis=dict(showgrid=False,\n                                                zeroline=False,\n                                                showticklabels=False),\n                                     plot_bgcolor='white'))\n\n    # search functionality\n    if search:\n        for node in node_trace['text']:\n            if search in node:\n                index = node_trace['text'].index(node)                \n                fig.add_scatter(x=[node_trace.x[index]],\n                                y=[node_trace.y[index]],\n                                mode=\"text\",\n                                text=search)\n\n    fig.show()\ninteract(interactive_clustering,\n         hide=widgets.Checkbox(value=True,\n                               description='Hide single edge nodes'),\n         attributes=widgets.Checkbox(value=False,\n                                     description='Show attributes'),\n         search=widgets.Combobox(options=tuple([labels[i] for i in labels.keys() if i in ego_G.nodes] + ['']),\n                                 placeholder='Your name here',\n                                 description='Search: ',\n                                continuous_update=False),\n         layout=widgets.RadioButtons(options=['spring_layout',\n                                              'force_atlas_2',\n                                              'kamada_kawai_layout'],\n                                     value='force_atlas_2',\n                                     description='Layout: '),\n         clustering=widgets.RadioButtons(options=['clauset_newman_moore', 'louvain', 'infomap'],\n                                         value='infomap',\n                                         description='Algorithm: '),         \n         k=widgets.IntSlider(layout=Layout(display='None'), disabled = True),\n         node_attr=widgets.Text(value='top',layout=Layout(display='None'), disabled = True))\n\"\"\"\nLooking at the graph while knowing who each node is is much better. The three major clusters common in the three algorithms are people from my highschool, people from my university and the people which I go out with. It's interesting to see that the people from my last job are connected to the university cluster, but infomap algorithm separates them into a different community. Even more interesting is that of those people it has separated those who have graduated from the university from the rest of my job colleagues. The rest of the mini-clusters are separated by city, some more correctly than others.\n\nIt is clear that there are many levels of potential communities to be found. If we want to see those levels we will need a hierarchical algorithm.\n\"\"\"\n\"\"\"\n### Hierarchical community detection methods\n#### Girvan-Newman\nThe Girvan-Newman algorithm detects communities by progressively removing edges from the original network. The connected components of the remaining network are the communities. Instead of trying to construct a measure that tells us which edges are the most central to communities, the Girvan-Newman algorithm focuses on edges that are most likely \"between\" communities.\n\"\"\"\ngirvan_newman = []\nfor i in nx.community.girvan_newman(ego_G):\n    girvan_newman.append(i)\n\"\"\"\n#### Walktrap\n\nThe [walktrap](https:\/\/www-complexnetworks.lip6.fr\/~latapy\/Publis\/communities.pdf) algorithm of Latapy & Pons tries to find communities in a graph via random walks. The idea is that short random walks on a graph tend to get \"trapped\" into densely connected parts corresponding to communities. Using some properties of random walks on graphs it defines a measurement of the structural similarity between nodes and between communities, thus defining a distance which can be used in a hierarchical clustering algorithm\n\"\"\"\nwalktr = ego_g.community_walktrap()\nwalktrap = []\nfor clust_count in range(1, len(ego_G.nodes)+1):\n    clust = walktr.as_clustering(n=clust_count)\n    ego_g.vs['membership'] = clust.membership\n    clusters = []\n    for i in range(clust_count):\n        cluster = []\n        for vertex in ego_g.vs:        \n            if vertex['membership'] == i:\n                cluster.append(int(vertex['label']))\n        clusters.append(cluster)\n    walktrap.append(clusters)\n\"\"\"\n#### Fluid Communities\nThe [Fluid Communities](https:\/\/arxiv.org\/pdf\/1703.09307.pdf) algorithm is based on the simple idea of fluids interacting in an environment, expanding and pushing each other. First each of the initial k communities is initialized in a random vertex in the graph. Then the algorithm iterates over all vertices in a random order, updating the community of each vertex based on its own community and the communities of its neighbours. This process is performed several times until convergence. At all times, each community has a total density of 1, which is equally distributed among the vertices it contains. If a vertex changes of community, vertex densities of affected communities are adjusted immediately. When a complete iteration over all vertices is done, such that no vertex changes the community it belongs to, the algorithm has converged and returns.\n\"\"\"\nasyn_fluidc = []\nfor i in range(1, len(ego_G)):\n    instance = nx.community.asyn_fluidc(ego_G, i, max_iter=300, seed=42)\n    asyn_fluidc.append([com for com in instance])\n\"\"\"\nNow we can explore communities at various resolutions by specifying the number of clusters we want.\n\"\"\"\ninteract(interactive_clustering,\n         hide=widgets.Checkbox(value=True,\n                               description='Hide single edge nodes'),\n         attributes=widgets.Checkbox(value=False,\n                                     description='Show attributes'),\n         search=widgets.Combobox(options=tuple([ego_labels[i] for i in ego_labels.keys()] + ['']),\n                                 placeholder='Your name here',\n                                 description='Search: '),\n         layout=widgets.RadioButtons(options=['spring_layout',\n                                              'force_atlas_2',\n                                              'kamada_kawai_layout'],\n                                     value='force_atlas_2',\n                                     description='Layout: '),\n         clustering=widgets.RadioButtons(options=['girvan_newman', 'asyn_fluidc', 'walktrap'],\n                                         value='girvan_newman',\n                                         description='Algorithm: '),         \n         k=widgets.IntSlider(min=1,\n                             max=len(ego_G.nodes)-1,\n                             step=1,\n                             value=32,\n                             layout=Layout(width='90%'),\n                             description='Clusters: ',\n                             continuous_update=False),\n        node_attr=widgets.Text(value='top',layout=Layout(display='None'), disabled = True))\n\"\"\"\nWe can change the number of clusters for each algorithm and eyeball it _or_ we can look at the metrics for more insight.\n\"\"\"\noptimal = ['clauset_newman_moore', 'louvain', 'infomap']\nhierarchical = ['girvan_newman', 'asyn_fluidc', 'walktrap']\nmetrics_list = ['modularity', 'coverage', 'performance']\noptimal_results = []\nfor algorithm in optimal:\n    optimal_dict = {}\n    optimal_dict['modularity'] = [nx.community.modularity(ego_G, eval(algorithm))]\n    optimal_dict['coverage'] = [nx.community.coverage(ego_G, eval(algorithm))]\n    optimal_dict['performance'] = [nx.community.performance(ego_G, eval(algorithm))]\n    optimal_results.append(optimal_dict)\nhierarchical_results = []\nfor algorithm in hierarchical:\n    hierarchical_dict = {}\n    hierarchical_dict['modularity'] = [nx.community.modularity(ego_G, eval(algorithm)[i]) for i in range(len(eval(algorithm)))]\n    hierarchical_dict['coverage'] = [nx.community.coverage(ego_G, eval(algorithm)[i]) for i in range(len(eval(algorithm)))]\n    hierarchical_dict['performance'] = [nx.community.performance(ego_G, eval(algorithm)[i]) for i in range(len(eval(algorithm)))]\n    hierarchical_results.append(hierarchical_dict)\ndef metrics(G, metrics_list, hierarchical_algorithms, hierarchical_results, optimal_algorithms, optimal_results):\n    for metric in metrics_list:\n        fig = go.Figure()\n        for algorithm in hierarchical_algorithms:\n\n            fig.add_trace(go.Scatter(x=[i+1 for i in range(len(eval(algorithm)))],\n                                     y=hierarchical_results[hierarchical_algorithms.index(algorithm)][metric],\n                                     mode='lines',\n                                     name=algorithm))\n        for algorithm in optimal_algorithms:\n            fig.add_trace(go.Scatter(x=[(len(eval(algorithm)))],\n                                     y=optimal_results[optimal_algorithms.index(algorithm)][metric],\n                                     mode='markers',\n                                     name=algorithm))\n        fig.update_layout(title=go.layout.Title(text=metric[:1].upper()+metric[1:]+\" in clustering algorithms\", xref=\"paper\"),\n                          xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text=\"Number of clusters\")),\n                          yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text=metric[:1].upper()+metric[1:])))\n        fig.show()\nmetrics(ego_G, metrics_list, hierarchical, hierarchical_results, optimal, optimal_results)\n\"\"\"\nWe can see that the three algorithms are vastly different from each other but they do have some crossing points. Almost all of them peak early on at about 6 clusters, except Girvan-Newman, which is barely changing at that level. This can be explained by the fact that the other methods separate the biggest clusters in the beginning, while Girvan-Newman trims the one-edge nodes first and works its way up to the bigger clusters from there. An interesting point is the secondary peak at cluster count 32, most notable in Girvan-Newman but present in Walktrap as well. This is a clustering we can't get with the optimal community findig algorithms, because they all converge early on around the first peak. Now we have a choice - if we want a broader view of the communities we can choose a cluster count of 6, but if we want more details then our cluster count is 32.\n\"\"\"\n\"\"\"\n### Semi-supervised community detection\n\nSo far we've tried unsupervised aproaches that rely solely on the connections between the nodes. But that's not all we've got. Some of our nodes have descriptions that can be used in a semi-supervised approach.\n\n#### Label propagation\n[Label Propagation](http:\/\/citeseerx.ist.psu.edu\/viewdoc\/download?doi=10.1.1.14.3864&rep=rep1&type=pdf) is a semi-supervised machine learning algorithm that assigns labels to previously unlabeled data points. At initial condition, the nodes carry a label that denotes the community they belong to. Membership in a community changes based on the labels that the neighboring nodes possess. This change is subject to the maximum number of labels within one degree of the nodes. Every node is initialized with a unique label, then the labels diffuse through the network. Consequently, densely connected groups reach a common label quickly. When many such dense groups are created throughout the network, they continue to expand outwards until it is impossible to do so.\n\nCurrently our \"labels\" are nothing more than strings. Some of them refer to the same location, but are written in a different way. If we want to use them in a meaningfull way, we need to transform them.<br> Geopy will do the trick. It offers a free geocoding functionallity that can give us not only the geographic coordinates of the location, but also its type. The only limitation is that if we want to use it in bulk we need to put a rate limiter on the queries.\n\"\"\"\nlocator = Nominatim(user_agent=\"FacebookLocator\")\ngeocode = RateLimiter(locator.geocode, min_delay_seconds=1, return_value_on_exception='Error')\n\"\"\"\nThis is going to take a while so we better minimize the amount of queries we'll need.\n\"\"\"\nlocations = pd.DataFrame(description_frame.description.value_counts().keys(), columns=['address'])\nnot_real_locations = ['BMW', 'The Krusty Krab', '\u041c\u0412\u0420', 'YouTube', 'Tumblr', 'Freelancer', 'McDonald\\'s', 'Oriflame', 'None', '']\nlocations = locations[~locations.address.isin(not_real_locations)]\nprint(\"Count of unique descriptions:\", len(locations))\n# # takes about a day\n# locations['location'] = locations['address'].apply(geocode)\n# locations = locations.reset_index(drop=True)\n# unknown_locations = locations[locations.location.isnull()]\n# locations = locations[locations.location.notnull()]      \nwith open(f\"..\/input\/locations\/locations.pickle\", \"rb\") as f:\n    locations = pickle.load(f)\nprint(\"Count of geocoded locations:\", len(locations))\n\"\"\"\nExtract all available information we have for each location:\n\"\"\"\nlocations['point'] = locations['location'].apply(lambda loc: tuple(loc.point) if loc else None)\nlocations['raw'] = locations['location'].apply(lambda loc: loc.raw if loc else None)\n\"\"\"\nMerge locations with nodes:\n\"\"\"\nadditional = locations.raw.apply(pd.Series)\nlocations = locations.join(additional, rsuffix='index')\nlocations = pd.merge(description_frame, locations, left_on='description', right_on='address', how='left')\n\"\"\"\nLet's see all the locations we have available.\n\"\"\"\nmap_df = locations.dropna().copy()\nmap_df['nodes_count'] = map_df.groupby('osm_id').osm_id.transform('count')\nmap_df.osm_id = map_df.osm_id.drop_duplicates()\nmap_df = map_df.dropna()\n\nscaler = MinMaxScaler(feature_range=(0.02, 1))\nscaler.fit(map_df[['nodes_count']])\nmap_df['nodes_count_scaled'] = scaler.transform(map_df[['nodes_count']])\n\nfig = px.scatter_geo(map_df,\n                     lat=\"lat\",\n                     lon=\"lon\",\n                     hover_name=\"address\",\n                     text='nodes_count',\n                     opacity=0.5,\n                     color='nodes_count_scaled',\n                     size='nodes_count_scaled',\n                     title='Available locations')\nfig.update_layout(margin={\"r\":0,\"t\":80,\"l\":0,\"b\":0})\nfig.show()\n\"\"\"\nGreat, we have locations all over the world. Not only that, but we have the type of the location as well. That gives us some additional options to choose from.\n\"\"\"\ndef propagate_by(by='full'):    \n    # different options for propagation\n    education_list = ['school', 'university', 'college', 'educational_institution', 'music_school', 'language_school']\n    if by=='education':        \n        location = locations[locations.type.isin(education_list)]\n    elif by=='area':\n        location = locations[(locations.type.isin(['city', 'town', 'village'])) | (locations['class']=='boundary')]\n    else:\n        location = locations[locations.osm_id.notna()]\n    \n    # the algorithm implementation needs the ids to start from 0\n    location = location.assign(location_id=(locations['osm_id']).astype('category').cat.codes)\n    by_dict = location[['target_id', 'location_id']].set_index('target_id').to_dict()['location_id']\n    G = nx.from_pandas_edgelist(edge_frame, source='source_id', target='target_id')\n    \n    # we're using igraph so we need to transform our graph to the proper fromat\n    G.add_nodes_from([(k, {'name': v}) for k, v in labels.items()])\n    G.add_nodes_from([(k, {by: v}) for k, v in by_dict.items()])\n    nx.write_gml(G, 'G.gml')\n    g = ig.Graph.Read_GML('G.gml')\n    \n    # fix mojibake and prepare attributes\n    for i in range(len(g.vs['name'])):\n        g.vs[i]['name'] = labels[int(g.vs[i]['label'])]\n    for i in range(len(g.vs[by])):\n        try:\n            g.vs[i][by] = by_dict[int(g.vs[i]['label'])]\n            g.vs[i]['fixed'] = True\n        except:        \n            g.vs[i][by] = -1\n            g.vs[i]['fixed'] = False\n    \n    # the actual model\n    label_propagation = g.community_label_propagation(initial=g.vs[by], fixed=g.vs['fixed'])\n    \n    # make it human readable\n    id_to_address = location[['location_id', 'address']].set_index('location_id').to_dict()['address']\n    \n    # transform format to nx-like clusters, leave only ego_G nodes and change node_attr\n    label_prop = []\n    attributes = {}\n    for i in range(len(label_propagation)):\n        cluster = []\n        cluster_locations = set(label_propagation.subgraph(i).vs[by])\n        for node in label_propagation.subgraph(i).vs:        \n            if int(node['label']) in ego_labels.keys():\n                cluster.append(int(node['label']))\n                if len(cluster_locations) > 1:\n                    ego_G.nodes[int(node['label'])][by] = [id_to_address[sorted(list(cluster_locations))[1]]]\n                else:\n                    ego_G.nodes[int(node['label'])][by] = [id_to_address[sorted(list(cluster_locations))[0]]]\n        if cluster:\n            label_prop.append(cluster)\n    return label_prop\n\"\"\"\nLet's try it with these 3 options:\n\"\"\"\nlabel_prop_by_area = propagate_by('area')\nlabel_prop_by_education = propagate_by('education')\nlabel_prop_full = propagate_by('full')\ninteract(interactive_clustering,\n         hide=widgets.Checkbox(value=False,\n                               description='Hide single edge nodes'),\n         attributes=widgets.Checkbox(value=True,\n                                     description='Show attributes'),\n         search=widgets.Combobox(options=tuple([labels[i] for i in labels.keys() if i in ego_G.nodes] + ['']),\n                                 placeholder='Your name here',\n                                 description='Search: ',\n                                 continuous_update=False),\n         layout=widgets.RadioButtons(options=['spring_layout',\n                                              'force_atlas_2',\n                                              'kamada_kawai_layout'],\n                                     value='spring_layout',\n                                     description='Layout: '),\n         clustering=widgets.RadioButtons(options=[\"label_prop_by_area\", \"label_prop_by_education\", \"label_prop_full\"],\n                                        value=\"label_prop_by_education\",\n                                         description='Algorithm: '),         \n         k=widgets.IntSlider(layout=Layout(display='None'), disabled = True),\n         node_attr=widgets.RadioButtons(options=[\"top\", \"area\", \"education\", \"full\"],\n                                        value='education', description='Attributes: '))\n\"\"\"\nThe advantages of this algorithm are obvious. We can extract useful information about single nodes that didn't belong to any cluster in the previous algoriths. It's pretty accurate for the sparsely connected unlabeled nodes, but the opposite is true for the ones that have a lot of connections between them. They tend to acquire each other's labels and end up being missclassified. In addition, due to the randomness of the algorithm it produces highly variable results. Nevertheless it is still usefull and can show us connections that the other algorithms can not.\n\nWe can compare the metrics but they migh be different on each run.\n\"\"\"\nalgorithms = [\"label_prop_by_area\", \"label_prop_by_education\", \"label_prop_full\"]\nfig = go.Figure(data=[\n    go.Bar(name='Modularity', x=algorithms, y=[nx.community.modularity(ego_G, eval(algorithm)) for algorithm in algorithms]),\n    go.Bar(name='Coverage', x=algorithms, y=[nx.community.coverage(ego_G, eval(algorithm)) for algorithm in algorithms]),\n    go.Bar(name='Performance', x=algorithms, y=[nx.community.performance(ego_G, eval(algorithm)) for algorithm in algorithms])])\n\nfig.update_layout(barmode='group',\n                  title=go.layout.Title(text='Comparison of metrics between label propagation algorithm', xref=\"paper\"))\nfig.show()\n\"\"\"\nOne last thing we can do is visualise the locations on the map.\n\"\"\"\nmap_df = pd.DataFrame()\nattributes = ['area', 'education', 'full']\nfor attr in attributes:\n    loc_dict = {}\n    for i in ego_G.nodes:\n        loc_dict[i] = ego_G.nodes[i][attr]\n    for i in loc_dict.keys():\n        point = locations[locations.address==loc_dict[i][0]].point.unique()[0][:2]\n        loc_dict[i] = (loc_dict[i][0], point[0], point[1], attr)\n        \n    df = pd.DataFrame.from_dict(loc_dict).T.rename(columns={0: 'name', 1:'lat', 2:'lon', 3:'type'})\n    df['friends_count'] = df.groupby('name').name.transform('count')\n    scaler = MinMaxScaler(feature_range=(0.2, 1))\n    scaler.fit(df[['friends_count']])\n    df['friends_count_scaled'] = scaler.transform(df[['friends_count']])\n    map_df = pd.concat([map_df, df])\n\nfig = px.scatter_geo(map_df,\n                     lat=\"lat\",\n                     lon=\"lon\",\n                     hover_name=\"name\",\n                     text='friends_count',\n                     size='friends_count_scaled',\n                     animation_frame='type',\n                     color='type',\n                     title='Friends locations')\nfig.update_layout(margin={\"r\":0,\"t\":80,\"l\":0,\"b\":0})\nfig.show()\n\"\"\"\n### Graph Embedding\n\nOne of the limitations of graphs remains the absence of vector features. Besides reducing the engineering effort, these vector representations can lead to greater predictive power and allow us to use a broader range of machine learning tools. \n\n\n#### Node2Vec\n\nOne well-known algorithm that extracts information about entities using context alone is word2vec. The input to word2vec is a set of sentences, and the output is an embedding for each word. Similarly to the way text describes the context of each word via the words surrounding it, graphs describe the context of each node via neighbor nodes. The embeddings are learned in the same way as word2vec\u2019s skip-gram embeddings are learned, using a skip-gram model. To generate the corpus, we use random walks sampling strategy\n\"\"\"\nego_node2vec = Node2Vec(ego_G)\nego_model = ego_node2vec.fit()\n\"\"\"\nNow instead of a graph specific algorithm, we can use any of the well known ML clustering approaches like K-means.\n\"\"\"\nkmeans = []\nsilhouettes = {}\ninertia = {}\nfor i in range(1, len(ego_G.nodes())-1):\n    X = ego_model.wv[ego_model.wv.vocab]\n    kmeans_model = KMeans(n_clusters=i, n_init=20, n_jobs=2, random_state=42)\n    kmeans_model.fit(X)\n    kmeans_labels = kmeans_model.labels_\n    # make compatible with interactive function\n    vector_clustering = []\n    for j in range(i+1):\n        cluster_list = []\n        for cluster, node in zip(kmeans_labels, ego_model.wv.vocab):\n            if (cluster==j) and (int(node) in ego_G.nodes()):\n                cluster_list.append(int(node))\n        if cluster_list:\n            vector_clustering.append(cluster_list)\n    kmeans.append(vector_clustering)\n    # scoring to plot\n    inertia[i] = kmeans_model.inertia_\n    \n    if i>1:\n        silhouettes[i] = silhouette_score(X, kmeans_labels, metric='euclidean')\n\"\"\"\nTo get a 2D representation of this high-dimensional space we can use TSNE. Note that the clustering we made earlier was in higher dimensions and this is simply a visualization of that space.\n\"\"\"\nembeddings = np.array([ego_model.wv[x] for x in ego_model.wv.vocab])\ntsne = TSNE(n_components=2, random_state=42, perplexity=15)\nembeddings_2d = tsne.fit_transform(embeddings)\n\n# make compatible with our interactive function\nembeddings_layout = spring_layout.copy()\ncounter = 0\nfor x in ego_model.wv.vocab:\n    for k, v in embeddings_layout.items():\n        if str(k) == x:\n            embeddings_layout[k] = embeddings_2d[counter]\n            counter +=1\ninteract(interactive_clustering,\n         hide=widgets.Checkbox(value=True,\n                               description='Hide single edge nodes'),\n         attributes=widgets.Checkbox(value=False,\n                                     description='Show attributes'),\n         search=widgets.Combobox(options=tuple([ego_labels[i] for i in ego_labels.keys()] + ['']),\n                                 placeholder='Your name here',\n                                 description='Search: '),\n         layout=widgets.RadioButtons(options=['spring_layout',\n                                              'force_atlas_2',\n                                              'kamada_kawai_layout',\n                                              'embeddings_layout'],\n                                     value='embeddings_layout',\n                                     description='Layout: '),\n         clustering=widgets.RadioButtons(options=['girvan_newman', 'asyn_fluidc', 'walktrap', 'kmeans'],\n                                         value='kmeans',\n                                         description='Algorithm: '),         \n         k=widgets.IntSlider(min=1,\n                             max=308,\n                             step=1,\n                             value=32,\n                             layout=Layout(width='90%'),\n                             description='Clusters: ',\n                             continuous_update=False),\n        node_attr=widgets.Text(value='top',layout=Layout(display='None'), disabled = True))\n\"\"\"\nAs we can see, structurally, the three main clusters are still present, but this time they are not so homogeneous. During the clustering process the sparsely connected nodes aren't getting divided first, as is the case with other hierarchical algorithms. Instead, K-means' random initialization results in a simultaneous grouping over the span of the whole graph.\nIn a way, this type of clustering is a combination of walktrap's random walks and fluid communities' random initialization.\n\nThis time we can check other types of metrics. Inertia is the sum of squared distances of samples to their closest cluster center. The elbow method is finding the \"elbow\" point after which the inertia start decreasing in a linear fashion. That will give us the optimal amount of clusters.\n\"\"\"\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=list(inertia.keys()), y=list(inertia.values()), mode='lines'))\nfig.update_layout(title=go.layout.Title(text=\"Elbow method\", xref=\"paper\"),\n                  xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text=\"Number of clusters\")),\n                  yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text=\"Inertia\")))\nfig.show()\n\"\"\"\nUnfortunately we have no clear cut point that shows us the optimal amount of clusters, as any number between 5 and 50 can be that point.\n\nAnother metric is the silhouette index. Silhouette values near +1 indicate that the sample is far away from the neighboring clusters. A value of 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters and negative values indicate that those samples might have been assigned to the wrong cluster.\n\"\"\"\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=list(silhouettes.keys()), y=list(silhouettes.values()), mode='lines'))\nfig.update_layout(title=go.layout.Title(text=\"Silhouette coefficients\", xref=\"paper\"),\n                  xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text=\"Number of clusters\")),\n                  yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text=\"Silhouette coefficient\")))\nfig.show()\n\"\"\"\nThe silhouette index gives us another confirmation that a smaller number of clusters is probably more optimal. However, even the highest values of the index are pretty low, which means that the whole structure is weak and we might have made artificial clusters.\n\nFinally, we can compare it to the rest of the algorithms:\n\"\"\"\nhierarchical.append('kmeans')\nhierarchical_dict = {}\nhierarchical_dict['modularity'] = [nx.community.modularity(ego_G, kmeans[i]) for i in range(len(kmeans))]\nhierarchical_dict['coverage'] = [nx.community.coverage(ego_G, kmeans[i]) for i in range(len(kmeans))]\nhierarchical_dict['performance'] = [nx.community.performance(ego_G, kmeans[i]) for i in range(len(kmeans))]\nhierarchical_results.append(hierarchical_dict)\n\nmetrics(ego_G, metrics_list, hierarchical, hierarchical_results, optimal, optimal_results)\n\"\"\"\nAs we can see, the method is very similar to Fluid Communities and is even sub-optimal in higher cluster count.\n\nEven though the metrics are not kind to this clustering, it did provide us with a different type of grouping. While Girvan-Newman and Walktrap keep most of the nodes inside the bigger clusters unified and slowly trim them down untill there's no more left and Fluid Communities \"spills out\" at higher cluster count, returning more randomly distributed clusters, Node2Vec embedding combined with k-means clustering provides uniformly distributed communities and finds connections between nodes where other methods can't. This can be useful if we want to separate the groups by equal amount of nodes.\n\nBut the biggest advantage of graph embedding might be the availability to see the distances between nodes.\n\"\"\"\ndef most_similar(name):\n    try:\n        for node, percent in ego_model.wv.most_similar(str({v:k for k, v in ego_labels.items()}[name])):\n                print(ego_labels[float(node)], percent)\n    except:\n        print(\"\")\nmost_similar('Alexander Collins')\ninteract(most_similar, name=widgets.Combobox(options=tuple(sorted(ego_labels.values())),\n                                             placeholder='Your name here',\n                                             description='Search: '))\n\"\"\"\nIf we apply Node2Vec to the full list of friends we can even add people we don't know to our communities. But that is another task, more related to link prediction and recommendation systems than clustering.\n\n### Conclusion\n\nOptimal community finding methods work well enough for low resolution clustering, but if we want to find smaller communities - hierarchical methods work better. Semi-supervised learning with label propagation returns mixed results, but can give us additional insight into the current communities, as long as we already have some \"labels\" for them. Graph embedding is useful if we are trying to artificially fit into a certain amount of equaly sized clusters, even if they are not the optimal amount for the graph. It is unclear if the same results apply to weighted and\/or directed graphs, as further research is required.\n\n### Refferences\n\n\n[M. E. J Newman \"Networks: An Introduction\" Oxford University Press 2011](http:\/\/math.sjtu.edu.cn\/faculty\/xiaodong\/course\/Networks%20An%20introduction.pdf)\n\n[Clauset, A., Newman, M. E., & Moore, C. \u201cFinding community structure in very large networks.\u201d Physical Review E 70(6), 2004.](https:\/\/arxiv.org\/pdf\/cond-mat\/0408187.pdf)\n\n[Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte and Etienne Lefebvre: Fast unfolding of communities in large networks](https:\/\/arxiv.org\/pdf\/0803.0476.pdf)\n\n[M. Rosvall, D. Axelsson, and C. T. Bergstrom, The map equation, Eur. Phys. J. Special Topics 178, 13 (2009)](https:\/\/arxiv.org\/pdf\/0906.1405.pdf)\n\n[Girvan M. and Newman M. E. J., Community structure in social and biological networks](https:\/\/www.pnas.org\/content\/pnas\/99\/12\/7821.full.pdf)\n\n[Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks](https:\/\/arxiv.org\/pdf\/physics\/0512106.pdf)\n\n[Par\u00e9s F., Garcia-Gasulla D. et al. \u201cFluid Communities: A Competitive and Highly Scalable Community Detection Algorithm\u201d.](https:\/\/arxiv.org\/pdf\/1703.09307.pdf)\n\n[Xiaojin Zhu & Zoubin Ghahramani \"Learning from Labeled and Unlabeled Data with Label Propagation\"](http:\/\/citeseerx.ist.psu.edu\/viewdoc\/download?doi=10.1.1.14.3864&rep=rep1&type=pdf)\n\n[node2vec: Scalable Feature Learning for Networks. A. Grover, J. Leskovec. ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 2016.](https:\/\/arxiv.org\/pdf\/1607.00653.pdf)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7132e0e66b9ac2'}"}
{"id":"17231","text":"\"\"\"\n## Pytorch to implement simple feed-forward NN model (0.89+)\n\n* As below discussion, NN model can get lB 0.89+\n* https:\/\/www.kaggle.com\/c\/santander-customer-transaction-prediction\/discussion\/82499#latest-483679\n* Add Cycling learning rate , K-fold cross validation (0.85 to 0.86)\n* Add flatten layer as below discussion (0.86 to 0.897)\n* https:\/\/www.kaggle.com\/c\/santander-customer-transaction-prediction\/discussion\/82863\n\n## LightGBM (LB 0.899)\n\n* Fine tune parameters (0.898 to 0.899)\n* Reference this kernel : https:\/\/www.kaggle.com\/chocozzz\/santander-lightgbm-baseline-lb-0-899\n\n\n## Plan to do\n* Modify model structure on NN model\n* Focal loss\n* Feature engineering\n* Tune parameters oof LightGBM\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport time\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader\n\nimport lightgbm as lgb\nfrom sklearn.metrics import mean_squared_error\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\"\"\"\n## Load Data\n\"\"\"\n#Load data\ntrain_df = pd.read_csv('..\/input\/train.csv')\ntest_df = pd.read_csv('..\/input\/test.csv')\ntrain_df.shape, test_df.shape\ntrain_df.head()\ntrain_features = train_df.drop(['target','ID_code'], axis = 1)\ntest_features = test_df.drop(['ID_code'],axis = 1)\ntrain_target = train_df['target']\ntrain_features.shape,test_features.shape,train_target.shape\n#### Scaling feature #####\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\ntrain_features = sc.fit_transform(train_features)\ntest_features = sc.transform(test_features)\n\"\"\"\n## Split K- fold validation\n\"\"\"\n# Implement K-fold validation to improve results\nn_splits = 5 # Number of K-fold Splits\n\nsplits = list(StratifiedKFold(n_splits=n_splits, shuffle=True).split(train_features, train_target))\nsplits[:3]\n\"\"\"\n## Cycling learning rate\n\n*copy from ==> https:\/\/github.com\/anandsaha\/pytorch.cyclic.learning.rate\/blob\/master\/cls.py\n\"\"\"\nclass CyclicLR(object):\n    def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,\n                 step_size=2000, mode='triangular', gamma=1.,\n                 scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):\n\n        if not isinstance(optimizer, Optimizer):\n            raise TypeError('{} is not an Optimizer'.format(\n                type(optimizer).__name__))\n        self.optimizer = optimizer\n\n        if isinstance(base_lr, list) or isinstance(base_lr, tuple):\n            if len(base_lr) != len(optimizer.param_groups):\n                raise ValueError(\"expected {} base_lr, got {}\".format(\n                    len(optimizer.param_groups), len(base_lr)))\n            self.base_lrs = list(base_lr)\n        else:\n            self.base_lrs = [base_lr] * len(optimizer.param_groups)\n\n        if isinstance(max_lr, list) or isinstance(max_lr, tuple):\n            if len(max_lr) != len(optimizer.param_groups):\n                raise ValueError(\"expected {} max_lr, got {}\".format(\n                    len(optimizer.param_groups), len(max_lr)))\n            self.max_lrs = list(max_lr)\n        else:\n            self.max_lrs = [max_lr] * len(optimizer.param_groups)\n\n        self.step_size = step_size\n\n        if mode not in ['triangular', 'triangular2', 'exp_range'] \\\n                and scale_fn is None:\n            raise ValueError('mode is invalid and scale_fn is None')\n\n        self.mode = mode\n        self.gamma = gamma\n\n        if scale_fn is None:\n            if self.mode == 'triangular':\n                self.scale_fn = self._triangular_scale_fn\n                self.scale_mode = 'cycle'\n            elif self.mode == 'triangular2':\n                self.scale_fn = self._triangular2_scale_fn\n                self.scale_mode = 'cycle'\n            elif self.mode == 'exp_range':\n                self.scale_fn = self._exp_range_scale_fn\n                self.scale_mode = 'iterations'\n        else:\n            self.scale_fn = scale_fn\n            self.scale_mode = scale_mode\n\n        self.batch_step(last_batch_iteration + 1)\n        self.last_batch_iteration = last_batch_iteration\n\n    def batch_step(self, batch_iteration=None):\n        if batch_iteration is None:\n            batch_iteration = self.last_batch_iteration + 1\n        self.last_batch_iteration = batch_iteration\n        for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):\n            param_group['lr'] = lr\n\n    def _triangular_scale_fn(self, x):\n        return 1.\n\n    def _triangular2_scale_fn(self, x):\n        return 1 \/ (2. ** (x - 1))\n\n    def _exp_range_scale_fn(self, x):\n        return self.gamma**(x)\n\n    def get_lr(self):\n        step_size = float(self.step_size)\n        cycle = np.floor(1 + self.last_batch_iteration \/ (2 * step_size))\n        x = np.abs(self.last_batch_iteration \/ step_size - 2 * cycle + 1)\n\n        lrs = []\n        param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)\n        for param_group, base_lr, max_lr in param_lrs:\n            base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))\n            if self.scale_mode == 'cycle':\n                lr = base_lr + base_height * self.scale_fn(cycle)\n            else:\n                lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)\n            lrs.append(lr)\n        return lrs\n\"\"\"\n## Build Simple NN model (Pytorch)\n\n* add flatten layer before fc layer (improve to 0.89+)\n* https:\/\/www.kaggle.com\/c\/santander-customer-transaction-prediction\/discussion\/82863\n\n* Model structure\n* (batch_size, 200) ==> Flatten ==> (batch_size* 200,1) ==> fc1 ==> (batch_size* 200, hidden_layer) ==>Reshape ==>(batch_size, hidden_layer * 200) ==> fc2 ==> (batch_size, 1)\n\"\"\"\nclass Simple_NN(nn.Module):\n    def __init__(self ,input_dim ,hidden_dim, dropout = 0.75):\n        super(Simple_NN, self).__init__()\n        \n        self.inpt_dim = input_dim\n        self.hidden_dim = hidden_dim\n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(dropout)\n        self.fc1 = nn.Linear(1, hidden_dim)\n        self.fc2 = nn.Linear(int(hidden_dim*input_dim), 1)\n        #self.fc3 = nn.Linear(int(hidden_dim\/2*input_dim), int(hidden_dim\/4))\n        #self.fc4 = nn.Linear(int(hidden_dim\/4*input_dim), int(hidden_dim\/8))\n        #self.fc5 = nn.Linear(int(hidden_dim\/8*input_dim), 1)\n        #self.bn1 = nn.BatchNorm1d(hidden_dim)\n        #self.bn2 = nn.BatchNorm1d(int(hidden_dim\/2))\n        #self.bn3 = nn.BatchNorm1d(int(hidden_dim\/4))\n        #self.bn4 = nn.BatchNorm1d(int(hidden_dim\/8))\n    \n    def forward(self, x):\n        b_size = x.size(0)\n        x = x.view(-1, 1)\n        y = self.fc1(x)\n        y = self.relu(y)\n        y = y.view(b_size, -1)\n        \n        out= self.fc2(y)\n        \n        return out\ndef sigmoid(x):\n    return 1 \/ (1 + np.exp(-x))\n\"\"\"\n## Start training\n* Epoch = 40\n* Batch size = 256\n* Cycling step = 150\n\"\"\"\nfrom torch.optim.optimizer import Optimizer\n## Hyperparameter\nn_epochs = 40\nbatch_size = 256\n\n## Build tensor data for torch\ntrain_preds = np.zeros((len(train_features)))\ntest_preds = np.zeros((len(test_features)))\n\nx_test = np.array(test_features)\nx_test_cuda = torch.tensor(x_test, dtype=torch.float).cuda()\ntest = torch.utils.data.TensorDataset(x_test_cuda)\ntest_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)\n\navg_losses_f = []\navg_val_losses_f = []\n\n## Start K-fold validation\nfor i, (train_idx, valid_idx) in enumerate(splits):  \n    x_train = np.array(train_features)\n    y_train = np.array(train_target)\n    \n    x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.float).cuda()\n    y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32).cuda()\n    \n    x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.float).cuda()\n    y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32).cuda()\n    \n    ##Loss function\n    #loss_fn = FocalLoss(2)\n    loss_fn = torch.nn.BCEWithLogitsLoss()\n    \n    #Build model, initial weight and optimizer\n    model = Simple_NN(200,16)\n    model.cuda()\n    optimizer = torch.optim.Adam(model.parameters(), lr = 0.001,weight_decay=1e-5) # Using Adam optimizer\n    \n    \n    ######################Cycling learning rate########################\n\n    step_size = 2000\n    base_lr, max_lr = 0.001, 0.005  \n    optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), \n                             lr=max_lr)\n    \n    scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr,\n               step_size=step_size, mode='exp_range',\n               gamma=0.99994)\n\n    ###################################################################\n\n    train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold)\n    valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold)\n    \n    train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)\n    valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)\n    \n    print(f'Fold {i + 1}')\n    for epoch in range(n_epochs):\n        start_time = time.time()\n        model.train()\n        avg_loss = 0.\n        #avg_auc = 0.\n        for i, (x_batch, y_batch) in enumerate(train_loader):\n            y_pred = model(x_batch)\n            ###################tuning learning rate###############\n            if scheduler:\n                #print('cycle_LR')\n                scheduler.batch_step()\n\n            ######################################################\n            loss = loss_fn(y_pred, y_batch)\n\n            optimizer.zero_grad()\n            loss.backward()\n\n            optimizer.step()\n            avg_loss += loss.item()\/len(train_loader)\n            #avg_auc += round(roc_auc_score(y_batch.cpu(),y_pred.detach().cpu()),4) \/ len(train_loader)\n        model.eval()\n        \n        valid_preds_fold = np.zeros((x_val_fold.size(0)))\n        test_preds_fold = np.zeros((len(test_features)))\n        \n        avg_val_loss = 0.\n        #avg_val_auc = 0.\n        for i, (x_batch, y_batch) in enumerate(valid_loader):\n            y_pred = model(x_batch).detach()\n            \n            #avg_val_auc += round(roc_auc_score(y_batch.cpu(),sigmoid(y_pred.cpu().numpy())[:, 0]),4) \/ len(valid_loader)\n            avg_val_loss += loss_fn(y_pred, y_batch).item() \/ len(valid_loader)\n            valid_preds_fold[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]\n            \n        elapsed_time = time.time() - start_time \n        print('Epoch {}\/{} \\t loss={:.4f} \\t val_loss={:.4f} \\t time={:.2f}s'.format(\n            epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time))\n        \n    avg_losses_f.append(avg_loss)\n    avg_val_losses_f.append(avg_val_loss) \n    \n    for i, (x_batch,) in enumerate(test_loader):\n        y_pred = model(x_batch).detach()\n\n        test_preds_fold[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]\n        \n    train_preds[valid_idx] = valid_preds_fold\n    test_preds += test_preds_fold \/ len(splits)\n\nauc  =  round(roc_auc_score(train_target,train_preds),4)      \nprint('All \\t loss={:.4f} \\t val_loss={:.4f} \\t auc={:.4f}'.format(np.average(avg_losses_f),np.average(avg_val_losses_f),auc))\n\"\"\"\n## LightGBM Model\n* reference this kernel : https:\/\/www.kaggle.com\/chocozzz\/santander-lightgbm-baseline-lb-0-899 \n\"\"\"\n## Use no scaling data to train LGBM\ntrain_features = train_df.drop(['target','ID_code'], axis = 1)\ntest_features = test_df.drop(['ID_code'],axis = 1)\ntrain_target = train_df['target']\n#LGBM Paramater tuning\nparam = {\n        'num_leaves': 7,\n        'learning_rate': 0.01,\n        'feature_fraction': 0.04,\n        'max_depth': 17,\n        'objective': 'binary',\n        'boosting_type': 'gbdt',\n        'metric': 'auc',\n    }\n\"\"\"\n## LGBM training\n\"\"\"\noof = np.zeros(len(train_df))\npredictions = np.zeros(len(test_df))\nfeature_importance_df = pd.DataFrame()\nfeatures = [c for c in train_df.columns if c not in ['ID_code', 'target']]\n\nfor i, (train_idx, valid_idx) in enumerate(splits):  \n    print(f'Fold {i + 1}')\n    x_train = np.array(train_features)\n    y_train = np.array(train_target)\n    trn_data = lgb.Dataset(x_train[train_idx.astype(int)], label=y_train[train_idx.astype(int)])\n    val_data = lgb.Dataset(x_train[valid_idx.astype(int)], label=y_train[valid_idx.astype(int)])\n    \n    num_round = 15000\n    clf = lgb.train(param, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=1000, early_stopping_rounds = 100)\n    oof[valid_idx] = clf.predict(x_train[valid_idx], num_iteration=clf.best_iteration)\n    \n    fold_importance_df = pd.DataFrame()\n    fold_importance_df[\"feature\"] = features\n    fold_importance_df[\"importance\"] = clf.feature_importance()\n    fold_importance_df[\"fold\"] = i + 1\n    feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n    \n    predictions += clf.predict(test_features, num_iteration=clf.best_iteration) \/ 5\n\nprint(\"CV score: {:<8.5f}\".format(roc_auc_score(train_target, oof)))\n\"\"\"\n## Ensemble two model (NN+ LGBM)\n* NN model accuracy is too low, ensemble looks don't work.\n\"\"\"\nesemble = 0.6*oof + 0.4* train_preds\nprint('NN auc = {:<8.5f}'.format(auc))\nprint('LightBGM auc = {:<8.5f}'.format(roc_auc_score(train_target, oof)))\nprint('NN+LightBGM auc = {:<8.5f}'.format(roc_auc_score(train_target, esemble)))\ntest_preds.shape,predictions.shape\nesemble_pred = 0.4* test_preds+ 0.6 *predictions\nid_code_test = test_df['ID_code']\n\"\"\"\n## Create submit file\n\"\"\"\nmy_submission_nn = pd.DataFrame({\"ID_code\" : id_code_test, \"target\" : test_preds})\nmy_submission_lbgm = pd.DataFrame({\"ID_code\" : id_code_test, \"target\" : predictions})\nmy_submission_esemble = pd.DataFrame({\"ID_code\" : id_code_test, \"target\" : esemble_pred})\nmy_submission_nn.to_csv('submission_nn.csv', index = False, header = True)\nmy_submission_lbgm.to_csv('submission_lbgm.csv', index = False, header = True)\nmy_submission_esemble.to_csv('submission_esemble.csv', index = False, header = True)","meta":"{'source': 'AI4Code', 'id': '1f79e1d5bb1577'}"}
{"id":"80492","text":"\"\"\"\nCredits to the Experts (Please like their kernels)<br>\nAshish Gupta: [24+ top lgbm models outputs](https:\/\/www.kaggle.com\/roydatascience\/lgmodels)<br>\nKonstantin: [ieee-internal-blend](https:\/\/www.kaggle.com\/kyakovlev\/ieee-internal-blend)<br>\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport glob\n\nfrom scipy.stats import describe\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\n# Stacking Approach using GMEAN\n\"\"\"\nLABELS = [\"isFraud\"]\nall_files = glob.glob(\"..\/input\/lgmodels\/*.csv\")\nscores = np.zeros(len(all_files))\nfor i in range(len(all_files)):\n    scores[i] = float('.'+all_files[i].split(\".\")[3])\ntop = scores.argsort()[::-1]\nfor i, f in enumerate(top):\n    print(i,scores[f],all_files[f])\nouts = [pd.read_csv(all_files[f], index_col=0) for f in top]\nconcat_sub = pd.concat(outs, axis=1)\ncols = list(map(lambda x: \"m\" + str(x), range(len(concat_sub.columns))))\nconcat_sub.columns = cols\n# check correlation\ncorr = concat_sub.corr()\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(len(cols)+2, len(cols)+2))\n\n# Draw the heatmap with the mask and correct aspect ratio\n_ = sns.heatmap(corr,mask=mask,cmap='prism',center=0, linewidths=1,\n                annot=True,fmt='.4f', cbar_kws={\"shrink\":.2})\n\"\"\"\n# Select models with low average correlation\n\"\"\"\nmean_corr = corr.mean()\nmean_corr = mean_corr.sort_values(ascending=True)\nmean_corr = mean_corr[:6]\nmean_corr\n\"\"\"\n# GMEAN of models with low average correlation\n\"\"\"\nm_gmean1 = 0\nfor n in mean_corr.index:\n    m_gmean1 += np.log(concat_sub[n])\nm_gmean1 = np.exp(m_gmean1\/len(mean_corr))\n\"\"\"\n# Weighted GMEAN by inverse correlation\n\"\"\"\nrank = np.tril(corr.values,-1)\nrank[rank<0.92] = 1\nm = (rank>0).sum() - (rank>0.97).sum()\nm_gmean2, s = 0, 0\nfor n in range(m):\n    mx = np.unravel_index(rank.argmin(), rank.shape)\n    w = (m-n)\/m\n    m_gmean2 += w*(np.log(concat_sub.iloc[:,mx[0]])+np.log(concat_sub.iloc[:,mx[1]]))\/2\n    s += w\n    rank[mx] = 1\nm_gmean2 = np.exp(m_gmean2\/s)\n\"\"\"\n# Top Blends weighted by score\nBased on: https:\/\/www.kaggle.com\/muhakabartay\/0-8518-what-proper-weights-give-ieee-int-blend\n\"\"\"\ntop_mean = 0\ns = 0\nfor n in [0,1,3,7,26]:\n    top_mean += concat_sub.iloc[:,n]*scores[top[n]]\n    s += scores[top[n]]\ntop_mean \/= s\n\"\"\"\n# GMEAN Final Stacking\n\"\"\"\nm_gmean = np.exp(0.3*np.log(m_gmean1) + 0.2*np.log(m_gmean2) + 0.5*np.log(top_mean))\ndescribe(m_gmean)\nconcat_sub['isFraud'] = m_gmean\nconcat_sub[['isFraud']].to_csv('stack_gmean.csv')","meta":"{'source': 'AI4Code', 'id': '93d3a7121e1d14'}"}
{"id":"112158","text":"# Pablo Leo Mu\u00f1oz\n\"\"\"\n---\n\"\"\"\n# Imports necesarios\nimport numpy as np \nimport os\nimport cv2\nimport matplotlib.pyplot as plt\n# Directorios del conjunto de entrenamiento y test\ntrain_dir = \"..\/input\/train\/train\/\"\ntest_dir = \"..\/input\/test_mixed\/Test_Mixed\/\"\n\"\"\"\n## Generaci\u00f3n del conjunto de Train\n\"\"\"\n# Obtenemos las clases disponibles (nombres de las carpetas)\nclases = os.listdir(train_dir)\nprint(\"Existen un total de {} clases de corales\".format(len(clases)))\nprint(\"Las clases son: {}\".format(clases))\n# Cargamos el conjunto de datos de entrenamiento en memoria (hay ~17GB en la m\u00e1quina, nos sobra)\nx_train = np.array([cv2.imread(os.path.join(train_dir, cl, name)) for cl in clases\n           for name in os.listdir(os.path.join(train_dir, cl))])\ny_train = np.array([cl for cl in clases\n           for name in os.listdir(os.path.join(train_dir, cl))])\n\"\"\"\n## Probar la carga de los datos\n\nEsta celda muestra una imagen de coral totalmente aleatoria entre todas las imagenes del conjunto de entrenamiento\n\n\"\"\"\n# obtenemos un \u00edndice aleatorio\nidx = np.random.randint(len(x_train))\n\nplt.imshow(x_train[idx]) # mostramos la im\u00e1gen\nplt.title(y_train[idx]) # indicamos la clase del coral cargado en el t\u00edtulo\nplt.show()\n\"\"\"\n---\nEsta es la forma en la que he cargado los datos yo, aunque existan otras formas es la que me ha parecido m\u00e1s sencilla. Espero que os sirva por lo menos para empezar a trabajar y que no se haga tan dura la competici\u00f3n ;)\n\n---\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ce14112eb04f16'}"}
{"id":"64414","text":"\"\"\"\n# Global Education Quality Analysis \nIn this notebook, I analyse the education quality along with other factors such as GDP, Government Expendisure on education, and their qualitative strategy on education. The quality of education can be measure by the  OECD Programme for International Student Assessment (or PISA) as well as the equality of education. Of course, test score is not the most accurate tool to measure education quality but it is what nearest thing we can probably use. Moreover, PISA examination is said to be the most unbiased exam ever.\n\nThe tools I use in this analysis include pandas, numpy, matplotlib, seaborn, as well as Google BigQuery. I decided to use SQL (bigQuery) since the data is huge and using pandas can be slow.\n\"\"\"\n\"\"\"\n### Outline\n0. Hypothesis Setting\n1. PISA Score\n2. GDP \n3. Government's Expenditure on Education\n4. Regression Analysis 1: PISA Score and GDP\n5. Regression Analysis 2: PISA Score and Expenditure\n6. Conclusion\n\"\"\"\n\"\"\"\n# Hypothesis setting\n\nI work in an education reform field and would like to learn about what consitutes a good education.\nI believe that the government's interaction is crucial and think that the its expenditure would contribute to a positive impact on education quality.\n\nI also think that GDP could be correlated as well. Especially the GDP per capita!\n\nMoreover,\n\"\"\"\n\"\"\"\n# Notbook Setting\n\"\"\"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n\n# import os\n# for dirname, _, filenames in os.walk('\/kaggle\/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n\"\"\"\n## Data\nWe will mainly use 3 sets of data here.\n1. PISA sccores (2013-2015) provided by PISA. \n2. GDP from each country by World Bank.\n3. Education Statistics by World Bank. We will use SQL, more specifically Google BigQuery,to manipulate this dataset instead of python because the data size is really big.\n\"\"\"\n\"\"\"\n# 1) PISA Scores Set\nFirstly, Let's check the data foor PISA set first.\n\nBefore we started, it would be useful to know what kind of questions are in PISA exam.\n\n\"\"\"\n# Read pisa test score\npisa_data = pd.read_csv('\/kaggle\/input\/pisa-scores-2015\/Pisa mean perfromance scores 2013 - 2015 Data.csv')\npisa_source = pd.read_csv('\/kaggle\/input\/pisa-scores-2015\/Pisa mean performance scores 2013 - 2015 Definition and Source.csv')\npisa_data.head()\npisa_source.head()\n\"\"\"\nOk. so it looks like we will mostly work on the pisa_data part since the source is just some information for the context.\n\"\"\"\n\"\"\"\n# Data Cleaning\nAs you can see above. There are a lot of missing data including NaN and \"..\".\n1. Firstly, we will drop the rows that have all the three year's data being NaN first since they are pretty useless for our objectives here. For this one we can simply use using dropna function. \n2. However, for rows with \"..\", we will use drop function to look for the rows that have '..' and '...'.\n\n\n\"\"\"\npisa_data.dropna(subset=['2013 [YR2013]', '2014 [YR2014]','2015 [YR2015]'], thresh = 1, inplace=True)\npisa_data.drop(pisa_data[(pisa_data['2013 [YR2013]'] == '..')&(pisa_data['2014 [YR2014]'] == '..')&(pisa_data['2015 [YR2015]'] == '..')].index, axis=0, inplace=True)\npisa_data.drop(pisa_data[(pisa_data['2013 [YR2013]'] == '...')&(pisa_data['2014 [YR2014]'] == '...')&(pisa_data['2015 [YR2015]'] == '...')].index, axis=0, inplace=True)\npisa_data.head()\n\"\"\"\nOkay, this is looking better.\nNext, it looks like this data doesn't provide the sum of the scores of every part which are\n1. Math\n2. Reading\n3. Science\n\nTherefore, we will have to create another row for each country that combine the score from each part.\nLet's do that.\n\nAlso, the number is object (which is like a string), we will have to convert them into float.\n\"\"\"\n# It looks like there's a lot of missing values here\n_2013_not_null  = pisa_data.loc[(pd.notnull(pisa_data['2013 [YR2013]'] )) & (pisa_data['2013 [YR2013]'] != '..' ) &(pisa_data['2013 [YR2013]'] != '...' ) ].count()\n_2014_not_null  = pisa_data.loc[(pd.notnull(pisa_data['2014 [YR2014]'] )) & (pisa_data['2014 [YR2014]'] != '..' ) &(pisa_data['2014 [YR2014]'] != '...' ) ].count()\n_2015_not_null  = pisa_data.loc[(pd.notnull(pisa_data['2015 [YR2015]'] )) & (pisa_data['2015 [YR2015]'] != '..' ) &(pisa_data['2015 [YR2015]'] != '...' ) ].count()\n# print(_2013_not_null)\n# print(_2014_not_null)\n# print(_2015_not_null)\npisa_data['2015 [YR2015]'] = pisa_data['2015 [YR2015]'].map(lambda x: float(x) if x not in  ['..','...']  else np.nan )\n# pisa_data.loc[(pd.notnull(pisa_data['2015 [YR2015]'] )) & (pisa_data['Series Name'] == 'PISA: Mean performance on the mathematics scale') ].info()\n\"\"\"\nFor there, I am 100% sure that the info of others eyars are useless. Let's just focus on the data on 2015.\n\"\"\"\ndef pisa_sum(country, year):\n    math = pisa_data.loc[(pisa_data['Country Name'] == country ) & (pisa_data['Series Code'] == 'LO.PISA.MAT') , [year]][year]\n    reading = pisa_data.loc[(pisa_data['Country Name'] == country ) & (pisa_data['Series Code'] == 'LO.PISA.REA') , [year]][year]\n    science = pisa_data.loc[(pisa_data['Country Name'] == country ) & (pisa_data['Series Code'] == 'LO.PISA.SCI') , [year]][year]\n    sum_score = (float(math)+float(reading)+float(science))\/3 if (math.dtype == np.float64) & (reading.dtype == np.float64) & (science.dtype == np.float64) else np.nan                   \n    return sum_score\n    \ncountries = pisa_data['Country Name'].unique()\nfor country in countries:    \n    new_df = pd.DataFrame({\n            'Country Name': country,\n            'Country Code': pisa_data.drop_duplicates(['Country Name']).loc[pisa_data['Country Name'] == country , ['Country Code']]['Country Code'],\n            'Series Name': \"PISA: Mean performance in total.\",\n            'Series Code': 'PISA_TOTAL', \n             \"2013 [YR2013]\": pisa_sum(country, \"2013 [YR2013]\"), \n             \"2014 [YR2014]\": pisa_sum(country, \"2014 [YR2014]\"),\n             \"2015 [YR2015]\": pisa_sum(country, \"2015 [YR2015]\")\n            \n        })\n    pisa_data = pd.concat([pisa_data, new_df], ignore_index=True, axis = 'index')\n\n    \n\"\"\"\n## Looking into PISA Score\n\"\"\"\n\"\"\"\nLet's make a new dataframe consiting of only countries and the mean total score of each year.\n\"\"\"\ntotal_df = pisa_data.loc[(pisa_data['Series Name'] == 'PISA: Mean performance in total.') & (pd.notnull(pisa_data['2015 [YR2015]']))].copy()\ntotal_df.sort_values(by='2015 [YR2015]',ascending = False, inplace=True)\ntotal_df.head()\n\n_2015_score = total_df[['Country Name','2015 [YR2015]','Country Code']]\n# pisa_data.loc[pisa_data['Country Name']]\n\ncountries = total_df['Country Name']\n\nfig = plt.figure()\nfig.set_size_inches(15,10)\nplt.xlabel('Countries')\nplt.ylabel(\"PISA Mean Score\")\nplt.xticks(rotation='vertical')\nbar_graph = plt.bar(countries, _2015_score['2015 [YR2015]'])\n\n\n# Let's color Thailand to emphasize how shitty we are doing\n# Firstly we have to find the index of Thailand\ncountries = countries.to_list()\nthailand_index = countries.index('Thailand')\n\nbar_graph[thailand_index].set_color('red')\n\"\"\"\nAs sewn in the graph, Singapore has the highest score in terms of total MEAN score of PISA. And it exceeds the second place which is Hong Kong a lot.\nI honestly thought that Finland (7th) would be the first because it is always said that Finland has one of the best educational system in the world.\n\"\"\"\n\"\"\"\n# Map\n\n\"\"\"\n\"\"\"\nAs we can see above that countries with high PISA scores are in North Europe and Asia. However, is this trend consistent? Let us see more in detail by looking in the world map.\n\"\"\"\n\n\nimport geopandas as gpd\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))\n\n#merge both data sets using country code\/iso_a3 as unique identifiers\ngeomap_df = world.merge(_2015_score, left_on = 'iso_a3', right_on = 'Country Code')[['geometry','Country Name','2015 [YR2015]']]\n\n\nfig, ax = plt.subplots()\nfig.set_size_inches(20,15)\n# fig = plt.figure()\n# ax = fig.add_subplot(111)\n\ndivider = make_axes_locatable(ax)\ncax = divider.append_axes(\"right\", size=\"2%\", pad=0.1)\ngeomap_df.plot(column=geomap_df['2015 [YR2015]'], legend = True, ax=ax, cax=cax, cmap='RdYlGn',linestyle=\":\",edgecolor='grey' )\n# ax = PHL.plot(figsize=(20,20), color='whitesmoke', linestyle=\":\", edgecolor='black')\n\n\n\n\n\"\"\"\n# 2) Country GDP\n\nLet's look at the GDP within these 10 years!\n\"\"\"\ngdp_df = pd.read_csv(\"..\/input\/gdp-world-bank-data\/GDP by Country.csv\",skiprows=3)\ngdp_df.head()\n_10_years_span_gdp = gdp_df[['Country Name','Country Code','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015']].copy()\nlen(_10_years_span_gdp['Country Name'])\n_10_years_span_gdp['mean'] = _10_years_span_gdp.mean(axis =1)\n_10_years_span_gdp.sort_values(by=['mean'], inplace=True, ascending=False)\n_10_years_span_gdp.head()\npisa_and_gdp = pd.merge(_2015_score[['Country Code','2015 [YR2015]']], _10_years_span_gdp, on='Country Code')[['Country Name','mean','2015 [YR2015]']]\npisa_and_gdp.head()\nsns.scatterplot(x=pisa_and_gdp['2015 [YR2015]'], y=pisa_and_gdp['mean'])\n\ncor = pisa_and_gdp['2015 [YR2015]'].corr(pisa_and_gdp['mean']) \nprint('correlation coeefficient')\nprint(cor)\nsns.regplot(x=pisa_and_gdp['2015 [YR2015]'], y=pisa_and_gdp['mean'])\n\"\"\"\n# 3) Government's Expenditure on Education\n\"\"\"\n\"\"\"\n## SQL Big Query Setting\nHere we have to register the account for google could platform (GCP) in order to have access to the BigQuery datasets. Referece on how to do it here.\n\"\"\"\n# Set your own project id here\nPROJECT_ID = 'kaggle-278402'\nfrom google.cloud import bigquery\n# Create a \"Client\" object\nclient = bigquery.Client(project=PROJECT_ID)\ndataset_ref = client.dataset(\"world_bank_intl_education\", project=\"bigquery-public-data\")\ndataset = client.get_dataset(dataset_ref)\n\ntables = list(client.list_tables(dataset))\nfor table in tables:\n    print(table.table_id)\n\"\"\"\nI want to see the expenditure that a Thai government spent to education. Let's search for it.\n\"\"\"\nquery = \"\"\"\nSELECT DISTINCT indicator_name, indicator_code\nFROM `bigquery-public-data.world_bank_intl_education.international_education`\nWHERE country_name LIKE '%Thailand%' AND\n      indicator_name LIKE '%education%' AND\n      indicator_name LIKE '%expenditure%' \n\"\"\"\n\n# Set up the query (cancel the query if it would use too much of \n# your quota, with the limit set to 1 Gb)\nsafe_config = bigquery.QueryJobConfig(maximum_bytes_billed=10**9)\nquery_job = client.query(query, job_config=safe_config)\n\n# API request - run the query, and convert the results to a pandas DataFrame\nquery_result = query_job.to_dataframe()\n\n# Print the first five rows\npd.options.display.width = 50\npd.options.display.max_colwidth = 200\npd.set_option('display.max_rows', None)\nquery_result\n\n\n\n\"\"\"\nThere are several indicators that might be useful to use.\n1. Government expenditure on education as % of GDP (%)\t - SE.XPD.TOTL.GD.ZS\n2. Expenditure on education as % of total government expenditure (%) - SE.XPD.TOTL.GB.ZS\nThe slight different is that the first one simply tell use how many % of GDP a government spent on education.\nThe second one indicates how important the government thinks education is compared to other areas such as transportation, healthcare, or infrastructure.\nI think the first one is more relevant so let us focus on that one.\n\nSince the score we are looking at is from 2015, it would make sense to look at the expenditure around that time. I would be unfair to look at the information in 2015 since investment takes time. I think it is fair if we calculate the mean of the expenditure spent in the spand of 10 years, which is from 2005-2015.\n\"\"\"\nquery = \"\"\"\nSELECT country_name,country_code, AVG(value) as mean_spending\nFROM `bigquery-public-data.world_bank_intl_education.international_education`\nWHERE \n    indicator_code = \"SE.XPD.TOTL.GD.ZS\" AND\n    year > 2004 AND \n    year < 2016\nGROUP BY country_name,country_code\nORDER BY mean_spending DESC\n\"\"\"\n\n# Set up the query (cancel the query if it would use too much of \n# your quota, with the limit set to 1 Gb)\nsafe_config = bigquery.QueryJobConfig(maximum_bytes_billed=10**9)\nquery_job = client.query(query, job_config=safe_config)\n\n# API request - run the query, and convert the results to a pandas DataFrame\nexp_on_ed = query_job.to_dataframe()\n\n# Print the first five rows\npd.options.display.width = 50\npd.options.display.max_colwidth = 200\npd.set_option('display.max_rows', None)\nexp_on_ed.head()\n\n\ncountries = exp_on_ed['country_name']\n\nfig = plt.figure()\nfig.set_size_inches(15,10)\nplt.xlabel('Countries')\nplt.ylabel(\"Expenditure on Education in percentage of GDP\")\nplt.xticks(rotation='vertical')\nbar_graph = plt.bar(countries, exp_on_ed['mean_spending'])\n\n\ncountries = countries.to_list()\n\nthailand_index = countries.index('Thailand')\nsingapore_index = countries.index('Singapore')\nfinland_index = countries.index('Finland')\n\nbar_graph[thailand_index].set_color('red')\nbar_graph[singapore_index].set_color('green')\nbar_graph[finland_index].set_color('yellow')\n\n\n\"\"\"\nNow we're going to do the linear regression. \nHowever, the problem is that the dimension of these 2 sets of data are not the same.\nWe will have to only select the country that appear in both sets of data. This can be done by inner join.\n\"\"\"\n\"\"\"\n# Regression Analysis 1: PISA and GDP\n\"\"\"\npisa_and_gdp = pd.merge(_2015_score[['Country Code','2015 [YR2015]']], _10_years_span_gdp, on='Country Code')[['Country Name','mean','2015 [YR2015]']]\npisa_and_gdp.head()\n\n\"\"\"\n## per capita GDP\n\"\"\"\n# sns.scatterplot(x=pisa_and_gdp['2015 [YR2015]'], y=pisa_and_gdp['mean'])\nsns.regplot(x=pisa_and_gdp['2015 [YR2015]'], y=pisa_and_gdp['mean'])\n\n\ncor = pisa_and_gdp['2015 [YR2015]'].corr(pisa_and_gdp['mean']) \nprint('correlation coeefficient')\nprint(cor)\n\"\"\"\n# Regression Analysis 2: PISA and Expenditure on Education\n\"\"\"\n# score_and_expenditure = pd.merge(_2015_score, exp_on_ed, on='Country Name')\npisa_and_expenditure = exp_on_ed.merge(_2015_score, left_on = 'country_code', right_on = 'Country Code')[['Country Name','Country Code','2015 [YR2015]','mean_spending']]\npisa_and_expenditure.head()\n# let's define each for easier code\ngov_spending = pisa_and_expenditure['mean_spending']\npisa_score = pisa_and_expenditure['2015 [YR2015]']\n\nsns.regplot(x=pisa_score, y=gov_spending)\n\"\"\"\nIt looks like there is a positive correlation between two variables, not so strong however.\nLet's calculate the Correlation coefficient to get a better idea between the two variables. In this case, we will use Pearson correlation coefficien since we want to analyze the linear regression.\n\nOf course, correlation does not indixate causation. \n\"\"\"\n# using pandas\ncor = pisa_score.corr(gov_spending) \nprint(f\"Pearson's Correlation Coeefficient from Pandas: {cor}\")\n# using numpy\n# cor_coef = np.corrcoef(pisa_score, gov_spending)\n# print(f\"Pearson's Correlation Coeefficient from Numpy: {cor_coef[0,1]}\")\n\n# using scipi\n# import scipy.stats\n# correlation_coef, p_value = scipy.stats.pearsonr(merge_2015_score, merge_exp_on_ed)\n# print(f\"Pearson's Correlation Coeefficient from Scipy: {correlation_coef}\")\n# print(f\"p_value: {p_value}\")\n\n#p value is 3% meaning the there is a correlation. But of does there is not gaurantee that the government's expenditure cause that.\n\n\"\"\"\n# Conclusion\n\n### Regression Analysis 1: PISA Score and GDP\n**Correlation Coeeficient:** 0.6\n\nLooks like there is a positive, although not so strong, correlation between PISA Score and GDP. Of course, correlation does not imply causation but I do believe that these two variables effect each other more or less. \n\n### Regression Analysis 2: PISA Score and Expenditure\n**Correlation Coeeficient:** 0.3\n\nSurprisingly, there is not much correlation between PISA score and government's expenditure on education. I thought that this should correlate somehow. One possible explanation is that the expenditure was not efficiently utylized by the stakeholders. Another possibility is that there might be some kind of corruption behind the scene.\n\n\n\"\"\"\n\"\"\"\n### To do\n1. I made a mistake by focusing too much on GDP in this analysis. However, I should also look at the GDP per capita as well.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '76da05783c0ed3'}"}
{"id":"29280","text":"\"\"\"\nPreamble\n\nMy goal with this work is not to succed or make something better, but to learn how to use graph based representations\n\"\"\"\n\"\"\"\n# Deep Q Network (DQN)\n\nThis notebook is to create an agent that works using Deep Q Network (DQN) over the generic Q Learning approach.\n\n<!-- For submission check https:\/\/www.kaggle.com\/aithammadiabdellatif\/lux-submission -->\n## Q Learning\n\nQ-learning is an off policy reinforcement learning algorithm that seeks to find the best action to take given the current state. It\u2019s considered off-policy because the q-learning function learns from actions that are outside the current policy, like taking random actions, and therefore a policy isn\u2019t needed. More specifically, q-learning seeks to learn a policy that maximizes the total reward.\n\n![](data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7QAAAEMCAYAAABEGIkdAAAgAElEQVR4AeydB5gkVbmw+a9IkCiwIkFhyUHCIkGJIlFykJxzEBBBFMkgwQsKkkGWJYclZwWElSQ5CBIkgyIsi4AEYQnW\/7zH+5U1vd091T3dM90z73memuqpOvE9oc75vhMmyjQSkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCCBDiQwUQfGyShJQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEMhXaFgIJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEuhIAiq0OzJbjJQEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCajQtgxIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkEBHElCh3ZHZYqQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSECFtmVAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQ6koAK7Y7MFiMlAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAIqtC0DEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCTQkQRUaHdkthgpCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhJQoW0ZkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCCBjiSgQrsjs8VISUACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCACm3LgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJdCQBFdodmS1GSgISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEVGhbBiQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIoCMJqNDuyGwxUhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkoELbMiABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAh1JQIV2R2aLkZKABCQgAQlIQAISkIAEJCABCXQ\/gX\/\/+98dlYjPP\/88+\/TTTzPuXEVDXOP9Z599lnVa3Itx9bcEJCABCUhAAhKQgAQkIIGhRECF9lDKbdMqAQlIQAISkIAEJCABCUhAAhJoIwEUwgcddFB2yCGHZOuss062wgorTKA4bib43\/\/+99nBBx+cruWXXz6FUekPimquWgYl9amnnpottthi2VxzzZVtvPHG2SuvvJKs8+6+++7Ldtxxx2yiiSbKpptuuuzQQw9VqV0Lps8lIAEJSEACEpCABCQgAQn0IwEV2v0I26AkIAEJSEACEpCABCQgAQlIoLMIVFup21kx7K7YwBOF83e+852kGG6lQnvJJZdMimYUzii3i2bcuHEpPN69+eabxVfp9zPPPJOtvvrqyf0VV1yRFO3Yveiii5LS+oQTTkju8XfiiSdOvxdccMG6CvIJAvGBBCQgAQlIQAISkIAEJCABCbSFgArttmDVUwlIQAISkIAEJCABCUhAAhLoBgK33XZbUsC6vXTrcguWN998c0sV2sQOf4877rhc8VyM8UknnZSeo6Q+8cQTi6+SuyOPPDK9P+2009KK8R\/\/+MfZsGHDsssvvzx78skn07stttgiveMZ71DKo6DXSEACEpCABCQgAQlIQAISkMDAElChPbD8DV0CEpCABCQgAQlIQAISkIAEBpAAW2OziliFdmszgS3CUS63aoV2xO7iiy9O\/lau0GbL8M022yxd\/C4a\/icexCe2JCe\/UVZzxy\/eFf3EjcrsIkV\/S0ACEpCABCQgAQlIQAISGDgCKrQHjr0hS0ACEpCABCQgAQlIQAISkMAAEkCZucoqq6jQbkMe3HrrrW1RaFdTPkf0UUBXU0LzLBTalcpu3NbzM\/z2LgEJSEACEpCABCQgAQlIQAIDR0CF9sCxN2QJSEACEpCABCQgAQlIQAISGEACzz33XDb11FOXVmijGEUhWk0pWisZKM25apl676q5Cf\/KuIv4ci9jvxheNfs8w6+4qtkJP1ql0I6wuGOaUT7jtq8K7cq0Rzp7u9djFH7GqvHe\/OJ98GjELm7KxKMRv8uErx0JSEACEpCABCQgAQlIQAKtIqBCu1Uk9UcCEpCABCQgAQlIQAISkIAEuoIA52azdfXaa6+dryI+6KCDkrKUO4q9ovnkk0+yM888M9tqq62yVVddNdthhx2S3VBEYv\/AAw\/M2L4chesBBxyQtrZm2+299torKVN5\/vzzzydvx40bl40cOTLbeuut0\/uzzz67h5Ic\/yI+uEMZS1j83njjjbN11103O+GEE\/Lts4tx5TfKywsuuCDbdNNNs5lnnjmbf\/75s+233z67\/\/77eyg28S+uDTfcMCOdhMt13nnnpf\/D76effjrbZJNNshVXXDExW2211TLOrX799dfDSo97XxXaMLj++uuz\/fbbL51xTjyJP3Gr3B4czryHf+RBRIbnuAmFNvkUacZdpBc\/+R32i5MW3nrrrQw+X\/7yl7N11lkn23PPPbP77rsvLyd33nlnHu7OO++c3XLLLckfzuC+6KKLsvHjx0d00h3OhLPBBhtka621Vrbbbrtl559\/fu4fYUdcSM\/PfvazlNeXXnppttNOOyV3lJ+xY8f28Df+gR35j13KK2nnIk+Kim1+Uxb33XffbPXVV8822mijbO+9905pK9oLf71LQAISkIAEJCABCUhAAhIYKAIqtAeKvOFKQAISkIAEJCABCUhAAhKQwIAQQJkdSj4UmSge4\/\/ll1++h3L5lVdeSUrBOeecM7v88suzZ555Jvv+97+flKooG1H8oYBcbrnlsmmmmSY9x49dd901KcyvuOKK7KyzzkrPp5122qTU5j0KSxSMW265ZXqHchtFJAb\/Fl988WyKKaZI74jbggsumBTgo0ePTm6JN8rQSmUpfvzyl79M7i688MLstddey0gDCtQZZpghu\/LKK3OlJvGYffbZk13823HHHTMUsttss016RvoiPoSFnbvuuivF75JLLsmmm266bLHFFquqWC8qtIvK4eRhL39IA8zwHz6k+ZxzzsnWX3\/9NHGAeJCeMIQ199xz5+kovoMz\/Mhj3BXzGXcw4FnlO5TO5O2YMWPSO5S9L7\/8clI8L7DAAokleYshvGL4p5xySrbmmmtmlBn8ZVIDfnGRX7hH0fzoo48m5fcSSyyR7B199NHJP+K10EILpWe4ZwIF9+222y5NNCC8iG8lW9jts88+6T1hoNhGwV5pv5i2XXbZJcXrjDPOSOminFx11VWB17sEJCABCUhAAhKQgAQkIIEBJ6BCe8CzwAhIQAISkIAEJCABCUhAAhKQQH8SCOViUdGHIjCeR1x4xopclIGnnXZaPE6K5xEjRqTnrNTFYPfmm29Oz7D\/gx\/8IFdQ8x6FNc9Raj\/wwAO5XygkQxHOatkw+BfxQzF62WWXpfjFexTK+Dds2LA8HNygrOf5UUcdFVbTnXBYZTzXXHNlr776anqGfRS3odBFOc2zH\/7wh8mP448\/PtljZTl+cqFoDgMTnoXCNp5zLyq08bOsIQ9CYfujH\/0oTxvu8YdVzYRZVFrzruiu+I7npD3SGIrqyGvuKL3xk3vx+RtvvJG2pF944YXTxIBIw5NPPpnshzI\/3ES8v\/jFL6Y8jjyCJ3EnHijQCYvV5mGeeuqp9GyqqabK3nvvvRQH7EdezjHHHGnldHDEn3nmmSe5gXMYnm+++ebp+bbbbhuP0yQKwuRiVTqGlfVstx9pCMtMHMAeCvnYgSDeeZeABCQgAQlIQAISkIAEJDBQBFRoDxR5w5WABCQgAQlIQAISkIAEJCCBASVQVLqilKw0bHmNco+V0i+99FKP12yFzTvuYcI\/nr\/55pvxON1DacpK7lBM8oLfoeQsKid5F\/6hjC26CXdf\/epXUxxYDU78Wf37rW99Kz176KGHUrjFP8cdd1x6t8ceeyTlKu+KStYjjjgiWccvFJ8RJv+ffPLJKZ7YD1NUdIfdeId7OFSLe9ipdi9OCojJAkV7oTQuKq3jfa13xC0U2tWUtLXcoVAnDayMLqYPHssuu2x6d+2110bwuSKeldHYwQ3ntIdbJiXgH\/kdz8Jx+HfdddfFozz\/J5100uzFF1\/Mn+N3pCdW0fMy2E0yySQ9yithkX9MaCD9uI9V3NyL5sMPP8xwTzz\/+c9\/Fl\/5WwISkIAEJCABCUhAAhKQwIARUKE9YOgNWAISkIAEJCABCUhAAhKQgAQGkkBRYYySr9JwtjWKve9973tp9S6Kz7hQJPIOJWG4Df94XlT84m8otDl\/uWhQNoZCO1bPxvvwr5ZSmPO0CYvtqfHn3nvvTf\/z7B\/\/+Ed4k99DyTzLLLPk8SuGX1yFnjsq\/MAuCtG\/\/e1v2U033ZT94he\/yMOrTG9vcS942+Pnueeem\/xEWU94laaW8hl7td7hTyiAyyq0cYNiGpaR55V33nGOeJgIn1XSlYYywoQB3FB2Kv2K8hGr4nEfDFmhXeSLX2y\/HnGLsILd17\/+9arswl5vaQtWDz\/8cDjxLgEJSEACEpCABCQgAQlIYEAJqNAeUPwGLgEJSEACEpCABCQgAQlIQAIDRSAUhtUUxij9fv7znyelIecvo3CsdqGYDBP+oWisVJyGwpJ70RBOswrt2NJ68sknTwpPlKGEzRVK9mJYxfg98sgj6VUx\/GuuuaZovcdv0sM26mxZTnxJd6SJ8IoKVxxGWNXY9vC48A9xPvLII1P8F1100apK2VAaF7mHF7XeEfdgXHnmOG6ruWNrcrbkDp7cJ5544uxrX\/tattRSS2Xrrbdetvvuu+dbeBf9YWV3pSEOa6+9dvKvmkKbOHDBLUxsOU\/cyacwcCJs4oSbMMGO+FXL\/7BXTFuEW+1eOcEi3HuXgAQkIAEJSEACEpCABCTQ3wRUaPc3ccOTgAQkIAEJSEACEpCABCQggY4gUFS6hgIQJSLP+T\/OiJ5tttnqKggjMWzzHQrQogKS9ygMeVep0EYRHMpWwi6aYvwq\/cPeyJEjk5+LLLJIUihfddVVNcPHfmyhTjxYZY0phl9LgYkydvbZZ09+H3vssUlZT3x4HulFSVo0vcW9aDd+w\/yUU05JfnJudeRJvOceHLlXmlrviGusOibOlaaaO7gsscQSKS5bbLFFpZOq\/8eq\/WpxIw6bbbZZ8o8V\/2VMMER5XmSBXz\/96U+TX8Wwgt3cc8\/dQwFeGRYMIm2sstdIQAISkIAEJCABCUhAAhLodAIqtDs9h4yfBCQgAQlIQAISkIAEJCABCbSFQCgMUXaiMORiC3GeYzgfORS248aNmyAOKD2feuqp\/Hls6Y0blI5FE6uZKxXa2AuFdqVCOVboVlvlTFxDEbvzzjun8F5++eU8vsSt0px66qnpPVuUx3vuoeytDB\/3xG\/NNddM7nbZZZce6cJt8EFJeuCBB+YrloNFtbhXxqv4\/xVXXJH8nGGGGXqEFXYizUVFbm\/vSEOksaxCGzdxhvaSSy7ZQ6Ec4WHn3XffjX\/z\/KgWNyz95Cc\/SWn7yle+UtM\/\/AxTWT7jOXm\/9dZbJ7+KYV155ZXp2WSTTZa9\/vrrYT2\/4448K6aNVePVzBNPPFGVfzW7PpOABCQgAQlIQAISkIAEJNBuAiq0201Y\/yUgAQlIQAISkIAEJCABCUigIwmEwpAtxVH0ofBjle3tt9+e4suzUDb\/4Q9\/mCANe+21V1Ji4g4TSlyUvJWK0zIK7VCkR0ARP5Sxlf69+uqr2cwzz5wUmKy8xqCoJE6EXy2+oQxGsRqKU9JI+nFTGX74GcrgyvdjxoxJ7nD7yiuvZCh+w06waFSh\/d5772Vzzjln1fjAGaU54RUVucEr0lf5jrRGGio54raWu0cffTRtOz7ddNPlEwAiLLjNO++82aWXXhqPavoTFv7+97\/n25jfdddd8TjdiSPxKMY9GFbbcnyVVVaZgAPnprNaHz7Fs70joO9\/\/\/u5\/5E2yhBpKRr+X2ONNbIbb7yx+NjfEpCABCQgAQlIQAISkIAEBoyACu0BQ2\/AEpCABCQgAQlIQAISkIAEJDCQBFAizjrrrEkBeN999yUl7\/Dhw3usumUrbRSs00wzTXbWWWcl5R9K0auvvjpjJSzvUbS+9dZbWfEMa5SRrOpGOchW5Ouuu24Kh+2j+Z\/nKCBvu+22fDtv3D\/77LO5sjkU2qHAJVzCwi0ryXm+\/fbb91B2v\/TSS0mxjBI04kY6L7zwwmQfN0V\/7r\/\/\/lyhPXr06Oyxxx7r4R\/hhcJ3wQUXTIpr8uyZZ57J2No6tiLn\/G2Uo2+\/\/XaK329+85sUHorkO+64Iw+zt\/wmvAceeCC5XWmllTLiF2keNWpUngb8ffrpp1NYpI90F7f85qxsOJHWO++8M1doM1kBZS7Pcffiiy\/m7g499NCUH8GnmHaU\/s8991zuJ9vRL7PMMokx\/qDQj\/Ar\/Yk04x8TDciDWWaZJW0BTxy5WD1f9I9np59+erJL2MQ57P7pT3\/K00OYzz\/\/fI8yM2zYsOSOM9aJG9c999yTLb744nne8izydcUVV0x+4D8TJXi+5ZZbpvAi7t4lIAEJSEACEpCABCQgAQkMJAEV2gNJ37AlIAEJSEACEpCABCQgAQlIYEAJhBJ6nnnmyeaff\/6kqEbxWDQoR1nVjMIWRSrnO7MNN4ppDIpAlJSVF0rlm2++eYLn2DvggAPy1d+V7ggPEwpttqhebbXVkhIU5WYoLDn\/GMVkpcE922XPNNNM6azkaaedNltggQWyE088MVdSksZYtVwZPqugiwYF7x577JF94xvfSGlZdNFFs\/nmmy9DYRrneOPHySefnBF2pX\/8T1iVXIthFH+TJhTrxBm3cPz617+eHXbYYYlb0X9Wvsfq9+Jzfn\/88cd103jxxRfXjGtw5c5K5W9961sZCn3i8rWvfS3bcccdc5ahGK4Mv1qaYcB24Ouvv372pS99KVtuueUy8pf\/UZhjIt8r\/SNfaoUVK+Pxn8kGu+66a8bK8rnmmivlFXFhkkXRRNqWWmqplDbsMHGDreUp0xoJSEACEpCABCQgAQlIQAKdQkCFdqfkhPGQgAQkIAEJSEACEpCABCQggX4ngALwzTffzNgCOlY0V4sECj7eP\/jgg9kHH3wwgSKZd9hB+RsX\/+M\/93DPO+yiTOR3vIvnxTiEYhNFKu9ZBY4SnTgQZ\/yuZcJ\/VjizephweFY0ETb3iAv3Snu4CbsoXVGM8j8Guyho2U474hN+hb\/xfzHsMr\/hzFnOrC4eO3ZsCouwSROK84hTpJVwIh+CY4QdcYk7birzJvzjXml4xupz8iTyL+w04k+4wb\/3338\/+Ucci8yL\/vGumK5iHIlHvA\/2Rf95zznsrPrHXjVDuPhJHsbOAcW4VHPjMwlIQAISkIAEJCABCUhAAv1NQIV2fxM3PAlIQAISkIAEJCABCUhAAhKQQAkCodBm5axKxhLAtCIBCUhAAhKQgAQkIAEJSEACg5KACu1Bma0mSgISkIAEJCABCUhAAhKQgAS6nUAotNnmmlW0GglIQAISkIAEJCABCUhAAhKQwFAkoEJ7KOa6aZaABCQgAQlIQAISkIAEJCCBjiWA8pqzkrfeeuv8jGf+56rcWrpjE2HEJCABCUhAAhKQgAQkIAEJSEACLSKgQrtFIPVGAhKQgAQkIAEJSEACEpCABCTQCgIotDfccMPsoIMOSkpsFNmbbLJJxkptFdqtIKwfEpCABCQgAQlIQAISkIAEJNBNBFRod1NuGVcJSEACEpCABCQgAQlIQAISGBIEUFzHFQlWmR0kvEtAAhKQgAQkIAEJSEACEpDAUCKgQnso5bZplYAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJNBFBFRod1FmGVUJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACQ4mACu2hlNumVQISkIAEJCABCUhAAhKQgAQk0GEExo8fny277LLp+uSTTzosdkZHAhKQgAQkIAEJSEACEpCABAaagArtgc4Bw5eABCQgAQlIQAISkIAEJCABCQxhAqNHj84mmmiidJ199tnp7PAhjMOkS0ACEpCABCQgAQlIQAISkEAFARXaFUD8VwISkIAEJCABCUhAAhKQgAQkIIH+IfDoo49mCyywQK7QRrH9u9\/9rn8CNxQJSEACEpCABCQgAQlIQAIS6AoCKrS7IpuMpAQkIAEJSEACEpCABCQgAQlIYHARKCqzhw8fni2zzDK5Yvvcc891pfbgym5TIwEJSEACEpCABCQgAQlIoGkCKrSbRqdDCUhAAhKQgAQkIAEJSEACEpCABBol8Pnnn2corIsrs++\/\/\/7s\/fffz6aYYopcqX3QQQdlY8eObdR77UtAAhKQgAQkIAEJSEACEpDAICOgQnuQZajJkYAEJCABCUhAAhKQgAQkIAEJdCKBf\/\/739kdd9yRrbvuurnSmi3GTzrppAwlN+a+++7r8W6OOebIjjvuuOzjjz\/uxCQZJwlIQAISkIAEJCABCUhAAhLoBwIqtPsBskFIQAISkIAEJCABCUhAAhKQgASGIgGU2K+99lp2+umnZ2ussUYPZTXK7GOPPTZXZsMH+4888sgE9kaMGJHtv\/\/+2d1335199tlnbkc+FAuTaZaABCQgAQlIQAISkIAEhiwBFdpDNutNuAQkIAEJSEACEpiQACvkxo8fn33yyScZ27+ifFhuueWy5Zdf3ksGlgHLgGXAMlC3DHz729\/OLrvssuxXv\/pVts8++2Sbbrppso\/iuvKaeuqps1GjRvVQZsdXKZTarM6udMf\/8803X8Z25IRzzjnnZBtttFFG2H6r\/FZbBiwDlgHLQJky8Lvf\/S579NFH04SrTz\/9tOq3KL5J3iUgAQlIQAIS6AwCKrQ7Ix+MhQQkIAEJSEACEhgwAigO3n777ey6665LCoJVV101Q9FQTYngswmVMjKRiWXAMmAZ+E8Z+PKXv1zq27HSSiulrcf5\/tQzKBv4JsnXOmYZsAxYBiwDrSoD00033QTflc033zy76KKLsrFjx6rcrvdh9p0EJCABCUhgAAmo0B5A+AYtAQlIQAISkIAEBpoAK7GPP\/74bNZZZ51AsNMqoZH+KIC0DFgGLANDowxMO+20db8lfGv45rAarqzB7m9+85ts4YUXruu3ZWxolDHz2Xy2DFgG+loGqim0w89ZZpklO+aYY7KPPvrIoy3Kfqi1JwEJSEACEugnAiq0+wm0wUhAAhKQgAQkIIFOIsD5ozfccEO28sorqyCoshVuCLW8KzS1DFgGLAPly0AthfZss82W7brrrtkLL7zQtILgn\/\/8Z3b44Yen7cbNk\/J5IitZWQYsA5aBnmWgnkI7WC2++OLpSItGJmB10ljPuEhAAhKQgAQGIwEV2oMxV02TBCQgAQlIQAISqEOAVdn7779\/aUX25JNPnk055ZReMrAMWAYsA5aBumWALceHDRuWzrLeZZddsjPPPDN77LHH0ors3rYXr\/PZyl\/hB8qFJ554IjvjjDOy3XbbLWP78qmmmir7whe+UDdufsf8jlsGLAOWAcsAZYDvVCiue7uvv\/762fjx4\/PvkD8kIAEJSEACEhg4Aiq0B469IUtAAhKQgAQkIIF+J4BAZo899phAiMM2sD\/84Q+z2267LXvooYeyZ599NnvjjTeSMuKcc87Jzj33XC8ZWAYsA5YBy0DdMsD3gh1AuD7\/\/PO2f+MIg7BGjRqVVtL5rfJbbRmwDFgGLANlysDHH3+cxjpPP\/10du+992ajR4\/Odt5552zuueeeYJzEam3st2JiVts\/jAYgAQlIQAISGMQEVGgP4sw1aRKQgAQkIAEJSKBIAGX2iBEjeghpNttss+yCCy5o2eq5Ynj+loAEJCABCUhAAhKQgAQk0A0EUFgzSequu+7Ktt566x5jphlnnDEptbshHcZRAhKQgAQkMFgJqNAerDlruiQgAQlIQAISkECBANuMTz\/99LlgZpZZZsmuv\/76pMguWPOnBCQgAQlIQAISkIAEJCCBIU0A5fbNN9+crbPOOvn4CaW2248P6WJh4iUgAQlIYIAJqNAe4AwweAlIQAISkIAEJNBuAh999FG2xRZb5MIYfrP6QCMBCUhAAhKQgAQkIAEJSEAC1QkwZvr5z3+ej6N+9KMfZYytNBKQgAQkIAEJ9D8BFdr9z9wQJSABCUhAAhKQQL8SuPDCC3MhDMrs\/jjXtF8TaGASkIAEJCABCUhAAhKQgATaQIDV2ieeeGI+njr55JPbEIpeSkACEpCABCTQGwEV2r0R8r0EJCABCUhAAhLoYgJsNb7EEkskAcyyyy6rMruL89KoS0ACEpCABCQgAQlIQAIDQ+D888\/Pldp\/\/vOfByYShioBCUhAAhIYwgRUaA\/hzDfpEpCABCQgAQkMfgIotCeaaKJsoYUWyj744IPBn2BTKAEJSEACEpCABCQgAQlIoMUE2H58hx12SGOrMWPGtNh3vZOABCQgAQlIoDcCKrR7I+R7CUhAAhKQgAQk0MUE2CLvlltuycaPH9\/FqTDqEpCABCQgAQlIQAISkIAEBpbAp59+msZWAxsLQ5eABCQgAQkMTQIqtIdmvptqCUhAAhKQgAQkIAEJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAh1PQIV2x2eREZSABCQgAQlIQAISkIAEJCABCUhAAhKQgAQkIAEJSEACEpCABCQwNAmo0B6a+W6qJSABCUhAAhKQQJ8IfP755xnnc3PXSEACEpCABCQgAWxGCUoAACAASURBVAlIQAIS6BQCjFO4NBKQgAQkIAEJDB4CKrQHT16aEglIQAISkIAEJNAvBBAObbrpptm0006b3Xvvvf0SpoFIQAISkIAEJCABCUhAAhLojcC\/\/\/3vbLXVVsvWXnvt7JFHHunNuu8lIAEJSEACEugSAiq0uySjjKYEJCABCUhAAhLoBAIosw866KBsookmykaOHOkK7U7IFOMgAQlIQAISkIAEJCABCeQEGLMMHz48GzFiRPbKK6\/kz\/0hAQlIQAISkED3ElCh3b15Z8wlIAEJSEACEpBAvxJAMLTnnnsmZfbRRx+dffbZZ\/0avoFJQAISkIAEJCABCUhAAhIoQ+Cvf\/1rGrfMOOOM2fvvv1\/GiXYkIAEJSEACEuhgAiq0OzhzjJoEJCABCUhAAhLoFAIor48\/\/vgkFNpll12y8ePHd0rUjIcEJCABCUhAAhKQgAQkIIEJCNxwww1p\/DL99NN7pvYEdHwgAQlIQAIS6C4CKrS7K7+MrQQkIAEJSEACEuh3ApxDd+ONN2YTTzxxtvzyy2fvvfdev8fBACUgAQlIQAISkIAEJCABCTRCgHHMMccck5Tam2++uTtMNQJPuxKQgAQkIIEOI6BCu8MyxOhIQAISkIAEJCCBTiPwwgsvZAsuuGA2bNiw7L777uu06BkfCUhAAhKQgAQkIAEJSEACVQl8\/vnn2dZbb52U2hyb9Omnn1a150MJSEACEpCABDqbgArtzs4fYycBCUhAAhKQgAQGlADnZm+wwQZJAHTaaadlrHLQSEACEpCABCQgAQlIQAIS6BYC48aNy5Zaaqk0pmEbco0EJCABCUhAAt1HQIV29+WZMZaABCQgAQlIQAL9QoDVDPvvv38S\/Kywwgpu0dcv1A1EAhKQgAQkIAEJSEACEmg1gWuuuSaNaxZZZJHsnXfeabX3+icBCUhAAhKQQJsJqNBuM2C9l4AEJCABCUhAAt1KYNSoUUnoM9FEE2WjR4\/u1mQYbwlIQAISkIAEJCABCUhgiBP47LPPsk022SSNb5i0y+RdjQQkIAEJSEAC3UNAhXb35JUxlYAEJCABCUhAAv1G4KOPPsoWXXTRJPBhy3G3Gu839AYkAQlIQAISkIAEJCABCbSBwB\/+8Ic0vpl44omzO++8sw0h6KUEJCABCUhAAu0ioEK7XWT1VwISkIAEJCABCXQpAZTXv\/rVr\/LV2WPGjOnSlBhtCUhAAhKQgAQkIAEJSEAC\/yHAquwtt9wyjXPWWmut7JNPPhGNBCQgAQlIQAJdQkCFdpdklNGUgAQkIAEJSEAC\/UWAM+Xmm2++JOjZaqutsk8\/\/bS\/gjYcCUhAAhKQgAQkIAEJSEACbSNwxRVX5BN3L7nkkraFo8cSkIAEJCABCbSWgArt1vLUNwlIQAISkIAEJNDVBFidffTRR+dCnptuuqmr02PkJSABCUhAAhKQgAQkIAEJBAHO0l544YXTeOc73\/lOxlFLGglIQAISkIAEOp+ACu3OzyNjKAEJSEACEpCABPqNwOuvv54NHz48CXhWWGGFjG35NBKQgAQkIAEJSEACEpCABAYLgYMPPjifwHvWWWcNlmSZDglIQAISkMCgJqBCe1Bnr4mTgAQkIAEJSEAC5QmwOvuQQw7JhTunnHJKecfalIAEJCABCUhAAhKQgAQk0AUE\/vSnP+VjnsUXXzwbP358F8TaKEpAAhKQgASGNgEV2kM7\/029BCQgAQlIQAISyAmMHTs2m2mmmZJwZ7bZZsvefffd\/J0\/JCABCUhAAhKQgAQkIAEJDAYCTORdZ511cqX2tddeOxiSZRokIAEJSEACg5qACu1Bnb0mTgISkIAEJCABCZQncN555+VCnf322y9D0KORgAQkIAEJSEACEpCABCQw2Aice+65+dhn9913zz799NPBlkTTIwEJSEACEhhUBFRoD6rsNDESkIAEJCABCUigOQKclb3VVlvlQp2HH364OY90JQEJSEACEpCABCQgAQlIoMMJvP\/++9nss8+exj9zzjln9sknn3R4jI2eBCQgAQlIYGgTUKE9tPPf1EtAAhKQgAQkIIFE4J133smmmmqqJNBZYoklXKFguZCABCQgAQlIQAISkIAEBjWB7bbbLp\/Qe8011wzqtJo4CUhAAhKQQLcTUKHd7Tlo\/CUgAQlIQAISkEALCIwePToX5uy6665uN94CpnohAQlIQAISkIAEJCABCXQugZEjR+ZjILcd79x8MmYSkIAEJCABCKjQthxIQAISkIAEJCCBIU6A7cY322yzXJhz0UUXDXEiJl8CEpCABCQgAQlIQAISGOwE\/va3v+VjoAUWWMBtxwd7hps+CUhAAhLoagIqtLs6+4y8BCQgAQlIQAIS6DuBjz76KJt44olzYc7YsWP77qk+SEACEpCABCQgAQlIQAIS6GACTOz95je\/mY+DHn\/88Q6OrVGTgAQkIAEJDG0CKrSHdv6beglIQAISkIAEJJBdfPHFuRCHlQmfffaZVCQgAQlIQAISkIAEJCABCQx6AgcddFA+Fjr77LOzTz\/9dNCn2QRKQAISkIAEupGACu1uzLVBHGdmRt5yyy3ZY489NohT2Z6koXxgi1iVEO3h24yvUZ7Nk8bpPf\/886ktgKFGAhJoP4GddtopF+Jsu+22np\/dfuSGIAEJSEACEsgJPPLII9mTTz6Z\/++P\/ifwyiuvpAl+jj\/6n\/1QCRG5APIuy1jjOX7rrbcmdv\/+978bd1zCxejRo\/OxEOMiFdoloGlFAhKQgAQkMAAEVGgPAPTKIOmQ0aGlc1u2c4Z9lL6nnnpq9sILLyQvcfv2229nN9xwQ3bWWWdlr776aq\/+ffDBB9nll1+eHXPMMeleqXjDTzpyt912W7pXxq8y3vyPXQbklXYr0135P\/ZJz0QTTZRdd911Dbuv9G+o\/X\/\/\/fdnK6+8crbBBhvY+W4i8yl\/leW5CW9yJ9QbZvkussgiqV7mL\/xRisBVV12V2gIYki8aCUigfQSoY0svvXQuxDn99NPbF5g+S0ACEpCABLqYAGMG+vl8Oxsd79ZKNv1edkc5\/vjj7ffWgtQPz6+55ppsxhlnzA488EAnifcD704PQvlAZ+UQizeQFbZLPvDMM8\/kY6E555zTc7Q7K\/uNjQQkIAEJSCAnoEI7R9F\/P+gYf\/LJJ9lTTz2VsZXNLrvski2\/\/PLp2nHHHTMGUr3NBqQzx6D3O9\/5Tup03XnnndmFF16Y0fFac801sxVWWCGbffbZs5NPPrnqQJsB+MEHH5zNPffc2XrrrZf9+Mc\/zrbccstsm222ycMmnr\/97W+zKaecMjviiCOSf88991wOivexLc9dd92VnqNUpZNJ2KSxrMGvM888M7k9\/PDDHciXBVdhjzIF\/3XXXTfPxwor\/vt\/BFpRD2vBZGLIPvvsk00\/\/fTZmDFjalnzeR0C5M++++6byvMJJ5xgm1CHla8k0FcC9DmmmWaaVN\/4hjz66KN99VL3EpCABCQggUFDgL79e++9l918883Zz3\/+8zTeZvzOmIvx\/Lhx45ruqz7wwAPZdNNNl+26664NjZ8HDdwOS0is0mT8UTnZv8OianRaTKCefGDnnXdOq4N7k9PVipLygVpkyj8vygfaMfmHPEL2yViI69lnny0fOW1KQAISkIAEJNBvBFRo9xvqLCmWP\/roo+zII49MyujoKH3lK1\/JllpqqTQbOJ4NHz48O\/fcc6sOjNkKa+aZZ85efPHFjG13cDP\/\/PNnK620Ut7pQmGNshrFduVAjE4424nirji7kQ7i1ltvnVZ3gwX\/idv48eOzq6++OtnfaqutcmKEseqqq6bn0bH\/4x\/\/mP7Hb+JW1rDafJZZZsnWWmutCeJb1g\/t\/YcAnXv4owwkjzQ9CVDOqYcIo5gUAisuyvq3vvWtVA7jWdTDyjrU08ee\/8H8\/PPPT35yJi3haZojwKQYhIXkB0w1EpBAewiwxX+0e5NMMokC9fZg1lcJSEACEugyAowBfv\/736cx6tRTT51\/K0eMGJHNO++82WSTTZaeMSmMyayNTOgGxd\/+9rc0\/lhjjTWcjNwhZYOx3N57753y9bzzznMs1yH50s5ohHygjJxu8cUXTzsSNiJnwW7IaJQP9C0nkU22Sz5APiEPijEReaWRgAQkIAEJSKDzCKjQ7qc8YTDMquoll1wydZBQYJ9xxhnZn\/70p6R0pBONUphV1ryLTtRxxx03gYL3tNNOy1ZfffUU81CcMau72KnmN8q6KaaYosfgmOco8vB\/iy226OGGOC644IJpy3I833333dOqaX7vueeeyQ2rusM8\/PDD6RmdvmLY2MF\/Bv9lDAP\/ddZZJ7lhu3JN3wiQj6uttlriOWrUqL55Nshcl62HbPv3ta99LTGkLFMPY9JGb0jYqmqOOebIEEwRnqZvBO64444kLJxpppky2hyNBCTQegIxaY32jravbHvX+pjoowQkIAEJSGDgCTA2f+mll7K99torHw8ccMABaZz8zjvvpLEv418mhMU4mW8oO5+99tprpRLAOGH99ddP\/jP20HQOgQ8\/\/DD79re\/nTH+eOihhzonYsak5QTo8zYqp2Py529+85vSY\/0rrrgi1XPlA63JvpAPfPWrX225fICzs2nLuZCbujihNXmmLxKQgAQkIIFWElCh3UqaNfx6\/PHHs0022STvGLE6up6ii9WjSyyxRG7\/xBNP7OEzMwUPOeSQ1LmKATRbjhcN\/tMJYwZpMSy2BI9tdAiH1d5sF87Z1d\/73vfSGcz\/+Mc\/kles3n7rrbfSgJ1zgJmBzpbWYUJxzUC\/qNC+9tprs8knn7xHuOGm8k4H8dhjj01x\/cEPfmCHsRJQk\/\/ffvvtieliiy3W8EqBJoPseGfN1MPiCu7KelgtwdQ1djGg7imYqkaouWe\/+MUvEtMddtihR1vTnG+6koAEKglwrEgIb+g3FL\/plXb9XwISkIAEJDCYCfANZLvp2WabLX0b2UWs3qpKxrOnn356\/h1ddNFFs3\/961+9ImL1L99ejgtzIlmvuPrdAtvLkz+MP4rylH6PiAG2jQCyrVbK6apFlLITxwQygVTTGgIhH0CG2MpxS8gmqfscx9jorhutSZ2+SEACEpCABCRQj4AK7Xp0WvDu5ZdfzhjUhqCYFchlZvndc889aXU17uabb76kWK6MDp1jVlSzOrtykHXZZZelMDmTOzp4hMvq7ogLd1Ziffe7302rselgV\/pDmKy0xu7GG2\/c431s9XP55Zf3iNrIkSPTtmwRbo+XFf\/cd9992bTTTpvNMMMMaYvzitf+2yQB2K+44oop30455ZRSZa7JoLrCWbP1kK3wmZxRrx4WATBTG7uskK9Wl4p2\/V2ewN\/\/\/vd8Is69995b3mGTNsk7BJMKF5sEqLOuIkDfoCjMQ7Bepp\/SVYkchJGlnWJFESsFNRKQgAQk0BoCjKGOPvro1J+nT89xXGX6g7jbZZddcncoW+p9S5lYHju3qeRqTd612he+szGe5lg1zeAi0Kx8oIycrkgq5G\/IB8rIx4pu\/V2bQMgHkCOym0arzKWXXpq340svvXSp9r9VYeuPBCQgAQlIQALlCKjQLsepKVsIGWM2JgNiBkL1BrbFQOjsbrDBBnln6tBDD53A7bPPPpves\/14sXNMGGwnTphnnnlm7i3Pd9111\/Scld3MNsQdg7Va8Sq6Oemkk3K\/GNijTCeMcePG5c\/5wSzJ4tbkPV4W\/iHs2MZt++23rxmHghN\/NkAgtpZnlXYZQUwDXneV1VbWw8MOO6xmOYXxsssum+oEA1dN6wjQDq211lqJbX+s0iYvadtYmaGRwGAnwLf4G9\/4RirzlPvttttusCd5UKQv2il209FIQAISkEDfCfA9ZNcyvoVcK620UkNjKCZdhltWd3M+djVDOHFsGJPI+F\/TmQRiPO0q7c7Mn2ZjVU0+UNYv6uuGG26Y1\/Vqcrrwi77acsstl+wqHwgqrbkX5QNHHXVUy9rRYjs+bNgwV2i3Jrv0RQISkIAEJNBSAiq0W4rzv57ReS0qpFHYNjpY3XffffOO8je\/+c0JVnyeddZZ6X2l8pizvBhMTzrppBlKb8LFDoPqWIVV6ea\/Me\/5C7crrLBC8o\/tysOwfTNhsPochXgYOpZzzjlnfg53PK92f+ONN7KZZ545+XPNNddUs+KzPhDgfPYQqrBKu12GMsLkCPK+0wxls1gPm1GGVtZD6nY1c8MNNyTeU089dfb6669Xs+KzPhBgy\/coz+1eJRGKIhXafcgwnXYNAdrJqFvcf\/azn3VN3IdyRKOdUqE9lEuBaZeABFpJIHY4i28iKwAbMe+++26P7ynblFcztN8xUfPKK6+sZsVnHUKA3bqiPLAyV9P9BKh\/RflAO+R0Qem6665L5Qf5ALIvTWsJhHxgoYUWytj1ohWGdj\/qPHfzrRVU9UMCEpCABCTQWgIqtFvLM\/mGgi+UzdEZ+stf\/tJwSLF9MX5MM800PWYHojxkCzTeVW75jbKa5xtttFFSMvJ+s802SzPML7jggvSOldrVzJgxY3qsri4qtIuK69iGHGU3dsKw\/WWEFc9q3X\/961+nuNDB\/\/DDD2tZ83mTBCgjCy+8cGK86aab9ph40KSXVZ3dcsstKQwGh51kWlUPi3W5sh5Gegkr6uMqq6zSkcr9iGu33pkkEO0pbUc7DRM0CEuFdjsp63enEPjggw\/yukW5b3f96pR0d3s8VGh3ew4afwlIoJMIjB07NltkkUXy7+EZZ5zRcPQYKw8fPjz3g63Lq034veuuu3I7bHus6VwCjPGiXNA\/qpafnRt7Y1ZJgPwsytjo97ZaThdh0k9TPhA02nMvKp9vv\/32lgRCvn3pS1\/K2+g777yzJf7qiQQkIAEJSEACrSOgQrt1LHOf2IK7uH1ns6tnrr\/++rwjRWf7hRdeyMNgwDz77LOn95Wd8EMOOSQ9P++885ISe8stt8zOPffc5BZFDau9F1hggR4KTjpuscUayuowPN95552Tf8QHw0AulOZsqY6fGAYI6623Xvbggw+m\/+v9wY\/NN988+YsCELfNGtzG1emDTOJZnBjQbJrLuqPsUXbmnnvuhrbMK+s\/6UFZPtNMM+XloKzbdtvrj3oYaaCefP3rX0+sjzjiiHjc1D3KCPduKM\/Esz8MLJZffvnEmC2R2xmuCu325Sj5SH3h6vTy3T4KneXzW2+9leoV3wouzo7rZEO54TtKGapmaBva2T5UC3MgnpF+8qvZPuZAxHkwhkl5pLz1Z99uMHI0Tf1PgHJb+R2OslyvDY0yX819vVRgP77\/3Kkz9cKp51er3xGfPfbYI\/8WctYtzxo1pGnxxRfP\/dlxxx2rpvGXv\/xlsjPrrLP2qe1oNi8aTVe326ec9aWNPvDAA1N+Mf7oiz\/dznEwxL9V8gF2F4x+M\/einC440Ya0Qz4Q\/nfqnfrWX2074YR8gOMBKr9pzTCijs8333x5\/rqLRjMUdSMBCUhAAhJoLwEV2i3mS6fqgAMOyDtAX\/jCF7InnniiqVBOP\/303B86ykVFM9t\/84ztyio7jLE11o9+9KP0\/thjj80H5XTyrr766rTVN6urWYH405\/+NFtnnXWSkvumm26awD+2rua87GWWWSad98WZQSNGjEjncxMHZp6ypTVbKjHjtTI+1RJPR3GeeeZJaeDcoWYM4dDB3G233bJVV10123jjjZNgd\/z48S3pzDYTp2puYM7se7axI0\/Y4oozlFCakQbuzQhNqoVV+ay4AqBy4kOl3Wb+f\/HFF7PpppsuY6DfigFEM3Go5gauraqHrNCgnMdVrIcRNnU83rPLQaMGdpRb6tE222yTBmbcqU8xYaRRP9tlH7YcOTBy5Mhs2223zdjtgZ0ZqNO8oyy3qzxzhjmc55133sSrXWlUod16spSJP\/\/5zxkTrRAaM5EJQS\/KuE4r461PfWf7+Nprr+XtF\/XrD3\/4Q8dGmLKy1157paNQ+O4wgY62hzaU30ceeWTq9zAR7+GHH25bW9QJgKhT5JcK7YHJDcodx18cfvjh6XxMBKrHH3983TJH\/5x+N99KjQT6kwBt5OjRo1N7QZvBtdVWW2W77757aj9pT+hz8oyyzLXnnnv2WLlIueUoK9yGHX6zUxP1oZbBHXWFY3\/YOWqGGWbIJptssjTZlnEsdaKae+KM37\/73e\/Snd\/Y5c7129\/+NrnDbS07PK\/md2VcK5VTv\/rVryqtlPqfsNjNKcYEnJ1bWd\/5n93MsMMZ3ZXvywQUTPfZZ580hmccz2\/GenDT\/GeifYy\/99577yQniMn+8KM\/UXa8wspP8gslV6u2NTaP+p8A+d4q+QC7L0Q9597f8oGyZbe\/KNP2IR9gZzvkA8i8rr322ryNJr7tinPIB1ZcccWWjClJC4t2In\/PPvvs\/sJoOBKQgAQkIAEJlCSgQrskqLLW2DobZUt0gDizutmBJUKC8Id7USFJh5BV0tU6hoTHIA1h70svvTSBHd4\/+uijGQrzo446KimpEfzWG\/Cz3S\/hcV144YXJLoMCBAAo4Rj4o\/iu50eRIed5R9qaOd8Z5R+KdfxYd911U6cZIQznd7MCnfedYOBx5pln5mllG3gU78Sb+DOwZrIAneZqednXNDCQD86tXnVHOaKMzjLLLBmK7U4y\/VUPI83kY3BGadeIoR498sgjqdxOPvnkacU79YyJD0wW2GmnndpSNhqJY9ilXYkzxRdbbLGkfF966aVT2mlvOHt32LBhSSDabLsXYVW701YEZ5Rw7TKkk3AQnGr6RoDy\/Y9\/\/COVa5hOMcUUSfi69tprZ9NOO23iPPPMM1dts8kH3GvaS4BVJVGvuD\/99NPtDbBJ3\/lGbrHFFimuCMpoL2ecccbUJ2GHGZQks802W\/oucZQJ31b6NoPVwIP84jus6V8CKDTiW1isO\/ymL1qtP8ezNddcM00Orfa+f1NgaEONAN9SlKuV5ZVntPncWUmIgplJZ6GU5Tv9wAMPpHFlrGBGmU2fb9lll839+8EPflB1DEhfkHFjhMukD\/pWPCueYfvjH\/94gnqD26LyKfwo3qlLjLWIU\/F5\/CZdvY1NYfPDH\/6wh\/u\/\/vWvTRWR5557roc\/TE6t7McQn5AVMC5s1MQYnzQyORBlLbuxxbbYZXZKazTMbrNPuYgJyfQH2BUOZRfMmAjPuI2d7sqOv4sTl5FhaLqTQCvlA9TtaGe4F+V0QaeV8gH6FkxaWX311dP4qVPlA+xQAZuQDxx33HFJPgAj0tBu+cDbb78d+Ju+02avscYaef7y3WpHvJuOoA4lIAEJSEACEshUaLe4EDCDr9i5bXaLGjpNrF4LvyaeeOKGz5nu5I7XjTfemKetUUUrA\/lQZiMQCUEBAgJWH6BQO\/\/88\/PnLc7i0t4xmGZ1fOQhyuXIk7vvvjt\/Hu8\/\/vjj0n6XtQiT\/\/mf\/0lhISyK8Mu6r2ePCQwoov73f\/+3pf7WC7Psu1bVQ8IrUw\/333\/\/PD+Z\/NGIQZnNEQAoYygXkUeU85NOOin52+wuD43Eoze7xIfVNZRXjlSgfBNXrsqzyMoIEHsLr9p72oqoL6zMaZchrYSjQrtvhGl\/Lr\/88lwwjuKN7a3DMLGKsg9rBDPFNpAdP3h+3333hXXvbSKAMiPqFfd33nmnTSH1zVtWfdBOPvTQQ0lBsdBCC\/WIN+WLdon+BbvIkBYE2tGm9i30znNNWkmjCu3+zRuU2Ww7W6wzlb85ZzX6phG7q666KrmhTdRIoL8J0A6i6GRlM0rrKLOsmEaxh0L0zTffzNtLvr1hh\/es5KbN5Tnfdgx9paJf7B5WaagH8Z3HP1YmR5vMPY674h19zPAbf3hPfFllzRVjP+zyLWDCMP5zFceVvEeByaTtSy65ZIK6WBlH0sHW37jjYrvxyvpb6abW\/6xIDH+4swtZpDfcfPDBB7kdlKuNGNp9Jr3iN21\/MZ5MPGDSDH5ib6ga0o4SDUZMHKBPE3nAWbjF\/KFslpkEz9gu3NE\/1XQngVbJByhPxQk9teR0RfnAG2+80RC0bpEPUH9CPhD9cPjQllfKB9g9qdjGNwSkjuVWywdoV7\/\/\/e\/ndZ7jHIdym1oHva8kIAEJSEACA0ZAhXYL0dNB+973vpd3fpih2Gznh44UK9hi8DTXXHM17VcLk9gyr1A8R9puvfXW0v7SQWYmOm4RwhQH8symDz9ZBd0s+9KRqWORskCnPuLDwLrSFN8vueSSbengw4cVa8QDIVKRV2V8Gvl\/7Nix2be\/\/e0kXCoqoRrxo112+7seUiZZmRJ53chADbtwxO3222\/fA0lxcHbyySfnwpgelvrpH4R9xYFd5TlhpAMhWjBgFU87DNu5RRiNToRpJD4qtBuhVd0ubU1xRT3tHXWl0txxxx15nrJrSNQfVi0xOakVM+0rw\/T\/ngTimJKoWwP57ewZs\/\/+R5xYlUI7SRmhjsYKf+JN+aLMIVgrtkWUwWrl7r8+d+8vmETauzcV3RVzyl30QVGA0U6xcgcFB3eO5iFP5phjjqy4iwhlk9U+fO+jjeuulBvbwUSASRnR3nNnvFnZ7lNOmZwY9lixjcK00hTHc6zarmxvqTPF1dPHHHNMj7EI9lGmRzj1JrERx+I2sOwSFoYtzcMPtr2tjEfYq3Zn8mK45c6k6GYNO5YV\/eJ4nkpTVI6inG7EFMcGzz\/\/fO4UNjGeYLIx3IeiodwWx9cosCsN5TTyaNNNN+1RHivtxv\/xvcUdfVVN9xGgbLRKTodf1LMoR9XkdHz3m5UPFOtzb\/KBgcwJ2pmQD7BrEvEuGjgV++QcudcOgywx8oJvUl8N3w9Wk4ef7ApFfmokIAEJSEACEugcAiq0W5gXdOqGDx+ed37o4DUyoC5GBYVhcbY4grDB1JEqbsPNKr2yho4yZ3\/TwWSruqIpCgjOPffcptkX\/Wz2d1E4wvne1coBq\/ejo8zgux2GcEPAikCJgUVfkGSx5QAAIABJREFUzSuvvJIGJ2zhVmZWe1\/Da9Q9ZaSyHjZbd8rUQxiEMG766advqJ6yFXOUgYsvvrhHUhn0xbtq25j1sNzGf2BX3GmAlf6VhnJW3K6RFSrtMEXFG21IuwxtOexdod08YVbRRvlFKFCrDlJfp5pqqmT3u9\/9bhLC8gy37ZrJ33yqBt4lHNmx4a677ppAcNRs7FhVF3nFvRPPhxw3blzGN+fqq69OyWSlYcSZbxtlBkPdZTVhvLvhhhuaxdLx7qKetKv\/0PEABiCCN910UypbrMyqVk\/oD8QWySi2ou9HuaVMshpV03cClH3OtGV751rflr6HMnh9iD5OtJPVlMiU3aLij+MeqrFmBXX4U22cgT+0USh\/5p9\/\/uzVV1+dACw7GoQf\/K5nWLUYiiSOmaJ\/TL2LSeAXXXRRPecTvCN+xf428WAHqmYMfhW3UccvVpZXmmeeeSZP7wknnFD5uub\/8A9l7TzzzNNjTFf89jGptBXjvZoRaeAF8WBVbCOT1xvwvodV+BfH3+uvv37eBhctXnHFFTn\/st9P0sGuAOQpbghL010EqCOV8oFm87GoQKVMVJPTtUo+wC4TRVNsrwZSPkCdiJ0QYMA51pWGNqsoH+B70Q6DLJE4cLVCPkC5YAwafrIrT7XvXzvSop8SkIAEJCABCZQjoEK7HKdSthC4RseH+1577VXKXTVLxQ4iflV2Zqu56aZnv\/zlL3NW1YQbtdISAtzgjKItznZjoELHHkF\/vU4ns+HbyZN4hNKdeN5zzz0TJIeOcnHWbjWBR9ERyk4EoY0KKAiH2efEgxVDjbovxuGf\/\/xndvTRR2czzTRT9q1vfSv717\/+lfzDz3ZexTiU+d3f9ZC0c447jBEw1St7lfEvDoiZeMAW+qx+xk\/KEVvsMlGj1oAbe5RnFL3tMtSvWAnJan8G6JWGeLDLAAwQ+FBW6plm62BxFwbakFpcaoVNPMtcsXqJbc3L2CevNP8lwLbinLFOeUBZ\/eyzz\/73ZcWvyvaSVY2xAhKFhea\/BCjvxdVfrDShfPbVVG7ByXe20wzfSMpTtD\/FPtKRRx7ZI7pMaEMRg2KjWhvBM9qgakqcHh4N0D98Q8q0O+yOAhMUqGXs2071LUOpF6w0QplW75vLpD\/6STHRgvKGkos2sRPrVt+o9L9rGBa3em2F8Lr\/UzGwIcKQtiOuapMzKLdFhTbjrWqm2I9lRXetPjDtT7H843+0dTFRhPgQZj2Du1DqYp8JpWPGjElpYUeORg1x4lzaYMH93XffbdSbZB9FeNGflVZaqeo3ujgh64ILLigdFryK40uOfGKXG74FfBv5pqHQrdUvgB1b5+6yyy417ZSOTB2L5DXx4jsd8e0PhXZlf7La+BuGe+65Z55PZRVsuGOMR\/5uu+22Nct5HSxD\/hV1rUxfpawd8qQR00r5AHWoWNeryZVIRyvkA5xFXSkfYCvvgZYPMBm2KB+o1sckz5daaqnEaooppujxDaiWd62SD1Tzu5FntJVFRTx9uEbLWyPhaVcCEpCABCQggcYJqNBunFlNF8waL3ZuGcg1Y+gwLbroorlfCAiKQoBm\/Ow0N5wpFqxQjJY1DNg52yzcxn2RRRZJA1SU43RCa5kQvKy33npt65gWBS0oAKsJFni24IILpnQgHP3www9rRTnlPenEXrXBQk2H\/3f+HCtqcT\/ppJM27D78RmD+xS9+Mfkz5ZRTJkEtQop2X5w9VY1fxKvavZ31sBp\/4rfiiismNmz318iAB8UvW3RFOY47XBE6VQuvmGYGfrhhS\/J2GNKyzjrr5PErnn1YDA+FZcS9t7pVrIP16mrR\/\/gdimbCgk8jrLFLeSpbZgmjrF0Guo2mJdI0GO\/77rtvXh6qrdgqppl8wU6Un3vvvTf7yle+ks7lHGzfvWK6m\/lNWxNHSASvattpNup3cYUd\/nYid8pJxIu6RjsTDMoKpIMLW0PjljakEw2T18q2PaSjrF3bqb7lNuWP\/niZ7SyjH4iCK1YOtes73bdUdZ\/rWO0e9Z+JAo32E7sv1a2NMX3L4Me9Gj\/a2aJCu1Y7G306\/Kmn0CYFjOEImwlKZ5xxRvbTn\/4022STTVIbFvHpTaGNP8SX9izcoFShzjXSJwyiuCl+T9hpqRqPsF\/vHn3yiBeTq6qZ2267LY87yvyyhjboiCOOyN1GOPQL2AnnD3\/4Q10GTz\/9dHLLeLIsK+yhPCtub14vvtiPeLENc\/xut0Kb8hrtLmHCpFoaYRgTLulrRr+iXpp4h1+xpfsqq6xS2l1v\/g6V94zNy\/ZVytpDyduIefjhh\/PySBlpVk7HWdixWh9\/asnpaEeK8oFGxom15AOMl5DJ9CYf2H333VNa29XvIG2V8oFqefHUU0\/lzNdaa62qdTLc0V7Ck\/a4EVa4R5aIW65G5QMRfvFO+D\/72c9yP9lBrGxbUfTH3xKQgAQkIAEJtI+ACu0Wsq0UCl922WVN+R4duuiYMZAcbOaoo47KO4ms5mvE0FENNpV3tp+rt91xuEWg3Q5DBx+lX8QLAUO1TjkrycMOW9PXG5iEsIit0xrtTBN2bJnEebTNCmmY1fyTn\/wkY3Yt8WYwxYXwoJ1XI4KeyM921sNqeQlTznaFCxNRqglQIm6Vd\/ITYV6Uhco7kzcYDFYzhBNnCbLaox2GcjnddNPl8au1XWrxCAFWjNQzlCPS2UwdLG7Rzm4B1fKjVtjw4uzBMuWVsk0cEayWsY+9RvK9VhwHw3Pqw4YbbpiXmd52KiEPiwptvn8TTzxx1gpF7WDgWUwD7cXcc8+ds6WM1mofiu56+x2r26L9qTfBqje\/+uM9ZeyrX\/1qzqGRSXHU0yhv7PLQieb3v\/99qXbHdqp\/c4+2irJX5rvz8ssvZ1\/4whfSakm+DyhXml312b+p7PzQWHUZbRV3+l3ki6Y8gdjdAX4LLbRQvvNF0QfKOWU3WNfaSSrGKNirpdDm24UyiXNIi5OyWMG82267pfFEhEOfq4zhSKBww73ergn1\/Ct+E\/Cn0X58+I0\/CyywQB4ndi2qNWZjJ7GIO8dPNWLYOehLX\/pS7j78iTu7uNTqj8b4qLeJp8X4UA5QMPJdKmuoj6SdK+LVboU2YRbPR2b8Xc1QTiJOTIqolUeVbmEaiw0Y89ViXOnO\/\/9DgDYHBWGZMVVZOy+99FJDeKP8R\/43K6c78cQT8zKEX7XkdJTJonygTN8hEkS5bFY+QLjdKB8IGV0zEw2QJUa+ImNshHUwL95xz\/g1\/GTcYJ0vEvK3BCQgAQlIYOAJqNBuYR4UZ1zTAWpkG7GIBp2llVdeOe9AMbOz7GAr\/OiG+0knnZSnsdHzf2B0\/fXXp22vo6NZvG+88cZVhTO4i1nZrAJsh2H1QWy9TJxqDXLOO++8PP29nZ+GAAi\/erNXLT10yDnXCfcjRozos9APgVSsimBmdCd27vu7HsJgo402Sow5975RJtRv6kNREFYszyh+q7UBcQYfK1PqTYioVi7KPqsUHD\/++OMTOKWM7bDDDnl5ZpvBWgY2UT+aqYPFleDMOu\/rgLVWPOFJHniGdi1CtZ+zip62JspwbwIj8rA4y58JPqzaaleZrh3z7nhDG4xSm4tvAoKrvhrqYuQX97fffruvXrbVfawyI65LLLFEQ20uvOabb76U3nZNBGpr4gue812AQVkFUMGpP9tMgHLGtxklNucG049r1\/eqzUnpOO8p9wisaQPZArjekRYdF\/kOiVBRoY2gvtp3hP5aUaGNMqiaKZ5ZjEK70i\/yi+8Wq4LjO0ObxXE20bct+lG2PSOc4spqVs+Gf9XiWesZ\/sQkJ+LH96HRfjx+czRUpI\/7yJEjawWZzugOu41umU87Qj+bo5\/Cj+J9lllmSVuQVwaOuzjq6vTTT698XfN\/WDSq0A7PcBtxa7dCmzLNiusIr9b4u6iM7G0CbqSDO+WEMR7+o2hspowU\/fN3\/xNohXygsr2oJ6fDbl\/lA5TXevIBwqg0\/SEfuPvuu\/O6Rp2oJR\/YYostcntl5QPN9M1bLR+gvdx6663zuKvQrixl\/i8BCUhAAhIYeAIqtFuYBwjgWQUbgymE8pWGjicDbu7VhFu\/\/vWvc\/ecPfrEE09UejEo\/j\/nnHPydFY746paIlEWM2CNQSQMX3zxxQy\/iquiWVGKvTDYJ29wj0CFLdB4j3uuVhrCKK5oRfBeacj34rk80XHnecQnflNWWJlNmWLFIukIO5X+VvuftC+88MLJPVs9NSPsqfQXP0KpzRmlkR+V9gbqf+LXn\/WQ9G+\/\/faJMasmyvIgnpQX8hM3\/M\/WpKyuKG6rz\/lbvAuDXcoBZwVSLhhkhT9hp1X3CINwWFVTrezxLCaKIEiLuFKGg0XEmfP98KvZOvjHP\/4xuccPVvKG\/61Kb\/gDX8JQoR1Eyt8pi1\/+8pfzfGJ3h3qGclIUGnB8hCsZ6xHLUh2LelbfZrm3lcc0\/P3vfy\/ncIBsIaimfnJxFmYZE21QsQ2JfgBlsBsNZQAGZRVA3ZjGbo0z5Q3lxzLLLJPyqGw\/t1vTOxDxpvxX65MMRFy6LUy+09GGooTm\/0pDu1hUaDe7QruorK61i9Y111yTxyfaM8Kv1Tbz\/KyzzkpumDweafn5z3+e90Er01Prf\/wqjr05Xqnarh+UNzhV+\/aye1CcE0tcOF+3Xv+UsWvEmd2Gyhj6pXyzInz8f+GFF7Lzzz8\/22mnnXL\/8JfJAmGwhxvcR1+dPOFZ+BV2q91x3w0KbeQlwZR7rfF3cRJEKNgoA721JbyPlfE77rhjr\/arsfTZwBKgDnS6fICySL2kraHucRFv5APsKtSofCD6ua0mXykfIJ6VhnYUuQD1sTf5QHFiLWmnvlXzszKM+L84AR\/5ABz7YnBfnGytQrsvNHUrAQlIQAISaA8BFdot5ErHqzioZKVZsUPF+c4MpGaccca0go0VrsUBFAPMOKeYzt8VV1zRw30LozrgXrHFWgw8620RHhFl+8ZQorKNGJ37ooFjbGNHpzmEM+RJnFUd4RXvrPKoZ\/CXsIr5WM8+dpmIQBjEp5qwAD9jNQDnJ0daUA4z4x43lJ1iPIu\/2aKvbHxIfyiXehOw1EtX5TviGOfkcmZbJ5n+rofkRXFbqvfee69XHNRtygCTH1DOVOZncabxpptumg\/q2PKvWBYqfyMkq2dgU61M1nJT3Emh1vb5lN+IR8SV9CCUZKIJ4dWrg7VWUVSLE21FhMU5mu0ykSYV2o0Tpu2dZpppUj7RBkb7Vssnysoee+yR52stoXkt9z7vO4Enn3wy50\/9anQbx77HoLwPlBfaomgH2K2lN1O5Kifcxr0o\/O\/Nr056T9tKGkIB1ElxG+pxoZzGqiq3px3qpaHz0s93Oto\/+qLFsWjEljJcVGjXWqFdb8tx\/F166aXzsHbdddfwvsednYgiPrRn9FXjaCPiUWmiL4wymLTETlT4UeabUOkfZ91H+Nzvv\/\/+3AppYLxOfUYZxjFOMcbEEnEtTspbfPHFe+1nF4\/PYSzVm6Gthx3hs8sRSqqiqfwuvvbaa+k1cYuth4vpi99HHnlk0Zuqvwl7IBTahNtb\/7EY4WIe1pqAy+4zMSYujtHJ3xh\/F\/0s\/uZM4+DGjhua7iNAfagnp6NeIWuaeuqp0xi9r3I66mUj8gHsNyIf2GeffVouH6jW3lbL6TLygRtuuCGvM9XkA7StUaeq3ZuVDzBBqq8GDssuu2wev1rfyb6Go3sJSEACEpCABJonoEK7eXZVXTJTOjplbH2FEhvDijPOXmL1GduShZAglDKc6RTCL9yjaKXjPVhNUQAyatSousmkU7n33nvnXGefffaqg9xgivCkKJxB8IEgJpTICEB4xoWgu5bhPYoWBjesACiTHwy+55133hRXhAjV3DBrPJTenF0Xdph1S1gM4uFDnBHsUB54zrOId604Vz6n3EV5\/MUvflH5uk\/\/I9DhrFwu4txJplgP2fYTQQcGHtTBynoYZ9hhr1gPEfZE\/tRLX+QTrHtTKlM22Rox8oUt8ivDgGfEY7\/99suDprxSBor1B6VrlIt6A1EmTCB0QxhH2apnNwJkskLE8+CDD47HPe6jR4\/O7cTg880330zKerZEJpyIc9RB2reIc2Xae3he8Q9tRcSHlZbtMiq0mydLu\/CNb3wj5ROC194Ekrwv1p\/4JjYfA102SqC4Woz6VW1lU6N+tss+7SeCaOI5ySSTZCgGejPRBtHu7b777skt38Nogz744IPevOjI93wn4ED90XQWAb5rcbxGfBc7K4bGZigTQHETfamyK7RrTfAr9kfxqzge4Pse4x3Cu\/TSS6tij\/FbtGf4QX+Rtq2yj8iOImzjz+TeCIvdf+jr454tw5977rmq4dR6iD\/FFdbRphJ2xA3lEf1d+uaMyfgW8W0p9l8Iv7c+D3EgPOxybbPNNrWilT8v9rNxU+0bTTvDO9JRjAP5wxXxZMzB\/3z\/6o2BI3AY9LdCm7ixPTo7lKFULDNeIc3TTz99YlBr\/E35C+5MjCNt+M34m62RK8taMOBe7CexUlbTnQSK8oGinI6xC2Uj5ANRX2JM0qycLvzB794mi9IuNCIfQJ4YphXyAZT9ZeUDY8aMyetSLflAtJ2kPfpBjcgHytT7SH+r5QO0BTGWJf7Iuuq1DxEP7xKQgAQkIAEJ9B8BFdotZs0AtzhTG0UsHVQ6tKxaCwU3wbI1GgN2zhYL5RWdJmY0DvZOE0xC+NDbGVZ0aCuZVvJhIBLKMgYrlQb7cW5mDE4q7RT\/x\/4xxxyTd9bJl1rCnKI78p+tvbFfbYY46Y732GFAjYnzjipZoHzE3s9+9rNiMKV\/F2esI8BotWG7NuJHme0kU1kP11577Zr1EKU1qzv6Ug9jK21Y9Lbaj7LFpAzscr311lsToLvqqqvSO2aJx0qLoiWe4ZaVBtXcF+3yG0FPnOOFO7ahZ1DZm2E1Q5wZF2W16IYt0IptV9QRtvtCiMl2iGEarYPhrng\/9thjU7prbQlZtNuX3\/CCU6SnL34NNbfkM5Mw4McOBEXBaiULVkFRN7EbV2y\/SbuP20YEGpX++385Aq+\/\/nrOn3xAcNephnYrygpCaNr6sga70V512s4iZdNQtEd\/Ahb0LzWdRYB2kD4p\/UCPUOisvDE2\/+kTRjtaXKlaZMO3t6iQqLV7CmOL8AuFNmU\/THFshp3tttsuXuV3lDxTTjll7gftGW318OHDU9tW7APgX7ThDz30UO4HP4477rjcD3ZDq9f36OHw\/\/4hfcVd0l555ZWk3CHexfNh77rrrhTOb3\/721xJjJ0ddtihdJikL8asa665Zq\/9HBSowZhtcCu\/e6QVf7Bz9tlnT+AfDGM8WTnOrMai+Iz8bIVCu+w4kfAqx98o2XozMInxNWyL5RC3TAKYZ555co6U7XgONyYN1DP0VyMPGPtoupMA5aRSphSymaKcjjrTCjldcSvtMvKBkI1R1qqN70M+QBmnPaw0RflAmQmftB1F+QAK\/UblA9X6oGeeeWZeX0hLjKc5JhD5QHHyP3W1ERldZZr5v9XyAeIU26UTf3Y5LH6LqsXBZxKQgAQkIAEJ9C8BFdpt4M2ZMcWZ3mybRkctBk8R5OWXX55mYsbgfNVVV03bnA2FDhMdxdg2tNYWdMGJO0poOpQoq+NsM\/zgQhHJbH3eH3LIIRMM9HGPG95\/4QtfqDpAKIbFbwY8CGZwE9ePf\/zjCQbIle74n057uKFDjyFPEWri5xJLLJF97WtfS3Z222239B5hBcqf4mCHtMVMXbagasYwezfiUk0x2oyfRTcMhFhlvvnmm3dcR7+yHiJsQnlWrR6y9Xtf6iEcYtXgZZddVkQ0wW\/KVggJORedASnlg\/zmHYPVKB\/MgK7WHtx0000pX9kir9r7ykAJI8pB3MtO7ED4hRvOPiR+GOJKOmFG3oefrH7ADgNtynZxsN1oHaxMA\/+HQI568dFHH1Wz0pJn5CdpigF4SzwdQp6QN3PMMUdiSPseCp0o53\/5y1+S8AHBzSqrrJJRniebbLJkH8EI9rh\/85vfzMvcEMLX70klf6IOc0cA16mmKFT+1a9+1VA0Y4IXE3pow7rdqNDu3BykfPEd3HbbbfNVpJ0bW2M2FAjwXaX9pF9TVP7S5tOfQzHNcTfjxo3LUNbyP8qN+DYwZsMtil\/aHsYr2GElbdhhsiZusYdShHrAtzzezzDDDElJHLxRuHAeMcfShCKHfiV+TzrppBljKMLjTv+vOLZmom+049Gvps8QYREu8eAqoxDFr5NPPjl3j4KYbwzK3OIW3\/QP2YkrxrBMLCUsmJQ10cchrmxRHumo5T627iUc+tLRl+JOfyu2UWZb32rxwP8YT8aOVcWweA\/DahfphQEMq72PZ0X\/4jf+Rn4g8yhj8K\/a+Ju09mbIa8JjggQTDzC4i\/O1gwF2KE\/Ej53YlllmmV7HFOxyhTvGQu0cf\/SWRt\/3nUClfAA5HeejV8oHaBcpM62SD\/S2FTZlP85tLsoHKMPU65APcPRALbnQjTfemMppf8gHQokMo1iwQ52KOBSPz6uUDxTbqaJ8oIwSvloJKMoHiu11NbtlnpEXlIlov2qtQi\/jl3YkIAEJSEACEmgPARXa7eGatjjefvvt844QHSIU1nRGf\/3rX6eBcMxGRGAwcuTICQahdKYGsyHNcGGg0FtaGVBzHi\/2v\/vd7yYhIQOPlVdeOZ11xKxrBCvFDnKRHdsT4xbWvYWFOzrknA9UXEnLdkNl3SIsio4wM4HZyowt51H+0dE+\/fTTU3zYFg0BBYN3eBQH7CgDY9UCAqZmDNvikW4E+LXYNONv0U2sxiSPOs0guEGxykpnOHBRD1HmtrIekvYYTCEc6c2QtyNGjEjxYUUBblC4xzPizFnclMNqhu1yScuee+5Z7fUEz8j7KAvBgfSXMcQ10oZbBnWxCiKEa8SDd6yYRKDGb869L5piHayVrqL9yt+4mWmmmZLf7Z4pTX6SBoRjmuYI0M4hBIUjk3VYmcWqqVB0M7EH4THli7w944wzkl3sR3nje1mmzW0uhroKAuQV3OPq1NXLfB85xiDi+ec\/\/zmSUOpOm4db2ttm2qBSgfSjJdp10kM7rOksAs8\/\/7x501lZMuRjQ\/tZqSiMtjTuKIlDKRjPqt35ZvTmF4ptDN942qiiP0z2YOtrVuoxtmK1XvFoKRTcKMpxWy8c3mOiz1YMo\/i7UlGVHFX5Q3\/jlFNOyfvi4QeTjjma6Cc\/+Ukag8aYgr4KytLi2I1vS5nxFgop\/J9iiil6tU\/6WC2KfcYJW265ZVK+sbsU\/WJWs7MzEvaqGTgxnmS8XS1ujJ8jrc3cycNqBhbhH0d3lTHkAfkFl3Bbdrtf0lYcf2+yySb56lO2jKecxViI8T0TjgijN0Uj+RvucDMY+g9l8mIw20E+0B9yOupkjGk4bqs3g2I4ZAHV5AOMpRhf1yqD\/Skf4DsQaWN1O4tKiDNb\/9PfRlEd9Wb11VfP5XjdIB\/48MMP8\/aHNoKdLzQSkIAEJCABCXQWARXabcwPOrGsdGIQRQcvtrqaccYZ06pWBvR0kqpt48agjJVrZc63amMS2uo1Z5zFYLXMFqcMclFwoDzjXC1mzx922GFpJijbMtXq3JOIEGSXVQDiBv\/orCPcYXBNHtYLowgLe6yEYHY\/ShzKwCWXXJIrZ0gL\/\/OcWf4ISnhWNGxpBh+U8GXDLbrHTQhd9t1336b8KPpX6zez9hmwNBPHWn628jmCHFaEIlBDKBIzrSvrIcK3olCKODRSDxHWNJJftA8IzhgMUpaZ7ICCjx0HCLcyLsEEzkzkIKxaM7TDbvFOeGwBzmpYZm43su0gDK+77rpUD1jlzrbQzMCOPCe+TNKgHPzwhz\/Mqp1vffjhh6c4N1IHi\/HnTL1oL4rnhhXttOo3rAhLhXbfiFIu2MaRvKeMs60dO12wcoZ3RUP7x3PaRATd7MYR5atoz9+tJ0BezDzzzHn9oq53quG7GDttVJahenGmPaXfQL1mpdVgMKSf9KjQ7rzcRLlE3iBc1kigEwjQBjIuoc8eF30cxqBx5\/gjVlbTHy7a4T0Xz3hHn5DxbdjhHn7EfezYsXmy+ZZjn7EI\/XBWITKuQvmIXxjaM9zSnnGnH4Y74hfh8Dx+8zzGTbiNOEf4YS\/ueWR6+UGYhE1\/nAnJrKBGucoK8rnmmiv1n5mMzBg+wi96SZ+HSam1+vBhly3NaSO4KrdPDzvFO2mk393MGJhJaoRDemrFi3RXuwg3VmhXe8+zahyIO+8ijXGGbjFNtX7D\/5133snLQyPjb+LCMVCMcYj3EUcckY7FijhyJy4oBtkdgPE38axncBPj6cHSf6iX3qHyjnJGu\/SjH\/0oQ+HKTmscO8BW08heWiWnC\/kA4\/zeyhrsiVc9+UCt\/MHvZuQD1PFWyAfWXXfd7Pjjj88efPDBPJ34HfIBJi3Vkw\/stddetZJW93lxQk6r5ANMLIi2i\/vtt99eNw6+lIAEJCABCUig\/wmo0O4H5nQw6dDRQeVCScr\/DMbpJDForjRsr8ZqR+wPVsMAMbYrbkS5xmAcply1BuZFZthDQQLrogKQyQJl3GOHTjqKR\/xqxEQca4XD+1p+nnrqqSnORQUg57gVz3KrFxcU5tEZZ3DfTlMrfe0Ms1G\/4dxoPTzttNPSxJIy9fD999\/PJ62wVXhZA7soB2U4snI78jXO18Jd2ckvCA9ZqXHeeeeVjWJuj3gSVq14UqervcMdK3Ir6yBK6mr28wALPxjo4h4hQ7u3+yO\/CQvBqKbvBMhj6h7lozcTZaw3e75vHQGYh+COcn\/iiSe2zvM2+ER8uRoxlL3Y4SG2RqRclm03Gwmrv+xSp8gvFdr9RbxcOJS1bbbZJuWNQtByzLQ1NAjQ5tJ2l+kLdAIR4kl\/kH5z3Ol\/0p9dbLHFJhijY4dtzy+88MJeow8HdmaiDW9k4kse3dH9AAAgAElEQVQwxD2\/ezPYYSIB4XA2dRi2AGY80ZshHBTD9NcbNbglXK5m+hXwj\/F3mbQW4xd8arnjPVcZE8d3Mf5g1almcBGgHDQqH0BOhxKcOt+boZ6xqIWJo0xkKWuijHKvVY6LftWSD1RTIhfdxW\/kk32RD9Rr13lXLQ2krVI+gL2yMjri3g75QBxRFO1XI\/kWPL1LQAISkIAEJNBeAiq028u3ru8oS+gosR0rK4\/pFP\/zn\/9MK9N4xgq1wW6uvfbaxGDppZdOg4l2pJdOdJxJHArAp556Ks22Z1vI3gyCDLbJLbtlXW\/+lXlPB59tyikfoYSng49QAUV1GRNbabFqtt4go4xfg9lOrXrIjGrqIavsqw3CKpmQZ4ceemjKs2ZnGVf6We1\/BGWUi+LKfdoKtmgsE89HHnkkuWc1S3+Zv\/71rylM4t1MHYQtZ7Xjnm0Xy6SzL2ljUE9YKrT7QlG33UKA+sRqJco8F6tVBpthlw7SVjw\/mx0B5p9\/\/tJC7U5jQp+RNKnQ7qycQTDOWcHkjcqPzsobYyOBvhJgPMXYgPrNFruM22mL77jjjtQWs0U6fcgyhtWh+MMZzrQb7TD0n2OHuNh9hTQwnmTHpt4M7luh0G5k4nrEaSDG3xF23OkfxXj6yCOP7Nr+QqTHe3kCRfkAuyNQz19\/\/fVs1KhRqQ0oK6crygfa2V8rygdinEwc6ffG\/\/VS32nygTKyq6J8gPrZKsPCBNpmLo4QJO81EpCABCQgAQl0FgEV2gOYHwx+o7PEfd55580mmWSS9IwZ3kOh88QAnq3bSD\/nGrfDEAb+owCkc0ynnvO4GaDSEe7NMECYbLLJ0rnovdlt1XviFVzY\/g\/D2aGcw11G6EE6OVONdIcAo1VxG2z+1KuH8Hv66adLJ5ntGjkTkJWAsQqwtOOSFhGgEa9QmpPXbIPIavLeDGWfLZ+ZQIKgqL8MM62LdZDy3UgdvPvuu5N7zrz729\/+1vZoEz9Wo5QZTLc9MgYggTYToF1AEEQd5WJr7jLCrzZHq6Xex5aE7HhC2qjjSy65ZMZOKN1qSAOrRmynOisHOdudekR\/zbzprLwxNhLoKwH6zqHQpp5PPvnk+aRp\/md73bKG9iFWaZdZ1V3W36I9vhPEi4vxJN8\/xpPLLrtsqTEw7htVaEf\/oRg2R8+QXp7F+2I8q\/1me2\/G32V3JqvmR1+fIYthPM34g8m5mqFDoFI+QD2IutSonG6g5ANzzjlnNnLkyF4zjXoZ8oH+lD8W5QPEgQv5wA9+8INS7RMTU8mTVssHzjjjjDyvv\/GNb5SSvfUKWQsSkIAEJCABCbSUgArtluJszLMXX3wx7yxFBznu119\/famOXGMhdqbt6DSuscYabUkzA2i2huP8K2bbfve738123333UoJGOvWcN7zHHnv0a2eWwX4IOc4+++xs2223TUrIsoOMUHqyyluBav1yX68eoiRmcFXWYJet6anH7VrRz\/bx+L\/KKqukQercc8+dzoMrIyBi27FJJ500Y6u0\/jRMwmi2DsL0e9\/7Xkoz5y1qJCCB1hNg+9Hof1BXG2n3Wh+b1vv48MMPZzPOOGNqN88666yskXaz9bHRx8FKgHrDcR7UpX322WewJtN0SWDIEmBMtckmm+Tfy\/hucmfM1ehk0VilzVndH374Ycu50ibttNNOKb6MDSPuZceTuG9EoY19jjDBTUzMhg27SPGMi3PNezOsch+I8XcxXoyrfvKTnyR2jD\/KjLOK7v3d3QTqyQcaldNRL9otHzjnnHNSWT344IPT7hFMdud3mXIb8oFGzrpvRe6yKpy+Oe0CcY22o4zsCqbtkg\/stttueRu\/9tprK0trRWbrhwQkIAEJSKDFBFRotxhoI94xmEQpVRwM8\/v4449veEDcSLidZpdO61ZbbZU4sPV6qw0dXgYenNfNyjOE2WU6ytjZe++901ZNY8eObXW0evVv3LhxafBDJ59zz8qszMZTZquy0p8tL++\/\/\/5ewxnqFmrVw6OOOqqpevjuu+9mI0aMSKu0X3755ZbjZWCKUIqyzDbBbNtPGe\/NIGRbeeWVU11rVODWm9+9vW+2DuJvbOO+4oorNpUfvcXN9xKQQJY99NBDeV9k+umnL\/296RZ2tEGXX3559v3vfz+1m9dcc82gS2O35MVgjif9Rrbspy9f9niYwczDtElgsBGgD37KKafk38sYw7Mjwz\/+8Y+Gk8u3ie248addW1rTLnFON+PJo48+utSYIRJC\/HBX9gxt7KOYqnf15hfj3YEcf0far7zyypQvTITn7HTN0CJQSz7QrJyuKB946aWXWg6zW+UDHK2HjG699dYrLaMDXizeaLV8AI4cHRFtOzvi8UwjAQlIQAISkEBnEVChPYD5QeeIcx033HDD1GliZjeK1zLK1gGMdluCZqDI7HRWhrVDCRiRhnnZTuljjz2W8uWGG24I5wNyJ74ICMoYys7qq6+e4s1q9LLuyvg9mO20uh5yNjsroZmoUXYVRKN8GynL+M2qbM6Lfe211xoNqqX2G4k353wzoGQb97JnErY0skPIM8ppf0906C+8tIMISNtVF\/srHe0M55133kl1LQQ4cdZ9O8McCL8baX8GIn6G2d0EaENXW2211Je1venuvDT2EqhFgP4EO32xne9CCy2UlMQc\/9Csod1gJy4mI7dzzNnIeDLSQv+pEYV2uOvLHZb0RTi3eKDM3\/\/+97SqnPEHxx5phh4B6kulfID62Rc5XSfKB04++eQkH6DMD6SBd1lTlA+0euxKmzds2LB8TMQRDRoJSEACEpCABDqPgArtDsgTOsZ0nvrSQe6AZPQ5Cv\/617+yKaaYImPr8VZ3TpuNHPnSLYaBQMzyv+eee1RmN5hxrayH5AV5gEBmv\/3265iVgGVX+TeIri3WUahxRtmss86avffee20JQ0\/\/Q4DyesABB6TyimBjsBm2t6QuMuO+EYHJYONQLz20f+wsEQrtBx98sJ5130lAAlUI0Gc87LDDMiZEdlP\/sUpSfCQBCdQhQP2OiYCt6FcwBmbXttlmmy3rpO8vabv44ov7vT1rBdM62Vf3FWMldsCaaaaZUtrrWvbloCfQTvlAJ8j+aMu6ST7ADoYhH3j\/\/fdbXv6YdBBjIe7XXXddy8PQQwlIQAISkIAE+k5AhXbfGepDCwmwCnODDTZo2\/nDLYxqx3mF0oazh66++mqVNh2QOwwQObcVJRrb22oaI8AZ5JRnBpaa9hKgrI4aNSoN4GefffakjGlviP3nO+ezLbDAAiltBx10UL8LZfsvpX0LiTIQWyUjwGFHB40EJNA4ARQxA6mMaTzGupCABDqBALuV0ffdaKONbEMGMEPoKzJ2o\/+okUCrCdDfpmwpH2iOLPWznfIBtkAvKrQ\/+OCD5iKqKwlIQAISkIAE2kpAhXZb8ep5MwTo6CsMbIZcprKmOWxtdUV55tI0RoA2QG6NMeuLbWbnszsGg3gUwKww7HZDGkKZTdrcArh+jnLGdAhxNttsM7\/D9XH5VgISkIAEJNBSArEatKWe6lnDBBx\/NIxMBw0SUD7QILD\/s95u+cDhhx+ej4UYO9oWNJdPupKABCQgAQm0m4AK7XYT1n8JSEACEpBAhxNAQHDHHXeks99Dqf3oo492eKxrR+\/WW2\/NldmcZ0\/anChVmxdvXn311VyIw0r9TtgKsX6MfSsBCUhAAp1MgO8IuxUdcsgh2VNPPZWUAyoIOjnHjJsEJCCBoUmAcSITemNy72mnnTY0QZhqCUhAAhKQQBcQUKHdBZlkFCUgAQlIQALtJoCQuTgznfMD2doNRWe3GITnxDmEEdz5XwF67zkIu6WXXjpn9\/jjj\/fuqAEb7AIwmFfJk7bBnL4GslqrEpDAECcQk+SWXHLJbOaZZ04Kbb7Hp5xySjr\/lHOZNRKQgAQkIIFOIcA4aLHFFsvHQc8880ynRM14SEACEpCABCRQQUCFdgUQ\/5WABCQgAQkMVQIM5rfaaqt8MI8AOhTbKDg7UTGM4Pydd97JzjvvvHSuWlGZvcUWW7jSuGRhhuNee+2V5\/1JJ51U0mU5awcccEDyG4XGYDO33HJLShtnInZiHRlsvE2PBCTQuQT4lnCExTTTTJNtvPHGeZv4pz\/9KVtwwQVTW3nwwQd3bgKMmQQkIAEJDDkCr7\/+evalL30pfaOWWWaZjIm4GglIQAISkIAEOpOACu3OzBdjJQEJSEACEhgQAtVWOYeSeNFFF8323HPPDAXe888\/n3388cdpVWp\/KPEIgxWw48ePz9566610zjervNgebsopp0wCiIgn9\/32209ldoMlKBSz8GNiQyvzddSoUXkeDabVeZRHViDCbIMNNrDMNVjm2mUdpRrtBe3ZYDSki7JHOjUS6CQC9A04toI28aGHHsqjxvckFNrXXntt\/twfEpCABCQggYEm8Jvf\/CYfpxx66KH2rwY6QwxfAhKQgAQkUIeACu06cHwlAQl0FwEEvG752l151tfYIiBlBrVC\/b6S7OkerqykRSBd7\/p\/\/+\/\/ZVNPPXU2yyyzZBdeeGE2duzYliqQyFuU5o899lg2zzzzZF\/+8peziSeeuG6ciO+JJ57Y0nj0pDN4\/4P3CiuskPjON998LV2dgN8bbbRRnneXXHJJ14MkTbPOOmtK07zzzpu99NJLXZ+mwZIA+gK0BWwfieJ3MBn6Ouuvv35KH5NQNBLoFAL0HbbeeutUNjfZZJMefTMmokV\/4l\/\/+lenRNl4SEACg5yA8oFBnsFVkteofAD76623Xv6NGjNmTBVffSQBCUhAAhKQQKcQUKHdKTlhPCQggT4RQKEZW9peeeWVffJLx91BgMFnnJd88803d0ekuyiW1Km77747Y9vuEEKXua+zzjrZqaee2qfJJSgKUaijAB0+fHjp8IkrcXaCQ3MFDW4nnHBCzvvGG29szqMarp566qke+clK7W7Nq9deey1baaWVclaXXnppS1e010Do45IEUGIvvvjiKX8OPPDAQZM31Be2a462+NFHHy1JRGsSaD+Bv\/zlL3nZpB9QNA8++GB6t\/zyyzvhrAjG3xKQQNsI8M1UPtA2vB3pMRMYGpUPPPfcc9kkk0ySvlFMoGYcqpGABCQgAQlIoHMJqNDu3LwxZhKQQAMEispNhGWu1G4AXpdaHTlyZC44VaHdvkxEMPDb3\/42W3fddXPeoUypd+f8sQsuuKAhoQBh4Qa39fyufEfcbrrpJoXkLSgGKGqHDRuW+DNBgLa1VQbB4kUXXdQjb3fbbbfsySefbFUQbfeHMnryySdnc801V56Offfd17LXdvKNB3D11VfneYRws5VlufHY9N0F9SeEtLSBxx13XNenqe9U9KGTCFx22WV5nXviiSd6RO2cc85J74444ogez\/1HAhKQQLsIKB9oF9nO9fess87Kv0Nld7EpTualn0V\/SyMBCUhAAhKQQOcSUKHduXljzCQggQYJvP3222l7UQS9nGXq7NoGAXaRdVZ2hlJzr732UpnUD3mHIu+uu+5KCpUll1wy5x\/5UOu++uqrZ\/fcc0+vMWT1FnZr+VP5fLnllsuOPfbY7IEHHjD\/e6Vb3gLCv5133jnlw\/\/8z\/9krV4Biv+cTVfMz2mmmSbbf\/\/909bynap0fPfdd7PzzjsvW3nllXvEnW11\/daUL1\/9aZNV2kUFML9px7rREO9iWih3H330UTcmxTgPYgJRRmebbbYeky2K35V77703KQuwq5GABCTQbgJvvPFGxjE69DuVD7Sb9sD634x8gO9T9O1nnnnm7OWXXx7YRBi6BCQgAQlIQAK9ElCh3SsiLUhAAt1EAIVbKEoYtLpSu5tyr\/e4Vq7w5Lxfhfq9c2ulDfIABd4NN9yQnXTSSdkee+yRrbnmmtmqq66aTTXVVHn9i3rIfcYZZ8xGjx5ddcY7\/t1+++3Z7LPPXtUtZxNvuOGG6dp7773TdubXX399Ukw5g76VOftfv+688848L1h93GqDcq64GqJYVhZYYIFsu+22S+WFLcqp37Tj\/aHoJgzC4tz2d955J3v88cczhGObbbZZNuWUU+ZMIr477bSTyuxWF44W+0d+rrbaanne0Vaxcrs\/ylMrkkIbd+utt2bsPBPljvv\/Z+88wLUo7vad75\/EhhVbFI0VTSxRFERFjcYeFWPBhgV7QSH2GisasWBXRFADiooYe42aKDaMgh019qiIvbeYzP+658uz35w9+5bT33PeZ65rz75np\/3mntk2z87M559\/3hrJOw0TaFUCmjln3XXXbXC\/ZxYOhAKeEbj+85EbSzZ0lvOwVSE5MRMwgXYlwH00FTotarcr\/nbJjHtJOgNUU\/oHpkyZkj1f8aGV70vtUmXOxARMwARMwARaRMCCdovwObIJmECtEeAlJJ1qis7rP\/\/5z345qbWKaoY9jBTdeeeds5dOOvX56t6uNgjQYURHNeLLkUceGXr16tWgrqgvRMy0o4A4N910U5h77rkbhF1qqaXCAQccEEeEkybh7NqPAB8s7LDDDrFOECFmzJjR6pnTDiR+pEJd0W9EkB49esTp6LGFNtFajrIiYE+bNi3w8cR8880XfvKTnzRoj0U2HXbYYa1qR2uVx+k0JvD000+HlVdeuUGd6tkAYbgWry+cH5MnT24wKlvt8L777mtcSB8xgRogIGGAa6nOK9Ym5YM32i8iA9dc1oHnAzU7EzABE2gPAjw37rvvvtlzAM8AfJibvpO0hx3Oo\/UJcN9pSf\/ASSedFNsF7zuvv\/566xvoFE3ABEzABEzABFqdgAXtVkfqBE3ABDqaAJ1lf\/zjH7OXVjrR1HmNnzrZOtpO51+ZAHXFKE2+mM6PkGTdbHdEVGbYUSEQCVnjdckll2xwLp599tnZOcja3BJp2C+\/\/PJxZG5rCpYdVf7Oni9rkqtuzjrrrDYrzmOPPRb23HPPLC\/lWW7fv3\/\/OFKf0bfNvZ5zL7jhhhvCoEGDAqPCy+WX+ule4mtPmzWJNkmYTkpGjaZ1ye8555wzbLjhhuHUU08NDz30UPxIiqnK2ZrbtqotANc55cX1EhsfeOCBOCX\/qquu2shWPup46qmn2tyuau13OBPIE+Cc4XltlllmiVP7MrsK59m4ceOiiD3\/\/POHY489Nk7\/yzXYzgRMwATaiwDXnO22267BvXWnnXaK9373D7RXLbROPuX6B+69996q+weo99VXXz22CY\/Obp26cSomYAImYAIm0B4ELGi3B2XnYQIm0O4EeEFJp55SJ\/YKK6wQmCZ24sSJcWpZOpQRJtjoUFbnckfsyZ8XtLbuRE8rg7zIt6PLzrTCqgfqBKHqlltuCQMGDGjQ8UA90lFqMTutxdr+zYhaOgl0DtKhzYjJDz\/8MPTp0yc7jqj57rvv1nZh6sg6zsMtttgi1g+j7b\/++us2Kz15PfLII00Wtvv16xfGjh3bpGm\/yYtZOxCm1Sar2RMeAZx7i13nJPDRRx+FLbfcsmK9zzTTTIHrFGIco6S5H7XWBwx61vjqq6\/C6aefHhZZZJF4T6vUBhHdfX3snO2u3qzmuZJ1skeNGhUuvvjicNddd8XnWq6dfLDB6GxfR+utVbi8JlAbBLj2FC15g6h50EEHhZtvvtn9AyHEa3Zn6x\/geaqpH\/2NGTMmPhN6dHZtnJ+2wgRMwARMwASqJWBBu1pSDmcCJtDpCCBcXHXVVWU7r7t37x6Y3rh3795h0003jQIOo\/86YmOU4C677BJHirHG59tvvx07\/VpT4OZFns75Dz74IK5bzBrITC3M+pwdUWbyXGONNQLCFFPCLrHEEmHeeectOeVvz549wz333NOuon+na\/g1aDBt+NJLL82EG0ZI7LPPPtm5ydTTrdnOaxBBpzQJIUJC27Bhw9q8DFyzn3322UBea665Zpa3bCi132STTaJQUqkNPfHEE00SsldcccVoC2K7BZg2r\/52yYA2duGFF4ZVVlml6vbFvZmO7scff7zZ08wjZDMC+\/jjj48jwhkZXqo9p8eZupnOd7e\/dmkezsQETMAETKCLE+A5IF2eLL3n6nfaP8CSCXzg2VHvyXyMX6\/9A\/QR\/OpXvwqLL754oE5KLQnER3\/vvPNOk94l\/\/nPfwb6Fahzj87u4ie9i2cCJmACJtDlCFjQ7nJV6gKZgAmkBOhE\/utf\/xo233zzqjqP9SLbEXumE83nu9JKK4W99tor3H777c3uSIcHneF04jO1GiJNPp\/8GsZ5\/7b8nxf1Sun\/+Mc\/DkOHDg2vvfZaWr3+3ckIcC4i0KT1fckll3SyUtSPuVw\/Dz\/88FhfCy64YHjllVfapfAI03Q43nrrrXFq8QMPPDAK0XQqlrpWIRBefvnlhSNpSe\/++++PHWJp29NvOrQYjcvGuq4XXHBBXNud62YlkbxdgDiTVifAh11NFbZnnnnmeB968cUXq24XtJ833ngjdpYyAkhtrtKe54GTTz45MKrcbbDVq98JmoAJmIAJ1DGBpvQPNOUDuEr39ub4L7rooo2eHdL+AcrSXFepf2COOeZolHdzytCcOMwOVSnefPPNFwcC8EzXFMdzldZUZ2ksntPsTMAETMAETMAEOg8BC9qdp65sqQmYQAsI8MI2cuTIsMwyy1R8Oar08tRW\/kWCdprX\/vvvH1599dUmdW4jCjHa+ze\/+U3ZcpcSidL82+o36yaXS5sR5A8\/\/HChUNWCJuGoHUSAWQFU34zEtVjTQRVRZbYIalrPd\/DgwVXGaptgtBWuaZMmTQqnnHJKQOBWW9L+jDPOaHCtIM5NN93USAhnSmnWz\/7LX\/4S03Q7bJs6q+VUqXM6QVmCZLfddgt0jKodldsTjtE8PFeUc7RVwi200EJVpTvXXHPFDtbrrrsuvP\/++w3acbl87GcCJmACJmACJtB0AtX0D1QjrJZ7ZmipX5GgnabZ3P4Blt+p1D\/QkYI2M7el5cz\/5rntmWeeadazEs99Sm\/ChAlNbziOYQImYAImYAIm0KEELGh3KH5nbgIm0N4Epk+fHkaMGBE23njj7EVGLzQdva8kaGMfL7XYX6kjHa5Tp06NI7KrKVetCdqsg8WIbNbRRhSw6zoEWJNtrbXWihu\/7WqfAJ09uo6wBmqtOK4N48ePj21J9rFn3VYJ1HfeeWdmO36IkWeddVb45JNPaqUYtqMGCDDCiesRbf2EE04IO+64Y\/j1r38dGAWVtq30N52ppUYFcY8eMmRIybhMj8kyJ7vuumsciY2Ife+99zarY7YG8NkEEzABEzABE+iUBHhepH\/g7LPPLuwfqHVBm+eStuofqDVBmyVgDjvssBb1D3zxxRfZsjM877mfoVOetjbaBEzABEygzglY0K7zBuDim0C9EqDz+vPPPw933HFHuPLKKwOj+nipYTRVR2zHHntsnFKXdTrp4GadLta1TjvP09+spVWqI50X8ylTpgRe+tI46e\/FFlsspj9w4MDY6b7ffvt1SLlhzXTCRx99dJzm95prrokjJhEDJEjVaxt1uU2gVgjQ2XPkkUfG68lWW21Vc50\/2IeIPcsss2TXPKaFZnR5nz59smPbb799XKO7VrjajtonwLPC22+\/HcaNGxeX\/1hggQWy9sQ9ldFNrI2dOu5fjP5P77n87tevXxg+fHj4+OOPLVynwPzbBEzABEzABGqAgPoHWOpL\/QPHHHNMh70jt2b\/AGXrbP0DlP+iiy6KHxvyoT7P+y3tHzjiiCPi89mAAQNK9qXUQFO0CSZgAiZgAiZgAmUIWNAuA8deJmACJtBRBHhZ46UN0Z1RynyNnP9CvHfv3uG7775rYCIvq08++WSjjnSmPGX9bEYz0tlOuJa+EDbI2P+YgAl0aQJcNzTFN7NE1KK77bbbAmt9Ix6uu+66YZ999smuhZdddpmvebVYaZ3IJu6ZrCPPOuvpxxOM4v7ggw9iSRjlzYdiqZjNaG8vm9GJKtqmmoAJmIAJmEANElD\/AB9sMrML60DnlzVpSv\/A0ksvHfbYY49w\/fXX10X\/wD333BOfz\/jon2Xc7EzABEzABEzABDonAQvanbPebLUJmECdEeAF9uuvv44jyZdccsmss7xbt27Z18WI1H\/9618zPzrUGeXNGlmlRnPXGUYX1wRMoAUEHnnkkTDbbLPFawwf2tSie+yxx8Ivf\/nLBtfBSy65pBZNtU2dmAAfjjG6R8L1IYccEu+z55xzTnaM++8NN9zgDyk6cT3bdBMwARMwAROoVQL0D7z55ptxBHkqbFfqH9h2223DpEmTGn0YX6vlbA27+AhgtdVWi89oN998s5\/NWgOq0zABEzABEzCBDiJgQbuDwDtbEzABE2guAdb5YqpudaQz+ovRkzNmzMiO4XfuuefW3NTAzS2z45mACdQGAY1uWGqppcK0adNqw6icFRdccEF2LWT0Ch1+dibQ2gSYRWWvvfbK2hpLl2i9SZYP4b5sZwImYAImYAImYAJtSYDn3DfeeKNB\/8AOO+xQ2D8wevTouusfgA9LutE\/ctppp\/n5rC0bo9M2ARMwARMwgXYgYEG7HSA7CxMwARNobQJ0pKei9pgxYwJTjEnkZs1PizitTd3pmYAJMBPEAw88EK81G2+8cU2O7uD6uNZaa8WNKaDtTKCtCCBaaz3GueeeO54XjMymDdqZQC0RoK26XdZSjdiWzkyAdyzOKZ6J7EygVghU6h949913665\/gHP15JNPjs9n\/fv3932wVhqr7TABEzABEzCBFhCwoN0CeI5qAiZgAh1JIH1pTdfzvPHGGzvSLOddggAv1HyEcPzxx8ft17\/+dZfpCKMtuqO8RMV3wcN04E6ZMiVO7b3\/\/vt7SYMuWMcuUvUEEDVYh5IPypiS\/4knnqg+skOaQDsQ4MMe2ifPIL5XtwNwZ9HlCYwfPz6eU3feeWeXL6sL2LkIuH\/g\/+qLd++xY8fGc3Xrrbf2+8r\/ofEvEzABEzABE+jUBCxod+rqs\/EmYAL1TmCJdmoAACAASURBVICO9IEDB8YXNTormebUrjYJIAIyck9T0lJfXWFkx7hx40L37t1D3759u0R5mtp6qEM6TOrNUe4JEyaEtddeO9x11131VnyX1wQaEBg5cmTo16+f78ENqPifWiEgQZvnjlGjRtWKWbbDBDolAT5a0owcd999d6csg43u2gS+\/\/579w+EEN\/PeE85++yzLWZ37Sbv0pmACZiACdQZAQvadVbhLq4JmEDXI\/Dll1\/GjpUePXp4Tagar15EwKlTp2YfIHR2QRshF5GeTnK2v\/zlLzVeA61rnspfb+VOKdKGO3s7Tsvj3yZgAibQ1QgwYo91Q3WvZnSpnQmYQNMJPPXUU2G55ZaL59K+++5rkazpCB2jnQhMnjw59g\/88pe\/rOv+Ab+ntFODczYmYAImYAIm0I4ELGi3I2xnZQImYAJtRcDruLUV2dZPl45ldSp3BSHw3nvvDZtvvnkYPHhw3Y1UZtQbI+5hYGcCJmACJmACtUrgm2++CSx1ouePq6++2h8j1Wpl2a6aI8AHjAiEErN\/9rOfhU8\/\/bTm7LRBJpAScP9ASsO\/TcAETMAETMAEugoBC9pdpSZdDhMwARMwgU5BgM4FdSh3BUEb6PX69fvtt98e69KCdqc49WykCZiACdQ1gS+++CJ7\/uA55Pjjjw8ffvhhXTNx4U2gEgHOkSOPPDLMMsss2fnz6KOP1t1HnJU42d8ETMAETMAETMAETMAE2oOABe32oOw8TMAETMAETOC\/BL777rusQ6yUoC2BuNLazPhXG7YlFVDJjpakXS4u+ebzVnnLxavGL5+u4nBceZQKQ1j8jjvuuKoFbaXLvly6ssP7zkmAjxv+8Ic\/RKEIsYg2YmcCJmACtUCAe9uDDz6YPYMgai+zzDJhxIgRcepk\/O1MwAT+l8BHH30Uzj\/\/\/PCLX\/yiwTlz4oknenYDNxITMAETMAETMAETMAET6CACFrQ7CLyzNQETMAETqE8C33\/\/fdYxlu88Ruh8+umnw3777Rc22mijwPp8V111VWCa8tQR7rHHHguHHXZY2HLLLUP\/\/v3DoYceGqe+zqfJ+s4IbGyIa+R\/7bXXhjPOOCM8\/PDDcV014kyYMKFBOPJ89tlnw6677hrjPfPMM43skHintDVSWekh6OF37LHHxrjTpk0L2267bUxv0qRJjdJTGcn7jjvuCBdeeGEYPnx4XJubjsXRo0eHrbfeOmy11VbhtttuU\/CS+\/vuuy+cd9550QaJizfddFM4\/fTTw9ixY8N7772XxYUprMQUrtjOeompAM1vGOKnkfZ33XVXjEt8MVDChKdOhwwZErbbbruwzz77hEsvvbRk2RXP+85JgDbQu3fv0K1bt9g+aCd2JtAaBLiW5K\/vrZGu06gvArSjV199NSy\/\/PLZPYx72SKLLBK22WabcPbZZ4cXXnghPhtwL6bNffbZZ+Hzzz8PjPD2VpkBrGAG6\/Zy5PXVV1+5nprYRqkrXVtp78yi9Pjjj4cDDzwwrj+s5zzteS4lnJ0JmIAJmIAJmIAJmIAJmEDHELCg3THcnasJmIAJmECdEig15TgdakxhSKfZ0KFDwz333BOFbf4\/4IADoogqZK+99loMt9dee4VrrrkmitEaLXzRRRc16ERlzcyFF14467hGUN1xxx2ztTSvvPLK2DnXr1+\/MPvss8dwSy65ZNhiiy3iqJTLLrssCsvYgbidduQhVKdpS8wlDPkqvXXWWSccffTRUeRjtAtrd5IeYdL0KB\/\/Dxo0KPojZiNIL7vssrHznTLefffd0Q+BupIbP358WGWVVWJ48sPexRdfPGBPPn94c+zggw+OTK+77rpwzDHHxGNMLa6OafaKu+6662a\/KQtbOiI3rdMBAwbEOsVu4iMcMFrfrmsRoM4RgKhf6rkrCdp8IMJ5gmjPVlQ2ym7RtXXbNDwfeeSRKLDQpriu6XrUujk5tXohQPthGmU+3KJNFW2zzjprvL+vuOKKoW\/fvmGllVYK6623nrcqGPCxwPrrrx+fJ0aNGhX+\/ve\/t\/oIeK4LfFz37bffRgF2zJgx8TmLDxNcT9W1U57hNtxww\/icuNRSS4X5558\/zDzzzIXnA8\/FEydO9P2tXi6SLqcJmIAJmIAJmIAJmEDNErCgXbNVY8NMwARqmQAdSerYR3BDKKvUiU8HooQAOqQRvvJiXkeXGUGSctFpg1ghgbKj7epK+ZcStBkxRacyI5jTtoSgzPFhw4ZlxxFO1QGtsLQlxNu55547dm6KGf4Ip4qz2GKLxXY3ePDgmIaEYcJJLCbt3XbbLWufpL333nvH8P\/4xz+UdBRV6FCVsJu2lzQ9\/LHt3XffzeIixpMPYrEccQ455JB4\/KyzztLheN4Qlk5i8sNmwlZynHPYzvlG\/D59+gTSfemll+L\/dNLrHFQZ2CttMf35z38epkyZkmWHP\/UoppzXHNOmgKpThABGmMupTjnHlL\/8vO8aBKhb2lyR6NtZS6iPPihXUdk4J\/hYZuDAgW7XrVTJXB+YlWLppZcOp5xySuQO+4ceeqiVcnAy9UyA++mpp54a5ptvvqxt6fzO7\/PTLuf9\/f\/\/fRiw0EILNeK54IILxllaRo4cGZ8fmtvuuCYwQw3PZKuvvnr24aD4zzPPPI3ylp\/3\/1dHsOADx2qY7L\/\/\/nFWA39I1NxWWz\/xeA\/gWYmN942m9g8wE1Wt9Q+k\/Rd8RI19fOBoZwImYAImYAImYAIdRcCCdkeRd74mYAKdmoDErDnmmCN2hiBs8RJbzuEvAUwdKKRTSw7xpWfPnlkHTypQ1pKdndkW6lz1rzZDB+Xmm28ejzMddeqmT5+ehVd7oRMa4fvcc89Ng0YRmrTzIhrpq+3Jb8aMGVEolg0khDBLfEaovPzyyw3SJl5R2mm7zrcXpkVXWZl2O3VKT4I6ftipDkZskeO40klFcflX2qtcM800UxTVsRnbUnFeTOmsSR3CflPLTXzyUJ3SoZU6pjonTUa3f\/nll6mXf3cRAnT4FbWbzlw8OjW5HrHEQVHZNPtAkV9nLndzbIcVMzxw7WquIw0+ZILnn\/\/85wbXxz\/96U\/NTbaqeK1hf1UZOVCHE+BexZIiutfR3oo2C9rFXIpYFQnaaTieDe6\/\/\/4mXR+op1deeSUgrqZp5X9b0K6+nvS8mWeo\/xllz8cDLbmOd\/gJbgPalYD6BxjtTztqbv9ALbU5rj2Uo2hGrnaF68xMwARMwARMwARM4L8ELGi7KZiACZhAMwnwsqkpoqt5YSUb4jBaVqNhJFA204RWj8ZLK\/ZpbcW8QNnqGdZhgqUEbUZW0\/lBhwHtac899wynnXZanE5co4fT9oLgwP+ffPJJHK2HEC6RWKK18FKvmmb7ggsu0OFGe43AZGrFfGdKubSxF9vz7YW2pI5BBOPUFaWHnepgTNPCFqWTF8bTNEv9Vrl69OhRdqpemGLDxx9\/HP72t79lU62TdxHTUuXGDmxWnZI\/5Uk31Smjxbu6g2spB2+2cmFKxW3qcdUv++bk15Q4Re27qfbWavhSYj0fajCSmC1dn75Wy9GWdjHFMNeN\/HW0KXmm1z1d+xG0rr\/++oof0DUln6KwrWF\/Ubo+VrsEaG8333xzFEyZfln3XO0taFcvlFYStMWUGWlY97qS4\/wfMWJEWHTRRRvVi9LS3oJ29fWk502xY48Qyej3sWPHtmgkfaU6tX\/XJcC1lA+OaU\/N7R9oybNDW5DFHt7pVl111Viu9B2tLfJzmiZgAiZgAiZgAiZQjoAF7XJ07GcCJmACFQgg0jXlhZXkeCmUEKZO6grZtKt3ap9fWFsfPXWuzjOEPJzEA44jFmlDFNPGMXVwsJ88eXIYMmRIYBpLBKRddtklxiONIvFVgjYj\/Uo5jWQmbL5tlhLoKIPac7696PzApmrSQzDUVORMey934403RmbLLbdc+OKLL3S46r0E7V69epWMg3105u+xxx7xg5PevXuH3XffvSTT9DxJR5Mrg7RO+UiBNcq32267uD44a6IfdthhMe3mCPTKo5b2tAOmdmeULm2F9vrss88GPqBgWYZp06Y1EJHhxxquhGV9cTr2ia9zgj31Bls22hb\/M82h\/ucYG\/+Tno6ne4nXb775ZsyLOthoo43iuvSMxld+Ysmo\/bQM5Ek4ynHrrbc2WMueOKR\/5513Bn1QMm7cuPDBBx+UbDfKpzPvS10LKBM880w7c1mba\/sZZ5wRr1m0y+Y64nLtRHRpb6atYX9zy+14HUuAaxpt78knn4wf1F100UXhyCOPDDvssEPYZ599vFXB4Le\/\/W1c855niK222ir85je\/yT5w45xON54NXn\/99Qb3x7QFICJpKZY0nn4vsMACUWT63e9+l01DjiDruqrcVuE0dOjQKD5effXV8RmCZ8H2vt6m9e3fXYMAz6aco9UK2pSa667ep1ry7NBWBFP7KJ+dCZiACZiACZiACXQUAQvaHUXe+ZqACXQJAnR8tOSFlfi15vzC2rY1ojZDu1GnWTqteH7K8bw1xEFQmm222QIjjq+99tosnVJCE3UqQbtcJwRCYKn2XC5tdcDk004FbZVV5SmVnkZ1s2410+peeeWVccaADTfcMDz11FOK3qS9BG3spLM+78SUsrPedToCspSdxMmXG7GVvPDTtOKkWalO8\/Z0xv913dAyDLS31VZbLbZVGLDpegcfPqxgFNvOO+8cmWm6W3gTjjCkMeecc8a4xGcd9vfffz+svfba2TGOEy6fP6PjSYv6Jj3WGmXmCTqtb7nlljj7AXFZS5685BDil1lmmSz9Cy+8MNazZtVA7FYbIl21D+yknvlQYcUVV6xbQVscW2sv1q2VXnukg83bbLNNbEO0y+Y6XT+5zujcKUqruYxKxWst+4ts9TETqDcCnE\/cYziHH3zwwXDyySfHj6q4\/2jr3r17\/LAxf07yPIQgrnDsefbbZJNN4odiLMFC2vl49cbY5TWBWiNQ7n2qlK08L+hcb8mzQ6n0W3pcz9nYmH\/fa2najm8CJmACJmACJmACTSFgQbsptBzWBEyg7ghU6iRKO5xTUaQcqPSFsFwndbk0muNHWbSVi085qhE\/y6VRzq8aG8rF7+x+1Lk6LNRmONa3b994\/Pe\/\/31hEdW5gWiq+Nddd12DsBLX2NPZgDgH77TN0clSypXrgEnTTuNThrywK386W2Wryiq\/Uulhw0EHHRTXtx49enQ466yz4sjdlpwrabngkXd33HFHZudzzz3XwDu1E6b8TxpF5UbMhgW82SrVaZ5Jg4w74T+UZ8qUKZElU6ozoi9t2y+++GIsleqDdUTFAKYanc+IfDF+6KGHsrr59ttvY3jinH766fE4I9fkOM75g3DNCHnVNeeB2iHnD46wEh1ZI1OOONSd6v2nP\/1pnH6e6UdJQwI44Y444oh4DLtVDtL55z\/\/ma2fTjqd2TEjAqPradtvvPFGrE+xScsGM84PNsKyTx18WKLj1FNPjdelqVOnxukrdY3Kh6WtXHbZZfH8v+GGG8Jnn33WgLHC074eeOCBwIhiRvhjY1oXhMM2jexPbaMOZTP7u+++O4tLGsyewHHaKxvhP\/roo\/j74YcfjizyebFcAaP01d5os9jIs0I+rMqQ35MP4YlLOlxTELZIh02O37DhGskmTsQv5WBBufj4QnHSNJtqP+nxodHIkSNjmqSdL2faNmAMU+4N7D\/\/\/PNYP6Xs9XET6IoEOOf4uGqttdbKrhWc61xXdP5wzqfTh3fr1i2cc8458dwpd453RV4ukwnUGoFK56Cec7l\/65yuVAbulXp24Hd7OcqirVyelKOt+geUfyWu5eyznwmYgAmYgAmYQP0QsKBdP3XtkpqACVRJgBc2Rmgy0g7B46ijjopTzRa9ZGk0aakXVtKig5fOXnUe01FNeF5a047kSubR+auNeGzqZMc2ddRzjN\/3339\/TBI\/4iE+sCEgsKcjucgVvbCSBukqbdLQy7aEAvzOP\/\/8OF1vnhVhH3\/88cjhlFNOiULFXXfdlQlORXZ01WPUmzosYI2DF9N6cnyzzTZrxOXll1+OfnCEM+FoQ\/n2w+hR\/Pbbb7\/YBuh4IA\/iac1m4pdySlsjXtNwtBnSZp86bCjVwaH0iJe3tSg9OHC8T58+0W7+x3b2bM11nA\/YAIMiJ1vy5zHsdK4ShnRSpvITU86zNA0ENvJNhVvlr49hWBO3KzmVi3IzhTvuhRdeiKIXdUg7YDpW\/OGTOqb25jjnQHpurL\/++vH4qFGjsuCIAYRlFHgadr311gtjxozJwvGDPKk\/trQdMfqaNJiuX2kookRwpoolDtdLxAbEahzXs5lnnjnGR\/DNO7Up9p3Rcd5NmDAhaC3dnXbaKU59veWWWxaOPufcYFQ8HwDAVOcEZSct7qU9e\/aMgjazLlBvhOOcTOsEQZopYFW38OO6tuSSSwaug3LUF9PI01Y23njjcOihh2YfRFx88cUNrjf6cIE0U9tIQ8e0x1acrhk6jh1szOCw6667xo81GJXPtL5qO0XpKT570qzGwSM\/C4HSOfbYY2MSOs\/4f999940fWjCLBdOT33TTTQ2YKs9JkyaFbbfdNpa5f\/\/+sR51z+BZhrIrn6J93n7OKz4gYSkIOMCH5RUOPvjgRvwR437yk5\/E9Ln3kz7XSo7z4VLaBmSv9ybQ1QlwDnG9Ss+3Tz75JH7QwodZOs49io9A7EzABDqOAPd4nosOP\/zwuIQQ9zw+ziu6f+kZIn0nSC0nLfUPnHnmmfGDNN3XOe\/1LJLGKfWbdw+eudhzTWHjf+xikx977Gpu\/wA25d\/3lL7S5tlZz0Rp\/8Dw4cPjs1y+DNjK8\/Qll1wS1D\/AMj5FTPNx\/b8JmIAJmIAJmED9ErCgXb9175KbgAkUEHj77bfDjjvuGDvPETt4QeOFlZdLxBdevFJXTtAmrDrmeQFEIGeNO8QtvRDy8lqtk8CiDi72elEu6ohG8MHppZqOb6baRXRedtllw8orrxxee+21RtnzIir7eDnGFaWvl21GXKU2wSt9ESWchD38+FhAYgajTfTi28iQLniAsmo9aJhJRBBj1njmOOIA3OD4\/PPPxzbDGr78n05PTlpyjH5E9CH+pptuGhi9TfsgHToLJGjTwUDbzHPnf0btEZ+w33zzTWYDayFL+GBPfGwhbcpAPsRLzxHSY4Qlx9nS9BCtlN4JJ5yQpUccnW\/YQLraGAXL+Zg\/B1X+oj02kqY6jEkTm9lShyApO8WUuJQHgQg\/7GLjPMaPDSENP61Ljj\/nKX448tFU2ghJ77zzTvRDFCUsIlzeltSuzvg77ZBj2vW8o\/4QPuHGtYlrTLpxfJFFFmlQz1yzOL7mmmvG+oQv19KBAwfG44zixsH1xz\/+cVyPNJ8vccgb+1gb9oorrsiuc7Qx1ZniUT\/kuf322+tQgz3nI\/4\/+9nPGp1LBFR89p3NwULMmeYdgUWOjxRYDoCyp2XjPHvmmWeyWQk4V3GkxbWI8Dq3dHyDDTaI57fYcy6QH2FZbgBHuojoHONcIgzHuKZxjPVnv\/rqqxiWP6yBznlJ2rq\/kj51r2ugbCM8x9N7mM5H4iAg6b5LWRH3H3vssZgX678zvf7ss8\/eIH\/i67kA+3SN57jKmRlb5ke5dIimD6AQkOGBQ+Bn6uIFF1wws1NZTJ48OfKaZZZZIjuOE2+JJZaIx0kPVy7f1H64UT7EbOpdjg90+MgAP\/EnHz5q0bWUpTIeeeSR+CEJ4ahXlUHpeG8C9UKA80ofaHE+8AHOoEGD4jnE\/1w3fX7US2twOWuVQL5\/gOdWPnhnCYDbb7+9wTMrZdC7N8+X+fOX+2faP8C7AB96ph+yEaZap+cUrhfa9FzLPV3HtOd6w3VHNtI\/cOutt8aleMr1D2BTvn9AzwJKm73Ky7PVTDPNFP7nf\/4n2pA+M1I2bEv7B\/hY4Be\/+EUMW2\/9A9XWtcOZgAmYgAmYgAn8LwEL2m4JJmACJvBfAryUITYz6i7t8ObFTCMHzz333OxFjWgSb\/IvrLykzT\/\/\/PGljFF96ggmLV7oJOg05YWVuISno54XRqbaVbrYwrSfHEcMRajGj02d+Oz1kskUrXRsM\/IxFQNIhzD5F1YdT1+M+Y0jDzqx+RCA\/Cmf7GIvkTQ9Th4SKZgauB5cyg5O2tK28+mnn8b6w4\/j1AOChURk8aYDYIsttohiytZbb50JBYjGq666aky7d+\/e8et\/0lFe6V4j\/UizlG0IQ1dddVVhfEbZFaXNMZ0XaX4qU9pxm\/rLHqa8RaxM\/dLfpM8U4dU4zuM0bvpb7Zd0aI8w5UMAwtChDHd+p0xhO2PGjCxrzkfCsuYy5xdTjKfpEpD\/GcVIWqytjP2kTXmbcv5nmdb4D4l5Sy+9dHa9SU2WEAkPxDRGQDM1+Z577hkOPPDAcOSRR0YRUdcq4iJUE56NKZ8RWLm+8nEMx9RJxggPro9pXOLzP9dHpginsw5hjesVHycQnzrRNUu2kiZ+dDrmHWEZpYs\/Hwbl4xJe8WVbPo1a\/p+PZjQyWx8LpPaWKhscWBMdLuk99LTTTovHSCtlhWjNNY5jbCw1QFzEnDQc8agzOm1xTD+uj3dYkzbvZB\/Tm6stkB71nLeNuLQpjrPlz9\/0GkKHr1yaHlOMp440SqWXhqv0u1w6TJMPE+4NKavtttsu5s1xORio7DzDyBFPrNJp98vlS1z8NdL7r3\/9q5LL9ghwlJ9rI2Hl9FxBnuT96quvxvyvvfZaBfHeBOqWgN4zdO1gz30xPb\/rFo4LbgIdSIBn9ab2D0gs5t6r5xCKwD0x7R9QsTiu+zHnfnrvVJhSe9Iv1z\/Aewxp0j\/w+uuvx2sK15Wm9g9gk+7j+uAdm8if\/3XtUnnJg2Wc0v4BlQG\/tH9Ax4mrj9\/qpX9AZffeBEzABEzABEygegIWtKtn5ZAmYAJdnIA6YREK8x1IvMTxUorYnb5g8QLJC1z6wkpcpnzmOFOB5h0va3rpa46gxRfMxEdc00sjeTB1GS\/Jb731VoMseUHGvnwHt15KU+GBiKRJePJIX1jxS4XK\/Mu2XsTVWU14hCdGW5IWoyJThz0cJ3xajjRMV\/tNfee3PEdYMLIVAY7RhoQv4sNx6oNOE8IpDHvqFH8c6WvjGL+L0iQt+eGvsKSn+IiV8tNx\/a\/w7HGl0uP8UFjC8Js96b3\/\/vtx9P6AAQNip4vswZ9OGAljCO2Er+TyeakcsjEfn+MI6vBjdKbyYJ8yTeMRh\/V+X3rppcgp9dNv4qtOmTZZ5ZV\/V9pTNs7r9JqYlo\/pGfFng1k1jnpkpDRx6ABj6nFETz4AYTQHMz6Q7yabbBKnLMynqY5FPiRiaketx6zjXAtV14qbXs90THvskaBNOfk\/78rFz4ettf81swKjfTln8q5U2WAov\/S+wm\/VOf5siMOcO0qfuJqhgpE5eYe\/OLNWNOnNO++8Wfw0vDpWV1hhhcyfuLqvpbYRDxtkn+xRerKd+1jqR3oaiXziiScqeNyXS69BwAr\/VEoHf7jAkfaPQMyHMpQFxnJcy1S+J554QoezPWmkrlK+fNSj9JhtI++wR\/6apYE8xP+8887LR\/H\/JmACITT4gDD9CNVwTMAEOo6A+geYFUjPIbKG+yWzotA\/oBlc8NNzSPosTNxy\/QOV7r3Ks9Re\/QPpUjyEpd+C\/gEtmaP4PCdgH8uUyHGvbk7\/gJ6VuPfnnynIh+Ppc0naP8A7bOr22GOPRuFTf\/82ARMwARMwARMwAQvabgMmYAIm8N8ObaY05oWLL5jzLu0MZ6pZOXXcpi+svMixziZpsW523uGPHxvxm+qIz+hb4mtacdKgI5sX5fzLNn7EYWM0Np3eTE\/N1+akgaiTOsKp4zkvaKu8xOPFO3XpCytp4JhWlLBsvOwy3TVpsmkdTb7czqeVpuvf9UNAnTH5zo2UAB1KCJPNOXfSdPy7bQjoGsE1pKiOUjGMEdZ5x\/VL14\/UTx2KjMBmrWCmeScso7q5vmiGCmbESB1pabQ9Qm3q1AGHrVyDuIYqb03hmHbApXG1\/naRGE649HqYxqv13zBVZyLTSRfdT0qVjbDyg60c7UD3V90P2HPt17IX8NeopYkTJypq4V7sVW\/5QKpX8tAa9dSr7mupbcTVRxiEz9+L9NHD6quvnrUN4lBWlSl\/n0\/T4yOg5jqdS9iVP5coD20e3rRBPj5g+nvsJDzH5dKPSJgqvZKrZL\/OtSJepJ3Gl4COveokZwp6OxMwgcYEOHf4eGauueZqMJV\/45A+YgIm0B4EeCYoda8nf\/z1bMGziZyeQ\/DTcyVh1T9w9tlnK2i2x5\/7aql7axawxA\/iq39Az8I8qwwePDj2DxRFwzY2+gd4Hmtu\/wAjsWW7yqv89FyYPpeof2DWWWeNs1dttdVWcW3ykSNHZsvAuH9ABL03ARMwARMwARPIE7CgnSfi\/03ABOqSAC+BTJHLy1g6klkw8NcLKyPz1MmvDuf8C6umFGcKwbzjRU8vfflO6nzYUv+fdNJJMQ2mSCY97GOkYtH0q\/gjBknAZtQa9qo8+c59wqvjuSmCdioAiQ8vppSVkSbKs2hPnnYmwKhN2gvttcjRTpjGllkUaPN2tUdA10TO+aI6Uh1Sz4y417VCJVEnYD4u\/+u6yRrO8kfY5viIESPi9OX5a0kaLy8u6gMKrkmaklHX5HQGCdmW7un0I19GFTNSPHWUqVL8NHwt\/cb2dPR5nie2FnVOcpyw8iu6r1x55ZXxgzF1uMKPpSdgTj3Rsckx6qWc00wNTB+fbz\/E475FOmyaBYBwpe55arOEV7tS\/hK0uX+meaVlZar71KVtTukRXr\/TsOV+F6Wj8Iy40nMGzDWdu\/izl8NPPJgFo5Iryje1f9KkSVl6RWVK47PEAA52pZ4rKtljfxOoJwLpuVZP5XZZTaAWCXA\/U\/9A\/p0Ye\/HXs0XaP6BnWfw4p3E8a+i+XdQ\/kN47+d0cauVMWgAAIABJREFUp\/4BngHI9+uvv47LU5XqH2B0tmabaUn\/wOeff549F6i8sj\/tH9CxavoH4JlPS\/G9NwETMAETMAETqG8CFrTru\/5dehMwgf8SSF9Y045gAUo7w9MXVnWEpy+spKUX1ltuuUVJZHteztS5TPzmuHSEFB3bdDD\/9re\/bfTih93Dhw+P+THaji+2yRMb9AJeJDyU6ngu97KddqSr4x8Bg7Iutthi8aWf40Vbcxg4TtcjQPtiJARrUl988cVxGn1GDTBNN6N5aWOMtkXwVhvrehQ6b4m4rkyePDm7vrG+LtebfF3pusm14eijj86EPsQvrkuM0M3H4f\/ddtstpn3ooYdm\/kwfvsACC8T1z88\/\/\/xG8GhTa665ZoxH21LnGDawpjk2IL7ffffdMRzHGcWq69kJJ5yQXTPTxLFHwu+QIUOyMnD88ssvzxjwAQZT0ufLk6ZVa7+ZhQQu3AfEK7VRbNinjjLKL72vcEydt4QhTc5nrdPNNJjUk+oDwbrIyZarrroq2jfLLLMU2sfa3NjPOoykiyPfUvc8whCeTeGVf1GntNLTqK1q1tBmNhU6dZvSDkrZla5DzxT6qRN\/9syIgiDPtOAqn0ZtpXH4Lbb8LsqX80P2s\/yD0svzIj55yP\/tt9\/OstJzRdo2Mk\/\/MAETMAETMIEaI8A9ToI2zx55lz5bpP0DRc8OPF+W6x8ouvfm86v0v\/oHll9++Xgvv+KKK8Lvfve7Bvd40uCen\/YPMGIa+zhe6lkJP93H8+I+cXXfT58nyCt9LpH97h8QCe9NwARMwARMwASaQ8CCdnOoOY4JmECXI8BLpDqnefHKO15Y1fmeTimmFzhe\/vQCR1qaUuzcc8\/NJxXD6aWP+M1x5MXobNI54ogjwsEHHxzXlc2nlYpL6dfZ6Qs4L928mKqTGfv1Mpt\/YS33sp2+sKrT\/vnnn89ecJmOLO8IJ255P\/9fnwRoY4jZdAyxTny3bt1iZxLC4CmnnBKYPlftqz4J1Wap02uDrm\/a69qSWs7Uqly3CMP1hk4yRtxyHSGtIiehLF2nkLZwwAEHxA8dpk+fXhQtTs288847x6lc6eTjN52KLHug6z4fStx5551RtJPd6b5I3MVOOjiXXHLJwKjxY445JpZn7733DjvttFN27SMdpjPvLI77ButBUi\/UU96VGn1OXeg+kNY5x4iTP2\/5AAE2dMDit++++2btIR\/2zTffjH7cL2QfcTWldWoj1wn89t9\/\/+z+Qnq6r+U\/fOA+R3i2fNuTH3HTexXpaVQT5UtdOuW2+I0fPz5e0\/LlSuPlf6fnVGqXbMLet956q0E08T\/kkEOimI3dPGf07ds3lu\/www9vEJ5\/+OCC80L36CL7YQo37Cc9TW3OxwN5p05ywqR2qyM8bRv5uP7fBEzABEzABGqFAPcwPScOGzaskVncE9U\/kC5Jxn2Oe3T67EBa5foH8C\/1LNIo4xIH0v4BPg6lr6DoPt2U\/gH1BWCfnqN0TGaoP6ToOUrPJemzUto\/wO8ilz5zFfn7mAmYgAmYgAmYQP0SsKBdv3XvkpuACeQI3HbbbfFFcrvttmvU8c5L3Oyzzx790xFOeoFLX1h5uWUta17q6KDPO8XBn9\/NdaNHj455MJoVMeW9995rlJQEA6YjTzvSeUlU5zKjXRl5xYYr98Ja7mVba9nywqq8CI8QSVnz07KSl174Fb5RAXygbgnQRmk\/2vjf7aS2mwNCmOpLe65xpeoNv3feeScw4pQ9\/5frwMKPawZpp44Ro5VEMtJmynHyoiPuiy++iEmQFoIq\/jjy4DfHCZ+WI81Tvynbl19+GZ599tk4MpXrMHGwh40Rsu+++27ZcimtWtljPx9Kcd2mgzatE+5\/c8wxR\/Tbc889IysYsBGOkUDEY0Sv4nFPYH1spr5OHR808CGB6oL2o3W0+ahF8Umbjxa4R3GMjY\/FyIePBxSOtOHP\/ZB08lPMI\/ISJ+1Upa4HDBgQj+PHFOWUX+WReMw9nuPkpfKqY5f0FAcb+M3HOKT3wAMPxCLzgY7usSmDUr\/JJxWWlT55s84labONHTs2SyKdhpz1KGl72Egc2ifhe\/bsGds\/x3DsWcIhZVJk\/29+85sGS0FovUyEcmZJkJsxY0ZYdNFFY17kiaMsbMyEgA2cF+QrGxTXexMwARMwAROoNQLN6R9Inx24\/+G455XrH8jf85vLQf0DrEHdvXv3ULTUSHP7B3Qfr1bQpuys4c29P\/+c4f6B5taw45mACZiACZiACVjQdhswARMwgf8SoGN79913jy9djKZSZysvY0wpy8sYndJ6MWXP6DCOL7LIIrHzmY5gHB3p6phPBXDi6GWWeDfffHPs\/G5OJdCJzJSqpFMkwpMm07riz2g7vsaWQ6RgRBZ+p556ahw9x4sm9r366qsNOp4l9BAXf16QiZeKBXSkM0qR43Tk81JOWBgyMpzjCy64YIPOd0bcEYe4diZgAiZgArVDgOs+9wSu3bvssksURxnx3KdPn7DBBhvE4\/jxQRVCLWH5zTFta6+9dry\/4cf9hqnhf\/\/73wem32aqeT6qyneKcu\/YZ599YhqI40wvrw5UpiaX4\/5CJzMfmrEON+GIh22MnE7vW4rD\/Xm11VaL903uw9znEco1xTp29+jRI9qFIC\/BWuVBqFVZdb+TH2tPph9ViB1rbw8dOjSsscYaVd\/rKRts9AxBHjDAHvLAn\/ThiR+j37mPYztsZRP7dKr3f\/zjH9EOpmrnPk4aTPNOunleqf3UGfnr+Qae2MBsGXyQsOGGG8YOazqt+U1ZyYswONJi2ZHULtKjjHrOUh15bwImYAImYAK1RID746BBgwL3Tj5S032Le1yp\/oFU0Oa5RvfPtH8gnW2ItHjG0n3y0UcfzeI0lYX6B2adddb4jCN703QmTJgQ82pJ\/4DKRLowUv8A5ZXjHV\/HBw4cmH0ESXnL9Q\/wrMbHpnYmYAImYAImYAImUETAgnYRFR8zAROoWwK8nJ1++unxJW\/77bePHbG8VNF5zdSy6vQlnF46033aQcsLHR3Z+HOcl95+\/fqFgw46qFHc9KWwWvi8oGrEWdF0YqRDunQm84X2yiuvHPPeZJNN4oisKVOmNLBj2rRpcVrctDz6Lft4AX366afjKC866hERmGZ3o402itP3Kjx7TbFLHIR\/Oro5Dtc99tgjzDvvvGHEiBHNfmGvlpPDmYAJmIAJNJ0A126mZb\/ooosC61ozfSWdsdxTtCGY0nHLhtiqjf8ZIUwaiMB0TBKX9LhnjBo1Kt5Lijpaud8wcwjrQ5911lnhhhtuKLxPEJf7GGsxMiU2o7bppNX9qqjEn376aWBt9zPOOCNu2MN9XUI1I8OxW\/bny0X5OKYtDcua1XKU+\/bbb4\/3OOxj5HK1jrhKV\/mw55jyIAzPGNiDoH3ZZZdFnuTBPZr6gTnhUvf1119HkRu23H+xsYhXtfaTB2uIM804afKRADMWpPWaL4P+x\/Y0XGqnf5tAEQHaKiIQ5yuzEzBbgV3LCXAN5GNWXWfy141qc+B8\/vjjj8N1110XP969\/PLLm3TtqzYfh2tIgPOCmWC4P3CfaG79NUzV\/6UEYEz\/ALOcIG7zLs\/04dX2D2i2FNLkfFP\/QP\/+\/eOU5vQT8GFa+h7N76L7c2pX0W\/OQ\/UPlLpGkm6+f4BlQpixJe0foO\/ggw8+aPSBn+yUfeRZ1D\/AOz\/9AQrPvpr+gfzsQEXl9DETMAETMAETMIH6JWBBu37r3iU3ARMoQYCXMkYP06FORzGjwD766KMGHa+EodNAnffpHj85XvQYGU1HLy9nrNFKJzQvkUwJpjTSOIpbzZ5RUCNHjiz7wosNTOl60003ZfkqP8o5adKkOB0Zx9JypL8VHpv4zcs4X1afcMIJ8Wt18qAjDNGDUefE5f\/UIWbwZTsssOWrr75yp0sKyL9NwARMoA4IpPeTjipuLdjQGmXvKuVoDRa1nAbPfUzRz7OP66x5NcXHE8wQwcwNCNoII8yq1Jl40g5Yj5f3i1oRHbEjFZv4LZGqKTVFPSDIzTnnnIHlJDTDBVMb27UdAeoPMTStw+bUX9tZ2HVSpo2zxA0fbvFRHO+6pfoHeAdO36P5nV6rqKN8\/4A+GOQjsdboH8DGcm0Bv7R\/gA8UZSP9A4888kjgI0CO6b0+LRM2Kjy1zO+i\/gH6Cv74xz8W9g8Qh+si\/QPYyz2SD+\/SdLtOC3JJTMAETMAETMAEWouABe3WIul0TMAETMAETMAETMAETMAETMAE6oqARrYWdcIjOGmtUESnV155pebYMLIzXfe+1gz8\/PPP4yxDP\/\/5z+NIVD7khCXL7tSKMAwzjZAtagccS9sBH6TWgsMuhDSEKomi5USwUjb\/7W9\/i\/FZmglRiz3psW+ugyezaNRSHTe3LG0Vj\/pDEERcbEn9tZV9TtcETMAETMAETMAETMAEWpuABe3WJur0TMAETMAETMAETMAETMAETMAE6oIAUyuzhnspIZMp4SU2IfbVmrviiiviiNpaFQ41IpvZjXAInYz4GzNmTE2hFMfO2A4QsdVGmypoU16mKia+Zmdi2nHqi6nMm+vEs1bbZXPL1RbxWlJ\/bWGP0zQBEzABEzABEzABEzCBtiJgQbutyDpdEzABEzABEzABEzABEzABEzCBLk1g5513jlOKFwmZFJzjTOHaVKGwvaAxdTdTRNeqcIgwilgqQbu9uDQ1H3Es1Q7gW6vtgA8tmitoUy5NMc46uq3lxLNW22VrlbM10mlJ\/bVG\/k7DBEzABEzABEzABEzABNqLgAXt9iLtfEzABEzABEzABEzABEzABEzABLoMAab7XXbZZaPYWkrIrOXCIoT98pe\/tKDdwkpKOXbGdtCSEb6UXes4M315a7iUpwXtykRbUn+VU3cIEzABEzABEzABEzABE6gdAha0a6cubIkJmIAJmIAJmIAJmIAJmIAJmEAbEkD8eeONN+K6wc8991z45JNPGo1ORpREVGMKZbaXX345W2sYP\/lr9DDTYhOetNnk9D9+jF5NxU6FRxR\/4oknoh\/iHesrk+cHH3ygZOKetJhuG\/80jzQQx996663MbtL5+9\/\/3iBfhSfspZdeGkfmMsIWOzhWlLbKO23atPDggw9GHl9++aWSavKePKgD1u5m\/V9+54VL8iScphxnX8q+SgYQjzq88847Y57kl9YF8cmfcNTL22+\/He6\/\/\/74P78nTZoU3n\/\/\/UY2Eo\/wagdwVL2Slpzsxu+pp56Kaef94K+6whbWWy\/VDmgvldrB9OnTq2oHKkNzRmhTLuzWCG0EbZU15UkYyiKnMB9\/\/HE8D2nXcvhVapdKm3Spn3x8OHMe0LZUz2pPpK84pPPMM8\/Ec43fqSM81wbq\/oEHHgivvfZarNs0TKXfpKn2wG9tiqf\/2WOXHP+TN+WCmzaOFznyyNcf9itvOLFOuliIP8cnT57coG6UPnmxfj18KP\/rr7\/e5PIrLe9NwARMwARMwARMwARMoLUIWNBuLZJOxwRMwARMwARMwARMwARMwARMoGYJIODsvffeYaWVVgoDBgwISy+9dBSCLrrookzsQci55pprQs+ePQPTHu+3337h5z\/\/eSb84n\/11VeHZZZZJhORJCaxZ7QqYdg0clX+Eq1SAUpxHn\/88bDyyitHcXCxxRaLaQ8dOjTadcwxx0SbEQ7nmmuusPjii0fxMwVNfqw73L1797D99tuH448\/PvTp0yfMNttsUXDFX278+PFh+eWXL7Qfe2Qn4YmHGEzeW2+9dUyXMMstt1wUZ5VmtXvKfvDBB8f4rL2MGLzwwgvHY2m+iJHilt+n4Srli7C5+eabhw022CAMHjw41uf8888f1z3\/9NNPs+gSpZXXXXfdFfr37x9mnXXWsNpqq4Vu3brF8iOGShgs1w5IR3bm05a4W6odwJqNdko6tAPcqFGjAm2jUjsYPXp0jLfllltGvmk7kE1ZwUOIorTKXeSfhk1\/H3vssYV1RLvP1x8McLDLnxfiwfm56qqrFqZZjidiLQ7bVQ7tVR4+ntAx9ti+zTbbxHOO\/znXdY5QL3z8wDnOkgL4EYZ2xLTx1TjKST0Rj\/N1qaWWir\/JEz\/KjF+6YSs2IDLPPffcYdNNNw2HHnpo2GSTTWK4QYMGZW0qtSFtRyovLNO0sUXl00ci8uf\/1BEuLf\/JJ58c02pK+dP0\/NsETMAETMAETMAETMAEWouABe3WIul0TMAETMAETMAETMAETMAETMAEapIAAg9C5iqrrBJHW2Mk4o\/ExnHjxkW7GfmK0HPjjTdm5UDE6tu3bxSoEHsYOYmIJmGINPgfkUojIRGt+M0m4UhiE34IfoqPSInIp1G3hJOo\/bvf\/S7ssssucXQk8RC7SA+RTOlhKOVDGMbv\/PPPj7bjP2TIkHjsggsuyIRY2S+RD7Erb78K\/+yzz8b4e+21VyaIMUp7nnnmiSxTGxSn1F7CG2J4ut7y1KlTM4Fd6clGMWKf8i2VR3qcUa58JNCvX7842hQ\/GDJKGkG\/V69eQSPNSfuSSy6JZYXhzDPPHM4888wYjzrngwM+DsCPkdQ42Yj4zfFSHGW3PiLgf9lCO5AwTJ3\/6le\/iunDChZrr712TBsxk3bw4YcfxnrABvJE+BQz0qQd0DbwUzvA\/oMOOigeu\/DCC7N2EI3ICdrEr9apXBJuaU86Bht+8+EItqSCNsfPOOOM+PEFfvyPw07aYaV2qbQ5n4lPHJzOuVNOOSUex09siMOHHLIV5pwbOv8JS\/6kcc4558T4fHjBMRw20uZ79+6dHYseJf7IFupX9X7xxRfHNoMfMwDccMMNMR9E7uuvvz7mjb20WezhOA4bRowYEY\/xoYpsUtY6r4ij+iNM2rYot+LBgnbABxvEUd2QXqnyN\/ecl43em4AJmIAJmIAJmIAJmEBrELCg3RoUnYYJmIAJmIAJmIAJmIAJmIAJmEBNEkDIYaQ14s3pp5\/ewMaJEyfG4zvssEMUfBitTbhHH320QbgxY8ZkgrY8JIaxRwgqcghUpMcmcU3hUrGbUdCpS0XONF6aHtNSy1HGddddN+aDYCuHwKX8JWjJD5EOv1Tskh978lp99dVjmEceeST1CltttVU8Dq9qHGntueeeMQ6CWt4h6GGLRrDKP2WsY9XsKesRRxxRMr8JEyZEv2HDhmV1lzKUyJrmtc8++8Q4Sy65ZPjiiy8yL9UjHMu1A4mp+bQVn\/JLnFXiaTtAuJSDp0Y6P\/nkkzoc27DaAUzlyrWD1I90m+JgVqpcpFOq\/siHke+UOc+jUrskXTgr3zwzpusnXbZ8eWQPovFHH30UXn311fihAKPacXy4wMcM8847b6MpttXmx44dG8NW++ess86KtuSvE0xjzscd6XnJ79122y2Gl03kQ93PN9988ThT5qcuFbTz5VXbglWaD\/EPO+ywzC6lV035EebtTMAETMAETMAETMAETKAjCFjQ7gjqztMETMAETMAETMAETMAETMAETKBdCCDyaMrf2267LYpcHGNjbWSEL6YfR9iTAMRoZwQo\/n\/33Xdj2LzwJnEsL1SlhapGbCL\/VKwkvkYmM7I2dYhSEuvy9lAepUM4fn\/zzTdZePkpvUrCIcI4eTFqOF0fmXz+9Kc\/RT9E3rxQpvTTPesly+68eE84bJM\/dSKXMtaxavaMqld6jHzPO5V9xRVXzERPylVKJCX+tddem6XJ6Fo5tRnilhK0KZ8E6Hy9yRbspQ2mTu2A6dlTzvwulR7lYMMWtYNvv\/02sz3fDlL2xGuKI30xy5eLdErVX7l44lEkwsq2coI2ZVDd58vDCGf8mPlAdYUt+q1R+szIQF0QX5vafLnzXfale9Y8J0+uQZrmnvyYSv6Pf\/xjGjT+Vn6EYcMOzj\/VN+0tdeXqrxzLorpJy9\/Scz610b9NwARMwARMwARMwARMoDUIWNBuDYpOwwRMwARMwARMwARMwARMwARMoCYJMKJRAle5PcIQYpLWzE3DMnI4LwSmghCiWJHjuNIh7dRJCEWoyvtJyGSfOtJjHW3SzAuI+DEVNSI4axGz9vdMM81UVf75spEnUzTL9lJ7bJcYmNqZ\/\/3MM89kaRXlxTHlkY4wTxnn0yz3\/5\/\/\/OcsvaL8xJ48WRcbB79SoqH8Z5lllpguUzbLKS3ikkaR43gp4Tcte1PagWwtageIqKXaQZ5HufyLypIeK1cuwpWqP8pZyv6UZ95W5U2bE0+m1k4dArDaUj6+7GEK\/bwjTc3koPhFe87Jatq80ofRmmuuGW1i6n8c5SftF198UcGyPWkzJT+2MkMC5zFTna+33noxTr6+y9VfKmjn25ZYsMdVW37qrSnlzwrmHyZgAiZgAiZgAiZgAibQQgIWtFsI0NFNwARMwARMwARMwARMwARMwARqlwBTMkuYYrQ1AlPRphIgECHyrLHGGmH22WfP4rL+dioKSRBCBJPAo3TTtJR3Ghf\/VLgjXupKCdrYpnWViS9HfAnQTGPMaNL33nsvlBuZm4pdyj+1\/7TTTotlX2GFFeIoUfnl97Kh3P6hhx7KOOY5EI9j4jRp0qQsKTGW6JZ5VPihdZBJU2VLozDtufLTmtiEk0iaslU8\/BEWicc00nKqR+KWawelBNxUgM3b2px2gGiKjazdrHbAaFuVl\/xSV04QTcMV\/U6Z5YVWwpeqP+KV4lGpXZIunEvVVbnyyB5GaucdaTJyG04617EzvxW133xa+f91LjEdPOmNGzcubLLJJo3aJn46j\/lwhXXQ33nnnThCu1R503Mnb1sRS9kmFjq3qi0\/NtqZgAmYgAmYgAmYgAmYQEcQsKDdEdSdpwmYgAmYgAmYgAmYgAmYgAmYQLsQQMDr0aNHFKrSdWmLMr\/mmmui0Iy4g3DzySefhAcffDBsuOGGMX4q2kkQ2nzzzaPARhxEulQMJQ0JiXmxSUIoAjUiXOpKCZmkVyQEairlueeeO6QjnPPiHjZgJ65I7CJfCVxXXXVVZjtrDbfEvf7661laeQ6kq2mZYZXmJcayqVobWAO9FHfSUNngJfawLSUaEge7F1xwwZjuAw88kJmiepSgDV84piOH07TTNkQiTIkuW2WLEm9qO7jxxhtjWuXaAXlQFmzC5duI8q5mX65cxC9Vf+Svtb7zPCq1S9KFcam6Im3x5HfqdJ4UtSfKog8hZptttuw8SeM39\/fzzz+f2cQHG2uttVZIR\/krXa41fERD\/dGG5SiHygsf\/lfZsLtUeYtYKs183cA0Lb\/ah8J7bwImYAImYAImYAImYAIdTcCCdkfXgPM3ARMwARMwARMwARMwARMwARNoMwIIdppKmOnE8w5hCEEIAQeRp1+\/fplYpLBjxoyJYc4880wdysQ6BGbEIIls999\/fxamnNikUcLElziliE0RMokrcbB\/\/\/5KIu7T0b+sp50K7qnYpfwpP3njJk+eHGaeeeZY7lGjRjVIl39eeeWVmG8jj4ID2MH0yXAm37xD3MNv8cUXj+t+yz8vuul4pX2l\/IYPHx7z23TTTTNhV\/WHHelHCcrrpptuinEQtbUWMn5FgjbiI\/UrRztIBUkdZ692QL6qB\/k3tR2wpjnp5NtBKlrn20G5Nio7Su3LlYs4pepvxowZYf7554+25ttDpXZJuuXq6pZbbonpFvEsJ2iT7mOPPZa1eY3cT8vOBzGUqakOe7fccstoF1PBp+tpp2nJvnz90S7UfmhvtAudp+XqL2VJODns2XbbbaM9aXnSc75U+XfaaScl470JmIAJmIAJmIAJmIAJtCsBC9rtituZmYAJmIAJmIAJmIAJmIAJmIAJtDeBadOmZQJafmTkeeedF0488cRM0EYIY9rf1J177rlR\/Lnzzjuzw9dee208htCEWIRIRNzp06fHMPyfComIrByTkxAqQTv1k5B57LHHNohDPlpDm\/jE4ZiEzI022kjJx\/2wYcOiTdjFiE9slYCotcUXWWSRTEjF\/8orr4xxsV3lRmgmPzny3HXXXQMibzWO8M8++2y0BSGN\/+U+++yz0Ldv3+g3duxYHY5lywuiKaMsYMEP0tfUzeXyy5eJuoDVHnvs0cBGBEVG4uN3yCGHNPCTIL3wwgvH49hY1A4kSDJyOy2H2gFxmBo89SvXDmRrqXaQplOuHZRrowVos0OkT1yVi3bFsTRffQiSiqYkcNJJJ2UfYdx9990N4qTtkvRxabvkf+qXeoDZxIkTYxgd32677eJx\/JhyP7VHPGVP6kd88jviiCNifM4lliiQw4+PMphNoDnu8ssvj+myJjb55\/MmTYVZddVVs3OS43fccUdWJuqbMl566aXRDOyirGz5awy2du\/ePfJLP5bgoxvNNpDaQlo65yk\/053L4UebY0YBOxMwARMwARMwARMwARPoCAIWtDuCuvM0ARMwARMwARMwARMwARMwARNoNwIIYEwT3adPnyj8IOIgRLJmLmtlIwThOI4w9NOf\/jScccYZMQyjJhF9mXY8FaEQiBCeCH\/RRReFXXbZJWywwQZRbCM\/xB+JfYThN8fIi\/1iiy0W4+LH\/4MHDw6XXXZZDMeUwxxHSCYeIycPPPDABumtvPLKMR52UDbCzznnnLEMiKYIc6wFjPCM34477hgQXb\/88stYVmzca6+9oh\/lZl1owqXCFyLWbbfdFqdB7tatW5ySmHWZV1tttTB06NAGwm6lyiS\/qVOnRhtYP3jkyJFx4zcjVlkvmDA4RDvKzTrQ2MSeUehwUphK+WE7AiGCXpofo7LhwPTcaVqUW\/W19NJLh2OOOSbw0cLVV18dttlmm2gHI7vTONjA\/2oHjGQ\/+uijw6GHHhqP015U75SDTf+rHay00krxuPxoB9Q34dQO2FN22kepdkB6Tz\/9dGSVtoPDDz881hc2kceAAQPinjXWyQP2edvyZcyzLioX9cNGW5KjDrCX+hsxYkSchp3ziTJSHvIlDtPu6xwk70rtkvTtN5JdAAAgAElEQVQJTzskPtz5gGH\/\/fcPfKCSloe0Ec0pq0aFl2tPpKvrQK9evaJwzMhszkXOqUpsVPb8nlH9nI\/Y9vDDD+e94\/983MF5TZg999wzngfwWm655YI+DuADDdZyV\/3hl5Y3PUfgzwcq+LOON6PXTz\/99MiMj2U4zrkAG02RT\/n1MUi+\/FdccUWzy19YYB80ARMwARMwARMwARMwgSYQsKDdBFgOagImYAImYAImYAImYAImYAIm0DkJIESxJjYjtJk2l+nHWUv5gw8+yAqEkIWYykhZRioilu22224BEbdIyHr\/\/ffDkCFDMrFRYdgzGpT0tNdvBCPEJI6nG6IcolJ6TL9ffvnlKNrpf+1JRwI0IycRPBGwsRuBGD+mBuc35XnuueeysvIDwevggw+Ogi+jeN9+++0G\/vxDGlOmTAn4b7HFFnFk7O23317Io1Hk3AG4IGozdTujTBHZL7jggjgSVOyIQh3Aq2hLw+WSb\/QvwuuTTz7ZID\/q\/+OPP25kfypoI+4jBO68886xbhEVGe1aKm\/aARw33njjKPorHPkXlYH6ox0gmqsutacdUN\/6P20rtA\/8836EoS5xTOdNu6Z90w7IHz\/Kd\/HFF0dhmZkGsJF08vZxTPY3AvrfA5SrKK7SSuORLyP599133yimjxs3LtqD8Lr99tvH\/EmLcHJpuzzllFMK2yU2IOry0QIiL1N533rrrdkHI4jisgdBu8jeUmWl\/KSF\/2abbRaFbNa3rsRF9pfaK720rPmwH374Ybj++utjeag\/RqIzap3ycn6feuqpcZaFauuPvFi3+6ijjsquC\/CFDWUTI83cgD3EaYvy58vq\/03ABEzABEzABEzABEygKQQsaDeFlsOagAmYgAmYgAmYgAmYgAmYgAl0agIIQYhDlcQpwuC0L1Vo0tFWKkx7HcfWInuLjqU2VWM\/Ilc14dJ0y\/2WraTZHq5SfpRPo4YR1HFNKa\/Ctld5KjGrVOeV4remv9inNulYuXzEtFyYonSKjpVLo5Sf8m+tOsWuatNqSthS9qfHSS91YlTOntYuf5q\/f5uACZiACZiACZiACZhAUwlY0G4qMYc3ARMwARMwARMwARMwARMwARMwARPoUgQQ7xgRyzTMErS7VAFdGBMwARMwARMwARMwARMwARPoxAQsaHfiyrPpJmACJmACJmACJmACJmACJmACJmACLSOAmD19+vRM0GaKaqZlzo9qbVkujm0CJmACJmACJmACJmACJmACJtBcAha0m0vO8UzABEzABEzABEzABEzABEzABEzABDo1AURr1rJmZHZ+80jtTl21Nt4ETMAETMAETMAETMAETKALEbCg3YUq00UxARMwARMwARMwARMwARMwARMwAROongCC9i233BJYQ5vt+++\/j6Oz2d93333VJ+SQJmACJmACJmACJmACJmACJmACbUbAgnaboXXCJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACLSFgQbsl9BzXBEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEygzQhY0G4ztE7YBEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEygJQQsaLeEnuOagAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAm0GQEL2m2G1gmbgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAmYgAm0hIAF7ZbQc1wTMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMIE2I2BBu83QOmETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMAETMIGWELCg3RJ6jmsCJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJmACJtBmBCxotxlaJ2wCJmACJmACJmAC9UHgP\/\/5T7jnnnvC1KlT66PALqUJmIAJmIAJmIAJ1BkBPe\/xzMdvOxMwARMwARMwARMwARNoTwIWtNuTtvMyARMwARMwARMwgS5I4Pvvvw8\/+tGPwvLLLx9ef\/31LlhCF8kETMAETMAETMAE6pvApEmT4vPeOuusE3744Yf6huHSm4AJmIAJmIAJmIAJtDsBC9rtjtwZmoAJmIAJmIAJmEDXIkCnZp8+fWIn53HHHRcQuO1MwARMwARMwARMwAS6BgGe7fr37x+f9bbZZpvw73\/\/u2sUzKUwARMwARMwARMwARPoNAQsaHeaqrKhJmACJmACJmACJlC7BK666qrYyclI7cGDB3vkTu1WlS0zARMwARMwARMwgaoJIGYjYvOMt9RSS4V33nmn6rgOaAImYAImYAImYAImYAKtRcCCdmuRdDomYAImYAImYAImUMcEvvvuuzBw4MBM1N5pp53Cm2++WcdEXHQTMAETMAETMAET6LwEWCf76aefzsRsBO27777bo7M7b5XachMwARMwARMwARPo1AQsaHfq6rPxJmACJmACJmACJlA7BP71r3+F7t27Z6L2QgstFJiC\/K233qodI22JCZiACZiACZiACZhAWQJffPFFOPHEE8Pcc8+dPdftt99+FrPLUrOnCZiACZiACZiACZhAWxKwoN2WdJ22CZiACZiACZiACdQZAaal7NWrV9b5yWgeCdsPP\/ywO0LrrD24uCZgAiZgAiZgAp2DAOtiP\/nkk+GEE04IK6+8coNnuc0228zLyXSOarSVJmACJmACJmACJtBlCVjQ7rJV64KZgAmYgAmYgAmYQMcQQNQ+8MADG3SEImyz9enTJwwfPjw8+OCD4bnnngvvvvtuGDduXBg1alQYPXq0NzNwG3AbaNc2cNlllwVml2BDzGGK3bZyP\/zwQxSEyItrnq97vub7vuc20BFtgOve9OnTwxNPPBFuvvnmcPHFF8cZdVZaaaXCZ7cDDjjAYnZb3RicrgmYgAmYgAmYgAmYQNUELGhXjcoBTcAETMAETMAETMAEqiWAYHPUUUcVdoxK3E73M888c\/jxj3\/szQzcBtwG2rUNzDvvvKFbt25hscUWC7179w4IN\/fcc08UuFtD3CaN7777LjBDxdlnnx0GDBgQFllkkXht\/H\/\/7\/+1a1l9jfU9xm3AbYA2sOaaa1b1fDbffPOFCy64wGJ2tQ+\/DmcCJmACJmACJmACJtCmBCxotyleJ24CJmACJmACJmAC9UuA0Y633357WH\/99St2nM4000wVw6QCuH\/\/74h3czAHt4GWtQEE7SKGPXv2DMOGDQvMONEcYZvr3yuvvBJYc1YCdlE+Ptay+jM\/83MbaHobWGKJJQqveynL3XbbLTz77LPNuv7V75OvS24CJmACJmACJmACJtCWBCxotyVdp20CJmACJmACJmACJhBHOo4YMaKsqGNBu+kd0mnHs3+bn9tA89pAKUFbPBnJeP3118frWLWXc0RwrnmLLrpoRdFI+XjfvPozN3NzG2h6GygnaK+xxhph4sSJHpVd7QXf4UzABEzABEzABEzABNqNgAXtdkPtjEzABEzABEzABEygvgl8\/PHH4Y477ggnnHBC2GyzzQJrNfbo0SNOucuU4+6UbnqntJmZmdtAy9pAJUFbfAcNGhQ++eSTsqMVGZX9+OOPhw022MDXsx+1rF7E3XtzdBto\/TbADBTpUgu77LJLuOSSS8LkyZMtZNf3o7pLbwImYAImYAImYAI1TcCCdk1Xj40zARMwARMwARMwga5JAOGHdbYZyXj11VeHoUOHht\/\/\/vfezMBtwG2gXdsA157XXnst3H\/\/\/WH06NHhuOOOC+uss06hIN2rV6\/w0ksvBa5feffDDz+Ee++9NyywwAKN4rI+N+kiGN16661h6tSp4cADD\/R1z229Xdu677F+xlAbOO200+LzF89gPIsVXdPy1zj\/bwImYAImYAImYAImYAIdTcCCdkfXgPM3ARMwARMwARMwARMwARMwAROoGQKIOx988EGYMGFC2H333RsI1Mwm8fDDDzcQgBCzmZY8HUnKyG9GPd54441xxGNz1uGuGSA2xARMwARMwARMwARMwARMwARMwAQ6mIAF7Q6uAGdvAiZgAiZgAiZgAiZgAiZgAiZQmwQQt++7776w9dZbNxCsp02bFqcfx\/\/UU09t4IcIzkhui9i1Wae2ygRMwARMwARMwARMwARMwARMoPMRsKDd+erMFpuACZiACZiACZiACZiACZiACbQjAYRrlkfQKOx55pknfPnll3EEto6tsMIKMYyF7HasGGdlAiZgAiZgAiZgAiZgAiZgAiZQFwQsaNdFNbuQJmACJmACJmACJmACJmACJmACLSUwfvz4TNTeZpttsjWzN9tss\/D++++3NHnHNwETMAETMAETMAETMAETMAETMAETKCBgQbsAig+ZgAmYgAmYgAmYgAmYgAmYgAmYQBGBVNRmdHb37t3DRx99VBTUx0zABEzABEzABEzABEzABEzABEzABFqBgAXtVoDoJEzABEzABEzABEzABEzABEzABOqHwNixY7OR2i+88EL9FNwlNQETMAETMAETMAETMAETMAETMIEOIGBBuwOgO0sTMAETMAETMAETMAETMAETMIHOS+Dbb78Na6+9dthhhx3CDz\/80HkLYstNwARMwARMwARMwARMwARMwARMoBMQsKDdCSrJJpqACZiACZiACZiACZiACZiACZiACZiACZiACZiACZiACZiACZiACZhAPRKwoF2Pte4ym4AJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmIAJmEAnIGBBuxNUkk00ARMwARMwARMwARMwARMwARMwARMwARMwARMwARMwARMwARMwARMwgXokYEG7HmvdZTYBEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzABEzCBTkDAgnYnqCSbaAImYAImYAImYAImYAImYAKtReDf\/\/53ayXldEzABEwgEvjPf\/5jEiZgAiZgAiZgAiZgAiZgAibQZgQsaLcZWidsAiZgAiZgAiZgAiZgAiZgArVF4J\/\/\/GdYZ511gsWn2qqXjrBGbUD7Ihv88UMRFR\/LE7juuuvCj370o\/D000\/nvfy\/CZiACZiACZiACZiACZiACbQKAQvarYLRiZiACZiACZiACZiACZiACdQbgXvvvTfcc889YeLEieEPf\/hD4P9adt9\/\/32Yc845w\/XXX1\/LZnYJ2xCJaRt\/+ctfwnnnnReOO+640Bri8H333Zele\/zxx8d084I0+fzwww8lOeJPWyX+uuuuG4YMGRLuv\/\/+GB6\/p556Khx11FFhqaWWCrvuumsYP358ybTsYQIicPrpp4devXqFd955R4e8NwETMAETMAETMAETMAETMIFWI2BBu9VQOiETMAETMAETMAETMAETMIF6IoCI3bNnzzgykdGJtSxo\/+tf\/wprrLFGGDx4cKGwiiiaF0brqS5bu6wIyr\/+9a\/DHHPMEdsHv1tD0EYgR2imvbHRBtN6+\/TTT8MWW2wRll9++TB9+vRGxcKGQYMGxbg33HBDFMRJZ9iwYTGda665JksXkRu\/bbfdtqxA3igTH2hQJ10FR6VrBP4DBw4MG2+8cfjmm2+6SrFdDhMwARMwARMwARMwARMwgRohYEG7RirCZpiACZiACZiACZiACZiACXQuAoiD3333XRQPEf5qVdBGaEL4RAhlyvEix8jffffdt0sKcUXlbY9jiNqPPvpoFIVbS9CmLkkXAbpI0Ebw5rj88uW88847Mz\/S4QMHwjJam\/+XXnrpsP7668ffSqtv374WtPMgy\/xPHR177LGt8gFDmWza3UszApTLmNHZK664YjjppJN8LSkHyn4mYAImYAImYAImYAImYAJNJmBBu8nIHMEETMAETMAETMAETMAETMAE\/pcAIiBiJaJgrQraTz75ZLTvrLPOKlltI0aMiOVAjLNrPQKMjKdttJagLcskNudHaL\/99tvxAwuE6fwIbT7AUFslPm7GjBlxCnPqPR2djR\/H\/v73v4dXX31V2XpfBQGYUeetMSK\/iuzaLcg222wTP4yplOHRRx8dlllmmfDFF19UCmp\/EzABEzABEzABEzABEzABE6iagAXtqlE5oAmYgAmYgAmYgAmYgAmYgAk0JFDrgjai5MEHHxwFNtZGLuW23nprC9ql4LTgeFsJ2nw8gWiaF7QxFSGVdpl3qaD9yiuv5L1jWkqzkacPVE3gjDPO6HKCNm2nR48eVQnaDz\/8cCz\/BRdcUDUzBzQBEzABEzABEzABEzABEzCBSgQsaFciZH8TMAETMAETMAETMAETMIG6I4AQrK1c4RF61llnnSjg1OII7U8++SQsuOCCYaWVVio5BTBlWGSRRaoWtOFS766atgGj77\/\/PraN9hqhXa5e0o8vmCo\/7xDHO1LQbut21dbpw5NziZHM1YzQVhtqD7uwjfrHvua4Bx54oOq2QR6\/+MUvwg477BD4oMPOBEzABEzABEzABEzABEzABFqDgAXt1qDoNEzABEzABEzABEzABEygixBgLWWEWbbx48fHtXURKF544YVw+eWXh3HjxoWPP\/64rDh60UUXhbPPPjuceeaZMY2vvvoqo0P6TMmL0IfYwXbLLbcERvXxG6GNPWuxEpZNx4jDVo0ApDIoD\/ZMsywR6Z577gmMUv3ss8+iPQg2OPyJi7jHdtxxx8X9559\/npUh\/QGbvKBNGuTFRj6koRGzlEd+559\/fuSbLw9hH3\/88TBy5MhwyimnhMsuuyzcddddVZU7tY3fjzzySEkhinzfeOONcOihh8YwiK7YRvnZ5+2CIXZdcsklmV2sySyRTOWmjKQxYcKE6Pfhhx+GG264IXKcOHFirF9so5z\/+Mc\/YlsZM2ZM\/K208Fd64gVH\/MnzwgsvDEyh\/uCDD2Zs82Xn\/6lTp8Zwe+21V9h7770DzD\/99NMGQdVWyOe8886LthPvhBNOiBxUd0Si\/XEOqH2wHzVqVMagQcIhxLaLuNkSQfujjz4Kt912W8xz9OjRsb3efffdWb2qntS2KA\/tjjWP5VSnmnKc+DqmePDFVtZ\/ll9aH3C44447wjnnnBMYhTx27NjAqH\/lT1tSvKuvvjr+ZtpzRupS7x988IHMiXvSu\/3222N6w4cPj1ynTJmSsSRvykG9sIc1ebEO\/I033hjOPffceA6nNqYZEJb0rrzyynDqqadmdca07HlHGtdff3047bTTYrrXXXdd+Prrr\/PByv7P9O3YCEM2bBYPGKfu6aefzuzRNeb555\/PWCos8ZVGpbZJHJhSDsoLN85ZrnHYtckmm8RzV\/Wl8JybnEvUgepU+cOFOmZddcqEralNaVqKwzHyW3zxxcuemwrvvQmYgAmYgAmYgAmYgAmYgAlUQ8CCdjWUHMYETMAETMAETMAETMAE6oQAIowEGfaHHHJI2HnnncP8888fRQoEsTnmmCOKrHkxA+GZ0YnLL798FDMRtGeeeeYohrz88suRoESzNI\/9998\/E4XT4xIy02P8TgXGUtVSlI9EReLn06TcOJUfUQ+hHYFr2WWXDSuvvHJ47bXXGmWH4JMXtIvSl80SIpW\/RDolTDg+JMAfP8Sp1VZbLf6PkFhKvFP8\/P7SSy+NcRGh805rJsuW\/F42E6\/ILkZhEgfxErvY0jTWXnvt2A5+9atfhYMOOigMHjw4+sMSkZb\/YUc5xRBhTe0KMS5Nj\/ojzpJLLhkOPPDAsNtuu0X\/zTffPLz55psNioctiKWLLrpoTB9xnfJuttlmkSdCuFy+rfDxAPmusMIKcU8bwMFA07cj0iLscX4QdsCAAYXtEgEcf7U95VnNnjIg3vfs2TOec9tvv3044IAD4vnEuUW6sCMcTm2X4\/JTPrRnHU\/31FG+Tab+Gsn93HPPhR133DH87Gc\/C1dddVX8WIVzm3Md8R+HLWlcOMKQkbocRxSVrXCBO7MHXHzxxYE13Emb+qLecGKnNFdfffUotvP\/HnvsEfbcc8+Y7q677pqlGyP+92MIPsDp3r17DLPtttvGc3ndddcNpJO2bV231lxzzXDttddmdYy9RVOzK490T3qys2iv6wtxyI8wa6yxRrzG8OHKpptuGuabb75w0003Ze2fsNW2TaXL9XejjTaK7ZJziuv2csstF3bZZZcAJ\/5X2VVu6iCtU8KrTlmKoKg8HKPt6FxNWfBb067rup\/39\/8mYAImYAImYAImYAImYAIm0FQCFrSbSszhTcAETMAETMAETMAETKALE0CgQLhFAEG0QOxAFJUQxShLBO386DtEEoSQ2WefPWi0M5i0niqiIwIl6SNU7bTTTjF9RnMTl\/Ql9JAO\/xP2iy++CJMmTWoQthr8xCe\/DTbYIMZFeEzFF0YdUr599tknlhc\/NgQvjrNXmSnPLLPMEgW5dLQ5dhBGYiwCpxxlYiMtNn7jyAORbLvttovHEQFlF3sJ0Olx8thyyy1jeEa3N8Vp9PXNN9\/cKBr5YZeEUERXmMl2RcjbpePYRTtYeOGFM0E5TQ8\/xGyNzCW82hV+iHUcwxFmrrnmimVUeI6THiOgxXHffffN4mCXxP9VVlklpHVD\/SJm7r777ll40qN8\/fv3jzYzohiHDYzkxSbyQaRlRC0CMv8jBOJSgZX6kUPcJtzQoUMb5JXG6du3b9YGFK\/SnhHIpMvIcmZFkGOEOenhl7YT1Scjs+WnOHDEfuoYP+pc9ax4Ek\/Z5\/3UxhkZLVd0br\/++utZHcMRgVZtGr6wZtP5j78ceXK9QcDXtYIPH5ihAJvZqBOuCTjCc63gOCP9U6d20a9fv+xDFM5PpaP6Ix\/SoA2rPZAOHzwQlronTDUOe7799tssD3inHJWGOJO+2j+jqKlTyv\/oo48qaPSv1DZVf7169Yp5M\/obx3FdN7jOUnd81IFL2ZWrU9kvm9O2gV8pxwc0lK\/oulMqjo+bgAmYgAmYgAmYgAmYgAmYQDkCFrTL0bGfCZiACZiACZiACZiACdQpAQQfBAlEklS44LdEsVTAlYg2cODABuERVRC2SIvRpnKMhORYnz59MlEH4UijflMhhGmzGSVdrbCkPNgzMpd8Vl111SwfjiP6MFrxrbfeSoNHgRAxO52uGdFJgh6jxlOHXxEPwqQCaMoQv8MPPzzalQqSrHfNWtbY++STT6bZRHs4TniJYA0CFPxDuEGDBhWmlwaX0Ec5qK+8S+3KC4eMlJVdipeWOy\/ASxhbbLHFGrQT+Ihx2q5IE+bkwZZvA5SREd\/4DRs2LNpPGAmmDz30kMzK9kqPOhbLtF1L7MQvDQMbZhOgfbz77rtZeuQn+\/L1LD\/atfLKIpb5wdTujIAmXcT5vNP5mbYfhUn9dIw9+Zdqq\/iXiqdzOy\/Klzq3lc56660X64N8EaVVd4zAply0dR2TnfoAJR3RrPZJHD5ukSN\/PljgeHq+UgeMwuZ4+nENdvABCwyUr8rGdSutH37zcQ5p8KFNtU71Tbw0vTT+rbfeGkdkI5an55u4sU9dNW3zpZdeirYywj1tg\/oogjabHle5m1qnedtSO9PfzNoAA0bJ25mACZiACZiACZiACZiACZhAaxCwoN0aFJ2GCZiACZiACZiACZiACXQxAhJXEAZTh0iTF8U4xlS3CBgIloxuTTdNd8xIWznWp11iiSViHIlOjETUiEumE5bYgy1HHHFE9r\/SqGaPbb179475ILLIYdN+++1XmCZx2BCnELMQFBlhTvlSoY20CJfnoTxScSsVk\/AXX\/akgdN61+SD6ApDxDw2TYPNtM\/5tJRffg+\/LbbYItr93nvv5b2z\/yUYUg4xzzwTu2adddaw4oorhq222ioK8kyVrOmqEedUjlTQ5nfqJGgjXqd5EVeCdv6jAdkHF+WRpilRUx9HsBYxYdmK1kuWoM102GJJuqpH1iou5bCZsMRjY7S0RiqTn4RSxVcbYARwke0Kl99rhPECCyyQ2ZiGSdtPypEwqV8aJy0jTPOuKB5pMyqesuGfntf8Ljq3lQ7TsOcd6TGtPOlR39iRtvOjjz46+tG2VC7VFwK46ot08Vde7OX4GIT0mcI8z5w4Shc\/piInbHrdwiY2tccXXnhBSVfcq75JM593Glnth\/CcI8zaIPE5LQtx0nor1TYnT54cy8FMBSkjRl9jC7MSyB7Kr+s1eTWlTvO2pWVKf7NcA\/kyNb6dCZiACZiACZiACZiACZiACbQGAQvarUHRaZiACZiACZiACZiACZhAFyOAcIEgwUji1KXiikQxjmlkMXHyG6LcSiutFEdpKi1EFdZVJixiNY71iZkavEePHnE92RkzZkSBkDWkEXub60466aSYD+vUYiuCDyNm03WUlTb+jKBkjeZlllkmTpmN0CmxMy+2El7Cl3gorVTcSkUm\/CXswlkCGyIePBhNqTyL9uRZjSOcRrx++eWXJaNIMKQcRWlXY1c62rQaQRu+aV4wEMc8Y9kHmzSOCjR69OjIjSnG4XzllVfG\/wmf506cND2NOCdd5X\/dddcp6UZ7wpE+I3pZ81h1RV5F+akNdOvWrdD2Rhn894BEX2Y3KCqzzs+0\/Sit1E\/H2MOiVDvGvygeeeujCJUx3Red20qH9b7zjnrW6Pk0Hf2ed95547rbpCGnKfEZdQ1POdJSXml4TVHOyP0idooPj3LXrYUWWiggEOfbo+IX7dO2n9qahsUmPt7BZtbtxgbqRR8HcFzXBOIRvlLb\/Pzzz+P64\/PMM08UyJVfykcs2Jcrd7k6TTkrj6K9PnQ5+eSTi7x9zARMwARMwARMwARMwARMwASaTMCCdpOROYIJmIAJmIAJmIAJmIAJdH0CqRCSlhaRRuKKRisjkCy99NJR0GNKX8SYUlualoQqRv2SLqNYEa4ROxG4xo0bF7vmdxAAABDfSURBVO644464trHEmDR+tb+1XjZpMgU20xb\/9re\/bSR2kcfw4cNj3owUZ+QtdnG8lBCIn3jkBW0EMwl1eWE15SvxSkKspuOuhmE5BsTXWt1MSVzKYTd2UkZxRsRTec4555zo\/\/Of\/zyKopXsSkW9fLkl5LNXubGLfNdee+2Yj9qV7JV92Cj75MeedYHxm3vuuRsJ2kXhGZGqennxxRdjUthZqh6VF21hyJAhMS4jXBHDOZbWc356avyVV5EtSju\/l6DNxxx5hoRV++EjkP\/f3v2EWFW+ARxfiS1MQZCBcBGJSIJRRgyBKCSjA5nSIpQgNHAoEFFyp4uCwT+4CMwa3UlDYdTGgSzdRGGhiwhqEWGIJlaoZVoE7c6P7wvP5ZnTuXNHf\/d2Hf2+cDn3nj\/vn8\/7nrt5zvue7JiP1YOPlB\/jOPo2lxt55uu4hhn5tGG693bkk5cBj3KoayxTH8uwdxpP8QBCHp\/kR92irFznCGgzA38qc1zv5H8r2tK0bepvrHNQnFnT\/Ndhytjlmnpbcr2nMzYx5H3kPBDArHPKoFweiCAoTxmRyHvRokV31KfhTHncp9xLTemjjz4q+Y+NjTUddp8CCiiggAIKKKCAAgoocNsCBrRvm8wLFFBAAQUUUEABBRS49wWaAkW0mmBIPShGcIMlwgnQcKwpRdAqHyNQQ7CF65ixSPCO\/CPgyKxfZsISUP1\/EnkyO5tymA1OEDAvfx55x7K9nJdnb1P3aHMEeiNARRviWD1IyDHy4sP3nLIv+ZPyUtl8b0q05XYSs2Qpv163nAfHOId2RP4EnPmQIjjFOdOpVw5o50AaeeWAdpTFfgwioBy2pfDajOp8TRzn3dnUjVUAcM6OdXeuiRndDz\/8cKtfyLdd+VHO1q1bSzn5Oo7lfqa9OdDHb+rGp6nukXd9G0uOs1pBUxti\/GzcuLGnAW36ZceOHaX+jI8Yq7m+7Mtti7qxbUoRcJ41a1b1zz\/\/\/OuUen6MB\/woP1twXlNZseT4vHnzJp0fBUX+1PlO\/rcin6Zt7u+oa76X2Pfkk0+W9tSX485t4T+QcUQd+XQam5yzbdu2inev7927t8yq5\/UE77zzzqS+oc60fzrtJs9IuW7so53UqX6vxvlxj\/HfYVJAAQUUUEABBRRQQAEFuiFgQLsbiuahgAIKKKCAAgoooMA9JlAPYETzCHJEADcHMz7++OMSpCEAlwMhXMfvDRs2\/Ot9qgRWmMVJsIqgD0uDkwiWPPHEE+UduBy7nXfYRj3r2wiwsIw4M42b3in91ltvlbowc5S6RaL+EVBi5mM9QBUe9aAxwSvqzyeCW5FnzELHOcrinHi37ZEjR+LU1jYCe3F+68AUX6Ifmf3dLhE4o460A3sS10V\/sJxxzOhsqtfZs2fLtVGv3G6C2zndSUA7Au7UsWlsxUMRzJ6mDrQhHN99991cfPk+Ojpa2rtly5ZWv5Avy4dTRh7XcTHHo58JbOfE+4+5js9vv\/1WxgqmJOoSx+p1z3nUvxOYnD17drmWFQbqKe4b6hTucU70OducchvqY5Xz2l2X7+36OCZP7m1mlEdql08c\/+WXX1rjiXbWE2OEvowU\/c89mMun3U1lcQ6rPuDODOh64mGBNWvWlN25bfX+CS\/OmW5ihn70d4x96si9RH0j2M45P\/3006Rsoy07d+4s76anvXE\/TjU2yYQ2L1iwoPrggw9KOdS9Pi5yYbnd2ZRzptOnnEP9uPeb0ptvvlkc2h1vusZ9CiiggAIKKKCAAgoooMBUAga0p9LxmAIKKKCAAgoooIAC95kAQRCCvRFcYUvAg\/18IshDQIagXQRc2P\/yyy+XIAazqq9fv96S+\/zzz6sXXnihdW7rQFWVJcDJiyW+maVNohxmUbOfd0BHGfm62\/1+69atsnQ5ebIMN2XUU8xEJpDIbO1Ihw8fLkv3ci2zHwkm4kKbL1y4MCkQmuuKG7MkuS4vRc2y54888kjZz2xNAl\/kRZ2YGc75AwMD1fj4eFShBL+Ywc77vW8nxWx3grjt0o0bN8oSyHPnzi3lUA\/eV\/zee++VS6gbgcemel26dKnMrI96cS5BXc6NdufxE+Nq\/fr1pV+j3ZT52GOPlWtiXEUfRSCf\/JiNzTUkjkd+BLVzYC4cBwcHq5s3b7aa\/vXXX5elycnrjz\/+aLWPMR9BQwKo5B3lcBLfY0xiE8fYEhiP9n722Wcl8E2dOUZ5cYx+znVsVarhC9ceOnSoXEsA\/a+\/\/mqd9eWXX1YPPvhgOcaS0owtzqfO5B8mbMOeLeVHUJ42ck1cx7iN6xjfuf2cs2\/fvlIe\/fbdd9+16pLvba75\/fffJ+XDiVyfE3WJh0eefvrp8pqBOM7rAB599NHq559\/btUhAtrxwEW0ifIisJ\/bSl6xDD3\/K99++21kXwx493mMV\/Jq97\/FQzAs353v6VZGbb6QX\/Q39wZ1XLFiReteunLlSut4XiWCVy3Edc8++2x5qCLa22lsUhXqyLjkfwWL\/OEBAYLnuR+m26fRTLyo39DQUMmHtvH72rVrccqk7RtvvFGO879rUkABBRRQQAEFFFBAAQW6IWBAuxuK5qGAAgoooIACCiigwD0iELN1I7gS2z179rSCYbEvtgRxSARV9u\/fXwIZzJB89dVXy3uRn3rqqbaBDwIrBK2ZMZkDLjGDkCBiNxKBpddee63UrWnWLmXQDoI\/8+fPrx5\/\/PFq+\/bt1fDwcEUQj2B7tJftuXPnKkzyvvgeHrSHYNrixYurdevWVbt27ap2795d2nrq1KlJ15IXiWsIghI4Ij+C77xzmHfj8n7vyHu6JsyunjNnTjHGoClRZgQzCeARZN+0adOk\/uAcgli0g3qx1HWuF8epWxjkLe\/GPn36dOMx2o1JPj++x0zpHNBevXp1qRv9FLOwWRL74sWLk5qWHRlbLL3OwwX0LfX+9ddfW+e3K58ycuIaHiqgfgQbCaYSRCS\/PDOXAHf+He1hy6xW6jadhGcsPc7s21deeaWMRYL39Trj2M6YezoC2bkufKeN7e75XFfubfqBFQ54V\/nIyEjJE48IapJXPf92baZtH374YZmpzfgkaL927dpyr3BvMFYJwDflR1valYUBieu\/+uqr6plnnikBcvoIv4ULF5Zrsz91OXDgQCmL\/y1mSPNwBW27evVqPnVa3+Ne4l557rnnqhdffLF139L39Cnv7mbpel6rwDjmwYT333+\/4r+SNnOM8dXuP4b25\/uZfFlevMkr9rHMeB579GmMr3Z9Gg3GKO43HOkz\/utzHeJcyqCP+A\/lOpMCCiiggAIKKKCAAgoo0A0BA9rdUDQPBRRQQAEFFFBAAQXuEYF4dyuzIglg1T\/sj2NsCYbloAbBDGYDsjQ3gR2WnCVwMlViNiX55MTsWWYwdjMg8uOPP1ZHjx6dMk\/KYzbsiRMnSv2ZpRntY9Y2S+n+8MMPZV\/dht91D66l\/cwYfv3116svvviilI8dAaGJiYlizO9IXENAlHMPHjxY6vL3339PCkbFuZ225EVg7YEHHqgIbrdL9Bsz1JmJS12b3MmLIGO9XuwnsaX9tIVP+DAjnVnbcYxtHKNP+NSv4Rxm+5I4FkE5XD755JPSD\/TN+fPnp3TBnocPxsbGSt+zfHd9PFKXXH7UnW094UR9eQ8045sHFmg3+xnHBAj5HhbRzrwNr3reTb8599NPP63efvvtMjudWfOsfkCwsz5+qG\/YZuvcnvw92p3v+bguzst15Tv9yMMmTfd2lB\/Xso3vOZ9oJ\/voY2b\/kh\/jKvcNjlGfqGt2zPmzn3NpS06MY8Yz76tmuXzuYfKtJ\/bxUAT9xz3OLPRcl\/r5U\/0mr5MnT5b+oex6PrSbfcxup93MVo\/A+eXLl0vfMguffKLd4Zi32ZR8uEd4aCMswoq2L1mypBznPsiJMqb7f40lDwNRFvddu8SDH9SFBwPI36SAAgoooIACCiiggAIKdEPAgHY3FM1DAQUUUEABBRRQQAEFFLhLBXi4gAATM2JnYiKIFwHtenBwJrbHOivQTQECzayqwHvumx5EoSwe5OAeeumll8rDFt0sv54XDw5QFgF7kwIKKKCAAgoooIACCijQLQED2t2SNB8FFFBAAQUUUEABBRRQ4C4UYJYks7Q3b97c82BWL5pvQLsXquZ5rwhwfxPQ5h3w7QLazPgmyMwrHHo5a5q8eU0Cy5P78Mm9MsJshwIKKKCAAgoooIACd4eAAe27ox+shQIKKKCAAgoooIACCijQMwGWUCegxZLKMyWxpDLBbJZkpu58WFaapZTzcsszpT3WU4FeCcSS48PDw9X3339fAtsEl1mefnx8vFq6dGk1MDBQlovvVR3I99ixY+U+PXPmTC+LMW8FFFBAAQUUUEABBRS4DwUMaN+HnW6TFVBAAQUUUEABBRRQ4P4SIAA8OjpaLVu2rLwzdya0ntmmCxYsqFauXFmtWrWqfB566KHyu5ezTGeCjXVUIAtwf7PE98jISLV8+fKy\/Dj3DQ+BDA4OVjt27KguXbrU0wdBvvnmmxI0J7juAye5d\/yugAIKKKCAAgoooIAC3RAwoN0NRfNQQAEFFFBAAQUUUEABBe5yAZYAJtj0\/PPPz5iAE4Hr+BDg5rvBsrt8oFm9vglwb3Cf3Lhxo6xu8Oeff5bfvb5nyH9oaKjat29fT5c07xusBSuggAIKKKCAAgoooEDfBQxo970LrIACCiiggAIKKKCAAgoo8N8IEBCemJj4bwqzFAUUuC8ECGgfP37ch03ui962kQoooIACCiiggAIK9EfAgHZ\/3C1VAQUUUEABBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUKCDgAHtDkAeVkABBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRToj4AB7f64W6oCCiiggAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiigQAcBA9odgDysgAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKKNAfAQPa\/XG3VAUUUEABBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUECBDgIGtDsAeVgBBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRRQoD8CBrT7426pCiiggAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIdBAxodwDysAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKKKBAfwQMaPfH3VIVUEABBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBToIGNDuAORhBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRRQQIH+CBjQ7o+7pSqggAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKdBAwoN0ByMMKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKKKCAAv0RMKDdH3dLVUABBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRToIGBAuwOQhxVQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRRQQAEF+iNgQLs\/7paqgAIKKKCAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKKNBBwIB2ByAPK6CAAgoooIACCiiggAIKKKCAAgoooIACCiiggAIKKKCAAgr0R8CAdn\/cLVUBBRRQQAEFFFBAAQUUUEABBRRQQAEFFFBAAQUUUEABBRRQoIPA\/wCkRRaNSDpJ4wAAAABJRU5ErkJggg==)\n\"\"\"\n\"\"\"\n![](https:\/\/github.com\/aaiit\/lux\/raw\/main\/lux.png)\n\"\"\"\n!pip install git+https:\/\/github.com\/aimat-lab\/gcnn_keras \n!pip install -q kaggle-environments -U\n!cp -r ..\/input\/lux-ai-2021\/* .\n!git clone https:\/\/github.com\/aaiit\/lux-AI.git\n!cp lux-AI\/Game\/*.py . \n!cp lux-AI\/Game\/lux\/* lux\/ \n!cp lux-AI\/*.png .\n!python3 -c 'import kgcnn as tf; print(tf.__version__)'\n\"\"\"\n<!-- Steps involved in reinforcement learning using deep Q-learning networks (DQNs):\n\n1. All the past experience is stored by the user in memory\n2. The next action is determined by the maximum output of the Q-network\n3. The loss function here is mean squared error of the predicted Q-value and the target Q-value \u2013 Q*. This is basically a regression problem. However, we do not know the target or actual value here as we are dealing with a reinforcement learning problem. Going back to the Q-value update equation derived fromthe Bellman equation. we have: -->\n\"\"\"\nfrom kgcnn.layers.gather import GatherNodes\nfrom kgcnn.layers.keras import Dense, LazyConcatenate  # ragged support\nfrom kgcnn.layers.pooling import PoolingLocalMessages, PoolingNodes\n\nfrom kaggle_environments import make\nfrom lux.game import Game\nfrom lux.game_map import Cell, RESOURCE_TYPES, Position\nfrom lux.game_objects import Unit\nfrom lux.constants import Constants\nfrom lux.game_constants import GAME_CONSTANTS\nfrom lux import annotate\nimport math, sys\nimport numpy as np\nimport random\nfrom IPython.display import clear_output \nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras import layers\nimport tensorflow_hub as hub\nfrom collections import deque\n\n\"\"\"\n# The input of the model \n\"\"\"\nTYPE_DICT = {None:0, Constants.RESOURCE_TYPES.WOOD: 1, Constants.RESOURCE_TYPES.COAL: 2, Constants.RESOURCE_TYPES.URANIUM: 3 }\ndef jitter(n):\n\n    adjencent = []# np.zeros((32,32))\n    for x in range(n**2):\n            \n        row = x \/\/ n\n        col = x % n\n        if col < n-1:\n            adjencent.append((x, row*n+col+1))\n            adjencent.append((row*n+col+1, x)) #symetry\n        if row < n-1:\n            adjencent.append((x, (row+1)*n+col))\n            adjencent.append(((row+1)*n+col, x))\n       \n    return adjencent\ndef get_inputs(game_state):\n    w,h = game_state.map.width, game_state.map.height\n    # Nodelist(Map Tile)\n    # Format: Resource Type, Number Resources\n    NG = np.zeros((1,w*h,2))\n\n    #NG = [[None]*w for i in range(h)]\n\n    for i in range(w):\n        for j in range(h):\n            cell = game_state.map.map[j][i]\n            node_id = j*h+i\n            if cell.resource is None:\n                if cell.citytile is None:\n                    NG[0][node_id] = [0, 0]#blank\n                else:\n                    NG[0][node_id] = [4, 0] #city\n            else:\n                NG[0][node_id] = [TYPE_DICT[cell.resource.type], cell.resource.amount]\n            #NG = [[ 0 if game_state.map.map[j][i].resource==None elif game_state.map.map[j][i].citytile is None TYPE_DICT[game_state.map.map[j][i].resource.type] else 4]]\n            #NG[i*h+w,1] = 0 if game_state.map.map[j][i].resource==None else game_state.map.map[j][i].resource.amount\n            \n    #NG = tf.data.Dataset.from_tensors(NG)#, 'node_input'\n    #edge_list = tf.data.Dataset.from_tensor_slices(np.array(jitter(3)).reshape(1,-1,2))#, 'edge_index_input'\n    NG = tf.ragged.constant(NG, ragged_rank=1, inner_shape=(2, ))\n    \n    edge_list = np.array(jitter(w)).reshape(1,-1,2)\n    edge_list = tf.ragged.constant(edge_list, ragged_rank=1, inner_shape=(2, ))\n    \n    # The map of units features\n    U_player = [ [[0,0,0,0,0] for i in range(w)]  for j in range(h)]    \n    units = game_state.player.units\n    for i in units:\n        U_player[i.pos.y][i.pos.x] = [i.type,i.cooldown,i.cargo.wood,i.cargo.coal,i.cargo.uranium]\n    U_player = np.array(U_player)#\n    \n    U_opponent = [ [[0,0,0,0,0] for i in range(w)]  for j in range(h)]\n    units = game_state.opponent.units\n    for i in units:\n        U_opponent[i.pos.y][i.pos.x] = [i.type,i.cooldown,i.cargo.wood,i.cargo.coal,i.cargo.uranium]\n\n    U_opponent = np.array(U_opponent)\n    \n    # The map of cities featrues\n    e = game_state.player.cities\n    C_player = [ [[0,0,0] for i in range(w)]  for j in range(h)]\n    for k in e:\n        citytiles = e[k].citytiles\n        for i in citytiles:\n            C_player[i.pos.y][i.pos.x] = [i.cooldown,e[k].fuel,e[k].light_upkeep]\n    C_player = np.array(C_player)\n\n    e = game_state.opponent.cities\n    C_opponent = [ [[0,0,0] for i in range(w)]  for j in range(h)]\n    for k in e:\n        citytiles = e[k].citytiles\n        for i in citytiles:\n            C_opponent[i.pos.y][i.pos.x] = [i.cooldown,e[k].fuel,e[k].light_upkeep]\n    C_opponent = np.array(C_opponent)\n    \n    # stacking all in one array\n    #E = tf.data.Dataset.from_tensors(np.dstack([U_opponent,U_player,C_opponent,C_player]))\n    E= tf.expand_dims(np.dstack([U_opponent,U_player,C_opponent,C_player]), axis=0).numpy()\n    return [NG, edge_list,E]\n    #return tf.data.Dataset.zip(( NG, edge_list,E))#.map(lambda _map, n, e: {'The game map': _map, 'node_input': n, 'edge_index_input': e}).as_numpy_iterator().batch(265)\n    #return E, NG, edge_list\n    \n\n\"\"\"\n# Model\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras import layers\nimport tensorflow_hub as hub\nfrom collections import deque\nimport random\nimport math\nfrom tensorflow.keras import backend as K\n\n\"\"\"\nwe add two lines:\n\ne= tf.keras.backend.max(y_true,axis = -1)\ny_pred*= K.stack([e]*8, axis=-1)\n    \nto make the positions which doesn't contain neither unit or city by zero in the prediction probabilities, in order to focus only on the main occupied positions.\n\"\"\"\n\ndef custom_mean_squared_error(y_true, y_pred):\n    y_units_true = y_true[:,:,:,:6]\n    y_cities_true = y_true[:,:,:,6:]\n\n    y_units_pred = y_pred[:,:,:,:6]\n    y_cities_pred = y_pred[:,:,:,6:]\n    \n    \n    is_unit = tf.keras.backend.max(y_units_true,axis = -1)\n    is_city = tf.keras.backend.max(y_cities_true,axis = -1)\n    \n    y_units_pred*= K.stack([is_unit]*6, axis=-1)\n    y_cities_pred*= K.stack([is_city]*2, axis=-1)\n    \n    loss1 = K.square(y_units_pred - y_units_true)#\/K.sum(is_unit)\n    loss2 = K.square(y_cities_pred - y_cities_true)#\/K.sum(is_city)\n    return K.concatenate([loss1,loss2])\n\ndef units_accuracy(y_true, y_pred):\n    y_units_true = y_true[:,:,:,:6]\n    y_cities_true = y_true[:,:,:,6:]\n\n    y_units_pred = y_pred[:,:,:,:6]\n    y_cities_pred = y_pred[:,:,:,6:]\n    \n    is_unit = tf.keras.backend.max(y_units_true,axis = -1)\n    y_units_pred*= K.stack([is_unit]*6, axis=-1)\n    return K.cast(K.equal(y_units_true, K.round(y_units_pred)), \"float32\")\/K.sum(is_unit)\n\ndef cities_accuracy(y_true, y_pred):\n    y_units_true = y_true[:,:,:,:6]\n    y_cities_true = y_true[:,:,:,6:]\n\n    y_units_pred = y_pred[:,:,:,:6]\n    y_cities_pred = y_pred[:,:,:,6:]\n    \n    is_city = tf.keras.backend.max(y_cities_true,axis = -1)\n    y_cities_pred*= K.stack([is_city]*2, axis=-1)\n    \n    return K.cast(K.equal(y_cities_true, K.round(y_cities_pred)), \"float32\")\/K.sum(is_city)\n\n\ndef get_model(s):\n    \n    #shape 4(n**2+n), 0 if 1\n\n    \n    n = keras.Input(shape=(None, 2), name='node_input', dtype=\"float32\", ragged=True)\n    \n    ei = keras.Input(shape=(None, 2), name='edge_index_input', dtype=\"int64\", ragged=True)\n    n_in_out = GatherNodes()([n, ei])\n    node_messages = Dense(4, activation='relu')(n_in_out)\n    node_updates = PoolingLocalMessages()([n, node_messages, ei])\n    n_node_updates = LazyConcatenate(axis=-1)([n, node_updates])\n    \n    n_embedd = Dense(s**2)(n_node_updates)#s**2\n    #n_embedd = layers.Reshape((s,s,-1))(n_embedd)\n    g_embedd = PoolingNodes()(n_embedd)\n    #print(g_embedd.shape)\n    \n    inputs = keras.Input(shape=(s,s,16),name = 'The game map')#,name = 'The game map'\n    #f = layers.Flatten()(inputs)   \n    h,w= s,s\n    f = layers.Conv2D(16, (4,4), padding='same')(inputs)\n    f = layers.Flatten()(f)\n    #f = layers.Conv1D(4, (4,4), padding='same')(f)\n    f = layers.Dense(w*h,activation = \"sigmoid\")(f)\n    f = layers.Reshape((h,w,-1))(f)\n    combined = layers.Concatenate()([f, layers.Reshape((h,w,-1))(g_embedd)])#layers.Reshape((h,w,-1))(g_embedd)#\n    #cov_combined = layers.Conv2D(4, 2, activation='relu', data_format='channels_last')(combined)\n    #cov_combined = layers.Dense(1)(combined)\n    units = layers.Dense(6,activation = \"softmax\",name = \"Units_actions\")(combined)#,name = \"Units_actions\"\n    cities = layers.Dense(2,activation = \"sigmoid\",name = \"Cities_actions\")(combined)#,name = \"Cities_actions\"\n    output = layers.Concatenate()([units,cities])\n    model = keras.Model(inputs = [n, ei, inputs], outputs = output)\n    #model = keras.Model(inputs = inputs, outputs = output)\n    model.compile(optimizer= \"adam\", loss= custom_mean_squared_error ,metrics = [\"accuracy\"])\n    \n    return model\n\n\nmodel =get_model(12)\nmodel.summary()\ntf.keras.utils.plot_model(\n    model,\n    to_file=\"model.png\",\n    show_shapes=1,\n    show_dtype=1,\n    show_layer_names=True,\n    rankdir=\"TB\",\n    expand_nested=False,\n    dpi=96)\nimport tensorflow.keras as ks\n\nfrom kgcnn.layers.casting import ChangeTensorType\nfrom kgcnn.layers.gather import GatherNodesOutgoing\nfrom kgcnn.layers.keras import Dense, Activation, LazyAdd\nfrom kgcnn.layers.mlp import MLP\nfrom kgcnn.layers.pooling import PoolingNodes, PoolingLocalEdges\nfrom kgcnn.layers.pool.topk import PoolingTopK, UnPoolingTopK, AdjacencyPower\nfrom kgcnn.utils.models import generate_embedding, update_model_kwargs\n\n# Graph U-Nets\n# by Hongyang Gao, Shuiwang Ji\n# https:\/\/arxiv.org\/pdf\/1905.05178.pdf\n\nmodel_default = {'name': \"Unet\",\n                 'inputs': [{'shape': (None,), 'name': \"node_attributes\", 'dtype': 'float32', 'ragged': True},\n                            {'shape': (None,), 'name': \"edge_attributes\", 'dtype': 'float32', 'ragged': True},\n                            {'shape': (None, 2), 'name': \"edge_indices\", 'dtype': 'int64', 'ragged': True}],\n                 'input_embedding': {\"node\": {\"input_dim\": 95, \"output_dim\": 64},\n                                     \"edge\": {\"input_dim\": 5, \"output_dim\": 64}},\n                 'output_embedding': 'graph',\n                 'output_units': {\"use_bias\": [True, False], \"units\": [25, 6], \"activation\": ['relu', 'softmax']}, #unit\n                 'output_citys': {\"use_bias\": [True, False], \"units\": [25, 2], \"activation\": ['relu', 'sigmoid']},\n                 'hidden_dim': {'units': 32, 'use_bias': True, 'activation': 'linear'},\n                 'top_k_args': {'k': 0.3, 'kernel_initializer': 'ones'},\n                 'activation': 'relu',\n                 'use_reconnect': True,\n                 'depth': 4,\n                 'pooling_args': {\"pooling_method\": 'segment_mean'},\n                 'gather_args': {\"node_indexing\": 'sample'},\n                 'verbose': 1\n                 }\n\n\n@update_model_kwargs(model_default)\ndef make_model(inputs=None,\n               input_embedding=None,\n               output_embedding=None,\n               output_units=None,\n               output_citys=None,\n               pooling_args=None,\n               gather_args=None,\n               top_k_args=None,\n               depth=None,\n               use_reconnect=None,\n               hidden_dim=None,\n               activation=None, **kwargs):\n    r\"\"\"Make U-Net graph network via functional API. Default parameters can be found in :obj:`model_default`.\n\n    Args:\n        inputs (list): List of dictionaries unpacked in :obj:`tf.keras.layers.Input`. Order must match model definition.\n        input_embedding (dict): Dictionary of embedding arguments for nodes etc. unpacked in `Embedding` layers.\n        output_embedding (str): Main embedding task for graph network. Either \"node\", (\"edge\") or \"graph\".\n        output_mlp (dict): Dictionary of layer arguments unpacked in the final classification `MLP` layer block.\n            Defines number of model outputs and activation.\n        depth (int): Number of graph embedding units or depth of the network.\n        pooling_args (dict): Dictionary of layer arguments unpacked in `PoolingLocalEdges` layers.\n        gather_args (dict): Dictionary of layer arguments unpacked in `GatherNodesOutgoing` layers.\n        top_k_args (dict): Dictionary of layer arguments unpacked in `PoolingTopK` layers.\n        use_reconnect (bool): Whether to use :math:`A^2` between pooling.\n        hidden_dim (dict): Dictionary of layer arguments unpacked in hidden `Dense` layer.\n        activation (dict, str): Activation to use.\n\n    Returns:\n        tf.keras.models.Model\n    \"\"\"\n\n    # Make input\n    node_input = ks.layers.Input(**inputs[0])\n    edge_input = ks.layers.Input(**inputs[1])\n    edge_index_input = ks.layers.Input(**inputs[2])\n\n    # embedding, if no feature dimension\n    n = generate_embedding(node_input, inputs[0]['shape'], input_embedding['node'])\n    ed = generate_embedding(edge_input, inputs[1]['shape'], input_embedding['edge'])\n    edi = edge_index_input\n\n    # Model\n    n = Dense(**hidden_dim)(n)\n    in_graph = [n, ed, edi]\n    graph_list = [in_graph]\n    map_list = []\n\n    # U Down\n    i_graph = in_graph\n    for i in range(0, depth):\n\n        n, ed, edi = i_graph\n        # GCN layer\n        eu = GatherNodesOutgoing(**gather_args)([n, edi])\n        eu = Dense(**hidden_dim)(eu)\n        nu = PoolingLocalEdges(**pooling_args)([n, eu, edi])  # Summing for each node connection\n        n = Activation(activation=activation)(nu)\n\n        if use_reconnect:\n            ed, edi = AdjacencyPower(n=2)([n, ed, edi])\n\n        # Pooling\n        i_graph, i_map = PoolingTopK(**top_k_args)([n, ed, edi])\n\n        graph_list.append(i_graph)\n        map_list.append(i_map)\n\n    # U Up\n    ui_graph = i_graph\n    for i in range(depth, 0, -1):\n        o_graph = graph_list[i - 1]\n        i_map = map_list[i - 1]\n        ui_graph = UnPoolingTopK()(o_graph + i_map + ui_graph)\n\n        n, ed, edi = ui_graph\n        # skip connection\n        n = LazyAdd()([n, o_graph[0]])\n        # GCN\n        eu = GatherNodesOutgoing(**gather_args)([n, edi])\n        eu = Dense(**hidden_dim)(eu)\n        nu = PoolingLocalEdges(**pooling_args)([n, eu, edi])  # Summing for each node connection\n        n = Activation(activation=activation)(nu)\n\n        ui_graph = [n, ed, edi]\n\n    # Output embedding choice\n    n = ui_graph[0]\n    if output_embedding == 'graph':\n        out = PoolingNodes(**pooling_args)(n)\n        out = MLP(**output_mlp)(out)\n        main_output = ks.layers.Flatten()(out)  # will be dense\n    elif output_embedding == 'node':\n        out_unit = MLP(**output_units)(n)\n        unit_output = ChangeTensorType(input_tensor_type='ragged', output_tensor_type=\"tensor\")(out_unit)\n        out_city = MLP(**output_citys)(n)\n        city_output = ChangeTensorType(input_tensor_type='ragged', output_tensor_type=\"tensor\")(out_city)\n        main_output = layers.Concatenate()([out_unit,out_city])\n    else:\n        raise ValueError(\"Unsupported graph embedding for mode `Unet`\")\n\n    model = ks.models.Model(inputs=[node_input, edge_input, edge_index_input], outputs=main_output)\n    return model\ntf.keras.utils.plot_model(\n    make_model(output_embedding='node'),\n    to_file=\"model.png\",\n    show_shapes=1,\n    show_dtype=1,\n    show_layer_names=True,\n    rankdir=\"TB\",\n    expand_nested=False,\n    dpi=96)\nsize = 12\nenv = make(\"lux_ai_2021\", debug=True, configuration={\"annotations\": True, \"width\":size, \"height\":size})\n\nobservation = env.reset()[0]['observation']\nif observation[\"step\"] == 0:\n    game_state = Game()\n    game_state._initialize(observation[\"updates\"])\n    game_state._update(observation[\"updates\"][2:])\n    game_state.id = observation.player\nelse:\n    game_state._update(observation[\"updates\"])\n\n\n### AI Code goes down here! ### \nplayer = game_state.players[observation.player]\nopponent = game_state.players[(observation.player + 1) % 2]\nwidth, height = game_state.map.width, game_state.map.height\n\n# Get Prediction of actions\nx = get_inputs(game_state)\ny = model.predict(x)[0]\n\n\n\"\"\"\nThe function will take the units of the game stat and predict the options and directions in case of move option gathered in actions list\n\"\"\"\ndef get_prediction_actions(y,player):\n    # move\n    option = np.argmax(y,axis = 2) \n    # c s n w e build_city & research & buid_worker  \n    actions = []\n    for i in player.units:\n#         print(option.shape,i.pos.y,i.pos.x)\n        d = \"csnwe#############\"[option[i.pos.y,i.pos.x]]\n        if option[i.pos.y,i.pos.x]<5:actions.append(i.move(d))\n        elif option[i.pos.y,i.pos.x]==5 and i.can_build(game_state.map):actions.append(i.build_city())\n    \n    city_tiles: List[CityTile] = []\n    for city in player.cities.values():\n        for city_tile in city.citytiles:\n#             city_tiles.append(city_tile)\n            if option[city_tile.pos.y,city_tile.pos.x]==6:\n                action = city_tile.research()\n                actions.append(action)\n            if option[city_tile.pos.y,city_tile.pos.x]==7:\n                action = city_tile.build_worker()\n                actions.append(action)\n    return actions,option\n\"\"\"\n# RL agent\n\"\"\"\nLast_State = {}\nlearning_rate = 0.01\ngamma = 0.95\nepsilon = 1.0\nepsilon_final = 0.01\nepsilon_decay = 0.995\ngame_state = None\nmodel = None\nlast_reward = 0\nW = 0\ndef agent(observation, configuration):\n    global game_state,epsilon,model,last_reward,W\n    \n    ### Do not edit ###\n    if observation[\"step\"] == 0:\n        game_state = Game()\n        game_state._initialize(observation[\"updates\"])\n        game_state._update(observation[\"updates\"][2:])\n        game_state.id = observation.player\n    else:\n        game_state._update(observation[\"updates\"])\n    \n\n    ### AI Code goes down here! ### \n    player = game_state.players[observation.player]\n    opponent = game_state.players[(observation.player + 1) % 2]\n    width, height = game_state.map.width, game_state.map.height\n\n    # Get Prediction of actions\n    x = get_inputs(game_state)\n    y = model.predict(x)[0]\n    \n    if random.random()<epsilon:\n        y = np.random.rand(*y.shape)\n    print(\"eps \",epsilon,end= \" | \") \n    actions,option = get_prediction_actions(y,player)\n    if observation[\"reward\"]>100:reward=0\n    else:reward=observation[\"reward\"]\n    print(\"Reward\",reward)\n\n    \n    if observation.player in Last_State:\n        _x,_y,_player,_option = Last_State[observation.player]\n        state,next_state,reward = _x,x,observation[\"reward\"]\n        if reward>1000:reward=0\n        # Reward \n        if reward > last_reward:r=1\n        elif reward < last_reward:r = -1\n        else:r = 0\n        \n        # Q-learning update\n\n        for i in _player.units:\n            Q1 = _y[i.pos.y,i.pos.x][_option[i.pos.y,i.pos.x]]\n            Q2 = y[i.pos.y,i.pos.x][_option[i.pos.y,i.pos.x]]\n            v = r + gamma*(Q2 - Q1)\n            _y[i.pos.y,i.pos.x][_option[i.pos.y,i.pos.x]] += learning_rate*v\n\n        _y = y + learning_rate*_y\n        \n        states = state\n        _y_ = [_y]\n\n        model.fit(state,np.asarray(_y_), epochs=1, verbose=1) #np.asarray(states)\n        if epsilon > epsilon_final:\n            epsilon*= epsilon_decay\n    Last_State[observation.player] = [x,y,player,option]\n    last_reward = observation[\"reward\"]\n    if last_reward>1000:last_reward=0\n    return actions\nepisodes = 10\n\n# RL training\nsizes = [12,16,24,32]\n\nfor size in sizes:\n    # Inistialise the model\n    model= get_model(size)\n    Last_State = {}\n    for eps in range(episodes):\n        epsilon = 0.2 # Maintaining exploration\n        clear_output()\n        print(\"=== Episode {} ===\".format(eps))\n        print(\"====Size {}\".format(size))\n        env = make(\"lux_ai_2021\", debug=True, configuration={\"annotations\": True, \"width\":size, \"height\":size})\n        steps = env.run([\"simple_agent\", agent])\n    # Save the model\n    model.save_weights(\"model_%d.h5\"%size)\n\"\"\"\n# Submission\n\"\"\"\n!rm lux -r\n!cp -r ..\/input\/lux-ai-2021\/* .\n%%writefile agent.py\nfrom lux.game import Game\nfrom lux.game_map import Cell, RESOURCE_TYPES, Position\nfrom lux.game_objects import Unit\nfrom lux.constants import Constants\nfrom lux.game_constants import GAME_CONSTANTS\nfrom lux import annotate\nimport math, sys\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom collections import deque\nimport random\n\nfrom kgcnn.layers.gather import GatherNodes\nfrom kgcnn.layers.keras import Dense, LazyConcatenate  # ragged support\nfrom kgcnn.layers.pooling import PoolingLocalMessages, PoolingNodes\n\nfrom pathlib import Path\np = Path('\/kaggle_simulations\/agent\/')\nif p.exists():\n    sys.path.append(str(p))\nelse:\n    p = Path('__file__').resolve().parent\n\n\ngame_state = None\nTYPE_DICT = {None:0, Constants.RESOURCE_TYPES.WOOD: 1, Constants.RESOURCE_TYPES.COAL: 2, Constants.RESOURCE_TYPES.URANIUM: 3 }\nmodel = None\n\ndef jitter(n):\n\n    adjencent = []# np.zeros((32,32))\n    for x in range(n**2):\n            \n        row = x \/\/ n\n        col = x % n\n        if col < n-1:\n            adjencent.append((x, row*n+col+1))\n            adjencent.append((row*n+col+1, x)) #symetry\n        if row < n-1:\n            adjencent.append((x, (row+1)*n+col))\n            adjencent.append(((row+1)*n+col, x))\n       \n    return adjencent\ndef get_inputs(game_state):\n    w,h = game_state.map.width, game_state.map.height\n    # Nodelist(Map Tile)\n    # Format: Resource Type, Number Resources\n    NG = np.zeros((1,w*h,2))\n\n    #NG = [[None]*w for i in range(h)]\n\n    for i in range(w):\n        for j in range(h):\n            cell = game_state.map.map[j][i]\n            node_id = j*h+i\n            if cell.resource is None:\n                if cell.citytile is None:\n                    NG[0][node_id] = [0, 0]#blank\n                else:\n                    NG[0][node_id] = [4, 0] #city\n            else:\n                NG[0][node_id] = [TYPE_DICT[cell.resource.type], cell.resource.amount]\n            #NG = [[ 0 if game_state.map.map[j][i].resource==None elif game_state.map.map[j][i].citytile is None TYPE_DICT[game_state.map.map[j][i].resource.type] else 4]]\n            #NG[i*h+w,1] = 0 if game_state.map.map[j][i].resource==None else game_state.map.map[j][i].resource.amount\n            \n    #NG = tf.data.Dataset.from_tensors(NG)#, 'node_input'\n    #edge_list = tf.data.Dataset.from_tensor_slices(np.array(jitter(3)).reshape(1,-1,2))#, 'edge_index_input'\n    NG = tf.ragged.constant(NG, ragged_rank=1, inner_shape=(2, ))\n    \n    edge_list = np.array(jitter(w)).reshape(1,-1,2)\n    edge_list = tf.ragged.constant(edge_list, ragged_rank=1, inner_shape=(2, ))\n    \n    # The map of units features\n    U_player = [ [[0,0,0,0,0] for i in range(w)]  for j in range(h)]    \n    units = game_state.player.units\n    for i in units:\n        U_player[i.pos.y][i.pos.x] = [i.type,i.cooldown,i.cargo.wood,i.cargo.coal,i.cargo.uranium]\n    U_player = np.array(U_player)#\n    \n    U_opponent = [ [[0,0,0,0,0] for i in range(w)]  for j in range(h)]\n    units = game_state.opponent.units\n    for i in units:\n        U_opponent[i.pos.y][i.pos.x] = [i.type,i.cooldown,i.cargo.wood,i.cargo.coal,i.cargo.uranium]\n\n    U_opponent = np.array(U_opponent)\n    \n    # The map of cities featrues\n    e = game_state.player.cities\n    C_player = [ [[0,0,0] for i in range(w)]  for j in range(h)]\n    for k in e:\n        citytiles = e[k].citytiles\n        for i in citytiles:\n            C_player[i.pos.y][i.pos.x] = [i.cooldown,e[k].fuel,e[k].light_upkeep]\n    C_player = np.array(C_player)\n\n    e = game_state.opponent.cities\n    C_opponent = [ [[0,0,0] for i in range(w)]  for j in range(h)]\n    for k in e:\n        citytiles = e[k].citytiles\n        for i in citytiles:\n            C_opponent[i.pos.y][i.pos.x] = [i.cooldown,e[k].fuel,e[k].light_upkeep]\n    C_opponent = np.array(C_opponent)\n    \n    # stacking all in one array\n    #E = tf.data.Dataset.from_tensors(np.dstack([U_opponent,U_player,C_opponent,C_player]))\n    E= tf.expand_dims(np.dstack([U_opponent,U_player,C_opponent,C_player]), axis=0).numpy()\n    return [NG, edge_list,E]\n\n\ndef get_model(s):\n    assert s>1\n    \n    n = keras.Input(shape=(None, 2), name='node_input', dtype=\"float32\", ragged=True)\n    ei = keras.Input(shape=(None, 2), name='edge_index_input', dtype=\"int64\", ragged=True)\n    n_in_out = GatherNodes()([n, ei])\n    node_messages = Dense(10, activation='relu')(n_in_out)\n    node_updates = PoolingLocalMessages()([n, node_messages, ei])\n    n_node_updates = LazyConcatenate(axis=-1)([n, node_updates])\n    n_embedd = Dense(s**2)(n_node_updates)#s**2\n    #n_embedd = layers.Reshape((s,s,-1))(n_embedd)\n    g_embedd = PoolingNodes()(n_embedd)\n    #print(g_embedd.shape)\n    \n    inputs = keras.Input(shape=(s,s,16))#,name = 'The game map'\n    f = layers.Flatten()(inputs)   \n    h,w= s,s\n    f = layers.Dense(w*h,activation = \"sigmoid\")(f)\n    f = layers.Reshape((h,w,-1))(f)\n    combined = layers.Concatenate()([f, layers.Reshape((h,w,-1))(g_embedd)])\n    #cov_combined = layers.Conv2D(4, 2, activation='relu', data_format='channels_last')(combined)\n    #cov_combined = layers.Dense(1)(combined)\n    units = layers.Dense(6,activation = \"softmax\")(combined)#,name = \"Units_actions\"\n    cities = layers.Dense(2,activation = \"sigmoid\")(combined)#,name = \"Cities_actions\"\n    output = layers.Concatenate()([units,cities])\n    model = keras.Model(inputs = [n, ei, inputs], outputs = output)\n    #model = keras.Model(inputs = inputs, outputs = output)\n    \n    return model\n\n\n\ndef get_prediction_actions(y,player):\n    # move\n    option = np.argmax(y,axis = 2) \n    # c s n w e build_city & research & buid_worker  \n    actions = []\n    for i in player.units:\n#         print(option.shape,i.pos.y,i.pos.x)\n        d = \"csnwe#############\"[option[i.pos.y,i.pos.x]]\n        if option[i.pos.y,i.pos.x]<5:actions.append(i.move(d))\n        elif option[i.pos.y,i.pos.x]==5 and i.can_build(game_state.map):actions.append(i.build_city())\n    \n    for city in player.cities.values():\n        for city_tile in city.citytiles:\n            if option[city_tile.pos.y,city_tile.pos.x]==6:\n                action = city_tile.research()\n                actions.append(action)\n            if option[city_tile.pos.y,city_tile.pos.x]==7:\n                action = city_tile.build_worker()\n                actions.append(action)\n    return actions,option\n\ndef agent(observation, configuration):\n    global game_state,epsilon,model\n    \n    ### Do not edit ###\n    if observation[\"step\"] == 0:\n        game_state = Game()\n        game_state._initialize(observation[\"updates\"])\n        game_state._update(observation[\"updates\"][2:])\n        game_state.id = observation.player\n        print(\"Creating model..\")\n        model =get_model(game_state.map.width)\n        print(\"Load model weight..\")\n        try:\n            model.load_weights( str(p\/f'model_{game_state.map.width}.h5'),  by_name=True, skip_mismatch=True)\n        except Exception as e:\n            print('Error in model load')\n            raise(e)\n#         model = tf.keras.models.load_model('model.h5')\n        print(\"Done crating mdoel\")\n        \n        \n    else:\n        game_state._update(observation[\"updates\"])\n    \n\n    ### AI Code goes down here! ### \n    player = game_state.players[observation.player]\n    opponent = game_state.players[(observation.player + 1) % 2]\n    width, height = game_state.map.width, game_state.map.height\n\n    # Get Prediction of actions\n    x = get_inputs(game_state)\n    y = model.predict(x)[0]\n    actions,_ = get_prediction_actions(y,player)\n    return actions\n!git clone https:\/\/github.com\/aimat-lab\/gcnn_keras\n!mkdir kgcnn\n!cp -r gcnn_keras\/kgcnn\/* .\/kgcnn\n!rm -r gcnn_keras\n!rm submission.tar.gz\nimport os\nos.environ['KAGGLE_USERNAME'] = 'alphonus'\nos.environ['KAGGLE_KEY'] = 'secret'\n!rm kaggle.json\n!tar  --exclude=\"*.png\" -czf submission.tar.gz *\n!kaggle competitions submit -c lux-ai-2021 -f submission.tar.gz -m \"Graph based RL\"\n# from kaggle_environments import make\n# import json\n# # run another match but with our empty agent\n#env = make(\"lux_ai_2021\",debug=True, configuration={\"seed\": 56221, \"loglevel\": 2})\n\n#steps = env.run([\".\/agent.py\", \".\/agent.py\"])\nenv.render(mode=\"ipython\", width=600, height=800)\n\"\"\"\n*Closing thoughts*\nAnyone reading this later on. This approach is illy souted for this challenge, as the resulting model sizes breach the 100MB size limit. Yet it was fun to think of this challenge in other ways.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '35c98b679d25f0'}"}
{"id":"124581","text":"\"\"\"\n#\u00a0Predicting 3D World position from Car bounding boxes.\n\nThis kernel aims to find a model which, given a 2D bounding box (defined as the center and its height\/width), can predict the position of a car in the real world (distance, height and lateral displacement).\n\nHere I test several baseline models and, later, fine tune the best one.\n\nThe dataset I'm going to be using is a derived one (built by me): https:\/\/www.kaggle.com\/alvaroibrain\/carworldpositions, which contains the features mentioned above. The dataset has been made from the Baidu one using YOLO for finding the bounding boxes and then, finding the matches between the BBoxes and the real world points.\n\nHope this approach can serve you to improve your predictions.\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport joblib\n\nimport sklearn\nfrom sklearn import preprocessing\nfrom sklearn import model_selection\nfrom sklearn import tree\nfrom sklearn import ensemble\nfrom sklearn import neighbors\n\nfrom sklearn import multioutput\nfrom sklearn import metrics\nfrom sklearn import svm\nfrom sklearn.gaussian_process.kernels import DotProduct, WhiteKernel, Matern, RBF\n\nfrom matplotlib import pyplot as plt\n\nsns.set(style=\"dark\")\nIMAGE_WIDTH = 3384\nIMAGE_HEIGHT = 2710\ndef print_metrics(test_set, predictions):\n    print(\"Test metrics\")\n    print(\"-\"*20)\n    \n    wx_error = sklearn.metrics.mean_absolute_error(test_set['wx'], predictions[:, 0])\n    wy_error = sklearn.metrics.mean_absolute_error(test_set['wy'], predictions[:, 1])\n    wz_error = sklearn.metrics.mean_absolute_error(test_set['wz'], predictions[:, 2])\n    \n    wx_r2 = sklearn.metrics.r2_score(test_set['wx'], predictions[:, 0])\n    wy_r2 = sklearn.metrics.r2_score(test_set['wy'], predictions[:, 1])\n    wz_r2 = sklearn.metrics.r2_score(test_set['wz'], predictions[:, 2])\n\n    print(f\"- WX error {wx_error}\")\n    print(f\"- WY error {wy_error}\")\n    print(f\"- WZ error {wz_error}\")\n\n    print(\"\")\n    print(f\"- WX R2 score {wx_r2}\")\n    print(f\"- WY R2 score {wy_r2}\")\n    print(f\"- WZ R2 score {wz_r2}\")\n    \n    return wx_error, wy_error, wz_error, wx_r2, wy_r2, wz_r2\n          \ndef plot_predictions(test_set, predictions, fig, ax):\n          \n    line_kws = {'color':'black', 'linestyle':'--', 'linewidth':2}\n    scatter_kws = {'s':1}\n    \n    ax[0].set_title('World X')\n    ax[1].set_title('World Y')\n    ax[2].set_title('World Z')\n\n    ax[0] = sns.regplot(test_set['wx'], predictions[:, 0], ax=ax[0], line_kws=line_kws, scatter_kws=scatter_kws)\n    ax[1] = sns.regplot(test_set['wy'], predictions[:, 1], ax=ax[1], line_kws=line_kws, scatter_kws=scatter_kws)\n    ax[2] = sns.regplot(test_set['wz'], predictions[:, 2], ax=ax[2], line_kws=line_kws, scatter_kws=scatter_kws)\ndataf = pd.read_csv('..\/input\/carworldpositions\/data_points.csv').drop('Unnamed: 0', axis=1)\ndataf.describe()\n# Remove outliers\ndataf = dataf[dataf['wx'] < 100]\ndataf = dataf[dataf['wy'] < 100]\ndataf = dataf[dataf['wz'] < 100]\nsns.pairplot(dataf)\n# Normalization (and centering) for some of the algorithms (knn, svm or nn)\ndataf['Cx'] \/= IMAGE_WIDTH\ndataf['Cy'] \/= IMAGE_HEIGHT\n\nscaler = sklearn.preprocessing.StandardScaler()\ndataf[['wx', 'wy', 'wz']] = scaler.fit_transform(dataf[['wx', 'wy', 'wz']])\n# Train test split\nmask = np.random.random(len(dataf)) > 0.7\n\ndtrain = dataf[mask]\ndtest = dataf[~mask]\n\n# Predictor and target variable names\npredictors = ['Cx', 'Cy', 'bh', 'bw']\ntargets = ['wx', 'wy', 'wz']\n\"\"\"\n#\u00a0Model selection\n\nWe will test baseline models to choose one to do the fine-tuning\n\"\"\"\n# DataFrame to store the results\ntest_metrics = pd.DataFrame(columns=['Method', 'WX_Error', 'WY_Error', 'WZ_Error', 'WX_r2', 'WY_r2', 'WZ_r2'])\n\"\"\"\n## Random Forest\n\"\"\"\nrf = sklearn.ensemble.RandomForestRegressor(n_estimators=200)\nrf = rf.fit(X=dtrain[predictors], y=dtrain[targets])\npreds = rf.predict(dtest[predictors])\nresults = print_metrics(dtest, preds)\ntest_metrics = test_metrics.append(pd.Series(('RF', *results), index=test_metrics.columns), ignore_index=True)\nfig, ax = plt.subplots(3, figsize=(15,16))\nplot_predictions(dtest, preds, fig, ax)\n\"\"\"\n##\u00a0Boosting\n\"\"\"\nbt = sklearn.ensemble.GradientBoostingRegressor()\n\nmor = sklearn.multioutput.MultiOutputRegressor(bt)\nmor = mor.fit(X=dtrain[predictors], y=dtrain[targets])\npreds = mor.predict(dtest[predictors])\nresults = print_metrics(dtest, preds)\ntest_metrics = test_metrics.append(pd.Series(('BoostingT', *results), index=test_metrics.columns), \n                                   ignore_index=True)\nfig, ax = plt.subplots(3, figsize=(15,16))\nplot_predictions(dtest, preds, fig, ax)\n\"\"\"\n##\u00a0KNN\n\"\"\"\nknn = neighbors.KNeighborsRegressor(10)\nknn = knn.fit(X=dtrain[predictors], y=dtrain[targets])\npreds = knn.predict(dtest[predictors])\nresults = print_metrics(dtest, preds)\ntest_metrics = test_metrics.append(pd.Series(('KNN', *results), index=test_metrics.columns), \n                                   ignore_index=True)\nfig, ax = plt.subplots(3, figsize=(15,16))\nplot_predictions(dtest, preds, fig, ax)\n\"\"\"\n## SVM\n\"\"\"\nsvr = sklearn.svm.SVR(gamma='scale')\n\nmor = sklearn.multioutput.MultiOutputRegressor(svr)\nmor = mor.fit(X=dtrain[predictors], y=dtrain[targets])\npreds = mor.predict(dtest[predictors])\nresults = print_metrics(dtest, preds)\ntest_metrics = test_metrics.append(pd.Series(('SVM', *results), index=test_metrics.columns), \n                                   ignore_index=True)\nfig, ax = plt.subplots(3, figsize=(15,16))\nplot_predictions(dtest, preds, fig, ax)\n\"\"\"\n# Neural net\n\"\"\"\nfrom tensorflow import keras as k\ninp = k.layers.Input(shape=(len(predictors),))\nh = k.layers.Dense(300, activation='linear')(inp)\nh = k.layers.Dropout(.3)(h)\nh = k.layers.Dense(500, activation='relu')(h)\nh = k.layers.Dropout(.1)(h)\nh = k.layers.Dense(300, activation='linear')(h)\nh = k.layers.Dense(200, activation='linear')(h)\nh = k.layers.Dense(200, activation='selu')(h)\nout = k.layers.Dense(3, activation='linear')(h)\n\nmodel = k.models.Model(inputs=inp, outputs=out)\n\nmodel.compile(k.optimizers.Adam(), loss='mse')\nh = model.fit(x=dtrain[predictors].values, y=dtrain[targets].values, \n              validation_split=.3, epochs=10, batch_size=16)\npreds = model.predict(dtest[predictors].values)\nresults = print_metrics(dtest, preds)\ntest_metrics = test_metrics.append(pd.Series(('NN', *results), index=test_metrics.columns), \n                                   ignore_index=True)\nfig, ax = plt.subplots(3, figsize=(15,16))\nplot_predictions(dtest, preds, fig, ax)\n\"\"\"\n# Results\n\"\"\"\ntest_metrics\n\"\"\"\nRandom Forest seems to be the baseline winner. I will finetune it.\n\nThe X position (lateral displacement is well predicted), however, Y and Z have a little more variance. This needs to be improved.\n\"\"\"\n# Reload dataset without normalization\ndataf = pd.read_csv('..\/input\/carworldpositions\/data_points.csv').drop('Unnamed: 0', axis=1)\n# Remove outliers\ndataf = dataf[dataf['wx'] < 100]\ndataf = dataf[dataf['wy'] < 100]\ndataf = dataf[dataf['wz'] < 100]\n\ndtrain = dataf[mask]\ndtest = dataf[~mask]\nrf = sklearn.ensemble.RandomForestRegressor()\nparam_grid = {\n    'n_estimators':[200, 400, 500, 800, 1000, 2000]\n}\n\ngs = sklearn.model_selection.GridSearchCV(rf, n_jobs=4, param_grid=param_grid)\ngs = gs.fit(dtrain[predictors], dtrain[targets])\npd.concat([pd.DataFrame(gs.cv_results_[\"params\"]),\n           pd.DataFrame(gs.cv_results_[\"mean_test_score\"], columns=[\"MSE\"])],axis=1)\n\n\"\"\"\n200 trees seems OK\n\"\"\"\nrf = sklearn.ensemble.RandomForestRegressor(n_estimators=200)\nrf = rf.fit(X=dtrain[predictors], y=dtrain[targets])\npreds = rf.predict(dtest[predictors])\nresults = print_metrics(dtest, preds)\n# Save the model if you need it\n# joblib.dump(rf, 'pos_predictor.joblib')","meta":"{'source': 'AI4Code', 'id': 'e523ab09bb1bb7'}"}
{"id":"13563","text":"\"\"\"\nKaggle kernels can be a bit of a pain to extract data from sometimes since you can't get the output until you commit the notebook, and if it got some neural network training in, it might take a _verrrrrrry_ long time... and in the meantime, if you leave your notebook for a few hours and it restarts, you lost all your hard work, so I've figure out how to transfer intermediate results to gcs:\n\"\"\"\n\"\"\"\n1. Install google cloud storage python sdk\n\"\"\"\n !pip install --upgrade google-cloud-storage\n\"\"\"\n2.setup your auth keys as per https:\/\/cloud.google.com\/storage\/docs\/reference\/libraries#client-libraries-install-python, download the authentication json file to your computer, then join all the split lines so it's one long string (the `cmd+J` shortcut if you are using atom is a useful option)\n\"\"\"\n\"\"\"\nsave your gcs json into a json file on the kernel env by dumping it in through the jupyter widget text box as per below (the textbox destroys itself after running so you don't need to worry about having keys shown if you share your kernel)\n\"\"\"\nfrom ipywidgets import interact, widgets\nfrom IPython.display import display, clear_output\nimport json\nimport os\ntext = widgets.Text(\n    value='my gcs.json auth',\n    placeholder='Paste your gcs json auth file here!',\n    description='Paste your gcs json auth file:',\n    disabled=False\n)\ndisplay(text)\n\ndef callback(text):\n    # replace by something useful\n    text = text.value.replace('\\n', '\\\\n')\n    \n    try:\n        json.loads(text)\n        with open (\"gcs.json\", \"w\") as f:\n            f.write(text) \n        \n    except Exception as e:\n        print(e)\n    clear_output()\n    \n\ntext.on_submit(callback)\n\"\"\"\n3.Create your bucket for storing stuff\n\"\"\"\nfrom google.cloud import storage\n\n# Instantiates a client\nif os.path.isfile('gcs.json') \n    storage_client = storage.Client.from_service_account_json(\n            'gcs.json')\n# -- uncomment the below to create a new bucket--\n# The name for the new bucket\n# bucket_name = 'my-bucket-name'\n\n# # Creates the new bucket\n# bucket = storage_client.create_bucket(bucket_name)\n\n# print('Bucket {} created.'.format(bucket.name))\n\"\"\"\n4.use the below to upload, e.g. \n`upload_blob(storage_client, \"my-bucket\", \"models\/stage-2.pth\", \"stage-2.pth\")`\n\"\"\"\n\ndef upload_blob(storage_client, bucket_name, source_file_name, destination_blob_name):\n    \"\"\"Uploads a file to the bucket.\"\"\"\n    bucket = storage_client.get_bucket(bucket_name)\n    blob = bucket.blob(destination_blob_name)\n\n    blob.upload_from_filename(source_file_name)\n\n    print('File {} uploaded to {}.'.format(\n        source_file_name,\n        destination_blob_name))","meta":"{'source': 'AI4Code', 'id': '18d2d5a0fea6c8'}"}
{"id":"45136","text":"\"\"\"\n![](https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRISoH2D1d3so8aIWzbv3MNtx1c_s7oMkiSmA&usqp=CAU)sitn.hms.harvard.edu\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nimport plotly.offline as py\nimport plotly.express as px\nfrom plotly.offline import iplot\n\n\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\n\"\"\"\n#Graphics by Wei Wu\n![](https:\/\/i1.wp.com\/sitn.hms.harvard.edu\/wp-content\/uploads\/2020\/04\/combined_comic6-01.jpg?resize=768%2C1830)http:\/\/sitn.hms.harvard.edu\/flash\/2020\/immune-response-viral-infection\/\n\"\"\"\ndf = pd.read_csv('..\/input\/ai4all-project\/results\/deconvolution\/CIBERSORTx_Results_Krasnow_facs_droplet.csv', encoding='ISO-8859-2')\ndf.head()\n\n\"\"\"\n#Codes from Vansh Jatana https:\/\/www.kaggle.com\/vanshjatana\/covid-19-in-australia\/notebook\n\"\"\"\n\ndf_grp = df.groupby([\"viral_load\",\"czb_id\"])[[\"B cell\",\"Basal\",\"Basophil\/Mast\", \"Ciliated\", \"Dendritic\", \"Goblet\", \"Ionocyte\", \"Monocytes\/macrophages\", \"Neutrophil\", \"T cell\"]].sum().reset_index()\ndf_grp.head()\ndf_grp = df_grp.rename(columns={\"B cell\":\"Bcell\",\"T cell\":\"Tcell\", \"Monocytes\/macrophages\": \"macrophages\"})\nplt.figure(figsize=(15, 5))\nplt.title('czb_id')\ndf_grp.czb_id.value_counts().plot.bar();\ndf_grp_plot = df_grp.tail(80)\ndf_grp_r = df_grp.groupby(\"czb_id\")[[\"Bcell\",\"Tcell\",\"macrophages\", \"Dendritic\", \"Ciliated\", \"Neutrophil\"]].sum().reset_index()\ndf_grp_r.head()\ndf_grp_rl20 = df_grp_r.tail(20)\nfig = px.bar(df_grp_rl20[['czb_id', 'Bcell']].sort_values('Bcell', ascending=False), \n             y=\"Bcell\", x=\"czb_id\", color='czb_id', \n             log_y=True, template='ggplot2', title='B Cells vs CZB ID')\nfig.show()\ndf_grp_rl20 = df_grp_rl20.sort_values(by=['Bcell'],ascending = False)\nplt.figure(figsize=(40,15))\nplt.bar(df_grp_rl20.czb_id, df_grp_rl20.Bcell,label=\"Bcell\")\nplt.bar(df_grp_rl20.czb_id, df_grp_rl20.Tcell,label=\"Tcell\")\nplt.bar(df_grp_rl20.czb_id, df_grp_rl20.macrophages,label=\"macrophages\")\nplt.xlabel('viral_load')\nplt.ylabel(\"Count\")\nplt.xticks(fontsize=13)\nplt.yticks(fontsize=15)\n\nplt.legend(frameon=True, fontsize=12)\nplt.title('Immune Response',fontsize=30)\nplt.show()\n\nf, ax = plt.subplots(figsize=(40,15))\nax=sns.scatterplot(x=\"czb_id\", y=\"Bcell\", data=df_grp_rl20,\n             color=\"black\",label = \"Bcell\")\nax=sns.scatterplot(x=\"czb_id\", y=\"Tcell\", data=df_grp_rl20,\n             color=\"red\",label = \"Tcell\")\nax=sns.scatterplot(x=\"czb_id\", y=\"macrophages\", data=df_grp_rl20,\n             color=\"blue\",label = \"macrophages\")\nplt.plot(df_grp_rl20.czb_id,df_grp_rl20.Bcell,zorder=1,color=\"black\")\nplt.plot(df_grp_rl20.czb_id,df_grp_rl20.Tcell,zorder=1,color=\"red\")\nplt.plot(df_grp_rl20.czb_id,df_grp_rl20.macrophages,zorder=1,color=\"blue\")\nplt.xticks(fontsize=13)\nplt.yticks(fontsize=15)\nplt.legend(frameon=True, fontsize=12)\ndf_grp_d = df_grp.groupby(\"viral_load\")[[\"Bcell\",\"Tcell\",\"macrophages\"]].sum().reset_index()\ndf_grp_dl20 = df_grp_d.tail(20)\ndf_grp_d['Bcell_new'] = df_grp_d['Bcell']-df_grp_d['Bcell'].shift(1)\ndf_grp_d['Tcell_new'] = df_grp_d['Tcell']-df_grp_d['Tcell'].shift(1)\ndf_grp_d['macrophages_new'] = df_grp_d['macrophages']-df_grp_d['macrophages'].shift(1)\nnew = df_grp_d\nnew = new.tail(14)\nf, ax = plt.subplots(figsize=(23,10))\nax=sns.scatterplot(x=\"viral_load\", y=\"Bcell\", data=df_grp_dl20,\n             color=\"black\",label = \"B cells\")\nax=sns.scatterplot(x=\"viral_load\", y=\"Tcell\", data=df_grp_dl20,\n             color=\"red\",label = \"T cells\")\nax=sns.scatterplot(x=\"viral_load\", y=\"macrophages\", data=df_grp_dl20,\n             color=\"blue\",label = \"Macrophages\")\nplt.plot(df_grp_dl20.viral_load,df_grp_dl20.Bcell,zorder=1,color=\"black\")\nplt.plot(df_grp_dl20.viral_load,df_grp_dl20.Tcell,zorder=1,color=\"red\")\nplt.plot(df_grp_dl20.viral_load,df_grp_dl20.macrophages,zorder=1,color=\"blue\")\n\"\"\"\nDas War\u00b4s, Kaggle Notebook Runner: Mar\u00edlia Prata   @mpwolke \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5321adae5e8d96'}"}
{"id":"79909","text":"import librosa \nimport numpy as np\nfrom scipy.io import wavfile as wav\nfname = '..\/input\/urbansound8k\/fold2\/100652-3-0-3.wav'\nlibrosa_audio , librosa_sample_rate = librosa.load(fname)\nscipy_sample_rate , scipy_audio = wav.read(fname)\nprint('Librosa Sample Rate',librosa_sample_rate)\nprint('Scipy sample Rate',scipy_sample_rate)\nlibrosa_audio\nscipy_audio\n\"\"\"\nLibrosa has also normalised the audio data\n\"\"\"\n\"\"\"\nLibrosa also converts Audio into Mono Channel\n\"\"\"\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(12,4))\nplt.plot(scipy_audio)\n\"\"\"\nDual Stereo Scipy Audio\n\"\"\"\nplt.figure(figsize=(12,4))\nplt.plot(librosa_audio)\n\"\"\"\nSingle Channel Librosa Audio\n\"\"\"\n\"\"\"\n# Feature Extraction\n\"\"\"\n\"\"\"\nwe will extract Mel-Frequency Cepstral Coefficients (MFCC) from the the audio samples.\n\nThe MFCC summarises the frequency distribution across the window size, so it is possible to analyse both the frequency and time characteristics of the sound. These audio representations will allow us to identify features for classification\n\"\"\"\nmfcc = librosa.feature.mfcc(y=librosa_audio,sr=librosa_sample_rate,n_mfcc=40)\nmfcc\nmfcc.shape\ndef extract_features(file_name):\n    try:\n        audio,sample_rate = librosa.load(file_name,res_type='kaiser_fast')\n        mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)\n        mfccsscaled = np.mean(mfccs.T,axis=0)\n    \n    except Exception as e:\n        print(\"Error encountered while parsing file: \", file)\n        return None \n     \n    return mfccsscaled\n        \n    \n# Load various imports \nimport pandas as pd\nimport os\nimport librosa\n\n# Set the path to the full UrbanSound dataset \n#fulldatasetpath = '..\/input\/urbansound8k'\n\n#metadata = pd.read_csv('..\/input\/urbansound8k\/UrbanSound8K.csv')\n\n#features = []\n\n# Iterate through each sound file and extract the features \n#for index, row in metadata.iterrows():\n    \n    #file_name = os.path.join(os.path.abspath(fulldatasetpath),'fold'+str(row[\"fold\"])+'\/',str(row[\"slice_file_name\"]))\n    \n    #class_label = row[\"class\"]\n    #data = extract_features(file_name)\n    \n    #features.append([data, class_label])\n\n# Convert into a Panda dataframe \n#featuresdf = pd.DataFrame(features, columns=['feature','class_label'])\n\n#print('Finished feature extraction from ', len(featuresdf), ' files')\nfeaturesdf\n#featuresdf.to_csv('urban_sound_data.csv')","meta":"{'source': 'AI4Code', 'id': '92b8790b34bd72'}"}
{"id":"17257","text":"\"\"\"\n# Use MNIST fashion dataset. Construct an auto encoder model that can compress the given images of MNIST dataset.\n\"\"\"\n\"\"\"\n## Import TensorFlow and other libraries\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import layers, losses\nfrom tensorflow.keras.datasets import fashion_mnist\nfrom tensorflow.keras.models import Model\n\"\"\"\n## Load the dataset\nTo start, you will train the basic autoencoder using the Fashon MNIST dataset. Each image in this dataset is 28x28 pixels. \n\"\"\"\n(x_train, _), (x_test, _) = fashion_mnist.load_data()\n\nx_train = x_train.astype('float32') \/ 255.\nx_test = x_test.astype('float32') \/ 255.\n\nprint (x_train.shape)\nprint (x_test.shape)\nlatent_dim = 64 \n\nclass Autoencoder(Model):\n  def __init__(self, latent_dim):\n    super(Autoencoder, self).__init__()\n    self.latent_dim = latent_dim   \n    self.encoder = tf.keras.Sequential([\n      layers.Flatten(),\n      layers.Dense(latent_dim, activation='relu'),\n    ])\n    self.decoder = tf.keras.Sequential([\n      layers.Dense(784, activation='sigmoid'),\n      layers.Reshape((28, 28))\n    ])\n\n  def call(self, x):\n    encoded = self.encoder(x)\n    decoded = self.decoder(encoded)\n    return decoded\n  \nautoencoder = Autoencoder(latent_dim) \nautoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError())\n\"\"\"\nTrain the model using `x_train` as both the input and the target. The `encoder` will learn to compress the dataset from 784 dimensions to the latent space, and the `decoder` will learn to reconstruct the original images.\n.\n\"\"\"\nautoencoder.fit(x_train, x_train,\n                epochs=10,\n                shuffle=True,\n                validation_data=(x_test, x_test))\n\"\"\"\nNow that the model is trained, let's test it by encoding and decoding images from the test set.\n\"\"\"\nencoded_imgs = autoencoder.encoder(x_test).numpy()\ndecoded_imgs = autoencoder.decoder(encoded_imgs).numpy()\nn = 10\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n  # display original\n  ax = plt.subplot(2, n, i + 1)\n  plt.imshow(x_test[i])\n  plt.title(\"original\")\n  plt.gray()\n  ax.get_xaxis().set_visible(False)\n  ax.get_yaxis().set_visible(False)\n\n  # display reconstruction\n  ax = plt.subplot(2, n, i + 1 + n)\n  plt.imshow(decoded_imgs[i])\n  plt.title(\"reconstructed\")\n  plt.gray()\n  ax.get_xaxis().set_visible(False)\n  ax.get_yaxis().set_visible(False)\nplt.show()\n(x_train, _), (x_test, _) = fashion_mnist.load_data()\nx_train = x_train.astype('float32') \/ 255.\nx_test = x_test.astype('float32') \/ 255.\n\nx_train = x_train[..., tf.newaxis]\nx_test = x_test[..., tf.newaxis]\n\nprint(x_train.shape)\n\"\"\"\nAdding random noise to the images\n\"\"\"\nnoise_factor = 0.2\nx_train_noisy = x_train + noise_factor * tf.random.normal(shape=x_train.shape) \nx_test_noisy = x_test + noise_factor * tf.random.normal(shape=x_test.shape) \n\nx_train_noisy = tf.clip_by_value(x_train_noisy, clip_value_min=0., clip_value_max=1.)\nx_test_noisy = tf.clip_by_value(x_test_noisy, clip_value_min=0., clip_value_max=1.)\n\"\"\"\nPlot the noisy images.\n\n\"\"\"\nn = 10\nplt.figure(figsize=(20, 2))\nfor i in range(n):\n    ax = plt.subplot(1, n, i + 1)\n    plt.title(\"original + noise\")\n    plt.imshow(tf.squeeze(x_test_noisy[i]))\n    plt.gray()\nplt.show()\n\"\"\"\n### Define a convolutional autoencoder\n\"\"\"\nclass Denoise(Model):\n  def __init__(self):\n    super(Denoise, self).__init__()\n    self.encoder = tf.keras.Sequential([\n      layers.Input(shape=(28, 28, 1)),\n      layers.Conv2D(16, (3, 3), activation='relu', padding='same', strides=2),\n      layers.Conv2D(8, (3, 3), activation='relu', padding='same', strides=2)])\n\n    self.decoder = tf.keras.Sequential([\n      layers.Conv2DTranspose(8, kernel_size=3, strides=2, activation='relu', padding='same'),\n      layers.Conv2DTranspose(16, kernel_size=3, strides=2, activation='relu', padding='same'),\n      layers.Conv2D(1, kernel_size=(3, 3), activation='sigmoid', padding='same')])\n\n  def call(self, x):\n    encoded = self.encoder(x)\n    decoded = self.decoder(encoded)\n    return decoded\n\nautoencoder = Denoise()\nautoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError())\nautoencoder.fit(x_train_noisy, x_train,\n                epochs=10,\n                shuffle=True,\n                validation_data=(x_test_noisy, x_test))\n\"\"\"\nLet's take a look at a summary of the encoder. Notice how the images are downsampled from 28x28 to 7x7.\n\"\"\"\nautoencoder.encoder.summary()\n\"\"\"\nThe decoder upsamples the images back from 7x7 to 28x28.\n\"\"\"\nautoencoder.decoder.summary()\n\"\"\"\nPlotting both the noisy images and the denoised images produced by the autoencoder.\n\"\"\"\nencoded_imgs = autoencoder.encoder(x_test).numpy()\ndecoded_imgs = autoencoder.decoder(encoded_imgs).numpy()\nn = 10\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n\n    # display original + noise\n    ax = plt.subplot(2, n, i + 1)\n    plt.title(\"original + noise\")\n    plt.imshow(tf.squeeze(x_test_noisy[i]))\n    plt.gray()\n    ax.get_xaxis().set_visible(False)\n    ax.get_yaxis().set_visible(False)\n\n    # display reconstruction\n    bx = plt.subplot(2, n, i + n + 1)\n    plt.title(\"reconstructed\")\n    plt.imshow(tf.squeeze(decoded_imgs[i]))\n    plt.gray()\n    bx.get_xaxis().set_visible(False)\n    bx.get_yaxis().set_visible(False)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '1f874dda67deaa'}"}
{"id":"121814","text":"!pip install xgboost\nimport pandas as pd\nimport xgboost as xgb\ndataset = pd.read_csv('..\/input\/titanic\/train.csv')\n\nnull_columns=dataset.columns[dataset.isnull().any()]\ndataset[null_columns].isnull().sum()\n#drop unimportant features\ndf_dataset = dataset.drop('Cabin', axis=1).drop('Name', axis=1).drop('Ticket', axis=1)\ndf_dataset['Age'].fillna((df_dataset['Age'].mean()), inplace=True)\nX_dataset = df_dataset.drop('Survived', axis=1).drop('PassengerId', axis=1)\ny_dataset = df_dataset[['Survived']]\n#gets test columns based on train featured columns\ncolumns = X_dataset.columns\nvalidation=pd.read_csv('..\/input\/titanic\/test.csv')\ndf_validation = validation[columns]\ndf_validation.head()\ndf_validation['Age'].fillna((df_dataset['Age'].mean()), inplace=True)\nX_dataset =  pd.get_dummies(X_dataset)\n\nX_validation= df_validation\nX_validation =  pd.get_dummies(X_validation)\nfrom sklearn import preprocessing\n#min-Max Scaler\nmin_max_scaler = preprocessing.MinMaxScaler()\n\n#transform main set\nX_dataset_values = X_dataset.values \nX_dataset_values_scaled = min_max_scaler.fit_transform(X_dataset_values)\nX_dataset_values_scaled = pd.DataFrame(X_dataset_values_scaled)\n\n#transform validation set\nX_validation_values = X_validation.values\nX_validation_values_scaled = min_max_scaler.transform(X_validation_values)\nX_validation_values_scaled = pd.DataFrame(X_validation_values_scaled)\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, RandomizedSearchCV\n\n#X_train, X_test, y_train, y_test = train_test_split(X_dataset_values_scaled, y_dataset, test_size=0.1)\n\n\"\"\"\n## Model\n\"\"\"\n# A parameter grid for XGBoost\nparams = {\n        'min_child_weight': [1, 5, 10],\n        'gamma': [0.5, 1, 1.5, 2, 5],\n        'subsample': [0.6, 0.8, 1.0],\n        'colsample_bytree': [0.6, 0.8, 1.0],\n        'max_depth': [3, 4, 5]\n        }\nxgb_model = xgb.XGBClassifier(learning_rate=0.02, n_estimators=600, objective='binary:logistic',\n                    silent=True, nthread=1)\nfolds = 3\nparam_comb = 5\n\nX = X_dataset_values_scaled\nY = y_dataset\n\nskf = StratifiedKFold(n_splits=folds, shuffle = True)\n\nrandom_search = RandomizedSearchCV(xgb_model, param_distributions=params, n_iter=param_comb, scoring='roc_auc', n_jobs=4, cv=skf.split(X,Y), verbose=3)\nrandom_search.fit(X, Y)\nprint('\\n Best estimator:')\nprint(random_search.best_estimator_)\nxgb_model_final = random_search.best_estimator_\n#xgb_model.fit(X_train, y_train)\n#TEST_SPLIT_CASE\n#from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_auc_score\n\n#y_hat = xgb_model.predict(X_test)\n#print(\"Roc AUC: \", roc_auc_score(y_test, xgb_model.predict_proba(X_test)[:,1],\n#              average='macro'))\n#print(confusion_matrix(y_test,y_hat))\n#print(classification_report(y_test,y_hat))\ny_hat_sub = xgb_model_final.predict(X_validation_values_scaled)\ny_hat_sub = pd.DataFrame(y_hat_sub)\ny_hat_sub.shape\nvalidation['Survived'] = y_hat_sub\nvalidation[['PassengerId','Survived']].to_csv('submission_final.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'e00918ecc026e0'}"}
{"id":"118607","text":"import os\nimport random\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models,Sequential\nimport cv2, numpy as np\nimport os\n\"\"\"\n## We are using pretrained weights of inceptionV3\n### [from->https:\/\/www.kaggle.com\/ekaterinadranitsyna\/keras-applications-models](https:\/\/www.kaggle.com\/ekaterinadranitsyna\/keras-applications-models)\nadding it to our dataset,\n\"\"\"\ntrain_data_csv = '..\/input\/petfinder-pawpularity-score\/train.csv'\ntest_data_csv  = '..\/input\/petfinder-pawpularity-score\/test.csv'\ntrain_folder = '..\/input\/petfinder-pawpularity-score\/train'\ntest_folder  = '..\/input\/petfinder-pawpularity-score\/test'\n\"\"\"\n## Hyperparameter for our newtowk\n\"\"\"\ny = 'Pawpularity'\nvalidation_size = 0.25\nautotune = tf.data.experimental.AUTOTUNE\nimg_size = 299\nbatch_size = 8\ndropout = 0.2\nlr = 1e-3\ndecay_steps = 100\ndecay_rate = 0.96\nepochs = 30\ndef id_to_path(img_id,dir):\n    return os.path.join(dir, f'{img_id}.jpg')\ndef get_image(path):\n    image = tf.image.decode_jpeg(tf.io.read_file(path), channels=3)\n    image = tf.cast(tf.image.resize_with_pad(image, img_size, img_size), dtype=tf.float32)\n    return tf.keras.applications.inception_v3.preprocess_input(image)\ndef process_dataset(path, label):\n    return get_image(path), label\ndef get_dataset(x, y=None):\n    if y is not None:\n        ds = tf.data.Dataset.from_tensor_slices((x, y))\n        return ds.map(process_dataset, num_parallel_calls=autotune) \\\n            .batch(batch_size).prefetch(buffer_size=autotune)\n    else:\n        ds = tf.data.Dataset.from_tensor_slices(x)\n        return ds.map(get_image, num_parallel_calls=autotune) \\\n            .batch(batch_size).prefetch(buffer_size=autotune)\ndata_train = pd.read_csv(train_data_csv)\ndata_train.head()\ndata_test = pd.read_csv(test_data_csv)\ndata_test.head()\ndata_train['path'] = data_train['Id'].apply(lambda x: id_to_path(x, train_folder))\ndata_test['path'] = data_test['Id'].apply(lambda x: id_to_path(x, test_folder))\n\ntrain_subset, valid_subset = train_test_split(\n    data_train[['path', y]],\n    test_size=validation_size, shuffle=True, random_state=5\n)\ndata_train.head()\ndata_train.path\ntrain_data = get_dataset(x=train_subset['path'], y=train_subset[y]\/100.).shuffle(1000)\nvalid_data = get_dataset(x=valid_subset['path'], y=valid_subset[y]\/100.).shuffle(1000)\ntest_data = get_dataset(x=data_test['path'])\nmodel = tf.keras.models.load_model('..\/input\/keras-applications-models\/InceptionV3.h5')\n#model.trainable = False\nlen(model.layers)\nfor layer in model.layers[300:]:\n    layer.trainable = True\nmodel= tf.keras.models.Sequential(\n    [\n        tf.keras.layers.Input(shape=(img_size, img_size, 3)),\n        tf.keras.layers.experimental.preprocessing.RandomFlip(mode=\"horizontal_and_vertical\"),\n        model,\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dropout(dropout, name='top_dropout'),\n        tf.keras.layers.Dense(32, activation='elu'),\n        tf.keras.layers.Dense(1)\n    ]\n)\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate=lr,\n    decay_steps=decay_steps, decay_rate=decay_rate,staircase=True)\n\nlr =tf.keras.callbacks.ReduceLROnPlateau(monitor=\"val_loss\", factor=0.5, patience=5, verbose=90)\nearly_stop = tf.keras.callbacks.EarlyStopping(\n    monitor='val_loss', patience=5, restore_best_weights=True)\nfrom tensorflow.keras import backend as K\ndef rmse(y_true, y_pred):\n    return K.sqrt(K.mean(K.square(y_true*100 - y_pred*100)))\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n                    loss=rmse,\n                    metrics=[rmse])\nhistory=model.fit(train_data,validation_data=valid_data, epochs=epochs,verbose=1,callbacks=[early_stop,lr],use_multiprocessing=True, workers=-1)\ndata_test[y] = model.predict(test_data,use_multiprocessing=True, workers=os.cpu_count())*100\ndata_test[['Id', y]].to_csv('submission.csv', index=False)\ndata_test[['Id', y]].head()","meta":"{'source': 'AI4Code', 'id': 'da324786c7618b'}"}
{"id":"124449","text":"\"\"\"\n# Prevendo o LTV de clientes do Varejo\n\nO LTV - \u201clifetime value\u201d ou \u201cvalor vital\u00edcio\u201d \u00e9 uma m\u00e9trica estat\u00edstica que estima o lucro l\u00edquido da vida de um cliente dentro da empresa. \u00c9 comum termos clientes mais valiosos que outros, estes se d\u00e3o pela frequ\u00eancia  que compram ou pela grande receita que geram, e \u00e9 importante investirmos mais naqueles que geram um maior valor para a empresa.\n\n\nEste projeto tem como objetivo identificar padr\u00f5es de comportamento dos clientes do Varejo a fim de prever o LTV do cliente para a empresa. Mais especificamente, foi dado um dataset refer\u00eante \u00e0 01\/2020 at\u00e9 02\/2021 e devemos prever o LTV de cada cliente do dia 25\/02\/2021 at\u00e9 24\/05\/2021. \n\n### O Dataset\nFoi disponibilizado um Dataset que cont\u00e9m as seguintes informa\u00e7\u00f5es:\n\n- ID_VENDA - Id \u00fanico para cada registro\n- DT_VENDA - Data da venda\n- LOJA - Id \u00fanico da loja em que a venda foi realizada\n- QTD_SKU - Quantidade de produtos vendidos\n- VALOR - Valor total da venda\n- ID_CLIENTE - Id \u00fanico do cliente\n- CANAL - Canal de venda (FIS - F\u00edsico, ECM - E-commerce, TELEVENDAS - Telefone, WHATSAPP - WhatsApp, IFOOD - iFood)\n\nO dataset \u00e9 nomeado por `sales_20_21_train.csv` e foi obtido em 01\/10\/2021 disponibilizado pela equipe do VLabs para o desafio de previs\u00e3o do LTV. \n\"\"\"\n\"\"\"\n1. [Configura\u00e7\u00f5es iniciais](#section-zero)\n\n2. [Obten\u00e7\u00e3o e visualiza\u00e7\u00e3o dos dados](#section-one)\n\n3. [Pr\u00e9-processamento dos dados](#section-two)\n\n4. [Analise dos dados](#section-three)\n    \n    4.1. [Quantidade de vendas realizadas por cada loja](#section-three-one)\n    \n    4.2. [Receita total gerada por cada loja](#section-three-two)\n    \n    4.3. [Canais de vendas mais recorrentes](#section-three-three)\n    \n    4.4. [Quantidade de vendas por dia](#section-three-four)\n    \n    4.5. [Receita total por dia](#section-three-five)\n    \n    4.6. [Correla\u00e7\u00e3o entre as vari\u00e1veis](#section-three-six)\n\n5. [Segmentando os dados](#section-four)\n\n    5.1.1. [C\u00e1lculo da Rec\u00eancia](#section-four-one-one)\n    \n    5.1.2. [Atribuindo um Score para a Rec\u00eancia](#section-four-one-two)\n    \n    5.2.1. [C\u00e1lculo da Frequ\u00eancia](#section-four-two-one)\n    \n    5.2.2. [Atribuindo um Score para a Frequ\u00eancia](#section-four-two-two)\n    \n    5.3.1. [C\u00e1lculo da Receita](#section-three-one)\n    \n    5.3.2. [Atribuindo um Score para a Receita](#section-four-three-two)\n\n6. [C\u00e1lculo do RFM](#section-five)\n\n7. [C\u00e1lculo do LTV](#section-six)\n\n8. [Determinando features](#section-seven)\n\n9. [Cria\u00e7\u00e3o do modelo](#section-eight)\n\n\n\"\"\"\n\"\"\"\n<a id=\"section-zero\"><\/a>\n\n# 1. Configura\u00e7\u00f5es iniciais\n\"\"\"\nimport pandas as pd\n\nimport matplotlib\nfrom matplotlib import pyplot\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nfrom sklearn import preprocessing\nfrom sklearn.cluster import KMeans\n\nimport numpy as np\n\nimport lightgbm as lgb\n\nimport plotly as py\nimport plotly.offline as pyoff\nimport plotly.graph_objs as go\n\nfrom hyperopt import hp\nfrom sklearn.metrics import mean_squared_error\n\nfrom sklearn.model_selection import TimeSeriesSplit\n\n\nimport math\nfrom scipy.stats import norm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom time import time\n\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as ctb\nfrom hyperopt import fmin, tpe, STATUS_OK, STATUS_FAIL, Trials\n\n# Configurando o estilo dos plots\nsns.set_style(\"whitegrid\")\n!pip install -U kaleido\n\"\"\"\n<a id=\"section-one\"><\/a>\n# 2. Obten\u00e7\u00e3o e visualiza\u00e7\u00e3o dos dados\n\"\"\"\n# Obtendo os dados de treinamento\ndf = pd.read_csv('..\/input\/VLabs-DC\/sales_20_21_train.csv')\n\ndf.head()\n# Verificando o shape\nprint(\"O dataset cont\u00e9m {} linhas e {} colunas.\".format(*df.shape))\n\n# Verificando duplicatas\nprint(\"E cont\u00e9m {} duplicatas.\".format(df.duplicated().sum()))\n# Verificando a porcentagem de valores faltantes dentro do Dataframe\npercent_missing = df.isnull().sum() * 100 \/ len(df)\n\nmissing_value_df = pd.DataFrame({\n                                 'PORCENTAGEM_VALORES_FALTANTES': percent_missing})\n\ndisplay(missing_value_df)\n# Visualizando algumas vari\u00e1veis estat\u00edsticas de cada feature cont\u00ednua\ndf.describe()\n# Visualizando os valores \u00fanicos de cada feature\nfor col in df:\n    print('A coluna {} possui {} valores \u00fanicos'.format(col, len(df[col].unique())))\n\n\"\"\"\n<a id=\"section-two\"><\/a>\n# 3. Pr\u00e9-processamento dos dados\n\"\"\"\n# Convertendo o tipo da coluna DT_VENDA de string para datetime.\ndf['DT_VENDA'] = pd.to_datetime(df['DT_VENDA'])\n\ndf.head()\n# Visualizando os dados estat\u00edsticos das datas\ndf['DT_VENDA'].describe(datetime_is_numeric=True)\n\"\"\"\n<a id=\"section-three\"><\/a>\n# 4. Analise dos dados\n\"\"\"\n\"\"\"\n<a id=\"section-three-one\"><\/a>\n\n### 4.1. Visualizando a quantidade de vendas realizadas por cada loja\n\"\"\"\n# Dataset para visualizar quantas vendas\/receita foram geradas em cada loja durante todo o per\u00edodo do Dataset\nstore_sells = pd.DataFrame(df.groupby('LOJA').count()['ID_VENDA'])\n\nstore_sells.columns = ['QTD_TOTAL_VENDAS']\n\nstore_sells.head()\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.barplot(x=store_sells.index, y='QTD_TOTAL_VENDAS', data=store_sells)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"LOJA\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Quantidade de vendas por loja\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-three-two\"><\/a>\n\n### 4.2. Visualizando a receita total gerada por cada loja\n\"\"\"\n# Dataset para visualizar a receita total gerada em cada loja durante todo o per\u00edodo do Dataset\nstore_sells = pd.DataFrame(df.groupby(\"LOJA\").sum()['VALOR'])\n\nstore_sells.head()\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.barplot(x=store_sells.index, y='VALOR', data=store_sells)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"LOJA\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Receita total gerada por loja\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-three-three\"><\/a>\n\n### 4.3. Analisando os canais de vendas mais recorrentes\n\n\n\"\"\"\n# Dataset para visualizar quantas vendas foram realizadas por cada tipo de canal durante todo o per\u00edodo do Dataset\nchannel_sells = df['CANAL'].value_counts()\n\nchannel_sells.head()\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nstore_sells_plot = sns.barplot(x=channel_sells.index, y=channel_sells.values)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"CANAL\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Quantidade de compras por CANAL\", pad=25, fontsize=24)\n\nplt.show(store_sells_plot)\n\"\"\"\n<a id=\"section-three-four\"><\/a>\n\n### 4.4. Analisando a quantidade de vendas por dia\n\n\"\"\"\n# Dataset para visualizar quantas compras foram realizadas por dia durante todo o per\u00edodo do Dataset\ndate_count_df = df.groupby('DT_VENDA').count()['ID_VENDA']\n\ndate_count_df.head()\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.lineplot(data=date_count_df)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Data\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Quantidade de compras por dia\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-three-five\"><\/a>\n\n### 4.5. Analisando a receita total por dia\n\"\"\"\n# Dataset para visualizar a receita gerada por dia durante todo o per\u00edodo do Dataset\ndate_revenue_sum_df = df.groupby('DT_VENDA').sum()['VALOR']\n\ndate_revenue_sum_df.head()\n# Dataset para visualizar a m\u00e9dia de receita gerada por dia durante todo o per\u00edodo do Dataset\ndate_revenue_mean_df = df.groupby('DT_VENDA').mean()['VALOR']\n\ndate_revenue_mean_df.head()\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.lineplot(data=date_revenue_sum_df)\n\nsns.lineplot(data=date_revenue_mean_df)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Data\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Receita total por dia\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-three-six\"><\/a>\n\n### 4.6. Analisando a correla\u00e7\u00e3o entre as vari\u00e1veis\n\"\"\"\n\"\"\"\nIremos analisar a correla\u00e7\u00e3o entre as vari\u00e1veis cont\u00ednuas do Dataset. \n\nA **correla\u00e7\u00e3o** \u00e9 uma an\u00e1lise bivariada que mede a for\u00e7a da associa\u00e7\u00e3o entre duas vari\u00e1veis \u200b\u200be a dire\u00e7\u00e3o da rela\u00e7\u00e3o. Em termos da for\u00e7a da rela\u00e7\u00e3o, o valor do coeficiente de correla\u00e7\u00e3o varia entre +1 e -1. Um valor de \u00b1 1 indica um grau de associa\u00e7\u00e3o entre as duas vari\u00e1veis. \u00c0 medida que o valor do coeficiente de correla\u00e7\u00e3o vai para 0, a rela\u00e7\u00e3o entre as duas vari\u00e1veis \u200b\u200bser\u00e1 mais fraca. \n\nExistem v\u00e1rios m\u00e9todos de correla\u00e7\u00e3o, de Perason, Spearman e Kendall. \n\nPara o m\u00e9todo de correla\u00e7\u00e3o iremos utilizar a correla\u00e7\u00e3o de Pearson.\n\"\"\"\n# Computa a matriz de correla\u00e7\u00e3o\ncorr = df.corr()\n\n\nfifg, ax = plt.subplots(figsize=(11, 9))\n\n# Gerando um colormap customizado\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\nsns.heatmap(corr, cmap=cmap, center=0,\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\"\"\"\n\u00c9 interessante tamb\u00e9m analisarmos a rela\u00e7\u00e3o que a vari\u00e1vel *CANAL* tem com o Valor de cada compra.\n\nPara que possamos utilizar esse algor\u00edtmo, precisamos criar labels para cada vari\u00e1vel categ\u00f3rica. Come\u00e7aremos por este passo.\n\"\"\"\n# Convers\u00e3o das vari\u00e1veis categ\u00f3ricas em num\u00e9ricas\ndf_labeled = pd.get_dummies(df)\n\ndf_labeled.head()\n# Computa a matriz de correla\u00e7\u00e3o\ncorr = df_labeled[['VALOR', 'CANAL_ECM', 'CANAL_FIS', 'CANAL_IFOOD', 'CANAL_TELEVENDAS', 'CANAL_WHATSAPP']].corr()\n\n\nfifg, ax = plt.subplots(figsize=(11, 9))\n\n# Gerando o mapeamento de cores\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\nsns.heatmap(corr, cmap=cmap, center=0,\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\"\"\"\n<a id=\"section-four\"><\/a>\n\n### 5. Segmentando os dados\n\nPara o problema de LTV podemos criar v\u00e1rias segmenta\u00e7\u00f5es. Caso a Reten\u00e7\u00e3o dos clientes nas lojas seja interessante, o dado pode ser segmentado baseado na probabilidade de Churn, entre outros m\u00e9todos. Para este caso, iremos trabalhar com RFM que diz respeito \u00e0 Recency - Frequency - Monetary Value que em tradu\u00e7\u00e3o livre se diz respeito \u00e0 Rec\u00eancia - Frequ\u00eancia  e Valor monet\u00e1rio. \n\n - Baixo valor de RFM: Clientes que s\u00e3o menos ativos que outros e n\u00e3o realizam compras frequentes e que gastam pouco - normalmente s\u00e3o visitantes. \n\n - Valor m\u00e9dio de RFM: Representa o cliente m\u00e9dio. Ele compra com certa frequ\u00eancia e de forma recente e gera um valor consider\u00e1vel de receita, mas que n\u00e3o chega a ser muito alto. \n\n - Alto valor de RFM: Cliente que gera muita receita de forma frequente e de forma recente, esses s\u00e3o os clientes que voc\u00ea n\u00e3o quer perder.\n\nPara isso, iremos calcular a Rec\u00eancia, Frequ\u00eancia e Valor monet\u00e1rio de cada cliente e iremos aplicar um processo de aprendizado n\u00e3o-supervisionado para gerar diferentes cluster para cada valor individual.\n\nSer\u00e1 gerado um Score final que representa o RFM somando cada cluster das vari\u00e1veis Rec\u00eancia, Frequ\u00eancia e Valor monet\u00e1rio.\n\"\"\"\n# Dataframe que cont\u00e9m os clientes \u00fanicos\nusers_df = pd.DataFrame(df[\"ID_CLIENTE\"].unique(), columns=[\"ID_CLIENTE\"])\n\n\nusers_df.head()\n\"\"\"\n<a id=\"section-four-one-one\"><\/a>\n\n### 5.1.1 C\u00e1lculo da Rec\u00eancia\n\nIremos calcular a rec\u00eancia do cliente que nada mais \u00e9 que a diferen\u00e7a de dias em que o usu\u00e1rio realizou sua \u00faltima transa\u00e7\u00e3o em rela\u00e7\u00e3o ao dia mais recente do *Dataset* - 24\/02\/2021. Quanto maior a rec\u00eancia, menos recente \u00e9 as compras deste cliente. \n\"\"\"\ndf_max_purchase = df.groupby('ID_CLIENTE')['DT_VENDA'].max().reset_index()\n\ndf_max_purchase.columns = ['ID_CLIENTE','DT_COMPRA_MAIS_RECENTE']\n\ndf_max_purchase['DT_COMPRA_MAIS_RECENTE'] = pd.to_datetime(df_max_purchase['DT_COMPRA_MAIS_RECENTE'])\n\ndf_max_purchase.head()\n# Compara a \u00faltima transa\u00e7\u00e3o do conjunto de dados com as datas da \u00faltima transa\u00e7\u00e3o dos IDs de clientes individuais.\ndf_max_purchase['RECENCIA'] = (df_max_purchase['DT_COMPRA_MAIS_RECENTE'].max() - df_max_purchase['DT_COMPRA_MAIS_RECENTE']).dt.days\n\ndf_max_purchase.head()\n# mesclar este dataframe ao nosso dataframe de usu\u00e1rios \u00fanicos\nusers_df = pd.merge(users_df, df_max_purchase[['ID_CLIENTE','RECENCIA']], on='ID_CLIENTE')\n\nusers_df.head()\n\"\"\"\n<a id=\"section-four-one-two\"><\/a>\n\n### 5.1.2 Atribuindo um Score para a Rec\u00eancia\n\nIremos aplicar a clusteriza\u00e7\u00e3o por K-means para atribuir um score para a rec\u00eancia. Para que isto ocorra de forma otimizada, iremos verificar quantos cluster s\u00e3o necess\u00e1rios para termos o melhor trade-off do algor\u00edtmo K-means utilizando o m\u00e9todo de Elbow. \n\n\"O m\u00e9todo Elbow se trata de uma t\u00e9cnica interessante para encontrar o valor ideal do par\u00e2metro k. Basicamente o que o m\u00e9todo faz \u00e9 testar a vari\u00e2ncia dos dados em rela\u00e7\u00e3o ao n\u00famero de clusters. \u00c9 considerado um valor ideal de k quando o aumento no n\u00famero de clusters n\u00e3o representa um valor significativo de ganho.\" - Mineirando dados\n\"\"\"\nsse={} # Erro\n\nrecency_df = users_df[['RECENCIA']]\n\nfor k in range(1, 10):\n    kmeans = KMeans(n_clusters=k, max_iter=1000).fit(recency_df)\n\n    # Nome dos clusters relativos ao valor da rec\u00eancia\n    recency_df[\"CLUSTERS\"] = kmeans.labels_  \n\n    # Erro correspondente aos clusters\n    sse[k] = kmeans.inertia_ \n\n\n\nfig, ax = pyplot.subplots(figsize=(30, 15))\n\nsns.lineplot(x=list(sse.keys()), y=list(sse.values()))\n\nplt.xlabel(\"N\u00famero de Cluster - K\")\n\nplt.xticks(fontsize=16, rotation=0, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.show()\n\n\n\"\"\"\nCom isto, podemos determinar que K = 4 nos d\u00e1 uma clusteriza\u00e7\u00e3o mais otimizada.\n\"\"\"\n# Construindo 4 clusters para a rec\u00eancia e colocando no dataframe\nkmeans = KMeans(n_clusters=4)\n\nusers_df['CLUSTER_RECENCIA'] = kmeans.fit_predict(users_df[['RECENCIA']])\n\nusers_df.head()\n# Visualizando dados estat\u00edsticos da rec\u00eancia para cada cluster criado.\nusers_df.groupby('CLUSTER_RECENCIA')['RECENCIA'].describe()\n\"\"\"\nPara o c\u00e1lculo do RFM \u00e9 interassante que os clusters em rela\u00e7\u00e3o \u00e0 rec\u00eancia estejam ordenados de forma decrescente em rela\u00e7\u00e3o a rec\u00eancia, em que o maior cluster corresponda ao cliente com uma boa rec\u00eancia (com um menor valor de rec\u00eancia). \n\"\"\"\n# M\u00e9todo que ordena o cluster\ndef order_cluster(cluster_field_name, target_field_name, df, ascending):\n    df_new = df.groupby(cluster_field_name)[target_field_name].mean().reset_index()\n\n    df_new = df_new.sort_values(by=target_field_name,ascending=ascending).reset_index(drop=True)\n\n    df_new['index'] = df_new.index\n\n    df_final = pd.merge(df,df_new[[cluster_field_name,'index']], on=cluster_field_name)\n\n    df_final = df_final.drop([cluster_field_name],axis=1)\n\n    df_final = df_final.rename(columns={\"index\":cluster_field_name})\n    \n    return df_final\n# Ordenando os clusters da rec\u00eancia\nusers_df = order_cluster('CLUSTER_RECENCIA', 'RECENCIA', users_df, False)\n\nusers_df.head()\n\n# Visualizando dados estat\u00edsticos da rec\u00eancia para cada cluster criado.\nusers_df.groupby('CLUSTER_RECENCIA')['RECENCIA'].describe()\n\n# Visualizando a quantidade de clientes pertencentes a cada cluster\ndisplay(users_df['CLUSTER_RECENCIA'].value_counts(ascending=True))\n# Criando um label pra a melhor visualiza\u00e7\u00e3o dos dados relativos aos clusters da rec\u00eancia\nusers_df['LABEL_RECENCIA'] = 'Alta'\n\nusers_df.loc[users_df['CLUSTER_RECENCIA'] == 0, 'LABEL_RECENCIA'] = 'Muito Baixa' \n\nusers_df.loc[users_df['CLUSTER_RECENCIA'] == 1, 'LABEL_RECENCIA'] = 'Baixa' \n\nusers_df.loc[users_df['CLUSTER_RECENCIA'] == 2, 'LABEL_RECENCIA'] = 'M\u00e9dia' \n\nrecency_values_count = users_df['LABEL_RECENCIA'].value_counts(ascending=True)\n# Visualizando a quantidade de clientes pertencentes a cada cluster\ndisplay(users_df['LABEL_RECENCIA'].value_counts(ascending=True))\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nlabel_recency_plot = sns.barplot(x=recency_values_count.index, y=recency_values_count)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Cluster\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Agrupamento das categorias de Rec\u00eancia\", pad=50, fontsize=24)\n\nplt.show(label_recency_plot)\n\"\"\"\n<a id=\"section-four-two-one\"><\/a>\n\n### 5.2.1. C\u00e1lculo da Frequ\u00eancia\n\nA frequ\u00eancia se d\u00e1 com base no total de compras que cada cliente realizou durante todo o per\u00edodo do *Dataset*.\n\n\"\"\"\n# Recupera a quantidade de compras por cliente \nfrequency_df = df.groupby('ID_CLIENTE')['DT_VENDA'].count().reset_index()\n\nfrequency_df.columns = ['ID_CLIENTE','FREQUENCIA']\n\nfrequency_df.head()\n# Mescla este dataframe ao nosso dataframe de usu\u00e1rios \u00fanicos\nusers_df = pd.merge(users_df, frequency_df, on='ID_CLIENTE')\n\nusers_df.head()\n\"\"\"\n<a id=\"section-four-two-two\"><\/a>\n\n### 5.2.2. Atribuindo um Score para a Frequ\u00eancia\nSemelhante ao caso da Rec\u00eancia, iremos clusterizar os clientes com base em sua frequ\u00eancia. Quanto maior a frequ\u00eancia, mais importante se torna este cliente em rela\u00e7\u00e3o ao RFM.\n\"\"\"\n\"\"\"\nPrimeiro iremos determina o n\u00famero K de clusters ideal utilizando o m\u00e9todo Elbow.\n\"\"\"\nsse={} # Erro\n\nrecency_df = users_df[['FREQUENCIA']]\n\nfor k in range(1, 10):\n    kmeans = KMeans(n_clusters=k, max_iter=1000).fit(recency_df)\n\n    # Nome dos clusters relativos ao valor da rec\u00eancia\n    recency_df[\"CLUSTERS\"] = kmeans.labels_  \n\n    # Erro correspondente aos clusters\n    sse[k] = kmeans.inertia_ \n\n\n\nfig, ax = pyplot.subplots(figsize=(30, 15))\n\nsns.lineplot(x=list(sse.keys()), y=list(sse.values()))\n\nplt.xlabel(\"N\u00famero de Cluster - K\")\n\nplt.xticks(fontsize=16, rotation=0, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.show()\n\"\"\"\nCom isto, podemos determinar que K = 4 nos d\u00e1 uma clusteriza\u00e7\u00e3o mais otimizada.\n\"\"\"\n# Aplicando K-means na coluna de frequ\u00eancia\nkmeans = KMeans(n_clusters = 4)\n\nusers_df['CLUSTER_FREQUENCIA'] = kmeans.fit_predict(users_df[['FREQUENCIA']])\n\n# Visualizando os dados estat\u00edsticos de cada cluster em rela\u00e7\u00e3o a frequ\u00eancia.\nusers_df.groupby('CLUSTER_FREQUENCIA')['FREQUENCIA'].describe()\n\n\"\"\"\nPara o c\u00e1lculo do RFM geral \u00e9 interassante que os clusters em rela\u00e7\u00e3o \u00e0 frequ\u00eancia estejam ordenados de forma crescente, em que o maior cluster corresponda ao cliente com uma boa frequ\u00eancia (com um maior valor de compras dentro do per\u00edodo determinado). \n\"\"\"\nusers_df = order_cluster('CLUSTER_FREQUENCIA', 'FREQUENCIA', users_df, True)\n\n# Visualizando os dados estat\u00edsticos de cada cluster em rela\u00e7\u00e3o a frequ\u00eancia.\nusers_df.groupby('CLUSTER_FREQUENCIA')['FREQUENCIA'].describe()\n# Visualizando a quantidade de clientes pertencentes a cada cluster\ndisplay(users_df['CLUSTER_FREQUENCIA'].value_counts(ascending=True))\n# Definindo um label para cada cluster para visualiza\u00e7\u00e3o\nusers_df['LABEL_FREQUENCIA'] = 'Alta'\n\nusers_df.loc[users_df['CLUSTER_FREQUENCIA'] == 0, 'LABEL_FREQUENCIA'] = 'Muito Baixa' \n\nusers_df.loc[users_df['CLUSTER_FREQUENCIA'] == 1, 'LABEL_FREQUENCIA'] = 'Baixa' \n\nusers_df.loc[users_df['CLUSTER_FREQUENCIA'] == 2,'LABEL_FREQUENCIA'] = 'M\u00e9dia' \n# Visualizando a quantidade de clientes pertencentes a cada cluster\ndisplay(users_df['LABEL_FREQUENCIA'].value_counts(ascending=True))\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nlabel_frequency_plot = sns.barplot(x=users_df['LABEL_FREQUENCIA'].value_counts(ascending=True).index, y=users_df['LABEL_FREQUENCIA'].value_counts(ascending=True))\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Cluster\", fontsize=24)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Agrupamento das categorias de frequ\u00eancia\", pad=50, fontsize=24)\n\nplt.show(label_frequency_plot)\n\"\"\"\n<a id=\"section-four-three-one\"><\/a>\n\n### 5.3.1 C\u00e1lculo da Receita\n\nIremos analisar como se comportam a receita (valor total) gasto nas lojas por cliente durante todo o per\u00edodo do Dataset.\n\n\"\"\"\n# Recupera a receita total das compras por cliente \nclient_revenue = df[['ID_CLIENTE', 'VALOR']].groupby(\"ID_CLIENTE\").sum()\n\nclient_revenue.head()\n# Cria um dataset com a receita total das compras por cliente \nclient_revenue_df = client_revenue.reset_index()[['ID_CLIENTE', 'VALOR']]\n\nclient_revenue_df = client_revenue_df.rename(columns={\"ID_CLIENTE\": \"ID_CLIENTE\", \"VALOR\": \"RECEITA\"}, errors=\"raise\")\n\nclient_revenue_df.head()\n# Mescla este dataframe ao nosso dataframe de usu\u00e1rios \u00fanicos\nusers_df = pd.merge(users_df, client_revenue_df, on='ID_CLIENTE')\n\nusers_df.head()\n# Analisando a distribui\u00e7\u00e3o de receita\n\nfig, ax = pyplot.subplots(figsize=(50, 10))\n\nsns.histplot(data=users_df, x=\"RECEITA\", bins=150, kde=True)\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Receita\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Histograma da receita\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\nEm primeiro momento iremos preservar todos os dados, por mais que tenhamos um usu\u00e1rio com um gasto exorbitante. \n\"\"\"\n\"\"\"\n<a id=\"section-four-three-two\"><\/a>\n\n### 5.3.2. Atribuindo um Score para a Receita\nAssim como nos casos anteriores, iremos clusterizar os clientes com base na receita gerada e determinar o n\u00famero K ideal de Clusters utilizando o m\u00e9todo Elbow.\n\"\"\"\nsse={} # Erro\n\nrecency_df = users_df[['RECEITA']]\n\nfor k in range(1, 10):\n    kmeans = KMeans(n_clusters=k, max_iter=1000).fit(recency_df)\n\n    # Nome dos clusters relativos ao valor da receita\n    recency_df[\"CLUSTERS\"] = kmeans.labels_  \n\n    # Erro correspondente aos clusters\n    sse[k] = kmeans.inertia_ \n\n\n\nfig, ax = pyplot.subplots(figsize=(30, 15))\n\nsns.lineplot(x=list(sse.keys()), y=list(sse.values()))\n\nplt.xlabel(\"N\u00famero de Cluster - K\")\n\nplt.xticks(fontsize=16, rotation=0, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.show()\n\"\"\"\nSemelhante aos casos anteriores, K = 4 nos d\u00e1 um n\u00famero de clusters ideal. \n\"\"\"\n# Aplicando a clusteriza\u00e7\u00e3o\nkmeans = KMeans(n_clusters=4)\n\nusers_df['CLUSTER_RECEITA'] = kmeans.fit_predict(users_df[['RECEITA']])\n\n#Visualizando dados estat\u00edsticos dos clusters da receita\nusers_df.groupby('CLUSTER_RECEITA')['RECEITA'].describe()\n\"\"\"\nPara este caso, quanto maior o cluster, maior deve ser a receita total gerada. \n\"\"\"\n# Ordena os clusters de forma crescente, em que o \u00faltimo cluster ter\u00e1 o maior valor de receita\nusers_df = order_cluster('CLUSTER_RECEITA', 'RECEITA', users_df, True)\n\n\n#Visualizando dados estat\u00edsticos dos clusters da receita\nusers_df.groupby('CLUSTER_RECEITA')['RECEITA'].describe()\n# Visualizando a quantidade de clientes pertencentes a cada cluster\nusers_df['CLUSTER_RECEITA'].value_counts(ascending=True)\n# Definindo um label para cada cluster para visualiza\u00e7\u00e3o\nusers_df['LABEL_RECEITA'] = 'Alta'\n\nusers_df.loc[users_df['CLUSTER_RECEITA'] == 0, 'LABEL_RECEITA'] = 'Muito Baixa' \n\nusers_df.loc[users_df['CLUSTER_RECEITA'] == 1, 'LABEL_RECEITA'] = 'Baixa' \n\nusers_df.loc[users_df['CLUSTER_RECEITA'] == 2,'LABEL_RECEITA'] = 'M\u00e9dia' \n# Visualizando a quantidade de clientes pertencentes a cada cluster\nusers_df['LABEL_RECEITA'].value_counts(ascending=True)\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.barplot(x=users_df['LABEL_RECEITA'].value_counts(ascending=True).index, y=users_df['LABEL_RECEITA'].value_counts(ascending=True))\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Cluster\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=0, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Agrupamento das categorias de receita\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-five\"><\/a>\n\n### 6. C\u00e1lculo do RFM\n\nN\u00f3s possu\u00edmos um Cluster Score para rec\u00eancia, frequ\u00eancia e receita, com isto, iremos criar um score geral que engloba esses tr\u00eas Cluster principais gerando o nosso RFM.\n\n O RFM \u00e9 dado pela soma de cada cluster indivualmente.\n\"\"\"\n# Calcula a pontua\u00e7\u00e3o geral e use a m\u00e9dia para ver os detalhes\nusers_df['RFM'] = users_df['CLUSTER_RECENCIA'] + users_df['CLUSTER_FREQUENCIA'] + users_df['CLUSTER_RECEITA']\n\nusers_df.groupby('RFM')['RECENCIA','FREQUENCIA','RECEITA'].mean()\n\"\"\"\n\n\nCom isso, podemos perceber que, quanto maior o Score RFM, mais confi\u00e1vel \u00e9 o consumidor. \n\"\"\"\n# Visualizando a quantidade de clientes pertencentes a cada cluster\nusers_df['RFM'].value_counts(ascending=True)\nusers_df['SEGMENTO'] = 'Baixo'\nusers_df.loc[users_df['RFM'] > 3,'SEGMENTO'] = 'M\u00e9dio' \nusers_df.loc[users_df['RFM'] > 6,'SEGMENTO'] = 'Alto' \n\nusers_df.head()\n# Visualizando a quantidade de clientes pertencentes a cada cluster\nusers_df['SEGMENTO'].value_counts(ascending=True)\n# Visualizando os dados por Segmento\nfig, ax = pyplot.subplots(figsize=(50, 15))\n\nsns.barplot(x=users_df['SEGMENTO'].value_counts(ascending=True).index, y=users_df['SEGMENTO'].value_counts(ascending=True))\n\nplt.ylabel(\"\")\n\nplt.xlabel(\"Cluster\", fontsize=16)\n\nplt.xticks(fontsize=16, rotation=30, horizontalalignment='center')\n\nplt.yticks(fontsize=16, rotation=0)\n\nplt.title(\"Agrupamento das categorias do RFM\", pad=25, fontsize=24)\n\nplt.show()\n\"\"\"\n<a id=\"section-six\"><\/a>\n\n### 7. C\u00e1lculo do LTV\nAgora entramos na parte que interessa, iremos calcular o valor de LTV de cada cliente durante todo o per\u00edodo do Dataset.\n\n\n\"\"\"\n\"\"\"\nTemos que o LTV \u00e9 dado pela Receita total - Custo total.\n\nComo no dataset n\u00e3o temos a informa\u00e7\u00e3o do Custo por cliente, iremos considerar que o Lifetime Value ser\u00e1 determinado apenas pela receita total do cliente.\n\"\"\"\nusers_df.head()\n\"\"\"\nAgora, iremos analisar a rela\u00e7\u00e3o entre o RFM e as categorias de Rec\u00eancia, Frequ\u00eancia e Receita. \n\"\"\"\nrecency_plot_data = [\n    go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'Baixo'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'Baixo'\")['CLUSTER_RECENCIA'],\n        mode='markers',\n        name='Low',\n        marker= dict(size= 7,\n            line= dict(width=1),\n            color= 'blue',\n            opacity= 0.8\n           )\n    ),\n        go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['CLUSTER_RECENCIA'],\n        mode='markers',\n        name='Mid',\n        marker= dict(size= 9,\n            line= dict(width=1),\n            color= 'green',\n            opacity= 0.5\n           )\n    ),\n        go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'Alto'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'Alto'\")['CLUSTER_RECENCIA'],\n        mode='markers',\n        name='High',\n        marker= dict(size= 11,\n            line= dict(width=1),\n            color= 'red',\n            opacity= 0.9\n           )\n    ),\n]\n\nplot_layout = go.Layout(\n        yaxis= {'title': \"Classifica\u00e7\u00e3o da Rec\u00eancia\"},\n        xaxis= {'title': \"Score do RFM\"},\n        title='LTV'\n    )\nfig = go.Figure(data=recency_plot_data, layout=plot_layout)\nfig.show(renderer='png')\n\"\"\"\nPara o cluster de Rec\u00eancia temos que clientes no perfil de Baixo RFM tendem a estar em todos os 4 n\u00edveis de Rec\u00eancia. J\u00e1 para os clientes com perfis de M\u00e9dio RFM tendem a estar nos n\u00edveis 1 a 3 de Rec\u00eanica. Por outro lado, os clientes com Alto perfil de RFM tendem a estar nos n\u00edveis 2 a 3 de Rec\u00eancia.\n\"\"\"\nfrequency_plot_data = [\n    go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'Baixo'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'Baixo'\")['CLUSTER_FREQUENCIA'],\n        mode='markers',\n        name='Low',\n        marker= dict(size= 7,\n            line= dict(width=1),\n            color= 'blue',\n            opacity= 0.8\n           )\n    ),\n        go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['CLUSTER_FREQUENCIA'],\n        mode='markers',\n        name='Mid',\n        marker= dict(size= 9,\n            line= dict(width=1),\n            color= 'green',\n            opacity= 0.5\n           )\n    ),\n        go.Scatter(\n        x=users_df.query(\"SEGMENTO == 'Alto'\")['RFM'],\n        y=users_df.query(\"SEGMENTO == 'Alto'\")['CLUSTER_FREQUENCIA'],\n        mode='markers',\n        name='High',\n        marker= dict(size= 11,\n            line= dict(width=1),\n            color= 'red',\n            opacity= 0.9\n           )\n    ),\n]\n\nplot_layout = go.Layout(\n        yaxis= {'title': \"Classifica\u00e7\u00e3o da Frequ\u00eancia\"},\n        xaxis= {'title': \"Score do RFM\"},\n        title='LTV'\n    )\nfig = go.Figure(data=frequency_plot_data, layout=plot_layout)\nfig.show(renderer=\"png\")\n\"\"\"\nPara o cluster de Frequ\u00eancia temos que clientes no perfil de Baixo RFM tendem a estar em todos os 3 primeiros n\u00edveis de Frequ\u00eancia. J\u00e1 para os clientes com perfis de M\u00e9dio RFM tendem a estar em todos os n\u00edveis de Frequ\u00eancia. Por outro lado, os clientes com Alto perfil de RFM tendem a estar nos n\u00edveis 2 a 3 de Frequ\u00eancia.\n\"\"\"\n#revenue_plot_data = [\n#    go.Scatter(\n#        x=users_df.query(\"SEGMENTO == 'Baixo'\")['RFM'],\n#        y=users_df.query(\"SEGMENTO == 'Baixo'\")['CLUSTER_RECEITA'],\n#        mode='markers',\n#        name='Low',\n#        marker= dict(size= 7,\n#           line= dict(width=1),\n#            color= 'blue',\n#            opacity= 0.8\n#           )\n#    ),\n#        go.Scatter(\n#        x=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['RFM'],\n#        y=users_df.query(\"SEGMENTO == 'M\u00e9dio'\")['CLUSTER_RECEITA'],\n#        mode='markers',\n#        name='Mid',\n#        marker= dict(size= 9,\n#            line= dict(width=1),\n#            color= 'green',\n#            opacity= 0.5\n#           )\n#    ),\n#        go.Scatter(\n#        x=users_df.query(\"SEGMENTO == 'Alto'\")['RFM'],\n#        y=users_df.query(\"SEGMENTO == 'Alto'\")['CLUSTER_RECEITA'],\n#        mode='markers',\n#        name='High',\n#        marker= dict(size= 11,\n#            line= dict(width=1),\n#            color= 'red',\n#            opacity= 0.9\n#           )\n#    ),\n#]\n\n#plot_layout = go.Layout(\n#        yaxis= {'title': \"Classifica\u00e7\u00e3o da Receita\"},\n#        xaxis= {'title': \"Score do RFM\"},\n#        title='LTV'\n#    )\n#fig = go.Figure(data=revenue_plot_data, layout=plot_layout)\n#fig.show(renderer=\"png\")\n\"\"\"\nPara o cluster de Receita temos que clientes no perfil de Baixo RFM tendem a estar no n\u00edvel 0 a 2 de Receita. J\u00e1 para os clientes com perfis de M\u00e9dio RFM tendem a estar em todos n\u00edveis de Receita. Enquanto isso, os clientes com Alto perfil de RFM tendem a estar nos n\u00edveis 2 a 3 de Receita.\n\"\"\"\n\"\"\"\n<a id=\"section-seven\"><\/a>\n\n### 8. Determinando features\n\"\"\"\n\"\"\"\n## Estrat\u00e9gia\n\nPara que possamos prever com precis\u00e3o o LTV de cada cliente nos pr\u00f3ximos 3 meses do Dataset iremos calcular a tend\u00eancia de consumo de cada cliente nos per\u00edodos a serem determinados. Como estrat\u00e9gia de segmenta\u00e7\u00e3o dos dados iremos utilizar o m\u00e9todo de **janela deslizante (rolling window)**.\n\nUsaremos para o treinamento do modelo todo o Dataset menos as \u00faltimas compras realizadas nos \u00faltimos 90 dias - elas ser\u00e3o utilizadas como a valida\u00e7\u00e3o do modelo (e conseguequentemente o resultado final).\n\n## Tend\u00eancia\nA tend\u00eancia de compra de cada cliente se d\u00e1 pela quantidade de compras realizadas, o desvio padr\u00e3o das compras, a m\u00e9dia, a mediana e vari\u00e2ncia - tudo isso em um per\u00eddo de X dias.  Nesta etapa usaremos per\u00edodos de 30 dias para calcular a tend\u00eancia em cada per\u00eddo, sendo assim, teremos colunas com dados estat\u00edsticos de para 30, 60, 90, 120, 150, 180 dias. Al\u00e9m disso, como iremos utilizar o m\u00e9todo de janela deslizante, para cada cliente e para cada m\u00eas associado a este cliente haver\u00e1 essas features de tend\u00eancia, assim, teremos mais dados para poder trabalhar o modelo.\n\n\"\"\"\n# Sele\u00e7\u00e3o das features\nfeatured_df = users_df[['ID_CLIENTE', 'RECENCIA', 'CLUSTER_RECENCIA', 'FREQUENCIA', 'CLUSTER_FREQUENCIA', 'RECEITA', 'CLUSTER_RECEITA', 'RFM']]\n\nfeatured_df.head()\n# Criando um dataframe com a coluna ANO_MES_VENDA para ser usado como s\u00e9rie temporal mensal\ndf_month = df\n\ndf_month['ANO_MES_VENDA'] = df_month['DT_VENDA'].map(lambda date: 100*date.year + date.month)\n\ndf_month.head()\n\"\"\"\nNeste momento iremos criar as features relativas a tend\u00eancia e sazonalidade nos dados de cada cliente al\u00e9m da segmenta\u00e7\u00e3o dos dados por janela deslizante.\n\"\"\"\n\"\"\"\nAgora iremos gerar as features relativas \u00e0 tend\u00eancia de consumo de cada cliente no determinado Ano\/M\u00eas analisando os pr\u00f3ximos 3, 6, 9 e 12 meses de consumo. \n\"\"\"\n# Fun\u00e7\u00e3o que gera as features relativas a tend\u00eancia no dataset\ndef get_trend_for_each_period(reference_df, months):\n    _df = reference_df[['ID_CLIENTE', 'VALOR']].groupby('ID_CLIENTE').sum().reset_index()\n    \n    aux_dict = {\n        3 : pd.to_timedelta(30,unit='d'),\n        6 : pd.to_timedelta(60,unit='d'),\n        9 : pd.to_timedelta(90,unit='d'),\n        12: pd.to_timedelta(360,unit='d')\n    }\n    \n    for month in months: \n        date_condition = reference_df['DT_VENDA'].max() - aux_dict[month]\n\n        _df[f'RECEITA_{month}m'] = reference_df.where(reference_df['DT_VENDA'] > date_condition) \\\n                                    .sort_values(['ID_CLIENTE','ANO_MES_VENDA'], ascending=True) \\\n                                    .groupby('ID_CLIENTE')['VALOR'] \\\n                                    .sum() \\\n                                    .fillna(0)\n\n        _df[f'MEDIA_{month}m'] = reference_df.where(reference_df['DT_VENDA'] > date_condition) \\\n                                    .sort_values(['ID_CLIENTE','ANO_MES_VENDA'], ascending=True) \\\n                                    .groupby('ID_CLIENTE')['VALOR'] \\\n                                    .mean() \\\n                                    .fillna(0)\n\n        _df[f'DESVIO_PRADRAO_{month}m'] = reference_df.where(reference_df['DT_VENDA'] > date_condition) \\\n                                            .sort_values(['ID_CLIENTE','ANO_MES_VENDA'], ascending=True) \\\n                                            .groupby('ID_CLIENTE')['VALOR'] \\\n                                            .std() \\\n                                            .fillna(0)\n\n        _df[f'VARIANCIA_{month}m'] = reference_df.where(reference_df['DT_VENDA'] > date_condition) \\\n                                        .sort_values(['ID_CLIENTE','ANO_MES_VENDA'], ascending=True) \\\n                                        .groupby('ID_CLIENTE')['VALOR'] \\\n                                        .var() \\\n                                        .fillna(0)\n    return _df.fillna(0)\nlist_of_months = [3, 6, 9, 12]\n\n# client_df = get_trend_for_each_period(df_month, list_of_months)\n\"\"\"\n### Sele\u00e7\u00e3o das features\n\n\"\"\"\nfeatures = ['RECEITA_3m', 'RECENCIA', 'CLUSTER_RECENCIA',\n            'FREQUENCIA', 'CLUSTER_FREQUENCIA','RECEITA', 'CLUSTER_RECEITA','RFM',\n            'MEDIA_3m', 'DESVIO_PRADRAO_3m','VARIANCIA_3m',\n            'RECEITA_6m', 'MEDIA_6m', 'DESVIO_PRADRAO_6m',\n            'VARIANCIA_6m', 'RECEITA_9m', 'MEDIA_9m', 'DESVIO_PRADRAO_9m',\n            'VARIANCIA_9m', 'RECEITA_12m', 'MEDIA_12m', 'DESVIO_PRADRAO_12m',\n            'VARIANCIA_12m']\n\ntarget = ['VALOR']\n# Criando as novas features no nosso dataset para 3, 6, 9 e 12 meses \n# Utilizando os 3 \u00faltimos meses como o modelo de predi\u00e7\u00e3o da sa\u00edda dos dias 24\/02\/2021 at\u00e9 25\/05\/2021\npredict_df = get_trend_for_each_period(df_month[df_month['ANO_MES_VENDA'] >= 202012], list_of_months)\n\n# Com os dados anteriores ao per\u00edodo de predi\u00e7\u00e3o iremos utilizar para realizar o treinamento\ntrain_test_df = get_trend_for_each_period(df_month[df_month['ANO_MES_VENDA'] < 202012], list_of_months)\npredict_df = predict_df.merge(featured_df, how=\"inner\", on=\"ID_CLIENTE\")\n\ntrain_test_df = train_test_df.merge(featured_df, how=\"inner\", on=\"ID_CLIENTE\")\n# Visualizando os dados\ntrain_test_df.head()\n# Visualizando os dados\npredict_df.head()\n\"\"\"\n<a id=\"section-eight\"><\/a>\n\n### 9. Cria\u00e7\u00e3o do modelo\n\"\"\"\n\"\"\"\nPara a cria\u00e7\u00e3o do modelo iremos utilizar o modelo LGBM para realizar a regress\u00e3o. Como auxilio, iremos utilizar o m\u00e9todo TimeSeriesSplit do Scikit-learn para realizamos a Cross Validation dos nossos dados. \n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Inicializando o modelo com 100 estimators\nrf = RandomForestRegressor(n_estimators = 100, random_state = 42)\n\nX_train, X_test, y_train, y_test = train_test_split(train_test_df[features], train_test_df[target], test_size=0.33, random_state=42)\n\n\n# Treinando o modelo\nrf.fit(X_train, y_train)\npredict_df['prediction'] = rf.predict(predict_df[features])\npredict_df[['VALOR', 'prediction']]\n\"\"\"\n### 9.2. Avaliando o modelo\n\"\"\"\n# Avaliando o modelo com RMSE\n\nrmse = mean_squared_error(predict_df['VALOR'], predict_df['prediction'], squared=False)\n\nprint('O RMSE dos dados de valida\u00e7\u00e3o \u00e9: ', rmse)\n\npredict_df.groupby('ID_CLIENTE').sum().reset_index()\n# Gerando a sa\u00edda \noutput_df = predict_df.groupby('ID_CLIENTE').sum().reset_index()[['ID_CLIENTE', 'prediction']]\n\noutput_df.columns = ['ID_CLIENTE', 'VALOR']\n\noutput_df[output_df['VALOR'] < 0] = 0\n\noutput_df = output_df.round(2)\n\noutput_df.head()\n\"\"\"\nEst\u00e1 na hora de gerar a sa\u00edda :)\n\"\"\"\nsample_submission = pd.read_csv('..\/input\/VLabs-DC\/sample_submission.csv')\n\nsample_submission.head()\nresult_submission = sample_submission.merge(output_df, on='ID_CLIENTE', how='left')\n\nresult_submission.head()\nresult_submission.shape\nresult_submission = result_submission[['ID_CLIENTE', 'VALOR_y']]\n\nresult_submission.columns = ['ID_CLIENTE', 'VALOR']\n\nresult_submission.head()\nresult_submission.fillna(0).to_csv('.\/result.csv', index=False)\n\"\"\"\nCom isto, temos o resultado da predi\u00e7\u00e3o do LTV pr\u00f3ximos 90 dias de cada cliente. \n\nPr\u00f3ximos passos: \n\n- Evoluir a an\u00e1lise da s\u00e9rie temporal;\n- Complementar as features com valores de tend\u00eancia em cada per\u00edodo de compras;\n- Melhorar a predi\u00e7\u00e3o com v\u00e1rios algor\u00edtmos de Regress\u00e3o estudando os melhores par\u00e2metros;\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e4dd4cea7d5329'}"}
{"id":"125067","text":"\"\"\"\n![](https:\/\/i.imgur.com\/OTmSEnt.jpg)  \nPhoto of Marienplatz in Munich by <a href=\"https:\/\/unsplash.com\/@danielsessler\">Daniel Se\u00dfler<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/C6l894Q7wpI\">Unsplash<\/a>\n\"\"\"\n\"\"\"\n# 0. Stablishing the goal \n<h1 style=\"background:#FFDE91;\n           font-family:newtimeroman;\n           font-size:350%;\n           text-align:center;\n           border-radius: 50px 50px;\n           border:5px solid black;\n           ; padding:15px\"> \ud83c\udfc1 Goal <\/h1><a id=0><\/a>\n\"\"\"\n\"\"\"\n**Using the open source airbnb dataset from below, build a dashboard to help property owners and investors understand the Airbnb property market.**\n\n**Beginner**  \nCreate a dashboard to describe the Airbnb property market by showing the number of properties with specific property attributes\n\n* How can we help property owners and investors get a high-level overview of the property market?\n* What is the average rental price for apartments in your chosen city?\n* What number of bedrooms is the most common?\n* What proportion of Airbnb rentals have a swimming pool, air-conditioning, washing machine, etc?\n\n**Intermediate**   \nCreate an interactive dashboard to explore the property market. Build on the beginner level by allowing users to filter data directly from the dashboard.\n\n* How can we help a property owner understand the market and compare their property to others nearby?\n* If I own a 2 bedroom apartment with a swimming pool in the centre of your chosen city, how much would I be able to rent it for?\n* How many other properties are similar to mine?\n* Can you bring in any external data sources to support your dashboard, e.g. transport stations, distance to airport, schools, etc\n\n**Advanced\u200d**  \nBuild an interactive dashboard with your own custom metrics to evaluate the state of Airbnb property markets.\n\n* What factors might impact whether an Airbnb rental is a successful investment?\n* What data can we provide to a property investor to help them decide where next to buy a property?\n* Can we make the market measurable through a custom evaluation metric, eg \"Amsterdam has a stable tourism industry year round and the demand for properties is higher than the supply. It is an A+ investment. Barcelona's tourism industry is highly seasonal & demand is low. It is a B- investment.)\n\"\"\"\n\"\"\"\n****\n\"\"\"\n\"\"\"\n# 1. Importing \n<h1 style=\"background:#FFDE91;\n           font-family:newtimeroman;\n           font-size:350%;\n           text-align:center;\n           border-radius: 50px 50px;\n           border:5px solid black;\n           ; padding:15px\"> \ud83d\udcda Importing Libraries and Data <\/h1><a id=1><\/a>\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport random\n\n# turn off warnings for final notebook\nimport warnings\nwarnings.filterwarnings('ignore')\n\npd.set_option('display.max_columns', None)\n%matplotlib inline\nsns.set_context('notebook')\nsns.set_palette('Set2')\nsns.set_style('darkgrid')\n\nclass color:\n   PURPLE = '\\033[95m'\n   CYAN = '\\033[96m'\n   DARKCYAN = '\\033[36m'\n   BLUE = '\\033[94m'\n   GREEN = '\\033[92m'\n   YELLOW = '\\033[93m'\n   RED = '\\033[91m'\n   BOLD = '\\033[1m'\n   UNDERLINE = '\\033[4m'\n   END = '\\033[0m'\ndf_list=pd.read_csv('..\/input\/listingsairbnbmunich\/listings.csv')\ndf_list.head(5)\ndf_rev=pd.read_csv('..\/input\/reviewsairbnbmunich\/reviews.csv')\ndf_rev.head(5)\ndf_cal=pd.read_csv('..\/input\/calendarairbnbmunich\/calendar.csv')\ndf_cal.head(5)\n\"\"\"\n### **Conclusions\/Insights:**\n\n* The Listing dataset is going to require the most work, given its size. It has many columns, few of which will not be used for this exercise.\n\"\"\"\n\"\"\"\n****\n\"\"\"\n\"\"\"\n# 2. Exploring and Preparing \n<h1 style=\"background:#FFDE91;\n           font-family:newtimeroman;\n           font-size:350%;\n           text-align:center;\n           border-radius: 50px 50px;\n           border:5px solid black;\n           ; padding:15px\"> \ud83d\udd0e Exploring and Preparing <\/h1><a id=2><\/a>\n\"\"\"\n\"\"\"\nFirst let's take a look at the columns of the Listing dataset\n\"\"\"\ndf_list.columns\n\"\"\"\nNow let's only keep the ones we are going to work with\n\"\"\"\ndf_list_1=df_list[['id', 'host_since',\n       'host_is_superhost',\n       'neighbourhood_cleansed',\n       'property_type', 'room_type', 'accommodates',\n       'bathrooms_text', 'bedrooms', 'beds', 'amenities', 'price',\n       'minimum_nights', 'maximum_nights', 'number_of_reviews',\n       'number_of_reviews_ltm', 'number_of_reviews_l30d', 'first_review',\n       'last_review', 'review_scores_rating', 'review_scores_accuracy',\n       'review_scores_cleanliness', 'review_scores_checkin',\n       'review_scores_communication', 'review_scores_location',\n       'review_scores_value', 'reviews_per_month']]\ndf_list_1.columns\n\"\"\"\n\n**Understanding the features**\n\nhttps:\/\/docs.google.com\/spreadsheets\/d\/1iWCNJcSutYqpULSQHlNyGInUvHg2BoUGoNRIGa6Szc4\/edit#gid=1938308660\n\n\n\"\"\"\n\"\"\"\n### **General information about the Listings dataset**\n\"\"\"\n# general information about the dataset\ndf=df_list_1\n\ndf.info()                                     # check for incorrect datatypes\ndf.isnull().sum().sort_values(ascending=False)# check for missing data (first step)\n\nprint(\"Duplicated values\")\ndf_list.duplicated().value_counts()\n# Attention price is listed as object, let's take a deeper look.\nprint(df_list_1['price'].apply(type).value_counts())\ndf_list_1['price']\n\"\"\"\n\"Price\" is listed as string.This has to be corrected immediately or it will hinder the next analysis\n\"\"\"\n#This has to be corrected immediately\ndf= df_list_1\n\ndef clean_currency(x):\n    \"\"\" If the value is a string, then remove currency symbol and delimiters\n    otherwise, the value is numeric and can be converted\n    \"\"\"\n    if isinstance(x, str):\n        return(x.replace('$', '').replace(',', ''))\n    return(x)\n\ndf['price'] = df['price'].apply(clean_currency).astype('float')\n\nprint(df_list_1['price'].apply(type).value_counts())\ndf_list_1['price']\ndf=df_list_1\n\n\nsns.heatmap(df.isnull(),cbar=True).set_title(\"Visualizing Missing Values\\n\", fontsize=25)\nplt.gcf().set_size_inches(30,8)\nplt.xticks(ticks=[x+0.5 for x in range(df.columns.shape[0])],labels=df.columns,rotation=80, fontsize=15)\n\nplt.show()\ndf=df_list_1\n\npd.set_option(\"display.precision\", 2)\n\ndef highlight_columns(df, rows=20, color='lightgreen', columns_to_shadow=[], columns_to_show=[]):\n    highlight = lambda slice_of_df: 'background-color: %s' % color\n    sample_df = df.head(rows)\n    if len(columns_to_show) != 0:\n        sample_df = sample_df[columns_to_show]\n    highlighted_df = sample_df.style.applymap(highlight, subset=pd.IndexSlice[{'accommodates','bedrooms','beds','number_of_reviews_l30d'}, columns_to_shadow])\n    return highlighted_df\n\nsubsets = pd.IndexSlice[{'accommodates','beds','price'}, {'min'}]\nhighlight_columns(df.describe().T,columns_to_shadow=['max']).applymap(lambda x: \"background-color: lightgreen\", subset=subsets) # Here we highlight suspicious numbers to futher investigate\n\"\"\"\n### **Further Exploration for missing values:**  \n(Conclusions resumed below, open if you want to check in details.)\n\"\"\"\n# Let's check if exists a missing value for reviews, but exists a non-zero number of reviews:\n# These represent cases where reviews exist, but the reviewee probably wrote a review, but didn't fill the score review.(1372-1312 = 60 cases)\nprint(df_list_1.loc[(df_list_1['review_scores_value'].isnull()) & (df_list_1['number_of_reviews']!=0) ].shape)\ndf_list_1.loc[(df_list_1['review_scores_value'].isnull()) & (df_list_1['number_of_reviews']!=0) ].head(5)\n# Here I checked if there is a good correlation between bedrooms and accommodations to guide imputation of missing values.\n# There is no clear correlation to take advantage of.\nsns.scatterplot(data=df_list_1,x=\"bedrooms\",y=\"accommodates\")\n#Checking value count of 'accomodates' in cases of missing values for 'bedrooms', this will guide imputation\ndf_list_1[df_list_1['bedrooms'].isnull()]['accommodates'].value_counts()\n# Here I checked if there is a good correlation between beds and accommodations to guide imputation of missing values.\n# There is no clear correlation to take advantage of.\ndf_list_1[df_list_1['beds'].isnull()]['accommodates'].value_counts()\nsns.scatterplot(data=df_list_1,x=\"beds\",y=\"accommodates\")\n#Checking value count of 'accomodates' in cases of missing values for 'beds', this will guide imputation.\ndf_list_1[df_list_1['beds'].isnull()]['accommodates'].value_counts()\n#Checking value count of 'accomodates' compared to 'beds', this will guide imputation.\ndf_list_1[['beds','accommodates']].value_counts( sort=False, ascending=True).head(30)\n#Checking value count of 'accomodates' in cases of missing values for 'bathrooms_text', this will guide imputation.\ndf_list_1[df_list_1['bathrooms_text'].isnull()]['accommodates'].value_counts()\n#Here we find the case where host_is_superhost and host_since features are missing\ndf_list_1[df_list_1['host_is_superhost'].isnull()]\n\"\"\"\n### **Further Exploration for atypical values:**  \n(Conclusions resumed below, open if you want to check in details.)\n\"\"\"\n#There seems to be something strange with the max \"accomodates\" being 16, but the max \"beds\" and \"bedrooms\" are 50.\ndf_list[df_list_1['accommodates']>15]\n# Accommodates seems to have a hardcap at 16 people.\n# Using the links in the listing we can see some hostel, hotels and similar in the listing. What isn't the particular goal of the study.\n# We are going to apply a filter for listing with \"accommodatas\" for 16 and \"bedrooms\" equal and higher than 10, this seeks to exclude hotels and similar that \n# didn't list in airbnb just about the room itself.\n#There seems to be something strange with the \"beds\" being 0.\ndf_list.loc[(df_list_1['beds']==0)]\n#After checking some entries through the listings_url. There are some campings, some makeshift beds out of sofas, but most of the visited listings have indeed a bed.\n#It constutites a lesser error to impute all these values as 1.\n#There seems to be something strange with the \"prices\" at 0 and \"accomodates\" at 0.\ndf_list.loc[(df_list_1['price']==0)|(df_list_1['accommodates']==0)]\n# it seems that actual hotels can list at airbnb, but due to being unnusual they lack \"price\" and proper \"accommodates\".\n#Definetely excluding those.\n#There seems to be something strange with the \"number_of_reviews_l30d\" with numbers higher than 30. More than one per day?\ndf_list.loc[(df_list_1['number_of_reviews_l30d']>=30)]\n# I couldn't pinpoint why this happened, the listings seem pretty normal. Maybe a case of selfreview to boost numbers? In any case I don't think this will hurt the overall results or model.\n# We are leaving as it is for the moment.\ndf_list.loc[(df_list_1['accommodates']>=16)|(df_list_1['bedrooms']>=10)]\n\"\"\"\n### **Conclusions\/Insights:**  \n\n    \n**DataTypes**  \n* The column 'Price' seems to be saved as string and not as float. The datatype was corrected on the spot.\n\n**Duplicates**  \n* No duplicates found.\n\n**Missing Values**\n\n* 1372 rows (~27%) of the listings don't have have score reviews. Probably recent listings. Despite bringing additional information, the lack of reviews can be interpreted as evidence that the pricing is not  adapted to the market,e.g. listing at a lower price to catch initial customers. These listings will be included the general overview, but excluded of models for price prediction.\n* 565 rows (~11%) of the listings don't have the number of bedrooms. Of those, 501 states that they accommodate 3 or less people.In this dataset the overwhelming majority of listings have only one bedroom. Because of this, in this notebook we will impute these values as being 1.\n* 89 rows  (~2%) of the listings don't have the number of beds. Of those, 79 states that they accommodate 2 or less people.In this dataset the overwhelming majority of listings have only one bed. Because of this, in this notebook we will impute these values as being 1.\n* 11 rows  (~0.2%) of the listings don't have bathrooms_text. Of those,10 states that they accommodate 3 or less people.In this dataset the overwhelming majority of listings have only one bathroom. Because of this, in this notebook we will impute these values as being 1.\n* 1 row  (~0.2%) of the listings doesn't have host_is_superhost, host_since or score reviews. This row will be included in the general overview, but naturaly excluded of models. \n\n**Atypical Values**  \n\n* Accommodates seems to have a hardcap at 16 people.Using the links in the listing we can see some hostel, hotels and similar in the listing. What isn't the particular goal of the study. We are going to apply a **filter** for listing with \"accommodates\" for 16 or \"bedrooms\" equal and higher than 10, which sums up** for 17 rows.\n* 237 rows (~6%) had number of beds set as 0. Listings were inspected: there are some campings, some makeshift beds out of sofas, but most of the visited listings have indeed a bed.I conclude that it constutites a lesser error to replace all these values by 1.\n* 3 rows had 0 as price or 0 accomodates. The listings referred to hotels. These rows will be excluded.\n\"\"\"\n\"\"\"\n### **Appling changes:**  \nJust code stuff\n\"\"\"\n# at this point we will change from df_list_1 to df_list_2 (consider this a version control)\ndf_list_2=df_list_1.copy()\ndf_list_2['bedrooms'].fillna(value=1, axis=None, inplace=True)\ndf_list_2['bedrooms'].isnull().value_counts()\ndf_list_2['beds'].fillna(value=1, axis=None, inplace=True)\ndf_list_2['beds'].replace(0,1, inplace=True)\ndf_list_2['beds'].isnull().value_counts()\ndf_list_2['bathrooms_text'].fillna(value=1, axis=None, inplace=True)\ndf_list_2['bathrooms_text'].isnull().value_counts()\ndf_list_2.drop(df_list_2.loc[(df_list_2['accommodates']>=16)|(df_list_2['bedrooms']>=10)].index, inplace=True)\ndf_list_2.drop(df_list_2.loc[(df_list_2['price']==0)|(df_list_2['accommodates']==0)].index, inplace=True)\n\"\"\"\n### **Categorical Variables**  \n\n\"\"\"\n\"\"\"\n**Amenities**  \nAmenities are a challenge. We can spend a whole lot of time perfecting this specific data, specially with NLP (Natural Language Processing). But for now let's stick with a simpler solution. We are going to remove some special characters, split each amenity in one column and then count the most frequent amenities.  \nThis procedure isn't perfect but it's fast and appropriately accurate at this level.\n\"\"\"\ndf=df_list_2.copy()\ndf.amenities = df.amenities.str.replace('[{\"\"}]', \"\")\ndf.amenities = df.amenities.str.replace('[', \"\")\ndf.amenities = df.amenities.str.replace(']', \"\")\ndf= df.amenities.str.get_dummies(sep = \",\")\namenities=df.sum(axis=0).sort_values(ascending=False)\nnormalized_amenities=(amenities)\/(df_list_2.shape[0])\nnormalized_amenities[normalized_amenities>0.05]\n\"\"\"\nAgain further cleaning is possible and even desireble for a more acurate description of the data. But this is good enough for the moment. If we got time we can come back to this LATER.\n\"\"\"\n\"\"\"\n**Neighborhood**  \nLet's take a look at the neighborhood.\n\"\"\"\ndf_list_2['neighbourhood_cleansed'].value_counts()\nfig, ax = plt.subplots(figsize=(8, 8))\nax.set_title(\"Neighbourhood\", size=20,fontweight='bold')\n\ndf_list_2['neighbourhood_cleansed'].value_counts().plot(kind='bar', cmap='tab20c', title=\"Property Type\",sort_columns=True)\n\"\"\"\nNo obvious problem here. But let's check if (\"Sendling-Westpark\", \"Sendling\") and (\"Berg am Laim\", \"Laim\") means different places.\n  \nAfter checking: yes, they are different places. Moving on.\n\"\"\"\n\"\"\"\n**Property type**  \nLet's inspect the property labels. Probably there will be some confusion.\n\n\"\"\"\ndf_list_2['property_type'].value_counts()\n\"\"\"\nWow. Cave? that was unexpected.  \n  \nLet's agree on standardizing these property types.\nI suggest:\n* Entire apartment  \n* Private room in apartment  \n* Private room in house  \n* Room in hotel  \n* Shared room in apartment  \n* Entire house  \n* Others\n\n(Let's control the urge to put cave in a separate category.)\n\"\"\"\ndf_list_2['property_type_clean']=df_list_2['property_type'].replace({\n'Entire apartment':'Entire apartment',\n'Private room in house':'Private room in house',\n'Private room in apartment':'Private room in apartment',\n'Private room in condominium':'Private room in apartment',\n'Shared room in apartment':'Shared room in apartment',\n'Entire townhouse':'Entire house',\n'Private room in villa':'Private room in house',\n'Entire condominium':'Private room in apartment',\n'Private room in townhouse':'Private room in house',\n'Entire house':'Entire house',\n'Private room in loft':'Private room in apartment',\n'Entire loft':'Entire apartment',\n'Private room in bed and breakfast':'Private room in apartment',\n'Private room':'Private room in apartment',\n'Entire serviced apartment':'Entire apartment',\n'Private room in camper\/rv':'Other',\n'Shared room in condominium':'Shared room in apartment',\n'Camper\/RV':'Other',\n'Entire guest suite':'Private room in apartment',\n'Hut':'Other',\n'Entire home\/apt':'Entire apartment',\n'Entire hostel':'room in hotel\/hostel',\n'Private room in guest suite':'Private room in apartment',\n'Private room in serviced apartment':'Private room in apartment',\n'Private room in guesthouse':'Private room in house',\n'Room in boutique hotel':'room in hotel\/hostel',\n'Entire place':'Entire apartment',\n'Cave':'Other',\n'Shared room in bed and breakfast':'Shared room in apartment',\n'Entire bungalow':'Entire apartment',\n'Private room in hostel':'room in hotel\/hostel',\n'Shared room in boat':'Other',\n'Earth house':'Other',\n'Room in bed and breakfast':'Private room in apartment',\n'Shared room in tipi':'Other',\n'Private room in tent':'Other',\n'Shared room in tent':'Other',\n'Room in hotel':'room in hotel\/hostel',\n'Room in serviced apartment':'Private room in apartment',\n'Room in aparthotel':'room in hotel\/hostel',\n'Tiny house':'Entire house',\n'Private room in bungalow':'Private room in house',\n'Shared room in guesthouse':'Shared room in apartment',\n'Bus':'Other',\n'Shared room in loft':'Shared room in apartment',\n'Shared room in hostel':'room in hotel\/hostel',\n'Entire guesthouse':'Entire house',\n'Private room in nature lodge':'Other',\n'Private room in barn':'Other'\n    })\ndf_list_2['property_type_clean'].value_counts()\ndef label_function(val):\n    return f'{val:.0f}%'\n\nfig, ax = plt.subplots(figsize=(8, 8))\ndf_list_2.groupby('property_type_clean').size().plot(kind='pie', textprops={'fontsize': 13},autopct=label_function, cmap='tab20c', title=\"Property Type\",sort_columns=True)\nplt.axis('off')\nax.set_title(\"Property Type\", size=20,fontweight='bold')\n\"\"\"\nMuch better.\n\"\"\"\n\"\"\"\n**Bathroom_text**  \nLet's clean some toilet related data, dear data janitors.\n\"\"\"\ndf_list_2['bathrooms_text'].value_counts()\n\"\"\"\nThis would be way better as **numbers**, don't you think?\n\"\"\"\ndf_list_2['bathrooms']=df_list_2['bathrooms_text'].replace({\n    '1 bath':'1',\n    '1 private bath':'1' ,\n    '1 shared bath':'1' ,\n    '1.5 shared baths':'1.5',\n    'Shared half-bath':'0.5',\n    '1.5 baths':'1.5',\n    '2.5 baths':'2.5',\n    '2.5 shared baths':'2.5' ,\n    '2 baths':'2',\n    '2 shared baths':'2' ,\n    '0 baths':'0',\n    '0 shared baths':'0' ,\n    'Half-bath':'0.5',\n    '3 baths':'3',\n    '4 baths':'4',\n    '3.5 baths':'3.5',\n    '5 baths':'5',\n    '4 shared baths':'4',\n    '8 shared baths':'8',\n    '8.5 shared baths':'8.5',\n    '3 shared baths':'3'\n    })\n\ndf_list_2['bathrooms']= df_list_2['bathrooms'].astype('float')\ndf_list_2['bathrooms'].value_counts()\n\"\"\"\nDone.\n\"\"\"\n\"\"\"\n**Room type**  \nLet's inspect the room types.\n\"\"\"\ndf_list_2['room_type'].value_counts()\n\"\"\"\nSurprisingly clean =)\n\"\"\"\n\"\"\"\n**Host is superhost?**  \nLet's inspect the superhost status.\n\"\"\"\ndf_list_2['host_is_superhost'].value_counts()\n\"\"\"\nWe could turn this into a boolean. but maybe later.\n\"\"\"\n\"\"\"\n****\nHere we can already export the csv files and plot some graphs with tablaeu.\n\"\"\"\ndf_list_2.to_csv('df_list_2.csv',index=False)\nnormalized_amenities.to_csv('amenities.csv',index=True)\n\"\"\"\n`Expand` to see possible dashboards at this point:  \n[Link to Tableau Public](https:\/\/public.tableau.com\/app\/profile\/aramis.farias\/viz\/AirbnbMunich\/Story1)\n\"\"\"\n\"\"\"\n![](https:\/\/i.imgur.com\/Ky8ZWjX.jpg)\n\"\"\"\n\"\"\"\n![](https:\/\/i.imgur.com\/NRyNtLW.jpg)\n\n\"\"\"\n\"\"\"\n****\n\"\"\"\n\"\"\"\n![](http:\/\/www.graciano.adv.br\/imagens\/Under-construction1.jpg)\n\"\"\"\n\"\"\"\n### **General information about the Reviews dataset**\n\"\"\"\ndf_rev.head()\n# general information about the dataset\ndf=df_rev\n\ndf.info()                                     # check for incorrect datatypes\ndf.isnull().sum().sort_values(ascending=False)# check for missing data (first step)\nfrom scipy.signal import find_peaks\n\n# Plot the number reviews over time to see any patterns\ndf_reviews_plot = df_rev.groupby('date')['id'].count().reset_index()\ndf_reviews_plot[\"rolling_mean\"] = df_reviews_plot.id.rolling(window=30).mean()\ndf_reviews_plot['date'] = pd.to_datetime(df_reviews_plot['date'])\n\npeaks, _ = find_peaks(df_reviews_plot['rolling_mean'],distance=200)\n\nplt.figure(figsize=(20, 10))\n\nplt.plot(df_reviews_plot['date'][peaks], df_reviews_plot[\"rolling_mean\"][peaks], \"x\", color='red') # ploting an X in the peaks\n\nplt.plot(df_reviews_plot.date, df_reviews_plot.rolling_mean); # ploting the series\n\nplt.title(\"Number of reviews by date (last 30 days mean)\", fontsize=20);\n#plt.xlabel(\"time\");\nplt.ylabel(\"reviews\", fontsize=14);\nfor i in peaks:\n    plt.annotate(df_reviews_plot['date'][i].date(),xy=(df_reviews_plot['date'][i],df_reviews_plot['rolling_mean'][i]))\n\n    \nprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\ntextstr = \"Oktoberfest period\\n ~ 20 Sep - 05 Oct\"\nplt.annotate(textstr,xy=(0.85, 0.90), xycoords=\"axes fraction\", fontsize=14, verticalalignment='top', bbox=props)\n\n\nplt.grid()\n\"\"\"\nHere I used a text analysis software, namely Iramuteq, to group the most common words present in the comments.  \nNotice: only word in english were included and with a frequency >100 counts.  \n\"\"\"\n\"\"\"\n<h3 style=\"\n           font-family:newtimeroman;\n           font-size:300%;\n           text-align:center;\n           ; padding:15px\"> Cooccurrence Analysis <\/h3><a id=2><\/a>\n \n![](https:\/\/i.imgur.com\/4sbMTit.png)\n\"\"\"\n\"\"\"\n****\n\"\"\"\n\"\"\"\n![](https:\/\/images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com\/f\/8cc1eeaa-4046-4c4a-ae93-93d656f68688\/dep51cx-d4206067-f005-4c8b-9fe8-d544c901b0a8.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzhjYzFlZWFhLTQwNDYtNGM0YS1hZTkzLTkzZDY1NmY2ODY4OFwvZGVwNTFjeC1kNDIwNjA2Ny1mMDA1LTRjOGItOWZlOC1kNTQ0YzkwMWIwYTguanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.9zBwe-a2skICkc12TH70AdE55bPsS4U1chM_MNSNS6A)\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e6157048169890'}"}
{"id":"52165","text":"\"\"\"\n# Description \n\nThis notebook is another basic introduction on how to use ensembling, and is purely based on this amazing [notebook](https:\/\/www.kaggle.com\/serigne\/stacked-regressions-top-4-on-leaderboard\/data?select=train.csv) by Serigne. The goal is to fist use first-level (base) predictions of a few basic classifiers and then use another model at the second-level in order to predict the output from the earlier first-level predictions.\n\nPlease note that in creating this notebook, I have also used other notbooks such as [this](https:\/\/www.kaggle.com\/pmarcelino\/comprehensive-data-exploration-with-python) and [this](https:\/\/www.kaggle.com\/apapiu\/regularized-linear-models). Feel free to leave your feedback in the comments.\n\"\"\"\n#import python librairies\n\nimport numpy as np \nimport pandas as pd \n%matplotlib inline\nimport matplotlib.pyplot as plt  \nimport seaborn as sns\ncolor = sns.color_palette()\nsns.set_style('darkgrid')\nimport warnings\ndef ignore_warn(*args, **kwargs):\n    pass\nwarnings.warn = ignore_warn \n\nfrom scipy import stats\nfrom scipy.stats import norm, skew \n\npd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) \n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"..\/input\"]).decode(\"utf8\")) \n\n#import the input files \ntrain = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\ntest = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\n\n#check the numbers of samples and features\nprint(\"The train data size before dropping Id feature is : {} \".format(train.shape))\nprint(\"The test data size before dropping Id feature is : {} \".format(test.shape))\n\n#Save the 'Id' column\ntrain_ID = train['Id']\ntest_ID = test['Id']\n\n#Now drop the  'Id' colum since it's unnecessary for  the prediction process.\ntrain.drop(\"Id\", axis = 1, inplace = True)\ntest.drop(\"Id\", axis = 1, inplace = True)\n\n#check again the data size after dropping the 'Id' variable\nprint(\"\\nThe train data size after dropping Id feature is : {} \".format(train.shape)) \nprint(\"The test data size after dropping Id feature is : {} \".format(test.shape))\n\"\"\"\n# Data Processing\n\nLet's explore the data:\n\"\"\"\n#Deleting outliers\ntrain = train.drop(train[(train['GrLivArea']>4000) & (train['SalePrice']<300000)].index)\n\n#Check the graphic again\nfig, ax = plt.subplots()\nax.scatter(train['GrLivArea'], train['SalePrice'])\nax.set_facecolor('white')\nplt.ylabel('SalePrice', fontsize=13)\nplt.xlabel('GrLivArea', fontsize=13)\nplt.show()\n\nsns.distplot(train['SalePrice'] , fit=norm);\n\n# Get the fitted parameters used by the function\n(mu, sigma) = norm.fit(train['SalePrice'])\nprint( '\\n mu = {:.2f} and sigma = {:.2f}\\n'.format(mu, sigma))\n\n#Now plot the distribution\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n            loc='best')\nax = plt.axes()\nax.set_facecolor(\"white\")\nplt.ylabel('Frequency')\nplt.title('SalePrice distribution')\n\n#Get also the QQ-plot\nfig = plt.figure()\nax = fig.add_subplot()\nax.set_facecolor('white')\nres = stats.probplot(train['SalePrice'], plot=plt)\nplt.show()\n\n#We use the numpy fuction log1p which  applies log(1+x) to all elements of the column\ntrain[\"SalePrice\"] = np.log1p(train[\"SalePrice\"])\n\n#Check the new distribution \nsns.distplot(train['SalePrice'] , fit=norm);\n\n# Get the fitted parameters used by the function\n(mu, sigma) = norm.fit(train['SalePrice'])\nprint( '\\n mu = {:.2f} and sigma = {:.2f}\\n'.format(mu, sigma))\n\n#Now plot the distribution\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n            loc='best')\nax = plt.axes()\nax.set_facecolor(\"white\")\nplt.ylabel('Frequency')\nplt.title('SalePrice distribution')\n\"\"\"\n# Feature Engineering \n\nLet's perform some feature engineering. Keep in mind the target variable is housing prices. \n\"\"\"\nntrain = train.shape[0]\nntest = test.shape[0]\ny_train = train.SalePrice.values\nall_data = pd.concat((train, test)).reset_index(drop=True)\nall_data.drop(['SalePrice'], axis=1, inplace=True)\nprint(\"all_data size is : {}\".format(all_data.shape))\n\nall_data_na = (all_data.isnull().sum() \/ len(all_data)) * 100\nall_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index).sort_values(ascending=False)[:30]\nmissing_data = pd.DataFrame({'Missing Ratio' :all_data_na})\nmissing_data.head(20)\n\nf, ax = plt.subplots(figsize=(15, 12))\nplt.xticks(rotation='90')\nax.set_facecolor(\"white\")\nsns.barplot(x=all_data_na.index, y=all_data_na)\nsns.color_palette(\"rocket\", as_cmap=True)\nplt.xlabel('Features', fontsize=15)\nplt.ylabel('Percent of missing values', fontsize=15)\nplt.title('Percent missing data by feature', fontsize=15)\n\"\"\"\n# Data Correlation\n\nLet's plot the correlation heatmap:\n\"\"\"\n#Correlation map to see how features are correlated with SalePrice\ncorrmat = train.corr()\nplt.subplots(figsize=(12,9))\nsns.heatmap(corrmat, cmap=\"YlGnBu\", vmax=0.9, square=True)\n\"\"\"\nNow let's impute the missing values:\n\"\"\"\nall_data[\"FireplaceQu\"] = all_data[\"FireplaceQu\"].fillna(\"None\")\n\nall_data[\"PoolQC\"] = all_data[\"PoolQC\"].fillna(\"None\")\n\nall_data[\"MiscFeature\"] = all_data[\"MiscFeature\"].fillna(\"None\")\n\nall_data[\"Alley\"] = all_data[\"Alley\"].fillna(\"None\")\n\nall_data[\"Fence\"] = all_data[\"Fence\"].fillna(\"None\")\n\n#Group by neighborhood and fill in missing value by the median LotFrontage of all the neighborhood\nall_data[\"LotFrontage\"] = all_data.groupby(\"Neighborhood\")[\"LotFrontage\"].transform(\n    lambda x: x.fillna(x.median()))\n\nfor col in ('GarageType', 'GarageFinish', 'GarageQual', 'GarageCond'):\n    all_data[col] = all_data[col].fillna('None')\n    \nfor col in ('GarageYrBlt', 'GarageArea', 'GarageCars'):\n    all_data[col] = all_data[col].fillna(0)\n    \nfor col in ('BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath'):\n    all_data[col] = all_data[col].fillna(0)\n    \nfor col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):\n    all_data[col] = all_data[col].fillna('None')\n    \nall_data[\"MasVnrType\"] = all_data[\"MasVnrType\"].fillna(\"None\")\nall_data[\"MasVnrArea\"] = all_data[\"MasVnrArea\"].fillna(0)\n\nall_data['MSZoning'] = all_data['MSZoning'].fillna(all_data['MSZoning'].mode()[0])\n\nall_data = all_data.drop(['Utilities'], axis=1)\n\nall_data[\"Functional\"] = all_data[\"Functional\"].fillna(\"Typ\")\n\nall_data['Electrical'] = all_data['Electrical'].fillna(all_data['Electrical'].mode()[0])\n\nall_data['KitchenQual'] = all_data['KitchenQual'].fillna(all_data['KitchenQual'].mode()[0])\n\nall_data['Exterior1st'] = all_data['Exterior1st'].fillna(all_data['Exterior1st'].mode()[0])\nall_data['Exterior2nd'] = all_data['Exterior2nd'].fillna(all_data['Exterior2nd'].mode()[0])\n\nall_data['SaleType'] = all_data['SaleType'].fillna(all_data['SaleType'].mode()[0])\nall_data['MSSubClass'] = all_data['MSSubClass'].fillna(\"None\")\n\n#Check remaining missing values if any \nall_data_na = (all_data.isnull().sum() \/ len(all_data)) * 100\nall_data_na = all_data_na.drop(all_data_na[all_data_na == 0].index).sort_values(ascending=False)\nmissing_data = pd.DataFrame({'Missing Ratio' :all_data_na})\nmissing_data.head()\n\n#MSSubClass=The building class\nall_data['MSSubClass'] = all_data['MSSubClass'].apply(str)\n\n#Changing OverallCond into a categorical variable\nall_data['OverallCond'] = all_data['OverallCond'].astype(str)\n\n#Year and month sold are transformed into categorical features.\nall_data['YrSold'] = all_data['YrSold'].astype(str)\nall_data['MoSold'] = all_data['MoSold'].astype(str)\n\nfrom sklearn.preprocessing import LabelEncoder\ncols = ('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond', \n        'ExterQual', 'ExterCond','HeatingQC', 'PoolQC', 'KitchenQual', 'BsmtFinType1', \n        'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope',\n        'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond', \n        'YrSold', 'MoSold')\n# process columns, apply LabelEncoder to categorical features\nfor c in cols:\n    lbl = LabelEncoder() \n    lbl.fit(list(all_data[c].values)) \n    all_data[c] = lbl.transform(list(all_data[c].values))\n\n# shape        \nprint('Shape all_data: {}'.format(all_data.shape))\n\n# Adding total sqfootage feature \nall_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']\n\nnumeric_feats = all_data.dtypes[all_data.dtypes != \"object\"].index\n\n# Check the skew of all numerical features\nskewed_feats = all_data[numeric_feats].apply(lambda x: skew(x.dropna())).sort_values(ascending=False)\nprint(\"\\nSkew in numerical features: \\n\")\nskewness = pd.DataFrame({'Skew' :skewed_feats})\nskewness.head(10)\n\"\"\"\nWe should also transform the skewed values:\n\"\"\"\nskewness = skewness[abs(skewness) > 0.75]\nprint(\"There are {} skewed numerical features to Box Cox transform\".format(skewness.shape[0]))\n\nfrom scipy.special import boxcox1p\nskewed_features = skewness.index\nlam = 0.15\nfor feat in skewed_features:\n    #all_data[feat] += 1\n    all_data[feat] = boxcox1p(all_data[feat], lam)\n    \n#all_data[skewed_features] = np.log1p(all_data[skewed_features])\n\nall_data = pd.get_dummies(all_data)\nprint(all_data.shape)\n\ntrain = all_data[:ntrain]\ntest = all_data[ntrain:]\n\n\"\"\"\n# Ensemble Learning\n\nThe base models used for ensemble learning include LASSO Regression, Elastic Net Regression, Kernel Ridge Regression, Gradient Boosting Regression, XGBoost, and LightGBM.\n\"\"\"\nfrom sklearn.linear_model import ElasticNet, Lasso,  BayesianRidge, LassoLarsIC\nfrom sklearn.ensemble import RandomForestRegressor,  GradientBoostingRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport xgboost as xgb\nimport lightgbm as lgb\n\n#Validation function\nn_folds = 5\n\ndef rmsle_cv(model):\n    kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(train.values)\n    rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring=\"neg_mean_squared_error\", cv = kf))\n    return(rmse)\nlasso = make_pipeline(RobustScaler(), Lasso(alpha =0.0005, random_state=1))\n\nENet = make_pipeline(RobustScaler(), ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3))\n\nKRR = KernelRidge(alpha=0.6, kernel='polynomial', degree=2, coef0=2.5)\n\nGBoost = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,\n                                   max_depth=4, max_features='sqrt',\n                                   min_samples_leaf=15, min_samples_split=10, \n                                   loss='huber', random_state =5)\n\nmodel_xgb = xgb.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468, \n                             learning_rate=0.05, max_depth=3, \n                             min_child_weight=1.7817, n_estimators=2200,\n                             reg_alpha=0.4640, reg_lambda=0.8571,\n                             subsample=0.5213, silent=1,\n                             random_state =7, nthread = -1)\n\nmodel_lgb = lgb.LGBMRegressor(objective='regression',num_leaves=5,\n                              learning_rate=0.05, n_estimators=720,\n                              max_bin = 55, bagging_fraction = 0.8,\n                              bagging_freq = 5, feature_fraction = 0.2319,\n                              feature_fraction_seed=9, bagging_seed=9,\n                              min_data_in_leaf =6, min_sum_hessian_in_leaf = 11)\n\nscore = rmsle_cv(lasso)\nprint(\"\\nLasso score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(ENet)\nprint(\"ElasticNet score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(KRR)\nprint(\"Kernel Ridge score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(GBoost)\nprint(\"Gradient Boosting score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(model_xgb)\nprint(\"Xgboost score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nscore = rmsle_cv(model_lgb)\nprint(\"LGBM score: {:.4f} ({:.4f})\\n\" .format(score.mean(), score.std()))\n\"\"\"\nFor stacking models, two different approaches are used: 1) averaging the base models, and 2) creating a meta-learner using linear regression. \n\"\"\"\nclass AveragingModels(BaseEstimator, RegressorMixin, TransformerMixin):\n    def __init__(self, models):\n        self.models = models\n        \n    # we define clones of the original models to fit the data in\n    def fit(self, X, y):\n        self.models_ = [clone(x) for x in self.models]\n        \n        # Train cloned base models\n        for model in self.models_:\n            model.fit(X, y)\n\n        return self\n    \n    #Now we do the predictions for cloned models and average them\n    def predict(self, X):\n        predictions = np.column_stack([\n            model.predict(X) for model in self.models_\n        ])\n        return np.mean(predictions, axis=1)   \n    \naveraged_models = AveragingModels(models = (ENet, GBoost, KRR, lasso))\n\nscore = rmsle_cv(averaged_models)\nprint(\" Averaged base models score: {:.4f} ({:.4f})\\n\".format(score.mean(), score.std()))\n\nclass StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin):\n    def __init__(self, base_models, meta_model, n_folds=5):\n        self.base_models = base_models\n        self.meta_model = meta_model\n        self.n_folds = n_folds\n   \n    # We again fit the data on clones of the original models\n    def fit(self, X, y):\n        self.base_models_ = [list() for x in self.base_models]\n        self.meta_model_ = clone(self.meta_model)\n        kfold = KFold(n_splits=self.n_folds, shuffle=True, random_state=156)\n        \n        # Train cloned base models then create out-of-fold predictions\n        # that are needed to train the cloned meta-model\n        out_of_fold_predictions = np.zeros((X.shape[0], len(self.base_models)))\n        for i, model in enumerate(self.base_models):\n            for train_index, holdout_index in kfold.split(X, y):\n                instance = clone(model)\n                self.base_models_[i].append(instance)\n                instance.fit(X[train_index], y[train_index])\n                y_pred = instance.predict(X[holdout_index])\n                out_of_fold_predictions[holdout_index, i] = y_pred\n                \n        # Now train the cloned  meta-model using the out-of-fold predictions as new feature\n        self.meta_model_.fit(out_of_fold_predictions, y)\n        return self\n   \n    #Do the predictions of all base models on the test data and use the averaged predictions as \n    #meta-features for the final prediction which is done by the meta-model\n    def predict(self, X):\n        meta_features = np.column_stack([\n            np.column_stack([model.predict(X) for model in base_models]).mean(axis=1)\n            for base_models in self.base_models_ ])\n        return self.meta_model_.predict(meta_features)\n    \nstacked_averaged_models = StackingAveragedModels(base_models = (ENet, GBoost, KRR),\n                                                 meta_model = lasso)\n\nscore = rmsle_cv(stacked_averaged_models)\nprint(\"Stacking Averaged models score: {:.4f} ({:.4f})\".format(score.mean(), score.std()))\n\ndef rmsle(y, y_pred):\n    return np.sqrt(mean_squared_error(y, y_pred))\n\nstacked_averaged_models.fit(train.values, y_train)\nstacked_train_pred = stacked_averaged_models.predict(train.values)\nstacked_pred = np.expm1(stacked_averaged_models.predict(test.values))\nprint(rmsle(y_train, stacked_train_pred))\n\nmodel_xgb.fit(train, y_train)\nxgb_train_pred = model_xgb.predict(train)\nxgb_pred = np.expm1(model_xgb.predict(test))\nprint(rmsle(y_train, xgb_train_pred))\n\nmodel_lgb.fit(train, y_train)\nlgb_train_pred = model_lgb.predict(train)\nlgb_pred = np.expm1(model_lgb.predict(test.values))\nprint(rmsle(y_train, lgb_train_pred))\n\n'''RMSE on the entire Train data when averaging'''\n\nprint('RMSLE score on train data:')\nprint(rmsle(y_train,stacked_train_pred*0.70 +\n               xgb_train_pred*0.15 + lgb_train_pred*0.15 ))\n\nensemble = stacked_pred*0.70 + xgb_pred*0.15 + lgb_pred*0.15\n\nsub = pd.DataFrame()\nsub['Id'] = test_ID\nsub['SalePrice'] = ensemble\nsub.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': '60017bab72d35b'}"}
{"id":"109584","text":"# 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\ndf=pd.read_csv('\/kaggle\/input\/cardataset\/data.csv')\n\ndf\ndf.columns=df.columns.str.lower().str.replace(' ','_')\ndf.head()\n\ndf.dtypes\ndf.dtypes[df.dtypes==\"object\"].index\nstrings=list(df.dtypes[df.dtypes==\"object\"].index)\n# Loop over the strings list\nfor i in strings:\n    df[i]=df[i].str.lower().str.replace(' ','_')\n    \ndf.head()\ndf.dtypes\nfor col in df.columns:\n    print(col)\n    print(df[col].unique()[:4],'\\n')\n    print(df[col].nunique())\n# lets try determining unique values\n# how many they are\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n\nsns.histplot(df.msrp, bins=60)\nsns.histplot(df.msrp[df.msrp<=100000], bins=50)\n\nprice_logs=np.log1p(df.msrp)\nprice_logs\n\nsns.histplot(price_logs, bins=50)\n\"\"\"\n#### Missing vaues\n\"\"\"\ndf.isnull().sum()\nn=len(df)\n\nn_val=int(n*0.2)\nn_test=int(n*0.2)\n#  But this is not sustainable becase n reduces by 2 due to rounding off with fxn int()\n# we just subtract\nn_train=n-n_val-n_test\n\n# thus they are the same\nn, n_val+n_test+n_train\nn, n_val,n_test, n_train\ndf.iloc[:10]\ndf_train=df.iloc[:n_train]\n\ndf_val=df.iloc[n_train:n_train+n_val]\n\ndf_test=df.iloc[n_train+n_val:]\n\n\nidx=np.arange(n)\nnp.random.seed(2)\nnp.random.shuffle(idx)\ndf.iloc[idx[:10]]\ndf_train= df.iloc[idx[:n_train]]\n\ndf_val= df.iloc[idx[n_train:n_train+n_val]]\n\ndf_test= df.iloc[idx[n_train+n_val:]]\n\n\ndf_train=df_train.reset_index(drop=True)\ndf_val=df_val.reset_index(drop=True)\ndf_test=df_test.reset_index(drop=True)\n\nlen(df_train), len(df_val), len(df_test)\n\"\"\"\nLog transformation of our target variable y. Use .values to remain with a numpy array and not a Pandas series\n\"\"\"\ny_train=np.log1p(df_train.msrp.values)\ny_val=np.log1p(df_val.msrp.values)\ny_test=np.log1p(df_test.msrp.values)\ndf.head()\ndel df_train ['msrp']\ndel df_val ['msrp']\ndel df_test ['msrp']\nlen(y_train)\n\"\"\"\n# 2. LINEAR REGRESSION\n\nA model used to solve regression problems. Used to predict number\n\"\"\"\ndf_train.iloc[10]\nxi=[453, 11, 86]\nw0=7.17 #bias\nw=[0.01,0.04,0.002]# weights\n#  is the linear regression model\ndef linear_regression(xi):\n    \n    n=len(xi)\n    \n    pred=w0\n    \n    for j in range(n):\n        \n        pred=pred+w[j] * xi[j]\n #do something\n    return pred\nnp.expm1(linear_regression(xi))\n\"\"\"\n## 2.1 Linear Regression Vector Form\n\"\"\"\ndef dot(xi, w):\n    n=len(xi)\n    \n    res=0.0\n    \n    for j in range(n):\n        \n        res=res + xi[j]* w[j]\n        \n    return res\n    \ndot(xi, w)\ndef linear_regression(xi):\n    return w0 + dot(xi, w)\nlinear_regression(xi)\nw_new=[w0]+ w\n\nw_new\n#  is the linear regression model\ndef linear_regression(xi):\n    \n    xi= [1] + xi\n    return dot(xi,w_new)\nround(linear_regression(xi), 3)\nxi=[453, 11, 86]\nw0=7.17 #bias\nw=[0.01,0.04,0.002]# weights\n\nw_new=[w0]+ w\nx1=[1, 148, 24, 1385]\nx2=[1, 132, 25, 2031]\nx10=[1, 453, 11, 86]\n\n# We then make a list of lists\n\nX=[x1, x2, x10]\n\nX=np.array(X)\n\nX\ndef linear_regression(X):\n    return X.dot(w_new)\n\"\"\"\n## 2.7 Training a linear regression model\n\"\"\"\nX=[[ 148, 24, 1385],\n[132, 25, 2031],\n[453, 11, 86],\n[158, 24, 185],\n[172, 25, 201],\n[413, 11, 86],\n[38, 54, 185],\n[142, 25, 431],\n[453, 31, 86]]\n\nX=np.array(X)\n# ones=np.ones(X.shape[0])\n# X= np.column_stack([ones,X])\nX\n\ny=[10000,20000,15000,20050,10000,20000,15000,25000,12000]\n# gram matrix\n\nXTX=X.T.dot(X)\nXTX\nXTX_inv= np.linalg.inv(XTX)\nXTX_inv\n# w_full=XTX_inv.dot(X.T).dot(y)\nnp.linalg.inv(XTX)\nnp.linalg.det(XTX_inv)\ndef train_linear_regression(X, y):\n# Iclude a bias term.. helps us identify value of car if we dont know anythig about the car.\n    ones=np.ones(X.shape[0])\n    X=np.column_stack([ones, X])\n    \n    XTX=X.T.dot(X)\n    XTX_inv= np.linalg.inv(XTX)\n    w_full= XTX_inv.dot(X.T).dot(y)\n    \n    return  w_full[0], w_full[1:]\ntrain_linear_regression(X,y)\n\"\"\"\n## 2.8 Car Price Baseline Model\n\"\"\"\ndf_train.dtypes\nbase=['engine_hp','engine_cylinders','highway_mpg','city_mpg','popularity']\n\n\n\nX_train= df_train[base].fillna(0).values\n# LEts now train a model\nw0, w= train_linear_regression(X_train, y_train)\n\nw0, w\ny_pred=w0+ X_train.dot(w)\nsns.histplot(y_pred, color='red', alpha=0.4, bins=50)\nsns.histplot(y_train, color='blue',alpha=0.4, bins=50)\n\"\"\"\n## 2.9 RMSE\n\nEVALUATION OF OUR REGRESSION MODELS\n\"\"\"\ndef rmse(y_pred, y):\n    \n    error=y_pred- y\n    se=error**2\n    mse=se.mean()\n    return np.sqrt(mse)\n    \nrmse(y_pred, y_train)\n\"\"\"\n## 2.10 Validating the  model\n\"\"\"\nbase=['engine_hp','engine_cylinders','highway_mpg','city_mpg','popularity']\nX_train= df_train[base].fillna(0).values\nw0, w= train_linear_regression(X_train, y_train)\ny_pred=w0+ X_train.dot(w)\ndef prepare_X(df):\n    df_num=df[base]\n    df_num=df_num.fillna(0)\n    X=df_num.values\n    return X\n\n    \nX_train=prepare_X(df_train)\nw0, w= train_linear_regression(X_train, y_train)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\n\"\"\"\n## 2.11 Simple Feature Engineering\n\"\"\"\ndf_train[\"year\"].max()# to determine the ages of the cars.\n\n2017-df_train[\"year\"] # we can use this as one of our feeatures in this model\ndef prepare_X(df):\n    df=df.copy()\n    \n    df['age']=2017-df[\"year\"] \n    \n    features= base+['age']\n    df_num=df[features]\n    df_num=df_num.fillna(0)\n    X=df_num.values\n    return X\n\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression(X_train, y_train)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\n\nsns.histplot(y_pred, color='red', alpha=0.4, bins=50)\nsns.histplot(y_val, color='blue',alpha=0.4, bins=50)\n\"\"\"\n## 2.12 Categorical Variables\n\"\"\"\ndf_train.dtypes #mostly strings(object)\n# df_train['num_doors_2']=(df_train.number_of_doors ==2).astype(int)\n# df_train['num_doors_3']=(df_train.number_of_doors ==3).astype(int)\n# df_train['num_doors_4']=(df_train.number_of_doors ==4).astype(int)\n# for v in [2,3,4]:\n#     df_train['num_doors_%s' %v]=(df_train.number_of_doors ==v).astype(int)\n# df_train\ndef prepare_X(df):\n    df=df.copy()\n    \n    df['age']=2017-df[\"year\"] \n    \n    features= base+['age']\n    \n    for v in[2,3,4]:\n        df['num_doors_%s' %v]=(df.number_of_doors ==v).astype(int)\n        features.append('num_doors_%s' %v)\n        \n    df_num=df[features]\n    df_num=df_num.fillna(0)\n    X=df_num.values\n    return X\nprepare_X(df_train)\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression(X_train, y_train)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\n\"\"\"\nThere is a slight change  .002 which shows that the doors feature is not useful.. Now let us look at the make feature\n\"\"\"\ndf.make.nunique()\nmakes=list(df.make.value_counts().head().index)\ndef prepare_X(df):\n    df=df.copy()\n    \n    df['age']=2017-df[\"year\"] \n    \n    features= base+['age']\n    \n    for v in[2,3,4]:\n        df['num_doors_%s' %v]=(df.number_of_doors ==v).astype(int)\n        features.append('num_doors_%s' %v)\n    for m in makes:\n        df['make_%s' %m]=(df.make ==m).astype(int)\n        features.append('make_%s' %m)\n        \n    df_num=df[features]\n    df_num=df_num.fillna(0)\n    X=df_num.values\n    return X\nprepare_X(df_train)\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression(X_train, y_train)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\ndf.dtypes\n# We can now use all the categorical variables\n\ncategorical_var=['make',\n    \"engine_fuel_type\",'transmission_type','driven_wheels','market_category','market_category'  \n     ,'vehicle_style',]\n# We use a dictionary\ncategories={}\n\nfor c in categorical_var:\n    categories[c]=list(df[c].value_counts().head().index)\n\ncategories\ndef prepare_X(df):\n    df=df.copy()\n    \n    df['age']=2017-df[\"year\"] \n    \n    features= base+['age']\n    \n    for v in[2,3,4]:\n        df['num_doors_%s' %v]=(df.number_of_doors ==v).astype(int)\n        features.append('num_doors_%s' %v)\n    for c, values in categories.items():\n        for v in values:\n            df['%s_%s' %(c,v)]=(df[c] ==v).astype(int)\n            features.append('%s_%s' %(c,v))\n        \n    df_num=df[features]\n    df_num=df_num.fillna(0)\n    X=df_num.values\n    return X\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression(X_train, y_train)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\nw0, w\n\"\"\"\n## 2.13 Regularization\n\"\"\"\ndef train_linear_regression_reg(X, y, r=0.001):\n# Iclude a bias term.. helps us identify value of car if we dont know anythig about the car.\n    ones=np.ones(X.shape[0])\n    X=np.column_stack([ones, X])\n    \n    XTX=X.T.dot(X)\n    \n    XTX=XTX+ r* np.eye(XTX.shape[0])\n    XTX_inv= np.linalg.inv(XTX)\n    w_full= XTX_inv.dot(X.T).dot(y)\n    \n    return  w_full[0], w_full[1:]\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression_reg(X_train, y_train, r=0.001)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nrmse(y_val, y_pred)\n\"\"\"\n## 2.14 Model Tuning\n\"\"\"\nfor r in [0.0, 0.00001,0.0001,0.001,0.1,1,10]:\n\n    X_train=prepare_X(df_train)\n    w0, w= train_linear_regression_reg(X_train, y_train, r=r)\n\n    X_val=prepare_X(df_val)\n    y_pred=w0+ X_val.dot(w)\n\n    score=rmse(y_val, y_pred)\n    \n    print(f\"for {r} the bias term is  {w0}  and score is  {score}\")\nr=0.001\nX_train=prepare_X(df_train)\nw0, w= train_linear_regression_reg(X_train, y_train, r=r)\n\nX_val=prepare_X(df_val)\ny_pred=w0+ X_val.dot(w)\n\nscore=rmse(y_val, y_pred)\nscore\n\"\"\"\n## 2.15 Using the Model on Test Data\n\"\"\"\ndf_full_train=pd.concat([df_train, df_val])\ndf_full_train=df_full_train.reset_index(drop=True)\ndf_full_train\nX_full_train=prepare_X(df_full_train)\nX_full_train\ny_full_train= np.concatenate([y_train, y_val])\n\nw0, w= train_linear_regression_reg(X_full_train, y_full_train, r=0.001)\n\nw0, w\nX_test=prepare_X(df_test)\ny_pred=w0+ X_test.dot(w)\n\nscore=rmse(y_test, y_pred)\nscore\ncar=df_test.iloc[20].to_dict()\n\ncar\ndf_small=pd.DataFrame([car])\n\nX_small=prepare_X(df_small)\n\ny_pred=w0+ X_small.dot(w)\n\ny_pred=y_pred[0]\ny_pred\nnp.expm1(y_pred)\n(np.expm1(y_test[20])- np.expm1(y_pred))\n\"\"\"\nOur model shows that there is a slight difference between the predicted and actual price of the car model pick. A difference of $1692.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c95f1685713861'}"}
{"id":"32551","text":"\"\"\"\nMany thanks to @nayuts for sharing his hard work with the community. All credit for this work goes to below notebooks and @nayuts. Kindly upvote and appreciate the original work.\n\n1. https:\/\/www.kaggle.com\/nayuts\/256-x-256-cropped-images\n2. https:\/\/www.kaggle.com\/nayuts\/efficientnet-with-undersampling\n\nI have increased the number of epochs and tuned the model optimizer paramaters to get slightly better results.\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/raw.githubusercontent.com\/tasotasoso\/kaggle_media\/main\/iwildcam2021\/model_image.png\" width=\"***300***\">\n\"\"\"\nimport sys\nsys.path.append('..\/input\/pytorch-image-models\/pytorch-image-models-master')\n\nimport collections\nimport gc\nimport json\nimport os\nimport random\nimport time\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nfrom albumentations import *\nfrom albumentations.pytorch import ToTensor\nimport cv2\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image, ImageFilter\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import train_test_split\nimport tifffile as tiff\nimport timm\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom torch.utils.data import DataLoader, Dataset, sampler\nfrom tqdm import tqdm_notebook as tqdm\n\n%matplotlib inline\n\"\"\"\n### setting\n\"\"\"\n!ls ..\/input\/256-x-256-cropped-images\nDATASET = \"..\/input\/iwildcam2021-fgvc8\"\nCROPED_DATA = \"..\/input\/256-x-256-cropped-images\/\"\n\nTRAIN_CROPED_DATA = \"croped_images_train\/\"\nTEST_CROPED_DATA = \"croped_images_test\/\"\nBATCH_SIZE = 32\nDEVICE = ('cuda' if torch.cuda.is_available() else 'cpu')\nEPOCHS = 5000\nNUM_WORKERS = 4\nSEED = 2021\ndef set_seed(seed=2**3):\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n    torch.backends.cudnn.deterministic = True\nset_seed(SEED)\ndf_croped_img_ids_train = pd.read_csv(CROPED_DATA + \"croped_train.csv\")\ndf_croped_img_ids_test = pd.read_csv(CROPED_DATA + \"croped_test.csv\")\ndf_croped_img_ids_train.head()\ndf_croped_img_ids_test.head()\n\"\"\"\n### create train dataframe\n\"\"\"\nwith open('..\/input\/iwildcam2021-fgvc8\/metadata\/iwildcam2021_train_annotations.json', encoding='utf-8') as json_file:\n    train_annotations =json.load(json_file)\ndf_train_annotation = pd.DataFrame(train_annotations[\"annotations\"])\ntrain = df_croped_img_ids_train[[\"id\", \"idx\"]].merge(df_train_annotation[[\"image_id\", \"category_id\"]], \n                                      left_on='id', right_on='image_id')[[\"id\", \"idx\", \"category_id\"]]\ndf_categories = pd.DataFrame(train_annotations[\"categories\"])\ncat_idxs = df_categories[\"id\"]\n\ndef convert_cat_to_index(x):\n    return np.where(cat_idxs==x)[0][0]\ntrain[\"category_id\"] = train[\"category_id\"].map(lambda x: convert_cat_to_index(x))\ntrain.head()\n\"\"\"\n### unzip croped data\n\"\"\"\n! unzip ..\/input\/256-x-256-cropped-images\/croped_images_train.zip \n! unzip ..\/input\/256-x-256-cropped-images\/croped_images_test.zip\n\"\"\"\n# Train\n\"\"\"\n\"\"\"\n## Create dataset for training\n\"\"\"\n# ====================================================\n# Dataset for train\n# ====================================================\n\nmean = np.array([0.37087523, 0.370876, 0.3708759] )\nstd = np.array([0.21022698, 0.21022713, 0.21022706])\n\ndef img2tensor(img,dtype:np.dtype=np.float32):\n    if img.ndim==2 : img = np.expand_dims(img,2)\n    img = np.transpose(img,(2,0,1))\n    return torch.from_numpy(img.astype(dtype, copy=False))\n\nclass IWildcamTrainDataset(Dataset):\n    def __init__(self, df, tfms=None):\n        self.ids = df[\"id\"]\n        self.idxs = df[\"idx\"]\n        self.categories = df[\"category_id\"]\n        self.tfms = tfms\n        \n    def __len__(self):\n        return len(self.ids)\n    \n    def __getitem__(self, idx):\n        size = (256, 256)\n        image_id = self.ids[idx]\n        image_idx = self.idxs[idx]\n        iamge_categorie = self.categories[idx]\n        \n        image_path = TRAIN_CROPED_DATA + f\"{image_id}_{image_idx}.jpg\"\n        img = cv2.resize(cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB),size)\n\n        if self.tfms is not None:\n            augmented = self.tfms(image=img)\n            img = augmented['image']\n            \n        # we should normalize here\n        return img2tensor((img\/255.0  - mean)\/std), torch.tensor(iamge_categorie)\ndef get_aug(p=1.0):\n    return Compose([\n        HorizontalFlip(),\n        ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=15, p=0.9, \n                         border_mode=cv2.BORDER_REFLECT),\n        VerticalFlip(),\n        RandomBrightnessContrast(p=0.9),\n    ], p=p)\n\"\"\"\n## Create model\n\"\"\"\n# ====================================================\n# EfficientNet Model\n# ====================================================\n\nclass enet_v2(nn.Module):\n\n    def __init__(self, backbone, out_dim, pretrained=False):\n        super(enet_v2, self).__init__()\n        self.enet = timm.create_model(backbone, pretrained=pretrained)\n        in_ch = self.enet.classifier.in_features\n        self.myfc = nn.Linear(in_ch, out_dim)\n        self.enet.classifier = nn.Identity()\n\n    def forward(self, x):\n        x = self.enet(x)\n        x = self.myfc(x)\n        return x\nmodel = enet_v2(backbone=\"tf_efficientnet_b0\", out_dim=205)\nmodel.to(DEVICE)\n\"\"\"\n## train setting\n\"\"\"\n# ====================================================\n# Optimizer and Loss\n# ====================================================\n\noptimizer = torch.optim.SGD(model.parameters(), lr=0.0001, momentum=0.9)\n#optimizer = torch.optim.SGD([\n#                {'params': model.parameters()},\n#               {'params': model.classifier.parameters(), 'lr': 1e-4}\n#            ], lr=1e-3, momentum=0.9)\ncriterion = nn.CrossEntropyLoss()\n\"\"\"\n## Train\n\nSince we know that [the training data is imbalanced](https:\/\/www.kaggle.com\/nayuts\/iwildcam-2021-overviewing-for-start#EDA), I undersampled it.\n\"\"\"\nrus = RandomUnderSampler(random_state=SEED, replacement=True)\n\ndef generate_dataloders(train):\n    \n    train_resampled, _ = rus.fit_resample(train, train[\"category_id\"])\n    test_resampled, _ = rus.fit_resample(train, train[\"category_id\"])\n\n    train_resampled = train_resampled.reset_index(drop=True)\n    test_resampled = test_resampled.reset_index(drop=True)\n    \n    ds_train = IWildcamTrainDataset(train_resampled, tfms=get_aug())\n    dl_train = DataLoader(ds_train,batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS)\n    ds_test = IWildcamTrainDataset(test_resampled)\n    dl_test = DataLoader(ds_test,batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS)\n    \n    return dl_train, dl_test\n# ====================================================\n# Train\n# ====================================================\n\nfor epoch in tqdm(range(EPOCHS)):\n    \n    dl_train, dl_test = generate_dataloders(train)\n    \n    ###Train\n    model.train()\n    train_loss = 0\n    \n    for data in dl_train:\n        optimizer.zero_grad()\n        imgs, categories = data\n        imgs = imgs.to(DEVICE)\n        categories = categories.to(DEVICE)\n        \n        outputs = model(imgs)\n    \n        loss = criterion(outputs, categories)\n        loss.backward()\n        optimizer.step()\n            \n        train_loss += loss.item()\n    train_loss \/= len(dl_train)\n        \n    print(f\"EPOCH: {epoch + 1}, train_loss: {train_loss}\")\n        \n    ###Validation\n    model.eval()\n    valid_loss = 0\n        \n    for data in dl_test:\n        imgs, categories = data\n        imgs = imgs.to(DEVICE)\n        categories = categories.to(DEVICE)\n        \n        outputs = model(imgs)\n    \n        loss = criterion(outputs, categories)\n        \n        valid_loss += loss.item()\n    valid_loss \/= len(dl_test)\n        \n    print(f\"EPOCH: {epoch + 1}, valid_loss: {valid_loss}\")\n        \n    \n    if (epoch+1)%50 == 0 or (epoch+1)%EPOCHS == 0:\n        ###Save model\n        torch.save(model.state_dict(), f\"{epoch+1}_.pth\")\n\"\"\"\n# Inference\n\"\"\"\n\"\"\"\n## Create dataset for test\n\"\"\"\n# ====================================================\n# Dataset for test\n# ====================================================\n\nmean = np.array([0.37087523, 0.370876, 0.3708759] )\nstd = np.array([0.21022698, 0.21022713, 0.21022706])\n\nclass IWildcamTestDataset(Dataset):\n    def __init__(self, df, tfms=None):\n        self.ids = df[\"id\"]\n        self.idx = df[\"idx\"]\n        self.tfms = tfms\n        \n    def __len__(self):\n        return len(self.ids)\n    \n    def __getitem__(self, idx):\n        size = (256, 256)\n        image_id = self.ids[idx]\n        image_idx = self.idx[idx]\n        \n        image_path = TEST_CROPED_DATA + f\"{image_id}_{image_idx}.jpg\"\n        \n        img = cv2.resize(cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB),size)\n\n        if self.tfms is not None:\n            augmented = self.tfms(image=img)\n            img = augmented['image']\n            \n        # we should normalize here\n        return img2tensor((img\/255.0 - mean)\/std), image_id\nds_test = IWildcamTestDataset(df_croped_img_ids_test)\ndl_test = DataLoader(ds_test,batch_size=32,shuffle=False,num_workers=NUM_WORKERS)\n\"\"\"\n## Load trained model\n\"\"\"\nmodel = enet_v2(backbone=\"tf_efficientnet_b0\", out_dim=205)\nmodel.to(DEVICE)\nmodel.load_state_dict(torch.load(f\"{epoch+1}_.pth\"))\nmodel.eval()\npred_categories = []\npred_img_ids = []\n\"\"\"\n## inference\n\"\"\"\nwith torch.no_grad():\n    for imgs, img_ids in tqdm(dl_test):\n        imgs = imgs.to(DEVICE)\n        \n        outputs = model(imgs)\n        output_labels = torch.argmax(outputs, dim=1).tolist()\n        pred_categories += output_labels\n        pred_img_ids += img_ids\npred = collections.defaultdict(list)\nfor category, img_id in zip(pred_categories, pred_img_ids):\n    pred[img_id].append(category)\npred\n\"\"\"\n# Create submit file\n\"\"\"\nsub = pd.read_csv(\"..\/input\/iwildcam2021-fgvc8\/sample_submission.csv\")\ncol_Predicted = [col for col in sub.columns if \"Predicted\" in col]\nwith open('..\/input\/iwildcam2021-fgvc8\/metadata\/iwildcam2021_train_annotations.json', encoding='utf-8') as json_file:\n    train_annotations =json.load(json_file)\ndf_categories = pd.DataFrame.from_records(train_annotations[\"categories\"])\n\"\"\"\nFor each image, count the number of each animal species and store them in the corresponding column.\n\"\"\"\nresults = []\n\nfor key in pred.keys():\n    c = collections.Counter(pred[key])\n    \n    res = []\n    cnts = [ 0 for i in range(205)]\n    for category, cnt in c.items():\n        cnts[category] = cnt\n    res += [key] + cnts[1:]\n    results.append(res)\n\"\"\"\nConvert to pandas dataframe.\n\"\"\"\nsub_tmp = pd.DataFrame(results, columns=sub.columns)\nsub_tmp.head()\nsub_tmp.to_csv(\".\/sub_tmp.csv\", index=False)\n\"\"\"\nAdd seq_id information to the counted results. iwildcam2021_test_information.json contains the mapping between the id of the image and the id of the sequence.\n\"\"\"\nwith open('..\/input\/iwildcam2021-fgvc8\/metadata\/iwildcam2021_test_information.json', encoding='utf-8') as json_file:\n    test_information =json.load(json_file)\n    \ndf_test_info = pd.DataFrame(test_information[\"images\"])[[\"id\", \"seq_id\"]]\ndf_test_info.head()\n\"\"\"\nTake right join on the image id.\n\"\"\"\nsub_tmp = sub_tmp.merge(df_test_info, left_on=\"Id\", right_on=\"id\", how=\"right\")\nsub_tmp.head()\n\"\"\"\nSince there are multiple lines for the same sequence ID. We should aggregate them to single line. In this case, we will choose the image with the highest number of animals shown and submit the animal species and the number of animals shown in that image.\n\"\"\"\nsum_counts = []\nfor i in range(len(sub_tmp)):\n    sum_counts.append(sum(sub_tmp.iloc[i][col_Predicted]))\nsub_tmp[\"total\"] =  sum_counts\nsub_tmp = sub_tmp.sort_values('total', ascending=False)\nsub_tmp = sub_tmp[~sub_tmp.duplicated(keep='first', subset='seq_id')].fillna(\"0\")\nsub_tmp\n\"\"\"\nI'll match the result to the sample submission format. I was told that the order of the rows is not related to the score, but we will match it just in case.\n\"\"\"\n# Since it was difficult to join the pandas series, I intentionally created an extra column.\nsub = sub.reset_index()\nsub = sub[[\"index\", \"Id\"]].merge(sub_tmp, left_on=\"Id\", right_on=\"seq_id\")\nsub = sub[[\"Id_x\"] + col_Predicted].rename(columns={\"Id_x\": \"Id\"})\nsub.to_csv(\"sub.csv\", index=False)\nsub.head()\n#If we don't delete them, csv files are buried and cannot be retrieved.\n!rm -r croped_images_train\n!rm -r croped_images_test","meta":"{'source': 'AI4Code', 'id': '3bfbf4d92ceb01'}"}
{"id":"65490","text":"# 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\n\"\"\"\n# Part 1: Method-ML Algorithams\n\"\"\"\n#ML Librarires \nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score, f1_score, confusion_matrix, precision_recall_curve, roc_curve\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nimport lightgbm as lgb\n\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.over_sampling import SMOTE\n\nimport seaborn as sns\nimport missingno as msno\nimport plotly.express as px\nimport  matplotlib.pyplot as plt\n\n\nplt.style.use('seaborn')\n%matplotlib inline\n\"\"\"\n# Data Read, Data Visualization,EDA Analysis,Data Pre-Processing,Data Splitting\n\"\"\"\n#Data Read\ndf=pd.read_csv('..\/input\/parkinsons-disease-classification\/pd_speech_features.csv',index_col=0, delimiter=',', skiprows=1)\n\ndf\ndf = df.loc[:,~df.columns.duplicated()]\ndf=df.sample(frac=1).reset_index(drop=True)\ndf.apply(lambda x: sum(x.isnull()),axis=0)\ndf.info()\ndf.describe()\n#Plotting data \nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport plotly.express as px\n#checking the target variable countplot\nsns.countplot(data=df,x = 'class',palette='plasma')\n\"\"\"\nImbalanced data distribution for target class.\n\"\"\"\nsns.set(rc={'figure.figsize':(10,8)})\nfig = sns.countplot(x = \"class\" , data = df)\nplt.xlabel(\"class\")\nplt.ylabel(\"Count\")\nplt.title(\"Class Count\")\nplt.grid(True)\nplt.show(fig)\n\nfrom sklearn.preprocessing import RobustScaler, StandardScaler\nfrom sklearn.model_selection import train_test_split\ndf.columns\n#Box Plotting All features distribution corresponding Target column\ni=1\nplt.figure(figsize=(40,40))\nfor c in df.columns[:49]:\n    plt.subplot(10,5,i)\n    plt.title(f\"Boxplot of {c}\",fontsize=16)\n    plt.yticks(fontsize=12)\n    plt.xticks(fontsize=12)\n    sns.boxplot(y=df[c],x=df['class'])\n    i+=1\nplt.show()\n#checking the target variable countplot\n\nplt.figure(figsize=(25,15))\nsns.set_style('white')\nsns.countplot(x='class', data = df, palette='GnBu')\nsns.despine(left=True)\n\"\"\"\nN.B. = I prefer to use models without outlier & imbalanced treatment, in many cases it can improve the model performance. But it also leads to change of information which might alter real\/practical situations\n\"\"\"\n\"\"\"\nData Splitting\n\"\"\"\ndataX=df.drop('class',axis=1)\ndataY=df['class']\nX_train,X_test,y_train,y_test=train_test_split(dataX,dataY,test_size=0.15,random_state=42)\nprint('X_train',X_train.shape)\nprint('X_test',X_test.shape)\nprint('y_train',y_train.shape)\nprint('y_test',y_test.shape)\ndims = X_train.shape[1]\nprint(dims, 'dims')\ndims = X_test.shape[1]\nprint(dims, 'dims')\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\ndef plot_roc_(false_positive_rate,true_positive_rate,roc_auc):\n    plt.figure(figsize=(5,5))\n    plt.title('Receiver Operating Characteristic')\n    plt.plot(false_positive_rate,true_positive_rate, color='red',label = 'AUC = %0.2f' % roc_auc)\n    plt.legend(loc = 'lower right')\n    plt.plot([0, 1], [0, 1],linestyle='--')\n    plt.axis('tight')\n    plt.ylabel('True Positive Rate')\n    plt.xlabel('False Positive Rate')\n    plt.show()\nfrom sklearn.neighbors  import KNeighborsClassifier\nfrom sklearn.model_selection import GridSearchCV,cross_val_score\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.metrics import roc_curve, auc\n\n\"\"\"\n# Part 1 for ML Algorithms\n\"\"\"\n\"\"\"\nWith PCA Analysis\n\"\"\"\nfrom sklearn.decomposition import PCA\npca=PCA(n_components=50)\nX_train=pca.fit_transform(X_train)\nX_test=pca.transform(X_test)\nprint('X_train',X_train.shape)\nprint('X_test',X_test.shape)\nprint('y_train',y_train.shape)\nprint('y_test',y_test.shape)\nfrom sklearn.linear_model import LogisticRegression\n\nlr=LogisticRegression(C=0.1,penalty='l2',random_state=42)\nlr.fit(X_train,y_train)\n\ny_pred=lr.predict(X_test)\n\n\ny_proba=lr.predict_proba(X_test)\n\nfalse_positive_rate, true_positive_rate, thresholds = roc_curve(y_test,y_proba[:,1])\nroc_auc = auc(false_positive_rate, true_positive_rate)\nplot_roc_(false_positive_rate,true_positive_rate,roc_auc)\n\n\nfrom sklearn.metrics import r2_score,accuracy_score\n\n#print('Hata Oran\u0131 :',r2_score(y_test,y_pred))\nprint('Accurancy Oran\u0131 :',accuracy_score(y_test, y_pred))\nprint(\"Logistic TRAIN score with \",format(lr.score(X_train, y_train)))\nprint(\"Logistic TEST score with \",format(lr.score(X_test, y_test)))\nprint()\n\ncm=confusion_matrix(y_test,y_pred)\nprint(cm)\nsns.heatmap(cm,annot=True)\nplt.show()\nknn=KNeighborsClassifier(n_jobs=2, n_neighbors=22)\nknn.fit(X_train,y_train)\n\ny_pred=knn.predict(X_test)\n\ny_proba=knn.predict_proba(X_test)\nfalse_positive_rate, true_positive_rate, thresholds = roc_curve(y_test,y_proba[:,1])\nroc_auc = auc(false_positive_rate, true_positive_rate)\nplot_roc_(false_positive_rate,true_positive_rate,roc_auc)\n\nfrom sklearn.metrics import r2_score,accuracy_score\n\nprint('Accurancy Oran\u0131 :',accuracy_score(y_test, y_pred))\nprint(\"KNN TRAIN score with \",format(knn.score(X_train, y_train)))\nprint(\"KNN TEST score with \",format(knn.score(X_test, y_test)))\nprint()\n\ncm=confusion_matrix(y_test,y_pred)\nprint(cm)\nsns.heatmap(cm,annot=True)\nplt.show()\n\"\"\"\n#  Withou PCA Analysis & Using Machine Learning Algorithms; Part 2 for ML Algorithms\n\"\"\"\nX_train,X_test,y_train,y_test=train_test_split(dataX,dataY,test_size=0.15,random_state=42)\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n# Fitting Logistic Regression To the training set \nfrom sklearn.linear_model import LogisticRegression   \n  \nclassifier = LogisticRegression(penalty='l2',solver='lbfgs',class_weight='balanced', max_iter=1000,random_state = 42) \nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict(X_test)\n\n# making confusion matrix between \n#  test set of Y and predicted value. \nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred) \nprint (cm)\nfrom sklearn.metrics import classification_report,accuracy_score\nprint(classification_report(y_test,y_pred))\nprint(\"Accuracy:\",accuracy_score(y_test, y_pred)*100)\n\nprint(y_pred)\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nnames = [ \"MLP-Neural Net\", \"Naive Bayes\", \"QDA\"]\n\nclassifiers = [\n    MLPClassifier(),\n    GaussianNB(),\n    QuadraticDiscriminantAnalysis()\n]\nfrom sklearn.model_selection import cross_val_score\n\n# iterate over classifiers\nresults = {}\nfor name, clf in zip(names, classifiers):\n    scores = cross_val_score(clf, X_train, y_train, cv=5)\n    results[name] = scores\nfor name, scores in results.items():\n    print(\"%20s | Accuracy: %0.2f%% (+\/- %0.2f%%)\" % (name, 100*scores.mean(), 100*scores.std() * 2))\nfrom sklearn.model_selection import GridSearchCV\n\nclf = SVC(kernel=\"linear\")\n\n# prepare a range of values to test\nparam_grid = [\n  {'C': [.01, .1, 1, 10], 'kernel': ['linear']},\n ]\n\ngrid = GridSearchCV(estimator=clf, param_grid=param_grid)\ngrid.fit(X_train, y_train)\nprint(grid)\n# summarize the results of the grid search\nprint(\"Best score: %0.2f%%\" % (100*grid.best_score_))\nprint(\"Best estimator for parameter C: %f\" % (grid.best_estimator_.C))\n\"\"\"\n# Part 3 for Algorithms\n\"\"\"\nseed = 42\n\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.model_selection import RandomizedSearchCV, cross_val_score, StratifiedKFold\nfrom sklearn.metrics import classification_report, roc_auc_score, roc_curve\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier,\\\n                            BaggingClassifier,VotingClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import make_pipeline, Pipeline\n# split the data into train and test\ndef split_data(X, Y, seed=42, train_size=0.8):\n    xtrain, xtest, ytrain, ytest = train_test_split(X, Y, train_size=train_size, random_state = seed, stratify=Y)\n    xtrain, xtest = preprocess(xtrain, xtest)\n    return (xtrain, xtest, ytrain, ytest)\n\n# preprocess the data for training\ndef preprocess(x1, x2=None):\n    sc = StandardScaler()\n    x1 = pd.DataFrame(sc.fit_transform(x1), columns=x1.columns)\n    if x2 is not None:\n        x2 = pd.DataFrame(sc.transform(x2), columns=x2.columns)\n        return (x1,x2)\n    return x1\n\n# for model evaluation and training\ndef eval_model(model, X, Y, seed=1):\n    xtrain, xtest, ytrain, ytest = split_data(X, Y)\n    model.fit(xtrain, ytrain)\n    \n    trainpred = model.predict(xtrain)\n    trainpred_prob = model.predict_proba(xtrain)\n    testpred = model.predict(xtest)\n    testpred_prob = model.predict_proba(xtest)\n    \n    print(\"Train ROC AUC : %.4f\"%roc_auc_score(ytrain, trainpred_prob, multi_class='ovr'))\n    print(\"\\nTrain classification report\\n\",classification_report(ytrain, trainpred))\n    \n    ### make a bar chart for displaying the wrong classification of one class coming in which other class\n    \n    print(\"\\nTest ROC AUC : %.4f\"%roc_auc_score(ytest, testpred_prob, multi_class='ovr'))\n    print(\"\\nTest classification report\\n\",classification_report(ytest, testpred))\n    \ndef plot_importance(columns, importance):\n    plt.bar(columns, importance)\n    plt.show()\n#Feature Extraction, Importance & Splitting\n\nY= df['class']\n\nX = df.drop(['class'],axis = 1)\nX_sc = preprocess(X)\n\"\"\"\n# Creating array of models\n\"\"\"\nmodel_logr = LogisticRegression(random_state=seed,n_jobs=-1)\nmodel_nb = GaussianNB()\nmodel_dt = DecisionTreeClassifier(random_state=seed)\nmodel_dt_bag = BaggingClassifier(model_dt, random_state=seed, n_jobs=-1)\nmodel_ada = AdaBoostClassifier(random_state=seed)\nmodel_gbc = GradientBoostingClassifier(random_state=seed)\nmodel_rf = RandomForestClassifier(random_state=seed, n_jobs=-1)\nmodel_xgb = XGBClassifier(random_state=seed)\nmodel_lgbm = LGBMClassifier(random_state=seed, n_jobs=-1)\nmodel_knn = KNeighborsClassifier(n_jobs=-1)\nmodels = []\nmodels.append(('LR',model_logr))\nmodels.append(('NB',model_nb))\nmodels.append(('DT',model_dt))\nmodels.append(('Bag',model_dt_bag))\nmodels.append(('Ada',model_ada))\nmodels.append(('GBC',model_gbc))\nmodels.append(('RF',model_rf))\nmodels.append(('XGB',model_xgb))\nmodels.append(('LGBM',model_lgbm))\nmodels.append(('KNN',model_knn))\n\"\"\"\n# Running the algorithms\n\"\"\"\ncv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)\n\nresults = []\nnames = []\n\nfor name, model in models:\n    scores = cross_val_score(model, X_sc, Y, scoring='f1_weighted', cv=cv, n_jobs=-1)\n    accuracy = scores.mean()\n    std = scores.std()\n    print(f\"{name} : Mean ROC {accuracy} STD:({std})\")\n    results.append(scores)\n    names.append(name)\nfig, ax = plt.subplots(figsize=(12,6))\nax.boxplot(results)\nax.set_xticklabels(names)\nplt.show()\n\"\"\"\n # Using Deep Neural Networks ; Part4\n\"\"\"\nprint(X_train.shape , y_train.shape)\nprint(X_test.shape , y_test.shape)\n#Keras\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\nfrom keras.layers import Dense, Dropout , BatchNormalization\nfrom keras.utils import np_utils\nfrom keras.optimizers import RMSprop, Adam\n\n#tf \nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nmodel = Sequential()\nmodel.add(Dense(64,input_dim=X_train.shape[1],activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\nmodel.add(Dense(128,activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\nmodel.add(Dense(256,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(512,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1,activation='sigmoid'))\n\nmodel.compile(loss = 'binary_crossentropy',\n              optimizer = 'adam',\n              metrics = ['accuracy'])\nmodel.summary()\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfBestModel = 'best_model.h5' \nearly_stop = EarlyStopping(monitor='val_loss', patience=2, verbose=1) \nbest_model = ModelCheckpoint(fBestModel, verbose=0, save_best_only=True)\n\nmodel.fit(X_train, y_train, validation_data = (X_test, y_test), epochs=100, \n          batch_size=62, verbose=True, callbacks=[best_model, early_stop])\nscore = model.evaluate(X_test, y_test, verbose=1)\nprint('Accuracy: ', score[1]*100)\nprint( 'loss:', score[0]*100)\nprediction = model.predict(X_test)\nprediction = (prediction > 0.5)\nfrom sklearn import metrics\nprint(metrics.classification_report(y_test, prediction))\n\"\"\"\n# Future Work & Suggestions : \n* If u  want to improve this work.You can focus on Class distribution ..\n* definetly it'll improve..Bcz class distribuion is imbalanced .\n* And do the hyperameter tuning for Deep Neural Networks\n\"\"\"\n\"\"\"\nResearch Projects Details; https:\/\/github.com\/sohel-ccse?tab=projects\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '78d0c387e948b7'}"}
{"id":"90436","text":"\"\"\"\n<h1><center>EDA + Submission Code<\/center><\/h1>\n                                                      \n<center><img src = \"https:\/\/miro.medium.com\/max\/576\/1*NzmIA9eUULy-hNyVOF9g5A.png\" width = \"750\" height = \"500\"\/><\/center>\n\"\"\"\n\"\"\"\n### <center>If you find this notebook useful and resourceful, do leave behind a upvote. I will be updating this notebook on a regular basis, so please check back once new version comes up.\u2620\ufe0f\u2620\ufe0f<\/center>\n\"\"\"\n\"\"\"\n## Evaluation Criteria\nWe will be using mean F score on the data set. F1-Score :-\n> In statistical analysis of binary classification, the F-score or F-measure is a measure of a test's accuracy. It is calculated from the precision and recall of the test, where the precision is the number of true positive results divided by the number of all positive results, including those not identified correctly, and the recall is the number of true positive results divided by the number of all samples that should have been identified as positive. Precision is also known as positive predictive value, and recall is also known as sensitivity in diagnostic binary classification.\n\n<center><img src = \"https:\/\/miro.medium.com\/max\/1530\/1*wUdjcIb9J9Bq6f2GvX1jSA.png\" width = \"550\" height = \"150\"\/><\/center>\n\n<center><img src = \"https:\/\/miro.medium.com\/max\/1872\/1*pOtBHai4jFd-ujaNXPilRg.png\" width = \"750\" height = \"250\"\/><\/center>\n\n> In pattern recognition, information retrieval and classification (machine learning), precision (also called positive predictive value) is the fraction of relevant instances among the retrieved instances, while recall (also known as sensitivity) is the fraction of relevant instances that were retrieved. Both precision and recall are therefore based on relevance.\n\n> Suppose a computer program for recognizing dogs (the relevant element) in photographs identifies eight dogs in a picture containing ten cats and twelve dogs, and of the eight it identifies as dogs, five actually are dogs (true positives), while the other three are cats (false positives). Seven dogs were missed (false negatives), and seven cats were correctly excluded (true negatives). The program's precision is then 5\/8 (true positives \/ all positives) while its recall is 5\/12 (true positives \/ relevant elements).\n\nwhere :-\n* TP = True Positive\n* FP = False Positive\n* TN = True Negative\n* FN = False Negative\n\"\"\"\nfrom IPython.core.display import display, HTML, Javascript\n\ndef ApplyCustomCSS():\n    return HTML(\"<style>\"+open(\"..\/input\/customcss\/custom_kaggle_forCommit.css\", \"r\").read()+\"<\/style>\")\n\nApplyCustomCSS()\n\"\"\"\nIf you wanna know more about modifying how a notebook look then please visit the Kaggle topic here [Click Here](https:\/\/www.kaggle.com\/discussion\/230082)\n\"\"\"\n\"\"\"\n## Data Set Information\n[train\/test].csv - the training set metadata. Each row contains the data for a single posting. Multiple postings might have the exact same image ID, but with different titles or vice versa.\n\nposting_id - the ID code for the posting.\nimage - the image id\/md5sum.\nimage_phash - a perceptual hash of the image.\ntitle - the product description for the posting.\nlabel_group - ID code for all postings that map to the same product. Not provided for the test set.\n\ntrain\/test images - the images associated with the postings.\n\n### Importing Dependencies\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport warnings as w\nfrom scipy import spatial\nfrom tqdm.notebook import tqdm\nimport random, math, cv2, os, string, re, gc\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom tensorflow.keras import layers as L\nimport tensorflow.keras as K\nfrom sklearn.model_selection import train_test_split\nimport cudf, cuml, cupy\nfrom cuml.neighbors import NearestNeighbors\nfrom cuml.feature_extraction.text import TfidfVectorizer\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS\n%matplotlib inline\nsns.set(style=\"whitegrid\")\n\n\nw.filterwarnings('ignore')\n\nTRAIN_BASE = '..\/input\/shopee-product-matching\/train_images\/'\nTEST_BASE = '..\/input\/shopee-product-matching\/test_images\/'\nSEED = 100\nIMG_SIZE = 444\nEPOCHS = 2\n\nsample_sub = pd.read_csv(\"..\/input\/shopee-product-matching\/sample_submission.csv\")\ntest = pd.read_csv(\"..\/input\/shopee-product-matching\/test.csv\")\ntrain = pd.read_csv(\"..\/input\/shopee-product-matching\/train.csv\")\n\n# train = pd.concat([train, train, train[:2000]], axis = 0)\n# train.reset_index(drop = True, inplace = True)\n# print(\"shape: \", train.shape)\n\ntrain.head()\nIS_GPU_AVAIL = tf.config.experimental.list_physical_devices('GPU')\nif IS_GPU_AVAIL:\n    try:\n        tf.config.experimental.set_virtual_device_configuration(IS_GPU_AVAIL[0],\n            [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*6.0)])\n        lgpu = tf.config.experimental.list_logical_devices('GPU')\n        \n    except RuntimeError as ex:\n        print(ex)\n        \nprint(f'Tensorflow GPU space 6GB GPU RAM')\nprint('RAPIDS GPU space 10GB GPU RAM')\ndef seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    tf.random.set_seed(seed)\n    \ndef process_data(df):\n    label_to_encoded = {idx:item for idx,item in enumerate(df.label_group.unique())}\n    encoded_to_label = {item:idx for idx,item in enumerate(df.label_group.unique())}\n    classes = df.label_group.nunique()\n    return label_to_encoded, encoded_to_label, classes\n\nseed_everything(SEED)\nlabel_to_encoded, encoded_to_label, NUM_CLASSES = process_data(train)\n\nfor col in train.columns:\n    print(f\"Number of unique {col} entries : \", train[col].nunique(), \" against the dataset of size \", train.shape)\n\"\"\"\n## Optimum Image Size\n\nFinding the average of height and width of all the images. As in the dataset the images size vary from 100x100 to something like 5000x5000, which is a vast range so taking the average should suffice because if a particular image is trimmed down too much the pixels start overlapping and is a image expanded to much then one pixel covers a very large portion \n\"\"\"\n# size = set()\n# for i in train['image'].values:\n#     img = cv2.imread(TRAIN_BASE+i)\n#     sh = tuple(img.shape)\n#     size.add(sh)\n\n# sizel = list(size)\n\n# ## sorting the size array based on width\n# sizel = sorted(sizel, key = lambda x: x[1])\n# IMG_SIZEavg = int(np.average([i for i in sizel]))\n\n# print(\"Taking the average of all the images sizes \", IMG_SIZEavg)\n# sizel[:5], sizel[-5:]\n# gc.collect()\nfor IMG_IDX in [1,2]: \n    temp_img = cv2.imread(TRAIN_BASE+train['image'].values[IMG_IDX])\n    ct = cv2.resize(temp_img, (IMG_SIZE, IMG_SIZE))\n\n    print(temp_img.shape, \" => \", ct.shape)\n\n    plt.subplot(1,2,1)\n    plt.imshow(temp_img)\n    plt.subplot(1,2,2)\n    plt.imshow(ct)\n    plt.show()\nif test.shape[0] == 3:\n    for IMG_IDX in range(3): \n        temp_img = cv2.imread(TEST_BASE+test['image'].values[IMG_IDX])\n        ct = cv2.resize(temp_img, (IMG_SIZE, IMG_SIZE))\n\n        print(temp_img.shape, \" => \", ct.shape)\n        print(\"Title : \", test['title'].values[IMG_IDX])\n        plt.imshow(temp_img)\n        plt.imshow(ct)\n        plt.show()\n\"\"\"\n## Now Lets do some digging\n\nGetting to know the data from the features prespective.\n\n### Label Sorting and Discovery\n\"\"\"\nbest10 = train['label_group'].value_counts().index.tolist()[:10]\nbest10_vals = train['label_group'].value_counts().tolist()[:10]\n\nplt.figure(figsize=(10, 6))\nsns.barplot(x=best10, y=best10_vals, palette=\"vlag\")\nplt.xticks(rotation=45)\nplt.xlabel(\"Label_Group\")\nplt.ylabel(\"Num of Images\")\nplt.title(\"Top 10 Labels by Images Count\")\nplt.show()\nworst10 = train['label_group'].value_counts().index.tolist()[-10:]\nworst10_vals = train['label_group'].value_counts().tolist()[-10:]\n\nplt.figure(figsize=(10, 6))\nsns.barplot(x=worst10, y=worst10_vals, palette=\"rocket\")\nplt.xticks(rotation=45)\nplt.xlabel(\"Label_Group\")\nplt.ylabel(\"Num of Images\")\nplt.title(\"10 Worst Labels by Images Count\")\nplt.show()\nfor item in train.label_group.unique()[3001:3004]: \n    df_temp = train[train.label_group == item]\n    \n    cols = df_temp.shape[0]\n    fig = plt.figure(figsize=(10,20))\n    for idx,(index,row) in enumerate(df_temp.iterrows()):\n        temp_img = cv2.imread(TRAIN_BASE+row.image)\n        ct = cv2.resize(temp_img, (IMG_SIZE, IMG_SIZE))\n        plt.subplot(1,cols,idx+1)\n        plt.imshow(temp_img)\n        plt.axis('off')\n    \n    print('\\033[1m' + '\\033[36m'+\"Group Label\"+'\\033[0m', item)\n    print('\\033[1m' + '\\033[32m'+\"Number of items in Group \"+'\\033[0m', cols)\n    print('\\033[1m' + '\\033[33m'+\"The Group Label Titles are \"+'\\033[0m', df_temp.title.to_list())\n    plt.show()\nfor IMG_IDX in [1,2]: \n    temp_img = cv2.imread(TRAIN_BASE+train['image'].values[IMG_IDX*1000])\n    dims = np.shape(temp_img)\n    ct = np.reshape(temp_img, (dims[0] * dims[1], dims[2]))\n\n    print(dims, \" => \", ct.shape)\n    plt.title(train['label_group'].values[IMG_IDX*1000])\n    sns.distplot(ct[:,0], bins=15)\n    sns.distplot(ct[:,1], bins=15)\n    sns.distplot(ct[:,2], bins=15)\n    plt.show()\n\"\"\"\n### Learning through and about NLP\n#### Label Distribution\n\"\"\"\ndef plot_hist(col, xlabel, ylabel, title):\n    ax = plt.subplots(figsize =(10, 5));\n    ax = sns.distplot(temp_nlp[col], kde=True);\n    ax.set_ylabel(ylabel, size=15)\n    ax.set_xlabel(xlabel, size=15)\n    ax.set_title(title, size=20)\n    plt.show()\n    \ntemp_nlp = train.copy()\ntemp_nlp['title_len'] = temp_nlp['title'].apply(lambda x: len(x))\ntemp_nlp['title_word_count'] =temp_nlp[\"title\"].apply(lambda x: len(str(x).split(\" \")))\ntemp_nlp['title_char_count'] = temp_nlp[\"title\"].apply(lambda x: sum(len(word) for word in str(x).split(\" \")))\ntemp_nlp['title_avg_word_length'] = temp_nlp['title_char_count'] \/ temp_nlp['title_word_count']\ngroups = temp_nlp.label_group.value_counts()\n\nplt.figure(figsize=(20,5))\nplt.plot(np.arange(len(groups)),groups.values)\nplt.ylabel('Duplicate Count',size=14)\nplt.xlabel('Index of Unique Item',size=14)\nplt.title('Duplicate Count vs. Unique Item Count',size=16)\nplt.show()\nwordcloud = WordCloud(background_color='white', stopwords=STOPWORDS, width=2560, height=1440).generate(' '.join(train['title']))\n\nax = plt.subplots(figsize=(15, 15), facecolor='w')\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.tight_layout(pad=0)\nfor col,x,y,title in [('title_len', 'Length Of Title', 'Num Observations', 'Distribution of Title Length'),\n          ('title_word_count', 'Num Words', 'Num Observations', 'Distribution of Word Count for Title'),\n          ('title_char_count', 'Num Characters', 'Num Observations', 'Distribution of Characters for Title'),\n          ('title_avg_word_length', 'Avg Word Length', 'Num Observations', 'Distribution of Avg Word Length for Title')]:\n    plot_hist(col,x,y,title)\ndel temp_nlp\n\"\"\"\n## Lets Just Build the model\n\"\"\"\nPREDICT_SCORE = True\nTRAINING = True\nif len(test) > 3:\n    TRAIN_BASE = TEST_BASE\n    ## Right now i am creating a dummy label column for test data later on i will predict this column as well\n    dummy_label_group = list(train.label_group.values)*3\n    test['label_group'] = dummy_label_group[:test.shape[0]].copy()\n    train = test\n    PREDICT_SCORE = False\n    TRAINING = False\ndel test\nclass DataGenerator(K.utils.Sequence):\n    def __init__(self, df, batchSize, code_to_labels, filepath = TRAIN_BASE, shuffle = False, \n                 img_size = IMG_SIZE, classes = NUM_CLASSES):\n        self.df = df\n        self.shuffle = shuffle\n        self.indexes = np.arange(len(df))\n        self.path = filepath\n        self.batch = batchSize \n        self.img_size = IMG_SIZE\n        self.label_dict = code_to_labels\n        self.n_classes = classes\n        \n    def __len__(self):\n        '''Total number of steps in a epoch'''\n        return int(np.floor(self.df.shape[0]\/self.batch))\n    \n    def on_epoch_end(self):\n        if self.shuffle:\n            np.random.shuffle(self.indexes)\n            \n    def __getitem__(self, index):\n        '''Generate One batch of files'''\n        indexes = self.indexes[index*self.batch:(index+1)*self.batch]\n        temp_df = self.df.iloc[indexes]\n        X = np.zeros(((len(indexes), self.img_size, self.img_size, 3)))\n        Y = np.zeros((self.batch, 1))\n        for idx,(index, row) in enumerate(temp_df.iterrows()):\n            img = cv2.imread(self.path + row.image)\n            X[idx,] = cv2.resize(img, (self.img_size, self.img_size)) \/ 255\n            Y[idx,] = self.label_dict[row.label_group]\n        return X, tf.keras.utils.to_categorical(Y, num_classes=self.n_classes)\n\ndef f1_score(y_true, y_pred):\n    y_true = y_true.apply(lambda x: set(x.split()))\n    y_pred = y_pred.apply(lambda x: set(x.split()))\n    intersection = np.array([len(x[0] & x[1]) for x in zip(y_true, y_pred)])\n    len_y_pred = y_pred.apply(lambda x: len(x)).values\n    len_y_true = y_true.apply(lambda x: len(x)).values\n    f1 = 2 * intersection \/ (len_y_pred + len_y_true)\n    return f1\n\ndef clean(text):\n    text = ''.join([k for k in text if k not in string.punctuation])\n    text = str(text).lower()\n    text = re.sub('[^a-zA-Z]', ' ', text)\n    text = re.sub(' +', ' ', text)\n    emoji_pattern = re.compile(\"[\"\n                               u\"\\U0001F600-\\U0001F64F\"  \n                               u\"\\U0001F300-\\U0001F5FF\"  \n                               u\"\\U0001F680-\\U0001F6FF\"  \n                               u\"\\U0001F1E0-\\U0001F1FF\"  \n                               \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    return text\n\n\ndef train_test_split_data(df, features, label, test_size = 0.33):\n    train_x, val_x, train_y, val_y = train_test_split(df[features], df[label], test_size = test_size,\n                                                      random_state = SEED, shuffle = True, stratify = df[label])\n    return train_x, val_x, train_y, val_y\n\ndef learning_rate_scheduler():\n    starting_pt_lr   = 0.0001\n    exp_decay = 0.1\n    def lrfn(epoch):\n        if epoch < 5:\n            return starting_pt_lr\n        else:\n            return starting_pt_lr * math.exp(-exp_decay * epoch)\n    lr = K.callbacks.LearningRateScheduler(lrfn, verbose = True)\n    return lr\n\ntqdm.pandas()\ntrain['title'] = train['title'].progress_apply(clean)\ntrain_x, val_x, train_y, val_y = train_test_split_data(train, ['image'], ['label_group'])\ntrain_x['label_group'] = train_y\ntrain_x.reset_index(inplace = True, drop = True)\nval_x['label_group'] = val_y\nval_x.reset_index(inplace = True, drop = True)\n\nparams = {'batchSize': 5,\n          'code_to_labels': encoded_to_label,\n          'filepath': TRAIN_BASE,\n          'shuffle': False,\n          'img_size' : IMG_SIZE,\n          'classes' : NUM_CLASSES}\n\ntraining_generator = DataGenerator(train_x, **params)\nvalidation_generator = DataGenerator(val_x, **params)\ncomplete_generator = DataGenerator(train[['image', 'label_group']], **params)\n\ngc.collect()\ndef get_multi_pretrained_model(pretrained_layer1, \n                               pretrained_layer2, \n                               classes = NUM_CLASSES):\n    \n    inp = L.Input(shape = (IMG_SIZE, IMG_SIZE, 3))\n    \n    ## PretrainedLayer 1\n    a = pretrained_layer1(inp)\n    a = L.GlobalAveragePooling2D()(a)\n    a = L.Dense(750, activation = 'relu')(a)\n    a = L.BatchNormalization()(a)\n    \n    ## PretrainedLayer2\n    b = pretrained_layer2(inp)\n    b = L.GlobalAveragePooling2D()(b)\n    b = L.Dense(750, activation = 'relu')(b)\n    b = L.BatchNormalization()(b)\n    \n    x1 = L.concatenate([a,b])\n    x = L.Dense(2048, activation = 'relu')(x1)\n    out = L.Dense(classes, activation = 'softmax')(x)\n\n    model = K.models.Model(inputs = inp, \n                           outputs = out)\n    image_embeddings = K.models.Model(inputs = inp, \n                           outputs = x1)\n    opt = K.optimizers.Adam(learning_rate = 0.0001)\n\n    model.compile(loss='categorical_crossentropy', \n                  optimizer=opt, \n                  metrics=['accuracy'])\n    return model, image_embeddings\n\npretrained_layer1 = K.applications.EfficientNetB0(include_top=False, \n                                                  weights='imagenet', \n                                                  input_shape=(IMG_SIZE, IMG_SIZE, 3))\npretrained_layer2 = K.applications.InceptionV3(include_top=False, \n                                               weights='imagenet', \n                                               input_shape=(IMG_SIZE, IMG_SIZE, 3))\n\nmodel_pretranied, image_embeddings = get_multi_pretrained_model(pretrained_layer1, \n                                                                pretrained_layer2)\n\nimage_embeddings.summary()\nif TRAINING: \n    checkpt = tf.keras.callbacks.ModelCheckpoint(f'model_weights_{SEED}.h5', \n                                                 monitor='val_loss', \n                                                 verbose=1, \n                                                 save_best_only=True,\n                                                 save_weights_only=True, \n                                                 mode='min')\n    checkpointeffnet = tf.keras.callbacks.ModelCheckpoint('best_model_eff_net.h5', \n                                                          monitor='val_loss', mode='min', save_best_only=True,verbose=1)\n    # Train model on dataset\n    model_pretranied.fit_generator(generator = training_generator, \n                        epochs = EPOCHS,\n                        validation_data=validation_generator,\n                        callbacks = [learning_rate_scheduler(), checkpt])\nelse:\n    model.load_weights(f'competition_data\/model_weights_{SEED}.h5')\n    \nimage_embeddings = image_embeddings.predict(complete_generator, \n                                batch_size=10, \n                                verbose = 0)\n\"Image embedding shape is :- \", image_embeddings.shape\nx_tr = train['title']\ny_tr = train['label_group']\ntokenizer = Tokenizer()\n\ntokenizer.fit_on_texts(list(x_tr))\n\nx_tr_seq  = tokenizer.texts_to_sequences(x_tr) \nx_tr_seq  = pad_sequences(x_tr_seq, maxlen=50)\n\nsize_of_vocabulary=len(tokenizer.word_index) + 1 # +1 for padding\nprint(size_of_vocabulary)\nembeddings_index = {}\nwith open(\"..\/input\/pretrainedfiles\/model.txt\", encoding='utf-8', errors='ignore') as f:\n    for line in f:\n        word, coefs = line.split(maxsplit=1)\n        coefs = np.fromstring(coefs, \"f\", sep=\" \")\n        embeddings_index[word] = coefs\n\nprint(\"Found %s word vectors.\" % len(embeddings_index))\nembedding_matrix = np.zeros((size_of_vocabulary, 100))\n\nfor word, i in tokenizer.word_index.items():\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None:\n        embedding_matrix[i] = embedding_vector\n        \ndel embeddings_index\ndef get_text_model():\n    inp = K.layers.Input(shape=(50,))\n    embed = K.layers.Embedding(size_of_vocabulary,100,weights=[embedding_matrix],trainable=True)(inp)\n    lstm = K.layers.LSTM(16,return_sequences=True,dropout=0.2)(embed)\n    pool = K.layers.GlobalMaxPooling1D()(lstm)\n\n    dense1 = K.layers.Dense(512,activation='relu')(pool)\n    out = K.layers.Dense(NUM_CLASSES,activation='sigmoid')(dense1)\n    \n    model = K.models.Model(inputs = inp, outputs = out)\n    embedding_model = K.models.Model(inputs = inp, outputs = pool)\n    #Add loss function, metrics, optimizer\n    model.compile(optimizer='adam', loss='binary_crossentropy',metrics=[\"acc\"]) \n    return model, embedding_model\n\nearlystopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=3)  \ncheckpoint = tf.keras.callbacks.ModelCheckpoint('best_model.h5', monitor='val_acc', mode='max', save_best_only=True,verbose=1)\n\nmodel_text, embedding_model = get_text_model()\n\n# embedding_model.summary()\n# model_text.fit(np.array(x_tr_seq),tf.keras.utils.to_categorical(y_tr),\n#                     batch_size=2,epochs=2,\n# #                     validation_data=(np.array(x_val_seq),np.array(y_val)),\n#                     verbose=1,callbacks=[earlystopping, checkpoint])\ndef get_text_predictions(df, max_features = 25_000):\n    \n    model = TfidfVectorizer(stop_words = 'english', binary = True, max_features = max_features)\n    text_embeddings = model.fit_transform(df_cu['title']).toarray()\n    preds = []\n    CHUNK = 1024*4\n\n    print('Finding similar titles...')\n    CTS = len(df)\/\/CHUNK\n    if len(df)%CHUNK!=0: CTS += 1\n    for j in range( CTS ):\n\n        a = j*CHUNK\n        b = (j+1)*CHUNK\n        b = min(b,len(df))\n        print('chunk',a,'to',b)\n\n        cts = cupy.matmul( text_embeddings, text_embeddings[a:b].T).T\n\n        for k in range(b-a):\n            IDX = cupy.where(cts[k,]>0.75)[0]\n            o = df.iloc[cupy.asnumpy(IDX)].posting_id.values\n            preds.append(\" \".join(o))\n    \n    del model,text_embeddings\n    gc.collect()\n    return preds\n\ndf_cu = cudf.DataFrame(train)\ntext_preds = get_text_predictions(train)\ndef combine_preds(x):\n    all_combined = x['image_preds']+\" \"+ x['text_preds']\n    return ' '.join( set(all_combined.split(\" \")) )\n\ndef get_nearest_neighors(df, embeds, n = 50, image = True, predict_score = PREDICT_SCORE):\n    model = NearestNeighbors(n_neighbors = n)\n    model.fit(embeds)\n    dist_arr, idx_arr = model.kneighbors(embeds)\n    if predict_score:\n        scores = []\n        if image:\n            print(\"Predicting for image\")\n            scores = np.arange(0,10.0,0.5)\n        else:\n            print(\"Predicting for text\")\n            scores = np.arange(20,35,0.5)\n            \n        allscores = []\n        for th in scores:\n            preds = []\n            for idx in range(embeds.shape[0]):\n                index_clear_of_th = np.where(dist_arr[idx,] < th)[0]\n                preds.append(' '.join(df.posting_id.iloc[idx_arr[idx,index_clear_of_th]].values))\n            \n            df[\"pred_values\"] = preds\n            df[\"f1_score\"] = f1_score(df['matches'], df['pred_values'])\n            print(f\"f1 Score for the threshold {th} is {df['f1_score'].mean()}\")\n            allscores.append(df['f1_score'].mean())\n        \n        score_df = pd.DataFrame({\"All_Scores\" : allscores, \"Thresholds\" : scores})\n        best_record = score_df[score_df.All_Scores == score_df.All_Scores.max()]\n        print(f\"Best iteration is with score {best_record.All_Scores.values} and threshold {best_record.Thresholds.values}\")\n        \n        preds = []\n        th = best_record.Thresholds.values[0]\n            \n        for idx in range(embeds.shape[0]):\n            index_clear_of_th = np.where(dist_arr[idx,] < th)[0]\n            preds.append(\" \".join(df.posting_id.iloc[idx_arr[idx,index_clear_of_th]].values))\n            \n    else:\n        preds = []\n        th = 0\n        if image:\n            print(\"Predicting for image\")\n            th = 2.4\n        else:\n            print(\"Predicting for text\")\n            th = 24.0\n            \n        for idx in range(embeds.shape[0]):\n            index_clear_of_th = np.where(dist_arr[idx,] < th)[0]\n            preds.append(\" \",join(df.posting_id.iloc[idx_arr[idx,index_clear_of_th]].values))\n            \n    return df, preds\n\nif PREDICT_SCORE:\n    tmp = train.groupby(['label_group'])['posting_id'].unique().to_dict()\n    train['matches'] = train['label_group'].map(tmp)\n    train['matches'] = train['matches'].apply(lambda x: ' '.join(x))\n    \ntrain, image_preds = get_nearest_neighors(train, image_embeddings, n = 50, image = True)\n# train, text_preds = get_nearest_neighors(train, text_embeddings, n = 50, image = False)\n\ntrain['image_preds'] = image_preds\ntrain['text_preds'] = text_preds\ntrain['matches'] = train.apply(combine_preds, axis = 1)\ntrain[['posting_id', 'matches']].to_csv('submission.csv', index = False)","meta":"{'source': 'AI4Code', 'id': 'a5d9ac7f1f42ab'}"}
{"id":"137214","text":"\"\"\"\n## Importing and understanding the data \n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\ndf = pd.read_csv('..\/input\/hr-analytics\/HR_comma_sep.csv')\ndf.head(10)\ndf.info()\ndf.describe()\n\"\"\"\n## Exploratory Data Analysis\n\nNow do some exploratory data analysis to figure out which variables have direct and clear impact on employee retention (ie, whether they leave the company or continue to work) \n\"\"\"\ndf['left'].describe()\nprint(\"No of employees lost by the company: \", df[df['left']==1].shape[0])\nprint(\"No of employees retained by the company: \", df[df['left']==0].shape[0])\ndf.groupby('left').mean() \nimport seaborn as sns\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\nsns.heatmap(df.corr(), linewidths = 2, cmap=\"plasma\", annot=True)\ndf1 = df[['satisfaction_level', 'last_evaluation', 'number_project',\n       'average_montly_hours', 'time_spend_company', 'left']]\n\"\"\"\n### Heatmap of continuous value attributes only\n\"\"\"\nfig, ax = plt.subplots(1, 1, figsize=(10, 5))\nsns.heatmap(df1.corr(), linewidths = 2, cmap=\"plasma\", annot=True)\n\"\"\"\n### Pairplot with Employee Retention as hue\n\"\"\"\nsns.pairplot(df, hue=\"left\")\n\"\"\"\nWe see that the plots made by each of the two from the following classifies Employees Retained from Employees left:\n- satisfaction level\n- average monthly hours\n- last evaluation\n\"\"\"\n\"\"\"\n## Understanding impact of employee salaries on retention using bar charts\n\"\"\"\n\"\"\"\n### A. Comparing Employee Retention with Salary\n\"\"\"\ndf1 = df[['left','salary']]\nleft = df1[df['left']==1].salary.value_counts()\nretained = df1[df['left']==0].salary.value_counts()\nleft_percent = left \/ (left + retained)\nretain_percent = retained \/ (left + retained)\ncounts1 = {\"retained\":retained, \"left\":left, \"retained_percent\":retain_percent, \"left_percent\":left_percent}\ncounts1 = pd.DataFrame(counts1)\ncounts1\nx = counts1.index\ny1 = counts1.retained\ny2 = counts1.left\n\nf, axs = plt.subplots(2,2,figsize=(15,5))\nplt.subplot(1, 2, 1)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Number of Employee Retention grouped by Salary\")\nplt.xlabel(\"Salary\")\nplt.ylabel(\"Number of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\ny1 = counts1.retained_percent\ny2 = counts1.left_percent\n\nplt.subplot(1, 2, 2)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Percent of Employee Retention grouped by Salary\")\nplt.xlabel(\"Salary\")\nplt.ylabel(\"Percent of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\n\nplt.show()\n\"\"\"\nHere, we see that the lower the salary, the more number of employees left their job at the company\n\"\"\"\n\"\"\"\n## Plotting bar charts to show the correlation between department and employee retention\n\"\"\"\n\"\"\"\n### B. Comparing Employee Retention with Department\n\"\"\"\ndf1 = df[['left','Department']]\nleft = df1[df['left']==1].Department.value_counts()\nretained = df1[df['left']==0].Department.value_counts()\nleft_percent = left \/ (left + retained)\nretain_percent = retained \/ (left + retained)\ncounts2 = {\"retained\":retained, \"left\":left, \"retained_percent\":retain_percent, \"left_percent\":left_percent}\ncounts2 = pd.DataFrame(counts2)\ncounts2\nx = counts2.index\ny1 = counts2.retained\ny2 = counts2.left\n\nf, axs = plt.subplots(2,2,figsize=(15,5))\nplt.subplot(1, 2, 1)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Number of Employee Retention grouped by Department\")\nplt.xlabel(\"Department\")\nplt.ylabel(\"Number of Employees Retained\/Left\")\nplt.xticks(rotation=80)\nplt.legend(['retained', 'left'])\n\ny1 = counts2.retained_percent\ny2 = counts2.left_percent\n\nplt.subplot(1, 2, 2)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Percent of Employee Retention grouped by Department\")\nplt.xlabel(\"Department\")\nplt.ylabel(\"Percent of Employees Retained\/Left\")\nplt.xticks(rotation=80)\nplt.legend(['retained', 'left'])\n\nplt.show()\n\"\"\"\nHere, we see that the percentage of Employees retained are slightly greater for the Department Management and RandD\n\"\"\"\n\"\"\"\n### C. Comparing Employee Retention with Work Accident\n\"\"\"\ndf1 = df[['left','Work_accident']]\nleft = df1[df['left']==1].Work_accident.value_counts()\nretained = df1[df['left']==0].Work_accident.value_counts()\nleft_percent = left \/ (left + retained)\nretain_percent = retained \/ (left + retained)\ncounts3 = {\"retained\":retained, \"left\":left, \"retained_percent\":retain_percent, \"left_percent\":left_percent}\ncounts3 = pd.DataFrame(counts3)\ncounts3.index = [\"No\", \"Yes\"]\ncounts3\nx = counts3.index\ny1 = counts3.retained\ny2 = counts3.left\n\nf, axs = plt.subplots(2,2,figsize=(15,5))\nplt.subplot(1, 2, 1)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Number of Employee Retention grouped by Work Accident\")\nplt.xlabel(\"Work Accident\")\nplt.ylabel(\"Number of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\n\ny1 = counts3.retained_percent\ny2 = counts3.left_percent\n\nplt.subplot(1, 2, 2)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Percent of Employee Retention grouped by Work Accident\")\nplt.xlabel(\"Work Accident\")\nplt.ylabel(\"Percent of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\n\nplt.show()\n\"\"\"\n### D. Comparing Employee Retention with promotion in last 5 years\n\"\"\"\ndf1 = df[['left','promotion_last_5years']]\nleft = df1[df['left']==1].promotion_last_5years.value_counts()\nretained = df1[df['left']==0].promotion_last_5years.value_counts()\nleft_percent = left \/ (left + retained)\nretain_percent = retained \/ (left + retained)\ncounts4 = {\"retained\":retained, \"left\":left, \"retained_percent\":retain_percent, \"left_percent\":left_percent}\ncounts4 = pd.DataFrame(counts4)\ncounts4.index = [\"No\", \"Yes\"]\ncounts4\nx = counts4.index\ny1 = counts4.retained\ny2 = counts4.left\n\nf, axs = plt.subplots(2,2,figsize=(15,5))\nplt.subplot(1, 2, 1)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Number of Employee Retention grouped by Promotion in last 5 years\")\nplt.xlabel(\"Work Accident\")\nplt.ylabel(\"Number of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\n\ny1 = counts4.retained_percent\ny2 = counts4.left_percent\n\nplt.subplot(1, 2, 2)\nplt.bar(x, y1, color='r')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.title(\"Percent of Employee Retention grouped by Promotion in last 5 years\")\nplt.xlabel(\"Work Accident\")\nplt.ylabel(\"Percent of Employees Retained\/Left\")\nplt.legend(['retained', 'left'])\n\nplt.show()\n\"\"\"\nThough the number of Employees retained are higher when they have gotten a promotion in the last 5 years, there are very few Employees with promotions\n\"\"\"\n\"\"\"\n### E. Comparing Employee Retention with continuous valued attributes, namely:\n\n1. satisfaction_level\n2. last_evaluation\n3. average_montly_hours\n4. time_spend_company\n5. sns.boxplot(data = df, y='number_project', x='left')\n\"\"\"\nsns.boxplot(data = df, y='satisfaction_level', x='left')\nbox=sns.boxplot(data = df, y='last_evaluation', x='left')\nsns.boxplot(data = df, y='average_montly_hours', x='left')\nsns.boxplot(data = df, y='time_spend_company', x='left')\nsns.boxplot(data = df, y='number_project', x='left')\n\"\"\"\nThus, we see that Satisfaction_level has a significant influence on Employee Retention\n\"\"\"\n\"\"\"\n## Building a Logistic Regression Model\n\"\"\"\ndf1 = df[['salary', 'Department','satisfaction_level', 'average_montly_hours', 'promotion_last_5years','left']]\ndf1 = pd.get_dummies(df1, columns = ['Department','salary'])\ndf1.head()\nX = np.asarray(df1.loc[:, df1.columns != 'left'])\ny = np.asarray(df1.loc[:, df1.columns == 'left'])\nfrom sklearn import preprocessing\n# scaler = preprocessing.StandardScaler().fit(X)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, classification_report\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,random_state = 1)\nfrom sklearn.metrics import roc_auc_score,roc_curve\nfrom sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression(max_iter=1000)\nmodel.fit(X_train,y_train.ravel())\nlog_pred = model.predict(X_test)\n\"\"\"\n## Evaluation of the model\n\"\"\"\nprint(\" accuracy = \", accuracy_score(y_test, log_pred)) \nprint(\" f1_score = \", f1_score(y_test, log_pred))\nprint(confusion_matrix(y_test, log_pred))\nprint(classification_report(y_test, log_pred))\nfrom sklearn.metrics import roc_auc_score,roc_curve\nmodel = LogisticRegression(max_iter=1000)\nmodel.fit(X_train,y_train.ravel())\n\ny_pred=model.predict(X_test)\ny_proba=model.predict_proba(X_test)\n\nns_probs = [0 for _ in range(len(y_test))]\nns_auc = roc_auc_score(y_test, ns_probs)\nprint(\"ROC AUC SCORE: \",roc_auc_score(y_test, y_proba[:, 1]))\nns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)\nlr_fpr, lr_tpr, _ = roc_curve(y_test, y_proba[:,1])\nplt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')\nplt.plot(lr_fpr, lr_tpr, marker='.', label='Logistic')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')","meta":"{'source': 'AI4Code', 'id': 'fc316b601f2c64'}"}
{"id":"78135","text":"\"\"\"\n[Lesson Video Link](https:\/\/course.fast.ai\/videos\/?lesson=4)\n\n[Lesson resources and updates](https:\/\/forums.fast.ai\/t\/lesson-4-official-resources-and-updates\/30317)\n\n[Lesson chat](https:\/\/forums.fast.ai\/t\/lesson-4-in-class-discussion\/30318\/12)\n\n[Further discussion thread](https:\/\/forums.fast.ai\/t\/lesson-4-advanced-discussion\/30319)\n\nNote: This is a mirror of the FastAI Lesson 4 Nb. \nPlease thank the amazing team behind fast.ai for creating these, I've merely created a mirror of the same here\nFor complete info on the course, visit course.fast.ai\n\"\"\"\nfrom fastai import *\nfrom fastai.collab import *\nfrom fastai.tabular import *\n\"\"\"\n## Collaborative filtering example\n\"\"\"\n\"\"\"\n`collab` models use data in a `DataFrame` of user, items, and ratings.\n\"\"\"\nuser,item,title = 'userId','movieId','title'\npath = untar_data(URLs.ML_SAMPLE)\npath\nratings = pd.read_csv(path\/'ratings.csv')\nratings.head()\n\"\"\"\nThat's all we need to create and train a model:\n\"\"\"\ndata = CollabDataBunch.from_df(ratings, seed=42)\ny_range = [0,5.5]\nlearn = collab_learner(data, n_factors=50, y_range=y_range)\nlearn.fit_one_cycle(3, 5e-3)\n\"\"\"\n## Movielens 100k\n\"\"\"\n\"\"\"\nLet's try with the full Movielens 100k data dataset, available from http:\/\/files.grouplens.org\/datasets\/movielens\/ml-100k.zip\n\"\"\"\npath=Path('..\/input\/')\nratings = pd.read_csv(path\/'u.data', delimiter='\\t', header=None,\n                      names=[user,item,'rating','timestamp'])\nratings.head()\nmovies = pd.read_csv(path\/'u.item',  delimiter='|', encoding='latin-1', header=None,\n                    names=[item, 'title', 'date', 'N', 'url', *[f'g{i}' for i in range(19)]])\nmovies.head()\nlen(ratings)\nrating_movie = ratings.merge(movies[[item, title]])\nrating_movie.head()\ndata = CollabDataBunch.from_df(rating_movie, seed=42, pct_val=0.1, item_name=title)\ndata.show_batch()\ny_range = [0,5.5]\nlearn = collab_learner(data, n_factors=40, y_range=y_range, wd=1e-1)\nlearn.lr_find()\nlearn.recorder.plot(skip_end=15)\nlearn.fit_one_cycle(5, 5e-3)\nlearn.save('dotprod')\n\"\"\"\nHere's [some benchmarks](https:\/\/www.librec.net\/release\/v1.3\/example.html) on the same dataset for the popular Librec system for collaborative filtering. They show best results based on RMSE of 0.91, which corresponds to an MSE of `0.91**2 = 0.83`.\n\"\"\"\n\"\"\"\n## Interpretation\n\"\"\"\n\"\"\"\n### Setup\n\"\"\"\nlearn.load('dotprod');\nlearn.model\ng = rating_movie.groupby(title)['rating'].count()\ntop_movies = g.sort_values(ascending=False).index.values[:1000]\ntop_movies[:10]\n\"\"\"\n### Movie bias\n\"\"\"\nmovie_bias = learn.bias(top_movies, is_item=True)\nmovie_bias.shape\nmean_ratings = rating_movie.groupby(title)['rating'].mean()\nmovie_ratings = [(b, i, mean_ratings.loc[i]) for i,b in zip(top_movies,movie_bias)]\nitem0 = lambda o:o[0]\nsorted(movie_ratings, key=item0)[:15]\nsorted(movie_ratings, key=lambda o: o[0], reverse=True)[:15]\n\"\"\"\n### Movie weights\n\"\"\"\nmovie_w = learn.weight(top_movies, is_item=True)\nmovie_w.shape\nmovie_pca = movie_w.pca(3)\nmovie_pca.shape\nfac0,fac1,fac2 = movie_pca.t()\nmovie_comp = [(f, i) for f,i in zip(fac0, top_movies)]\nsorted(movie_comp, key=itemgetter(0), reverse=True)[:10]\nsorted(movie_comp, key=itemgetter(0))[:10]\nmovie_comp = [(f, i) for f,i in zip(fac1, top_movies)]\nsorted(movie_comp, key=itemgetter(0), reverse=True)[:10]\nsorted(movie_comp, key=itemgetter(0))[:10]\nidxs = np.random.choice(len(top_movies), 50, replace=False)\nidxs = list(range(50))\nX = fac0[idxs]\nY = fac2[idxs]\nplt.figure(figsize=(15,15))\nplt.scatter(X, Y)\nfor i, x, y in zip(top_movies[idxs], X, Y):\n    plt.text(x,y,i, color=np.random.rand(3)*0.7, fontsize=11)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '8f92f4b147190f'}"}
{"id":"123778","text":"\"\"\" # COVID-19 Open Research Dataset (CORD-19) Analysis ![CORD-19.png](attachment:CORD-19.png) *An example of result snippet is shown below, For each tasks a sperate notebook is created with answers to each questions in a task added to a excel* \"\"\" \"\"\" **TASK 1:** Task Details What do we know about COVID-19 risk factors? What have we learned from epidemiological studies? Specifically, we want to know what the literature reports about: 1. Data on potential risks factors * Smoking, pre-existing pulmonary disease * Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities * Neonates and pregnant women * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. 2. Transmission dynamics of the virus, including the basic reproductive number, incubation period, serial interval, modes of transmission and environmental factors 3. Severity of disease, including risk of fatality among symptomatic hospitalized patients, and high-risk patient groups 4. Susceptibility of populations 5. Public health mitigation measures that could be effective for control \"\"\" \"\"\" In the above Questions, Questions 1, 3 AND 5 are attempted using a combination of word2vec embedding to extract the keywords and search algorithm to extract the research articles related to it. Word2vec embedding provides the keywords that are closest to answer the questions \"\"\" \"\"\" # SOLUTION APPROACH ![covid.JPG](attachment:covid.JPG) \"\"\" \"\"\" # PROS and CONS PROS: 1. Good understanding and iference of the research papers through TSNE and LDA models 2. Well Trained word embedding models 3. Accurate keyword extraction with emamples demonstrated with results CONS: 1. Manual intervention to establish the relationship of search algorithm to derive answers to the questions. \"\"\" \"\"\" # VISUALIZATION \"\"\" \"\"\" Import libraries \"\"\" # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle\/python docker image: https:\/\/github.com\/kaggle\/docker-python # For example, here's several helpful packages to load in import re import string import collections import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from nltk import word_tokenize from nltk.stem import PorterStemmer from nltk.corpus import stopwords from sklearn.manifold import TSNE from sklearn.cluster import KMeans from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.cluster import MiniBatchKMeans from time import time %matplotlib inline import os import pandas as pd import nltk nltk.download('stopwords') nltk.download('punkt') import spacy import spacy.cli from spacy.matcher import Matcher from spacy.matcher import PhraseMatcher spacy.cli.download(\"en\") spacy.cli.download(\"en_core_web_lg\") nlp = spacy.load('en_core_web_lg') \"\"\" Cleaning of corpus helper functions \"\"\" ## set english loanguage stop_words = set(stopwords.words('english')) ## declaration of Porter stemmer. porter=PorterStemmer() ## Clean Null Record in dataframe def cleanEmptyData(columnName,df): return df[df[columnName].notnull()] ## Remove Punctuation def remove_punctuation(columnName,df): return df.loc[:,columnName].apply(lambda x: re.sub('[^a-zA-z\\s]','',x)) ## Convert To Lower Case def lower_case(input_str): input_str = input_str.lower() return input_str ## Remove duplicate item in the dataframe def removeDuplicate(df,list): df.drop_duplicates(list, inplace=True) ## Remove nlp stop words def remove_stop_words(columnName,df): return df.loc[:,columnName].apply(lambda x: [word for word in x.split() if word not in stop_words]) ##Remove single character from the sentence def remove_one_character_word(columnName,df): return df.loc[:,columnName].apply(lambda x: [i for i in x if len(i) > 1]) ## Join as a single text with seperator def join_seperator(columnName,df): seperator = ', ' return df.loc[:,columnName].apply(lambda x: seperator.join(x)) ## apply stemmer to data frame fields def apply_stemmer(columnName,df): return df.loc[:,columnName].apply(lambda x: [porter.stem(word) for word in x]) ## Data Cleaning Process function def dataCleaningProcess(dataFrame): ## remove duplicate records removeDuplicate(dataFrame,['abstract', 'text_body']) ## clean null value records clean_data = cleanEmptyData('text_body',dataFrame) clean_data.loc[:,'text_body_clean'] = clean_data.loc[:,'text_body'].apply(lambda x: lower_case(x)) ## removing punctuation clean_data.loc[:,'text_body_clean'] = remove_punctuation('text_body_clean',clean_data) ## apply stop words clean_data.loc[:,'text_body_clean'] = remove_stop_words('text_body_clean',clean_data) ## apply stemmer for each tokens clean_data.loc[:,'text_body_clean'] = apply_stemmer('text_body_clean',clean_data) ## removing single charter word in the sentence clean_data.loc[:,'text_body_clean'] = remove_one_character_word('text_body_clean',clean_data) ## join as a single text from words token clean_data.loc[:,'text_body_clean'] = join_seperator('text_body_clean',clean_data) ## remove coma after join clean_data.loc[:,'text_body_clean'] = remove_punctuation('text_body_clean',clean_data) return clean_data \"\"\" Re usable Helper functions \"\"\" ## get words token from text def getWordsFromText(_text): words = [] for i in range(0,len(_text)): words.append(str(_text.iloc[i]['text_body']).split(\" \")) return words # Read Excel data as Data Frame def readExcelToDataFrame(path): research_dataframe = pd.read_csv(path,index_col=False) research_dataframe.drop(research_dataframe.columns[research_dataframe.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True) return research_dataframe ## basic scatter plot def showScatterPlot(_X,title): # sns settings sns.set(rc={'figure.figsize':(15,15)}) # colors palette = sns.color_palette(\"bright\", 1) # plot sns.scatterplot(_X[:,0], _X[:,1], palette=palette) plt.title(title) # plt.savefig(\"plots\/t-sne_covid19.png\") plt.show() ## scatter plot with cluster def showClusterScatterPlot(_X, _y_pred, title): # sns settings sns.set(rc={'figure.figsize':(10,10)}) # colors palette = sns.color_palette(\"bright\", len(set(_y_pred))) # plot sns.scatterplot(_X[:,0], _X[:,1], hue=_y_pred, legend='full', palette=palette) plt.title(title) # plt.savefig(\"plots\/t-sne_covid19_label.png\") plt.show() ## drop clumns def getTargetData(dataFrame): text_body = dataFrame.drop([\"doc_id\", \"source\", \"title\", \"abstract\"], axis=1) return getWordsFromText(text_body) ## train model for tSNE clustering visualization def trainEmbededData(_perplexity,dataFrame,total_cluster, _n_iter): ## convert text to word frequency vectors vectorizer = TfidfVectorizer(max_features=2**12) ## training the data and returning term-document matrix. _X = vectorizer.fit_transform(dataFrame['text_body_clean'].values) ## tsne declartion tsne = TSNE(verbose=1, perplexity=_perplexity,learning_rate=200, random_state=0, n_iter=_n_iter) _X_embeded = tsne.fit_transform(_X.toarray()) ## clusterring for tsne _kmeans = MiniBatchKMeans(n_clusters=total_cluster) return _X_embeded,_kmeans,_X ## predicting cluster centers and predict cluster index for each sample def predict(_kmeans,_X): return _kmeans.fit_predict(_X) ## reusable fucntion for TSNE K-Mean Clustering with TF-IDF def analyse(pplexity,data_frame,cluster,iter): ## train model for tSNE clustering visualization embeded,kmeans,x = trainEmbededData(pplexity,data_frame,cluster,iter) pred = predict(kmeans,x) ## visualized the scatter plot showClusterScatterPlot(embeded,pred,'t-SNE Covid-19 - Clustered(K-Means) - Tf-idf with Plain Text') return embeded,kmeans,x \"\"\" **Loading data(a)-Complete data by reading uploaded CSV** | CSV file is created by parsing the JSON data \"\"\" research_dataframe = readExcelToDataFrame('\/kaggle\/input\/coviddata21\/data.csv') research_dataframe.head() \"\"\" Data Cleaning \"\"\" clean_data =dataCleaningProcess(research_dataframe) \"\"\" Visualise Cleaned Data and removing columns \"\"\" clean_data.head() clean_process_data = clean_data.drop([\"doc_id\", \"source\", \"title\", \"abstract\"], axis=1) clean_process_data.head(20) \"\"\" Read the meta data from meta_data CSV \"\"\" meta_data = readExcelToDataFrame('\/kaggle\/input\/metadata\/meta.csv') meta_data.head() \"\"\" Data Preparation included the below process: * Load Research & Meta Data * Meta Data filter for published time from 2019 to 2020 on doc_id * Remove unused fields for the search inference. \"\"\" def prepare_search_data(_meta_data_frame,research_dataframe): ## add a field doc_id _meta_data_frame[\"doc_id\"] = _meta_data_frame[\"sha\"] ## clean NUll record _meta_data_frame = cleanEmptyData('doc_id', _meta_data_frame) _meta_data_frame = cleanEmptyData('publish_time', _meta_data_frame) ## select only 2019 & 2020 published records meta_data_filter = _meta_data_frame[_meta_data_frame['publish_time'].str.contains('2019') | _meta_data_frame['publish_time'].str.contains('2020')] ## clean NUll record research_dataframe_clean = cleanEmptyData('doc_id', research_dataframe) research_dataframe_clean = cleanEmptyData('text_body', research_dataframe_clean) ## merging of Research data and meta data on doc_id tmp_data_frame = research_dataframe_clean.merge(meta_data_filter, on='doc_id', how='right') ## remove un used fields clean_process_data = tmp_data_frame.drop([\"source\", \"abstract_x\", \"abstract_x\",\"sha\",\"source_x\",\"title_y\",\"pmcid\",\"pubmed_id\",\"license\",\"abstract_y\",\"journal\",\"Microsoft Academic Paper ID\",\"WHO #Covidence\"], axis=1) ## clean NUll record clean_process_data = cleanEmptyData('text_body', clean_process_data) clean_process_data = clean_process_data.rename(columns={'title_x': 'title'}) # reordering the column index columns = [\"doc_id\",\"doi\", \"publish_time\", \"authors\",\"url\",\"title\", \"text_body\"] clean_process_data = clean_process_data.reindex(columns=columns) return clean_process_data def process_title(x): if not str(x['title_x']).lower() =='nan': return str(x['title_x']) + ' (' + str(x['url']) + ')' else: return str(x['url']) \"\"\" Filtered Data to be used to visualize the word cloud in the upcoming cells to understand the importance of topics and vocabs used. \"\"\" filter_data = prepare_search_data(meta_data,research_dataframe) filter_data.head() \"\"\" # EDA WORD CLOUD FOR THE TITLE OF ARTICLES FROM 2019 - 2020 \"\"\" \"\"\" Import libraries \"\"\" from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt \"\"\" **WORD CLOUD VISUALIZATION ** We have filtered 2019-2020 research papers to understand COVID-19 data through the word cloud visualization. \"\"\" def show_WordCloud(filter_data): comment_words = ' ' stopwords = set(STOPWORDS) # iterate through the csv file for val in filter_data: # typecaste each val to string val = str(val) # split the value tokens = val.split() #print(val) # Converts each token into lowercase for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words = comment_words + words + ' ' #print(comment_words) wordcloud = WordCloud(width = 800, height = 800, background_color ='white', max_words = 200, stopwords = stopwords, min_font_size = 10).generate(comment_words) # plot the WordCloud image plt.figure(figsize = (10, 10), facecolor = None) plt.imshow(wordcloud) plt.axis(\"off\") plt.tight_layout(pad = 0) plt.show() show_WordCloud(filter_data.title) \"\"\" The Visualization clearly talks about the : **coronavirus, transmission, infection, vaccine, ourbreak etc.. ** Giving a clear picture of the terminalogies and informations that can be retrived from the research papers. \"\"\" \"\"\" **Dimensionality Reduction with t-SNE** Using t-SNE we can reduce our high dimensional features vector to 2 dimensions. By using the 2 dimensions as x,y coordinates, the text_body_clean can be plotted. t-SNE will attempt to preserve the relations of the higher dimensional data as closely as possible when shrunk to 2D Analyse with perplexity of 5000, cluster 10, iteration : 15000 The optimal cluster parameter is decided after clustering the data from different preplexity and clusters and visualized. \"\"\" embeded,kmeans,x = analyse(5000,clean_process_data,10,15000) \"\"\" We tried understanding documents with different clusters with various perplexity and identified the optimal perplexity where the convergence of documents took place. \"\"\" \"\"\" # MODEL BUILDING AND INFERENCE \"\"\" \"\"\" LOAD the Research Dataset \"\"\" papers = research_dataframe['text_body'].astype('str') len(papers) papers.head() #meta_data_filter = _meta_data_frame[_meta_data_frame['publish_time'].str.contains('2019') | _meta_data_frame['publish_time'].str.contains('2020')] \"\"\" We perform some basic text wrangling or preprocessing before diving into topic modeling. We keep things simple here \"\"\" %%time import nltk import tqdm nltk.download('wordnet') stop_words = nltk.corpus.stopwords.words('english') wtk = nltk.tokenize.RegexpTokenizer(r'\\w+') wnl = nltk.stem.wordnet.WordNetLemmatizer() def normalize_corpus(papers): norm_papers = [] for paper in tqdm.tqdm(papers): paper = paper.lower() paper_tokens = [token.strip() for token in wtk.tokenize(paper)] paper_tokens = [wnl.lemmatize(token) for token in paper_tokens if not token.isnumeric()] paper_tokens = [token for token in paper_tokens if len(token) > 1] paper_tokens = [token for token in paper_tokens if token not in stop_words] paper_tokens = list(filter(None, paper_tokens)) #if paper_tokens: norm_papers.append(paper_tokens) return norm_papers norm_papers = normalize_corpus(papers) print(len(norm_papers)) \"\"\" Build a Bi-gram Phrase Model \"\"\" import gensim bigram = gensim.models.Phrases(norm_papers, min_count=20, threshold=20, delimiter=b'_') # higher threshold fewer phrases. bigram_model = gensim.models.phrases.Phraser(bigram) print(bigram_model[norm_papers[0]][:50]) print(bigram_model[norm_papers[1]][:50]) norm_corpus_bigrams = [bigram_model[doc] for doc in norm_papers] # Create a dictionary representation of the documents. dictionary = gensim.corpora.Dictionary(norm_corpus_bigrams) print('Sample word to number mappings:', list(dictionary.items())[:15]) print('Total Vocabulary Size:', len(dictionary)) \"\"\" Looks like we have a lot of unique phrases in our corpus of research papers, based on the preceding output. Several of these terms are not very useful since they are specific to a paper. Hence, we will prune our vocabulary and start removing terms. \"\"\" # Filter out words that occur less than 20 documents, or more than 60% of the documents. dictionary.filter_extremes(no_below=20, no_above=0.6) print('Total Vocabulary Size:', len(dictionary)) \"\"\" **Transforming corpus into bag of words vectors** We can now perform feature engineering by leveraging a simple Bag of Words model. \"\"\" bow_corpus = [dictionary.doc2bow(text) for text in norm_corpus_bigrams] print(bow_corpus[1][:50]) print([(dictionary[idx] , freq) for idx, freq in bow_corpus[1][:50]]) print('Total number of papers:', len(bow_corpus)) \"\"\" **Topic Models with Latent Dirichlet Allocation (LDA)** \"\"\" \"\"\" ***Building model** > %%time > > > TOTAL_TOPICS = 10 > > lda_model = gensim.models.LdaModel(corpus=bow_corpus, id2word=dictionary, chunksize=1740, > alpha='auto', eta='auto', random_state=42, > iterations=500, num_topics=TOTAL_TOPICS, > passes=20, eval_every=None)* \"\"\" \"\"\" **Load the LDA Model ** \"\"\" import joblib lda_model = joblib.load('\/kaggle\/input\/coviddata21\/lda_model.jl') topics_assigned = lda_model[bow_corpus] len(topics_assigned) b= pd.DataFrame(topics_assigned,columns = ['T0','T1','T2','T3','T4','T5','T6','T7','T8','T9']) \"\"\" > TOPIC CSV CREATION \"\"\" d= pd.concat([research_dataframe['text_body'],b],axis=1) \"\"\" EXTRACT CSV \"\"\" d.to_csv(\"Topic_paper_07042020_v4.csv\") \"\"\" **LDA TOPICS WITH TOPIC ID** \"\"\" for topic_id, topic in lda_model.print_topics(num_topics=50, num_words=20): print('Topic #'+str(topic_id+1)+':') print(topic) print() import numpy as np topics_coherences = lda_model.top_topics(bow_corpus, topn=20) avg_coherence_score = np.mean([item[1] for item in topics_coherences]) print('Avg. Coherence Score:', avg_coherence_score) \"\"\" **LDA TOPIC WITH WEIGHTS** \"\"\" topics_with_wts = [item[0] for item in topics_coherences] print('LDA Topics with Weights') print('='*50) for idx, topic in enumerate(topics_with_wts): print('Topic #'+str(idx+1)+':') print([(term, round(wt, 3)) for wt, term in topic]) print() \"\"\" **LDA TOPIC WITHOUT WEIGHTS** \"\"\" print('LDA Topics without Weights') print('='*50) for idx, topic in enumerate(topics_with_wts): print('Topic #'+str(idx+1)+':') print([term for wt, term in topic]) print() \"\"\" **Evaluating topic model:** Quality We can use perplexity and coherence scores as measures to evaluate the topic model. Typically, lower the perplexity, the better the model. Similarly, the lower the UMass score and the higher the Cv score in coherence, the better the model. \"\"\" cv_coherence_model_lda = gensim.models.CoherenceModel(model=lda_model, corpus=bow_corpus, texts=norm_corpus_bigrams, dictionary=dictionary, coherence='c_v') avg_coherence_cv = cv_coherence_model_lda.get_coherence() umass_coherence_model_lda = gensim.models.CoherenceModel(model=lda_model, corpus=bow_corpus, texts=norm_corpus_bigrams, dictionary=dictionary, coherence='u_mass') avg_coherence_umass = umass_coherence_model_lda.get_coherence() perplexity = lda_model.log_perplexity(bow_corpus) print('Avg. Coherence Score (Cv):', avg_coherence_cv) print('Avg. Coherence Score (UMass):', avg_coherence_umass) print('Model Perplexity:', perplexity) \"\"\" **Creation of Word Cloud Topic wise** \"\"\" from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt stopwords = set(STOPWORDS) def show_wordcloud(data, title = None): wordcloud = WordCloud( background_color='white', stopwords=stopwords, max_words=2000, max_font_size=40, scale=3, random_state=1 # chosen at random by flipping a coin; it was heads ).generate(str(data)) fig = plt.figure(1, figsize=(15, 15)) plt.axis('off') if title: fig.suptitle(title, fontsize=20) fig.subplots_adjust(top=2.3) plt.imshow(wordcloud) plt.show() with open(\"\/kaggle\/input\/coviddata21\/Topic_paper_07042020_v4.csv\",encoding = 'utf8', errors='ignore') as f: df_topic = pd.read_csv(f) #df = df.replace(\"\\n\",\" \").dropna() \"\"\" **WORD CLOUD FOR THE DOMINANT TOPIC(S) ** Example: Topic 1 can have 20 documents while Topic 2 may have 200 documents in it.Hence a word cloud is drawn to visualize the intersting vocabs involving each Topic \"\"\" \"\"\" **Topic 1** \"\"\" show_WordCloud(df_topic.loc[df_topic['Dominant_topic'] == 0]['text_body']) #show_WordCloud(filter_data.title) \"\"\" In the above word cloud for the topics were mostly about genome of the covid-19 and possibilties of other corona virus genomes and carriers. \"\"\" \"\"\" **Topic 2** \"\"\" show_WordCloud(df_topic.loc[df_topic['Dominant_topic'] == 1]['text_body']) \"\"\" > In the above word cloud for the topics were mostly about infection samples and detection of virus in a patient \"\"\" \"\"\" **Inference of some topics ** * Topic 1&5: mainly deals with the virus structure and genome * Topic 3: deals with the origin and history * Topic 4&10: For public health risk information * Topic 9: Has lab research on various subjects \"\"\" \"\"\" **WORD2VEC MODEL ** WORD2VEC EMBEDDING IS USED TO PREDICT THE TARGET WORD(S) FORM THE CONTEXT WORDS(Questions from task) USING CBOW In this COVID-19 challenge the questions form the context words, we leverage the context words from the questions to predict the target words to form the keywords, which inturn will lead us to the answers for the respective context words(questions). we are using the CBOW approach in word2vec to acheive this. \"\"\" \"\"\" **Robust Word2Vec Model with Gensim** The __`gensim`__ framework, created by Radim \u0158eh\u016f\u0159ek consists of a robust, efficient and scalable implementation of the Word2Vec model. We will leverage the same on our covid-19 corpus. In our workflow, we will tokenize our normalized corpus and then focus on the following four parameters in the Word2Vec model to build it. - __`size`:__ The word embedding dimensionality : 100 - __`window`:__ The context window size : 20 - __`min_count`:__ The minimum word count : 1 - __`iter`:__ Iteration : 1000 - __`sg`:__ Training model, 1 for skip-gram otherwise CBOW : CBOW We have build a Word2Vec model on the corpus. \"\"\" \"\"\" Import libraries \"\"\" from __future__ import print_function __author__ = 'maxim' import numpy as np import gensim import string from gensim.models import Word2Vec from keras.callbacks import LambdaCallback from keras.layers.recurrent import LSTM from keras.layers.embeddings import Embedding from keras.layers import Dense, Activation from keras.models import Sequential from keras.utils.data_utils import get_file from gensim.models import Word2Vec import pandas as pd import numpy as np import re import json import pandas as pd from gensim.models.fasttext import FastText from os import listdir from os.path import isfile, join from tqdm import tqdm import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import re import gensim import nltk \"\"\" word2vec model loading, we are using the training model by loading it. \"\"\" print('loading model') word_model = Word2Vec.load(\"\/kaggle\/input\/coviddata21\/word2vec_1000ITR.model\") print('model loaded') \"\"\" **Model Evaluation:** Example 1: **\" COVID-19 \"** keyword when tested against our word embedding model gave the following results. [('ncp', 0.7167163491249084), ('wuhan', 0.7067078351974487), ('2019ncov', 0.7065909504890442), ('sarscov2', 0.6876667737960815), ('mers', 0.6260266304016113), ('sars', 0.6118236780166626), ('2020', 0.6101416349411011), ('hubei', 0.5763685703277588), ('mainland', 0.5460340976715088), ('china', 0.531872034072876)] notable keywords from the word2vec output are: 'wuhan','sars','china' relating to the orgin of the virus Example 2: For Multiple keywords **'treatment','option'** keyword when tested against our word embedding model gave the following results. [('treatments', 0.88392174243927), ('therapies', 0.7969704866409302), ('therapy', 0.7752498984336853), ('drugs', 0.7263898253440857), ('medications', 0.7093261480331421), ('antivirals', 0.6795921325683594), ('regimens', 0.6594418287277222), ('prophylaxis', 0.653971254825592), ('medication', 0.6348516941070557), ('antibiotics', 0.6138178706169128)] notable keywords from the word2vec outpur are : 'prophylaxis','therapies' relating to preventive medications . As shown below: \"\"\" #Severity of disease, including risk of fatality among symptomatic hospitalized patients, and high-risk patient groups a=['severity','disease','fatality','patients','symptomatic'] print(word_model.most_similar(positive=a,topn=30)) print(\"=================================================================\") print(word_model.predict_output_word(a,topn=30)) #'populations','susceptibility','covid19' #Severity of disease, including risk of fatality among symptomatic hospitalized patients, and high-risk patient groups \"\"\" risk factor * Smoking, pre-existing pulmonary disease * Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities * Neonates and pregnant women * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. \"\"\" #Data on potential risks factors #--Smoking, pre-existing pulmonary disease a=['covid19','risk','smoking','existing', 'pulmonary' ,'disease','comorbidity'] #comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic|cvd print(word_model.most_similar(positive=a,topn=30)) print(\"=================================================================\") print(word_model.predict_output_word(a,topn=30)) #'populations','susceptibility','covid19' #Severity of disease, including risk of fatality among symptomatic hospitalized patients, and high-risk patient groups \"\"\" As shown in the above steps, the context of the context words 'covid19' are well understood by the word2vec model in predicting the target words 'wuhan','sars','china' relating to the orgin of the virus which are very relavant in approaching the answers to the questions. \"\"\" #Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities a=['infection','coexisting','virus','transmissible', 'virulent' ,'comorbidity'] #severe|fatal|coinfection|contagious|susceptible|merscov|sftsv|highly|ibv|pedv|csfv|pathogenicity|eiav|prrsv|prv|h1n1pdm|hepatatis|lethalmhv| print(word_model.most_similar(positive=a,topn=30)) print(\"=================================================================\") print(word_model.predict_output_word(a,topn=30)) # Risk of COVID-19 in Neonates and pregnant women a=['covid19','virus','risk','neonates','pregnant', 'women','postpartum','congenital'] #stillbirth|miscarriage|congenital|malformations|microcephaly|abortion|obstetric|lbw|covid19 print(word_model.most_similar(positive=a,topn=40)) print(\"=================================================================\") print(word_model.predict_output_word(a,topn=40)) #Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. a=['covid19','virus','risk','economy','impact','behaviour','industry','global','socioeconomic','consequences'] #lessen productivity|macroeconomic affecting|vulnerability|devastating|reducing|recession|unemployment print(word_model.most_similar(positive=a,topn=40)) print(\"=================================================================\") print(word_model.predict_output_word(a,topn=40)) print(word_model.most_similar(positive=['treatment','options' ])) \"\"\" As shown in the above steps, the context of the context words 'treatment','options' are well understood by the word2vec model in predicting the target words 'therapy','antivirals','regimens','prophylaxis' which are very relavant in finding the answers to the questions. \"\"\" \"\"\" **Answering Approach word embedding method** Word embedding for the following questions are extracted by passing a set of words from the question to the word embedding model and closest keywords are extracted to further find the closest keywords as shown in the example below: 1. Data on potential risks factors * Smoking, pre-existing pulmonary disease * Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities * Neonates and pregnant women * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. 2. Severity of disease, including risk of fatality among symptomatic hospitalized patients, and high-risk patient groups 3. Public health mitigation measures that could be effective for control **Example:** **Question 3 : Persistence of virus on surfaces of different materials (e,g., copper, stainless steel, plastic).** ***Embedding Step to extract keywords* ** > print(word_model.predict_output_word(['covid19','surfaces'],topn=30)) > print(word_model.predict_output_word(['covid19','surfaces','nonporous','handrails','desks','floor','fomite'],topn=30)) > print(word_model.most_similar(['covid19','fomites','airborne','nonporous','handrails','desks','floor','fomite'],topn=30)) ***Search Algorithm to extracted related research articles:*** > searc_by_keys_as_excel('fomites|airborne|nonporous|handrails|desks|floor|fomite|hands|toilets|door|bedrails',search_data) > \"\"\" arr_most_similar = [['severity','disease','fatality','patients','symptomatic'], ['covid19','risk','smoking','existing', 'pulmonary' ,'disease','comorbidity'], ['infection','coexisting','virus','transmissible', 'virulent' ,'comorbidity'], ['covid19','virus','risk','neonates','pregnant', 'women','postpartum','congenital'], ['covid19','virus','risk','economy','impact','behaviour','industry','global','socioeconomic','consequence']] arr_predict=[['severity','disease','fatality','patients','symptomatic'], ['covid19','risk','smoking','existing', 'pulmonary' ,'disease','comorbidity'], ['infection','coexisting','virus','transmissible', 'virulent' ,'comorbidity'], ['covid19','virus','risk','neonates','pregnant', 'women','postpartum','congenital'], ['covid19','virus','risk','economy','impact','behaviour','industry','global','socioeconomic','consequence']] #EXAMPLE #Public health mitigation measures that could be effective for control #Intial input fed to word2vec model to extract related words that could lead to the answers of this question #['public','health','mitigation','measures', 'effective', 'control','covid19','disease']] #RESULT from first Query: [('interventions', 0.7447171807289124), ('prevention', 0.7438710927963257), ('preventive', 0.7241473197937012), ('policies', 0.7131460905075073), ('intervention', 0.7103219628334045), ('management', 0.7056314945220947), ('implementing', 0.6939526200294495), ('policy', 0.6897070407867432), ('quarantine', 0.6833001971244812), ('planning', 0.6516326069831848), ('implementation', 0.641217827796936), ('awareness', 0.6297034025192261), ('containment', 0.6278428435325623), ('preparedness', 0.622099757194519), ('epidemic', 0.6220937967300415), ('timely', 0.6204564571380615), ('community', 0.6184203624725342), ('government', 0.6134730577468872), ('outbreak', 0.6104072332382202), ('pandemic', 0.6079082489013672)]] #Updated input taken from first querying of word2vec model after choosing relevant keywords #['mitigation','measures','control','covid19','quarantine','containment','awareness','policies']] #RESULT from second Query: [[('interventions', 0.7805880308151245), ('intervention', 0.7159266471862793), ('policy', 0.690924346446991), ('preventive', 0.6865450143814087), ('implementing', 0.6757345795631409), ('implementation', 0.6531403064727783), ('planning', 0.6507831811904907), ('practices', 0.6400246620178223), ('prevention', 0.6383914947509766), ('management', 0.6378570199012756), ('government', 0.6369956731796265), ('preparedness', 0.6348874568939209), ('restrictions', 0.6139740943908691), ('campaigns', 0.6061151027679443), ('behaviors', 0.5989149808883667), ('plans', 0.5976110696792603), ('decisions', 0.5968020558357239), ('timely', 0.591980516910553), ('governmental', 0.5905696153640747), ('biosecurity', 0.5887465476989746)]] #Most Similar Keywrods Detection len(arr_most_similar) arrans=[] print(len(arr_most_similar)) count=0 for i in arr_most_similar: print('--------->',i) answers=word_model.most_similar(positive=i,topn=30) arrans.append(answers) count +=1 print('=========',count) print(arrans) print(len(arrans)) #Predicted Keywords Detection arr_predict len(arr_predict) arrans_arr_predict=[] print(len(arr_predict)) count=0 for j in arr_predict: print('--------->',j) answers1=word_model.predict_output_word(j,topn=30) arrans_arr_predict.append(answers1) count +=1 print('=========',count) print(arrans_arr_predict) print(len(arrans_arr_predict)) for q in arrans: print(q) #arrans for k in arrans_arr_predict: print(k) \"\"\" **KEYWORD EXTRACTION** * Public health mitigation measures that could be effective for control **--> 'interventions|policies|quarantine|awareness|preparedness|restrictions|campaigns|behaviors|biosecurity|governmental|search_data'** * Smoking, pre-existing pulmonary disease **--> comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic** * Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities **--> severe|fatal|coinfection|contagious|susceptible|merscov|sftsv|highly|ibv|pedv|csfv|pathogenicity|eiav|prrsv|prv|h1n1pdm|hepatatis|lethal|mhv** * Neonates and pregnant women **--> stillbirth|miscarriage|congenital|malformations|microcephaly|abortion|obstetric|lbw|covid19** * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. **--> lessen productivity|macroeconomic affecting|vulnerability|devastating|reducing|recession|unemployment** \"\"\" \"\"\" **SEARCH ALGORITHM ** To extract the relevant research documents from the keywords extarcted \"\"\" ## constant for spliting sentence alphabets= \"([A-Za-z])\" prefixes = \"(Mr|St|Mrs|Ms|Dr)[.]\" suffixes = \"(Inc|Ltd|Jr|Sr|Co)\" starters = \"(Mr|Mrs|Ms|Dr|He\\s|She\\s|It\\s|They\\s|Their\\s|Our\\s|We\\s|But\\s|However\\s|That\\s|This\\s|Wherever)\" acronyms = \"([A-Z][.][A-Z][.](?:[A-Z][.])?)\" websites = \"[.](com|net|org|io|gov)\" ## spliting to sentence from text def split_into_sentences(text): text = \" \" + text + \" \" text = text.replace(\"\\n\",\" \") text = re.sub(prefixes,\"\\\\1<prd>\",text) text = re.sub(websites,\"<prd>\\\\1\",text) if \"Ph.D\" in text: text = text.replace(\"Ph.D.\",\"Ph<prd>D<prd>\") text = re.sub(\"\\s\" + alphabets + \"[.] \",\" \\\\1<prd> \",text) text = re.sub(acronyms+\" \"+starters,\"\\\\1<stop> \\\\2\",text) text = re.sub(alphabets + \"[.]\" + alphabets + \"[.]\" + alphabets + \"[.]\",\"\\\\1<prd>\\\\2<prd>\\\\3<prd>\",text) text = re.sub(alphabets + \"[.]\" + alphabets + \"[.]\",\"\\\\1<prd>\\\\2<prd>\",text) text = re.sub(\" \"+suffixes+\"[.] \"+starters,\" \\\\1<stop> \\\\2\",text) text = re.sub(\" \"+suffixes+\"[.]\",\" \\\\1<prd>\",text) text = re.sub(\" \" + alphabets + \"[.]\",\" \\\\1<prd>\",text) if \"\u201d\" in text: text = text.replace(\".\u201d\",\"\u201d.\") if \"\\\"\" in text: text = text.replace(\".\\\"\",\"\\\".\") if \"!\" in text: text = text.replace(\"!\\\"\",\"\\\"!\") if \"?\" in text: text = text.replace(\"?\\\"\",\"\\\"?\") text = text.replace(\".\",\".<stop>\") text = text.replace(\"?\",\"?<stop>\") text = text.replace(\"!\",\"!<stop>\") text = text.replace(\"<prd>\",\".\") sentences = text.split(\"<stop>\") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences ## search inference text by key words and return all the matches sentence def search_inference_keys(text, keywords): sentences = split_into_sentences(text) txt = '' for sent in sentences: r = re.compile(keywords,flags=re.IGNORECASE) if len(r.findall(sent))>0: txt = str(txt) + str(sent) return txt ## check key words exist or not in a sentence def check_exist_multiple_keywords(text, keywords): r = re.compile(keywords, flags=re.IGNORECASE) if len(r.findall(text))>0: return True else: return False ## Search Inference and download results as excel def searc_by_keys_as_excel(keyword, src_data_frame): data_frame = src_data_frame ## check exist to slice down the related contents data_frame['search_key_status'] =data_frame.loc[:,'text_body'].apply(lambda x: check_exist_multiple_keywords(x,keyword)) ## select only target data process_data_frame = data_frame.query('search_key_status == True') ## filter on corona and covid 19 related data process_data_frame['search_covid_content'] =process_data_frame.loc[:,'text_body'].apply(lambda x: check_exist_multiple_keywords(x,'covid-19|sars-cov-2|2019-ncov|ncov-19|coronavirus')) ## get only covid-19|sars-cov-2|2019-ncov|ncov-19|coronavirus data process_data_frame = process_data_frame.query('search_covid_content == True') process_data_frame.loc[:,'inference'] = process_data_frame.loc[:,'text_body'].apply( lambda x: search_inference_keys(x,keyword)) ## remove unused fields final_data = process_data_frame.drop([\"search_key_status\",\"text_body\"], axis=1) ## download as excel final_data.to_excel(str(keyword) + '_result.xlsx', sheet_name='keyword') return final_data # Search Inference for \"incubation period\" and download results as excel search_data = prepare_search_data(meta_data,research_dataframe) \"\"\" *The Keywords extracted through embedding are passed on to the below functions to extarct the list of research articles to further manually pick the articles relevant to the questions to answer the questions.* **Following are the keywords picked question wise:** * Public health mitigation measures that could be effective for control **--> 'interventions|policies|quarantine|awareness|preparedness|restrictions|campaigns|behaviors|biosecurity|governmental|search_data'** * Smoking, pre-existing pulmonary disease **--> comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic** * Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities **--> severe|fatal|coinfection|contagious|susceptible|merscov|sftsv|highly|ibv|pedv|csfv|pathogenicity|eiav|prrsv|prv|h1n1pdm|hepatatis|lethal|mhv** * Neonates and pregnant women **--> stillbirth|miscarriage|congenital|malformations|microcephaly|abortion|obstetric|lbw|covid19** * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. **--> lessen productivity|macroeconomic affecting|vulnerability|devastating|reducing|recession|unemployment** Seperate Excel is created in the Output section for each questions with its possible research articles that can prove the inference made using the word2vec answering approach. \"\"\" \"\"\" Question 1:* Public health mitigation measures that could be effective for control **--> 'interventions|policies|quarantine|awareness|preparedness|restrictions|campaigns|behaviors|biosecurity|governmental|search_data'** \"\"\" final_data =searc_by_keys_as_excel('interventions|policies|quarantine|awareness|preparedness|restrictions|campaigns|behaviors|biosecurity|governmental|search_data',search_data) #comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic #'interventions','policies','quarantine','awareness''preparedness','restrictions','campaigns','behaviors', #'biosecurity','governmental' final_data.head() \"\"\" Question 2: * Smoking, pre-existing pulmonary disease **--> comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic** \"\"\" final_data =searc_by_keys_as_excel('comorbidities|mellitus|cardiovascular|vulnerability|hypertension|pneumonia|chronic',search_data) \"\"\" Question 3: Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities --> severe|fatal|coinfection|contagious|susceptible|merscov|sftsv|highly|ibv|pedv|csfv|pathogenicity|eiav|prrsv|prv|h1n1pdm|hepatatis|lethal|mhv \"\"\" final_data =searc_by_keys_as_excel('severe|fatal|coinfection|contagious|susceptible|merscov|sftsv|highly|ibv|pedv|csfv|pathogenicity|eiav|prrsv|prv|h1n1pdm|hepatatis|lethalmhv|',search_data) \"\"\" Question 4: Neonates and pregnant women --> stillbirth|miscarriage|congenital|malformations|microcephaly|abortion|obstetric|lbw|covid19 \"\"\" final_data =searc_by_keys_as_excel('stillbirth|miscarriage|congenital|malformations|microcephaly|abortion|obstetric|lbw|covid19',search_data) \"\"\" Question 5: * Socio-economic and behavioral factors to understand the economic impact of the virus and whether there were differences. **--> lessen productivity|macroeconomic affecting|vulnerability|devastating|reducing|recession|unemployment** \"\"\" final_data =searc_by_keys_as_excel('lessen | productivity|macroeconomic | affecting|vulnerability|devastating|reducing|recession|unemployment',search_data) \"\"\" # CONCLUSION \"\"\" \"\"\" **Question 1: Public health mitigation measures that could be effective for control ** 492 f24d3b4b4af138be06b7452b7acefc8948bc1056 doi.org\/10.1101\/2020.01.28.923169 2020-01-28 Shao, P.; Shan, Y. Beware of asymptomatic transmission: Study on 2019-nCoV prevention and control measures based on extended SEIR model TRUE The purpose of this study is to reveal the role of the three most important current measures to control the spread of the epidemic, such as quarantine of infected persons, reduction of human mobility, and improvement of treatment. 508 754315299d847600d6c5d414665c728d40bf731d doi.org\/10.1101\/2020.01.27.922443 2020-01-30 Ming, W.-k.; Huang, J.; Zhang, C. J. P. Breaking down of healthcare system: Mathematical modelling for controlling the novel coronavirus (2019-nCoV) outbreak in Wuhan, China TRUE With the increasing incidence of confirmed cases, corresponding spread control policies and emergency actions are taking place.[6] Earlier studies on the effectiveness of spread control measures during infectious disease pandemic showed large-scale strategies, such as closure of school closure, case isolation, household quarantine, internal travel restrictions and border control, were able to delay the spread and\/or reduce incidence rate at certain periods through the outbreak season.922443 doi: bioRxiv preprint As of 31 st January, it is estimated that there were 246,172 cases given a 10% diagnosis rate whilst being 88,075 and 52,094 cases given diagnosis rates of 50% and 90%, respectively, if no public health interventions were implemented ( Table 2) .If 70% efficacy rate could be achieved (Scenario 4), the forecasting number of cases would drop dramatically to 11,056 as of 10 th February compared to 115,355 without public health interventions (Scenario 2).922443 doi: bioRxiv preprint Therefore, the burdens on healthcare system would be substantial, particularly for the isolation wards and ICU, if no effective public health interventions were implemented.Second, classic SIR model assumes a constant infection rate, which is not likely to be true as interventions being implemented.Therefore, in this study, we constructed SIR models with multiple efficacy rates of public health interventions as proxy for the change of infection rate.To achieve higher efficacy of the public health interventions, efforts from individuals should not be neglected.All these are extremely important in raising awareness in the public as to personal preventive steps given the present situation (mild or subclinical symptoms observed in many cases and observed long incubation period).We believe that these volunteering activities can contribute to a successful delivery of public health principle and, in turn, efficacious interventions.To conclude, our estimates of the healthcare system burdens arising from the actual number of cases infected by the novel coronavirus appear to be considerable if no effective public health interventions were implemented.922443 doi: bioRxiv preprint -13 -public transport) and further effective large-scale interventions spanning all subgroups of populations (e.g., universal facemask wear) with an aim to obtain overall efficacy with at least 70%-90% to ensure the functioning of and avoid the breakdown of healthcare system. Highlight: Most important current measures to control the spread of the epidemic, such as quarantine of infected persons, reduction of human mobility, and improvement of treatment. =============================================================================================== **Question 2: Data on potential risks factors: Smoking, pre-existing pulmonary disease** Observation made from research papers published on 2020: 1572 f294f0df7468a8ac9e27776cc15fa20297a9f040 10.3390\/v12020244 2020 Xu, Jiabao; Zhao, Shizhe; Teng, Tieshan; Abdalla, Abualgasim Elgaili; Zhu, Wan; Xie, Longxiang; Wang, Yunlong; Guo, Xiangqian Systematic Comparison of Two Animal-to-Human Transmitted Human Coronaviruses: SARS-CoV-2 and SARS-CoV TRUE The source of unexplained pneumonia was first discovered in Wuhan in Dec, 2019, and SARS-CoV-2, a new coronavirus, was isolated from the respiratory epithelium of patients.The following month, there were clusters of atypical pneumonia reported in other parts of mainland China, Hong Kong [21] , Canada [22] , and Singapore [23] .29th, 2019, the health departments of Hubei Province received a report that four employees of the South China Seafood Wholesale Market were diagnosed with unknown-caused pneumonia in a local hospital, which was the first report of SARS-CoV-2 [27] .The following month, there were clusters of atypical pneumonia reported in other parts of mainland China, Hong Kong [21] , Canada [22] , and Singapore [23] .29th, 2019, the health departments of Hubei Province received a report that four employees of the South China Seafood Wholesale Market were diagnosed with unknown-caused pneumonia in a local hospital, which was the first report of SARS-CoV-2 [27] .COVID-19 can be classified into light, normal, severe, and critical types based on the severity of the disease [31] : (1) Mild cases-the clinical symptoms were mild, and no pneumonia was found on the chest computed tomography (CT); (2) normal cases-fever, respiratory symptoms, and patients found to have imaging manifestations of pneumonia; (3) severe cases-one of the following three conditions: Respiratory distress, respiratory rate \u2265 30 times\/min (in resting state, refers to oxygen saturation \u2264 93%), partial arterial oxygen pressure (PaO2)\/oxygen absorption concentration (FiO2) \u2264 300 mmHg (1 mmHg = 0.However, severe cases have been documented in young adults who have unique factors, particularly those with chronic diseases, such as diabetes or hepatitis B. Those with a long-term use of hormones or immunosuppressants, and decreased immune function, are likely to get severely infected.COVID-19 can be classified into light, normal, severe, and critical types based on the severity of the disease [31] : (1) Mild cases-the clinical symptoms were mild, and no pneumonia was found on the chest computed tomography (CT); (2) normal cases-fever, respiratory symptoms, and patients found to have imaging manifestations of pneumonia; (3) severe cases-one of the following three conditions: Respiratory distress, respiratory rate \u2265 30 times \/ min (in resting state, refers to oxygen saturation \u2264 93%), partial arterial oxygen pressure (PaO2)\/oxygen absorption concentration (FiO2) \u2264 300 mmHg (1 mmHg = 0.However, severe cases have been documented in young adults who have unique factors, particularly those with chronic diseases, such as diabetes or hepatitis B. Those with a long-term use of hormones or immunosuppressants, and decreased immune function, are likely to get severely infected.However, severe COVID-19 cases and deaths have mostly been in the middle-aged adults and the elderly with long smoking histories or other basic diseases, such as heart disease and hypertension [43, 44] .Viruses 2020, 12, x FOR PEER REVIEW 5 of 18 basic diseases, such as heart disease and hypertension [43, 44] .The early symptoms of SARS and COVID-19 are very similar to winter influenza, and the most important way to distinguish flu and pneumonia is to take throat swabs for viral testing [68] . Highlights: However, severe COVID-19 cases and deaths have mostly been in the middle-aged adults and the elderly with long smoking histories or other basic diseases, such as heart disease and hypertension ======================================================================================= **Question 3: Co-infections (determine whether co-existing respiratory\/viral infections make the virus more transmissible or virulent) and other co-morbidities** 137 39a7144b3eb9ddf5b9076163aa61099d8b58f977 http:\/\/dx.doi.org\/10.1093\/ofid\/ofz424 2019 Oct 3 ['Noyola, Daniel E', 'Hunsberger, Sally', 'Vald\u00e9s Salgado, Raydel', 'Powers, John H', 'Galindo-Fraga, Arturo', 'Ortiz-Hern\u00e1ndez, Ana A', 'Ramirez-Venegas, Alejandra', 'Moreno-Espinosa, Sarbelio', 'Llamosas-Gallardo, Beatriz', 'Guerrero, M Lourdes', 'Beigel, John H', 'Ruiz-Palacios, Guillermo', 'Perez-Patrigeon, Santiago', None] Open Forum Infectious Diseases Comparison of Rates of Hospitalization Between Single and Dual Virus Detection in a Mexican Cohort of Children and Adults With Influenza-Like Illness TRUE Current estimates indicate that lower respiratory tract infections (LRTIs) are the fifth leading cause of death in the world, accounting for 2.74 million deaths in 2015 [1] .The etiology of acute respiratory infections is diverse, and respiratory viruses are increasingly recognized as important causes of severe respiratory infections.Before the introduction of molecular detection methods, the etiology of a large proportion of acute respiratory infections could not be ascertained.The increasing use of reverse transcription polymerase chain reaction (RT-PCR) and other molecular methods has allowed for detection of respiratory viruses in a large proportion of cases.In addition, during the last 2 decades, previously unrecognized agents, such as human metapneumovirus (HMPV), human bocavirus (HBoV), rhinovirus C, and several coronaviruses, have been identified as new causes of respiratory infection [2] [3] [4] [5] .As such, the use of currently available diagnostic techniques allows detection of at least 1 pathogen in the majority of patients [6] .Additionally, the rates of hospitalization are significantly different based on the virus isolated.Mexican children 5 years of age and younger presenting with influenza-like illness (ILI) caused by human respiratory syncytial virus (RSV) and HMPV have been shown to be at greater risk of hospitalization compared with other viruses [7] .As a result of the increasing use of molecular detection of respiratory viruses and the frequent detection of some of these viruses in asymptomatic individuals, there is a need to clarify their role in the etiology of LRTI [8] .In addition, the availability of diagnostic platforms that allow for the simultaneous detection of many pathogens has resulted in the identification of \u22652 agents in a large number of patients with respiratory infections [9] [10] [11] .Before the use of molecular methods, detection of viral co-infections was relatively rare [12] .In contrast, most recent studies report detection of >1 virus in approximately one-fourth of patients (22.1%-22 .7%) [9] [10] [11] .This has created new opportunities for studying the contribution of each virus in the development, intensity, and duration of symptoms, as well as complications (eg, pneumonia) and death.To address this, many studies have sought to determine whether co-infection with \u22652 viruses contributes to the severity of an infection.Some of these studies have reported that the presence of >1 virus is associated with more severe infections, whereas others have not [9] [10] [11] [13] [14] [15] .In a systematic review and meta-analysis of studies carried out in children <5 years of age, no association between co-infection and increase in disease severity was found, but the need for further studies on this matter was identified [16] .Variability in the results of these studies might be a reflection of the populations included in each study, the definition of severity used, or the viruses that were compared.Of particular relevance is the definition of co-infection, as many studies compare those infected with a specific virus to infection with >1 virus [9] [10] [11] 15] .When assessing the effect of the presence of 2 viruses, various combinations may have differential effects on severity.In the present study, we investigated whether severity, defined as hospitalization with acute respiratory infections, increases with 2 viruses over that of each single virus.We analyzed data from a large prospective ILI cohort during 4 consecutive years in Mexico (ILI-002 study).This analysis is based on data from ILI-002, a hospital-based prospective observational cohort study of ILI [17] [18] [19] .The present analysis includes all participants enrolled in the ILI-002 study in whom 1 or 2 viruses were detected.The ILI-002 study was carried out at 6 public hospitals, 5 of them located in Mexico City and 1 in San Luis Potos\u00ed.Participating hospitals included 2 general hospitals (1 located in Mexico City and 1 in San Luis Potos\u00ed), 2 tertiary care pediatric hospitals, and 2 tertiary care hospitals (1 of them dedicated to the treatment of respiratory disorders, whereas the other provides medical care in a wide range of medical specialties).Adults and children seeking medical attention with ILI, defined as a respiratory symptom (eg, cough, dyspnea) plus a systemic symptom (eg, fever, malaise), were invited to participate in the ILI-002 protocol (ClinicalTrials.gov identifier: NCT01418287).For those enrolled, a follow-up telephone or face-to-face interview was performed at 14+\/-3 days, and a visit happened 28+\/-5 days after inclusion.The study protocol was approved by the ethics committee at all participating institutions, and all participants or guardians signed an informed consent or an assent form when pertinent.A nasopharyngeal swab for multiple PCR pathogen detection was obtained at enrollment.Samples were stored in transport media at 4\u00b0C at each site (for sites located in Mexico City) and sent daily to a central facility ( [HAdV] ) and 4 bacteria (Bordetella pertussis, Chlamydophila pneumoniae, Legionella pneumophila, and Mycoplasma pneumoniae).The 22-pathogen assay added CoV HKU1, HBoV, and influenza A (H1N1) pdm09 while removing influenza A H5N1.As reported by the manufacturer, the analytical limit of detection of the assay varies between 5 and 50 copies per reaction for most targets.Samples that were tested originally with the RespiFinder19 kit were subsequently tested for HBoV detection with the use of virus-specific primers.In addition, all samples were tested by real-time RT-PCR for influenza A following the Centers for Disease Control and Prevention (CDC) protocol [20] .Participants hospitalized during the 28 days of the study follow-up were considered to have severe disease.Hospitalization was defined as participants who were admitted to the hospital or remained in the emergency departments for at least 24 hours.Participants with a detected bacterial pathogen (Bordetella pertussis, Chlamydophila pneumoniae, Legionella pneumophila, and Mycoplasma pneumoniae), no virus, or >2 viruses were excluded.Comorbidities were defined as 1 of the following: chronic obstructive pulmonary disease, cardiovascular disease, diabetes mellitus, previous use of systemic steroids, obesity, overweight, and underweight.For this analysis, we grouped similar genera of viruses and examined the 8 most frequent groups of viruses isolated: influenza (A, A (H1N1)pdm09, and B grouped as influenza), HMPV, HPIV, RSV, RV, HAdV, CoV, and HBoV.Comparisons of baseline factors were made between hospitalization and nonhospitalization groups.All potential risk factors that were not categorical were grouped into categories.Chi-square statistics were used to make the univariate comparisons of the risk factors.Logistic regression models were used to compare hospitalization between all pairs of viruses and the combinations of the 2 viruses.Combinations with <10 participants were not analyzed.Each logistic regression model included sex, age (grouped into 3 categories), days since symptom onset (grouped into 3 categories), and comorbidity (yes\/no).Odds ratios and 95% confidence intervals were calculated.From 2010 to 2014, 5662 participants were included in the ILI-002 study.From these, 96.89% had a 28-day interview, 1619 had no virus isolated, and 32 had no sample; additionally, 85 were excluded for other reasons such as bacterial infections (18 subjects), missing covariate information (11 subjects), and >2 viruses (56 subjects).The final data set had 3926 participants.Of the 3926 participants, 1856 (47.3%) were hospitalized, 1411 (35.9%) were <11 years old, and 308 (7.8%) were >60 years old; 1673 (42.6%) were males (Table 1) .Of the 1856 hospitalized cases, 65 died with 1 virus and 12 died with 2 viruses detected.Table 2 shows the distribution of participants with a single virus diagnosis across the covariates used in the logistic regression models.Influenza, HPIV, CoV, and RV were detected more frequently in participants 11-60 years old, whereas RSV, HMPV, HAdV, and HBoV were more common in children <11 years old.One virus was detected in 3285 and 2 viruses were detected in 641 participants (Table 3) .RV (n = 1433), influenza (n = 888), and CoV (n = 703) were the most frequently detected viruses (either alone or in co-infection).The most frequent combination was influenza+CoV (116 of 641 dual infections; 18%).Influenza was found in combination with other agents in 237 participants (37% of 641 dual infections).There were 52 subjects with a combination of >3 viruses.The numbers were too small to perform any statistical analyses but were analyzed descriptively.In the subjects with 3 viruses detected, 56% had RV, 54% had influenza, and 48% had CoV.The combination of 3 viruses that occurred the most often (in 6 subjects) was influenza, HMPV, and HBoV.The adjusted odds ratios (ORs) for hospitalization rates between each of the viruses included in the study are shown in Figure 1 .Participants infected with HBoV were more likely to be hospitalized than those infected with influenza, CoV, HPIV, and RV ( Figure 1A) .Those with HAdV, HMPV, and RSV had similar but not statistically significant results.Participants infected with RSV were more likely to be hospitalized compared with cases of influenza, CoV, RV, HPIV, HAdV, and, to a lesser extent (not statistically significant), HMPV ( Figure 1B ).Participants with HMPV were more likely to be hospitalized compared with cases of influenza, CoV, and RV, but were not statistically significantly different compared with HPIV and HAdV ( Figure 1C ).HPIV cases were more likely to be hospitalized compared with cases of influenza, CoV, and, to lesser extent, HAdV (as assessed by point estimates) ( Figure 1D ), although none of these comparisons were statistically significant.Participants with HAdV were more likely to be hospitalized compared with cases of influenza and CoV (as assessed by point estimates), although neither of these comparisons reached statistical significance ( Figure 1E ).Participants with RV were more likely to be hospitalized as compared with CoV cases ( Figure 1F ).Although not statistically significant, CoV cases were less likely to be hospitalized as compared with those with influenza ( Figure 1G ).Figure 1H shows comparisons with influenza cases (already described).When 2 viruses were isolated, those with combinations of RSV+HPIV, CoV+HMPV, and CoV+RSV were less likely to be hospitalized than participants infected with individual viruses (Figure 2A-C) .The point estimates for individual viruses in HMPV and RV demonstrated a higher likelihood of these patients being hospitalized than those with combinations, but all confidence intervals included 1 ( Figure 2D ).Participants with HBoV+RV were more likely to be hospitalized than those with RV, but were hospitalized as frequently as those with HBoV alone ( Figure 2J ).The point estimate for severity in CoV+RV was greater than that for individuals for CoV or RV alone ( Figure 2K ), but the confidence interval included 1.The confidence intervals for all other combinations included 1, but the point estimates indicated that some of the combinations could be more severe than 1 of the single agents ( Figure 2L -R).Reports of the impact of multiple viral infections have been more frequent with the availability of PCR assays that detect multiple pathogens [9] [10] [11] [12] [13] [14] [15] .Most reports analyze data by grouping all combinations and compare this group with different single viruses.This has resulted in variable interpretations.ILI-002 is a large study of those with ILI in which a multipathogen PCR assay was performed on samples from all participants.The size of this cohort allowed there to be a sufficient number of participants with various virus combinations to perform separate analyses for some virus combinations and examine whether virus combinations increase severity over individual viruses.Our results highlight the importance of carrying out these separate analyses.Our data demonstrate that the severity of diseases was higher with specific viruses (eg, HBoV, RSV, and HMPV).However, in no combination was the dual infection significantly worse than in both of the individual viruses.Furthermore, as a class effect, it does not appear that infection with >1 virus increases severity of disease.Many of the confidence intervals for the combinations include no difference for each of the comparisons with the individual viruses.Based solely on point estimates, which may change with increasing numbers of participants, there appear to be some patterns that indicate a leading or governing effect of 1 virus in the combination.An example of this is the combination of CoV+RSV ( Figure 2C , panel C); CoV cases and CoV+RSV cases were less severe than cases of only RSV.Moreover, the severity of CoV+RSV cases was no different than that of CoV cases.This could indicate that CoV is the leading\/ governing agent in the combination.Similarly, HBoV may be governing RV in the combination of these 2 viruses (panel J), RV governing CoV (panel K), influenza governing HBoV (panel N), and RV governing RSV (panel P).The confidence intervals around the combinations are often large and include 1, so these interpretations are not conclusive and could differ if larger numbers of participants were studied.However, the pattern observed in the point estimates is suggestive of the governing effect described above and warrants further study.One explanation for the governing results is that virological testing was done only once in each participant, which does not distinguish sequential infections with 2 viruses from simultaneous infection with both viruses.It is possible that these results could reflect sequential infections rather than simultaneous infection and that symptoms (and hospitalization) could be the result of only 1 of the 2 viruses.The sample collection time with respect to the course of illness would then be an important factor.In a study carried out in participants with ILI, viral co-infections were detected more frequently in samples obtained during the first 2 days from symptom onset compared with those obtained after 3-7 days [21] .Thus, it is plausible that detection of co-infections might be the result of prolonged shedding of 1 virus with a subsequent infection with the second virus.Also, it could reflect a reduced ability of a second virus to replicate due to an already initiated host response and the production of interferon as a result of an initial viral infection.Interference of 1 virus with another virus has been shown to occur in vitro [22] , and epidemiological studies suggest that circulation of 1 virus might affect circulation of another virus in communities [23] .Overall, most previous studies have shown similar severity of single infections when compared with mixed infections [16] .However, some studies have shown significant differences between specific combinations of viruses and single viruses.For example, in cases of co-infection with RSV+RV and RSV+HBoV, the illness appeared to be more severe than in cases of RSV or HBoV infection alone [24] .Our results for RSV+RV follow the same pattern, but we did not have sufficient data to study the combination RSV+HBoV.Our analysis showed that participants with detection of only influenza virus were less likely to require hospitalization than participants in whom other viruses were detected.This was observed despite the fact that the study included the 2013-2014 winter season, when a severe wave of influenza A(H1N1) pdm09 was registered in Mexico [25] .This result could be derived from inclusion of all influenza subtypes in the analysis.The lower hospitalization rate in participants with influenza virus infection compared with those with other viruses may also be explained by influenza vaccination.Since 2009, influenza vaccination coverage in Mexico has been high [26] , and influenza vaccination has been reported to reduce influenza hospitalizations [27] .Unfortunately, it was not possible to obtain detailed data regarding influenza vaccination status for study participants to assess this.We also found that for single virus comparisons, HBoV, RSV, and HMPV were associated with severe infections.The RSV and HMPV finding is consistent with other reports that show these viruses to be leading causes of LRTI in children and adults [28] [29] [30] .In contrast, the role of HBoV as a cause of severe infections is less well established.Because HBoV infection is very common and frequently found in asymptomatic participants, the pathogenic role of this virus has been questioned [31, 32] .Children with higher viral loads tend to have more severe infections [33] , longer hospitalization duration [34, 35] , and are found to have co-infection by other viruses [36, 37] less frequently than those with lower viral loads.However, in children in daycare, viral load had no apparent association with severity of illness [31] , which also might reflect challenges in reproducibly measuring viral load in secretions.In all, these studies suggest that HBoV is frequently present in children as an asymptomatic or chronic infection with low viral loads, whereas some infections in which a high viral load is present may be associated with severe infections requiring hospitalization.Our study did not measure viral load, so it is unclear if our HBoV participants represented a sample of high-viral load participants, as we did not include asymptomatic participants with HBoV.The strengths of this study include the large numbers of participants and the consistent baseline testing and follow-up.Limitations include the definition of severity, as hospitalization was a surrogate for actual patient health status.Patients may be hospitalized for causes other than their respiratory illness, such as worsening of comorbidities, observation in high-risk participants, or social reasons.Further studies should be done using direct measures of patient health status such as intensity and duration of participants' symptoms or complications (eg, pneumonia).We have developed a symptom scale for influenza (FLU-PRO) as part of the study ILI-002 that could be used in future studies [38] .Adjusted odds ratio (on log scale) 20 The presence of chronic underlying conditions is an important factor that is associated with risk of developing severe respiratory infections.In addition, it is possible that chronic conditions may increase the risk of acquiring infections by multiple pathogens.A recent study reported that patients with coinfection caused by 2 or 3 different influenza virus strains were more likely to have underlying cardiovascular disorders than those with single influenza infections [39] ; however, no differences were observed in the prevalence of other underlying conditions.Although some other studies have found a higher prevalence of chronic disorders in patients with multiple viral pathogens, these appear to be limited to specific conditions, and no differences have been observed for other disorders [15, 40] .In addition, many studies have not found an association between the presence of chronic disorders and detection of multiple viruses [9, 14, 21, 24] .The main objective of our study was to determine if codetection of 2 viruses was associated with worse outcome, and we did not analyze which factors may have led to acquisition of \u22652 viruses; nevertheless, our analysis included the presence of chronic conditions as a covariate, in order to account for potential confounding.In a previous analysis of ILI-002 limited to children <5 years of age, the severity of single viruses was compared [7] , and the results were similar to our findings for single viruses in the present study.The majority of studies have focused on children, and the effect of mixed viral infections in adults is less clear [40] .One of the strengths of this analysis is that our study population included both pediatric and adult symptomatic participants.Although some comparisons resulted in estimates with wide confidence intervals, our interpretation based on point estimates revealed several patterns and could be hypothesis-generating for future studies.Our results suggest that, in general, having >1 virus detected by PCR on a respiratory sample does not increase the severity of disease from ILI.To assess the differences in hospitalization rates of mixed respiratory infections, it is necessary to carry out analyses between specific combinations of viruses.When 2 viruses are detected, it appears that the clinical severity of a respiratory infection, as defined by hospitalization, may be associated with 1 of these agents.Future studies with a larger number of participants designed to distinguish between sequential and simultaneous infection and using direct measures of patient health status should be of help in defining the role of each virus during the evolution of an acute respiratory episode. Highlight: In addition, many studies have not found","meta":"{'source': 'AI4Code', 'id': 'e3a31560074b3c'}"}
{"id":"16745","text":"\"\"\"\n## Applied Machine Learning in Python - Notebook 1\n\n### Module 1: Simple classification task\n\n\"\"\"\n# Importing required modules\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n# Loading data\nfruits = pd.read_csv('..\/input\/fruits\/fruits.csv')\n# Visualizing data\nfruits.head()\n\"\"\"\nThe features available for each entry are the mass, height, and width of mandarins, oranges, lemons and apples. Heights are measured along the core and widths are the widest measurment perpendicular to the core.\n\"\"\"\n# Creating dictionary with fruit labels as keys and names as values\nfruit_name = dict(zip(fruits.fruit_label.unique(), fruits.fruit_name.unique()))\nfruit_name\n\"\"\"\n### Examing the data\n\"\"\"\n# lists with features and labels\nX = fruits[['height', 'width', 'mass', 'color_score']]\ny = fruits['fruit_label']\n\n# Splitting in train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n# plotting a scatter matrix\nfrom matplotlib import cm\nfrom pandas.plotting import scatter_matrix\n\ncmap = cm.get_cmap('gnuplot')\nscatter = scatter_matrix(X_train, c= y_train, marker = 'o', s=40, hist_kwds={'bins':15}, figsize=(7,7), cmap=cmap)\n# plotting a 3D scatter plot\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection = '3d')\nax.scatter(X_train['width'], X_train['height'], X_train['color_score'], c = y_train, marker = 'o', s=100)\nax.set_xlabel('width')\nax.set_ylabel('height')\nax.set_zlabel('color_score')\nplt.show()\n\"\"\"\n### Creating a K-nearest neighbors classifier object\n\"\"\"\n# Choosing features\nX = fruits[['mass', 'width', 'height']]\ny = fruits['fruit_label']\n\n# Tran test split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier(n_neighbors = 5)\n\n# Training\nknn.fit(X_train, y_train)\n\n# Estimating accuracy using test data\nknn.score(X_test, y_test)\n\"\"\"\n### Classifying unseen data\n\"\"\"\n# first example: a small fruit with mass 20g, width 4.3 cm, height 5.5 cm\nfruit_prediction = knn.predict([[20, 4.3, 5.5]])\nfruit_name[fruit_prediction[0]]\n\"\"\"\n### Plotting k-NN classifier decision boundaries\n\"\"\"\n## Code by Shahul Es stack overflow\n\nimport matplotlib.cm as cm\nfrom matplotlib.colors import ListedColormap, BoundaryNorm\nimport matplotlib.patches as mpatches\nimport matplotlib.patches as mpatches\n\n\ndef plot_fruit_knn(X, y, n_neighbors, weights):\n    X_mat = X[['height', 'width']].values\n    y_mat = y.values\n# Create color maps\n    cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#FCBF56','#FFFD6B'])\n    cmap_bold  = ListedColormap(['#FF0000', '#00FF00', '#FFA100','#E8E500'])\n    clf = KNeighborsClassifier(n_neighbors, weights=weights)\n    clf.fit(X_mat, y_mat)\n# Plot the decision boundary by assigning a color in the color map\n    # to each mesh point.\n\n    mesh_step_size = .01  # step size in the mesh\n    plot_symbol_size = 50\n\n    x_min, x_max = X_mat[:, 0].min() - 1, X_mat[:, 0].max() + 1\n    y_min, y_max = X_mat[:, 1].min() - 1, X_mat[:, 1].max() + 1\n    xx, yy = np.meshgrid(np.arange(x_min, x_max, mesh_step_size),\n                         np.arange(y_min, y_max, mesh_step_size))\n    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n# Put the result into a color plot\n    Z = Z.reshape(xx.shape)\n    plt.figure()\n    plt.pcolormesh(xx, yy, Z, cmap=cmap_light, shading='auto')\n# Plot training points\n    plt.scatter(X_mat[:, 0], X_mat[:, 1], s=plot_symbol_size, c=y, \n                cmap=cmap_bold, edgecolor = 'black')\n    plt.xlim(xx.min(), xx.max())\n    plt.ylim(yy.min(), yy.max())\n    patch0 = mpatches.Patch(color='#FF0000', label='apple')\n    patch1 = mpatches.Patch(color='#00FF00', label='mandarin')\n    patch2 = mpatches.Patch(color='#FFA100', label='orange')\n    patch3 = mpatches.Patch(color='#E8E500', label='lemon')\n    plt.legend(handles=[patch0, patch1, patch2, patch3])\n\n#plt.title(\"4-Class classification (k = %i, weights = '%s')\" % (n_neighbors, weights))    \n\nplot_fruit_knn(X_train, y_train, 5, 'uniform')\nplt.xlabel('height (cm)')\nplt.ylabel('width (cm)')\nplt.show()\n\"\"\"\n### Checking k-NN accuracy sensitivity to the k parameter\n\"\"\"\nk_range = range(1,20)\nscores = []\n\nfor k in k_range:\n    knn = KNeighborsClassifier(n_neighbors = k)\n    knn.fit(X_train, y_train)\n    scores.append(knn.score(X_test, y_test))\n\nplt.figure()\nplt.xlabel('k')\nplt.ylabel('accuracy')\nplt.scatter(k_range, scores)\nplt.xticks([0,5,10,15,20]);\n\"\"\"\n### Checking k-NN accuracy sensitivity to the train\/test split proportion\n\"\"\"\nt = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]\n\nknn = KNeighborsClassifier(n_neighbors = 5)\n\nplt.figure()\n\nfor s in t:\n\n    scores = []\n    for i in range(1,1000):\n        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1-s)\n        knn.fit(X_train, y_train)\n        scores.append(knn.score(X_test, y_test))\n    plt.plot(s, np.mean(scores), 'bo')\n\nplt.xlabel('Training set proportion (%)')\nplt.ylabel('accuracy');","meta":"{'source': 'AI4Code', 'id': '1e8d8d95218ae9'}"}
{"id":"46299","text":"# 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 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\nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom textblob import TextBlob\nfrom sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn import decomposition, ensemble\n\nimport pandas, xgboost, numpy, textblob, string\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix, accuracy_score, mean_squared_error, r2_score, roc_auc_score, roc_curve, classification_report\nfrom sklearn.model_selection import train_test_split\n\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n\ntrain  =pd.read_csv(\"..\/input\/nlp-getting-started\/train.csv\")\ntrain.head()\ntrain.isnull().sum()\n#Dropping unncessary columns\ntrain.drop([\"keyword\",\"location\"],axis = 1,inplace = True)\n\n\"\"\"\n# Cleaning  & Preprocessing\n\"\"\"\ntrain[\"text\"] = train[\"text\"].apply(lambda x : \" \".join(x.lower() for x in x.split()))\ntrain.head()\n\"\"\"\n## Dropping Numbers\n\"\"\"\ntrain[\"text\"] = train[\"text\"].str.replace(\"\\d\",\"\")\ntrain.head()\n\"\"\"\n## Dropping punctuation marks\n\"\"\"\ntrain[\"text\"] = train[\"text\"].str.replace(\"[^\\w\\s]\",\"\")\ntrain.head()\nimport nltk \nnltk.download(\"stopwords\")\n\"\"\"\n## Stopwords\n\n**Stopwords** : Words that are filtered out by Web search engines and other enterprise searching and indexing platforms. Stop words are natural language words which have very little meaning, such as \"and\", \"the\", \"a\", \"an\", and similar words.\n\"\"\"\nfrom nltk.corpus import stopwords\nsw = stopwords.words(\"english\")\nsw.append(\"u\")\nsw.append(\"im\")\ntrain[\"text\"] = train[\"text\"].apply(lambda x: \" \".join(x for x in x.split() if x not in sw))\n\"\"\"\n## Lemmatization\n\n**Lemmatization :** In linguistics, it is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Putting an example to the definition, \u201ccomputers\u201d is an inflected form of \u201ccomputer\u201d, the same logic as \u201cdogs\u201d being an inflected form of \u201cdog\u201d.\n\"\"\"\nfrom textblob import Word\nnltk.download(\"wordnet\")\ntrain[\"text\"] = train[\"text\"].apply(lambda x: \" \".join([Word(word).lemmatize() for word in x.split()]))\ntrain.head()\n#regex\ntrain[\"text\"] = train[\"text\"].str.replace('http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',\"\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"We're\", \"We are\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"That's\", \"That is\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"won't\", \"will not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"they're\", \"they are\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"Can't\", \"Cannot\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"wasn't\", \"was not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"don\\x89\u00db\u00aat\", \"do not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"aren't\", \"are not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"isn't\", \"is not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"You're\", \"You are\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"I'M\", \"I am\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"shouldn't\", \"should not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"wouldn't\", \"would not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"i'm\", \"I am\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"We've\", \"We have\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"Didn't\", \"Did not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"it's\", \"it is\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"can't\", \"cannot\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"don't\", \"do not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"you're\", \"you are\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"I've\", \"I have\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"Don't\", \"do not\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"I'll\", \"I will\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"Let's\", \"Let us\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"Could've\", \"Could have\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"youve\", \"you have\")\ntrain[\"text\"] = train[\"text\"].str.replace(r\"It's\", \"It is\")\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n## Visualisation\n\"\"\"\nfreq = (train[\"text\"][0:1000]).apply(lambda x: pd.value_counts(x.split(\" \"))).sum(axis = 0).reset_index()\nfreq.columns = [\"words\",\"tf\"]\nx = freq[freq[\"tf\"] > 30].sort_values(by = \"tf\" ,ascending = False)\nx.plot.bar(x = \"words\", y = \"tf\",color = \"pink\");\n#WordCloud for the first 5 row\nfor i in range (0,5):\n    text = train[\"text\"][i]\n    wordcloud = WordCloud().generate(text)\n    plt.imshow(wordcloud, interpolation = \"bilinear\")\n    plt.axis(\"off\")\n    plt.show()\n    print(\"***********************************************\")\nfrom nltk.tokenize import sent_tokenize, word_tokenize \nimport warnings \n  \nwarnings.filterwarnings(action = 'ignore') \n  \nimport gensim \nfrom gensim.models import Word2Vec \nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nx_train, x_test, y_train, y_test = train_test_split(train[\"text\"], train[\"target\"],\n                                                    test_size = 0.3,\n                                                    random_state = 18)\n\"\"\"\n# Prediction\n\"\"\"\n\"\"\"\n## Count Vector\n\n\n![count%20vector.png](attachment:count%20vector.png)\n\nBy word frequency we indicate the number of times each token occurs in a text. When talking about word frequency, we distinguish between types and tokens. Types are the distinct words in a corpus, whereas tokens are the words, including repeats. Let's see how this works in practice.\n\"\"\"\nvectorizer = CountVectorizer()\nvectorizer.fit(x_train)\nx_train_count = vectorizer.transform(x_train)\nx_test_count = vectorizer.transform(x_test)\n\"\"\"\n## Logistic Regression\n\"\"\"\nloj = linear_model.LogisticRegression()\nloj_model = loj.fit(x_train_count, y_train)\ny_pred = loj_model.predict(x_test_count)\n\n\naccuracy_score(y_test,y_pred)\n\"\"\"\n## Naive Bayes\n\"\"\"\nx_train_count\nnb = naive_bayes.MultinomialNB()\nnb_model = nb.fit(x_train_count,y_train)\ny_pred = nb_model.predict(x_test_count)\naccuracy_score(y_test,y_pred)\n\"\"\"\n## RF\n\"\"\"\nrf = ensemble.RandomForestClassifier()\nrf_model = rf.fit(x_train_count,y_train)\ny_pred = rf_model.predict(x_test_count)\naccuracy_score(y_test,y_pred)\n\"\"\"\n## XGBOOST\n\"\"\"\nxgb = xgboost.XGBClassifier()\nxgb_model = xgb.fit(x_train_count,y_train)\ny_pred = xgb_model.predict(x_test_count)\naccuracy_score(y_test,y_pred)\n\"\"\"\n## TF-IDF Word Level\n\n![tf%20idf.png](attachment:tf%20idf.png)\n\n\n\n**Term-frequency-inverse document frequency (TF-IDF)** is another way to judge the topic of an article by the words it contains. With TF-IDF, words are given weight \u2013 TF-IDF measures relevance, not frequency. That is, wordcounts are replaced with TF-IDF scores across the whole dataset.\n\n\n\n\"\"\"\ntf_idf_word_vectorizer = TfidfVectorizer()\n\ntf_idf_word_vectorizer.fit(x_train)\nx_train_tf_idf_word = tf_idf_word_vectorizer.transform(x_train)\nx_test_tf_idf_word = tf_idf_word_vectorizer.transform(x_test)\n\"\"\"\n## Logistic Regression\n\"\"\"\nloj = linear_model.LogisticRegression()\nloj_model = loj.fit(x_train_tf_idf_word, y_train)\ny_pred = loj_model.predict(x_test_tf_idf_word)\naccuracy_score(y_test,y_pred)\n\"\"\"\n## Naive Bayes\n\"\"\"\nnb = naive_bayes.MultinomialNB()\nnb_model = nb.fit(x_train_tf_idf_word,y_train)\ny_pred = nb.predict(x_test_tf_idf_word)\naccuracy_score(y_test,y_pred)\n\"\"\"\n## For the test\n\n\"\"\"\ntest = pd.read_csv(\"..\/input\/nlp-getting-started\/test.csv\")\ntest.drop([\"keyword\",\"location\"],axis = 1,inplace = True)\ndef prep(test):\n    \n    \n    test[\"text\"] = test[\"text\"].apply(lambda x : \" \".join(x.lower() for x in x.split()))\n    \n    test[\"text\"] = test[\"text\"].str.replace(\"\\d\",\"\")\n    \n    test[\"text\"] = test[\"text\"].str.replace(\"[^\\w\\s]\",\"\")\n    \n    test[\"text\"] = test[\"text\"].apply(lambda x: \" \".join(x for x in x.split() if x not in sw))\n    \n    test[\"text\"] = test[\"text\"].apply(lambda x: \" \".join([Word(word).lemmatize() for word in x.split()]))\n    \n    test[\"text\"] = test[\"text\"].str.replace('http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',\"\")\n    \n    test[\"text\"] = test[\"text\"].str.replace(r'(((http)(s)?|www(.)?)(:\/\/)?\\S+)',\"\")\n    \n    test[\"text\"] = test[\"text\"].str.replace(r\"\\x89\u00db\u00d3\", \"\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"he's\", \"he is\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"there's\", \"there is\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"We're\", \"We are\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"That's\", \"That is\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"won't\", \"will not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"they're\", \"they are\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"Can't\", \"Cannot\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"wasn't\", \"was not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"don\\x89\u00db\u00aat\", \"do not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"aren't\", \"are not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"isn't\", \"is not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"You're\", \"You are\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"I'M\", \"I am\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"shouldn't\", \"should not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"wouldn't\", \"would not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"i'm\", \"I am\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"We've\", \"We have\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"Didn't\", \"Did not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"it's\", \"it is\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"can't\", \"cannot\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"don't\", \"do not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"you're\", \"you are\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"I've\", \"I have\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"Don't\", \"do not\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"I'll\", \"I will\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"Let's\", \"Let us\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"Could've\", \"Could have\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"youve\", \"you have\")\n    test[\"text\"] = test[\"text\"].str.replace(r\"It's\", \"It is\")\n    \n\n    \n    return test\n  \n\n\ndf = prep(test)\n\ntest_x = df[\"text\"]\nvectorizer = CountVectorizer()\nvectorizer.fit(test_x)\nvectorizer.transform(test_x)\n vectorizer.transform(test_x)\nx_test_co= vectorizer.transform(test_x)\nx_train_count = vectorizer.transform(x_train)\nnb = naive_bayes.MultinomialNB()\nnb_model = nb.fit(x_train_count,y_train)\ny_pred = nb_model.predict(x_test_co)\ny_pred\ndictt = {}\ndictt['id'] = test.id\ndictt['target'] = y_pred\nsubmission = pd.DataFrame(dictt)\nsubmission\n#submission.to_csv(\"submission3.csv\" , index = None)\n\"\"\"\n# Credits\n\n\nhttps:\/\/www.webopedia.com\/TERM\/S\/stop_words.html\n\nhttps:\/\/www.twinword.com\/blog\/what-is-lemmatization\/\n\nhttps:\/\/port.sas.ac.uk\/mod\/book\/view.php?id=583&chapterid=381#:~:text=2.3%20Word%20count,-After%20tokenising%20a&text=By%20word%20frequency%20we%20indicate,how%20this%20works%20in%20practice.\n\nhttps:\/\/wiki.pathmind.com\/bagofwords-tf-idf\n\nhttps:\/\/medium.com\/deep-math-machine-learning-ai\/chapter-9-1-nlp-word-vectors-d51bff9628c1\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '555453dd8b483b'}"}
{"id":"65061","text":"import numpy as np \nimport pandas as pd\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!pip install py7zr\nimport py7zr\nfrom subprocess import check_output\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        archive = py7zr.SevenZipFile(os.path.join(dirname, filename), mode='r')\n        archive.extractall(path=\"\/kaggle\/working\")\n        archive.close()\n\nprint(check_output([\"ls\", \"..\/working\"]).decode(\"utf8\"))\n#train = pd.read_csv(\"..\/input\/train.csv\")\ntest = pd.read_csv(\"..\/working\/test.csv\")\nstores = pd.read_csv(\"..\/working\/stores.csv\")\nitems = pd.read_csv(\"..\/working\/items.csv\")\ntrans = pd.read_csv(\"..\/working\/transactions.csv\")\noil = pd.read_csv(\"..\/working\/oil.csv\")\nholiday = pd.read_csv(\"..\/working\/holidays_events.csv\")\nprint(\"done\")\n\"\"\"\nSince train.csv has 125 mil records, it is best to consider performing some data engineering before starting any analysis.\n\"\"\"\n#check memory use for the two biggest files - train and test\n#mem_train = train.memory_usage(index=True).sum()\nmem_test=test.memory_usage(index=True).sum()\n#print(\"train dataset uses \",mem_train\/ 1024**2,\" MB\")\nprint(\"test dataset uses \",mem_test\/ 1024**2,\" MB\")\n\ntest.head()\n# optimize test.csv\n# First check the contents of train.csv\nprint(test.max())\nprint(test.min())\n#check datatypes\nprint(test.dtypes)\n#There are only 54 stores\ntest['store_nbr'] = test['store_nbr'].astype(np.uint8)\n\n# The ID column is a continuous number from 1 to 128867502 in train and 128867503 to 125497040 in test\ntest['id'] = test['id'].astype(np.uint32)\n\n# item number is unsigned \ntest['item_nbr'] = test['item_nbr'].astype(np.uint32)\n\n#Converting the date column to date format\ntest['date']=pd.to_datetime(test['date'],format=\"%Y-%m-%d\")\n\n#check memory\nprint(test.memory_usage(index=True))\nnew_mem_test=test.memory_usage(index=True).sum()\nprint(\"test dataset uses \",new_mem_test\/ 1024**2,\" MB after changes\")\nprint(\"memory saved =\",(mem_test-new_mem_test)\/ 1024**2,\" MB\")\n\"\"\"\n# Around 50% save in memory utilization\n\"\"\"\nprint(test.memory_usage())\n\n#check range of float 16\nmin_value = np.finfo(np.float16).min\nmax_value = np.finfo(np.float16).max\nprint(\"range of float16 is\",min_value,max_value)\ndtype_dict={\"id\":np.uint32,\n            \"store_nbr\":np.uint8,\n            \"item_nbr\":np.uint32,\n            \"unit_sales\":np.float32\n           }\n\ntrain_part1 = pd.read_csv(\"..\/working\/train.csv\",dtype=dtype_dict,usecols=[0,2,3,4])\nprint(train_part1.dtypes)\ntrain_part2=pd.read_csv(\"..\/working\/train.csv\",dtype=dtype_dict,usecols=[1,5],parse_dates=[0])\ntrain_part2['Year'] = pd.DatetimeIndex(train_part2['date']).year\ntrain_part2['Month'] = pd.DatetimeIndex(train_part2['date']).month\ntrain_part2['Day'] =pd.DatetimeIndex(train_part2['date']).day.astype(np.uint8)\ndel(train_part2['date'])\ntrain_part2['Day']=train_part2['Day'].astype(np.uint8)\ntrain_part2['Month']=train_part2['Month'].astype(np.uint8)\ntrain_part2['Year']=train_part2['Year'].astype(np.uint16)\n\n#impute the missing values to be -1\ntrain_part2[\"onpromotion\"].fillna(0, inplace=True)\ntrain_part2[\"onpromotion\"]=train_part2[\"onpromotion\"].astype(np.int8)\nprint(train_part2.head())\nprint(train_part2.dtypes)\n# joining part one and two\n# For people familiar with R , the equivalent of cbind in pandas is the following command\ntrain = pd.concat([train_part1.reset_index(drop=True), train_part2], axis=1)\n#drop temp files\ndel(train_part1)\ndel(train_part2)\n#Further Id is just an indicator column, hence not required for analysis\nid=train['id']\ndel(train['id'])\n# check memory\nprint(train.memory_usage())\n#The extracted train.csv file is approx 5 GB\nmem_train=5*1024**3\nnew_mem_train=train.memory_usage().sum()\nprint(\"Train dataset uses \",new_mem_train\/ 1024**2,\" MB after changes\")\nprint(\"memory saved is approx\",(mem_train-new_mem_train)\/ 1024**2,\" MB\")\n\"\"\"\n1.6GB is a managable size\n\"\"\"\n\"\"\"\n# Now lets look into the dataset\n\"\"\"\n\"\"\"\n\n\n## Further to make EDA easier, rolling up the sales to different levels\n\n - Day-Store level\n - Day-Item level\n - Store level\n - Item level\n - Day level\n\n\n\"\"\"\n\"\"\"\n\n Store-day level sale -- This variable indicates the sale of a particular store over time\n\n Store-day level count -- This variable gives an indication of the variaty\/spread of the items sold\n\n Item-day level sale -- Sale of an item over time\n \n Item-day level count -- This gives an indication of the popularity of the item across the supermarket chain.\n\n\"\"\"\nsale_day_store_level=train.groupby(['Year','Month','Day','store_nbr'])['unit_sales'].sum()\nsale_day_item_level=train.groupby(['Year','Month','Day','item_nbr'])['unit_sales'].sum()\ndef aggregate_level1(df):\n    #day-store level\n    sale_day_store_level=df.groupby(['Year','Month','Day','store_nbr'],as_index=False)['unit_sales'].agg(['sum','count'])\n    #drop index and rename\n    sale_day_store_level=sale_day_store_level.reset_index().rename(columns={'sum':'store_sales','count':'item_variety'})\n    \n    #day-item level  \n    sale_day_item_level=df.groupby(['Year','Month','Day','item_nbr'],as_index=False)['unit_sales'].agg(['sum','count'])\n    sale_day_item_level=sale_day_item_level.reset_index().rename(columns={'sum':'item_sales','count':'store_spread'})\n    \n    #store item level   \n    sale_store_item_level=df.groupby(['Year','store_nbr','item_nbr'],as_index=False)['unit_sales'].agg(['sum','count'])\n    sale_store_item_level=sale_store_item_level.reset_index().rename(columns={'sum':'item_sales','count':'entries'})\n\n    return sale_day_store_level,sale_day_item_level,sale_store_item_level\nimport time\nstart_time = time.time()\nsale_day_store_level,sale_day_item_level,sale_store_item_level=aggregate_level1(train)\n\nend_time=time.time()\ntime_taken=end_time-start_time\nprint(\"This block took \",time_taken,\"seconds\")\nsale_day_store_level.to_csv(\"sale_day_store_level.csv\")\nsale_day_item_level.to_csv(\"sale_day_item_level.csv\")\nsale_store_item_level.to_csv(\"sale_store_item_level.csv\")","meta":"{'source': 'AI4Code', 'id': '7801cabf78f0ff'}"}
{"id":"13781","text":"import numpy as np\nimport collections as c\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nfrom IPython.display import display\nfrom ipywidgets import interact_manual\nimport ipywidgets as widgets\n#Calcula a probabilidade de cair x caras ou y coroas\ndef calcula_probabilidade(moeda,qtd_lancamentos,qtd_cara,qtd_coroa,p_cara=0.5):\n    \n    qtd_lancamentos = qtd_lancamentos\n    qtd_cara = qtd_cara \n    qtd_coroa = qtd_coroa \n    p_coroa = 1 - p_cara\n        \n    prob = p_cara**qtd_cara * p_coroa**(qtd_lancamentos-qtd_cara) * math.factorial(qtd_lancamentos)\/(math.factorial(qtd_cara)*math.factorial(qtd_lancamentos-qtd_cara)) + \\\n           p_coroa**qtd_coroa * p_cara**(qtd_lancamentos-qtd_coroa) * math.factorial(qtd_lancamentos)\/(math.factorial(qtd_coroa)*math.factorial(qtd_lancamentos-qtd_coroa))\n\n    print(\"Para uma moeda %s, em %d lan\u00e7amentos, a probabilidade de cair %d Caras ou %d Coroas \u00e9 %.3f\" %(moeda,qtd_lancamentos,qtd_cara,qtd_coroa,prob))\n\n#Gera N lan\u00e7amentos aleat\u00f3rios de moeda\ndef gera_lancamentos(moeda,qtd_lancamentos,p_cara=0.5):\n    eventos = ['K','C']\n    p_coroa = 1 - p_cara\n\n    probabilidades = [p_cara,p_coroa]\n    lancamentos = np.random.choice(eventos,p=probabilidades,size=qtd_lancamentos)\n    contagem = c.Counter(lancamentos)  \n    \n    return contagem\n\n#Mostra os n\u00fameros obtidos com gera_lancamentos\ndef mostra_probabilidades(contagem):\n    print('Quantidade de Caras: ',contagem['K'])\n    print('P(K): ', contagem['K']\/sum(contagem.values()))\n    print('Quantidade de Coroas: ',contagem['C'])\n    print('P(C): ', contagem['C']\/sum(contagem.values()))\n    \n#Plota grafico de lan\u00e7amentos\ndef grafico_lancamentos(moeda='justa',qtd_lancamentos=2000,p_cara=50):\n    p_cara=p_cara\/100\n    probabilidades = pd.DataFrame(data={},columns=['qtd_lancamentos','prob_cara'])\n    for i in range(1,qtd_lancamentos,10):\n        contagem = gera_lancamentos(moeda,i,p_cara)\n        prob_cara = contagem['K']\/sum(contagem.values())\n        probabilidades.loc[i,'qtd_lancamentos'] = i\n        probabilidades.loc[i,'prob_cara'] = prob_cara\n\n    fig = plt.figure(figsize=(30,5))\n    ax = fig.add_subplot(1,1,1)\n    l1 = ax.plot(probabilidades['qtd_lancamentos'],probabilidades['prob_cara'],label = 'Probabilidade calculada')\n    l3 = ax.axhline(y=p_cara,linewidth=2, label = 'Probabilidade esperada', linestyle='--',color='r')\n    ax.set_ylim(ymin=0,ymax=1)\n    handles, labels = ax.get_legend_handles_labels()\n    ax.legend(handles, labels, loc=2,prop={'size': 18})\n    ax.set_title('P(K) de acordo com a quantidade de lan\u00e7amentos', size=24)\n    ax.set_ylabel('Probabilidade',size=20)\n    ax.set_xlabel('Quantidade de Lan\u00e7amentos',size=20)\n    plt.xticks(fontsize=16)\n    plt.yticks(fontsize=16)\n\"\"\"\nOBS: Para conseguir executar as c\u00e9lulas de c\u00f3digo e mudar os par\u00e2metros dos exemplos, clique em \"Copiar e editar\". Para executar uma c\u00e9lula, basta clicar sobre ela e, em seguida, no bot\u00e3o \"Run\" \u00e0 esquerda (com formato de tri\u00e2ngulo).\n\"\"\"\n\"\"\"\n# Introdu\u00e7\u00e3o \u00e0 Ci\u00eancia de dados\n\"\"\"\n\"\"\"\n#### Porque usar dados?\nO uso de dados nas organiza\u00e7\u00f5es sempre existiu, mesmo que de forma escassa e pouco estruturada, mas foram os recentes avan\u00e7os na tecnologia que possibilitaram o in\u00edcio da utiliza\u00e7\u00e3o de grandes volumes de dados.\nAt\u00e9 pouco tempo atr\u00e1s, algoritmos que poderiam ser utilizados na identifica\u00e7\u00e3o de padr\u00f5es e correla\u00e7\u00f5es ou na constru\u00e7\u00e3o de modelos de previs\u00e3o demoravam dias para processarem grandes volumes de informa\u00e7\u00e3o. Atualmente algumas an\u00e1lises podem acontecer em tempo real, permitindo que a lideran\u00e7a tome decis\u00f5es cada vez mais r\u00e1pidas e assertivas.\nDessa forma, o uso de an\u00e1lise de dados \u00e9 algo que as organiza\u00e7\u00f5es n\u00e3o podem ignorar. \n\nAl\u00e9m disso, h\u00e1 alguns anos, o uso de *Big Data & Analytics* parecia uma tarefa impratic\u00e1vel em fun\u00e7\u00e3o da restri\u00e7\u00e3o de informa\u00e7\u00f5es e de tecnologias dispon\u00edveis para implementar o uso de dados em uma empresa. Mas hoje, o uso de sistemas e estrat\u00e9gias para coleta, armazenagem e an\u00e1lise de dados est\u00e1 cada vez mais presente no dia a dia das grandes organiza\u00e7\u00f5es, trazendo in\u00fameros benef\u00edcios para as diversas linhas de neg\u00f3cio, e principalmente, auxiliando em r\u00e1pidas tomadas de decis\u00e3o, de forma que as empresas que n\u00e3o fazem proveito de seus dados estar\u00e3o sempre um passo atr\u00e1s dos seus competidores.\n\nUma an\u00e1lise mais avan\u00e7ada dos dados permite identificar oportunidades de melhoria em uma companhia, tais como:\n\n- O armazenamento de dados do hist\u00f3rico de compras permite uma comunica\u00e7\u00e3o mais efetiva com o cliente, proporcionando um melhor servi\u00e7o ao consumidor\n\n\n- O uso de dados obtidos em redes sociais, e-commerce ou pesquisas auxiliam na percep\u00e7\u00e3o de como determinado produto est\u00e1 sendo utilizado e recebido pelo mercado consumidor, servindo como feedback para futuros lan\u00e7amentos\n\n\n- A efici\u00eancia operacional de uma empresa pode ser totalmente transformada. A an\u00e1lise de dados pode ajudar na melhoria dos processos de manufatura, distribui\u00e7\u00e3o, gest\u00e3o de estoque, aloca\u00e7\u00e3o de pessoas e em diversas outras \u00e1reas\n\n\nA Ci\u00eancia de Dados \u00e9 uma \u00e1rea multidisciplinar, que envolve conhecimentos de Matem\u00e1tica, Estat\u00edstica, Ci\u00eancia da Computa\u00e7\u00e3o e \u00c1rea de Neg\u00f3cio para extrair valor dos dados. O diagrama abaixo mostra como a intersec\u00e7\u00e3o de campos diferentes do conhecimento formam o que chamamos de Ci\u00eancia de dados.\n\n![img](https:\/\/www.datocms-assets.com\/14946\/1596797558-da-vs-ds-diagram.png)\n\"\"\"\n\"\"\"\nVamos come\u00e7ar pelo c\u00edrculo da matem\u00e1tica, com probabilidade!\n\"\"\"\n\"\"\"\n# Probabilidade\n\"\"\"\n\"\"\"\n### Por Que Come\u00e7ar com Probabilidade?\n\nA probabilidade est\u00e1 em todo lugar!\n\nProbabilidade \u00e9 a ci\u00eancia da incerteza. Portanto, sempre que houver alguma d\u00favida sobre um evento, os conceitos de probabilidade s\u00e3o envolvidos para estimar a probabilidade de um evento. Se queremos prever um resultado de uma vari\u00e1vel que pode assumir um dos muitos valores dispon\u00edveis, precisamos envolver a matem\u00e1tica da probabilidade. \n\nPortanto, podemos usar a teoria da probabilidade em diversas situa\u00e7\u00f5es, seja em nossas vidas pessoais ou profissionais. A incerteza sempre estar\u00e1 l\u00e1, mas ela pode ser medida, pode ser gerenciada..\n\nIdentifica\u00e7\u00e3o de transa\u00e7\u00f5es fraudulentas, classifica\u00e7\u00e3o de c\u00e2ncer em benigno e maligno, separa\u00e7\u00e3o de emails de forma autom\u00e1tica em grupos espec\u00edficos... s\u00e3o exemplos de problemas que envolvem probabilidade aplicados no dia-a-dia de Ci\u00eancia de Dados.\n\"\"\"\n\"\"\"\n### O Que \u00e9 Espa\u00e7o de Probabilidade?\nUm espa\u00e7o de probabilidade \u00e9 usado para modelar experimentos. Existem tr\u00eas componentes em um espa\u00e7o de probabilidade: espa\u00e7o de amostra, eventos e medida de probabilidade.\n\n#### 1. Espa\u00e7o de Amostra\n\n\u00c9 um conjunto de todos os resultados poss\u00edveis, ou seja, uma cole\u00e7\u00e3o \u00fanica de elementos envolvendo todos as possibilidades de resultados. Por exemplo, o espa\u00e7o de amostra ao jogar um dado \u00e9: $S = \\{1, 2, 3, 4, 5, 6\\}$, pois o dado com 6 faces oferece 6 resultados poss\u00edveis sempre que o dado \u00e9 jogado.\n\nO espa\u00e7o de amostra de um movimento do pre\u00e7o das a\u00e7\u00f5es pode ser $S = \\{Aumenta, Igual, Diminui\\}$. Como Aumenta \u00e9 um elemento de S, podemos escrever como Aumenta \u2208 S (Aumenta pertence a S).\n\n#### 2. Eventos\n\nUm evento \u00e9 um conjunto de resultados (um subconjunto do espa\u00e7o amostral) ao qual \u00e9 associado um valor de probabilidade. Assim, podemos dizer que, para um espa\u00e7o amostral com um n\u00famero finito de elementos, qualquer subconjunto seu \u00e9 um evento. Confuso? Vejamos um exemplo:\n\nUm baralho de 52 cartas tem um espa\u00e7o amostral de 52 elementos, um associado a cada uma das 52 cartas. Um evento \u00e9 qualquer subconjunto do espa\u00e7o amostral, incluindo qualquer elemento sozinho, o conjunto vazio (definido como tendo probabilidade 0) e o conjunto inteiro de 52 cartas (com probabilidade 1). Outros eventos s\u00e3o subconjuntos cont\u00eam m\u00faltiplos elementos. Algumas possibilidades:\n\n - \u201cO 5 de Copas\u201d (1 elemento),\n - \u201cUm Rei\u201d (4 elementos),\n - \u201cUma carta de Espadas\u201d (13 elementos),\n - \u201cUma carta\u201d (52 elementos).\n\n#### 3. Medida de Probabilidade\n\nSendo assim, podemos definir a probabilidade de um evento x como:\n\n$P(x) = \\frac{n(E)}{n(S)}$\n\"\"\"\n\"\"\"\n# Probabilidade  na pr\u00e1tica: Lan\u00e7amento de moeda\n\nA fim de apresentar algumas regras de probabilidade, vejamos um exemplo aplicado a lan\u00e7amento de moedas.\n\n![img](https:\/\/docplayer.com.br\/docs-images\/69\/60074537\/images\/1-1.jpg)\n\nConsidere uma moeda justa padr\u00e3o com dois lados: Cara (K) e coroa (C). Se eu jogar a moeda no ar, talvez veja cara ou coroa quando ela cair na minha m\u00e3o. Para esse tipo de moeda, a probabilidade de obter cara, P(K), \u00e9 0,5 e a probabilidade de obter coroa, P(C), tamb\u00e9m \u00e9 0,5. Dessa forma, podemos dizer que a soma das probabilidades individuais \u00e9 igual a 1, ou seja, $P(K) + P(C) = 1$. O mesmo princ\u00edpio se aplica no caso de um dado justo de 6 lados, por exemplo; a probabilidade de que o dado caia em um dos lados \u00e9 a mesma, $\\frac{1}{6}$, e, dessa forma, a soma das probabilidades \u00e9 1 ($P(1)+P(2)+P(3)+P(4)+P(5)+P(6)=1$). Isso mostra o porqu\u00ea da **probabilidade de um evento** ser sempre um valor **entre 0 e 1**.\n\nRetomando nosso jogo de moedas, podemos ver que cara e coroa s\u00e3o os dois resultados poss\u00edveis, o que permite definir 2 regras da probabilidade:\n\n**1. Princ\u00edpio da Multiplica\u00e7\u00e3o:** Se jogarmos uma moeda duas vezes, a probabilidade de ver cara nas duas vezes, ou seja, Cara **E** Cara, \u00e9 $P(K).P(K) = \\frac{1}{2}\\frac{1}{2} = \\frac{1}{4}$;\n\n**2. Princ\u00edpio da Adi\u00e7\u00e3o:** Se jogarmos uma moeda duas vezes, a probabilidade de ver Cara **OU** Coroa \u00e9 1 pois, $P(K) + P(C) = (0,5 + 0,5) = 1$. \n\nEsses dois eventos s\u00e3o independentes um do outro, porque jogar uma moeda uma vez n\u00e3o afeta o resultado de nosso pr\u00f3ximo teste.\n\n### Exerc\u00edcio 1: Moeda Justa\n\nVamos supor que queremos saber a probabilidade de tirar 2 coroas **OU** 2 caras em 3 lan\u00e7amentos de moeda, isto \u00e9, queremos que **2 lan\u00e7amentos sejam Cara e 1 Coroa ou que 2 sejam Coroa e 1 seja Cara**. Temos:\n\n| 1\u00ba | 2\u00ba | 3\u00ba |\n|----|----|----|\n| K  | K  | K  |\n| K  | C  | K  |\n| K  | K  | C  |\n| C  | K  | K  |\n| C  | K  | C  |\n| C  | C  | K  |\n| K  | C  | C  |\n| C  | C  | C  |\n\n\"\"\"\n\"\"\"\nCom exce\u00e7\u00e3o das primeira e \u00faltima linhas, todas as outras se adequam ao que queremos. Assim, temos 6 possibilidades em 8 poss\u00edveis: \n\n$Prob = \\frac{n(E)}{n(S)} = \\frac{6}{8}$.\n\nDe outra forma, podemos calcular a probabilidade utilizando algumas regrinhas de An\u00e1lise Combinat\u00f3ria (uma outra especificidade de probabilidades). Resumidamente, funciona assim para o problema acima: $P(1\u00ba).P(2\u00ba).P(3\u00ba).\\frac{n!}{K!C!}$. Temos a multiplica\u00e7\u00e3o das probabilidades individuais de cada lan\u00e7amento, multiplicado pela quantidade de lan\u00e7amentos (n) fatorial, dividido pela quantidade de caras (K) e coroas (C) fatorial. Um pouco confuso, n\u00e9? Mas \u00e9 bem simples, observe o desenvolvimetno abaixo:\n\n$P(K).P(K).P(C).\\frac{3!}{2!1!} + P(K).P(C).P(C).\\frac{3!}{2!1!} = \\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.3 + \\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.3 = \\frac{1}{8}.3 + \\frac{1}{8}.3 = \\frac{6}{8}$\n\nSe caso o problema fosse com 4 lan\u00e7amentos ao inv\u00e9s de 3, e quis\u00e9ssemos obter 3 Caras ou 2 Coroas, ter\u00edamos o seguinte:\n\n$P(K).P(K).P(K).P(C).\\frac{4!}{3!1!} + P(K).P(K).P(C).P(C).\\frac{4!}{2!2!} = \\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.4 + \\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.\\frac{1}{2}.6 = \\frac{1}{16}.4 + \\frac{1}{16}.6 = \\frac{5}{8}$\n\nAs c\u00e9lulas a seguir mostram um pequeno script que calcula de forma autom\u00e1tica a proabilidade para este tipo de problema a partir de alguns par\u00e2metros de entrada. Altere os par\u00e2mteros e veja como o resultado se comporta.\n\n\"\"\"\n## Calcula a probabilidade de cair K caras ou C coroas em n lan\u00e7amentos de moeda\n#OBS1: Para este problema, a quantidade de coroas e coroas devem ser menor ou igual do que o total de lan\u00e7amentos\ncalcula_probabilidade(moeda='justa',qtd_lancamentos=3,qtd_cara=2,qtd_coroa=2)\n\"\"\"\n### Exerc\u00edcio 1: Moeda \"Viciada\"\n\nVimos como funciona a probabilidade para uma moeda justa, tanto pela forma exaustiva (passando por todas as possibilidades) quanto pela forma matem\u00e1tica; contudo, testar todas as possibilidades \u00e9 impratic\u00e1vel para a maioria dos problemas, devido \u00e0 enorme quantidade de op\u00e7\u00f5es (caso aumentassemos os lan\u00e7amentos para 5, por exemplo, j\u00e1 ter\u00edamos 120 op\u00e7\u00f5es diferentes). Vale dizer tamb\u00e9m que, para moedas viciadas, o primeiro m\u00e9todo n\u00e3o funcionaria, visto que as probabilidades individuais seriam diferentes.\n\nVejamos um exemplo:\n\n    Uma moeda foi preparada para que Cara tenha probabilidade de 25% (P(K) = 0,25) e, consequentemente, Coroa de 75% (P(C) = 0,75). Para o mesmo problema anterior, onde, em 3 lan\u00e7amentos, queremos determinar a probabilidade de cair 2 caras ou 2 coroas, teremos o seguinte resultado:\n\"\"\"\ncalcula_probabilidade(moeda='viciada',qtd_lancamentos=3,qtd_cara=2,qtd_coroa=2,p_cara=0.25)\n\"\"\"\nPerceba que as probabilidades nos dois casos (justo e viciado) s\u00e3o diferentes, como era esperado. Abaixo mais alguns exemplos comparando os dois tipos de moeda.\n\"\"\"\ncalcula_probabilidade(moeda='justa',qtd_lancamentos=4,qtd_cara=3,qtd_coroa=2)\ncalcula_probabilidade(moeda='viciada',qtd_lancamentos=4,qtd_cara=3,qtd_coroa=2,p_cara=0.15)\nprint()\ncalcula_probabilidade(moeda='justa',qtd_lancamentos=5,qtd_cara=2,qtd_coroa=3)\ncalcula_probabilidade(moeda='viciada',qtd_lancamentos=5,qtd_cara=2,qtd_coroa=3,p_cara=0.15)\n\"\"\"\nExperimente alterar a probabilidade de Cara (p_cara) de uma moeda viciada para 0,5 e veja o que acontece.\n\"\"\"\ncalcula_probabilidade(moeda='justa',qtd_lancamentos=4,qtd_cara=3,qtd_coroa=2)\ncalcula_probabilidade(moeda='viciada',qtd_lancamentos=4,qtd_cara=3,qtd_coroa=2,p_cara=0.35)\n\"\"\"\n### Exerc\u00edcio 2: Moeda Justa\n\nAgora, vamos supor um caso hipot\u00e9tico no qual voc\u00ea lan\u00e7a 20 moedas, obtendo 8 Caras e 12 Coroas. Isso significa que a moeda utilizada \u00e9 viciada? \n\nObserve o teste abaixo:\n\"\"\"\ncontagem = gera_lancamentos(moeda='justa',qtd_lancamentos=20)\nmostra_probabilidades(contagem)\n\"\"\"\nNote que a as probabilidades s\u00e3o diferentes daquelas mostradas inicialmente de 50% e que, a cada execu\u00e7\u00e3o da c\u00e9lula o n\u00famero se altera. Mude a quantidade de lan\u00e7amentos e observe o resultado.\n\nMas por que isso acontece?\n\nVamos rodar novamente o c\u00f3digo, por\u00e9m agora aumentando (muito) a quantidade de lan\u00e7amentos:\n\"\"\"\ncontagem = gera_lancamentos(moeda='justa',qtd_lancamentos=2000)\nmostra_probabilidades(contagem)\n\"\"\"\nFaz mais sentido agora, n\u00e9? \u00c0 medida que aumentamos a quantidade de lan\u00e7amentos, mais pr\u00f3ximo da probabilidade individual ideal chegamos, isto \u00e9, se la\u00e7armos infinitas moedas, 50% delas ser\u00e3o Caras e 50% Coroas. \n\n### Exerc\u00edcio 2: Moeda \"Viciada\"\n\nE para uma moeda viciada, na qual a probabilidade de Cara \u00e9 25%, o que ser\u00e1 que acontece?\n\"\"\"\ncontagem = gera_lancamentos(moeda='viciada',qtd_lancamentos=20000,p_cara=0.25)\nmostra_probabilidades(contagem)\n\"\"\"\nAssim como visto para uma moeda justa, a probabilidade esperada foi alcan\u00e7ada.\n\"\"\"\n\"\"\"\n### Converg\u00eancia da probabilidade esperada\n\"\"\"\n\"\"\"\nBeleza, agora que j\u00e1 vimos que o aumento da quantidade de lan\u00e7amentos leva \u00e0 probabilidade esperada, fica o questionamento: quantas vezes eu preciso lan\u00e7ar a moeda para se aproximar desse valor? Ser\u00e1 que 100 j\u00e1 \u00e9 o suficientes? 10 mil, talvez? Abaixo, temos um exemplo com mil lan\u00e7amentos para uma moeda justa. \n\"\"\"\n\"\"\"\n![image.png](attachment:a19dcc4c-02d0-4473-bde2-7d88e3c0ea91.png)\n\"\"\"\n\"\"\"\n**O poder agora \u00e9 seu!** Clique em \"Copiar e editar\" (na por\u00e7\u00e3o superior direita da tela) e, em seguida, em *Run All*. Deslize at\u00e9 o final do notebook para conseguir interagir com os sliders abaixo (\u00e9 bem legal).\n\"\"\"\n# Deslize as op\u00e7\u00f5es abaixo e clique em \"Run interact para ver como o gr\u00e1fico se comporta\"\n_ = interact_manual(grafico_lancamentos, \n                    qtd_lancamentos =     widgets.IntSlider(min = 10, max = 20000, step = 50, value = 1000),\n                    p_cara =     widgets.IntSlider(min = 0, max = 100, step = 5, value = 50))\n\"\"\"\nBom, depois de uma pequena quantidade j\u00e1 \u00e9 poss\u00edvel notar que os valores parecem ficar mais est\u00e1veis, oscilando em torno da probabilidade esperada, n\u00e9? \n\"\"\"\n\"\"\"\n# Question\u00e1rio\n\nAgora que voc\u00ea j\u00e1 \u00e9 craque em probabilidades, bora responder algumas quest\u00f5es sobre o tema.\n\nClique [aqui](https:\/\/forms.office.com\/r\/Jt9LdCjVHM) para responder as quest\u00f5es que preparamos para treinar o que voc\u00ea aprendeu. Ao final, temos um [formul\u00e1rio de feedback](https:\/\/forms.office.com\/r\/8JVU2N576u) que gostar\u00edamos que respondesse tamb\u00e9m.\n\"\"\"\n\"\"\"\n### Muito obrigado por participar! :)\n\nA seguir, algumas op\u00e7\u00f5es de cursos gratuitos para voc\u00ea come\u00e7ar a estudar:\n\nPS: alguns deles s\u00e3o em ingl\u00eas, mas todos tem legendas para portug\u00eas\n\n**Python:**\n\n[Udemy - Introdu\u00e7\u00e3o a python](https:\/\/www.udemy.com\/course\/intro_python\/)\n\n[Udacity - Introdu\u00e7\u00e3o \u00e0 programa\u00e7\u00e3o em python](https:\/\/www.udacity.com\/course\/introduction-to-python--ud1110) \n\n[Coursera - Iniciando com python](https:\/\/www.coursera.org\/learn\/ciencia-computacao-python-conceitos)\n\n[Python.org - rela\u00e7\u00e3o de cursos para diversos n\u00edveis em python](https:\/\/python.org.br\/introducao\/)\n\n**Matem\u00e1tica:**\n\n[Rela\u00e7\u00e3o de \u00e1reas e cursos sobre matem\u00e1tica para Ci\u00eancia de Dados](https:\/\/www.agatetepe.com.br\/matematica-para-ciencia-de-dados\/)\n\n**Ci\u00eancia de dados:**\n\n[Udacity - Introdu\u00e7\u00e3o \u00e0 Ci\u00eancia de Dados](https:\/\/www.udacity.com\/course\/intro-to-data-science--ud359)\n\n[Coursera - Python para an\u00e1lise de dados](https:\/\/www.coursera.org\/learn\/python-data-analysis)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '192e5d47477f78'}"}
{"id":"38782","text":"\"\"\"\n Big transfer is a training model proposed by Google in 2019, which achieves the SOTA effect on multiple datasets[Big Transfer](https:\/\/paperswithcode.com\/paper\/large-scale-learning-of-general-visual#code)\n\n# I will show you how to use big transfer. Using big transfer, you can get **0.88 +** score after only **one epoch**\ud83d\ude1c\ud83d\ude1c\ud83d\ude1c\u3002\n\"\"\"\nimport os\nimport re\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport math\nimport tensorflow_hub as hub\nfrom matplotlib import pyplot as plt\n\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\n\n\nfrom kaggle_datasets import KaggleDatasets\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\ndef seed_everything(seed=0):\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed = 1024\nseed_everything(seed)\n\"\"\"\nLimited by the memory limit of kaggle GPU, only 8 batch_size can be used. If the local GPU is used, the speed will be faster\n\"\"\"\n# For tf.dataset\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\n\n# Configuration\nEPOCHS = 1\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [224, 224]\ndef append_path(pre):\n    return np.vectorize(lambda file: os.path.join(GCS_DS_PATH, pre, file))\nsub = pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/sample_submission.csv')\ntrain = pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/train.csv')\nsns.countplot(train['target'])\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '\/tfrecords\/test*.tfrec')\nvalid = True\nif valid:\n    TRAINING_FILENAMES, VALIDATION_FILENAMES = train_test_split(\n    tf.io.gfile.glob(GCS_PATH + '\/tfrecords\/train*.tfrec'),\n    test_size=0.1, random_state=5)\n\nCLASSES = [0,1]   \ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) \/ 255.0  # convert image to floats in [0, 1] range\n#     image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    image = tf.image.resize(image, IMAGE_SIZE)\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        #\"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n        \"target\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    #label = tf.cast(example['class'], tf.int32)\n    label = tf.cast(example['target'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALID_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\nprint('Dataset: {} training images,{} vaid images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES,NUM_VALID_IMAGES, NUM_TEST_IMAGES))\ndef build_lrfn(lr_start=0.00001, lr_max=0.0001, \n               lr_min=0.000001, lr_rampup_epochs=20, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) \/ lr_rampup_epochs * epoch + lr_start\n        elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_exp_decay**(epoch - lr_rampup_epochs - lr_sustain_epochs) + lr_min\n        return lr\n    \n    return lrfn\n\"\"\"\n# Google also offers several other [models](https:\/\/tfhub.dev\/s?module-type=image-augmentation,image-classification,image-feature-vector,image-generator,image-object-detection,image-others,image-style-transfer,image-rnn-agent&q=BiT)\n\nThere are two ways to load this model. One is to load the web page directly, and the other is to load the model uploaded by kaggle directly. I suggest the second method here\n\"\"\"\n\"\"\"\nchoice1\n\"\"\"\n\n# model_url = \"https:\/\/tfhub.dev\/google\/bit\/m-r50x1\/1\"\n# # module = hub.KerasLayer(\"https:\/\/tfhub.dev\/google\/bit\/m-r152x4\/1\")\n# # module = hub.KerasLayer(\"https:\/\/tfhub.dev\/google\/bit\/m-r101x1\/1\")\n# # module = hub.KerasLayer(\"https:\/\/tfhub.dev\/google\/bit\/m-r101x3\/1\")\n# module = hub.KerasLayer(model_url)\n\"\"\"\nchoice2\n\"\"\"\nMODELPATH = KaggleDatasets().get_gcs_path('big-transfer-models-without-top')\n# module = hub.KerasLayer(f'{MODELPATH}\/bit_m-r101x1_1\/')\n# module = hub.KerasLayer(f'{MODELPATH}\/bit_m-r101x3_1\/')\n# module = hub.KerasLayer(f'{MODELPATH}\/bit_m-r152x4_1\/')\n# module = hub.KerasLayer(f'{MODELPATH}\/bit_m-r50x1_1\/')\nmodule = hub.KerasLayer(f'{MODELPATH}\/bit_m-r50x3_1\/')\nlr = 0.003 * BATCH_SIZE \/ 512 \n\nlr_schedule = tf.keras.optimizers.schedules.PiecewiseConstantDecay(boundaries=[5,10,15], \n                                                                   values=[lr, lr*0.1, lr*0.001, lr*0.0001])\nwith strategy.scope():\n    inputs = tf.keras.layers.Input(shape=(IMAGE_SIZE[0],IMAGE_SIZE[1],3))\n    MODELPATH = KaggleDatasets().get_gcs_path('big-transfer-models-without-top')\n    module = hub.KerasLayer(f'{MODELPATH}\/bit_m-r152x4_1\/')\n    back_bone = module\n    back_bone.trainable = True\n    logits = back_bone(inputs)\n#     logits = tf.keras.layers.Dense(32, activation='relu', dtype='float32')(logits)\n    outputs = tf.keras.layers.Dense(1, activation='sigmoid', dtype='float32')(logits)\n    model = tf.keras.Model(inputs=inputs, outputs=outputs)\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(),\n        loss = tf.keras.losses.BinaryCrossentropy(label_smoothing = 0.01),\n        metrics=['binary_crossentropy',tf.keras.metrics.AUC()]\n    )\n    model.summary()\nlrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\nclass_weight = {0: 1, 1: 2}\nhistory = model.fit(\n    get_training_dataset(), \n    epochs=EPOCHS, \n    callbacks=[lr_schedule],\n    steps_per_epoch=STEPS_PER_EPOCH,\n    class_weight=class_weight,\n    validation_data=get_validation_dataset()\n)\ntest_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\npred_df = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities)})\npred_df.head()\nsub.head()\ndel sub['target']\nsub = sub.merge(pred_df, on='image_name')\n#sub.to_csv('submission_label_smoothing.csv', index=False)\nsub.to_csv('submission.csv', index=False)\nsub.head()","meta":"{'source': 'AI4Code', 'id': '4771f6281cae6a'}"}
{"id":"134595","text":"\"\"\"\n# Stock Market Prediction using CNN-LSTM model\nThis project is about analysis of Stock Market and providing predictions to the stockholders. For this, we used CNN-LSTM approach to create a blank model, then use it to train on stock market data. Further implementation is discussed below...\n\"\"\"\n# 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\n#for 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\n\"\"\"\n# Data Preprocessing and Analysis\n\"\"\"\nimport math\nimport seaborn as sns\nimport datetime as dt\nfrom datetime import datetime    \nsns.set_style(\"whitegrid\")\nfrom pandas.plotting import autocorrelation_plot\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use(\"ggplot\")\n\"\"\"\nBefore preprocessing data, a function to fetch real-time stock data (using Alpha Vantage API) is made\n\"\"\"\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nkey = user_secrets.get_secret(\"api\")\n\nimport requests\nimport csv\nfrom tqdm import tqdm\n\ndef request_stock_price_list(symbol, size, token):\n    q_string = 'https:\/\/www.alphavantage.co\/query?function=TIME_SERIES_DAILY&symbol={}&outputsize={}&apikey={}'\n    \n    print(\"Retrieving stock price data from Alpha Vantage (This may take a while)...\")\n    r = requests.get(q_string.format(symbol, size, token))\n    print(\"Data has been successfully downloaded...\")\n    date = []\n    colnames = list(range(0, 5))\n    df = pd.DataFrame(columns = colnames)\n    print(\"Sorting the retrieved data into a dataframe...\")\n    for i in tqdm(r.json()['Time Series (Daily)'].keys()):\n        date.append(i)\n        row = pd.DataFrame.from_dict(r.json()['Time Series (Daily)'][i], orient='index').reset_index().T[1:]\n        df = pd.concat([df, row], ignore_index=True)\n    df.columns = [\"open\", \"high\", \"low\", \"close\", \"volume\"]\n    df['date'] = date\n    return df\n# UNCOMMENT THE CELL IF DATA IS NEEDED TO BE LOADED FOR 1ST TIME\n\n#cv1 = request_stock_price_list('IBM', 'full', key)\n#print(cv1.head)\n#cv1.to_csv('data.csv')\n\"\"\"\nThen the datasets are loaded\n\"\"\"\n# For data preprocessing and analysis part\ndata = pd.read_csv('..\/input\/price-volume-data-for-all-us-stocks-etfs\/Stocks\/abe.us.txt')\n#data = pd.read_csv('..\/input\/nifty50-stock-market-data\/COALINDIA.csv')\n#data = pd.read_csv('..\/input\/stock-market-data\/stock_market_data\/nasdaq\/csv\/ABCO.csv')\n#data = pd.read_csv('.\/data.csv')\n# Any CSV or TXT file can be added here....\ndata.head()\ndata.info()\ndata.describe()\ndata.isnull().sum()\n\"\"\"\nFilling null columns with mean values....\n\"\"\"\ndata.reset_index(drop=True, inplace=True)\ndata.fillna(data.mean(), inplace=True)\ndata.head()\ndata.plot(legend=True,subplots=True, figsize = (12, 6))\nplt.show()\n#data['Close'].plot(legend=True, figsize = (12, 6))\n#plt.show()\n#data['Volume'].plot(legend=True,figsize=(12,7))\n#plt.show()\n\ndata.shape\ndata.size\ndata.describe(include='all').T\ndata.dtypes\ndata.nunique()\nma_day = [10,50,100]\n\nfor ma in ma_day:\n    column_name = \"MA for %s days\" %(str(ma))\n    data[column_name]=pd.DataFrame.rolling(data['Close'],ma).mean()\n\ndata['Daily Return'] = data['Close'].pct_change()\n# plot the daily return percentage\ndata['Daily Return'].plot(figsize=(12,5),legend=True,linestyle=':',marker='o')\nplt.show()\n\nsns.displot(data['Daily Return'].dropna(),bins=100,color='green')\nplt.show()\n\ndate=pd.DataFrame(data['Date'])\nclosing_df1 = pd.DataFrame(data['Close'])\nclose1  = closing_df1.rename(columns={\"Close\": \"data_close\"})\nclose2=pd.concat([date,close1],axis=1)\nclose2.head()\n\ndata.reset_index(drop=True, inplace=True)\ndata.fillna(data.mean(), inplace=True)\ndata.head()\n\ndata.nunique()\n\ndata.sort_index(axis=1,ascending=True)\n\ncols_plot = ['Open', 'High', 'Low','Close','Volume','MA for 10 days','MA for 50 days','MA for 100 days','Daily Return']\naxes = data[cols_plot].plot(marker='.', alpha=0.7, linestyle='None', figsize=(11, 9), subplots=True)\nfor ax in axes:\n    ax.set_ylabel('Daily trade')\n\nplt.plot(data['Close'], label=\"Close price\")\nplt.xlabel(\"Timestamp\")\nplt.ylabel(\"Closing price\")\ndf = data\nprint(df)\n\ndata.isnull().sum()\n\"\"\"\nAfter that, we'll visualize the data for understanding, this is shown below...\n\"\"\"\ncols_plot = ['Open', 'High', 'Low','Close']\naxes = data[cols_plot].plot(marker='.', alpha=0.5, linestyle='None', figsize=(11, 9), subplots=True)\nfor ax in axes:\n    ax.set_ylabel('Daily trade')\n\"\"\"\nThen we'd print the data after making changes and dropping null data\n\"\"\"\nplt.plot(data['Close'], label=\"Close price\")\nplt.xlabel(\"Timestamp\")\nplt.ylabel(\"Closing price\")\ndf = data\nprint(df)\n\ndf.describe().transpose()\n\"\"\"\nThe data has been analysed but it must be converted into data of shape [100,1] to make it easier for CNN to train on... Else it won't select necessary features and the model will fail\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX = []\nY = []\nwindow_size=100\nfor i in range(1 , len(df) - window_size -1 , 1):\n    first = df.iloc[i,2]\n    temp = []\n    temp2 = []\n    for j in range(window_size):\n        temp.append((df.iloc[i + j, 2] - first) \/ first)\n    temp2.append((df.iloc[i + window_size, 2] - first) \/ first)\n    X.append(np.array(temp).reshape(100, 1))\n    Y.append(np.array(temp2).reshape(1, 1))\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, shuffle=True)\n\ntrain_X = np.array(x_train)\ntest_X = np.array(x_test)\ntrain_Y = np.array(y_train)\ntest_Y = np.array(y_test)\n\ntrain_X = train_X.reshape(train_X.shape[0],1,100,1)\ntest_X = test_X.reshape(test_X.shape[0],1,100,1)\n\nprint(len(train_X))\nprint(len(test_X))\n\"\"\"\n# Training part\n\"\"\"\n\"\"\"\nThis part has 2 subparts: CNN and LSTM\n\nFor CNN, the layers are created with sizes 64,128,64 with kernel size = 3. In every layer, TimeDistributed function is added to track the features for every temporal slice of data with respect to time. In between, MaxPooling layers are added.\n\nAfter that, it's passed to Bi-LSTM layers\n\"\"\"\n# For creating model and training\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Conv1D, LSTM, Dense, Dropout, Bidirectional, TimeDistributed\nfrom tensorflow.keras.layers import MaxPooling1D, Flatten\nfrom tensorflow.keras.regularizers import L1, L2\nfrom tensorflow.keras.metrics import Accuracy\nfrom tensorflow.keras.metrics import RootMeanSquaredError\n\nmodel = tf.keras.Sequential()\n\n# Creating the Neural Network model here...\n# CNN layers\nmodel.add(TimeDistributed(Conv1D(64, kernel_size=3, activation='relu', input_shape=(None, 100, 1))))\nmodel.add(TimeDistributed(MaxPooling1D(2)))\nmodel.add(TimeDistributed(Conv1D(128, kernel_size=3, activation='relu')))\nmodel.add(TimeDistributed(MaxPooling1D(2)))\nmodel.add(TimeDistributed(Conv1D(64, kernel_size=3, activation='relu')))\nmodel.add(TimeDistributed(MaxPooling1D(2)))\nmodel.add(TimeDistributed(Flatten()))\n# model.add(Dense(5, kernel_regularizer=L2(0.01)))\n\n# LSTM layers\nmodel.add(Bidirectional(LSTM(100, return_sequences=True)))\nmodel.add(Dropout(0.5))\nmodel.add(Bidirectional(LSTM(100, return_sequences=False)))\nmodel.add(Dropout(0.5))\n\n#Final layers\nmodel.add(Dense(1, activation='linear'))\nmodel.compile(optimizer='adam', loss='mse', metrics=['mse', 'mae'])\n\nhistory = model.fit(train_X, train_Y, validation_data=(test_X,test_Y), epochs=40,batch_size=40, verbose=1, shuffle =True)\nplt.plot(history.history['loss'], label='train loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.xlabel(\"epoch\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.plot(history.history['mse'], label='train mse')\nplt.plot(history.history['val_mse'], label='val mse')\nplt.xlabel(\"epoch\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.plot(history.history['mae'], label='train mae')\nplt.plot(history.history['val_mae'], label='val mae')\nplt.xlabel(\"epoch\")\nplt.ylabel(\"Loss\")\nplt.legend()\n# After the model has been constructed, we'll summarise it\nfrom tensorflow.keras.utils import plot_model\nprint(model.summary())\nplot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)\nmodel.evaluate(test_X, test_Y)\nfrom sklearn.metrics import explained_variance_score, mean_poisson_deviance, mean_gamma_deviance\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import max_error\n\n# predict probabilities for test set\nyhat_probs = model.predict(test_X, verbose=0)\n# reduce to 1d array\nyhat_probs = yhat_probs[:, 0]\n\nvar = explained_variance_score(test_Y.reshape(-1,1), yhat_probs)\nprint('Variance: %f' % var)\n\nr2 = r2_score(test_Y.reshape(-1,1), yhat_probs)\nprint('R2 Score: %f' % var)\n\nvar2 = max_error(test_Y.reshape(-1,1), yhat_probs)\nprint('Max Error: %f' % var2)\npredicted  = model.predict(test_X)\ntest_label = test_Y.reshape(-1,1)\npredicted = np.array(predicted[:,0]).reshape(-1,1)\nlen_t = len(train_X)\nfor j in range(len_t , len_t + len(test_X)):\n    temp = data.iloc[j,3]\n    test_label[j - len_t] = test_label[j - len_t] * temp + temp\n    predicted[j - len_t] = predicted[j - len_t] * temp + temp\nplt.plot(predicted, color = 'green', label = 'Predicted  Stock Price')\nplt.plot(test_label, color = 'red', label = 'Real Stock Price')\nplt.title(' Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel(' Stock Price')\nplt.legend()\nplt.show()\n\"\"\"\n# Testing part\n\"\"\"\n\"\"\"\nIn this part, the model is saved and loaded back again. Then, it's made to train again but with different data to check it's loss and prediction\n\"\"\"\n# First we need to save a model\nmodel.save(\"model.h5\")\n# Load model\nnew_model = tf.keras.models.load_model(\".\/model.h5\")\nnew_model.summary()\n# For data preprocessing and analysis part\n#data2 = pd.read_csv('..\/input\/price-volume-data-for-all-us-stocks-etfs\/Stocks\/aaoi.us.txt')\n#data2 = pd.read_csv('..\/input\/nifty50-stock-market-data\/SBIN.csv')\n#data2 = pd.read_csv('..\/input\/stock-market-data\/stock_market_data\/nasdaq\/csv\/ACTG.csv')\ndata2 = pd.read_csv('.\/data.csv')\n# Any CSV or TXT file can be added here....\ndata2.dropna(inplace=True)\ndata2.head()\n\ndata2.reset_index(drop=True, inplace=True)\ndata2.fillna(data.mean(), inplace=True)\ndata2.head()\ndf2 = data2.drop('date', axis=1)\n\nprint(df2)\n\nX = []\nY = []\nwindow_size=100\nfor i in range(1 , len(df2) - window_size -1 , 1):\n    first = df2.iloc[i,4]\n    temp = []\n    temp2 = []\n    for j in range(window_size):\n        temp.append((df2.iloc[i + j, 4] - first) \/ first)\n    # for j in range(week):\n    temp2.append((df2.iloc[i + window_size, 4] - first) \/ first)\n    # X.append(np.array(stock.iloc[i:i+window_size,4]).reshape(50,1))\n    # Y.append(np.array(stock.iloc[i+window_size,4]).reshape(1,1))\n    # print(stock2.iloc[i:i+window_size,4])\n    X.append(np.array(temp).reshape(100, 1))\n    Y.append(np.array(temp2).reshape(1, 1))\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, shuffle=False)\n\ntrain_X = np.array(x_train)\ntest_X = np.array(x_test)\ntrain_Y = np.array(y_train)\ntest_Y = np.array(y_test)\n\ntrain_X = train_X.reshape(train_X.shape[0],1,100,1)\ntest_X = test_X.reshape(test_X.shape[0],1,100,1)\n\nprint(len(train_X))\nprint(len(test_X))\nmodel.evaluate(test_X, test_Y)\npredicted  = model.predict(test_X)\ntest_label = test_Y.reshape(-1,1)\npredicted = np.array(predicted[:,0]).reshape(-1,1)\nlen_t = len(train_X)\nfor j in range(len_t , len_t + len(test_X)):\n    temp = data2.iloc[j,3]\n    test_label[j - len_t] = test_label[j - len_t] * temp + temp\n    predicted[j - len_t] = predicted[j - len_t] * temp + temp\nplt.plot(predicted, color = 'green', label = 'Predicted  Stock Price')\nplt.plot(test_label, color = 'red', label = 'Real Stock Price')\nplt.title(' Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel(' Stock Price')\nplt.legend()\nplt.show()\n# Converting model from HDF5 format to TFJS format...\n!pip install tensorflowjs[wizard]\n# Need to be done on a CLI and not in notebook\n!tensorflowjs_converter --input_format=keras \/kaggle\/working\/model.h5 \/kaggle\/working\/model-tjs\n\"\"\"\n# EDA\n\"\"\"\n\"\"\"\nThis section is exploratory data analysis on the dataset collected. This is just for analysing the data...\n\"\"\"\ndataX = pd.read_csv('.\/data.csv')\ndataY = pd.read_csv('.\/data.csv')\ndataX.info()\ndataX.head()\nstart_date = '2020-01-01'\nend_date = '2021-11-29'\n\nstart = '2018-01-01'\nend = '2020-01-01'\n\nfill = (dataX['date']>=start_date) & (dataX['date']<=end_date)\ndataX = dataX.loc[fill]\ndataX\nfill2 = (dataY['date']>=start) & (dataY['date']<=end)\ndataY = dataY.loc[fill2]\ndataY\ndataX.describe()\ndataY.describe()\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom sklearn.model_selection import train_test_split,GridSearchCV,RandomizedSearchCV\nfrom sklearn.linear_model import LinearRegression,Ridge,Lasso\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor\nfrom sklearn.metrics import r2_score,mean_squared_error\n\nsns_plot = sns.distplot(dataX['close'])\nsns_plot2 = sns.distplot(dataY['close'])\nfig, ax = plt.subplots(4, 2, figsize = (15, 13))\nsns.boxplot(x= dataX[\"close\"], ax = ax[0,0])\nsns.distplot(dataX['close'], ax = ax[0,1])\nsns.boxplot(x= dataX[\"open\"], ax = ax[1,0])\nsns.distplot(dataX['open'], ax = ax[1,1])\nsns.boxplot(x= dataX[\"high\"], ax = ax[2,0])\nsns.distplot(dataX['high'], ax = ax[2,1])\nsns.boxplot(x= dataX[\"low\"], ax = ax[3,0])\nsns.distplot(dataX['low'], ax = ax[3,1])\nplt.tight_layout()\nfig, ax = plt.subplots(4, 2, figsize = (15, 13))\nsns.boxplot(x= dataY[\"close\"], ax = ax[0,0])\nsns.distplot(dataY['close'], ax = ax[0,1])\nsns.boxplot(x= dataY[\"open\"], ax = ax[1,0])\nsns.distplot(dataY['open'], ax = ax[1,1])\nsns.boxplot(x= dataY[\"high\"], ax = ax[2,0])\nsns.distplot(dataY['high'], ax = ax[2,1])\nsns.boxplot(x= dataY[\"low\"], ax = ax[3,0])\nsns.distplot(dataY['low'], ax = ax[3,1])\nplt.tight_layout()\nplt.figure(figsize=(10,6))\nsns.heatmap(dataX.corr(),cmap=plt.cm.Reds,annot=True)\nplt.title('Heatmap displaying the relationship between the features of the data (During COVID)',\n         fontsize=13)\nplt.show()\nplt.figure(figsize=(10,6))\nsns.heatmap(dataY.corr(),cmap=plt.cm.Blues,annot=True)\nplt.title('Heatmap displaying the relationship between the features of the data (Before COVID)',\n         fontsize=13)\nplt.show()\n# For other company....\n\n# UNCOMMENT IF NEEDED...\n#cv2 = request_stock_price_list('RELIANCE.BSE', 'full', key)\n#print(cv2.head)\n#cv2.to_csv('data2.csv')\n\ndataX = pd.read_csv('.\/data2.csv')\ndataY = pd.read_csv('.\/data2.csv')\ndataX.info()\nstart_date = '2020-01-01'\nend_date = '2021-11-29'\n\nstart = '2018-01-01'\nend = '2020-01-01'\n\nfill = (dataX['date']>=start_date) & (dataX['date']<=end_date)\ndataX = dataX.loc[fill]\ndataX\nfill2 = (dataY['date']>=start) & (dataY['date']<=end)\ndataY = dataY.loc[fill2]\ndataY\ndataX.describe()\ndataY.describe()\nsns_plot = sns.distplot(dataX['close'])\nsns_plot2 = sns.distplot(dataY['close'])\nfig, ax = plt.subplots(4, 2, figsize = (15, 13))\nsns.boxplot(x= dataX[\"close\"], ax = ax[0,0])\nsns.distplot(dataX['close'], ax = ax[0,1])\nsns.boxplot(x= dataX[\"open\"], ax = ax[1,0])\nsns.distplot(dataX['open'], ax = ax[1,1])\nsns.boxplot(x= dataX[\"high\"], ax = ax[2,0])\nsns.distplot(dataX['high'], ax = ax[2,1])\nsns.boxplot(x= dataX[\"low\"], ax = ax[3,0])\nsns.distplot(dataX['low'], ax = ax[3,1])\nplt.tight_layout()\nfig, ax = plt.subplots(4, 2, figsize = (15, 13))\nsns.boxplot(x= dataY[\"close\"], ax = ax[0,0])\nsns.distplot(dataY['close'], ax = ax[0,1])\nsns.boxplot(x= dataY[\"open\"], ax = ax[1,0])\nsns.distplot(dataY['open'], ax = ax[1,1])\nsns.boxplot(x= dataY[\"high\"], ax = ax[2,0])\nsns.distplot(dataY['high'], ax = ax[2,1])\nsns.boxplot(x= dataY[\"low\"], ax = ax[3,0])\nsns.distplot(dataY['low'], ax = ax[3,1])\nplt.tight_layout()\nplt.figure(figsize=(10,6))\nsns.heatmap(dataX.corr(),cmap=plt.cm.Reds,annot=True)\nplt.title('Heatmap displaying the relationship between the features of the data (During COVID)',\n         fontsize=13)\nplt.show()\nplt.figure(figsize=(10,6))\nsns.heatmap(dataY.corr(),cmap=plt.cm.Blues,annot=True)\nplt.title('Heatmap displaying the relationship between the features of the data (Before COVID)',\n         fontsize=13)\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'f7773d5910964b'}"}
{"id":"38962","text":"# 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\n! unzip \"\/kaggle\/input\/quora-question-pairs\/train.csv.zip\"\n! unzip \"\/kaggle\/input\/quora-question-pairs\/test.csv.zip\"\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom subprocess import check_output\n%matplotlib inline\n\n! pip install plotly\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\nimport os\nimport gc\n\nimport re\nfrom nltk.corpus import stopwords\n\n!pip3 install distance\nimport distance\nfrom nltk.stem import PorterStemmer\n! pip3 install bs4\nfrom bs4 import BeautifulSoup\n\"\"\"\n# 3.1 Reading and Basic EDA\n\"\"\"\ndf=pd.read_csv(\"train.csv\")\nprint(\"number of data points\",df.shape[0])\ndf.head()\ndf.info()\n\"\"\"\n# 3.2 Distribution of data points among output classes\n\"\"\"\ndf.groupby('is_duplicate')['id'].count().plot.bar()\nprint(\"total number of question pairs for training {}\".format(len(df)))\nprint(\"question pairs are not similar {}\".format(100-round(df['is_duplicate']).mean()*100,2))\nprint(\"question pairs are similar {}\".format(round(df['is_duplicate']).mean()*100))\n\"\"\"\n# 3.2.1  Number of unique questions\n\"\"\"\nqids=pd.Series(df['qid1'].tolist() + df['qid2'].tolist())\nunique_qs = len(np.unique(qids))\nqs_morethan_onetime = np.sum(qids.value_counts()>1)\n\nprint ('Total number of  Unique Questions are: {}\\n'.format(unique_qs))\n\nprint ('Number of unique questions that appear more than one time: {} ({}%)\\n'.format(qs_morethan_onetime,qs_morethan_onetime\/unique_qs*100))\n\nprint ('Max number of times a single question is repeated: {}\\n'.format(max(qids.value_counts()))) \n\nq_vals=qids.value_counts()\n\nq_vals=q_vals.values\nx=[\"unique question\",\"repeated_questions\"]\ny=[unique_qs,qs_morethan_onetime]\n\nplt.figure(figsize=(10,6))\nsns.barplot(x,y)\nplt.show()\n\"\"\"\n# check for duplicate\n\"\"\"\npair_duplicate=df[['qid1','qid2','is_duplicate']].groupby(['qid1','qid2']).count().reset_index()\nprint(\"no of duplicate questions\",(pair_duplicate).shape[0]-df.shape[0])\n\"\"\"\n# No of occurance of each questions\n\"\"\"\nplt.figure(figsize=(10, 6))\n\nplt.hist(qids.value_counts(), bins=160)\n\nplt.yscale('log', nonposy='clip')\n\nplt.title('Log-Histogram of question appearance counts')\n\nplt.xlabel('Number of occurences of question')\n\nplt.ylabel('Number of questions')\n\nprint ('Maximum number of times a single question is repeated: {}\\n'.format(max(qids.value_counts()))) \n\"\"\"\n# Checking for null values\n\"\"\"\nnan_rows=df[df.isnull().any(1)]\nprint(nan_rows)\ndf=df.fillna(\"\")\nnan_rows=df[df.isnull().any(1)]\nprint(nan_rows)\n\"\"\"\n# Basic Feature Extraction\n\"\"\"\n\"\"\"\n\n    freq_qid1 = Frequency of qid1's\n    freq_qid2 = Frequency of qid2's\n    q1len = Length of q1\n    q2len = Length of q2\n    q1_n_words = Number of words in Question 1\n    q2_n_words = Number of words in Question 2\n    word_Common = (Number of common unique words in Question 1 and Question 2)\n    word_Total =(Total num of words in Question 1 + Total num of words in Question 2)\n    word_share = (word_common)\/(word_Total)\n    freq_q1+freq_q2 = sum total of frequency of qid1 and qid2\n    freq_q1-freq_q2 = absolute difference of frequency of qid1 and qid2\n\n\"\"\"\nif os.path.isfile(\".\/df_fe_without_preprocessing_train.csv\"):\n    df=pd.read_csv(\".\/df_fe_without_preprocessing_train.csv\")\n    df.head()\nelse:\n    df['freq_qid1']=df.groupby('qid1')['qid1'].transform('count')\n    df['freq_qid2']=df.groupby('qid2')['qid2'].transform('count')\n    df['q1len']=df['question1'].str.len()\n    df['q2len']=df['question2'].str.len()\n    df['q1_n_words'] = df['question1'].apply(lambda row: len(row.split(\" \")))\n    df['q2_n_words'] = df['question2'].apply(lambda row: len(row.split(\" \")))\n    \n    def normalised_word_common(row):\n        w1=set(map(lambda word: word.lower().strip(),row['question1'].split(\" \")))\n        w2=set(map(lambda word: word.lower().strip(),row['question2'].split(\" \")))\n        return 1.0*len(w1 & w2)\n    df['word_common']=df.apply(normalised_word_common,axis=1)\n    \n    def normalized_word_Total(row):\n        w1 = set(map(lambda word: word.lower().strip(), row['question1'].split(\" \")))\n        w2 = set(map(lambda word: word.lower().strip(), row['question2'].split(\" \")))    \n        return 1.0 * (len(w1) + len(w2))\n    df['word_Total'] = df.apply(normalized_word_Total, axis=1)\n    \n    def normalized_word_share(row):\n        w1 = set(map(lambda word: word.lower().strip(), row['question1'].split(\" \")))\n        w2 = set(map(lambda word: word.lower().strip(), row['question2'].split(\" \")))    \n        return 1.0 * len(w1 & w2)\/(len(w1) + len(w2))\n    df['word_share'] = df.apply(normalized_word_share, axis=1)\n    \n    df['freq_q1+q2'] = df['freq_qid1']+df['freq_qid2']\n    df['freq_q1-q2'] = abs(df['freq_qid1']-df['freq_qid2'])\n\n    df.to_csv(\"df_fe_without_preprocessing_train.csv\", index=False)\n    \ndf.head()\n    \n    \n    \n\"\"\"\n**Analysis of extraxted feature **\n\"\"\"\nprint (\"Minimum length of the questions in question1 : \" , min(df['q1_n_words']))\n\nprint (\"Minimum length of the questions in question2 : \" , min(df['q2_n_words']))\n\nprint (\"Number of Questions with minimum length [question1] :\", df[df['q1_n_words']== 1].shape[0])\nprint (\"Number of Questions with minimum length [question2] :\", df[df['q2_n_words']== 1].shape[0])\n\"\"\"\n# Word share\n\"\"\"\nplt.figure(figsize=(12,8))\n\nplt.subplot(1,2,1)\nsns.violinplot(x='is_duplicate',y='word_share',data=df[0:])\n\nplt.subplot(1,2,2)\nsns.distplot(df[df['is_duplicate'] == 1.0]['word_share'][0:] , label = \"1\", color = 'red')\nsns.distplot(df[df['is_duplicate'] == 0.0]['word_share'][0:] , label = \"0\" , color = 'blue' )\n\nplt.show()\n\"\"\"\n\n    The distributions for normalized word_share have some overlap on the far right-hand side, i.e., there are quite a lot of questions with high word similarity\n    The average word share and Common no. of words of qid1 and qid2 is more when they are duplicate(Similar)\n\n\n\"\"\"\n\"\"\"\nFeature: word_Common \n\"\"\"\nplt.figure(figsize=(12, 8))\n\nplt.subplot(1,2,1)\nsns.violinplot(x = 'is_duplicate', y = 'word_common', data = df[0:])\n\nplt.subplot(1,2,2)\nsns.distplot(df[df['is_duplicate'] == 1.0]['word_common'][0:] , label = \"1\", color = 'red')\nsns.distplot(df[df['is_duplicate'] == 0.0]['word_common'][0:] , label = \"0\" , color = 'blue' )\nplt.show()\n\"\"\"\nThe distributions of the word_Common feature in similar and non-similar questions are highly overlapping \n\"\"\"\n\"\"\"\n# EDA :Advanced Feature extraction\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport re\nfrom fuzzywuzzy import fuzz\nfrom sklearn.manifold import TSNE\n\nfrom wordcloud import WordCloud,STOPWORDS\nfrom PIL import Image\ndf.head(2)\n\"\"\"\n# Preprocessing of Text\n\"\"\"\n\"\"\"\nPreprocessing:\n\n    Removing html tags\n    Removing Punctuations\n    Performing stemming\n    Removing Stopwords\n    Expanding contractions etc.\n\n\"\"\"\nSAFE_DIV=0.0001\n\nSTOP_WORDS=stopwords.words('english')\n\ndef preprocess(x):\n    x=str(x).lower()\n    x=x.replace(\",000,000\", \"m\").replace(\",000\", \"k\").replace(\"\u2032\", \"'\").replace(\"\u2019\", \"'\")\\\n                           .replace(\"won't\", \"will not\").replace(\"cannot\", \"can not\").replace(\"can't\", \"can not\")\\\n                           .replace(\"n't\", \" not\").replace(\"what's\", \"what is\").replace(\"it's\", \"it is\")\\\n                           .replace(\"'ve\", \" have\").replace(\"i'm\", \"i am\").replace(\"'re\", \" are\")\\\n                           .replace(\"he's\", \"he is\").replace(\"she's\", \"she is\").replace(\"'s\", \" own\")\\\n                           .replace(\"%\", \" percent \").replace(\"\u20b9\", \" rupee \").replace(\"$\", \" dollar \")\\\n                           .replace(\"\u20ac\", \" euro \").replace(\"'ll\", \" will\")\n    \n    x = re.sub(r\"([0-9]+)000000\", r\"lm\", x)\n    x = re.sub(r\"([0-9]+)000\", r\"lk\", x)\n    \n    \n    porter=PorterStemmer()\n    pattern=re.compile('\\W')\n    \n    if type(x) == type(''):\n        x = re.sub(pattern, ' ', x)\n    \n    \n    if type(x) == type(''):\n        x = porter.stem(x)\n        example1 = BeautifulSoup(x)\n        x = example1.get_text()\n               \n    return x\n    \n    \n\"\"\"\nDefinition:\n\n    Token: You get a token by splitting sentence a space\n    Stop_Word : stop words as per NLTK.\n    Word : A token that is not a stop_word\n\nFeatures:\n\n    cwc_min : Ratio of common_word_count to min lenghth of word count of Q1 and Q2\n    cwc_min = common_word_count \/ (min(len(q1_words), len(q2_words))\n\n\n    cwc_max : Ratio of common_word_count to max lenghth of word count of Q1 and Q2\n    cwc_max = common_word_count \/ (max(len(q1_words), len(q2_words))\n\n\n    csc_min : Ratio of common_stop_count to min lenghth of stop count of Q1 and Q2\n    csc_min = common_stop_count \/ (min(len(q1_stops), len(q2_stops))\n\n\n    csc_max : Ratio of common_stop_count to max lenghth of stop count of Q1 and Q2\n    csc_max = common_stop_count \/ (max(len(q1_stops), len(q2_stops))\n\n\n    ctc_min : Ratio of common_token_count to min lenghth of token count of Q1 and Q2\n    ctc_min = common_token_count \/ (min(len(q1_tokens), len(q2_tokens))\n\n\n    ctc_max : Ratio of common_token_count to max lenghth of token count of Q1 and Q2\n    ctc_max = common_token_count \/ (max(len(q1_tokens), len(q2_tokens))\n\n\n    last_word_eq : Check if First word of both questions is equal or not\n    last_word_eq = int(q1_tokens[-1] == q2_tokens[-1])\n\n\n    first_word_eq : Check if First word of both questions is equal or not\n    first_word_eq = int(q1_tokens[0] == q2_tokens[0])\n\n\n    abs_len_diff : Abs. length difference\n    abs_len_diff = abs(len(q1_tokens) - len(q2_tokens))\n\n\n    mean_len : Average Token Length of both Questions\n    mean_len = (len(q1_tokens) + len(q2_tokens))\/2\n\n\n    fuzz_ratio : https:\/\/github.com\/seatgeek\/fuzzywuzzy#usage http:\/\/chairnerd.seatgeek.com\/fuzzywuzzy-fuzzy-string-matching-in-python\/\n\n\n    fuzz_partial_ratio : https:\/\/github.com\/seatgeek\/fuzzywuzzy#usage http:\/\/chairnerd.seatgeek.com\/fuzzywuzzy-fuzzy-string-matching-in-python\/\n\n\n    token_sort_ratio : https:\/\/github.com\/seatgeek\/fuzzywuzzy#usage http:\/\/chairnerd.seatgeek.com\/fuzzywuzzy-fuzzy-string-matching-in-python\/\n\n    token_set_ratio : https:\/\/github.com\/seatgeek\/fuzzywuzzy#usage http:\/\/chairnerd.seatgeek.com\/fuzzywuzzy-fuzzy-string-matching-in-python\/\n\n    longest_substr_ratio : Ratio of length longest common substring to min lenghth of token count of Q1 and Q2\n    longest_substr_ratio = len(longest common substring) \/ (min(len(q1_tokens), len(q2_tokens))\n\n\n\"\"\"\ndef get_token_features(q1,q2):\n    token_features=[0.0]*10\n    \n    \n    q1_tokens=q1.split()\n    q2_tokens=q2.split()\n    \n    if len(q1_tokens)==0 or len(q2_tokens)==0:\n        return token_features\n    \n    q1_words=set([word for word in q1_tokens if word not in STOP_WORDS])\n    q2_words=set([word for word in q2_tokens if word not in STOP_WORDS])\n    \n    q1_stops=set([word for word in q1_tokens if word in STOP_WORDS])\n    q2_stops=set([word for word in q2_tokens if word in STOP_WORDS])\n    \n    common_word_count=len(q1_words.intersection(q2_words))\n    \n    common_stop_count=len(q1_stops.intersection(q2_stops))\n    \n    common_token_count=len(set(q1_tokens).intersection(set(q2_tokens)))\n    \n    \n    token_features[0]=common_word_count\/(min(len(q1_words),len(q2_words))+SAFE_DIV)\n    token_features[1]=common_word_count\/(max(len(q1_words),len(q2_words))+SAFE_DIV)\n    token_features[2]=common_stop_count\/(min(len(q1_words),len(q2_words))+SAFE_DIV)\n    token_features[3]=common_stop_count\/(max(len(q1_words),len(q2_words))+SAFE_DIV)\n    token_features[4]=common_token_count\/(min(len(q1_words),len(q2_words))+SAFE_DIV)\n    token_features[5]=common_token_count\/(max(len(q1_words),len(q2_words))+SAFE_DIV)\n    \n    \n    token_features[6]=int(q1_tokens[-1]==q2_tokens[-1])\n    token_features[7]=int(q1_tokens[0]==q2_tokens[0])\n    \n    \n    token_features[9]=(len(q1_tokens)+len(q2_tokens))\/2\n    \n    return token_features\n\n\n\ndef get_longest_substr_ratio(a, b):\n    strs = list(distance.lcsubstrings(a, b))\n    if len(strs) == 0:\n        return 0\n    else:\n        return len(strs[0]) \/ (min(len(a), len(b)) + 1)\n    \n    \ndef extract_features(df):\n    df[\"question1\"] = df[\"question1\"].fillna(\"\").apply(preprocess)\n    df[\"question2\"] = df[\"question2\"].fillna(\"\").apply(preprocess)\n    \n    token_features=df.apply(lambda x:get_token_features(x['question1'],x['question2']),axis=1)\n    \n    df[\"cwc_min\"]       = list(map(lambda x:x[0],token_features))\n    df[\"cwc_max\"]       = list(map(lambda x: x[1], token_features))\n    df[\"csc_min\"]       = list(map(lambda x: x[2], token_features))\n    df[\"csc_max\"]       = list(map(lambda x: x[3], token_features))\n    df[\"ctc_min\"]       = list(map(lambda x: x[4], token_features))\n    df[\"ctc_max\"]       = list(map(lambda x: x[5], token_features))\n    df[\"last_word_eq\"]  = list(map(lambda x: x[6], token_features))\n    df[\"first_word_eq\"] = list(map(lambda x: x[7], token_features))\n    df[\"abs_len_diff\"]  = list(map(lambda x: x[8], token_features))\n    df[\"mean_len\"]      = list(map(lambda x: x[9], token_features))\n    \n    df[\"token_set_ratio\"]       = df.apply(lambda x: fuzz.token_set_ratio(x[\"question1\"], x[\"question2\"]), axis=1)\n    # The token sort approach involves tokenizing the string in question, sorting the tokens alphabetically, and \n    # then joining them back into a string We then compare the transformed strings with a simple ratio().\n    df[\"token_sort_ratio\"]      = df.apply(lambda x: fuzz.token_sort_ratio(x[\"question1\"], x[\"question2\"]), axis=1)\n    df[\"fuzz_ratio\"]            = df.apply(lambda x: fuzz.QRatio(x[\"question1\"], x[\"question2\"]), axis=1)\n    df[\"fuzz_partial_ratio\"]    = df.apply(lambda x: fuzz.partial_ratio(x[\"question1\"], x[\"question2\"]), axis=1)\n    df[\"longest_substr_ratio\"]  = df.apply(lambda x: get_longest_substr_ratio(x[\"question1\"], x[\"question2\"]), axis=1)\n    return df\n    \n\n\n    \n    \n    \n    \n\nif os.path.isfile(\".\/nlp_features_train.csv\"):\n    df=pd.read_csv(\".\/nlp_features_train.csv\",encoding='latin-1')\n    df.fillna(\"\")\nelse:\n    print(\"Extracting features for train:\")\n    df = pd.read_csv(\".\/train.csv\")\n    df = extract_features(df)\n    df.to_csv(\"nlp_features_train.csv\", index=False)\ndf.head(2)\n    \n\"\"\"\n# Analysis of extracteed features\n\"\"\"\ndf_duplicate=df[df['is_duplicate']==1]\ndfp_nonduplicate=df[df['is_duplicate']==0]\n\n# Converting 2d array of q1 and q2 and flatten the array: like {{1,2},{3,4}} to {1,2,3,4}\np = np.dstack([df_duplicate[\"question1\"], df_duplicate[\"question2\"]]).flatten()\nn = np.dstack([dfp_nonduplicate[\"question1\"], dfp_nonduplicate[\"question2\"]]).flatten()\n\nprint (\"Number of data points in class 1 (duplicate pairs) :\",len(p))\nprint (\"Number of data points in class 0 (non duplicate pairs) :\",len(n))\n\n#Saving the np array into a text file\nnp.savetxt('train_p.txt', p, delimiter=' ', fmt='%s')\nnp.savetxt('train_n.txt', n, delimiter=' ', fmt='%s')\nfrom os import path\n\nd = path.dirname('.\/')\n\ntextp_w = open(path.join(d, 'train_p.txt')).read()\ntextn_w = open(path.join(d, 'train_n.txt')).read()\nstopwords = set(STOPWORDS)\nstopwords.add(\"said\")\nstopwords.add(\"br\")\nstopwords.add(\" \")\nstopwords.remove(\"not\")\n\nstopwords.remove(\"no\")\n#stopwords.remove(\"good\")\n#stopwords.remove(\"love\")\nstopwords.remove(\"like\")\n#stopwords.remove(\"best\")\n#stopwords.remove(\"!\")\nprint (\"Total number of words in duplicate pair questions :\",len(textp_w))\nprint (\"Total number of words in non duplicate pair questions :\",len(textn_w))\nwc = WordCloud(background_color=\"white\", max_words=len(textp_w), stopwords=stopwords)\nwc.generate(textp_w)\nprint (\"Word Cloud for Duplicate Question pairs\")\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\nwc = WordCloud(background_color=\"white\", max_words=len(textn_w),stopwords=stopwords)\n# generate word cloud\nwc.generate(textn_w)\nprint (\"Word Cloud for non-Duplicate Question pairs:\")\nplt.imshow(wc, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\nn = df.shape[0]\nsns.pairplot(df[['ctc_min', 'cwc_min', 'csc_min', 'token_sort_ratio', 'is_duplicate']][0:n], hue='is_duplicate', vars=['ctc_min', 'cwc_min', 'csc_min', 'token_sort_ratio'])\nplt.show()\n# Distribution of the token_sort_ratio\nplt.figure(figsize=(10, 8))\n\nplt.subplot(1,2,1)\nsns.violinplot(x = 'is_duplicate', y = 'token_sort_ratio', data = df[0:] , )\n\nplt.subplot(1,2,2)\nsns.distplot(df[df['is_duplicate'] == 1.0]['token_sort_ratio'][0:] , label = \"1\", color = 'red')\nsns.distplot(df[df['is_duplicate'] == 0.0]['token_sort_ratio'][0:] , label = \"0\" , color = 'blue' )\nplt.show()\nplt.figure(figsize=(10, 8))\n\nplt.subplot(1,2,1)\nsns.violinplot(x = 'is_duplicate', y = 'fuzz_ratio', data = df[0:] , )\n\nplt.subplot(1,2,2)\nsns.distplot(df[df['is_duplicate'] == 1.0]['fuzz_ratio'][0:] , label = \"1\", color = 'red')\nsns.distplot(df[df['is_duplicate'] == 0.0]['fuzz_ratio'][0:] , label = \"0\" , color = 'blue' )\nplt.show()\n\"\"\"\n# Visualization\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\ndfp_subsampled=df[0:5000]\nX = MinMaxScaler().fit_transform(dfp_subsampled[['cwc_min', 'cwc_max', 'csc_min', 'csc_max' , 'ctc_min' , 'ctc_max' , 'last_word_eq', 'first_word_eq' , 'abs_len_diff' , 'mean_len' , 'token_set_ratio' , 'token_sort_ratio' ,  'fuzz_ratio' , 'fuzz_partial_ratio' , 'longest_substr_ratio']])\ny = dfp_subsampled['is_duplicate'].values\ntsne2d = TSNE(\n    n_components=2,\n    init='random', # pca\n    random_state=101,\n    method='barnes_hut',\n    n_iter=1000,\n    verbose=2,\n    angle=0.5\n).fit_transform(X)\ndf = pd.DataFrame({'x':tsne2d[:,0], 'y':tsne2d[:,1] ,'label':y})\n\n# draw the plot in appropriate place in the grid\nsns.lmplot(data=df, x='x', y='y', hue='label', fit_reg=False, size=8,palette=\"Set1\",markers=['s','o'])\nplt.title(\"perplexity : {} and max_iter : {}\".format(30, 1000))\nplt.show()\nfrom sklearn.manifold import TSNE\ntsne3d = TSNE(\n    n_components=3,\n    init='random', # pca\n    random_state=101,\n    method='barnes_hut',\n    n_iter=1000,\n    verbose=2,\n    angle=0.5\n).fit_transform(X)\ntrace1 = go.Scatter3d(\n    x=tsne3d[:,0],\n    y=tsne3d[:,1],\n    z=tsne3d[:,2],\n    mode='markers',\n    marker=dict(\n        sizemode='diameter',\n        color = y,\n        colorscale = 'Portland',\n        colorbar = dict(title = 'duplicate'),\n        line=dict(color='rgb(255, 255, 255)'),\n        opacity=0.75\n    )\n)\n\ndata=[trace1]\nlayout=dict(height=800, width=800, title='3d embedding with engineered features')\nfig=dict(data=data, layout=layout)\npy.iplot(fig, filename='3DBubble')\n\"\"\"\n# Featurizing text data with tfidf weighted word-vectors \n\"\"\"\nfrom sklearn.preprocessing import normalize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport sys\nfrom tqdm import tqdm\n\nimport spacy\n\ndf = pd.read_csv(\"train.csv\")\n \n# encode questions to unicode\n# https:\/\/stackoverflow.com\/a\/6812069\n# ----------------- python 2 ---------------------\n# df['question1'] = df['question1'].apply(lambda x: unicode(str(x),\"utf-8\"))\n# df['question2'] = df['question2'].apply(lambda x: unicode(str(x),\"utf-8\"))\n# ----------------- python 3 ---------------------\ndf['question1'] = df['question1'].apply(lambda x: str(x))\ndf['question2'] = df['question2'].apply(lambda x: str(x))\ndf.head()\nquestion=list(df['question1'])+list(df['question2'])\n\ntfidf=TfidfVectorizer(lowercase=False)\ntfidf.fit_transform(question)\n\n\nword2tfidf = dict(zip(tfidf.get_feature_names(), tfidf.idf_))\n# en_vectors_web_lg, which includes over 1 million unique vectors.\nnlp = spacy.load('en_core_web_sm')\n\nvecs1 = []\n# https:\/\/github.com\/noamraph\/tqdm\n# tqdm is used to print the progress bar\nfor qu1 in tqdm(list(df['question1'])):\n    doc1 = nlp(qu1) \n    # 384 is the number of dimensions of vectors \n    mean_vec1 = np.zeros([len(doc1), len(doc1[0].vector)])\n    for word1 in doc1:\n        # word2vec\n        vec1 = word1.vector\n        # fetch df score\n        try:\n            idf = word2tfidf[str(word1)]\n        except:\n            idf = 0\n        # compute final vec\n        mean_vec1 += vec1 * idf\n    mean_vec1 = mean_vec1.mean(axis=0)\n    vecs1.append(mean_vec1)\ndf['q1_feats_m'] = list(vecs1)\nvecs2 = []\nfor qu2 in tqdm(list(df['question2'])):\n    doc2 = nlp(qu2) \n    mean_vec2 = np.zeros([len(doc1), len(doc2[0].vector)])\n    for word2 in doc2:\n        # word2vec\n        vec2 = word2.vector\n        # fetch df score\n        try:\n            idf = word2tfidf[str(word2)]\n        except:\n            #print word\n            idf = 0\n        # compute final vec\n        mean_vec2 += vec2 * idf\n    mean_vec2 = mean_vec2.mean(axis=0)\n    vecs2.append(mean_vec2)\ndf['q2_feats_m'] = list(vecs2)\nif os.path.isfile('nlp_features_train.csv'):\n    dfnlp = pd.read_csv(\"nlp_features_train.csv\")\nelse:\n    print(\"download nlp_features_train.csv from drive or run previous notebook\")\n\nif os.path.isfile('df_fe_without_preprocessing_train.csv'):\n    dfppro = pd.read_csv(\"df_fe_without_preprocessing_train.csv\",encoding='latin-1')\nelse:\n    print(\"download df_fe_without_preprocessing_train.csv from drive or run previous notebook\")\ndf1 = dfnlp.drop(['qid1','qid2','question1','question2'],axis=1)\ndf2 = dfppro.drop(['qid1','qid2','question1','question2','is_duplicate'],axis=1)\ndf3 = df.drop(['qid1','qid2','question1','question2','is_duplicate'],axis=1)\ndf3_q1 = pd.DataFrame(df3.q1_feats_m.values.tolist(), index= df3.index)\ndf3_q2 = pd.DataFrame(df3.q2_feats_m.values.tolist(), index= df3.index)\n# dataframe of nlp features\ndf1.head()\n# data before preprocessing \ndf2.head()\n# Questions 1 tfidf weighted word2vec\ndf3_q1.head()\n# Questions 2 tfidf weighted word2vec\ndf3_q2.head()\nprint(\"Number of features in nlp dataframe :\", df1.shape[1])\nprint(\"Number of features in preprocessed dataframe :\", df2.shape[1])\nprint(\"Number of features in question1 w2v  dataframe :\", df3_q1.shape[1])\nprint(\"Number of features in question2 w2v  dataframe :\", df3_q2.shape[1])\nprint(\"Number of features in final dataframe  :\", df1.shape[1]+df2.shape[1]+df3_q1.shape[1]+df3_q2.shape[1])\n# storing the final features to csv file\nif not os.path.isfile('final_features.csv'):\n    df3_q1['id']=df1['id']\n    df3_q2['id']=df1['id']\n    df1  = df1.merge(df2, on='id',how='left')\n    df2  = df3_q1.merge(df3_q2, on='id',how='left')\n    result  = df1.merge(df2, on='id',how='left')\n    result.to_csv('final_features.csv')\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics.classification import accuracy_score, log_loss\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom collections import Counter\nfrom scipy.sparse import hstack\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold \nfrom collections import Counter, defaultdict\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nimport math\nfrom sklearn.metrics import normalized_mutual_info_score\nfrom sklearn.ensemble import RandomForestClassifier\n\nimport sqlite3\nfrom sqlalchemy import create_engine # database connection\nimport datetime as dt\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import SGDClassifier\nfrom mlxtend.classifier import StackingClassifier\n\n\n\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_curve, auc, roc_curve\n#Creating db file from csv\n\"\"\"\nif not os.path.isfile('.\/train.db'):\n    disk_engine = create_engine('sqlite:\/\/\/train.db')\n    start = dt.datetime.now()\n    chunksize = 180000\n    j = 0\n    index_start = 1\n    for df in pd.read_csv('.\/final_features.csv', names=['Unnamed: 0','id','is_duplicate','cwc_min','cwc_max','csc_min','csc_max','ctc_min','ctc_max','last_word_eq','first_word_eq','abs_len_diff','mean_len','token_set_ratio','token_sort_ratio','fuzz_ratio','fuzz_partial_ratio','longest_substr_ratio','freq_qid1','freq_qid2','q1len','q2len','q1_n_words','q2_n_words','word_Common','word_Total','word_share','freq_q1+q2','freq_q1-q2','0_x','1_x','2_x','3_x','4_x','5_x','6_x','7_x','8_x','9_x','10_x','11_x','12_x','13_x','14_x','15_x','16_x','17_x','18_x','19_x','20_x','21_x','22_x','23_x','24_x','25_x','26_x','27_x','28_x','29_x','30_x','31_x','32_x','33_x','34_x','35_x','36_x','37_x','38_x','39_x','40_x','41_x','42_x','43_x','44_x','45_x','46_x','47_x','48_x','49_x','50_x','51_x','52_x','53_x','54_x','55_x','56_x','57_x','58_x','59_x','60_x','61_x','62_x','63_x','64_x','65_x','66_x','67_x','68_x','69_x','70_x','71_x','72_x','73_x','74_x','75_x','76_x','77_x','78_x','79_x','80_x','81_x','82_x','83_x','84_x','85_x','86_x','87_x','88_x','89_x','90_x','91_x','92_x','93_x','94_x','95_x','96_x','97_x','98_x','99_x','100_x','101_x','102_x','103_x','104_x','105_x','106_x','107_x','108_x','109_x','110_x','111_x','112_x','113_x','114_x','115_x','116_x','117_x','118_x','119_x','120_x','121_x','122_x','123_x','124_x','125_x','126_x','127_x','128_x','129_x','130_x','131_x','132_x','133_x','134_x','135_x','136_x','137_x','138_x','139_x','140_x','141_x','142_x','143_x','144_x','145_x','146_x','147_x','148_x','149_x','150_x','151_x','152_x','153_x','154_x','155_x','156_x','157_x','158_x','159_x','160_x','161_x','162_x','163_x','164_x','165_x','166_x','167_x','168_x','169_x','170_x','171_x','172_x','173_x','174_x','175_x','176_x','177_x','178_x','179_x','180_x','181_x','182_x','183_x','184_x','185_x','186_x','187_x','188_x','189_x','190_x','191_x','192_x','193_x','194_x','195_x','196_x','197_x','198_x','199_x','200_x','201_x','202_x','203_x','204_x','205_x','206_x','207_x','208_x','209_x','210_x','211_x','212_x','213_x','214_x','215_x','216_x','217_x','218_x','219_x','220_x','221_x','222_x','223_x','224_x','225_x','226_x','227_x','228_x','229_x','230_x','231_x','232_x','233_x','234_x','235_x','236_x','237_x','238_x','239_x','240_x','241_x','242_x','243_x','244_x','245_x','246_x','247_x','248_x','249_x','250_x','251_x','252_x','253_x','254_x','255_x','256_x','257_x','258_x','259_x','260_x','261_x','262_x','263_x','264_x','265_x','266_x','267_x','268_x','269_x','270_x','271_x','272_x','273_x','274_x','275_x','276_x','277_x','278_x','279_x','280_x','281_x','282_x','283_x','284_x','285_x','286_x','287_x','288_x','289_x','290_x','291_x','292_x','293_x','294_x','295_x','296_x','297_x','298_x','299_x','300_x','301_x','302_x','303_x','304_x','305_x','306_x','307_x','308_x','309_x','310_x','311_x','312_x','313_x','314_x','315_x','316_x','317_x','318_x','319_x','320_x','321_x','322_x','323_x','324_x','325_x','326_x','327_x','328_x','329_x','330_x','331_x','332_x','333_x','334_x','335_x','336_x','337_x','338_x','339_x','340_x','341_x','342_x','343_x','344_x','345_x','346_x','347_x','348_x','349_x','350_x','351_x','352_x','353_x','354_x','355_x','356_x','357_x','358_x','359_x','360_x','361_x','362_x','363_x','364_x','365_x','366_x','367_x','368_x','369_x','370_x','371_x','372_x','373_x','374_x','375_x','376_x','377_x','378_x','379_x','380_x','381_x','382_x','383_x','0_y','1_y','2_y','3_y','4_y','5_y','6_y','7_y','8_y','9_y','10_y','11_y','12_y','13_y','14_y','15_y','16_y','17_y','18_y','19_y','20_y','21_y','22_y','23_y','24_y','25_y','26_y','27_y','28_y','29_y','30_y','31_y','32_y','33_y','34_y','35_y','36_y','37_y','38_y','39_y','40_y','41_y','42_y','43_y','44_y','45_y','46_y','47_y','48_y','49_y','50_y','51_y','52_y','53_y','54_y','55_y','56_y','57_y','58_y','59_y','60_y','61_y','62_y','63_y','64_y','65_y','66_y','67_y','68_y','69_y','70_y','71_y','72_y','73_y','74_y','75_y','76_y','77_y','78_y','79_y','80_y','81_y','82_y','83_y','84_y','85_y','86_y','87_y','88_y','89_y','90_y','91_y','92_y','93_y','94_y','95_y','96_y','97_y','98_y','99_y','100_y','101_y','102_y','103_y','104_y','105_y','106_y','107_y','108_y','109_y','110_y','111_y','112_y','113_y','114_y','115_y','116_y','117_y','118_y','119_y','120_y','121_y','122_y','123_y','124_y','125_y','126_y','127_y','128_y','129_y','130_y','131_y','132_y','133_y','134_y','135_y','136_y','137_y','138_y','139_y','140_y','141_y','142_y','143_y','144_y','145_y','146_y','147_y','148_y','149_y','150_y','151_y','152_y','153_y','154_y','155_y','156_y','157_y','158_y','159_y','160_y','161_y','162_y','163_y','164_y','165_y','166_y','167_y','168_y','169_y','170_y','171_y','172_y','173_y','174_y','175_y','176_y','177_y','178_y','179_y','180_y','181_y','182_y','183_y','184_y','185_y','186_y','187_y','188_y','189_y','190_y','191_y','192_y','193_y','194_y','195_y','196_y','197_y','198_y','199_y','200_y','201_y','202_y','203_y','204_y','205_y','206_y','207_y','208_y','209_y','210_y','211_y','212_y','213_y','214_y','215_y','216_y','217_y','218_y','219_y','220_y','221_y','222_y','223_y','224_y','225_y','226_y','227_y','228_y','229_y','230_y','231_y','232_y','233_y','234_y','235_y','236_y','237_y','238_y','239_y','240_y','241_y','242_y','243_y','244_y','245_y','246_y','247_y','248_y','249_y','250_y','251_y','252_y','253_y','254_y','255_y','256_y','257_y','258_y','259_y','260_y','261_y','262_y','263_y','264_y','265_y','266_y','267_y','268_y','269_y','270_y','271_y','272_y','273_y','274_y','275_y','276_y','277_y','278_y','279_y','280_y','281_y','282_y','283_y','284_y','285_y','286_y','287_y','288_y','289_y','290_y','291_y','292_y','293_y','294_y','295_y','296_y','297_y','298_y','299_y','300_y','301_y','302_y','303_y','304_y','305_y','306_y','307_y','308_y','309_y','310_y','311_y','312_y','313_y','314_y','315_y','316_y','317_y','318_y','319_y','320_y','321_y','322_y','323_y','324_y','325_y','326_y','327_y','328_y','329_y','330_y','331_y','332_y','333_y','334_y','335_y','336_y','337_y','338_y','339_y','340_y','341_y','342_y','343_y','344_y','345_y','346_y','347_y','348_y','349_y','350_y','351_y','352_y','353_y','354_y','355_y','356_y','357_y','358_y','359_y','360_y','361_y','362_y','363_y','364_y','365_y','366_y','367_y','368_y','369_y','370_y','371_y','372_y','373_y','374_y','375_y','376_y','377_y','378_y','379_y','380_y','381_y','382_y','383_y'], chunksize=chunksize, iterator=True, encoding='utf-8', ):\n        df.index += index_start\n        j+=1\n        print('{} rows'.format(j*chunksize))\n        df.to_sql('data', disk_engine, if_exists='append')\n        index_start = df.index[-1] + 1\n \"\"\"\n\"\"\"\n#http:\/\/www.sqlitetutorial.net\/sqlite-python\/create-tables\/\ndef create_connection(db_file):\n     create a database connection to the SQLite database\n        specified by db_file\n    :param db_file: database file\n    :return: Connection object or None\n    \n    try:\n        conn = sqlite3.connect(db_file)\n        return conn\n    except Error as e:\n        print(e)\n \n    return None\n\n\ndef checkTableExists(dbcon):\n    cursr = dbcon.cursor()\n    str = \"select name from sqlite_master where type='table'\"\n    table_names = cursr.execute(str)\n    print(\"Tables in the databse:\")\n    tables =table_names.fetchall() \n    print(tables[0][0])\n    return(len(tables))\n\"\"\"\n\"\"\"\n  #read_db = 'train.db'\n#  conn_r = create_connection(read_db)\n # checkTableExists(conn_r)\nconn_r.close()\n\"\"\"\n\"\"\"\n# try to sample data according to the computing power you have\nif os.path.isfile(read_db):\n    conn_r = create_connection(read_db)\n    if conn_r is not None:\n        # for selecting first 1M rows\n        # data = pd.read_sql_query(\"\"\"SELECT * FROM data LIMIT 100001;\"\"\", conn_r\n        \n        # for selecting random points\n        data = pd.read_sql_query(\"SELECT * From data ORDER BY RANDOM() LIMIT 100001;\", conn_r)\n        conn_r.commit()\n        conn_r.close()\n\"\"\"\ndf=pd.read_csv(\".\/final_features.csv\")\ndf.head()\n# remove the first row \n\ny_true = df['is_duplicate']\ndf.drop(['Unnamed: 0', 'id','is_duplicate'], axis=1, inplace=True)\ndf.head()\n-y_true = list(map(int, y_true.values))\n\"\"\"\n#  Random train test split( 70:30) \n\"\"\"\nX_train,X_test, y_train, y_test = train_test_split(df, y_true, stratify=y_true, test_size=0.3)\nprint(\"Number of data points in train data :\",X_train.shape)\nprint(\"Number of data points in test data :\",X_test.shape)\nprint(\"-\"*10, \"Distribution of output variable in train data\", \"-\"*10)\ntrain_distr = Counter(y_train)\ntrain_len = len(y_train)\nprint(\"Class 0: \",int(train_distr[0])\/train_len,\"Class 1: \", int(train_distr[1])\/train_len)\nprint(\"-\"*10, \"Distribution of output variable in train data\", \"-\"*10)\ntest_distr = Counter(y_test)\ntest_len = len(y_test)\nprint(\"Class 0: \",int(test_distr[1])\/test_len, \"Class 1: \",int(test_distr[1])\/test_len)\n# This function plots the confusion matrices given y_i, y_i_hat.\ndef plot_confusion_matrix(test_y, predict_y):\n    C = confusion_matrix(test_y, predict_y)\n    # C = 9,9 matrix, each cell (i,j) represents number of points of class i are predicted class j\n    \n    A =(((C.T)\/(C.sum(axis=1))).T)\n    #divid each element of the confusion matrix with the sum of elements in that column\n    \n    # C = [[1, 2],\n    #     [3, 4]]\n    # C.T = [[1, 3],\n    #        [2, 4]]\n    # C.sum(axis = 1)  axis=0 corresonds to columns and axis=1 corresponds to rows in two diamensional array\n    # C.sum(axix =1) = [[3, 7]]\n    # ((C.T)\/(C.sum(axis=1))) = [[1\/3, 3\/7]\n    #                           [2\/3, 4\/7]]\n\n    # ((C.T)\/(C.sum(axis=1))).T = [[1\/3, 2\/3]\n    #                           [3\/7, 4\/7]]\n    # sum of row elements = 1\n    \n    B =(C\/C.sum(axis=0))\n    #divid each element of the confusion matrix with the sum of elements in that row\n    # C = [[1, 2],\n    #     [3, 4]]\n    # C.sum(axis = 0)  axis=0 corresonds to columns and axis=1 corresponds to rows in two diamensional array\n    # C.sum(axix =0) = [[4, 6]]\n    # (C\/C.sum(axis=0)) = [[1\/4, 2\/6],\n    #                      [3\/4, 4\/6]] \n    plt.figure(figsize=(20,4))\n    \n    labels = [1,2]\n    # representing A in heatmap format\n    cmap=sns.light_palette(\"blue\")\n    plt.subplot(1, 3, 1)\n    sns.heatmap(C, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n    plt.xlabel('Predicted Class')\n    plt.ylabel('Original Class')\n    plt.title(\"Confusion matrix\")\n    \n    plt.subplot(1, 3, 2)\n    sns.heatmap(B, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n    plt.xlabel('Predicted Class')\n    plt.ylabel('Original Class')\n    plt.title(\"Precision matrix\")\n    \n    plt.subplot(1, 3, 3)\n    # representing B in heatmap format\n    sns.heatmap(A, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n    plt.xlabel('Predicted Class')\n    plt.ylabel('Original Class')\n    plt.title(\"Recall matrix\")\n    \n    plt.show()\n\"\"\"\n# Building a random model (Finding worst-case log-loss) \n\"\"\"\n# we need to generate 9 numbers and the sum of numbers should be 1\n# one solution is to genarate 9 numbers and divide each of the numbers by their sum\n# ref: https:\/\/stackoverflow.com\/a\/18662466\/4084039\n# we create a output array that has exactly same size as the CV data\npredicted_y = np.zeros((test_len,2))\nfor i in range(test_len):\n    rand_probs = np.random.rand(1,2)\n    predicted_y[i] = ((rand_probs\/sum(sum(rand_probs)))[0])\nprint(\"Log loss on Test Data using Random Model\",log_loss(y_test, predicted_y, eps=1e-15))\n\npredicted_y =np.argmax(predicted_y, axis=1)\nplot_confusion_matrix(y_test, predicted_y)\n\"\"\"\n# Logistic Regression with hyperparameter tuning \n\"\"\"\nalpha = [10 ** x for x in range(-5, 2)] # hyperparam for SGD classifier.\n\n# read more about SGDClassifier() at http:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.linear_model.SGDClassifier.html\n# ------------------------------\n# default parameters\n# SGDClassifier(loss=\u2019hinge\u2019, penalty=\u2019l2\u2019, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=None, tol=None, \n# shuffle=True, verbose=0, epsilon=0.1, n_jobs=1, random_state=None, learning_rate=\u2019optimal\u2019, eta0=0.0, power_t=0.5, \n# class_weight=None, warm_start=False, average=False, n_iter=None)\n\n# some of methods\n# fit(X, y[, coef_init, intercept_init, \u2026])\tFit linear model with Stochastic Gradient Descent.\n# predict(X)\tPredict class labels for samples in X.\n\n#-------------------------------\n# video link: \n#------------------------------\n\n\nlog_error_array=[]\nfor i in alpha:\n    clf = SGDClassifier(alpha=i, penalty='l2', loss='log', random_state=42)\n    clf.fit(X_train, y_train)\n    sig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\n    sig_clf.fit(X_train, y_train)\n    predict_y = sig_clf.predict_proba(X_test)\n    log_error_array.append(log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n    print('For values of alpha = ', i, \"The log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n\nfig, ax = plt.subplots()\nax.plot(alpha, log_error_array,c='g')\nfor i, txt in enumerate(np.round(log_error_array,3)):\n    ax.annotate((alpha[i],np.round(txt,3)), (alpha[i],log_error_array[i]))\nplt.grid()\nplt.title(\"Cross Validation Error for each alpha\")\nplt.xlabel(\"Alpha i's\")\nplt.ylabel(\"Error measure\")\nplt.show()\n\n\nbest_alpha = np.argmin(log_error_array)\nclf = SGDClassifier(alpha=alpha[best_alpha], penalty='l2', loss='log', random_state=42)\nclf.fit(X_train, y_train)\nsig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\nsig_clf.fit(X_train, y_train)\n\npredict_y = sig_clf.predict_proba(X_train)\nprint('For values of best alpha = ', alpha[best_alpha], \"The train log loss is:\",log_loss(y_train, predict_y, labels=clf.classes_, eps=1e-15))\npredict_y = sig_clf.predict_proba(X_test)\nprint('For values of best alpha = ', alpha[best_alpha], \"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\npredicted_y =np.argmax(predict_y,axis=1)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)\n\"\"\"\n# Linear SVM with hyperparameter tuning \n\"\"\"\nalpha = [10 ** x for x in range(-5, 2)] # hyperparam for SGD classifier.\n\n# read more about SGDClassifier() at http:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.linear_model.SGDClassifier.html\n# ------------------------------\n# default parameters\n# SGDClassifier(loss=\u2019hinge\u2019, penalty=\u2019l2\u2019, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=None, tol=None, \n# shuffle=True, verbose=0, epsilon=0.1, n_jobs=1, random_state=None, learning_rate=\u2019optimal\u2019, eta0=0.0, power_t=0.5, \n# class_weight=None, warm_start=False, average=False, n_iter=None)\n\n# some of methods\n# fit(X, y[, coef_init, intercept_init, \u2026])\tFit linear model with Stochastic Gradient Descent.\n# predict(X)\tPredict class labels for samples in X.\n\n#-------------------------------\n# video link: \n#------------------------------\n\n\nlog_error_array=[]\nfor i in alpha:\n    clf = SGDClassifier(alpha=i, penalty='l1', loss='hinge',max_iter=15,random_state=42)\n    clf.fit(X_train, y_train)\n    sig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\n    sig_clf.fit(X_train, y_train)\n    predict_y = sig_clf.predict_proba(X_test)\n    log_error_array.append(log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n    print('For values of alpha = ', i, \"The log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n\nfig, ax = plt.subplots()\nax.plot(alpha, log_error_array,c='g')\nfor i, txt in enumerate(np.round(log_error_array,3)):\n    ax.annotate((alpha[i],np.round(txt,3)), (alpha[i],log_error_array[i]))\nplt.grid()\nplt.title(\"Cross Validation Error for each alpha\")\nplt.xlabel(\"Alpha i's\")\nplt.ylabel(\"Error measure\")\nplt.show()\n\n\nbest_alpha = np.argmin(log_error_array)\nclf = SGDClassifier(alpha=alpha[best_alpha], penalty='l1', loss='hinge', random_state=42)\nclf.fit(X_train, y_train)\nsig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\nsig_clf.fit(X_train, y_train)\n\npredict_y = sig_clf.predict_proba(X_train)\nprint('For values of best alpha = ', alpha[best_alpha], \"The train log loss is:\",log_loss(y_train, predict_y, labels=clf.classes_, eps=1e-15))\npredict_y = sig_clf.predict_proba(X_test)\nprint('For values of best alpha = ', alpha[best_alpha], \"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\npredicted_y =np.argmax(predict_y,axis=1)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)\n\"\"\"\n# XGBoost \n\"\"\"\nimport xgboost as xgb\nparams = {}\nparams['objective'] = 'binary:logistic'\nparams['eval_metric'] = 'logloss'\nparams['eta'] = 0.02\nparams['max_depth'] = 4\n\nd_train = xgb.DMatrix(X_train, label=y_train)\nd_test = xgb.DMatrix(X_test, label=y_test)\n\nwatchlist = [(d_train, 'train'), (d_test, 'valid')]\n\nbst = xgb.train(params, d_train, 400, watchlist, early_stopping_rounds=20, verbose_eval=10)\n\nxgdmat = xgb.DMatrix(X_train,y_train)\npredict_y = bst.predict(d_test)\nprint(\"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\npredicted_y =np.array(predict_y>0.5,dtype=int)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)","meta":"{'source': 'AI4Code', 'id': '47c2748eafb8a9'}"}
{"id":"14261","text":"\"\"\"\n# Problem Statement\nA bike-sharing system is a service in which bikes are made available for shared use to individuals on a short term basis for a price or free. Many bike share systems allow people to borrow a bike from a \"dock\" which is usually computer-controlled wherein the user enters the payment information, and the system unlocks it. This bike can then be returned to another dock belonging to the same system.\n\n\nA US bike-sharing provider BoomBikes has recently suffered considerable dips in their revenues due to the ongoing Corona pandemic. The company is finding it very difficult to sustain in the current market scenario. So, it has decided to come up with a mindful business plan to be able to accelerate its revenue as soon as the ongoing lockdown comes to an end, and the economy restores to a healthy state.\n\nIn such an attempt, BoomBikes aspires to understand the demand for shared bikes among the people after this ongoing quarantine situation ends across the nation due to Covid-19. They have planned this to prepare themselves to cater to the people's needs once the situation gets better all around and stand out from other service providers and make huge profits.\n\n\nThey have contracted a consulting company to understand the factors on which the demand for these shared bikes depends. Specifically, they want to understand the factors affecting the demand for these shared bikes in the American market. The company wants to know:\n- Which variables are significant in predicting the demand for shared bikes.\n- How well those variables describe the bike demands\n\nBased on various meteorological surveys and people's styles, the service provider firm has gathered a large dataset on daily bike demands across the American market based on some factors. \n\n## Business Goal:\nYou are required to model the demand for shared bikes with the available independent variables. It will be used by the management to understand how exactly the demands vary with different features. They can accordingly manipulate the business strategy to meet the demand levels and meet the customer's expectations. Further, the model will be a good way for management to understand the demand dynamics of a new market. \n\"\"\"\n### Import important libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n### Read the file\n\nbike=pd.read_csv(\"\/kaggle\/input\/bikesharing\/day.csv\")\nbike.head()\n### Dataframe shape\n\nbike.shape\n###Information\n\nbike.info()\n\"\"\"\n***There is no null value***\n\"\"\"\n### Change season into proper format  as these have some labels\n\nbike['season']=bike['season'].replace({1:'spring', 2:'summer', 3:'fall', 4:'winter'})\n\n### Change weathersit into proper format\n\nbike['weathersit']=bike['weathersit'].replace({1:'Sunny\/Partial cloudy', 2:'cloudy\/Misty', 3:'Light rainy\/Light snowy', 4:'Heavy rainy\/heavy snowy'})\n\n### Change weekday into proper format\n\nbike['weekday']=bike['weekday'].replace({1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thrusday',5:'Friday',6:'Saturday',7:'Sunday'})\n### Change weekday into proper format\n\nbike['mnth']=bike['mnth'].replace({1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'})\n\n###check dataframe again to check whether all above 4 codes are applied correctly or not\n\nbike.head()\n### Fetching list of all numerical values\n\nbike.describe().columns.to_list()\n### Outlier detection\n\n\nplt.figure(figsize=[15,18])\n\n\nbike_num=['instant',\n 'yr',\n 'holiday',\n 'workingday',\n 'temp',\n 'atemp',\n 'hum',\n 'windspeed',\n 'casual',\n 'registered',\n 'cnt']\nc=1\n\nfor i in bike_num:\n    plt.subplot(3, 4, c)\n    plt.title('{}'.format(i))\n    plt.xlabel(i)\n    sns.boxplot(bike[i])\n    c = c + 1\n    \nplt.show()\n\"\"\"\n**There is no outliers,we are good to go**\n\"\"\"\n\"\"\"\n# Visualization\n\"\"\"\n###pairplot\n\nsns.pairplot(bike)\nplt.show()\n\"\"\"\n**We can observe that there are some linear relationship between target variable(cnt) and some independent variables**\n\"\"\"\n### We can drop thsese column because it has no significance\n\nbike.drop(['dteday'],axis=1,inplace=True)\nbike.drop(['instant'],axis=1,inplace=True)\nbike.drop(['casual'],axis=1,inplace=True)\nbike.drop(['registered'],axis=1,inplace=True)\n\n###Checkinga dataframe again\nbike.head()\n###Correlation using heatmap\n\nplt.figure(figsize=[11,7])\nbike_corr=bike[['yr','holiday','workingday','temp','atemp','hum','windspeed','cnt']].corr()\nsns.heatmap(data=bike_corr,annot=True)\nplt.show()\n\"\"\"\n- Target variable is highly correlated with registered\n- Target variable is moderately correlated with temp,atemp,year and casual\n\n\"\"\"\n### We can drop either atemp or temp because of high correlation\n### Dropping atemp\nbike.drop(['temp'],axis=1,inplace=True)\n\"\"\"\n### Looking pattern into categorical columns\n\n\n\"\"\"\n### Looking pattern into categorical columns using boxplots\n\nplt.figure(figsize=(20, 12))\n\nplt.subplot(2,2,1)\nsns.boxplot(x = 'season', y = 'cnt', data = bike)\n\nplt.subplot(2,2,2)\nsns.boxplot(x = 'mnth', y = 'cnt', data = bike)\n\nplt.subplot(2,2,3)\nsns.boxplot(x = 'weekday', y = 'cnt', data = bike)\n\nplt.subplot(2,2,4)\nsns.boxplot(x = 'weathersit', y = 'cnt', data = bike)\n\nplt.show()\n\"\"\"\n- In spring season deamnd is less.\n- In the month of January and December demands are lowest while highest in the month.\n- In light rainy\/light snowny demand is lowest while in sunny demand is highest\n\"\"\"\n\"\"\"\n# Data Prepartion\n\"\"\"\n### Dummy variable\n\n### Season,mnth,weekdays and weathersit have some lebels\n### Change these labels into 0\/1.\n### We are dropping first column because to minimize redundancy.\nseason_d=pd.get_dummies(bike['season'],drop_first = True)\nmnth_d=pd.get_dummies(bike['mnth'],drop_first = True)\nweekday_d=pd.get_dummies(bike['weekday'],drop_first = True)\nweathersit_d=pd.get_dummies(bike['weathersit'],drop_first = True)\n### Add the above results into original data set\n\nbike=pd.concat([bike,season_d,mnth_d,weekday_d,weathersit_d],axis=1)\nbike.head()\n## Checking columns\nbike.columns\n### Drop Season,mnth,weekday,weathersit columns because these are no more significant.\n\nbike=bike.drop(['season','mnth','weekday','weathersit'],axis=1)\nbike.head()\n\"\"\"\n## Spliting data set into train and test\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nnp.random.seed(0)\nbike_train, bike_test = train_test_split(bike, train_size = 0.7, random_state = 100)\n### checking shape of splitted data frame\nprint(bike_train.shape)\nprint(bike_test.shape)\n\"\"\"\n## Rescaling using MinMaxScaler\n\"\"\"\nbike_train.head()\n### Importing MinMaxScaler\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\n\n\n\n###Variable on which scaling to be applied are,\nbike_num=['atemp','hum','windspeed','cnt']\n\n### Apply Scaler\n\nbike_train[bike_num] = scaler.fit_transform(bike_train[bike_num])\nbike_train.describe()\n\"\"\"\n**Scaling applied successfully**\n\"\"\"\n### Regplot for target variable with independent variable for train data set to check linear relationship.\n\nplt.figure(figsize=[20,7])\n\nplt.subplot(1,3,1)\nsns.regplot(data=bike_train,x='atemp',y='cnt')\n\n\nplt.subplot(1,3,2)\nsns.regplot(data=bike_train,x='hum',y='cnt')\n\nplt.subplot(1,3,3)\nsns.regplot(data=bike_train,x='windspeed',y='cnt')\n\n\nplt.show()\n\"\"\"\n**We can clearly see that target variable has many linear relationship with independent variables**\n\"\"\"\n### Separate target and independent variables\n\ny_train = bike_train.pop('cnt')\nX_train = bike_train\n### Checking shape of target and independent dataframe\nprint(y_train.shape)\nprint(X_train.shape)\n### Using RFE,we will find top 10 columns\n\n#Importing libraries\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LinearRegression\n\nmodel = LinearRegression()\nmodel.fit(X_train, y_train)\n\nrfe = RFE(model, 10)            \nrfe = rfe.fit(X_train, y_train)\nlist(zip(X_train.columns,rfe.support_,rfe.ranking_))\n### Top 10 columns\ntop_10_col = X_train.columns[rfe.support_]\ntop_10_col\n### selecting top 10 independent variable,selected using RFE method\nX_train_top_10 = X_train[top_10_col]\nX_train_top_10.shape\nimport statsmodels.api as sm \n# Adding a constant variable to avoid line passing through origin\n \nX_train_cons = sm.add_constant(X_train_top_10)\n# Creating first model \nmlr = sm.OLS(y_train, X_train_cons).fit()\n### Fetching constant and coefficients of models\nmlr.params\n### Fetching summaries like p-value,r-squared,adjusted r-squared etc. of model\n\nprint(mlr.summary())\n\"\"\"\n- Before dropping columns we will also ckeck VIF of independent variables\n- VIF is used to check multicollinearity between independent variables\n\"\"\"\n### Importing libraries to check VIF\n\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n### Checking VIF value i.e multicollinearity\n\nvif = pd.DataFrame()\nvif['Features'] = X_train_top_10.columns\nvif['VIF'] = [variance_inflation_factor(X_train_top_10.values, i) for i in range(X_train_top_10.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\n### First we will drop which are highly insignificant and hight VIF i.e\n### Dropping hum because of high VIF value\n\nX_dropped = X_train_top_10.drop('hum', 1)\nX_dropped.shape\n# Building second model\nX_train_cons = sm.add_constant(X_dropped)\n\nmlr2 = sm.OLS(y_train, X_train_cons).fit()\n### summaries of second model\n\nprint(mlr2.summary())\n### Checking VIFs for second model\n\nvif = pd.DataFrame()\nvif['Features'] = X_dropped.columns\nvif['VIF'] = [variance_inflation_factor(X_dropped.values, i) for i in range(X_dropped.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\n### Next,We will drop 'Sunny\/Partial cloudy' because it has high VIF value'\nX_dropped = X_dropped.drop('Sunny\/Partial cloudy', 1,)\nX_dropped.shape\n# Building third  model\nX_train_cons = sm.add_constant(X_dropped)\n\nmlr3 = sm.OLS(y_train, X_train_cons).fit()\n\n### Summaries of third model\n\nprint(mlr3.summary())\n### Checking VIFs for third model\n\nvif = pd.DataFrame()\nvif['Features'] = X_dropped.columns\nvif['VIF'] = [variance_inflation_factor(X_dropped.values, i) for i in range(X_dropped.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\nX_train_cons.head()\nX_train_cons.columns\nX_train_latest = X_train_cons.drop(['const'], axis=1)\nX_train_latest.columns\n\"\"\"\n# mlr3 is the decent  model\n\"\"\"\n### Residual analysis\n\ny_train_pred = mlr3.predict(X_train_cons)\n# plotting distribution plot to check distribution of error terms\n\nplt.figure(figsize=[8,5])\nerror = y_train - y_train_pred\nsns.distplot(error, hist=False,bins = 50)\nplt.title('Distribution of residual term')                \nplt.show()    \n\"\"\"\n**Errors are normally distributed with mean is equal to zero**\n\"\"\"\n\"\"\"\n### Making prediction using mlr3\n\n\n\n\"\"\"\n###Variable on which scaling to be applied are,\nbike_num=['atemp','hum','windspeed','cnt']\n\n### Apply Scaler\n\nbike_test[bike_num] = scaler.transform(bike_test[bike_num])\nbike_test.describe()\n### Splitting test data set into dependent and independent variable\ny_test = bike_test.pop('cnt')\nX_test = bike_test\n# Now let's use our model to make predictions.\n\n# Creating X_test_cons with columns using final X_tain\nX_test_cons = X_test[X_train_latest.columns]\n\n# Adding a constant variable to avoid line passing through origin\nX_test_cons = sm.add_constant(X_test_cons)\n# Making predictions using final model i.e mlr3\ny_pred = mlr3.predict(X_test_cons)\n### Importing library to compare r-squared\n\nfrom sklearn.metrics import r2_score\n\n### R-squared for test dataframe\nprint(r2_score(y_test, y_pred))\n\n### R-squared for train dataframe\nprint(r2_score(y_train, y_train_pred))\n\"\"\"\n### Tthe R-squared for train and test both dataframe within acceptable range\n- R-Squared_test:76.8\n- R-Squared_train :78.1\n\"\"\"\n\"\"\"\n# Equation of Final model is\n\n<span style='color:green'> **Demand= 0.1175 + 0.2394(yr)-0.0823(holiday) + 0.5795(atemp) - 0.1628(windspeed) + 0.0821(summer) + 0.1070(winter) + 0.0919(sep) - 0.0658(cloud\/misty)**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1a0d8b3b6fbdfc'}"}
{"id":"58129","text":"!mkdir -p \/root\/.cache\/torch\/hub\/checkpoints\n!cp -r ..\/input\/landmark-additional-packages\/rwightman_gen-efficientnet-pytorch_master\/rwightman_gen-efficientnet-pytorch_master \/root\/.cache\/torch\/hub\n!cp ..\/input\/landmark-additional-packages\/tf_efficientnet_b3_aa-84b4657e.pth \/root\/.cache\/torch\/hub\/checkpoints\/\n!cp ..\/input\/landmark-additional-packages\/tf_efficientnet_b5_ra-9a3e5369.pth \/root\/.cache\/torch\/hub\/checkpoints\/\n!cp ..\/input\/landmark-additional-packages\/se_resnext50_32x4d-a260b3a4.pth \/root\/.cache\/torch\/hub\/checkpoints\/\n!cp ..\/input\/landmark-additional-packages\/resnet50d_ra2-464e36ba.pth \/root\/.cache\/torch\/hub\/checkpoints\/\n!pip install -q ..\/input\/landmark-additional-packages\/timm-0.3.4-py3-none-any.whl\n!pip install -q ..\/input\/landmark-additional-packages\/geffnet-1.0.0-py3-none-any.whl\n!pip install -q ..\/input\/landmark-additional-packages\/EfficientNet-PyTorch\/EfficientNet-PyTorch-master\n!pip install -q ..\/input\/landmark-additional-packages\/pycocotools-2.0.2\/dist\/pycocotools-2.0.2.tar\n!pip install -q ..\/input\/landmark-additional-packages\/pretrainedmodels-0.7.4\/pretrainedmodels-0.7.4\n!pip install \"\/kaggle\/input\/hpamisc\/pytorch_zoo-master\"\n!pip install \"\/kaggle\/input\/hpamisc\/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl\"\n!pip install \"\/kaggle\/input\/hpamisc\/faiss_gpu-1.7.0-cp37-cp37m-manylinux2014_x86_64.whl\"\n! python ..\/input\/maozi-no-arcface\/maozi_no_arcface.py\nimport sys\nsys.path.append('..\/input\/hpa-singlecell-e050f56\/hpa_singlecell-double_level_valid_all\/')\n\nfrom torch import nn\nimport torch\nimport torch.nn.functional as F\nimport torchvision\nimport timm\nfrom torch.nn.parameter import Parameter\nimport albumentations as A\n\nfrom utils import parse_args, prepare_for_result\nfrom torch.utils.data import DataLoader, Dataset\nfrom losses import get_loss, get_class_balanced_weighted\nfrom dataloaders import get_dataloader\nfrom utils import load_matched_state\nfrom configs import Config\nfrom models import get_model\nfrom dataloaders.transform_loader import get_tfms\n\ntensor_tfms = torchvision.transforms.Compose([\n            torchvision.transforms.ToTensor(),\n            torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406, 0.406], std=[0.229, 0.224, 0.225, 0.225]),\n        ])\n\ntta_tfms = A.Compose([\n    A.Resize(always_apply=False, p=1, height=256, width=256, interpolation=1),\n    A.HorizontalFlip(always_apply=False, p=0.5),\n    A.ShiftScaleRotate(always_apply=False, p=0.7, shift_limit_x=(-0.06, 0.06), shift_limit_y=(-0.06, 0.06), scale_limit=(-0.3, 0.3), rotate_limit=(-22.5, 22.5), interpolation=1, border_mode=2, value=None, mask_value=None),\n    A.RandomBrightnessContrast(always_apply=False, p=0.5, brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), brightness_by_max=True),\n])\n\n\nimport base64\nimport zlib\nfrom pycocotools import _mask as coco_mask\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport tqdm\nimport seaborn as sns\ndef binary_mask_to_ascii(mask, mask_val=1):\n    \"\"\"Converts a binary mask into OID challenge encoding ascii text.\"\"\"\n    mask = np.where(mask==mask_val, 1, 0).astype(np.bool)\n    \n    # check input mask --\n    if mask.dtype != np.bool:\n        raise ValueError(f\"encode_binary_mask expects a binary mask, received dtype == {mask.dtype}\")\n\n    mask = np.squeeze(mask)\n    if len(mask.shape) != 2:\n        raise ValueError(f\"encode_binary_mask expects a 2d mask, received shape == {mask.shape}\")\n\n    # convert input mask to expected COCO API input --\n    mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)\n    mask_to_encode = mask_to_encode.astype(np.uint8)\n    mask_to_encode = np.asfortranarray(mask_to_encode)\n\n    # RLE encode mask --\n    encoded_mask = coco_mask.encode(mask_to_encode)[0][\"counts\"]\n\n    # compress and base64 encoding --\n    binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)\n    base64_str = base64.b64encode(binary_str)\n    return base64_str.decode()\n\ndef process(x):\n    iid, msk, img, sz = x\n    img = cv2.resize(img, (2048, 2048))\n    enc_msk = cv2.resize(msk, (sz, sz))\n    cell_mask = msk\n    subs = {}\n    results = []\n    for i in range(1, cell_mask.max() + 1):\n        enc = binary_mask_to_ascii(enc_msk, i)\n        sub = cv2.resize((cell_mask == i).astype(np.float), (2048, 2048), cv2.INTER_LINEAR)\n        xr, yr = np.where(sub == 1)\n        xmin, xmax, ymin, ymax = xr.min(), xr.max(), yr.min(), yr.max()\n        subs[i] = (img * np.repeat((sub == 1).astype(np.int)[:, :, np.newaxis], 4, 2))[xmin:xmax, ymin: ymax]\n#         imsave(f'.\/seg_png_fix_test\/{iid}_{i}.png', (255 * subs[i]).astype(np.uint8))\n        results.append(((255 * subs[i]).astype(np.uint8), enc, sz, sz))\n    return results\n\ndef squarify(M,val):\n    (a,b,c)=M.shape\n    if a>b:\n        padding=((0,0),((a-b)\/\/2,a-b-(a-b)\/\/2),(0, 0))\n    else:\n        padding=(((b-a)\/\/2,b-a-(b-a)\/\/2),(0,0),(0, 0))\n    return np.pad(M,padding,mode='constant',constant_values=val)\n\"\"\"\n## Loading models\n* b3\n* b5\n* r50d\n* r200d\n* se50\n\"\"\"\nckpt = {\n    0: 13, 1: 12, 2: 12, 3: 11, 4: 14\n}\n\nmodels = []\nfor i in range(5):\n    cfg = Config.load_json('..\/input\/hpa-single-cell-b3-philandrare-5f\/5f_double_sin_exp5_rare.yaml\/config.json')\n    model = get_model(cfg).cuda()\n    load_matched_state(model, torch.load(\n        f'..\/input\/hpa-single-cell-b3-philandrare-5f\/5f_double_sin_exp5_rare.yaml\/f{i}_epoch-{ckpt[i]}.pth'))\n    _ = model.eval()\n    models.append(model)\nckpt = {\n    0: 18, 1: 14, 2: 14, 3: 15, 4: 15\n}\n\n# models = []\nfor i in range(5):\n    if i in [2, 3, 4]: continue\n    cfg = Config.load_json('..\/input\/hpa-b5-final-model\/b5_final_hpa_0504\/config.json')\n    model = get_model(cfg).cuda()\n    load_matched_state(model, torch.load(\n        f'..\/input\/hpa-b5-final-model\/b5_final_hpa_0504\/checkpoints\/f{i}_epoch-{ckpt[i]}.pth'))\n    _ = model.eval()\n    models.append(model)\nckpt = {\n    0: 19, 1: 19, 2: 17, 3: 17, 4: 18\n}\n\nfor i in range(5):\n    if i in [0, 3, 4]: continue\n    cfg = Config.load_json('..\/input\/hpa-resnet50d-0508\/resnet50d_final\/config.json')\n    model = get_model(cfg).cuda()\n    load_matched_state(model, torch.load(\n        f'..\/input\/hpa-resnet50d-0508\/resnet50d_final\/checkpoints\/f{i}_epoch-{ckpt[i]}.pth'))\n    _ = model.eval()\n    models.append(model)\n!cp ..\/input\/landmark-additional-packages\/resnet200d_ra2-bdba9bf9.pth \/root\/.cache\/torch\/hub\/checkpoints\/\nckpt = {\n    0: 15, 1: 15, 2: 13, 3: 13\n}\n\nfor i in range(4):\n    if i in [0, 1, 4]: continue\n    cfg = Config.load_json('..\/input\/hpa-jakiro-resnet200d\/double_sin_exp5_r200d_rarex2_upload\/config.json')\n    model = get_model(cfg).cuda()\n    load_matched_state(model, torch.load(\n        f'..\/input\/hpa-jakiro-resnet200d\/double_sin_exp5_r200d_rarex2_upload\/f{i}_epoch-{ckpt[i]}.pth'))\n    _ = model.eval()\n    models.append(model)\nckpt = {\n    0: 19, 1: 16, 2: 16, 3: 17, 4:19\n}\n\nfor i in range(5):\n    if i in [0, 1, 2]: continue\n    print(i)\n    cfg = Config.load_json('..\/input\/hpa-se50-final-0509\/se50_final\/config.json')\n    model = get_model(cfg).cuda()\n    load_matched_state(model, torch.load(\n        f'..\/input\/hpa-se50-final-0509\/se50_final\/checkpoints\/f{i}_epoch-{ckpt[i]}.pth'))\n    _ = model.eval()\n    models.append(model)\nlen(models)\n\"\"\"\n## If we read from a csv\n\"\"\"\ndf = pd.read_csv('submission.csv')\n\nimgs = []\nfor i, x in df.iterrows():\n    label = x.PredictionString.split(' ')[0::3]\n    prob = x.PredictionString.split(' ')[1::3]\n    encodes = x.PredictionString.split(' ')[2::3]\n    for idx, enc in enumerate(list(set(encodes))):\n        imgs.append({\n            'image_id': x.ID,\n            'cell_id': idx+1,\n            'enc': enc,\n            'fname': f'{x.ID}_{idx+1}',\n        })\n\ntm = pd.DataFrame(imgs)\nprobs = []\nfor i, x in df.iterrows():\n    label = x.PredictionString.split(' ')[0::3]\n    prob = x.PredictionString.split(' ')[1::3]\n    encodes = x.PredictionString.split(' ')[2::3]\n    for idx, enc in enumerate(encodes):\n        probs.append({\n            'enc': enc,\n            'predict': int(label[idx]),\n            'prob': float(prob[idx])\n        })\n\nprob = pd.DataFrame(probs)\ntm_pred = prob.groupby(['enc', 'predict']).mean().unstack()['prob']\ntm_pred.columns.name = ''\nteam = tm[['enc', 'fname']].merge(tm_pred.reset_index(), on='enc', how='inner').drop('enc', 1)\nsample_submission = pd.read_csv('..\/input\/hpa-single-cell-image-classification\/sample_submission.csv', index_col=0)\nteam_pred = team.set_index('fname')\nclass SliceInferenceDataset(torch.utils.data.Dataset):\n    def __init__(self, df, tta=16, cfg=None, tfms=None):\n        self.df = df\n        self.iids = self.df.image_id.unique()\n        self.tta = tta\n        \n    def __len__(self):\n        return len(self.iids)\n\n    def __getitem__(self, idx):\n        iid = self.iids[idx]\n        mt = f'..\/input\/hpa-single-cell-image-classification\/test\/{iid}_red.png'\n        er = f'..\/input\/hpa-single-cell-image-classification\/test\/{iid}_yellow.png'\n        nu = f'..\/input\/hpa-single-cell-image-classification\/test\/{iid}_blue.png'\n        pr = f'..\/input\/hpa-single-cell-image-classification\/test\/{iid}_green.png'\n        r = cv2.imread(mt, 0).astype(np.float) \/ 255.0\n        g = cv2.imread(pr, 0).astype(np.float) \/ 255.0\n        b = cv2.imread(nu, 0).astype(np.float) \/ 255.0\n        a = cv2.imread(er, 0).astype(np.float) \/ 255.0\n        sz = r.shape[0]\n        img = np.stack([r, g, b, a], -1)\n        sli = []\n        for i, x in self.df[self.df.image_id == iid].iterrows():\n            bd = base64.b64decode(x.enc)\n            zd = zlib.decompress(bd)\n            encoded = [{'counts': zd, 'size': (sz, sz)}]\n            ded = coco_mask.decode(encoded)[:, :, 0]\n\n            xr, yr = np.where(ded == 1)\n            sub = img[xr.min(): xr.max(), yr.min(): yr.max()]\n            crop_sub_mask = ded[xr.min(): xr.max(), yr.min(): yr.max()]\n            crop_sub_mask = np.repeat(crop_sub_mask[:, :, np.newaxis], 4, axis=2)\n            r = sub * crop_sub_mask\n            sli.append((cv2.resize(squarify(r, 0), (256, 256)).astype(np.float32), x.fname))\n        BS, tta=len(sli) + 1, self.tta\n        ipts = []\n        raw_ipt = [e[0] for e in sli]\n        for tt in range(tta):\n            ipts.append(torch.stack([tensor_tfms(tta_tfms(image=x)['image']) for x in raw_ipt]).float())\n        return ipts, BS, len(sli), tta, iid, [x[1] for x in sli]\n# tm\nsid = SliceInferenceDataset(tm, tta=8)\ndl = torch.utils.data.DataLoader(sid, batch_size=1, num_workers=2)\npdfs = []\nwhole_dfs = []\nfor ipts, BS, lsli, tta, iid, fnames_raw in tqdm.tqdm(dl):\n    BS, tta, iid, fnames, lsli = BS.item(), tta.item(), iid[0], [e[0] for e in fnames_raw], lsli.item()\n    predicted_ps = []\n    exp_ps = []\n    for i in range(0, lsli, BS):\n    #   ipt = torch.stack([tensor_tfms(cv2.resize(squarify(s[0], 0), (256, 256))) for s in ress[i: BS+i]]).cuda()\n        with torch.no_grad():\n            res = []\n            exp = []\n            for tt in range(tta):\n                ipt = ipts[tt][0].cuda()\n                for model in models:\n                    with torch.cuda.amp.autocast():\n                        ifr = model(ipt, len(ipt))\n                    res.append(ifr[0].float())\n                    exp.append(ifr[1].float())\n        predict_p = [torch.sigmoid(r.cpu()) for r in res]\n        exp_p = [torch.sigmoid(r.cpu()) for r in exp]\n        predict_p = np.stack(predict_p).mean(0)\n        exp_p = np.stack(exp_p).mean(0)\n        predicted_ps.append(predict_p)\n        exp_ps.append(exp_p)\n    p = np.concatenate(predicted_ps)\n    image_df = pd.DataFrame(p, index=fnames)\n    whole_df = pd.DataFrame(np.concatenate(exp_ps).mean(0).reshape(1, 19), index=[iid])\n    whole_dfs.append(whole_df)\n    pdfs.append(image_df) \n# tm = tm.reset_index('fname')\nimage_level = pd.concat(whole_dfs)\nimage_pred = image_level.reset_index().merge(\n    tm[['image_id', 'fname']], left_on='index', right_on='image_id', how='left'\n).set_index('fname').drop(['index', 'image_id'], 1)\npub_pred = pd.concat(pdfs)\nmerge_pred = pub_pred * image_pred.loc[pub_pred.index]\n\"\"\"\n## If any ensemble\n\"\"\"\nmerge_pred\nensem = merge_pred + team_pred.loc[merge_pred.index]\nmerge_pred = ensem\n\"\"\"\n## Save prediction\n\"\"\"\ndf = df.set_index('ID')\nmerge_pred.index.name = 'fname'\nmerge_pred = merge_pred.reset_index()\ntm = tm.set_index('fname')\n\nmerge_pred['ID'] = merge_pred['fname'].str.split('_', expand=True)[0]\nj_pred = []\nfor iid in merge_pred.ID.unique():\n    enc = ''\n    sub_df = merge_pred[merge_pred.ID == iid]\n    for idx, row in sub_df.iterrows():\n        for i in range(19):\n            enc += f'{i} {row[i]} {tm.loc[row.fname].enc} '\n    j_pred.append({\n        'ID': iid,\n        'ImageWidth': df.loc[iid].ImageWidth,\n        'ImageHeight': df.loc[iid].ImageHeight,\n        'PredictionString': enc[:-1]\n    })\nfast_sub = pd.DataFrame(j_pred)\nfast_sub.to_csv('pub.csv')\nfast_sub = fast_sub.set_index('ID')\nfast_sub.head(2)\n\"\"\"\n## save\n\"\"\"\nsub2 = pd.concat([sample_submission.drop(fast_sub.index), fast_sub], 0)\nsub2 = sub2.loc[sample_submission.index]\nsub2.to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': '6b5de3e2fe7eac'}"}
{"id":"136669","text":"\"\"\"\n# Final project: Fault Segmentation \n### This assignment is to implement convolutional neural networks for fault data segmentation\n### AI in geosciences, ESS1502\n\"\"\"\n\"\"\"\n#### Task: Train and validate your networks\/models on the provide dataset. You are free to use Tensorflow, Keras, or Pytorch to implement your networks. The test result need to upload to the kaggle platform to get the final score \n\"\"\"\nfrom modelarts.session import Session\nsession = Session()\nsession.download_data(bucket_path=\"20ai-project\/data.npy\", path=\"\/home\/ma-user\/work\/data.npy\")\nsession.download_data(bucket_path=\"20ai-project\/label.npy\", path=\"\/home\/ma-user\/work\/label.npy\")\nsession.download_data(bucket_path=\"20ai-project\/new_test_data.npy\", path=\"\/home\/ma-user\/work\/new_test_data.npy\")\n# session.download_data(bucket_path=\"20ai-project\/new_test_label.npy\", path=\"\/home\/ma-user\/work\/new_test_label.npy\")\n\"\"\"\n## 1. Import the requirements\n\"\"\"\nimport os\nimport random\nimport numpy as np\nimport skimage\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom numpy.random import seed\nfrom keras import backend as K\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau, TensorBoard\nfrom keras import backend as keras\nfrom keras.models import load_model\nfrom keras.utils import to_categorical\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nseed(12345)\nos.mkdir('fig')\nos.mkdir('check1channel')\n\"\"\"\n## 2. Load the train dataset\n\"\"\"\n# select your own datapath\ndata = np.load('data.npy')\nlabel = np.load('label.npy')\n\"\"\"\n### 2.1 visualize the train dataset\n\"\"\"\nj = 1500\nplt.figure(figsize=(8,4),dpi=200)\nplt.subplot(1,2,1)\nplt.imshow(np.squeeze(data[j,:,:]),cmap=plt.cm.gray)\nplt.subplot(1,2,2)\nplt.imshow(np.squeeze(label[j,:,:]),interpolation=\"bilinear\",vmin=0.2,vmax=1.0,cmap=plt.cm.gray)\nfigname = '.\/fig\/data_' +str(j)+'.jpg'\nplt.savefig(figname)\ndef Z_ScoreNormalization(x): #\u7070\u5ea6\u503c\u5f52\u4e00\u5316\n    for i in range(len(x)):\n        mu = np.average(x[i,:])\n        sigma = np.std(x[i,:])\n        x[i,:] = (x[i,:] - mu) \/ sigma;\n    return x;\n# normalize data\ndata = Z_ScoreNormalization(data)\ndata = np.reshape(data,(2000,128,128,1))\nlabel = np.reshape(label,(2000,128,128,1))\n# split the train_data and val_data\ntrain_data = data[0:1600]\nval_data = data[1600:2000]\ntrain_label = label[0:1600]\nval_label = label[1600:2000]\nprint(train_data.shape)\nprint(val_data.shape)\nprint(train_label.shape)\nprint(val_label.shape)\n\"\"\"\n## 3. Define the neural network\n\"\"\"\n#given network\ndef unet(pretrained_weights=None, input_size1=(None, None, 1)):\n    input = Input(input_size1, name='input')\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(input)\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(conv1)\n    pool1 = MaxPooling2D(pool_size=(2,2))(conv1)\n\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(pool1)\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(conv2)\n    pool2 = MaxPooling2D(pool_size=(2,2))(conv2)\n\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(pool2)\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(conv3)\n    pool3 = MaxPooling2D(pool_size=(2,2))(conv3)\n\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(pool3)\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(conv4)\n\n    up5 = concatenate([UpSampling2D(size=(2,2))(conv4), conv3], axis=-1)\n    conv5 = Conv2D(64, (3,3), activation='relu', padding='same')(up5)\n    conv5 = Conv2D(64, (3,3), activation='relu', padding='same')(conv5)\n\n    up6 = concatenate([UpSampling2D(size=(2,2))(conv5), conv2], axis=-1)\n    conv6 = Conv2D(32, (3,3), activation='relu', padding='same')(up6)\n    conv6 = Conv2D(32, (3,3), activation='relu', padding='same')(conv6)\n\n    up7 = concatenate([UpSampling2D(size=(2,2))(conv6), conv1], axis=-1)\n    conv7 = Conv2D(16, (3,3), activation='relu', padding='same')(up7)\n    conv7 = Conv2D(16, (3,3), activation='relu', padding='same')(conv7)\n\n    conv8 = Conv2D(1, (1,1), activation='sigmoid')(conv7)\n    model = Model(inputs=[input], outputs=[conv8])\n    model.summary()\n    return model\n#one more layer\n#each layer one more convlution with a (1,1) kernel\ndef unet(pretrained_weights=None, input_size1=(None, None, 1)):\n    input = Input(input_size1, name='input')\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(input)\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(16, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(16, (1,1), activation='relu', padding='same')(conv1)\n    pool1 = MaxPooling2D(pool_size=(2,2))(conv1)\n\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(pool1)\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(32, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(32, (1,1), activation='relu', padding='same')(conv2)\n    pool2 = MaxPooling2D(pool_size=(2,2))(conv2)\n\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(pool2)\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(64, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(64, (1,1), activation='relu', padding='same')(conv3)\n    pool3 = MaxPooling2D(pool_size=(2,2))(conv3)\n\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(pool3)\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(128, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(128, (1,1), activation='relu', padding='same')(conv4)\n    pool4 = MaxPooling2D(pool_size=(2,2))(conv4)\n    \n    conv5 = Conv2D(256, (3,3), activation='relu', padding='same')(pool4)\n    conv5 = Conv2D(256, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(256, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(256, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(256, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(256, (1,1), activation='relu', padding='same')(conv5)\n\n    up6 = concatenate([UpSampling2D(size=(2,2))(conv5), conv4], axis=-1)\n    conv6 = Conv2D(128, (3,3), activation='relu', padding='same')(up6)\n    conv6 = Conv2D(128, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(128, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(128, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(128, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(128, (1,1), activation='relu', padding='same')(conv6)\n\n    up7 = concatenate([UpSampling2D(size=(2,2))(conv6), conv3], axis=-1)\n    conv7 = Conv2D(64, (3,3), activation='relu', padding='same')(up7)\n    conv7 = Conv2D(64, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(64, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(64, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(64, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(64, (1,1), activation='relu', padding='same')(conv7)\n\n    up8 = concatenate([UpSampling2D(size=(2,2))(conv7), conv2], axis=-1)\n    conv8 = Conv2D(32, (3,3), activation='relu', padding='same')(up8)\n    conv8 = Conv2D(32, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(32, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(32, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(32, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(32, (1,1), activation='relu', padding='same')(conv8)\n    \n    up9 = concatenate([UpSampling2D(size=(2,2))(conv8), conv1], axis=-1)\n    conv9 = Conv2D(16, (3,3), activation='relu', padding='same')(up9)\n    conv9 = Conv2D(16, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(16, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(16, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(16, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(16, (1,1), activation='relu', padding='same')(conv9)\n\n    conv10 = Conv2D(1, (1,1), activation='sigmoid')(conv9)\n    model = Model(inputs=[input], outputs=[conv10])\n    model.summary()\n    return model\n#one more layer\n#begin with 32\n#each layer one more convlution with a (1,1) kernel\ndef unet(pretrained_weights=None, input_size1=(None, None, 1)):\n    input = Input(input_size1, name='input')\n    conv1 = Conv2D(32, (3,3), activation='relu', padding='same')(input)\n    conv1 = Conv2D(32, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(32, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(32, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(32, (3,3), activation='relu', padding='same')(conv1)\n    conv1 = Conv2D(32, (1,1), activation='relu', padding='same')(conv1)\n    pool1 = MaxPooling2D(pool_size=(2,2))(conv1)\n\n    conv2 = Conv2D(64, (3,3), activation='relu', padding='same')(pool1)\n    conv2 = Conv2D(64, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(64, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(64, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(64, (3,3), activation='relu', padding='same')(conv2)\n    conv2 = Conv2D(64, (1,1), activation='relu', padding='same')(conv2)\n    pool2 = MaxPooling2D(pool_size=(2,2))(conv2)\n\n    conv3 = Conv2D(128, (3,3), activation='relu', padding='same')(pool2)\n    conv3 = Conv2D(128, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(128, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(128, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(128, (3,3), activation='relu', padding='same')(conv3)\n    conv3 = Conv2D(128, (1,1), activation='relu', padding='same')(conv3)\n    pool3 = MaxPooling2D(pool_size=(2,2))(conv3)\n\n    conv4 = Conv2D(256, (3,3), activation='relu', padding='same')(pool3)\n    conv4 = Conv2D(256, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(256, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(256, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(256, (3,3), activation='relu', padding='same')(conv4)\n    conv4 = Conv2D(256, (1,1), activation='relu', padding='same')(conv4)\n    pool4 = MaxPooling2D(pool_size=(2,2))(conv4)\n    \n    conv5 = Conv2D(512, (3,3), activation='relu', padding='same')(pool4)\n    conv5 = Conv2D(512, (3,3), activation='relu', padding='same')(pool4)\n    conv5 = Conv2D(512, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(512, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(512, (3,3), activation='relu', padding='same')(conv5)\n    conv5 = Conv2D(512, (1,1), activation='relu', padding='same')(conv5)\n\n    up6 = concatenate([UpSampling2D(size=(2,2))(conv5), conv4], axis=-1)\n    conv6 = Conv2D(256, (3,3), activation='relu', padding='same')(up6)\n    conv6 = Conv2D(256, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(256, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(256, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(256, (3,3), activation='relu', padding='same')(conv6)\n    conv6 = Conv2D(256, (1,1), activation='relu', padding='same')(conv6)\n\n    up7 = concatenate([UpSampling2D(size=(2,2))(conv6), conv3], axis=-1)\n    conv7 = Conv2D(128, (3,3), activation='relu', padding='same')(up7)\n    conv7 = Conv2D(128, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(128, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(128, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(128, (3,3), activation='relu', padding='same')(conv7)\n    conv7 = Conv2D(128, (1,1), activation='relu', padding='same')(conv7)\n\n    up8 = concatenate([UpSampling2D(size=(2,2))(conv7), conv2], axis=-1)\n    conv8 = Conv2D(64, (3,3), activation='relu', padding='same')(up8)\n    conv8 = Conv2D(64, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(64, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(64, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(64, (3,3), activation='relu', padding='same')(conv8)\n    conv8 = Conv2D(64, (1,1), activation='relu', padding='same')(conv8)\n    \n    up9 = concatenate([UpSampling2D(size=(2,2))(conv8), conv1], axis=-1)\n    conv9 = Conv2D(32, (3,3), activation='relu', padding='same')(up9)\n    conv9 = Conv2D(32, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(32, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(32, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(32, (3,3), activation='relu', padding='same')(conv9)\n    conv9 = Conv2D(32, (1,1), activation='relu', padding='same')(conv9)\n\n    conv10 = Conv2D(1, (1,1), activation='sigmoid')(conv9)\n    model = Model(inputs=[input], outputs=[conv10])\n    model.summary()\n    return model\nmodel = unet()\nmodel.compile(optimizer=Adam(lr=5e-4), loss='binary_crossentropy',metrics=['accuracy'])\n# checkpoint\nfilepath=\"check1channel\/fault-{epoch:02d}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_accuracy',verbose=1, save_best_only=False, mode='max')\ncallbacks_list = [checkpoint]\nprint(\"data prepared, ready to train!\")\n# Fit the model\nhistory = model.fit(train_data, train_label,\n#                    validation_split=0.2,\n                    validation_data=(val_data,val_label),\n                    epochs=40,\n                    batch_size=8,\n                    shuffle=True,\n                    verbose=1,callbacks=callbacks_list)\n\n\"\"\"\n## 4. Plot the loss and acc\n\"\"\"\ndef showHistory(history):\n  # list all data in history\n  print(history.history.keys())\n  fig = plt.figure(figsize=(10,6))\n\n  # summarize history for accuracy\n  plt.plot(history.history['acc'])\n  plt.plot(history.history['val_acc'])\n  plt.title('Model accuracy',fontsize=20)\n  plt.ylabel('Accuracy',fontsize=20)\n  plt.xlabel('Epoch',fontsize=20)\n  plt.legend(['train', 'test'], loc='center right',fontsize=20)\n  plt.tick_params(axis='both', which='major', labelsize=18)\n  plt.tick_params(axis='both', which='minor', labelsize=18)\n  plt.show()\n\n  # summarize history for loss\n  fig = plt.figure(figsize=(10,6))\n  plt.plot(history.history['loss'])\n  plt.plot(history.history['val_loss'])\n  plt.title('Model loss',fontsize=20)\n  plt.ylabel('Loss',fontsize=20)\n  plt.xlabel('Epoch',fontsize=20)\n  plt.legend(['train', 'test'], loc='center right',fontsize=20)\n  plt.tick_params(axis='both', which='major', labelsize=18)\n  plt.tick_params(axis='both', which='minor', labelsize=18)\n  plt.show()\nshowHistory(history)\n\"\"\"\n## 5. Validate the network using val_data\n\"\"\"\nmodel = load_model('.\/check1channel\/fault-28.hdf5')\n# need a threshold to get the true predict result \nthreshold = 0.4\nresult = model.predict(val_data)\nresult[result>threshold]=1\nresult[result<threshold]=0\n# np.save('.\/Data\/data\/result.npy',result)\nj=200\nplt.figure(figsize=(12,4),dpi=150)\nplt.subplot(1,3,1)\nplt.imshow(np.squeeze(val_data[j,:,:,:]),cmap=plt.cm.gray)\nplt.subplot(1,3,2)\nplt.imshow(np.squeeze(result[j,:,:,:]),interpolation=\"bilinear\",vmin=0.2,vmax=1.0,cmap=plt.cm.gray)\nplt.subplot(1,3,3)\nplt.imshow(np.squeeze(val_label[j,:,:]),interpolation=\"bilinear\",vmin=0.2,vmax=1.0,cmap=plt.cm.gray)\n# savefig\nfigname = '.\/fig\/data_pred_nothreshold_' +str(j)+'.jpg'\nplt.savefig(figname)\n\"\"\"\n## 6. Predictions on the testing datasets and visualize the prediction results\n\"\"\"\nnew_test_data = np.load('new_test_data.npy')\n# new_test_label = np.load('new_test_label.npy')\nreal_test_data = np.reshape(new_test_data,(100,256,640,1))\n# real_test_label = np.reshape(new_test_label,(100,256,640,1))\ntemp = 0.25\nreal_result = model.predict(real_test_data)\nreal_result[real_result>temp]=1\nreal_result[real_result<temp]=0\nresult = np.squeeze(real_result)\n# np.save('.\/Data\/data\/real_result.npy',real_result)\nj=50\nplt.figure(figsize=(6,6),dpi=150)\nplt.subplot(2,1,1)\nplt.imshow(np.squeeze(real_test_data[j,:,:,:]),cmap=plt.cm.gray)\nplt.subplot(2,1,2)\nplt.imshow(np.squeeze(real_result[j,:,:]),interpolation=\"bilinear\",vmin=0.2,vmax=1.0,cmap=plt.cm.gray)\n\"\"\"\n## 7. Output the results as csv and upload it to the kaggle\n\"\"\"\nresult_csv = np.reshape(result,(-1))\nprint(result_csv.shape)\ndf = pd.DataFrame(result_csv)\ndf=df.astype(int)\ndf=df.astype(str)\ndf['index'] = range(len(df))\nnew_col = ['value', 'index']\ndf.columns = new_col\norder = ['index','value']\ndf=df[order]\ndf=df.astype(str)\nprint(df)\n#choose your own name\ndf.to_csv('2_13_5.csv',index=False)\nimport moxing as mox\nmox.file.copy('2_13_5.csv','obs:\/\/geo-ai-dataset\/2_13_5.csv')\nprint(\"done\")","meta":"{'source': 'AI4Code', 'id': 'fb33a412fad0ff'}"}
{"id":"96920","text":"# Import required libraries\nimport os\nimport gc\nimport sys\nimport json\nimport random\nfrom pathlib import Path\n\nimport cv2 # CV2 for image manipulation\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nfrom tqdm import tqdm\n\nfrom imgaug import augmenters as iaa\n\nimport seaborn as sns\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.model_selection import StratifiedKFold, KFold\n!pip install tensorflow==1.5\n!pip install keras==2.1.5\n\nimport tensorflow\nprint(tensorflow.__version__)\nimport keras\nprint(keras.__version__)\n!ls \/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/\n%%time\nwith open('\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/label_descriptions.json', 'r') as file:\n    label_desc = json.load(file)\nsample_sub_df = pd.read_csv('\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/sample_submission.csv')\ntrain_df = pd.read_csv('\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train.csv')\ntrain_df.head()\nsample_sub_df.head()\nprint(f'Shape of training dataset: {train_df.shape}')\nprint(f'# of images in training set: {train_df[\"ImageId\"].nunique()}')\nprint(f'# of images in test set: {sample_sub_df[\"ImageId\"].nunique()}')\n\"\"\"\n### Image size analysis in training dataset\n\"\"\"\npd.DataFrame([train_df['Height'].describe(), train_df['Width'].describe()]).T.loc[['max', 'min', 'mean']]\n\"\"\"\n### Height and Width destribution of training images\n\"\"\"\nimage_shape_df = train_df.groupby(\"ImageId\")[\"Height\", \"Width\"].first()\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5))\nax1.hist(image_shape_df['Height'], bins=100)\nax1.set_title(\"Height distribution\")\nax2.hist(image_shape_df['Width'], bins=100)\nax2.set_title(\"Width distribution\")\nplt.show()\n\"\"\"\n### Image with minimum height\n\"\"\"\nplt.figure(figsize = (70,7))\nmin_height = list(set(train_df[train_df['Height'] == train_df['Height'].min()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{min_height}.jpg'))\nplt.grid(False)\nplt.show()\n\"\"\"\n### Image with maximum height\n\"\"\"\nplt.figure(figsize = (70,7))\nmax_height = list(set(train_df[train_df['Height'] == train_df['Height'].max()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{max_height}.jpg'))\nplt.grid(False)\nplt.show()\n\"\"\"\n### Image with minimum width\n\"\"\"\nplt.figure(figsize = (70,7))\nmin_width = list(set(train_df[train_df['Width'] == train_df['Width'].min()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{min_width}.jpg'))\nplt.grid(False)\nplt.show()\n\"\"\"\n### Image with maximum width\n\"\"\"\nplt.figure(figsize = (70,7))\nmax_width = list(set(train_df[train_df['Width'] == train_df['Width'].max()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{max_width}.jpg'))\nplt.grid(False)\nplt.show()\narea_df = pd.DataFrame()\narea_df['ImageId'] = train_df['ImageId']\narea_df['area'] = train_df['Height'] * train_df['Width']\nmin_area = list(set(area_df[area_df['area'] == area_df['area'].min()]['ImageId']))[0]\nmax_area = list(set(area_df[area_df['area'] == area_df['area'].max()]['ImageId']))[0]\n\"\"\"\n### Image with minimum area\n\"\"\"\nplt.figure(figsize = (70,7))\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{min_area}.jpg'))\nplt.grid(False)\nplt.show()\n\"\"\"\n### Image with maximum area\n\"\"\"\nplt.figure(figsize = (70,7))\nplt.imshow(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{max_area}.jpg'))\nplt.grid(False)\nplt.show()\n\"\"\"\n## Details about Classes and Attributes\n\"\"\"\nnum_classes = len(label_desc['categories'])\nnum_attributes = len(label_desc['attributes'])\nprint(f'Total # of classes: {num_classes}')\nprint(f'Total # of attributes: {num_attributes}')\ncategories_df = pd.DataFrame(label_desc['categories'])\nattributes_df = pd.DataFrame(label_desc['attributes'])\ncategories_df\npd.set_option('display.max_rows', 300)\nattributes_df\n\"\"\"\n## Plotting a few training images without any masks\n\"\"\"\ndef plot_images(size=12, figsize=(12, 12)):\n    # First get some images to be plotted\n    image_ids = train_df['ImageId'].unique()[:12]\n    images=[]\n    \n    for image in image_ids:\n        images.append(mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{image}.jpg'))\n    \n    # Plot images in groups of 4 images\n    n_groups = 4\n    \n    count = 0\n    for index in range(size \/\/ 4):\n        fig, ax = plt.subplots(nrows=2, ncols=2, figsize=figsize)\n        for row in ax:\n            for col in row:\n                col.imshow(images[count])\n                col.axis('off')\n                count += 1\n        plt.show()\n    gc.collect()\nplot_images()\n\"\"\"\n## Plotting a few images with given segments\n\"\"\"\ndef create_mask(size):\n    image_ids = train_df['ImageId'].unique()[:size]\n    images_meta=[]\n\n    for image_id in image_ids:\n        img = mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{image_id}.jpg')\n        images_meta.append({\n            'image': img,\n            'shape': img.shape,\n            'encoded_pixels': train_df[train_df['ImageId'] == image_id]['EncodedPixels'],\n            'class_ids':  train_df[train_df['ImageId'] == image_id]['ClassId']\n        })\n\n    masks = []\n    for image in images_meta:\n        shape = image.get('shape')\n        encoded_pixels = list(image.get('encoded_pixels'))\n        class_ids = list(image.get('class_ids'))\n        \n        # Initialize numpy array with shape same as image size\n        height, width = shape[:2]\n        mask = np.zeros((height, width)).reshape(-1)\n        \n        # Iterate over encoded pixels and create mask\n        for segment, (pixel_str, class_id) in enumerate(zip(encoded_pixels, class_ids)):\n            splitted_pixels = list(map(int, pixel_str.split()))\n            pixel_starts = splitted_pixels[::2]\n            run_lengths = splitted_pixels[1::2]\n            assert max(pixel_starts) < mask.shape[0]\n            for pixel_start, run_length in zip(pixel_starts, run_lengths):\n                pixel_start = int(pixel_start) - 1\n                run_length = int(run_length)\n                mask[pixel_start:pixel_start+run_length] = 255 - class_id * 4\n        masks.append(mask.reshape((height, width), order='F'))  # https:\/\/stackoverflow.com\/questions\/45973722\/how-does-numpy-reshape-with-order-f-work\n    return masks, images_meta\ndef plot_segmented_images(size=12, figsize=(14, 14)):\n    # First create masks from given segments\n    masks, images_meta = create_mask(size)\n    \n    # Plot images in groups of 4 images\n    n_groups = 4\n    \n    count = 0\n    for index in range(size \/\/ 4):\n        fig, ax = plt.subplots(nrows=2, ncols=2, figsize=figsize)\n        for row in ax:\n            for col in row:\n                col.imshow(images_meta[count]['image'])\n                col.imshow(masks[count], alpha=0.75)\n                col.axis('off')\n                count += 1\n        plt.show()\n    gc.collect()\nplot_segmented_images()\n\"\"\"\n## Analysing Categories and Attributes\n\"\"\"\ncategories_df = pd.DataFrame(label_desc.get('categories'))\nattributes_df = pd.DataFrame(label_desc.get('attributes'))\nprint(f'# of categories: {len(categories_df)}')\nprint(f'# of attributes: {len(attributes_df)}')\n\"\"\"\nSo there are 46 categories (classes) and 294 attributes. Let's see some of the categories and attributes\n\"\"\"\ncategories_df.head()\nattributes_df.head()\ncategory_map, attribute_map = {}, {}\nfor cat in label_desc.get('categories'):\n    category_map[cat.get('id')] = cat.get('name')\nfor attr in label_desc.get('attributes'):\n    attribute_map[attr.get('id')] = attr.get('name')\ntrain_df['ClassId'] = train_df['ClassId'].map(category_map)\ntrain_df['ClassId'] = train_df['ClassId'].astype('category')\n\"\"\"\n### Let's see the class wise distribution of segments in training dataset\n\"\"\"\nsns.set(style='darkgrid')\nfig, ax = plt.subplots(figsize = (10,10))\nsns.countplot(y='ClassId',data=train_df , ax=ax, order = train_df['ClassId'].value_counts().index)\nfig.show()\n\"\"\"\n### Now let's visualize an image with all its classes and attributes\n\"\"\"\nIMAGE_ID = '000b3ec2c6eaffb491a5abb72c2e3e26'\n# Get the an image id given in the training set for visualization\nvis_df = train_df[train_df['ImageId'] == IMAGE_ID]\nvis_df['ClassId'] = vis_df['ClassId'].cat.codes\nvis_df = vis_df.reset_index(drop=True)\nvis_df\n\"\"\"\nFrom above table, this image has 8 segmentes and a few attributes. Let's visualize all of them!\n\"\"\"\n\"\"\"\n## Let's first the plot the plain image\n\"\"\"\nplt.figure(figsize = (110,11))\nimage = mpimg.imread(f'\/kaggle\/input\/imaterialist-fashion-2020-fgvc7\/train\/{IMAGE_ID}.jpg')\nplt.grid(False)\nplt.imshow(image)\nplt.plot()\ntrain_df[train_df['ImageId'] == IMAGE_ID]\n\"\"\"\n## Now let's plot each segment in a separate image\n\"\"\"\nsegments = list(vis_df['EncodedPixels'])\nclass_ids = list(vis_df['ClassId'])\nmasks = []\nfor segment, class_id in zip(segments, class_ids):\n    \n    height = vis_df['Height'][0]\n    width = vis_df['Width'][0]\n    # Initialize empty mask\n    mask = np.zeros((height, width)).reshape(-1)\n    \n    # Iterate over encoded pixels and create mask\n    splitted_pixels = list(map(int, segment.split()))\n    pixel_starts = splitted_pixels[::2]\n    run_lengths = splitted_pixels[1::2]\n    assert max(pixel_starts) < mask.shape[0]\n    for pixel_start, run_length in zip(pixel_starts, run_lengths):\n        pixel_start = int(pixel_start) - 1\n        run_length = int(run_length)\n        mask[pixel_start:pixel_start+run_length] = 255 - class_id * 4\n\n    mask = mask.reshape((height, width), order='F')\n    masks.append(mask)\ndef plot_individual_segment(*masks, image, figsize=(110, 11)):\n    plt.figure(figsize = figsize)\n    plt.imshow(image)\n    for mask in masks:\n        plt.imshow(mask, alpha=0.6)\n    plt.axis('off')\n    plt.show()\n\"\"\"\n## Plotting 1st Segment: ClassId: \"Shoe\" and no attributes \n\"\"\"\nplot_individual_segment(masks[0], image=image)\n\"\"\"\n## Plotting 2nd Segment: ClassId: \"shoe\"\n\"\"\"\nplot_individual_segment(masks[1], image=image)\n\"\"\"\n## Plotting 3rd Segment with ClassId: \"pants\"\n\"\"\"\nplot_individual_segment(masks[2], image=image)\n\"\"\"\n## Plotting 4th Segment with ClassId: \"top, t-shirt, sweatshirt\"\n\"\"\"\nplot_individual_segment(masks[3], image=image)\n\"\"\"\n## Plotting 5th Segment with ClassId: \"pocket\"\n\"\"\"\nplot_individual_segment(masks[4], image=image)\n\"\"\"\n## Plotting 6th Segment with ClassId: \"sleeve\"\n\"\"\"\nplot_individual_segment(masks[5], image=image)\n\"\"\"\n## Plotting 7th Segment with ClassId: \"sleeve\"\n\"\"\"\nplot_individual_segment(masks[6], image=image)\n\"\"\"\n## Plotting 8th segment with Class \"neckline\"\n\"\"\"\nplot_individual_segment(masks[6], image=image)\n\"\"\"\nSome of the segments have no attributes. Let's check how many such segment exists in training dataset.\n\"\"\"\n\"\"\"\nLet's check of missing values in training dataset for columns other than \"AttributeIds\"\n\"\"\"\ntrain_df[['ImageId', 'EncodedPixels', 'Height', 'Width', 'ClassId']].isna().sum()\n\"\"\"\n## Data Preparation and modeling\n\"\"\"\ntrain_df.head()\ntrain_df['ClassId'] = train_df['ClassId'].cat.codes\ntrain_df","meta":"{'source': 'AI4Code', 'id': 'b206d2f79830e0'}"}
{"id":"90470","text":"\"\"\"\n# Set Lists\n\nThis notebook generates files that list all cards in a set in the order which I use to archive a set. It goes by collector number, which isn't in the data source, but is (hopefully) what is used as an index\n\"\"\"\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\ncolorWheel = ['White', 'Blue', 'Black', 'Red', 'Green', 'Colorless', 'Multi']\nkeeps = ['name', 'rarity']\n\nraw = pd.read_json('..\/input\/AllSets-x.json')\nraw.shape\n\n#setStartDate = '2003-07-28' #8th Edition and later\nsetStartDate = '2013-09-26' #Theros and later\n\nsets = {}\nmtg = []\nfor col in raw.columns.values:\n    release = pd.DataFrame(raw[col]['cards'])\n    release = release.loc[:, keeps]\n    #release['modernLegal'] = release.legalities.apply(lambda l: 'none' if not isinstance(l,list) else next((legals['legality'] for legals in l if legals['format'] == 'Modern'),'none'))\n    #release = release[release.modernLegal == 'Legal']\n    #print(release.modernLegal.unique())\n    #release = release[release.legalities.isnotnull() and release.legalities]\n    if raw[col]['releaseDate'] > setStartDate and (raw[col]['type'] == 'core' or raw[col]['type'] == 'expansion'): #8th edition was released 2003-07-29, so this should include all modern sets\n        release['index'] = release.reset_index().index\n        release['setName'] = raw[col]['name']\n        release['releaseDate'] = raw[col]['releaseDate']\n        mtg.append(release)\n        sets[col] = release\ndel release, raw\nprint(len(sets))\nmtg.sort(key=lambda x: x['releaseDate'][0])\noutput = '''\\\\documentclass[10pt]{article}\n\\\\usepackage[left=3cm, right=2cm, top=1cm, bottom=1cm]{geometry}\n\\\\usepackage{amsmath}\n\\\\usepackage{graphicx}\n\\\\usepackage{hyperref}\n\\\\usepackage[latin1]{inputenc}\n\n\\\\begin{document}\n\\\\pagestyle{empty}\n\n\\\\twocolumn '''\n\nfor curSet in mtg:\n    df = curSet\n    df.sort_values(by=['index'])\n    df['output'] = df['index'].apply(lambda x: str(x+1).zfill(3)) + '  ' + df.rarity.apply(lambda x: x[0]) + '  ' + df['index'].apply(lambda x: str(int(x \/ 9 + 1)).zfill(2) + ':'+str(x % 9 + 1)) +'   ' + df['name']\n    setname = df['setName'][0]\n    output += '\\\\section{'+setname+'}\\n\\\\begin{description}\\n\\\\setlength\\\\itemsep{-0.5em}\\n'\n    output += df.output.apply(lambda x: '\\t\\\\item ' + x).str.cat(sep='\\n')\n    output +='\\n\\\\end{description}\\n\\\\clearpage\\n'\n    \n    \noutput += '\\\\end{document}'\n\nf = open('sets.tex','w')\nf.write(output)\nf.close()","meta":"{'source': 'AI4Code', 'id': 'a5eba5526f1bf6'}"}
{"id":"21817","text":"\"\"\"\n## Hello,\nThis notebook aims to serve as a project to consolidate all the knowledge that I have acquired so far about data science.\nI am still a beginner in this area, however, I see the need to put what I learned into practice in order to learn new things.\n\n\nComments explaining the lines of code will be made in Portuguese (pt-br) which is my native language.\n\"\"\"\n# 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\n#importando as bibliotecas que sera utilizadas para a analise exploratoria do conjunto de dados.\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf = pd.read_csv('..\/input\/covid-world-vaccination-progress\/country_vaccinations.csv')\n\"\"\"\n# Data cleaning\n\"\"\"\n#o dataset se encontra dessa forma\ndf.head()\n#selecionando colunas que ser\u00e3o utilizadas na analise\ndf.columns\ndf = df[['country','date', 'daily_vaccinations', 'daily_vaccinations_per_million','vaccines' ]]\n#visualizando formato das variaveis no dataset\ndf.info()\n#transformando a variavel date para o formato de datas, as outras variaveis n\u00e3o precisaram ser transformadas\ndf.date = pd.to_datetime(df.date)\n#a coluna ['daily_vaccinations'] \u00e9 a que menos tem valores NaN, ent\u00e3o as linhas ser\u00e3o removidas de \n#acordo com essa coluna\nprint(df.info())\ndf.drop(df[df.daily_vaccinations.isna()==True].index, inplace=True)\n#tudo certo agora\ndf.info()\n\"\"\"\n# Countries with more vaccinations so far\n\"\"\"\n# os dados ser\u00e3o agrupados pelo pais e ser\u00e1 feita uma soma do numero de vacinas at\u00e9 o momento\ndf_country = df.groupby(['country']).daily_vaccinations.agg(sum)\ndf_country = pd.DataFrame(df_country)\ndf_country.rename(columns={'daily_vaccinations':'total_vaccinations'}, inplace=True)\ndf_country = df_country.sort_values(by='total_vaccinations', ascending=False)\ndf_country\n#plotagem com os vinte paises que mais vacinaram at\u00e9 o momento\nplt.figure(figsize=(14,8))\nplt.xticks(rotation=45)\nsns.barplot(data=df_country.head(20), x=df_country.index[:20], y='total_vaccinations')\nplt.title('Top 20 country vaccinations')\n#plotagem com 20 paises que menos vacinaram at\u00e9 agora\n#vale lembrar que o baixo numero de vaccina\u00e7\u00f5es pode n\u00e3o ser por conta de ineficiencia\n#tambem existe o fator que de infec\u00e7\u00e3o que pode ter sido baixo nesse pais\nplt.figure(figsize=(14,8))\nplt.xticks(rotation=45)\nsns.barplot(data=df_country.tail(20), x=df_country.index[-20:], y='total_vaccinations')\nplt.title('Top 20 country with less vaccinations')\n#aparentenmente na colombia n\u00e3o teve vaccina\u00e7\u00f5es de acordo com o grafico acima\n#numero de vacinados na colombia\ndf_country[df_country.index == 'Colombia']\n\"\"\"\n# Relative growth in the number of daily vaccines\n\"\"\"\n#preparando subdatasets pra fazer uma compara\u00e7\u00e3o da evolu\u00e7\u00e3o da vaccina\u00e7\u00e3o, entre o brasil e alguns\n#dos paises que mais vacinaram\ndf_bra = df[df.country == 'Brazil']\ndf_in = df[df.country == 'India']\ndf_chi = df[df.country == 'China']\ndf_is = df[df.country == 'Israel']\ndf_en = df[df.country == 'England']\n\n#plotagem da distribui\u00e7\u00e3o do numero de vacinas diarias por paises\nplt.figure(figsize=(14,8))\nsns.kdeplot(data=df_bra.daily_vaccinations, shade=True)\nsns.kdeplot(data=df_in.daily_vaccinations, shade=True)\nsns.kdeplot(data=df_chi.daily_vaccinations, shade=True)\nsns.kdeplot(data=df_is.daily_vaccinations, shade=True)\nsns.kdeplot(data=df_en.daily_vaccinations, shade=True)\nplt.legend(['Brazil', 'India','China','Israel','England'])\nplt.title('Distribution of the number of vaccines per day')\n#prepara\u00e7\u00e3o para cria\u00e7\u00e3o da variavel que registra o crescimento relativo do numero de vacinas\ndf_bra['relative'] = df_bra.daily_vaccinations \/ df_bra.daily_vaccinations.iloc[0]\ndf_in['relative'] = df_in.daily_vaccinations \/ df_in.daily_vaccinations.iloc[0]\ndf_chi['relative'] = df_chi.daily_vaccinations \/ df_chi.daily_vaccinations.iloc[0]\ndf_is['relative'] = df_is.daily_vaccinations \/ df_is.daily_vaccinations.iloc[0]\ndf_en['relative'] = df_en.daily_vaccinations \/ df_en.daily_vaccinations.iloc[0]\n#concatenando os subdatasets criados, menos o brasil\ndf_comparative = pd.concat([df_in,df_chi,df_is,df_en])\n#plotando o crescimento relativo de 4 paises em rela\u00e7\u00e3o ao brasil\nfigure, axes = plt.subplots(1, 2, figsize=(14,7), gridspec_kw={'wspace': 0.2})\nfigure.suptitle('Relative growth in the number of daily vaccines')\nsns.lineplot(data=df_comparative[['country','date','relative']],x='date',y='relative',hue=\"country\", ax=axes[0])\nplt.xticks(rotation=45)\nsns.lineplot(data=df_bra[['date','relative']],x='date', y='relative', ax=axes[1], color='purple')\nplt.legend(['Brasil'])\n\n\"\"\"\n# Most used vaccines in countries\n\"\"\"\n#criando dataset que mostra o nome das vacinas utilizadas sem duplicatas na coluna pais\ndf_vaccines = df[['country','vaccines']].copy()\ndf_vaccines.country = df_vaccines.country.drop_duplicates()\ndf_vaccines.dropna(inplace=True)\n#mostrando a quantidade que cada vaccina \u00e9 utilizada\ndf_vaccines.vaccines.value_counts()\n#preparando dataframe para plotagem do numero de vacinas\ndf_vac = pd.DataFrame(df_vaccines.vaccines.value_counts())\nplt.figure(figsize=(6,8))\nplt.ylabel('Vaccines')\nplt.xlabel('Count')\nplt.title('Most used vaccines')\nsns.barplot(data=df_vac, y=df_vac.index, x='vaccines', orient='h')","meta":"{'source': 'AI4Code', 'id': '2815f357ae736a'}"}
{"id":"112209","text":"\"\"\"\n## Importing Lib :\n\n\"\"\"\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nx = np.linspace(0, 5, 11)\ny = x ** 2\nx\ny\n\"\"\"\n## So we have two methods for plotting :\n\n### - Function method\n### - Object-oriented method\n\"\"\"\n\"\"\"\n### 1- Function method :\n### Similar as matlab :\n\"\"\"\nplt.plot(x, y)\n\n\"\"\"\n### - Subplot Functional method:\n\n\"\"\"\nplt.subplot(1, 2, 1) # 1 row , 2 cols , plot number you referring to (1)\nplt.plot(x, y, 'r') # plot in 1 x, y and color is red\n\nplt.subplot(1, 2, 2) # 1 row , 2 cols , plot number you referring to (2)\nplt.plot(y, x, 'b') # plot in 2 x, y and color is red\n\"\"\"\n## 2- Object-oriented method :\n\n\"\"\"\nfig = plt.figure() # create figure\n\naxes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # draw the plot 10% from the left , 10% from the bottom 80% from the width, 80% from the hieght\n\naxes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # draw the plot 20% from the left , 50% from the bottom 40% from the width, 30% from the hieght\naxes1.plot(x, y)\naxes2.plot(y, x)\n\n\"\"\"\n### - Subplot for OO method:\n\n\"\"\"\nfig, axes = plt.subplots(nrows= 1, ncols=2) # notice here we deal with the figure like a matrix\n\n\"\"\"\n### If want to draw in this subplot \"OO Method\"\n\"\"\"\nfig, axes = plt.subplots(figsize=(12,3)) #here we control the size of fig , 12 px in x axis, 3 px in y axis.\n\naxes.plot(x, y, 'r')\naxes.set_xlabel('x')\naxes.set_ylabel('y')\naxes.set_title('title');\n\n\"\"\"\n## - We can control the color and marker by matplot lib:\n\n\"\"\"\nfig = plt.figure() # create figure\nax = fig.add_axes([0, 0, 1, 1])\nax.plot(x, y, color='purple', lw=1, ls='-', marker='o', markersize=20) #lw  isline width, ls is line style, marker of the points and its size.\n\"\"\"\n# AND THANK U \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ce2b8ed9af4d76'}"}
{"id":"15512","text":"# 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)\nfrom sklearn.preprocessing import OrdinalEncoder\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\n#Input and test data\ndf_train = pd.read_csv(\"\/kaggle\/input\/titanic\/train.csv\")\ndf_test = pd.read_csv(\"\/kaggle\/input\/titanic\/test.csv\")\n#feature importance identification for continuous and categorical variables\n#using mutual_information and chi-square test and crammer's v\n\n\nfrom sklearn import feature_selection\nimport math\nfrom scipy import stats\nfrom collections import defaultdict\ndef feature_importance_classification(features, target, cont_cols, cat_cols, n_neighbors=3,\n                                      random_state=None):\n    '''chisquare test'''\n    cont = features[cont_cols]\n    disc = features[cat_cols]\n\n    cont_imp = pd.DataFrame(index=cont.columns)\n    disc_imp = pd.DataFrame(index=disc.columns)\n\n    # Continuous features\n    if cont_imp.index.size > 0:\n        # F-test\n        f_test = feature_selection.f_classif(cont, target)\n        cont_imp['f_statistic'] = f_test[0]\n        cont_imp['f_p_value'] = f_test[1]\n\n        # Mutual information\n        mut_inf = feature_selection.mutual_info_classif(cont, target, discrete_features=False,\n                                                        n_neighbors=n_neighbors,\n                                                        random_state=random_state)\n        cont_imp['mutual_information'] = mut_inf\n\n    # Discrete features\n    if disc_imp.index.size > 0:\n\n        # Chi\u00b2-test\n        chi2_tests = defaultdict(dict)\n\n        for feature in disc.columns:\n            #             if disc[feature].dtype != np.int32 and disc[feature].dtype != np.int64:\n            #                 disc[feature] = disc[feature].apply(lambda x: x.lower())\n            cont = pd.crosstab(disc[feature], target)\n            statistic, p_value, _, _ = stats.chi2_contingency(cont)\n            chi2_tests[feature]['chi2_statistic'] = statistic\n            chi2_tests[feature]['chi2_p_value'] = p_value\n\n        chi2_tests_df = pd.DataFrame.from_dict(chi2_tests, orient='index')\n        disc_imp['chi2_statistic'] = chi2_tests_df['chi2_statistic']\n        disc_imp['chi2_p_value'] = chi2_tests_df['chi2_p_value']\n\n        # Cram\u00e9r's V (corrected)\n        disc_imp['cramers_v'] = [\n            cramers_vcorrected_stat(pd.crosstab(feature, target).values)\n            for obj_first, feature in disc.iteritems()\n        ]\n\n    return cont_imp, disc_imp\n\ndef cramers_vcorrected_stat(confusion_matrix):\n    \"\"\"Calculate Cram\u00e9rs V statistic for categorial-categorial association.\n\n    Uses correction from Bergsma and Wicher, Journal of the Korean Statistical\n    Society 42 (2013): 323-328.\n    \"\"\"\n    chi2 = stats.chi2_contingency(confusion_matrix)[0]\n    number_of_rows = confusion_matrix.sum()\n    phi2 = chi2 \/ number_of_rows\n    row, key = confusion_matrix.shape\n    phi2_corr = max(0, phi2 - ((key - 1) * (row - 1)) \/ (number_of_rows - 1))\n    r_corr = row - ((row - 1) ** 2) \/ (number_of_rows - 1)\n    k_corr = key - ((key - 1) ** 2) \/ (number_of_rows - 1)\n    return math.sqrt(phi2_corr \/ min((r_corr - 1), (k_corr - 1)))\n#target variable set\ntarget = \"Survived\"\ntarget_arr = [\"Survived\"]\n\n#manually separating columns based on their data\ncat_cols = [\"Pclass\",\"Sex\",\"Embarked\",\"Cabin\"]\ncont_cols = [\"SibSp\",\"Parch\",\"Fare\",\"Age\"]\nprint(df_train[cat_cols+cont_cols+target_arr].shape)\ndf_final = df_train[cat_cols+cont_cols+target_arr]\ndf_final[cat_cols] = df_final[cat_cols].fillna(df_final[cat_cols].mode().iloc[0])\ndf_final[cont_cols] = df_final[cont_cols].fillna(df_final[cont_cols].mean())\nfeature_importance_classification(df_final,df_final[target],cont_cols,cat_cols)\n#After running the feature selection we will select the following\nfinal_cat = [\"Pclass\",\"Sex\",\"Cabin\"]\nfinal_cont = [\"Fare\"]\nfrom sklearn.naive_bayes import GaussianNB,CategoricalNB\ngc = GaussianNB()\ncont_classifier = gc.fit(df_final[cont_cols],df_final[target])\ncont_classifier.class_prior_\nCc = CategoricalNB()\noenc = OrdinalEncoder()\nout_df = pd.DataFrame(data=oenc.fit_transform(df_final[cat_cols]),columns=cat_cols)\nmod = Cc.fit(out_df,df_final[target])\nnp.exp(mod.class_log_prior_)\n\"\"\"\nwe can take prior probability of the classes from cont_classifier as cont_classifier.class_prior_ or from CategoricalNB as np.exp(mod.class_log_prior_)\n\"\"\"\nprint(df_test[cat_cols+cont_cols].shape)\n# test_final = df_test[cat_cols+cont_cols].dropna()\ndf_test[cat_cols] = df_test[cat_cols].fillna(df_test[cat_cols].mode().iloc[0])\ndf_test[cont_cols] = df_test[cont_cols].fillna(df_test[cont_cols].mean())\ntest_final = df_test[cat_cols+cont_cols]\nprint(test_final.shape)\ntest_out_df = oenc.fit_transform(test_final[cat_cols])\npred2 = cont_classifier.predict_log_proba(test_final[cont_cols])\npred1 = mod.predict_log_proba(test_out_df)\nn = len(cat_cols)+len(cont_cols)\n#jll - sum of log probability of continuous and categorical data\n\nlog_prior = mod.class_log_prior_\njlls = []\njlls.append(cont_classifier._joint_log_likelihood(test_final[cont_cols]))\njlls.append(mod._joint_log_likelihood(np.array(test_out_df.astype(int))))\n\njlls = np.hstack([jlls])\n\njlls = jlls - log_prior\njll = jlls.sum(axis=0) + log_prior\n#Standardising the results\nfo = np.exp(jll)\nsumso = np.sum(fo, axis = 1, keepdims = True) \nresult = fo\/sumso\n#Output calculation\ny_pred = np.argmax(result,axis=1)\nzz = zip(df_test[\"PassengerId\"],y_pred)\nout = [[a[0],a[1]] for a in zz]\nmy_submission = pd.DataFrame(out,columns=[\"PassengerId\",\"Survived\"])\nmy_submission.to_csv('submission_1.csv', index=False)\n\n# df_test[\"PassengerId\"].shape\n# y_pred.shape","meta":"{'source': 'AI4Code', 'id': '1c52cf69a718ff'}"}
{"id":"91130","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\ntrain = pd.read_csv('..\/input\/titanic\/train.csv')\ntest = pd.read_csv('..\/input\/titanic\/test.csv')\ntrain.head()\ntrain.dtypes\ntrain.describe()\ntrain.shape\n\"\"\"\n# Data Visualization\n\"\"\"\nsns.barplot(x='Pclass', y='Survived', data=train)\nplt.xlabel('Ticket Class')\nplt.ylabel('Survived')\nplt.show()\nsns.barplot(x='Sex', y='Survived', data=train)\nplt.xlabel('Sex')\nplt.ylabel('Survived')\nplt.show()\nsns.barplot(x='SibSp', y='Survived', data=train)\nplt.xlabel('Siblings or Spouses')\nplt.ylabel('Survived')\nplt.show()\nsns.barplot(x='Parch', y='Survived', data=train)\nplt.xlabel('Parent or Childerns')\nplt.ylabel('Survived')\nplt.show()\ncorr = train.corr()\n\nsns.heatmap(corr, \n        xticklabels=corr.columns,\n        yticklabels=corr.columns)\n\"\"\"\n# Data Cleaning\n\"\"\"\ndef checkNull(df):\n    total = df.isnull().sum()\n    percent = (total \/ df.isnull().count()) * 100\n    null_df = pd.concat([total, percent], keys=['Sum', 'Percent'], axis=1)\n    return null_df\ncheckNull(train)\ncheckNull(test)\ntrain['Embarked'].fillna(train['Embarked'].mode()[0], inplace=True)\ntrain['Cabin'].fillna(train['Cabin'].mode()[0], inplace=True)\ntrain['Age'].fillna(0, inplace=True)\ntrain['Title'] = train['Name'].str.split(\", \", expand=True)[1].str.split(\".\", expand=True)[0]\ntrain['Title'].unique()\ntest['Age'].fillna(0, inplace=True)\ntest['Cabin'].fillna(test['Cabin'].mode()[0], inplace=True)\ntest.dropna(inplace=True)\ntest['Title'] = train['Name'].str.split(\", \", expand=True)[1].str.split(\".\", expand=True)[0]\ntest['Title'].unique()\ncheckNull(train)\ncheckNull(test)\ndef changeTitle(df):\n    df['Title'] = df['Title'].replace(['Lady', 'Capt', 'Col',\n    'Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona'], 'Rare')\n    df['Title'] = df['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal')\n    df['Title'] = df['Title'].replace('Mlle', 'Miss')\n    df['Title'] = df['Title'].replace('Ms', 'Miss')\n    df['Title'] = df['Title'].replace('Mme', 'Mrs')\n    \n    title_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Royal\": 5, \"Rare\": 6}\n    df['Title'] = df['Title'].map(title_mapping)\n    df['Title'] = df['Title'].fillna(0)\n    df['Title'] = df['Title'].astype('int64')\nchangeTitle(train)\nchangeTitle(test)\nsex_mapping = {'male':1, 'female':2}\ntrain['Sex'] = train['Sex'].map(sex_mapping)\ntest['Sex'] = test['Sex'].map(sex_mapping)\nage_bins = [-1, 0, 3, 14, 18, 30, 80]\nage_labels = ['Unknown', 'Infant', 'Childern', 'Teenagers', 'Adult', 'Old']\ntrain['AgeGroup'] = pd.cut(train['Age'], age_bins, labels=age_labels)\ntest['AgeGroup'] = pd.cut(test['Age'], age_bins, labels=age_labels)\nage_mapping = {'Unknown': 0, 'Infant': 1, 'Childern': 2, 'Teenagers': 3, 'Adult': 4, 'Old': 5}\ntrain['AgeGroup'] = train['AgeGroup'].map(age_mapping)\ntest['AgeGroup'] = test['AgeGroup'].map(age_mapping)\nemb_mapping = {'S': 0, 'C': 1, 'Q': 2}\ntrain['Embarked'] = train['Embarked'].map(emb_mapping)\ntest['Embarked'] = test['Embarked'].map(emb_mapping)\ntrain['FareBand'] = pd.qcut(train['Fare'], 4, labels = [1, 2, 3, 4])\ntest['FareBand'] = pd.qcut(train['Fare'], 4, labels = [1, 2, 3, 4])\ntrain.drop(['Name', 'Age', 'Ticket', 'Fare', 'Cabin'], axis=1, inplace=True)\ntest.drop(['Name', 'Age', 'Ticket', 'Fare', 'Cabin'], axis=1, inplace=True)\ntrain.head()\ntest.head()\n\"\"\"\n# Prediction & Evaluation\n\"\"\"\nx = train.drop('Survived', axis=1)\ny = train['Survived']\n\"\"\"\n**1. KNN**\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)\n\nks = list(range(1,51))\nk = 0\nweight_options = [\"uniform\", \"distance\"]\nparam_grid = dict(n_neighbors = ks, weights = weight_options)\n\nknn = KNeighborsClassifier()\ngrid = GridSearchCV(knn, param_grid, cv = 10, scoring = 'accuracy')\ngrid.fit(x_train,y_train)\n\nknn = KNeighborsClassifier(grid.best_params_['n_neighbors'])\nknn.fit(x_train,y_train)\nyhat = knn.predict(x_test)\nkscore = knn.score(x_test, y_test)\nkscore\n\"\"\"\n**2. Gaussian Distribution**\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\n\ngaussian = GaussianNB()\ngaussian.fit(x_train,y_train)\nyhat = gaussian.predict(x_test)\ngscore = gaussian.score(x_test,y_test)\ngscore\n\"\"\"\n**3. Logistic Regression**\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression()\nlr.fit(x_train,y_train)\nyhat = lr.predict(x_test)\nlscore = lr.score(x_test, y_test)\nlscore\n\"\"\"\n**4. Random Forest Classifier**\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\nforest = RandomForestClassifier()\nforest.fit(x_train,y_train)\nyhat = forest.predict(x_test)\nfscore = forest.score(x_test, y_test)\nfscore\nmodels = pd.DataFrame({\n    'Model': ['KNN', 'Gaussian Distribution', 'Logistic Regression', 'Random Forest'],\n    'Score': [kscore, gscore, lscore, fscore]})\nmodels.sort_values(by='Score', ascending=False)\nyhat = forest.predict(test)\n\nsubmission = pd.DataFrame({ 'PassengerId' : test['PassengerId'], 'Survived': yhat })\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'a72d894835b801'}"}
{"id":"78503","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.metrics import plot_confusion_matrix, classification_report, f1_score\nfrom sklearn.model_selection import train_test_split ,GridSearchCV, cross_val_score\nfrom sklearn.preprocessing import StandardScaler\n\n#Classification Models:\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, VotingClassifier, StackingClassifier\nfrom xgboost import XGBClassifier\n\n#Supress Warnings:\nimport warnings\nwarnings.filterwarnings('ignore')\ntrain_df = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntest_df = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\ntrain_df = train_df.set_index(\"PassengerId\")\ntrain_df.head()\ntrain_df.info()\ntrain_df.shape\ntrain_df.isnull().sum()\/len(train_df)\ntrain_df.describe()\ntest_df.isnull().sum()\/len(test_df)\ntrain_df.dropna(subset=[\"Embarked\"], inplace=True)\ntrain_df.drop(columns=['Cabin'],inplace=True)\n\ntrain_df.info()\ntrain_df['Sex'].unique()\ntrain_df['Embarked'].unique()\ndf_all_corr = train_df.corr().abs().unstack().sort_values(kind=\"quicksort\", ascending=False).reset_index()\ndf_all_corr.rename(columns={\"level_0\": \"Feature 1\", \"level_1\": \"Feature 2\", 0: 'Correlation Coefficient'}, inplace=True)\ndf_all_corr[df_all_corr['Feature 1'] == 'Age']\nage_by_pclass_sex = train_df.groupby(['Sex', 'Pclass']).median()['Age']\n\nfor pclass in range(1, 4):\n    for sex in ['female', 'male']:\n        print('Median age of Pclass {} {}s: {}'.format(pclass, sex, age_by_pclass_sex[sex][pclass]))\nprint('Median age of all passengers: {}'.format(train_df['Age'].median()))\n\n# Filling the missing values in Age with the medians of Sex and Pclass groups\ntrain_df['Age'] = train_df.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))\n\"\"\"\n**DATA Visualization**\n\"\"\"\nplt.figure(figsize=(14,8))\nsns.countplot(x=\"Survived\", data=train_df,hue='Sex')\nplt.show()\ntrain_df[[\"Sex\", \"Survived\"]].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False)\nplt.figure(figsize=(14,8))\nsns.countplot(x=\"Survived\", data=train_df,hue='Pclass')\nplt.show()\ntrain_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().sort_values(by='Survived', ascending=False)\nplt.figure(figsize=(14,8))\nsns.countplot(x=\"Survived\", data=train_df,hue='Embarked')\nplt.show()\ntrain_df[[\"Embarked\", \"Survived\"]].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False)\ntitle_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}\nfor dataset in [train_df, test_df]:\n    # factorize Name column\n    dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\n    dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\n    dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')\n    dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')\n    dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')\n    dataset['Title'] = dataset['Title'].map(title_mapping)\n    dataset['Title'] = dataset['Title'].fillna(0)\n    # facotrize Sex column\n    dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)\n# extract number of family members\nfor dataset in [train_df, test_df]:\n    dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1\n\ntrain_df[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean().sort_values(by='Survived', ascending=False)\nfor dataset in [train_df, test_df]:\n    dataset['IsAlone'] = 0\n    dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1\n\ntrain_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean()\n# factorize values in Embarked column \nfreq_port = train_df.Embarked.dropna().mode()[0]\nfor dataset in [train_df, test_df]:\n    dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)\n    \ntrain_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False)\ntrain_df.columns\nfeatures = ['Pclass',  'Sex', 'Age', 'SibSp', 'Parch', \n       'Fare', 'Embarked', 'Title', 'FamilySize', 'IsAlone']\n# fill missing values in test df\nfare_median = test_df['Fare'].dropna().median()\ntest_df['Fare'].fillna(fare_median, inplace=True)\ntest_df['Age'] = test_df.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))\ntest_df.info()\nX = train_df[features]\ny = train_df['Survived']\n\n#Split training data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X,y,test_size = 0.2,stratify = y,random_state=42)\n\nX_train.info()\n# knn - k-nearest neighbours\nfrom sklearn.neighbors import KNeighborsClassifier\nmodel = KNeighborsClassifier(n_neighbors=3)\nmodel.fit(X_train, y_train)\n# print metric to get performance\nprint(\"Accuracy: \",model.score(X_val, y_val) * 100)\ny_pred = model.predict(X_val)\nf1 = f1_score(y_val, y_pred, average='micro')\nprint(\"f1_score: \",f1)\nprint(\"  Validation set Classification Report:\")\nprint(classification_report(y_val, y_pred, digits=4))\nfig, ax = plt.subplots(1, 2, figsize = (15, 5))\nax[0].set_title(\"Training Set Confusion Matrix\")\nplot_confusion_matrix(model, X_train, y_train, ax=ax[0], \n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\n\nax[1].set_title(\"Validation Set Confusion Matrix\")\nplot_confusion_matrix(model, X_val, y_val, ax=ax[1],\n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\nplt.show()\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nclf = BaggingClassifier(\n    DecisionTreeClassifier(), n_estimators=500,\n    max_samples=100, bootstrap=True, random_state=42)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_val)\nfrom sklearn.metrics import accuracy_score\nprint(\"Accuracy: \",accuracy_score(y_val, y_pred)*100)\nf1 = f1_score(y_val, y_pred, average='micro')\nprint(\"f1_score: \",f1)\nprint(\"  Validation set Classification Report:\")\nprint(classification_report(y_val, y_pred, digits=4))\nfig, ax = plt.subplots(1, 2, figsize = (15, 5))\nax[0].set_title(\"Training Set Confusion Matrix\")\nplot_confusion_matrix(clf, X_train, y_train, ax=ax[0], \n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\n\nax[1].set_title(\"Validation Set Confusion Matrix\")\nplot_confusion_matrix(clf, X_val, y_val, ax=ax[1],\n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\nplt.show()\nfrom sklearn.ensemble import RandomForestClassifier\n\nclf = RandomForestClassifier(n_estimators=100,\n                               criterion=\"entropy\",\n                               max_depth=6,\n                               min_samples_split=4,\n                               bootstrap=True,\n                               max_samples=0.8,\n                               oob_score=True,\n                               n_jobs=-1,\n                               random_state=0)\n\nclf.fit(X_train, y_train)\nscores=cross_val_score(clf, X, y, cv=5)\nprint(\"Cross Validation:\\n  %0.5f accuracy with a standard deviation of %0.5f \\n\" % (scores.mean(), scores.std()))# print metric to get performance\nprint(\"Accuracy: \",clf.score(X_val, y_val) * 100)\ny_pred = clf.predict(X_val)\nf1 = f1_score(y_val, y_pred, average='micro')\nprint(\"f1_score: \",f1)\nprint(\"  Validation set Classification Report:\")\nprint(classification_report(y_val, y_pred, digits=4))\nfig, ax = plt.subplots(1, 2, figsize = (15, 5))\nax[0].set_title(\"Training Set Confusion Matrix\")\nplot_confusion_matrix(clf, X_train, y_train, ax=ax[0], \n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\n\nax[1].set_title(\"Validation Set Confusion Matrix\")\nplot_confusion_matrix(clf, X_val, y_val, ax=ax[1],\n                      cmap=\"YlGnBu\", xticks_rotation=\"vertical\")\nplt.show()\ntest_df.head()\ntest_df.info()\npredictions = clf.predict(test_df[features])\noutput = pd.DataFrame({'PassengerId': test_df.PassengerId, 'Survived': predictions})\noutput.to_csv('my_submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","meta":"{'source': 'AI4Code', 'id': '904cdbcda1ea34'}"}
{"id":"27034","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom time import time\nimport pickle\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\ndf = pd.read_csv('\/kaggle\/input\/scl-2021-ds\/train.csv')\npoi_street_df = df[\"POI\/street\"].str.split(\"\/\", n = 1, expand = True) \ndf[\"POI\"]= poi_street_df[0] \ndf[\"street\"]= poi_street_df[1] \ndf1 = df.drop([\"POI\/street\"], axis=1) \ndf1\n\"\"\"\n## Data Cleaning\n\n### 1. Let's fix discrepancies between `street` and `raw_address` labels.\n\"\"\"\ndef find_first_index(ra_split, st_split):\n    \n    if len(st_split) <= len(ra_split): # new\n    \n        num_iter = len(ra_split) - len(st_split) + 1\n        overlap_list = []\n\n        for i in range(num_iter):\n            window = ra_split[i: i+len(st_split)]\n            overlap = list(set(window) & set(st_split))\n            overlap_list.append(len(overlap))\n\n        max_overlap = [e for e in range(len(overlap_list)) if overlap_list[e] == max(overlap_list)]\n        if len(max_overlap) == 1:\n            return max_overlap[0]\n\n        else:\n            count_list = []\n            for idx in max_overlap:\n                subset_ra = ra_split[idx: idx+len(st_split)]\n                count = 0\n                for e in range(len(subset_ra)):\n                    if subset_ra[e] not in st_split[e]:\n                        count += 0\n                    else:\n                        count += 1\n                count_list.append(count)\n            index = count_list.index(max(count_list))\n            return max_overlap[index]\n    else:\n        return 0\ndef fix_street_errors(row):\n    \n    raw_add = row['raw_address']\n\n    # If a street name is extracted...\n    if row['street'] != \"\":\n\n        raw_add_split = word_tokenize(raw_add)\n        \n        extr_street = row['street']\n        extr_street_split = word_tokenize(extr_street)\n        \n        # If the extracted street is in the raw address as an entire string, good!\n        if extr_street in raw_add:\n            return raw_add\n        \n        # This is where there are discrepancies!\n        else:\n            index_in_ra = find_first_index(raw_add_split, extr_street_split)\n            raw_add_split[index_in_ra: index_in_ra+len(extr_street_split)] = extr_street_split\n            updated_raw_add = ' '.join(raw_add_split).replace(' ,', ',').replace(' .', '.').replace(' )', ')').replace(' (', '(').replace(' ?', '?')          \n            return updated_raw_add\n      \n    # If a street name is originally an empty string, we just assume there's no error. \n    else:\n        return raw_add\nstart = time()\n\ndf1['cleaned_raw_add'] = df1.apply(fix_street_errors, axis=1)\n\nprint(\"Executed in {} minutes.\".format(round((time() - start)\/60, 3)))\n\n# Sanity checks\ndf1.loc[[69, 86, 117, 130, 135, 169], :]\n\"\"\"\n### 2. We also build a dictionary mapping the incorrect\/incomplete street names in `raw_address` to the correct `street` labels. \n\"\"\"\ndef get_street_mapping_dict(row):\n    \n    raw_add = row['raw_address']\n\n    # If a street name is extracted...\n    if row['street'] != \"\":\n\n        raw_add_split = word_tokenize(raw_add)\n        \n        extr_street = row['street']\n        extr_street_split = word_tokenize(extr_street)\n        \n        # If the extracted street is in the raw address as an entire string, good!\n        if extr_street in raw_add:\n            return None\n        \n        # This is where there are discrepancies!\n        else:\n            index_in_ra = find_first_index(raw_add_split, extr_street_split)\n            before = raw_add_split[index_in_ra: index_in_ra+len(extr_street_split)] \n            before = ' '.join(before)\n            return before, extr_street\n      \n    # If a street name is originally an empty string, we just assume there's no error. \n    else:\n        return None\nstart = time()\n\ndf1['street_mapping'] = df1.apply(get_street_mapping_dict, axis=1)\n\nprint(\"Executed in {} minutes.\".format(round((time() - start)\/60, 3)))\n\n# Sanity checks\ndf1.loc[[69, 86, 117, 130, 135, 169], :]\n# Create a separate dataframe containing only values in `street_mapping` columns, i.e., rows where changes occurred\ndf_with_street_mappings = df1[df1['street_mapping'].notnull()]\n\nstreet_mapping_dict = dict()\n\n# Create a mapping dictionary, where key is the truncated word\/words and the value is the corresponding correct word\/words\nfor row, col in df_with_street_mappings.iterrows():\n    street_mapping_dict[col['street_mapping'][0]] = col['street_mapping'][1]\n    \n# How many street errors are there altogether?\nprint(\"Length of street mapping dictionary:\", len(street_mapping_dict))\n\"\"\"\n### 3. Next, let's rectify discrepancies between `POI` and `raw_address` labels.\n\"\"\"\ndef fix_poi_errors(row):\n    \n    raw_add = row['cleaned_raw_add']\n\n    # If a POI name is extracted...\n    if row['POI'] != \"\":\n\n        raw_add_split = word_tokenize(raw_add)\n        \n        extr_poi = row['POI']\n        extr_poi_split = word_tokenize(extr_poi)\n        \n        # If the extracted POI is in the raw address as an entire string, good!\n        if extr_poi in raw_add:\n            return raw_add\n        \n        # This is where there are discrepancies!\n        else:\n            index_in_ra = find_first_index(raw_add_split, extr_poi_split)\n            raw_add_split[index_in_ra: index_in_ra+len(extr_poi_split)] = extr_poi_split\n            updated_raw_add = ' '.join(raw_add_split).replace(' ,', ',').replace(' .', '.').replace(' )', ')').replace(' (', '(').replace(' ?', '?')          \n            return updated_raw_add\n      \n    # If a POI name is originally an empty string, we just assume there's no error. \n    else:\n        return raw_add\nstart = time()\n\ndf1['cleaned_raw_add_1'] = df1.apply(fix_poi_errors, axis=1)\n\nprint(\"Executed in {} minutes.\".format(round((time() - start)\/60, 3)))\n\n# Sanity checks\ndf1.loc[[10, 11, 40, 110, 152, 157, 169], :]\n\"\"\"\n### 4. Likewise, we also build a dictionary mapping the incorrect\/incomplete POI names in `raw_address` to the correct `POI` labels. \n\"\"\"\ndef get_poi_mapping_dict(row):\n    \n    raw_add = row['cleaned_raw_add']\n\n    # If a POI name is extracted...\n    if row['POI'] != \"\":\n\n        raw_add_split = word_tokenize(raw_add)\n        \n        extr_poi = row['POI']\n        extr_poi_split = word_tokenize(extr_poi)\n        \n        # If the extracted POI is in the raw address as an entire string, good!\n        if extr_poi in raw_add:\n            return None\n        \n        # This is where there are discrepancies!\n        else:\n            index_in_ra = find_first_index(raw_add_split, extr_poi_split)\n            before = raw_add_split[index_in_ra: index_in_ra+len(extr_poi_split)] \n            before = ' '.join(before)\n            return before, extr_poi\n      \n    # If a POI name is originally an empty string, we just assume there's no error. \n    else:\n        return None\nstart = time()\n\ndf1['poi_mapping'] = df1.apply(get_poi_mapping_dict, axis=1)\n\nprint(\"Executed in {} minutes.\".format(round((time() - start)\/60, 3)))\n\n# Sanity checks\ndf1.loc[[10, 11, 40, 110, 152, 157, 169], :]\n# Create a separate dataframe containing only values in `poi_mapping` columns, i.e., rows where changes occurred\ndf_with_poi_mappings = df1[df1['poi_mapping'].notnull()]\n\npoi_mapping_dict = dict()\n\n# Create a mapping dictionary, where key is the truncated word\/words and the value is the corresponding correct word\/words\nfor row, col in df_with_poi_mappings.iterrows():\n    poi_mapping_dict[col['poi_mapping'][0]] = col['poi_mapping'][1]\n    \n# How many POI errors are there altogether?\nprint(\"Length of POI mapping dictionary:\", len(poi_mapping_dict))\n\"\"\"\n### 5. We've cleaned the raw address to make sure that it tallies with both the extracted `street` and `POI` labels. Now, let's tidy things up. \n\"\"\"\n# Select required columns\ncleaned_df = df1[['id','cleaned_raw_add_1', 'POI', 'street']]\n\n# Rename columns\ncleaned_df.columns = ['id', 'raw_address', 'POI', 'street']\n\n# Sanity checks\ncleaned_df.loc[[10, 11, 40, 69, 86, 110, 117, 130, 135, 152, 157, 169], :]\n\"\"\"\n### 6. Now that we have the two mapping dictionaries, let's check whether some of those truncated words exist in the test data, and if so, replace them with the correct labels. \n\"\"\"\n# Load test dataset\ntest_df = pd.read_csv('\/kaggle\/input\/scl-2021-ds\/test.csv')\n\n# Preview\ntest_df.head()\n\"\"\"\nIt might be risky to replace single words like `par` in the test data as they may form part of a bigger word that is different from the intended word. For example, we should not replace \"par\" in the address \"daya paru 43\" with its value in the `street_mapping_dict`, \"parigi\". This is less likely the case if there are two or more words.\n\nLet's try to filter out single words from the list.\n\"\"\"\nnew_street_mapping_dict = {k: v for k, v in street_mapping_dict.items() if len(k.split()) > 1}\nnew_poi_mapping_dict = {k: v for k, v in poi_mapping_dict.items() if len(k.split()) > 1}\n\nprint(\"Length of street mapping dictionary after removing single words:\", len(new_street_mapping_dict))\nprint(\"Length of POI mapping dictionary after removing single words:\", len(new_poi_mapping_dict))\nstart = time()\n\n# Replace truncated words in raw_address of test set with correct street labels\ncount1 = 0\nfor row, col in test_df.iterrows():\n    for k, v in new_street_mapping_dict.items():\n        if k in col['raw_address']:\n            test_df.loc[row, 'raw_address'] = test_df.loc[row, 'raw_address'].replace(k, v)\n            count1 += 1\n            \nprint(\"Number of raw addresses updated due to errors in street labels:\", count1)\n\n# Replace truncated words in raw_address of test set with correct POI labels\ncount2 = 0\nfor row, col in test_df.iterrows():\n    for k, v in new_poi_mapping_dict.items():\n        if k in col['raw_address']:\n            test_df.loc[row, 'raw_address'] = test_df.loc[row, 'raw_address'].replace(k, v)\n            count2 += 1\n\nprint(\"Number of raw addresses updated due to errors in POI labels:\", count2)\n\nprint(\"Executed in {} minutes.\".format(round((time() - start)\/60, 3)))\n\ntest_df\n# 0\n# s. par 53 sidanegara 4 cilacap tengah to be replaced with s. par\n# Updated:  s. parman 53 sidanegara 4 cilacap tengah\n# 1\n# angg per, baloi indah kel. lubuk baja to be replaced with angg per\n# Updated:  anggrek per, baloi indah kel. lubuk baja\n# 2\n# asma laun, mand imog, to be replaced with , man\n# Updated:  asma laun, mangund imog,\n# 3\n# ud agung rej, raya nga sri wedari karanganyar to be replaced with raya nga\n# Updated:  ud agung rej, raya ngawi- sri wedari karanganyar\n# 5\n# pem dos dapur ala perum gar no a 12 suka jaya sukarami to be replaced with perum gar\n# Updated:  pem dos dapur ala perumahan gar no a 12 suka jaya sukarami\n# 9\n# raya won wonotunggal wonotunggal to be replaced with raya won\n# Updated:  raya wonoso wonotunggal wonotunggal\n# 10\n# tebet timur tebet raya 92 rt 2 1 tebet to be replaced with bet raya\n# Updated:  tebet timur tebetung raya 92 rt 2 1 tebet\n# 14\n# toko teddy raya pan jakat, to be replaced with raya pan\n# Updated:  toko teddy raya pandan jakat,\n# 14\n# toko teddy raya pan jakat, to be replaced with raya pan jakat\n# Updated:  toko teddy raya pandan jakat,\n# 36\n# m. t. haryono, no 11 bank neg indonesia kali rejo ungaran timur to be replaced with bank negara indonesia\n# Updated:  m. t. haryono, no 11 bank negara indonesiaesia kali rejo ungaran timur\n# 36\n# m. t. haryono, no 11 bank neg indonesia kali rejo ungaran timur to be replaced with bank negara indonesia\n# Updated:  m. t. haryono, no 11 bank negara indonesiaesia kali rejo ungaran timur\n# 47\n# rezi, pasar raya to be replaced with pasar campor\n# Updated:  rezi, pasar campor\n# 52\n# mas nurul huda badang ngoro to be replaced with masjid nurul huda\n# Updated:  masjid nurul huda badang ngoro\n# 86\n# kateguhan roti bakar bandung pak budi, jenderal sudirman, to be replaced with roti bakar bandung\n# Updated:  kateguhan roti bakar bandungung pak budi, jenderal sudirman,\n# 92\n# kenc utama ii kembangan selatan 7 kembangan to be replaced with kencana utama\n# Updated:  kencana utama ii kembangan selatan 7 kembangan\n\"\"\"\n### 7. Save the cleaned-up train and test datasets, as well as the two mapping dictionaries.\n\"\"\"\n# Save the cleaned train dataset\ncleaned_df.to_csv('cleaned_train.csv', index=False)\n\n# Save the cleaned test dataset\ntest_df.to_csv('cleaned_test.csv', index=False)\n# Save the dictionaries\ns_file = open(\"street_mapping_dict.pkl\", \"wb\")\npickle.dump(street_mapping_dict, s_file)\ns_file.close()\n\np_file = open(\"poi_mapping_dict.pkl\", \"wb\")\npickle.dump(street_mapping_dict, p_file)\np_file.close()\n\"\"\"\n### Note: Run the following codes to load the two dictionaries\n\"\"\"\n# s_file = open(\"street_mapping_dict.pkl\", \"rb\")\n# street_mapping_dict = pickle.load(s_file)\n# print(street_mapping_dict)\n\n# p_file = open(\"poi_mapping_dict.pkl\", \"rb\")\n# poi_mapping_dict = pickle.load(p_file)\n# print(poi_mapping_dict)","meta":"{'source': 'AI4Code', 'id': '31bf4289a2be3c'}"}
{"id":"81493","text":"\"\"\"\n<a id=\"top\"><\/a>\n<div class=\"list-group\" id=\"list-tab\" role=\"tablist\">\n<h3 class=\"list-group-item list-group-item-action active\" data-toggle=\"list\" role=\"tab\" aria-controls=\"home\">Table of Content<\/h3>\n\n- [1. Reading the Data](#1)\n- [2. EDA: Exploring Insights](#2)\n    - [2.1 An Overview from the Data](#2.1)\n    - [2.2 Demographic Analysis](#2.2)\n    - [2.3 Financial Profile](#2.3)\n- [3. Prep: Building Pipelines](#3) \n    - [3.1 Initial Pipeline](#3.1)\n        - [3.1.1 Candidate Features](#3.1.1)\n        - [3.1.2 Duplicated Data](#3.1.2)\n        - [3.1.3 Target Definition](#3.1.3)\n        - [3.1.4 Training and Testing Data](#3.1.4)\n    - [3.2 Numerical Pipeline](#3.2)\n        - [3.2.1 Null Data](#3.2.1)\n        - [3.2.2 Log Transformation](#3.2.2)\n        - [3.3.3 Normalization](#3.2.3)\n    - [3.3 Categorical Pipeline](#3.3)\n        - [3.3.1 Dummies Encoding](#3.3.1)\n    - [3.4 Complete Pipelines](#3.4)\n- [4. Modelling: Predicting Churn](#4)\n    - [4.1 Structuring Variables](#4.1)\n    - [4.2 Training Models](#4.2)\n    - [4.3 Evaluating Models](#4.3)\n\"\"\"\n\"\"\"\nThis notebook aims to allocate the development referring to exploratory analysis of insights related to the [Credit Card Customers](https:\/\/www.kaggle.com\/sakshigoyal7\/credit-card-customers) dataset taken from the Kaggle platform to improve skills in Data Science and Machine Learning.\n\n___\n**_Description and context:_**\n_A bank manager is in a scenario where several customers are leaving their credit card services. It would be extremely interesting for the company to be able to predict the customers most likely to leave such services so that, in this way, the bank can act preventively in order to offer better services in favor of maintaining the customer._\n\n_[...]\nThe data set has 10,000 customers with attributes such as age, salary, marital status, credit limit, card category, among others. There are approximately 18 features in the whole set and there are only 16.0% of customers with churn_\n___\n\"\"\"\n!pip install pycomp --upgrade --no-cache-dir\n# Importing libraries\nimport pandas as pd\nimport os\nfrom pycomp.viz.insights import *\n\npd.options.display.max_columns = 500\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n\n# Project variables\nDATA_PATH = '..\/input\/credit-card-customers\/'\nFILENAME = 'BankChurners.csv'\n\"\"\"\n<a id=\"1\"><\/a>\n<font color=\"darkslateblue\" size=+2.5><b>1. Reading the Data<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAfter a formal definition of the project context, the alignment of the objectives of this work and, finally, the definition of the project variables, it is possible to start the investigations by reading the database available for analysis.\n\nIn this first contact, it is expected to understand a little more about the available content and the possibilities of analysis within the defined context. It is at this point that the data analyst\/scientist takes the first impressions of the data and sets a macro direction for the project while looking for relevant insights to the business problem.\n\"\"\"\n# Reading data\ndf = pd.read_csv(os.path.join(DATA_PATH, FILENAME))\nprint(f'Shape of the data: {df.shape}')\ndf.head()\n\"\"\"\nLooking at the [metadadata](https:\/\/www.kaggle.com\/sakshigoyal7\/credit-card-customers) of the dataset available in Kaggle, it is possible to detail each of the 23 columns in the database as:\n\n- **_CLIENTNUM_** unique identifier of the customer cartonista;\n- **_Attrition_Flag_** internal event related to customer activity;\n- **_Customer_Age_** age of the customer (in years);\n- **_Gender_** gender of the client (M = Male, F = Female);\n- **_Dependent_count_** number of customer dependents;\n- **_Education_Level_** customer's school level;\n- **_Marital_Status_** marital status of the client;\n- **_Income_Category_** category related to the client's annual salary;\n- **_Card_Category_** credit card category (Blue, Silver, Gold or Platinum);\n- **_Months_on_book_** period of relationship with the bank (in months)\n\n___\n\n_The other attributes present in the database do not have detailed descriptions on the metadata page. However, in an intuitive way, it is possible to extract some meaning from these from the name of the registered columns_\n___\n\n- **_Total_Relationship_Count:_** indicator of the customer's general relationship with the bank;\n- **_Months_Inactive_12_mon:_** number of months of customer inactivity considering the last 12 months;\n- **_Contacts_Count_12_mon:_** number of contacts registered by the customer considering the last 12 months;\n- **_Credit_Limit:_** customer's credit limit;\n- **_Total_Revolving_Bal:_**\n- **_Avg_Open_To_Buy:_** indicator of purchase willingness by the customer (opening of offer);\n- **_Total_Amt_Chng_Q4_Q1:_** probably indicates the value migrated between Q4 and Q1 for a full annual period;\n- **_Total_Trans_Amt:_** total traded by the customer;\n- **_Total_Trans_Ct:_** total traded by the customer on the card;\n- **_Total_Ct_Chng_Q4_Q1:_** probably indicates the amount migrated from card transactions between Q4 and Q1 for a full annual period;\n- **_Avg_Utilization_Ratio:_** indicator of average customer usage of the card;\n\n___\n_The last two attributes present in the database indicate, in some way, the results of classification processes and the construction of scores for customers_\n___\n\"\"\"\n\"\"\"\n<a id=\"2\"><\/a>\n<font color=\"darkslateblue\" size=+2.5><b>2. EDA: Exploring Insights<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAt this point, there is a well-defined context of the project's objective, in addition to a database already read and transformed into a DataFrame format of the pandas. From this moment on, a true scan of the data will be proposed for the application of a detailed descriptive analysis in order to gather relevant insights for the business context.\n\nUsing the homemade package [pycomp](https:\/\/github.com\/ThiagoPanini\/pycomp), whose construction was motivated exactly to facilitate the work of data scientists in the pillars of insights, prep and modeling, for this second session is expected a full understanding of the set of available data and a clear idea of the steps required to be applied in the prep and in the modeling.\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/WcAaq1P.png\" alt=\"pycomp Logo\">\n\"\"\"\n\"\"\"\n<a id=\"2.1\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>2.1 An Overview from the Data<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nThe first proposed analysis is based on the extraction of metadata from the available database itself. Performing this work is extremely important to have a clear idea about the attributes contained in the data set and the existing possibilities given the characteristics of the features.\n\"\"\"\n# Returning an overview from the data\ndf_overview = data_overview(df=df)\ndf_overview\n\"\"\"\nThe `data_overview()` function, extracted from the [pycomp](https:\/\/github.com\/ThiagoPanini\/pycomp) package returns an overview of a given database, informing the user of important factors, such as the quantity of null records, the primitive type and the number of categorical entries for each column. Observing the result generated for the database in question, it is possible to state:\n\n- There are no null records for the database available;\n- Of the 23 columns available, 6 are categorical and 17 are numeric;\n- The categorical column with the most registered entries is **_Education_Level_** with 7 different entries;\n\"\"\"\n\"\"\"\n<a id=\"2.2\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>2.1 Demographic Analysis<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nIn this first exploratory analysis session, demographic variables present in the database, such as age, gender, dependents, education, among others, will be discussed. The objective is to understand the public of this banking institution a little better and to cross these factors with other key variables that can better define possible customer migrations.\n\"\"\"\n\"\"\"\n___\n**_Customer analysis by age and gender_**\n___\n\"\"\"\n# Customers age distribution\nplot_distplot(df=df, col='Customer_Age', hist=True, title='Age distribution of the customers on the data')\n\"\"\"\nThe graph above shows an expected normal distribution for the age variable and, therefore, it is noticed that the database does not have any \"bias\" linked to this factor for the analysis clients present in the dataset. Now let's look at the age distribution by other demographic factors:\n\"\"\"\n# Public by gender\nplot_donut_chart(df=df, col='Gender', colors=['lightcoral', 'lightskyblue'],\n                 title='Total customers by gender')\n# Age by gender\nplot_distplot(df=df, col='Customer_Age', hue='Gender', kind='kde', color_list=['lightcoral', 'lightskyblue'],\n              title='Age distribution of the customers by its gender')\n\"\"\"\nThe distribution charts above allow to extract some important information related to the demographic attributes of the customers present in the database:\n\n1. The public of analysis is mainly formatted by customers between 45 and 55 years old;\n2. There is a good balance of clients by gender: 53% are women and 47% are men, with no distinction between these two groups in relation to age (strictly similar distribution curves);\n\"\"\"\n\"\"\"\n___\n**_Analysis of the public by family dependents_**\n___\n\"\"\"\n# Dependents\nplot_pie_chart(df=df, col='Dependent_count', explode=(0.02, 0.02, 0, 0, 0, 0),\n               title='Customer analysis by its dependents')\n# Age by dependents\nplot_distplot(df=df, col='Customer_Age', hue='Dependent_count', kind='boxen', palette='plasma',\n              title=\"Customer's age distribution by dependents count\")\n\"\"\"\nIn general, the analysis of the public in relation to family dependents is possible to state:\n\n1. Most customers have 1, 2 or 3 dependents;\n3. It is possible to notice that customers with a high number of dependents usually establish themselves in more restricted age groups (between 35 and 55 years old), while customers with a low number of dependents (none, 1 or 2) have a greater spread and spread in relation to age;\n\"\"\"\n\"\"\"\n___\n**_Analysis of the public by marital status and education level_**\n___\n\"\"\"\n# Marital status\nplot_donut_chart(df=df, col='Marital_Status', title=\"Total customers by marital status\")\n# Dependents and marital status\nplot_countplot(df=df, col='Dependent_count', hue='Marital_Status', figsize=(17, 8),\n               title=\"Customer analysis by marital status and dependents count\")\n\"\"\"\nProbably an interesting analysis for the financial institution is related to a joint study between the marital status and the number of dependents of each client. We know that different decisions can be made taking into account the marital situation and the \"family size\" of each client. The bar graph above shows:\n\n1. The base is formed, in its majority, by married clients and, therefore, in spite of being majority in the whole analysis by registered dependents, single clients without dependents surpass married clients without dependents.\n2. The financial institution may, in some way, further analyze single customers who have a large number of dependents (green bars). This audience may have specific needs and specific spending behaviors.\n\"\"\"\n# Education\nplot_countplot(df=df, col='Education_Level', order=True, palette='Blues_r',\n               title='Total customers by education level')\n\"\"\"\nThe graph above is important to have a better understanding of the audience present at the base in relation to the level of education of customers.\n\"\"\"\n\"\"\"\n___\n**_Analysis by income category_**\n___\n\"\"\"\n# Income category\nplot_countplot(df=df, col='Income_Category', order=False, palette='cividis',\n               title='Total customers by salary range (income category in annual earnings $)')\n# Salary range by age\nplot_distplot(df=df, col='Customer_Age', hue='Income_Category', kind='box', order=True, palette='cividis',\n              title='Age distribution by income category')\n\"\"\"\nThe above graphs allow us to infer that:\n\n1. The vast majority of this institution's clients fall into the portion with annual earnings of less than $40K;\n2. There is a subtle relationship between age and salary range, indicating that customers with high annual earnings are usually part of an older audience.\n\"\"\"\n\"\"\"\n<a id=\"2.3\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>2.3 Financial Profile<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAfter a brief analysis of the base's public through customer demographic variables, it is possible to continue the study using variables that, in some way, characterize the public from the financial consumption and \/ or use of the bank's resources.\n\nFrom this point, it will be possible to understand a little better the target of analysis of the project as a whole.\n\"\"\"\n\"\"\"\n___\n**_Attrited Customers_**\n___\n\"\"\"\n# Attrition flag\nplot_pie_chart(df=df, col='Attrition_Flag', explode=(0, 0.03),\n               title='How many customers have some attrition with the bank?')\n\"\"\"\nThe graph above reveals that approximately 16% of the customers present at the base have some type of friction with the financial institution. This is an important slice of analysis, given that it basically represents the target audience of customers who, in some way, are not comfortable with the services offered by this financial institution.\n\nAccording to the metadata, this column describes exactly the customers who left the bank (churn) and thus represents the target for much of the subsequent analysis. Before diving deeper into this slice, let's look at some other important categories for a better understanding of the audience.\n\"\"\"\n\"\"\"\n___\n**_Credit Card Category_**\n___\n\"\"\"\n# Card category\nplot_countplot(df=df, col='Card_Category', palette=['darkslateblue', 'silver', 'gold', 'cadetblue'],\n               order=True, title='Total customers by card category')\nplot_distplot(df=df, col='Months_on_book', hue='Card_Category', kind='box', \n              palette=['darkslateblue', 'gold', 'silver', 'cadetblue'],\n              title='Relationship time by card category')\n# Age by card category\nplot_aggregation(df=df, group_col='Card_Category', value_col='Credit_Limit', aggreg='mean',\n                 palette=['cadetblue', 'gold', 'silver', 'darkslateblue'],\n                 title=\"Average customer age by card category\")\n\"\"\"\nThe charts above show important factors related to how customers can be categorized in terms of consumption variables at this financial institution. At first, it is possible to state that:\n\n1. 93% of base customers have a \"Blue\" card, followed by 5.5% of customers with a Silver card, 1.1% in the Gold category and only 0.2% from the Platinum category;\n2. Regarding customer relationship time, it is possible to perceive a slight positive correlation between \"card level\" and \"long relationship time\" with the bank.\n3. Analyzing the pre-approved limit of customers by type of card, it is noticed that the \"level\" of the card is directly proportional to the average pre-approved limit, following the order Platinum, Gold, Silver and Blue;\n\"\"\"\n\"\"\"\n___\n**_Correlation matrix_**\n___\n\"\"\"\n\"\"\"\nAfter an initial approach to important variables that describe the profile of the financial institution's customers, it is possible to analyze the numerical attributes at once in terms of correlation. This approach is important to give an overview, in a single view, of how the variables are correlated with each other and with a target variable (`Attrition_flag`)\n\"\"\"\n# Correlation matrix\ntmp = df.copy()\ntmp['churned'] = tmp['Attrition_Flag'].map({'Existing Customer': 1, 'Attrited Customer': 0})\nclf_drop_cols = ['Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_1',\n                 'Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_2']\nplot_corr_matrix(df=tmp.drop(clf_drop_cols, axis=1), corr_col='churned', figsize=(13, 13))\n\"\"\"\nFrom the correlation matrix above, it is possible to analyze the main factors that possibly influence the _churn_ of clients of this financial institution. The function `plot_corr_matrix ()` of the module `pycomp` analyzes the correlation (default =` Pearson`) of the numeric variables with a target variable (argument `corr_col`) and also between them, thus allowing a detailed analysis of the main correlated variables . Thus, it is possible to quote:\n\n1. The variables `Total_Trans_Ct`,` Total_Ct_Chng_Q4_Q1` and `Total_Revolving_Bal` are the top 3 features that most directly and positively influence the _churn_ of customers. In other words, the higher the value of these 3 variables mentioned, the higher the _churn_ rate of these customers.\n2. In the other analysis spectrum, the `Contacts_Count_12_mon` and` Months_Inactive_12_mon` variables are the 2 main features that have a negative correlation with the churn target variable. This means that the lower the value of these 2 mentioned variables, the higher the _churn_ rate of the public.\n3. Analyzing the correlations of the variables with each other, it is possible to mention:\n    * The variables `Total_Trans_Amt` and` Total_Trans_Ct` have a high index of positive correlation (directly proportional growths) - the higher the total value transacted, the greater the total value transacted on the card\n    * The variables `Avg_Utilization_Ratio` and` Total_Revolving_Bal` have a high index of positive correlation (growth directly proportional)\n    * The variables `Customer_Age` and` Months_on_book` have a high index of positive correlation (directly proportional growths) - the older the customer, the longer the relationship with the bank\n    * There is an inversely proportional relationship between the variables `Credit_Limit` and` Avg_Utilization_Ratio`, indicating that the lower the average customer use of the products, the lower the pre-approved limit;\n    * This same inverse relationship also occurs between `Avg_Open_To_Buy` and` Avg_Utilization_Ratio`, indicating that less use also influences the customer's purchase opening.\n4. The pre-approved limit does not influence _churn_\n\"\"\"\nplot_distplot(df=df, col='Total_Trans_Ct', hue='Attrition_Flag', kind='kde',\n              title='Total transactions on credit card by attrition flag\\nDo attrited customers use more or less the credit card?')\n\"\"\"\nAnalyzing the correlations and proposing a more detailed view of the variables with the greatest impact on customers who left the bank, it is possible to perceive that customers who are attributable have a smaller distribution of volume traded on the card, thus indicating a possible dissatisfaction with services and a possible migration to other institutions.\n\"\"\"\nplot_distplot(df=df, col='Total_Ct_Chng_Q4_Q1', hue='Attrition_Flag', kind='strip', \n              palette=['cadetblue', 'crimson'],\n              title='Total transactions changed Q4-Q1 by attrition flag')\n# Correlation between age and relationship time\nfig, ax = plt.subplots(figsize=(15, 10))\nsns.scatterplot(x='Customer_Age', y='Months_on_book', data=df, hue='Attrition_Flag',\n                palette=['cadetblue', 'crimson'])\nax.set_title(\"Correlation between customer's age and relationship time\\n(analysis by attrition flag)\", size=16)\nformat_spines(ax, right_border=False)\n\"\"\"\nThe distribution chart above shows the directly proportional relationship that exists between age and the relationship between customers and the bank. The breakdown by attrition flag indicates that there is no direct relationship between these two variables with clients who migrated to another institution. This is because the red points indicated in the graph are spread across all two dimensions and are not positioned in a specific portion of the axes.\n\"\"\"\nfig, ax = plt.subplots(figsize=(15, 10))\nsns.scatterplot(x='Credit_Limit', y='Avg_Utilization_Ratio', data=df, hue='Attrition_Flag',\n                palette=['cadetblue', 'crimson'])\nax.set_title('Correlation between utilization ratio and credit limit\\n(analysis by attrition)', size=16)\nformat_spines(ax, right_border=False)\nfig, ax = plt.subplots(figsize=(15, 10))\nsns.scatterplot(x='Avg_Open_To_Buy', y='Avg_Utilization_Ratio', data=df, hue='Attrition_Flag',\n                palette=['cadetblue', 'crimson'])\nax.set_title('Correlation between utilization ratio and opening to buy\\n(analysis by attrtion flag)', size=16)\nformat_spines(ax, right_border=False)\n\"\"\"\nThe two distribution charts above show an inversely proportional relationship generated from the column that indicates an average use of the card by the customer. In the first case, we have the behavior of this variable with the pre-approved credit limit and, in the second case, the relationship with a variable that indicates the opening of the customer's purchase.\n\nAgain, the friction break does not show a specific niche or concentration in the plotted dimensions.\n\"\"\"\n\"\"\"\n<a id=\"3\"><\/a>\n<font color=\"darkslateblue\" size=+2.5><b>3. Prep: Building Pipelines<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAfter a detailed exploratory analysis session on the available basis, it was possible to create familiarity with the database and to draw some valuable insights related to the defined business problem. The visions and graphical plots allowed a better understanding of the target audience of analysis and a clear idea about the most promising variables for the prediction of _churn_ of clients of this financial institution.\n\nFrom that point on, a series of necessary steps will be proposed for the application of a complete _DataPrep_ process in the database in search of training a predictive model capable of returning the probability of _churn_ of each client.\n\nFor that, some features present in the `pycomp` library will be used, more specifically in its` pycomp.ml.transformers` module.\n\"\"\"\n\"\"\"\n<a id=\"3.1\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>3.1 Initial Pipeline<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nIn this session, changes in the database common to the whole set will be proposed. The big goal in creating an initial pipeline of data preparation is to ensure that some steps are applied before an official pipeline enters the scene, for example, an initial drop in features or the removal of duplicate data from a training base.\n\"\"\"\n\"\"\"\n<a id=\"3.1.1\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.1.1 Candidate Features<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nThe objectives of this step are:\n1. Filter the initial columns to be used in the modeling (elimination of key or non-representative columns for a predictive model)\n2. Prepare a transformer that can carry out this process automatically, in case there is a need to repeat the entire training process\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import FiltraColunas\n\n# Initial definition\nTO_DROP = ['CLIENTNUM', 'Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_1',\n           'Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_2']\nINITIAL_FEATURES = list(df.drop(TO_DROP, axis=1).columns)\n\n# Criando e aplicando transformador de sele\u00e7\u00e3o de features\nselector = FiltraColunas(features=INITIAL_FEATURES)\ndf_slct = selector.fit_transform(df)\n\n# Resultados\nprint(f'Shape of original dataset: {df.shape}')\nprint(f'Shape of dataset after selecting candidate features: {df_slct.shape}')\n\"\"\"\n<a id=\"3.1.2\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.1.2 Duplicated Data<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nThe objectives of this step are:\n\n1. Check for the presence of null and duplicate data in the database\n2. Treat null and duplicate data (if applicable)\n\"\"\"\n# Looking at null and duplicated data\nprint(f'Total of null data: {df_slct.isnull().sum().sum()}')\nprint(f'Total of duplicated data: {df_slct.duplicated().sum()}')\n\"\"\"\nPreviously, just after reading the database, it was possible to notice that the `data_overview ()` function did not return any null data for the columns. With this confirmation and, also verifying the absence of duplicate data, we can proceed further in the steps related to the prep.\n\"\"\"\n\"\"\"\n<a id=\"3.1.3\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.1.3 Target Definition<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nIn our original database, the column that identifies the target of the business problem is given by `Attrition_Flag`. In order to be able to train a predictive model, it is necessary to prepare in this column to transform it into \"0s and 1s\". For this, it is possible to use a class `DefineTarget` which, in turn, is responsible for applying a modification to a database based on a target column and an entry given as a positive class.\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import DefineTarget\n\n# Applying transformation\ntarget_transformer = DefineTarget(target_col='Attrition_Flag', pos_class='Attrited Customer')\ndf_tgt = target_transformer.fit_transform(df_slct)\n\ndf_tgt['target'].value_counts()\n\"\"\"\n<a id=\"3.1.4\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.1.4 Training and Testing Data<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nThe objectives of this session are:\n\n1. Define the target column of the model;\n2. Apply data separation in training and testing\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import SplitDados\n\n# Creating object and applying transformer\nTARGET = 'target'\nsplitter = SplitDados(target=TARGET)\nX_train, X_test, y_train, y_test = splitter.fit_transform(df_tgt)\n\n# Results\nprint(f'Shape of X_train: {X_train.shape}')\nprint(f'Shape of X_test: {X_test.shape}')\nprint(f'Shape of y_train: {y_train.shape}')\nprint(f'Shape of y_test: {y_test.shape}')\n\"\"\"\n<a id=\"3.2\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>3.2 Numerical Pipeline<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAfter building an initial pipeline capable of receiving a raw database, applying a feature selection process, performing a categorical grouping procedure and, finally, separating the data in training and testing, we will use the resulting training base to build pipelines in two different ways:\n\n* **Numerical pipeline:** preparation of the numerical data contained in the database;\n* **Categorical pipeline:** preparation of categorical data contained in the database.\n\"\"\"\n# Splitting features by its dtype\nnum_features = [col for col, dtype in X_train.dtypes.items() if dtype != 'object']\ncat_features = [col for col, dtype in X_train.dtypes.items() if dtype == 'object']\n\n# Validating\nprint(f'Total of num_features: {len(num_features)}')\nprint(f'Total of cat_features: {len(cat_features)}')\nprint(f'Total of features after initial drop: {X_train.shape[1]}')\n\n# Splitting data\nX_train_num = X_train[num_features]\nX_train_cat = X_train[cat_features]\n\"\"\"\nOnce the numerical and categorical sets of our training base are separated, we will start the steps of building individual pipelines for each of the two primitive types, starting with the numerical pipeline and its particularities.\n\"\"\"\n\"\"\"\n<a id=\"3.2.1\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.2.1 Null Data<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nPerhaps the first step to investigate in terms of numerical pipelines is the presence of null data in the database. In this context, we saw, from the function `data_overview()` proposed at the beginning of the EDA process, that the data set does not have any null data. Thus, it will not be necessary to provide any transformers responsible for filling or dropping null data.\n\nSee the confirmation below.\n\"\"\"\n# Returning null data\nprint(f'Null data on X_train_num:')\nX_train_num.isnull().sum()\n\"\"\"\n<a id=\"3.2.2\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.2.2 Log Transformation<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nTo validate the impact of the logarithmic transformation on candidate predictive models, we will optionally propose a step in the pipeline that applies this procedure to the numerical features present in the base. With this, we can validate whether the final performance of the model is sensitive to this type of transformation.\n\"\"\"\n# Distribution example\nlog_ex = 'Credit_Limit'\nfig, axs = plt.subplots(nrows=1, ncols=2, figsize=(17, 7))\nplot_distplot(df=X_train_num, col='Credit_Limit', ax=axs[0], hist=True,\n              title=f'Original {log_ex} Distribution')\n\ntmp_data = X_train_num.copy()\ntmp_data['Credit_Limit'] = tmp_data['Credit_Limit'].apply(lambda x: np.log1p(x))\nplot_distplot(df=tmp_data, col='Credit_Limit', ax=axs[1], color='mediumseagreen', hist=True, \n              title=f'{log_ex} After Log Transformation')\n\"\"\"\nTwo highly relevant statistical measures for distribution analysis are `skew` and` kurtosis`. Through the [link](https:\/\/codeburst.io\/2-important-statistics-terms-you-need-to-know-in-data-science-skewness-and-kurtosis-388fef94eeaa) it is possible to have a clear idea on what each of these measures is and how to interpret continuous distributions through their values.\n\nThe logarithmic transformation helps to increase performance for distributions with positive skewness (asymmetric on the left). Thus, we will analyze the numerical features again and rank the main features with the opportunity for improvement through this type of transformation.\n\"\"\"\nfrom scipy.stats import skew, kurtosis\n\ntmp_ov = df_overview.copy()\ntmp_ov['skew'] = tmp_ov.query('feature in @num_features')['feature'].apply(lambda x: skew(X_train_num[x]))\ntmp_ov['kurtosis'] = tmp_ov.query('feature in @num_features')['feature'].apply(lambda x: kurtosis(X_train_num[x]))\ntmp_ov[~tmp_ov['skew'].isnull()].sort_values(by='skew', ascending=False).loc[:, ['feature', 'skew', 'kurtosis']]\n\"\"\"\nThe table above shows a list of features through their skewness and kurtosis measures of symmetry. In the code block below, we will execute the `DynamicLogTransformation` class, which, in turn, has the role of applying the logarithmic transformation in a database in a preparation pipeline. The advantage of this class is the previous definition of a list of features to which the transformation will be applied, which is defined by the user.\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import DynamicLogTransformation\n\n# Defining parameters\nCOLS_TO_LOG = ['Total_Trans_Amt', 'Credit_Limit', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1',\n               'Avg_Utilization_Ratio']\nlog_tr = DynamicLogTransformation(num_features=num_features, cols_to_log=COLS_TO_LOG)\nX_train_num_ori = X_train_num.copy()\nX_train_num_log = log_tr.fit_transform(X_train_num)\n\n# Plotting some results\nfig, axs = plt.subplots(nrows=2, ncols=3, figsize=(17, 12))\n\nfor i in range(3):\n    ax = axs[0, i]\n    plot_distplot(df=df, col=COLS_TO_LOG[i], ax=ax, hist=True,\n                  title=f'{COLS_TO_LOG[i]} Distribution $Before$ \\nLog Transformation')\n    \nfor i in range(3):\n    ax = axs[1, i]\n    plot_distplot(df=X_train_num_log, col=COLS_TO_LOG[i], ax=ax, hist=True, color='mediumseagreen',\n                  title=f'{COLS_TO_LOG[i]} Distribution $After$ \\nLog Transformation')\n\nplt.tight_layout()\n\"\"\"\nAdditionally, it is worth mentioning that the class and `DynamicLogTransformation` have a Boolean attribute called `application` that can be used in the future for interactions in `GridSearch` or `RandomizedSearch`. Its objective is to enable performance analysis of models **with** or **without** the logarithmic transformation.\n\"\"\"\n\"\"\"\n<a id=\"3.2.3\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.2.3 Normalization<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nAnother interesting way to apply a procedure that helps a given predictive model to converge to the optimal value more quickly is given by the `normalization` of the data. For the context of machine learning, it is possible to use ready-made sklearn classes, for example, `MinMaxScaler` or` StandardScaler`.\n\nThis type of standardization \/ normalization can optionally be applied directly to the numerical pipeline. Below, an example of how this transformation can be applied to our numerical database will be demonstrated.\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import DynamicScaler\n\nscaler = DynamicScaler(scaler_type='Standard')\nX_train_num_scaled = scaler.fit_transform(X_train_num_log)\nX_train_num_scaled = pd.DataFrame(X_train_num_scaled, columns=num_features)\nX_train_num_scaled.head()\n\"\"\"\nWith that, we ended the preparation steps in the numerical pipeline of the project. In the future, we will consolidate each of these _steps_ into a single preparation block using the `sklearn` class `Pipeline`. As next steps, let's look at the categorical part of the set.\n\"\"\"\n\"\"\"\n<a id=\"3.3\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>3.3 Categorical Pipeline<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nContinuing with the base transformation step, we now have the mission of applying specific transformers within the categorical universe of the data set. Recalling a little about the main features existing in this world, the block below rescues some parameters extracted previously:\n\"\"\"\n# Categorical dataset\nX_train_cat.head()\n\"\"\"\nIn principle, the only transformation required in this categorical block is the application of the encoding process at the base. This is essential to feed the predictive models correctly, so that they can read the numeric inputs present after coding the categorical inputs. For this, we will use the `DummiesEncoding` class present in the `pycomp` package, which is responsible for applying the pandas `get_dummies()` method in order to transform the set appropriately.\n\"\"\"\n\"\"\"\n<a id=\"3.3.1\"><\/a>\n<font color=\"dimgrey\" size=+1.0><b>3.3.1 Dummies Encoding<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n# Importing class\nfrom pycomp.ml.transformers import DummiesEncoding\n\n# Applying encoding \nencoder = DummiesEncoding(dummy_na=False)\nX_train_cat_encoded = encoder.fit_transform(X_train_cat)\n\n# Results after encoding\nX_train_cat_encoded.head()\n\"\"\"\nWith the result of the application of the encoding method, it is possible to notice a significant growth in the number of features present in our database. This was due to the large number of categorical variables present, each contributing a reasonable number of entries. When applying the `DummiesEncoding` class, each categorical entry is pivoted at the base and transformed into a different new column (example: `Gender_F`, `Education_Level_College`, `Marital_Status_Single`, among others).\n\"\"\"\n\"\"\"\n<a id=\"3.4\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>3.4 Complete Pipelines<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nOnce the steps to be considered in preparing the data, whether initial or official, have been defined, we now have the ability to consolidate all _steps_ into single data transformation blocks. Thus, the cell below aims to carry out this consolidation process while defining some global design variables.\n\"\"\"\n# Importing libraries\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import train_test_split\n\n# Defining global variables\nORIGINAL_TARGET = 'Attrition_Flag'\nTARGET = 'target'\nTARGET_POSITIVE_CLASS = 'Attrited Customer'\n\nINITIAL_FEATURES = ['Customer_Age', 'Gender', 'Dependent_count', 'Education_Level', 'Marital_Status',\n                    'Income_Category', 'Card_Category', 'Months_on_book', 'Total_Relationship_Count',\n                    'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Attrition_Flag',\n                    'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt',\n                    'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio']\n\nINITIAL_PRED_FEATURES = [col for col in INITIAL_FEATURES if col not in [ORIGINAL_TARGET, TARGET]]\n\nNUM_FEATURES = ['Customer_Age', 'Dependent_count', 'Months_on_book', 'Total_Relationship_Count',\n                'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal',\n                'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct',\n                'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio']\n\nCAT_FEATURES = ['Gender', 'Education_Level', 'Marital_Status', 'Income_Category', 'Card_Category']\n\nMODEL_FEATURES = ['Customer_Age', 'Dependent_count', 'Months_on_book', 'Total_Relationship_Count',\n                  'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal',\n                  'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct',\n                  'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio', 'Gender_F', 'Gender_M',\n                  'Education_Level_College', 'Education_Level_Doctorate', 'Education_Level_Graduate',\n                  'Education_Level_High School', 'Education_Level_Post-Graduate',\n                  'Education_Level_Uneducated', 'Education_Level_Unknown', 'Marital_Status_Divorced',\n                  'Marital_Status_Married', 'Marital_Status_Single', 'Marital_Status_Unknown',\n                  'Income_Category_$120K +', 'Income_Category_$40K - $60K', 'Income_Category_$60K - $80K',\n                  'Income_Category_$80K - $120K', 'Income_Category_Less than $40K',\n                  'Income_Category_Unknown', 'Card_Category_Blue', 'Card_Category_Gold',\n                  'Card_Category_Platinum', 'Card_Category_Silver']\n\nSCALER_TYPE = 'Standard'\nENCODER_DUMMY_NA = False\nLOG_APPLICATION = True\nCOLS_TO_LOG = ['Total_Trans_Amt', 'Credit_Limit', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1',\n               'Avg_Utilization_Ratio']\n\n# Building initial pipeline (train and prediction)\ninitial_train_pipeline = Pipeline([\n    ('col_filter', FiltraColunas(features=INITIAL_FEATURES)),\n    ('target_transformer', DefineTarget(target_col=ORIGINAL_TARGET, pos_class=TARGET_POSITIVE_CLASS))\n])\n\ninitial_pred_pipeline = Pipeline([\n    ('col_filter', FiltraColunas(features=INITIAL_PRED_FEATURES))\n])\n\n# Building numerical pipeline\nnum_pipeline = Pipeline([\n    ('log_transformer', DynamicLogTransformation(application=LOG_APPLICATION, num_features=NUM_FEATURES, \n                                                 cols_to_log=COLS_TO_LOG)),\n    ('scaler', DynamicScaler(scaler_type=SCALER_TYPE))\n])\n\n# Building categorical pipeline\ncat_pipeline = Pipeline([\n    ('encoder', DummiesEncoding(dummy_na=ENCODER_DUMMY_NA))\n])\n\n# Building a complete pipeline\nprep_pipeline = ColumnTransformer([\n    ('num', num_pipeline, NUM_FEATURES),\n    ('cat', cat_pipeline, CAT_FEATURES)\n])\n# Reading raw data\ndf = pd.read_csv(os.path.join(DATA_PATH, FILENAME))\n\n# Executing initial training pipeline\ndf_prep = initial_train_pipeline.fit_transform(df)\n\n# Splitting training and testing data\nX_train, X_test, y_train, y_test = train_test_split(df_prep.drop(TARGET, axis=1), df_prep[TARGET].values,\n                                                    test_size=.20, random_state=42)\n\n# Executing preparation pipeline on training and testing data\nX_train_prep = prep_pipeline.fit_transform(X_train)\nX_test_prep = prep_pipeline.fit_transform(X_test)\n\n# Results\nprint(f'After reading raw data and applying initial and preparation pipelines, we have:\\n')\nprint(f'Shape of X_train_prep: {X_train_prep.shape}')\nprint(f'Shape of X_test_prep: {X_test_prep.shape}')\nprint(f'\\nTotal features considered on MODEL_FEATURES list: {len(MODEL_FEATURES)}')\n\"\"\"\n<a id=\"3.4\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>3.4 Complete Pipelines<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nOnce the steps to be considered in preparing the data, whether initial or official, have been defined, we now have the ability to consolidate all _steps_ into single data transformation blocks. Thus, the cell below aims to carry out this consolidation process while defining some global design variables.\n\"\"\"\n# Importing libraries\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import train_test_split\n\n# Defining global variables\nORIGINAL_TARGET = 'Attrition_Flag'\nTARGET = 'target'\nTARGET_POSITIVE_CLASS = 'Attrited Customer'\n\nINITIAL_FEATURES = ['Customer_Age', 'Gender', 'Dependent_count', 'Education_Level', 'Marital_Status',\n                    'Income_Category', 'Card_Category', 'Months_on_book', 'Total_Relationship_Count',\n                    'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Attrition_Flag',\n                    'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt',\n                    'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio']\n\nINITIAL_PRED_FEATURES = [col for col in INITIAL_FEATURES if col not in [ORIGINAL_TARGET, TARGET]]\n\nNUM_FEATURES = ['Customer_Age', 'Dependent_count', 'Months_on_book', 'Total_Relationship_Count',\n                'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal',\n                'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct',\n                'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio']\n\nCAT_FEATURES = ['Gender', 'Education_Level', 'Marital_Status', 'Income_Category', 'Card_Category']\n\nMODEL_FEATURES = ['Customer_Age', 'Dependent_count', 'Months_on_book', 'Total_Relationship_Count',\n                  'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal',\n                  'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct',\n                  'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio', 'Gender_F', 'Gender_M',\n                  'Education_Level_College', 'Education_Level_Doctorate', 'Education_Level_Graduate',\n                  'Education_Level_High School', 'Education_Level_Post-Graduate',\n                  'Education_Level_Uneducated', 'Education_Level_Unknown', 'Marital_Status_Divorced',\n                  'Marital_Status_Married', 'Marital_Status_Single', 'Marital_Status_Unknown',\n                  'Income_Category_$120K +', 'Income_Category_$40K - $60K', 'Income_Category_$60K - $80K',\n                  'Income_Category_$80K - $120K', 'Income_Category_Less than $40K',\n                  'Income_Category_Unknown', 'Card_Category_Blue', 'Card_Category_Gold',\n                  'Card_Category_Platinum', 'Card_Category_Silver']\n\nSCALER_TYPE = 'Standard'\nENCODER_DUMMY_NA = False\nLOG_APPLICATION = True\nCOLS_TO_LOG = ['Total_Trans_Amt', 'Credit_Limit', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1',\n               'Avg_Utilization_Ratio']\n\n# Building initial pipelines (training and prediction)\ninitial_train_pipeline = Pipeline([\n    ('col_filter', FiltraColunas(features=INITIAL_FEATURES)),\n    ('target_transformer', DefineTarget(target_col=ORIGINAL_TARGET, pos_class=TARGET_POSITIVE_CLASS))\n])\n\ninitial_pred_pipeline = Pipeline([\n    ('col_filter', FiltraColunas(features=INITIAL_PRED_FEATURES))\n])\n\n# Building a numerical pipeline\nnum_pipeline = Pipeline([\n    ('log_transformer', DynamicLogTransformation(application=LOG_APPLICATION, num_features=NUM_FEATURES, \n                                                 cols_to_log=COLS_TO_LOG)),\n    ('scaler', DynamicScaler(scaler_type=SCALER_TYPE))\n])\n\n# Building a categorical pipeline\ncat_pipeline = Pipeline([\n    ('encoder', DummiesEncoding(dummy_na=ENCODER_DUMMY_NA))\n])\n\n# Building a preparation pipeline\nprep_pipeline = ColumnTransformer([\n    ('num', num_pipeline, NUM_FEATURES),\n    ('cat', cat_pipeline, CAT_FEATURES)\n])\n# Reading raw data\ndf = pd.read_csv(os.path.join(DATA_PATH, FILENAME))\n\n# Executing initial training prep pipeline\ndf_prep = initial_train_pipeline.fit_transform(df)\n\n# Splitting data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(df_prep.drop(TARGET, axis=1), df_prep[TARGET].values,\n                                                    test_size=.20, random_state=42)\n\n# Executing preparation pipeline\nX_train_prep = prep_pipeline.fit_transform(X_train)\nX_test_prep = prep_pipeline.fit_transform(X_test)\n\n# Results\nprint(f'Shape of X_train_prep: {X_train_prep.shape}')\nprint(f'Shape of X_test_prep: {X_test_prep.shape}')\nprint(f'\\nTotal model features: {len(MODEL_FEATURES)}')\n\"\"\"\n_To be continued..._\n\"\"\"\n\"\"\"\n<a id=\"4\"><\/a>\n<font color=\"darkslateblue\" size=+2.5><b>4. Modelling: Predicting Churn<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nFinally, after extensive steps of exploratory analysis and preparation of the database, the time has come to apply Machine Learning concepts for the development of a predictive model capable of predicting the loss or migration of customers to other banking institutions. In possession of the final prepared basis, we will propose some algorithms capable of giving us this answer and, through their training and evaluation, we will choose the best model for the task in question.\n\nAll these steps will be built based on the tools available in the `pycomp` package through its `pycomp.ml.trainer` module (more specifically in the `ClassifierBinary` class). With ready-made codes and functions, the package brings a wide range of possibilities containing components that provide great ease in the development of predictive models.\n\"\"\"\n\"\"\"\n<a id=\"4.1\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>4.1 Structuring Variables<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nIn this step, some important variables will be defined for the use of the `ClassificadorBinario` class of the `pycomp` package. It is at this moment that we define the structures and objects that will serve as input for the training and evaluation of the models.\n\"\"\"\n# Importando modelos\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom lightgbm import LGBMClassifier\nfrom xgboost import XGBClassifier\n\n# Instanciando objetos\ndtree = DecisionTreeClassifier()\nforest = RandomForestClassifier()\nlgbm = LGBMClassifier()\nxgb = XGBClassifier()\n\n# Criando dicion\u00e1rio set_classifiers\nmodel_obj = [dtree, forest, lgbm, xgb]\nmodel_names = [type(model).__name__ for model in model_obj]\nset_classifiers = {name: {'model': obj, 'params': {}} for (name, obj) in zip(model_names, model_obj)}\n\nprint(f'Classifiers that will be trained on next steps: \\n\\n{model_names}')\n\"\"\"\n<a id=\"4.2\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>4.2 Training Models<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nOnce the modeling structure has been prepared from specific objects, such as the `set_classifiers` dictionary, it is now possible to import the` ClassificadorBinario` class present in the `pycomp.ml.trainer` module to carry out all the training and evaluation of the candidate models.\n\nThis class was developed in order to greatly facilitate the work of the analyst \/ scientist in terms of implementing codes to train, evaluate and optimize predictive models for binary classification. Its methods include powerful features that perform various actions with just one call.\n\"\"\"\n# Importing class\nfrom pycomp.ml.trainer import ClassificadorBinario\n\n# Creating an object and training models\ntrainer = ClassificadorBinario()\ntrainer.fit(set_classifiers, X_train_prep, y_train, random_search=False)\n\"\"\"\nThe `fit()` method of the created `trainer` object is responsible for training the models encapsulated in the `set_classifiers` dictionary created in the initial definitions stage.\n\nBy configuring the method to also apply the process of `RandomizedSearchCV` (random search of the best hyperparameters of each algorithm), it is possible to build models optimized according to the search space passed in the dictionary `set_classifiers`.\n\"\"\"\n\"\"\"\n<a id=\"4.3\"><\/a>\n<font color=\"dimgrey\" size=+2.0><b>4.3 Evaluating Performance<\/b><\/font>\n\n<a href=\"#top\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Go to TOC<\/a>\n\"\"\"\n\"\"\"\nOnce the candidate models are trained through the `fit()` method, it is then possible to evaluate the performance obtained in each case, thus returning the main classification metrics capable of indicating the best direction for the given task.\n\nTo perform this process, we can use the `evaluate_performance()` or `plot_metrics()` methods of the `trainer` object. In the first case, the return is an analytical DataFrame containing the result of the evaluation of each model against the main metrics. In the second case, the return is a visual analysis of the metrics for each of the models.\n\"\"\"\n# Training results\nmetrics = trainer.evaluate_performance(X_train_prep, y_train, X_test_prep, y_test)\nmetrics\n\"\"\"\nAs mentioned earlier, the `evaluate_performance()` method returns an analytical table containing the performance of each model (in training and testing) for the main metrics for evaluating classification models. From this table, it is possible to point out that, in terms of accuracy, the `LightGBM` model performed slightly better than the others, despite the high time required to perform the calculations.\n\nThinking about setting, in fact, an optimization goal to choose the best predictive model, let's consider the \"accuracy\" as the metric to be used for this decision. Another way to analyze the performance of candidate models is from the `plot_metrics()` method. Its result can be seen below:\n\"\"\"\n# Visual analysis on metrics\ntrainer.plot_metrics()\n\"\"\"\n_To be continued..._\n\"\"\"\n\"\"\"\n<font size=\"+1\" color=\"black\"><b>Please visit my other kernels by clicking on the buttons<\/b><\/font><br>\n\n<a href=\"https:\/\/www.kaggle.com\/thiagopanini\/pycomp-exploring-and-modeling-housing-prices\" class=\"btn btn-primary\" style=\"color:white;\">Pycomp: Housing Prices<\/a>\n<a href=\"https:\/\/www.kaggle.com\/thiagopanini\/pycomp-predicting-survival-on-titanic-disaster\" class=\"btn btn-primary\" style=\"color:white;\">Pycomp: Titanic EDA<\/a>\n<a href=\"https:\/\/www.kaggle.com\/thiagopanini\/predicting-restaurant-s-rate-in-bengaluru\" class=\"btn btn-primary\" style=\"color:white;\">Bengaluru's Restaurants<\/a>\n<a href=\"https:\/\/www.kaggle.com\/thiagopanini\/sentimental-analysis-on-e-commerce-reviews\" class=\"btn btn-primary\" style=\"color:white;\">Sentimental Analysis E-Commerce<\/a>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '95915cfc74e630'}"}
{"id":"61552","text":"\"\"\"\n# PACKAGES AND LIBRARIES\n\"\"\"\n\"\"\"\n#### GENERAL\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\"\"\"\n#### PATH\n\"\"\"\nimport os\nimport os.path\nfrom pathlib import Path\nimport glob\n\"\"\"\n#### IMAGE PROCESS\n\"\"\"\nfrom PIL import Image\nfrom keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\"\"\"\n#### SCALER & TRANSFORMATION\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.utils.np_utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom keras import regularizers\n\"\"\"\n#### ACCURACY CONTROL\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report, roc_auc_score, roc_curve\n\"\"\"\n#### OPTIMIZER\n\"\"\"\nfrom keras.optimizers import RMSprop,Adam,Optimizer\n\"\"\"\n#### MODEL LAYERS\n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization,MaxPooling2D,BatchNormalization,\\\n                        Permute, TimeDistributed, Bidirectional,GRU, SimpleRNN, LSTM, GlobalAveragePooling2D\nfrom keras import models\nfrom keras import layers\nimport tensorflow as tf\nfrom keras.applications import VGG16,VGG19\n\"\"\"\n#### IGNORING WARNINGS\n\"\"\"\nfrom warnings import filterwarnings\n\nfilterwarnings(\"ignore\",category=DeprecationWarning)\nfilterwarnings(\"ignore\", category=FutureWarning) \nfilterwarnings(\"ignore\", category=UserWarning)\n\"\"\"\n# PATH\n\"\"\"\nBrain_CT_Path = Path(\"..\/input\/brain-ct-hemorrhage-dataset\/Data\")\n\"\"\"\n* file path is determined\n\"\"\"\nJPG_Path = list(Brain_CT_Path.glob(r\"**\/*.jpg\"))\n\"\"\"\n* all images in the file path are assigned to a list\n\"\"\"\n\"\"\"\n# LABEL\n\"\"\"\nJPG_Labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1],JPG_Path))\n\"\"\"\n* the categories of the images are separated\n\"\"\"\n\"\"\"\n# TRANSFORMATION TO SERIES\n\"\"\"\nJPG_Path_Series = pd.Series(JPG_Path,name=\"JPG\").astype(str)\nJPG_Labels_Series = pd.Series(JPG_Labels,name=\"CATEGORY\")\n\"\"\"\n* it is converted to Series structure before it is converted to DataFrame\n\"\"\"\n\"\"\"\n# TRANSFORMATION TO DATAFRAME\n\"\"\"\nMain_Data = pd.concat([JPG_Path_Series,JPG_Labels_Series],axis=1)\n\"\"\"\n* it is converted to DataFrame\n\"\"\"\nprint(Main_Data.head(-1))\n\"\"\"\n#### REPLACING\n\"\"\"\nMain_Data[\"CATEGORY\"].replace({\"11[11]\":\"Hemorrhage\",\"11[11]\":\"Hemorrhage\",\"12[12]\":\"Hemorrhage\",\"13[13]\":\"Hemorrhage\",\n                               \"14[14]\":\"Hemorrhage\",\"15[15]\":\"Hemorrhage\",\"17[17]__\":\"Hemorrhage\",\n                               \"19[19]\":\"Hemorrhage\",\"1[1]\":\"Hemorrhage\",\"20[20]_2\":\"Hemorrhage\",\n                               \"21[21] _2\":\"Hemorrhage\",\"2[2]\":\"Hemorrhage\",\"3[3]\":\"Hemorrhage\",\"4[4]\":\"Hemorrhage\",\"5[5]\":\"Hemorrhage\",\n                               \"6[6]\":\"Hemorrhage\",\"7[7]\":\"Hemorrhage\",\"8[8]\":\"Hemorrhage\",\"9[9]\":\"Hemorrhage\"},inplace=True)\nMain_Data[\"CATEGORY\"].replace({\"N10[N10]\":\"Normal\",\"N11[N11]\":\"Normal\",\"N12[N12]\":\"Normal\",\"N13[N13]\":\"Normal\",\"N14[N14]\":\"Normal\",\n                               \"N15[N15]\":\"Normal\",\"N15[N15]\":\"Normal\",\n                               \"N16[N16]\":\"Normal\",\"N17[N17]\":\"Normal\",\"N18[N18]\":\"Normal\",\n                               \"N19[N19]\":\"Normal\",\"N1[N1]\":\"Normal\",\"N20[N20]\":\"Normal\",\"N21[N21]\":\"Normal\",\n                               \"N22[N22]\":\"Normal\",\"N23[N23]\":\"Normal\",\"N24[N24]\":\"Normal\",\n                               \"N25[N25]\":\"Normal\",\"N26[N26]\":\"Normal\",\"N27[N27]\":\"Normal\",\"N2[N2]\":\"Normal\",\n                               \"N3[N3]\":\"Normal\",\"N4[N4]\":\"Normal\",\"N5[N5]\":\"Normal\",\n                               \"N6[N6]\":\"Normal\",\"N7[N7]\":\"Normal\",\"N8[N8]\":\"Normal\",\"N9[N9]\":\"Normal\"},inplace=True)\n\"\"\"\n* we have to change the names because the categories in the data are complex\n\"\"\"\nprint(Main_Data.head(-1))\nprint(Main_Data[\"CATEGORY\"].value_counts())\n\"\"\"\n# SHUFFLING\n\"\"\"\nMain_Data = Main_Data.sample(frac=1).reset_index(drop=True)\n\"\"\"\n* we have to mix the data to increase the success of the model and maintain its objectivity.\n\"\"\"\nprint(Main_Data.head(-1))\n\"\"\"\n# VISUALIZATION\n\"\"\"\nplt.style.use('dark_background')\nsns.countplot(Main_Data[\"CATEGORY\"])\nplt.show()\nMain_Data['CATEGORY'].value_counts().plot.pie(figsize=(5,5))\nplt.show()\nsns.histplot(Main_Data['CATEGORY'].index)\nplt.show()\nfigure = plt.figure(figsize=(10,10))\nx = plt.imread(Main_Data[\"JPG\"][0])\nplt.imshow(x)\nplt.xlabel(x.shape)\nplt.title(Main_Data[\"CATEGORY\"][0])\nfigure = plt.figure(figsize=(10,10))\nx = plt.imread(Main_Data[\"JPG\"][25])\nplt.imshow(x)\nplt.xlabel(x.shape)\nplt.title(Main_Data[\"CATEGORY\"][6769])\nfig, axes = plt.subplots(nrows=5,\n                        ncols=5,\n                        figsize=(10,10),\n                        subplot_kw={\"xticks\":[],\"yticks\":[]})\n\nfor i,ax in enumerate(axes.flat):\n    ax.imshow(plt.imread(Main_Data[\"JPG\"][i]))\n    ax.set_title(Main_Data[\"CATEGORY\"][i])\nplt.tight_layout()\nplt.show()\n\"\"\"\n# DETERMINATION TRAIN AND TEST DATA\n\"\"\"\nTrain_Data,Test_Data = train_test_split(Main_Data,train_size=0.9,shuffle=True,random_state=42)\n\"\"\"\n* we divided it into test and training set\n* we set the shuffle parameter to True for training quality\n* we told it to use the same data as random state\n\"\"\"\nprint(\"TRAIN SHAPE: \",Train_Data.shape)\nprint(\"TEST SHAPE: \",Test_Data.shape)\nprint(Train_Data.head(-1))\nprint(\"----\"*20)\nprint(Test_Data.head(-1))\n\"\"\"\n# IMAGE GENERATOR\n\"\"\"\nGenerator = ImageDataGenerator(rescale=1.\/255,\n                               zoom_range=0.2,\n                              shear_range=0.2,\n                              rotation_range=40,\n                              horizontal_flip=True,\n                               fill_mode=\"nearest\",\n                              validation_split=0.1)\n\"\"\"\n* we used diversification so that the model does not shift to the overfitting orientation\n\"\"\"\nTest_Generator = ImageDataGenerator(rescale=1.\/255)\n\"\"\"\n* we don't need diversification for test data, we will use it as it is\n\"\"\"\n\"\"\"\n#### How Generator Applied Image Look Like\n\"\"\"\nexample_Image = Train_Data[\"JPG\"][99]\nLoad_Image = image.load_img(example_Image,target_size=(200,200))\nArray_Image = image.img_to_array(Load_Image)\nArray_Image = Array_Image.reshape((1,) + Array_Image.shape)\n\ni = 0\nfor batch in Generator.flow(Array_Image,batch_size=1):\n    plt.figure(i)\n    IMG = plt.imshow(image.array_to_img(batch[0]))\n    i += 1\n    if i % 4 == 0:\n        break\nplt.show()\n\"\"\"\n#### APPLYING GENERATOR AND TRANSFORMATION TO TENSOR\n\"\"\"\nTrain_IMG_Set = Generator.flow_from_dataframe(dataframe=Train_Data,\n                                             x_col=\"JPG\",\n                                             y_col=\"CATEGORY\",\n                                             color_mode=\"grayscale\",\n                                             class_mode=\"categorical\",\n                                             subset=\"training\")\nValidation_IMG_Set = Generator.flow_from_dataframe(dataframe=Train_Data,\n                                                  x_col=\"JPG\",\n                                                  y_col=\"CATEGORY\",\n                                                  color_mode=\"grayscale\",\n                                                  class_mode=\"categorical\",\n                                                  subset=\"validation\")\nTest_IMG_Set = Generator.flow_from_dataframe(dataframe=Test_Data,\n                                                 x_col=\"JPG\",\n                                                 y_col=\"CATEGORY\",\n                                                 color_mode=\"grayscale\",\n                                                 class_mode=\"categorical\")\n\"\"\"\n#### CHECKING\n\"\"\"\nfor data_batch,label_batch in Train_IMG_Set:\n    print(\"DATA SHAPE: \",data_batch.shape)\n    print(\"LABEL SHAPE: \",label_batch.shape)\n    break\nfor data_batch,label_batch in Validation_IMG_Set:\n    print(\"DATA SHAPE: \",data_batch.shape)\n    print(\"LABEL SHAPE: \",label_batch.shape)\n    break\nprint(\"TRAIN: \")\nprint(Train_IMG_Set.class_indices)\nprint(Train_IMG_Set.classes[0:5])\nprint(Train_IMG_Set.image_shape)\nprint(\"---\"*20)\nprint(\"VALIDATION: \")\nprint(Validation_IMG_Set.class_indices)\nprint(Validation_IMG_Set.classes[0:5])\nprint(Validation_IMG_Set.image_shape)\nprint(\"---\"*20)\nprint(\"TEST: \")\nprint(Test_IMG_Set.batch_size)\nprint(Test_IMG_Set.image_shape)\n\"\"\"\n# CNN STRUCTURE WITH LSTM \/ RCNN\n\"\"\"\nModel = Sequential()\n\nModel.add(Conv2D(12,(3,3),activation=\"relu\",\n                 input_shape=(256,256,1)))\nModel.add(BatchNormalization())\nModel.add(MaxPooling2D((2,2)))\n\n#\nModel.add(Conv2D(24,(3,3),\n                 activation=\"relu\",padding=\"same\"))\nModel.add(Dropout(0.2))\nModel.add(MaxPooling2D((2,2)))\n\n#\nModel.add(Conv2D(64,(3,3),\n                 activation=\"relu\",padding=\"same\"))\nModel.add(Dropout(0.5))\nModel.add(MaxPooling2D((2,2)))\n\n\n#\nModel.add(TimeDistributed(Flatten()))\nModel.add(Bidirectional(LSTM(32,\n                                  return_sequences=True,\n                                  dropout=0.5,\n                                  recurrent_dropout=0.5)))\nModel.add(Bidirectional(GRU(32,\n                                  return_sequences=True,\n                                  dropout=0.5,\n                                  recurrent_dropout=0.5)))\n\n#\nModel.add(Flatten())\nModel.add(Dense(256,activation=\"relu\"))\nModel.add(Dropout(0.5))\nModel.add(Dense(2,activation=\"softmax\"))\n\"\"\"\n* LSTM and GRU are iterative layers\n\"\"\"\n\"\"\"\n* LSTM and GRU serve to inject past information into the future, thereby reducing the gradient destruction problem\n\"\"\"\n\"\"\"\n* we used LSTM and GRU layers both with fully-connetted layers and Conv2D\n* RCNN structure is created in this way\n* we determined the LSTM and GRU layers as bidirectional\n\"\"\"\n\"\"\"\n* less problem of gradient disappearance in LSTM and GRU\n\"\"\"\n\"\"\"\n* we used it with Dropout so that the model does not shift to overfitting orientation\n* we made return_success True because we wanted each process to generate output separately\n\"\"\"\n\"\"\"\n* we also used dropout within the GRU and LSTM layers to prevent the model from shifting to the overfitting orientation\n* recurrent_dropout means transmission damping ratio of iterative layers\n\"\"\"\n\"\"\"\nLoss Function We Used:\n\n\n![](https:\/\/gombru.github.io\/assets\/cross_entropy_loss\/intro.png)\n\"\"\"\n\"\"\"\n* Activation Function:\n\n![](http:\/\/rasbt.github.io\/mlxtend\/user_guide\/general_concepts\/activation-functions_files\/activation-functions.png)\n\"\"\"\nCall_Back = tf.keras.callbacks.EarlyStopping(monitor=\"loss\",patience=5,mode=\"min\")\n\"\"\"\n* we wanted the training of the model to stop where the loss value is minimal\n\"\"\"\nModel.compile(optimizer=\"rmsprop\",loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])\nCNN_Model = Model.fit(Train_IMG_Set,\n                      validation_data=Validation_IMG_Set,\n                            callbacks=Call_Back,\n                      epochs=50)\n\"\"\"\n#### CHECKING\n\"\"\"\nModel_Results = Model.evaluate(Test_IMG_Set,verbose=False)\nprint(\"LOSS:  \" + \"%.4f\" % Model_Results[0])\nprint(\"ACCURACY:  \" + \"%.2f\" % Model_Results[1])\nprint(Model.summary())\nplt.plot(CNN_Model.history[\"accuracy\"])\nplt.plot(CNN_Model.history[\"val_accuracy\"])\nplt.ylabel(\"ACCURACY\")\nplt.legend()\nplt.show()\nplt.plot(CNN_Model.history[\"loss\"])\nplt.plot(CNN_Model.history[\"val_loss\"])\nplt.ylabel(\"LOSS\")\nplt.legend()\nplt.show()\nplt.plot(CNN_Model.history[\"loss\"])\nplt.plot(CNN_Model.history[\"accuracy\"])\nplt.ylabel(\"LOSS - ACCURACY\")\nplt.legend()\nplt.show()\nplt.plot(CNN_Model.history[\"val_loss\"])\nplt.plot(CNN_Model.history[\"val_accuracy\"])\nplt.ylabel(\"VAL LOSS - VAL ACCURACY\")\nplt.legend()\nplt.show()\nDict_Summary = pd.DataFrame(CNN_Model.history)\nDict_Summary.plot()\n\n\"\"\"\n#### PREDICTION\n\"\"\"\nPrediction = Model.predict(Test_IMG_Set)\nPrediction = Prediction.argmax(axis=-1)\nfig, axes = plt.subplots(nrows=5,\n                         ncols=5,\n                         figsize=(20, 20),\n                        subplot_kw={'xticks': [], 'yticks': []})\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(plt.imread(Test_Data[\"JPG\"].iloc[i]))\n    ax.set_title(f\"PREDICTION:{Prediction[i]}\")\nplt.tight_layout()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '7186e0d15319c2'}"}
{"id":"120260","text":"\"\"\"\n## Visualizing Images \n\nThis is read and Visualizing Images Demo.\n\"\"\"\nimport os\nimport sys\nimport random\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom skimage.transform import resize\nfrom skimage.morphology import label\nfrom skimage.feature import hog\nfrom skimage import exposure\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom skimage.feature import canny\nfrom skimage.filters import sobel\nfrom skimage.morphology import watershed\nfrom scipy import ndimage as ndi\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom skimage.segmentation import mark_boundaries\nfrom scipy import signal\nimport cv2\nimport glob, pylab, pandas as pd\nimport pydicom, numpy as np\nimport tqdm\nimport gc\ngc.enable()\nimport glob\n\nfrom skimage.transform import resize\nfrom skimage.morphology import label\nfrom skimage import exposure\nROOT_FOLDER = '\/kaggle\/input\/rsna-intracranial-hemorrhage-detection'\nTRAIN_CSV = ROOT_FOLDER + '\/stage_1_train.csv'\nTRAIN_FOLDER = ROOT_FOLDER + '\/stage_1_train_images'\nTEST_FOLDER = ROOT_FOLDER + '\/stage_1_test_images'\ntrain_files = glob.glob(TRAIN_FOLDER + '\/*.dcm')\nlen(train_files)\n\ntest_files = glob.glob(TEST_FOLDER + '\/*.dcm')\nlen(test_files)\ndf = pd.read_csv(TRAIN_CSV,header=None)\ndf.head()\ndf.shape\nimport cv2\nfrom IPython.display import display, Image\ndef cvshow(image, format='.png', rate=255 ):\n    decoded_bytes = cv2.imencode(format, image*rate)[1].tobytes()\n    display(Image(data=decoded_bytes))\n    return\nj = 0\nnImg = 10\nimg_ar = np.empty(0)\nwhile img_ar.shape[0]!=nImg:\n    dcm_file = train_files[j]\n    dcm_data = pydicom.read_file(dcm_file)\n    img = np.expand_dims(dcm_data.pixel_array,axis=0)    \n    if j==0:\n        img_ar = img\n    elif (j%100==0):\n        print(j,'images loaded')\n    else:\n        img_ar = np.concatenate([img_ar,img],axis=0)\n    j += 1\ndef imgtile(imgs,tile_w):\n    assert imgs.shape[0]%tile_w==0,\"'imgs' cannot divide by 'th'.\"\n    r=imgs.reshape((-1,tile_w)+imgs.shape[1:])\n    return np.hstack(np.hstack(r))\n\n#usage\ntiled = imgtile(img_ar,5)\n# cvshow(tiled)\ntiled.shape\nimg = tiled.astype(np.float32)\ncvshow(cv2.resize( img, (1024,512), interpolation=cv2.INTER_LINEAR ))\n\"\"\"\n## Train Image\n\"\"\"\nplt.figure(figsize=(30,15))\nplt.subplots_adjust(bottom=0.2, top=0.7, hspace=0)  #adjust this to change vertical and horiz. spacings..\nnImg = 3  #no. of images to process\nfor j in range(nImg):\n    q = j+1\n    img = np.array(pydicom.read_file(train_files[j]).pixel_array)\n    \n#     # Contrast stretching\n    p2, p97 = np.percentile(img, (2, 97))\n    img_rescale = exposure.rescale_intensity(img, in_range=(p2, p97))\n    \n    # Equalization\n    img_eq = exposure.equalize_hist(img)\n\n    # Adaptive Equalization\n    img_adapteq = exposure.equalize_adapthist(img)\n    \n    plt.subplot(nImg,7,q*7-6)\n    plt.imshow(img, cmap=plt.cm.bone)\n    plt.title('Original Image')\n    \n    \n    plt.subplot(nImg,7,q*7-5)    \n    plt.imshow(img_rescale, cmap=plt.cm.bone)\n    plt.title('Contrast stretching')\n    \n    \n    plt.subplot(nImg,7,q*7-4)\n    plt.imshow(img_eq, cmap=plt.cm.bone)\n    plt.title('Equalization')\n    \n    \n    plt.subplot(nImg,7,q*7-3)\n    plt.imshow(img_adapteq, cmap=plt.cm.bone)\n    plt.title('Adaptive Equalization')\nplt.show()\n\"\"\"\n## Test Images\n\"\"\"\nplt.figure(figsize=(30,15))\nplt.subplots_adjust(bottom=0.2, top=0.7, hspace=0)  #adjust this to change vertical and horiz. spacings..\nnImg = 3  #no. of images to process\nfor j in range(nImg):\n    q = j+1\n    img = np.array(pydicom.read_file(test_files[j]).pixel_array)\n    \n#     # Contrast stretching\n    p2, p97 = np.percentile(img, (2, 97))\n    img_rescale = exposure.rescale_intensity(img, in_range=(p2, p97))\n    \n    # Equalization\n    img_eq = exposure.equalize_hist(img)\n\n    # Adaptive Equalization\n    img_adapteq = exposure.equalize_adapthist(img)\n    \n    plt.subplot(nImg,7,q*7-6)\n    plt.imshow(img, cmap=plt.cm.bone)\n    plt.title('Original Image')\n    \n    \n    plt.subplot(nImg,7,q*7-5)    \n    plt.imshow(img_rescale, cmap=plt.cm.bone)\n    plt.title('Contrast stretching')\n    \n    \n    plt.subplot(nImg,7,q*7-4)\n    plt.imshow(img_eq, cmap=plt.cm.bone)\n    plt.title('Equalization')\n    \n    \n    plt.subplot(nImg,7,q*7-3)\n    plt.imshow(img_adapteq, cmap=plt.cm.bone)\n    plt.title('Adaptive Equalization')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'dd33dce7736876'}"}
{"id":"82511","text":"\"\"\"\n# Gradient Descent \n\n   Gradient descent is one of the most basic and easy to implement algorithm for finding minima of the cost function. For a mean square cost function there exists only one minima which it's global minima. This is because the mean square cost function is a Quadratic Function.\n            \n   For a complex cost function with many local minimas, the algorithm that I have given below might not work effectively.\n            \n   Always check the convergence curve when you're training the model for the first time. If it doesn't converge try decreasing the learning rate(a) and increase the iterations. This is one of the downsides of gradient descent, but in more complex solvers like BGFS, L-BGFS, etc we need not specify the learning rate.\n\"\"\"\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\"\"\"\n## Creating synthetic datasets for testing\n\"\"\"\nfrom sklearn.datasets import make_regression\n\nX, y = make_regression(n_samples = 100, n_features=5,\n                            n_informative=1, bias = 150.0,\n                            noise = 30, random_state=0)\nX[:5], y[:5]\n\"\"\"\n## Linear Regression\n\"\"\"\n\"\"\"\n### Mean Square Cost Function for linear regression\n\"\"\"\n\"\"\"\n### Specify loc='in' while using cost function inside Gradient Descent(gd function) \n\"\"\"\ndef cost(x, y, th, loc=None):\n    m = len(x)\n    if loc != 'in':\n        x = np.hstack((np.array([1]*m).reshape(-1,1), x))\n    y = y.reshape(-1,1)\n    return (np.sum((x.dot(th) - y)**2)) \/ (2*m)\n\"\"\"\n### Intercept and Coefficient calculating Function for linear regression using Gradient Descent\n\nx     -> the training dataset, a 2D array.\n\ny     -> target values, 1D array.\n\na     -> learning rate.\n\nitr   -> maximum number of iterations to be performed.\n\"\"\"\ndef gd(x, y, a=0.1, itr=100, graph=0):\n    m, n = x.shape \n    # m -> no of datapoints\n    # n -> no of features\n    \n    th = np.array([0]*(n+1)).reshape(-1,1)\n    # th -> set intercept and coefficient values to 0 initially\n    \n    x = np.hstack((np.ones((m,1)), x))\n    # add a row of 1s to the dataset to mulitply with the intercept term in th\n    \n    y = y.reshape(-1,1)\n    cst = [cost(x, y, th, loc='in')]\n    # list to store the cost to check for convergence\n    \n    for i in range(itr):\n        der = (x.T).dot(x.dot(th) - y) \/ m\n        # gradient of the cost function\n        \n        th = th - (a * der) #updated th\n        cst.append(cost(x, y, th, loc='in')) #cost for updated th\n    if graph == 1:\n        return th, cst, a, itr\n    return th\n\"\"\"\n### A diverging model for high learning rate(a)\n\"\"\"\nout = gd(X, y, a=1.6, itr=100, graph=1)\nplt.figure()\nplt.plot(out[1]) #plot the cost wrt iterations\nplt.title('Convergence curve for alpha = {} and max_iteration = {}'.format(out[2], out[3]))\nplt.ylabel('Mean square error (Cost function)')\nplt.xlabel('Iteration')\nplt.show()\nprint('Intercept: ', out[0][0,0])\nprint('Coefficients: ', out[0][1:].ravel()) # Gives bad estimates\n\"\"\"\n### A perfectly converging model for appropriate learning rate(a)\n\"\"\"\nout = gd(X, y, a=0.1, itr=500, graph=1)\nplt.figure()\nplt.plot(out[1]) #plot the cost wrt iterations\nplt.title('Convergence curve for alpha = {} and max_iteration = {}'.format(out[2], out[3]))\nplt.ylabel('Mean square error (Cost function)')\nplt.xlabel('Iteration')\nplt.show()\nprint('Intercept: ', out[0][0,0])\nprint('Coefficients: ', out[0][1:].ravel()) # Gives proper estimates\n\"\"\"\n### Verifying Results with Scikit-learn\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression().fit(X, y)\nprint('Intercept: ', lr.intercept_)\nprint('Coefficients: ', lr.coef_)","meta":"{'source': 'AI4Code', 'id': '977d5e27170e46'}"}
{"id":"85587","text":"\"\"\"\n Hello everyone, this is my first kernel. I will appreciate any kind of constructive feedback. \n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA\nfrom sklearn import cross_validation, metrics\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nimport xgboost as xgb\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\n#Read files:\ntrain_df = pd.read_csv(\"..\/input\/train.csv\")\ntest_df = pd.read_csv(\"..\/input\/test.csv\")\nprint(train_df.columns.values)\n\"\"\"\nWhich features are categorical? Which features are numerical?\n\"\"\"\n# preview the data\ntrain_df.head(10)\n\"\"\"\nLet's get a detailed distribution of numerical feature values across the samples.\n\"\"\"\ntrain_df.describe() #Get summary of numerical variables\n\"\"\"\nNext, let's get a detailed distribution of categorical features across the samples.\n\"\"\"\ntrain_df.describe(include=['O']) #Get summary of categorical variables\n\"\"\"\nNow, if you look at the data_description.txt, you can observe that a lot of categorical features contain **NA**  as a feature value. However, now they are considered as missing values.  For example the categorical feature **Alley** has **3** unique values: *Grvl*, *Pave* and *NA*. But in the above summary of cateforical features, **Alley** is seen to have **2** unique values as *NA* is considered as missing value. We will now rectify all those features.\n\"\"\"\n# Here NA is a value for the feature Alley\ntrain_df['Alley'].fillna('No_Alley',inplace=True)\ntest_df['Alley'].fillna('No_Alley',inplace=True)\n# Here NA is a value for the feature BsmtQual\ntrain_df['BsmtQual'].fillna('No_Basement',inplace=True)\ntest_df['BsmtQual'].fillna('No_Basement',inplace=True)\n# Here NA is a value for the feature BsmtCond\ntrain_df['BsmtCond'].fillna('No_Basement',inplace=True)\ntest_df['BsmtCond'].fillna('No_Basement',inplace=True)\n# Here NA is a value for the feature BsmtExposure\ntrain_df['BsmtExposure'].fillna('No_Basement',inplace=True)\ntest_df['BsmtExposure'].fillna('No_Basement',inplace=True)\n# Here NA is a value for the feature BsmtFinType1\ntrain_df['BsmtFinType1'].fillna('No_Basement',inplace=True)\ntest_df['BsmtFinType1'].fillna('No_Basement',inplace=True)\n# Here NA is a value for the feature BsmtFinType2\ntrain_df['BsmtFinType2'].fillna('No_Basement',inplace=True)\ntest_df['BsmtFinType2'].fillna('No_Basement',inplace=True)\n# Here NA is a value for the feature FireplaceQu\ntrain_df['FireplaceQu'].fillna('No_Fireplace',inplace=True)\ntest_df['FireplaceQu'].fillna('No_Fireplace',inplace=True)\n# Here NA is a value for the feature GarageType\ntrain_df['GarageType'].fillna('No_Garage',inplace=True)\ntest_df['GarageType'].fillna('No_Garage',inplace=True)\n# Here NA is a value for the feature GarageFinish\ntrain_df['GarageFinish'].fillna('No_Garage',inplace=True)\ntest_df['GarageFinish'].fillna('No_Garage',inplace=True)\n# Here NA is a value for the feature GarageQual\ntrain_df['GarageQual'].fillna('No_Garage',inplace=True)\ntest_df['GarageQual'].fillna('No_Garage',inplace=True)\n# Here NA is a value for the feature GarageCond\ntrain_df['GarageCond'].fillna('No_Garage',inplace=True)\ntest_df['GarageCond'].fillna('No_Garage',inplace=True)\n# Here NA is a value for the feature PoolQC\ntrain_df['PoolQC'].fillna('No_Pool',inplace=True)\ntest_df['PoolQC'].fillna('No_Pool',inplace=True)\n# Here NA is a value for the feature Fence\ntrain_df['Fence'].fillna('No_Fence',inplace=True)\ntest_df['Fence'].fillna('No_Fence',inplace=True)\n# Here NA is a value for the feature MiscFeature\ntrain_df['MiscFeature'].fillna('None',inplace=True)\ntest_df['MiscFeature'].fillna('None',inplace=True)\n# Here None is a value for the feature MasVnrType\ntrain_df['MasVnrType'].fillna('None',inplace=True)\ntest_df['MasVnrType'].fillna('None',inplace=True)\n\"\"\"\nNow, let's get a detailed distribution of categorical features across the samples. This time we will observe all such features has one more unique value than the previous one.\n\"\"\"\ntrain_df.describe(include=['O']) #Get summary of categorical variables\n\"\"\"\nWe will perform some visualization to better understand the distribution of different features and also the relationship of our dependent variable *SalePrice* with other features.\n\"\"\"\n# plotting the histogram of GrLivArea\ntrain_df['GrLivArea'].hist(bins=50)\nplt.show()\n# plotting the histogram of GarageArea\ntrain_df['GarageArea'].hist(bins=50)\nplt.show()\n#scatter plot BedroomAbvGr\/saleprice\nvar = 'BedroomAbvGr'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#scatter plot grlivarea\/saleprice\nvar = 'GrLivArea'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#scatter plot OverallQual\/saleprice\nvar = 'OverallQual'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#scatter plot OverallCond\/saleprice\nvar = 'OverallCond'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n\"\"\"\nNext, we will create some new features from the combination of old features and then drop the old features. For example, we can combine *OverallCond* and *OverallQual* to get a new feature as that will be more relevant.\n\"\"\"\n#creating new_variable\ntrain_df['Overallscore']=train_df['OverallQual']+train_df['OverallCond']\ntest_df['Overallscore']=test_df['OverallQual']+test_df['OverallCond']\n#dropping irrevalent variables\ntrain_df = train_df.drop(['OverallQual', 'OverallCond'], axis=1)\ntest_df = test_df.drop(['OverallQual', 'OverallCond'], axis=1)\n#scatter plot Overallscore\/saleprice\nvar = 'Overallscore'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='green');\n#creating new_variable\ntrain_df['BsmtFin']=train_df['BsmtFinSF1']+train_df['BsmtFinSF2']\ntest_df['BsmtFin']=test_df['BsmtFinSF1']+test_df['BsmtFinSF2']\n#dropping irrevalent variables\ntrain_df = train_df.drop(['BsmtFinSF1', 'BsmtFinSF2', 'TotalBsmtSF'], axis=1)\ntest_df = test_df.drop(['BsmtFinSF1', 'BsmtFinSF2', 'TotalBsmtSF'], axis=1)\n# converting some categorical features to ordinal\nGarage_mapping = {\"No_Garage\": 0, \"Po\": 1, \"Fa\": 2, \"TA\": 3, \"Gd\": 4, \"Ex\": 5}\ntrain_df['GarageQual'] = train_df['GarageQual'].map(Garage_mapping)\ntest_df['GarageQual'] = test_df['GarageQual'].map(Garage_mapping)\ntrain_df['GarageCond'] = train_df['GarageCond'].map(Garage_mapping)\ntest_df['GarageCond'] = test_df['GarageCond'].map(Garage_mapping)\n#creating new_variable\ntrain_df['Garagescore']=train_df['GarageQual']+train_df['GarageCond']\ntest_df['Garagescore']=test_df['GarageQual']+test_df['GarageCond']\n#dropping irrevalent variables\ntrain_df = train_df.drop(['GarageQual', 'GarageCond'], axis=1)\ntest_df = test_df.drop(['GarageQual', 'GarageCond'], axis=1)\ntrain_df['Garagescore'].head(10)\n# converting some categorical features to ordinal\nBsmt_mapping = {\"No_Basement\": 0, \"Unf\":1, \"LwQ\": 2, \"Rec\": 3, \"BLQ\": 4, \"ALQ\": 5, \"GLQ\":6}\ntrain_df['BsmtFinType1'] = train_df['BsmtFinType1'].map(Bsmt_mapping)\ntest_df['BsmtFinType1'] = test_df['BsmtFinType1'].map(Bsmt_mapping)\ntrain_df['BsmtFinType2'] = train_df['BsmtFinType2'].map(Bsmt_mapping)\ntest_df['BsmtFinType2'] = test_df['BsmtFinType2'].map(Bsmt_mapping)\n#creating new_variable\ntrain_df['BsmtFinType']=train_df['BsmtFinType1']+train_df['BsmtFinType2']\ntest_df['BsmtFinType']=test_df['BsmtFinType1']+test_df['BsmtFinType2']\n#dropping irrevalent variables\ntrain_df = train_df.drop(['BsmtFinType1', 'BsmtFinType2'], axis=1)\ntest_df = test_df.drop(['BsmtFinType1', 'BsmtFinType2'], axis=1)\ntrain_df['BsmtFinType'].head(10)\n# converting some categorical features to ordinal\nExter_mapping = {\"Po\": 1, \"Fa\": 2, \"TA\": 3, \"Gd\": 4, \"Ex\": 5}\ntrain_df['ExterQual'] = train_df['ExterQual'].map(Exter_mapping)\ntest_df['ExterQual'] = test_df['ExterQual'].map(Exter_mapping)\ntrain_df['ExterCond'] = train_df['ExterCond'].map(Exter_mapping)\ntest_df['ExterCond'] = test_df['ExterCond'].map(Exter_mapping)\n#creating new_variable\ntrain_df['Exterscore']=train_df['ExterQual']+train_df['ExterCond']\ntest_df['Exterscore']=test_df['ExterQual']+test_df['ExterCond']\n#dropping irrevalent variables\ntrain_df = train_df.drop(['ExterQual', 'ExterCond'], axis=1)\ntest_df = test_df.drop(['ExterQual', 'ExterCond'], axis=1)\ntrain_df['Exterscore'].head(10)\n#dropping irrevalent variables\ntrain_df = train_df.drop(['Condition2'], axis=1)\ntest_df = test_df.drop(['Condition2'], axis=1)\n\"\"\"\nThere are multiple features that have **year** as feature value. Instead of keeping the entire year as feature value, I have converted it to a number as 2018 - **year**\n\"\"\"\n# Determining the years from Original construction date\n# Years:\ntrain_df['Age_of_House'] = 2018 - train_df['YearBuilt']\ntest_df['Age_of_House'] = 2018 - test_df['YearBuilt']\ntrain_df['Age_of_House'].describe()\n#scatter plot Age_of_House\/saleprice\nvar = 'Age_of_House'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='green');\n# dropping YearBuilt feature\ntrain_df = train_df.drop(['YearBuilt'], axis=1)\ntest_df = test_df.drop(['YearBuilt'], axis=1)\n# Determining the years from Remodelling date\n# Years:\ntrain_df['Age_of_Remod_House'] = 2018 - train_df['YearRemodAdd']\ntest_df['Age_of_Remod_House'] = 2018 - test_df['YearRemodAdd']\ntrain_df['Age_of_Remod_House'].describe()\n#scatter plot Age_of_Remod_House\/saleprice\nvar = 'Age_of_Remod_House'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='green');\n# dropping YearRemodAdd feature\ntrain_df = train_df.drop(['YearRemodAdd'], axis=1)\ntest_df = test_df.drop(['YearRemodAdd'], axis=1)\n# Determining the years from garage built date\n# Years:\ntrain_df['Age_of_garage'] = 2018 - train_df['GarageYrBlt']\ntest_df['Age_of_garage'] = 2018 - test_df['GarageYrBlt']\ntrain_df['Age_of_garage'].describe()\n#scatter plot Age_of_House\/saleprice\nvar = 'Age_of_garage'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='green');\n# dropping GarageYrBlt feature\ntrain_df = train_df.drop(['GarageYrBlt'], axis=1)\ntest_df = test_df.drop(['GarageYrBlt'], axis=1)\n\"\"\"\nDropping some more irrevalent features\n\"\"\"\n#scatter plot YrSold\/saleprice\nvar = 'YrSold'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#dropping irrevalent variables\ntrain_df = train_df.drop(['YrSold', 'MoSold'], axis=1)\ntest_df = test_df.drop(['YrSold', 'MoSold'], axis=1)\n#scatter plot LotFrontage\/saleprice\nvar = 'LotFrontage'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#dropping irrevalent variables\ntrain_df = train_df.drop(['LotFrontage'], axis=1)\ntest_df = test_df.drop(['LotFrontage'], axis=1)\n#scatter plot MasVnrArea\/saleprice\nvar = 'MasVnrArea'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#dropping irrevalent variables\ntrain_df = train_df.drop(['MasVnrArea'], axis=1)\ntest_df = test_df.drop(['MasVnrArea'], axis=1)\n#scatter plot GarageCars\/saleprice\nvar = 'GarageCars'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#scatter plot GarageArea\/saleprice\nvar = 'GarageArea'\ndata = pd.concat([train_df['SalePrice'], train_df[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000), color='red');\n#dropping irrevalent variables\ntrain_df = train_df.drop(['GarageArea'], axis=1)\ntest_df = test_df.drop(['GarageArea'], axis=1)\n\"\"\"\n**Missing data**\nLet's analyze the missing data for training set and test set\n\"\"\"\n#missing data for training set\ntotal = train_df.isnull().sum().sort_values(ascending=False)\npercent = (train_df.isnull().sum()\/train_df.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(10)\n#missing data for test set\ntotal = test_df.isnull().sum().sort_values(ascending=False)\npercent = (test_df.isnull().sum()\/test_df.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(15)\n\"\"\"\n**Age_of_garage** is missing where there is no garage so we can fill the missing values by 0.  Same is the case for **BsmtFin**, **BsmtUnfSF** and **GarageCars**. For rest of the features, we will simply fill the missing values by mode value of that feature.\n\"\"\"\n# Age_of_garage is missing where there is no garage\ntrain_df['Age_of_garage'].fillna(0,inplace=True)\ntest_df['Age_of_garage'].fillna(0,inplace=True)\n#Treating missing values\ntrain_df['Electrical'].fillna(train_df['Electrical'].mode()[0],inplace=True)\ntest_df['MSZoning'].fillna(test_df['MSZoning'].mode()[0],inplace=True)\ntest_df['BsmtHalfBath'].fillna(test_df['BsmtHalfBath'].mode()[0],inplace=True)\ntest_df['BsmtFullBath'].fillna(test_df['BsmtFullBath'].mode()[0],inplace=True)\ntest_df['Functional'].fillna(test_df['Functional'].mode()[0],inplace=True)\ntest_df['Utilities'].fillna(test_df['Utilities'].mode()[0],inplace=True)\ntest_df['KitchenQual'].fillna(test_df['KitchenQual'].mode()[0],inplace=True)\ntest_df['SaleType'].fillna(test_df['SaleType'].mode()[0],inplace=True)\ntest_df['Exterior1st'].fillna(test_df['Exterior1st'].mode()[0],inplace=True)\ntest_df['Exterior2nd'].fillna(test_df['Exterior2nd'].mode()[0],inplace=True)\ntest_df['BsmtFin'].fillna(0,inplace=True)\ntest_df['BsmtUnfSF'].fillna(0,inplace=True)\ntest_df['GarageCars'].fillna(0,inplace=True)\n\"\"\"\nNext, we convert all categorical variables into numeric by Label Encoding\n\"\"\"\n# Converting all categorical variables into numeric by encoding the categories\nvar_mod = ['MSZoning','Street','Alley','LotShape','LandContour','Utilities','LotConfig','LandSlope','Neighborhood','Condition1','BldgType','HouseStyle','RoofStyle','RoofMatl','Exterior1st','Exterior2nd','MasVnrType','Foundation','BsmtQual','BsmtCond','BsmtExposure','Heating','HeatingQC','CentralAir','Electrical','KitchenQual','Functional','FireplaceQu','GarageType','GarageFinish','PavedDrive','PoolQC','Fence','MiscFeature','SaleType','SaleCondition']\nle = LabelEncoder()\nfor i in var_mod:\n    train_df[i] = le.fit_transform(train_df[i])\n    test_df[i] = le.fit_transform(test_df[i])\ntrain_df.dtypes\n#dropping irrevalent variables\ntrain_df = train_df.drop(['Id'], axis=1)\nX_train = train_df.drop(\"SalePrice\", axis=1)\nY_train = train_df[\"SalePrice\"]\nX_test  = test_df.drop(\"Id\", axis=1).copy()\nX_train.shape, Y_train.shape, X_test.shape\n\"\"\"\nAs you can see, we have 67 features currently which is huge. We will further reduce the dimensionality using *Principal Component Analysis(PCA).  *\n\"\"\"\npca = PCA(n_components=30)\nX_train_reduced=pca.fit_transform(X_train)\nX_train_reduced.shape\nX_test_reduced=pca.fit_transform(X_test)\nX_test_reduced.shape\n\"\"\"\nWe will define a generic function for model fitting and then we will fit models like *Linear Regression, Ridge Regression, Decision Tree Regressor, Random Forest Regressor *and *XGB regressor *\n\"\"\"\n# generic function\ndef modelfit(alg, dtrain_X, dtrain_Y, dtest_X):\n    #Fit the algorithm on the data\n    alg.fit(dtrain_X, dtrain_Y)\n        \n    #Predict training set:\n    dtrain_predictions = alg.predict(dtrain_X)\n\n    #Perform cross-validation:\n    cv_score = cross_validation.cross_val_score(alg, dtrain_X, dtrain_Y, cv=20, scoring='neg_mean_squared_error')\n    cv_score = np.sqrt(np.abs(cv_score))\n    \n    #Print model report:\n    print (\"\\nModel Report\")\n    print (\"RMSE : %.4g\" % np.sqrt(metrics.mean_squared_error(dtrain_Y.values, dtrain_predictions)))\n    print (\"CV Score : Mean - %.4g | Std - %.4g | Min - %.4g | Max - %.4g\" % (np.mean(cv_score),np.std(cv_score),np.min(cv_score),np.max(cv_score)))\n    \n    #Predict on testing data:\n    Y_pred = alg.predict(dtest_X)\n    \n    return Y_pred\n# Linear Regression Model\nalg1 = LinearRegression(normalize=True)\nY_pred=modelfit(alg1, X_train_reduced, Y_train, X_test_reduced)\n# Ridge Regression Model\nalg2 = Ridge(alpha=0.05,normalize=True)\nY_pred=modelfit(alg2, X_train_reduced, Y_train, X_test_reduced)\n# Decision Tree Model\nalg3 = DecisionTreeRegressor(max_depth=20, min_samples_leaf=300)\nY_pred=modelfit(alg3, X_train_reduced, Y_train, X_test_reduced)\n# Random Forest Model\nalg4 = RandomForestRegressor(n_estimators=400,max_depth=20, min_samples_leaf=100, n_jobs=4)\nY_pred=modelfit(alg4, X_train_reduced, Y_train, X_test_reduced)\n# XGB regressor\nalg5 = xgb.XGBRegressor(n_estimators=300, max_depth=2, learning_rate=0.1) \nY_pred=modelfit(alg5, X_train_reduced, Y_train, X_test_reduced)\n\"\"\"\nXGB regressor outperforms other models. So, we will tune its parameters to further improve the results.\n\"\"\"\n# Tuning of parameters\n# Create the parameter grid based on the results of random search \nparam_grid = {\n    'max_depth': [2, 3, 5, 7],\n    'learning_rate': [0.05, 0.1, 0.3],\n    'n_estimators': [200, 350, 450, 500]\n}\n# Create a based model\nXGBR = xgb.XGBRegressor()\n# Instantiate the grid search model\ngrid_search = GridSearchCV(estimator = XGBR, param_grid = param_grid, \n                          cv = 5, n_jobs = -1, verbose = 2)\n# Fit the grid search to the data\ngrid_search.fit(X_train_reduced, Y_train)\ngrid_search.best_params_\n# XGB regressor with tuned parameters\nalg6 = xgb.XGBRegressor(n_estimators=500, max_depth=3, learning_rate=0.05) \nY_pred=modelfit(alg6, X_train_reduced, Y_train, X_test_reduced)\n\"\"\"\nNext we will use Artificial Neural Network with two hidden layers.\n\"\"\"\n# Using ANN\n# Initialising the ANN\nalg7 = Sequential()\n\n# Adding the input layer and the first hidden layer\nalg7.add(Dense(units = 256, kernel_initializer = 'normal', activation = 'relu', input_dim = 30))\n\n# Adding the second hidden layer\nalg7.add(Dense(units = 256, kernel_initializer = 'normal', activation = 'relu'))\n\n# Adding the output layer\nalg7.add(Dense(units = 1, kernel_initializer = 'normal'))\n\n# Compiling the ANN\nalg7.compile(optimizer = 'adam', loss = 'mse')\n\n# Fitting the ANN to the Training set\nalg7.fit(X_train_reduced, Y_train, batch_size = 64, epochs = 800)\n\n# Predicting the Test set results\ny_pred = alg7.predict(X_test_reduced)\n\"\"\"\nBut the neural network has not outperformed our XGB regressor. So, we will submit the predictions made by XGB regressor.\n\"\"\"\nsubmission = pd.DataFrame({\n        \"Id\": test_df[\"Id\"],\n        \"SalePrice\": Y_pred\n    })\n\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '9cfc5a35297b99'}"}
{"id":"132525","text":"\"\"\"\nThe Following work is a part of the Medium Post an attempt to make everyone familiar with Confusion Matrix and related evaluation Metrics! \n\nYou can [read the Article here](https:\/\/medium.com\/@salrite\/demystifying-confusion-matrix-confusion-9e82201592fd). Please upvote the Kernel in-case you liked the Article. \nForged & Authorized Note, Binary Classifier based on the [UCI Dataset](https:\/\/archive.ics.uci.edu\/ml\/datasets\/banknote+authentication).\n\n![](https:\/\/img-aws.ehowcdn.com\/877x500p\/s3.amazonaws.com\/photography.prod.demandstudios.com\/8ac96de8-3f1f-438d-848a-c573e021532b.jpg)\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nimport os\nprint(os.listdir(\"..\/input\"))\nimport itertools\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ndf = pd.read_csv('..\/input\/BankNote_Authentication.csv')\ndf.head(5)\n#Class is our Target Label, with zero indicating the Bank Note is Forged and 1 Indicating it is Legit\ndf['class'].value_counts() #to check if the data is equally balanced between the two classes for prediction\n#defining features and target variable\ny = df['class']\nX = df.drop(columns = ['class'])\n\n#splitting the data into train and test set \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n#Predicting using Logistic Regression for Binary classification \nfrom sklearn.linear_model import LogisticRegression\nLR = LogisticRegression()\nLR.fit(X_train,y_train) #fitting the model \ny_pred = LR.predict(X_test) #prediction \n#Evaluation \ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    print(cm)\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.tight_layout()\n\n\n# Compute confusion matrix\ncnf_matrix = confusion_matrix(y_test, y_pred)\nnp.set_printoptions(precision=2)\n\n# Plot non-normalized confusion matrix\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=['Forged','Authorized'],\n                      title='Confusion matrix, without normalization')\n#extracting true_positives, false_positives, true_negatives, false_negatives\ntn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()\nprint(\"True Negatives: \",tn)\nprint(\"False Positives: \",fp)\nprint(\"False Negatives: \",fn)\nprint(\"True Positives: \",tp)\n#Accuracy (%) \nAccuracy = (tn+tp)*100\/(tp+tn+fp+fn) \nprint(\"Accuracy {:0.2f}%\".format(Accuracy))\n#Precision \nPrecision = tp\/(tp+fp) \nprint(\"Precision {:0.2f}\".format(Precision))\n#Recall \nRecall = tp\/(tp+fn) \nprint(\"Recall {:0.2f}\".format(Recall))\n#F1 Score\nf1 = (2*Precision*Recall)\/(Precision + Recall)\nprint(\"F1 Score {:0.2f}\".format(f1))\n#Fbeta score\ndef fbeta(precision, recall, beta):\n    return ((1+pow(beta,2))*precision*recall)\/(pow(beta,2)*precision + recall)\n            \nf2 = fbeta(Precision, Recall, 2)\nf0_5 = fbeta(Precision, Recall, 0.5)\n\nprint(\"F2 {:0.2f}\".format(f2))\nprint(\"\\nF0.5 {:0.2f}\".format(f0_5))\n#Specificity \nSpecificity = tn\/(tn+fp)\nprint(\"Specificity {:0.2f}\".format(Specificity))\n#ROC\nimport scikitplot as skplt #to make things easy\ny_pred_proba = LR.predict_proba(X_test)\nskplt.metrics.plot_roc_curve(y_test, y_pred_proba)\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'f3ccc240afc28b'}"}
{"id":"61040","text":"\"\"\"\n# \u30e9\u30a4\u30d6\u30e9\u30ea\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport datetime\nimport random\nimport glob\nimport cv2\nimport os\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import StratifiedKFold\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import BatchNormalization, Activation, Dropout, Dense\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import BatchNormalization,Activation,Dropout,Dense,concatenate,Input\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.layers import Flatten, Conv2D, MaxPooling2D,GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, Callback, ReduceLROnPlateau\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Input\nfrom tensorflow.keras import regularizers\nfrom keras.applications.resnet50 import ResNet50\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom category_encoders import OrdinalEncoder, OneHotEncoder, TargetEncoder\nfrom tensorflow.keras.applications import VGG16, VGG19\n\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n\n# \u4e71\u6570\u30b7\u30fc\u30c9\u56fa\u5b9a\nseed_everything(2020)\n\n# for dirname, _, filenames in os.walk('\/kaggle\/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\"\"\"\n# \u6570\u5024\u30c7\u30fc\u30bf\u306e\u8aad\u307f\u8fbc\u307f\n\"\"\"\ntrain = pd.read_csv('\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/train.csv')\ntrain = train.sort_values('id')\ntest = pd.read_csv('\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/test.csv')\ntest = test.sort_values('id')\n#display(train.shape), display(test.shape)\n#display(train.head()), display(test.head())\n#\u63d0\u51fa\u30d5\u30a1\u30a4\u30eb\nsubmission = pd.read_csv('\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/sample_submission.csv', index_col=0)\n#display(submission.head())\ncols=['bedrooms','bathrooms','area','zipcode']\ntarget=['price']\n#\u6b20\u6e2c\u5024\ntrain[cols]=train[cols].fillna(-99)\ntest[cols] = test[cols].fillna(-99)\n# area\ntrain['area']=train['area'].astype(str).str[:1]\ntest['area']=test['area'].astype(str).str[:1]\n\ntemp = train.groupby(['area'],as_index=False)[target].mean()\ntemp = temp.rename(columns={'price': 'area_price'})\n\ntrain_1 = pd.merge(train, temp, on='area', how='left')\ntrain_1 = train_1.drop('area', axis=1)\ntrain = train_1.rename(columns={'area_price': 'area'})\n\ntest_1 = pd.merge(test, temp, on='area', how='left')\ntest_1 = test_1.drop('area', axis=1)\ntest = test_1.rename(columns={'area_price': 'area'})\n\n#display(train.head())\n#display(test.head())\n# zipcode\ntrain['zipcode']=train['zipcode'].astype(str).str[:1]\ntest['zipcode']=test['zipcode'].astype(str).str[:1]\n\ntemp = train.groupby(['zipcode'],as_index=False)[target].mean()\ntemp = temp.rename(columns={'price': 'zipcode_price'})\n\ntrain_1 = pd.merge(train, temp, on='zipcode', how='left')\ntrain_1 = train_1.drop('zipcode', axis=1)\ntrain = train_1.rename(columns={'zipcode_price': 'zipcode'})\n\ntest_1 = pd.merge(test, temp, on='zipcode', how='left')\ntest_1 = test_1.drop('zipcode', axis=1)\ntest = test_1.rename(columns={'zipcode_price': 'zipcode'})\n\n#display(train.head()), display(test.head())\ntrain[cols]=train[cols].fillna(-99)\ntest[cols] = test[cols].fillna(-99)\n\n# \u6b63\u898f\u5316\nscaler = StandardScaler()\n#X_all = pd.concat([train, test], axis=0)\ntrain[cols] = scaler.fit_transform(train[cols])\ntest[cols] = scaler.fit_transform(test[cols])\n#train = X_all.iloc[:train.shape[0], :]\n#test = X_all.iloc[train.shape[0]:, :]\n#display(train.head())\n#display(test.head())\n#\u6b20\u6e2c\u5024\ntrain[cols]=train[cols].fillna(-99)\ntest[cols] = test[cols].fillna(-99)\n\"\"\"\n# \u753b\u50cf\u51e6\u7406\n\"\"\"\n#\u753b\u50cf\u3092\u7d50\u5408\u3057\u3066\u8aad\u307f\u8fbc\u307f\ndef load_images_unit(df,inputPath,size):\n    images = []\n    for i in df['id']:\n        basePath0 = os.path.sep.join([inputPath, \"{}_{}*\".format(i,'bathroom')])\n        basePath1 = os.path.sep.join([inputPath, \"{}_{}*\".format(i,'bedroom')])\n        basePath2 = os.path.sep.join([inputPath, \"{}_{}*\".format(i,'frontal')])\n        basePath3 = os.path.sep.join([inputPath, \"{}_{}*\".format(i,'kitchen')])\n        housePaths0 = sorted(list(glob.glob(basePath0)))\n        housePaths1 = sorted(list(glob.glob(basePath1)))\n        housePaths2 = sorted(list(glob.glob(basePath2)))\n        housePaths3 = sorted(list(glob.glob(basePath3)))\n        for housePath in housePaths3:\n            image0 = cv2.imread(housePaths0[0])\n            image1 = cv2.imread(housePaths1[0])\n            image2 = cv2.imread(housePaths2[0])\n            image3 = cv2.imread(housePaths3[0])\n            image0 = cv2.cvtColor(image0, cv2.COLOR_BGR2RGB)\n            image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)\n            image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)\n            image3 = cv2.cvtColor(image3, cv2.COLOR_BGR2RGB)\n            image0 = cv2.resize(image0, (size, size))\n            image1 = cv2.resize(image1, (size, size))\n            image2 = cv2.resize(image2, (size, size))\n            image3 = cv2.resize(image3, (size, size))\n            image_h0 = cv2.hconcat([image0, image1])\n            image_h1 = cv2.hconcat([image2, image3])\n            image = cv2.vconcat([image_h0, image_h1])\n        images.append(image)\n    return np.array(images) \/ 255.0\n\n# load train images\ninputPath = '\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/images\/train_images\/'\ninputPath2 = '\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/images\/test_images\/'\nsize = 32\ntrain_images = load_images_unit(train,inputPath,size)\ntest_images = load_images_unit(test,inputPath2,size)\n#display(train_images.shape)\n#display(train_images[0][0][0])\n#\u753b\u50cf\u3092\u305d\u308c\u305e\u308c\u8aad\u307f\u8fbc\u307f\ndef load_images(df,inputPath,size,roomType):\n    images = []\n    for i in df['id']:\n        basePath = os.path.sep.join([inputPath, \"{}_{}*\".format(i,roomType)])\n        housePaths = sorted(list(glob.glob(basePath)))\n        for housePath in housePaths:\n            image = cv2.imread(housePath)\n            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n            image = cv2.resize(image, (size, size))\n        images.append(image)\n    return np.array(images) \/ 255.0\n\n# load train images\ninputPath = '\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/images\/train_images\/'\ninputPath2 = '\/kaggle\/input\/5th-datarobot-ai-academy-deep-learning\/images\/test_images\/'\nsize = 64\nroomType = 'bathroom'\ntrain_bathroom = load_images(train,inputPath,size,roomType)\ntest_bathroom = load_images(test,inputPath2,size,roomType)\nroomType = 'bedroom'\ntrain_bedroom = load_images(train,inputPath,size,roomType)\ntest_bedroom = load_images(test,inputPath2,size,roomType)\nroomType = 'frontal'\ntrain_frontal = load_images(train,inputPath,size,roomType)\ntest_frontal = load_images(test,inputPath2,size,roomType)\nroomType = 'kitchen'\ntrain_kitchen = load_images(train,inputPath,size,roomType)\ntest_kitchen = load_images(test,inputPath2,size,roomType)\n#display(train_images.shape)\n#display(train_images[0][0][0])\ndef create_model(inputShape ,TableShape):    \n    \n    backbone = VGG16(weights='imagenet',\n                     include_top=False,\n                     input_shape=inputShape)\n    \n    for layer in backbone.layers[:15]:\n        layer.trainable = False\n\n    vgg = Sequential(layers=backbone.layers)   \n    \n    vgg.add(GlobalAveragePooling2D())\n    vgg.add(Dense(units=256, activation='relu',kernel_initializer='he_normal')) \n    vgg.add(Dropout(0.2))\n    vgg.add(Dense(units=32, activation='relu',kernel_initializer='he_normal'))    \n    vgg.add(Dense(units=1, activation='linear'))    \n    \n\n    L1_L2 = regularizers.l1_l2(l1=0.005,l2=0.005)\n    input_df=Input(shape=(len(TableShape),))\n    \n    nn = Sequential()\n    \n    nn = Dense(units=256,input_shape=(TableShape,),kernel_initializer='he_normal',activation='relu')(input_df)\n    nn = BatchNormalization()(nn)\n    \n    nn = Dense(units=128,kernel_initializer='he_normal',activation='relu')(nn)\n    nn = Dropout(0.2)(nn)\n    \n    nn = Dense(units=64,kernel_initializer='he_normal',activation='relu')(nn)\n    nn = Dropout(0.2)(nn)\n    \n    nn = Dense(units=32,kernel_initializer='he_normal',activation='relu',kernel_regularizer=L1_L2)(nn)\n    nn = Dropout(0.2)(nn)\n    \n    nn = Model(inputs=input_df, outputs=nn)\n\n\n    merge = concatenate([vgg.output, nn.output])\n#     merge = concatenate([vgg.output, cnn.output, nn.output])\n    \n    mm = Dense(units=256, activation='relu',kernel_initializer='he_normal')(merge)\n    mm = Dropout(0.2)(mm)\n    mm = Dense(units=32, activation='relu',kernel_initializer='he_normal',kernel_regularizer=L1_L2)(mm)\n    mm = Dropout(0.2)(mm)\n    mm = Dense(units=1, activation='linear')(mm)\n    model = Model(inputs=[vgg.input,nn.input],outputs=mm) \n    model.compile(loss='mape', optimizer='adam', metrics=['mape'])\n    \n    return model\ntrain_x = train.drop(['price', 'id'], axis=1)\ntrain_y = train.price\ntest_x = test.drop(['id'], axis=1)\ndef mean_absolute_percentage_error(y_true, y_pred): \n    y_true, y_pred = np.array(y_true), np.array(y_pred)\n    return np.mean(np.abs((y_true - y_pred) \/ y_true)) * 100\n#CV\nscores = []\n\nkf = KFold(n_splits=3, shuffle=True)\n\nfor i, (train_ix, valid_ix) in enumerate(kf.split(train_x)):\n\n    train_x_, train_y_ = train_x.iloc[train_ix].values, train_y.iloc[train_ix].values\n    valid_x_, valid_y_ = train_x.iloc[valid_ix].values, train_y.iloc[valid_ix].values\n    \n    train_image_x_ = train_images[train_ix]\n    valid_image_x_ = train_images[valid_ix]\n    \n    # callback parameter\n    filepath = \"cnn_best_model_CV\"+str(i)+\".hdf5\" \n    es = EarlyStopping(patience=5, mode='min', verbose=1) \n    checkpoint = ModelCheckpoint(monitor='val_loss', filepath=filepath, save_best_only=True, mode='auto') \n    reduce_lr_loss = ReduceLROnPlateau(monitor='val_loss',  patience=5, verbose=1,  mode='min')\n\n    # \u8a13\u7df4\u5b9f\u884c\n    inputShape = (size, size, 3)\n    tableShape = cols\n    \n    model = create_model(inputShape,tableShape)\n    history = model.fit([train_image_x_, train_x_],train_y_, \n                    validation_data=([valid_image_x_, valid_x_],valid_y_),\n                    epochs=100, batch_size=32,callbacks=[es, checkpoint, reduce_lr_loss])\n    \n    # load best model weights\n    if os.path.exists(filepath):\n        model.load_weights(filepath)\n\n    # \u8a55\u4fa1\n    valid_pred = model.predict([valid_image_x_, valid_x_],batch_size=5).reshape((-1,1))\n    mape_score = mean_absolute_percentage_error(valid_y_, valid_pred)\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(len(loss))\nplt.plot(epochs, loss, 'bo' ,label = 'training loss')\nplt.plot(epochs, val_loss, 'b' , label= 'validation loss')\nplt.title('Training and Validation loss')\nplt.legend()\nplt.show()\nplot_model(model, to_file='cnn.png')\nmodel.summary()\nprint (mape_score)\nprice1 = model.predict([test_images,test_x], batch_size=16).reshape((-1,1))\n#price1\nsubmission.price = price1 \nsubmission.to_csv('.\/submission.csv')\nsubmission.head()","meta":"{'source': 'AI4Code', 'id': '7096ea1c6039b3'}"}
{"id":"120772","text":"\"\"\"\n # The World Happiness Report - Kaggle Master Project\n\"\"\"\n\"\"\"\n## Gerekli K\u00fct\u00fcphanelerin Import Edilmesi\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n# Visualization\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-whitegrid')\nimport seaborn as sns\n\n# Plotly\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True) # #do not miss this line\nimport plotly as py\nimport plotly.graph_objs as go\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## Verilerin \u0130ncelenmesi\n\"\"\"\ndata_2015 = pd.read_csv('..\/input\/world-happiness\/2015.csv')\ndata_2016 = pd.read_csv('..\/input\/world-happiness\/2016.csv')\ndata_2017 = pd.read_csv('..\/input\/world-happiness\/2017.csv')\ndata_2018 = pd.read_csv('..\/input\/world-happiness\/2018.csv')\ndata_2019 = pd.read_csv('..\/input\/world-happiness\/2019.csv')\ndata_2015.head()\ndata_2016.head()\ndata_2017.head()\ndata_2018.head()\ndata_2019.head()\ndata_2015.info()\ndata_2016.info()\ndata_2017.info()\ndata_2018.info()\ndata_2019.info()\ndisplay(data_2015.describe())\nprint('2015 '+'*' * 40)\ndisplay(data_2016.describe())\nprint('2016 '+'*' * 40)\ndisplay(data_2017.describe())\nprint('2017 '+'*' * 40)\ndisplay(data_2018.describe())\nprint('2018 '+'*' * 40)\ndisplay(data_2019.describe())\nprint('2019 '+'*' * 40)\ndata_2015 = data_2015.rename(columns={\"Happiness Rank\":\"Rank\", \"Happiness Score\":\"Score\", \"Economy (GDP per Capita)\": \"Economy\", \n                                      \"Health (Life Expectancy)\": \"Life_Expectancy\", \"Trust (Government Corruption)\":\"Corruption\"})\n\ndata_2016 = data_2016.rename(columns={\"Happiness Rank\":\"Rank\",\"Happiness Score\":\"Score\", \"Economy (GDP per Capita)\": \"Economy\", \n                                      \"Health (Life Expectancy)\": \"Life_Expectancy\", \"Trust (Government Corruption)\":\"Corruption\"})\n\ndata_2017 = data_2017.rename(columns={\"Happiness.Rank\":\"Rank\", \"Happiness.Score\":\"Score\", \"Economy..GDP.per.Capita.\": \"Economy\", \n                                      \"Health..Life.Expectancy.\": \"Life_Expectancy\", \"Trust..Government.Corruption.\":\"Corruption\"})\n\ndata_2018 = data_2018.rename(columns={\"Overall rank\":\"Rank\", \"Country or region\":\"Country\",\"GDP per capita\":\"Economy\", \n                                      \"Healthy life expectancy\":\"Life_Expectancy\",\"Freedom to make life choices\":\"Freedom\", \n                                      \"Perceptions of corruption\":\"Corruption\"})\n\ndata_2019 = data_2019.rename(columns={\"Overall rank\":\"Rank\", \"Country or region\":\"Country\", \"GDP per capita\": \"Economy\", \n                                      \"Healthy life expectancy\": \"Life_Expectancy\", \"Freedom to make life choices\":\"Freedom\", \n                                      \"Perceptions of corruption\":\"Corruption\"})\n\"\"\"\n1) \u00dclkemiz T\u00fcrkiye'yi baz alacak olursak; 2015-2019 y\u0131llar\u0131 aras\u0131nda insanlar\u0131n mutlu olmas\u0131na etki eden fakt\u00f6rler y\u0131llara g\u00f6re neler ve zamanla nas\u0131l de\u011fi\u015fmi\u015f?\n\"\"\"\ndisplay(data_2015[data_2015.Country=='Turkey'])\n\ndisplay(data_2016[data_2016.Country=='Turkey'])\n\ndisplay(data_2017[data_2017.Country=='Turkey'])\n\ndisplay(data_2018[data_2018.Country=='Turkey'])\n\ndisplay(data_2019[data_2019.Country=='Turkey'])\n# T\u00fcrkiye'ye ait verilerin tek bir dataframe'de g\u00f6sterilmesi\ndatas = [data_2015, data_2016, data_2017, data_2018, data_2019]\nyears = [2015,2016,2017,2018,2019]\nrank_list = []\nscore_list = []\neconomy_list = []\nlife_list = []\nfreedom_list = []\ngenerosity_list = []\ncorruption_list = []\n\nfor i in range(len(datas)):\n    rank_list.append((datas[i][datas[i]['Country']=='Turkey']['Rank']).values[0])\n    score_list.append((datas[i][datas[i]['Country']=='Turkey']['Score']).values[0])\n    economy_list.append((datas[i][datas[i]['Country']=='Turkey']['Economy']).values[0])\n    life_list.append((datas[i][datas[i]['Country']=='Turkey']['Life_Expectancy']).values[0])\n    freedom_list.append((datas[i][datas[i]['Country']=='Turkey']['Freedom']).values[0])\n    generosity_list.append((datas[i][datas[i]['Country']=='Turkey']['Generosity']).values[0])\n    corruption_list.append((datas[i][datas[i]['Country']=='Turkey']['Corruption']).values[0])\n    \n    \nturkey_data = pd.DataFrame({\"years\":years,\"rank\": rank_list, \"score\":score_list, \"economy\":economy_list,\"life_expectancy\":life_list,\n                            \"freedom\":freedom_list, \"generosity\": generosity_list, \"corruption\":corruption_list})\nturkey_data\ntr_data = turkey_data.drop(['years'], axis=1)\nf,ax = plt.subplots(figsize=(6, 6))\nheat_map = sns.heatmap(tr_data.corr(), annot=True, linewidths=0.6, fmt= '.2f',ax=ax, cmap=\"coolwarm\")\nheat_map.set_yticklabels(heat_map.get_yticklabels(), rotation=0)\nplt.show()\n\"\"\"\nT\u00fcrkiye'deki insanlar\u0131n mutlu olmas\u0131na etki eden en \u00f6nemli fakt\u00f6r\u00fcn \u00d6zg\u00fcrl\u00fck(Freedom) oldu\u011fu g\u00f6r\u00fclmektedir. \n* Ekomomik Durum (Economy GDP per capita): 0.61 - pozitif korelasyon\n* Yolsuzluk (Corruption): -0.76 - negatif korelasyon\n* Sa\u011fl\u0131kl\u0131 Ya\u015fam Beklentisi (Healthy life expectancy) : -0.59 - negatif korelasyon\n\nEkonomi, yolsuzluk alg\u0131lar\u0131 ve ya\u015fam beklentisi de mutlu olmas\u0131na etki eden di\u011fer \u00f6nemli fakt\u00f6rlerdir.\n\"\"\"\nimport plotly.graph_objs as go\n\ntrace1=go.Bar(\n                x=years,\n                y=turkey_data.economy,\n                name=\"Economy\",\n                marker=dict(color = 'rgba(156, 30, 130, 0.7)',\n                           line=dict(color='rgb(0,0,0)',width=1.9)),\n                text='Economy')\ntrace2=go.Bar(\n                x=years,\n                y=turkey_data.life_expectancy,\n                name=\"Life Expectancy\",\n                marker=dict(color = 'rgba(240,120,10 , 0.7)', \n                           line=dict(color='rgb(0,0,0)',width=1.9)),\n                text='Life Expectancy')\n\ntrace3=go.Bar(\n                x=years,\n                y=turkey_data.freedom,\n                name=\"Freedom\",\n                marker=dict(color = 'rgba( 50, 240,120 , 0.7)',\n                           line=dict(color='rgb(0,0,0)',width=1.9)),\n                text='Freedom')\ntrace4=go.Bar(\n                x=years,\n                y=turkey_data.generosity,\n                name=\"Generosity\",\n                marker=dict(color = 'rgba(200, 250,20 , 0.7)',\n                           line=dict(color='rgb(0,0,0)',width=1.9)),\n                text='Generosity')\ntrace5=go.Bar(\n                x=years,\n                y=turkey_data.corruption,\n                name=\"Corruption\",\n                marker=dict(color = 'rgba(200, 10,10 , 0.7)',\n                           line=dict(color='rgb(0,0,0)',width=1.9)),\n                text='Corruption')\n\nedit_df=[trace1,trace2,trace3,trace4,trace5]\nlayout=go.Layout(barmode=\"group\",title=\"2015-2019 aras\u0131ndaki y\u0131llara g\u00f6re T\u00fcrkiye'nin mutluluk raporu\")\nfig=dict(data=edit_df,layout=layout)\nplt.savefig('graph.png')\niplot(fig)\n# Y\u0131llara g\u00f6re de\u011fi\u015fim grafikleri\nfig, ax =plt.subplots(nrows=2,ncols=3, figsize=(16,6))\nsns.lineplot(x = \"years\", y = \"score\", data = turkey_data,color=\"coral\", ax=ax[0][0])\nsns.lineplot(x = \"years\", y = \"economy\", data = turkey_data,color=\"red\", ax=ax[0][1])\nsns.lineplot(x = \"years\", y = \"life_expectancy\", data = turkey_data, color=\"purple\", ax=ax[0][2])\nsns.lineplot(x = \"years\", y = \"freedom\", data = turkey_data, color=\"green\", ax=ax[1][0])\nsns.lineplot(x = \"years\", y = \"generosity\", data = turkey_data, color=\"blue\", ax=ax[1][1])\nsns.lineplot(x = \"years\", y = \"corruption\", data = turkey_data, color=\"black\", ax=ax[1][2])\nplt.show()\n\"\"\"\n2) Sadece 2019 verisini baz al\u0131rsak; 2019 y\u0131l\u0131ndaki en mutlu \u00fclke hangisidir? Hangi fakt\u00f6r\/fakt\u00f6rler en mutlu \u00fclke olmas\u0131n\u0131 sa\u011flam\u0131\u015f olabilir? G\u00f6rselle\u015ftirerek ifade etmenizi bekliyoruz.\n\"\"\"\n# 2019 y\u0131l\u0131n\u0131n en mutlu ilk 10 \u00fclkesi\ndata_2019.head(10)\nf,ax = plt.subplots(figsize=(8, 8))\nheat_map = sns.heatmap(data_2019.corr(), annot=True, linewidths=0.6, fmt= '.2f',ax=ax, cmap=\"coolwarm\")\nheat_map.set_yticklabels(heat_map.get_yticklabels(), rotation=0)\nplt.show()\n\"\"\"\n2019 y\u0131l\u0131n\u0131n en mutlu \u00fclkesi Finlandiya olmu\u015ftur. \n\n* Ekomomik durum (Economy GDP per capita): 0.79 - pozitif korelasyon\n* Sosyal destek (Social support): 0.78 - pozitif korelasyon\n* Sa\u011fl\u0131kl\u0131 ya\u015fam beklentisi (Healthy life expectancy): 0.78 - pozitif korelasyon\n* \u00d6zg\u00fcrl\u00fck (Freedom): 0.57 - pozitif korelasyon\n\nBu fakt\u00f6rlerin etkisi mutluluk skoruna yans\u0131m\u0131\u015ft\u0131r. Mutluluk skorunun en y\u00fcksek olmas\u0131 da Finlandiya'n\u0131n en mutlu \u00fclke olmas\u0131n\u0131 sa\u011flam\u0131\u015ft\u0131r.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'de2c686219fd59'}"}
{"id":"29953","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as  plt\nimport sklearn\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\nI have imported an updated version of the dataset with an additional column for risk profile- Good\/Bad to make predictions with the dataset whether the transaction is likely to be a fraud or genuine.\n\"\"\"\ndata= pd.read_csv(\"..\/input\/german-credit-data-with-risk\/german_credit_data.csv\")\ndata\n\ndata= data.drop(['Unnamed: 0'], axis=1)\ndata\n\"\"\"\nWe'll first convert the target variable (**Risk**) to numeric form so that we can make some visualizations. We'll be using **LabelBinarize**r function present in the sklearn library for that purpose,\n\"\"\"\nfrom sklearn.preprocessing import LabelBinarizer\nlb= LabelBinarizer()\ndata[\"Risk\"]= lb.fit_transform(data[\"Risk\"])\nsns.countplot('Risk', data=data)\nplt.title('Risk Distribution', fontsize=14)\nplt.show()\nax = sns.scatterplot(x=\"Duration\", y=\"Age\", hue=\"Risk\", data=data)\n\"\"\"\nFrom the scatterplot we can see a lot of straight lines. Duration is a continous variable from 0-70 . The lines show that it is practically possible to convert them into categories of Time duration groups. \n\"\"\"\nax = sns.scatterplot(x=\"Age\", y=\"Duration\", hue=\"Risk\", data=data)\n\"\"\"\nSimiliar observation can be made regarding Age columns. They are organized into groups for various age segments. \nNext what we will be doing is creating categorical columns for both duration and Ages and plot a histogram to see the frequency distribution plot.\n\"\"\"\nax = sns.scatterplot(x=\"Credit amount\", y=\"Age\", hue=\"Risk\", data=data)\n\"\"\"\nAn inference that can be made regarding the Credit amount is that people with lower credit amount have a risk possibiity of 1, i.e. those transactions are likely to be genuine.\n\"\"\"\nfrom scipy.stats import norm\n\nf, (ax1,ax2) =plt.subplots(1,2, figsize=(20, 6))\n\ncredit_amount_dist = data['Credit amount'].loc[data['Risk'] == 1].values\nsns.distplot(credit_amount_dist,ax=ax1, fit=norm, color='#FB8861')\nax1.set_title('Credit amount distribution for good transactions', fontsize=14)\n\ncredit_amount_dist = data['Credit amount'].loc[data['Risk'] == 0].values\nsns.distplot(credit_amount_dist,ax=ax2, fit=norm, color='#56F9BB')\nax2.set_title('Credit amount distribution for bad transactions', fontsize=14)\n\n\"\"\"\nThe distribution is uneven in the sense that there are nearly 700 good transactions and 300 bad transactions\nThis is a very likely scenario because from a dataset of large no. of transactions, there are obviously more no of genuine transactions.\nBasically, our dataset is imbalanced as a primitive model which preicts 1 always will also obtain an accuracy of 70% .\n2 things can be done: \n1. Resample (Over-sample\/ Under-sample) the dataset and obtain an even distribution of the 2 classes.\n2. Use the precision\/Recall scores to evaluate the model.\nWe'll first make visualizations on our dataset, and then use these techniques.\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nSC= StandardScaler()\ncredit=data['Credit amount'].values\ncredit= credit.reshape(-1,1)\ndata[\"Credit amount\"]= SC.fit_transform(credit)\nSaving_accounts= data[\"Saving accounts\"]\nSaving_accounts.isnull().values.sum()\n\n\nChecking_accounts= data[\"Checking account\"]\nChecking_accounts.isnull().values.sum()\n\n\n\"\"\"\nUpon analysis, we notice that there are only 2 columns which have missing values, Savings account and Checking account.  It is likely that there were no mistakes in updating the datasets, but the users didnt actually have a savings or a checking account. We'll impute the 'NaN' by 'NoSavingAcc'\/ 'NoChecAcc and only then. we will LabelEncode\/ OneHotEncode the data. \n\"\"\"\ndata[\"Saving accounts\"].fillna('NoSavingAcc', inplace= True)\ndata[\"Checking account\"].fillna('NoCheckAcc', inplace= True)\ninterval = (0, 12, 24, 36, 48, 60, 72, 84)\ncats = ['year1', 'year2', 'year3', 'year4', 'year5', 'year6', 'year7']\ndata[\"Duration\"] = pd.cut(data.Duration, interval, labels=cats)\n\"\"\"\nWe'll convert age column into a categorical column by creating intervals . This will help us know the customer base in a broader sense. We'll create an interval for Students, Youth, Adults and Senior Citizens.\n\"\"\"\ninterval = (18, 25, 35, 60, 120)\n\ncats = ['Student', 'Youth', 'Adult', 'Senior']\ndata[\"Age\"] = pd.cut(data.Age, interval, labels=cats)\ndata\n\"\"\"\nNow, we'll encode the categorial data into 0s and 1s creating seperate columns, and we will aslso take care of the dummy variable trap using drop_first feature. Our data is now encoded and we'll drop the original features\n\"\"\"\ndata = data.merge(pd.get_dummies(data.Purpose, drop_first=True, prefix='Purpose'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data.Sex, drop_first=True, prefix='Sex'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data[\"Saving accounts\"], drop_first=True, prefix='Savings'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data[\"Checking account\"], drop_first=True, prefix='Check'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data.Housing, drop_first=True, prefix='Housing'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data.Job, drop_first=True, prefix='Job'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data.Duration, drop_first=True, prefix='Duration'), left_index=True, right_index=True)\ndata = data.merge(pd.get_dummies(data.Age, drop_first=True, prefix='Age'), left_index=True, right_index=True)\ndel data[\"Checking account\"]\ndel data[\"Saving accounts\"]\ndel data[\"Job\"]\ndel data[\"Duration\"]\ndel data[\"Sex\"]\ndel data[\"Purpose\"]\ndel data[\"Housing\"]\ndel data[\"Age\"]\nX= data.drop('Risk', axis= 1)\ny=data[\"Risk\"]\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.25, random_state= 0)\n\nX_train\nfrom sklearn.decomposition import TruncatedSVD\nsvd = TruncatedSVD(n_components=17, n_iter=7, random_state= 0)\nX_train_svd= svd.fit_transform(X_train)\nexplained_variance=svd.explained_variance_ratio_\nexplained_variance\nwith plt.style.context('dark_background'):\n    plt.figure(figsize=(10, 10))\n    plt.bar(range(17), explained_variance, alpha=0.5, align='center',\n            label='individual explained variance')\n    plt.ylabel('Explained variance ratio')\n    plt.xlabel('Principal components')\n    plt.legend(loc='best')\n    plt.tight_layout()\nX_train_svd= pd.DataFrame(X_train_svd)\nX_train_svd\nX_test_svd= svd.transform(X_test)\n\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report #To evaluate our model\nfrom sklearn.model_selection import GridSearchCV\n# Algorithmns models to be compared\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom xgboost import XGBClassifier\nclassifier = LogisticRegression()\nparameters = {\"penalty\": ['l1', 'l2'], 'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]}\ngrid_search = GridSearchCV(estimator= classifier,param_grid= parameters, cv=5,  n_jobs= -1)\ngrid_search.fit(X_train, y_train)\ny_pred = grid_search.predict(X_test)\n\ncm= confusion_matrix(y_test, y_pred)\nlabels = ['Bad', 'Good']\nprint(classification_report(y_test, y_pred, target_names=labels))\nparameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}\nsvc = SVC()\ngrid_search = GridSearchCV(estimator= svc, param_grid= parameters, cv=5, n_jobs= -1)\ngrid_search.fit(X_train, y_train)\ny_pred = grid_search.predict(X_test)\ncm= confusion_matrix(y_test, y_pred)\nlabels = ['Bad', 'Good']\nprint(classification_report(y_test, y_pred, target_names=labels))\nparameters = { \n    'n_estimators': [200, 500],\n    'max_features': ['auto', 'sqrt', 'log2'],\n    'max_depth' : [4,5,6,7,8],\n 'criterion' :['gini', 'entropy']\n}\nclassifier= RandomForestClassifier()\ngrid_search= GridSearchCV(estimator=classifier, param_grid=parameters, cv= 5, n_jobs= -1)\ngrid_search.fit(X_train, y_train)\ny_pred = grid_search.predict(X_test)\ncm= confusion_matrix(y_test, y_pred)\nlabels = ['Bad', 'Good']\nprint(classification_report(y_test, y_pred, target_names=labels))\nclassifier= XGBClassifier()\nclassifier.fit(X_train, y_train)\ny_pred= classifier.predict(X_test)\ncm= confusion_matrix(y_test, y_pred)\nlabels = ['Bad', 'Good']\nprint(classification_report(y_test, y_pred, target_names=labels))","meta":"{'source': 'AI4Code', 'id': '3711b0775af9a2'}"}
{"id":"119405","text":"\"\"\"\n# Poisonous vs. Edible Mushroom Classification \n\"\"\"\n\"\"\"\n### Table of contents\n1. [Introduction](#introduction)\n2. [Data Import\/Cleaning](#import)\n3. [Feature Selection](#feat_select)\n    1. [Data Exploration](#exp)\n4. [PCA Visualiztion](#pca)\n5. [Kmeans Visualization](#kmean)\n6. [Linear Classifiers](#lin)\n    1. [Logistic Regression](#logreg)\n    2. [SVM](#svm)\n7. [Bagging Classifiers](#bag)\n    1. [GradientBoost](#bag)\n    2. [XGBoost](#xgb)\n8. [Random Forest Classifier](#trees)\n\"\"\"\n\"\"\"\n#### Synopsis <a name=\"introduction\"><\/a>\nThe following analysis will explore the kaggle Mushroom Classification dataset (https:\/\/www.kaggle.com\/uciml\/mushroom-classification). Several ML models will be explored for their ability to classify mushrooms as poisonous or edible based off of the provided data. \n\nBoth unsupervised and supervised methods will be used, as well as regression and ensemble methods for a rounded look at how different models work with categorical datasets. \n\"\"\"\n\"\"\"\n#### Mushrooms:\nMushrooms come in all shapes, sizes, colours, and flavours--as the saying goes: every mushroom is edible at least <i>once<\/i>.\n\nMushroom identification is a multifaceted process, where several important features of the fruiting body are taken into account before determining edibility. In addition to physical factors, the time of season and where a mushroom fruits (dirt, grass, manure, on a tree, on a fallen log, etc.) are also important considerations when id'ing fungi. Id'ing should always be done by an experienced mushroom hunter with local knowledge. \n\n#### Quick Poisonous Mushroom Identifiers\n* Spore Print: Spores are collected by placing a mushroom cap facedown over a sheet of paper or mirror. Different species' spores will be specific shades\/colours, for example genus <a href=\"https:\/\/en.wikipedia.org\/wiki\/Amanita\"><i>Amanita<\/i><\/a> will spore print white--poison. \n* Fruiting Body: Several dispersal mechanisms for spores have evolved; between gilled, porous, sac or puffball fungi poisonous species may all mimic edible look-a-likes. \n* Bruising\/Color: Certain species that bruise dark when handled can sometimes indicate poison or inedibility. \n* Morphology: \n   * The genus <a href=\"https:\/\/en.wikipedia.org\/wiki\/Amanita\"><i>Amanita<\/i><\/a> carries some of the some deadliest mushrooms in the world. Destroying Angel, Death Cap and Fool's Mushroom are all fatal, however share characteristics of the Amanita class making them easily identifiable. While the cap colour may alter, typically White cap, gills, and spore print, along with a physical structure called the volva are telltale signs of  <a href=\"https:\/\/en.wikipedia.org\/wiki\/Amanita\"><i>Amanita's<\/i><\/a>. \n   <img src=\"https:\/\/atrium.lib.uoguelph.ca\/xmlui\/bitstream\/handle\/10214\/6850\/Amanita_virosa_Destroying_Angel_amanitin_and_phalloidin.jpg?sequence=1&isAllowed=y\" alt=\"Identifying a Destroying angel\" width=\"40%\"><\/img>\n   <div align=\"center\"><small>Source: University of Guelph<\/small><\/div>\n   * The genus <a href=\"https:\/\/en.wikipedia.org\/wiki\/Gyromitra_esculenta\"><i>Gyromitra<\/i><\/a>, better known as the False Morel, is an example of a poisonous mushroom that looks like the famously delicious Morel. Inexperienced mushroom hunters could potentially mix this type of mushroom up with an edible counterpart and suffer the consequences. However, false morels have a full stem and are tellingly <i>not<\/i> hollow. \n   <img src=\"https:\/\/cdn0.wideopenspaces.com\/wp-content\/uploads\/2017\/03\/morel-mushroom-real-fake.jpg\" alt=\"Two true morels on the left, false morel on the right\" width=\"50%\"><\/img>\n   <div align=\"center\"><small><a href=\"https:\/\/www.wideopenspaces.com\/learn-important-difference-real-false-morel-mushrooms\/\">Source: Wide Open Spaces<\/a><\/small><\/div>\n\"\"\"\n\"\"\"\nLet's first import packages and data. <a name=\"import\"><\/a>\n\"\"\"\n#import cleaning and visualization modules\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom matplotlib import rcParams, gridspec\n\n#import analysis modules\nfrom sklearn.svm import SVC\nfrom sklearn import neighbors\nfrom sklearn import linear_model\nfrom xgboost import XGBClassifier\nfrom sklearn import preprocessing\nfrom sklearn.svm import LinearSVC\nfrom xgboost import plot_importance\nfrom sklearn.metrics import log_loss\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier\n\n#pandas configuration\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\nData is read into a dataframe and displayed. Next dataypes, counts and columns are shown and a check if any null values are present.\n\"\"\"\n#read into dataframe, display first 5 values\ndf = pd.read_csv('..\/input\/mushrooms.csv')\ndf.head()\n#Look into df for datatypes, if nulls exist \nnull_count = 0\nfor val in df.isnull().sum():\n    null_count += val\nprint('There are {} null values.\\n'.format(null_count))\ndf.info()\n\"\"\"\nWe've seen that the data is categorical and there are no nulls in our set. Let's check how many classes are in each column. <a name=\"feat_select\"><\/a>\n\"\"\"\ndef show_features(df):\n    '''Takes a dataframe and outputs the columns, number of classes and category variables.'''\n    col_count, col_var = [], []\n    for col in df:\n        col_count.append(len(df[col].unique()))\n        col_var.append(df[col].unique().sum())\n    df_dict = {'Count': col_count, 'Variables': col_var}\n    df_table = pd.DataFrame(df_dict, index=df.columns)\n    print(df_table)\n    \nshow_features(df)\n\"\"\"\nRight away there are some interesting things to note: Veil-type has only one class and can be removed from our set, several classes are binary and can be reduced to a single feature, and there is a '?' class in the stalk-root class. One-hot encoding will transform our data into a usable format for our models, remove excess feature columns and prepare our independent variable for supervised learning. \n\nNext, let's see how many '?' values are present in the stalk-root category.\n\"\"\"\ndf['stalk-root'].value_counts()\n\"\"\"\nThere are a few options--remove the class entirely but lose potential information in our dataset, delete any row with a '?' but lose data across all variables, or encode the data and treat it as an unknown variable. For the purposes of this study we'll keep the class and use encoding to transform '?' into a feature. \n\"\"\"\ndf_dum = pd.get_dummies(df, drop_first=True)\ndf_dum.head()\n\"\"\"\n### Mushroom Hunting & Important Features of Determining Edibility  <a name=\"exp\"><\/a>\n\nAs discussed earlier, the art of mushroom foraging can be difficult at times when ID'ing unknown species. In the field, we'll collect a spore print, look at morphological features, mark time of year, use smell, test for bruising, note the conditions it was found in: healthy or rotted terrain, neighbouring trees and plant life, near other fungi--all important steps in correctly identifying whether a find is edible or poisonous. \n\nWe can graph some of the data to determine if there are any features that are more associated with poisonous species at a glance before running our models and testing for important features.\n\n\"\"\"\nplt.figure(figsize=[16,12])\n\nplt.subplot(231)\nsns.countplot(x='odor', hue='class', data=df)\nplt.title('Odor')\nplt.xticks(np.arange(10),('Pungent', 'Almond', 'Anise', 'None', 'Foul', 'Creosote', 'Fish', 'Spicy', 'Musty'), rotation='vertical')\nplt.ylabel('Count')\n\nplt.subplot(232)\nsns.countplot(x='spore-print-color', hue='class', data=df)\nplt.title('Spore Print Color')\nplt.xticks(np.arange(10),('Black', 'Brown','Purple','Chocolate','White','Green','Orange','Yellow','Brown'), rotation='vertical')\nplt.legend(loc='upper right')\n\nplt.subplot(233)\nsns.countplot(x='cap-color', hue='class', data=df)\nplt.title('Cap Color')\nplt.xticks(np.arange(11),('Brown', 'Yellow','White','Gray','Red','Pink','Buff','Purple','Cinnamon','Green'), rotation='vertical')\nplt.legend(loc='upper right')\n\nplt.subplot(234)\nsns.countplot(x='bruises', hue='class', data=df)\nplt.title('Bruising')\nplt.xticks(np.arange(2),('Bruise', 'No Bruise'), rotation='vertical')\nplt.legend(loc='upper right')\n\nplt.subplot(235)\nsns.countplot(x='habitat', hue='class', data=df)\nplt.title('Habitat')\nplt.xticks(np.arange(8),('Urban', 'Grasses','Meadows','Woods','Paths','Waste','Leaves'), rotation='vertical')\nplt.legend(loc='upper right')\n\nplt.subplot(236)\nsns.countplot(x='population', hue='class', data=df)\nplt.title('Population')\nplt.xticks(np.arange(7),('Scattered', 'Numerous','Abundant','Several','Solitary','Clustered'), rotation='vertical')\nplt.legend(loc='upper right')\n\nplt.tight_layout()\nsns.despine()\n\"\"\"\nAt first glance, odour, spore print color and bruising are fairly good features to predict edibility, while cap colour, habitat and population-type show a bit more variance between species. These graphs are interesting from a foraging standpoint and reinforce how it's important to use multiple traits to ID a mushroom. \n\nNext we'll run some classification models to try and predict whether a mushroom is poison or edible. The data is split into our X-dependent feature columns and y-independent label, then split again into a 70:30 train:test set. \n\"\"\"\n#set features\nX = df_dum.drop('class_p', axis=1)\n#set independent variable\ny = df_dum['class_p']\n#split the training and test data\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\n\n#print shapes of training\/testing sets\nprint(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\"\"\"\n### PCA & KMeans Visualization <a name=\"pca\"><\/a>\n\"\"\"\n#visualize edible vs poison classes\npca = PCA(n_components=2)\n\nx_pca = X.values\nx_pca = pca.fit_transform(X)\n\nplt.figure(figsize=(8,6))\nplt.scatter(x_pca[:,0], x_pca[:,1], c=y, s=40, edgecolor='k')\nplt.title('Visualizing Edible vs. Poison Classes')\n\"\"\"\nPCA is used to visualize the dataset by transforming our features into 2 dimensions. Right away we can see a clear separation of classes with some overlap in the left cluster. We can see if an unsupervised KMeans with K=2 clusters is able to classify our data with any accuracy. <a name=\"kmean\"><\/a>\n\"\"\"\n\"\"\"\n### KMeans\n\"\"\"\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans\n\n#Specify the model and fit to training set\nkm = KMeans(n_clusters = 2)\nkm.fit(X_train)\n\n#PCA X_test for visualization\npca_test = PCA(n_components = 2)\npca_test.fit(X_test)\nX_test_pca = X_test.values\nX_test_pca = pca_test.fit_transform(X_test)\n\n#KMeans prediction\ny_pred_km = km.predict(X_test)\n\n#Plot the data\nplt.figure(figsize=(8,6))\nplt.scatter(X_test_pca[:, 0], X_test_pca[:, 1], c=y_pred_km, \n            s=40, edgecolor='k')\nplt.title('KMeans: Test Data')\nplt.show();\n\"\"\"\nVisually this looks OK, but not great. The model acheives 89% accuracy. KMeans is fast, and works by measuring the distance from the centroid of a cluster to classify points. Since there is some overlap in the left-most cluster, it groups everything to the same class.   \n\"\"\"\ndef plot_confusion_matrix(cm, classes, fontsize=15,\n                          normalize=False, title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    cm_num = cm\n    cm_per = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n    \n    plt.figure(figsize=(5,5))\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title.replace('_',' ').title()+'\\n', size=fontsize)\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45, size=fontsize)\n    plt.yticks(tick_marks, classes, size=fontsize)\n\n    fmt = '.5f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        # Set color parameters\n        color = \"white\" if cm[i, j] > thresh else \"black\"\n        alignment = \"center\"\n\n        # Plot perentage\n        text = format(cm_per[i, j], '.5f')\n        text = text + '%'\n        plt.text(j, i,\n            text,\n            fontsize=fontsize,\n            verticalalignment='baseline',\n            horizontalalignment='center',\n            color=color)\n        # Plot numeric\n        text = format(cm_num[i, j], 'd')\n        text = '\\n \\n' + text\n        plt.text(j, i,\n            text,\n            fontsize=fontsize,\n            verticalalignment='center',\n            horizontalalignment='center',\n            color=color)\n        \n    plt.tight_layout()\n    plt.ylabel('True label'.title(), size=fontsize)\n    plt.xlabel('Predicted label'.title(), size=fontsize)\n\n    return None\ncm_km = metrics.confusion_matrix(y_test, y_pred_km)\nplot_confusion_matrix(cm_km, classes=['Edible','Poison'])\nprint(f'KMeans accuracy: {str(accuracy_score(y_test, y_pred_km)*100)[:5]}%')\n\"\"\"\nOverall an unsupervised KMeans approach was interesting but by reducing our features into 2 dimensions there was a loss in accuracy. Next, we're going to try some regression models on our training set, starting with a Logistic Regression. Features can be auto-selected for and tuned using Recursive Feature Elimination and Cross-validation. <a name=\"lin\"><\/a>\n\"\"\"\n\"\"\"\n### Logistic Regression\n\"\"\"\n#set the model and fit entire data to RFECV--train\/test splits are done automatically and cross-validated.\nlm = linear_model.LogisticRegression()\nrfecv = RFECV(estimator=lm, step=1, cv=10, scoring='accuracy')\nrfecv.fit(X, y)\n\nprint('Optimal number of features: %d' % rfecv.n_features_)\nprint('Selected features: %s' % list(X.columns[rfecv.support_]))\n\n#plot features vs. validation scores\nplt.figure(figsize=(10,6))\nplt.xlabel('Number of features selected')\nplt.ylabel('Cross validation score')\nplt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)\nplt.show()\n\"\"\"\nWow! 14\/95 of the features give us the optimal amount for modelling. The rest is noise. This selection tests helps us to avoid overfitting and multicollinearity. Let's move forward with only those 14 features and see how our models perform. <a name=\"logreg\"><\/a>\n\"\"\"\n#set optimal features and assign new X, train\/test split\nopt_features = ['odor_c', 'odor_f', 'odor_l', 'odor_n', 'odor_p', \n                'gill-spacing_w', 'gill-size_n', 'stalk-surface-above-ring_k', \n                'ring-type_f', 'spore-print-color_k', 'spore-print-color_n', \n                'spore-print-color_r', 'spore-print-color_u', 'population_c']\n#new dependent variables\nX_opt = X[opt_features] \n\n#split the training and test data\nXo_train, Xo_test, yo_train, yo_test = train_test_split(X_opt, y, test_size=0.3)\n#print shapes of training\/testing sets\nprint(Xo_train.shape, Xo_test.shape, yo_train.shape, yo_test.shape)\n#logistic regression\nlm = linear_model.LogisticRegression()\nlm.fit(Xo_train, yo_train)\nlog_probs = lm.predict_proba(Xo_test)\nloss = log_loss(yo_test, log_probs)\nprint(f'Loss value: {loss}')\nprint(f'Training accuracy: {str(lm.score(Xo_train, yo_train)*100)[:5]}%')\nprint(f'Test accuracy: {str(lm.score(Xo_test, yo_test)*100)[:5]}%')\ny_pred_lm = lm.predict(Xo_test)\n\ncm_lm = metrics.confusion_matrix(yo_test, y_pred_lm)\nplot_confusion_matrix(cm_lm, ['Edible','Poison'])\nprint(f'Logistic Regression accuracy: {str(accuracy_score(yo_test, y_pred_lm)*100)[:5]}%')\n\"\"\"\nAs shown, a logistic regression performs very well on this smaller categorical dataset. With only one false negative and no false positives the model makes quick work of this problem. Now we have our features and benchmarks for performance, let's try an SVM (Support Vector Machine) with different kernals to see what our best fit is. <a name=\"svm\"><\/a>\n\"\"\"\n\"\"\"\n### SVM\n\"\"\"\n#test out different SVMs using the different kernals\nkerns = ['linear', 'rbf', 'sigmoid']\nfor i in kerns:\n    #Kernel trick\n    svm_kern = SVC(kernel=f'{i}')\n    svm_kern.fit(Xo_train,yo_train)\n    \n    #Get the score\n    print(f'{i} kernal SVM score: {str(100*svm_kern.score(Xo_test,yo_test))[:6]}%')\n#fit SVM model to scaled data\nsvm = LinearSVC()\nsvm.fit(Xo_train, yo_train)\nprint(f'Linear SVM Training accuracy is: {svm.score(Xo_train, yo_train)*100}%')\nprint(f'Linear SVM Test accuracy is: {svm.score(Xo_test, yo_test)*100}%')\ny_pred_svm = svm.predict(Xo_test)\n\ncm_svm = metrics.confusion_matrix(yo_test, y_pred_svm)\nplot_confusion_matrix(cm_svm, ['Edible','Poison'])\nprint(f'SVM accuracy: {str(accuracy_score(yo_test, y_pred_svm)*100)[:5]}%')\n\"\"\"\nBoth of our linear models performed spectacularly on the mushroom dataset. Let's see how tree and bagging classifiers handle the data. <a name=\"bag\"><\/a>\n\n### Gradient Boost and XGBoost Classifiers\n\"\"\"\n#initialize gradientboost and xgboost\ngb = GradientBoostingClassifier()\nxgb = XGBClassifier()\n#fit models\ngb.fit(Xo_train,yo_train)\nxgb.fit(Xo_train,yo_train)\n#score models\nprint(f'Gradient Boost score: {(100 * gb.score(Xo_test,yo_test))}%')\nprint(f'XG Boost score: {(100 * xgb.score(Xo_test,yo_test))}%')\n\"\"\"\nIt's apparent that our binary classification of mushroom toxicity is not a difficult problem for bagging and regression models to solve. We can see how XGBoost weighted the feature columns below. <a name=\"xgb\"><\/a>\n\"\"\"\n#plot feature importance XGBoost\nplot_importance(xgb)\nplt.show()\n\"\"\"\nXGBoost puts narrow-gills and odourless as it's top predictors of edibility--this makes sense after exploring our data and knowing how mushrooms are ID'd. Next we'll run the same analysis but with a Random Forest. <a name=\"trees\"><\/a>\n\n### Random Forest Classifier\n\"\"\"\n#fitting a random forest\nrf = RandomForestClassifier()\nrf.fit(Xo_train, yo_train)\nprint(\"Default RFR: %3.1f\" % (rf.score(Xo_test, yo_test)*100))\n\"\"\"\nThe default Random Forest achieves a 100% accuracy as well, but will assign different weights and importance to features. Next, we'll run a Grid Search with 10-fold cross-validation to observe optimal parameters--this will illustrate how to tune for hyperparameters and to avoid overfitting. \n\"\"\"\nparam_grid = { \n    'n_estimators': [50, 100, 200],\n    'max_features': ['auto', 'sqrt', 'log2'],\n    'max_depth' : [4,5,6,7,8],\n    'criterion' :['gini', 'entropy']\n}\nCV_rfc = GridSearchCV(estimator=rf, param_grid=param_grid, cv= 10)\nCV_rfc.fit(Xo_train, yo_train)\nCV_rfc.best_params_\nrfcv = RandomForestClassifier(criterion= 'gini',\n max_depth= 6,\n max_features= 'auto',\n n_estimators= 50)\nrfcv.fit(Xo_train, yo_train)\nprint(f'GridSearchCV RFR: {(rfcv.score(Xo_test, yo_test)*100)}%')\n\"\"\"\nThe optimized Random Forest classifier still achieves a 100% accuracy, which is to be expected. Let's visualize the difference between feature importance.\n\"\"\"\nfeature_imp = pd.Series(rfcv.feature_importances_,index=Xo_train.columns).sort_values(ascending=False)\nprint(feature_imp)\n#plot feature importance for RFR\nplt.figure(figsize=(12,8))\nsns.barplot(x=feature_imp, y=feature_imp.index)\nplt.title('Random Forest Feature Importance');\n\"\"\"\nThe features are slightly different than XGBoost, however the first two, odourless and narrow-gilled are still the strongest predictors. \n\nThat sums up our look at Mushroom Classifications. Happy foraging!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dba31c3833699e'}"}
{"id":"60969","text":"\"\"\"\n## Simple EDA and LightGBM model\n* 5-fold cross validation\n* easy feature engineering and EDA\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport os\nimport seaborn as sns\nimport lightgbm as lgb\nfrom sklearn.model_selection import GroupKFold,StratifiedKFold\nfrom sklearn.preprocessing import LabelEncoder\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\nprint(os.listdir(\"..\/input\"))\ntrain = pd.read_csv('..\/input\/train.csv')\ntest = pd.read_csv('..\/input\/test.csv')\n\"\"\"\n## Train \/ Test Set\n\"\"\"\n\"\"\"\nthe training set, where the first column (molecule_name) is the name of the molecule where the coupling constant originates (the corresponding XYZ file is located at .\/structures\/.xyz), the second (atom_index_0) and third column (atom_index_1) is the atom indices of the atom-pair creating the coupling and the fourth column (scalar_coupling_constant) is the scalar coupling constant that we want to be able to predict\n\"\"\"\ntrain.head()\nprint (\"Total Train Set : %d\" %len(train))\nprint ('Total Test Set : %d' %len(test))\n\"\"\"\n### Target : scalar_coupling_constant\n\n\"\"\"\ntrain['scalar_coupling_constant'].describe()\nsns.distplot(train['scalar_coupling_constant'])\n\"\"\"\n### Plot type \/ target correlation\nLooks each type have some correlate to target\n\"\"\"\ntypelist = list(train['type'].value_counts().index)\ntypelist\nplt.figure(figsize=(26, 24))\nfor i, col in enumerate(typelist):\n    plt.subplot(4,2, i + 1)\n    sns.distplot(train[train['type']==col]['scalar_coupling_constant'],color ='orange')\n    plt.title(col)\n\"\"\"\n## Structure X\/Y\/Z\n\"\"\"\nstructures = pd.read_csv('..\/input\/structures.csv')\nstructures.head()\n\"\"\"\n## Merge the train set and structure set\n\"\"\"\n#https:\/\/www.kaggle.com\/inversion\/atomic-distance-benchmark\/output\ndef map_atom_info(df, atom_idx):\n    df = pd.merge(df, structures, how = 'left',\n                  left_on  = ['molecule_name', f'atom_index_{atom_idx}'],\n                  right_on = ['molecule_name',  'atom_index'])\n    \n    df = df.drop('atom_index', axis=1)\n    df = df.rename(columns={'atom': f'atom_{atom_idx}',\n                            'x': f'x_{atom_idx}',\n                            'y': f'y_{atom_idx}',\n                            'z': f'z_{atom_idx}'})\n    return df\n\ntrain = map_atom_info(train, 0)\ntrain = map_atom_info(train, 1)\n\ntest = map_atom_info(test, 0)\ntest = map_atom_info(test, 1)\ntrain.head()\n\"\"\"\n## FE - Distance of atom\n\"\"\"\n#https:\/\/www.kaggle.com\/inversion\/atomic-distance-benchmark\/output\n\ntrain['dist'] = ((train['x_1'] - train['x_0'])**2 +\n             (train['y_1'] - train['y_0'])**2 +\n             (train['z_1'] - train['z_0'])**2 ) ** 0.5\n\ntest['dist'] = ((test['x_1'] - test['x_0'])**2 +\n             (test['y_1'] - test['y_0'])**2 +\n             (test['z_1'] - test['z_0'])**2 ) ** 0.5\n\"\"\"\n## Label Encoding\n\"\"\"\nmolecules = train.pop('molecule_name')\ntest = test.drop('molecule_name', axis=1)\nid_train = train.pop('id')\nid_test = test.pop('id')\n\ny = train.pop('scalar_coupling_constant')\n\n# Label Encoding\nfor f in ['type', 'atom_0', 'atom_1']:\n    lbl = LabelEncoder()\n    lbl.fit(list(train[f].values) + list(test[f].values))\n    train[f] = lbl.transform(list(train[f].values))\n    test[f] = lbl.transform(list(test[f].values))\ntrain.head()\n\"\"\"\n## Training\n\"\"\"\n## Evaluate matric\n## https:\/\/www.kaggle.com\/abhishek\/competition-metric\ndef metric(df, preds):\n    df[\"prediction\"] = preds\n    maes = []\n    for t in df.type.unique():\n        y_true = df[df.type==t].scalar_coupling_constant.values\n        y_pred = df[df.type==t].prediction.values\n        mae = np.log(metrics.mean_absolute_error(y_true, y_pred))\n        maes.append(mae)\n    return np.mean(maes)\n#df for evaluate\neval_df = pd.DataFrame({\"type\":train[\"type\"]})\neval_df[\"scalar_coupling_constant\"] = y\nn_splits = 5 # Number of K-fold Splits\n\nsplits = list(GroupKFold(n_splits=n_splits).split(train, y, groups=molecules))\nsplits[:3]\nparams = {\"learning_rate\" : 0.1,\n          \"depth\": 9,\n          'metric':'MAE',\n          'min_samples_leaf': 3,\n          \"loss_function\": \"MAE\"}\noof = np.zeros(len(train))\npredictions = np.zeros(len(test))\nfeature_importance_df = pd.DataFrame()\nfeatures = [c for c in train.columns if c not in ['id']]\n\nfor i, (train_idx, valid_idx) in enumerate(splits):  \n    print(f'Fold {i + 1}')\n    x_train = np.array(train)\n    y_train = np.array(y)\n    trn_data = lgb.Dataset(x_train[train_idx.astype(int)], label=y_train[train_idx.astype(int)])\n    val_data = lgb.Dataset(x_train[valid_idx.astype(int)], label=y_train[valid_idx.astype(int)])\n    \n    num_round = 10000\n    clf = lgb.train(params, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=500, early_stopping_rounds = 200)\n    oof[valid_idx] = clf.predict(x_train[valid_idx], num_iteration=clf.best_iteration)\n    \n    fold_importance_df = pd.DataFrame()\n    fold_importance_df[\"feature\"] = features\n    fold_importance_df[\"importance\"] = clf.feature_importance()\n    fold_importance_df[\"fold\"] = i + 1\n    feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n    #predictions[fake_data.index] += clf.predict(fake_data, num_iteration=clf.best_iteration) \/ n_splits\n    predictions += clf.predict(test, num_iteration=clf.best_iteration) \/ n_splits\n\n#print(\"CV score: {:<8.5f}\".format(np.log(metrics.mean_absolute_error(train, oof))))\nprint(\"CV score: {:<8.5f}\".format(metric(eval_df, oof)))\n\"\"\"\n## Plot feature important\n\"\"\"\ncols = (feature_importance_df[[\"feature\", \"importance\"]]\n        .groupby(\"feature\")\n        .mean()\n        .sort_values(by=\"importance\", ascending=False)[:1000].index)\nbest_features = feature_importance_df.loc[feature_importance_df.feature.isin(cols)]\n\nplt.figure(figsize=(14,5))\nsns.barplot(x=\"importance\", y=\"feature\", data=best_features.sort_values(by=\"importance\",ascending=False))\nplt.title('LightGBM Features (averaged over folds)')\nplt.tight_layout()\nplt.savefig('lgbm_importances.png')\n\"\"\"\n## Submission\n\"\"\"\nsample_submission = pd.read_csv('..\/input\/sample_submission.csv')\n\nbenchmark = sample_submission.copy()\nbenchmark['scalar_coupling_constant'] = predictions\nbenchmark.to_csv('LGBM_submission.csv',index=False)\nbenchmark.head()\n\"\"\"\n## Future work\n* EDA on Additional data\n* More FE\n* NN model build\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '707085ea5588ad'}"}
{"id":"21047","text":"import 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 \"..\/input\/\" directory.\n# For example, running this (Shift+Enter) will list the files in the input directory\nimport os\npath = '..\/input'\nprint(os.listdir(\"..\/input\"))\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Any results you write to the current directory are saved as output.\ntrain_path = f'{path}\/train.csv'\ntest_path = f'{path}\/test.csv'\ntrain_df = pd.read_csv(train_path)\nprint(train_df.shape)\ntrain_df.head()\ntarget = train_df['target']\ntrain_df = train_df.drop(['ID_code'], axis = 1).astype('float16')\ntarget.value_counts().plot.bar()\nprint('%age value of 0s target variable:', target.value_counts()[0]\/len(target) * 100)\nprint('%age value of 1s target variable:', target.value_counts()[1]\/len(target) * 100)\n\"\"\"\nLet's see on high level, if data is separable in 2d\/3d using PCA\/tSNE\n\"\"\"\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=3)\nx_pca = pca.fit_transform(train_df)\nprint(pca.explained_variance_ratio_)\nprint(sum(pca.explained_variance_ratio_))\n\nx_pca = pd.DataFrame(data = x_pca)\nplt.scatter(x = x_pca[0], y = x_pca[1], data = x_pca, c = target.values)\nplt.xlabel('pc1')\nplt.ylabel('pc2')\nplt.title('representation of classes with pca')\npca = PCA().fit(train_df)\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance');\n\"\"\"\nonly 13% of variance is explained in 3 principle axis. PCA was unable to capture the variance into 2\/3 dimesions meaning that there is high varaince in the data given. So linear models might not perform well on this data.\n\"\"\"\n\"\"\"\nTrain Data distrubution:\nLet us see, how distrubution of data varies b\/w two targets\n\"\"\"\ndef density_feature_plot(df, features, grid_size = (8,8)):\n    i = 0\n    sns.set_style('whitegrid')\n    plt.figure()\n    fig, ax = plt.subplots(grid_size[0],grid_size[1],figsize=(16,16))\n    \n    t0 = df.loc[df['target'] == 0]\n    t1 = df.loc[df['target'] == 1]\n\n    for feature in features:\n        i += 1\n        plt.subplot(grid_size[0],grid_size[1],i)\n        sns.kdeplot(t0[feature], bw=0.5,label=0)\n        sns.kdeplot(t1[feature], bw=0.5,label=1)\n        plt.xlabel(feature, fontsize=9)\n    locs, labels = plt.xticks()\n    plt.tick_params(axis='x', which='major', labelsize=6, pad=-6)\n    plt.tick_params(axis='y', which='major', labelsize=6)\n    plt.tight_layout()\n    plt.show();\nfeatures = train_df.columns.values[2:66]\ndensity_feature_plot(train_df, features)\nfeatures = train_df.columns.values[66:130]\ndensity_feature_plot(train_df, features)\nfeatures = train_df.columns.values[130:166]\ndensity_feature_plot(train_df, features, (6,6))\nfeatures = train_df.columns.values[166:]\ndensity_feature_plot(train_df, features, (6,6))\n\"\"\"\nWe can observe that there is a considerable number of features with significant different distribution for the two target values.\nFor example, var_0, var_1, var_2, var_5, var_9, var_13, var_21, var_26, var_44, var_76, var_86, var_99, var_106, var_109, var_139, var_174, var_198.\n\"\"\"\n\"\"\"\n### Outliers in the data\n\"\"\"\ntrain_df.iloc[:, 2:100].plot(kind='box', figsize=[16,8])\n# Plot last 100 features.\ntrain_df.iloc[:, 100:].plot(kind='box', figsize=[16,8])\n\"\"\"\nThere are significan[](http:\/\/)t no.of outliers in the data, they should be treated accordingly\n\"\"\"\n\"\"\"\n### Co-relation among variables\n\"\"\"\ncorr_df = train_df.corr()\nimport seaborn as sns\nsns.set(style=\"white\")\nmask = np.zeros_like(corr_df.iloc[:,1:], dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(16, 16))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr_df.iloc[:,1:], mask=mask, cmap=cmap, vmax=.2, center=0,\n            square=True, linewidths=.5)\n\"\"\"\nvery less co-rrelation among the features\n\"\"\"\n\"\"\"\n> ### co-rrelation with target variable\n\"\"\"\ncorr_target=corr_df.loc[corr_df.target>0.05]['target'].iloc[1:] # slight +ve co-rrelation\ncorr_target.plot(kind='bar')\ncorr_target=corr_df.loc[corr_df.target < -0.05]['target'].iloc[1:] \ncorr_target.plot(kind='bar') # slight -ve co-rrelation\n\"\"\"\n### check for missing ang duplicate rows\n\"\"\"\npd.DataFrame(train_df.isnull().sum()).T\ntrain_df.duplicated().sum()\n\"\"\"\nNo missing values and the duplicate rows\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '269b091c55fcaf'}"}
{"id":"47478","text":"\"\"\"\n## Please upvote if you like it ;) \n\"\"\"\n\"\"\"\n# Import Module\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport random\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\nos.chdir('..\/input')\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n# Get FileName\n\"\"\"\n# get all file name\nfilenames = [x for x in os.listdir() if x.endswith('.csv') and os.path.getsize(x) > 0]\nprint(filenames)\n\"\"\"\n# Close Price Plot\n\"\"\"\nimport plotly as py\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n\n# make close value trace\n\nr = lambda: random.randint(0,255)\ntraces = []\n\nfor filename in filenames:\n    # random color create\n    color = 'rgb({},{},{})'.format(str(r()),str(r()),str(r()))\n    # get stock name \n    stock_name = filename.replace('.csv', '')\n    # load csv\n    df = pd.read_csv('..\/input\/{}'.format(filename))\n    # create line plot\n    trace = go.Scatter(x=df.Date, y=df['Close'],name=stock_name,line=dict(color = color))\n    traces.append(trace)\n\nlayout = py.graph_objs.Layout(\n    title='Close Plot',\n)\nfig = py.graph_objs.Figure(data=traces, layout=layout)\n\npy.offline.iplot(fig)\n\"\"\"\n# Log Plot\n\"\"\"\n# make log close value trace\n\nr = lambda: random.randint(0,255)\ntraces = []\n\nfor filename in filenames:\n    # random color create\n    color = 'rgb({},{},{})'.format(str(r()),str(r()),str(r()))\n    # get stock name \n    stock_name = filename.replace('.csv', '')\n    # load csv\n    df = pd.read_csv('..\/input\/{}'.format(filename))\n    # create line plot\n    trace = go.Scatter(x=df.Date, y=np.log(df['Close']),name=stock_name,line=dict(color = color))\n    traces.append(trace)\n\nlayout = py.graph_objs.Layout(\n    title='Log Plot',\n)\nfig = py.graph_objs.Figure(data=traces, layout=layout)\n\npy.offline.iplot(fig)\n\"\"\"\n# Diff Plot\n\"\"\"\n# make price diff trace\n\nr = lambda: random.randint(0,255)\ntraces = []\n\nfor filename in filenames:\n    # random color create\n    color = 'rgb({},{},{})'.format(str(r()),str(r()),str(r()))\n    # get stock name \n    stock_name = filename.replace('.csv', '')\n    # load csv\n    df = pd.read_csv('..\/input\/{}'.format(filename))\n    # create line plot\n    trace = go.Scatter(x=df.Date, y=df['Close'] - df['Open'],name=stock_name,line=dict(color = color))\n    traces.append(trace)\n\nlayout = py.graph_objs.Layout(\n    title='Price Diff Plot',\n)\nfig = py.graph_objs.Figure(data=traces, layout=layout)\n\npy.offline.iplot(fig)\n\"\"\"\n## Please upvote if you like it ;) \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '577637b38b6e9c'}"}
{"id":"23460","text":"# 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 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\nt_news = pd.read_csv('\/kaggle\/input\/fake-and-real-news-dataset\/True.csv')\nf_news = pd.read_csv('\/kaggle\/input\/fake-and-real-news-dataset\/Fake.csv')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nt_news['category'] = 'true'\nf_news['category'] = 'fake'\n\"\"\"\n#### Balancing this data\n\"\"\"\nf_news = f_news.sample(t_news.shape[0])\nnews = f_news.append(t_news, ignore_index = True)\n\"\"\"\n### Text Preprocessing and Cleaning\n#### Word Count \n\"\"\"\nnews['Word_Count'] = news['text'].apply(lambda x: len(str(x).split()))\n\"\"\"\n#### Character_Count\n\"\"\"\nnews['Char_Count'] = news['text'].apply(lambda x: len(x))\n\"\"\"\n#### Removing multiple Spaces\n\"\"\"\nnews['text'] = news['text'].apply(lambda x: ' '.join(x.split()))\n\"\"\"\n#### Punctuation Count\n\"\"\"\nimport re\nnews['punct_count'] = news['text'].apply(lambda x: len(re.findall('[^a-z A-Z 0-9-]+', x)))\n\"\"\"\n####  Count hashtags(#) and @ mentions\n\"\"\"\nnews['hashtags_count'] = news['text'].apply(lambda x: len([t for t in x.split() if t.startswith('#')]))\nnews['mention_count'] = news['text'].apply(lambda x: len([t for t in x.split() if t.startswith('@')]))\n\"\"\"\n#### If numeric digits are present in tweets\n\"\"\"\nnews['numerics_count'] = news['text'].apply(lambda x: len([t for t in x.split() if t.isdigit()]))\n\"\"\"\n#### UPPER_case_words_count\n\"\"\"\nnews['UPPER_CASE_COUNT'] = news['text'].apply(lambda x: len([t for t in  x.split() if t.isupper() and len(x)>3]))\ncontractions = {\n\"aight\": \"alright\",\n\"ain't\": \"am not\",\n\"amn't\": \"am not\",\n\"aren't\": \"are not\",\n\"can't\": \"can not\",\n\"cause\": \"because\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"daren't\": \"dare not\",\n\"daren't\": \"dared not\",\n\"daresn't\": \"dare not\",\n\"dasn't\": \"dare not\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"don't\": \"do not\",\n\"don't\": \"does not\",\n\"d'ye\": \"do you\",\n\"d'ye\": \"did you\",\n\"e'er\": \"ever\",\n\"everybody's\": \"everybody is\",\n\"everyone's\": \"everyone is\",\n\"finna\": \"fixing to\",\n\"finna\": \"going to\",\n\"g'day\": \"good day\",\n\"gimme\": \"give me\",\n\"giv'n\": \"given\",\n\"gonna\": \"going to\",\n\"gon't\": \"go not\",\n\"gotta\": \"got to\",\n\"hadn't\": \"had not\",\n\"had've\": \"had have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he had\",\n\"he'd\": \"he would\",\n\"he'dn't've'd\": \"he would not have had\",\n\"he'll\": \"he shall\",\n\"he'll\": \"he will\",\n\"he's\": \"he has\",\n\"he's\": \"he is\",\n\"he've\": \"he have\",\n\"how'd\": \"how did\",\n\"how'd\": \"how would\",\n\"howdy\": \"how do you do\",\n\"howdy\": \"how do you fare\",\n\"how'll\": \"how will\",\n\"how're\": \"how are\",\n\"I'll\": \"I shall\",\n\"I'll\": \"I will\",\n\"I'm\": \"I am\",\n\"I'm'a\": \"I am about to\",\n\"I'm'o\": \"I am going to\",\n\"innit\": \"is it not\",\n\"I've\": \"I have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it would\",\n\"it'll\": \"it shall\",\n\"it'll\": \"it will\",\n\"it's\": \"it has\",\n\"it's\": \"it is\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"may've\": \"may have\",\n\"methinks\": \"me thinks\",\n\"mightn't\": \"might not\",\n\"might've\": \"might have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"must've\": \"must have\",\n\"needn't\": \"need not\",\n\"ne'er\": \"never\",\n\"o'clock\": \"of the clock\",\n\"o'er\": \"over\",\n\"ol'\": \"old\",\n\"oughtn't\": \"ought not\",\n\"'s\": \"is, has, does, or us\",\n\"shalln't\": \"shall not\",\n\"shan't\": \"shall not\",\n\"she'd\": \"she had\",\n\"she'd\": \"she would\",\n\"she'll\": \"she shall\",\n\"she'll\": \"she will\",\n\"she's\": \"she has\",\n\"she's\": \"she is\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"somebody's\": \"somebody has\",\n\"somebody's\": \"somebody is\",\n\"someone's\": \"someone has\",\n\"someone's\": \"someone is\",\n\"something's\": \"something has\",\n\"something's\": \"something is\",\n\"so're\": \"so are\",\n\"that'll\": \"that shall\",\n\"that'll\": \"that will\",\n\"that're\": \"that are\",\n\"that's\": \"that has\",\n\"that's\": \"that is\",\n\"that'd\": \"that would\",\n\"that'd\": \"that had\",\n\"there'd\": \"there had\",\n\"there'd\": \"there would\",\n\"there'll\": \"there shall\",\n\"there'll\": \"there will\",\n\"there're\": \"there are\",\n\"there's\": \"there has\",\n\"there's\": \"there is\",\n\"these're\": \"these are\",\n\"these've\": \"these have\",\n\"they'd\": \"they had\",\n\"they'd\": \"they would\",\n\"they'll\": \"they shall\",\n\"they'll\": \"they will\",\n\"they're\": \"they are\",\n\"they're\": \"they were\",\n\"they've\": \"they have\",\n\"this's\": \"this has\",\n\"this's\": \"this is\",\n\"those're\": \"those are\",\n\"those've\": \"those have\",\n\"'tis\": \"it is\",\n\"to've\": \"to have\",\n\"'twas\": \"it was\",\n\"wanna\": \"want to\",\n\"wasn't\": \"was not\",\n\"we'd\": \"we had\",\n\"we'd\": \"we would\",\n\"we'd\": \"we did\",\n\"we'll\": \"we shall\",\n\"we'll\": \"we will\",\n\"we're\": \"we are\",\n\"we've\": \"we have\",\n\"weren't\": \"were not\",\n\"what'd\": \"what did\",\n\"what'll\": \"what shall\",\n\"what'll\": \"what will\",\n\"what're\": \"what are\",\n\"what're\": \"what were\",\n\"what's\": \"what has\",\n\"what's\": \"what is\",\n\"what's\": \"what does\",\n\"what've\": \"what have\",\n\"when's\": \"when has\",\n\"when's\": \"when is\",\n\"where'd\": \"where did\",\n\"where'll\": \"where shall\",\n\"where'll\": \"where will\",\n\"where're\": \"where are\",\n\"where's\": \"where has\",\n\"where's\": \"where is\",\n\"where's\": \"where does\",\n\"where've\": \"where have\",\n\"which'd\": \"which had\",\n\"which'd\": \"which would\",\n\"which'll\": \"which shall\",\n\"which'll\": \"which will\",\n\"which're\": \"which are\",\n\"which's\": \"which has\",\n\"which's\": \"which is\",\n\"which've\": \"which have\",\n\"who'd\": \"who would\",\n\"who'd\": \"who had\",\n\"who'd\": \"who did\",\n\"who'd've\": \"who would have\",\n\"who'll\": \"who shall\",\n\"who'll\": \"who will\",\n\"who're\": \"who are\",\n\"who's\": \"who has\",\n\"who's\": \"who is\",\n\"who's\": \"who does\",\n\"who've\": \"who have\",\n\"why'd\": \"why did\",\n\"why're\": \"why are\",\n\"why's\": \"why has\",\n\"why's\": \"why is\",\n\"why's\": \"why does\",\n\"won't\": \"will not\",\n\"would've\": \"would have\",\n\"wouldn't\": \"would not\",\n\"wouldn't've\": \"would not have\",\n\"y'all\": \"you all\",\n\"y'all'd've\": \"you all would have\",\n\"y'all'dn't've'd\": \"you all would not have had\",\n\"y'all're\": \"you all are\",\n\"you'd\": \"you had\",\n\"you'd\": \"you would\",\n\"you'll\": \"you shall\",\n\"you'll\": \"you will\",\n\"you're\": \"you are\",\n\"you're\": \"you are\",\n\"you've\": \"you have\",\n\" u \": \"you\",\n\" ur \": \"your\",\n\" n \": \"and\"\n}\ndef cont_to_exp(x):\n    if type(x) is str:\n        for key in contractions:\n            value = contractions[key]\n            x = x.replace(key,value)\n        return x\n    else:\n        return x\nnews['text'] = news['text'].apply(lambda x: cont_to_exp(x))\n\"\"\"\n### Count and Removing Emails\n\"\"\"\nnews['Emails'] = news['text'].apply(lambda x: re.findall(r'([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)',x))\nnews['text'] = news['text'].apply(lambda x: re.sub(r'([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)', '',x))\n\"\"\"\n#### Count URLs and remove them\n\"\"\"\nnews['URL_Flags'] = news['text'].apply(lambda x: len(re.findall(r'(http|ftp|https):\/\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\/~+#-]*[\\w@?^=%&\/~+#-])?', x)))\nnews['text'] = news['text'].apply(lambda x: re.sub(r'(http|ftp|https):\/\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\/~+#-]*[\\w@?^=%&\/~+#-])?', '', x))\n\"\"\"\n####  Removal of special chars and punctuation\n\"\"\"\nnews['text'] = news['text'].apply(lambda x: re.sub('[^a-z A-Z 0-9-]+', '', x))\n\"\"\"\n#### WordCloud Visualization\n\"\"\"\nfrom wordcloud import WordCloud\ntext = ' '.join(news['text'])\ntext = text.split()\nx = ' '.join(text[:20000])\nwc = WordCloud(width = 2000, height = 1000).generate(x)\nplt.imshow(wc)\nplt.axis('off')\nplt.show()\n\"\"\"\n### EDA\n\"\"\"\nnews['date'] = news['date'].str.replace('Jul', 'July')\nnews['date'] = news['date'].str.replace('Sep', 'September')\nnews['date'] = news['date'].str.replace('Oct', 'October')\nnews['date'] = news['date'].str.replace('Aug', 'August')\nnews['date'] = news['date'].str.replace('Augustust', 'August')\nnews['date'] = news['date'].str.replace('Dec', 'December')\nnews['date'] = news['date'].str.replace('Nov', 'November')\nnews['date'] = news['date'].str.replace('Decemberember', 'December')\nnews['date'] = news['date'].str.replace('Septembertember', 'September')\nnews['date'] = news['date'].str.replace('Jun', 'June')\nnews['date'] = news['date'].str.replace('Junee', 'June')\nnews['date'] = news['date'].str.replace('Feb', 'February')\nnews['date'] = news['date'].str.replace('Februaryruary', 'February')\nnews['date'] = news['date'].str.replace('Mar', 'March')\nnews['date'] = news['date'].str.replace('Marchch', 'March')\nnews['date'] = news['date'].str.replace('Apr', 'April')\nnews['date'] = news['date'].str.replace('Aprilil', 'April')\nnews['date'] = news['date'].str.replace('Julyy', 'July')\nnews['date'] = news['date'].str.replace('Jan', 'January')\nnews['date'] = news['date'].str.replace('Januaryuary', 'January')\nnews['date'] = news['date'].str.replace('Novemberember', 'November')\nnews['date'] = news['date'].str.replace('Octoberober', 'October')\ni = news[(news.date == '14-February-18')].index\nnews = news.drop(i)\nj = news[(news.date == '15-February-18')].index\nnews = news.drop(j)\nk = news[(news.date == '16-February-18')].index\nnews = news.drop(k)\nl = news[(news.date == '17-February-18')].index\nnews = news.drop(l)\nm = news[(news.date == '18-February-18')].index\nnews = news.drop(m)\nn = news[(news.date == '19-February-18')].index\nnews = news.drop(n)\no = news[(news.date == 'https:\/\/100percentfedup.com\/video-hillary-asked-about-trump-i-just-want-to-eat-some-pie\/')].index\nnews = news.drop(o)\np = news[(news.date == 'https:\/\/100percentfedup.com\/12-yr-old-black-conservative-whose-video-to-obama-went-viral-do-you-really-love-america-receives-death-threats-from-left\/')].index\nnews = news.drop(p)\nq = news[(news.date == 'https:\/\/fedup.wpengine.com\/wp-content\/uploads\/2015\/04\/hillarystreetart.jpg')].index\nnews = news.drop(q)\nr = news[(news.date == 'https:\/\/fedup.wpengine.com\/wp-content\/uploads\/2015\/04\/entitled.jpg')].index\nnews = news.drop(r)\ns = news[(news.date == 'MSNBC HOST Rudely Assumes Steel Worker Would Never Let His Son Follow in His Footsteps\u2026He Couldn\u2019t Be More Wrong [Video]')].index\nnews = news.drop(s)\nt = news[(news.date == 'https:\/\/100percentfedup.com\/served-roy-moore-vietnamletter-veteran-sets-record-straight-honorable-decent-respectable-patriotic-commander-soldier\/')].index\nnews = news.drop(t)\nnews['date'] = pd.to_datetime(news['date'])\nnews['Day'] = news['date'].dt.day\nnews['Month'] = news['date'].dt.month\nnews['Year'] = news['date'].dt.year\nplt.hist(news[news['category']=='fake']['Word_Count'], bins=100, alpha=0.7)\nplt.hist(news[news['category']=='true']['Word_Count'], bins=100, alpha=0.7)\nplt.show()\nplt.hist(news[news['category']=='fake']['punct_count'], bins=100, alpha=0.7)\nplt.hist(news[news['category']=='true']['punct_count'], bins=100, alpha=0.7)\nplt.show()\n\"\"\"\n### Data Preparation\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score,classification_report,confusion_matrix\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer \nX = news['text']\ny = news['category']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, shuffle = True, \n                                                    stratify = news['category'])\n\"\"\"\n### Bag of Words Creation\n\"\"\"\nvectorizer = TfidfVectorizer()\nX_train1 = vectorizer.fit_transform(X_train)\nX_train1.shape\n\"\"\"\n### Pipeline and RandomForestClassifier\n\"\"\"\nclf = Pipeline([('tfidf',TfidfVectorizer()),('clf',RandomForestClassifier(n_estimators=100, n_jobs=-1))])\nclf.fit(X_train,y_train)\ny_pred = clf.predict(X_test)\nconfusion_matrix(y_test,y_pred)\nprint(classification_report(y_test,y_pred))\naccuracy_score(y_test,y_pred)\n\"\"\"\n### SVM\n\"\"\"\nclf = Pipeline([('tfidf',TfidfVectorizer()),('clf',SVC(C = 1000, gamma = 'auto'))])\nclf.fit(X_train,y_train)\ny_pred = clf.predict(X_test)\nconfusion_matrix(y_test,y_pred)\nprint(classification_report(y_test,y_pred))\naccuracy_score(y_test,y_pred)","meta":"{'source': 'AI4Code', 'id': '2b296cae65746d'}"}
{"id":"111959","text":"### Importar librerias necesarias\nimport numpy as np\nimport pandas as pd\n \nimport xgboost as xgb\nfrom sklearn import metrics, model_selection\n\"\"\"\n* Para predecir qu\u00e9 productos comprados anteriormente estar\u00e1n en el pr\u00f3ximo pedido de un usuario\n\nComenzaremos con la lectura del archivo de pedidos.\n\"\"\"\ndata_path = \"..\/input\/\"\norders_df = pd.read_csv(data_path + \"orders.csv\", usecols=[\"order_id\",\"user_id\",\"order_number\"])\naisles=pd.read_csv('..\/input\/aisles.csv')\ndepartments=pd.read_csv('..\/input\/departments.csv')\norders=pd.read_csv('..\/input\/orders.csv')\norderp=pd.read_csv('..\/input\/order_products__prior.csv')\nordert=pd.read_csv('..\/input\/order_products__train.csv')\nproducts=pd.read_csv('..\/input\/products.csv')\naisles.head()\nprint('Total pasillos: {}'.format(aisles.shape[0]))\ndepartments.head()\nprint('Total departamentos: {}'.format(departments.shape[0]))\norders.head()\nprint('Total pedidos: {}'.format(orders.shape[0]))\norderp.head()\nprint('Total pedidosP: {}'.format(orderp.shape[0]))\nordert.head()\nprint('Total pedidosT: {}'.format(ordert.shape[0]))\nproducts.head()\nprint('Total productos: {}'.format(products.shape[0]))\n# Combinanaci\u00f3n pasillos, departamentos y productos (left joined to products)\ngoods = pd.merge(left=pd.merge(left=products, right=departments, how='left'), right=aisles, how='left')\n# para conservar '-' y hacer que los nombres de los productos sean m\u00e1s \"est\u00e1ndar\"\ngoods.product_name = goods.product_name.str.replace(' ', '_').str.lower() \n\ngoods.head()\nimport matplotlib.pyplot as plt # plotting\n\n\n# informaci\u00f3n b\u00e1sica del grupo (departamentos)\nplt.figure(figsize=(12, 5))\ngoods.groupby(['department']).count()['product_id'].copy()\\\n.sort_values(ascending=False).plot(kind='bar', \n                                   #figsize=(12, 5), \n                                   title='Departments: Product #')\n\n\n# informaci\u00f3n b\u00e1sica del grupo (top-x aisles)\ntop_aisles_cnt = 15\nplt.figure(figsize=(12, 5))\ngoods.groupby(['aisle']).count()['product_id']\\\n.sort_values(ascending=False)[:top_aisles_cnt].plot(kind='bar', \n                                   #figsize=(12, 5), \n                                   title='Aisles: Product #')\n\n# Volumen de departamentos de parcelas, dividido por pasillos.\nf, axarr = plt.subplots(6, 4, figsize=(12, 30))\nfor i,e in enumerate(departments.department.sort_values(ascending=True)):\n    axarr[i\/\/4, i%4].set_title('Dep: {}'.format(e))\n    goods[goods.department==e].groupby(['aisle']).count()['product_id']\\\n    .sort_values(ascending=False).plot(kind='bar', ax=axarr[i\/\/4, i%4])\nf.subplots_adjust(hspace=2)\n\"\"\"\nDado que el objetivo es predecir qu\u00e9 productos comprados anteriormente estar\u00e1n en el pr\u00f3ximo pedido, primero obtengamos la lista de todos los productos comprados por el cliente.\n\"\"\"\n# leer el archivo de pedido anterior #\nprior_df = pd.read_csv(data_path + \"order_products__prior.csv\")\n\n# fusionarse con el archivo de pedidos para obtener el user_id #\nprior_df = pd.merge(prior_df, orders_df, how=\"inner\", on=\"order_id\")\n\n# Obtenga los productos y reordene el estado de la \u00faltima compra de cada usuario.#\nprior_grouped_df = prior_df.groupby(\"user_id\")[\"order_number\"].aggregate(\"max\").reset_index()\nprior_df_latest = pd.merge(prior_df, prior_grouped_df, how=\"inner\", on=[\"user_id\", \"order_number\"])\nprior_df_latest = prior_df_latest[[\"user_id\", \"product_id\", \"reordered\"]]\nprior_df_latest.columns = [\"user_id\", \"product_id\", \"reordered_latest\"]\n\n# Obtenga el recuento de cada producto y el n\u00famero de pedidos por parte del cliente #\nprior_df = prior_df.groupby([\"user_id\",\"product_id\"])[\"reordered\"].aggregate([\"count\", \"sum\"]).reset_index()\nprior_df.columns = [\"user_id\", \"product_id\", \"reordered_count\", \"reordered_sum\"]\n\n# fusionar el df anterior con el \u00faltimo df#\nprior_df = pd.merge(prior_df, prior_df_latest, how=\"left\", on=[\"user_id\",\"product_id\"])\nprior_df.head()\n\"\"\"\nLea el entrenamiento y el conjunto de datos de prueba y luego fusionar con los datos de los pedidos para obtener el user_id para el order_id correspondiente.\n\"\"\"\norders_df.drop([\"order_number\"],axis=1,inplace=True)\n\ntrain_df = pd.read_csv(data_path + \"order_products__train.csv\", usecols=[\"order_id\"])\ntrain_df = train_df.groupby(\"order_id\").aggregate(\"count\").reset_index()\ntest_df = pd.read_csv(data_path + \"sample_submission.csv\", usecols=[\"order_id\"])\ntrain_df = pd.merge(train_df, orders_df, how=\"inner\", on=\"order_id\")\ntest_df = pd.merge(test_df, orders_df, how=\"inner\", on=\"order_id\")\nprint(train_df.shape, test_df.shape)\n\"\"\"\nCombinar el entrenamiento y los datos de prueba con prior_df para obtener los productos comprados previamente por el cliente.\n\"\"\"\ntrain_df = pd.merge(train_df, prior_df, how=\"inner\", on=\"user_id\")\ntest_df = pd.merge(test_df, prior_df, how=\"inner\", on=\"user_id\")\ndel prior_df, prior_grouped_df, prior_df_latest\nprint(train_df.shape, test_df.shape)\n\"\"\"\nEl archivo products.csv contiene informaci\u00f3n sobre los productos, como a qu\u00e9 departamento y pasillo pertenece el producto en cuesti\u00f3n. As\u00ed que fusionear el entrenamiento y los datos de prueba con la informaci\u00f3n del producto.\n\"\"\"\nproducts_df = pd.read_csv(data_path + \"products.csv\", usecols=[\"product_id\", \"aisle_id\", \"department_id\"])\ntrain_df = pd.merge(train_df, products_df, how=\"inner\", on=\"product_id\")\ntest_df = pd.merge(test_df, products_df, how=\"inner\", on=\"product_id\")\ndel products_df\nprint(train_df.shape, test_df.shape)\n\"\"\"\nAhora tenemos todos los productos que el cliente ha comprado anteriormente, junto con algunas caracter\u00edsticas. Por lo tanto, podemos usar el conjunto de datos del entrenamiento para rellenar la variable objetivo, es decir, el producto se ha reordenado en el siguiente orden.\n\"\"\"\ntrain_y_df = pd.read_csv(data_path + \"order_products__train.csv\", usecols=[\"order_id\", \"product_id\", \"reordered\"])\ntrain_y_df = pd.merge(train_y_df, orders_df, how=\"inner\", on=\"order_id\")\ntrain_y_df = train_y_df[[\"user_id\", \"product_id\", \"reordered\"]]\n#print(train_y_df.reordered.sum())\ntrain_df = pd.merge(train_df, train_y_df, how=\"left\", on=[\"user_id\", \"product_id\"])\ntrain_df[\"reordered\"].fillna(0, inplace=True)\nprint(train_df.shape)\n#print(train_df.reordered.sum())\ndel train_y_df\n# target variable for train set #\ntrain_y = train_df.reordered.values\n\n# marco de datos para las predicciones del conjunto de pruebas #\nout_df = test_df[[\"order_id\", \"product_id\"]]\n\n# soltar las columnas innecesarias #\ntrain_df = np.array(train_df.drop([\"order_id\", \"user_id\", \"reordered\"], axis=1))\ntest_df = np.array(test_df.drop([\"order_id\", \"user_id\"], axis=1))\nprint(train_df.shape, test_df.shape)\n# funci\u00f3n para ejecutar el modelo xgboost #\ndef runXGB(train_X, train_y, test_X, test_y=None, feature_names=None, seed_val=0):\n        params = {}\n        params[\"objective\"] = \"binary:logistic\"\n        params['eval_metric'] = 'logloss'\n        params[\"eta\"] = 0.05\n        params[\"subsample\"] = 0.7\n        params[\"min_child_weight\"] = 10\n        params[\"colsample_bytree\"] = 0.7\n        params[\"max_depth\"] = 8\n        params[\"silent\"] = 1\n        params[\"seed\"] = seed_val\n        num_rounds = 100\n        plst = list(params.items())\n        xgtrain = xgb.DMatrix(train_X, label=train_y)\n\n        if test_y is not None:\n                xgtest = xgb.DMatrix(test_X, label=test_y)\n                watchlist = [ (xgtrain,'train'), (xgtest, 'test') ]\n                model = xgb.train(plst, xgtrain, num_rounds, watchlist, early_stopping_rounds=50, verbose_eval=10)\n        else:\n                xgtest = xgb.DMatrix(test_X)\n                model = xgb.train(plst, xgtrain, num_rounds)\n\n        pred_test_y = model.predict(xgtest)\n        return pred_test_y\n# ejecuta el modelo xgboost #\npred = runXGB(train_df, train_y, test_df)\ndel train_df, test_df\n\n# Usa valor cut-off para obtener las predicciones #\ncutoff = 0.2\npred[pred>=cutoff] = 1\npred[pred<cutoff] = 0\nout_df[\"Pred\"] = pred\nout_df = out_df.ix[out_df[\"Pred\"].astype('int')==1]\n# cuando hay m\u00e1s de 1 producto, fusionarlos en una sola cadena #\ndef merge_products(x):\n    return \" \".join(list(x.astype('str')))\nout_df = out_df.groupby(\"order_id\")[\"product_id\"].aggregate(merge_products).reset_index()\nout_df.columns = [\"order_id\", \"products\"]\n# lea el archivo csv de muestra y rellene los productos de las predicciones #\nsub_df = pd.read_csv(data_path + \"sample_submission.csv\", usecols=[\"order_id\"])\nsub_df = pd.merge(sub_df, out_df, how=\"left\", on=\"order_id\")\n\n# cuando no hay predicciones usa \"ninguna\" #\nsub_df[\"products\"].fillna(\"None\", inplace=True)\nsub_df.to_csv(\"xgb_starter_3450.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': 'cdb1013465c4e7'}"}
{"id":"34842","text":"from IPython.display import clear_output\n!pip3 install rx\nclear_output()\nimport rx\nfrom rx import of,operators as ops\npublisher = of(\"Apple\", \"Banna\", \"PineApple\", \"Melon\", \"Strawberry\")\n\"\"\"\n# Example 1\n\"\"\"\ndef getFruits(minLength):\n    return rx.pipe(\n        ops.filter(lambda fruit: len(fruit) >= minLength),\n    )\n\npublisher.pipe(\n   getFruits(6)\n).subscribe(lambda value: print(\"Received {0}\".format(value)))\n\"\"\"\n# Example 2\n\"\"\"\ndef lowercase():\n    \n    def _lowercase(source):\n        \n        def subscribe(observer, scheduler = None):\n            def on_next(value):\n                observer.on_next(value.lower())\n\n            return source.subscribe(\n                on_next,\n                observer.on_error,\n                observer.on_completed,\n                scheduler)\n        \n        return rx.create(subscribe)\n    \n    return _lowercase\n\npublisher.pipe(\n        lowercase()\n     ).subscribe(lambda value: print(\"Received {0}\".format(value)))","meta":"{'source': 'AI4Code', 'id': '40299be6beeae9'}"}
{"id":"4162","text":"\"\"\"\n## Video Game Sales Exploratory Data Analysis by Ammar Altalibi\n\nUses 'Sales Of Video Games' dataset from Kaggle\n\nLink to dataset: \nhttps:\/\/www.kaggle.com\/arslanali4343\/sales-of-video-games\n\nThe data is comprised of video games from 1980-2016 and their sales across NA, EU, JP, and total Global sales.\n\n\n---\n\n\n\nThis is my exploratory data analysis of global video games sales. The notebook is divided into sections, with each section divided into subsections based on what questions I have. For the Data Analysis section, I included my thoughts and observations under each graph as well.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n# Read the csv file into a dataframe\ndata = pd.read_csv('\/kaggle\/input\/sales-of-video-games\/vgsales.csv', sep = ',', encoding = 'Latin-1')\n\n# Display the first 5 rows\ndata.head()\n\"\"\"\n## Data Cleaning\n\"\"\"\n\"\"\"\nCheck to see the data types and if there are any null values\n\"\"\"\ndata.info()\n\"\"\"\nWe can see that we have some missing values in columns 'Year', 'Publisher', and 'Global_Sales'. We also need to convert Year from a string into an integer format.\n\"\"\"\n\"\"\"\nCount the number of rows with null values, and then drop the rows that are missing global sales values\n\"\"\"\ndata.isnull().sum()\ndata = data.dropna(subset = ['Global_Sales'])\n\"\"\"\nCheck the shape of our dataset (number of rows and columns)\n\"\"\"\nprint('There are',data.shape[0], 'rows in our dataframe')\nprint('There are',data['Name'].nunique(), 'unique video games in our dataframe')\nprint('There are',data.shape[1], 'columns in our dataframe')\n\"\"\"\nConverting the Year column to datetime format\n\"\"\"\ndata['Year'] = pd.to_datetime(data['Year'], format = '%Y')\n\"\"\"\n## Data Exploration\n\"\"\"\n\"\"\"\nCount the number of unique video games for each publisher and display the top 5\n\"\"\"\ndata.groupby('Publisher')[['Name']].nunique().sort_values(by = 'Name', ascending = False).head()\n\"\"\"\nCount the number of unique video games for each platform and display the top 5\n\"\"\"\ndata.groupby('Platform')[['Name']].count().sort_values(by = 'Name', ascending = False).head()\n\"\"\"\nHere are the top 10 highest selling video games globally\n\"\"\"\ndata[['Name', 'Platform', 'Year','Publisher','Global_Sales']].head(10).sort_values(by = 'Global_Sales', ascending = False)\n\"\"\"\n## Data Analysis\n\nAfter getting familiar with our data, we can begin analyzing the data further to find any trends, patterns, or any useful insights such as relationships. This section will divided based on the main question asked.\n\"\"\"\n\"\"\"\nWe first groupby publisher, and then sort the values by sales and taking the top 20, before creating a barplot\n\"\"\"\nlmdata = data.groupby('Publisher')[['Publisher','Global_Sales']].sum().sort_values('Global_Sales', ascending = False).head(20)\n\nlmdata['Global_Sales'].plot(kind = 'bar', \n                            figsize = (16,6), \n                            colormap = 'Set3', \n                            ylabel = 'Global Sales (Millions)', \n                            title = 'Global Video Games Sales by Publisher');\n\"\"\"\nObservations:\n\nWe can see that Nintendo has the greatest global sales out of any publisher, with nearly 1.8 billion in total sales, and is followed by Electronic Arts, at 1.1 billion. Lets look into Nintendo a little further.\n\"\"\"\n\"\"\"\n### Analyzing Nintendo\n\nLet's create a lineplot that shows us the total global sales for Nintendo each year\n\"\"\"\nndata = data[data['Publisher'] == 'Nintendo']\nndata = ndata.groupby('Year')[['Year','NA_Sales','EU_Sales','JP_Sales','Global_Sales']].sum()\n\nfig = plt.figure(figsize = (14,8))\nsns.lineplot(data = ndata, x = 'Year', y = 'Global_Sales');\n\"\"\"\nObservations:\n\nFor the first 20 years, Nintendo sales seem to follow a relatively consistent pattern that spikes every 3-4 years. However, there is a very steep incline from 2004-2007. What caused this?\n\"\"\"\nndata2 = data[data['Publisher'] == 'Nintendo']\nndata2 = ndata2[(ndata2['Year'] >= '2004') & (ndata2['Year'] <= '2007')]\nndata2 = ndata2[['Name','Platform','Year','Global_Sales']]\nndata2.head()\n\"\"\"\nObservations:\n\nWe can see that 'Wii Sports', the highest selling Nintendo game of all time, was released during this timeframe, which would explain the dramatic increase in sales\n\"\"\"\n\"\"\"\n### Analyzing Electronic Arts\n\nWe'll make a similar lineplot to the one made for Nintendo, in order to see the sales for EA\n\"\"\"\neadata = data[data['Publisher'] == 'Electronic Arts']\neadata = eadata.groupby('Year')[['Year','NA_Sales','EU_Sales','JP_Sales','Global_Sales']].sum()\n\nfig = plt.figure(figsize = (14,8))\nsns.lineplot(data = eadata, x = 'Year', y = 'Global_Sales');\n\"\"\"\nObservations:\n\nUnlike Nintendo, EA had a slower but more stable increase in sales. There seems to be a few years where sales sharply declined, such as 1998 and 2005, but sales recovered quickly afterwards.\n\"\"\"\n\"\"\"\n## Conclusions\n\nWhile the data was a bit messy originally, simple data cleaning and reformating solved any issues I ran across. I also found it very interesting just how many different games were released for the Nintendo DS console (over 2100 games!) with some being released around 2014, despite the console originally releasing in 2004. \n\nNintendo outselling its competitors globally was no surprise, but it was interesting seeing just out much it's able to outsell the others was fascinating. As a fan of Nintendo games since I was a child, I can't wait to see just how far Nintendo can progress in the upcoming years. Thanks for reading!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '07cb1f2ed37f10'}"}
{"id":"131879","text":"## Most Important\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nfrom pathlib import Path\nfrom PIL import Image\n\n## less Important\nfrom functools import partial\nimport os\nfrom scipy import stats\nimport missingno as msno\nimport joblib\nimport tarfile\nimport shutil\nimport urllib\n\n## Sklearn\nfrom sklearn import datasets\n## Preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n## Metrics\nfrom sklearn.metrics import accuracy_score\n\n## tensorflow & Keras\nimport tensorflow as tf    ## i will use tf for every thing and for keras using tf.keras\n\"\"\"\n## Loading the Data and Look at the Big Picture\n\"\"\"\n\"\"\"\n`Only for training here`\n\"\"\"\ntrain_labels = pd.read_csv('..\/input\/arabic-hwr-ai-pro-intake1\/train.csv')\ntrain_images = Path(r'..\/input\/arabic-hwr-ai-pro-intake1\/train')\n\n## read these all training images paths as Series\ntrain_images_paths = pd.Series(sorted(list(train_images.glob(r'*.png'))), name='Filepath').astype(str)\n\ntrain_images_paths.head()\ntrain_labels['label'].unique()\ntrain_labels['label'] = train_labels['label'] - 1\ntrain_labels['label'].unique()\n\"\"\"\n## Explore the Data\n\"\"\"\nimg_key_value = {}\nfor value in train_labels['label'].unique():\n    img_key_value[value] = train_labels[train_labels['label']==value].index[0]\n    \nimg_index = list(img_key_value.values())\nimg_label = list(img_key_value.keys())\n\nfig, ax = plt.subplots(4, 7, figsize=(12, 8))\n\ni = 0\nfor row in range(4):\n    for col in range(7):\n        plt.sca(ax[row, col])\n        plt.title(f'label = {img_label[i]}')\n        img = plt.imread(train_images_paths.iloc[img_index[i]])\n        plt.imshow(img)\n        plt.axis('off')\n        i+=1\nnp.asarray(plt.imread(train_images_paths.iloc[0])).shape\n\nfrom PIL import Image\nimg = Image.open(train_images_paths.iloc[0]).convert('L')\nnp.asarray(img)\/255\nprint('Number of Instances in train_set =>', len(train_images_paths))\nprint('Number of Instances in train_labels =>', len(train_labels))\n\nprint()\n\nimg = plt.imread(train_images_paths.iloc[img_index[20]])\nprint('shape of each Image is =>', img.shape)\n\nimg\n\"\"\"\n## Data Preprocessing\n\"\"\"\ntrain_full_labels = train_labels['label'].values\ntrain_full_set = np.empty((13440, 64, 64), dtype=np.float32)\nnewsize = (64, 64)\n\nfor idx, path in enumerate(train_images_paths):\n    img = Image.open(path).convert('L')\n    img = img.resize(newsize)\n    img = np.asarray(img)\/255\n    train_full_set[idx] = img\n    \ntrain_full_set = train_full_set.reshape(train_full_set.shape[0], train_full_set.shape[1],\\\n                                        train_full_set.shape[2], 1)\nprint('train_full_set.shape =>', train_full_set.shape)\nprint('train_full_labels.shape =>', train_full_labels.shape)\n\"\"\"\n## Split the Data\n\"\"\"\nX_train, X_valid, y_train, y_valid = train_test_split(train_full_set, train_full_labels,\\\n                                        test_size=0.1, stratify=train_full_labels, random_state=42)\n\nprint('X_train.shape =>', X_train.shape)\nprint('X_valid.shape =>', X_valid.shape)\nprint('y_train.shape =>', y_train.shape)\nprint('y_valid.shape =>', y_valid.shape)\ny_valid[y_valid == 1].shape\nnp.random.seed(10)\n\"\"\"\n## Model Training\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, BatchNormalization, Dropout, Dense\n\ndef create_model(optimizer='adam', kernel_initializer='he_normal', activation='relu'):\n  # create model\n  model = Sequential()\n  model.add(Conv2D(filters=16, kernel_size=3, padding='same', input_shape=(64, 64, 1), kernel_initializer=kernel_initializer, activation=activation))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D(pool_size=2))\n  model.add(Dropout(0.1))\n\n  model.add(Conv2D(filters=32, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D(pool_size=2))\n  model.add(Dropout(0.1))\n\n  model.add(Conv2D(filters=64, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D(pool_size=2))\n  model.add(Dropout(0.1))\n\n  model.add(Conv2D(filters=128, kernel_size=3, padding='same', kernel_initializer=kernel_initializer, activation=activation))\n  model.add(BatchNormalization())\n  model.add(MaxPooling2D(pool_size=2))\n  model.add(Dropout(0.1))\n  model.add(GlobalAveragePooling2D())\n  \n  #Fully connected final layer\n  model.add(Dense(28, activation='softmax'))\n    \n  # Compile model\n  model.compile(loss='sparse_categorical_crossentropy', metrics=['accuracy'], optimizer=optimizer)\n  return model\nmodel = create_model(optimizer='Adam', kernel_initializer='uniform', activation='relu')\nmodel.summary()\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\n# using checkpoints to save model weights to be used later instead of training again on the same epochs.\ncheckpointer = ModelCheckpoint(filepath='weights6.hdf5', verbose=1, save_best_only=True)\nearly_stopp = EarlyStopping(patience=10, restore_best_weights=True)\nhistory = model.fit(X_train, y_train, \n                    validation_data=(X_valid, y_valid),\n                    epochs=100, batch_size=20, verbose=1)\n# history = model.fit(X_train, y_train, \n#                     validation_data=(X_valid, y_valid),\n#                     epochs=100, batch_size=20, verbose=1, callbacks=[checkpointer, early_stopp])\npd.DataFrame(history.history).plot(figsize=(10, 6));\nloss_all_data, acc_all_data = model.evaluate(train_full_set, train_full_labels, verbose=0)\nprint('loss_all_data =>', loss_all_data)\nprint('acc_all_data =>', acc_all_data)\n\"\"\"\n## Evaluation on Testing DataSet\n\"\"\"\ntest_labels = pd.read_csv('..\/input\/arabic-hwr-ai-pro-intake1\/test.csv')\ntest_images = Path(r'..\/input\/arabic-hwr-ai-pro-intake1\/test')\n\n## read these all training images paths as Series\ntest_images_paths = pd.Series(sorted(list(test_images.glob(r'*.png'))), name='Filepath').astype(str)\n\ntest_images_paths.head()\nprint('Number of Instances in test_set is', len(test_images_paths))\ntest_full_set = np.empty((3360, 64, 64), dtype=np.float32)\nnewsize = (64, 64)\n\nfor idx, path in enumerate(test_images_paths):\n    img = Image.open(path).convert('L')\n    img = img.resize(newsize)\n    img = np.asarray(img)\/255\n    test_full_set[idx] = img\n    \ntest_full_set = test_full_set.reshape(test_full_set.shape[0], test_full_set.shape[1],\\\n                                        test_full_set.shape[2], 1)\nprint('test_full_set.shape =>', test_full_set.shape)\ny_preds_classes = np.argmax(model.predict(test_full_set) , axis=-1)\ny_preds_classes = y_preds_classes + 1\ny_preds_classes.shape\ntest_labels['label'] = y_preds_classes\ntest_labels['label'].value_counts().plot(kind='bar')\ntest_labels[['id', 'label']].to_csv('\/kaggle\/working\/submission.csv', index=False)\n\"\"\"\n## Done :D\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f29b655dd3def2'}"}
{"id":"4291","text":"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n%matplotlib inline\ntrain = pd.read_json('..\/input\/stanford-covid-vaccine\/train.json', lines=True)\ntest = pd.read_json('..\/input\/stanford-covid-vaccine\/test.json', lines=True)\nsubmission = pd.read_csv('..\/input\/stanford-covid-vaccine\/sample_submission.csv')\ntrain.head()\ntest.head()\nsubmission.head()\n\"\"\"\nAh! Got something. If we look at the train set columns and test set columns, here is what I found.\n\"\"\"\ntrain.columns\ntest.columns\nset(train.columns).difference(test.columns).difference(submission.columns)\n\"\"\"\nApart from the columns from submission files, we have the above columns extra in our train set. This thing is mentiond in the Data section of the competition, however I am summarizing a few points as per my understading.\n\"\"\"\n\"\"\"\n\n\n*   There were 3029 RNA sequeces.\n*   Experiments were done using first 68 values of the 107-length sequence.\n-   These 3069 (107-base) were split into 2400 train + 629 test with filters being applied to choose the 629 samples. The filters are as follows:\n\n\n\n---\n\n1. Minimum value across all 5 conditions must be greater than -0.5.\n2. Mean signal\/noise across all 5 conditions must be greater than 1.0. [Signal\/noise is defined as mean( measurement value over 68 nts )\/mean( statistical error in measurement value over 68 nts)]\n3. To help ensure sequence diversity, the resulting sequences were clustered into clusters with less than 50% sequence similarity, and the 629 test set sequences were chosen from clusters with 3 or fewer members. That is, any sequence in the test set should be sequence similar to at most 2 other sequences.\n\n---\nAnd as per the instructions, Private LB scoring will be made on 130-base 3005 sequences where the measurement is done on the basis of first 91 bases.\n\n> Note that, the above filters won't be applied to these 3005 samples.\n\"\"\"\n# let's do some cleaning and understand our data more clearly\ntrain = train.drop(['index'], axis=1)\ntest = test.drop(['index'], axis=1)\n\"\"\"\n# Understading our Train set\n\"\"\"\ntrain.info()\n\"\"\"\nNo null values present in the train set.\n\"\"\"\nprint(train['sequence'].apply(lambda x: len(x)).value_counts())  # all the sequences have 107 bases\nprint(train['structure'].apply(lambda x: len(x)).value_counts())  # all the structures have 107 bases\nprint(train['predicted_loop_type'].apply(lambda x: len(x)).value_counts())  # all the structures have 107 bases\n\"\"\"\nAnd reactivity_error,\tdeg_error_Mg_pH10,\tdeg_error_pH10,\tdeg_error_Mg_50C,\tdeg_error_50C,\treactivity,\tdeg_Mg_pH10,\tdeg_pH10,\tdeg_Mg_50C,\tdeg_50C; these columns have length 68 as its measured on first 68 bases.\n\"\"\"\ntrain.head()\ntest.head()\n\"\"\"\nSome Measure clues that you might miss:\n- Test set has two types of sequences one of length 107 and another of length 130. \n- As mentioned earlier, the 107 base sequences are filtered out from the 3029 samples of the previous dataset, and these consists of public leader board.\n- Rest 3005 samples are of length 130.\n\"\"\"\n3005 * 130 + 629 * 107\n\"\"\"\nThis is what is the lenght of our submission file. So, we gotta predict the five measurements for each base of each sequence, or say it in terms of Sequence models, we gotta predict sequences of length x from sequences of length x, where the values of x can be 107 -> 107 and 130 -> 130 for test cases and 107 -> 68 for train cases.\n\"\"\"\n\"\"\"\n# EDA on RNA Sequences\n\"\"\"\n\"\"\"\n## For Sequences:\n\n- The possible values are A, G, C and U.\n\"\"\"\ntrain['seq_counts'] = train['sequence'].apply(lambda x: Counter(x.upper()))\ntrain['seq_counts']\ntrain['seq_counts'].apply(lambda x: (x.keys(), x.values()))\n# doing a bit of feature engieering by taking up the contribution of each code\npercentage = []\nfor i in range(len(train)):\n  count = train.iloc[i]['seq_counts']\n  percentage.append((count['A']\/train.iloc[i]['seq_length'],\n                     count['G']\/train.iloc[i]['seq_length'],\n                     count['C']\/train.iloc[i]['seq_length'],\n                     count['U']\/train.iloc[i]['seq_length']))\n  \npercentage = pd.DataFrame(percentage, columns=['A_p', 'G_p', 'C_p', 'U_p'])\npercentage\n\"\"\"\nIn RNA, its sequence that matters. Let's have a look on the paired-sequence. (We will focus on 3-gram model later on.)\n\"\"\"\npairs = []\nall_partners = []\nfor j in range(len(train)):\n    partners = [-1 for i in range(130)]\n    pairs_dict = {}\n    queue = []\n    for i in range(0, len(train.iloc[j]['structure'])):\n        if train.iloc[j]['structure'][i] == '(':\n            queue.append(i)\n        if train.iloc[j]['structure'][i] == ')':\n            first = queue.pop()\n            try:\n                pairs_dict[(train.iloc[j]['sequence'][first], train.iloc[j]['sequence'][i])] += 1\n            except:\n                pairs_dict[(train.iloc[j]['sequence'][first], train.iloc[j]['sequence'][i])] = 1\n                \n            partners[first] = i\n            partners[i] = first\n    \n    all_partners.append(partners)\n    \n    pairs_num = 0\n    pairs_unique = [('U', 'G'), ('C', 'G'), ('U', 'A'), ('G', 'C'), ('A', 'U'), ('G', 'U')]\n    for item in pairs_dict:\n        pairs_num += pairs_dict[item]\n    add_tuple = list()\n    for item in pairs_unique:\n        try:\n            add_tuple.append(pairs_dict[item]\/pairs_num)\n        except:\n            add_tuple.append(0)\n    pairs.append(add_tuple)\n    \npairs = pd.DataFrame(pairs, columns=['U-G', 'C-G', 'U-A', 'G-C', 'A-U', 'G-U'])\npairs\n\"\"\"\n## For Structures\n\"\"\"\npairs_rate = []\n\nfor j in range(len(train)):\n    res = dict(Counter(train.iloc[j]['structure']))\n    pairs_rate.append(res['('] \/ 53.5)  # 2 * res['(']\/107\n    \npairs_rate = pd.DataFrame(pairs_rate, columns=['pairs_rate'])\npairs_rate\n\"\"\"\n## For Predicted Loop Type\n\"\"\"\nloops = []\nfor j in range(len(train)):\n    counts = dict(Counter(train.iloc[j]['predicted_loop_type']))\n    available = ['E', 'S', 'H', 'B', 'X', 'I', 'M']\n    row = []\n    for item in available:\n        try:\n            row.append(counts[item] \/ 107)\n        except:\n            row.append(0)\n    loops.append(row)\n    \nloops = pd.DataFrame(loops, columns=available)\nloops\n\"\"\"\n## BBPS features\n\"\"\"\n\"\"\"\nThis is a great insight found by [Hidehisa Arai](https:\/\/https:\/\/www.kaggle.com\/hidehisaarai1213\/openvaccine-checkout-bpps). Let's cultivate on it.\n\"\"\"\nbbps_dir = '..\/input\/stanford-covid-vaccine\/bpps'\n\nbbps_fns = os.listdir(bbps_dir)\nlen(train) + len(test) == len(bbps_fns)\n\"\"\"\nEach  ```.npy``` file corresponds to each sample in our train and test dataset IDs.\n\n\n\"\"\"\n\"\"\"\n### Compare between Structure and BPPS files\n\"\"\"\ndef get_bppm(id_):\n    return np.load(os.path.join(bbps_dir, bbps_fns[id_]))\n\n\ndef draw_structure(structure: str):\n    pm = np.zeros((len(structure), len(structure)))\n    start_token_indices = []\n    for i, token in enumerate(structure):\n        if token == \"(\":\n            start_token_indices.append(i)\n        elif token == \")\":\n            j = start_token_indices.pop()\n            pm[i, j] = 1.0\n            pm[j, i] = 1.0\n    return pm\n\n\ndef plot_structures(bppm: np.ndarray, pm: np.ndarray):\n    fig, axes = plt.subplots(1, 2, figsize=(10, 10))\n    axes[0].imshow(bppm)\n    axes[0].set_title(\"BPPM\")\n    axes[1].imshow(pm)\n    axes[1].set_title(\"structure\")\n    plt.show()\nfor _ in range(5):\n  idx = np.random.randint(len(bbps_fns))\n  fn = bbps_fns[idx]\n  df_id = fn.split('.')[0]\n\n  print(fn)\n  bbps_ff = get_bppm(idx)\n  struct = train[train['id']==df_id]['structure'].values[0] if df_id in train['id'].to_list() else test[test['id']==df_id]['structure'].values[0]\n  plot_struct = draw_structure(struct)\n  plot_structures(bbps_ff, plot_struct)\n\"\"\"\nFrom here, I will go for a very simple model by stacking 3 seq-models and one DNN model for our created features. Let's move ahead.\n\"\"\"\n\"\"\"\nOur target columns are\n\"\"\"\ntarget_cols = submission.columns.to_list()[1:]\nfor col in target_cols:\n  print(train[col].apply(lambda x: len(x)).sum()\/len(train))\n\n# prediction sequence lenght is 68\n\"\"\"\nAnd interestingly, our result will be measured or evalulated on 'reactivity', 'deg_Mg_pH10', 'deg_Mg_50C'. However, we gotta predict for all the 5 values.\n\"\"\"\n\"\"\"\n# Model\nSo my plan is to use the sequences, structures and predicted loops features along with bbps features (via CNN layers) with separate custom embedding for each sequential input and then concatenating them all together to get our desired output sequence of measures.\n\"\"\"\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras import layers as L\nfrom sklearn.model_selection import StratifiedKFold, KFold, GroupKFold\ndef tokentoInt(bases):\n  return {x:i for i, x in enumerate(bases)}\n  pass\n\nprint(tokentoInt(\"\".join([x for x in loops.columns])))\ndef gru_layer(hidden_dim, dropout):\n    return L.Bidirectional(L.GRU(hidden_dim, dropout=dropout, return_sequences=True, kernel_initializer='orthogonal'))\n\ndef lstm_layer(hidden_dim, dropout):\n    return L.Bidirectional(L.LSTM(hidden_dim, dropout=dropout, return_sequences=True, kernel_initializer='orthogonal'))\n# source : https:\/\/www.kaggle.com\/c\/stanford-covid-vaccine\/discussion\/183211\ndef MCRMSE(y_true, y_pred):\n    colwise_mse = tf.reduce_mean(tf.square(y_true - y_pred), axis=1)\n    return tf.reduce_mean(tf.sqrt(colwise_mse), axis=1)\ndef encoding(df, col):\n  \"\"\"\n  df: dataframe containing sequences and the features\n  col: column to apply encoding\n      : valid values are: 'sequence', 'structure' and 'predicted_loop_type'\n  \"\"\"\n  try:\n    if col == 'sequence':\n      seq_encoding = tokentoInt('AGCU')\n      \n    elif col == 'structure':\n      seq_encoding = tokentoInt('(.)')\n\n    elif col == 'predicted_loop_type':\n      seq_encoding = tokentoInt(\"\".join([x for x in loops.columns]))\n\n    return np.array(df[col].apply(lambda seq: [seq_encoding[x] for x in seq]).values.tolist())\n\n  except KeyError:\n    print('Invalid arguments as col')\n\"\"\"\n## Preparing Data to fit into our Model\n- Sequence Model\n- Structure Model\n- Predicted Loop Type\n- CNN model for BPPS files\n\"\"\"\nfrom tqdm import tqdm\n\"\"\"\nSo I plan to split the data like following:\n- train: `train_data` and `valid_data` by filtering on SN_filer == 1\n- test: `private_test` and `public_test` filtered on seq_length\n\"\"\"\nprivate_test = test.query(\"seq_length==130\").copy()\npublic_test = test.query(\"seq_length==107\").copy()\n\n# this split on train set is applied if none of the cv folding aren't applied\ntrain_data = train.query('SN_filter==0')\nval_data = train.query('SN_filter==1')\n\"\"\"\n### Features\n\"\"\"\ndef get_features(df):\n  seq_inp = encoding(df, 'sequence')\n  struc_inp = encoding(df, 'structure')\n  plt_inp = encoding(df, 'predicted_loop_type')\n  '''\n  bpps_arr = []\n  for i in tqdm(range(len(df))):\n    idx = df.loc[i]['id']\n    bpps_arr.append(np.expand_dims(np.load(os.path.join(bbps_dir, str(idx)+'.npy')), axis=-1))\n\n  cnn_inp = np.array(bpps_arr) # cnn data input\n  '''\n  return seq_inp, struc_inp, plt_inp #, cnn_inp\n\"\"\"\n### Labels\n\"\"\"\ntrain_labels = np.array(train[target_cols].values.tolist()).transpose(0, 2, 1)\ntrain_labels[0, 0, :]\ndef seq_model(encoding_dict,\n              seq_len=107,\n              pred_len=68,\n              dropout=0.4,\n              sp_dropout=0.2,\n              embed_size=128,\n              hidden_dim=256,\n              layers=2,\n              gru=False):\n  \n  # one sequence at a time of len 107 (if training specified)\n  input = L.Input(shape=(seq_len, ))\n\n  # apply embedding layer\n  embed = L.Embedding(input_dim=len(encoding_dict),\n                      output_dim=embed_size)(input)\n\n  '''reshaped = tf.reshape(embed,\n                        shape=(-1, embed.shape[1], embed.shape[2] * embed.shape[3]))'''\n  hidden = tf.keras.layers.SpatialDropout1D(sp_dropout)(embed)\n  # apply bidirectional lstm\/gru layers * layers count\n  if gru:\n    for _ in range(layers):\n      hidden = gru_layer(hidden_dim, dropout)(hidden)\n  else:\n    for _ in range(layers):\n      hidden = gru_layer(hidden_dim, dropout)(hidden)\n  \n  return tf.keras.Model(input, hidden)\n  pass\ndef cnn_model(input_shape=(107, 107), flag=False):\n  \"\"\"\n  can be of shape 107*107(train and public set) and 130*130(private set) \n  \"\"\"\n  input = L.Input(shape=(*input_shape, 1))  # images are of 2-D\n\n  # let's just go with 3 layers of CNN\n  x = L.Conv2D(kernel_size=(5, 5),\n               filters=64,\n               strides=(2, 2))(input)\n  x = L.MaxPool2D(pool_size=(2, 2))(x)\n  x = L.Activation('relu')(x)\n\n  x = L.Conv2D(kernel_size=(3, 3),\n               filters=256)(x)\n  x = L.MaxPool2D(pool_size=(2, 2))(x)\n  x = L.Activation('relu')(x)\n  \n  x = L.Conv2D(kernel_size=(1, 4), filters=512)(x)\n  x = L.Activation('relu')(x)\n  \n  if flag:\n    x = L.Conv2D(kernel_size=(2, 2), filters=512)(x)\n    x = L.Activation('relu')(x)\n    x = tf.reshape(x, shape=(-1, x.shape[1]*x.shape[2], x.shape[-1], 1))\n    return tf.keras.Model(input, x)\n\n  x = tf.reshape(x, shape=(-1, x.shape[1]*x.shape[2], x.shape[-1], 1))\n  x = L.Conv2D(kernel_size=(2, 1), filters=1)(x)\n  x = L.Activation('relu')(x)\n\n\n\n\n  return tf.keras.Model(input, x)\n  pass\ndef main_model(seq_len=107, pred_len=68, cnn_input_shape=(107, 107), flag=False):\n  \"\"\"\n  Consists of four models, one seq_model each for sequence, structure and predicted_loop\n  and one CNN for BPPS files.\n  \"\"\"\n  # extract from sequences\n  Seq_model = seq_model(tokentoInt('AGCU'), seq_len=seq_len, pred_len=pred_len, dropout=0.0)\n  Seq_op = Seq_model.output  # for train,  seq_len = 107\n\n  Struct_model = seq_model(tokentoInt('(.)'), seq_len=seq_len, pred_len=pred_len, dropout=0.0)\n  Struct_op = Struct_model.output\n\n  PLT_model = seq_model(tokentoInt(\"\".join([x for x in loops.columns])), seq_len=seq_len, pred_len=pred_len, dropout=0.0)\n  PLT_op = PLT_model.output\n  '''\n  # add cnn layer output\n  CNN_model = cnn_model(cnn_input_shape, flag=flag)\n  CNN_op = CNN_model.output\n  CNN_op = tf.reshape(CNN_op, shape=(-1, CNN_op.shape[1], CNN_op.shape[2] * CNN_op.shape[3]))\n  \n  print(Seq_op.shape, Struct_op.shape, PLT_op.shape, CNN_op.shape)\n  '''\n  # now we got 4 tensors of shape (BS, 107, 512)\n  ip = tf.add_n([Seq_op, Struct_op, PLT_op])\/3\n  print(ip.shape)\n  ip = ip[:, :pred_len]\n  ip = L.Dense(5, activation='linear')(ip)\n  print(ip.shape)\n  return tf.keras.Model(inputs=[Seq_model.input, Struct_model.input, PLT_model.input], outputs=ip)\n  pass\nmodel = main_model()\nmodel.summary()\nmodel.compile(loss=MCRMSE,\n           optimizer=tf.keras.optimizers.Adam(lr=0.001))\nlr_callback = tf.keras.callbacks.ReduceLROnPlateau(patience=5)\nsv_lstm = tf.keras.callbacks.ModelCheckpoint(f'lstm.h5')\nmodel.fit(get_features(train), train_labels,\n       epochs=75, batch_size=64,\n       callbacks=[lr_callback, sv_lstm])\nmodel_long = main_model(seq_len=130, pred_len=130, cnn_input_shape=(130, 130), flag=True)\nmodel_long.summary()\nmodel_long.load_weights('.\/lstm.h5')\npred_long = model_long.predict(get_features(private_test), verbose=1)\npred_long.shape\nmodel_short = main_model(seq_len=107, pred_len=107, cnn_input_shape=(107, 107), flag=True)\nmodel_short.summary()\nmodel_short.load_weights('.\/lstm.h5')\npred_short = model_short.predict(get_features(public_test), verbose=1)\npred_short.shape\ndef format_predictions(public_preds, private_preds):\n    preds = []\n    \n    for df, preds_ in [(public_test, public_preds), (private_test, private_preds)]:\n        for i, uid in enumerate(df.id):\n            single_pred = preds_[i]\n\n            single_df = pd.DataFrame(single_pred, columns=target_cols)\n            single_df['id_seqpos'] = [f'{uid}_{x}' for x in range(single_df.shape[0])]\n\n            preds.append(single_df)\n\n    return pd.concat(preds).groupby('id_seqpos')\ndf = format_predictions(pred_short, pred_long)\ndf.first()\nsubmission = df.sum().reset_index()\nsubmission\nsubmission.to_csv('submission.csv', index=False)\n\"\"\"\nIf you find this notebook, consider upvoting the same, I will experimenting with other approaches, I set this as my base model as of now. Thank you for reading so far.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '080178decd11da'}"}
{"id":"43567","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport re\nimport missingno as msno\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.offline as py\nimport plotly.graph_objs as go\npd.options.display.max_columns = 999\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nplt.style.use('seaborn-bright')\n\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n**Quick look**\n\"\"\"\ndf = pd.read_csv(\"..\/input\/data.csv\")\ndf.drop(columns='Unnamed: 0', inplace=True)\ndf.head(5)\ncolumns_to_drop = ['ID', 'Real Face', 'Joined', 'Loaned From', 'Contract Valid Until', 'LS',\n                   'ST', 'RS', 'LW', 'LF', 'CF','RF', 'RW', 'LAM','CAM','RAM', 'LM',\n                   'LCB', 'CB', 'RCB', 'RB', 'LCM', 'CM', 'RCM', 'RM', 'LWB', 'LDM',\n                   'CDM', 'RDM', 'RWB', 'LB','Flag', 'Club Logo']\ndf.drop(columns_to_drop, inplace=True, axis=1)\n\ndf.head(5)\n\"\"\"\n**Missing data**\n\"\"\"\nnull = df.isnull().sum()\/df.shape[0]\nplt.figure(figsize=(16,12))\nnull.plot.bar()\nplt.title('Missing data in percent', fontsize=20)\nplt.xticks(rotation=60)\nplt.show()\ncolumn_null = null[9:].index\nmsno.matrix(df[column_null])\n\"\"\"\nVariables in which occurs missing data are often specific rows which has most of the data missing. That's why I'm going to drop these rows.\n\"\"\"\ndf.dropna(inplace=True)\ndf.isnull().sum()\n\"\"\"\n**Feature enginnering need for visualization**\n\"\"\"\ndef dollar_to_number(df_value):\n    try:\n        value = float(df_value[1:-1])\n        dollar = df_value[-1:]\n\n        if dollar == 'M':\n            value = value * 1000000\n        elif dollar == 'K':\n            value = value * 1000\n    except ValueError:\n        value = 0\n    return value\n\ndef height_to_cm(df_value):\n    try:\n        feet = int(df_value[0])\n        inch = int(df_value[2:])\n        \n        new_value = (feet*30.48)+(inch*2.54)\n    except ValueError:\n        new_value = 0\n    return new_value\n\ndef weight_to_kg(df_value):\n    try:\n        lbs = int(df_value[:-3])\n        \n        new_value = lbs*0.453592\n    except ValueError:\n        new_value = 0\n    return new_value\ndf['Value'] = df['Value'].apply(dollar_to_number)\ndf['Release Clause'] = df['Release Clause'].apply(dollar_to_number)\ndf['Wage'] = df['Wage'].apply(dollar_to_number)\ndf['CM'] = df['Height'].apply(height_to_cm)\ndf['KG'] = df['Weight'].apply(weight_to_kg)\n\n#positions = {['ST', 'RW', 'LW', 'CF', 'LF', 'LS', 'RS', 'RF']:'Attacker',\n            #['CAM', 'CM', 'LM', 'RM', 'CDM', 'RCM','LCM', 'LDM', 'RDM', 'LAM', 'RAM']:'Middlefielder',\n             #['LWB', 'RWB', 'CB', 'RB', 'LB', 'LCB', 'RCB']:'Defender'}\ndf['Position_Cat'] = df['Position'].replace(['ST', 'RW', 'LW', 'CF', 'LF', 'LS', 'RS', 'RF'], 'Attacker')\ndf['Position_Cat'] = df['Position_Cat'].replace(['CAM', 'CM', 'LM', 'RM', 'CDM', 'RCM','LCM', 'LDM', 'RDM', 'LAM', 'RAM'], 'Middlefielder')\ndf['Position_Cat'] = df['Position_Cat'].replace(['LWB', 'RWB', 'CB', 'RB', 'LB', 'LCB', 'RCB'], 'Deffender')\nfield_players = df[df['Position'] != 'GK']\nfield_players.drop(columns=['GKDiving','GKHandling', 'GKKicking',\n                            'GKPositioning', 'GKReflexes'], inplace=True)\ngoalkeepers = df[df['Position'] == 'GK']\ncat_columns = df.select_dtypes(include='object')\nnumeric_columns = df.select_dtypes(exclude='object')\nnumeric_columns_field = field_players.select_dtypes(exclude='object')\nnumeric_columns_GK = goalkeepers.select_dtypes(exclude='object')\n\"\"\"\n**Correlations heatmaps for field players and goalkeepers**\n\"\"\"\nnumeric_columns_field_corr = numeric_columns_field.corr()\nnumeric_columns_GK_corr = numeric_columns_GK.corr()\nmask1 = np.zeros_like(numeric_columns_field_corr)\nmask2 = np.zeros_like(numeric_columns_GK_corr)\nmask1[np.triu_indices_from(mask1)] = True\nmask2[np.triu_indices_from(mask2)] = True\nfig = plt.figure(figsize=(15,20))\nax1 = fig.add_subplot(211)\nax1.title.set_text('Field players')\nsns.heatmap(numeric_columns_field_corr, cmap='YlGnBu', annot=True, fmt='.1f', mask=mask1)\nax2 = fig.add_subplot(212)\nax2.title.set_text('Goalkeepers')\nsns.heatmap(numeric_columns_GK_corr, cmap='YlGnBu', annot=True, fmt='.1f', mask=mask2)\n\"\"\"\n**Countries with most players**\n\"\"\"\ntop_10 = df['Nationality'].value_counts()[:20]\n\nplt.figure(figsize=(16,10))\nsns.barplot(top_10.index, top_10.values)\nplt.xticks(rotation=45)\nplt.title('Most frequent nationality of player')\nplt.show()\n\"\"\"\n**Basic statistics**\n\"\"\"\nplt.figure(figsize=(16,10))\nsns.countplot(x='Preferred Foot', data=df)\nplt.title('Foot preferation')\nfix, (ax1,ax2) = plt.subplots(1, 2, figsize=(16,10))\nsns.barplot(x=df['Work Rate'].value_counts().index, y=df['Work Rate'].value_counts().values, data=df, ax=ax1)\nax1.tick_params(rotation=45)\nax1.title.set_text('Work rate')\nsns.countplot(x='Body Type', data=df, ax=ax2, order=df['Body Type'].value_counts().index)\nax2.tick_params(rotation=45)\nax2.title.set_text('Body Type')\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,10))\nsns.countplot(x='Position_Cat', data=df, ax=ax1, order=['GK', 'Deffender', 'Middlefielder', 'Attacker'])\nsns.violinplot(x='Position_Cat', y='Overall', data=df, ax=ax2, order=['GK', 'Deffender', 'Middlefielder', 'Attacker'])\nplt.suptitle('Positions')\nax1.set_xlabel('Position category')\nax2.set_xlabel('Position category')\nplt.show()\nplt.figure(figsize=(16,10))\nsns.scatterplot(df['KG'], df['CM'], alpha=0.5)\nplt.title('Height vs Weight')\nplt.arrow(110.222856,170, 0, 5, head_width=0.5)\nplt.annotate('A. Akinfenwa', (107, 168), fontsize=12)\nplt.show()\ncorr = round(df[['Value', 'Wage']].corr().iloc[1,0], 2)\nplt.figure(figsize=(16,10))\nsns.scatterplot(df['Value']\/1000000, 'Wage', data=df, style='Position_Cat', hue='Preferred Foot', markers=['^','v', 'o','X'], palette='Set1')\nplt.text(x=40,y=500000, s='Correlattion {}'.format(corr), fontsize=15)\nplt.xlabel('Value in milions')\nplt.title('Wage vs Value')\n#plt.xlim(0,150)\n#plt.ylim(0,600000)\nplt.show()\n\"\"\"\n**Top 10 clubs**\n\"\"\"\ntop_10_club = df.groupby(by='Club').mean()['Overall'].sort_values(ascending=False)[:10].index\ndf10 = df[df['Club'].isin(top_10_club)]\nplt.figure(figsize=(16,10))\nsns.boxplot(x='Club', y='Overall', data=df10, order=top_10_club)\nplt.title('Top 10 clubs rating based on overall of players')\nplt.show()\ntop_10_value = df.groupby(by='Club').mean()['Value'].sort_values(ascending=False)[:10].index\nvalue10 = df[df['Club'].isin(top_10_value)]\nplt.figure(figsize=(16,10))\nsns.boxplot(x='Club', y=df['Value']\/1000000, data=value10, order=top_10_value)\nplt.title('Top 10 clubs rating based on value of players')\nplt.xticks(rotation=45)\nplt.show()\ntop_10_sum = df.groupby(by='Club').sum()['Value'].sort_values(ascending=False)[:10]\nplt.figure(figsize=(16,10))\nsns.barplot(top_10_sum.index, top_10_sum.values\/1000000)\nplt.title('Most valuable clubs in milions')\nplt.xticks(rotation=45)\nplt.show()\n\"\"\"\n**Effect of jersey number**\n\"\"\"\nplt.figure(figsize=(16,10))\nsns.scatterplot(y='Overall', x='Jersey Number', data=df, hue='Position_Cat', size=df['Wage'])\nplt.arrow(30, 95, -17, 0, head_width=0.85, head_length=0.5, fc='k', ec='k')\nplt.annotate('Number 10 and 7', (31, 94), fontsize=15)\nplt.xticks(np.linspace(0,100,11))\nplt.show()\n\"\"\"\n**Radar graphs**\n\"\"\"\ndata_sort = pd.DataFrame()\nbest_features = df[numeric_columns.columns].groupby(df['Position_Cat']).mean()\nfor i, j in zip(range(best_features.shape[0]), best_features.index):\n    best_9 = best_features.iloc[i,:].sort_values(ascending=False)\n    #print(best_9)\n    data_sort[j] = best_9[:15].index\n    \nbest_Attacker = ['SprintSpeed', 'Acceleration', 'Agility', 'Balance', 'ShotPower', 'Jumping']\nbest_GK = ['GKReflexes', 'GKDiving', 'GKPositioning', 'GKHandling', 'GKKicking', 'Reactions']\nbest_Middlefielder = ['Balance', 'Agility', 'Acceleration', 'SprintSpeed', 'Stamina', 'ShortPassing']\nbest_Deffender = ['Strength', 'Jumping', 'Stamina', 'StandingTackle', 'Aggression', 'SlidingTackle']\n\nlabels = [best_Attacker,best_Middlefielder, best_Deffender, best_GK]\nplayer_atk = df[df['Position_Cat'] == 'Attacker'][best_Attacker].sample(1)\nplayer_def = df[df['Position_Cat'] == 'Deffender'][best_Deffender].sample(1)\nplayer_gk = df[df['Position_Cat'] == 'GK'][best_GK].sample(1)\nplayer_mid = df[df['Position_Cat'] == 'Middlefielder'][best_Middlefielder].sample(1)\n#\nstats1=player_atk.values.T\nstats2=player_def.values.T\nstats3=player_gk.values.T\nstats4=player_mid.values.T\n#\nangles1=np.linspace(0, 2*np.pi, len(best_Attacker), endpoint=False)\nangles2=np.linspace(0, 2*np.pi, len(best_Deffender), endpoint=False)\nangles3=np.linspace(0, 2*np.pi, len(best_GK), endpoint=False)\nangles4=np.linspace(0, 2*np.pi, len(best_Middlefielder), endpoint=False)\n#\nstats1=np.concatenate((stats1,[stats1[0]]))\nstats2=np.concatenate((stats2,[stats2[0]]))\nstats3=np.concatenate((stats3,[stats3[0]]))\nstats4=np.concatenate((stats4,[stats4[0]]))\n#\nangles1=np.concatenate((angles1,[angles1[0]]))\nangles2=np.concatenate((angles2,[angles2[0]]))\nangles3=np.concatenate((angles3,[angles3[0]]))\nangles4=np.concatenate((angles4,[angles4[0]]))\n#\nplayer = [player_atk, player_mid, player_def, player_gk]\nangles = [angles1, angles2, angles3, angles4]\nstats = [stats1, stats2, stats3, stats4]\n\nfig  = plt.figure(figsize=(15,14))\nfor p, s in zip([0, 1, 2, 3],[1, 2, 3, 4]):\n    ax = fig.add_subplot(2, 2, s, polar=True)\n    ax.plot(angles[p], stats[p], 'o-', linewidth=2, label='Messi')\n    ax.fill(angles[p], stats[p], alpha=0.25)\n    ax.set_thetagrids(angles[p] * 180\/np.pi, labels[p])\n    ax.set_title(df.loc[player[p].index[0]]['Position_Cat'] + ': ' + df.loc[player[p].index[0]]['Name']\n                 + '\\n Nationality: ' + df.loc[player[p].index[0]]['Nationality']\n                 + '\\n Overall: ' + np.str(df.loc[player[p].index[0]]['Overall'])\n                )\n    fig.suptitle('Random players for each position', fontsize=16)\n\"\"\"\n**3D Scatter**\n\"\"\"\ndef scatter_3d(x, y, z):\n    \"\"\"Choose X, Y, Z.\"\"\"\n    trace1 = go.Scatter3d(\n        x=x,\n        y=y,\n        z=z,\n        mode='markers',\n        marker=dict(\n            size=12,\n            color=z,                \n            colorscale='Viridis',  \n            opacity=0.8\n\n        ),text=df['Name']\n    )\n\n    data = [trace1]\n    layout = go.Layout(\n        scene=dict(\n        xaxis=dict(\n            title=x.name),\n        yaxis=dict(\n            title=y.name),\n        zaxis=dict(\n            title=z.name)),\n        margin=dict(\n            l=0,\n            r=0,\n            b=0,\n            t=0\n        )\n    )\n    fig = go.Figure(data=data, layout=layout)\n    py.iplot(fig, filename='3d-scatter-colorscale')\nscatter_3d(df['Value'], df['Wage'], df['Overall'])\n\"\"\"\n**Finding similar player**\n\"\"\"\ndef find_player(c, player):\n    sc = StandardScaler()\n    pos = df[df['Name'] == player]['Position_Cat'].values[0]\n    base_data = df[df['Position_Cat'] == pos].reset_index(drop=True)\n    base_scales = sc.fit_transform(base_data[col_to_cluster])\n    base = pd.DataFrame(columns=col_to_cluster, data=base_scales)\n    \n    kmeans = KMeans(n_clusters=c, random_state=1)\n    k = kmeans.fit_predict(base[col_to_cluster])\n    pred = pd.concat([base_data[col_to_cluster], base_data['Name'], base_data['Overall'],\n                      pd.Series(k).rename('Cluster')], axis=1)\n    pred['Cluster'] = pred['Cluster'].astype('category')\n    \n    player_predict = pred[pred['Name'] == player]['Cluster']\n    \n    top_5_similar = pred[pred['Cluster'] == player_predict.values[0]]\n    top_5_similar = top_5_similar.sort_values(by='Overall', ascending=False)\n    \n    print(top_5_similar[:5])\n    \n    fig, ax = plt.subplots(figsize=(16,10))\n    x = np.array(pred[col_to_cluster[0]])\n    y = np.array(pred[col_to_cluster[1]])\n    cluster = np.array(pred['Cluster'])\n    for g in np.unique(cluster):\n        i = np.where(cluster == g)\n        ax.scatter(x[i], y[i], label=g)\n        \n    ax.legend()\n    plt.xlabel(col_to_cluster[0])\n    plt.ylabel(col_to_cluster[1])\n    plt.show()\n    \n    return pred\n    \n    \n\ncol_to_cluster = ['Stamina', 'Strength']\n\npred = find_player(5, 'L. Messi')","meta":"{'source': 'AI4Code', 'id': '504f81b258915f'}"}
{"id":"110458","text":"\"\"\"\n# INDIAN PREMIER LEAGUE (IPL)\n\n### The Indian Premier League (IPL) is a professional Twenty20 cricket league in India usually contested between March and May of every year by eight teams representing eight different cities or states in India. The league was founded by the Board of Control for Cricket in India (BCCI) in 2007.\n\n### Teams \n* Mumbai Indians\n* Chennai Super Kings\n* Sunrisers Hyderabad\n* Kings XI Punjab \n* Delhi Captians\n* Rajasthan Royals \n* Kolkatta Knight Riders\n* Royal Challengers Banglore\n\"\"\"\n\"\"\"\n### Problem Statement: We have the historical data of all IPL matches since the year 2008 this time we are trying to predict the player performance of each player who participated in the IPL \n\n### Libraries Used:\n* Pandas : Pandas is used for data manipulating and to slice and index the tabular dataframe. \n* Numpy : Numpy is being used to convert the dataframe into a array of numbers because the model accepts only numeric data \n* missigno : This library is used to check for null values in the given data. Since the presence of null values leads to poor performance of model\n* Matplotlib and Seaborn : These libraries are used for data visualization ie to present the numeric data in a graphical manner making it easy to interpret \n* Sklearn : This library form the brain of our machine learning model. Using the we import the Linear Regression model and the metrics to evaluate our model ie mean_squared_error. Further we also use train_test_split to split our data into training and validation set. We will talk more about this as you scroll down \n\n#### This whole model is build using python because of the following reasons:\n* Python is open source language \n* Because of its high compatablility with various modules and libraries it is the most suitable language for data analytics and machine learning applications\n* Python Code are easier to understand and interpret compared to any other programming language \n\"\"\"\n\"\"\"\n# Loading Datasets \n\"\"\"\n# 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\n\"\"\"\n### Importing Libraries \n\"\"\"\nimport missingno as msno\nfrom math import sqrt\n\nimport matplotlib.pyplot as plt \nimport seaborn as sns \nfrom termcolor import colored \n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\nimport tensorflow \nimport keras\nfrom keras.models import Sequential\nfrom keras import layers\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import layers, callbacks\n\nteams = pd.read_csv('..\/input\/ipl-2020-player-performance\/IPL 2020 Squads.csv',encoding='latin1')\nmatch2020 = pd.read_csv('..\/input\/ipl-2020-player-performance\/Matches IPL 2020.csv')\nmatch = pd.read_csv('..\/input\/ipl-2020-player-performance\/Matches IPL 2008-2019.csv')\ntrain = pd.read_csv('..\/input\/ipl-2020-player-performance\/Training.csv')\n\"\"\"\nBelow is information stored in the four tables ie teams ,match2020,match and train along with the number of rows and columns, number of null values in each column and its corresponding datatypes. There are mainly 2 data types being discussed here Object and integer \n\"\"\"\nprint('*'*50)\nprint(colored('TEAMS','red'))\nprint(teams.info())\nprint('*'*50)\nprint(colored('MATCHS IN 2020','red'))\nprint(match2020.info())\nprint('*'*50)\nprint(colored('MATCHS 2008-2019','red'))\nprint(match.info())\nprint('*'*50)\nprint(colored('TRAINING DATA','red'))\nprint(train.info())\ntrain.head(20)\n\n\"\"\"\n# Exploratory Data Analysis\n\n### This section will provide us insights about the following information:\n* Defining the target variable \n* Defining the dependent variables \n* Finding the relation between dependent and independent variables \n\"\"\"\n\"\"\"\n### Bivariate Analysis \n#### Finding the relation between all the dependent variables against the independent or target variable\n\"\"\"\nplt.figure(figsize=(15,10))\nplt.subplot(2,3,1)\nsns.scatterplot(x='Runs',y='Batting_Points',data=train)\nplt.subplot(2,3,2)\nsns.scatterplot(x='Boundaries',y='Batting_Points',data=train)\nplt.subplot(2,3,3)\nsns.scatterplot(x='Six',y='Batting_Points',data=train)\nplt.subplot(2,3,4)\nsns.barplot(x='Fifty',y='Batting_Points',data=train)\nplt.subplot(2,3,5)\nsns.barplot(x='Hundred',y='Batting_Points',data=train)\nplt.subplot(2,3,6)\nsns.barplot(x='Duck',y='Batting_Points',data=train)\nplt.figure(figsize=(15,10))\nplt.subplot(2,3,1)\nsns.scatterplot(x='Runs',y='Bowling_Points',data=train)\nplt.subplot(2,3,2)\nsns.scatterplot(x='Boundaries',y='Bowling_Points',data=train)\nplt.subplot(2,3,3)\nsns.scatterplot(x='Six',y='Bowling_Points',data=train)\nplt.subplot(2,3,4)\nsns.barplot(x='Fifty',y='Bowling_Points',data=train)\nplt.subplot(2,3,5)\nsns.barplot(x='Hundred',y='Bowling_Points',data=train)\nplt.subplot(2,3,6)\nsns.barplot(x='Duck',y='Bowling_Points',data=train)\nplt.figure(figsize=(15,10))\nplt.subplot(2,2,1)\nsns.scatterplot(x='Wickets',y='Batting_Points',data=train)\nplt.subplot(2,2,2)\nsns.barplot(x='4W_Haul',y='Batting_Points',data=train)\nplt.subplot(2,2,3)\nsns.barplot(x='5W_Haul',y='Batting_Points',data=train)\nplt.subplot(2,2,4)\nsns.barplot(x='Maidens',y='Batting_Points',data=train)\nplt.figure(figsize=(15,10))\nplt.subplot(2,2,1)\nsns.scatterplot(x='Wickets',y='Bowling_Points',data=train)\nplt.subplot(2,2,2)\nsns.barplot(x='4W_Haul',y='Bowling_Points',data=train)\nplt.subplot(2,2,3)\nsns.barplot(x='5W_Haul',y='Bowling_Points',data=train)\nplt.subplot(2,2,4)\nsns.barplot(x='Maidens',y='Bowling_Points',data=train)\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\nsns.scatterplot(x='Batting_Points',y='Total Points',data=train)\nplt.subplot(1,2,2)\nsns.scatterplot(x='Bowling_Points',y='Total Points',data=train)\n\n\"\"\"\n### Insights:\n\n* The batting score is linearly depended on Runs scored , Boundaries , Sixs , Hundreds , Fiftys and Duck outs.\n* The bowlings score is also linearly related to Runs scored , Boundaries , Sixs , Hundreds , Fiftys and Duck outs. \n* Batting score shows negative correlation with Wickets takes, 4W haul, 5W haul and maiden overs. \n* Bowling Score shows positive correlation with wickets takes , 4W Haul, 5W Haul and Maiden overs \n\n\"\"\"\n\"\"\"\n## Univariate Analysis\n* Here we look for outliers in continuous data and cap some of them to 95 or 90 percent of the maximum value. The presence of outlier cause the model to learn extreme values and overfit the training data. To generalise the data well it is good to remove outliers before feeding data to the mode\n\n* We use boxplot from seaborn library to show the presence of outliers in data\n\"\"\"\nplt.figure(figsize=(30,10))\nplt.subplot(2,4,1)\nsns.boxplot(x='Total Points',data=train)\nplt.subplot(2,4,2)\nsns.boxplot(x='Bowling_Points',data=train)\nplt.subplot(2,4,3)\nsns.boxplot(x='Batting_Points',data=train)\nplt.subplot(2,4,4)\nsns.boxplot(x='Runs',data=train)\nplt.subplot(2,4,5)\nsns.boxplot(x='Boundaries',data=train)\nplt.subplot(2,4,6)\nsns.boxplot(x='Six',data=train)\nplt.subplot(2,4,7)\nsns.boxplot(x='Wickets',data=train)\n\n\"\"\"\n## Outlier Treatment\n\"\"\"\ndef Outlier(col_name,quantile):\n    uiqr = np.percentile(train[str(col_name)],quantile)\n    print('Capping outlier to value {}'.format(uiqr))\n    filt = train[str(col_name)] > uiqr\n    train.loc[filt,:] = uiqr\n    \n    return sns.boxplot(x=str(col_name),data=train)\nplt.figure(figsize=(30,10))\nplt.subplot(2,3,1)\nOutlier('Total Points',95)\nplt.subplot(2,3,2)\nOutlier('Bowling_Points',90)\nplt.subplot(2,3,3)\nOutlier('Batting_Points',95)\nplt.subplot(2,3,4)\nOutlier('Runs',95)\nplt.subplot(2,3,5)\nOutlier('Boundaries',87)\ntrain.columns\ntrain['Id']\n\"\"\"\n#### Since the model accepts only numeric data and the columns Id from train dataset is object data type we cannot feed it to the model. Hence i first split the id column info id and surename and dropped the column.\n\"\"\"\ntrain['Id'] = np.array(train['Id'].str.split(' ',expand=True))\ntrain.head(10)\ntrain.drop(train[train['Id'].isnull() == True].index, inplace = True) \n\ntrain.head()\n\"\"\"\n#### Used numpy library to convert the dataframe in to numerical arrays. Further assigned the dependent variables to the variable x and independent variable to y \n\"\"\"\nx=np.array(train.iloc[:,1:-1])\ny=np.array(train.iloc[:,-1])\n\"\"\"\n#### Here we divide the hundred percent of training data into 80% train and 20% validation data using train_test_split method from sklearn library. We train the model on 80% of the training data and test the model on rest of the 20% of validation data which is new to the model. Then compare the prediction wi\n\"\"\"\ntrain_x,val_x,train_y,val_y = train_test_split(x,y,test_size=0.2,random_state=0)\nprint(train_x.shape)\nprint(val_x.shape)\nprint('*'*30)\nprint(train_y.shape)\nprint(val_y.shape)\n\"\"\"\n# Linear Regression \n#### Since there exists a linear relation between the dependent and independent variable we choose the linear regression model to perform the prediction task. This model accepts numeric values and tunes its weights in order to form a generalised polynomial equation that can evaluate the value of y. \n\n\"\"\"\nmodel = LinearRegression()\nmodel.fit(train_x,train_y)\npred_y = model.predict(val_x)\npred_y[2]\nval_y[2]\nsqrt(mean_squared_error(pred_y,val_y))","meta":"{'source': 'AI4Code', 'id': 'caf88a8ed207a4'}"}
{"id":"36711","text":"\"\"\"\n# **Recursive Feature Elimination (RFE) to Predict Customer Churn**\n\"\"\"\n\"\"\"\nLet's dig down how recursive feature elimination can be useful to reduce data with many features, and this feature-selected data will still give similar performance result (or even higher) on various machine learning models compared to the original data.\n\"\"\"\n\"\"\"\n## Contents\n1. [Exploratory Data Analysis](#Exploratory-Data-Analysis)\n2. [Feature Engineering and Selection](#Feature-Engineering-and-Selection)\n3. [Build Some ML Models](#Build-Some-ML-Models)\n4. [Model Evaluation](#Model-Evaluation)\n5. [Feature Importance](#Feature-Importance)\n6. [Summary](#Summary)\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, OrdinalEncoder, LabelEncoder\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, cross_validate\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score, plot_confusion_matrix\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline\nrandom_state = 123\n\"\"\"\nImport the dataset.\n\"\"\"\ndf = pd.read_csv(\"..\/input\/telco-customer-churn\/WA_Fn-UseC_-Telco-Customer-Churn.csv\", index_col=\"customerID\")\ndf.head()\n\"\"\"\nDo some changes on \"SeniorCitizen\" and \"TotalCharges\" data type to make them appropriate.\n\"\"\"\ndf[\"TotalCharges\"] = df[\"TotalCharges\"].apply(pd.to_numeric, errors='coerce')\ndf[\"SeniorCitizen\"] = df[\"SeniorCitizen\"].apply(lambda x: \"Yes\" if x == 0 else \"No\")\n\"\"\"\nLet's check the data type.\n\"\"\"\ndf.dtypes\n\"\"\"\nRemove any rows that have NaN value.\n\"\"\"\ndf.isnull().sum()\ndf = df.dropna()\ndf.isnull().sum()\n\"\"\"\n<a id='Exploratory-Data-Analysis'><\/a>\n# A. Exploratory Data Analysis\n\"\"\"\n\"\"\"\nMake histogram for every numeric features against churn.\n\"\"\"\nfor column in df.select_dtypes(\"number\").columns:\n    df.pivot(columns=\"Churn\")[column].plot.hist(alpha=0.5)\n    plt.title(column)\n    plt.show()\n\"\"\"\nThen, make bar plot for every categorical features against churn.\n\"\"\"\nfor column in df.select_dtypes(\"object\").columns.drop(\"Churn\"):\n    df.pivot(columns=\"Churn\")[column].apply(pd.value_counts).plot.bar()\n    plt.title(column)\n    plt.show()\n\"\"\"\n<a id='Feature-Engineering-and-Selection'><\/a>\n# B. Feature Engineering and Selection\n\"\"\"\n\"\"\"\nSeparate features and label column into two variables, X and y.\n\"\"\"\nX = df.drop(columns=[\"Churn\"])\ny = df[\"Churn\"]\n\"\"\"\nUse StandarScaler to standardize all numerical features, so their mean and standard deviation are zero and one, respectively.\n\"\"\"\nscaler = StandardScaler()\nX[X.select_dtypes(\"number\").columns] = scaler.fit_transform(X.select_dtypes(\"number\"))\n\"\"\"\nEncode each categorical feature by using ordinal encoder.\n\"\"\"\nordEnc = OrdinalEncoder(dtype=np.int)\nX[X.select_dtypes(\"object\").columns] = ordEnc.fit_transform(X.select_dtypes(\"object\"))\n\"\"\"\nAlso, don't forget to encode the label.\n\"\"\"\nlabEnc = LabelEncoder()\ny = labEnc.fit_transform(y)\n\"\"\"\nDo feature selection by using recursive feature elimination (RFE). Use Logistic Regression classifier as the estimator, and set the fold (k) for cross-validation to 10.\n\"\"\"\nestimator = LogisticRegression(random_state=random_state)\nrfecv = RFECV(estimator=estimator, cv=StratifiedKFold(10, random_state=random_state, shuffle=True), scoring=\"accuracy\")\nrfecv.fit(X, y)\n\"\"\"\nMake a line plot of number of selected features against cross-validation score. Then, print the optimal number of features.\n\"\"\"\nplt.figure(figsize=(8, 6))\nplt.plot(range(1, len(rfecv.grid_scores_)+1), rfecv.grid_scores_)\nplt.grid()\nplt.xticks(range(1, X.shape[1]+1))\nplt.xlabel(\"Number of Selected Features\")\nplt.ylabel(\"CV Score\")\nplt.title(\"Recursive Feature Elimination (RFE)\")\nplt.show()\n\nprint(\"The optimal number of features: {}\".format(rfecv.n_features_))\n\"\"\"\nMake a new DataFrame called \"X_rfe\" that contains selected features.\n\"\"\"\nX_rfe = X.iloc[:, rfecv.support_]\n\"\"\"\nCompare the dimension of DataFrame \"X\" and \"X_rfe\".\n\"\"\"\nprint(\"\\\"X\\\" dimension: {}\".format(X.shape))\nprint(\"\\\"X\\\" column list:\", X.columns.tolist())\nprint(\"\\\"X_rfe\\\" dimension: {}\".format(X_rfe.shape))\nprint(\"\\\"X_rfe\\\" column list:\", X_rfe.columns.tolist())\n\"\"\"\nFrom the steps above, the data is reduced to only 9 features from 19 features in the original data.\n\nNow, let's compare their performance on various machine learning models.\n\"\"\"\n\"\"\"\n<a id='Build-Some-ML-Models'><\/a>\n# C. Build Some ML Models\n\"\"\"\n\"\"\"\nSplit the feature-selected DataFrame into train and test set. Also, do the same thing on the original DataFrame.\n\"\"\"\nX_train, X_test, X_rfe_train, X_rfe_test, y_train, y_test = train_test_split(X, X_rfe, y, \n                                                                             train_size=0.8, \n                                                                             stratify=y,\n                                                                             random_state=random_state)\nprint(\"Train size: {}\".format(len(y_train)))\nprint(\"Test size: {}\".format(len(y_test)))\n\"\"\"\nLet's try these following classifiers to make the machine learning model, and compare their performance for the original and feature-selected dataset.\n* Logistic Regression\n* Support Vector Machine (linear kernel)\n* Naive Bayes\n* k-Nearest Neighbors\n* Stochastic Gradient Descent\n* Decision Tree\n* AdaBoost\n* Multi-layer Perceptron\n\"\"\"\nclf_keys = [\"Logistic Regression\", \"Support Vector Machine\", \"Naive Bayes\", \"k-Nearest Neighbors\",\n            \"Stochastic Gradient Descent\", \"Decision Tree\", \"AdaBoost\", \"Multi-layer Perceptron\"]\nclf_values = [LogisticRegression(random_state=random_state), SVC(kernel=\"linear\", random_state=random_state),\n              GaussianNB(), KNeighborsClassifier(), SGDClassifier(random_state=random_state),\n              DecisionTreeClassifier(random_state=random_state), AdaBoostClassifier(random_state=random_state), \n              MLPClassifier(random_state=random_state, max_iter=1000)]\nclf_rfe_keys = [\"Logistic Regression\", \"Support Vector Machine\", \"Naive Bayes\", \"k-Nearest Neighbors\",\n                \"Stochastic Gradient Descent\", \"Decision Tree\", \"AdaBoost\", \"Multi-layer Perceptron\"]\nclf_rfe_values = [LogisticRegression(random_state=random_state), SVC(kernel=\"linear\",random_state=random_state),\n                  GaussianNB(), KNeighborsClassifier(), SGDClassifier(random_state=random_state),\n                  DecisionTreeClassifier(random_state=random_state), AdaBoostClassifier(random_state=random_state), \n                  MLPClassifier(random_state=random_state, max_iter=1000)]\nclfs = dict(zip(clf_keys, clf_values))\nclfs_rfe = dict(zip(clf_rfe_keys, clf_rfe_values))\n\n# Original dataset\nprint(\"Model training using original data: started!\")\nfor clf_name, clf in clfs.items():\n    clf.fit(X_train, y_train)\n    clfs[clf_name] = clf\n    print(clf_name, \"training: done!\")\nprint(\"Model training using original data: done!\\n\")\n\n# Feature-selected dataset\nprint(\"Model training using feature-selected data: started!\")\nfor clf_rfe_name, clf_rfe in clfs_rfe.items():\n    clf_rfe.fit(X_rfe_train, y_train)\n    clfs_rfe[clf_rfe_name] = clf_rfe\n    print(clf_rfe_name, \"training: done!\")\nprint(\"Model training using feature-selected data: done!\")\n\"\"\"\nCheck the accuracy of these two models, for now.\n\"\"\"\n# Original dataset\nacc = []\nfor clf_name, clf in clfs.items():\n    y_pred = clf.predict(X_test)\n    acc.append(accuracy_score(y_test, y_pred))\n\n# Feature selected dataset\nacc_rfe = []\nfor clf_rfe_name, clf_rfe in clfs_rfe.items():\n    y_rfe_pred = clf_rfe.predict(X_rfe_test)\n    acc_rfe.append(accuracy_score(y_test, y_rfe_pred))\n    \nacc_all = pd.DataFrame({\"Original dataset\": acc, \"Feature-selected dataset\": acc_rfe},\n                       index=clf_keys)\nacc_all\n\"\"\"\nMake a bar plot of all accuracy results to visualize them.\n\"\"\"\nprint(\"Accuracy\\n\" + acc_all.mean().to_string())\n\nax = acc_all.plot.bar(figsize=(10, 8))\nfor p in ax.patches:\n    ax.annotate(str(p.get_height().round(3)), (p.get_x()*0.985, p.get_height()*1.002))\nplt.ylim((0.7, 0.82))\nplt.xticks(rotation=90)\nplt.title(\"All Classifier Accuracies\")\nplt.grid()\nplt.show()\n\"\"\"\nFrom the result above, the mean accuracy of feature-selected data is slightly higher (0.3% higher) than the mean accuracy of the original data. The model that has the best accuracy is Support Vector Machine trained on feature-selected data with 79.6% accuracy. Multi-layer Perceptron accuracy improved by 2.3% with training on feature-selected data. But, there are some classifiers (Naive Bayes, k-Nearest Neighbors, Stochastic Gradient Descent, and AdaBoost) that don't get the advantage from training on feature-selected data.\n\nTo ensure this result, evaluate the model by using cross-validation.\n\"\"\"\n\"\"\"\n<a id='Model-Evaluation'><\/a>\n# D. Model Evaluation\n\"\"\"\n\"\"\"\nTo validate the accuracy result and evaluate the performance of these two models furthermore, do k-fold cross-validation with $k = 10$ on the whole dataset.\nMetrics to validate are: accuracy, and ROC AUC score.\n\"\"\"\nscoring = [\"accuracy\", \"roc_auc\"]\n\nscores = []\n# Original dataset\nprint(\"Cross-validation on original data: started!\")\nfor clf_name, clf in clfs.items():\n    score = pd.DataFrame(cross_validate(clf, X, y, cv=StratifiedKFold(10, random_state=random_state, shuffle=True), scoring=scoring)).mean()\n    scores.append(score)\n    print(clf_name, \"cross-validation: done!\")\ncv_scores = pd.concat(scores, axis=1).rename(columns=dict(zip(range(len(clf_keys)), clf_keys)))\nprint(\"Cross-validation on original data: done!\\n\")\n\nscores = []\n# Feature-selected dataset\nprint(\"Cross-validation on feature-selected data: started!\")\nfor clf_name, clf in clfs_rfe.items():\n    score = pd.DataFrame(cross_validate(clf, X_rfe, y, cv=StratifiedKFold(10, random_state=random_state, shuffle=True), scoring=scoring)).mean()\n    scores.append(score)\n    print(clf_name, \"cross-validation: done!\")\ncv_scores_rfe = pd.concat(scores, axis=1).rename(columns=dict(zip(range(len(clf_keys)), clf_keys)))\nprint(\"Cross-validation on feature-selected data: done!\")\n\"\"\"\nLet's visualize cross-validation accuracy, ROC AUC score, and fit time results.\n\"\"\"\n# Accuracy\ncv_acc_all = pd.concat([cv_scores.loc[\"test_accuracy\"].rename(\"Original data\"), cv_scores_rfe.loc[\"test_accuracy\"].rename(\"Feature-selected data\")], \n                       axis=1)\n\nprint(\"Cross-validation accuracy\\n\" + cv_acc_all.mean().to_string())\nax = cv_acc_all.plot.bar(figsize=(10, 8))\nfor p in ax.patches:\n    ax.annotate(str(p.get_height().round(3)), (p.get_x()*0.985, p.get_height()*1.003))\nplt.xticks(rotation=90)\nplt.ylim((0.7, 0.82))\nplt.title(\"Cross-validation Accuracy\")\nplt.grid()\nplt.legend()\nplt.show()\n# ROC AUC\ncv_roc_auc_all = pd.concat([cv_scores.loc[\"test_roc_auc\"].rename(\"Original data\"), cv_scores_rfe.loc[\"test_roc_auc\"].rename(\"Feature-selected data\")], \n                           axis=1)\n\nprint(\"Cross-validation ROC AUC score\\n\" + cv_roc_auc_all.mean().to_string())\nax = cv_roc_auc_all.plot.bar(figsize=(10, 8))\nfor p in ax.patches:\n    ax.annotate(str(p.get_height().round(3)), (p.get_x()*0.985, p.get_height()*1.003))\nplt.xticks(rotation=90)\nplt.ylim((0.63, 0.88))\nplt.title(\"Cross-validation ROC AUC Score\")\nplt.grid()\nplt.legend()\nplt.show()\n# Fit time\ncv_fit_time_all = pd.concat([cv_scores.loc[\"fit_time\"].rename(\"Original data\"), cv_scores_rfe.loc[\"fit_time\"].rename(\"Feature-selected data\")], \n                           axis=1)\n\nprint(\"Cross-validation fit time\\n\" + cv_fit_time_all.mean().to_string())\nax = cv_fit_time_all.plot.bar(figsize=(10, 8))\nfor p in ax.patches:\n    ax.annotate(str(p.get_height().round(3)), (p.get_x()*0.985, p.get_height()*1.003))\nplt.xticks(rotation=90)\nplt.yscale(\"log\")\nplt.title(\"Cross-validation Fit Time\")\nplt.grid()\nplt.legend()\nplt.show()\n\"\"\"\nFrom the accuracy result, the mean accuracy of feature-selected data is 0.75% higher than the mean accuracy of the original data. The best accuracy here is Logistic Regression model trained on feature-selected data with 80.4% accuracy. Multi-layer Perceptron accuracy got the highest improvement by 2.8% with training on feature-selected data. Both SVM and AdaBoost accuracies of feature-selected data are slightly lower (only 0.1% lower) than the accuracies of original data. Remember, feature-selected data only has **9 features** while original data has 19 features.\n\nThe models that have the best ROC AUC score are Logistic Regression and AdaBoost with an ROC AUC score of 0.844. The ROC AUC result is not much different from the accuracy result. But there are some classifiers (Logistic Regression, Naive Bayes, and AdaBoost) that have slightly lower ROC AUC score of feature-selected data than the ROC AUC score of original data.\n\nAll models that were trained on feature-selected data have faster fit time than the one that was trained on original data. It is obviously because the number of features trained on those models.\n\"\"\"\n\"\"\"\n<a id='Feature-Importance'><\/a>\n# E. Feature Importance\n\"\"\"\n\"\"\"\nFind the feature importance of the predictive model that has been made. In this case, use Logistic Regression because it has the highest accuracy among all models.\n\"\"\"\nimportance = abs(clfs[\"Logistic Regression\"].coef_[0])\nplt.barh(X.columns.values[importance.argsort()], importance[importance.argsort()])\nplt.title(\"Logistic Regression - Feature Importance (Original Data)\")\nplt.grid()\nplt.show()\n\nimportance_rfe = abs(clfs_rfe[\"Logistic Regression\"].coef_[0])\nplt.barh(X_rfe.columns.values[importance_rfe.argsort()], importance_rfe[importance_rfe.argsort()])\nplt.title(\"Logistic Regression - Feature Importance (Feature-selected Data)\")\nplt.grid()\nplt.show()\n\"\"\"\nTop 5 important features of both Logistic Regression models are the same (\"tenure\", \"PhoneService\", \"Contract\", \"TotalCharges\", and \"MonthlyCharges\"). The rest of these important features are quite the same in both models.\n\"\"\"\n\"\"\"\nLet's check the feature importance of AdaBoost classifier for comparison.\n\"\"\"\nimportance = clfs[\"AdaBoost\"].feature_importances_\nplt.barh(X.columns.values[importance.argsort()], importance[importance.argsort()])\nplt.title(\"AdaBoost - Feature Importance (Original Data)\")\nplt.grid()\nplt.show()\n\nimportance_rfe = clfs_rfe[\"AdaBoost\"].feature_importances_\nplt.barh(X_rfe.columns.values[importance_rfe.argsort()], importance_rfe[importance_rfe.argsort()])\nplt.title(\"AdaBoost - Feature Importance (Feature-selected Data)\")\nplt.grid()\nplt.show()\n\"\"\"\nThe top 5 important features of both AdaBoost models are slightly different. AdaBoost classifier that was trained on original data includes \"PaymentMethod\" on the fifth rank of its feature importance, while this feature is not selected during the RFE step. The rest of these important features are similar in both models.\n\"\"\"\n\"\"\"\nAlso find the feature importance of Support Vector Machine.\n\"\"\"\nimportance = abs(clfs[\"Support Vector Machine\"].coef_[0])\nplt.barh(X.columns.values[importance.argsort()], importance[importance.argsort()])\nplt.title(\"Support Vectore Machine - Feature Importance (Original Data)\")\nplt.grid()\nplt.show()\n\nimportance_rfe = abs(clfs_rfe[\"Support Vector Machine\"].coef_[0])\nplt.barh(X_rfe.columns.values[importance_rfe.argsort()], importance_rfe[importance_rfe.argsort()])\nplt.title(\"Support Vectore Machine - Feature Importance (Feature-selected Data)\")\nplt.grid()\nplt.show()\n\"\"\"\nThe top 5 important features of both Support Vector Machine models are kind of different. SVM classifier that was trained on original data placed \"tenure\" on the fifth rank, while the other model placed \"tenure\" on the first rank.\n\"\"\"\n\"\"\"\nFrom these three models, \"tenure\", \"MonthlyCharges\", and \"TotalCharges\" are always appeared on the top 5 important features of each model.\n\"\"\"\n\"\"\"\n<a id='Summary'><\/a>\n# F. Summary\n\"\"\"\n\"\"\"\nRecursive feature elimination (RFE) is very useful to select only necessary features, save the training time, and still get similar accuracy, or even higher than the original data. RFE is popular because it is easy to configure and use and because it is effective at selecting those features (columns) in a training dataset that are more or most relevant in predicting the target variable. The feature importance of feature-selected data is also still preserved and is quite the same with original data based on the observation above.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '43948601d8a2d0'}"}
{"id":"19513","text":"\"\"\"\n# Python for Data 7: Dictionaries and Sets\n[back to index](https:\/\/www.kaggle.com\/hamelg\/python-for-data-analysis-index)\n\"\"\"\n\"\"\"\nSequence data types like lists, tuples and strings are ordered. Ordering can be useful in some cases, such as if your data is sorted or has some other natural sense of ordering, but it comes at a price. When you search through sequences like lists, your computer has to go through each element one at a time to find an object you're looking for.\n\nConsider the following code:\n\"\"\"\nmy_list = [1,2,3,4,5,6,7,8,9,10]\n\n0 in my_list\n\"\"\"\nWhen running the code above, Python has to search through the entire list, one item at a time before it returns that 0 is not in the list. This sequential searching isn't much of a concern with small lists like this one, but if you're working with data that contains thousands or millions of values, it can add up quickly.\n\nDictionaries and sets are unordered Python data structures that solve this issue using a technique called [hashing](https:\/\/en.wikipedia.org\/wiki\/Hash_function). We won't go into the details of their implementation, but dictionaries and sets let you check whether they contain objects without having to search through each element one at a time, at the cost of having no order and using a bit more system memory.\n\"\"\"\n\"\"\"\n## Dictionaries\n\"\"\"\n\"\"\"\nA [dictionary](https:\/\/docs.python.org\/3.7\/tutorial\/datastructures.html#dictionaries) or dict is an object that maps a set of named indexes called keys to a set of corresponding values. Dictionaries are mutable, so you can add and remove keys and their associated values. A dictionary's keys must be immutable objects, such as ints, strings or tuples, but the values can be anything.\n\nCreate a dictionary with a comma-separated list of key: value pairs within curly braces:\n\"\"\"\nmy_dict = {\"name\": \"Joe\",\n           \"age\": 10, \n           \"city\": \"Paris\"}\n\nprint(my_dict)\n\"\"\"\nNotice that in the printed dictionary, the items don't appear in the same order as when we defined it, since dictionaries are unordered. Index into a dictionary using keys rather than numeric indexes:\n\"\"\"\nmy_dict[\"name\"]\n\"\"\"\nAdd new items to an existing dictionary with the following syntax:\n\"\"\"\nmy_dict[\"new_key\"] = \"new_value\"\n\nprint(my_dict)\n\"\"\"\nDelete existing key: value pairs with del:\n\"\"\"\ndel my_dict[\"new_key\"]\n\nprint(my_dict)\n\"\"\"\nCheck the number of items in a dict with len():\n\"\"\"\n\nlen(my_dict)\n\"\"\"\nCheck whether a certain key exists with \"in\":\n\"\"\"\n\"name\" in my_dict\n\"\"\"\nYou can access all the keys, all the values or all the key: value pairs of a dictionary with the keys(), value() and items() functions respectively:\n\"\"\"\nmy_dict.keys()\nmy_dict.values()\nmy_dict.items()\n\"\"\"\nReal world data often comes in the form tables of rows and columns, where each column specifies a different data feature like name or age and each row represents an individual record. We can encode this sort of tabular data in a dictionary by assigning each column label a key and then storing the column values as a list.\n\nConsider the following table:\n\nname  &nbsp; &nbsp;&nbsp;age      &nbsp;&nbsp;&nbsp;city  <br>\nJoe  &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;10     &nbsp;&nbsp;&nbsp;&nbsp; Paris <br>\nBob   &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;15     &nbsp; &nbsp;&nbsp;&nbsp;New York <br>\nHarry  &nbsp;&nbsp; &nbsp;20      &nbsp;&nbsp;&nbsp; Tokyo\n\nWe can store this data in a dictionary like so:\n\"\"\"\nmy_table_dict = {\"name\": [\"Joe\", \"Bob\", \"Harry\"],\n                 \"age\": [10,15,20] , \n                 \"city\": [\"Paris\", \"New York\", \"Tokyo\"]}\n\"\"\"\nCertain data formats like XML and Json have a non-tabular, nested structure. Python dictionaries can contain other dictionaries, so they can mirror this sort of nested structure, providing a convenient interface for working with these sorts of data formats in Python. (We'll cover loading data into Python in a future lesson.).\n\"\"\"\n\"\"\"\n## Sets\n\"\"\"\n\"\"\"\nSets are unordered, mutable collections of immutable objects that cannot contain duplicates. Sets are useful for storing and performing operations on data where each value is unique.\nCreate a set with a comma separated sequence of values within curly braces:\n\"\"\"\nmy_set = {1,2,3,4,5,6,7}\n\ntype(my_set)\n\"\"\"\nAdd and remove items from a set with add() and remove() respectively:\n\"\"\"\nmy_set.add(8)\n\nmy_set\nmy_set.remove(7)\n\nmy_set\n\"\"\"\nSets do not support indexing, but they do support basic sequence functions like len(), min(), max() and sum(). You can also check membership and non-membership as usual with in:\n\"\"\"\n6 in my_set\n\"\"\"\nOne of the main purposes of sets is to perform set operations that compare or combine different sets. Python sets support many common mathematical set operations like union, intersection, difference and checking whether one set is a subset of another:\n\"\"\"\nset1 = {1,3,5,6}\nset2 = {1,2,3,4}\n\nset1.union(set2)          # Get the union of two sets\nset1.intersection(set2)   # Get the intersection of two sets\nset1.difference(set2)     # Get the difference between two sets\nset1.issubset(set2)       # Check whether set1 is a subset of set2\n\"\"\"\nYou can convert a list into a set using the set() function. Converting a list to a set drops any duplicate elements in the list. This can be a useful way to strip unwanted duplicate items or count the number of unique elements in a list. I can also be useful to convert a list to a set if you plan to lookup items repeatedly, since membership lookups are faster with sets than lists.\n\"\"\"\nmy_list = [1,2,2,2,3,3,4,5,5,5,6]\n\nset(my_list)\n\"\"\"\n## Wrap Up\n\"\"\"\n\"\"\"\nDictionaries are general-purpose data structures capable of encoding both tabular and non-tabular data. As basic built in Python data structures, however, they lack many of the conveniences we'd like when working with tabular data, like the ability to look at summary statistics for each column and transform the data quickly and easily. In the next two lessons, we'll look at data structures available in Python packages designed for data analysis: numpy arrays and pandas DataFrames.\n\"\"\"\n\"\"\"\n## Next Lesson: [Python for Data 8: Numpy Arrays](https:\/\/www.kaggle.com\/hamelg\/python-for-data-8-numpy-arrays)\n[back to index](https:\/\/www.kaggle.com\/hamelg\/python-for-data-analysis-index)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '23b3404efc623b'}"}
{"id":"5892","text":"\"\"\"\n<h1 style=\"text-align: center;\">EDA of Udemy Courses and ML to Predict Subscribers<\/h1>\n\"\"\"\n# common imports\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# pandas imports\nfrom pandas.plotting import scatter_matrix\n\n# machine learning imports\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn import metrics\n\n# display setup\npd.set_option(\"display.max_columns\", None) # the None parameter displays unlimited columns\nsns.set(style=\"whitegrid\") # for plots\n\"\"\"\n# 1. Getting the Data\n\"\"\"\n# read the csv file\ndf = pd.read_csv(\"..\/input\/udemy-courses\/udemy_courses.csv\")\n# display the first 5 rows for a quick look\ndf.head()\n# DataFrame shape (rows, columns)\n# understand the amount of data we are working with\ndf.shape\n# description of data\ndf.info()\n# check if there are null values\ndf.isna().sum()\n# summary of the numerical attributes\ndf.describe()\n\"\"\"\n> As shown above, there are no missing values which is excellent!\n>\n> ##### *It is vital to understand the features we are working with.*\n> ### Features in the DataFrame:\n>> 1. course_id: Course identification number\n>> 2. course_title: Title of course\n>> 3. url: Course URL\n>> 4. is_paid: True if the course costs money, false if the course is free\n>> 5. price: Price of course\n>> 6. num_subscribers: Number of subscribers for the course\n>> 7. num_lectures: Number of lectures in the course\n>> 8. level: Difficulty level of the course\n>> 9. content_duration: Duration of all course materials\n>> 10. published_timestamp: Course publication date\n>> 11. subject: Subject of course\n\"\"\"\n# a histogram plot for each numerical attribute\ndf.drop(\"is_paid\", axis=1).hist(bins=30, figsize=(20,15))\nplt.tight_layout()\nplt.show()\n\"\"\"\n> Initial observations from the histograms:\n>> 1. Most course durations are between 0-5 hours.\n>> 2. There are usually around 1-50 lectures per course.\n>> 3. Courses tend to have few reviews. There are probably a handful of courses\n>> with a large amount of reviews since the X axis goes up to 25000 while over 3000\n>> instances are represented in the first bin.\n>> 4. The majority of courses are in the same range of subscribers. The instances farther up\n>> the scale were probably more successful or perhaps courses on a trending topic.\n>> 5. Assuming the prices are in USD, the range is between 0-250 dollars.\n>> The plot shows the most common price roughly $25.\n\"\"\"\n\"\"\"\n> # Objective\n> ## Predicting the number of subscribers for a course.\n>> ### Chosen Feature:\n>> #### *num_subscribers* column\n>>> The column represents how many people have subscribed to each course.\n>>> ### Motive:\n>>> Predicting the number of people subscribed to a course, course popularity.\n\"\"\"\n\"\"\"\n> ### Splitting the Data:\n>> Before further analysis let's split the data into a training set and a testing set.\n>> This will ensure avoidance of bias that could occur from learning the data as a whole.\n\"\"\"\n# use sklearn train_test_split function to split the data\n# the random state parameter ensures that data will be shuffled and split the same way in each run\ntrain_set, test_set = train_test_split(df, test_size=0.20, random_state=42)\nprint(\"Number of instances in training set: \", len(train_set))\nprint(\"Number of instances in testing set: \", len(test_set))\n\"\"\"\n# 2. Understanding and Visualizing the Data\n> ##### *The motivation for this section is to gain more insights*\n\"\"\"\n# deep copy of the training set\ndf2 = train_set.copy()\ndf2.head(2)\n\"\"\"\n> ## Exploring Attribute Combinations\n\"\"\"\n# method creates a correlations matrix\ncorr_matrix = df2.corr()\n# looking at attributes correlation with num_subscribers feature\ncorr_matrix[\"num_subscribers\"].sort_values(ascending=False)\n# a histogram plot for attributes with a high correlation\n\nattributes = [\"num_subscribers\", \"num_reviews\", \"num_lectures\", \"content_duration\", \"course_id\"]\n\nscatter_matrix(df2[attributes], figsize=(12,8))\nplt.tight_layout()\nplt.show()\n# scatter plot of the strongest correlation in the corr matrix\n# the alpha is set to show the distribution more clearly\ndf2.plot(kind=\"scatter\", x=\"num_reviews\", y=\"num_subscribers\", alpha=0.1,\n         color='b', figsize=(10,5))\nplt.title(\"Reviews and Subscribers Correlation\", size=20)\nplt.xlabel(\"num_reviews\", size=15)\nplt.ylabel(\"num_subscribers\", size=15)\nplt.tight_layout()\nplt.show()\n\"\"\"\n> ### Correlations with num_subscribers Attribute- Overview:\n>> The strongest positive correlations (0.1 or more) are:\n>> * num_reviews\n>> * num_lectures\n>> * content_duration\n>>\n>> The strongest negative correlations (-0.1 or less) are:\n>> * course_id\n>> * is_paid\n\"\"\"\n\"\"\"\n> ### Examining Course ID Feature\n\"\"\"\nprint(\"Number of unique course IDs:\", df2[\"course_id\"].nunique())\nprint(\"Length of DataFrame:\", len(df2))\n# check if number of unique urls\n# should be individual for each instance\ndf2[\"url\"].nunique()\n\"\"\"\n> Since there is a unique value for almost every course ID, the correlation was probably\n> coincidental.\n\"\"\"\n# show duplicated listings\ndf2[df2.duplicated(\"course_id\")]\n# remove duplicated listings\ndf2.drop_duplicates(inplace=True)\n# examine changes\ndf2.shape\n\"\"\"\n> ### Overview:\n>> * The course ID is unique for each course.\n>> * This column should be removed when training a model in order to generalize better.\n\"\"\"\n\"\"\"\n> ### Assessing Price Features\n\"\"\"\n# evaluate current values in column\ndf2[\"is_paid\"].head(10)\n# use encoder to convert \"is_paid\" column to binary outcome\nordinal_encoder = OrdinalEncoder(dtype=int)\ndf2[\"is_paid\"] = ordinal_encoder.fit_transform(df2[[\"is_paid\"]])\n# evaluate changes\ndf2[\"is_paid\"].head(10)\n# 0 is False, 1 is True\nordinal_encoder.categories_\n# count number of instances for each outcome\ndf2[\"is_paid\"].value_counts()\n# use groupby for price attribute\nprice_values = df2.groupby(\"price\")\n# check if number of free courses matches when the price is 0\nprice_values_0 = price_values.get_group(0)\nprice_values_0.shape\n# plot of free and paid courses\nplt.figure(figsize=(10,5))\nsns.countplot(x=df2[\"is_paid\"])\nplt.title(\"Free and Paid Courses\", size=20)\nplt.xlabel(\"is_paid\", size = 15)\nplt.ylabel(\"count\", size=15)\nplt.tight_layout()\nplt.show()\n# course price values sorted by prices\ndf2[\"price\"].value_counts().sort_index()\n# top ten course price values sorted by value counts\nprices_top10 = df2[\"price\"].value_counts().sort_values(ascending=False).head(10)\n# calculate percentage of instances per price in data\nprices_percent_in_data = []\nnum_subscribed = []\n\nfor i in range(len(prices_top10.index)):\n    prices_percent_in_data.append(round((prices_top10.values[i]\/len(df2))*100,2))\n    num_subscribed.append(price_values.get_group(prices_top10.index[i])[\"num_subscribers\"].sum())\n# create a DataFrame with the results\nprices_top10_dict = {\"price\": prices_top10.index, \"number_of_instances\": prices_top10.values,\n                     \"% of data\": prices_percent_in_data, \"num_subscribers\": num_subscribed}\nprices_top10_df = pd.DataFrame(prices_top10_dict, index=range(1,11))\nprices_top10_df\n# plot of top 10 common prices by amount of subscribers\nplt.figure(figsize=(10,5))\nsns.barplot(x=prices_top10_df[\"price\"], y=prices_top10_df[\"num_subscribers\"])\nplt.xlabel(\"price\", size=15)\nplt.ylabel(\"num_subscribers\\n(millions)\", size=15)\nplt.title(\"Top 10 Common Prices by Subscribers\", size=20)\nplt.tight_layout()\nplt.show()\n# plot of content duration by free or paid course\nplt.figure(figsize=(10,5))\nsns.scatterplot(x=df2[\"content_duration\"], y=df2[\"is_paid\"], alpha=0.1)\nplt.title(\"Content Duration by Type of Course Payment\", size=20)\nplt.xlabel(\"content_duration\", size=15)\nplt.ylabel(\"is_paid\", size=15)\nplt.tight_layout()\nplt.show()\n\"\"\"\n> ### Observations:\n>> * As speculated earlier in the initial observations, $20 is the most common price for a course.\n>> * The number of listings with the price $0 matches the number of instances that were\n>> labeled \"False\" in the is_paid column.\n>> * The prices listed tend to increase by 5 dollars until they reach the maximum price\n>> which is $200.\n>> * Amongst the 10 most common prices in the data, most are subscribed to the free courses.\n>> * Content duration is longer for paid courses.\n\"\"\"\n\"\"\"\n> ### Researching Level and Subject Features\n\"\"\"\n# count number of instances\nlevel_values = df2[\"level\"].value_counts()\nlevel_values\n# count number of instances\nsubject_values = df2[\"subject\"].value_counts()\nsubject_values\n# pie plot of course levels and subjects in data\nfig, ax = plt.subplots(1,2, figsize=(10,5))\nax[0].pie(level_values, startangle=180, labels=level_values.index, autopct=\"%1.1f%%\")\nax[0].set_title(\"Course Levels\", size=20)\nax[1].pie(subject_values, startangle=180, labels=subject_values.index, autopct=\"%1.1f%%\")\nax[1].set_title(\"Course Subjects\", size=20)\nplt.tight_layout()\nplt.show()\n# scatter plot of price by course level\nplt.figure(figsize=(10,5))\nsns.scatterplot(y=df2[\"level\"], x=df2[\"price\"], alpha=0.1)\nplt.title(\"Price by Course Level\", size=20)\nplt.xlabel(\"price\", size=15)\nplt.ylabel(\"level\", size=15)\nplt.tight_layout()\nplt.show()\n# plot subject by number of subscribers and level\n# the black bars represent the error\nplt.figure(figsize=(10,5))\nsns.barplot(x=df2[\"subject\"], y=df2[\"num_subscribers\"], hue=df2[\"level\"])\nplt.title(\"Subject by Number of Subscribers and Level\", size=20)\nplt.xlabel(\"subject\", size=15)\nplt.ylabel(\"num_subscribers\", size=15)\nplt.tight_layout()\nplt.show()\n\"\"\"\n> ### Observations:\n>> * All Levels is the most common level, representing over 50%.\n>> * Web Development is the most common subject, and Business Finance is second with\n>> approximately a 1% differential.\n>> * Price variations according to the level of the course also show that Expert is\n>> the least common level in the data. It is also the only level that does not\n>> provide free courses. The other levels are dispersed more frequently\n>> throughout the line.\n>> * Web Development courses are significantly higher in subscribers than the other subjects.\n>> Since Business Finance falls shortly behind in content, it is likely that people are more\n>> interested in studying Web Development courses.\n\"\"\"\n\"\"\"\n> ### Analyzing Additional Columns\n\"\"\"\n# examine current shape\ndf2.shape\n# every course has a unique URL\ndf2[\"url\"].nunique()\n# some courses have an identical title\ndf2[\"course_title\"].nunique()\n# find duplicated instances\n# false marks all duplicates as true\ntitle_df = df2[df2.duplicated(\"course_title\", keep=False)].copy()\n# show duplicated titles\ntitle_df[\"course_title\"].unique()\n# examine number of unique subscribers values\ntitle_df[\"num_subscribers\"].nunique()\n# groupy course title\ntitle = title_df.groupby(\"course_title\")\n# examining one of the duplicated courses\n# the courses have the same name and different values for some features\ntitle.get_group(\"Acoustic Blues Guitar Lessons\")\n\"\"\"\n> ### Observations:\n>> * The duplicated courses have different parameters such as is_paid or published_timestamp.\n>> Maybe the course provides the first lessons free of charge, or they added new content.\n>> * These instances can be kept as they are likely to have various values (i.e. each\n>> value in the num_subscribers column is unique).\n\"\"\"\n\"\"\"\n# 3. Data Cleaning\n\"\"\"\n# clean copy of training set\ndf3 = train_set.copy()\ndf3.shape\n# remove duplicated instances\ndf3.drop_duplicates(\"course_id\", inplace=True)\n# evaluate changes\ndf3.shape\n# separate predictors from target values\n\n# drop creates a copy without changing the training set\nX_train = df3.drop(\"num_subscribers\", axis=1)\n\n# create a deep copy of the target values\ny_train = df3[\"num_subscribers\"].copy()\n\"\"\"\n> ### Removing the Following Columns:\n> The reason for removing these columns is for the model to generalize better.\n> Furthermore, these columns have a unique value for each instance (i.e. URL, course ID) which\n> does not provide information the model can learn from to predict on new data.\n>> * course_id\n>> * course_title\n>> * url\n>> * published_timestamp\n\"\"\"\n# list of numerical features\nnum_features = [\"price\", \"num_reviews\", \"num_lectures\", \"content_duration\"]\n\n# list of level feature categories\nlevels = [\"All Levels\", \"Beginner Level\", \"Intermediate Level\", \"Expert Level\"]\n\n# column transformer:\n# features generated by each transformer will be concatenated to form a single feature space\n# columns of the original feature matrix that are not specified are dropped\nfull_pipeline = ColumnTransformer([\n\n# MinMaxScaler normalizes data (rescales between 0-1)\n    (\"num\", MinMaxScaler(), num_features),\n\n# OrdinalEncoder converts categories to integers according to order specified in list\n    (\"level\", OrdinalEncoder(categories=[levels]), [\"level\"]),\n\n# OrdinalEncoder converts True and False values to integers\n# True=1, False=0\n    (\"is_paid\", OrdinalEncoder(dtype=int), [\"is_paid\"]),\n\n# OneHotEncoder converts categories to a binary dummy array\n    (\"subject\", OneHotEncoder(handle_unknown=\"ignore\"), [\"subject\"])\n])\nfeatures = num_features+[\"level\", \"is_paid\", \"subject\"]\n\n# transform training data using pipeline\nX_train_prepared = full_pipeline.fit_transform(X_train)\nX_tr_testing = full_pipeline.transform(X_train)\n\"\"\"\n# 4. Training and Evaluating Models\n\"\"\"\n\"\"\"\n> Chosen evaluation metric:\n>\n> The root-mean-square error (RMSE) is the standard deviation of the prediction error.\n> It is the differences between the predicted and actual values, and shows how much they are\n> spread out.\n\"\"\"\n# function prints scores, mean and std\ndef display_scores(scores):\n    print(\"Scores:\", scores)\n    print(\"Mean:\", scores.mean())\n    print(\"Standard deviation:\", scores.std())\n\n# function prints evaluation metrics\ndef display_evaluation(actual, pred):\n    mse = metrics.mean_squared_error(actual, pred)\n    print(\"Mean Squared Error:\", mse)\n    print(\"Root Mean Squared Error:\", np.sqrt(mse))\n\"\"\"\n> The Linear Regression model computes a weighted sum of the input features, and a constant which\n> is the bias\/intercept term. As the name implies, this is in fact a linear function.\n\"\"\"\n\"\"\"\n#### Model 1: Linear Regression\n\"\"\"\n# instantiate model\nlr = LinearRegression()\n# fit the training data\nlr.fit(X_train_prepared, y_train)\n# predict using training data\nlr_pred = lr.predict(X_tr_testing)\n# test on a few instances from training data\nsome_data = X_train.iloc[:10]\nsome_labels = y_train.iloc[:10]\nsome_data_prepared = full_pipeline.transform(some_data)\nprint(\"Predictions:\", lr.predict(some_data_prepared))\nprint(\"Labels:\", list(some_labels))\n# use function to show results\ndisplay_evaluation(y_train, lr_pred)\n\"\"\"\n##### Cross Validation for Linear Regression Model\n\"\"\"\n# 10 fold cross validation\nlr_scores = cross_val_score(lr, X_train_prepared, y_train, cv=10, scoring=\"neg_mean_squared_error\", )\n\n# scoring function returns a negative value for MSE (need to add the minus)\nlr_rmse_scores = np.sqrt(-lr_scores)\ndisplay_scores(lr_rmse_scores)\n# estimate prediction using cross validation\nlr_pred = cross_val_predict(lr, X_tr_testing, y_train, cv=10)\n# test on a few instances from training data\nsome_data = X_train.iloc[:10]\nsome_labels = y_train.iloc[:10]\nsome_data_prepared = full_pipeline.transform(some_data)\nprint(\"Predictions:\", lr.predict(some_data_prepared))\nprint(\"Labels:\", list(some_labels))\n# use function to show results\ndisplay_evaluation(y_train, lr_pred)\n\"\"\"\n> The Random Forest Regressor model is based on many decision trees.\n> A decision tree is a non-linear model built by constructing many linear boundaries.\n> The random forest model samples random points and subsets of features when training.\n> Then, the predictions are made by averaging the predictions made by each decision tree.\n\"\"\"\n\"\"\"\n#### Model 2: Random Forest Regressor\n\"\"\"\n# instantiate model\nrfr = RandomForestRegressor(random_state=42)\n# fit the training data\nrfr.fit(X_train_prepared, y_train)\n# predict using training data\nrfr_pred = rfr.predict(X_tr_testing)\n# use function to show results\ndisplay_evaluation(y_train, rfr_pred)\n\"\"\"\n> The Random Forest Regressor model performed better than the linear regression model,\n> even after cross validation. The next step is to find the hyperparameters\n> that provide the best results.\n>\n> For this task we can use grid search cv. The grid search works by trying all parameter\n> combinations from the ones instantiated, then shows the best combination according to\n> the highest score.\n\"\"\"\n\"\"\"\n#### Grid Search Cross Validation 1\n\"\"\"\n# max features default is sqrt (number of features selected per split)\n# bootstrap default is true (resampling data true)\n# n estimators default is 100 (number of decision trees)\n# parameters for grid search\nparam_grid = {\"n_estimators\": [10,50,100,500], \"max_features\":[2,4,8], \"bootstrap\": [True, False]}\n# instantiate grid search\ngrid_search = GridSearchCV(rfr, param_grid, cv=5, scoring=\"neg_mean_squared_error\", return_train_score=True)\n# fit to the training data\ngrid_search.fit(X_train_prepared, y_train)\n# show the best score\nnp.sqrt(-grid_search.best_score_)\n# show the best parameters\ngrid_search.best_estimator_\n# show results for each iteration\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n    print(np.sqrt(-mean_score), params)\n\"\"\"\n#### Model 3: Random Forest Regressor\n\"\"\"\n# instantiate model\nrfr = grid_search.best_estimator_\nrfr\n# test on a few instances from training data\nsome_data = X_train.iloc[:10]\nsome_labels = y_train.iloc[:10]\nsome_data_prepared = full_pipeline.transform(some_data)\nprint(\"Predictions:\", rfr.predict(some_data_prepared))\nprint(\"Labels:\", list(some_labels))\n# predict using training data\nrfr_pred_2 = rfr.predict(X_tr_testing)\n# use function to show results\ndisplay_evaluation(y_train, rfr_pred_2)\n\"\"\"\n#### Feature Importance\n\"\"\"\nlevel_encoder = full_pipeline.named_transformers_[\"level\"]\nlevel_encoder_attribs = list(level_encoder.categories_[0])\n\nsubject_encoder = full_pipeline.named_transformers_[\"subject\"]\nsubject_encoder_attribs = list(subject_encoder.categories_[0])\n\nfeatures_sub = num_features+level_encoder_attribs+[\"is_paid\"]+subject_encoder_attribs\n# pair the feature names with the results from grid search\nfeature_importance = grid_search.best_estimator_.feature_importances_\nsorted(zip(feature_importance,features_sub), reverse=True)\n\"\"\"\n> Next, lets train a model without the parameters that have less than 0.05 feature importance\n> and compare the model performances.\n>\n> In this case, all categorical features will be removed.\n\"\"\"\n# column transformer with numerical attributes only\nfull_pipeline_2 = ColumnTransformer([\n    (\"num\", MinMaxScaler(), num_features),\n])\nX_train_prepared_2 = full_pipeline_2.fit_transform(X_train)\nX_tr_testing_2 = full_pipeline_2.transform(X_train)\n\"\"\"\n#### Model 4: Random Forest Regressor\n\"\"\"\n# instantiate model\nrfr = RandomForestRegressor(random_state=42)\n# fit the training data\nrfr.fit(X_train_prepared_2, y_train)\n# test on a few instances from training data\nsome_data = X_train.iloc[:10]\nsome_labels = y_train.iloc[:10]\nsome_data_prepared = full_pipeline_2.transform(some_data)\nprint(\"Predictions:\", rfr.predict(some_data_prepared))\nprint(\"Labels:\", list(some_labels))\n# predict using training data\nrfr_pred_3 = rfr.predict(X_tr_testing_2)\n# use function to show results\ndisplay_evaluation(y_train, rfr_pred_3)\n\"\"\"\n#### Grid Search Cross Validation 2\n\"\"\"\n# parameters for grid search\nparam_grid_2 = {\"n_estimators\": [10,50,100,500], \"max_features\":[2,3,4], \"bootstrap\": [True, False]}\n# instantiate grid search\ngrid_search_2 = GridSearchCV(rfr, param_grid_2, cv=5, scoring=\"neg_mean_squared_error\", return_train_score=True)\n# fit the training data\ngrid_search_2.fit(X_train_prepared_2, y_train)\n# show the best score\nnp.sqrt(-grid_search.best_score_)\n# show the best parameters\ngrid_search_2.best_estimator_\n# show results for each iteration\ncvres = grid_search_2.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n    print(np.sqrt(-mean_score), params)\n\"\"\"\n#### Model 5: Random Forest Regressor\n\"\"\"\n# instantiate model\nrfr_2 = grid_search_2.best_estimator_\nrfr_2\n# test on a few instances from training data\nsome_data = X_train.iloc[:10]\nsome_labels = y_train.iloc[:10]\nsome_data_prepared = full_pipeline_2.transform(some_data)\nprint(\"Predictions:\", rfr_2.predict(some_data_prepared))\nprint(\"Labels:\", list(some_labels))\n# predict using training data\nrfr_pred_4 = rfr_2.predict(X_tr_testing_2)\n# use function to show results\ndisplay_evaluation(y_train, rfr_pred_4)\n\"\"\"\n#### Dummy Regressor\n> The dummy regressor serves as an indication and comparison for model performance.\n\"\"\"\n# instantiate dummy regressor\n# predicts the mean for each instance\ndummy = DummyRegressor(strategy=\"mean\")\n# fit the training set\ndummy.fit(X_train_prepared_2, y_train)\n# predict using dummy regressor\ndummy_pred = dummy.predict(X_train_prepared_2)\n# use function to show results\ndisplay_evaluation(y_train, dummy_pred)\n\"\"\"\n> ### Overview:\n>> ####  Removing the categorical features even slightly improved the score.\n>> * The RMSE with all features was approximately 2551.\n>> * The RMSE with only the numerical features was approximately 2520.\n>> * The model is substantially better than the dummy regressor.\n\"\"\"\n\"\"\"\n# 5. Evaluating the Test Set\n\"\"\"\n# separate test set predictors and labels\nX_test = test_set.drop(\"num_subscribers\", axis=1)\ny_test = test_set[\"num_subscribers\"].copy()\nfinal_model = grid_search_2.best_estimator_\nfinal_model\n# transform test set\nX_test_prep = full_pipeline_2.transform(X_test)\n# predict test set\nfinal_predictions = final_model.predict(X_test_prep)\n# evaluate predictions\ndisplay_evaluation(y_test, final_predictions)\n\"\"\"\n> #### Resources:\n> 1. Udemy Courses Dataset <a href=\"https:\/\/www.kaggle.com\/andrewmvd\/udemy-courses\"\n> title=\"Kaggle\">link<\/a>\n> 2. Regression Evaluation Metrics Article <a href=\"https:\/\/medium.com\/analytics-vidhya\/mae-mse-rmse\n> -coefficient-of-determination-adjusted-r-squared-which-metric-is-better-cd0326a5697e\" title=\"medium\">link<\/a>\n> 3. Random Forest Article <a href=\"https:\/\/towardsdatascience.com\/an-implementation-and-\n> explanation-of-the-random-forest-in-python-77bf308a9b76\" title=\"towardsdatascience\">link<\/a>\n\"\"\"\n\"\"\"\n### Any feedback, suggestions, questions? Leave a comment below!\n### Upvote if you liked this notebook, learned something new or found it useful!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0af1ecf58678b9'}"}
{"id":"105809","text":"\"\"\"\nMachine Learning vs. Deep Learning\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\nresp_2021 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2021\/kaggle_survey_2021_responses.csv')\nresp_2020 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2020\/kaggle_survey_2020_responses.csv')\nresp_2019 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2019\/multiple_choice_responses.csv')\nresp_2018 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2018\/multipleChoiceResponses.csv')\nresp_2017 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2017\/multipleChoiceResponses.csv', encoding='ISO-8859-1')\nschema_2017 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2017\/schema.csv', encoding='ISO-8859-1')\nschema_2017\nschema_2017[schema_2017['Question'].str.contains('hardware')]\ngpu_res = dict()\ngpu_res['Years'] = []\ngpu_res['Accelerator Usage By Users'] = []\nsearchfor = ['GPU', 'TPU']\n\ngpu_2017 = resp_2017[resp_2017['WorkHardwareSelect'].str.contains('|'.join(searchfor)).fillna(value=False)].shape[0] # gpu at work users in 2017 \ngpu_total_2017 = sum(resp_2017['WorkHardwareSelect'].str.contains('GPU').value_counts()) #total number of people answering question at work\n\n\ngpu_2017 += resp_2017[resp_2017['HardwarePersonalProjectsSelect'].str.contains('|'.join(searchfor)).fillna(value=False)].shape[0] #added personal project gpu numbers\ngpu_total_2017 += sum(resp_2017['HardwarePersonalProjectsSelect'].str.contains('GPU').value_counts())\n\ngpu_res['Years'].append('2017')\ngpu_res['Accelerator Usage By Users'].append(gpu_2017 \/ gpu_total_2017)\n#2018\ub144\uc5d0 gpu data \uc874\uc7ac X \nschema_2019 = pd.read_csv('\/kaggle\/input\/kaggle-survey-2019\/questions_only.csv', encoding='ISO-8859-1').transpose() #\ub3cc\ub824\uc57c\uc9c0 \ub370\uc774\ud130\uac00 \ubcf4\uae30 \uc27d\uac8c \ub098\uc634 \uad81\uae08\ud558\uba74 transpose \uc5c6\uc774 \ud574\ubcf4\uba74 \ub428\nschema_2019[schema_2019[0].str.contains('hardware')] #Q21\n#\uac19\uc740 \uc0ac\ub78c\uc744 \ub450\ubc88 \uc138\uc9c0 \uc54a\uac8c \uc8fc\uc758 !! \n\ngpu_total_2019 = resp_2019['Q21_Part_1'].str.contains('CPUs').fillna(value = False) | \\\nresp_2019['Q21_Part_2'].str.contains('GPUs').fillna(value = False) | \\\nresp_2019['Q21_Part_3'].str.contains('TPUs').fillna(value = False) | \\\nresp_2019['Q21_Part_4'].str.contains('None').fillna(value = False) | \\\nresp_2019['Q21_Part_5'].str.contains('Other').fillna(value = False) #boolean indexing to get unique users\n\ngpu_total_2019 = gpu_total_2019.value_counts().to_frame().transpose()[True][0] - 5 #minus to account for question itself\n\ngpu_2019 = resp_2019['Q21_Part_2'].str.contains('GPUs').fillna(value = False) | \\\nresp_2019['Q21_Part_3'].str.contains('TPUs').fillna(value = False)\n\ngpu_2019 = gpu_2019.value_counts().to_frame().transpose()[True][0] - 2 #minus to account for question itself\n\n\ngpu_res['Years'].append('2019')\ngpu_res['Accelerator Usage By Users'].append(gpu_2019 \/ gpu_total_2019)\n#2020 ==> Q12\n\ngpu_total_2020 = resp_2020['Q12_Part_1'].str.contains('GPUs').fillna(value = False) | \\\nresp_2020['Q12_Part_2'].str.contains('TPUs').fillna(value = False) | \\\nresp_2020['Q12_Part_3'].str.contains('None').fillna(value = False) | \\\nresp_2020['Q12_OTHER'].str.contains('Other').fillna(value = False) \n\ngpu_total_2020 = gpu_total_2020.value_counts().to_frame().transpose()[True][0] - 4 #minus to account for question itself\n\ngpu_2020 = resp_2020['Q12_Part_1'].str.contains('GPUs').fillna(value = False) | \\\nresp_2020['Q12_Part_2'].str.contains('TPUs').fillna(value = False)\n\ngpu_2020 = gpu_2020.value_counts().to_frame().transpose()[True][0] - 2 #minus to account for question itself\n\ngpu_res['Years'].append('2020')\ngpu_res['Accelerator Usage By Users'].append(gpu_2020 \/ gpu_total_2020)\n#2021 --> Q12\n\ngpu_total_2021 = resp_2021['Q12_Part_1'].str.contains('GPUs').fillna(value = False) | \\\nresp_2021['Q12_Part_2'].str.contains('TPUs').fillna(value = False) | \\\nresp_2021['Q12_Part_3'].str.contains('AWS Trainium Chips').fillna(value = False) | \\\nresp_2021['Q12_Part_4'].str.contains('AWS Inferentia Chips').fillna(value = False) | \\\nresp_2021['Q12_Part_5'].str.contains('None').fillna(value = False) | \\\nresp_2021['Q12_OTHER'].str.contains('Other').fillna(value = False)\n\ngpu_total_2021 = gpu_total_2021.value_counts().to_frame().transpose()[True][0] - 6 #minus to account for question itself\n\ngpu_2021 = resp_2021['Q12_Part_1'].str.contains('GPUs').fillna(value = False) | \\\nresp_2021['Q12_Part_2'].str.contains('TPUs').fillna(value = False) | \\\nresp_2021['Q12_Part_3'].str.contains('AWS Trainium Chips').fillna(value = False) | \\\nresp_2021['Q12_Part_4'].str.contains('AWS Inferentia Chips').fillna(value = False)\n\n#gpu_2021.value_counts()\n\ngpu_2021 = gpu_2021.value_counts().to_frame().transpose()[True][0] - 4 #minus to account for question itself\n\ngpu_res['Years'].append('2021')\ngpu_res['Accelerator Usage By Users'].append(gpu_2021 \/ gpu_total_2021)\ngpu_res['Accelerator Usage By Users']\ngpu_res['Style'] = ['Accelerator Usage By Users' for _ in range(4)]\nsns.lineplot(data=gpu_res, x='Years', y='Accelerator Usage By Users', style = 'Style', markers=True)\n#plt.plot(gpu_res['Accelerator Usage By Users'])\n#Which ML algos do you use on a regular basis\n\n#2021 Q17\n#2020 Q17\n#2019 Q24\n#2018 none\n#2017 WorkAlgorithmsSelect\n#interesting datapoint in 2017 --> chooseOne(\"MLMethodNextYearSelect\")\n#shows that 40% of users indicated they were interested in deep learning and 12% in Neural Nets\n#so did they learn those?\n\n#if there is plateau, does it mean that deep learning is difficult to use and may be too expensive and requires\n#too much data so they just use machine learning techniques when they can, because performance is extremely\n#important in real world applications, not just accuracy \n#like whats the point of using nn if xgboost does about the same thing but faster \n#also it may be that kaggle users usually find their niche in one area or another and just stick to that\n#particular niche and specialize in it, so they'd rather just get better at let's say image processing\n#and not attempt to try out RNNs or Transformers \n#maybe some techniques are just still in research stage and not easily applicable to real world yet\n#so as deep nns advance in multiple fronts they will become more and more popular\nresponses_df_2021 = resp_2021\n\ndef count_then_return_percent_for_multiple_column_questions(dataframe,list_of_columns_for_a_single_question,dictionary_of_counts_for_a_single_question):\n    '''\n    A helper function to convert counts to percentages.\n    '''\n    df = dataframe\n    subset = list_of_columns_for_a_single_question\n    df = df[subset]\n    df = df.dropna(how='all')\n    total_count = len(df) \n    dictionary = dictionary_of_counts_for_a_single_question\n    for i in dictionary:\n        dictionary[i] = round(float(dictionary[i]*100\/total_count),1)\n    return dictionary\n\n\nq17_list_of_columns_2021 = ['Q17_Part_1',\n                       'Q17_Part_2',\n                       'Q17_Part_3',\n                       'Q17_Part_4',\n                       'Q17_Part_5',\n                       'Q17_Part_6',\n                       'Q17_Part_7',\n                       'Q17_Part_8',\n                       'Q17_Part_9',\n                       'Q17_Part_10',\n                       'Q17_Part_11',\n                       'Q17_OTHER']\n\nq17_dictionary_of_counts_2021 = {\n    'Linear or Logistic Regression' : (responses_df_2021['Q17_Part_1'].count()),\n    'Decision Trees or Random Forests': (responses_df_2021['Q17_Part_2'].count()),\n    'Gradient Boosting Machines (xgboost, lightgbm, etc)' : (responses_df_2021['Q17_Part_3'].count()),\n    'Dense Neural Networks (MLPs, etc)' : (responses_df_2021['Q17_Part_6'].count()),\n    'Convolutional Neural Networks' : (responses_df_2021['Q17_Part_7'].count()),\n    'Recurrent Neural Networks' : (responses_df_2021['Q17_Part_9'].count()),\n    'Transformer Networks (BERT, gpt-3, etc)' : (responses_df_2021['Q17_Part_10'].count()),\n}\n\n\n\nq17_dictionary_of_perc_2021 = count_then_return_percent_for_multiple_column_questions(responses_df_2021,\n                                                  q17_list_of_columns_2021,\n                                                  q17_dictionary_of_counts_2021)\n\nresponses_df_2020 = resp_2020\n\nq17_list_of_columns_2020 = ['Q17_Part_1',\n                       'Q17_Part_2',\n                       'Q17_Part_3',\n                       'Q17_Part_4',\n                       'Q17_Part_5',\n                       'Q17_Part_6',\n                       'Q17_Part_7',\n                       'Q17_Part_8',\n                       'Q17_Part_9',\n                       'Q17_Part_10',\n                       'Q17_Part_11',\n                       'Q17_OTHER']\n\nq17_dictionary_of_counts_2020 = {\n    'Linear or Logistic Regression' : (responses_df_2020['Q17_Part_1'].count()),\n    'Decision Trees or Random Forests': (responses_df_2020['Q17_Part_2'].count()),\n    'Gradient Boosting Machines (xgboost, lightgbm, etc)' : (responses_df_2020['Q17_Part_3'].count()),\n    'Dense Neural Networks (MLPs, etc)' : (responses_df_2020['Q17_Part_6'].count()),\n    'Convolutional Neural Networks' : (responses_df_2020['Q17_Part_7'].count()),\n    'Recurrent Neural Networks' : (responses_df_2020['Q17_Part_9'].count()),\n    'Transformer Networks (BERT, gpt-3, etc)' : (responses_df_2020['Q17_Part_10'].count()),\n}\n\nq17_dictionary_of_perc_2020 = count_then_return_percent_for_multiple_column_questions(responses_df_2020,\n                                                  q17_list_of_columns_2020,\n                                                  q17_dictionary_of_counts_2020)\n#q24 2019\n\nq24_list_of_columns_2019 = ['Q24_Part_1',\n                       'Q24_Part_2',\n                       'Q24_Part_3',\n                       'Q24_Part_4',\n                       'Q24_Part_5',\n                       'Q24_Part_6',\n                       'Q24_Part_7',\n                       'Q24_Part_8',\n                       'Q24_Part_9',\n                       'Q24_Part_10',\n                       'Q24_Part_11',\n                       'Q24_Part_12']\n\nq24_dictionary_of_counts_2019 = {\n    'Linear or Logistic Regression' : (resp_2019['Q24_Part_1'].count()),\n    'Decision Trees or Random Forests': (resp_2019['Q24_Part_2'].count()),\n    'Gradient Boosting Machines (xgboost, lightgbm, etc)' : (resp_2019['Q24_Part_3'].count()),\n    'Dense Neural Networks (MLPs, etc)' : (resp_2019['Q24_Part_6'].count()),\n    'Convolutional Neural Networks' : (resp_2019['Q24_Part_7'].count()),\n    'Recurrent Neural Networks' : (resp_2019['Q24_Part_9'].count()),\n    'Transformer Networks (BERT, gpt-3, etc)' : (resp_2019['Q24_Part_10'].count()),\n}\n\nq24_dictionary_of_perc_2019 = count_then_return_percent_for_multiple_column_questions(resp_2019,\n                                                  q24_list_of_columns_2019,\n                                                  q24_dictionary_of_counts_2019)\n#2017\n\nsearchfor = ['Decision Trees', 'Random Forests']\n\ndef count_2017_q_workalg(dictionary_of_counts_for_a_single_question):\n    '''\n    A helper function to convert counts to percentages.\n    '''\n    total_count = 7301 #number taken from 2017 kaggle survey analysis kernel by the pudding\n    dictionary = dictionary_of_counts_for_a_single_question\n    for i in dictionary:\n        dictionary[i] = round(float(dictionary[i]*100\/total_count),1)\n    return dictionary\n\nq_workalg_dictionary_of_counts_2017 = { \n\n    'Linear or Logistic Regression' : resp_2017['WorkAlgorithmsSelect'].str.contains('Regression\/Logistic Regression').value_counts().to_frame().transpose()[True][0],\n    'Decision Trees or Random Forests': resp_2017['WorkAlgorithmsSelect'].str.contains('|'.join(searchfor)).value_counts().to_frame().transpose()[True][0],\n    'Gradient Boosting Machines (xgboost, lightgbm, etc)' : resp_2017['WorkAlgorithmsSelect'].str.contains('Gradient Boosted Machines').value_counts().to_frame().transpose()[True][0],\n    'Dense Neural Networks (MLPs, etc)' : resp_2017['WorkAlgorithmsSelect'].str.contains('Neural Networks').value_counts().to_frame().transpose()[True][0],\n    'Convolutional Neural Networks' : resp_2017['WorkAlgorithmsSelect'].str.contains('CNNs').value_counts().to_frame().transpose()[True][0],\n    'Recurrent Neural Networks' : resp_2017['WorkAlgorithmsSelect'].str.contains('RNNs').value_counts().to_frame().transpose()[True][0],\n    'Transformer Networks (BERT, gpt-3, etc)' : 0\n\n}\n\nq24_dictionary_of_perc_2017 = count_2017_q_workalg(q_workalg_dictionary_of_counts_2017)\nq17_dictionary_of_perc_2021\n#scatterplot work\n\ndef algo_type_scatterplot(perc_dict, year):\n    df = pd.DataFrame(data = perc_dict, index = ['Percentage of Respondents']).transpose()\n    df['Year'] = year\n    df = df.reset_index()\n    df = df.rename(columns={'index':'Type of Algorithm'})\n    \n    return df\n    \n\nalgo_type_df = algo_type_scatterplot(q17_dictionary_of_perc_2021, 2021)\nalgo_type_df = algo_type_df.append(algo_type_scatterplot(q17_dictionary_of_perc_2020, 2020))\nalgo_type_df = algo_type_df.append(algo_type_scatterplot(q24_dictionary_of_perc_2019, 2019))\nalgo_type_df = algo_type_df.append(algo_type_scatterplot(q24_dictionary_of_perc_2017, 2017))\nalgo_type_df = algo_type_df.reset_index(drop=True)\na4_dims = (13, 10)\nalgo_fig, algo_ax = plt.subplots(figsize=a4_dims)\n\nsns.lineplot(data = algo_type_df,\n            ax = algo_ax,\n            x = 'Year',\n            y = 'Percentage of Respondents',\n            hue = 'Type of Algorithm',\n            style = 'Type of Algorithm',\n            markers = True,\n            dashes = False)\nalgo_ax.set_xticks(ticks = [2017, 2019, 2020, 2021])\n#cloud compute\n#popularity of cloud compute show that users who don't use any are decreasing\n#show that trend in money used for cloud is not changing much maybe since cloud is expensive\n#credits to kaggle's eda notebook\n\nresponses_df_2018 = resp_2018\nresponses_df_2019 = resp_2019\n\nq26a_dictionary_of_counts_2018 = {\n    'Amazon Web Services (AWS)' : (responses_df_2018['Q15_Part_2'].count()),\n    'Microsoft Azure': (responses_df_2018['Q15_Part_3'].count()),\n    'Google Cloud Platform (GCP)' : (responses_df_2018['Q15_Part_1'].count()),\n    'None' : (responses_df_2018['Q15_Part_6'].count()),\n}\n\nq26a_list_of_columns_2018 = ['Q15_Part_1',\n                        'Q15_Part_2',\n                        'Q15_Part_3',\n                        'Q15_Part_4',\n                        'Q15_Part_5',\n                        'Q15_Part_6',\n                        'Q15_Part_7']\n\nq26a_dictionary_of_counts_2019 = {\n    'Amazon Web Services (AWS)' : (responses_df_2019['Q29_Part_2'].count()),\n    'Microsoft Azure': (responses_df_2019['Q29_Part_3'].count()),\n    'Google Cloud Platform (GCP)' : (responses_df_2019['Q29_Part_1'].count()),\n    'None' : (responses_df_2019['Q29_Part_11'].count()),\n}\n\nq26a_list_of_columns_2019 = ['Q29_Part_1',\n                        'Q29_Part_2',\n                        'Q29_Part_3',\n                        'Q29_Part_4',\n                        'Q29_Part_5',\n                        'Q29_Part_6',\n                        'Q29_Part_7',\n                        'Q29_Part_8',\n                        'Q29_Part_9',\n                        'Q29_Part_10',\n                        'Q29_Part_11',\n                        'Q29_Part_12']\n\nq26a_dictionary_of_counts_2020 = {\n    'Amazon Web Services (AWS)' : (responses_df_2020['Q26_A_Part_1'].count()),\n    'Microsoft Azure': (responses_df_2020['Q26_A_Part_2'].count()),\n    'Google Cloud Platform (GCP)' : (responses_df_2020['Q26_A_Part_3'].count()),\n    'None' : (responses_df_2020['Q26_A_Part_11'].count()),\n}\n\nq26a_list_of_columns_2020 = ['Q26_A_Part_1',\n                        'Q26_A_Part_2',\n                        'Q26_A_Part_3',\n                        'Q26_A_Part_4',\n                        'Q26_A_Part_5',\n                        'Q26_A_Part_6',\n                        'Q26_A_Part_7',\n                        'Q26_A_Part_8',\n                        'Q26_A_Part_9',\n                        'Q26_A_Part_10',\n                        'Q26_A_Part_11',\n                        'Q26_A_OTHER']\n\nq27a_dictionary_of_counts_2021 = {\n    'Amazon Web Services (AWS)' : (responses_df_2021['Q27_A_Part_1'].count()),\n    'Microsoft Azure': (responses_df_2021['Q27_A_Part_2'].count()),\n    'Google Cloud Platform (GCP)' : (responses_df_2021['Q27_A_Part_3'].count()),\n    'None' : (responses_df_2021['Q27_A_Part_11'].count()),\n}\n\nq27a_list_of_columns_2021 = ['Q27_A_Part_1',\n                        'Q27_A_Part_2',\n                        'Q27_A_Part_3',\n                        'Q27_A_Part_4',\n                        'Q27_A_Part_5',\n                        'Q27_A_Part_6',\n                        'Q27_A_Part_7',\n                        'Q27_A_Part_8',\n                        'Q27_A_Part_9',\n                        'Q27_A_Part_10',\n                        'Q27_A_Part_11',\n                        'Q27_A_OTHER']\n\nq26a_dictionary_of_perc_2018 = count_then_return_percent_for_multiple_column_questions(responses_df_2018,\n                                                  q26a_list_of_columns_2018,\n                                                  q26a_dictionary_of_counts_2018)\nq26a_dictionary_of_perc_2019 = count_then_return_percent_for_multiple_column_questions(responses_df_2019,\n                                                  q26a_list_of_columns_2019,\n                                                  q26a_dictionary_of_counts_2019)\nq26a_dictionary_of_perc_2020 = count_then_return_percent_for_multiple_column_questions(responses_df_2020,\n                                                  q26a_list_of_columns_2020,\n                                                  q26a_dictionary_of_counts_2020)\nq27a_dictionary_of_perc_2021 = count_then_return_percent_for_multiple_column_questions(responses_df_2021,\n                                                  q27a_list_of_columns_2021,\n                                                  q27a_dictionary_of_counts_2021)\n\ndef cloud_scatterplot(perc_dict, year):\n    df = pd.DataFrame(data = perc_dict, index = ['Percentage of Respondents']).transpose()\n    df['Year'] = year\n    df = df.reset_index()\n    df = df.rename(columns={'index':'Cloud Computing Platform'})\n    \n    return df\n\ncloud_use_df = cloud_scatterplot(q27a_dictionary_of_perc_2021, 2021)\ncloud_use_df = cloud_use_df.append(cloud_scatterplot(q26a_dictionary_of_perc_2020, 2020))\ncloud_use_df = cloud_use_df.append(cloud_scatterplot(q26a_dictionary_of_perc_2019, 2019))\ncloud_use_df = cloud_use_df.append(cloud_scatterplot(q26a_dictionary_of_perc_2018, 2018))\ncloud_use_df = cloud_use_df.reset_index(drop=True)\na4_dims = (13, 10)\ncloud_fig, cloud_ax = plt.subplots(figsize=a4_dims)\n\nsns.lineplot(data = cloud_use_df,\n            ax = cloud_ax,\n            x = 'Year',\n            y = 'Percentage of Respondents',\n            hue = 'Cloud Computing Platform',\n            style = 'Cloud Computing Platform',\n            markers = True,\n            dashes = False)\ncloud_ax.set_xticks(ticks = [2018, 2019, 2020, 2021])\ndef count_then_return_percent(dataframe,column_name):\n    '''\n    A helper function to return value counts as percentages.\n    '''\n    counts = dataframe[column_name].value_counts(dropna=True)\n    percentages = round(counts*100\/(dataframe[column_name].count()),1)\n    return percentages\n\n#responses_df_2019 = responses_df_2019['Q11'].replace([\"$0 (USD)\"], \"$0\",inplace=True)\n\ndef cloud_cost_scatterplot(perc_dict, year):\n    df = perc_dict.to_frame(name = 'Percentage of Respondents').iloc[1:,:]\n    df = df.reset_index()\n    df = df.rename(columns={'index': 'Money Spent on Cloud(USD)'})\n    df['Year'] = year\n    \n    return df\n\ncloud_cost_perc_2019 = count_then_return_percent(responses_df_2019,'Q11').iloc[::-1]#[responses_in_order]\ncloud_cost_perc_2020 = count_then_return_percent(responses_df_2020,'Q25').iloc[::-1]#[responses_in_order]\ncloud_cost_perc_2021 = count_then_return_percent(responses_df_2021,'Q26').iloc[::-1]#[responses_in_order]\n\ncloud_cost_df = cloud_cost_scatterplot(cloud_cost_perc_2021, 2021)\ncloud_cost_df = cloud_cost_df.append(cloud_cost_scatterplot(cloud_cost_perc_2020, 2020))\ncloud_cost_df = cloud_cost_df.append(cloud_cost_scatterplot(cloud_cost_perc_2019, 2019))\ncloud_cost_df = cloud_cost_df.reset_index(drop=True)\na4_dims = (13, 10)\ncloud_cost_fig, cloud_cost_ax = plt.subplots(figsize=a4_dims)\n\nsns.lineplot(data = cloud_cost_df,\n            ax = cloud_cost_ax,\n            x = 'Year',\n            y = 'Percentage of Respondents',\n            hue = 'Money Spent on Cloud(USD)',\n            style = 'Money Spent on Cloud(USD)',\n            markers = True,\n            dashes = False)\ncloud_ax.set_xticks(ticks = [2019, 2020, 2021])\n\n#shows that more people are using, but using free tier, perhaps to experiment\n#\uc720\uc800 \ubd84\uc11d\ngpu_total_2021 = resp_2021['Q17_Part_1'].str.contains('GPUs').fillna(value = False) | \\\nresp_2021['Q17_Part_2'].str.contains('TPUs').fillna(value = False) | \\\nresp_2021['Q12_Part_3'].str.contains('AWS Trainium Chips').fillna(value = False) | \\\nresp_2021['Q12_Part_4'].str.contains('AWS Inferentia Chips').fillna(value = False) | \\\nresp_2021['Q12_Part_5'].str.contains('None').fillna(value = False) | \\\nresp_2021['Q12_OTHER'].str.contains('Other').fillna(value = False)\n(pd.Series(['hi', 'hello']).str.contains('')) & (pd.Series(['hey', 'ho']).str.contains('hey'))\nresp_2021.iloc[8].to_frame().reset_index().iloc[90:102]\nresp_2021.iloc[0:10]\n#\uc720\uc800\ub97c 3\uc73c\ub85c \ub098\ub208\ub2e4  --> \uba38\uc2e0\ub7ec\ub2dd only  \/ \ub525\ub7ec\ub2dd only \/ \uba38\uc2e0\ub7ec\ub2dd + \ub525\ub7ec\ub2dd \n#\ub144\ub3c4\ub9c8\ub2e4 \ucd94\uc774? \ub144\ub3c4 + \uba38\uc2e0\ub7ec\ub2dd pref + \ub2e4\ub978 \ubcc0\uc218 \ubd84\uc11d\n# --> \uc5f0\ubd09?\n# \uc9c1\uc885???\n\n'''Don't count other, none''' \n\n'''\nMachine Learning Algos \nLin Log Reg (1)\nDecision (2)\nGrad Boosting (3)\nBayesian (4)\nEvolutionary (5)\n'''\n\n'''\nDeep Learning Algos \nDense NN (6)\nCNN (7)\nGAN (8)\nRNN (9)\nTransformer (10)\n'''\n\n\nml_only_2021 = (resp_2021['Q17_Part_1'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_2'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_3'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_4'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_5'].str.contains('').fillna(value = False)) & \\\n(resp_2021['Q17_Part_6'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_7'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_8'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_9'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_10'].str.contains('impossible_val').fillna(value = True))\n\nml_only_2021 = resp_2021[ml_only_2021]\nml_only_2021 = ml_only_2021[(ml_only_2021['Q25'] != '$0-999') &  \n                            (ml_only_2021['Q25'] != 'What is your current yearly compensation (approximate $USD)?')]\n\ndl_only_2021 = (resp_2021['Q17_Part_6'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_7'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_8'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_9'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_10'].str.contains('').fillna(value = False)) & \\\n(resp_2021['Q17_Part_1'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_2'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_3'].str.contains('impossible_val').fillna(value = True) & \\\nresp_2021['Q17_Part_4'].str.contains('impossible_val').fillna(value = True) &  \\\nresp_2021['Q17_Part_5'].str.contains('impossible_val').fillna(value = True))\ndl_only_2021 = resp_2021[dl_only_2021]\ndl_only_2021 = dl_only_2021[(dl_only_2021['Q25'] != '$0-999') &  \n                            (dl_only_2021['Q25'] != 'What is your current yearly compensation (approximate $USD)?')]\n\nml_dl_2021 = (resp_2021['Q17_Part_1'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_2'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_3'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_4'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_5'].str.contains('').fillna(value = False)) & \\\n(resp_2021['Q17_Part_6'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_7'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_8'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_9'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_10'].str.contains('').fillna(value = False))\nml_dl_2021 = resp_2021[ml_dl_2021]\nml_dl_2021 = ml_dl_2021[(ml_dl_2021['Q25'] != '$0-999') &  \n                            (ml_dl_2021['Q25'] != 'What is your current yearly compensation (approximate $USD)?')]\n\nmldl_count_check = (resp_2021['Q17_Part_1'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_2'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_3'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_4'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_5'].str.contains('').fillna(value = False)) | \\\n(resp_2021['Q17_Part_6'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_7'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_8'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_9'].str.contains('').fillna(value = False) | \\\nresp_2021['Q17_Part_10'].str.contains('').fillna(value = False))\nmldl_count_check = resp_2021[mldl_count_check]\nmldl_count_check = mldl_count_check[(mldl_count_check['Q25'] != '$0-999') &  \n                            (mldl_count_check['Q25'] != 'What is your current yearly compensation (approximate $USD)?')]\n\n\ndef salary_conv_2021(df):\n    #for responses in 2020\n    #converts from strings to numerical data\n    #I put inputted the value of salary that was right in between the range of salaries in order for a fair estimate of salaries\n    conv_dict = {'10,000-14,999':12500, '1,000-1,999':1500, '100,000-124,999': 112500,\n                '40,000-49,999':45000, '30,000-39,999':35000, '50,000-59,999': 55000, '5,000-7,499':6250,\n                '15,000-19,999':17500, '60,000-69,999':65000, '20,000-24,999': 22500, '70,000-79,999':75000,\n                '7,500-9,999':8750, '150,000-199,999':175000, '2,000-2,999':2500, '125,000-149,999':137500,\n                '25,000-29,999':27500, '90,000-99,999':95000, '4,000-4,999':4500, '80,000-89,999':85000,\n                '3,000-3,999':3500, '200,000-249,999':225000, '300,000-500,000':400000, '$500,000-999,999':500000,\n                '250,000-299,999':275000, '>$1,000,000': 1000000, '300,000-499,999':350000}\n    df = df['Q25'].map(conv_dict)\n    return df\nprint(len(mldl_count_check)) \nprint((len(ml_only_2021) + len(dl_only_2021)) + ( len(ml_dl_2021)))\n#if same, the stuff is done correctly \nprint(salary_conv_2021(ml_only_2021).mean())\nprint(salary_conv_2021(dl_only_2021).mean())\nprint(salary_conv_2021(ml_dl_2021).mean())\nprint(salary_conv_2021(mldl_count_check).mean())\nprint(salary_conv_2021(ml_only_2021).median())\nprint(salary_conv_2021(dl_only_2021).median())\nprint(salary_conv_2021(ml_dl_2021).median())\nprint(salary_conv_2021(mldl_count_check).median())\nhi = salary_conv_2021(ml_only_2021).value_counts()\n(salary_conv_2021(ml_only_2021).value_counts() \/ sum(hi)).to_frame().reset_index()\nml_only_2021\ndef df_to_salary_bar(series, x_ind, y_ind, specialty):\n    val_counts = salary_conv_2021(series).value_counts()\n    res = ((val_counts \/ sum(val_counts)) * 100).to_frame().reset_index()\n    res = res.rename(columns = {'index':x_ind, 'Q25': y_ind})\n    res['Type'] = specialty\n    return res\n    \na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\n\n\n#sns.histplot(data = salary_conv_2021(ml_only_2021))\nsns.barplot(data = df_to_salary_bar(ml_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML Only'), x = 'Salary (USD)', y = 'Percentage of Respondents')\n\nhi_ax.tick_params(labelrotation=45)\n\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\n\n#sns.histplot(data = salary_conv_2021(dl_only_2021))\nsns.barplot(data = df_to_salary_bar(dl_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'DL Only'),  x = 'Salary (USD)', y = 'Percentage of Respondents')\n\nhi_ax.tick_params(labelrotation=45)\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\n\nsns.barplot(data = df_to_salary_bar(ml_dl_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML and DL'),  x = 'Salary (USD)', y = 'Percentage of Respondents')\n#sns.histplot(data = salary_conv_2021(ml_dl_2021))\nhi_ax.tick_params(labelrotation=45)\nhi = df_to_salary_bar(ml_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML Only')\nhi = hi.append(df_to_salary_bar(dl_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'DL Only'))\nhi = hi.append(df_to_salary_bar(ml_dl_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML and DL'))\nhi\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\n\n#sns.histplot(data = hi, x='Salary (USD)', y = 'Percentage of Respondents', hue='Type', element = 'step')\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\nsns.boxplot(x=salary_conv_2021(ml_only_2021))\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\nsns.boxplot(x=salary_conv_2021(dl_only_2021))\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\nsns.boxplot(x=salary_conv_2021(ml_dl_2021))\nhi\nsalary_conv_2021(ml_only_2021)\ndef ahh(df, name):\n    res = salary_conv_2021(df).dropna().to_frame()\n    res['Type'] = name\n    \n    return res\nhey = ahh(ml_only_2021, 'ML Only')\nhey = hey.append(ahh(dl_only_2021, 'DL Only'))\nhey = hey.append(ahh(ml_dl_2021, 'ML and DL'))\nhey = hey.reset_index(drop = True)\nhey\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\nsns.violinplot(data = hey, y = 'Type', x = 'Q25', jitter = 0.55)\na4_dims = (13, 10)\nhi_fig, hi_ax = plt.subplots(figsize=a4_dims)\n\n\nsns.barplot(data = df_to_salary_bar(ml_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML Only'), x = 'Salary (USD)', y = 'Percentage of Respondents', \n            color = 'blue', alpha = 1)\nsns.barplot(data = df_to_salary_bar(dl_only_2021, 'Salary (USD)', 'Percentage of Respondents', 'DL Only'),  x = 'Salary (USD)', y = 'Percentage of Respondents', \n            color = 'green', alpha = 1)\nsns.barplot(data = df_to_salary_bar(ml_dl_2021, 'Salary (USD)', 'Percentage of Respondents', 'ML and DL'),  x = 'Salary (USD)', y = 'Percentage of Respondents', \n            color = 'orange', alpha = 1)\n\n\nhi_ax.tick_params(labelrotation=45)\nhello = hi.pivot(index='Salary (USD)', columns ='Type', values = 'Percentage of Respondents')\n\nhello.plot.bar(stacked = True, figsize = (13, 10))\nsalary_conv_2021(ml_only_2021)\nq17_dictionary_of_counts_2021 = {\n    'Linear or Logistic Regression' : (responses_df_2021['Q17_Part_1'].count()),\n    'Decision Trees or Random Forests': (responses_df_2021['Q17_Part_2'].count()),\n    'Gradient Boosting Machines (xgboost, lightgbm, etc)' : (responses_df_2021['Q17_Part_3'].count()),\n    'Bayesian Approaches' : (responses_df_2021['Q17_Part_4'].count()),\n    'Evolutionary Approaches' : (responses_df_2021['Q17_Part_5'].count()),\n    'Dense Neural Networks (MLPs, etc)' : (responses_df_2021['Q17_Part_6'].count()),\n    'Convolutional Neural Networks' : (responses_df_2021['Q17_Part_7'].count()),\n    'Generative Adversarial Networks' : (responses_df_2021['Q17_Part_8'].count()),\n    'Recurrent Neural Networks' : (responses_df_2021['Q17_Part_9'].count()),\n    'Transformer Networks (BERT, gpt-3, etc)' : (responses_df_2021['Q17_Part_10'].count()),\n    'None' : (responses_df_2021['Q17_Part_11'].count()),\n    'Other' : (responses_df_2021['Q17_OTHER'].count())\n}\n\n\n\nq17_dictionary_of_perc_2021 = count_then_return_percent_for_multiple_column_questions(responses_df_2021,\n                                                  q17_list_of_columns_2021,\n                                                  q17_dictionary_of_counts_2021)\n'''\n\uc5c5\uacc4\ub294 \ub108\ubb34 \ub9ce\uc544\uc11c \uc77c\ub2e8 \ubcf4\ub958\n'''\n\n#slope graph\ub97c \ubcf4\uc5ec\uc8fc\uace0 \uc81c\uc77c \uccab\ubc88\uc9f8, \ub9c8\uc9c0\ub9c9 \ube7c\uace0\ub294 \ub4e4\ub7ec\ub9ac \uc2dd\uc73c\ub85c \ub9cc\ub4e4\uae30 \n#\uc774\uac70\ub97c \ud074\ub77c\uc6b0\ub4dc\uac00 \uc544\ub2cc ml \/ dl \ud37c\uc13c\ud14c\uc774\uc9c0\ub85c? \n\n\n#\uc5c5\uacc4\ub9c8\ub2e4 \ub525\ub7ec\ub2dd \/ \uba38\uc2e0\ub7ec\ub2dd \ud604\ud669 \uc5bc\ub9c8\ub098 \uc4f0\uc774\ub294\uc9c0 \uadf8\ub9ac\uace0 \uc5c5\uacc4 \ub9c8\ub2e4 \ub354 \uc4f0\ub294 \uc5c5\uacc4\uac00 \uc788\ub294\uc9c0 2018\uc5d0 \ube44\ud574\uc11c \uc5bc\ub9c8\ub098 \ubc14\ub00c\uc5c8\ub294\uc9c0 \n\n#\uc5c5\uacc4\ub9c8\ub2e4 \uc9e4\ub77c\uc11c \ud074\ub77c\uc6b0\ub4dc\uc5d0 \uc4f0\ub294 \ub3c8\uc744 \ube44\uad50 \n\nresp_2021['Q20'].value_counts()\nhi = resp_2021[resp_2021['Q20'] == 'Academics\/Education']['Q26'].value_counts()\nhi \/ sum(hi)","meta":"{'source': 'AI4Code', 'id': 'c263132756e3c9'}"}
{"id":"78169","text":"\"\"\"\n# Tutorial: Bar Charts in Python\n\nThis tutorial demonstrates the use of bar charts in Python. We will use both Matplotlib and Seaborn and the **FIFA 19 player dataset**. It can also be used as a quick reference when you are plotting bar charts in Python.\n\"\"\"\n\"\"\"\n## Loading Data and Cleaning\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndata = pd.read_csv(\"..\/input\/data.csv\")\n# These columns are links and will not be used in this notebook\ndata = data.drop(axis = 1, columns=['Photo','Flag', 'Club Logo'])  \ndata.head()\n\"\"\"\nThe 'Value' and 'Wage' columns have a Euro (\u20ac) sign. We need to remove the Euro sign and transform into numbers.\n\"\"\"\n# Clean up value and wage columns\ndef get_value(value):\n    value_num = value.replace('\u20ac','')\n    if 'M' in value_num:\n        value_num = float(value_num.replace('M','')) * 1000000\n    elif 'K' in value_num:\n        value_num = float(value_num.replace('K','')) * 1000\n    return float(value_num) # Ensure both columns are in float format\n\ndata['Value'] = data['Value'].apply(lambda x: get_value(x))\ndata['Wage'] = data['Wage'].apply(lambda x: get_value(x))\n\ndata.head()\n\"\"\"\n## Basic Bar Plots\n\nWe start with the basic bar plots of the count of players by Nationality in this dataset. To plot bar charts in Python we have four ways: **(1) .plot() method in pandas; (2) plt.bar() in matplotlib; (3) barplot() in Seaborn; (4) countplot() in Seaborn.**\n\"\"\"\n# Create the top_10_nation pandas series\nby_nation = data.Nationality.value_counts()\ntop_10_nation = by_nation[:10]\ntop_10_nation\n# Method 1: .plot() in pandas\ntop_10_nation.plot(kind='bar'); # The ';' is to avoid showing a message before the chart\n# We can also plot horizontally by using 'barh' in 'kind' argument\ntop_10_nation.plot(kind='barh');\n\"\"\"\nI prefer using horizontal bars in most cases because the axis labels can be seen more easily.\n\"\"\"\n# Method 2: plt.bar() in matplotlib - we input x and y arguments\nplt.bar(top_10_nation.index, top_10_nation);\n# Horizontally\nplt.barh(top_10_nation.index, top_10_nation);\n\"\"\"\nThe bars are thicker than the first method, and by default it is shown in single color. But the vertical bars, the axis labels do not rotate and it looks messy.\n\"\"\"\n# Method 3: barplot() in Seaborn\nsns.barplot(top_10_nation.index, top_10_nation);\n# To plot horizontal bars, just flip the first two arguments and seaborn will sort out the orientation itself\nsns.barplot(top_10_nation, top_10_nation.index);\n\"\"\"\nDefault in Seaborn is to put the first value at the top. To do the same for .plot(), we need to reverse the sorting order of the input data:\n\"\"\"\ntop_10_nation_r = top_10_nation.sort_values(ascending=True)\ntop_10_nation_r.plot(kind='barh');\n\"\"\"\nWe can also plot bar chart of counts directly from data using countplot() function in Seaborn:\n\"\"\"\n# Method 4: Countplot\nsns.countplot(y = 'Nationality', data=data);\n\"\"\"\nAll countries will be plotted and the labels will be messed up. To plot only the top 10, we need to specify in 'order' argument:\n\"\"\"\nsns.countplot(y = 'Nationality', data=data, order = data.Nationality.value_counts().iloc[:10].index);\n\"\"\"\nFor more details of the functions above, please check the documentation:\n- [pandas.Series.plot()](https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/api\/pandas.Series.plot.html)\n- [matplotlib.pyplot.barh()](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.barh.html)\n- [seaborn.barplot()](https:\/\/seaborn.pydata.org\/generated\/seaborn.barplot.html)\n- [seaborn.countplot()](https:\/\/seaborn.pydata.org\/generated\/seaborn.countplot.html)\n\"\"\"\n\"\"\"\n## Simple Customization\n\nThis part will demonstrate how to customize colors, figure and font size, axis labels, and show values in charts. We will plot the most valuable English players in this example.\n\"\"\"\nengland = data.loc[data.Nationality == 'England'].sort_values('Value', ascending = False)\nengland.head()\n# Top 30 players by value\nengland_30 = england.head(30).loc[:, ['Name','Value']]\nsns.barplot(england_30.Value, england_30.Name);\n\"\"\"\nWe want to make the following changes:\n1. Add a title to the plot;\n2. Enlarge the plot so that the player names can be seen more clearly;\n3. Instead of scientific notation (1e7), we show the value in millions (and change the x-axis label to Value (M EUR))\n\"\"\"\nplt.figure(figsize=(10,7)) # Specify figure size\nsns.barplot(england_30.Value \/ 1000000 , england_30.Name) # in millions\nplt.title('Top 30 English Players by Value', fontsize=16)\nplt.xlabel('Value (EUR M)')\nplt.yticks(fontsize=12) # Larger tick labels\nplt.xticks(fontsize=12)\nplt.show()\n\"\"\"\nThe default colors in seaborn is beautiful, but if we want to specify a single color or another set of colors, we can specify in the plot function:\n\"\"\"\nplt.figure(figsize=(10,7)) # Specify figure size\nsns.barplot(england_30.Value \/ 1000000 , england_30.Name, color = 'red') # color argument specifies a single color\nplt.title('Top 30 English Players by Value', fontsize=16)\nplt.xlabel('Value (EUR M)')\nplt.yticks(fontsize=12) # Larger tick labels\nplt.xticks(fontsize=12)\nplt.show()\nplt.figure(figsize=(10,7)) # Specify figure size\nsns.barplot(england_30.Value \/ 1000000 , england_30.Name, palette = 'spring') # palette argument specifies the color map\nplt.title('Top 30 English Players by Value', fontsize=16)\nplt.xlabel('Value (EUR M)')\nplt.yticks(fontsize=12) # Larger tick labels\nplt.xticks(fontsize=12)\nplt.show()\n\"\"\"\nFor the list of color and palette names, please see below links:\n- [Colors can be used in color argument](https:\/\/matplotlib.org\/gallery\/color\/named_colors.html)\n- [Colormaps can be used in palette argument](https:\/\/matplotlib.org\/2.0.2\/examples\/color\/colormaps_reference.html)\n\"\"\"\n\"\"\"\n## Data Label, Annotation, and Reference Line\n\nWe can show the data values on the chart, and add reference lines for comparison. We plot the wage of Arsenal Players:\n\"\"\"\ndata['Club'].fillna('None', inplace=True) # Clean up some null values to avoid errors in the next step\narsenal = data[data['Club'].str.contains('Arsenal')]\narsenal = arsenal.sort_values('Wage', ascending=False)\narsenal.head()\n\"\"\"\nHere, we want to plot:\n- The wage of Arsenal players in descending order\n- Add actual values of their wages alongside each bar\n- Add a vertical line showing average wage for comparison, and show the average value on the chart\n\"\"\"\navg_arsenal = np.mean(arsenal['Wage'])\n\nplt.figure(figsize=(10,8))\ng = sns.barplot(arsenal.Wage \/ 1000 , arsenal.Name) # in thousands\n# Adding labels of data value\nfor i, v in enumerate(arsenal.Wage \/ 1000):\n    g.text(v+1, i, str(int(v))) # The three arguments are x-coordinate, y-coordinate, and the label\nplt.title('Wage of Arsenal Players')\nplt.xlabel('Wage (EUR K)')\nplt.axvline(avg_arsenal\/1000) # The vertical line\ng.text(avg_arsenal\/1000 + 5, 20, 'Mean wage: ' + str(int(avg_arsenal\/1000)) + 'K') # Annotation of the line\nplt.show()\n\"\"\"\nThat's it for now. Happy charting!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8fa3cc7a1155c6'}"}
{"id":"112583","text":"# 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 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\n\"\"\"\n# Loading the Datasets\n\"\"\"\ndf_pow_gen1 = pd.read_csv(\"..\/input\/solar-power-generation-data\/Plant_1_Generation_Data.csv\")   #Module Function\n# df_pow_gen1 is a data frame object\ndf_wthr_gen1 = pd.read_csv(\"..\/input\/solar-power-generation-data\/Plant_1_Weather_Sensor_Data.csv\")\ndf_pow_gen2 = pd.read_csv(\"..\/input\/solar-power-generation-data\/Plant_2_Generation_Data.csv\")\ndf_wthr_gen2 = pd.read_csv(\"..\/input\/solar-power-generation-data\/Plant_2_Weather_Sensor_Data.csv\")\ntype(df_pow_gen1)\n\"\"\"\n# Exploring the Datasets\n\"\"\"\ndf_pow_gen1.describe() \ndf_pow_gen2.describe() \ndf_wthr_gen1.describe()\ndf_wthr_gen2.describe()\n\"\"\"\n# Mean Daily Yield\n\"\"\"\ndf_pow_gen1['DAILY_YIELD'].mean()\ndf_pow_gen2['DAILY_YIELD'].mean()\n\"\"\"\n# Total Irradiation\n\"\"\"\ndf_wthr_gen1['IRRADIATION'].count()\ndf_wthr_gen2['IRRADIATION'].count()\n\"\"\"\n# Maximum Ambient Temperature and Module Temperature\n\"\"\"\ndf_wthr_gen1[['AMBIENT_TEMPERATURE','MODULE_TEMPERATURE']].max()\ndf_wthr_gen2[['AMBIENT_TEMPERATURE','MODULE_TEMPERATURE']].max()\n\"\"\"\n# Number of Inverters in each Generator\n\"\"\"\nlen(df_pow_gen1['SOURCE_KEY'].unique())\nlen(df_pow_gen2['SOURCE_KEY'].unique())\n\"\"\"\n# Maximum and Minimum of AC-DC Power Generated\n\"\"\"\ndf_pow_gen1[['AC_POWER','DC_POWER']].max()\ndf_pow_gen1[['AC_POWER','DC_POWER']].min()\n\"\"\"\n# Inverter with Maximum AC-DC Power\n\"\"\"\ndf_pow_gen1[['AC_POWER','DC_POWER']].idxmax()\ndf_pow_gen1['SOURCE_KEY'][61624]\ndf_pow_gen2[['AC_POWER','DC_POWER']].idxmax()\ndf_pow_gen1['SOURCE_KEY'][41423]\n\"\"\"\nTherefore, the inverters with the maximum AC\/DC Power Generation is \n\nGenerator 1 - wCURE6d3bPkepu2\n\nGenerator 2 - ZoEaEvLYb1n2sOq\n\"\"\"\n\"\"\"\n# Missing Data\n\"\"\"\ndf_pow_gen1.isnull()\ndf_pow_gen2.isnull()\ndf_wthr_gen1.isnull()\ndf_wthr_gen2.isnull()\n\"\"\"\nTherefore, there seems to be no missing data.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ceda6976238ef9'}"}
{"id":"56096","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('bmh')\nimport os\nimport cv2\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nOUTPUT_DIR = '.\/'\nimage_size = 256\nbatch_size = 32\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\ndevice\n\"\"\"\n### Load Model\n\"\"\"\nmodel = torch.load('..\/input\/cassava-balanced-ce-model\/sgd_balanced_ce_aug.pt')\n\"\"\"\n### Get Data\n\"\"\"\nclass CassavaDataset(Dataset):\n    def __init__(self, data_dir, ids, labels, transform=None):\n        self.data_dir = data_dir\n        self.ids = ids\n        self.labels = labels\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.ids)\n    \n    def __getitem__(self, idx):\n        image = cv2.imread(os.path.join(self.data_dir, self.ids[idx]))\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        if self.transform:\n            image = self.transform(image=image)['image']\n        \n        label = self.labels[idx]    \n        \n        return (image, label)\ntransform = A.Compose([\n    A.RandomResizedCrop(image_size, image_size),\n    A.HorizontalFlip(p=0.5),\n    A.VerticalFlip(p=0.25),\n    A.Transpose(p=0.25),\n    A.RandomBrightnessContrast(\n                brightness_limit=(-0.1,0.1), \n                contrast_limit=(-0.1, 0.1), \n                p=0.5),\n    A.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0),\n    ToTensorV2(p=1.0)\n])\ntest_df = pd.read_csv('..\/input\/cassava-leaf-disease-classification\/sample_submission.csv')\ntest_dir = '..\/input\/cassava-leaf-disease-classification\/test_images'\nids = test_df['image_id'].values\nlabels = test_df['label'].values\ntest_df\ntest_dataset = CassavaDataset(test_dir, ids, labels, transform=transform)\ntest_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)\n\"\"\"\n### Inference with TTA\n\"\"\"\nsoftmax = nn.Softmax(dim = 1)\nnum_inferences = 10\ninferences = []\n\nfor i in range(num_inferences): \n    inf = []\n    model.eval()\n    with torch.no_grad(): \n        for data in test_loader:\n            inputs, labels = data\n            inputs = inputs.to(device)\n            outputs = softmax(model(inputs))\n            outputs = outputs.cpu().numpy()\n            inf += list(outputs)\n    inferences.append(np.array(inf))\npreds = np.zeros((inferences[0].shape))\nfor inf in inferences:\n    preds += inf\npreds = preds \/ num_inferences\npreds = list(np.argmax(preds, axis=1))\ntest_df['label'] = preds\ntest_df.to_csv(OUTPUT_DIR+'submission.csv', index=False)\npd.read_csv(OUTPUT_DIR+'submission.csv')","meta":"{'source': 'AI4Code', 'id': '6776fb7e8b2ba5'}"}
{"id":"40666","text":"\"\"\"\n# Project Overview\n\nWhile crowdfunding Kickstarter projects seem lucrative, it does not mean that it is without risk. When a project fails, the risk extends to both project owners and backers. Project owners who have invested a large amount of money into building the product will suffer from a huge loss if the goal is not reached. Backers who have contributed into the projects may end up not receiving the products that they expected to get.\n\n\nThis project aims to identify the different factors that affect the success of a Kickstarter project. The analysis will be based on data of Kickstarter projects in the year 2018.\n\"\"\"\n\"\"\"\n## Imports\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n# Getting glimpse of the data\n\ndf = pd.read_csv(\"..\/input\/kickstarter-projects\/ks-projects-201801.csv\")\ndf.head()\n# I noticed that there is an inconsistency in the format of the column name 'usd pledged'\n# This will cause a problem later as Pandas cannot access columns that contain spaces\n# Here, I'm replacing columns with ' ' space with '_' underscore\n\ndf.columns = [col.replace(\" \", \"_\") for col in df.columns]\n# Dropping the column pledged, usd pledged\n# These columns are equal to usd_pledged_real & usd_pledged_goal fields\n# The only difference is the conversion rate used; _real columns uses conversion provided by Fixer.io.\n\ndf = df.drop(labels=[\"pledged\", \"usd_pledged\", \"goal\"], axis=1)\ndf.head()\n\"\"\"\n## Business Understanding\n\nThese are the specific questions that we aim to answer in the analysis: \n\n\"Are there differences in project popularity or amount of goal across different categories?\"\n\n\"Is the goal realistic?\"\n\n\"What is the average amount pledged by each backer? Are people willing to contribute more of their money into certain projects?\"\n\n\"Are there differences in project popularity or amount of goal across different durations?\"\n\"\"\"\n\"\"\"\n## Data Understanding & Analysis\n\"\"\"\n\"\"\"\nIn this section, we will deep dive into the data to familiarise ourselves further, identify data quality issues that can potentially affect our analysis and discover insights in the data that can answer our questions.\n\"\"\"\n# Computing summary statistics pertaining to the quantitative variables of the data\n\ndf.describe()\n\"\"\"\n**Interpretation**\n\nIt is interesting to see that there are a lot of variance between the median (50% percentile) and the maximum values of the quantitative variables...\n\"\"\"\n# Checking the number of rows and columns in the datasest\n\nnum_rows = df.shape[0]\nnum_cols = df.shape[1]\n\nf\"There are {num_rows} rows and {num_cols} columns in the dataset\"\n# Proportion of NaN values in each of the column, sorted from in descending order\n\n(df.isnull().mean()).sort_values(ascending=False)\n\"\"\"\n**Interpretation**\n\nThe only column that has NaN values is 'name', but the proportion is very small (0.0011%). It doesn't seem that there is an alarming number of NaN values in any of the columns, which is a good sign.\n\"\"\"\n# A bar chart showing the count of projects by Main Category\n\ncount_by_main_cat = (df[\"main_category\"].value_counts()).sort_values(ascending=False)\ncount_by_main_cat = count_by_main_cat.to_frame().reset_index()\n\ncount_by_main_cat.rename(\n    columns={\"index\": \"main_category\", \"main_category\": \"project_count\"}, inplace=True\n)\n\ncount_by_main_cat.style.bar(subset=\"project_count\", align=\"mid\", color=[\"#5fba7d\"])\n\"\"\"\n**Interpretation**\n\nThe top 3 projects that are hosted on Kickstarter are:\n1. 'Film&Video'\n2. 'Music'\n3. 'Publishing'\n\nThe bottom 3 projects that are hosted on Kickstarter are:\n1. 'Dance',\n2. 'Journalism'\n3. 'Crafts'\n\"\"\"\n# Finding the number of backers per main_category\n\nmain_cat_backers_count = (\n    df.groupby(df[\"main_category\"]).sum()[[\"backers\"]].reset_index()\n)\nmain_cat_backers_count = main_cat_backers_count.sort_values(\n    by=\"backers\", ascending=False\n)\nmain_cat_backers_count.style.bar(subset=[\"backers\"], align=\"mid\", color=[\"#5fba7d\"])\n\"\"\"\n**Interpretation:**\n\nFrom the chart above, we can see that these are the most popular 3 main category by the total number of backers:\n1. 'Games'\n2. 'Design'\n3. 'Technology'.\n\n\nOn the bottom rows, these are the least backed projects:\n1. 'Dance'\n2. 'Journalism'\n3. 'Crafts'\n\nOn the chart above, I'm actually totalling up the number of backers for each category. The caveat of doing this is that it is possible that there are fewer projects in that category to begin with and therefore, there would not be many backers.\n\n.\n\n.\n\n.\n\n_Let's find the median number of backers per each main category instead._\n\"\"\"\n\"\"\"\n## Note\n\nI'm using median instead of mean here as the distribution of the quantitative variables are very skewed, as we can see in the table at the beginning of this notebook. Median is a measure of central tendency that is more robust to outliers.\n\"\"\"\n# Median number of backers per category\n\nmain_cat_backers_median = (\n    df.groupby(df[\"main_category\"]).median()[[\"backers\"]].reset_index()\n)\nmain_cat_backers_median = main_cat_backers_median.sort_values(\n    by=[\"backers\"], ascending=False\n)\n\nmain_cat_backers_median.style.bar(subset=[\"backers\"], align=\"mid\", color=[\"#5fba7d\"])\n\"\"\"\n**Intepretation**\n\nThe top 3 main categories that has the highest median number of backers are:\n1. Comics\n2. Design\n3. Games\n\nThe top 3 main categories that has the lowest median number of backers are:\n1. Journalism\n2. Crafts\n3. Fashion\n\nIt is interesting to see that Comics has the highest median number of backer in a single project. We can also see that Design is second after Comics.\n\nJournalism still has the lowest number of backer. The number of backer a project has doesn't always determine the success of a project. A project can have only 1 backer (sounds extreme, but why not), but he\/she can contribute $1,000,000 dollar to a project and the goal can still be easily met. I know this example sounds unrealistic, but I hope you get my point.\n\n.\n\n.\n\n.\n\n.\n\nNext, we will be looking into the median amount of money that each backer put to fund a project. \n\"\"\"\n# Finding the MEDIAN of the total amount pledged by main_category\n\nmedian_pledged_by_main_cat = (\n    df.groupby(df[\"main_category\"])\n    .median()[[\"usd_pledged_real\"]]\n    .sort_values(by=[\"usd_pledged_real\"], ascending=False)\n    .reset_index()\n)\n\nmedian_pledged_by_main_cat.style.bar(\n    subset=[\"usd_pledged_real\"], align=\"mid\", color=[\"#5fba7d\"]\n)\n\"\"\"\n**Interpretation**\n\nTop 3 main categories with the highest median amount pledged:\n\n1. Design\n2. Dance\n3. Theater\n\nBottom 3 main categories with the lowest median amount pledged:\n1. Journalism\n2. Crafts\n3. Photography\n\nWow, Design didn't only have a lot of backers but it also does have the highest median amount pledged!\n.\n\n.\n\n.\n\n.\n\nLet's also take a look at the median amount of goal set for each category. It doesn't matter if a project has a relatively high total pledged amount or number of backers but it still far away from the goal. On the other hand, a project can only have a few backers and little amount of money pledged, but if the goal set is relatively low, then there is still chance for it to be successful.\n\"\"\"\n# Finding the MEDIAN of the amount of project goal set, by main_category\n\nmedian_goal_by_main_cat = (\n    df.groupby(df[\"main_category\"])\n    .median()[[\"usd_goal_real\"]]\n    .sort_values(by=[\"usd_goal_real\"], ascending=False)\n    .reset_index()\n)\n\nmedian_goal_by_main_cat.style.bar(\n    subset=[\"usd_goal_real\"], align=\"mid\", color=[\"#5fba7d\"]\n)\n\"\"\"\n**Interpretation**\n\nTop 3 main categories by amount of project goal:\n1. Technology\n2. Design\n3. Food\n\nBottom 3 main categories by amount of project goal:\n1. Crafts\n2. Art\n3. Theater\n\nSeems that 'Technology' requires the highest amount of money to fund the project! Wait..didn't technology have a relatively low number of backers and median amount pledged though? This means that it is less likely for 'technology' projects to reach the goal.\n\n'Crafts' projects fortunately do not require lots of fund in the first place, even though it doesn't have high number of backers & amount pledged.\n\n.\n\n.\n\n.\n\nLet's find out if this is the case.\n\"\"\"\n# Finding the difference between the goal set and the total amount pledged\n\ngoal_vs_pledged = median_goal_by_main_cat.merge(\n    median_pledged_by_main_cat, how=\"outer\", on=\"main_category\"\n)\n\ngoal_vs_pledged[\"pledged_minus_goal\"] = (\n    goal_vs_pledged[\"usd_pledged_real\"] - goal_vs_pledged[\"usd_goal_real\"]\n)\n\n\ngoal_vs_pledged[\"pledged_over_goal_rate\"] = (\n    goal_vs_pledged[\"usd_pledged_real\"] \/ goal_vs_pledged[\"usd_goal_real\"]\n)\n\ngoal_vs_pledged.style.bar(\n    subset=[\n        \"usd_goal_real\",\n        \"usd_pledged_real\",\n        \"pledged_minus_goal\",\n        \"pledged_over_goal_rate\",\n    ],\n    align=\"mid\",\n    color=[\"#d65f5f\", \"#5fba7d\"],\n)\n\"\"\"\n**Interpretation**\n\nIn the chart above, I plotted the median of USD Goal, median of USD Pledged side by side. Then I subtract USD Pledged from USD Goal to see which main category that has the highest amount of losses.\n\nOn the right hand side, I created another column that divides USD Pledged \/ USD Goal to see which project main category that has the highest success rate.\n\n.\n\n.\n\n.\n\n\nThe highest success rate (pledged_over_goal_rate) is seen across the main categories of:\n1. Dance\n2. Theater\n3. Comics\n\nThe lowest success rate (pledged_over_goal_rate) is seen across the main categories of:\n1. Journalism\n2. Technology\n3. Crafts\n\nInterestingly, even though 'Technology' seems to be the main_category that typically sets the highest goal (median of 20k USD), the median amount of total money pledged is the lowest.\n\nCrowdfunding through sites like Kickstarter might seem lucrative at first glance, however if creators do not create a comprehensive budgeting plan, they might overlook 'unforeseen' costs that will make it even more difficult for the project to be fully funded\n\nI'm wondering if the goal if duration also plays a part in a project success? We'll analyse the results in the coming sections.\n\"\"\"\n# Calculating 'duration_in_days' and add into the dataframe\n\ndf[\"duration_in_days\"] = (\n    pd.to_datetime(df[\"deadline\"]) - pd.to_datetime(df[\"launched\"])\n).dt.days\ndf.head(3)\n# Returning the unique duration_in_days to check for its values\n\ndf.duration_in_days.unique()\n\"\"\"\nIn the array above, you can see that the the number of duration in days ranges from 58 to 16,738. I will those values that are above 14,000, which are outliers. This step is necessary as I will create a histogram to visualize the quantitative variables (backers, goals, amount pledged) into the binned duration.\n\nIf we include these outliers, then it would be difficult for us to interpret the histogram meaningfully.\n\"\"\"\n# Removing outliers in duration_in_days\n\ndf = df.loc[df[\"duration_in_days\"] < 14000]\n# Creating bins for duration_in_days\n\nduration_in_days_bins = np.linspace(\n    df.duration_in_days.min(), df.duration_in_days.max(), 10\n)\ndf[\"duration_in_days_bins\"] = pd.cut(df.duration_in_days, duration_in_days_bins)\n\nnumerical_col_list = [\"usd_goal_real\", \"backers\", \"usd_pledged_real\"]\n\n# Calculating the median of goal, backers & pledged amount for each duration bin\nmedian_by_duration_bins = (\n    df.groupby(df[\"duration_in_days_bins\"])[numerical_col_list].median().reset_index()\n)\nmedian_by_duration_bins\ndef plot_hist(\n    x,\n    bins,\n    weights,\n    xlabel=None,\n    ylabel=None,\n    title=None,\n    ax=None,\n    color=\"#5fba7d\",\n    **kwargs\n):\n    \"\"\"Plotting a histogram.\n\n    INPUT:\n    x - input values of the histogram\n    bins - bins of the histogram that the x should be put into\n    weights - array of weights with a same shape as x\n    xlabel - label of the histogram x axis (optional)\n    ylabel - label of the histogram y axis (optional)\n    ylabel - title of the histogram y axis (optional)\n    ax - subplot axis to plot the histogram (optional)\n    color - color of the histogram. default is green.\n\n    OUTPUT\n    hist - the histogram plot\n    \"\"\"\n    ax = ax or plt.gca()\n    # Do some cool data transformations...\n    hist = ax.hist(x=x, bins=bins, weights=weights, color=color, **kwargs)\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_title(\"Median Goal by Duration\")\n    \n    return hist\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\nfig.delaxes(ax[1, 1])\n\n# 'Median Goal by Duration'\nplot_hist(\n    duration_in_days_bins[:-1],\n    duration_in_days_bins,\n    median_by_duration_bins['usd_goal_real'],\n    xlabel='Duration in days bins',\n    ylabel='Median goal amount',\n    title='Median Goal by Duration',\n    ax=ax[0,0]\n);\n\n# 'Median Backers Count by Duration'\nplot_hist(\n    duration_in_days_bins[:-1],\n    duration_in_days_bins,\n    median_by_duration_bins['backers'],\n    xlabel='Duration in days bins',\n    ylabel='Median backers amount',\n    title='Median Backers by Duration',\n    ax=ax[0, 1]\n);\n\n# 'Median Pledged Amount by Duration'\nplot_hist(\n    duration_in_days_bins[:-1],\n    duration_in_days_bins,\n    median_by_duration_bins['usd_pledged_real'],\n    xlabel='Duration in days bins',\n    ylabel='Median pledged amount',\n    title='Median Pledged Amount by Duration',\n    ax=ax[1, 0]\n);\n\n\"\"\"\n**Interpretation:**\n\n\n_Goal_\n\nInitially, I thought that projects with high amount of goal set will have longer duration for the project to allow more time for the projects to attract backers.\nBased on the 'Goal by duration' figure, the highest median goal amount interestingly belongs to projects with duration that ranges from 30-60 days.\n\n_Backers_\n\nThe longer the duration of a project, does not necessarily mean that the project will end up attracting more backers, as can be seen in the 'Backers count by duration' histogram. The duration range that attracted the highest number of backers is 30-40 days.\n\n_Pledged_\n\nAgain, the highest median pledged amount seen in Kickstarter projects in 2018 belong to the 30-40 duration day range.\n\"\"\"\n\"\"\"\n## Conclusion\n\"\"\"\n\"\"\"\nWhile crowdfunding Kickstarter projects seem lucrative, it does not mean that there is no risk. When a project is failing, the risk extends to both project owners and backers. Project owners who have invested a large amount of money into building the product will suffer from a huge loss if the goal is not met. Backers who have contributed the projects may end up not receiving the products that they expected to get.\n\nIn the analysis above, we did a comparison of several success metrics of a project (e.g. number of backers, amount pledged) across different categories & project duration. The aim is to help backers & project owners to be more discerning of the different factors that affect a project success.\n\nHere is the summary of our findings:\n\n_Riskiest Category_\n\n- The riskiest category is 'Technology'. Not only does it require a lot of funds in the first place, but it also has the lowest success rate across all main categories.\n- 'Journalism' & 'Crafts' also have low success rates even though the amount of funds required to build the project is relatively low. When these projects failed, the amount of loss tends to be a lot lesser than the loss of Technology projects.\n- From the initial analysis, 'Design' seems to be pretty popular among backers and it has the highest median amount pledged. However, the goal that is set for Design projects tends to be high, which makes it more challenging for it to be successful.\n\n_Safest Category_\n\n- The safest category to go for is 'Dance', followed by 'Theater' and 'Comics'.\n- These projects do not require a lot of fixed costs to start and have the highest success rates.\n- If product owners can reduce the cost associated with Design projects significantly, then it can be a good category to launch your product.\n\n_Ideal Duration_\n\n- Duration does not seem to affect the success of a project much. Setting a longer duration does not necessarily increase the amount pledged and the number of backers.\n- Based on the analysis, the ideal duration is around 30\u201360 days, where it can attract the highest number of backers & generated a good amount of money pledged.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4ae3131ab20de9'}"}
{"id":"14912","text":"\"\"\"\n# Hourly Variation of Data across days\n\"\"\"\n\"\"\"\n### Objective\nTo see the hourly variation of power generated and temprature across dates per inverter\n\"\"\"\n\"\"\"\n**How to use the dashboard:**\n1. A line on each graph represents information from a date\n2. X axis in all line graphs represents the hour of the day\n3. Inverter ID is the source key from the plant table\n4. Clicking on a line will highlight that data point in all the graphs\n5. Filter icon displays a day level scatter plot between - Sum(AC Power) vs Avg(Ambient Tembrature)\n6. You can use the scatter plot to filter the highlight the lines on the other graphs, it will help in understanding instances like high temprature\n\n**Note:** Use the dashboard in desktop mode, full screen for better. You can go to <a href=\"https:\/\/tinyurl.com\/y4uvshj7\">this link<\/a> to view the dashboard better\n\"\"\"\n%%html\n<div class='tableauPlaceholder' id='viz1601916844713' style='position: relative'><noscript><a href='#'><img alt=' ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;So&#47;SolarPlantKaggle&#47;HourlyVariation&#47;1_rss.png' style='border: none' \/><\/a><\/noscript><object class='tableauViz'  style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' \/> <param name='embed_code_version' value='3' \/> <param name='site_root' value='' \/><param name='name' value='SolarPlantKaggle&#47;HourlyVariation' \/><param name='tabs' value='no' \/><param name='toolbar' value='yes' \/><param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;So&#47;SolarPlantKaggle&#47;HourlyVariation&#47;1.png' \/> <param name='animate_transition' value='yes' \/><param name='display_static_image' value='yes' \/><param name='display_spinner' value='yes' \/><param name='display_overlay' value='yes' \/><param name='display_count' value='yes' \/><param name='language' value='en' \/><param name='filter' value='publish=yes' \/><\/object><\/div>                <script type='text\/javascript'>                    var divElement = document.getElementById('viz1601916844713');                    var vizElement = divElement.getElementsByTagName('object')[0];                    if ( divElement.offsetWidth > 800 ) { vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';} else if ( divElement.offsetWidth > 500 ) { vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px';} else { vizElement.style.width='100%';vizElement.style.height='1327px';}                     var scriptElement = document.createElement('script');                    scriptElement.src = 'https:\/\/public.tableau.com\/javascripts\/api\/viz_v1.js';                    vizElement.parentNode.insertBefore(scriptElement, vizElement);                <\/script>\n\"\"\"\n**Aggregation present at hour level:**\n* Max of Daily Yield per hour\n* Sum of AC Power\/ DC Power per hour\n* Average of Ambient and Module Temprature\n* Sum of irradiation\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1b3f52f855c431'}"}
{"id":"71171","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\"\"\"\n# Classification task\n\nHi! It's a classification task baseline notebook.\nIt include a data reader, baseline model and submission generator.\n\"\"\"\nfrom pathlib import Path\nfrom datetime import datetime\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\n\nimport catalyst\nfrom catalyst import dl\nfrom catalyst.utils import metrics, set_global_seed\nset_global_seed(42)\n\"\"\"\n## Dataset\n\nThis code will help you to generate dataset. If your data have the following folder structure:\n\n```\ndataset\/\n    class_1\/\n        *.ext\n        ...\n    class_2\/\n        *.ext\n        ...\n    ...\n    class_N\/\n        *.ext\n        ...\n```\nFirst of all `create_dataset` function goes through a given directory and creates a dictionary `Dict[class_name, List[image]]`.\nThen `create_dataframe` function creates typical `pandas.DataFrame` for further analysis.\nAfter that, `prepare_dataset_labeling` creates a numerical label for each unique class name.\nFinally, to add a column with a numerical label value to the DataFrame, we can use `map_dataframe` function.\n\nAdditionaly let's save the `class_names` for further usage.\n\"\"\"\nfrom catalyst.utils import (\n    create_dataset, create_dataframe, get_dataset_labeling, map_dataframe\n)\n\ndataset = create_dataset(dirs=f\"..\/input\/Imagenette-comp\/train\/*\", extension=\"*.jpg\")\ndf = create_dataframe(dataset, columns=[\"class\", \"filepath\"])\n\ntag_to_label = get_dataset_labeling(df, \"class\")\nclass_names = [\n    name for name, id_ in sorted(tag_to_label.items(), key=lambda x: x[1])\n]\n\ndf_with_labels = map_dataframe(\n    df, \n    tag_column=\"class\", \n    class_column=\"label\", \n    tag2class=tag_to_label, \n    verbose=False\n)\ndf_with_labels.head()\n\"\"\"\nAnd you should split data in `train \/ valid \/ test` parts.\nThere are only `train` and `valid` parts, so you must load test data as shows in a code cell.\n\"\"\"\nfrom catalyst.utils import split_dataframe_train_test\n\ntrain_data, valid_data = split_dataframe_train_test(\n    df_with_labels, test_size=0.2, random_state=42\n)\ntrain_data, valid_data = (\n    train_data.to_dict(\"records\"),\n    valid_data.to_dict(\"records\"),\n)\nfrom catalyst.data.cv.reader import ImageReader\nfrom catalyst.dl import utils\nfrom catalyst.data import ScalarReader, ReaderCompose\n\nnum_classes = len(tag_to_label)\n\nopen_fn = ReaderCompose(\n    [\n        ImageReader(\n            input_key=\"filepath\", output_key=\"features\", rootpath=\"..\/input\/Imagenette-comp\/train\"\n        ),\n        ScalarReader(\n            input_key=\"label\",\n            output_key=\"targets\",\n            default_value=-1,\n            dtype=np.int64,\n        ),\n        ScalarReader(\n            input_key=\"label\",\n            output_key=\"targets_one_hot\",\n            default_value=-1,\n            dtype=np.int64,\n            one_hot_classes=num_classes,\n        ),\n    ]\n)\n\"\"\"\n## Augmentation\n\nUse some augmentations to generate more images for training process.\n\"\"\"\nimport albumentations as albu\nfrom albumentations.pytorch import ToTensorV2 as ToTensor\n\nIMAGE_SIZE = 224\n\ntrain_transform = albu.Compose([\n    albu.HorizontalFlip(p=0.5),\n    albu.LongestMaxSize(IMAGE_SIZE),\n    albu.PadIfNeeded(IMAGE_SIZE, IMAGE_SIZE, border_mode=0),\n    albu.RandomResizedCrop(IMAGE_SIZE, IMAGE_SIZE, p=0.3),\n    albu.Normalize(),\n    ToTensor(),\n])\n\nvalid_transform = albu.Compose([\n    albu.LongestMaxSize(IMAGE_SIZE),\n    albu.PadIfNeeded(IMAGE_SIZE, IMAGE_SIZE, border_mode=0),\n    albu.Normalize(),\n    ToTensor(),\n])\n\nfrom catalyst.data import Augmentor\n\ntrain_data_transform = Augmentor(\n    dict_key=\"features\", augment_fn=lambda x: train_transform(image=x)[\"image\"]\n)\n\nvalid_data_transform = Augmentor(\n    dict_key=\"features\", augment_fn=lambda x: valid_transform(image=x)[\"image\"]\n)\n\n\"\"\"\nDon't forget to create test loader.\n\"\"\"\nbatch_size = 256\nnum_workers = 4\n\ntrain_loader = utils.get_loader(\n    train_data,\n    open_fn=open_fn,\n    dict_transform=train_data_transform,\n    batch_size=batch_size,\n    num_workers=num_workers,\n    shuffle=True,\n    sampler=None,\n    drop_last=True,\n)\n\nvalid_loader = utils.get_loader(\n    valid_data,\n    open_fn=open_fn,\n    dict_transform=valid_data_transform,\n    batch_size=batch_size,\n    num_workers=num_workers,\n    shuffle=False, \n    sampler=None,\n    drop_last=True,\n)\n\nloaders = {\n    \"train\": train_loader,\n    \"valid\": valid_loader\n}\n\"\"\"\n## Model\n\nFor the baseline, we will use a ResNet model, we already have examined in the seminar.\nEnhance the model, use any* instruments or module as you like.\n\n*(Don't forget about the rules!)\n\"\"\"\nfrom torchvision import transforms, models\n\nclass MyResNet50(torch.nn.Module):\n    def __init__(self):\n        super(MyResNet50, self).__init__()\n        self.net = models.resnet50(pretrained=True)\n        \n        # Disable grad for all conv layers\n        for param in self.net.parameters():\n            param.requires_grad = False                \n        \n        # Create some additional layers for ResNet model\n        fc_inputs = self.net.fc.in_features\n        self.net.fc = torch.nn.Sequential(\n            torch.nn.Linear(fc_inputs, 256),\n            torch.nn.ReLU(),\n            torch.nn.Linear(256, 128),\n            torch.nn.Sigmoid(),\n            torch.nn.Linear(128, 10),\n        )  \n    def forward(self, x):\n        x = self.net(x)\n        return x\nclass ResNetBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride, p=0.1):\n        super().__init__()\n\n        self.input = nn.Sequential(\n            nn.Conv2d(\n                in_channels,\n                out_channels,\n                kernel_size=3,\n                stride=stride,\n                padding=1,\n            ),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(),\n            nn.Conv2d(\n                out_channels, out_channels, kernel_size=3, stride=1, padding=1\n            ),\n            nn.BatchNorm2d(out_channels),\n        )\n        self.res = nn.Conv2d(\n            in_channels, out_channels, kernel_size=1, stride=stride\n        )\n        self.output = nn.Sequential(nn.BatchNorm2d(out_channels), nn.ReLU())\n\n    def forward(self, x):\n        input = self.input(x)\n        res = self.res(x)\n        return self.output(res + input)\n\n\nclass BaselineModel(nn.Module):\n    def __init__(self, channels=3, in_features=64, num_classes=10, p=0.1):\n        super().__init__()\n\n        self.input = nn.Sequential(\n            nn.Conv2d(\n                channels, in_features, kernel_size=7, stride=2, padding=3\n            ),\n            nn.BatchNorm2d(in_features),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n        )\n\n        self.layer_0 = self._make_layer(in_features, 1)\n        self.layer_1 = self._make_layer(in_features)\n        in_features *= 2\n        self.layer_2 = self._make_layer(in_features)\n        in_features *= 2\n        self.layer_3 = self._make_layer(in_features)\n\n        self.fc = nn.Sequential(\n            nn.AdaptiveAvgPool2d((1, 1)),\n            nn.Flatten(),\n            nn.Linear(2 * in_features, num_classes),\n        )\n\n    def _make_layer(self, in_features, multiplier=2, p=0.1):\n        return nn.Sequential(\n            ResNetBlock(in_features, in_features * multiplier, stride=2, p=p),\n            ResNetBlock(\n                in_features * multiplier,\n                in_features * multiplier,\n                stride=1,\n                p=p,\n            ),\n        )\n\n    def forward(self, x):\n        x = self.input(x)\n        x = self.layer_0(x)\n        x = self.layer_1(x)\n        x = self.layer_2(x)\n        x = self.layer_3(x)\n        return self.fc(x)\nfrom catalyst.dl import SupervisedRunner\n\nclass ClassificationRunner(SupervisedRunner):\n    def predict_batch(self, batch):\n        prediction = {\n            \"filepath\": batch[\"filepath\"],\n            \"log_probs\": self.model(batch[self.input_key].to(self.device))\n        }\n        return prediction\nmodel = MyResNet50()\n\n# model = BaselineModel()\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\nrunner = ClassificationRunner(input_key=\"features\", input_target_key=\"targets\")\nrunner.train(\n    model=model,\n    optimizer=optimizer,\n    criterion=criterion,\n    loaders=loaders,\n    logdir=Path(\"logs\") \/ datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n    num_epochs=10,\n    verbose=True,\n    load_best_on_end=True,\n    callbacks={\n        \"optimizer\": dl.OptimizerCallback(\n            metric_key=\"loss\", accumulation_steps=1, grad_clip_params=None,\n        ),\n        \"criterion\": dl.CriterionCallback(\n            input_key=\"targets\", output_key=\"logits\", prefix=\"loss\",\n        ),\n        \"accuracy\": dl.AccuracyCallback(num_classes=10),\n    },\n)\n\"\"\"\nThis code below will generate a submission.\nIt reads images from `test` folder and gathers prediction from the trained model.\nCheck your submission before uploading it into `Kaggle`.\n\"\"\"\nimport pandas as pd\nfrom PIL import Image\nfrom tqdm.notebook import tqdm\n\nsubmission = {\"Id\": [], \"Category\": []}\nmodel.eval()\n\ntest_dataset = create_dataset(dirs=f\"..\/input\/Imagenette-comp\/test\/\", extension=\"*.jpg\")\ntest_data = list({\"filepath\": filepath} for filepath in test_dataset[\"test\"])\n\ntest_open_fn = ReaderCompose(\n    [\n        ImageReader(\n            input_key=\"filepath\", output_key=\"features\", rootpath=\"\"\n        ),\n        ScalarReader(\n            input_key=\"filepath\",\n            output_key=\"filepath\",\n            default_value=\"\",\n            dtype=str,\n        ),\n    ]\n)\n\ntest_loader = utils.get_loader(\n    test_data,\n    open_fn=test_open_fn,\n    dict_transform=valid_data_transform,\n    batch_size=batch_size,\n    num_workers=num_workers,\n    shuffle=False,\n    sampler=None,\n    drop_last=False,\n)\n\nfor prediction in runner.predict_loader(loader=test_loader):\n    prediction[\"labels\"] = [class_names[c] for c in torch.max(prediction[\"log_probs\"], axis=1)[1]]\n    submission[\"Id\"].extend(f.split(\"\/\")[4].split(\".\")[0] for f in prediction[\"filepath\"])\n    submission[\"Category\"].extend(prediction[\"labels\"])\npd.DataFrame(submission).to_csv(\"baseline.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '82e98290828d26'}"}
{"id":"88162","text":"\"\"\"\n<img src=\"https:\/\/i.imgur.com\/RFR6UZX.jpg\" width=\"100%\"\/>\n\n# 2. The Dataset\n### [chaii - Hindi and Tamil Question Answering](https:\/\/www.kaggle.com\/c\/chaii-hindi-and-tamil-question-answering) - A quick overview for QA noobs\n\nHi and welcome! This is the second kernel of the series `chaii - Hindi and Tamil Question Answering - A quick overview for QA noobs`.\n\n**In this short kernel, we will go over the competition dataset very briefly and provide a transliteration table .**\n\n\n---\n\nThe entire series consists of the following notebooks:\n1. [The competition](https:\/\/www.kaggle.com\/julian3833\/1-the-competition-qa-for-qa-noobs)\n2. _[The dataset](https:\/\/www.kaggle.com\/julian3833\/2-the-dataset-qa-for-qa-noobs) (This notebook)_\n3. [The metric (Jaccard)](https:\/\/www.kaggle.com\/julian3833\/3-the-metric-jaccard-qa-for-qa-noobs) \n4. [Exploring Public Models](https:\/\/www.kaggle.com\/julian3833\/4-exploring-public-models-qa-for-qa-noobs\/)\n5. [\ud83e\udd47 XLM-Roberta + Torch's extra data [LB: 0.749]](https:\/\/www.kaggle.com\/julian3833\/5-xlm-roberta-torch-s-extra-data-lb-0-749)\n6. [\ud83e\udd17 Pre & post processing](https:\/\/www.kaggle.com\/julian3833\/6-pre-post-processing-qa-for-qa-noobs\/)\n\nThis is an ongoing project, so expect more notebooks to be added to the series soon. Actually, we are currently working on the following ones:\n* Exploring Public Models Revisited\n* Reviewing `squad2`, `mlqa` and others\n* About `xlm-roberta-large-squad2`\n* Own improvements\n\n---\n\"\"\"\nBASE_PATH = \"..\/input\/chaii-hindi-and-tamil-question-answering\/\"\n!ls -l $BASE_PATH\n\"\"\"\n# Small-data regime\n\nThe training dataset is tiny! It looks like the addition of datasets might be an important aspect of this competition as it goes by.\n\nRegarding the size of the test and submission: these are just placeholders, as explained in [this section](https:\/\/www.kaggle.com\/julian3833\/1-the-competition-qa-for-qa-noobs#Code-requirements) of the [first notebook](https:\/\/www.kaggle.com\/julian3833\/1-the-competition-qa-for-qa-noobs). It is a common practice in `Kernel-only` competitions like this one.\n\"\"\"\nimport pandas as pd\ndf_train = pd.read_csv(BASE_PATH + \"train.csv\")\ndf_test = pd.read_csv(BASE_PATH + \"test.csv\")\ndf_sub = pd.read_csv(BASE_PATH + \"sample_submission.csv\")\n\n# How many training and test samples have been provided?\nprint(f\"Training shape  : {df_train.shape}\")\nprint(f\"Test shape      : {df_test.shape}\")\nprint(f\"Submission shape: {df_sub.shape}\")\ndf_train.head()\n# This is the full df_test, not only the head\ndf_test\n# Same here\ndf_sub\n\"\"\"\n# Let's take a look at `df_train`\n\nIt has a `question` and a `context` (the inputs) and an `answer_text` (the output) plus the `answer_start` position indicator, which is a common practice as we mentioned in the [first notebook](https:\/\/www.kaggle.com\/julian3833\/1-the-competition-qa-for-qa-noobs#Question-Answering).\n\nNote that the submission only requires the `PredictionString` and not the position of it.\n\"\"\"\ndf_train.head()\n\"\"\"\nAs we explained in the first notebook, the answer is always a substring of the context:\n\"\"\"\nfor _, row in df_train.iterrows():\n    assert row.answer_text in row.context\n\"\"\"\n## Language percentages\n`67% hindi`, \n`33% tamil`\n\"\"\"\ndisplay(df_train['language'].value_counts())\nprint()\ndf_train['language'].value_counts(normalize=True).round(2)\ndf_train['language'].value_counts(normalize=True).round(2).plot.bar(alpha=0.5, rot=0, color=['red', 'green'], figsize=(10, 5));\n\"\"\"\n# Length of text columns (number of words)\n\n| Field | Average | Min | Max |\n| -- | -- | -- | -- |\n| question|  7 | 3 | 22| \n| answer|  7 | 1 | 51| \n| context|  1694 | 24 | 10259| \n\nThe context is huge! I don't know how good models work on this sequence length regime. We will see...\n\"\"\"\ndf_train['question'].str.split().str.len().hist(figsize=(10, 5), alpha=0.5)\npd.DataFrame(df_train['question'].str.split().str.len().describe().round(2)).T\ndf_train['answer_text'].str.split().str.len().hist(figsize=(10, 5), alpha=0.5)\npd.DataFrame(df_train['answer_text'].str.split().str.len().describe().round(2)).T\ndf_train['context'].str.split().str.len().hist(figsize=(10, 5), alpha=0.5)\npd.DataFrame(df_train['context'].str.split().str.len().describe().round(2)).T\n# You can uncomment this line to see the size of the largest context:\n# df_train.loc[df_train['context'].str.split().str.len() == 10259, 'context'].iloc[0]\n\"\"\"\n# Some quick and dirty transliterations\n\nI saw some beautiful EDAs with [wordclouds](https:\/\/www.kaggle.com\/hoshi7\/chaii-the-beginning-eda-wordclouds) in `Hindi` and `Tamil` and thought immediately: a transliteration could be something good to do.\n\n\n# What is transliteration?  `\u0905\u0915\u094d\u0924\u0942\u092c\u0930` -> `akt\u016bbr` (October)\n\nTransliteration is phonetically replacing one alphabet with another. It allows or improves phonetic readability and, sometimes, interpretability too.\n\nSee this example:\n\nThis is how you write `police` in Russian: `\u043f\u043e\u043b\u0438\u0446\u0438\u044f`.\n\nAnd this is how it looks when you transliterate Cyrillic to Latin: `politsiya`\n\nIt's still Russian, but much more familiar, isn't it?\nThe transliteration is a simple phonetic mapping from one alphabet to another. Here, the mapping was:\n```python\n{'\u043f': 'p', '\u043e': 'o', '\u043b': 'l', '\u0438': 't', '\u0446': 's', '\u0438': 'i', '\u044f': 'ya'}\n```\n\n\n# Origin of the tables\n\nI couldn't find well-established python packaged for that, at least fast. But I did find the following tables:\n\nFor Hindi:\n* https:\/\/pandey.github.io\/posts\/transliterate-devanagari-to-latin.html\n\nFor Tamil:\n* https:\/\/www.loc.gov\/catdir\/cpso\/romanization\/tamil.pdf\n\n\nNote that few characters are dropped (this is actually quick and dirty)\n\n\n# Usage\n\nThe usage is quite straightforward. See examples below for some good surprises!\n```python\ndf_trans = transliterate(df_train)\n```\n\"\"\"\nimport string\n\ndef transliterate_hindi(st):\n    HINDI_MAP = { '\u0950' : 'o\u1e41', '\u0900' : '\u1e41', '\u0901' : '\u1e43', '\u0902' : '\u1e43', '\u0903' : '\u1e25', '\u0905' : 'a', '\u0906' : '\u0101', '\u0907' : 'i', '\u0908' : '\u012b', '\u0909' : 'u', '\u090a' : '\u016b', '\u090b' : 'r\u0325', '\u0960' : ' r\u0325\u0304', '\u090c' : 'l\u0325', '\u0961' : ' l\u0325\u0304', '\u090d' : '\u00ea', '\u090e' : 'e', '\u090f' : 'e', '\u0910' : 'ai', '\u0911' : '\u00f4', '\u0912' : 'o', '\u0913' : 'o', '\u0914' : 'au', '\u093e' : '\u0101', '\u093f' : 'i', '\u0940' : '\u012b', '\u0941' : 'u', '\u0942' : '\u016b', '\u0943' : 'r\u0325', '\u0944' : ' r\u0325\u0304', '\u0962' : 'l\u0325', '\u0963' : ' l\u0325\u0304', '\u0945' : '\u00ea', '\u0947' : 'e', '\u0948' : 'ai', '\u0949' : '\u00f4', '\u094b' : 'o', '\u094c' : 'au', '\u0915\u093c' : 'q', '\u0915' : 'k', '\u0916\u093c' : 'x', '\u0916' : 'kh', '\u0917\u093c' : '\u0121', '\u0917' : 'g', '\u097b' : 'g', '\u0918' : 'gh', '\u0919' : '\u1e45', '\u091a' : 'c', '\u091b' : 'ch', '\u091c\u093c' : 'z', '\u091c' : 'j', '\u097c' : 'j', '\u091d' : 'jh', '\u091e' : '\u00f1', '\u091f' : '\u1e6d', '\u0920' : '\u1e6dh', '\u0921\u093c' : '\u1e5b', '\u0921' : '\u1e0d', '\u0978' : '\u1e0d', '\u097e' : 'd', '\u0922\u093c' : '\u1e5bh', '\u0922' : '\u1e0dh', '\u0923' : '\u1e47', '\u0924' : 't', '\u0925' : 'th', '\u0926' : 'd', '\u0927' : 'dh', '\u0928' : 'n', '\u092a' : 'p', '\u092b\u093c' : 'f', '\u092b' : 'ph', '\u092c' : 'b', '\u097f' : 'b', '\u092d' : 'bh', '\u092e' : 'm', '\u092f' : 'y', '\u0930' : 'r', '\u0932' : 'l', '\u0933' : '\u1e37', '\u0935' : 'v', '\u0936' : '\u015b', '\u0937' : '\u1e63', '\u0938' : 's', '\u0939' : 'h', '\u093d' : '\\'', '\u094d' : '', '\u093c' : '', '\u0966' : '0', '\u0967' : '1', '\u0968' : '2', '\u0969' : '3', '\u096a' : '4', '\u096b' : '5', '\u096c' : '6', '\u096d' : '7', '\u096e' : '8', '\u096f' : '9', '\ua8f3' : '\u1e41', '\u0964' : '.', '\u0965' : '..', ' ' : ' '}\n    return ''.join(HINDI_MAP.get(c, c)  for c in st)\n\ndef transliterate_tamil(st):\n    text = \"\"\"\u0b85 a \u0b8e e \u0b86 \u0101 \u0b8f \u0113 \u0b87 i \u0b90 ai \u0b88 \u012b \u0b92 o \u0b89 u \u0b93 \u014d \u0b8a \u016b \u0b94 au \u0b83 ka \u0bae ma \u0b95 ka \u0baf ya \u0b99 \u1e45a \u0bb0 ra \u0b9a ca \u0bb2 la \u0b9e \u00f1a \u0bb5 va \u0b9f \u1e6da \u0bb4 la \u0ba3 \u1e47a \u0bb3 \u1e37a \u0ba4 ta \u0bb1 ra\u0ba8 na \u0ba9 na \u0baa pa \u0b9c ja \u0bb8 sa \u0bb6 \u015ba \u0bb9 ha \u0bb7 \u1e63a\"\"\".split()\n    TAMIL_MAP = dict(zip(text[0::2], text[1::2]))\n    TAMIL_MAP.update({t: t for t in ' ?.1234567890'+string.ascii_lowercase})\n    return ''.join(TAMIL_MAP.get(c.lower(), '') for c in st)\n\ndef transliterate(df_in, columns=['question', 'context', 'answer_text']):\n    df = df_in.copy()\n    for c in columns:\n        df.loc[df['language'] == 'hindi', c] = df.loc[df['language'] == 'hindi', c].apply(transliterate_hindi)\n        df.loc[df['language'] == 'tamil', c] = df.loc[df['language'] == 'tamil', c].apply(transliterate_tamil)        \n    return df\ndf_trans = transliterate(df_train)\ndf_train.head(5)\ndf_trans.head(5)\ndf_train[df_train['language'] == 'hindi'].head(5)\ndf_trans[df_trans['language'] == 'hindi'].head(5)\n\"\"\"\nIt increases a little the readability. See for example:\n\"\"\"\n# This is a name. Adolph Meyr or something\ndf_trans[df_trans['language'] == 'hindi']['answer_text'].iloc[0]\ndf_train[df_train['language'] == 'hindi']['answer_text'].iloc[0]\n\"\"\"\nAnd this is a date (October 27, 1605):\n\"\"\"\ndf_train.iloc[1112]['answer_text']\ndf_trans.iloc[1112]['answer_text']\n\"\"\"\nI created a short notebook with the transliteration code so it's easy to copy-and-paste the code: [Quick and Dirty Transliteration Tables](https:\/\/www.kaggle.com\/julian3833\/quick-and-dirty-transliteration-tables).\n\n## What's next?\n\nEnough of the data! Let's check the `Jaccard metric` in the [next notebook](https:\/\/www.kaggle.com\/julian3833\/3-the-metric-jaccard-qa-for-qa-noobs) so we can move to the Public Models.\n\nIf you want to see more EDA, there are some incredible notebooks around. These are the ones I liked the most, but there are many more!\n* [EDA Chaii Gogogo \ud83d\ude05](https:\/\/www.kaggle.com\/vaby667\/eda-chaii-gogogo)\n* [chaii-explore_the_data](https:\/\/www.kaggle.com\/aakashnain\/chaii-explore-the-data)\n* [ChAii: The Beginning: EDA, Wordclouds](https:\/\/www.kaggle.com\/hoshi7\/chaii-the-beginning-eda-wordclouds)\n\n&nbsp;\n&nbsp;\n&nbsp;\n&nbsp;\n&nbsp;\n## Remember to upvote the notebook if you found it useful! \ud83e\udd17\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a1bca62a978bd4'}"}
{"id":"105028","text":"\"\"\"\n# import libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm.notebook import tqdm\nfrom dataclasses import make_dataclass\n\"\"\"\n# load data\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\n\"\"\"\n# make data class \n\"\"\"\n\"\"\"\n##### data class name : \"NewInfo\" \n##### variables : \"PassengerId\",\"Name\",\"Age\",\"Sex\" \n\"\"\"\nNewInfo = make_dataclass(\"NewInfo\",  \n                         [\n                             (\"PassengerId\", int), \n                             (\"Name\", str),\n                             (\"Age\",int),\n                             (\"Sex\",str)\n                         ]\n                        )\n\"\"\"\n# make new data list using make_dataclass\n\"\"\"\ndataList=[]\n\nfor i in tqdm(range(len(train))):\n    PassengerId=train.loc[i,'PassengerId']\n    Name=train.loc[i,'Name']\n    Age=train.loc[i,'Age']\n    Sex=train.loc[i,'Sex']\n\n    dataList += [NewInfo(PassengerId,Name,Age,Sex)]\n    \ndataList[:5]\n\"\"\"\n# data list => dataframe\n\"\"\"\nnew_df = pd.DataFrame(dataList)\nnew_df = new_df.set_index([\"PassengerId\"])\nnew_df.head()","meta":"{'source': 'AI4Code', 'id': 'c0f08e24975c9b'}"}
{"id":"60992","text":"\"\"\"\nTable of Contents\n\n- What Are NLP and spaCy?\n- Installation\n- How to Install spaCy\n- How to Download Models and Data\n- Using spaCy\n- How to Read a String\n- How to Read a Text File\n- Sentence Detection\n- Tokenization in spaCy\n- Stop Words\n- Lemmatization\n- Word Frequency\n- Part of Speech Tagging\n- Visualization: Using displaCy\n- Preprocessing Functions\n- Rule-Based Matching Using spaCy\n- Dependency Parsing Using spaCy\n- Navigating the Tree and Subtree\n- Shallow Parsing\n- Noun Phrase Detection\n- Verb Phrase Detection\n- Named Entity Recognition\n- Conclusion\n\"\"\"\n\"\"\"\nspaCy is a free and open-source library for Natural Language Processing (NLP) in Python with a lot of in-built capabilities. It\u2019s becoming increasingly popular for processing and analyzing data in NLP. Unstructured textual data is produced at a large scale, and it\u2019s important to process and derive insights from unstructured data. To do that, you need to represent the data in a format that can be understood by computers. NLP can help you do that.\n\nIn this tutorial, we\u2019ll learn:\n\n- What the foundational terms and concepts in NLP are\n- How to implement those concepts in spaCy\n- How to customize and extend built-in functionalities in spaCy\n- How to perform basic statistical analysis on a text\n- How to create a pipeline to process unstructured text\n- How to parse a sentence and extract meaningful insights from it\n\"\"\"\n\"\"\"\nWhat Are NLP and spaCy?\nNLP is a subfield of Artificial Intelligence and is concerned with interactions between computers and human languages. NLP is the process of analyzing, understanding, and deriving meaning from human languages for computers.\n\nNLP helps you extract insights from unstructured text and has several use cases, such as:\n\n- Automatic summarization\n- Named entity recognition\n- Question answering systems\n- Sentiment analysis\n\nspaCy is a free, open-source library for NLP in Python. It\u2019s written in Cython and is designed to build information extraction or natural language understanding systems. It\u2019s built for production use and provides a concise and user-friendly API.\n\"\"\"\n\"\"\"\n# Installation\nIn this section, you\u2019ll install spaCy and then download data and models for the English language.\n\n# How to Install spaCy\nspaCy can be installed using pip, a Python package manager. You can use a virtual environment to avoid depending on system-wide packages.\n\nCreate a new virtual environment:\n\"\"\"\n!pip install spacy\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n# Using spaCy\nIn this section, you\u2019ll use spaCy for a given input string and a text file. Load the language model instance in spaCy:\n\"\"\"\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\"\"\"\nHere, the nlp object is a language model instance. You can assume that, throughout this tutorial, nlp refers to the language model loaded by en_core_web_sm. Now you can use spaCy to read a string or a text file.\n\n# How to Read a String\nYou can use spaCy to create a processed Doc object, which is a container for accessing linguistic annotations, for a given input string:\n\"\"\"\nintroduction_text = ('This tutorial is about Natural'\\\n                     ' Language Processing in Spacy.')\nintroduction_doc = nlp(introduction_text)\n# Extract tokens for the given doc\nprint ([token.text for token in introduction_doc])\n\"\"\"\nIn the above example, notice how the text is converted to an object that is understood by spaCy. You can use this method to convert any text into a processed Doc object and deduce attributes, which will be covered in the coming sections.\n\n# How to Read a Text File\nIn this section, you\u2019ll create a processed Doc object for a text file:\n\"\"\"\n!echo \"This tutorial is about Natural Language Processing in Spacy.\" >> introduction.txt\nfile_name = 'introduction.txt'\nintroduction_file_text = open(file_name).read()\nintroduction_file_doc = nlp(introduction_file_text)\n# Extract tokens for the given doc\nprint ([token.text for token in introduction_file_doc])\n\"\"\"\nThis is how you can convert a text file into a processed Doc object.\n\nNote:\n\nYou can assume that:\n\n- Variable names ending with the suffix _text are Unicode string objects.\n- Variable name ending with the suffix _doc are spaCy\u2019s language model objects.\n\"\"\"\n\"\"\"\n# Sentence Detection\nSentence Detection is the process of locating the start and end of sentences in a given text. This allows you to you divide a text into linguistically meaningful units. You\u2019ll use these units when you\u2019re processing your text to perform tasks such as part of speech tagging and entity extraction.\n\nIn spaCy, the sents property is used to extract sentences. Here\u2019s how you would extract the total number of sentences and the sentences for a given input text\n\"\"\"\nabout_text = ('Syed Riaz is a Applied AI developer currently' \\\n              ' working for a Indian-based Anuncio' \\\n              ' Technologies. He is interested in exploring' \\\n              ' Natural Language Processing.')\nabout_doc = nlp(about_text)\nsentences = list(about_doc.sents)\nlen(sentences)\nfor sentence in sentences:\n    print (sentence)\n\"\"\"\nIn the above example, spaCy is correctly able to identify sentences in the English language, using a full stop(.) as the sentence delimiter. You can also customize the sentence detection to detect sentences on custom delimiters.\n\nHere\u2019s an example, where an ellipsis(...) is used as the delimiter\n\"\"\"\ndef set_custom_boundaries(doc):\n    # Adds support to use `...` as the delimiter for sentence detection\n    for token in doc[:-1]:\n        if token.text == '...':\n            doc[token.i+1].is_sent_start = True\n    return doc\n\nellipsis_text = ('Syed, can you, ... never mind, I forgot' \\\n                 ' what I was saying. So, do you think' \\\n                 ' we should ...')\n# Load a new model instance\ncustom_nlp = spacy.load('en_core_web_sm')\ncustom_nlp.add_pipe(set_custom_boundaries, before='parser')\ncustom_ellipsis_doc = custom_nlp(ellipsis_text)\ncustom_ellipsis_sentences = list(custom_ellipsis_doc.sents)\nfor sentence in custom_ellipsis_sentences:\n    print(sentence)\n# Sentence Detection with no customization\nellipsis_doc = nlp(ellipsis_text)\nellipsis_sentences = list(ellipsis_doc.sents)\nfor sentence in ellipsis_sentences:\n    print(sentence)\n\"\"\"\nNote that custom_ellipsis_sentences contain three sentences, whereas ellipsis_sentences contains two sentences. These sentences are still obtained via the sents attribute, as you saw before.\n\n# Tokenization in spaCy\nTokenization is the next step after sentence detection. It allows you to identify the basic units in your text. These basic units are called tokens. Tokenization is useful because it breaks a text into meaningful units. These units are used for further analysis, like part of speech tagging.\n\nIn spaCy, you can print tokens by iterating on the Doc object:\n\"\"\"\nfor token in about_doc:\n    print (token, token.idx)\n\"\"\"\nNote how spaCy preserves the starting index of the tokens. It\u2019s useful for in-place word replacement. spaCy provides various attributes for the Token class:\n\"\"\"\nfor token in about_doc:\n    print (token, token.idx, token.text_with_ws,\n           token.is_alpha, token.is_punct, token.is_space,\n           token.shape_, token.is_stop)\n\"\"\"\nIn this example, some of the commonly required attributes are accessed:\n\n- text_with_ws prints token text with trailing space (if present).\n- is_alpha detects if the token consists of alphabetic characters or not.\n- is_punct detects if the token is a punctuation symbol or not.\n- is_space detects if the token is a space or not.\n- shape_ prints out the shape of the word.\n- is_stop detects if the token is a stop word or not.\n\nNote: You\u2019ll learn more about stop words in the next section.\n\nYou can also customize the tokenization process to detect tokens on custom characters. This is often used for hyphenated words, which are words joined with hyphen. For example, \u201cIndian-based\u201d is a hyphenated word.\n\nspaCy allows you to customize tokenization by updating the tokenizer property on the nlp object:\n\"\"\"\nimport re\nimport spacy\nfrom spacy.tokenizer import Tokenizer\ncustom_nlp = spacy.load('en_core_web_sm')\nprefix_re = spacy.util.compile_prefix_regex(custom_nlp.Defaults.prefixes)\nsuffix_re = spacy.util.compile_suffix_regex(custom_nlp.Defaults.suffixes)\ninfix_re = re.compile(r'''[-~]''')\ndef customize_tokenizer(nlp):\n    # Adds support to use `-` as the delimiter for tokenization\n    return Tokenizer(nlp.vocab, prefix_search=prefix_re.search,\n                     suffix_search=suffix_re.search,\n                     infix_finditer=infix_re.finditer,\n                     token_match=None\n                    )\n\ncustom_nlp.tokenizer = customize_tokenizer(custom_nlp)\ncustom_tokenizer_about_doc = custom_nlp(about_text)\nprint([token.text for token in custom_tokenizer_about_doc])\n\"\"\"\nIn order for you to customize, you can pass various parameters to the Tokenizer class:\n\n- nlp.vocab is a storage container for special cases and is used to handle cases like contractions and emoticons.\n- prefix_search is the function that is used to handle preceding punctuation, such as opening parentheses.\n- infix_finditer is the function that is used to handle non-whitespace separators, such as hyphens.\n- suffix_search is the function that is used to handle succeeding punctuation, such as closing parentheses.\n- token_match is an optional boolean function that is used to match strings that should never be split. It overrides the previous rules and is useful for entities like URLs or numbers.\n\nNote: spaCy already detects hyphenated words as individual tokens. The above code is just an example to show how tokenization can be customized. It can be used for any other character.\n\n# Stop Words\nStop words are the most common words in a language. In the English language, some examples of stop words are the, are, but, and they. Most sentences need to contain stop words in order to be full sentences that make sense.\n\nGenerally, stop words are removed because they aren\u2019t significant and distort the word frequency analysis. spaCy has a list of stop words for the English language\n\"\"\"\nimport spacy\nspacy_stopwords = spacy.lang.en.stop_words.STOP_WORDS\nlen(spacy_stopwords)\nfor stop_word in list(spacy_stopwords)[:10]:\n    print(stop_word)\n\"\"\"\nYou can remove stop words from the input text:\n\"\"\"\nfor token in about_doc:\n    if not token.is_stop:\n        print (token)\n\"\"\"\nStop words like is, a, for, the, and in are not printed in the output above. You can also create a list of tokens not containing stop words:\n\"\"\"\nabout_no_stopword_doc = [token for token in about_doc if not token.is_stop]\nprint (about_no_stopword_doc)\n\"\"\"\nabout_no_stopword_doc can be joined with spaces to form a sentence with no stop words.\n\n# Lemmatization\nLemmatization is the process of reducing inflected forms of a word while still ensuring that the reduced form belongs to the language. This reduced form or root word is called a lemma.\n\nFor example, organizes, organized and organizing are all forms of organize. Here, organize is the lemma. The inflection of a word allows you to express different grammatical categories like tense (organized vs organize), number (trains vs train), and so on. Lemmatization is necessary because it helps you reduce the inflected forms of a word so that they can be analyzed as a single item. It can also help you normalize the text.\n\nspaCy has the attribute lemma_ on the Token class. This attribute has the lemmatized form of a token:\n\"\"\"\nconference_help_text = ('Syed Riaz is helping organize a developer'\n                        ' conference on Applications of Natural Language'\n                        ' Processing. He keeps organizing local AI meetups'\n                        ' and several internal talks at his workplace.')\nconference_help_doc = nlp(conference_help_text)\nfor token in conference_help_doc:\n    print (token, token.lemma_)\n\"\"\"\nIn this example, organizing reduces to its lemma form organize. If you do not lemmatize the text, then organize and organizing will be counted as different tokens, even though they both have a similar meaning. Lemmatization helps you avoid duplicate words that have similar meanings.\n\n# Word Frequency\nYou can now convert a given text into tokens and perform statistical analysis over it. This analysis can give you various insights about word patterns, such as common words or unique words in the text:\n\"\"\"\nfrom collections import Counter\ncomplete_text = ('Syed Riaz is a Applied AI research engineer currently'\n                 'working for a Bangalore-based Anuncio Technologies. He is'\n                 ' interested in exploring Natural Language Processing.'\n                 ' There is a developer conference happening on 13 March'\n                 ' 2020 in Bangalore. It is titled \"Applications of Natural'\n                 ' Language Processing\". There is a helpline number '\n                 ' available at +1-1234567891. Syed is helping organize it.'\n                 ' He keeps organizing local AI meetups and several'\n                 ' internal talks at his workplace. Syed is also presenting'\n                 ' a talk. The talk will introduce the reader about \"Use'\n                 ' cases of Natural Language Processing in AI industry\".'\n                 ' Apart from his work, he is very passionate about travelling.'\n                 ' Syed would like to see whole world. He has planned '\n                 ' to travel different countries one at a time.'\n                 ' He is also planning to create travel videos'\n                 ' for which he is planning to join a film making course.')\n\ncomplete_doc = nlp(complete_text)\n# Remove stop words and punctuation symbols\nwords = [token.text for token in complete_doc\n         if not token.is_stop and not token.is_punct]\n\nword_freq = Counter(words)\n\n# 5 commonly occurring words with their frequencies\ncommon_words = word_freq.most_common(5)\nprint (common_words)\n# Unique words\nunique_words = [word for (word, freq) in word_freq.items() if freq == 1]\nprint (unique_words)\n\"\"\"\nBy looking at the common words, you can see that the text as a whole is probably about Syed, Bangalore, or Natural Language Processing. This way, you can take any unstructured text and perform statistical analysis to know what it\u2019s about.\n\nHere\u2019s another example of the same text with stop words\n\"\"\"\nwords_all = [token.text for token in complete_doc if not token.is_punct]\nword_freq_all = Counter(words_all)\n# 5 commonly occurring words with their frequencies\ncommon_words_all = word_freq_all.most_common(5)\nprint (common_words_all)\n\"\"\"\nFour out of five of the most common words are stop words, which don\u2019t tell you much about the text. If you consider stop words while doing word frequency analysis, then you won\u2019t be able to derive meaningful insights from the input text. This is why removing stop words is so important.\n\n# Part of Speech Tagging\nPart of speech or POS is a grammatical role that explains how a particular word is used in a sentence. There are eight parts of speech:\n\n1. Noun\n2. Pronoun\n3. Adjective\n4. Verb\n5. Adverb\n6. Preposition\n7. Conjunction\n8. Interjection\n\nPart of speech tagging is the process of assigning a POS tag to each token depending on its usage in the sentence. POS tags are useful for assigning a syntactic category like noun or verb to each word.\n\nIn spaCy, POS tags are available as an attribute on the Token object:\n\"\"\"\nfor token in about_doc:\n    print (token, token.tag_, token.pos_, spacy.explain(token.tag_))\n\"\"\"\nHere, two attributes of the Token class are accessed:\n\n- tag_ lists the fine-grained part of speech.\n- pos_ lists the coarse-grained part of speech.\n\nspacy.explain gives descriptive details about a particular POS tag. spaCy provides a [complete tag list](https:\/\/spacy.io\/api\/annotation#pos-tagging) along with an explanation for each tag.\n\nUsing POS tags, you can extract a particular category of words\n\"\"\"\nnouns = []\nadjectives = []\nfor token in about_doc:\n    if token.pos_ == 'NOUN':\n        nouns.append(token)\n    if token.pos_ == 'ADJ':\n        adjectives.append(token)\n\nprint(nouns)\nprint(adjectives)\n\"\"\"\nYou can use this to derive insights, remove the most common nouns, or see which adjectives are used for a particular noun.\n\n# Visualization: Using displaCy\nspaCy comes with a built-in visualizer called displaCy. You can use it to visualize a dependency parse or named entities in a browser or a Jupyter notebook.\n\nYou can use displaCy to find POS tags for tokens:\n\"\"\"\nfrom spacy import displacy\nabout_interest_text = ('He is interested in learning'\n                       ' Natural Language Processing.')\nabout_interest_doc = nlp(about_interest_text)\ndisplacy.render(about_interest_doc, style='dep', jupyter=True)\n\n\"\"\"\n# Preprocessing Functions\nYou can create a preprocessing function that takes text as input and applies the following operations:\n\n- Lowercases the text\n- Lemmatizes each token\n- Removes punctuation symbols\n- Removes stop words\n\nA preprocessing function converts text to an analyzable format. It\u2019s necessary for most NLP tasks. Here\u2019s an example\n\"\"\"\ndef is_token_allowed(token):\n    '''\n    Only allow valid tokens which are not stop words\n    and punctuation symbols.\n    '''\n    if (not token or not token.string.strip() or\n        token.is_stop or token.is_punct):\n        return False\n    return True\n\ndef preprocess_token(token):\n    # Reduce token to its lowercase lemma form\n    return token.lemma_.strip().lower()\n\ncomplete_filtered_tokens = [preprocess_token(token)\n                            for token in complete_doc if is_token_allowed(token)]\nprint(complete_filtered_tokens)\n\"\"\"\nNote that the complete_filtered_tokens does not contain any stop word or punctuation symbols and consists of lemmatized lowercase tokens.\n\n# Rule-Based Matching Using spaCy\nRule-based matching is one of the steps in extracting information from unstructured text. It\u2019s used to identify and extract tokens and phrases according to patterns (such as lowercase) and grammatical features (such as part of speech).\n\nRule-based matching can use [regular expressions](https:\/\/en.wikipedia.org\/wiki\/Regular_expression) to extract entities (such as phone numbers) from an unstructured text. It\u2019s different from extracting text using regular expressions only in the sense that regular expressions don\u2019t consider the lexical and grammatical attributes of the text.\n\nWith rule-based matching, you can extract a first name and a last name, which are always proper nouns\n\"\"\"\nfrom spacy.matcher import Matcher\nmatcher = Matcher(nlp.vocab)\n\ndef extract_full_name(nlp_doc):\n    pattern = [{'POS': 'PROPN'}, {'POS': 'PROPN'}]\n    matcher.add('FULL_NAME', None, pattern)\n    matches = matcher(nlp_doc)\n    for match_id, start, end in matches:\n        span = nlp_doc[start:end]\n        return span.text\n\nextract_full_name(about_doc)\n\"\"\"\nIn this example, pattern is a list of objects that defines the combination of tokens to be matched. Both POS tags in it are PROPN (proper noun). So, the pattern consists of two objects in which the POS tags for both tokens should be PROPN. This pattern is then added to Matcher using FULL_NAME and the the match_id. Finally, matches are obtained with their starting and end indexes.\n\nYou can also use rule-based matching to extract phone numbers:\n\"\"\"\nfrom spacy.matcher import Matcher\n\nmatcher = Matcher(nlp.vocab)\n\nconference_org_text = ('There is a developer conference'\n                       'happening on 13 March 2020 in Bangalore. It is titled'\n                       ' \"Applications of Natural Language Processing\".'\n                       ' There is a helpline number available'\n                       ' at (123) 456-789')\n\ndef extract_phone_number(nlp_doc):\n    pattern = [{'ORTH': '('}, {'SHAPE': 'ddd'},\n               {'ORTH': ')'}, {'SHAPE': 'ddd'},\n               {'ORTH': '-', 'OP': '?'},\n               {'SHAPE': 'ddd'}]\n    matcher.add('PHONE_NUMBER', None, pattern)\n    matches = matcher(nlp_doc)\n    for match_id, start, end in matches:\n        span = nlp_doc[start:end]\n        return span.text\n\nconference_org_doc = nlp(conference_org_text)\nextract_phone_number(conference_org_doc)\n\"\"\"\nIn this example, only the pattern is updated in order to match phone numbers from the previous example. Here, some attributes of the token are also used:\n\n- ORTH gives the exact text of the token.\n- SHAPE transforms the token string to show orthographic features.\n- OP defines operators. Using ? as a value means that the pattern is optional, meaning it can match 0 or 1 times.\n\n**Note**: For simplicity, phone numbers are assumed to be of a particular format: (123) 456-789. You can change this depending on your use case.\n\nRule-based matching helps you identify and extract tokens and phrases according to lexical patterns (such as lowercase) and grammatical features(such as part of speech).\n\n# Dependency Parsing Using spaCy\nDependency parsing is the process of extracting the dependency parse of a sentence to represent its grammatical structure. It defines the dependency relationship between headwords and their dependents. The head of a sentence has no dependency and is called the root of the sentence. The verb is usually the head of the sentence. All other words are linked to the headword.\n\nThe dependencies can be mapped in a directed graph representation:\n\n- Words are the nodes.\n- The grammatical relationships are the edges.\n\nDependency parsing helps you know what role a word plays in the text and how different words relate to each other. It\u2019s also used in shallow parsing and named entity recognition.\n\nHere\u2019s how you can use dependency parsing to see the relationships between words\n\"\"\"\ntravel_text = 'Syed is planning to travel planet earth.'\ntravel_doc = nlp(travel_text)\nfor token in travel_doc:\n    print (token.text, token.tag_, token.head.text, token.dep_)\n\"\"\"\nIn this example, the sentence contains three relationships:\n\n1. nsubj is the subject of the word. Its headword is a verb.\n2. aux is an auxiliary word. Its headword is a verb.\n3. dobj is the direct object of the verb. Its headword is a verb.\n\nThere is a detailed [list of relationships](https:\/\/nlp.stanford.edu\/software\/dependencies_manual.pdf) with descriptions. You can use displaCy to visualize the dependency tree:\n\"\"\"\n#displacy.serve(travel_doc, style='dep')\ndisplacy.render(travel_doc, style='dep', jupyter=True)\n\"\"\"\n# Navigating the Tree and Subtree\nThe dependency parse tree has all the properties of a [tree](https:\/\/en.wikipedia.org\/wiki\/Tree_(data_structure)). This tree contains information about sentence structure and grammar and can be traversed in different ways to extract relationships.\n\nspaCy provides attributes like children, lefts, rights, and subtree to navigate the parse tree:\n\"\"\"\none_line_about_text = ('Syed Riaz is a Applied AI research engineer'\n                       ' currently working for a Bangalore-based Anuncio Technologies')\n\none_line_about_doc = nlp(one_line_about_text)\n# Extract children of `engineer`\nprint([token.text for token in one_line_about_doc[7].children])\n# Extract previous neighboring node of `engineer`\nprint (one_line_about_doc[7].nbor(-1))\n# Extract next neighboring node of `engineer`\nprint (one_line_about_doc[7].nbor())\n# Extract all tokens on the left of `engineer`\nprint([token.text for token in one_line_about_doc[7].lefts])\n# Extract tokens on the right of `engineer`\nprint([token.text for token in one_line_about_doc[7].rights])\n# Print subtree of `engineer`\nprint (list(one_line_about_doc[7].subtree))\n\"\"\"\nYou can construct a function that takes a subtree as an argument and returns a string by merging words in it:\n\"\"\"\ndef flatten_tree(tree):\n    return ''.join([token.text_with_ws for token in list(tree)]).strip()\n\n# Print flattened subtree of `engineer`\nprint (flatten_tree(one_line_about_doc[7].subtree))\n\"\"\"\nYou can use this function to print all the tokens in a subtree.\n\n# Shallow Parsing\nShallow parsing, or chunking, is the process of extracting phrases from unstructured text. Chunking groups adjacent tokens into phrases on the basis of their POS tags. There are some standard well-known chunks such as noun phrases, verb phrases, and prepositional phrases.\n\n# Noun Phrase Detection\nA noun phrase is a phrase that has a noun as its head. It could also include other kinds of words, such as adjectives, ordinals, determiners. Noun phrases are useful for explaining the context of the sentence. They help you infer what is being talked about in the sentence.\n\nspaCy has the property noun_chunks on Doc object. You can use it to extract noun phrases\n\"\"\"\nconference_text = ('There is a AI developer conference'\n                   ' happening on 13 March 2020 in Bangalore.')\nconference_doc = nlp(conference_text)\n# Extract Noun Phrases\nfor chunk in conference_doc.noun_chunks:\n    print (chunk)\n\"\"\"\nBy looking at noun phrases, you can get information about your text. For example, a AI developer conference indicates that the text mentions a conference, while the date 13 Marchlets you know that conference is scheduled for 13 March. You can figure out whether the conference is in the past or the future. Bangalore tells you that the conference is in Bangalore.\n\"\"\"\n\"\"\"\n# Verb Phrase Detection\nA verb phrase is a syntactic unit composed of at least one verb. This verb can be followed by other chunks, such as noun phrases. Verb phrases are useful for understanding the actions that nouns are involved in.\n\nspaCy has no built-in functionality to extract verb phrases, so you\u2019ll need a library called textacy:\n\nNote:\n\nYou can use pip to install textacy:\n\"\"\"\n!pip install textacy\n\"\"\"\nNow that you have textacy installed, you can use it to extract verb phrases based on grammar rules\n\"\"\"\nimport textacy\nabout_talk_text = ('The talk will introduce reader about Use'\n                   ' cases of Natural Language Processing in'\n                   ' AI industry')\npattern = r'(<VERB>?<ADV>*<VERB>+)'\nabout_talk_doc = textacy.make_spacy_doc(about_talk_text,\n                                        lang='en_core_web_sm')\nverb_phrases = textacy.extract.pos_regex_matches(about_talk_doc, pattern)\n# Print all Verb Phrase\nfor chunk in verb_phrases:\n    print(chunk.text)\n# Extract Noun Phrase to explain what nouns are involved\nfor chunk in about_talk_doc.noun_chunks:\n    print (chunk)\n\"\"\"\nIn this example, the verb phrase introduce indicates that something will be introduced. By looking at noun phrases, you can see that there is a talk that will introduce the reader to use cases of Natural Language Processing or AI industry.\n\nNote: In the previous example, you could have also done dependency parsing to see what the [relationships](https:\/\/nlp.stanford.edu\/software\/dependencies_manual.pdf) between the words were.\n\"\"\"\n\"\"\"\n# Named Entity Recognition\nNamed Entity Recognition (NER) is the process of locating named entities in unstructured text and then classifying them into pre-defined categories, such as person names, organizations, locations, monetary values, percentages, time expressions, and so on.\n\nYou can use NER to know more about the meaning of your text. For example, you could use it to populate tags for a set of documents in order to improve the keyword search. You could also use it to categorize customer support tickets into relevant categories.\n\nspaCy has the property ents on Doc objects. You can use it to extract named entities\n\"\"\"\nanuncio_class_text = ('Anuncio Technologies is situated'\n                      ' near Manyatha Tech Park or the City of Bangalore and has'\n                      ' world-class AI developers.')\nanuncio_class_doc = nlp(anuncio_class_text)\nfor ent in anuncio_class_doc.ents:\n    print(ent.text, ent.start_char, ent.end_char,\n          ent.label_, spacy.explain(ent.label_))\n\"\"\"\nIn the above example, ent is a Span object with various attributes:\n\n- text gives the Unicode text representation of the entity.\n- start_char denotes the character offset for the start of the entity.\n- end_char denotes the character offset for the end of the entity.\n\nlabel_ gives the label of the entity.\nspacy.explain gives descriptive details about an entity label. The spaCy model has a pre-trained [list of entity classe](https:\/\/spacy.io\/api\/annotation#named-entities)s. You can use displaCy to visualize these entities\n\"\"\"\n#displacy.serve(anuncio_class_doc, style='ent')\ndisplacy.render(anuncio_class_doc, style='dep', jupyter=True)\n\"\"\"\nYou can use NER to redact people\u2019s names from a text. For example, you might want to do this in order to hide personal information collected in a survey. You can use spaCy to do that\n\"\"\"\nsurvey_text = ('Out of 5 people surveyed, Syed Riaz,'\n               ' Satyadev Shetty and Praveen Kumar like'\n               ' apples. Gourav Sinha and Vikrant Dharmshi'\n               ' like oranges.')\n\ndef replace_person_names(token):\n    if token.ent_iob != 0 and token.ent_type_ == 'PERSON':\n        return '[REDACTED] '\n    return token.string\n\ndef redact_names(nlp_doc):\n    for ent in nlp_doc.ents:\n        ent.merge()\n        tokens = map(replace_person_names, nlp_doc)\n        return ''.join(tokens)\n\nsurvey_doc = nlp(survey_text)\nredact_names(survey_doc)\n\"\"\"\nIn this example, replace_person_names() uses ent_iob. It gives the IOB code of the named entity tag using [inside-outside-beginning (IOB) tagging](https:\/\/en.wikipedia.org\/wiki\/Inside%E2%80%93outside%E2%80%93beginning_(tagging)). Here, it can assume a value other than zero, because zero means that no entity tag is set.\n\n# Conclusion\nspaCy is a powerful and advanced library that is gaining huge popularity for NLP applications due to its speed, ease of use, accuracy, and extensibility. Congratulations! You now know:\n\n- What the foundational terms and concepts in NLP are\n- How to implement those concepts in spaCy\n- How to customize and extend built-in functionalities in spaCy\n- How to perform basic statistical analysis on a text\n- How to create a pipeline to process unstructured text\n- How to parse a sentence and extract meaningful insights from it\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '707c93c9ade483'}"}
{"id":"18423","text":"import numpy as np \nimport pandas as pd \nimport sklearn\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\n%matplotlib inline\n\n\n# Ignore useless warnings\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\n!ls ..\/input\/\n\"\"\"\n# Get the Data\n\"\"\"\ntrain = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\ntest = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\n\ntrain.shape, test.shape\ntrain.info()\ntrain.head()\ntrain = train.drop(\"Id\", axis=1)\nplt.figure(figsize=(9,8))\nsns.distplot(train['SalePrice'], color='g', bins=100);\nlist(set(train.dtypes.tolist()))\ntrain_num = train.select_dtypes(include = ['float64', 'int64'])\ntrain_cat = train.select_dtypes(include = ['O'])\n\"\"\"\n# **Numerics Features - Univariate Distribution, Missing Values, and Correlations**\n\"\"\"\n#univariate distributions\nnum_dist = train_num.describe(percentiles=[0.01,0.05,0.10,0.25,0.50,0.75,0.90,0.95,0.99]).T\nnum_dist = num_dist.rename(columns={\"count\": \"non-missing count\"})\n\n#missing values\nmissing_ = train_num.isnull().sum().to_frame(name = \"missing count\")\nmissing_[\"missing pct\"] = missing_[\"missing count\"] \/ len(train)\n\n#correlations\ncorr_matrix = train_num.corr()\ncorr_matrix[\"abs SalePrice Corr\"] = abs(corr_matrix[\"SalePrice\"])\ncorr_ = corr_matrix[[\"SalePrice\",\"abs SalePrice Corr\"]]\ncorr_ = corr_.rename(columns={\"SalePrice\": \"SalePrice Corr\"})\n\n#Concatenate\nnum_dist = pd.concat([corr_, missing_, num_dist], \n                     axis=1).sort_values(by='abs SalePrice Corr', ascending=False)\n\nnum_dist.style.format({'missing pct':\"{:.2%}\",\n                       'mean':\"{:.1f}\",\n                       'std':\"{:.1f}\",\n                       '5%':\"{:.1f}\",\n                       '10%':\"{:.1f}\",\n                       '25%':\"{:.1f}\",\n                       '50%':\"{:.1f}\",\n                       '75%':\"{:.1f}\",\n                       '90%':\"{:.1f}\",\n                       '95%':\"{:.1f}\",\n                       '99%':\"{:.1f}\",\n                       'min':\"{:.1f}\",\n                       'max':\"{:.1f}\",\n                       'SalePrice Corr':\"{:.2f}\",\n                       'abs SalePrice Corr':\"{:.2f}\",\n                       'missing count':\"{:.0f}\",\n                       'non-missing count':\"{:.0f}\"\n                      })\n\nmissing_[missing_[\"missing pct\"] > 0].sort_values(by=\"missing pct\",ascending=False)\nnum_dist[num_dist[\"abs SalePrice Corr\"] > 0.5]\nhighCorr = num_dist[num_dist[\"abs SalePrice Corr\"] > 0.5].T\ncols = list(highCorr.columns)\n\nsns.pairplot(train_num[cols], height = 3, corner=True)\nplt.show();\nfor i in range(0, len(train_num.columns),5):\n    sns.pairplot(data=train_num,\n                x_vars=train_num.columns[i:i+5],\n                y_vars=['SalePrice']\n                )\n\"\"\"\n# Categorical Features - Univariate Analysis & Data Quality\n\"\"\"\ncat = list(train.select_dtypes(include = ['O']).columns)\n\ndef bp(x, y, **kwargs):\n    sns.boxplot(x=x, y=y)\n    x=plt.xticks(rotation=90)\n    \nf = pd.melt(train, id_vars=['SalePrice'], value_vars=cat)\ng = sns.FacetGrid(f, col=\"variable\",  col_wrap=3, sharex=False, sharey=False, size=5)\ng = g.map(bp, \"value\", \"SalePrice\")\n\ntrain_cat = train.select_dtypes(include = ['O'])\n\nmissing_cat = train_cat.isna().sum().to_frame(name = \"missing count\")\nmissing_cat[\"missing pct\"] = missing_cat[\"missing count\"] \/ len(train)\n\nmissing_cat[missing_cat[\"missing pct\"] > 0].sort_values(by=\"missing pct\",ascending=False)\n\"\"\"\n# Data Cleansing\n\"\"\"\ntrain[\"PoolQC\"] = train[\"PoolQC\"].fillna(\"None\")\ntrain[\"MiscFeature\"] = train[\"MiscFeature\"].fillna(\"None\")\ntrain[\"Alley\"] = train[\"Alley\"].fillna(\"None\")\ntrain[\"Fence\"] = train[\"Fence\"].fillna(\"None\")\ntrain[\"FireplaceQu\"] = train[\"FireplaceQu\"].fillna(\"None\")\n\ntrain[\"LotFrontage\"] = train.groupby(\"Neighborhood\")[\"LotFrontage\"].transform(lambda x: x.fillna(x.median()))\n\nfor col in ('GarageType', 'GarageFinish', 'GarageQual', 'GarageCond'):\n    train[col] = train[col].fillna('None')\nfor col in ('GarageYrBlt', 'GarageArea', 'GarageCars'):\n    train[col] = train[col].fillna(0)\n\nfor col in ('BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath'):\n    train[col] = train[col].fillna(0)\nfor col in ('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'):\n    train[col] = train[col].fillna('None')\n      \ntrain[\"MasVnrType\"] = train[\"MasVnrType\"].fillna(\"None\")\ntrain[\"MasVnrArea\"] = train[\"MasVnrArea\"].fillna(0)\n\ntrain['MSZoning'] = train['MSZoning'].fillna(train['MSZoning'].mode()[0])\n\ntrain[\"Functional\"] = train[\"Functional\"].fillna(\"Typ\")\ntrain['Electrical'] = train['Electrical'].fillna(train['Electrical'].mode()[0])\ntrain['KitchenQual'] = train['KitchenQual'].fillna(train['KitchenQual'].mode()[0])\ntrain['Exterior1st'] = train['Exterior1st'].fillna(train['Exterior1st'].mode()[0])\ntrain['Exterior2nd'] = train['Exterior2nd'].fillna(train['Exterior2nd'].mode()[0])\ntrain['SaleType'] = train['SaleType'].fillna(train['SaleType'].mode()[0])\ntrain['MSSubClass'] = train['MSSubClass'].fillna(\"None\")\n\n\"\"\"\n# Tranform Categorical Variables into dummy variables \n\"\"\"\ncat_col = list(train.select_dtypes(include = ['O']).columns)\ntrain = pd.get_dummies(train, columns = cat_col)\n\"\"\"\n# Regression\n\"\"\"\ntrain_X = train.drop(\"SalePrice\", axis=1) # drop labels for training set\ntrain_Y = train[\"SalePrice\"].copy()\nfrom sklearn.linear_model import LinearRegression\n\nlin_reg = LinearRegression()\nlin_reg.fit(train_X, train_Y)\n\nfrom sklearn.metrics import mean_squared_error\n\nhomevalue_predictions = lin_reg.predict(train_X)\nlin_mse = mean_squared_error(train_Y, homevalue_predictions)\nlin_rmse = np.sqrt(lin_mse)\n\nfrom sklearn.metrics import mean_absolute_error\nlin_mae = mean_absolute_error(train_Y, homevalue_predictions)\n\nlin_rmse, lin_mae\nfrom sklearn.model_selection import cross_val_score\n\nscores = cross_val_score(lin_reg, train_X, train_Y, scoring=\"neg_mean_squared_error\", cv=10)\npd.Series(np.sqrt(-scores)).describe()\n\"\"\"\n# Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\n\nforest_reg = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(train_X, train_Y)\n\nhomevalue_predictions = forest_reg.predict(train_X)\nforest_mse = mean_squared_error(train_Y, homevalue_predictions)\nforest_rmse = np.sqrt(forest_mse)\nforest_rmse\nfrom sklearn.model_selection import cross_val_score\n\nforest_scores = cross_val_score(forest_reg, train_X, train_Y,\n                                scoring=\"neg_mean_squared_error\", cv=10)\nforest_rmse_scores = np.sqrt(-forest_scores)\ndisplay_scores(forest_rmse_scores)\n\"\"\"\n# Support Vector Regression\n\"\"\"\nfrom sklearn.svm import SVR\n\nsvm_reg = SVR(kernel=\"linear\")\nsvm_reg.fit(train_X, train_Y)\nhomevalue_predictions = svm_reg.predict(train_X)\nsvm_mse = mean_squared_error(train_Y, homevalue_predictions)\nsvm_rmse = np.sqrt(svm_mse)\nsvm_rmse\n\"\"\"\n# Fine Tune Model - Grid Search\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = [\n    # try 12 (3\u00d74) combinations of hyperparameters\n    {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},\n    # then try 6 (2\u00d73) combinations with bootstrap set as False\n    {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},\n  ]\n\nforest_reg = RandomForestRegressor(random_state=42)\n# train across 5 folds, that's a total of (12+6)*5=90 rounds of training \ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n                           scoring='neg_mean_squared_error',\n                           return_train_score=True)\ngrid_search.fit(train_X, train_Y)\ngrid_search.best_params_\ngrid_search.best_estimator_\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n    print(np.sqrt(-mean_score), params)\n\"\"\"\n# To be Continued...\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '21ac299d2c5fce'}"}
{"id":"104016","text":"\"\"\"\n# Proyecto 1 Computaci\u00f3n Emergente\nIntegrantes:\n- Samuel Mari\u00f1a\n- Mar\u00eda G. Cafarelli\n\"\"\"\n\"\"\"\n## Carga de paquetes\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch.utils.data import Dataset,DataLoader\nfrom torchvision import transforms\nfrom torch import optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport time\nfrom time import process_time\n\"\"\"\n## Definici\u00f3n de Variables\n\"\"\"\nbatch_size = 300\nepochs = 30\ntest_size = 0.15\nlearning_rate = 0.0001\n\"\"\"\n## Carga de Data (Training Set)\n\"\"\"\n# Im\u00e1genes y labels de entrenamiento (Training Set)\ntrain_images = np.load(\"..\/input\/kuzushiji\/kmnist-train-imgs.npz\")[\"arr_0\"]\ntrain_labels = np.load(\"..\/input\/kuzushiji\/kmnist-train-labels.npz\")[\"arr_0\"]\n\"\"\"\n## Separaci\u00f3n de Datos\n\"\"\"\nprint(\"Tama\u00f1o Set de Entrenamiento antes:\" ,train_images.shape)\n\ntrain_images, test_images, train_labels, test_labels = train_test_split(train_images, train_labels, test_size = test_size)\n# #Imprimimos para confirmar\nprint(\"Tama\u00f1o Set de Entrenamiento despu\u00e9s: \", train_images.shape)\nprint(\"Tama\u00f1o Set de Validacion: \", test_images.shape)\n\"\"\"\n## Normalizaci\u00f3n de Datos\n\"\"\"\ndef normalizar(dataset, labels):\n    data = dataset.astype('float32')\n    data \/= 255\n    data = np.reshape(data, (len(data), 1, 28, 28))\n    newLabels = labels.astype('int64')\n    return data, newLabels\ntrain_images, train_labels = normalizar(train_images, train_labels)\ntest_images, test_labels = normalizar(test_images, test_labels)\n\"\"\"\n## Conversi\u00f3n a Tensores\n\"\"\"\nx_train_images = torch.Tensor(train_images)\ny_train_images = torch.Tensor(train_labels).type(torch.LongTensor)\nx_valid_images = torch.Tensor(test_images)\ny_valid_images = torch.Tensor(test_labels).type(torch.LongTensor)\n\nprint(\"Set de Entrenamiento: \" + str(x_train_images.shape))\nprint(\"Labels del Set de Entrenamiento: \" + str(y_train_images.shape))\nprint(\"Set de Validaci\u00f3n: \" + str(x_valid_images.shape))\nprint(\"Labels del Set de Validaci\u00f3n: \" + str(y_valid_images.shape))\n\"\"\"\n## Agregar Device si se tiene GPU\n\"\"\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\"\"\"\n## Obtener Datasets\n\"\"\"\n# Training Dataset\ntrain_dataset = torch.utils.data.TensorDataset(x_train_images, y_train_images)\ntrainloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=False)\n\n#Validation Dataset\nvalid_dataset = torch.utils.data.TensorDataset(x_valid_images, y_valid_images)\nvalidloader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)\n\"\"\"\n# Arquitectura del Modelo\n\"\"\"\nclass CNN(nn.Module):\n    def __init__(self):\n        super(CNN, self).__init__()\n        self.layer1 = nn.Sequential(\n            nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1), # output dim = (28x28x32)\n            nn.BatchNorm2d(32),\n            nn.ReLU(),\n            nn.Dropout(p=0.2)\n        )\n        \n        self.layer2 = nn.Sequential(\n            nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1), # output dim = (28x28x32)\n            nn.BatchNorm2d(32),\n            nn.ReLU(),\n            nn.Dropout(p=0.2)\n        )\n        \n        self.layer3 = nn.Sequential(\n            nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=0), # output = (26x26x64)\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2,stride=2), # output = (13x13x64)\n            nn.Dropout(p=0.2)\n        )\n        \n        \n        self.fc1 = nn.Sequential(\n            nn.Linear(10816, 512),\n            nn.ReLU(),\n            nn.Linear(512, 256),\n            nn.ReLU(),\n            nn.Linear(256, 10),\n            nn.LogSoftmax(dim=1)\n        )\n        \n    def forward(self, x):\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = x.view(x.size(0), -1)\n        x = self.fc1(x)\n        \n        return x\n\"\"\"\n# Entrenamiento de la Red\n\"\"\"\nmodel = CNN()\nmodel.cuda()\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\ntraining_loss = []\nvalid_loss = []\ntraining_accuracy = []\nvalid_accuracy = []\ntrainingTimeStart = time.process_time()\nfor epoch in range(epochs):\n    model.train()\n    running_loss = 0\n    accuracy = 0\n    steps = 0\n    \n    for images, labels in trainloader:    \n        images = images.cuda()\n        labels = labels.cuda()\n        #Training pass\n        output = model(images)\n        loss = criterion(output, labels)\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        \n        running_loss += loss.item()\n        \n        _, predicted = torch.max(output, 1)\n        accuracy += (predicted == labels).sum()\n        steps += 1\n        \n    training_loss.append(running_loss\/steps)\n    training_accuracy.append(100 * accuracy.cpu().numpy()\/len(train_dataset))\n    model.eval()\n    \n    with torch.no_grad():\n        iter_loss = 0\n        accuracy = 0\n        steps = 0\n        \n        for images, labels in validloader:\n            images = images.cuda()\n            labels = labels.cuda()\n            output = model(images)\n            loss = criterion(output, labels)\n            \n            iter_loss += loss.item()\n            _, predicted = torch.max(output, 1)\n            accuracy += (predicted == labels).sum()\n            steps += 1\n            \n        valid_loss.append(iter_loss\/steps)\n        valid_accuracy.append(100 * accuracy.cpu().numpy()\/len(valid_dataset))\n        \n    print ('Epoch {}\/{}, Training Loss: {:.3f}, Training Accuracy: {:.2f}%, Validation Loss: {:.3f}, Validation Acc: {:.2f}%'\n            .format(epoch+1, epochs, training_loss[-1], training_accuracy[-1], valid_loss[-1], valid_accuracy[-1]))\n    \ntrainingTimeStop = time.process_time() - trainingTimeStart\nprint('Tiempo de ejecuci\u00f3n: ' + str(trainingTimeStop))\nplt.plot(training_loss, color='red', label=\"Training loss\")\nplt.plot(valid_loss, color='blue',label=\"Validation loss\")\nplt.legend()\nplt.show()\nplt.plot(training_accuracy, color='red', label=\"Training acc\")\nplt.plot(valid_accuracy, color='blue',label=\"Validation acc\")\nplt.legend()\nplt.show()\n\"\"\"\n# Resultado\n\"\"\"\ntesting_images = np.load(\"..\/input\/kuzushiji\/kmnist-test-imgs.npz\")[\"arr_0\"]\ntesting_labels = np.load(\"..\/input\/kuzushiji\/kmnist-test-labels.npz\")[\"arr_0\"]\nnew_testing_images, new_testing_labels = normalizar(testing_images, testing_labels)\nx_testing_images = torch.Tensor(new_testing_images)\ny_testing_images = torch.Tensor(new_testing_labels).type(torch.LongTensor)\nprint(\"Set de Prueba: \" + str(x_testing_images.shape))\nprint(\"Labels del Set de Prueba: \" + str(y_testing_images.shape))\ntest_dataset = torch.utils.data.TensorDataset(x_testing_images, y_testing_images)\ntestloader = torch.utils.data.DataLoader(test_dataset, batch_size=300, shuffle=False)\nmodel.eval()\ntestingTimeStart = time.process_time()\nwith torch.no_grad():\n    accuracy = 0\n    total = 0\n    test_loss = 0\n    \n    for images, labels in testloader:\n        images = images.cuda()\n        labels = labels.cuda()\n        output = model(images)\n        loss = criterion(output, labels)\n        test_loss += loss.item()\n        test_loss = test_loss\/len(testloader)\n        \n        _, predicted = torch.max(output.data, 1)\n        total += labels.size(0)\n        accuracy += (predicted == labels).sum().item()\n        test_accuracy = (100 * accuracy)\/total\n    \n    print('Test Loss: {:.4f}, Test Accuracy: {:.2f}%'.format(test_loss, test_accuracy))\ntestingTimeStop = time.process_time() - testingTimeStart\nprint(\"Tiempo de ejecuci\u00f3n: \" + str(testingTimeStop))","meta":"{'source': 'AI4Code', 'id': 'bf102e9886b96a'}"}
{"id":"9228","text":"\"\"\"\n## **1. Background**\n\"\"\"\n\"\"\"\n![Natural language processing](https:\/\/landbot.io\/wp-content\/uploads\/2019\/11\/natural-language-processing-chatbot.jpg)\n\"\"\"\n\"\"\"\n**What is Natural Language Processing?**\n\nFrom wikipedia, Natural language processing (NLP) is a subfield of linguistics, computer science, information engineering, and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data.\n\n**What is Sentiment Classification?**\n\nSentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information. Sentiment analysis is widely applied to voice of the customer materials such as reviews and survey responses, online and social media, and healthcare materials for applications that range from marketing to customer service to clinical medicine.\n\n**What is Tokenizer?**\n\nTokenization is a necessary first step in many natural language processing tasks, such as word counting, parsing, spell checking, corpus generation, and statistical analysis of text.\n\nTokenizer is a compact pure-Python (2 and 3) executable program and module for tokenizing Icelandic text. It converts input text to streams of tokens, where each token is a separate word, punctuation sign, number\/amount, date, e-mail, URL\/URI, etc. It also segments the token stream into sentences, considering corner cases such as abbreviations and dates in the middle of sentences.[Tokenizer](https:\/\/pypi.org\/project\/tokenizer\/)\n\n**What is Padding?**\n\nAs a same approach in Convolution Neural Network, Padding assure the input layer have the same shape for the model. \n\n**What is LSTM (long short term memory)?**\n\nLong short-term memory (LSTM) is an artificial recurrent neural network (RNN) architecture used in the field of deep learning. Unlike standard feedforward neural networks, LSTM has feedback connections. It can not only process single data points (such as images), but also entire sequences of data (such as speech or video). For example, LSTM is applicable to tasks such as unsegmented, connected handwriting recognition, speech recognition and anomaly detection in network traffic or IDS's (intrusion detection systems)\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\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# Any results you write to the current directory are saved as output.\n\"\"\"\n## **2. Data exploratory analysis**\n\"\"\"\n\"\"\"\n### **2.1 Data overview**\n\"\"\"\n\"\"\"\n![IMDB 50 review datasets](https:\/\/o.aolcdn.com\/images\/dims?quality=85&image_uri=https%3A%2F%2Fo.aolcdn.com%2Fimages%2Fdims%3Fcrop%3D908%252C537%252C0%252C0%26quality%3D85%26format%3Djpg%26resize%3D1600%252C947%26image_uri%3Dhttps%253A%252F%252Fs.yimg.com%252Fos%252Fcreatr-uploaded-images%252F2019-08%252F560e5d20-c833-11e9-bf26-36635805fe83%26client%3Da1acac3e1b3290917d92%26signature%3D639a4965c41ca6cec13652498f65cfc97170ea5d&client=amp-blogside-v2&signature=765e155477177a69b93eac5611145d4241be6071)\n\"\"\"\n\"\"\"\nThis dataset contains movie reviews along with their associated binary sentiment polarity labels. It is intended to serve as a benchmark for sentiment classification. This document outlines how the dataset was gathered, and how to use the files provided.\n\n**Dataset**\n\nThe core dataset contains 50,000 reviews. The overall distribution of labels is balanced (25k pos and 25k neg). We also include an additional 50,000 unlabeled documents for unsupervised learning.\n\nIn the entire collection, no more than 30 reviews are allowed for any given movie because reviews for the same movie tend to have correlated ratings. Further, the train and test sets contain a disjoint set of movies, so no significant performance is obtained by memorizing movie-unique terms and their associated with observed labels. In the labeled train\/test sets, a negative review has a score <= 4 out of 10, and a positive review has a score >= 7 out of 10. Thus reviews with more neutral ratings are not included in the train\/test sets. In the unsupervised set, reviews of any rating are included and there are an even number of reviews > 5 and <= 5.\n\"\"\"\n\"\"\"\n### **2.2 Data pre-processing**\n\"\"\"\n\"\"\"\nThe first step is to load the data to global environment.\n\"\"\"\ndf = pd.read_csv(\"\/kaggle\/input\/imdb-dataset-of-50k-movie-reviews\/IMDB Dataset.csv\")\ndf.head()\n\"\"\"\nTo visualize the work and choose the proper approach to pre-process data and visualize the text data, here come some task as my defined.\n\n1) Data shape. From this to split our data to train and test data.\n\n2) What is the most common words? Use different approach to visualize the most common words. From this we can find out if any inappropriate words which could be removed.\n\n3) What is the distribution of the sentences length? From this we can choose the proper max_length of sentence.\n\n4) How many total words from our dataset? From this we can choose the vocabulary size for our model.\n\"\"\"\nfrom collections import Counter\nCounter(\" \".join(df[\"review\"]).lower().split()).most_common(100)\n\"\"\"\nWe could see some abnormal words such as <br \/><br \/>, then we should replace them by a null or space value.\n\"\"\"\n#import string as str\n#df['review'] = [i.replace('<br>', '').str.replace('<\/br>', '') for i in df['review']]\ndf['review'] = df['review'].str.replace('<br \/>','')\ndf['review'] = df['review'].str.lower()\nplt.figure()\nplt.hist(df['review'].str.split().apply(len).value_counts())\nplt.xlabel('number of words in sentence')\nplt.ylabel('frequency')\nplt.title('Words occurrence frequency')\nprint('The maximum length of a sentence is: ',np.max(df['review'].str.split().apply(len).value_counts()))\nprint('The average lenth of a sentence is: ', np.average(df['review'].str.split().apply(len).value_counts()))\nfrom sklearn import preprocessing\nlabel_encoder = preprocessing.LabelEncoder()\ndf['sentiment'] = label_encoder.fit_transform(df['sentiment'])\ndf.head()\nsentences = np.array(df['review'])\nlabels = np.array(df['sentiment'])\n\"\"\"\nSplit data to train and test for modeling and performance evaluation.\n\"\"\"\ntraining_sentences, testing_sentences,training_labels, testing_labels = train_test_split(sentences, labels, test_size = 0.2)\n\"\"\"\n## **3. Modeling**\n\"\"\"\n# choose hyper parameters to tune\nvocab_size = 20000 #(before 10000)\nembedding_dim = 150 #(before 16)\nmax_length =  400 #(was 32)\ntrunc_type = 'post'\npadding_type = 'post'\noov_tok = \"<OOV>\"\n\n\n# import Tokenizer & fit on training test\ntokenizer = Tokenizer(num_words = vocab_size, oov_token = oov_tok)\ntokenizer.fit_on_texts(training_sentences)\n\nword_index = tokenizer.word_index\n\n# convert text to sequences\ntraining_sequences = tokenizer.texts_to_sequences(training_sentences)\ntraining_padded = pad_sequences(training_sequences, maxlen = max_length,\n                                padding = padding_type,\n                                truncating = trunc_type)\n\ntesting_sequences = tokenizer.texts_to_sequences(testing_sentences)\ntesting_padded = pad_sequences(testing_sequences, maxlen = max_length,\n                                padding = padding_type,\n                                truncating = trunc_type)\n\n    # modeling\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\n    \n    # option 1: Flatten\n    #tf.keras.layers.Flatten(),\n    #tf.keras.layers.GlobalAveragePooling1D(),\n    \n    # option 2: LSTM\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),\n    #tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.15),\n\n    # option 3: GRU\n    #tf.keras.layers.Bidirectional(tf.keras.layers.GRU(64)),\n    \n    # option 4: Conv1D\n    #tf.keras.layers.Conv1D(128,5,activation='relu'),\n    #tf.keras.layers.GlobalAveragePooling1D(),\n    \n    tf.keras.layers.Dense(128, activation = 'relu'),\n    tf.keras.layers.Dense(1, activation = 'sigmoid')\n])\n\nmodel.summary()\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import LearningRateScheduler\n\n# compile model\nmodel.compile(loss = 'binary_crossentropy',\n            optimizer = Adam(learning_rate=0.001),\n            metrics = ['accuracy'])\n\n# add early stopping\ncallback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n\n# learning rate decay\ndef lr_decay(epoch, initial_learningrate = 0.001):#lrv\n    return initial_learningrate * 0.9 ** epoch\n\n# training model\nnum_epochs = 10\nhistory = model.fit(training_padded, training_labels,\n                    epochs=num_epochs,\n                    callbacks=[LearningRateScheduler(lr_decay),\n                              callback],\n                    batch_size = 512,\n                    validation_data = (testing_padded, testing_labels),\n                    verbose=1)\ndef plot_graphs(history, string):\n    plt.plot(history.history[string])\n    plt.plot(history.history['val_'+string])\n    plt.xlabel('Epochs')\n    plt.ylabel(string)\n    plt.title(print('vocab_size: ',vocab_size))\n    plt.legend([string, 'val_' + string])\n    plt.show()\n    \nplot_graphs(history, \"accuracy\")\nplot_graphs(history,\"loss\")","meta":"{'source': 'AI4Code', 'id': '110efb7d2ada92'}"}
{"id":"69725","text":"\"\"\"\n# Mall Segmentation Using K Means Clustering :\n\"\"\"\n\"\"\"\n### Importing Libraries :\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\ndf=pd.read_csv('..\/input\/mall-customers\/Mall_Customer_Dataset.csv')\ndf.head()\ndf.shape\ndf.info()\ndf.describe().T\ndf.isnull().sum()\ndf.corr()['Spending Score (1-100)'].sort_values(ascending=False)\nsns.pairplot(df)\nsns.set_style('darkgrid')\nplt.figure(figsize=(12,6))\nplt.scatter(x='Age',y='Annual Income (k$)',data=df)\nplt.xlabel('Age')\nplt.ylabel('Annual Income in k$')\nX=df.iloc[:,[3,4]].values\nX.shape\nfrom sklearn.cluster import KMeans\nkm=KMeans(n_clusters=3,init='k-means++',random_state=0)\ny_predicted=km.fit_predict(X)\ny_predicted\ndf['Cluster']=y_predicted\ndf.head()\nkm.cluster_centers_\nplt.scatter(X[y_predicted == 0, 0], X[y_predicted == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\nplt.scatter(X[y_predicted == 1, 0], X[y_predicted == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_predicted == 2, 0], X[y_predicted == 2, 1], s = 100, c = 'green', label = 'Cluster 3')\n\n#plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids',marker='*')\nplt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],color='purple',marker='*',label='centroid')\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\"\"\"\n## Analysing Error:\n\"\"\"\nerror=[]\nfor i in range(1,20):\n    kmeans=KMeans(n_clusters=i,init='k-means++',random_state=0)\n    kmeans.fit(X)\n    error.append(kmeans.inertia_)\nplt.plot(range(1,20),error)\nplt.xlabel('K Values')\nplt.ylabel('Error')\nkmeans_new=KMeans(n_clusters=5,init='k-means++', random_state=0)\ny_kmeans=kmeans_new.fit_predict(X)\ny_kmeans\ndf['Cluster']=y_kmeans\ndf.head()\nplt.figure(figsize=(12,6))\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')\nplt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')\nplt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')\nplt.scatter(kmeans_new.cluster_centers_[:, 0], kmeans_new.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids',marker='*')\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\"\"\"\n## Here is The Detailed Analysis of the plot shown Above:\n\"\"\"\n#Cluster 1 (Red Color) -> Average Income , average spending\n#cluster 2 (Blue Color) -> Less income,high spending \n#cluster 3 (Green Color) -> earning high and also spending high [Potential Target Customers]\n#cluster 4 (cyan Color) -> earning less but spending less\n#Cluster 5 (magenta Color) -> Earning High , spending less\n\"\"\"\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\n\nhere plt.scatter(x,y)=x=y_kmeans==0,0 ->first 0 indicates= cluster label 0 &second 0 indicates feature number=Annual Income\n                    y=y_kmeans=0,1-> first 0 indicates cluster label 0 & second 1 indicates feature number 1=Spending score\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '804861d4cf35eb'}"}
{"id":"1911","text":"\"\"\"\n# The Challenge\n\"\"\"\n\"\"\"\nThe sinking of the Titanic is one of the most infamous shipwrecks in history.\n\nOn April 15, 1912, during her maiden voyage, the widely considered \u201cunsinkable\u201d RMS Titanic sank after colliding with an iceberg. Unfortunately, there weren\u2019t enough lifeboats for everyone onboard, resulting in the death of 1502 out of 2224 passengers and crew.\n\nWhile there was some element of luck involved in surviving, it seems some groups of people were more likely to survive than others.\n\nIn this challenge, we ask you to build a predictive model that answers the question: \u201cwhat sorts of people were more likely to survive?\u201d using passenger data (ie name, age, gender, socio-economic class, etc).\n\"\"\"\n\"\"\"\n# Libraries\n\"\"\"\n# Basic\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n# File\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n# Load Data\n\"\"\"\ndf_train = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ndf_train.shape\ndf_test = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\ndf_test.shape\ndf_sub = pd.read_csv('\/kaggle\/input\/titanic\/gender_submission.csv')\ndf_sub.shape\n\"\"\"\n# Explore\n\"\"\"\ndf_train.head()\ndf_train.info()\ndf_train.isnull().sum()\nwomen = df_train.loc[df_train.Sex == 'female'][\"Survived\"]\nrate_women = sum(women)\/len(women)\n\nprint(\"% of women who survived:\", rate_women)\nmen = df_train.loc[df_train.Sex == 'male'][\"Survived\"]\nrate_men = sum(men)\/len(men)\n\nprint(\"% of men who survived:\", rate_men)\n\"\"\"\n# Data Pre-processing\n\"\"\"\n#df = pd.concat([df_train, df_test])#.reset_index(drop=True)\n#df.shape\ndf_train = df_train.fillna(-999)\ndf_test = df_test.fillna(-999)\n\"\"\"\n# Model\n\"\"\"\n'''\nsplit = len(df_train)\ntrain = df[:split]\ntest = df[split:]\n'''\n# Get train and validation sub-datasets\nfrom sklearn.model_selection import train_test_split\n\nX = df_train.drop([\"Survived\"], axis=1)\ny = df_train[\"Survived\"]\n\n#Do train data splitting\nX_train, X_test, y_train, y_test = train_test_split(X,y, train_size=0.75, random_state=42)\n\"\"\"\n# Baseline Model\n\"\"\"\n'''\nfrom sklearn.ensemble import RandomForestClassifier\n\ny = df_train[\"Survived\"]\n\nfeatures = [\"Pclass\", \"Sex\", \"SibSp\", \"Parch\"]\nX = pd.get_dummies(df_train[features])\nX_test = pd.get_dummies(df_test[features])\n\nmodel = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)\nmodel.fit(X, y)\npredictions = model.predict(X_test)\n\noutput = pd.DataFrame({'PassengerId': df_test.PassengerId, 'Survived': predictions})\noutput.to_csv('my_submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")\n'''\n\"\"\"\n# Model\n\"\"\"\n# Libs\nfrom catboost import CatBoostClassifier, Pool, cv\nfrom sklearn.metrics import accuracy_score\n\n# Select categorical indices\ncat_features_indices = np.where(X.dtypes != float)[0]\n\n# Define the model\nmodel = CatBoostClassifier(\n    eval_metric='Accuracy',\n    loss_function='Logloss',\n    #iterations=150,\n    use_best_model=True,\n    random_seed=42,\n    logging_level='Silent'\n)\n\n#now just to make the model to fit the data\nmodel.fit(X_train,y_train,cat_features=cat_features_indices,eval_set=(X_test,y_test), plot=True)\n#TODO: Early stopping\n\"\"\"\n# Validation\n\"\"\"\ncv_params = model.get_params()\ncv_params.update({\n    'loss_function': 'Logloss'\n})\ncv_data = cv(\n    Pool(X, y, cat_features=cat_features_indices),\n    cv_params,\n    plot=True\n)\nprint('Best validation accuracy score: {:.2f}\u00b1{:.2f} on step {}'.format(\n    np.max(cv_data['test-Accuracy-mean']),\n    cv_data['test-Accuracy-std'][np.argmax(cv_data['test-Accuracy-mean'])],\n    np.argmax(cv_data['test-Accuracy-mean'])\n))\nprint('Precise validation accuracy score: {}'.format(np.max(cv_data['test-Accuracy-mean'])))\n# Create pool\ntrain_pool = Pool(X_train, y_train, cat_features=cat_features_indices)\nvalidate_pool = Pool(X_test, y_test, cat_features=cat_features_indices)\n# Feature importance\nfeature_importances = model.get_feature_importance(train_pool)\nfeature_names = X_train.columns\nfor score, name in sorted(zip(feature_importances, feature_names), reverse=True):\n    print('{}: {}'.format(name, score))\neval_metrics = model.eval_metrics(validate_pool, ['AUC'], plot=True)\n\"\"\"\n# Submission\n\"\"\"\n# Re-train model with full data\n#model.fit(X,y,cat_features=cat_features_indices)\n# Make predictions\npredictions = model.predict(df_test)\npredictions_probs = model.predict_proba(df_test)\nprint(predictions[:10])\nprint(predictions_probs[:10])\n# Save results\noutput = pd.DataFrame({'PassengerId': df_test.PassengerId, 'Survived': predictions})\noutput.to_csv('my_submission.csv', index=False)\nprint(\"Submission was successfully saved!\")","meta":"{'source': 'AI4Code', 'id': '03a8bcf6801a1d'}"}
{"id":"1325","text":"\"\"\"\n# Aim and motivation\nThe primary reason I have chosen to create this kernel is to practice and use RNNs for various tasks and applications. First of which is time series data. RNNs have truly changed the way sequential data is forecasted. My goal here is to create the ultimate reference for RNNs here on kaggle.\n\"\"\"\n\"\"\"\n## Things to remember\n* Please upvote(like button) and share this kernel if you like it. This would increase its visibility and more people will be able to learn about the awesomeness of RNNs.\n* I will use keras for this kernel. If you are not familiar with keras or neural networks, refer to this kernel\/tutorial of mine:  https:\/\/www.kaggle.com\/thebrownviking20\/intro-to-keras-with-breast-cancer-data-ann\n* Your doubts and curiousity about time series can be taken care of here: https:\/\/www.kaggle.com\/thebrownviking20\/everything-you-can-do-with-a-time-series\n* Don't let the explanations intimidate you. It's simpler than you think.\n* Eventually, I will add more applications of LSTMs. So stay tuned for more!\n* The code is inspired from Kirill Eremenko's Deep Learning Course: https:\/\/www.udemy.com\/deeplearning\/\n\"\"\"\n\"\"\"\n## Recurrent Neural Networks\nIn a recurrent neural network we store the output activations from one or more of the layers of the network. Often these are hidden later activations. Then, the next time we feed an input example to the network, we include the previously-stored outputs as additional inputs. You can think of the additional inputs as being concatenated to the end of the \u201cnormal\u201d inputs to the previous layer. For example, if a hidden layer had 10 regular input nodes and 128 hidden nodes in the layer, then it would actually have 138 total inputs (assuming you are feeding the layer\u2019s outputs into itself \u00e0 la Elman) rather than into another layer). Of course, the very first time you try to compute the output of the network you\u2019ll need to fill in those extra 128 inputs with 0s or something.\n\nSource: [Quora](https:\/\/www.quora.com\/What-is-a-simple-explanation-of-a-recurrent-neural-network)\n<img src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/1*NKhwsOYNUT5xU7Pyf6Znhg.png\">\n\nSource: [Medium](https:\/\/medium.com\/ai-journal\/lstm-gru-recurrent-neural-networks-81fe2bcdf1f9)\n\nLet me give you the best explanation of Recurrent Neural Networks that I found on internet: https:\/\/www.youtube.com\/watch?v=UNmqTiOnRfg&t=3s\n\"\"\"\n\"\"\"\nNow, even though RNNs are quite powerful, they suffer from  **Vanishing gradient problem ** which hinders them from using long term information, like they are good for storing memory 3-4 instances of past iterations but larger number of instances don't provide good results so we don't just use regular RNNs. Instead, we use a better variation of RNNs: **Long Short Term Networks(LSTM).**\n\n### What is Vanishing Gradient problem?\nVanishing gradient problem is a difficulty found in training artificial neural networks with gradient-based learning methods and backpropagation. In such methods, each of the neural network's weights receives an update proportional to the partial derivative of the error function with respect to the current weight in each iteration of training. The problem is that in some cases, the gradient will be vanishingly small, effectively preventing the weight from changing its value. In the worst case, this may completely stop the neural network from further training. As one example of the problem cause, traditional activation functions such as the hyperbolic tangent function have gradients in the range (0, 1), and backpropagation computes gradients by the chain rule. This has the effect of multiplying n of these small numbers to compute gradients of the \"front\" layers in an n-layer network, meaning that the gradient (error signal) decreases exponentially with n while the front layers train very slowly.\n\nSource: [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/Vanishing_gradient_problem)\n\n<img src=\"https:\/\/cdn-images-1.medium.com\/max\/1460\/1*FWy4STsp8k0M5Yd8LifG_Q.png\">\n\nSource: [Medium](https:\/\/medium.com\/@anishsingh20\/the-vanishing-gradient-problem-48ae7f501257)\n\"\"\"\n\"\"\"\n## Long Short Term Memory(LSTM)\nLong short-term memory (LSTM) units (or blocks) are a building unit for layers of a recurrent neural network (RNN). A RNN composed of LSTM units is often called an LSTM network. A common LSTM unit is composed of a cell, an input gate, an output gate and a forget gate. The cell is responsible for \"remembering\" values over arbitrary time intervals; hence the word \"memory\" in LSTM. Each of the three gates can be thought of as a \"conventional\" artificial neuron, as in a multi-layer (or feedforward) neural network: that is, they compute an activation (using an activation function) of a weighted sum. Intuitively, they can be thought as regulators of the flow of values that goes through the connections of the LSTM; hence the denotation \"gate\". There are connections between these gates and the cell.\n\nThe expression long short-term refers to the fact that LSTM is a model for the short-term memory which can last for a long period of time. An LSTM is well-suited to classify, process and predict time series given time lags of unknown size and duration between important events. LSTMs were developed to deal with the exploding and vanishing gradient problem when training traditional RNNs.\n\nSource: [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/Long_short-term_memory)\n\n<img src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*LyfY3Mow9eCYlj7o.\">\n\nSource: [Medium](https:\/\/codeburst.io\/generating-text-using-an-lstm-network-no-libraries-2dff88a3968)\n\nThe best LSTM explanation on internet: https:\/\/medium.com\/deep-math-machine-learning-ai\/chapter-10-1-deepnlp-lstm-long-short-term-memory-networks-with-math-21477f8e4235\n\nRefer above link for deeper insights.\n\"\"\"\n\"\"\"\n## Components of LSTMs\nSo the LSTM cell contains the following components\n* Forget Gate \u201cf\u201d ( a neural network with sigmoid)\n* Candidate layer \u201cC\"(a NN with Tanh)\n* Input Gate \u201cI\u201d ( a NN with sigmoid )\n* Output Gate \u201cO\u201d( a NN with sigmoid)\n* Hidden state \u201cH\u201d ( a vector )\n* Memory state \u201cC\u201d ( a vector)\n\n* Inputs to the LSTM cell at any step are X<sub>t<\/sub> (current input) , H<sub>t-1<\/sub> (previous hidden state ) and C<sub>t-1<\/sub> (previous memory state).  \n* Outputs from the LSTM cell are H<sub>t<\/sub> (current hidden state ) and C<sub>t<\/sub> (current memory state)\n\"\"\"\n\"\"\"\n## Working of gates in LSTMs\nFirst, LSTM cell takes the previous memory state C<sub>t-1<\/sub> and does element wise multiplication with forget gate (f) to decide if  present memory state C<sub>t<\/sub>. If forget gate value is 0 then previous memory state is completely forgotten else f forget gate value is 1 then previous memory state is completely passed to the cell ( Remember f gate gives values between 0 and 1 ).\n\n**C<sub>t<\/sub> = C<sub>t-1<\/sub> * f<sub>t<\/sub>**\n\nCalculating the new memory state: \n\n**C<sub>t<\/sub> = C<sub>t<\/sub> + (I<sub>t<\/sub> * C\\`<sub>t<\/sub>)**\n\nNow, we calculate the output:\n\n**H<sub>t<\/sub> = tanh(C<sub>t<\/sub>)**\n\"\"\"\n\"\"\"\n### And now we get to the code...\nI will use LSTMs for predicting the price of stocks of IBM for the year 2017\n\"\"\"\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Dropout, GRU, Bidirectional\nfrom keras.optimizers import SGD\nimport math\nfrom sklearn.metrics import mean_squared_error\n# Some functions to help out with\ndef plot_predictions(test,predicted):\n    plt.plot(test, color='red',label='Real IBM Stock Price')\n    plt.plot(predicted, color='blue',label='Predicted IBM Stock Price')\n    plt.title('IBM Stock Price Prediction')\n    plt.xlabel('Time')\n    plt.ylabel('IBM Stock Price')\n    plt.legend()\n    plt.show()\n\ndef return_rmse(test,predicted):\n    rmse = math.sqrt(mean_squared_error(test, predicted))\n    print(\"The root mean squared error is {}.\".format(rmse))\n# First, we get the data\ndataset = pd.read_csv('..\/input\/IBM_2006-01-01_to_2018-01-01.csv', index_col='Date', parse_dates=['Date'])\ndataset.head()\n# Checking for missing values\ntraining_set = dataset[:'2016'].iloc[:,1:2].values\ntest_set = dataset['2017':].iloc[:,1:2].values\n# We have chosen 'High' attribute for prices. Let's see what it looks like\ndataset[\"High\"][:'2016'].plot(figsize=(16,4),legend=True)\ndataset[\"High\"]['2017':].plot(figsize=(16,4),legend=True)\nplt.legend(['Training set (Before 2017)','Test set (2017 and beyond)'])\nplt.title('IBM stock price')\nplt.show()\n# Scaling the training set\nsc = MinMaxScaler(feature_range=(0,1))\ntraining_set_scaled = sc.fit_transform(training_set)\n# Since LSTMs store long term memory state, we create a data structure with 60 timesteps and 1 output\n# So for each element of training set, we have 60 previous training set elements \nX_train = []\ny_train = []\nfor i in range(60,2769):\n    X_train.append(training_set_scaled[i-60:i,0])\n    y_train.append(training_set_scaled[i,0])\nX_train, y_train = np.array(X_train), np.array(y_train)\n# Reshaping X_train for efficient modelling\nX_train = np.reshape(X_train, (X_train.shape[0],X_train.shape[1],1))\n# The LSTM architecture\nregressor = Sequential()\n# First LSTM layer with Dropout regularisation\nregressor.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1],1)))\nregressor.add(Dropout(0.2))\n# Second LSTM layer\nregressor.add(LSTM(units=50, return_sequences=True))\nregressor.add(Dropout(0.2))\n# Third LSTM layer\nregressor.add(LSTM(units=50, return_sequences=True))\nregressor.add(Dropout(0.2))\n# Fourth LSTM layer\nregressor.add(LSTM(units=50))\nregressor.add(Dropout(0.2))\n# The output layer\nregressor.add(Dense(units=1))\n\n# Compiling the RNN\nregressor.compile(optimizer='rmsprop',loss='mean_squared_error')\n# Fitting to the training set\nregressor.fit(X_train,y_train,epochs=50,batch_size=32)\n# Now to get the test set ready in a similar way as the training set.\n# The following has been done so forst 60 entires of test set have 60 previous values which is impossible to get unless we take the whole \n# 'High' attribute data for processing\ndataset_total = pd.concat((dataset[\"High\"][:'2016'],dataset[\"High\"]['2017':]),axis=0)\ninputs = dataset_total[len(dataset_total)-len(test_set) - 60:].values\ninputs = inputs.reshape(-1,1)\ninputs  = sc.transform(inputs)\n# Preparing X_test and predicting the prices\nX_test = []\nfor i in range(60,311):\n    X_test.append(inputs[i-60:i,0])\nX_test = np.array(X_test)\nX_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))\npredicted_stock_price = regressor.predict(X_test)\npredicted_stock_price = sc.inverse_transform(predicted_stock_price)\n# Visualizing the results for LSTM\nplot_predictions(test_set,predicted_stock_price)\n# Evaluating our model\nreturn_rmse(test_set,predicted_stock_price)\n\"\"\"\nTruth be told. That's one awesome score. \n\nLSTM is not the only kind of unit that has taken the world of Deep Learning by a storm. We have **Gated Recurrent Units(GRU)**. It's not known, which is better: GRU or LSTM becuase they have comparable performances. GRUs are easier to train than LSTMs.\n\n## Gated Recurrent Units\nIn simple words, the GRU unit does not have to use a memory unit to control the flow of information like the LSTM unit. It can directly makes use of the all hidden states without any control. GRUs have fewer parameters and thus may train a bit faster or need less data to generalize. But, with large data, the LSTMs with higher expressiveness may lead to better results.\n\nThey are almost similar to LSTMs except that they have two gates: reset gate and update gate. Reset gate determines how to combine new input to previous memory and update gate determines how much of the previous state to keep. Update gate in GRU is what input gate and forget gate were in LSTM. We don't have the second non linearity in GRU before calculating the outpu, .neither they have the output gate.\n\nSource: [Quora](https:\/\/www.quora.com\/Whats-the-difference-between-LSTM-and-GRU-Why-are-GRU-efficient-to-train)\n\n<img src=\"https:\/\/cdnpythonmachinelearning.azureedge.net\/wp-content\/uploads\/2017\/11\/GRU.png?x31195\">\n\"\"\"\n# The GRU architecture\nregressorGRU = Sequential()\n# First GRU layer with Dropout regularisation\nregressorGRU.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1],1), activation='tanh'))\nregressorGRU.add(Dropout(0.2))\n# Second GRU layer\nregressorGRU.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1],1), activation='tanh'))\nregressorGRU.add(Dropout(0.2))\n# Third GRU layer\nregressorGRU.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1],1), activation='tanh'))\nregressorGRU.add(Dropout(0.2))\n# Fourth GRU layer\nregressorGRU.add(GRU(units=50, activation='tanh'))\nregressorGRU.add(Dropout(0.2))\n# The output layer\nregressorGRU.add(Dense(units=1))\n# Compiling the RNN\nregressorGRU.compile(optimizer=SGD(lr=0.01, decay=1e-7, momentum=0.9, nesterov=False),loss='mean_squared_error')\n# Fitting to the training set\nregressorGRU.fit(X_train,y_train,epochs=50,batch_size=150)\n\"\"\"\nThe current version version uses a dense GRU network with 100 units as opposed to the GRU network with 50 units in previous version\n\"\"\"\n# Preparing X_test and predicting the prices\nX_test = []\nfor i in range(60,311):\n    X_test.append(inputs[i-60:i,0])\nX_test = np.array(X_test)\nX_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))\nGRU_predicted_stock_price = regressorGRU.predict(X_test)\nGRU_predicted_stock_price = sc.inverse_transform(GRU_predicted_stock_price)\n# Visualizing the results for GRU\nplot_predictions(test_set,GRU_predicted_stock_price)\n# Evaluating GRU\nreturn_rmse(test_set,GRU_predicted_stock_price)\n\"\"\"\n## Sequence Generation\nHere, I will generate a sequence using just initial 60 values instead of using last 60 values for every new prediction. **Due to doubts in various comments about predictions making use of test set values, I have decided to include sequence generation.** The above models make use of test set so it is using last 60 true values for predicting the new value(I will call it a benchmark). This is why the error is so low. Strong models can bring similar results like above models for sequences too but they require more than just data which has previous values. In case of stocks, we need to know the sentiments of the market, the movement of other stocks and a lot more. So, don't expect a remotely accurate plot. The error will be great and the best I can do is generate the trend similar to the test set.\n\nI will use GRU model for predictions. You can try this using LSTMs also. I have modified GRU model above to get the best sequence possible. I have run the model four times and two times I got error of around 8 to 9. The worst case had an error of around 11. Let's see what this iterations.\n\nThe GRU model in the previous versions is fine too. Just a little tweaking was required to get good sequences. **The main goal of this kernel is to show how to build RNN models. How you predict data and what kind of data you predict is up to you. I can't give you some 100 lines of code where you put the destination of training and test set and get world-class results. That's something you have to do yourself.**\n\"\"\"\n# Preparing sequence data\ninitial_sequence = X_train[2708,:]\nsequence = []\nfor i in range(251):\n    new_prediction = regressorGRU.predict(initial_sequence.reshape(initial_sequence.shape[1],initial_sequence.shape[0],1))\n    initial_sequence = initial_sequence[1:]\n    initial_sequence = np.append(initial_sequence,new_prediction,axis=0)\n    sequence.append(new_prediction)\nsequence = sc.inverse_transform(np.array(sequence).reshape(251,1))\n# Visualizing the sequence\nplot_predictions(test_set,sequence)\n# Evaluating the sequence\nreturn_rmse(test_set,sequence)\n\"\"\"\nSo, GRU works better than LSTM in this case. Bidirectional LSTM is also a good way so make the model stronger. But this may vary for different data sets. **Applying both LSTM and GRU together gave even better results.** \n\"\"\"\n\"\"\"\n#### I was going to cover text generation using LSTM but already an excellent kernel by [Shivam Bansal](https:\/\/www.kaggle.com\/shivamb) on the mentioned topic exists. Link for that kernel here: https:\/\/www.kaggle.com\/shivamb\/beginners-guide-to-text-generation-using-lstms\n\"\"\"\n\"\"\"\n#### This is certainly not the end. Stay tuned for more stuff!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '02784f4b25d78e'}"}
{"id":"3739","text":"\"\"\"\n# Heart Disease Model\n\"\"\"\n\"\"\"\nAccording to CDC, heart disease is the leading cause of death in the United States. Wouldn't it be great if we tried to diagnose heart disease before it becomes\nsevere? My model predicts whether a patient has heart disease or not based on the patient's medical reports.\n\n## Dataset Specifics\nIn the data, you are given several attributes: \n\n 1. age\n \n 2. sex\n \n 3. chest pain type (4 values)\n \n 4. resting blood pressure\n \n 5. serum cholesterol in mg\/dl\n \n 6.  fasting blood sugar > 120 mg\/dl\n \n 7. resting electrocardiographic results (values 0, 1, 2)\n \n 8. maximum heart rate achieved\n \n 9. exercise induced angina\n \n 10. oldpeak = ST depression induced by exercise relative to rest \n \n 11. the slope of the peak exercise ST segment\n \n 12.  number of major vessels (0-3) colored by flourosopy\n \n 13.   thal: 3 = normal; 6 = fixed defect; 7 = reversable defect\n\n## Algorithm \nThis is a classification problem (binary classification) and the results can be interpreted as 0 and 1 (0 = without heart disease, 1 = with heart disease). I used two methods: a [neural network]( https:\/\/en.wikipedia.org\/wiki\/Artificial_neural_network) using **Keras**, and [Logistic Regression](https:\/\/en.wikipedia.org\/wiki\/Logistic_regression#:~:text=Logistic%20regression%20is%20a%20statistical,a%20form%20of%20binary%20regression). My neural network involves the use of [Early Stopping](https:\/\/en.wikipedia.org\/wiki\/Early_stopping) and [Dropout Layers](https:\/\/keras.io\/api\/layers\/regularization_layers\/dropout\/) to prevent overfitting of the data. Logistic Regression is used when dealing with categorical data (in this case, patients with and without heart disease).\n\n\n| Type | Accuracy |  Precision| Recall|F1-Score|\n|--|--|--|--|--|\n| Logistic Regression | 85% | 0 = 88%, 1 = 82% | 0 = 80%, 1 = 89% |0 = 83%, 1 = 86%   |\n| Neural Network|  87%| 0 = 90%, 1 = 83%| 0 = 80%, 1 = 91%| 0 = 84%, 1 = 87%\n\n**[My Github](https:\/\/github.com\/anyaiyer\/heart-disease-predictor) for this project**\n\n\n\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nheart = pd.read_csv('\/kaggle\/input\/heart-disease-uci\/heart.csv')\nheart.head()\nheart.info()\nheart.describe()\n\"\"\"\n## Exploratory Data Analysis\n\"\"\"\nsns.set_theme()\n\"\"\"\nData visualization is a useful tool in comparing these features of patients to find the most correlated attributes with the presence of heart disease.\nVarious plot types such as heatmaps, countplots, barplots, and histplots help find common patterns between patients with and without heart disease. My code\nincludes a few of these plots to compare and contrast patients. \n\"\"\"\n\"\"\"\nMore people have heart disease.\nMore females have heart disease than males; more females are included in this dataset\n\"\"\"\nsns.countplot(x='target',data=heart,hue='sex') \n\"\"\"\nMost patients are ages 50-60.\n\"\"\"\nplt.figure(figsize=(12,6))\nheart['age'].plot(kind='hist',bins=40)\nheart.corr()\n\"\"\"\nAttribute info: \n- age\n- sex\n-  pain type (4 values)\n- resting blood pressure\n- serum cholestoral in mg\/dl\n- fasting blood sugar > 120 mg\/dl\n- resting electrocardiographic results (values 0,1,2)\n- maximum heart rate achieved\n- exercise induced angina\n- oldpeak = ST depression induced by exercise relative to rest\n- the slope of the peak exercise ST segment\n- number of major vessels (0-3) colored by flourosopy\n- thal: 3 = normal; 6 = fixed defect; 7 = reversable defect\n\"\"\"\nplt.figure(figsize=(15,8))\nsns.heatmap(heart.corr(),cmap='viridis',annot=True)\n\"\"\"\nUsing a heatmap, we can get the most correlated features with target.\n\"\"\"\n\"\"\"\nMost correlated features:\n- slope (slope of peak exercise ST segment) -> 35% correlated\n\n- thalach (max heart rate achieved) -> 42% correlated\n\n- restecg (resting electrocadiographic results) -> 14% correlated\n\n- cp (chest pain type) -> 43% correlated (most correlated feature with target) \n\"\"\"\nplt.figure(figsize=(10,6))\nsns.barplot(x='cp',y='target',data=heart)\n\"\"\"\nChest pain of 1 is the most common.\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.countplot(x='restecg',data=heart,hue='target')\n\"\"\"\nMost people who had heart disease have a restcg of 1.\n\"\"\"\nheart.corr()['target'][:-1].sort_values().plot(kind='bar')\nplt.tight_layout\n\"\"\"\n Visual representation (bar chart) showing most correlated features with target column.\n\"\"\"\nplt.figure(figsize=(10,6))\nheart['thalach'].plot(kind='hist',bins=40)\n\"\"\"\nMost people have a thalach between 140 and 170.\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.countplot(x='slope',data=heart,hue='target')\n\"\"\"\nMost affected people have a slope of 2\n\"\"\"\n\"\"\"\n## Data PreProcessing \n\"\"\"\nplt.figure(figsize=(12,6))\nheart.isnull().sum()\n\"\"\"\nNo null values\n\"\"\"\nheart.head()\n\"\"\"\nData is already cleaned -> no need to fill in missing data or convert data to numerical data.\n\"\"\"\n\"\"\"\n## Train Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nheart.columns\nX = heart.drop('target',axis=1).values\ny = heart['target'].values\nprint(len(heart)) # data size is small\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)\n\"\"\"\n[Features scaling](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.preprocessing.MinMaxScaler.html#:~:text=Transform%20features%20by%20scaling%20each,e.g.%20between%20zero%20and%20one) (also known as Standardization) helps normalise the data within a specific range. This ensures\nmore accurate results as the model does not have to process large ranges of data. MinMaxScaler transforms the data\nsuch that it is all within a given range.\n\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\"\"\"\n## Create Model\n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Dropout\nmodel = Sequential()\n\nmodel.add(Dense(40,activation='relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(20,activation='relu'))\nmodel.add(Dropout(0.2))\n\n# BINARY CLASSIFICATION so use sigmoid for the last layer\nmodel.add(Dense(1,activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',optimizer='adam')\nfrom tensorflow.keras.callbacks import EarlyStopping\n\"\"\"\nUse of [EarlyStopping](https:\/\/en.wikipedia.org\/wiki\/Early_stopping) and [Dropout layers](https:\/\/keras.io\/api\/layers\/regularization_layers\/dropout\/) prevents overfitting of the data.\n\n\"\"\"\nearly_stop = EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=25)\n\"\"\"\nIn order to fit the model, we pass in X_train, y_train, the number of epochs (number of times the model will \nwork through the entire dataset), validation data (testing data), batch size (number of samples to work through \nbefore updating the model parameters), and early stopping.\n\"\"\"\nmodel.fit(x=X_train,y=y_train,epochs=200,validation_data=(X_test,y_test),batch_size=30,callbacks=[early_stop])\n\"\"\"\n## Model Evaluation\n\"\"\"\nmodel_loss = pd.DataFrame(model.history.history)\nmodel_loss.plot()\n\"\"\"\nEventually, the validation loss goes below the loss. This is ideal as the loss is reaching a minimum point, and overfitting is not occuring.\n\"\"\"\npredictions = model.predict_classes(X_test)\nfrom sklearn.metrics import classification_report, confusion_matrix\nprint(classification_report(y_test,predictions))\nprint(confusion_matrix(y_test,predictions))\nsns.countplot(x='target',data=heart) # fairly balanced \n\"\"\"\nRecall is most important because we need to detect all the true positives of heart disease. It is the most important that recall is high for all positive cases. Accuracy is ok because the data set is fairly balanced. Precision is less important than recall in this case.\n\"\"\"\nfrom tensorflow.keras.models import load_model\nneural_net_model = model.save('heart-disease-predictor.h5') # save model\nmodel_loss # loss vs. val loss \n\"\"\"\n# Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlogmodel = LogisticRegression()\nlogmodel.fit(X_train,y_train)\npredictions = logmodel.predict(X_test)\nfrom sklearn.metrics import classification_report, confusion_matrix\nprint(classification_report(y_test,predictions))\nconfusion_matrix(y_test,predictions)\nacc = logmodel.score(X_test, y_test)*100\n\nprint(\"Test Accuracy {:.2f}%\".format(acc))\nimport pickle\nfilename = \"heart-disease-LR.pkl\"  # save model with pickle\n\nwith open(filename, 'wb') as file:  \n    pickle.dump(logmodel, file)","meta":"{'source': 'AI4Code', 'id': '06fbf1418b990a'}"}
{"id":"79094","text":"\"\"\"\nIn week 2 competition, I found I submitted a prediction of a model trained with data only before public LB periods.\nThen, here I tried to simulated late submission and checked how good my fixed submission is.  \n\"\"\"\nimport os, gc, pickle, copy, datetime, warnings\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport lightgbm as lgb\nfrom sklearn import metrics\npd.set_option('display.max_columns', 100)\nwarnings.filterwarnings('ignore')\ndf_test = pd.read_csv(\"..\/input\/my-covid-pred\/test_week2.csv\")\ndf_test.head()\ndf_week4 = pd.read_csv(\"..\/input\/covid19-global-forecasting-week-4\/train.csv\")\ndf_week4.head()\ndf_test2 = pd.merge(df_test, df_week4, on=['Province_State', 'Country_Region', 'Date'], how='left')\ndf_test2.head()\ndf_test2['Date'] = pd.to_datetime(df_test2['Date'])\ndf_test2['day'] = df_test2['Date'].apply(lambda x: x.dayofyear).astype(np.int16)\ndf_test2.head()\n# check the last day of existing true data\ntmp = df_test2[pd.isna(df_test2['ConfirmedCases'])==False]['Date'].max()\nprint(\"last day of existing true data: {}\".format(tmp))\n\"\"\"\n- df_sub_osciiart_bug: [My final submission with bug](https:\/\/www.kaggle.com\/osciiart\/covid-19-lightgbm-no-leak?scriptVersionId=31248128)\n- df_sub_osciiart_fixed: [My fixed submission](https:\/\/www.kaggle.com\/osciiart\/covid-19-lightgbm-no-leak\/output?scriptVersionId=31694015)\n- df_sub_kaz: [1st place solution](https:\/\/www.kaggle.com\/kazanova\/gr1621-v2)\n\"\"\"\ndf_sub_osciiart_bug = pd.read_csv(\"..\/input\/my-covid-pred\/submission1.csv\") # my final submission with bug\ndf_sub_osciiart_fixed = pd.read_csv(\"..\/input\/my-covid-pred\/submission_osciiart_fixed.csv\") # my fixed submission\ndf_sub_kaz = pd.read_csv(\"..\/input\/my-covid-pred\/submission_Kaz.csv\") # 1st place solution\ndf_sub_osciiart_bug.head()\ndef calc_score(y_true, y_pred):\n    y_true[y_true<0] = 0\n    score = metrics.mean_squared_error(np.log(y_true.clip(0, 1e10)+1), np.log(y_pred[:]+1))**0.5\n    return score\n\ndef calc_private_score(df_sub):\n    day_before_private = 92\n    period = (pd.isna(df_test2['ConfirmedCases'])==False) & (df_test2['day']>day_before_private)\n\n    y_true = df_test2['ConfirmedCases'][period].values\n    y_pred = df_sub['ConfirmedCases'][period].values\n    score1 = calc_score(y_true, y_pred)\n    y_true = df_test2['Fatalities'][period].values\n    y_pred = df_sub['Fatalities'][period].values\n    score2 = calc_score(y_true, y_pred)\n    score = (score1+score2)\/2\n    return score\nprint(\"df_sub_osciiart_bug: {:.5f}\".format(calc_private_score(df_sub_osciiart_bug)))\nprint(\"df_sub_osciiart_fixed: {:.5f}\".format(calc_private_score(df_sub_osciiart_fixed)))\nprint(\"df_sub_kaz: {:.5f}\".format(calc_private_score(df_sub_kaz)))\n\"\"\"\n\ud83d\ude2d\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '914551b62a69e8'}"}
{"id":"2133","text":"\"\"\"\n## Introduction\n\nWe explain here how to read and plot EARTHDATA-MERRA2 Data Files.\n\n### Data Format\n\nThe data format used is nc4. To read such files, we need to use netCDF4 Python package.\n\n### External Resources\n\n[ON NASA site](https:\/\/disc.gsfc.nasa.gov\/information\/howto) you can find a set of instructions how to read, explore and visualize data content from EARTHDATA-MERRA2 files.\n\nIn particular, we used this resource: [How to read and plot NetCDF MERRA-2 data in Python](https:\/\/disc.gsfc.nasa.gov\/information\/howto?title=How%20to%20read%20and%20plot%20NetCDF%20MERRA-2%20data%20in%20Python)\n\n\n\"\"\"\n\"\"\"\n## Data Analysis\n\n### Load Packages\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport folium\nfrom folium.plugins import HeatMap, HeatMapWithTime\nfrom netCDF4 import Dataset\nimport cartopy.crs as ccrs\n\"\"\"\n### Load Data\n\n\nWe will load here only one file.\n\"\"\"\ndata = Dataset(\"\/kaggle\/input\/earthdata-merra2-co\/MERRA2_400.tavgM_2d_chm_Nx.202004.nc4\", more=\"r\")\n\"\"\"\n### Data Extraction\n\nLet's inspect the dataset.\n\"\"\"\nprint(data)\n\"\"\"\nWe then filter atmospheric latitude\/longitude\/time\/ and variables and load them as numpy arrays.\n\"\"\"\nlons = data.variables['lon'][:]\nlats = data.variables['lat'][:]\ntime = data.variables['time'][:]\nCOCL = data.variables['COCL'][:,:,:]; COCL = COCL[0,:,:]\nCOEM = data.variables['COEM'][:,:,:]; COEM = COEM[0,:,:]\nCOLS = data.variables['COLS'][:,:,:]; COLS = COLS[0,:,:]\nTO3 =  data.variables['TO3'][:,:,:];  TO3 =  TO3[0,:,:]\nprint(f\"longitudes: {len(lons)}\")\nprint(f\"latitudes: {len(lats)}\")\nprint(f\"time: {len(time)}\")\nprint(f\"COCL: {len(COCL)}\")\nprint(f\"COEM: {len(COEM)}\")\nprint(f\"COLS: {len(COLS)}\")\nprint(f\"TO3:  {len(TO3)}\")\nprint(f\"Latitudes: {len(lats)}, vals[:]: {len(COCL[0])}, Longitudes: {len(lons)}, vals[:,:]: {len(COCL[0])}\")\n\"\"\"\n## Plot data\n\nWe write first a function for plotting the data.\n\"\"\"\ndef plot_merra_data(data, title='', date='April 2020'):\n    fig = plt.figure(figsize=(16,8))\n    ax = plt.axes(projection=ccrs.Robinson())\n    ax.set_global()\n    ax.coastlines(resolution=\"110m\",linewidth=1)\n    ax.gridlines(linestyle='--',color='black')\n    plt.contourf(lons, lats, data, transform=ccrs.PlateCarree(),cmap=plt.cm.jet)\n    plt.title(f'MERRA-2 {title} levels, {date}', size=14)\n    cb = plt.colorbar(ax=ax, orientation=\"vertical\", pad=0.02, aspect=16, shrink=0.8)\n    cb.set_label('K',size=12,rotation=0,labelpad=15)\n    cb.ax.tick_params(labelsize=10)\n\"\"\"\nWe then apply the function for few of the data features.\n\"\"\"\nplot_merra_data(COCL, 'COCL')\nplot_merra_data(COEM, 'COEM')\nplot_merra_data(COLS, 'COLS')\nplot_merra_data(TO3, 'TO3')","meta":"{'source': 'AI4Code', 'id': '040c5ffb0af823'}"}
{"id":"109086","text":"\"\"\"\n## Load library\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport lightgbm as lgb\nfrom category_encoders.ordinal import OrdinalEncoder\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import f1_score\n\"\"\"\n## Load data\n\"\"\"\ntrain = pd.read_csv('\/kaggle\/input\/kakr-4th-competition\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/kakr-4th-competition\/test.csv')\nsample_submission = pd.read_csv('\/kaggle\/input\/kakr-4th-competition\/sample_submission.csv')\ntrain.head()\n\"\"\"\n## EDA & pre-process\n\"\"\"\nsns.distplot(train.age)\nsns.distplot(np.log1p(train.age))\ntrain.age = np.log1p(train.age)\ntest.age = np.log1p(test.age)\nsns.distplot(train.hours_per_week)\nsns.distplot(np.log1p(train.hours_per_week))\ntrain.hours_per_week = np.log1p(train.hours_per_week)\ntest.hours_per_week = np.log1p(test.hours_per_week)\nsns.distplot(train.fnlwgt)\nsns.distplot(np.log1p(train.fnlwgt))\ntrain.fnlwgt = np.log1p(train.fnlwgt)\ntest.fnlwgt = np.log1p(test.fnlwgt)\ntrain['capital_d'] = train.capital_gain - train.capital_loss\ntest['capital_d'] = test.capital_gain - test.capital_loss\ntrain.capital_gain = np.log1p(train.capital_gain)\ntest.capital_gain = np.log1p(test.capital_gain)\ntrain.capital_loss = np.log1p(train.capital_loss)\ntest.capital_loss = np.log1p(test.capital_loss)\ntrain.capital_d = np.log1p(train.capital_d)\ntest.capital_d = np.log1p(test.capital_d)\n\"\"\"\n## Label data convert\n\"\"\"\ntarget = train['income'] != '<=50K'\ntrain.drop(['income'], axis=1, inplace=True)\ntrain_le = train\ntest_le = test\n# LE_encoder = OrdinalEncoder(list(train.columns))\n# train_le = LE_encoder.fit_transform(train, target)\n# test_le = LE_encoder.transform(test)\ncat_features = ['workclass', 'education', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'native_country']\nfor f in cat_features:\n    train_le[f] = train_le[f].astype('category')\n    test_le[f] = test_le[f].astype('category')\nskf = StratifiedKFold(n_splits=5)\n# train_le['fold'] = 0\nfold_id_list = list()\nfor fold_id, (trn_id, val_id) in enumerate(skf.split(X=train_le.index, y=target)):\n    fold_id_list.append(val_id)\nparams = {\n        'objective':'binary',\n        \"boosting\": \"gbdt\",\n        'num_leaves': 100,\n        'max_depth': 6,#16\n        'learning_rate': 0.1,#0.1\n#         'min_data_in_leaf': 16, \n#         'min_child_samples': 30,\n#         'min_child_weight': 0.5,\n#         'min_split_gain': 0.1,\n#         \"feature_fraction\": 0.9,\n#         \"bagging_fraction\": 0.9,\n#         \"bagging_freq\": 2,\n        \"bagging_seed\": 42,\n        \"colsample_bytree\": 0.8,\n        \"metric\": 'lgb_f1_score',\n        \"lambda_l1\": 0.2,\n        \"lambda_l2\": 0.5,\n        'verbose':-1\n    }\ndef custom_round(predict, threshold):\n    data = predict.copy()\n    try:\n        data.loc[data>=threshold] = 1\n        data.loc[data<threshold] = 0\n    except:\n        data[data>=threshold] = 1\n        data[data<threshold] = 0\n    return data\n\ndef lgb_f1_score(y_hat, data):\n    y_true = data.get_label()\n#     y_hat = custom_round(y_hat, np.quantile(y_hat, 0.7))\n    y_hat = custom_round(y_hat, 0.5) #  \n    return 'f1', f1_score(y_true, y_hat), True\nC_FOLD = 0\nresult_pred = list()\nfor C_FOLD in range(5):\n    valid_fold_id = fold_id_list[C_FOLD]\n    \n    train_dataset = train_le.loc[train_le.index.isin(valid_fold_id) == False]\n    valid_dataset = train_le.loc[train_le.index.isin(valid_fold_id)]\n    \n    train_target = target[train_le.index.isin(valid_fold_id) == False]\n    valid_target = target[train_le.index.isin(valid_fold_id)]\n    \n    # LightGBM\n    trn_df = lgb.Dataset(train_dataset, label=train_target)\n    val_df = lgb.Dataset(valid_dataset, label=valid_target)\n    \n    model = lgb.train(params, trn_df, 1000, \n                            valid_sets = [trn_df, val_df], \n                            early_stopping_rounds = 100, \n                            verbose_eval=100, \n                            feval=lgb_f1_score)\n    pred = model.predict(test_le)\n    result_pred.append(pred)\n    \n    # RandomForest\n#     RF_clf = RandomForestClassifier()\n#     RF_clf.fit(train_dataset, train_target)\n    \n#     pred = RF_clf.predict_proba(test_le)\n#     result_pred.append(pred[:, 1])\nresult_pred = np.stack(result_pred)\n# result_pred = custom_round(result_pred.mean(axis=0), np.quantile(result_pred.mean(axis=0), 0.7))\nresult_pred = (result_pred.mean(axis=0) >= 0.5)\nsample_submission['prediction'] = result_pred.astype(int)\nsample_submission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'c8892b2655aacb'}"}
{"id":"27042","text":"\"\"\"\nGlaucoma is a gathering of eye conditions that harm the optic nerve, the soundness of which is indispensable for acceptable vision. This harm is frequently brought about by a strangely high weight in your eye. \n\nGlaucoma is one of the main sources of visual impairment for individuals beyond 60 years old. It can happen at any age yet is progressively normal in more established grown-ups. \n\nNumerous types of glaucoma have no admonition signs. The impact is continuous to such an extent that you may not see an adjustment in vision until the condition is at a propelled arrange. \n\nSince vision misfortune because of glaucoma can't be recouped, it's essential to have customary eye tests that incorporate estimations of your eye pressure so a conclusion can be made in its beginning times and treated properly. On the off chance that glaucoma is perceived early, vision misfortune can be eased back or forestalled. In the event that you have the condition, you'll for the most part need treatment for a mind-blowing remainder.\n\n\"\"\"\n\"\"\"\n![](https:\/\/www.kaggleusercontent.com\/kf\/16917358\/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..J3SdYQETDQfIPyjVfxzsRg.FPl9uKD_qD6aZF1a9XMJOByjUFC19WEsNJtnN_WFC9tChP0PXbEbCNuCGm1LKfEVKbCSPH77yIE4Y2MkbBCYTwC36le-U-tKxCXNkNuhYj473KKFxEnxwYr5wla1KmS4gdyz7wvJJFjU3GbeE6gr9tVgqQxqCawNxkomYcUVncY.2AX-ccvCI-T4X0ILiroMvA\/__results___files\/__results___11_0.png)\n\"\"\"\n#library\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nimport seaborn as sn\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix\nimport plotly.graph_objects as go\n#dataset\ndata_load = pd.read_csv('\/kaggle\/input\/glaucoma-dataset\/GlaucomaM.csv')\ndata_load.head()\ndata_load.isnull().sum()\nle = LabelEncoder()\ndata_load.Class = le.fit_transform(data_load.Class)\ndata_load['Class']\nmodel_params = {\n    'svm': {\n        'model': svm.SVC(gamma='auto'),\n        'params' : {\n            'C': [1,10,20],\n            'kernel': ['rbf','linear']\n        }  \n    },\n    'random_forest': {\n        'model': RandomForestClassifier(),\n        'params' : {\n            'n_estimators': [1,5,10]\n        }\n    },\n    'logistic_regression' : {\n        'model': LogisticRegression(solver='liblinear',multi_class='auto'),\n        'params': {\n            'C': [1,5,10]\n        }\n    }\n}   \n\npd.DataFrame(model_params)\nscores = []\n\nfor model_name, mp in model_params.items():\n    clf =  GridSearchCV(mp['model'], mp['params'], cv=3, return_train_score=False)\n    clf.fit(data_load.drop('Class',axis='columns'), data_load.Class)\n    scores.append({\n        'model': model_name,\n        'best_score': clf.best_score_,\n        'best_params': clf.best_params_\n    })\n    \ndf = pd.DataFrame(scores,columns=['model','best_score','best_params'])\ndf\nfrom sklearn.model_selection import train_test_split\nX = data_load.drop('Class', axis='columns')\ny = data_load.Class\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,random_state=0)\n\nmodel = SVC(C=1.0,kernel='linear')\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\nclasses1 = {\n    0:'Normal',\n    1:'Gulcoma',\n}\ny_predicted = model.predict(X_test)\ny_predicted\nclasses1[y_predicted[3]]\ncm = confusion_matrix(y_test, y_predicted)\ncm\nfig = go.Figure(data=go.Heatmap(\n                   z=cm,\n                   x=['Normal','Glucoma'],\n                   y=['Normal','Glucoma'],\n                   hoverongaps = False))\nfig.show()","meta":"{'source': 'AI4Code', 'id': '31c38ed04a2b98'}"}
{"id":"87843","text":"import numpy as np \nimport pandas as pd \nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport plotly.graph_objects as go\ndf = pd.read_json('..\/input\/fraud-detection-dataset\/transactions.txt', lines=True)\ndf.head()\ndf.shape\ndf.columns\ndf.dtypes\ndf.nunique()\n#empty columns\ndf.drop(['merchantCity','merchantState','merchantZip','echoBuffer','posOnPremises','recurringAuthInd'],axis=1,inplace=True)\ndf.head()\n\"\"\"\n#### **Target col**\n\"\"\"\nfig = go.Figure(data=[go.Pie(labels=df.isFraud, hole=.3)])\nfig.add_annotation(text='isFraud',\n                   x=0.5,y=0.5,showarrow=False,font_size=14,opacity=0.7,font_family='monospace')\nfig.update_traces(hoverinfo='label+percent+value',\n                  marker=dict(colors=['darkorange','blue'], line=dict(color='#000000', width=2)))\nfig.show()\n\"\"\"\n#### **Data preprocessing**\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\nvar = ['merchantName','acqCountry','merchantCountryCode','posEntryMode','posConditionCode','merchantCategoryCode','transactionType','cardPresent','expirationDateKeyInMatch','isFraud']\nfor i in var:\n    df[i] = le.fit_transform(df[i])\n# converting in datetime format\ndf['transactionDateTime'] = pd.to_datetime(df['transactionDateTime'])\ndf['currentExpDate'] = pd.to_datetime(df['currentExpDate'])\ndf['accountOpenDate'] = pd.to_datetime(df['accountOpenDate'])\ndf['dateOfLastAddressChange'] = pd.to_datetime(df['dateOfLastAddressChange'])\n# extractind year, month, day, hour, minute and seconds from datetime columns\ndf['transactionDateTime_year'] = df['transactionDateTime'].dt.year\ndf['transactionDateTime_month'] = df['transactionDateTime'].dt.month\ndf['transactionDateTime_day'] = df['transactionDateTime'].dt.day\ndf['transactionDateTime_hour'] = df['transactionDateTime'].dt.hour\ndf['transactionDateTime_minute'] = df['transactionDateTime'].dt.minute\ndf['transactionDateTime_second'] = df['transactionDateTime'].dt.second\n\ndf['currentExpDate_year'] = df['currentExpDate'].dt.year\ndf['currentExpDate_month'] = df['currentExpDate'].dt.month\ndf['currentExpDate_day'] = df['currentExpDate'].dt.day\n\ndf['accountOpenDate_year'] = df['accountOpenDate'].dt.year\ndf['accountOpenDate_month'] = df['accountOpenDate'].dt.month\ndf['accountOpenDate_day'] = df['accountOpenDate'].dt.day\n\ndf['dateOfLastAddressChange_year'] = df['dateOfLastAddressChange'].dt.year\ndf['dateOfLastAddressChange_month'] = df['dateOfLastAddressChange'].dt.month\ndf['dateOfLastAddressChange_day'] = df['dateOfLastAddressChange'].dt.day\n# drop datetime column\ndf.drop('transactionDateTime',axis = 1,inplace = True)\ndf.drop('currentExpDate',axis = 1,inplace = True)\ndf.drop('accountOpenDate',axis = 1,inplace = True)\ndf.drop('dateOfLastAddressChange',axis = 1,inplace = True)\ndf.head()\ndf.dtypes\n\"\"\"\n#### **VIF (Variable Inflation Factors)**\nfor multicollinearity detection\n\"\"\"\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\ndef calc_vif(X):\n\n    # Calculating VIF\n    vif = pd.DataFrame()\n    vif[\"variables\"] = X.columns\n    vif[\"VIF\"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]\n\n    return(vif)\nX = df.drop('isFraud',axis=1)\ncalc_vif(X)\n\"\"\"\nWe can see here that the 'enteredCVV','customerId','availableMoney', 'currentBalance','cardCVV','accountNumber' and 'creditLimit'  have a high VIF value, meaning they can be predicted by other independent variables in the dataset.\n\n#### **Fixing Multicollinearity**\nDropping one of the correlated features will help in bringing down the multicollinearity between correlated features:\n\n\n\"\"\"\ndf.drop(['enteredCVV','customerId','availableMoney'],axis=1,inplace=True)\nX = df.drop('isFraud',axis=1)\ncalc_vif(X)\n\"\"\"\n#### **Model building**\n\"\"\"\n\"\"\"\nI'm using pycaret. pycaret package is used to automate the major steps for evaluating and comparing machine learning algorithms for classification and regression. The main benefit of the library is that a lot can be achieved with very few lines of code and little manual configuration.\n\"\"\"\n! pip install pycaret\nfrom pycaret.classification import setup, compare_models, blend_models, finalize_model, predict_model\ndef pycaret_model(train, target, n_select, fold, opt):\n    print('Setup Your Data....')\n    setup(data=train,\n              target=target,\n              numeric_imputation = 'mean',\n              silent= True)\n  \n    print('Comparing Models....')\n    best = compare_models(sort=opt, n_select=n_select, fold = fold,include = ['gbc','rf','et','xgboost','lightgbm','catboost'])\n    # gbc = gradient boosting classifier\n    # rf = random forest classifier\n    # et = extra tree classifier\n    \n    print('Blending Models....')\n    blended = blend_models(estimator_list= best, fold=fold, optimize=opt)\n    pred = predict_model(blended)\n    \n    return pred\npycaret_model(df, 'isFraud', 5, 3, 'Accuracy')","meta":"{'source': 'AI4Code', 'id': 'a115b07bf9c42a'}"}
{"id":"59915","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.gridspec import  GridSpec\nimport plotly.graph_objs as go \nfrom plotly.offline import init_notebook_mode, iplot, plot\ninit_notebook_mode(connected=True) \nimport warnings\nwarnings.filterwarnings('ignore')\nimport pandas_profiling as pp\n#import DataScienceHelper as dsh\n\n%matplotlib inline\n\nfrom sklearn.utils import resample\nfrom sklearn.linear_model import LogisticRegression, Perceptron, RidgeClassifier, SGDClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, ExtraTreesClassifier \nfrom sklearn.ensemble import BaggingClassifier, VotingClassifier \nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import metrics\nimport xgboost as xgb\nfrom xgboost import XGBClassifier\nimport lightgbm as lgb\nfrom lightgbm import LGBMClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.preprocessing import normalize, StandardScaler\nfrom sklearn import metrics \n\n\n\n\n## We look at the data using the head and tail functions\nHF = pd.read_csv('\/kaggle\/input\/heart-failure-clinical-data\/heart_failure_clinical_records_dataset.csv')\n\nHF.head(5)\nHF.tail(5)\nHF.shape\nHF.info()\n\"\"\"\n#### The above shows that all variables of the integer and float type. However looking at summary statistics of the data we can see that some variables are of the binary format and as such cannot be analysed as either integer or floating variables. We have to rectify accordingly\n\"\"\"\nHF.describe()\nHF.isnull().sum()\n\"\"\"\n#### We can see from the above that there are no missing values in any of the columns, which makes our job relatively much easier\n\"\"\"\n## Change the data type of the variables with Binary values to the appropriate data type\nHF[\"anaemia\"] = HF[\"anaemia\"].astype(str)\nHF[\"diabetes\"] = HF[\"diabetes\"].astype(str)\nHF[\"high_blood_pressure\"] = HF[\"high_blood_pressure\"].astype(str)\nHF[\"sex\"] = HF[\"sex\"].astype(str)\nHF[\"smoking\"] = HF[\"smoking\"].astype(str)\nHF[\"DEATH_EVENT\"] = HF[\"DEATH_EVENT\"].astype(str)\n\nprint(HF.describe())\nprint(HF.describe(include = np.object))\n\"\"\"\n# Visualizations\n\"\"\"\ncolumns = list(HF._get_numeric_data().keys())\n\ncolumns\npp.ProfileReport(HF) ## Another way of generating descriptive statistics using Pandas Profiling package\n\"\"\"\n### KDE plots of Quantitative Variables\n\"\"\"\ndsh.show_kdeplot(HF, columns)\n\"\"\"\n### Boxplots of Quatitative Variables\n\"\"\"\ndsh.show_boxplot(HF, columns)\n\"\"\"\n### Correlation Matrix\n\"\"\"\n## First reconvert the categorical binary variables to intergers\ncat_columns = list(HF.select_dtypes(include = 'object').keys())\n\nfor column in cat_columns:\n    HF[column] = HF[column].astype(int)\n\nprint(cat_columns)\n## Then we proceed with the correlation matrix\nHF_matrix = HF.corr()\n\nf, ax = plt.subplots(figsize = (12,10))\nk = 13 ## Number of columns in the matrix\n## Use the DEATH EVENT variable as index as it will be compared against other variables\ncols = HF_matrix.nlargest(k, 'DEATH_EVENT')['DEATH_EVENT'].index \nhfm = np.corrcoef(HF[cols].values.T)\nsns.set(font_scale = 1.5)\n\nsns.heatmap(hfm, cbar = True, annot = True, square = True, fmt = '.2f', annot_kws = {'size': 12},\n           cmap = 'BrBG', yticklabels = cols.values, xticklabels = cols.values)\n\nplt.show()\n\n\"\"\"\n# Modelling \n\"\"\"\nHF['DEATH_EVENT'].value_counts()\n\"\"\"\n#### From the above we can see that this is clearly an imbalanced data. Therefore, we will employ resampling techniques(Over Sampling)\n\"\"\"\nDeath_major = HF[HF['DEATH_EVENT'] == 0]\nDeath_minor = HF[HF['DEATH_EVENT'] == 1]\n\nUP_min = resample(Death_minor, replace = True, n_samples = 203, random_state = 320)\n\n## Combine the majority class with the upsampled minority class\nHFN = pd.concat([Death_major, UP_min])\n\nHFN['DEATH_EVENT'].value_counts()\n## get the target variable and the independent variables\ntarget = HFN['DEATH_EVENT']\nindependent = HFN.drop(['DEATH_EVENT'], axis = 1)\n## Normalize the independent variable values\nindependent = normalize(independent)\nindependent = StandardScaler().fit_transform(independent)\n\n\n\n## OR\n# independent = StandardScaler().fit_transform(normalize(independent))\n\"\"\"\n### Logistic Regression\n\"\"\"\nscores_lr = []\ntrain_list = []\nfor i in range(1,10):\n    x_train, x_test, y_train, y_test = train_test_split(independent, target,test_size = i\/10, random_state = 123)\n    \n    \n    lr = LogisticRegression()\n    lr.fit(x_train,y_train) \n    print(\"Test accuracy: {}\/Test Size: {}\".format(np.round(lr.score(x_test,y_test),3),i))\n    scores_lr.append(lr.score(x_test,y_test))\n    train_list.append(lr.score(x_train,y_train))\n     \n    \n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1, 4, left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])\n\nax1.plot(range(1,10),scores_lr,label = \"Test Accuracy\")\nax1.plot(range(1,10),train_list, label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Test Sizes\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores For Each Test Size\",fontsize = 17)\nax1.grid(True, alpha = 0.4)\n\n\nx_train, x_test, y_train, y_test = train_test_split(independent, \n                                                    target,test_size = (1 + scores_lr.index(np.max(scores_lr)))\/10, \n                                                    random_state = 123)\n\nlr_best = LogisticRegression(random_state = 123)\nlr_best = lr_best.fit(x_train, y_train)\ny_pred = lr_best.predict(x_test)\ny_true = y_test\n\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True, annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f',\n            ax = ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Logistic Regression Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy(test): {}\/Test Size: {}\".format(np.max(scores_lr), 1 + scores_lr.index(np.max(scores_lr))))\n\n       \nprint(classification_report(y_pred, y_true))\npred_prob = lr_best.predict_proba(x_test)\n\ny_preds = pred_prob[:, 1]\nfpr, tpr, _ = metrics.roc_curve(y_true, y_preds)\nauc_score = metrics.auc(fpr, tpr)\n\nplt.figure(figsize = (10,10))\nplt.title('ROC Curve: Logistic')\nplt.plot(fpr, tpr, label = 'AUC = {:.2f}'.format(auc_score))\nplt.plot([0, 1], [0, 1], 'r--')\n\nplt.xlim(-0.1, 1.1)\nplt.ylim(-0.1, 1.1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.legend(loc = 'lower right')\nplt.show()\n\"\"\"\n### K-Nearest Neighbours\n\"\"\"\nx_train, x_test, y_train, y_test = train_test_split(independent, target, test_size = 0.2, random_state = 123)\n\nscores_knn = []\ntrain_list = []\nfor i in range(1,25):\n    knn = KNeighborsClassifier(n_neighbors = i)\n    knn.fit(x_train,y_train)\n    print(\"test accuracy: {}\/Neighbors: {}\".format(np.round(knn.score(x_test,y_test), 3),i))\n    scores_knn.append(knn.score(x_test,y_test))\n    train_list.append(knn.score(x_train,y_train))\n    \n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])    \n\nax1.plot(range(1,25),scores_knn, label = \"Test Accuracy\")\nax1.plot(range(1,25),train_list,c = \"orange\", label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"K Values\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores For Each K Value\",fontsize = 17)\nax1.grid(True , alpha = 0.4)\n\n\n\nBest_knn = KNeighborsClassifier(n_neighbors = 1 + scores_knn.index(np.max(scores_knn)))\nBest_knn = Best_knn.fit(x_train, y_train)\ny_pred = Best_knn.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"KNN Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy(test): {}\/Neighbors: {}\".format(np.max(scores_knn),1 + scores_knn.index(np.max(scores_knn))))\n\nprint(classification_report(y_pred, y_true))\nknn_prob = Best_knn.predict_proba(x_test)\n\ny_preds = knn_prob[:, 1]\nfpr, tpr, _ = metrics.roc_curve(y_true, y_preds)\nauc_score = metrics.auc(fpr, tpr)\n\nplt.figure(figsize = (10,10))\nplt.title('ROC Curve: KNN')\nplt.plot(fpr, tpr, label = 'AUC = {:.2f}'.format(auc_score))\nplt.plot([0, 1], [0, 1], 'r--')\n\nplt.xlim(-0.1, 1.1)\nplt.ylim(-0.1, 1.1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.legend(loc = 'lower right')\nplt.show()\n\"\"\"\n### Support Vector Machine(SVM)\n\"\"\"\nscores_svm = []\ntrain_list = []\nfor i in range(100,500,50):\n    svm = SVC(cache_size = i)\n    svm.fit(x_train,y_train)\n    print(\"test accuracy: {}\/Cache Size: {}\".format(np.round(svm.score(x_test,y_test),3),i))\n    scores_svm.append(svm.score(x_test,y_test))\n    train_list.append(svm.score(x_train,y_train))\n\n\n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])  \n    \nax1.plot(range(100,500,50), scores_svm, label = \"Test Accuracy\")\nax1.plot(range(100,500,50), train_list,c = \"orange\", label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Cache Sizes\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores For Each Cache Size\",fontsize = 17)\nax1.grid(True , alpha = 0.4)\n\nBest_SVM = SVC(cache_size = 50*(1+scores_svm.index(np.max(scores_svm))))\nBest_SVM = Best_SVM.fit(x_train, y_train)\ny_pred = Best_SVM.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy(test): {}\/Cache Size: {}\".format(np.max(scores_svm), \n                                                      50 + 50 * (1 + scores_svm.index(np.max(scores_svm)))))\nprint(classification_report(y_pred, y_true))\n\"\"\"\n### Decision Trees\n\"\"\"\nscores_dt = []\ntrain_list = []\nfor d in range(1,10):\n    clf = DecisionTreeClassifier(max_depth = d,random_state = 123)\n    clf = clf.fit(x_train, y_train)\n    print(\"Test accuracy: {}\/Max Depth: {}\".format(np.round(clf.score(x_test,y_test),3),d))\n    scores_dt.append(clf.score(x_test,y_test))\n    train_list.append(clf.score(x_train,y_train))\n    \nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])  \n    \nax1.plot(range(1,10),scores_dt,label = \"Test Score\")\nax1.plot(range(1,10),train_list,label = \"Train Score\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Max Depth\")\nax1.set_ylabel(\"Accuracy\")\nax1.grid(True, alpha = 0.5)\nax1.set_title(\"Accuricies for each Max Depth Value\",fontsize = 17)\n\nBest_DT = DecisionTreeClassifier(max_depth = 1 + scores_dt.index(np.max(scores_dt)))\nBest_DT = Best_DT.fit(x_train, y_train)\ny_pred = Best_DT.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy: {}\/Max Depth: {}\".format(np.max(scores_dt), 1 + scores_dt.index(np.max(scores_dt))))\nprint(classification_report(y_pred, y_true))\nDT_prob = Best_DT.predict_proba(x_test)\n\ny_preds = DT_prob[:, 1]\nfpr, tpr, _ = metrics.roc_curve(y_true, y_preds)\nauc_score = metrics.auc(fpr, tpr)\n\nplt.figure(figsize = (10,10))\nplt.title('ROC Curve: Decision Tree')\nplt.plot(fpr, tpr, label = 'AUC = {:.2f}'.format(auc_score))\nplt.plot([0, 1], [0, 1], 'r--')\n\nplt.xlim(-0.1, 1.1)\nplt.ylim(-0.1, 1.1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.legend(loc = 'lower right')\nplt.show()\n\"\"\"\n### Random Forests\n\"\"\"\nscores_rf = []\ntrain_list = []\n\nfor i in range(20,160,20):\n    rf = RandomForestClassifier(n_estimators = i, random_state = 123) #100\n    rf.fit(x_train,y_train)\n    print(\"Test Score: {}\/Number of Estimators: {} \".format(np.round(rf.score(x_test,y_test),3),i))\n    scores_rf.append(rf.score(x_test,y_test))\n    train_list.append(rf.score(x_train,y_train))\n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])  \n\nax1.plot(range(20,160,20),scores_rf,label = \"Test Accuracy\")\nax1.plot(range(20,160,20),train_list,label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"N Estimators\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores for each N Estimator\",fontsize = 17)\nax1.grid(True, alpha=0.5)\n\nBest_rf = RandomForestClassifier(n_estimators = 20*(1+scores_rf.index(np.max(scores_rf))))\nBest_rf = Best_rf.fit(x_train, y_train)\ny_pred = Best_rf.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\n\nprint(\"Best Accuracy: {}\/Max Depth: {}\".format(np.max(scores_rf),\n                                               20*(1+scores_rf.index(np.max(scores_rf)))))\nprint(classification_report(y_pred, y_true))\nrf_prob = Best_rf.predict_proba(x_test)\n\ny_preds = rf_prob[:, 1]\nfpr, tpr, _ = metrics.roc_curve(y_true, y_preds)\nauc_score = metrics.auc(fpr, tpr)\n\nplt.figure(figsize = (10,10))\nplt.title('ROC Curve: Random Forest')\nplt.plot(fpr, tpr, label = 'AUC = {:.2f}'.format(auc_score))\nplt.plot([0, 1], [0, 1], 'r--')\n\nplt.xlim(-0.1, 1.1)\nplt.ylim(-0.1, 1.1)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.legend(loc = 'lower right')\nplt.show()\n\"\"\"\n### Perceptron\n\"\"\"\nscores_per = []\ntrain_list = []\nfor i in np.arange(0.0001, 0.001, 0.0001):\n    perceptron = Perceptron(alpha = i, random_state = 123) \n    perceptron.fit(x_train,y_train)\n    print(\"Test Score: {}\/Alpha: {} \".format(np.round(perceptron.score(x_test,y_test),3),np.round(i,5)))\n    scores_per.append(perceptron.score(x_test,y_test))\n    train_list.append(perceptron.score(x_train,y_train))\n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])      \n\nax1.plot(np.arange(0.0001,0.001, 0.0001),scores_per,label = \"Test Accuracy\")\nax1.plot(np.arange(0.0001,0.001, 0.0001),train_list,label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Alpha\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores for each Alpha\",fontsize = 17)\nax1.grid(True, alpha=0.5)    \n\nBest_per = Perceptron(alpha = 0.0001+0.0001*(1+scores_per.index(np.max(scores_per))))\nBest_per = Best_per.fit(x_train, y_train)\ny_pred = Best_per.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy: {}\/Alpha: {}\".format(np.max(scores_per),0.0001*(1+scores_per.index(np.max(scores_per)))))\nprint(classification_report(y_pred, y_true))\n\"\"\"\n### Stochastic Gradient Descent\n\"\"\"\nscores_SGD = []\ntrain_list = []\nfor i in np.arange(0.05, 0.3, 0.02):\n    sgd = SGDClassifier(epsilon = i, random_state = 123) \n    sgd.fit(x_train,y_train)\n    print(\"Test Score: {}\/Epsilon: {} \".format(np.round(sgd.score(x_test,y_test),3),np.round(i,4)))\n    scores_SGD.append(sgd.score(x_test,y_test))\n    train_list.append(sgd.score(x_train,y_train))\n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])    \n\nax1.plot(np.arange(0.05, 0.3, 0.02),scores_SGD,label = \"Test Accuracy\")\nax1.plot(np.arange(0.05, 0.3, 0.02),train_list,label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Epsilons\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores for each Epsilon\", fontsize = 17)\nax1.grid(True, alpha=0.5)\n\nBest_SGD = SGDClassifier(epsilon = 0.03+0.02*(1 + scores_SGD.index(np.max(scores_SGD))))\nBest_SGD = Best_SGD.fit(x_train, y_train)\ny_pred = Best_SGD.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy: {}\/Epsilon: {}\".format(np.max(scores_SGD),\n                                             0.03+0.02*(1+scores_SGD.index(np.max(scores_SGD)))))\nprint(classification_report(y_pred, y_true))\n\"\"\"\n### Ridge Regression\n\"\"\"\nscores_ridge = []\ntrain_list = []\nfor i in np.arange(0.0005, 0.003, 0.0005):\n    ridge = RidgeClassifier(tol = i, random_state = 123) \n    ridge.fit(x_train,y_train)\n    print(\"Test Score: {}\/Tol: {} \".format(np.round(ridge.score(x_test,y_test),3),np.round(i,4)))\n    scores_ridge.append(ridge.score(x_test,y_test))\n    train_list.append(ridge.score(x_train,y_train))\n\nfig, ax = plt.subplots(1,2, figsize = (17,6))\ngs = fig.add_gridspec(1, 4)\n\ngrid = GridSpec(1,4,left=0.1, bottom=0.05, right=1.2, top=0.94, wspace=0.3, hspace=0.3)\n\nax1 = fig.add_subplot(grid[0:3])\nax2 = fig.add_subplot(grid[3:4])  \n\nax1.plot(np.arange(0.0005, 0.003, 0.0005),scores_ridge,label = \"Test Accuracy\")\nax1.plot(np.arange(0.0005, 0.003, 0.0005),train_list,label = \"Train Accuracy\")\nax1.legend(fontsize = 15)\nax1.set_xlabel(\"Tols\")\nax1.set_ylabel(\"Accuracy\")\nax1.set_title(\"Scores for each Tol\",fontsize = 17)\nax1.grid(True, alpha=0.5)\n\nBest_Ridge = RidgeClassifier(tol = 0.0005*(1+scores_ridge.index(np.max(scores_ridge))))\nBest_Ridge = Best_Ridge.fit(x_train, y_train)\ny_pred = Best_Ridge.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f', ax=ax2,cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"Confusion Matrix\",fontsize = 17)\nplt.show()\n\nprint(\"Best Accuracy: {}\/Tol: {}\".format(np.max(scores_ridge),0.0005*(1+scores_ridge.index(np.max(scores_ridge)))))\nprint(classification_report(y_true, y_pred))\n\"\"\"\n### Naive Bayes\n\"\"\"\nnb = GaussianNB()\nnb.fit(x_train,y_train)\n\nprint(\"Test Accuracy: \",nb.score(x_test,y_test))\n\ny_pred = nb.predict(x_test)\ny_true = y_test\n\ncm = confusion_matrix(y_true,y_pred)\n\nplt.figure(figsize = (6,6))\nsns.heatmap(cm, annot=True,annot_kws = {\"size\": 25}, linewidths=0.5, fmt = '.0f',cmap = \"Blues\",linecolor = \"black\")\nplt.title(\"NB Confusion Matrix\",fontsize = 17)\nplt.show()\n\"\"\"\n### Compile the results\n\"\"\"\nmodels = {\"Models\":[\"Logistic Regression\",\n                       \"KNN\",\n                       \"SVC\",\n                       \"Decision Tree\",\n                       \"Random Forest\",\n                       \"Perceptron\",\n                       \"Sthocastic Gradient Descent\",\n                       \"Ridge\", \"Naive Bayes\"],\n             \"Scores\":[np.max(scores_lr).round(3),\n                       np.max(scores_knn).round(3),\n                       np.max(scores_svm).round(3),\n                       np.max(scores_dt).round(3),\n                       np.max(scores_rf).round(3),\n                       np.max(scores_per).round(3),\n                       np.max(scores_SGD).round(3),\n                       np.max(scores_ridge).round(3),\n                       nb.score(x_test,y_test).round(3)]}\n\n\nmodelsDF = pd.DataFrame(models)\nmodelsDF = modelsDF.sort_values(by = [\"Scores\"])\nmodelsDF.head(len(modelsDF)) \n\ntrace = go.Bar(\n    x = modelsDF[\"Models\"],\n    y = modelsDF[\"Scores\"],\n    text = modelsDF[\"Scores\"],\n    textposition = \"auto\",\n    marker=dict(color = modelsDF[\"Scores\"],colorbar=dict(\n            title=\"ColorScale\"\n        ),colorscale=\"Viridis\",))\n\ndata = [trace]\nlayout = go.Layout(title = \"Comparison of Models\",template = \"plotly_white\")\n\nfig = go.Figure(data = data, layout = layout)\nfig.update_xaxes(title_text = \"Models\")\nfig.update_yaxes(title_text = \"Scores\")\nfig.show()","meta":"{'source': 'AI4Code', 'id': '6e8da18be168fe'}"}
{"id":"77622","text":"\"\"\"\n## **Project Overview**: \n\n| <br\/><font size=\"3\"><b> Focus <\/b><\/font><br\/><br\/>  | <br\/><font size=\"3\"><b> Description <\/b><\/font><br\/><br\/> |\n| :-- | :-- |\n| <br\/><font size=\"3\"> <b>Project Title<\/b> <\/font>  <br\/><br\/>| <br\/><font size=\"3\"> CARLA Image Semantic Segmentation with DeepLabV3+<\/font> <br\/><br\/>|\n| <br\/><font size=\"3\"> <b>Project Type<\/b> <\/font> <br\/><br\/>| <br\/><font size=\"3\">Image Segmentation (Semantic Segmenetation) <\/font> <br\/><br\/>|\n| <br\/><font size=\"3\"><b>Project Objectives<\/b> <\/font>  <br\/><br\/>| <br\/><font size=\"3\">1. Create a Model to predict semantic segmentations of CARLA images<br\/><br\/> 2. Predict masks using the model and compare with ground-truth masks <\/font> <br\/><br\/>|\n| <br\/><font size=\"3\"> <b>Dataset Overview <\/b> <\/font> <br\/><br\/>| <br\/><font size=\"3\"> This dataset provides data images and labeled semantic segmentations captured via CARLA self-driving car simulator. The data which was generated as part of the 2018 Lyft Udacity Perception Challenge consists of **5000** images and their semantic segmentations. <\/font> <br\/><br\/>|\n| <br\/><font size=\"3\"> <b> Model Evaluation Metrics<\/b> <\/font> <br\/><br\/>| <br\/><font size=\"3\"> Accuracy:- Minimum of 92% <br\/> Intersection over Union (IoU):- Minimum IoU: 50%, Max IoU: 80%, Mean IoU: 65% <\/font> <br\/><br\/>|\n| <font size=\"3\"> <b>Image Segmentation Model Type<\/b> <\/font> | <br\/><font size=\"3\"> <a href=\"https:\/\/arxiv.org\/pdf\/1802.02611.pdf\"> <b> DeepLabV3+ Architecture<\/b><\/a> <\/font> <br\/><br\/>|\n| <br\/><font size=\"3\"> <b>Major Libraries Used<\/b> <\/font> <br\/><br\/>| <br\/><font size=\"3\"> <a href=\"https:\/\/keras.io\"><b>Keras<\/b><\/a>, <a href=\"https:\/\/imageio.readthedocs.io\/\"><b>ImageIO<\/b><\/a>, <a href=\"https:\/\/scikit-learn.org\"><b> Scikit-Learn <\/b><\/a>, <a href=\"https:\/\/numpy.org\"><b>Numpy<\/b><\/a>, <a href=\"https:\/\/matplpotlib.org\"><b>Matplotlib<\/b><\/a><\/font> <br\/><br\/>|\n\n<br\/>\n\"\"\"\n\"\"\"\n## **Table of Contents**: \n<font size=\"3\">\n\n- [**1 - Import Required Packages**](#1)\n\n    \n- [**2 - Data Preparation**](#2)\n    - [2.1. Load the images and masks from their directories](#2-1)\n    - [2.2.  Create a data pipeline to read and preprocess our data](#2-2)\n\n    \n- [**3 - Model Architecture and Training**](#3)\n    - [3.1. - DeepLabV3+ Model design](#3-1)\n    - [3.2. - Model training](#3-2)    \n\n    \n- [**4 - Model Evaluation**](#4)\n    - [4.1. - Model Accuracy](#4-1)\n    - [4.2. - Intersection-over-Union (IoU)](#4-2)\n\n    \n- [**5 - Predict image segmentations using the trained Model**](#5)\n    - [5.1. - Create functions to preprocess selected images and display their true state, true mask and predicted mask](#5-1)\n    - [5.2. - Prediction on the train set](#5-2)\n    - [5.3. - Prediction on the validation set](#5-3)\n    - [5.4. - Prediction on the test set](#5-4)    \n    \n<font>\n\"\"\"\n\"\"\"\n<a name='1'><\/a>\n## **1. Import Required Packages**\n\"\"\"\nimport numpy as np\nimport imageio\nimport random\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nimport tensorflow as tf \nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.layers import Activation, Input, Conv2D, MaxPooling2D, BatchNormalization, Conv2DTranspose, concatenate\nfrom tensorflow.keras.models import Model, load_model\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n<a name='2'><\/a>\n## **2. Data Preparation**\n\nThe Lyft Udacity Semantic Segmentation for Self-driving Cars Challenge data (images and masks) is splitted across five directories (dataA, dataB, dataC, dataD, and dataE). As part of the data preparation step, we will load images and masks from all the five directories and carry out the a few preprocessing steps to ensure we provide our model with quality dataset.\n\"\"\"\n\"\"\"\n<a name='2-1'><\/a>\n### **2.1. Load the images and masks from their directories**\n\nIn this data preparation step, we will:\n1. Create 2 lists containing the paths of images and masks\n2. Split the lists into training, validation and test sets\n\"\"\"\n\"\"\"\n#### **2.1.1. Create lists containing the paths of images and masks**\n\nIn this step, we will\n\n* Create a list that contains all the paths to all directories in the main directory (a list that contains the path to dataA, dataB, dataC, dataD, and dataE)\n* Create a function to iterate over all the direcory paths where our data are located (list in 1.) and return the list of the image paths in those directories. \n* Create lists of image and mask paths by initializing the function above\n* Preview some masked and unmasked images by reading them from their paths\n\"\"\"\n\"\"\"\n**A. Create a list that contains all the paths to all directories in the main directory (a list that contains the path to dataA, dataB, dataC, dataD, and dataE)**\n\"\"\"\nimage_path = [\"..\/input\/lyft-udacity-challenge\/\"+\"data\"+i+\"\/\"+\"data\"+i+\"\/CameraRGB\/\" for i in ['A', 'B', 'C', 'D', 'E']]\nmask_path = [\"..\/input\/lyft-udacity-challenge\/\"+\"data\"+i+\"\/\"+\"data\"+i+\"\/CameraSeg\/\" for i in ['A', 'B', 'C', 'D', 'E']]\n\"\"\"\n**Create a function to iterate over all the direcory paths where our data are located (list in 2.1.1.) and return the list of the image paths in those directories**\n\"\"\"\ndef list_image_paths(directory_paths):\n    image_paths = []\n    for directory in range(len(directory_paths)):\n        image_filenames = os.listdir(directory_paths[directory])\n        for image_filename in image_filenames:\n            image_paths.append(directory_paths[directory] + image_filename)\n    return image_paths\n\"\"\"\n**Create lists of image and mask paths by initializing the function above**\n\"\"\"\nimage_paths = list_image_paths(image_path) \nmask_paths = list_image_paths(mask_path)\nnumber_of_images, number_of_masks = len(image_paths), len(mask_paths)\nprint(f\"1. There are {number_of_images} images and {number_of_masks} masks in our dataset\")\nprint(f\"2. An example of an image path is: \\n {image_paths[0]}\")\nprint(f\"3. An example of a mask path is: \\n {mask_paths[0]}\")\n\n\"\"\"\n**Preview random masked and unmasked images by reading them from their paths**\n\"\"\"\nimport random\nnumber_of_samples = len(image_paths)\n\nfor i in range(3):\n    N = random.randint(0, number_of_samples - 1)\n\n    img = imageio.imread(image_paths[N])\n    mask = imageio.imread(mask_paths[N])\n    mask = np.array([max(mask[i, j]) for i in range(mask.shape[0]) for j in range(mask.shape[1])]).reshape(img.shape[0], img.shape[1])\n\n    fig, arr = plt.subplots(1, 3, figsize=(20, 8))\n    arr[0].imshow(img)\n    arr[0].set_title('Image')\n    arr[0].axis(\"off\")\n    arr[1].imshow(mask)\n    arr[1].set_title('Segmentation')\n    arr[1].axis(\"off\")    \n    arr[2].imshow(mask, cmap='Paired')\n    arr[2].set_title('Segmentation')\n    arr[2].axis(\"off\")\n\"\"\"\n#### **2.1.2. Split the image and mask paths into training, validation, and test sets**\n\"\"\"\n# First split the image paths into training and validation sets\ntrain_image_paths, val_image_paths, train_mask_paths, val_mask_paths = train_test_split(image_paths, mask_paths, train_size=0.8, random_state=0)\n\n# Keep part of the validation set as test set\nvalidation_image_paths, test_image_paths, validation_mask_paths, test_mask_paths = train_test_split(val_image_paths, val_mask_paths, train_size = 0.80, random_state=0)\n\nprint(f'There are {len(train_image_paths)} images in the Training Set')\nprint(f'There are {len(validation_image_paths)} images in the Validation Set')\nprint(f'There are {len(test_image_paths)} images in the Test Set')\n\"\"\"\n<a name='2-2'><\/a>\n### **2.2. - Create a data pipeline to read and preprocess our data**\n\nWe will be using the tf.data.Dataset API to load our images and masks for our model to process. The Dataset API allows us to build an asynchronous, highly optimized data pipeline to prevent our GPU from data starvation. It loads data from the disk (images or text), applies optimized transformations, creates batches and sends it to the GPU. Unlike former data pipelines made the GPU, the Dataset API wait for the CPU to load the data, leading to performance issues.\n\nTo do this, we will \n1. Create a function to read image and mask paths and return equivalent arrays\n2. Create a data generator function to read and load images and masks in batches\n3. Create data pipelines for the training, validation and test sets using both functions\n4. Preview sample images and their segmentations from the three dataset categories\n\"\"\"\n\"\"\"\n#### **2.2.1. Create a function to read image and mask paths and return equivalent arrays**\n\nThe **read_image** function will\n1. Read an image and its mask from their paths\n2. Convert the digital image and its mask to image arrays \n3. Normalize the datasets\n4. Resize the image and its masks to a desired dimension\n\"\"\"\ndef read_image(image_path, mask_path):\n    \n    image = tf.io.read_file(image_path)\n    image = tf.image.decode_png(image, channels=3)\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, (256, 256), method='nearest')\n\n    mask = tf.io.read_file(mask_path)\n    mask = tf.image.decode_png(mask, channels=3)\n    mask = tf.math.reduce_max(mask, axis=-1, keepdims=True)\n    mask = tf.image.resize(mask, (256, 256), method='nearest')\n    \n    return image, mask\n\"\"\"\n#### **2.2.2. Create a data generator function to read and load images and masks in batches**\n\n\n\"\"\"\ndef data_generator(image_paths, mask_paths, buffer_size, batch_size):\n    \n    image_list = tf.constant(image_paths) \n    mask_list = tf.constant(mask_paths)\n    dataset = tf.data.Dataset.from_tensor_slices((image_list, mask_list))\n    dataset = dataset.map(read_image, num_parallel_calls=tf.data.AUTOTUNE)\n    dataset = dataset.cache().shuffle(buffer_size).batch(batch_size)\n    \n    return dataset\n\"\"\"\n#### **2.2.3. Create data pipelines for the training, validation and test sets using both functions**\n\"\"\"\nbatch_size = 32\nbuffer_size = 500\n\ntrain_dataset = data_generator(train_image_paths, train_mask_paths, buffer_size, batch_size)\nvalidation_dataset = data_generator(validation_image_paths, validation_mask_paths, buffer_size, batch_size)\ntest_dataset = data_generator(test_image_paths, test_mask_paths, buffer_size, batch_size)\n\"\"\"\n#### **2.2.4. Preview sample images and masks from the three dataset categories**\n\"\"\"\n# Take a batch (32 images and their labelled segmentations from each category of data)\nfor train_images, train_masks in train_dataset:\n    break\nfor validation_images, validation_masks in validation_dataset:\n    break\nfor test_images, test_masks in test_dataset:\n    break\n    \n\nfor i in range(3):\n    N = random.randint(0, batch_size-1)\n    \n    images = [train_images[N], validation_images[N], test_images[N]]\n    masks = [train_masks[N], validation_masks[N], test_masks[N]]\n    title = ['Train Image', 'Validation Image', 'Test Image', 'Train Mask', 'Validation Mask', 'Test Mask']\n\n    fig, arr = plt.subplots(1, 3, figsize=(20, 8))\n    arr[0].imshow(images[i])\n    arr[0].set_title(title[i])\n    arr[0].axis(\"off\")\n    arr[1].imshow(masks[i])\n    arr[1].set_title(title[i+3])\n    arr[1].axis(\"off\")\n    arr[2].imshow(masks[i], cmap='Paired')\n    arr[2].set_title(title[i+3])\n    arr[2].axis(\"off\")\n\"\"\"\n<a name='3'><\/a>\n## **3. Model Architecture and Training**\nWe will using a the **DeepLabv3+ architecture** to train our semantic segmentation model. The DeepLabv3+ is a semantic segmentation architecture that improves upon DeepLabv3 with several improvements, such as adding a simple yet effective decoder module to achieve an encoder-decoder structure. The encoder module processes multiscale contextual information by applying dilated convolution at multiple scales, while the decoder module refines the segmentation results along object boundaries.\n\n<center><img src=\"https:\/\/i.ibb.co\/cXmRSr3\/deeplabv3-plus-diagram.png\" alt=\"deeplabv3-plus-diagram\" border=\"0\"><\/center>\n\n\"\"\"\n\"\"\"\n<a name='3-1'><\/a>\n\n### **3.1. DeepLabV3+ Model Design**\n\"\"\"\ndef convolution_block(block_input, num_filters=256, kernel_size=3, dilation_rate=1, padding=\"same\", use_bias=False):\n    x = layers.Conv2D(\n        num_filters,\n        kernel_size=kernel_size,\n        dilation_rate=dilation_rate,\n        padding=\"same\",\n        use_bias=use_bias,\n        kernel_initializer=keras.initializers.HeNormal(),\n        )(block_input)\n    x = BatchNormalization()(x)\n    x = Activation('relu')(x)\n    \n    return x\ndef DilatedSpatialPyramidPooling(dspp_input):\n    dims = dspp_input.shape\n    x = layers.AveragePooling2D(pool_size=(dims[-3], dims[-2]))(dspp_input)\n    x = convolution_block(x, kernel_size=1, use_bias=True)\n    out_pool = layers.UpSampling2D(\n        size=(dims[-3] \/\/ x.shape[1], dims[-2] \/\/ x.shape[2]), interpolation=\"bilinear\",\n    )(x)\n\n    out_1 = convolution_block(dspp_input, kernel_size=1, dilation_rate=1)\n    out_6 = convolution_block(dspp_input, kernel_size=3, dilation_rate=6)\n    out_12 = convolution_block(dspp_input, kernel_size=3, dilation_rate=12)\n    out_18 = convolution_block(dspp_input, kernel_size=3, dilation_rate=18)\n\n    x = layers.Concatenate(axis=-1)([out_pool, out_1, out_6, out_12, out_18])\n    output = convolution_block(x, kernel_size=1)\n    return output\ndef DeeplabV3(image_size, num_classes):\n    model_input = keras.Input(shape=(image_size, image_size, 3))\n    resnet50 = keras.applications.ResNet50(\n        weights=\"imagenet\", include_top=False, input_tensor=model_input\n    )\n    x = resnet50.get_layer(\"conv4_block6_2_relu\").output\n    x = DilatedSpatialPyramidPooling(x)\n\n    input_a = layers.UpSampling2D(\n        size=(image_size \/\/ 4 \/\/ x.shape[1], image_size \/\/ 4 \/\/ x.shape[2]),\n        interpolation=\"bilinear\",\n    )(x)\n    input_b = resnet50.get_layer(\"conv2_block3_2_relu\").output\n    input_b = convolution_block(input_b, num_filters=48, kernel_size=1)\n\n    x = layers.Concatenate(axis=-1)([input_a, input_b])\n    x = convolution_block(x)\n    x = convolution_block(x)\n    x = layers.UpSampling2D(\n        size=(image_size \/\/ x.shape[1], image_size \/\/ x.shape[2]),\n        interpolation=\"bilinear\",\n    )(x)\n    model_output = layers.Conv2D(num_classes, kernel_size=(1, 1), padding=\"same\")(x)\n    model = tf.keras.Model(inputs=model_input, outputs=model_output)\n    \n    return model\nimg_height = 256\nimg_width = 256\nnum_channels = 3\nfilters = 32\nn_classes = 23\n\nmodel = DeeplabV3(img_height, num_classes=23)\nmodel.summary()\n\"\"\"\n<a name='3-2'><\/a>\n### **3.2. Model Training**\n\"\"\"\nmodel.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])\ncallback = EarlyStopping(monitor='val_accuracy', patience=20, restore_best_weights=True)\nreduce_lr = ReduceLROnPlateau(monitor='val_accuracy',factor=1e-1, patience=5, verbose=1, min_lr = 2e-6)\nbatch_size = 32\nepochs = 30\nhistory = model.fit(train_dataset, \n                    validation_data = validation_dataset, \n                    epochs = epochs, \n                    verbose=1, \n                    callbacks = [callback, reduce_lr], \n                    batch_size = batch_size, \n                    shuffle = True)\nacc = [0.] + history.history['accuracy']\nval_acc = [0.] + history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.ylabel('Accuracy')\nplt.ylim([min(plt.ylim()),1])\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 1, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylabel('Cross Entropy')\nplt.ylim([0,1.0])\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()\nmodel.save('carla-image-segmentation-model.h5')\n\"\"\"\n<a name='4'><\/a>\n## **4. Model Evaluation**\n\nWe will be using Model Accuracy and Mean Intersection-over-Union (mIoU) to evaluate our model performance.\n\"\"\"\n\"\"\"\n<a name='4-1'><\/a>\n### **4.1. Model Accuracy**\n\n\"\"\"\ntrain_loss, train_accuracy = model.evaluate(train_dataset, batch_size = 32)\nvalidation_loss, validation_accuracy = model.evaluate(validation_dataset, batch_size = 32)\ntest_loss, test_accuracy = model.evaluate(test_dataset, batch_size = 32)\nprint(f'Model Accuracy on the Training Dataset: {round(train_accuracy * 100, 2)}%')\nprint(f'Model Accuracy on the Validation Dataset: {round(validation_accuracy * 100, 2)}%')\nprint(f'Model Accuracy on the Test Dataset: {round(test_accuracy * 100, 2)}%')\n\"\"\"\n<a name='4-2'><\/a>\n### **4.2. Intersection-over-Union (IoU)**\n\nThe Intersection-over-Union (IoU), also referred to as the Jaccard index is useful in quantifying the percent overlap between the target mask and the mask prediction output from our model. Recall that the task of semantic segmentation is simply to predict the class of each pixel in an image. So, the IoU aims to evaluate the similarities in the pixels of both the ground true mask and the predicted mask.\n\nSince the size of our ground true masks and the predicted masks size is 256 * 256 * 23 (which is equivalent to 59,069,888 pixels). Hence, our Model's IoU Score for any image in our dataset is the proprortion of the 59,069,888 pixels in the predicted mask that matches with the ground true mask's 59,069,888 pixels. \n\n\n[Kindly Read more on IoU and other Image Segmentation Metrics here](https:\/\/www.jeremyjordan.me\/evaluating-image-segmentation-models\/)\n\"\"\"\ndef iou_score(dataset):\n    \n    \"\"\"\n    Argument:\n        dataset -- the dataset to calculate IoU on\n    \n    Returns:\n        min_iou -- minimum IoU\n        max_iou -- maximum IoU\n        mean_iou -- mean IoU ()\n        \"\"\"\n    # Create empty lists \n    intersections, unions, max_ious, min_ious = [], [], [], []\n    \n    for images, masks in dataset:\n        pred_mask = model.predict(images)\n        intersection = np.logical_and(masks, pred_mask)\n        union = np.logical_or(masks, pred_mask)\n        intersection_sum = np.array([np.sum(inter) for inter in intersection])\n        union_sum = np.array([np.sum(un) for un in union])\n        batch_iou_score = intersection_sum \/ union_sum\n        batch_min_iou = np.amin(batch_iou_score)\n        batch_max_iou = np.amax(batch_iou_score)\n        \n        intersections.append(np.sum(intersection))\n        unions.append(np.sum(union))\n        min_ious.append(batch_min_iou)\n        max_ious.append(batch_max_iou)\n\n    min_iou = np.amin(min_ious)\n    max_iou = np.amax(max_ious)\n    mean_iou = np.sum(intersections) \/ np.sum(unions)   \n    \n    return min_iou, max_iou, mean_iou\ntrain_min_iou, train_max_iou, train_mean_iou = iou_score(train_dataset)\nvalidation_min_iou, validation_max_iou, validation_mean_iou = iou_score(validation_dataset)\ntest_min_iou, test_max_iou, test_mean_iou = iou_score(test_dataset)\nprint(f'IoU on the Training Dataset: \\n Minimum IoU Score: {round(train_min_iou*100, 2)}% \\n Maximum IoU Score: {round(train_max_iou*100, 2)}% \\n Mean IoU Score: {round(train_mean_iou*100, 2)}% \\n')\nprint(f'IoU on the Validation Dataset: \\n Minimum IoU Score: {round(validation_min_iou*100, 2)}% \\n Maximum IoU Score: {round(validation_max_iou*100, 2)}% \\n Mean Iou Score: {round(validation_mean_iou*100, 2)}% \\n')\nprint(f'IoU on the Test Dataset: \\n Minimum IoU Score: {round(test_min_iou*100, 2)}% \\n Maximum IoU Score: {round(test_max_iou*100, 2)}% \\n Mean IoU Score: {round(test_mean_iou*100, 2)}% \\n')\n\"\"\"\n<a name='5'><\/a>\n## **5. Predict image segmentations using the trained Model**\n\nIn this section, we will\n\n1. Create a function to preprocess selected images and display their true state, true mask and predicted mask\n2. Predict and compare masks of images in the training set\n3. Predict and compare masks of images in the validation set\n4. Predict and compare masks of images in the test set\n\"\"\"\n\"\"\"\n<a name='5-1'><\/a>\n### **5.1. Create functions to preprocess selected images and display their true state, true mask and predicted mask**\n\nIn this step, we will:\n1. Load our model\n2. Define a function to create new masks using our model\n3. Define a function to display outputs of this process: an input image, its true mask, and its predicted mask.\n4. Define a function to select images from a specified dataset and return the images, their true masks and their predicted masks.\n\"\"\"\n\"\"\"\n##### **5.1.1. Load our model** \n\"\"\"\n# Load model\nfrom tensorflow.keras.models import Model, load_model\nmodel = load_model('carla-image-segmentation-model.h5')\n\"\"\"\n##### **5.1.2. Define a function to create new masks using our model** \n\"\"\"\ndef create_mask(pred_mask):\n    pred_mask = tf.argmax(pred_mask, axis=-1)\n    pred_mask = pred_mask[..., tf.newaxis]\n    return pred_mask[0]\n\"\"\"\n##### **5.1.3. Define a function to display outputs of this process: an input image, its true mask, and its predicted mask** \n\"\"\"\ndef display(display_list):\n    plt.figure(figsize=(15, 15))\n\n    title = ['Input Image', 'True Mask', 'Predicted Mask']\n\n    for i in range(len(display_list)):\n        plt.subplot(1, len(display_list), i+1)\n        plt.title(title[i])\n        plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i]))\n        plt.axis('off')\n    plt.show()\n\"\"\"\n##### **5.1.4. Define a function to select images from a specified dataset and return the images, their true masks and their predicted masks** \n\"\"\"\ndef show_predictions(dataset, num):\n    \"\"\"\n    Displays the first image of each of the num batches\n    \"\"\"\n    if dataset:\n        for image, mask in dataset.take(num):\n            pred_mask = model.predict(image)\n            display([image[0], mask[0], create_mask(pred_mask)])\n    else:\n        display([sample_image, sample_mask,\n             create_mask(model.predict(sample_image[tf.newaxis, ...]))])\n\"\"\"\n<a name='5-2'><\/a>\n### **5.2. Predict and compare masks of images in the training set**\n\"\"\"\nshow_predictions(train_dataset, 6)\n\"\"\"\n<a name='5-3'><\/a>\n### **5.3. Predict and compare masks of images in the validation set**\n\"\"\"\nshow_predictions(validation_dataset, 6)\n\"\"\"\n<a name='5-4'><\/a>\n### **5.4. Predict and compare masks of images in the test set**\n\"\"\"\nshow_predictions(test_dataset, 6)","meta":"{'source': 'AI4Code', 'id': '8e8acf552dd34b'}"}
{"id":"85665","text":"\"\"\"\n# Data analysis and Forecasting of COVID19 cases in Italy\n\"\"\"\n\"\"\"\n## <font color='white'><span style='background :black' >The notebook is updated daily. Latest update: <font color='red'>Jan 30th with Jan 30th data.<\/font>\n\"\"\"\n\"\"\"\n**The following project is about modeling daily COVID19 cases in Italy by Machine Learning algorithms, with the goal of forecasting the cases for future days.<br>\nThe time series modeling will be performed by Prophet by Facebook, Neural Prophet and SARIMAX models.**\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/pnhV2Ow.png\" width=\"900px\">\n\"\"\"\n\"\"\"\n# Main results Dashboard:\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/2NXrfU6.png\" width=\"900px\">\n\"\"\"\n\"\"\"\n**All the three algorithms performed well on the last 4 weeks of data compared to the actual values, with similar predicted cases.** <br>\nMoreover, **the forecasted values are also similar**.\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/7G22LLn.png\" width=\"900px\">\n\"\"\"\n\"\"\"\nWe can clearly see that **the number of weekly cases is getting more stable and lower in terms of Mean, Median and Std. Deviation.**<br>\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/oycem0Q.png\" width=\"900px\">\n\"\"\"\n\"\"\"\n**Trend and seasionality plots analysis:**\n- Trend: We can see the trends of the 5 covid waves: the steeper one is the current one (Jan 2022).\n- Holidays: We can see the effects of holidays on the number of new cases.\n- Weekly seasonality: We can observe the drop of cases on Monday, since on Sunday less tests are carried, and an overall increase over the week, with the highest number of positive cases found around Friday.\n- Yearly seasonality: We can observe the drop in cases from May to November, seen both in 2020 and 2021\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/QuKpBxc.png\" width=\"900px\">\n\"\"\"\n\"\"\"\nOverall, we can see that **the average predicted values fit well the last 4 weeks data.**\n\"\"\"\n\"\"\"\n### Install necessary libraries: pmdarima, neuralprophet and holidays\n\"\"\"\n!pip install pmdarima\npip install neuralprophet\npip install holidays\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.metrics import mean_squared_error\n\nimport calendar\n\nimport holidays\n\nimport fbprophet\nfrom fbprophet import Prophet\n\nfrom neuralprophet import NeuralProphet\n\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\nimport pmdarima as pm\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\n\nseed=42\n\nplt.style.use(\"seaborn-whitegrid\")\nplt.rc(\"figure\", autolayout=True)\nplt.rc(\"axes\", labelweight=\"bold\", labelsize=\"large\", titleweight=\"bold\", titlesize=14, titlepad=10)\n\"\"\"\n## Custom defined functions\n\"\"\"\ndef mape(y_true, y_pred): \n    y_true, y_pred = np.array(y_true), np.array(y_pred)\n    return np.mean(np.abs((y_true - y_pred) \/ y_true)) * 100\n\"\"\"\n## Loading the data\n\"\"\"\n\"\"\"\nWe can fetch the data from the official government github repository, where the data is updated daily at 18:00.\n\"\"\"\ndf = pd.read_csv('https:\/\/raw.githubusercontent.com\/pcm-dpc\/COVID-19\/master\/dati-regioni\/dpc-covid19-ita-regioni.csv', parse_dates=['data'])\ndf.tail()\ndf.info()\n\"\"\"\n**NOTE: We can see that the dataframe contains lots of columns. For our analysis we will just focus on the columns 'data' ( 'date' in english) and 'nuovi_positivi' ('new cases' in english).<br>**\n\"\"\"\n\"\"\"\nFirst, we convert the date column to pandas datetime format.\n\"\"\"\ndf['data'] = pd.to_datetime(df['data']).dt.normalize()\n\"\"\"\nMoreover, we get today's and tomorrow's date, since they will be useful for future plots.\n\"\"\"\ntoday = df['data'].iloc[-1]\ntomorrow = today + pd.DateOffset(days=1)\n\"\"\"\nSince the data is divided by region for each day, we create a new dataframe 'df_italy' where we group the rows by the column 'data' ( 'date' in english) to get the total daily data in Italy.\n\"\"\"\ndf_italy=df.groupby('data').sum()\nplt.figure(figsize=(10,4))\nplt.title('COVID19 new cases in Italy', fontsize=20)\nplt.plot(df_italy['nuovi_positivi'])\nplt.text(df_italy.index[0],np.max(df_italy['nuovi_positivi'])-30000,\n         'Todays new cases:{}'.format(df_italy['nuovi_positivi'].iloc[-1]),\n         fontsize=20,\n         bbox=dict(facecolor='white', alpha=1))\nplt.ylabel('New cases')\nplt.show()\nplt.figure(figsize=(13,6))\nplt.title('COVID19 new cases in Italy during the last 4 weeks', fontsize=30)\nplt.plot(df_italy[-28:].index, df_italy[-28:].nuovi_positivi, marker='o', color='red')\nplt.bar(df_italy[-28:].index, df_italy[-28:].nuovi_positivi, color='#000080', alpha=0.8)\nplt.ylabel('New Cases', fontsize=15)\nplt.text(df_italy[-29:].index[0],np.max(df_italy[-28:]['nuovi_positivi'])-5000,\n         'Todays new cases:{}'.format(df_italy['nuovi_positivi'].iloc[-1]),\n         fontsize=20,\n         bbox=dict(facecolor='white', alpha=1))\nplt.grid(visible=None, axis='x')\nplt.show()\n\"\"\"\n## Holidays\n\"\"\"\n\"\"\"\nIn the following, we will define a 'holiday' column to include boolean values to check if a day is a holiday or not. We decided to include this column since, after a first analysis, it looks like that on days after holidays the number of new cases decreases, since on holidays usually less PCR tests are performed. By specifing this information to the prediction models, we can obtain a more accurate forecast.\n\"\"\"\n\"\"\"\nWe create a list compregension to extract the holidays from the holidays library, and add bolean values to a list is_holiday depending if the date is a holiday (value=1) or not (value=0).\n\"\"\"\nis_holiday = [1 if x==True else 0 for x in [day in holidays.Italy() for day in df_italy.index]]\n\"\"\"\nThen we assign these values to a new column 'holiday' of the dataframe.\n\"\"\"\ndf_italy['holiday'] = is_holiday\n\"\"\"\n# Weekly case distribution analysis\n\"\"\"\n\"\"\"\nNext we will analyze the weekly distribution to check how the mean, median and standard deviation of new cases changed during the weeks.<br>\nFirst, we create a list of the days for each date.\n\"\"\"\nday = [calendar.day_name[day.weekday()] for day in df_italy.index]\n\"\"\"\nThen we create a new column in the dataframe to host this list.\n\"\"\"\ndf_italy['day'] = day\n\"\"\"\nNow we need to create a function that select only the last 4 weeks in the dataframe. We decided to create a new dataframe 'df_italy_small' and assign it the last 34 rows of the  dataframe 'df_italy'. Then we check if the current day, and in case it is a Sunday then we can copy 28 rows (4 weeks) of data and assign to a new dataframe 'df_4weeks'\n\"\"\"\nidx=0 #index to move along the rows\ndf_4weeks = pd.DataFrame() #empty dataframe\ndf_italy_small = df_italy.iloc[-34:].iloc[::-1] #consider 34 rows (worst case)\n\nwhile(True):\n    if df_italy_small.iloc[idx:].day[0] == 'Sunday':\n        df_4weeks=df_italy_small.iloc[idx:idx+28]\n        break\n    else:\n        idx+=1\n\"\"\"\nThen we extract the 4 values for the 4 weeks, and add a column to indicate the week.\n\"\"\"\ndf_week1=df_4weeks.iloc[:7]\ndf_week1['week']='1 week ago'\n\ndf_week2=df_4weeks.iloc[7:14]\ndf_week2['week']='2 weeks ago'\n\ndf_week3=df_4weeks.iloc[14:21]\ndf_week3['week']='3 weeks ago'\n\ndf_week4=df_4weeks.iloc[21:28]\ndf_week4['week']='4 weeks ago'\n\ndf_4weeks_2 = pd.concat([df_week1, df_week2, df_week3, df_week4])\n\"\"\"\nWe extract also the mean, median and standard deviation of the cases during these weeks.\n\"\"\"\nmean_1 = np.round(df_week1.nuovi_positivi.mean(),0)\nmedian_1 = np.round(df_week1.nuovi_positivi.median(),0)\nstd_1 = np.round(df_week1.nuovi_positivi.std(),0)\n\nmean_2 = np.round(df_week2.nuovi_positivi.mean(),0)\nmedian_2 = np.round(df_week2.nuovi_positivi.median(),0)\nstd_2 = np.round(df_week2.nuovi_positivi.std(),0)\n\nmean_3 = np.round(df_week3.nuovi_positivi.mean(),0)\nmedian_3 = np.round(df_week3.nuovi_positivi.median(),0)\nstd_3 = np.round(df_week3.nuovi_positivi.std(),0)\n\nmean_4 = np.round(df_week4.nuovi_positivi.mean(),0)\nmedian_4 = np.round(df_week4.nuovi_positivi.median(),0)\nstd_4 = np.round(df_week4.nuovi_positivi.std(),0)\n\"\"\"\nAnd create ad additional dataframe where we include the week and the three statistics.\n\"\"\"\ndf_stats = pd.DataFrame({'week':['1 week ago','2 weeks ago','3 weeks ago','4 weeks ago'],\n                         'mean':[mean_1,mean_2,mean_3,mean_4],\n                         'median':[median_1,median_2,median_3,median_4],\n                         'std':[std_1,std_2,std_3,std_4]})\ndf_stats\n_, ax = plt.subplots(2,2,figsize=(14,9))\nplt.suptitle('Analysis of weekly COVID19 cases over last 4 weeks', fontsize=32)\n\n##PLOT 1\n\nsns.kdeplot(x='nuovi_positivi', data=df_week4, label='4 weeks ago', shade=1,ax=ax[0,0])\nsns.kdeplot(x='nuovi_positivi', data=df_week3, label='3 weeks ago', shade=1,ax=ax[0,0])\nsns.kdeplot(x='nuovi_positivi', data=df_week2, label='2 weeks ago', shade=1,ax=ax[0,0])\nsns.kdeplot(x='nuovi_positivi', data=df_week1, label='1 week ago', shade=1,ax=ax[0,0])\n\nax[0,0].axvline(mean_1, linewidth=1.5, color='red', linestyle='--')\nax[0,0].axvline(mean_2, linewidth=1.5, color='green', linestyle='--')\nax[0,0].axvline(mean_3, linewidth=1.5, color='orange', linestyle='--')\nax[0,0].axvline(mean_4, linewidth=1.5, color='blue', linestyle='--')\n\nax[0,0].legend(fontsize=13,fancybox=True, shadow=True, frameon=True, loc=\"upper left\")\nax[0,0].set_xlabel('New Cases', fontsize=15)\nax[0,0].set_title('New cases Distribution ', fontsize=20)\n\n##PLOT 2\ng = sns.barplot(y='mean', x='week', data=df_stats.iloc[::-1] ,ax=ax[0,1], ci=False)\ng.bar_label(g.containers[0], padding=2, fontsize=16, color='black')\nsns.lineplot(y='mean', x='week', data=df_stats.iloc[::-1], ax=ax[0,1], ci=False, color='black',linewidth=1, linestyle='--')\nax[0,1].set_ylabel('New Cases', fontsize=15)\nax[0,1].set_xlabel(' ')\nax[0,1].set_title('Mean cases', fontsize=20)\n\n##PLOT 3\ng = sns.barplot(y='median', x='week', data=df_stats.iloc[::-1] ,ax=ax[1,0], ci=False)\ng.bar_label(g.containers[0], padding=2, fontsize=16, color='black')\nsns.lineplot(y='median', x='week', data=df_stats.iloc[::-1], ax=ax[1,0], ci=False, color='black',linewidth=1, linestyle='--')\nax[1,0].set_ylabel('New Cases', fontsize=15)\nax[1,0].set_xlabel(' ')\nax[1,0].set_title('Median cases', fontsize=20)\n\n##PLOT 4\ng = sns.barplot(y='std', x='week', data=df_stats.iloc[::-1] ,ax=ax[1,1], ci=False)\ng.bar_label(g.containers[0], padding=2, fontsize=16, color='black')\nsns.lineplot(y='std', x='week', data=df_stats.iloc[::-1], ax=ax[1,1], ci=False, color='black',linewidth=1, linestyle='--')\nax[1,1].set_ylabel('New Cases', fontsize=16)\nax[1,1].set_xlabel(' ')\nax[1,1].set_title('Weekly Standard Deviation', fontsize=20)\n\n\nplt.show()\n\"\"\"\n**We can clearly see that the number of weekly cases is getting more stable and lower in terms of Mean, Median and Std. Deviation.**\n\"\"\"\n\"\"\"\n# Time series modeling and Forecasting \n\"\"\"\n\"\"\"\nNow we consider just 2 columns for the time series forecasting: 'new_cases' and 'holiday'.\n\"\"\"\ndf = df_italy.copy()\ndf = df[['nuovi_positivi','holiday']]\ndf.head()\n\"\"\"\nMoreover, we also define some time windows which will be useful during the forecasting analysis and plotting.\n\"\"\"\nprediction_window = 28 #testing window (4 weeks of data)\nforecast_window = 7 # forecasting window (1 week)\nwindow = prediction_window + forecast_window #prediction + forecasting window\n\"\"\"\n# Prophet \n\"\"\"\n\"\"\"\n**The first model we use is Prophet by Facebook Research.**<br>\nThe model requires the dataset to have just 2 columns: 'ds' which host the dates and 'y' which hosts the time series values: for this reason we define a new dataframe 'df_p' which will present just these two columns. The holiday column will be specified by calling a method on the model.\n\"\"\"\ndf_p = df['nuovi_positivi'].reset_index().copy()\ndf_p = df_p.rename(columns={'data': 'ds', 'nuovi_positivi': 'y'})\n\"\"\"\nNow we can define the Prophet model.\n\"\"\"\nprophet_model = Prophet(n_changepoints=50, # hyperparameter\n                        seasonality_mode='multiplicative',\n                       changepoint_prior_scale=10) # hyperparameter\n\"\"\"\nWe add both weekly and yearly seasonality.\n\"\"\"\nprophet_model.add_seasonality('weekly', period = 7, fourier_order = 5)\nprophet_model.add_seasonality('yearly', period = 365, fourier_order = 25)\n\"\"\"\nSince we cannot add the holiday column as we defined previously, we add the holidays using the 'add_country_holidays()' method of the prophet model class.\n\"\"\"\nprophet_model.add_country_holidays(country_name='Italy')\nprophet_model.fit(df_p)\n\"\"\"\n# Prophet Forecasting\n\"\"\"\n\"\"\"\nTo perform the forecasting, we need to first create a forecast dataframe to include future days. As stated before, we will forecast the time series values of the next week.\n\"\"\"\nfuture = prophet_model.make_future_dataframe(periods=forecast_window)\n\"\"\"\nThen we call the 'predict()' method of the prophet model, where we specify the dataframe with future days 'future'\n\"\"\"\nforecast = prophet_model.predict(future)\nprophet_model.plot(forecast);\nplt.title(\"COVID19 new cases in Italy with forecasting by Prophet\", fontsize=23)\nplt.ylabel(\"New cases\", fontsize=15)\nplt.xlabel('')\nplt.show()\n\"\"\"\n**At a first glance, we can see that the predicted time series (in blue) fits well the original data (black dots).**\n\"\"\"\n\"\"\"\nMoreover, it could be interesting to see the components (the trend for example) of the predicted time series by calling the 'plot_components()' method of the prophet model.\n\"\"\"\nfig = prophet_model.plot_components(forecast)\n\"\"\"\nPlots analysis:\n- Trend: We can see the trends of the 5 covid waves: the steeper one is the current one (Jan 2022).\n- Holidays: We can see the effects of holidays on the number of new cases.\n- Weekly seasonality: We can observe the drop of cases on Monday, since on Sunday less tests are carried, and an overall increase over the week, with the highest number of positive cases found around Friday.\n- Yearly seasonality: We can observe the drop in cases from May to November, seen both in 2020 and 2021\n\"\"\"\n\"\"\"\nNext, we want to make a custom plot to check the forecasted days. We first create a dataframe including the dates (ds), predicted values (yhat) and confidence intervals( yhat_lower and yhat_upper).\n\"\"\"\nforecast_df = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]\nforecast_df\nplt.figure(figsize=(15,5))\nplt.title('COVID19 new cases in Italy with forecasting by Prophet', fontsize=22)\n#Actual cases\nplt.plot(df[-prediction_window:].index, df[-prediction_window:]['nuovi_positivi'], label='Actual cases', marker='o')\n\n#PROPHET\nplt.plot(forecast_df[-window:]['ds'],forecast_df[-window:]['yhat'],color='#006400',label='PROPHET', marker='o')\nplt.fill_between(forecast_df[-forecast_window-1:]['ds'], forecast_df[-forecast_window-1:]['yhat_lower'],forecast_df[-forecast_window-1:]['yhat_upper'], color='lightgreen', alpha=0.5)\n\nplt.axvline(today, linewidth=1.5, color='red', linestyle=\"--\")\nplt.legend(loc='upper left', fontsize=14, fancybox=True, shadow=True, frameon=True)\nplt.ylabel('New cases', fontsize=20)\nplt.xticks(forecast_df[-prediction_window-forecast_window:]['ds'], rotation=80, fontsize=14)\nplt.yticks(fontsize=15)\n\nplt.grid(visible=None, axis='x')\nplt.show()\nmape_prophet = mape(forecast_df[-forecast_window-prediction_window:-forecast_window]['yhat'],df_p[-prediction_window:]['y'])\nrmse_prophet = mean_squared_error(forecast_df[-forecast_window-prediction_window:-forecast_window]['yhat'],df_p[-prediction_window:]['y'], squared=False)\n\nprint('PROPHET RMSE: {:.0f} Cases'.format(rmse_prophet))\nprint('PROPHET MAPE: {:.1f} %'.format(mape_prophet))\n\"\"\"\n**Prophet achives a good MAPE during the last 4 weeks of data, but fails to predict weekly extreme values, such as the very low values of cases found on Sundays.**\n\"\"\"\n\"\"\"\n# Neural Prophet\n\"\"\"\n\"\"\"\n**Next we will use a model called Neural Prophet, built using PyTorch neural networks on top of the original Prophet model by facebook**.<br>\nThe procedure to make a model by using this algorithm will be very similar to the one seen for Prophet.\n\"\"\"\nm = NeuralProphet(\n    n_changepoints=50,\n    yearly_seasonality=False,\n    weekly_seasonality=False,\n    daily_seasonality=False,\n    seasonality_mode=\"multiplicative\",\n    n_forecasts=forecast_window,\n    n_lags=forecast_window,\n    learning_rate=1.0,\n)\nm.add_seasonality('weekly_custom', period = 7, fourier_order = 5)\nm.add_seasonality('yearly_custom', period = 365, fourier_order = 20)\nm.add_country_holidays(country_name='Italy')\nmetrics = m.fit(df_p, freq=\"D\")\n\"\"\"\n# Neural Prophet Forecasting\n\"\"\"\nfuture = m.make_future_dataframe(df_p, periods=forecast_window, n_historic_predictions=len(df_p)-forecast_window)\nforecast_df_nn = m.predict(future)\nforecast_plot = m.plot(forecast_df_nn)\nplt.title(\"COVID19 new cases in Italy with forecasting by Neural Prophet\", fontsize=26)\nplt.xlabel(\"\")\nplt.ylabel(\"New cases\", fontsize=15)\nplt.show()\nfig2 = m.plot_components(forecast_df_nn)\n\"\"\"\nThe components are comparable to those obtained using Prophet.\n\"\"\"\nforecast_plot = m.plot(forecast_df_nn.iloc[-prediction_window:])\nplt.title(\"New COVID cases in Italy by Neural Prophet (last 2 weeks)\", fontsize=20)\nplt.xlabel(\"Date\")\nplt.ylabel(\"New cases\")\nplt.show()\n\"\"\"\n**We can see that there are 7 different yhat prediction columns.**\n\"\"\"\nfor i in range(7):\n    col = 'yhat' + str(i+1)\n    mape_test = mape(forecast_df_nn.iloc[-window:-forecast_window][col],df_p.iloc[-prediction_window:]['y'])\n    rmse_test = mean_squared_error(forecast_df_nn.iloc[-window:-forecast_window][col],df_p.iloc[-prediction_window:]['y'], squared=False)\n    print('PROPHET RMSE {}: {:.0f} Cases'.format(i+1,rmse_test))\n    print('PROPHET MAPE {}: {:.1f} %'.format(i+1,mape_test))\n\"\"\"\n**We will create a new 'yhat_avg' column to host an average prediction of the 7 'yhat' values.**\n\"\"\"\nforecast_df_nn['yhat_avg'] = forecast_df_nn[['yhat1', 'yhat2', 'yhat3', 'yhat4', 'yhat5', 'yhat6', 'yhat7']].mean(axis=1)\nplt.figure(figsize=(15,6))\nplt.title('COVID19 new cases in Italy with forecasting by Neural Prophet', fontsize=20)\n\n#Actual cases\nplt.plot(df[-prediction_window:].index, df[-prediction_window:]['nuovi_positivi'], label='Actual cases', marker='o')\n\n#Neural Prophet predicted cases\nplt.plot(forecast_df_nn[-window:]['ds'],forecast_df_nn[-window:]['yhat_avg'],color='purple',label='PROPHET-Forecast', marker='o')\n\nplt.axvline(today, linewidth=1.5, color='red', linestyle=\"--\")\nplt.legend(loc='upper left', fontsize=14, fancybox=True, shadow=True, frameon=True)\nplt.ylabel('New cases', fontsize=20)\nplt.xticks(forecast_df[-prediction_window-forecast_window:]['ds'], rotation=80, fontsize=14)\nplt.yticks(fontsize=15)\n\nplt.grid(visible=None, axis='x')\nplt.show()\nmape_prophet_nn = mape(forecast_df_nn.iloc[-window:-forecast_window]['yhat_avg'],df_p.iloc[-prediction_window:]['y'])\nrmse_prophet_nn = mean_squared_error(forecast_df_nn.iloc[-window:-forecast_window]['yhat_avg'],df_p.iloc[-prediction_window:]['y'], squared=False)\nprint('PROPHET RMSE : {:.0f} Cases'.format(rmse_prophet_nn))\nprint('PROPHET MAPE : {:.1f} %:'.format(mape_prophet_nn))\n\"\"\"\n**Neural Prophet seems to fit the data very well and make reasonable predictions for the next days.**\n\"\"\"\n\"\"\"\n# SARIMAX\n\"\"\"\n\"\"\"\n**The third model we will develop is a SARIMAX model.<br>**\nBefore starting the modeling, we first check the time series' stationarity performing the Augmented Dickey Fuller test (ADF), also to understand the best value for the D parameter of the model (integrative term).\n\"\"\"\nresult=adfuller(df['nuovi_positivi'].dropna())\nprint(f'ADF Statistics:{result[0]}')\nprint(f'p-value:{result[1]}')\n\"\"\"\nThe p-value is higher than 0.05. This means that the time serie is non stationary with a confidence of 95%. Next we will check if with a one step differentiation, the time serie become stationary (in terms of a trendless time series).\n\"\"\"\nresult=adfuller(df['nuovi_positivi'].diff().dropna())\nprint(f'ADF Statistics:{result[0]}')\nprint(f'p-value:{result[1]}')\n\"\"\"\nAfter a 1-order difference the p-value is lower than 0.05.\n\"\"\"\n\"\"\"\n## ACF AND PACF\n\"\"\"\n\"\"\"\nTo have a better idea of possible the autoregressive parameter (p) and moving average parameter (q) of the SARIMAX model, we can check the auto-correlation function (ACF) and partial auto-correlation function (PACF).\n\"\"\"\nfig, (ax1, ax2)=plt.subplots(2,1,figsize=(8,8))\n\nplot_acf(df['nuovi_positivi'],lags=30, zero=False, ax=ax1)\nplot_pacf(df['nuovi_positivi'],lags=30, zero=False, ax=ax2)\nplt.show()\n\"\"\"\nThe series looks indeed non stationary from these plots, and we cannot easily identify good values of p and q. <br>\nFor this reason we will use the convenient auto *arima module* to find good parameters for the sarimax model.\n\"\"\"\n\"\"\"\n## AUTO ARIMA\n\"\"\"\nresults=pm.auto_arima(df['nuovi_positivi'], start_p=0, d=None, start_q=0, max_p=3, max_q=3,\n                      seasonal=True, m=7, D=None, test='adf', start_P=0, start_Q=0, max_P=3, max_Q=3,\n                      information_criterion='aic', trace=True, error_action='ignore',\n                      trend=None, exog=df['holiday'],with_intercept=True, stepwise=True)\nmodel=SARIMAX(df['nuovi_positivi'], order=(0,1,1), seasonal_order=(2,0,0,7), exog = df['holiday'])\nresults=model.fit()\nresults.summary()\nresults.plot_diagnostics(figsize=(8,8))\nplt.show()\n\"\"\"\nThese plots indicate a good but improvable model. This is probably due to the high variability of the time series among the different waves.<br>\n\"\"\"\n\"\"\"\n# SARIMAX Forecasting\n\"\"\"\n\"\"\"\n## SARIMAX Prediction\n\"\"\"\n\"\"\"\nOur goal now is to create a dataframe which will host the model test predictions (last 4 weeks of data) and the forecast values (future 7 days).<br>\nWe start by creating the prediction dataset.\n\"\"\"\nprediction = results.get_prediction(start=-prediction_window, exog = df['holiday'])\nmean_prediction = prediction.predicted_mean\n\"\"\"\nMoreover, we also get the confidence intervals from the sarimax prediction\n\"\"\"\nconfi_int_p = prediction.conf_int()\nlower_limits_p = confi_int_p.iloc[:,0]\nupper_limits_p = confi_int_p.iloc[:,1]\n\"\"\"\nThen we create a new dataframe which will include 3 columns: predicted value 'yhat' and the upper and lower values for yhat (confidence interval)\n\"\"\"\nlower_today = np.full([1, prediction_window], np.nan).flatten() #empty list with length = 28 (4 weeks)\nupper_today = np.full([1, prediction_window], np.nan).flatten() #empty list with length = 28 (4 weeks)\n\"\"\"\nWe also define the confidence interval for the prediction of today's new cases: if we dont do so, the following plot will have a 'gap' for the forecast value.\n\"\"\"\nlower_today[-1] = confi_int_p.iloc[:,0][-1] # lower value for prediction of todays value\nupper_today[-1] = confi_int_p.iloc[:,1][-1] # upper value for prediction of todays value\nsarimax_prediction = pd.DataFrame({'yhat':mean_prediction, 'y_lower':lower_today,'y_upper': upper_today})\n\"\"\"\n## SARIMAX FORECAST\n\"\"\"\n\"\"\"\nWe will create a forecast dataframe similarly how we created the prediction dataframe.\n\"\"\"\nforecast = results.get_forecast(steps=forecast_window, exog = df['holiday'].iloc[-forecast_window:])\nmean_forecast=forecast.predicted_mean\n#Confidence Intervals for forecasting\nconfi_int_f=forecast.conf_int()\nlower_limits_f=confi_int_f.iloc[:,0]\nupper_limits_f=confi_int_f.iloc[:,1]\nsarimax_forecast = pd.DataFrame({'yhat':mean_forecast, 'y_lower':lower_limits_f,'y_upper':upper_limits_f})\n\"\"\"\nFinally we append the forecast dataframe to the prediction dataframe.\n\"\"\"\nsarimax_results = sarimax_prediction.append(sarimax_forecast)\nplt.figure(figsize=(16,6))\nplt.title('COVID19 new cases in Italy with forecasting by SARIMAX', fontsize=30)\n\n\n#Actual cases\nplt.plot(df[-prediction_window:].index,df[-prediction_window:]['nuovi_positivi'], label='Actual cases', marker='o')\n\n#sarimax\nplt.plot(sarimax_results.index, sarimax_results.yhat,color='purple',label='SARIMAX', marker='o')\nplt.fill_between(sarimax_results[-forecast_window-1:].index, sarimax_results[-forecast_window-1:].y_lower, sarimax_results[-forecast_window-1:].y_upper, color='purple', alpha=0.1)\n\n#text = 'Today\\'s new cases : {:.0f}\\nTomorrows new cases : {:.0f}'.format(float(df['nuovi_positivi'][-1:]),mean_forecast[0])\n#plt.text(today + pd.DateOffset(days=1), np.min(df[-prediction_window:]['nuovi_positivi']), text, bbox=dict(facecolor='white', alpha=1), fontsize=14)\n\n\nplt.axvline(today, linewidth=1.5, color='red', linestyle=\"--\")\n#plt.text(today, np.max(mean_forecast), 'Forecast->', bbox=dict(facecolor='white', alpha=1),fontsize=17)\n\nplt.legend(loc='upper left', fontsize=14, fancybox=True, shadow=True, frameon=True)\nplt.ylabel('New cases', fontsize=20)\nplt.xticks(forecast_df[-prediction_window-forecast_window:]['ds'], rotation=80, fontsize=14)\nplt.yticks(fontsize=15)\nplt.grid(visible=None, axis='x')\nplt.show()\nmape_sarimax= mape(df[-prediction_window:]['nuovi_positivi'], mean_prediction.values)\nrmse_sarimax = mean_squared_error(df[-prediction_window:]['nuovi_positivi'], mean_prediction.values, squared=False)\n\nprint('SARIMAX RMSE: {:.0f} Cases'.format(rmse_sarimax))\nprint('SARIMAX MAPE: {:.1f} %'.format(mape_sarimax))\n\"\"\"\n**SARIMAX seems to have predicted decently last weeks data, with high errors on the previous weeks. Nonetheless, the predicted cases for the next days look reasonable compared to the current week cases.**\n\"\"\"\n\"\"\"\n# Results Summary\n\"\"\"\npd.DataFrame({'Model':['Prophet','Neural Prophet','SARIMAX'],'MAPE': [mape_prophet,mape_prophet_nn,mape_sarimax],'RMSE':[rmse_prophet,rmse_prophet_nn,rmse_sarimax]}).set_index('Model')\nplt.figure(figsize=(18,8))\nplt.title('COVID19 new cases in Italy with Forecasted cases by ML models', fontsize=28)\n#Actual cases\nplt.bar(df[-prediction_window:].index, df[-prediction_window:]['nuovi_positivi'], label='Actual cases', color='silver', edgecolor=\"black\", linewidth=2.0, alpha=0.6)\n#PROPHET\nplt.plot(forecast_df[-window:]['ds'],forecast_df[-window:]['yhat'],color='blue',label='Prophet', marker='o',linewidth=3.0)\nplt.fill_between(forecast_df[-forecast_window-1:]['ds'], forecast_df[-forecast_window-1:]['yhat_lower'],forecast_df[-forecast_window-1:]['yhat_upper'], color='blue', alpha=0.1)\n\n#NEURAL PROPHET\nplt.plot(forecast_df_nn[-window:]['ds'],forecast_df_nn[-window:]['yhat_avg'],color='green',label='Neural Prophet', marker='o',linewidth=3.0)\n\n#sarimax\nplt.plot(sarimax_results.index, sarimax_results.yhat,color='red',label='SARIMAX', marker='o',linewidth=3.0)\nplt.fill_between(sarimax_results[-forecast_window-1:].index, sarimax_results[-forecast_window-1:].y_lower, sarimax_results[-forecast_window-1:].y_upper, color='red', alpha=0.1)\n\n\ntext = 'Today\\'s new cases : {:.0f}\\nTomorrow\\'s new cases:\\nProphet : {:.0f}\\nNeural Prophet : {:.0f}\\nSARIMAX : {:.0f}'.format(float(df['nuovi_positivi'][-1:]),forecast_df[forecast_df['ds']==str(tomorrow)]['yhat'].values[0],forecast_df_nn[forecast_df_nn['ds']==str(tomorrow)]['yhat_avg'].values[0],mean_forecast[0])\nplt.text(today + pd.DateOffset(days=1), 180000, text, bbox=dict(facecolor='white', alpha=1), fontsize=17)\n\nplt.axvline(today, linewidth=4, color='black', linestyle=\"--\")\nplt.legend(fontsize=12, bbox_to_anchor=(0.12, 1.0), fancybox=True, shadow=True, frameon=True)\nplt.ylabel('New cases', fontsize=20)\nplt.xticks(forecast_df[-prediction_window-forecast_window:]['ds'], rotation=80, fontsize=14)\nplt.yticks(fontsize=15)\nplt.grid(visible=None, axis='x')\n\nplt.show()\nprint('Today\\'s new cases : {:.0f}'.format(float(df['nuovi_positivi'][-1:])))\nprint('Tomorrows new cases according to SARIMAX : {:.0f}'.format(mean_forecast[0]))\nprint('Tomorrows new cases according to PROPHET : {:.0f}'.format(forecast_df[forecast_df['ds']==str(tomorrow)]['yhat'].values[0]))\nprint('Tomorrows new cases according to Neural PROPHET : {:.0f}'.format(forecast_df_nn[forecast_df_nn['ds']==str(tomorrow)]['yhat_avg'].values[0]))\n\"\"\"\n**Overall, we can see that Neural Prophet and SARIMAX predict and forecast similar values, which are higher compared to those predicted and forecasted by Prophet.**<br>\n\"\"\"\n\"\"\"\nFinally, we will create a final dataframe that will host the average prediction among the three models.\n\"\"\"\ndf_final = pd.DataFrame({'date':forecast_df_nn[-window:]['ds'], 'y_p':forecast_df[-window:]['yhat'], 'y_p_nn':forecast_df_nn[-window:]['yhat_avg'], 'y_s':sarimax_results['yhat'].values})\ndf_final = df_final.set_index('date')\ndf_final['y_avg'] = df_final.mean(axis=1)\nplt.figure(figsize=(16,6))\nplt.title('COVID19 new cases in Italy with AVG Forecasted cases', fontsize=30)\n#Actual cases\nplt.bar(df[-prediction_window:].index, df[-prediction_window:]['nuovi_positivi'], label='Actual cases', color='black',alpha=1)\n\n#AVG Forecast\nplt.bar(df_final.index, df_final.y_avg,label='AVG cases by ML models', color='#00FF00',alpha=0.6, edgecolor=\"black\", linewidth=2.0)\n\ntext = 'New Cases:\\nToday: {:.0f}\\nTomorrow {:.0f}'.format(float(df['nuovi_positivi'][-1:]),df_final[-forecast_window:]['y_avg'].values[0])\nplt.text(today + pd.DateOffset(days=3), 7000, text, bbox=dict(facecolor='white', alpha=1), fontsize=17)\n\nplt.axvline(today, linewidth=2.5, color='red', linestyle=\"--\")\nplt.legend(loc='upper right', fontsize=14,  fancybox=True, shadow=True, frameon=True)\nplt.ylabel('New cases', fontsize=20)\nplt.xticks(forecast_df[-prediction_window-forecast_window:]['ds'], rotation=80, fontsize=14)\nplt.yticks(fontsize=15)\nplt.grid(visible=None, axis='x')\n\nplt.show()\n\"\"\"\n**Overall, we can see that the average predicted values fits well the last 4 weeks data. Moreover, we can see the weekly trend and holiday effect on forecasted values.**\n\"\"\"\n\"\"\"\n**I will update this notebook daily with the new data and add deeper analysis. Thanks for reading the notebook :)**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9d2281904b4c4e'}"}
{"id":"39678","text":"\"\"\"\nThis is an inference notebook with the `t5-large` model. You can achieve decent results with this model and choose to use the provided model in an ensemble of yours.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nfrom typing import Dict, Any, Union\n\nfrom pathlib import Path\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import StratifiedKFold\n\nimport torch\nimport torch.nn as nn\n\nimport torch.utils.data as D\nfrom torch.utils.data.dataset import Dataset, IterableDataset\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom transformers import AutoModel, AutoTokenizer, AutoConfig\nfrom transformers import PreTrainedModel\n\nfrom tqdm.notebook import tqdm\n\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import mean_squared_error\n\nimport yaml, gc\n\"\"\"\n### Folders and Dataframes\n\"\"\"\nBASE_PATH = Path('\/kaggle\/input\/commonlit-t5-large')\nDATA_PATH = Path('\/kaggle\/input\/commonlitreadabilityprize\/')\nassert DATA_PATH.exists()\nMODELS_PATH = Path(BASE_PATH\/'best_models')\nassert MODELS_PATH.exists()\ntrain_df = pd.read_csv(DATA_PATH\/'train.csv')\ntest_df = pd.read_csv(DATA_PATH\/'test.csv')\nsample_df = pd.read_csv(DATA_PATH\/'sample_submission.csv')\n\ndef remove_unnecessary(df):\n    df.drop(df[df['target'] == 0].index, inplace=True)\n    df.reset_index(drop=True, inplace=True)\n    \nremove_unnecessary(train_df)\n\"\"\"\n### Configuration\n\"\"\"\nclass Config(): \n    NUM_FOLDS = 6\n    NUM_EPOCHS = 3\n    BATCH_SIZE = 16\n    MAX_LEN = 248\n    MODEL_PATH = BASE_PATH\/'lm'\n#     TOKENIZER_PATH = str(MODELS_PATH\/'roberta-base-0')\n    DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    SEED = 1000\n    NUM_WORKERS = 2\n    MODEL_FOLDER = MODELS_PATH\n    model_name = 't5-large'\n    svm_kernels = ['rbf']\n    svm_c = 5\n\ncfg = Config()\ntrain_df['normalized_target'] = (train_df['target'] - train_df['target'].mean()) \/ train_df['target'].std()\n\"\"\"\n### Read Existing Models\n\"\"\"\nmodel_path = MODELS_PATH\nassert model_path.exists()\n!ls {MODELS_PATH}\nclass AttentionHead(nn.Module):\n    \n    def __init__(self, in_features, hidden_dim, num_targets):\n        super().__init__()\n        self.in_features = in_features\n        \n        self.hidden_layer = nn.Linear(in_features, hidden_dim)\n        self.final_layer = nn.Linear(hidden_dim, num_targets)\n        self.out_features = hidden_dim\n        \n    def forward(self, features):\n        att = torch.tanh(self.hidden_layer(features))\n        score = self.final_layer(att)\n        attention_weights = torch.softmax(score, dim=1)\n        return attention_weights\nfrom transformers import T5EncoderModel\n\nclass CommonLitModel(nn.Module):\n    def __init__(self):\n        super(CommonLitModel, self).__init__()\n        config = AutoConfig.from_pretrained(cfg.MODEL_PATH)\n        config.update({\n            \"output_hidden_states\": True,\n            \"hidden_dropout_prob\": 0.0,\n            \"layer_norm_eps\": 1e-7\n        })\n        self.transformer_model = T5EncoderModel.from_pretrained(cfg.MODEL_PATH, config=config)\n        self.attention = AttentionHead(config.hidden_size, 512, 1)\n        self.regressor = nn.Linear(config.hidden_size, 1)\n    \n    def forward(self, input_ids, attention_mask):\n        last_layer_hidden_states = self.transformer_model(input_ids=input_ids, attention_mask=attention_mask)['last_hidden_state']\n        weights = self.attention(last_layer_hidden_states)\n        context_vector = torch.sum(weights * last_layer_hidden_states, dim=1) \n        return self.regressor(context_vector), context_vector\ndef load_model(i):\n    inference_model = CommonLitModel()\n    inference_model = inference_model.cuda()\n    inference_model.load_state_dict(torch.load(str(model_path\/f'{i + 1}_pytorch_model.bin')))\n    inference_model.eval();\n    return inference_model\n\"\"\"\n### DataSet and Tokenizers\n\"\"\"\ndef convert_to_list(t):\n    return t.flatten().long()\n\nclass CommonLitDataset(nn.Module):\n    def __init__(self, text, test_id, tokenizer, max_len=128):\n        self.excerpt = text\n        self.test_id = test_id\n        self.max_len = max_len\n        self.tokenizer = tokenizer\n    \n    def __getitem__(self,idx):\n        encode = self.tokenizer(self.excerpt[idx],\n                                return_tensors='pt',\n                                max_length=self.max_len,\n                                padding='max_length',\n                                truncation=True)\n        return {'input_ids': convert_to_list(encode['input_ids']),\n                'attention_mask': convert_to_list(encode['attention_mask']),\n                'id': self.test_id[idx]}\n    \n    def __len__(self):\n        return len(self.excerpt)\n!ls {MODELS_PATH}\/tokenizer-1\nfrom transformers import T5Tokenizer\n\ntokenizers = []\nfor i in range(1, cfg.NUM_FOLDS):\n    tokenizer_path = MODELS_PATH\/f\"tokenizer-{i}\"\n    print(tokenizer_path)\n    assert(Path(tokenizer_path).exists())\n    tokenizer = T5Tokenizer.from_pretrained(str(tokenizer_path))\n    tokenizers.append(tokenizer)\ndef create_dl(df, tokenizer):\n    text = df['excerpt'].values\n    ids = df['id'].values\n    ds = CommonLitDataset(text, ids, tokenizer, max_len=cfg.MAX_LEN)\n    return DataLoader(ds, \n                      batch_size = cfg.BATCH_SIZE,\n                      shuffle=False,\n                      num_workers = 1,\n                      pin_memory=True,\n                      drop_last=False\n                     )\n\"\"\"\n#### Extract Embeddings\n\"\"\"\ndef get_cls_embeddings(dl, transformer_model):\n    cls_embeddings = []\n    with torch.no_grad():\n        for input_features in tqdm(dl, total=len(dl)):\n            _, context_vector = transformer_model(input_features['input_ids'].cuda(), input_features['attention_mask'].cuda())\n#             cls_embeddings.extend(output['last_hidden_state'][:,0,:].detach().cpu().numpy())\n            embedding_out = context_vector.detach().cpu().numpy()\n            cls_embeddings.extend(embedding_out)\n    return np.array(cls_embeddings)\n\"\"\"\n#### Extract Number of Bins\n\"\"\"\nnum_bins = int(np.ceil(np.log2(len(train_df))))\ntrain_df['bins'] = pd.cut(train_df['target'], bins=num_bins, labels=False)\nbins = train_df['bins'].values\n\"\"\"\n#### Training\n\"\"\"\ndef rmse_score(X, y):\n    return np.sqrt(mean_squared_error(X, y))\n%%time\n\ntrain_target = train_df['normalized_target'].values\n\ndef calc_mean(scores):\n    return np.mean(np.array(scores), axis=0)\n\nfinal_scores = []\nfinal_rmse = []\nfor j, tokenizer in enumerate(tokenizers):\n    print('Model', j)\n    test_dl = create_dl(test_df, tokenizer)\n    train_dl = create_dl(train_df, tokenizer)\n    transformer_model = load_model(j)\n    transformer_model.cuda()\n    X = get_cls_embeddings(train_dl, transformer_model)\n    y = train_target\n    X_test = get_cls_embeddings(test_dl, transformer_model)\n    kfold = StratifiedKFold(n_splits=cfg.NUM_FOLDS)\n    scores = []\n    rmse_scores = []\n    for kernel in cfg.svm_kernels:\n        print('Kernel', kernel)\n        kernel_scores = []\n        kernel_rmse_scores = []\n        for k, (train_idx, valid_idx) in enumerate(kfold.split(X, bins)):\n\n            print('Fold', k, train_idx.shape, valid_idx.shape)\n            model = SVR(C=cfg.svm_c, kernel=kernel, gamma='auto')\n\n            X_train, y_train = X[train_idx], y[train_idx]\n            X_valid, y_valid = X[valid_idx], y[valid_idx]\n            model.fit(X_train, y_train)\n            prediction = model.predict(X_valid)\n            kernel_rmse_scores.append(rmse_score(prediction, y_valid))\n            print('rmse_score', kernel_rmse_scores[k])\n            kernel_scores.append(model.predict(X_test))\n        scores.append(calc_mean(kernel_scores))\n        rmse_scores.append(calc_mean(kernel_rmse_scores))\n    final_scores.append(calc_mean(scores))\n    final_rmse.append(calc_mean(rmse_scores))\n    del transformer_model\n    torch.cuda.empty_cache()\n    del tokenizer\n    gc.collect()\nprint('FINAL RMSE score', np.mean(np.array(final_rmse)))\nfinal_scores_bck = final_scores\nfinal_scores_bck\n# (train_df['target'] - cfg.train_target_mean) \/ cfg.train_target_std\nfinal_scores = np.array(final_scores) * train_df['target'].std() + train_df['target'].mean()\nfinal_scores\n\"\"\"\n#### Ensure the mean of the prediction equals the mean of the training data\n\"\"\"\ndef calc_mean(scores):\n    return np.mean(np.array(scores), axis=0)\ntarget_mean = train_df['target'].mean()\nfinal_scores_flat = calc_mean(final_scores).flatten()\nfinal_scores_mean = final_scores_flat.mean()\ntarget_mean, np.array(final_scores).mean()\nmean_diff = target_mean - final_scores_mean\nmean_diff, mean_diff \/ len(final_scores)\nsample_df['target'] = final_scores_flat\n# sample_df['target'] = len(final_scores) \/ np.sum(1 \/ np.array(final_scores), axis=0) # harmonic mean\nsample_df\npd.DataFrame(sample_df).to_csv('submission.csv', index=False)\n!cat submission.csv","meta":"{'source': 'AI4Code', 'id': '4910be2f6d5bb6'}"}
{"id":"10367","text":"\"\"\"\n*Note: This is a modified version of previous notebook* [here](https:\/\/github.com\/muzavan\/katalagu\/blob\/main\/showcase\/indonesia_2000an.ipynb)\n\"\"\"\n\"\"\"\n### Indonesia 2000an Simple EDA\n\nPada notebook ini, saya akan mengeksplorasi lagu-lagu tenar di Indonesia periode 2000-an berdasarkan kata-kata pada liriknya. \n\nPertama-tama, saya butuh meng-install dan mempersiapkan pustaka tambahan yang saya butuhkan untuk mengolah data ini.\n\"\"\"\n# 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)\nimport sys\nimport nltk\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\n\"\"\"\n## Pembersihan Kata\nLirik pada dataset ini masih berupa lirik yang memiliki format tampilan (misal baris baru atau anotasi untuk bagian lagu seperti verse atau chorus).\n\nSaya akan membersihkan datanya terlebih dahulu. Proses pembersihan yang saya lakukan:\n\n- Membuat semua huruf dalam bentuk huruf kecil untuk mempermudah pemrosesan\n- Memisahkan setiap lirik berdasarkan baris baru. Ini perlu saya lakukan karena saya lihat anotasi bagian lagu biasanya ada pada baris sendiri\n- Membuang anotasi bagian lagu seperti `[verse]` atau `[chorus]`\n- Memisahkan setiap kata dengan spasi\n- Membersihkan setiap kata dari tanda baca yang tertinggal pada awal dan akhir kata, misalkan pada kata \"aku...\", tiga titik terakhir akan dihapus dari kata tersebut. Tanda baca ini digunakan sebagai panduan intonasi pada lirik lagu asli (misal memberi efek sendu, penekanan, atau pemisahan)\n\"\"\"\n# Convert all lyrics to token of words\nimport json \nLYRIC_FILE = '..\/input\/katalagu-lirik-lagu-indonesia-2000an\/katalagu-indonesia-2000an.json' # Indonesia 2000an\n\nraw_json = {}\n\nwith open(LYRIC_FILE, 'r') as f:\n    raw_json = json.load(f)\n    \nraw_json.get(\"lyrics\", [{}])[0]\nraw_lyrics = raw_json.get('lyrics', [])\nall_lyrics = list(map(lambda x: x.get('lyric', ''), raw_lyrics))\n\nall_lyrics[0]\nSAMPLE = 5\n\nsanitized_lyrics = []\n\nfor lyr in all_lyrics:\n    lyr = lyr.lower()\n    lyrs = lyr.split('\\n') # Split by newline\n    lyrs = [l for l in lyrs if len(l) > 0 and l[0] != '[' and l[-1] != ']'] # Avoid [chorus] [verse-1] etc\n    sanitized_lyrics.extend(lyrs)\n    \nsanitized_lyrics[:SAMPLE]\nwords = []\n\nfor lyric in sanitized_lyrics:\n    words.extend(lyric.split())\n    \n# Remove trailing dot or comma\ndef stripnonalpha(w):    \n    st, en = -1, -1\n    \n    for i, c in enumerate(w):\n        if c.isalpha():\n            if st == -1:\n                st = i\n            en = i\n    \n    if st == -1 or en == -1:\n        # No nonalpha\n        return ''\n        \n    return w[st:en+1]\n\nwords = [stripnonalpha(w) for w in words]\n\n# Filter 'unusable' word\nunusable = set(['', 'reff'])\n\nwords = [w for w in words if w not in unusable]\n    \n\"\"\"\n## Eksplorasi Data\nPada bagian ini, saya akan mencoba menjawab beberapa hipotesis\/pertanyaan saya seputar kata-kata pada lagu tenar.\n\"\"\"\n# Helper function that helps the data processing or data visualization\ndef as_table(word_freqs):\n    word_list, count_list = [], []\n    for w, c in word_freqs:\n        word_list.append(w)\n        count_list.append(c)\n\n    return pd.DataFrame.from_dict({\"words\": word_list, \"count\": count_list})\n    \ndef freq_word_order(w):\n    # (word, freq)\n    # order by freq DESC, if freq same, sort by word ASC\n    return -w[1], w[0]\n\nfrom collections import defaultdict\n\"\"\"\n## Pemendekan Kata\nPada saat saya membersihkan data, saya menemukan banyak kata yang ditulis dengan pemendakan sebagai panduan pengucapan pada lagu. Contohnya adalah penggunaan kata `s'gala` untuk kata segala karena dalam menyanyikan lagu tersebut, huruf `e` tidak gamblang diucapkan.\n\nSaya ingin melihat kata-kata apa saja yang lazim dibuat menjadi bentuk pendeknya (catatan: saya tidak tahu istilah baku untuk bentuk ini).\n\"\"\"\n# Check for contracted words ex: s'mua, s'gala\ncontracted = defaultdict(int)\n\nfor w in words:\n    if \"'\" in w or \"`\" in w:\n        contracted[w] += 1\n        \ncontracted_tp = sorted(contracted.items(), key=freq_word_order)\n\ndf = as_table(contracted_tp)\n\ndf\n\"\"\"\nHmmm, di luar kata-kata dalam Bahasa Inggris, ada pola menarik yang saya temukan:\n\n- Huruf yang paling sering di-abai-kan adalah huruf `e`. Contohnya pada kata `s'gala`, `t'lah`, `kar'na`.\n- Huruf awal yang sering mengikuti huruf `e` tersebut adalah huruf `s`.\n\nAda penjelasan ilmiahnya dalam tata bahasa Indonesia tidak ya? Hipotesis saya sih, mungkin karena huruf `e` adalah salah satu huruf yang punya banyak pengucapan berbeda, misal pada kata `meja` dan `teduh`. Sepertinya sih pemendekan ini lazim terjadi untul lafal `e` pada `teduh`.\n\"\"\"\n\"\"\"\n## Kata Ulang\nSalah satu guna kata ulang adalah untuk menunjukkan nominal banyak. Kata ulang apa yang sering digunakan pada lagu tenar di Indonesia?\n\"\"\"\n# Check for repeated words\nreps = defaultdict(int)\n\nfor w in words:\n    if \"-\" in w:\n        reps[w] += 1\n        \nreps_tp = sorted(reps.items(), key=freq_word_order)\n\ndf = as_table(reps_tp)\n\ndf[:10]\n\"\"\"\nHmm, sepertinya tidak banyak yang bisa saya simpulkan sih. dosa-dosaku sering muncul pada lirik lagu `Andai Ku Tahu` dari `Ungu`.\n\nOh iya, ini membuat saya ingat bahwa data lirik ini sendiri bisa jadi tidak valid karena adanya perbedaan format dalam penulisan lirik. Ada lagu yang menuliskan gamblang lirik yang diulang berkali-kali dan adapula yang menuliskan dengan menggunakan format semacam `(x 2)` atau `back to reff`.\n\"\"\"\n\"\"\"\n## Kata Dominan\n\nSaya penasaran, kata apa sih yang paling sering muncul di lirik lagu-lagu tenar ini? Hipotesis saya, kata yang akan dominan adalah kata `cinta` karena topik banyak berkutat tentang `cinta`.\n\"\"\"\nwholes = defaultdict(int)\n\nfor word in words:\n    if word in contracted or word in reps:\n        continue\n        \n    if all([c.isalpha() for c in word]):\n        wholes[word] += 1\n    \nwholes_tp = sorted(wholes.items(), key=freq_word_order)\n\ndf = as_table(wholes_tp)\ndf[:10]\n\"\"\"\nAh, saya benar, kata `cinta` menjadi salah satu kata yang muncul paling sering dari lirik lagu.\n\nTapi, ternyata kata yang justru paling dominan adalah kata ganti orang seperti `aku`, `ku`, dan `kau`. Hal ini bisa jadi terjadi karena lagu Indonesia sering menjadi lagu yang dinyanyikan kepada orang lain sehingga akan muncul banyak kata ganti orang.\n\"\"\"\n\"\"\"\n## Sudut Pandang Lagu Dominan\n\nSaya jadi penasaran, kalau kita mengelompokkan kata-kata berdasarkan jenis kata ganti nya, kira-kira pihak mana yang paling dominan diceritakan pada lagu ya?\n\nKata ganti akan saya kelompokan menjadi tiga (sumber: [dosenbahasa](https:\/\/dosenbahasa.com\/jenis-jenis-kata-ganti), dengan tambahan):\n\n- **Pertama**: `aku`, `saya`, `daku`, `diriku`, `kita`, `kami`, atau kata yang berakhiran `-ku` (seharusnya saya juga memeriksa apakah kata tersebut kata kerja transitif, tapi saya menyederhanakan permasalahan di sini)\n- **Kedua**:` kamu`, `anda`, `kau`, `dirimu`, `kalian`, atau kata yang berakhiran `-mu`\n- **Ketiga**: `ia`, `dia`, `dirinya`, `beliau`, `mereka`, atau kata yang berakhiran `-nya`\n\nHipotesis saya, lagu akan dominan dari sudut pandang orang kedua dengan alasan banyak lagu di Indonesia yang dinyanyikan 'seolah-olah' sedang berbicara dengan orang lain (misal: minta maaf, menyatakan cinta, dll).\n\"\"\"\ndef is_pertama(w):\n    pertama_set = set(['aku', 'ku', 'saya', 'daku', 'diriku', 'kita', 'kami'])\n    return (w in pertama_set) or (len(w) > 2 and w[-2:] == 'ku')\n\ndef is_kedua(w):\n    kedua_set = set(['kamu', 'engkau', 'anda', 'kau', 'dirimu', 'kalian'])\n    return (w in kedua_set) or (len(w) > 2 and w[-2:] == 'mu')\n\ndef is_ketiga(w):\n    ketiga_set = set(['ia', 'dia', 'dirinya', 'beliau', 'mereka'])\n    return (w in ketiga_set) or (len(w) > 3 and w[-3:] == 'nya')\n\nsudut_pandangs = defaultdict(int)\n\nfor w, c in wholes_tp:\n    if is_pertama(w):\n        sudut_pandangs[\"pertama\"] += c\n    if is_kedua(w):\n        sudut_pandangs[\"kedua\"] += c\n    if is_ketiga(w):\n        sudut_pandangs[\"ketiga\"] += c\n        \nsudut_pandangs_tp = sorted(sudut_pandangs.items(), key=freq_word_order)\n\ndf = as_table(sudut_pandangs_tp)\ndf\n\"\"\"\nWah, ternyata hipotesis saya kurang tepat. Ternyata, **sudut pandang orang pertama** lebih dominan untuk digunakan.\n\"\"\"\n\"\"\"\n\n## Kata Inti Dominan\nDari kumpulan kata dominan, kita melihat ada banyak kata ganti orang dan juga `stopwords`. `Stopwords` bisa diartikan sebagai kata yang tidak memberikan makna tambahan dari sebuah kalimat, misalkan `yang`, `dan`, dsb.\n\nSekarang, saya ingin fokus pada kata-kata inti saja.\n\"\"\"\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nstops = set(stopwords.words('indonesian'))\n\ndef is_sudut_pandang(w):\n    return is_pertama(w) or is_kedua(w) or is_ketiga(w)\n\ncores = defaultdict(int)\nfor w, c in wholes_tp:\n    if w in stops or is_sudut_pandang(w):\n        continue\n        \n    cores[w] += c\n    \ncores_tp = sorted(cores.items(), key=freq_word_order)\ndf = as_table(cores_tp)\ndf[:20]\n\"\"\"\nYeay, kali ini, hipotesis saya benar! Kata yang berkaitan dengan cinta dan perasaan seperti `cinta`, `hati`, `sayang`, dan `love` memang menjadi kata yang dominan muncul pada lirik lagu Indonesia.\n\nBeberapa temuan menarik:\n\n- Kata senandung `oh` dan `ah` juga ternyata sering digunakan walaupun tidak memiliki arti tertentu.\n- `Hidup` dan `mati` memiliki frekuensi yang cukup mirip. Bisa jadi kedua kata ini sering digunakan bersamaan.\n\"\"\"\n\"\"\"\n## Lalu?\nItu saja yang bisa saya ulik dari data lirik lagu tenar di Indonesia. Memang tidak ada actionable items sih dari eksplorasinya, hehe.\n\nHmm, kira-kita hal apa lagi ya yang bisa kita ulik dari data lirik lagu?\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '13050af371388e'}"}
{"id":"130011","text":"\"\"\"\n# Tabular Playground Series - March 2021\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport joblib\nimport gc\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.model_selection import GridSearchCV\npd.set_option('max_columns', None)\n\"\"\"\n# Load Data\n\"\"\"\ntrain = pd.read_csv('..\/input\/tabular-playground-series-mar-2021\/train.csv')\ntrain = train.sample(frac=1, random_state=1)\n\nprint(train.shape)\nmb = train.memory_usage(index=True, deep=True).sum() \/ 1024**2\nprint(mb)\ntrain.head()\n\"\"\"\n# Missing Values\n\"\"\"\ntrain.isnull().sum().to_frame().T\n\"\"\"\n# Label Distribution\n\"\"\"\n(train.target.value_counts() \/ len(train)).to_frame()\ny_train = train.target.values\ntrain.drop(['id', 'target'], axis=1, inplace=True)\n\"\"\"\n# Column Types\n\"\"\"\nfor c, d in zip(train.columns, train.dtypes):\n    print(f'{c:<10}{d}')\ncat_features = train.columns.values[train.dtypes.values == 'O'].tolist()\nnum_features = [c for c in train.columns if c not in cat_features]\nfeatures = num_features + cat_features\n\nprint(cat_features)\nprint(num_features)\n\"\"\"\n# Explore Categorical Levels\n\"\"\"\ntrain[cat_features].nunique()\ncat_features.remove('cat10')\nfeatures.remove('cat10')\n\"\"\"\n# Preprocessing\n\"\"\"\nnum_transformer = Pipeline(\n    steps = [\n        ('imputer', SimpleImputer(strategy='mean')),\n        ('scaler', StandardScaler())  \n    ]\n)\n\ncat_transformer = Pipeline(\n    steps = [\n        ('imputer', SimpleImputer(strategy='constant', fill_value='Missing')),\n        ('onehot', OneHotEncoder(handle_unknown='ignore'))\n    ]\n)\n\npreprocessor = ColumnTransformer(\n    transformers = [\n        ('num', num_transformer, num_features),\n        ('cat', cat_transformer, cat_features)\n    ]\n)\npreprocessor.fit(train)\nX_train = preprocessor.transform(train)\n\nprint('X_train shape:', X_train.shape)\nprint('y_train shape:', y_train.shape)\ndel train\ngc.collect()\n\"\"\"\n# Sample Training Data\n\"\"\"\nX_sample, X_valid, y_sample, y_valid = train_test_split(X_train, y_train, test_size=0.8, stratify=y_train, random_state=1)\n\nprint(X_sample.shape)\nprint(X_valid.shape)\n\"\"\"\n# Model Selection\n\"\"\"\n\"\"\"\n## Logistic Regression\n\"\"\"\n%%time \n\nlr_clf = LogisticRegression(max_iter=1000, solver='saga', penalty='elasticnet')\n\nlr_parameters = {\n    'l1_ratio': [0, 1],\n    'C': [0.01, 0.1, 1, 10]\n}\n\nlr_grid = GridSearchCV(lr_clf, lr_parameters, cv=5, refit='True', n_jobs=-1, verbose=10, scoring='roc_auc')\nlr_grid.fit(X_sample, y_sample)\n\nlr_model = lr_grid.best_estimator_\n\nprint('Best Parameters:', lr_grid.best_params_)\nprint('Best CV Score:  ', lr_grid.best_score_)\nprint('Training Acc:   ', lr_model.score(X_sample, y_sample))\nprint('Validation Acc: ', lr_model.score(X_valid, y_valid))\nlr_summary = pd.DataFrame(lr_grid.cv_results_['params'])\nlr_summary['cv_score'] = lr_grid.cv_results_['mean_test_score']\n\nfor r in lr_parameters['l1_ratio']:\n    temp = lr_summary.query(f'l1_ratio == {r}')\n    plt.plot(temp.C, temp.cv_score, label=r)\nplt.xscale('log')\nplt.xlabel('Regularization Parameter (C)')\nplt.ylabel('CV Score')\nplt.legend(title='L1 Ratio', loc='lower right')\nplt.grid()\nplt.show()\n\nfor p, s in zip(lr_grid.cv_results_['params'], lr_grid.cv_results_['mean_test_score']):\n    print(f\"l1: {p['l1_ratio']:<.3f},  C: {p['C']:>8.3f},  score: {s:.4f}\")\n\"\"\"\n# Decision Trees\n\"\"\"\n%%time \n\ndt_clf = DecisionTreeClassifier(random_state=1)\n\ndt_parameters = {\n    'max_depth': [2, 4, 6, 8, 10, 12, 14, 16],\n    'min_samples_leaf': [2, 4, 8, 16]\n}\n\ndt_grid = GridSearchCV(dt_clf, dt_parameters, cv=5, refit='True', n_jobs=-1, verbose=10, scoring='roc_auc')\ndt_grid.fit(X_sample, y_sample)\n\ndt_model = dt_grid.best_estimator_\n\nprint('Best Parameters:', dt_grid.best_params_)\nprint('Best CV Score:  ', dt_grid.best_score_)\nprint('Training Acc:   ', dt_model.score(X_sample, y_sample))\nprint('Validation Acc: ', dt_model.score(X_valid, y_valid))\ndt_summary = pd.DataFrame(dt_grid.cv_results_['params'])\ndt_summary['cv_score'] = dt_grid.cv_results_['mean_test_score']\n\nfor ms in dt_parameters['min_samples_leaf']:\n    temp = dt_summary.query(f'min_samples_leaf == {ms}')\n    plt.plot(temp.max_depth, temp.cv_score, label=ms)\nplt.xlabel('Maximum Depth')\nplt.ylabel('CV Score')\nplt.legend(title='Min Samples')\nplt.grid()\nplt.show()\n\nfor p, s in zip(dt_grid.cv_results_['params'], dt_grid.cv_results_['mean_test_score']):\n    print(f\"depth: {p['max_depth']:>3},  min_inst: {p['min_samples_leaf']:>4},  score: {s:.4f}\")\n\"\"\"\n# Random Forest\n\"\"\"\n%%time \n\nrf_clf = RandomForestClassifier(random_state=1, n_estimators=50)\n\nrf_parameters = {\n    'max_depth': [4, 8, 16, 20, 24, 28, 32],\n    'min_samples_leaf': [1, 2, 4]\n}\n\nrf_grid = GridSearchCV(rf_clf, rf_parameters, cv=5, refit='True', n_jobs=-1, verbose=10, scoring='roc_auc')\nrf_grid.fit(X_sample, y_sample)\n\nrf_model = rf_grid.best_estimator_\n\nprint('Best Parameters:', rf_grid.best_params_)\nprint('Best CV Score:  ', rf_grid.best_score_)\nprint('Training Acc:   ', rf_model.score(X_sample, y_sample))\nprint('Validation Acc: ', rf_model.score(X_valid, y_valid))\nrf_summary = pd.DataFrame(rf_grid.cv_results_['params'])\nrf_summary['cv_score'] = rf_grid.cv_results_['mean_test_score']\n\nfor ms in rf_parameters['min_samples_leaf']:\n    temp = rf_summary.query(f'min_samples_leaf == {ms}')\n    plt.plot(temp.max_depth, temp.cv_score, label=ms)\nplt.xlabel('Maximum Depth')\nplt.ylabel('CV Score')\nplt.legend(title='Min Samples')\nplt.grid()\nplt.show()\n\nfor p, s in zip(rf_grid.cv_results_['params'], rf_grid.cv_results_['mean_test_score']):\n    print(f\"depth: {p['max_depth']:>3},  min_inst: {p['min_samples_leaf']:>4},  score: {s:.4f}\")\n\"\"\"\n# Train Final Model\n\"\"\"\nprint(rf_grid.best_params_)\nfinal_model = RandomForestClassifier(random_state=1, n_estimators=50, max_depth=24, min_samples_leaf=4)\nfinal_model.fit(X_train, y_train)\n\nprint(final_model.score(X_train, y_train))\n\"\"\"\n# Save Final Model\n\"\"\"\njoblib.dump(preprocessor, 'tps_preprocessor_01.joblib')\njoblib.dump(final_model, 'tps_model_01.joblib')\nprint('Model written to file.')","meta":"{'source': 'AI4Code', 'id': 'ef1fbe1de382db'}"}
{"id":"59083","text":"# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\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\n#importing dataset \n\ndf = pd.read_csv('\/kaggle\/input\/hotel-booking-demand\/hotel_bookings.csv')\npd.set_option('display.max_columns', None)\n# viewing column and the data inside them and how they correlate\n\ndf.head()\n#now viewing which column is empty and of which data type\n\ndf.info()\n\"\"\"\n# Countries\n\"\"\"\n#countries with most booking, month wise\n\n#grouping by countries and making dummy data of month\ngc = pd.get_dummies(df, columns=['arrival_date_month']).groupby('country').sum()\n\n#selecting countries which have more than 27000 arrival_data_day_month\nsc = gc.loc[gc['arrival_date_day_of_month']>=27000]\n\n#removing prefix from every month\nrp = sc.rename(columns = lambda x: x.replace('arrival_date_month_', ''))\n\n#selecting particular columns\nsp = rp.loc[:, 'April':'September']\n\nplt.figure(figsize = (18,8))\nax = sns.lineplot(data= sp, dashes=False)\nax.set_xlabel('Countries', fontsize = 20)\nax.set_ylabel('Visit Count', fontsize = 20)\nax.set_title('Month Wise Visiting Countries', fontsize = 30)\nplt.show()\n\"\"\"\nas we can see in upper graph that Portugal visits very frequently and they tops every month\n\"\"\"\n#in this we can see that which country spends the most amount of money when the are visiting\n\n#countries who visits the most\nsome_countries = ('PRT', 'GBR', 'FRA', 'ESP', 'DEU', 'ITA', 'IRL', 'BEL', 'BRA', 'NLD','USA','CHE')\n\n#counting how much time those top countries appear\ndft = df.loc[df['country'].isin(some_countries)]['country']\n\nplt.rcParams['figure.figsize'] = (18, 8)\nsns.set_style('whitegrid')\nax = sns.lineplot(x = dft, y = df['adr'])\nax.set_xlabel('Country name', fontsize =20)\nax.set_ylabel('Expenditure',fontsize =20)\nax.set_title('Expenditure of Visiting Countries', fontsize = 30)\nplt.show()\n\"\"\"\nin the upper graph USA leads in spending the money\n\"\"\"\n#combining the stays in weekends and stays in week days to get the total number nights spent\nstay = df['stays_in_weekend_nights'] + df['stays_in_week_nights']\n\nplt.rcParams['figure.figsize'] = (18, 8)\nsns.set_style('whitegrid')\nax = sns.lineplot(x = dft, y = stay)\nax.set_xlabel('Country name', fontsize =20)\nax.set_ylabel('Night Spent',fontsize =20)\nax.set_title('Country wise spending nights', fontsize = 30)\nplt.show()\n\"\"\"\nin the upper graph, people from Ireland spents the most nights in average\n\"\"\"\n#summing up the adults, children and babies column to see how much people visit\n\npeople = df['adults'] + df['children'] + df['babies']\n\nplt.rcParams['figure.figsize'] = (15, 7)\nsns.set_style('whitegrid')\nax = sns.lineplot(x = dft, y = people)\nax.set_xlabel('Country name', fontsize =20)\nax.set_ylabel('People visiting',fontsize =20)\nax.set_title('Country Wise People visiting', fontsize = 30)\nplt.show()\n\"\"\"\n# Hotel\n\"\"\"\n#in this we will see which hotel books the most\n\nplt.figure(figsize = (18,8))\nsns.set_style('darkgrid')\nax = sns.countplot(x = 'hotel', data = df, hue = 'is_canceled', palette = 'pink')\nax.set_xlabel('Hotel', fontsize=20)\nax.set_ylabel('Hotel Count', fontsize=20)\nax.set_title('Type of Hotel', fontsize=30)\nplt.show()\n\"\"\"\ncity hotel gets the most amount of booking\n\"\"\"\n#how much hotel gets canceled\n\ncanc_count = df['is_canceled'].value_counts()\ncanc_count\n#which hotel gets canceled the most\n\ncanceled_hotel = df[(df['is_canceled']==1) & (df['hotel'])]['hotel'].value_counts()\n\ncanceled_hotel\n#now see percent wise cancelation of hotel\n\nlabels = canceled_hotel.index\ndata  = canceled_hotel.values\n\nplt.rcParams['figure.figsize'] = (15,9)\n\nplt.pie(data, labels = labels,autopct='%1.1f%%',shadow=True, startangle=90)\nplt.axis('equal')\nplt.title(\"Canceled Hotel Percent by Type\", fontsize=20)\nplt.show()\n#which hotel got most booking in which month\n\nplt.figure(figsize = (18,8))\nax = sns.countplot( x = df['arrival_date_month'],data = df, hue = 'hotel', palette = 'husl')\nax.set_xlabel('Month', fontsize = 20)\nax.set_ylabel('Hotels', fontsize = 20)\nax.set_title('Month with Type of Hotel', fontsize = 30)\nplt.show()\n#which type of hotel has the highest lead_time\n\nres_lead = df[(df['hotel']=='Resort Hotel')]['lead_time'].sum()\ncit_lead = df[(df['hotel']=='City Hotel')]['lead_time'].sum()\nplt.figure(figsize = (18,8))\nax = sns.barplot(x = ['Resort','City'],y = [res_lead,cit_lead],palette = 'magma')\nax.set_xlabel('Hotel', fontsize=20)\nax.set_ylabel('Lead Time Total', fontsize=20)\nax.set_title('Type of Hotel with Lead Time', fontsize=30)\nplt.show()\nsome_countries = ('PRT', 'GBR', 'FRA', 'ESP', 'DEU', 'ITA', 'IRL', 'BEL', 'BRA', 'NLD','USA','CHE')\ndft = df.loc[df['country'].isin(some_countries)]['country']\n\nplt.rcParams['figure.figsize'] = (18, 8)\nsns.set_style('whitegrid')\nax = sns.countplot(dft, hue = df['hotel'], palette = 'bone')\nax.set_xlabel('Country name', fontsize =20)\nax.set_ylabel('Tourist Trip',fontsize =20)\nax.set_title('Countries like for Particular type of hotel', fontsize = 30)\nplt.show()\n#dropping this one hotel, it is the only hotel which is getting 5400 amount\n\ndf.index[df['adr']==5400]\ndf.drop([48515],inplace = True)\n#which type of hotel earns the most\n\n\nsns.violinplot(x = 'hotel', y='adr', data =df)\nax.set_xlabel('Hotel Type', fontsize =20)\nax.set_ylabel('Earning Amount',fontsize =20)\nax.set_title('Earning of Hotel by Type', fontsize = 30)\nplt.show()\n\"\"\"\n# Month\n\"\"\"\n#month with most number of bookings\n\nplt.figure(figsize = (18,8))\nsns.set_style(\"darkgrid\")\nax = sns.countplot(x = df['arrival_date_month'], data = df)\nax.set_xlabel('Month', fontsize = 20)\nax.set_ylabel('Hotels', fontsize = 20)\nax.set_title('Month With most booking', fontsize = 30)\n\nplt.show()\n\n\n#month with most number of lead_time\n\nplt.figure(figsize = (18,8))\nsns.set_style(\"whitegrid\")\nax = sns.violinplot(x = 'arrival_date_month', y = 'lead_time' ,data=df)\nax.set_xlabel('Month', fontsize = 20)\nax.set_ylabel('Lead Time', fontsize = 20)\nax.set_title('Most Number of Lead Time', fontsize = 30)\nplt.show()\n#in which month hotel get canceled the most\n\ncanceled_month = df[(df['is_canceled']==1) & (df['arrival_date_month'])]['arrival_date_month'].value_counts()\nplt.figure(figsize = (18,8))\nsns.set_style(\"darkgrid\")\nax = sns.lineplot(x = canceled_month.index, y = canceled_month.values, markers=True, dashes=False)\nax.set_xlabel('Month', fontsize = 20)\nax.set_ylabel('Canceled Hotels', fontsize = 20)\nax.set_title('Month With most canceled hotel', fontsize = 30)\n\nplt.show()\nlabels = canceled_month.index\nsizes = canceled_month.values\ncolors = plt.cm.rainbow(np.linspace(0,3))\n\nexplode = (0.2,0.1, 0, 0,0,0,0,0,0,0,0,0)\nplt.rcParams['figure.figsize'] = (15,9)\n\nplt.pie(sizes, labels=labels,explode = explode ,  autopct='%1.1f%%',shadow=True, startangle=90, colors = colors)\n\nplt.axis('equal')  \nplt.title(\"Month with most canceled hotel by Percent\", fontsize =20)\nplt.show()\n#month where hotels gained most\nsns.stripplot(x = 'arrival_date_month' , y = 'adr', data = df)\nax.set_xlabel('Month', fontsize =20)\nax.set_ylabel('Earning',fontsize =20)\nax.set_title('Month Wise Earning of Hotel', fontsize = 30)\nplt.show()\n\"\"\"\nThank You. If you like the analysis, please upvote :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6d1048f2ab2a1f'}"}
{"id":"12940","text":"# 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\n\"\"\"\n# Install waymo_open_dataset package\n\"\"\"\n!rm -rf waymo-od > \/dev\/null\n!git clone https:\/\/github.com\/waymo-research\/waymo-open-dataset.git waymo-od\n!cd waymo-od && git branch -a\n!cd waymo-od && git checkout remotes\/origin\/master\n# !pip3 install --upgrade pip\n!pip3 install waymo-open-dataset-tf-2-1-0==1.2.0\nimport os\nimport tensorflow.compat.v1 as tf\nimport math\nimport numpy as np\nimport itertools\n\ntf.enable_eager_execution()\n\nfrom waymo_open_dataset.utils import range_image_utils\nfrom waymo_open_dataset.utils import transform_utils\nfrom waymo_open_dataset.utils import  frame_utils\nfrom waymo_open_dataset import dataset_pb2 as open_dataset\n\"\"\"\n# Read One Frame\nEach file in the dataset is a sequence of frames ordered by frame start timestamps. We have extracted two frames from the dataset to demonstrate the dataset format.\n\"\"\"\n!ls -lrt\nFILENAME = 'waymo-od\/tutorial\/frames'\ndataset = tf.data.TFRecordDataset(FILENAME, compression_type='')\nfor data in dataset:\n    frame = open_dataset.Frame()\n    frame.ParseFromString(bytearray(data.numpy()))\n    break\n(range_images, camera_projections,range_image_top_pose) = frame_utils.parse_range_image_and_camera_projection(frame)\n\n\"\"\"\n# Examine frame context\n\"\"\"\nprint(frame.context)\n\"\"\"\n# Visualize Camera Images and Camera Labels\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\ndef show_camera_image(camera_image, camera_labels, layout, cmap=None):\n  \"\"\"Show a camera image and the given camera labels.\"\"\"\n\n  ax = plt.subplot(*layout)\n\n  # Draw the camera labels.\n  for camera_labels in frame.camera_labels:\n    # Ignore camera labels that do not correspond to this camera.\n    if camera_labels.name != camera_image.name:\n      continue\n\n    # Iterate over the individual labels.\n    for label in camera_labels.labels:\n      # Draw the object bounding box.\n      ax.add_patch(patches.Rectangle(\n        xy=(label.box.center_x - 0.5 * label.box.length,\n            label.box.center_y - 0.5 * label.box.width),\n        width=label.box.length,\n        height=label.box.width,\n        linewidth=1,\n        edgecolor='red',\n        facecolor='none'))\n\n  # Show the camera image.\n  plt.imshow(tf.image.decode_jpeg(camera_image.image), cmap=cmap)\n  plt.title(open_dataset.CameraName.Name.Name(camera_image.name))\n  plt.grid(False)\n  plt.axis('off')\n\nplt.figure(figsize=(25, 20))\n\nfor index, image in enumerate(frame.images):\n  show_camera_image(image, frame.camera_labels, [3, 3, index+1])\n\"\"\"\n# Visualize Range Images\n\"\"\"\nplt.figure(figsize=(64, 20))\ndef plot_range_image_helper(data, name, layout, vmin = 0, vmax=1, cmap='gray'):\n  \"\"\"Plots range image.\n\n  Args:\n    data: range image data\n    name: the image title\n    layout: plt layout\n    vmin: minimum value of the passed data\n    vmax: maximum value of the passed data\n    cmap: color map\n  \"\"\"\n  plt.subplot(*layout)\n  plt.imshow(data, cmap=cmap, vmin=vmin, vmax=vmax)\n  plt.title(name)\n  plt.grid(False)\n  plt.axis('off')\n\ndef get_range_image(laser_name, return_index):\n  \"\"\"Returns range image given a laser name and its return index.\"\"\"\n  return range_images[laser_name][return_index]\n\ndef show_range_image(range_image, layout_index_start = 1):\n  \"\"\"Shows range image.\n\n  Args:\n    range_image: the range image data from a given lidar of type MatrixFloat.\n    layout_index_start: layout offset\n  \"\"\"\n  range_image_tensor = tf.convert_to_tensor(range_image.data)\n  range_image_tensor = tf.reshape(range_image_tensor, range_image.shape.dims)\n  lidar_image_mask = tf.greater_equal(range_image_tensor, 0)\n  range_image_tensor = tf.where(lidar_image_mask, range_image_tensor,\n                                tf.ones_like(range_image_tensor) * 1e10)\n  range_image_range = range_image_tensor[...,0] \n  range_image_intensity = range_image_tensor[...,1]\n  range_image_elongation = range_image_tensor[...,2]\n  plot_range_image_helper(range_image_range.numpy(), 'range',\n                   [8, 1, layout_index_start], vmax=75, cmap='gray')\n  plot_range_image_helper(range_image_intensity.numpy(), 'intensity',\n                   [8, 1, layout_index_start + 1], vmax=1.5, cmap='gray')\n  plot_range_image_helper(range_image_elongation.numpy(), 'elongation',\n                   [8, 1, layout_index_start + 2], vmax=1.5, cmap='gray')\nframe.lasers.sort(key=lambda laser: laser.name)\nshow_range_image(get_range_image(open_dataset.LaserName.TOP, 0), 1)\nshow_range_image(get_range_image(open_dataset.LaserName.TOP, 1), 4)\n\"\"\"\n# Point Cloud Conversation and Visualization\n\"\"\"\npoints, cp_points = frame_utils.convert_range_image_to_point_cloud(\n    frame,\n    range_images,\n    camera_projections,\n    range_image_top_pose)\npoints_ri2, cp_points_ri2 = frame_utils.convert_range_image_to_point_cloud(\n    frame,\n    range_images,\n    camera_projections,\n    range_image_top_pose,\n    ri_index=1)\n\n# 3d points in vehicle frame.\npoints_all = np.concatenate(points, axis=0)\npoints_all_ri2 = np.concatenate(points_ri2, axis=0)\n# camera projection corresponding to each point.\ncp_points_all = np.concatenate(cp_points, axis=0)\ncp_points_all_ri2 = np.concatenate(cp_points_ri2, axis=0)\n\"\"\"\n# Examine number of points in each lidar sensor.\n\"\"\"\nprint(points_all.shape)\nprint(cp_points_all.shape)\nprint(points_all[0:2])\nfor i in range(5):\n  print(points[i].shape)\n  print(cp_points[i].shape)\n\"\"\"\nSecond rerun\n\"\"\"\nprint(points_all_ri2.shape)\nprint(cp_points_all_ri2.shape)\nprint(points_all_ri2[0:2])\nfor i in range(5):\n  print(points_ri2[i].shape)\n  print(cp_points_ri2[i].shape)\n\"\"\"\n# Show point Cloud\n\n3D point clouds are rendered using an internal tool, which is unfortunately not publicly available yet. Here is an example of what they look like.\n\"\"\"\nfrom IPython.display import Image, display\ndisplay(Image('waymo-od\/tutorial\/3d_point_cloud.png'))\n\"\"\"\n# Visualize Camera Position\n\"\"\"\nimages = sorted(frame.images, key=lambda i:i.name)\ncp_points_all_concat = np.concatenate([cp_points_all, points_all], axis=-1)\ncp_points_all_concat_tensor = tf.constant(cp_points_all_concat)\n\n# The distance between lidar points and vehicle frame origin.\npoints_all_tensor = tf.norm(points_all, axis=-1, keepdims=True)\ncp_points_all_tensor = tf.constant(cp_points_all, dtype=tf.int32)\n\nmask = tf.equal(cp_points_all_tensor[..., 0], images[0].name)\n\ncp_points_all_tensor = tf.cast(tf.gather_nd(\n    cp_points_all_tensor, tf.where(mask)), dtype=tf.float32)\npoints_all_tensor = tf.gather_nd(points_all_tensor, tf.where(mask))\n\nprojected_points_all_from_raw_data = tf.concat(\n    [cp_points_all_tensor[..., 1:3], points_all_tensor], axis=-1).numpy()\ndef rgba(r):\n  \"\"\"Generates a color based on range.\n\n  Args:\n    r: the range value of a given point.\n  Returns:\n    The color for a given range\n  \"\"\"\n  c = plt.get_cmap('jet')((r % 20.0) \/ 20.0)\n  c = list(c)\n  c[-1] = 0.5  # alpha\n  return c\n\ndef plot_image(camera_image):\n  \"\"\"Plot a cmaera image.\"\"\"\n  plt.figure(figsize=(20, 12))\n  plt.imshow(tf.image.decode_jpeg(camera_image.image))\n  plt.grid(\"off\")\n\ndef plot_points_on_image(projected_points, camera_image, rgba_func,\n                         point_size=5.0):\n  \"\"\"Plots points on a camera image.\n\n  Args:\n    projected_points: [N, 3] numpy array. The inner dims are\n      [camera_x, camera_y, range].\n    camera_image: jpeg encoded camera image.\n    rgba_func: a function that generates a color from a range value.\n    point_size: the point size.\n\n  \"\"\"\n  plot_image(camera_image)\n\n  xs = []\n  ys = []\n  colors = []\n\n  for point in projected_points:\n    xs.append(point[0])  # width, col\n    ys.append(point[1])  # height, row\n    colors.append(rgba_func(point[2]))\n\n  plt.scatter(xs, ys, c=colors, s=point_size, edgecolors=\"none\")\nplot_points_on_image(projected_points_all_from_raw_data,\n                     images[0], rgba, point_size=5.0)\n\"\"\"\n# Install from source code\n## Install dependencies\n\"\"\"\n!sudo apt install build-essential\n!sudo apt-get install --assume-yes pkg-config zip g++ zlib1g-dev unzip python3 python3-pip\n!wget https:\/\/github.com\/bazelbuild\/bazel\/releases\/download\/0.28.0\/bazel-0.28.0-installer-linux-x86_64.sh\n!sudo bash .\/bazel-0.28.0-installer-linux-x86_64.sh\n\"\"\"\n# Build and Test\n\"\"\"\n!cd waymo-od && .\/configure.sh && cat .bazelrc && bazel clean\n!cd waymo-od && bazel build ... --show_progress_rate_limit=10.0\n\"\"\"\n# Command line detection metrics computation\n\"\"\"\n!cd waymo-od && bazel-bin\/waymo_open_dataset\/metrics\/tools\/compute_detection_metrics_main waymo_open_dataset\/metrics\/tools\/fake_predictions.bin  waymo_open_dataset\/metrics\/tools\/fake_ground_truths.bin","meta":"{'source': 'AI4Code', 'id': '179bef8a89e11c'}"}
{"id":"81767","text":"\"\"\"\n## Ke\u015fif\u00e7i Veri Analizi | Becerileri Peki\u015ftirme\n\"\"\"\n\"\"\"\nA\u015fa\u011f\u0131da ihtiyac\u0131m\u0131z do\u011frultusunda kullanaca\u011f\u0131m\u0131z k\u00fct\u00fcphaneleri y\u00fckleyelim.\n\"\"\"\nimport numpy as np\nimport seaborn as sns # kendine \u00f6zg\u00fc k\u0131saltmalar\u0131 ile k\u00fct\u00fcphaneleri ekledik\nimport pandas as pd \n\"\"\"\nVeri \u00e7er\u00e7evemizi bulundu\u011fumuz dizinden y\u00fckleyelim ve bir veri \u00e7er\u00e7evesi haline getirerek df de\u011fi\u015fkenine atayal\u0131m. (pd.read_csv(...csv))\n\"\"\"\ndf = pd.read_csv(\"..\/input\/iris.csv\") #veri dosyam\u0131z\u0131 dataframe k\u0131saltmas\u0131 olan df isimli de\u011fi\u015fkene ta\u015f\u0131d\u0131k\n\"\"\"\nVeri \u00e7er\u00e7evesinin ilk 5 g\u00f6zlemini g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf.head() #parantezin i\u00e7ine n = 10 gibi say\u0131lar ekleyerek sat\u0131r say\u0131s\u0131n\u0131 artt\u0131rabiliriz\n\"\"\"\nVeri \u00e7er\u00e7evesinin ka\u00e7 \u00f6znitelik ve ka\u00e7 g\u00f6zlemden olu\u015ftu\u011funu g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf.shape #sat\u0131r s\u00fctun say\u0131s\u0131 yerine \u00f6znitelik ve g\u00f6zlem say\u0131s\u0131 olarak t\u00fcrk\u00e7ele\u015ftiriyoruz\n         #shape komutunda parantez kullanmamaya dikkat ediyoruz\n\"\"\"\nVeri \u00e7er\u00e7evesindeki de\u011fi\u015fkenlerin hangi tipte oldu\u011funu ve bellek kullan\u0131m\u0131n\u0131 g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf.info() #bo\u015f olmayan veri kolon say\u0131s\u0131 dahil temel bilgileri verir\n\"\"\"\nVeri \u00e7er\u00e7evesindeki say\u0131sal de\u011fi\u015fkenler i\u00e7in temel istatistik de\u011ferlerini g\u00f6r\u00fcnt\u00fcleyelim.\n\nStandart sapma ve ortalama de\u011ferlerden \u00e7\u0131kar\u0131mda bulunarak hangi de\u011fi\u015fkenlerin ne kadar varyansa sahip oldu\u011fu hakk\u0131nda fikir y\u00fcr\u00fctelim.\n\"\"\"\ndf.describe() #varyans standart sapman\u0131n karek\u00f6k al\u0131nmam\u0131\u015f halidir\n              #.T ekleyerek sat\u0131r ile s\u00fctunun yer de\u011fi\u015ftirmesini sa\u011fayabiliriz\n\"\"\"\nVeri \u00e7er\u00e7evesinde hangi \u00f6znitelikte ka\u00e7 adet eksik de\u011fer oldu\u011funu g\u00f6zlemleyelim.\n\"\"\"\ndf.isna().sum()#isna is null olarak a\u00e7\u0131labilir\n               #tekrar sum() ekleyerek toplam eksik de\u011fer say\u0131s\u0131n\u0131 bulabiliriz\n\"\"\"\nSay\u0131sal de\u011fi\u015fkenler aras\u0131nda korelasyon olup olmad\u0131\u011f\u0131n\u0131 g\u00f6stermek i\u00e7in korelasyon matrisi \u00e7izdirelim. Korelasyon katsay\u0131lar\u0131 hakk\u0131nda fikir y\u00fcr\u00fctelim.\n\nEn g\u00fc\u00e7l\u00fc pozitif ili\u015fki hangi iki de\u011fi\u015fken aras\u0131ndad\u0131r?\n\"\"\"\ndf.corr() #en g\u00fc\u00e7l\u00fc ili\u015fki petal.lenght ile petal.with aras\u0131nda\n\"\"\"\nKorelasyon katsay\u0131lar\u0131n\u0131 daha iyi okuyabilmek i\u00e7in \u0131s\u0131 haritas\u0131 \u00e7izdirelim.\n\"\"\"\ncorr = df.corr()\nsns.heatmap(corr,\n            xticklabels=corr.columns.values,\n            yticklabels=corr.columns.values);\n#renk koyula\u015ft\u0131k\u00e7a negatif y\u00f6nde,beyazla\u015ft\u0131k\u00e7a pozitif y\u00f6nde korelasyon artar\n\"\"\"\nVeri \u00e7er\u00e7evemizin hedef de\u011fi\u015fkeninin \"variety\" benzersiz de\u011ferlerini g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf[\"variety\"].unique()#dizi \u015feklinde d\u00f6nd\u00fcr\u00fcr\n\"\"\"\nVeri \u00e7er\u00e7evemizin hedef de\u011fi\u015fkeninin \"variety\" benzersiz ka\u00e7 adet de\u011fer i\u00e7erdi\u011fini g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf[\"variety\"].nunique()#number'in 'n'si ba\u015fa gelir ve bize adet bilgisini verir\n\"\"\"\nVeri \u00e7er\u00e7evesindeki sepal.width ve sepal.length de\u011fi\u015fkenlerinin s\u00fcrekli oldu\u011funu g\u00f6r\u00fcyoruz. Bu iki s\u00fcrekli veriyi g\u00f6rselle\u015ftirmek i\u00e7in \u00f6nce scatterplot kullanal\u0131m.\n\"\"\"\nsns.scatterplot(x=\"sepal.width\", y=\"sepal.length\", data=df)\n#kategorile\u015ftirme yapmadan noktal\u0131 olarak g\u00f6rselle\u015ftirdik\n\"\"\"\nAyn\u0131 iki veriyi daha farkl\u0131 bir a\u00e7\u0131dan frekanslar\u0131yla incelemek i\u00e7in jointplot kullanarak g\u00f6rselle\u015ftirelim. \n\"\"\"\nsns.jointplot(x=df[\"sepal.width\"],y=df[\"sepal.length\"],kind=\"kde\",color=\"blue\");\n\"\"\"\nAyn\u0131 iki veriyi scatterplot ile tekrardan g\u00f6rselle\u015ftirelim fakat bu sefer \"variety\" parametresi ile hedef de\u011fi\u015fkenine g\u00f6re k\u0131rd\u0131ral\u0131m. \n\n3 farkl\u0131 renk aras\u0131nda sepal de\u011fi\u015fkenleriyle bir k\u00fcmeleme yap\u0131labilir mi? Ne kadar ay\u0131rt edilebilir bunun \u00fczerine d\u00fc\u015f\u00fcnelim.\n\"\"\"\nsns.scatterplot(x=\"sepal.width\", y=\"sepal.length\",hue=\"variety\" , data=df)\n#virginica t\u00fcr\u00fc sepal.lenght \u00f6zelli\u011fi ile \u00f6n plana \u00e7\u0131karken setosa t\u00fcr\u00fc sepal.with \u00f6zelli\u011fi ile \u00f6n planda\n\"\"\"\nvalue_counts() fonksiyonu ile veri \u00e7er\u00e7evemizin ne kadar dengeli da\u011f\u0131ld\u0131\u011f\u0131n\u0131 sorgulayal\u0131m. \n\"\"\"\ndf[\"variety\"].value_counts()\n\n\"\"\"\nKeman grafi\u011fi \u00e7izdirerek sepal.width de\u011fi\u015fkeninin da\u011f\u0131l\u0131m\u0131n\u0131 inceleyin. \n\nS\u00f6z konusu da\u011f\u0131l\u0131m bizim i\u00e7in ne ifade ediyor, normal bir da\u011f\u0131l\u0131m oldu\u011funu s\u00f6yleyebilir miyiz?\n\"\"\"\nsns.violinplot(y=\"sepal.width\",data=df);\n#en yayg\u0131n 3.0 de\u011ferinde g\u00f6zlemleniyor\n\"\"\"\nDaha iyi anlayabilmek i\u00e7in sepal.width \u00fczerine bir distplot \u00e7izdirelim.\n\"\"\"\nsns.distplot(df[\"sepal.width\"],bins=16,color='purple')\n#merkezi limit teoremi\n\"\"\"\n\u00dc\u00e7 \u00e7i\u00e7ek t\u00fcr\u00fc i\u00e7in \u00fc\u00e7 farkl\u0131 keman grafi\u011fini sepal.length de\u011fi\u015fkeninin da\u011f\u0131l\u0131m\u0131 \u00fczerine tek bir sat\u0131r ile g\u00f6rselle\u015ftirelim.\n\"\"\"\nsns.violinplot(x=\"variety\",y=\"sepal.width\",data=df);\n\"\"\"\nHangi \u00e7i\u00e7ek t\u00fcr\u00fcnden ka\u00e7ar adet g\u00f6zlem bar\u0131nd\u0131r\u0131yor veri \u00e7er\u00e7evemiz?\n\n50 x 3 oldu\u011funu ve dengeli oldu\u011funu value_counts ile zaten g\u00f6rm\u00fc\u015ft\u00fck, ancak bunu g\u00f6rsel olarak ifade etmek i\u00e7in sns.countplot() fonksiyonuna variety parametresini vereilm.\n\"\"\"\nax = sns.countplot(x=\"variety\", data=df)\n\"\"\"\nsepal.length ve sepal.width de\u011fi\u015fkenlerini sns.jointplot ile g\u00f6rselle\u015ftirelim, da\u011f\u0131l\u0131m\u0131 ve da\u011f\u0131l\u0131m\u0131n frekans\u0131 y\u00fcksek oldu\u011fu b\u00f6lgelerini inceleyelim.\n\"\"\"\ng = sns.jointplot(x=\"sepal.length\", y=\"sepal.width\", data=df)\n\"\"\"\nBir \u00f6nceki h\u00fccrede yapm\u0131\u015f oldu\u011fumuz g\u00f6rselle\u015ftirmeye kind = \"kde\" parametresini ekleyelim. B\u00f6ylelikle da\u011f\u0131l\u0131m\u0131n noktal\u0131 g\u00f6sterimden \u00e7\u0131k\u0131p yo\u011funluk odakl\u0131 bir g\u00f6rselle\u015ftirmeye d\u00f6n\u00fc\u015ft\u00fc\u011f\u00fcn\u00fc g\u00f6rm\u00fc\u015f olaca\u011f\u0131z.\n\"\"\"\ng = sns.jointplot(x=\"sepal.length\", y=\"sepal.width\",kind = \"kde\", data=df)\n\"\"\"\nscatterplot ile petal.length ve petal.width de\u011fi\u015fkenlerinin da\u011f\u0131l\u0131mlar\u0131n\u0131 \u00e7izdirelim.\n\"\"\"\nsns.scatterplot(x=\"petal.length\",y=\"petal.width\",data=df)\n\"\"\"\nAyn\u0131 g\u00f6rselle\u015ftirmeye hue = \"variety\" parametresini ekleyerek 3. bir boyut verelim.\n\"\"\"\nsns.scatterplot(x=\"petal.length\",y=\"petal.width\",hue = \"variety\",data=df)\n\"\"\"\nsns.lmplot() g\u00f6rselle\u015ftirmesini petal.length ve petal.width de\u011fi\u015fkenleriyle implemente edelim. Petal length ile petal width aras\u0131nda ne t\u00fcr bir ili\u015fki var ve bu ili\u015fki g\u00fc\u00e7l\u00fc m\u00fcd\u00fcr? sorusunu yan\u0131tlayal\u0131m.\n\"\"\"\nsns.lmplot(x=\"petal.length\",y=\"petal.width\",data=df)\n\"\"\"\nBu sorunun yan\u0131t\u0131n\u0131 peki\u015ftirmek i\u00e7in iki de\u011fi\u015fken aras\u0131nda korelasyon katsay\u0131s\u0131n\u0131 yazd\u0131ral\u0131m. \n\"\"\"\ndf.corr()[\"petal.width\"][\"petal.length\"]\n\"\"\"\nPetal Length ile Sepal Length de\u011ferlerini toplayarak yeni bir total length \u00f6zniteli\u011fi olu\u015ftural\u0131m.\n\"\"\"\ndf[\"total.length\"]=df[\"sepal.length\"]+df[\"petal.length\"]\n\n\"\"\"\ntotal.length'in ortalama de\u011ferini yazd\u0131ral\u0131m. \n\"\"\"\ndf[\"total.length\"].mean()\n\"\"\"\ntotal.length'in standart sapma de\u011ferini yazd\u0131ral\u0131m.\n\"\"\"\ndf[\"total.length\"].std()\n\"\"\"\nsepal.length'in maksimum de\u011ferini yazd\u0131ral\u0131m.\n\"\"\"\ndf.max()[\"petal.length\"]\n\"\"\"\nsepal.length'i 5.5'den b\u00fcy\u00fck ve t\u00fcr\u00fc setosa olan g\u00f6zlemleri yazd\u0131ral\u0131m.\n\"\"\"\n#df[ (df[\"variety\"] == \"setosa\") & ( df[\"sepal.length\" > 5.5] ) ]\n\ndf.sort_values('sepal.length', axis = 0, ascending = False).head(1)\n\"\"\"\npetal.length'i 5'den k\u00fc\u00e7\u00fck ve t\u00fcr\u00fc virginica olan g\u00f6zlemlerin sadece sepal.length ve sepal.width de\u011fi\u015fkenlerini ve de\u011ferlerini yazd\u0131ral\u0131m.\n\"\"\"\n#df_filtered = df.query(\"petal.length<5 & variety==virginica\")[[\"sepal.length\",\"sepal.width\"]]\n\n#&(df[\"sepal.length > 5.5\"]\ndf[(df[\"variety\"] == \"setosa\") & (df[\"sepal.length\"] > 5.5)]\n\n\"\"\"\nHedef de\u011fi\u015fkenimiz variety'e g\u00f6re bir gruplama i\u015flemi yapal\u0131m de\u011fi\u015fken de\u011ferlerimizin ortalamas\u0131n\u0131 g\u00f6r\u00fcnt\u00fcleyelim.\n\"\"\"\ndf.groupby([\"variety\"]).mean()\n\"\"\"\nHedef de\u011fi\u015fkenimiz variety'e g\u00f6re gruplama i\u015flemi yaparak sadece petal.length de\u011fi\u015fkenimizin standart sapma de\u011ferlerini yazd\u0131ral\u0131m. \n\"\"\"\ndf.groupby([\"variety\"]).std()[\"petal.length\"]\n\"\"\"\nEme\u011finiz, ay\u0131rd\u0131\u011f\u0131n\u0131z vakit ve ilginiz i\u00e7in te\u015fekk\u00fcrler.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '96063cd3358f3b'}"}
{"id":"55075","text":"import numpy as np \nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nimport glob\nimport json\nimport re\nimport os\n# for dirname, _, filenames in os.walk('\/kaggle\/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\"\"\"\n**Goal**\n- With a large amount of literature and fast spreading of COVID-19. It's difficult for health care professionals figure out relevant research. \n- In this post, we will try to identify which topic is discussed in research. It also reduce number of articles which scientist has go through. \n- Research paper topic modelling is an unsupervised machine learning method which allow us to learn topic of articles in corpus\n\"\"\"\n\"\"\"\n*ok Lets go*\n- Because kaggle provided us lot of json file so we will load all json data to dataframe and drop abstract duplicate to make sure unique articles\n\"\"\"\n\npath = '\/kaggle\/input\/'\nall_json = glob.glob(f'{path}\/**\/*.json', recursive=True)\nclass FileReader:\n    def __init__(self, file_path):\n        with open(file_path) as file:\n            content = json.load(file)\n            self.paper_id = content['paper_id']\n            self.abstract = []\n            self.body_text = []\n            for entry in content['abstract']:\n                self.abstract.append(entry['text'])\n            for entry in content['body_text']:\n                self.body_text.append(entry['text'])\n            self.abstract = '\\n'.join(self.abstract)\n            self.body_text = '\\n'.join(self.body_text)\ndict_ = {'paper_id': [], 'abstract': [], 'body_text': []}\nfor idx, entry in enumerate(all_json):\n    if idx % (len(all_json) \/\/ 10) == 0:\n        print(f'Processing index: {idx} of {len(all_json)}')\n    content = FileReader(entry)\n    dict_['paper_id'].append(content.paper_id)\n    dict_['abstract'].append(content.abstract)\n    dict_['body_text'].append(content.body_text)\ncovid_df = pd.DataFrame(dict_, columns=['paper_id', 'abstract', 'body_text'])\ncovid_df.drop_duplicates(['abstract'], inplace=True)\ncovid_df.head()\n\"\"\"\nWe have to clean-up the text by\u00a0\n- Remove punctuation\n- Convert each text to lower case\n\"\"\"\ncovid_df['body_text'] = covid_df['body_text'].apply(lambda x: re.sub('[^a-zA-z0-9\\s]','',x))\ncovid_df['abstract'] = covid_df['abstract'].apply(lambda x: re.sub('[^a-zA-z0-9\\s]','',x))\n\ndef lower_case(input_str):\n    input_str = input_str.lower()\n    return input_str\n\ncovid_df['body_text'] = covid_df['body_text'].apply(lambda x: lower_case(x))\ncovid_df['abstract'] = covid_df['abstract'].apply(lambda x: lower_case(x))\ncovid_df.head()\n\"\"\"\n- Because we only need body_text of the article so we will drop paper_id and abstract then save clean file, we will use it later\n\"\"\"\ntext = covid_df.drop([\"paper_id\", \"abstract\"], axis=1)\ntext.head()\ntext.to_csv('.\/clean_text.csv')\n\"\"\"\n- Next we will import spacy. If you never installed spacy before then you have to install before import\n- If you are using anaconda then implement\n    - *conda install -c conda-forge spacy*\n- If you are not using anaconda and you want to install via pip then implement:\n    - *pip install -U spacy*\n- If you want to install from source then implement:\n    - *git clone https:\/\/github.com\/explosion\/spaCy\n    - *cd spaCy*\n    - *pip install -r requirements.txt*\n    - *python setup.py build_ext\u200a-\u200ainplace*\n- You can refer to this page for more option: https:\/\/spacy.io\/usage\n- **Then what is spaCy\u00a0?**\n    - spaCy is a free, open-source library for advanced Natural Language Processing (NLP) in Python.\n    - If you're working with a lot of text, you'll eventually want to know more about it. For example, what's it about? What do the words mean in context? Who is doing what to whom? What companies and products are mentioned? Which texts are similar to each other?\n    - spaCy is designed specifically for production use and helps you build applications that process and \"understand\" large volumes of text. It can be used to build information extraction or natural language understanding systems, or to pre-process text for deep learning ([source](https:\/\/spacy.io\/usage\/spacy-101))\n- ok let's import spacy\n\"\"\"\nimport spacy\nspacy.load('en')\nfrom spacy.lang.en import English\nparser = English()\n\"\"\"\n- We will use following function to clean our text and return list of tokens:\n\"\"\"\ndef tokenize(text):\n    lda_tokens = []\n    tokens = parser(text)\n    for token in tokens:\n        if token.orth_.isspace():\n            continue\n        elif token.like_url:\n            lda_tokens.append('URL')\n        elif token.orth_.startswith('@'):\n            lda_tokens.append('SCREEN_NAME')\n        else:\n            lda_tokens.append(token.lower_)\n    return lda_tokens\n\"\"\"\nWe use NLTK\u2019s Wordnet to find the meanings of words, synonyms, antonyms, and more. In addition, we use WordNetLemmatizer to get the root word.\n\"\"\"\n\"\"\"\n- We use NLTK Wordnet and WordNetLemmatizer to find the meaning of words such as synonyms, antonyms, etc. and also get the root word\n- Before that feel free to install nltk and download wordnet together with stopword\n    - *pip install\u200a-\u200auser -U nltk*\n    - *nltk.download('wordnet')*\n    - *nltk.download('stopwords')*\n\"\"\"\nimport nltk\nfrom nltk.corpus import wordnet as wn\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\ndef get_lemma(word):\n    lemma = wn.morphy(word)\n    if lemma is None:\n        return word\n    else:\n        return lemma\ndef get_lemma2(word):\n    return WordNetLemmatizer().lemmatize(word)\n\"\"\"\n- Filter out stop words:\n\"\"\"\nen_stop = set(nltk.corpus.stopwords.words('english'))\n\"\"\"\n- We can define a function to prepare the text for topic modelling\n\"\"\"\ndef prepare_text_for_lda(text):\n    tokens = tokenize(text)\n    tokens = [token for token in tokens if len(token) > 4]\n    tokens = [token for token in tokens if token not in en_stop]\n    tokens = [get_lemma(token) for token in tokens]\n    return tokens\n\"\"\"\n- Open up our data, read line by line, for each line, prepare text for LDA, then add to a list.\n\n\"\"\"\nimport random\nfrom random import randint\n\ntext_data = []\nwith open('.\/clean_text.csv') as f:\n    for line in f:\n        tokens = prepare_text_for_lda(line)\n        value = randint(0, 100)\n        if value==99:\n            text_data.append(tokens)\n\"\"\"\n**Latent Dirichlet Allocation (LDA) with\u00a0Gensim**\n- What is Gensim\u00a0?\n    - Gensim = \"Generate Similar\".\u00a0\n    - Gensim started off as a collection of various Python scripts for the Czech Digital Mathematics Library dml.cz in 2008, where it served to generate a short list of the most similar articles to a given article (source)\n- Install Gensim via anaconda\n    - conda install -c anaconda gensim\n- Install Gensim via pip\n    - pip install\u200a-\u200aupgrade gensim\n    \n**Then what is\u00a0LDA**\n- In natural language processing, the latent Dirichlet allocation (LDA) is a generative statistical model that allows sets of observations to be explained by unobserved groups that explain why some parts of the data are similar. For example, if observations are words collected into documents, it posits that each document is a mixture of a small number of topics and that each word's presence is attributable to one of the document's topics. LDA is an example of a topic model and belongs to the machine learning toolbox and in wider sense to the artificial intelligence toolbox (source)\n- Ok, we will create a dictionary from the data, then convert to bag-of-words corpus and save the dictionary and corpus for future use\n\"\"\"\nfrom gensim import corpora\ndictionary = corpora.Dictionary(text_data)\ncorpus = [dictionary.doc2bow(text) for text in text_data]\nimport pickle\npickle.dump(corpus, open('corpus.pkl', 'wb'))\ndictionary.save('dictionary.gensim')\n\"\"\"\n- So we are trying to ask LDA to find 20 topics in the data\n\"\"\"\nimport gensim\nNUM_TOPICS = 10\nldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics = NUM_TOPICS, id2word=dictionary, passes=15)\nldamodel.save('model10.gensim')\ntopics = ldamodel.print_topics(num_words=4)\nfor topic in topics:\n    print(topic)\n\"\"\"\nAll topic related to virus mechanism but research on difference way\n\"\"\"\n\"\"\"\n# pyLDAvis\n- pyLDAvis is designed to help users interpret the topics in a topic model that has been fit to a corpus of text data. The package extracts information from a fitted LDA topic model to inform an interactive web-based visualization.\n- Visualizing 20 topics:\n\"\"\"\ndictionary = gensim.corpora.Dictionary.load('dictionary.gensim')\ncorpus = pickle.load(open('corpus.pkl', 'rb'))\nlda = gensim.models.ldamodel.LdaModel.load('model10.gensim')\nimport pyLDAvis.gensim\nlda_display = pyLDAvis.gensim.prepare(lda, corpus, dictionary, sort_topics=False)\npyLDAvis.display(lda_display)\n\"\"\"\n- Saliency: a measure of how much the term tells you about the topic.\n- Relevance: a weighted average of the probability of the word given the topic and the word given the topic normalized by the probability of the topic.\n- The size of the bubble measures the importance of the topics, relative to the data.\n- First, we got the most salient terms, means terms mostly tell us about what\u2019s going on relative to the topics. We can also look at individual topic.\n\"\"\"\n\"\"\"\n> When we have 10 or more topics, we can see certain topics are clustered together, this indicates the similarity between topics\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6584a83b928e56'}"}
{"id":"65450","text":"\"\"\"\n# Song Popularity Prediction Notebook\n\"\"\"\n#Load the liberaries\n\nimport numpy as np\nimport pandas as pd \npd.set_option('display.max_columns' ,500)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\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\n#Helper functions code\n\n\ndef investigate_continues_variable(df , column , bins =30 ):\n    \"\"\"\n    Function to devide the continues varibales into equal bins \n    then plot a chart showing the \n    counts of popular and un-popular songs \n    accross deffrinet continues numrical variables\n    and line chart showing the percentage of the popularity across the selected bins\n    \n    input : \n        original data frame  -pandas df\n        column name - str\n        bins number  - int\n    \n    output :\n        chart - matplotlib.pyplot\n    \n    \"\"\"\n    \n    \n    #Create new data frame using cross tap between the song popularity and the variables bins\n    df_plot = df.copy()\n    df_plot =df_plot.reset_index()\n    df_plot['bins'] = pd.cut(df_plot[column] , bins = bins ,\n                                  labels=range(0,bins))\n    df_plot1 = pd.DataFrame(pd.crosstab(df_plot['bins'],df_plot['song_popularity']),)\n    df_plot1['Popularity_Percenatge'] = df_plot1[1] \/ (df_plot1[1] + df_plot1[0]) * 100\n    \n    \n    \n    \n    #plot the distribution using matplotlib.pyplot\n    ind = np.arange(bins)\n    width = 0.3\n\n    fig, ax1 = plt.subplots(figsize = (15 ,5))\n    ax2 = ax1.twinx()\n    ax2.plot(df_plot1.index ,  df_plot1.Popularity_Percenatge  ,label='Percentage of Popularity'  ,\n                   ls =':' , lw = 2 , color = 'red' , zorder = 100)\n    \n    ax2.set_ylim(0,100)\n    ax2.set_ylabel(\"Percentage of Popularity\" , color = 'red' , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax2.tick_params(axis='y', colors='red')\n    ax2.spines['right'].set_color('red')\n    ax2.spines['top'].set_visible(False)\n    \n    #ax1 setup\n    ax1.set_title(f'Percentage of songs Popularity Accross {column}'.title() , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.set_xlim(1,bins-1)\n\n    ax1.bar(ind, df_plot1[1] , width, label='Counts of  Popular songs' , color  = '#23a108' ,\n                  edgecolor  = 'black' ,hatch =  '*')\n    ax1.bar(ind+width, df_plot1[0] , width , label='Counts of un-Popular Songs' , color  = '#8ea389' ,\n                  edgecolor  = 'black' )\n\n    ax1.set_xlabel(f\"Range of {column} from {round(df[column].min() , 3)} to {round(df[column].max(),3)} divided to {bins} equivilant Bins\" ,\n                  fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.set_ylabel(\"Counts Per each Bin\" , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.spines['top'].set_visible(False)\n    ax1.spines['right'].set_color('red')\n    ax1.set_xticks([])\n    \n    fig.legend( bbox_to_anchor=(0.2, 1.02, 0.6, .102), loc='lower left',\n                      ncol=3, mode=\"expand\", borderaxespad=0.)\n    plt.show()\n    \n\n\n    \ndef investigate_discrete_Variables (df , column):\n    \"\"\"\n    Function to plot a bar chart showing the \n    counts of popular and un-popular songs \n    accross deffrinet continues numrical variables\n    \n    input : \n        original data frame  -pandas df\n        column name - str\n    \n    output :\n        chart - matplotlib.pyplot\n    \n    \n    \"\"\"\n    new = df.groupby([column , 'song_popularity']).size().reset_index()\n    pop = new[new.song_popularity == 1]\n    unpop = new[new.song_popularity  == 0]\n    \n    pop[column].apply(str)\n    unpop[column].apply(str)\n    \n    \n    ind = np.arange(len(pop[column]))\n    width = 0.3\n\n\n    fig, ax1 = plt.subplots(figsize = (15 ,5))\n    \n    #ax1 setup\n    ax1.set_title(f'Counts of Popular and non-Popular songs Accross {column}'.title() , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n\n    ax1.bar(ind, pop[0] , width, label='Counts of  Popular songs' , color  = '#23a108' ,\n                  edgecolor  = 'black' ,hatch =  '*')\n   \n    ax1.bar(ind+width, unpop[0] , width , label='Counts of un-Popular Songs' , color  = '#8ea389' ,\n                  edgecolor  = 'black' )\n\n    \n\n    ax1.set_ylabel(\"Counts \" , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.spines['top'].set_visible(False)\n    ax1.spines['right'].set_visible(False)\n    \n    ax1.set_xticks(pop[column])\n    \n    fig.legend( bbox_to_anchor=(0.2, 1.02, 0.6, .102), loc='lower left',\n                      ncol=3, mode=\"expand\", borderaxespad=0.)\n    ax1.grid(axis = 'y' , zorder =-1 , linestyle =\":\")\n    plt.show()\n\ntrain = pd.read_csv('\/kaggle\/input\/song-popularity-prediction\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/song-popularity-prediction\/test.csv')\ntest['song_popularity'] = np.nan\ndf = pd.concat([train, test])\n\ndisplay(df)\n\"\"\"\n\n!pip install sweetviz\nimport sweetviz\nreport = sweetviz.analyze([train,'df'],target_feat='song_popularity')\nreport.show_html('report.html')\n\n\"\"\"\nprint('Pass')\n\"\"\"\n# Data Cleaning Pipe Line \n\"\"\"\n\n#Reload the Data frame\ndf = pd.concat([train, test])\n\n#df.id\ndf.drop(['id' , 'instrumentalness' ] ,axis  = 1 , inplace = True)\n\n\n#df.song_duration_ms\ndf.song_duration_ms.fillna(df.song_duration_ms.mean() , inplace = True)\ndf.song_duration_ms = df.song_duration_ms.apply(lambda x: df.tempo.mean() if x >400000 else x)\n\n#df.acousticness\nfrom sklearn.preprocessing import PowerTransformer\nPower_Transfrom_acous = PowerTransformer(method='yeo-johnson')\ndf.acousticness = Power_Transfrom_acous.fit_transform(df.acousticness.values.reshape(-1, 1))\ndf.acousticness.fillna(df.acousticness.mode()[0] , inplace = True)\n\n\n#df.danceability\ndf.danceability.fillna(df.danceability.mean() , inplace = True)\n\n\n#df.energy\ndf.energy.fillna(df.energy.mean() , inplace = True)\n\n\n#df.liveness\ndf.liveness = df.liveness.apply(lambda x: df.liveness.mean() if x>0.75 else x)\nPower_Transfrom_liv = PowerTransformer(method='yeo-johnson')\ndf.liveness = Power_Transfrom_liv.fit_transform(df.liveness.values.reshape(-1, 1))\ndf.liveness.fillna(df.liveness.mode()[0] , inplace = True)\n\n#df.loudness\nPower_Transfrom_loud = PowerTransformer(method='yeo-johnson')\ndf.loudness= Power_Transfrom_loud.fit_transform(df.loudness.values.reshape(-1, 1))\ndf.loudness.fillna(df.loudness.mean() , inplace = True)\n\n\n\n#df.speechiness\ndf.speechiness = df.speechiness.apply(lambda x: df.speechiness.mean() if x>0.45 else x)\nPower_Transfrom_speac= PowerTransformer(method='yeo-johnson')\ndf.speechiness = Power_Transfrom_speac.fit_transform(df.speechiness.values.reshape(-1, 1))\ndf.speechiness.fillna(df.speechiness.mode()[0] , inplace = True)\n\n\n#df.tempo\ndf.tempo = df.tempo.apply(lambda x: df.tempo.mean() if x >190 else x)\ndf.tempo.fillna(df.tempo.mean() , inplace = True)\n\n#df.audio_valence\ndf.audio_valence.fillna(df.audio_valence.mean() , inplace = True)\n\n#df.key\ndf.key.fillna(12 , inplace = True)\n\n\n\n\"\"\"\n# Checking the outliers after data cleaning\n\"\"\"\nfig , ax = plt.subplots(3,4 , figsize = (10,10))\nfor column  , axes in zip(df.columns , ax.flatten()):\n    axes.boxplot(df[column] , patch_artist=True , boxprops=dict(facecolor='#23a108', edgecolor  = 'black' ,hatch =  '*'))\n    axes.set_title(column)\n\nplt.tight_layout()\nplt.show()\n\"\"\"\n\n\n!pip install sweetviz\nimport sweetviz\ntrain = df[df.song_popularity.notnull()]\nreport = sweetviz.analyze([train,'df'],target_feat='song_popularity')\nreport.show_html('report.html')\n\n\"\"\"\nprint ('pass')\n\"\"\"\n# Visualize the continues numirical variables\n\"\"\"\nContinues_numerical = ['song_duration_ms','acousticness','danceability', 'energy',\n                       'liveness', 'loudness', 'speechiness', 'tempo', 'audio_valence']\n\n\n\nfor column in Continues_numerical:\n    investigate_continues_variable(df , column  , bins = 25)\n\npopular = []\nunpopular = []\nfor column in Continues_numerical:\n    popular.append(df[df.song_popularity == 1][column].mean())\n    unpopular.append(df[df.song_popularity == 0][column].mean())\n\nind = 1\nwidth = 0.3  \nfig , ax = plt.subplots(3,3 , figsize  = (15 ,15))\nfor column , pop , unpop , axes in zip (Continues_numerical , popular , unpopular , ax.flatten()):\n    \n    axes.bar(ind, pop , width, label='Average of  Popular songs' , color  = '#23a108' ,\n                  edgecolor  = 'black' ,hatch =  '*' )\n    axes.bar(ind+width+0.1, unpop , width , label='Average un-Popular Songs' , color  = '#8ea389' ,\n                  edgecolor  = 'black' )\n    axes.set_title(column ,fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold' )\n    axes.spines['top'].set_visible(False)\n    axes.spines['right'].set_visible(False)\n    axes.set_xticks([])\n\n    \nfont = {'family':'serif','weight':'bold','style':'normal', 'size':12}\n\nfig.suptitle('Compasion between the average of Continues Variables accross the popularity'.title(), \n             fontsize = 16 , fontfamily = 'serif' , fontweight = 'bold')\nax[0,0].legend(bbox_to_anchor=(0.2, 1.2, 3, .102), loc='lower left',\n                      ncol=2, mode=\"expand\", borderaxespad=0. , prop = font)\nplt.show();\n\"\"\"\n# Inverstigate the Descrete columns\n\"\"\"\ndescrite_numerical = [ 'key','audio_mode','time_signature']\nfor column in descrite_numerical:\n    investigate_discrete_Variables (df , column)\n\"\"\"\n# Check the coorrelation with the song popularity\n\"\"\"\ncorr_df = df.drop('song_popularity', axis=1).corrwith(df.song_popularity).sort_values().reset_index().rename(columns = {'index':'feature' ,0:'correlation'})\n\nfig , ax = plt.subplots(figsize  = (5,8))\nax.barh(y =corr_df.feature , width = corr_df.correlation ,\n        color  = '#23a108' ,edgecolor  = 'black' ,hatch =  '*' )\nax.set_title('correlation between featuer and target'.title() ,\n            fontsize = 16 , fontfamily = 'serif' , fontweight = 'bold')\nplt.show();\ndf.drop(['tempo' , 'audio_mode' ,'song_duration_ms',  'key' ] , axis = 1 , inplace = True)\n\"\"\"\n# Try PCA and clustring of the train data\n\"\"\"\nnp.random.seed(42)\n\n\ntrain = df[df.song_popularity.notnull()]\n\nfrom sklearn.preprocessing import StandardScaler\nSC = StandardScaler()\n\ntrain_scale = SC.fit_transform(train)\n\n\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=3)\nprincebal_componants_array = pca.fit_transform(train_scale)\n\nfrom sklearn.cluster import KMeans\nmodel42 = KMeans(n_clusters=10 , random_state=42)\nmodel42.fit(princebal_componants_array)\n\nlabels = model42.labels_\n\ntrain ['labels'] = labels\n\n    \n    \ncorr_df = train.drop('song_popularity', axis=1).corrwith(train.song_popularity).sort_values().reset_index().rename(columns = {'index':'feature' ,0:'correlation'})\nfig , ax = plt.subplots(figsize  = (5,8))\nax.barh(y =corr_df.feature , width = corr_df.correlation ,\n        color  = '#23a108' ,edgecolor  = 'black' ,hatch =  '*' )\nax.set_title('correlation between featuer and target after adding the labels'.title() ,\n            fontsize = 16 , fontfamily = 'serif' , fontweight = 'bold')\nplt.show();\ndef investigate_continues_variable_7_2 (df ,label ,  column , bins =30 , ax1=None ):\n    \"\"\"\n    Function to devide the continues varibales into equal bins \n    then plot a chart showing the \n    counts of popular and un-popular songs \n    accross deffrinet continues numrical variables\n    and line chart showing the percentage of the popularity across the selected bins\n    \n    input : \n        original data frame  -pandas df\n        column name - str\n        bins number  - int\n    \n    output :\n        chart - matplotlib.pyplot\n    \n    \"\"\"\n    \n    \n    #Create new data frame using cross tap between the song popularity and the variables bins\n    df_plot = df.copy()\n    df_plot =df_plot.reset_index()\n    df_plot = df_plot[df_plot.labels == label]\n    df_plot['bins'] = pd.cut(df_plot[column] , bins = bins ,\n                                  labels=range(0,bins))\n    df_plot1 = pd.DataFrame(pd.crosstab(df_plot['bins'],df_plot['song_popularity']),)\n    df_plot1['Popularity_Percenatge'] = df_plot1[1] \/ (df_plot1[1] + df_plot1[0]) * 100\n    \n    \n    \n    \n    #plot the distribution using matplotlib.pyplot\n    ind = np.arange(bins)\n    width = 0.3\n\n    \n    ax2 = ax1.twinx()\n    ax2.plot(df_plot1.index ,  df_plot1.Popularity_Percenatge  ,label='Percentage of Popularity'  ,\n                   ls =':' , lw = 2 , color = 'red' , zorder = 100)\n    \n    ax2.set_ylim(0,100)\n    ax2.set_ylabel(\"Percentage of Popularity\" , color = 'red' , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax2.tick_params(axis='y', colors='red')\n    ax2.spines['right'].set_color('red')\n    ax2.spines['top'].set_visible(False)\n    \n    #ax1 setup\n    ax1.set_title(f'Percentage of songs Popularity Accross {column} Label number {label}'.title() , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.set_xlim(1,bins-1)\n\n    ax1.bar(ind, df_plot1[1] , width, label='Counts of  Popular songs' , color  = '#23a108' ,\n                  edgecolor  = 'black' ,hatch =  '*')\n    ax1.bar(ind+width, df_plot1[0] , width , label='Counts of un-Popular Songs' , color  = '#8ea389' ,\n                  edgecolor  = 'black' )\n\n    ax1.set_xlabel(f\"Range of {column} from {round(df[column].min() , 3)} to {round(df[column].max(),3)} divided to {bins} equivilant Bins\" ,\n                  fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.set_ylabel(\"Counts Per each Bin\" , fontsize = 12 , fontfamily = 'serif' , fontweight = 'bold')\n    ax1.spines['top'].set_visible(False)\n    ax1.spines['right'].set_color('red')\n    ax1.set_xticks([])\n    \n    \n    \ntrain ['labels'] = labels\nfor label in train.labels.unique().tolist():\n    print (label, \" :  mean of popularity \" , round(train[train.labels ==label].song_popularity.mean() , 2) , \" & Count per label \" , train[train.labels ==label].song_popularity.count())\n    print ('_________________________')\ntrain.labels = train.labels.apply(lambda x: 100 if x in [2, 9 , 5 , 4 ] else x)\ntrain.labels = train.labels.apply(lambda x: 200 if x in [0 , 3 , 8 ] else x)\ntrain.labels = train.labels.apply(lambda x: 300 if x in [1 , 7 , 6 ] else x)\nfor label in train.labels.unique().tolist():\n    print (\"label number\" ,label, \" :  mean of song popularity \" , round(train[train.labels ==label].song_popularity.mean() , 2) , \" & Count per label \" , train[train.labels ==label].song_popularity.count())\n    print ('_________________________')\nfig , ax = plt.subplots(2,2 , figsize = (15,10))\n\n\n\ninvestigate_continues_variable_7_2 (train ,100 ,  column = 'energy' , bins =15 , ax1=ax[0,0] )\ninvestigate_continues_variable_7_2 (train ,300 ,  column = 'energy' , bins =15 , ax1=ax[0,1] )\ninvestigate_continues_variable_7_2 (train ,100,  column = 'speechiness' , bins =15 , ax1=ax[1,0] )\ninvestigate_continues_variable_7_2 (train ,300 ,  column = 'speechiness' , bins =15 , ax1=ax[1,1] )\nplt.tight_layout()\n\"\"\"\n# Predict the new labels in the test dataset\n\"\"\"\ntrain.head()\nfrom sklearn.preprocessing import StandardScaler\nSC = StandardScaler()\n\ntrain['energy_double'] = train.energy * 10\ntrain['speechiness_double'] = train.speechiness *10\n\ntrain_after_clsuster = train.drop(['song_popularity' , 'labels'] , axis = 1).values\ntrain_after_clsuster = SC.fit_transform(train_after_clsuster)\n\n\n\ntarget = train.labels.values\n\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(train_after_clsuster, target, test_size=0.25, random_state=42)\n\n\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import accuracy_score\n\nneural_network = MLPClassifier()\nneighbors = KNeighborsClassifier()\nsvm = SVC()\nkernels = RBF()\ntree = DecisionTreeClassifier()\nRandomForestClassifier = RandomForestClassifier()\nAdaBoostClassifier = AdaBoostClassifier()\nnaive_bayes = GaussianNB()\ndiscriminant_analysis = QuadraticDiscriminantAnalysis()\n\nclfs = [neural_network ,neighbors ,  svm   ]\nnames = ['neural_network' ,'neighbors' ,  'svm'  ]\n\n\nfor clf , name in zip (clfs , names):\n    clf.fit(X_train, y_train)\n    predict_train = clf.predict(X_train)\n    predict_test = clf.predict(X_test)\n    \n    print (name)\n    print ('train ROC : ' , accuracy_score(y_train , predict_train))\n    print ('test ROC : ' , accuracy_score(y_test , predict_test))\n    print ('_________________________')\nclfs = [tree ,  \n        RandomForestClassifier , AdaBoostClassifier , naive_bayes ,discriminant_analysis  ]\nnames = ['tree' ,  \n        'RandomForestClassifier' , 'AdaBoostClassifier' , 'naive_bayes' ,'discriminant_analysis'  ]\n\n\nfor clf , name in zip (clfs , names):\n    clf.fit(X_train, y_train)\n    predict_train = clf.predict(X_train)\n    predict_test = clf.predict(X_test)\n    \n    print (name)\n    print ('train ROC : ' , accuracy_score(y_train , predict_train))\n    print ('test ROC : ' , accuracy_score(y_test , predict_test))\n    print ('_________________________')\n\"\"\"\n# Adding labels to the test dataset\n\"\"\"\ntest = df[df.song_popularity.isnull()].drop('song_popularity' , axis = 1)\ntest['energy_double'] = test.energy * 10\ntest['speechiness_double'] = test.speechiness *10\ntest_scaled = SC.transform(test.values)\ntest_labels = neural_network.predict(test_scaled)\n\ntest['labels'] = test_labels\ntest.head()\ntrain.head()\n\"\"\"\n# Predict the song popularity according to the new features\n\"\"\"\n\"\"\"\n# Regressor\n\"\"\"\nX = train.drop('song_popularity' , axis = 1).values\ny = train.song_popularity.values\nX = SC.fit_transform(X)\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\n\n\nimport os\nimport pandas as pd\nfrom pandas import DataFrame,Series\nfrom sklearn import tree\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nfrom sklearn.preprocessing import StandardScaler\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sns\nfrom sklearn import neighbors\nfrom sklearn import linear_model\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.ensemble import RandomForestRegressor\n%matplotlib inline\n\n\nmodel=linear_model.Ridge()\nknn=neighbors.KNeighborsRegressor()\nreg = linear_model.BayesianRidge()\ndec = tree.DecisionTreeRegressor(max_depth=1)\nsvm_reg=svm.SVR()\nreg_random_forest = RandomForestRegressor()\n\n\n\nregs = [model ,knn , reg ,dec  ]\nnames = ['model' ,'knn' , 'reg' ,'dec'  ]\n\nfor reg , name in zip (regs , names):\n    reg.fit(X_train, y_train)\n    predict_train = reg.predict(X_train)\n    predict_test = reg.predict(X_test)\n    \n    print (name)\n    print ('train ROC : ' , roc_auc_score(y_train , predict_train))\n    print ('test ROC : ' , roc_auc_score(y_test , predict_test))\n    print ('_________________________')\n\"\"\"\n# Classifier Comparasion\n\"\"\"\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.metrics import roc_auc_score\n\nneural_network = MLPClassifier()\nneighbors = KNeighborsClassifier()\nsvm = SVC()\nkernels = RBF()\ntree = DecisionTreeClassifier()\nRandomForestClassifier = RandomForestClassifier()\nAdaBoostClassifier = AdaBoostClassifier()\nnaive_bayes = GaussianNB()\ndiscriminant_analysis = QuadraticDiscriminantAnalysis()\n\nclfs = [neural_network ,neighbors ,  svm   ]\nnames = ['neural_network' ,'neighbors' ,  'svm'  ]\n\n\nfor clf , name in zip (clfs , names):\n    clf.fit(X_train, y_train)\n    predict_train = clf.predict(X_train)\n    predict_test = clf.predict(X_test)\n    \n    print (name)\n    print ('train ROC : ' , roc_auc_score(y_train , predict_train))\n    print ('test ROC : ' , roc_auc_score(y_test , predict_test))\n    print ('_________________________')\nclfs = [tree ,  \n        RandomForestClassifier , AdaBoostClassifier , naive_bayes ,discriminant_analysis  ]\nnames = ['tree' ,  \n        'RandomForestClassifier' , 'AdaBoostClassifier' , 'naive_bayes' ,'discriminant_analysis'  ]\n\n\nfor clf , name in zip (clfs , names):\n    clf.fit(X_train, y_train)\n    predict_train = clf.predict(X_train)\n    predict_test = clf.predict(X_test)\n    \n    print (name)\n    print ('train ROC : ' , roc_auc_score(y_train , predict_train))\n    print ('test ROC : ' , roc_auc_score(y_test , predict_test))\n    print ('_________________________')\n\"\"\"\n# Submission\n\"\"\"\ntest = SC.transform(test)\nsubmision_prediction = knn.predict(test)\nsubmission = pd.read_csv('\/kaggle\/input\/song-popularity-prediction\/sample_submission.csv')\nsubmission['song_popularity'] =submision_prediction\nsubmission.to_csv('knn.scv' , index = False)","meta":"{'source': 'AI4Code', 'id': '78c20bd1fb29c4'}"}
{"id":"58865","text":"\"\"\"\n# American sign language alphabets recognition using multi-layer perceptron network.\n\"\"\"\n# Importing the libraries.\n\nimport tensorflow as tf\nimport cv2\nfrom glob import glob\nfrom matplotlib import pyplot as plt\nimport random\nimport math\nimport os\nimport numpy as np\nfrom numpy.random import seed\nseed(100)\nfrom tensorflow import set_random_seed\nset_random_seed(101)\n\n# A utility function to display sample images from the dataset.\n\n\ndef plotSample(character):\n    print(\"Samples images for letter \" + character)\n    basePath = '..\/input\/asl_alphabet_train\/asl_alphabet_train\/'\n    imagePath = basePath + character + '\/**'\n    pathData = glob(imagePath)\n    \n    plt.figure(figsize=(16,16))\n    images = random.sample(pathData, 3)\n    plt.subplot(1,3,1)\n    plt.imshow(cv2.imread(images[0]))\n    plt.subplot(1,3,2)\n    plt.imshow(cv2.imread(images[1]))\n    plt.subplot(1,3,3)\n    plt.imshow(cv2.imread(images[2]))\n    plt.colorbar()\n    plt.show()\n    return\nplotSample('H')\n\"\"\"\n### Importing the data using ImageDataGenerator module from Tensorflow.\n\"\"\"\ndataPath = \"..\/input\/asl_alphabet_train\/asl_alphabet_train\"\nresizeTuple = (64, 64)\nresizeDim = (64, 64, 3)\nnumLabels = 29\nbatchSize = 64\n\ndata_generator = tf.keras.preprocessing.image.ImageDataGenerator(samplewise_center=True, \n                                    samplewise_std_normalization=True, \n                                    validation_split=0.1)\n\ntrain_generator = data_generator.flow_from_directory(dataPath, target_size=resizeTuple, batch_size=batchSize, shuffle=True, subset=\"training\")\nval_generator = data_generator.flow_from_directory(dataPath, target_size=resizeTuple, batch_size=batchSize, subset=\"validation\")\n# A utility function to plot the loss and accuracy learning curves.\n\ndef plotCurves(history):\n    # Plotting history for accuracy\n    plt.plot(history.history['acc'])\n    plt.plot(history.history['val_acc'])\n    plt.title('model accuracy')\n    plt.ylabel('accuracy')\n    plt.xlabel('epoch')\n    plt.legend(['training accuracy', 'validation accuracy'], loc='upper right')\n    plt.show()\n\n\n    # Plotting history for losses\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n    plt.legend(['training loss', 'validation loss'], loc='upper right')\n    plt.show()\n\"\"\"\n### Defining a basic neural network model. This will be a shallow network. The numpy array representing a image will be unpacked and flattened to form a vector. This will be done for all images. The first two hidden layers contains 15 neurons with ReLU activation and some level of L2 regularization with lambda = 0.002. The output layer will contain 29 neurons with softmax activation for multi-class classification.\n\"\"\"\nmodel_1 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape=resizeDim),\n    tf.keras.layers.Dense(15, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.002)),\n    tf.keras.layers.Dense(15, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.002)),\n    tf.keras.layers.Dense(29, activation = \"softmax\")\n])\n\nmodel_1.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[\"accuracy\"])\n\nhistory = model_1.fit_generator(train_generator, epochs=10, steps_per_epoch = 1224,validation_data=val_generator, validation_steps = 136, verbose = 1)\n\nplotCurves(history)\n\"\"\"\n### Note: One can observe in the above learning curves that the loss minimization for validation dataset is not consistently decreasing which means that there is less learning happening over validation dataset (no generalization) even though the network is learning comparitively well on the training dataset. This is a clear sign of overfitting. We can avoid the huge gap between the loss curves over training and validation datasets by increasing regularization in our network.\n\"\"\"\n\"\"\"\n### The below network includes a dropout layer with keep probability = 0.8 which means that each neuron in the layer has 20% chance of being dropped out. This will introduce some noise to our network thus increasing the regularization effect.\n\n#### Note: We have removed the regularization from our second hidden layer and increased the lambda for L2 regularization in our first layer to 0.005 from 0.002 initially.\n\"\"\"\nmodel_2 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape=resizeDim),\n    tf.keras.layers.Dense(15, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dropout(0.2),\n    tf.keras.layers.Dense(15, activation = \"relu\"),\n    tf.keras.layers.Dense(29, activation = \"softmax\")\n])\n\nmodel_2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[\"accuracy\"])\n\nhistory = model_2.fit_generator(train_generator, epochs=10, steps_per_epoch = 1224,validation_data=val_generator, validation_steps = 136, verbose = 1)\n\nplotCurves(history)\n\"\"\"\n### Note: The above trained model shows comparitively better performance over validation dataset than training dataset. The loss learning curve for the validation dataset shows that the loss decreases overall throughout the training process but is still inconsistent. We can also notice that the accuracy over the training and validation dataset is extremely low. Therefore, let us now try a compartively more complex model with more layers and neurons per layer and little more regularization to compensate for the added complexity.\n\n#### We also start with a lower learning rate (earlier: default learning_rate was used which is 0.01) in our next model and include a callback to learning_rate scheduler so that the learning_rate is reduced over time to avoid divergence when close to the loss minimum.\n\"\"\"\n# A utility function to define a learning_rate decay based on epoch schedule.\n\ndef scheduler(epoch):\n    if epoch < 5:\n        return 0.00001\n    else:\n        return 0.00001 * math.exp(0.1 * (5 - epoch))\nmodel_3 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape=resizeDim),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dropout(0.1),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dropout(0.1),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dense(100, activation = \"relu\"),\n    tf.keras.layers.Dense(100, activation = \"relu\"),\n    tf.keras.layers.Dense(50, activation = \"relu\"),\n    tf.keras.layers.Dense(29, activation = \"softmax\")\n])\n\nmodel_3.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[\"accuracy\"])\n\ncallback = tf.keras.callbacks.LearningRateScheduler(scheduler)\n\nhistory = model_3.fit_generator(train_generator, epochs=10, steps_per_epoch = 1224,validation_data=val_generator, validation_steps = 136, callbacks = [callback], verbose = 1)\n\nplotCurves(history)\n\"\"\"\n### Note: The above learning curves show that the network is learning in a better way now. The training accuracy goes well upto 70% and validation accuracy goes upto 56.5%. The training and validation loss curves are still decreasing at the end of the training phase. This indicates that there is more room for learning. Therefore, we can run the model for more epochs. We will also have to tweak our learning_rate scheduler callback according to the number of epochs set.\n\"\"\"\n# A utility function to define a learning_rate decay based on epoch schedule.\n\ndef scheduler(epoch):\n    if epoch < 25:\n        return 0.00001\n    else:\n        return 0.00001 * math.exp(0.1 * (25 - epoch))\nmodel_4 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape=resizeDim),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dropout(0.1),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dropout(0.1),\n    tf.keras.layers.Dense(200, activation = \"relu\", kernel_regularizer = tf.keras.regularizers.l2(0.005)),\n    tf.keras.layers.Dense(100, activation = \"relu\"),\n    tf.keras.layers.Dense(100, activation = \"relu\"),\n    tf.keras.layers.Dense(50, activation = \"relu\"),\n    tf.keras.layers.Dense(29, activation = \"softmax\")\n])\n\nmodel_4.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[\"accuracy\"])\n\ncallback = tf.keras.callbacks.LearningRateScheduler(scheduler)\n\nhistory = model_4.fit_generator(train_generator, epochs=30, steps_per_epoch = 1224,validation_data=val_generator, validation_steps = 136, callbacks = [callback], verbose = 1)\n\n\nplotCurves(history)\n\"\"\"\n### The above learning curves shows that we have a decent fit over our data.\n\n#### Note: We did not monitor accuracies in our training process since a multi layer perceptron network is not considered to be very efficient over image data. Convolutional neural networks are considered to be more efficient which perform better than MLP networks. The reason behind creating this notebook was for learning purposes and to discover how the dataset performs over the MLP network.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6cae0e9b47c778'}"}
{"id":"7446","text":"\"\"\"\n## Random forest and Random Search on red wine quality:\n![Random forest: credit: github user kjw0612](https:\/\/camo.githubusercontent.com\/5afa4bc35f56871811e34f442baacc6cc098bd12a9320062846efe1bed011275\/68747470733a2f2f33312e6d656469612e74756d626c722e636f6d2f37393637306561626539336364643434386331356635626362313938643066622f74756d626c725f696e6c696e655f6e386533393859624b76317330347263332e706e67)\nIn this notebook Eswar sai and I have worked on Random forest regression and feature importance based feature selection using it. This is a good notebook for someone who is starting out with random forest. But before all that, <br\/>\n### What Is Random Forest?\nRandom forest is a supervised learning algorithm. The \"forest\" it builds, is an ensemble of decision trees, usually trained with the \u201cbagging\u201d method. The general idea of the bagging method is that a combination of learning models increases the overall result.<br\/>\n### How Random Forest Works:\n\nPut simply: random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction.<br\/>\n\nOne big advantage of random forest is that it can be used for both classification and regression problems, which form the majority of current machine learning systems. Let's look at random forest in classification, since classification is sometimes considered the building block of machine learning.<br\/>\n\nRandom forest has nearly the same hyperparameters as a decision tree or a bagging classifier. Fortunately, there's no need to combine a decision tree with a bagging classifier because you can easily use the classifier-class of random forest. With random forest, you can also deal with regression tasks by using the algorithm's regressor.<br\/>\n\nRandom forest adds additional randomness to the model, while growing the trees. Instead of searching for the most important feature while splitting a node, it searches for the best feature among a random subset of features. This results in a wide diversity that generally results in a better model.<br\/>\n\nTherefore, in random forest, only a random subset of the features is taken into consideration by the algorithm for splitting a node. You can even make trees more random by additionally using random thresholds for each feature rather than searching for the best possible thresholds (like a normal decision tree does).<br\/>\n\nRandom forest was first introduced by Briemann in his paper of 2001. You can read the details of random forest's inner working, which is called the CART algorithm, in the [following blog](https:\/\/shyambhu20.blogspot.com\/2020\/01\/Random-forest-model.html).<br\/>\nNow, let's discuss the contents of this notebook:<br\/>\n### contents:\n(1) [Basic data exploration](#section1)<br\/>\n(2) [Basic Random forest regressor fitting](#section2)<br\/>\n(3) [Fine tuning using RandomizedSearchCV](#random)<br\/>\n(4) [Fine tuning using GridSearchCV](#grid)<br\/>\n<br\/>\nEnjoy reading! and if you like the effort, consider showing your appreciation with a upvote!\nReferences:\n(1) [Description taken from this article](https:\/\/builtin.com\/data-science\/random-forest-algorithm)<br\/>\n\n\"\"\"\n\"\"\"\n### Data loading\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndf= pd.read_csv('\/kaggle\/input\/red-wine-quality-cortez-et-al-2009\/winequality-red.csv')\ndf.head()\ndf.describe().T\n\"\"\"\n### <a id = 'section1'> Basic data exploration<\/a>\n\"\"\"\ndf.isnull().sum()\nfrom scipy import stats\nz = np.abs(stats.zscore(df))\nprint(z)\n\"\"\"\n### Z-score based outlier removal\n\"\"\"\nthreshold = 3\nprint(np.where(z > 3))\nprint(z[13][9])\ndf_o = df[(z < 3).all(axis=1)]\ndf.shape\ndf_o.shape\n\"\"\"\n### Train-test-split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX = df_o.drop(columns = 'quality')\ny = df_o['quality']\nX.head()\ny.head()\n\"\"\"\n### <a id='section1'>Basic Random forest fitting<\/a>\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)\nfrom sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(n_estimators=100)\nclf.fit(X_train,y_train)\ny_pred = clf.predict(X_test)\nfrom sklearn import metrics\nprint('Accuracy: ', metrics.accuracy_score(y_test,y_pred))\ndf.columns\nimport pandas as pd\nfeature_imp = pd.Series(clf.feature_importances_, index=df_o.columns[:11]).sort_values(ascending=False)\nfeature_imp\n\"\"\"\n### Feature importance visualization\n\"\"\"\n%matplotlib inline\nimport seaborn as sns\n\nsns.barplot(x=feature_imp, y=feature_imp.index)\n\nplt.xlabel('Feature Importance Score')\nplt.ylabel('Features')\nplt.title(\"Visualizing Important Features\")\nplt.legend()\nplt.show()\n\"\"\"\n### <a id = 'random'>Fine tuning using RandomSearchCV<\/a>\n\"\"\"\n#Random Search Cross Validation\n\nfrom sklearn.ensemble import RandomForestRegressor\nrf = RandomForestRegressor(random_state = 42)\nfrom pprint import pprint\n# Look at parameters used by our current forest\nprint('Parameters currently in use:\\n')\npprint(rf.get_params())\nfrom sklearn.model_selection import RandomizedSearchCV\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(2, 14, num = 7)]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4]\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n# Create the random grid\nrandom_grid = {'n_estimators': n_estimators,\n               'max_features': max_features,\n               'max_depth': max_depth,\n               'min_samples_split': min_samples_split,\n               'min_samples_leaf': min_samples_leaf,\n               'bootstrap': bootstrap}\npprint(random_grid)\n# Use the random grid to search for best hyperparameters\n# First create the base model to tune\nrf = RandomForestRegressor()\n# Random search of parameters, using 3 fold cross validation, \n# search across 100 different combinations, and use all available cores\nrf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n# Fit the random search model\nrf_random.fit(X_train,y_train)\nrf_random.best_params_\ndef evaluate(model, X_test, y_test):\n    predictions = model.predict(X_test)\n    errors = abs(predictions - y_test)\n    mape = 100 * np.mean(errors \/ y_test)\n    accuracy = 100 - mape\n    print('Model Performance')\n    print('Average Error: {:0.4f} degrees.'.format(np.mean(errors)))\n    print('Accuracy = {:0.2f}%.'.format(accuracy))\n    \n    return accuracy\nbase_model = RandomForestRegressor(n_estimators = 10, random_state = 42)\nbase_model.fit(X_train, y_train)\nbase_accuracy = evaluate(base_model, X_test,y_test)\nbest_random = rf_random.best_estimator_\nrandom_accuracy = evaluate(best_random, X_test, y_test)\nprint('Improvement of {:0.2f}%.'.format( 100 * (random_accuracy - base_accuracy) \/ base_accuracy))\n\"\"\"\n### <a id='grid'>Fine tuning with GridSearchCV <\/a>\n\"\"\"\n#Grid Search with Cross Validation\n\nfrom sklearn.model_selection import GridSearchCV\n# Create the parameter grid based on the results of random search \nparam_grid = {\n    'bootstrap': [True],\n    'max_depth': [8, 10, 12, 14],\n    'max_features': [2, 3],\n    'min_samples_leaf': [3, 4, 5],\n    'min_samples_split': [8, 10, 12],\n    'n_estimators': [100, 200, 300, 1000]\n}\n# Create a based model\nrf = RandomForestRegressor()\n# Instantiate the grid search model\ngrid_search = GridSearchCV(estimator = rf, param_grid = param_grid, \n                          cv = 3, n_jobs = -1, verbose = 2)\n# Fit the grid search to the data\ngrid_search.fit(X_train, y_train)\ngrid_search.best_params_\nbest_grid = grid_search.best_estimator_\ngrid_accuracy = evaluate(best_grid, X_test, y_test)\n\"\"\"\n#### Here ends our treaties with Random forest. Thanks for reading the notebook. Happy kaggling!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0dd96ec2341c3d'}"}
{"id":"137730","text":"# 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\n\"\"\"\nImport necessary modules\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pycountry\nimport plotly.express as px\nimport plotly.graph_objs as go\n\"\"\"\n# **Exploratory Data Analysis \/ Data Preprocessing**\n> ## **Data Visualization**\n***\n\"\"\"\n\"\"\"\n## **Exploratory Data Analysis \/ Data Preprocesesing**\n\"\"\"\n\"\"\"\n**Data Familiarization**\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/forbes-billionaires-of-2021\/Billionaire.csv', index_col='Rank')\ndf.head()\n\"\"\"\n2755 Billionaires \n\"\"\"\ndf.shape\ndf.info()\ndf.describe()\n\"\"\"\nThe top industries that produce billionaires \n\"\"\"\ndf['Industry'].value_counts()\n\"\"\"\n**Data Wrangling**\n\"\"\"\n\"\"\"\nI'm not going to drop the rows that contain NaN because I'd rather have more data on billionaries (missing some ages) than less \n\"\"\"\ndf.isna().sum()\ndf['NetWorth'] = df['NetWorth'].str.replace('$', '', regex=True)\ndf['NetWorth'] = df['NetWorth'].str.replace('B', '', regex=True)\ndf['NetWorth'] = df['NetWorth'].astype(float)\ndf.head()\n\"\"\"\nFrom the code below, we now know that the average billionaire is worth ~ $4.75 B \n\"\"\"\ndf.describe()\n\"\"\"\n**DataFrame Creation\/Aggregation**\n\"\"\"\n\"\"\"\n*Technology billionaires*\n\"\"\"\ndf_tech = df.loc[df['Industry'] == 'Technology'].copy()\ndf_tech\n\"\"\"\n*Finance and Investments Billionaires*\n\"\"\"\ndf_money = df.loc[df['Industry'] == 'Finance & Investments'].copy()\ndf_money\n\"\"\"\n*Manufacturing billionaires*\n\"\"\"\ndf_man = df.loc[df['Industry'] == 'Manufacturing'].copy()\ndf_man\n\"\"\"\n### **Data Visualization**\n\"\"\"\n\"\"\"\nWho are the top 5 billionaires in 2021?\n\"\"\"\nplt.figure(figsize=(10, 6))\nplt.barh(df['Name'].head(10), df['NetWorth'].head(10), color='limegreen')\nplt.title('The top 10 billionaires in the world as of 2021', weight='bold')\nplt.xlabel('NetWorth (in billions)')\nplt.ylabel('Billionaires')\nplt.show()\n\"\"\"\nWhat are the countries with the most billionaires?\n\"\"\"\ndf['Country'].value_counts()[:5].plot(kind='barh', cmap='Pastel1', figsize=(9,6))\nplt.title('The top 5 countries with the most billionaires', weight='bold')\nplt.xlabel('Number of Billionaires')\nplt.ylabel('Countries')\nplt.show()\n\"\"\"\nWhat industries produce the most billionaires?\n\"\"\"\ndf['Industry'].value_counts()[:5].plot(kind='barh', cmap='Pastel2', figsize=(9,6))\nplt.title('The top 5 industries that produce billionaires', weight='bold')\nplt.xlabel('Number of Billionaires')\nplt.ylabel('Industries')\nplt.show()\n\"\"\"\nCreate df_map - dataframe needed to visualize the world's billionaires\n\"\"\"\ndf_map = df.drop_duplicates().groupby('Country').count().copy()\n\ndf_map = df_map['Name'].copy()\n\ndf_map = df_map.sort_values(ascending=False)\n\ndf_map = pd.DataFrame(df_map)\n\ndf_map.rename(columns = {'Name':'Billionaires'}, inplace = True)\ndf_map.head()\n\"\"\"\nAdd the iso-alpha 3 digit country codes column and the full Country Name column\n\"\"\"\nfor Country in df_map.index:\n    code = [value.alpha_3 for value in pycountry.countries if (value.name==Country)] #retrieves iso-alpha codes\n    if len(code)==0: #if iso alpha code doesn't match country\n        df_map.loc[Country,\"Sign\"]= None\n        df_map.loc[Country,\"Country Name\"]= Country\n    else: #if iso alpha code does match country\n        df_map.loc[Country,\"Sign\"]= code[0]\n        df_map.loc[Country,\"Country Name\"]= Country\n\"\"\"\nNaN values in df_map\n\"\"\"\ndf_map[df_map.isna().any(axis=1)]\n\"\"\"\nManually impute iso-alpha missing values with first 3 letters of country name\n\"\"\"\nfiller = pd.DataFrame(index=df_map.index[df_map.isnull().any(axis=1)], data=['RUS', 'TAI', 'SOU', 'VIE', 'VEN', 'TAN', 'SKT', 'ESW \/ SWA'], columns=['Sign'])\ndf_map.fillna(filler, inplace=True)\ndef continent_graph(continent=\"world\",title=\"\"):\n    fig = px.choropleth(df_map, locations='Sign',\n                       color='Billionaires',\n                        hover_name='Country Name', \n                        color_continuous_scale=\"agsunset\",\n                        color_continuous_midpoint= 300,\n                       scope = str(continent))\n    layout = go.Layout(\n        title=go.layout.Title(\n            text= f\"<b>{title}<\/b>\",\n            x=0.5\n        ),\n        showlegend=False,\n        font=dict(size=13),\n       width = 750,\n        height = 350,\n        margin=dict(l=0,r=0,b=0,t=30)\n   )\n    fig.update_layout(layout)\n    fig.show()\ncontinent_graph(continent='world', title='Worldwide Billionaires')\n\"\"\"\n**Note:** I took inspiration from the following notebook: https:\/\/www.kaggle.com\/tahmidurrahmantabin\/forbes-billionaires-2021\n\"\"\"\n\"\"\"\nThanks for reading my notebook. Feel free to upvote this notebook and leave comments!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fd33d2ba79aaf7'}"}
{"id":"115892","text":"# 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 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\n\"\"\"\npandas version:\n\"\"\"\ndf=pd.read_csv(\"..\/input\/default-of-credit-card-clients-dataset\/UCI_Credit_Card.csv\")\ndf\ndf.info()\ndf.columns\n\"\"\"\n# *********Get CATEGORICAL data which is represented by int64:*************\n\"\"\"\n\"\"\"\nsources: \n* https:\/\/pbpython.com\/categorical-encoding.html=\n\n* https:\/\/www.shanelynn.ie\/using-pandas-dataframe-creating-editing-viewing-data-in-python\/\n\n* https:\/\/towardsdatascience.com\/categorical-encoding-using-label-encoding-and-one-hot-encoder-911ef77fb5bd\n\"\"\"\ncat_df = df.select_dtypes(include=['int64']).copy()\ncat_df = cat_df.drop(columns=\"ID\")#delete ID from categorical data -> not useful\ncat_df.columns\ncat_df.shape\n\"\"\"\n1. ONE-HOT-ENCODE certain categorical data\n\n\n* replaces i column with multiple columns that will be \"hot\" when rows with a certain status\n* will not one-hot-encode AGE\n\"\"\"\n\"\"\"\nONE-HOT-ENCODE: \"SEX\",\"MARRIAGE\",\"EDUCATION\",\n\"\"\"\n\"\"\"\nTOO MANY COLUMNS FOR \"EDUCATION\"\n\n->replace certain education statuses due to too many cols ->put all other options into 4 \n\"\"\"\ncat_df['EDUCATION'].replace({0: 4, 5: 4, 6: 4}, inplace=True)\nencode_columns=['SEX','MARRIAGE','EDUCATION']\nfor i in encode_columns:\n    cat_df=pd.get_dummies(cat_df, columns=[i])\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\ncat_df.columns\n\n\"\"\"\nONE-HOT-ENCODE \"PAY_i\":\n\"\"\"\nunique_status = np.unique(cat_df[['PAY_0']])\nprint(\"total unique statuses:\", len(unique_status))\nprint(unique_status)\n\"\"\"\n* will get 10-11 new columns per PAY_i with one-hot-encoding because some monthes might have 0 frequency of a payment status\/es\n\"\"\"\nmonthes=['PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']\nfor i in monthes:\n    cat_df=pd.get_dummies(cat_df, columns=[i])\n\n\"\"\"\nBIN the AGE feature\n\n5 groups : 21-30 , 31-40 , 40-50 , 50-60 , 60-75\n\nsources:\n\nhttps:\/\/medium.com\/vickdata\/four-feature-types-and-how-to-transform-them-for-machine-learning-8693e1c24e80\n\"\"\"\nbins = [21, 30, 40, 50, 60, 76]\ngroup_names = ['21-30', '31-40', '41-50', '51-60', '61-76']\nage_cats = pd.cut(cat_df['AGE'], bins, labels=group_names)\ncat_df['age_cats'] = pd.cut(cat_df['AGE'], bins, labels=group_names)\n\"\"\"\nONE-HOT-ENCODE the age categories :\n\"\"\"\ncat_df=pd.get_dummies(cat_df, columns=['age_cats'])\ncat_df.columns\nlen(cat_df.columns)\ncat_df.dtypes\nlen(cat_df.columns)\n\"\"\"\n# *********Get NUMERICAL data which is represented by float64:************* \n\"\"\"\nnum_df = df.select_dtypes(include=['float64']).copy()\nnum_df.columns\n\"\"\"\n1. ADAPTIVE BINNING: the BILL_AMT cols\n\n\n* we use the data distribution itself to decide our bin ranges\n\n* bill_amts will be put into quantiles\n\nsource: https:\/\/towardsdatascience.com\/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b\n\"\"\"\nbills=['BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4','BILL_AMT5','BILL_AMT6']\ncol_names=['Q_BILL_AMT1', 'Q_BILL_AMT2', 'Q_BILL_AMT3', 'Q_BILL_AMT4','Q_BILL_AMT5', 'Q_BILL_AMT6']\ni=0#counter \n\nfor col in bills:\n    quantile_list = [0, 0.25, 0.5, 0.75, 1.0]\n    quantile_labels = ['0-25Q', '25-50Q', '50-75Q', '75-100Q']\n    num_df[col_names[i]] = pd.qcut(num_df[col],q=quantile_list,labels=quantile_labels)\n    i+=1\n    \nnum_df.columns\nnum_df.head()\n\"\"\"\n2. ADAPTIVE BINNING: the PAY_AMT cols AND LIMIT_BAL\nwe use the data distribution itself to decide our bin ranges\n\nPAY_AMT(s) and LIMIT_BAL will be put into quantiles\n\nsource: https:\/\/towardsdatascience.com\/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b\n\"\"\"\npays=['PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5','PAY_AMT6','LIMIT_BAL']\ncol_names=['Q_PAY_AMT1', 'Q_PAY_AMT2', 'Q_PAY_AMT3','Q_PAY_AMT4','Q_PAY_AMT5','Q_PAY_AMT6','Q_LIMIT_BAL']\ni=0#counter \n\nfor col in pays:\n    quantile_list = [0, 0.25, 0.5, 0.75, 1.0]\n    quantile_labels = ['0-25Q', '25-50Q', '50-75Q', '75-100Q']\n    num_df[col_names[i]] = pd.qcut(num_df[col],q=quantile_list,labels=quantile_labels)\n    i+=1\n    \nnum_df.columns\n\"\"\"\nnow the originally numerical columns are categorical columns \n\"\"\"\n\"\"\"\nONE-HOT-ENCODE the Q_PAY_AMTs , Q_BILL_AMTs, and Q_LIM_BAL\n\"\"\"\nencode_columns=['Q_BILL_AMT1', 'Q_BILL_AMT2','Q_BILL_AMT3', 'Q_BILL_AMT4', 'Q_BILL_AMT5', 'Q_BILL_AMT6','Q_PAY_AMT1', 'Q_PAY_AMT2', 'Q_PAY_AMT3','Q_PAY_AMT4','Q_PAY_AMT5','Q_PAY_AMT6','Q_LIMIT_BAL']\nfor i in encode_columns:\n    num_df=pd.get_dummies(num_df, columns=[i])\nnum_df.head()\nnum_df.columns\nlen(num_df.columns)\n\"\"\"\nNEW COLUMN: create column that indicates if tuple has payment status >1 in first month and last month\n\n\n* make loop to go thru each PAY_0\n* make col with 0 or 1 that will indicate if condtion in true \n* add to num_df \n\n\"\"\"\n\"\"\"\nsource:https:\/\/stackoverflow.com\/questions\/32984462\/setting-1-or-0-to-new-pandas-column-conditionally\n\"\"\"\nnum_df['late_payer']=df['PAY_0'].apply(lambda x: 1 if x > 1 else 0)\n\nnum_df['late_payer'].head()\n\"\"\"\nNEW COLUMN: create column that indicates if tuple has payed more than BILL_AMT (meaning they have a negative balance)\n\"\"\"\nbill_mons=['BILL_AMT1','BILL_AMT2','BILL_AMT3','BILL_AMT4','BILL_AMT5','BILL_AMT6']\ncols=['OVER_BILL_AMT1','OVER_BILL_AMT2','OVER_BILL_AMT3','OVER_BILL_AMT4','OVER_BILL_AMT5','OVER_BILL_AMT6']\ni=0#counter\n\nfor mon in bill_mons:\n    num_df[cols[i]]=df[mon].apply(lambda x: 1 if x < 0 else 0)\n    i+=1\n    \nnum_df['OVER_BILL_AMT1'].head()    \n\"\"\"\nCONCAT ALL DATAFRAMES MADE:\n\"\"\"\ndata = pd.concat([cat_df, num_df], axis=1)\ntarget=data['default.payment.next.month']\ndata = data.drop(columns='default.payment.next.month')#delete target from dataframe\ndata.head()\nlen(data.columns)\n\"\"\"\n152 columns in all: next step is creating model with this df \n\"\"\"\n#data.to_csv('mycsvfile.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'd51b019fadb3a4'}"}
{"id":"6192","text":"\"\"\"\n# Welcome to my notebook!\nThis competition is a classic machine learning classification problem. And like with most data science competition, **dealing with noise and data pre-processing is a major part of the process.** I will walk you through my entire thought process in dealing with noise present within the data. It should be easy enough for beginners to understand but don't hope to achieve a high score with this! :)\n\n\n\"\"\"\n\"\"\"\n# Importing libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport re\n\nfrom sklearn.metrics import matthews_corrcoef\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBRFClassifier\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n# Read and inspect the csv files\n\"\"\"\ntrain_df = pd.read_csv(\"..\/input\/open-shopee-code-league-marketing-analytics\/train.csv\").set_index('row_id')\ntest_df = pd.read_csv(\"..\/input\/open-shopee-code-league-marketing-analytics\/test.csv\").set_index('row_id')\nuser_df = pd.read_csv(\"..\/input\/open-shopee-code-league-marketing-analytics\/users.csv\")\ntrain_df.head()\nuser_df.head()\n\"\"\"\n# Data Anomalies\n\nWith the help of [@soappp9527's EDA work](http:\/\/www.kaggle.com\/soappp9527\/marketing-analytics-eda-by-r-data-table-ggplot2), and inspecting them within the csv in the excel program, here are the basic anomalies that requires processing.\n\n**1. Never open\/login\/checkout in 3 of the columns**\n\n**2. Missing values in attr_1,2 and 3**\n\n**3. Missing values in age**\n\"\"\"\n\"\"\"\n# Merging Users Dataframe with Train and Test Dataframes\n\nEvery feature is important to me unless otherwise told by the random forest algorithm's feature importance. Since we are given the user's information, why not make use of the data? Especially when you think about it, age might probably play a factor in opening e-mails. So let's do a left join on both the train and test dataframes to add additional features for prediction.\n\"\"\"\ntrain_df = train_df.merge(user_df, left_on = 'user_id', right_on = 'user_id')\ntest_df = test_df.merge(user_df, left_on = 'user_id', right_on = 'user_id')\ntrain_df.head()\n\"\"\"\nNow we see that every row has been added 5 additional features that could potentially help with the robustness of the prediction.\n\"\"\"\n\"\"\"\n# Adding Additional Features by Adding Date Parts\n\nWhen we look at the ``grass_date`` feature in the dataset, it may not appear to be a great predictive feature on its own. However, if we dissect the dates and separate it based on the day of week, day of month, etc.. Some of these additional features might serve as a great predictor.\n\nFor example, some might open an e-mail relating to e-commerce during the weekends in their own personal e-mails because that is when they are most likely to be free.\n\nSo I will make use of fast.ai's ``add_datepart`` function to help with the addition of these features.\n\"\"\"\ndef add_datepart(df, fldname, drop=True):\n    fld = df[fldname]\n    if not np.issubdtype(fld.dtype, np.datetime64):\n        df[fldname] = fld = pd.to_datetime(fld, infer_datetime_format=True)\n    targ_pre = re.sub('[Dd]ate$', '', fldname)\n    for n in ('Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear',\n            'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'):\n        df[targ_pre+n] = getattr(fld.dt,n.lower())\n    if drop: df.drop(fldname, axis=1, inplace=True)\n    \nadd_datepart(train_df, 'grass_date')\nadd_datepart(test_df, 'grass_date')\ntrain_df.head()\n\"\"\"\nNow that we have separated the date into multiple features, it's time to remove features that are unnecessary for obvious reasons.\n\"\"\"\ndef remove_datecols(df):\n    fld = ['grass_Year','grass_Is_quarter_end','grass_Is_quarter_start','grass_Is_year_start','grass_Is_year_end']\n    df.drop(fld, axis=1, inplace=True)\n    \nremove_datecols(train_df)\nremove_datecols(test_df)\ntrain_df.head()\n\"\"\"\n# Removing User ID\n\"\"\"\n#Remove userid because they are not required for prediction\ntrain_df.drop('user_id', axis = 1, inplace = True)\ntest_df.drop('user_id', axis = 1, inplace = True)\n\"\"\"\n# One-Hot Encoding E-mail Domain and Country Code\n\nI do this because these are categorical features and should not have any cardinality within the random forest algorithm.\n\"\"\"\ntrain_df = pd.concat([train_df.drop('country_code', axis=1), pd.get_dummies(train_df['country_code'])], axis=1)\ntrain_df = pd.concat([train_df.drop('domain', axis=1), pd.get_dummies(train_df['domain'])], axis=1)\ntest_df = pd.concat([test_df.drop('country_code', axis=1), pd.get_dummies(test_df['country_code'])], axis=1)\ntest_df = pd.concat([test_df.drop('domain', axis=1), pd.get_dummies(test_df['domain'])], axis=1)\n\"\"\"\n# Processing Never Open\/Login\/Checkout and Other Missing Values\n\"\"\"\n#Replace never open, never checkout and never login to nan\ntrain_df.replace([\"Never open\", \"Never login\", \"Never checkout\"], np.nan, inplace = True)\ntest_df.replace([\"Never open\", \"Never login\", \"Never checkout\"], np.nan, inplace = True)\ntrain_df[['last_open_day','last_login_day','last_checkout_day']] = train_df[['last_open_day','last_login_day','last_checkout_day']].apply(pd.to_numeric)\ntest_df[['last_open_day','last_login_day','last_checkout_day']] = test_df[['last_open_day','last_login_day','last_checkout_day']].apply(pd.to_numeric)\n\n#Fill missing values\ntrain_df.fillna({\"last_open_day\":train_df['last_open_day'].max(),\n                 \"last_login_day\":train_df['last_login_day'].max(),\n                 \"last_checkout_day\":train_df['last_checkout_day'].max(),\n                 \"attr_1\": 2,\n                 \"attr_2\": 2,\n                 \"attr_3\": 2,\n                 \"age\": train_df['age'].median()}, inplace = True)\n\ntest_df.fillna({\"last_open_day\":test_df['last_open_day'].max(),\n                 \"last_login_day\":test_df['last_login_day'].max(),\n                 \"last_checkout_day\":test_df['last_checkout_day'].max(),\n                 \"attr_1\": 2,\n                 \"attr_2\": 2,\n                 \"attr_3\": 2,\n                 \"age\": test_df['age'].median()}, inplace = True)\n\"\"\"\n# Split Training Dataset for Modelling\n\nCredits to [Nathaniel Ng's notebook](https:\/\/www.kaggle.com\/nathaniel\/marketing-analytics-baseline-0-41795) for the following chunk of code, saved me the trouble from typing it out on my own!\n\"\"\"\ndef get_xy(df, target_col='open_flag', **kwargs):\n    feature_cols = [ col for col in df.columns if col != target_col ]\n    if target_col in df:\n        X = df[feature_cols]\n        y = df[target_col]\n        X_train, X_valid, y_train, y_valid = train_test_split(X, y)\n        return X_train, X_valid, y_train, y_valid\n    else:\n        X_test = df[feature_cols]\n        return X_test\n    \nX_train, X_valid, y_train, y_valid = get_xy(train_df, test_size=0.2, random_state=123)\nX_test = get_xy(test_df)\n\"\"\"\n# Modelling using Random Forest Classifier\n\"\"\"\nmodel = RandomForestClassifier(max_depth = 200, n_estimators = 300, n_jobs = -1, bootstrap = True, random_state = 123)\nrf = model.fit(X_train, y_train)\n\"\"\"\n# Evaluating the Model\n\"\"\"\ny_pred = rf.predict(X_valid)\nmatthews_corrcoef(y_valid,y_pred)\n\"\"\"\n# Predicting the Test Set and Submitting to Kaggle\n\"\"\"\n# Make predictions on test set with RF\ny_pred = model.predict(X_test)\nsubmission_df = pd.DataFrame({'row_id':np.arange(len(test_df)),\n                              'open_flag':y_pred})\nsubmission_df.to_csv('submission.csv', index = False)\n\"\"\"\n# [Optional] Inspecting Feature Importance\n\"\"\"\ndef imp_df(column_names, importances):\n  df = pd.DataFrame({'variable': column_names,\n                     'variable_importance': importances}) \\\n         .sort_values('variable_importance', ascending = False) \\\n         .reset_index(drop = True)\n  return df\nbase_imp = imp_df(X_train.columns, rf.feature_importances_)\n\nplt.figure(figsize = (15,8))\nfig = sns.barplot(x = 'variable_importance', y = 'variable', data = base_imp, orient = 'h', color = 'royalblue')\nplt.title(\"Variable Importance using RFC\", fontsize = 20)\nplt.xlabel('Variable Importance', fontsize = 16)\nplt.ylabel('')\nplt.xticks(fontsize = 14)\nplt.yticks(fontsize = 14)\nplt.show()\n\"\"\"\n# Conclusion\n\nI am clearly still a beginner in fine-tuning the random forest classifier algorithm. It's been awhile since I messed around with machine learning algorithms, but I'm still happy I managed to tackle this competition!\n\nThere is still much to learn including using more sophisticated algorithms such as LightGBM and XGBoost as well as hyperparameter tuning using GridSearchCV.\n\nThere are still a lot of things you can do in data preparation such as, and not limited to:\n\n***1. Dealing with outliers (negative age and age hitting 118)***\n\n***2. Removing certain features that appear redundant with either Recursive Feature Elimination or simply deciding from the feature importance chart***\n\n***3. More feature engineering, especially with the top 3 features.***\n\nI hope you find this notebook useful especially in the data pre-processing part for your participation in this competition! :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0b7a176b12a9b0'}"}
{"id":"120608","text":"\"\"\"\n# Heart Disease with Logistic Regression\n\"\"\"\n\"\"\"\n### Cordivacular diseases, in colloquial speech heart diseases can be big trouble for human kind. In this kernel we are going to try to make analysis about this illness by investigating different parameters.\n\"\"\"\n\"\"\"\n![heart.jpg](attachment:f8b66335-d09d-4f53-a455-28c08c263d5c.jpg)\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly as pl\n\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\n\"\"\"\n## Read Data\n\"\"\"\ndata = pd.read_csv(\"\/kaggle\/input\/heart-disease-uci\/heart.csv\")\ndata.head()\ndata.columns\n\"\"\"\n## First of all I want to have a look at the features meanings :\n####  * age       --> age\n#### * sex       --> gender in binary (1:male, 0:female)\n#### * cp        --> chest pain type\n#### * trestbps  --> resting blood pressure (in mm Hg on admission to the hospital)\n#### * chol      --> serum cholestoral in mg\/dl\n#### * fbs       --> (fasting blood sugar > 120 mg\/dl) (1 = true; 0 = false)\n#### * restecg   --> resting electrocardiographic results\n#### * thalach   --> maximum heart rate achieved\n#### * exang     --> exercise induced angina (1 = yes; 0 = no)\n#### * oldpeak   --> ST depression induced by exercise relative to rest\n#### * slope     --> the slope of the peak exercise ST segment\n#### * ca        --> number of major vessels (0-3) colored by flourosopy\n#### * thal      --> 3 = normal; 6 = fixed defect; 7 = reversable defect\n#### * target    --> have disease or not (1=yes, 0=no)\n\"\"\"\ndata.corr()\n\"\"\"\n#### This is corrolation table. By the helping of this table we can see that if features have corrolation or not (if values is close to 1 there is positive corrolation, if near to -1 negative corrolation, and if it near to 0 there are no corrolation). As you see there are not much corrolated features in our data. The map you will see in below is corrolation map:\n\"\"\"\nf,ax = plt.subplots(figsize=(10, 10))\nsns.heatmap(data.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)\nplt.show()\n\"\"\"\n#### By this method, you can have a look at what you want to dig in. In this senerio target must be our target :\n\"\"\"\ndata.corr()[\"target\"].sort_values()\ndata.info()\n\"\"\"\n#### This is the data types that what we will work on. 12 integers and 1 float and all of them is filled with non-null. We can double check like that also :\n\"\"\"\ndata.isnull().sum()\n\"\"\"\n#### Now its time to getting more familiar with the data :\n\"\"\"\ndata.describe()\n\"\"\"\n## Visualization\n\"\"\"\n\"\"\"\n#### The first thing I wondered is dependecy between illness and age:\n\"\"\"\n\"\"\"\n#### Initially we need to view a pandas function which is crosstab. Crosstab computes a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed. For example: \n\n\"\"\"\npd.crosstab(data.age,data.target)\n\"\"\"\n#### As you see the the information we wanted, they are grouped\n\"\"\"\ncrosstabAge = pd.crosstab(data.age,data.target)\ncrosstabAge.plot(kind=\"bar\",figsize=(20,8), color =\"cmyk\", alpha = 0.8) #alpha is opacity\nplt.title('Heart Disease Frequency Given Ages')\nplt.xlabel('Ages')\nplt.ylabel('Frequency')\nplt.legend([\"Have not Disease\", \"Have Disease\"])\nplt.show()\n\"\"\"\n#### According to table, 41, 51, 52, 54 are the ages that heart diseases mostly seen.\n\"\"\"\n\"\"\"\n#### But what about the numbers of the target ?\n\"\"\"\ndata[\"target\"].value_counts()\nsns.countplot(data[\"target\"], palette=\"Set2\")\nplt.xlabel(' 0 = Not Have Disease,  1 = Have Disease')\n\"\"\"\n#### What about the difference between man and woman ?\n\"\"\"\ncrosstabSex = pd.crosstab(data[\"sex\"], data[\"target\"])\ncrosstabSex\ncrosstabSex.plot(kind=\"bar\", figsize=(15,6), color=\"cmyk\")\nplt.title(\"Heart Disease Frequency Given Sex\")\nplt.xticks(rotation=0)\nplt.xlabel(\"0 = Female , 1 = Male\")\nplt.ylabel(\"Frequency\")\nplt.legend([\"Have not Disease\", \"Have Disease\"])\n\"\"\"\n#### According to table, men have more tendecy to have heart diseases.\n\"\"\"\n\"\"\"\n#### So whats next ? fbs : Fasting Blood Sugar\n\"\"\"\ncrosstabFbs = pd.crosstab(data[\"fbs\"], data[\"target\"])\ncrosstabFbs\ncrosstabFbs.plot(kind=\"bar\", figsize=(10, 8), color=\"cmyk\")\nplt.xticks(rotation=0)\nplt.xlabel(\"Fasting Blood Sugar < 120 : 0 | Fasting Blood Sugar > 120 : 1\")\nplt.ylabel(\"Frequency\")\nplt.legend([\"Have not Disease\", \"Have Disease\"])\n\"\"\"\n#### This result actually suprised me because i expected more datas on fasting blood sugar > 1 but there are not much.\n\"\"\"\ndata.fbs.value_counts()\ncrosstabExang = pd.crosstab(data[\"exang\"], data[\"target\"])\ncrosstabExang\ncrosstabExang.plot(kind=\"bar\", figsize=(10, 8), color=\"cmyk\")\nplt.xticks(rotation=0)\nplt.xlabel(\"Exercise Induced Angina 0 : No | 1 : Yes\")\nplt.ylabel(\"Frequency\")\nplt.legend([\"Have not Disease\", \"Have Disease\"])\n\"\"\"\n#### Another interesting result. Exercise induced angina is the problem that chest pain, relaxation and pressure hiss caused by ischemia or corner spasm in the heart muscle of the day. \n\"\"\"\n\"\"\"\n## Logistic Regression\n\"\"\"\n\"\"\"\n#### In this tutorial, I am going to write logistic regression code by myself basicaly. After that with sklearn.\n\"\"\"\n\"\"\"\n#### Lets define x and y values\n\"\"\"\ny = data.target.values #values convert values onto numpy array\nx_data = data.drop([\"target\"], axis=1) #except for target the other columns is our x data\nprint(y)\n\"\"\"\n#### First of all, we need to make normalization on data because in this data there are some values like 140, 250 (trestbs, chol) and there are binary values like 0 and 1. This may cause overtower between datas on features. To prevent this, we are doing normalization.\n\"\"\"\n\"\"\"\n### X_normalized = (x - x minimum)\/(x maximum - x minimum)\n\"\"\"\nx = (x_data - np.min(x_data))\/(np.max(x_data) - np.min(x_data)).values\nx\n\"\"\"\n#### Alright its time to split to train and test\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=0)\n#transpose matrices\nx_train = x_train.T\ny_train = y_train.T\nx_test = x_test.T\ny_test = y_test.T\n\"\"\"\n### So, How Its Work ?\n\"\"\"\n\"\"\"\n![Inkedweights and bias_LI.jpg](attachment:318d4528-bf75-490e-8596-b03256ed4367.jpg)\n\"\"\"\n\"\"\"\n#### Well, what are those things ?\n* Inputs (x1, x2, x3 ... xn) are our specific values on each column\n* Weights are coefficent \n* Bias is interception\n* Activation functions are mathematical functions like unit step function, sigmoid etc. We will use sigmoid\n* Basicaly its working based on very familiar expression y = wx + b\n* In this scenario , z = b + w1.x1 + w2.x2 + .... + w302.x302\n* y_pred is sigmoid(z) (will work on sigmoid a little later)\n\"\"\"\n\"\"\"\n### Initializing Weights and Bias\n\"\"\"\ndef initialize_weights_and_bias(dimension):\n    weight = np.full((dimension, 1), 0.01)\n    bias = 0.0\n    return weight,bias\n\"\"\"\n#### The values must be defined. In initialize_weights_and_bias function I defined the initial values. This values are not very important because after forward and bacward propagations values will be updated.\n\"\"\"\n\"\"\"\n#### For whom asking what is np.full : \n\"\"\"\nnp.full((10, 1), 0.01)\n\"\"\"\n### Sigmoid Function\n\"\"\"\n\"\"\"\n![sigmoid.png](attachment:f8a01b1c-2b33-494c-b5d8-ed02046e014d.png)\n\"\"\"\n\"\"\"\n#### Sigmoid function returns probabilistic values. For example at the point 2, nearly %75 probability this value classified as 1\n\"\"\"\ndef sigmoid(z):\n    y_head = 1\/(1 + np.exp(-z))\n    return y_head\n\"\"\"\n## Forward-Backward Propagation and Gradient Descent\n\"\"\"\n\"\"\"\n#### Basically in neural networks (logistic regression is fundamental form of neural networks), you forward propagate to get the output and compare it with the real value to get the error. Now, to minimize the error, you propagate backwards by finding the derivative of error with respect to each weight and then subtracting this value from the weight value. The purpose of this calculations is optimize the algorithm. This operation can be done with gradient descent method.\n\"\"\"\n\"\"\"\n![gradient descent.png](attachment:2578a93a-6185-4e3f-a155-996fa0dd2951.png)\n\"\"\"\n\"\"\"\n### Loss = (Y)(-log(Y_pred)) + (1-Y)(-log(1-Y_pred))\n\"\"\"\n\"\"\"\n#### This is loss function. Sumation for each value is cost function. If you predict 1 and the result is 1 you will get 0 loss otherwise big amount of lost.\n\"\"\"\n\"\"\"\n![grad2.png](attachment:47016ac7-1ee3-4dda-bdad-a7e5b90dc3d9.png)\n\"\"\"\n\"\"\"\n#### This is updating equations. By taking derivative of cost function according to weight and bias. Then multiply it with \u03b1 learning rate. Step by step model will be updated by this method. Learning rate can be say like learning speed. In other words, Incremental step is stepping by the helping of learning rate.\n\"\"\"\n\"\"\"\n#### Lets continue to code :\n\"\"\"\ndef forward_backward_propagtion(weight, bias, x_train, y_train):\n    # forward propagation\n    z = np.dot(weight.T,x_train) + bias # z = b + w1.x1 + w2.x2 + .... + w302.x302\n    y_head = sigmoid(z)\n    loss = -(y_train*np.log(y_head) + (1-y_train)*np.log(1-y_head))\n    cost = np.sum(loss) \/ x_train.shape[1] #x_train.shape[1] for normalization\n    \n    # backward propagation\n    derivative_weight = np.dot(x_train,((y_head-y_train).T))\/x_train.shape[1] #simple derivative\n    derivative_bias = np.sum(y_head-y_train)\/x_train.shape[1]\n    gradients = {\"Derivative Weight\" : derivative_weight, \"Derivative Bias\" : derivative_bias} #for storage\n     \n    return cost,gradients\n\ndef update(weight, bias, x_train, y_train, learning_rate, iteration) :\n    cost_list = []\n    index = []\n    \n    # updating(learning) parameters in number_of_iterarion times\n    for i in range(iteration):\n        # make forward and backward propagation and find cost and gradients\n        cost,gradients = forward_backward_propagtion(weight,bias,x_train,y_train)\n        # update\n        weight = weight - learning_rate * gradients[\"Derivative Weight\"]\n        bias = bias - learning_rate * gradients[\"Derivative Bias\"]\n        \n        cost_list.append(cost)\n        index.append(i)\n        print (\"Cost after iteration %i: %f\" %(i, cost))\n        \n    parameters = {\"weight\": weight,\"bias\": bias}\n    \n    print(\"iteration:\",iteration)\n    print(\"cost:\",cost)\n\n    plt.plot(index,cost_list)\n    plt.xlabel(\"Number of Iteration\")\n    plt.ylabel(\"Cost\")\n    plt.show()\n\n    return parameters, gradients\ndef predict(weight, bias, x_test):\n    # x_test is an input for forward propagation\n    z = np.dot(weight.T,x_test) + bias\n    y_head = sigmoid(z)\n\n    y_prediction = np.zeros((1,x_test.shape[1]))\n    \n    # if z is bigger than 0.5, our prediction is sign one (y_head=1),\n    # if z is smaller than 0.5, our prediction is sign zero (y_head=0)\n    for i in range(z.shape[1]):\n        if z[0,i] <= 0.5:\n            y_prediction[0,i] = 0\n        else:\n            y_prediction[0,i] = 1\n    return y_prediction\ndef logistic_regression(x_train, y_train, x_test, y_test, learning_rate, iteration):\n    # initialize\n    dimension = x_train.shape[0]\n    weight,bias = initialize_weights_and_bias(dimension)\n     \n    parameters, gradients = update(weight, bias,x_train, y_train, learning_rate, iteration)\n\n    y_prediction = predict(parameters[\"weight\"],parameters[\"bias\"],x_test)\n    \n    print(\"Accuracy of Model : {}%\".format((100 - np.mean(np.abs(y_prediction - y_test))*100)))\nlogistic_regression(x_train,y_train,x_test,y_test,2,200)\n\"\"\"\n## Sklearn\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\n\nlr.fit(x_train.T, y_train.T)\nprint(\"test accuracy {}\".format(lr.score(x_test.T,y_test.T))) #\n\"\"\"\n## Conclusion\n\"\"\"\n\"\"\"\n#### In this tutorial, first we do exploratory data analysis then we generate our logistic regression model by hand then tried it by sklearn\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dddd1149d7d199'}"}
{"id":"107919","text":"\"\"\"\n# In this notebook I tried to build a recommendation system that would recommend similar anime based on the user's browsing history\n\"\"\"\n\"\"\"\nPlan:\n* Explore the data\n* Check and clean the missing values\n* Prepare data for clustering\n* Make clusters(use minbatchkmeans)\n* Display clusters(use t-SNE)\n* Find nearest neighbors\n* Test our model\n\"\"\"\n\"\"\"\nImports:\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nimport plotly as py\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\n%matplotlib inline\n\ninit_notebook_mode(connected=True)\n\"\"\"\nRead the data\n\"\"\"\ndf_anime = pd.read_csv('..\/input\/anime-recommendations-database\/anime.csv')\ndf_anime\ndf_rating = pd.read_csv('..\/input\/anime-recommendations-database\/rating.csv')\ndf_rating\n\"\"\"\nCheck missing values\n\"\"\"\ndf_anime.isna().sum(), df_anime.isnull().sum()\n\"\"\"\nWe have some missing values, i decide to drop rows. their number is small, our completeness of information has not suffered much\n\"\"\"\ndf_anime = df_anime.dropna()\ndf_anime.isna().sum(), df_anime.isnull().sum()\n\"\"\"\nCheck missing values in df_rating\n\"\"\"\ndf_rating.isna().sum(), df_rating.isnull().sum()\n\"\"\"\nColumn \"episodes\" has a value \"Unknown\". it does not suit us.We replace this value by median.\n\"\"\"\nunknown_index = df_anime[df_anime['episodes']=='Unknown'].index.to_list()\ndf_anime.loc[unknown_index,'episodes'] = 0\ndf_anime[df_anime['episodes']==0]\ndf_anime['episodes'] = df_anime['episodes'].astype('int')\ndf_anime['episodes'].describe()\ndf_anime.loc[unknown_index,'episodes'] = df_anime['episodes'].median()\ndf_anime['episodes'].describe()\n\"\"\"\n# Explore anime dataframe\n\"\"\"\n\"\"\"\nExplore genre\n\"\"\"\ndf_anime\n\"\"\"\nNumber of unique anime\n\"\"\"\nlen(df_anime['anime_id'].unique())\n\"\"\"\nWork with genre. make dummy variables with one hot code\n\"\"\"\n#first of all get all genres \nall_genres = ''\nfor genre in df_anime['genre'].to_list():\n    all_genres += str(genre) + ', '\nall_genres = all_genres.split(',')\nall_genres = list(map(lambda x: x.strip() ,all_genres))\nall_genres = set(all_genres)\nall_genres.remove('')\n\"\"\"\nCreate dummy variables. we check if genre name in genre list -> column genre, then set 1 in other case set 0\n\"\"\"\nfor genre_name in all_genres:\n    list_code = list(map(lambda x: 1 if x.find(genre_name)+1 else 0,df_anime['genre'].to_list()))\n    df_anime.loc[:,'genre_%s'%genre_name] =list_code \n\"\"\"\nWhen we create dummy variables, no longer needed a column \"genre\"\n\"\"\"\ndf_anime = df_anime.drop('genre',axis=1)\n\"\"\"\nTop count genres. Make plot\n\"\"\"\ncount_genres = {genre: df_anime['genre_%s'%genre].sum() for genre in all_genres}\ncount_genres = {key: value for key, value in sorted(count_genres.items(),key=lambda x: x[1],reverse=True)}\nx = list(count_genres.keys())[:10]\ny = [count_genres[key] for key in x]\nplt.figure(figsize=(10,10))\nsns.barplot(x=x,y=y)\n\"\"\"\nTop rating genres. Make plot\n\"\"\"\n\nrate_genres = [(genre,df_anime[df_anime['genre_%s'%genre]==1]['rating'].mean()) for genre in all_genres]\nrate_genres = sorted(rate_genres, key=lambda x: x[1], reverse=True)\nlen(rate_genres)\nplt.figure(figsize=(11,10))\nplt.xlabel('Genre')\nplt.ylabel('Mean rating')\nsns.barplot(x=list(map(lambda x: x[0],rate_genres[:10])), y=list(map(lambda x: x[1],rate_genres[:10])))\n\"\"\"\nExplore type anime. dummy variables make later\n\"\"\"\nvalues = df_anime['type'].value_counts()\n\"\"\"\nMake count plot\n\"\"\"\nlabels = values.index.to_list()\nvalues = values.to_list()\nvalues,labels\nplt.figure(figsize=(10,10))\nplt.pie(values, labels=labels,autopct='%1.1f%%')\n_ = plt.legend(labels)\n\"\"\"\nmake rating\\type plot\n\"\"\"\nrate_type = [(type_name, df_anime[df_anime['type']==type_name]['rating'].mean()) for type_name in df_anime['type'].unique()]\nrate_type = sorted(rate_type, key=lambda x: x[1],reverse=True)\nplt.figure(figsize=(10,10))\nplt.xlabel('type')\nplt.ylabel('mean rating')\nsns.barplot(x=list(map(lambda x: x[0],rate_type)), y=list(map(lambda x: x[1],rate_type)))\n\"\"\"\nExplore amount of ratings\n\"\"\"\nsns.violinplot(df_anime['rating'])\ndf_anime['rating'].describe()\n\"\"\"\nExplore members\n\"\"\"\ntop5 = df_anime.sort_values(by=['members'], ascending=False)[:5]\ndown5 = df_anime.sort_values(by=['members'], ascending=False)[-5:]\n\"\"\"\nBuild count plot top5 \n\"\"\"\nplt.figure(figsize=(10,10))\na = sns.barplot(x=top5['name'],y=top5['members'])\n_ = plt.xticks(a.get_xticks(), rotation=90)\n\"\"\"\nMake plot of rating top5\n\"\"\"\nplt.figure(figsize=(10,10))\na = sns.barplot(x=top5['name'],y=top5['rating'])\n_ = plt.xticks(a.get_xticks(), rotation=90)\n\"\"\"\nMake plot of down5\n\"\"\"\nplt.figure(figsize=(10,10))\na = sns.barplot(x=down5['name'],y=down5['members'])\n_ = plt.xticks(a.get_xticks(), rotation=90)\n\"\"\"\nMake plot of rating down5\n\"\"\"\nplt.figure(figsize=(10,10))\na = sns.barplot(x=down5['name'],y=down5['rating'])\n_ = plt.xticks(a.get_xticks(), rotation=90)\n\"\"\"\n# Explore rating dataframe\n\"\"\"\ndf_rating\n\"\"\"\nExplore user_id\n\"\"\"\n#find number of unique user\nlen(df_rating['user_id'].unique())\n\"\"\"\nExplore anime_id\n\"\"\"\n#find number of unique anime\nlen(df_rating['anime_id'].unique())\n\"\"\"\ndetermine which anime the user liked, by determine mean user rating and if single rating bigger than mean, then user like this anime\n\"\"\"\ndf_rating['mean_rating'] = df_rating.groupby('user_id')['rating'].transform('mean')\ndf_rating\na = df_rating[df_rating['rating']>=df_rating['mean_rating']].apply(lambda x: 1,axis=1)\nindex_liked = a.index.to_list()\ndf_rating_liked = df_rating.iloc[index_liked,:]\n\ndf_rating_liked = df_rating_liked.drop(['rating','mean_rating'], axis=1)\ndf_rating_liked\n\"\"\"\n# Prepare data for clusterize\n\"\"\"\n\"\"\"\nThe idea is that we first clusterize df_anime according to its parameters(without anime_id). Then, for example, we take the first user and his anime which he \u201cliked\u201d. We build the \"user centroid\" according to his anime. And then we look for the nearest points through the centroids of the clusters\n\"\"\"\nanime_index = {df_anime.loc[idx,'anime_id']:idx for idx in df_anime.index}\ndf_anime_clusterize = df_anime.drop(['name','anime_id'],axis=1)\ndf_anime_clusterize = pd.get_dummies(df_anime_clusterize)\n\"\"\"\nDefine numerical and categorical columns\n\"\"\"\nnum_cols= df_anime_clusterize[['episodes','rating','members']]\ncat_cols = df_anime_clusterize.drop(['episodes','rating','members'], axis=1)\n\"\"\"\nScale numericals columns\n\"\"\"\nscaler = StandardScaler()\nnum_cols = pd.DataFrame(scaler.fit_transform(num_cols))\nnum_cols.columns = ['episodes_scale','rating_scale','members_scale']\ndf_anime_clusterize = pd.concat([num_cols, cat_cols], axis=1, join='inner')\n\"\"\"\n# Make clusters by MiniBatchKMeans\n\"\"\"\nscores = []\ninertia_list = np.empty(11)\n\nfor i in range(2,11):\n    print(i)\n    kmeans = MiniBatchKMeans(n_clusters=i, batch_size=50)\n    kmeans.fit(df_anime_clusterize)\n    inertia_list[i] = kmeans.inertia_\n    scores.append(silhouette_score(df_anime_clusterize, kmeans.labels_))\n\n\nplt.plot(range(0,11),inertia_list,'-o')\nplt.xlabel('Number of cluster')\nplt.axvline(x=4, color='blue', linestyle='--')\nplt.ylabel('Inertia')\nplt.show()\n\n\n\n\nplt.plot(range(2,11), scores);\nplt.title('Results KMeans')\nplt.xlabel('n_clusters');\nplt.axvline(x=4, color='blue', linestyle='--')\nplt.ylabel('Silhouette Score');\nplt.show()\n\n\n\"\"\"\nFrom theses result, i decide to pick 4 number of clusters\n\"\"\"\nkmeans =  MiniBatchKMeans(n_clusters=4,batch_size=40)\nkmeans = kmeans.fit(df_anime_clusterize)\nclusters = kmeans.predict(df_anime_clusterize)\ndf_anime_clusterize['cluster'] = clusters\ndf_anime_clusterize['cluster'].value_counts()\n\"\"\"\n# Display clusters\n\"\"\"\n\"\"\"\nPick 4000 rows, to reduce time of a calculation\n\"\"\"\nplot_df = pd.DataFrame(np.array(df_anime_clusterize.sample(4000)))\nplot_df.columns = df_anime_clusterize.columns\n\"\"\"\nPick this value of perplexity. because return good result with good time of a calculation\n\"\"\"\nperplexity = 30\n\"\"\"\ncreate tsne for 2d and 3d plots\n\"\"\"\ntsne_2d = TSNE(n_components=2, perplexity=perplexity)\n\ntsne_3d = TSNE(n_components=3, perplexity=perplexity)\nTCs_2d = pd.DataFrame(tsne_2d.fit_transform(plot_df.drop([\"cluster\"], axis=1)))\nTCs_3d = pd.DataFrame(tsne_3d.fit_transform(plot_df.drop([\"cluster\"], axis=1)))\nTCs_2d.columns = [\"TC1_2d\",\"TC2_2d\"]\n\nTCs_3d.columns = [\"TC1_3d\",\"TC2_3d\",\"TC3_3d\"]\nplot_df = pd.concat([plot_df,TCs_2d,TCs_3d], axis=1, join='inner')\nplot_df[\"1d_y\"] = 0\nclusters = {}\nfor cluster_label in plot_df['cluster'].unique():\n    clusters[cluster_label] = plot_df[plot_df[\"cluster\"] == cluster_label]\n\"\"\"\n2d plot\n\"\"\"\ndata = []\nfor key in clusters.keys():\n    data.append(go.Scatter(\n                    x = clusters[key][\"TC1_2d\"],\n                    y = clusters[key][\"TC2_2d\"],\n                    mode = \"markers\",\n                    name = \"Cluster %s\"%key,\n                    text = None))\n\ntitle = \"Visualizing Clusters in Two Dimensions Using T-SNE (perplexity=\" + str(perplexity) + \")\"\n\nlayout = dict(title = title,\n              xaxis= dict(title= 'TC1',ticklen= 5,zeroline= False),\n              yaxis= dict(title= 'TC2',ticklen= 5,zeroline= False)\n             )\n\nfig = dict(data = data, layout = layout)\n\niplot(fig)\n\"\"\"\n3d plot\n\"\"\"\ndata = []\nfor key in clusters.keys():\n    data.append(go.Scatter3d(\n                    x = clusters[key][\"TC1_3d\"],\n                    y = clusters[key][\"TC2_3d\"],\n                    z = clusters[key][\"TC3_3d\"],\n                    mode = \"markers\",\n                    name = \"Cluster %s\"%key,\n                    text = None))\n\n\ntitle = \"Visualizing Clusters in Three Dimensions Using T-SNE (perplexity=\" + str(perplexity) + \")\"\n\nlayout = dict(title = title,\n              xaxis= dict(title= 'TC1',ticklen= 5,zeroline= False),\n              yaxis= dict(title= 'TC2',ticklen= 5,zeroline= False)\n             )\nplt.figure(figsize=(20,20))\nfig = dict(data = data, layout = layout)\n\niplot(fig)\n\"\"\"\n# find the closest anime to user's liked anime\n\"\"\"\n\"\"\"\nBuild dict with key cluster and a list of values anime in this cluster\n\"\"\"\nanime_clusters = {i: [] for i in range(4)}\nfor anime_id, c_pred in zip(df_anime['anime_id'], df_anime_clusterize['cluster']):\n    anime_clusters[c_pred] +=[anime_id]\n\"\"\"\nFunction that find mean vector \"user centroid\" of their view history\n\"\"\"\ndef find_user_centroid(data):\n    data = data[data['cluster']==data['cluster'].mode()[0]]\n    data = data.drop(['user_id','anime_id','cluster'], axis=1,errors='ignore')\n    return pd.DataFrame(data.mean(axis=0)).T\n\"\"\"\nCreate experiment data. take 100k from df_rating rows so it would take less time to calculate.\n\"\"\"\n\"\"\"\nStructure of experiment data. we group by data by user, and take 75% to build recommendations, and other 25% we check how to close our recommendations to true value(anime which liked our user)\n\"\"\"\ndata = df_rating_liked[:100000]\ngrouped = data.groupby('user_id')\ntrain_data = {'user_id': [],'anime_id': []}\ntest_data = {'user_id': [],'anime_id': []}\nfor name,group in grouped:\n    if len(group)>1:\n        \n        train, test = train_test_split(group['anime_id'],test_size=0.2,random_state=42)\n\n        train_data['user_id']+=[name for _ in range(len(train))]\n        train_data['anime_id']+= list(train)\n\n        test_data['user_id']+=[name for _ in range(len(test))]\n        test_data['anime_id']+= list(test)\n    \n    \nlen(train_data['user_id']),len(test_data['user_id'])\ndf_train = pd.DataFrame(train_data)\ndf_test = pd.DataFrame(test_data)\n\ndf_train = df_train.join(df_anime_clusterize, how='inner')\ntrain_centroids = pd.DataFrame(columns = ['user_id']+list(df_anime_clusterize.columns))\n\nfor name,group in df_train.groupby('user_id'):\n    user_centroid = find_user_centroid(group)\n    user_centroid['user_id'] = name\n    user_centroid['cluster'] = group['cluster'].mode()[0]\n    train_centroids = train_centroids.append(user_centroid,ignore_index=True)\n#     print(group['cluster'])\ntrain_centroids\n\"\"\"\nWhen we find users centroids, next step find nearest global centroid. we find distance to each centroids and sort them ascending=True, and pick top 3 centroids.\n\"\"\"\nresult = {}\nfor user_id in train_centroids['user_id'][:10]:\n    print('User id %s'%user_id)\n    user = train_centroids[train_centroids['user_id']==user_id]\n    result_dist = []\n   \n    for anime_id in anime_clusters[user['cluster'].iloc[0]]:\n        #iterate by all points in cluster. find 10 closer points to user centroid\n        \n        anime_point = df_anime_clusterize.loc[anime_index[anime_id],:].drop('cluster').to_numpy()\n        \n        result_dist.append((anime_id, np.linalg.norm(user.drop(['cluster','user_id'],axis=1)-anime_point)))\n        \n    \n    result[user_id] = sorted(result_dist,key=lambda x: x[1])[:10]\n\"\"\"\nWhen we get our recommendation let's check it\n\"\"\"\ntest_data = pd.DataFrame(test_data)\nerror_recom = {}\nfor user_id in list(result.keys())[:10]:\n    test_centroid = find_user_centroid(test_data[test_data['user_id']==user_id].join(df_anime_clusterize,how='inner'))\n    index = list(map(lambda x: anime_index[x[0]],result[user_id]))\n    result_centroid = find_user_centroid(df_anime_clusterize.iloc[index,:])\n    error_recom[user_id]  = np.linalg.norm(test_centroid-result_centroid)\nerror_recom","meta":"{'source': 'AI4Code', 'id': 'c6516552cf1c35'}"}
{"id":"122366","text":"\"\"\"\n# Introduction\n\nFrom Wikipedia: [r\/subredditoftheday](https:\/\/www.reddit.com\/r\/subredditoftheday\/), .. is a celebration of the interesting communities on reddit.com. Once a day we shine a spotlight on the small, the big, the new and the old. Our mission is to spotlight unique reddit communities and bring the awesome, every damn day.\n\n<center><img src=\"https:\/\/styles.redditmedia.com\/t5_2sgno\/styles\/communityIcon_2wot6zdwqem01.png\" width=600><\/img><\/center>\n\n### Inspiration comes from Gabriel Preda Analysis https:\/\/www.kaggle.com\/gpreda\/wallstreetbets-reddit-posts-analysis. Thanks to give him credits. \ud83d\udc4f\n\"\"\"\n\"\"\"\n# Analysis preparation\n\nWe initialize the packages that we will use in the analysis.\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline \nfrom wordcloud import WordCloud, STOPWORDS\nfrom nltk.sentiment import SentimentIntensityAnalyzer\nfrom textblob import TextBlob\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\"\"\"\nWe read and glimpse the data.\n\"\"\"\ndata_df = pd.read_csv(\"..\/input\/sub-reddit-of-the-day-posts\/subredditoftheday_reddit.csv\")\ndata_df.head()\n\"\"\"\nWe also look to things like data quality, for example missing data.\n\"\"\"\ndata_df.info()\ndef missing_data(data):\n    total = data.isnull().sum()\n    percent = (data.isnull().sum()\/data.isnull().count()*100)\n    tt = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n    types = []\n    for col in data.columns:\n        dtype = str(data[col].dtype)\n        types.append(dtype)\n    tt['Types'] = types\n    return(np.transpose(tt))\nmissing_data(data_df)\n\"\"\"\nBody of posts is missing in approximatively half of the data.\n\"\"\"\n\"\"\"\n# Data visualization\n\n\nWe will use wordclouds to identify the most frequent words in the titles and body of the posts.\n\nFor understanding some of the frequent used terms, it will be useful to consult this resource: [r\/subredditoftheday stats](https:\/\/subredditstats.com\/r\/subredditoftheday)\n\nSome examples (from the resource mentioned above):  \n\n1\t  pancakeswap\t\u00d73717\n2\t  girlsyouknowirl\t\u00d72709\n3\t  amazing_architecture\t\u00d72047\n4\t  BaddieHermOnlyFans\t\u00d71709\n5\t  SmartGamingDeals\t\u00d71315\n6\t  GrandPieceOnline\t\u00d7844\n7\t  thesongofachilles\t\u00d7668\n8\t  WKHS\t\u00d7537\n9\t  mangacoloring\t\u00d7466\n10\t  RushRoyale\t\u00d7451\n11\t  FranceDetendue\t\u00d7410\n12\t  RustConsole\t\u00d7395\n13\t  t3ddyyyy\t\u00d7383\n14\t  Ranboo\t\u00d7356\n15\t  WANDAVISION\t\u00d7348\n16\t  NFT\t\u00d7336\n17\t  SpecialHumor\t\u00d7313\n18\t  MakersPlace\t\u00d7296\n19\t  NarakaBladePoint\t\u00d7295\n20\t  pantiesandsocks\t\u00d7270\n21\t  Timberborn\t\u00d7242\n22\t  LesliePecas\t\u00d7227\n23\t  sekulermilliyetciturk\t\u00d7223\n24\t  TollbugataBets\t\u00d7221\n25\t  GenshinTrades\t\u00d7213\n26\t  epoxyhotdog\t\u00d7200\n27\t  FuckPierre\t\u00d7185\n28\t  InsideJob\t\u00d7185\n29\t  AxieInfinity\t\u00d7182\n30\t  BinanceSmartChain\t\u00d7181\n\"\"\"\ndef show_wordcloud(data, title=\"\"):\n    text = \" \".join(t for t in data.dropna())\n    stopwords = set(STOPWORDS)\n    stopwords.update([\"t\", \"co\", \"https\", \"amp\", \"U\", \"fuck\", \"fucking\"])\n    wordcloud = WordCloud(stopwords=stopwords, scale=4, max_font_size=50, max_words=500,background_color=\"black\").generate(text)\n    fig = plt.figure(1, figsize=(16,16))\n    plt.axis('off')\n    fig.suptitle(title, fontsize=20)\n    fig.subplots_adjust(top=2.3)\n    plt.imshow(wordcloud, interpolation='bilinear')\n    plt.show()\n\"\"\"\n## Title\n\"\"\"\nshow_wordcloud(data_df['title'], title = 'Prevalent words in titles')\n\"\"\"\n## Body\n\"\"\"\nshow_wordcloud(data_df['body'], title = 'Prevalent words in post bodies')\n\"\"\"\n# Sentiment analysis\n\n## With nltk SentimentIntensityAnalyzer\n\"\"\"\n# borrowed from https:\/\/www.kaggle.com\/pashupatigupta\/sentiments-transformer-vader-embedding-bert\nsia = SentimentIntensityAnalyzer()\ndef find_sentiment(post):\n    if sia.polarity_scores(post)[\"compound\"] > 0:\n        return \"Positive\"\n    elif sia.polarity_scores(post)[\"compound\"] < 0:\n        return \"Negative\"\n    else:\n        return \"Neutral\"       \ndef plot_sentiment(df, feature, title):\n    counts = df[feature].value_counts()\n    percent = counts\/sum(counts)\n\n    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))\n\n    counts.plot(kind='bar', ax=ax1, color='green')\n    percent.plot(kind='bar', ax=ax2, color='blue')\n    ax1.set_ylabel(f'Counts : {title} sentiments', size=12)\n    ax2.set_ylabel(f'Percentage : {title} sentiments', size=12)\n    plt.suptitle(f\"Sentiment analysis: {title}\")\n    plt.tight_layout()\n    plt.show()\n\"\"\"\n### Title\n\"\"\"\ndata_df['title_sentiment'] = data_df['title'].apply(lambda x: find_sentiment(x))\nplot_sentiment(data_df, 'title_sentiment', 'Title')\nshow_wordcloud(data_df.loc[data_df['title_sentiment']=='Positive', 'title'], title = 'Prevalent words in titles (Positive sentiment)')\nshow_wordcloud(data_df.loc[data_df['title_sentiment']=='Negative', 'title'], title = 'Prevalent words in titles (Negative sentiment)')\nshow_wordcloud(data_df.loc[data_df['title_sentiment']=='Neutral', 'title'], title = 'Prevalent words in titles (Neutral sentiment)')\n\"\"\"\n### Body\n\"\"\"\ndf = data_df.loc[~data_df.body.isna()]\ndf['body_sentiment'] = df['body'].apply(lambda x: find_sentiment(x))\nplot_sentiment(df, 'body_sentiment', 'Body')\nshow_wordcloud(df.loc[df['body_sentiment']=='Positive', 'body'], title = 'Prevalent words in body (Positive sentiment)')\nshow_wordcloud(df.loc[df['body_sentiment']=='Negative', 'body'], title = 'Prevalent words in body (Negative sentiment)')\nshow_wordcloud(df.loc[df['body_sentiment']=='Neutral', 'body'], title = 'Prevalent words in body (Neutral sentiment)')\n\"\"\"\n## With TextBlob\n\"\"\"\ndef find_sentiment_polarity_textblob(post):\n    blob = TextBlob(post)\n    polarity = 0\n    for sentence in blob.sentences:\n        polarity += sentence.sentiment.polarity\n    return polarity\n\ndef find_sentiment_subjectivity_textblob(post):\n    blob = TextBlob(post)\n    subjectivity = 0\n    for sentence in blob.sentences:\n        subjectivity += sentence.sentiment.subjectivity\n    return subjectivity\ndata_df['title_sentiment_polarity'] = data_df['title'].apply(lambda x: find_sentiment_polarity_textblob(x))\ndata_df['title_sentiment_subjectivity'] = data_df['title'].apply(lambda x: find_sentiment_subjectivity_textblob(x))\ndef plot_sentiment_textblob(df, feature, title):\n    polarity = df[feature+'_sentiment_polarity']\n    subjectivity = df[feature+'_sentiment_subjectivity']\n\n    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))\n\n    polarity.plot(kind='kde', ax=ax1, color='magenta')\n    subjectivity.plot(kind='kde', ax=ax2, color='green')\n    ax1.set_ylabel(f'Sentiment polarity : {title}', size=12)\n    ax2.set_ylabel(f'Sentiment subjectivity: {title}', size=12)\n    plt.suptitle(f\"Sentiment analysis (polarity & subjectivity): {title}\")\n    plt.tight_layout()\n    plt.show()\nplot_sentiment_textblob(data_df, \"title\", 'Title')\ndf['body_sentiment_polarity'] = df['body'].apply(lambda x: find_sentiment_polarity_textblob(x))\ndf['body_sentiment_subjectivity'] = df['body'].apply(lambda x: find_sentiment_subjectivity_textblob(x))\nplot_sentiment_textblob(df, \"body\", 'Body')","meta":"{'source': 'AI4Code', 'id': 'e105c2f86bf233'}"}
{"id":"55616","text":"\"\"\"\n## INTRODUCTION\n\nAs you may know, Kaggle kernels have a **limit for how much time they can keep running**.   \nSometimes, it's enough time to train a descent model, but sometimes it isn't. \n\nIf you have a big model, using very big data, it's possible that Kaggle's kernels available time is not enough for you. (Even if you're using a GPU)\n\nFor that reason, this kernel brings you a simple way to continuously train a Keras model for the time you want.   \nThis allows you to commit and run your kernel without worrying whether it will be interrupted for exceeding execution time or not. \n\n## Creating a custom callback\n\nHere, we are going to create a custom callback, called `TimerCallback`, in order to manage training time and eventually interrupt it.\n\nA `Callback` in Keras is an object that you pass either to the `model.fit` or `model.fit_generator` methods, in order to execute additional commands between batches, epochs, etc.   \nThere are several kinds of ready-to-use callbacks, such as to save the best model in each epoch, to interrupt training when some metric or loss reaches a condition, to show graphs, etc., and there is also the possibility of creating custom ones.\n\nOurs will interrupt training shortly before our time limit.\n\n\n\n\"\"\"\nimport time \n\n#let's also import the abstract base class for our callback\nfrom keras.callbacks import Callback\n\n#defining the callback\nclass TimerCallback(Callback):\n    \n    def __init__(self, maxExecutionTime, byBatch = False, on_interrupt=None):\n        \n# Arguments:\n#     maxExecutionTime (number): Time in minutes. The model will keep training \n#                                until shortly before this limit\n#                                (If you need safety, provide a time with a certain tolerance)\n\n#     byBatch (boolean)     : If True, will try to interrupt training at the end of each batch\n#                             If False, will try to interrupt the model at the end of each epoch    \n#                            (use `byBatch = True` only if each epoch is going to take hours)          \n\n#     on_interrupt (method)          : called when training is interrupted\n#         signature: func(model,elapsedTime), where...\n#               model: the model being trained\n#               elapsedTime: the time passed since the beginning until interruption   \n\n        \n        self.maxExecutionTime = maxExecutionTime * 60\n        self.on_interrupt = on_interrupt\n        \n        #the same handler is used for checking each batch or each epoch\n        if byBatch == True:\n            #on_batch_end is called by keras every time a batch finishes\n            self.on_batch_end = self.on_end_handler\n        else:\n            #on_epoch_end is called by keras every time an epoch finishes\n            self.on_epoch_end = self.on_end_handler\n    \n    \n    #Keras will call this when training begins\n    def on_train_begin(self, logs):\n        self.startTime = time.time()\n        self.longestTime = 0            #time taken by the longest epoch or batch\n        self.lastTime = self.startTime  #time when the last trained epoch or batch was finished\n    \n    \n    #this is our custom handler that will be used in place of the keras methods:\n        #`on_batch_end(batch,logs)` or `on_epoch_end(epoch,logs)`\n    def on_end_handler(self, index, logs):\n        \n        currentTime      = time.time()                           \n        self.elapsedTime = currentTime - self.startTime    #total time taken until now\n        thisTime         = currentTime - self.lastTime     #time taken for the current epoch\n                                                               #or batch to finish\n        \n        self.lastTime = currentTime\n        \n        #verifications will be made based on the longest epoch or batch\n        if thisTime > self.longestTime:\n            self.longestTime = thisTime\n        \n        \n        #if the (assumed) time taken by the next epoch or batch is greater than the\n            #remaining time, stop training\n        remainingTime = self.maxExecutionTime - self.elapsedTime\n        if remainingTime < self.longestTime:\n            \n            self.model.stop_training = True  #this tells Keras to not continue training\n            print(\"\\n\\nTimerCallback: Finishing model training before it takes too much time. (Elapsed time: \" + str(self.elapsedTime\/60.) + \" minutes )\\n\\n\")\n            \n            #if we have passed the `on_interrupt` callback, call it here\n            if self.on_interrupt is not None:\n                self.on_interrupt(self.model, self.elapsedTime)\n\"\"\"\n## Using callbacks\n\nUsing callbacks in Keras is very simple, you just pass a list of them to the fit method. Suppose we want to stop training before reaching 350 minutes (5:50 hours):\n\n    timerCallback = TimerCallback(350)\n    model.fit(x_train, y_train, ..... , callbacks = [timerCallback, someOtherCallback])\n    \nYou can explore the `on_interrupt` method to save the model or its weights at interruption:\n\n    timerCallback = TimerCallback(350, \n                    on_interrupt = lambda model, elapsed: model.save_weights('my_weights.h5'))\n    \nOr you can use a `ModelCheckpoint` or a `LambdaCallback` if you want more customization:\n\n    from keras.callbacks import ModelCheckpoint\n    model.fit(x_train, y_train, ...., callbacks = [timerCallback, \n                                                   ModelCheckpoint('my_weights.h5')])\n\nSee more on callbacks here:  https:\/\/keras.io\/callbacks\/\n    \n## EXAMPLE\n\nNow, let's take a toy model for digit classification and interrupt it's training in five minutes, for instance.\n\nSince this Kernel is not about models, how to make good networks, etc., let's not take too much time explaining the details of data loading and model creation.   \nI'm sure there are lots of tutorial kernels on this :)\n\n### Loading and checking:\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom keras.utils import to_categorical\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n#loading data - as for a demonstration of the callback,\n#we won't worry about validation data in this kernel (but it would work the same way)\ntrainData = pd.read_csv('..\/input\/train.csv')\ny_train = to_categorical(np.array(trainData['label']))                   \nx_train = np.array(trainData[list(trainData)[1:]]).reshape((-1,28,28,1)) \n    #labels as one-hot encoded vectors (ex: label 2 will become [0,0,1,0,0,0,0,0,0,0])\n    #x shaped as images with one channel\n    \n    \n#quick check\ndef quickCheck(x, y, predicted=None):\n    #plotting images\n    fig,ax = plt.subplots(nrows=1,ncols=10, figsize=(10,2))\n    for i in range(10):\n        ax[i].imshow(x[i].reshape((28,28)))\n    plt.show()\n    \n    #printing labels\n    y = np.argmax(y, axis=1) #converting from one-hot to numerical labels\n    print(\"  \" + \"      \".join([str(i) for i in y[:10]]) + \" <- labels\")\n    \n    #printing predicted if passed\n    if predicted is not None:\n        predicted = np.argmax(predicted, axis=1)\n        print(\"  \" + \"      \".join([str(i) for i in predicted[:10]]) + \" <- predicted labels\")\n\nquickCheck(x_train,y_train)\n\n\n\n    \n\"\"\"\n### Creating a model\n\"\"\"\nfrom keras.layers import Input, Conv2D, Dense, Flatten, MaxPooling2D\nfrom keras.models import Model\n\n#a simple convolutional model (not worried about it's capabilities)\ndef createModel():\n    inputImage = Input((28,28,1))\n    output = Conv2D(10, 3, activation='tanh')(inputImage)\n    output = Conv2D(20, 3, activation='tanh')(output)\n    output = MaxPooling2D((4,4))(output)\n    output = Conv2D(10, 3, activation='tanh')(output)\n    output = Flatten()(output)\n    output = Dense(10, activation='sigmoid')(output)\n\n    model = Model(inputImage, output)\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n    model.summary()\n    return model\n\nmodel = createModel()\n\"\"\"\n### Training the model for 5 minutes at most \n\n#### For your Kaggle kernel, you could try 350 minutes, as it has a 360 minutes limit\n\n.\n\nOf course that usually you should enable the GPU for your kernel to run many times faster. This callback technique is absolutely not necessary for such a simple model with a simple dataset, but might come in handy when you're working on really big models and data :)\n\n\"\"\"\nmodel.fit(x_train, y_train, epochs = 1000000000, callbacks=[TimerCallback(5)])\n\"\"\"\n### Saving the model's weights as outputs (you can then download these weights later or use them as inputs to other kernels)\n\nYou could also explore `model.save(file)` and `model = load_model(file)`, if you prefer. (Some models might have serialization problems, because of this I always prefer `save_weights()` )\n\"\"\"\n#a function compatible with the on_interrupt handler\ndef saveWeights(model, elapsed):\n    model.save_weights(\"model_weights.h5\")\n\n#fitting with the callback\ncallbacks = [TimerCallback(5, on_interrupt=saveWeights)]\nmodel.fit(x_train,y_train, epochs = 100000000000, callbacks=callbacks)\n\n\n#check that the weights were saved:\nimport os\nos.listdir(\".\")\n\"\"\"\n### Using the saved weights in a new model and checking predictions\n\"\"\"\n#although it uses the same creator function, it's a different model from the previous one\ndel(model)\nmodel2 = createModel()\n\n#load weights - this only works if the model has the same layer types and the same parameters\nmodel2.load_weights('model_weights.h5') #\n\n#evaluate model2\nprint(\"\\n\\nEvaluating model 2:\")\nloss, acc = model2.evaluate(x_train, y_train)\nprint('model 2 loss: ' + str(loss))\nprint('model 2 acc:  ' + str(acc))\n\n#predicting and checking\npredicts = model2.predict(x_train[25:35])\nquickCheck(x_train[25:35],y_train[25:35], predicts)","meta":"{'source': 'AI4Code', 'id': '667d2d0a22ad82'}"}
{"id":"133082","text":"# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.decomposition import PCA\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\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\n\"\"\"\n# Load Data\n\"\"\"\ndf= pd.read_csv('\/kaggle\/input\/unsupervised-learning-on-country-data\/Country-data.csv')\ndf.head()\ndf.shape\ndf.info()\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nnum_cols= [col for col in df.columns]\nnum_cols.remove('country')\n\nplt.figure(figsize=(20,20))\ni=1\nfor col in num_cols:\n    plt.subplot(5,2,i)\n    sns.distplot(df[col])\n    i+=1\n\nsns.scatterplot(x= 'gdpp', y='exports', data=df)\nsns.scatterplot(x= 'gdpp', y='income', data=df)\nsns.scatterplot(x= 'gdpp', y='inflation', data=df)\nsns.scatterplot(x= 'gdpp', y='health', data=df)\nsns.scatterplot(x= 'gdpp', y='life_expec', data=df)\nplt.figure(figsize=(8,8))\nsns.heatmap(df.corr(), annot=True, cmap='coolwarm')\n\"\"\"\n# Insights\n* Child mortality is highly corelated to total fertility\n* Child Mortality is highly negatively corelated to life expectancy\n* Exports and imports are corelated\n* Income and gdp are highly corelated\n\"\"\"\n\"\"\"\n# Preprocessing\n\"\"\"\ndf.drop('country', axis=1, inplace=True)\ncolumns=df.columns\nfrom sklearn.preprocessing import StandardScaler\n\nss= StandardScaler()\ndf_scaled= ss.fit_transform(df)\ndf_scaled= pd.DataFrame(df_scaled,columns=columns)\ndf_scaled.head()\ndistortions=[]\nsil_scores=[]\n\nfor i in range(2,10):\n    kmeans= KMeans(n_clusters= i )\n    kmeans.fit(df_scaled)\n    distortions.append(kmeans.inertia_)\n    label= kmeans.labels_\n    sil_scores.append(silhouette_score(df_scaled,label))\nplt.plot(np.arange(2,10,1) ,distortions)\nplt.plot(np.arange(2,10,1), distortions, 'o')\nplt.plot(np.arange(2,10,1) , sil_scores)\nplt.plot(np.arange(2,10,1), sil_scores, 'o')\n\"\"\"\n# K-Means\n\"\"\"\nkmeans= KMeans(n_clusters= 3,n_init=10, init='random', tol=1e-04, max_iter=300 )\nkmeans.fit(df_scaled)\ny_pred= kmeans.predict(df_scaled)\ny_pred\ndf_scaled['clusters']= y_pred\n\ndata= pd.read_csv('\/kaggle\/input\/unsupervised-learning-on-country-data\/Country-data.csv')\ndf_scaled['Country']= data['country']\ndf.head()\nsns.scatterplot(x= 'gdpp', y='income', hue='clusters', data=df_scaled)\nsns.scatterplot(x= 'gdpp', y='health', hue='clusters', data=df_scaled)\ndf_scaled.drop('Country', axis=1, inplace=True)\npca= PCA(n_components=2)\ndf_final= pca.fit_transform(df_scaled)\ndf_final_pca= pd.DataFrame(df_final, columns=['pca1', 'pca2'])\ndf_final_pca.head()\ndf_final_pca['cluster']= df_scaled['clusters']\ndf_final_pca.head()\n\"\"\"\n# Final Outcome\n\"\"\"\nplt.figure(figsize=(7,5))\nax = sns.scatterplot(x='pca1', y='pca2', hue='cluster', data=df_final_pca, palette='bright')\ndf_final_pca['Country']= data['country']\ndf_final_pca.head()\ncluster_0= df_final_pca.loc[df_final_pca['cluster']==0]\ncluster_0['Country'].unique()\ncluster_1= df_final_pca.loc[df_final_pca['cluster']==1]\ncluster_1['Country'].unique()\ncluster_2= df_final_pca.loc[df_final_pca['cluster']==2]\ncluster_2['Country'].unique()\n\"\"\"\n# Conclusion\n\n1. Cluster 0 contains the 3rd world or poor countries\n1. Cluster 1 contains the developed countries\n1. Cluster 2 contains the developing countries with average value of the parameters \n\"\"\"\n\"\"\"\n# Like and Upvote if you liked my Notebook :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f4d23eb806453e'}"}
{"id":"87729","text":"import numpy as np\nimport pandas as pd\n#a = pd.read_csv('..\/input\/amazon_cells_labelled.txt',names=['sentence','label'],sep='\\t')[:10]\nfiles={'yelp':'yelp_labelled.txt',\n       'amazon':'amazon_cells_labelled.txt',\n       'imdb':'imdb_labelled.txt'}\ndf_list=[]\nfor k,v in files.items():\n    path='..\/input\/'+v\n    df = pd.read_csv(path,names=['sentence','label'],sep='\\t')\n    df['source']=k\n    df_list.append(df)\ndf = pd.concat(df_list)\nprint(df.iloc[0])\nprint(type(df))\nfrom sklearn.model_selection import train_test_split\n#Split the data\ndf_yelp = df[df['source']=='yelp']\nsentence = df_yelp['sentence']\nlabel = df_yelp['label']\nsen_train,sen_test,y_train,y_test = train_test_split(sentence,label,test_size=0.25,random_state=1000)\nlen(sen_train),len(sen_test)\n#Best way to understand feature vector\n'''\nsentences = ['John John likes icecream','utsav','John is utsav']\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nvec = CountVectorizer(min_df=0,lowercase=False)\nvec.fit(sentences)\nvec.vocabulary_\nvec.transform(sentences).toarray()\n'''\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\nvectorizer.fit(sen_train)\nX_train = vectorizer.transform(sen_train)\nX_test = vectorizer.transform(sen_test)\nX_train,X_test\n\"\"\"\n**sparse matrix**:\n                This is a data type that is optimized for matrices with only a few non-zero elements, which only keeps track of the non-zero elements reducing the memory load\n\"\"\"\n\"\"\"\n**1. LogisticRegression classifier **\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression(solver='lbfgs')\nlr.fit(X_train,y_train)\npredict_lr = lr.predict(X_test)\nscore = lr.score(X_test,y_test)\nresult_lr = pd.DataFrame({'Predict':predict_lr,'actual':y_test})\nprint(f'Accuracy: {score}')\nresult_lr[0:10]\n#Acuuracy\nfrom sklearn.metrics import classification_report,confusion_matrix\nclr = classification_report(y_test,predict_lr)\ncom = confusion_matrix(y_test,predict_lr)\nprint(clr)\nprint(\"Confusion_matrix\")\nprint(com)\n#Test for unseen data\nfor source in df['source'].unique():\n    df_yelp = df[df['source']==source]\n    sentence = df_yelp['sentence']\n    label = df_yelp['label']\n    sen_train,sen_test,y_train,y_test = train_test_split(sentence,label,test_size=0.25,random_state=1000)\n    \n    vectorizer = CountVectorizer()\n    vectorizer.fit(sen_train)\n    X_train = vectorizer.transform(sen_train)\n    X_test = vectorizer.transform(sen_test)\n\n    lr = LogisticRegression(solver='lbfgs')\n    lr.fit(X_train,y_train)\n    score = lr.score(X_test,y_test)\n    print('Source: {} Accuracy: {:.3f}'.format(source,score))\n    \nfrom sklearn.model_selection import train_test_split\n#Split the data\ndf_yelp = df[df['source']=='yelp']\nsentence = df_yelp['sentence']\nlabel = df_yelp['label']\nsen_train,sen_test,y_train,y_test = train_test_split(sentence,label,test_size=0.25,random_state=1000)\nlen(sen_train),len(sen_test)\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\nvectorizer.fit(sen_train)\nX_train = vectorizer.transform(sen_train)\nX_test = vectorizer.transform(sen_test)\nX_train,X_test\nfrom keras.models import Sequential\nfrom keras import layers\ninput_dim = X_train.shape[1]\nmodel = Sequential()\nmodel.add(layers.Dense(10,input_dim=input_dim,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy',\n             optimizer='adam',\n             metrics=['accuracy'])\nmodel.summary()\nhistory = model.fit(X_train,y_train,\n                   epochs=100,verbose=True,\n                   validation_data=(X_test,y_test),\n                   batch_size=10)\nloss,accuracy = model.evaluate(X_train,y_train,verbose=False)\nprint('Training accuracy {}'.format(accuracy))\nloss,accuracy = model.evaluate(X_test,y_test,verbose=False)\nprint('Testing accuracy {}'.format(accuracy))\ndef hist(history):\n    from matplotlib import pyplot as plt\n    loss = history.history['loss']\n    val_loss = history.history['val_loss']\n    acc = history.history['acc']\n    val_acc = history.history['val_acc']\n    x = range(1,len(loss)+1)\n    plt.subplot(1,2,1)\n    plt.plot(x,loss,'r',label='training loss')\n    plt.plot(x,val_loss,'b',label='validation loss')\n    plt.legend()\n    plt.subplot(1,2,2)\n    plt.plot(x,acc,'r',label='training accuracy')\n    plt.plot(x,val_acc,'b',label='validation accuracy')\n    plt.legend()\nhist(history)\n\"\"\"\n**Overfitted model**\n\"\"\"\n#Two possible ways to represent a word as a vector are one-hot encoding and word embeddings\n#1)label encoding\nfrom sklearn.preprocessing import LabelEncoder\ncities = ['London', 'Berlin', 'Berlin', 'New York', 'London']\nle =LabelEncoder()\ncity_label = le.fit_transform(cities)\nprint(\"Label encoding -> \" ,city_label)\n\n#2)one-hot encoding\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder(sparse=False,categories='auto')\ncity_label = city_label.reshape((5,1))\nohe.fit_transform(city_label)\n#Word embeddings\n#This method represents words as dense word vectors (also called word embeddings) \n#which are trained unlike the one-hot encoding which are hardcoded.\n#This means that the word embeddings collect more information into fewer dimensions.\n#Now you need to tokenize the data into a format that can be used by the word embeddings\nfrom keras.preprocessing.text import Tokenizer\ntokenizer = Tokenizer(num_words=5000)\ntokenizer.fit_on_texts(sen_train)\n\nvocab_size = len(tokenizer.word_index) + 1\n\nX_train = tokenizer.texts_to_sequences(sen_train)\nX_test = tokenizer.texts_to_sequences(sen_test)\n\nfrom keras.preprocessing.sequence import pad_sequences\nmaxlen=100\nX_train = pad_sequences(X_train, padding='post', maxlen=maxlen)\nX_test = pad_sequences(X_test, padding='post', maxlen=maxlen)\n#input_dim: the size of the vocabulary\n#output_dim: the size of the dense vector\n#input_length: the length of the sequence\nfrom keras.models import Sequential\nfrom keras import layers\n\nout_dim=50\nmodel=Sequential()\nmodel.add(layers.Embedding(input_dim=vocab_size,\n                          output_dim=out_dim,\n                          input_length=maxlen))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(10, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\nmodel.summary()\nhistory = model.fit(X_train,y_train,\n                   epochs=20,\n                   verbose=True,\n                   validation_data=(X_test,y_test),\n                   batch_size=10)\nloss, accuracy = model.evaluate(X_train, y_train, verbose=False)\nprint(\"Training Accuracy: {:.4f}\".format(accuracy))\nloss, accuracy = model.evaluate(X_test, y_test, verbose=False)\nprint(\"Testing Accuracy:  {:.4f}\".format(accuracy))\nhist(history)\nfrom keras.models import Sequential\nfrom keras import layers\n\nout_dim=50\nmodel=Sequential()\nmodel.add(layers.Embedding(input_dim=vocab_size,\n                          output_dim=out_dim,\n                          input_length=maxlen))\nmodel.add(layers.GlobalMaxPool1D())\nmodel.add(layers.Dense(10, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\nmodel.summary()\nhistory = model.fit(X_train, y_train,\n                    epochs=20,\n                    verbose=False,\n                    validation_data=(X_test, y_test),\n                    batch_size=10)\nloss, accuracy = model.evaluate(X_train, y_train, verbose=False)\nprint(\"Training Accuracy: {:.4f}\".format(accuracy))\nloss, accuracy = model.evaluate(X_test, y_test, verbose=False)\nprint(\"Testing Accuracy:  {:.4f}\".format(accuracy))\nhist(history)","meta":"{'source': 'AI4Code', 'id': 'a0dfa2a1d5b155'}"}
{"id":"63018","text":"%matplotlib inline\n#\u9019\u662fjuoyter notebook\u7684magic word\u02d9\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom IPython import display\n\"\"\"\n# Steel Defect \u8cc7\u6599\u9810\u8655\u7406\n\n\"\"\"\nimport os\n#\u5224\u65b7\u662f\u5426\u5728jupyter notebook\u4e0a\ndef is_in_ipython():\n    \"Is the code running in the ipython environment (jupyter including)\"\n    program_name = os.path.basename(os.getenv('_', ''))\n\n    if ('jupyter-notebook' in program_name or # jupyter-notebook\n        'ipython'          in program_name or # ipython\n        'jupyter' in program_name or  # jupyter\n        'JPY_PARENT_PID'   in os.environ):    # ipython-notebook\n        return True\n    else:\n        return False\n\n\n#\u5224\u65b7\u662f\u5426\u5728colab\u4e0a\ndef is_in_colab():\n    if not is_in_ipython(): return False\n    try:\n        from google import colab\n        return True\n    except: return False\n\n#\u5224\u65b7\u662f\u5426\u5728kaggke_kernal\u4e0a\ndef is_in_kaggle_kernal():\n    if 'kaggle' in os.environ['PYTHONPATH']:\n        return True\n    else:\n        return False\n\nif is_in_colab():\n    from google.colab import drive\n    drive.mount('\/content\/gdrive')\nos.environ['TRIDENT_BACKEND'] = 'pytorch'\n\nif is_in_kaggle_kernal():\n    os.environ['TRIDENT_HOME'] = '.\/trident'\n    \nelif is_in_colab():\n    os.environ['TRIDENT_HOME'] = '\/content\/gdrive\/My Drive\/trident'\n\n#\u70ba\u78ba\u4fdd\u5b89\u88dd\u6700\u65b0\u7248 \n!pip uninstall tridentx -y\n!pip install ..\/input\/trident\/tridentx-0.7.4-py3-none-any.whl --upgrade\nimport json\nimport copy\nimport numpy as np\n#\u8abf\u7528trident api\nimport trident as T\nfrom trident import *\nfrom trident.models import resnet,efficientnet\nimport random\nimport glob\nimport pandas as pd\nimgs=glob.glob('..\/input\/severstal-steel-defect-detection\/train_images\/*jpg')\nprint(len(imgs))\n\ndf_train=pd.read_csv('..\/input\/severstal-steel-defect-detection\/train.csv')\nprint(df_train)\n\ndf_images_frequency=df_train['ImageId'].value_counts()\nprint(df_images_frequency)\n\npalette = [(0, 0, 0),(256, 192, 0), (0, 192, 256), (128, 0, 256), (256,64,0)]\n\ndef enc2mask(enc, shape=(1600,256),fill_value=0):\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    s = enc.split()\n    for i in range(len(s)\/\/2):\n        start = int(s[2*i]) - 1\n        length = int(s[2*i+1])\n        img[start:start+length] = int(fill_value)\n    return img.reshape(shape).T\n\n\ndef mask2enc(mask, n=4):\n    pixels = mask.T.flatten()\n    encs = []\n    for i in range(1,n+1):\n        p = (pixels == i).astype(np.int8)\n        if p.sum() == 0: encs.append('')\n        else:\n            p = np.concatenate([[0], p, [0]])\n            runs = np.where(p[1:] != p[:-1])[0] + 1\n            runs[1::2] -= runs[::2]\n            encs.append(' '.join(str(x) for x in runs))\n    return encs\n\n\ndef label2color(label_mask,palette):\n    num_classes = len(palette)\n\n    color_label= np.zeros((*label_mask.shape,3)).astype(np.int64)\n    for i in range(num_classes):\n        color_label[label_mask==i]=palette[i]\n    return color_label\ndf_train['mask'] = df_train.apply(lambda row: enc2mask(enc=row.EncodedPixels,fill_value=row.ClassId),axis=1)\nprint(df_train)\nfor i in range(10):\n    exsample_mask=df_train['mask'].iloc[i]\n    print(exsample_mask.shape)\n    print(exsample_mask.max())\n\nexsample_mask=df_train['mask'].iloc[3]\nexsample_image=image2array('..\/input\/severstal-steel-defect-detection\/train_images\/'+df_train['ImageId'].iloc[3])\nprint(exsample_mask.max())\ndisplay.display(array2image(exsample_mask))\n\nis_mask=np.expand_dims(np.greater(exsample_mask,0).astype(np.float32),-1)\ncolor_mask=label2color(exsample_mask,palette)\n\n\ndisplay.display(array2image(label2color(exsample_mask,palette)))\ndisplay.display(array2image(exsample_image))\n\ndisplay.display(array2image(0.5*exsample_image+0.5*(1-is_mask)*exsample_image+0.5*is_mask*color_mask))\n\nmasked_dict=OrderedDict()\n\nfor index, row in df_train.iterrows():\n    img_key='..\/input\/severstal-steel-defect-detection\/train_images\/'+row['ImageId']\n    if img_key not in masked_dict:\n        masked_dict[img_key]=row['mask']\n    else:\n        masked_dict[img_key]=masked_dict[img_key]+row['mask']\n\nprint(len(masked_dict))\n\"\"\"\n\u4f60\u5982\u679c\u8a66\u5716\u8981\u628a\u6240\u6709mask\u751f\u6210\u51fa\u4f86\uff0c\u5f88\u5feb\u4f60\u6703\u8d85\u904ekaggle\u8a18\u61b6\u9ad4\u4e0a\u9650\u9020\u6210notebook\u91cd\u555f\uff0c\u800c\u82e5\u662f\u4e00\u5f35\u4e00\u5f35\u5b58\u6a94\u4f86\u8abf\u7528\u770b\u8d77\u4f86\u53ef\u884c\uff0c\u53ef\u662f\u6703\u4f54\u7528\u4e0d\u5c11\n\"\"\"\nclass MyMaskDataset(MaskDataset):\n    def __init__(self, masks, class_names=None, symbol=\"mask\", **kwargs):\n        super().__init__(masks,class_names=class_names, symbol=symbol, object_type=ObjectType.label_mask, **kwargs)\n     \n    def __getitem__(self, index: int):\n        img_id = self.items[index]  # self.pop(index)\n        if img_id in masked_dict:\n            return masked_dict[img_id].astype(np.int64)\n        else:\n            return np.zeros((256,1600,3),dtype=np.int64)\n        \n#\u5982\u679c\u662fmask\u975e\u96f6\u5247ok\uff0c\u5426\u5247\u53ea\u670920%\u6a5f\u7387\u53d6\u7528\nsample_filter=lambda x:x[-1].max()>0 or random.random()>0.9\n\nds1=ImageDataset(list(masked_dict.keys()),symbol='image')\nds2=MyMaskDataset(list(masked_dict.keys()),symbol='mask')\n\n#\u8a2d\u5b9a\u8abf\u8272\u76e4\nfor i in range(5):\n    ds2.palette[i] =palette[i]\n\ndata_provider=DataProvider(traindata=Iterator(data=ds1,label=ds2,sample_filter=sample_filter))\ndata_provider.paired_transform_funcs=[\n    RandomTransformAffine(rotation_range=5, zoom_range=0.00, shift_range=0.00, shear_range=0.1, random_flip=0.15 ,border_mode='zero'),\n    RandomRescaleCrop((224,224),scale=(0.8,1.2))]\n\ndata_provider.image_transform_funcs=[\n                     AddNoise(0.01),\n                     RandomAdjustGamma(gamma_range=(0.6,1.5)),\n                     RandomAdjustContrast(value_range=(0.6, 1.5)),\n                     RandomAdjustHue(value_range=(-0.5, 0.5)),\n                     Normalize(127.5,127.5)]\n        \n\nimg_data,mask_data=data_provider.next()\nprint(mask_data.shape)\nprint(mask_data.max())\n\n\n%%time\ndata_provider.preview_images()\nfrom trident.models import efficientnet,deeplab\nbackbond_net=efficientnet.EfficientNetB0(pretrained=True,input_shape=(3,224,224))\nbackbond=backbond_net.model\nbackbond.trainable=False\ndeeplabv3=deeplab.DeeplabV3_plus(backbond,atrous_rates=(6,12,18,24),num_filters=256,classes=5)\ndeeplabv3.load_model('..\/input\/steeldefect\/Models\/deeplabv3.pth')\ndeeplabv3.summary()\n\nfrom trident.models import densenet\ntiramisu=densenet.DenseNetFcn(blocks=(4, 5, 6, 7, 8),input_shape=(3,224,224),growth_rate=16, initial_filters=32,num_classes=5)\ntiramisu.load_model('..\/input\/steeldefect\/Models\/tiramisu_1.pth')\ntiramisu.summary()\ndef draw_seg_image(training_context):\n    data_feed = training_context['data_feed']\n    data = training_context['train_data']\n    model = training_context['current_model']\n    output_data=data[data_feed['output']]\n    target_data=to_numpy(data['mask'])\n    input_data=to_numpy(data['image'])\n    output_data=np.argmax(to_numpy(output_data),1)\n    tile_images_list=[]\n    input_arr = []\n    target_arr=[]\n    output_arr=[]\n    for i in range(len(output_data)):\n        input_arr.append(image_backend_adaption(data_provider.reverse_image_transform(input_data[i])))\n        target_arr.append(label2color(target_data[i],palette))\n        output_arr.append(label2color(output_data[i],palette))\n    tile_images_list.append(input_arr)\n    tile_images_list.append(target_arr)\n    tile_images_list.append(output_arr)\n    fig = tile_rgb_images(*tile_images_list, save_path='Results\/segtile_image_{0}.png', imshow=True)\n    plt.close()\n        \n        \n    \ndeeplabv3.with_optimizer(optimizer=AdaBelief,lr=1e-3,betas=(0.9, 0.999),gradient_centralization='all')\\\n    .with_loss(DiceLoss(ignore_index=0),loss_weight=2)\\\n    .with_loss(CrossEntropyLoss(auto_balance=True)) \\\n    .with_loss(FocalLoss())\\\n    .with_metric(pixel_accuracy,name='pixel_accuracy',print_only=True)\\\n    .with_metric(iou,name='iou')\\\n    .with_regularizer('l2',reg_weight=1e-5)\\\n    .with_model_save_path('Models\/deeplabv3.pth') \\\n    .trigger_when(when='on_batch_end',frequency=50,action=draw_seg_image)\\\n    .with_automatic_mixed_precision_training()\n\ntiramisu.with_optimizer(optimizer=AdaBelief,lr=1e-3,betas=(0.9, 0.999),gradient_centralization='all')\\\n    .with_loss(DiceLoss(ignore_index=0),loss_weight=2)\\\n    .with_loss(CrossEntropyLoss(auto_balance=True)) \\\n    .with_loss(FocalLoss()) \\\n    .with_metric(pixel_accuracy,name='pixel_accuracy',print_only=True)\\\n    .with_metric(iou,name='iou')\\\n    .with_regularizer('l2',reg_weight=1e-5)\\\n    .with_model_save_path('Models\/tiramisu_1.pth') \\\n    .trigger_when(when='on_batch_end',frequency=50,action=draw_seg_image)\\\n    .with_automatic_mixed_precision_training()\n\nplan=TrainingPlan()\\\n    .add_training_item(deeplabv3,name='deeplabv3')\\\n    .add_training_item(tiramisu,name='tiramisu')\\\n    .with_data_loader(data_provider)\\\n    .repeat_epochs(30)\\\n    .with_batch_size(32)\\\n    .print_progress_scheduling(10,unit='batch')\\\n    .display_loss_metric_curve_scheduling(frequency=100,unit='batch',imshow=True)\\\n    .save_model_scheduling(20,unit='batch')\\\n\n\nplan.start_now()","meta":"{'source': 'AI4Code', 'id': '7429874b74dfea'}"}
{"id":"41480","text":"\"\"\"\n# Seoul Bike Rental\n\"\"\"\n\"\"\"\n#### Importing necessary libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import mean_squared_log_error\nfrom scipy import stats\n\"\"\"\n#### Loading datasets into notebook\n\"\"\"\ndir_path = '\/kaggle\/input\/seoul-bike-rental-ai-pro-iti'\n\ndf_train = pd.read_csv(os.path.join(dir_path, 'train.csv'))\ndf_test = pd.read_csv(os.path.join(dir_path, 'test.csv'))\n\ndf_test_ids = df_test['ID']\ndf_train = df_train.drop(columns = ['ID'])\ndf_test = df_test.drop(columns = ['ID'])\ndf_train.head()\ndf_test.head()\n\"\"\"\n#### Reviewing data\n\"\"\"\ndf_train.columns\ndf_train.dtypes\n\"\"\"\n### Fixing names of Temperature columns \n\n\"\"\"\ndf_train = df_train.rename(columns = {df_train.columns[3] : 'Temperature (C)', df_train.columns[7] : 'Dew point temperature (C)'})\ndf_test = df_test.rename(columns = {df_test.columns[2] : 'Temperature (C)', df_test.columns[6] : 'Dew point temperature (C)'})\n#df_train = df_train[df_train['Functioning Day'] != 'No']\n#df_train.drop(columns='Functioning Day', inplace=True)\ndf_train.columns\ndf_train.describe()\ndf_train.isna().sum()\n\"\"\"\nThere are no missing values, so..That's a good start\n\"\"\"\ndf_train.var().sort_values(ascending = False)\n\"\"\"\nWe should keep an eye for 'Snowfall' and 'Solar Radiation' columns, Cause with a variance this low they might be adding an insignificant amount of information \n\"\"\"\n# we should drop after visualization so this cell should be moved\n#df_temp = df_train.drop(columns=[\"Holiday\", \"Date\", \"Rainfall(mm)\", \"Wind speed (m\/s)\", Snowfall (cm)\"])\ndef add_working_hour_column(df):\n    df[\"working_hour\"] = 0\n    df[\"working_hour\"] = ((df[\"Hour\"] >= 5) & (df[\"Hour\"] <= 20)).astype(int)\n    return df\ndf_train['Month'] = pd.DatetimeIndex(df_train['Date']).month\ndf_train['Day'] = pd.DatetimeIndex(df_train['Date']).day\ndf_train['Weekday'] = pd.DatetimeIndex(df_train['Date']).weekday\ndf_test['Month'] = pd.DatetimeIndex(df_test['Date']).month\ndf_test['Day'] = pd.DatetimeIndex(df_test['Date']).day\ndf_test['Weekday'] = pd.DatetimeIndex(df_test['Date']).weekday\n#df_train[\"m_d_h\"] = df_train[\"Month\"] * 30 + df_train[\"Day\"] * 24 + df_train[\"Hour\"]\n#df_test[\"m_d_h\"] = df_test[\"Month\"] * 30 + df_test[\"Day\"] * 24 + df_test[\"Hour\"]\ndf_train.head()\ndf_train=add_working_hour_column(df_train)\ndf_test=add_working_hour_column(df_test)\n\"\"\"\n# Some EDA \n\"\"\"\n\"\"\"\n#### We'll plot the scatter plot for some selected columns\n\"\"\"\n# feature=['y', 'Solar Radiation (MJ\/m2)']\n# # IQR\n# Q1 = np.percentile(df_train[feature], 25, \n#                    interpolation = 'midpoint',axis=0) \n# print(Q1) \n# Q3 = np.percentile(df_train[feature], 75,\n#                    interpolation = 'midpoint',axis=0) \n# print(Q3) \n# IQR = Q3 - Q1 \n  \n# print(\"Old Shape: \", df_train.shape) \n  \n# # Upper bound\n# upper = np.where(df_train[feature] >= (Q3+1.5*IQR))\n# # Lower bound\n# lower = np.where(df_train[feature] <= (Q1-1.5*IQR))\n  \n# #Removing the Outliers\n# df_train.drop(upper[0], inplace = True, axis=0)\n# df_train.drop(lower[0], inplace = True, axis=0)\n  \n# print(\"New Shape: \", df_train.shape)\n\"\"\"\n# **Encoding Categorical Columns**\n\"\"\"\ndef get_temp_range(temp_val):\n    counter=1\n    for i in range(-20,41,10):\n        if temp_val <= i :\n            return counter\n        counter+=1\n    return 0\n# df_train[\"temp_range\"]=df_train['Temperature (C)'].apply(get_temp_range)\n# df_test[\"temp_range\"]=df_test['Temperature (C)'].apply(get_temp_range)\ndf_train.head()\ndef encode_categroical_features(df):\n    df[\"Seasons\"] = df[\"Seasons\"].astype(\"category\").cat.codes\n    df[\"Functioning Day\"] = df[\"Functioning Day\"].astype(\"category\").cat.codes\n    df[\"Holiday\"] = df[\"Holiday\"].astype(\"category\").cat.codes\n    return df\n    \ndef pca_3_components(df, feature1, feature2, feature3,  new_col_name,df_test):\n    to_be_transformed = df[[feature1, feature2, feature3]]\n    to_be_transformed_test = df_test[[feature1, feature2, feature3]]\n    pca = PCA(n_components=1)\n    transformed_components = pca.fit_transform(to_be_transformed)\n    df[new_col_name] = transformed_components\n    df_test[new_col_name]=pca.transform(to_be_transformed_test)\n    df.drop(columns=[feature1, feature2, feature3],inplace=True)\n    df_test.drop(columns=[feature1, feature2, feature3],inplace=True)\n    return df\ndef filter_functioning_day(df):\n    df_columns=df.columns\n    for col in df_columns:\n        df[col]=df[col]*df['Functioning Day']\n    return df\ndef replace_outlaires(df):\n    for feature in df.drop(columns=[\"Hour\", \"Month\", \"Day\",'Functioning Day','Seasons']).columns:\n        # IQR\n        Q1 = np.percentile(df[feature], 25, \n                           interpolation = 'midpoint') \n        Q3 = np.percentile(df[feature], 75,\n                           interpolation = 'midpoint') \n        IQR = Q3 - Q1 \n\n        upperL = Q3 + 1.5*IQR\n        lowerL = Q1 - 1.5*IQR\n        df[feature] = df[feature].map(lambda val: (val if val < upperL else upperL))\n        df[feature] = df[feature].map(lambda val: (val if val > lowerL else lowerL))\n\n    print(\"New Shape: \", df.shape)\n    return df\n def pre_processing(df):\n    columns_to_drop=['Date', 'Snowfall (cm)', 'Holiday', 'Wind speed (m\/s)']\n    df=encode_categroical_features(df)  \n    df=df.drop(columns=columns_to_drop)\n#     _ = pca_3_components(df, \"Day\", \"Month\", \"m_d_h\", \"D_M\",df_test)\n    #df=filter_functioning_day(df)\n    return df\n\"\"\"\n# **Now let's see heat map to check for corrolation**\n\"\"\"\n#corr_mat = df_train.corr()\n#fig = plt.figure(figsize = (14, 14))\n#sns.heatmap(corr_mat, annot= True)\n#plt.show()\n\"\"\"\n* We can see strong corrolation between temp and dew point temp, so we can drop dew point\n* Snowfall, Rainfall, Holiday and FunctioningDay can be droped\n\"\"\"\nfrom sklearn.decomposition import PCA\ndef pca_2_components(df, feature1, feature2,  new_col_name , df_test):\n    to_be_transformed = df[[feature1, feature2]]\n    to_be_transformed_test = df_test[[feature1, feature2]]\n    pca = PCA(n_components=1)\n    transformed_components = pca.fit_transform(to_be_transformed)\n    df[new_col_name] = transformed_components\n    df_test[new_col_name]= pca.transform(to_be_transformed_test)\n    df.drop(columns=[feature1,feature2],inplace=True)\n    df_test.drop(columns=[feature1,feature2],inplace=True)\n    return df\npca_2_components(df_train, 'Dew point temperature (C)', 'Temperature (C)', 'temp_pca',df_test)\n#pca_2_components(df_train, 'Solar Radiation (MJ\/m2)', 'working_hour', 'solar_work_pca',df_test)\ncolumns_to_drop_aftePCA=['Dew point temperature (C)', 'Temperature (C)']\ndf_temp =pre_processing(df_train)\ndf_temp=replace_outlaires(df_temp)\n# corr_mat = df_temp.corr()\n# fig = plt.figure(figsize = (14, 14))\n# sns.heatmap(corr_mat, annot= True)\n# plt.show()\n\"\"\"\n# # **Model**\n\"\"\"\n\"\"\"\n### Functioning Day filteration\n\"\"\"\n\ndf_temp[df_temp['Functioning Day']==0]\n#df_temp['y'] = np.log1p(df_temp['y'])\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\n\nX_train, X_test, y_train, y_test = train_test_split(df_temp.drop(columns=['y', 'Month', 'Day']), df_temp[\"y\"], test_size=0.005, random_state=42)\ndf_temp.describe()\n\"\"\"\n### Apply Feature Scaling\n\"\"\"\n\n# scaler=MinMaxScaler()\n# X_train=scaler.fit_transform(X_train)\n# X_test=scaler.transform(X_test)\n\nscaler=StandardScaler()\nX_train=scaler.fit_transform(X_train)\nX_test=scaler.transform(X_test)\n\n#print(pd.DataFrame(X_train).describe())\n'''\n\nfrom sklearn.ensemble import ExtraTreesRegressor\n\nregr = ExtraTreesRegressor(random_state=0)\nregr.fit(X_train, y_train)\n\ny_pred=regr.predict(X_test)\n\nprint(regr.score(X_test, y_test))\n\ny_test, y_pred = np.expm1(y_test), np.expm1(y_pred)\nrmsle = np.sqrt(mean_squared_log_error(y_test, y_pred))\nprint(rmsle)\n'''\n#len(np.where(y_pred < y_test)[0])\n\"\"\"\n# **XGB**\n\"\"\"\nfrom xgboost import XGBRegressor\nXGBModel = XGBRegressor(objective=\"reg:tweedie\", tweedie_variance_power=1.6, gamma=2, max_depth=6, subsample=.7, reg_alpha=0.15, reg_lambda=1, learning_rate= 0.15)\nX_train=scaler.fit_transform(X_train)\nX_test=scaler.transform(X_test)\nXGBModel = XGBModel.fit(X_train, y_train, verbose=False)\nprint(XGBModel.score(X_test, y_test))\ny_test\ny_pred = XGBModel.predict(X_test)\nrmsle = np.sqrt(mean_squared_log_error(y_test, y_pred))\nprint(rmsle)\nlen(np.where(y_pred < y_test)[0])\nprint(df_temp[df_temp[\"y\"] < 0])\nsns.histplot(df_temp[\"y\"])\nsns.histplot(y_train, bins=20)\nsns.histplot(y_test, bins=20)\nsns.histplot(y_pred, bins=20)\nsns.scatterplot(y_pred, y_test)\nsns.histplot(y_pred-y_test)\nprint(np.sum(np.abs(y_pred - y_test) > 100))\nlen(y_test)\ndf_test.head()\n\ndf_test=pre_processing(df_test)\ndf_test.head()\ndf_test[df_test['Functioning Day']==0]\nX_test = df_test.drop(columns=['Month','Day'])\nX_test=scaler.transform(X_test)\n# You should update\/remove the next line once you change the features used for training\ny_test_predicted = XGBModel.predict(X_test)\ndf_test['y'] = y_test_predicted\ndf_test['ID']=df_test_ids\ndf_test.head()\ndf_test[['ID', 'y']].to_csv('\/kaggle\/working\/submission.csv', index=False)\nX_test = df_test.drop(columns=['Month','Day'])\nX_test.head()\ndf_test.describe()\ndf_test[df_test['Functioning Day']==0]","meta":"{'source': 'AI4Code', 'id': '4c76d86c604725'}"}
{"id":"24919","text":"\"\"\"\n# Data Analysis of 911 Calls - Capstone Project\n\nThe 911 system was designed to provide a universal, easy-to-remember number for people to reach police, fire or emergency medical assistance from any phone in any location, without having to look up specific phone numbers. Today, people communicate in ways that the designers of the original 911 system could not have envisioned: wireless phones, text and video messages, social media, Internet Protocol (IP)-enabled devices, and more.\n\nThe National 911 Program works with States, technology providers, public safety officials and 911 professionals to ensure a smooth transition to an updated 911 system that takes advantage of new communications technologies. It also creates and shares a variety of resources and tools to help 911 systems.\n\nCreated by Congress in 2004 as the 911 Implementation and Coordination Office (ICO), the National 911 Program is housed within the National Highway Traffic Safety Administration at the U.S. Department of Transportation and is a joint program with the National Telecommunication and Information Administration in the Department of Commerce\n\nThis is a capstone project for the udemy course [\"Python for Data Science and Machine Learning Bootcamp\"\n](https:\/\/www.udemy.com\/course\/python-for-data-science-and-machine-learning-bootcamp\/) [](http:\/\/)\n\nFor this capstone project we will be analyzing some 911 call data from [Kaggle](https:\/\/www.kaggle.com\/mchirico\/montcoalert). The data contains the following fields:\n\n* lat : String variable, Latitude\n* lng: String variable, Longitude\n* desc: String variable, Description of the Emergency Call\n* zip: String variable, Zipcode\n* title: String variable, Title\n* timeStamp: String variable, YYYY-MM-DD HH:MM:SS\n* twp: String variable, Township\n* addr: String variable, Address\n* e: String variable, Dummy variable (always 1)\n\n\n\"\"\"\n# Importing numpy and pandas libraries\n\nimport numpy as np\nimport pandas as pd\n#Importing Visualization libraries\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n#Read in the csv file from Kaggle and create a dataframe called df\n\ndf=pd.read_csv('..\/input\/montcoalert\/911.csv')\n#Check the info() of the df\n\ndf.info()\n#Read in the csv file as a dataframe called df\n\ndf.head()\n\"\"\"\n# Creating new features\n\nIn the titles column there are \"Reasons\/Departments\" specified before the title code. These are EMS, Fire, and Traffic. Now using .apply() with a custom lambda expression we will create a new column called \"Reason\" that contains this string value.**\n\n*For example, if the title column value is EMS: BACK PAINS\/INJURY , the Reason column value would be EMS. *\n\"\"\"\ndf['Reason'] = df['title'].apply(lambda title: title.split(':')[0])\n#What is the most common Reason for a 911 call based off of this new column?\n\ndf['Reason'].value_counts()\n#Now using seaborn to create a countplot of 911 calls by Reason.\n\nsns.countplot(x='Reason',data=df,palette='coolwarm')\n#Now let us begin to focus on time information. What is the data type of the objects in the timeStamp column?\n\ntype(df['timeStamp'].iloc[0])\n#Use [pd.to_datetime] to convert the column from strings to DateTime objects\n\ndf['timeStamp'] = pd.to_datetime(df['timeStamp'])\n# Since the timestamp column are actually DateTime objects, we will use .apply() to create 3 new columns called Hour, Month, and Day of Week. \n\ndf['Hour'] = df['timeStamp'].apply(lambda time: time.hour)\ndf['Month'] = df['timeStamp'].apply(lambda time: time.month)\ndf['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)\n#Notice how the Day of Week is an integer 0-6. Use the .map() with this dictionary to map the actual string names to the day of the week:\n\ndmap = {0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'}\n#Now use seaborn to create a countplot of the Day of Week column with the hue based off of the Reason column.\n\nsns.countplot(x='Day of Week',data=df,hue='Reason',palette='coolwarm')\n\n# To relocate the legend\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n#Now use seaborn to create a countplot of the Month column.\n\nsns.countplot(x='Month',data=df,hue='Reason',palette='coolwarm')\n\n# To relocate the legend\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n#Create a new column called 'Date' that contains the date from the timeStamp column. You'll need to use apply along with the .date() method\n\ndf['Date']=df['timeStamp'].apply(lambda t: t.date())\n#Now groupby this Date column with the count() aggregate and create a plot of counts of 911 calls and recreate this plot representing a Reason for the 911 call\n\ndf[df['Reason']=='Traffic'].groupby('Date').count()['twp'].plot()\nplt.title('Traffic')\nplt.tight_layout()\n#Now recreate this plot but create 3 separate plots with each plot representing a Reason for the 911 call\n\ndf[df['Reason']=='Fire'].groupby('Date').count()['twp'].plot()\nplt.title('Fire')\nplt.tight_layout()\n#Now recreate this plot but create 3 separate plots with each plot representing a Reason for the 911 call\n\ndf[df['Reason']=='EMS'].groupby('Date').count()['twp'].plot()\nplt.title('EMS')\nplt.tight_layout()\n# Now let's move on to creating heatmaps with seaborn and our data. We'll first need to restructure the dataframe so that the columns become the Hours and the Index becomes the Day of the Week. \n#There are lots of ways to do this, but I would recommend trying to combine groupby with an unstack method. \n\ndayHour = df.groupby(by=['Day of Week','Hour']).count()['Reason'].unstack()\ndayHour.head()\n#Now create a HeatMap using this new DataFrame.\n\nplt.figure(figsize=(12,6))\nsns.heatmap(dayHour,cmap='coolwarm')\n#Now create a clustermap using this DataFrame\n\nsns.clustermap(dayHour,cmap='coolwarm')\n#Now repeat these same plots and operations, for a DataFrame that shows the Month as the column\n\ndayMonth = df.groupby(by=['Day of Week','Month']).count()['Reason'].unstack()\ndayMonth.head()\nplt.figure(figsize=(12,6))\nsns.heatmap(dayMonth,cmap='coolwarm')\nsns.clustermap(dayMonth,cmap='coolwarm')","meta":"{'source': 'AI4Code', 'id': '2dd4277f58f3c3'}"}
{"id":"98549","text":"\"\"\"\n# some of the most needed code snippets \nI'm will put some usefull and most repetitive code snippets in this notebook.<br>\nfeel free to fork this notebook and complete it:)\n\"\"\"\nimport numpy as np \nimport pandas as pd\n\n\n# Input data files are available in the \"..\/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\"\"\"\n<font color='red'>you can skip this part of the notebook. it's only for creating some dummy data<\/font>\n\"\"\"\n# creating a sample csv file \nsize = 150\ny = np.random.choice(['L1', 'L2', 'L3'], size=size, p=[0.1, 0.6, 0.3]) # labels for our dummy data\ncat1 = np.random.choice(['a','b','c','d', np.nan], size=size, p=[0.2,0.1,0.2,0.45, 0.05])\ncat2 = np.random.choice([0,1, np.nan], size=size, p=[0.5,0.45, 0.05])\n\ndf = pd.DataFrame({'x1': np.random.randn(size), 'x2' : np.random.randn(size),'cat1': cat1, 'cat2':cat2, 'y': y})\n\ndf.to_csv('sample.csv', index=False)\n\"\"\"\n# Reading Dataset\n\"\"\"\n\"\"\"\n### CSV File\n\"\"\"\ncsv_path = 'sample.csv'\ndf = pd.read_csv(csv_path)\ndf.head()\n\"\"\"\n### opening Image Files from Zip\n\nnot recommended for large image datasets\n\"\"\"\nzip_file_path = 'zip.zip' # or 'your_npz.npz'\n# uncomment the line below\n# images = np.load(zip_file_path) \n\"\"\"\n### Extracting Zip file\n\"\"\"\nimport zipfile\n# uncomment the folowing lines\n# with zipfile.ZipFile(zip_file_path) as z:\n#     z.extractall()\n\"\"\"\n# Visualization\n\"\"\"\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\n# set the figure sizes\nplt.figure(figsize=(10,5))\nsns.set(rc={'figure.figsize':(10,5)})\n\"\"\"\n### histogram\n\"\"\"\nsns.distplot(df['x1'])\n\"\"\"\n### bar chart\nfor label y\n\"\"\"\nsns.countplot(df.y)\n\"\"\"\n### boxplot\n\"\"\"\nsns.boxplot(df.x2, df.y)\n\"\"\"\n### pie chart\n\"\"\"\nlabels, counts = np.unique(df.y,return_counts=True)\nplt.pie(counts, labels=labels)\n\"\"\"\n# Preprocessing\n\"\"\"\nfrom sklearn import preprocessing\n\"\"\"\n## Handling <font color='blue'> Nan<\/font> Vaules\n\"\"\"\nfrom sklearn.impute import SimpleImputer\n# here I changed the missing value to 'nan' but most of the times default is good\nimputer = SimpleImputer(missing_values=np.nan, strategy='most_frequent') \ndf[['cat1', 'cat2']] = imputer.fit_transform(df[['cat1','cat2']])\n\"\"\"\n<font color='red'>Note: if your feature is 1-D array you shall use reshape(1,-1) before using it with imputer<\/font>\n\"\"\"\n\"\"\"\n## Normalizing\n\"\"\"\n\"\"\"\n### MinMax\n\"\"\"\nminmax = preprocessing.MinMaxScaler((0,1))\ndf[['x1','x2']] = minmax.fit_transform(df[['x1','x2']])\ndf.head()\n\"\"\"\n### Label Encoder\n\"\"\"\ncategorical_features = df.select_dtypes('object').columns\n\n\nle = preprocessing.LabelEncoder()\nfor col in categorical_features:\n    df[col] = le.fit_transform(df[col])\n    \ndf.head()\n\"\"\"\n### One Hot Encoder\n\"\"\"\n# adding another dummy categorical feature\ngender = np.random.choice(['Male', 'Female', 'another'], size=size, p=[0.4, 0.4, 0.2])\ndf['gender'] = gender\nfrom sklearn.preprocessing import OneHotEncoder\n\nohe = OneHotEncoder(handle_unknown='ignore', sparse=False)\n\n\noht = pd.DataFrame(ohe.fit_transform(df[['gender']]))\n\noht.index = df.index\n\nnum_df = df.drop(['gender'], axis=1)\n\ndf = pd.concat([num_df, oht],axis=1)\n\"\"\"\n## Train-Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ny = df.y\nX = df.drop(['y'], axis=1)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nprint('train shape: {}\\ntest shape: {}'.format(X_train.shape, X_test.shape))\n\"\"\"\n# Baseline Models\n\"\"\"\n# using mean squared error\nfrom sklearn.metrics import mean_squared_error\n\ndef calculate_error(y_pred, y_true):\n    print(mean_squared_error(y_pred, y_true))\n\"\"\"\n## Linear Models\n\"\"\"\n\"\"\"\n### RidgeClassifier\n\"\"\"\nfrom sklearn.linear_model import RidgeClassifier\n\nmodel = RidgeClassifier(random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n### SGDClassifier\n\"\"\"\nfrom sklearn.linear_model import SGDClassifier\n\nmodel = SGDClassifier(random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n## Ensemble\n\"\"\"\n\"\"\"\n### Random forrest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier(n_estimators=100, random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n### AdaBoost\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\n\nmodel = AdaBoostClassifier(random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n### GradientBoosting\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nmodel = GradientBoostingClassifier(random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n## Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\n\nmodel = DecisionTreeClassifier(max_leaf_nodes=200, random_state=0)\nmodel.fit(X_train, y_train)\npreds = model.predict(X_test)\ncalculate_error(preds, y_test)\n\"\"\"\n# create submission csv\n\"\"\"\ndef save_submission(test_path, preds, path='submission.csv'):    \n    '''\n    test_path: test csv file\n    preds    : predicted label from your model\n    path     : where you want to save the csv file\n    '''\n    test_df = pd.read_csv(test_path)\n    test_df['label_column'] = preds\n    test_df.to_csv(path, index=False)","meta":"{'source': 'AI4Code', 'id': 'b50d92457e6e78'}"}
{"id":"85352","text":"\"\"\"\n\u53ef\u8996\u5316\u3057\u305f\u7d50\u679c\u306b\u5bfe\u3057\u3066\u3001\uff12\u6b21\u5143\u5ea7\u6a19\u3092\u3082\u3068\u306b\u30cf\u30f3\u30c9\u3067\u5404\u30a2\u30af\u30b7\u30e7\u30f3\u30b7\u30fc\u30af\u30a8\u30f3\u30b9\u3092\u5f15\u304d\u5f53\u3066\u308b\u3053\u3068\u3082\u53ef\u80fd\u3067\u3059\u304c\u3001\u3053\u3053\u306f K-means \u3092\u5229\u7528\u3057\u3066 ML \u3089\u3057\u304f\u5206\u985e\u3057\u3066\u307f\u307e\u3057\u305f\u3002\n\n\u3055\u3089\u306b K-means \u306e\u7d50\u679c\u3092\u6c7a\u5b9a\u6728\u306b\u639b\u3051\u3066\u3001\u305d\u306e\u5206\u985e\u304c\u884c\u308f\u308c\u305f\u8981\u56e0\u3092\u8abf\u3079\u307e\u3057\u305f\u3002\u6c7a\u5b9a\u6728\u306e\u7d50\u679c\u306f\u3001output \u306b\u30bb\u30fc\u30d6\u3057\u305f\u30ab\u30e9\u30fc\u306e PNG\u30a4\u30e1\u30fc\u30b8\u304c\u898b\u6613\u304f\u306a\u3063\u3066\u3044\u307e\u3059\u3002\uff08\u4e0b\u306e\u65b9\u306b\u3042\u308a\u307e\u3059\uff09\n\u6c7a\u5b9a\u6728\u306e\u7d50\u679c\u304b\u3089\u3001imu(\u59ff\u52e2)\u306b\u95a2\u4fc2\u3059\u308b\u7279\u5fb4\u91cf\u304c\u52b9\u3044\u3066\u3044\u308b\u3088\u3046\u306b\u8aad\u307f\u53d6\u308c\u307e\u3059\u3002\n\"\"\"\n!pip install umap-learn\n!pip install pydotplus\n# \u30e9\u30a4\u30d6\u30e9\u30ea\u306eimport\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nplt.style.use('ggplot')\n%matplotlib inline\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\n#from sklearn.cluster import DBSCAN\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\nimport pydotplus\n#import os\n#for dirname, _, filenames in os.walk('\/kaggle\/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\ndf_train = pd.read_csv('\/kaggle\/input\/data-science-spring-osaka-hard-mode\/train.csv')\ndf_test = pd.read_csv('\/kaggle\/input\/data-science-spring-osaka-hard-mode\/test_hard.csv')\ndf_action = pd.read_csv('\/kaggle\/input\/data-science-spring-osaka-hard-mode\/actions_hard.csv')\ndf_train.head(2)\ndf_test.head(2)\ndf_action.head(10)\ndf = pd.read_csv('\/kaggle\/input\/data-science-spring-osaka-hard-mode\/test_hard\/test_hard\/0000.csv')\ndf.tail(2)\nscaler = MinMaxScaler()\ndf.iloc[:] = scaler.fit_transform(df)\ndf.tail(2)\nDataFrame(df.std()).T\ndef add_std_as_feature(df):\n    df_temp = DataFrame()\n    for path in df.file_path:\n        df_sensor = pd.read_csv('\/kaggle\/input\/data-science-spring-osaka-hard-mode\/test_hard\/'+path)\n        df_sensor = DataFrame(df_sensor.std()).T\n        df_temp = pd.concat([df_temp, df_sensor])\n    df_temp.columns = [col+'_std' for col in df_temp.columns]\n    df_temp.index = df.index\n    df = pd.concat([df, df_temp], axis=1)\n    return df\n#df_train = add_std_as_feature(df_train)\ndf_test = add_std_as_feature(df_test)\nX_test = df_test\nX_test.drop(['file_path'],axis=1,inplace=True)\n#df_train.head(2)\nX_test.tail(2)\nfrom sklearn.preprocessing import StandardScaler\nimport umap\n\nreducer = umap.UMAP(random_state=42)\n\ny_test = reducer.fit_transform(X_test)\n\nplt.scatter(y_test[:, 0], y_test[:, 1])\ny_test.shape\n\"\"\"\n***K-means \u3092\u4f7f\u3063\u3066\u3001\uff18\u3064\u306e\u30af\u30e9\u30b9\u30bf\u30fc\u306b\u5206\u985e***\n\"\"\"\nkmeans = MiniBatchKMeans(n_clusters=8, max_iter=300)\nkmeans_y_test = kmeans.fit_predict(y_test)\ncolor=cm.brg(np.linspace(0,1,np.max(kmeans_y_test) - np.min(kmeans_y_test)+1))\nfor i in range(np.min(kmeans_y_test), np.max(kmeans_y_test)+1):\n    plt.plot(y_test[kmeans_y_test == i][:,0],\n             y_test[kmeans_y_test == i][:,1],\n             \".\",\n             color=color[i]\n             )\n    plt.text(y_test[kmeans_y_test == i][:,0][0],\n             y_test[kmeans_y_test == i][:,1][0],\n             str(i), color=\"black\", size=16\n             )\n\"\"\"\n\u6ce8\uff1a\u30b0\u30e9\u30d5\u306e\u756a\u53f7\u306f\u3001\u30a2\u30af\u30b7\u30e7\u30f3\u30b7\u30fc\u30af\u30a8\u30f3\u30b9No.\u3068\u306f\u4e00\u81f4\u3057\u307e\u305b\u3093\u3002\n\"\"\"\nkmeans_y_test\n\"\"\"\n***\u6c7a\u5b9a\u6728\u3092\u4f7f\u3063\u3066\u30af\u30e9\u30b9\u30bf\u30fc\u306e\u7279\u5fb4\u3092\u8abf\u67fb***\n\"\"\"\nclf = DecisionTreeClassifier( random_state = 0 )\nclf.classes_ = np.max(kmeans_y_test) - np.min(kmeans_y_test) + 1\nclf.fit(X_test, kmeans_y_test)\ndot_data = export_graphviz(clf,\n                feature_names=X_test.columns, \n                class_names=['0','1','2','3','4','5','6','7'], \n                filled=True, \n                rounded=True)\n\ngraph = pydotplus.graph_from_dot_data( dot_data )\n\ntree.plot_tree(clf);\ngraph.write_png( 'hardmode_umap_std.dot.png' )\n\"\"\"\n\u30a2\u30a6\u30c8\u30d7\u30c3\u30c8\u3057\u305f\u30ab\u30e9\u30fc\u306e PNG \u30a4\u30e1\u30fc\u30b8\u306e\u65b9\u304c\u898b\u6613\u3044\u3000\uff08\u66f4\u306b\u4e0b\u306e\u65b9\u306b\u3042\u308a\u307e\u3059\uff09\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9ca088e60b4b56'}"}
{"id":"56089","text":"\"\"\"\n<h1><center><font size=\"6\">RSNA Pneumonia Detection EDA<\/font><\/center><\/h1>\n\n<center><img src=\"https:\/\/www.rsna.org\/images\/rsna\/home\/line_r.svg\" width=\"500\"><\/img><\/center>\n\n# <a id='0'>Content<\/a>\n\n- <a href='#1'>Introduction<\/a>  \n- <a href='#2'>Prepare the data analysis<\/a>  \n    -<a href='#21'>Load packages<\/a>  \n     -<a href='#21'>Load the data<\/a>  \n- <a href='#3'>Data exploration<\/a>   \n    -<a href='#31'>Missing data<\/a>  \n    -<a href='#32'>Merge train and class info data<\/a>  \n    -<a href='#33'>Explore DICOM data<\/a>  \n    -<a href='#34'>Add meta information from DICOM data<\/a>  \n    -<a href='#35'>Modality<\/a>  \n    -<a href='#36'>Body Part Examined<\/a>  \n    -<a href='#37'>View Position<\/a>  \n    -<a href='#38'>Conversion Type<\/a>  \n    -<a href='#39'>Rows and Columns<\/a>  \n    -<a href='#310'>Patient Age<\/a>  \n    -<a href='#311'>Patient Sex<\/a>  \n- <a href='#4'>Conclusions<\/a>    \n- <a href='#5'>References<\/a>    \n\n\"\"\"\nfrom datetime import datetime\ndt_string = datetime.now().strftime(\"%d\/%m\/%Y %H:%M:%S\")\nprint(f\"Updated {dt_string} (GMT)\")\n\"\"\"\n# <a id=\"1\">Introduction<\/a>  \n\nThis Kernel objective is to explore the dataset for RSNA Pneumonia Detection Challenge.   \n\nWe start by exploring the DICOM data, we extract then meta information from the DICOM files and visualize the various features of the DICOM images, grouped by age, sex.\n\nThe Kernel was modified to work with **stage_2** data instead of **stage_1** data.\n\n\n\"\"\"\n\"\"\"\n# <a id=\"2\">Prepare the data analysis<\/a>  \n\n## <a id=\"21\">Load packages<\/a>\n\n\"\"\"\nimport pandas as pd \nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm_notebook\nfrom matplotlib.patches import Rectangle\nimport seaborn as sns\nimport pydicom as dcm\n%matplotlib inline \nIS_LOCAL = False\nimport os\nif(IS_LOCAL):\n    PATH=\"..\/input\/rsna-pneumonia-detection-challenge\"\nelse:\n    PATH=\"..\/input\/\"\nprint(os.listdir(PATH))\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n\n## <a id=\"22\">Load the data<\/a>\n\nLet's load the tabular data. There are two files:\n* Detailed class info;  \n* Train labels.\n\"\"\"\nclass_info_df = pd.read_csv(PATH+'\/stage_2_detailed_class_info.csv')\ntrain_labels_df = pd.read_csv(PATH+'\/stage_2_train_labels.csv')                         \nprint(f\"Detailed class info -  rows: {class_info_df.shape[0]}, columns: {class_info_df.shape[1]}\")\nprint(f\"Train labels -  rows: {train_labels_df.shape[0]}, columns: {train_labels_df.shape[1]}\")\n\"\"\"\nLet's explore the two loaded files. We will take out a 5 rows samples from each dataset.\n\"\"\"\nclass_info_df.sample(10)\ntrain_labels_df.sample(10)\n\"\"\"\nIn **class detailed info** dataset are given the detailed information about the type of positive or negative class associated with a certain patient.  \n\nIn **train labels** dataset are given the patient ID and the window (x min, y min, width and height of the) containing evidence of pneumonia.\n\"\"\"\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n# <a id=\"1\">Data exploration<\/a>  \n\nLet's explore the data further.\n\"\"\"\n\"\"\"\n## <a id=\"31\">Missing data<\/a>\n\nLet's check missing information in the two datasets. \n\"\"\"\ndef missing_data(data):\n    total = data.isnull().sum().sort_values(ascending = False)\n    percent = (data.isnull().sum()\/data.isnull().count()*100).sort_values(ascending = False)\n    return np.transpose(pd.concat([total, percent], axis=1, keys=['Total', 'Percent']))\nmissing_data(train_labels_df)\nmissing_data(class_info_df)\n\"\"\"\nThe percent missing for x,y, height and width in train labels represents the percent of the target **0** (not **Lung opacity**).\n\nLet's check the class distribution from class detailed info.\n\"\"\"\nf, ax = plt.subplots(1,1, figsize=(6,4))\ntotal = float(len(class_info_df))\nsns.countplot(class_info_df['class'],order = class_info_df['class'].value_counts().index, palette='Set3')\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}%'.format(100*height\/total),\n            ha=\"center\") \nplt.show()\n\"\"\"\nLet's look into more details to the classes.\n\"\"\"\ndef get_feature_distribution(data, feature):\n    # Get the count for each label\n    label_counts = data[feature].value_counts()\n\n    # Get total number of samples\n    total_samples = len(data)\n\n    # Count the number of items in each class\n    print(\"Feature: {}\".format(feature))\n    for i in range(len(label_counts)):\n        label = label_counts.index[i]\n        count = label_counts.values[i]\n        percent = int((count \/ total_samples) * 10000) \/ 100\n        print(\"{:<30s}:   {} or {}%\".format(label, count, percent))\n\nget_feature_distribution(class_info_df, 'class')\n\"\"\"\n**No Lung Opacity \/ Not Normal** and **Normal** have together the same percent (**69.077%**) as the percent of missing values for target window in class details information.   \n\nIn the train set, the percent of data with value for **Target = 1** is therefore **30.92%**.   \n\n\"\"\"\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n## <a id=\"32\">Merge train and class detail info data<\/a>   \n\nLet's merge now the two datasets, using Patient ID as the merge criteria.\n\"\"\"\ntrain_class_df = train_labels_df.merge(class_info_df, left_on='patientId', right_on='patientId', how='inner')\ntrain_class_df.sample(5)\n\"\"\"\n### Target and class  \n\nLet's plot the number of examinations for each class detected, grouped by Target value.\n\"\"\"\nfig, ax = plt.subplots(nrows=1,figsize=(12,6))\ntmp = train_class_df.groupby('Target')['class'].value_counts()\ndf = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\nsns.barplot(ax=ax,x = 'Target', y='Exams',hue='class',data=df, palette='Set3')\nplt.title(\"Chest exams class and Target\")\nplt.show()\n\"\"\"\nAll chest examinations with`Target` = **1** (pathology detected) associated with `class`:  **Lung Opacity**.    \n\nThe chest examinations with `Target` = **0** (no pathology detected) are either of `class`: **Normal** or `class`: **No Lung Opacity \/ Not Normal**.\n\"\"\"\n\"\"\"\n### Detected Lung Opacity window   \n\nFor the class **Lung Opacity**, corresponding to values of **Target = 1**, we plot the density of **x**, **y**, **width** and **height**.\n\n\n\"\"\"\ntarget1 = train_class_df[train_class_df['Target']==1]\nsns.set_style('whitegrid')\nplt.figure()\nfig, ax = plt.subplots(2,2,figsize=(12,12))\nsns.distplot(target1['x'],kde=True,bins=50, color=\"red\", ax=ax[0,0])\nsns.distplot(target1['y'],kde=True,bins=50, color=\"blue\", ax=ax[0,1])\nsns.distplot(target1['width'],kde=True,bins=50, color=\"green\", ax=ax[1,0])\nsns.distplot(target1['height'],kde=True,bins=50, color=\"magenta\", ax=ax[1,1])\nlocs, labels = plt.xticks()\nplt.tick_params(axis='both', which='major', labelsize=12)\nplt.show()\n\"\"\"\nWe can plot also the center of the rectangles points in the plane x0y.   The centers of the rectangles are the points $$x_c = x + \\frac{width}{2}$$ and $$y_c = y + \\frac{height}{2}$$.\n\nWe will show a sample of center points superposed with the corresponding sample of the rectangles.\nThe rectangles are created using the method described in Kevin's Kernel <a href=\"#4\">[1]<\/a>.\n\"\"\"\nfig, ax = plt.subplots(1,1,figsize=(7,7))\ntarget_sample = target1.sample(2000)\ntarget_sample['xc'] = target_sample['x'] + target_sample['width'] \/ 2\ntarget_sample['yc'] = target_sample['y'] + target_sample['height'] \/ 2\nplt.title(\"Centers of Lung Opacity rectangles (brown) over rectangles (yellow)\\nSample size: 2000\")\ntarget_sample.plot.scatter(x='xc', y='yc', xlim=(0,1024), ylim=(0,1024), ax=ax, alpha=0.8, marker=\".\", color=\"brown\")\nfor i, crt_sample in target_sample.iterrows():\n    ax.add_patch(Rectangle(xy=(crt_sample['x'], crt_sample['y']),\n                width=crt_sample['width'],height=crt_sample['height'],alpha=3.5e-3, color=\"yellow\"))\nplt.show()\n\"\"\"\nWe follow with the exploration of the DICOM data.\n\"\"\"\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n## <a id=\"33\">Explore DICOM data<\/a>  \n\nLet's read now the DICOM data in the train set. The image path is as following:\n\"\"\"\nimage_sample_path = os.listdir(PATH+'\/stage_2_train_images')[:5]\nprint(image_sample_path)\n\"\"\"\nThe files names are the patients IDs.    \nLet's check how many images are in the train and test folders.\n\"\"\"\nimage_train_path = os.listdir(PATH+'\/stage_2_train_images')\nimage_test_path = os.listdir(PATH+'\/stage_2_test_images')\nprint(\"Number of images in train set:\", len(image_train_path),\"\\nNumber of images in test set:\", len(image_test_path))\n\"\"\"\n\n\nOnly a reduced number of images are present in the training set (**26684**), compared with the number of  images in the train_df data (**30227**).  \n\nIt might be that we do have duplicated entries in the train and class datasets. Let's check this.\n\n### Check duplicates in train dataset\n\n\"\"\"\nprint(\"Unique patientId in  train_class_df: \", train_class_df['patientId'].nunique())      \n\"\"\"\nWe confirmed that the number of *unique* **patientsId** are equal with the number of DICOM images in the train set.  \n\nLet's see what entries are duplicated. We want to check how are these distributed accross classes and Target value.\n\"\"\"\ntmp = train_class_df.groupby(['patientId','Target', 'class'])['patientId'].count()\ndf = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\ntmp = df.groupby(['Exams','Target','class']).count()\ndf2 = pd.DataFrame(data=tmp.values, index=tmp.index).reset_index()\ndf2.columns = ['Exams', 'Target','Class', 'Entries']\ndf2\nfig, ax = plt.subplots(nrows=1,figsize=(12,6))\nsns.barplot(ax=ax,x = 'Target', y='Entries', hue='Exams',data=df2, palette='Set2')\nplt.title(\"Chest exams class and Target\")\nplt.show()\n\"\"\"\n\nLet's now extract one image and process the DICOM information. \n\"\"\"\n\"\"\"\n### DICOM meta data\n\"\"\"\nsamplePatientID = list(train_class_df[:3].T.to_dict().values())[0]['patientId']\nsamplePatientID = samplePatientID+'.dcm'\ndicom_file_path = os.path.join(PATH,\"stage_2_train_images\/\",samplePatientID)\ndicom_file_dataset = dcm.read_file(dicom_file_path)\ndicom_file_dataset\n\"\"\"\nWe can observe that we do have available some useful information in the DICOM metadata with predictive value, for example:   \n* Patient sex;   \n* Patient age;  \n* Modality;  \n* Body part examined;  \n* View position;  \n* Rows & Columns;  \n* Pixel Spacing.  \n\n\"\"\"\n\"\"\"\nLet's sample few images having the **Target = 1**.\n\n### Plot DICOM images with Target = 1\n\"\"\"\ndef show_dicom_images(data):\n    img_data = list(data.T.to_dict().values())\n    f, ax = plt.subplots(3,3, figsize=(16,18))\n    for i,data_row in enumerate(img_data):\n        patientImage = data_row['patientId']+'.dcm'\n        imagePath = os.path.join(PATH,\"stage_2_train_images\/\",patientImage)\n        data_row_img_data = dcm.read_file(imagePath)\n        modality = data_row_img_data.Modality\n        age = data_row_img_data.PatientAge\n        sex = data_row_img_data.PatientSex\n        data_row_img = dcm.dcmread(imagePath)\n        ax[i\/\/3, i%3].imshow(data_row_img.pixel_array, cmap=plt.cm.bone) \n        ax[i\/\/3, i%3].axis('off')\n        ax[i\/\/3, i%3].set_title('ID: {}\\nModality: {} Age: {} Sex: {} Target: {}\\nClass: {}\\nWindow: {}:{}:{}:{}'.format(\n                data_row['patientId'],\n                modality, age, sex, data_row['Target'], data_row['class'], \n                data_row['x'],data_row['y'],data_row['width'],data_row['height']))\n    plt.show()\nshow_dicom_images(train_class_df[train_class_df['Target']==1].sample(9))\n\"\"\"\nWe would like to represent the images with the overlay boxes superposed. For this, we will need first to parse the whole dataset with **Target = 1** and gather all coordinates of the windows showing a **Lung Opacity** on the same image.  The simples method is show in <a href='#5'>[1]<\/a> and we will adapt our rendering from this method.\n\"\"\"\ndef show_dicom_images_with_boxes(data):\n    img_data = list(data.T.to_dict().values())\n    f, ax = plt.subplots(3,3, figsize=(16,18))\n    for i,data_row in enumerate(img_data):\n        patientImage = data_row['patientId']+'.dcm'\n        imagePath = os.path.join(PATH,\"stage_2_train_images\/\",patientImage)\n        data_row_img_data = dcm.read_file(imagePath)\n        modality = data_row_img_data.Modality\n        age = data_row_img_data.PatientAge\n        sex = data_row_img_data.PatientSex\n        data_row_img = dcm.dcmread(imagePath)\n        ax[i\/\/3, i%3].imshow(data_row_img.pixel_array, cmap=plt.cm.bone) \n        ax[i\/\/3, i%3].axis('off')\n        ax[i\/\/3, i%3].set_title('ID: {}\\nModality: {} Age: {} Sex: {} Target: {}\\nClass: {}'.format(\n                data_row['patientId'],modality, age, sex, data_row['Target'], data_row['class']))\n        rows = train_class_df[train_class_df['patientId']==data_row['patientId']]\n        box_data = list(rows.T.to_dict().values())\n        for j, row in enumerate(box_data):\n            ax[i\/\/3, i%3].add_patch(Rectangle(xy=(row['x'], row['y']),\n                        width=row['width'],height=row['height'], \n                        color=\"yellow\",alpha = 0.1))   \n    plt.show()\nshow_dicom_images_with_boxes(train_class_df[train_class_df['Target']==1].sample(9))\n\"\"\"\nFor some of the images with **Target=1**, we might see multiple areas (boxes\/rectangles) with **Lung Opacity**.\n\nLet's sample few images having the **Target = 0**.   \n\n### Plot DICOM images with Target = 0\n\n\"\"\"\nshow_dicom_images(train_class_df[train_class_df['Target']==0].sample(9))\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>   \n\n\n## <a id=\"34\">Add meta information from DICOM data<\/a>\n\n\n### Train data\n\nWe will parse the DICOM meta information and add it to the train dataset. We will do the same with the test data.\n\"\"\"\nvars = ['Modality', 'PatientAge', 'PatientSex', 'BodyPartExamined', 'ViewPosition', 'ConversionType', 'Rows', 'Columns', 'PixelSpacing']\n\ndef process_dicom_data(data_df, data_path):\n    for var in vars:\n        data_df[var] = None\n    image_names = os.listdir(PATH+data_path)\n    for i, img_name in tqdm_notebook(enumerate(image_names)):\n        imagePath = os.path.join(PATH,data_path,img_name)\n        data_row_img_data = dcm.read_file(imagePath)\n        idx = (data_df['patientId']==data_row_img_data.PatientID)\n        data_df.loc[idx,'Modality'] = data_row_img_data.Modality\n        data_df.loc[idx,'PatientAge'] = pd.to_numeric(data_row_img_data.PatientAge)\n        data_df.loc[idx,'PatientSex'] = data_row_img_data.PatientSex\n        data_df.loc[idx,'BodyPartExamined'] = data_row_img_data.BodyPartExamined\n        data_df.loc[idx,'ViewPosition'] = data_row_img_data.ViewPosition\n        data_df.loc[idx,'ConversionType'] = data_row_img_data.ConversionType\n        data_df.loc[idx,'Rows'] = data_row_img_data.Rows\n        data_df.loc[idx,'Columns'] = data_row_img_data.Columns  \n        data_df.loc[idx,'PixelSpacing'] = str.format(\"{:4.3f}\",data_row_img_data.PixelSpacing[0]) \nprocess_dicom_data(train_class_df,'stage_2_train_images\/')\n\"\"\"\n### Test data\n\nWe will create as well a test dataset with similar information.\n\"\"\"\ntest_class_df = pd.read_csv(PATH+'\/stage_2_sample_submission.csv')\ntest_class_df = test_class_df.drop('PredictionString',1)\nprocess_dicom_data(test_class_df,'stage_2_test_images\/')\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n\n## <a id=\"35\">Modality<\/a>\n\nLet's check how many modalities are used. Both train and test set are checked.\n\"\"\"\nprint(\"Modalities: train:\",train_class_df['Modality'].unique(), \"test:\", test_class_df['Modality'].unique())\n\"\"\"\nThe meaning of this modality is **CR** - **Computer Radiography**  <a href='#4'>[2]<\/a> <a href='#4'>[3]<\/a>.\n\n\n## <a id=\"36\">Body Part Examined<\/a>\n\nLet's check if other body parts than 'CHEST' appears in the data.\n\"\"\"\nprint(\"Body Part Examined: train:\",train_class_df['BodyPartExamined'].unique(), \"test:\", test_class_df['BodyPartExamined'].unique())\n\"\"\"\n## <a id=\"37\">View Position<\/a>\n\nView Position is a radiographic view associated with the Patient Position. Let's check the View Positions distribution for the both datasets.\n\n\n\n\"\"\"\nprint(\"View Position: train:\",train_class_df['ViewPosition'].unique(), \"test:\", test_class_df['ViewPosition'].unique())\n\"\"\"\n### Train dataset  \n\nLet's get into more details for the train dataset. First, let's check the distribution of PA and AP.\n\"\"\"\nget_feature_distribution(train_class_df,'ViewPosition')\n\"\"\"\nBoth **AP** and **PA** body positions are present in the data.  The meaning of these view positions are <a href='#4'>[2]<\/a> <a href='#4'>[3]<\/a>:\n* **AP** - Anterior\/Posterior;    \n* **PA** - Posterior\/Anterior.    \n\n\nLet's check, for the training data presenting **Lung Opacity**, the distribution of the window for both View Positions. We create a function to represent the distribution of the window centers and windows.\n\"\"\"\ndef plot_window(data,color_point, color_window,text):\n    fig, ax = plt.subplots(1,1,figsize=(7,7))\n    plt.title(\"Centers of Lung Opacity rectangles over rectangles\\n{}\".format(text))\n    data.plot.scatter(x='xc', y='yc', xlim=(0,1024), ylim=(0,1024), ax=ax, alpha=0.8, marker=\".\", color=color_point)\n    for i, crt_sample in data.iterrows():\n        ax.add_patch(Rectangle(xy=(crt_sample['x'], crt_sample['y']),\n            width=crt_sample['width'],height=crt_sample['height'],alpha=3.5e-3, color=color_window))\n    plt.show()\n\"\"\"\nWe sample a subset of the train data with **Target = 1**. We calculate as well the center of the windows with **Lung Opacity**.   We then select from this sample the data with the two view position, to plot the window distribution separatelly.\n\"\"\"\ntarget1 = train_class_df[train_class_df['Target']==1]\n\ntarget_sample = target1.sample(2000)\ntarget_sample['xc'] = target_sample['x'] + target_sample['width'] \/ 2\ntarget_sample['yc'] = target_sample['y'] + target_sample['height'] \/ 2\n\ntarget_ap = target_sample[target_sample['ViewPosition']=='AP']\ntarget_pa = target_sample[target_sample['ViewPosition']=='PA']\nplot_window(target_ap,'green', 'yellow', 'Patient View Position: AP')\nplot_window(target_pa,'blue', 'red', 'Patient View Position: PA')\n\"\"\"\n### Test dataset  \n\nLet's check the distribution of AP and PA positions for the test set.\n\"\"\"\nget_feature_distribution(test_class_df,'ViewPosition')\n\"\"\"\n## <a id=\"38\">Conversion Type<\/a>\n\nLet's check the Conversion Type data.\n\"\"\"\nprint(\"Conversion Type: train:\",train_class_df['ConversionType'].unique(), \"test:\", test_class_df['ConversionType'].unique())\n\"\"\"\nBoth train and test have only **WSD** Conversion Type Data. The meaning of this Conversion Type is **WSD**: **Workstation**.\n\n## <a id=\"39\">Rows and Columns<\/a>\n\"\"\"\nprint(\"Rows: train:\",train_class_df['Rows'].unique(), \"test:\", test_class_df['Rows'].unique())\nprint(\"Columns: train:\",train_class_df['Columns'].unique(), \"test:\", test_class_df['Columns'].unique())\n\"\"\"\nOnly {Rows:Columns} {1024:1024} are present in both train and test.  \n\n\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\"\"\"\n\"\"\"\n## <a id=\"310\">Patient Age<\/a>\n\nLet's examine now the data for the Patient Age for the train set.\n\n### Train dataset\n\"\"\"\ntmp = train_class_df.groupby(['Target', 'PatientAge'])['patientId'].count()\ndf = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\ntmp = df.groupby(['Exams','Target', 'PatientAge']).count()\ndf2 = pd.DataFrame(data=tmp.values, index=tmp.index).reset_index()\ntmp = train_class_df.groupby(['class', 'PatientAge'])['patientId'].count()\ndf1 = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\ntmp = df1.groupby(['Exams','class', 'PatientAge']).count()\ndf3 = pd.DataFrame(data=tmp.values, index=tmp.index).reset_index()\nfig, (ax) = plt.subplots(nrows=1,figsize=(16,6))\nsns.barplot(ax=ax, x = 'PatientAge', y='Exams', hue='Target',data=df2)\nplt.title(\"Train set: Chest exams Age and Target\")\nplt.xticks(rotation=90)\nplt.show()\nfig, (ax) = plt.subplots(nrows=1,figsize=(16,6))\nsns.barplot(ax=ax, x = 'PatientAge', y='Exams', hue='class',data=df3)\nplt.title(\"Train set: Chest exams Age and class\")\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n\n**Note**: most probably, the values of age 148 to 155 are mistakes.   \n\nLet's group the ages in 5 groups (0-19, 20-34, 35-49, 50-64 and 65+). \n\"\"\"\ntarget_age1 = target_sample[target_sample['PatientAge'] < 20]\ntarget_age2 = target_sample[(target_sample['PatientAge'] >=20) & (target_sample['PatientAge'] < 35)]\ntarget_age3 = target_sample[(target_sample['PatientAge'] >=35) & (target_sample['PatientAge'] < 50)]\ntarget_age4 = target_sample[(target_sample['PatientAge'] >=50) & (target_sample['PatientAge'] < 65)]\ntarget_age5 = target_sample[target_sample['PatientAge'] >= 65]\n\"\"\"\nLet's show the distribution of windows for the 5 age groups.\n\"\"\"\nplot_window(target_age1,'blue', 'red', 'Patient Age: 1-19 years')\nplot_window(target_age2,'blue', 'red', 'Patient Age: 20-34 years')\nplot_window(target_age3,'blue', 'red', 'Patient Age: 35-49 years')\nplot_window(target_age4,'blue', 'red', 'Patient Age: 50-65 years')\nplot_window(target_age5,'blue', 'red', 'Patient Age: 65+ years')\n\"\"\"\nLet's check also the distribution of patient age for the test data set.\n\n### Test dataset\n\"\"\"\nfig, (ax) = plt.subplots(nrows=1,figsize=(16,6))\nsns.countplot(test_class_df['PatientAge'], ax=ax)\nplt.title(\"Test set: Patient Age\")\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n\n## <a id=\"311\">Patient Sex<\/a>\n\nLet's examine now the data for the Patient Sex.   \n\n### Train dataset\n\nWe represent the number of Exams for each Patient Sex, grouped by value of Target.\n\"\"\"\ntmp = train_class_df.groupby(['Target', 'PatientSex'])['patientId'].count()\ndf = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\ntmp = df.groupby(['Exams','Target', 'PatientSex']).count()\ndf2 = pd.DataFrame(data=tmp.values, index=tmp.index).reset_index()\nfig, ax = plt.subplots(nrows=1,figsize=(6,6))\nsns.barplot(ax=ax, x = 'PatientSex', y='Exams', hue='Target',data=df2)\nplt.title(\"Train set: Patient Sex and Target\")\nplt.show()\n\"\"\"\nWe represent the number of Exams for each Patient Sex, grouped by value of  class.\n\"\"\"\ntmp = train_class_df.groupby(['class', 'PatientSex'])['patientId'].count()\ndf1 = pd.DataFrame(data={'Exams': tmp.values}, index=tmp.index).reset_index()\ntmp = df1.groupby(['Exams','class', 'PatientSex']).count()\ndf3 = pd.DataFrame(data=tmp.values, index=tmp.index).reset_index()\nfig, (ax) = plt.subplots(nrows=1,figsize=(6,6))\nsns.barplot(ax=ax, x = 'PatientSex', y='Exams', hue='class',data=df3)\nplt.title(\"Train set: Patient Sex and class\")\nplt.show()\n\"\"\"\nLet's plot as well the distribution of  window with Lung Opacity, separatelly for the female and male patients. We will reuse the sample with **Target = 1** for which we calculated also the center of the window.\n\"\"\"\ntarget_female = target_sample[target_sample['PatientSex']=='F']\ntarget_male = target_sample[target_sample['PatientSex']=='M']\nplot_window(target_female,\"red\", \"magenta\",\"Patients Sex: Female\")\nplot_window(target_male,\"darkblue\", \"blue\", \"Patients Sex: Male\")\n\"\"\"\nLet's check as well the distribution of Patient Sex for the test data.   \n\n### Test dataset\n\"\"\"\nsns.countplot(test_class_df['PatientSex'])\nplt.title(\"Test set: Patient Sex\")\nplt.show()\n\"\"\"\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n\n# <a id='4'>Conclusions<\/a>   \n\nAfter exploring the data, both the tabular and DICOM data, we were able to:  \n- discover duplications in the tabular data;  \n- explore the DICOM images;  \n- extract meta information from the DICOM data;  \n- add features to the tabular data from the meta information in DICOM data;  \n- further analyze the distribution of the data with the newly added features from DICOM metadata;  \n\nAll these findings are useful as preliminary work for building a model.\n\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\"\"\"\n\"\"\"\n# <a id='5'>References<\/a>  \n\n\n[1] Kevin Mader, Lung Opacity Overview, https:\/\/www.kaggle.com\/kmader\/lung-opacity-overview  \n[2] Modality Specific Modules, DICOM Standard,  http:\/\/dicom.nema.org\/medical\/dicom\/2014c\/output\/chtml\/part03\/sect_C.8.html  \n[3] DICOM Standard, https:\/\/www.dicomstandard.org\/     \n[4] Getting Started with Pydicom, https:\/\/pydicom.github.io\/pydicom\/stable\/getting_started.html   \n[5] ITKPYthon package, https:\/\/itkpythonpackage.readthedocs.io\/en\/latest\/   \n[6] DICOM in Python: Importing medical image data into NumPy with PyDICOM and VTK, https:\/\/pyscience.wordpress.com\/2014\/09\/08\/dicom-in-python-importing-medical-image-data-into-numpy-with-pydicom-and-vtk\/  \n[7] DICOM Processing and Segmentation in Python, https:\/\/www.raddq.com\/dicom-processing-segmentation-visualization-in-python\/  \n[8] DICOM Standard Browser, https:\/\/dicom.innolitics.com\/ciods  \n[9] How can I read a DICOM image in Python, https:\/\/www.quora.com\/How-can-I-read-a-DICOM-image-in-Python  \n[10] DICOM read example in Python, https:\/\/www.programcreek.com\/python\/example\/97517\/dicom.read_file    \n[11] DICOM in Python, https:\/\/github.com\/pydicom   \n\n\n<a href=\"#0\"><font size=\"1\">Go to top<\/font><\/a>\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6773248097154e'}"}
{"id":"47337","text":"\"\"\"\n## Note:\n1. This is just a Keras Starter For This Competition.\n2. This kernel is made for getting hands on over ideas of K fold Cross Validation With Neural Networks (Dense Networks in this case)\n3. It is risky to use Neural Networks With small datasets , Still this is  just an experiment\n4. The code for Neural Network is Taken from \" Deep Learning With Python \" by Francois Chollet.\n5. <b> Please do point out any correction and mistakes if it exists as I am a beginner in Machine Learning I am very much open to learn by Constructive Criticism <\/b>\n\"\"\"\n# 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 pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVC\n#from sklearn.multioutput import ClassifierChain\nfrom sklearn.naive_bayes import GaussianNB\n#from modlamp.sequences import MixedLibrary\nfrom sklearn.model_selection import train_test_split\nfrom skmultilearn.problem_transform import BinaryRelevance, LabelPowerset, ClassifierChain\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import f1_score\nimport xgboost as xgb\nfrom sklearn.metrics import log_loss\n#from mlxtend.classifier import StackingClassifier\nfrom sklearn.datasets import make_multilabel_classification\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom lightgbm import LGBMClassifier as lgb\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\ntrain_feat = pd.read_csv(\"..\/input\/lish-moa\/train_features.csv\")\ntrain_targ = pd.read_csv(\"..\/input\/lish-moa\/train_targets_scored.csv\")\ntest_feat = pd.read_csv(\"..\/input\/lish-moa\/test_features.csv\")\nsubm = pd.read_csv(\"..\/input\/lish-moa\/sample_submission.csv\")\nX = np.array(train_feat.loc[:,'g-0':'c-99'])\ny = np.array(train_targ.loc[:,\"5-alpha_reductase_inhibitor\":\"wnt_inhibitor\"])\nX_train , X_test , y_train , y_test = train_test_split(X , y , test_size = 0.20 , random_state = np.random.randint(2))\nprint((X_train.shape , y_train.shape))\nprint((X_test.shape , y_test.shape))\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_train  = scaler.fit_transform(X_train)\nX_test = scaler.fit_transform(X_test)\n\"\"\"\n### Model Architecture\n1. Three Hidden Layers\n2. Activation Units 1024 , 512 and 256 in each Dense Layer\n3. Rms Prop Optimizer Used for Finding Params\n4. Dropout of 0.2 added between each layers\n\"\"\"\nfrom keras import models\nfrom keras import layers\nfrom keras.layers import Dropout\n\ndef build_model():\n    model = models.Sequential()\n    model.add(layers.Dense(1024, activation = 'relu' , input_shape = (X_train.shape[1],)))\n    model.add(Dropout(0.2))\n    model.add(layers.Dense(512 , activation ='relu'))\n    model.add(Dropout(0.2))\n    model.add(layers.Dense(256 , activation ='relu'))\n    model.add(Dropout(0.2))\n    model.add(layers.Dense(206 , activation = 'sigmoid'))\n    model.compile(optimizer = 'rmsprop' , loss = 'binary_crossentropy')\n    return model\nimport numpy as np\nk= 10\nnum_val_samples = len(X_train) \/\/ k \nnum_epochs  = 30\nall_scores = []\n\nfor i in range(k):\n    print(\"Processing Fold #\",i)\n    val_data =  X_train[i* num_val_samples : (i+1) * num_val_samples]\n    val_targets = y_train[i* num_val_samples : (i+1) * num_val_samples]\n    \n    partial_train_data  = np.concatenate([X_train[:i * num_val_samples] , X_train[(i+1) * num_val_samples :]] , axis = 0)\n    partial_train_targets  = np.concatenate([y_train[:i * num_val_samples] , y_train[(i+1) * num_val_samples :]] , axis = 0)\n    \n    model = build_model()\n    \n    history = model.fit(partial_train_data , partial_train_targets ,  epochs = num_epochs , batch_size = 64 , verbose = 2)\n    y_prob = model.predict_proba(val_data)\n    score  = log_loss(val_targets , y_prob)\n    \n    #score = np.array(score)\n    #val_score = \n    all_scores.append(score)\n    \n\nprint(\"Scores on All 10 Folds\")\nprint(all_scores)\n# Building Final Model\nmodel = build_model()\nmodel.fit(X_train , y_train)\n## Evaluation on Holdout\nprobs = model.predict_proba(X_test)\nprobs\n## Evaluation of Log loss\nlog_loss(y_test , probs)\nprobs.shape\n# Building Entire Model with full Train Data\nX = np.array(train_feat.loc[: , 'g-0':'c-99'])\ny = np.array(train_targ.loc[:, \"5-alpha_reductase_inhibitor\":\"wnt_inhibitor\"])\nmodel = build_model()\nmodel.fit(X , y ,  epochs = 30 , batch_size = 128)\nX_test =  np.array(test_feat.loc[:,'g-0':'c-99'])\nX.shape\ncols  = [c for c in subm.columns if c not in 'sig_id']\n#X_test = test_feat[cols]\nX_test = scaler.fit_transform(X_test)\ny_prob = model.predict_proba(X_test)\n#cols  = [c for c in subm.columns if c not in 'sig_id']\n#cols\ndf_prob = pd.DataFrame(y_prob , columns =cols )\nids = subm['sig_id']\nids_df  = pd.DataFrame(data =ids)\ndf_final = pd.concat([ids_df ,df_prob],axis =1 )\nprint(df_final.head())\nprint(\"Submission File Shape\",subm.shape)\nprint(\"Our File Shape\" , df_final.shape)\ndf_final.to_csv(\"submission.csv\", index = False)\n","meta":"{'source': 'AI4Code', 'id': '57378a799c6e92'}"}
{"id":"14487","text":"# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.offline as py\nimport plotly.graph_objs as go\nimport plotly\nplotly.offline.init_notebook_mode(connected=True)\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\n\"\"\"\n<h1 style=\"background-color:#DC143C; font-family:'Brush Script MT',cursive;color:white;font-size:200%; text-align:center;border-radius: 50% 20% \/ 10% 40%\">Effect of lockdown amid COVID-19 pandemic on air quality of the megacity Delhi, India<\/h1>\n\nAuthors: Susanta Mahato, Swades Pal, and Krishna Gopal Ghosh\n\nSci Total Environ. 2020 Aug 15; 730: 139086. - Published online 2020 Apr 29.\nDOI: 10.1016\/j.scitotenv.2020.139086 - PMCID: PMC7189867 - PMID: 32375105\n\n\"Amid the COVID-19 pandemic, a nationwide lockdown is imposed in India initially for three weeks from 24th March to 14th April 2020 and extended up to 3rd May 2020. Due to the forced restrictions, pollution level in cities across the country drastically slowed down just within few days which magnetize discussions regarding lockdown to be the effectual alternative measures to be implemented for controlling air pollution.\"\n\n\"The present article eventually worked on this direction to look upon the air quality scenario amidst the lockdown period scientifically with special reference to the megacity Delhi.\" \n\n\"The results demonstrated that during lockdown air quality is significantly improved. Among  pollutants, NO2 (\u221252.68%) and CO (\u221230.35%) level have also reduced during-lockdown phase.\"\n\n\"About 40% to 50% improvement in air quality is identified just after four days of commencing lockdown. Overall, the study is thought to be a useful supplement to the regulatory bodies since it showed the pollution source control can attenuate the air quality. Temporary such source control in a suitable time interval may heal the environment.\"\n\nhttps:\/\/www.ncbi.nlm.nih.gov\/pmc\/articles\/PMC7189867\/\n\n\n\"\"\"\n\"\"\"\n![](https:\/\/static.toiimg.com\/img\/74868916\/Master.jpg)timesofindia.indiatimes.com\n\"\"\"\ndf1 = pd.read_csv(\"\/kaggle\/input\/impact-of-covid19-outbreak-on-global-air-quality\/CASE_DELHI.csv\")\nprint(df1.shape)\ndf1.head().style.set_properties(**{'background-color':'Aquamarine',\n                                     'color': 'purple'})\ndf = pd.read_csv(\"\/kaggle\/input\/impact-of-covid19-outbreak-on-global-air-quality\/NO2vO3_DELHI.csv\")\nprint(df.shape)\ndf.head().style.set_properties(**{'background-color':'BurlyWood',\n                                     'color': 'purple'})\ndf2 = pd.read_csv(\"\/kaggle\/input\/impact-of-covid19-outbreak-on-global-air-quality\/CASE_Satellite.csv\")\nprint(df2.shape)\ndf2.head().style.set_properties(**{'background-color':'PaleGreen',\n                                     'color': 'purple'})\ndf.shape\ndf.isnull().sum()\nfig = px.bar(df, \n             x='yr', y='no2', color_discrete_sequence=['#D63230'],\n             title='NO2 in Delhi 2015-20', text='n_no2')\nfig.show()\nfig = px.line(df, x=\"yr\", y=\"no2\", color_discrete_sequence=['#2B3A67'], \n              title=\"NO2 in Delhi 2015-20\")\nfig.show()\nfig = px.pie(df,\n             values=\"yr\",\n             names=\"case\",\n             template=\"seaborn\")\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n#Handling Missing Values\n\"\"\"\n# categorical features with missing values\ncategorical_nan = [feature for feature in df.columns if df[feature].isna().sum()>0 and df[feature].dtypes=='O']\nprint(categorical_nan)\n# replacing missing values in categorical features\nfor feature in categorical_nan:\n    df[feature] = df[feature].fillna('None')\ndf[categorical_nan].isna().sum()\n\"\"\"\n#Label Encoding\n\"\"\"\n#Code by Bizen https:\/\/www.kaggle.com\/hiro5299834\/tps-apr-2021-deebtables\/notebook\n\nTARGET = 'n_no2' #Target could Not be float otherwise will result in valueError: Unknown label type: 'continuous'. Even after the encoding.\n\nlabel_cols = ['case']\nnumerical_cols = ['yr', 'mo', 'da', 'no2', 'o3mx8', 'starthr', 'n_o3']\n#Code by Bizen https:\/\/www.kaggle.com\/hiro5299834\/tps-apr-2021-deebtables\/notebook\n\nfrom sklearn.preprocessing import LabelEncoder\n\ndef label_encoder(c):\n    le = LabelEncoder()\n    return le.fit_transform(c)\n\nlabel_encoded_df = df[label_cols].apply(label_encoder)\nnumerical_df = df[numerical_cols]\ntarget_df = df[TARGET]\n\ndf = pd.concat([numerical_df, label_encoded_df, target_df], axis=1)\ndf.head()\n\"\"\"\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\"\"\"\n\"\"\"\n#Installing scikit-learn-intelex\n\nPackage also available in conda - please refer to details https:\/\/github.com\/intel\/scikit-learn-intelex\n\"\"\"\n!pip install scikit-learn-intelex --progress-bar off >> \/tmp\/pip_sklearnex.log\nfrom sklearnex import patch_sklearn\npatch_sklearn()\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import SGDClassifier\n\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\nimport optuna\nRANDOM_SEED = 2021\nPROBAS = True\nFOLDS = 5\nN_ESTIMATORS = 1000\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\ndf_scaled = df.drop([TARGET], axis = 1).copy()\n\nscaler = StandardScaler()\nscaler.fit(df.drop([TARGET], axis = 1))\ndf_scaled = scaler.transform(df_scaled)\n\ndf_scaled = pd.DataFrame(df_scaled, columns=df.drop([TARGET], axis = 1).columns)\ndf_scaled.head(5)\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\nX = df_scaled\ny = df[TARGET]\n\nprint (f'X:{X.shape} y: {y.shape} \\n')\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = RANDOM_SEED)\nprint (f'X_train:{X_train.shape} y_train: {y_train.shape}')\nprint (f'X_test:{X_test.shape} y_test: {y_test.shape}')\n\ntest = df_scaled[len(df):]\nprint (f'test:{test.shape}')\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\n%time\nsvc_kernel_rbf = SVC(kernel='rbf', random_state=0, C=1.3040348958661234, gamma=0.11195797734572176 )\nsvc_kernel_rbf.fit(X_train, y_train)\ny_pred = svc_kernel_rbf.predict(X_test)\naccuracy_score(y_pred, y_test)\n%time\nfinal_pred = svc_kernel_rbf.predict(test)\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\ndef objective(trial):\n    from sklearn.svm import SVC\n    params = {\n        'C': trial.suggest_loguniform('C', 0.1, 0.5),\n        'gamma': trial.suggest_categorical('gamma', [\"auto\"]),\n        'kernel': trial.suggest_categorical(\"kernel\", [\"rbf\"])\n    }\n\n    svc = SVC(**params)\n    svc.fit(X_train, y_train)\n    return svc.score(X_test, y_test)\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\nstudy = optuna.create_study(sampler=optuna.samplers.TPESampler(seed=123),\n                            direction=\"maximize\",\n                            pruner=optuna.pruners.MedianPruner())\nstudy.optimize(objective, n_trials=5, show_progress_bar=True)\nprint(f\"Best Value: {study.best_trial.value}\")\nprint(f\"Best Params: {study.best_params}\")\n#Code by Napetrov https:\/\/www.kaggle.com\/napetrov\/tps04-svm-with-scikit-learn-intelex\/notebook\n\n%time\nn_folds = 5\nkf = KFold(n_splits=n_folds, shuffle=True, random_state=0)\ny_pred = np.zeros(test.shape[0])\n\nfor fold, (train_index, valid_index) in enumerate(kf.split(X, y)):\n    print(\"Running Fold {}\".format(fold + 1))\n    X_train, X_valid = pd.DataFrame(X.iloc[train_index]), pd.DataFrame(X.iloc[valid_index])\n    y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n    svc_kernel_rbf = SVC(**study.best_params)\n    svc_kernel_rbf.fit(X_train, y_train)\n    print(\"  Accuracy: {}\".format(accuracy_score(y_valid, svc_kernel_rbf.predict(X_valid))))\n    y_pred += svc_kernel_rbf.predict(test)\n\ny_pred \/= n_folds\n\nprint(\"I'm so screwed!\")\nprint(\"Not Done yet!\")\n\"\"\"\nMaybe next time I can handle with scikit-learn-intelex. I was almost there.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1a6f5e682c38b7'}"}
{"id":"71094","text":"\"\"\"\n# Task for Today  \n\n***\n\n## Critical Heat Flux Prediction  \n  \nGiven *data about various experimental conditions*, let's try to predict the **critical heat flux** for a given experiment.  \n  \nWe will use a random forest regression model to make our predictions.\n\"\"\"\n\"\"\"\n# Getting Started\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.ensemble import RandomForestRegressor\ndata = pd.read_csv('..\/input\/predicting-heat-flux\/Data_CHF_Zhao_2020_ATE.csv')\ndata\ndata.info()\n\"\"\"\n# Preprocessing\n\"\"\"\ndef preprocess_inputs(df):\n    df = df.copy()\n    \n    # Drop id and author columns\n    df = df.drop(['id', 'author'], axis=1)\n    \n    # Shuffle the dataset\n    df = df.sample(frac=1.0, random_state=1)\n    \n    # Split df into X and y\n    y = df['chf_exp [MW\/m2]']\n    X = df.drop('chf_exp [MW\/m2]', axis=1)\n    \n    return X, y\nX, y = preprocess_inputs(data)\nX\ny\n\"\"\"\n# Building Pipeline\n\"\"\"\ndef build_model():\n    \n    nominal_transformer = Pipeline(steps=[\n        ('onehot', OneHotEncoder(sparse=False, handle_unknown='ignore'))\n    ])\n    \n    preprocessor = ColumnTransformer(transformers=[\n        ('nominal', nominal_transformer, ['geometry'])\n    ], remainder='passthrough')\n    \n    model = Pipeline(steps=[\n        ('preprocessor', preprocessor),\n        ('regressor', RandomForestRegressor(random_state=1))\n    ])\n    \n    return model\n\"\"\"\n# Training\n\"\"\"\nkf = KFold(n_splits=5)\n\nrmses = []\n\nfor train_idx, test_idx in kf.split(X):\n    \n    X_train = X.iloc[train_idx, :]\n    X_test = X.iloc[test_idx, :]\n    y_train = y.iloc[train_idx]\n    y_test = y.iloc[test_idx]\n    \n    model = build_model()\n    model.fit(X_train, y_train)\n    \n    y_pred = model.predict(X_test)\n    \n    rmse = np.sqrt(np.mean((y_test - y_pred)**2))\n    \n    rmses.append(rmse)\n\nfinal_rmse = np.mean(rmses)\nprint(\"RMSE: {:.2f}\".format(final_rmse))\n\"\"\"\n# Data Every Day  \n\nThis notebook is featured on Data Every Day, a YouTube series where I train models on a new dataset each day.  \n\n***\n\nCheck it out!  \nhttps:\/\/youtu.be\/rK_Y9DjQ8js\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '82c1ccad4e112b'}"}
{"id":"96947","text":"\"\"\"\nAs any other Kaggle newbie, I baptized myself into Kagglism by completing 'Housing Prices Competition for Kaggle Learn Users'. My best submission so far got me into top 7% (I know it's nothing impressive) where I played around with XGBoost. However, I was curious how would Google Cloud Platform's AutoML would do with Housing Price data. So, I gave it a try and would like to share my experience.\nThe first thing you should keep in mind before using AutoML is that it is not free (apparently not cheap too) and has a lot of limitations. The data cannot be modified after you have uploaded it, therefore you should do all your data cleaning and feature engineering beforehand. Here\u2019s the data processing I went through before uploading my training data:\n\n\"\"\"\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nX_full = pd.read_csv('train.csv', index_col='Id')\nX_test = pd.read_csv('test.csv', index_col='Id')\n\n# Remove rows with missing target\nX_full.dropna(axis=0, subset=['SalePrice'], inplace=True)\n\n# I got the following idea from someone else's Notebook which made a lot of sence to me. The logic is that for example months are represented as numerical but in fact they are categorical\n# Convert some numeric columns to categorical\nX_full['MSSubClass'] = X_full['MSSubClass'].apply(str)\nX_full['MoSold'] = X_full['MoSold'].apply(str)\n\nX_test['MSSubClass'] = X_full['MSSubClass'].apply(str)\nX_test['MoSold'] = X_test['MoSold'].apply(str)\n\n\n# The next spet we merge columns that depend on each other into one\n# Merge 'Exterior1st' and 'Exterior2nd' to 'Exterior' since 'Exterior2nd' depends on 'Exterior1st'\nX_full['Exterior'] = X_full.apply(lambda x:x['Exterior1st'] if (pd.isnull(x['Exterior2nd'])) \n                                                            else str(x['Exterior1st'])+'-'+str(x['Exterior2nd']), axis=1)\n\n# Merge 'Condition1', 'Condition2' to 'Condition'\nX_full['Condition'] = X_full.apply(lambda x: x['Condition1'] if (pd.isnull(x['Condition2']))\n                                                             else str(x['Condition1'])+'-'+str(x['Condition2']), axis=1)\nX_test['Exterior'] = X_test.apply(lambda x:x['Exterior1st'] if (pd.isnull(x['Exterior2nd'])) \n                                                            else str(x['Exterior1st'])+'-'+str(x['Exterior2nd']), axis=1)\n\n# Merge 'Condition1', 'Condition2' to 'Condition'\nX_test['Condition'] = X_test.apply(lambda x: x['Condition1'] if (pd.isnull(x['Condition2']))\n                                                             else str(x['Condition1'])+'-'+str(x['Condition2']), axis=1)\n# Drop the merged columns since we do not need them anymore\nX_full.drop(['Exterior1st', 'Exterior2nd'], axis=1, inplace=True)\nX_full.drop(['Condition1', 'Condition2'], axis=1, inplace=True)\n\nX_test.drop(['Exterior1st', 'Exterior2nd'], axis=1, inplace=True)\nX_test.drop(['Condition1', 'Condition2'], axis=1, inplace=True)\n\n# Select categorical columns with relatively low cardinality\ncategorical_cols = [cname for cname in X_full.columns if X_full[cname].nunique()<15 and X_full[cname].dtype == 'object']\n# Select numerical columns\nnumerical_cols = [cname for cname in X_full.columns if X_full[cname].dtype in ['int64', 'float64']]\n\n# We keep only selected colums\nmy_cols = categorical_cols + numerical_cols\n\nX_train = X_full[my_cols].copy()\nX_test_final = X_test[my_cols].copy()\n\n# One-hot encode the data (to shorten the code, we use pandas)\nX_train = pd.get_dummies(X_train)\nX_test_final = pd.get_dummies(X_test_final)\nX_train, X_test_final = X_train.align(X_test_final, join='left', axis=1)\n\nX_train.to_csv('processed_train.csv', index=False)\nX_test_final.to_csv('processed_test.csv', index=False)\n\n\"\"\"\nStandard procedure to get your data One-hot encoded read.\n\n\"\"\"\n\"\"\"\n- In Google Cloud Platform you have to create a project and enable AutoML API for it. \n- From navigation menu you can find Tables. \n- On Table's Dataset you should create a new dataset. Remember the region of your dataset becsuse when uploading your data your storage bucket should be located in the same region. \n- Once you create dataset you can import data into it\n- You have three options for importing your data: importing form BigQuery, selecting CSV from Cloud Storage or uploading file form your computer. Second and third options are essentially the same (in both cases you upload data to Cloud Storage and select it from there)\n- If you are importing CSV file there are some requirements in terms of size and number of rows. But since Housing Data is not large the only requirement you should keep in mind is column names. The name of the column can contain alphanumeric characters or underscore (*_*). If you do not match those requirements the file import process will give an error\n- Before you start training your data you can see the summary of your data as below \n\n![Summary](https:\/\/i.imgur.com\/iNDVTuu.png)\n\n- You can select target column, which in our case is 'SalePrice'\n- You can have few other options such as training budget, selecting features (I went with all features from the code) and optimization objective (I selected MAE)\n\"\"\"\n\"\"\"\nThe training took around three hours and here's the result:\nTables AutoML picked regression model based on input data characteristics.\nMAE which I chose as my optimization objective is 15,651.237\n\n\n![Models Summary](https:\/\/i.imgur.com\/P2DhHmu.png)\n\"\"\"\n\"\"\"\nAnd finnaly AutoML provides a downlaodable feature importance which you could find helpful in building your own model.\n\n![Feature importance](https:\/\/i.imgur.com\/DovCleJ.png)\n\"\"\"\n\"\"\"\nThere are three options to test and use your model. The first one is, Batch Prediction where you upload you test dataset and AutoML will use your model with your test data and saves the result in your storage bucket (as you can expect this requires some computing power so it is not free). Second you can manually input data and you will get the predicted result (useful for 1 or 2 test cases). Finally, you can export your model as a TensorFlow package and run it locally on your Docker container.\n\nI used test data from the above code and prepared submission file for Housing Data Prediction Competition. My submission scored 15162.77580 which is less than my previous submission using XGBoost.\n\"\"\"\n\"\"\"\nTo sum it up, GCP's Tables AutoML is expensive, easy to use and gives decent result. Since for starters it gives you around $200 free credit that expires in three days, I did not spend any money. I would like to hear your suggestions and input on how I could improve the above processing step to get better result.   \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b2116423df2ce4'}"}
{"id":"8343","text":"\"\"\"\n# Convolutional and Relu With Arrays \n\"\"\"\n# Sympy is a python library for symbolic mathematics. It has a nice\n# pretty printer for matrices, which is all we'll use it for.\nimport sympy\nsympy.init_printing()\nfrom IPython.display import display\n\"\"\"\nDefine a image\n\"\"\"\nimport numpy as np\n#It is a image contains\n#1. Horizontal line\n#2. a small vertical line at left bottom\nimage = np.array([\n    [0,0,0,0,0,0],\n    [1,1,1,1,1,1],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n])\n#uncomment to show a difference of using sympy library\n#print(image)\ndisplay(sympy.Matrix(image))\n#kernel1 detect horizontal line\nkernel1 = np.array([\n    [1,1],\n    [-1,-1]\n])\n\ndisplay(sympy.Matrix(kernel1))\n# Reformat for Tensorflow\nimage = tf.cast(image, dtype=tf.float32)\nimage = tf.reshape(image, [1, *image.shape, 1])\nkernel1 = tf.reshape(kernel1, [*kernel1.shape, 1, 1])\nkernel1 = tf.cast(kernel1, dtype=tf.float32)\n\"\"\"\nDetection of Horizontal Line\n\"\"\"\nimport tensorflow as tf\n#get feature map \nimage_filter = tf.nn.conv2d(\n    input=image,\n    filters=kernel1,\n    strides=1,\n    padding='VALID',\n)\n#Detect filter\nimage_detect = tf.nn.relu(image_filter)\n\n# The first matrix is the image after convolution, and the second is\n# the image after ReLU.\ndisplay(sympy.Matrix(tf.squeeze(image_filter).numpy()))\ndisplay(sympy.Matrix(tf.squeeze(image_detect).numpy()))\n\"\"\"\nDetection of Vertical Line\n\"\"\"\nimage2 = np.array([\n    [0,0,0,0,0,0],\n    [1,1,1,1,1,1],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n    [0,1,0,0,0,0],\n])\n#kernel2 detect vertical line\nkernel2 = np.array([\n    [1,-1],\n    [1,-1]\n])\n# Reformat for Tensorflow\nimage2 = tf.cast(image2, dtype=tf.float32)\nimage2 = tf.reshape(image2, [1, *image2.shape, 1])\nkernel2 = tf.reshape(kernel2, [*kernel2.shape, 1, 1])\nkernel2 = tf.cast(kernel2, dtype=tf.float32)\nimport tensorflow as tf\n#get feature map \nimage_filter2 = tf.nn.conv2d(\n    input=image2,\n    filters=kernel2,\n    strides=1,\n    padding='VALID',\n)\n#Detect filter\nimage_detect2 = tf.nn.relu(image_filter2)\n\n# The first matrix is the image after convolution, and the second is\n# the image after ReLU.\ndisplay(sympy.Matrix(tf.squeeze(image_filter2).numpy()))\ndisplay(sympy.Matrix(tf.squeeze(image_detect2).numpy()))","meta":"{'source': 'AI4Code', 'id': '0f7186532e9e4f'}"}
{"id":"65979","text":"\"\"\"\n## About the Dataset\n\n> The dataset contains 2 folders\n  \n> * Infected\n> * Uninfected  \n  \n> And a total of 27,558 images.\n\n## Task\n> To come up with a model that can predict label for each image\n\"\"\"\n\"\"\"\n# Libraries\n\"\"\"\n# file operations\nimport os\n# to list files\nimport glob\n\n# for numerical analysis\nimport numpy as np \n# to store and process in a dataframe\nimport pandas as pd \n\n# for ploting graphs\nimport matplotlib.pyplot as plt\n# advancec ploting\nimport seaborn as sns\n\n# image processing\nimport matplotlib.image as mpimg\n\n# train test split\nfrom sklearn.model_selection import train_test_split\n# model performance metrics\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# utility functions\nfrom tensorflow.keras.utils import to_categorical, plot_model\n# process image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\n# sequential model\nfrom tensorflow.keras.models import Sequential\n# layers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout\n# callback functions\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler\n\"\"\"\n# Data\n\"\"\"\n\"\"\"\n### List files\n\"\"\"\n# list of files in the dataset\nos.listdir('..\/input\/cell-images-for-detecting-malaria\/cell_images\/cell_images')\n# list all the images in the directory Parasitized\nparasitized = glob.glob('..\/input\/cell-images-for-detecting-malaria\/cell_images\/cell_images\/Parasitized\/*.png')\n\n# no. of files in the directory Parasitized\nprint('No. of files in the directory Parasitized', len(parasitized))\n\n# first few images\nparasitized[:5]\n# list all the images in the directory Uninfected\nuninfected = glob.glob('..\/input\/cell-images-for-detecting-malaria\/cell_images\/cell_images\/Uninfected\/*.png')\n\n# no. of files in the directory Uninfected\nprint('No. of files in the directory Uninfected', len(uninfected))\n\n# first few images\nuninfected[:5]\n\"\"\"\n# Images\n\"\"\"\nfig, ax = plt.subplots(figsize=(18, 8))\nfig.suptitle('Parasitized cells', fontsize=24)\n\nfor ind, img_src in enumerate(parasitized[:30]):\n    plt.subplot(3, 10, ind+1)\n    img = plt.imread(img_src)\n    plt.axis('off')\n    plt.imshow(img)\nfig, ax = plt.subplots(figsize=(18, 8))\nfig.suptitle('Uninfected cells', fontsize=24)\n\nfor ind, img_src in enumerate(uninfected[:30]):\n    plt.subplot(3, 10, ind+1)\n    img = plt.imread(img_src)\n    plt.axis('off')\n    plt.imshow(img)\n\"\"\"\n# Model\n\"\"\"\n\"\"\"\n### Model parameters\n\"\"\"\nBATCH_SIZE = 100  # Number of training examples to process before updating our models variables\nIMG_SHAPE  = 150  # Our training data consists of images with width of 150 pixels and height of 150 pixels\nTARGET_SIZE = 64\nEPOCHS = 10\n\"\"\"\n### Model initialization\n\"\"\"\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3,3), activation='relu', input_shape=(IMG_SHAPE, IMG_SHAPE, 3)))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Conv2D(64, (3,3), activation='relu'))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Conv2D(128, (3,3), activation='relu'))\nmodel.add(MaxPooling2D(2,2))\n\nmodel.add(Flatten())\n\nmodel.add(Dropout(0.2))\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()\nplt.figure(figsize=(5, 10))\nplot_model(model, to_file=\"model.png\")\n\"\"\"\n### Data generator\n\"\"\"\ndatagen = ImageDataGenerator(rescale=1.\/255,\n                             zoom_range=0.2,\n                             horizontal_flip=True,\n                             vertical_flip=True,\n                             width_shift_range=0.2,\n                             height_shift_range=0.2,\n                             validation_split=0.3)\n\ntrain_data = datagen.flow_from_directory('..\/input\/cell-images-for-detecting-malaria\/cell_images\/cell_images',\n                                         target_size=(IMG_SHAPE,IMG_SHAPE),\n                                         batch_size=BATCH_SIZE,\n                                         shuffle=True,\n                                         class_mode='binary',\n                                         subset='training')\n\nvalidation_data = datagen.flow_from_directory('..\/input\/cell-images-for-detecting-malaria\/cell_images\/cell_images',\n                                              target_size=(IMG_SHAPE,IMG_SHAPE),\n                                              batch_size=BATCH_SIZE,\n                                              shuffle=True,\n                                              class_mode='binary',\n                                              subset='validation')\n\"\"\"\n### Callback functions\n\"\"\"\n# Instantiate an early stopping callback\nearly_stopping = EarlyStopping(monitor='val_loss', \n                               min_delta = 0.01,\n                               patience=5)\n\n# Instantiate a model checkpoint callback\nmodel_save = ModelCheckpoint('best_model.hdf5',\n                             monitor='val_loss',\n                             mode='min',\n                             save_best_only=True)\n\"\"\"\n### Fit model\n\"\"\"\nhistory = model.fit(train_data,\n                    validation_data=validation_data,\n                    epochs=EPOCHS,\n                    verbose=1, \n                    callbacks=[early_stopping, model_save])\n\"\"\"\n### Plot metrics\n\"\"\"\nplt.figure(figsize=(14, 5))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': '79a0d69d4848a2'}"}
{"id":"83790","text":"# 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)\nimport plotly.graph_objects as go\nimport seaborn as sn\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\nimport xgboost as xgb\nfrom xgboost import plot_importance\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\ndata_app_train = pd.read_csv('\/kaggle\/input\/home-credit-default-risk\/application_train.csv')\ndata_app_train['SK_ID_CURR'] = data_app_train['SK_ID_CURR'].astype(str)\nimport plotly.graph_objects as go\nimport plotly.express as px\ndata_app_test = pd.read_csv('\/kaggle\/input\/home-credit-default-risk\/application_test.csv')\ndata_app_test['SK_ID_CURR'] = data_app_test['SK_ID_CURR'].astype(str)\ndata_app_test['EMERGENCYSTATE_MODE'].unique()\n'XNA' in data_app_test['ORGANIZATION_TYPE'].unique().tolist()\npd.set_option('display.max_rows', None)\ndata_null_value_col = data_app_train.isna().sum()[data_app_train.isna().sum()!=0].reset_index().rename(columns={'index': 'col_name', 0: '#'})\ndata_null_value_col['%'] = data_null_value_col['#'] \/ data_app_train.shape[0]\ndata_null_value_col\npd.set_option('display.max_rows', 60)\ndef default_rate_cal(df, col, threshold):\n    print('default rate high band: ', df[df[col]>threshold]['TARGET'].sum()\/df[df[col]>threshold].shape[0])\n    print('default rate low band: ', df[df[col]>threshold]['TARGET'].sum()\/df[df[col]<=threshold].shape[0])\ndefault_rate_cal(data_app_train, 'AMT_INCOME_TOTAL', 600000)\nlist_cat_col = [\n    'NAME_CONTRACT_TYPE',\n    'CODE_GENDER',\n    'FLAG_OWN_CAR',\n    'FLAG_OWN_REALTY',\n    'NAME_TYPE_SUITE',\n    'NAME_INCOME_TYPE',\n    'NAME_EDUCATION_TYPE',\n    'NAME_FAMILY_STATUS',\n    'NAME_HOUSING_TYPE',\n    'OCCUPATION_TYPE',\n    'ORGANIZATION_TYPE',\n    'FONDKAPREMONT_MODE',\n    'HOUSETYPE_MODE',\n    'WALLSMATERIAL_MODE',\n    'EMERGENCYSTATE_MODE',\n#     'FLAG_MOBIL',\n    'FLAG_EMP_PHONE',\n#     'FLAG_WORK_PHONE',\n#     'FLAG_CONT_MOBILE',\n    'FLAG_PHONE',\n#     'FLAG_EMAIL',\n    'AMT_REQ_CREDIT_BUREAU_HOUR',\n    'AMT_REQ_CREDIT_BUREAU_DAY',\n    'AMT_REQ_CREDIT_BUREAU_WEEK',\n    'AMT_REQ_CREDIT_BUREAU_MON',\n    'AMT_REQ_CREDIT_BUREAU_QRT',\n    'AMT_REQ_CREDIT_BUREAU_YEAR',\n    'REG_REGION_NOT_LIVE_REGION',\n    'REG_REGION_NOT_WORK_REGION',\n#     'LIVE_REGION_NOT_WORK_REGION',\n    'REG_CITY_NOT_LIVE_CITY',\n    'REG_CITY_NOT_WORK_CITY',\n    'LIVE_CITY_NOT_WORK_CITY'\n]\n\nlist_num_col = [\n    'TARGET',\n    'CNT_CHILDREN',\n    'AMT_INCOME_TOTAL',\n    'AMT_CREDIT',\n    'AMT_ANNUITY',\n    'AMT_GOODS_PRICE',\n    'REGION_POPULATION_RELATIVE',\n    'DAYS_EMPLOYED',\n    'DAYS_REGISTRATION',\n    'DAYS_ID_PUBLISH',\n    'OWN_CAR_AGE',\n    'CNT_FAM_MEMBERS',\n    'REGION_RATING_CLIENT',\n    'REGION_RATING_CLIENT_W_CITY',\n    'EXT_SOURCE_1',\n    'EXT_SOURCE_2',\n    'EXT_SOURCE_3',\n    'APARTMENTS_AVG',\n    'BASEMENTAREA_AVG',\n    'YEARS_BEGINEXPLUATATION_AVG',\n    'YEARS_BUILD_AVG',\n    'COMMONAREA_AVG',\n    'ELEVATORS_AVG',\n    'ENTRANCES_AVG',\n    'FLOORSMAX_AVG',\n    'FLOORSMIN_AVG',\n    'LANDAREA_AVG',\n    'LIVINGAPARTMENTS_AVG',\n    'LIVINGAREA_AVG',\n    'NONLIVINGAPARTMENTS_AVG',\n    'NONLIVINGAREA_AVG',\n    'APARTMENTS_MODE',\n    'BASEMENTAREA_MODE',\n    'YEARS_BEGINEXPLUATATION_MODE',\n    'YEARS_BUILD_MODE',\n    'COMMONAREA_MODE',\n    'ELEVATORS_MODE',\n    'ENTRANCES_MODE',\n    'FLOORSMAX_MODE',\n    'FLOORSMIN_MODE',\n    'LANDAREA_MODE',\n    'LIVINGAPARTMENTS_MODE',\n    'LIVINGAREA_MODE',\n    'NONLIVINGAPARTMENTS_MODE',\n    'NONLIVINGAREA_MODE',\n    'APARTMENTS_MEDI',\n    'BASEMENTAREA_MEDI',\n    'YEARS_BEGINEXPLUATATION_MEDI',\n    'YEARS_BUILD_MEDI',\n    'COMMONAREA_MEDI',\n    'ELEVATORS_MEDI',\n    'ENTRANCES_MEDI',\n    'FLOORSMAX_MEDI',\n    'FLOORSMIN_MEDI',\n    'LANDAREA_MEDI',\n    'LIVINGAPARTMENTS_MEDI',\n    'LIVINGAREA_MEDI',\n    'NONLIVINGAPARTMENTS_MEDI',\n    'NONLIVINGAREA_MEDI',\n    'FONDKAPREMONT_MODE',\n    'HOUSETYPE_MODE',\n    'TOTALAREA_MODE',\n    'OBS_30_CNT_SOCIAL_CIRCLE',\n    'DEF_30_CNT_SOCIAL_CIRCLE',\n    'OBS_60_CNT_SOCIAL_CIRCLE',\n    'DEF_60_CNT_SOCIAL_CIRCLE',\n    'DAYS_LAST_PHONE_CHANGE',\n    'FLAG_DOCUMENT_2',\n    'FLAG_DOCUMENT_3',\n    'FLAG_DOCUMENT_4',\n    'FLAG_DOCUMENT_5',\n    'FLAG_DOCUMENT_6',\n    'FLAG_DOCUMENT_7',\n    'FLAG_DOCUMENT_8',\n    'FLAG_DOCUMENT_9',\n    'FLAG_DOCUMENT_10',\n    'FLAG_DOCUMENT_11',\n    'FLAG_DOCUMENT_12',\n    'FLAG_DOCUMENT_13',\n    'FLAG_DOCUMENT_14',\n    'FLAG_DOCUMENT_15',\n    'FLAG_DOCUMENT_16',\n    'FLAG_DOCUMENT_17',\n    'FLAG_DOCUMENT_18',\n    'FLAG_DOCUMENT_19',\n    'FLAG_DOCUMENT_20',\n    'FLAG_DOCUMENT_21'\n]\n\nlist_flag_to_cat = [\n#     'FLAG_MOBIL',\n    'FLAG_EMP_PHONE',\n#     'FLAG_WORK_PHONE',\n#     'FLAG_CONT_MOBILE',\n    'FLAG_PHONE',\n#     'FLAG_EMAIL',\n    'REG_REGION_NOT_LIVE_REGION',\n    'REG_REGION_NOT_WORK_REGION',\n    'REG_CITY_NOT_LIVE_CITY',\n    'REG_CITY_NOT_WORK_CITY',\n    'LIVE_CITY_NOT_WORK_CITY'\n]\n\nlist_to_remove = [\n    'WEEKDAY_APPR_PROCESS_START',\n    'HOUR_APPR_PROCESS_START',\n    'FLAG_MOBIL',\n    'FLAG_CONT_MOBILE',\n    'FLAG_EMAIL',\n    'FLAG_WORK_PHONE',\n    'LIVE_REGION_NOT_WORK_REGION',\n    \n]\n\"\"\"\n## Remove useless columns\n\"\"\"\ndata_app_train.drop(list_to_remove, axis=1, inplace=True)\n\"\"\"\n## Flag variable to cat\n\"\"\"\ndata_app_train[list_flag_to_cat] = data_app_train[list_flag_to_cat].astype(str)\ndf_non_default_ratio = pd.DataFrame(columns=['col_value', 'TARGET', 'count', 'total', 'col_name', 'ratio'])\nfor col in list_cat_col:\n    x_axis = data_app_train[col].unique().tolist()\n    y_axis = data_app_train[[col, 'TARGET', 'SK_ID_CURR']].groupby([col, 'TARGET']).count().reset_index().rename(columns={col: 'col_value', 'SK_ID_CURR': 'count'})\n    df_total = data_app_train[[col, 'SK_ID_CURR']].groupby([col]).count().reset_index().rename(columns={col: 'col_value', 'SK_ID_CURR': 'total'})\n    for col_value in list(set(x_axis).difference(set(y_axis[y_axis['TARGET']==0]['col_value'].values.tolist()))):\n        y_axis.loc[len(y_axis)] = [col_value, 0, 0]\n    for col_value in list(set(x_axis).difference(set(y_axis[y_axis['TARGET']==1]['col_value'].values.tolist()))):\n        y_axis.loc[len(y_axis)] = [col_value, 1, 0]\n    y_axis = y_axis.merge(df_total, on=['col_value'], how='left')\n    y_axis['col_name'] = col\n    y_axis['ratio'] = y_axis['count'] \/ (y_axis['total'] - y_axis['count'])\n    df_non_default_ratio = df_non_default_ratio.append(y_axis)\n\npd.set_option('display.max_rows', None)\ndf_non_default_ratio\npd.set_option('display.max_rows', 60)\n\"\"\"\n### CODE_GENDER\n* Exclude XNA, which is not in test data and not material\n\"\"\"\ndata_app_train.shape\ndata_app_train = data_app_train[data_app_train['CODE_GENDER']!='XNA']\ndata_app_train.shape\n\"\"\"\n### FLAG_OWN_CAR, OWN_CAR_AGE and DAYS_BIRTH\n* Flag own car but no own car age, Flag not own car but has own car age\n* OWN_CAR_AGE > DAYS_BIRTH\n* new feature: age_when_own_car\n\"\"\"\ndata_app_train[data_app_train['FLAG_OWN_CAR']=='N']['OWN_CAR_AGE'].unique()\ndata_app_train[data_app_train['FLAG_OWN_CAR']=='Y']['OWN_CAR_AGE'].unique()\ndata_app_train['age_when_own_car'] = data_app_train['DAYS_BIRTH'] \/ (-365) - data_app_train['OWN_CAR_AGE']\ndata_app_train = data_app_train[(data_app_train['age_when_own_car'] >= 0) | (data_app_train['age_when_own_car'].isna())]\ndata_app_train.drop(['OWN_CAR_AGE'], axis=1, inplace=True)\ndata_app_train.shape\n\"\"\"\n### FLAG_OWN_REALTY\n* Delete since Non-default ratio very similar\n\"\"\"\ndata_app_train.drop(['FLAG_OWN_REALTY'], axis=1, inplace=True)\ndata_app_train.shape\n\"\"\"\n### NAME_TYPE_SUITE\n* drop na since only 1000+ rows\n* combine some column values\n\"\"\"\ndata_app_train.dropna(subset=['NAME_TYPE_SUITE'], axis=0, inplace=True)\ndata_app_train.shape\ndata_app_train.loc[(data_app_train['NAME_TYPE_SUITE']=='Children') |\n                   (data_app_train['NAME_TYPE_SUITE']=='Family'), 'NAME_TYPE_SUITE_cat'] = 'high'\ndata_app_train.loc[(data_app_train['NAME_TYPE_SUITE']=='Spouse, partner') |\n                   (data_app_train['NAME_TYPE_SUITE']=='Unaccompanied'), 'NAME_TYPE_SUITE_cat'] = 'mid'\ndata_app_train.loc[(data_app_train['NAME_TYPE_SUITE']=='Group of people') |\n                   (data_app_train['NAME_TYPE_SUITE']=='Other_A'), 'NAME_TYPE_SUITE_cat'] = 'low'\ndata_app_train.loc[data_app_train['NAME_TYPE_SUITE']=='Other_B', 'NAME_TYPE_SUITE_cat'] = 'btm'\n\"\"\"\n### NAME_INCOME_TYPE\n* Combine columns values\n\n\"\"\"\ndata_app_train.loc[(data_app_train['NAME_INCOME_TYPE']=='Businessman') |\n                   (data_app_train['NAME_INCOME_TYPE']=='Student'), 'NAME_INCOME_TYPE_cat'] = 'no_default'\ndata_app_train.loc[(data_app_train['NAME_INCOME_TYPE']=='State servant') |\n                   (data_app_train['NAME_INCOME_TYPE']=='Pensioner'), 'NAME_INCOME_TYPE_cat'] = 'high'\ndata_app_train.loc[data_app_train['NAME_INCOME_TYPE']=='Commercial associate', 'NAME_INCOME_TYPE_cat'] = 'mid'\ndata_app_train.loc[data_app_train['NAME_INCOME_TYPE']=='Working', 'NAME_INCOME_TYPE_cat'] = 'low'\ndata_app_train.loc[(data_app_train['NAME_INCOME_TYPE']=='Maternity leave') |\n                   (data_app_train['NAME_INCOME_TYPE']=='Unemployed'), 'NAME_INCOME_TYPE_cat'] = 'high_default'\n\"\"\"\n### NAME_EDUCATION_TYPE\n* combine Incomplete higher\tand Secondary \/ secondary special\n\"\"\"\ndata_app_train['NAME_EDUCATION_TYPE_cat'] = data_app_train['NAME_EDUCATION_TYPE']\ndata_app_train.loc[(data_app_train['NAME_EDUCATION_TYPE_cat']=='Incomplete higher') |\n                   (data_app_train['NAME_EDUCATION_TYPE_cat']=='Secondary \/ secondary special'), 'NAME_EDUCATION_TYPE_cat'] = 'not_well_edu'\n\"\"\"\n### NAME_FAMILY_STATUS\n* drop unknown\n* combine values\n\"\"\"\ndata_app_train = data_app_train[data_app_train['NAME_FAMILY_STATUS']!='Unknown']\ndata_app_train.shape\ndata_app_train.loc[(data_app_train['NAME_FAMILY_STATUS']=='Civil marriage') |\n                   (data_app_train['NAME_FAMILY_STATUS']=='Single \/ not married'), 'NAME_FAMILY_STATUS_cat'] = 'low'\ndata_app_train.loc[(data_app_train['NAME_FAMILY_STATUS']=='Married') |\n                   (data_app_train['NAME_FAMILY_STATUS']=='Separated'), 'NAME_FAMILY_STATUS_cat'] = 'mid'\ndata_app_train.loc[data_app_train['NAME_FAMILY_STATUS']=='Widow', 'NAME_FAMILY_STATUS_cat'] = 'high'\n\"\"\"\n### NAME_HOUSING_TYPE\n* Combine values\n\"\"\"\ndata_app_train.loc[(data_app_train['NAME_HOUSING_TYPE']=='Rented apartment') |\n                   (data_app_train['NAME_HOUSING_TYPE']=='With parents'), 'NAME_HOUSING_TYPE_cat'] = 'low'\ndata_app_train.loc[(data_app_train['NAME_HOUSING_TYPE']=='Co-op apartment') |\n                   (data_app_train['NAME_HOUSING_TYPE']=='House \/ apartment') |\n                   (data_app_train['NAME_HOUSING_TYPE']=='Municipal apartment'), 'NAME_HOUSING_TYPE_cat'] = 'mid'\ndata_app_train.loc[data_app_train['NAME_HOUSING_TYPE']=='Office apartment', 'NAME_HOUSING_TYPE_cat'] = 'high'\n\"\"\"\n### OCCUPATION_TYPE\n* Combine values\n\"\"\"\ndata_app_train.loc[(data_app_train['OCCUPATION_TYPE']=='Accountants')|\n                    (data_app_train['OCCUPATION_TYPE']=='Core staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='HR staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='High skill tech staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='IT staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Managers')|\n                    (data_app_train['OCCUPATION_TYPE']=='Medicine staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Private service staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Realty agents')|\n                    (data_app_train['OCCUPATION_TYPE']=='Secretaries'), 'OCCUPATION_TYPE_cat'] = 'high'\ndata_app_train.loc[(data_app_train['OCCUPATION_TYPE']=='Cleaning staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Cooking staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Drivers')|\n                    (data_app_train['OCCUPATION_TYPE']=='Laborers')|\n                    (data_app_train['OCCUPATION_TYPE']=='Low-skill Laborers')|\n                    (data_app_train['OCCUPATION_TYPE']=='Sales staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Security staff')|\n                    (data_app_train['OCCUPATION_TYPE']=='Waiters\/barmen staff'), 'OCCUPATION_TYPE_cat'] = 'mid'\ndata_app_train.loc[data_app_train['OCCUPATION_TYPE_cat'].isna(), 'OCCUPATION_TYPE_cat'] = 'mid'\nlist_modeled_cat = [\n    'NAME_CONTRACT_TYPE',\n    'CODE_GENDER',\n    'FLAG_OWN_CAR',\n    'age_when_own_car',\n    'NAME_TYPE_SUITE_cat',\n    'NAME_INCOME_TYPE_cat',\n    'NAME_EDUCATION_TYPE_cat',\n    'NAME_FAMILY_STATUS',\n    'NAME_HOUSING_TYPE_cat',\n    'OCCUPATION_TYPE_cat',\n    'FLAG_EMP_PHONE',\n    'FLAG_PHONE',\n    'EMERGENCYSTATE_MODE',\n    'REG_CITY_NOT_LIVE_CITY',\n    'REG_CITY_NOT_WORK_CITY',\n    'LIVE_CITY_NOT_WORK_CITY',\n    'REG_REGION_NOT_LIVE_REGION'\n]\ndata_app_train['NAME_HOUSING_TYPE_cat'].unique()\n\ndata_app_train_train = data_app_train[list_modeled_cat+['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'TARGET']]\ndata_app_train_train['TARGET'] = data_app_train_train['TARGET'].astype(str)\n\ndata_app_train_xgboost = pd.concat([data_app_train_train[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'TARGET']], pd.get_dummies(data_app_train_train[list_modeled_cat])], axis=1)\n\n\nX_train, X_test, y_train, y_test = train_test_split(data_app_train_xgboost.drop(['TARGET'], axis=1).values, data_app_train_xgboost['TARGET'].values, test_size=0.2, random_state=1234565)\nparams = {\n    'booster': 'dart',\n    'objective': 'binary:logistic',\n    'eval_metric': 'auc',\n    'verbosity': 1,\n    'eta': 0.005,\n    'max_depth':7\n    \n}\n\nplst = params.items()\n\ndtrain = xgb.DMatrix(X_train, y_train)\nnum_rounds = 50\nmodel = xgb.train(list(params.items()), dtrain, num_rounds)\n\n\ndtest = xgb.DMatrix(X_test)\nans = model.predict(dtest)\n\nfrom sklearn.metrics import roc_auc_score\n\n\ncnt1 = 0\ncnt2 = 0\nfor i in range(len(y_test)):\n    if ans[i] == y_test[i]:\n        cnt1 += 1\n    else:\n        cnt2 += 1\n\nprint(\"Accuracy: %.2f %% \" % (100 * cnt1 \/ (cnt1 + cnt2)))\nprint('roc: ', roc_auc_score(y_test, ans))\n\n\nplot_importance(model)\nplt.show()\n\"\"\"\n# EDA\n\"\"\"\n\"\"\"\n## Days to Years\n\"\"\"\ndata_app_train = pd.read_csv('\/kaggle\/input\/home-credit-default-risk\/application_train.csv')\ndata_app_train['SK_ID_CURR'] = data_app_train['SK_ID_CURR'].astype(str)\ndata_app_train['DAYS_BIRTH_year'] = data_app_train['DAYS_BIRTH'] \/ -365\ndata_app_train['DAYS_EMPLOYED_year'] = data_app_train['DAYS_EMPLOYED'] \/ -365\ndata_app_train.loc[data_app_train['DAYS_EMPLOYED']==365243, 'DAYS_EMPLOYED_year'] = 0\ndata_app_train['DAYS_REGISTRATION_year'] = data_app_train['DAYS_REGISTRATION'] \/ -365\ndata_app_train['DAYS_ID_PUBLISH_year'] = data_app_train['DAYS_ID_PUBLISH'] \/ -365\ndata_app_train['DAYS_LAST_PHONE_CHANGE_year'] = data_app_train['DAYS_LAST_PHONE_CHANGE'] \/ -365\nplt.figure(figsize=(40, 30))\ncorrMatrix = data_app_train[list_num_col].corr()\nsn.heatmap(corrMatrix)\nplt.show()\npd.set_option('display.max_rows', None)\ncorrMatrix[['TARGET']].sort_values(by='TARGET', ascending=False)\npd.set_option('display.max_rows', 60)\n\"\"\"\n## Bar Chart to show ratios\n\"\"\"\ndef colored_and_styled_bar_chart(col, title):\n    x_axis = data_app_train[col].unique().tolist()\n    y_axis = data_app_train[[col, 'TARGET']].groupby([col, 'TARGET']).count().reset_index()\n#     if len(y_axis[y_axis['TARGET']==0][col].values.tolist()) < len(x_axis):\n        \n    y_axis_default = data_app_train[data_app_train['TARGET']==1][[col, 'TARGET']].groupby([col]).count()['TARGET'].values.tolist()\n    y_axis_non_default = data_app_train[data_app_train['TARGET']==0][[col, 'TARGET']].groupby([col]).count()['TARGET'].values.tolist()\n    fig = go.Figure()\n    fig.add_trace(go.Bar(x=x_axis,\n                    y=y_axis_non_default,\n                    name='Not Default',\n                    marker_color='rgb(55, 83, 109)',\n                         texttemplate='%{y:.2s}', textposition='outside'\n#                     text=data_app_train[data_app_train['TARGET']==0][[col, 'TARGET']].groupby([col]).count()['TARGET'].values.tolist(),\n#                     textposition='outside',\n                    ))\n    fig.add_trace(go.Bar(x=x_axis,\n                    y=y_axis_default,\n                    name='Default',\n                    marker_color='rgb(26, 118, 255)',\n                         texttemplate='%{y:.2s}', textposition='outside'\n#                     text=data_app_train[data_app_train['TARGET']==1][[col, 'TARGET']].groupby([col]).count()['TARGET'].values.tolist(),\n#                     textposition='outside',\n                    ))\n\n    fig.update_layout(\n        title=title,\n        xaxis_tickfont_size=14,\n        yaxis=dict(\n            title='Count',\n            titlefont_size=16,\n            tickfont_size=14,\n        ),\n        legend=dict(\n            x=0,\n            y=1.0,\n            bgcolor='rgba(255, 255, 255, 0)',\n            bordercolor='rgba(255, 255, 255, 0)'\n        ),\n        barmode='group',\n        bargap=0.15, # gap between bars of adjacent location coordinates.\n        bargroupgap=0.1 # gap between bars of the same location coordinate.\n    )\n#     fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')\n#     fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\n    fig.show()\n#     for i in range(len(x_axis)):\n#         if y_axis_default[i] == 0:\n#             print('Non-default Ratio of ', x_axis[i], ': 1')\n#         else:\n#             print('Non-default Ratio of ', x_axis[i], ': ', y_axis_non_default[i] \/ y_axis_default[i])\ncolored_and_styled_bar_chart('NAME_CONTRACT_TYPE', 'Contract Type')\ncolored_and_styled_bar_chart('CODE_GENDER', 'Gender')\ncolored_and_styled_bar_chart('NAME_INCOME_TYPE', 'Income Type')\ncolored_and_styled_bar_chart('NAME_TYPE_SUITE', 'Suite Type')\n\"\"\"\n* Non-default ratio almost 10, except for Other B about 1.15\n\"\"\"\ncolored_and_styled_bar_chart('NAME_EDUCATION_TYPE', 'Education Type Defaults')\n\"\"\"\nVery few # for those 4 types of income\nState servant and pensioners have similar default rate while working has highest default rate\n\"\"\"\ncolored_and_styled_bar_chart('NAME_FAMILY_STATUS', 'Family Status Defaults')\n\"\"\"\n* Unknown has no defaults\n* separated is highly possible to default\n* other status has similar non-default ratio 10:1\n\"\"\"\ncolored_and_styled_bar_chart('NAME_HOUSING_TYPE', 'Housing Defaults')\n\"\"\"\n* similar non-default ratio\n\"\"\"\ncolored_and_styled_bar_chart('OCCUPATION_TYPE', 'Occupation Type')\n\"\"\"\n* non-default ratio \\> 10: Laborers, Managers, Drivers, Sales staff, Cleaning staff, Medicine staff, Security staff, High skill tech staff, Waiters\/barmen staff, Lowe-skill Laboreres, Realty agents\n* non-default ratio \\< 10: Core Staff, Accountants, Cooking staff, Private Service staff, secretaries, IT staff\n\"\"\"\ncolored_and_styled_bar_chart('FLAG_EMP_PHONE', 'Employer Phone')\n\"\"\"\n* with employer phone, has increased the ND ratio a lot\n\"\"\"\ncolored_and_styled_bar_chart('FLAG_WORK_PHONE', 'Work Phone')\ncolored_and_styled_bar_chart('FLAG_CONT_MOBILE', 'Cont Mobile')\n\"\"\"\n* No obvisous difference\n\"\"\"\n\ncolored_and_styled_bar_chart('FLAG_MOBIL', 'Mobile')\ncolored_and_styled_bar_chart('FLAG_PHONE', 'Phone')\n\"\"\"\n* ND ratio Minor diff\n\"\"\"\ncolored_and_styled_bar_chart('FLAG_EMAIL', 'Email')\n\"\"\"\n* ND ratio super close\n\"\"\"\ncolored_and_styled_bar_chart('CNT_FAM_MEMBERS', '# of Family')\n\"\"\"\n* Family with 2 members has the highest non-default ratio\n* Family members with 1, 3, 4, 5 has around 10 non-default ratio\n* \\> 5 does not have enough data points to make decision, set as one category to let the model learn.\n\"\"\"\ncolored_and_styled_bar_chart('REGION_RATING_CLIENT', 'Region Rating')\n\"\"\"\n* No idea what the column means\n* 11.66, 19.375, 7.9\n* rating 1 => normal range, rating 2 => good range, rating 3 => bad range\n\"\"\"\ncolored_and_styled_bar_chart('REGION_RATING_CLIENT_W_CITY', 'Region Rating with City')\n\"\"\"\n* 11.66, 19.41, 7.8\n* Very similar to region rating\n\"\"\"\ncolored_and_styled_bar_chart('WEEKDAY_APPR_PROCESS_START', 'Process Start Weekday')\n\"\"\"\n* Very similar and normal range\n\"\"\"\ncolored_and_styled_bar_chart('HOUR_APPR_PROCESS_START', 'Process Start Hour')\ncolored_and_styled_bar_chart('ORGANIZATION_TYPE', 'Organization Type')\ndata_app_train['FONDKAPREMONT_MODE'] = data_app_train['FONDKAPREMONT_MODE'].fillna('blank')\ncolored_and_styled_bar_chart('FONDKAPREMONT_MODE', 'FONDKAPREMONT_MODE')\ndata_app_train['HOUSETYPE_MODE'] = data_app_train['HOUSETYPE_MODE'].fillna('blank')\ncolored_and_styled_bar_chart('HOUSETYPE_MODE', 'HOUSETYPE_MODE')\ndata_app_train['WALLSMATERIAL_MODE'] = data_app_train['WALLSMATERIAL_MODE'].fillna('blank')\ncolored_and_styled_bar_chart('WALLSMATERIAL_MODE', 'WALLSMATERIAL_MODE')\ndata_app_train['EMERGENCYSTATE_MODE'] = data_app_train['EMERGENCYSTATE_MODE'].fillna('blank')\ncolored_and_styled_bar_chart('EMERGENCYSTATE_MODE', 'EMERGENCYSTATE_MODE')\ndef histagram(col):\n    fig = px.histogram(data_app_train, x=col, color='TARGET')\n    fig.show()\n\"\"\"\n* Does not have obvious trends\n\"\"\"\nhistagram('REGION_POPULATION_RELATIVE')\ndata_app_train['DAYS_BIRTH_year'] = data_app_train['DAYS_BIRTH'] \/ -365\ndata_app_train['DAYS_EMPLOYED_year'] = data_app_train['DAYS_EMPLOYED'] \/ -365\ndata_app_train.loc[data_app_train['DAYS_EMPLOYED']==365243, 'DAYS_EMPLOYED_year'] = 0\ndata_app_train['DAYS_REGISTRATION_year'] = data_app_train['DAYS_REGISTRATION'] \/ -365\ndata_app_train['DAYS_ID_PUBLISH_year'] = data_app_train['DAYS_ID_PUBLISH'] \/ -365\ndata_app_train['DAYS_LAST_PHONE_CHANGE_year'] = data_app_train['DAYS_LAST_PHONE_CHANGE'] \/ -365\nhistagram('DAYS_BIRTH_year')\n\"\"\"\n* \\> 27, increase a lot\n* from 27 onwards, gradually decrease\n* \\> 65 sudden decrease\n\"\"\"\nhistagram('DAYS_EMPLOYED_year')\n\"\"\"\n* Gradually decrease\n* entry = 365243 are either pensioner or unemployed\n\"\"\"\nhistagram('DAYS_REGISTRATION_year')\n\"\"\"\n* Gradually decrease when registration year increase\n\"\"\"\nhistagram('DAYS_ID_PUBLISH_year')\n\"\"\"\n* similar trned for defaults and non-defaults\n* heap in 10.6-12.6\n\"\"\"\nhistagram('OWN_CAR_AGE')\nhistagram('DAYS_LAST_PHONE_CHANGE')","meta":"{'source': 'AI4Code', 'id': '99c2ec1df9b979'}"}
{"id":"16645","text":"from IPython.display import display\nimport pandas as pd\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\npd.set_option('display.max_columns', None)\ntrain = pd.read_csv('..\/input\/titanic\/train.csv')\ntest = pd.read_csv('..\/input\/titanic\/test.csv')\ntrain.head()\ndata1 = [train, test]\ntrain.describe()\ntest.describe()\ntrain.isnull().sum()\ntest.isnull().sum()\nsns.countplot(train['Survived'])\n# Making Column 'FamilySize'\nfor dataset in data1:\n    dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1\nprint (train[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean())\ntrain.corrwith(train['FamilySize'])\nsns.heatmap(train.corr(), annot=True)\nsns.boxplot(x='Pclass', y='Fare', data=train)\nsns.countplot(x='Pclass', hue='FamilySize', data=train)\ntrain['FamilySize'].value_counts()\nfor dataset in data1:\n    display(dataset['Cabin'].isnull().sum() \/ len(dataset['Cabin']))\ntrain['Cabin']\nfor dataset in data1:\n    #dataset['TravellingAlone'] = np.nan\n    dataset.loc[dataset['FamilySize'] == 1 ,'TravellingAlone'] = 1\n    dataset.loc[dataset['FamilySize'] != 1 ,'TravellingAlone'] = 0\ntrain.head()\nfor dataset in data1:\n    dataset['TravellingAlone'] = dataset['TravellingAlone'].astype('int64')\ntrain.head()\ntrain.corrwith(train['TravellingAlone'])\nfor dataset in data1:\n    print(dataset.isnull().sum())\n    print('-'*19)\ntrain.corrwith(train['Age'])\nsns.boxplot(x='Pclass', y='Age', data=train)\nsns.distplot(train['Age'])\ntrain.loc[(train['Pclass'] == 1) ,'Age'].isnull().sum()\ntrain.loc[(train['Pclass'] == 2) ,'Age'].isnull().sum()\ntrain.loc[(train['Pclass'] == 3) ,'Age'].isnull().sum()\ntrain['Age'].isnull().sum()\nfor dataset in data1:\n    dataset.loc[(dataset['Pclass'] == 1), 'Age'] = dataset.loc[(dataset['Pclass'] == 1), 'Age'].fillna(dataset.loc[(dataset['Pclass'] == 1), 'Age'].median())\n    dataset.loc[(dataset['Pclass'] == 2), 'Age'] = dataset.loc[(dataset['Pclass'] == 2), 'Age'].fillna(dataset.loc[(dataset['Pclass'] == 2), 'Age'].median())\n    dataset.loc[(dataset['Pclass'] == 3), 'Age'] = dataset.loc[(dataset['Pclass'] == 3), 'Age'].fillna(dataset.loc[(dataset['Pclass'] == 3), 'Age'].median())\ntrain['Age'].isnull().sum()\nfor dataset in data1:\n    print(dataset.isnull().sum())\n    print('#'*100)\nsns.distplot(train['Fare'])\nsns.boxplot(x='Survived', y='Fare', data=train)\ntrain.corrwith(train['Fare'])\nfor dataset in data1:\n    dataset['Fare'] = dataset['Fare'].fillna(dataset['Fare'].median())\ntest['Fare'].isnull().sum()\ntype(train['Embarked'].mode().values[0])\nfor dataset in data1:\n    dataset['Embarked'] = dataset['Embarked'].fillna(dataset['Embarked'].mode().values[0])\npassenger_id = test['PassengerId']\nfor dataset in data1:\n    dataset.drop(['PassengerId', 'Name', 'Ticket', 'Cabin', 'SibSp', 'Parch', 'FamilySize'], axis=1, inplace=True)\ntrain.head()\ntrain['Age'].hist()\nfor dataset in data1:\n    dataset['Age'] = dataset['Age'].astype('int64')\ntrain['CategoricalAge'] = pd.cut(train['Age'], 5)\ntrain['CategoricalFare'] = pd.qcut(train['Fare'], 3)\ntrain['CategoricalAge'].value_counts()\ntrain['CategoricalFare'].value_counts()\nfor dataset in data1:\n    dataset.loc[(dataset['Age'] < 16), 'Age'] = 0\n    dataset.loc[(dataset['Age'] >= 16) & (dataset['Age'] < 32), 'Age'] = 1\n    dataset.loc[(dataset['Age'] >= 32) & (dataset['Age'] < 48), 'Age'] = 2\n    dataset.loc[(dataset['Age'] >= 48) & (dataset['Age'] < 64), 'Age'] = 3\n    dataset.loc[(dataset['Age'] >= 64), 'Age'] = 4\n    dataset.loc[(dataset['Fare'] < 9.00), 'Fare'] = 0\n    dataset.loc[(dataset['Fare'] >=9.00 ) & (dataset['Fare'] < 26.00), 'Fare'] = 1\n    dataset.loc[(dataset['Fare'] >= 26.00), 'Fare'] = 2\ntrain.drop(['CategoricalAge', 'CategoricalFare'] ,axis=1, inplace=True)\nsns.countplot(x='Survived', hue='Sex', data=train)\ntrain.head()\ntest.head()\nfrom sklearn.preprocessing import LabelEncoder\nlabelEnc = LabelEncoder()\nfor dataset in data1:\n    dataset['Sex_En'] = labelEnc.fit_transform(dataset['Sex'])\n    dataset['Embarked_En'] = labelEnc.fit_transform(dataset['Embarked'])\n    dataset['Pclass_En'] = labelEnc.fit_transform(dataset['Pclass'])\n    dataset.drop(['Sex', 'Embarked', 'Pclass'], axis=1, inplace=True)\ntrain.head()\ntest.head()\nX = train.drop('Survived', axis=1)\ny = y_train = train['Survived']\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)\nfrom sklearn.linear_model import LogisticRegression\nlr_model = LogisticRegression()\nlr_model.fit(X_train,y_train)\ny_pred = lr_model.predict(X_test)\nfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score\ncm = confusion_matrix(y_test,y_pred)\ncm\nac = accuracy_score(y_test,y_pred)\nac\nfrom sklearn.ensemble import RandomForestClassifier\nrf_model = RandomForestClassifier()\nrf_model.fit(X_train,y_train)\ny_pred_rf = rf_model.predict(X_test)\nac = accuracy_score(y_test,y_pred_rf)\nac\ncm = confusion_matrix(y_test,y_pred_rf)\ncm\nfrom sklearn.tree import DecisionTreeClassifier\ndt_model = DecisionTreeClassifier()\ndt_model.fit(X_train,y_train)\ny_pred_dt = dt_model.predict(X_test)\ncm = confusion_matrix(y_test,y_pred_dt)\ncm\nac = accuracy_score(y_test,y_pred_dt)\nac\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_model = KNeighborsClassifier(3)\nknn_model.fit(X_train,y_train)\ny_pred_knn = knn_model.predict(X_test)\ncm = confusion_matrix(y_test,y_pred_knn)\ncm\nac = accuracy_score(y_test,y_pred_knn)\nac\ny_pred_test = lr_model.predict(test)\nfrom sklearn.svm import SVC\nsvc_model = SVC(probability=True)\nsvc_model.fit(X_train,y_train)\ny_pred_svc = svc_model.predict(X_test)\nac = accuracy_score(y_test,y_pred_svc)\nac\ny_pred_svc_test = svc_model.predict(test)\n\"\"\"\n### Model Evaluation\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, classification_report\ndef evaluate_models(models):\n    for model in models:\n        print(\"Evaluation for {}\".format(type(model).__name__))\n        print(\"----\"*20)\n        y_pred = model.predict(X_test)\n        cm = confusion_matrix(y_test,y_pred)\n        print(\"\\nConfusion Matrix:\\n\",cm)\n        ac = accuracy_score(y_test,y_pred)\n        print(\"\\nAccuracy:\\n\",ac)\n        print(\"\\nClassification Report:\\n\")\n        print(classification_report(y_test,y_pred))\nmodels = [lr_model,rf_model,dt_model, knn_model, svc_model]\nevaluate_models(models)\n\"\"\"\n### Cross Validation\n\"\"\"\nfrom sklearn.model_selection import KFold, cross_val_score, RandomizedSearchCV\ndef cross_validate_models(models, splits):\n    kf = KFold(n_splits=splits,shuffle=True)\n    for model in models:\n        scores = cross_val_score(model,\n                                 X_train,\n                                 y_train,\n                                 cv=kf,\n                                 n_jobs=12,\n                                 scoring=\"accuracy\")\n        print(\"Cross-Validation for {}:\\n\".format(type(model).__name__))\n        print(\"Mean score: \", np.mean(scores))\n        print(\"Variance of score: \", np.std(scores)**2)\n        fig = plt.figure(figsize = (10,5))\n        ax = fig.add_subplot(111)\n        ax = sns.distplot(scores)\n        ax.set_xlabel(\"Cross-Validated Accuracy scores\")\n        ax.set_ylabel(\"Frequency\")\n        ax.set_title('Frequency Distribution of Cross-Validated Accuracy scores for {}'.format(type(model).__name__), fontsize = 15)\ncross_validate_models(models,100)\n\"\"\"\n### Hyperparameter Tuning\n\"\"\"\nlr_params = {\"penalty\" : [\"l1\", \"l2\"],\n             \"C\" : np.logspace(0, 4, 10),\n             \"solver\" : ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga']}\ndt_params = {\"criterion\":[\"gini\",\"entropy\"],\n             \"splitter\":[\"best\",\"random\"],\n             \"max_depth\":[3,9,81,200],\n             \"min_samples_split\":[25,30,35,50]}\nknn_params = {\"n_neighbors\" : [1,3,5,7,9,11,13,15,17,19,21],\n              \"metric\" :  ['euclidean', 'manhattan', 'minkowski'],\n              \"weights\" : ['uniform', 'distance']}             \nrf_params = {'bootstrap': [True, False],\n 'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, None],\n 'max_features': ['auto', 'sqrt'],\n 'min_samples_leaf': [1, 2, 4],\n 'min_samples_split': [2, 5, 10],\n 'n_estimators': [200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000]}\n\nsvc_params = {'kernel' : ['linear', 'rbf', 'poly'],\n'gamma' : [0.1, 1, 10, 100],\n'C' : [0.1, 1, 10, 100, 1000],\n'degree' : [0, 1, 2, 3, 4, 5, 6]}\n\nmodels = [lr_model,rf_model,dt_model, knn_model, svc_model]\nparams = [lr_params,rf_params,dt_params, knn_params, svc_params]\ntuned_models = []\nimport time\ndef hyper_param_tuning(models,params,splits,scorer):\n    for i in range(len(models)):\n        gsearch = RandomizedSearchCV(estimator=models[i],\n                               param_distributions=params[i],\n                               scoring=scorer,\n                               verbose=2,\n                               n_jobs=-1,\n                               cv=5)\n        start = time.time()\n        gsearch.fit(X_train,y_train)\n        end = time.time()\n        \n        print(\"Grid Search Results for {}:\\n\".format(type(models[i]).__name__))\n        print(\"Time taken for tuning (in secs): \\n\", end-start)\n        print(\"Best parameters: \\n\",gsearch.best_params_)\n        print(\"Best score: \\n\",gsearch.best_score_)\n        tuned_models.append(gsearch.best_estimator_)\n        print(\"\\n\\n\")\nhyper_param_tuning(models,params,100,\"accuracy\")\ntuned_models\ndt_model_updated =  DecisionTreeClassifier(criterion='entropy', max_depth=81, min_samples_split=25,\n                        splitter='random')\ndt_model_updated.fit(X_train,y_train)\ny_pred_dt_updated = dt_model_updated.predict(test)\nsubmission1 = pd.DataFrame({\n        \"PassengerId\": passenger_id,\n        \"Survived\": y_pred_dt_updated\n    })\nsubmission1.to_csv('mysubmission7.csv', index=False)\n\"\"\"\n#### Decision Tree seems to be the most efficient classifier in predicting whether the passenger survived or not with accuracy of 0.78229 on a dataset which our model has never seen before.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1e576fd60ca589'}"}
{"id":"60677","text":"\"\"\"\n# This is a modeling notebook for [EDA about: LSTM Feature Importance](https:\/\/www.kaggle.com\/marutama\/eda-about-lstm-feature-importance).\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport gc\n\nimport optuna\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.callbacks import LearningRateScheduler, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers.schedules import ExponentialDecay\n\nfrom sklearn.metrics import mean_absolute_error as mae\nfrom sklearn.preprocessing import RobustScaler, normalize\nfrom sklearn.model_selection import train_test_split, GroupKFold, KFold\n\nfrom IPython.display import display\nDEBUG = False\n\ntrain = pd.read_csv('..\/input\/ventilator-pressure-prediction\/train.csv')\ntest = pd.read_csv('..\/input\/ventilator-pressure-prediction\/test.csv')\nsubmission = pd.read_csv('..\/input\/ventilator-pressure-prediction\/sample_submission.csv')\n\nif DEBUG:\n    train = train[:80*1000]\n# def add_features(df):\n#     # rewritten calculation of lag features from this notebook: https:\/\/www.kaggle.com\/patrick0302\/add-lag-u-in-as-new-feat\n#     # some of ideas from this notebook: https:\/\/www.kaggle.com\/mst8823\/google-brain-lightgbm-baseline\n#     df['last_value_u_in'] = df.groupby('breath_id')['u_in'].transform('last')\n#     df['u_in_lag1'] = df.groupby('breath_id')['u_in'].shift(1)\n#     df['u_out_lag1'] = df.groupby('breath_id')['u_out'].shift(1)\n#     df['u_in_lag_back1'] = df.groupby('breath_id')['u_in'].shift(-1)\n#     df['u_out_lag_back1'] = df.groupby('breath_id')['u_out'].shift(-1)\n#     df['u_in_lag2'] = df.groupby('breath_id')['u_in'].shift(2)\n#     df['u_out_lag2'] = df.groupby('breath_id')['u_out'].shift(2)\n#     df['u_in_lag_back2'] = df.groupby('breath_id')['u_in'].shift(-2)\n#     df['u_out_lag_back2'] = df.groupby('breath_id')['u_out'].shift(-2)\n#     df['u_in_lag3'] = df.groupby('breath_id')['u_in'].shift(3)\n#     df['u_out_lag3'] = df.groupby('breath_id')['u_out'].shift(3)\n#     df['u_in_lag_back3'] = df.groupby('breath_id')['u_in'].shift(-3)\n#     df['u_out_lag_back3'] = df.groupby('breath_id')['u_out'].shift(-3)\n#     df = df.fillna(0)\n\n\n#     df['R__C'] = df[\"R\"].astype(str) + '__' + df[\"C\"].astype(str)\n\n#     # max value of u_in and u_out for each breath\n#     df['breath_id__u_in__max'] = df.groupby(['breath_id'])['u_in'].transform('max')\n#     df['breath_id__u_out__max'] = df.groupby(['breath_id'])['u_out'].transform('max')\n\n#     # difference between consequitive values\n#     df['u_in_diff1'] = df['u_in'] - df['u_in_lag1']\n#     df['u_out_diff1'] = df['u_out'] - df['u_out_lag1']\n#     df['u_in_diff2'] = df['u_in'] - df['u_in_lag2']\n#     df['u_out_diff2'] = df['u_out'] - df['u_out_lag2']\n#     # from here: https:\/\/www.kaggle.com\/yasufuminakama\/ventilator-pressure-lstm-starter\n#     df.loc[df['time_step'] == 0, 'u_in_diff'] = 0\n#     df.loc[df['time_step'] == 0, 'u_out_diff'] = 0\n\n#     # difference between the current value of u_in and the max value within the breath\n#     df['breath_id__u_in__diffmax'] = df.groupby(['breath_id'])['u_in'].transform('max') - df['u_in']\n#     df['breath_id__u_in__diffmean'] = df.groupby(['breath_id'])['u_in'].transform('mean') - df['u_in']\n\n#     # OHE\n#     df = df.merge(pd.get_dummies(df['R'], prefix='R'), left_index=True, right_index=True).drop(['R'], axis=1)\n#     df = df.merge(pd.get_dummies(df['C'], prefix='C'), left_index=True, right_index=True).drop(['C'], axis=1)\n#     df = df.merge(pd.get_dummies(df['R__C'], prefix='R__C'), left_index=True, right_index=True).drop(['R__C'], axis=1)\n\n#     # https:\/\/www.kaggle.com\/c\/ventilator-pressure-prediction\/discussion\/273974\n#     df['u_in_cumsum'] = df.groupby(['breath_id'])['u_in'].cumsum()\n#     df['time_step_cumsum'] = df.groupby(['breath_id'])['time_step'].cumsum()\n#     return df\ndef add_features(df):\n    df['area'] = df['time_step'] * df['u_in']\n    df['area'] = df.groupby('breath_id')['area'].cumsum()\n\n    #######################################\n    # fast area calculation\n    df['time_delta'] = df['time_step'].diff()\n    df['time_delta'].fillna(0, inplace=True)\n    df['time_delta'].mask(df['time_delta'] < 0, 0, inplace=True)\n    df['tmp'] = df['time_delta'] * df['u_in']\n    df['area_true'] = df.groupby('breath_id')['tmp'].cumsum()\n    \n    #u_in_max_dict = df.groupby('breath_id')['u_in'].max().to_dict()\n    #df['u_in_max'] = df['breath_id'].map(u_in_max_dict)\n    #u_in_min_dict = df.groupby('breath_id')['u_in'].min().to_dict()\n    #df['u_in_min'] = df['breath_id'].map(u_in_min_dict)\n    u_in_mean_dict = df.groupby('breath_id')['u_in'].mean().to_dict()\n    df['u_in_mean'] = df['breath_id'].map(u_in_mean_dict)\n    del u_in_mean_dict\n    u_in_std_dict = df.groupby('breath_id')['u_in'].std().to_dict()\n    df['u_in_std'] = df['breath_id'].map(u_in_std_dict)\n    del u_in_std_dict\n    \n    # u_in_half is time:0 - time point of u_out:1 rise (almost 1.0s)\n    df['tmp'] = df['u_out']*(-1)+1 # inversion of u_out\n    df['u_in_half'] = df['tmp'] * df['u_in']\n    \n    # u_in_half: max, min, mean, std\n    u_in_half_max_dict = df.groupby('breath_id')['u_in_half'].max().to_dict()\n    df['u_in_half_max'] = df['breath_id'].map(u_in_half_max_dict)\n    del u_in_half_max_dict\n    u_in_half_min_dict = df.groupby('breath_id')['u_in_half'].min().to_dict()\n    df['u_in_half_min'] = df['breath_id'].map(u_in_half_min_dict)\n    del u_in_half_min_dict\n    u_in_half_mean_dict = df.groupby('breath_id')['u_in_half'].mean().to_dict()\n    df['u_in_half_mean'] = df['breath_id'].map(u_in_half_mean_dict)\n    del u_in_half_mean_dict\n    u_in_half_std_dict = df.groupby('breath_id')['u_in_half'].std().to_dict()\n    df['u_in_half_std'] = df['breath_id'].map(u_in_half_std_dict)\n    del u_in_half_std_dict\n    \n    gc.collect()\n    \n    # All entries are first point of each breath_id\n    first_df = df.loc[0::80,:]\n    # All entries are first point of each breath_id\n    last_df = df.loc[79::80,:]\n    \n    # The Main mode DataFrame and flag\n    main_df= last_df[(last_df['u_in']>4.8)&(last_df['u_in']<5.1)]\n    main_mode_dict = dict(zip(main_df['breath_id'], [1]*len(main_df)))\n    df['main_mode'] = df['breath_id'].map(main_mode_dict)\n    df['main_mode'].fillna(0, inplace=True)\n    del main_df\n    del main_mode_dict\n\n    # u_in: first point, last point\n    u_in_first_dict = dict(zip(first_df['breath_id'], first_df['u_in']))\n    df['u_in_first'] = df['breath_id'].map(u_in_first_dict)\n    del u_in_first_dict\n    u_in_last_dict = dict(zip(first_df['breath_id'], last_df['u_in']))\n    df['u_in_last'] = df['breath_id'].map(u_in_last_dict)\n    del u_in_last_dict\n    # time(sec) of end point\n    time_end_dict = dict(zip(last_df['breath_id'], last_df['time_step']))     \n    df['time_end'] = df['breath_id'].map(time_end_dict)\n    del time_end_dict\n    del last_df\n    \n    # u_out1_timing flag and DataFrame: speed up\n    # \u9ad8\u901f\u7248 uout1_df \u4f5c\u6210\n    df['u_out_diff'] = df['u_out'].diff()\n    df['u_out_diff'].fillna(0, inplace=True)\n    df['u_out_diff'].replace(-1, 0, inplace=True)\n    uout1_df = df[df['u_out_diff']==1]\n    \n    gc.collect()\n    \n    #main_uout1 = uout1_df[uout1_df['main_mode']==1]\n    #nomain_uout1 = uout1_df[uout1_df['main_mode']==1]\n    \n    # Register Area when u_out becomes 1\n    uout1_area_dict = dict(zip(first_df['breath_id'], first_df['u_in']))\n    df['area_uout1'] = df['breath_id'].map(uout1_area_dict)\n    del uout1_area_dict\n    \n    # time(sec) when u_out becomes 1\n    uout1_dict = dict(zip(uout1_df['breath_id'], uout1_df['time_step']))\n    df['time_uout1'] = df['breath_id'].map(uout1_dict)\n    del uout1_dict\n    \n    # u_in when u_out becomes1\n    u_in_uout1_dict = dict(zip(uout1_df['breath_id'], uout1_df['u_in']))\n    df['u_in_uout1'] = df['breath_id'].map(u_in_uout1_dict)\n    del u_in_uout1_dict\n    \n    # Dict that puts 0 at the beginning of the 80row cycle\n    first_0_dict = dict(zip(first_df['id'], [0]*len(uout1_df)))\n\n    del first_df\n    del uout1_df   \n    \n    gc.collect()\n    \n    # Faster version u_in_diff creation, faster than groupby\n    df['u_in_diff'] = df['u_in'].diff()\n    df['tmp'] = df['id'].map(first_0_dict) # put 0, the 80row cycle\n    df.iloc[0::80, df.columns.get_loc('u_in_diff')] = df.iloc[0::80, df.columns.get_loc('tmp')]\n\n    # Create u_in vibration\n    df['diff_sign'] = np.sign(df['u_in_diff'])\n    df['sign_diff'] = df['diff_sign'].diff()\n    df['tmp'] = df['id'].map(first_0_dict) # put 0, the 80row cycle\n    df.iloc[0::80, df.columns.get_loc('sign_diff')] = df.iloc[0::80, df.columns.get_loc('tmp')]\n    del first_0_dict\n    \n    # Count the number of inversions, so take the absolute value and sum\n    df['sign_diff'] = abs(df['sign_diff']) \n    sign_diff_dict = df.groupby('breath_id')['sign_diff'].sum().to_dict()\n    df['diff_vib'] = df['breath_id'].map(sign_diff_dict)\n    \n    if 'diff_sign' in df.columns:\n        df.drop(['diff_sign', 'sign_diff'], axis=1, inplace=True)\n    if 'tmp' in df.columns:\n        df.drop(['tmp'], axis=1, inplace=True)\n    \n    gc.collect()\n    #######################################\n    '''\n    '''\n    \n    df['u_in_cumsum'] = (df['u_in']).groupby(df['breath_id']).cumsum()\n    \n    df['u_in_lag1'] = df.groupby('breath_id')['u_in'].shift(1)\n    #df['u_out_lag1'] = df.groupby('breath_id')['u_out'].shift(1)\n    df['u_in_lag_back1'] = df.groupby('breath_id')['u_in'].shift(-1)\n    #df['u_out_lag_back1'] = df.groupby('breath_id')['u_out'].shift(-1)\n    df['u_in_lag2'] = df.groupby('breath_id')['u_in'].shift(2)\n    #df['u_out_lag2'] = df.groupby('breath_id')['u_out'].shift(2)\n    df['u_in_lag_back2'] = df.groupby('breath_id')['u_in'].shift(-2)\n    #df['u_out_lag_back2'] = df.groupby('breath_id')['u_out'].shift(-2)\n    df['u_in_lag3'] = df.groupby('breath_id')['u_in'].shift(3)\n    #df['u_out_lag3'] = df.groupby('breath_id')['u_out'].shift(3)\n    df['u_in_lag_back3'] = df.groupby('breath_id')['u_in'].shift(-3)\n    #df['u_out_lag_back3'] = df.groupby('breath_id')['u_out'].shift(-3)\n    df['u_in_lag4'] = df.groupby('breath_id')['u_in'].shift(4)\n    #df['u_out_lag4'] = df.groupby('breath_id')['u_out'].shift(4)\n    df['u_in_lag_back4'] = df.groupby('breath_id')['u_in'].shift(-4)\n    #df['u_out_lag_back4'] = df.groupby('breath_id')['u_out'].shift(-4)\n    df = df.fillna(0)\n    \n    #df['breath_id__u_in__max'] = df.groupby(['breath_id'])['u_in'].transform('max')\n    df['breath_id__u_out__max'] = df.groupby(['breath_id'])['u_out'].transform('max')\n    \n    df['u_in_diff1'] = df['u_in'] - df['u_in_lag1']\n    #df['u_out_diff1'] = df['u_out'] - df['u_out_lag1']\n    df['u_in_diff2'] = df['u_in'] - df['u_in_lag2']\n    #df['u_out_diff2'] = df['u_out'] - df['u_out_lag2']\n    \n    #df['breath_id__u_in__diffmax'] = df.groupby(['breath_id'])['u_in'].transform('max') - df['u_in']\n    df['breath_id__u_in__diffmean'] = df.groupby(['breath_id'])['u_in'].transform('mean') - df['u_in']\n    \n    df['u_in_diff3'] = df['u_in'] - df['u_in_lag3']\n    #df['u_out_diff3'] = df['u_out'] - df['u_out_lag3']\n    df['u_in_diff4'] = df['u_in'] - df['u_in_lag4']\n    #df['u_out_diff4'] = df['u_out'] - df['u_out_lag4']\n    #df['cross']= df['u_in']*df['u_out']\n    #df['cross2']= df['time_step']*df['u_out']\n    \n    df['R_'] = df['R'].astype(str)\n    df['C_'] = df['C'].astype(str)\n    df['R__C'] = df[\"R\"].astype(str) + '__' + df[\"C\"].astype(str)\n      \n    df = pd.get_dummies(df)\n    \n    # Drop an unimportant features\n    df.drop(['R__C_20__20', 'R__C_20__10', 'R__C_5__10', 'R__C_5__10', 'R__20', 'R__50', 'C__20'], axis=1, inplace=True)\n    \n    return df\n%%time\ntrain = add_features(train)\n%%time\ntest = add_features(test)\ntrain.head()\ntargets = train[['pressure']].to_numpy().reshape(-1, 80)\ntrain.drop(['pressure', 'id', 'breath_id'], axis=1, inplace=True)\ntest = test.drop(['id', 'breath_id'], axis=1)\nRS = RobustScaler()\ntrain = RS.fit_transform(train)\ntest = RS.transform(test)\ntrain = train.reshape(-1, 80, train.shape[-1])\ntest = test.reshape(-1, 80, train.shape[-1])\nfrom tensorflow.keras.callbacks import Callback\nimport tensorflow.keras.backend as K\nclass WarmupExponentialDecay(Callback):\n    def __init__(self,lr_base=0.0002,lr_min=0.0,decay=0,warmup_epochs=0):\n        self.num_passed_batchs = 0   #\u4e00\u4e2a\u8ba1\u6570\u5668\n        self.warmup_epochs=warmup_epochs  \n        self.lr=lr_base #learning_rate_base\n        self.lr_min=lr_min #\u6700\u5c0f\u7684\u8d77\u59cb\u5b66\u4e60\u7387,\u6b64\u4ee3\u7801\u5c1a\u672a\u5b9e\u73b0\n        self.decay=decay  #\u6307\u6570\u8870\u51cf\u7387\n        self.steps_per_epoch=0 #\u4e5f\u662f\u4e00\u4e2a\u8ba1\u6570\u5668\n        \n    def on_batch_begin(self, batch, logs=None):\n        # params\u662f\u6a21\u578b\u81ea\u52a8\u4f20\u9012\u7ed9Callback\u7684\u4e00\u4e9b\u53c2\u6570\n        if self.steps_per_epoch==0:\n            #\u9632\u6b62\u8dd1\u9a8c\u8bc1\u96c6\u7684\u65f6\u5019\u5457\u66f4\u6539\u4e86\n            if self.params['steps'] == None:\n                self.steps_per_epoch = np.ceil(1. * self.params['samples'] \/ self.params['batch_size'])\n            else:\n                self.steps_per_epoch = self.params['steps']\n        if self.num_passed_batchs < self.steps_per_epoch * self.warmup_epochs:\n            K.set_value(self.model.optimizer.lr,\n                        self.lr*(self.num_passed_batchs + 1) \/ self.steps_per_epoch \/ self.warmup_epochs)\n        else:\n            K.set_value(self.model.optimizer.lr,\n                        self.lr*((1-self.decay)**(self.num_passed_batchs-self.steps_per_epoch*self.warmup_epochs)))\n        self.num_passed_batchs += 1\n        \n    def on_epoch_begin(self,epoch,logs=None):\n        #\u7528\u6765\u8f93\u51fa\u5b66\u4e60\u7387\u7684,\u53ef\u4ee5\u5220\u9664\n        print(\"learning_rate:\",K.get_value(self.model.optimizer.lr))\nEPOCH = 300\nBATCH_SIZE = 1024\nNUM_FOLDS = 10\n\nTPU = False\n\nif TPU:\n    # detect and init the TPU\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()\n\n    ## instantiate a distribution strategy\n    xpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # GET GPU STRATEGY\n    xpu_strategy = tf.distribute.get_strategy()\n\nwith xpu_strategy.scope():\n    kf = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=2021)\n    test_preds = []\n    for fold, (train_idx, test_idx) in enumerate(kf.split(train, targets)):\n        print('-'*15, '>', f'Fold {fold+1}', '<', '-'*15)\n        X_train, X_valid = train[train_idx], train[test_idx]\n        y_train, y_valid = targets[train_idx], targets[test_idx]\n        model = keras.models.Sequential([\n            keras.layers.Input(shape=train.shape[-2:]),\n            keras.layers.Bidirectional(keras.layers.LSTM(1024, return_sequences=True)),\n            keras.layers.Bidirectional(keras.layers.LSTM(512, return_sequences=True)),\n            keras.layers.Bidirectional(keras.layers.LSTM(256, return_sequences=True)),\n            keras.layers.Bidirectional(keras.layers.LSTM(128, return_sequences=True)),\n#             keras.layers.Bidirectional(keras.layers.LSTM(128, return_sequences=True)),\n            keras.layers.Dense(128, activation='selu'),\n#             keras.layers.Dropout(0.1),\n            keras.layers.Dense(1),\n        ])\n        model.compile(optimizer=\"adam\", loss=\"mae\")\n\n#         scheduler = ExponentialDecay(1e-3, 40*((len(train)*0.8)\/BATCH_SIZE), 1e-5)\n#         lr = LearningRateScheduler(scheduler, verbose=1)\n        lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.5, patience=10, verbose=1)\n#         lr = WarmupExponentialDecay(lr_base=1e-3, decay=1e-5, warmup_epochs=30)\n        es = EarlyStopping(monitor=\"val_loss\", patience=60, verbose=1, mode=\"min\", restore_best_weights=True)\n    \n        checkpoint_filepath = f\"folds{fold}.hdf5\"\n        sv = keras.callbacks.ModelCheckpoint(\n            checkpoint_filepath, monitor='val_loss', verbose=1, save_best_only=True,\n            save_weights_only=False, mode='auto', save_freq='epoch',\n            options=None\n        )\n\n        model.fit(X_train, y_train, validation_data=(X_valid, y_valid), epochs=EPOCH, batch_size=BATCH_SIZE, callbacks=[lr, es, sv])\n        #model.save(f'Fold{fold+1} RNN Weights')\n        test_preds.append(model.predict(test).squeeze().reshape(-1, 1).squeeze())\n!ls .\/\nsubmission[\"pressure\"] = sum(test_preds)\/NUM_FOLDS\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '6fd7d242c4e95f'}"}
{"id":"44008","text":"\"\"\"\n#### In this notebook, we show a full GPU pipleline from ETL to XGB training. We compare two xgboost models with different depth and number of trees. The notebook is adapted from [FARES SAYAH's wonderful notebook](https:\/\/www.kaggle.com\/faressayah\/credit-card-fraud-detection-anns-vs-xgboost). \n\"\"\"\nimport cudf\nimport cupy\nimport xgboost as xgb\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\nsns.set_style(\"whitegrid\")\ndata = cudf.read_csv(\"\/kaggle\/input\/creditcardfraud\/creditcard.csv\")\ndata['Class'] = data['Class'].astype('float32')\ndata.head()\n\"\"\"\n# 2. Exploratory Data Analysis\n\n\"\"\"\nprint(\"Number of missing values:\")\ndata.isnull().sum().sum()\n\"\"\"\n### The only non-transformed variables to work with are:\n- `Time`\n- `Amount`\n- `Class` (1: fraud, 0: not_fraud)\n\"\"\"\ncount_classes = data['Class'].value_counts(sort=True)\ncount_classes\n\"\"\"\nNotice how imbalanced is our original dataset! Most of the transactions are non-fraud. If we use this dataframe as the base for our predictive models and analysis we might get a lot of errors and our algorithms will probably overfit since it will \"assume\" that most transactions are not fraud. But we don't want our model to assume, we want our model to detect patterns that give signs of fraud!\n\"\"\"\nfraud = data[data['Class']==1]\nnormal = data[data['Class']==0]\n\nprint(f\"Shape of Fraudulant transactions: {fraud.shape}\")\nprint(f\"Shape of Non-Fraudulant transactions: {normal.shape}\")\n\"\"\"\nHow different are the amount of money used in different transaction classes?\n\"\"\"\na_fraud = fraud.Amount.describe().to_frame().transpose()\na_normal = normal.Amount.describe().to_frame().transpose()\namount = cudf.concat([a_fraud,a_normal],axis=0)\namount.index = ['fraud','normal']\nprint(\"Amount: fraud vs normal\")\namount\n\"\"\"\nDo fraudulent transactions occur more often during certain time frame ?\n\"\"\"\nt_fraud = fraud.Time.describe().to_frame().transpose()\nt_normal = normal.Time.describe().to_frame().transpose()\ntime = cudf.concat([t_fraud,t_normal],axis=0)\ntime.index = ['fraud','normal']\nprint(\"Time: fraud vs normal\")\ntime\n# plot the time feature\nplt.figure(figsize=(10,8))\n\nplt.subplot(2, 2, 1)\nplt.title('Time Distribution (Seconds)')\n\nsns.distplot(data['Time'].values.get(), color='blue');\n\n#plot the amount feature\nplt.subplot(2, 2, 2)\nplt.title('Distribution of Amount')\nsns.distplot(data['Amount'].values.get(),color='blue');\n# data[data.Class == 0].Time.hist(bins=35, color='blue', alpha=0.6)\nplt.figure(figsize=(12, 10))\n\nplt.subplot(2, 2, 1)\ndata[data.Class == 1].Time.to_pandas().hist(bins=35, color='blue', alpha=0.6, label=\"Fraudulant Transaction\")\nplt.legend()\n\nplt.subplot(2, 2, 2)\ndata[data.Class == 0].Time.to_pandas().hist(bins=35, color='blue', alpha=0.6, label=\"Non Fraudulant Transaction\")\nplt.legend()\n\"\"\"\nBy seeing the distributions we can have an idea how skewed are these features, we can also see further distributions of the other features. There are techniques that can help the distributions be less skewed which will be implemented in this notebook in the future.\n\nDoesn't seem like the time of transaction really matters here as per above observation.\nNow let us take a sample of the dataset for out modelling and prediction\n\"\"\"\n\"\"\"\n# 3. Data Pre-processing\n\n`Time` and `Amount` should be scaled as the other columns.\n\"\"\"\nfrom cuml.model_selection import train_test_split\nfrom cuml.preprocessing import StandardScaler\n\nscalar = StandardScaler()\n\nX = data.drop('Class', axis=1)\ny = data.Class\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n                                                    test_size=0.3, random_state=42)\ny_train.mean(), y_test.mean()\nprint(f\"TRAINING: X_train: {X_train.shape}, y_train: {y_train.shape}\\n{'_'*55}\")\nprint(f\"TESTING: X_test: {X_test.shape}, y_test: {y_test.shape}\")\n\"\"\"\n# XGB Training\n\"\"\"\n\"\"\"\n#### Model 1 (big): \n- `max_depth = 10`\n- `num_trees = 300`\n\"\"\"\nmax_depth = 10\nnum_trees = 300\n\nparams = {\n            'eta':0.1,\n            'objective': 'binary:logistic',\n            'eval_metric': 'error',\n            'tree_method': 'gpu_hist',\n            'max_depth': max_depth,\n            'predictor': 'gpu_predictor'\n        }\ndtrain = xgb.DMatrix(data=X_train, label=y_train)\ndtest = xgb.DMatrix(data=X_test, label=y_test)\nwatchlist = [(dtrain, 'train'), (dtest, 'test')] \n\nbst = xgb.train(params, dtrain=dtrain,\n    num_boost_round=num_trees,evals=watchlist,\n    verbose_eval=100)\n\"\"\"\n#### Model 2 (small): \n- `max_depth = 3`\n- `num_trees = 50`\n\"\"\"\nmax_depth = 3\nnum_trees = 50\n\nparams = {\n            'eta':0.1,\n            'objective': 'binary:logistic',\n            'eval_metric': 'error',\n            'tree_method': 'gpu_hist',\n            'max_depth': max_depth,\n            'predictor': 'gpu_predictor'\n        }\ndtrain = xgb.DMatrix(data=X_train, label=y_train)\ndtest = xgb.DMatrix(data=X_test, label=y_test)\nwatchlist = [(dtrain, 'train'), (dtest, 'test')] \n\nbst = xgb.train(params, dtrain=dtrain,\n    num_boost_round=num_trees,evals=watchlist,\n    verbose_eval=10)","meta":"{'source': 'AI4Code', 'id': '512c90ba34745d'}"}
{"id":"125832","text":"\"\"\"\n# Data Importing\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndataset = pd.read_csv(\"..\/input\/Level of education of female in BD by residence of 5 years since 2008.csv\")\nprint(dataset)\ninput_data = dataset.values\nprint(input_data)\ndataset.head()\ndataset.info()\n\"\"\"\n# Examine the properties of the dataset\n\"\"\"\nprint(dataset['National'].describe())\n\"\"\"\n# Performing EDA\n\"\"\"\n\"\"\"\n# Scatter Plot\n\"\"\"\n             #Rural VS National\nprint(\"-------------Scatter Plot: Rural vs National -----------\")\nx_Rural = input_data[:,2] \ny_National = input_data[:,1]\nplt.scatter(x_Rural,y_National)\nplt.show()\n             #Urban VS National\nprint(\"-------------Scatter Plot: Urban vs National -----------\")\nx_Urban = input_data[:,3]\ny_National = input_data[:,1]\nplt.scatter(x_Urban,y_National)\nplt.show()\n\"\"\"\n# Boxplot\n\"\"\"\ndataset.boxplot()\n\"\"\"\n# Histogram\n\"\"\"\ndataset.hist()\n\"\"\"\n# Pie Chart\n\"\"\"\ndf = pd.DataFrame({'Classpassed': ['National', 'Rural', 'Urban'], 'Schooling': [35.4, 38.1,26.5]})\n\ndf.Schooling.groupby(df.Classpassed).sum().plot(kind='pie')\nplt.axis('equal')\nplt.show()\n\"\"\"\n# Bar Chart\n\"\"\"\ndf=dataset.copy()\nw=df.groupby(['Class passed'])['National'].sum().sort_values(ascending=False).head(9).reset_index()\nx=df.groupby(['Class passed'])['Rural'].sum().sort_values(ascending=False).head(9).reset_index()\ny=df.groupby(['Class passed'])['Urban'].sum().sort_values(ascending=False).head(9).reset_index()\nz=w.merge(x,on=['Class passed']).merge(y,on=['Class passed'])\nz.plot(x='Class passed',y=['National','Rural','Urban'], kind=\"bar\",figsize=(9,4))\n\"\"\"\n# Multiple Linear Regression\n\n\"\"\"\nimport statsmodels.formula.api as sm\nad = pd.read_csv(\"..\/input\/Level of education of female in BD by residence of 5 years since 2008.csv\", index_col=0)\nad.corr()\nmodelAll = sm.ols('National ~ Rural + Urban', ad).fit()\nmodelAll.params","meta":"{'source': 'AI4Code', 'id': 'e7754341a4ba69'}"}
{"id":"96419","text":"\"\"\"\n# <center> Personality Profile Predictions <\/center>\n\"\"\"\n\"\"\"\n___________________________________________________________________________________________________________________________________________________\n\"\"\"\n\"\"\"\n# Table of contents\n\"\"\"\n\"\"\"\n1. [Introduction](#1)\n2. [Importing libraries](#2)\n3. [Importing data](#3)\n3. [Creating required functions](#4)\n4. [EDA and feature engineering](#5)\n5. [Train preprocessing](#6)\n6. [Test preprocessing](#7)\n7. [Vectorization](#8)\n8. [Model fitting and predicting](#9)\n    * [Mind](#10)\n    * [Energy](#11)\n    * [Nature](#12)\n    * [Tactics](#13)\n    \n9. [Prepared submission](#14)\n10. [Still to do](#15) \n11. [Acknowledgements](#16)\n\n\"\"\"\n\"\"\"\n\n<a id='1'><\/a>\n___________________________________________________________________________________________________________________________________________________\n\"\"\"\n\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\n<div style=\"text-align: justify\">The Myers-Briggs Type Indicator (mbti) categories individuals into 16 different personality types using four opposite pairs of variables represented by a letter or word. These letters each represent a characteristic that groups interests, needs and values together. The MBTI personality type binary variables are: Mind: Introverted (I) or Extraverted (E) Energy: Sensing (S) or Intuitive (N) Nature: Feeling (F) or Thinking (T) Tactics: Perceiving (P) or Judging (J) An individual's final type is made up of one of the variables combined. For example an individual with INFP type would have a combination of Introverted(I), Intuitive (N), Feeling (F) and Perceiving (P). <\/div>\n\n<div style=\"text-align: justify\"> The common way of finding out your persoanlity type is to take a personality type test on a websites, where they would determine your personality type from the different questions you have to answer about yourself.\nIn this notebook, I will build a model that will predict the personality of a person from their twitter post. We will predict four separate labels for each person which, when combined, results in that person's personality type just like the example. The data is available on kaggle competition.<\/div>\n\nFor more info about the MBTI personality types click [here](https:\/\/www.16personalities.com\/personality-types) OR the test click [here to take the test](https:\/\/www.16personalities.com\/free-personality-test)\n\"\"\"\n\"\"\"\n[Return to index](#index)\n<a id='2'><\/a>\n___________________________________________________________________________________________________________________________________________________\n\"\"\"\n\"\"\"\n# Importing libraries\n\"\"\"\n#Standard Python libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n#Natural language processing libraries\nimport nltk\nimport re\n\nimport time\n\n#Interactive computing\nfrom IPython.core.magics.execution import _format_time\nfrom IPython.display import display as d\nfrom IPython.display import Audio\nfrom IPython.core.display import HTML\n\n#Accountability\nimport logging as log\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='3'><\/a>\n\"\"\"\n\"\"\"\n# Importing data\n\"\"\"\n\"\"\"\nWe loaded our data (train.csv and test.csv) and inspected. This helped to see where we can start with feature engineering. \n\"\"\"\ntrain_df = pd.read_csv('..\/input\/train.csv')\ntrain_df.head()\ntest = pd.read_csv('..\/input\/test.csv')\ntest.head()\n#Checking if we have all sixteen personality types represented\nPersonalities = train_df.groupby(\"type\").count()\nPersonalities.sort_values(\"posts\", ascending=False, inplace=True)\nPersonalities.index.values\n\"\"\"\nAbove output shows the 'type' column contains 16 unique codes, representing the 16 different personality types.\n\"\"\"\n\"\"\"\n### Distribution of Myers-Briggs Personality Types in the Dataset\n\"\"\"\n#Visualizing the distribution of the personality types\ncount_types = train_df['type'].value_counts()\nplt.figure(figsize=(10,5))\nsns.barplot(count_types.index, count_types.values, alpha=1, palette=\"winter\")\nplt.ylabel('No of persons', fontsize=12)\nplt.xlabel('personality Types', fontsize=12)\nplt.title('Distribution of personality types')\nplt.show()\n\"\"\"\nThe bar chart above shows that INFP (Introversion - Intuition - Feeling - Perceiving) is the most frequently appearing type in the dataset, followed by INFJ (Introversion - Intuition - Feeling - Judging). Overall, the dataset contains many more Intuitive-Intuition (IN-) groupings than any other type. Conversely, the dataset contains very few Extroversion-Sensing (ES-) types.\n\"\"\"\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='4'><\/a>\n\"\"\"\n\"\"\"\n# Function creation\n\"\"\"\n\"\"\"\nIn cleaning and exploring our data we built some functions that will help remove and transform our features that make machine learning algorithms work. We created the 'alert' function for the long running time cells, this will alert us when they are done running. The 'link transformer' function opens the link address in the data frame to find title names of the url. It then replaces the url with the title. The 'remove urls' function removes urls and replace it with web-link. The function 'no_punc_num' removes numbers and puntuation. The 'lemmatized' function lemmatizes our words using WordNetLemmatizer. Lastly, we created 'remove_stop_words' function which removed stop words that we will decide not to use.\n\"\"\"\ndef alert():\n    \"\"\" makes sound on client using javascript\"\"\"  \n    \n    framerate = 44100\n    duration=0.5\n    freq=340\n    t = np.linspace(0,duration,framerate*duration)\n    data = np.sin(2*np.pi*freq*t)\n    d(Audio(data,rate=framerate, autoplay=True))\ndef link_transformer(df, column, reports=True):\n    \"\"\"Search over a column in a pandas dataframe for urls.\n    \n    extract the title related to the url then replace the url with the title.\n    \n    \n    df : pandas Dataframe object\n    \n    column: string type object equal to the exact name of the colum you want to replace the urls\n    \n    reports: Boolean Value (default=True)\n        If true give active report updates on the last index completed and the ammount of reported fail title extractions\n   \n    \"\"\"\n    \n    total_errors = 0\n    count = 0\n    from mechanize import Browser\n    br = Browser()\n    \n    while count != len(df):\n        errors = 0\n        \n        url = re.findall(r'http[s]?:\/\/(?:[A-Za-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9A-Fa-f][0-9A-Fa-f]))+', df.loc[count, column])\n        \n        for link in url:\n            try: \n                br.open(link)\n                df.loc[count, column] = df.loc[count, column].replace(link, br.title())\n            except:\n                \n                if reports == True:\n                    print(f'failed--- {link}')\n                elif reports == False:\n                    pass\n                else:\n                    raise ValueError('reports expected a boolean value')\n                \n                total_errors += 1\n                errors += 1\n                \n                continue\n                \n        if reports == True:\n            if errors == 0:\n                report = 'no errors'\n                errors = ''\n            elif errors == 1:\n                report = 'error'\n            else:\n                report = 'errors'\n            print(f'\\nIndex {count + 1} completed. {errors} {report} reported\\n______________________\\n\\n')\n    \n        elif reports == False:\n            pass\n        \n        else:\n            raise ValueError('reports expected a boolean value')\n                \n        \n        count += 1\n    print(f'{total_errors} total errors throughout full runtime')\n    \n#example\n\n#sample = pd.read_csv('train.csv').sample(3, random_state=20).reset_index(drop=True)\n#sample\n\n#link_transformer(sample, 'posts')\n\n#sample\ndef remove_links(df, column):\n    \"\"\"Replace urls by searching for the characters normally found in urls \n    and replace the string found with the string web-link\n    \n    df : pandas Dataframe object\n    \n    column: string type object equal to the exact name of the colum you want to replace the urls\n    \"\"\"\n    \n    return df[column].replace(r'http[s]?:\/\/(?:[A-Za-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9A-Fa-f][0-9A-Fa-f]))+', \n                           r'web-link', regex=True, inplace=True)\ndef no_punc_num(post):\n    \"\"\"The function imports punctuation and define numbers then removes them from a column in a dataframe \n    using a for loop.\n    \n    to use, use pd.DataFrame.apply() on a Dataframe object\"\"\"\n    \n    from string import punctuation\n    pun_num = punctuation + '1234567890'\n    return ''.join([letter for letter in post if letter not in pun_num])\ntokens = nltk.tokenize.TreebankWordTokenizer()\nlem = nltk.stem.WordNetLemmatizer()\ndef lemmatized(words, lemmatizer):\n    \"\"\"Transform a list of words into base forms \n    \n    example: hippopotami = hippopotamus\n\n\n    Required imports  \n   ------------------\n    nltk.stem.WordNetLemmatizer()\n    \n    \n    Parameters \n   ------------\n   lemmatizer: nltk.stem.WordNetLemmatizer() object\n   \n   \n   to use, use pd.DataFrame.apply() on a Dataframe object \n    \"\"\"\n    return [lemmatizer.lemmatize(word) for word in words]\ndef remove_stop_words(tokens):\n    \"\"\"Removes a list of words from a Dataframe\n    \n    Required imports  \n   ------------------\n    A list of stopwords to remove\n    \n    \n    to use, use pd.DataFrame.apply() on a Dataframe object  \n    \"\"\"\n    return [t for t in tokens if t not in stopwords]\n\"\"\"\n# Feature engineering\n\"\"\"\n\"\"\"\nTo start with our feature engineering we started by spitting the sentences. (|||) indicated where a sentece started or ended so we split the sentence were we find (|||). We tokenized and lammatized our sentences. Then we created a bag of words. We grouped the lemmatized words that were used per type, this we can see which words were mostly used by certain personality types and create stopwords for each variable.   \n\"\"\"\n#Splitting sentences\ntrain = []\nfor types, posts in train_df.iterrows():\n    for split_at in posts['posts'].split('|||'):\n        train.append([posts['type'], split_at])\ntrain = pd.DataFrame(train, columns=['type', 'post'])\ntrain.head()\n#making all the words lowwer case\ntrain.post = train.post.str.lower()\n#removing punctuation and numbers\ntrain.post = train.post.apply(no_punc_num)\n#tokenizing words\ntrain['tokenized'] = train.post.apply(tokens.tokenize)\n#lemmatizing words\ntrain['lemmatized'] = train.tokenized.apply(lemmatized, args=(lem,))\ndef bag_count(word, bag={}):\n    '''text vectorize by representing every word as a integer and counting the frequency of appearence'''\n    for w in word:\n        if w not in bag.keys():\n            bag[w] = 1\n        else:\n            bag[w] += 1\n    return bag\n\nper_type = {}\nfor pt in list(train.type.unique()):\n    df = train.groupby('type')\n    per_type[pt] = {}\n    for row in df.get_group(pt)['lemmatized']:\n        per_type[pt] = bag_count(row, per_type[pt])\n\nlen(per_type.keys())\n#creating a list of unique words\nunique_words = set()\nfor pt in list(train.type.unique()):\n    for word in per_type[pt]:\n        unique_words.add(word)\nunique_words\npersonality_stop_words = list(per_type.keys())\n#finding the frequency of words\nper_type['all'] = {}\nfor tp in list(train.type.unique()):\n    for word in unique_words:\n        if word in per_type[tp].keys():\n            if word not in per_type['all']:\n                per_type['all'][word] = per_type[tp][word]\n            else:\n                per_type['all'][word] += per_type[tp][word] \nper_type['all']\nprint(len(per_type['all']))\n#Appearence of a word longer that 2 standard deviations in percentage\n(sum([v for v in per_type['all'].values() if v >= 43]))\/sum([v for v in per_type['all'].values()])\n#Checking the words\nword_index = [k for k, v in per_type['all'].items() if v > 43]\n#using for loop to find word usage per type\nper_type_words = []\nfor pt, p_word in per_type.items():\n    word_useage = pd.DataFrame([(k, v) for k, v in p_word.items() if k in word_index], columns=['Word', pt])\n    word_useage.set_index('Word', inplace=True)\n    per_type_words.append(word_useage)\nword_useage = pd.concat(per_type_words, axis=1)\nword_useage.fillna(0, inplace=True)\nword_useage.sample(10)\npersonality_stop_words\n#Finding sum of the word usage and identifying them to each variable\n\nI = [x for x in personality_stop_words if x[0] == 'I']\nE = [x for x in personality_stop_words if x[0] == 'E']\nword_useage['I'] = word_useage[I].sum(axis=1)\nword_useage['E'] = word_useage[E].sum(axis=1)\n\nS = [x for x in personality_stop_words if x[1] == 'S']\nN = [x for x in personality_stop_words if x[1] == 'N']\nword_useage['S'] = word_useage[S].sum(axis=1)\nword_useage['N'] = word_useage[N].sum(axis=1)\n\nF = [x for x in personality_stop_words if x[2] == 'F']\nT = [x for x in personality_stop_words if x[2] == 'T']\nword_useage['F'] = word_useage[F].sum(axis=1)\nword_useage['T'] = word_useage[T].sum(axis=1)\n\nP = [x for x in personality_stop_words if x[3] == 'P']\nJ = [x for x in personality_stop_words if x[3] == 'J']\nword_useage['P'] = word_useage[P].sum(axis=1)\nword_useage['J'] = word_useage[J].sum(axis=1)\nword_useage.sample(10)\n#Word usage in percentage form\nfor col in ['I', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\nfor col in ['E', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\n\nfor col in ['S', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\nfor col in ['N', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\n\nfor col in ['F', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\nfor col in ['T', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\n\nfor col in ['P', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\nfor col in ['J', 'all']:\n    word_useage[col+'_perc'] = word_useage[col] \/ word_useage[col].sum()\nword_useage.sample(1)\nstopwords = nltk.corpus.stopwords.words('english')\n#Word usage in percentage form for each variable \nword_useage['I chi2'] = np.power((word_useage['I_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\nword_useage['E chi2'] = np.power((word_useage['E_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\n\nword_useage['S chi2'] = np.power((word_useage['S_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\nword_useage['N chi2'] = np.power((word_useage['N_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\n\nword_useage['F chi2'] = np.power((word_useage['F_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\nword_useage['T chi2'] = np.power((word_useage['T_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\n\nword_useage['P chi2'] = np.power((word_useage['P_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\nword_useage['J chi2'] = np.power((word_useage['J_perc'] - word_useage['all_perc']), 2) \/ word_useage['all_perc'].astype(np.float64)\nI_words = word_useage[['I_perc', 'all_perc', 'I chi2']][(word_useage['I_perc'] > word_useage['all_perc'])].sort_values(by='I chi2', ascending=False)\nE_words = word_useage[['E_perc', 'all_perc', 'E chi2']][word_useage['E_perc'] > word_useage['all_perc']].sort_values(by='E chi2', ascending=False)\n\nS_words = word_useage[['S_perc', 'all_perc', 'S chi2']][(word_useage['S_perc'] > word_useage['all_perc'])].sort_values(by='S chi2', ascending=False)\nN_words = word_useage[['N_perc', 'all_perc', 'N chi2']][word_useage['N_perc'] > word_useage['all_perc']].sort_values(by='N chi2', ascending=False)\n\nF_words = word_useage[['F_perc', 'all_perc', 'F chi2']][(word_useage['F_perc'] > word_useage['all_perc'])].sort_values(by='F chi2', ascending=False)\nT_words = word_useage[['T_perc', 'all_perc', 'T chi2']][word_useage['T_perc'] > word_useage['all_perc']].sort_values(by='T chi2', ascending=False)\n\nP_words = word_useage[['P_perc', 'all_perc', 'P chi2']][(word_useage['P_perc'] > word_useage['all_perc'])].sort_values(by='P chi2', ascending=False)\nJ_words = word_useage[['J_perc', 'all_perc', 'J chi2']][word_useage['J_perc'] > word_useage['all_perc']].sort_values(by='J chi2', ascending=False)\nI_keep = I_words[I_words.index.isin(list(stopwords))].head(5)\nE_keep = E_words[E_words.index.isin(list(stopwords))].head(5)\n\nS_keep = S_words[S_words.index.isin(list(stopwords))].head(5)\nN_keep = N_words[N_words.index.isin(list(stopwords))].head(5)\n\nF_keep = F_words[F_words.index.isin(list(stopwords))].head(5)\nT_keep = T_words[T_words.index.isin(list(stopwords))].head(5)\n\nP_keep = P_words[P_words.index.isin(list(stopwords))].head(5)\nJ_keep = J_words[J_words.index.isin(list(stopwords))].head(5)\nI_keep = list(I_keep.index)\nE_keep = list(E_keep.index)\n\nS_keep = list(S_keep.index)\nN_keep = list(N_keep.index)\n\nF_keep = list(F_keep.index)\nT_keep = list(T_keep.index)\n\nP_keep = list(P_keep.index)\nJ_keep = list(J_keep.index)\nkeep = I_keep+E_keep+S_keep+N_keep+F_keep+T_keep+P_keep+J_keep\n\nkeep = set(keep)\nlen(keep)\nstop = nltk.corpus.stopwords.words('english')\nlen(stop)\nstopwords = []\nfor i in stop:\n    if i in keep:\n        pass\n    else:\n        stopwords.append(i)\nlen(stopwords)\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='5'><\/a>\n\"\"\"\n\"\"\"\n# train\n\"\"\"\n\"\"\"\nTo check if we still have any unwatned characters, we look at our training data again and remove any unwanted characters. We also created our four columns for each variable using the type column. \n\"\"\"\ntrain = train_df\nsample = train.sample(3).reset_index(drop=True)\ntrain.shape\n#Removes links\nremove_links(train, 'posts')\ntrain.head(1)\ntrain['posts'].replace(r'\\|\\|\\|', r' ', regex=True, inplace=True)\ntrain['posts'].head(1)\n#Removes punchuations and set text to lowercase\ntrain['posts'] = train['posts'].str.lower()\ntrain['posts'] = train['posts'].apply(no_punc_num)\ntrain['posts'].head(1)\n#Tokenize the posts\ntrain['posts'] = train['posts'].apply(tokens.tokenize)\ntrain['posts'].head(1)\n#Lemmatize the posts\ntrain['posts'] = train['posts'].apply(lemmatized, args=(lem,))\ntrain.head(1)\n#Removes stopwords from the posts\ntrain['posts'] = train['posts'].apply(remove_stop_words)\ntrain.head(1)\ntrain['posts'] = [' '.join(map(str, l)) for l in train['posts']]\ntrain.head(1)\ntrain['Mind']   = train['type'].apply(lambda x: x[0] == 'E').astype('int')\ntrain['Energy'] = train['type'].apply(lambda x: x[1] == 'N').astype('int')\ntrain['Nature'] = train['type'].apply(lambda x: x[2] == 'T').astype('int')\ntrain['Tactics']= train['type'].apply(lambda x: x[3] == 'J').astype('int')\ntrain = train[['Mind','Energy','Nature','Tactics','posts', 'type']]\n\"\"\"\nColumn names for the new columns and their binary codes(1s and 0s):\n\n- Mind: Introversion(I = 0) - Extroversion(E = 1)<br\/>\n- Energy: Sensing(S = 0) - Intuition(N = 1)<br\/>\n- Nature: Feeling(F = 0) - Thinking(T = 1)<br\/>\n- Tactics: Perceiving(P = 0) - Judging(J = 1)\n\"\"\"\ntrain.head(1)\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='6'><\/a>\n\"\"\"\n\"\"\"\n# test\n\"\"\"\n\"\"\"\nWe did the same for our test data. We removed links, punctuation, numbers and stop words. We lammatized our words. We did all this by using the functions we built. We will call our functions and check everytime to see if the function is working by using .head()\n\"\"\"\n#Removes links\nremove_links(test, 'posts')\ntest.head(1)\ntest['posts'].replace(r'\\|\\|\\|', r' ', regex=True, inplace=True)\ntest['posts'].head(1)\n#Removes punchuations and set text to lowercase\ntest['posts'] = test['posts'].str.lower()\ntest['posts'] = test['posts'].apply(no_punc_num)\ntest['posts'].head(1)\n#Tokenize the posts\ntest['posts'] = test['posts'].apply(tokens.tokenize)\ntest['posts'].head(1)\n#Lemmatize the posts\ntest['posts'] = test['posts'].apply(lemmatized, args=(lem,))\ntest.head(1)\n#Removes the stopwords from the posts\ntest['posts'] = test['posts'].apply(remove_stop_words)\ntest.head(1)\ntest['posts'] = [' '.join(map(str, l)) for l in test['posts']]\ntest.head(1)\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='7'><\/a>\n\"\"\"\n\"\"\"\n# Vectorization\n\"\"\"\n\"\"\"\nWe created a bag of words above but we will also be using CountVectorizer and TfidfVectorizer below. These methods work differently to do the same work. Although CountVectorizer is traditionally the main vectorizer these methods are found on the same module and not superior to each other. But since they work differently and have different parameters, we will test them both.\n\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\"\"\"\nCountVectorizer encodes text by splitting a set of words into one column per word, with (by default) the count of the word for that row in that column.\n\"\"\"\n#Vectorising using CountVectorizer\nCount_vect = CountVectorizer(max_df=0.8, min_df=43,  lowercase=False)\nCount_train = Count_vect.fit_transform(train['posts'])\nCount_test = Count_vect.transform(test['posts'])\n\"\"\"\nTfidfVectorizer convert a collection of raw documents to a matrix of TF-IDF features.\n\"\"\"\n#Vectorising using TfidfVectorizer\nTfidf_vect =TfidfVectorizer(max_df=0.8, min_df=43, lowercase=False)\nTfidf_train = Tfidf_vect.fit_transform(train['posts'])\nTfidf_test = Tfidf_vect.transform(test['posts'])\n#It seems they have exactly the same result in this case according to the results printed out.\nprint(f'count: {Count_train.shape}\\nCount_test: {Count_test.shape}\\n\\nTfidf: {Tfidf_train.shape}\\nTfidf_test: {Tfidf_test.shape}')\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='8'><\/a>\n\"\"\"\n\"\"\"\n# Model fitting and predicting\n\"\"\"\n\"\"\"\nWe are ready to fit our model. First we import our models. There are different machine learning models which we first tried (Logistic Regression, Naive Bayes(the three known), Extra-trees Classifier and Random Forest) among which the code for logistic regression is shown below. We decided to use logistic regression, because it seemed to fit our data and predict better from our kaggle submissions.\n\"\"\"\n#Import libraries\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.metrics import log_loss\n#We saved our id for submission purposes\nsubm = {}\nsubm['id'] = test['id'].values\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='9'><\/a>\n\"\"\"\n\"\"\"\n### Model fitting and predicting for each class (Mind, Energy, Nature, and Tactics) using Logistic Regression\n\"\"\"\n\"\"\"\n# Mind\n\"\"\"\n\"\"\"\nFirst is mind which compares Introverted (I) and Extraverted (E). We fitted the model with out 'y' as train['Mind'] and our 'x' as Tfidf_train. We then we predicted our X_test that we also vectorised using TfidfVectorizer.\n\"\"\"\nnp.mean(train['Mind'] == 1)\nmind = LogisticRegression(C=1, solver='lbfgs')\nmind.fit(Tfidf_train, train['Mind'].values)\nalert()\ny_probs = mind.predict_proba(Tfidf_train)\nmind_pred = mind.predict(Tfidf_train)\n\nfor thresh in np.arange(0.1, 1, 0.1).round(1):\n    fiddled_y = np.where(y_probs[:,1] > thresh, 1, 0)\n    print(f'the loss for {thresh} is:  {log_loss(fiddled_y, train[\"Mind\"])}')\ntrue_mind = np.where(mind.predict_proba(Tfidf_test)[:,1] > 0.3, 1, 0)\ntrue_mind\nsubm['mind'] = true_mind\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='10'><\/a>\n\"\"\"\n\"\"\"\n# Energy\n\"\"\"\n\"\"\"\nSecond is Energy which compares  Sensing (S) and Intuitive (N). We fitted the model with out 'y' as train['Energy'] and our 'x' as Tfidf_train. We then we predicted our X_test that we also vectorised using TfidfVectorizer.\n\"\"\"\nnp.mean(train['Energy'] == 1)\nEnergy  = LogisticRegression(C=1, solver='lbfgs')\nEnergy.fit(Tfidf_train,  train['Energy'])\nalert()\ny_probs = Energy.predict_proba(Tfidf_train)\nEnergy_pred = Energy.predict(Tfidf_train)\n\nfor thresh in np.arange(0.1, 1, 0.1).round(1):\n    fiddled_y = np.where(y_probs[:,1] > thresh, 1, 0)\n    print(f'the loss for {thresh} is:  {log_loss(fiddled_y, train[\"Energy\"])}')\ntrue_energy = np.where(Energy.predict_proba(Tfidf_test)[:,1] > 0.7, 1, 0)\ntrue_energy\nsubm['energy'] = true_energy\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='11'><\/a>\n\"\"\"\n\"\"\"\n# Nature\n\"\"\"\n\"\"\"\nThird is Nature which compares Feeling (F) and Thinking (T). We fitted the model with out 'y' as train['Nature'] and our 'x' as Tfidf_train. We then we predicted our X_test that we also vectorised using TfidfVectorizer.\n\"\"\"\nnp.mean(train['Nature'] == 1)\nNature  = LogisticRegression(C=1, solver='lbfgs')\nNature.fit(Tfidf_train,  train['Nature'])\nalert()\ny_probs = Nature.predict_proba(Tfidf_train)\nNature_pred = Nature.predict(Tfidf_train)\n\nfor thresh in np.arange(0.1, 1, 0.1).round(1):\n    fiddled_y = np.where(y_probs[:,1] > thresh, 1, 0)\n    print(f'the loss for {thresh} is:  {log_loss(fiddled_y, train[\"Nature\"])}')\ntrue_nature = np.where(Nature.predict_proba(Tfidf_test)[:,1] > 0.5, 1, 0)\ntrue_nature\nsubm['nature'] = true_nature\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='12'><\/a>\n\"\"\"\n\"\"\"\n# Tactics\n\"\"\"\n\"\"\"\nLast one is Tactics which compares Perceiving (P) and Judging (J). We fitted the model with out 'y' as train['Tactics'] and our 'x' as Tfidf_train. We then we predicted our X_test that we also vectorised using TfidfVectorizer.\n\"\"\"\nnp.mean(train['Tactics'] == 1)\nTactics = LogisticRegression(C=1, solver='lbfgs')\nTactics.fit(Tfidf_train, train['Tactics'])\nalert()\ny_probs = Tactics.predict_proba(Tfidf_train)\nTactics_pred = Tactics.predict(Tfidf_train)\n\nfor thresh in np.arange(0.1, 1, 0.1).round(1):\n    fiddled_y = np.where(y_probs[:,1] > thresh, 1, 0)\n    print(f'the loss for {thresh} is:  {log_loss(fiddled_y, train[\"Tactics\"])}')\ntrue_tactics = np.where(Tactics.predict_proba(Tfidf_test)[:,1] > 0.4, 1, 0)\ntrue_tactics\nsubm['tactics'] = true_tactics\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='13'><\/a>\n\"\"\"\n\"\"\"\n# Prepared submission\n\"\"\"\nsubmit = pd.DataFrame(subm)\nsubmit.sample(10)\nsubmit.to_csv('kaggle submit.csv', index=False)\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='14'><\/a>\n\"\"\"\n\"\"\"\n# Conclusion\nText data comes in many different forms depending on the source. The data we used are twitter posts which do not come with translation of any videos or images shared. We had to clean our data in a way that saves some of those messages we can't see just from the text. We saw that in our model improved a lot after we have replaced the urls with title of their videos from youtube.\n\nThis model present an alternative way of getting mbti personality type. Also with the method described in this notebook, one does not need to wait for somebody to take the test but need their social media posts or words they normally say to people. It makes it easier to get someone else's personality type. This can be very useful for companies that would like to pick people according to their personality type, people looking to interact with certain personality type and more.\n\nThere are different machine learning models which we first tried (Logistic Regression, Naive Bayes, Extra-trees Classifier and Random Forest) among which the code for logistic regression is shown above. We decided to use logistic regression, because it seemed to fit our data and predict better score from our kaggle submissions.The binary classification exercise to predict each of the classes in the four axes (mind, energy, nature, and tactics) was somewhat more successful. A Logistic Regression was used in each of the classes.\n\nWe still have challenges of reading people's tone and level of english and their writting skills. This factors can play a big role in our model predicting the exact personality type. The fact that another forum or platform can have a different way of writting can also mean that the model will have to be trained and fitted again for that specific platform. \n\"\"\"\n\"\"\"\n# Still to do\n\"\"\"\n\"\"\"\n* Attempt upscaling to help with the skewness of the data\n* Weighting the response of personality traits based on other traits\n* Apply GridsearchCV to my models\n\"\"\"\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n<a id='15'><\/a>\n\"\"\"\n\"\"\"\n# Acknowledgements\n\"\"\"\n\"\"\"\n1. A large part of the code and idea to fiddle with the logistic regression thresholds was inspired by the **advanced logistic regression** train and **Nicholas Meyers** \n2. EDA\/Feature engineering (to keep certain stopwords) was largely inspired by the **How do machines understand language** train\n3. Most preprocessing functions were largely inspired by the **How do machines understand language** train\n4. EDSA supervisors **Bryan Davies, Tristan Naidoo**\n5. Kaggle dataset from [Personality Cafe website forums](https:\/\/www.personalitycafe.com\/forum\/)\n\"\"\"\n\"\"\"\n[Return to index](#index)\n___________________________________________________________________________________________________________________________________________________\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b11db61cb1a800'}"}
{"id":"11680","text":"\"\"\"\nHere is the  kernel to show how punt formation affect the rate of concussion\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\"\"\"\nLoad player role and concussion data\n\"\"\"\nplayer_role_data = pd.read_csv('..\/input\/play_player_role_data.csv')\nplayer_role_data.head()\nplay_information_data = pd.read_csv('..\/input\/play_information.csv')\nplay_information_data.head()\nconcussion_data = pd.read_csv('..\/input\/video_review.csv')\nconcussion_data.head()\nlen(concussion_data)\nconcussion_data['concussed'] = 1\n\"\"\"\nCreate a pivot table for all punt play data and merge it with concussion data\n\"\"\"\ntable = pd.pivot_table(player_role_data,index=['GameKey', 'PlayID'],columns=['Role'], aggfunc=lambda x: len(x.unique()))['GSISID'].fillna(0)\n\ntable.reset_index(inplace=True)\ntable.head()\nmerged_data = pd.merge(table,play_information_data)\nmerged_data = pd.merge(merged_data,concussion_data,how='outer')\nmerged_data.concussed.fillna(0, inplace=True)\n\"\"\"\nCheck the number of concussed player  in the new dataframe\n\"\"\"\nlen(merged_data[merged_data['Primary_Impact_Type'].notnull()])\n\"\"\"\nHere we would like to find number of defender in box and if the receiver team is overloading one side. \n\"\"\"\nmerged_data['overload'] =  ((merged_data['PDL1'] + merged_data['PDL2'] + merged_data['PDL3'] + merged_data['PDL4'] + merged_data['PDL5'] + merged_data['PDL6']) - \\\n(merged_data['PDR1'] + merged_data['PDR2'] + merged_data['PDR3'] + merged_data['PDR4'] + merged_data['PDR5'] + merged_data['PDR6']) + \\\n(merged_data['PLL1'] + merged_data['PLL2'] + merged_data['PLL3']) - \\\n(merged_data['PLR1'] + merged_data['PLR2'] + merged_data['PLR3'])).abs()\nmerged_data['box_defender'] =  ((merged_data['PDL1'] + merged_data['PDL2'] + merged_data['PDL3'] + merged_data['PDL4'] + merged_data['PDL5'] + merged_data['PDL6']) + \\\n(merged_data['PDR1'] + merged_data['PDR2'] + merged_data['PDR3'] + merged_data['PDR4'] + merged_data['PDR5'] + merged_data['PDR6']) + \\\n(merged_data['PLL1'] + merged_data['PLL2'] + merged_data['PLL3']) + \\\n(merged_data['PLR1'] + merged_data['PLR2'] + merged_data['PLR3']) + \n(merged_data['PLM1'] + merged_data['PLM'] + merged_data['PDM']))\n\"\"\"\nAlso remove punt plays that are blocked or killed by penalties\n\"\"\"\nyards_list = []\n\nfor i,yards in enumerate(merged_data.PlayDescription.str.split(' yard').str[0].str[-2:]):\n    try:\n        yards_list.append(float(yards))\n    except ValueError:\n        yards_list.append('NaN')\nmerged_data['punt_yards'] = yards_list\nmerged_data['no_play'] = merged_data.PlayDescription.str.contains('No Play', regex=True)\nmerged_data['blocked'] = merged_data.PlayDescription.str.contains('BLOCKED', regex=True)\nmerged_data = merged_data[(merged_data.box_defender > 3) & (merged_data.box_defender  <9) & (merged_data.punt_yards != 'NaN') & (merged_data.no_play == False) & (merged_data.blocked == False)]\nmerged_data.head()\n\"\"\"\nWe now load the statsmodels module for logistic regression to determine whether no. of box defender and overload players would affect\n\"\"\"\nimport statsmodels\nimport statsmodels.api as sm\n\nimport statsmodels.formula.api as smf\n\n\nresults = smf.logit(formula='concussed ~ box_defender + overload', data=merged_data).fit()\nresults.summary()\n\"\"\"\nFrom the result we can see that no. of box defender may has some effect on concussion chance, but overloading one side by receiving team seems to not making any difference.\nFinally we plot the 95% Wilson convidence interval for each case\n\"\"\"\nzero_overload = merged_data[merged_data['overload'] == 0]\nlower_zero,upper_zero = statsmodels.stats.proportion.proportion_confint(len(zero_overload[zero_overload['concussed'] == 1]), len(zero_overload['concussed']), alpha=0.05, method='wilson')\none_overload = merged_data[merged_data['overload'] == 1]\nlower_one,upper_one = statsmodels.stats.proportion.proportion_confint(len(one_overload[one_overload['concussed'] == 1]), len(one_overload['concussed']), alpha=0.05, method='wilson')\ntwo_overload = merged_data[merged_data['overload'] == 2]\nlower_two,upper_two = statsmodels.stats.proportion.proportion_confint(len(two_overload[two_overload['concussed'] == 1]), len(two_overload['concussed']), alpha=0.05, method='wilson')\nthree_overload = merged_data[merged_data['overload'] == 3]\nlower_three,upper_three = statsmodels.stats.proportion.proportion_confint(len(three_overload[three_overload['concussed'] == 1]), len(three_overload['concussed']), alpha=0.05, method='wilson')\nx = [0,1,2,3]\ny = [np.mean(zero_overload['concussed']),np.mean(one_overload['concussed']),np.mean(two_overload['concussed']),np.mean(three_overload['concussed'])]\n\nyerr = [[y[0] - lower_zero, y[1] - lower_one, y[2] - lower_two, y[3] - lower_three ], [upper_zero - y[0], upper_one - y[1], upper_two - y[2], upper_three - y[3]]]\nplt.errorbar(x,y,yerr, capsize=3, elinewidth=1)\nplt.xlabel('No. of overload defender')\nplt.ylabel('Concussion chance')\nplt.title('Error of concussion chance vs overload defender')\nplt.xticks(np.arange(0, 4, step=1))\nsix_box = merged_data[merged_data['box_defender'] == 6]\nlower_six,upper_six = statsmodels.stats.proportion.proportion_confint(len(six_box[six_box['concussed'] == 1]), len(six_box['concussed']), alpha=0.05, method='wilson')\nseven_box = merged_data[merged_data['box_defender'] == 7]\nlower_seven,upper_seven = statsmodels.stats.proportion.proportion_confint(len(seven_box[seven_box['concussed'] == 1]), len(seven_box['concussed']), alpha=0.05, method='wilson')\neight_box = merged_data[merged_data['box_defender'] == 8]\nlower_eight,upper_eight = statsmodels.stats.proportion.proportion_confint(len(eight_box[eight_box['concussed'] == 1]), len(eight_box['concussed']), alpha=0.05, method='wilson')\nx = [6,7,8]\ny = [np.mean(six_box['concussed']),np.mean(seven_box['concussed']),np.mean(eight_box['concussed'])]\n\nyerr = [[y[0] - lower_six, y[1] - lower_seven, y[2] - lower_eight], [upper_six - y[0], upper_seven - y[1], upper_eight - y[2]]]\nplt.errorbar(x,y,yerr, capsize=3, elinewidth=1)\nplt.xlabel('No. of box defender')\nplt.ylabel('Concussion chance')\nplt.title('Error of concussion chance vs box defender')\nplt.xticks(np.arange(6,9, step=1))","meta":"{'source': 'AI4Code', 'id': '156afa21a6fb27'}"}
{"id":"15160","text":"\"\"\"\nNotebook References:\n1. Inspiration to use Spacy: https:\/\/www.kaggle.com\/vigneshbaskaran\/commonlit-spacy-with-ridge-regression\n2. Inpiration to use Umap: https:\/\/www.kaggle.com\/subinium\/commonlit-how-to-visualize-text-dataset <br>\n**Please upvote if you find this useful, it helps in keeping the motivation levels high**\n\"\"\"\n# 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\n# for 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\n\"\"\"\n# Create Vectors\n\"\"\"\nimport spacy\nfrom tqdm.notebook import tqdm\nnlp = spacy.load('en_core_web_lg')\nimport re\ndef clean_text(text):\n    text= text.lower() # make text lowercase\n    text = text.replace(\"\\n\",\" \") #remove \\n from text\n#     text = re.sub('[^A-Za-z0-9., ], ' ', text)\n    return text\ntrain = pd.read_csv('..\/input\/commonlitreadabilityprize\/train.csv')\ntest = pd.read_csv('..\/input\/commonlitreadabilityprize\/test.csv')\ntrain['excerpt'] = train['excerpt'].apply(lambda x: clean_text(x))\ntest['excerpt'] = test['excerpt'].apply(lambda x: clean_text(x))\n#example of vstack\na = np.array([1, 2, 3])\nb = np.array([2, 3, 4])\nnp.vstack((a,b))\n#nlp(text).vector returns  average of the token vectors as default\n#https:\/\/spacy.io\/api\/doc#vector\nprint(nlp(\"this is\").vector[0])\nprint((nlp(\"this\").vector[0] + nlp(\" \").vector[0]  + nlp(\"is\").vector[0] )\/2)\nX_train = np.vstack([nlp(text).vector for text in tqdm(train['excerpt'])])\ny_train = train['target']\nprint(f'Shape of Train vectors: {X_train.shape}')\nX_test = np.vstack([nlp(text).vector for text in tqdm(test['excerpt'])])\nprint(f'Shape of Test vectors: {X_test.shape}')\n\"\"\"\n# Visualize Data\nHow to read UMAP: https:\/\/pair-code.github.io\/understanding-umap\/\n\"\"\"\nfrom umap import UMAP\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf = pd.DataFrame(X_train)\ndf.index= train.index\ndf['target'] = train['target']\numap = UMAP(n_neighbors=20,random_state=0)\ndr = umap.fit_transform(df, df['target'])\ntarget = df['target']\nfig = plt.figure(figsize=(15, 10))\ngs = fig.add_gridspec(4, 6)\nax = fig.add_subplot(gs[:,:4])\nax.axis('off')\n\nax.scatter(x=dr[:,0], y=dr[:,1], s=10, c=target)\nax.set_title('Word 2 Vec Output', loc='left', fontsize=20, fontweight='bold')\n\nax_dist = fig.add_subplot(gs[:2,4:])\nax_dist.set_title('Target Distribution', loc='left', fontsize=15, fontweight='bold')\n\nsns.kdeplot(target, fill=True, alpha=0, linewidth=0, ax=ax_dist)\npath = ax_dist.collections[0].get_paths()[0]\npatch = mpl.patches.PathPatch(path, transform=ax_dist.transData)\n\nx = np.linspace(0, 1, 200)\n\n\nim = ax_dist.imshow(np.vstack([x, x]), \n               cmap=\"viridis\",\n               aspect=\"auto\",\n               extent=[*ax_dist.get_xlim(), *ax_dist.get_ylim()]\n              )\n\nim.set_clip_path(patch)\n\nqtile = target.quantile([0, .25, .5, .75, 1.])\n\nfor idx in range(4):\n    sub_ax = fig.add_subplot(gs[2+idx\/\/2,4+idx%2])\n    sub_ax.axis('off')\n    q_range = (target < qtile.iloc[idx+1]) & (target >= qtile.iloc[idx])\n    sub_ax.scatter(dr[:,0][q_range],\n                   dr[:,1][q_range],\n                   s=10, \n                   c=(target[q_range]-qtile.iloc[0])\/(qtile.iloc[-1]-qtile.iloc[0]), \n                   vmin=0, vmax=1\n                  )\n    sub_ax.set_title(f'Q{idx}', loc='left')\n\nfig.tight_layout()\nplt.show()\n\"\"\"\nPatterns in data can be observed as difficult excerpts with dark blue color are very much separated from easy excerpts with yellowish colors\n\"\"\"\n\"\"\"\n# Model\n\"\"\"\nfrom pathlib import Path\nfrom tqdm.notebook import tqdm\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, y_train, y_val = train_test_split(X_train, train['target'], test_size=0.2, random_state=42)\nfrom sklearn.metrics import mean_squared_error\nfor i in [1e-5,1e-4,1e-3,1e-2,1e-1,1,10,100]:\n    print(f' aplha {i}')\n    regressor = Ridge(alpha=i,fit_intercept=True, normalize=False)\n    regressor.fit(X_train,y_train)\n    print(f'Train Root mean squared error: {mean_squared_error(y_train,regressor.predict(X_train),squared=False)}')\n    print(f'Validation Root mean squared error: {mean_squared_error(y_val,regressor.predict(X_val),squared=False)}')\nregressor = Ridge(alpha=1,fit_intercept=True, normalize=False) #aplha =1\nregressor.fit(X_train, y_train) \ntest['target'] = regressor.predict(X_test)\ntest[['id','target']].to_csv('.\/submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '1bb569b1174d0b'}"}
{"id":"101593","text":"# 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)\nimport seaborn as sns;\nimport matplotlib.pyplot as plt;\nfrom collections import Counter;\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\n# Import data\nmedianHouseHoldInCome = pd.read_csv(\"..\/input\/fatal-police-shootings-in-the-us\/MedianHouseholdIncome2015.csv\", encoding = \"windows-1252\");\npercentagePeopleBelowPovertyLevel = pd.read_csv(\"..\/input\/fatal-police-shootings-in-the-us\/PercentagePeopleBelowPovertyLevel.csv\", encoding = \"windows-1252\");\npercentOver25CompletedHighSchool = pd.read_csv(\"..\/input\/fatal-police-shootings-in-the-us\/PercentOver25CompletedHighSchool.csv\", encoding = \"windows-1252\");\nshareRaceCity = pd.read_csv(\"..\/input\/fatal-police-shootings-in-the-us\/ShareRaceByCity.csv\", encoding = \"windows-1252\");\nkill = pd.read_csv(\"..\/input\/fatal-police-shootings-in-the-us\/PoliceKillingsUS.csv\", encoding = \"windows-1252\");\npercentagePeopleBelowPovertyLevel.head()\npercentagePeopleBelowPovertyLevel.info()\nprint(percentagePeopleBelowPovertyLevel.poverty_rate.value_counts());\n# Delete all poverty_rate = \"-\" items\npercentagePeopleBelowPovertyLevel.poverty_rate.replace(\"-\", 0.0, inplace = True);\npercentagePeopleBelowPovertyLevel.poverty_rate.value_counts()\npercentagePeopleBelowPovertyLevel.poverty_rate = percentagePeopleBelowPovertyLevel.poverty_rate.astype(\"float\");\npercentagePeopleBelowPovertyLevel.info()\n# Get poverty rate of each state\nareaList = list(percentagePeopleBelowPovertyLevel[\"Geographic Area\"].unique());\nprint(areaList);\nprint(\"The number of states: {}\".format(len(percentagePeopleBelowPovertyLevel[\"Geographic Area\"].unique())));\nareaPovertyRatio = [];\nfor each in areaList:\n    stateFilter = percentagePeopleBelowPovertyLevel[\"Geographic Area\"] == each\n    currentState = percentagePeopleBelowPovertyLevel[stateFilter];\n    areaPovertyRate = sum(currentState.poverty_rate) \/ len(currentState);\n    areaPovertyRatio.append(areaPovertyRate);\ndata = pd.DataFrame({\"areaList\": areaList, \"areaPovertyRatio\": areaPovertyRatio});\nnewIndex = (data[\"areaPovertyRatio\"].sort_values(ascending = False)).index.values; # S\u0131ralanan de\u011ferlerin indisleri\nsortedData = data.reindex(newIndex);\n\nplt.figure(figsize=(15, 10));\nax = sns.barplot(x = sortedData.areaList, y = sortedData.areaPovertyRatio);\nplt.xticks(rotation=90);\nplt.xlabel(\"States\");\nplt.ylabel(\"Poverty Rate\");\nplt.title(\"Poverty Rata vs States\");\nsortedData.head()\n# Find most 15 Name or Surname of the killed people\n#print(kill.head());\n#print(kill.name.value_counts());\nnameFilter = kill.name != \"TK TK\";\nseparate = kill.name[nameFilter].str.split();\nprint(separate.value_counts());\na, b = zip(*separate);\n#print(b);\nnameList = (a+b);\n#print(nameList);\nnameCount = Counter(nameList);\n#print(nameCount);\nmostCommonNames = nameCount.most_common(15);\n#print(mostCommonNames);\nx, y = zip(*mostCommonNames);\n#print(y)\nx,y = list(x), list(y);\n\nplt.figure(figsize = (15, 10));\nax = sns.barplot(x = x, y=y, palette=sns.cubehelix_palette(len(x)));\nplt.xlabel(\"Name or Surname of the killed people\");\nplt.ylabel(\"Frequency\");\nplt.title(\"The most common names or surnames of the killed people\");\nprint(percentOver25CompletedHighSchool.head())\nprint(percentOver25CompletedHighSchool.percent_completed_hs.value_counts());\npercentOver25CompletedHighSchool.percent_completed_hs.replace(\"-\", 0.0, inplace = True);\npercentOver25CompletedHighSchool.percent_completed_hs = percentOver25CompletedHighSchool.percent_completed_hs.astype(\"float\");\nprint(percentOver25CompletedHighSchool.info());\n\nareaList = list(percentOver25CompletedHighSchool[\"Geographic Area\"].unique());\nprint(areaList);\nareaHighSchool = [];\nfor each in areaList:\n    filterArea = percentOver25CompletedHighSchool[\"Geographic Area\"] == each;\n    x = percentOver25CompletedHighSchool[filterArea];\n    rate = sum(x.percent_completed_hs) \/ len(x);\n    areaHighSchool.append(rate);\n\n# sorting\ndata = pd.DataFrame({\"AreaList\": areaList, \"hsRate\": areaHighSchool});\nnewIndices = (data.hsRate.sort_values(ascending = True)).index.values;\nsortedData2 = data.reindex(newIndices);\n\n# Visualization\nplt.figure(figsize = (15, 10));\nsns.barplot(x = sortedData.areaList, y = sortedData.areaPovertyRatio);\nplt.xticks(rotation = 90);\nplt.xlabel(\"States\");\nplt.ylabel(\"High School Rate\");\nplt.title(\"High School Rate vs States\");\n\nsortedData2.head()\n\"\"\"\nPercentage of state's population according to races which are black, white, native American, asian and hispanic\n\"\"\"\n#print(shareRaceCity.head());\nprint(shareRaceCity.info());\nshareRaceCity.replace(\"-\", 0.0, inplace = True);\nshareRaceCity.replace(\"(X)\", 0.0, inplace = True);\nshareRaceCity.loc[:, [\"share_white\", \"share_black\", \"share_native_american\", \"share_asian\", \"share_hispanic\"]] = shareRaceCity.loc[:, [\"share_white\", \"share_black\", \"share_native_american\", \"share_asian\", \"share_hispanic\"]].astype(\"float\");\nshareRaceCity.info()\nareaList = list(shareRaceCity[\"Geographic area\"].unique());\nprint(areaList);\nshare_white = [];\nshare_black = [];\nshare_native_american = [];\nshare_asian = [];\nshare_hispanic = [];\n\nfor each in areaList:\n    currentAreaFilter = (shareRaceCity[\"Geographic area\"] == each);\n    share_white.append(sum(shareRaceCity[currentAreaFilter].share_white) \/ len(shareRaceCity[currentAreaFilter].share_white));\n    share_black.append(sum(shareRaceCity[currentAreaFilter].share_black) \/ len(shareRaceCity[currentAreaFilter].share_black));\n    share_native_american.append(sum(shareRaceCity[currentAreaFilter].share_native_american) \/ len(shareRaceCity[currentAreaFilter].share_native_american));\n    share_asian.append(sum(shareRaceCity[currentAreaFilter].share_asian) \/ len(shareRaceCity[currentAreaFilter].share_asian));\n    share_hispanic.append(sum(shareRaceCity[currentAreaFilter].share_hispanic) \/ len(shareRaceCity[currentAreaFilter].share_hispanic));\n# visualization\nf,ax = plt.subplots(figsize = (9,15))\nsns.barplot(x=share_white,y=areaList,color='green',alpha = 0.5,label='White' )\nsns.barplot(x=share_black,y=areaList,color='blue',alpha = 0.7,label='African American')\nsns.barplot(x=share_native_american,y=areaList,color='cyan',alpha = 0.6,label='Native American')\nsns.barplot(x=share_asian,y=areaList,color='yellow',alpha = 0.6,label='Asian')\nsns.barplot(x=share_hispanic,y=areaList,color='red',alpha = 0.6,label='Hispanic')\n\nax.legend(loc='lower right',frameon = True)     # legendlarin gorunurlugu\nax.set(xlabel='Percentage of Races', ylabel='States',title = \"Percentage of State's Population According to Races \")\n\n\"\"\"\nPoint Plot\n\"\"\"\n# sortedData = areaPovertyRatio\n# sortedData2 = areaHighSchool\n\nsortedData.areaPovertyRatio = sortedData.areaPovertyRatio \/ max(sortedData.areaPovertyRatio);\nsortedData2.hsRate = sortedData2.hsRate \/ max(sortedData2.hsRate);\ndata = pd.concat([sortedData, sortedData2[\"hsRate\"]], axis = 1);\ndata.sort_values(\"areaPovertyRatio\", inplace = True);\n\n# Visualization\nf, ax1 = plt.subplots(figsize = (20, 10));\nsns.pointplot(x = \"areaList\", y = \"areaPovertyRatio\", data = data, color = \"lime\", alpha = 0.8);\nsns.pointplot(x = \"areaList\", y = \"hsRate\", data = data, color = \"red\", alpha = 0.8);\nplt.text(40, 0.6, \"HS Graduate Ratio\", color = \"red\", fontsize = 17, style = \"italic\");\nplt.text(40, 0.55, \"Poverty Ratio\", color = \"lime\", fontsize = 17, style = \"italic\");\nplt.xlabel(\"States\", fontsize = 15, color = \"blue\");\nplt.ylabel(\"Values\", fontsize = 15, color = \"blue\");\nplt.title(\"High School Gradate Rate vs Poverty Rate\", fontsize = 20, color = \"blue\");\nplt.grid();","meta":"{'source': 'AI4Code', 'id': 'baa91a699685b1'}"}
{"id":"31850","text":"\"\"\"\nThis note is trying to answer the following questions:\n\nQ1: Effect of gender and education level on average score.\nQ2: Effect of gender and preparation on average score.\nQ3: Which group is the most Successful?\n\"\"\"\n#Importing Libraries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n#Load DataSet\nmy_data = pd.read_csv(\"..\/input\/stuperformance\/StudentsPerformance_DataSet.xls\")\ndf = my_data.copy()\n#Checking the data\ndf.info()\n#Look at heed\ndf.head()\n#Renaming Columns \ndf.rename(inplace = True,\n           columns={\"race\/ethnicity\":\"race_ethnicity\",\n                   \"parental level of education\":\"Education_level\",\n                   \"test preparation course\":\"prep_course\",\n                   \"math score\":\"math_score\",\n                   \"reading score\":\"reading_score\",\n                   \"writing score\":\"writing_score\"})\n#Creating a new column average score\ndf['average_score'] = df[['math_score', 'reading_score', 'writing_score']].mean(axis=1)\ndf.head()\ndf.describe().T\n#Assigning Grades\ndef Grade(AverageScore):\n    if(AverageScore >= 80):return 'A'\n    if(AverageScore >= 70):return 'B'\n    if(AverageScore >= 60):return 'C'\n    if(AverageScore >= 50):return 'D'\n    if(AverageScore >= 40):return 'E'\n    else: return 'F'\n    \ndf[\"grade\"] = df.apply(lambda x : Grade(x[\"average_score\"]), axis=1)\n    \n#Pie Chart Showing the grade Distribution\nplt.figure(figsize=(7,7))\nplt.pie(df['grade'].value_counts().values,\n       labels=df['grade'].value_counts().index,\n       autopct='%1.1f%%',\n       shadow=True,\n       explode=[0,0,0.1,0,0,0])\nplt.title('Grand Pie Chart', color='Black', fontsize=20)\nplt.show()\n#Look at the Score\nplt.figure(figsize=(7,7))\nplt.title('Score Heatmap', color='Black', fontsize=20,pad=40)\nsns.heatmap(df.corr(),annot=True,linewidths=.5);\n#Answer to question no 1\nsns.catplot(data=df, x=\"gender\", y=\"average_score\", hue=\"Education_level\",kind=\"bar\", height=5 )\n#Answer to question no. 2\nsns.catplot(data=df, x=\"gender\", y=\"average_score\", hue=\"prep_course\",kind=\"bar\",height=5);\n#Answer to question no.3\nsns.barplot(x='race_ethnicity',y='average_score',data=df);\ndf.groupby(\"race_ethnicity\")[\"average_score\"].mean()\ndf.groupby(\"race_ethnicity\")['Education_level'].describe()\ndf.groupby(\"race_ethnicity\")['prep_course'].describe()\ndf.groupby('race_ethnicity')['grade'].describe()\n(sns.FacetGrid(df,hue=\"race_ethnicity\",height=5,xlim=(0,100)).map(sns.kdeplot, \"average_score\").add_legend())\nsns.catplot(x=\"race_ethnicity\", y=\"average_score\", hue=\"grade\", kind=\"point\", data=df);\n\"\"\"\n* **Comment. Waiting for feedback**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3aa1b9b2b707a8'}"}
{"id":"30529","text":"\"\"\"\n# Stroke prediction\n## This dataset is used to predict whether a patient is likely to get stroke based on the input parameters\n## Attribute Information\n- **id**: unique identifier\n- **gender**: \"Male\", \"Female\" or \"Other\"\n- **age**: age of the patient\n- **hypertension**: 0 if the patient doesn't have hypertension, 1 if the patient has hypertension\n- **heart_disease**: 0 if the patient doesn't have any heart diseases, 1 if the patient has a heart disease\n- **ever_married**: \"No\" or \"Yes\"\n- **work_type**: \"children\", \"Govt_jov\", \"Never_worked\", \"Private\" or \"Self-employed\"\n- **Residence_type**: \"Rural\" or \"Urban\"\n- **avg_glucose_level**: average glucose level in blood\n- **bmi**: body mass index\n- **smoking_status**: \"formerly smoked\", \"never smoked\", \"smokes\" or \"Unknown\"*\n- **stroke**: 1 if the patient had a stroke or 0 if not.\nNote: \"Unknown\" in smoking_status means that the information is unavailable for this patient\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import tree\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Original dataset\ndf_orig = pd.read_csv('..\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv', index_col='id')\ny = df_orig['stroke'].copy()\nX_orig = df_orig.drop(columns=['stroke'], inplace=False)\nnum_feat = len(X_orig.columns) \nnum_obj = len(X_orig)\n# Cross-validator\ncv = KFold(n_splits=5, shuffle=True, random_state=42)\nX_orig.head()\n\"\"\"\n# Visualization of the data\n\"\"\"\n# Stroke pie chart\nplt.figure(figsize=(10, 6))\nplt.pie(y.value_counts(), labels=['1', '0'], autopct='%.1f%%', shadow=True, explode=(0, 0.3));  \nplt.title('Pie chart of the \"stroke\" column\\n \\\n    \"1\" $-$ patient had a stroke,\\n \\\n    \"0\" $-$ patient did not have a stroke')\n# Stroke \u043e\u0442 age\nplt.figure(figsize=(7, 5))\nage_stroke = X_orig['age'].loc[y==1]\nsns.histplot(x=age_stroke, bins=40, kde=True)\nplt.xlabel('Age, years')\nplt.ylabel('Number of strokes')\nplt.grid()\n# Age distribution\nplt.figure(figsize=(7, 5))\nsns.histplot(x=X_orig['age'], hue=X_orig['gender'], element='step', legend=True)\nplt.xlabel('Age, years')\nplt.ylabel('Number of people')\nplt.grid()\nage_stroke = X_orig['age'].loc[y==1]\nfig, ax = plt.subplots(figsize=(7, 5))\nsns.histplot(x=X_orig['age'], ax=ax, stat='density', kde=True, element='step')\nsns.histplot(x=age_stroke, ax=ax, bins=20, stat='density', kde=True, element='step', color='g')\nax.set_xlabel('age, years')\nax.grid()\nfig, ax = plt.subplots(1, 2, figsize=(14, 6))\n# Glucose\nsns.histplot(X_orig['avg_glucose_level'], ax=ax[0], bins=30, kde=True)\nax[0].set_xlabel('Average glucose level in blood')\nax[0].axvline(X_orig['avg_glucose_level'].median(), label='Median', linestyle='--', color='r', lw=3)\nax[0].axvline(X_orig['avg_glucose_level'].mean(), label='Mean', linestyle='--', color='g', lw=3)\nax[0].legend()\nax[0].grid()\n# BMI\nsns.histplot(x=X_orig['bmi'], ax=ax[1], bins=30, kde=True, color='tab:orange')\nax[1].set_xlabel('Body mass index')\nax[1].axvline(X_orig['bmi'].median(), label='Median', linestyle='--', color='r', lw=2.5)\nax[1].axvline(X_orig['bmi'].mean(), label='Mean', linestyle='--', color='g', lw=2.5)\nax[1].legend()\nax[1].grid()\n\n# Smoking status\nplt.figure(figsize=(10, 6))\nsns.countplot(y=X_orig['smoking_status'])\nplt.ylabel('Smoking status')\nfig, ax  = plt.subplots(1, 2, figsize=(10, 6))\nax[0].pie(X_orig['heart_disease'].value_counts(), labels=['1', '0'], autopct='%.1f%%', shadow=True, explode=(0, 0.3));  \nax[0].set_title('\"1\" $-$ patient has a heart disease,\\n \\\n    \"0\" $-$ patient does not have any heart diseases')\nax[1].pie(X_orig['hypertension'].value_counts(), labels=['1', '0'], autopct='%.1f%%', shadow=True, explode=(0, 0.3));  \nax[1].set_title('\"1\" $-$ patient has hypertension,\\n \\\n    \"0\" $-$ patient does not have hypertension')\n\n\"\"\"\n# Feature engineering\n\"\"\"\ndef ohe(df, features):\n    \"\"\"\n    one-hot enccoder.\n    df -- input DataFrame\n    features -- list of features to be encoded\n\n    One can easily use sklearn.preprocessing.OneHotEncoder instead\n    \"\"\"\n    for feat in features:\n        categ_list = df[feat].unique()\n        df_enc = np.zeros((df.shape[0], len(categ_list)))\n        for ii in range(len(categ_list)):\n            df_enc[:, ii] = (df[feat]==categ_list[ii]).astype(int) \n\n        df_enc = pd.DataFrame(data=df_enc, index=df.index, columns=categ_list)\n        df = pd.concat([df, df_enc], axis=1)\n    return df\n\nX_prep = X_orig.copy()\n# Encode categorial features\n# Male - 1, Female - 0\nX_prep['gender'] = X_prep['gender'].map({'Male': 1, 'Female': 0, 'Other': 1})\n# urban - 1, rural - 0\nX_prep['Residence_type'] = X_prep['Residence_type'].map({'Urban': 1, 'Rural': 0})\n# ever_married yes - 1, no - 0\nX_prep['ever_married'] = X_prep['ever_married'].map({'Yes': 1, 'No': 0})\n# One-hot encoder for work_type, smoking_status\nX_prep = ohe(X_prep, ['work_type', 'smoking_status'])\nX_prep.drop(columns=['work_type', 'smoking_status'], inplace=True)\n# Fill the NaN in BMI column\nX_prep['bmi'].fillna(X_prep['bmi'].median(), inplace=True)\n# Scaling\nscaler = StandardScaler()\nX_prep = pd.DataFrame(data=scaler.fit_transform(X_prep), index=X_prep.index, columns=X_prep.columns)\n\"\"\"\n# 1) Logistic regression\n\"\"\"\nC_regul = [0.01, 0.1, 1]\nfor regul in C_regul:\n    clf = LogisticRegression(penalty='l2', C=regul).fit(X_prep, y)\n    print('Cross-validation score: %f' % \n          cross_val_score(clf, X_prep, y, cv=cv, scoring='roc_auc').mean())\n\"\"\"\n# 2) Support Vector Machine (SVM)\n\"\"\"\n# Find the best value for C regularization parameter\ngrid_linear = {'C': [0.0001]}\ngrid_poly = {'C': [0.01, 0.1, 1], 'gamma': [0.001, 0.01, 0.1], 'coef0': [3, 4]}\ngrid_rbf = {'C': [0.1, 1], 'gamma': [0.001, 0.01, 0.1]}\ngrid_sigmoid = {'C': [0.001, 0.01, 0.1], 'gamma': [0.0001, 0.01], 'coef0': [1, 10]}\ngrids = [grid_linear, grid_poly, grid_rbf, grid_sigmoid]\nkernels = ['linear', 'poly', 'rbf', 'sigmoid']\nparams = []\nscores = []\nfor ind, kern in enumerate(kernels):\n    svc_clf = SVC(kernel=kern)\n    gs = GridSearchCV(estimator=svc_clf, param_grid=grids[ind], cv=cv, scoring='roc_auc')\n    gs.fit(X_prep, y)\n    params.append(gs.best_params_)\n    scores.append(gs.best_score_)\n    print(kern, gs.best_params_, gs.best_score_)\nparams_best = params[np.argmax(scores)]\nkern_best = kernels[np.argmax(scores)]\nprint('Best parameters: kernel = %s, C = %f, coef0 = %f, gamma = %f' % \n      (kern_best, params_best['C'], params_best['coef0'], params_best['gamma']))\nclf_svm = SVC(C=params_best['C'], \n              kernel=kern_best, \n              coef0=params_best['coef0'], \n              gamma=params_best['gamma']).fit(X_prep, y)\nprint('Cross-validation score: %f' % \n          cross_val_score(clf_svm, X_prep, y, cv=cv, scoring='roc_auc').mean())\n\"\"\"\n# 3) Decision tree\n\"\"\"\nX_tree = X_orig.copy()\n# Encode categorial features\n# Male - 1, Female - 0\nX_tree['gender'] = X_tree['gender'].map({'Male': 1, 'Female': 0, 'Other': 1})\n# urban - 1, rural - 0\nX_tree['Residence_type'] = X_tree['Residence_type'].map({'Urban': 1, 'Rural': 0})\n# ever_married yes - 1, no - 0\nX_tree['ever_married'] = X_tree['ever_married'].map({'Yes': 1, 'No': 0})\n# One-hot encoder for work_type, smoking_status\nX_tree = ohe(X_tree, ['work_type', 'smoking_status'])\nX_tree.drop(columns=['work_type', 'smoking_status'], inplace=True)\n# Fill the NaN in BMI column\nX_tree['bmi'].fillna(X_tree['bmi'].median(), inplace=True)\n# We do not need to scale our data for decision tree algorithm\nclf_tree = DecisionTreeClassifier(criterion='entropy', ccp_alpha=0.003)\nclf_tree.fit(X_tree, y)\nprint('Cross-validation score: %f' % cross_val_score(clf_tree, X_tree, y, cv=cv, scoring='roc_auc').mean())\n\"\"\"\n# 4) K-Nearest Neighbours\n\"\"\"\n# Find the best parameters\n# Actually, KNN is quite bad with highly unbalanced classes.\n# One should use some oversampling technique first, e.g. SMOTE (TODO)\ngrid = {'n_neighbors': [50, 75, 100], 'p': [1, 3, 5]}\n\nclf_knn = KNeighborsClassifier(weights='distance', metric='minkowski')\ngs = GridSearchCV(estimator=clf_knn, param_grid=grid, cv=cv, scoring='roc_auc')\ngs.fit(X_prep, y)\nprint('Best parameters: n_neighbors = %d, p = %d' % (gs.best_params_['n_neighbors'], gs.best_params_['p']))\n# Use the best parameters in the model\nclf_knn = KNeighborsClassifier(weights='distance', metric='minkowski', \n                               n_neighbors=gs.best_params_['n_neighbors'], \n                               p=gs.best_params_['p'])\nprint('Cross-validation score: %f' % cross_val_score(clf_knn, X_prep, y, cv=cv, scoring='roc_auc').mean())\n\"\"\"\n# 5) Naive Bayes\n\"\"\"\nclf_bayes = GaussianNB().fit(X_prep, y)\nprint('Cross-validation score: %f' % cross_val_score(clf_bayes, X_prep, y, cv=cv, scoring='roc_auc').mean())\n\"\"\"\n# 6) Random Forest\n\"\"\"\nX_forest = X_orig.copy()\n# Encode categorial features\n# Male - 1, Female - 0\nX_forest['gender'] = X_forest['gender'].map({'Male': 1, 'Female': 0, 'Other': 1})\n# urban - 1, rural - 0\nX_forest['Residence_type'] = X_forest['Residence_type'].map({'Urban': 1, 'Rural': 0})\n# ever_married yes - 1, no - 0\nX_forest['ever_married'] = X_forest['ever_married'].map({'Yes': 1, 'No': 0})\n# One-hot encoder for work_type, smoking_status\nX_forest = ohe(X_forest, ['work_type', 'smoking_status'])\nX_forest.drop(columns=['work_type', 'smoking_status'], inplace=True)\n# Fill the NaN in BMI column\nX_forest['bmi'].fillna(X_forest['bmi'].median(), inplace=True)\n# Find the best parameters\ngrid = {'n_estimators': [20, 50, 100, 200], 'ccp_alpha': [0.0, 0.01, 0.1], 'max_depth': [4, 5, 6]}\nclf_forest = RandomForestClassifier(criterion='entropy',\n                    max_features='auto')\ngs = GridSearchCV(clf_forest, param_grid=grid, cv=cv, scoring='roc_auc')\ngs.fit(X_forest, y)\nprint('Best parameters: n_estimators = %d, ccp_alpha = %f, max_depth = %d' % \n      (gs.best_params_['n_estimators'], gs.best_params_['ccp_alpha'], gs.best_params_['max_depth']))\n# Use the best parameters in the model\nclf_forest = RandomForestClassifier(criterion='entropy', max_features='auto',\n                                   n_estimators=gs.best_params_['n_estimators'],\n                                   ccp_alpha=gs.best_params_['ccp_alpha'],\n                                   max_depth=gs.best_params_['max_depth'])\nprint('Cross-validation score: %f' % cross_val_score(clf_forest, X_forest, y, cv=cv, scoring='roc_auc').mean())","meta":"{'source': 'AI4Code', 'id': '38345513f29a44'}"}
{"id":"71574","text":"import pandas as pd\npd.plotting.register_matplotlib_converters()\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nprint(\"Setup Complete\")\nnetflix_filepath = \"..\/input\/netflix-shows\/netflix_titles.csv\"\n\nnetflix_data = pd.read_csv(netflix_filepath)\nnetflix_ratings =netflix_data['rating'].value_counts()\n#netflix_data.head()\n#netflix_data\nnetflix_ratings\n\"\"\"\nnumber of shows available on Netflix = 7669\nnumber of shows suitable for children 13 and under = 2229\n\"\"\"\n\"\"\"\n* TV-MA=15+\n* TV-14=14+\n* TV-PG=PG(<13)\n* TV-Y =for all ages\n* TV-Y7=for children above 7\n* TV-G =for all ages\n* NR   = not rated \n* TV-Y7-FV=for children 7 and above (include fantsy violence)\n* UR   =Unrated\n* NC-17=not for children below 17\n\n\"\"\"\n\"\"\"\nWhat proportioned of the available shows are for younger viewers (PG and below)?\n\"\"\"\nplt.figure(figsize=(14,8))\nsns.barplot(x=netflix_ratings.index, y=netflix_ratings)\nplt.title(\"Ratings and Viewership\")\n\"\"\"\nTo make this bar graph i used the command sns.barplot from the bar charts course and replaced their data with mine.\n\"\"\"\nd = {'Shows':[\"Total shows\", \"Shows for under 13\"], 'Total shows': [7669, 2229]}\ndf = pd.DataFrame(data=d)\ndf\nsns.barplot(x=df['Shows'], y=df['Total shows'])\n\"\"\"\nthis graph above shows a clear difference in proportion of shows available shows for audience 13 and under.\nbased on this we can predict that the majority of the members subscripted to netflix are adults as most shows targets an older audience.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '839ecffcd9f160'}"}
{"id":"840","text":"\"\"\"\n### \u0417\u0430\u0434\u0430\u043d\u0438\u0435 \u0434\u043b\u044f \u043a\u0443\u0440\u0441\u043e\u0432\u043e\u0433\u043e \u043f\u0440\u043e\u0435\u043a\u0442\u0430\n\n\u041c\u0435\u0442\u0440\u0438\u043a\u0430:\nR2 - \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442 \u0434\u0435\u0442\u0435\u0440\u043c\u0438\u043d\u0430\u0446\u0438\u0438 (sklearn.metrics.r2_score)\n\n\u0421\u0434\u0430\u0447\u0430 \u043f\u0440\u043e\u0435\u043a\u0442\u0430:\n1. \u0421\u043e\u0440\u0435\u0432\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u0437\u0430\u043a\u0430\u043d\u0447\u0438\u0432\u0430\u0435\u0442\u0441\u044f 02.03.21\n2. \u041f\u0440\u0438\u0441\u043b\u0430\u0442\u044c \u0432 \u0440\u0430\u0437\u0434\u0435\u043b \u0417\u0430\u0434\u0430\u043d\u0438\u044f \u0423\u0440\u043e\u043a\u0430 10 (\"\u0412\u0435\u0431\u0438\u043d\u0430\u0440. \u041a\u043e\u043d\u0441\u0443\u043b\u044c\u0442\u0430\u0446\u0438\u044f \u043f\u043e \u0438\u0442\u043e\u0433\u043e\u0432\u043e\u043c\u0443 \u043f\u0440\u043e\u0435\u043a\u0442\u0443\")\n\u0441\u0441\u044b\u043b\u043a\u0443 \u043d\u0430 \u043d\u043e\u0443\u0442\u0431\u0443\u043a \u0432 github \u0438\u043b\u0438 public kaggle notebook.\n3. \u041d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c R2 > 0.6 \u043d\u0430 Private Leaderboard.\n4. \u0423\u043a\u0430\u0436\u0438\u0442\u0435 \u0441\u0432\u043e\u0439 \u043d\u0438\u043a \u043d\u0430 kaggle \n\n\n\u041f\u0440\u0438\u043c\u0435\u0447\u0430\u043d\u0438\u0435:\n\u0412\u0441\u0435 \u0444\u0430\u0439\u043b\u044b csv \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u043f\u043e\u043b\u0435\u0439 (header - \u0442\u043e \u0435\u0441\u0442\u044c \"\u0448\u0430\u043f\u043a\u0443\"),\n\u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c - \u0437\u0430\u043f\u044f\u0442\u0430\u044f. \u0412 \u0444\u0430\u0439\u043b\u0430\u0445 \u043d\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c\u0441\u044f \u0438\u043d\u0434\u0435\u043a\u0441\u044b \u0438\u0437 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c\u0430.\n____________\n\u0420\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0438 \u0434\u043b\u044f \u0444\u0430\u0439\u043b\u0430 \u0441 \u043a\u043e\u0434\u043e\u043c (ipynb):\n1. \u0424\u0430\u0439\u043b \u0434\u043e\u043b\u0436\u0435\u043d \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c \u0437\u0430\u0433\u043e\u043b\u043e\u0432\u043a\u0438 \u0438 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u0438\n2. \u041f\u043e\u0432\u0442\u043e\u0440\u044f\u044e\u0449\u0438\u0435\u0441\u044f \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438 \u043b\u0443\u0447\u0448\u0435 \u043e\u0444\u043e\u0440\u043c\u043b\u044f\u0442\u044c \u0432 \u0432\u0438\u0434\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0439\n3. \u041f\u043e \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0441\u0442\u0438 \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0442\u044c \u0433\u0440\u0430\u0444\u0438\u043a\u0438, \u043e\u043f\u0438\u0441\u044b\u0432\u0430\u044e\u0449\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 (\u043e\u043a\u043e\u043b\u043e 3-5)\n4. \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0442\u044c \u0442\u043e\u043b\u044c\u043a\u043e \u043b\u0443\u0447\u0448\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c, \u0442\u043e \u0435\u0441\u0442\u044c \u043d\u0435 \u0432\u043a\u043b\u044e\u0447\u0430\u0442\u044c \u0432 \u043a\u043e\u0434 \u0432\u0441\u0435 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u044b \u0440\u0435\u0448\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u0435\u043a\u0442\u0430\n5. \u0421\u043a\u0440\u0438\u043f\u0442 \u043f\u0440\u043e\u0435\u043a\u0442\u0430 \u0434\u043e\u043b\u0436\u0435\u043d \u043e\u0442\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0442\u044c \u043e\u0442 \u043d\u0430\u0447\u0430\u043b\u0430 \u0438 \u0434\u043e \u043a\u043e\u043d\u0446\u0430 (\u043e\u0442 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043e \u0432\u044b\u0433\u0440\u0443\u0437\u043a\u0438 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0439)\n6. \u0412\u0435\u0441\u044c \u043f\u0440\u043e\u0435\u043a\u0442 \u0434\u043e\u043b\u0436\u0435\u043d \u0431\u044b\u0442\u044c \u0432 \u043e\u0434\u043d\u043e\u043c \u0441\u043a\u0440\u0438\u043f\u0442\u0435 (\u0444\u0430\u0439\u043b ipynb).\n7. \u041f\u0440\u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0438 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a (\u0441\u0440\u0435\u0434\u043d\u0435\u0435, \u043c\u0435\u0434\u0438\u0430\u043d\u0430 \u0438 \u0442.\u0434.) \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432, \u043b\u0443\u0447\u0448\u0435 \u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0438\u0445 \u043d\u0430 \u0442\u0440\u0435\u0439\u043d\u0435, \u0438 \u043f\u043e\u0442\u043e\u043c \u043d\u0430 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0445 \u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u043d\u0435 \u0441\u0447\u0438\u0442\u0430\u0442\u044c \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438 \u0437\u0430\u043d\u043e\u0432\u043e, \u0430 \u0431\u0440\u0430\u0442\u044c \u0438\u0445 \u0441 \u0442\u0440\u0435\u0439\u043d\u0430.\n8. \u041f\u0440\u043e\u0435\u043a\u0442 \u0434\u043e\u043b\u0436\u0435\u043d \u043f\u043e\u043b\u043d\u043e\u0441\u0442\u044c\u044e \u043e\u0442\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0442\u044c \u0437\u0430 \u0440\u0430\u0437\u0443\u043c\u043d\u043e\u0435 \u0432\u0440\u0435\u043c\u044f (\u043d\u0435 \u0431\u043e\u043b\u044c\u0448\u0435 10 \u043c\u0438\u043d\u0443\u0442), \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0432 \u0444\u0438\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442 \u043b\u0443\u0447\u0448\u0435 \u043d\u0435 \u0432\u043a\u043b\u044e\u0447\u0430\u0442\u044c GridSearch \u0441 \u043f\u0435\u0440\u0435\u0431\u043e\u0440\u043e\u043c \u0431\u043e\u043b\u044c\u0448\u043e\u0433\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0439 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432. \n\"\"\"\n\"\"\"\n**\u041f\u043b\u0430\u043d \u0437\u0430\u043d\u044f\u0442\u0438\u044f**\n* [\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445](#load)\n* [1. EDA](#eda)\n* [2. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432](#outlier)\n* [3. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432](#nan)\n* [4. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#feature)\n* [5. \u041e\u0442\u0431\u043e\u0440 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#feature_selection)\n* [6. \u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043d\u0430 train \u0438 test](#split)\n* [7. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438](#modeling)\n* [8. \u041f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435](#prediction)\n\"\"\"\n\"\"\"\n**\u041f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a \u0438 \u0441\u043a\u0440\u0438\u043f\u0442\u043e\u0432**\n\"\"\"\n# 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 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\nimport numpy as np\nimport pandas as pd\nimport random\n\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import r2_score as r2\nfrom sklearn.model_selection import KFold, GridSearchCV\n\nfrom datetime import datetime\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\nmatplotlib.rcParams.update({'font.size': 14})\ndef evaluate_preds(train_true_values, train_pred_values, test_true_values, test_pred_values):\n    print(\"Train R2:\\t\" + str(round(r2(train_true_values, train_pred_values), 3)))\n    print(\"Test R2:\\t\" + str(round(r2(test_true_values, test_pred_values), 3)))\n    \n    plt.figure(figsize=(18,10))\n    \n    plt.subplot(121)\n    sns.scatterplot(x=train_pred_values, y=train_true_values)\n    plt.xlabel('Predicted values')\n    plt.ylabel('True values')\n    plt.title('Train sample prediction')\n    \n    plt.subplot(122)\n    sns.scatterplot(x=test_pred_values, y=test_true_values)\n    plt.xlabel('Predicted values')\n    plt.ylabel('True values')\n    plt.title('Test sample prediction')\n\n    plt.show()\n\"\"\"\n**\u041f\u0443\u0442\u0438 \u043a \u0434\u0438\u0440\u0435\u043a\u0442\u043e\u0440\u0438\u044f\u043c \u0438 \u0444\u0430\u0439\u043b\u0430\u043c**\n\"\"\"\nTRAIN_DATASET_PATH = '\/kaggle\/input\/real-estate-price-prediction-moscow\/train.csv'\nTEST_DATASET_PATH = '\/kaggle\/input\/real-estate-price-prediction-moscow\/test.csv'\nRNDM = 21\n\"\"\"\n### \u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445 <a class='anchor' id='load'>\n\"\"\"\n\"\"\"\n**\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430**\n\n* **Id** - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b\n* **DistrictId** - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0440\u0430\u0439\u043e\u043d\u0430\n* **Rooms** - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043a\u043e\u043c\u043d\u0430\u0442\n* **Square** - \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n* **LifeSquare** - \u0436\u0438\u043b\u0430\u044f \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n* **KitchenSquare** - \u043f\u043b\u043e\u0449\u0430\u0434\u044c \u043a\u0443\u0445\u043d\u0438\n* **Floor** - \u044d\u0442\u0430\u0436\n* **HouseFloor** - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0432 \u0434\u043e\u043c\u0435\n* **HouseYear** - \u0433\u043e\u0434 \u043f\u043e\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u0434\u043e\u043c\u0430\n* **Ecology_1, Ecology_2, Ecology_3** - \u044d\u043a\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438\n* **Social_1, Social_2, Social_3** - \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438\n* **Healthcare_1, Helthcare_2** - \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u0441 \u043e\u0445\u0440\u0430\u043d\u043e\u0439 \u0437\u0434\u043e\u0440\u043e\u0432\u044c\u044f\n* **Shops_1, Shops_2** - \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u0441 \u043d\u0430\u043b\u0438\u0447\u0438\u0435\u043c \u043c\u0430\u0433\u0430\u0437\u0438\u043d\u043e\u0432, \u0442\u043e\u0440\u0433\u043e\u0432\u044b\u0445 \u0446\u0435\u043d\u0442\u0440\u043e\u0432\n* **Price** - \u0446\u0435\u043d\u0430 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b\n\"\"\"\ntrain_df = pd.read_csv(TRAIN_DATASET_PATH)\ntrain_df.tail()\ntrain_df.dtypes\ntest_df = pd.read_csv(TEST_DATASET_PATH)\ntest_df.tail()\nprint('\u0421\u0442\u0440\u043e\u043a \u0432 \u0442\u0440\u0435\u0439\u043d\u0435:', train_df.shape[0])\nprint('\u0421\u0442\u0440\u043e\u043a \u0432 \u0442\u0435\u0441\u0442\u0435', test_df.shape[0])\ntrain_df.shape[1] - 1 == test_df.shape[1]\n\"\"\"\n### \u041f\u0440\u0438\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0442\u0438\u043f\u043e\u0432\n\"\"\"\ntrain_df.dtypes\ntrain_df['Id'] = train_df['Id'].astype(str)\ntrain_df['DistrictId'] = train_df['DistrictId'].astype(str)\n\"\"\"\n## 1. EDA  <a class='anchor' id='eda'>\n\u0414\u0435\u043b\u0430\u0435\u043c EDA \u0434\u043b\u044f:\n- \u0418\u0441\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\n- \u0417\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f NaN\n- \u0418\u0434\u0435\u0439 \u0434\u043b\u044f \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438 \u043d\u043e\u0432\u044b\u0445 \u0444\u0438\u0447\n\"\"\"\n\"\"\"\n**\u0426\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f**\n\"\"\"\nplt.figure(figsize = (16, 8))\n\ntrain_df['Price'].hist(bins=30)\nplt.ylabel('Count')\nplt.xlabel('Price')\n\nplt.title('Target distribution')\nplt.show()\n\"\"\"\n**\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435**\n\"\"\"\ntrain_df.describe()\ndf_num_features = train_df.select_dtypes(include=['float64', 'int64'])\ndf_num_features.drop('Price', axis=1, inplace=True)\ndf_num_features.hist(figsize=(16,16), bins=20, grid=False);\n\"\"\"\n**\u041d\u043e\u043c\u0438\u043d\u0430\u0442\u0438\u0432\u043d\u044b\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435**\n\"\"\"\ntrain_df.select_dtypes(include='object').columns.tolist()\ntrain_df['DistrictId'].value_counts()\ntrain_df['Ecology_2'].value_counts()\ntrain_df['Ecology_3'].value_counts()\ntrain_df['Shops_2'].value_counts()\n\"\"\"\n### 2. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432  <a class='anchor' id='outlier'>\n\u0427\u0442\u043e \u043c\u043e\u0436\u043d\u043e \u0434\u0435\u043b\u0430\u0442\u044c \u0441 \u043d\u0438\u043c\u0438?\n1. \u0412\u044b\u043a\u0438\u043d\u0443\u0442\u044c \u044d\u0442\u0438 \u0434\u0430\u043d\u043d\u044b\u0435 (\u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0430 \u0442\u0440\u0435\u0439\u043d\u0435, \u043d\u0430 \u0442\u0435\u0441\u0442\u0435 \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0432\u044b\u043a\u0438\u0434\u044b\u0432\u0430\u0435\u043c)\n2. \u0417\u0430\u043c\u0435\u043d\u044f\u0442\u044c \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u0440\u0430\u0437\u043d\u044b\u043c\u0438 \u043c\u0435\u0442\u043e\u0434\u0430\u043c\u0438 (\u043c\u0435\u0434\u0438\u0430\u043d\u044b, \u0441\u0440\u0435\u0434\u043d\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, np.clip \u0438 \u0442.\u0434.)\n3. \u0414\u0435\u043b\u0430\u0442\u044c\/\u043d\u0435 \u0434\u0435\u043b\u0430\u0442\u044c \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u0443\u044e \u0444\u0438\u0447\u0443\n4. \u041d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0434\u0435\u043b\u0430\u0442\u044c\n\"\"\"\n\"\"\"\n**Square**\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u043e\u0431\u0440\u0435\u0436\u0435\u043c \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u043d\u044b\u0435 \u043c\u0435\u0442\u0440\u044b\n\"\"\"\ntrain_df.loc[train_df['Square'] < 3, 'Square'] = 3\n\"\"\"\n**Rooms**\n\"\"\"\n\"\"\"\n\u0432\u044b\u0440\u0430\u0437\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043a\u043e\u043c\u043d\u0430\u0442 \u0447\u0435\u0440\u0435\u0437 \u043e\u0431\u0449\u0443\u044e \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n\"\"\"\ntrain_df['Rooms'].value_counts()\ntrain_df['Rooms_outlier'] = 0\ntrain_df.loc[(train_df['Rooms'] == 0) | (train_df['Rooms'] >= 6), 'Rooms_outlier'] = 1\ntrain_df.head()\ntrain_df.loc[train_df['Rooms'] == 0, 'Rooms'] = 1\ntemp_df = train_df.loc[train_df['Rooms'] < 6]\nSquare_Rooms_K = (temp_df['Square'] \/ temp_df['Rooms']).median()\nSquare_Rooms_K\ntrain_df.loc[train_df['Rooms'] >= 6, 'Rooms'] = round(train_df['Square'] \/ Square_Rooms_K)\ntrain_df['Rooms'].value_counts()\n\"\"\"\n**KitchenSquare** \n\"\"\"\ntrain_df['KitchenSquare'].value_counts()\ntrain_df['KitchenSquare'].quantile(.975), train_df['KitchenSquare'].quantile(.025)\n\"\"\"\n\u0432\u044b\u0440\u0430\u0437\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u043f\u043b\u043e\u0449\u0430\u0434\u0438 \u043a\u0443\u0445\u043d\u0438 \u0447\u0435\u0440\u0435\u0437 \u043e\u0431\u0449\u0443\u044e \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n\"\"\"\ntemp_df = train_df.loc[train_df['KitchenSquare'] < train_df['Square']]\nSquare_KitchenSquare_K = (temp_df['Square'] \/ temp_df['KitchenSquare']).median()\nSquare_KitchenSquare_K\ncondition = (train_df['KitchenSquare'].isna()) \\\n             | (train_df['KitchenSquare'] > train_df['KitchenSquare'].quantile(.975))\ntrain_df.loc[condition, 'KitchenSquare'] = round(train_df['Square'] \/ Square_KitchenSquare_K)\n\ntrain_df.loc[train_df['KitchenSquare'] < 3, 'KitchenSquare'] = 3\ntrain_df['KitchenSquare'].value_counts()\n\"\"\"\n**HouseFloor, Floor**\n\"\"\"\ntrain_df['HouseFloor'].sort_values().unique()\ntrain_df['Floor'].sort_values().unique()\n(train_df['Floor'] > train_df['HouseFloor']).sum()\ntrain_df['HouseFloor_outlier'] = 0\ntrain_df.loc[train_df['HouseFloor'] == 0, 'HouseFloor_outlier'] = 1\ntrain_df.loc[train_df['Floor'] > train_df['HouseFloor'], 'HouseFloor_outlier'] = 1\ntrain_df.loc[train_df['HouseFloor'] == 0, 'HouseFloor'] = train_df['HouseFloor'].median()\nfloor_outliers = train_df.loc[train_df['Floor'] > train_df['HouseFloor']].index\nfloor_outliers\n# train_df.loc[floor_outliers, 'Floor'] = train_df.loc[floor_outliers, 'HouseFloor']\\\n#                                                 .apply(lambda x: random.randint(1, x))\n# \u0438\u0441\u043f\u0440\u0430\u0432\u0438\u043b \u044d\u0442\u0430\u0436\u043d\u043e\u0441\u0442\u044c, \u0430 \u043d\u0435 \u044d\u0442\u0430\u0436\n\ntrain_df.loc[floor_outliers, 'HouseFloor'] = train_df.loc[floor_outliers, 'Floor']\n(train_df['Floor'] > train_df['HouseFloor']).sum()\n\"\"\"\n**HouseYear**\n\"\"\"\ntrain_df['HouseYear'].sort_values(ascending=False)\ntrain_df.loc[train_df['HouseYear'] > 2020, 'HouseYear'] = 2020\ntrain_df.loc[train_df['HouseYear'] < 1900, 'HouseYear'] = 1900\n\"\"\"\n### 3. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432  <a class='anchor' id='nan'>\n\"\"\"\ntrain_df.isna().sum()\ntrain_df[['Square', 'LifeSquare', 'KitchenSquare']].head(10)\n\"\"\"\n**LifeSquare**\n\"\"\"\ntrain_df['LifeSquare_nan'] = train_df['LifeSquare'].isna() * 1\n\ncondition = (train_df['LifeSquare'].isna()) \\\n             & (~train_df['Square'].isna()) \\\n             & (~train_df['KitchenSquare'].isna())\n        \ntrain_df.loc[condition, 'LifeSquare'] = train_df.loc[condition, 'Square'] \\\n                                            - train_df.loc[condition, 'KitchenSquare'] - 3\n\"\"\"\n**Healthcare_1**\n\"\"\"\ntrain_df.drop('Healthcare_1', axis=1, inplace=True)\nclass DataPreprocessing:\n    \"\"\"\u041f\u043e\u0434\u0433\u043e\u0442\u043e\u0432\u043a\u0430 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445\"\"\"\n\n    def __init__(self):\n        \"\"\"\u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u043a\u043b\u0430\u0441\u0441\u0430\"\"\"\n        self.medians=None\n        self.kitchen_square_quantile = None\n        self.temp_df = None\n        \n        \n    def fit(self, X):\n        \"\"\"\u0421\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\"\"\"       \n        # \u0420\u0430\u0441\u0447\u0435\u0442 \u043c\u0435\u0434\u0438\u0430\u043d\n        self.medians = X.median()\n        self.kitchen_square_quantile = X['KitchenSquare'].quantile(.975)\n        \n    \n    def transform(self, X):\n        \"\"\"\u0422\u0440\u0430\u043d\u0441\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\"\"\"\n\n        # Square\n        X.loc[X['Square'] < 3, 'Square'] = 3\n        \n        # Rooms\n        X['Rooms_outlier'] = 0\n        X.loc[(X['Rooms'] == 0) | (X['Rooms'] >= 6), 'Rooms_outlier'] = 1\n        \n        X.loc[X['Rooms'] == 0, 'Rooms'] = 1\n        \n        self.temp_df = X.loc[X['Rooms'] < 6]\n        Square_Rooms_K = (self.temp_df['Square'] \/ self.temp_df['Rooms']).median()\n        X.loc[X['Rooms'] >= 6, 'Rooms'] = round(X['Square'] \/ Square_Rooms_K)\n                \n        # KitchenSquare\n        self.temp_df = X.loc[X['KitchenSquare'] < X['Square']]\n        Square_KitchenSquare_K = (self.temp_df['Square'] \/ self.temp_df['KitchenSquare']).median()\n        condition = (X['KitchenSquare'].isna()) \\\n                    | (X['KitchenSquare'] > self.kitchen_square_quantile)\n        \n        X.loc[condition, 'KitchenSquare'] = round(X['Square'] \/ Square_KitchenSquare_K)\n        X.loc[X['KitchenSquare'] < 3, 'KitchenSquare'] = 3\n        \n        # HouseFloor, Floor\n        X['HouseFloor_outlier'] = 0\n        X.loc[X['HouseFloor'] == 0, 'HouseFloor_outlier'] = 1\n        X.loc[X['Floor'] > X['HouseFloor'], 'HouseFloor_outlier'] = 1\n        \n        X.loc[X['HouseFloor'] == 0, 'HouseFloor'] = self.medians['HouseFloor']\n        \n        floor_outliers = X.loc[X['Floor'] > X['HouseFloor']].index\n#         X.loc[floor_outliers, 'Floor'] = X.loc[floor_outliers, 'HouseFloor']\\\n#                                             .apply(lambda x: random.randint(1, x))\n        X.loc[floor_outliers, 'HouseFloor'] = X.loc[floor_outliers, 'Floor']\n        \n        # HouseYear\n        current_year = datetime.now().year\n        \n        X['HouseYear_outlier'] = 0\n        X.loc[X['HouseYear'] > current_year, 'HouseYear_outlier'] = 1\n        X.loc[X['HouseYear'] < 1900, 'HouseYear_outlier'] = 1\n        \n        X.loc[X['HouseYear'] > current_year, 'HouseYear'] = current_year\n        X.loc[X['HouseYear'] < 1900, 'HouseYear'] = 1900\n        \n        # Healthcare_1\n        if 'Healthcare_1' in X.columns:\n            X.drop('Healthcare_1', axis=1, inplace=True)\n            \n        # LifeSquare\n        X['LifeSquare_nan'] = X['LifeSquare'].isna() * 1\n        condition = (X['LifeSquare'].isna()) & \\\n                      (~X['Square'].isna()) & \\\n                      (~X['KitchenSquare'].isna())\n        \n        X.loc[condition, 'LifeSquare'] = X.loc[condition, 'Square'] - X.loc[condition, 'KitchenSquare'] - 3\n        \n        \n        X.fillna(self.medians, inplace=True)\n        \n        return X\n\"\"\"\n### 4. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432  <a class='anchor' id='feature'>\n\"\"\"\ntrain_df_corr = train_df.corr()\nimport seaborn as sns\nplt.figure(figsize = (16,8))\nsns.set(font_scale=0.8)\ntrain_df_corr_round = np.round(train_df_corr, 2)\ntrain_df_corr_round[np.abs(train_df_corr) < 0.3] = 0\nsns.heatmap(train_df_corr_round, annot=True, linewidths=.5, cmap='coolwarm')\nplt.show()\n\"\"\"\n#### \u043c\u043e\u0436\u043d\u043e \u043f\u043e\u043f\u0440\u043e\u0431\u043e\u0432\u0430\u0442\u044c \u043d\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c social_1 \u0438\u043b\u0438 social_2 (\u0438\u0437-\u0437\u0430 \u043a\u043e\u0440\u0435\u043b\u044f\u0446\u0438\u0438)\n\"\"\"\n\"\"\"\n**Dummies**\n\"\"\"\nbinary_to_numbers = {'A': 0, 'B': 1}\n\ntrain_df['Ecology_2'] = train_df['Ecology_2'].replace(binary_to_numbers)\ntrain_df['Ecology_3'] = train_df['Ecology_3'].replace(binary_to_numbers)\ntrain_df['Shops_2'] = train_df['Shops_2'].replace(binary_to_numbers)\n\"\"\"\n**DistrictSize, IsDistrictLarge**\n\"\"\"\ndistrict_size = train_df['DistrictId'].value_counts().reset_index()\\\n                    .rename(columns={'index':'DistrictId', 'DistrictId':'DistrictSize'})\n\ndistrict_size.head()\ntrain_df = train_df.merge(district_size, on='DistrictId', how='left')\ntrain_df.head()\n(train_df['DistrictSize'] > 100).value_counts()\ntrain_df['IsDistrictLarge'] = (train_df['DistrictSize'] > 100).astype(int)\n\"\"\"\n**MedPriceByDistrict**\n\"\"\"\nmed_price_by_district = train_df.groupby(['DistrictId', 'Rooms'], as_index=False).agg({'Price':'median'})\\\n                            .rename(columns={'Price':'MedPriceByDistrict'})\n\nmed_price_by_district.head()\ntrain_df = train_df.merge(med_price_by_district, on=['DistrictId', 'Rooms'], how='left')\ntrain_df.head()\n\"\"\"\n**MedPriceByFloorYear**\n\"\"\"\ndef floor_to_cat(X):\n\n    X['floor_cat'] = 0\n\n    X.loc[X['Floor'] <= 3, 'floor_cat'] = 1  \n    X.loc[(X['Floor'] > 3) & (X['Floor'] <= 5), 'floor_cat'] = 2\n    X.loc[(X['Floor'] > 5) & (X['Floor'] <= 9), 'floor_cat'] = 3\n    X.loc[(X['Floor'] > 9) & (X['Floor'] <= 15), 'floor_cat'] = 4\n    X.loc[X['Floor'] > 15, 'floor_cat'] = 5\n\n    return X\n\n\ndef floor_to_cat_pandas(X):\n    bins = [0, 3, 5, 9, 15, X['Floor'].max()]\n    X['floor_cat'] = pd.cut(X['Floor'], bins=bins, labels=False)\n    \n    X['floor_cat'].fillna(-1, inplace=True)\n    return X\n\n\ndef year_to_cat(X):\n\n    X['year_cat'] = 0\n\n    X.loc[X['HouseYear'] <= 1941, 'year_cat'] = 1\n    X.loc[(X['HouseYear'] > 1941) & (X['HouseYear'] <= 1945), 'year_cat'] = 2\n    X.loc[(X['HouseYear'] > 1945) & (X['HouseYear'] <= 1980), 'year_cat'] = 3\n    X.loc[(X['HouseYear'] > 1980) & (X['HouseYear'] <= 2000), 'year_cat'] = 4\n    X.loc[(X['HouseYear'] > 2000) & (X['HouseYear'] <= 2010), 'year_cat'] = 5\n    X.loc[(X['HouseYear'] > 2010), 'year_cat'] = 6\n\n    return X\n\n\ndef year_to_cat_pandas(X):\n    bins = [0, 1941, 1945, 1980, 2000, 2010, X['HouseYear'].max()]\n    X['year_cat'] = pd.cut(X['HouseYear'], bins=bins, labels=False)\n    \n    X['year_cat'].fillna(-1, inplace=True)\n    return X\nbins = [0, 3, 5, 9, 15, train_df['Floor'].max()]\npd.cut(train_df['Floor'], bins=bins, labels=False)\nbins = [0, 3, 5, 9, 15, train_df['Floor'].max()]\npd.cut(train_df['Floor'], bins=bins)\ntrain_df = year_to_cat(train_df)\ntrain_df = floor_to_cat(train_df)\ntrain_df.head()\nmed_price_by_floor_year = train_df.groupby(['year_cat', 'floor_cat'], as_index=False).agg({'Price':'median'}).\\\n                                            rename(columns={'Price':'MedPriceByFloorYear'})\nmed_price_by_floor_year.head()\ntrain_df = train_df.merge(med_price_by_floor_year, on=['year_cat', 'floor_cat'], how='left')\ntrain_df.head()\n\"\"\"\n#### \u041d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\ncolnames = train_df.columns\ntrain_df_scaled = pd.DataFrame(scaler.fit_transform(train_df), columns=colnames)\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\ntrain_df_scaled = pd.DataFrame(scaler.fit_transform(train_df), columns=['Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear',\n                 'Ecology_1', 'Ecology_2', 'Ecology_3', 'Social_1', 'Social_2', 'Social_3',\n                 'Helthcare_2', 'Shops_1', 'Shops_2'])\n\"\"\"\ntrain_df_scaled.head()\nfrom sklearn.manifold import TSNE\ndef reduce_dims(df, dims=2, method='pca', perplexity=30):\n    \n    assert method in ['pca', 'tsne'], '\u041d\u0435\u0432\u0435\u0440\u043d\u043e \u0443\u043a\u0430\u0437\u0430\u043d \u043c\u0435\u0442\u043e\u0434'\n    \n    if method=='pca':\n        dim_reducer = PCA(n_components=dims, random_state=42)\n        components = dim_reducer.fit_transform(df)\n    elif method == 'tsne':\n        dim_reducer = TSNE(n_components=dims, learning_rate=250, random_state=42, perplexity=perplexity)\n        components = dim_reducer.fit_transform(df)\n    else:\n        print('Error')\n        \n    colnames = ['component_' + str(i) for i in range(1, dims+1)]\n    return dim_reducer, pd.DataFrame(data = components, columns = colnames) \ndef display_components_in_2D_space(components_df, labels=None):\n    components_with_labels_df = pd.concat([components_df, pd.DataFrame(labels)], axis=1)\n\n    figsize = (10, 7)\n    if labels is not None:\n        components_with_labels_df.plot(kind='scatter', x='component_1', y='component_2', \n                                         c=components_with_labels_df.iloc[:, -1], cmap=plt.get_cmap('jet'),\n                                         alpha=0.5, figsize=figsize)\n    else:\n        components_with_labels_df.plot(kind='scatter', x='component_1', y='component_2', alpha=0.5, figsize=figsize)\n\n    plt.xlabel('component_1')\n    plt.ylabel('component_2')\n    plt.title('2D mapping of objects')    \n    plt.show()\n\ndef display_components_in_3D_space(components_df, labels=None):\n    components_with_labels_df = pd.concat([components_df, pd.DataFrame(labels)], axis=1)\n\n    fig = plt.figure(figsize=(10,10))\n    ax = fig.add_subplot(111, projection='3d')\n    \n    if labels is not None:\n        ax.scatter(components_with_labels_df['component_1'], \n                   components_with_labels_df['component_2'], \n                   components_with_labels_df['component_3'], \n                   c=components_with_labels_df.iloc[:, -1], \n                   cmap=plt.get_cmap('jet'), alpha=0.5)\n    else:\n        ax.scatter(components_with_labels_df['component_1'], \n                   components_with_labels_df['component_2'], \n                   components_with_labels_df['component_3'], \n                   alpha=0.5)\n\n    ax.set_xlabel('component_1')\n    ax.set_ylabel('component_2')\n    ax.set_zlabel('component_3')\n    plt.title('3D mapping of objects')\n    plt.show()\n\"\"\"\n%%time\ndim_reducer2d_tsne, components_2d_tsne = reduce_dims(train_df_scaled, dims=2, method='tsne', perplexity=50)\ndisplay_components_in_2D_space(components_2d_tsne, train_df['Price'])\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist\ndef apply_elbow_method(X):\n    \"\"\"\u0412\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u0434\u043b\u044f \u043c\u0435\u0442\u043e\u0434\u0430 '\u043b\u043e\u043a\u0442\u044f'\"\"\"\n    \n    distortions = []\n    K = range(2,30)\n    for k in K:\n        kmeanModel = KMeans(n_clusters=k, random_state=RNDM).fit(X)\n        distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) \/ X.shape[0])\n\n    plt.figure(figsize=(10, 8))\n    plt.plot(K, distortions, 'bx-')\n    plt.xlabel('k')\n    plt.ylabel('Distortion')\n    plt.title('The Elbow Method showing the optimal k')\n    plt.show()\n\"\"\"\napply_elbow_method(train_df_scaled)\n\"\"\"\ndef display_clusters_distribution(unique_labels, labels_counts):\n    \"\"\"\u0412\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u043a\u043b\u0430\u0441\u0441\u043e\u0432 \u043f\u043e \u043a\u043b\u0430\u0441\u0442\u0435\u0440\u0430\u043c\"\"\"\n    plt.figure(figsize=(8,5))\n\n    plt.bar(unique, counts)\n\n    plt.xlabel('Clusters')\n    plt.xticks(unique)\n    plt.ylabel('Count')\n    plt.title('Clusters distribution')\n    plt.show()\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\nkmeans_n = KMeans(n_clusters=8, random_state=RNDM)\nlabels_clast_n = kmeans_n.fit_predict(train_df_scaled)\nlabels_clast_n = pd.Series(labels_clast_n, name='clusters_n')\n\nunique, counts = np.unique(labels_clast_n, return_counts=True)\ndisplay_clusters_distribution(unique, counts)\nclusters_n_dummies = pd.get_dummies(labels_clast_n, drop_first=True, prefix='clusters')\n\ntrain_df_cluster = pd.concat([train_df_scaled, clusters_n_dummies], axis=1)\ntrain_df_cluster.head()\n\"\"\"\n\u0412\u0441\u0435 \u044d\u0442\u043e \u043a\u0440\u0443\u0442\u043e, \u043d\u043e \u043a\u043b\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u044f \u043d\u0435 \u043f\u043e\u043c\u043e\u0433\u043b\u0430\n\"\"\"\nclass FeatureGenetator():\n    \"\"\"\u0413\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044f \u043d\u043e\u0432\u044b\u0445 \u0444\u0438\u0447\"\"\"\n    \n    def __init__(self):\n        self.DistrictId_counts = None\n        self.binary_to_numbers = None\n        self.med_price_by_district = None\n        self.med_price_by_floor_year = None\n        self.house_year_max = None\n        self.floor_max = None\n        \n    def fit(self, X, y=None):\n        \n        X = X.copy()\n        \n        # Binary features\n        self.binary_to_numbers = {'A': 0, 'B': 1}\n        \n        # DistrictID\n        self.district_size = X['DistrictId'].value_counts().reset_index() \\\n                               .rename(columns={'index':'DistrictId', 'DistrictId':'DistrictSize'})\n                \n        # Target encoding\n        ## District, Rooms\n        df = X.copy()\n        \n        if y is not None:\n            df['Price'] = y.values\n            \n            self.med_price_by_district = df.groupby(['DistrictId', 'Rooms'], as_index=False).agg({'Price':'median'})\\\n                                            .rename(columns={'Price':'MedPriceByDistrict'})\n            \n            self.med_price_by_district_median = self.med_price_by_district['MedPriceByDistrict'].median()\n            \n        ## floor, year\n        if y is not None:\n            self.floor_max = df['Floor'].max()\n            self.house_year_max = df['HouseYear'].max()\n            df['Price'] = y.values\n            df = self.floor_to_cat(df)\n            df = self.year_to_cat(df)\n            self.med_price_by_floor_year = df.groupby(['year_cat', 'floor_cat'], as_index=False).agg({'Price':'median'}).\\\n                                            rename(columns={'Price':'MedPriceByFloorYear'})\n            self.med_price_by_floor_year_median = self.med_price_by_floor_year['MedPriceByFloorYear'].median()\n        \n\n        \n    def transform(self, X):\n        \n        # Binary features\n        X['Ecology_2'] = X['Ecology_2'].map(self.binary_to_numbers)  # self.binary_to_numbers = {'A': 0, 'B': 1}\n        X['Ecology_3'] = X['Ecology_3'].map(self.binary_to_numbers)\n        X['Shops_2'] = X['Shops_2'].map(self.binary_to_numbers)\n        \n        # DistrictId, IsDistrictLarge\n        X = X.merge(self.district_size, on='DistrictId', how='left')\n        \n        X['new_district'] = 0\n        X.loc[X['DistrictSize'].isna(), 'new_district'] = 1\n        \n        X['DistrictSize'].fillna(5, inplace=True)\n        \n        X['IsDistrictLarge'] = (X['DistrictSize'] > 100).astype(int)\n        \n        # More categorical features\n        X = self.floor_to_cat(X)  # + \u0441\u0442\u043e\u043b\u0431\u0435\u0446 floor_cat\n        X = self.year_to_cat(X)   # + \u0441\u0442\u043e\u043b\u0431\u0435\u0446 year_cat\n        X = self.last_floor(X)   # + \u0441\u0442\u043e\u043b\u0431\u0435\u0446 last_floor\n        X = self.first_floor(X)   # + \u0441\u0442\u043e\u043b\u0431\u0435\u0446 first_floor\n        \n        \n        # Target encoding\n        if self.med_price_by_district is not None:\n            X = X.merge(self.med_price_by_district, on=['DistrictId', 'Rooms'], how='left')\n            X.fillna(self.med_price_by_district_median, inplace=True)\n            \n        if self.med_price_by_floor_year is not None:\n            X = X.merge(self.med_price_by_floor_year, on=['year_cat', 'floor_cat'], how='left')\n            X.fillna(self.med_price_by_floor_year_median, inplace=True)\n            \n            \n        # normalize\n#         scaler = StandardScaler()\n#         colnames = X.columns\n#         X = pd.DataFrame(scaler.fit_transform(X), columns=colnames)\n        # clusters\n        kmeans_n = KMeans(n_clusters=8, random_state=RNDM)\n        labels_clast_n = kmeans_n.fit_predict(X)\n        labels_clast_n = pd.Series(labels_clast_n, name='clusters_n')\n        # dummy clusters\n        clusters_n_dummies = pd.get_dummies(labels_clast_n, drop_first=True, prefix='clusters')\n        X = pd.concat([X, clusters_n_dummies], axis=1)\n        \n        return X\n    \n    def floor_to_cat(self, X):\n        bins = [0, 1, 4, 5, 8, 9, 13, 15, self.floor_max]\n        X['floor_cat'] = pd.cut(X['Floor'], bins=bins, labels=False)\n\n        X['floor_cat'].fillna(-1, inplace=True) \n        return X\n     \n    def year_to_cat(self, X):\n        bins = [0, 1941, 1945, 1980, 2000, 2010, self.house_year_max]\n        X['year_cat'] = pd.cut(X['HouseYear'], bins=bins, labels=False)\n\n        X['year_cat'].fillna(-1, inplace=True)\n        return X\n            \n    def last_floor(self, X):\n        X['last_floor'] = 0\n        X.loc[(X['Floor'] == X['HouseFloor']), 'last_floor'] = 1\n        return X\n    \n    def first_floor(self, X):\n        X['first_floor'] = 0\n        X.loc[(X['Floor'] == 1), 'first_floor'] = 1\n        return X\n\"\"\"\n### 5. \u041e\u0442\u0431\u043e\u0440 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432  <a class='anchor' id='feature_selection'>\n\"\"\"\ntrain_df_cluster.columns.tolist()\n\"\"\"\nfeature_names = ['Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear',\n                 'Ecology_1', 'Ecology_2', 'Ecology_3', 'Social_1', 'Social_2', 'Social_3',\n                 'Helthcare_2', 'Shops_1', 'Shops_2']\n\nnew_feature_names = ['Rooms_outlier', 'HouseFloor_outlier', 'HouseYear_outlier', 'LifeSquare_nan', 'DistrictSize',\n                     'new_district', 'IsDistrictLarge',  'MedPriceByDistrict', 'MedPriceByFloorYear',\n#                      'last_floor', 'first_floor',\n#                      'clusters_1','clusters_2','clusters_3', 'clusters_4', 'clusters_5', \n#                      'clusters_6', 'clusters_7'\n                    ]\n\ntarget_name = 'Price'\n\"\"\"\nfeature_names = ['DistrictId', 'Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear',\n                 'Ecology_1', 'Ecology_2', 'Ecology_3', 'Social_1', 'Social_2', 'Social_3', \n                 'Helthcare_2', 'Shops_1', 'Shops_2'] \n\nnew_feature_names = ['Rooms_outlier'] \n\ntarget_name = 'Price'\n\"\"\"\n### 6. \u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043d\u0430 train \u0438 test  <a class='anchor' id='split'>\n\"\"\"\ntrain_df = pd.read_csv(TRAIN_DATASET_PATH)\ntest_df = pd.read_csv(TEST_DATASET_PATH)\n\nX = train_df.drop(columns=target_name)\ny = train_df[target_name]\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33, shuffle=True, random_state=RNDM)\npreprocessor = DataPreprocessing()\npreprocessor.fit(X_train)\n\nX_train = preprocessor.transform(X_train)\nX_valid = preprocessor.transform(X_valid)\ntest_df = preprocessor.transform(test_df)\n\nX_train.shape, X_valid.shape, test_df.shape\nfeatures_gen = FeatureGenetator()\nfeatures_gen.fit(X_train, y_train)\n\nX_train = features_gen.transform(X_train)\nX_valid = features_gen.transform(X_valid)\ntest_df = features_gen.transform(test_df)\n\nX_train.shape, X_valid.shape, test_df.shape\nX_train = X_train[feature_names + new_feature_names]\nX_valid = X_valid[feature_names + new_feature_names]\ntest_df = test_df[feature_names + new_feature_names]\nX_train.isna().sum().sum(), X_valid.isna().sum().sum(), test_df.isna().sum().sum()\n\"\"\"\n### 7. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438  <a class='anchor' id='modeling'>\n\"\"\"\n\"\"\"\n**\u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435**\n\"\"\"\n%%time\nfrom sklearn.ensemble import GradientBoostingRegressor\n# from sklearn.ensemble import BaggingRegressor\n\ngb = GradientBoostingRegressor(\n                               max_depth=4,\n                               min_samples_leaf=20,\n                               random_state=RNDM,  \n                               n_estimators=150\n                              )\n\n# br = BaggingRegressor(base_estimator=gb, n_estimators=25, random_state=RNDM)\n# br.fit(X_train, y_train)\n%%time\nrf = RandomForestRegressor(\n    random_state=RNDM, \n    max_depth=40,  # gridsearch\n    criterion='mse',\n    min_samples_leaf=5,  # gridsearch\n    n_jobs=-1,\n    n_estimators=1000  # gridsearch\n)\n# rf.fit(X_train, y_train)\n%%time\nrf2 = RandomForestRegressor(\n    random_state=RNDM, \n    max_depth=17, \n    criterion='mse',\n    max_features=7, \n    n_jobs=-1,\n    n_estimators=200  \n)\n# rf.fit(X_train, y_train)\n%%time\nrf3 = RandomForestRegressor(\n    max_depth=20,\n    random_state=RNDM, \n)\n%%time\nrf4 = RandomForestRegressor(\n    random_state=RNDM, \n)\n%%time\nimport xgboost as xgb\n\nxg=xgb.XGBRegressor(\n                  random_state=RNDM,\n                  n_estimators=5, \n                  n_jobs=-1,\n                  subsample=0.5,\n                  colsample_bynode=0.5,\n                  num_parallel_tree=100,\n                  learning_rate=0.5,\n                  max_depth=3\n                  )\n\"\"\"\n%%time\nfrom sklearn.ensemble import BaggingRegressor\n\nbr = BaggingRegressor(\n                       base_estimator=rf, \n                       n_estimators=5, \n                       random_state=RNDM\n                     )\nbr.fit(X_train, y_train)\n\"\"\"\n\"\"\"\n%%time\nfrom sklearn.model_selection import GridSearchCV\n\nparams = {'n_estimators':[5, 10, 20, 50, 100, 200, 400, 1000], \n          'max_depth':[3, 5, 7, 10, 20, 40],\n          'min_samples_leaf': [1, 2, 5, 10, 20, 40, 100]\n         }\n\ngs = GridSearchCV(rf, params, \n                  scoring='r2', # \u043c\u0435\u0442\u0440\u0438\u043a\u0430 \n                  cv=KFold(n_splits=5,   # k (\u043a\u043e\u043b-\u0432\u043e \u0440\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0439\/\u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0439) \u0432 \u043a\u0440\u043e\u0441\u0441-\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u0438\n                           random_state=RNDM, \n                           shuffle=True),\n                  n_jobs=-1\n                  )\ngs.fit(X_train, y_train)\nres = pd.DataFrame(gs.cv_results_)\nres.head(2), gs.best_params_, gs.best_score_\n\"\"\"\n%%time\nfrom sklearn.ensemble import StackingRegressor\n\nstack = StackingRegressor([\n                           ('rf', rf),\n                           ('rf2', rf2),\n#                            ('rf3', rf3),\n                           ('rf4', rf4),\n                           ('gb', gb), \n                           ('xg', xg),\n                          ],\n                          cv=5,\n                          n_jobs=-1,\n                          final_estimator=GradientBoostingRegressor(\n                               \n                               max_depth=1,\n                               random_state=RNDM,  \n                               n_estimators=85,\n                               \n                          )\n                         )\n                             \nstack.fit(X_train, y_train)\n\"\"\"\n**\u041e\u0446\u0435\u043d\u043a\u0430 \u043c\u043e\u0434\u0435\u043b\u0438**\n\"\"\"\nfinal_model = stack\n%%time\ny_train_preds = final_model.predict(X_train)\ny_test_preds = final_model.predict(X_valid)\n\nevaluate_preds(y_train, y_train_preds, y_valid, y_test_preds)\n\"\"\"\n[](http:\/\/)**\u041a\u0440\u043e\u0441\u0441-\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044f**  (\u043e\u0442\u043a\u043b\u044e\u0447\u0438\u043b, \u043e\u043d\u0430 \u0435\u0441\u0442\u044c \u0432 \u0441\u0442\u0435\u043a\u0435 \u0443\u0436\u0435)\n\"\"\"\n\"\"\"\n%%time\n\u041a\u0440\u043e\u0441\u0441-\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044f (\u043e\u0442\u043a\u043b\u044e\u0447\u0438\u043b, \u043e\u043d\u0430 \u0435\u0441\u0442\u044c \u0432 \u0441\u0442\u0435\u043a\u0435 \u0443\u0436\u0435)\ncv_score = cross_val_score(final_model, X_train, y_train, scoring='r2', cv=KFold(n_splits=3, shuffle=True, random_state=RNDM))\ncv_score, cv_score.mean()\n\"\"\"\n\"\"\"\n### 8. \u041f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435  <a class='anchor' id='prediction'>\n\n1. \u0412\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u0434\u043b\u044f \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0433\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 \u0442\u0435 \u0436\u0435 \u044d\u0442\u0430\u043f\u044b \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u043d\u0438\u044f\u043d\u0438\u044f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\n2. \u041d\u0435 \u043f\u043e\u0442\u0435\u0440\u044f\u0442\u044c \u0438 \u043d\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u0448\u0430\u0442\u044c \u0438\u043d\u0434\u0435\u043a\u0441\u044b \u043e\u0442 \u043f\u0440\u0438\u043c\u0435\u0440\u043e\u0432 \u043f\u0440\u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0438 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u043e\u0432\n3. \u041f\u0440\u043e\u0433\u043d\u043e\u0437\u044b \u0434\u043e\u043b\u0436\u043d\u044b \u0431\u044b\u0442\u044c \u0434\u043b\u044f \u0432\u0441\u0435 \u043f\u0440\u0438\u043c\u0435\u0440\u043e\u0432 \u0438\u0437 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0433\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 (\u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0441\u0442\u0440\u043e\u043a)\n\"\"\"\ntest_df.shape, test_df\nsubmit = pd.read_csv('\/kaggle\/input\/real-estate-price-prediction-moscow\/sample_submission.csv')\nsubmit.head()\npredictions = final_model.predict(test_df)\npredictions\nsubmit['Price'] = predictions\nsubmit.head()\nsubmit.to_csv('rf_submit.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '01966ed4bf7dc1'}"}
{"id":"25608","text":"\"\"\"\n# Yenilenebilir Enerji Kaynaklar\u0131 T\u00fcketim Oran\u0131\n\"\"\"\n\"\"\"\nD\u00fcnya Kalk\u0131nma G\u00f6stergeleri (WDI), resmi olarak tan\u0131nan uluslararas\u0131 kaynaklardan derlenen, D\u00fcnya Bankas\u0131'n\u0131n temel kalk\u0131nma g\u00f6stergeleri koleksiyonudur. Mevcut en g\u00fcncel ve do\u011fru k\u00fcresel kalk\u0131nma verilerini sunar ve ulusal, b\u00f6lgesel ve k\u00fcresel tahminleri i\u00e7erir.\nBu \u00e7al\u0131\u015fmada ise WDI veri taban\u0131 i\u00e7erisindeki kategorilerden biri olan \u201cYenilenebilir Enerji Kaynaklar\u0131 T\u00fcketimi Oran\u0131\u201d  ile ilgili veri madencili\u011fi teknikleri kullan\u0131larak 1990 ve 2015 y\u0131llar\u0131 aras\u0131 i\u00e7in  analizler yap\u0131l\u0131p sonu\u00e7lar\u0131 veri madencili\u011fi k\u00fct\u00fcphanelerinden olan seaborn , mathplotlib-pyplot, numpy ve pandas kullan\u0131larak g\u00f6rselle\u015ftirildi.\nGelecek be\u015f y\u0131l sonras\u0131 , 2020 , i\u00e7in de veri madencili\u011fi modelleri kullan\u0131larak d\u00fcnya \u00fclkelerinin yenilenebilir enerji kaynaklar\u0131 t\u00fcketim oran\u0131 hakk\u0131nda tahminde bulunulmu\u015ftur.\n\n( Tahmin de\u011ferleri i\u00e7in be\u015f y\u0131l sonras\u0131n\u0131n se\u00e7ilme sebebi ise yenilenebilir enerji kaynaklar\u0131n\u0131 enerji \u00fcretip kullanabilmenin pahal\u0131 olmas\u0131ndan dolay\u0131 k\u0131sa s\u00fcre i\u00e7erisinde \u00e7ok b\u00fcy\u00fck de\u011fi\u015fiklikler g\u00f6zlemlenemiyor olmas\u0131d\u0131r. )\n\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport pandas as pd\ndata = pd.read_csv(\"..\/input\/yenilenebilirenerjikaynaklarituketimi.csv\")\nyenilenebilirenerjituketimi_metadata = pd.read_csv(\"..\/input\/yenilenebilirenerjituketimi_metadata.csv\")\ndata.head()\n# Satir Sayisi\nprint(\"Sat\u0131r Say\u0131s\u0131:\\n\",data.shape[0:])\n\n# Sutun Adlari\nprint(\"S\u00fctun Adlari:\\n\",data.columns.tolist())\n\n# Veri Tipleri\nprint(\"Veri Tipleri:\\n\",data.dtypes)\n\n\"\"\"\n**Eksik de\u011fer analizi, veri seti i\u00e7erisindeki gerek g\u00f6zlem gerekse kay\u0131t s\u0131ras\u0131nda ortaya \u00e7\u0131kan sorunlar nedeniyle eksik kalan verilerin ortaya \u00e7\u0131kartt\u0131\u011f\u0131 sorunlar\u0131 \u00e7\u00f6zmeye \u00e7al\u0131\u015f\u0131r.\n Makine \u00f6\u011frenmesi modellerinin verisetine uygulanabilmesi i\u00e7in verisetindeki eksik alanlar\u0131n belirli metodlara g\u00f6re i\u015flenmesi gereklidir.**\n\"\"\"\n# Eksik veri say\u0131lar\u0131 ve veri setindeki oranlar\u0131 \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.figure(figsize=(8,8))\nsns.heatmap(pd.isnull(data.T), cbar=False)\n\npd.concat([data.isnull().sum(), 100 * data.isnull().sum()\/len(data)], \n              axis=1).rename(columns={0:'Missing Records', 1:'Percentage (%)'})\n\"\"\"\n**Makine \u00f6\u011frenmesi algoritmalar\u0131 do\u011frudan kategorik veriler \u00fczerinde \u00e7al\u0131\u015fmamaktad\u0131r. Bu nedenle veriler s\u00fcrekli de\u011fi\u015fkenlere d\u00f6n\u00fc\u015ft\u00fcr\u00fclmelidir.\nBu \u00e7al\u0131\u015fmadaki veriler numeric de\u011ferlere d\u00f6n\u00fc\u015ft\u00fcr\u00fclm\u00fc\u015ft\u00fcr.**\n\"\"\"\n# 1998 y\u0131l\u0131 haricindekiler kategorik de\u011fi\u015fkenden s\u00fcrekli de\u011fi\u015fkene d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc.\ndt=['YRbir','YRiki','YRuc','YRdort','YRbes','YRalti','YRyedi','YRdokuz','YRon','YRonbir','YRoniki','YRonuc','YRondort','YRonbes','YRonalti','YRonyedi','YRonsekiz','YRondokuz','YRyirmi','YRyirmibir','YRyirmiiki','YRyirmiuc','YRyirmidort', 'YRyirmibes','YRyirmialti' ]\nfor i in  dt:\n  data[i] = pd.to_numeric(data[i], errors = 'coerce')\ndata.info()\ndata['YRbir']\n\"\"\"\n** T\u00fcrkiye i\u00e7in datasetteki t\u00fcm y\u0131llar\u0131n korelasyon matrisi olu\u015fturulup bir bar plot ile g\u00f6rselle\u015ftirildi.\nBar plot T\u00fcrkiye i\u00e7in y\u0131llar(\u00f6zellikler) aras\u0131 ili\u015fkiyi g\u00f6stermektedir.**\n\n**Y\u0131llar birbiri ile ba\u011f\u0131ml\u0131 \u00f6zellikler olmad\u0131\u011f\u0131 i\u00e7in de korelasyon de\u011ferlerinin d\u00fc\u015f\u00fck oldu\u011funu g\u00f6zlemleyebiliyoruz.**\n\"\"\"\ndata_a=data.copy()\ny = (data_a['Country Name'] == 'Turkey').astype(int)\nfields = list(data_a.columns[:-1])  # everything except \"country name\"\ncorrelations = data_a[fields].corrwith(y)\ncorrelations.sort_values(inplace=True)\ncorrelations\n\nax = correlations.plot(kind='bar')\nax.set(ylim=[-1, 1], ylabel='turkey correlation');\n\"\"\"\n**Eksik veri analizi yap\u0131ld\u0131ktan sonra ya bo\u015f alanlar silinir ya da tamamlan\u0131r. Yap\u0131lan her i\u015flem t\u00fcm veri setini etkiledi\u011fi i\u00e7in uygun olan y\u00f6ntem tercih edilmelidir.\n\u00d6ncelikli olarak eksik de\u011ferler tamamlanabiliyorsa tamamlanmal\u0131d\u0131r.**\n\n**Bu \u00e7al\u0131\u015fma i\u00e7in y\u00f6ntem olarak Mean Substitution (yerine ortalamay\u0131 koyma) se\u00e7ilmi\u015ftir.\nVerisetindeki de\u011ferler aras\u0131nda \u00e7ok b\u00fcy\u00fck farklar olmad\u0131\u011f\u0131 i\u00e7in eksik alanlar s\u00fctun baz\u0131nda ortalama de\u011fer ile doldurulmu\u015ftur.**\n\n\n(ya bir atama yap\u0131yoruz , ya da inplace kullan\u0131yoruz)\n\"\"\"\n# S\u00fcrekli de\u011fi\u015fken s\u00fctunlar\u0131ndaki bo\u015f alanlar ortalama de\u011ferler ile dolduruldu.\ncols = ['YRbir','YRiki','YRuc','YRdort','YRbes','YRalti','YRyedi' ,'YRdokuz','YRon','YRonbir','YRoniki','YRonuc','YRondort','YRonbes','YRonalti','YRonyedi','YRonsekiz','YRondokuz','YRyirmi','YRyirmibir','YRyirmiiki','YRyirmiuc','YRyirmidort', 'YRyirmibes','YRyirmialti']\nfor i in cols:\n   data[i].fillna(data[i].mean(),inplace=True)\n#Yaln\u0131zca kategorik de\u011fi\u015fkenlerde ve YRsekizde bo\u015f alanlar kalm\u0131\u015ft\u0131r. \nfor i in data:\n  df=data[i].isnull().values.sum()\n  print(df)\n\"\"\"\n**Bu \u00e7al\u0131\u015fma ile d\u00fcnya \u00fclkelerinin 1990 ,1995, 2000, 2005, 2010, 2015 y\u0131llar\u0131ndaki yenilenebilir enerji kaynaklar\u0131 t\u00fcketim oranlar\u0131na bak\u0131larak 2020 y\u0131l\u0131 i\u00e7in tahmin de\u011ferlerini bulunabilmesi hedeflenmi\u015ftir.**\n\"\"\"\n\"\"\"\n**  Veriseti i\u00e7erisinden \u00e7al\u0131\u015fma i\u00e7in kullan\u0131lacak de\u011ferler se\u00e7ilip yeni bir veriseti olu\u015fturulmu\u015ftur.**\n\"\"\"\n# Se\u00e7ilmi\u015f olan y\u0131llarla yeni bir dataframe olu\u015fturuldu.\ndf1=pd.Series(data['Country Name'],name=\"CountryName\")\ndf2=pd.Series(data['YRbir'],name=\"YRbir\")\ndf3=pd.Series(data['YRalti'],name=\"YRalti\")\ndf4=pd.Series(data['YRonbir'],name=\"YRonbir\")\ndf5=pd.Series(data['YRonalti'],name=\"YRonalti\")\ndf6=pd.Series(data['YRyirmibir'],name=\"YRyirmibir\")\ndf7=pd.Series(data['YRyirmialti'],name=\"YRyirmialti\")\ndf=pd.concat([df1, df2,df3, df4,df5, df6,df7], axis=1)\n\"\"\"\n**Y\u0131llar\u0131n yenilenebilir enerji kaynaklar\u0131 t\u00fcketim oranlar\u0131n\u0131n ortalamalar\u0131na bak\u0131ld\u0131\u011f\u0131nda genel olarak bir azalma g\u00f6zlemlenmi\u015ftir.Bunun sebepleri aras\u0131nda ;**\n\n\n**  yenilenebilir enerji kaynaklar\u0131n\u0131n kullan\u0131labilir hale getirilmesindeki ekonomik yetersizlikler,\n  nuf\u00fcs art\u0131\u015f\u0131n\u0131n ve gelir art\u0131\u015f\u0131n\u0131n do\u011fru orant\u0131l\u0131 artmamas\u0131 ,\n  yeterli kaynak bulunanamamas\u0131 **\n\n**yer al\u0131r.**\n\n\"\"\"\ndf.describe().T\n\"\"\"\n**\nYRbir(1990),\nYRalti(1995),\nYRonbir(2000),\nYRonalti(2005),\nYRyirmibir(2010),\nYRyirmialti(2015)\nifade etmektedir.**\n\"\"\"\n\"\"\"\n**Verisetine ait her bir s\u00fctun i\u00e7in histogram grafikleri ve ayk\u0131r\u0131 de\u011ferleri g\u00f6zlemleyebilmek ad\u0131na box plotlar olu\u015fturuldu. \nBu boxplotlar\u0131 ve histogram grafiklerini inceledi\u011fimizde **\n\n    1990 ve 1995 y\u0131llar\u0131 de\u011ferlerinin ,\n    2000 ve 2005 y\u0131llar\u0131 de\u011ferlerinin ,\n    2005 ve 2010 y\u0131llar\u0131 de\u011ferlerinin ,\n    \n**birbirleri ile benzerlik g\u00f6sterdi\u011fi g\u00f6r\u00fclmektedir.\nBunu ayn\u0131 zamanda verisetinden describe metodu ile olu\u015fturdu\u011fumuz tablodaki ortalama (mean) de\u011ferler ile de    g\u00f6rebiliriz.**\n\n\"\"\"\n# Ayk\u0131r\u0131 de\u011ferleri g\u00f6zlemleyebilmek i\u00e7in box plot kullan\u0131ld\u0131\nplt.figure()\ndf.boxplot(column=['YRbir','YRalti','YRonbir','YRonalti','YRyirmibir','YRyirmialti'])\n\nfig,axs=plt.subplots(2,3) \naxs[0, 0].boxplot(df['YRbir'])\naxs[0, 0].set_title('YRbir')\n\naxs[0, 1].boxplot(df['YRalti'])\naxs[0, 1].set_title('YRalti')\n\naxs[0, 2].boxplot(df['YRonbir'])\naxs[0, 2].set_title('YRonbir')\n\naxs[1, 0].boxplot(df['YRonalti'])\naxs[1, 0].set_title('YRonalti')\n\naxs[1, 1].boxplot(df['YRyirmibir'])\naxs[1, 1].set_title('YRyirmibir')\n\naxs[1, 2].boxplot(df['YRyirmialti'])\naxs[1, 2].set_title('YRyirmialti')\n# Histogram grafi\u011fi\nfrom matplotlib import pyplot\ndf.hist()\npyplot.show()\n# Scatter Plot Matrix\nfrom pandas.plotting import scatter_matrix\nscatter_matrix(df)\npyplot.show()\n\n\"\"\"\n**Verisetinden tahmin de\u011ferleri olu\u015fturabilmek i\u00e7in \u00f6ncelikli olarak veriseti e\u011fitim ve test verisi olarak ayr\u0131ld\u0131.**\n\n**Bu oran ;\ntest verisi (0.25)\ne\u011fitim verisi (0.75) \u015feklindedir.\nTest boyutunu art\u0131rd\u0131k\u00e7a tahmin de\u011ferleri i\u00e7in ba\u015far\u0131 \u00f6l\u00e7\u00fcm metriklerinde d\u00fc\u015f\u00fc\u015f g\u00f6zlemlendi.**\n\n**Tahmin de\u011ferleri i\u00e7in de baz\u0131 modeller belirlendi.**\n\n**Veriler \u00fczerinde normalizasyon ve standartla\u015ft\u0131rma i\u015flemleri de denendi ancak ba\u015far\u0131 sonu\u00e7lar\u0131nda bir etki g\u00f6stermedi.Bu i\u015flemler denenirken kullna\u0131lan iki metot MinMaxScaler() ve StandartScaler() metotlar\u0131yd\u0131.**\n\"\"\"\nimport numpy as np\nfrom sklearn    import metrics, svm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn import  linear_model\narray = df.values\nX = array[:,1:6]\ny = array[:,6]\nX_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.25, random_state=1, shuffle=True)\nprint(\"Dataframe boyutu: \",df.shape)\nprint(\"E\u011fitim verisi boyutu: \",X_train.shape, Y_train.shape)\nprint(\"Test verisi boyutu: \",X_validation.shape, Y_validation.shape)\n\n# type error i\u00e7in target types\u0131 \"Label Encoder\" ile  multiclassa \u00e7evirdim.(Target=Y_train)\nfrom sklearn import preprocessing\nfrom sklearn import utils\n\nlab_enc = preprocessing.LabelEncoder()\nencoded = lab_enc.fit_transform(y)\nprint(utils.multiclass.type_of_target(y))\nprint(utils.multiclass.type_of_target(Y_train.astype('int')))\nprint(utils.multiclass.type_of_target(encoded))\n\nlab_enc = preprocessing.LabelEncoder()\nY_train = lab_enc.fit_transform(Y_train)\nprint(utils.multiclass.type_of_target(Y_train))\n\"\"\"\n**Verisetinin niteli\u011fine g\u00f6re modellerin ne kadar iyi \u00e7al\u0131\u015ft\u0131\u011f\u0131n\u0131 g\u00f6rebilmek i\u00e7in cross validation ile accuracy(do\u011fruluk de\u011feri) de\u011ferleri bulundu.**\n\"\"\"\n# Modeller\nmodels = []\nmodels.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC(gamma='auto')))\n# modellerin s\u0131ras\u0131yla de\u011ferlendirilmeleri\nresults = []\nnames = []\nfor name, model in models:\n\tkfold = StratifiedKFold(n_splits=10, random_state=1)\n\tcv_results = cross_val_score(model, X, encoded, cv=kfold, scoring='accuracy')\n\tresults.append(cv_results)\n\tnames.append(name)\n\tprint('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))\n# Algoritmalr\u0131n boxplot \u00fczerinde kar\u015f\u0131la\u015ft\u0131r\u0131l\u0131p ayk\u0131r\u0131 de\u011fer tespiti yap\u0131lmas\u0131\npyplot.boxplot(results, labels=names)\npyplot.title('Algorithm Comparison')\npyplot.show()\n\"\"\"\n**Modellerin do\u011fruluk de\u011ferlerinin olduk\u00e7a d\u00fc\u015f\u00fck oldu\u011funu g\u00f6zlemliyoruz. Bu \u00fclke say\u0131s\u0131n\u0131n ya da y\u0131llar\u0131n \u00e7oklu\u011fundan kaynaklan\u0131yor olabilir. Bir tek do\u011fruluk de\u011ferlerine bakarak ideal modele karar vermek bu veriseti i\u00e7in zor olaca\u011f\u0131ndan \nkar\u0131\u015f\u0131kl\u0131k matrisi ve s\u0131n\u0131fland\u0131rma raporlamas\u0131na da bakmak da fayda vard\u0131r.**\n\n**< En y\u00fcksek do\u011fruluk de\u011feri  CART ve SVM'indir. >**\n\"\"\"\n# Her bir modelin do\u011fruluk de\u011feri ,s\u0131n\u0131fland\u0131rma raporu , kar\u0131\u015f\u0131kl\u0131k matrisi ve MSE(Ortalama Kare Hata Regresyon Oran\u0131) de\u011ferlerini hesaplamak i\u00e7in import edildi.\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import mean_squared_error\n\"\"\"\n* **Se\u00e7ilmi\u015f olan t\u00fcm modeller i\u00e7erisinde de\u011ferlendirme \u00f6l\u00e7\u00fct\u00fc olarak confusion matrix (kar\u0131\u015f\u0131kl\u0131k matrisi) , classification report(s\u0131n\u0131fland\u0131rma raporlar\u0131) ve MSE kullan\u0131ld\u0131.**\n \n \n* ** F1 Score precision ve recall un ortalamas\u0131 denebilir. Se\u00e7ilmi\u015f olan modeller i\u00e7in g\u00f6zlemlenen macro ve weighted ortalamalar\u0131n\u0131n f1 scorlar\u0131 da olduk\u00e7a d\u00fc\u015f\u00fck(F1 score i\u00e7i iyi durum 1 , k\u00f6t\u00fc durum 0 olmas\u0131d\u0131r.) .**\n \n* **Verisetindeki de\u011ferler s\u00fcrekli olduklar\u0131 i\u00e7in tahmin sonu\u00e7lar\u0131na g\u00f6re regresyon modellerinde s\u0131n\u0131fland\u0131rma modellerinden daha ba\u015far\u0131l\u0131 sonu\u00e7lar al\u0131nm\u0131\u015ft\u0131r.**\n \n* **Ayn\u0131 zamanda \u00e7o\u011fu model i\u00e7in de (kendi i\u00e7erisinde) tahmin de\u011ferlerinin birbirine fazlas\u0131yla yak\u0131nl\u0131k g\u00f6sterdi\u011fini g\u00f6zlemleyebiliyoruz.\u00d6zellikle her bir model i\u00e7in g\u00f6rselle\u015ftirilmi\u015f olan heatmap lerde bu a\u00e7\u0131k\u00e7a g\u00f6r\u00fclmektedir.**\n \n* **T\u00fcm modeller aras\u0131nda en ba\u015far\u0131l\u0131 sonucu  lineer regresyon vermi\u015ftir .Yine de sonu\u00e7lar k\u0131yasland\u0131\u011f\u0131nda ger\u00e7e\u011fe uzak varsay\u0131ld\u0131\u011f\u0131 i\u00e7in de\u011ferlerin yorumlanmas\u0131yla do\u011fru yarg\u0131lar elde edilemez. **\n\"\"\"\n# Lineer Regresyon\nprint(\"\\nLineer Regresyon\")\nlm = linear_model.LinearRegression()\nmodel = lm.fit(X_train, Y_train)\ny_true1 , y_pred1 =Y_validation,lm.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred1)\nplt.scatter(y_true1, y_pred1,c='orange')\nplt.scatter(y_true1, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n#Lineer Regresyon\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v = lab_enc.fit_transform(y_true1)\nutils.multiclass.type_of_target(y_true1.astype('int'))\nypred1= lab_enc.fit_transform(y_pred1)\nutils.multiclass.type_of_target(ypred1.astype('int'))\nconf=confusion_matrix(encoded_v, ypred1)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n#Lineer Regresyon\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v, ypred1))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v, ypred1))\nprint(\"MSE:\",mean_squared_error(encoded_v, ypred1))\n# SVR(Support Vector Regressions)\nprint(\"SVR(Support Vector Regressions)\")\nclf = svm.SVR(gamma=\"auto\")\n# modelimizi e\u011fitim verilerimiz ve buna kar\u015f\u0131l\u0131k gelen Y_train(target ) de\u011ferleri ile e\u011fittik\nclf.fit(X_train, Y_train)\n# test de\u011ferlerimize kar\u015f\u0131l\u0131k gelecek olan tahmin de\u011ferlerimizi olu\u015fturduk\ny_true2 , y_pred2 =Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred2)\nplt.scatter(y_true2, y_pred2,c='black')\nplt.scatter(y_true2, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n\n#SVR\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v1 = lab_enc.fit_transform(y_true2)\nutils.multiclass.type_of_target(y_true2.astype('int'))\nypred2= lab_enc.fit_transform(y_pred2)\nutils.multiclass.type_of_target(ypred2.astype('int'))\nconf=confusion_matrix(encoded_v1, ypred2)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v1, ypred2))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v1, ypred2))\nprint(\"MSE:\",mean_squared_error(encoded_v1, ypred2))\n# SVC\nprint(\"SVC\")\nclf = SVC(gamma=\"auto\")\nclf.fit(X_train, Y_train)\ny_true3 , y_pred3 =Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred3)\nplt.scatter(y_true3, y_pred3,c='yellow')\nplt.scatter(y_true3, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n#SVC\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v2 = lab_enc.fit_transform(y_true3)\nutils.multiclass.type_of_target(y_true3.astype('int'))\nypred3= lab_enc.fit_transform(y_pred3)\nutils.multiclass.type_of_target(ypred3.astype('int'))\nconf=confusion_matrix(encoded_v2, ypred3)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v2, ypred3))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v2, ypred3))\nprint(\"MSE:\",mean_squared_error(encoded_v2, ypred3))\n\"\"\"\n**Naive Bayes  bir olas\u0131l\u0131ksal yakla\u015f\u0131m modelidir. Bu model data tipine g\u00f6re farkl\u0131 bi\u00e7imlerde uygulan\u0131r. Bu versetindeki veriler s\u00fcrekli veriler oldu\u011fu i\u00e7in Gaussian se\u00e7ilmi\u015ftir.**\n\"\"\"\n# GaussianNB\nprint(\"GaussianNB\")\nclf = GaussianNB()\nclf.fit(X_train, Y_train)\ny_true4 , y_pred4=Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred4)\nplt.scatter(y_true4, y_pred4,c='grey')\nplt.scatter(y_true4, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n\n# GaussianNB\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v3 = lab_enc.fit_transform(y_true4)\nutils.multiclass.type_of_target(y_true4.astype('int'))\nypred4= lab_enc.fit_transform(y_pred4)\nutils.multiclass.type_of_target(ypred4.astype('int'))\nconf=confusion_matrix(encoded_v3, ypred4)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v3, ypred4))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v3, ypred4))\nprint(\"MSE:\",mean_squared_error(encoded_v3, ypred4))\n# Decision Tree Classifier\nprint(\"Decision Tree Classifier\")\nclf = DecisionTreeClassifier()\nclf.fit(X_train, Y_train)\ny_true5 , y_pred5=Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred5)\nplt.scatter(y_true5, y_pred5,c='brown')\nplt.scatter(y_true5, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n\"\"\"\n**Karar a\u011fa\u00e7lar\u0131 genellikle kategorik veriler i\u00e7in uygundur. Bu verisetinde s\u00fcrekli veriler \u00fczerinden tahmin y\u00fcr\u00fct\u00fcld\u00fc\u011f\u00fc i\u00e7in bu model ba\u015far\u0131l\u0131 sonu\u00e7 vermemi\u015ftir.**\n\"\"\"\n# Decision Tree Classifier\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v4 = lab_enc.fit_transform(y_true5)\nutils.multiclass.type_of_target(y_true5.astype('int'))\nypred5= lab_enc.fit_transform(y_pred5)\nutils.multiclass.type_of_target(ypred5.astype('int'))\nconf=confusion_matrix(encoded_v4, ypred5)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v4, ypred5))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v4, ypred5))\nprint(\"MSE:\",mean_squared_error(encoded_v4, ypred5))\n# Logistic Regresyon\nfrom sklearn.linear_model import LogisticRegression\nprint(\"Logistic Regression\")\nclf = LogisticRegression(multi_class=\"auto\")\nclf.fit(X_train, Y_train)\ny_true6 , y_pred6=Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred6)\nplt.scatter(y_true6, y_pred6,c='purple')\nplt.scatter(y_true6, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n\n# Logistic Regresyon\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v5 = lab_enc.fit_transform(y_true6)\nutils.multiclass.type_of_target(y_true6.astype('int'))\nypred6= lab_enc.fit_transform(y_pred6)\nutils.multiclass.type_of_target(ypred6.astype('int'))\nconf=confusion_matrix(encoded_v5, ypred6)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v5, ypred6))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v5, ypred6))\nprint(\"MSE:\",mean_squared_error(encoded_v5, ypred6))\n# KNeighborsClassifier\nprint(\"KNeighbors Classifier\")\nclf = KNeighborsClassifier()\nclf.fit(X_train, Y_train)\ny_true7 , y_pred7=Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred7)\nplt.scatter(y_true7, y_pred7,c='blue')\nplt.scatter(y_true7, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n# KNeighborsClassifier\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v6 = lab_enc.fit_transform(y_true7)\nutils.multiclass.type_of_target(y_true7.astype('int'))\nypred7= lab_enc.fit_transform(y_pred7)\nutils.multiclass.type_of_target(ypred7.astype('int'))\nconf=confusion_matrix(encoded_v6, ypred7)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v6, ypred7))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v6, ypred7))\nprint(\"MSE:\",mean_squared_error(encoded_v6, ypred7))\n# Linear Discriminant Analysis\nprint(\"Linear Discriminant Analysis\")\nclf = LinearDiscriminantAnalysis()\nclf.fit(X_train, Y_train)\ny_true8 , y_pred8=Y_validation,clf.predict(X_validation)\nprint(\"\\nTahmin de\u011ferleri: \",y_pred8)\nplt.scatter(y_true8, y_pred8,c='red')\nplt.scatter(y_true8, Y_validation,c='green')\nplt.xlabel(\"True Values\")\nplt.ylabel(\"Predictions\")\n\n\n# Linear Discriminant Analysis\n#predictions multiclass oldu\u011fundan y_validation da multiclassa d\u00f6n\u00fc\u015ft\u00fcr\u00fcld\u00fc\nencoded_v7 = lab_enc.fit_transform(y_true8)\nutils.multiclass.type_of_target(y_true8.astype('int'))\nypred8= lab_enc.fit_transform(y_pred8)\nutils.multiclass.type_of_target(ypred8.astype('int'))\nconf=confusion_matrix(encoded_v7, ypred8)\nprint(\"\\nConfusion matrix :\\n\",conf)\nsns.heatmap(conf, cmap=\"Blues\")\n\n\nprint(\"Accuracy score(Do\u011fruluk de\u011feri):\\n\",accuracy_score(encoded_v7, ypred8))\nprint(\"\\nClassification Report:\\n\",classification_report(encoded_v7, ypred8))\nprint(\"MSE:\",mean_squared_error(encoded_v7, ypred8))","meta":"{'source': 'AI4Code', 'id': '2f259772fb9517'}"}
{"id":"120106","text":"# 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\n\"\"\"\nWe'll use the BMW dataset.\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.svm import SVR\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\ndata = pd.read_csv('\/kaggle\/input\/used-car-dataset-ford-and-mercedes\/bmw.csv')\ndata.head()\ndata.isnull().sum()\n\"\"\"\nWe don't have any null values which is a good sign.\n\"\"\"\ndata.describe()\n\"\"\"\nLet's check the percentage of different car models in the dataset.\n\"\"\"\n(data['model'].value_counts()\/len(data))*100\nplt.figure(figsize=(24,5))\nplt.xticks(rotation = 20)\nsns.barplot(x = data['model'], y = data['price'], data = data, hue = data['transmission'])\ntransmission_counts = dict(data['transmission'].value_counts())\nplt.title('Transmission Distribution', size = 20)\nplt.pie(transmission_counts.values(), labels=transmission_counts.keys(), textprops={'size' : 14}, autopct='%1.2f%%')\nplt.show()\nplt.figure(figsize = (15,5))\nsns.barplot(x = data['year'], y = data['price'])\nplt.figure(figsize=(15,5))\nsns.scatterplot(x = data['mileage'], y = data['price'], hue = data['year'])\nsns.countplot(x = data['fuelType'])\nplt.hist(data['engineSize'], bins=5, color='brown')\nplt.show()\nsns.pairplot(data = data)\ncorr = data.corr()\ncorr_dataFrame = corr['price'].sort_values(ascending=False).to_frame()\ns = corr_dataFrame.style.background_gradient(cmap = 'coolwarm')\ns\n\"\"\"\n# Handling Outliers\n\"\"\"\ndata['car_age'] = 2021 - data['year']\ndata = data.drop(columns = ['year'])\n\nnumerical_variables = [var for var in data.columns if data[var].dtype != 'O']\nprint('There are {} numerical variables'.format(len(numerical_variables)))\nprint('The numerical variables are: ', numerical_variables)\n\nplt.figure(figsize=(12,8))\nplt.title('Numerical Variables in BMW Dataset')\ndata[numerical_variables].boxplot(color = 'brown')\nplt.show()\ndata[data['price'] >= 90000]\ndata[data['mileage'] >= 200000]\ni1 = data[data.mileage >= 200000].index\ni2 = data[data.price >= 90000].index\ndata = data.drop(i1)\ndata = data.drop(i2)\n\"\"\"\nNow using One Hot Encoding on categorical data.\nI am using pd.get_dummies for the same.\n\"\"\"\ndata_expanded = pd.get_dummies(data)\ndata_expanded.head()\nstd = StandardScaler()\ndata_expanded_std = std.fit_transform(data_expanded)\ndata_expanded_std = pd.DataFrame(data_expanded_std, columns = data_expanded.columns)\nprint(data_expanded.shape)\ndata_expanded_std.head()\nx_train, x_test, y_train, y_test = train_test_split(data_expanded_std.drop(columns = ['price']), data_expanded_std[['price']])\nx_train.shape, x_test.shape, y_train.shape, y_test.shape\ndef test_models(models, x_train, x_test, y_train, y_test):\n\n    np.random.seed(42)\n\n    model_mse = {}\n    model_mape = {}    \n    model_r2 = {}\n\n    for name, model in models.items():\n        model.fit(x_train, y_train.values.ravel())\n        y_preds = model.predict(x_test)\n        model_mse[name] = mean_squared_error(y_test, y_preds)\n        model_mape[name] = np.mean(np.abs((np.array(y_test)-np.array(y_preds))\/np.array(y_test)))*100\n        model_r2[name] = r2_score(y_test, y_preds)\n\n    model_mse = pd.DataFrame(model_mse, index = ['MSE']).transpose()\n    model_mse = model_mse.sort_values('MSE', ascending=False)\n\n    model_mape = pd.DataFrame(model_mape, index = ['MAPE']).transpose()\n    model_mape = model_mape.sort_values('MAPE', ascending=False)\n\n    model_r2= pd.DataFrame(model_r2, index = ['R2']).transpose()\n    model_r2 = model_r2.sort_values('R2')\n\n    return model_mse, model_mape, model_r2\nmodels = {'LinearRegression' : LinearRegression(),\n          'KNeighborsRegressor': KNeighborsRegressor(),\n          'DecisionTreeRegressor': DecisionTreeRegressor(),\n          'RandomForestRegressor':RandomForestRegressor(),\n          'GradientBoostingRegressor': GradientBoostingRegressor(),\n          'SVM': SVR()\n        }\nmodel_mse,model_mape,model_r2 = test_models(models, x_train, x_test, y_train, y_test)\nmodel_mse\nmodel_mape\nmodel_r2\n\"\"\"\n# Using Neural Network\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nmodel = Sequential()\n\nmodel.add(Dense(37, activation = 'relu'))\nmodel.add(Dense(24, activation = 'relu'))\nmodel.add(Dense(8, activation = 'relu'))\nmodel.add(Dense(1))\n\nmodel.compile(\n    optimizer = 'adam',\n    loss = tf.keras.losses.MSE\n)\nhistory = model.fit(x = x_train, y =  y_train, epochs = 200)\ny_preds = model.predict(x_test)\ny_preds = pd.DataFrame(y_preds)\nr2_nn_result = r2_score(y_test, y_preds)\nr2_nn_result\n\"\"\"\n# Conclusion\nRandomForestRegressor and Neural Nwtwork gave the best results on the Dataset with an R2 score of nearly 95%.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dce492a6a6e028'}"}
{"id":"89065","text":"# 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\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.svm import SVC\niris=pd.read_csv(\"\/kaggle\/input\/iris\/Iris.csv\")\niris.head()\niris.tail()\niris.describe()\niris.info()\niris.isnull().sum()\n\"\"\"\nThere are no null values in the dataset.\n\n\"\"\"\niris['Species'].unique()\n\"\"\"\nThere are three categories of Iris flower.\n\"\"\"\niris['Species'].value_counts()\nimport matplotlib.pyplot as plt\nplt.hist(iris['Species'],bins=10, color='purple')\nimport seaborn as sns\nsns.swarmplot(x=iris['Species'],y=iris['SepalWidthCm'], data=iris)\nsns.swarmplot(x=iris['Species'],y=iris['PetalLengthCm'], data=iris)\nplt.bar(x=iris['Species'],height=iris['SepalLengthCm'], color='green')\nplt.show()\nsns.boxplot(x='Species',y='SepalLengthCm',data=iris);\nencoder=LabelEncoder()\niris['Species']=encoder.fit_transform(iris['Species'])\niris['Species']\niris.drop('Id', axis=1, inplace=True)\nX=iris.drop('Species',axis=1)\ny=iris['Species']\ny=iris['Species']\nX_train,X_test, y_train,y_test= train_test_split(X,y, test_size=0.25, random_state=1)\nX_train.head()\n# Feature Scaling\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.fit_transform(X_test)\nX_train.shape,X_test.shape,y_train.shape,y_test.shape\nmodel = SVC(kernel='linear')\nmodel.fit(X_train,y_train)\n\ny_pred_train=model.predict(X_train)\ny_pred_test=model.predict(X_test)\n\n\nprint(\"Confusion Matrix of test data: \")\nprint(confusion_matrix(y_pred_test,y_test))\n\nprint(\"Classification Report of test data: \") \nprint(classification_report(y_pred_test, y_test))\n\nprint(\"Accuracy score of train data using SVC:\" , accuracy_score(y_pred_train,y_train))\nprint(\"Accuracy score of test data using SVC: \" , accuracy_score(y_pred_test, y_test))\nmodel=LogisticRegression()\nmodel.fit(X_train,y_train)\n\ny_pred_train=model.predict(X_train)\ny_pred_test=model.predict(X_test)\n\ntrain_accuracy=np.round(accuracy_score(y_pred_train,y_train),2)\ntest_accuracy=np.round(accuracy_score(y_pred_test,y_test),2)\n\nprint(\"Accuracy score on train data using Logistic Regression is: \" , train_accuracy)\nprint(\"Accuracy score on test data using Logistic Regression is: \" , test_accuracy)\n\nprint(\"Confusion Matrix of test data: \")\nprint(confusion_matrix(y_pred_test,y_test))\n\nprint(\"Classification Report of test data: \") \nprint(classification_report(y_pred_test, y_test))\n\nprint(\"Accuracy score on train data using Logistic Regression is: \" , train_accuracy)\nprint(\"Confusion Matrix of train data: \")\nprint(confusion_matrix(y_pred_train,y_train))\n\nprint(\"Classification Report of train data: \") \nprint(classification_report(y_pred_train, y_train))\n\nprint(\"Accuracy score on test data using Logistic Regression is: \" , test_accuracy)","meta":"{'source': 'AI4Code', 'id': 'a3520e4e5b0d2f'}"}
{"id":"48419","text":"# 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\ndfguapo = pd.read_csv(r\"\/kaggle\/input\/the-human-freedom-index\/hfi_cc_2020.csv\")\n\"\"\"\n# Obt\u00e9n una lista con los atributos cuantitativos y otra lista con los atributos cualitativos.\n\"\"\"\nvariablescuali = list()\nvariablescuanti = list()\nfor x,i in zip(dfguapo.columns,dfguapo.dtypes):\n    if i == np.int64:\n        variablescuanti.append(x)\n    elif i == np.float64:\n        variablescuanti.append(x)\n    else:\n        variablescuali.append(x)\n\"\"\"\n# Define el rango de cada uno de los atributos (cuantitativos).\n\"\"\"\nfor j in variablescuanti:\n    print(str(j)+\": \"+str(np.max(dfguapo[j])-np.min(dfguapo[j])))\n\"\"\"\n# Obt\u00e9n la moda o promedio dependiendo el caso para cada atributo.\n\"\"\"\nimport sympy\nimport numpy as np\nimport scipy\nfrom scipy import stats \nfor i,x in dfguapo.iteritems():\n    if i in variablescuanti:\n        print(str(i)+\": \"+str(np.mean(x)))\n    elif i in variablescuali:\n        print(str(i)+\": \"+(str(stats.mode(x)[0][0])))\n\"\"\"\n# Obt\u00e9n el rango, varianza, desviaci\u00f3n estandar para los atributos cuantitativos.\n\"\"\"\nfor j in variablescuanti:\n    print(str(j)+\": \"+str(np.max(dfguapo[j])-np.min(dfguapo[j]))+\", \"+str(np.var(dfguapo[j]))+\", \"+str(np.std(dfguapo[j])))","meta":"{'source': 'AI4Code', 'id': '592228fd85b97b'}"}
{"id":"17861","text":"#some of the codelines are copied from https:\/\/www.kaggle.com\/wspinkaggle\/seti-basic-tensorflow-efficientnet\n\"\"\"\n# Import the required libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport math\nimport os\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport pathlib\nfrom tensorflow.keras.applications import EfficientNetB2\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n# Set the path for input data\n\"\"\"\ndata_dir = Path('..\/input\/seti-breakthrough-listen\/')\ntrain_data_dir = data_dir \/ 'train'\ntest_data_dir = data_dir \/ 'test'\n\ntrain_label_file = data_dir \/ 'train_labels.csv'\nsample_file = data_dir \/ 'sample_submission.csv'\ndf_labels = pd.read_csv(train_label_file, index_col='id')\ndf_labels.head()\n\"\"\"\n# Visualise the input data\n\"\"\"\n\"\"\"\n### Datapoint where target is 0\n\"\"\"\ndf_labels.query(\"target == 0\").sample(3)\nd_point = np.load('..\/input\/seti-breakthrough-listen\/train\/6\/6759b44dd672.npy')\nd_point = d_point.astype('float')\n\nplt.figure(figsize=(16,10))\nfor i in range(6):\n    plt.subplot(6, 1, i + 1)\n    if i == 0:\n        plt.title('File name: 6759b44dd672  | Target: 0', fontsize=18)\n    plt.imshow(d_point[i].astype(float), interpolation='nearest', aspect='auto')\n    plt.text(5, 100, [\"ON\", \"OFF\"][i % 2], bbox={'facecolor': 'white'})\n    plt.xticks([])\nplt.show()\nd_point = np.load('..\/input\/seti-breakthrough-listen\/train\/e\/ee3e7543040a.npy')\nd_point = d_point.astype('float')\n\nplt.figure(figsize=(16,10))\nfor i in range(6):\n    plt.subplot(6, 1, i + 1)\n    if i == 0:\n        plt.title('File name: ee3e7543040a  | Target: 0', fontsize=18)\n    plt.imshow(d_point[i].astype(float), interpolation='nearest', aspect='auto')\n    plt.text(5, 100, [\"ON\", \"OFF\"][i % 2], bbox={'facecolor': 'white'})\n    plt.xticks([])\nplt.show()\n\"\"\"\n### Datapoint where target is 1\n\"\"\"\ndf_labels.query(\"target == 1\").sample(3)\nd_point = np.load('..\/input\/seti-breakthrough-listen\/train\/a\/a5db9a15fb61.npy')\nd_point = d_point.astype('float')\n\nplt.figure(figsize=(16,10))\nfor i in range(6):\n    plt.subplot(6, 1, i + 1)\n    if i == 0:\n        plt.title('File name: 22fa5d1a87de  | Target: 1', fontsize=18)\n    plt.imshow(d_point[i].astype(float), interpolation='nearest', aspect='auto')\n    plt.text(5, 100, [\"ON\", \"OFF\"][i % 2], bbox={'facecolor': 'white'})\n    plt.xticks([])\nplt.show()\nd_point = np.load('..\/input\/seti-breakthrough-listen\/train\/8\/84cd8577baec.npy')\nd_point = d_point.astype('float')\n\nplt.figure(figsize=(16,10))\nfor i in range(6):\n    plt.subplot(6, 1, i + 1)\n    if i == 0:\n        plt.title('File name: b18e4f5d7132  | Target: 1', fontsize=18)\n    plt.imshow(d_point[i].astype(float), interpolation='nearest', aspect='auto')\n    plt.text(5, 100, [\"ON\", \"OFF\"][i % 2], bbox={'facecolor': 'white'})\n    plt.xticks([])\nplt.show()\n\"\"\"\nIt can be seen that in the data points where target is 1, there is a vertical or inclined line. The horizontal lines are mostly noise and can be eliminated.\nWe will use fourier tranform to filter out the horizontal lines before the data is feed to the CNN model.\n\nLets look at an example of the fourier tranform.\n\"\"\"\n\"\"\"\n# Filtering the signal using Fourier transform.\n\"\"\"\n#Fourier function\n\ndef fourier_masker_ver(image):\n    dark_image_fourier =np.fft.fftshift(np.fft.fft2(image))\n    dark_image_fourier[:, 124:136] = 1\n    fig, ax = plt.subplots(1,3,figsize=(15,15))\n    ax[0].imshow(np.log(abs(dark_image_fourier)), cmap='gray')\n    ax[0].set_title('Fourier Image', fontsize = 15)\n    ax[1].imshow(image)\n    ax[1].set_title('Original Image', fontsize = 15);\n    ax[2].imshow(abs(np.fft.ifft2(dark_image_fourier)))\n    ax[2].set_title('Transformed  Image', fontsize = 15);\ndf_labels.query(\"target == 1\").sample(3)\nd_point = np.load('..\/input\/seti-breakthrough-listen\/train\/2\/2c407e6d4cce.npy')\nd_point = d_point.astype('float')\/255\nfourier_masker_ver(d_point[0])\nfourier_masker_ver(d_point[1])\nfourier_masker_ver(d_point[2])\n\"\"\"\nAs seen above the horizontal lines are removed by fourier transform. Now lets build a model based on EfficientNetB2.\n\"\"\"\ndef id_to_path(file_id, train=True):\n    data_dir = train_data_dir if train else test_data_dir\n    return data_dir \/ file_id[0] \/ f'{file_id}.npy'\nclass SETISequence(Sequence):\n    \"\"\"\n    Taken from this nice starter notebook https:\/\/www.kaggle.com\/kenjirokiyono\/seti-simple-code-for-beginners-tensorflow and added the fourier transform step\n    \"\"\"\n    def __init__(self, x_set, y_set=None, batch_size=64):\n        self.x, self.y = x_set, y_set\n        self.batch_size = batch_size\n        self.is_train = False if y_set is None else True\n    \n    def __len__(self):\n        return math.ceil(len(self.x) \/ self.batch_size)\n    \n    def __getitem__(self, idx):\n        batch_ids = self.x[idx * self.batch_size: (idx + 1) * self.batch_size]\n        if self.y is not None:\n            batch_y = self.y[idx * self.batch_size: (idx + 1) * self.batch_size]\n        \n        # taking channels \n        list_x=[]\n        # below is the fourier transform step\n        for x in batch_ids:\n            new = np.load(id_to_path(x, train=self.is_train))\n            new = new.astype('float')\/255\n            new = np.fft.fftshift(np.fft.fft2(new))\n            new[:, :, 120:136] = 1\n            new = abs(np.fft.ifft2(new))\n            list_x.append(new)\n        batch_x = np.moveaxis(list_x,1,-1)\n        batch_x = batch_x.astype(\"float\")\n        \n        if self.is_train:\n            return batch_x, batch_y\n        else:\n            return batch_x\n        \n# small output test\nSETISequence([\"00047dfc96a9\"], [1], batch_size=2).__getitem__(0)[0].shape\n\"\"\"\n# Model\n\"\"\"\ndata_augmentation_1 = tf.keras.layers.experimental.preprocessing.RandomTranslation(\n    height_factor=0.2, width_factor=0.2, fill_mode='wrap',\n    interpolation='bilinear', seed=None, fill_value=0.0\n)\ndata_augmentation_2 = tf.keras.layers.experimental.preprocessing.RandomFlip(\"vertical\")\nlr_scheduler = tf.keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate=0.001, \n    decay_steps=1000, \n    decay_rate=0.9)\nmodel = tf.keras.Sequential([\n        tf.keras.layers.Conv2D(3,(3,3), strides=(1,1), padding=\"same\", activation='relu', input_shape=(273,256,6)), data_augmentation_1, data_augmentation_2,\n        EfficientNetB2(input_shape=(273, 256, 3), weights='imagenet', include_top=False, drop_connect_rate=0.4),\n        tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(32, activation='relu'),\n        tf.keras.layers.Dense(1, activation='sigmoid')\n        ])\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler),\n              loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\"\"\"\n## To make it quick, i'll run the model on 2000 data points only.\n\"\"\"\ntrain_ids = df_labels.index.values\ntrain_y = df_labels['target'].values\ntrain = SETISequence(train_ids, train_y, batch_size=64)\nhistory = model.fit(train, epochs=8)\nsubmission = pd.read_csv(sample_file, index_col='id')\nsubmission.head()\ntest_ids = submission.index.values\ntest = SETISequence(test_ids, batch_size=64)\ntest_prediction = model.predict(test)\nfinal_pred = np.where(test_prediction > 0.5, 1, 0)\nfinal_pred[:10]\nsubmission['target'] = final_pred\nsubmission.to_csv('sub.csv', index=False)\nsubmission.head()\n\"\"\"\n### The model might not perfom well, but I have only trained the model on limited data and just 5 epochs. \n### But do let me know what you think about the idea to use fourier transform as a preprocessor.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '209e5bbca105ca'}"}
{"id":"110984","text":"\"\"\"\n# \u30e2\u30b8\u30e5\u30fc\u30eb\u5c0e\u5165\n\"\"\"\nfrom kaggle.competitions import nflrush\nimport pandas as pd\nimport numpy as np\n#from sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier as RFC\nfrom tqdm import tqdm\n\nenv = nflrush.make_env()\nfrom sklearn.model_selection import GridSearchCV,train_test_split\n\"\"\"\n # \u30c7\u30fc\u30bf\u8aad\u307f\u8fbc\u307f\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/nfl-big-data-bowl-2020\/train.csv', low_memory=False)\niter_test = env.iter_test()\n\"\"\"\n# \u524d\u51e6\u7406\n\"\"\"\n#new_df=df.groupby(['PlayId','Position']).count()\n#position_count=new_df['GameId'].unstack().fillna(0).astype(int)\nrusher_df=df[df['NflId']==df['NflIdRusher']]\n#def count_position(rusher_df):\n    #usher_df=rusher_df.merge(position_count, on='PlayId')\n    #rusher_df=rusher_df.rename(columns={'S_x':'S','S_y':'S_position'})\n    #return rusher_df\ndef preprocess(df):\n    #StadiumType\u304b\u3089\u304a\u304b\u3057\u306a\u30c7\u30fc\u30bf\u3092\u524a\u9664\n    #df=df[(df['StadiumType']!='Cloudy') & (df['StadiumType']!='Bowl')]\n    #StadiumType\u306e\u6587\u5b57\u5217\u3092\u5c4b\u5916\u5185\u3067\u5206\u3051\u3066\u30ea\u30b9\u30c8\u5316\n    #outdoor=['Outdoor', 'Outdoors','Open','Indoor, Open Roof','Outdoor Retr Roof-Open', 'Oudoor', 'Ourdoor','Retr. Roof-Open','Outdor','Retr. Roof - Open', 'Domed, Open', 'Domed, open', 'Outside','Heinz Field']\n    #indoor=['Indoors', 'RetractableRoof', 'Indoor','Retr. Roof-Closed','Dome', 'Domed, closed','Indoor, Roof Closed', 'Retr. Roof Closed','Closed Dome','Dome, closed','Domed']\n    #StadiumType\u304coutdoor\u306e\u6642\u306b\uff11\u306b\u306a\u308b\u3088\u3046\u306b\u30c0\u30df\u30fc\u5909\u6570\u5316\n    #df['stadiumtype']=(df['StadiumType'].isin(outdoor)*1)\n    #\u5929\u5019\u306e\u60aa\u3044\u6642\u3060\u3051\u30ea\u30b9\u30c8\u5316\n    #rain=['Light Rain', 'Showers','Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.','Rain', 'Heavy lake effect snow','Snow', 'Cloudy, Rain','Rain shower','Rainy']\n    #\u5929\u6c17\u304c\u60aa\u304f\u306a\u3044\u6642\u306b\uff11\u306b\u306a\u308b\u3088\u3046\u306b\u30c0\u30df\u30fc\u5909\u6570\u5316\n    #df['weather']=(~df['GameWeather'].isin(rain)*1)\n    #\u8eab\u9577\u3092\u30d5\u30a3\u30fc\u30c8\u304b\u3089\u30bb\u30f3\u30c1\u306b\u5909\u63db\n    df['PlayerHeight']= df['PlayerHeight'].apply(lambda x: 12*int(x.split('-')[0])+int(x.split('-')[1]))\n    #\u30b2\u30fc\u30e0\u306e\u7d4c\u904e\u6642\u9593\u3092\u7b97\u51fa\n    df['gameclock']=[ pd.Timedelta(val).total_seconds() for val in df['GameClock']]\n    return df\ndef add_team_yard(rusher_df):\n    #\u30c1\u30fc\u30e0\u6bce(home\/away\u5225)\u306e\u7372\u5f97\u30e4\u30fc\u30c9\u6570\u306e\u5e73\u5747\u3092\u898b\u308b\n    team_yards_df = rusher_df.groupby(['Team','PossessionTeam']).mean()[['Yards']]\n    team_yards_df = team_yards_df.rename(columns={'Yards':'team_yards'})\n    #rusher\u306e\u307f\u306e\u30c7\u30fc\u30bf\u306b\u30c1\u30fc\u30e0\u6bce\u306e\u5e73\u5747\u7372\u5f97\u30e4\u30fc\u30c9\u6570\u3092\u52a0\u3048\u308b\n    rusher_df = rusher_df.merge(team_yards_df,on='PossessionTeam',how=\"left\")\n    return rusher_df,team_yards_df\ndef add_team_score(rusher_df):\n    # \u653b\u6483\u30c1\u30fc\u30e0\u306e\u5f97\u70b9\n    rusher_df.loc[rusher_df[\"Team\"]==\"home\", \"rusherTeamScore\"] = rusher_df[\"HomeScoreBeforePlay\"]\n    rusher_df.loc[rusher_df[\"Team\"]==\"away\", \"rusherTeamScore\"] = rusher_df[\"VisitorScoreBeforePlay\"]\n\n    # \u5b88\u5099\u30c1\u30fc\u30e0\u306e\u5f97\u70b9\n    rusher_df.loc[rusher_df[\"Team\"]==\"home\", \"defenceTeamScore\"] = rusher_df[\"VisitorScoreBeforePlay\"]\n    rusher_df.loc[rusher_df[\"Team\"]==\"away\", \"defenceTeamScore\"] = rusher_df[\"HomeScoreBeforePlay\"]\n\n    # \u5f97\u70b9\u5dee\n    rusher_df.loc[:, \"diffScore\"] = rusher_df[\"rusherTeamScore\"] - rusher_df[\"defenceTeamScore\"]\n    return rusher_df\ndef count_yard_to_touchdown(rusher_df):\n    #\u30bf\u30c3\u30c1\u30c0\u30a6\u30f3\u307e\u3067\u4f55\u30e4\u30fc\u30c9\u3042\u308b\u304b\n    rusher_df[\"yardsToTouchdown\"] = rusher_df[\"YardLine\"]\n    rusher_df.loc[rusher_df[\"PossessionTeam\"] == rusher_df[\"FieldPosition\"], \"yardsToTouchdown\"] = 100-rusher_df[\"YardLine\"]\n    return rusher_df\ndef add_personal_yard(rusher_df):\n    # \u9078\u624b\u6bce\u306e\u5e73\u5747\u7372\u5f97\u30e4\u30fc\u30c9\n    rusher_yards = rusher_df[[\"NflId\", \"Yards\"]].groupby(\"NflId\").mean()[[\"Yards\"]]\n    rusher_yards.dropna(inplace=True)\n    rusher_yards=rusher_yards.rename(columns={'Yards':'PersonalYard'})\n    rusher_df = rusher_df.merge(rusher_yards, on=\"NflId\", how=\"left\")\n    return rusher_df,rusher_yards\n    \ndef add_average_data(df,rusher_df):\n    offence_position = ['WR', 'TE', 'T', 'QB', 'RB', 'G', 'C', 'FB', 'HB',  'OT', 'OG']\n    df[\"offence\"] = 0\n    df.loc[df[\"Position\"].isin(offence_position), \"offence\"] = 1\n    # \u653b\u6483,\u5b88\u5099\u30c1\u30fc\u30e0\u5e73\u5747 \u4f53\u91cd, \u8eab\u9577, S, A\uff08PlayId\u304c\u30ad\u30fc\uff09\n    offence_av = df.loc[df[\"offence\"]==1, [\"PlayerHeight\", \"PlayerWeight\", \"S\", \"A\", \"PlayId\"]].groupby(\"PlayId\").mean()\n    defence_av = df.loc[df[\"offence\"]==0, [\"PlayerHeight\", \"PlayerWeight\", \"S\", \"A\", \"PlayId\"]].groupby(\"PlayId\").mean()\n    offence_av.columns = ['PlayerHeight_offence', 'PlayerWeight_offence', 'S_offence', 'A_offence']\n    defence_av.columns = ['PlayerHeight_defence', 'PlayerWeight_defence', 'S_defence', 'A_defence']\n    rusher_df = rusher_df.merge(offence_av, on=\"PlayId\", how=\"left\").merge(defence_av, on=\"PlayId\", how=\"left\")\n    return rusher_df\n    \ndef feature(df):\n    features=pd.DataFrame(df,columns=['X', 'Y', 'S', 'A', 'Dis','Dir','YardLine', 'Quarter',\n       'gameclock', 'Down', 'Distance','HomeScoreBeforePlay', 'VisitorScoreBeforePlay', 'DefendersInTheBox','PlayerHeight',\n       'PlayerWeight','Temperature', 'Humidity',\n        #'stadiumtype', 'weather', \n        #'C', 'CB', 'DB','DE', 'DL', 'DT', 'FB', 'FS', 'G', 'HB', 'ILB', 'LB', 'MLB', 'NT', 'OG','OLB', 'OT', 'QB', 'RB', 'S_position', 'SAF', 'SS', 'T', 'TE', 'WR',\n        \"yardsToTouchdown\",\n       'PersonalYard','team_yards',\n       \"rusherTeamScore\",\"defenceTeamScore\",\"diffScore\",\n        'PlayerHeight_offence', 'PlayerWeight_offence', 'S_offence', 'A_offence',\n        'PlayerHeight_defence', 'PlayerWeight_defence', 'S_defence', 'A_defence'])\n    return features   \n#rusher_df=count_position(rusher_df)\ndf=preprocess(df)\nrusher_df=preprocess(rusher_df)\nrusher_df,team_yards_df=add_team_yard(rusher_df)\nrusher_df=add_team_score(rusher_df)\nrusher_df=count_yard_to_touchdown(rusher_df)\nrusher_df,rusher_yards=add_personal_yard(rusher_df)\nrusher_df=add_average_data(df,rusher_df)\nrusher_df=rusher_df.dropna()\nfeatures=feature(rusher_df)\ntrain_mean=features.mean(axis=0)\ntrain_std=features.std(axis=0)\n\"\"\"\n## \u6b63\u898f\u5316\n\"\"\"\ndef normalize(features):\n    X=(features-train_mean)\/train_std\n    return X\nX=normalize(features)\ntarget=pd.Series(rusher_df['Yards'])\ntrain_X,test_X,train_y,test_y=train_test_split(X,target,test_size=0.2)\n\"\"\"\n## RandomForest\u3067\u8a13\u7df4\n\"\"\"\n\"\"\"\n### GridSeach\u3067\u30c1\u30e5\u30fc\u30cb\u30f3\u30b0(\u65ad\u5ff5\uff09\n\"\"\"\nfeatures.shape\n#import warnings\n#warnings.simplefilter('ignore')\n'''\nimport datetime\nprint(datetime.datetime.now())\n\nsearch_params = {\n    'n_estimators'      : [280,300,350,400],\n    'max_features'      : [10,20,'auto'],\n    #'random_state'      : [1],\n    #'n_jobs'            : [4],\n    #'min_samples_split' : [10, 20, 30],\n    'max_depth'         : [20,30,40]}\ngsr = GridSearchCV(RFC(),search_params,cv = 3,n_jobs=-1,verbose=True)\ngsr.fit(train_X, train_y)\n\nprint(datetime.datetime.now())\n'''\n'''\n#\u6700\u9069\u306a\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u306e\u6c7a\u5b9a\u4fc2\u6570\nprint(gsr.best_score_)\n#\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u306e\u6700\u9069\u6761\u4ef6\u306e\u78ba\u8a8d\nprint(gsr.best_estimator_)\nprint(gsr.best_params_)\n'''\n#best_estimator\u3067\u51fa\u529b\u3055\u308c\u305f\u6700\u9069\u306a\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u4f7f\u7528\n#\u6c7a\u5b9a\u4fc2\u6570=0.5976363835937214\ndef train_predict(X,target):\n    clf = RFC(bootstrap=True, class_weight=None, criterion='gini',\n                       max_depth=30, max_features=10, max_leaf_nodes=None,\n                       min_impurity_decrease=0.0, min_impurity_split=None,\n                       min_samples_leaf=1, min_samples_split=2,\n                       min_weight_fraction_leaf=0.0, n_estimators=400,\n                       n_jobs=None, oob_score=False, random_state=None,\n                       verbose=0, warm_start=False)\n    clf.fit(X, target)\n    return clf\n    \n\"\"\"\n## \u3079\u30a4\u30ba\u6700\u9069\u5316\u3067\u30c1\u30e5\u30fc\u30cb\u30f3\u30b0\uff08\u6642\u9593\u304c\u304b\u304b\u308a\u3059\u304e\u308b\u306e\u3067\u65ad\u5ff5\uff09\n\"\"\"\n#from sklearn.model_selection import cross_val_score\n#from bayes_opt import BayesianOptimization\n#def randomforest_cv(n_estimators, max_features, max_depth):\n    #val = cross_val_score(\n        #RFC(\n            #n_estimators=int(n_estimators),\n            #max_features=int(max_features),\n            #max_depth=int(max_depth),\n            #criterion = 'entropy'),\n        #train_X, train_y,\n        #scoring = 'r2',\n        #cv = 3,\n        #n_jobs = -1)\n    #return val.mean()\n    \n#bo = BayesianOptimization(\n#    randomforest_cv,\n#    {'n_estimators': (200, 400),\n#    'max_features': (5, 32),\n#    'max_depth' : (30,50)})\n#import warnings\n#warnings.simplefilter('ignore')\n#bo.maximize(init_points=8,n_iter=20)\n#from matplotlib.pyplot as plt\n#%matplotlib inline\n#\u30d9\u30a4\u30ba\u6700\u9069\u5316\u306e\u7d50\u679c\u3092\u30d7\u30ed\u30c3\u30c8\n#plot_bo(bo)\n#plt.legend()\n#plt.grid()\n#plt.show()\n#bo.max['params']\n#bo.max['target']\n#\u30d9\u30a4\u30ba\u6700\u9069\u5316\u3067\u51fa\u529b\u3055\u308c\u305f\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u3092\u56db\u6368\u4e94\u5165\u3067\u4e38\u3081\u308b\n#'max_depth': 48.704309793515755,\n#'max_features': 5.671956856631306,\n#'min_samples_split': 6.739604788678628,\n#'n_estimators': 248.58715626809243\n#\u6c7a\u5b9a\u4fc2\u6570\u306f0.673114259554454\n\n#def train_predict(X,target):\n#    clf = RFC(n_estimators=249,\n#              max_features=6,\n#              max_depth=49,\n#              min_samples_split=7)\n#    clf.fit(X,target)\n#    return clf\n#RandomForestClassier\u3067\u306f\u306a\u304fCatBoostClassifier\u306b\u6311\u6226\u3057\u305f\u3044\n#from catboost import CatBoostClassifier as CBC\n#def train_predict(X,target):\n    #clf=CBC()\n    #clf.fit(X,target)\n    #return clf\nclf=train_predict(train_X,train_y)\n#\u8aac\u660e\u5909\u6570\u306e\u5f71\u97ff\u306e\u78ba\u8a8d\nfeat_imp=pd.DataFrame(clf.feature_importances_,index=X.columns)\nfeat_imp.sort_values(0,ascending=False)\nscore_test=np.array([(i >= test_y)*1 for i in range(-99,100)])\npred_y=clf.predict(test_X)\n\"\"\"\n## Yards\u306e\u7d2f\u7a4d\u78ba\u7387\u5206\u5e03\u3092\u898b\u308b\n\"\"\"\nfrom scipy.stats import norm \nyard = np.arange(-99, 100) \npred_prob = [norm.cdf(yard, loc=i, scale=target.std()) for i in pred_y] \nimport matplotlib.pyplot as plt\n\n#pred_prob\u3092dataframe\u306b\u3059\u308b\npred_prob2=pd.DataFrame(pred_prob)\n\n#\u7d2f\u7a4d\u78ba\u7387\u66f2\u7dda\u306e\u8868\u793a\nplt.plot(yard,pred_prob2.mean())\nplt.show()\n#score=np.array([(i >= pred_y)*1 for i in range(-99,100)])\n\"\"\"\n# \u30e2\u30c7\u30eb\u306e\u7cbe\u5ea6\u306e\u78ba\u8a8d\n\"\"\"\nc=((pred_prob - score_test.T)**2).sum().sum()\/(199*len(pred_prob))\nc\ntrain_df=rusher_df.iloc[:0,:]\n#yard=['Yards' + str(i) for i in range(-99,100)]\n\"\"\"\n# \u4e88\u6e2c\n\"\"\"\nfor (test_df, sample_prediction_df) in tqdm(iter_test):\n    #new_df=test_df.groupby(['PlayId','Position']).count()\n    #position_count=new_df['GameId'].unstack().fillna(0).astype(int)\n    rusher_df=test_df[test_df['NflId']==test_df['NflIdRusher']]\n    rusher_df=preprocess(rusher_df)\n    test_df=preprocess(test_df)\n    #test_df=count_position(test_df)\n    rusher_df=rusher_df.merge(rusher_yards,  on=\"NflId\", how=\"left\")\n    rusher_df = rusher_df.merge(team_yards_df,on='PossessionTeam',how=\"left\")\n    rusher_df=add_team_score(rusher_df)\n    rusher_df=count_yard_to_touchdown(rusher_df)\n    rusher_df=add_average_data(test_df,rusher_df)\n    rusher_df=pd.concat([train_df,test_df],sort=False)\n    test_feature=feature(rusher_df)\n    test_feature=test_feature.fillna(0)\n    test_X=normalize(test_feature)\n    pred_y=clf.predict(test_X)\n    pred_y=np.round(pred_y)\n    pred_prob =norm.cdf(yard, loc=pred_y[0], scale=target.std()) \n    sample_prediction_df.iloc[0,:]=pred_prob\n    env.predict(sample_prediction_df)\nsample_prediction_df\nenv.write_submission_file()\nimport os\nprint([filename for filename in os.listdir('\/kaggle\/working') if '.csv' in filename])","meta":"{'source': 'AI4Code', 'id': 'cbf1ddd224da43'}"}
{"id":"17385","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n# Showing\n\"\"\"\ndf = pd.read_excel('\/kaggle\/input\/lottery-br\/megas.xls')\ndf\n\"\"\"\n# Checking\n\"\"\"\ndf.info()\n\"\"\"\n# Changing DataFrame to Arrays\n\"\"\"\ndf2 = df.drop(['date_occured','lottery'], axis=1)\ndf2 = df2.to_numpy()\ntype(df2)\n\"\"\"\n# The problem  (II)\n\"\"\"\ndf2\n\"\"\"\n# The solution\n\"\"\"\ndf2.sort(axis=1)\ndf2\n\"\"\"\n# Changing Arrays to DataFrame\n\"\"\"\ndf2 = pd.DataFrame({'Draw1': df2[:, 0], 'Draw2': df2[:, 1], 'Draw3': df2[:, 2], 'Draw4': df2[:, 3], 'Draw5': df2[:, 4], 'Draw6': df2[:, 5]})\ndf2\n\"\"\"\n# Wow! Fantastic!\n\"\"\"\ndf3 = pd.concat([df, df2], axis=1, sort=False)\ndf3\n\"\"\"\n# Cleaning\n\"\"\"\ndf3 = df3.drop(['ball_01','ball_02','ball_03','ball_04','ball_05','ball_06'], axis=1)\ndf3\n\"\"\"\n\n# Thank You!\n## Is there a way to make this code better? Leave your comment below!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1fbcdccf462719'}"}
{"id":"35412","text":"\"\"\"\n# Various classifications of speech data, via Deep Learning methods, built using PyTorch\n\"\"\"\n\"\"\"\nImport some packages to get us started:\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\n\"\"\"\nThe following information is given in the dataset description. Essentially, the name of the file is an encoded representation of each of the following aspects:\n\"\"\"\n\"\"\"\n**Filename identifiers**\n\n* Modality (01 = full-AV, 02 = video-only, 03 = audio-only).\n\n* Vocal channel (01 = speech, 02 = song).\n\n* Emotion (01 = neutral, 02 = calm, 03 = happy, 04 = sad, 05 = angry, 06 = fearful, 07 = disgust, 08 = surprised).\n\n* Emotional intensity (01 = normal, 02 = strong). NOTE: There is no strong intensity for the 'neutral' emotion.\n\n* Statement (01 = \"Kids are talking by the door\", 02 = \"Dogs are sitting by the door\").\n\n* Repetition (01 = 1st repetition, 02 = 2nd repetition).\n\n* Actor (01 to 24. Odd numbered actors are male, even numbered actors are female).\n\"\"\"\n\"\"\"\nWe create various dictionaries and a function to decipher this encoded information in the filename, in order to be able to train our Deep Learning models to predict them.\n\"\"\"\nmodality = {'01':'full_av','02':'video_only','03':'audio_only'}\nvocal_channel = {'01':'speech','02':'song'}\nemotion = {'01':'neutral','02':'calm','03':'happy','04':'sad','05':'angry','06':'fearful','07':'disgust','08':'surprised'}\nemotional_intensity = {'01':'normal','02':'strong'}\nstatement = {'01':'Kids are talking by the door','02':'Dogs are sitting by the door'}\nreptition = {'01':'first_repitition','02':'second_repetition'}\ndef actor_f(num):\n    if int(num)%2==0: return('female')\n    else: return('male')\n\"\"\"\nHere, we just get a full list of all the actors, removing a piece of irrelevant information via the .pop() method:\n\"\"\"\nactors = sorted(os.listdir('..\/input\/ravdess-emotional-speech-audio'))\nactors.pop()\nactors\n\"\"\"\nNow, for each of the actors, we obtain the label information from the filenames:\n\"\"\"\naudio_file_dict = {}\nfor actor in actors:\n    actor_dir = os.path.join('..\/input\/ravdess-emotional-speech-audio',actor)\n    actor_files = os.listdir(actor_dir)\n    actor_dict = [i.replace(\".wav\",\"\").split(\"-\") for i in actor_files]\n    dict_entry = {os.path.join(actor_dir,i):j for i,j in zip(actor_files,actor_dict)}\n    audio_file_dict.update(dict_entry)\n\"\"\"\nWe cast this as a pandas dataframe, but need to transpose it so that the labels appear in the columns and the filenames become the row indices, we also give our columns appropriate names:\n\"\"\"\naudio_file_dict = pd.DataFrame(audio_file_dict).T\naudio_file_dict.columns = ['modality','vocal_channel','emotion','emotional_intensity','statement','repetition','actor']\naudio_file_dict\n\"\"\"\nNow, we use the dictionaries and function created above to transform the digit-encoded labels into human-readable format:\n\"\"\"\naudio_file_dict.modality = audio_file_dict.modality.map(modality)\naudio_file_dict.vocal_channel = audio_file_dict.vocal_channel.map(vocal_channel)\naudio_file_dict.emotion = audio_file_dict.emotion.map(emotion)\naudio_file_dict.emotional_intensity = audio_file_dict.emotional_intensity.map(emotional_intensity)\naudio_file_dict.statement = audio_file_dict.statement.map(statement)\naudio_file_dict.repetition = audio_file_dict.repetition.map(reptition)\naudio_file_dict['actor_sex'] = audio_file_dict.actor.apply(actor_f)\naudio_file_dict\n\"\"\"\nImport plotting libraries:\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\nWe plot a few of the labels we might want to predict in this exercise, below. Mostly there is an even class distribution. We shouldn't have to use any sampling techniques to account for class imbalances\n\"\"\"\nfig, (ax1,ax2) = plt.subplots(2, 2,figsize=(12,8))\nax1[0].barh(y=audio_file_dict.emotion.value_counts().index,width=audio_file_dict.emotion.value_counts().values)\nax1[0].set_title('Emotion')\nax1[1].bar(x=audio_file_dict.actor_sex.value_counts().index,height=audio_file_dict.actor_sex.value_counts().values)\nax1[1].set_title('Actor Sex')\nax2[0].bar(x=audio_file_dict.emotional_intensity.value_counts().index,height=audio_file_dict.emotional_intensity.value_counts().values)\nax2[0].set_title('Emotional Intensity')\nax2[1].bar(x=audio_file_dict.statement.value_counts().index,height=audio_file_dict.statement.value_counts().values)\nplt.xticks(rotation=45)\nax2[1].set_title('Statement')\nfig.tight_layout() \n\"\"\"\nWe need the **Torch Audio** library to be able to load the .wav files in this dataset:\n\"\"\"\nimport torchaudio\n\"\"\"\nHaving a look at what loading an audio file returns, we see a 2D-tensor as well as the sampling rate gets returned for each file\n\"\"\"\nsample1, sample_rate1 = torchaudio.load('..\/input\/ravdess-emotional-speech-audio\/Actor_01\/03-01-01-01-01-01-01.wav')\nsample1, sample_rate1\nsample2, sample_rate2 = torchaudio.load('..\/input\/ravdess-emotional-speech-audio\/Actor_01\/03-01-01-01-01-02-01.wav')\nsample2, sample_rate2\n\"\"\"\nUnfortunately, the files do not have the same lengths, which will require us to do some extra processing later:\n\"\"\"\nsample1.shape\nsample2.shape\n\"\"\"\nWe import the torch library and have a look at some very basic descriptive about the examples we have loaded:\n\"\"\"\nimport torch\ntorch.mean(sample1), torch.std(sample1), torch.min(sample1), torch.max(sample1)\ntorch.mean(sample2), torch.std(sample2), torch.min(sample2), torch.max(sample2)\n\"\"\"\nLet's plot an example waveform:\n\"\"\"\nplt.plot(sample1.t().numpy())\nplt.plot(sample2.t().numpy())\n\"\"\"\nNow, in order to get around the fact that we have audio files of differing lengths, we first load all the files into a python list:\n\"\"\"\naudio_files = []\nfor i in list(audio_file_dict.index):\n    i, _ = torchaudio.load(i)\n    audio_files.append(i)\n\"\"\"\nWe then get the minimum and maximum lengths for all the files in our dataset:\n\"\"\"\nmaxlen = 0\nminlen = np.Inf\nfor i in audio_files:\n    if i.shape[1]>maxlen:\n        maxlen = i.shape[1]\n    if i.shape[1]<minlen:\n        minlen = i.shape[1]\nminlen, maxlen\n\"\"\"\nNext, we encode our audio data into a spectrogram:\n\nFrom : [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/Spectrogram#:~:text=A%20spectrogram%20is%20a%20visual,sonographs%2C%20voiceprints%2C%20or%20voicegrams.)\n> A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. When applied to an audio signal, spectrograms are sometimes called sonographs, voiceprints, or voicegrams. \n\"\"\"\n\"\"\"\nWe transform one of our example waveforms into a spectrogram and visualize the result:\n\"\"\"\nspecgram = torchaudio.transforms.Spectrogram()(sample1)\n\nprint(\"Shape of spectrogram: {}\".format(specgram.size()))\n\nplt.figure()\nplt.imshow(specgram.log2()[0,:,:].numpy(), cmap='gray')\n\"\"\"\nNext, we loop through all of our loaded waveforms and transform each one into a spectrogram:\n\"\"\"\nspectrograms = []\nfor i in audio_files:\n    specgram = torchaudio.transforms.Spectrogram()(i)\n    spectrograms.append(specgram)\n\"\"\"\nLook at a couple of examples of their shapes:\n\"\"\"\nspectrograms[0].shape,spectrograms[1].shape,spectrograms[2].shape,\n\"\"\"\nNow, we grab the maximum heights and widths for all the spectrograms:\n\"\"\"\nmax_width, max_height = max([i.shape[2] for i in spectrograms]), max([i.shape[1] for i in spectrograms])\n\"\"\"\nAnd we use the pad function from torch.nn.functional, to pad images that are smaller than these maximum sizes with zeros, to make them all the same shape:\n\"\"\"\nimport torch.nn.functional as F\nimage_batch = [\n    # The needed padding is the difference between the\n    # max width\/height and the image's actual width\/height.\n    F.pad(img, [0, max_width - img.size(2), 0, max_height - img.size(1)])\n    for img in spectrograms\n]\n\"\"\"\nNow, we can see that they are all the same shape:\n\"\"\"\nimage_batch[0].shape, image_batch[1].shape, image_batch[2].shape,\n\"\"\"\nPlotting an example, showing the padded space on the right:\n\"\"\"\nplt.imshow(image_batch[0][0].log2())\n\"\"\"\nWe collapse this list of tensors, which are all the same size now, along the first dimension:\n\"\"\"\nimage_batch = torch.cat(image_batch,0)\n\"\"\"\nWe just delete some objects in our workspace which are chowing our limited available RAM:\n\"\"\"\ndel audio_files, spectrograms\n\"\"\"\n# Classifying male vs female voices\n\nThis should hopefully be easy, but you never know...\n\nFirst, we one-hot encode the actor sex column and plot the result, confirming that we have similar numbers of male and female actors, making accuracy an easy to implement metric to evaluate the success of our model:\n\"\"\"\ny = pd.get_dummies(audio_file_dict.actor_sex,drop_first=True)\ny.plot.hist()\ny = torch.from_numpy(np.array(y))\ny.shape\n\"\"\"\nBut really, in order to be able to properly train on this dataset, we need to define our own custom PyTorch Dataset class, in order to get the relevant files from disk only as they're needed, thus freeing up memory:\n\"\"\"\nfrom torch.utils.data.dataset import Dataset\n\n\nclass MyCustomDataset(Dataset):\n    def __init__(self, audio_file_dict):\n        self.audio_fie_dict = audio_file_dict\n        \n    def __getitem__(self, index):\n        img = list(audio_file_dict.index)[index]\n        img, _ = torchaudio.load(img)\n        img = torch.mean(img, dim=0).unsqueeze(0)\n        img = torchaudio.transforms.Spectrogram()(img)\n        img = F.pad(img, [0, max_width - img.size(2), 0, max_height - img.size(1)])\n        \n        def labeler(name):\n            if name == 'male':\n                return(1)\n            else:\n                return(0)\n        \n        label = list(audio_file_dict.actor_sex)[index]\n        label = np.array(labeler(label))\n        label = torch.from_numpy(label)\n        return (img, label)\n\n    def __len__(self):\n        count = len(audio_file_dict)\n        return count\n\"\"\"\nWe split our data into training- (70%) and testing- (30%) sets:\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test = train_test_split(audio_file_dict,test_size=0.3)\ntrain_data = MyCustomDataset(audio_file_dict=X_train)\ntest_data = MyCustomDataset(audio_file_dict=X_test)\n\"\"\"\nNow, we can go ahead and delete these fairly large objects, to free up some more memory:\n\"\"\"\ndel image_batch, y\n\"\"\"\nWe set up some hyperparameters before training. We will see what 50 epochs can achieve, at a batch size of 16, with a relatively low learning rate of 1e-5\n\"\"\"\nnum_epochs = 50\nnum_classes = 2\nbatch_size = 16\nlearning_rate = 0.000001\n\"\"\"\nNext, we use a dataloader each to load our training and test sets, shuffling the training, but not the test set:\n\"\"\"\nfrom torch.utils.data import DataLoader\ntrain_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True)\ntest_loader = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=False)\nimport torch.nn as nn\n\"\"\"\nWe define a convolutional neural network, with 4 convolutional layers, with increasing number of filters, each with a kernel size of 5x5, followed by maxpooling downsampling with a window of 2x2 and lastly two fully connected layers.\n\nWe will use CrossEntropy as our loss function and Adam as our optimizer:\n\"\"\"\nclass ConvNet(nn.Module):\n    def __init__(self):\n        super(ConvNet, self).__init__()\n        self.layer1 = nn.Sequential(\n            nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer2 = nn.Sequential(\n            nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer3 = nn.Sequential(\n            nn.Conv2d(64, 128, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer4 = nn.Sequential(\n            nn.Conv2d(128, 256, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.drop_out = nn.Dropout()\n        self.fc1 = nn.Linear(242688, 1000)\n        self.fc2 = nn.Linear(1000, 2)\n    def forward(self, x):\n        out = self.layer1(x)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = out.reshape(out.size(0), -1)\n        out = self.drop_out(out)\n        out = self.fc1(out)\n        out = self.fc2(out)\n        return out\n\nmodel = ConvNet()\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\"\"\"\nWe have access to a GPU on Kaggle, thankfully, so we move our model to the CUDA device:\n\"\"\"\nmodel.cuda()\n\"\"\"\nHere, we train our model, printing accuracy and loss metrics after each of 50 epochs:\n\"\"\"\n# Train the model\ntotal_step = len(train_loader)\n\nfor epoch in range(num_epochs):\n    loss_list = []\n    acc_list = []\n    for i, (images, labels) in enumerate(train_loader):\n        # Run the forward pass\n        images = images.cuda()\n        labels = labels.cuda()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss_list.append(loss.item())\n\n        # Backprop and perform Adam optimisation\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n        # Track the accuracy\n        total = labels.size(0)\n        _, predicted = torch.max(outputs.data, 1)\n        correct = (predicted == labels).sum().item()\n        acc_list.append(correct \/ total)\n    print(f'epoch: {epoch}: acc:',np.mean(acc_list),'loss: ',np.mean(loss_list))\n\"\"\"\nSo, we get just under 80% accuracy on our training dataset after 50 epochs, let's see how we do on unseen data:\n\"\"\"\n\"\"\"\nWe put our model into evaluation mode, disabling features only needed during training, such as Dropout:\n\"\"\"\nmodel.eval()\n\"\"\"\nNow, we evaluate how well our model does on the unseen data in the test set:\n\"\"\"\npreds = []\noutcome = []\nlabs = []\nwith torch.no_grad():\n    for data in test_loader:\n        images, labels = data\n        images = images.cuda()\n        labels = labels.cuda()\n        labs.append(labels)\n        outputs = model(images)\n        _, predicted = torch.max(outputs, 1)\n        preds.append(predicted)\n        c = (predicted == labels).squeeze()\n        outcome.append(c)\noutcome = torch.stack(outcome).view(-1).cpu().numpy()\n\"\"\"\nAccuracy on test set:\n\"\"\"\nprint('Accuracy on test set after 50 epochs: ',100*round(outcome.sum()\/len(outcome),2),'%')\n\"\"\"\n# Classifying emotion\n\nNext, we'll step up our game a little and try to predict emotions, rather than just the binary case of male\/ female. Before starting with this, an initial guess is that this might be a bit harder to get good accuracy with, but let's see what we can come up with:\n\"\"\"\n\"\"\"\nWe use the same data loader, but just adjust it to load the emotion associated with each file, instead of the sex of the actor, as the labels to be predicted:\n\"\"\"\nclass EmotionDataset(Dataset):\n    def __init__(self, audio_file_dict):\n        self.audio_fie_dict = audio_file_dict\n        \n    def __getitem__(self, index):\n        img = list(audio_file_dict.index)[index]\n        img, _ = torchaudio.load(img)\n        img = torch.mean(img, dim=0).unsqueeze(0)\n        img = torchaudio.transforms.Spectrogram()(img)\n        img = F.pad(img, [0, max_width - img.size(2), 0, max_height - img.size(1)])\n        \n        label = pd.get_dummies(audio_file_dict.emotion)[index]\n        label = np.array(label)\n        label = torch.from_numpy(label)\n        return (img, label)\n\n    def __len__(self):\n        count = len(audio_file_dict)\n        return count\ntrain_data = EmotionDataset(audio_file_dict=X_train)\ntest_data = EmotionDataset(audio_file_dict=X_test)\n\"\"\"\nSimilarly, we use the same model architecture, only changing the number of neurons in the output layer from 2 to 8, representing the 8 possible emotions in the set of labels we've been given:\n\"\"\"\nclass ConvNet(nn.Module):\n    def __init__(self):\n        super(ConvNet, self).__init__()\n        self.layer1 = nn.Sequential(\n            nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer2 = nn.Sequential(\n            nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer3 = nn.Sequential(\n            nn.Conv2d(64, 128, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.layer4 = nn.Sequential(\n            nn.Conv2d(128, 256, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2))\n        self.drop_out = nn.Dropout()\n        self.fc1 = nn.Linear(242688, 1000)\n        self.fc2 = nn.Linear(1000, 8)\n    def forward(self, x):\n        out = self.layer1(x)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = out.reshape(out.size(0), -1)\n        out = self.drop_out(out)\n        out = self.fc1(out)\n        out = self.fc2(out)\n        return out\n\nmodel = ConvNet()\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\"\"\"\nAgain, move model onto the GPU device:\n\"\"\"\nmodel.cuda()\n\"\"\"\nTrain for 50 epochs:\n\"\"\"\n# Train the model\ntotal_step = len(train_loader)\n\nfor epoch in range(num_epochs):\n    loss_list = []\n    acc_list = []\n    for i, (images, labels) in enumerate(train_loader):\n        # Run the forward pass\n        images = images.cuda()\n        labels = labels.cuda()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss_list.append(loss.item())\n\n        # Backprop and perform Adam optimisation\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n        # Track the accuracy\n        total = labels.size(0)\n        _, predicted = torch.max(outputs.data, 1)\n        correct = (predicted == labels).sum().item()\n        acc_list.append(correct \/ total)\n    print(f'epoch: {epoch}: acc:',np.mean(acc_list),'loss: ',np.mean(loss_list))\nmodel.eval()\npreds = []\noutcome = []\nlabs = []\nwith torch.no_grad():\n    for data in test_loader:\n        images, labels = data\n        images = images.cuda()\n        labels = labels.cuda()\n        labs.append(labels)\n        outputs = model(images)\n        _, predicted = torch.max(outputs, 1)\n        preds.append(predicted)\n        c = (predicted == labels).squeeze()\n        outcome.append(c)\noutcome = torch.stack(outcome).view(-1).cpu().numpy()\nprint('Accuracy on test set after 50 epochs: ',100*round(outcome.sum()\/len(outcome),2),'%')\n\"\"\"\n# Classifying multiple attributes with a single model, using transfer learning:\n\nLastly, we want to use transfer learning to take a pretrained neural network, chop off its head and give it four new heads (shameless GOT reference: how many heads does the Dragon have? - It's not 4...)\n\nWe then want to use this single model to predict 4 different outcomes:\n* Actor Sex\n* Emotion\n* Emotional Intensity\n* Statement\n\"\"\"\nfrom torchvision import models\nclass MultiOutputModel(nn.Module):\n    def __init__(self, n_actor_sex_classes, n_emotion_classes, n_emotional_intensity_classes, n_statement_classes):\n        super().__init__()\n        arch = models.AlexNet().features  # take the model without classifier\n        arch = list(arch.children())\n        w = arch[0].weight\n        arch[0] = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=2, bias=False)\n        arch[0].weight = nn.Parameter(torch.mean(w, dim=1, keepdim=True))\n        self.base_model = nn.Sequential(*arch)\n        \n        last_channel = 256 # size of the layer before the classifier\n\n        # the input for the classifier should be two-dimensional, but we will have\n        # [<batch_size>, <channels>, <width>, <height>]\n        # so, let's do the spatial averaging: reduce <width> and <height> to 1\n        self.pool = nn.AdaptiveAvgPool2d((1, 1))\n\n        # create separate classifiers for our outputs\n        self.actor_sex = nn.Sequential(\n            nn.Dropout(p=0.2),\n            nn.Linear(in_features=last_channel, out_features=n_actor_sex_classes )\n        )\n        self.emotion = nn.Sequential(\n            nn.Dropout(p=0.2),\n            nn.Linear(in_features=last_channel, out_features=n_emotion_classes)\n        )\n        self.emotional_intensity = nn.Sequential(\n            nn.Dropout(p=0.2),\n            nn.Linear(in_features=last_channel, out_features=n_emotional_intensity_classes)\n        )\n        self.statement = nn.Sequential(\n            nn.Dropout(p=0.2),\n            nn.Linear(in_features=last_channel, out_features=n_statement_classes)\n        )\n    def forward(self, x):\n        x = self.base_model(x)\n        x = self.pool(x)\n\n        # reshape from [batch, channels, 1, 1] to [batch, channels] to put it into classifier\n        #x = torch.flatten(x, start_dim=1)\n        x = x.view(-1)\n        return {\n            'actor_sex': self.actor_sex(x),\n            'emotion': self.emotion(x),\n            'emotional_intensity': self.emotional_intensity(x),\n            'statement': self.statement(x)\n        }\n    def get_loss(self, net_output, ground_truth):\n        actor_sex_loss = F.cross_entropy(net_output['actor_sex'].unsqueeze(0), torch.argmax(ground_truth['actor_sex']).unsqueeze(0))\n        emotion_loss = F.cross_entropy(net_output['emotion'].unsqueeze(0), torch.argmax(ground_truth['emotion']).unsqueeze(0))\n        emotional_intensity_loss = F.cross_entropy(net_output['emotional_intensity'].unsqueeze(0),\n                                                   torch.argmax(ground_truth['emotional_intensity']).unsqueeze(0))\n        statement_loss = F.cross_entropy(net_output['statement'].unsqueeze(0), torch.argmax(ground_truth['statement']).unsqueeze(0))\n        loss = actor_sex_loss + emotion_loss + emotional_intensity_loss + statement_loss\n        return loss, {'actor_sex': actor_sex_loss, 'emotion': emotion_loss, 'emotional_intensity': emotional_intensity_loss,\n                     'statement': statement_loss}\nN_epochs = 50\nbatch_size = 1\n\nmodel = MultiOutputModel(n_actor_sex_classes=2,n_emotion_classes=8,n_emotional_intensity_classes=2,n_statement_classes=2).cuda()\n\n\noptimizer = torch.optim.Adam(model.parameters(),lr=0.01)\nimport torch\nclass MultiLabelDataset(Dataset):\n    def __init__(self, audio_file_dict):\n        self.audio_file_dict = audio_file_dict\n        \n    def __getitem__(self, index):\n        img = list(audio_file_dict.index)[index]\n        img, _ = torchaudio.load(img)\n        img = torch.mean(img, dim=0).unsqueeze(0)\n        img = torchaudio.transforms.Spectrogram()(img)\n        img = F.pad(img, [0, max_width - img.size(2), 0, max_height - img.size(1)])\n        \n        def labeler(name):\n            if name == 'male':\n                return([1,0])\n            else:\n                return([0,1])\n        \n        actor_sex_label = list(audio_file_dict.actor_sex)[index]\n        actor_sex_label = np.array(labeler(actor_sex_label))\n        actor_sex_label = torch.from_numpy(actor_sex_label)\n        \n        emotion_label = pd.get_dummies(audio_file_dict.emotion).iloc[index,:]\n        emotion_label = torch.from_numpy(np.array(emotion_label))\n        \n        emotional_intensity_label = pd.get_dummies(audio_file_dict.emotional_intensity).iloc[index,:]\n        emotional_intensity_label = torch.from_numpy(np.array(emotional_intensity_label))\n        \n        statement_label =  pd.get_dummies(audio_file_dict.statement).iloc[index,:]\n        statement_label = torch.from_numpy(np.array(statement_label))\n        \n        label = {'actor_sex': actor_sex_label.cuda(),\n                'emotion': emotion_label.cuda(),\n                'emotional_intensity':emotional_intensity_label.cuda(),\n                'statement': statement_label.cuda()}\n        \n        return (img, label)\n\n    def __len__(self):\n        count = len(audio_file_dict)\n        return count\ntrain_data = MultiLabelDataset(audio_file_dict=X_train)\ntest_data = MultiLabelDataset(audio_file_dict=X_test)\ntrain_dataloader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True)\ntest_dataloader = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=False)\nfor epoch in range(0, N_epochs + 1):\n    total_loss = []\n    total_accuracy = []\n    for batch in train_dataloader:\n        optimizer.zero_grad()\n        img, labels = batch\n        img = img.cuda()\n        output = model(img)\n        \n        loss_train, losses_train = model.get_loss(output, labels)\n        total_loss.append(loss_train.item())\n        \n        acc = 100*(torch.sum(torch.tensor([torch.argmax(output['actor_sex'])==torch.argmax(labels['actor_sex']),\n            torch.argmax(output['emotion'])==torch.argmax(labels['emotion']),\n            torch.argmax(output['emotional_intensity'])==torch.argmax(labels['emotional_intensity']),\n            torch.argmax(output['statement'])==torch.argmax(labels['statement'])]))\/4.)\n        total_accuracy.append(acc)\n        \n        \n    print(f'Epoch: {epoch}: Loss: ',np.mean(total_loss),' Accuracy: ',np.mean(total_accuracy))","meta":"{'source': 'AI4Code', 'id': '4144778538e896'}"}
{"id":"76122","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimg1 = cv.resize(cv.imread('..\/input\/monalisa\/mona.jpg',cv.IMREAD_GRAYSCALE), (0,0), fx=0.5, fy=0.5)\nimg2 = cv.resize(cv.imread('..\/input\/monalisa\/3.jpg',cv.IMREAD_GRAYSCALE), (0,0), fx=0.5, fy=0.5)\n# Initiate AKAZE detector\ndetector = cv.AKAZE_create()\n\"\"\"\n# Basics of Brute-Force Matcher\n\"\"\"\n\"\"\"\nBrute-Force Matching with KAZE Descriptors and Ratio Test\n\nThis time, we will use BFMatcher.knnMatch() to get k best matches. In this example, we will take k=2 so that we can apply ratio test explained by D.Lowe in his paper\n\"\"\"\n# find the keypoints and descriptors with AKAZE\nkp1, des1 = detector.detectAndCompute(img1,None)\nkp2, des2 = detector.detectAndCompute(img2,None)\n# ([], [])\nimgL = cv.drawKeypoints(img1, kp1, None, color=(0,0,255), flags=0)\nimgR = cv.drawKeypoints(img2, kp2, None, color=(0,0,255), flags=0)\n# BFMatcher with default params\nbf = cv.BFMatcher()\nmatches = bf.knnMatch(des1,des2,k=2)\n# Apply ratio test\ngood = []\nfor m,n in matches:\n    if m.distance < 0.75*n.distance:\n        good.append([m])\n# cv.drawMatchesKnn expects list of lists as matches.\nimg3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\nplt.figure(figsize=(16, 16))\nplt.title('AKAZE Interest Points')\nplt.imshow(img3)\nplt.show()\n\"\"\"\n# Feature Matching + Homography to find Objects\n\"\"\"\n\"\"\"\nNow, we will mix up the feature matching and findHomography from calib3d module to find known objects in a complex image\n\"\"\"\nMIN_MATCH_COUNT = 10\n# store all the good matches as per Lowe's ratio test.\ngood = []\nfor m,n in matches:\n    if m.distance < 0.7*n.distance:\n        good.append(m)\n\nif len(good)>MIN_MATCH_COUNT:\n    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)\n    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)\n    M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)\n    matchesMask = mask.ravel().tolist()\n    h, w  = img1.shape\n    d  = img1.shape\n    pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n    dst = cv.perspectiveTransform(pts,M)\n    img2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)\nelse:\n    print( \"Jumlah Key Point : {}\/{}\".format(len(good), MIN_MATCH_COUNT) )\n    matchesMask = None\n\ndraw_params = dict(matchColor = (0,255,0), # draw matches in green color\n                   singlePointColor = None,\n                   matchesMask = matchesMask, # draw only inliers\n                   flags = 2)\nimg3 = cv.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)\nplt.figure(figsize=(20, 20))\nplt.title('Feature Matching + Homography to find Objects with AKAZE Algorithm')\nplt.imshow(img3, 'gray'),plt.show()","meta":"{'source': 'AI4Code', 'id': '8bef4e13a01ec2'}"}
{"id":"66991","text":"\"\"\"\n# Project: Is playing home advantageous to the soccer team?\n\n## Table of Contents\n<ul>\n<li><a href=\"#intro\">Introduction<\/a><\/li>\n<li><a href=\"#wrangling\">Data Wrangling<\/a><\/li>\n<li><a href=\"#eda\">Exploratory Data Analysis<\/a><\/li>\n<li><a href=\"#conclusions\">Conclusions and Limitations<\/a><\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n<a id='intro'><\/a>\n## Introduction\n> In this report, we will be analysing the Europeon Soccer Dataset to find out the titled question. This dataset comes from Kaggle and is well suited for data analysis and machine learning. It contains data for 25k+ soccer matches, 10k+ players, and teams from several European countries from 2008 to 2016.\n\"\"\"\n\"\"\"\n### Question\n> Do teams playing home have an advantage? \n\"\"\"\n\"\"\"\nWe will try to validate the possibility the above question.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sqlite3\n\n%matplotlib inline\n\"\"\"\n<a id='wrangling'><\/a>\n## Data Wrangling\n### General Properties\n\"\"\"\n\"\"\"\nThe data is present is a SQLite file, which is a kind of database, that contains data in different tables. We will be using the `Match` table for analysis.\n\"\"\"\nconn = sqlite3.connect('..\/input\/soccer\/database.sqlite')\ncursor = conn.cursor()\n\nsql = \"\"\"SELECT * FROM Match\"\"\" # sql query to get data\n# loading the data\nmatch = pd.read_sql(sql, conn, index_col='id')\nmatch.shape\nmatch.head()\n# selecting relevant col for matches\nselected_cols = ['country_id', 'league_id', 'season', 'stage', 'date', 'match_api_id',\n       'home_team_api_id', 'away_team_api_id', 'home_team_goal', 'away_team_goal']\n\nmatch_data = match[selected_cols]\n\n# selecting relevant col for betting data,\nbetting_data = match[['home_team_api_id', 'away_team_api_id', 'home_team_goal',\n       'away_team_goal','B365H', 'B365D', 'B365A', 'BWH', 'BWD', 'BWA','IWH',\n         'IWD', 'IWA', 'LBH', 'LBD', 'LBA', 'PSH', 'PSD', 'PSA', 'WHH', 'WHD',\n     'WHA', 'SJH', 'SJD', 'SJA', 'VCH', 'VCD', 'VCA', 'GBH', 'GBD', 'GBA', 'BSH', 'BSD', 'BSA']]\n# no any missing values or wrong data type was found except `date`\n# we will ignore it for a this time\nmatch_data.info()\nmatch_data.describe()\n# data types look right,\nbetting_data.info()\n# But, there are many sources for which we don't have betting scores for all matches\nbetting_data.isnull().any(axis=1).sum()   # there are 23K rows which have atleast one missing value\n# lets select data for top 3 sources by data availability - B365, BW, WH\nbetting_data = betting_data.drop(columns=['IWH', 'IWD', 'IWA', 'LBH', 'LBD', 'LBA', 'PSH', 'PSD', 'PSA',\n     'SJH', 'SJD', 'SJA', 'VCH', 'VCD', 'VCA', 'GBH', 'GBD', 'GBA', 'BSH', 'BSD', 'BSA'])\nbetting_data.info()\n# still we have around 3K rows with atleast one missing value\nbetting_data.isnull().any(axis=1).sum()   \n# lets check the number of matches for which we don't have betting score at all\nbetting_data.loc[:,\"B365H\":\"WHA\"].isnull().all(axis=1).sum()\n# lets remove these records\nall_indexes = betting_data.loc[:,\"B365H\":\"WHA\"].isnull().all(axis=1)\nidx_to_del = all_indexes[all_indexes==True].index\n\nbetting_data = betting_data.drop(idx_to_del)\n\nbetting_data.loc[:,\"B365H\":\"WHA\"].isnull().all(axis=1).sum() # checking if we deleted the correct records\n# now we have 45 rows with atleast one missing value\nbetting_data.isnull().any(axis=1).sum() \nbetting_data.info()\n# lets fill them with mean values\nmean_dict = betting_data.loc[:,'B365H':].mean().to_dict()\nbetting_data.fillna(value=mean_dict, inplace=True)\n# No any missing values. Yay!\nbetting_data.isnull().any(axis=1).sum() \n\"\"\"\n<a id='eda'><\/a>\n## Exploratory Data Analysis\n\n<!-- ### Research Question 1 (Replace this header name!) -->\n### Does team playing home have high changes to win?\n\"\"\"\n# lets look at big picture. \nmatch_data[['home_team_goal','away_team_goal']].describe()\n\"\"\"\n> It is seen from the mean that home teams generally score higher than away team, in turn win the match  \n> Let's check the distribution of match outcomes\n\"\"\"\n# let's calculate the match outcome. This determines who won the match or it was a draw\ndef outcome(m):\n    if m.home_team_goal > m.away_team_goal:\n        return 'Home'\n    elif m.home_team_goal < m.away_team_goal:\n        return 'Away'\n    elif m.home_team_goal == m.away_team_goal:\n        return 'Draw'\nmatch_data['Outcome'] = match_data.apply(outcome, axis=1);\n# lets look what we got\nmatch_data.Outcome.value_counts().plot(kind='pie');\nmatch_data.Outcome.value_counts(normalize=True).round(4)*100\n\"\"\"\n> The above composition suggests that Home teams won around `46%` of matches, while away team won `29%`. A quarter of all matches were a draw.  \n> This asserts that playing at home boosts the chances of a team to win the match\n\"\"\"\n\"\"\"\nLet's explore this advantage. How exactly a team playing home is benefitted?  \n### Does a team scores higher playing at home in comparison to away locations?\n\"\"\"\n\"\"\"\nLet's see if this holds in team-wise comparison\n\"\"\"\n# calculating the mean goals a team scored when it played home and away\nteam_mean_home_scores = match_data.groupby(['home_team_api_id'])['home_team_goal'].mean()\nteam_mean_away_scores = match_data.groupby(['away_team_api_id'])['away_team_goal'].mean()\n# merging both dataset based on team id\nteam_scores_home_away = pd.concat([team_mean_home_scores,team_mean_away_scores], axis=1, join='inner')\n# lets examine the scores individually\nsns.distplot(team_scores_home_away.home_team_goal);\nsns.distplot(team_scores_home_away.away_team_goal);\n\"\"\"\n> Both the features follow normal distribution\n\"\"\"\n# comparing a team's mean goals when played home and away\nteam_scores_home_away['score_higher_at'] = team_scores_home_away.apply(outcome, axis=1)\nteam_scores_home_away.score_higher_at.value_counts(normalize=True).plot(kind='pie');\nteam_scores_home_away.score_higher_at.value_counts(normalize=True).round(4)*100\n\"\"\"\n> It was seen that `96%` teams have scored higher at home location in comparison to their away scores\n\"\"\"\nteam_scores_home_away.plot.scatter(x='home_team_goal',y='away_team_goal', alpha=0.2);\nteam_scores_home_away[['home_team_goal','away_team_goal']].corr()\n\"\"\"\n> There is a `strong correlation` between a team's home scoring and away scoring.\n\"\"\"\n\"\"\"\n### And How large this difference in score can be?\n\"\"\"\n# computing the score difference where teams have scored higher at home\nteam_scores_home_away['pos_score_diff'] = team_scores_home_away.home_team_goal - team_scores_home_away.away_team_goal\n# deleting negative differences\nteam_scores_home_away[team_scores_home_away.pos_score_diff<0]=np.NaN\nteam_scores_home_away.pos_score_diff.plot(kind='box');\n\"\"\"\n> It looks like the team can score `0.2` to `0.5` goals extra playing at home. However, in extreme cases, this can go high upto `0.8`\n\"\"\"\n\"\"\"\n### How do betting odds compare for home and away teams? \n\"\"\"\nbetting_data.describe()\n# lets look at the betting odds distribution from the three sources \n\nf, axes = plt.subplots(1, 2, figsize=(10, 5), sharey=True, sharex=True)\nsns.kdeplot(betting_data.BWH, shade=False, ax=axes[0]);\nsns.kdeplot(betting_data.B365H, shade=False, ax=axes[0]);\nsns.kdeplot(betting_data.WHH, shade=False, ax=axes[0]);\n\nsns.kdeplot(betting_data.BWA, shade=False, ax=axes[1]);\nsns.kdeplot(betting_data.B365A, shade=False, ax=axes[1]);\nsns.kdeplot(betting_data.WHA, shade=False, ax=axes[1]);\n\"\"\"\n> Looks like all the sources have similar odds, \n\"\"\"\n# lets check if the odds are in favour of home team or not for B365 odds\nbetting_data['B365Fav'] = betting_data['B365H'] < betting_data['B365A']\nbetting_data.B365Fav.value_counts(normalize=True).round(4)*100\n\"\"\"\n> For B365 scores, `70%` of matches have home odds less than away odds, which indicates home teams are favourable to win\n\"\"\"\n\"\"\"\n<a id='conclusions'><\/a>\n## Conclusions\n\nSo, the answer to our question - 'Is playing home advantageous to the soccer team?' is **Yes!!**. Below are our findings:  \n1. A team playing home has almost 1.5 time the chances to win the match.\n2. 96% out of 299 teams scored higher goals playing home than their respective mean away score.\n3. Teams can score upto 0.5 goals extra playing home\n4. There is a strong correlation between a team's home score and away scores. Generally this suggests that a team will score similar at both home and away conditions.\n5. 70% matches have home team as favourable (from odd scores)\n\"\"\"\n\"\"\"\n**Limitations**\n1. Current analysis consider *mean* values for calculation. However, *mean* can be effected by presence of outliers in dataset (some teams may have scored exceptionally high goals in some matches). We could have used *median* instead (which can be seen same for both home and away teams).\n2. The analysis performed does not has any statistical inference.\n3. This dataset does not contains data for all matches. (sample data) There could have been different number of samples available for a team's matches played at home and away.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7b6caf7c2fda98'}"}
{"id":"5641","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\nThis dataset gives information about us diabetes on Pima Indians.\n\nOutcome = 0; not diabetes.\nOutcome = 1; diabetes.\n\nFirstly, read dataset and save at \"data\" variable.\n\"\"\"\ndata = pd.read_csv(\"..\/input\/diabetes.csv\") \ndata.info() # gives info about our data\n\"\"\"\nAs we seen above, our dataset has 9 features (columns) and have 768 different data. Let's see correlation between of features and make its visualisation:\n\"\"\"\ndata.corr()\n#correlation map \nf,ax = plt.subplots(figsize=(15, 10)) #figsize; sets the size of boxes\nsns.heatmap(data.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)\n#annot = True; allows the use of correlation results in boxes\n#linewidth; thickness of line between boxes\n#fmt; sets the length of the decimal portion\nplt.show()\n\"\"\"\nIf correlation result is 1 or close to 1; we can say this features is revelant (positive revelant).\nIf correlation result is 0 or close to 0; we can say this features is not revelant.\nIf correlation result ise -1 or close to -1; we can say this features is revelant (negative revelant).\n\nBased on this information, if we look at results, we can comment about features.  For example; Age and Pregnancies can be revelant because its correlation results is 0,5. An other example; Insulin and Age can't be revelant because its correlation result is 0. \n\nWe can make more comment about this results.\n\"\"\"\nprint(data.head(20)) #Gives us top 20 of data.\nprint(data.tail(20)) #gives us last 20 of data.\n\"\"\"\nNow, we will see the histogram of our data. Firstly, we will view histogram of Age.\n\"\"\"\ndata.Age.plot(kind = 'hist',bins = 60,figsize = (15,15))\n# bins = number of bar in figure\n#x axis is Age. y axis is frequency of Age.\nplt.show()\n\"\"\"\nIf we look at histogram; there is the maximum data in the dataset is in the 21-23 age group. The minimum data in the dataset is in the ~65-66,~68-69,~72-73 and~80-82 ages and there is any data under ~22 years old and ~74-80 years old.\n\"\"\"\ndata.Outcome.plot(kind = 'hist',bins = 20,figsize = (5,5))\n# bins = number of bar in figure\n#x axis is Age. y axis is frequency of Age.\nplt.show()\n\"\"\"\nWe can see relevant of 2 features with scatter plot. For example; we can plot the relevant of glucose and insulin.\n\"\"\"\n# x = pregnancy, y = outcome\ndata.plot(kind='scatter', x='Glucose', y='Insulin',alpha = 0.5,color = 'red')\n#plt.scatter(data.Glucose,data.Insulin,alpha = 0.5,color = 'red') ## It is same as top row\nplt.xlabel('Glucose')              \nplt.ylabel('Insulin')\nplt.title('Glucose and Insulin Relevant')            \nplt.show()\n\"\"\"\nNow we can analyse the outcome. In out dataset; 0 is not diabetes patient and 1 is diabetes patient.\nAs we can see, in out dataset; have diabetes patient about 260 people and have not about 500 diabetes patient. \n\nThere is the describe of out dataset is in below.\n\"\"\"\ndata.describe()\n\"\"\"\nLet's analyse the describe results. \n\nThe minimum age is 21 and maximum age is 81.  We saw this in histogram chart.\nThe mean of our dataset is ~33.\n\nIn our dataset there is the maximum number of pregnancy is 17 and minimum number of pregnancy is 0. The mean of pregnancy is ~4.\n\nThe maximum glucose level is 199 and mean glucose level is ~120. \n\nThe maximum blood pressure level is 122, minimum blood pressure level is ~19 and mean blood pressure level is ~69. \n\n\"\"\"\n\"\"\"\nWe can make filters for see the data that we want.\n\"\"\"\nfilt = data.Age > data.Age.mean() #if da\nfiltered_data = data[filt]\nprint(filtered_data)\nx = data['Glucose']>185 \ndata[x]\ndata[np.logical_and(data['Glucose']>180, data['Outcome'] == 1 )] \n#we have find the people who has glucose level over 180 and have diabetes.\n\ndata[np.logical_and(data['Age']>40, data['Outcome'] == 0 )]\n#we have find the people who is over 40 years old and have not diabetes.\n\"\"\"\n**Conclusion**\nThis is my first work while I am learning Data Science. So I can make mistakes or I may have missings.\nPlease suggest me about this work. Thank you.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0a72f1600b21df'}"}
{"id":"133762","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\n\n\n# NOTE : Seaborn library is not updated in kaggle, hence I have attached\n# graph from my notebook.\n\"\"\"\n# Reading the CSV file:\n\"\"\"\ndf = pd.read_csv(\"..\/input\/credit-card-customers\/BankChurners.csv\")\ndf.head()\n\"\"\"\n# Pre-Processing:\n\"\"\"\n\"\"\"\n## 1. Dropping \"CLIENTNUM\" and last two Column:\n\"\"\"\ndf = df.drop([\"CLIENTNUM\", \"Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_2\", \"Naive_Bayes_Classifier_Attrition_Flag_Card_Category_Contacts_Count_12_mon_Dependent_count_Education_Level_Months_Inactive_12_mon_1\"], axis=1)\n\"\"\"\n## 2. There is not a single \"NULL\" value in the whole data set:\n\"\"\"\ndf.info()\n\"\"\"\n## 3. Printing all the unique value in a column with its total count:\n\"\"\"\nfor i in  df.columns:\n    print(df[i].value_counts())\n    print(\"----------------\")\n\"\"\"\n# Visualizing the data:\n\"\"\"\na=sns.FacetGrid(df, col=\"Education_Level\", row=\"Gender\")\na.map_dataframe(sns.countplot, x=\"Attrition_Flag\", hue=\"Attrition_Flag\", palette=\"tab10\")\na.fig.subplots_adjust(wspace=0.5, hspace=0.3)\na.set_xticklabels([\"\", \"\"])\na.add_legend()\n\"\"\"\n![image.png](attachment:image.png)\n\nfrom my notebook\n\"\"\"\n\"\"\"\nAfter plotting above graph, it is clearly seen that the maximum number of active members belong to \"Graduated\". And it decreases rapidly in the next phase i.e \"Post-Graduate\" and again in \"Doctorate\". The bank manager can use this data to give extra facilities to \"Graduated\" group and keep them as active members.\n\"\"\"\nfig = plt.figure(figsize=(12, 12))\n\nfig.add_subplot(211)\nsns.countplot(x=df[\"Customer_Age\"][df[\"Gender\"]==\"M\"], hue=df[\"Attrition_Flag\"])\nplt.text(x=5, y=150, s=\"FOR MALE\")\n\nfig.add_subplot(212)\nsns.countplot(x=df[\"Customer_Age\"][df[\"Gender\"]==\"F\"], hue=df[\"Attrition_Flag\"])\nplt.text(x=5, y=150, s=\"FOR FEMALE\")\n\nplt.show()\n\"\"\"\nThis plot shows that the number of active member increase as the age increase and later it decreases, that's an obvious thing. But above this, the number of existed members between that peak i.e age 35-55 in \"Female\" is greater than in \"Male\". Bank manager should pay extra attention to keep those \"Female\" accounts stick.\n\"\"\"\ndf[\"Income_Category\"].value_counts()\nfig = plt.figure(figsize=(10, 5))\nsns.histplot(data=df, x=\"Income_Category\", binwidth=1, hue=\"Attrition_Flag\")\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\nThis plot show that the probablity that member will stick to the bank is very very high in the group having income \n\"Less than $40K\" as compare to other. \n\nThe graph is fairly saturated and gives not much information.\n\"\"\"\nfig = plt.figure(figsize=(10, 5))\nsns.histplot(data=df, x=\"Card_Category\", binwidth=1, hue=\"Attrition_Flag\")\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\nThis plot also dont give much information. It just shows that most of the member have \"Blue\" i.e. the basic card only.\nBank should provide much more benefits of having premium cards to increase there subcriptions.\n\"\"\"\n\nfig = plt.figure(figsize=(10, 5))\nsns.histplot(data=df, x=\"Months_Inactive_12_mon\", binwidth=1, hue=\"Attrition_Flag\")\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\nThis plot can be very benefical, this graph shows that a person to be inactive is \"3 Months\" after which they get into active membership. The bank manager should give some cashbacks if the person uses card\/account atleast one time for consecutive for 2 monthns, it will decrease the time period of the member to be inactive from 3 months to 1-2 months at most and hence reducing the number. \n\"\"\"\n\"\"\"\n## CONCLUSION:\n\n#### The bank should give cashback regularly with extra features (*low interest*) for member having <$40K income and bank should provide more benefits to premium cards.\n\"\"\"\n\"\"\"\n# Pre-Processing 2:\n\"\"\"\n\"\"\"\n# 1. LabelEncoding:\n\"\"\"\ndf.info()\nfrom sklearn.preprocessing import LabelEncoder\n\nclass label_encoding:\n    def __init__(self, name):\n        self.name = name\n        self.le = LabelEncoder()\n        df[name] = self.le.fit_transform(df[name])\n        self.give_function()\n    \n    def inverse(self, i):\n        return self.le.inverse_transform([i])\n    \n    def transform(self, col):\n        return self.le.transform(col)\n        \n    def give_function(self):\n        return self.le\nle = {}\n\nfor val in df.columns:\n    if df[val].dtypes == 'object':\n         le[val] = label_encoding(val)\nfor val in le.keys():\n    for i in range(0, len(df[val].value_counts())):\n        print('The value for {} in {} is {}'.format(i, val, le[val].inverse(i).item()))\n    else:\n        print(\"---------------------- \\n \\n \")\n        \n\"\"\"\n# CORRELATION PLOT:\n\"\"\"\nfig = plt.figure(figsize=(18, 12))\nsns.heatmap(df.corr(), annot=True, annot_kws={\"size\": 9})\ncorr = {}\n\nfor idx1 in df.columns:\n    corr[idx1] = {'Positive': [], 'Negetive': []}\n    \n    for idx2 in df.columns:\n        if not idx1 == idx2:\n            if (df[idx1].corr(other=df[idx2])) > 0.25:\n                corr[idx1][\"Positive\"].append(idx2)\n                \n            \n            if (df[idx1].corr(other=df[idx2])) < -0.25:\n                corr[idx1][\"Negetive\"].append(idx2)\n                \n\"\"\"\nI have created a dict in which every columns have item that have positive and negetive with the same.\n\nEX:\n\"\"\"\ncorr[\"Attrition_Flag\"]\n\"\"\"\n## X and y split:\n\"\"\"\nX = df.iloc[:, 1:].values\ny = df.iloc[:, 0].values\n\nprint(X.shape, y.shape)\n\"\"\"\n## SOM:\n\"\"\"\nfrom sklearn.feature_selection import SelectKBest, chi2\n\nSOM = SelectKBest(chi2, k=8)\nX_new_som = SOM.fit_transform(X, y)\nX_new_som.shape\n\"\"\"\n## PCA:\n\"\"\"\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=8)\nX_new_pca = pca.fit_transform(X, y)\nX_new_pca.shape\n\"\"\"\n## Test Train split:\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX_train_pca, X_test_pca, y_train, y_test = train_test_split(X_new_pca, y, test_size=0.33, random_state=0)\nX_train_som, X_test_som, y_train, y_test = train_test_split(X_new_som, y, test_size=0.33, random_state=0)\nfrom sklearn import tree\n\nclf_pca = tree.DecisionTreeClassifier()\nclf_pca = clf_pca.fit(X_train_pca, y_train)\n\nclf_som = tree.DecisionTreeClassifier()\nclf_som = clf_som.fit(X_train_pca, y_train)\nfrom sklearn.metrics import accuracy_score\n\ny_pred_pca = clf_pca.predict(X_test_pca)\ny_pred_som = clf_som.predict(X_test_som)\n\naccuracy_score(y_test, y_pred_pca)\naccuracy_score(y_test, y_pred_som)\n\"\"\"\n### The PCA is more suitable in this senerio.\n\"\"\"\n\"\"\"\n# THANK YOU.\n## Leave a like \ud83d\udc4d.\n\n## PEACE :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f5f5c2ae572ada'}"}
{"id":"43547","text":"\"\"\"\n# Training EfficientNet based on \nhttps:\/\/www.kaggle.com\/khoongweihao\/efficientnets-quantile-regression-inference\n\"\"\"\n!pip install ..\/input\/kerasapplications\/keras-team-keras-applications-3b180cb -f .\/ --no-index\n!pip install ..\/input\/efficientnet\/efficientnet-1.1.0\/ -f .\/ --no-index\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport tensorflow as tf \nimport matplotlib.pyplot as plt\nimport keras\nimport pydicom\nimport tqdm\nimport cv2\nfrom tqdm.notebook import tqdm\nfrom tensorflow.keras import Model\nimport tensorflow.keras.backend as K\nimport tensorflow.keras.layers as L\nimport tensorflow.keras.models as M\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.metrics import mean_absolute_error\nfrom tensorflow_addons.optimizers import RectifiedAdam\nfrom tensorflow.keras.layers import (\n    Dense, Dropout, Activation, Flatten, Input, BatchNormalization, GlobalAveragePooling2D, Add, Conv2D, AveragePooling2D, \n    LeakyReLU, Concatenate \n)\nfrom tensorflow.keras.models import Model\nimport efficientnet.tfkeras as efn\nimport random\ndef seed_everything(seed=2020):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    \nseed_everything(42)\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.Session(config=config)\ntrain = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/train.csv') \nprint(train.shape)\ntrain.head()\ndef get_tab(df):\n    vector = [(df.Age.values[0] - 30) \/ 30] \n    \n    if df.Sex.values[0] == 'male':\n        vector.append(0)\n    else:\n        vector.append(1)\n    \n    if df.SmokingStatus.values[0] == 'Never smoked':\n        vector.extend([0,0])\n    elif df.SmokingStatus.values[0] == 'Ex-smoker':\n        vector.extend([1,1])\n    elif df.SmokingStatus.values[0] == 'Currently smokes':\n        vector.extend([0,1])\n    else:\n        vector.extend([1,0])\n    return np.array(vector) \n\n\nA = {} \nTAB = {} \nP = [] \nfor i, p in tqdm(enumerate(train.Patient.unique())):\n    sub = train.loc[train.Patient == p, :] \n    fvc = sub.FVC.values\n    weeks = sub.Weeks.values\n    c = np.vstack([weeks, np.ones(len(weeks))]).T\n    a, b = np.linalg.lstsq(c, fvc)[0]\n    \n    A[p] = a\n    TAB[p] = get_tab(sub)\n    P.append(p)\ndef get_img(path):\n    d = pydicom.dcmread(path)\n    return cv2.resize((d.pixel_array - d.RescaleIntercept) \/ (d.RescaleSlope * 1000), (512, 512))\nimport albumentations as Alb\n\naugs = {'Original': None,\n             'Blur': Alb.Blur(p=1.0),\n             #'MedianBlur': A.MedianBlur(blur_limit=5, p=1.0),\n             'GaussianBlur': Alb.GaussianBlur(p=1.0),\n             'MotionBlur': Alb.MotionBlur(p=1.0),\n        'GridDropout': Alb.GridDropout(p=1.0),\n        #'CenterCrop': A.CenterCrop(height=256, width=256, p=1.0),\n        #'RandomRotate90': A.RandomRotate90(p=1.0),\n        # 'ShiftScaleRotate': A.ShiftScaleRotate(p=1.0),\n        #'Rotate': A.Rotate()\n       }\n\nimage = get_img(f'..\/input\/osic-pulmonary-fibrosis-progression\/train\/ID00007637202177411956430\/9.dcm')\nprint(\"Real SHape = \",image.shape)\nfor ite,(key, aug) in enumerate(augs.items()):\n    if aug is not None:\n        image = aug(image=image)['image']\n        print(\"New Shape = \",image.shape)\n        plt.imshow(image)\nx, y = [], []\nfor p in tqdm(train.Patient.unique()):\n    try:\n        ldir = os.listdir(f'..\/input\/osic-pulmonary-fibrosis-progression-lungs-mask\/mask_noise\/mask_noise\/{p}\/')\n        numb = [float(i[:-4]) for i in ldir]\n        for i in ldir:\n            x.append(cv2.imread(f'..\/input\/osic-pulmonary-fibrosis-progression-lungs-mask\/mask_noise\/mask_noise\/{p}\/{i}', 0).mean())\n            y.append(float(i[:-4]) \/ max(numb))\n    except:\n        pass\nfrom tensorflow.keras.utils import Sequence\n\nclass IGenerator(Sequence):\n    BAD_ID = ['ID00011637202177653955184', 'ID00052637202186188008618']\n    def __init__(self, keys, a, tab, batch_size=32):\n        self.keys = [k for k in keys if k not in self.BAD_ID]\n        self.a = a\n        self.tab = tab\n        self.batch_size = batch_size\n        \n        self.train_data = {}\n        for p in train.Patient.unique():\n            ldir = os.listdir(f'..\/input\/osic-pulmonary-fibrosis-progression\/train\/{p}\/')\n            numb = [float(i[:-4]) for i in ldir]\n            self.train_data[p] = [i for i in os.listdir(f'..\/input\/osic-pulmonary-fibrosis-progression\/train\/{p}\/') \n                                  if int(i[:-4]) \/ len(ldir) < 0.8 and int(i[:-4]) \/ len(ldir) > 0.15]\n    \n    def __len__(self):\n        return 1000\n    \n    def __getitem__(self, idx):\n        x = []\n        a, tab = [], [] \n        keys = np.random.choice(self.keys, size = self.batch_size)\n        for k in keys:\n            try:\n                i = np.random.choice(self.train_data[k], size=1)[0]\n                image = get_img(f'..\/input\/osic-pulmonary-fibrosis-progression\/train\/{k}\/{i}')\n                for ite,(key, aug) in enumerate(augs.items()):\n                    if aug is not None:\n                        image = aug(image=image)['image']\n                        x.append(image)\n                        a.append(self.a[k])\n                        tab.append(self.tab[k])\n            except:\n                print(k, i)\n       \n        x,a,tab = np.array(x), np.array(a), np.array(tab)\n        #print(len(x),len(a),len(tab))\n        x = np.expand_dims(x, axis=-1)\n        return [x, tab] , a\ndef build_model(shape=(512,512,1), model_class=None):\n    inp = Input(shape=shape)\n    base = efn.EfficientNetB0(input_shape=shape,weights=None,include_top=False)\n    base.trainable = False\n    x = base(inp)\n    x = GlobalAveragePooling2D()(x)\n    inp2 = Input(shape=(4,))\n    x2 = tf.keras.layers.GaussianNoise(0.2)(inp2)\n    x = Concatenate()([x, x2]) \n    x = Dropout(0.5)(x) \n    x = Dense(1)(x)\n    model = Model([inp, inp2] , x)\n    return model\n\nmodel = build_model()\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='mae')\nfrom sklearn.model_selection import train_test_split \ntr_p, vl_p = train_test_split(P,shuffle=True,train_size= 0.8)\ner = tf.keras.callbacks.EarlyStopping(\n    monitor=\"val_loss\",\n    min_delta=1e-3,\n    patience=10,\n    verbose=0,\n    mode=\"auto\",\n    baseline=None,\n    restore_best_weights=True,\n)\n\ncheckpoint_path = \"..\/input\/output\/training_1\/weights{epoch:08d}.h5\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\n\n# Create a callback that saves the model's weights\ncp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n                                                 save_weights_only=True,\n                                                 verbose=1)\nmodel.fit_generator(IGenerator(keys=tr_p, \n                               a = A, \n                               tab = TAB), \n                    steps_per_epoch = 500,\n                    validation_data=IGenerator(keys=vl_p, \n                               a = A, \n                               tab = TAB),\n                    validation_steps = 40, \n                    callbacks = [er,cp_callback], \n                    epochs=1)\nfrom keras.applications import DenseNet121\ndensenet = DenseNet121(\n    weights= None,\n    include_top=False,\n    input_shape=(512,512,1)\n)\ndef build_densenet_model(densenet,shape=(512,512,1)):\n    inp = Input(shape=shape)\n    #base = efn.EfficientNetB0(input_shape=shape,weights=None,include_top=False)\n    densenet.trainable = False\n    x = densenet(inp)\n    x = GlobalAveragePooling2D()(x)\n    inp2 = Input(shape=(4,))\n    x2 = tf.keras.layers.GaussianNoise(0.2)(inp2)\n    x = Concatenate()([x, x2]) \n    x = Dropout(0.5)(x) \n    x = Dense(1)(x)\n    model = Model([inp, inp2] , x)\n    return model\nmodel = build_densenet_model(densenet)\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005), loss='mae')\ndensenet_path = \"..\/input\/output\/densenet\/weights{epoch:08d}.h5\"\nnew_cp = tf.keras.callbacks.ModelCheckpoint(filepath=densenet_path,\n                                                 save_weights_only=True,\n                                                 verbose=1)\nmodel.fit_generator(IGenerator(keys=tr_p, \n                               a = A, \n                               tab = TAB), \n                    steps_per_epoch = 500,\n                    validation_data=IGenerator(keys=vl_p, \n                               a = A, \n                               tab = TAB),\n                    validation_steps = 40, \n                    callbacks = [new_cp], \n                    epochs=1)","meta":"{'source': 'AI4Code', 'id': '504357a53b35df'}"}
{"id":"54628","text":"# 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 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\nimport matplotlib.pyplot as plt # this is used for the plot the graph \nimport seaborn as sns # used for plot interactive graph.\nimport matplotlib.pyplot as plt\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom pylab import rcParams\n# figure size in inches\n%matplotlib inline\ndf = pd.read_csv('\/kaggle\/input\/mobile-data-speeds-of-all-india-during-march-2018\/march18_myspeed.csv')\ndf.head()\ndf.info()\ndf.rename(columns={'Service Provider': 'Operator','Data Speed(Mbps)': 'Throughput'},inplace=True)\ndf.head()\ndf.groupby('Technology')['Throughput'].max().sort_index()\n#reference from https:\/\/www.kaggle.com\/anuragk240\/visualising-data-speeds\ncolumns = ['Technology', 'Test_type', 'Operator', 'LSA']\nfor c in columns:\n    v = df[c].unique()\n    g = df.groupby(by=c)[c].count().sort_values(ascending=True)\n    r = np.arange(len(v))\n    print(g.head)\n    plt.figure(figsize = (6, len(v)\/2 +1))\n    plt.barh(y = r, width = g.head(len(v)))\n    total = sum(g.head(len(v)))\n    print(total)\n    for (i, u) in enumerate(g.head(len(v))):\n        plt.text(x = u + 0.2, y = i - 0.08, s = str(round(u\/total*100, 2))+'%', color = 'green', fontweight = 'bold')\n    plt.margins(x = 0.2)\n    plt.yticks(r, g.index)\n    plt.show()\n\"\"\"\n# Throughput Analysis across the Telecom Circles\n\n* Maximum upload and download throughput recorded was at Himachal Pradesh circle\n* Minimum upload and download throughput recorded is 0 Mbps\n* Delhi has very low average throughput in upload\n* North East has very low average throughput in download\n\"\"\"\nrcParams['figure.figsize'] = 16, 8\nwidth = 0.25 \n# Plotting the bars\nx = df.groupby('LSA')['Throughput'].mean().sort_values()\nx_indexes = np.arange(len(x.index))\ny = df[df[\"Test_type\"]==\"Upload\"].groupby('LSA')['Throughput'].mean().sort_values()\nz = df[df[\"Test_type\"]==\"Download\"].groupby('LSA')['Throughput'].mean().sort_values()\nplt.bar(x_indexes-width,y, width,label=\"Average Upload\") \nplt.bar(y.index,z, width,label=\"Average Download\") \nplt.bar(x_indexes+width,x, width,label=\"Average Combined\") \nplt.title(\"Throughput accross Circles\")\nplt.ylabel('Throughput in Mbps')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.show()\nfig = plt.figure()\nrcParams['figure.figsize'] = 16, 8\nplt.subplot(2, 2, 1)\nwidth = 0.25 \n# Plotting the bars\nx = df[df[\"Test_type\"]==\"Download\"].groupby('LSA')['Throughput'].max().sort_values()\nx_indexes = np.arange(len(x.index))\ny = df[df[\"Test_type\"]==\"Download\"].groupby('LSA')['Throughput'].mean().sort_values()\nplt.title(\"Download Throughput accross country\")\nplt.bar(y.index,y, width,label=\"Average\") \nplt.bar(x_indexes+width,x, width,label=\"Maximum\") \nplt.ylabel('Throughput in Mbps')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.subplot(2, 2, 2)\nu = df[df[\"Test_type\"]==\"Upload\"].groupby('LSA')['Throughput'].max().sort_values()\nx_indexes = np.arange(len(u.index))\nv = df[df[\"Test_type\"]==\"Upload\"].groupby('LSA')['Throughput'].mean().sort_values()\nplt.title(\"Upload Throughput accross country\")\nplt.bar(v.index,v, width,label=\"Average\") \nplt.bar(x_indexes+width,u, width,label=\"Maximum\") \nplt.ylabel('Throughput in Mbps')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\n\"\"\"\n# Data across the Telecom circles\n\"\"\"\n#download data\nx,y\n#upload data\nu,v\nfig = plt.figure()\nrcParams['figure.figsize'] = 16, 8\nwidth = 0.25 \n# Plotting the bars\n\ny = df[df[\"Test_type\"]==\"Download\"].groupby('Operator')['Throughput'].max().sort_values()\nz = df[df[\"Test_type\"]==\"Upload\"].groupby('Operator')['Throughput'].max().sort_values()\nx_indexes = np.arange(len(y.index))\nplt.title(\"Throughput accross country\")\nplt.bar(y.index,y, width,label=\"Maximum Download\") \nplt.bar(x_indexes+width,z, width,label=\"Maximum Upload\") \nplt.ylabel('Throughput in Mbps')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\n\"\"\"\n# Operator throughput analysis\n\n* Maximum throughput accross all the circles is maintained by Jio\n* JIO has highest throughput for 4G networks as well\n\"\"\"\nfig = plt.figure()\nrcParams['figure.figsize'] = 16, 8\nwidth = 0.25 \n# Plotting the bars\ny = df[df[\"Technology\"]==\"4G\"].groupby('Operator')['Throughput'].max().sort_values()\nx_indexes = np.arange(len(y.index))\nz = df[df[\"Technology\"]==\"4G\"].groupby('Operator')['Throughput'].mean().sort_values()\nplt.title(\"4G Throughput accross country \/ Operator\")\nplt.bar(y.index,y, width,label=\"Maximum \") \nplt.bar(x_indexes+width,z, width,label=\"Average\") \nplt.ylabel('Throughput in Mbps')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\ndef float_signal_strength(x):\n    if x == \"na\":\n        return np.NaN\n    else:\n        return float(x)\ndf[\"Signal_strength\"] = df[\"Signal_strength\"].apply(lambda x: float_signal_strength(x))\ndf.info()\ndf[\"Signal_strength\"].fillna(df[\"Signal_strength\"].mean(),inplace=True)\n\"\"\"\n# Signal strength vs Throughput\n\"\"\"\n#reference from https:\/\/www.kaggle.com\/anuragk240\/visualising-data-speeds\n\nimport matplotlib.colors as colors\n\nfig = plt.figure()\nrcParams['figure.figsize'] = 16, 8\nx = df['Signal_strength']\ny = df['Throughput']\nplt.hist2d(x, y, bins = 40, norm=colors.LogNorm())\nplt.ylabel('Data Speed(Mbps)')\nplt.xlabel('Signal_strength')\nplt.style.use('seaborn-pastel')\nplt.xticks(rotation = 90)\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '649e251910abb1'}"}
{"id":"27424","text":"\"\"\"\n# Spam Detection\n\"\"\"\n\"\"\"\n## Use case\nYou were recently hired in start up company and you were asked to build a system to identify spam emails.\n\n\"\"\"\n\"\"\"\n## Importing Libraries\n\"\"\"\n#Import libs\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as sns\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,AdaBoostClassifier,ExtraTreesClassifier\nfrom collections import Counter\nimport string\nimport warnings\nwarnings.filterwarnings('ignore')\nimport warnings\nwarnings.filterwarnings('ignore')\ndf=pd.read_csv('..\/input\/lingspam-dataset\/messages.csv')\ndf.head()\n# converting all messages to lower case\n\ndf['message'] = df['message'].str.lower()\n# check data once \ndf.head()\n\"\"\"\n## Data Cleansing\n\"\"\"\n# checing null values \ndf.isnull().sum()\n\"\"\"\nFrom here we can observe that data is missing here .\n\"\"\"\ndf.fillna(df['subject'].mode().values[0],inplace=True)\n# let's once again \ndf.isnull().sum()\n\"\"\"\nNow it's looking perfect and move on to next step's .\n\"\"\"\n\"\"\"\n## Feature Engineering \n\"\"\"\n\"\"\"\nTo get clarity about mail i'm going to merge both subject and message .\n\"\"\"\ndf['sub_mssg']=df['subject']+df['message']\ndf.head()\ndf['sub_mssg'].describe()\ndf['length']=df['sub_mssg'].apply(len)\ndf.head()\n#now i'm going to drop un-necessary features \ndf.drop('subject',axis=1,inplace=True)\n# check it once \ndf.head()\n\"\"\"\n## Data Visualization \n\"\"\"\nlb=df['label'].value_counts().index.tolist()\nval=df['label'].value_counts().values.tolist()\nexp=(0.025,0)\nclr=('orange','blue')\nplt.figure(figsize=(10,5),dpi=140)\nplt.pie(x=val,explode=exp,labels=lb,colors=clr,autopct='%2.0f%%',pctdistance=0.5, shadow=True,radius=0.9)\nplt.legend([\"0 = NO SPAM\",'1 = SPAM'])\nplt.show()\n\"\"\"\n## Preprocessing Email Messages :\n\"\"\"\ndf['message'][0]\nimport re\ndef decontact(phrase):\n    # specific\n    phrase = re.sub(r\"won't\", \"will not\", phrase)\n    phrase = re.sub(r\"can\\'t\", \"can not\", phrase)\n\n    # general\n    phrase = re.sub(r\"n\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'re\", \" are\", phrase)\n    phrase = re.sub(r\"\\'s\", \" is\", phrase)\n    phrase = re.sub(r\"\\'d\", \" would\", phrase)\n    phrase = re.sub(r\"\\'ll\", \" will\", phrase)\n    phrase = re.sub(r\"\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'ve\", \" have\", phrase)\n    phrase = re.sub(r\"\\'m\", \" am\", phrase)\n    return phrase\nmssg=decontact(df['message'][70])\nmssg\n#REPLACING NUMBERS\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'\\d+(\\.\\d+)?', 'numbers')\ndf['sub_mssg'][0]\n#CONVRTING EVERYTHING TO LOWERCASE\ndf['sub_mssg']=df['sub_mssg'].str.lower()\n#REPLACING NEXT LINES BY 'WHITE SPACE'\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'\\n',\" \") \n# REPLACING EMAIL IDs BY 'MAILID'\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'^.+@[^\\.].*\\.[a-z]{2,}$','MailID')\n# REPLACING URLs  BY 'Links'\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'^http\\:\/\/[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(\/\\S*)?$','Links')\n# REPLACING CURRENCY SIGNS BY 'MONEY'\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'\u00a3|\\$', 'Money')\n# REPLACING LARGE WHITE SPACE BY SINGLE WHITE SPACE\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'\\s+', ' ')\n\n# REPLACING LEADING AND TRAILING WHITE SPACE BY SINGLE WHITE SPACE\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'^\\s+|\\s+?$', '')\n#REPLACING CONTACT NUMBERS\ndf['sub_mssg']=df['sub_mssg'].str.replace(r'^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$','contact number')\n#REPLACING SPECIAL CHARACTERS  BY WHITE SPACE \ndf['sub_mssg']=df['sub_mssg'].str.replace(r\"[^a-zA-Z0-9]+\", \" \")\n#CONVRTING EVERYTHING TO LOWERCASE\ndf['message']=df['message'].str.lower()\n#REPLACING NEXT LINES BY 'WHITE SPACE'\ndf['message']=df['message'].str.replace(r'\\n',\" \") \n# REPLACING EMAIL IDs BY 'MAILID'\ndf['message']=df['message'].str.replace(r'^.+@[^\\.].*\\.[a-z]{2,}$','MailID')\n# REPLACING URLs  BY 'Links'\ndf['message']=df['message'].str.replace(r'^http\\:\/\/[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(\/\\S*)?$','Links')\n# REPLACING CURRENCY SIGNS BY 'MONEY'\ndf['message']=df['message'].str.replace(r'\u00a3|\\$', 'Money')\n# REPLACING LARGE WHITE SPACE BY SINGLE WHITE SPACE\ndf['message']=df['message'].str.replace(r'\\s+', ' ')\n\n# REPLACING LEADING AND TRAILING WHITE SPACE BY SINGLE WHITE SPACE\ndf['message']=df['message'].str.replace(r'^\\s+|\\s+?$', '')\n#REPLACING CONTACT NUMBERS\ndf['message']=df['message'].str.replace(r'^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$','contact number')\n#REPLACING SPECIAL CHARACTERS  BY WHITE SPACE \ndf['message']=df['message'].str.replace(r\"[^a-zA-Z0-9]+\", \" \")\ndf['sub_mssg'][0]\n\"\"\"\nNow message looking perfect .\n\"\"\"\ndf.head()\nfrom tqdm import tqdm\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize, sent_tokenize\n# removing stopwords \nstop = stopwords.words('english')\ndf['Cleaned_Text'] = df['sub_mssg'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))\n\ndf.head()\ndf.drop('message',axis=1,inplace=True)\ndf.drop('sub_mssg',axis=1,inplace=True)\ndf.head()\ndf.isnull().sum()\ndf['lgth_clean']=df['Cleaned_Text'].apply(len)\ndf.head()\noriginal_length=sum(df['length'])\nafter_cleaning=sum(df['lgth_clean'])\nprint(\"original_length\",original_length)\nprint('after_cleaning',after_cleaning)\n\"\"\"\n## Training Model\n\"\"\"\n# 1. Convert text into vectors using TF-IDF\n# 2. Instantiate MultinomialNB classifier\n# 3. Split feature and label\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nimport warnings\nfrom sklearn.pipeline import Pipeline\n\"\"\"\n## Logistic Regression\n\"\"\"\ntvec = TfidfVectorizer()\nlr = LogisticRegression(solver = \"lbfgs\")\nX = df.Cleaned_Text\nY = df.label\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.1, random_state = 225,stratify=Y)\nmodel = Pipeline([('vectorizer',tvec),('classifier',lr)])\n\nmodel.fit(X_train,Y_train)\n\n\nfrom sklearn.metrics import confusion_matrix\n\ny_pred = model.predict(X_test)\n\nconfusion_matrix(y_pred,Y_test)\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\n\"\"\"\n## KNeighbors Classifier\n\"\"\"\nknc = KNeighborsClassifier()\nmodel_1 = Pipeline([('vectorizer',tvec),('classifier',knc)])\nmodel_1.fit(X_train,Y_train)\n\n\ny_pred = model_1.predict(X_test)\n\nprint(confusion_matrix(y_pred,Y_test))\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\"\"\"\n## Ada Boost Classifier\n\"\"\"\nabc = AdaBoostClassifier()\nmodel_3 = Pipeline([('vectorizer',tvec),('classifier',abc)])\nmodel_3.fit(X_train,Y_train)\n\n\ny_pred = model_3.predict(X_test)\n\nprint(confusion_matrix(y_pred,Y_test))\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\"\"\"\n## Naive Bayes\n\"\"\"\nmnb = MultinomialNB()\nmodel_5 = Pipeline([('vectorizer',tvec),('classifier',mnb)])\nmodel_5.fit(X_train,Y_train)\n\n\ny_pred = model_5.predict(X_test)\n\nprint(confusion_matrix(y_pred,Y_test))\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\"\"\"\n## Gradient Boosting Classifier\n\"\"\"\ngbc = GradientBoostingClassifier()\nmodel_6= Pipeline([('vectorizer',tvec),('classifier',gbc)])\nmodel_6.fit(X_train,Y_train)\n\n\ny_pred = model_6.predict(X_test)\nprint(confusion_matrix(y_pred,Y_test))\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\"\"\"\n## Random Forest Classifier\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier as RFC\nrfc = RFC(random_state=42)\nmodel_7 = Pipeline([('vectorizer',tvec),('classifier',rfc)])\n\nmodel_7.fit(X_train,Y_train)\n\ny_pred = model_7.predict(X_test)\nprint(confusion_matrix(y_pred,Y_test))\nprint(\"Accuracy : \", accuracy_score(y_pred,Y_test))\nprint(\"Precision : \", precision_score(y_pred,Y_test, average = 'weighted'))\nprint(\"Recall : \", recall_score(y_pred,Y_test, average = 'weighted'))\n\"\"\"\nFrom here we can observe that Random forest classifier working well compared to all other algorithms\n\"\"\"\n\"\"\"\n## Testing Model\n\"\"\"\nresult=model_7.predict(['your microsoft account has been compromised ,you must update before or else your account going to close click to update'])\nresult\nresult=model_7.predict(['Today we want to inform you that the application period for 15.000 free Udacity Scholarships in Data Science is now open! Please apply by November 16th, 2020 via https:\/\/www.udacity.com\/bertelsmann-tech-scholarships.'])\nresult\n\"\"\"\nHere 0 is spam and 1 is normal message.\n\"\"\"\n\"\"\"\n#  EOF DONE CLASSIFICATION OF SPAM CLASSIFICATION \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '327935e8faa915'}"}
{"id":"83157","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom scipy import stats\nfrom scipy.stats import norm, skew\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\nfrom sklearn.metrics import mean_squared_error, make_scorer\nfrom sklearn.linear_model import LinearRegression, RidgeCV, LassoCV, ElasticNetCV\nfrom sklearn.linear_model import BayesianRidge, LassoLarsIC\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import RandomForestRegressor,  GradientBoostingRegressor\nfrom sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n%matplotlib inline\n# get data\ntrain = pd.read_csv(\"..\/input\/train.csv\")\ntest = pd.read_csv(\"..\/input\/test.csv\")\n# sample = pd.read_csv(\"..\/input\/sample_submission.csv\")\nprint(\"train.csv shape: \" + str(train.shape))\nprint(\"test.csv shape: \" + str(test.shape))\n# print(\"sample.csv shape: \" + str(sample.shape))\ntrain.head()\ntrain.SalePrice.describe()\n# get a overview of the SalePrice distribution\nsns.distplot(train.SalePrice);\n# look at some general outliers\nplt.scatter(train.GrLivArea, train.SalePrice, c=\"blue\", s=2)\nplt.title(\"Looking for outliers\")\nplt.xlabel(\"GrLivArea\")\nplt.ylabel(\"SalePrice\")\nplt.show()\n# remove outliers, i.e. GrLivArea > 4000\ntrain = train.drop(train[(train.GrLivArea > 4000) & (train.SalePrice < 300000)].index)\nplt.scatter(train.GrLivArea, train.SalePrice, c=\"blue\", s=2);\nplt.title(\"Looking for outliers\")\nplt.xlabel(\"GrLivArea\")\nplt.ylabel(\"SalePrice\")\nplt.show()\n# log transform the SalePrice, so that the bigger values does not have a to big impact\n# on the smaller ones\n#train = train.drop(train.loc[train.Electrical.isnull()].index)\n# save the \"Id\" column\ntrain_ID = train[\"Id\"]\ntest_ID = test[\"Id\"]\n\n# drop the \"Id\" column\ntrain.drop(\"Id\", axis=1, inplace=True)\ntest.drop(\"Id\", axis=1, inplace=True)\n# build a correlation matrix to get an idea of the important or relevant categories\ncorrmat = train.corr()\nplt.subplots(figsize=(12,9))\nsns.heatmap(corrmat, square=True);\ncols = corrmat.nlargest(15, \"SalePrice\")[\"SalePrice\"].index\nvalues = corrmat.nlargest(15, \"SalePrice\")[\"SalePrice\"].values\nhigh_corrmat = np.corrcoef(train[cols].values.T)\nf, ax = plt.subplots(figsize=(10,8))\nsns.set(font_scale=1.25)\nhigh_heatmap = sns.heatmap(high_corrmat, cbar=True, annot=True, fmt=\".2f\",\n                          annot_kws={\"size\": 10}, square=True,\n                          yticklabels=cols.values, xticklabels=cols.values)\nhigh_cor = pd.concat([pd.Series(cols), pd.Series(values)], keys=[\"index\", \"value\"], axis=1)\nprint(high_cor)\n\"\"\"\n* We can see now which data could be relevant\n* Furthermore you can see that there is some missing data...\n\"\"\"\ntrain.SalePrice = np.log1p(train.SalePrice)\nntrain = train.shape[0]\nntest = test.shape[0]\ny_train = train.SalePrice.values\nall_data = pd.concat((train, test)).reset_index(drop=True)\nall_data.drop(['SalePrice'], axis=1, inplace=True)\nprint(\"all_data size is : {}\".format(all_data.shape))\n# find the missing data\ntotal_na = all_data.isnull().sum()\ntotal_na = total_na.drop(total_na[total_na == 0].index).sort_values(ascending=False)\nmissing = pd.DataFrame({\"Total Missing data\": total_na})\nmissing.head(20)\n\"\"\"\nSo fill in the missing gaps of the categories...\n\"\"\"\n# handel missing values for features where median\/mean or most common value does not\n# make sense\n\n# Alley: NA for Alley means \"no alley access\"\nall_data.loc[:, \"Alley\"] = all_data.loc[:, \"Alley\"].fillna(\"NoAl\")\n\n# BedroomAbvGr: NA for Bedrooms above ground means 0 Bedrooms\nall_data.loc[:, \"BedroomAbvGr\"] = all_data.loc[:, \"BedroomAbvGr\"].fillna(0)\n\n# BsmtXXX: NA for basement features means there is \"no basement\"\nall_data.loc[:, \"BsmtQual\"] = all_data.loc[:, \"BsmtQual\"].fillna(\"NoBa\")\nall_data.loc[:, \"BsmtCond\"] = all_data.loc[:, \"BsmtCond\"].fillna(\"NoBa\")\nall_data.loc[:, \"BsmtExposure\"] = all_data.loc[:, \"BsmtExposure\"].fillna(\"NoBa\")\nall_data.loc[:, \"BsmtFinType1\"] = all_data.loc[:, \"BsmtFinType1\"].fillna(\"NoBa\")\nall_data.loc[:, \"BsmtFinType2\"] = all_data.loc[:, \"BsmtFinType2\"].fillna(\"NoBa\")\n\n# Electrical: NA means no electricity\n# Electrical: Should be dropped\n#train = train.drop(train.loc[train.Electrical.isnull()].index)\nall_data.loc[:, \"Electrical\"] = all_data.loc[:, \"Electrical\"].fillna(\"NoEL\")\n\n# Fence: NA means \"no fence\"\nall_data.loc[:, \"Fence\"] = all_data.loc[:, \"Fence\"].fillna(\"NoFe\")\n\n# FireplaceQu: data description says NA means \"no fireplace\"\nall_data.loc[:, \"FireplaceQu\"] = all_data.loc[:, \"FireplaceQu\"].fillna(\"NoFi\")\n\n# GarageType etc: data description says NA for garage features is \"no garage\"\nall_data.loc[:, \"GarageType\"] = all_data.loc[:, \"GarageType\"].fillna(\"NoGa\")\nall_data.loc[:, \"GarageFinish\"] = all_data.loc[:, \"GarageFinish\"].fillna(\"NoGa\")\nall_data.loc[:, \"GarageQual\"] = all_data.loc[:, \"GarageQual\"].fillna(\"NoGa\")\nall_data.loc[:, \"GarageCond\"] = all_data.loc[:, \"GarageCond\"].fillna(\"NoGa\")\n# use for GarageYrBlt the average\n#train.loc[:, \"GarageArea\"] = train.loc[:, \"GarageArea\"].fillna(0)\n#train.loc[:, \"GarageCars\"] = train.loc[:, \"GarageCars\"].fillna(0)\n\n#\n# LotFrontage : NA most likely means no lot frontage\n# to much data missing, try mean()\n#train.loc[:, \"LotFrontage\"] = train.loc[:, \"LotFrontage\"].fillna(0)\n#\n\n# MasVnrType: NA means no veneer\nall_data.loc[:, \"MasVnrType\"] = all_data.loc[:, \"MasVnrType\"].fillna(\"None\")\nall_data.loc[:, \"MasVnrArea\"] = all_data.loc[:, \"MasVnrArea\"].fillna(0)\n\n# MiscFeature: NA means \"no misc feature\"\nall_data.loc[:, \"MiscFeature\"] = all_data.loc[:, \"MiscFeature\"].fillna(\"NoFe\")\n#train.loc[:, \"MiscVal\"] = train.loc[:, \"MiscVal\"].fillna(0)\n\n# PoolQC: NA means \"no pool\"\nall_data.loc[:, \"PoolQC\"] = all_data.loc[:, \"PoolQC\"].fillna(\"NoPo\")\n#train.loc[:, \"PoolArea\"] = train.loc[:, \"PoolArea\"].fillna(0)\n#Some numerical features are actually really categories\nall_data = all_data.replace({\"MSSubClass\" : {20 : \"SC20\", 30 : \"SC30\", 40 : \"SC40\", 45 : \"SC45\", \n                                       50 : \"SC50\", 60 : \"SC60\", 70 : \"SC70\", 75 : \"SC75\", \n                                       80 : \"SC80\", 85 : \"SC85\", 90 : \"SC90\", 120 : \"SC120\", \n                                       150 : \"SC150\", 160 : \"SC160\", 180 : \"SC180\", 190 : \"SC190\"},\n                       \"MoSold\" : {1 : \"Jan\", 2 : \"Feb\", 3 : \"Mar\", 4 : \"Apr\",\n                                   5 : \"May\", 6 : \"Jun\", 7 : \"Jul\", 8 : \"Aug\",\n                                   9 : \"Sep\", 10 : \"Oct\", 11 : \"Nov\", 12 : \"Dec\"},\n                       \n                      })\n# all_data.MSSubClass = all_data.MSSubClass.apply(str)\nall_data.OverallCond = all_data.OverallCond.astype(str)\n# all_data.MoSold = all_data.MoSold.astype(str)\nall_data.YrSold = all_data.YrSold.astype(str)\n# encode some categorical features as ordered numbers when there is information in\n# the order\nall_data = all_data.replace({#\"Alley\" : {\"Grvl\" : 1, \"Pave\" : 2},\n                       \"BsmtCond\": {\"NoBa\": 0, \"Po\": 1, \"Fa\": 2, \"TA\": 3, \"Gd\": 4,\n                                   \"Ex\": 5},\n                       \"BsmtExposure\": {\"NoBa\": 0, \"Mn\": 1, \"Av\": 2, \"Gd\": 3},\n                       \"BsmtFinType1\" : {\"NoBa\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\n                                        \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\n                       \"BsmtFinType2\" : {\"NoBa\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\n                                        \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\n                       \"BsmtQual\" : {\"NoBa\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\" : 4,\n                                    \"Ex\" : 5},\n                       \n                       \"ExterCond\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\n                       \"ExterQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\n                       # try both\n                       \"Functional\" : {\"Sal\" : 1, \"Sev\" : 2, \"Maj2\" : 3, \"Maj1\" : 4, \"Mod\": 5, \n                                       \"Min2\" : 6, \"Min1\" : 7, \"Typ\" : 8},\n                       \n                       \"GarageCond\" : {\"NoGa\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\n                       \"GarageQual\" : {\"NoGa\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\n                       \n                       \"HeatingQC\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\n                       \n                       \"KitchenQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\n                       # try both\n                       \"LandSlope\" : {\"Sev\" : 1, \"Mod\" : 2, \"Gtl\" : 3},\n                       # try both\n                       \"LotShape\" : {\"IR3\" : 1, \"IR2\" : 2, \"IR1\" : 3, \"Reg\" : 4},\n                       \n                       #\"PavedDrive\" : {\"N\" : 0, \"P\" : 1, \"Y\" : 2},\n                       \n                       \"PoolQC\" : {\"NoPo\" : 0, \"Fa\" : 1, \"TA\" : 2, \"Gd\" : 3, \"Ex\" : 4},\n                       \n                       #\"Street\" : {\"Grvl\" : 1, \"Pave\" : 2},\n                       # try both\n                       \"Utilities\" : {\"ELO\" : 1, \"NoSeWa\" : 2, \"NoSewr\" : 3, \"AllPub\" : 4}\n                            })\n# differentiate numerical and categorical features\ncat_features = all_data.select_dtypes(include=[\"object\"]).columns\nnum_features = all_data.select_dtypes(exclude=[\"object\"]).columns\n#num_features = num_features.drop(\"SalePrice\")\nprint(\"Numerical features: \" + str(len(num_features)))\nprint(\"Categorical features: \" + str(len(cat_features)))\nall_data_num = all_data[num_features]\nall_data_cat = all_data[cat_features]\nprint(\"NAs for numerical features in train : \" + str(all_data_num.isnull().values.sum()))\nall_data_num = all_data_num.fillna(all_data_num.mean())\nprint(\"Remaining NAs for numerical features in train : \" + str(all_data_num.isnull().values.sum()))\n# log transform of the skewed numerical features to lessen impact the outliers\nskewness = all_data_num.apply(lambda x: skew(x))\nskewness = skewness[abs(skewness) > 0.5]\nprint(str(skewness.shape[0]) + \" skewed numerical features to log transform\")\nskewed_features = skewness.index\nall_data_num[skewed_features] = np.log1p(all_data_num[skewed_features])\n# create dummy features for categorical values via one-hot encoding\nprint(\"NAs for categorical features in train : \" + str(all_data_cat.isnull().values.sum()))\nall_data_cat = pd.get_dummies(all_data_cat)\nprint(\"Remaining NAs for categorical features in train : \" + str(all_data_cat.isnull().values.sum()))\nall_data = pd.get_dummies(all_data)\nprint(all_data.shape)\ntrain = all_data[:ntrain]\ntest = all_data[ntrain:]\n\"\"\"\nModelling\n\"\"\"\n# join numerical and categorical features\nall_data = pd.concat([all_data_num, all_data_cat], axis=1)\nprint(\"New number of features : \" + str(all_data.shape[1]))\ntrain = all_data[:ntrain]\ntest = all_data[ntrain:]\n# # Partition the dataset in train + validation sets\n# X_train, X_test, y_train, y_test = train_test_split(train.values, y_train, test_size = 0.3, random_state = 0)\n# print(\"X_train : \" + str(X_train.shape))\n# print(\"X_test : \" + str(X_test.shape))\n# print(\"y_train : \" + str(y_train.shape))\n# print(\"y_test : \" + str(y_test.shape))\nprint(len(train))\nprint(len(y_train))\n# stdSc = StandardScaler()\n# train.values.loc[:, num_features] = stdSc.fit_transform(train.values.loc[:, num_features])\n# X_test.loc[:, num_features] = stdSc.transform(X_test.loc[:, num_features])\nscorer = make_scorer(mean_squared_error, greater_is_better=False)\n\ndef rmse_cv_train(model):\n    rmse = np.sqrt(-cross_val_score(model, train.values, y_train, scoring=scorer, cv=10))\n    return(rmse)\nl1 = [0.00001, 0.00003, 0.00006, 0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1, 0.3, 0.6, 1, 3, 6, 10, 30, 60, 100]\nl2 = np.arange(100) + 1\nl3 = l2 * 0.1\nl4 = l2 * 0.01\nl5 = l2 * 0.001\nl6 = l2 * 0.0001\nl7 = l2 * 0.00001\nl8 = l2 * 0.000001\nprint(l3)\nl2_1 = np.arange(1000) + 1\nl3_1 = l2_1 * 0.1\nl4_1 = l2_1 * 0.01\n\nridge = RidgeCV(alphas = [5.63])\nridge.fit(train.values, y_train)\nalpha = ridge.alpha_\nprint(\"Best alpha: \", alpha)\nprint(\"Ridge RMSE on Training set :\", rmse_cv_train(ridge).mean())\nlasso = LassoCV(alphas = [0.00031], max_iter=50000, cv=10)\nlasso.fit(train.values, y_train)\n# alpha = lasso.alpha_\n# print(\"Best alpha: \", alpha)\nprint(\"Lasso RMSE on Training set: \", rmse_cv_train(lasso).mean())\n# 4* ElasticNet\nelasticNet = ElasticNetCV(l1_ratio = [0.1, 0.3, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1],\n                          alphas = [0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, \n                                    0.01, 0.03, 0.06, 0.1, 0.3, 0.6, 1, 3, 6], \n                          max_iter = 50000, cv = 10)\nelasticNet.fit(train.values, y_train)\nalpha = elasticNet.alpha_\nratio = elasticNet.l1_ratio_\nprint(\"Best l1_ratio :\", ratio)\nprint(\"Best alpha :\", alpha )\n\nprint(\"Try again for more precision with l1_ratio centered around \" + str(ratio))\nelasticNet = ElasticNetCV(l1_ratio = [ratio * .85, ratio * .9, ratio * .95, ratio, ratio * 1.05, ratio * 1.1, ratio * 1.15],\n                          alphas = [0.0001, 0.0003, 0.0006, 0.001, 0.003, 0.006, 0.01, 0.03, 0.06, 0.1, 0.3, 0.6, 1, 3, 6], \n                          max_iter = 50000, cv = 10)\nelasticNet.fit(train.values, y_train)\nif (elasticNet.l1_ratio_ > 1):\n    elasticNet.l1_ratio_ = 1    \nalpha = elasticNet.alpha_\nratio = elasticNet.l1_ratio_\nprint(\"Best l1_ratio :\", ratio)\nprint(\"Best alpha :\", alpha )\n\nprint(\"Now try again for more precision on alpha, with l1_ratio fixed at \" + str(ratio) + \n      \" and alpha centered around \" + str(alpha))\nelasticNet = ElasticNetCV(l1_ratio = ratio,\n                          alphas = [alpha * .6, alpha * .65, alpha * .7, alpha * .75, alpha * .8, alpha * .85, alpha * .9, \n                                    alpha * .95, alpha, alpha * 1.05, alpha * 1.1, alpha * 1.15, alpha * 1.25, alpha * 1.3, \n                                    alpha * 1.35, alpha * 1.4], \n                          max_iter = 50000, cv = 10)\nelasticNet.fit(train.values, y_train)\nif (elasticNet.l1_ratio_ > 1):\n    elasticNet.l1_ratio_ = 1    \nalpha = elasticNet.alpha_\nratio = elasticNet.l1_ratio_\nprint(\"Best l1_ratio :\", ratio)\nprint(\"Best alpha :\", alpha )\n\nprint(\"ElasticNet RMSE on Training set :\", rmse_cv_train(elasticNet).mean())\ny_train_ela = elasticNet.predict(train.values)\nKRR = KernelRidge(alpha = [600], kernel=\"polynomial\", degree=1.94, coef0=40)\nKRR.fit(train.values, y_train)\nprint(\"Kernel Ridge Regression RMSE on Training set :\", rmse_cv_train(KRR).mean())\nGBoost = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,\n                                   max_depth=4, max_features='sqrt',\n                                   min_samples_leaf=15, min_samples_split=10, \n                                   loss='huber', random_state =5)\nGBoost.fit(train.values, y_train)\nprint(\"XGB RMSE on Training set: \", rmse_cv_train(GBoost).mean())\nclass AveragingModels(BaseEstimator, RegressorMixin, TransformerMixin):\n    def __init__(self, models):\n        self.models = models\n        \n    # define clones of ther original models to fit the data\n    def fit(self, X, y):\n        self.models_ = [clone(x) for x in self.models]\n        \n        # train all cloned models\n        for model in self.models_:\n            model.fit(X, y)\n            \n        return self\n    \n    # predictions for cloned models\n    def predict(self, X):\n        predictions = np.column_stack([model.predict(X) for model in self.models_])\n        return np.mean(predictions, axis=1)\naveraged_models = AveragingModels(models = (lasso, elasticNet, KRR, GBoost))\n\nprint(\"Averaged Models RMSE on Training set :\", rmse_cv_train(averaged_models).mean())\n\n# averaged2 = AveragingModels(models = (lasso, KRR, GBoost))\n# print(\"Averaged Models RMSE on Training set: \", rmse_cv_train(averaged2).mean())\n# averaged3 = AveragingModels(models = (elasticNet, KRR, GBoost))\n# print(\"Averaged Models RMSE on Training set: \", rmse_cv_train(averaged3).mean())\n# averaged4 = AveragingModels(models = (KRR, GBoost))\n# print(\"Averaged Models RMSE on Training set: \", rmse_cv_train(averaged4).mean())\n# averaged5 = AveragingModels(models = (lasso, GBoost))\n# print(\"Averaged Models RMSE on Training set: \", rmse_cv_train(averaged5).mean())\ndef rmse(y, y_pred):\n    return np.sqrt(mean_squared_error(y, y_pred))\naveraged_models.fit(train.values, y_train)\naveraged_train_pred = averaged_models.predict(train.values)\naveraged_pred = np.expm1(averaged_models.predict(test.values))\nprint(rmse(y_train, averaged_train_pred))\nsub = pd.DataFrame()\nsub[\"Id\"] = test_ID\nsub[\"SalePrice\"] = averaged_pred\nsub.to_csv(\"submission2.csv\", index=False)\n# averaged5.fit(train.values, y_train)\n# averaged5_train_pred = averaged5.predict(train.values)\n# averaged5_pred = np.expm1(averaged5.predict(test.values))\n# print(rmse(y_train, averaged5_train_pred))\n# sub = pd.DataFrame()\n# sub[\"Id\"] = test_ID\n# sub[\"SalePrice\"] = averaged5_pred\n# sub.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '98adf89e320d5e'}"}
{"id":"46633","text":"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score\ntrain_df = pd.read_csv('\/kaggle\/input\/liverpool-ion-switching\/train.csv')\ntest_df = pd.read_csv('\/kaggle\/input\/liverpool-ion-switching\/test.csv')\n\"\"\"\n<h2>Initial EDA<\/h2>\n\"\"\"\ntrain_df.head()\ntrain_df.info(null_counts=True)\ntest_df.head()\ntest_df.info(null_counts=True)\ntrain_df['open_channels'].value_counts().plot(kind='bar')\nplt.title('Open channels distribution')\nplt.show()\n\"\"\"\nThe open_channels target is not evenly distributed, look like it decreases almost linearly.\n\"\"\"\nplt.hist(train_df.signal, bins=20)\nplt.hist(test_df.signal, bins=20)\nplt.title('Signal Distribution for Test and Train')\nplt.legend(labels=['Train', 'Test'])\nplt.show()\nprint('Train mean {}, median {}, standard deviation {}'.format(np.mean(train_df.signal), np.median(train_df.signal), np.std(train_df.signal)))\nprint('Test mean {}, median {}, standard deviation {}'.format(np.mean(test_df.signal), np.median(test_df.signal), np.std(test_df.signal)))\nprint('\\nTrain:', stats.normaltest(train_df.signal))\nprint('Test:', stats.normaltest(train_df.signal))\n\"\"\"\nDistribution of the signal feature for the train and test data. They appear to have similar distributions, but the mean, median, and standard deviations are all different. Even though they are not normally distributed, both distributions have enough samples to make a t-test valid.\n\"\"\"\nstats.ttest_ind(train_df.signal, test_df.signal)\n\"\"\"\nDespite the similar shape, these definitely were NOT both randomly sampled from the same population.\n\"\"\"\nplt.hist(train_df.time)\nplt.hist(test_df.time)\nplt.legend(labels=['Train', 'Test'])\nplt.title('Time Distribution (Just Checking)')\nplt.show()\n\"\"\"\nThe time feature resets every 50. Thank you https:\/\/www.kaggle.com\/artgor\/eda-and-model-qwk-optimization for the following little batch code:\n\"\"\"\ntrain_df['batch'] = 0\nfor i in range(0, 10):\n    train_df.iloc[i * 500000: 500000 * (i + 1), 3] = i\nplt.figure(figsize=(20,10))\nplt.plot(train_df.signal[train_df.time < 3])\nplt.plot(train_df.open_channels[train_df.time < 3])\nplt.legend(labels=['Signal', 'Open Channels'], fontsize=16)\nplt.title('Signal and Open Channels', fontsize=20)\nplt.show()\n\"\"\"\nThere is a basic easy to visualize connection between our target variable open_channels and our only feature signal. When the open channels switch is flipped on, the signal spikes up. Here is a breakdown of the 10 different batches of data and their distributions:\n\"\"\"\nfig, axes = plt.subplots(2, 5, figsize=(16, 8))\nnum_batches = len(train_df.batch.unique())\nfig.suptitle('Signal and Open Channels by Batch. Blue == signal, Orange == open_channels', fontsize=16)\naxis_on = True\nfor i in range(num_batches):\n    axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].plot(train_df.signal[train_df.batch == i])\n    axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].plot(train_df.open_channels[train_df.batch == i])\n    axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_yticks(range(-4, 13))\n    if axis_on == False:\n        axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_xticks([])\n        axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_yticks([])\n    axis_on = False\n\"\"\"\nThis problem is going to be harder than it initially looks. Different open_channel inputs can cause some weird looking shapes. There is also a lot of noise in this data to work with. Here are the test distributions:\n\"\"\"\ntest_df['batch'] = 0\nfor i in range(0, 4):\n    test_df.iloc[i * 500000: 500000 * (i + 1), 2] = i\n\nfig, axes = plt.subplots(2, 2, figsize=(10, 10))\nnum_batches = len(test_df.batch.unique())\nfig.suptitle('Test Distributions', fontsize=16)\naxis_on = True\nfor i in range(num_batches):\n    axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].plot(test_df.signal[test_df.batch == i])\n    axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_yticks(range(-4, 13))\n    if axis_on == False:\n        axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_xticks([])\n        axes[i \/\/ (num_batches \/\/ 2), i % (num_batches \/\/ 2)].set_yticks([])\n    axis_on = False\n\"\"\"\nThey gave us some real doozies to predict here. Next, I am curious about the distribution of signal broken down by number of open_channels.\n\"\"\"\nfig, axes = plt.subplots(4, 3, figsize=(15, 20))\nfig.suptitle('Signal Distributions at Number of Open Channels', fontsize=16)\nfor i in range(11):\n    n, bins, patches = axes[i \/\/ 3, i % 3].hist(train_df.signal[train_df.open_channels == i], bins=40)\n    ind = list(n).index(max(n))\n    mean = round(np.mean(train_df.signal[train_df.open_channels == i]), 2)\n    binned_mode = (bins[ind] + bins[ind + 1])\/2\n    axes[i \/\/ 3, i % 3].set_title('Channels {}, BinMode {}, Mean {}'.format(i, round(binned_mode, 2), mean))\n    axes[i \/\/ 3, i % 3].set_xticks([-5, -2.5, 0, 2.5, 5, 7.5, 10, 12.5])\n    axes[i \/\/ 3, i % 3].axvline(binned_mode , color='orange')\n    axes[i \/\/ 3, i % 3].axvline(mean , color='green')\nplt.show()\n\"\"\"\nThere is a large peak and an interesting secondary slope at each open_channels number. The mean does not go up linearly with number of open channels, and neither does the location of the peak. There is an overall trend towards higher signal with more open_channels, but it's clearly much more complex than that. I will now zoom in heavily to see how a change in open_channels affects the signal.\n\"\"\"\nstart = 0.72\nend = 0.727\nplt.figure(figsize=(20,10))\nplt.plot(train_df.signal[(train_df.time > start) & (train_df.time < end)])\nplt.plot(train_df.open_channels[(train_df.time > start) & (train_df.time < end)])\nplt.legend(['Signal', 'Open Channels'], fontsize=16)\nplt.show()\nstart = 200.07\nend = 200.08\nplt.figure(figsize=(20,10))\nplt.plot(train_df.signal[(train_df.time > start) & (train_df.time < end)])\nplt.plot(train_df.open_channels[(train_df.time > start) & (train_df.time < end)])\nplt.legend(['Signal', 'Open Channels'], fontsize=16)\nplt.show()\nstart = 310.07\nend = 310.08\nplt.figure(figsize=(20,10))\nplt.plot(train_df.signal[(train_df.time > start) & (train_df.time < end)])\nplt.plot(train_df.open_channels[(train_df.time > start) & (train_df.time < end)])\nplt.legend(['Signal', 'Open Channels'], fontsize=16)\nplt.show()\n\"\"\"\nThese 3 zoom ins are from different batches. If you compare the first zoom in with the 3rd, they both are switching back and forth from 0 and 1 open_channels and yet the charge is much higher in the second zoom in. Maybe the signal is dependent on long-term open_channel settings rather than just the immediate number of open channels plus noise.\n\nI will now try to use a basic random forest classifier to predict open_channels using signal and time. I expect this to perform pretty poorly but I want to use it as a baseline for later after I engineer features.\n\"\"\"\nrfc = RandomForestClassifier(n_estimators=100, max_depth=5)\nX = train_df.drop('open_channels', 1)\nY = train_df.open_channels\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\nrfc.fit(X_train, y_train)\npreds = rfc.predict(X_test)\nprint('Results with just signal and time:', cohen_kappa_score(preds, y_test, weights='quadratic'))\n\"\"\"\n<h2>Feature Engineering pt. 1<\/h2>\n\n1. previous: Difference between signal and previous time increment. At the start of a chunk, just sets it to 0.\n2. second: Same but two time increments ago.\n3. third: three increments ago.\n4. MicroMean: mean signal of very closeby neighbors\n5. LocalMean: mean signal of semi-closeby neighbors\n6. MacroMean: mean signal in a large range\n\n![](http:\/\/)I'm going to ignore the test data from here on out in this notebook version, since this notebook is mostly exploratory and I don't feel ready to make submissions yet.\n\"\"\"\nprevious_signal = []\nfor batch in train_df.batch.unique():\n    previous_signal += [train_df[train_df.batch == batch].signal.iloc[0]]\n    previous_signal += list(train_df[train_df.batch == batch].signal.iloc[:-1])\ntrain_df['previous'] = previous_signal\ntrain_df['previous'] = train_df.previous - train_df.signal\n\nsecond_prev = []\nfor batch in train_df.batch.unique():\n    second_prev += list(train_df[train_df.batch == batch].signal.iloc[:2])\n    second_prev += list(train_df[train_df.batch == batch].signal.iloc[:-2])\ntrain_df['second'] = second_prev\ntrain_df['second'] = train_df.second - train_df.signal\n\nthird_prev = []\nfor batch in train_df.batch.unique():\n    third_prev += list(train_df[train_df.batch == batch].signal.iloc[:3])\n    third_prev += list(train_df[train_df.batch == batch].signal.iloc[:-3])\ntrain_df['third'] = third_prev\ntrain_df['third'] = train_df.third - train_df.signal\n\nchunk_size = 20\nbatch_size = len(train_df[train_df.batch == 0])\nmean_chunks = []\nif batch_size \/\/ chunk_size == batch_size \/ chunk_size:\n    for i in range(len(train_df) \/\/ chunk_size):\n        mean_chunks += [np.mean(train_df.signal.iloc[chunk_size * i : chunk_size * (i + 1)])] * chunk_size\nelse:\n    print('Error! Not an even split!')\ntrain_df['MicroMean'] = mean_chunks\n\nchunk_size = 500\nbatch_size = len(train_df[train_df.batch == 0])\nmean_chunks = []\nif batch_size \/\/ chunk_size == batch_size \/ chunk_size:\n    for i in range(len(train_df) \/\/ chunk_size):\n        mean_chunks += [np.mean(train_df.signal.iloc[chunk_size * i : chunk_size * (i + 1)])] * chunk_size\nelse:\n    print('Error! Not an even split!')\ntrain_df['LocalMean'] = mean_chunks\n\nchunk_size = 5000\nbatch_size = len(train_df[train_df.batch == 0])\nmean_chunks = []\nif batch_size \/\/ chunk_size == batch_size \/ chunk_size:\n    for i in range(len(train_df) \/\/ chunk_size):\n        mean_chunks += [np.mean(train_df.signal.iloc[chunk_size * i : chunk_size * (i + 1)])] * chunk_size\nelse:\n    print('Error! Not an even split!')\ntrain_df['MacroMean'] = mean_chunks\n\"\"\"\nJust want to check the distributions of the new features. This result shouldn't be surprising:\n\"\"\"\nfig, axes = plt.subplots(3, 2, figsize=(10, 15))\naxes[0, 0].hist(train_df.previous, bins=30)\naxes[0, 0].set_title('Previous')\naxes[0, 1].hist(train_df.second, bins=30)\naxes[0, 1].set_title('Second')\naxes[1, 0].hist(train_df.third, bins=30)\naxes[1, 0].set_title('Third')\naxes[1, 1].hist(train_df.previous, bins=30)\naxes[1, 1].set_title('MicroMean')\naxes[2, 0].hist(train_df.previous, bins=30)\naxes[2, 0].set_title('LocalMean')\naxes[2, 1].hist(train_df.previous, bins=30)\naxes[2, 1].set_title('MacroMean')\nplt.show()\n\"\"\"\nThis is just a little helper function to automate plotting better\n\"\"\"\ndef plot_features(col_names, start, stop, title, lw):\n    plt.figure(figsize=(20,10))\n    for col in range(len(col_names)):\n        plt.plot(train_df[col_names[col]].iloc[start:stop], lw=lw[col])\n    plt.legend(col_names, fontsize=16)\n    plt.title(title, fontsize=20)\n    plt.show()\nplot_features(['signal', 'previous', 'open_channels'], 0, 500000, 'Previous in Batch 0', [1,1,1])\nplot_features(['signal', 'previous', 'open_channels'], 7215, 7250, '\\\"Previous\\\" Close Up on a Bump', [3,3,3])\n\"\"\"\nNot sure how helpful this previous feature is. If I was just looking at the previous plot I'm not sure I could pinpoint where the open_channels bump would be.\n\"\"\"\nplot_features(['signal', 'second', 'open_channels'], 7215, 7250, '\\\"Second\\\" Close Up on a Bump', [3,3,3])\nplot_features(['signal', 'third', 'open_channels'], 7215, 7250, '\\\"Third\\\" Close Up on a Bump', [3,3,3])\nplot_features(['signal', 'MicroMean'], 3000000, 3010000, 'Signal and MicroMean in Batch 6', [1, 2])\nplot_features(['signal', 'LocalMean'], 3000000, 3010000, 'Signal and LocalMean in Batch 6', [1, 5])\nplot_features(['signal', 'MacroMean'], 3000000, 3010000, 'Signal and MacroMean in Batch 6', [1, 5])\n\"\"\"\nMicroMean, LocalMean, MacroMean are all acting as 'smoothing' at different window sizes. I think they might be useful for different chunks of the data. Here are some examples for when I think they will help predict open_channels best:\n\"\"\"\nplot_features(['open_channels', 'MicroMean'], 472000, 478000, 'MicroMean in Batch 0', [1, 2])\nplot_features(['open_channels', 'LocalMean'], 500000, 700000, 'LocalMean in Batch 1', [1, 2])\nplot_features(['open_channels', 'MacroMean'], 3000000, 3500000, 'MacroMean in Batch 1', [1, 2])\n\"\"\"\nIt's possible that the MacroMean feature will help the model learn the overall shape of signal for some of the more interestingly shaped plots, but I'm not sure if that will actually translate to predicting open_channels\n\"\"\"\nresults = []\nfor batch in range(10):\n    batch_results = []\n    rfc = RandomForestClassifier(n_estimators=100, max_depth=4)\n    X = train_df.drop(['open_channels', 'time', 'batch'], 1)[train_df.batch == batch]\n    Y = train_df['open_channels'][train_df.batch == batch]\n    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\n    rfc.fit(X_train, y_train)\n    \n    for feature in zip(X.columns, rfc.feature_importances_):\n        batch_results.append(feature[1])\n    \n    preds = rfc.predict(X_test)\n    batch_results.append(cohen_kappa_score(preds, y_test, weights='quadratic'))\n    results.append(batch_results)\n    \nresults_df = pd.DataFrame()\nresults_df['Signal'] = [item[0] for item in results]\nresults_df['Previous'] = [item[1] for item in results]\nresults_df['Second'] = [item[2] for item in results]\nresults_df['Third'] = [item[3] for item in results]\nresults_df['MicroMean'] = [item[4] for item in results]\nresults_df['LocalMean'] = [item[5] for item in results]\nresults_df['MacroMean'] = [item[6] for item in results]\nresults_df['Kappa'] = [item[7] for item in results]\nresults_df\nrfc = RandomForestClassifier(n_estimators=100, max_depth=5)\nX = train_df[['signal', 'previous', 'second', 'third', 'MicroMean', 'LocalMean', 'MacroMean']]\nY = train_df['open_channels']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\nrfc.fit(X_train, y_train)\npreds = rfc.predict(X_test)\nprint('Results with original features:', cohen_kappa_score(preds, y_test, weights='quadratic'))\n\"\"\"\n<h2>Feature Engineering pt. 1 Analysis<\/h2>\n\nIn the previous section I engineered 6 features: The past 3 signal datapoints, and then the localized mean at 3 different window sizes.\n\nSince this is time series data, and from looking at the signal plot it appeared that past datapoints affect the open_channels target variable. The localized means acts as a 'smoothing' for the data as well, which might add insight since the data is subject to quite a bit of random noise. I modeled each chunk of the data seperately using Random Forest and then used the feature importances attribute in scikit-learn.\n\n'Previous', 'Second', and 'Third' were all very low importance for 'flat' shapes of the signal. However, in curved or sloped batches, they increase in importance, with Third being the most important followed by Second and then Previous. In batch 6, Third is a more important feature than signal, which is pretty amazing. Based on this, I want to add features beyond the Third last datapoint. I will have to manage the size of my data however.\n\nThe three localized mean features were also somewhat important. MicroMean is very important in the batch 0, which is not surprising since it just acts as a very localized smoothing feature. In the second batch, all three were important features with MacroMean helping the most. Maybe it was most helpful because of the chaotic start of the data. Interestingly, MacroMean is extremely unimportant for batches 2 - 5\n\n![](http:\/\/)Overall, adding these features increases the kappa score by quite a bit and I will keep all of them.\n\"\"\"\n\"\"\"\n<h2>Feature Engineering pt. 2<\/h2>\n    \n1. PrevAvgLittle \/ Medium \/ Big \/ Real Big\n2. FutAvgLittle \/ Medium \/ Big \/ Real Big\n3. SlopeLittle \/ Medium \/ Big \/ Real Big\n\nNow I add 12 features that are the average of a previous window, an average of a future window, and their difference in order to find a slope.\n\"\"\"\navg = []\nwin_size = 100\ncs = 500000 #chunk size\nfor i in range(len(train_df)):\n    if (i % cs) - win_size <= 0:\n        avg.append(np.mean(train_df.signal.iloc[(i\/\/cs) * cs : ((i\/\/cs) * cs) + win_size]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i - win_size : i]))\ntrain_df['PrevAvgLittle'] = avg\n\navg = []\nfor i in range(len(train_df)):\n    if (i % cs) > cs - win_size:\n        avg.append(np.mean(train_df.signal.iloc[((i\/\/cs + 1) * cs) - win_size : (i\/\/cs + 1) * cs]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i : i + win_size]))\ntrain_df['FutAvgLittle'] = avg\n                                \ntrain_df['SlopeLittle'] = train_df['FutAvgLittle'] - train_df['PrevAvgLittle']\n\ntrain_df['PrevAvgLittle'].fillna(method='bfill', inplace=True)\ntrain_df['FutAvgLittle'].fillna(method='ffill', inplace=True)\ntrain_df['SlopeLittle'].fillna(method='bfill', inplace=True)\ntrain_df['SlopeLittle'].fillna(method='ffill', inplace=True)\navg = []\nwin_size = 1000\ncs = 500000 #chunk size\nfor i in range(len(train_df)):\n    if (i % cs) - win_size <= 0:\n        avg.append(np.mean(train_df.signal.iloc[(i\/\/cs) * cs : ((i\/\/cs) * cs) + win_size]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i - win_size : i]))\ntrain_df['PrevAvgMedium'] = avg\n\navg = []\nfor i in range(len(train_df)):\n    if (i % cs) > cs - win_size:\n        avg.append(np.mean(train_df.signal.iloc[((i\/\/cs + 1) * cs) - win_size : (i\/\/cs + 1) * cs]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i : i + win_size]))\ntrain_df['FutAvgMedium'] = avg\n                                \ntrain_df['SlopeMedium'] = train_df['FutAvgMedium'] - train_df['PrevAvgMedium']\n\ntrain_df['PrevAvgMedium'].fillna(method='bfill', inplace=True)\ntrain_df['FutAvgMedium'].fillna(method='ffill', inplace=True)\ntrain_df['SlopeMedium'].fillna(method='bfill', inplace=True)\ntrain_df['SlopeMedium'].fillna(method='ffill', inplace=True)\navg = []\nwin_size = 5000\ncs = 500000 #chunk size\nfor i in range(len(train_df)):\n    if (i % cs) - win_size <= 0:\n        avg.append(np.mean(train_df.signal.iloc[(i\/\/cs) * cs : ((i\/\/cs) * cs) + win_size]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i - win_size : i]))\ntrain_df['PrevAvgBig'] = avg\n\navg = []\nfor i in range(len(train_df)):\n    if (i % cs) > cs - win_size:\n        avg.append(np.mean(train_df.signal.iloc[((i\/\/cs + 1) * cs) - win_size : (i\/\/cs + 1) * cs]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i : i + win_size]))\ntrain_df['FutAvgBig'] = avg\n                                \ntrain_df['SlopeBig'] = train_df['FutAvgBig'] - train_df['PrevAvgBig']\n\ntrain_df['PrevAvgBig'].fillna(method='bfill', inplace=True)\ntrain_df['FutAvgBig'].fillna(method='ffill', inplace=True)\ntrain_df['SlopeBig'].fillna(method='bfill', inplace=True)\ntrain_df['SlopeBig'].fillna(method='ffill', inplace=True)\navg = []\nwin_size = 15000\ncs = 500000 #chunk size\nfor i in range(len(train_df)):\n    if (i % cs) - win_size <= 0:\n        avg.append(np.mean(train_df.signal.iloc[(i\/\/cs) * cs : ((i\/\/cs) * cs) + win_size]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i - win_size : i]))\ntrain_df['PrevAvgRealBig'] = avg\n\navg = []\nfor i in range(len(train_df)):\n    if (i % cs) > cs - win_size:\n        avg.append(np.mean(train_df.signal.iloc[((i\/\/cs + 1) * cs) - win_size : (i\/\/cs + 1) * cs]))\n    else:\n        avg.append(np.mean(train_df.signal.iloc[i : i + win_size]))\ntrain_df['FutAvgRealBig'] = avg\n                                \ntrain_df['SlopeRealBig'] = train_df['FutAvgRealBig'] - train_df['PrevAvgRealBig']\n\ntrain_df['PrevAvgRealBig'].fillna(method='bfill', inplace=True)\ntrain_df['FutAvgRealBig'].fillna(method='ffill', inplace=True)\ntrain_df['SlopeRealBig'].fillna(method='bfill', inplace=True)\ntrain_df['SlopeRealBig'].fillna(method='ffill', inplace=True)\n\"\"\"\nNow I will investigate these features visually\n\"\"\"\nplot_features(['signal', 'PrevAvgLittle', 'FutAvgLittle', 'SlopeLittle'],\n                     0, 500000, 'Is LocalSlope Showing What We Want?', [1, 5, 5, 1])\nplot_features(['signal', 'PrevAvgLittle', 'FutAvgLittle', 'SlopeLittle', 'open_channels'],\n                     470000, 500000, 'Zoomed Once', [1, 3, 3, 1, 1])\nplot_features(['signal', 'PrevAvgLittle', 'FutAvgLittle', 'SlopeLittle', 'open_channels'],\n                     496000, 499000, 'Zoomed Twice', [1, 3, 3, 3, 1])\nplot_features(['signal', 'PrevAvgLittle', 'FutAvgLittle', 'SlopeLittle', 'open_channels'],\n                     498000, 502000, 'Different spot', [1, 3, 3, 3, 1])\nplot_features(['signal', 'PrevAvgMedium', 'FutAvgMedium', 'SlopeMedium'],\n                     500000, 1000000, 'Medium Slope', [1, 3, 3, 3])\nplot_features(['signal', 'PrevAvgMedium', 'FutAvgMedium', 'SlopeMedium'],\n                     495000, 505000, 'SlopeMedium', [1, 3, 3, 3])\nplot_features(['signal', 'PrevAvgBig', 'FutAvgBig', 'SlopeBig'],\n                     500000, 550000, 'Macro Slope', [1, 3, 3, 3])\nplot_features(['signal', 'PrevAvgBig', 'FutAvgBig', 'SlopeBig'],\n                     3000000, 3500000, 'Macro Slope', [1, 3, 3, 3])\nplot_features(['signal', 'PrevAvgRealBig', 'FutAvgRealBig', 'SlopeRealBig'],\n                     3000000, 3500000, 'Is RealBig Showing What We Want?', [1, 5, 5, 1])\nplt.figure(figsize=(20,10))\nplt.plot(train_df.SlopeRealBig.iloc[3000000:3500000], lw=3)\nplt.plot(train_df.SlopeBig.iloc[3000000:3500000], alpha=.8)\nplt.plot(train_df.SlopeMedium.iloc[3000000:3500000], alpha=.6)\nplt.axhline(0, color='red')\nplt.title('Comparison of Slope Features in Batch 6')\nplt.legend(labels=['SlopeRealBig', 'SlopeBig', 'SlopeMedium'])\nplt.show()\n\"\"\"\n<h2> Feature Engineering pt. 2 Analysis<\/h2>\n\nI tried to engineer a rate of change feature, and sort of succeeded. The smaller window slopes are too volitile to be that useful, but the larger window slopes do pick up on the general slope of some of the non-flat batches. Are these features actually useful though? In the next cell I make a table of the feature importances broken down by batch.\n\nI feel like I still haven't gotten to the bottom of why certain batches have such different shapes despite having seemingly similar open_channels. I think I need to spend more time analyzing the open_channels target and look for patterns and how it indicates the overall shape of the signal.\n\"\"\"\nresults = []\nfor batch in range(10):\n    batch_results = []\n    rfc = RandomForestClassifier(n_estimators=150, max_depth=5)\n    X = train_df.drop(['open_channels', 'time', 'batch'], 1)[train_df.batch == batch]\n    Y = train_df['open_channels'][train_df.batch == batch]\n    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\n    rfc.fit(X_train, y_train)\n    \n    for feature in zip(X.columns, rfc.feature_importances_):\n        batch_results.append(feature[1])\n    \n    preds = rfc.predict(X_test)\n    batch_results.append(cohen_kappa_score(preds, y_test, weights='quadratic'))\n    results.append(batch_results)\n    \nresults_df = pd.DataFrame()\nfor column in range(len(X.columns)):\n    results_df[X.columns[column]] = [item[column] for item in results]\nresults_df\n\"\"\"\nActually, our slope features are extremely poor. It's possible that I need a better algorithm for finding the localized slope, but I think it's also likely that slope doesn't actually affect the number of open_channels feature. For now, I will drop these features, but keep the previous and future average features since they seem to actually help.\n\"\"\"\ntrain_df.drop(['SlopeLittle', 'SlopeMedium', 'SlopeBig', 'SlopeRealBig'], 1, inplace=True)\nrfc = RandomForestClassifier(n_estimators=100, max_depth=5)\nX = train_df.drop(['open_channels', 'time', 'batch'], 1)\nY = train_df['open_channels']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\nrfc.fit(X_train, y_train)\npreds = rfc.predict(X_test)\nprint('Results with all features:', cohen_kappa_score(preds, y_test, weights='quadratic'))\n\"\"\"\nImprovement with these new features. Now I will go back and add more 'previous' features from the first part, since they have been heavy lifters so far.\n\"\"\"\nfor i in range(4, 9):\n    prev = []\n    for batch in train_df.batch.unique():\n        prev += list(train_df[train_df.batch == batch].signal.iloc[:i])\n        prev += list(train_df[train_df.batch == batch].signal.iloc[:-i])\n    train_df['{}_prev'.format(i)] = prev\n    train_df['{}_prev'.format(i)] -= train_df.signal\nrfc = RandomForestClassifier(n_estimators=100, max_depth=5)\nX = train_df.drop(['open_channels', 'time', 'batch'], 1)\nY = train_df['open_channels']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\nrfc.fit(X_train, y_train)\npreds = rfc.predict(X_test)\nprint('Results with all features:', cohen_kappa_score(preds, y_test, weights='quadratic'))\n\"\"\"\nThat's all for now, I will continue to look for more features. For the future:\n1. Reconsider slope features and try to understand why they weren't helpful\n2. Engineer some measure of 'jitter' or how bouncy the signal data is\n3. Imagine new features\n4. Pursue RNN models in keras, probably without the extra features and just a souped up model with the signal data\n\nThanks for reading!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '55e5e77784d76e'}"}
{"id":"32245","text":"\"\"\"\n# LearnPlatform COVID-19 Impact on Digital Learning\n\n## 1. Introduction\n\n### Problem Statement\n\nThe COVID-19 Pandemic has disrupted learning for more than 56 million students in the United States. In the Spring of 2020, most states and local governments across the U.S. closed educational institutions to stop the spread of the virus. In response, schools and teachers have attempted to reach students remotely through distance learning tools and digital platforms. Until today, concerns of the exacaberting digital divide and long-term learning loss among America\u2019s most vulnerable learners continue to grow.\n\n### Challenge\n\n1. Explore the state of digital learning in 2020.\n2. How the engagement of digital learning relates to factors such as district demographics, broadband access, and state\/national level policies and events.\n\"\"\"\n\"\"\"\n## 2. Data Description\n\nOriginal dataset contains daily edtech engagement data from over 200 school districts in 2020. There are three basic sets of files to get started with:\n\n* The `engagement_data` folder is based on LearnPlatform\u2019s Student Chrome Extension. The extension collects page load events of over 10K education technology products in our product library, including websites, apps, web apps, software programs, extensions, ebooks, hardwares, and services used in educational institutions. The engagement data have been aggregated at school district level, and each file represents data from one school district.\n* The `products_info.csv` file includes information about the characteristics of the top 372 products with most users in 2020.\n* The `districts_info.csv` file includes information about the characteristics of school districts, including data from NCES and FCC.\n\"\"\"\n\"\"\"\n### 2.1 Import modules and setup directories\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n\n# Input data files are available in the read-only \"..\/input\/\" directory\ndata_root = '..\/input\/learnplatform-covid19-impact-on-digital-learning'\nengagement_data_folder = os.path.join(data_root, 'engagement_data')\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\n\"\"\"\n### 2.2 View data sample from `engagement_data` folder\n\"\"\"\n# Read and view first file from engagement_data folder\nengagement_sample = pd.read_csv(\n    os.path.join(engagement_data_folder, os.listdir(engagement_data_folder)[0])\n)\nengagement_sample.head()\n\"\"\"\n**Columns description:**\n\n| Name | Description |\n| :--- | :----------- |\n| time | date in \"YYYY-MM-DD\" |\n| lp_id | The unique identifier of the product |\n| pct_access | Percentage of students in the district have at least one page-load event of a given product and on a given day |\n| engagement_index | Total page-load events per one thousand students of a given product and on a given day |\n\n<font color='green'>**Note:**<\/font> The engagement data are aggregated at school district level, and each file in the folder `engagement_data` represents data from one school district. The 4-digit file name represents `district_id` which can be used to link to district information in `district_info.csv`. The `lp_id` can be used to link to product information in `product_info.csv`.\n\"\"\"\n\"\"\"\n### 2.3 View data sample from `products_info.csv` file\n\"\"\"\n# Read and view products_info.cvs file\nproducts_info = pd.read_csv(os.path.join(data_root, 'products_info.csv'))\nproducts_info.head()\n\"\"\"\n**Columns description:**\n\n| Name | Description |\n| :--- | :----------- |\n| LP ID| The unique identifier of the product |\n| URL | Web Link to the specific product |\n| Product Name | Name of the specific product |\n| Provider\/Company Name | Name of the product provider |\n| Sector(s) | Sector of education where the product is used |\n| Primary Essential Function | The basic function of the product. There are two layers of labels here. Products are first labeled as one of these three categories: LC = Learning & Curriculum, CM = Classroom Management, and SDO = School & District Operations. Each of these categories have multiple sub-categories with which the products were labeled | \n\n\n<font color='green'>**Note:**<\/font> Some products may not have labels due to being duplicate, lack of accurate url or other reasons.\n\"\"\"\n\"\"\"\n### 2.4 View data sample from `districts_info.csv` file\n\"\"\"\n# Read and view districts_info.csv file\ndistricts_info = pd.read_csv(os.path.join(data_root, 'districts_info.csv'))\ndistricts_info.head()\n\"\"\"\n**Columns description:**\n\n| Name | Description |\n| :--- | :----------- |\n| district_id | The unique identifier of the school district |\n| state | The state where the district resides in |\n| locale | NCES locale classification that categorizes U.S. territory into four types of areas: City, Suburban, Town, and Rural. See [Locale Boundaries User's Manual](https:\/\/eric.ed.gov\/?id=ED577162) for more information. |\n| pct_black\/hispanic | Percentage of students in the districts identified as Black or Hispanic based on 2018-19 NCES data |\n| pct_free\/reduced | Percentage of students in the districts eligible for free or reduced-price lunch based on 2018-19 NCES data |\n| county_connections_ratio | `ratio` (residential fixed high-speed connections over 200 kbps in at least one direction\/households) based on the county level data from FCC From 477 (December 2018 version). See [FCC data](https:\/\/www.fcc.gov\/form-477-county-data-internet-access-services) for more information. |\n| pp_total_raw | Per-pupil total expenditure (sum of local and federal expenditure) from Edunomics Lab's National Education Resource Database on Schools \\(NERD\\$\\) project. The expenditure data are school-by-school, and we use the median value to represent the expenditure of a given school district. |\n\n<font color='green'>**Note:**<\/font> There are many missing data marked as `NaN` indicating that the data was suppressed to maximize anonymization of the dataset.\n\n\"\"\"\n\"\"\"\n## 3. The state of digital learning in 2020.\n\nLet's explore the state of digital learning in 2020. I'd like to start with `engagement_data` first.\n\n### 3.1 Explore `engagement_data`\n\n#### 3.1.1 Load data\n\nBefore starting to make any data analisys it is good to write a helper function which will read multiple files into one dictionary of dataframes.\n\"\"\"\n# Create function to read engagement data\ndef read_engagement_data(data_folder=engagement_data_folder):\n    \"\"\"\n    Returns dictionary of dataframes with key as filename\n    and value as pd.DataFrame.\n    >>> read_engagement_data()\n    {\"6345\": pd.DataFrame, ...}\n    \"\"\"\n    result = {}\n    for i in os.listdir(data_folder):\n        result[i[:-4]] = pd.read_csv(os.path.join(data_folder, i), parse_dates=[0,])\n    return result\n\n# Read engagement data\nengagement_data = read_engagement_data()\n\n# View data sample\nengagement_data[\"6345\"].head()\n\"\"\"\n#### 3.1.2 Calculate monthly mean engagement index\n\nNow let's calculate monthly mean `engagement_index` for each district.\n\"\"\"\n# Create function to calculate monthly engagement_index mean\ndef mean_monthly_engagement_index(data=engagement_data):\n    \"\"\"\n    Calculates mean monthly engagement_index dropping 'Nan' values.\n    monthly_engagement_index()\n    >>> {\"6345\": pd.DataFrame, ...}\n    \"\"\"\n    result = {}\n    cols_filter = [\"time\", \"engagement_index\"]\n    cols_rename = {\"time\": \"month\", \"engagement_index\": \"mean_eng_idx\"}\n    for key, value in data.items():\n        new_value = value[cols_filter].fillna(0).copy()\n        new_value[\"time\"] = new_value[\"time\"].dt.month\n        new_value = new_value.groupby([\"time\"]).mean().reset_index()\n        new_value.rename(columns=cols_rename, inplace=True)\n        result[key] = new_value\n    return result\n\n# Calculate monthly engagement index mean\nmean_eng_idx = mean_monthly_engagement_index()\n\n# View data sample\nmean_eng_idx[\"6345\"]\n\"\"\"\n#### 3.1.3 Merge monthly districts data\nIn the below code cell we'll merge all districts monthly mean `engagement_index` into one dataframe.\n\"\"\"\n# Create function to merge monthly engagement index mean\ndef merge_mean_monthly_engagement_index(data=mean_eng_idx):\n    \"\"\"\n    Merge mean_eng_idx (mean monthly engagement index) of\n    every district into one pd.Dataframe and rename columns\n    with mean monthly engagement index values by district\n    id number.\n    \"\"\"\n    result = pd.DataFrame()\n    for key, value in data.items():\n        val = value.rename(columns={\"mean_eng_idx\": key})\n        if result.empty:\n            result = val\n        else:\n            result = pd.merge(result, val, how=\"left\", on=\"month\")\n    return result.fillna(0)\n\n# Merge monthly engagement index mean\nmean_eng_idx_merged = merge_mean_monthly_engagement_index()\n\n# View result\nmean_eng_idx_merged\n\"\"\"\n#### 3.1.4 View difference between districts in 2020\n\nLet's see if there is any big difference between districts' `engagement_index` in 2020 to identify outliers and understand data distribution:\n\"\"\"\nmean_eng_idx_merged.iloc[:, 1:].mean().describe()\n\"\"\"\nIn 233 school districts mean `engagement_index` in 2020 vary from 3.61 to 1215.50 total page-load events per one thousand students per day. Such a big values distribution tells us that school districts differ in terms of using distance learning tools and digital platforms. The best result is almost 1 page-load event per student per day. The worst is 4.16 which means that in some districts students don't use digital learning platforms at all.\n\n#### 3.1.5 The biggest and the lowest mean engagement index examples\nLet's explore districts with the biggest and the lowest mean engagement index values in more details on below charts to try to identify data patterns for the both examples.\n\"\"\"\n# Find max and min index (label)\nidx_max = mean_eng_idx_merged.iloc[:, 1:].mean().idxmax()\nidx_min = mean_eng_idx_merged.iloc[:, 1:].mean().idxmin()\n\n# Create months values array for x axis\nmonths = mean_eng_idx_merged.month.values\n\n# Create line plots for 2 districts\nfig, axes = plt.subplots(1, 2, figsize=(18, 6))\nfig.suptitle(\"Districts with max and min engagement_index in 2020\")\naxes[0].set_title(f\"District {idx_max} (top outlier)\")\nsns.lineplot(ax=axes[0], x=months, y=mean_eng_idx_merged[idx_max].values)\naxes[1].set_title(f\"District {idx_min} (bottom outlier)\")\nsns.lineplot(ax=axes[1], x=months, y=mean_eng_idx_merged[idx_min].values)\nplt.show()\n\"\"\"\nFor the 2 school districts (top and bottom outliers) data patterns of mean engagement index from month to month look also different.\n\"\"\"\n\"\"\"\n#### 3.1.6 Monthly mean egagement index\n\nLet's try to look at mean engagement index values distribution for all districts. But first we need to prepare data for it.\n\"\"\"\n# Create function to concat monthly engagement index mean\ndef concat_mean_monthly_engagement_index(data=mean_eng_idx, fix_missing=False):\n    \"\"\"\n    Concat mean_eng_idx (mean monthly engagement index) of\n    every district into one pd.Dataframe and add new colum\n    district_id with district id number. Fix missing\n    month values by adding zero (optional).\n    \"\"\"\n    result = []\n    fix_df = pd.DataFrame({\"month\": [i for i in range(1, 13)]})\n    \n    def fix(dataframe):\n        \"\"\"\n        Add missing months values.\n        \"\"\"\n        if len(dataframe) < 12:\n            #print(key, len(new_value), end=\" >> \")\n            dataframe = pd.merge(fix_df, dataframe, how=\"left\", on=\"month\")\n            dataframe.fillna(0)\n            #print(key, len(new_value))\n        return dataframe\n    \n    for key, value in data.items():\n        new_value = value.copy()\n        if fix_missing:\n            new_value = fix(new_value)\n        new_value[\"district_id\"] = key\n        result.append(new_value)\n    return pd.concat(result, ignore_index=True)\n\n# Concat monthly engagement index mean\nmean_eng_idx_concat = concat_mean_monthly_engagement_index(fix_missing=True)\n\n# View result\nmean_eng_idx_concat\n# Count month values, should be 233 if there are no missing values in dataset\n# or fix_missing=True and less than 233 otherwise\nmean_eng_idx_concat.month.value_counts()\n# Create function to boxenplot monthly mean engagement index for all districts\ndef plot_monthly_engagement_index(data, stripplot=True):\n    plt.figure(figsize=(18, 5))\n    plt.title(\"Monthly mean engagement index in 2020 (all districts)\")\n    if stripplot:\n        sns.stripplot(x=\"month\", y=\"mean_eng_idx\", data=data)\n    sns.boxenplot(x=\"month\", y=\"mean_eng_idx\", data=data)\n    \n# Boxenplot monthly mean engagement index for all districts  \nplot_monthly_engagement_index(mean_eng_idx_concat)\n\n# Plot line for mean engagement index (all districts)\nplt.figure(figsize=(18, 4))\nplt.title(\"Monthly mean engagement index in 2020 (all districts combined)\")\nsns.lineplot(x=\"month\", y=\"mean_eng_idx\", data=mean_eng_idx_concat.groupby(\"month\").mean().reset_index())\nplt.show()\n\"\"\"\nThere are some significant outliers in the first half of 2020. From May to July it looks like decreasing trend but in January and February trend is increasing. July is the worst month of the year. Let's drop some top outliers to better see data distribution on chart.\n\"\"\"\n# Create function to boxenplot monthly mean engagement index for all districts w\/o outliers\ndef plot_monthly_engagement_index_wo_outliers(data, top_limit, stripplot=True):\n    top_map = data[\"mean_eng_idx\"] < top_limit\n    plot_monthly_engagement_index(data[top_map], stripplot)\n\ntop_limit = 1000\n# Boxenplot monthly mean engagement index for all districts w\/o outliers\nplot_monthly_engagement_index_wo_outliers(mean_eng_idx_concat, top_limit)\n\"\"\"\nIn this chart data became more distinct. And what is more interesting, the last 4 months look very similar and display some stability (even with top outliers). Moreover bottom line of the biggest box segments raised a little up. Let's plot common boundaries for the last 4 months and mean engagement index of all districts combined in 2020.\n\"\"\"\n# Create function to find and plot common boundaries for last 4 months\ndef plot_monthly_engagement_index_with_bound(data, top_limit, stripplot=False,):\n    plot_monthly_engagement_index_wo_outliers(data, top_limit, stripplot)\n    reg_map = data[\"mean_eng_idx\"] < top_limit\n    upper_bound = data[reg_map].groupby(\"month\").describe()[-4:][(\"mean_eng_idx\", \"75%\")].max()\n    lower_bound = data[reg_map].groupby(\"month\").describe()[-4:][(\"mean_eng_idx\", \"25%\")].min()\n    plt.plot([upper_bound for i in range(12)], color=\"red\")\n    plt.plot([lower_bound for i in range(12)], color=\"red\")\n    \n# Boxenplot monthly mean engagement index for all districts with boundaries\nplot_monthly_engagement_index_with_bound(mean_eng_idx_concat, top_limit)\n\n# Calculate outliers % input\nreg_map = mean_eng_idx_concat[\"mean_eng_idx\"] < top_limit\ndiff = mean_eng_idx_concat.groupby(\"month\").mean().reset_index()\\\n    - mean_eng_idx_concat[reg_map].groupby(\"month\").mean().reset_index()\noutliers_input = diff \/ mean_eng_idx_concat.groupby(\"month\").mean().reset_index() * 100\noutliers_input.month = mean_eng_idx_concat.groupby(\"month\").mean().reset_index().month\noutliers_input.rename(columns={\"mean_eng_idx\": \"outliers_percent_input\"}, inplace=True)\n\n# Find top outliers\ntop_map = (mean_eng_idx_concat[\"mean_eng_idx\"] > top_limit)\njuly_map = (mean_eng_idx_concat[\"mean_eng_idx\"] > 400)\\\n            & (mean_eng_idx_concat[\"month\"] == 7)\ntop_map = top_map | july_map\ntop_outliers = mean_eng_idx_concat[top_map]\n\n# Plot line for mean engagement index (all districts)\nplt.figure(figsize=(18, 4))\nplt.title(\"Monthly mean engagement index in 2020 (all districts combined)\")\nsns.lineplot(\n    x=\"month\", y=\"mean_eng_idx\",\n    data=mean_eng_idx_concat[reg_map].groupby(\"month\").mean().reset_index(),\n    label=\"Top outliers excluded\",\n)\nsns.lineplot(\n    x=\"month\", y=\"mean_eng_idx\",\n    data=mean_eng_idx_concat.groupby(\"month\").mean().reset_index(),\n    label=\"Top outliers included\",\n)\nax2 = plt.twinx()\nax2.grid(False)\nfor i, txt in enumerate(outliers_input.outliers_percent_input.values):\n    ax2.annotate(\n        round(txt, 2),\n        (outliers_input.month.values[i],\n        outliers_input.outliers_percent_input.values[i]),\n        xytext=(outliers_input.month.values[i] + 0.1,\n        outliers_input.outliers_percent_input.values[i] + 0.1),\n    )\nsns.lineplot(\n    x=\"month\", y=\"outliers_percent_input\",\n    data=outliers_input,\n    label=\"Top outliers % input\",\n    ax=ax2,\n    linestyle=\"None\",\n    marker=\"o\",\n    color='k'\n)\nplt.legend()\nplt.show()\nplt.figure(figsize=(18, 4))\nplt.title(\"Monthly mean engagement index in 2020 (top outliers)\")\nsns.lineplot(x=\"month\", y=\"mean_eng_idx\", data=top_outliers.groupby(\"month\").mean())\nplt.show()\n\"\"\"\nJuly was the most inactive month during 2020. Top outliers made more significant input to engagement index in the begining of the year gradually degreasing to 0 in July. After July their input was at maximum in September gradually decreasing again. In general top outliers input into monthly mean engagement index decreased almost as much as 5 times (in comparison with February). It is difficult to say now what was the reason for it. This fact needs more study in terms of characteristics of the top 372 products from `products_info.csv` file, engagement data `pct_access` and state interventions, practices or policies. Hopefully this extra data will help us to find a reasonable explanation.\n\"\"\"\n\"\"\"\n#### 3.1.7 Top outliers\n\nLet's identify a group of top outliers and districts with the biggest mean engagement index in 2020.\n\"\"\"\n# Find districts with biggest mean engagement index\nb_map = mean_eng_idx_concat.groupby(\"month\").idxmax()\nbiggest_outliers = mean_eng_idx_concat.iloc[b_map.mean_eng_idx.values]\n\n# Calculate final rating\nfinal_rating = pd.concat(\n    [top_outliers, biggest_outliers]\n    ).district_id.value_counts()\n\n# Plot results\nplt.figure(figsize=(18, 10))\ngs = gridspec.GridSpec(2, 6)\ngs.update(wspace=0.4, hspace=0.3)\nax1 = plt.subplot(gs[0, :3])\nax2 = plt.subplot(gs[0, 3:])\nax3 = plt.subplot(gs[1, :2])\nax4 = plt.subplot(gs[1, 2:4])\nax5 = plt.subplot(gs[1, 4:]) \nplt.suptitle(\"Top outliers\", fontsize=\"16\")\n\nax1.set_title(\"Top outliers in 2020\")\nsns.stripplot(\n    ax=ax1, x=\"month\", y=\"mean_eng_idx\",\n    hue=\"district_id\", data=top_outliers\n)\n\nax2.set_title(\"Top positions in 2020\")\nsns.stripplot(\n    ax=ax2, x=\"month\", y=\"mean_eng_idx\",\n    hue=\"district_id\", data=biggest_outliers\n)\n\nax3.set_title(\"Top outliers scores in 2020\")\nsns.barplot(\n    ax=ax3,\n    x=top_outliers.district_id.value_counts().index,\n    y=top_outliers.district_id.value_counts().values,\n)\n\nax4.set_title(\"Top position scores in 2020\")\nsns.barplot(\n    ax=ax4,\n    x=biggest_outliers.district_id.value_counts().index,\n    y=biggest_outliers.district_id.value_counts().values,\n)\n\nax5.set_title(\"Final rating scores\")\nsns.barplot(ax=ax5, x=final_rating.index, y=final_rating.values)\nplt.show()\n\"\"\"\nNow we have top outliers and some information about them. Most interesting for further study are districts 9536, 6418 and probably 9007. District 9536 is the most persistent one. It appears 7 times among top outliers and keeps top position during 5 months in a row (collecting 12 points in final rating score) during decreasing trend and capturing the worst month July. District 6418 is a newcomer in top outliers since September. It won position from district 9536 in September and October, keeping top position during 4 months in a row till the end of the year. The second newcomer is district 9007. It had top position in August and the third position among top outliers in September disappearing from top outliers till the end of the year. Before making further top outliers study let's identify middle segments first.\n\"\"\"\n\"\"\"\n#### 3.1.8 Middle segments\n\n\"\"\"\n# Find upper and lower boundaries of middle segments in each month\nb_lim = mean_eng_idx_concat[\"mean_eng_idx\"] < top_limit\nmid_seg_cols = [(\"mean_eng_idx\", \"25%\"), (\"mean_eng_idx\", \"75%\")]\nlimits = mean_eng_idx_concat[b_lim].groupby(\"month\").describe()[mid_seg_cols]\nlimits.columns = ['_'.join(col) for col in limits.columns.values]\n\n# Filter middle segment\nraw = mean_eng_idx_concat[b_lim].merge(limits.reset_index(), on=\"month\")\nmid_seg_map = (raw.iloc[:, 1] <= raw.iloc[:, 4]) & (raw.iloc[:, 1] >= raw.iloc[:, 3])\nmid_seg = raw[mid_seg_map].iloc[:, 0:3].copy()\nmid_seg\n# Plot monthly mean engagement index of middle segments\nplt.figure(figsize=(18, 5))\nplt.title(\"Monthly mean engagement index in 2020 (middle segments)\")\nsns.lineplot(x=\"month\", y=\"mean_eng_idx\", data=mid_seg.groupby(\"month\").mean())\nplt.show()\n\"\"\"\nMiddle segments demonstrate more stability and improvement in the last 4 months of 2020 comparing to the begining of the year.\n\"\"\"\n\"\"\"\n### 3.2 Explore `products_info.csv`\n\n#### 3.2.1 Variety of product types\n\nLet's count values in `Primary Essential Function` column, to view variety of product types.\n\"\"\"\n# Count values of Primary Essential Function\ncount_prod_types = products_info[\"Primary Essential Function\"].value_counts()\nprint(count_prod_types.shape[0], \"types of products in total.\")\ncount_prod_types\n\"\"\"\nThere are 35 types of products. It is a little complicated starting point for data study. Let's make it a bit easier and find top 10 products with highest mean engagement index in 2020.\n\"\"\"\n\"\"\"\n#### 3.2.2 Top 10 products in 2020\n\nPrepare data.\n\"\"\"\n# Create function to merge products and engagement index\ndef eng_prod_merge(prod=products_info, eng=engagement_data):\n    \"\"\"\n    \"\"\"\n    prd_inf = prod.rename(columns={\"LP ID\": \"lp_id\"})\n    result = None\n    for key, value in eng.items():\n        new_val = value.copy()\n        #new_val.dropna(inplace=True)\n        new_val.rename(columns={\"time\": \"month\"}, inplace=True)\n        new_val[\"month\"] = new_val[\"month\"].dt.month\n        new_val = new_val.groupby([\"month\", \"lp_id\"]).mean().reset_index()\n        new_val[\"district_id\"] = key\n        new_val = new_val.merge(prd_inf[[\"lp_id\", \"Primary Essential Function\"]], on=\"lp_id\")\n        new_val[\"lp_id\"] = new_val[\"lp_id\"].astype(int)\n        if result is None:\n            result = new_val.copy()\n        else:\n            result = pd.concat([result, new_val])\n    return result\n\ne_p_merged = eng_prod_merge()\ne_p_merged\n\"\"\"\nFind top 10 products with highest mean engagement index.\n\"\"\"\n# Find top ten products\ne_p_summary = e_p_merged[[\"lp_id\", \"pct_access\", \"engagement_index\"]].groupby(\"lp_id\").mean()\ntop_ten = e_p_summary.sort_values([\"engagement_index\"], ascending=False)[:10].reset_index()\ntop_ten = top_ten.merge(products_info.rename(columns={\"LP ID\": \"lp_id\"}), on=\"lp_id\")\ntop_ten\n\"\"\"\nLet's plot 10 top products in 2020 to see their engagement index trend over all school districts.\n\"\"\"\n# Plot top ten products line charts\nfig, axes = plt.subplots(4, 3, figsize=(18, 12))\nplt.subplots_adjust(hspace=0.6)\nplt.suptitle(\"Top 10 products in 2020\\n with trend line\", fontsize=\"16\")\nfor i in range(12):\n    r, c = divmod(i, 3)\n    if i < top_ten.shape[0]:\n        _map = e_p_merged.lp_id == top_ten.iloc[i].lp_id\n        data = e_p_merged[_map].groupby(\"month\").mean().reset_index()\n        axes[r][c].set_title(f\"Product id: {top_ten.iloc[i].lp_id}, rating position # {i + 1}\")\n        sns.lineplot(ax=axes[r][c], x=\"month\", y=\"engagement_index\", data=data)\n        # Plot trend line if no data is missing\n        if len(data) == 12:\n            sns.lineplot(\n                ax=axes[r][c], x=[1, 12],\n                y=[data.iloc[:4].mean().engagement_index, data.iloc[-4:].mean().engagement_index]\n            )\n    else:\n        axes[r][c].axis(\"off\")\nplt.show()\n\"\"\"\nAt quick view product 61292 (LC - Sites, Resources & Reference - Streaming Services) stands out. It looks like it was created in June and had significant growth and took the 3rd rating position (there is no trend line as not all months data is available). On the other hand engagement index of product 24711 (LC - Study Tools) reduced by the end of the year. And it has almost identical negative slope of trend line with product 99916 (LC\/CM\/SDO - Other).\n\n#### 3.2.3 Positive and negative trends.\n\nLet's find which products have positive and negative trends.\n\"\"\"\n# Find trend line slopes for all products\ntrends_dict = {}\nfor i in e_p_merged.lp_id.unique():\n    _map = e_p_merged.lp_id == i\n    data = e_p_merged[_map].set_index(\"lp_id\").groupby(\"month\").mean()#.reset_index()\n    if data.shape[0] == 12:\n        trends_dict[i] = data.iloc[-4:].mean().engagement_index\\\n            - data.iloc[:4].mean().engagement_index\n\nproduct_trends = pd.DataFrame(trends_dict.values(), trends_dict.keys()).reset_index()\nproduct_trends.rename(columns={\"index\": \"lp_id\", 0: \"trend\"}, inplace=True)\npos_trends = (product_trends[\"trend\"] > 0).sum()\nneg_trends = (product_trends[\"trend\"] < 0).sum()\nprint(\"Positive trend:\", pos_trends)\nprint(\"Negative trend:\", neg_trends)\nprint(\"Missing values:\", len(e_p_summary) - (pos_trends + neg_trends))\nprint(\"Total:\", len(e_p_summary))\n\"\"\"\nWe have 66 positive trends, 256 negative trends, 47 with missing values and 3 products are missing in our summary as total number of products is 371. Let's identify the missing products to figure out the reason why they were skipped.\n\"\"\"\n# Identify missing products numbers\nmissing_products = set(products_info[\"LP ID\"]).difference(set(e_p_summary.index))\nmissing_products\n\"\"\"\nIt looks like products 36254, 37805, 88065 do not have any records in egagement data.\n\"\"\"\n# View missing products\nproducts_info[products_info[\"LP ID\"].isin(missing_products)]\n# Check missing products vs engagement data\nall_districts = pd.concat(engagement_data.values())\nall_districts[all_districts.lp_id.isin(missing_products)]\n# Add trend annotation to product trends\ndef trend(x):\n    if x < -1:\n        return \"negative\"\n    elif x > 1:\n        return \"positive\"\n    else:\n        return \"no trend\"\nproduct_trends[\"trend\"].transform(trend)\nproduct_trends[\"trend_annot\"] = product_trends[\"trend\"].transform(trend)\nproduct_trends\n\"\"\"\n### 3.3 Explore `districts_info.csv`\n\n#### 3.3.1 Check for missing data\nNow let's try to explore districts info data to understand how much we can get from this dataset for our analysis.\n\"\"\"\n# Check what kind of missing values we have\ntotal = len(districts_info)\ncol_names = districts_info.columns.to_list()[3:]\nprint(\"Total number of districts:\", total)\nprint(\"Districts with missing location data:\", total - len(districts_info.iloc[:, :3].dropna()))\nfor i, col_n in enumerate(col_names, 3):\n    print(\n        f\"Districts with missing {col_n} data:\",\n        total - len(districts_info.iloc[:, [0, i]].dropna())\n    )\nprint(\n    \"Districts with missing all the data:\",\n    districts_info[districts_info.isna().sum(axis=1) == 6].count().sum())\n\"\"\"\nIt looks like 57 districts which do not have location data, also do not have all the other data in the dataset. Let's drop them as they will not give us any valuable information. \n\"\"\"\n\"\"\"\n#### 3.3.2 How many states represented by school districts\n\"\"\"\n# Drop distrcicts with Nan values in all columns\nd_inf_clean = districts_info\\\n    .set_index(\"district_id\")\\\n    .dropna(how=\"all\")\\\n    .reset_index()\n\n# Count districts by state\nprint(\n    \"Total number of states:\",\n    d_inf_clean.iloc[:, :2].groupby(\"state\").count().count()[0]\n)\nprint(\n    \"Total number of districts:\",\n    d_inf_clean.iloc[:, :2].groupby(\"state\").count().sum()[0]\n)\nd_inf_clean.iloc[:, :2]\\\n    .groupby(\"state\")\\\n    .count()\\\n    .sort_values(\"district_id\", ascending=False)\\\n    .rename(columns={\"district_id\": \"number_of_districts\"})\n\"\"\"\nAfter removing missing data we have 23 states represented by 176 districts. Connecticut is on the top and has 30 school districts in the dataset.\n\"\"\"\n\"\"\"\n#### 3.3.3 Correlation\n\nLet's combine some of the data we've explored so far into one dataset.\n\"\"\"\n# Combine all districts data with mean_eng_idx\nyear_mean = mean_eng_idx_concat[[\"district_id\", \"mean_eng_idx\"]]\\\n    .groupby(\"district_id\")\\\n    .mean()\\\n    .reset_index()\nyear_mean[\"district_id\"] = year_mean[\"district_id\"].astype(int)\nall_districts = d_inf_clean.merge(year_mean, on=\"district_id\")\nall_districts.head()\n\"\"\"\nDo the same for top districts.\n\"\"\"\n# Top districts\n# Set index as 'district_id' and filter by final_rating.index\ntop_districts = all_districts\\\n    .set_index(\"district_id\")\\\n    .reindex(final_rating.index.astype(int))\ntop_districts.dropna(how=\"all\", inplace=True)\ntop_districts\n\"\"\"\nInteresting fact about top districts: District 9536 in New York (city locations) is on the top of the list. District 9515 is also located in New York state but rural.\n\nSplit columns to prepare data for pairplot.\n\"\"\"\n# Split columns data\ndef split(series, col1, col2, dict_, to=\"int\"):\n    for val in series.values:\n        if val is not np.nan:\n            val = val[1:-1]\n            if to == \"int\":\n                val1 = int(val[:val.find(\",\")])\n                val2 = int(val[val.find(\" \"):])\n            elif to == \"float\":\n                val1 = float(val[:val.find(\",\")])\n                val2 = float(val[val.find(\" \"):])\n        elif val is np.nan:\n            val1, val2 = np.nan, np.nan\n        \n        if col1 in dict_:\n            dict_[col1].append(val1)\n        elif col1 not in dict_:\n            dict_[col1] = [val1,]\n        \n        if col2 in dict_:\n            dict_[col2].append(val2)\n        elif col2 not in dict_:\n            dict_[col2] = [val2,]\n    return dict_\n\nsplitted = {}\nsplitted = split(all_districts[\"pct_black\/hispanic\"], \"pct_b\", \"pct_h\", splitted, to=\"float\")\nsplitted = split(all_districts[\"pct_free\/reduced\"], \"pct_free\", \"pct_reduced\", splitted, to=\"float\")\nsplitted = split(all_districts[\"county_connections_ratio\"], \"conn_r\", \"conn_rr\", splitted, to=\"float\")\nsplitted = split(all_districts[\"pp_total_raw\"], \"pp_loc\", \"pp_fed\", splitted)\n# Add splitted data to dataframe\nfor key, val in splitted.items():\n    series = pd.Series(splitted[key], all_districts.index, name=key)\n    all_districts = all_districts.merge(series, left_index=True, right_index=True)\n\nall_districts\n\"\"\"\nPlot pair correlations.\n\"\"\"\n# Plot pair correlations\nsns.pairplot(all_districts.iloc[:, 7:])\n\"\"\"\nFrom the above plot it is possible to see only 2 correlations: `pct_black\/hispanic` (`pct_h`\/`pct_b`) and `pp_total_raw` as local vs federal expenditures (`pp_loc` \/ `pp_fed`). No correlation found between mean engagement index and districts info data.\n\"\"\"\n\"\"\"\n#### 3.3.4 By state rating\n\nLet's find mean engagement index by state and add number of districts in each state.\n\"\"\"\n# Mean by state\nmean_dist = all_districts[[\"state\", \"mean_eng_idx\"]].groupby(\n    \"state\").mean().sort_values(\"mean_eng_idx\", ascending=False)\ncount = d_inf_clean.iloc[:, :2].groupby(\n    \"state\").count().sort_values(\"district_id\", ascending=False)\ncount.rename(columns={\"district_id\": \"n_of_districts\"}, inplace=True)\nmean_dist.merge(count, left_index=True, right_index=True)\n\"\"\"\n## 4. Conclusion\n\n### Districts\nI tried to identify top outliers (districts) in my study as a first step. These top 10 districts are located in the following states in descending order by mean enagement index:\n\n1. New York (City) - district 9536\n2. District of Columbia (City) - district 6418\n3. Arizona (City) - district 9007\n4. Illinois (Suburb) - district 8815\n5. New York (Rural) - district 9515\n6. Utah (Suburb) - district 3692\n\nBut if we combine data by mean engagement index in each state including city and rural (all districts) we'll have the following top 10 results:\n\n1. Arizona - 1 district\n2. New York - 8 districts\n3. New Hampshire - 2 districts\n4. District Of Columbia - 3 districts\n5. Connecticut - 30 districts\n6. New Jersey - 2 districts\n7. Indiana - 7 districts\n8. Illinois - 18 districts\n9. Massachusetts - 21 districts\n10. Utah - 29 districts\n\nThere is some intersection of states within both lists. It can be considered as strong evidence that the listed states have very good engagement index in comparison with other states. No correlation was found between engagement index and such districts data as:\n\n* pct_black\/hispanic\n* pct_free\/reduced\n* county_connections_ratio\n* pp_total_raw\n\n### Trends and patterns\nAll districts had similar pattern of engagement index in 2020. Engagement index dropped in summer with the smallest minimum in July. There are 66 products with positive trend, 256 with negative trend. 47 products have missing values (mostly) in the begining of the year which makes impossible to calculate trend.\n\n### Products\n\nIt is obvious to outline 3 most popular products:\n* Google Docs - which was probably driven by the need of creating and exchanging documents and information.\n* Google Classroom - which was probably driven by the need of LMS, online classes and digital learning.\n* YouTube - which was probably driven by the need of educational videos.\n\"\"\"\n\"\"\"\n## 5. Afterword\n\nThank you very much for your attention and time spent in reading my study. As it is my first analytics competition, and I realize that my notebook not so perfect that I would like it to be. But I hope it was helpful and you could get valuable insights from it. Thank you very much for this interesting experience.\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3b5c6a31bc11c3'}"}
{"id":"126430","text":"import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport os.path\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n# Create a list with the filepaths for training and testing\ndir_ = Path('..\/input\/dogs-cats-images\/dataset\/training_set')\ntrain_filepaths = list(dir_.glob(r'**\/*.jpg'))\n\ndir_ = Path('..\/input\/dogs-cats-images\/dataset\/test_set')\ntest_filepaths = list(dir_.glob(r'**\/*.jpg'))\ndef proc_img(filepath):\n    \"\"\" Create a DataFrame with the filepath and the labels of the pictures\n    \"\"\"\n\n    labels = [str(filepath[i]).split(\"\/\")[-2] \\\n              for i in range(len(filepath))]\n\n    filepath = pd.Series(filepath, name='Filepath').astype(str)\n    labels = pd.Series(labels, name='Label')\n\n    # Concatenate filepaths and labels\n    df = pd.concat([filepath, labels], axis=1)\n\n    # Shuffle the DataFrame and reset index\n    df = df.sample(frac=1,random_state=0).reset_index(drop = True)\n    \n    return df\ntrain = proc_img(train_filepaths)\ntest = proc_img(test_filepaths)\n\nprint(f'Number of pictures in the training dataset: {train.shape[0]}\\n')\nprint(f'Number of pictures in the test dataset: {test.shape[0]}\\n')\nprint(f'Number of different labels: {len(train.Label.unique())}\\n')\nprint(f'Labels: {train.Label.unique()}')\n\n\npd.set_option('display.max_colwidth',200)\ntrain.head()\ntrain.shape, test.shape\nCLASSES = train['Label'].unique().tolist()\n# Display some pictures of the dataset\nfig, axes = plt.subplots(nrows=4, ncols=6, figsize=(15, 7),\n                        subplot_kw={'xticks': [], 'yticks': []})\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(plt.imread(train.Filepath[i]))\n    ax.set_title(train.Label[i], fontsize = 15)\nplt.tight_layout(pad=0.5)\nplt.show()\n\"\"\"\n### Data Preprocessing\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Preprocessing the Training set\ntrain_datagen = ImageDataGenerator(rescale = 1.\/255,\n                                   shear_range = 0.2,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = True,\n                                   validation_split=0.25)\n\ntraining_set = train_datagen.flow_from_dataframe(dataframe=train,\n                                                 x_col='Filepath',\n                                                 y_col='Label',\n                                                 subset='training')\n\n \nval_set = train_datagen.flow_from_dataframe(dataframe=train,\n                                             x_col='Filepath',\n                                              y_col='Label',\n                                            subset='validation')\n\n# Preprocessing the Test set\ntest_datagen = ImageDataGenerator(rescale = 1.\/255)\ntest_set = test_datagen.flow_from_dataframe(dataframe=test,\n                                            x_col='Filepath',\n                                            y_col='Label')\n\"\"\"\n### MobileNet\n\"\"\"\nfrom keras import Sequential\nfrom keras.applications import MobileNet\nfrom tensorflow.keras.layers import Dense\nbase_Net = MobileNet(include_top = False, \n                         weights = '..\/input\/keras-pretrained-models\/MobileNet_NoTop_ImageNet.h5', \n                         input_shape = training_set.image_shape, \n                         pooling='avg',\n                         classes = CLASSES)\n#Adding the final layers to the above base models where the actual classification is done in the dense layers\nmodel_Net = Sequential()\nmodel_Net.add(base_Net)\nmodel_Net.add(Dense(2, activation=('sigmoid')))\n\nmodel_Net.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel_Net.summary()\n\"\"\"\n* Training model on the Training_set and evaluating it on the val_set\n\"\"\"\nr=model_Net.fit(x = training_set, validation_data = val_set, epochs = 5,batch_size=128)\n# plot the loss\nimport matplotlib.pyplot as plt\nplt.plot(r.history['loss'], label='train loss')\nplt.plot(r.history['val_loss'], label='val loss')\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend()\nplt.show()\n\n# plot the accuracy\nplt.plot(r.history['accuracy'], label='train acc')\nplt.plot(r.history['val_accuracy'], label='val acc')\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend()\nplt.show()\npred = model_Net.predict(test_set)\nmodel_Net.save('dogs_cat.h5')\n\"\"\"\n#### if you like this notebook plz upvote it :)\n#### Thank you\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e8739c0314f618'}"}
{"id":"89330","text":"import numpy as np \nimport pandas as pd \nimport os\nimport seaborn as sns\nimport networkx as nx\nimport csv\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\ntf.Session()\nfrom IPython.display import YouTubeVideo\nprint(os.listdir(\"..\/input\/\"))\nprint(os.listdir(\"..\/input\/frame-sample\/\/frame\"))\nprint(os.listdir(\"..\/input\/video-sample\/\/video\"))\nvideo_record00 = \"..\/input\/video-sample\/video\/train00.tfrecord\"\nframe_record00 = \"..\/input\/frame-sample\/\/frame\/train00.tfrecord\"\nlabel_names=pd.read_csv(\"..\/input\/label_names_2018.csv\")\nvocabulary=pd.read_csv(\"..\/input\/vocabulary.csv\")\nsample_submission=pd.read_csv(\"..\/input\/sample_submission.csv\")\nprint(label_names.head(5))\nprint('The Data in label_names is : {}'.format(label_names.shape))\nprint(vocabulary.head(5))\nprint('The data dictionary in vocabulary is : {}'.format(vocabulary.shape))\n# Sample Submission File\nprint(sample_submission.head(5))\n#Tensorflow version\nprint(tf.__version__)\n\"\"\"\n<h3>Lets first read the data from the video file<\/h3>\n\n\"\"\"\nvid_ids = []\nlabels = []\nmean_rgb = []\nmean_audio = []\n\nfor train00 in tf.python_io.tf_record_iterator(video_record00):\n    train_f= tf.train.Example.FromString(train00)\n    vid_ids.append(train_f.features.feature['id'].bytes_list.value[0].decode(encoding='UTF-8'))\n    labels.append(train_f.features.feature['labels'].int64_list.value)\n    mean_rgb.append(train_f.features.feature['mean_rgb'].float_list.value)\n    mean_audio.append(train_f.features.feature['mean_audio'].float_list.value)\nprint('Number of videos in train00.tfrecord file  is : ',len(mean_rgb))\n#Let us randomly select a video id 18 \nprint('Select  a youtube video id:',vid_ids[18])\n# The list of 20 features of the video d 18 \nprint('First 20 features of a  selected youtube video is  (',vid_ids[18],'):')\nprint(mean_rgb[18][:20])\nvid_ids = []\nlabels = []\nmean_rgb = []\nmean_audio = []\n\nfor train00 in tf.python_io.tf_record_iterator(video_record00):\n    train_f= tf.train.Example.FromString(train00)\n    vid_ids.append(train_f.features.feature['id'].bytes_list.value[0].decode(encoding='UTF-8'))\n    labels.append(train_f.features.feature['labels'].int64_list.value)\n    mean_rgb.append(train_f.features.feature['mean_rgb'].float_list.value)\n    mean_audio.append(train_f.features.feature['mean_audio'].float_list.value)\nprint('Number of videos in train00.tfrecord file  is : ',len(mean_rgb))\n#Let us randomly select a video id 18 \nprint('Select  a youtube video id:',vid_ids[18])\n# The list of 20 features of the video d 18 \nprint('First 20 features of a  selected youtube video is  (',vid_ids[18],'):')\nprint(mean_rgb[18][:20])\n\"\"\"\nAs ID field in the TensorFlow record files is a <b>4-character string<\/b> ( e.g. ABCD). To get the YouTubeID, you can construct a URI like \/AB\/ABCD.js. As a real example, the ID <b>XE00<\/b> can be converted to a video ID via the URL <b>(http:\/\/data.yt8m.org\/2\/j\/i\/XE\/XE00.js.)<\/b>  The format of the file is JSONP, and should be self-explainatory.\n\"\"\"\nYouTubeVideo('mLEJIW9HeIw')\n\"\"\"\n<h3>Lets  read the data from the frame  file<\/h3>\n\"\"\"\nfeat_rgb = []\nfeat_audio = []\nrgb_frame = []\naudio_frame = []\nimport warnings\nwarnings.filterwarnings(action='ignore',category=UserWarning,module='tensorflow')\nfor train00 in tf.python_io.tf_record_iterator(frame_record00):        \n    train_f = tf.train.SequenceExample.FromString(train00)\n    num_frames = len( train_f .feature_lists.feature_list['audio'].feature)\n    sess = tf.InteractiveSession()\n    # iterate through frames\n    for i in range(num_frames):\n        rgb_frame.append(tf.cast(tf.decode_raw( train_f .feature_lists.feature_list['rgb'].feature[i].bytes_list.value[0],tf.uint8) ,tf.float32).eval())\n        audio_frame.append(tf.cast(tf.decode_raw( train_f .feature_lists.feature_list['audio'].feature[i].bytes_list.value[0],tf.uint8),tf.float32).eval())\n    sess.close()\n    feat_rgb.append(rgb_frame)\n    feat_audio.append(audio_frame)\n    break\nprint('The first video has %d frames' %len(feat_rgb[0]))\nsns.lmplot(x='Index', y='TrainVideoCount', data=vocabulary , size=15)\nwith open('..\/input\/vocabulary.csv', 'r') as f:\n  vocabularylist = list(csv.reader(f))\nT1=[]\nfor l in vocabularylist:\n    if l[5] != 'NaN' and l[6] !='NaN' and l[5] != '' and l[6] !='' and l[5] !=  l[6] :\n        c1 = l[5]\n        c2 = l[6]\n        tuple = (c1, c2)\n    if l[5] != 'NaN' and l[7] !='NaN' and l[5] != '' and l[7] !='' and l[5] !=  l[7] :\n        c1 = l[5]\n        c2 = l[7]\n        tuple = (c1, c2)\n    if l[6] != 'NaN' and l[7] !='NaN' and l[6] != '' and l[7] !='' and l[7] !=  l[6] :\n        c1 = l[6]\n        c2 = l[7]\n        tuple = (c1, c2)\n    T1.append(tuple)\nedges = {k: T1.count(k) for k in set(T1)}\nedges\nB = nx.DiGraph()\nnodecolor=[]\nfor ed, weight in edges.items():\n    if ed[0]!='Vertical2' and ed[0]!='Vertical3' and  ed[1]!='Vertical2' and ed[1]!='Vertical3':\n        B.add_edge(ed[0], ed[1], weight=weight)\nfor k in B.nodes:\n    if (k == \"Beauty & Fitness\"):\n        nodecolor.append('blue')\n    elif (k == \"News\"):\n        nodecolor.append('Magenta')\n    elif (k == \"Food & Drink\"):\n        nodecolor.append('crimson')\n    elif (k == \"Health\"):\n        nodecolor.append('green')\n    elif (k == \"Science\"):\n        nodecolor.append('yellow')\n    elif (k == \"Business & Industrial\"):\n        nodecolor.append('cyan')\n    elif (k == \"Home & Garden\"):\n        nodecolor.append('darkorange')\n    elif (k == \"Travel\"):\n        nodecolor.append('slategrey')\n    elif (k == \"Arts & Entertainment\"):\n        nodecolor.append('red')\n    elif (k == \"Games\"):\n        nodecolor.append('grey')\n    elif (k == \"People & Society\"):\n        nodecolor.append('lightcoral')\n    elif (k == \"Shopping\"):\n        nodecolor.append('maroon')\n    elif (k ==\"Computers & Electronics\"):\n        nodecolor.append('orangered')\n    elif (k == \"Hobbies & Leisure\"):\n        nodecolor.append('saddlebrown')\n    elif (k == \"Sports\"):\n        nodecolor.append('lawngreen')\n    elif (k == \"Real Estate\"):\n        nodecolor.append('deeppink')\n    elif (k == \"Finance\"):\n        nodecolor.append('springgreen')\n    elif (k == \"Reference\"):\n        nodecolor.append('royalblue')\n    elif (k == \"Autos & Vehicles\"):\n        nodecolor.append('turquoise')\n    elif (k == \"Internet & Telecom\"):\n        nodecolor.append('lime')\n    elif (k == \"Law & Government\"):\n        nodecolor.append('palegreen')\n    elif (k == \"Jobs & Education\"):\n        nodecolor.append('navy')\n    elif (k == \"Pets & Animals\"):\n        nodecolor.append('lightpink')\n    elif (k == \"Books & Literature\"):\n        nodecolor.append('lightpink')\n    \n                         \nplt.figure(figsize = (15,15))\nnx.draw(B, pos=nx.circular_layout(B), node_size=1500, with_labels=True, node_color=nodecolor)\nnx.draw_networkx_edge_labels(B, pos=nx.circular_layout(B), edge_labels=nx.get_edge_attributes(B, 'weight'))\nplt.title('Weighted graph representing the relationship between the categories', size=20)\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'a3cbfe1813ee3e'}"}
{"id":"69543","text":"\"\"\"\n# Conway's Reverse Game of Life 2020\n\nThe Game of Life is a cellular automaton created by mathematician John Conway in 1970. The game consists of a board of cells that are either on or off. One creates an initial configuration of these on\/off states and observes how it evolves. There are **four simple rules** to determine the next state of the game board, given the current state:\n\n- **Overpopulation:** if a living cell is surrounded by more than three living cells, it dies.\n\n- **Stasis:** if a living cell is surrounded by two or three living cells, it survives.\n\n- **Underpopulation:** if a living cell is surrounded by fewer than two living cells, it dies.\n\n- **Reproduction:** if a dead cell is surrounded by exactly three cells, it becomes a live cell.\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\nprint(\"hello world\")\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\n\"\"\"\n# Initial Exploration - Data Set\n\nThe data consists of 50.000 games on a 25x25 board (625 locations). Each line is a game with the first column as game id and the second the delta (time steps between start set up and final\/stop board). The next 625 columns represent each position in the start matrix and the last 625 each position in the stop one.  \n\"\"\"\ntrain_ds = pd.read_csv(\"..\/input\/conways-reverse-game-of-life-2020\/train.csv\")\ntrain_ds.head()\ntrain_ds.shape\ntrain_ds.describe()\n\"\"\"\nA sample of how the board looks like\n\"\"\"\nfig= plt.figure()\n\nstart = train_ds.iloc[5,2:625+2]\nmat_start = np.array(start).reshape(25,25)\nfig.add_subplot(1, 2, 1)\nplt.imshow(mat_start), plt.title('START MATRIX')\n\n\nstop = train_ds.iloc[5,625+2:]\nmat_stop= np.array(stop).reshape(25,25)\nfig.add_subplot(1, 2, 2)\nplt.imshow(mat_stop), plt.title('STOP MATRIX')\n\"\"\"\nLooking for differences in the start and stop matrixes. We sum each matrix to get the total value of cells\/ones and see if there is any difference.\nBoth distributions are fairly similar, but the stop board has slighly less cells\/ones.\n\"\"\"\nstart = train_ds.iloc[:,:2]\nstart['Sum'] = train_ds.iloc[:,2:627].sum(axis=1)\n\nstop = train_ds.iloc[:,:2]\nstop['Sum'] = train_ds.iloc[:,627:].sum(axis=1)\nprint('START')\nprint('mean= ' + str(start['Sum'].mean()))\nprint('std= ' + str(start['Sum'].std()))\nprint('STOP')\nprint('mean= ' + str(stop['Sum'].mean()))\nprint('std= ' + str(stop['Sum'].std()))\n\nfig = plt.figure(figsize=(15,15))\n\n#START\nfig.add_subplot(3, 2, 1)\n#Histogram\nsns.distplot( start['Sum'], bins=15)\nplt.title('START')\n\n#Boxplot\nfig.add_subplot(3, 2, 3)\nsns.boxplot( y=start['Sum'] )\n\n#Violin\nfig.add_subplot(3, 2, 5)\nsns.violinplot( y=start['Sum'] )\n\n#STOP\nfig.add_subplot(3, 2, 2)\n#Histogram\nsns.distplot( stop['Sum'], bins=15)\nplt.title('STOP')\n\nfig.add_subplot(3, 2, 4)\n#Boxplot\nsns.boxplot( y=stop['Sum'] )\n\nfig.add_subplot(3, 2, 6)\n#Violin\nsns.violinplot( y=stop['Sum'] )\n\"\"\"\nNow we look into the difference of cells between start and stop boards. \nWe clearly see again, that stop boards have less cells alive. In general we see three patterns:\n\n1) As we could expect, the start #cells highly influences the stop #cells\n\n2) The more the delta the more the variance on the relation start\/stop #cells\n\n3) The more the start #cells the more the variance on the relation\n\"\"\"\nrelation = start.copy()\nrelation = relation.rename(columns={'Sum':'Start_Sum'})\nrelation['Stop_Sum'] = stop['Sum']\nrelation['Diff'] = abs(relation['Start_Sum'] - relation['Stop_Sum'])\n\nplt.figure(figsize=(15,7))\nsns.violinplot( x= relation['delta'],y=relation['Diff']  )\ncmap = plt.cm.Spectral\nfig,axes = plt.subplots(nrows=1, ncols=5, figsize=(30, 10))\nfor i,delta in enumerate(np.sort(relation['delta'].unique())):\n    delta_condition=relation['delta']==delta\n    sns.regplot(x=relation['Start_Sum'][delta_condition], y=relation['Stop_Sum'][delta_condition],ax=axes[i], scatter=False)\n    sns.scatterplot(data=relation[delta_condition],x=relation['Start_Sum'][delta_condition], y=relation['Stop_Sum'][delta_condition],ax=axes[i], hue=relation['Diff'][delta_condition])\n    \n\"\"\"\n# Deep Learning model\nNow we train a DL model to predict the start state given the stop board. (It is the reverse game of life)\n\"\"\"\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model\n\nstart = train_ds.iloc[:,2:625+2]\nstop = train_ds.iloc[:,625+2:]\n\n#For now I am only considering delta=1\ny = np.array(start[train_ds['delta']==1])\nx = np.array(stop[train_ds['delta']==1])\n\nx= x.reshape(np.shape(x)[0],25,25,1)\n#y= y.reshape(np.shape(y)[0],25,25,1)\n\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.3)\n\n#Some sanity checks\nprint(np.shape(x_train))\nprint(np.shape(y_train))\nprint(np.shape(y_test))\n\nprint(x_train[:3].reshape(3,25,25))\n#Simple model\nmodel = tf.keras.models.Sequential([\n    Conv2D(2, 3, activation='relu', dilation_rate=2, input_shape=(25,25,1), padding='same'),\n    Conv2D(1, 3, activation='relu', dilation_rate=2, input_shape=(25,25,1), padding='same'),\n    Flatten()#,\n    #Dense(625, input_dim=625, activation='sigmoid')\n  ])\n\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy'\n             )\n\nmodel.fit(x_train, y_train,validation_data=(x_test,y_test) , epochs=150, batch_size=32)\nmodel.summary()\n\"\"\"\n# Results data analysis\n\nWe plot some samples to check the results. In this case we define the treshold as 0.5 but we will explore further to get the best value.\nWe get an **accuracy of 83.4%**.\n\nWe will differentiate between accuracy on predicting alive and dead cells. As there many more dead cells that alive it is easy to predict an output of all dead cells and get fairly good results.\n\"\"\"\ny_pred = model.predict(x_test)\n\npred = np.where(y_pred > 0.5, 1, 0)\n\nfig = plt.figure(figsize=(15,15))\n\nax1=fig.add_subplot(1,3,1)\nax1.imshow(x_test[0].reshape(25,25))\nplt.title('START')\n\nax2 = fig.add_subplot(1,3,2)\nax2.imshow(pred[0].reshape(25,25))\nplt.title('PREDICTION')\n\nax3 = fig.add_subplot(1,3,3)\nax3.imshow(y_test[0].reshape(25,25))\nplt.title('GROUND TRUTH')\n\nprint(np.shape(pred))\npred = np.where(y_pred > 0.5, 1, 0)\n\naccuracy_1 = []\naccuracy_0 = []\nfor i,prediction in enumerate(pred):\n    accuracy_1.append(np.sum(prediction[y_test[i] == 1] == y_test[i][y_test[i] == 1])\/len(y_test[i][y_test[i] == 1]))\n    accuracy_0.append(np.sum(prediction[y_test[i] == 0] == y_test[i][y_test[i] == 0])\/len(y_test[i][y_test[i] == 0]))\n    acc = (np.sum(prediction[prediction == 1] == y_test[i][y_test[i] == 1])\/len(y_test[i][y_test[i] == 1]))\n    \n    #print(str(len(y_test[i][y_test[i] == 1])) +' - ' + str(len(prediction[prediction == 1])) + ' - ' + str(acc))\n#print(str(prediction[y_test[i] == 1]) + ' - ' + str(y_test[i][y_test[i] == 1]))\nprint(sum(accuracy_1)\/len(accuracy_1))\nprint(sum(accuracy_0)\/len(accuracy_0))\n\nprint( (sum(accuracy_1)\/len(accuracy_1) + sum(accuracy_0)\/len(accuracy_0) )\/2.0)\n\"\"\"\nOur output is a probability of [0,1] of a cell being alive. We plot the difference between our probability and the ground truth for dead and alive cells.\n\nWith this, we see that the treshold value for a cell being considerd alive is close to 0.2 not to the \"usual\" 0.5. There are also many more cells dead than alive.\n\"\"\"\ndiff = y_test-y_pred\n#print(sum(diff)\/len(diff))\n\nsns.distplot( diff[y_test==1], label='Alive [1]')\n\nsns.distplot( abs(diff[y_test==0]), label='Dead [0]')\nplt.title('Diff of Ground truth - probability')\nplt.legend()\nplt.show()\n\"\"\"\nNow we will se how changing the treshold changes the accuracy\n\"\"\"\n\ntresh = np.arange(0,1,0.01)\nacc1 = []\nacc0 = []\nacc = []\nfor treshold in tresh:\n    pred = np.where(y_pred > treshold, 1, 0)\n    \n    accuracy_1 = []\n    accuracy_0 = []\n    for i,prediction in enumerate(pred):\n        accuracy_1.append(np.sum(prediction[y_test[i] == 1] == y_test[i][y_test[i] == 1])\/len(y_test[i][y_test[i] == 1]))\n        accuracy_0.append(np.sum(prediction[y_test[i] == 0] == y_test[i][y_test[i] == 0])\/len(y_test[i][y_test[i] == 0]))\n\n    acc1.append(sum(accuracy_1)\/len(accuracy_1))\n    acc0.append(sum(accuracy_0)\/len(accuracy_0))\n\n    acc.append( (sum(accuracy_1)\/len(accuracy_1) + sum(accuracy_0)\/len(accuracy_0) )\/2.0)\nsns.scatterplot(x=tresh, y = acc1)\nsns.scatterplot(x=tresh, y = acc0)\nsns.lineplot(x=tresh, y = acc)\npred = np.where(y_pred > 0.3, 1, 0)\n\naccuracy_1 = []\naccuracy_0 = []\nfor i,prediction in enumerate(pred):\n    accuracy_1.append(np.sum(prediction[y_test[i] == 1] == y_test[i][y_test[i] == 1])\/len(y_test[i][y_test[i] == 1]))\n    accuracy_0.append(np.sum(prediction[y_test[i] == 0] == y_test[i][y_test[i] == 0])\/len(y_test[i][y_test[i] == 0]))\n    acc = (np.sum(prediction[prediction == 1] == y_test[i][y_test[i] == 1])\/len(y_test[i][y_test[i] == 1]))\n    \n    #print(str(len(y_test[i][y_test[i] == 1])) +' - ' + str(len(prediction[prediction == 1])) + ' - ' + str(acc))\n#print(str(prediction[y_test[i] == 1]) + ' - ' + str(y_test[i][y_test[i] == 1]))\nprint(sum(accuracy_1)\/len(accuracy_1))\nprint(sum(accuracy_0)\/len(accuracy_0))\n\nprint( (sum(accuracy_1)\/len(accuracy_1) + sum(accuracy_0)\/len(accuracy_0) )\/2.0)\n\"\"\"\nWe have increased our global accuracy by 12pp only with the treshold setting. \n\"\"\"\ntest_ds = pd.read_csv('..\/input\/conways-reverse-game-of-life-2020\/test.csv')\ntest_ds.head()\ntest_ds.iloc[:,2:].head()\npredictions = np.array([])\nfor delta in np.flip(np.arange(1,6)):\n    print(delta)\n    if np.shape(predictions)[0] >0: \n        a = np.concatenate((predictions,np.array(test_ds.iloc[:,2:][test_ds['delta']==delta])),axis=0)\n    else:\n        a=np.array(test_ds.iloc[:,2:][test_ds['delta']==delta])\n    a = a.reshape(np.shape(a)[0],25,25,1)\n    print(np.shape(a))\n    predictions = model.predict(a)\n    predictions = np.where(predictions > 0.3, 1, 0)\n    \n\nsample_submission = pd.read_csv('..\/input\/conways-reverse-game-of-life-2020\/sample_submission.csv', index_col='id')\nsample_submission.iloc[:] = predictions\nsample_submission.to_csv('submission.csv')\nsample_submission.to_csv('submission3.csv')\nsample_submission","meta":"{'source': 'AI4Code', 'id': '7ffadeab848915'}"}
{"id":"45738","text":"\"\"\"\n#  **Importing Libraries**\n\"\"\"\nimport pandas as pd  \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndata = pd.read_csv('..\/input\/random-linear-regression\/train.csv')\ndata\ndata.info()\n\"\"\"\n> Here 1 missing data is present in y column.Therefore, this data requires some `Preprocessing`.\n\"\"\"\ndata.dropna(inplace=True)\ndata.info()\n\"\"\"\n# Data Visualization\n\"\"\"\nplt.subplots(figsize=(10, 6))\nplt.hist(data['x'],bins= 15)\nplt.show()\nplt.subplots(figsize=(10, 6))\nplt.hist(data['y'],bins= 15)\nplt.show()\nnp.corrcoef(data['x'],data['y'])[0,1]\n\"\"\"\n> Through Data Visualization, We cannot deduct any correlation between `X` and `Y`.\nUsing correlation it shows that data `99%` correlates.\nTherefore, It is perfect for `Linear Regression`.\n\"\"\"\nplt.subplots(figsize=(10, 6))\nplt.scatter(data['x'],data['y'],color = \"blue\", edgecolors = \"white\", linewidths = 0.1, alpha = 0.7)\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.show()\n\"\"\"\n> The plot is `strong`,`positive` and `linear`.\n\"\"\"\n\"\"\"\n# Linear Regression Model\n\"\"\"\nX = data['x'].values.reshape(-1, 1)\nY = data['y'].values.reshape(-1, 1)\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,Y, test_size=0.33, random_state=143)\nfrom sklearn.linear_model import LinearRegression\nmodel = LinearRegression()\nmodel.fit(X_train,y_train)\ny_predict=model.predict(X_test)\ny_predict\nplt.subplots(figsize=(10, 6))\nplt.scatter(X_test,y_test)\nplt.plot(X_test,y_predict,c='r')\nfrom sklearn.metrics import r2_score\nscore=r2_score(y_test,y_predict)\nscore","meta":"{'source': 'AI4Code', 'id': '54465f8d1e7dc8'}"}
{"id":"105991","text":"# 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\n\"\"\"\nThis is my first exporation in Kaggle and learning to make submission in Kaggle. Thank you Alexis Cook for the Notebook https:\/\/www.kaggle.com\/alexisbcook\/titanic-tutorial\n\"\"\"\ntrain_data = pd.read_csv(\"\/kaggle\/input\/titanic\/train.csv\")\ntrain_data.head()\ntest_data = pd.read_csv(\"\/kaggle\/input\/titanic\/test.csv\")\ntest_data.head()\n\"\"\"\nExplore a pattern\u00b6\nRemember that the sample submission file in **gender_submission.csv** assumes that all female passengers survived (and all male passengers died).\n\nIs this a reasonable first guess? We'll check if this pattern holds true in the data (in train.csv).\n\nRunning the below cells to find this out. \n\"\"\"\nwomen = train_data.loc[train_data.Sex == 'female'][\"Survived\"]\nrate_women = sum(women)\/len(women)\n\nprint(\"% of women who survived:\", rate_women)\n\"\"\"\nPandas module enables us to handle large data sets containing a considerably huge amount of data for processing altogether.\n\nThis is when Python loc() function comes into the picture. The loc() function helps us to retrieve data values from a dataset at an ease.\n\nUsing the loc() function, we can access the data values fitted in the particular row or column based on the index value passed to the function.\n\n**Syntax:**\n> pandas.DataFrame.loc[index label]\n\nSource:https:\/\/www.askpython.com\/python-modules\/pandas\/python-loc-function\n\"\"\"\nmen = train_data.loc[train_data.Sex == 'male'][\"Survived\"]\nrate_men = sum(men)\/len(men)\n\nprint(\"% of men who survived:\", rate_men)\n\"\"\"\nFrom this you can see that almost 75% of the women on board survived, whereas only 19% of the men lived to tell about it. Since gender seems to be such a strong indicator of survival, the submission file in **gender_submission.csv** is not a bad first guess!\n\"\"\"\n\"\"\"\n<h2> Builiding a Random forest model <\/h2>\n\nFollowing the notebook of Alexis Cook, we will build a random forest model. \n\nWe'll build what's known as a random forest model. This model is constructed of several \"trees\" that will individually consider each passenger's data and vote on whether the individual survived. Then, the random forest model makes a democratic decision: the outcome with the most votes wins!\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\ny = train_data[\"Survived\"]\n\nfeatures = [\"Pclass\", \"Sex\", \"SibSp\", \"Parch\"]\nX = pd.get_dummies(train_data[features])\nX_test = pd.get_dummies(test_data[features])\n\"\"\"\nThe code cell below looks for patterns in four different columns (\"Pclass\", \"Sex\", \"SibSp\", and \"Parch\") of the data. It constructs the trees in the random forest model based on patterns in the **train.csv** file, before generating predictions for the passengers in **test.csv**. The code also saves these new predictions in a CSV file **submission.csv**.\n\"\"\"\nmodel = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)\nmodel.fit(X, y)\npredictions = model.predict(X_test)\n\noutput = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})\noutput.to_csv('submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","meta":"{'source': 'AI4Code', 'id': 'c2ba34091f56ca'}"}
{"id":"27101","text":"\"\"\"\n<img src=\"https:\/\/www.policybazaar.com\/pblife\/assets\/images\/pb_life_How_to_increase_Health_insurance_cover_1592063367.gif\">\n\"\"\"\n\"\"\"\n# About Dataset\n\"\"\"\n\"\"\"\nThis dataset contains person's information like age,sex,gender,bmi,region,smoke or not and we have to predict their medical insurance cost.In this notebook I will apply regression techniques of supervised learning to predict the medical insurance costs.\n\"\"\"\n\"\"\"\n# This notebook will cover the following\n\n1. Exploratory Data Analysis \n2. Data Modelling and Evaluation\n\"\"\"\n\"\"\"\n<font size=\"+2\" color=chocolate ><b>Please Upvote my kernel if you like my work.<\/b><\/font>\n\"\"\"\n\"\"\"\n# Import Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n\"\"\"\n# Import Dataset\n\"\"\"\ndata=pd.read_csv('..\/input\/insurance\/insurance.csv')\ndata.head()\n\"\"\"\n<font size=\"+3\" color='#1f0c75' ><b>Exploratory Data Analysis<\/b><\/font>\n\"\"\"\n\"\"\"\n# Data Summary\n\"\"\"\ndata.iloc[:,[0,2,6]].describe()\n\"\"\"\n* Age is ranging from 18 to 64 ,with mean of 38.2 and standard deviation of 14.04 \n* bmi is ranging from 15.96 to 53.13 , with mean of 30.6 and standard deviation of 6.09\n* charges is ranging from 1121 to 63770 , with mean of 13270 and standard deviation of 12110\n\"\"\"\n\"\"\"\n# Age distribution\n\"\"\"\nsns.distplot(data['age'])\n\"\"\"\n* As you can see age is normally distrtibuted \n* Maximum number of patients are of 18-22 age \n\"\"\"\nsns.boxplot(y='age',data=data,color='green')\n\"\"\"\n# Age Vs Bmi by age\n\"\"\"\nsns.scatterplot(x=\"age\", y=\"bmi\", hue='sex',data=data,color='red')\n\"\"\"\n* No relation between age and bmi\n\"\"\"\n\"\"\"\n# Gender wise Age distribution\n\"\"\"\nsns.boxplot(x='sex',y='age',data=data)\nf= plt.figure(figsize=(12,5))\n\nax=f.add_subplot(121)\nsns.distplot(data[(data.sex == 'male')][\"age\"],color='b',ax=ax)\nax.set_title('Distribution of ages of male')\n\nax=f.add_subplot(122)\nsns.distplot(data[(data.sex == 'female')]['age'],color='r',ax=ax)\nax.set_title('Distribution of ages of female')\n\"\"\"\n* As you can see age distribution of male and female are almost same .\n\"\"\"\n\"\"\"\n# Age distribution of Smoker vs Non-Smoker\n\"\"\"\nsns.boxplot(x='smoker',y='age',data=data)\nf= plt.figure(figsize=(12,5))\n\nax=f.add_subplot(121)\nsns.distplot(data[(data.smoker == 'yes')][\"age\"],color='#b0b0b0',ax=ax)\nax.set_title('Distribution of ages of smoker')\n\nax=f.add_subplot(122)\nsns.distplot(data[(data.smoker == 'no')]['age'],color='#333ed6',ax=ax)\nax.set_title('Distribution of ages of non smoker')\n\"\"\"\n* As you can see there is slight change in distribution of smoker and non smoker and also we can see there is some interesting spike in % of age group between 18-22.\n\"\"\"\n\"\"\"\n# Smokers count by gender\n\"\"\"\nsns.catplot(x=\"smoker\", kind=\"count\",hue = 'sex',palette='GnBu',data=data)\n\"\"\"\n* There are more male smokers than female,but difference is not that big.\n* More non smokers patients than smokers patients .\n\"\"\"\n\"\"\"\n# Cost distribution of smokers Vs non smokers \n\"\"\"\nsns.boxplot(x='smoker',y='charges',palette='viridis',data=data)\nf= plt.figure(figsize=(12,5))\n\nax=f.add_subplot(121)\nsns.distplot(data[(data.smoker == 'yes')][\"charges\"],color='#b0b0b0',ax=ax)\nax.set_title('Distribution of charges of smoker')\n\nax=f.add_subplot(122)\nsns.distplot(data[(data.smoker == 'no')]['charges'],color='#333ed6',ax=ax)\nax.set_title('Distribution of charges of non smoker')\n\"\"\"\n* Smoking patients spend more \n\"\"\"\n\"\"\"\n# Charges of patients Age 18-22 of smokers Vs non-smokers\n\"\"\"\nsns.boxplot(x='smoker',y='charges',data=data[(data.age>=18)&(data.age<=22)])\n\"\"\"\n* As we can see, patients of age 18-22 smokers spend much more on treatment than non-smokers. Although we can see some outliers om non smokers this may be due to some serious disease.\n\"\"\"\n\"\"\"\n# Age vs charges of smokers\n\"\"\"\nsns.scatterplot(x=\"age\", y=\"charges\", data=data[data.smoker=='yes'],color='purple')\ng = sns.jointplot(x=\"age\", y=\"charges\", data=data[data.smoker=='yes'], kind=\"kde\", color=\"b\")\ng.plot_joint(plt.scatter, c=\"w\", s=30, linewidth=1, marker=\"+\")\ng.ax_joint.collections[0].set_alpha(0)\ng.set_axis_labels(\"age\", \"charges\");\nsns.jointplot(x=\"age\", y=\"charges\", data=data[data.smoker=='yes'], kind=\"kde\");\n\"\"\"\n# Age vs Charges of Non-smokers\n\"\"\"\nsns.scatterplot(x=\"age\", y=\"charges\", data=data[data.smoker=='no'],color='#82113a')\ng = sns.jointplot(x=\"age\", y=\"charges\", data=data[data.smoker=='no'], kind=\"kde\", color=\"#82113a\")\ng.plot_joint(plt.scatter, c=\"w\", s=30, linewidth=1, marker=\"+\")\ng.ax_joint.collections[0].set_alpha(0)\ng.set_axis_labels(\"age\", \"charges\");\nsns.jointplot(x=\"age\", y=\"charges\", data=data[data.smoker=='no'],color='#82113a', kind=\"kde\");\n\"\"\"\n* In case of non smokers charges increase with age ,  but in case of smokers there is no such dependency.\n\"\"\"\n\"\"\"\n# Bmi of Male Vs Female\n\"\"\"\nsns.boxplot(x='sex',y='bmi',palette='viridis',data=data)\nf= plt.figure(figsize=(12,5))\n\nax=f.add_subplot(121)\nsns.distplot(data[(data.sex == 'male')][\"bmi\"],color='b',ax=ax)\nax.set_title('Distribution of bmi of male')\n\nax=f.add_subplot(122)\nsns.distplot(data[(data.sex == 'female')]['bmi'],color='r',ax=ax)\nax.set_title('Distribution of bmi of female')\n\"\"\"\n* Distribution of bmi of male and female are normally distributed\n\"\"\"\nf= plt.figure(figsize=(12,5))\n\nax=f.add_subplot(121)\nsns.distplot(data[(data.smoker == 'yes')][\"bmi\"],color='#b0b0b0',ax=ax)\nax.set_title('Distribution of bmi of smoker')\n\nax=f.add_subplot(122)\nsns.distplot(data[(data.smoker == 'no')]['bmi'],color='#333ed6',ax=ax)\nax.set_title('Distribution of bmi of non smoker')\n\"\"\"\n* distribution of bmi of  smoker and non smoker are normally distributed\n\"\"\"\n\"\"\"\n# Patients Region wise\n\"\"\"\nsns.catplot(x=\"region\", kind=\"count\",palette='viridis',data=data)\nsns.catplot(x=\"region\", kind=\"count\",hue = 'sex',palette='viridis',data=data)\n\"\"\"\n# Bmi vs Charges\n\"\"\"\nsns.lmplot(x=\"bmi\", y=\"charges\",data=data);\n\"\"\"\n# Bmi vs Charges of smoker Vs non smoker\n\"\"\"\nsns.lmplot(x=\"bmi\", y=\"charges\", hue=\"smoker\", data=data, palette=\"Set1\")\nsns.lmplot(x=\"bmi\", y=\"charges\", hue=\"smoker\", col=\"sex\", data=data)\nsns.lmplot(x=\"bmi\", y=\"charges\", col=\"children\", data=data,aspect=.5)\ng = sns.jointplot(x=\"bmi\", y=\"charges\", data=data, kind=\"kde\", color=\"#4837cc\")\ng.plot_joint(plt.scatter, c=\"w\", s=30, linewidth=1, marker=\"+\")\ng.ax_joint.collections[0].set_alpha(0)\ng.set_axis_labels(\"bmi\", \"charges\")\n\"\"\"\n# Childrens Vs Charges\n\"\"\"\nsns.catplot(x=\"children\", kind=\"count\",palette='rainbow',data=data)\nsns.lmplot(x=\"children\", y=\"charges\",data=data)\nsns.lmplot(x=\"children\", y=\"charges\", hue='smoker',data=data)\n\"\"\"\n# Correlation matrix\n\"\"\"\nf, ax = plt.subplots(figsize=(10, 8))\ncorr = data.corr()\nsns.heatmap(corr)\n\"\"\"\n<font size=\"+3\" color='#1f0c75' ><b>Data Modelling and Evaluation <\/b><\/font>\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import linear_model\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import r2_score,mean_squared_error\n\"\"\"\n# Create dummy variables \n\"\"\"\n\n#sex\nle = LabelEncoder()\nle.fit(data.sex.drop_duplicates()) \ndata.sex = le.transform(data.sex)\n# smoker or not\nle.fit(data.smoker.drop_duplicates()) \ndata.smoker = le.transform(data.smoker)\n#region\nle.fit(data.region.drop_duplicates()) \ndata.region = le.transform(data.region)\ndata.head()\n\"\"\"\n# Train Test split\n\"\"\"\nx = data.drop(['charges','region'], axis = 1)\ny = data.charges\n\nx_train,x_test,y_train,y_test = train_test_split(x,y, random_state = 0)\n\"\"\"\n# Linear regression\n\"\"\"\nlreg = linear_model.LinearRegression()\nlreg.fit(x_train,y_train)\ny_train_pred = lreg.predict(x_train)\ny_test_pred = lreg.predict(x_test)\nlreg.score(x_test,y_test)\n\"\"\"\n# Polynomial Regression \n\"\"\"\ndegree=2\npolyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression())\npolyreg.fit(x_train,y_train)\ny_train_pred = polyreg.predict(x_train)\ny_test_pred = polyreg.predict(x_test)\npolyreg.score(x_test,y_test)\n\"\"\"\n# Decision Tree Regressor\n\"\"\"\ndt_regressor = DecisionTreeRegressor(random_state=0)\ncross_val_score(dt_regressor,x_train, y_train, cv=10).mean()\n\"\"\"\n# Random Forest Regressor\n\"\"\"\nRf = RandomForestRegressor(n_estimators = 100,\n                              criterion = 'mse',\n                              random_state = 1,\n                              n_jobs = -1)\nRf.fit(x_train,y_train)\nRf_train_pred = Rf.predict(x_train)\nRf_test_pred = Rf.predict(x_test)\n\n\nr2_score(y_test,Rf_test_pred)\n\"\"\"\n# Conclusion\n\n* Got maximum score of 0.88 from polynomial regression\n* Although random forest regressor performing good with an accuracy 0.86\n\"\"\"\n\"\"\"\n<font size=\"+1\" color=purple ><b> I hope you enjoyed this kernel ,also if you have any suggestions to improve my model ,then feel free to comment it down .<\/b><\/font>\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/i.pinimg.com\/originals\/71\/c0\/68\/71c068478e7499d73ec005eacbe42c10.gif\">\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '31dd832a2d0f7e'}"}
{"id":"46715","text":"\"\"\"\nUPDATE on V3:  \nAdded 2. Display an image for each shape\n\"\"\"\n\"\"\"\nThis kernel uses the following kernel code:\n* https:\/\/www.kaggle.com\/h4211819\/image-size-eda\n* https:\/\/www.kaggle.com\/yangsaewon\/basic-eda-train-test-image-distribution-check\n* https:\/\/www.kaggle.com\/kaerunantoka\/extract-image-features\n\nI think that this competition needs to be careful because the target is biased due to the shape of the image.  \nAlso, I think that the information of the image shape of the previous competition will be helpful, but because it can not be read from the kernel, I released the [dataset](https:\/\/www.kaggle.com\/currypurin\/diabetic-retinopathy-detection-image-size) and [discussion](https:\/\/www.kaggle.com\/c\/aptos2019-blindness-detection\/discussion\/99846).\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport sys\nimport os\nimport pickle\nfrom tqdm import tqdm_notebook as tqdm\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nprint(os.listdir('..\/input'))\nprint(os.listdir('..\/input\/diabetic-retinopathy-detection-image-size'))\n\"\"\"\n# 1. present competition\n\"\"\"\ntrain = pd.read_csv('..\/input\/aptos2019-blindness-detection\/train.csv')\ntest = pd.read_csv('..\/input\/aptos2019-blindness-detection\/test.csv')\nlen(train), len(test)\n#the func is from https:\/\/www.kaggle.com\/toshik\/image-size-and-rate-of-new-whale\ndef get_size_list(targets, dir_target):\n    result = list()\n    for target in tqdm(targets):\n        img = np.array(Image.open(os.path.join(dir_target, target+'.png')))\n        result.append(img.shape)\n    return result\n\n# the func is from https:\/\/www.kaggle.com\/kaerunantoka\/extract-image-features\ndef get_size(file_name_list, dir_target):\n    result = list()\n    #filename = images_path + filename\n    for file_name in tqdm(file_name_list):\n        st = os.stat(f'{dir_target}\/{file_name}.png')\n        result.append(st.st_size)\n    return result\ntrain['image_shape'] = get_size_list(train.id_code.tolist(),\n                                     dir_target='..\/input\/aptos2019-blindness-detection\/train_images')\ntest['image_shape'] = get_size_list(test.id_code.tolist(),\n                                    dir_target='..\/input\/aptos2019-blindness-detection\/test_images')\ntrain['image_size'] = get_size(train.id_code.tolist(),\n                               dir_target='..\/input\/aptos2019-blindness-detection\/train_images')\ntest['image_size'] = get_size(test.id_code.tolist(),\n                              dir_target='..\/input\/aptos2019-blindness-detection\/test_images')\nfor df in [train, test]:\n    df['height'] = df['image_shape'].apply(lambda x:x[0])\n    df['width'] = df['image_shape'].apply(lambda x:x[1])\n    df['width_height_ratio'] = df['height'] \/ df['width']\n    df['width_height_added'] = df['height'] + df['width']\ntrain.head()\ntrain.describe()\ntest.describe()\nfig = plt.figure(figsize=(16,10))\nplt.subplot(241)\nplt.hist(train['width'])\nplt.title(\"train width\")\nplt.xlim(200, 4500)\n\nplt.subplot(242)\nplt.hist(test['width'])\nplt.title(\"test width\")\nplt.xlim(200, 4500)\n\nplt.subplot(243)\nplt.hist(train['height'])\nplt.title(\"train height\")\nplt.xlim(200, 3100)\n\nplt.subplot(244)\nplt.hist(test['height'])\nplt.title(\"test height\")\nplt.xlim(200, 3100)\n\nplt.subplot(245)\nplt.hist(train['width_height_ratio'])\nplt.title(\"train width height ratio\")\nplt.xlim(0.6, 1.05)\n\n\nplt.subplot(246)\nplt.hist(test['width_height_ratio'])\nplt.title(\"test width height ratio\")\nplt.xlim(0.6, 1.05)\n\nplt.subplot(247)\nplt.hist(train['width_height_added'])\nplt.title(\"train width height added\")\n\nplt.subplot(248)\nplt.hist(test['width_height_added'])\nplt.title(\"train width height added\");\nsns.heatmap(train.corr(), cmap=plt.cm.Blues, annot=True);\n\"\"\"\n* Many feature seems to be correlated with the target.\n\"\"\"\ntrain_meta = train.groupby(['width', 'height', 'diagnosis']).agg({'diagnosis':'count'}).unstack('diagnosis').fillna(0)\ntrain_meta.columns = [f'{i[0]}_{i[1]}' for i in train_meta.columns]\ntrain_meta['train_count'] = train_meta.sum(axis=1)\n\ntest_meta = test.groupby(['width', 'height']).agg({'id_code':'count'}).rename(columns={'id_code':'pub_test_count'})\ncount_ratio = train_meta.join(test_meta, how='outer')\n\nfor i in range(5):\n    count_ratio.loc[:, f'{i}_ratio'] = count_ratio.iloc[:, i] \/ count_ratio['train_count']\n\ncount_ratio = count_ratio.fillna(0)\n\ncount_ratio = count_ratio.astype({'diagnosis_0': int, 'diagnosis_1': int, 'diagnosis_2': int,\n                                  'diagnosis_3': int, 'diagnosis_4': int})\ncount_ratio = count_ratio.astype({'train_count': int, 'pub_test_count': int})\n\ncount_ratio.reset_index(inplace=True)\ncount_ratio.set_index(['width', 'height', 'train_count', 'pub_test_count'], inplace=True)\ncount_ratio\n\"\"\"\n* Training data has different target distribution for each image shape.\n  * For example 1050x1050 is high ratio of class_0, 2136x3216 is high ratio of class_2\n* If we leave the image shape information in the preprocessed image, there is a possibility of overfitting, so be very careful.\n* Let's look at the images.\n\"\"\"\n\"\"\"\n# 2.Display an image for each shape\n\"\"\"\ndef im_show(height, width, num):\n    tmp = train[(train['width'] == width) & (train['height'] == height)].id_code\n    dir_target = '..\/input\/aptos2019-blindness-detection\/train_images'\n    id = tmp.values[num]\n    img = Image.open(os.path.join(dir_target, id +'.png'))\n    plt.imshow(img.resize((256, 256)))\n    plt.tick_params(bottom=False,\n                    left=False,\n                    right=False,\n                    top=False,\n                    labelbottom=False,\n                    labelleft=False,\n                    labelright=False,\n                    labeltop=False)\n    value = train.loc[train['id_code'] == id, :].values[0]\n    plt.title(f'({value[4]},{value[5]})->(256,256)\\n {id}, diagnosis:{value[1]}')\n\ndef five_img_plot(height, width):\n    print('-' * 10)\n    print(f'shape({height}, {width})')\n    plt.figure(figsize=(16, 4))\n    for i in range(5):\n        plt.subplot(1,5,i+1)\n        im_show(height, width, i)\n    plt.show()\nfive_img_plot(480, 640)\nfive_img_plot(614, 819)\nfive_img_plot(1050, 1050)\nfive_img_plot(1536, 2048)\nfive_img_plot(1736, 2416)\nfive_img_plot(1958, 2588)\nfive_img_plot(2588, 3388)\n\"\"\"\n* The proportion of black area and the tendency of brightness are also likely to be in each image shape.\n* I would like to update this point later.\n* ref : https:\/\/www.kaggle.com\/c\/aptos2019-blindness-detection\/discussion\/99846#575147\n\"\"\"\n\"\"\"\n# 3.previous competition\n\"\"\"\n\"\"\"\nThere are about 90,000 images of [the previous competition](https:\/\/www.kaggle.com\/c\/diabetic-retinopathy-detection) and Kernel can not read all the images. So I run the same code as above, and [dataset](https:\/\/www.kaggle.com\/currypurin\/diabetic-retinopathy-detection-image-size) made public.\n\"\"\"\npre_train = pd.read_csv('..\/input\/diabetic-retinopathy-detection-image-size\/pre_train_shape.csv')\npre_test = pd.read_csv('..\/input\/diabetic-retinopathy-detection-image-size\/pre_test_shape.csv')\n\nfor df in [pre_train, pre_test]:\n    df['width_height_ratio'] = df['height'] \/ df['width']\n    df['width_height_added'] = df['height'] + df['width']\nlen(pre_train), len(pre_test)\n\"\"\"\n* The number of images of the last competition is very large.\n\"\"\"\npre_train.head()\npre_test.head()\npre_train.describe()\nfig = plt.figure(figsize=(16,10))\nplt.subplot(241)\nplt.hist(pre_train['width'])\nplt.title(\"pre train width\")\nplt.xlim(200, 5500)\n\nplt.subplot(242)\nplt.hist(pre_test['width'])\nplt.title(\"pre test width\")\nplt.xlim(200, 5500)\n\nplt.subplot(243)\nplt.hist(pre_train['height'])\nplt.title(\"pre train height\")\nplt.xlim(200, 4000)\n\nplt.subplot(244)\nplt.hist(pre_test['height'])\nplt.title(\"pre test height\")\nplt.xlim(200, 4000)\n\nplt.subplot(245)\nplt.hist(pre_train['width_height_ratio'])\nplt.title(\"pre train width height ratio\")\nplt.xlim(0.6, 1.05)\n\n\nplt.subplot(246)\nplt.hist(pre_test['width_height_ratio'])\nplt.title(\"pre test width height ratio\")\nplt.xlim(0.6, 1.05)\n\nplt.subplot(247)\nplt.hist(pre_train['width_height_added'])\nplt.title(\"pre train width height added\")\n\nplt.subplot(248)\nplt.hist(pre_test['width_height_added'])\nplt.title(\"pre train width height added\");\npre_train.drop('channel', axis=1, inplace=True)\npre_test.drop('channel', axis=1, inplace=True)\nplt.rcParams[\"font.size\"] = 14\n# pre_train.rename(columns={'level': 'diagnosis'}, inplace=True)\nplt.figure(figsize=(16,8))\nplt.subplot(121)\nsns.heatmap(pre_train.corr(), cmap=plt.cm.Blues, annot=True)\nplt.title('previous_competition')\n\nplt.subplot(122)\nsns.heatmap(train.corr(), cmap=plt.cm.Blues, annot=True)\nplt.title('this_competition')\n\nplt.tight_layout()\npre_train_meta = pre_train.groupby(['width', 'height', 'level']).agg({'level':'count'}).unstack('level').fillna(0)\npre_train_meta.columns = [f'{i[0]}_{i[1]}' for i in pre_train_meta.columns]\npre_train_meta['train_count'] = pre_train_meta.sum(axis=1)\n\npre_test_meta = pre_test.groupby(['width', 'height']).agg({'image':'count'}).rename(columns={'image':'pub_test_count'})\npre_count_ratio = pre_train_meta.join(pre_test_meta, how='outer')\n\nfor i in range(5):\n    pre_count_ratio.loc[:, f'{i}_ratio'] = pre_count_ratio.iloc[:, i] \/ pre_count_ratio['train_count']\n\npre_count_ratio = pre_count_ratio.fillna(0)\n\npre_count_ratio = pre_count_ratio.astype({'level_0': int, 'level_1': int, 'level_2': int, 'level_3': int, 'level_4': int})\npre_count_ratio = pre_count_ratio.astype({'train_count': int, 'pub_test_count': int})\n\npre_count_ratio.reset_index(inplace=True)\npre_count_ratio.set_index(['width', 'height', 'train_count', 'pub_test_count'], inplace=True)\npre_count_ratio\n\"\"\"\n# 4.Number of image and ratio by image shape in previous and present competition\n\"\"\"\nplt.rcParams[\"font.size\"] = 13\nplt.figure(figsize=(12, 8))\nsns.heatmap(pre_count_ratio.iloc[:, 5:], cmap=plt.cm.Blues)\nplt.xlabel('target')\nplt.ylabel('width - height - number_of_train - number_of_public_test')\nplt.title('Number of image and ratio by image shape in previous competition')\nplt.xticks([0.5, 1.5, 2.5, 3.5, 4.5], ['0',  '1', '2', '3', '4'])\nfor i, j in itertools.product(range(5), range(len(pre_count_ratio))):\n    train_count = pre_count_ratio.index[j][2]\n    if train_count != 0:\n        ratio = np.int(np.round(pre_count_ratio.iloc[j, i+5] * 100))\n        count = pre_count_ratio.iloc[j, i]\n        plt.text(i+0.2, j+0.8, f'{count:>4}', color='k'if ratio < 65 else \"w\")\n        plt.text(i+0.5, j+0.8, f'{ratio:>3}%', color='k'if ratio < 65 else \"w\")\n    elif train_count == 0:\n        plt.text(i+0.5, j+0.8, '-', color='k')\nplt.show()\n\nplt.figure(figsize=(12, 8))\nsns.heatmap(count_ratio.iloc[:, 5:], cmap=plt.cm.Blues)\nplt.xlabel('target')\nplt.ylabel('width - height - number_of_train - number_of_public_test')\nplt.title('Number of image and ratio by image shape in present competition')\nfor i, j in itertools.product(range(5), range(len(count_ratio))):\n    train_count = count_ratio.index[j][2]\n    if train_count != 0:\n        ratio = np.int(np.round(count_ratio.iloc[j, i+5] * 100))\n        count = count_ratio.iloc[j, i]\n        plt.text(i+0.2, j+0.8, f'{count:>4}', color='k'if ratio < 65 else \"w\")\n        plt.text(i+0.5, j+0.8, f'{ratio:>3}%', color='k'if ratio < 65 else \"w\")\n    elif train_count == 0:\n        plt.text(i+0.5, j+0.8, '-', color='k')\n    plt.xticks([0.5, 1.5, 2.5, 3.5, 4.5], ['0',  '1', '2', '3', '4'])\nplt.show();\n\"\"\"\n* The bias of the class by the shape of the train image was small in the last competition, but this time the competition is not.\n* In the previous competition, the ranking change on the public and private leaderboard is not large.\n* I\u00a0think that this bias may cause a large shakeup.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5602dd1764fd33'}"}
{"id":"30515","text":"import numpy as np   \nimport pandas as pd    \nimport matplotlib.pyplot as plt \n%matplotlib inline \nimport seaborn as sns\nfrom scipy.stats import zscore\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nimport time\ndata = pd.read_csv('vehicle.csv')\ndata.head()\ndata.shape\ndata.info()\n\"\"\"\n## Data pre-processing\n\"\"\"\n# Check number of not a number values\ndata.isna().sum()\ndata[data['radius_ratio'].isna() == True]\ndata['class'].value_counts()\n# Creating a copy of dataframe to have class variable with us before operating on NaN values\nimport copy\ndata_copy = copy.deepcopy(data)\n# Convert class variable to values\nfrom sklearn.preprocessing import LabelEncoder\ndata_copy[\"class\"] = LabelEncoder().fit_transform(data_copy[\"class\"])\ndata_copy.head()\ndata_copy.describe().transpose()\n# Observation: as outliers present, replace nan values with median\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(missing_values=np.nan, strategy='median')\nimputer = imputer.fit(data_copy)\ndata_copy = pd.DataFrame(np.array(imputer.transform(data_copy)),columns=data_copy.columns)\ndata_copy\n\"\"\"\n## Understanding the attributes\n\"\"\"\n# Understanding the attributes - Find relationship between different\n# attributes (Independent variables) and choose carefully which all\n# attributes have to be a part of the analysis and why\n# 2. Relationship between var\ndata_copy.corr()\ncorrelation_matrix = data_copy.corr()\nfig,ax = plt.subplots(figsize=(20,20)) \nsns.heatmap(correlation_matrix, annot=True, ax=ax)  \nplt.xticks(range(len(correlation_matrix.columns)), correlation_matrix.columns) \nplt.yticks(range(len(correlation_matrix.columns)), correlation_matrix.columns) \n\"\"\"\n#### Remove columns if we can \n\"\"\"\n# For multicollinearity lets remove columns having corr of 95% pr.axis_rectangularity,scaled_variance,scaled_variance.1\n# 99 % corelation between scatter_ratio and scaled_variance\n# There are Attributes which are directly not related to class but can not remove these columns directly as they can be useful while doing PCA\ndata_copy.drop(['pr.axis_rectangularity','scaled_variance','scaled_variance.1'],axis=1,inplace=True)\ndata_copy.shape\n# draw pair plot which wil lhelp to get idea of covariance matrix \nsns.pairplot(data_copy,diag_kind='kde',size=4)\nX=data_copy.drop('class',axis=1)\nY=data_copy['class']\n# Lets scale our data\nX_Scaled=X.apply(zscore)\nX_Scaled.head()\n\"\"\"\n## Split the data into train and test\n\"\"\"\ndef get_SVM_Accuracy(X):\n    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=1)\n    model = SVC()\n    start_time = time.time() \n    model.fit(X_train, y_train)\n    elapsed_time = time.time() - start_time\n    return model.score(X_train,y_train)*100,model.score(X_test,y_test)*100,elapsed_time\n\"\"\"\n## Train a Support vector machine\n\"\"\"\nBefore_PCA_train_acc,Before_PCA_test_acc,time_taken = get_SVM_Accuracy(X_Scaled)\nprint(Before_PCA_train_acc)\nprint(Before_PCA_test_acc)\nprint(time_taken)\ndata_copy.shape\n\"\"\"\n## Perform K-fold cross validation\n\"\"\"\n#Apply k fold cross validation\n#using default genral practice 10 kfolds\n# Common k fold function\ndef get_kFold_Results(X):\n    Y = data_copy['class']\n    num_folds = 10\n    seed = 7\n    kfold = KFold(n_splits=num_folds, random_state=seed)\n    model = SVC()\n    results = cross_val_score(model, X, Y, cv=kfold)\n    print(results)\n    print(\"Accuracy: %.2f%% (%.2f%%)\" % (results.mean()*100.0, results.std()*100.0))\n    return results\ndata_copy.head()\nbeforePCACV_results = get_kFold_Results(X_Scaled)\n\"\"\"\n## Use PCA from Scikit learn\n\"\"\"\n#Apply PCA\ncovMatrix = np.cov(X_Scaled,rowvar=False)\nprint(covMatrix)\npca = PCA()\npca.fit(X_Scaled)\n# eigen value\nprint(pca.explained_variance_)\n# eigen ratio\nprint(pca.explained_variance_ratio_)\nplt.bar(list(range(1,16)),pca.explained_variance_ratio_,alpha=0.5, align='center')\nplt.ylabel('Variation explained')\nplt.xlabel('eigen Value')\nplt.show()\nplt.step(list(range(1,16)),np.cumsum(pca.explained_variance_ratio_), where='mid')\nplt.ylabel('Cum of variation explained')\nplt.xlabel('eigen Value')\nplt.show()\n# Ploting \nplt.figure(figsize=(10 , 5))\nplt.bar(range(1, pca.explained_variance_ratio_.size + 1), pca.explained_variance_ratio_, alpha = 0.5, align = 'center', label = 'Individual explained variance')\nplt.step(range(1, pca.explained_variance_ratio_.size + 1), np.cumsum(pca.explained_variance_ratio_), where='mid', label = 'Cumulative explained variance')\nplt.ylabel('Explained Variance Ratio')\nplt.xlabel('Principal Components')\nplt.legend(loc = 'best')\nplt.tight_layout()\nplt.show()\n\"\"\"\n## Use 7 Principal components\n\"\"\"\npca7 = PCA(n_components=7)\npca7.fit(X_Scaled)\nX_Scaled_PCA = pca7.transform(X_Scaled)\nX_Scaled_PCA\nAfter_PCA_train_acc,After_PCA_test_acc,time_taken = get_SVM_Accuracy(X_Scaled_PCA)\nprint(After_PCA_train_acc)\nprint(After_PCA_test_acc)\nprint(time_taken)\n\"\"\"\n## Compare the accuracy scores and cross validation scores\n\"\"\"\nBefore_PCA_train_acc,Before_PCA_test_acc,time_taken = get_SVM_Accuracy(X_Scaled)\nprint(Before_PCA_train_acc)\nprint(Before_PCA_test_acc)\nprint(time_taken)\nAfter_PCA_train_acc,After_PCA_test_acc,time_taken = get_SVM_Accuracy(X_Scaled_PCA)\nprint(After_PCA_train_acc)\nprint(After_PCA_test_acc)\nprint(time_taken)\nbeforePCACV_results = get_kFold_Results(X_Scaled)\nafterPCACV_results = get_kFold_Results(X_Scaled_PCA)\n# Summary:\n# After PCA we can see drop in accuracy as we loose information(from attributes 6 to 7 Principal components)\n# Although there is no significant gain in\n# Computation time as well \n# before PCA time taken is 0.0267 \n# After PCA tie taken in fitting the SVC model 0.0209\n# with confidance interval of 95 % we can say that with using PCA acc 91.48% with std deviation 2.44% will range \n# from 86.6 to  96.36","meta":"{'source': 'AI4Code', 'id': '382c427f87747d'}"}
{"id":"2358","text":"# 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 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\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf=pd.read_csv(\"..\/input\/factors-affecting-campus-placement\/Placement_Data_Full_Class.csv\")\ndf.head()\n# information of the Dataset\ndf.info()\n# check null values in dataset\ncount_missing=df.isnull().sum()\npercent_missing=count_missing*100\/df.shape[0]\nmissing_value=pd.DataFrame({'Count_Missing':count_missing,\n                            'percent_missing':percent_missing})\nmissing_value\n#Here we can see 31% missing value in salary column\n\"\"\"\n## 1. In placement How many percentage of Male or Female?\n\"\"\"\nplt.figure(figsize=(12,7))\ndata=df.gender.value_counts()\nlabels=['Male','Female']\nplt.title(\"percentage of Male or Female\",fontsize=18)\nplt.pie(data=data,x=data.values,autopct=\"%.2f%%\",labels=labels)\nplt.show()\n\"\"\"\n## 2. In placement How many no of male or female students?\n\"\"\"\nplt.figure(figsize=(12,7))\nax=sns.countplot(x=\"gender\",data=df)\nplt.title(\"Gender wise students\",fontsize=20)\n\nplt.xlabel(\"Gender\",fontsize=18)\nplt.ylabel(\"Count\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\n\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n\"\"\"\n## 3. student Belong which fields in 12th\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"hsc_s\",data=df)\nplt.title(\"student Belong which fields in 12th\",fontsize=20)\n\nplt.xlabel(\"Fields\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n\"\"\"\n## 4 student complete degree in which field\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"degree_t\",data=df)\nplt.title(\"complete Degree in field\",fontsize=20)\n\nplt.xlabel(\"Degree\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n\"\"\"\n## 5. student specialization in which field\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"specialisation\",data=df)\nplt.title(\"student Belong which specialisation \",fontsize=20)\n\nplt.xlabel(\"specialisation \",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n\"\"\"\n## 6.student Belong which specialisation Gender wise\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"specialisation\",data=df,hue=df.gender)\nplt.title(\"student Belong which specialisation Gender wise\",fontsize=20)\n\nplt.xlabel(\"specialisation \",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\nplt.legend(fontsize=22)\nplt.show()\n\"\"\"\n## 7. In placement how many student work experience?\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"workex\",data=df)\nplt.title(\"Student work experience or not\",fontsize=20)\n\nplt.xlabel(\"Experience\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n    \n\"\"\"\n## 8 No of Male or female student work experience\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"workex\",data=df,hue=df.gender)\nplt.title(\"Student work experience or not gender wise\",fontsize=20)\n\nplt.xlabel(\"Experience\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\nplt.legend(fontsize=22)\nplt.show()\n\"\"\"\n## 9.How many no. of student placed or not\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"status\",data=df)\nplt.title(\"NO. of student placed or not\",fontsize=20)\n\nplt.xlabel(\"Placed or not\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n\nplt.show()\n\"\"\"\n## 10.How many no. of student placed or not gender wise\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"status\",data=df,hue=df.gender)\nplt.title(\"NO. of Male or Female student placed or not\",fontsize=20)\n\nplt.xlabel(\"Placed or not\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n    \nplt.legend(fontsize=22)\nplt.show()\n\"\"\"\n## 11 How many fresher or experience student placed\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"status\",data=df,hue=df.workex)\nplt.title(\"NO. of student placed or not\",fontsize=20)\n\nplt.xlabel(\"Placed or not\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\n    \nplt.legend(fontsize=22)\nplt.show()\n\"\"\"\n## 12 which category student placed or not\n\"\"\"\nplt.figure(figsize=(10,7))\nax=sns.countplot(x=\"degree_t\",data=df,hue=df.status)\nplt.title(\"Category wise no. of student placed or not\",fontsize=20)\n\nplt.xlabel(\"Placed or not\",fontsize=18)\nplt.ylabel(\"No of student\",fontsize=18)\n\nplt.xticks(fontsize=15)\nplt.yticks(fontsize=15)\nfor p in ax.patches:\n    ax.text(p.get_x() + p.get_width()\/2., p.get_height(), '%d'% int(p.get_height()),\n           fontsize=12,color='blue',ha='center',va='bottom')\nplt.legend(fontsize=22)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '047e47917d41a0'}"}
{"id":"29211","text":"# 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\n\"\"\"\n# Introduction\n\nData sources from: [the future 50 from 2020](https:\/\/www.restaurantbusinessonline.com\/future-50-2020):\n\n![jonathan-borba-8l8Yl2ruUsg-unsplash (1).jpg](attachment:a3d3676e-708e-4fe2-8d7f-a06102d21ec7.jpg)\n\"\"\"\n#Libraries\n#Plotly <3\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\nimport plotly.io as pio\n\npio.templates.default = \"seaborn\"\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n#Reading the data\n\ntop250_data = pd.read_csv('\/kaggle\/input\/restaurant-business-rankings-2020\/Top250.csv')\nfuture50_data = pd.read_csv('\/kaggle\/input\/restaurant-business-rankings-2020\/Future50.csv')\nindependence100_data = pd.read_csv('\/kaggle\/input\/restaurant-business-rankings-2020\/Independence100.csv')\n\"\"\"\n# Exploration Data Analysis\n****\n\nFirst, let's understand a little bit about each dataset.\n1. Top 250 restaurants\n2. Future 50 restaurants\n3. Independent 100 restaurants\n\"\"\"\n\"\"\"\n## Top 250 Restaurants\n****\n\"\"\"\nindependence100_data['id'] = 'ind100'\ntop250_data['id'] = 'top250'\nfuture50_data['id']='fut50'\n\n#Transforming the string YOY data to numbers\ntop250_data['YOY_Sales_numbers'] = [float(i[:-1]) for i in top250_data['YOY_Sales']]\ntop250_data['YOY_Units_numbers'] = [float(i[:-1]) for i in top250_data['YOY_Units']]\ntop250_data['Sales_per_units'] = top250_data['Sales']\/top250_data['Units']\ntop250_data['Segment'] = [x.split('&')[0] if len(x.split('&')) >= 2 else 'Undefined' for x in top250_data['Segment_Category']]\ntop250_data['Category'] = [x.split('&')[1].replace(' ', '') if len(x.split('&')) >= 2 else x.replace(' ', '') for x in top250_data['Segment_Category']]\n\ntop250_data = top250_data.drop(['Content','YOY_Sales','Headquarters','YOY_Units'],axis=1).copy()\n\nindependence100_data['Sales Divided'] = round(independence100_data['Sales']\/10**6,2)\n\n#Let's Check the values from clusters E and then clusters D,C,B,A,S\nlower200 = top250_data[top250_data['Rank'] > 50].copy()\ntop50 = top250_data[top250_data['Rank'] <= 50].copy()\n\nsub = {\n'Asian\/Noodle':'Asian',\n'Italian\/Pizza':'Pizza',\n'CoffeeCafe':'Cafe',\n'BakeryCafe':'Cafe',\n'FamilyCasual':'Family',\n'FamilyStyle':'Family',\n'Burger':'Sandwich',\n'FrozenDesserts':'Frozen Desserts',\n'VariedMenu':'Varied Menu'\n}\ntop250_data['Category'] = top250_data['Category'].replace(sub)\n\n\n#Features that will be appended\nfeat = ['Restaurant','Sales','id']\n\n#Auxiliar dataframe\nmy_data = independence100_data[['Restaurant','Sales Divided','id']].copy()\nmy_data['Sales'] = independence100_data['Sales Divided']\n\n#Setting a table with all restaurants with the name of the restaurant and the sales\n#\n# And a feature that tells from which data it came from\nall_restaurants = my_data[feat].copy().append(future50_data[feat].copy()).append(top250_data[feat].copy())\n#This is how the new data looks like after changing some formatting\ntop250_data.head()\ntop250_data.describe(include='all')\nfig = px.histogram(top250_data, x = 'Sales',labels = {\n    'count':'Count',\n    'Sales':'Sales ($000,000)'\n})\n\nfig.update_layout(\ntitle = dict(\n    text = 'Sales distribution',\n    xref = 'paper',\n    font_family = \"Arial Black\",\n    x = 0.0))\nfig.update_yaxes(title='Count', visible=True)\nfig.show()\n\"\"\"\n### Some notations that will be used along this notebook\n\nAs we can see, most of the restaurants have sales lower than 100k million dollars, so I think it is convinient that we cluster this data according to this huge difference.\nFor that, I am going to be refering the bottom 200 from the top 250 restaurants as **B200** and the top 50 Restaurants as **Top 50**\n\"\"\"\n#Let's check the distribution of sales by unity\n\nsales_mean = top250_data['Sales_per_units'].mean()\nfig = px.box(top250_data,y='Sales_per_units',\n                   labels = {\n                      'Sales_per_units':'Sales (in millions) per Units',\n                  },title = 'Boxplot of the sales per units from the top 250 restaurants')\n\nfig.update_layout(\n    title = dict(\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n    hovermode='y unified',\n    yaxis_title=\"Count\",\n    legend_title=\"Segment\"\n)\n\n# fig.add_shape( # add a horizontal \"target\" line\n#     type=\"line\", line_color=\"salmon\", line_width=3, opacity=1, line_dash=\"dot\",\n#     x0=0, x1=1, xref=\"paper\", y0=sales_mean, y1=sales_mean, yref=\"y\"\n# )\n\nfig.update_yaxes(\n    title = \"Sales (in millions) per units\",\n    tickprefix = 'U$',\n    ticksuffix = ' M'\n)\n\n\nfig.show()\n#Let's check the distribution of sales by unity\nfig = make_subplots(4, 1,subplot_titles=['Top 50 and B200','Top 50 Restaurants', 'B200'],\n                    specs = [[{\"rowspan\": 2}],\n                            [None],\n                            [{}],\n                            [{}]]\n)\n\nfig.add_trace(go.Box(x = top50['Sales'], name='Top 50'), row = 1, col = 1)\nfig.add_trace(go.Box(x = lower200['Sales'], name='B200'), row = 1, col = 1)\nfig.add_trace(go.Box(x = top250_data['Sales'], name='Top 250'), row = 1, col = 1)\n\nfig.add_trace(go.Box(x = top50['Sales'], name='Top 50'), row = 3, col = 1)\nfig.add_trace(go.Box(x = lower200['Sales'], name='B200'), row = 4, col = 1)\n\n\nfig.update_layout(\n    title = dict(\n    font_family = \"Arial Black\",\n    text = 'Sales in millions grouped by ranks',\n    xref = 'paper',\n    x = 0),\n    hovermode='x unified',\n    legend_title=\"Slice\",\n)\n\n\nfig.show()\n\"\"\"\nAs we can see, the sales from the top 250 restaurants have a lot of outliers and maybe clustering it might help with understanding it.\n\"\"\"\nlabels = top250_data['Segment'].unique()\n\nfig = make_subplots(1, 3,subplot_titles=['B200', 'Top 50 Restaurants','Top 250 Restaurants'], specs=[[{\"type\": \"pie\"}, {\"type\": \"pie\"}, {\"type\": \"pie\"}]])\n\nfig.add_trace(go.Pie(labels=labels, values= list(lower200['Segment'].value_counts())), 1, 1)\nfig.add_trace(go.Pie(labels=labels, values= list(top50['Segment'].value_counts())), 1, 2)\nfig.add_trace(go.Pie(labels=labels, values= list(top250_data['Segment'].value_counts())), 1, 3)\n\nfig.update_layout(\n    title = dict(\n        font_family = \"Arial Black\",\n        xref = 'paper',\n        x = 0\n    ),\n    title_text='Restaurants Count grouped by Segment')\nfig.show()\nlabels = top250_data['Category'].unique()\n\nfig = make_subplots(1, 3,subplot_titles=['B200', 'Top 50','Top 250 Restaurants'], specs=[[{\"type\": \"domain\"}, {\"type\": \"pie\"}, {\"type\": \"pie\"}]])\n\nfig.add_trace(go.Pie(labels=labels, values= list(lower200['Category'].value_counts())), 1, 1)\nfig.add_trace(go.Pie(labels=labels, values= list(top50['Category'].value_counts())), 1, 2)\nfig.add_trace(go.Pie(labels=labels, values= list(top250_data['Category'].value_counts())), 1, 3)\nfig.update_layout(\n    title = dict(\n        font_family = \"Arial Black\",\n        xref = 'paper',\n        x = 0\n    ),\n    title_text='Restaurants Count grouped by by Category')\nfig.show()\n\"\"\"\n## Future 50\n****\n\"\"\"\nfuture50_data['YOY_Sales_numbers'] = [float(i[:-1]) for i in future50_data['YOY_Sales']]\nfuture50_data['YOY_Units_numbers'] = [float(i[:-1]) for i in future50_data['YOY_Units']]\nfuture50_data.head()\nfuture50_data.describe(include = 'all')\n\n# fig = px.pie(future50_data, names = 'Franchising',title= \")\n\nfig = go.Figure(go.Pie(\n    labels = future50_data['Franchising'],\n    hovertemplate = '%{label}<extra><\/extra>'\n))\n\nfig.update_layout(\n    title = dict(\n    text = 'Is the restaurant franchised?',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x=0),\n    \n)\n\n\nfig.show()\nfig = px.histogram(future50_data,x = 'Sales', marginal=\"box\")\n\nfig.update_layout(\n    title = dict(\n    text = 'Sales Distribution',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n    hovermode='x unified'\n)\n                   \nfig.update_xaxes(\n    tickprefix = \"U$\",\n    ticksuffix = ' M'\n)\n\nfig.show()\n#Let's check the distribution of sales by unity\nfig = make_subplots(4, 1,subplot_titles=['Future 50 Restaurants and B200', 'Future 50 Restaurants','B200'],\n                    specs = [[{\"rowspan\": 2}],\n                            [None],\n                            [{}],\n                            [{}]], vertical_spacing = 0.2)\n\nfig.add_trace(go.Box(x = future50_data['Sales'], name='Future 50 Restaurants'), row = 1, col = 1)\nfig.add_trace(go.Box(x = lower200['Sales'], name='Bottom 200'), row = 1, col = 1)\n\nfig.add_trace(go.Box(x = future50_data['Sales'], name='Future 50 Restaurants'), row = 3, col = 1)\n\nfig.add_trace(go.Box(x = lower200['Sales'], name='B200'), row = 4, col = 1)\nfig.update_layout(\n    title = dict(\n        text = 'Comparisson between the future 50 restaurants and the bottom 200',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n    hovermode='x unified',\n    legend_title=\"Segment\",\n)\n\nfig.update_xaxes(\ntickprefix = 'U$',\nticksuffix = ' M')\n\nfig.show()\n\nfuture50_data['Sales_after_10_years'] = future50_data['Sales']*(future50_data['YOY_Sales_numbers']*10**(-2) + 1)**10\nlower200['Sales_after_10_years'] = lower200['Sales']*(lower200['YOY_Sales_numbers']*10**(-2) + 1)**10\nlower200['id'] = 'low200'\n\nfeat = ['Restaurant','Sales_after_10_years','id','YOY_Sales_numbers','Sales']\ndf_joined = pd.concat([lower200[feat], future50_data[feat]])\n\ndf_joined.sort_values(by = 'Sales_after_10_years', ascending = False).head(10).reset_index()\n\"\"\"\n### Expected sales of the restaurants over 10 years (Given that the YOY is constant)\n\nThe formula used to get those results are:\n\n$$\n\\text{Sales after 10 years} = \\text{Sales}(1 + \\text{YOYSales})^{10} \\quad \\quad 0 \\leq \\text{YOYSales}\\leq 1\n$$\n\nGiven $S=$ Sales, $i=$ YOYSales, $n=$ number of years \n\nAnd the formula I used to get results by year is:\n\n$$\n\\begin{aligned} \n    S_0 &= \\text{Inicial Sales}\\\\\n    S_n &= S_{n-1} (1 + i)\n\\end{aligned}\n$$\n\nThe results below are very innacurate, given the depth of the data we have in hands and the overall chaotic nature of economy. However, it is still very cool to see how the data would look like in those hypothetical scenarios.\n\n(Any help in improving this part of the notebook is very welcomed)\n\"\"\"\nfig = px.bar(df_joined.sort_values(by = 'Sales_after_10_years', ascending = False).head(10), color = 'id',x='Restaurant', y = 'Sales_after_10_years')\n\nfig.update_layout(\n    title = dict(\n        text = 'Top 10 Restaurants after 10 years',\n        font_family = 'Arial Black',\n        xref = 'paper',\n        x = 0),     \n    legend = dict(\n        title = 'Original dataset'\n  ))\n\nfig.update_xaxes(categoryorder = 'total descending')\n\nfig.update_yaxes(title = 'Sales prediction after 10 years')\n\nfig.for_each_trace(lambda trace: trace.update(name=\"B200\") if trace.name == \"low200\" else (trace.update(name=\"Future 50\")),)\nfig.show()\n\"\"\"\n##\n\"\"\"\ntop10_after_10 = df_joined.sort_values(by = 'Sales_after_10_years', ascending = False).head(10).reset_index().copy()\n\n\nfig = go.Figure()\n\nx = np.arange(2020,2030,1)\ny = np.zeros(10)\n\nfor i in range(10):\n    y[0] = top10_after_10['Sales'][i]\n    for j in range(9):\n        y[j+1] = y[0]*((top10_after_10['YOY_Sales_numbers'][i]*(10**(-2)) + 1)**(j+1))\n    if  top10_after_10['id'][i] == 'fut50':\n        fig.add_trace(go.Scatter(\n                x=x, y=y,name = top10_after_10['Restaurant'][i], line_color = '#4287f5',legendgroup=\"Fut50\",\n            ))\n    else:\n        fig.add_trace(go.Scatter(\n                x=x, y=y,name = top10_after_10['Restaurant'][i], line_color = '#64b564',legendgroup=\"Bott200\"\n            ))\n        \nfig.update_layout(\n    title = dict(\n    text = 'Increase in sales given constant YOY sales',\n    font_family = 'Arial Black',\n    xref = 'paper',\n    x = 0),\n    legend_title = 'Restaurants \\n(Blue: Future 50 | Green:B200)'\n)\n\nfig.update_xaxes(\ntitle = 'Years',\ndtick = 1)\n\nfig.update_yaxes(\ntitle = 'Sales in millions',\n    tickprefix = \"U$\")\n\n\nfig.show()\n\"\"\"\n### Random YOY (Normal)\n\nThe YOY of each restaurant was set as a random variable normally distributed with mean equal to the inicial YOY and the variation equal to 1.\n\nIn the code bellow you can change the number of restaurants analised. (currently n_restaurants = 20)\n\"\"\"\ntop10_after_10 = df_joined.sort_values(by = 'Sales_after_10_years', ascending = False).reset_index().copy()\n\nn_restaurants = 20\nfig = go.Figure()\n\nx = np.arange(2020,2030,1)\ny = np.zeros(n_restaurants)\n\nfor i in range(n_restaurants):\n    y[0] = top10_after_10['Sales'][i]\n    for j in range(n_restaurants-1):\n        y[j+1] = y[0]*((np.random.normal(top10_after_10['YOY_Sales_numbers'][i],scale=1)*(10**(-2)) + 1)**(j+1))\n    if  top10_after_10['id'][i] == 'fut50':\n        fig.add_trace(go.Scatter(\n                x=x, y=y,name = top10_after_10['Restaurant'][i], line_color = '#4287f5',legendgroup=\"Fut50\",\n            ))\n    else:\n        fig.add_trace(go.Scatter(\n                x=x, y=y,name = top10_after_10['Restaurant'][i], line_color = '#64b564',legendgroup=\"Bott200\"\n            ))\n        \nfig.update_layout(\n    title = dict(\n    text = 'Increase in sales given random YOY sales',\n    font_family = 'Arial Black',\n    xref = 'paper',\n    x = 0),\n    legend_title = 'Restaurants \\n(Blue: Future 50 | Green:B200)'\n)\n\nfig.update_xaxes(\ntitle = 'Years',\ndtick = 1)\n\nfig.update_yaxes(\ntitle = 'Sales in millions',\n    tickprefix = \"U$\")\n\n\nfig.show()\n\"\"\"\n## Independent 100 Restaurants\n****\n\"\"\"\nindependence100_data['State'].unique()\n\nindependence100_data['State'] = independence100_data['State'].replace({\n    'N.Y.':'NY',\n    'Fla.':'FL',\n    'D.C.':'DC',\n    'Ill.':'IL',\n    'Nev.':'NV',\n    'N.C.':'NC',\n    'Ind.':'IN',\n    'Texas':'TX',\n    'Pa.':'PA',\n    'Calif.':'CA',\n    'Ga.':'GA',\n    'Mich.':'MI',\n    'Mass.':'MA',\n    'Ore.':'OR',\n    'N.J.':'NJ',\n    'Fla. ':'FL',\n    'Tenn.':'TN',\n    'Colo.':'CO',\n    'Va.':'VA'\n})\nindependence100_data.head()\nindependence100_data.describe(include = 'all')\nfig = px.box(independence100_data, y='Sales Divided', x='State')\n\nfig.update_layout(\ntitle = dict(\ntext = 'Sales per States',\nfont_family = 'Arial Black',\nxref = 'paper',\nx = 0))\n\nfig.update_yaxes(\ntitle = \"Sales\",\n    tickprefix = \"U$\",\n    ticksuffix = ' M')\n\nfig.show()\nfig = px.box(independence100_data, y='Sales Divided', x='City')\n\nfig.update_layout(\ntitle = dict(\ntext = 'Sales per City',\nfont_family = 'Arial Black',\nxref = 'paper',\nx = 0))\n\nfig.update_yaxes(\ntitle = \"Sales\",\n    tickprefix = \"U$\",\n    ticksuffix = ' M')\nfig.update_xaxes(\ntitle = 'Cities')\nfig.show()\nfig = px.histogram(independence100_data,y = 'Average Check', marginal=\"box\")\n\nfig.update_layout(\n    title = dict(\n    text = 'Avarage Check Distribution',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n)\n\nfig.update_yaxes(\n    tickprefix = \"U$\",\n    ticksuffix = ' M'\n)\nfig.show()\n#Let's check the distribution of sales by unity\nfig = make_subplots(4, 1,subplot_titles=['Independent 100 Restaurants and B200', 'Independent 100 Restaurants','B200'],\n                            specs = [[{\"rowspan\": 2}],\n                            [None],\n                            [{}],\n                            [{}]], vertical_spacing = 0.2)\n\nfig.add_trace(go.Box(x = independence100_data['Sales Divided'], name='Independent 100 Restaurants'), row = 1, col = 1)\nfig.add_trace(go.Box(x = lower200['Sales'], name='B200'), row = 1, col = 1)\n\nfig.add_trace(go.Box(x = independence100_data['Sales Divided'], name='Independent 100 Restaurants'), row = 3, col = 1)\n\nfig.add_trace(go.Box(x = lower200['Sales'], name='B200 '), row = 4, col = 1)\nfig.update_layout(\n    title = dict(\n    text =  'Comparisson of sales between the independet 100 restaurants and the B200',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n    hovermode='x unified',\n    yaxis_title=\"Count\",\n    legend_title=\"Segment\"\n)\n\nfig.update_yaxes(\n    title = \"Sales\"\n)\n\nfig.show()\n#Let's check the distribution of sales by unity\nfig = make_subplots(3, 1,subplot_titles=['Independent 100 Restaurants and 50 Future', 'Independent 100 Restaurants','50 Future'])\n\nfig.add_trace(go.Box(x = independence100_data['Sales Divided'], name='Independent 100 Restaurants'), row = 1, col = 1)\nfig.add_trace(go.Box(x = future50_data['Sales'], name='50 Future'), row = 1, col = 1)\n\nfig.add_trace(go.Box(x = independence100_data['Sales Divided'], name='Independent 100 Restaurants'), row = 2, col = 1)\n\nfig.add_trace(go.Box(x = future50_data['Sales'], name='50 Future'), row = 3, col = 1)\nfig.update_layout(\n    title = dict(\n    text =  'Comparisson of sales between the independet 100 restaurants and B200',\n    font_family = \"Arial Black\",\n    xref = 'paper',\n    x = 0),\n    hovermode='x unified',\n    legend_title=\"Segment\"\n)\n\nfig.update_xaxes(\n    tickprefix = 'U$',\n    ticksuffix = ' M'\n)\n\nfig.show()\nfig = px.choropleth(independence100_data,\n                   locations='State',\n                   locationmode = 'USA-states',\n                   scope = 'usa',\n                   color = 'Sales Divided',\n                   color_continuous_scale = \"Viridis\",\n                   title = 'Sales in millions of the independent 100 Restaurants over the USA')\nfig.update_layout(title = dict(\nfont_family='Arial Black',\nxref = 'paper',\nx = 0\n))\nfig.show()\nfig = px.choropleth(independence100_data,\n                   locations='State',\n                   locationmode = 'USA-states',\n                   scope = 'usa',\n                   color = 'Average Check',\n                   color_continuous_scale = \"Viridis\",\n                   title = 'Average Check in millions of the independent 100 Restaurants over the USA')\nfig.update_layout(title = dict(\nfont_family='Arial Black',\nxref = 'paper',\nx = 0\n))\nfig.show()\n\"\"\"\n## Thanks\n\n![Thanks.gif](attachment:b3a4aa4f-abdf-4162-aa1e-74450a93aab8.gif)\n\nAny comments and suggestions to improve my notebook are very welcomed, and also feel free to talk to me <3\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '35a98df448a3af'}"}
{"id":"34779","text":"\"\"\"\n![Cover](https:\/\/imgur.com\/xhJclfL.png)\n\"\"\"\n\"\"\"\n### Our classification model for Content Moderation will be trained over 330,000 images on a pretrained RESNET50\n\"\"\"\n\"\"\"\n# Like the beginning of every project, we import libraries\n\"\"\"\nfrom torchvision import transforms # To perform all the transforms on our data\nfrom torchvision import datasets #Used to load the data from the folders\nfrom torch.utils.data import DataLoader\nfrom torchvision import models\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport time\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt\n!nvidia-smi\n\"\"\"\n# Importing Files, Splitting into Batches and Defining Classes\n\"\"\"\nfrom shutil import copyfile\nclasses = ['drawing','hentai','neutral','porn','sexy']\nfor i in classes:\n  files = os.listdir(\"..\/input\/nsfw-image-classification\/test\/\"+i)\n  for j in files[:3000]:\n    copyfile(\"..\/input\/nsfw-image-classification\/test\/\"+i+\"\/\"+j, \"..\/input\/output\/test_norm\/\"+i+\"\/\"+j)\n  print(i)\nfiles = os.listdir(\"..\/input\/output\/test_norm\/\"+i)\nprint(len(files))\nos.rmdir(\"..\/input\/output\/test_norm\/.ipynb_checkpoints\")\n\"\"\"\n# Preparing to Train\n\"\"\"\nimage_transforms = {\n    'train':transforms.Compose([\n        transforms.RandomRotation(degrees=15),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize([0.485, 0.456, 0.406],\n                             [0.229, 0.224, 0.225])\n    ]),\n    'test':transforms.Compose([\n        transforms.ToTensor(),\n        transforms.Normalize([0.485, 0.456, 0.406],\n                             [0.229, 0.224, 0.225])\n    ]),\n    'valid':transforms.Compose([\n        transforms.ToTensor(),\n        transforms.Normalize([0.485, 0.456, 0.406],\n                             [0.229, 0.224, 0.225])\n    ])\n}\ntest_directory = 'test_norm'\n\n# Setting batch size for training\nbatch_size=128\n\n#Number of classes for the data\nnum_classes = 5\n\n#Loading the data from the folders into the variable 'data'\ndata = {\n    'test': datasets.ImageFolder(root=test_directory,transform=image_transforms['test']),\n}\n\ntest_data_size = len(data['test'])\ntest_data_loader = DataLoader(data['test'],batch_size=batch_size,shuffle=True)\nidx_to_class = {v: k for k, v in data['test'].class_to_idx.items()}\nprint(idx_to_class)\n# Set the train, test and validation directory\ntrain_directory = 'batch-7\/train'\ntest_directory = 'batch-7\/test'\nvalid_directory = 'batch-7\/valid'\n\n# Setting batch size for training\nbatch_size=128\n\n#Number of classes for the data\nnum_classes = 5\n\n#Loading the data from the folders into the variable 'data'\ndata = {\n    'train': datasets.ImageFolder(root=train_directory,transform=image_transforms['train']),\n    'test': datasets.ImageFolder(root=test_directory,transform=image_transforms['test']),\n    'valid': datasets.ImageFolder(root=valid_directory,transform=image_transforms['valid'])\n}\n\n#Find out the size of the data\ntrain_data_size = len(data['train'])\ntest_data_size = len(data['test'])\nvalid_data_size = len(data['valid'])\n\n# Create iterators for the Data loaded using DataLoader module\ntrain_data_loader = DataLoader(data['train'],batch_size=batch_size,shuffle=True)\ntest_data_loader = DataLoader(data['test'],batch_size=batch_size,shuffle=True)\nvalid_data_loader = DataLoader(data['valid'],batch_size=batch_size,shuffle=True)\n\n#Printing the sizes of the sets\nprint(train_data_size,test_data_size,valid_data_size)\nidx_to_class = {v: k for k, v in data['train'].class_to_idx.items()}\nprint(idx_to_class)\n# Load the pretrained resnet 50 model\nresnet50 = models.resnet50(pretrained=True)\n# We don't want to train the model with new values, so we make the existing values untrainable\nfor param in resnet50.parameters():\n    param.requires_grad=False\n    \n# We want to add in a extra layer at the last with a 10 neuron output to classify the data\n#Number of neurons in the last layer\nfc_inputs = resnet50.fc.in_features\n\n#Replacing last layer with our layers\nresnet50.fc = nn.Sequential(\n    nn.Linear(fc_inputs,256),\n    nn.ReLU(),\n    nn.Dropout(0.4),\n    nn.Linear(256,5),\n    nn.LogSoftmax(dim=1)\n)\nmodel = torch.load(\"drive\/My Drive\/Image_class_NSFW_Stats\/models\/model_batch-9.pt\")\n# Define the optimizer and loss function\nweights = torch.tensor([1,1,1,1,6])\nloss_func = nn.NLLLoss(weight=weights.float().cuda())\noptimizer = optim.Adam(model.parameters())\ndef train_and_validate(model,loss_criterion,optimizer,epochs=25):\n    start = time.time()\n    best_acc = 0.0\n    history = []\n    \n    #Training the data\n    for epoch in range(epochs):\n        epoch_start = time.time()\n        print(\"Epoch - {}\/{}\".format(epoch+1,epochs))\n        \n        #Set to training mode\n        model.train()\n        \n        train_loss = 0.0\n        train_acc = 0.0\n        \n        val_loss = 0.0\n        val_acc = 0.0\n        \n        #Training\n        for i,(inputs,labels) in enumerate(train_data_loader):\n            inputs = inputs.to(device)\n            labels = labels.to(device)\n            optimizer.zero_grad()\n            #lavde  mooditu kelu\n            outputs = model(inputs)\n            loss = loss_criterion(outputs, labels)\n            loss.backward()\n            optimizer.step()\n            \n            train_loss = loss.item()*inputs.size(0)\n            \n            ret,predictions = torch.max(outputs.data,1)\n            correct_counts = predictions.eq(labels.data.view_as(predictions))\n            \n            acc = torch.mean(correct_counts.type(torch.cuda.FloatTensor))\n            train_acc += acc.item() * inputs.size(0)\n            \n        #Validation\n        with torch.no_grad():\n            \n            model.eval()\n            \n            for j,(inputs,labels) in enumerate(valid_data_loader):\n                inputs = inputs.to(device)\n                labels = labels.to(device)\n                outputs = model(inputs)\n                loss = loss_criterion(outputs,labels)\n                \n                val_loss += loss.item() * inputs.size(0)\n                \n                ret,predictions = torch.max(outputs.data,1)\n                correct_counts = predictions.eq(labels.data.view_as(predictions))\n                \n                acc = torch.mean(correct_counts.type(torch.cuda.FloatTensor))\n                val_acc += acc.item()*inputs.size(0)\n                \n        avg_train_loss = train_loss\/train_data_size\n        avg_train_acc = train_acc\/train_data_size\n        \n        avg_val_loss = val_loss\/valid_data_size\n        avg_val_acc = val_acc\/valid_data_size\n        \n        history.append([avg_train_loss,avg_val_loss,avg_train_acc,avg_val_acc])\n        \n        epoch_end = time.time()\n        print(\"Epoch : {},Training: Loss: {:.4f}, Accuracy:{:.4f}%\\n\\t\\tValidation : Loss:{:.4f},Accuracy:{:.4f}\".format(epoch+1,avg_train_loss,avg_train_acc*100,avg_val_loss,avg_val_acc*100))\n        print(\"Time taken:\"+str((epoch_end-epoch_start)))\n        if(avg_val_acc>best_acc):\n              best_acc = avg_val_acc\n    return model,history   \n\"\"\"\n# Begin Training\n\"\"\"\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nnum_epochs=30\n\nif torch.cuda.is_available():\n    model.cuda()\nprint(torch.cuda.is_available())\n    \nmodel,history = train_and_validate(model,loss_func,optimizer,num_epochs)\n\n# Save the model of the corresponding batch and its history for further use\ntorch.save(model,'drive\/My Drive\/Image_class_NSFW_Stats\/models\/model_batch-10.pt')\ntorch.save(history, 'drive\/My Drive\/Image_class_NSFW_Stats\/history\/history_batch-10.pt')\n\"\"\"\n# Predicting an Image\n\"\"\"\ndef predict(model, test_image_name):\n     \n    transform = image_transforms['test']\n \n    test_image = Image.open(test_image_name)\n    plt.imshow(test_image)\n     \n    test_image_tensor = transform(test_image)\n \n    if torch.cuda.is_available():\n        test_image_tensor = test_image_tensor.view(1, 3, 224, 224).cuda()\n    else:\n        test_image_tensor = test_image_tensor.view(1, 3, 224, 224)\n     \n    with torch.no_grad():\n        model.eval()\n        # Model outputs log probabilities\n        out = model(test_image_tensor)\n        ps = torch.exp(out)\n        topk, topclass = ps.topk(1, dim=1)\n        print(\"Output class :  \", idx_to_class[topclass.cpu().numpy()[0][0]])\n\"\"\"\n# Testing and Benchmarking\n\n\"\"\"\npredict(model,\"batch-1\/test\/neutral\/01013.jpg\")\nmodel = torch.load(\"nsfw_classification.pt\")\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nweights = torch.tensor([1,1,1,1,6])\nloss_func = nn.NLLLoss(weight=weights.float().cuda())\n\ny_true = torch.Tensor([]).cuda()\ny_pred = torch.Tensor([]).cuda()\n\ntest_loss = 0.0\ntest_acc = 0.0\nfor j,(inputs,labels) in enumerate(test_data_loader):\n  inputs = inputs.to(device)\n  labels = labels.to(device)\n  outputs = model(inputs)\n  loss = loss_func(outputs,labels)\n  y_true = torch.cat([y_true,labels.float()],dim=0)\n  \n  test_loss += loss.item() * inputs.size(0)\n\n  ret,predictions = torch.max(outputs.data,1)\n  y_pred = torch.cat([y_pred,predictions.float()],dim=0)\n  correct_counts = predictions.eq(labels.data.view_as(predictions))\n\n  acc = torch.mean(correct_counts.type(torch.cuda.FloatTensor))\n  test_acc += acc.item()*inputs.size(0)\n\navg_test_loss = test_loss\/test_data_size\navg_test_acc = test_acc\/test_data_size\nprint(y_true,y_pred)\nprint(avg_test_acc)\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nsns.set_style('white') \nlabels = ['drawing', 'hentai', 'neutral', 'porn', 'provocative']\nx = confusion_matrix(y_true.tolist(),y_pred.tolist())\nsns.heatmap(x,xticklabels=labels,yticklabels=labels,linecolor='white')\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_true.tolist(),y_pred.tolist()))\ncurrent = \"7,\"+str(train_data_size)+\",\"+str(avg_test_acc*100)+\"\\n\"\nprint(current)","meta":"{'source': 'AI4Code', 'id': '400c15057a3d3e'}"}
{"id":"13371","text":"\"\"\"\n## Indonesian DistilBERT finetuning with ArcMargin\n\"\"\"\n\"\"\"\nIn this notebook we are going to first download a DistilBERT model and tokenizer from HuggingFace which is pre-treained on the Indonesian Wikipedia. Then, we fine-tune it on the titles of this dataset with the help of ArcMarginProduct to build more useful embeddings. After that, we can use the model to obtain embeddings for titles in test set and hope that they are representative enough to find similar and dissimilar products.\n\"\"\"\n\"\"\"\nIf you are not familiar with HuggingFace or BERT models, I've done a tutorial on them on Kaggle and there in addition to explaning how to work with HuggingFace models, I've introduced resources to learn more about NLP and Transformers in general. You can find the notebook [here](https:\/\/www.kaggle.com\/moeinshariatnia\/simple-distilbert-fine-tuning-0-84-lb).\n\"\"\"\nimport os\nimport copy\nimport math\nimport pandas as pd\nimport numpy as np\nfrom tqdm.autonotebook import tqdm\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\nimport transformers\nfrom transformers import (BertTokenizer, BertModel,\n                          DistilBertTokenizer, DistilBertModel)\ntrain = pd.read_csv(\"..\/input\/rosaccred-dataset\/result_file_for_training.csv\")\n\ntrain['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'] =\\\n                train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'].apply(lambda x: int(x*100))\n\ntrain = train[train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)']\\\n    .isin(train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'].value_counts().index.tolist()[:50])]\n\n# train = pd.concat([train[train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'] == 930010].sample(4000),\\\n#                   train[~(train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'] == 930010)]])\n# train = train.sample(train.shape[0]).reset_index(drop=True)\n\ndisplay(train.head(), train.shape[0])\n\"\"\"\nThe following histogram gives us an idea that roughly how many words are there in each title. It is not a precise count of the tokens fed to the model because DistilBERT tokenizer does a more sophisticated function than simply splitting the sentence from its white spaces.\n\"\"\"\ntitle_lengths = train['\u041e\u0431\u0449\u0435\u0435 \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438'].apply(lambda x: len(x.split(\" \"))).to_numpy()\nprint(f\"MIN words: {title_lengths.min()}, MAX words: {title_lengths.max()}\")\nplt.hist(title_lengths);\n\"\"\"\nmax_length is set to 30 according to the histogram. But you can safely change it.\n\"\"\"\nclass CFG:\n    DistilBERT = True # if set to False, BERT model will be used\n    bert_hidden_size = 768\n    \n    batch_size = 64\n    epochs = 30\n    num_workers = 4\n    learning_rate = 1e-5 #3e-5\n    scheduler = \"ReduceLROnPlateau\"\n    step = 'epoch'\n    patience = 2\n    factor = 0.8\n    dropout = 0.5\n    model_path = \"\/kaggle\/working\"\n    max_length = 30\n    model_save_name = \"model.pt\"\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else 'cpu')\n\"\"\"\nLoading the model and its tokenizer from amazing HuggingFace model hub. As mentioned before, this model has been pre-trained on indonesian wikipedia.\n\"\"\"\nif CFG.DistilBERT:\n    model_name='cahya\/distilbert-base-indonesian'\n    tokenizer = DistilBertTokenizer.from_pretrained(model_name)\n    bert_model = DistilBertModel.from_pretrained(model_name)\nelse:\n    model_name='cahya\/bert-base-indonesian-522M'\n    tokenizer = BertTokenizer.from_pretrained(model_name)\n    bert_model = BertModel.from_pretrained(model_name)\n\"\"\"\nSee an example\n\"\"\"\ntext = train['title'].values[np.random.randint(0, len(train) - 1, 1)[0]]\nprint(f\"Text of the title: {text}\")\nencoded_input = tokenizer(text, return_tensors='pt')\nprint(f\"Input tokens: {encoded_input['input_ids']}\")\ndecoded_input = tokenizer.decode(encoded_input['input_ids'][0])\nprint(f\"Decoded tokens: {decoded_input}\")\noutput = bert_model(**encoded_input)\nprint(f\"last layer's output shape: {output.last_hidden_state.shape}\")\n\"\"\"\n## Dataset\n\"\"\"\n\"\"\"\nEncoding label_group coulmn to numeric labels so we can feed them to the model and loss function.\n\"\"\"\nlbl_encoder = LabelEncoder()\ntrain['label_code'] = lbl_encoder.fit_transform(train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'])\nNUM_CLASSES = train['label_code'].nunique()\nNUM_CLASSES\nclass TextDataset(torch.utils.data.Dataset):\n    def __init__(self, dataframe, tokenizer, mode=\"train\", max_length=None):\n        self.dataframe = dataframe\n        if mode != \"test\":\n            self.targets = dataframe['label_code'].values\n        texts = list(dataframe['\u041e\u0431\u0449\u0435\u0435 \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438'].apply(lambda o: str(o)).values)\n        self.encodings = tokenizer(texts, \n                                   padding=True, \n                                   truncation=True, \n                                   max_length=max_length)\n        self.mode = mode\n        \n        \n    def __getitem__(self, idx):\n        # putting each tensor in front of the corresponding key from the tokenizer\n        # HuggingFace tokenizers give you whatever you need to feed to the corresponding model\n        item = {key: torch.tensor(values[idx]) for key, values in self.encodings.items()}\n        # when testing, there are no targets so we won't do the following\n        if self.mode != \"test\":\n            item['labels'] = torch.tensor(self.targets[idx]).long()\n        return item\n    \n    def __len__(self):\n        return len(self.dataframe)\ndataset = TextDataset(train.sample(100), tokenizer, max_length=CFG.max_length)\ndataloader = torch.utils.data.DataLoader(dataset, \n#                                          batch_size=CFG.batch_size, \n                                         num_workers=CFG.num_workers, \n                                         shuffle=True)\nbatch = next(iter(dataloader))\nprint(batch['input_ids'].shape, batch['labels'].shape)\ndataset\n# code from https:\/\/github.com\/ronghuaiyang\/arcface-pytorch\/blob\/47ace80b128042cd8d2efd408f55c5a3e156b032\/models\/metrics.py#L10\n\nclass ArcMarginProduct(nn.Module):\n    r\"\"\"Implement of large margin arc distance: :\n        Args:\n            in_features: size of each input sample\n            out_features: size of each output sample\n            s: norm of input feature\n            m: margin\n            cos(theta + m)\n        \"\"\"\n    def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False):\n        super(ArcMarginProduct, self).__init__()\n        self.in_features = in_features\n        self.out_features = out_features\n        self.s = s\n        self.m = m\n        self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))\n        nn.init.xavier_uniform_(self.weight)\n\n        self.easy_margin = easy_margin\n        self.cos_m = math.cos(m)\n        self.sin_m = math.sin(m)\n        self.th = math.cos(math.pi - m)\n        self.mm = math.sin(math.pi - m) * m\n\n    def forward(self, input, label):\n        # --------------------------- cos(theta) & phi(theta) ---------------------------\n        cosine = F.linear(F.normalize(input), F.normalize(self.weight))\n        sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1))\n        phi = cosine * self.cos_m - sine * self.sin_m\n        if self.easy_margin:\n            phi = torch.where(cosine > 0, phi, cosine)\n        else:\n            phi = torch.where(cosine > self.th, phi, cosine - self.mm)\n        # --------------------------- convert label to one-hot ---------------------------\n        # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')\n        one_hot = torch.zeros(cosine.size(), device=CFG.device)\n        one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n        # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------\n        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)  # you can use torch.where if your torch.__version__ is 0.4\n        output *= self.s\n        # print(output)\n\n        return output\nclass Model(nn.Module):\n    def __init__(self, \n                 bert_model, \n                 num_classes=NUM_CLASSES, \n                 last_hidden_size=CFG.bert_hidden_size):\n        \n        super().__init__()\n        self.bert_model = bert_model\n        self.arc_margin = ArcMarginProduct(last_hidden_size, \n                                           num_classes,\n                                           s=30.0, \n                                           m=0.50, \n                                           easy_margin=False)\n    \n    def get_bert_features(self, batch):\n        output = self.bert_model(input_ids=batch['input_ids'], attention_mask=batch['attention_mask'])\n        last_hidden_state = output.last_hidden_state # shape: (batch_size, seq_length, bert_hidden_dim)\n        CLS_token_state = last_hidden_state[:, 0, :] # obtaining CLS token state which is the first token.\n        return CLS_token_state\n    \n    def forward(self, batch):\n        CLS_hidden_state = self.get_bert_features(batch)\n#         output = self.arc_margin(CLS_hidden_state, batch['labels'])\n        return CLS_hidden_state\nclass AvgMeter:\n    def __init__(self, name=\"Metric\"):\n        self.name = name\n        self.reset()\n    \n    def reset(self):\n        self.avg, self.sum, self.count = [0]*3\n    \n    def update(self, val, count=1):\n        self.count += count\n        self.sum += val * count\n        self.avg = self.sum \/ self.count\n    \n    def __repr__(self):\n        text = f\"{self.name}: {self.avg:.4f}\"\n        return text\n\ndef one_epoch(model, \n              criterion, \n              loader,\n              optimizer=None, \n              lr_scheduler=None, \n              mode=\"train\", \n              step=\"batch\"):\n    \n    loss_meter = AvgMeter()\n    acc_meter = AvgMeter()\n    \n    tqdm_object = tqdm(loader, total=len(loader))\n    for batch in tqdm_object:\n        batch = {k: v.to(CFG.device) for k, v in batch.items()}\n        preds = model(batch)\n        loss = criterion(preds, batch['labels'])\n        if mode == \"train\":\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step()\n            if step == \"batch\":\n                lr_scheduler.step()\n                \n        count = batch['input_ids'].size(0)\n        loss_meter.update(loss.item(), count)\n        \n        accuracy = get_accuracy(preds.detach(), batch['labels'])\n        acc_meter.update(accuracy.item(), count)\n        if mode == \"train\":\n            tqdm_object.set_postfix(train_loss=loss_meter.avg, accuracy=acc_meter.avg, lr=get_lr(optimizer))\n        else:\n            tqdm_object.set_postfix(valid_loss=loss_meter.avg, accuracy=acc_meter.avg)\n    \n    return loss_meter, acc_meter\n\ndef get_lr(optimizer):\n    for param_group in optimizer.param_groups:\n        return param_group[\"lr\"]\n\ndef get_accuracy(preds, targets):\n    \"\"\"\n    preds shape: (batch_size, num_labels)\n    targets shape: (batch_size)\n    \"\"\"\n    preds = preds.argmax(dim=1)\n    acc = (preds == targets).float().mean()\n    return acc\ndef train_eval(epochs, model, train_loader, valid_loader, \n               criterion, optimizer, lr_scheduler=None):\n    \n    best_loss = float('inf')\n    best_model_weights = copy.deepcopy(model.state_dict())\n    \n    for epoch in range(epochs):\n        print(\"*\" * 30)\n        print(f\"Epoch {epoch + 1}\")\n        current_lr = get_lr(optimizer)\n        \n        model.train()\n        train_loss, train_acc = one_epoch(model, \n                                          criterion, \n                                          train_loader, \n                                          optimizer=optimizer,\n                                          lr_scheduler=lr_scheduler,\n                                          mode=\"train\",\n                                          step=CFG.step)                     \n        model.eval()\n        with torch.no_grad():\n            valid_loss, valid_acc = one_epoch(model, \n                                              criterion, \n                                              valid_loader, \n                                              optimizer=None,\n                                              lr_scheduler=None,\n                                              mode=\"valid\")\n        \n        if valid_loss.avg < best_loss:\n            best_loss = valid_loss.avg\n            best_model_weights = copy.deepcopy(model.state_dict())\n            tmp_model_state = model.state_dict()\n            torch.save(model.state_dict(), f'{CFG.model_path}\/{CFG.model_save_name}')\n            print(\"Saved best model!\")\n            break\n        \n        if isinstance(lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):\n            lr_scheduler.step(valid_loss.avg)\n            if current_lr != get_lr(optimizer):\n                print(\"Loading best model weights!\")\n                model.load_state_dict(torch.load(f'{CFG.model_path}\/{CFG.model_save_name}', \n                                                 map_location=CFG.device))\n        \n        print(\"*\" * 30)\ntrain_df, valid_df = train_test_split(train, \n                                      test_size=0.33, \n                                      shuffle=True, \n                                      random_state=42,\n                                      stratify=train['label_code'])\n\ntrain_dataset = TextDataset(train_df, tokenizer, max_length=CFG.max_length)\ntrain_loader = torch.utils.data.DataLoader(train_dataset, \n                                           batch_size=CFG.batch_size, \n                                           num_workers=CFG.num_workers, \n                                           shuffle=True)\n\nvalid_dataset = TextDataset(valid_df, tokenizer, max_length=CFG.max_length)\nvalid_loader = torch.utils.data.DataLoader(valid_dataset, \n                                           batch_size=CFG.batch_size, \n                                           num_workers=CFG.num_workers, \n                                           shuffle=False)\nmodel = Model(bert_model).to(CFG.device)\nmodel.state_dict()\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=CFG.learning_rate)\nif CFG.scheduler == \"ReduceLROnPlateau\":\n    lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, \n                                                              mode=\"min\", \n                                                              factor=CFG.factor, \n                                                              patience=CFG.patience)\n\ntrain_eval(CFG.epochs, model, train_loader, valid_loader,\n           criterion, optimizer, lr_scheduler=lr_scheduler)\n# !mkdir tokenizer\n# tokenizer.save_pretrained(\".\/tokenizer\")\ntorch.save(model.state_dict(), \"final.pt\")\nmodel = Model(bert_model)\nmodel.load_state_dict(torch.load('..\/input\/zaebalomenya-eto-vse\/model(1).pt', map_location=torch.device('cpu')))\nmodel.cpu()\ndef get_predicts(model, dataloader):\n    tqdm_object = tqdm(dataloader, total=len(dataloader))\n    preds = []\n    for batch in tqdm_object:\n        batch = {k: v.cuda() for k, v in batch.items()}\n        preds.append(model(batch))\n    return preds\nmodel = Model(bert_model)\nmodel.load_state_dict(torch.load('..\/input\/zaebalomenya-eto-vse\/model(1).pt'))\nmodel.eval()\nmodel.cuda()\n\ncatogories = train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'].unique()\nbase_vectors_for_unique_categories = {}\nfor subCategory in tqdm(catogories):\n    dataframe_categories = train[train['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)']== subCategory]\n    if dataframe_categories.shape[0] > 500:\n        corpus = dataframe_categories.sample(500).reset_index(drop=True)\n    else:\n        corpus = dataframe_categories.reset_index(drop=True)\n        \n    dataset = TextDataset(corpus, tokenizer, max_length=CFG.max_length)\n    dataloader = torch.utils.data.DataLoader(dataset,\n                                             batch_size=32,\n                                             num_workers=CFG.num_workers, \n                                             shuffle=True)\n    embedings = get_predicts(model, dataloader)\n    \n    \n    mean_emb = np.zeros(embedings[0].shape[1])\n    for predict in embedings:\n        mean_emb += predict.mean(axis=0).cpu().detach().numpy()\n    mean_emb \/= len(embedings)\n    \n                         \n    base_vectors_for_unique_categories.update({str(subCategory):mean_emb})\n{'base_vectors':base_vectors_for_unique_categories}\nbase_vectors_for_unique_categories\njson_with_emb = pd.DataFrame(base_vectors_for_unique_categories)\njson_with_emb.to_csv('df_with_embs.csv', index=False)\n\njson_with_emb = pd.read_csv('df_with_embs.csv')\ntest_df = train.sample(50).reset_index(drop=True)\ntest_df['predict'] = None\nfor i in range(test_df.shape[0]-1):\n    dataset = TextDataset(test_df.iloc[i:i+1, :], tokenizer, max_length=CFG.max_length)\n    dataloader = torch.utils.data.DataLoader(dataset,\n                                         batch_size=1,\n                                         num_workers=CFG.num_workers, \n                                         shuffle=True)\n    predicts = get_predicts(model, dataloader)[0][0].cpu().detach().numpy()\n\n    dists = np.sum((np.square(predicts - json_with_emb_.values.T)), axis=1)\n    indices = np.argsort(dists)[:5]\n    predict_category = list(base_vectors_for_unique_categories.keys())[indices[0]]\n    test_df.loc[i, 'predict'] = predict_category\n\nfrom sklearn.metrics import accuracy_score\ntest_df = test_df[~(test_df['predict'].isna())]\ntest_df['predict'] = test_df['predict'].apply(lambda x: int(x))\n\naccuracy_score(test_df['predict'].values,\\\n               test_df['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'].values)\n\"\"\"\n# \u0414\u043b\u044f \u0426\u041f\u0423 \u0431\u0435\u0437 \u043b\u0435\u0439\u0431\u043b\u0430\n\"\"\"\nmodel = Model(bert_model)\nmodel.load_state_dict(torch.load('..\/input\/zaebalomenya-eto-vse\/model(1).pt', map_location=torch.device('cpu')))\nmodel.cpu()\ntest_df.loc[10, '\u041e\u0431\u0449\u0435\u0435 \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438']\ntest_df = train.sample(50).reset_index(drop=True)\ntest_df['predict'] = None\nfor i in range(test_df.shape[0]+1):\n    dataset = TextDataset(test_df.iloc[10:10+1, :], tokenizer, max_length=CFG.max_length, mode='test')\n    dataloader = torch.utils.data.DataLoader(dataset,\n                                             batch_size=1,\n                                             num_workers=CFG.num_workers, \n                                             shuffle=True)\n    tqdm_object = tqdm(dataloader, total=len(dataloader))\n    preds = []\n    model.cpu()\n    model.eval()\n    for batch in tqdm_object:\n        print(batch)\n        with torch.no_grad():\n            batch = {k: v.cpu() for k, v in batch.items()}\n            preds.append(model(batch))\n\n    dists = np.sum((np.square(preds[0][0].cpu().detach().numpy() - np.array(list(base_vectors_for_unique_categories.values())))), axis=1)\n    indices = np.argsort(dists)[:5]\n    predict_category = list(base_vectors_for_unique_categories.keys())[indices[0]]\n    test_df.loc[i, 'predict'] = predict_category\npredict_category\npredict_category\ntest_df = test_df[~(test_df['predict'].isna())]\ntest_df['predict'] = test_df['predict'].apply(lambda x: int(x))\n\naccuracy_score(test_df['predict'].values,\\\n               test_df['\u0420\u0430\u0437\u0434\u0435\u043b \u0415\u041f \u0420\u0424 (\u041a\u043e\u0434 \u0438\u0437 \u0424\u0413\u0418\u0421 \u0424\u0421\u0410 \u0434\u043b\u044f \u043f\u043e\u0434\u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438)'].values)\n\"\"\"\n# predict with tensor and label\n\"\"\"\ndists = np.sum((np.square(predicts - np.array(list(base_vectors_for_unique_categories.values())))), axis=1)\nindices = np.argsort(dists)[:5]\npredict_category = list(base_vectors_for_unique_categories.keys())[indices[0]]\npredict_category\nindices = np.argsort(dists)[:5]\nlist(base_vectors_for_unique_categories.keys())[indices[0]]\nlist(base_vectors_for_unique_categories.keys())[10]\ndataset = TextDataset(train.sample(500), tokenizer, max_length=CFG.max_length)\ndataloader = torch.utils.data.DataLoader(dataset,\n                                         batch_size=64,\n                                         num_workers=CFG.num_workers, \n                                         shuffle=True)\ntrain\ndef get_predicts(model, dataloader):\n    tqdm_object = tqdm(dataloader, total=len(dataloader))\n    preds = []\n    for batch in tqdm_object:\n        batch = {k: v.cuda() for k, v in batch.items()}\n        preds.append(model(batch))\n    return preds\n\npredicts = get_predicts(model, dataloader)\npredicts[0][0]\nmean_embs = np.zeros(predicts[0].shape[1])\nfor predict in predicts:\n    mean_embs += predict.mean(axis=0).cpu().detach().numpy()\nmean_embs.shape\npredicts[0].shape[1]\nnp.zeros(5)\nlen(predicts)\nmean_embs[0]\ntext = 'max_length=maxl, pad_to_max_length=True, truncation=True'\nfrom torch.utils.data import TensorDataset, DataLoader\nX_test = torch.tensor(tokenizer.encode(text, max_length=30, pad_to_max_length=True, truncation=True))\ntest_data = TensorDataset(X_test)\ntest_dataloader = DataLoader(\n    test_data,\n    batch_size=1,\n    num_workers=4,\n    pin_memory=True\n)\nfor batch in test_dataloader:\n    batch = batch[0]\n    batch.cuda()\n    with torch.no_grad():\n        logits = model(batch)\nbatch['input_ids'][0].shape\ntrain.loc[0, '\u041e\u0431\u0449\u0435\u0435 \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438']\ndef model_vector(text, tokenizer_model):\n    token = tokenizer_model.encode(text, max_length=30, pad_to_max_length=True, truncation=True)\n    token_with_dop_dimension = np.expand_dims(token, axis=0)\n    return torch.tensor(token_with_dop_dimension).to('cuda')\n\nmodel(model_vector(train.loc[0, '\u041e\u0431\u0449\u0435\u0435 \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0446\u0438\u0438'], tokenizer))\nmodel.eval()\nmodel(batch['input_ids'][0])\nmodel_['bert_model.embeddings.word_embeddings.weight'].shape\nmodel_ = torch.load('..\/input\/zaebalomenya-eto-vse\/model(1).pt')\nmodel_['arc_margin.weight'].shape","meta":"{'source': 'AI4Code', 'id': '186ce65f1819e5'}"}
{"id":"78904","text":"\"\"\"\n# Mask Classier - using CNN for COVID-19 #  \n\"\"\"\n\"\"\"\n![Wearing-face-masks-at-home-might-help-ward-off-COVID-19-spread-among-family-members-375x195.jpg](attachment:Wearing-face-masks-at-home-might-help-ward-off-COVID-19-spread-among-family-members-375x195.jpg)\n\"\"\"\n\"\"\"\nAnyone travelling by bus, train, ferry or plane should wear a face covering to help reduce the risk of coronavirus transmission.\n\nThe new rules coincided with a further easing of lockdown in different countries - including the return to class of  school pupils and the reopening of shops.\nIn the following work We\u2019ll try to classify if the person is using a mask or not .\n\"\"\"\n\"\"\"\nThis is a basic implementation using the ResNet50 model. I am a beginner so please feel free to offer corrections and suggestions.\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport tensorflow\nimport keras\nfrom keras.preprocessing.image import load_img\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D\nfrom sklearn.datasets import load_files\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\nfrom keras.models import Sequential\nimport cv2\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing import image\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\nfrom keras_preprocessing.image import ImageDataGenerator\nimport numpy as np\n\n\n#Test & Train dirs \n\ntrain_dir='\/kaggle\/input\/withwithout-mask\/maskdata\/maskdata\/train\/'\ntest_dir='\/kaggle\/input\/withwithout-mask\/maskdata\/maskdata\/test\/'\n\"\"\"\nLet's extract data from dir : for each dir we have target=y(0\/1 - without\/with mask) filenames=x(image path)\n\"\"\"\ndef load_dataset(path):\n    data = load_files(path) #load all files from the path\n    files = np.array(data['filenames']) #get the file  \n    targets = np.array(data['target'])#get the the classification labels as integer index\n    target_labels = np.array(data['target_names'])#get the the classification labels \n    return files,targets,target_labels\n    \nx_train, y_train,target_labels = load_dataset(train_dir)\nx_test, y_test,_ = load_dataset(test_dir)\n\nprint('Training set size : ' , x_train.shape[0])\nprint('Testing set size : ', x_test.shape[0])\n\"\"\"\nShow image example\n\"\"\"\nimage = load_img(x_train[1])\nplt.imshow(image)\n\"\"\"\nShow image shape\n\"\"\"\nim = cv2.imread(x_train[5])\nh, w, c = im.shape\nprint('width:  ', w)\nprint('height: ', h)\nprint('channel:', c)\n\"\"\"\n# Parameters\n\"\"\"\nnum_classes = 2\nFAST_RUN       = False\nIMAGE_WIDTH    =64\nIMAGE_HEIGHT   =64\nbatch_size=50\nimage_size = 64\nepoch =15\nIMAGE_SIZE     =(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS =3\nDROP_OUT_VALUE =0.1\nFILTER_SIZE    =(3, 3)\nPOOL_SIZE      =(2, 2)\n\"\"\"\nCreate model :)\n\"\"\"\nmodel = Sequential()\n\nmodel.add(Conv2D(32, FILTER_SIZE, activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=POOL_SIZE))\n#model.add(Dropout(DROP_OUT_VALUE))\n\nmodel.add(Conv2D(64, FILTER_SIZE, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=POOL_SIZE))\nmodel.add(Dropout(DROP_OUT_VALUE))\n\nmodel.add(Conv2D(128, FILTER_SIZE, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=POOL_SIZE))\nmodel.add(Dropout(DROP_OUT_VALUE))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(DROP_OUT_VALUE))\nmodel.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.summary()\n\"\"\"\nPreprocessing the data via ImageDataGenerator.The data here is categorical as it is divided into two categories namely with & without mask.\n\"\"\"\n\n\n\ndata_generator = ImageDataGenerator(preprocessing_function=preprocess_input,horizontal_flip=True,\n                                   width_shift_range = 0.2,\n                                   height_shift_range = 0.2)\n\n\ntrain_generator = data_generator.flow_from_directory(\n        train_dir,\n        target_size=(image_size, image_size),\n        batch_size=batch_size,\n        class_mode='categorical')\n\nvalidation_generator = data_generator.flow_from_directory(test_dir,target_size=(image_size, image_size),\n        class_mode='categorical')\n\nhistory=model.fit_generator(\n        train_generator,\n        epochs=epoch, \n        validation_data=validation_generator,\n        validation_steps=1)\n\"\"\"\nPlot accuracy & lost for train & test set \n\"\"\"\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\"\"\"\nGreat results :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '90f3144771fe0e'}"}
{"id":"133970","text":"\"\"\"\n## Project Overview <a class='anchor' id='Section_1'>\n\nCredit default risk is the risk that a lender takes the chance that a borrower fails to make required payments of the loan. \n\nIn this project, I utilized different learning algorithms including KNN, Logistic regression, decision tree, and the popular XGBoost to find the best algorithms, and on top of that, I also implemented RandomizedSearchCV and GridSearchCV to fine tune the hyperparamters and further improve the model. \n\nThe final model has a 0.939 accuracy score and 0.957 AUROC score.\n\n\"\"\"\n# import libraries and packages \nimport numpy as np \nimport pandas as pd \nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom scipy.stats import uniform, randint\nfrom sklearn import model_selection,linear_model, metrics\nfrom sklearn.metrics import auc, accuracy_score, confusion_matrix, roc_auc_score, classification_report\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import GridSearchCV, KFold, RandomizedSearchCV, train_test_split\n\nimport xgboost as xgb\nimport seaborn as sns\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## Exploratory Analysis <a class='anchor' id='Section_2'>\n\"\"\"\n# read data into a DataFrame\ncredit_df = pd.read_csv(\"\/kaggle\/input\/credit-risk-dataset\/credit_risk_dataset.csv\")\n# check the data size\ncredit_df.shape\nNan_per = credit_df.isnull().sum()\/credit_df.shape[0]*100\nNan_per.round(2)\n\"\"\"\n**Obeservation:** \n* Only two columns of data contains NaN, \n* `person_emp_length` contains **2.75%** NaN and `loan_int_rate` contains **9.56%** NaN\n\"\"\"\n# check the mode, median for the two features\nprint('person_emp_length mode {}'.format(credit_df['person_emp_length'].mode()[0]))\nprint('person_emp_length median {}'.format(credit_df['person_emp_length'].median()))\nprint('loan_int_rate mode {}'.format(credit_df['loan_int_rate'].mode()[0]))\nprint('loan_int_rate median {}'.format(credit_df['loan_int_rate'].median()))\n\"\"\"\n**Obeservation:**  \n* `person_emp_length` is the person employment history, to be more conservative, the nan values are replaced with mode, which is 0 year.\n* `loan_int_rate` is the loan income rate, to be more conservative, the nan values are replaced with 10.99, which is the median\n\"\"\"\n# fill NaN with the mode\ncredit_df['person_emp_length'].fillna(credit_df['person_emp_length'].mode()[0], inplace=True)\ncredit_df['loan_int_rate'].fillna(credit_df['loan_int_rate'].median(), inplace=True)\n# check the nans are replaced \ncredit_df.isnull().sum()\n# numerical variebles\nnum_cols = pd.DataFrame(credit_df[credit_df.select_dtypes(include=['float', 'int']).columns])\n# print the numerical variebles\nnum_cols.columns\n# drop the label column 'loan status' before visualization\nnum_cols_hist = num_cols.drop(['loan_status'], axis=1)\n# visualize the distribution for each varieble\nplt.figure(figsize=(12,16))\n\nfor i, col in enumerate(num_cols_hist.columns):\n    idx = int('42'+ str(i+1))\n    plt.subplot(idx)\n    sns.distplot(num_cols_hist[col], color='forestgreen', \n                 kde_kws={'color': 'indianred', 'lw': 2, 'label': 'KDE'})\n    plt.title(col+' distribution', fontsize=14)\n    plt.ylabel('Probablity', fontsize=12)\n    plt.xlabel(col, fontsize=12)\n    plt.xticks(fontsize=12)\n    plt.yticks(fontsize=12)\n    plt.legend(['KDE'], prop={\"size\":12})\n\nplt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.35,\n                    wspace=0.35)\nplt.show()\n# decribe the dataset\ncredit_df.describe()\n\"\"\"\n**Observation:** All of the distributions are positive skewed.\n\n* `person_age`: Most people are 20 to 60 years old. In the following analysis, to be more general, people age > 100 will be droped.\n* `person_emp_length`: Most people have less than 40 years of employment. People with employment > 60 years will be droped.\n* `person_income`: It seems that there are outliers which has to be removed (> 4 million).\n* For all other variables, the distribution is more uniform across the whole range, thus they will be kept.\n\n\"\"\"\n# clean the dataset and drop outliers\ncleaned_credit_df = credit_df[credit_df['person_age']<=100]\ncleaned_credit_df = cleaned_credit_df[cleaned_credit_df['person_emp_length']<=60]\ncleaned_credit_df = cleaned_credit_df[cleaned_credit_df['person_income']<=4e6]\n# get the cleaned numberical variebles\ncleaned_num_cols = pd.DataFrame(cleaned_credit_df[cleaned_credit_df.select_dtypes(include=['float', 'int']).columns])\ncorr = cleaned_num_cols.corr().sort_values('loan_status', axis=1, ascending=False)\ncorr = corr.sort_values('loan_status', axis=0, ascending=True)\nmask = np.zeros_like(corr)\nmask[np.triu_indices_from(mask, k=1)] = True\nwith sns.axes_style(\"white\"):\n    f, ax = plt.subplots(figsize=(8, 6))\n    ax = sns.heatmap(corr, mask=mask, vmin=corr.loan_status.min(), \n                     vmax=corr.drop(['loan_status'], axis=0).loan_status.max(),\n                     square=True, annot=True, fmt='.2f',\n                     center=0, cmap='RdBu',annot_kws={\"size\": 12})\n\"\"\"\n**Observation:** \n\n* `person_income`, `person_emp_length`, and `person_age`: has negative effect on loan_status being default, which means the larger these variebles, the less likely the person is risky.\n* `loan_percent_income`, `loan_int_rate`, and `loan_amnt`: has postive effect on loan_status being default, which means the larger these variebles, the more likely the person is risky.\n\"\"\"\n# get the categorical variebles \ncat_cols = pd.DataFrame(cleaned_credit_df[cleaned_credit_df.select_dtypes(include=['object']).columns])\ncat_cols.columns\n# one-hot encode the catogorical variebles\nencoded_cat_cols = pd.get_dummies(cat_cols)\ncat_cols_corr = pd.concat([encoded_cat_cols, cleaned_credit_df['loan_status']], axis=1)\ncorr = cat_cols_corr.corr().sort_values('loan_status', axis=1, ascending=False)\ncorr = corr.sort_values('loan_status', axis=0, ascending=True)\nmask = np.zeros_like(corr)\nmask[np.triu_indices_from(mask, k=1)] = True\nwith sns.axes_style(\"white\"):\n    f, ax = plt.subplots(figsize=(16, 10))\n    ax = sns.heatmap(corr, mask=mask, vmin=corr.loan_status.min(), \n                     vmax=corr.drop(['loan_status'], axis=0).loan_status.max(), \n                     square=True, annot=True, fmt='.2f',\n                     center=0, cmap='RdBu',annot_kws={\"size\": 10})\n# concat the numerical and one-hot encoded categorical variebles\ncleaned_credit_df = pd.concat([cleaned_num_cols, encoded_cat_cols], axis=1)\ncleaned_credit_df.head()\n# check the cleaned dataset size \nprint ('The cleaned dataset has {} rows and {} columns'.format(cleaned_credit_df.shape[0], \n                                                               cleaned_credit_df.shape[1]))\nprint ('The cleaned dataset has {} numerical features and {} categorical features'\n       .format(len(cleaned_num_cols.columns)-1, len(encoded_cat_cols.columns)))\n\"\"\"\n## Modeling\n\"\"\"\n# Split Train and Test Sets\nlabel = cleaned_credit_df['loan_status'] # labels\nfeatures = cleaned_credit_df.drop('loan_status',axis=1) # features\nx_train, x_test, y_train, y_test = model_selection.train_test_split(features, label, \n                                                                    random_state=42, test_size=.30)\nprint('The train dataset has {} data\\nThe test dataset has {} data'.\n      format(x_train.shape[0], x_test.shape[0]))\n\n# define a model assess function to test a few model performance\ndef model_assess(model, name='Default'):\n    '''\n    This function is used to test model performance \n    \n    Input: model, defined classifer\n    Output: print the confusion matrix\n    \n    '''\n    \n    model.fit(x_train, y_train)\n    preds = model.predict(x_test)\n    preds_proba = model.predict_proba(x_test)\n    print(name, '\\n',classification_report(y_test, model.predict(x_test)))\n\"\"\"\n### Evaluate different algorithms\n\"\"\"\n#KNN\nknn = KNeighborsClassifier(n_neighbors=150)\nmodel_assess(knn, name='KNN')\n#Logistic Regression\nlg = LogisticRegression(random_state=42)\nmodel_assess(lg, 'Logistic Regression')\n# Dicision trees\nD_tree = DecisionTreeClassifier(max_depth=10, min_samples_split=2, min_samples_leaf=1, random_state=42)\nmodel_assess(D_tree, 'DecisionTree Classifier')\n#XGB\nxgb = xgb.XGBClassifier(objective=\"binary:logistic\", random_state=42) \nmodel_assess(xgb, 'XGBoost')\n#ROC AUC\nfig = plt.figure(figsize=(8,5))\nplt.plot([0, 1], [0, 1],'r--')\n\n#KNN\npreds_proba_knn = knn.predict_proba(x_test)\nprobsknn = preds_proba_knn[:, 1]\nfpr, tpr, thresh = metrics.roc_curve(y_test, probsknn)\naucknn = roc_auc_score(y_test, probsknn)\nplt.plot(fpr, tpr, label=f'KNN, AUC = {str(round(aucknn,3))}')\n\n#Logistic Regression\npreds_proba_lg = lg.predict_proba(x_test)\nprobslg = preds_proba_lg[:, 1]\nfpr, tpr, thresh = metrics.roc_curve(y_test, probslg)\nauclg = roc_auc_score(y_test, probslg)\nplt.plot(fpr, tpr, label=f'Logistic Regression, AUC = {str(round(auclg,3))}')\n\n#DecisionTree Classifier\npreds_proba_D_tree = D_tree.predict_proba(x_test)\nprobsD_tree = preds_proba_D_tree[:, 1]\nfpr, tpr, thresh = metrics.roc_curve(y_test, probsD_tree)\nauclg = roc_auc_score(y_test, probsD_tree)\nplt.plot(fpr, tpr, label=f'DecisionTree Classifier, AUC = {str(round(auclg,3))}')\n\n#XGBoost\npreds_proba_xgb = xgb.predict_proba(x_test)\nprobsxgb = preds_proba_xgb[:, 1]\nfpr, tpr, thresh = metrics.roc_curve(y_test, probsxgb)\naucxgb = roc_auc_score(y_test, probsxgb)\nplt.plot(fpr, tpr, label=f'XGBoost, AUC = {str(round(aucxgb,3))}')\nplt.ylabel(\"True Positive Rate\", fontsize=12)\nplt.xlabel(\"False Positive Rate\", fontsize=12)\nplt.title(\"ROC curve\")\nplt.rcParams['axes.titlesize'] = 16\nplt.legend()\nplt.show()\n\"\"\"\n### Feature importance\n\"\"\"\nfeature_importance = pd.DataFrame({'feature': x_train.columns, \n                                   'importance': xgb.feature_importances_})\n\nnew_features_df = feature_importance[feature_importance['importance']>0\n                                    ].sort_values(by=['importance'],ascending=False)\nsns.set(context='paper', style='ticks',  font='sans-serif', \n        font_scale=1.2, color_codes=True, rc=None)\nfigure, ax = plt.subplots(figsize=(8, 5))\nax=sns.barplot(data = new_features_df[:10],\n              y='feature',\n              x='importance',\n              palette='Blues_d') # rocket, Blues_d\nax.set_title('feature importance', fontsize=14)\nax.set_xlabel('importance', fontsize=13)\nax.set_ylabel('feature', fontsize=13)\nplt.show()\n# print the xgb base model\nxgb\n\"\"\"\n### Hyperparameter Tuning\n\"\"\"\n# RandomizedSearchCV hyperparameter tuning\nparams = {\n    \"colsample_bytree\": uniform(0.9, 0.1), # 0.9-1 0.9 is the lower bound, 0.1 is the range\n    \"gamma\": uniform(0.2, 0.3),# 0.2-0.5\n    \"learning_rate\": uniform(0.2, 0.2), # 0.2-0.4 \n    \"max_depth\": randint(4, 6), # 4, 5, 6\n    \"n_estimators\": randint(100, 300), # 100-300\n    \"subsample\": uniform(0.9, 0.1) # 0.9-1\n}\n\nRandom_CV = RandomizedSearchCV(xgb, param_distributions=params, random_state=42, \n                            n_iter=100, cv=3, verbose=2, n_jobs=16, return_train_score=True)\n\nRandom_CV.fit(x_train, y_train)\n# function to return the top selcted models\ndef report_best_scores(results, n_top=3):\n    for i in range(1, n_top + 1):\n        candidates = np.flatnonzero(results['rank_test_score'] == i)\n        for candidate in candidates:\n            print(\"Model with rank: {0}\".format(i))\n            print(\"Mean validation score: {0:.3f} (std: {1:.3f})\".format(\n                  results['mean_test_score'][candidate],\n                  results['std_test_score'][candidate]))\n            print(\"Parameters: {0}\".format(results['params'][candidate]))\n            print(\"\")\nreport_best_scores(Random_CV.cv_results_, 3)\nRandom_best_xgb = Random_CV.best_estimator_\nRandom_best_xgb.fit(x_train, np.ravel(y_train)) \npreds_proba_Random = Random_best_xgb.predict_proba(x_test)\nprobs_Random = preds_proba_Random[:, 1]\nRandom_bestauc = roc_auc_score(y_test, probs_Random)\nprint ('xgb base model AUROC socre: {}'.format(aucxgb))\nprint ('xgb best model using RandomizedSearchCV AUROC socre: {}'.format(Random_bestauc))\n# GridSearchCV hyperparameter tuning\nparams = {\n    \"colsample_bytree\": [0.9, 0.91],\n    \"gamma\": [0.45],\n    \"learning_rate\": [0.26], # default 0.1 \n    \"max_depth\": [5], # default 3\n    \"n_estimators\": [150, 157, 160], # default 100\n    \"subsample\": [0.98, 0.97, 0.96]\n}\n\nGrid_CV = GridSearchCV(xgb, param_grid=params, cv=3, verbose=1, n_jobs=16, return_train_score=True)\nGrid_CV.fit(x_train, y_train)\nreport_best_scores(Grid_CV.cv_results_, 3)\nGrid_best_xgb = Grid_CV.best_estimator_\nGrid_best_xgb.fit(x_train, np.ravel(y_train)) \npreds_proba_Grid = Grid_best_xgb.predict_proba(x_test)\nprobs_Grid = preds_proba_Grid[:, 1]\nGrid_bestauc = roc_auc_score(y_test, probs_Grid)\nprint ('xgb base model AUROC socre: {}'.format(aucxgb))\nprint ('xgb best model using RandomizedSearchCV AUROC socre: {}'.format(Random_bestauc))\nprint ('xgb best model using GridSearchCV AUROC socre: {}'.format(Grid_bestauc))\n# display feature and their importance of the best model\nfeature_importance = pd.DataFrame({'feature': x_train.columns, \n                                   'importance': Grid_best_xgb.feature_importances_})\n\nnew_features_df = feature_importance[feature_importance['importance']>0\n                                    ].sort_values(by=['importance'],ascending=False)\n\nsns.set(context='paper', style='ticks',  font='sans-serif', \n        font_scale=1.2, color_codes=True, rc=None)\nfigure, ax = plt.subplots(figsize=(8, 5))\nax=sns.barplot(data = new_features_df[:10],\n              y='feature',\n              x='importance',\n              palette='Blues_d') # rocket, Blues_d\nax.set_title('feature importance', fontsize=14)\nax.set_xlabel('importance', fontsize=13)\nax.set_ylabel('feature', fontsize=13)\nplt.show()\n\n# display the top 10 important features\nnew_features_df.head(10)\n\"\"\"\n**Observation**\n\nThe top 5 important features includes:\n* `person_home_ownership_RENT`\n* `person_home_ownership_OWN`\n* `loan_grade_C`\n* `loan_percent_income`\n* `person_home_ownership_MORTGAGE`\n\"\"\"\n# select the top 20 features and then retrain the model\nnew_features = new_features_df['feature'][0:20]\nnew_features\n# Split Train and Test Sets\nnew_features_df = pd.DataFrame(cleaned_credit_df[new_features])\nnew_features_df.shape\nx_train1, x_test1, y_train1, y_test1 = model_selection.train_test_split(new_features_df, label, \n                                                                    random_state=42, test_size=.30)\nprint('The train dataset has {} data\\nThe test dataset has {} data'.\n      format(x_train.shape[0], x_test.shape[0]))\n# RandomizedSearchCV hyperparameter tuning\nparams = {\n    \"colsample_bytree\": uniform(0.9, 0.1), # 0.9-1 0.9 is the lower bound, 0.1 is the range\n    \"gamma\": uniform(0.2, 0.3),# 0.2-0.5\n    \"learning_rate\": uniform(0.2, 0.2), # 0.2-0.4 \n    \"max_depth\": randint(4, 6), # 4, 5, 6\n    \"n_estimators\": randint(100, 300), # 100-300\n    \"subsample\": uniform(0.9, 0.1) # 0.9-1\n}\n\nRandom_CV = RandomizedSearchCV(xgb, param_distributions=params, random_state=42, \n                            n_iter=100, cv=3, verbose=2, n_jobs=16, return_train_score=True)\n\nRandom_CV.fit(x_train1, y_train1)\nreport_best_scores(Random_CV.cv_results_, 3)\nRandom_best_xgb = Random_CV.best_estimator_\nRandom_best_xgb.fit(x_train, np.ravel(y_train)) \npreds_proba_Random = Random_best_xgb.predict_proba(x_test1)\nprobs_Random = preds_proba_Random[:, 1]\nRandom_bestauc = roc_auc_score(y_test1, probs_Random)\nprint ('xgb base model AUROC socre: {}'.format(aucxgb))\nprint ('xgb best model using RandomizedSearchCV AUROC socre: {}'.format(Random_bestauc))\n\"\"\"\n**Observation**\n\nit turns out after dropping some features, the model is only improved to 0.955, thus no furhter GridSearchCV is performed. And the original GridSearchCV best model will be used for futher threshhold optimizaiton. \n\"\"\"\n\"\"\"\n### Threshold Optimization\n\"\"\"\npreds = Grid_best_xgb.predict_proba(x_test) # 1st col = pred val, 2nd col = pred prob\n\npred_probs = pd.DataFrame(preds[:,1],columns = ['Default Probability'])\n\npd.concat([pred_probs, y_test.reset_index(drop=True)],axis=1)\nthresh = np.linspace(0,1,41)\nthresh\ndef optimize_threshold(predict,thresholds =thresh, y_true = y_test):\n    data = predict\n    \n    def_recalls = []\n    nondef_recalls = []\n    accs =[]\n\n    \n    for threshold in thresholds:\n        # predicted values for each threshold\n        data['loan_status'] = data['Default Probability'].apply(lambda x: 1 if x > threshold else 0 )\n        \n        accs.append(metrics.accuracy_score(y_true, data['loan_status']))\n        \n        stats = metrics.precision_recall_fscore_support(y_true, data['loan_status'], zero_division=0)\n        \n        def_recalls.append(stats[1][1])\n        nondef_recalls.append(stats[1][0])\n        \n        \n    return accs, def_recalls, nondef_recalls\n\naccs, def_recalls, nondef_recalls = optimize_threshold(pred_probs)\n\nfigure = plt.subplots(figsize=(8, 6))\nplt.plot(thresh,def_recalls)\nplt.plot(thresh,nondef_recalls)\nplt.plot(thresh,accs)\nplt.xlabel(\"Probability Threshold\")\nplt.legend([\"Default Recall\",\"Non-default Recall\",\"Model Accuracy\"])\nplt.show()\noptim_threshold = accs.index(max(accs))\n\nprint('The model accuracy is {} using the optimal probabilty threshold'\n      .format(round(accs[optim_threshold],3)))\n\nprint ('The optimal probabilty threshold is {}'.format(thresh[optim_threshold]))\n\"\"\"\n** Discussion**\n\n* The XGBClassifier has the best performance with 0.954 AUROC score compared to other three classifiers KNN, Logistic regression, and decision tree using the base model.\n\n* Using RandomizedSearchCV to fast optimize hyperparamters, the model AUROC is improved to 0.9563\n\n* With further fine tuning around those hyperparameters using GridSearchCV, the final best model has a 0.9571 AUROC score. \n\n* The optimal probability threshold for the best model is 0.55 resulting accuracy 0.939.\n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f65b1c26f2cb2a'}"}
{"id":"71301","text":"\"\"\"\n# GAN to assist in Melanoma Detection\n\n[melanoma competition](https:\/\/www.kaggle.com\/c\/siim-isic-melanoma-classification\/data)\n\n\"\"\"\nimport glob\nimport os\nimport time\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nprint(tf.__version__)\n\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom IPython import display\n\"\"\"\n## Why use GAN?\n\n* Dataset target classes are highly imbalance, only 1.76% of malignant\n\n## Interesting topics to try\n\n1. GAN to generate additional malignant class images\n2. Using VAEs to train anomaly detection from benign (non lethal) lesion\n3. GAN to generate SR and additional attention based cropping for train a better lesion classifier and detector\n\"\"\"\n# asign some paths\ntrain_csv_path = '..\/input\/siim-isic-melanoma-classification\/train.csv'\ntest_csv_path = '..\/input\/siim-isic-melanoma-classification\/test.csv'\nimage_path = '..\/input\/siim-isic-melanoma-classification\/jpeg\/train\/'\n\n# read the csv data using pandas\ntrain_df = pd.read_csv(train_csv_path)\ntest_df = pd.read_csv(test_csv_path)\n\nprint(\"unique values in column 'target': {}\".format(list(train_df['target'].unique())))\ntarget_dis = list(train_df['target'].value_counts())\nbenign_per = target_dis[0]\/sum(target_dis)\nprint(\"target count distribution: {}\".format(target_dis))\nprint(\"benign percentage: {:.2f}% vs malignant: {:.2f}%\".format(benign_per*100, (1-benign_per)*100))\n\"\"\"\n## 1. DCGAN to generate Malignant images\n\nSource\n* [code](https:\/\/www.tensorflow.org\/tutorials\/generative\/dcgan) \n* [GAN-based Synthetic Medical Image Augmentation](https:\/\/arxiv.org\/pdf\/1803.01229.pdf)\n\nDataset\n* [JPEG 128x128](https:\/\/www.kaggle.com\/cdeotte\/jpeg-melanoma-128x128) melanoma from Chris Deotte\n\nProblems:\n* Generated images are nowhere near the input images\n* Maybe needs some augmentation. [Augmentation in GAN](https:\/\/arxiv.org\/pdf\/2006.05338v1.pdf) \n\"\"\"\n# detect and initialize TPU (ignore if using GPU)\n# try:\n#     tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n#     print('Device:', tpu.master())\n#     tf.config.experimental_connect_to_cluster(tpu)\n#     tf.tpu.experimental.initialize_tpu_system(tpu)\n#     # set distribution strategy\n#     strategy = tf.distribute.experimental.TPUStrategy(tpu)\n# except:\n#     strategy = tf.distribute.get_strategy()\n# print('Number of replicas:', strategy.num_replicas_in_sync)\n\n# # Use these params if using TPU\n# IMAGE_SIZE = [128, 128]  # used for reshaping\n# AUTOTUNE = tf.data.experimental.AUTOTUNE\n# GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-128x128')  # store dataset to gcs buckets for the TPU to access in cloud\n# BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\"\"\"\n### Preprocess Image\n\"\"\"\npath_tfrec = '..\/input\/melanoma-128x128\/'\npath_jpg = '..\/input\/jpeg-melanoma-128x128\/train\/'\nIMAGE_SIZE = [128, 128]\n\nmalignant = train_df[train_df[\"target\"] == 1]  # list of malignant images\n\ndef preprocess_X():  # load the images into memory\n    X = []\n    for img in malignant.image_name.values:\n        img_name = path_jpg + img + '.jpg'\n        i = tf.keras.preprocessing.image.load_img(img_name) #color_mode='grayscale')\n        i = tf.keras.preprocessing.image.img_to_array(i)\n        i = preprocess_input(i)  # preprocessing fits the pixel value from -127.5 to 127.5\n        X.append(i)\n    return np.array(X)  # convert to numpy array\nX = preprocess_X()\nX.shape\n\"\"\"\n### Display preprocessed image\n\"\"\"\ndef display_img(arr):\n    i = tf.keras.preprocessing.image.array_to_img(arr)\n    plt.imshow(i, cmap='gray')\n\nplt.figure(figsize=(7,7))\nfor i in range(9):\n    plt.subplot(3,3, i+1)\n    display_img(X[i])  \n\"\"\"\n### Hyperparameters\n\"\"\"\nBUFFER_SIZE = 584\nBATCH_SIZE = 32  # from 128\nEPOCHS = 50  # from 50\nnoise_dim = 200  # from 100\nnum_examples_to_generate = 9\n\n# We will reuse this seed overtime (so it's easier to visualize progress in the animated GIF)\nseed = tf.random.normal([num_examples_to_generate, noise_dim])\n\"\"\"\n### Increase training data with Augmentations\n\"\"\"\ndef augmentation_pipeline(image):\n    image = tf.image.random_flip_left_right(image)\n#     image = tf.image.resize(image, IMAGE_RESIZE)\n    return image\n# Simple dataset processing with batch and shuffle\ndef get_dataset():\n    ds = tf.data.Dataset.from_tensor_slices(X)\n#     ds = ds.map(augmentation_pipeline)\n    ds = ds.shuffle(BUFFER_SIZE)\n    ds = ds.batch(BATCH_SIZE)\n    return ds\n    \ntrain_dataset = get_dataset()\n# inspect a batch\nn_batch = 0\nfor i in train_dataset:\n    n_batch += 1\nprint(f\"num of batch: {n_batch}, shape of each batch: {i.shape}\")\n\"\"\"\n### Create Generator and Discriminator\n\"\"\"\ndef make_generator_model():\n    model = tf.keras.Sequential()   # dense unit is configured to match soon tobe reshaped layer\n    model.add(layers.Dense(32*32*256, use_bias=False, input_shape=(noise_dim,)))  # starts with 1D array, input is noise array of 100\n    model.add(layers.BatchNormalization())\n    model.add(layers.LeakyReLU())\n\n    # 32x32 bcz there's 2 conv2D. 128\/2\/2=32\n    model.add(layers.Reshape((32, 32, 256)))\n\n    model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))\n    model.add(layers.BatchNormalization())\n    model.add(layers.LeakyReLU())\n\n    model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))\n    model.add(layers.BatchNormalization())\n    model.add(layers.LeakyReLU())\n\n    model.add(layers.Conv2DTranspose(3, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))\n\n    return model\n\n# create the generator\ngenerator = make_generator_model()\ngenerator.summary()\n\"\"\"\nDisplay an image generated from noise (G still not trained yet)\n\"\"\"\nnoise = tf.random.normal([1, noise_dim])  # outputs random values from normal dist. to a certain array shape\ngenerated_image = generator(noise, training=False)  # interesting, doesn't need .fit .predict or anything\n\nplt.imshow(generated_image[0, :, :, :]*255)#, cmap='gray')\ndef make_discriminator_model():\n    model = tf.keras.Sequential()   # basic binary classification model\n    model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',\n                                     input_shape=[128, 128, 3]))\n    model.add(layers.LeakyReLU())\n    model.add(layers.Dropout(0.3))\n\n    model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))\n    model.add(layers.LeakyReLU())\n    model.add(layers.Dropout(0.3))\n\n    model.add(layers.Flatten())\n    model.add(layers.Dense(1))\n\n    return model\n\n# create D\ndiscriminator = make_discriminator_model()\nprint(discriminator.summary())\n\"\"\"\nLet the untrained D predict that generated image\n\"\"\"\ndecision = discriminator(generated_image)\nprint(decision)\n\"\"\"\n## Define Loss and Optimizer\n\"\"\"\n# This method returns a helper function to compute cross entropy loss (prob between 0 and 1)\ncross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n\"\"\"\n### Discriminator Loss\nmeasures how well D distinguish real and fake images. It compares the discriminator's predictions on real images to an array of 1s, and the discriminator's predictions on fake (generated) images to an array of 0s.\n\"\"\"\ndef discriminator_loss(real_output, fake_output):\n    # ones_like creates array of ones with similar shape as the input array\n    real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n    fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n    total_loss = real_loss + fake_loss\n    return total_loss\n\"\"\"\n### Generator Loss\nMeasures how well G can trick D. If G is performing well, D will classify fake images as 1 (real)\nthe discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s. Here, we will compare the discriminators decisions on the generated images to an array of 1s.\n\"\"\"\ndef generator_loss(fake_output):\n    return cross_entropy(tf.ones_like(fake_output), fake_output)\n\"\"\"\n### Optimizers\n\"\"\"\ngenerator_optimizer = tf.keras.optimizers.Adam(1e-4)  # but here they use the same Adam anyway\ndiscriminator_optimizer = tf.keras.optimizers.Adam(1e-4)\n\"\"\"\n### Create callbacks\n\"\"\"\ncheckpoint_dir = '.\/training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n                                 discriminator_optimizer=discriminator_optimizer,\n                                 generator=generator,\n                                 discriminator=discriminator)\n\"\"\"\n### Defining training loop\n\nThe training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fake images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator.\n\"\"\"\n# Notice the use of `tf.function`\n# This annotation causes the function to be \"compiled\".\n@tf.function\ndef train_step(images):\n    noise = tf.random.normal([BATCH_SIZE, noise_dim])\n\n    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n        generated_images = generator(noise, training=True)\n        real_output = discriminator(images, training=True)\n        fake_output = discriminator(generated_images, training=True)\n\n        gen_loss = generator_loss(fake_output)\n        disc_loss = discriminator_loss(real_output, fake_output)\n\n    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)\n    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)\n\n    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))\n    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))\ndef train(dataset, epochs):\n    for epoch in range(epochs):\n        start = time.time()\n\n        for image_batch in dataset:\n            train_step(image_batch)\n\n        # Produce images for the GIF as we go\n        display.clear_output(wait=True)\n        generate_and_save_images(generator,\n                                 epoch + 1,\n                                 seed)\n\n        # Save the model every 15 epochs\n        if (epoch + 1) % 15 == 0:\n            checkpoint.save(file_prefix = checkpoint_prefix)\n\n        print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n\n        # Generate after the final epoch\n        display.clear_output(wait=True)\n        generate_and_save_images(generator, epochs, seed)\ndef generate_and_save_images(model, epoch, test_input):\n    # Notice `training` is set to False.\n    # This is so all layers run in inference mode (batchnorm).\n    predictions = model(test_input, training=False)  # same as num_examples_to_generate\n    fig = plt.figure(figsize=(12,12))\n\n    for i in range(predictions.shape[0]):\n        plt.subplot(3, 3, i+1)\n        plt.imshow(predictions[i, :, :, :] * 127.5 + 127.5, cmap='gray')\n        plt.axis('off')\n\n    plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n    plt.show()\ntrain(train_dataset, EPOCHS)\n\"\"\"\n## 2. GAN for anomali detection\n\n* Anomali detection in Alzheimer Disease with GAN\n* SHOW RESULTS\n\n* Also other research that has anomali results: HERE HERE and HERE\n* Very effective when positive samples are rare, it's also a how doctors learn to classify\n* But in melanoma, is it really effective? since the difference between benign and malignant images can sometimes be **very subtle**\n\"\"\"\n\"\"\"\n### 2.1 Papers on anomali detection\n\n* [Lesion detection in Brain MRI with constrained adversarial auto-encoder](https:\/\/arxiv.org\/pdf\/1806.04972.pdf)\n* \n\"\"\"\nbenign = train_df[train_df[\"target\"] == 0]\nmalignant = train_df[train_df[\"target\"] == 1]\n\ndef show_img(target, n=16):\n    img_name = target.image_name.values\n    ex_img = np.random.choice(img_name, n)  # grab n number of images\n    plt.figure(figsize=(15,15))\n    for i in range(n):\n        plt.subplot(4, 4, i + 1)\n        img = plt.imread(image_path + ex_img[i]+'.jpg')\n        plt.imshow(img, cmap='gray')\n        plt.axis('off')\n    plt.tight_layout()\nshow_img(benign)\nshow_img(malignant)","meta":"{'source': 'AI4Code', 'id': '832782d1e230a8'}"}
{"id":"88352","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\"\"\"\nLet's read our data into raw_data as a dataset and examine the contents and shape \n\"\"\"\nraw_data = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\npd.set_option(\"display.max_columns\",0)\nraw_data\n\"\"\"\nThe data consists of 1460 rows and 81 columns\n\"\"\"\nraw_data.shape\nnumeric = raw_data.select_dtypes({'int64','float64'}).columns\nnumeric\ncategorical = raw_data.select_dtypes({'object'}).columns\ncategorical\n#Number of numeric columns\nraw_data.select_dtypes({'int64','float64'}).shape\n#Number of categorical columns\nraw_data.select_dtypes({'object'}).shape\n\"\"\"\n# Step 1 : Analysing 'SalePrice'\n\"\"\"\n\"\"\"\nBefore we dive into exploring datasets and deploying ML algorithms, it would be nice to look into the SalePrice variable as it's the reason of our quest.\n\"\"\"\nraw_data['SalePrice'].describe()\n\"\"\"\nThe minimum price isn't negative. Thus, one less thing to worry.\n\"\"\"\nsns.distplot(raw_data['SalePrice'])\nraw_data['SalePrice'].skew()\n\"\"\"\nGoing by the definition, positve skewness implies that more number of houses are being sold for price less than the average value.\n\"\"\"\nraw_data['SalePrice'].kurt()\n\"\"\"\nKurtosis : The measure of outliers. Leptokurtic (positive kurtosis) implies that our dataset has heavy outliers\n\"\"\"\n\"\"\"\n# Intuitive parameters affecting SalePrice\n\"\"\"\n\"\"\"\nTo my knowledge and the variables present in the dataset. I classify the variables into 4 categories which one looks upon while deciding a house to buy.\n1. SIZE\/AREA - LotArea, TotalBsmntSF, Bedroom, GrLivArea\n2. LOCATION - Neighborhood, Condition1 ( Proximity to main road )\n3. BUILT - YearBuilt\n4. QUALITY - OverallQual\n\"\"\"\n\"\"\"\nBest way to check the correlation between parameters is i guess, HeatMap. Let's check whether our intuition about factors affecting SalePrice is correct or does it differs in actual.\n\"\"\"\n#correlation matrix\ncorrmat = raw_data.corr()\nplt.subplots(figsize=(10, 10))\nsns.heatmap(corrmat, square=True);\n\"\"\"\nLooking at the heatmap, the factors having a strong correlation with SalePrice I could see are : OverallQual, GrLivArea, GarageCars, GarageArea. We should also consider mild correlated factors which could be : YearBuilt, 1stFlrSF, TotalBsmntSF.\nAnyways, let's just take the top 10 factors depending upon the correlation with SalePrice.\n\"\"\"\nk = 10\nmost_correlated = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\nprint(most_correlated)\nfactors = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'GarageArea',\n            'TotalBsmtSF', '1stFlrSF', 'FullBath', 'TotRmsAbvGrd', 'YearBuilt']\n\"\"\"\n# Step 2 : Data Cleaning\n\"\"\"\n#Checking for duplicate values:\ndup_data = raw_data[raw_data.duplicated()]\ndup_data.shape[0]\n\"\"\"\nThus, we dont have any duplicate value in the data set.\n\"\"\"\ntotal = pd.isnull(raw_data).sum().sort_values(ascending=False)\npercentage = ((pd.isnull(raw_data).sum() \/ pd.isnull(raw_data).count()).sort_values(ascending=False))*100\nno_values = pd.concat([total,percentage],axis = 1, keys = ['Total', 'Percent'])\nno_values.head(19)\n\"\"\"\nIt seems that the data for columns with more than 15% null values i.e. PoolQC, MiscFeatur, Alley, Fence, FireplaceQu, LotFrontage is missing a lot. Trying to replace these values by mean\/median\/mode would definitely mean changing the distribution of the dataset. For example if we try to replace the missing values by mean value, it would imply that we have deviated the dataset toward mean.\n\"\"\"\nraw_data_without_null = raw_data.drop((no_values[no_values['Total'] > 1]).index,1)\n\"\"\"\nFor other columns, it's upto you how you treat your data. If you have expertise in the concerned field, you could treat the missing values accordingly, else (my case here): None of these columns have a strong correlation with SalePrice. Thus, could remove the entire column.\nAlso, for the 'Electrical' column we can just remove the row containing missing value, as only a single value is missing.\n\"\"\"\nraw_data_without_null = raw_data_without_null.dropna()\npd.isnull(raw_data_without_null).sum().max()\nraw_data_without_null.shape\n\"\"\"\nOUTLIER DETECTION\n\"\"\"\n\"\"\"\nI'll be using the box and whisker plot method to detect the outliers.\n1. I used the flooring and capping techique to mark the boundary.\n2. I used the outer boundary to remove the confirmed outliers and not the suspected outliers. If you wish you can try removing the suspected outliers as well.\n\"\"\"\nsns.boxplot(raw_data_without_null['OverallQual'])\nq1 = raw_data_without_null['OverallQual'].quantile(.25)\nq3 = raw_data_without_null['OverallQual'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['OverallQual'] > floor) & (raw_data_without_null['OverallQual'] < cap)]\nsns.boxplot(raw_data_without_null['GrLivArea'])\nq1 = raw_data_without_null['GrLivArea'].quantile(.25)\nq3 = raw_data_without_null['GrLivArea'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['GrLivArea'] > floor) & (raw_data_without_null['GrLivArea'] < cap)]\nsns.boxplot(raw_data_without_null['GarageCars'])\nq1 = raw_data_without_null['GarageCars'].quantile(.25)\nq3 = raw_data_without_null['GarageCars'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['GarageCars'] > floor) & (raw_data_without_null['GarageCars'] < cap)]\nsns.boxplot(raw_data_without_null['GarageArea'])\nq1 = raw_data_without_null['GarageArea'].quantile(.25)\nq3 = raw_data_without_null['GarageArea'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['GarageArea'] > floor) & (raw_data_without_null['GarageArea'] < cap)]\nsns.boxplot(raw_data_without_null['TotalBsmtSF'])\nq1 = raw_data_without_null['TotalBsmtSF'].quantile(.25)\nq3 = raw_data_without_null['TotalBsmtSF'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['TotalBsmtSF'] > floor) & (raw_data_without_null['TotalBsmtSF'] < cap)]\nsns.boxplot(raw_data_without_null['1stFlrSF'])\nq1 = raw_data_without_null['1stFlrSF'].quantile(.25)\nq3 = raw_data_without_null['1stFlrSF'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['1stFlrSF'] > floor) & (raw_data_without_null['1stFlrSF'] < cap)]\nsns.boxplot(raw_data_without_null['FullBath'])\nq1 = raw_data_without_null['FullBath'].quantile(.25)\nq3 = raw_data_without_null['FullBath'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['FullBath'] > floor) & (raw_data_without_null['FullBath'] < cap)]\nsns.boxplot(raw_data_without_null['TotRmsAbvGrd'])\nq1 = raw_data_without_null['TotRmsAbvGrd'].quantile(.25)\nq3 = raw_data_without_null['TotRmsAbvGrd'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['TotRmsAbvGrd'] > floor) & (raw_data_without_null['TotRmsAbvGrd'] < cap)]\nsns.boxplot(raw_data_without_null['YearBuilt'])\nq1 = raw_data_without_null['YearBuilt'].quantile(.25)\nq3 = raw_data_without_null['YearBuilt'].quantile(.75)\niqr = q3 - q1\nfloor = q1 - 3*iqr\ncap = q3 + 3*iqr\nprint('Floor = {}, Capping = {}'.format(floor,cap))\nraw_data_without_null = raw_data_without_null[(raw_data_without_null['YearBuilt'] > floor) & (raw_data_without_null['YearBuilt'] < cap)]\nraw_data_without_null.shape\n\"\"\"\n# Step 3 : Checking conditions for Linear Model\n\"\"\"\n\"\"\"\n1. Linearity - Check using scatter plots\n2. No Endogeneity\n3. Homoscedasticity\n4. No autocorrelation\n\"\"\"\ndata_cleaned = raw_data_without_null.copy()\ndata_use = data_cleaned[factors].copy()\nf, (ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9) = plt.subplots(1,9, sharey = True, figsize = (30,5))\nax1.scatter(data_use['OverallQual'],data_use['SalePrice'])\nax1.set_title('OverallQual and SalePrice')\n\nax2.scatter(data_use['GrLivArea'],data_use['SalePrice'])\nax2.set_title('GrLivArea and SalePrice')\n\nax3.scatter(data_use['GarageCars'],data_use['SalePrice'])\nax3.set_title('GarageCars and SalePrice')\n\nax4.scatter(data_use['GarageArea'],data_use['SalePrice'])\nax4.set_title('GarageArea and SalePrice')\n\nax5.scatter(data_use['TotalBsmtSF'],data_use['SalePrice'])\nax5.set_title('TotalBsmtSF and SalePrice')\n\nax6.scatter(data_use['1stFlrSF'],data_use['SalePrice'])\nax6.set_title('1stFlrSF and SalePrice')\n\nax7.scatter(data_use['FullBath'],data_use['SalePrice'])\nax7.set_title('FullBath and SalePrice')\n\nax8.scatter(data_use['TotRmsAbvGrd'],data_use['SalePrice'])\nax8.set_title('TotRmsAbvGrd and SalePrice')\n\nax9.scatter(data_use['YearBuilt'],data_use['SalePrice'])\nax9.set_title('YearBuilt and SalePrice')\n\"\"\"\nLooking from the about scatter plots some factors need to be treated for linearity before applying the regression model.\n1. OverallQual\n2. GarageArea\n3. TotalBsmtSF\n4. 1stFlrSF\n5. YearBuilt\n\"\"\"\n\"\"\"\nAs we saw above there was skewness in the SalePrice, which can be treated using the logarithmic transformation. Let's verify the skewness before and after the transformation.\n\"\"\"\ndata_use['logPrice'] = np.log(data_use['SalePrice'])\nbefore = raw_data['SalePrice'].skew()\nafter = data_use['logPrice'].skew()\nprint('Skewness before : {}, Skewness after : {}'.format(before,after))\n\"\"\"\nSee, by mere applying the log transformation the skewness got reduced to near 0 i.e. close to Normally Distributed Graph. Also, let's check the density plot for same.\n\"\"\"\nsns.distplot(data_use['logPrice'])\nf, (ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9) = plt.subplots(1,9, sharey = True, figsize = (30,5))\nax1.scatter(data_use['OverallQual'],data_use['logPrice'])\nax1.set_title('OverallQual and logPrice')\n\nax2.scatter(data_use['GrLivArea'],data_use['logPrice'])\nax2.set_title('GrLivArea and logPrice')\n\nax3.scatter(data_use['GarageCars'],data_use['logPrice'])\nax3.set_title('GarageCars and logPrice')\n\nax4.scatter(data_use['GarageArea'],data_use['logPrice'])\nax4.set_title('GarageArea and logPrice')\n\nax5.scatter(data_use['TotalBsmtSF'],data_use['logPrice'])\nax5.set_title('TotalBsmtSF and logPrice')\n\nax6.scatter(data_use['1stFlrSF'],data_use['logPrice'])\nax6.set_title('1stFlrSF and logPrice')\n\nax7.scatter(data_use['FullBath'],data_use['logPrice'])\nax7.set_title('FullBath and logPrice')\n\nax8.scatter(data_use['TotRmsAbvGrd'],data_use['logPrice'])\nax8.set_title('TotRmsAbvGrd and logPrice')\n\nax9.scatter(data_use['YearBuilt'],data_use['logPrice'])\nax9.set_title('YearBuilt and logPrice')\n\"\"\"\nIf not perfectly linear, we are still able to see some improvement in linearity after applying log transformation.\n\"\"\"\n\"\"\"\nNow coming to homoscedasticity, we already implemented the log transformation which is the best fix for heteroscedasticity. Thus, we don't need any other fix or tansformation.\n\"\"\"\n\"\"\"\nAutocorrelation needs to checked when the data is a time series. Observations here are not coming from a time series or a panel data. These are just the snapshot of current situation, where it's different for each customer.\n\"\"\"\n\"\"\"\nOur dataset is almost ready, but before we dive into modelling and predictions let's include the dummy variables for categorical data that we haven't used till now. At the initial stage we included location as a factor determinig the SalePrice of a house.  I'll add the 'Neighborhood' and 'Condition1' columns and create dummy variables.\n\"\"\"\nlocation = data_cleaned[['Neighborhood','Condition1']].copy()\ndata = data_cleaned[factors]\ndata_with_cat = data.join(location)\ndata_with_cat\ndata_with_cat['logPrice'] = np.log(data_with_cat['SalePrice'])\ndata_with_cat = data_with_cat.drop(['SalePrice'],axis=1)\ndata_with_dummies = pd.get_dummies(data_with_cat, drop_first = True)\ncols = ['logPrice','OverallQual', 'GrLivArea', 'GarageCars', 'GarageArea',\n       'TotalBsmtSF', '1stFlrSF', 'FullBath', 'TotRmsAbvGrd', 'YearBuilt',\n        'Neighborhood_Blueste', 'Neighborhood_BrDale',\n       'Neighborhood_BrkSide', 'Neighborhood_ClearCr',\n       'Neighborhood_CollgCr', 'Neighborhood_Crawfor',\n       'Neighborhood_Edwards', 'Neighborhood_Gilbert',\n       'Neighborhood_IDOTRR', 'Neighborhood_MeadowV',\n       'Neighborhood_Mitchel', 'Neighborhood_NAmes',\n       'Neighborhood_NPkVill', 'Neighborhood_NWAmes',\n       'Neighborhood_NoRidge', 'Neighborhood_NridgHt',\n       'Neighborhood_OldTown', 'Neighborhood_SWISU',\n       'Neighborhood_Sawyer', 'Neighborhood_SawyerW',\n       'Neighborhood_Somerst', 'Neighborhood_StoneBr',\n       'Neighborhood_Timber', 'Neighborhood_Veenker', 'Condition1_Feedr',\n       'Condition1_Norm', 'Condition1_PosA', 'Condition1_PosN',\n       'Condition1_RRAe', 'Condition1_RRAn', 'Condition1_RRNe',\n       'Condition1_RRNn']\ndata_preprocessed = data_with_dummies[cols]\ndata_preprocessed\n\"\"\"\n# Linear Regression Model\n\"\"\"\ninputs = data_preprocessed.drop(['logPrice'], axis = 1)\ntarget = data_preprocessed['logPrice']\nscaler = StandardScaler()\nscaler.fit(inputs)\nscaled_input = scaler.transform(inputs)\nx_train, x_test, y_train, y_test = train_test_split(scaled_input, target, test_size = 0.4, random_state = 365)\nlinReg = LinearRegression()\nlinReg.fit(x_train, y_train)\n\"\"\"\nThis is not simply a linear regression but a log linear regression as our dependent variable is logarithmic of SalePrice\n\"\"\"\ny_pred = linReg.predict(x_test)\n\"\"\"\nLet's try to visualize whether our predicted values form a linear relationship with our training data. We create a scatter plot between y-pred and y-train.\n\"\"\"\nplt.scatter(y_test,y_pred,alpha = 0.5)\nplt.xlabel('y_train')\nplt.ylabel('y_pred')\nsns.distplot(y_pred - y_test)\n\"\"\"\nThis probability density graph verifies the Normality assumption ( If error terms are not normal, then the standard errors of OLS estimates won\u2019t be reliable. ) for LinearRegression as the error terms are normally distributed.\n\"\"\"\nlinReg.score(x_test,y_test)\ndf_pred = pd.DataFrame(np.exp(y_pred), columns = ['Predictions'])\ny_test = y_test.reset_index(drop=True)\ndf_pred['Target'] = np.exp(y_test)\ndf_pred['Residual'] = df_pred['Target'] - df_pred['Predictions']\ndf_pred['Difference %'] =np.absolute((df_pred['Residual']\/df_pred['Target'])*100)\ndf_pred\ndf_pred.describe()\n\"\"\"\nWe got close in estimating the price correctly (min being 0.02% and third quartile of data being under 7.46%), but you can see the maximum difference % to 97%, which is clearly off the mark.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a215249852b414'}"}
{"id":"83385","text":"\"\"\"\n# <h1><center> Predictive Analysis - Porto Seguro\u2019s Safe Driver Prediction | Kaggle\n\"\"\"\n\"\"\"\n# <h1><center> I. Importation & Missing Value Check\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.offline as py     # \u7ed8\u56fe\u7684\u51fd\u6570\n\n\nimport plotly.graph_objs as go              # \u53ef\u7528\u4e8e\u7ed8\u5236\u4e0d\u540c\u56fe\u578b\uff0c\u5982 go.bar()\nimport plotly.express as px                 # \u53ef\u7528\u4e8e\u7ed8\u5236\u4e0d\u540c\u56fe\u578b\uff0c\u5982 px.bar()\nfrom plotly.subplots import make_subplots   # \u521b\u5efa\u5b50\u56fe\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)    #THIS LINE IS MOST IMPORTANT AS THIS WILL DISPLAY PLOT ON \n#NOTEBOOK WHILE KERNEL IS RUNNING\ntrain = pd.read_csv('..\/input\/porto-seguro-safe-driver-prediction\/train.csv')\ntest = pd.read_csv('..\/input\/porto-seguro-safe-driver-prediction\/test.csv')\ntrain.head()\n# Function to calculate missing values by column# Funct \ndef missing_values_table(df):\n        # Total missing values\n        mis_val = df.isnull().sum()\n\n        # Percentage of missing values\n        mis_val_percent = 100 * df.isnull().sum() \/ len(df)\n\n        # Make a table with the results\n        mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)\n\n        # Rename the columns\n        mis_val_table_ren_columns = mis_val_table.rename(\n        columns = {0 : 'Missing Values', 1 : '% of Total Values'})\n\n        # Sort the table by percentage of missing descending\n        mis_val_table_ren_columns = mis_val_table_ren_columns[\n            mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(\n        '% of Total Values', ascending=False).round(1)\n\n        # Print some summary information\n        print (\"Your selected dataframe has \" + str(df.shape[1]) + \" columns.\\n\"      \n            \"There are \" + str(mis_val_table_ren_columns.shape[0]) +\n            \" columns that have missing values.\")\n\n        # Return the dataframe with missing information\n        return mis_val_table_ren_columns\ntrain_copy = train\ntrain_copy = train_copy.replace(-1, np.NaN)\n# Missing values statistics\nmissing_values = missing_values_table(train_copy)  # train_copy \u662f\u4e00\u4e2a dataframe\nmissing_values.head(20)\n\"\"\"\n\u53ef\u4ee5\u770b\u51fa `ps_car_03_cat` \u548c `ps_car_05_cat` \u6240\u5360\u7f3a\u5931\u503c\u6bd4\u4f8b\u5f88\u9ad8\n\"\"\"\n\"\"\"\n# <center>II. Data Cleaning & Visualisation\n\"\"\"\n# train_counts = train.target.value_counts()\n# train_counts = pd.DataFrame(train_counts)\n\n# fig = px.bar(train_counts,x=train_counts.index,y='target',barmode='group',color='target')\n# fig.update_traces(textposition='outside')\n# fig.update_layout(template='seaborn',title='target (counts)')\n# fig.show()\n\"\"\"\n### \u76ee\u6807\u53d8\u91cf\u68c0\u6d4b\n\n\u5bf9\u4e8e\u5206\u7c7b\u53d8\u91cf\u6211\u4eec\u9700\u8981\u8fdb\u884c\u76ee\u6807\u53d8\u91cf\u68c0\u6d4b\uff0c\u5982\u679c\u6570\u636e\u5b58\u5728\u4e25\u91cd\u7684\u4e0d\u5e73\u8861\uff0c\u9884\u6d4b\u5f97\u51fa\u7684\u7ed3\u8bba\u5f80\u5f80\u4e5f\u662f\u6709\u504f\u7684\uff0c\u5373\u5206\u7c7b\u7ed3\u679c\u4f1a\u504f\u5411\u4e8e\u8f83\u591a\u89c2\u6d4b\u7684\u7c7b\u3002\n\n\"\"\"\ntrain_counts = train.target.value_counts()\ntrain_counts = pd.DataFrame(train_counts)\n\nfig = px.bar(train_counts,x=train_counts.index,y='target',barmode='group',color='target',text='target') # text \u53ef\u4ee5\u6807\u4e0a\u6570\u503c\nfig.update_traces(textposition='outside')\nfig.update_layout(yaxis_title='counts',xaxis_title='target',template='seaborn',title='target (counts)')\nfig.show()\n\"\"\"\n### \u4e8c\u8fdb\u5236\u6570\u636e\u68c0\u6d4b `bin`\n\"\"\"\nbin_col = [col for col in train.columns if '_bin' in col]\nzero_list = []\none_list = []\nfor col in bin_col:\n    zero_list.append((train[col]==0).sum())\n    one_list.append((train[col]==1).sum())\ntrace1 = go.Bar(\n    x=bin_col,\n    y=zero_list ,\n    name='Zero count'\n)\ntrace2 = go.Bar(\n    x=bin_col,\n    y=one_list,\n    name='One count'\n)\n\ndata = [trace1, trace2]\nlayout = go.Layout(\n    barmode='stack',\n    title='Count of 1 and 0 in binary variables'\n)\n\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\n\"\"\"\n\u6211\u4eec\u80fd\u770b\u5230\uff0c\u5bf9\u4e8e`10_bin` `11_bin` `12_bin` `13_bin` \u57fa\u672c\u4e0a\u5168\u662f\u76ee\u6807\u503c\u90fd\u4e3a 0\uff0c\u90a3\u4e48\u6211\u4eec\u53ef\u4ee5\u521d\u6b65\u5224\u65ad\u8fd9\u51e0\u4e2a\u7279\u5f81\u53ef\u80fd\u5bf9\u6211\u4eec\u7684\u76ee\u6807\u503c\u9884\u6d4b\u8d77\u4e0d\u4e86\u4f5c\u7528\uff0c\u7b49\u4e00\u4e0b\u6211\u4eec\u4e5f\u53ef\u4ee5\u518d\u8fdb\u4e00\u6b65\u7684\u53bb\u9a8c\u8bc1\u3002\n\"\"\"\n\"\"\"\n## \u6570\u636e\u4e0d\u5e73\u8861\n\n\u53ef\u4ee5\u53d1\u73b0\u6807\u7b7e\u4e4b\u524d\u5b58\u5728\u4e0d\u5e73\u8861\u7684\u72b6\u6001\uff0c\u5982\u679c\u6570\u636e\u5b58\u5728\u4e25\u91cd\u7684\u4e0d\u5e73\u8861\uff0c\u9884\u6d4b\u5f97\u51fa\u7684\u7ed3\u8bba\u5f80\u5f80\u4e5f\u662f\u6709\u504f\u7684\uff0c\u5373\u5206\u7c7b\u7ed3\u679c\u4f1a\u504f\u5411\u4e8e\u8f83\u591a\u89c2\u6d4b\u7684\u7c7b\u3002\n\n\u6bd4\u5982\u6211\u4eec\u4f7f\u7528\u51c6\u786e\u7387\u6765\u8fdb\u884c\u6a21\u578b\u7684\u8bc4\u4f30\uff0c\u5373\u4f7f\u6211\u4eec\u5168\u90e8\u9884\u6d4b\u6210 `target == 0`\uff0c\u90a3\u4e48\u4e5f\u6709\u5f88\u9ad8\u7684\u51c6\u786e\u7387: `573518\/(573518+21694)=0.96`\u3002\n\n\u6240\u4ee5\u5bf9\u4e8e\u5206\u7c7b\u4e0d\u5e73\u8861\u7684\u6570\u636e\uff0c\u6211\u4eec\u53ef\u4ee5\u8fdb\u884c\u5982\u4e0b\u64cd\u4f5c\uff1a\n\n### \u6b20\u91c7\u6837\uff1a\n\n\u968f\u673a\u6b20\u91c7\u6837\uff08\u4e0b\u91c7\u6837\uff09\u7684\u76ee\u6807\u662f\u901a\u8fc7\u968f\u673a\u5730\u6d88\u9664\u5360\u591a\u6570\u7684\u7c7b\u7684\u6837\u672c\u6765\u5e73\u8861\u7c7b\u5206\u5e03\uff1b\u76f4\u5230\u591a\u6570\u7c7b\u548c\u5c11\u6570\u7c7b\u7684\u5b9e\u4f8b\u5b9e\u73b0\u5e73\u8861\uff0c\u76ee\u6807\u624d\u7b97\u8fbe\u6210\u3002\n\n* `\u968f\u673a\u6b20\u91c7\u6837\uff08\u4e0b\u91c7\u6837\uff09`\u7684\u76ee\u6807\u662f\u901a\u8fc7\u968f\u673a\u5730\u6d88\u9664\u5360\u591a\u6570\u7684\u7c7b\u7684\u6837\u672c\u6765\u5e73\u8861\u7c7b\u5206\u5e03\uff1b\u76f4\u5230\u591a\u6570\u7c7b\u548c\u5c11\u6570\u7c7b\u7684\u5b9e\u4f8b\u5b9e\u73b0\u5e73\u8861\uff0c\u76ee\u6807\u624d\u7b97\u8fbe\u6210\u3002\n\n* `\u968f\u673a\u4e0b\u91c7\u6837\u7684\u4f18\u70b9\uff1a`\n    \n    \u5b83\u53ef\u4ee5\u63d0\u5347\u8fd0\u884c\u65f6\u95f4\uff1b\u5e76\u4e14\u5f53\u8bad\u7ec3\u6570\u636e\u96c6\u5f88\u5927\u65f6\uff0c\u53ef\u4ee5\u901a\u8fc7\u51cf\u5c11\u6837\u672c\u6570\u91cf\u6765\u89e3\u51b3\u5b58\u50a8\u95ee\u9898\u3002\n\n* `\u968f\u673a\u4e0b\u91c7\u6837\u7684\u7f3a\u70b9\uff1a`\n    \n    \u5b83\u4f1a\u4e22\u5f03\u5bf9\u6784\u5efa\u89c4\u5219\u5206\u7c7b\u5668\u5f88\u91cd\u8981\u7684\u6709\u4ef7\u503c\u7684\u6f5c\u5728\u4fe1\u606f\u3002\n\n    \u88ab\u968f\u673a\u6b20\u91c7\u6837\u9009\u53d6\u7684\u6837\u672c\u53ef\u80fd\u5177\u6709\u504f\u5dee\u3002\u5b83\u4e0d\u80fd\u51c6\u786e\u4ee3\u8868\u5927\u591a\u6570\u3002\u4ece\u800c\u5728\u5b9e\u9645\u7684\u6d4b\u8bd5\u6570\u636e\u96c6\u4e0a\u5f97\u5230\u4e0d\u7cbe\u786e\u7684\u7ed3\u679c\u3002\u679c\u3002\n\n\n### \u8fc7\u91c7\u6837\n\n\n* `\u968f\u673a\u8fc7\u91c7\u6837` \u901a\u8fc7\u968f\u673a\u590d\u5236\u5c11\u6570\u7c7b\u6765\u589e\u52a0\u5176\u4e2d\u7684\u5b9e\u4f8b\u6570\u91cf\uff0c\u4ece\u800c\u53ef\u589e\u52a0\u6837\u672c\u4e2d\u5c11\u6570\u7c7b\u7684\u4ee3\u8868\u6027\u3002\n\n* `\u968f\u673a\u8fc7\u91c7\u6837\u7684\u4f18\u70b9\uff1a`\n\n    \u4e0e\u6b20\u91c7\u6837\u4e0d\u540c\uff0c\u8fd9\u79cd\u65b9\u6cd5\u4e0d\u4f1a\u5e26\u6765\u4fe1\u606f\u635f\u5931\u3002\n\n    \u8868\u73b0\u4f18\u4e8e\u6b20\u91c7\u6837\u3002\n\n* `\u968f\u673a\u8fc7\u91c7\u6837\u7684\u7f3a\u70b9\uff1a`\n    \n    \u7531\u4e8e\u590d\u5236\u5c11\u6570\u7c7b\u4e8b\u4ef6\uff0c\u5b83\u52a0\u5927\u4e86\u8fc7\u62df\u5408\u7684\u53ef\u80fd\u6027\u3002\n    \n\n\u672c notebook \u5c06\u91c7\u7528 SMOTE \u6765\u8fdb\u884c\u8fc7\u91c7\u6837\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nimport lightgbm as lgb\nfrom xgboost import XGBClassifier\n\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import recall_score\n\"\"\"\n### \u4e0d\u8fdb\u884c\u91c7\u6837\uff0c\u76f4\u63a5\u8fdb\u884c\u6a21\u578b\u8bad\u7ec3\u548c\u9884\u6d4b\u67e5\u770b\u6a21\u578b\u8d28\u91cf\n\n* \u901a\u8fc7\u5bf9\u6bd4\u51c6\u786e\u5ea6\u548c\u53ec\u56de\u7387\n    \n* \u901a\u8fc7\u7ed8\u5236\u6df7\u6dc6\u77e9\u9635\n\"\"\"\n\"\"\"\n### 1\u3001\u5bf9\u6bd4\u51c6\u786e\u5ea6\u548c\u53ec\u56de\u7387\n\"\"\"\ntrain_target = train['target']\n# train_feature = train.drop(columns='target')\ntrain_feature = train.drop(columns = ['target','id'])\n\n\nx_train,x_test,y_train,y_test = train_test_split(train_feature,train_target,test_size= 0.2,random_state=10)\n# model = XGBClassifier(n_estimators=1000)\nmodel = XGBClassifier()\n\n\nmodel.fit(x_train,y_train)\ny_pred = model.predict(x_test)\n\nacc = accuracy_score(y_test,y_pred)\nrecall = recall_score(y_test,y_pred)\n\nprint('Accuracy: {:.3f}'.format(acc* 100.0))\nprint('recall: {:.3f}'.format(recall* 100.0))\n\"\"\"\n\u53ef\u4ee5\u770b\u5230\uff0c\u5373\u4f7f\u4f60\u7684\u51c6\u786e\u7387\u975e\u5e38\u9ad8\uff0c\u4f46\u662f\u53ec\u56de\u7387\u5374\u975e\u5e38\u4f4e    \n\"\"\"\n\"\"\"\n### 2\u3001\u7ed8\u5236\u6df7\u6dc6\u77e9\u9635\n\n\u6df7\u6dc6\u77e9\u9635\u7528\u6cd5\u793a\u4f8b\uff0c\u7528\u4e8e\u8bc4\u4f30\u6570\u636e\u96c6\u4e0a\u5206\u7c7b\u5668\u8f93\u51fa\u7684\u8d28\u91cf\u3002 \u5bf9\u89d2\u7ebf\u5143\u7d20\u8868\u793a\u9884\u6d4b\u6807\u7b7e\u7b49\u4e8e\u771f\u5b9e\u6807\u7b7e\u7684\u70b9\u6570\uff0c\u800c\u975e\u5bf9\u89d2\u7ebf\u5143\u7d20\u5219\u662f\u5206\u7c7b\u5668\u672a\u6b63\u786e\u6807\u8bb0\u7684\u5143\u7d20\u3002 \u6df7\u6dc6\u77e9\u9635\u7684\u5bf9\u89d2\u7ebf\u503c\u8d8a\u9ad8\uff0c\u8868\u793a\u5bf9\u6570\u8d8a\u591a\u8d8a\u597d\u3002\u6df7\u6dc6\u77e9\u9635\u7528\u6cd5\u793a\u4f8b\uff0c\u7528\u4e8e\u8bc4\u4f30\u6570\u636e\u96c6\u4e0a\u5206\u7c7b\u5668\u8f93\u51fa\u7684\u8d28\u91cf\u3002 \u5bf9\u89d2\u7ebf\u5143\u7d20\u8868\u793a\u9884\u6d4b\u6807\u7b7e\u7b49\u4e8e\u771f\u5b9e\u6807\u7b7e\u7684\u70b9\u6570\uff0c\u800c\u975e\u5bf9\u89d2\u7ebf\u5143\u7d20\u5219\u662f\u5206\u7c7b\u5668\u672a\u6b63\u786e\u6807\u8bb0\u7684\u5143\u7d20\u3002 \u6df7\u6dc6\u77e9\u9635\u7684\u5bf9\u89d2\u7ebf\u503c\u8d8a\u9ad8\uff0c\u8868\u793a\u5bf9\u6570\u8d8a\u591a\u8d8a\u597d\u3002\n\"\"\"\ndef plot_confusion_matrix(cm, classes,\n                                normalize=False,\n                                title='Confusion matrix',\n                                cmap=plt.cm.Blues):\n        \"\"\"\n            \u6b64\u51fd\u6570\u6253\u5370\u5e76\u7ed8\u5236\u6df7\u6dc6\u77e9\u9635\u3002\n            \u53ef\u4ee5\u901a\u8fc7\u8bbe\u7f6e\u201c normalize = True\u201d\u6765\u5e94\u7528\u5f52\u4e00\u5316\u3002\n        \"\"\"\n        plt.imshow(cm, interpolation='nearest', cmap=cmap)\n        plt.title(title)\n        plt.colorbar()\n        tick_marks = np.arange(len(classes))\n        plt.xticks(tick_marks, classes, rotation=45)\n        plt.yticks(tick_marks, classes)\n\n        if normalize:\n            cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n            print(\"Normalized confusion matrix\")\n        else:\n            print('Confusion matrix, without normalization')\n\n        print(cm)\n\n        thresh = cm.max() \/ 2.\n        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n            plt.text(j, i, cm[i, j],\n                        horizontalalignment=\"center\",\n                        color=\"white\" if cm[i, j] > thresh else \"black\")\n\n        plt.tight_layout()\n        plt.ylabel('True label')\n        plt.xlabel('Predicted label')\nclasses = ['target_0','target_1'] # \u987a\u5e8f\u522b\u641e\u9519\nnp.set_printoptions(precision=2)\n\ncm = confusion_matrix(y_test,y_pred)\nplt.figure()\nplot_confusion_matrix(cm,classes)\nplt.show()\n\n# plt.figure()\n# plot_confusion_matrix(cm,classes,normalize=True)\n# plt.show()\n\"\"\"\n### \u4f7f\u7528 SMOTE \u8fdb\u884c\u8fc7\u91c7\u6837\n\"\"\"\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import StandardScaler\n\"\"\"\n### \u67e5\u770b2D\u6570\u636e\u7684\u5206\u5e03\n\"\"\"\n# \u5b9a\u4e49\u7ed8\u56fe\u51fd\u6570\ndef plot_2d_space(X, y, label='Classes'):   \n            colors = ['#1F77B4', '#FF7F0E']\n            markers = ['o', 's']\n            for l, c, m in zip(np.unique(y), colors, markers):\n                plt.scatter(\n                    X[y==l, 0],\n                    X[y==l, 1],\n                    c=c, label=l, marker=m\n                )\n            plt.title(label)\n            plt.legend(loc='upper right')\n            plt.show()\n            \nprint(\"label0: \",len(x_train[y_train==0]))\nprint(\"label1: \",len(x_train[y_train==1]))\n\nss = StandardScaler()\nX = ss.fit_transform(x_train)\n\n# `2\u3001`\u5982\u679c\u6570\u636e\u5b58\u5728\u591a\u7ef4\u7279\u5f81\u53ef\u4f7f\u7528PCA\u6765\u964d\u7ef4\uff0c\u4f7f\u5176\u80fd\u57282D\u56fe\u4e2d\u5c55\u793a\n\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\nX = pca.fit_transform(X)\n\nplot_2d_space(X, y_train, 'Imbalanced dataset (2 PCA components)')\noversampler=SMOTE(random_state=0)\n# \u5f00\u59cb\u4eba\u5de5\u5408\u6210\u6570\u636e\nos_features,os_labels=oversampler.fit_sample(x_train,y_train)\n\n# \u67e5\u770b\u751f\u6210\u7ed3\u679c\nprint(\"label1: \",len(os_labels[os_labels==1]))\nprint(\"label0: \",len(os_labels[os_labels==0]))\noversampler=SMOTE(random_state=0)\n# \u5f00\u59cb\u4eba\u5de5\u5408\u6210\u6570\u636e\nos_features_test,os_labels_test=oversampler.fit_sample(x_test,y_test)\n\n# \u67e5\u770b\u751f\u6210\u7ed3\u679c\nprint(\"label1: \",len(os_labels_test[os_labels_test==1]))\nprint(\"label0: \",len(os_labels_test[os_labels_test==0]))\nss = StandardScaler()\nX = ss.fit_transform(os_features)\n\npca = PCA(n_components=2)\nX = pca.fit_transform(X)\n\nplot_2d_space(X, os_labels, 'Imbalanced dataset (2 PCA components)')\n\"\"\"\n### \u7279\u5f81\u76f8\u5173\u6027\u68c0\u6d4b\n\"\"\"\n\"\"\"\n1\u3001\u7279\u5f81\u548c\u76ee\u6807\u7279\u5f81\u4e4b\u95f4\u7684\u76f8\u5173\u6027\u68c0\u6d4b\n\"\"\"\nnew_os_features = os_features.copy()\nnew_os_features['target'] = os_labels\n\n# Find correlations with the target and sort\ncorrs = new_os_features.corr()['target'].sort_values(ascending=False)\ncorrelations = pd.DataFrame(corrs)\n\n# Display correlations\nprint('Most Positive Correlations:\\n')\ncorrelations.head()\nprint('Most Negative Correlations:\\n')\ncorrelations.tail()\ncorrelations.loc[correlations.index.isin(['ps_ind_10_bin','ps_ind_11_bin','ps_ind_12_bin','ps_ind_13_bin'])]\nnp.abs(corrs).sort_values(ascending=False).tail(15)\n\"\"\"\n\u6211\u4eec\u53ef\u4ee5\u770b\u51fa \u5728 `bin` \u7c7b\u578b\u7684\u7279\u5f81\u4e2d `ps_ind_10_bin`,`ps_ind_11_bin`,`ps_ind_12_bin`,`ps_ind_13_bin` \u786e\u5b9e\u662f\u5f71\u54cd\u529b\u6700\u4f4e\u7684\u7279\u5f81\n\"\"\"\n\"\"\"\n2\u3001\u7279\u5f81\u4e0e\u7279\u5f81\u4e4b\u95f4\u8fdb\u884c\u76f8\u5173\u6027\u68c0\u6d4b\n\"\"\"\ncorrs = os_features.corr()\n\"\"\"\n3\u3001\u5220\u9664\u5171\u7ebf\u7279\u5f81\n\"\"\"\n# \u8bbe\u7f6e\u9608\u503c\nthreshold = 0.8\n\n# \u521b\u5efa\u4e00\u4e2a\u7a7a\u5b57\u5178\u4ee5\u5bb9\u7eb3\u76f8\u5173\u53d8\u91cf\nabove_threshold_vars = {}\n\n# \u5bf9\u4e8e\u6bcf\u4e00\u5217\uff0c\u8bb0\u5f55index\u884c\u4e2d\u7684\u90a3\u4e2a\u503c\u9ad8\u4e8e\u9608\u503c\u7684\u53d8\u91cf\nfor col in corrs:\n    above_threshold_vars[col] = list(corrs.index[corrs[col] > threshold])\n# above_threshold_vars\n# \u8ddf\u8e2a\u8981\u5220\u9664\u7684\u5217\u548c\u5df2\u68c0\u67e5\u7684\u5217\ncols_to_remove = []\ncols_seen = []\ncols_to_remove_pair = []\n\n# \u904d\u5386\u5217\u548c\u76f8\u5173\u5217\nfor key, value in above_threshold_vars.items():\n    # \u8ddf\u8e2a\u5df2\u68c0\u67e5\u7684\u5217\n    cols_seen.append(key)\n    for x in value:\n        if x == key:\n            next\n        else:\n            # \u5982\u679c\u5b58\u5728\u9ad8\u76f8\u5173\u7684\u7279\u5f81\uff0c\u53ea\u4fdd\u7559\u4e00\u4e2a\n            if x not in cols_seen:                  # \u5982\u679c\u8be5\u7279\u5f81\u5728\u4e4b\u524d\u7684 key \u6570\u636e\u4e2d\u6ca1\u6709\u51fa\u73b0\u8fc7\u3002\n                cols_to_remove.append(x)            # \u5b58\u5728\u9ad8\u5ea6\u76f8\u5173\uff0c\u5c06\u9ad8\u5ea6\u76f8\u5173\u7684\u7279\u5f81\u653e\u5165 cols_to_remove \u4e2d\u3002\n                cols_to_remove_pair.append(key)     # cols_to_remove \u548c cols_to_remove_pair \u5f97\u5230\u7684\u7ed3\u679c\u4e00\u81f4\u3002\n\ncols_to_remove = list(set(cols_to_remove))\nprint('Name of columns to remove: ', cols_to_remove)\nprint('Number of columns to remove: ', len(cols_to_remove))\ntrain_corrs_removed = os_features.drop(columns = cols_to_remove)\ntest_corrs_removed = os_features_test.drop(columns = cols_to_remove)\n\nprint('Training Corrs Removed Shape: ', train_corrs_removed.shape)\nprint('Testing Corrs Removed Shape: ', test_corrs_removed.shape)\ntrain_corrs_removed.to_csv('train_corrs_removed.csv', index = False)\ntest_corrs_removed.to_csv('test_corrs_removed.csv', index = False)\n\"\"\"\n# <center>III. ML Approach\n\"\"\"\n\"\"\"\n### XGBoost\u8bad\u7ec3\u6a21\u578b\n\n\u4f7f\u7528 gini \u7cfb\u6570\u8bc4\u4f30 + \u4ea4\u53c9\u9a8c\u8bc1\n\"\"\"\n# `1\u3001\u5b9a\u4e49\u57fa\u5c3c\u7cfb\u6570\uff1a`\n\ndef gini(y, pred):\n    g = np.asarray(np.c_[y, pred, np.arange(len(y)) ], dtype=np.float)\n    g = g[np.lexsort((g[:,2], -1*g[:,1]))]\n    gs = g[:,0].cumsum().sum() \/ g[:,0].sum()\n    gs -= (len(y) + 1) \/ 2.\n    return gs \/ len(y)\n\n# `2\u3001\u5b9a\u4e49 xgb gini \u7cfb\u6570\uff1a`\n\n# \u8fd4\u56de\u4e00\u4e2a normalized \u540e\u7684 gini \u5206\u6570\ndef gini_xgb(pred, y):\n    y = y.get_label()\n    return 'gini', gini(y, pred) \/ gini(y, y)\n\"\"\"\n### \u8fc7\u91c7\u6837\u524d\u6570\u636e\u8fdb\u884c\u8bad\u7ec3\n\"\"\"\nfrom sklearn.model_selection import StratifiedKFold\nimport xgboost as xgb\nimport lightgbm as lgb\nparams = {'eta': 0.02, 'max_depth': 4, 'subsample': 0.9, 'colsample_bytree': 0.9, \n          'objective': 'binary:logistic', 'eval_metric': 'auc', 'silent': True}\n\nnrounds=200  \nkfold = 2\nskf = StratifiedKFold(n_splits=kfold, random_state=0)\n\nfor i, (train_index, test_index) in enumerate(skf.split(train_feature, train_target)):\n    print(' xgb kfold: {}  of  {} : '.format(i+1, kfold))\n    X_train, X_valid = train_feature.loc[train_index], train_feature.loc[test_index]\n    y_train, y_valid = train_target.loc[train_index], train_target.loc[test_index]\n    d_train = xgb.DMatrix(X_train, y_train) \n    d_valid = xgb.DMatrix(X_valid, y_valid) \n    watchlist = [(d_train, 'train'), (d_valid, 'valid')]\n    xgb_model = xgb.train(params, d_train, nrounds, watchlist, early_stopping_rounds=100, \n                          feval=gini_xgb, maximize=True, verbose_eval=100)\n    \n# xgb_y_pred = xgb_model.predict(xgb.DMatrix(test[features].values), \n#                         ntree_limit=xgb_model.best_ntree_limit+50)\nfeatures = train_feature.columns\ntest_ids = test['id']\nxgb_test_predictions1 = xgb_model.predict(xgb.DMatrix(test[features]),ntree_limit=xgb_model.best_ntree_limit+50)\n\nsubmission = pd.DataFrame({'id': test_ids, 'target': xgb_test_predictions1})\nsubmission.to_csv('before_oversampling_xgb.csv', index = False, float_format='%.5f')\n\"\"\"\n`Kfold = 2` and `nrounds = 200` \u63d0\u4ea4\u540e\uff1a`score=0.254` \n\n`Kfold = 5` and `nrounds = 2000` \u63d0\u4ea4\u540e\uff1a`score=0.2767` \n\"\"\"\n\"\"\"\n### \u7279\u5f81\u9009\u62e9\n\n\u7ed8\u5236 xgb \u6a21\u578b\u7279\u5f81\u7684\u91cd\u8981\u6027\u56fe\n\"\"\"\ndef model_feature_importances(model):\n    trace = go.Scatter(\n        y = np.array(list(model.get_fscore().values())),\n        x = np.array(list(model.get_fscore().keys())),\n        mode='markers',\n        marker=dict(\n            sizemode = 'diameter',\n            sizeref = 1,\n            size = 13,\n            #size= model.feature_importances_,\n            #color = np.random.randn(500), #set color equal to a variable\n            color =  np.array(list(model.get_fscore().values())),\n            colorscale='Portland',\n            showscale=True\n        ),\n        text = np.array(list(model.get_fscore().keys()))\n    )\n    data = [trace]\n\n    layout= go.Layout(\n        autosize= True,\n        title= 'xgb Feature Importance',\n        hovermode= 'closest',\n         xaxis= dict(\n             ticklen= 5,\n             showgrid=False,\n            zeroline=False,\n            showline=False\n         ),\n        yaxis=dict(\n            title= 'Feature Importance',\n            showgrid=False,\n            zeroline=False,\n            ticklen= 5,\n            gridwidth= 2\n        ),\n        showlegend= False\n    )\n    fig = go.Figure(data=data, layout=layout)\n    fig.show()\n\nmodel_feature_importances(xgb_model)\n\"\"\"\n\u66f4\u8fd1\u4e00\u6b65\uff0c\u6211\u4eec\u8fd8\u80fd\u901a\u8fc7\u7ed8\u5236\u67f1\u72b6\u56fe(\u6a2a)\u6765\u5bf9\u7279\u5f81\u91cd\u8981\u6027\u8fdb\u884c\u6548\u679c\u5c55\u793a\n\"\"\"\nxgb_importance = np.array(list(xgb_model.get_fscore().values()))\nxgb_features = np.array(list(xgb_model.get_fscore().keys()))\n\nx, y = (list(x) for x in zip(*sorted(zip(xgb_importance,xgb_features), reverse = False)))\ntrace2 = go.Bar(\n    x=x ,\n    y=y,\n    marker=dict(\n        color=x,\n        colorscale = 'Viridis',\n        reversescale = True\n    ),\n    name='Random Forest Feature importance',\n    orientation='h',\n)\n\nlayout = dict(\n    title='Barplot of Feature importances',\n    width = 900, height = 2000,\n    yaxis=dict(\n        showgrid=False,\n        showline=False,\n        showticklabels=True,\n#         domain=[0, 0.85],\n    ))\n\nfig1 = go.Figure(data=[trace2])\nfig1['layout'].update(layout)\npy.iplot(fig1, filename='plots')\n\"\"\"\n\u4ece\u56fe\u4e2d\u6211\u4eec\u80fd\u53d1\u73b0\u4e2a\u522b\u7279\u5f81\u91cd\u8981\u6027\u975e\u5e38\u4f4e\uff0c\u6211\u4eec\u53ef\u4ee5\u8fdb\u884c\u5254\u9664\n\"\"\"\nnew_features = pd.DataFrame(xgb_model.get_fscore(),index=['features_importance']).T\\\n                        .sort_values(by='features_importance',ascending=False)\\\n                        .iloc[0:38]\nnew_features \ntrain_feature.shape\nnew_train_feature = train_feature[new_features.index]\nnew_train_feature.head()\nnew_train_feature.shape\nparams = {'eta': 0.02, 'max_depth': 4, 'subsample': 0.9, 'colsample_bytree': 0.9, \n          'objective': 'binary:logistic', 'eval_metric': 'auc', 'silent': True}\n\nnrounds=200  \nkfold = 2\nskf = StratifiedKFold(n_splits=kfold, random_state=0)\n\nfor i, (train_index, test_index) in enumerate(skf.split(new_train_feature, train_target)):\n    print(' xgb kfold: {}  of  {} : '.format(i+1, kfold))\n    X_train, X_valid = new_train_feature.loc[train_index], new_train_feature.loc[test_index]\n    y_train, y_valid = train_target.loc[train_index], train_target.loc[test_index]\n    d_train = xgb.DMatrix(X_train, y_train) \n    d_valid = xgb.DMatrix(X_valid, y_valid) \n    watchlist = [(d_train, 'train'), (d_valid, 'valid')]\n    xgb_model2 = xgb.train(params, d_train, nrounds, watchlist, early_stopping_rounds=100, \n                          feval=gini_xgb, maximize=True, verbose_eval=100)\nxgb_test_predictions2 = xgb_model2.predict(xgb.DMatrix(test[new_features.index]),ntree_limit=xgb_model2.best_ntree_limit+50)\n\nsubmission = pd.DataFrame({'id': test_ids, 'target': xgb_test_predictions2})\nsubmission.to_csv('before_oversampling_after_feature_choose_xgb.csv', index = False, float_format='%.5f')\n\"\"\"\n### xgb + lgb \u5806\u53e0\u8bad\u7ec3\u9884\u6d4b\n\n\u5bf9\u9009\u51fa\u6765\u7684\u7279\u5f81\u8fdb\u884c\u8bad\u7ec3\n\"\"\"\ndef gini_lgb(preds, dtrain):\n    y = list(dtrain.get_label())\n    score = gini(y, preds) \/ gini(y, y)\n    return 'gini', score, True\n# https:\/\/www.kaggle.com\/rshally\/porto-xgb-lgb-kfold-lb-0-282\n\n# xgb\n# params = {'eta': 0.02, 'max_depth': 4, 'subsample': 0.9, 'colsample_bytree': 0.9, \n#         'objective': 'binary:logistic', 'eval_metric': 'auc', 'silent': True}\n\n# submission=test['id'].to_frame()\n# submission['target']=0\n\n# nrounds=200  # need to change to 2000\n# kfold = 2  # need to change to 5\n# skf = StratifiedKFold(n_splits=kfold, random_state=0)\n# for i, (train_index, test_index) in enumerate(skf.split(new_train_feature, train_target)):\n#     print(' xgb kfold: {}  of  {} : '.format(i+1, kfold))\n#     X_train, X_valid = new_train_feature.loc[train_index], new_train_feature.loc[test_index]\n#     y_train, y_valid = train_target.loc[train_index], train_target.loc[test_index]\n#     d_train = xgb.DMatrix(X_train, y_train) \n#     d_valid = xgb.DMatrix(X_valid, y_valid) \n#     watchlist = [(d_train, 'train'), (d_valid, 'valid')]\n#     xgb_model3 = xgb.train(params, d_train, nrounds, watchlist, early_stopping_rounds=100, \n#                         feval=gini_xgb, maximize=True, verbose_eval=100)\n\n#     # \u7ed3\u5c3e \u9664\u4ee5 (2*kfold)\uff0c\u662f\u56e0\u4e3a\u8981\u5c06 xgb \u548c lgb \u53bb\u5e73\u5747\u7136\u540e\u5c06\u7ed3\u679c\u76f8\u52a0\u5408\u5e76\n#     submission['target'] += xgb_model3.predict(xgb.DMatrix(test[new_features.index]), \n#                         ntree_limit=xgb_model3.best_ntree_limit+50) \/ (2*kfold)\n    \n# submission.head(2)\n\n# # lgb\n# params = {'metric': 'auc', 'learning_rate' : 0.01, 'max_depth':10, 'max_bin':10,  'objective': 'binary', \n#         'feature_fraction': 0.8,'bagging_fraction':0.9,'bagging_freq':10,  'min_data': 500}\n\n# skf = StratifiedKFold(n_splits=kfold, random_state=1)\n# for i, (train_index, test_index) in enumerate(skf.split(new_train_feature, os_labels)):\n#     print(' lgb kfold: {}  of  {} : '.format(i+1, kfold))\n#     X_train, X_eval = new_train_feature.loc[train_index], new_train_feature.loc[test_index]\n#     y_train, y_eval = train_target.loc[train_index], train_target.loc[test_index]\n#     lgb_model = lgb.train(params, lgb.Dataset(X_train, label=y_train), nrounds, \n#                 lgb.Dataset(X_eval, label=y_eval), verbose_eval=100, \n#                 feval=gini_lgb, early_stopping_rounds=100)\n\n#     # \u7ed3\u5c3e \u9664\u4ee5 (2*kfold)\uff0c\u662f\u56e0\u4e3a\u8981\u5c06 xgb \u548c lgb \u53bb\u5e73\u5747\u7136\u540e\u5c06\u7ed3\u679c\u76f8\u52a0\u5408\u5e76\n#     submission['target'] += lgb_model.predict(test[new_features.index], \n#                         num_iteration=lgb_model.best_iteration) \/ (2*kfold)\n\n# submission.to_csv('before_oversampling_lgb+xgb.csv', index=False, float_format='%.5f') \n\n# submission.head(2)\n# submission.to_csv('before_oversampling_after_feature_choose_xgb.csv', index = False, float_format='%.5f')\n\"\"\"\n### \u8fc7\u91c7\u6837\u540e\u6570\u636e\u8fdb\u884c\u8bad\u7ec3\n\noversampling good or bad?\n\n\u5bf9\u91c7\u6837\u540e\u7684\u6570\u636e\u8fdb\u884c\u8bad\u7ec3\uff0c\u53d1\u73b0\u9884\u6d4b\u51fa\u6765\u7684\u7ed3\u679c\u5206\u6570\u5f88\u4f4e\n\"\"\"\n# params = {'eta': 0.02, 'max_depth': 4, 'subsample': 0.9, 'colsample_bytree': 0.9, \n#           'objective': 'binary:logistic', 'eval_metric': 'auc', 'silent': True}\n\n# nrounds=200  \n# kfold = 2  \n# skf = StratifiedKFold(n_splits=kfold, random_state=0)\n\n# for i, (train_index, test_index) in enumerate(skf.split(os_features, os_labels)):\n#     print(' xgb kfold: {}  of  {} : '.format(i+1, kfold))\n#     X_train, X_valid = os_features.loc[train_index], os_features.loc[test_index]\n#     y_train, y_valid = os_labels.loc[train_index], os_labels.loc[test_index]\n#     d_train = xgb.DMatrix(X_train, y_train) \n#     d_valid = xgb.DMatrix(X_valid, y_valid) \n#     watchlist = [(d_train, 'train'), (d_valid, 'valid')]\n#     xgb_model2 = xgb.train(params, d_train, nrounds, watchlist, early_stopping_rounds=100, \n#                           feval=gini_xgb, maximize=True, verbose_eval=100)\n\n# xgb_test_predictions = xgb_model2.predict(xgb.DMatrix(test[features]), \n#                         ntree_limit=xgb_model2.best_ntree_limit+50)\n# submission = pd.DataFrame({'id': test_ids, 'target': xgb_test_predictions})\n# submission.to_csv('after_oversampling_xgb.csv', index = False, float_format='%.5f')\n\"\"\"\n# <center> IV. Extend...\n\"\"\"\n\"\"\"\n### RandomForestClassifier \u8bad\u7ec3\u6570\u636e\n\n\u63a5\u4e0b\u6765\u6211\u4eec\u5c06\uff1a\n\n* 1\u3001\u4f7f\u7528 RandomForestClassifier \u6765\u8fdb\u884c\u8bad\u7ec3\u6570\u636e\n\n* 2\u3001\u7ed8\u5236\u7279\u5f81\u7684\u91cd\u8981\u6027\u56fe\n\n* 3\u3001\u5e76\u4e14\u8fdb\u4e00\u6b65\u8fdb\u884c\u7279\u5f81\u9009\u62e9\n\"\"\"\n# from sklearn.ensemble import RandomForestClassifier\n# os_features.drop(['id'],axis=1,inplace=True)\n# os_features_test.drop(['id'],axis=1,inplace=True)\n\n\n# rdf_clf = RandomForestClassifier(n_estimators=150, max_depth=8, min_samples_leaf=4, max_features=0.2, n_jobs=-1, random_state=0)\n# rdf_clf.fit(os_features, os_labels)\n# features = os_features.columns.values\n# print(\"----- Training Done -----\")\n# RandomForestClassifier feature importances Scatter plot \n\n# def rdf_feature_importances(model):\n#     trace = go.Scatter(\n#         y = model.feature_importances_,\n#         x = features,\n#         mode='markers',\n#         marker=dict(\n#             sizemode = 'diameter',\n#             sizeref = 1,\n#             size = 13,\n#             #size= model.feature_importances_,\n#             #color = np.random.randn(500), #set color equal to a variable\n#             color = model.feature_importances_,\n#             colorscale='Portland',\n#             showscale=True\n#         ),\n#         text = features\n#     )\n#     data = [trace]\n\n#     layout= go.Layout(\n#         autosize= True,\n#         title= 'Random Forest Feature Importance',\n#         hovermode= 'closest',\n#          xaxis= dict(\n#              ticklen= 5,\n#              showgrid=False,\n#             zeroline=False,\n#             showline=False\n#          ),\n#         yaxis=dict(\n#             title= 'Feature Importance',\n#             showgrid=False,\n#             zeroline=False,\n#             ticklen= 5,\n#             gridwidth= 2\n#         ),\n#         showlegend= False\n#     )\n#     fig = go.Figure(data=data, layout=layout)\n#     fig.show()\n\n# rdf_feature_importances(model=rdf_clf)\n\"\"\"\n\u66f4\u8fd1\u4e00\u6b65\uff0c\u6211\u4eec\u8fd8\u80fd\u901a\u8fc7\u7ed8\u5236\u67f1\u72b6\u56fe(\u6a2a)\u6765\u5bf9\u7279\u5f81\u91cd\u8981\u6027\u8fdb\u884c\u6548\u679c\u5c55\u793a\n\"\"\"\n# x, y = (list(x) for x in zip(*sorted(zip(rdf_clf.feature_importances_, features), \n#                                                             reverse = False)))\n# trace2 = go.Bar(\n#     x=x ,\n#     y=y,\n#     marker=dict(\n#         color=x,\n#         colorscale = 'Viridis',\n#         reversescale = True\n#     ),\n#     name='Random Forest Feature importance',\n#     orientation='h',\n# )\n\n# layout = dict(\n#     title='Barplot of Feature importances',\n#      width = 900, height = 2000,\n#     yaxis=dict(\n#         showgrid=False,\n#         showline=False,\n#         showticklabels=True,\n# #         domain=[0, 0.85],\n#     ))\n\n# fig1 = go.Figure(data=[trace2])\n# fig1['layout'].update(layout)\n# py.iplot(fig1, filename='plots')\n# y_pred = rdf_clf.predict(os_features_test)\n\n# acc = accuracy_score(os_labels_test,y_pred)\n# recall = recall_score(os_labels_test,y_pred)\n\n# print('Accuracy: {:.3f}'.format(acc* 100.0))\n# print('recall: {:.3f}'.format(recall* 100.0))\n# model = XGBClassifier()\n\n\n# model.fit(os_features,os_labels)\n# y_pred = model.predict(os_features_test)\n\n# acc = accuracy_score(os_labels_test,y_pred)\n# recall = recall_score(os_labels_test,y_pred)\n\n# print('Accuracy: {:.3f}'.format(acc* 100.0))\n# print('recall: {:.3f}'.format(recall* 100.0))\n\"\"\"\n\u6211\u4eec\u53ef\u4ee5\u770b\u51fa\u76f8\u6bd4\u4e8e\u4e4b\u524d\u7684\u4e0d\u5e73\u8861\u6570\u636e\uff0c\u8fc7\u91c7\u6837\u540e\u7684\u6570\u636e\uff0c\u53ec\u56de\u7387\u5f97\u5230\u4e86\u660e\u663e\u7684\u4e0a\u5347\n\"\"\"\n\"\"\"\n### \u5bf9\u6570\u636e\u8fdb\u884c\u9884\u6d4b\n\n\u4f7f\u7528 \u4ea4\u53c9\u9a8c\u8bc1 \u653e\u6cd5\u8fdb\u884c\u6a21\u578b\u8bad\u7ec3\n\"\"\"\n\"\"\"\n\u968f\u673a\u68ee\u6797\u9884\u6d4b\u7ed3\u679c\uff1a\n\"\"\"\n# test_predictions = rdf_clf.predict(new_test)\n\n# submission = pd.DataFrame({'id': test_ids, 'target': test_predictions})\n# submission.to_csv('RandomForestClassifier_predict_1.csv', index = False)\n# submission.head()\n\"\"\"\n### \u7279\u5f81\u9009\u62e9\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '99125b733cbd65'}"}
{"id":"47961","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\ndf = pd.read_csv(\"\/kaggle\/input\/meteorite-landings\/meteorite-landings.csv\")\ndf.head()\ndf.info()\ndf = df.dropna(subset=[\"reclong\", \"reclat\"])\ndf = df[df.reclong < 300]\n\"\"\"\n## 2D Histogram\n\"\"\"\nplt.hist2d(df.reclong, df.reclat, bins=200, vmax=4)\nplt.colorbar();\n\"\"\"\n# Contour \n\"\"\"\nspacing = np.linspace(0,10,200)\nX,Y = np.meshgrid(spacing,spacing)\nZ = (np.sin(X) + np.cos(Y) + 2 * np.arcsinh(X * Y))**2\n\nplt.contour(X,Y,Z, levles=20)\nplt.colorbar();\nc = plt.contour(X,Y,Z, levels=20)\nplt.clabel(c, inline=True, fmt=\"%0.1f\")\nplt.colorbar();\nc = plt.contourf(X,Y,Z, levels=20)\nplt.colorbar();\nplt.contourf(X,Y,Z,levels=10)\nc = plt.contour(X,Y,Z, levels=10, colors='black')\nplt.clabel(c, inline=True, fmt=\"%0.1f\");\n\"\"\"\n# Joinplots\n\"\"\"\nsb.jointplot(data=df, x=\"reclong\", y=\"reclat\");\nsb.jointplot(data=df,x=\"reclong\", y=\"reclat\", kind=\"hex\",\n             gridsize=100, vmax=3, linewidth=0, marginal_kws={\"bins\": 100});","meta":"{'source': 'AI4Code', 'id': '5859aea1b839eb'}"}
{"id":"20887","text":"\"\"\"\n# About\nThis notebook is my EDA for the Tabular Playground Series June 2021. The June competitions has quite some similarities to the May competition. For the May EDA please see my notebook [TPS5 - EDA raising more questions than answers](https:\/\/www.kaggle.com\/melanie7744\/tps5-eda-raising-more-questions-than-answers).\n\nHere is a summary of my findings, please find the details below. \n\n**The most obivous similarities are:**\n- multi-class classification problem\n- mulit-class log loss as evaluation metric\n- anonymized (obfuscated) features\n- most feature values are 0\n- there are no binary features\n\n**The differences lie in the details:**\n- 9 classes vs 4 in TPS5\n- 75 features vs 50 in TPS5\n- training and testing data are twice as big as in TPS5\n- the features do not have any negative values\n- there are much more \"feature duplicates\" than in TPS5\n\n\nIf you like my analysis, please upvote!\n\nLet's load the environment and look at training and testing data.\n\"\"\"\n# 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\nimport matplotlib\nimport matplotlib.pyplot as plt # plotting\n%matplotlib inline \nprint(\"matplotlib version: {}\". format(matplotlib.__version__))\nmatplotlib.style.use('seaborn')\n\nimport seaborn as sns\nprint(\"seaborn version: {}\". format(sns.__version__))\n\nimport sklearn # machine learning algorithms\nprint(\"scikit-learn version: {}\". format(sklearn.__version__))\nfrom sklearn.preprocessing import StandardScaler\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\n# read competition data files\ndf_train = pd.read_csv('..\/input\/tabular-playground-series-jun-2021\/train.csv')\ndf_test = pd.read_csv('..\/input\/tabular-playground-series-jun-2021\/test.csv')\nsample_submission = pd.read_csv('..\/input\/tabular-playground-series-jun-2021\/sample_submission.csv')\ndf_all = df_train.append(df_test, ignore_index = True) \n\"\"\"\n# Data Overview\n\"\"\"\nprint(\"Size of training data: \",df_train.shape)\ndf_train.head()\nprint(\"Size of testing data: \",df_test.shape)\ndf_test.head()\nfeature_cols = [col for col in df_train.columns if col.startswith(\"feat\")]\ndf_train.describe().transpose()\\\n        .drop(\"id\")\\\n        .style.bar(subset=['mean','std'])\\\n        .background_gradient(subset=['max'])\ndf_test.describe().transpose()\\\n        .drop(\"id\")\\\n        .style.bar(subset=['mean','std'])\\\n        .background_gradient(subset=['max'])\n# number of rows with any values below zero\ndisplay(df_train[(df_train.drop([\"target\"],axis=1) < 0).any(1)].shape)\ndf_test[(df_test < 0).any(1)].shape\n\"\"\"\nWe can see here, that there are no missing values. The variable statistics are comparable between training and testing data. Most features are in a range from 0 to 100, with a few exceptions. The highest value of any feature is 352. This is much higher than the highest value in TPS5. Like in TPS5 0 is by far the most common value for any feature. \n\"\"\"\n\"\"\"\n# Target Variable Analysis\n\"\"\"\n# check the target variable\ntarget_absolute = df_train.target.value_counts()\ntarget_percent = df_train.target.value_counts(normalize=True)\ntarget_distribution = pd.DataFrame(data={'absolute':target_absolute, 'percent': target_percent})\ntarget_distribution[['percent']] = target_distribution[['percent']].applymap(lambda x: \"{0:.2f}%\".format(x*100))\ntarget_distribution\nplt.figure( figsize=(12,6))\nax= target_distribution['absolute'].sort_values(ascending=True).plot(kind='barh')\nax.set_title(\"Distribution of Target Variable\")\nax.set_xlabel(\"Count\")\n\nrects = ax.patches\nlabels = target_distribution['absolute'].sort_values(ascending=True)\nfor rect, label in zip(rects, labels):\n    width = rect.get_width()\n    ax.text(width +1500 ,rect.get_y() + rect.get_height() \/ 2, label,\n            ha='center', va='center')\nplt.show()\n\"\"\"\nThe target variable is imbalanced with Class_6 and Class_8 sharing half of the values. \n\"\"\"\n\"\"\"\n# Duplicates\n\"\"\"\n# check for true duplicates, i.e. where features and target match\ndf_dupli_f = df_train[df_train.drop(columns=[\"id\"]).duplicated(keep=\"first\")]\nprint(\"Number of duplicates: \", df_dupli_f.shape[0]) \nprint(\"Number of duplicates per class: \\n\", df_dupli_f.target.value_counts())\n# drop duplicates\ndf_train = df_train.drop(columns=[\"id\"]).drop_duplicates()\ndf_train.shape\n# check for duplicates in the feature columns, only possible for training data\ndf_dupli_f = df_train[df_train.drop(columns=[\"target\"]).duplicated(keep=\"first\")].copy() \ndf_dupli_f[\"f_sum\"] = df_dupli_f.sum(axis=1, numeric_only=True)\n#display(df_dupli_f.sort_values(by=\"f_sum\")) # sort the df to find matching duplicates easier\nprint(\"Number of duplicates per class if first duplicate is kept: \\n\", df_dupli_f.target.value_counts())\n\ndf_dupli_l = df_train[df_train.drop(columns=[\"target\"]).duplicated(keep=\"last\")].copy()\ndf_dupli_l[\"f_sum\"] = df_dupli_l.sum(axis=1, numeric_only=True)\n#display(df_dupli_l.sort_values(by=\"f_sum\"))\nprint(\"Number of duplicates per class if last duplicate is kept: \\n\",df_dupli_l.target.value_counts())\n#df_train.drop(columns=[\"target\"]).loc[131686] == df_train.drop(columns=[\"target\"]).loc[66469] # this is a feature dupliacte pair, row 131686 \u2014> Class_2 vs. row 66469 \u2014> Class_3\n# look at test set only\ndf_test[df_test.drop(columns=[\"id\"]).duplicated(keep=\"first\")]\n# check for samples with identical features in train and test data\ndf_train_temp = df_train.drop(columns=\"target\").drop_duplicates()\ndf_test_temp = df_test.drop(columns=\"id\").drop_duplicates()\ndf_all_temp = df_train_temp.append(df_test_temp, ignore_index = True) \ndf_all_temp[df_all_temp.duplicated(keep=\"last\")] # this shows the rows from the training data, keep=\"last\" would show the rows from the testing data\n\"\"\"\nIn the **training data** we have 106 true duplicates. That is rows where features and target match.\n\nBut we also have 118 \"feature duplicates\" here. That is, rows where the features are the same but the target variable is different! An example would be: \n- row 131686-> Class_2 vs. \n- row  66469-> Class_3\n\nAnd just by counting the target variable values for the feature dupliates it can be seen that they do not match. \n\nIn the **test set** we have 79 rows indicated as duplicates. Comparing them to the number of dupicates in the train set 106+118 = 224, their number is a bit lower than expected.\n\nIf we **combine the training and testing set** we have 101 rows with identical features. So the model gets the exact same data in the test set that it learned from in the training phase. Would be interesting to check exactly those predictions. \n\nWhile TPS5 with a low number of feature duplicates led me to just drop them, I will think twice if this is a good approach here, for TPS6.\n\nSome further investigation made me believe that this is an artifact from making a synthetic dataset. So no use trying to make sense out of those rows, \"just\" decide how to deal with them.\n\"\"\"\n\"\"\"\n# Feature Value Distributions\n\"\"\"\n# thanks to Maxim Kazantsev (@maximkazantsev) for this function! I adapted it slighty\ndef make_data_plots(df, i=0):\n    \"\"\"\n    Makes value distribution histogram plots for a given dataframe features\n    df should contain only the features to be plotted\n    \"\"\"\n    columns = df.columns.values\n\n    cols = 4\n    rows = (len(columns) - i) \/\/ cols + 1\n\n    fig, axs = plt.subplots(ncols=cols, nrows=rows, figsize=(16,rows*4), sharey=True)\n    \n    plt.subplots_adjust(hspace = 0.2)\n    for r in np.arange(0, rows, 1):\n        for c in np.arange(0, cols, 1):\n            if i >= len(columns):\n                axs[r, c].set_visible(False)\n            else:\n                axs[r, c].hist(df[columns[i]].values, bins = 30)\n                axs[r, c].set_title(columns[i], fontsize=12, pad=5)\n            i+=1\n            \n            \nmake_data_plots(df_train[feature_cols])\nmake_data_plots(df_test[feature_cols])\n\"\"\"\nWe can see here that all distributions are right skewed. Some very heavily.\n\"\"\"\n\"\"\"\n# Feature Value Analysis\n\"\"\"\n# let's check if there are as many unique feature values as the range of values\npd.options.display.max_rows = 75\ndf_features = df_all[feature_cols] # use df_all, df_test here depending on what you want to see\n\nfeature_range = df_features.max() - df_features.min()\nno_unique_values = df_features.nunique()\n\nunique_values = pd.DataFrame(data={\"feature_range\": feature_range, \"no_unique_values\": no_unique_values})\nunique_values.plot(kind=\"barh\", figsize=(12,24), color=['tab:blue', 'tab:orange'])\nplt.show()\n\"\"\"\nHere we see a quite different picture than in TPS5. Now, in TPS6, there are no low cardinality features. There are many features with a seizable difference between their value range and their number of unique features. I am still puzzeld what to make out of this observation. Any ideas?\n\"\"\"\n# check how many % of feature values are 0\nzerolist = []\n\nfor col in feature_cols:\n    zeroperc = df_train[col].value_counts()[0]\/df_train.shape[0]\n    zerolist.append(zeroperc)\n    \nzeros = round(pd.Series(data=zerolist)*100,2)\nzeros.sort_values(ascending=False).plot(kind='bar', figsize=(20,6))\nplt.axhline(y=50)\nplt.title(\"Percentage of Zeros in each feature\")\nplt.xlabel(\"Feature Number\")\nplt.ylabel(\"%\")\nplt.annotate(zeros.max(),xy=(0,zeros.max()+2))\nplt.annotate(zeros.min(),xy=(73,zeros.min()+2))\nplt.show()\n\"\"\"\nThere feature with the highest number of zeros has 86.09% zeros in it. The feature with the lowest number of zeros has 28.97% of zeros in it. Only 10 features have less than 50% of zeros. \n\"\"\"\n\"\"\"\n# Viz per Feature\n\"\"\"\n# choose feature for a closer look\ncurrent_feature = \"feature_17\"\ncurrent_df = df_train\nprint(current_feature)\n\nfig = plt.figure(figsize=fsize) # create figure\nfsize = (10,6)\nax0 = fig.add_subplot(2, 1, 1) # add subplot 1 (2 rows, 1columns, first plot)\nax1 = fig.add_subplot(2, 1, 2)\n#current_df[current_feature].hist(figsize=fsize, ax=ax0)\nsns.histplot(x=current_feature, data=current_df, ax=ax0) # just an alternative with sns instead of plt\nsns.boxplot(x=current_feature, data=current_df, ax=ax1)\nplt.show()\n\nprint(current_df[current_feature].value_counts())\n\"\"\"\n# Sample Analysis\n\"\"\"\ndf_train = pd.read_csv('..\/input\/tabular-playground-series-jun-2021\/train.csv') # read again, because of dropped duplicates\ntarget_col = df_train.target # store the target column, it interfers with the calcluations below\ndf_train.drop(columns=\"target\", inplace=True)\nif \"id\" in df_train.columns.to_list(): # if the id is still present, remove it beause it screws computations\n    df_train.drop(columns=\"id\", inplace=True)\nrownumber = 3 # enter the row you want to analyse\npd.Series(data=df_train[feature_cols].loc[rownumber].values).plot(kind='bar', figsize=(16,6))\nplt.title(\"Sample {} Values\".format(rownumber))\nplt.show()\n# get the number of entries that are not 0 in each row\nnumber_nz = np.count_nonzero(df_train, axis=1) #dont assign directly to df_train, this will inclued number_nz in sum_nz! (learning by mistakes...)\n# get the sum of the entered values in each row\nsum_nz = df_train.sum(axis=1, numeric_only=True) \ndf_train[\"number_nz\"] = number_nz \ndf_train[\"sum_nz\"] = sum_nz\ndf_train.tail()\ndf_train.number_nz.value_counts()#.plot(kind='barh', figsize=(16,12))\n# ... there are 5422 rows where 27 features have entries (to be preceise: non zero entries)\n# ... there is 1 row where 65 features have entries\n# ... and there are 9 rows where no features have entries\n# add the target column back to check for target when all features are 0\ndf_train['target'] = target_col\ndf_train[df_train.number_nz == 0]\n# repeat for test data\ndf_test.drop(columns=\"id\", inplace=True)\n# get the number of entries that are not 0 in each row\nnumber_nz = np.count_nonzero(df_test, axis=1) #dont assign directly to df_train, this will inclued number_nz in sum_nz! (learning by mistakes...)\n# get the sum of the entered values in each row\nsum_nz = df_test.sum(axis=1, numeric_only=True) \ndf_test[\"number_nz\"] = number_nz \ndf_test[\"sum_nz\"] = sum_nz\n# check for all zero samples\ndf_test[df_test.number_nz == 0]\n\"\"\"\nIn the training data there are 9 rows where all features are 0. These 9 rows have different target classes: 5x Class_2, 2x Class_6, 1x Class_5, 1x Class_3.\n\nThere are also 6 rows with 0 for all features in the test set. Ids: 221601, 232129, 245875, 250216, 284469, 295642. So at least train and test have the same properties... Although the number of zero features is a big higher than expected in the test set. \n\nSome further investigation made me believe that this is an artifact from making a synthetic dataset. So no use trying to make sense out of those rows, \"just\" decide how to deal with them.\n\"\"\"\n\"\"\"\n# Set Baseline\n\"\"\"\n# predict like train set probabilites\nfor col in sample_submission.drop(columns=\"id\"):\n    sample_submission.loc[:,col] = target_distribution.percent.loc[col]\n\nsample_submission.to_csv('submission.csv', index=False)\nsample_submission","meta":"{'source': 'AI4Code', 'id': '264a20bc9a90e1'}"}
{"id":"27659","text":"\"\"\"\n# Census Income Data Set\n\"\"\"\n\"\"\"\n## **Table of Content**\n\n\"\"\"\n\"\"\"\n### **1. Introduction**\n     1.1 Data Description\n     1.2 Features Description\n     1.3 Objective of this project\n  \n\n### **2. Fetching Data**\n    2.1 Import packages\n    2.2 Import data\n\n\n### **3. Data Cleaning**\n\n### **4. Summary**\n    4.1 Summary statistics for numeric attribute\n    4.2 Summary and count for categorical attribute\n\n### **5. EDA**\n#### 5.1.Univariate analysis\n    histograms and count plots for all single variables\n#### 5.2.Bivariate analysis\n    relationship with income for all variables            \n#### 5.3.Multivariate analysis\n    5.3.1 Correlation among the numeric variables.\n    5.3.2 Multivariate analysis between \"income\", \"age\", \"gender\"\n    5.3.3 Multivariate Analysis between \"income\", \"hours-per-week\", \"gender\"\n    5.3.4 Making new variable(capital_change)\n   \n### **6. Conclusion of Complete EDA**\n\"\"\"\n\"\"\"\n# 1. Introduction:\n\"\"\"\n\"\"\"\nA census is the procedure of systematically acquiring and recording information about the members of a given population.\nThe census is a special, wide-range activity, which takes place once a decade in the entire country. The purpose is to gather information about the general population, in order to present a full and reliable picture of the population in the country - its housing conditions and demographic, social and economic characteristics. The information collected includes data on age, gender, country of origin, marital status, housing conditions, marriage, education, employment, etc.\n\"\"\"\n\"\"\"\n## 1.1  Data description\n\"\"\"\n\"\"\"\nThis data was extracted from the 1994 Census bureau database by Ronny Kohavi and Barry Becker (Data Mining and Visualization, Silicon Graphics).  The prediction task is to determine whether a person makes over $50K a year.\n\"\"\"\n\"\"\"\n## 1.2 Features Description\n\"\"\"\n\"\"\"\n**1. Categorical Attributes**\n * **workclass**:  Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.\n  -  Individual work category  \n * **education**: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool.\n  -  Individual's highest education degree  \n * **marital-status**: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse.\n  -  Individual marital status  \n * **occupation**:  Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces.\n  -  Individual's occupation  \n * **relationship**:  Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried.\n  -  Individual's relation in a family   \n * ** race**:  White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black.\n  -  Race of Individual   \n * **sex**:  Female, Male.\n * **native-country**:  United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands.\n  -  Individual's native country   \n\"\"\"\n\"\"\"\n**2. Continuous Attributes**\n * **age**: continuous.\n  -  Age of an individual  \n * **fnlwgt**: final weight, continuous. \n * The weights on the CPS files are controlled to independent estimates of the civilian noninstitutional population of the US.  These are prepared monthly for us by Population Division here at the Census Bureau.\n * **capital-gain**: continuous.\n * **capital-loss**: continuous.\n * **hours-per-week**: continuous.\n  -  Individual's working hour per week   \n\"\"\"\n\"\"\"\n## 1.3 Objective of this project\n\"\"\"\n\"\"\"\nThe goal of this machine learning project is to predict whether a person makes over 50K a year or not given their demographic variation. This is a classification problem.\n\"\"\"\n\"\"\"\n# 2. Fetching Data:\n\"\"\"\n\"\"\"\n## 2.1 Import packages\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom scipy.stats import ttest_ind, ttest_rel\nfrom scipy import stats\n\"\"\"\n## 2.2 Import data\n\"\"\"\ndata = pd.read_csv(\"..\/input\/adult.csv\")\ndata.head(10)\n\"\"\"\nAt a first glance of our dataset, we can see that missing values are present in the form of \"?\" in \"workclass\",\"occupation\", \"native-country\".\n\"\"\"\ndata.shape\ndata_num = data.copy()\n\"\"\"\nThis shows that we have 48842 observation and 15 attributes including target attribute(income).\n\"\"\"\n\"\"\"\n# 3. Data Cleaning\n\"\"\"\n\"\"\"\n**Fixing the common nan values**\n\"\"\"\n\"\"\"\n> Nan values were as ? in data. Hence we fix this with most frequent element(mode) in the entire dataset. It generalizes well, as we will see with the accuracy of our classifiers\n\"\"\"\nattrib, counts = np.unique(data['workclass'], return_counts = True)\nmost_freq_attrib = attrib[np.argmax(counts, axis = 0)]\ndata['workclass'][data['workclass'] == '?'] = most_freq_attrib \n\nattrib, counts = np.unique(data['occupation'], return_counts = True)\nmost_freq_attrib = attrib[np.argmax(counts, axis = 0)]\ndata['occupation'][data['occupation'] == '?'] = most_freq_attrib \n\nattrib, counts = np.unique(data['native-country'], return_counts = True)\nmost_freq_attrib = attrib[np.argmax(counts, axis = 0)]\ndata['native-country'][data['native-country'] == '?'] = most_freq_attrib \n\"\"\"\nLets look the data it again :\n\"\"\"\ndata.head(10)\ndata['income']=data['income'].map({'<=50K': 0, '>50K': 1, '<=50K.': 0, '>50K.': 1})\ndata.head()\n\"\"\"\n# 4. Summary\n\"\"\"\n\"\"\"\n## 4.1 Summary statistics for numeric attribute\n\"\"\"\ndata_num = data.drop([\"educational-num\",\"income\"], axis=1)\ndata_num.describe()\n\"\"\"\nSummary of attributes explain following things:\n>  **For Age :**\n1.  The mean value is 38 i.e. on an average the value of age attribute is 38.\n2.  Age is having the standerd deviation 13.71 which indicates the deviation of an observation from the mean.    \n3.  The value of Age attribute varies from 17 to 90.\n4.  The 1st quartile is 28 i.e. 25% of the observations lies below 28.\n5.  3rd quartile is 48 which indicates that in 75% of the observations the value of age is less than 48.\n6.  The difference between 1st quartile and the minimum is lesser than the difference between 3rd quartile and the maximum which is showing that the data is more dispersed after the value 48.\n7.  The difference between mean & median is not significantly high but the difference between 3rd quartile & maximum made the distribution right skewed.\n\n\n>  **For fnlwgt :**\n1.  This is the sampling weight corresponding to the observations.\n2.  finalweight seems to be rightly skewed since there is very large distance between median & maximum value as compared to minimum & median value.\n\n\n> **For capital-gain :**\n1.  For capital-gain, the mean is 1079.06 and median is 0, which indicates that the distribution is highly right skewed.\n2.  From the qurtiles it is clearly visible that 75% observations are having capital gain zero.\n3.  capital-gain is concentrated on the one particular value i.e. zero and other are spread after 3rd quartile which results as the large standard deviation(7452.01).\n4.  capital-gain shows that either a person has no gain or has gain of very large amount(10k or 99k).\n \n\n> **For capital-loss :**\n1.  This attribute is similar to the capital-gain i.e. most of the values are centered on 0(this can be told using the summary statistic as minimum is 0 and values lie under 75 percentile is also zero.\n2.  Mean is 87 but median is 0(i.e. mean is greater than median this tells us that it is right skewed distribution).\n\n\n> **For hours-per-week :**\n1.  This attribute means number of working hours spend by an individual in a week.\n2.  In this data the hours per week atrribute varies within the range of 1 to 99.\n3.  75 percentage of the people spend 45 or less working hours per week.\n4.  The IQR is very less i.e. [40-45] which indicates that 50% of the observations are concentrated between 40 & 45.\n5.  Observations are very sparse below 25th percentile and after 75th percentile.\n6.  Using quartiles we can say that data is approximately symmetric.\n4.  Minimum is 1 hour per week & maximum value is 99 hours per week means person spending 99 working hours per week are very rare events. We will later analyze that which workclass they belong.\n\"\"\"\n\"\"\"\n## 4.2 Summary and count for categorical attribute\n\"\"\"\ndata.describe(include=[\"O\"])\n\"\"\"\n* Native-country has maximum number of unique categories i.e. 41 categories.\n* But the native-country is highly biased toward the US which has frequency of 44689 out of total 48842(nearly 91%).\n* Occupation has  more or less uniform distribution of categories as comparerd to the other attributes.\n* Race is also biased to the white race category(41762) with 85.5%.\n* The top category in workclass is Private having frequency(36705) and percentage(75.5%).\n\"\"\"\n\"\"\"\n# 5. EDA\n\"\"\"\n\"\"\"\n## 5.1.Univariate analysis\n\"\"\"\n\"\"\"\n## 5.1.1 Age\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\ndata['age'].hist(figsize=(8,8))\nplt.show()\ndata[data[\"age\"]>70].shape\n\"\"\"\n### **ii.\tDescription about the distribution**\n\"\"\"\n\"\"\"\nThe above histogram shows that :\n* \"age\" attribute is not symmetric.\n*  it is right-skewed(But this is totally fine as younger adult earn wages not the older ones)\n*  Minimum and Maximum age of the people is 17 and 90 respectively.\n*  This dataset has fewer observations(868) of people's age after certain age i.e. 70 years.\n\"\"\"\n\"\"\"\n## 5.1.2 Hours per week\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\ndata['hours-per-week'].hist(figsize=(8,8))\nplt.show()\n\"\"\"\n### **ii.\tDescription about the distribution**\n\"\"\"\n\"\"\"\nThis histogram of \"hours-per-week\" shows that:\n* In this data the hours per week atrribute varies within the range of 1 to 99.\n* Most people work 30-40 hours per week, they are roughly 27,000 people.\n* There are also few people who works 80-100 hours per week and some less than 20 which is unusual. \n*  75 percentage of the people spend 45 or less working hours per week.\n\"\"\"\n\"\"\"\n## 5.1.3 fnlwgt\n\"\"\"\n\"\"\"\n**fnlwght** variable may stand for a weight of an observation.\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\ndata['fnlwgt'].hist(figsize=(8,8))\nplt.show()\n\"\"\"\n### **ii.\tDescription about distribution**\n\"\"\"\n\"\"\"\nThe above histogram shows that :\n* This is the sampling weight corresponding to the observations.\n* The distribution of finalweight seems to be rightly skewed since mean(189664.1) is greater than median(178144.5).\n\"\"\"\n\"\"\"\n## 5.1.4 capital-gain\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\ndata[\"capital-gain\"].hist(figsize=(8,8))\nplt.show()\n\"\"\"\n### **ii.\tDescription about distribution**\n\"\"\"\n\"\"\"\n\n* This histogram shows that most of the \"capital-gain\" values are centered on 0 and few on 10k and 99k.\n*  capital-gain is concentrated on the one particular value and other are spread with  large standard deviation(7452.01).\n*  capital-gain shows that either a person has no gain or has gain of very large amount(10k or 99k).\n\"\"\"\n\"\"\"\n## 5.1.5 capital-loss\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\ndata[\"capital-loss\"].hist(figsize=(8,8))\nplt.show()\ndata[data[\"capital-loss\"]>0].shape\n\"\"\"\n### **ii.\tDescription about distribution**\n\"\"\"\n\"\"\"\n* This histogram shows that most of the \"capital-loss\" values are centered on 0 and only few are non zero(2282).\n* This attribute is similar to the capital-gain i.e. most of the values are centered on 0(nearly 43000 of them)\n\"\"\"\n\"\"\"\n### Relation between capital gain and capital loss\n\"\"\"\n\"\"\"\n#### Let's explore more about capital loss and capital gain.\n\"\"\"\nsns.relplot('capital-gain','capital-loss', data= data)\nplt.xlabel(\"capital gain\")\nplt.ylabel(\"capital loss\")\nplt.show()\n\"\"\"\nPossibilities for capital gain and capital loss\n\n*     Both capital gain and capital loss can be zero\n*     If capital.gain is zero there is possibility of capital loss being high or above zero.\n*     If capital loss is zero there is possibility of capital.gain being high or above zero.\n\n\n\"\"\"\n\"\"\"\n**With the help of this, we can do one modification later(It could be combine these together i.e. capital-change = [capital-gain - capital-loss])**\n\"\"\"\n\"\"\"\n## 5.1.6 Workclass\n\"\"\"\n\"\"\"\n### **i.\tDistribution**\n\"\"\"\nplt.figure(figsize=(12,8))\n\ntotal = float(len(data[\"income\"]) )\n\nax = sns.countplot(x=\"workclass\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii.\tDescription about distribution**\n\"\"\"\n\"\"\"\nSummary  distribution shows that:\n* There are 8 unique categories present in the worclass attribute.\n* Most of them belong to the *private* workclass(36705) i.e. 75.15%.\n* *without-pay* and *never-worked* has minimum count in workclass attribute(less than 1%).\n* There is huge imbalance in the categories of workclass attribute.\n\"\"\"\n\"\"\"\n## 5.1.7 Education\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(20,8))\ntotal = float(len(data[\"income\"]) )\n\nax = sns.countplot(x=\"education\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\n\n* There are 16 unique categories present in the **education** attribute.\n* *Hs-grad* has 32.32% of all the education attribute.\n* *HS-grad* (15784) has the maximum number of observations followed by *some-college*(10878) and *Bachelors*(8025).\n* *Pre-school* has minimum samples i.e. 83.\n\n\"\"\"\n\"\"\"\n## 5.1.8 marital-status\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(15,8))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"marital-status\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\n\n* This *marital-status* attribute has 7 unique categories.\n* Two of them are dominate over other categories(these are *Never-married*(33%) and *married-civ-spouse*(45.82%).\n* *Married-civ-spouse* has maximum number of samples.\n* *Married-AF-spouse* has minimum number of obs.\n\n\"\"\"\n\"\"\"\n## 5.1.9 Occupation\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(25,8))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"occupation\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\n\n* There are 14 unique categories present in the **occupation** attribute.\n* *Prof-specialty* has the maximum count(8981) but *Craft-repair*, *Exec-managerial* and *Adm-clerical Sales* has comparable number of observations.\n* *Armed-Forces * has minimum samples in the **occupation** attribute.\n\"\"\"\n\"\"\"\n## 5.1.10 Relationship\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(15,8))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"relationship\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\n\n* There are 6 unique categories in the **relationship** attribute.\n* *Husband* has maximum percentage (40.37%) among all categories followed by *not-in-family*(25.76%)\n\"\"\"\n\"\"\"\n## 5.1.11 Race\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(15,8))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"race\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\nThis distribution explains that:\n* There are 5 unique categories in the **race** attribute.\n* Most of them are \"white\" which is roughly 85.50%.\n* This dataset is totally bias toward the \"white\" race.\n* Second major race in the dataset is the \"black\" with just 9.59%.\n\"\"\"\n\"\"\"\n## 5.1.12 Gender\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(8,8))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"gender\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\nThis distribution explains that:\n* Gender has 2 unique categories(male and female).\n* But the frequency of *male*(32650) is higher than the *female*(16192) categories.\n* Distribution shows that this dataset is skewed toward the male with nearly 67%.\n\"\"\"\n\"\"\"\n## 5.1.13 Native-country\n\"\"\"\nplt.figure(figsize=(18,8))\ntotal = float(len(data) )\n\nax = sns.countplot(y=\"native-country\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\nThis distribution explains that:\n* This dataset is taken from the US.\n* As 91.5% of them have native country America and others are immigrants.\n\"\"\"\n\"\"\"\n## 5.1.14 Income(Target variable)\n\"\"\"\n\"\"\"\n### **i. Distribution**\n\"\"\"\nplt.figure(figsize=(7,7))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### **ii. Description about distribution**\n\"\"\"\n\"\"\"\nThis distibution says that:\n* **This dataset not balance , i.e. 23.93%of them are belong to income group 1 (who earns more than 50k) and 76% fall under the income group 0 (who earns less than 50k).**\n\"\"\"\n\"\"\"\n# 5.2.Bivariate analysis\n\"\"\"\n\"\"\"\n## 5.2.1 Age\n\"\"\"\n\"\"\"\n### i. **Boxplot (Relationship with income)**\n\"\"\"\nfig = plt.figure(figsize=(10,10)) \nsns.boxplot(x=\"income\", y=\"age\", data=data)\nplt.show()\ndata[['income', 'age']].groupby(['income'], as_index=False).mean().sort_values(by='age', ascending=False)\n\"\"\"\n    The mean \"age\" for Income group(<=50k) is 36.8 years.\n    And for Income group(>50k) is 44.2 years\n\"\"\"\n\"\"\"\n### ii. Description about boxplot\n\"\"\"\n\"\"\"\nThe above bivariate boxplot shows :\n* Outliers present in both the income group(<=50k and >50k) wrt \"age\" attribute.\n* Income group(<=50k) has lower median \"age\"(34 year) than the Income group(>50k) which has median \"age\"(42 year).\n* Interquartile range(IQR) :\n   *   For Income group(<=50k) , IQR is between [25,46] (long range)\n> Middle 50% of the Age is spread over longer range for the income group who earn <=50k.   \n   *   For Income group(>50k) , IQR is between [38,50] (shorter range)\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & Age )\n\"\"\"\n\"\"\"\n**Two sampled T-test** :-The Independent Samples t Test or 2-sample t-test compares the means of two independent groups in order to determine whether there is statistical evidence that the associated population means are significantly different. The Independent Samples t Test is a parametric test. This test is also known as: Independent t Test.\n\"\"\"\n\"\"\"\nExample : is there any association between age and income\n\"\"\"\n\"\"\"\n\n\nDetermine a null and alternative hypothesis.\n\n    In general, the null hypothesis will state that the two populations being tested have no statistically significant difference.\n    The alternate hypothesis will state that there is one present.\n\n\n\"\"\"\n\"\"\"\nIn this example we can say that:\n*  Null Hypothesis :- there is no difference in Mean age  of income group >50k and income group <=50k.\n*  Alternate Hypothesis :- there is difference in Mean age of income group >50k and income group <=50k.\n\n\"\"\"\nimport random\n\ndata = data[(np.abs(stats.zscore(data[\"age\"])) < 3)] \n\nincome_1 = data[data['income']==1]['age']\nincome_0 = data[data['income']==0]['age']\n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 100)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 100)\nfrom scipy.stats import ttest_ind\nttest,pval = ttest_ind(income_1,income_0,equal_var = False)\nprint(\"ttest\",ttest)\nprint('p value',pval)\n\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nUsing statistical analysis,\n\n    We can conclude that there is a significant difference in the mean ages of income group >50k and income group <=50k.\n    It means that age has some contribution to the distinguish income groups.\n\n\n\"\"\"\n\"\"\"\n## 5.2.2 Hours per week\n\"\"\"\n\"\"\"\n### i. Boxplot (Relationship with income)\n\"\"\"\nfig = plt.figure(figsize=(10,10)) \nsns.boxplot(x=\"income\", y=\"hours-per-week\", data=data)\nplt.show()\n\"\"\"\n### ii. Description about boxplot\n\"\"\"\n\"\"\"\nBivariate Analysis with the boxplot shows that:\n* The median \"hours-per-week\" for Income group who earns >50k is greater than the Income group who earns <=50k.\n>   **Interpretation**\n    * Income group who earns >50k has spend ~44 \"hours-per-week\".(long hours)\n    * Income group who earns <=50k has spend  ~37 \"hours-per-week\".\n   \n* The boxplot for Income group who earns <=50k has small range for minimum (q1-1.5* IQR) and maximum (q3+ 1.5* IQR) i.e.~[28,48].But the boxplot for Income group who earns >50k has large range for minimum (q1-1.5* IQR) and maximum (q3+ 1.5* IQR) i.e.~[23,68].\n>   **Interpretation**\n    *  Income group who earns >50k have flexible working hours\n* More Outliers present in the Income group who earns <=50k.\n\"\"\"\n\"\"\"\n### iii.  Hypothesis test (to test the relationship between income & hours-per-week )\n\"\"\"\n\"\"\"\nIn this example we can say that:\n\n    Null Hypothesis :- there is no difference in Mean of income group >50k and income group <=50k.\n    Alternate Hypothesis :- there is difference in Mean of income group >50k and income group <=50k.\n\n\n\"\"\"\ndata = data[(np.abs(stats.zscore(data[\"hours-per-week\"])) < 3)] \n\nincome_1 = data[data['income']==1][\"hours-per-week\"]\nincome_0 = data[data['income']==0][\"hours-per-week\"]\n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 100)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 100)\n\nttest,pval = ttest_ind(income_1,income_0,equal_var = False)\nprint(\"ttest\",ttest)\nprint('p value',format(pval, '.70f'))\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### iv.  Final conclusion\n\"\"\"\n\"\"\"\nUsing statistical analysis with the help of two sample t-test,\n\n    We can conclude that there is difference in Mean of income group >50k and income group <=50k.\n    It means that hours-per-week has some contribution to the distinguish income groups.\n\n\n\"\"\"\n\"\"\"\n## 5.2.3 fnlwgt\n\"\"\"\n\"\"\"\n### i. Boxplot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(10,7))\nsns.boxplot(x=\"income\", y=\"fnlwgt\", data=data)\nplt.show()\n\"\"\"\n### ii.  Description about boxplot\n\"\"\"\n\"\"\"\n* As evident from the above plot, both income group has nearly same IQR and median is centered on 0.\n* Outliers are present in both the income groups.\n* It seems that the boxplot for final weight w.r.t income groups is similar except the number of outliers in income group who earns <=50k is more.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & fnlwgt)\n\"\"\"\n\"\"\"\n\n    Null Hypothesis :- there is no difference in Mean of income group >50k and income group <=50k.\n    Alternate Hypothesis :- there is difference in Mean of income group >50k and income group <=50k.\n\"\"\"\ndata = data[(np.abs(stats.zscore(data[\"fnlwgt\"])) < 3)] \n\nincome_1 = data[data['income']==1][\"fnlwgt\"]\nincome_0 = data[data['income']==0][\"fnlwgt\"]\n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 100)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 100)\n\nttest,pval = ttest_ind(income_1,income_0,equal_var = False)\nprint(\"ttest\",ttest)\nprint(\"p-value\",pval)\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### iv.  Final conclusion\n\"\"\"\n\"\"\"\nUsing statistical analysis with the help of two sample t-test,\n\n    We can conclude that there is no difference in Mean of income group >50k and income group <=50k.\n    It means that final weight has no contribution to the distinguish income group.\n\n\n\"\"\"\n\"\"\"\n## 5.2.4 capital-gain\n\"\"\"\n\"\"\"\n### i. Boxplot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(10,7))\nsns.boxplot(x=\"income\", y=\"capital-gain\", data=data)\nplt.show()\n\"\"\"\n ### ii. Description about boxplot\n\"\"\"\n\"\"\"\nThis boxplot tells us that:\n\n    Most of the capital gains value is accumulated at 0 for both the income group .\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & capital gain )\n\"\"\"\n\"\"\"\n* Null Hypothesis :- there is no difference in Mean of income group >50k and income group <=50k.\n* Alternate Hypothesis :- there is difference in Mean of income group >50k and income group <=50k.\n\"\"\"\ndata = data[(np.abs(stats.zscore(data[\"capital-gain\"])) < 3)] \n\nincome_1 = data[data['income']==1][\"capital-gain\"]\nincome_0 = data[data['income']==0][\"capital-gain\"]\n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 100)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 100)\n\nttest,pval = ttest_ind(income_1,income_0,equal_var = False)\nprint(\"ttest\",ttest)\nprint(\"p-value\",pval)\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### iv.  Final conclusion\n\"\"\"\n\"\"\"\nUsing statistical analysis with the help of two sample t-test,\n\n    We can conclude that there is difference in Mean of income group >50k and income group <=50k.\n\"\"\"\n\"\"\"\n## 5.2.5. capital-loss\n\"\"\"\n\"\"\"\n### i. Boxplot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(10,7))\nsns.boxplot(x=\"income\", y=\"capital-loss\", data=data)\nplt.show()\n\"\"\"\n### ii. Description about boxplot\n\"\"\"\n\"\"\"\nThis boxplot is similar to the capital gain boxplot where most of the values are concentrated on 0.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & capital loss )\n\"\"\"\n\"\"\"\n\n    Null Hypothesis :- there is no difference in Mean of income group >50k and income group <=50k.\n    Alternate Hypothesis :- there is difference in Mean of income group >50k and income group <=50k.\n\"\"\"\nincome_1 = data[data['income']==1][\"capital-loss\"]\nincome_0 = data[data['income']==0][\"capital-loss\"]\n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 100)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 100)\n\nttest,pval = ttest_ind(income_1,income_0,equal_var = False)\nprint(\"ttest\",ttest)\nprint(\"p-value\",pval)\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nUsing statistical analysis with the help of two sample t-test,\n\n    We can conclude that there is no difference in Mean capital loss of income group >50k and income group <=50k.\n    It means that capital-loss is unable to seperate the income groups.\n\"\"\"\n\"\"\"\n## 5.2.6 Workclass\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(12,10))\ntotal = float(len(data[\"income\"]) )\n\nax = sns.countplot(x=\"workclass\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis plot shows that:\n\n*     In private workclass most of the people(59.48%) earn <=50k(belong to income group 0).\n*     self-emp-inc workclass is only where more people earn >50k(belong to income group 1).\n*     In Federal-gov workclass nearly more than half of the people earn >50k.\n\"\"\"\n\"\"\"\n### iii.  Hypothesis test (to test the relationship between income & workclass)\n\"\"\"\n\"\"\"\n**Chi-square goodness of fit**\n\"\"\"\n\"\"\"\nA chi-square goodness of fit test allows us to test whether the observed proportions for a categorical variable differ from hypothesized proportions. The chi-square statistical test is used to determine whether there\u2019s a significant difference between an expected distribution and an actual distribution.\n* For example, let\u2019s suppose that we believe that the general population consists of 70% private workclass, 10% local-gov, 10% self-emp-not-inc and 10% self-emp-inc. We want to test whether the observed proportions from our sample differ significantly from these hypothesized proportions. \n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['workclass'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\n\"\"\"\nThe table was called a contingency table, by Karl Pearson, because the intent is to help determine whether one variable is contingent upon or depends upon the other variable. For example, does an interest in **workclass** depend on **income**, or are they independent?\n\nThis is challenging to determine from the table alone; instead, we can use a statistical method called the **Pearson\u2019s Chi-Squared test**.\n\"\"\"\n\"\"\"\nWe can interpret the test statistic in the context of the chi-squared distribution with the requisite number of degress of freedom as follows:\n\n    If Statistic >= Critical Value: significant result, reject null hypothesis (H0), dependent.\n    If Statistic < Critical Value: not significant result, fail to reject null hypothesis (H0), independent.\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : There is no relationship between workclass and income.\n*     **H1(Alternate Hypothesis)** : There is a relationship between workclass and income.\n\"\"\"\nfrom scipy.stats import chi2_contingency\nfrom scipy.stats import chi2\n\n\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint('p_value', p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\n\"\"\"\n### iv.  Final conclusion\n\"\"\"\n\"\"\"\n\n\nWith the help of Chi-Squared test,\n\n    As we have accept the H0, that there is no relationship between these two categorical variable.\n    We can conclude that is no dependency of \"workclass\" attribute on the target variable \"income\n\"\"\"\n\"\"\"\n## 5.2.7 Education\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(20,10))\ntotal = float(len(data[\"income\"]) )\n\nax = sns.countplot(x=\"education\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis plot shows that:\n\n*     Despite the fact that most of the categories fall under the HS-grad but the interesting thing is only 5.12% of all people belong to the income group 1(i.e. earns more than 50k), surprisely less than the categories fall under the Bachelors which is 6.78%.\n*     There only few categories in \"education\" attribute whose percentage to fall under income group 1 is greater than the falling under income group 0.\n*     These are prof-school, masters and doctorate.\n*     We can also infer that higher eduction may provide better earnings.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & education)\n\"\"\"\n\"\"\"\nHere, In this example\n\n    H0(Null Hypothesis) : There is no relationship between education and income.\n    H1(Alternate Hypothesis) : There is a relationship between education and income\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['education'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint(\"p-value\", p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv.  Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n*     As we have rejected the H0, that there is no relationship between these two categorical variable.\n*     We can conclude that is some dependency of \"education\" attribute on the target variable \"income\"\n\"\"\"\n\"\"\"\n## 5.2.8 Marital-status\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(17,10))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"marital-status\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis countplot explain following things:\n\n*     Married-civ-spouse has the highest percentage(20.44%) of falling under the income group 1(>50k).\n*     Despite the fact that we have 16117 observation in the marital-status attribute(which is sec. highest) but only 1.5% of the people of \"Never-married\" earn more than 50k.\n*     Married-spouse-absent and Married-AF-spouse has negligible contribution to the fall under income group 1.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & marital-status)\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : There is no relationship between marital-status and income.\n*     **H1(Alternate Hypothesis)** : There is a relationship between marital-status and income.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['marital-status'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint('p_value', p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n* As we have rejected the H0, that there is no relationship between these two categorical variable.\n* We can conclude that is some dependency of \"marital-status\" attribute on the target variable \"income\"\n\"\"\"\n\"\"\"\n## 5.2.9 Occupation\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(25,10))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"occupation\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis countplot explain following things:\n\n*     Prof-specialty has maximum percentage that fall in both income group 0 and 1 in whole categories with 12.15% and 6.24% respectively.\n*     There is an interesting thing to look in this plot which is no occupation has greater percentage of falling in income group 1 than the income group 0. i.e. in every occupation, people who earn less than 50k is greater than people who earn >50k.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & occupation)\n\"\"\"\n\"\"\"\nHere, In this example\n\n    H0(Null Hypothesis) : There is no relationship between occupation and income.\n    H1(Alternate Hypothesis) : There is a relationship between occupation and income.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['occupation'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n*     As we have rejected the H0, that there is no relationship between these two categorical variable.\n*     We can conclude that is some dependency of \"occupation\" attribute on the target variable \"income\"\n\"\"\"\n\"\"\"\n## 5.2.10 Relationship\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(17,10))\ntotal = float(len(data))\n\nax = sns.countplot(x=\"relationship\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis countplot explain following things:\n\n*     husbands has the highest percentage(18.11%) of earning more than 50k in all the other categories.\n*     One thing to notice is that \"not-in-family\" has highest percentage(23.15%) to earn less than 50k but they had nearly same percentage(2.61%) as of the \"wife\"(2.24%) category. This comparsion is done due to fact that \"wife\" category has only 2.53% to fall under the income group 0.\n*     \"own-child\" and \"other-relative\" has the minimum percentage to fall under the income group 1 i.e. 0.23% and 0.11% respectively.\n*     There is huge difference between the percentage of fall either groups except for \"husband\" and \"wife\".\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & relationship)\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : Both the relationship and income variables are independent to each other.\n*     **H1(Alternate Hypothesis)** : There is a dependent to each other.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['relationship'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n*     As we have rejected the H0, that there are independent to each other..\n*     We can conclude that is some dependency of \"relationship\" attribute on the target variable \"income\"\n\n\"\"\"\n\"\"\"\n## 5.2.11 Race\n\"\"\"\n\"\"\"\n### i.  Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(17,10))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"race\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis countplot explain following things:\n\n*     The relationship of \"white\" race with \"income\" can easily guess based on previous summary statistics.\n*     There is huge difference between the percentage of fall either groups for each \"race\" except for the \"other\"(.63%) and \"amer-indian-eskimo\"(.74%) but this could be due the lesser number of observations for those categories.\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & race)\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : There is no relationship between race and income.\n*     **H1(Alternate Hypothesis)** : There is a relationship between race and income.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['race'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint('p_value', p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n*     As we have accept the H0, that there is no relationship between these two categorical variable.\n*     We can conclude that is no dependency of \"race\" attribute on the target variable \"income\"\n\"\"\"\n\"\"\"\n## 5.2.12 Gender\n\"\"\"\n\"\"\"\n### i. Plot (Relationship with income)\n\"\"\"\nplt.figure(figsize=(10,10))\ntotal = float(len(data) )\n\nax = sns.countplot(x=\"gender\", hue=\"income\", data=data)\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()\/2.,\n            height + 3,\n            '{:1.2f}'.format((height\/total)*100),\n            ha=\"center\") \nplt.show()\n\"\"\"\n### ii. Description about plot\n\"\"\"\n\"\"\"\nThis countplot explain following things:\n\n*     For \"female\" earning more than 50k is rare with only 3.62% of all observations.\n*     But for male, 20.31% of all people earn more than 50k .\n\"\"\"\n\"\"\"\n### iii. Hypothesis test (to test the relationship between income & gender)\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : There is no relationship between gender and income.\n*     **H1(Alternate Hypothesis**) : There is a relationship between gender and income.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['gender'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nc_t\nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint('p_value', p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### iv. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n*     As we have rejected the H0, that there is no relationship between these two categorical variable.\n*     We can conclude that is some dependency of \"gender\" attribute on the target variable \"income\"\n\"\"\"\n\"\"\"\n## 5.2.12 Native-country\n\"\"\"\n\"\"\"\n### i. Hypothesis test (to test the relationship between income & native-country)\n\"\"\"\n\"\"\"\nHere, In this example\n\n*     **H0(Null Hypothesis)** : There is no relationship between native-country and income.\n*     **H1(Alternate Hypothesis)** : There is a relationship between native-country and income.\n\"\"\"\n# contingency table\nc_t = pd.crosstab(data['native-country'].sample(frac=0.002, replace=True, random_state=1),data['income'].sample(frac=0.002, replace=True, random_state=1),margins = False) \nstat, p, dof, expected = chi2_contingency(c_t)\nprint('dof=%d' % dof)\nprint('p_value', p)\nprint(expected)\n\n# interpret test-statistic\nprob = 0.95\ncritical = chi2.ppf(prob, dof)\nprint('probability=%.3f, critical=%.3f, stat=%.3f' % (prob, critical, stat))\n\nif abs(stat) >= critical:\n    print('Dependent (reject H0)')\nelse:\n    print('Independent (fail to reject H0)')\n\"\"\"\n### ii. Final conclusion\n\"\"\"\n\"\"\"\nWith the help of Chi-Squared test,\n\n* As we have accept the H0, that there is no relationship between these two categorical variable.\n* We can conclude that is no dependency of \"native-country\" attribute on the target variable \"income\"\n\n\"\"\"\n\"\"\"\n## 5.3\tSome multivariate relationships\n\"\"\"\n\"\"\"\n### **5.3.1 Correlation among the numeric variables.**\n\"\"\"\nplt.figure(figsize=(15,10))  \nsns.heatmap(data_num.corr(),annot=True,linewidths=.5, cmap=\"Blues\")\nplt.title('Heatmap showing correlations between numerical data')\nplt.show()\n\"\"\"\n* There is no strong correlation among the numeric attributes.\n* There is neither strong positive nor strong negative correlation present in any variable .\n* The strongest correlation is present between capital gain and hours-per-week with Coefficient .082.(which is less than 0.1, it means that very small correlation among them).\n\n\"\"\"\n\"\"\"\n### **5.3.2 Multivariate Analysis between \"income\", \"hours-per-week\", \"gender\"**\n\"\"\"\nplt.figure(figsize=(12,6))\nsns.boxplot(x='income',y ='hours-per-week', hue='gender',data=data)\nplt.show()\n\"\"\"\n* The median \"hours-per-week\" for females is lower than the males in the Income group who earns <=50k.\n* Boxplot range for Income group who earns <=50k [minimum (q1-1.5* IQR) and maximum (q3+ 1.5* IQR)] i.e.\n  * Male ~[32,52]\n  * Female ~[17,57]\n  \n> **Interpretation**\n\n     Females have more flexible working hours per week in the income groups who earns <=50k\n* Boxplot range for Income group who earns >50k [minimum (q1-1.5* IQR) and maximum (q3+ 1.5* IQR)] i.e.\n  * Male ~[23,63]\n  * Female ~[30,57]\n  \n> **Interpretation**\n \n     Males have more flexible working hours per week in the income groups who earns <=50k\n\"\"\"\n\"\"\"\n### ** 5.3.3 Multivariate analysis between \"income\", \"age\", \"gender\"**\n\"\"\"\nplt.figure(figsize=(15,10))\nsns.boxplot(x=\"income\", y=\"age\",hue=\"gender\",data=data)\nplt.show()\n\"\"\"\nMultivariate analysis between \"income\", \"age\", \"gender\" shows that:\n*   Median \"age\" of Females who earn less than 50k has very minute difference than the Median \"age\" of males who earn less than 50k.\n*   But the Median \"age\" of Females who earn greater than 50k has age difference of 2-3years than the Median \"age\" of males who earn greater than 50k.\n\n\"\"\"\n\"\"\"\n### Other Mutlivariate analysis \n\"\"\"\nfig = plt.figure(figsize = (17,10))\nax = fig.add_subplot(2,1,1)\nsns.stripplot('age', 'capital-gain', data = data,\n         jitter = 0.2,ax = ax);\nplt.xlabel('Age',fontsize = 12);\nplt.ylabel('Capital Gain',fontsize = 12);\n\nax = fig.add_subplot(2,1,2)\nsns.stripplot('age', 'capital-gain', data = data,\n         jitter = 0.2);\nplt.xlabel('Age',fontsize = 12);\nplt.ylabel('Capital Gain',fontsize = 12);\nplt.ylim(0,40000);\n\"\"\"\n> **Explanation:**\n*     Between age 28 and 64 capital gain is upto 15000 and after that it decreases and again increments at age 90\n*     Age 90 doesn't follow the pattern.\n*     Capital.gain of 99999 is clearly a outlier .\n\"\"\"\ncols = ['workclass','occupation']\ncat_col = data.dtypes[data.dtypes == 'object']\nfor col in cat_col.index:\n    if col in cols:\n        print(f\"======================================={col}=========================\")\n        print(data[data['age'] == 90][col].value_counts())\n    else:\n        continue\n\"\"\"\n**At age 90 people can't work in goverment or private sectors. But there are some observations present in our dataset which shows that despite the age of 90 years they work in those sectors.**\n\n\"\"\"\nfig = plt.figure(figsize = (17,10))\nax = fig.add_subplot(2,1,1)\nsns.stripplot('hours-per-week', 'capital-gain', data = data,\n         jitter = 0.2,ax = ax);\nplt.xlabel('Hours per week',fontsize = 12);\nplt.ylabel('Capital Gain',fontsize = 12);\n\nax = fig.add_subplot(2,1,2)\nsns.stripplot('hours-per-week', 'capital-gain', data = data,\n         jitter = 0.2,ax = ax);\nplt.xlabel('Hours per week',fontsize = 12);\nplt.ylabel('Capital Gain',fontsize = 12);\nplt.ylim(0,40000);\n\"\"\"\n> **Explanation:**\n*   Majority of people can be seen working for 40,50 and 60 hours per week and capital gain seems to be increasing.\n*   There are few people working for 99 hours per week but doesn't seem to make high capital gain. Conversely people working below 40 hours per week are making high capital gains.\n\"\"\"\ncols = ['workclass','occupation']\ncat_col = data.dtypes[data.dtypes == 'object']\nfor col in cat_col.index:\n    if col in cols:\n        print(f\"======================================={col}=========================\")\n        print(data[data['hours-per-week'] == 99][col].value_counts())\n    else:\n        continue\n\"\"\"\n## 5.3.4 Making new variable(capital_change)\n\"\"\"\n\"\"\"\n### **i. Summary statistics**\n\"\"\"\ndata[\"capital_change\"] = data[\"capital-gain\"] - data[\"capital-loss\"]\ndata[\"capital_change\"].describe()\n\"\"\"\n### **ii. Distribution**\n\"\"\"\ndata[\"capital_change\"].hist(figsize=(8,8))\nplt.show()\n\"\"\"\n### **iii. Description about summary & Distribution**\n\"\"\"\n\"\"\"\nThe summary statistics and distribution of **capital_change** shows that:\n* It is similar summary stats and distribution to the capital gain and capital loss.\n* This suggest that , we may replace these two features with one feature called **capital_change**\n\"\"\"\n\"\"\"\n### **iv. Hypothesis test (to test the relationship between income & capital change)**\n\"\"\"\n\"\"\"\n* Null Hypothesis :- there is no difference in Mean of income group >50k and income group <=50k.\n* Alternate Hypothesis :- there is difference in Mean of income group >50k and income group <=50k.\n\"\"\"\nincome_1 = data[data['income']==1][\"capital_change\"]\nincome_0 = data[data['income']==0][\"capital_change\"]\n\ndata = data[(np.abs(stats.zscore(data[\"age\"])) < 3)] \n\nincome_0 = income_0.values.tolist()\nincome_0 = random.sample(income_0, 50)\nincome_1 = income_1.values.tolist()\nincome_1 = random.sample(income_1, 50)\n\nttest,pval = ttest_ind(income_1,income_0, equal_var=0)\nprint(\"ttest\",ttest)\nprint(\"p-value\",pval)\n\nif pval <0.05:\n    print(\"we reject null hypothesis\")\nelse:\n    print(\"we accept null hypothesis\")\n\"\"\"\n### **v. Final conclusion**\n\"\"\"\n\"\"\"\n\n\nUsing statistical analysis with the help of two sample t-test,\n\n    We can conclude that there is difference in Mean of income group >50k and income group <=50k.\n    Hence, we can replace capital-gain and capital-loss with capital-change.\n\n\n\"\"\"\n\"\"\"\n## **6. Conclusion of Complete EDA**\n\"\"\"\n\"\"\"\nFeature Removal:\n\n    1. Education num and education are giving similar information.\n    2. Using capital-gain and capital loss , we can make new variable called capital-change.\n\n\nOutliers Summary:\n\n    1. Capital gain of 99999 doesn't follow any pattern and from graph above it clearly distinguishes to be an outlier.\n    2. Our dataset has people with age 90 and working for 40 hours per week in goverment or private sectors which is rare.\n\n\n\nOther conclusion:\n\n    1. This dataset not balance , i.e. 76% of them are belong to income group 1 (who earns more than 50k) and 23.93% fall under the income group 0 (who earns less than 50k).\n    \n    2. Females have more flexible working hours per week in the income groups who earns <=50k.\n    \n    3. Males have more flexible working hours per week in the income groups who earns >50k.\n    \n    4. The Median \"age\" of Females who earn greater than 50k has age difference of 2-3years(lower) than the Median \"age\" of males who earn greater than 50k.\n    \n    5. Generally people can be seen working for 30 hours to 40 hours per week. \n    \n    6. Income group who earns >50k have flexible working hours.\n    \n    7. For \"female\" earning more than 50k is rare with only 3.62% of all observations.\n       But for male, 20.31% of all people earn more than 50k .\n       \n    8. self-emp-inc workclass is only where more people earn >50k(belong to income group 1).\n    \n    9. People having degree doctorate,prof-school,masters are making salary more than 50K(it can be concluded that higher education means more salary).\n  \nAttributes affecting the target feature:\n    \n    Age \n    Hours per week\n    capital-change\n    workclass\n    Education\n    marital-status\n    occupation\n    relationship\n    race\n    gender\n    native-country\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '32e54c816527e6'}"}
{"id":"61380","text":"# 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\n\"\"\"\n# Understanding the data\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\nfish=pd.read_csv(\"\/kaggle\/input\/fish-market\/Fish.csv\")\nfish.head(5)\nfish.info()\nfish.describe()\nround(fish.isnull().sum()\/len(fish),2)\nfish.drop_duplicates(inplace=True)\n\"\"\"\n# EDA\n\"\"\"\nplt.figure(figsize=(20,15))\nsns.pairplot(fish)\nplt.show()\nplt.figure(figsize=(20,15))\nplt.subplot(1,2,1)\nsns.boxplot(x='Species',y='Weight',data=fish)\nplt.figure(figsize=(20,15))\nsns.heatmap(fish.corr())\nplt.show()\n\"\"\"\n### Creating Dummy Variables\n\"\"\"\nSpecies=pd.get_dummies(fish['Species'],drop_first=True)\nfish=pd.concat([fish,Species],axis=1)\nfish.drop(['Species'],axis=1,inplace=True)\nfish.head(5)\n\"\"\"\n# train test split and feature scaling\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nnp.random.seed(0)\ndf_train,df_test=train_test_split(fish,test_size=0.2,random_state=42)\ndf_train.shape\ndf_test.shape\nfrom sklearn.preprocessing import MinMaxScaler\nscaler=MinMaxScaler()\nnum_vars=['Weight','Length1','Length2','Length3','Height','Width']\ndf_train[num_vars]=scaler.fit_transform(df_train[num_vars])\ndf_test[num_vars]=scaler.transform(df_test[num_vars])\nplt.figure(figsize=(20,15))\nsns.heatmap(df_train.corr())\nplt.show()\ndf_train.head(5)\n\"\"\"\n# Feature selection and model buliding using statsmodels api\n\"\"\"\ny_train=df_train.pop('Weight')\nX_train=df_train\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.feature_selection import RFE\nlm=LinearRegression()\nlm.fit(X_train,y_train)\nrfe=RFE(lm,7)\nrfe.fit(X_train,y_train)\nlist(zip(X_train.columns,rfe.support_,rfe.ranking_))\ncol=X_train.columns[rfe.support_]\ncol\nX_train_rfe=X_train[col]\nimport statsmodels.api as sm\nX_train_sm1=sm.add_constant(X_train_rfe)\nlm1=sm.OLS(y_train,X_train_sm1).fit()\nprint(lm1.summary())\n# Calculate the VIFs for the model\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nvif = pd.DataFrame()\nX = X_train_rfe\nvif['Features'] = X.columns\nvif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\nX_train_new = X_train_rfe.drop([\"Length3\"], axis = 1)\nX_train_sm2 = sm.add_constant(X_train_new)\n\n# Create a first fitted model\nlr2 = sm.OLS(y_train, X_train_sm2).fit()\nprint(lr2.summary())\nX_train_new = X_train_new.drop([\"Height\"], axis = 1)\nX_train_sm3 = sm.add_constant(X_train_new)\n\n# Create a first fitted model\nlr3 = sm.OLS(y_train, X_train_sm3).fit()\nprint(lr3.summary())\nX_train_new = X_train_new.drop([\"Length1\"], axis = 1)\nX_train_sm4 = sm.add_constant(X_train_new)\n\n# Create a first fitted model\nlr4 = sm.OLS(y_train, X_train_sm4).fit()\nprint(lr4.summary())\n# Calculate the VIFs for the final model\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nvif = pd.DataFrame()\nX = X_train_new\nvif['Features'] = X.columns\nvif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]\nvif['VIF'] = round(vif['VIF'], 2)\nvif = vif.sort_values(by = \"VIF\", ascending = False)\nvif\n\"\"\"\n### Observations\n- This model looks good, as there are VERY LOW Multicollinearity between the predictors and the p-values for all the predictors seems to be significant. For now, we will consider this as our final model (unless the Test data metrics are not significantly close to this number).\n\"\"\"\n\"\"\"\n# Checking Assumptions\n\"\"\"\n\"\"\"\n1.Error terms are normally distributed with mean zero (not X, Y)\n\"\"\"\ny_train_pred=lr4.predict(X_train_sm4)\nres = y_train-y_train_pred\n# Plot the histogram of the error terms\nfig = plt.figure()\nsns.distplot((res), bins = 20)\nfig.suptitle('Error Terms', fontsize = 20)                  # Plot heading \nplt.xlabel('Errors', fontsize = 18) ;\n\"\"\"\nFrom the above histogram, we could see that the Residuals are normally distributed. Hence our assumption for our model is valid.\n\"\"\"\n\"\"\"\n# Making prediction on test data set\n\"\"\"\ny_test=df_test.pop('Weight')\nX_test=df_test\nX_test_new=sm.add_constant(X_test)\n#Selecting the variables that were part of final model.\ncol1=X_train_new.columns\nX_test=X_test[col1]\n# Adding constant variable to test dataframe\nX_test_lm4 = sm.add_constant(X_test)\nX_test_lm4.info()\ny_test_pred=lr4.predict(X_test_lm4)\n\"\"\"\n# Model Evaluation\n\"\"\"\nfrom sklearn.metrics import r2_score\nr2_score(y_train,y_train_pred)\nfrom sklearn.metrics import r2_score\nr2_score(y_test,y_test_pred)\n\"\"\"\nwe have got a better accuracy around 94% on test data set.\n\"\"\"\n\"\"\"\n## Conclusion\n\n- If you have any suggestions or suggestions, please write to me. I wil be happy to help.\n\n- Thank you for your suggestion and votes ;)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7136f0cf605ea1'}"}
{"id":"66965","text":"\"\"\"\n> **Zomato: Exploratory Restaurant Data Analysis**\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n#read Country Code csv file into dataframe\nrest_country = pd.read_excel(\"..\/input\/Country-Code.xlsx\")\n\n#rename all columns in dataframe\nrest_country.columns=['country code','country']\n\nprint (rest_country.head())\n\n#read zomato restaurants csv file into dataframe\nrest_data=pd.read_csv('..\/input\/zomato.csv',encoding='latin-1')\n#renaming all columns to lowercase for easy access\nrest_data.columns=[x.lower() for x in rest_data.columns]\n\nprint (rest_data.head())\n#printing column names of rest_data dataframe\nprint(rest_data.columns)\n\n\n#print tuple showing total rows and columns in rest_data dataframe\nrest_data.shape\n#Join 2 dataframes to have Country Name column in resulting DataFrame\nrest_all_data = pd.merge(rest_data,rest_country,on='country code',how='inner')\n\n#print tuple to ensure addition of new column Country Name\nrest_all_data.shape\n#Find which all countries data in the dataset\nrest_all_data['country'].unique()\n\"\"\"\nIndia has highest number of restuarants registered on Zomato across the globe.\n\nData Visualization concluded that this data is not upto date for countries other than India.\n\nThough we see significant restuarants registered on Zomato in India,there are high chances that restuarant data for India is stale in given dataset.\n\nAll exploratory analysis on the data which is available in this dataset.\n\"\"\"\n#Find out number of restaurant registered on Zomato across all countries\nprint(rest_all_data['country'].value_counts())\n\n#plot bar graph\nrest_all_data['country'].value_counts().plot(kind='bar',title='Total Restaurants On Zomato In Countries'\n                                             ,figsize=(20,10),fontsize=20)\n\n\n\n\"\"\"\nIndia has highest number of restaurants registered on Zomato in given dataset as seen on graph above.\n\nLet's take restaurants data belonging to India.\n\"\"\"\nrest_india = rest_all_data[rest_all_data['country']=='India']\n\nrest_india['country'].unique()\n\nrest_india.head(10)\nrest_india.shape\n\"\"\"\nLet's find out how much percentage data for each City of India is in dataset\n\"\"\"\n#Find out percentage of data comprises to each city in India dataset\n#as_index option set False to consider city as column of dataframe rather than index\ngrouped_cities=rest_india.groupby('city',as_index=False)[['restaurant id']].count().sort_values(ascending=False,by='restaurant id')\ngrouped_cities['total'] = grouped_cities['restaurant id'].sum()\ngrouped_cities['percent'] = (grouped_cities['restaurant id']\/grouped_cities['total'])*100\n\n#plot the Pie Chart showing percentage of restaurants in top 3 cities\ncolors = ['b', 'g', 'r']\nexplode = (0, 0, 0.3)\nlabel = grouped_cities['city'].head(3)\nvalues = grouped_cities['percent'].head(3).round(2)\nplt.pie(values, colors=colors, labels= values ,explode=explode,counterclock=False, shadow=True)\nplt.title('Percentage of Resturants on Zomato in top 3 cities of India')\nplt.legend(label,loc=4)\nplt.show()\n\"\"\"\nDataset having most of resturants of **New Delhi, Noida and Gurgaon**. Let's get restaurant data of New delhi to initiate more granual level of analysis\n\"\"\"\nrest_new_delhi = rest_india[rest_india['city'] == 'New Delhi']\nrest_new_delhi.head()\n\"\"\"\nIt would be interesting to analyse and see - How people have rated the **\"Well known famous Coffee Brands\"** in New Delhi.\n\n**Analysis would answer few questions mentioned below:**\n1. Which coffee shop is rated highest by customers?\n2. Whether people rated \"Popular Coffee Shops\" with respect to their average cost?\n3. What is average cost for each \"Well Known\" Coffee shops\n\n\"\"\"\ncoffee_shops = ['Costa Coffee','Starbucks','Barista','Cafe Coffee Day']\n\ndelhi_coffee_shops = rest_new_delhi[rest_new_delhi['restaurant name'].isin(coffee_shops)]\ndelhi_coffee_shops = delhi_coffee_shops.groupby('restaurant name',as_index=False)[['aggregate rating','average cost for two']].mean().round(2).sort_values(ascending=False,by='aggregate rating')\n\n\"\"\"\nLet's visualize this summary on **Bar Chart** to find trends of customers.\n\n**Trends:**\n1. Customers prefer and love to have Starbucks coffee though average cost in Starbucks is high as compared to other 3 coffee shops\n2. Barista is costlier than Costa Coffee. This seems to be one of the reasons that customers preferred the Costa Coffee over Barista. One more crucial deciding factor missing in dataset is the taste or different flavors of coffee offered in Barista and Costa Coffee.That's the another factor which customer might be taking into consideration when rating coffee shops\n3. Question here is whether all people visiting these coffee shops rated them.This confirmation is missing. Trends shown below could drastically change if this missed taken into this analysis\n\"\"\"\n#bar graph to plot average cost for 2 people\ncosts = delhi_coffee_shops['average cost for two']\nrnames = delhi_coffee_shops['restaurant name']\ncolors = ['g','b','r','y']\nplt.bar(rnames,costs,color=colors,edgecolor='black')\nplt.title('Avg Cost for two in Well Known Coffee Shops in New Delhi',fontsize=12)\nplt.ylabel('Average Cost')\nplt.xlabel('Coffee Shops')\nplt.show()\n\n#bar graph to plot average ratings of Well known Coffee Shops\nratings = delhi_coffee_shops['aggregate rating']\nplt.barh(rnames,ratings,color=colors,edgecolor='black')\nplt.title('Average Ratings for Popular Coffee Shops in New Delhi',fontsize=12)\nplt.xlabel('Average Rating')\nplt.ylabel('Coffee Shops')\nplt.show()\n\"\"\"\nNow, It's interesting to see how people rated **\"Non-famous local\"** Coffee Shops\n\nTrends:\n**Green Cafe** was rated at 4.6 average rating by customers which is higher than well known **\"Starbucks\"**\n\"\"\"\ndelhi_local_coffee_shops = rest_new_delhi[(rest_new_delhi['cuisines']=='Cafe') \n                                          & (~rest_new_delhi['restaurant name'].isin(coffee_shops))]\n\ntop_coffee_shops=delhi_local_coffee_shops.groupby('restaurant name',as_index=False)[['average cost for two','aggregate rating']].mean().round(2).sort_values(ascending=False,by='aggregate rating')\n\ntop_coffee_shops=top_coffee_shops[top_coffee_shops['aggregate rating'] >= 4].sort_values(ascending=False,by='aggregate rating')\n\n#plot top local coffee with average rating more than 4\nrnames = top_coffee_shops['restaurant name']\ncolors = ['#B00303','#DC0508','#DC0508','#F9908D','#F7CAC9','#F7CAC9']\nratings = top_coffee_shops['aggregate rating']\nplt.bar(rnames,ratings,color=colors,edgecolor='black')\nplt.title('Top Local Coffee Shops with min 4 rating in New Delhi',fontsize=12)\nplt.ylabel('Average Rating')\nplt.xlabel('Coffee Shops')\nplt.xticks(rotation='vertical')\nplt.show()\n\n\"\"\"\nLet's see which local coffee shops are costly.\n\n**Trends:**\n* None of top 6 expensive coffee shops in New Delhi were rated above 4.0 by the customers. Interesting! And these expensive coffee shops operating through well-known multi-star hotels like The Taj Mahal,Le Meridien and The Royal Plaza\n\"\"\"\nexpensive_coffee_shops=delhi_local_coffee_shops.groupby('restaurant name',as_index=False)[['average cost for two','aggregate rating']].mean().round(2).sort_values(ascending=False,by='average cost for two').head(6)\n\n#plot 6 expensive local coffee shops\nrnames = expensive_coffee_shops['restaurant name']\ncolors = ['#B00303','#B00303','#DC0508','#F9908D','#F7CAC9','#F7CAC9']\nratings = expensive_coffee_shops['average cost for two']\nplt.bar(rnames,ratings,color=colors,edgecolor='black')\nplt.title('Expensive Local Coffee Shops in New Delhi',fontsize=12)\nplt.ylabel('Average Cost for two')\nplt.xlabel('Coffee Shops')\nplt.xticks(rotation='vertical')\nplt.show()\n\"\"\"\nWith above trends, Let's see correlation between average cost for 2 vs average rating for local coffee shops in New Delhi\n\"\"\"\ncorrelation = delhi_local_coffee_shops.groupby('restaurant name',as_index=False)[['average cost for two','aggregate rating']].mean().round(2).sort_values(ascending=False,by='aggregate rating')\n\n#plot scatter graph to analyse correlation\nweight = correlation['aggregate rating']\nheight = correlation['average cost for two']\nplt.figure(figsize=(10,8))\nplt.scatter(weight,height,c='g',marker='o')\nplt.xlabel('Average Rating')\nplt.ylabel('Average Cost')\nplt.title('Average Rating Vs Average Cost for Local Coffee Shops')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '7b6076b7afb562'}"}
{"id":"106917","text":"\"\"\"\n**Introduction**\n\"\"\"\n\"\"\"\n> Vector autoregression (VAR) is a *stochastic process model used to capture the linear interdependencies among multiple time series*. VAR models generalize the univariate autoregressive model (AR model) by allowing for more than one evolving variable. All variables in a VAR enter the model in the same way: *each variable has an equation explaining its evolution based on its own lagged values, the lagged values of the other model variables, and an error term*.\n\nTaken from: [Vector autoregression](https:\/\/en.wikipedia.org\/wiki\/Vector_autoregression)\n\"\"\"\n\"\"\"\n**Practical Use**\n\nThe model predicts number a variety of parameters which can be translated into practical use.\nFor example, Predicting the number of patients that will need hospital care, can help the country to be better prepared towards what is expected.\nThe same holds for the prediction of number of tests to be performed, number of patients expected to be entered to home confinment and more.\n\"\"\"\n\"\"\"\n**Related Work and Credits**\n\n[Analysis and Prediction on Coronavirus (Italy)](https:\/\/www.kaggle.com\/vanshjatana\/analysis-and-prediction-on-coronavirus-italy\/data)\n\nLarge parts of code snippets used for VAR modeling were taken from: [Vector Autoregression (VAR) \u2013 Comprehensive Guide with Examples in Python](https:\/\/www.machinelearningplus.com\/time-series\/vector-autoregression-examples-python\/)\n\"\"\"\n\"\"\"\n**Imports**\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nfrom statsmodels.tsa.api import VAR\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.stattools import grangercausalitytests\nfrom statsmodels.tools.eval_measures import rmse, aic\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport datetime\n\"\"\"\n**Settings**\n\"\"\"\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', -1)\npd.plotting.register_matplotlib_converters()\nnp.set_printoptions(suppress=True)\n\"\"\"\n**Reading Data**\n\"\"\"\nita_regional=pd.read_csv(\"..\/input\/covid19-in-italy\/covid19_italy_region.csv\")\n\"\"\"\n**Basic EDA**\n\"\"\"\nita_regional.info()\n# Checking the percentage of missing data in each column\nper_missing = ita_regional.isna().sum()*100\/len(ita_regional)\nper_missing.sort_values(ascending=False)\n# Check for the period covered by the data (total # of days)\nita_regional['Date'] = pd.to_datetime(ita_regional['Date']).dt.normalize()\n(ita_regional.Date.max()-ita_regional.Date.min()) + datetime.timedelta(days=1)\nvar_df = ita_regional.groupby('Date')[['HospitalizedPatients', 'IntensiveCarePatients', 'TotalHospitalizedPatients',\n                                      'HomeConfinement', 'CurrentPositiveCases', 'NewPositiveCases',\n                                      'Recovered', 'Deaths', 'TotalPositiveCases', 'TestsPerformed']].sum().reset_index()\nprint(\"df shape: \", var_df.shape)\nvar_df.head()\n# Droping columns who are part of other columns (e.g., \n#    TotalHospitalizedPatients = HospitalizedPatients + IntensiveCarePatients)\n\nvar_df.drop(['HospitalizedPatients', 'IntensiveCarePatients', 'NewPositiveCases', 'TotalPositiveCases', 'CurrentPositiveCases'],\n            axis=1, inplace=True)\n\nvar_df.head(n=5)\ntype(var_df['Date'])\nfig, axes = plt.subplots(nrows=1, ncols=5, figsize=(22,5))\n\nfor ycol, ax in zip(['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed'], axes):\n\n    var_df.plot(kind='line', x='Date', y=ycol, ax=ax, alpha=0.5, color='r')\n\"\"\"\n**VAR**\n\"\"\"\n\"\"\"\n**Checking for Causlity**\n\n> Granger causality is a concept of causality derived from the notion that causes may not occur after effects and that *if one variable is the cause of another*, knowing the status on the cause at an earlier point in time can enhance prediction of the effect at a later point in time (Granger, 1969; L\u00fctkepohl, 2005, p. 41)\n\nTaken from: [Vector Autoregressive (VAR) Models and Granger Causality in Time Series Analysis in Nursing Research: Dynamic Changes Among Vital Signs Prior to Cardiorespiratory Instability Events as an Example](https:\/\/www.ncbi.nlm.nih.gov\/pmc\/articles\/PMC5161241\/)\n\"\"\"\ndef grangers_causation_matrix(data, variables, test='ssr_chi2test', verbose=False, maxlag=5):    \n    \n    \"\"\"Check Granger Causality of all possible combinations of the Time series.\n    The rows are the response variable, columns are predictors. \n\n    data      : pandas dataframe containing the time series variables\n    variables : list containing names of the time series variables.\n    \"\"\"\n    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)\n    for c in df.columns:\n        for r in df.index:\n            test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)\n            p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]\n            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')\n            min_p_value = np.min(p_values)\n            df.loc[r, c] = min_p_value\n    df.columns = [var + '_x' for var in variables]\n    df.index = [var + '_y' for var in variables]\n    return df  \ngrangers_causation_matrix(var_df, variables = ['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed']) \n\"\"\"\nThe test *Null Hypothesis is that the coefficients of the corresponding past values are zero; That is the X does not cause Y*. \nThe P-values in the table are lesser than our significance level (0.05), which implies that the Null Hypothesis can be rejected.\n\"\"\"\n\"\"\"\n**Checking for Cointegration**\n\n> Cointegration tests analyze non-stationary time series\u2014 processes that have variances and means that vary over time. In other words, the method allows you to estimate the long-run parameters or equilibrium in systems with unit root variables (Rao, 2007).\n\nTaken from: [Cointegration: Definition, Examples, Tests](https:\/\/www.statisticshowto.datasciencecentral.com\/cointegration\/)\n\nMore information about python implementation and the test results can be found here:\n\n[Test](https:\/\/www.statsmodels.org\/dev\/generated\/statsmodels.tsa.vector_ar.vecm.coint_johansen.html)\n\n[Results](https:\/\/www.statsmodels.org\/dev\/generated\/statsmodels.tsa.vector_ar.vecm.JohansenTestResult.html#statsmodels.tsa.vector_ar.vecm.JohansenTestResult)\n\"\"\"\nfrom statsmodels.tsa.vector_ar.vecm import coint_johansen\n\ndef cointegration_test(df, alpha=0.05): \n    \"\"\"Perform Johanson's Cointegration Test and Report Summary\"\"\"\n    out = coint_johansen(df,-1,5)\n    d = {'0.90':0, '0.95':1, '0.99':2}\n    traces = out.lr1\n    cvts = out.cvt[:, d[str(1-alpha)]]\n    def adjust(val, length= 6): return str(val).ljust(length)\n\n    # Summary\n    print('Name   ::  Test Stat > C(95%)    =>   Signif  \\n', '--'*20)\n    for col, trace, cvt in zip(df.columns, traces, cvts):\n        print(adjust(col), ':: ', adjust(round(trace,2), 9), \">\", adjust(cvt, 8), ' =>  ' , trace > cvt)\ncointegration_test(var_df[['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed']])\n\"\"\"\nTrain-Test Split\n\"\"\"\ntest_frec = 0.25\nn_test = round((len(var_df)) * test_frec)\ndf_train, df_test = var_df[0:-n_test], var_df[-n_test:]\n# df_train_copy = df_train.copy()\ndf_train.drop('Date',1, inplace=True)\n\"\"\"\n**Unit Root Test (checking for stationaity)**\n\n> In statistics, a unit root test tests whether a time series variable is non-stationary and possesses a unit root. *The null hypothesis is generally defined as the presence of a unit root and the alternative hypothesis is either stationarity*, trend stationarity or explosive root depending on the test used.\n\nTaken from: [Unit root test](https:\/\/en.wikipedia.org\/wiki\/Unit_root_test)\n\"\"\"\ndef adfuller_test(series, signif=0.05, name='', verbose=False):\n    \"\"\"Perform ADFuller to test for Stationarity of given series and print report\"\"\"\n    r = adfuller(series, autolag='AIC')\n    output = {'test_statistic':round(r[0], 4), 'pvalue':round(r[1], 4), 'n_lags':round(r[2], 4), 'n_obs':r[3]}\n    p_value = output['pvalue'] \n    def adjust(val, length= 6): return str(val).ljust(length)\n\n    # Print Summary\n    print(f'    Augmented Dickey-Fuller Test on \"{name}\"', \"\\n   \", '-'*47)\n    print(f' Null Hypothesis: Data has unit root. Non-Stationary.')\n    print(f' Significance Level    = {signif}')\n    print(f' Test Statistic        = {output[\"test_statistic\"]}')\n    print(f' No. Lags Chosen       = {output[\"n_lags\"]}')\n\n    for key,val in r[4].items():\n        print(f' Critical value {adjust(key)} = {round(val, 3)}')\n\n    if p_value <= signif:\n        print(f\" => P-Value = {p_value}. Rejecting Null Hypothesis.\")\n        print(f\" => Series is Stationary.\")\n    else:\n        print(f\" => P-Value = {p_value}. Weak evidence to reject the Null Hypothesis.\")\n        print(f\" => Series is Non-Stationary.\")\n# ADF Test on each column\nfor name, column in df_train.iteritems():\n    adfuller_test(column, name=column.name)\n    print('\\n')\n# 1st difference\ndf_differenced = df_train.diff().dropna()\n# ADF Test on each column\nfor name, column in df_differenced.iteritems():\n    adfuller_test(column, name=column.name)\n    print('\\n')\n# 2nd Difference\ndf_differenced = df_differenced.diff().dropna()\n# ADF Test on each column\nfor name, column in df_differenced.iteritems():\n    adfuller_test(column, name=column.name)\n    print('\\n')\n\"\"\"\nAs you can see, after 2 series differences, we have 2 stationary columns under significance level of 5%, 1 stationary column under significance level of 0.1%, and 2 non-stationary columns (under plausible significance level).\nThis is not ideal - however, because we're using \"short\" time series, I've decided to go on with only 2 diffrences and not to add more differences.  \n\"\"\"\n\"\"\"\nModeling\n\"\"\"\nmodel = VAR(df_differenced[['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed']])\n\nfitted = model.fit(6)\nfitted.summary()\n\"\"\"\nChoosing number of lags to be inserted into the model is a matter of trial and error, and can be changed according to the regression results (above), the durbin-watson test results (will be explained in a moment), and other metrics (e.g., RMSE, MAE, etc.)\n\"\"\"\n\"\"\"\n**Checking for Residuals' Autocorrelaotion**\n\nWe'll use Durbin-Watson test for this (denoted as *d*):\n\n> The value of d always lies between 0 and 4. \n> \n> d = 2 indicates no autocorrelation.\n> \n> If d < 2, there is evidence of positive serial correlation. As a rough rule of thumb, if d < 1.0, there may be cause > for alarm. Small values of d indicate successive error terms are positively correlated.\n> \n> If d > 2, successive error terms are negatively correlated. In regressions, this can imply an underestimation of the > level of statistical significance.\n\nTaken from (modified by the author): [Durbin\u2013Watson statistic](https:\/\/en.wikipedia.org\/wiki\/Durbin%E2%80%93Watson_statistic)\n\n\"\"\"\nfrom statsmodels.stats.stattools import durbin_watson\nout = durbin_watson(fitted.resid)\n\nfor col, val in zip(var_df[['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed']], out):\n    print(col, ':', round(val, 2))\n\"\"\"\n**Forecasting**\n\"\"\"\n# Get the lag order\nlag_order = fitted.k_ar\n\n# Input data for forecasting\nforecast_input = df_differenced.values[-lag_order:]\nforecast_input\nvar_df_forecast = var_df[['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed']]\n\nfc = fitted.forecast(y=forecast_input, steps=n_test)\ndf_forecast = pd.DataFrame(fc, index=var_df_forecast.index[-n_test:], columns=var_df_forecast.columns + '_2d')\ndf_forecast\n\"\"\"\nTurning Forecasting into original values\n\"\"\"\ndef invert_transformation(df_train, df_forecast, second_diff=False, third_diff=False):\n    \"\"\"Revert back the differencing to get the forecast to original scale.\"\"\"\n    df_fc = df_forecast.copy()\n    columns = df_train.columns\n    for col in columns:        \n        # Roll back 3rd Diff\n        if third_diff:\n            df_fc[str(col)+'_2d'] = (df_train[col].iloc[-2]-df_train[col].iloc[-3]) + df_fc[str(col)+'_3d'].cumsum()\n        # Roll back 2nd Diff\n        if second_diff:\n            df_fc[str(col)+'_1d'] = (df_train[col].iloc[-1]-df_train[col].iloc[-2]) + df_fc[str(col)+'_2d'].cumsum()\n        # Roll back 1st Diff\n        df_fc[str(col)+'_forecast'] = df_train[col].iloc[-1] + df_fc[str(col)+'_1d'].cumsum()\n    return df_fc\ndf_results = invert_transformation(df_train, df_forecast, second_diff=True, third_diff=False)        \ndf_results.loc[:, ['TotalHospitalizedPatients_forecast', 'HomeConfinement_forecast',\n                                                  'Recovered_forecast', 'Deaths_forecast', 'TestsPerformed_forecast']]\ndf_results\n\"\"\"\nResults Visualization\n\"\"\"\ndf_results['Date'] = var_df['Date'][13:17]\ndf_test.set_index('Date',inplace=True)\nfig, axes = plt.subplots(nrows=1, ncols=5, figsize=(22,6))\n\nfor col, ax in zip(['TotalHospitalizedPatients', 'HomeConfinement',\n                                                  'Recovered', 'Deaths', 'TestsPerformed'], axes):\n\n    df_results.plot(kind='line', y=[col+'_forecast'], x='Date', ax=ax, alpha=0.5, color='r', legend=True).autoscale(axis='x',tight=True)\n    df_test[col][-n_test:].plot(legend=True, ax=ax)\n    ax.set_title(col + \": Forecast vs Actuals\")\nplt.tight_layout();\nfrom statsmodels.tsa.stattools import acf\ndef forecast_accuracy(forecast, actual):\n    mape = np.mean(np.abs(forecast - actual)\/np.abs(actual))  # MAPE\n    me = np.mean(forecast - actual)             # ME\n    mae = np.mean(np.abs(forecast - actual))    # MAE\n    mpe = np.mean((forecast - actual)\/actual)   # MPE\n    rmse = np.mean((forecast - actual)**2)**.5  # RMSE\n    corr = np.corrcoef(forecast, actual)[0,1]   # corr\n    mins = np.amin(np.hstack([forecast[:,None], \n                              actual[:,None]]), axis=1)\n    maxs = np.amax(np.hstack([forecast[:,None], \n                              actual[:,None]]), axis=1)\n    minmax = 1 - np.mean(mins\/maxs)             # minmax\n    return({'mape':mape, 'me':me, 'mae': mae, \n            'mpe': mpe, 'rmse':rmse, 'corr':corr, 'minmax':minmax})\nprint('Forecast Accuracy of: TotalHospitalizedPatients')\naccuracy_prod = forecast_accuracy(df_results['TotalHospitalizedPatients_forecast'].values, df_test['TotalHospitalizedPatients'])\nfor k, v in accuracy_prod.items():\n    print(k, ': ', round(v,4))\n\nprint('\\nForecast Accuracy of: HomeConfinement')\naccuracy_prod = forecast_accuracy(df_results['HomeConfinement_forecast'].values, df_test['HomeConfinement'])\nfor k, v in accuracy_prod.items():\n    print(k, ': ', round(v,4))\n\nprint('\\nForecast Accuracy of: Recovered')\naccuracy_prod = forecast_accuracy(df_results['Recovered_forecast'].values, df_test['Recovered'])\nfor k, v in accuracy_prod.items():\n    print(k, ': ', round(v,4))\n\nprint('\\nForecast Accuracy of: Deaths')\naccuracy_prod = forecast_accuracy(df_results['Deaths_forecast'].values, df_test['Deaths'])\nfor k, v in accuracy_prod.items():\n    print(k, ': ', round(v,4))\n\nprint('\\nForecast Accuracy of: TestsPerformed')\naccuracy_prod = forecast_accuracy(df_results['TestsPerformed_forecast'].values, df_test['TestsPerformed'])\nfor k, v in accuracy_prod.items():\n    print(k, ': ', round(v,4))\n\"\"\"\n**Considering the length of our data, the results seems to be reasonable (altough not perfect :)).** \n\n**It might be the case that the model predictions will be better, as we get more updated data to feed into the model.** \n\n**In addition, I invite you to use this model (and modify it) in order to make similar predictions to other countries.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c46c6f419b8f36'}"}
{"id":"39552","text":"\"\"\"\n![image](https:\/\/neurohive.io\/wp-content\/uploads\/2018\/11\/vgg16.png)\n\"\"\"\n# 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 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\n\"\"\"\n## VGG16 And ImageNet\n\"\"\"\n\"\"\"\nThe pre-trained model we'll be working with to classify images of cats and dogs is called VGG16, which is the model that won the 2014 ImageNet competition.\n\nIn the ImageNet competition, multiple teams compete to build a model that best classifies images from the ImageNet library. The ImageNet library houses thousands of images belonging to 1000 different categories.\n\nWe\u2019ll import this VGG16 model and then fine-tune it using Keras. The fine-tuned model will not classify images as one of the 1000 categories for which it was trained on, but instead it will only work to classify images as either cats or dogs.\n\nNote that dogs and cats were included in the ImageNet library from which VGG16 was originally trained. Therefore, the model has already learned the features of cats and dogs. Given this, the fine-tuning we'll do on this model will be very minimal\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Activation, Dense, Flatten, BatchNormalization, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import KFold\nimport itertools\nimport os\nimport shutil\nimport random\nimport glob\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n%matplotlib inline\ntrain_path = '\/kaggle\/input\/cat-and-dog\/training_set\/training_set'\n# valid_path = 'data\/dogs-vs-cats\/valid'\ntest_path = '..\/input\/cat-and-dog\/test_set\/test_set'\ntrain_batches = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \\\n    .flow_from_directory(directory=train_path, target_size=(224,224), classes=['cats', 'dogs'], batch_size=10)\ntest_batches = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \\\n    .flow_from_directory(directory=test_path, target_size=(224,224), classes=['cats', 'dogs'], batch_size=10, shuffle=False)\nimgs, labels = next(train_batches)\ndef plotImages(images_arr):\n    fig, axes = plt.subplots(1, 10, figsize=(20,20))\n    axes = axes.flatten()\n    for img, ax in zip( images_arr, axes):\n        ax.imshow(img)\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\"\"\"\nLet's first check out a batch of training data using the plotting function\n\"\"\"\nplotImages(imgs)\nprint(labels)    \n\"\"\"\nWhen we [previously](https:\/\/www.kaggle.com\/bavalpreet26\/cnn-tutorial-keras-nb2) inspected these images, we briefly discussed that the color data was skewed as a result of preprocessing the images using the tf.keras.applications.vgg16.preprocess_input function.\n\"\"\"\n\"\"\"\nTo understand what preprocessing is needed for images that will be passed to a VGG16 model, we can look at the [VGG16 paper](https:\/\/arxiv.org\/pdf\/1409.1556.pdf).\n\"\"\"\n\"\"\"\nUnder the 2.1 Architecture section, we can see that the authors stated that, \"The only preprocessing we do is subtracting the mean RGB value, computed on the training set, from each pixel.\"\n\nThis is the preprocessing that was used on the original training data, and therefore, this is the way we need to process images before passing them to VGG16 or a fine-tuned VGG16 model.\n\nThis processing is what is causing the underlying color data to look distorted\n\"\"\"\n\"\"\"\n# Part-1 Building A Fine - Tuned Model\n\"\"\"\n\"\"\"\nNow, let's begin building our model.\n\"\"\"\nvgg16_model = tf.keras.applications.vgg16.VGG16()\n\"\"\"\nThe original trained VGG16 model, along with its saved weights and other parameters, is now downloaded.\n\nWe can check out a summary of the model just to see what the architecture looks like.\n\"\"\"\nvgg16_model.summary()\n\"\"\"\nIn contrast, recall how much simpler the CNN was that we worked with in the last [notebook](https:\/\/www.kaggle.com\/bavalpreet26\/cnn-tutorial-keras-nb2). VGG16 is much more complex and sophisticated and has many more layers than our previous model.\n\"\"\"\n\"\"\"\nNotice that the last `Dense` layer of VGG16 has `1000` outputs. These outputs correspond to the 1000 categories in the ImageNet library.\n\nSince we\u2019re only going to be classifying two categories, cats and dogs, we need to modify this model in order for it to do what we want it to do, which is to only classify cats and dogs.\n\nBefore we do that, note that the type of Keras models we\u2019ve been working with so far in this series have been of type `Sequential`.\n\"\"\"\n\"\"\"\nIf we check out the type of model `vgg16_model` is, we see that it is of type `Model`, which is from the Keras\u2019 `Functional` API.\n\"\"\"\ntype(vgg16_model)\n\"\"\"\nWe\u2019ve not yet worked with the more sophisticated Functional API, although we will work with it in later notebooks using the MobileNet model.\n\"\"\"\n\"\"\"\nFor now, we\u2019re going to go through a process to convert the `Functional` model to a `Sequential` model, so that it will be easier for us to work with given our current knowledge.\n\nWe first create a new model of type `Sequential`. We then iterate over each of the layers in `vgg16_model`, except for the last layer, and add each layer to the new `Sequential` model.\n\"\"\"\nmodel = Sequential()\nfor layer in vgg16_model.layers[:-1]:\n    model.add(layer)\n\"\"\"\nNow, we have replicated the entire `vgg16_model` (excluding the output layer) to a new `Sequential` model, which we've just given the name `model`.\n\nNext, we\u2019ll iterate over each of the layers in our new `Sequential` model and set them to be <font color='red'>non-trainable<\/font>. This freezes the weights and other trainable parameters in each layer so that they will not be trained or updated when we later pass in our images of cats and dogs.\n\"\"\"\nfor layer in model.layers:\n    layer.trainable = False\n\"\"\"\nThe reason we don\u2019t want to retrain these layers is because, as mentioned earlier, cats and dogs were already included in the original ImageNet library. So, VGG16 already does a nice job at classifying these categories. We only want to modify the model such that the output layer understands only how to classify cats and dogs and nothing else. Therefore, we don\u2019t want any re-training to occur on the earlier layers.\n\nNext, we add our new output layer, consisting of only 2 nodes that correspond to cat and dog. This output layer will be the only trainable layer in the model.\n\"\"\"\nmodel.add(Dense(units=2, activation='softmax'))\n\"\"\"\nWe can now check out a `summary` of our model and see that everything is exactly the same as the original `vgg16_model`, except for now, the output layer has only `2` nodes, rather than 1000, and the number of `trainable parameters` has drastically decreased since we froze all the parameters in the earlier layers.\n\"\"\"\nmodel.summary()\n\"\"\"\n# Part - 2\n\"\"\"\n\"\"\"\n### Train A Fine-Tuned Neural Network With TensorFlow's Keras API\n\"\"\"\n\"\"\"\nLet's see how to train the fine-tuned VGG16 model to classify images as cats or dogs.\n\"\"\"\n\"\"\"\nwe\u2019ll use the `Adam` optimizer with a learning rate of `0.0001`, `categorical_crossentropy` as our loss, and `\u2018accuracy\u2019` as our metric.\n\"\"\"\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])\n\"\"\"\nNow, we\u2019ll train the model using model.fit().\n\nNote that the call to `fit()` is exactly the same as it was when we used it on the original CNN we built from scratch in a previous [notebook](https:\/\/www.kaggle.com\/bavalpreet26\/cnn-tutorial-keras-nb2), except for we're only running 5 epochs this time\n\"\"\"\nmodel.fit(x = train_batches, \n          steps_per_epoch = len(train_batches),\n          epochs = 5,\n          verbose = 2\n         )\n\"\"\"\nLooking at the results from training, we can see just after 5 epochs, we have some pretty outstanding results, especially when you compare it to the results we got from our original model.\n\nOur accuracy starts off at 96% and goes over 99% in just 5 epochs.\n\"\"\"\n\"\"\"\n# Part-3 Predict\n\"\"\"\n\"\"\"\nNow see how to use the fine-tuned VGG16 model that we trained above to predict on images of cats and dogs in our test set.\n\"\"\"\n\"\"\"\nPicking up with the code, we\u2019ll first get a batch of test samples and their corresponding labels from the test set, and plot them to see what the data looks like\n\"\"\"\ntest_imgs, test_labels = next(test_batches)\nplotImages(test_imgs)\nprint(test_labels)\n\"\"\"\nRecall that this is the same test set we used in a previous [notebook](https:\/\/www.kaggle.com\/bavalpreet26\/cnn-tutorial-keras-nb2) to test the model we built from scratch, and the color in the images appears to be distorted due to the VGG16 preprocessing we discussed previously.\n\"\"\"\n\"\"\"\nWe now call model.predict to have the model predict on the test data.\n\"\"\"\npredictions = model.predict(x = test_batches, steps = len(test_batches), verbose = 0)\n\"\"\"\nWe pass in the test set, test_batches, and set steps to be then length of test_batches, steps specifies how many batches to yield from the test set before declaring one prediction round complete.\n\"\"\"\n\"\"\"\n#### Plot Predictions with a Confusion Matrix\n\"\"\"\n\"\"\"\nWe\u2019re now going to create a confusion matrix so we can visualize our predictions.\n\"\"\"\n# def plot_confusion_matrix(cm, classes,\n#                           normalize=False,\n#                           title='Confusion matrix',\n#                           cmap=plt.cm.Blues):\n#     \"\"\"\n#     This function prints and plots the confusion matrix.\n#     Normalization can be applied by setting `normalize=True`.\n#     \"\"\"\n#     plt.imshow(cm, interpolation='nearest', cmap=cmap)\n#     plt.title(title)\n#     plt.colorbar()\n#     tick_marks = np.arange(len(classes))\n#     plt.xticks(tick_marks, classes, rotation=45)\n#     plt.yticks(tick_marks, classes)\n\n#     if normalize:\n#         cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n#         print(\"Normalized confusion matrix\")\n#     else:\n#         print('Confusion matrix, without normalization')\n\n#     print(cm)\n\n#     thresh = cm.max() \/ 2.\n#     for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n#         plt.text(j, i, cm[i, j],\n#             horizontalalignment=\"center\",\n#             color=\"white\" if cm[i, j] > thresh else \"black\")\n\n#     plt.tight_layout()\n#     plt.ylabel('True label')\n#     plt.xlabel('Predicted label')\n# test_batches.class_indices\ncm = confusion_matrix(y_true=test_batches.classes, y_pred=np.argmax(predictions, axis=-1))\ncm_plot_labels = ['cat','dog']\nplot_confusion_matrix(cm=cm, classes=cm_plot_labels, title='Confusion Matrix')\n\"\"\"\nInspired from [this channel](https:\/\/www.youtube.com\/watch?v=oDHpqu52soI&list=PLZbbT5o_s2xrwRnXk_yCPtnqqo4_u2YGL&index=13)\n\"\"\"\n\"\"\"\nWe can see that the model incorrectly predicted only few samples.So proving this model to be much more capable of generalizing than the previous CNN we built from scratch.\n\"\"\"\n\"\"\"\nto be continue...\nwill share next kernal publically soon\n\nlink to next [part](https:\/\/www.kaggle.com\/bavalpreet26\/keras4\/edit)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '48db96a90a373a'}"}
{"id":"90360","text":"import numpy as np\nimport pandas as pd\nimport os\nimport json\nfrom pathlib import Path\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\nfrom os.path import join as path_join\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")  #suppress all warnings\n\n#######THIS CODE IS FOR USE WITH ANOCONDA PYTHON EDITOR IN MY DIRECTORY###########\n#training_path = 'kaggle\/input\/abstraction-and-reasoning-challenge\/training\/'\n#training_tasks = os.listdir(training_path)\n#Trains = []\n#for i in range(400):\n#    task_file = str(training_path + training_tasks[i])\n#    task = json.load(open(task_file, 'r'))\n#    Trains.append(task)\n#train_tasks = Trains\n##############################################################################\n\ndata_path = Path('\/kaggle\/input\/abstraction-and-reasoning-challenge\/')\ntraining_path = data_path \/ 'training'\nevaluation_path = data_path \/ 'evaluation'\ntest_path = data_path \/ 'test'\ntraining_tasks = os.listdir(training_path)\neval_tasks = os.listdir(evaluation_path)\nT = training_tasks\nTrains = []\nfor i in range(400):\n    task_file = str(training_path \/ T[i])\n    task = json.load(open(task_file, 'r'))\n    Trains.append(task)\ndef load_data(path):\n    tasks = pd.Series()\n    for file_path in os.listdir(path):\n        task_file = path_join(path, file_path)\n        with open(task_file, 'r') as f:\n            task = json.load(f)\n        tasks[file_path[:-5]] = task\n    return tasks\ntrain_tasks = load_data('..\/input\/abstraction-and-reasoning-challenge\/training\/')\n\n\"\"\"\n* # The following functions retrieve the matrix dimensions, infer how to calculate the output dimensions, then applies that rule to the test input matrix dimensions.\n* # The accuracy is 346 \/ 400 (86%) 'test' matrix output dimensions successfully predicted based on training pairs.\n* # The types of inferences it makes are:\n    * ###     'multiply or divide by' (such as multiply the height of input matrix by 2), \n    * ###     'add or subtract', \n    * ###     and 'static' (such as make height equal to 9 regardless of input matrix size).\n* ## Stay tuned for the release of more functions I have made for object similarity estimation, transformations, attribute comparisons, etc. in the coming days.\n\"\"\"\n\ndef get_matrix_dims(task_num):\n    amatrix_dims={'in_matrix_height': [], \n                  'in_matrix_width': [], \n                  'out_matrix_height': [], \n                  'out_matrix_width': [],\n                  'test_in_height': [], \n                  'test_in_width': [],\n                  'test_out_height': [], \n                  'test_out_width': []}\n    # iterate through training examples \n    num_examples = len(train_tasks[task_num]['train'])\n    ain_height = []\n    ain_width = []\n    aout_height = []\n    aout_width = []\n    for i in range(num_examples):\n        input_image = np.array(train_tasks[task_num]['train'][i]['input'])\n        output_image = np.array(train_tasks[task_num]['train'][i]['output'])\n        in_matrix_height = input_image.shape[0]\n        in_matrix_width = input_image.shape[1]\n        out_matrix_height = output_image.shape[0]\n        out_matrix_width = output_image.shape[1] \n        ain_height.append(in_matrix_height)\n        ain_width.append(in_matrix_width)\n        aout_height.append(out_matrix_height)\n        aout_width.append(out_matrix_width)\n    amatrix_dims['in_matrix_height'].append(ain_height)\n    amatrix_dims['in_matrix_width'].append(ain_width)\n    amatrix_dims['out_matrix_height'].append(aout_height)\n    amatrix_dims['out_matrix_width'].append(aout_width)\n    num_examples = len(train_tasks[task_num]['test'])\n    ain_height = []\n    ain_width = []\n    aout_height = []\n    aout_width = []\n    for i in range(num_examples):\n        input_image = np.array(train_tasks[task_num]['test'][i]['input'])\n        output_image = np.array(train_tasks[task_num]['test'][i]['output'])\n        in_matrix_height = input_image.shape[0]\n        in_matrix_width = input_image.shape[1]\n        out_matrix_height = output_image.shape[0]\n        out_matrix_width = output_image.shape[1] \n        ain_height.append(in_matrix_height)\n        ain_width.append(in_matrix_width)\n        aout_height.append(out_matrix_height)\n        aout_width.append(out_matrix_width)\n    amatrix_dims['test_in_height'].append(ain_height)\n    amatrix_dims['test_in_width'].append(ain_width)\n    amatrix_dims['test_out_height'].append(aout_height)\n    amatrix_dims['test_out_width'].append(aout_width)\n    return amatrix_dims\n\ndef get_matrix_rule(amatrix_dims):\n    funcs_match_not_unknown = False\n    multiplier_height = []\n    multiplier_width = []\n    addition_height = []\n    addition_width = []\n    answer_height = 'unknown' # if no rule found then uses size of 30\n    height_param = 30\n    answer_width = 'unknown'\n    width_param = 30\n    num_examples = len(amatrix_dims['in_matrix_width'][0])\n    for i in range(num_examples):\n        in_height = amatrix_dims['in_matrix_height'][0][i]\n        out_height = amatrix_dims['out_matrix_height'][0][i]\n        in_width = amatrix_dims['in_matrix_width'][0][i]\n        out_width = amatrix_dims['out_matrix_width'][0][i]\n        mult_height = out_height \/ in_height\n        mult_width = out_width \/ in_width\n        multiplier_height.append(mult_height)\n        multiplier_width.append(mult_width)\n        add_height = out_height - in_height\n        addition_height.append(add_height)\n        add_width = out_width - in_width\n        addition_width.append(add_width)\n    mult_height_unique = np.unique(multiplier_height)\n    mult_width_unique = np.unique(multiplier_width)\n    if len(mult_height_unique) == 1:\n        answer_height = 'multiply by'\n        height_param = mult_height_unique[0]\n    if len(mult_width_unique) == 1:\n        answer_width = 'multiply by'\n        width_param = mult_width_unique[0]\n    height_unique = np.unique(amatrix_dims['out_matrix_height'][0])\n    width_unique = np.unique(amatrix_dims['out_matrix_width'][0])\n    if answer_height != 'unknown' and answer_width == answer_height:\n        funcs_match_not_unknown = True\n    if len(height_unique) == 1 and funcs_match_not_unknown == False:\n        answer_height = 'static'\n        height_param = int(height_unique[0])\n    if len(width_unique) == 1 and funcs_match_not_unknown == False:\n        answer_width = 'static'\n        width_param = int(width_unique[0])\n    add_height_unique = np.unique(addition_height)\n    add_width_unique = np.unique(addition_width)\n    if answer_height != 'unknown' and answer_width == answer_height:\n        funcs_match_not_unknown = True\n    if len(add_height_unique) == 1 and funcs_match_not_unknown == False:\n        answer_height = 'add this much'\n        height_param = add_height_unique[0]\n    if len(add_width_unique) == 1 and funcs_match_not_unknown == False:\n        answer_width = 'add this much'\n        width_param = add_width_unique[0]\n    return answer_height, height_param, answer_width, width_param\n\ndef get_test_matrix_dims(amatrix_dims, matrix_rule):\n    test_in_height = amatrix_dims['test_in_height'][0][0]\n    test_in_width = amatrix_dims['test_in_width'][0][0]\n    if matrix_rule[0] == 'static':\n        test_out_height = matrix_rule[1]\n    elif matrix_rule[0] == 'multiply by':\n        test_out_height = test_in_height*matrix_rule[1]\n    elif matrix_rule[0] == 'add this much':\n        test_out_height = test_in_height + matrix_rule[1]\n    else:\n        test_out_height = 30\n    if matrix_rule[2] == 'static':\n        test_out_width = matrix_rule[3]\n    elif matrix_rule[2] == 'multiply by':\n        test_out_width = test_in_width*matrix_rule[3]\n    elif matrix_rule[2] == 'add this much':\n        test_out_width = test_in_width + matrix_rule[3]\n    else:\n        test_out_width = 30\n    test_out_height = int(test_out_height)\n    test_out_width = int(test_out_width)\n    return test_out_height, test_out_width\n\n#%% [to test multiple tasks]\n\n\n\"\"\"\n\n## Below is how to run the program in a for loop and estimate the test pair's output matrix dimensions for all 400 tasks without looking at the answer, then checking the answer against the predicted dimensions and making a list of successful and failed predictions. The accuracy is 346 out of 400.\n\"\"\"\namatrix_successfully_predicted =[]\namatrix_unsuccessfully_predicted = []\n##uncomment the two lines below and comment the third line to test for only certain tasks\n#task_num = [0, 1, 7, 263]\n#for i in task_num:     \nfor i in range(400):\n    try:\n        height_success = False\n        width_success = False\n        task_num=i\n        task = train_tasks[task_num] \n        amatrix_dims = get_matrix_dims(task_num)\n        matrix_rule = get_matrix_rule(amatrix_dims)\n        test_matrix_dims = get_test_matrix_dims(amatrix_dims, matrix_rule)\n        if test_matrix_dims[0] == amatrix_dims['test_out_height'][0][0]:\n            height_success = True\n        if test_matrix_dims[1] == amatrix_dims['test_out_width'][0][0]:\n            width_success = True\n        a=[i,'guess', test_matrix_dims, 'actual', amatrix_dims['test_out_height'][0][0], amatrix_dims['test_out_width'][0][0]]\n        if height_success == True and width_success == True:\n            amatrix_successfully_predicted.append(i)\n        else:\n            amatrix_unsuccessfully_predicted.append(a)\n    except KeyboardInterrupt:\n        print('matrix dims failed for task:', task_num)\nprint('predicted:', len(amatrix_successfully_predicted),'\/ 400 matrix sizes.')\nprint('failed:   ', len(amatrix_unsuccessfully_predicted),'\/ 400  matrix sizes.')\nprint('')\npp.pprint('failed matrixes are:')\npp.pprint(amatrix_unsuccessfully_predicted)","meta":"{'source': 'AI4Code', 'id': 'a5b65722b0b6dc'}"}
{"id":"98964","text":"\"\"\"\n# Selective Mask\n\"\"\"\n\"\"\"\nThis version update:\n- uses `openslide` to view the `.tiff` files instead of the previous version that involved coverting the files from `.tiff` to `.png`\n- each image is categorized by an `isup_grade` and we can selectively choose what grade to view by specifying `min_px` and `max_px` values\n- load the selective mask into a `DataLoader`\n\n### Original Mask\n\n![selective_msk.PNG](attachment:selective_msk.PNG)\n\n### Selective Mask\n`min_px` value of 3\n\n![selective_msk2.PNG](attachment:selective_msk2.PNG)\n\"\"\"\n\"\"\"\n# Load the dependencies\n\"\"\"\n!pip install fastai2 -q\n#Load the dependancies\nfrom fastai2.basics import *\nfrom fastai2.callback.all import *\nfrom fastai2.vision.all import *\n\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport openslide\n\nsns.set(style=\"whitegrid\")\nsns.set_context(\"paper\")\n\nmatplotlib.rcParams['image.cmap'] = 'ocean_r'\nsource = Path(\"..\/input\/prostate-cancer-grade-assessment\")\nfiles = os.listdir(source)\nfiles\n\"\"\"\nSpecify the folders\n\"\"\"\ntrain = source\/'train_images'\nmask = source\/'train_label_masks'\ntrain_labels = pd.read_csv(source\/'train.csv')\ntrain_labels.head()\n\"\"\"\n# Viewing an image\n\"\"\"\n\"\"\"\nYou can view the images and masks by specifying their filename.  The only difference in the naming between the images and masks is that the mask filenames have `_mask` before the file type.\n\nThe masks are saved in RGB format and the mask is stored in the red channel and the rest of the channels are set to 0. To view the mask we have to explicity display only that channel.\n\nWe can create a function to view the images and masks using `openslide` that takes into consideration where the image is stored, if the non-mask image display the image as is or if it is the mask image display the red channel only.\n\"\"\"\ndef view_image(folder, fn):\n    if folder == train:\n        filename = f'{folder}\/{fn}.tiff'\n    if folder == mask:\n        filename = f'{folder}\/{fn}_mask.tiff'\n    file = openslide.OpenSlide(str(filename))\n    t = tensor(file.get_thumbnail(size=(255, 255)))\n    if folder == train:\n        show_image(t)\n    if folder == mask:\n        show_image(t[:,:,0])\n\"\"\"\nView an image\n\"\"\"\nview_image(train, '0005f7aaab2800f6170c399693a96917')\n\"\"\"\nView the corresponding mask\n\"\"\"\nview_image(mask, '0005f7aaab2800f6170c399693a96917')\n\"\"\"\nThe dataset is categorized by both `isup_grade` and `gleason_score`.  What is noticed is that the masks have different intensities.  For example we can specify a function that will display the image, the mask and plot a histogram of the intensites. \n\"\"\"\ndef view_images(file, mask, fn):\n    ima = f'{file}\/{fn}.tiff'\n    msk = f'{mask}\/{fn}_mask.tiff'\n    ima_file = openslide.OpenSlide(str(ima)); ima_t = tensor(ima_file.get_thumbnail(size=(255, 255)))\n    ima_msk = openslide.OpenSlide(str(msk)); msk_t = tensor(ima_msk.get_thumbnail(size=(255, 255)))\n    \n    fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize = (20, 6))\n    s1 = show_image(ima_t, ax=ax1, title='image')\n    s2 = show_image(msk_t[:,:,0], ax=ax2, title='mask')\n    s3 = plt.hist(msk_t.flatten()); plt.title('mask histogram')\n    plt.show()\nview_images(train, mask, '06636cdd43041e78141f2f5069fa62d5')\n\"\"\"\nPlotting a histogram of the mask intensities shows that the bulk of the intensity is between `0` and `1` and this corresponds to the the bulk of the pixels which is the outline of the mask (light blue)\n\nHere are some more examples:\n\"\"\"\nview_images(train, mask, '0d3159cd1b2495cc82637ececf63ed41')\nview_images(train, mask, '08134913a9aa1d541f719e9f356f9378')\n\"\"\"\nCan see that the bulk of the pixels within the mask are the light blue areas of the mask which correspond to the the out outline of the mask itself.  \n\"\"\"\n\"\"\"\n# Selective Mask\n\"\"\"\n\"\"\"\nTo be able to view the mask images at different intensities I adapted a function from `fastai`'s medical imaging library (which is typically geared towards working with DICOM images). To learn more about `fastai`'s medical imaging module please read my blog [here](https:\/\/asvcode.github.io\/MedicalImaging\/) or view this [notebook](https:\/\/www.kaggle.com\/avirdee\/fastai2-dicom-starter)\n\nLoad the medical imaging library\n\"\"\"\nfrom fastai2.medical.imaging import *\n\"\"\"\nThis library has a `show` function that has the capability of specifying max and min pixel values so you can specify the range of pixels you want to view within an image (useful when DICOM images can vary in pixel values between the range of -32768 to 32768).\n \nYou can easily adapt any function in `fastai2` using `@patch` and it just works!  In this case I am adapting the `show` function so you can specify `min` and `max` pixel values for this dataset.\n\"\"\"\n@patch\n@delegates(show_image)\ndef show(self:PILImage, scale=True, cmap=plt.cm.ocean_r, min_px=None, max_px=None, **kwargs):\n    px = tensor(self)\n    if min_px is not None: px[px<min_px] = float(min_px)\n    if max_px is not None: px[px>max_px] = float(max_px)\n    show_image(px, cmap=cmap, **kwargs)\n\"\"\"\nWe will also have to define another function that will allow us to view the selective masks\n\"\"\"\ndef selective_mask(file, mask, fn, min_px=None, max_px=None):\n    ima = f'{file}\/{fn}.tiff'\n    msk = f'{mask}\/{fn}_mask.tiff'\n    ima_file = openslide.OpenSlide(str(ima)); ima_t = tensor(ima_file.get_thumbnail(size=(255, 255)))\n    ima_msk = openslide.OpenSlide(str(msk)); msk_t = tensor(ima_msk.get_thumbnail(size=(255, 255)))\n    msk_pil = PILImage.create(msk_t[:,:,0])\n    \n    fig, (ax1, ax2, ax3, ax4) = plt.subplots(1,4, figsize = (20, 6))\n    s1 = show_image(ima_t, ax=ax1, title='image')\n    s2 = show_image(msk_t[:,:,0], ax=ax2, title='mask')\n    s3 = msk_pil.show(min_px=min_px, max_px=max_px, ax=ax3, title=f'selective mask: min_px:{min_px}')\n    s4 = plt.hist(msk_t.flatten()); plt.title('mask histogram')\n    plt.show()\n\"\"\"\nThe plot shows the original image, the mask, the selective mask(in this case all intensities are shown hence the reason it looks the same as the mask image) and the histogram of intensities (again the bulk of pixels are within `0` and `1`\n\"\"\"\nselective_mask(train, mask, '08134913a9aa1d541f719e9f356f9378', min_px=None, max_px=None)\n\"\"\"\nHow about intensities above 1 (so getting rid of the bulk of pixels)\n\"\"\"\nselective_mask(train, mask, '08134913a9aa1d541f719e9f356f9378', min_px=1, max_px=None)\n\"\"\"\nIntensities above 2\n\"\"\"\nselective_mask(train, mask, '08134913a9aa1d541f719e9f356f9378', min_px=2, max_px=None)\n\"\"\"\nIntensities above 3\n\"\"\"\nselective_mask(train, mask, '08134913a9aa1d541f719e9f356f9378', min_px=3, max_px=None)\n\"\"\"\nThe histogram does show some pixels above 4 but not many\n\"\"\"\nselective_mask(train, mask, '08134913a9aa1d541f719e9f356f9378', min_px=4, max_px=None)\n\"\"\"\nLooking at the selective masks side by side\n\"\"\"\nmsk = f'{mask}\/08134913a9aa1d541f719e9f356f9378_mask.tiff'\nima_msk = openslide.OpenSlide(str(msk)); msk_t = tensor(ima_msk.get_thumbnail(size=(255, 255)))\nmsk_pil = PILImage.create(msk_t[:,:,0])\nfig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(1,5, figsize = (20, 6))\ns1 = msk_pil.show(min_px=None, max_px=None, ax=ax1, title='original mask')\ns2 = msk_pil.show(min_px=1, max_px=2, ax=ax2, title='1 and 2')\ns3 = msk_pil.show(min_px=2, max_px=3, ax=ax3, title='2 and 3')\ns4 = msk_pil.show(min_px=3, max_px=4, ax=ax4, title='3 and 4')\ns4 = msk_pil.show(min_px=4, max_px=5, ax=ax5, title='4 and 5')\nplt.show()\n\"\"\"\nlets check to see what the `isup_grade` of the example above is:\n\"\"\"\ntrain_labels[train_labels.values == '08134913a9aa1d541f719e9f356f9378']\n\"\"\"\nIt has an `isup_grade` of 4\n\"\"\"\n\"\"\"\n### isup_grade = 0\n\"\"\"\n\"\"\"\nLets check an example with `isup_grade` of 0\n\"\"\"\nisup_0 = train_labels[train_labels.isup_grade == 0]\nisup_0[:1]\nselective_mask(train, mask, '0005f7aaab2800f6170c399693a96917', min_px=None, max_px=None)\n\"\"\"\n### isup_grade = 5\n\"\"\"\n\"\"\"\nWhat about images with `isup_grade` of 5\n\"\"\"\nisup_5 = train_labels[train_labels.isup_grade == 5]\nisup_5[:1]\nselective_mask(train, mask, '00928370e2dfeb8a507667ef1d4efcbb', min_px=None, max_px=None)\n\"\"\"\nIt looks like:\n- each mask has intensities based on its `isup_grade`\n\"\"\"\n\"\"\"\n# DataBlock\n\"\"\"\n\"\"\"\nLets see what the `dataBlock` would look like.  `fastai` provides a very convenient way of getting the dataset ready for training for example you can specify `blocks` and `getters` where `blocks` can be images, labels etc and `getters` are where are the images or labels located.\n\"\"\"\n\"\"\"\nFor this we would have to create 2 custom functions, one so that that the `dataloader` can correctly view the images (as they are in `.tiff` format and `fastai` does not have an out of the box method of parsing these files and the second so that we only view the masks in the red channel\n\"\"\"\n\"\"\"\nAs we'll be using the `csv` file to load the images\n\"\"\"\ndef custom_img(fn):\n    fn = f'{train}\/{fn.image_id}.tiff'\n    file = openslide.OpenSlide(str(fn))\n    t = tensor(file.get_thumbnail(size=(255, 255)))\n    img_pil = PILImage.create(t)\n    return img_pil\n\"\"\"\nFor the masks\n\"\"\"\n\"\"\"\nWe have to make a custom function `show_selective` so that we can pass the different intensities to the `dataloader`\n\"\"\"\ndef show_selective(p, scale=True, cmap=plt.cm.ocean_r, min_px=None, max_px=None):\n    px = tensor(p)\n    if min_px is not None: px[px<min_px] = float(min_px)\n    if max_px is not None: px[px>max_px] = float(max_px)\n    return px\ndef custom_selective_msk(fn):\n    fn = f'{mask}\/{fn.image_id}_mask.tiff'\n    file = openslide.OpenSlide(str(fn))\n    t = tensor(file.get_thumbnail(size=(255, 255)))[:,:,0]\n    ts = show_selective(t, min_px=None, max_px=None)\n    return ts\n\"\"\"\nSpecify the `blocks`\n\nLets look at images and masks side by side just to see what the images and masks look like\n\"\"\"\n\"\"\"\n### Using original mask\n\"\"\"\nblocks = (ImageBlock,\n          ImageBlock)\n\ngetters = [\n           custom_img,\n           custom_selective_msk\n          ]\nprostate = DataBlock(blocks=blocks,\n                 getters=getters,\n                 item_tfms=Resize(128))\n\nj = prostate.dataloaders(train_labels, bs=16)\nj.show_batch(max_n=12, nrows=2, ncols=6)\n\"\"\"\nThe batch above shows the images and masks side by side, in this case the full mask is being shown.  However what if we specify the mask intensites, as an example I want to get rid of the bulk of images which is predominantly the outline of the mask or any intensitiy below 1\n\"\"\"\n\"\"\"\n### Using Selective mask\n\"\"\"\n\"\"\"\nSpecify the min_px value as 1 in the `custom_selective_msk` function:\n\"\"\"\ndef custom_selective_msk(fn):\n    fn = f'{mask}\/{fn.image_id}_mask.tiff'\n    file = openslide.OpenSlide(str(fn))\n    t = tensor(file.get_thumbnail(size=(255, 255)))[:,:,0]\n    ts = show_selective(t, min_px=1, max_px=None)\n    return ts\nblocks = (ImageBlock,\n          ImageBlock)\n\ngetters = [\n           custom_img,\n           custom_selective_msk\n          ]\nprostate = DataBlock(blocks=blocks,\n                 getters=getters,\n                 item_tfms=Resize(128))\n\nj = prostate.dataloaders(train_labels, bs=16)\nj.show_batch(max_n=12, nrows=2, ncols=6)\n\"\"\"\nWe can see that the mask images are selective.  The mask images that are fully purple correspond to images that have an `isup_grade` of 0\n\"\"\"\n\"\"\"\nNow lets look at the images and masks over-layed on each other.  For this we simply change the `ImageBlock` we used above for the mask images into a `MaskBlock` and lets add a `CategoryBlock` so that we can identify the `isup_grade`\n\"\"\"\ndef custom_selective_msk(fn):\n    fn = f'{mask}\/{fn.image_id}_mask.tiff'\n    file = openslide.OpenSlide(str(fn))\n    t = tensor(file.get_thumbnail(size=(255, 255)))[:,:,0]\n    ts = show_selective(t, min_px=None, max_px=None)\n    return ts\nblocks = (ImageBlock,\n          MaskBlock,\n          CategoryBlock)\n\ngetters = [\n           custom_img,\n           custom_selective_msk,\n           ColReader('isup_grade')\n          ]\nprostate = DataBlock(blocks=blocks,\n                 getters=getters,\n                 item_tfms=Resize(224))\n\nj = prostate.dataloaders(train_labels, bs=16)\nj.show_batch(max_n=4)\n\"\"\"\n# Next Steps\n\"\"\"\n\"\"\"\nThere is still alot of experimentation to be done.\n\n- for example the data is extremely unbalanced but images with say `isup_grade` of 5 also have masks for grades 2,3 and 4 \n- extract the portions within the masks to create a seperate dataset\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b5c8b8ab6409ac'}"}
{"id":"7529","text":"# 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 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\n# Importing the libraries\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.offline as pyoff\nimport plotly.graph_objs as go\nimport nltk\nfrom collections import Counter\n\nfrom plotly import graph_objs as go\nfrom sklearn import preprocessing \nfrom sklearn.preprocessing import LabelBinarizer\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom wordcloud import WordCloud,STOPWORDS\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize,sent_tokenize\nfrom bs4 import BeautifulSoup\nimport re,string,unicodedata\nfrom keras.preprocessing import text, sequence\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom string import punctuation\nfrom nltk import pos_tag\nfrom nltk.corpus import wordnet\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nimport re\nimport nltk\nimport gensim\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Embedding,LSTM,Dropout, Bidirectional, Conv2D\nfrom keras.callbacks import ReduceLROnPlateau\nimport tensorflow as tf\nimport transformers\nfrom tokenizers import BertWordPieceTokenizer\nfrom keras.layers import LSTM,Dense,Bidirectional,Input\nfrom keras.models import Model\nimport torch\nimport transformers\ndf = pd.read_csv('\/kaggle\/input\/60k-stack-overflow-questions-with-quality-rate\/data.csv')\ndf.head()\n\"\"\"\nWe first concatenate both the 'Title' and 'Body' as a simple 'text' column. We shall remove the tags, Id, CreationDate\n\"\"\"\ndf['text'] = df['Title'] + df['Body']\n\ndf.drop(['Id', 'Title', 'Body', 'CreationDate', 'Tags'], axis=1, inplace=True)\ndf.head()\nsns.countplot(df['Y'])\n\"\"\"\nData looks pretty much balanced.\n\"\"\"\ndf.info()\n# Data Cleaning\nstop = set(stopwords.words('english'))\n\ndef cleaner(phrase):\n    phrase = re.sub(r\"won't\", \"will not\", phrase)\n    phrase = re.sub(r\"can't\", 'can not', phrase)\n  \n  # general\n    phrase = re.sub(r\"n\\'t\",\" not\", phrase)\n    phrase = re.sub(r\"\\'re'\",\" are\", phrase)\n    phrase = re.sub(r\"\\'s\",\" is\", phrase)\n    phrase = re.sub(r\"\\'ll\",\" will\", phrase)\n    phrase = re.sub(r\"\\'d\",\" would\", phrase)\n    phrase = re.sub(r\"\\'t\",\" not\", phrase)\n    phrase = re.sub(r\"\\'ve\",\" have\", phrase)\n    phrase = re.sub(r\"\\'m\",\" am\", phrase)\n    \n    return phrase\n\ncleaned_title = []\n\nfor sentance in tqdm(df['text'].values):\n    sentance = str(sentance)\n    sentance = re.sub(r\"http\\S+\", \"\", sentance)\n    sentance = BeautifulSoup(sentance, 'lxml').get_text()\n    sentance = cleaner(sentance)\n    sentance = re.sub(r'[?|!|\\'|\"|#|+]', r'', sentance)\n    sentance = re.sub(\"\\S*\\d\\S*\", \"\", sentance).strip()\n    sentance = re.sub('[^A-Za-z]+', ' ', sentance)\n    sentance = ' '.join(e.lower() for e in sentance.split() if e.lower() not in stop)\n    cleaned_title.append(sentance.strip())\n    \ndf['text'] = cleaned_title\ndf.head()\ndf.head()\n# Creating some basic EDA plots\n# WordCloud for HighQuality Posts\n\nplt.figure(figsize = (20,20)) # Text that is Not Sarcastic\nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800).generate(\" \".join(df[df.Y == 'HQ'].text))\nplt.imshow(wc , interpolation = 'bilinear')\n# WordCloud for LowQuality Posts Closed\n\nplt.figure(figsize = (20,20)) # Text that is Not Sarcastic\nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800).generate(\" \".join(df[df.Y == 'LQ_CLOSE'].text))\nplt.imshow(wc , interpolation = 'bilinear')\n# WordCloud for LowQuality Posts Open\n\nplt.figure(figsize = (20,20)) # Text that is Not Sarcastic\nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800).generate(\" \".join(df[df.Y == 'LQ_EDIT'].text))\nplt.imshow(wc , interpolation = 'bilinear')\n# Continuing with some n-gram analysis\n\ndef basic_clean(text):\n  \"\"\"\n  A simple function to clean up the data. All the words that\n  are not designated as a stop word is then lemmatized after\n  encoding and basic regex parsing are performed.\n  \"\"\"\n  wnl = nltk.stem.WordNetLemmatizer()\n  stopwords = nltk.corpus.stopwords.words('english')\n  text = (unicodedata.normalize('NFKD', text)\n    .encode('ascii', 'ignore')\n    .decode('utf-8', 'ignore')\n    .lower())\n  words = re.sub(r'[^\\w\\s]', '', text).split()\n  return [wnl.lemmatize(word) for word in words if word not in stopwords]\n# Bi-grams for HQ posts\n\nHQ_words = basic_clean(''.join(str(df[df.Y == 'HQ']['text'].tolist())))\nbigram_HQ=(pd.Series(nltk.ngrams(HQ_words, 2)).value_counts())[:20]\nbigram_HQ=pd.DataFrame(bigram_HQ)\nbigram_HQ['idx']=bigram_HQ.index\nbigram_HQ['idx'] = bigram_HQ.apply(lambda x: '('+x['idx'][0]+', '+x['idx'][1]+')',axis=1)\nplot_data = [\n    go.Bar(\n        x=bigram_HQ['idx'],\n        y=bigram_HQ[0],\n        marker = dict(\n            color = 'Blue'\n        )\n    )\n]\nplot_layout = go.Layout(\n        title='Top 20 bi-grams from High Quality Posts',\n        yaxis_title='Count',\n        xaxis_title='bi-gram',\n        plot_bgcolor='rgba(0,0,0,0)'\n    )\nfig = go.Figure(data=plot_data, layout=plot_layout)\npyoff.iplot(fig)\n# Bi-grams for LQ-CLOSED posts\n\nLQC_words = basic_clean(''.join(str(df[df.Y == 'LQ_CLOSE']['text'].tolist())))\nbigram_LQC=(pd.Series(nltk.ngrams(LQC_words, 2)).value_counts())[:20]\nbigram_LQC=pd.DataFrame(bigram_LQC)\nbigram_LQC['idx']=bigram_LQC.index\nbigram_LQC['idx'] = bigram_LQC.apply(lambda x: '('+x['idx'][0]+', '+x['idx'][1]+')',axis=1)\nplot_data = [\n    go.Bar(\n        x=bigram_LQC['idx'],\n        y=bigram_LQC[0],\n        marker = dict(\n            color = 'Green'\n        )\n    )\n]\nplot_layout = go.Layout(\n        title='Top 20 bi-grams from Low Quality Posts Closed',\n        yaxis_title='Count',\n        xaxis_title='bi-gram',\n        plot_bgcolor='rgba(0,0,0,0)'\n    )\nfig = go.Figure(data=plot_data, layout=plot_layout)\npyoff.iplot(fig)\n# Bi-grams for LQ-OPEN posts\n\nLQE_words = basic_clean(''.join(str(df[df.Y == 'LQ_EDIT']['text'].tolist())))\nbigram_LQE=(pd.Series(nltk.ngrams(LQE_words, 2)).value_counts())[:20]\nbigram_LQE=pd.DataFrame(bigram_LQE)\nbigram_LQE['idx']=bigram_LQE.index\nbigram_LQE['idx'] = bigram_LQE.apply(lambda x: '('+x['idx'][0]+', '+x['idx'][1]+')',axis=1)\nplot_data = [\n    go.Bar(\n        x=bigram_LQE['idx'],\n        y=bigram_LQE[0],\n        marker = dict(\n            color = 'Red'\n        )\n    )\n]\nplot_layout = go.Layout(\n        title='Top 20 bi-grams from Low Quality Posts Open',\n        yaxis_title='Count',\n        xaxis_title='bi-gram',\n        plot_bgcolor='rgba(0,0,0,0)'\n    )\nfig = go.Figure(data=plot_data, layout=plot_layout)\npyoff.iplot(fig)\n# Word2Vec\n# Model Building\n# Step 1 - Tokenization\nX = []\ntokenizer = nltk.tokenize.RegexpTokenizer(r'\\w+')\nfor par in df['text'].values:\n    tmp = []\n    sentences = nltk.sent_tokenize(par)\n    for sent in sentences:\n        sent = sent.lower()\n        tokens = tokenizer.tokenize(sent)\n        filtered_words = [w.strip() for w in tokens if w not in stop and len(w) > 1]\n        tmp.extend(filtered_words)\n    X.append(tmp)\nprint ('Tokenization done...')   \n# Model Building and Training\nw2v_model = gensim.models.Word2Vec(sentences=X, size=150, window=5, min_count=2)\nprint ('Word2Vec model created')\n# Making some naive observations\n\nw2v_model.wv.most_similar(positive = 'python')\nw2v_model.wv.most_similar(positive = 'java')\nw2v_model.wv.most_similar(positive = 'bug')\nw2v_model.wv.most_similar(positive = 'stack')\nw2v_model.wv.similarity('java', 'kotlin')\nw2v_model.wv.similarity('java', 'python')\nw2v_model.wv.doesnt_match(['java', 'python', 'scala', 'kotlin'])\nw2v_model.wv.doesnt_match(['java', 'python', 'pandas', 'numpy'])\n# label_encoder object knows how to understand word labels. \nlabel_encoder = preprocessing.LabelEncoder() \n  \n# Encode labels in column 'class'. \ndf['Y']= label_encoder.fit_transform(df['Y']) \nX = df['text']\ny = df['Y']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\"\"\"\n## String Tokenization\n\"\"\"\ntokenizer = text.Tokenizer(num_words=10000)\ntokenizer.fit_on_texts(X_train)\n\ntokenized_train = tokenizer.texts_to_sequences(X_train)\nX_train = sequence.pad_sequences(tokenized_train, maxlen=300)\n\ntokenized_test = tokenizer.texts_to_sequences(X_test)\nX_test = sequence.pad_sequences(tokenized_test, maxlen=300)\nprint(len(tokenizer.word_index))\nvocab_size = 10000 + 1\n\"\"\"\n## Loading the GLoVe embeddings pretrained\n\"\"\"\nEMBEDDING_FILE = '..\/input\/glovetwitter27b100dtxt\/glove.twitter.27B.200d.txt'\nembeddings_index = dict()\nf = open(EMBEDDING_FILE)\nfor line in f:\n\tvalues = line.split()\n\tword = values[0]\n\tcoefs = asarray(values[1:], dtype='float32')\n\tembeddings_index[word] = coefs\nf.close()\nprint('Loaded %s word vectors.' % len(embeddings_index))\n# create a weight matrix for words in training docs\nembedding_matrix = zeros((vocab_size, 100))\nfor word, i in tokenizer.word_index.items():\n\tembedding_vector = embeddings_index.get(word)\n\tif embedding_vector is not None:\n\t\tembedding_matrix[i] = embedding_vector\nembedding_matrix = zeros((vocab_size, 200))\nfor word, i in tokenizer.word_index.items():\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None:\n        embedding_matrix[i] = embedding_vector\nembedding_matrix.shape\n\"\"\"\n### Model Training\n\"\"\"\n# Training the Model. We will use a GRU model.\n\nbatch_size = 256\nepochs = 10\nembed_size = 200\nmaxlen = 300\nmax_features = 10001\n\n#Defining Neural Network\nmodel = Sequential()\n#Non-trainable embeddidng layer\nmodel.add(Embedding(max_features, output_dim=embed_size, weights=[embedding_matrix], input_length=maxlen, trainable=True))\n#LSTM\nmodel.add(LSTM(units=128 , return_sequences = True , recurrent_dropout = 0.4 , dropout = 0.4))\n#GRU\nmodel.add(GRU(units=256 , return_sequences = False, dropout = 0.4))\nmodel.add(Dense(3, activation='softmax'))\nmodel.compile(optimizer=keras.optimizers.Adam(lr = 0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.3, min_lr=0.000001)\nhistory = model.fit(X_train, y_train, batch_size = batch_size , \n                    validation_data = (X_test, y_test) , epochs = 5, \n                    callbacks = [learning_rate_reduction])\nprint(\"Accuracy of the model on Training Data is - \" , model.evaluate(X_train,y_train)[1]*100 , \"%\")\nprint(\"Accuracy of the model on Testing Data is - \" , model.evaluate(X_test,y_test)[1]*100 , \"%\")\nepochs = [i for i in range(5)]\nfig , ax = plt.subplots(1,2)\ntrain_acc = history.history['accuracy']\ntrain_loss = history.history['loss']\nval_acc = history.history['val_accuracy']\nval_loss = history.history['val_loss']\nfig.set_size_inches(20,10)\n\nax[0].plot(epochs , train_acc , 'go-' , label = 'Training Accuracy')\nax[0].plot(epochs , val_acc , 'ro-' , label = 'Testing Accuracy')\nax[0].set_title('Training & Testing Accuracy')\nax[0].legend()\nax[0].set_xlabel(\"Epochs\")\nax[0].set_ylabel(\"Accuracy\")\n\nax[1].plot(epochs , train_loss , 'go-' , label = 'Training Loss')\nax[1].plot(epochs , val_loss , 'ro-' , label = 'Testing Loss')\nax[1].set_title('Training & Testing Loss')\nax[1].legend()\nax[1].set_xlabel(\"Epochs\")\nax[1].set_ylabel(\"Loss\")\nplt.show()\n# We can see that the accuracy rises steadily for training while the growth is damped in case of testing\n# The loss values for both training and testing are decreasing steadily.\n# If we train for 15-20 epochs we can have a good convergent model\n# We can also use different layers like :\n# 1. Stacked GRU's\n# 2. Bidirectional LSTM\n# 3. Stacked LSTM's\n# 4. Stacked Bidirectional LSTM's","meta":"{'source': 'AI4Code', 'id': '0e00e0183a6ce0'}"}
{"id":"35680","text":"\"\"\"\n### IPL Player Performance\n\"\"\"\n\"\"\"\nwe are attempting to predict the ipl player performance for the year 2020 using previous year player performances\n\"\"\"\n\"\"\"\nImporting header files\n\"\"\"\nimport pandas as pd# data processing, CSV file I\/O (e.g. pd.read_csv)\nimport re\nimport numpy as np\ndata = pd.read_csv('D:\\ka\\\\training.csv')\ndata.head()\ndata_match = pd.read_csv('D:\\ka\\\\Matches IPL 2008-2019.csv')\ndata_match.head()\n\"\"\"\nWe have the player and match details but we dont have detail on which team the player was on for every year, we can use 2020 squad for now to get the team details\n\"\"\"\nsquad = pd.read_csv('D:\\ka\\\\IPL 2020 Squads.csv')\n\"\"\"\nhad to resave the csv file again in utf-8 format\n\"\"\"\nsquad\nline = \"Royal Challengers Bangalore\"\nwords = line.split()\nletters = [word[0] for word in words]\nprint(\"\".join(letters))\ndata_match1=data_match.head()\nteam = data_match1[['team1']]\n#print(team)\ncolumns = list(data_match1) \n  \nfor i in columns: \n  \n    # printing the third element of the column \n    print (data_match1[i][1]) \ndata_match.head()\nteam1_short = []\nfor index, row in data_match.iterrows():\n    line = (row['team1'])\n    words = line.split()\n    letters = [word[0] for word in words]\n    fw=\"\".join(letters)\n    team1_short.append(fw)\ndata_match['team1_short'] = team1_short\nteam2_short = []\nfor index, row in data_match.iterrows():\n    line = (row['team2'])\n    words = line.split()\n    letters = [word[0] for word in words]\n    fw=\"\".join(letters)\n    team2_short.append(fw)\ndata_match['team2_short'] = team2_short\ndata_match.head()\nimport re #for regex expressions\nstr= \"1_Bipul Sharma\"\nre.split('_',str)\nplayer_name = []\nmatch_id = []\nfor index, row in data.iterrows():\n    line = (row['Id'])\n    a = re.split('_',line)\n    match_id.append(int(a[0]))\n    player_name.append(a[1])\ndata['player_name'] = player_name\ndata['match_id'] = match_id\ndata.head()\nnew_df1= pd.merge(data,data_match[['match_id','team1_short','team2_short','season']])\nnew_df1.head()\n\"\"\"\nremoving details such as captian from name which is not necessary for player score and the two dataframes can be merged\n\"\"\"\nsquad=squad.rename(columns={\"Player_name\": \"player_name\"})\nplayer_name=[]\nsquad.head()\nfor index, row in squad.iterrows():\n    line = (row['player_name'])\n    a = re.split('\ufffd',line)\n    player_name.append(a[0])\nsquad['player_name'] = player_name\nsquad.head()\n#find most common team, this can be used to find which team was the player playing for in each season\nfrom collections import Counter\n  \ndef most_common(test_list1):\n    print(test_list1)\n    test_list1 = Counter(test_list1) \n    res = test_list1.most_common()[0][0]\n    freq = test_list1.most_common()[0][1]\n    return freq,res\n\"\"\"\nSplitting Player Name into first Name and last name\n\"\"\"\nplayer_lname=[]\nplayer_fname=[]\nnew_df1.head()\nfor index, row in new_df1.iterrows():\n    line = (row['player_name'])\n    #print(line)\n    ele = re.split(' ',line)\n    a=ele[-1]\n    b=ele[0]\n    #print(a,b)\n    #b=ele[0]\n    player_lname.append(a)\n    player_fname.append(b)\nnew_df1['lname'] = player_lname\nnew_df1['fname'] = player_fname\nnew_df1.head()\n\"\"\"\n#### Finding in which team each player has been playing for the previous years, so that we can map player performance against each team which will enable us to predict better\n\"\"\"\n\"\"\"\nto find that we are getting the match details of each game player has participated and the most common team(mode) will be the team the player will be playing for\n\"\"\"\nseason=[]\nplayer=[]\nteam=[]\nfor i in squad['player_name']:\n    nname=i #saving name for saving to list later\n    filter1=new_df1[new_df1.player_name.isin([i])]\n    if(filter1.empty):\n        nname=i.split()\n        nname=nname[1]\n        filter1=new_df1[new_df1.lname.isin([nname])]\n    for j in range(2008,2020):\n        #print(i,j)\n        filter2=filter1[filter1.season.isin([j])]\n        if(filter2.empty):\n            continue\n        else:\n            ipdf=filter2['team1_short'].values.tolist()\n            ipdf.extend(filter2['team2_short'].values.tolist())\n            freq,res=most_common(ipdf)# the mode team and its frequency\n            #print(filter2['team1_short'].head)\n            print(filter2['team1_short'].values.tolist())\n            #print(freq,res)\n            season.append(j)\n            player.append(i)\n            print(\"Team\",res)\n            team.append(res)\nnew_player_team_details = pd.DataFrame()\nnew_player_team_details['season']  = season\nnew_player_team_details['p_team']  = team\nnew_player_team_details['player_name']  = player\nnew_player_team_details\nnew_df1= pd.merge(new_df1,new_player_team_details[['season','player_name','p_team']])\n\nnew_df1.head()\n\"\"\"\nsince we now have data on which team the player is playing for we can get which team the player is playing against so that we can get the layer performace against every team\n\"\"\"\np_against=[]\nfor index, row in new_df1.iterrows():\n    p_team = (row['p_team'])\n    team1= (row['team1_short'])\n    team2=(row['team2_short'])\n    if team1==p_team:\n        p_against.append(team2)\n    else:\n        p_against.append(team1)\nnew_df1['p_against'] = p_against\nnew_df1.head()\nseason1 = squad\nseason1.head()\nseason1['player_code'] = len(season1) - pd.Categorical(season1.player_name, ordered=True).codes\nnew_df1= pd.merge(new_df1,season1[['player_name','player_code']])\nnew_df1.head()\n\"\"\"\nsince we are using regression we need to convert the strings to numbers. For that we are creating codes for each team\n\"\"\"\np_against\nnew_df1['p_against_code'] = 30 - pd.Categorical(new_df1.p_against, ordered=True).codes\n\"\"\"\nSaving file for future use\n\"\"\"\nnew_df1.to_csv (r'D:\\ka\\\\customtraining.csv', index = False, header=True)\n\"\"\"\n### Trying XGboost\n\"\"\"\n!pip install xgboost\nfrom numpy import loadtxt\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n# load data\ndataset = pd.read_csv('D:\\ka\\\\customtraining.csv')\n# split data into X and y\nY = dataset['Total Points']\nX = dataset[['player_code','p_against_code']]\n# split data into train and test sets\nseed = 7\ntest_size = 0.33\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)\n# fit model no training data\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\n# make predictions for test data\ny_pred = model.predict(X_test)\npredictions = [round(value) for value in y_pred]\n# evaluate predictions\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\"\"\"\n### Linear Regression\n\"\"\"\nfrom sklearn import linear_model\nX = dataset[['player_code','p_against_code']]\ny = dataset['Total Points']\n# split data into train and test sets\nseed = 7\ntest_size = 0.05\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)\nlm = linear_model.LinearRegression()\nmodel = lm.fit(X_train,y_train) #running with entire dataset\ny_pred = model.predict(X_test)\n\"\"\"\n#### RMSE\n\"\"\"\nfrom sklearn.metrics import mean_squared_error\nmean_squared_error(y_test, y_pred,squared=False)\nWe are getting an RMSE value of 25.8 with 95% train and 5% test value using simple linear regression\n\"\"\"\n## Logistic Regression\n\"\"\"\nfrom sklearn import preprocessing\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_scaled = scaler.transform(X_train)\nscaler1 = preprocessing.StandardScaler().fit(X_train)\nX_testscaled = scaler.transform(X_test)\n\nfrom sklearn.linear_model import LogisticRegression\nclf = LogisticRegression(random_state=0).fit(X_scaled,y_train)\ny_predl=clf.predict(X_testscaled)\nmean_squared_error(y_test, y_predl,squared=False)\n\"\"\"\n## Working with final file\n\"\"\"\nsubmission= pd.read_csv(\"D:\\ka\\\\sample_submission.csv\")\ndataset = pd.read_csv('D:\\ka\\\\customtraining.csv')\nsubmission.head()\n\"\"\"\nsplitting into ID and Player Name\n\"\"\"\nplayer_name = []\nmatch_id = []\nfor index, row in submission.iterrows():\n    line = (row['Id'])\n    a = re.split('_',line)\n    match_id.append(int(a[0]))\n    player_name.append(a[1])\nsubmission['player_name'] = player_name\nsubmission['match_id'] = match_id\nsubmission.head()\ndata_match2020 = pd.read_csv('D:\\ka\\\\Matches IPL 2020.csv')\ndata_match2020.head()\nplayer_lname=[]\nplayer_fname=[]\nsubmission.head()\nfor index, row in submission.iterrows():\n    line = (row['player_name'])\n    #print(line)\n    ele = re.split(' ',line)\n    a=ele[-1]\n    b=ele[0]\n    #print(a,b)\n    #b=ele[0]\n    player_lname.append(a)\n    player_fname.append(b)\nsubmission['lname'] = player_lname\nsubmission['fname'] = player_fname\nsubmission.head()\nsquad=squad.rename(columns={\"Player_name\": \"player_name\"})\nsquad['player_code'] = len(squad) - pd.Categorical(squad.player_name, ordered=True).codes\nplayer_lname=[]\nplayer_fname=[]\nsquad.head()\nfor index, row in squad.iterrows():\n    line = (row['player_name'])\n    #print(line)\n    ele = re.split(' ',line)\n    a=ele[-1]\n    b=ele[0]\n    #print(a,b)\n    #b=ele[0]\n    player_lname.append(a)\n    player_fname.append(b)\nsquad['lname'] = player_lname\nsquad['fname'] = player_fname\nsquad.head()\nplayer_name=[]\nsquad.head()\nfor index, row in squad.iterrows():\n    line = (row['player_name'])\n    a = re.split('\ufffd',line)\n    player_name.append(a[0])\nsquad['player_name'] = player_name\n    \nsubmission= pd.merge(submission,data_match2020[['match_id','team1','team2']])\nsubmission.head()\ndataset.head()\nsquad=squad.rename(columns={\"Player_name\": \"player_name\"})\nplayer_name=[]\nfor index, row in squad.iterrows():\n    line = (row['player_name'])\n    a = re.split('\ufffd',line)\n    player_name.append(a[0])\nsquad['player_name'] = player_name\nsquad.head()\ntype(play)\n\"\"\"\n### Working with different sheets \n\"\"\"\n\"\"\"\nthere are some issues in the name of player in squad and final_submission which makes it hard to merge files, we are merging files in 3 steps, first comaparing the player name, then if that fails comparing with last name only and even if that failes then doing manually\n\"\"\"\nplayer_name=[]\nteam=[]\nfailed_list=[]\nplayer_id=[]\nfor i in submission['player_name']:\n    filter1=squad[squad.player_name.isin([i])]\n    if(filter1.empty):\n        nname=i.split()\n        fname=nname[0]\n        if(len(nname)>=2):\n            lname=nname[len(nname)-1]\n        filter1=squad[squad.lname.isin([lname])]\n        if(filter1.empty):\n            continue\n   # else:\n    ipdf=filter1['Player_ipl_team'].values.tolist()\n        #print(ipdf)\n    if(len(ipdf)==1):\n        team.append(ipdf[0])\n        player_name.append(i)\n        player_code=filter1['player_code'].values.tolist()\n        player_id.append(player_code[0])\n    else:\n        filter2=filter1[filter1.fname.isin([fname])]\n        ipdf=filter2['Player_ipl_team'].values.tolist()\n            #print(ipdf)\n        if(len(ipdf)==1):\n            team.append(ipdf[0])\n            player_name.append(i)\n            player_code=filter1['player_code'].values.tolist()\n            player_id.append(player_code[0])\n        else:\n            failed_list.append(i)\nplay = pd.DataFrame()                   \nplay['player_name'] = player_name\nplay['team'] = team\nplay['player_code']=player_id\n#print(player_id)\nplay\nplay_drmvd = play.drop_duplicates()\nfailed_list=np.array(failed_list)\nfailed_list=np.unique(failed_list)\nprint(len(failed_list))\nprint(failed_list)\n\n\"\"\"\nManually adding missing data\n\"\"\"\nsquad['player_name'] = squad['player_name'].replace(['Axar Patel','Suryakumar Yadav','Ankit Sharma','Sheldon Cottrell','Deepak Chahar','Pavan Deshpande','Hardik Pandya','Harshal Patel','Harpreet Brar','Krunal Pandya','Karn Sharma','Josh Philippe','Prabhsimran Singh','Rinku Singh','Rahul Chahar','Rohit Sharma','Suryakumar Yadav','Sarfaraz Khan','Simran Singh','Umesh Yadav'],['AR Patel','AS Yadav','Ankit Sharma','Cottrell','DL Chahar','Deshpande',\n 'HH Pandya','HV Patel','Harpreet Singh','KH Pandya','KV Sharma','Philippe','Prabhsimran Singh','R Singh','RD Chahar','RG Sharma','SA Yadav' ,'SN Khan' ,'Simran Singh', 'UT Yadav'])\nsubmission1= pd.merge(submission,play_drmvd[['player_name','team','player_code']],on='player_name',how = 'left')\nsubmission1.to_csv (r'D:\\ka\\\\playerteamnew.csv', index = False, header=True)\nsubmission1.head()\n\"\"\"\nto check whether all rows  is filled correctly\n\"\"\"\n\"\"\"\nTo find which team is playing against\n\"\"\"\np_against=[]\nfor index, row in submission1.iterrows():\n    p_team = (row['team'])\n    team1= (row['team1'])\n    team2=(row['team2'])\n    if team1==p_team:\n        p_against.append(team2)\n    else:\n        p_against.append(team1)\nsubmission1['p_against'] = p_against\nsubmission1.head()\nsubmission1['p_against'] = submission1['p_against'].replace(['SRH'],'SH')\nsubmission1['p_against'] = submission1['p_against'].replace(['KXIP'],'KXP')\ndataset.head()\nsubmission1.to_csv (r'D:\\ka\\\\submissionv2.csv', index = False, header=True)\nsubmission1=pd.read_csv('D:\\ka\\\\submissionv2.csv')\nsubmission1.head()\nnds=dataset[['p_against','p_against_code']]\nnds=nds.drop_duplicates()\nsubmission1.head()\nnds\nsubmission1= pd.merge(submission1,nds[['p_against','p_against_code']],on='p_against',how = 'left')\nsubmission1.head()\n\"\"\"\nsubmission1.to_csv (r'D:\\ka\\\\submissionv3.csv', index = False, header=True)\n\"\"\"\nX_pred = submission1[['player_code','p_against_code']]\nfrom sklearn import linear_model\nX_train = dataset[['player_code','p_against_code']]\ny_train = dataset['Total Points']\nlm = linear_model.LinearRegression()\nmodel = lm.fit(X_train,y_train) #running with entire dataset\ny_pred = model.predict(X_pred)\n\"\"\"\nThere are some missing values in the sheet so we are manually filling the data\n\"\"\"\ny_pred\nlen(play.player_name.unique())\nplay_drmvd.to_csv (r'D:\\ka\\\\playersdd.csv', index = False, header=True)\ndf2=pd.read_csv('D:\\ka\\\\csvplayer.csv')\np_names=df2['player_name']\np_names=p_names.drop_duplicates()\np_name=[]\np_team=[]\nfor i in p_names:\n    n_f=df2[df2.player_name.isin([i])]\n    ipdf=n_f['team1'].values.tolist()\n    ipdf.extend(n_f['team2'].values.tolist())\n    freq,res=most_common(ipdf)\n    p_team.append(res)\n    p_name.append(i)\nn_p_d = pd.DataFrame()\nn_p_d['player_name']  = p_name\nn_p_d['team']  = p_team\nn_p_d\ndfextend= pd.merge(df2,n_p_d[['player_name','team']],on='player_name',how = 'left')\np_against=[]\nfor index, row in dfextend.iterrows():\n    p_team = (row['team'])\n    team1= (row['team1'])\n    team2=(row['team2'])\n    if team1==p_team:\n        p_against.append(team2)\n    else:\n        p_against.append(team1)\ndfextend['p_against'] = p_against\ndfextend\n#print(len(squad))\nnew_ids=len(squad)+len(n_p_d)\nprint(new_ids)\ndfextend['player_code'] = new_ids - pd.Categorical(dfextend.player_name, ordered=True).codes\ndfextend\ndfextend['p_against'] = dfextend['p_against'].replace(['SRH'],'SH')\ndfextend['p_against'] = dfextend['p_against'].replace(['KXIP'],'KXP')\nnds=dataset[['p_against','p_against_code']]\nnds=nds.drop_duplicates()\ndfextend= pd.merge(dfextend,nds[['p_against','p_against_code']],on='p_against',how = 'left')\ndfextend\ndfextend.to_csv (r'D:\\ka\\\\missingplayerdetails.csv', index = False, header=True)\ndfextend_final= pd.merge(submission1,dfextend[['Id','player_code','p_against_code','team']],on='Id',how = 'left')\nsubmission_final=submission1\nfor index, row in submission_final.iterrows():\n    p_team = (row['player_code'])\n    if(pd.isna(p_team)):\n        id= (row['Id'])\n        filter1=dfextend[dfextend.Id.isin([id])]\n        team_val=filter1['team'].values.tolist()\n        pcodeval=filter1['player_code'].values.tolist()\n        t_against_val=filter1['p_against_code'].values.tolist()\n        submission_final.at[index,'team'] = team_val[0]\n        submission_final.at[index,'p_against_code'] = t_against_val[0]\n        submission_final.at[index,'player_code'] = pcodeval[0]\nsubmission_final.to_csv (r'D:\\ka\\\\final.csv', index = False, header=True)\nfinal_df=pd.read_csv('D:\\ka\\\\final_submission.csv')\nplayer_code=[]\np_against_code=[]\nteam=[]\nfor index, row in final_df.iterrows():\n    id= (row['Id'])\n    filter1=submission_final[submission_final.Id.isin([id])]\n    team_val=filter1['team'].values.tolist()\n    pcodeval=filter1['player_code'].values.tolist()\n    t_against_val=filter1['p_against_code'].values.tolist()\n    team.append(team_val[0])\n    p_against_code.append(t_against_val[0])\n    player_code.append(pcodeval[0])\nfinal_df['team'] = team\nfinal_df['player_code'] = player_code\nfinal_df['p_against_code']=p_against_code\nfinal_df.to_csv (r'D:\\ka\\\\finalfinal.csv', index = False, header=True)\n\"\"\"\n## Final Prediction\n\"\"\"\nimport pandas as pd\nfinal_df=pd.read_csv('D:\\ka\\\\finalfinal.csv')\nX_pred = final_df[['p_against_code']]\nfrom sklearn import linear_model\nX_train = dataset[['p_against_code']]\ny_train = dataset['Total Points']\nlm = linear_model.LinearRegression()\nmodel = lm.fit(X_train,y_train) #running with entire dataset\ny_pred = model.predict(X_pred)\nfinal_df['Total Points']=y_pred\nfinal_df.to_csv (r'D:\\ka\\\\finalsubmission2.csv', index = False, header=True)","meta":"{'source': 'AI4Code', 'id': '41c43471e5e723'}"}
{"id":"30365","text":"\"\"\"\n## Introduction\nGreetings! This is a kernel with starter code demonstrating how to read in the data and begin exploring. Click the blue \"Fork Notebook\" button at the top of this kernel to begin editing.\n\"\"\"\n\"\"\"\n## Exploratory Analysis\nTo begin this exploratory analysis, first use `matplotlib` to import libraries and define functions for plotting the data.\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt # plotting\nimport numpy as np # linear algebra\nimport os # accessing directory structure\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n\"\"\"\nThere is 1 csv file in the current version of the dataset:\n\n\"\"\"\nprint(os.listdir('..\/input'))\n\"\"\"\nThe next hidden code cells define functions for plotting data. Click on the \"Code\" button in the published kernel to reveal the hidden code.\n\"\"\"\n# Distribution graphs (histogram\/bar graph) of column data\ndef plotPerColumnDistribution(df, nGraphShown, nGraphPerRow):\n    nunique = df.nunique()\n    df = df[[col for col in df if nunique[col] > 1 and nunique[col] < 50]] # For displaying purposes, pick columns that have between 1 and 50 unique values\n    nRow, nCol = df.shape\n    columnNames = list(df)\n    nGraphRow = (nCol + nGraphPerRow - 1) \/ nGraphPerRow\n    plt.figure(num = None, figsize = (6 * nGraphPerRow, 8 * nGraphRow), dpi = 80, facecolor = 'w', edgecolor = 'k')\n    for i in range(min(nCol, nGraphShown)):\n        plt.subplot(nGraphRow, nGraphPerRow, i + 1)\n        columnDf = df.iloc[:, i]\n        if (not np.issubdtype(type(columnDf.iloc[0]), np.number)):\n            valueCounts = columnDf.value_counts()\n            valueCounts.plot.bar()\n        else:\n            columnDf.hist()\n        plt.ylabel('counts')\n        plt.xticks(rotation = 90)\n        plt.title(f'{columnNames[i]} (column {i})')\n    plt.tight_layout(pad = 1.0, w_pad = 1.0, h_pad = 1.0)\n    plt.show()\n\n# Correlation matrix\ndef plotCorrelationMatrix(df, graphWidth):\n    filename = df.dataframeName\n    df = df.dropna('columns') # drop columns with NaN\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    if df.shape[1] < 2:\n        print(f'No correlation plots shown: The number of non-NaN or constant columns ({df.shape[1]}) is less than 2')\n        return\n    corr = df.corr()\n    plt.figure(num=None, figsize=(graphWidth, graphWidth), dpi=80, facecolor='w', edgecolor='k')\n    corrMat = plt.matshow(corr, fignum = 1)\n    plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)\n    plt.yticks(range(len(corr.columns)), corr.columns)\n    plt.gca().xaxis.tick_bottom()\n    plt.colorbar(corrMat)\n    plt.title(f'Correlation Matrix for {filename}', fontsize=15)\n    plt.show()\n\n# Scatter and density plots\ndef plotScatterMatrix(df, plotSize, textSize):\n    df = df.select_dtypes(include =[np.number]) # keep only numerical columns\n    # Remove rows and columns that would lead to df being singular\n    df = df.dropna('columns')\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    columnNames = list(df)\n    if len(columnNames) > 10: # reduce the number of columns for matrix inversion of kernel density plots\n        columnNames = columnNames[:10]\n    df = df[columnNames]\n    ax = pd.plotting.scatter_matrix(df, alpha=0.75, figsize=[plotSize, plotSize], diagonal='kde')\n    corrs = df.corr().values\n    for i, j in zip(*plt.np.triu_indices_from(ax, k = 1)):\n        ax[i, j].annotate('Corr. coef = %.3f' % corrs[i, j], (0.8, 0.2), xycoords='axes fraction', ha='center', va='center', size=textSize)\n    plt.suptitle('Scatter and Density Plot')\n    plt.show()\n\n\"\"\"\nNow you're ready to read in the data and use the plotting functions to visualize the data.\n\"\"\"\n\"\"\"\n### Let's check the file: ..\/input\/kaggle_rankings.csv\n\"\"\"\ndf = pd.read_csv('..\/input\/kaggle_rankings.csv', delimiter=',')\ndf.dataframeName = 'kaggle_rankings.csv'\nnRow, nCol = df.shape\nprint(f'There are {nRow} rows and {nCol} columns')\n\"\"\"\nLet's take a quick look at what the data looks like:\n\"\"\"\ndf.head(5)\n\"\"\"\nDistribution graphs (histogram\/bar graph) of sampled columns:\n\"\"\"\nplotPerColumnDistribution(df, 10, 5)\n\"\"\"\nCorrelation matrix:\n\"\"\"\nplotCorrelationMatrix(df, 8)\n\"\"\"\nScatter and density plots:\n\"\"\"\nplotScatterMatrix(df, 15, 10)\n\"\"\"\n## Conclusion\nThis concludes the starter analysis! Please \"Upvote\" the kernel if you find it useful.\n\nHappy Kaggling! \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '37d99013b24704'}"}
{"id":"33119","text":"# 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\n\"\"\"\n# **\u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u0430\u044f \u21162**\n* \u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043d\u0430 \u0441\u0430\u0439\u0442\u0435 Kaggle.com DataSet \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 csv, \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0449\u0438\u0439 \u043d\u0435 \u043c\u0435\u043d\u0435\u0435 3-\u0445 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u043e\u0432;\n* \u0421\u043e\u0437\u0434\u0430\u0442\u044c notebook \u0438 \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u043a \u043d\u0435\u043c\u0443 \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0439 DataSet.\n\"\"\"\ndata = pd.read_csv(\"\/kaggle\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv\")\ndata.rename(columns={'id':'ID','gender':'Gender','age':'Age','hypertension':'Hypertension','heart_disease':'Heart_Disease','ever_married':'Ever_Married','work_type':'Work_Type','Residence_type':'Residence_Type','avg_glucose_level':'AVG_Glucose_Level','bmi':'BMI','smoking_status':'Smoking_Status','stroke':'Stroke'},inplace=True)\ndata = data[['ID','Gender','Age','Hypertension','Heart_Disease','Ever_Married','Work_Type','Residence_Type', 'AVG_Glucose_Level', 'BMI', 'Smoking_Status', 'Stroke']]\ndata = data.sort_values('AVG_Glucose_Level',ascending = False)\ndata.head(20)\n\n\"\"\"\n# **\u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u0430\u044f \u21163**\n\u041d\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u043d\u0430 \u044f\u0437\u044b\u043a\u0435 python \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u043e\u0431\u043d\u0430\u0440\u0443\u0436\u0435\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0435\u0439 \u0432 DataSet \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438 pandas:\n* 1 \u0443\u0440\u043e\u0432\u0435\u043d\u044c \u2013 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043e\u0434\u043d\u043e\u0439 \u0424\u0417;\n* 2 \u0443\u0440\u043e\u0432\u0435\u043d\u044c \u2013 \u043f\u043e\u0438\u0441\u043a \u0432\u0441\u0435\u0445 \u0424\u0417;\n* 3 \u0443\u0440\u043e\u0432\u0435\u043d\u044c \u2013 \u043f\u043e\u0438\u0441\u043a \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0424\u0417, \u0438\u0441\u043a\u043b\u044e\u0447\u0430\u044f \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0435 \u0424\u0417 (\u0442\u0435 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043c\u043e\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0438\u0437 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445). \n\"\"\"\nfor item in data.ID.unique():\n    if len(data.Ever_Married[data.ID == item].unique()) != 1:\n        print(item)\n\"\"\"\n# **\u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u0430\u044f \u21164**\n1. \u041f\u0440\u043e\u0430\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0442\u0438\u043f\u044b \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u043e\u0432 DataSet, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0442\u0438\u043f (\u043d\u043e\u043c\u0438\u043d\u0430\u043b\u044c\u043d\u044b\u0439, \u043f\u043e\u0440\u044f\u0434\u043a\u043e\u0432\u044b\u0439, \u0434\u0438\u0441\u043a\u0440\u0435\u0442\u043d\u044b\u0439 (\u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u044c\u043d\u044b\u0439), \u043d\u0435\u043f\u0440\u0435\u0440\u044b\u0432\u043d\u044b\u0439), \u0434\u043e\u043c\u0435\u043d (\u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u043c\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439) \u0438 \u0448\u043a\u0430\u043b\u0443;\n2. \u0412\u044b\u044f\u0432\u0438\u0442\u044c \u0438 \u0443\u0441\u0442\u0440\u0430\u043d\u0438\u0442\u044c \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u0438 \u0432 DataSet (\u043d\u0435\u0430\u0442\u043e\u043c\u0430\u0440\u043d\u044b\u0435 \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u044b, \u043e\u0448\u0438\u0431\u043a\u0438 \u0432\u0432\u043e\u0434\u0430, \u0433\u0435\u0442\u0435\u0440\u043e\u0433\u0435\u043d\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 \u0432 \u0441\u0442\u043e\u043b\u0431\u0446\u0430\u0445, \u043e\u0448\u0438\u0431\u043a\u0430 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0442\u0438\u043f\u0430, \u043f\u043e\u0434\u043c\u0435\u043d\u0430 \u0441\u0443\u0449\u043d\u043e\u0441\u0442\u0435\u0439 \u044d\u043a\u0437\u0435\u043c\u043f\u043b\u044f\u0440\u0430\u043c\u0438);\n3. \u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u0439 DataSet \u0438 \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 \u043d\u0438\u043c.\n\n# \n1. \n* \u041d\u043e\u043c\u0438\u043d\u0430\u043b\u044c\u043d\u044b\u0435 - Gender, Work_Type, Residence_Type, Smoking_Status. \n* \u0418\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u044c\u043d\u044b\u0435 - Age, BMI.\n* \u041e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 ID, AVG_Glucose_Level.\n2. \n3. \n\"\"\"\nprint (data.Work_Type)\ndata['Work']=data['Work_Type']\nfor i in data['Work'].index:\n    if isinstance(data.loc[i, 'Work_Type'], str):\n        data.loc[i,'Work']=str(data.loc[i, 'Work_Type']).split('_')[0]\ndata.loc[1324]\n\"\"\"\n# **\u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u0430\u044f \u21167**\n\u041f\u043e\u0441\u0442\u0440\u043e\u0438\u0442\u044c Fact-dimensional model \u0434\u043b\u044f \u0441\u0432\u043e\u0435\u0433\u043e DataSet-\u0430, \u0432\u043a\u043b\u044e\u0447\u0430\u044f:\n* \u0424\u0430\u043a\u0442\u044b \u0438 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438;\n* \u0423\u0440\u043e\u0432\u0435\u043d\u044c \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f Grain \u0438 \u0434\u0440\u0443\u0433\u0438\u0435 \u0443\u0440\u043e\u0432\u043d\u0438 \u0438\u0435\u0440\u0430\u0440\u0445\u0438\u0447\u0435\u0441\u043a\u043e\u0433\u043e \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f (\u043f\u0440\u0438 \u043d\u0430\u043b\u0438\u0447\u0438\u0438);\n* \u0410\u0442\u0440\u0438\u0431\u0443\u0442\u044b \u0443\u0440\u043e\u0432\u043d\u0435\u0439 \u0438\u0435\u0440\u0430\u0440\u0445\u0438\u0438 \u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u044f.\n* \u041f\u043e\u0441\u0442\u0440\u043e\u0438\u0442\u044c \u0434\u043b\u044f DataSet-\u0430 \u0441\u0432\u043e\u0434\u043d\u0443\u044e \u0442\u0430\u0431\u043b\u0438\u0446\u0443 (\u043a\u0440\u043e\u0441\u0441-\u0442\u0430\u0431\u043b\u0438\u0446\u0443) \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u0438 pivot_table (\u0438\u043b\u0438 pivot) \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438 pandas, \u0433\u0434\u0435 \u0447\u0430\u0441\u0442\u044c \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0430\u0435\u0442\u0441\u044f \u0432 \u0432\u0435\u0440\u0442\u0438\u043a\u0430\u043b\u044c\u043d\u043e\u0439 \u0448\u0430\u043f\u043a\u0435, \u0430 \u0447\u0430\u0441\u0442\u044c \u0432 \u0433\u043e\u0440\u0438\u0437\u043e\u043d\u0442\u0430\u043b\u044c\u043d\u043e\u0439. \u0423\u0431\u0435\u0434\u0438\u0442\u044c\u0441\u044f, \u0447\u0442\u043e \u0441\u0432\u043e\u0434\u043d\u0430\u044f \u0442\u0430\u0431\u043b\u0438\u0446\u0430 \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0430 \u043d\u0435 \u043c\u0435\u043d\u0435\u0435 \u0447\u0435\u043c \u043d\u0430 80% \u043d\u0435\u043f\u0443\u0441\u0442\u044b\u043c\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438;\n* \u041f\u0440\u043e\u0434\u0435\u043c\u043e\u043d\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0439 Slice, Dice \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u0439 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438 pandas \u043d\u0430\u0434 \u0441\u0432\u043e\u0434\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u0435\u0439.\n\"\"\"\n\"\"\"\n![]()![\u0411\u0435\u0437 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f.png](attachment:d3df50a1-0d7f-435a-af4a-f11099ae47eb.png)\n\"\"\"\n#data.pivot_table(index='Gender', columns='Hypertension', values='ID')\n#data.pivot_table(index='Age', columns='Hypertension', values='ID')\n#data.pivot_table(index='Ever_Married', columns='Hypertension', values='ID')\nps = data.pivot_table(index='Age', columns='Gender', values='BMI')\nps\n#SLICE\n# \u041e\u0442 Female \u0434\u043e Male\nps.loc[:, 'Female':'Male']\n# \u041e\u0442 Other \u0434\u043e Male\nps.loc[:,'Male':'Other']\nps = pd.DataFrame(np.random.randn(5, 3),\n                       columns=list('Age'),\n                       index=pd.date_range('20130101', periods=5))","meta":"{'source': 'AI4Code', 'id': '3d05893a6b2a8c'}"}
{"id":"100446","text":"\"\"\"\n# Analysis of Games from the Apple Store\n\nThe dataset contains 18 columns:\n - **URL**: _URL of the app.[](http:\/\/)_\n - **ID**: _ID of the game._\n - **Name**: _Name of the game._\n - **Subtitle**: _Advertisement text of the game._\n - **Icon URL**: _Icon of the game, 512x512 pixels jpg._\n - **Average User Rating**: _Rounded to nearest .5. Requires at least 5 ratings._\n - **User Rating Count**: _Total of user ratings. Null values means it is below 5._\n - **Price**: _Price in USD._\n - **In-app Purchases**: _Prices of available in-app purchases._\n - **Description**: _Game description._\n - **Developer**: _Game developer._\n - **Age Rating**: _Age to play the game. Either 4+, 9+, 12+or 17+._\n - **Languages**: _Languages the game supports in ISO Alpha-2 codes._\n - **Size**: _Size in bytes._\n - **Genre**: _Main genre of the game._\n - **Primary Genre**: _All genre the game fits in._\n - **Original Release Date**: _Date the game was released._\n - **Current Version Release Date**: _Date of last update._\n \nThe questions we are going to answer are:\n\n    1. Does the advance in technology impact the size of the apps?\n    2. Does the advance in technology impact the amount of apps being produced?\n    3. Are most apps free or paid and which category is more popular?\n    4. Is there a better one between free or paid apps?\n    5. How is the distribution of the age restriction?\n    6. Do most games offer more than one language?\n    \n#### Below is the sequence I will be following:\n    1. Reading and Understanding the Data\n    2. Exploratory analysis\n         -> Missing data\n         -> Data types in the dataframe\n         -> Sorting by a desired column\n         -> Saving a new file after this job is done\n    3. Graphics and insights\n    \n## Important note\n > **This notebook is intended exclusively to practicing and learning purposes. Any corrections, comments and suggestions are more than welcome and I would really appreciate it. Feel free to get in touch if you liked it or if you want to colaborate somehow.**\n\"\"\"\n# 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 in \n\n# Important imports for the analysis of the dataset\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n# Create the dataframe and check the first 8 rows\napp_df = pd.read_csv(\"\/kaggle\/input\/17k-apple-app-store-strategy-games\/appstore_games.csv\")\napp_df.head(8)\n# Dropping columns that I will not use for this analysis\napp_df_cut = app_df.drop(columns=['URL', 'Subtitle', 'Icon URL'])\n\"\"\"\n# 2. Exploratory Analysis\n\"\"\"\napp_df_cut.info()\n\"\"\"\n***\n\nFrom the above cell I understand that I should take a closer look into the columns listed below because they have some missing values:\n - Average User Rating\n - User Rating Count\n - Price\n - Languages\n \nAnother important thing to check is if there are any **duplicate ID's** and, if so, remove them. Also, the last two column are not *datetime* type, which they should be.\n\nThe dataframe will be sorted by the \"User Rating Count\" column. This column will be our guide to conclude if a game is successful or not.\n\"\"\"\n# Most reviewed app\n#app_df_cut.iloc[app_df_cut[\"User Rating Count\"].idxmax()]\n\n# A better way of seeing the most reviwed apps \napp_df_cut = app_df_cut.sort_values(by=\"User Rating Count\", ascending=False)\napp_df_cut.head(5)\n\"\"\"\n### Rating columns\n> I'm going to consider that all the NaN values in the \"User Rating Count\" column means that the game recieved no ratings and therefore is 0. If the app recieved no ratings, then the \"Average User Rating\" will also be zero for these games.\n\"\"\"\n# Get the columns \"User Rating Count\" and \"Average User Rating\" where they are both equal to NaN and set the\n# values to 0.\napp_df_cut.loc[(app_df_cut[\"User Rating Count\"].isnull()) | (app_df_cut[\"Average User Rating\"].isnull()),\n               [\"Average User Rating\", \"User Rating Count\"]] = 0\n# Check if there are any other missing values in those columns\napp_df_cut.loc[(app_df_cut[\"User Rating Count\"].isnull()) | (app_df_cut[\"Average User Rating\"].isnull())]\n\"\"\"\n### In-app Purchases column\n> I'm considering that the null values within the \"In-app Purchases\" column means that there are no in-app purchases available\n\n**Different considerations could have been done, but I will continue with this one for now.**\n\"\"\"\n# Get the column \"In-app Purchases\" where the value is NaN and set it to zero\napp_df_cut.loc[app_df_cut[\"In-app Purchases\"].isnull(),\n               \"In-app Purchases\"] = 0\n# Check if there are any NaN value in the \"In-app Purchases\" column\napp_df_cut.loc[app_df_cut[\"In-app Purchases\"].isnull()]\n\"\"\"\n### ID column\n> Let's check if there are missing or duplicate ID's in the dataset:\n\"\"\"\n# Check if there are missing or 0 ID's\napp_df_cut.loc[(app_df_cut[\"ID\"] == 0) | (app_df_cut[\"ID\"].isnull()),\n              \"ID\"]\n# Check for duplicates in the ID column\nlen(app_df_cut[\"ID\"]) - len(app_df_cut[\"ID\"].unique())\n\n# The number of unique values is lower than the total amount of ID's, therefore there are duplicates among them.\n# Drop every duplicate ID row\napp_df_cut.drop_duplicates(subset=\"ID\", inplace=True)\napp_df_cut.shape\n\"\"\"\n### Size column\n> I will check if there are any missing or 0 values in the size column. If so, they will be removed from the data since we cannot know it's value.\n\"\"\"\n# Check if there are null values in the Size column\napp_df_cut[(app_df_cut[\"Size\"].isnull()) | (app_df_cut['Size'] == 0)]\n# Drop the only row in which the game has no size\napp_df_cut.drop([16782], axis=0, inplace=True)\n# Convert the size to MB\napp_df_cut[\"Size\"] = round(app_df_cut[\"Size\"]\/1000000)\napp_df_cut.head(5)\n\"\"\"\n### Price column\n   > Games with a missing value in the price column will be dropped\n\"\"\"\n# Drop the row with NaN values in the \"Price\" column\napp_df_cut = app_df_cut.drop(app_df_cut.loc[app_df_cut[\"Price\"].isnull()].index)\n# Check if there are any null values on the price column\napp_df_cut.loc[app_df_cut[\"Price\"].isnull()]\n\"\"\"\n### Languages column\n> Games with a missing value in the \"Languages\" column will be dropped\n\"\"\"\n# Drop the rows with NaN values in the \"Languages\" column\napp_df_cut = app_df_cut.drop(app_df_cut.loc[app_df_cut[\"Languages\"].isnull()].index)\n# Check if there are any null values on the \"Languages\" column\napp_df_cut.loc[app_df_cut[\"Languages\"].isnull()]\napp_df_cut.info()\n\"\"\"\n### Now that the dataset is organized, let's save it into a csv file so that we do not have to redo all the steps above\n\"\"\"\napp_df_cut.to_csv(\"app_df_clean.csv\", index=False)\napp_df_clean = pd.read_csv(\"app_df_clean.csv\")\napp_df_clean.head()\n# Transform the the string dates into datetime objects\napp_df_clean[\"Original Release Date\"] = pd.to_datetime(app_df_clean[\"Original Release Date\"])\napp_df_clean[\"Current Version Release Date\"] = pd.to_datetime(app_df_clean[\"Current Version Release Date\"])\napp_df_clean.info()\n\"\"\"\n# 3. Graphics and Insights\n\"\"\"\n\"\"\"\n### Evolution of the Apps' Size\n> Do the apps get bigger with time?\n\"\"\"\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Variables\nyears = app_df_clean[\"Original Release Date\"].apply(lambda date: date.year)\nsize = app_df_clean[\"Size\"]\n\n# Plot a swarmplot\npalette = sns.color_palette(\"muted\")\nsize = sns.swarmplot(x=years, y=size, palette=palette)\nsize.set_ylabel(\"Size (in MB)\", fontsize=16)\nsize.set_xlabel(\"Original Release Date\", fontsize=16)\nsize.set_title(\"Time Evolution of the Apps' Sizes\", fontsize=20)\nplt.show()\n\"\"\"\n> **With the advance in technology and the internet becoming cheaper and cheaper more people have access to faster networks. As the years go by, it can be seen in the graph above that the games' size get bigger. Some games that have more than 2GB can be noted, reaching a maximum value of 4GB, but they are not the most common ones. As each game is represented by a different tiny ball in the graph above, the quantity of games seems to grow as well. Let's investigate the amount of apps per year to be sure.**\n\"\"\"\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Plot a countplot\npalette1 = sns.color_palette(\"inferno_r\")\napps_per_year = sns.countplot(x=years, data=app_df_clean, palette=palette1)\napps_per_year.set_xlabel(\"Year of Release\", fontsize=16)\napps_per_year.set_ylabel(\"Amount\", fontsize=16)\napps_per_year.set_title(\"Quantity of Apps per Year\", fontsize=20)\n\n# Write the height of each bar on top of them\nfor p in apps_per_year.patches:\n    apps_per_year.annotate(\"{}\".format(p.get_height()),\n                          (p.get_x() + p.get_width() \/ 2, p.get_height() + 40),\n                          va=\"center\", ha=\"center\", fontsize=16)\n\"\"\"\n> **From 2008 to 2016 we can identify a drastic increase in the amount of games released each year in which the highest increase occurs between the years of 2015 and 2016. After 2016 the amount of games released per year starts to drop down almost linearly for 2 years (2019 cannot be considered yet because the data was collected in August, 4 months of data of the current year is missing).**\n>\n> **Without further analysis, I would argue that after a boom in the production of apps it gets harder to come up with new ideas that are not out there yet, making the production and release of new games slow down, but it is important to keep in mind that without further research it cannot be taken as the right explanation.**\n\"\"\"\n#Make a list of years from 2014 to 2018\nyears_lst = [year for year in range(2014,2019)]\n\n#For loop to get a picture of the amount of games produced from August to December\nfor year in years_lst:\n    from_August = app_df_clean[\"Original Release Date\"].apply(lambda date: (date.year == year) & (date.month >= 8)).sum()\n    total = app_df_clean[\"Original Release Date\"].apply(lambda date: date.year == year).sum()\n    print(\"In {year}, {percentage}% games were produced from August to December.\"\n          .format(year=year,\n                  percentage=round((from_August\/total)*100, 1)))\n\"\"\"\n> **Having checked the previous five years we can see that the amount of games released from August to December represents a significant portion of the whole and that it can be considered roughly constant at 42%. Nevertheless, the last two years show a tendency for a linear decrease in the quantity of games released per year and taking into account that we still have 42% of the games of this year to be released, the total amount in the present year (2019) would be 2617. This is bigger than 2018, but this was not an elaborate calculation as we took the average of games being prouced between the months 8-12 to be 42%.**\n\"\"\"\n\"\"\"\n### The amount of apps had a considerable increase in the past years indicating that producing an app has been a trend and possibly a lucrative market. That being said, it is important to analyse if there is a preference for free or paid games and the range of prices they are in.\n\"\"\"\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Variables\nprice = app_df_clean[\"Price\"]\n\n# Plot a Countplot\npalette2 = sns.light_palette(\"green\", reverse=True)\nprice_vis = sns.countplot(x=price, palette=palette2)\nprice_vis.set_xlabel(\"Price (in US dollars)\", fontsize=16)\nprice_vis.set_xticklabels(price_vis.get_xticklabels(), fontsize=12, rotation=45)\nprice_vis.set_ylabel(\"Amount\", fontsize=16)\nprice_vis.set_title(\"Quantity of Each App per Price\", fontsize=20)\n\n# Write the height of the bars on top\nfor p in price_vis.patches:\n    price_vis.annotate(\"{:.0f}\".format(p.get_height()), # Text that will appear on the screen\n                       (p.get_x() + p.get_width() \/ 2 + 0.1, p.get_height()), # (x, y) has to be a tuple\n                       ha='center', va='center', fontsize=14, color='black', xytext=(0, 10), # Customizations\n                       textcoords='offset points')\n\"\"\"\n> **We can see that the majority of the games are free. That leads me to analyse if the free apps have more in-app purchases then the paid ones, meaning that this might be their source of income.**\n\"\"\"\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Variables\nin_app_purchases = app_df_clean[\"In-app Purchases\"].str.split(\",\").apply(lambda lst: len(lst))\n\n# Plot a stripplot\npalette3 = sns.color_palette(\"BuGn_r\", 23)\nin_app_purchases_vis = sns.stripplot(x=price, y=in_app_purchases, palette=palette3)\nin_app_purchases_vis.set_xlabel(\"Game Price (in US dollars)\", fontsize=16)\nin_app_purchases_vis.set_xticklabels(in_app_purchases_vis.get_xticklabels(), fontsize=12, rotation=45)\nin_app_purchases_vis.set_ylabel(\"In-app Purchases Available\", fontsize=16)\nin_app_purchases_vis.set_title(\"Quantity of In-app Purchases per Game Price\", fontsize=20)\nplt.show()\n\"\"\"\n> **As expected, free and lower priced apps provide more items to be purchased and a wider range of in-app prices than expensive games. Two reasons can be named:**\n>\n>> **1.The developers have to invest money into making the games and updating them, therefore they need a source of income. In the case of free games this comes with the in-app purchases available.**\n>\n>> **2. People who have spent a lot of money on an app would not be happy or willing to spend more, given that they have already made an initial high investment.**\n\"\"\"\n\"\"\"\n### We know that most of the apps are free. Let's see if there are any links between an app being paid and being better than the free ones:\n\"\"\"\n# Plot a distribution of the top 200 apps by their price\n\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Plot a Countplot\npalette4 = sns.color_palette(\"BuPu_r\")\ntop_prices = sns.countplot(app_df_clean.iloc[:200][\"Price\"], palette=palette4)\ntop_prices.set_xlabel(\"Price (in US dollars)\", fontsize=16)\ntop_prices.set_xticklabels(top_prices.get_xticklabels(), fontsize=12)\ntop_prices.set_ylabel(\"Amount\", fontsize=16)\ntop_prices.set_title(\"Quantity of Each App per Price\", fontsize=20)\n\n# Write the height of the bars on top\nfor p in top_prices.patches:\n    top_prices.annotate(\"{:.0f}\".format(p.get_height()), \n                        (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                        ha='center', va='center', fontsize=14, color='black', xytext=(0, 8),\n                        textcoords='offset points')\n\"\"\"\n> **The graph above shows that among the top 200 games the vast majority are free ones. This result makes sense considering you don't have to invest any money to start playing and can spend afterwards if you would like to invest in it.**\n\"\"\"\n\"\"\"\n### Even though most games are free we should take a look if a type of app (paid or free) is better. Let's do that by checking the average user rating.\n\"\"\"\n# Create the DataFrames needed\npaid = app_df_clean[app_df_clean[\"Price\"] > 0]\ntotal_paid = len(paid)\nfree = app_df_clean[app_df_clean[\"Price\"] == 0]\ntotal_free = len(free)\n\n# Make the figure and the axes (1 row, 2 columns)\nfig, axes = plt.subplots(1, 2, figsize=(16,10))\n\n# Free apps countplot\nfree_vis = sns.countplot(x=\"Average User Rating\", data=free, ax=axes[0])\nfree_vis.set_xlabel(\"Average User Rating\", fontsize=16)\nfree_vis.set_ylabel(\"Amount\", fontsize=16)\nfree_vis.set_title(\"Free Apps\", fontsize=20)\n\n# Display the percentages on top of the bars\nfor p in free_vis.patches:\n     free_vis.annotate(\"{:.1f}%\".format(100 * (p.get_height()\/total_free)),\n                       (p.get_x() + p.get_width() \/ 2 + 0.1, p.get_height()),\n                        ha='center', va='center', fontsize=14, color='black', xytext=(0, 8),\n                        textcoords='offset points')\n    \n# Paid apps countplot\npaid_vis = sns.countplot(x=\"Average User Rating\", data=paid, ax=axes[1])\npaid_vis.set_xlabel(\"Average User Rating\", fontsize=16)\npaid_vis.set_ylabel(\" \", fontsize=16)\npaid_vis.set_title(\"Paid Apps\", fontsize=20)\n\n# Display the percentages on top of the bars\nfor p in paid_vis.patches:\n    paid_vis.annotate(\"{:.1f}%\".format(100 * (p.get_height()\/total_paid)),\n                      (p.get_x() + p.get_width() \/ 2 + 0.1, p.get_height()),\n                       ha='center', va='center', fontsize=14, color='black', xytext=(0, 8),\n                       textcoords='offset points')\n\"\"\"\n> **There is no indications to whether a paid or a free game is better. Actually, the pattern of user ratings are pretty much equal for both type of games. The graph above shows that both categories seems to deliver a good service and mostly satisfy their costumers as most of the rating are between 4-5 stars. We can also identify that the majority of the users do not rate the games.**\n\"\"\"\n\"\"\"\n# Age Rating\n> Is there a preference for permitted age to the games?\n\"\"\"\n# Make the figure\nplt.figure(figsize=(16,10))\n\n# Make a countplot\npalette5 = sns.color_palette(\"BuGn_r\")\nage_vis = sns.countplot(x=app_df_clean[\"Age Rating\"], order=[\"4+\", \"9+\", \"12+\", \"17+\"], palette=palette5)\nage_vis.set_xlabel(\"Age Rating\", fontsize=16)\nage_vis.set_ylabel(\"Amount\", fontsize=16)\nage_vis.set_title(\"Amount of Games per Age Restriction\", fontsize=20)\n\n# Write the height of the bars on top\nfor p in age_vis.patches:\n    age_vis.annotate(\"{:.0f}\".format(p.get_height()), \n                        (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                        ha='center', va='center', fontsize=14, color='black', xytext=(0, 8),\n                        textcoords='offset points')\n\"\"\"\n> **Most of the apps are in the +4 age category, which can be translated as \"everyone can play\". This ensures that the developers are targeting a much broader audience with their games.**\n\"\"\"\n\"\"\"\n# Languages\n> Do most games have various choices of languages?\n\"\"\"\n# Create a new column that contains the amount of languages that app has available\napp_df_clean[\"numLang\"] = app_df_clean[\"Languages\"].apply(lambda x: len(x.split(\",\")))\n#Make the figure\nplt.figure(figsize=(16,10))\n\n#Variables\nlang = app_df_clean.loc[app_df_clean[\"numLang\"] <= 25, \"numLang\"]\n\n#Plot a countplot\npalette6 = sns.color_palette(\"PuBuGn_r\")\nnumLang_vis = sns.countplot(x=lang, data=app_df_clean, palette=palette6)\nnumLang_vis.set_xlabel(\"Quantity of Languages\", fontsize=16)\nnumLang_vis.set_ylabel(\"Amount of Games\", fontsize=16)\nnumLang_vis.set_title(\"Quantity of Languages Available per Game\", fontsize=20)\n\n# Write the height of the bars on top\nfor p in numLang_vis.patches:\n    numLang_vis.annotate(\"{:.0f}\".format(p.get_height()), \n                        (p.get_x() + p.get_width() \/ 2. + .1, p.get_height()),\n                        ha='center', va='center', fontsize=12, color='black', xytext=(0, 12),\n                        textcoords='offset points')\n#Amount of games that have only the English language\nlen(app_df_clean[(app_df_clean[\"numLang\"] == 1) & (app_df_clean[\"Languages\"] == \"EN\")])\n#Amount of games that have only one language and is not English\nlen(app_df_clean[(app_df_clean[\"numLang\"] == 1) & (app_df_clean[\"Languages\"] != \"EN\")])\n\"\"\"\n> **The vast majority of the games - 12.431 - have only one language available and more than 99% of these use the English language. After that there is a huge drop and only 1089 games have two languages available. Note that not all the data is shown in the graph above, but games with more than 25 languages were left out and they don't represent a huge number overall. It is interesting to point out that there is a strange increase in the number of games with 16 languages and then another one when we reach 25 languages. The explanation to that is unknown and it will not be investigated in this notebook.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b892f6377cf56c'}"}
{"id":"75479","text":"\"\"\"\n# Libraries importing and configuration\n\"\"\"\n# 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)\nimport seaborn as sns\nfrom sklearn.impute import KNNImputer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nfrom scipy import stats\nimport matplotlib.pyplot as plt\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\ntrain_data = pd.read_csv('..\/input\/titanic\/train.csv')\ntest_data = pd.read_csv('..\/input\/titanic\/test.csv')\n\ntrain_data.head()\n\"\"\"\n# Removing irrelevant features\n\"\"\"\n\"\"\"\nFor the classification models predictions some features will not give useful information, so we'll be removing the features 'PassengerId' and 'Name' that arent relevant information to know if a passenger survived or not.\n\"\"\"\ndel train_data['Name']\ndel train_data['PassengerId']\n\"\"\"\n# Handling missing data I\n\"\"\"\ntrain_data.isna().sum()\n\"\"\"\nAs the feature Embarked has a small number of missing data, we can remove the rows containing them.\n\"\"\"\ntrain_data = train_data[train_data[\"Embarked\"].notna()]\n\"\"\"\n# Textual data encoding\n\"\"\"\n\"\"\"\nMost of the available machine learning algorithms can't handle textual data, so we'll be transforming them into numercical data.\n\nFirst we'll see how many unique values each of the textual features has to see the right encoding for each of them. If we aren't careful with the encoding, the model can suffer from the curse of dimensionality or it'll learn the features in the wrong way.\n\"\"\"\nfor col in train_data.columns:\n    print(col+\": \",len(pd.unique(train_data[col])), \" (\"+str(train_data[col].dtype)+\")\")\n\"\"\"\nAs can be seen, some of the features would lead to high dimensional data if we applied the one hot encoding. So, we'll apply the Ordinal encoding for the ticket and cabin features.\n\"\"\"\ntrain_data['Cabin'][train_data['Cabin'].isna()] = 'NaN'\nord_enc = OrdinalEncoder()\nord_enc = ord_enc.fit(train_data[['Ticket', 'Cabin']])\ntrain_data[['Ticket', 'Cabin']] = ord_enc.transform(train_data[['Ticket', 'Cabin']])\n\"\"\"\nFor the embarked and sex features we'll be using one hot encoding because the problem with the ordinal encoding is that the model could learn a order relationship between the values, and as we know, there isn't this kind of relation on these features values.\n\"\"\"\ntrain_data = pd.get_dummies(train_data, columns=['Sex', 'Embarked'])\ntrain_data.head()\n\"\"\"\n# Handling missing data II\n\"\"\"\n\"\"\"\nFor the rest, we'll be using the kNN imputer to fill the missing data.\n\"\"\"\nknn_imputer = KNNImputer(n_neighbors=5)\ntrain_data = pd.DataFrame(knn_imputer.fit_transform(train_data), columns=train_data.columns)\ntrain_data.head()\ntrain_data.isna().sum()\n\"\"\"\n# Checking for outliers\n\"\"\"\n\"\"\"\nOne way to check if a attribute has outliers is to check the statistical summary of the data. If the feature has a high discrepance between the mean and the median, its likely that it has outliers.\n\"\"\"\ntrain_data.describe()\ntrain_data.median()\n\"\"\"\nAs can be seen, only the fare feature has a significant difference between the mean and median, so we'll be removing all rows where the fare is higher than 2.4 standard deviations. \n\"\"\"\ntrain_data = train_data[(np.abs(stats.zscore(train_data['Fare'])) < 2.4)]\ntrain_data.describe()\n\"\"\"\n# Feature scaling\n\nFor a lot of machine learning algorithms is important for the data to have the same scale, so we'll be applying the MinMax encoding on the features with high variance.\n\"\"\"\nvariance = np.var(train_data)\nprint(variance)\nhighvar_cols = [col for col in train_data.columns if variance[col] > 2]\nprint(highvar_cols)\ntrain_data_scaled = train_data.copy()\nminmax_scal = MinMaxScaler(feature_range=(0.0,1.0))\nminmax_scal = minmax_scal.fit(train_data_scaled[highvar_cols])\ntrain_data_scaled[highvar_cols] = minmax_scal.transform(train_data_scaled[highvar_cols])\ntrain_data_scaled.head()\n\"\"\"\n# Correlation analysis\n\nAs we can see above, there are no features with high correlation.\n\"\"\"\nsns.pairplot(train_data_scaled)\nplt.show()\ntrain_data_scaled.corr()\nplt.figure(figsize=(12,8))\nsns.heatmap(train_data_scaled.corr())\nplt.show()\ndef preprocess_titanic(data):\n    from sklearn.impute import KNNImputer\n    from sklearn.preprocessing import OrdinalEncoder\n    from sklearn.preprocessing import MinMaxScaler\n    from scipy import stats\n    \n    del data['Name']\n    del data['PassengerId']\n    \n    data = data[data[\"Embarked\"].notna()]\n    data['Cabin'][data['Cabin'].isna()] = 'NaN'\n    \n    ord_enc = OrdinalEncoder()\n    ord_enc = ord_enc.fit(data[['Ticket', 'Cabin']])\n    data[['Ticket', 'Cabin']] = ord_enc.transform(data[['Ticket', 'Cabin']])\n    \n    data = pd.get_dummies(data, columns=['Sex', 'Embarked'])\n    \n    knn_imputer = KNNImputer(n_neighbors=5)\n    data = pd.DataFrame(knn_imputer.fit_transform(data), columns=data.columns)\n    \n    data = data[(np.abs(stats.zscore(data['Fare'])) < 2.4)]\n    \n    variance = np.var(data)\n    highvar_cols = [col for col in data.columns if variance[col] > 2]\n\n    minmax_scal = MinMaxScaler(feature_range=(0.0,1.0))\n    minmax_scal = minmax_scal.fit(data[highvar_cols])\n    data[highvar_cols] = minmax_scal.transform(data[highvar_cols])\n    return data\nteste = pd.read_csv('..\/input\/titanic\/train.csv')\nteste = preprocess_titanic(teste)\nteste.head()\ntrain_data_scaled.head()","meta":"{'source': 'AI4Code', 'id': '8ab7629f45b549'}"}
{"id":"28945","text":"\"\"\"\n# **Faster Semantic Search over BERT embeddings using Faiss**\nRecently I was experimenting with COVID-19 dataset using BERT. I generated BERT embeddings and later used those embeddings for semantic search. I found out that the semantic search using traditional methods were very slow , especially for larger datasets like COVID-19 Open-Research data which has 44k+ papers. Here is a method to fasten up semantic search process using FAISS. \n\nIn this notebook, I will create embeddings from scratch and later build-up an index using FAISS.\n\n1, Install the requirements\n\"\"\"\n!pip install transformers\n!pip install faiss-gpu\n\"\"\"\nWe will use Sci-BERT to generate embeddings over COVID-19 paper titles, we can also build embeddings for abstract and contents. For this demonstration we will consider only titles of the articles, we will encode all the titles. (All 44k). First, download Sci-BERT model.\n\"\"\"\n!wget https:\/\/s3-us-west-2.amazonaws.com\/ai2-s2-research\/scibert\/huggingface_pytorch\/scibert_scivocab_uncased.tar -O scibert.tar\n! tar -xvf scibert.tar\n!pip install sentence-transformers\n\"\"\"\n Now, we import all the libraries and create a transformer pytorch model. We will load the model on GPU. You can remove `sciBert.cuda()` in case you don't want to use a GPU. \n\"\"\"\nimport torch\nimport transformers\nimport numpy as np \nimport pandas as pd\n\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n#globals \nMODEL = 'scibert_scivocab_uncased'\n\n#load the model\nsciBert = transformers.BertModel.from_pretrained(MODEL)\n\n#create a transformer tokenizer for BERT\ntokenizer = transformers.BertTokenizer.from_pretrained(MODEL, do_lower_case=True)\n\nprint(type(sciBert))\n\nsciBert.eval()\nsciBert.cuda(0)\n\"\"\"\nNext we define some important functions that will help us in generating the embeddings. These functions will be used throughout the notebook. `Use embedding_fn_cpu` if not using GPU.\n\"\"\"\ndef embedding_fn(model, text) :\n\n  if not isinstance(model, transformers.modeling_bert.BertModel) :\n    print('Model must be of type transformers.modeling_bert.BertModel, but got ', type(model))\n    return\n\n  with torch.no_grad():\n    #generate tokens :\n    tokens = tokenizer.encode(text)\n    #expand dims : \n    batch_tokens = np.expand_dims(tokens, axis = 0)\n    batch_tokens = torch.tensor(batch_tokens).cuda()\n    #print(type(batch_tokens))\n    #generate embedding and return hidden_state : \n    return model(batch_tokens)[0].cpu()\n\ndef embedding_fn_cpu(model, text) :\n\n  if not isinstance(model, transformers.modeling_bert.BertModel) :\n    print('Model must be of type transformers.modeling_bert.BertModel, but got ', type(model))\n    return\n\n  with torch.no_grad():\n    #generate tokens :\n    tokens = tokenizer.encode(text, max_length = 512)\n    #expand dims : \n    batch_tokens = np.expand_dims(tokens, axis = 0)\n    batch_tokens = torch.tensor(batch_tokens)\n    #print(type(batch_tokens))\n    #generate embedding and return hidden_state : \n    return model(batch_tokens)[0]\n\ndef compute_mean(embedding):\n\n  if not isinstance(embedding, torch.Tensor):\n    print('Embedding must be a torch.Tensor')\n    return \n  \n  return embedding.mean(1)\n\n\ndef compute_cosine_measure(x1, x2):\n\n  #given two points in vector space, measure cosine distance\n  return cosine_similarity(x1, x2)\n\n\ndef compute_distance(x1, x2):\n  #replace this with your own measure\n  return compute_cosine_measure(x1.detach().numpy(), x2.detach().numpy())\n\"\"\"\nThe actual information is in CSV format, present in `metadata.csv`, we will build an index that contains information we need, we can use this index to present the human-readable information. Add the dataset to the notebook if you haven't added yet. It will be loaded in the following path, it is a read-only mount.\n\"\"\"\n!ls \/kaggle\/input\/CORD-19-research-challenge\n\"\"\"\n### Download pre-grenerated embeddings for Titles :\nFor easy demo, I have already uploaded pre-generated CORD-19 title embeddings. You can get it from here : [CORD-19 title embeddings](https:\/\/www.kaggle.com\/narasimha1997\/cord-19-title-embeddings)\n\"\"\"\ndataset = pd.read_csv('\/kaggle\/input\/CORD-19-research-challenge\/metadata.csv')\n\n\nimport json\n\n#We generate Index File and of key-value pair , each dict has 2 values : cord_uid and title. This we save in a separate CSV file\ndef generate_mapping_index(dataframe):\n\n  index_map = {}\n\n  for index, row in dataframe.iterrows():\n    index_map[index] = {\n        \"cord_uid\" : row['cord_uid'],\n        \"title\" : row['title'],\n        \"abstract\" : row['abstract'],\n        \"url\" : row['url']\n    }\n  \n  return index_map\n\n\nindex_map = generate_mapping_index(dataset)\nopen('index.json', 'w').write(json.dumps(index_map))\ndataset.head()\n\"\"\"\n  We are interested only in `cord_uid` , `title` , `abstract` and `url`, we will present these fileds upon search completion. I have dumped the `index.json` file for later use. I have prepared the code to process data as chunks, If you want to save numpy gz arrays as chunks, you can reduce the CHUNK_SIZE_EACH to a lesser value, The simple logic below will split the dataframe, embed them individually and save them as chunks, now I am creating a single big chunk of 44k records. Embeddings are generated by GPU. Skip this step if you have downloaded pre-generated embeddings.\n\"\"\"\nCHUNK_SIZE_EACH = 44000\n\n\n\ndef __embedding(text):\n  return compute_mean(embedding_fn(sciBert, text))\n\n\n\ndef compute_bert_embeddings(dataframe_chunk, current_index, end_marker):\n\n  np_chunk = __embedding(dataframe_chunk.loc[current_index * end_marker]['title']).detach().numpy()\n  #np_chunk = np_chunk.reshape(np_chunk.shape[1])\n\n  for idx in range(1, end_marker):\n\n    try:\n      embedding = __embedding(dataframe_chunk.loc[(current_index * end_marker) + idx]['title']).detach().numpy()\n      #embedding = embedding.reshape(embedding.shape[1])\n      np_chunk = np.append(np_chunk, embedding, axis = 0)\n      print('\\r {}'.format(np_chunk.shape), end = '')\n    except Exception as e:\n      print(e)\n      np_chunk = np.append(np_chunk, np.zeros(shape = (1, 768)), axis = 0)\n      continue \n\n  print(np_chunk.shape)\n  np.savez_compressed('title_{}'.format(current_index), a = np_chunk)\n\n\ndef compute_embeddings_and_save(dataframe):\n\n  n_rows = len(dataframe)\n  \n  chunk_sizes = n_rows \/\/ CHUNK_SIZE_EACH\n  remaining = n_rows - chunk_sizes * CHUNK_SIZE_EACH\n\n  for i in range(1):\n\n    compute_bert_embeddings(dataframe[i * CHUNK_SIZE_EACH : (i * CHUNK_SIZE_EACH) + CHUNK_SIZE_EACH ], i, CHUNK_SIZE_EACH)\n\n\n#Un-comment this if you want to regenerate embeddings.\n#compute_embeddings_and_save(dataset)\n\n\"\"\"\nThis will generate embeddings for COVID-19 article titles, These embeddings can be used for semantic search. In simple words, BERT is like a hash-mapping function. It maps arbitrary length sentences ( presented as tokens ) to fixed-length word-vectors, These word-vectors are n-dimensional numerical values. These word-vectors contain enough information to semantically present the given sentence. How BERT was able to generate this? It was able to do so because it has developed a language model of the data it was trained on. How it developed the language model is quite complex and is outside the scope of the notebook, You can refer to BERT research paper to understand more. The above code will handle NaN values implicitly, so no need of data-cleaning to remove NaNs. The dataset has atleast 100 titles missing from the CSV file, those are ignored. Now, let us verifiy the npz file.\n\"\"\"\n!ls\n\"\"\"\n`title_0.npz` is generated. We will load and verifiy its dimension.\n\"\"\"\nembeddings = np.load('\/kaggle\/input\/cord-19-title-embeddings\/title_0.npz')['a']\nembeddings.shape\n\"\"\"\n`embeddings` is a vector of (40000, 768) dimensions, this is our look-up vector, Now we will examine various ways of performing semantic search.\n\"\"\"\n\"\"\"\n**Method -1 : Normal Brute-force search using cosine-distance measure**\nWe will do a normal brute-force cosine-distance calculation and display top 20 matches.\n\"\"\"\nimport time\n\n#print(index_map.keys())\ndef index_to_title(indexes):\n    \n    for i, idx in enumerate(indexes) :\n        print('{}. {}'.format(i, index_map[idx]['title']))\n\ndef do_consine_search(embeddings, query_text, model, top_k):\n    \n    n_embeddings = embeddings.shape[0]\n    \n    embedding_q = compute_mean(embedding_fn(sciBert, query_text)).detach().numpy()\n    \n    #lets do the search and time the process\n    st = time.time()\n    distances = []\n    for em in embeddings :\n        \n        em = np.expand_dims(em, axis = 0)\n        distances.append(compute_cosine_measure(em, embedding_q)[0][0])\n        \n    top_k_arguments = np.argsort(np.array(distances))[::-1][:top_k]\n    et = time.time()\n    \n    return et - st, top_k_arguments\n\n    \ntime_cosine, indexes_top = do_consine_search(embeddings, \"Middle East Virus\", sciBert, 20)\nprint('Cosine search time :  ', time_cosine, ' seconds')\n\nindex_to_title(indexes_top)\n        \n\"\"\"\nWe got good results from the cosine search over embeddings, Sci-BERT model was able to provide us some satisfactory level of accuracy eventhough it was not fine-tuned with COVID-19 text corpus.\n\"\"\"\n\"\"\"\n### Improving search speed and efficiency with FAISS \nCosine Metric search was good enough but it took 11 seconds to provide search results. We can speed it up in many ways, one way is to do batch cosine-distance calculation but still it takes some time. I found this library from facebook, which could do semantic search efficiently with great speed. It builds an index in RAM and uses that index to perform lookups. \nlet's see how to build an index \n\"\"\"\nimport faiss\n\"\"\"\nBuild the index\n\"\"\"\nn_dimensions = embeddings.shape[1] #Number of dimensions (764)\n\nfastIndex = faiss.IndexFlatL2(n_dimensions) # We will create an index of type FlatL2, there are many kinds of indexes, you can look at it in their repo.\nfastIndex.add(embeddings.astype('float32')) # Add the embedding vector to faiss index, it should of dtype 'float32'\n\"\"\"\nNow we have built  the index, we can perform lookup efficiently.\n\"\"\"\ndef do_faiss_lookup(fastIndex, query_text, model, top_k):\n    n_embeddings = embeddings.shape[0]\n    embedding_q = compute_mean(embedding_fn(sciBert, query_text)).detach().numpy()\n    \n    #let it be float32\n    embedding_q = embedding_q.astype('float32')\n    \n    #perform the search\n    st = time.time()\n    matched_em, matched_indexes = fastIndex.search(embedding_q, top_k) # it returns matched vectors and thier respective indexes, we are interested only in indexes.\n    \n    #indexes are already sorted wrt to closest match\n    et = time.time()\n    \n    return et - st, matched_indexes[0]\n\ntime_faiss_cpu, indexes_top_faiss = do_faiss_lookup(fastIndex, \"Middle East Virus\", sciBert, 20)\nprint('Faiss index lookup time :  ', time_faiss_cpu, ' seconds')\n\nindex_to_title(indexes_top_faiss)\n\n\n    \n\"\"\"\nHurray! We have completed Faiss index lookup, it can be noted that results are same as cosine-search , however it took us only **40 milliseconds**, almost 370x speedup. Faiss also supports GPU computations, so we can even build an index on GPU and use GPU cores for computation.\n\n### FAISS on GPU\n\nLet's try to build same thing on GPU. We need to install faiss-gpu\n\"\"\"\nimport faiss\n\nn_dimensions = embeddings.shape[1] #Number of dimensions (764)\n\nfastIndex_gpu = faiss.IndexFlatL2(n_dimensions) # We will create an index of type FlatL2, there are many kinds of indexes, you can look at it in their repo.\n\n#copy the index to GPU \nres = faiss.StandardGpuResources()\n\nfastIndex_gpu = faiss.index_cpu_to_gpu(res, 0, fastIndex_gpu)\n\nfastIndex_gpu.add(embeddings.astype('float32')) # Add the embedding vector to faiss index, it should of dtype 'float32'\n\"\"\"\nCreating a GPU index will take soem time. Wait for it. Now you can do search similar to CPU.\n\"\"\"\ndef do_faiss_lookup_gpu(fastIndex, query_text, model, top_k):\n    n_embeddings = embeddings.shape[0]\n    embedding_q = compute_mean(embedding_fn(sciBert, query_text)).detach().numpy()\n    \n    #let it be float32\n    embedding_q = embedding_q.astype('float32')\n    \n    #perform the search\n    st = time.time()\n    matched_em, matched_indexes = fastIndex.search(embedding_q, top_k) # it returns matched vectors and thier respective indexes, we are interested only in indexes.\n    \n    #indexes are already sorted wrt to closest match\n    et = time.time()\n    \n    return et - st, matched_indexes[0]\n\ntime_faiss_gpu, indexes_top_faiss = do_faiss_lookup_gpu(fastIndex, \"Middle East Virus\", sciBert, 20)\nprint('Faiss index lookup time :  ', time_faiss_gpu, ' seconds')\n\nindex_to_title(indexes_top_faiss)\n\n\"\"\"\nThe GPU lookup tool **33ms** which is almost same as CPU based look-up.\nNow let us conclude the time of all three experiments :\n\n\"\"\"\nprint('CPU based cosine-distance metric lookup : (Brute-force method : )', time_cosine)\nprint('CPU based FAISS index lookup : ', time_faiss_cpu)\nprint('GPU based FAISS index lookup : ', time_faiss_gpu)\n\"\"\"\n**Downlaod the embeddings of CORD-19 Titles here : [CORD-19 Title embeddings](https:\/\/drive.google.com\/file\/d\/1rCA5Y_7gL6Maitcf0_5mjWfYGml3vHEO\/view?usp=sharing)**\n\nThank you for your time, In case of any queries or corrections, mail me at narasimhaprasannahn@gmail.com\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '353b2d82c23533'}"}
{"id":"85428","text":"\"\"\"\n## Stock Sentiment Analysis using News Headlines\n\"\"\"\nimport pandas as pd\ndf=pd.read_csv('..\/input\/stock-sentiment-analysis\/Stock_Dataa.csv', encoding = \"ISO-8859-1\")\ndf.head()\ntrain = df[df['Date'] < '20150101']\ntest = df[df['Date'] > '20141231']\n# Removing punctuations\ndata=train.iloc[:,2:27]\ndata.replace(\"[^a-zA-Z]\",\" \",regex=True, inplace=True)\n\n# Renaming column names for ease of access\nlist1= [i for i in range(25)]\nnew_Index=[str(i) for i in list1]\ndata.columns= new_Index\ndata.head(5)\n\n\n# Convertng headlines to lower case\nfor index in new_Index:\n    data[index]=data[index].str.lower()\ndata.head(1)\n' '.join(str(x) for x in data.iloc[1,0:25])\nheadlines = []\nfor row in range(0,len(data.index)):\n    headlines.append(' '.join(str(x) for x in data.iloc[row,0:25]))\nheadlines[0]\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\n## implement BAG OF WORDS\ncountvector=CountVectorizer(ngram_range=(2,2))\ntraindataset=countvector.fit_transform(headlines)\n# implement RandomForest Classifier\nrandomclassifier=RandomForestClassifier(n_estimators=200,criterion='entropy')\nrandomclassifier.fit(traindataset,train['Label'])\n## Predict for the Test Dataset\ntest_transform= []\nfor row in range(0,len(test.index)):\n    test_transform.append(' '.join(str(x) for x in test.iloc[row,2:27]))\ntest_dataset = countvector.transform(test_transform)\npredictions = randomclassifier.predict(test_dataset)\n## Import library to check accuracy\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score\nmatrix=confusion_matrix(test['Label'],predictions)\nprint(matrix)\nscore=accuracy_score(test['Label'],predictions)\nprint(score)\nreport=classification_report(test['Label'],predictions)\nprint(report)","meta":"{'source': 'AI4Code', 'id': '9cbceae47f4329'}"}
{"id":"4202","text":"\"\"\"\n# Article Summarizer using NLP\n\"\"\"\n\"\"\"\n### Importing the required Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport warnings\nimport re\nimport nltk\nfrom nltk import word_tokenize\nfrom nltk.tokenize import sent_tokenize\nfrom textblob import TextBlob\nimport string\nfrom string import punctuation\nfrom nltk.corpus import stopwords\nfrom statistics import mean\nfrom heapq import nlargest\nfrom wordcloud import WordCloud\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nstop_words = set(stopwords.words('english'))\npunctuation = punctuation + '\\n' + '\u2014' + '\u201c' + ',' + '\u201d' + '\u2018' + '-' + '\u2019'\nwarnings.filterwarnings('ignore')\n# Importing the dataset\ndf_1 = pd.read_csv(\"\/kaggle\/input\/all-the-news\/articles1.csv\")\ndf_2 = pd.read_csv(\"\/kaggle\/input\/all-the-news\/articles2.csv\")\ndf_3 = pd.read_csv(\"\/kaggle\/input\/all-the-news\/articles3.csv\")\n# Checking if the columns are same or not\ndf_1.columns == df_2.columns\n# Checking if the columns are same or not\ndf_2.columns == df_3.columns\n# Making one Dataframe by appending all of them for the further process\nd = [df_1, df_2, df_3]\ndf = pd.concat(d, keys = ['x', 'y', 'z'])\ndf.rename(columns = {'content' : 'article'}, inplace = True);\ndf.head(10)\n# Shape of the dataset\nprint (\"The shape of the dataset : \", df.shape)\n# Dropping the unnecessary columns\ndf.drop(columns = ['Unnamed: 0'], inplace = True)\ndf.head()\n\"\"\"\nSince the content of the article are in a pandas series so we need to change them into a single string\n\"\"\"\n\"\"\"\n### Exploratory Data Analysis\n\"\"\"\ndf.head()\n# Replacing the unnecessary row value of year with it's actual values\ndf['year'] = df['year'].replace(\"https:\/\/www.washingtonpost.com\/outlook\/tale-of-a-woman-who-died-and-a-woman-who-killed-in-the-northern-ireland-conflict\/2019\/03\/08\/59e75dd4-2ecd-11e9-8ad3-9a5b113ecd3c_story.html\", 2019)\n# Years\ndf['year'].value_counts()\n# Countplot shows the distribution of the articles according to the year\nplt.rcParams['figure.figsize'] = [15, 8]\nsns.set(font_scale = 1.2, style = 'whitegrid')\nsns_year = sns.countplot(df['year'], color = 'darkcyan')\nsns_year.set(xlabel = \"Year\", ylabel = \"Count\", title = \"Distribution of the articles according to the year\")\n# Authors\ndf['author'].value_counts()\n# Changing the value \"The Associated Press\" to \"Associated Press\"\ndf['author'] = df['author'].replace(\"The Associated Press\", \"Associated Press\")\n# Top 100 authors\ndf['author'].value_counts()[0:100]\n# Barplot showing the top 50 Authors\nplt.rcParams['figure.figsize'] = [20, 10]\nauthor_count = df['author'].value_counts()[0:50]\nauthor_top_50 = sns.barplot(x = list(author_count.index), y = (author_count.values), color = 'orange')\nauthor_top_50.set(xlabel = \"Authors\", ylabel = \"Published Articles\", title = \"Top 50 Authors\")\nplt.setp(author_top_50.get_xticklabels(), rotation = 90);\n# Countplot shows the distribution of the Publications\nplt.rcParams['figure.figsize'] = [15, 10]\nsns.set(font_scale = 1.2, style = 'whitegrid')\nsns_pub = sns.countplot(df['publication'], color = 'slategrey')\nsns_pub.set(xlabel = \"Publications\", ylabel = \"Count\", title = \"Distribution of the Publications across the dataset\")\nplt.setp(sns_pub.get_xticklabels(), rotation = 90);\n\"\"\"\n### Making the Article Summarizer\n\"\"\"\ncontractions_dict = { \n\"ain't\": \"am not\",\n\"aren't\": \"are not\",\n\"can't\": \"cannot\",\n\"can't've\": \"cannot have\",\n\"'cause\": \"because\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"doesn\u2019t\": \"does not\",\n\"don't\": \"do not\",\n\"don\u2019t\": \"do not\",\n\"hadn't\": \"had not\",\n\"hadn't've\": \"had not have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he had\",\n\"he'd've\": \"he would have\",\n\"he'll\": \"he will\",\n\"he'll've\": \"he will have\",\n\"he's\": \"he is\",\n\"how'd\": \"how did\",\n\"how'd'y\": \"how do you\",\n\"how'll\": \"how will\",\n\"how's\": \"how is\",\n\"i'd\": \"i would\",\n\"i'd've\": \"i would have\",\n\"i'll\": \"i will\",\n\"i'll've\": \"i will have\",\n\"i'm\": \"i am\",\n\"i've\": \"i have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it would\",\n\"it'd've\": \"it would have\",\n\"it'll\": \"it will\",\n\"it'll've\": \"it will have\",\n\"it's\": \"it is\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"might've\": \"might have\",\n\"mightn't\": \"might not\",\n\"mightn't've\": \"might not have\",\n\"must've\": \"must have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"needn't\": \"need not\",\n\"needn't've\": \"need not have\",\n\"o'clock\": \"of the clock\",\n\"oughtn't\": \"ought not\",\n\"oughtn't've\": \"ought not have\",\n\"shan't\": \"shall not\",\n\"sha'n't\": \"shall not\",\n\"shan't've\": \"shall not have\",\n\"she'd\": \"she would\",\n\"she'd've\": \"she would have\",\n\"she'll\": \"she will\",\n\"she'll've\": \"she will have\",\n\"she's\": \"she is\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"so've\": \"so have\",\n\"so's\": \"so is\",\n\"that'd\": \"that would\",\n\"that'd've\": \"that would have\",\n\"that's\": \"that is\",\n\"there'd\": \"there would\",\n\"there'd've\": \"there would have\",\n\"there's\": \"there is\",\n\"they'd\": \"they would\",\n\"they'd've\": \"they would have\",\n\"they'll\": \"they will\",\n\"they'll've\": \"they will have\",\n\"they're\": \"they are\",\n\"they've\": \"they have\",\n\"to've\": \"to have\",\n\"wasn't\": \"was not\",\n\"we'd\": \"we would\",\n\"we'd've\": \"we would have\",\n\"we'll\": \"we will\",\n\"we'll've\": \"we will have\",\n\"we're\": \"we are\",\n\"we've\": \"we have\",\n\"weren't\": \"were not\",\n\"what'll\": \"what will\",\n\"what'll've\": \"what will have\",\n\"what're\": \"what are\",\n\"what's\": \"what is\",\n\"what've\": \"what have\",\n\"when's\": \"when is\",\n\"when've\": \"when have\",\n\"where'd\": \"where did\",\n\"where's\": \"where is\",\n\"where've\": \"where have\",\n\"who'll\": \"who will\",\n\"who'll've\": \"who will have\",\n\"who's\": \"who is\",\n\"who've\": \"who have\",\n\"why's\": \"why is\",\n\"why've\": \"why have\",\n\"will've\": \"will have\",\n\"won't\": \"will not\",\n\"won't've\": \"will not have\",\n\"would've\": \"would have\",\n\"wouldn't\": \"would not\",\n\"wouldn't've\": \"would not have\",\n\"y'all\": \"you all\",\n\"y\u2019all\": \"you all\",\n\"y'all'd\": \"you all would\",\n\"y'all'd've\": \"you all would have\",\n\"y'all're\": \"you all are\",\n\"y'all've\": \"you all have\",\n\"you'd\": \"you would\",\n\"you'd've\": \"you would have\",\n\"you'll\": \"you will\",\n\"you'll've\": \"you will have\",\n\"you're\": \"you are\",\n\"you've\": \"you have\",\n\"ain\u2019t\": \"am not\",\n\"aren\u2019t\": \"are not\",\n\"can\u2019t\": \"cannot\",\n\"can\u2019t\u2019ve\": \"cannot have\",\n\"\u2019cause\": \"because\",\n\"could\u2019ve\": \"could have\",\n\"couldn\u2019t\": \"could not\",\n\"couldn\u2019t\u2019ve\": \"could not have\",\n\"didn\u2019t\": \"did not\",\n\"doesn\u2019t\": \"does not\",\n\"don\u2019t\": \"do not\",\n\"don\u2019t\": \"do not\",\n\"hadn\u2019t\": \"had not\",\n\"hadn\u2019t\u2019ve\": \"had not have\",\n\"hasn\u2019t\": \"has not\",\n\"haven\u2019t\": \"have not\",\n\"he\u2019d\": \"he had\",\n\"he\u2019d\u2019ve\": \"he would have\",\n\"he\u2019ll\": \"he will\",\n\"he\u2019ll\u2019ve\": \"he will have\",\n\"he\u2019s\": \"he is\",\n\"how\u2019d\": \"how did\",\n\"how\u2019d\u2019y\": \"how do you\",\n\"how\u2019ll\": \"how will\",\n\"how\u2019s\": \"how is\",\n\"i\u2019d\": \"i would\",\n\"i\u2019d\u2019ve\": \"i would have\",\n\"i\u2019ll\": \"i will\",\n\"i\u2019ll\u2019ve\": \"i will have\",\n\"i\u2019m\": \"i am\",\n\"i\u2019ve\": \"i have\",\n\"isn\u2019t\": \"is not\",\n\"it\u2019d\": \"it would\",\n\"it\u2019d\u2019ve\": \"it would have\",\n\"it\u2019ll\": \"it will\",\n\"it\u2019ll\u2019ve\": \"it will have\",\n\"it\u2019s\": \"it is\",\n\"let\u2019s\": \"let us\",\n\"ma\u2019am\": \"madam\",\n\"mayn\u2019t\": \"may not\",\n\"might\u2019ve\": \"might have\",\n\"mightn\u2019t\": \"might not\",\n\"mightn\u2019t\u2019ve\": \"might not have\",\n\"must\u2019ve\": \"must have\",\n\"mustn\u2019t\": \"must not\",\n\"mustn\u2019t\u2019ve\": \"must not have\",\n\"needn\u2019t\": \"need not\",\n\"needn\u2019t\u2019ve\": \"need not have\",\n\"o\u2019clock\": \"of the clock\",\n\"oughtn\u2019t\": \"ought not\",\n\"oughtn\u2019t\u2019ve\": \"ought not have\",\n\"shan\u2019t\": \"shall not\",\n\"sha\u2019n\u2019t\": \"shall not\",\n\"shan\u2019t\u2019ve\": \"shall not have\",\n\"she\u2019d\": \"she would\",\n\"she\u2019d\u2019ve\": \"she would have\",\n\"she\u2019ll\": \"she will\",\n\"she\u2019ll\u2019ve\": \"she will have\",\n\"she\u2019s\": \"she is\",\n\"should\u2019ve\": \"should have\",\n\"shouldn\u2019t\": \"should not\",\n\"shouldn\u2019t\u2019ve\": \"should not have\",\n\"so\u2019ve\": \"so have\",\n\"so\u2019s\": \"so is\",\n\"that\u2019d\": \"that would\",\n\"that\u2019d\u2019ve\": \"that would have\",\n\"that\u2019s\": \"that is\",\n\"there\u2019d\": \"there would\",\n\"there\u2019d\u2019ve\": \"there would have\",\n\"there\u2019s\": \"there is\",\n\"they\u2019d\": \"they would\",\n\"they\u2019d\u2019ve\": \"they would have\",\n\"they\u2019ll\": \"they will\",\n\"they\u2019ll\u2019ve\": \"they will have\",\n\"they\u2019re\": \"they are\",\n\"they\u2019ve\": \"they have\",\n\"to\u2019ve\": \"to have\",\n\"wasn\u2019t\": \"was not\",\n\"we\u2019d\": \"we would\",\n\"we\u2019d\u2019ve\": \"we would have\",\n\"we\u2019ll\": \"we will\",\n\"we\u2019ll\u2019ve\": \"we will have\",\n\"we\u2019re\": \"we are\",\n\"we\u2019ve\": \"we have\",\n\"weren\u2019t\": \"were not\",\n\"what\u2019ll\": \"what will\",\n\"what\u2019ll\u2019ve\": \"what will have\",\n\"what\u2019re\": \"what are\",\n\"what\u2019s\": \"what is\",\n\"what\u2019ve\": \"what have\",\n\"when\u2019s\": \"when is\",\n\"when\u2019ve\": \"when have\",\n\"where\u2019d\": \"where did\",\n\"where\u2019s\": \"where is\",\n\"where\u2019ve\": \"where have\",\n\"who\u2019ll\": \"who will\",\n\"who\u2019ll\u2019ve\": \"who will have\",\n\"who\u2019s\": \"who is\",\n\"who\u2019ve\": \"who have\",\n\"why\u2019s\": \"why is\",\n\"why\u2019ve\": \"why have\",\n\"will\u2019ve\": \"will have\",\n\"won\u2019t\": \"will not\",\n\"won\u2019t\u2019ve\": \"will not have\",\n\"would\u2019ve\": \"would have\",\n\"wouldn\u2019t\": \"would not\",\n\"wouldn\u2019t\u2019ve\": \"would not have\",\n\"y\u2019all\": \"you all\",\n\"y\u2019all\": \"you all\",\n\"y\u2019all\u2019d\": \"you all would\",\n\"y\u2019all\u2019d\u2019ve\": \"you all would have\",\n\"y\u2019all\u2019re\": \"you all are\",\n\"y\u2019all\u2019ve\": \"you all have\",\n\"you\u2019d\": \"you would\",\n\"you\u2019d\u2019ve\": \"you would have\",\n\"you\u2019ll\": \"you will\",\n\"you\u2019ll\u2019ve\": \"you will have\",\n\"you\u2019re\": \"you are\",\n\"you\u2019re\": \"you are\",\n\"you\u2019ve\": \"you have\",\n}\ncontractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys()))\n# Function to clean the html from the article\ndef cleanhtml(raw_html):\n    cleanr = re.compile('<.*?>')\n    cleantext = re.sub(cleanr, '', raw_html)\n    return cleantext\n\n# Function expand the contractions if there's any\ndef expand_contractions(s, contractions_dict=contractions_dict):\n    def replace(match):\n        return contractions_dict[match.group(0)]\n    return contractions_re.sub(replace, s)\n\n# Function to preprocess the articles\ndef preprocessing(article):\n    global article_sent\n    \n    # Converting to lowercase\n    article = article.str.lower()\n    \n    # Removing the HTML\n    article = article.apply(lambda x: cleanhtml(x))\n    \n    # Removing the email ids\n    article = article.apply(lambda x: re.sub('\\S+@\\S+','', x))\n    \n    # Removing The URLS\n    article = article.apply(lambda x: re.sub(\"((http\\:\/\/|https\\:\/\/|ftp\\:\/\/)|(www.))+(([a-zA-Z0-9\\.-]+\\.[a-zA-Z]{2,4})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(\/[a-zA-Z0-9%:\/-_\\?\\.'~]*)?\",'', x))\n    \n    # Removing the '\\xa0'\n    article = article.apply(lambda x: x.replace(\"\\xa0\", \" \"))\n    \n    # Removing the contractions\n    article = article.apply(lambda x: expand_contractions(x))\n    \n    # Stripping the possessives\n    article = article.apply(lambda x: x.replace(\"'s\", ''))\n    article = article.apply(lambda x: x.replace('\u2019s', ''))\n    article = article.apply(lambda x: x.replace(\"\\'s\", ''))\n    article = article.apply(lambda x: x.replace(\"\\\u2019s\", ''))\n    \n    # Removing the Trailing and leading whitespace and double spaces\n    article = article.apply(lambda x: re.sub(' +', ' ',x))\n    \n    # Copying the article for the sentence tokenization\n    article_sent = article.copy()\n    \n    # Removing punctuations from the article\n    article = article.apply(lambda x: ''.join(word for word in x if word not in punctuation))\n    \n    # Removing the Trailing and leading whitespace and double spaces again as removing punctuation might\n    # Lead to a white space\n    article = article.apply(lambda x: re.sub(' +', ' ',x))\n    \n    # Removing the Stopwords\n    article = article.apply(lambda x: ' '.join(word for word in x.split() if word not in stop_words))\n    \n    return article\n\n# Function to normalize the word frequency which is used in the function word_frequency\ndef normalize(li_word):\n    global normalized_freq\n    normalized_freq = []\n    for dictionary in li_word:\n        max_frequency = max(dictionary.values())\n        for word in dictionary.keys():\n            dictionary[word] = dictionary[word]\/max_frequency\n        normalized_freq.append(dictionary)\n    return normalized_freq\n\n# Function to calculate the word frequency\ndef word_frequency(article_word):\n    word_frequency = {}\n    li_word = []\n    for sentence in article_word:\n        for word in word_tokenize(sentence):\n            if word not in word_frequency.keys():\n                word_frequency[word] = 1\n            else:\n                word_frequency[word] += 1\n        li_word.append(word_frequency)\n        word_frequency = {}\n    normalize(li_word)\n    return normalized_freq\n\n# Function to Score the sentence which is called in the function sent_token\ndef sentence_score(li):\n    global sentence_score_list\n    sentence_score = {}\n    sentence_score_list = []\n    for list_, dictionary in zip(li, normalized_freq):\n        for sent in list_:\n            for word in word_tokenize(sent):\n                if word in dictionary.keys():\n                    if sent not in sentence_score.keys():\n                        sentence_score[sent] = dictionary[word]\n                    else:\n                        sentence_score[sent] += dictionary[word]\n        sentence_score_list.append(sentence_score)\n        sentence_score = {}\n    return sentence_score_list\n\n# Function to tokenize the sentence\ndef sent_token(article_sent):\n    sentence_list = []\n    sent_token = []\n    for sent in article_sent:\n        token = sent_tokenize(sent)\n        for sentence in token:\n            token_2 = ''.join(word for word in sentence if word not in punctuation)\n            token_2 = re.sub(' +', ' ',token_2)\n            sent_token.append(token_2)\n        sentence_list.append(sent_token)\n        sent_token = []\n    sentence_score(sentence_list)\n    return sentence_score_list\n\n# Function which generates the summary of the articles (This uses the 20% of the sentences with the highest score)\ndef summary(sentence_score_OwO):\n    summary_list = []\n    for summ in sentence_score_OwO:\n        select_length = int(len(summ)*0.25)\n        summary_ = nlargest(select_length, summ, key = summ.get)\n        summary_list.append(\".\".join(summary_))\n    return summary_list\n\n# This Function can be used to generate the summary which uses the mean sentence score\n#def summary(sentence_score_OwO):\n#    summary_list = []\n#    li_sen = []\n#    for summ in sentence_score_OwO:\n#        for sent, score in summ.items():\n#            threshold_score = mean(list(summ.values()))\n#            if score >= threshold_score:\n#                li_sen.append(sent)\n#            else:\n#                continue\n#        sugoi = ', '.join(li_sen)\n#        summary_list.append(sugoi)\n#        li_sen = []\n#    return summary_list\n\n# Functions to change the article string (if passed) to change it to generate a pandas series\ndef make_series(art):\n    global dataframe\n    data_dict = {'article' : [art]}\n    dataframe = pd.DataFrame(data_dict)['article']\n    return dataframe\n\n# Function which is to be called to generate the summary which in further calls other functions alltogether\ndef article_summarize(artefact):\n    \n    if type(artefact) != pd.Series:\n        artefact = make_series(artefact)\n    \n    df = preprocessing(artefact)\n    \n    word_normalization = word_frequency(df)\n    \n    sentence_score_OwO = sent_token(article_sent)\n    \n    summarized_article = summary(sentence_score_OwO)\n    \n    return summarized_article\n# Generating the Word Cloud of the article using the preprocessing and make_series function mentioned below\ndef word_cloud(art):\n    art_ = make_series(art)\n    OwO = preprocessing(art_)\n    wordcloud_ = WordCloud(height = 500, width = 1000, background_color = 'white').generate(art)\n    plt.figure(figsize=(15, 10))\n    plt.imshow(wordcloud_, interpolation='bilinear')\n    plt.axis('off');\n# Generating the summaries for the first 100 articles\nsummaries = article_summarize(df['article'][0:100])\n\"\"\"\n### Examples\n\"\"\"\nprint (\"The Actual length of the article is : \", len(df['article'][0]))\ndf['article'][0]\nprint (\"The length of the summarized article is : \", len(summaries[0]))\nsummaries[0]\nword_cloud(df['article'][0])\nprint (\"The Actual length of the article is : \", len(df['article'][50]))\ndf['article'][50]\nprint (\"The length of the summarized article is : \", len(summaries[50]))\nsummaries[50]\nword_cloud(df['article'][50])\nprint (\"The Actual length of the article is : \", len(df['article'][99]))\ndf['article'][99]\nprint (\"The length of the summarized article is : \", len(summaries[99]))\nsummaries[99]\nword_cloud(df['article'][99])\nprint (\"The Actual length of the article is : \", len(df['article'][75]))\ndf['article'][75]\nprint (\"The length of the summarized article is : \", len(summaries[75]))\nsummaries[75]\nword_cloud(df['article'][75])","meta":"{'source': 'AI4Code', 'id': '07d809ac686903'}"}
{"id":"33430","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport plotly.express as px\nimport plotly.graph_objects as go\n\ndata = pd.read_csv('..\/input\/videogamesales\/vgsales.csv')\ndata.drop(['Rank'], axis=1, inplace=True)\ndata['Year'] = data['Year'].fillna(2009.0)\n\"\"\"\n# Which game has highest Global Sales? ----> Wii Sports\n\"\"\"\ngame = data.loc[:,['Name','Global_Sales']]\ngame = game.sort_values('Global_Sales', ascending=False)\ngame = game.head()\n\nfig = plt.figure(figsize=(10,7))\nplt.pie(game['Global_Sales'], labels=game['Name'], autopct='%1.1f%%', shadow=True)\ncentre_circle = plt.Circle((0,0),0.45,color='black', fc='white',linewidth=1.25)\nfig = plt.gcf()\nfig.gca().add_artist(centre_circle)\nplt.axis('equal')\nplt.show()\n\"\"\"\n# Top 5 platforms per year\n\"\"\"\ntop_5_platforms = ['DS', 'PS2', 'PS3', 'Wii', 'X360']\nperc = data.loc[:,[\"Year\",\"Platform\",'Global_Sales']]\nperc['total_sales'] = perc.groupby([perc.Platform,perc.Year])['Global_Sales'].transform('sum')\nperc.drop('Global_Sales', axis=1, inplace=True)\nperc = perc.drop_duplicates()\nperc = perc[(perc['Year'].astype('float')>=2006.0) & (perc['Year'].astype('float')<=2011.0)]\nperc = perc.sort_values(\"Year\",ascending = False)\nperc = perc.loc[perc['Platform'].isin(top_5_platforms)]\nperc = perc.sort_values(\"Year\")\nfig=px.bar(perc,x='Platform', y=\"total_sales\", animation_frame=\"Year\", \n           animation_group=\"Platform\", color=\"Platform\", hover_name=\"Platform\")\nfig.show()\n\"\"\"\n# Which years saw highest game launches?  ----> 2007-2010\n\"\"\"\nsns.kdeplot(data=data['Year'], label='Year', shade=True)\nplt.title('Number of game launches according to years')\nplt.show()\n\"\"\"\n# Relation of Global_sales with year ---> One outlier noticed\n\"\"\"\nplt.figure(figsize=(10,7))\nsns.scatterplot(data=data, x='Year', y='Global_Sales')\nplt.show()\n\"\"\"\n# Which genre of games have highest sales? ----> Sports\n\"\"\"\ngenre = data.loc[:,['Genre','Global_Sales']]\ngenre['total_sales'] = genre.groupby('Genre')['Global_Sales'].transform('sum')\ngenre.drop('Global_Sales', axis=1, inplace=True)\ngenre = genre.drop_duplicates()\n\nfig = px.pie(genre, names='Genre', values='total_sales', template='seaborn')\nfig.update_traces(rotation=90, pull=[0.2,0.06,0.06,0.06,0.06], textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Which Publisher of games have highest sales? ---> Nintendo\n\"\"\"\npublisher = data.loc[:,['Publisher','Global_Sales']]\npublisher['total_sales'] = publisher.groupby('Publisher')['Global_Sales'].transform('sum')\npublisher.drop('Global_Sales', axis=1, inplace=True)\npublisher = publisher.drop_duplicates()\npublisher = publisher.head(10)\n\nfig = px.pie(publisher, names='Publisher', values='total_sales', template='seaborn')\nfig.update_traces(rotation=90, pull=[0.2,0.1,0.1,0.1,0.1], textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Top 5 publishers per year\n\"\"\"\ntop_5_publishers = ['Nintendo', 'Electronic Arts', 'Activision', 'Ubisoft', 'Sony Computer Entertainment']\nperc = data.loc[:,[\"Year\",\"Publisher\",'Global_Sales']]\nperc['total_sales'] = perc.groupby([perc.Publisher,perc.Year])['Global_Sales'].transform('sum')\nperc.drop('Global_Sales', axis=1, inplace=True)\nperc = perc.drop_duplicates()\nperc = perc[(perc['Year'].astype('float')>=2006.0)]\nperc = perc.sort_values(\"Year\",ascending = False)\nperc = perc.loc[perc['Publisher'].isin(top_5_publishers)]\nperc = perc.sort_values(\"Year\")\nfig=px.bar(perc,x='Publisher', y=\"total_sales\", animation_frame=\"Year\", \n           animation_group=\"Publisher\", color=\"Publisher\", hover_name=\"Publisher\")\nfig.show()\n\"\"\"\n# Which sales range is most games in? ---> (0-10)(in millions)\n\"\"\"\nsns.kdeplot(data=data['Global_Sales'], label='Global_Sales', shade=True)\nplt.title('Sales of various games over the years')\nplt.show()\n\"\"\"\n# Top 5 games for each Genre\n\"\"\"\ngenres = data['Genre'].value_counts().reset_index()['index'].tolist()\n\nfor genre,num in zip(genres,range(1,13)):\n    df = data[data['Genre']==genre]\n    df = df.sort_values('Global_Sales', ascending=False)\n    df = df.head(3)\n    plt.figure()\n    sns.barplot(data=df, x='Global_Sales', y='Name')\n    plt.title('Top 5 games in {}'.format(genre))\n    plt.show()\n\"\"\"\n# Most popular game in North America ---> Super Mario Bros.\n\"\"\"\ngame = data.loc[data['Name']!='Wii Sports',['Name','NA_Sales']]\ngame = game.sort_values('NA_Sales', ascending=False)\ngame = game.head()\n\nfig = px.pie(game, names='Name', values='NA_Sales', template='seaborn')\nfig.update_traces(rotation=90, pull=0.06, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Most popular platform in North America ---> X360\n\"\"\"\nplatform = data.loc[data['Name']!='Wii Sports',['Platform','NA_Sales']]\nplatform['total_sales'] = platform.groupby('Platform')['NA_Sales'].transform('sum')\nplatform.drop('NA_Sales', axis=1, inplace=True)\nplatform = platform.drop_duplicates()\nplatform = platform.sort_values('total_sales', ascending=False)\nplatform = platform.head()\n\nfig = px.pie(platform, names='Platform', values='total_sales', template='seaborn')\nfig.update_traces(rotation=90, pull=0.06, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Most popular Genre in North America ---> Action\n\"\"\"\ngenre = data.loc[data['Name']!='Wii Sports',['Genre','NA_Sales']]\ngenre['total_sales'] = genre.groupby('Genre')['NA_Sales'].transform('sum')\ngenre.drop('NA_Sales', axis=1, inplace=True)\ngenre = genre.drop_duplicates()\ngenre = genre.sort_values('total_sales', ascending=False)\ngenre = genre.head()\n\nfig = px.pie(genre, names='Genre', values='total_sales', template='seaborn')\nfig.update_traces(rotation=90, pull=0.06, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Most popular publisher in North America ---> Nintendo\n\"\"\"\npublisher = data.loc[data['Name']!='Wii Sports',['Publisher','NA_Sales']]\npublisher['total_sales'] = publisher.groupby('Publisher')['NA_Sales'].transform('sum')\npublisher.drop('NA_Sales', axis=1, inplace=True)\npublisher = publisher.drop_duplicates()\npublisher = publisher.sort_values('total_sales', ascending=False)\npublisher = publisher.head()\n\nfig = px.pie(publisher, names='Publisher', values='total_sales', template='seaborn')\nfig.update_traces(rotation=90, pull=0.06, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\nThe same can be analysed for Europe and Japan. I am not going into that.\n\"\"\"\n\"\"\"\n# Sales in all places every year\n\"\"\"\nperc = data.loc[:,[\"Year\",'NA_Sales','EU_Sales','JP_Sales','Other_Sales']]\nperc[['NA_mean','EU_mean','JP_mean','Other_mean']] = perc.groupby('Year')[['NA_Sales','EU_Sales','JP_Sales','Other_Sales']].transform('sum')\nperc.drop(['NA_Sales','EU_Sales','JP_Sales','Other_Sales'], axis=1, inplace=True)\nperc = perc.drop_duplicates()\nperc = perc.sort_values(\"Year\")\ndf = pd.DataFrame({'Place': ['NA_Sales']*perc.shape[0], 'Year':perc['Year'], 'Sales': perc['NA_mean']})\ndf1 = pd.DataFrame({'Place': ['EU_Sales']*perc.shape[0], 'Year':perc['Year'], 'Sales': perc['EU_mean']})\ndf2 = pd.DataFrame({'Place': ['JP_Sales']*perc.shape[0], 'Year':perc['Year'], 'Sales': perc['JP_mean']})\ndf3 = pd.DataFrame({'Place': ['Other_Sales']*perc.shape[0], 'Year':perc['Year'], 'Sales': perc['Other_mean']})\nfinal = pd.concat([df,df1,df2,df3], axis=0)\nfinal = final.sort_values(\"Year\")\nfinal = final[final['Year']<=2016.0]\nfig=px.bar(final,x='Place', y=\"Sales\", animation_frame=\"Year\", \n           animation_group=\"Place\", color=\"Place\", hover_name=\"Place\", range_y=[0,400])\nfig.show()\n\"\"\"\n# Relation of Global Sales to other places sales\n\"\"\"\ndf = data.loc[:,['Year','NA_Sales','EU_Sales','JP_Sales','Other_Sales','Global_Sales']]\ndf[['NA_sum','EU_sum','JP_sum','Other_sum', 'Global_sum']] = df.groupby('Year')[['NA_Sales','EU_Sales','JP_Sales','Other_Sales','Global_Sales']].transform('sum')\ndf.drop(['NA_Sales','EU_Sales','JP_Sales','Other_Sales','Global_Sales'], axis=1, inplace=True)\ndf = df.drop_duplicates()\ndf = df.sort_values('Year')\ndf1 = pd.DataFrame({'Place': ['NA_Sales']*df.shape[0], 'Year':df['Year'], 'Sales': df['NA_sum'], 'Global_Sales': df['Global_sum']})\ndf2 = pd.DataFrame({'Place': ['EU_Sales']*df.shape[0], 'Year':df['Year'], 'Sales': df['EU_sum'], 'Global_Sales': df['Global_sum']})\ndf3 = pd.DataFrame({'Place': ['JP_Sales']*df.shape[0], 'Year':df['Year'], 'Sales': df['JP_sum'], 'Global_Sales': df['Global_sum']})\ndf4 = pd.DataFrame({'Place': ['Other_Sales']*df.shape[0], 'Year':df['Year'], 'Sales': df['Other_sum'], 'Global_Sales': df['Global_sum']})\nfinal = pd.concat([df1,df2,df3,df4], axis=0)\nfinal = final.sort_values(\"Year\")\nfinal = final[(final['Year']>=1994.0) & (final['Year']<=2016.0)]\n\nfig = px.scatter(final, x=\"Global_Sales\", y=\"Sales\", animation_frame=\"Year\", animation_group=\"Place\", color=\"Place\", hover_name=\"Place\", size_max=1000, range_x=[0,768], range_y=[0,400])\nfig.update_traces(marker=dict(size=12,\n                              line=dict(width=2,\n                                        color='DarkSlateGrey')),\n                  selector=dict(mode='markers'))\nfig.show()","meta":"{'source': 'AI4Code', 'id': '3d9d9fdcac8b0c'}"}
{"id":"98736","text":"# 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\n\"\"\"\n## Steps I followed:\n1. Importing data\n2. Cleaning data and data exploration\n3. Feature engineering (choosing required features)\n4. Data visualization\n5. Finding if there exists corr among variables\n6. train test split\n7. Model building and Hyper-parameter tuning\n8. using various sklearn.metrics : mean_absolute_error, mean_squared_error, np.sqrt(mean_squared_error)\n9. converting the model to pickle file for future use\n\"\"\"\n# Importing Dependencies\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Lasso\nfrom sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.feature_selection import SelectFromModel\nimport xgboost as xgb\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import metrics\n# Importing data\ndataset = pd.read_csv(\"..\/input\/vehicle-dataset-from-cardekho\/car data.csv\")\n\"\"\"\n# About features\n1. **name** - Name of the cars\n2. **year** - Year of the car when it was bought\n3. **selling_price** - Price at which the car is being sold\n4. **km_driven** - Number of Kilometres the car is driven\n5. **fuel** - Fuel type of car\n6. **seller_type** - tells if a seller is individual or a dealer\n7. **transmission** - Gear transmission fo the car\n8. **owner** - Number of previous owners of the car\n\"\"\"\n# top 5-rows of dataset\ndataset.head()\n# getting more familier with the dataset\ndataset.info()\n\"\"\"\n### Selling_Price is the target feature\n\"\"\"\n\"\"\"\n# Missing Values\n\"\"\"\n# Checking if there is any missing value\ndataset.isnull().sum()\n\"\"\"\n# Categorical Variable Encoding\n\"\"\"\ncat_features = [feature for feature in dataset.columns if dataset[feature].dtypes in ['object']]\ncat_features\n\"\"\"\n### Categorical feature distribution with 'Selling_Price'\n\"\"\"\ndataset.shape\ndataset.Car_Name.nunique()\n# There are 98 different features\n# Mean prices per category of categorical variables\nplt.figure(figsize=(15,8))\nfor feature in cat_features:\n    dataset.groupby(feature)['Selling_Price'].mean().plot.bar()\n    plt.title(feature)\n    plt.show()\n\"\"\"\n#### Observation of categorical features\n1. Few car names have higher prices, like 'fortuner', 'innova', 'land cruiser', etc.\n2. In Fuel_Type, 'Diesel' type cars have higher prices as compared to CNG or Petrol driven cars\n3. In seller_type, 'Dealer' are selling cars with higher prices than 'Individual'\n4. And finally, 'Automatic' cars are being sold for higher prices than 'Manual' cars\n\"\"\"\n# count of prices per category of categorical variables\nplt.figure(figsize=(15,8))\nfor feature in cat_features:\n    dataset.groupby(feature)['Selling_Price'].count().plot.bar()\n    plt.title(feature)\n    plt.show()\n\"\"\"\n# Temporal Feature: Features releted to time, date or year\n\"\"\"\ntemporal_feature = [feature for feature in dataset.columns if 'year' in feature.lower() or 'yr' in feature.lower()]\ntemporal_feature\n\"\"\"\n##### Updating the temporal feature with number years since the car was bought\n\"\"\"\nfor feature in temporal_feature:\n    dataset[feature] = 2021 - dataset[feature]\ndataset.head()\n\"\"\"\n#### Now 'year' variable represents the number of years passed since the car was bought\n\"\"\"\n\"\"\"\n# Numerical Variables\n\"\"\"\n\"\"\"\n##### finding correlation between all the numerical values with target variable Selling_Price\n\"\"\"\ndataset.corr()['Selling_Price'].drop('Selling_Price', axis=0) # pandas.core.frame.DataFrame\n\"\"\"\n##### Observation: The Selling_Price is linearly directly correlated with Present_Price\n\"\"\"\ndataset[['Year', 'Present_Price',  'Kms_Driven', 'Owner']].head()\n# Checking the number of unique values present per numerical variable\ndataset[['Year', 'Present_Price',  'Kms_Driven', 'Owner']].nunique()\ndataset[['Year', 'Present_Price',  'Kms_Driven', 'Owner']].info()\n\"\"\"\n##### Although 'Kms_Driven' is of type int64, but it should be continuous numerical variable\n\"\"\"\n# Changing the datatype of Kms_driven\ndataset.Kms_Driven = dataset.Kms_Driven.astype('float64')\ndataset[['Year', 'Present_Price',  'Kms_Driven', 'Owner']].info()\n\"\"\"\n### Discrete Numerical Variables\n\"\"\"\ndiscrete_num_features = [feature for feature in dataset.columns if dataset[feature].dtypes in ['int64']]\ndiscrete_num_features\n# Let's see the relationship of discrete numerical variables with target variable ('SalePrice')\nfor feature in discrete_num_features:\n    dataset.groupby(feature)['Selling_Price'].mean().plot.bar()\n\n    plt.xlabel(feature)\n    plt.ylabel('Selling_Price')\n    plt.title(feature)\n    plt.show()\n\"\"\"\n##### Observations: \n1. With the increase in the number of years, we can see a clear decline in Selling Price\n2. In case of Owner, if there was no previous (0 owner) the selling price is highest, but the 3 owner mean > 1 onwer; we need to check the median value here\n\"\"\"\n# Let's see the relationship of discrete numerical variables with target variable ('SalePrice')\nfor feature in discrete_num_features:\n    dataset.groupby(feature)['Selling_Price'].median().plot.bar()\n\n    plt.xlabel(feature)\n    plt.ylabel('Selling_Price')\n    plt.title(feature)\n    plt.show()\n\"\"\"\n##### Observations: \n1. With the increase in the number of years, we can see a clear decline in Selling Price\n2. In case of Owner, if there was no previous (0 owner) the selling price is highest, but the 3 owner meadian > 1 onwer median.\n\"\"\"\n\"\"\"\n### Continuous Numerical Variables\n\"\"\"\ncontinuous_num_features = [feature for feature in dataset.columns if dataset[feature].dtypes == 'float64']\ncontinuous_num_features\n# dropping target variable from continuous_num_features list\ncontinuous_num_features.remove('Selling_Price')\ncontinuous_num_features\n# Let's analyse the continuous values by creating histograms to understand the distribution\nfor feature in continuous_num_features:\n    dataset[feature].hist(bins=30)\n    plt.xlabel(feature)\n    plt.ylabel('count')\n    plt.title(feature)\n    plt.show()\n# Let's analyse the continuous values by creating histograms to understand the distribution\nfor feature in continuous_num_features:\n    sns.histplot(data=dataset, x=feature, kde=True)\n    plt.xlabel(feature)\n    plt.ylabel('count')\n    plt.title(feature)\n    plt.show()\n\"\"\"\n##### Obseravation: Continuous variables are right skewed (mode < median < mean)\n\"\"\"\n\"\"\"\n### Outliers : Checking outliers in numerical variables\n\"\"\"\n# boxplot to visualize outliers\n\nfor feature in discrete_num_features + continuous_num_features:\n    dataset.boxplot(column = feature)\n    plt.ylabel(feature)\n    plt.title(feature)\n    plt.show()\n\"\"\"\n##### Observations: All the numerical variables have outliers. Had there been any missing values, we would have replaced with median() instead of mean()\n\"\"\"\n\"\"\"\n# Splitting Data\n\"\"\"\nX = dataset.drop('Selling_Price', axis=1)\ny = dataset.Selling_Price\nX.head()\n\"\"\"\n# Categorical variable Encoding\n### Label encoding and One-hot encoding\n\"\"\"\n\"\"\"\n#### Label Encoding for Fuel_Type, Seller_Type, Transmission\n\"\"\"\n# label encoding\ncar_dataset = X.copy()\ncar_dataset.replace({'Fuel_Type':{'Petrol':3, 'Diesel':1, 'CNG':2}}, inplace=True)\ncar_dataset.replace({'Seller_Type':{'Dealer':1, 'Individual':2}}, inplace=True)\ncar_dataset.replace({'Transmission':{'Manual':2, 'Automatic':1}}, inplace=True)\n\"\"\"\n# Train - Test Split\n\"\"\"\nx_train, x_test, y_train, y_test = train_test_split(car_dataset, y, random_state=1, test_size=0.1)\n\"\"\"\n### One-hot encoding for Car-Name\n\"\"\"\nx_train.head()\n# 'handle_unknown' helps to discard categories not seen during fit\nencoder_OH = OneHotEncoder(handle_unknown = 'ignore', sparse=False)\n\ntrain_encoded = pd.DataFrame(encoder_OH.fit_transform(x_train[['Car_Name']]), index = x_train.index)\ntest_encoded = pd.DataFrame(encoder_OH.transform(x_test[['Car_Name']]), index = x_test.index)\n\ntrain_OH = pd.concat([x_train.select_dtypes(include = ['int64', 'float64']), train_encoded], axis = 1)\ntest_OH = pd.concat([x_test.select_dtypes(include = ['int64', 'float64']), test_encoded], axis = 1)\nprint(train_OH.shape)\nprint(test_OH.shape)\n# total number of features = 101\n\"\"\"\n### Feature Selection\n\"\"\"\n# Next setps:\n#     1. feature scaling \n#     2. feature selection using lasso and select from model\n#     3. model building using treebase ensemble models randomforest, extra tree, xgboost\n#     4. use of randomized search cv for hyperparameter tuning\n#     5. selecting the best model out of them\n#     6. printing the test score\ntrain_cols = train_OH.columns\n\n# MinMax scaler object\nscaler = MinMaxScaler()\n\n# transforming train data\nx_train_encoded_scaled = pd.DataFrame(scaler.fit_transform(train_OH), columns = train_cols)\n\n# transforming test data\nx_test_encoded_scaled = pd.DataFrame(scaler.transform(test_OH), columns = train_cols)\n\"\"\"\n## Feature Selection using Lasso regression to select important features\n#### This is the reason why I performed feature scaling\n\"\"\"\n# The bigger the alpha for Lasso, less features gets selected\n# SelectFromModel selects features whose coefficients are non-zero\n# feature selection using training data\nfeature_sel = SelectFromModel(Lasso(alpha = 0.01, random_state=1, max_iter=10000))\nfeature_sel.fit(x_train_encoded_scaled, y_train)\n\nselected_features = x_train_encoded_scaled.columns[feature_sel.get_support()]\nlen(selected_features)\n\"\"\"\n##### Out of 101 features, only 24 got selected\n\"\"\"\nnp.array(selected_features)\n\"\"\"\n# Model building\n\"\"\"\n\"\"\"\n### Refer below articles to know more about Tree based algorithms\n### [Decision trees and ensemble methods do not require feature scaling to be performed as they are not sensitive to the the variance in the data](https:\/\/towardsdatascience.com\/do-decision-trees-need-feature-scaling-97809eaa60c6)\n\n### [ExtraTreesRegressor vs RandomForestRegressor](https:\/\/quantdare.com\/what-is-the-difference-between-extra-trees-and-random-forest\/)\n\"\"\"\n# # ExtraTreesRegressor and RandomForestRegressor have exactly same set of parameters,\n\n# Important differences among them exists as below:\n    # 1. Random forest uses bootstrap replicas (bootstrap == True), i.e., it subsamples the input data with replacement. \n    # But Extra Trees uses the whole original samples (bootstrap == False).\n\n    # 2. Random forest chooses optimum split for splitting nodes (computationally costly), but ExtraTrees chooses splits randomly\n# Considering features selected using lasso regression\nx_train_final = train_OH[selected_features]\nx_test_final = test_OH[selected_features]\nx_train_final.head()\n\"\"\"\n#### Hyper-parameter Tuning\n\"\"\"\nparams_ET_RF = {\n'n_jobs' : [-1],\n'n_estimators' : [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200],\n'criterion' : ['mse', 'mae'],\n'max_depth' : [5, 10, 15, 20, 25, 30],\n'max_features' : ['auto', 'sqrt'],\n'min_samples_split' : [2, 5, 10, 15, 100],\n'min_samples_leaf' : [1, 2, 5, 10]\n}\n\nparams_XGBRegressor = {\n'n_jobs' : [-1],\n'learning_rate' : [0.05, 0.1, 0.15, 0.2, 0.25, 0.3],\n'max_depth' : [3,4,5,6,8,10,12,15],\n'n_estimators' : [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200],\n\"min_child_weight\" : [1,3,5,7],\n\"gamma\" : [0.0, 0.1, 0.2, 0.3, 0.4],\n\"colsample_bytree\" : [0.3, 0.4, 0.5, 0.6]\n}\n\nregressors = [ExtraTreesRegressor(), RandomForestRegressor(), xgb.XGBRegressor()]\nparams = [params_ET_RF, params_ET_RF, params_XGBRegressor]\nnames = ['ExtraTreesRegressor', 'RandomForestRegressor', 'XGBRegressor']\n# looping through each regressor\nfor i in range(3):\n    cv_regressor = RandomizedSearchCV(regressors[i], param_distributions = params[i], n_iter = 5, scoring = 'neg_mean_squared_error', n_jobs=-1, cv = 5)\n    # scorings='roc_auc' for classification problems\n    # scorings='neg_mean_squared_error' for regression problems\n\n    cv_regressor.fit(x_train_final,y_train)\n\n    print(\"************\",names[i],\"************\")\n    print(\"Best estimators: \\n {}\".format(cv_regressor.best_estimator_))\n    print()\n    print(\"Best score: \\n {}\".format(cv_regressor.best_score_))\n    print()\n    print(\"Best parameters: \\n {}\".format(cv_regressor.best_params_))\n    print()\n    print()\n\"\"\"\n##### XGBRegressor performed best\n\"\"\"\n\"\"\"\n### Final Prediction\n\"\"\"\n# defination of final model\nfinal_model = xgb.XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n             colsample_bynode=1, colsample_bytree=0.3, gamma=0.3, gpu_id=-1,\n             importance_type='gain', interaction_constraints='',\n             learning_rate=0.05, max_delta_step=0, max_depth=3,\n             min_child_weight=5,  monotone_constraints='()',\n             n_estimators=1100, n_jobs=-1, num_parallel_tree=1, random_state=0,\n             reg_alpha=0, reg_lambda=1, scale_pos_weight=1, subsample=1,\n             tree_method='exact', validate_parameters=1, verbosity=None)\n\n# fitting and prediction\nfinal_model.fit(x_train_final, y_train)\npredictions = final_model.predict(x_test_final)\n\"\"\"\n## Performance Metrics\n\"\"\"\nfrom sklearn import metrics\n\n# performance metrices\nprint('MAE:', metrics.mean_absolute_error(y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))\n\n\nimport pickle\n# open a file, where you ant to store the data\nfile = open('final_model.pkl', 'wb')\n\n# dump information to that file\npickle.dump(final_model, file)","meta":"{'source': 'AI4Code', 'id': 'b563cf8e28cdf7'}"}
{"id":"82075","text":"\"\"\"\n# Team ASYC notebook\n\"\"\"\n\"\"\"\n*First we installed the necessary libraries:*\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport gc\n\nimport matplotlib.pyplot as plt # matplotlib and seaborn for plotting\nimport matplotlib.patches as patches\nimport seaborn as sns\n\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\npd.set_option('max_columns', 150)\npy.init_notebook_mode(connected=True)\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport os,random, math, psutil, pickle\n\nfrom time import time\nimport datetime\npd.set_option('display.max_columns',100)\npd.set_option('display.float_format', lambda x: '%.5f' % x)\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split,KFold\nfrom sklearn import metrics\nfrom sklearn.metrics import mean_squared_error\nimport lightgbm as lgb\n\nroot = '..\/input\/ashrae-energy-prediction'\nprint(os.listdir(root))\n\"\"\"\nThen we upload the dataframes. \nWe parse the datetime data and use specific dtypes for the building and weather dataframe. \nAlso for the test dataframe we select to read especific columns.\n\"\"\"\ntrain = pd.read_csv(root + \"\/train.csv\", parse_dates=['timestamp'])\n\nweather_train = pd.read_csv(root+\"\/weather_train.csv\",parse_dates=['timestamp'])\n\ntest_cols_to_read = ['building_id','meter','timestamp']\ntest = pd.read_csv(root+\"\/test.csv\",parse_dates=['timestamp'],usecols=test_cols_to_read)\n\nweather_test = pd.read_csv(root + \"\/weather_test.csv\", parse_dates=['timestamp'])\n\nbuilding_meta = pd.read_csv(root + \"\/building_metadata.csv\")\n\nsample_submission = pd.read_csv(root + \"\/sample_submission.csv\")\n\"\"\"\nNow we take a look of the size of the tables:\n\"\"\"\nprint('Size of train data', train.shape)\nprint('Size of weather_train data', weather_train.shape)\nprint('Size of weather_test data', weather_test.shape)\nprint('Size of building_meta data', building_meta.shape)\n\"\"\"\n# Timestamps Adjustments\n\"\"\"\nweather = pd.concat([weather_train,weather_test],ignore_index=True)\nweather_key = ['site_id', 'timestamp']\ntemp_skeleton = weather[weather_key + ['air_temperature']].drop_duplicates(subset=weather_key).sort_values(by=weather_key).copy()\ndata_to_plot = temp_skeleton.copy()\ndata_to_plot[\"hour\"] = data_to_plot[\"timestamp\"].dt.hour\ncount = 1\nplt.figure(figsize=(25, 15))\nfor site_id, data_by_site in data_to_plot.groupby('site_id'):\n    by_site_by_hour = data_by_site.groupby('hour').mean()\n    ax = plt.subplot(4, 4, count)\n    plt.plot(by_site_by_hour.index,by_site_by_hour['air_temperature'],'xb-')\n    ax.set_title('site: '+str(site_id))\n    count += 1\nplt.tight_layout()\nplt.show()\ndel data_to_plot\n\"\"\"\n* We calculate ranks of hourly temperatures within date\/site_id chunks.\n* Then create a dataframe of site_ids (0-16) x mean hour rank of temperature within day (0-23).\n* And we subtract the columnID of temperature peak by 14, getting the timestamp alignment gap.\n* Finally we do a function to align the timestamps.\n\"\"\"\ntemp_skeleton['temp_rank'] = temp_skeleton.groupby(['site_id', temp_skeleton.timestamp.dt.date])['air_temperature'].rank('average')\n\ndf_2d = temp_skeleton.groupby(['site_id', temp_skeleton.timestamp.dt.hour])['temp_rank'].mean().unstack(level=1)\n\nsite_ids_offsets = pd.Series(df_2d.values.argmax(axis=1) - 14)\nsite_ids_offsets.index.name = 'site_id'\n\ndef timestamp_align(df):\n    df['offset'] = df.site_id.map(site_ids_offsets)\n    df['timestamp_aligned'] = (df.timestamp - pd.to_timedelta(df.offset, unit='H'))\n    df['timestamp'] = df['timestamp_aligned']\n    del df['timestamp_aligned']\n    return df\n\"\"\"\nWe reduce the memory size. \nFunction to reduce the DF size:\n\"\"\"\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() \/ 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    end_mem = df.memory_usage().sum() \/ 1024**2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) \/ start_mem))\n    return df\nbuilding_site_dict = dict(zip(building_meta['building_id'], building_meta['site_id']))\nsite_meter_raw = train[['building_id', 'meter', 'timestamp', 'meter_reading']].copy()\nsite_meter_raw['site_id'] = site_meter_raw.building_id.map(building_site_dict)\ndel site_meter_raw['building_id']\nsite_meter_to_plot = site_meter_raw.copy()\nsite_meter_to_plot[\"hour\"] = site_meter_to_plot[\"timestamp\"].dt.hour\nelec_to_plot = site_meter_to_plot[site_meter_to_plot.meter == 0]\ncount = 1\nplt.figure(figsize=(25, 50))\nfor site_id, data_by_site in elec_to_plot.groupby('site_id'):\n    by_site_by_hour = data_by_site.groupby('hour').mean()\n    ax = plt.subplot(15, 4, count)\n    plt.plot(by_site_by_hour.index,by_site_by_hour['meter_reading'],'xb-')\n    ax.set_title('site: '+str(site_id))\n    count += 1\nplt.tight_layout()\nplt.show()\ndel elec_to_plot, site_meter_to_plot, building_site_dict, site_meter_raw\n\"\"\"\n**Reducing memory:**\n\"\"\"\ntrain = reduce_mem_usage(train)\ntest = reduce_mem_usage(test)\nweather_train = reduce_mem_usage(weather_train)\nweather_test = reduce_mem_usage(weather_test)\nbuilding_meta = reduce_mem_usage(building_meta)\nweather_train = timestamp_align(weather_train)\nweather_test = timestamp_align(weather_test)\ndel weather\n\"\"\"\nWe review the dataframes:\n\"\"\"\nprint('train info',train.info())\nprint('-------------------')\nprint('weather_train info', weather_train.info())\nprint('-------------------')\nprint('test info', test.info()) \nprint('-------------------')\nprint('weather_test info', weather_test.info())\nprint('-------------------')\nprint('building info', building_meta.info())\n\"\"\"\n# Exploratory Data Analysis\n## Looking for missing values\n\nWe see the basic statistical measures of the dataframes:\n\"\"\"\ntrain.head()\ntrain.describe(include='all')\n\"\"\"\n* Data contains records from 1st Jan to 31st Dec of 2016.\n* Data has information about 1448 buildings.\n* Data has 4 meter types.\n* Some extremely high values in meter reading which can be explored further.\n\"\"\"\ntest.head()\ntest.describe(include='all')\n\"\"\"\n* Time period in **test data** is 2017 and 2018\n* We see that the test data points are a bit more than the double of the train data points...\n\"\"\"\n\"\"\"\nWe check for missing values on the test and train dataframes:\n\"\"\"\nmissing_train_test = pd.DataFrame(train.isna().sum()\/len(train),columns=[\"Missing_Pct_Train\"])\nmissing_train_test[\"Missing_Pct_Test\"] = test.isna().sum()\/len(test)\nmissing_train_test\n\"\"\"\nNo Missing values in train\/test datasets\n\"\"\"\nbuilding_meta.head()\nbuilding_meta.describe(include='all')\n\"\"\"\n*For the building metadata we see:*\n* There are only 16 different primary uses and Education is the most frecuent with 549 apperances. \n* For the square feet the maximum is 875000 and the minimum is 283.\n* For the year built there is a range between 1900 till 2017. \n* For the floor count the average and median coincide in 3 floors; we see that the maximum floor count is 26.\n* And that there are some missing values for the year_built and floor_count columns.\n\"\"\"\n\"\"\"\nWe divide the number of missing values by the overall number of values to see which columns have missing values:\n\"\"\"\nbuilding_meta.isna().sum()\/len(building_meta)*100\nweather_train.head()\nweather_train.describe()\nweather_test.head()\nweather_test.describe()\n\"\"\"\n* We see that almost all columns have missing values on the weather's datasets.\n* For the columns cloud_coverage and precip_depth_1_hr we see a lot of values = 0.\n\nWe divide the number of missing values by the overall number of values to compare the number of missing values in Weather_Train and Weather_Test:\n\"\"\"\nmissing_weather = pd.DataFrame(weather_train.isna().sum()\/len(weather_train)*100,columns=[\"Weather_Train_Missing_Pct\"]) \nmissing_weather[\"Weather_Test_Missing_Pct\"] = weather_test.isna().sum()\/len(weather_test)*100 \nmissing_weather\n\"\"\"\n* **precip_depth_1_hr variable** and **cloud_coverage variable** have similar number of missing values in both train and test weather data.\n* site_id and timestamp do not have missing values.\n* Other variables have some missing values.\n\"\"\"\n\"\"\"\n### Calculating Min_value and Max_value of the columns in Weather_train:\n\"\"\"\ncols = ['air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr','sea_level_pressure','wind_direction','wind_speed']\nfor col in cols:\n    print (\" Minimum Value of {} column is {}\".format(col,weather_train[col].min()))\n    print (\" Maximum Value of {} column is {}\".format(col,weather_train[col].max()))\n    print (\"----------------------------------------------------------------------\")\nweather_train['timestamp'].describe()\n\"\"\"\n> This data is from 31st Dec 2015 to 31st Dec 2016, similar to the timestamp of the training data\n\"\"\"\n#creating a distplot of columns air_temperature,cloud_coverage,dew_temperature,precip_depth_1_hr,sea_level_pressure,wind_speed\ncols = ['air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr','sea_level_pressure','wind_speed']\nfor ind,col in enumerate(weather_train[cols]):\n    plt.figure(ind)\n    sns.distplot(weather_train[col].dropna())\n\"\"\"\n* Cloud_Coverage takes distinct values unlike these other variables.\n* Dew Temperature looks like a Negatively skewed distribution.\n* Lot of 0 values in precip_depth_1_hr variable.\n* Distribution of sea_level_pressure looks like a normal distribution.\n* Wind_Speed distribution looks like positively skewed.\n\"\"\"\nweather_test['timestamp'].describe()\n\"\"\"\n> The time duration is similar to the test dataset.\n\"\"\"\n\"\"\"\n# Dealing with missing values \n\"\"\"\n\"\"\"\n**Before we start filling missing values, we drop floor_count column as it has more than 75% missing values.** \n> It will manipulate the training data into a different direction if we impute it.<br \/> \n> Also,year_built also has a large number of missing columns, but we leave it for now.\n\"\"\"\nbuilding_meta.drop('floor_count',axis=1,inplace=True)\nbuilding_meta.head()\n\"\"\"\n### We fill out the missing values in the weather columns both in train and test\n\nAs we read so many popular tutorials and suggestion, there are few main solutions to fill in the missing values.\n1. Just ignore the data row \n2. Back-fill or forward-fill to propagate next or previous values respectively\n3. Replace with some constant value outside fixed value range-999,-1 etc.\n4. Replace with mean or median value. \n\n> Most of tutorials implement the way 'the daily mean of each site per month'. It had been proven the most logical and proven method so far.<br \/> \n> We will fill with the mean of the filler object created by grouping site_id, day and month if daily means per month \/ site_id is not available.\n--Ref2 and Ref3 <br \/>\n\"\"\"\n\"\"\"\nFirst, we do for the **building part**:\n\"\"\"\n# since NA values only present in building age fillna can be used\nbuilding_meta.fillna(round(building_meta.year_built.mean(),0),\n                inplace=True)\nbuilding_meta.head()\nbuilding_meta.isna().sum()\n\"\"\"\nWe had quite a deal of missing values in the training and testing dataset, except site_id and time_stamp. \n\"\"\"\n\"\"\"\nFirst We deal with wheather_train\n\"\"\"\n# add month, day of week, day of month and hour \nweather_train['month'] = weather_train['timestamp'].dt.month.astype(np.int8)\nweather_train['day_of_week'] = weather_train['timestamp'].dt.dayofweek.astype(np.int8)\nweather_train['day_of_month']= weather_train['timestamp'].dt.day.astype(np.int8)\nweather_train['hour'] = weather_train['timestamp'].dt.hour\n\n# add is weekend column\nweather_train['is_weekend'] = weather_train.day_of_week.apply(lambda x: 1 if x>=5 else 0)\ndef convert_season(month):\n    if (month <= 2) | (month == 12):\n        return 0\n    # as winter\n    elif month <= 5:\n        return 1\n    # as spring\n    elif month <= 8:\n        return 2\n    # as summer\n    elif month <= 11:\n        return 3\n    # as fall\nweather_train['season'] = weather_train.month.apply(convert_season)\n#Reset Index for Update for training \nweather_train = weather_train.set_index(\n    ['site_id','day_of_month','month'])\n\"\"\"\n**Air temperature**\n\"\"\"\n# create dataframe of daily means per site id \nair_temperature_filler = pd.DataFrame(weather_train\n                                      .groupby(['site_id','day_of_month','month'])\n                                      ['air_temperature'].mean(),\n                                      columns=[\"air_temperature\"])\nair_temperature_filler.isna().sum()\n# create dataframe of air_temperatures to fill\ntemporary_df = pd.DataFrame({'air_temperature' : weather_train.air_temperature})\n\n# update NA air_temperature values\ntemporary_df.update(air_temperature_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"air_temperature\"] = temporary_df[\"air_temperature\"]\n\ndel temporary_df, air_temperature_filler\ngc.collect()\n\"\"\"\n**Cloud Coverage**\n\"\"\"\n# create dataframe of daily means per site id\ncloud_coverage_filler = pd.DataFrame(weather_train\n                                     .groupby(['site_id','day_of_month','month'])\n                                     ['cloud_coverage'].mean(),\n                                     columns = ['cloud_coverage'])\ncloud_coverage_filler.isna().sum()\n\"\"\"\nBecause cloud_coverage takes discrete values and still have some NA value, I will fill it again with rounded mean\n\"\"\"\nround(cloud_coverage_filler.cloud_coverage.mean(),0)\ncloud_coverage_filler.fillna(round(cloud_coverage_filler.cloud_coverage.mean(),0), \n                             inplace=True)\n\n# create dataframe of cloud_coverages to fill\ntemporary_df = pd.DataFrame({'cloud_coverage' : weather_train.cloud_coverage})\n\n# update NA cloud_coverage values\ntemporary_df.update(cloud_coverage_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"cloud_coverage\"] = temporary_df[\"cloud_coverage\"]\n\ndel temporary_df, cloud_coverage_filler\ngc.collect()\n\"\"\"\n**Dew Temperature**\n\"\"\"\n# create dataframe of daily means per site id\ndew_temperature_filler = pd.DataFrame(weather_train\n                                      .groupby(['site_id','day_of_month','month'])\n                                      ['dew_temperature'].mean(),\n                                      columns=[\"dew_temperature\"])\ndew_temperature_filler.isna().sum()\n# create dataframe of dew_temperatures to fill\ntemporary_df = pd.DataFrame({'dew_temperature' : weather_train.dew_temperature})\n\n# update NA dew_temperature values\ntemporary_df.update(dew_temperature_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"dew_temperature\"] = temporary_df[\"dew_temperature\"]\n\ndel temporary_df, dew_temperature_filler\ngc.collect()\n\"\"\"\n**Precip Depth 1 Hour**\n\"\"\"\n# create dataframe of daily means per site id\nprecip_depth_filler = pd.DataFrame(weather_train\n                                   .groupby(['site_id','day_of_month','month'])\n                                   ['precip_depth_1_hr'].mean(),\n                                   columns=['precip_depth_1_hr'])\nprecip_depth_filler.isna().sum()\n\"\"\"\nAs cloud_coverage, I fill NA values of the filler with the rounded mean since the discrete values and still got some NA\n\"\"\"\nround(precip_depth_filler['precip_depth_1_hr'].mean(),0)\nprecip_depth_filler.fillna(round(precip_depth_filler['precip_depth_1_hr'].mean(),0)\n                           , inplace=True)\n\n# create dataframe of precip_depth_1_hr to fill\ntemporary_df = pd.DataFrame({'precip_depth_1_hr' : weather_train.precip_depth_1_hr})\n\n# update NA precip_depth_1_hr values\ntemporary_df.update(precip_depth_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"precip_depth_1_hr\"] = temporary_df[\"precip_depth_1_hr\"]\n\ndel precip_depth_filler, temporary_df\ngc.collect()\n\"\"\"\n**Sea Level Pressure**\n\"\"\"\n# create dataframe of daily means per site id\nsea_level_filler = pd.DataFrame(weather_train\n                                .groupby(['site_id','day_of_month','month'])\n                                ['sea_level_pressure'].mean(),\n                                columns=['sea_level_pressure'])\nsea_level_filler.isna().sum()\n\"\"\"\nWe did the same as with cloud_coverage:\n\"\"\"\nmean_sea_level_pressure = round(\n    sea_level_filler\n    ['sea_level_pressure']\n    .astype(float)\n    .mean(),2)\nsea_level_filler.fillna(mean_sea_level_pressure, inplace=True)\n\n# create dataframe of sea_level_pressure to fill\ntemporary_df = pd.DataFrame({'sea_level_pressure' : weather_train.sea_level_pressure})\n\n# update NA sea_level_pressure values\ntemporary_df.update(sea_level_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"sea_level_pressure\"] = temporary_df[\"sea_level_pressure\"]\n\ndel sea_level_filler, temporary_df\ngc.collect()\n\"\"\"\n**Wind Direction**\n\"\"\"\n# create dataframe of daily means per site id\nwind_direction_filler = pd.DataFrame(weather_train\n                                     .groupby(['site_id','day_of_month','month'])\n                                     ['wind_direction'].mean(),\n                                     columns=['wind_direction'])\nwind_direction_filler.isna().sum()\n# create dataframe of wind_direction to fill\ntemporary_df = pd.DataFrame({'wind_direction' : weather_train.wind_direction})\n\n# update NA wind_direction values\ntemporary_df.update(wind_direction_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"wind_direction\"] = temporary_df[\"wind_direction\"]\n\ndel temporary_df, wind_direction_filler\ngc.collect()\n\"\"\"\n**Wind Speed**\n\"\"\"\n# create dataframe of daily means per site id\nwind_speed_filler = pd.DataFrame(weather_train\n                                 .groupby(['site_id','day_of_month','month'])\n                                 ['wind_speed'].mean(),\n                                 columns=['wind_speed'])\nwind_speed_filler.isna().sum()\n# create dataframe of wind_speed to fill\ntemporary_df = pd.DataFrame({'wind_speed' : weather_train.wind_speed})\n\n# update NA wind_speed values\ntemporary_df.update(wind_speed_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_train[\"wind_speed\"] = temporary_df[\"wind_speed\"]\n\ndel temporary_df, wind_speed_filler\ngc.collect()\n# check if NA values left\nweather_train.isna().sum()\n\"\"\"\nWe reset indexes to transfrom weather dataframe to original form:\n\"\"\"\nweather_train = weather_train.reset_index()\nweather_train.drop('day_of_month',axis=1,inplace=True)\nweather_train.drop('month',axis=1,inplace=True)\nweather_train.drop('day_of_week',axis=1,inplace=True)\nweather_train.drop('hour',axis=1,inplace=True)\nweather_train.drop('is_weekend',axis=1,inplace=True)\nweather_train.drop('season',axis=1,inplace=True)\nweather_train.sample(5)\n\"\"\"\n Repeat again for wheather_test\n\"\"\"\n# add month, day of week, day of month and hour \nweather_test['month'] = weather_test['timestamp'].dt.month.astype(np.int8)\nweather_test['day_of_week'] = weather_test['timestamp'].dt.dayofweek.astype(np.int8)\nweather_test['day_of_month']= weather_test['timestamp'].dt.day.astype(np.int8)\nweather_test['hour'] = weather_test['timestamp'].dt.hour\n\n# add is weekend column\nweather_test['is_weekend'] = weather_test.day_of_week.apply(lambda x: 1 if x>=5 else 0)\n\nweather_test['season'] = weather_test.month.apply(convert_season)\n\n#Reset Index for Update for training \nweather_test = weather_test.set_index(\n    ['site_id','day_of_month','month'])\n\n#Air temperature\n\n\n# create dataframe of daily means per site id \nair_temperature_filler = pd.DataFrame(weather_test\n                                      .groupby(['site_id','day_of_month','month'])\n                                      ['air_temperature'].mean(),\n                                      columns=[\"air_temperature\"])\nair_temperature_filler.isna().sum()\n\n# create dataframe of air_temperatures to fill\ntemporary_df = pd.DataFrame({'air_temperature' : weather_test.air_temperature})\n\n# update NA air_temperature values\ntemporary_df.update(air_temperature_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"air_temperature\"] = temporary_df[\"air_temperature\"]\n\ndel temporary_df, air_temperature_filler\ngc.collect()\n\n#Cloud Coverage\n\n# create dataframe of daily means per site id\ncloud_coverage_filler = pd.DataFrame(weather_test\n                                     .groupby(['site_id','day_of_month','month'])\n                                     ['cloud_coverage'].mean(),\n                                     columns = ['cloud_coverage'])\ncloud_coverage_filler.isna().sum()\n\n#Because cloud_coverage takes discrete values and still have some NA value, I will fill it again with rounded mean\n\nround(cloud_coverage_filler.cloud_coverage.mean(),0)\ncloud_coverage_filler.fillna(round(cloud_coverage_filler.cloud_coverage.mean(),0), \n                             inplace=True)\n\n# create dataframe of cloud_coverages to fill\ntemporary_df = pd.DataFrame({'cloud_coverage' : weather_test.cloud_coverage})\n\n# update NA cloud_coverage values\ntemporary_df.update(cloud_coverage_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"cloud_coverage\"] = temporary_df[\"cloud_coverage\"]\n\ndel temporary_df, cloud_coverage_filler\ngc.collect()\n\n#Dew Temperature\n\n# create dataframe of daily means per site id\ndew_temperature_filler = pd.DataFrame(weather_test\n                                      .groupby(['site_id','day_of_month','month'])\n                                      ['dew_temperature'].mean(),\n                                      columns=[\"dew_temperature\"])\ndew_temperature_filler.isna().sum()\n\n# create dataframe of dew_temperatures to fill\ntemporary_df = pd.DataFrame({'dew_temperature' : weather_test.dew_temperature})\n\n# update NA dew_temperature values\ntemporary_df.update(dew_temperature_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"dew_temperature\"] = temporary_df[\"dew_temperature\"]\n\ndel temporary_df, dew_temperature_filler\ngc.collect()\n\n#Precip Depth 1 Hour\n\n# create dataframe of daily means per site id\nprecip_depth_filler = pd.DataFrame(weather_test\n                                   .groupby(['site_id','day_of_month','month'])\n                                   ['precip_depth_1_hr'].mean(),\n                                   columns=['precip_depth_1_hr'])\nprecip_depth_filler.isna().sum()\n\n#As cloud_coverage, I fill NA values of the filler with the rounded mean since the discrete values and still got some NA\n\n\nround(precip_depth_filler['precip_depth_1_hr'].mean(),0)\nprecip_depth_filler.fillna(round(precip_depth_filler['precip_depth_1_hr'].mean(),0)\n                           , inplace=True)\n\n# create dataframe of precip_depth_1_hr to fill\ntemporary_df = pd.DataFrame({'precip_depth_1_hr' : weather_test.precip_depth_1_hr})\n\n# update NA precip_depth_1_hr values\ntemporary_df.update(precip_depth_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"precip_depth_1_hr\"] = temporary_df[\"precip_depth_1_hr\"]\n\ndel precip_depth_filler, temporary_df\ngc.collect()\n\n#Sea Level Pressure\n\n# create dataframe of daily means per site id\nsea_level_filler = pd.DataFrame(weather_test\n                                .groupby(['site_id','day_of_month','month'])\n                                ['sea_level_pressure'].mean(),\n                                columns=['sea_level_pressure'])\nsea_level_filler.isna().sum()\n\n#We did the same as with cloud_coverage:\n\nmean_sea_level_pressure = round(\n    sea_level_filler\n    ['sea_level_pressure']\n    .astype(float)\n    .mean(),2)\n\nsea_level_filler.fillna(mean_sea_level_pressure, inplace=True)\n\n# create dataframe of sea_level_pressure to fill\ntemporary_df = pd.DataFrame({'sea_level_pressure' : weather_test.sea_level_pressure})\n\n# update NA sea_level_pressure values\ntemporary_df.update(sea_level_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"sea_level_pressure\"] = temporary_df[\"sea_level_pressure\"]\n\ndel sea_level_filler, temporary_df\ngc.collect()\n\n#Wind Direction\n\n# create dataframe of daily means per site id\nwind_direction_filler = pd.DataFrame(weather_test\n                                     .groupby(['site_id','day_of_month','month'])\n                                     ['wind_direction'].mean(),\n                                     columns=['wind_direction'])\nwind_direction_filler.isna().sum()\n\n# create dataframe of wind_direction to fill\ntemporary_df = pd.DataFrame({'wind_direction' : weather_test.wind_direction})\n\n# update NA wind_direction values\ntemporary_df.update(wind_direction_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"wind_direction\"] = temporary_df[\"wind_direction\"]\n\ndel temporary_df, wind_direction_filler\ngc.collect()\n\n#Wind Speed\n\n\n# create dataframe of daily means per site id\nwind_speed_filler = pd.DataFrame(weather_test\n                                 .groupby(['site_id','day_of_month','month'])\n                                 ['wind_speed'].mean(),\n                                 columns=['wind_speed'])\nwind_speed_filler.isna().sum()\n\n# create dataframe of wind_speed to fill\ntemporary_df = pd.DataFrame({'wind_speed' : weather_test.wind_speed})\n\n# update NA wind_speed values\ntemporary_df.update(wind_speed_filler, overwrite=False)\n\n# update in the weather train dataset\nweather_test[\"wind_speed\"] = temporary_df[\"wind_speed\"]\n\ndel temporary_df, wind_speed_filler\ngc.collect()\n\n# check if NA values left\nweather_test.isna().sum()\n\n#We reset indexes to transfrom weather dataframe to original form:\n\nweather_test = weather_test.reset_index()\n\nweather_test.drop('day_of_month',axis=1,inplace=True)\nweather_test.drop('month',axis=1,inplace=True)\nweather_test.drop('day_of_week',axis=1,inplace=True)\nweather_test.drop('hour',axis=1,inplace=True)\nweather_test.drop('is_weekend',axis=1,inplace=True)\nweather_test.drop('season',axis=1,inplace=True)\n\nweather_test.sample(5)\n\"\"\"\n## We merge train data (train, building, weather) into 1 dataframe:\n\"\"\"\ntrain_total = pd.merge(train,building_meta,how='left',on='building_id')\ntrain_total = pd.merge(train_total,weather_train,how='left',on=[\"site_id\", \"timestamp\"])\ntrain_total.info()\ntrain_total.sample(5)\n\"\"\"\n## We merge test data (train, building, weather) into 1 dataframe:\n\"\"\"\ntest_total = pd.merge(test,building_meta,how='left',on='building_id')\ntest_total = pd.merge(test_total,weather_test,how='left',on=[\"site_id\", \"timestamp\"])\n\ntest_total.info()\ntest_total.head()\n\"\"\"\n# Looking for unique values\n\"\"\"\ndef feat_value_count(df,colname):\n    \"\"\"value count of each feature\n    \n    Args\n    df: data frame.\n    colname: string. Name of to be valued column\n    \n    Returns\n    df_count: data frame.\n    \"\"\"\n    df_count = df[colname].value_counts().to_frame().reset_index()\n    df_count = df_count.rename(columns={'index':colname+'_values',colname:'counts'})\n    return df_count\n\nfeat_value_count(train,'building_id')\n\"\"\"\nA total of 1449 buildings are in **train data**. Building 1298,1249 has the most records and building 403 has the least records.\n\"\"\"\nfeat_value_count(test,'building_id')\n\"\"\"\nA total of 1449 buildings are in **test data**. Buildings 1258,1241,1331,1301... have the most records and building 0,666,667,668,669... have the least records. Many buildings have same amout of records. Maybe make sense to check the distribution.\n\"\"\"\nlen(set(train.building_id) & set(test.building_id))\n\"\"\"\nWe use the function **set()** and the command **&** so that we identify the intersection between the train and the test dataframes. We need to predict all 1449 building meter readings. All buildings that need to be predicted appear in train data.\n\"\"\"\ntrain_total['meter'].replace({0:\"Electricity\",1:\"ChilledWater\",2:\"Steam\",3:\"HotWater\"},inplace=True)\ntest_total['meter'].replace({0:\"Electricity\",1:\"ChilledWater\",2:\"Steam\",3:\"HotWater\"},inplace=True)\nfeat_value_count(train_total,'meter')\nsns.countplot(train_total['meter'])\nplt.title(\"Distribution of Meter Id Code\")\nplt.xlabel(\"Meter Id Code\")\nplt.ylabel(\"Frequency\")\n\"\"\"\n* Not every building has all meter types. Electricity has the most records.\n\"\"\"\nfeat_value_count(weather_train,'site_id')\n\"\"\"\nThere are 15 locations according to the weather data\n\"\"\"\nfeat_value_count(building_meta,'primary_use')\nplt.figure(figsize=(8,6))\nbuilding_meta['primary_use'].value_counts().sort_values().plot(kind='bar')\nplt.title(\"Count of Primary_Use Variable in the Metadata table\")\nplt.xlabel(\"Primary Use\")\nplt.ylabel(\"Count\")\nplt.xticks(rotation=90)\n\"\"\"\n* There are 15 primary use of buildings. \n* Most buildings are for education, the least is for religious worship. \n* Education, Office, Entertainment\/Public Assembly, Public Services, Lodging\/Residential form the bulk of Primary Use. \n* Education and office occupies 57% of all buildings.\n\"\"\"\nbuilding_meta['primary_use'].value_counts(normalize=True)\n\"\"\"\n> Since there are a lot of categories which are a minor percentage of the whole, it makes sense to combine them.\n\nWe therefore combine all categories with minor percentage:\n\"\"\"\nbuilding_meta['primary_use'].replace({\"Healthcare\":\"Other\",\"Parking\":\"Other\",\"Warehouse\/storage\":\"Other\",\"Manufacturing\/industrial\":\"Other\",\n                                \"Retail\":\"Other\",\"Services\":\"Other\",\"Technology\/science\":\"Other\",\"Food sales and service\":\"Other\",\n                                \"Utility\":\"Other\",\"Religious worship\":\"Other\"},inplace=True)\nfeat_value_count(building_meta,'site_id')\nsns.countplot(building_meta['site_id'])\nplt.title(\"Count of Site_id in the Metadata table\")\nplt.xlabel(\"Site_Id\")\nplt.ylabel(\"Count\")\n\"\"\"\n* Out of 1449 buildings and 15 sites, site 3 has most buildings.\n\"\"\"\nbuilding_meta['square_feet'].describe()\n\"\"\"\n**We created distplot of Distribution of Square Feet variable of Metadata Table**\n\"\"\"\nsns.distplot(building_meta['square_feet'])\nplt.title(\"Distribution of Square Feet variable of Metadata Table\")\nplt.xlabel(\"Area in Square Feet\")\nplt.ylabel(\"Frequency\")\n\"\"\"\nLooks like a normal distribution distribution.\n\"\"\"\nbuilding_meta['square_feet'] = np.log1p(building_meta['square_feet'])\nbuilding_meta.groupby('primary_use')['square_feet'].agg(['mean','median','count']).sort_values(by='count')\n\"\"\"\nWe obtain the mean, median, count of grouped by columns primary_use, square_feet:\n* Others (Parking) has the highest average although the count is less.\n* Education has the highest count as can be seen in the countplot above.\n\"\"\"\nbuilding_meta['year_built'].value_counts().sort_values().plot(kind='bar',figsize=(15,6))\nplt.xlabel(\"Year Built\")\nplt.ylabel(\"Count\")\nplt.title(\"Distribution of Year Built Variable\")\nbuilding_meta.groupby('primary_use')['square_feet'].agg(['count','mean','median']).sort_values(by='count')\ncols = ['site_id','primary_use','building_id','year_built']\nfor col in cols:\n    print (\"Number of Unique Values in the {} column are:\".format(col),building_meta[col].nunique())\n\"\"\"\n### Now we take a single building 1258 to analyze the meter variable (our target):\n\"\"\"\ndf_one_building = train_total[train_total.building_id == 1258]\ndf_one_building.head()\nsns.lineplot(x='timestamp',y='meter_reading',data=df_one_building[train_total.meter == 'Electricity']).set_title('electricity of building 1258')\n\"\"\"\nWith a Electricity lineplot we see that **in spring**, less electricity is used.\n\"\"\"\nsns.lineplot(x='timestamp',y='meter_reading',data=df_one_building[train_total.meter == 'ChilledWater']).set_title('chilledwater of building 1258')\n\"\"\"\nWith a Chilled water lineplot we see that **in summer**, more chilled water is used.\n\"\"\"\nsns.lineplot(x='timestamp',y='meter_reading',data=df_one_building[train_total.meter == 'Steam']).set_title('steam of building 1258')\n\"\"\"\nIn winter, more steam is used for heating.\n\"\"\"\nsns.lineplot(x='timestamp',y='meter_reading',data=df_one_building[train_total.meter == 'HotWater']).set_title('hotwater of building 1258')\n\"\"\"\nIn summmer there is very low consumption of hot water, but in winter very high consumption.\n\"\"\"\ndf_lots_building = train_total[train_total['building_id'].isin([1258,1298,1249])]\nmeasures = ['Electricity', 'ChilledWater', 'Steam', 'HotWater']\nfor i in measures:\n    f, ax = plt.subplots(figsize=(15, 6))\n    sns.lineplot(x='timestamp',y='meter_reading', hue = 'building_id',legend='brief',\n             data=df_lots_building[df_lots_building.meter == i]);\n#del df_lots_building\n#gc.collect()\n\"\"\"\nIn Multiple buildings the patterns of energy consumption is quite consistent. Building 1258 has the highest consumption.\n\"\"\"\ntrain_total.groupby('meter')['meter_reading'].agg(['min','max','mean','median','count','std'])\n\"\"\"\nWe can see that Steam meter has some values that are very high maximum values, we have to explore further. \nMinimum value for all 4 types of meter is 0.\n\"\"\"\nfor df in [train_total, test_total]:\n    df['Month'] = df['timestamp'].dt.month.astype(\"uint8\")\n    df['DayOfMonth'] = df['timestamp'].dt.day.astype(\"uint8\")\n    df['DayOfWeek'] = df['timestamp'].dt.dayofweek.astype(\"uint8\")\n    df['Hour'] = df['timestamp'].dt.hour.astype(\"uint8\")\n\"\"\"\n### Meter_reading is grouped by meter and month. Max, mean, median, count and std are calculated:\n\"\"\"\ntrain_total.groupby(['meter','Month'])['meter_reading'].agg(['max','mean','median','count','std'])\n\"\"\"\n* We can see that only Steam meter has very high meter_reading values as compared to other types of meters.\n* We can see that the average electricity meter_reading does not vary much across the months.\n* Average Hot Water meter_reading is relatively less from April to October Months.\n* Average Steam meter_reading is way higher from March to June as compared to the other months.\n\"\"\"\n\"\"\"\n### Meter_reading is grouped by meter and dayofweek. Max, mean, median, count and std are calculated:\n\"\"\"\ntrain_total.groupby(['meter','DayOfWeek'])['meter_reading'].agg(['max','mean','median','count','std'])\n\"\"\"\n* Average meter_reading of Steam type of meter is higher as compared to the other meter types.\n\"\"\"\ntrain_total['meter_reading'].describe()\n\"\"\"\n**We create a distplot Distribution of Log of Meter Reading Variable:**\n\"\"\"\nsns.distplot(np.log1p(train_total['meter_reading']),kde=False)\nplt.title(\"Distribution of Log of Meter Reading Variable\")\n\"\"\"\n* Lot of 0 values as can be seen from the distribution\n\"\"\"\n\"\"\"\n### Converting the dependent variable to logarithmic scale:\n\"\"\"\ntrain_total['meter_reading'] = np.log1p(train_total['meter_reading'])\nsns.distplot(train_total[train_total['meter'] == \"Electricity\"]['meter_reading'],kde=False)\nplt.title(\"Distribution of Meter Reading per MeterID code: Electricity\")\nsns.distplot(train_total[train_total['meter'] == \"ChilledWater\"]['meter_reading'],kde=False)\nplt.title(\"Distribution of Meter Reading per MeterID code: Chilledwater\")\nsns.distplot(train_total[train_total['meter'] == \"Steam\"]['meter_reading'],kde=False)\nplt.title(\"Distribution of Meter Reading per MeterID code: Steam\")\nsns.distplot(train_total[train_total['meter'] == \"HotWater\"]['meter_reading'],kde=False)\nplt.title(\"Distribution of Meter Reading per MeterID code: Hotwater\")\n\"\"\"\n> There is some discrepancy in the meter_readings for different ste_id's and buildings. It makes sense to delete them. Ref1\n\"\"\"\nidx_to_drop = list((train_total[(train_total['site_id'] == 0) & (train_total['timestamp'] < \"2016-05-21 00:00:00\")]).index)\ntrain_total.drop(idx_to_drop,axis='rows',inplace=True)\n\"\"\"\n# Method Kfold and LightGBM\n\"\"\"\n\"\"\"\nGBM stands for **Gradient Boosting Machine**. It is an ensamble model of decision trees that works on reducing the residual errors. The most time-consuming part is to find the best split points. \n\nLightGBM contains the techniques of **Gradient-based One-Side Sampling** and **Exclusive Feature Bundling** to deal with large number of data instances and large number of features respectively.\n\n\"\"\"\ndef label_encoder(df, categorical_columns=None):\n    \"\"\"Encode categorical values as integers (0,1,2,3...) with pandas.factorize. \"\"\"\n    # if categorical_colunms are not given than treat object as categorical features\n    if not categorical_columns:\n        categorical_columns = [col for col in df.columns if df[col].dtype == 'object']\n    for col in categorical_columns:\n        df[col], uniques = pd.factorize(df[col])\n    return df, categorical_columns;\ntrain_total,colname = label_encoder(train_total, categorical_columns=['primary_use'])\ntest_total,colname = label_encoder(test_total, categorical_columns=['primary_use']);\n\"\"\"\nThen we set a parameter:\n\"\"\"\nparams = {'objective':'regression',\n          'boosting_type':'gbdt',\n          'metric':'rmse',\n          'learning_rate':0.1,\n          'num_leaves': 2**8,\n          'max_depth':-1,\n          'colsample_bytree':0.5,\n          'feature_fraction':0.7,\n          'subsample_freq':1,\n          'subsample':0.7,\n          'verbose':-1,\n          'num_threads':8,\n          'seed': 47,} ;\ncategory_cols = ['building_id', 'site_id', 'primary_use'];\n#%% create feature: age\ntrain_total['age'] = train_total['year_built'].max() - train_total['year_built'] + 1\ntest_total['age'] = test_total['year_built'].max() - test_total['year_built'] + 1\n\"\"\"\n### Label encoding: dealing with categorical variables.\n\"\"\"\nle = LabelEncoder()\ntrain_total['primary_use'] = train_total['primary_use'].astype(str)\ntrain_total['primary_use'] = le.fit_transform(train_total['primary_use']).astype(np.int8)\n\ntest_total['primary_use'] = test_total['primary_use'].astype(str)\ntest_total['primary_use'] = le.fit_transform(test_total['primary_use']).astype(np.int8)\n#%% divide time into columns of month,weekofyear,dayofyear... and log squarefeet in both training and testing data\n\ntrain_total['month_datetime'] = train_total['timestamp'].dt.month.astype(np.int8)\ntrain_total['weekofyear_datetime'] = train_total['timestamp'].dt.weekofyear.astype(np.int8)\ntrain_total['dayofyear_datetime'] = train_total['timestamp'].dt.dayofyear.astype(np.int16)\n    \ntrain_total['hour_datetime'] =train_total['timestamp'].dt.hour.astype(np.int8)  \ntrain_total['day_week'] = train_total['timestamp'].dt.dayofweek.astype(np.int8)\ntrain_total['day_month_datetime'] = train_total['timestamp'].dt.day.astype(np.int8)\ntrain_total['week_month_datetime'] = train_total['timestamp'].dt.day\/7\ntrain_total['week_month_datetime'] = train_total['week_month_datetime'].apply(lambda x: math.ceil(x)).astype(np.int8)\n    \ntrain_total['year_built'] = train_total['year_built']-1900\ntrain_total['square_feet'] = np.log(train_total['square_feet'])\ntest_total['month_datetime'] = test_total['timestamp'].dt.month.astype(np.int8)\ntest_total['weekofyear_datetime'] = test_total['timestamp'].dt.weekofyear.astype(np.int8)\ntest_total['dayofyear_datetime'] = test_total['timestamp'].dt.dayofyear.astype(np.int16)\n    \ntest_total['hour_datetime'] = test_total['timestamp'].dt.hour.astype(np.int8)\ntest_total['day_week'] = test_total['timestamp'].dt.dayofweek.astype(np.int8)\ntest_total['day_month_datetime'] = test_total['timestamp'].dt.day.astype(np.int8)\ntest_total['week_month_datetime'] = test_total['timestamp'].dt.day\/7\ntest_total['week_month_datetime'] = test_total['week_month_datetime'].apply(lambda x: math.ceil(x)).astype(np.int8)\n    \ntest_total['year_built'] = test_total['year_built']-1900\ntest_total['square_feet'] = np.log(test_total['square_feet'])\ntrain_total['meter']= le.fit_transform(train_total['meter']).astype(np.int8)\ntest_total['meter']= le.fit_transform(test_total['meter']).astype(np.int8)\n#%% drop columns\n\nfrom tqdm import tqdm\ndrop_cols = [ \"sea_level_pressure\", \"wind_speed\",\"timestamp\"]\ntarget = np.log1p(train_total[\"meter_reading\"])  \ntrain_df = train_total.drop(drop_cols, axis=1)\ncategoricals = [\"site_id\", \"building_id\", \"primary_use\",  \"meter\",  \"wind_direction\"]\nnumericals = [\"square_feet\", \"year_built\", \"air_temperature\", \"cloud_coverage\",\n              \"dew_temperature\", 'precip_depth_1_hr']\nfeat_cols = categoricals + numericals\n#%% modeling\nfrom sklearn.model_selection import KFold, StratifiedKFold\nparams = {\n            'boosting_type': 'gbdt',\n            'objective': 'regression',\n            'metric': {'rmse'},\n            'subsample_freq': 1,\n            'learning_rate': 0.3,\n            'bagging_freq': 5,\n            'num_leaves': 330,\n            'feature_fraction': 0.9,\n            'lambda_l1': 1,  \n            'lambda_l2': 1\n            }\n\nfolds = 5\nseed = 666\nshuffle = False\nkf = KFold(n_splits=folds, shuffle=shuffle, random_state=seed)\n \nmodels = []\nfor train_index, val_index in kf.split(train_total[feat_cols], train_total['building_id']):\n    train_X = train_total[feat_cols].iloc[train_index]\n    val_X = train_total[feat_cols].iloc[val_index]\n    train_y = target.iloc[train_index]\n    val_y = target.iloc[val_index]\n    lgb_train = lgb.Dataset(train_X, train_y, categorical_feature=categoricals)\n    lgb_eval = lgb.Dataset(val_X, val_y, categorical_feature=categoricals)\n    gbm = lgb.train(params,\n                lgb_train,\n                num_boost_round=500,\n                valid_sets=(lgb_train, lgb_eval),\n                early_stopping_rounds=50,\n                verbose_eval = 50)\n    models.append(gbm)\n#%%see which variables are the most relevant\nfeature_imp = pd.DataFrame(sorted(zip(gbm.feature_importance(), gbm.feature_name()),reverse = True), columns=['Value','Feature'])\nplt.figure(figsize=(10, 5))\nsns.barplot(x=\"Value\", y=\"Feature\", data=feature_imp.sort_values(by=\"Value\", ascending=False))\nplt.title('LightGBM FEATURES')\nplt.tight_layout()\nplt.show();\ntest_total = test_total[feat_cols]\ni=0\nres=[]\nstep_size = 50000\nfor j in tqdm(range(int(np.ceil(test_total.shape[0]\/50000)))):\n    res.append(np.expm1(sum([model.predict(test_total.iloc[i:i+step_size]) for model in models])\/folds))\n    i+=step_size \n\n#%% remove the columns that cannot be calculated in the test data and rerun the last step. DataFrame.dtypes for data must be int, float or bool.\n\nres = np.concatenate(res)\n#%% submission. all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 100000 and the array at index 416 has size 97600\nsample_submission = pd.read_csv(root + \"\/sample_submission.csv\")\nsample_submission['meter_reading'] = res\nsample_submission.loc[sample_submission['meter_reading']<0, 'meter_reading'] = 0\nsample_submission.to_csv('submission.csv', index=False)\n\n#%%\n#submission.shape\nos.chdir(r'\/kaggle\/working')\n#df_name.to_csv(r'df_name.csv')\nfrom IPython.display import FileLink\nFileLink(r'submission.csv')\ntrain_total.head()\n\"\"\"\n# Scores results\n[![Captura%20de%20Pantalla%202020-01-20%20a%20la%28s%29%2017.32.21.png](attachment:Captura%20de%20Pantalla%202020-01-20%20a%20la%28s%29%2017.32.21.png)](http:\/\/)\n\"\"\"\n\"\"\"\n![Captura%20de%20Pantalla%202020-01-20%20a%20la%28s%29%2019.03.53.png](attachment:Captura%20de%20Pantalla%202020-01-20%20a%20la%28s%29%2019.03.53.png)\n\"\"\"\n\"\"\"\n# Lessons learned and outlook\n**IN GENERAL:**\n1. We found \u2018modin\u2019 library can help accelerate pandas even on the laptop and so we tried to install it in windows. We learned that:\n    * Pip install \u201cmodin[dask]\u201d is ran in the command line, therefore, the code should be put in the command in terminal instead of interpreter.\n    * If still get error when using modin to read data, it\u2019s because Windows doesn\u2019t support Ray which is the dependency of modin. To use it, we have to install WSL. But it would easier for laptops using Linux or Mac.\n    * We didn\u2019t use it in the end because we don\u2019t want to install more applications.\n2.\tDataFrame.dtypes for data must be int, float or bool.\n3.\tDifference between statistics modeling (e.g. linear regression) and machine learning:\n    * Statistical modeling is more about finding relationships between variables and the significance of those relationships. Test data is not necessary but we analyze confidential intervals, p value, test value to access the model\u2019s accuracy.\n    * Machine learning is more about prediction results, we don\u2019t care much if the model is interpretable. Test data is normally needed to validate results\u2019 accuracy.\n4.\tEven though in machine learning, we don\u2019t care much about the independency\/collinearity problems, but we still should ensure that the training data is as clean as possible, therefore, we should still drop the useless columns, which also reduce the data size and increase the speed.\n5. The cells took to much time to execute, this was very annoying. It felt like a waste of time.\n6. It was initially difficult to understand the different data sets and the connections between them. It took us some time to get the hang of it.\n7. We encountered many unknown methods, so we had to research what each method does in order to use it properly.\n\n**FOR THE MISSING VALUES:**\n\nAfter tried several different solutions without efficiency, we saw a tutorial indicating a really simple but useful action before start looking for proper ML. This tutorial mentioned that it's better **to calculate a ''common-sense'' baseline**. This baseline is defined in how a person who has knowledge in that field would solve the problem without using any data science tricks. Alternatively, it can be a dummy or simple algorithm, consisting of few lines of code, to use as a baseline metric.\nBaseline metrics can be different in regression and classification problems. For a regression problem, it can be a central tendency measure as the result for all predictions, such as the mean or the median. Since this is a regression problem and competition's results will be evaluated for root mean squared logarithmic error. Baseline metrics are important in a way that, if a ML model cannot beat the simple and intuitive prediction of a person's or an algorithm's guess, the original problem needs reconsideration or training data needs reframing.\ne.g.The baseline guess is a score of 4.38\nBaseline Performance on the valid set: RMSE = 2.1070\nHowever, when we try linear regression, RMSE of the linear regression model is: 1.9895562449483846 without too much difference. Then why we are going to use such ML for prediction? By doing so, it's really easy to do the benchmark even if we don't start with any complicated statistics.\n\n\"\"\"\n\"\"\"\n# References\n\nRef1: **As per the discussion in the following thread, https:\/\/www.kaggle.com\/c\/ashrae-energy-prediction\/discussion\/117083, there is some discrepancy in the meter_readings for different ste_id's and buildings. It makes sense to delete them**\n\nRef2: https:\/\/www.kaggle.com\/aitude\/ashrae-kfold-lightgbm-without-leak-1-08\n\nRef3: https:\/\/www.kaggle.com\/cereniyim\/save-the-energy-for-the-future-2-fe-lightgbm\n\nRef4: https:\/\/www.kaggle.com\/nz0722\/aligned-timestamp-lgbm-by-meter-type\n\nOthers:\n\nhttps:\/\/www.kaggle.com\/migglu\/odyssey-towards-a-sustainable-built-environment#Modeling-and-prediction\nRandom forest: https:\/\/www.kaggle.com\/holoong9291\/ashrae-great-energy-predict\nhttps:\/\/www.kaggle.com\/aldrinl\/eda-rf-ashrae-great-energy-predictor\nLightgbm https:\/\/www.kaggle.com\/kaushal2896\/ashrae-eda-fe-lightgbm-1-12\nLightgbm: https:\/\/www.kaggle.com\/isaienkov\/lightgbm-fe-1-19\nKfold lightgbm: https:\/\/www.kaggle.com\/aitude\/ashrae-kfold-lightgbm-without-leak-1-08\nStratified lightgb,: https:\/\/www.kaggle.com\/roydatascience\/ashrae-energy-prediction-using-stratified-kfold\nhttps:\/\/www.kaggle.com\/cereniyim\/save-the-energy-for-the-future-3-predictions\nhttps:\/\/www.kaggle.com\/cereniyim\/save-the-energy-for-the-future-2-fe-lightgbm#-4.-Compare-Several-Machine-Learning-Models-\n\nhttps:\/\/www.kaggle.com\/jaseziv83\/a-deep-dive-eda-into-all-variables\nhttps:\/\/www.kaggle.com\/ishaan45\/pandas-profiling-missing-value-imputation\nhttps:\/\/www.kaggle.com\/caesarlupum\/ashrae-start-here-a-gentle-introduction#14.-Handling-missing-values\nhttps:\/\/www.kaggle.com\/kaushal2896\/ashrae-eda-fe-lightgbm-1-12\nhttps:\/\/www.kaggle.com\/aitude\/ashrae-missing-weather-data-handling\nhttps:\/\/www.kaggle.com\/vikassingh1996\/ashrae-great-energy-insightful-eda-fe-lgbm\nhttps:\/\/www.kaggle.com\/cereniyim\/save-the-energy-for-the-future-2-fe-lightgbm\nhttps:\/\/www.kaggle.com\/drcapa\/ashrae-feature-engineering-merge-data\n\n\nhttps:\/\/www.youtube.com\/watch?v=ErDgauqnTHk - Gopal Prasad Malakar\nhttps:\/\/www.youtube.com\/watch?v=l3OmtvcaTmM&list=PL1UM2yYgxPh-2kKL53wCsBQP5MoCBvH1z&index=5 Ligdi Gonzalez\nhttps:\/\/www.youtube.com\/watch?v=F7xj8H_p288&list=PL1UM2yYgxPh-2kKL53wCsBQP5MoCBvH1z&index=6 - Ligdi Gonzalez\nhttps:\/\/www.microsoft.com\/en-us\/research\/wp-content\/uploads\/2017\/11\/lightgbm.pdf\n\"\"\"\n\"\"\"\n## Previous Code\n\nfor df in [train, test]:\n    df['air_temperature'] = df['air_temperature'].astype('float16')\n    df['cloud_coverage'] = df['cloud_coverage'].astype(\"float16\")\n    df['dew_temperature'] = df['dew_temperature'].astype('float16')\n    df['precip_depth_1_hr'] = df['precip_depth_1_hr'].astype('float32')\n    df['sea_level_pressure'] = df['sea_level_pressure'].astype('float32')\n    df['wind_direction'] = df['wind_direction'].astype('float32')\n    df['wind_speed'] = df['wind_speed'].astype('float16')\n    df['square_feet'] = df['square_feet'].astype(\"float32\")\n    df['building_id'] = df['building_id'].astype(\"int16\")\n    \ntrain.drop('timestamp',axis=1,inplace=True)\ntest.drop('timestamp',axis=1,inplace=True)\n\ntrain['number_unique_meter_per_building']\ntrain['mean_meter_reading_per_building']\ntrain['median_meter_reading_per_building']\ntrain['std_meter_reading_per_building']\n\ntrain['mean_meter_reading_on_year_built']\ntrain['median_meter_reading_on_year_built']\ntrain['std_meter_reading_on_year_built']\n\ntrain['mean_meter_reading_per_meter']\ntrain['median_meter_reading_per_meter']\ntrain['std_meter_reading_per_meter']\n\ntrain['mean_meter_reading_per_primary_usage']\ntrain['median_meter_reading_per_primary_usage']\ntrain['std_meter_reading_per_primary_usage']\n\ntrain['mean_meter_reading_per_site_id']\ntrain['median_meter_reading_per_site_id']\ntrain['std_meter_reading_per_site_id']\n\nThen again but with the test dataset.\n\nle = LabelEncoder()\n\ntrain['meter']= le.fit_transform(train['meter']).astype(\"uint8\")\ntest['meter']= le.fit_transform(test['meter']).astype(\"uint8\")\ntrain['primary_use']= le.fit_transform(train['primary_use']).astype(\"uint8\")\ntest['primary_use']= le.fit_transform(test['primary_use']).astype(\"uint8\")\n\nCheck the correlation between the variables and eliminate the one's that have high correlation.Threshold for removing correlated variables:\nthreshold = 0.9\n\nAbsolute value correlation matrix\ncorr_matrix = train.corr().abs()\ncorr_matrix.head()\n\nUpper triangle of correlations\nupper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))\nupper.head()\n\nSelect columns with correlations above threshold\nto_drop = [column for column in upper.columns if any(upper[column] > threshold)]\n\nprint('There are %d columns to remove.' % (len(to_drop)))\nprint (\"Following columns can be dropped {}\".format(to_drop))\n\ntrain.drop(to_drop,axis=1,inplace=True)\ntest.drop(to_drop,axis=1,inplace=True)\n\ny = train['meter_reading']\ntrain.drop('meter_reading',axis=1,inplace=True)\n\ncategorical_cols = ['building_id','Month','meter','Hour','primary_use','DayOfWeek','DayOfMonth']\n\n%%time\nx_train,x_test,y_train,y_test = train_test_split(train,y,test_size=0.25,random_state=42)\nprint (x_train.shape)\nprint (y_train.shape)\nprint (x_test.shape)\nprint (y_test.shape)\n\nlgb_train = lgb.Dataset(x_train, y_train,categorical_feature=categorical_cols)\nlgb_test = lgb.Dataset(x_test, y_test,categorical_feature=categorical_cols)\ndel x_train, x_test , y_train, y_test\n\nparams = {'feature_fraction': 0.75,\n          'bagging_fraction': 0.75,\n          'objective': 'regression',\n          'max_depth': -1,\n          'learning_rate': 0.15,\n          \"boosting_type\": \"gbdt\",\n          \"bagging_seed\": 11,\n          \"metric\": 'rmse',\n          \"verbosity\": -1,\n          'reg_alpha': 0.5,\n          'reg_lambda': 0.5,\n          'random_state': 47\n         }\n\nreg = lgb.train(params, lgb_train, num_boost_round=3000, valid_sets=[lgb_train, lgb_test], early_stopping_rounds=100, verbose_eval = 100)\n\ndel lgb_train,lgb_test\n\nser = pd.DataFrame(reg.feature_importance(),train.columns,columns=['Importance']).sort_values(by='Importance')\nser['Importance'].plot(kind='bar',figsize=(10,6))\n\ndel train\n\n%%time\npredictions = []\nstep = 50000\nfor i in range(0, len(test), step):\n    predictions.extend(np.expm1(reg.predict(test.iloc[i: min(i+step, len(test)), :], num_iteration=reg.best_iteration)))\n    \n%%time\nSubmission['meter_reading'] = predictions\nSubmission['meter_reading'].clip(lower=0,upper=None,inplace=True)\nSubmission.to_csv(\"Twentysix.csv\",index=None)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '96a5c3e66330e4'}"}
{"id":"42804","text":"\"\"\"\n## <h1 align=\"center\">Introduction <\/h1>Mall Analytics measure the quality of relationships between the mall and the store. By tracking customers we analyize their shopping behaviour and spending index.\n![mall](https:\/\/www.dw.com\/image\/17955220_303.jpg)\n\"\"\"\n\"\"\"\nNote:- This Kernel is subject to get updated as soon as i find something which can be revelant to the context. Please Upvote if you like the Kernel\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}\n\n\n\"\"\"\n<b>Loading the datatset<b>\n\"\"\"\ndata=pd.read_csv(\"..\/input\/Mall_Customers.csv\")\n\"\"\"\n<b>The First Gaze<b>\n\"\"\"\ndata.head()\n\"\"\"\nShape of the data\n\"\"\"\ndata.shape\n\"\"\"\nBasic Information \n\"\"\"\ndata.info()\ndata.describe()\n\"\"\"\n<b> Checking for the Null values <\/b>\n\"\"\"\ndata.isnull().any()\nfrom sklearn.preprocessing import LabelEncoder\nle=LabelEncoder()\ndata['Gender']=le.fit_transform(data['Gender'])\n\"\"\"\n<b>Loading dependencies for Visualization<\/b>\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport shap\nsns.set(style=\"white\", palette=\"PuBuGn_d\", color_codes=True)\n\n\"\"\"\n<b> Gender Distribution <\/b>\n\"\"\"\nsns.countplot('Gender',data=data,palette='winter')\nsize=data['Gender'].value_counts()\nprint('Female :',size[0]\/(size[0]+size[1])*100)\nprint('Male :',size[1]\/(size[0]+size[1])*100)\nplt.title(\"Gender distirbution\")\n\"\"\"\nA great insight, why female contribute more to the shopping \n> The real reason is sobering.  In virtually every society in the world, women have primary care-giving responsibilities for both children and the elderly (and often, just about everybody else in-between). In this primary caregiving role, women find themselves buying on behalf of everyone else in their lives. More here \n> https:\/\/www.forbes.com\/sites\/bridgetbrennan\/2013\/03\/06\/the-real-reason-women-shop-more-than-men\/#1a0c65d174b9\n\"\"\"\n\"\"\"\n<b> Age ,Annual Income and Spending Score Distribution <\/b>\n\"\"\"\nplt.figure(1 , figsize = (15 ,6))\nn = 0 \ncolor=['red','green','blue']\ncount=0\nfor x in ['Age' , 'Annual Income (k$)' , 'Spending Score (1-100)']:\n    n += 1\n    plt.subplot(1 , 3 , n)\n    plt.subplots_adjust(hspace =0.5 , wspace = 0.5)\n    sns.distplot(data[x] , color=color[count])\n    plt.title('Distplot of {}'.format(x))\n    count+=1\nplt.show()\n\"\"\"\n## <b>Understanding the distributionn and relation between the attributes<b>\n\"\"\"\n\"\"\"\nWe will be using pairs plot which allows us to see both distribution of single variables and relationships between two variables. Pair plots are a great method to identify trends for follow-up analysis and, fortunately and here in this example we will identify the pattern \n\"\"\"\nsns.pairplot(data)\nplt.plot()\n\"\"\"\nFrom the pair plot , we figure out that the <b>Age<\/b> between <b>20-40<\/b> having high spending index and following it, the spending score doesn't show any frequent rise in the score. \nWe also conclude that <b>age between 20-40<\/b> have dense and higher Annual Income and the trend decreases down the age. We also see that <b>Spending score<\/b> is releatively less with higher Annual income (50-75)K compare to 25-50K Annual income. Spending Index (45-60) becomes constant for indiviudal with <b> Annual income between 50-75K dollar <\/b> and then the spending index increases for higher and lower Annual income. This is weird!\n\n\"\"\"\n\"\"\"\n<b> Checking for the correleation<b>\n\"\"\"\nplt.rcParams['figure.figsize'] = (18, 8)\ncorr=data.corr()\nsns.heatmap(corr)\nplt.title(\"Data correleation\", fontsize=14)\nplt.plot()\n\"\"\"\nThe one with the least inference with each other can be analysized by seeing the color saturity. We see that Age is highly uncorreleated with the spending index. The maximum correleation is represnted by the bright skin colour and least with the black colour. We analyized from the heatmap, that the data is not well correleated\n\n\"\"\"\n\"\"\"\n## <h1> Determing Relationship with the attributes <\/h2>\n\"\"\"\nplt.rcParams['figure.figsize'] = (18, 6)\nsns.violinplot(data['Gender'], data['Spending Score (1-100)'], palette = 'pastel')\nplt.title('Gender vs Spending Score', fontsize = 14)\nplt.show()\n\"\"\"\nWe conclude that spending score is more distributed in female\n\"\"\"\nplt.rcParams['figure.figsize'] = (18, 6)\nsns.violinplot(data['Age'], data['Spending Score (1-100)'], palette = 'pastel')\nplt.title('Age vs Spending Score', fontsize = 14)\nplt.show()\nplt.rcParams['figure.figsize'] = (18, 6)\nsns.violinplot(data['Annual Income (k$)'], data['Spending Score (1-100)'], palette = 'pastel')\nplt.title('Gender vs Spending Score', fontsize = 14)\nplt.show()\n\"\"\"\nViolin plot vs the Box plot\n> a violin plot is more informative than a plain box plot. While a box plot only shows summary statistics such as mean\/median and interquartile ranges, the violin plot shows the full distribution of the data. The difference is particularly useful when the data distribution is multimodal (more than one peak). In this case a violin plot shows the presence of different peaks, their position and relative amplitude.\n\"\"\"\nplt.rcParams['figure.figsize'] = (18, 6)\nsns.violinplot(data['Gender'], data['Annual Income (k$)'], palette = 'pastel')\nplt.title('Gender vs Annual Income (k$)', fontsize = 14)\nplt.show()\nplt.rcParams['figure.figsize'] = (18, 6)\nsns.violinplot(data['Age'], data['Annual Income (k$)'], palette = 'pastel')\nplt.title('Gender vs Annual Income (k$)', fontsize = 14)\nplt.show()\nX=data.iloc[:,:-1]\ny=data.iloc[:,-1]\nfrom sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(max_depth=10, n_estimators=300)\nclf.fit(X,y)\nshap_values = shap.TreeExplainer(clf).shap_values(X)\nshap.summary_plot(shap_values[0], X)\nshap.dependence_plot(\"Age\", shap_values[0], X)\nshap.dependence_plot(\"Gender\", shap_values[0], X)\n\"\"\"\n* 1 represents Male\n* 0 represents Female\n\"\"\"\nshap.dependence_plot('Annual Income (k$)', shap_values[0], X)\nplt.show()\n\"\"\"\n## <h1> CLUSTERING <\/h1>\n\"\"\"\n\"\"\"\nK Means Clustering \n> k-means is one of the simplest unsupervised learning algorithms that solve the clustering problems. The procedure follows a simple and easy way to classify a given data set through a certain number of clusters (assume k clusters). The main idea is to define k centers, one for each cluster.\n\n> To start with k-means algorithm, you first have to randomly initialize points called the cluster centroids (K). K-means is an iterative algorithm and it does two steps: 1. Cluster assignment 2. Move centroid step.\n\n> 1. Cluster assignment\n\n> the algorithm goes through each of the data points and depending on which cluster is closer, It assigns the data points to one of the three cluster centroids.\n\n> 2. Move centroid\n\n> Here, K-means moves the centroids to the average of the points in a cluster. In other words, the algorithm calculates the average of all the points in a cluster and moves the centroid to that average location.\n\n> This process is repeated until there is no change in the clusters (or possibly until some other stopping condition is met). K is chosen randomly or by giving specific initial starting points by the user.\n\"\"\"\n\"\"\"\n![K means clustering](https:\/\/cdn-images-1.medium.com\/max\/800\/0*rrzG3LyOnAvOepbJ.png)\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\n\nsns.set_style(\"white\")\nfig = plt.figure(figsize=(18,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(data['Age'], data[\"Annual Income (k$)\"], data[\"Spending Score (1-100)\"], c='red', s=60)\nax.view_init(30, 185)\nplt.xlabel(\"Age\")\nplt.ylabel(\"Annual Income (k$)\")\nax.set_zlabel('Spending Score (1-100)')\nplt.show()\n\"\"\"\n> Implicit objective function in k-Means measures sum of distances of observations from their cluster centroids, called Within-Cluster-Sum-of-Squares (WCSS). This is computed as\n![](https:\/\/content.edupristine.com\/images\/blogs\/Beyond_the_k-Means_5.png)\n\n\"\"\"\n\"\"\"\n> where Yi is centroid for observation Xi. By definition, this is geared towards maximizing number of clusters, and in limiting case each data point becomes its own cluster centroid. This is, naturally, neither practical nor desirable. Fig. 2 plots WCSS for k=1.20 and we can see that it continuously drops, indicating more clusters the better!\n\"\"\"\nfrom sklearn.cluster import KMeans\n\nwcss = []\nfor k in range(1,11):\n    kmeans = KMeans(n_clusters=k, init=\"k-means++\")\n    kmeans.fit(data.iloc[:,1:])\n    wcss.append(kmeans.inertia_)\nplt.figure(figsize=(12,6))    \nplt.grid()\nplt.plot(range(1,11),wcss, linewidth=2, color=\"blue\", marker =\"8\")\nplt.xlabel(\"K Value\")\nplt.xticks(np.arange(1,11,1))\nplt.ylabel(\"WCSS\")\nplt.show()\n\"\"\"\n<b>K=5<\/b>\n\"\"\"\nkm = KMeans(n_clusters=5)\nclusters = km.fit_predict(data.iloc[:,1:])\ndata[\"label\"] = clusters\nfig = plt.figure(figsize=(20,10))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(data.Age[data.label == 0], data[\"Annual Income (k$)\"][data.label == 0], data[\"Spending Score (1-100)\"][data.label == 0], c='blue', s=60)\nax.scatter(data.Age[data.label == 1], data[\"Annual Income (k$)\"][data.label == 1], data[\"Spending Score (1-100)\"][data.label == 1], c='red', s=60)\nax.scatter(data.Age[data.label == 2], data[\"Annual Income (k$)\"][data.label == 2], data[\"Spending Score (1-100)\"][data.label == 2], c='green', s=60)\nax.scatter(data.Age[data.label == 3], data[\"Annual Income (k$)\"][data.label == 3], data[\"Spending Score (1-100)\"][data.label == 3], c='orange', s=60)\nax.scatter(data.Age[data.label == 4], data[\"Annual Income (k$)\"][data.label == 4], data[\"Spending Score (1-100)\"][data.label == 4], c='purple', s=60)\nax.view_init(30, 185)\nplt.xlabel(\"Age\")\nplt.ylabel(\"Annual Income (k$)\")\nax.set_zlabel('Spending Score (1-100)')\nplt.show()\n\"\"\"\n## <h2>Hierarchical CLustering <\/h2>\n\n\"\"\"\n\"\"\"\n> In hierarchical clustering, we assign each object (data point) to a separate cluster. Then compute the distance (similarity) between each of the clusters and join the two most similar clusters\n\"\"\"\ndata['Spending Score (1-100)']=data['Spending Score (1-100)'].astype(float)\n\"\"\"\nTaking every attribute in account\n\"\"\"\nimport scipy.cluster.hierarchy as sch\ndendogram=sch.dendrogram(sch.linkage(data,method='ward'))\nplt.title('Dendogram', fontsize=20)\nplt.xlabel(\"Customers\")\nplt.ylabel(\"Euclidean Distance\")\nplt.show()\n\"\"\"\nWhen taking Annual Income and Spending Score in account\n\"\"\"\nimport scipy.cluster.hierarchy as sch\ndendogram=sch.dendrogram(sch.linkage(data.iloc[:,3:5],method='ward'))\nplt.title('Dendogram', fontsize=20)\nplt.xlabel(\"Customers\")\nplt.ylabel(\"Euclidean Distance\")\nplt.show()\ndata.head(5)\n\"\"\"\nTaking gender and Spending Score in account\n\"\"\"\nimport scipy.cluster.hierarchy as sch\ndendogram=sch.dendrogram(sch.linkage(data.iloc[:,[1,4]],method='ward'))\nplt.title('Dendogram', fontsize=20)\nplt.xlabel(\"Customers\")\nplt.ylabel(\"Euclidean Distance\")\nplt.show()\n\"\"\"\nTaking age and spending score in account\n\"\"\"\nimport scipy.cluster.hierarchy as sch\ndendogram=sch.dendrogram(sch.linkage(data.iloc[:,[2,4]],method='ward'))\nplt.title('Dendogram', fontsize=20)\nplt.xlabel(\"Customers\")\nplt.ylabel(\"Euclidean Distance\")\nplt.show()\n\"\"\"\n<h1 align=\"center\"> End Of Kernel <\/h1>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4ede85c54d1028'}"}
{"id":"55580","text":"\"\"\"\n# This notebook is to underestand easily for especially train data.\n## (ver6 adding submission test and explanation)\n## if it is helpful for you, please upvote!\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport os\nimport cv2\nimport matplotlib.pyplot as plt\n\"\"\"\n# 0. Confirming each csv file\n\"\"\"\ntraindf = pd.read_csv(\"..\/input\/shopee-product-matching\/train.csv\")\ntraindf\ntestdf = pd.read_csv(\"..\/input\/shopee-product-matching\/test.csv\")\ntestdf\nsample = pd.read_csv(\"..\/input\/shopee-product-matching\/sample_submission.csv\")\nsample\nTRAIN_PATH = \"..\/input\/shopee-product-matching\/train_images\"\nTEST_PATH = \"..\/input\/shopee-product-matching\/test_images\"\n\ntraindf[\"path\"] = [os.path.join(TRAIN_PATH,s) for s in traindf[\"image\"]]\ntestdf[\"path\"] = [os.path.join(TEST_PATH,s) for s in testdf[\"image\"]]\n\ntraindf.to_csv(\"traindf.csv\",index=False)\ntestdf.to_csv(\"testdf.csv\",index=False)\n\"\"\"\n# 1. Train.csv\n\"\"\"\ntraindf.head(3)\ntraindf.info()\n\"\"\"\n* no nan data\n\"\"\"\nfor col in traindf.columns:\n    print(col + \":\" + str(len(traindf[col].unique())))\n\"\"\"\n* This result shows the how many uniques in each columns.\n* Total rows are 34250. Each column has some duplicates.\n* There are duplicates in images, hashes, and titles, not just label groups.\n\"\"\"\n\"\"\"\n## 1.1 easy visualizing image\n\"\"\"\nimg = cv2.imread(traindf[\"path\"].iloc[0])\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nplt.imshow(img)\ntmpdf = traindf[traindf[\"label_group\"]==traindf[\"label_group\"].iloc[0]]\ntmpdf\nfor a in tmpdf[\"path\"]:\n    img = cv2.imread(a)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    plt.figure()\n    plt.imshow(img)\n    plt.axis(\"off\")\n\"\"\"\n* It can be confirmed that both images are victoria's seacret.\n\"\"\"\n\"\"\"\n## 1.2 Understanding same label_groups\n\"\"\"\n\"\"\"\n### 1.2.1 Counting the number of images in each label group\n\"\"\"\nlabels = traindf.groupby(\"label_group\")[\"image\"].count().reset_index()\nlabels.columns=[\"label_group\",\"image_num\"]\nlabels\nsortlabels = labels.sort_values(\"image_num\")\nsortlabels\n\"\"\"\n* minimum images are 2, max images are 51\n\"\"\"\n\"\"\"\n### 1.2.2 Counting the label_groups in each image_num\n\"\"\"\nimagecount = labels.groupby(\"image_num\").count().reset_index()\nimagecount.columns=[\"image_num\",\"counts\"]\nimagecount\n\"\"\"\n* Image num counts in each labels are almost 2.\n\"\"\"\nplt.bar(imagecount[\"image_num\"],imagecount[\"counts\"])\n\"\"\"\n### 1.2.3 visualizing images of label_group with max counts \n\"\"\"\ntmpdf = traindf[traindf[\"label_group\"]==sortlabels[\"label_group\"].iloc[-1]]\ntmpdf.head(5)\n    \nplt.figure(figsize=(20,20))\n\nfor num,a in enumerate(tmpdf[\"path\"]):\n    plt.subplot(11,5,num+1)\n    img = cv2.imread(a)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.axis(\"off\")\n    plt.imshow(img)\n    \n    \n\"\"\"\n## 1.3 Understanding same images\n\"\"\"\nimagegroup = traindf.groupby(\"image\")[\"path\"].count().reset_index()\nimagegroup.columns=[\"image\",\"counts\"]\nimagegroup\ntmpdf = imagegroup[imagegroup[\"counts\"] > 1]\ntmpdf.sort_values(\"counts\")\ntmpdf\n\"\"\"\n* min and max same images are 2.\n\"\"\"\ntmpdf[\"image\"].iloc[0]\ntraindf[traindf[\"image\"]==tmpdf[\"image\"].iloc[0]]\n\"\"\"\n* posting id is different, but others are same. it should be duplicated ?\n\"\"\"\ntraindf[traindf[\"image\"]==tmpdf[\"image\"].iloc[1]]\n\"\"\"\n* Other example shows not only posting id, but also title is different. it seemes that it was edited ?\n\"\"\"\ntraindf.groupby([\"image\",\"image_phash\"])[\"path\"].count().reset_index()\n\"\"\"\n* 32412 is the same numbers as images. at least, image and image_phash are same in same images.\n\"\"\"\n\"\"\"\n## 1.4 Understanding same image_phash\n\"\"\"\nphashgroup = traindf.groupby(\"image_phash\")[\"path\"].count().reset_index()\nphashgroup.columns=[\"image_phash\",\"counts\"]\nphashgroup\nsortphash = phashgroup.sort_values(\"counts\")\nsortphash\n\"\"\"\n* maximum counts are 26.\n\"\"\"\ntmpdf = traindf[traindf[\"image_phash\"]==sortphash[\"image_phash\"].iloc[-1]]\ntmpdf\n\"\"\"\n* same phash, but images are different. Visualing the images with max counts.\n\"\"\"\nplt.figure(figsize=(20,20))\n\nfor num,a in enumerate(tmpdf[\"path\"]):\n    plt.subplot(6,5,num+1)\n    img = cv2.imread(a)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    plt.axis(\"off\")\n    plt.title(tmpdf[\"posting_id\"].iloc[num])\n    plt.imshow(img)\n    \n\"\"\"\n* images are different but we can see all same.\n\"\"\"\n\"\"\"\n## 1.5 Understanding same titles\n\"\"\"\ntraindf\ntitlegroup = traindf.groupby(\"title\")[\"path\"].count().reset_index()\ntitlegroup.columns=[\"title\",\"counts\"]\ntitlegroup\nsorttitle = titlegroup.sort_values(\"counts\")\nsorttitle\n\"\"\"\n* max same title is 9. Visualing the images with max counts title.\n\"\"\"\ntmpdf = traindf[traindf[\"title\"]==sorttitle[\"title\"].iloc[-1]]\ntmpdf\nplt.figure(figsize=(20,20))\n\nfor num,a in enumerate(tmpdf[\"path\"]):\n    plt.subplot(3,5,num+1)\n    img = cv2.imread(a)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    plt.axis(\"off\")\n    plt.imshow(img)\n    \n\"\"\"\n* title is same but images are different.\n\"\"\"\n\"\"\"\n# 2. test.csv\n\"\"\"\ntestdf\nplt.figure(figsize=(20,20))\n\nfor num,a in enumerate(testdf[\"path\"]):\n    \n    plt.subplot(1,3,num+1)\n    img = cv2.imread(a)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n\"\"\"\n# 3.submission.csv\n\"\"\"\nsample\n\"\"\"\n## submission rules\n\nsample_submission.csv - a sample submission file in the correct format.\n\nposting_id - the ID code for the posting.\n\nmatches - Space delimited list of all posting IDs that match this posting. Posts always self-match. Group sizes were capped at 50, so there's no need to predict more than 50 matches.\n\"\"\"\n\"\"\"\n# 4.Easy test to submission\n### From above results, I thought it would match if the image_phash were the same.\n### To achieve that, I used defaultdict, but firstly I practiced with train.csv because test.csv is too short and difficult to understand.\n\"\"\"\npracticedf = traindf.iloc[:1000,:]\npracticedf\nfrom collections import defaultdict\nevery_phash = defaultdict(list)\nfor num, row in enumerate(practicedf[['posting_id', 'image_phash']].values):\n    every_phash[row[1]].append(row[0])\n#every_phash\nevery_phash_list = []\n\nfor num, row in enumerate(practicedf[['posting_id','image_phash']].values):\n    pred = \"\"\n    for a in every_phash[row[1]]:\n        pred = pred + a + \" \"\n\n    \n    pred=pred[:-1] # delete last space\n    \n    every_phash_list.append(pred)\nevery_phash_list[:20]\npracticedf[\"matches\"] = every_phash_list\npracticedf\n\"\"\"\n## The case using test data to submit\n\"\"\"\ntestdf\nevery_phash = defaultdict(list)\nfor num, row in enumerate(testdf[['posting_id', 'image_phash']].values):\n    every_phash[row[1]].append(row[0])\nevery_phash\nevery_phash_list = []\n\nfor num, row in enumerate(testdf[['posting_id','image_phash']].values):\n    pred = \"\"\n    for a in every_phash[row[1]]:\n        pred = pred + a + \" \"\n\n    \n    pred=pred[:-1] # delete last space\n    \n    every_phash_list.append(pred)\ntestdf[\"matches\"] = every_phash_list\ntestdf\nsubmission = testdf[[\"posting_id\",\"matches\"]]\nsubmission\nsubmission.to_csv(\"submission.csv\",index=False)\n\"\"\"\n## Thank you for reading!! Attension : internet must be off.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '666cbd74f29f77'}"}
{"id":"38220","text":"\"\"\"\n\uc774 \ub178\ud2b8\ubd81\uc740 2\uac00\uc9c0 \ub178\ud2b8\ubd81\uc744 \uc885\ud569\ud574\uc11c \ub9cc\ub4e4\uc5c8\uc2b5\ub2c8\ub2e4.\n- EDA \ubc0f \uc804\uccb4\uc801\uc778 \uad6c\uc870: [Twitter sentiment Extaction-Analysis,EDA and Model](https:\/\/www.kaggle.com\/tanulsingh077\/twitter-sentiment-extaction-analysis-eda-and-model) \n  - \ud574\ub2f9 dataset \uc5d0\uc11c Most vote \ub97c \ubc1b\uc740 notebook \uc785\ub2c8\ub2e4.\n- \ubaa8\ub378 \uc0ac\uc6a9(Tensorflow): [TensorFlow roBERTa - [0.705]](https:\/\/www.kaggle.com\/cdeotte\/tensorflow-roberta-0-705)\n  - \uc800\ub294 Tensorflow \uc5d0 \uc775\uc219\ud55c\ub370, \ud2b9\ud788 \uc810\uc218\uac00 \uad1c\ucc2e\uc544\ubcf4\uc774\uace0, \ud2b9\uc815 \ubaa8\ub378\uc744 \uc0ac\uc6a9\ud55c \uac83\uc73c\ub85c \ubcf4\uc5ec \uc774 notebook \uc744 \uc120\ud0dd\ud588\uc2b5\ub2c8\ub2e4.\n\nData \ub85c\ub294 \ucd1d 3\uac00\uc9c0\ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4. \uc624\ub978\ucabd\uc758 + Add data \uc5d0 \ub2e4\uc74c\uacfc \uac19\uc740 3\uac1c\ub97c \ub4f1\ub85d\ud558\uc138\uc694.\n* tweet-sentiment-extraction\n* tf-roberta\n* tse-spacy-model\n\n\ucd94\uac00\ud558\uac70\ub098 \uc5c5\ub370\uc774\ud2b8\ub41c \ub0b4\uc6a9\uc740 \ub530\ub85c \ud45c\uc2dc\ud560 \uc218 \uc788\ub3c4\ub85d \ud574\ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n\"\"\"\n\"\"\"\n# \ucc38\uace0\uc790\ub8cc\n\n**[Twitter sentiment Extaction-Analysis,EDA and Model](https:\/\/www.kaggle.com\/tanulsingh077\/twitter-sentiment-extaction-analysis-eda-and-model)**\n* https:\/\/www.kaggle.com\/aashita\/word-clouds-of-various-shapes\n  * WORDCLOUDS FUNCTION: \ub2e4\uc591\ud55c \uae00\uc790\ub4e4\uc744 \ud2b9\uc815 \uc774\ubbf8\uc9c0\uc758 \ud615\ud0dc\ub85c \ub9cc\ub4e4\uc5b4 \ud45c\ud604\ud558\ub294 \uae30\ubc95\uc73c\ub85c \uba4b\uc9c4 \uadf8\ub9bc\uc744 \uc704\ud574\uc11c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n* https:\/\/www.kaggle.com\/rohitsingh9990\/ner-training-using-spacy-0-628-lb \n  * For understanding how to train spacy NER on custom inputs\n    \n**[TensorFlow roBERTa - [0.705]](https:\/\/www.kaggle.com\/cdeotte\/tensorflow-roberta-0-705)**\n* \bhttps:\/\/www.kaggle.com\/abhishek\/roberta-inference-5-folds\n  * Tokenization logic \uc744 \ube4c\ub824\uc654\ub2e4\uace0 \ud569\ub2c8\ub2e4.\n* roBERTa \ub17c\ubb38\uc740 BERT \ub97c '\uc798' \ud559\uc2b5\uc2dc\ud0b4\uc73c\ub85c\uc368 BERT \uc774\ud6c4\uc5d0 \ub098\uc628 work \ub4e4 \ubcf4\ub2e4 \ub2e4\uc591\ud55c finetuning job \ub4e4\uc5d0\uc11c \uc88b\uc740 \uc131\ub2a5\uc744 \ubcf4\uc77c \uc218 \uc788\uc74c\uc744 \ubcf4\uc5ec\uc8fc\uc5c8\uc2b5\ub2c8\ub2e4. \uc544\ub798\ub294 roBERTa \ub17c\ubb38\uc758 4\uc7a5\uc5d0 \uc2e4\ub9b0 \uc2e4\ud5d8 \ub0b4\uc6a9\ub4e4\uc744 \uac00\uc838\uc628 \uac83\ub4e4\uc785\ub2c8\ub2e4.\n  * Static vs. Dynamic Masking \uc2e4\ud5d8: MLM \uc758 \ud2b9\uc131\uc744 \uc798 \uc0b4\ub824\uc11c \ubbf8\ub9ac \uac19\uc740 \uacf3\ub9cc masking \uc744 \ud558\uc9c0 \uc54a\uace0 on-the-fly \ub85c dynamic \ud558\uac8c input masking \uc744 \ud569\ub2c8\ub2e4.\n  * Model Input Format and Next Sentence Prediction: NSP(Next Sentence Prediction) \ub97c objective \ub85c \uc0ac\uc6a9\ud588\uc744\ub54c \uc131\ub2a5\uc774 \uc88b\uc544\uc9c0\uc9c0 \uc54a\uc74c\uc744 \ubcf4\uc5ec\uc8fc\uba70, Segment-pair, sentence-pair, full-sentences, doc-sentences \ub4e4\uc758 \ubc29\ubc95\uc744 \ud1b5\ud574\uc11c Sentence \ub97c \uc5b4\ub5bb\uac8c \uc798 \ubaa8\uc544\uc11c \ud559\uc2b5\uc744 \uc2dc\ucf30\uc744\ub54c \uc131\ub2a5\uc774 \uc88b\uc544\uc9c0\ub294 \uc9c0 \ubcf4\uc5ec\uc90d\ub2c8\ub2e4. \uacb0\ub860\uc801\uc73c\ub85c \uac00\uc7a5 \uc88b\uc740 \uc131\ub2a5\uc740 NSP \ub97c \uc0ac\uc6a9\ud558\uc9c0 \uc54a\uc73c\uba70, \uac19\uc740 Document \uc758 \ubb38\uc7a5\ub4e4\ub9cc \uc798 \ubaa8\uc544\uc11c \ud559\uc2b5\uc2dc\ucf30\uc744\ub54c\uac00 \uc88b\uc740 \uacb0\uacfc\ub97c \ub0c8\uc2b5\ub2c8\ub2e4.\n  * Training with large batches: Batch \uc0ac\uc774\uc988\ub97c 2K, 8K \ub4f1\uacfc \uac19\uc774 \uc5c4\uccad \ud06c\uac8c \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4.\n  * Text Encoding: \uae30\uc874 BERT \uc5d0\uc11c\ub294 char-level \uc758 BPE \uc744 \uc0ac\uc6a9\ud558\uba70 30k \uc758 vocab \uc744 \uc0ac\uc6a9\ud588\uc9c0\ub9cc, roBERTa \uc5d0\uc11c\ub294 50k byte-level BPE \ub97c \uc0ac\uc6a9\ud588\uc73c\uba70, \ucd94\uac00\uc801\uc778 input \uc5d0 \ub300\ud55c tokenization \uc774\ub098 preprocessing \uc744 \ud558\uc9c0 \uc54a\uc558\ub2e4\uace0 \ud569\ub2c8\ub2e4.\n  * \ub610\ud55c 5\uc7a5\uc5d0\uc11c\ub294 BERT-large \uc5d0\uc11c \uc0ac\uc6a9\ud55c 13GB \ub370\uc774\ud130\uc14b\ubcf4\ub2e4 \ud6e8\uc52c \ud070 496GB \uc815\ub3c4\uc758 \ud559\uc2b5 \ub370\uc774\ud130\uc14b\uc744 \uac01\uac01 8K batch\ub85c 500K step \uae4c\uc9c0 \ud559\uc2b5\uc2dc\ud0b4\uc73c\ub85c\uc368 \uc131\ub2a5 \ud5a5\uc0c1\uc744 \uc774\ub8ec \ubc29\ubc95\uc785\ub2c8\ub2e4.\n\"\"\"\n\"\"\"\n# \ubaa9\uc801\n\n\uc774 \ub178\ud2b8\ubd81\uc744 \ud1b5\ud574\uc11c \uc800\ub294 \ub2e4\uc74c\uacfc \uac19\uc740 \ubaa9\uc801\uc744 \uc774\ub8e8\uace0\uc790 \ud569\ub2c8\ub2e4.\n- EDA \ub97c \ud1b5\ud55c \ub370\uc774\ud130\uc14b \uc774\ud574\ud558\uae30.\n  - \ub370\uc774\ud130 \uc14b \ubd84\uc11d\uc744 \uc704\ud55c \uc2dc\uac01\ud654. (matplotlib, seaborn, plotly, word cloud)\n  - \ub370\uc774\ud130\uc14b\uc758 \ubd84\ud3ec \ubd84\uc11d.\n- Tensorflow \ubaa8\ub378\uc778 roBERTa \ub97c \ud1b5\ud574\uc11c \ud559\uc2b5\uc744 \uc2dc\ucf1c\ubcf4\uae30.\n\"\"\"\n\"\"\"\n# \ud544\uc694\ud55c \ud328\ud0a4\uc9c0\ub4e4\uc744 import \ud569\ub2c8\ub2e4.\n\n[PEP8](https:\/\/www.python.org\/dev\/peps\/pep-0008\/) \ucc38\uace0\n* import \ub294 \ud55c \uc904\uc529 \uc801\uc5b4\uc57c \ud55c\ub2e4.\n* \ud30c\uc77c\uc758 \ub9e8 \uc704\uc5d0 import \ub97c \uc801\uc5b4\uc57c \ud55c\ub2e4.\n* python \ud328\ud0a4\uc9c0\ub97c import \ud560\ub54c\ub294 \ucd1d 3\uac00\uc9c0\ub85c \uadf8\ub8f9\ud551\ud574\uc57c \ud55c\ub2e4.\n  * python \uc758 standard library\n  * third_party library\n  * \ub85c\uceec(Local application\/library) \uc5d0\uc11c \uac00\uc838\uc62c \ud328\ud0a4\uc9c0\ub4e4\n* wild import \ub294 \uc4f0\uc9c0 \ub9d0\uc544\uc57c \ud55c\ub2e4.\n\n\uc774\uac74 \ud604\uc5c5\uc5d0\uc11c\ub9cc \ud574\ub2f9\ud560 \uc218 \uc788\uc9c0\ub9cc, \ubcf4\ud1b5\uc740 \uac01 \uadf8\ub8f9\ubcc4\ub85c a->z \ub97c \uc2dc\ucf1c\uc11c \uc501\ub2c8\ub2e4.\n\"\"\"\n# standard library\nimport collections\nimport os\nimport random\nimport re\nimport string\nimport tqdm\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# third-party library\nimport matplotlib.pyplot as plt\nimport nltk.corpus # stopwords\nimport numpy as np \nimport pandas as pd \nfrom PIL import Image\nfrom plotly import graph_objs, express, figure_factory  # go. pe, ff\nimport seaborn as sns\nimport spacy.util # compounding, minibatch\nimport tensorflow as tf\nimport tokenizers\nimport transformers\nfrom sklearn.model_selection import StratifiedKFold\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n%matplotlib inline\nprint('TF version', tf.__version__)\n\"\"\"\n\ub79c\ub364 \uceec\ub7ec\ub97c \ub9cc\ub4e4 \uc218 \uc788\ub3c4\ub85d \ud558\ub294 \ud568\uc218\ub97c \uc81c\uacf5\ud574\uc8fc\uace0\uc790 \ud558\ub124\uc694.\n\"\"\"\ndef random_colours(number_of_colors):\n    '''\n    Simple function for random colours generation.\n    Input:\n        number_of_colors - integer value indicating the number of colours which are going to be generated.\n    Output:\n        Color in the following format: ['#E86DA4'] .\n    '''\n    colors = []\n    for i in range(number_of_colors):\n        colors.append(\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]))\n    return colors\n\"\"\"\n# \ub370\uc774\ud130 \uc77d\uae30\n\nkaggle \uc5d0\uc11c\ub294 \ubcf4\ud1b5 \ub370\uc774\ud130\ub97c \ucc98\ub9ac\ud558\uae30 \uc704\ud574\uc11c pandas library \ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n\"\"\"\ntrain = pd.read_csv('\/kaggle\/input\/tweet-sentiment-extraction\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/tweet-sentiment-extraction\/test.csv')\nss = pd.read_csv('\/kaggle\/input\/tweet-sentiment-extraction\/sample_submission.csv')\n# row \uc218, col \uc218 \ub77c\uace0 \uc0dd\uac01\ud558\uc2dc\uba74 \ub429\ub2c8\ub2e4.\nprint(train.shape)\nprint(test.shape)\n\"\"\"\n27481 \uac1c\uc758 train set, 3534 \uac1c\uc758 test set \uc744 \uc81c\uacf5\ud558\ub124\uc694.\n\"\"\"\ntrain.info()\n\"\"\"\n1\uac1c\uc5d0 \ub300\ud574\uc11c text, selected_text \uac00 null \uc774 \uc874\uc7ac\ud558\ub2c8\uae4c \uc5c6\uc560\uc90d\ub2c8\ub2e4.\n\"\"\"\ntrain.dropna(inplace=True)\ntest.info()\n\"\"\"\ntest \uc14b\uc740 \uad1c\ucc2e\ub124\uc694.\n\"\"\"\n\"\"\"\n# EDA\n\n[EDA](https:\/\/www.itl.nist.gov\/div898\/handbook\/eda\/section1\/eda11.htm) \ub780 Exploratory Data Analysis \uc758 \uc904\uc784\ub9d0\uc785\ub2c8\ub2e4. \ub370\uc774\ud130 \uc14b\uc5d0 \ub300\ud55c insight \ub97c \uac00\uc9c0\uae30 \uc704\ud574\uc11c \ub370\uc774\ud130\ub294 \ubd84\uc11d\ud558\ub294 \ubc29\ubc95\uc785\ub2c8\ub2e4.\n* \ub370\uc774\ud130 \uc14b\uc5d0 \ub300\ud574\uc11c insight \ub97c \ucd5c\ub300\ud654 \ud558\uace0\n* \ub370\uc774\ud130 \uc14b\uc758 \uc0dd\uae40\uc0c8\uc5d0 \ub300\ud574\uc11c \uc54c\uc544\ub0b4\uba70\n* \uc911\uc694\ud55c \ubcc0\uc218\ub97c \ucc3e\uc544\uc11c \ucd94\ucd9c\ud574\ub0b4\uace0\n* outlier \ub098 anomalies \ub97c \ubc1c\uacac\ud574\ub0b4\uace0\n* \uc608\uc0c1\uc5d0 \ub300\ud55c \ud14c\uc2a4\ud2b8\ub97c \ud574\ubcf4\uba70\n* \uad49\uc7a5\ud788 \uac80\uc18c\ud55c \ubaa8\ub378(parsimonious model)\uc744 \ub9cc\ub4e4\uace0\n* optimal factor \ub97c \ub9cc\ub4e4\uc5b4\ub0b4\ub294 \uacfc\uc815\uc774\ub77c\uace0 \ud569\ub2c8\ub2e4.\n\n\uac80\uc18c\ud55c \ubaa8\ub378\uc744 'explain data with a minimum number of parameters, or predictor variables' \ub77c\uace0 \ub9d0\ud558\uace0 \uc788\ub124\uc694. \ud558\uc9c0\ub9cc \uc6b0\ub9ac\ub294 tensorflow \uc758 keras \ub97c \uc0ac\uc6a9\ud560 \uac83\uc774\ub77c... EDA \uc5d0\uc11c \ub370\uc774\ud130 \ubd84\uc11d\ub9cc\uc744 \ud558\uace0 \ub118\uc5b4\uac00\uaca0\uc2b5\ub2c8\ub2e4!\n\"\"\"\ntrain.head()\n\"\"\"\nselected_text \uc5f4\uc740 text \uc5f4\uc758 substring \uc778\uac83 \uac19\uc2b5\ub2c8\ub2e4.\n\"\"\"\nlen(train.apply(lambda x: x.selected_text in x.text, axis=1))\ntrain.describe()\n\"\"\"\nsentiment \uc758 distribution \uc744 \ubd05\uc2dc\ub2e4.\n\"\"\"\ntemp = train.groupby('sentiment').count()['text'].reset_index().sort_values(by='text',ascending=False)\ntemp.style.background_gradient(cmap='Purples')\n\"\"\"\n\uc0dd\uac01\ubcf4\ub2e4 \ub9ce\uc740 \uac83\ub4e4\uc774 neutral \uac12\uc744 \uac00\uc9c0\uace0 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplt.figure(figsize=(12,6))\nsns.countplot(x='sentiment',data=train)\n\"\"\"\nFunnel-Chart \ub85c \ubcf4\uba74 \ub354 \ud655\uc2e4\ud558\uac8c \ubcf4\uc785\ub2c8\ub2e4.\n\"\"\"\nfig = graph_objs.Figure(graph_objs.Funnelarea(\n    text =temp.sentiment,\n    values = temp.text,\n    title = {\"position\": \"top center\", \"text\": \"Funnel-Chart of Sentiment Distribution\"}\n    ))\nfig.show()\n\"\"\"\n## \ub370\uc774\ud130\ub97c \ubcf4\uace0 \uc54c\uac8c\ub41c \uac83\ub4e4\n\n* \uc6b0\ub9ac\ub294 selected_text \uac00 text \uc758 subset \uc774\ub77c\ub294 \uac83\uc744 \ubcf4\uc558\uc2b5\ub2c8\ub2e4.\n* \uc6b0\ub9ac\ub294 selected_text \uac00 \uc5f0\uc18d\ub41c \ub2e8\uc5b4\ub85c\ubd80\ud130 \uc0dd\uc131\ub418\uc5c8\uc74c\uc744 \uc54c\uc558\uc2b5\ub2c8\ub2e4. \uc5ec\ub7ec \ubb38\uc7a5\uc5d0\uc11c \uc77c\ubd80\ubd84\uc529 \ucd94\ucd9c\ub418\uc9c0\ub294 \uc54a\uc74c\uc744 \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n* https:\/\/www.kaggle.com\/c\/tweet-sentiment-extraction\/discussion\/138520 \ub97c \ubcf4\uba74 neutral tweet \uc740 selected_text \uc640 text \uac04\uc758 jaccard similarity \uac00 97% \ub77c\uace0 \ud569\ub2c8\ub2e4.\n* https:\/\/www.kaggle.com\/c\/tweet-sentiment-extraction\/discussion\/138272 \ub97c \ubcf4\uba74 selected_text \uac00 \ub2e8\uc5b4 \uc0ac\uc774\uc5d0\uc11c \uc2dc\uc791\ud558\ub294 \uacbd\uc6b0\uac00 \uc885\uc885 \uc788\uc5b4\uc11c \ud56d\uc0c1 \ub9d0\uc774 \ub418\ub294\uac74 \uc544\ub2c8\uba70, \ud14c\uc2a4\ud2b8 \uc14b\uc5d0\uc11c\ub3c4 \uc774\uac83\uc774 \uc720\ud6a8\ud55c\uc9c0\ub294 \uc798 \ubaa8\ub974\uae30 \ub54c\ubb38\uc5d0 \ubb38\uc7a5\uc744 preprocessing \ud558\uac70\ub098 punctuation \uc744 \uc5c6\uc560\ub294\uac8c \uc88b\uc740 \uc194\ub8e8\uc158\uc778\uc9c0 \uc54c \uc218 \uc5c6\ub2e4\uace0 \ud569\ub2c8\ub2e4.\n\"\"\"\n\"\"\"\n## Meta-Feature \ub9cc\ub4e4\uae30\n\"\"\"\n\"\"\"\n\ub2e4\uc74c\uacfc \uac19\uc740 \ub450 \uac00\uc9c0 \uc815\ubcf4\ub97c \uc0ac\uc6a9\ud558\uba74 \ub354 \uc88b\uc740 \uacb0\uacfc\ub97c \ub0bc \uc218 \uc788\uc744 \uac70\ub77c\uace0 \ud569\ub2c8\ub2e4.\n* text \uc640 selected_text \uc0ac\uc774\uc758 \ub2e8\uc5b4 \uc22b\uc790 \ucc28\uc774\n* text \uc640 selected_text \uc0ac\uc774\uc758 jaccard similarity score.\n\n[jaccard similiarity](https:\/\/www.geeksforgeeks.org\/find-the-jaccard-index-and-jaccard-distance-between-the-two-given-sets\/)\ub294 \ub2e4\uc74c\uacfc \uac19\uc774 \uacc4\uc0b0\ub420 \uc218 \uc788\ub2e4\uace0 \ud569\ub2c8\ub2e4.\n\n![image.png](attachment:image.png)\n\"\"\"\ndef jaccard(str1, str2): \n    a = set(str1.lower().split()) \n    b = set(str2.lower().split())\n    c = a.intersection(b)\n    return float(len(c)) \/ (len(a) + len(b) - len(c))\nresults_jaccard=[]\n\nfor ind,row in train.iterrows():\n    sentence1 = row.text\n    sentence2 = row.selected_text\n\n    jaccard_score = jaccard(sentence1,sentence2)\n    results_jaccard.append([sentence1,sentence2,jaccard_score])\njaccard = pd.DataFrame(results_jaccard,columns=[\"text\",\"selected_text\",\"jaccard_score\"])\ntrain = train.merge(jaccard,how='outer')\ntrain['Num_words_ST'] = train['selected_text'].apply(lambda x:len(str(x).split())) #Number Of words in Selected Text\ntrain['Num_word_text'] = train['text'].apply(lambda x:len(str(x).split())) #Number Of words in main text\ntrain['difference_in_words'] = train['Num_word_text'] - train['Num_words_ST'] #Difference in Number of words text and Selected Text\ntrain.head()\n\"\"\"\nMeta-Features \uc758 distribution \uc744 \uc0b4\ud3b4\ubd05\uc2dc\ub2e4.\n\"\"\"\ntrain.describe()\nhist_data = [train['Num_words_ST'],train['Num_word_text']]\n\ngroup_labels = ['Selected_Text', 'Text']\n\n# Create distplot with custom bin_size\nfig, axes = plt.subplots(figsize=(20,10))\nsns.countplot(train['Num_words_ST'], ax=axes, color='blue', alpha=0.3, label='selected_text')\nsns.countplot(train['Num_word_text'], ax=axes, color='red', alpha=0.3, label='text')\naxes.legend()\nfig.show()\n\"\"\"\nSentiment \ubcc4\ub85c \ub370\uc774\ud130\ub4e4\uc744 \uc0b4\ud3b4\ubd05\uc2dc\ub2e4.\n\"\"\"\nplt.figure(figsize=(12,6))\np1=sns.kdeplot(train[train['sentiment']=='positive']['difference_in_words'], shade=True, color=\"b\", label='positive').set_title('Kernel Distribution of Difference in Number Of words')\np2=sns.kdeplot(train[train['sentiment']=='negative']['difference_in_words'], shade=True, color=\"r\",label='negative')\nplt.figure(figsize=(12,6))\nsns.distplot(train[train['sentiment']=='neutral']['difference_in_words'],kde=False)\n\"\"\"\n\uadf8\ub9bc\uc5d0\uc11c \ubcfc \uc218 \uc788\ub4ef\uc774 neutral \uc5d0 \ub300\ud574\uc11c\ub294 \ucc28\uc774\uac00 \uac70\uc758 \uc5c6\uc74c\uc744 \ubcfc \uc218 \uc788\uc5c8\uc2b5\ub2c8\ub2e4. \uc774\ub294 jaccard_score \ub97c \ud655\uc778\ud558\uba74 \ub354 \uc798 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplt.figure(figsize=(12,6))\np1=sns.kdeplot(train[train['sentiment']=='positive']['jaccard_score'], shade=True, color=\"b\", label='positive').set_title('KDE of Jaccard Scores across different Sentiments')\np2=sns.kdeplot(train[train['sentiment']=='negative']['jaccard_score'], shade=True, color=\"r\", label='negative')\nplt.legend(labels=['positive','negative'])\n\"\"\"\n\ub450 \uac00\uc9c0 \uc7ac\ubbf8\uc788\ub294 \uac83\ub4e4\uc744 \ubcf4\uc558\uc2b5\ub2c8\ub2e4.\n* positive, negative tweets \ub4e4\uc758 jaccard \uc810\uc218\ub294 \ub192\uc740 \ucca8\ub3c4(kurtosis) \ub97c \ubcf4\uc774\uace0 \uc788\uc73c\uba70, \ub450 \uacf3\uc5d0 \uc881\uace0 \uc870\ubc00\ud558\uac8c \ubd84\ud3ec\ud574\uc788\uc2b5\ub2c8\ub2e4.\n* Neutral tweets\ub294 \ucca8\ub3c4\uac00 \ub0ae\uc73c\uba70, 1\uc5d0 \uac70\uc758 \ubaa8\ub4e0 \uac12\uc774 \uc874\uc7ac\ud569\ub2c8\ub2e4.\n\"\"\"\n\"\"\"\n# Tensorflow \ub97c \ud65c\uc6a9\ud574\uc11c roBERTa \uc2e4\ud589\ud558\uae30\n\n\uc5ec\uae30\ubd80\ud130\ub294 [TensorFlow roBERTa - 0.705](https:\/\/www.kaggle.com\/cdeotte\/tensorflow-roberta-0-705) \ub97c \ucc38\uace0\ud574\uc11c \uc791\uc131\ud558\ub3c4\ub85d \ud558\uaca0\uc2b5\ub2c8\ub2e4.\n\"\"\"\nMAX_LEN = 96\nPATH = '..\/input\/tf-roberta\/'\ntokenizer = tokenizers.ByteLevelBPETokenizer(\n    vocab_file=PATH+'vocab-roberta-base.json', \n    merges_file=PATH+'merges-roberta-base.txt', \n    lowercase=True,\n    add_prefix_space=True\n)\n\"\"\"\nTraining \ub370\uc774\ud130\ub97c \ub9cc\ub4e4\uc5b4\uc8fc\uae30 \uc704\ud574\uc11c \ub2e4\uc74c\uacfc \uac19\uc740 \uc791\uc5c5\uc744 \ud569\ub2c8\ub2e4.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n\uae30\uc874 BERT \ub294 token, segment embedding, positional embedding \ub4f1\uc758 3\uac00\uc9c0\uc5d0 \ub300\ud574\uc11c input \uc744 \ubc1b\uc558\ub294\ub370 roberta \uc758 \uacbd\uc6b0\uc5d0\ub294 token, attention_mask, start_token, end_token \uc758 \ud615\ud0dc\ub85c \uc778\uc790\ub97c \ubc1b\uace0 \uc788\ub294 \uac83\uc744 \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4. \n\nsegment embedding \uc740 \ubb38\uc7a5\uacfc \ub2e4\uc74c \ubb38\uc7a5\uc5d0 \ub300\ud55c \uacbd\uacc4\ub97c \ud45c\uc2dc\ud558\uae30 \uc704\ud574\uc11c \uc0ac\uc6a9\ud588\ub358 \uac83\uc774\uace0, positional embedding \uc740 \ud2b9\uc815 \uc704\uce58\uc758 \ud1a0\ud070\uc774 \uc5b4\ub5a4 embedding \uc744 \uac16\ub294\uc9c0\uc5d0 \ub300\ud574\uc11c (512, 768) matrix \ub85c \ud45c\ud604\ub418\uc5c8\uc2b5\ub2c8\ub2e4. (\uc8fc\uc758! \ud2c0\ub9b4\ud655\ub960\uc774 \ub9e4\uc6b0 \ub192\uc2b5\ub2c8\ub2e4!) \uc774\uc640 \ube44\uc2b7\ud558\uac8c \ubb38\uc7a5\uc758 \uacbd\uacc4\ub97c \ud45c\uc2dc\ud558\uae30 \uc704\ud574\uc11c `<\/s><\/s>` \ub97c \uc0ac\uc6a9\ud558\ub294 \uac83\uc73c\ub85c \ubcf4\uc774\ub294\ub370 positional \uc5d0 \ub300\ud55c \uc815\ubcf4\ub97c \ub531\ud788 \uc8fc\uc5b4\uc9c0\uc9c0 \uc54a\ub294 \uac83\uc73c\ub85c \ubcf4\uc774\ub124\uc694.\n\"\"\"\n# \uc800\uc790\uc640 \uc880 \ub2e4\ub974\uac8c unique sentiment \uc5d0 \ub300\ud55c \ud45c\uae30\ub97c \ub2e8\uc21c\ud55c 0,1,2 \ub85c \ud574\ubcf4\uace0\uc790 \ud569\ub2c8\ub2e4.\nunique_sentiment = train.sentiment.unique()\nprint(unique_sentiment)\nsentiment_id = collections.defaultdict(int)\nfor idx, sentiment in enumerate(unique_sentiment):\n    sentiment_id[sentiment] = idx\n\"\"\"\n\uc544\ub798 \ub0b4\uc6a9\uc744 \uc774\ud574\ud558\uae30 \uc27d\ub3c4\ub85d \uacfc\uc815\uc744 \ud45c\ud604\ud574\ubcf4\ub3c4\ub85d \ud558\uaca0\uc2b5\ub2c8\ub2e4.\n```\n  Text  = \"Kaggle is a fun webplace!\", Selected_text=\"fun webplace!\", Sentiment = positive\n```\n\ntext1, text2 \ub97c split \ud558\uace0 \" \" \ub85c \ubd99\uc5ec\uc90d\ub2c8\ub2e4. text1 \uc740 \uc2dc\uc791\uc5d0 space \ub97c \ub123\uc5b4\uc90d\ub2c8\ub2e4. <br>\n```\n  text1 = \" Kaggle is a fun webplace!\"\n  text2 = \"fun webplace!\"\n```\n\ntext1 \uc5d0\uc11c text2 \uc758 \uc704\uce58(idx) \ub97c \ucc3e\uace0, chars \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4. enc \ub77c\ub294 \ubcc0\uc218\ub294 text1 \uc744 tokenizer \ub85c encode \ud55c \uac83 \uc785\ub2c8\ub2e4. \ucc38\uace0\ub85c '\u0120' \ub294 space \ub77c\uace0 \ubcf4\uc785\ub2c8\ub2e4.\n```\n  idx = 3\n  chars = [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n  enc.tokens = ['\u0120k', 'agg', 'le', '\u0120is', '\u0120a', '\u0120fun', '\u0120web', 'place', '!']\n  enc.ids = [449, 7165, 459, 16, 10, 1531, 3748, 6406, 328]\n```\n\n\uc2e4\uc81c token \ub4e4\uc758 (\uc2dc\uc791, \uae38\uc774)\ub97c \uac00\uc9c0\ub294 offset \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4. <br>\n```\n  offset = [(0, 2), (2, 5), (5, 7), (7, 10), (10, 12), (12, 16), (16, 20), (20, 25), (25, 26)]\n```\n\ntext2 \uc5d0\uc11c text1 \uc758 \uc704\uce58\ub97c token \uc758 \uc704\uce58\ub85c \ud45c\uc2dc\ud560 \uc218 \uc788\ub294 tok \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4.\n```\n  tok = [5,6,7,8]\n```\n\n\uadf8\ub9ac\uace0 \uc704\uc5d0\uc11c \uad6c\ud55c \ubaa8\ub4e0 \uc815\ubcf4\ub97c \ud1b5\ud574\uc11c \uadf8\ub9bc\uc5d0\uc11c \ubcfc \uc218 \uc788\ub294 input \uc744 \ub9cc\ub4e4\uc5b4\uc900\ub2e4!\n\"\"\"\nshape0 = train.shape[0]\ninput_ids = np.ones((shape0,MAX_LEN),dtype='int32')\nattention_mask = np.zeros((shape0,MAX_LEN),dtype='int32')\ntoken_type_ids = np.zeros((shape0,MAX_LEN),dtype='int32')\nsentiment = np.zeros((shape0,3), dtype='int32') \n\nfor k in range(train.shape[0]):\n    # text2 \uc758 \uc704\uce58\ub97c \ucc3e\uc544\uc11c idx \ub85c \uc815\uc758\ud558\uace0, text2 \uc704\uce58\uc5d0 1\uc774\ub77c\uace0 \ud45c\uc2dc\ud574\uc8fc\ub294 chars \ubc30\uc5f4\uc744 \uc0dd\uc131\ud569\ub2c8\ub2e4.\n    text1 = \" \"+\" \".join(train.loc[k,'text'].split())\n    text2 = \" \".join(train.loc[k,'selected_text'].split())\n    idx = text1.find(text2)\n    chars = np.zeros((len(text1)))\n    chars[idx:idx+len(text2)]=1\n    if text1[idx-1] == ' ': \n        chars[idx-1] = 1 \n    enc = tokenizer.encode(text1) \n        \n    # text1 \uc5d0 \ub300\ud574\uc11c \ud2b9\uc815 \ub2e8\uc5b4\uc758 \uae38\uc774\ub97c \ud45c\uae30\ud574\uc8fc\ub294 offsets \ubc30\uc5f4\uc744 \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4. (\ub2e8\uc5b4\uc758 \uc2dc\uc791, \ub2e8\uc5b4\uc758 \ub05d)\n    offsets = []\n    idx = 0\n    for t in enc.ids:\n        w = tokenizer.decode([t])\n        offsets.append((idx,idx+len(w)))\n        idx += len(w)\n    \n    # enc.ids \ub97c \ud1b5\ud574\uc11c \uadf8\ub9bc\uc758 input_ids \ub97c \ub9cc\ub4e4\uc5b4\uc90d\ub2c8\ub2e4.\n    # attention_mask \ub294 input_ids \uc758 \uae38\uc774\ub9cc\ud07c\uc774\uae30 \ub54c\ubb38\uc5d0 \ud574\ub2f9 \ubd80\ubd84\ub4e4\uc744 1\ub85c \ucc44\uc6cc\uc90d\ub2c8\ub2e4.\n    input_ids[k,:len(enc.ids)+2] = [0] + enc.ids + [2]\n    attention_mask[k,:len(enc.ids)+2] = 1\n    s_tok = sentiment_id[train.loc[k,'sentiment']]\n    sentiment[k,s_tok] = 1\n\"\"\"\n\ub9cc\ub4e4\uc5b4\uc9c4 \ub370\uc774\ud130\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\ntarget = 1042\nprint(input_ids[target,])\nprint(attention_mask[target,])\nprint(sentiment[target])\n\"\"\"\n# Build roBERTa Model\n\n\uc704\uc5d0\uc11c \ubaa8\ub378\uc774 \uc0ac\uc6a9\ud560 \ub370\uc774\ud130\ub97c \ub9cc\ub4e4\uc5c8\uc73c\ub2c8, \uc774\uc81c \ubaa8\ub378\uc744 \ub9cc\ub4e4\uc5b4\uc11c \ud559\uc2b5\uc744 \uc2dc\ucf1c\ubd05\ub2c8\ub2e4.\nconfig \ud30c\uc77c\uc744 \uc774\uc6a9\ud574\uc11c config \ub97c \ub85c\ub529\ud558\uace0, config \ub97c \uc0ac\uc6a9\ud574\uc11c reberta \ubaa8\ub378\uc744 \ub85c\ub529\ud569\ub2c8\ub2e4.\nbert_model \uc774 \ubf51\uc544\uc8fc\ub294 output \uc740 x \uc778\ub370, x \ub294 \ubc30\uc5f4 \ud615\ud0dc\ub85c \ub4e4\uc5b4\uc635\ub2c8\ub2e4. \n\n--- \n\uc544\ub798 \ubd80\ubd84\uc740 \ud655\uc778\uc774 \ud544\uc694\ud569\ub2c8\ub2e4!\n\n\uadf8 \uc911 \uccab\ubc88\uc9f8 \uc544\uc6c3\ud48b\uc740 (MAX_LEN, 768) \ud06c\uae30\uc758 \uc544\uc6c3\ud48b\uc778\ub370, \uc774\uac83\uc744 softmax \ud568\uc218 \ud615\ud0dc\ub85c (MAX_LEN,) \ud615\ud0dc\ub85c \ubf51\uc544\uc90d\ub2c8\ub2e4. \nReturn \uc740 [transformers.BertModel](https:\/\/huggingface.co\/transformers\/model_doc\/bert.html#transformers.BertModel) \uc744 \ucc38\uace0\ud574\ubcf4\uba74 \ub429\ub2c8\ub2e4.\n> A BaseModelOutputWithPoolingAndCrossAttentions (if return_dict=True is passed or when config.return_dict=True) or a tuple of torch.FloatTensor comprising various elements depending on the configuration (BertConfig) and inputs.\n\n> last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) \u2013 Sequence of hidden-states at the output of the last layer of the model.\n\nMAX_LEN \uc5d0 \ub300\ud574\uc11c softmax \ub97c \ud558\uae30 \ub54c\ubb38\uc5d0 x=sentiment \uc5d0 \ub300\ud55c \ud655\ub960 \ud615\ud0dc\ub85c \ub098\ud0c0\ub098\uac8c \ub429\ub2c8\ub2e4. \n\uc774 sentiment \uc5d0 \ub300\ud574\uc11c crossentropy\ub97c \uad6c\ud558\uae30 \uc704\ud574\uc11c [categorical_crossentropy](https:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/losses\/categorical_crossentropy) \ub97c loss \ub85c \uc124\uc815\ud574\uc90d\ub2c8\ub2e4.\n\"\"\"\ndef build_roberta():\n    # input \ub4e4\uc744 \ubc1b\uc744 \uc218 \uc788\ub3c4\ub85d \ub9cc\ub4e7\ub2c8\ub2e4.\n    ids = tf.keras.layers.Input((MAX_LEN,), dtype=tf.int32)\n    att = tf.keras.layers.Input((MAX_LEN,), dtype=tf.int32)\n    tok = tf.keras.layers.Input((MAX_LEN,), dtype=tf.int32)\n    \n    # \uae30\ubcf8\uc801\uc73c\ub85c transformers \uc548\uc5d0 roberta \uc5d0 \ub300\ud55c \uc124\uc815 \ubc0f \ubaa8\ub4c8\ub4e4\uc774 \ub4e4\uc5b4\uc788\uc2b5\ub2c8\ub2e4.\n    # \uc790\uc138\ud55c \ub0b4\uc6a9\uc740 [huggingface](https:\/\/huggingface.co\/transformers\/model_doc\/roberta.html) \ub97c \ucc38\uace0\ud558\uba74 \uc88b\uc744 \uac83 \uac19\uc2b5\ub2c8\ub2e4.\n    config = transformers.RobertaConfig.from_pretrained(PATH+'config-roberta-base.json')\n    bert_model=transformers.TFRobertaModel.from_pretrained(PATH+'pretrained-roberta-base.h5', config=config)\n    \n    x = bert_model(ids, attention_mask=att, token_type_ids=tok)\n    \n    # x[0] \ub294 bert_model\uc758 bert \uc758 \uccab\ubc88\uc9f8 \uc544\uc6c3\ud48b\uc73c\ub85c (batch_size, MAX_LEN, 768) \ud06c\uae30\uc758 tensor \uc785\ub2c8\ub2e4.\n    # \uc6b0\ub9ac\ub294 \uac01 input token \uc5d0 \ub300\ud574\uc11c \ud574\ub2f9 token \uc774 start \uc778\uc9c0 \uc544\ub2cc\uc9c0\ub97c \ud45c\ud604\ud558\ub294 \uac12\ub4e4\uc744 softmax \ud558\uc5ec \ub098\ud0c0\ub0c5\ub2c8\ub2e4.\n    x = tf.keras.layers.Dropout(0.1)(x[0])\n    x = tf.keras.layers.Conv1D(1,1)(x)\n    x = tf.keras.layers.Flatten()(x)\n    x = tf.keras.layers.Dense(3)(x)\n    x = tf.keras.layers.Activation('softmax')(x)\n\n    # x = sentiment\n    model = tf.keras.models.Model(inputs=[ids, att, tok], outputs=[x])\n    optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5)\n    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])\n\n    return model\nmodel = build_roberta()\nmodel.summary()\n\"\"\"\n# Train roBERTa Model\n\n\uc6b0\ub9ac\ub294 [StratifiedKFold](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.model_selection.StratifiedKFold.html) \ud568\uc218\ub97c \ud1b5\ud574\uc11c input_ids \ub97c \ucd1d 5\uac1c\ub85c \ub098\ub20c\uac83\uc785\ub2c8\ub2e4. StratifiedKFold \ub294 \uad50\ucc28\uac80\uc99d(cross-validation) \uc744 \uc774\uc6a9\ud55c \ud559\uc2b5\ubc95\uc785\ub2c8\ub2e4. \uad50\ucc28 \uc720\ud6a8\uc131 \uac80\uc0ac \uc804\ub7b5\uc5d0 \ub530\ub77c \ub370\uc774\ud130 \uc9d1\ud569\uc744 \uc0dd\uc131\ud558\ub294\ub370 \uc0ac\uc6a9\ud560 \uc218 \uc788\ub294 \uc778\ub371\uc2a4\ub97c \uc0dd\uc131\ud558\ub294 \ub3c4\uad6c\uc785\ub2c8\ub2e4. \uac01\uac01\uc758 fold \uc5d0\uc11c \ucd5c\uace0\uc758 \uc131\ub2a5\uc744 \ub0b4\ub294 \ubaa8\ub378\uc744 \uc0ac\uc6a9\ud574\uc11c validation prediction \uc744 \uc9c4\ud589\ud569\ub2c8\ub2e4.\n\n![image.png](attachment:image.png)\n\n[\ucc38\uace0](https:\/\/swlock.blogspot.com\/2019\/01\/scikit-learn-cross-validation-iterators.html?m=1)\n\"\"\"\nVER='v0'\nDISPLAY=1\n\nskf = StratifiedKFold(n_splits=5,shuffle=True,random_state=777)\nbest_model = 0\nhistory = []\nfor fold,(idxT,idxV) in enumerate(skf.split(input_ids,train.sentiment.values)):\n\n    print('#'*25)\n    print('### FOLD %i'%(fold+1))\n    print('#'*25)\n    \n    tf.keras.backend.clear_session()\n    model = build_roberta()\n        \n    sv = tf.keras.callbacks.ModelCheckpoint(\n        '\/kaggle\/working\/%s-roberta-%i.h5'%(VER,fold), monitor='val_loss', verbose=1, save_best_only=True,\n        save_weights_only=True, mode='auto', save_freq='epoch')\n        \n    history.append(model.fit([input_ids[idxT,], attention_mask[idxT,], token_type_ids[idxT,]], [sentiment[idxT,]], \n        epochs=3, batch_size=32, verbose=DISPLAY, callbacks=[sv],\n        validation_data=([input_ids[idxV,],attention_mask[idxV,],token_type_ids[idxV,]], \n        [sentiment[idxV,]])))\n    \n    print('Loading model...')\n    model.load_weights('\/kaggle\/working\/%s-roberta-%i.h5'%(VER,fold))\n    \n    print('Predicting validation...')\n    sentiment[idxV,] = model.predict([input_ids[idxV,],attention_mask[idxV,],token_type_ids[idxV,]],verbose=DISPLAY)\n    break\n\"\"\"\n# See train history\n\n\"\"\"\nimport matplotlib.pyplot as plt\n\nplt.plot(history[0].history['loss'])\nplt.plot(history[0].history['val_loss'])\nplt.title('Model Loss')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\n\"\"\"\n# Submission\n\"\"\"\ntest0 = test.shape[0]\ninput_ids_t = np.ones((test0,MAX_LEN),dtype='int32')\nattention_mask_t = np.zeros((test0,MAX_LEN),dtype='int32')\ntoken_type_ids_t = np.zeros((test0,MAX_LEN),dtype='int32')\n\nfor k in range(test0):\n        \n    # INPUT_IDS\n    text1 = \" \"+\" \".join(test.loc[k,'text'].split())\n    enc = tokenizer.encode(text1)                \n    input_ids_t[k,:len(enc.ids)+5] = [0] + enc.ids + [2,2] + [s_tok] + [2]\n    attention_mask_t[k,:len(enc.ids)+5] = 1\nimport glob\nsaved_model = glob.glob('\/kaggle\/working\/*.h5')\n\nmodel = build_roberta()\nmodel.load_weights(saved_model[0])\n\npreds = np.zeros((input_ids_t.shape[0],3))\n\nprint('Predicting Test...')\npreds = model.predict([input_ids_t,attention_mask_t,token_type_ids_t],verbose=DISPLAY)\ncategory_pred = [unique_sentiment[np.argmax(pred)] for pred in preds]\ntest['predicted_sentiment'] = category_pred\ntest[['textID','predicted_sentiment']].to_csv('submission.csv',index=False)\npd.set_option('max_colwidth', 60)\ntest.sample(25)\n\"\"\"\n\uc774 \ub178\ud2b8\ubd81\uacfc\ub294 \ubcc4\uac1c\uc758 \uc791\uc5c5\uc774 \ub420 \uc218 \uc788\uaca0\uc9c0\ub9cc, \ub2e4\uc74c\uc73c\ub85c \uc815\ub9ac\ud560 \uc77c\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4.\n* TPU \ub85c \ud559\uc2b5\ud558\ub294 \ubc29\ubc95\uc5d0 \ub300\ud574\uc11c \uc368\ubcfc\uae4c \ud569\ub2c8\ub2e4.\n* GPU \ub85c \ud559\uc2b5\ud55c \ubaa8\ub378\uc744 \uc800\uc7a5\ud574\ubcfc\uae4c \ud569\ub2c8\ub2e4. \ub2e4\uc74c\uc5d0 \ub2e4\uc2dc \uc4f8 \uc218 \uc788\ub3c4\ub85d\uc694.\n\n\uacc4\uc18d \ucd94\uac00\ub420 \uc608\uc815\uc785\ub2c8\ub2e4. TO BE CONTINUED.\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '466a93b6e0b252'}"}
{"id":"102687","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import *\nimport numpy as np\nimport tensorflow.keras.initializers as initer\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport pickle\n\"\"\"\n# Model\n\"\"\"\nclass InstanceNormalization(Layer):\n    def __init__(self, axis=(1, 2), epsilon=1e-6):\n        super().__init__()\n        self.epsilon = epsilon\n        self.axis = axis\n        self.beta, self.gamma = None, None\n\n    def build(self, input_shape):\n        shape = [1 for _ in range(len(input_shape))]\n        shape[-1] = input_shape[-1]\n        self.gamma = self.add_weight(\n            name='gamma',\n            shape=shape,\n            initializer='ones')\n\n        self.beta = self.add_weight(\n            name='beta',\n            shape=shape,\n            initializer='zeros')\n\n    def call(self, x, *args, **kwargs):\n        mean = tf.math.reduce_mean(x, axis=self.axis, keepdims=True)\n        x -= mean\n        variance = tf.reduce_mean(tf.math.square(x), axis=self.axis, keepdims=True)\n        x *= tf.math.rsqrt(variance + self.epsilon)\n        return x * self.gamma + self.beta\nclass AdaNorm(Layer):\n    def __init__(self, axis=(1, 2), epsilon=1e-6):\n        super().__init__()\n        # NHWC\n        self.axis = axis\n        self.epsilon = epsilon\n\n    def call(self, x, **kwargs):\n        mean = tf.math.reduce_mean(x, axis=self.axis, keepdims=True)\n        x -= mean\n        variance = tf.reduce_mean(tf.math.square(x), axis=self.axis, keepdims=True)\n        x *= tf.math.rsqrt(variance + self.epsilon)\n        return x\nclass AdaMod(Layer):\n    def __init__(self):\n        super().__init__()\n        self.y = None\n\n    def call(self, inputs, **kwargs):\n        x, w = inputs\n        y = self.y(w)\n        o = (y[:, 0] + 1) * x + y[:, 1]\n        return o\n\n    def build(self, input_shape):\n        x_shape, w_shape = input_shape\n        self.y = keras.Sequential([\n            Dense(x_shape[-1]*2, input_shape=w_shape[1:], kernel_initializer=initer.HeNormal()),\n            Reshape([2, 1, 1, -1]),\n        ])  # [2, h, w, c] per feature map\nclass AddNoise(Layer):\n    def __init__(self):\n        super().__init__()\n        self.s = None\n        self.x_shape = None\n\n    def call(self, inputs, **kwargs):\n        x, noise = inputs\n        noise_ = noise[:, :self.x_shape[1], :self.x_shape[2], :]\n        return self.s * noise_ + x\n\n    def build(self, input_shape):\n        self.x_shape, _ = input_shape\n        self.s = self.add_weight(name=\"noise_scale\", shape=[1, 1, self.x_shape[-1]],\n                                 initializer=initer.RandomNormal(0, 0.05))\nclass Map(Layer):\n    def __init__(self, size, num_layers, norm=None):\n        super().__init__()\n        self.size = size\n        self.num_layers = num_layers\n        self.norm_name = norm\n        self.f = None\n\n    def call(self, inputs, **kwargs):\n        w = self.f(inputs)\n        return w\n\n    def build(self, input_shape):\n        self.f = keras.Sequential()\n        for i in range(self.num_layers):\n            if i == 0:\n                self.f.add(Dense(self.size, input_shape=input_shape[1:], kernel_initializer=initer.HeNormal()))\n                continue\n            self.f.add(LeakyReLU(0.2))\n            if self.norm_name is not None:\n                if self.norm_name.lower() == \"batch\":\n                    self.f.add(BatchNormalization())    # batch norm also increase model collapse\n                elif self.norm_name.lower() == \"instance\":\n                    self.f.add(InstanceNormalization(axis=(1,)))        # instance norm increase model collapse\n\n            self.f.add(Dense(self.size, kernel_initializer=initer.HeNormal()))\nclass Style(Layer):\n    def __init__(self, filters, upsampling=True):\n        super().__init__()\n        self.filters = filters\n        self.upsampling = upsampling\n        self.ada_mod, self.ada_norm, self.add_noise, self.up, self.conv, self.conv_expend = None, None, None, None, None, None\n\n    def call(self, inputs, **kwargs):\n        x, w, noise = inputs\n        # x = self.conv_expend(x)     #TODO: may help for styling\n        x = self.ada_mod((x, w))\n        if self.up is not None:\n            x = self.up(x)\n        x = self.conv(x)\n        x = LeakyReLU(0.2)(x)\n        x = self.add_noise((x, noise))\n        x = self.ada_norm(x)\n        return x\n\n    def build(self, input_shape):\n        self.ada_mod = AdaMod()\n        self.ada_norm = AdaNorm()\n        if self.upsampling:\n            self.up = UpSampling2D((2, 2), interpolation=\"bilinear\")\n        self.add_noise = AddNoise()\n        # self.conv_expend = Conv2D(self.filters*2, 1, 1, kernel_initializer=initer.HeNormal())\n        self.conv = Conv2D(self.filters, 3, 1, \"same\", kernel_initializer=initer.HeNormal())\ndef get_generator(latent_dim, img_shape , num_layers ,base=256):\n    \n    n_style_block = 0\n    \n    const_size = _size = 4\n    \n    while _size <= img_shape[1]:\n        n_style_block += 1\n        _size *= 2\n\n    z = keras.Input((n_style_block, latent_dim,), name=\"z\") #(m,blocks,dim)\n    noise_ = keras.Input((img_shape[0], img_shape[1]), name=\"noise\") #(m,h,w)\n    ones = keras.Input((1,), name=\"ones\")#(m,1)\n\n    w = Map(size=base, num_layers=num_layers)(z)\n    noise = tf.expand_dims(noise_, axis=-1) #(m,h,w,1), pixel-wise noise\n    const = keras.Sequential([\n        Dense(const_size * const_size * base, use_bias=False, name=\"const\", kernel_initializer=initer.HeNormal()),\n        Reshape((const_size, const_size, -1)),\n    ], name=\"const\")(ones)\n\n    x = AddNoise()((const, noise))\n    x = AdaNorm()(x)\n    \n    \n    for i in range(n_style_block):\n        x = Style(base, upsampling=False if i == 0 else True)((x, w[:, i], noise))\n        \n        \n    o = Conv2D(img_shape[-1], 7, 1, \"same\", activation=keras.activations.tanh)(x)\n\n    g = keras.Model([ones, z, noise_], o, name=\"generator\")\n    return g, n_style_block\ndef get_discriminator(img_shape):\n    def add_block(filters, do_norm=True, padding=\"same\"):\n        model.add(Conv2D(filters, 4, strides=2, padding=padding))\n        if do_norm: \n            model.add(InstanceNormalization())\n        model.add(LeakyReLU(alpha=0.2))\n\n    model = keras.Sequential([Input(img_shape)], name=\"d\")\n    # [n, 128, 128, 3]\n    # model.add(GaussianNoise(0.02))\n    add_block(32, do_norm=False)   # -> 64^2\n    add_block(64)                   # -> 32^2\n    add_block(128)                  # -> 16^2\n    add_block(256)                  # -> 8^2\n    add_block(512, padding=\"valid\")  # -> 4^2\n    model.add(Flatten())\n    # model.add(GlobalAveragePooling2D())\n    model.add(Dense(256))\n    model.add(Dense(1))\n    return model\nclass Trainer(keras.Model):\n    def __init__(self,img_shape,latent_dim,num_layers=5,lr=2e-4,\n                 beta1=0.5, beta2=0.99, lambda_=10, wgan=2):\n        '''\n        img_shape:(h,w,c)\n        z_dim: dim\n        '''\n        super().__init__()\n        self.img_shape=img_shape\n        self.latent_dim=latent_dim\n        self.wgan=wgan\n        self.lambda_=lambda_\n        \n        self.g,self.n_blocks=get_generator(latent_dim,img_shape,num_layers=num_layers)\n        self.d=get_discriminator(img_shape)\n        \n    \n        self.opt = keras.optimizers.Adam(lr, beta_1=beta1, beta_2=beta2)\n\n        \n        \n    def call(self, inputs, training=None, mask=None):\n        '''\n        inputs:[ones,z,noise]\n        '''\n        if isinstance(inputs[0], np.ndarray):\n            inputs = [tf.convert_to_tensor(i) for i in inputs]\n        return self.g(inputs, training=training)\n    \n    \n    def get_inputs(self, n):\n        if np.random.rand() < 0.5:\n            available_z = [tf.random.normal((n, 1, self.latent_dim)) for _ in range(2)]\n            z = tf.concat([available_z[np.random.randint(0, len(available_z))] for _ in range(self.n_blocks)], axis=1)\n        else:\n            z = tf.repeat(tf.random.normal((n, 1, self.latent_dim)), self.n_blocks, axis=1)\n        noise = tf.random.normal((n, self.img_shape[0], self.img_shape[1]))\n        return [tf.ones((n, 1)), z, noise]\n    \n    @staticmethod\n    def w_distance(real, fake):\n        # the distance of two data distributions\n        return tf.reduce_mean(real) - tf.reduce_mean(fake)\n    \n    def gp(self, real_img, fake_img):\n        e = tf.random.uniform((len(real_img), 1, 1, 1), 0, 1)\n        noise_img = e * real_img + (1. - e) * fake_img  # extend distribution space\n        with tf.GradientTape() as tape:\n            tape.watch(noise_img)\n            o = self.d(noise_img)\n        g = tape.gradient(o, noise_img)  # image gradients\n        g_norm2 = tf.sqrt(tf.reduce_sum(tf.square(g), axis=[1, 2, 3]))  # norm2 penalty\n        gp = tf.square(g_norm2 - 1.)\n        return tf.reduce_mean(gp)\n    \n    def train_d(self, img):\n        n = len(img)\n\n        with tf.GradientTape() as tape:\n            gimg = self.call(self.get_inputs(n), training=False) #(n,h,w,3)\n            gp = self.gp(img, gimg)\n            pred_fake = self.d(gimg, training=True)\n            pred_real = self.d(img, training=True)\n            w_distance = -self.w_distance(pred_real, pred_fake)  # maximize W distance\n            gp_loss = self.lambda_ * gp\n            loss = gp_loss + w_distance\n        grads = tape.gradient(loss, self.d.trainable_variables)\n        self.opt.apply_gradients(zip(grads, self.d.trainable_variables))\n        return gp, w_distance\n\n    def train_g(self, n):\n        with tf.GradientTape() as tape:\n            gimg = self.call(self.get_inputs(n), training=True)\n            pred_fake = self.d(gimg, training=False)\n            w_distance = tf.reduce_mean(-pred_fake)  # minimize W distance\n        grads = tape.gradient(w_distance, self.g.trainable_variables)\n        self.opt.apply_gradients(zip(grads, self.g.trainable_variables))\n        return w_distance\n    \n    @tf.function\n    def step(self, img):\n        gw = self.train_g(len(img)*2) #this is just a trick, not following original training method\n        for _ in range(self.wgan):\n            dgp, dw = self.train_d(img)\n        return gw, dgp, dw \n    \n    '''\n    gw: generator loss\n    dw: discriminator loss\n    dgp: gradient penalty\n    '''\n\"\"\"\n# Training\n\"\"\"\nbatch_size=32\nepochs=4\nlatent_dim=128\nlr=2e-4\nb1=0\nb2=0.99\nw=2\nimage_size=128\nlam=10\nnum_layers=5\ndef show(model):\n    global z1, z2\n    n = 7\n    if \"z1\" not in globals():\n        z1 = np.random.normal(0, 1, size=(n, 1, model.latent_dim))\n    if \"z2\" not in globals():\n        z2 = np.random.normal(0, 1, size=(n, 1, model.latent_dim))\n    n_z1 = 3\n    assert n_z1 < model.n_blocks - 1\n    noise = np.random.normal(0, 1, [len(z1), model.img_shape[0], model.img_shape[1]])\n    \n    #mixing style\n    inputs = [\n        np.ones((len(z1)*n, 1)),\n        np.concatenate(\n            (z1.repeat(n, axis=0).repeat(n_z1, axis=1),\n             np.repeat(np.concatenate([z2 for _ in range(n)], axis=0), model.n_blocks - n_z1, axis=1)),\n            axis=1\n        ),\n        noise.repeat(n, axis=0),\n    ]\n    \n    #marginal style\n    z1_inputs = [np.ones((len(z1), 1)), z1.repeat(model.n_blocks, axis=1), noise]\n    z2_inputs = [np.ones((len(z2), 1)), z2.repeat(model.n_blocks, axis=1), noise]\n\n    imgs = model.predict(inputs)\n    z1_imgs = model.predict(z1_inputs)\n    z2_imgs = model.predict(z2_inputs)\n    imgs = np.concatenate([z2_imgs, imgs], axis=0)\n    rest_imgs = np.concatenate([np.ones([1, 128, 128, 3], dtype=np.float32), z1_imgs], axis=0)\n    for i in range(len(rest_imgs)):\n        imgs = np.concatenate([imgs[:i * (n+1)], rest_imgs[i:i + 1], imgs[i * (n+1):]], axis=0)\n    imgs = (imgs + 1) \/ 2\n\n    nc, nr = n+1, n+1\n    f = plt.figure(0, (nc*1.5, nr*1.5))\n    for c in range(nc):\n        for r in range(nr):\n            i = r * nc + c\n            plt.subplot(nr, nc, i + 1)\n            plt.imshow(imgs[i])\n            plt.axis(\"off\")\n\n    plt.tight_layout()\n    plt.show()\n\"\"\"\n* Train\n\"\"\"\npth='..\/input\/celeba-dataset\/img_align_celeba'\n\n\nds=tf.keras.preprocessing.image_dataset_from_directory(\n    directory=pth,\n    image_size=(image_size,image_size),\n    batch_size=batch_size,\n    seed=0,\n    shuffle=True\n)\ntrainer=Trainer((image_size,image_size,3),latent_dim,num_layers,lr,b1,b2,lam,w)\n_=trainer.step(tf.random.normal((32,128,128,3))) #to prevent nontype error\ntry:\n    trainer.load_weights('..\/input\/weights\/StyleGAN.pt')\n    print('load weights successfully')\nexcept:\n    print('no weights ')\ntrack={'gw':[],'dgp':[],'dw':[]}\ndef main(ds):\n    aug=Rescaling(1\/127.5,offset=-1)\n    ds=ds.map(lambda x,y : (aug(x),y))\n    ckpt = tf.train.Checkpoint(trainer=trainer)\n    ckpt_manager = tf.train.CheckpointManager(ckpt,'.\/ckpt', max_to_keep=1)\n    i=0\n    for epoch in range(epochs):\n        show(trainer)\n        trainer.save_weights('.\/weights\/StyleGAN.pt')\n        i+=1\n            \n        loop=tqdm(ds)\n        for x,y in loop:\n            gw, dgp, dw = trainer.step(x)\n            \n            track['gw'].append(gw)\n            track['dgp'].append(dgp)\n            track['dw'].append(dw)\n            \n            loop.set_postfix(loss=f'epoch : {epoch}, gw:{gw}, dgp:{dgp}, dw:{dw}')\nmain(ds)\nwith open('.\/track.pickle','wb') as file:\n    pickle.dump(track,file)","meta":"{'source': 'AI4Code', 'id': 'bcb3d87b1e03d5'}"}
{"id":"62404","text":"\"\"\"\n# Background\n\n\"\"\"\n\"\"\"\n##### This project is a part of the Google Data Analytics Certificate program. For this project I have used the publically available data presented by \"Motivate International Inc.\" refered by the project instruction menaul. \n\"\"\"\n\"\"\"\n##### This project will cover all six data analysis stages,\n* Ask\n* Prepare\n* Process\n* Analyze\n* Share\n* Act\n\"\"\"\n\"\"\"\n# ASK***\n\"\"\"\n\"\"\"\n##### The first stage \"ASK\" has 2 key tasks \n\n1. **Identifying the business task**\n\n    Cyclistic is already a well-known bike-sharing company that is operating for quite a few years now. Right now it has 2 types of users Annual Members and Causal(non-member users). According to financial analysts, the annual members are much more profitable than the causal riders. According to the marketing director Lily Moreno, maximization of the annual membership is key to long-term success. The aim of the task is to design marketing strategies that will convert casual riders to annal members. \n    \n2. **Consider key satakeholders**\n\n     The marketing director Lily Moreno, assigned me to identify how these two different types of users use Cyclistic bikes differently. The Cyclistic marketing analytics team is responsible for creating cyclistic marketing strategies by collecting, analyzing, and reporting data. Finally, the marketing executive team will decide whether or not the new marketing strategy will be implemented or not. \n     \n   **Deliverable**\n\n       A clear statement of the business task. The business taks is to provide insight to the marketing analyst team by analyzing the Cyclistic historical bike trip data to better understand how annual members and casual riders differ, why casual riders would buy a membership, and how digital media could affect their marketing tactics.\n \n   \n\"\"\"\n\"\"\"\n# PREPARE***\n\"\"\"\n\"\"\"\n##### There are 4 key tasks for the preparation stage. Download data and store it appropriately, Identify how it\u2019s organized, Sort and filter the data, and Determine the credibility of the data. For this project, I have used the publically available data presented by \"Motivate International Inc.\" I have downloaded the latest 12 months Cyclistic bike-sharing Zipped data according to the instruction and up-loaded it into Kaggle under the name of \"bike-share capstone project\". The latest 12 months data seems to be organized. However, there are some minor changes and missing values which will be identified. From the huge data set, we have already shorted and filtered the latest 12 months' data. Determine the credibility of the data. Data was imported from https:\/\/divvy-tripdata.s3.amazonaws.com\/index.html which is a credible source. \n\n**Deliverable**\n   \n  A description of all data sources used. The monthly .csv files as data (April 2020 to March 2021) has been imported from https:\/\/divvy-tripdata.s3.amazonaws.com\/index.html.\n\n\n\n\"\"\"\n# This R environment comes with many helpful analytics packages installed\n# It is defined by the kaggle\/rstats Docker image: https:\/\/github.com\/kaggle\/docker-rstats\n# For example, here's a helpful package to load\n\nlibrary(tidyverse) # metapackage of all tidyverse packages\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\nlist.files(path = \"..\/input\/bike-share-capstone-project\")\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\n\"\"\"\n### Installing packages\n\"\"\"\ninstall.packages(\"tidyverse\")\ninstall.packages(\"lubridate\")\ninstall.packages(\"janitor\")\ninstall.packages(\"ggplot2\")\n\"\"\"\n### Installing libraries \n\"\"\"\nlibrary(tidyverse)\nlibrary(lubridate)\nlibrary(janitor)\nlibrary(ggplot2)\nlibrary(data.table)\nlibrary(dplyr)\n\"\"\"\n### Modifying R options to disable scientific notation in advance\n\"\"\"\noptions(scipen = 999)\n\"\"\"\n### Importing the .csv data \n\n\"\"\"\ntd1 <- read_csv(\"..\/input\/bike-share-capstone-project\/202004-divvy-tripdata.csv\")\ntd2 <- read_csv(\"..\/input\/bike-share-capstone-project\/202005-divvy-tripdata.csv\")\ntd3 <- read_csv(\"..\/input\/bike-share-capstone-project\/202006-divvy-tripdata.csv\")\ntd4 <- read_csv(\"..\/input\/bike-share-capstone-project\/202007-divvy-tripdata.csv\")\ntd5 <- read_csv(\"..\/input\/bike-share-capstone-project\/202008-divvy-tripdata.csv\")\ntd6 <- read_csv(\"..\/input\/bike-share-capstone-project\/202009-divvy-tripdata.csv\")\ntd7 <- read_csv(\"..\/input\/bike-share-capstone-project\/202010-divvy-tripdata.csv\")\ntd8 <- read_csv(\"..\/input\/bike-share-capstone-project\/202011-divvy-tripdata.csv\")\ntd9 <- read_csv(\"..\/input\/bike-share-capstone-project\/202012-divvy-tripdata.csv\")\ntd10 <- read_csv(\"..\/input\/bike-share-capstone-project\/202101-divvy-tripdata.csv\")\ntd11 <- read_csv(\"..\/input\/bike-share-capstone-project\/202102-divvy-tripdata.csv\")\ntd12 <- read_csv(\"..\/input\/bike-share-capstone-project\/202103-divvy-tripdata.csv\")\n\"\"\"\n##### Note: \"td\" stands for \"trip data\" and numbers 1,2,3...12 stands for months accordingly, so \"td1\" means trip data \"202004-divvy-tripdata.csv\" and all the other numbers goes accordingly\n\"\"\"\n\"\"\"\n# PROCESS***\n\"\"\"\n\"\"\"\n##### I choose R as the tool for this analytic project as it contains really big amount of data. R is a strong tool to handle enormous data and for smooth visualization.  \n\"\"\"\n\"\"\"\n### Checking for inconsistency by examining the data structure \n\"\"\"\nstr(td1)\nstr(td2)\nstr(td3)\nstr(td4)\nstr(td5)\nstr(td6)\nstr(td7)\nstr(td8)\nstr(td9)\nstr(td10)\nstr(td11)\nstr(td12)\n\"\"\"\n#### Result: after conducting the examination on the data structures the inconsistency has been found. The \"start_station_id\" and \"end_station_id\" suppose to be character, but in td1, td2, td3, td4, td5, td6, td7,and td8 they are numeric and that need to be fixed.\n\"\"\"\n\"\"\"\n### Transforming\"start_station_id\" and \"end_station_id\" data type to character\n\"\"\"\ntd1 <- mutate(td1,start_station_id = as.character(start_station_id))\ntd2 <- mutate(td2,start_station_id = as.character(start_station_id))\ntd3 <- mutate(td3,start_station_id = as.character(start_station_id))\ntd4 <- mutate(td4,start_station_id = as.character(start_station_id))\ntd5 <- mutate(td5,start_station_id = as.character(start_station_id))\ntd6 <- mutate(td6,start_station_id = as.character(start_station_id))\ntd7 <- mutate(td7,start_station_id = as.character(start_station_id))\ntd8 <- mutate(td8,start_station_id = as.character(start_station_id))\n\n\ntd1 <- mutate(td1,end_station_id = as.character(end_station_id))\ntd2 <- mutate(td2,end_station_id = as.character(end_station_id))\ntd3 <- mutate(td3,end_station_id = as.character(end_station_id))\ntd4 <- mutate(td4,end_station_id = as.character(end_station_id))\ntd5 <- mutate(td5,end_station_id = as.character(end_station_id))\ntd6 <- mutate(td6,end_station_id = as.character(end_station_id))\ntd7 <- mutate(td7,end_station_id = as.character(end_station_id))\ntd8 <- mutate(td8,end_station_id = as.character(end_station_id))\n\"\"\"\n### Combining all 12 months data into one data frame\n\"\"\"\ntrip_data <- rbind(td1,td2,td3,td4,td5,td6,td7,td8,td9,td10,td11,td12)\n\"\"\"\n### Inspecting the combined data frame that has been created recently by calling list of column name\n\"\"\"\ncolnames(trip_data) \n\"\"\"\n### Removing empty rows and columns \n\"\"\"\ntrip_data <-janitor:: remove_empty(trip_data, which = c(\"rows\"))\ntrip_data <-janitor:: remove_empty(trip_data, which = c(\"cols\"))\n\"\"\"\n### Inspecting the numbers of rows in the data frame\n\"\"\"\nnrow(trip_data)\n\"\"\"\n### Inspecting the column names and data types\n\"\"\"\nstr(trip_data)\n\"\"\"\n### Inspecting the statistical summery of data frame \n\"\"\"\nsummary(trip_data)\n\"\"\"\n### Inspecting the number of different member types\n\"\"\"\ntable(trip_data$member_casual)\n\"\"\"\n### Renaming member_casual to rider_type to have a better understanding of the column names\n\"\"\"\ntrip_data <- trip_data %>% rename(rider_type = member_casual)\n\"\"\"\n### Inspecting the rideable bikes types\n\"\"\"\ntable(trip_data$rideable_type)\n\"\"\"\n### Adding date and time data into the data frame\n\"\"\"\ntrip_data$started_at <- lubridate::ymd_hms(trip_data$started_at)\ntrip_data$ended_at <- lubridate::ymd_hms(trip_data$ended_at)\n\"\"\"\n### Adding date field to the data set for future analysis and visualization purpose \n\n\n\"\"\"\ntrip_data$date <- as.Date(trip_data$started_at)\n\"\"\"\n### Creating hour field into the data frame\n\"\"\"\ntrip_data$start_hour <- lubridate::hour(trip_data$started_at)\ntrip_data$end_hour <- lubridate::hour(trip_data$ended_at)\n\"\"\"\n### Adding months and days of the week field in the data frame\n\"\"\"\ntrip_data$months <- months.Date(trip_data$started_at)\ntrip_data$day_of_week <- weekdays.Date(trip_data$started_at)\n\"\"\"\n### Calculating trip length in minutes \n\"\"\"\ntrip_data$trip_length <- difftime(trip_data$ended_at, trip_data$started_at, units = \"mins\")\n\"\"\"\n##### Note: Trip lengths are in minutes but the data type is not numeric \n\"\"\"\n\"\"\"\n### Transforming trip length to numeric to ensure the execution of smooth calculation\n\"\"\"\ntrip_data$trip_length <- as.numeric(as.character(trip_data$trip_length))\n\"\"\"\n### Inspecting the transformed format\n\"\"\"\nis.numeric(trip_data$trip_length)\n\"\"\"\n### Inspecting column structure in the data frame \n\"\"\"\nstr(trip_data)\n\"\"\"\n### Creating new version of the data \n\"\"\"\ntrip_data_V2 <- trip_data[!(trip_data$start_station_name == \"HQ QR\" | trip_data$trip_length < 0),]\n\"\"\"\n### Removing NA for further cleaning the data and creating cleaned version of the data \n\"\"\"\ncleaned_trip_data <- drop_na(trip_data_V2)\n\"\"\"\n### Inspecting summary of the clean data\n\"\"\"\nsummary(cleaned_trip_data)\n\"\"\"\n### Varying if all NA has been removed\n\"\"\"\nsum(is.na(cleaned_trip_data))\n\"\"\"\n### Calling a tibble to have a sink pick of the new data frame\n\"\"\"\ntibble(cleaned_trip_data)\n\"\"\"\n# ANALYZE***\n\"\"\"\n\"\"\"\n##### Key Tasks\n\n1. Aggregate your data so it\u2019s useful and accessible.\n2. Organize and format your data.\n3. Perform calculations.\n4. Identify trends and relationships.\n\n**Deliverable**\n\nA summary of your analysis\n\"\"\"\n\"\"\"\n### Descriptive analysis of tripe_length in minutes\n\n### Calculating the average trip time (total trip length divided by the total number of riders)\n\"\"\"\nmean(cleaned_trip_data$trip_length)\n\"\"\"\n### Calculating the longest ride \n\"\"\"\nmax(cleaned_trip_data$trip_length)\nmedian(cleaned_trip_data$trip_length)\nmin(cleaned_trip_data$trip_length)\n\"\"\"\n### Summary of the trip length data\n\"\"\"\nsummary(cleaned_trip_data$trip_length)\n\"\"\"\n### Finding out mean trip length according to membership type \n\"\"\"\naggregate(cleaned_trip_data$trip_length ~ cleaned_trip_data$rider_type, FUN = mean)\n\"\"\"\n### Finding out average trip length according to membership type\n\"\"\"\naggregate(cleaned_trip_data$trip_length ~ cleaned_trip_data$rider_type, FUN = median)\n\"\"\"\n### Statistical summary of the trip duration according to the customer type\n\"\"\"\ncleaned_trip_data %>% group_by(rider_type)%>%\n  summarise(min_trip_length = min(trip_length), median_trip_length = median(trip_length),\n            max_trip_length = max(trip_length), mean_trip_length = mean(trip_length))\n\"\"\"\n### Finding out mean trip length by months and days of week according to membership type \n\"\"\"\naggregate(cleaned_trip_data$trip_length ~ cleaned_trip_data$rider_type \n          + cleaned_trip_data$day_of_week + cleaned_trip_data$months, FUN = mean)\n\"\"\"\n##### Note: The order of the day and months are not according to the order and we need to fix it for smooth visualization \n\"\"\"\n\"\"\"\n### Fixing the order of months and the day_of_week for the preparation of smooth visualization \n\"\"\"\ncleaned_trip_data$months <- ordered(cleaned_trip_data$months, \n                                         levels = c(\"April\",\"May\",\"June\",\"July\",\n                                                    \"August\",\"September\",\"October\",\n                                                    \"November\",\"December\",\"January\",\"February\",\"March\"))\ncleaned_trip_data$day_of_week <- ordered(cleaned_trip_data$day_of_week, \n                        levels = c(\"Monday\",\"Tuesday\",\"Wednesday\",\n                                   \"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"))\n\"\"\"\n### Checking for the test trips that company made due to quality check and R&D purpose \n\"\"\"\nnrow(subset(cleaned_trip_data, start_station_name %like% \"TEST\"))\nnrow(subset(cleaned_trip_data, start_station_name %like% \"Test\"))\nnrow(subset(cleaned_trip_data, start_station_name %like% \"test\"))\n\"\"\"\n### Removing the test trips form data to ensure the accuracy of the analysis \n\"\"\"\ncleaned_trip_data <- cleaned_trip_data[!(cleaned_trip_data$start_station_name %like% \"TEST\"),]\n\"\"\"\n### Inspection if the TEST data has been removed\n\n\n\n\"\"\"\nnrow(subset(cleaned_trip_data, start_station_name %like% \"TEST\"))\n\"\"\"\n### Checking the data frame\n\n\n\"\"\"\nglimpse(cleaned_trip_data)\n\"\"\"\n### Inspecting the distinct value \n\n\n\"\"\"\ntable(cleaned_trip_data$rider_type)\n\"\"\"\n# SHARE***\n## VISUALIZATION***\n\"\"\"\n\"\"\"\n### Finding out the demand of rideable types according to the number of trips taken bye the types of customers\n\n\n\n\"\"\"\ncleaned_trip_data %>% group_by(rideable_type, rider_type) %>% summarise(number_of_trips = n()) %>%\n  ggplot(aes(x = rideable_type, y= number_of_trips, fill = rider_type)) + geom_col() +\n  labs(title = \"Demand of Rideable type vs number of trips base on rider types\")\n\"\"\"\n##### According to the visualized data, Docked bikes seemed to be the most popular bike among both casual and member riders. Classic bikes and Electric bikes are popular among the member riders. If electric bikes are more expensive to ride for casual riders then the company can consider reducing the riding cost for non-menber riders to increase the demand for electric bikes at least as a campaign. That can possibly attract causal riders to become a member.     \n\"\"\"\n\"\"\"\n### The total number of trips by hours for the 12 months including all stations\n\n\n\"\"\"\ncleaned_trip_data %>% count(start_hour, sort = T) %>% \n  ggplot(aes(x= start_hour, y = n)) + geom_line(size = 1) + \n  labs(title = \"Count of Trips by Hours for Pervious 12 Months\", x = \"Start Hour of Trips\",\n       y = \"Count of Trips\")\n\"\"\"\n##### According to the visualized data, bike demands start rising from 500 hours and the demand keeps increasing throughout the day. The demands are at peak between 1700 to 1800 hours, after that it starts decreasing.\n\"\"\"\n\"\"\"\n### Average trip duration in a day according to the rider type\n\n\n\"\"\"\ncleaned_trip_data %>% \n  group_by(rider_type, day_of_week) %>% summarise(average_trip_length = mean(trip_length)) %>%\n                              ggplot(aes(x = day_of_week, y = average_trip_length, fill = rider_type)) + \n  geom_col(width = 1, position = position_dodge(width = 1)) + labs(title = \"Average Trip Duration in a Day based on rider type\",\n                                                                   x = \"Day of the Week\", y = \"Average Trip Duration\")\n\"\"\"\n##### According to the visualized data, the average trip duration of casual riders seems to be more than double of member riders. That means there are more non-member users than member users. That gives a hint there is a huge amount of non-member users that can be converted as members with proper marketing. The visualization may seem like causal riders are taking longer trips than the member riders which is true to some extent but does not have to possibly be true every time. I could possibly mean there are more casual users than members. The column chart also shows that there are more users during the weekends than on weekdays.\n\"\"\"\n\"\"\"\n### Total number of trips in a month according to the type of riders \n\n\n\"\"\"\ncleaned_trip_data %>% group_by(rider_type, months) %>% summarise(number_of_trips = n()) %>% arrange(rider_type,months) %>%\n  ggplot(aes(x = months, y = number_of_trips, fill = rider_type)) + \n  labs(title = \"Total number of trips in a month\") + geom_col(width = 1, position = position_dodge(width = 1))+\n  theme(axis.text.x = element_text(angle = 30))\n\"\"\"\n##### According to the visualized data, among both types of users bike rides are most popular during the months of summer which is obvious. Then it starts decreasing during the Autumn. The demand is lowes during the Winter season. Then it starts increasing again during the Spring. \n\n##### If the maintenance cost is expensive, the company can stop their operation during the Winter-time and resume it again from Spring. By that time company can put the resource and effort more into R&D to make the service better. \n\"\"\"\n\"\"\"\n### Total number of trips in a day of week according to the type of riders \n\n\"\"\"\ncleaned_trip_data %>% group_by(rider_type, day_of_week) %>% summarise(number_of_trips = n()) %>% arrange(rider_type,day_of_week) %>%\n  ggplot(aes(x = day_of_week, y = number_of_trips, fill = rider_type)) + \n  labs(title = \"Total number of trips in a week based on rider type\") + geom_col(width = 1, position = position_dodge(width = 1))+\n  theme(axis.text.x = element_text(angle = 20))\n\"\"\"\n##### According to the visualized data, the maximum number of trips taken by the member users during the weekdays. During the weekend the non-member users are taking almost the same amount or more rides. The number of trips taken by the member users is almost static or close during the whole week. On the other hand, the riding behavior of casual users seems to be increasing gradually from the beginning of the week and touch the peak during the weekend.\n\"\"\"\n\"\"\"\n### Number of trips according to the rider type and trip date \n\n\n  \n\"\"\"\ncleaned_trip_data %>%\n  group_by(rider_type,date) %>%\n  summarise(number_of_rides = n(), average_duration = mean(trip_length)) %>%\n  arrange(rider_type, date) %>% ggplot(aes(x= date, y= number_of_rides, group = rider_type)) + \n  geom_line(aes(color= rider_type)) + labs(title = \"Number of Rides by Ride Date and Rider type\", X = \"Ride Date\", y = \"Rider Type\") \n\n\"\"\"\n##### According to the visualized data, over the whole 12 months, both member and casual riders took almost the same amount of rides on average. If we look at the graph it may seem the causal riders took more rides than the members, but if we take a closer look into the graph we can easily notice the number of trips that member users took is more constant than the non-member users. The causal riders are at peak only during the summer months where the member users are more constant to use the service through the whole 12 months compared to the casual users. \n\"\"\"\n\"\"\"\n### Creating .csv files by weeks and months for other visualization tools.\n\"\"\"\ntrip_data_by_week <- aggregate(cleaned_trip_data$trip_length ~ cleaned_trip_data$rider_type + \n                                         cleaned_trip_data$day_of_week, FUN = mean)\nwrite.csv(cleaned_trip_data, \"Trip Data by Week.csv\", row.names = F)\ntrip_data_by_months <- aggregate(cleaned_trip_data$trip_length ~ cleaned_trip_data$rider_type +\n                                                + cleaned_trip_data$months, FUN = mean)\nwrite.csv(cleaned_trip_data, \"Trip Data by months.csv\", row.names = F)\n\"\"\"\n# ACT***\n\"\"\"\n\"\"\"\n## Key Findings\n\n* Member riders constantly use the service throughout the week, when Causal riders are more likely to use the service during the weekends.\n* Casual riders seem to have longer rides than member riders.\n* For the obvious reason, both types of customers use the bikes most during the summer season and least in winter.\n* The demand for the bikes is in peak at evening between 1700 to 1800 hours.\n* Docked bikes are the most popular bike among both types of users compared to classic and electric bikes.\n\"\"\"\n\"\"\"\n## Recommendations \n\n* The company should send out attractive promotions to attract more members.\n* Off-peak hours price should be discounted (that may attract younger age group customers more in addition).\n* the company can introduce different levels of membership (that can brings benefits like reduced riding or fees) that can be achieved through membership longevity. \n\"\"\"\n\"\"\"\n## Additional data you could lead to more deep and detail analysis\n\n* Age group data: This could be used to understand the customers better and also can be used to stand out different promotional offers, such as off-peak hours offers.\n* occupational data: This could create different kinds of membership offers, such as Student members, Career partners members (e.g. private courier services, food delivery services), and General members (that includes every one but Students and courier partners).\n\"\"\"\n\"\"\"\n## Resources\n\n* Google Data Analytics Professional Certificate Program\n* Stake Overflow\n* Kaggle Community\n\"\"\"\n\"\"\"\n****************\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '730021d5e508a9'}"}
{"id":"24805","text":"\"\"\"\n#### Loading Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport os \nimport plotly.offline as pyoff\nfrom plotly.offline import iplot,plot,init_notebook_mode\nimport plotly.graph_objs as go\ninit_notebook_mode()\nimport matplotlib.pyplot as plt\n\"\"\"\n#### Loading data\n\"\"\"\nbike_share = pd.read_csv('..\/input\/data.csv')\nbike_share.columns\nbike_share.dtypes\nbike_share.head()\n\"\"\"\n##### Converting data to appropriate types\n\"\"\"\ncat_cols = ['year','day','week']\nbike_share.loc[:,cat_cols] = bike_share.loc[:,cat_cols].astype(str) # converting the categorcical columns to str type \n\"\"\"\nNote : \n     - I have used the terms 'rides' and 'trips' interchangeably.\n     - I have written the aggregated data into csv files to prevent recomputing everytime I close and open the notebook.\n\"\"\"\n\"\"\"\n###### Number of trips taken in each year\n\"\"\"\ntrips_year = pd.DataFrame(bike_share.year.value_counts()).reset_index()\ntrips_year.columns = ['year','trips']\ntrips_year = trips_year.sort_values('year')\n# trips_year.to_csv(\"trips_year.csv\",index = False)\n# trips_year = pd.read_csv(\"trips_year.csv\")\nty = go.Bar(x = \"Year-\"+trips_year.year.astype(str) ,y = trips_year.trips,name = 'Trips',\n           text = trips_year.trips,textposition = 'auto')\nlayout = go.Layout(title = 'Number of trips taken every year')\n\ndata = [ty]\nfig = go.Figure(data= data,layout =layout)\niplot(fig)\n\"\"\"\nPlotly is plotting the years as continuous, I have added the string \"Year-\" to the years to prevent this.\n\"\"\"\n\"\"\"\nOverall, the number of trips have been rising consistently\n\"\"\"\n\"\"\"\n###### How do the number of trips taken vary over time?\n\"\"\"\nfrom datetime import datetime\n\"\"\"\n###### Extracting the date from the startdate column and adding it to the dataframe\n\"\"\"\ndates = bike_share.starttime.apply(lambda x : datetime.strptime(x,\"%Y-%m-%d %H:%M:%S\").date())\nbike_share['startdateonly'] = dates\ndaily = bike_share.groupby(['startdateonly']).size().to_frame().reset_index()\ndaily.columns = ['date','trips']\n# daily.to_csv(\"daily.csv\",index = False)\n# daily= pd.read_csv(\"daily.csv\")\ndata = [go.Scatter(\n          x=daily.date,\n          y=daily.trips)]\nlayout = layout = go.Layout(title = \"Rides taken over the years (timeline)\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\nWe can see an clear pattern here, there is a spike in the months of July, August and September. i.e Q3\nAlso the Q4 have fewer rides in every year\n\n- Q4 can be explained by the holiday season.\n\"\"\"\n\"\"\"\n###### Let us see if the pattern is different among men and women\n\"\"\"\n###### Gender distribution plot\ngender_dist = go.Bar( x= bike_share.gender.value_counts().index,\n                     y = bike_share.gender.value_counts(),\n                     text = bike_share.gender.value_counts(),\n                     textposition = 'auto'\n                    )\nlayout = go.Layout(title = 'Gender Distribution in the dataset')\ndata = [gender_dist]\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\ndaily_gender = bike_share.groupby(['startdateonly','gender']).size().to_frame().reset_index()\ndaily_gender.columns = ['startdateonly','gender','trips']\n# daily_gender.to_csv('daily_gender.csv',index=False)\n# daily_gender = pd.read_csv('daily_gender.csv')\ntrace_Male = go.Scatter(\n                x=daily_gender.startdateonly[daily_gender.gender =='Male'],\n                y=daily_gender.trips[daily_gender.gender =='Male'],\n                name = \"Male\",\n                line = dict(color = 'blue'),\n                opacity = 0.8)\n\ntrace_Female = go.Scatter(\n                x=daily_gender.startdateonly[daily_gender.gender =='Female'],\n                y=daily_gender.trips[daily_gender.gender =='Female'],\n                name = \"Female\",\n                line = dict(color = 'green'),\n                opacity = 0.8)\nlayout = layout = go.Layout(title = \"Rides taken over the years based on gender\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\ndata = [trace_Male,trace_Female]\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\n- Overall the number of rides taken by females is less, but we don't see any perceivable difference in the pattern above.\n- We can conclude that there is no preference given by any gender to a particular time of the year.\n\"\"\"\n\"\"\"\n###### Does the time of day say anything about the number of rides taken?\n\"\"\"\nrides_hour = bike_share.groupby(['hour']).size().reset_index()\nrides_hour.columns = ['hour','trips']\n# rides_hour.to_csv('rides_hour.csv',index= False)\n# rides_hour = pd.read_csv('rides_hour.csv')\nrides_hour.head()\nhour = go.Bar(x = rides_hour.hour.astype(str),\n             y = rides_hour.trips, text = rides_hour.trips,textposition = 'auto')\nlayout = go.Layout(title = 'Rides taken at different hour of the day')\ndata = [hour]\nfig = go.Figure(data= data,layout=layout)\niplot(fig)\n\"\"\"\n- This is a bimodal data, we see that the number of rides taken at 8 am and number rides taken at 5 pm are high, the typical office rush hours.\n\"\"\"\n\"\"\"\n##### Let us see if we can find out more about the trips\n\"\"\"\n\"\"\"\n- I think that if a location has offices,the rides taken aroud 8 AM will end at that location and the rides around 5 pm will start at that location\n\"\"\"\n\"\"\"\n- Let us see where the morning trips were taken to, and also if the trips in the evening were from same location\n\"\"\"\nmorning_rides_start_location = bike_share.to_station_name[(bike_share.hour > 8) & bike_share.hour<9].value_counts()\nevening_rides_end_location = bike_share.from_station_name[(bike_share.hour > 16)& (bike_share.hour <19)].value_counts() \nlen([i for i in morning_rides_start_location.index if i in evening_rides_end_location.index])\nfiltered_time_rides_morning = bike_share[(8<bike_share.hour) & (bike_share.hour>9)]\nfiltered_time_rides_evening = bike_share[(17<bike_share.hour) & (bike_share.hour>19)]\nfiltered_time_rides_morning_grouped = filtered_time_rides_morning.groupby(['to_station_name']).size().to_frame('trips').reset_index()\nfiltered_time_rides_morning_grouped = filtered_time_rides_morning.groupby(['to_station_name']).size().to_frame('trips').reset_index()\nfiltered_time_rides_evening_grouped = filtered_time_rides_evening.groupby(['from_station_name']).size().to_frame('trips').reset_index()\nfiltered_time_rides_morning_grouped.columns = ['station','trips_to']\nfiltered_time_rides_evening_grouped.columns = ['station','trips_from']\nrides_from_to_df = filtered_time_rides_morning_grouped.merge(filtered_time_rides_evening_grouped)\nrides_from_to_df = rides_from_to_df.sort_values(['trips_to','trips_from'],ascending=False)\n# rides_from_to_df.to_csv('rides_from_to_df.csv',index = False)\n# rides_from_to_df = pd.read_csv('rides_from_to_df.csv')\nrides_from_to_df.head()\nrides_from_to_df_plot = rides_from_to_df.head(10)\ntrips_to = go.Bar(x = rides_from_to_df_plot.station,\n                  y = rides_from_to_df_plot.trips_to,\n                  text = rides_from_to_df_plot.trips_to,\n                  textposition = 'auto',name = 'Morning trips ended in')\ntrips_from = go.Bar(x = rides_from_to_df_plot.station,\n                  y = rides_from_to_df_plot.trips_from,\n                  text = rides_from_to_df_plot.trips_from,\n                  textposition = 'auto',name = 'Evening trips started from')\ndata = [trips_to,trips_from]\nlayout = go.Layout(title ='Trips taken in the morning and trips taken in the evening<br>(Top 10 based on counts of places where the trips ended)')\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\n- Based on the information I found on google, the first 4 stations are located in close vicinity and the area is a commercial area, there is a subway staion located here as well, there is a good possibility that people riding to these destinations might have done so to take the subway.\n\"\"\"\n\"\"\"\n###### Let us see if the pattern is different between different type of customers\n\"\"\"\ndaily_usertype = bike_share.groupby(['startdateonly','usertype']).size().to_frame().reset_index()\ndaily_usertype.columns = ['startdateonly','usertype','trips']\n# daily_usertype.to_csv('daily_usertype.csv',index = False)\n# daily_usertype = pd.read_csv('daily_usertype.csv')\ndaily_usertype.usertype.value_counts()\ndaily_usertype.head()\ntrace_Subscriber = go.Scatter(\n                x=daily_usertype.startdateonly[daily_usertype.usertype =='Subscriber'],\n                y=daily_usertype.trips[daily_usertype.usertype =='Subscriber'],\n                name = \"Subscriber\",\n                opacity = 0.8)\n\ntrace_Customer = go.Scatter(\n                x=daily_usertype.startdateonly[daily_usertype.usertype =='Customer'],\n                y=daily_usertype.trips[daily_usertype.usertype =='Customer'],\n                name = \"Customer\",\n                opacity = 0.8)\ntrace_Dependent = go.Scatter(\n                x=daily_usertype.startdateonly[daily_usertype.usertype =='Dependent'],\n                y=daily_usertype.trips[daily_usertype.usertype =='Dependent'],\n                name = \"Dependent\",\n                opacity = 0.8)\n\n\nlayout = layout = go.Layout(title = \"Rides taken over the years based on customer type\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\ndata = [trace_Subscriber,trace_Customer,trace_Dependent]\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\nThe number of trips taken by sucbsribers are far more than those taken by others , we cannot infer much from this graph\n\"\"\"\n\"\"\"\nAlthough on kaggle it says that the trip duration is in seconds but on inspection of the dataset, the trip duration is actually in minutes.\n\"\"\"\nbike_share.starttime[0] ,bike_share.stoptime[0] , bike_share.tripduration[0]\n##### Are people riding more over the years?\ntrip_duration_median = bike_share.groupby(['startdateonly']).agg({'tripduration':np.median}).reset_index()\n# trip_duration_median.to_csv('trip_duration_median.csv',index = False)\n# trip_duration_median =pd.read_csv('trip_duration_median.csv')\ntrip_duration_median.columns\n\"\"\"\n###### Ride time over the years plot\n\"\"\"\ndata = [go.Scatter(\n          x=trip_duration_median.startdateonly,\n          y=trip_duration_median.tripduration)]\nlayout = layout = go.Layout(title = \"Median ride time over the years\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\n- One interesting observation here is that not only the number of rides were high in the Q3, the median duration also was more,\n- Also we see that the median duration varies between 6 Minutes and 13 mintues for the rides in the dataset\n\"\"\"\ntrip_duration_agg_df = bike_share.groupby(['startdateonly']).agg({'tripduration':{\n                                                                        'medianduration' : np.median,\n                                                                        'minduration' : np.min,\n                                                                        'maxduration' : np.max,\n                                                                }}).reset_index()\ntrip_duration_agg_df.columns  = ['startdateonly', 'medianduration', 'minduration', 'maxduration']\n# trip_duration_agg_df.to_csv('trip_duration_agg_df.csv',index = False)\n# trip_duration_agg_df = pd.read_csv('trip_duration_agg_df.csv')\ntrip_duration_agg_df.head()\nminduration = go.Scatter(\n          x=trip_duration_agg_df.startdateonly,\n          y=trip_duration_agg_df.minduration,name ='Minimum duration' )\n               \nmaxduration = go.Scatter(\n          x=trip_duration_agg_df.startdateonly,\n          y=trip_duration_agg_df.maxduration,name = 'Maximum duration')\n\nmedianduration = go.Scatter(\n          x=trip_duration_agg_df.startdateonly,\n          y=trip_duration_agg_df.medianduration,name = 'Median duration')\n\ndata = [minduration,medianduration,maxduration]\n\nlayout = layout = go.Layout(title = \"Ride time over the years\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\nWe see that the max duration is 60 minutes only, this is because the data set was cleaned and all the trips with duration more that 60 minutes were removed by the uploader in kaggle.\n\n\"\"\"\n\"\"\"\n##### Is there a difference in the ride times for different types of customers?\n\"\"\"\nusertype_ridetime_df = bike_share.groupby('usertype').agg({'tripduration' : {'minduration':np.min,\n                                                     'medianduration':np.median,\n                                                     'maxduration':np.max,\n                                                    }}).reset_index()\nusertype_ridetime_df.columns = ['usertype','minduration','medianduration','maxduration']\n# usertype_ridetime_df.to_csv('usertype_ridetime_df.csv',index = False)\n# usertype_ridetime_df = pd.read_csv(\"usertype_ridetime_df.csv\")\nusertype_ridetime_df.head()\nminduration = go.Bar(\n          x=usertype_ridetime_df.usertype, \n          y=usertype_ridetime_df.minduration.round(2),\n    text = usertype_ridetime_df.minduration.round(2),textposition = 'auto' ,\n    name ='Minimum duration' )\n               \nmaxduration = go.Bar(\n          x=usertype_ridetime_df.usertype,\n          y=usertype_ridetime_df.maxduration.round(2),\n     text = usertype_ridetime_df.maxduration.round(2),textposition = 'auto' ,\n    name = 'Maximum duration')\n\nmedianduration = go.Bar(\n          x=usertype_ridetime_df.usertype,\n          y=usertype_ridetime_df.medianduration.round(2),\n     text = usertype_ridetime_df.medianduration.round(2),textposition = 'auto' ,\n    name = 'Median duration')\n\ndata = [minduration,medianduration,maxduration]\n\nlayout = layout = go.Layout(title = \"Median Ride time of different types of customers\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\n- We see that there is not a huge difference in the median ride time between different types of customers \n- but we cannot make conclusions about the maximum time as the dataset was cleaned before \n\"\"\"\n\"\"\"\n#### How are different weather conditions affecting the ride time?\n\"\"\"\n\"\"\"\n###### Trip Counts\n\"\"\"\nusertype_events_counts_df = bike_share.groupby('events').size().to_frame('trips').reset_index()\nusertype_events_counts_df\n# usertype_events_counts_df.to_csv('usertype_events_counts_df.csv',index=False)\n# usertype_events_counts_df = pd.read_csv('usertype_events_counts_df.csv')\ntrace1 = go.Bar(x = usertype_events_counts_df.events,\n               y=usertype_events_counts_df.trips,\n                name = 'Number of trips')\nlayout = go.Layout(title = 'Number of trips in different weather conditions')\n\ndata = [trace1]\nfig = go.Figure(data=data,layout=layout)\niplot(fig)\n\"\"\"\n- Maximum trips are taken on cloudy days!\n\"\"\"\n\"\"\"\n##### Is this trend of taking more trips in cloudy weather consistent over the years?\n\"\"\"\nusertype_events_counts_years_df = bike_share.groupby(['events','year']).size().to_frame('trips').reset_index()\n# usertype_events_counts_years_df.to_csv('usertype_events_counts_years_df.csv',index=False)\n# usertype_events_counts_years_df = pd.read_csv('usertype_events_counts_years_df.csv')\nusertype_events_counts_years_df.head()\n\"\"\"\nPutting events on the x axis and year on the x axis leads to different insights\n\"\"\"\nx = usertype_events_counts_years_df.year.unique()\nclear = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'clear'].trips\ncloudy = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'cloudy'].trips\nnot_clear = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'not clear'].trips\nrain_or_snow = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'rain or snow'].trips\ntstorms = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'tstorms'].trips\nunknown = usertype_events_counts_years_df[usertype_events_counts_years_df.events == 'unknown'].trips\n\nclear  = go.Bar(x =x,\n               y= clear,name = 'clear')\ncloudy  = go.Bar(x =x,\n               y= cloudy,name = 'cloudy')\n\nnot_clear  = go.Bar(x =x,\n               y= not_clear,name = 'not_clear')\n\nrain_or_snow  = go.Bar(x =x,\n               y= rain_or_snow,name = 'rain_or_snow')\n\ntstorms  = go.Bar(x =x,\n               y= tstorms,name = 'tstorms')\n\nunknown  = go.Bar(x =x,\n               y= unknown,name = 'unknown')\n\nlayout = go.Layout(title = 'Number of rides in different weather conditions over the years')\ndata = [clear,cloudy,not_clear,rain_or_snow,tstorms,unknown]\n\nfig = go.Figure(data= data,layout= layout)\niplot(fig)\n\"\"\"\n- Yes, Cloudy weather always had the most number of rides.\n\"\"\"\n\"\"\"\n###### Distribution of rides in different weather conditions over the years\n\"\"\"\nx = usertype_events_counts_years_df.events.unique()\nusertype_events_counts_years_df.year = usertype_events_counts_years_df.year.astype(str)\ny2014 = usertype_events_counts_years_df[usertype_events_counts_years_df.year == '2014'].trips\ny2015 = usertype_events_counts_years_df[usertype_events_counts_years_df.year == '2015'].trips\ny2016 = usertype_events_counts_years_df[usertype_events_counts_years_df.year == '2016'].trips\ny2017 = usertype_events_counts_years_df[usertype_events_counts_years_df.year == '2017'].trips\ny2014  = go.Bar(x =x,\n               y= y2014,name = '2014')\ny2015  = go.Bar(x =x,\n               y= y2015,name = '2015')\n\ny2016  = go.Bar(x =x,\n               y= y2016,name = '2016')\n\ny2017  = go.Bar(x =x,\n               y= y2017,name = '2017')\n\nlayout = go.Layout(title = 'Distribution of rides in different weather conditions over the years')\ndata = [y2014,y2015,y2016,y2017]\n\nfig = go.Figure(data= data,layout= layout)\niplot(fig)\n\"\"\"\n- The number of riders in cloudy weather have always been more, also the number has been rising over the years\n- We can see that over the years, the numeber of rides in thunderstorms remained almost same.\n\"\"\"\n\"\"\"\n##### - But does correlation mean causation? Are the number of rides more in cloudy weather or the weather is mostly cloudy??\n\"\"\"\n\"\"\"\nLet us look at the weather conditions at different stations\n\"\"\"\nbike_share.columns\nprint(\"There are {} unique stations in the dataset\".format(len(bike_share.from_station_name.unique())))\n\"\"\"\nPlotting all of the becomes clumsy here, we will try to look at the stations with atleast 1000 rides\n\"\"\"\nlen(bike_share.from_station_name.value_counts().index[bike_share.from_station_name.value_counts()>10000])\n\"\"\"\nWith that condition in place , the number of stations come down to 280\n\"\"\"\nlen(bike_share.from_station_name.value_counts()>10000)\nrides_stations_weather = bike_share.groupby(['from_station_name','events']).size().to_frame().reset_index()\nrides_stations_weather.columns = ['from_station_name','events','trips']\nrides_stations_weather = rides_stations_weather.sort_values(['from_station_name','events'])\n# rides_stations_weather.to_csv('rides_stations_weather.csv',index=False)\n# rides_stations_weather = pd.read_csv('rides_stations_weather.csv')\ndata = []\nfor i in rides_stations_weather.events.unique():\n    data.append(go.Bar (x = rides_stations_weather[rides_stations_weather.events == i].from_station_name,\n                       y = rides_stations_weather[rides_stations_weather.events == i].trips,\n                       name = i))\nlayout = go.Layout(title = 'Weather conditions at different stations',barmode='stack')\nfig = go.Figure(data= data,layout = layout)\niplot(fig)\n\"\"\"\nIt sure is a lot of data,you can pan and look around, but we can see that most of the plot is orange, and orange corresponds to cloudy weather, so we can safely conclude that the weather is mostly cloudy!\n\"\"\"\n\"\"\"\n###### Is the ride time different in different weather conditions?\n\"\"\"\nusertype_events_df = bike_share.groupby('events').agg({'tripduration' : {'minduration':np.min,\n                                                     'medianduration':np.median,\n                                                     'maxduration':np.max,\n                                                    }}).reset_index()\nusertype_events_df.columns = ['events','minduration','medianduration','maxduration']\n# usertype_events_df.to_csv('usertype_events_df.csv',index=False)\n# usertype_events_df = pd.read_csv('usertype_events_df.csv') \nminduration = go.Bar(\n          x=usertype_events_df.events,\n          y=usertype_events_df.minduration.round(2),\n    text = usertype_events_df.minduration.round(2),textposition = 'auto',\n    name ='Minimum duration' )\n               \nmaxduration = go.Bar(\n          x=usertype_events_df.events,\n          y=usertype_events_df.maxduration.round(2),\n    text = usertype_events_df.maxduration.round(2),textposition = 'auto',\n    name = 'Maximum duration')\n\nmedianduration = go.Bar(\n          x=usertype_events_df.events,\n          y=usertype_events_df.medianduration.round(2),\n     text = usertype_events_df.medianduration.round(2),textposition = 'auto',\n    name = 'Median duration')\n\ndata = [minduration,medianduration,maxduration]\n\nlayout = layout = go.Layout(title = \"Ride time in different weather conditions\",\n    xaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    ),\n    yaxis=dict(\n        autorange=True,\n        showgrid=True,\n        zeroline=True,\n#         showline=True,\n#         ticks='',\n#         showticklabels=False\n    )\n)\nfig = go.Figure(data=data,layout = layout)\niplot(fig)\n\"\"\"\n##### Did subscribers take rides irrespective of the weather conditions?\n\"\"\"\n\"\"\"\nPlotting the precentage of rides taken by different users in different weather conditions\n\"\"\"\nrides_customertype = bike_share.groupby(['events','usertype']).size().to_frame('trips').reset_index()\nrides_customertype = rides_customertype.pivot_table(index= ['events'],columns= ['usertype'],aggfunc=[np.sum],fill_value=0).reset_index()\nrides_customertype.columns = ['events','Customer','Dependent','Subscriber']\nrides_customertype['Other'] = rides_customertype.Dependent+rides_customertype.Customer\n# Here I have divided each value in the Customer and Other column by the corresponsing column total and multiplied it by 100\nrides_customertype['OtherPer'] = (rides_customertype.Other\/rides_customertype.Other.sum())*100\nrides_customertype['SubscriberPer'] = (rides_customertype.Subscriber\/rides_customertype.Subscriber.sum())*100\n# rides_customertype.to_csv('rides_customertype.csv',index=False)\n# rides_customertype = pd.read_csv('rides_customertype.csv')\nrides_customertype\nOtherPer = go.Bar(x = rides_customertype.events,\n                 y = rides_customertype.OtherPer,\n                name = \"Other\")\nSubscriberPer = go.Bar(x = rides_customertype.events,\n                 y = rides_customertype.SubscriberPer,\n                       name = \"Subscriber\")\n\nlayout = go.Layout(title = 'Comparing the Number of rides taken by different types of customers <br> in different weather coditions')\n\ndata = [OtherPer,SubscriberPer]\n\nfig = go.Figure(data= data, layout=layout)\n\niplot(fig)\n\"\"\"\n - Overall,As per the data, we see that surprisingly, the percentage of customers who are not subscribers take more rides in the cloudy environment. Well, who would not?\n\"\"\"\nbike_share.columns\n\"\"\"\n##### Let us try to plot the rides on a map\n\"\"\"\n\"\"\"\nfor lattitude and longitude, I will just take median of the values of the *_start  for simplicity.\n\"\"\"\nlat_lon = bike_share.groupby(['from_station_name']).agg({'latitude_start': {'lat': np.median},\n                                                         'longitude_start':{'lon':np.median}}).reset_index()\nlat_lon.columns = ['from_station_name','lat','lon']\nairports = [ dict(\n        type = 'scattergeo',\n        locationmode = 'USA-states',\n        lon = lat_lon['lon'],\n        lat = lat_lon['lat'],\n        hoverinfo = 'text',\n#         text = df_airports['airport'],\n        mode = 'markers',\n        marker = dict( \n            size=2, \n            color='rgb(255, 0, 0)',\n            line = dict(\n                width=3,\n                color='rgba(68, 68, 68, 0)'\n            )\n        ))]\nflight_paths = []\nfor i in range( len( bike_share.trip_id[0:1000] ) ):\n    flight_paths.append(\n        dict(\n            type = 'scattergeo',\n            locationmode = 'USA-states',\n            lon = [ bike_share['longitude_start'][i], bike_share['longitude_end'][i] ],\n            lat = [ bike_share['latitude_start'][i], bike_share['latitude_end'][i] ],\n            mode = 'lines',\n            line = dict(\n                width = 1,\n                color = 'red',\n            ),\n#             opacity = 0.3,\n        )\n    )\nlayout = dict(\n        title = 'Rides taken in chicago over all the years<br>(Hover for Station names) <br> (plotting only first 1000 rides for now)',\n        showlegend = False, \n        geo = dict(\n            scope='north america',\n            projection=dict(type='azimuthal equal area'),\n            showland = True,\n            landcolor = 'rgb(243, 243, 243)',\n            countrycolor = 'rgb(204, 204, 204)',\n        ),\n    ) \nfig = dict( data=flight_paths + airports, layout=layout )\niplot(fig)","meta":"{'source': 'AI4Code', 'id': '2d9a118c584418'}"}
{"id":"27155","text":"# 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\n# importing libraries\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# loading datasets\ncustomers=pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_customers_dataset.csv')\nsellers=pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_sellers_dataset.csv')\norder_reviews=pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_order_reviews_dataset.csv')\norder_items=pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_order_items_dataset.csv')\nproducts=pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_products_dataset.csv')\ngeolocation = pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_geolocation_dataset.csv')\nproduct_category = pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/product_category_name_translation.csv')\norders = pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_orders_dataset.csv')\npayments = pd.read_csv('\/kaggle\/input\/brazilian-ecommerce\/olist_order_payments_dataset.csv')\n# storing all datasets as a list for future reference\n\nlist_of_all_datasets=['customers','sellers','order_reviews','order_items','products','geolocation','product_category','orders','payments']\n\"\"\"\n### Analysis of Customers Data\n\"\"\"\n# print top 5 values\ncustomers.head(5)\ncustomers.shape\ncustomers.isnull().sum()\n\"\"\"\n#### We can see that there is no null value in Customers dataset\n#### Now, we will try to find no of unique states and city from the Customers Dataset\n\"\"\"\ncustomers.customer_city.unique()\nlen(customers.customer_city.unique())\n\"\"\"\n#### There are total 4119 different Cities from where Customers visit\n\"\"\"\ncustomers.customer_state.unique()\ncustomers.customer_state\nlen(customers.customer_state.unique())\nlen(customers.customer_state)\n\"\"\"\nThere are total 27 different states\n\"\"\"\n\"\"\"\n### Visualisation of Customer Dataset\n\"\"\"\nplt.figure(figsize=(13,7))\nsns.histplot(x=customers['customer_state'],data=customers,color='blue')\nplt.show()\n\"\"\"\n#### From above histogram, we can see that most numbers of customer are from SP (Sao Paul) state,followed by Rj (Rio de Janeiro) state.\n\"\"\"\ntop_10_cities=customers['customer_city'].value_counts().nlargest(10)\ntop_10_cities\ncities=customers['customer_city'].value_counts(ascending=True)\ncities[0:20]\n\"\"\"\n#### We can see that there are so many cites with count 1, they can be said to be city with least customers\n\"\"\"\ncity_df=customers.groupby('customer_city').count()['customer_id'].reset_index()\nsns.barplot(data = city_df.sort_values('customer_id', ascending = False).nlargest(10,'customer_id'), x = 'customer_id', \n            y = 'customer_city',)\nplt.title('Cities with the Most Customers')\nplt.xlabel('City')\nplt.ylabel('Number of Customers')\n\"\"\"\n##### Again the city with most no of customers is Sao Paulo, followed by rio de janeiro\n\"\"\"\n\"\"\"\n### Analyis of products and items\n\"\"\"\nproducts.head()\norder_items.head()\n\"\"\"\n#### From above two datasets, we can see that we can 'inner join' these datasets on products id, Lets see\n\"\"\"\nproducts_and_order_items_df=pd.merge(order_items,products)\nproducts_and_order_items_df.head()\ntop_10_products=products_and_order_items_df['product_category_name'].value_counts().reset_index().nlargest(10, 'product_category_name')\nlowest_10_products=products_and_order_items_df['product_category_name'].value_counts().reset_index().nsmallest(10, 'product_category_name')\ntop_10_products\nlowest_10_products\n\"\"\"\n### Payments Analysis\n\"\"\"\npayments.head()\npayments.payment_type.unique()\n\"\"\"\n#### There are bascially 5 types of payment methods used by the customers\n\"\"\"\ntop_payment_type = payments['payment_type'].value_counts(ascending=False)\ntop_payment_type\n\"\"\"\n#### Out of 5 types of methods, credit card is used on the top, then boleto and then voucher\n\"\"\"\ntype(top_payment_type)\n\"\"\"\n#### Since this is a series object we can draw a histplot using its index and values\n\"\"\"\na = top_payment_type.index\nb = top_payment_type.values\nsns.barplot(x=a,y=b)\n\"\"\"\n##### From the above bar graph we can see that,uses of Credit Card is the highest aroud 75000, then boleto that is slightly less than 20000, \n\"\"\"\n\"\"\"\n### Products Reviews\n\"\"\"\n# we will first see if there is any relation between our product_and_order_items_df, and order_reviews\nproducts_and_order_items_df.head(3)\n# printing top 3 rows or order_reviews\norder_reviews.head(3)\n\"\"\"\n#### We can join it based on order_id column which is common to both, for this we will make another dataframe named \"reviews_df'\n\"\"\"\nreviews_df=pd.merge(products_and_order_items_df, order_reviews)\nreviews_df.head(3)\nreviews_df.shape\norder_reviews['review_score'].value_counts()\norder_reviews['review_score'].unique()\n\"\"\"\n#### Ratings points are discrete, starting from 1 to 5.\n\"\"\"\nsns.barplot(x=order_reviews['review_score'].value_counts().index,y=order_reviews['review_score'].value_counts().values)\nplt.xlabel('Ratings')\nplt.ylabel('Counts')\n\"\"\"\nMost of the products have been rated 5,then 4.\nalso 1 rating is higher than 2 and 3\n\n\"\"\"\n\"\"\"\n### Top Ten rated products\n\"\"\"\nreviews_df.head(3)\nproduct_reviews_mean = reviews_df.groupby('product_category_name').mean()['review_score'].reset_index()\nproduct_reviews_mean.head(3)\ntop_10_ratings = product_reviews_mean.sort_values('review_score', ascending = False).nlargest(10,'review_score')\nlowest_10_ratings = product_reviews_mean.sort_values('review_score', ascending = False).nsmallest(10,'review_score')\nsns.barplot(data = top_10_ratings, x = 'review_score', y = 'product_category_name')\nplt.title('Top 10 Product Ratings')\nplt.xlabel('Average Rating')\nplt.ylabel('Product Category Name')\n\"\"\"\n#### Music, dvd, and cds category have the highest average ratings. after tha infant's fashion clothes come.\n\"\"\"\nsns.barplot(data = lowest_10_ratings, x = 'review_score', y = 'product_category_name')\nplt.title('Lowest 10 Product Ratings')\nplt.xlabel('Average Rating')\nplt.ylabel('Product Category Name')\n\"\"\"\n#### Insurance Services have the worst ratings, followed by fraldas higiene products\n\"\"\"\n# list print again list of all datasets\nlist_of_all_datasets\ngeolocation.head()\ngeolocation.isnull().sum()\nlen(geolocation.geolocation_city.unique())\n\"\"\"\n#### There are 8011 unique city from geolocation data.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '31f1f5e4df7a91'}"}
{"id":"93537","text":"\"\"\"\nCredits to **Hans Rosling**\n\"\"\"\nimport plotly_express as px\npx.scatter(px.data.gapminder(), x = \"gdpPercap\", y = \"lifeExp\", animation_frame = \"year\", animation_group = \"country\",\n          size = \"pop\", color = \"country\", log_x = True, size_max = 45,\n          range_x = [100, 100000], range_y = [25, 90])","meta":"{'source': 'AI4Code', 'id': 'aba873879deba5'}"}
{"id":"8596","text":"# 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\n\"\"\"\n# Problem Statement\n\nFind the best strategies to improve for the next marketing campaign. How can the financial institution have a greater effectiveness for future marketing campaigns? In order to answer this, we have to analyze the last marketing campaign the bank performed and identify the patterns that will help us find conclusions in order to develop future strategies\n\"\"\"\n\"\"\"\n# Please note the analysis is in progress.\n\"\"\"\n\"\"\"\n# Read Dataset\n\"\"\"\ndf = pd.read_csv('..\/input\/bank-marketing-dataset\/bank.csv')\ndf.head()\ndf.info()\n\"\"\"\n# Feature\/column description\n1. Age - Age of the customer - Integer value\n2. job - Job of the customer - Categorical feature\n3. marital - Marital status of the customer- Categorical feature\n4. education - eduction status - categorical feature\n5. default - whether the custome is defaulter or not - categorical feature\n6. balance - yearly account balance of the customer - continueous feature\n7. housing - housing status of the customer - categorical feature\n8. loan - whether the customer availed any loans - categorical feature\n9. contact - how many times the customer has been contacted - categorical feature\n10. day - day from last contact - discrete feature\n11. month - month from last contacted date - categorical feature. \n12. duration - duration of last contact in hours - contineous feature\n13. campaign - contact with how many campaign - categorical feature\n\n\"\"\"\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.gridspec import GridSpec\ncols= ['#00876c','#85b96f','#f7e382','#f19452','#d43d51']\nsns.palplot(cols)\nfig=plt.figure(figsize=(15,8), facecolor=(0.2,0.0,0.0,0.0), edgecolor='black')\nplt.suptitle(\"Compare the deposit by Age\", family='Serif', size=15,weight='bold')\n\nplt.figtext(0.5,0.93,\"Histogram and boxplot to identify the mid value of Age by deposits\", family='Serif', size=12, ha='center')\ngs = GridSpec(nrows=2, ncols=4, figure=fig)\nax1=plt.subplot(gs[0,:3])\n\n\nsns.histplot(data=df, x='age', bins=10, ax=ax1, kde=True, hue='deposit', multiple='layer', element='bars', palette=['#00876c','#d43d51']);\nax2=plt.subplot(gs[0,3:4], sharey=ax1)\nsns.histplot(data=df[df['deposit']=='yes'], x='age', bins=10, ax=ax2, kde=True, color=['#00876c']);\nax2.yaxis.set_visible(False)\n\n\n\nax4=plt.subplot(gs[1,:4])\nsns.boxplot(data=df[df['deposit']=='yes'], x='age', ax=ax4, palette=['#00876c']);\nax4.yaxis.set_visible(False)\nax4.text(60,0.15,\"Mean value: {:.2f}\".format(df[df['deposit']=='yes']['age'].mean()))\nax4.text(60,0.20,\"Median value: {:.2f}\".format(df[df['deposit']=='yes']['age'].median()))\nax4.text(60,0.25,\"Frequent age : {:.2f}\".format(df[df['deposit']=='yes']['age'].mode().max()))\nfor i in ['left','right','bottom','top']:\n    ax1.spines[i].set_visible(False)\n    ax2.spines[i].set_visible(False)\n    ax4.spines[i].set_visible(False)\n\"\"\"\n**Observation:** Interesting outcome from the above graph. deposit starts at the age of 20+ and peack is between 30, 50. frequntly deposit age is 32. in addtion Non deposite age is between 30-50 years with mean is around 35-40 years\n\"\"\"\nfig = plt.figure(figsize=(12,8))\ngs = GridSpec(ncols=3, nrows=2, figure=fig)\nplt.suptitle(\"Box plot to compare the age by marital status and deposits\", family='Serif', weight='bold', size=15)\nfor i,c in enumerate(df['marital'].unique()):\n    ax=plt.subplot(gs[0,i])\n    ax=sns.boxplot(y=df[df['marital']==c]['age'], x=df['deposit'],palette=['#00876c','#d43d51']);\n    ax.spines['left'].set_visible(False)\n    ax.spines['right'].set_visible(False)\n    ax.spines['top'].set_visible(False)\n    ax.spines['bottom'].set_visible(False)\n\nax=plt.subplot(gs[1,:])\nax=sns.boxplot(data=df[df['deposit']=='yes'],y='marital',x='age', palette=['#00876c','#d43d51','#f7e382'])\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.spines['bottom'].set_visible(False)\n\nplt.figtext(0.05,-0.05,\"Observation:\\n Obivous that the single's deposit is less compared to married & divorced.\\n Married average age starts from 35+ to 60.\\n divorced ages is between 40 to 60 & singel ages is between 28 to 35.\\n Reason could be that the single might get married after 35 years approximately\",\n           family='San', size=12, ha='left')\n\nfig = plt.figure(figsize=(12,8))\nax=sns.countplot(data=df, x='loan', hue='deposit', palette=['#00876c','#d43d51'])\nax.set_title('Comparison of Loan and deposit', font='Serif', weight='bold', size=15)\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.spines['bottom'].set_visible(False)\nplt.figtext(0.05,-0.05,\"Observation: People who has loan, have not deposited\",\n           family='San', size=12, ha='left')\nfig = plt.figure(figsize=(12,8))\ngs = GridSpec(ncols=3, nrows=2, figure=fig)\nplt.suptitle(\"Box plot to compare the age by marital status and deposits\", family='Serif', weight='bold', size=15)\nfor i,c in enumerate(df['loan'].unique()):\n    ax=plt.subplot(gs[0,i])\n    ax=sns.boxplot(y=df[df['loan']==c]['age'], x=df['deposit'],palette=['#00876c','#d43d51']);\n    ax.spines['left'].set_visible(False)\n    ax.spines['right'].set_visible(False)\n    ax.spines['top'].set_visible(False)\n    ax.spines['bottom'].set_visible(False)\n    ax.set_title(\"Loan : {}\".format(c))\n\nax=plt.subplot(gs[1,:])\nax=sns.boxplot(data=df[df['deposit']=='yes'],y='loan',x='age', palette=['#00876c','#d43d51','#f7e382'])\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.spines['bottom'].set_visible(False)\n\nplt.figtext(0.05,-0.05,\"Observation:\\n Loan has bigger impact on the deposits, people who has loans has less deposits.\\n people deposited with loan is between the age of 30 to 50. people deposited without loan is from 30 to 60 year. so people getting olde preferes deposits than the loan\",\n           family='San', size=12, ha='left')\ndf.groupby(['loan']).describe()['age']\nfig = plt.figure(figsize=(12,8))\nax=sns.scatterplot(data=df, x='age',y='balance', hue='deposit',palette=['#00876c','#d43d51'])\nax.set_ylim(0,4000)\nplt.figtext(0.05,-0.05,\"Observation: There is no significant relationship in age and balance. \",\n           family='San', size=12, ha='left')\n\nfig=plt.figure(figsize=(15,8))\n\nplt.suptitle(\"Comparision of Age & Balance by Deposit\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"Line plot shows that the increase in balance after 80 year\", family='Serif', size=12, ha='center')\ngs = GridSpec(nrows=3, ncols=1, height_ratios=[5,2,2])\nax1=plt.subplot(gs[0,0])\nax1=sns.lineplot(data=df,y='balance',x='age', hue='deposit',palette=['#00876c','#d43d51'])\nax2=plt.subplot(gs[1,0])\nax2=sns.barplot(data=df[df['deposit']=='yes'],y='balance',x='age', hue='deposit', palette=['#00876c'], ci=False)\nax3=plt.subplot(gs[2,0])\nax3=sns.barplot(data=df[df['deposit']=='no'],y='balance',x='age', hue='deposit', palette=['#d43d51'], ci=False)\nfor i in ['left','right','bottom','top']:\n    ax1.spines[i].set_visible(False)\n    ax2.spines[i].set_visible(False)\n    ax3.spines[i].set_visible(False)\nplt.figtext(0.05,-0.05,\"Observation: Balance in deposit increases by Age\",\n           family='San', size=12, ha='left')\ndf.groupby(['age'])['balance'].mean().nlargest(5).to_frame().T\nfig=plt.figure(figsize=(12,8))\nax=sns.kdeplot(df['balance'], fill=True,palette=['#00876c','#d43d51'])\nax.axvline(df['balance'].mean(),c='r',ls='--')\nax.text(x=df['balance'].mean(),y=0.0002,s=\"mean value\", rotation=90)\nfig=plt.figure(figsize=(12,8))\nax.axvline(df['balance'].median(),c='blue',ls='--')\nax.text(x=df['balance'].median(),y=0.0002,s=\"mean value\", rotation=90)\nax.set_xlim(-5000,20000)\n# lets check if campaign has significant change in deposit\nfig=plt.figure(figsize=(12,8))\nsns.countplot(data=df,x='campaign',hue='deposit', palette=['#00876c','#d43d51'])\n\nfig = plt.figure(figsize=(12,8))\nplt.suptitle(\"Comparision of Education with deposit\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"comparing the ecucation impact on deposit\", family='Serif', size=12, ha='center')\ngs = GridSpec(nrows=1, ncols=2, width_ratios=[5,2])\nax1=plt.subplot(gs[0,0])\nax1=plt.pie(df[df['deposit']=='yes']['education'].value_counts(), labels=df[df['deposit']=='yes']['education'].unique(), autopct='%2d', colors=cols)\nax2=plt.subplot(gs[0,1])\nax2=plt.pie(df[df['deposit']=='no']['education'].value_counts(), labels=df[df['deposit']=='no']['education'].unique(), autopct='%2d', colors=cols)\nfig = plt.figure(figsize=(12,8))\ndf1=df.groupby('education')['balance'].sum().reset_index()\nplt.suptitle(\"Comparison of balance with education\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"compare and see if the eduction increases the balance\", family='Serif', size=12, ha='center')\nax=sns.barplot(data=df1, y='education',x='balance', palette=cols, ci=False)\n#ax.set_xlim(0,20000)\nfor i in ['left','right','bottom','top']:\n    ax.spines[i].set_visible(False)\n\nfor y,x in enumerate(df1['balance']):\n    ax.text(x=x\/2,y=y, s=x)\n\nplt.figtext(0.05,-0.05,\"Observation: Education level Secondary & Tertiary has higher balance\",\n           family='San', size=12, ha='left')\nsns.pairplot(df, hue='deposit')\nfig = plt.figure(figsize=(12,8))\nsns.heatmap(df.corr(), cmap=cols, annot=True, linewidths=0.5)\n\"\"\"\n# Data preparation\n\"\"\"\ndf.isna().sum()\ndf.head()\n\"\"\"\n# One hot encoding\n\"\"\"\ndf['deposit']=df['deposit'].map({'yes':1,'no':0})\ndf2=pd.get_dummies(df,drop_first=True)\nX=df2.drop(['deposit'], axis=1)\ny=df2['deposit']\n\"\"\"\n# Train Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=42)\n\"\"\"\n# Standardise the Variables\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\nX_train=scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\"\"\"\n# Model Creation\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom yellowbrick.classifier import ROCAUC, ClassificationReport, ClassificationScoreVisualizer\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train)\nmodel.score(X_test ,y_test)\npred=model.predict(X_test)\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nprint(accuracy_score(y_test,pred))\nprint(classification_report(y_test,pred))\n\n## Yellow brick reports\nfig = plt.figure(figsize=(20,8))\ngs=GridSpec(nrows=1, ncols=2)\nplt.suptitle(\"Classification Reports\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"Classification report based on the Logisitic regression model\", family='Serif', size=12, ha='center')\nax1=plt.subplot(gs[0,0])\nax1.set(title='ROC Curve')\nvisual = ROCAUC(model, classes=[0,1])\nvisual.fit(X_train,y_train)\nax1=visual.score(X_test,y_test)\n\nax2=plt.subplot(gs[0,1])\nax2.set(title='Classification report')\nax2=ClassificationReport(model,classes=[0,1], support=True).fit(X_train,y_train).score(X_test,y_test)\n\nplt.figtext(0.05,-0.05,\"Observation: Logistic Regression performed well with Accuracy score of 83%\",\n           family='Serif', size=14, ha='left', weight='bold')\n\"\"\"\n# Support Vector Machine\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom yellowbrick.classifier import ROCAUC, ClassificationReport, ClassificationScoreVisualizer\nmodel = KNeighborsClassifier()\nmodel.fit(X_train, y_train)\nmodel.score(X_test ,y_test)\npred=model.predict(X_test)\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nprint(accuracy_score(y_test,pred))\nprint(classification_report(y_test,pred))\n\n## Yellow brick reports\nfig = plt.figure(figsize=(20,8))\ngs=GridSpec(nrows=1, ncols=2)\nplt.suptitle(\"Classification Reports\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"Classification report based on the KNeighborsClassifier model\", family='Serif', size=12, ha='center')\nax1=plt.subplot(gs[0,0])\nax1.set(title='ROC Curve')\nvisual = ROCAUC(model, classes=[0,1])\nvisual.fit(X_train,y_train)\nax1=visual.score(X_test,y_test)\n\nax2=plt.subplot(gs[0,1])\nax2.set(title='Classification report')\nax2=ClassificationReport(model,classes=[0,1], support=True).fit(X_train,y_train).score(X_test,y_test)\n\nplt.figtext(0.05,-0.05,\"Observation: KNeighborsClassifier performed well with Accuracy score of 77%\",\n           family='Serif', size=14, ha='left', weight='bold')\nfrom sklearn.tree import DecisionTreeClassifier\nfrom yellowbrick.classifier import ROCAUC, ClassificationReport, ClassificationScoreVisualizer\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, y_train)\nmodel.score(X_test ,y_test)\npred=model.predict(X_test)\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nprint(accuracy_score(y_test,pred))\nprint(classification_report(y_test,pred))\n\n## Yellow brick reports\nfig = plt.figure(figsize=(20,8))\ngs=GridSpec(nrows=1, ncols=2)\nplt.suptitle(\"Classification Reports\", family='Serif', size=15, ha='center', weight='bold')\nplt.figtext(0.5,0.93,\"Classification report based on the DecisionTreeClassifier\", family='Serif', size=12, ha='center')\nax1=plt.subplot(gs[0,0])\nax1.set(title='ROC Curve')\nvisual = ROCAUC(model, classes=[0,1])\nvisual.fit(X_train,y_train)\nax1=visual.score(X_test,y_test)\n\nax2=plt.subplot(gs[0,1])\nax2.set(title='Classification report')\nax2=ClassificationReport(model,classes=[0,1], support=True).fit(X_train,y_train).score(X_test,y_test)\n\nplt.figtext(0.05,-0.05,\"Observation: DecisionTreeClassifier performed well with Accuracy score of 79%\",\n           family='Serif', size=14, ha='left', weight='bold')","meta":"{'source': 'AI4Code', 'id': '0fe73abc4a6c7d'}"}
{"id":"105510","text":"\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# importing libraries\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n# reading dataset\nds = pd.read_csv('\/kaggle\/input\/housing-in-london\/housing_in_london_monthly_variables.csv')\nds.head()\nds.info()\n# checking null values\nds.isnull().sum()\n\"\"\"\n**Preprocessing the data for removing 'nan' values**\n\"\"\"\n# filling null values with their corresponding mean of columns\nmean_of_hs = ds['houses_sold'].mean()        \nmean_of_noc = ds['no_of_crimes'].mean()\n\nds = ds.fillna({'houses_sold' : mean_of_hs})\nds = ds.fillna({'no_of_crimes' : mean_of_noc})\nds.isnull().sum()\n\"\"\"\n# Encoding string to integar\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\n\narea = LabelEncoder()\ncode = LabelEncoder()\n\nds['area_n'] = area.fit_transform(ds['area'])\nds['code_n'] = code.fit_transform(ds['code'])\nds.drop(['area','code','date'], axis = 1, inplace=True)\nds\n\"\"\"\n# Balancing DataSet\n\"\"\"\nds['borough_flag'].value_counts()\nborough_flag_1 = ds[ds['borough_flag']==1]\nborough_flag_0 = ds[ds['borough_flag']==0]\n\nborough_flag_1.shape , borough_flag_0.shape\nborough_flag_1 = borough_flag_1.sample(n=borough_flag_0.shape[0])\nborough_flag_1.shape\ndf = borough_flag_0.append(borough_flag_1, ignore_index=True)\ndf.shape\ndf['borough_flag'].value_counts()\n\"\"\"\n## Spliting data into train and test  \n\"\"\"\nx = df.drop('borough_flag', axis=1)\ny = df['borough_flag']\nfrom sklearn.model_selection import train_test_split\n\nx_train,x_test,y_train,y_test = train_test_split(x,y, test_size = 0.25)\nx_train.shape , x_test.shape\n\"\"\"\n# standardizing data\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.transform(x_test)\n\ny_train = y_train.to_numpy()\ny_test = y_test.to_numpy()\n\"\"\"\n# **ML Models for borough_flag**\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\ndt = DecisionTreeClassifier()\ndt.fit(x_train,y_train)\ndt.score(x_test,y_test)\nrf = RandomForestClassifier()\nrf.fit(x_train,y_train)\nrf.score(x_test,y_test)\nxgb = XGBClassifier()\nxgb.fit(x_train,y_train)\nxgb.score(x_test,y_test)\n\"\"\"\n## Confusion Matrix\n\"\"\"\ny_pred = rf.predict(x_test)\n\ncm = confusion_matrix(y_test, y_pred)\nprint('Confusion Matrix\\n',cm)\nplt.figure(figsize=(7,5))\nsns.heatmap(cm,annot=True)\nplt.xlabel('Predicted')\nplt.ylabel('truth')\n\"\"\"\n# **ML Models for houses_sold**\n\"\"\"\n\"\"\"\nspliting data into train and test\n\"\"\"\nx = df.drop('houses_sold',axis=1)\ny = df['houses_sold']\n\nx_train,x_test,y_train,y_test = train_test_split(x,y, test_size = 0.25)\nx_train.shape , x_test.shape\n\"\"\"\nstandardizing data\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.transform(x_test)\n\ny_train = y_train.to_numpy()\ny_test = y_test.to_numpy()\n\nfrom xgboost import XGBRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nxgbr = XGBRegressor()\nxgbr.fit(x_train,y_train)\nxgbr.score(x_test,y_test)\ndtr = DecisionTreeRegressor()\ndtr.fit(x_train,y_train)\ndtr.score(x_test,y_test)\nknnr = KNeighborsRegressor()\nknnr.fit(x_train,y_train)\nknnr.score(x_test,y_test)\nrfr = RandomForestRegressor()\nrfr.fit(x_train,y_train)\nrfr.score(x_test,y_test)\ny_pred2 = knnr.predict(x_test)\ny_pred2","meta":"{'source': 'AI4Code', 'id': 'c1d8d522a6fe71'}"}
{"id":"98724","text":"\"\"\"\n## About this Notebook\nIn this notebook, we learn how to use scikit-learn to implement simple linear regression. We [download](https:\/\/open.canada.ca\/data\/en\/dataset\/98f1a129-f628-4ce4-b24d-6f16bf24dd64) a dataset that is related to **fuel consumption** and **Carbon dioxide emission** of cars. Then, we split our data into **training** and **test** sets, create a model using training set, evaluate your model using test set, and finally use model to predict unknown value.\n\"\"\"\n\"\"\"\n## Importing Needed packages\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pylab as pl\nimport numpy as np\n%matplotlib inline\n\"\"\"\n## Reading the data\n\"\"\"\ndf = pd.read_csv(\"..\/input\/fuelconsumptionco2\/FuelConsumptionCo2.csv\")\n\n# take a look at the dataset\ndf.head()\n\"\"\"\n## Data Exploration\nLets first have a descriptive exploration on our data.\n\"\"\"\n# summarize the data\ndf.describe()\n\"\"\"\nLets select some features to explore more.\n\"\"\"\ncdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\ncdf.head(9)\n\"\"\"\nWe can plot each of these features:\n\"\"\"\nviz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]\nviz.hist()\nplt.show()\n\"\"\"\nNow, lets plot each of these features vs the Emission, to see how linear is their relation:\n\"\"\"\nplt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS,  color='blue')\nplt.xlabel(\"FUELCONSUMPTION_COMB\")\nplt.ylabel(\"Emission\")\nplt.show()\nplt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS,  color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()\n\"\"\"\n## Practice\nplot **CYLINDER** vs the Emission, to see how linear is their relation:\n\"\"\"\n# write your code here\nplt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS,  color='blue')\nplt.show()\n\"\"\"\n## Creating train and test dataset\nTrain\/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive. After which, you train with the training set and test with the testing set. This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have been used to train the data. It is more realistic for real world problems.\n\nThis means that we know the outcome of each data point in this dataset, making it great to test with! And since this data has not been used to train the model, the model has no knowledge of the outcome of these data points. So, in essence, it is truly an out-of-sample testing.\n\nLets split our dataset into train and test sets, 80% of the entire data for training, and the 20% for testing. We create a mask to select random rows using **np.random.rand()** function:\n\"\"\"\nmsk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]\n\"\"\"\n## Simple Regression Model\nLinear Regression fits a linear model with coefficients  \u03b8=(\u03b81,...,\u03b8n)  to minimize the 'residual sum of squares' between the independent x in the dataset, and the dependent y by the linear approximation.\n\"\"\"\n\"\"\"\n## Train data distribution\n\"\"\"\nplt.scatter(train.ENGINESIZE, train.CO2EMISSIONS,  color='blue')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\nplt.show()\n\"\"\"\n## Modeling\nUsing sklearn package to model data.\n\"\"\"\nfrom sklearn import linear_model\nregr = linear_model.LinearRegression()\ntrain_x = np.asanyarray(train[['ENGINESIZE']])\ntrain_y = np.asanyarray(train[['CO2EMISSIONS']])\nregr.fit (train_x, train_y)\n# The coefficients\nprint ('Coefficients: ', regr.coef_)\nprint ('Intercept: ',regr.intercept_)\n\"\"\"\nAs mentioned before, Coefficient and Intercept in the simple linear regression, are the parameters of the fit line. Given that it is a simple linear regression, with only 2 parameters, and knowing that the parameters are the intercept and slope of the line, sklearn can estimate them directly from our data. Notice that all of the data must be available to traverse and calculate the parameters.\n\"\"\"\n\"\"\"\n## Plot outputs\nwe can plot the fit line over the data:\n\"\"\"\nplt.scatter(train.ENGINESIZE, train.CO2EMISSIONS,  color='blue')\nplt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')\nplt.xlabel(\"Engine size\")\nplt.ylabel(\"Emission\")\n\"\"\"\n## Evaluation\nwe compare the actual values and predicted values to calculate the accuracy of a regression model. Evaluation metrics provide a key role in the development of a model, as it provides insight to areas that require improvement.\n\nThere are different model evaluation metrics, lets use MSE here to calculate the accuracy of our model based on the test set:\n\n* Mean absolute error: It is the mean of the absolute value of the errors. This is the easiest of the metrics to understand since it\u2019s just average error.\n* Mean Squared Error (MSE): Mean Squared Error (MSE) is the mean of the squared error. It\u2019s more popular than Mean absolute error because the focus is geared more towards large errors. This is due to the squared term exponentially increasing larger errors in comparison to smaller ones.\n* Root Mean Squared Error (RMSE): This is the square root of the Mean Square Error.\n* R-squared is not error, but is a popular metric for accuracy of your model. It represents how close the data are to the fitted regression line. The higher the R-squared, the better the model fits your data. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).\n\"\"\"\nfrom sklearn.metrics import r2_score\n\ntest_x = np.asanyarray(test[['ENGINESIZE']])\ntest_y = np.asanyarray(test[['CO2EMISSIONS']])\ntest_y_hat = regr.predict(test_x)\n\nprint(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y_hat - test_y)))\nprint(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y_hat - test_y) ** 2))\nprint(\"R2-score: %.2f\" % r2_score(test_y_hat , test_y) )","meta":"{'source': 'AI4Code', 'id': 'b55cab519ebf71'}"}
{"id":"3775","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\n\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\"\"\"\n# Loading dataset\n\"\"\"\ncancer = pd.read_csv(\"\/kaggle\/input\/breast-cancer-prediction-dataset\/Breast_cancer_data.csv\")\ncancer.head()\n\"\"\"\n# Check if there is missing data\n\"\"\"\ncancer.describe().T\n\"\"\"\nClearly, there is no missing data so we can proceed with the next steps:\n1. Scaling\n2. Visualization\n3. Modification (if required)\n\"\"\"\n\"\"\"\n# Data Scaling\n\"\"\"\nscaler = MinMaxScaler()\ncancer = pd.DataFrame(data=scaler.fit_transform(cancer), columns=cancer.columns)\ncancer.head()\n\"\"\"\n# Data Visualization\n\"\"\"\nsns.pairplot(data=cancer)\n\"\"\"\nFrom the above pairplot it is clearly visible that \"mean_area\", \"mean_radius\" and \"mean_perimeter\" are closely related to one another and can thereby be removed to reduce collinearity. Same can be visualized using the heatmap (as shown below)\n\"\"\"\nplt.figure(figsize=(10, 8))\nsns.heatmap(cancer.corr(), annot=True)\ntarget = cancer.diagnosis\nfeatures = cancer.drop(columns=[\"diagnosis\"])\n\"\"\"\n# Removing multi-colilinearity using VIF\nHere we remove the features that increase the multi-collinearity of the data distribution. We do this using variance_inflation_factor\n\"\"\"\nwhile True:\n    temp_var = 0\n    temp_col = \"\"\n    for i in range(features.shape[1]):\n        if variance_inflation_factor(features.values, i) > temp_var:\n            temp_col = features.columns[i]\n            temp_var = variance_inflation_factor(features.values, i)\n    if temp_var > 5:\n        print(\"Dropping feature '{}' which has a VIF value: {}\\n\".format(temp_col, temp_var))\n        features.drop(columns=[temp_col], inplace=True)\n    else:\n        break\n        \nprint(\"Final Features with VIF <=5:\")\nfor i in range(features.shape[1]):\n    print(features.columns[i], variance_inflation_factor(features.values, i))\n\"\"\"\n# Splitting data into training and test set\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(features, target, random_state=0)\n\"\"\"\n# Using different classification models and selecting the best fit\n\"\"\"\nmodel_data = []\nlistOfModels = [LogisticRegression(), LogisticRegressionCV(), KNeighborsClassifier(), SVC(), GradientBoostingClassifier(), DecisionTreeClassifier()]\n\nfor model in listOfModels:\n    classifier = model\n    classifier.fit(X_train, y_train)\n    y_pred = classifier.predict(X_test)\n    model_data.append([model.__class__.__name__, roc_auc_score(y_test, y_pred)])\n    \nmodel_data_frame = pd.DataFrame(columns=[\"Model\", \"ROC_Score\"], data=model_data)\nprint(model_data_frame.sort_values(\"ROC_Score\"))\n\"\"\"\nGradient Boosting Classifier is the best fitting model amongst all. We'll now derive its confusion matrix and plot auc-roc curve\n\"\"\"\nprint(\"Confusion Matrix\")\nprint(pd.DataFrame(data=confusion_matrix(y_test, y_pred), columns=[\"Predicted True\", \"Predicted False\"], index=[\"Actual True\", \"Actual False\"]))\nfalsePositive, truePositive, threshold = roc_curve(y_test, y_pred, pos_label=1)\nplt.figure(figsize=(10, 8))\nsns.lineplot(falsePositive, truePositive)\nplt.title(\"ROC - AUC Curve\")","meta":"{'source': 'AI4Code', 'id': '070ea4ac2c749c'}"}
{"id":"77108","text":"\"\"\"\n# What is about ?\n\nDataset is downloaded from https:\/\/amp.pharm.mssm.edu\/archs4\/download.html\nThe methods are described in Nature Communications paper: https:\/\/www.nature.com\/articles\/s41467-018-03751-6\n\nThe ARCHS4 data provides user-friendly access to multiple gene expression data from the GEO database. (https:\/\/www.ncbi.nlm.nih.gov\/geo\/ ).  While in GEO database most of data is stored in raw formats,\nARCHS4 provides prepared count matrix expression data. While GEO contains data stored separately for each research paper,\nARCHS4 collects all the information in one single matrix. One may consult the main site for further information.  \n\n\nMain data files are in H5 (HD5, Hierarchical Data Format ) file format https:\/\/en.wikipedia.org\/wiki\/Hierarchical_Data_Format\nIt contains expression data, as well as annotation data and futher meta-information. There are several other auxilliary files like TSNE 3d projection (in CSV format) and correlation matrices for genes for human and mouse in feather format. \n\nThe notebook below gives examples how to work with such files. \n\nThe ARCHS4 project is by :\n\n'Alexander Lachmann', 'alexander.lachmann@mssm.edu', update: '2020-02-06'\n\n\"\"\"\n\"\"\"\n## Some details on data\n\nThe file human_matrix.h5 - is version of 8 of the data file.\nIt contains expressions of 35238 genes for  238522 samples. Same file contains meta-information - gene names, sources of data etc \n\nExpression files for mouse and human in HDF5 format. All gene counts are on gene level (Entrez Gene Symbol). For compression purposes the Kallisto pseudocounts are rounded to integer values.\n\n\nSmall csv files like sample_human_tsne.csv may correspond to different version of the main file for example to version 2,\nand thus contains data corresponding to a subset of data relatively to .h5. \n\n\"\"\"\n# 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\nimport h5py\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport time\n\n\"\"\"\n# Open file way 1\n\"\"\"\nfilename = '\/kaggle\/input\/multiple-single-cell-rna-expressions-archs4\/human_matrix.h5'\nwith h5py.File(filename, \"r\") as f:\n    # List all groups\n    print(\"Keys: %s\" % f.keys())\n    a_group_key = list(f.keys())[0]\n\n    # Get the data\n    # data = list(f[a_group_key])\n\"\"\"\n# Open file way 2 - more simple \n\"\"\"\nf = h5py.File(filename,'r')#, mode)\nfor key in f.keys():\n    print(key) #Names of the groups in HDF5 file.\n\"\"\"\n# Access expression data  \n\"\"\"\n\"\"\"\n## Look for \n\"\"\"\nkey = 'data'\ngroup = f[key]\nprint(group.keys())\nfor k in group.keys():\n    print(group[k])\n\"\"\"\n## Access\n\"\"\"\nkey = 'data'\nkey2 = 'expression'\nX = f[key][key2]\nprint(X.shape)\nX\nX[:5,:8]\n\"\"\"\n# Exercise - show percent of zeros for several genes ( illustrate dropout)\n\"\"\"\nt0=time.time()\nfor gene in range((X.shape[0]))[:10]:\n    v = X[:,gene]\n    print('Gene N', gene, 'Percent of zeros:',np.round(100*np.sum(v==0)\/len(v), 2),'%  ', 'seconds passed:', np.round(time.time()-t0,1))\n    \n    \n\"\"\"\n# Get meta data\n\n\"\"\"\nkey = 'meta'\ngroup = f[key]\nl = []\nfor key in group.keys():\n    l.append(key)\n    #print(key)\nprint(len(l))    \nprint(l)    \nl_gene = list(  filter(lambda x: 'gene' in x , l) )\nprint(len(l_gene))\nprint(l_gene)\n\"\"\"\n## Gene names etc,  35238 genes\n\"\"\"\nkey = 'meta'\nkey2 = 'gene_name'\ngene_names = f[key][key2]\nprint(len(gene_names))\ngene_names[:10]\nl_gene\nkey = 'meta'\nfor key2 in l_gene:\n    dt = f[key][key2]\n    print(key2, 'len = ', len(dt), 'First 5 elements:')\n    print(dt[:5] )\n\"\"\"\n## Sample information\n\"\"\"\nl_sample = list(  filter(lambda x: 'Sample' in x , l) )\nprint(len(l_sample))\nprint(l_sample)\nkey = 'meta'\nkey2 = 'Sample_organism_ch1'\ndt = f[key][key2]\ns = pd.Series(dt)\nprint(s.value_counts())\ndt[:10]\nl_sample\nkey = 'meta'\nfor key2 in l_sample:\n    dt = f[key][key2]\n    print(key2, 'len = ', len(dt), 'First 5 elements:')\n    print(dt[:5] )\n\"\"\"\n# Info on ARCHS4 authorship\n\"\"\"\nprint( f['info'] )\nprint( f['info'].keys() )\nfor k in f['info']:\n    print(f['info'][k][0])\n\n\"\"\"\n# Plot genes in TSNE 3d dimensional reduction \n\"\"\"\nfn = '\/kaggle\/input\/multiple-single-cell-rna-expressions-archs4\/gene_human_tsne.csv'\ndf = pd.read_csv(fn)\ndf\nfn = '\/kaggle\/input\/multiple-single-cell-rna-expressions-archs4\/gene_human_tsne.csv'\ndf = pd.read_csv(fn)\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure(figsize = (15,8))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(df['x'], df['y'], df['z'])# , c=c, marker=m)\n\nplt.title('Human genes in TSN3 3D space')\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\n\nplt.show()\nfn = '\/kaggle\/input\/multiple-single-cell-rna-expressions-archs4\/sample_mouse_tsne.csv'\ndf = pd.read_csv(fn)\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure(figsize = (15,8))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(df['x'], df['y'], df['z'])# , c=c, marker=m)\n\nplt.title('Mouse genes in TSN3 3D space')\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()\n\"\"\"\n# Load and look at gene correlation matrices\n\"\"\"\nimport pyarrow.feather as feather\n\nfn = '\/kaggle\/input\/multiple-single-cell-rna-expressions-archs4\/mouse_correlation_archs4.f'\nwith open(fn, 'rb') as f:\n    df = feather.read_feather(f)\n    \n\ndf\nv = df.values.ravel()\n\n#corr_matr = df.values\n#corr_matr_abs = np.abs(read_df.values )\n\nplt.figure(figsize=(14,8))\nt0 = time.time()\nplt.hist(v, bins = 50)\nplt.title('correlation coefficients distribution')\nplt.show()\nprint(time.time() - t0, 'seconds passed')\n\nprint(np.min(v ), 'minimal correlation' )\nprint(np.mean(np.abs(v) ), 'average absolute correlation' )\nprint(np.median(np.abs(v)), 'median absolute correlation' )\nprint(np.min(np.abs(v) ), 'min absolute correlation' )\nprint(np.std(np.abs(v) ), 'std absolute correlation' )\nfor t in [0.5,0.6, 0.7,0.8,0.9,0.95,0.97,0.98,.99]:\n    print( ((np.abs(v) < 0.99999999) & (np.abs(v) > t)).sum()\/2 , 'number of pairs correlated more than', t  )\nv.shape\n# Strange extremelt highly correlated elements - will look on them below  in more details\nt = 0.9999\nprint( ((np.abs(v) < 0.9999999999999) & (np.abs(v) > t)).sum()\/2 , 'number of pairs correlated more than', t  )\nt = 0.999\nprint( ((np.abs(v) < 0.9999999999999) & (np.abs(v) > t)).sum()\/2 , 'number of pairs correlated more than', t  )\n\na = np.where( np.abs(np.triu(df.values,1)) > 0.9999 )\nl = zip( a[0],a[1])\nl = list(l)\nprint( len(l) ); print()\nfor t in l[:20]:\n    print(t[0],t[1], df.columns[t[0]], df.columns[t[1]],'Correlation:',  df.iloc[t[0], t[1]] )\n\n\"\"\"\n## Graph of correlations\n\"\"\"\nimport igraph\n\n# Create graph\na = np.where( np.abs(np.triu(df.values,1)) > 0.5 )\nl = list( zip( a[0],a[1]) )\nprint('Number of edges:', len(l) )\n\ng = igraph.Graph()\ng.add_vertices(len(df))\ng.add_edges( list(l) )\n# Analyse connected components:\n\ng_clusters = g.clusters(mode='WEAK')\ng_clusters\nprint('Number of components',len(g_clusters))\n\nlist_cluster_sizes = [len(t) for t  in g_clusters ]\nl = np.sort(list_cluster_sizes)[::-1]\nprint('Sizes of 20 largest components:',  l[:20] )\nprint('Number of single node components', (np.array(l) == 1).sum()) \n\n# Visualize largest connected component\nix_max = np.argmax(list_cluster_sizes)\nprint(ix_max)\nlen(g_clusters[ix_max] )\ng2 = g.subgraph( g_clusters[ix_max] )\nvisual_style = {}\nvisual_style[\"vertex_color\"] = ['green' for v in g2.vs]\n#visual_style[\"vertex_label\"] = range(g.vcount()) \nvisual_style[\"vertex_size\"] = 2\nigraph.plot(g2,bbox = (800,500), **visual_style )\n","meta":"{'source': 'AI4Code', 'id': '8da2ae8695e93c'}"}
{"id":"106541","text":"\"\"\"\n# STOCK PREDICTION USING TWITTER SENTIMENT ANALYSIS\n\"\"\"\n\"\"\"\n#### importing machine learning libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.corpus import subjectivity\nfrom nltk.sentiment import SentimentAnalyzer\nfrom nltk.sentiment.util import *\nimport matplotlib.pyplot as mlpt\nimport math\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.metrics import Accuracy\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras.layers import *\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import EarlyStopping\n\"\"\"\n#### importing library to fetch data from twitter\n\"\"\"\n!pip3 install tweepy\nimport tweepy\nimport csv\nimport pandas as pd\nimport random\nimport numpy as np\nimport pandas as pd\n\"\"\"\n#### setting up consumer key and access token\n\"\"\"\nconsumer_key    = '3jmA1BqasLHfItBXj3KnAIGFB'\nconsumer_secret = 'imyEeVTctFZuK62QHmL1I0AUAMudg5HKJDfkx0oR7oFbFinbvA'\n\naccess_token  = '265857263-pF1DRxgIcxUbxEEFtLwLODPzD3aMl6d4zOKlMnme'\naccess_token_secret = 'uUFoOOGeNJfOYD3atlcmPtaxxniXxQzAU4ESJLopA1lbC'\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth,wait_on_rate_limit=True)\n\"\"\"\n#### Fetching tweets for Google from Sundar Pichai's timeline in extended mode (means entire tweet will come and not just few words + link)\n\"\"\"\nfetch_tweets=tweepy.Cursor(api.user_timeline, screen_name='@sundarpichai', tweet_mode=\"extended\").items()\n# fetch_tweets=tweepy.Cursor(api.search, q=\"#YESBANK\",count=100000, lang =\"en\",since=\"2020-01-01\", tweet_mode=\"extended\").items()\ndata=pd.DataFrame(data=[[tweet_info.created_at.date(),tweet_info.full_text]for tweet_info in fetch_tweets],columns=['Date','Tweets'])\n\"\"\"\n#### Removing special character from each tweets\n\"\"\"\ndata.to_csv(\"Tweets.csv\")\ncdata=pd.DataFrame(columns=['Date','Tweets'])\ntotal=100\nindex=0\nfor index,row in data.iterrows():\n    stre=row[\"Tweets\"]\n    my_new_string = re.sub('[^ a-zA-Z0-9]', '', stre)\n    cdata.sort_index()\n    cdata.at[index,'Date'] = row[\"Date\"]\n    cdata.at[index,'Tweets'] = my_new_string\n    index=index+1\n#print(cdata.dtypes)\n\"\"\"\n#### Displaying the data with date and tweets, you can notice there are multiple tweets for each day. So we will club them together later.\n\"\"\"\nprint(cdata, min(cdata['Date']))\n\"\"\"\n#### Creating a dataframe where we will combine the tweets date wise and store into\n\"\"\"\nccdata=pd.DataFrame(columns=['Date','Tweets'])\nindx=0\nget_tweet=\"\"\nfor i in range(0,len(cdata)-1):\n    get_date=cdata.Date.iloc[i]\n    next_date=cdata.Date.iloc[i+1]\n    if(str(get_date)==str(next_date)):\n        get_tweet=get_tweet+cdata.Tweets.iloc[i]+\" \"\n    if(str(get_date)!=str(next_date)):\n        ccdata.at[indx,'Date'] = get_date\n        ccdata.at[indx,'Tweets'] = get_tweet\n        indx=indx+1\n        get_tweet=\" \"\n\"\"\"\n#### All the tweets has been clubbed as per their date.\n\"\"\"\nccdata\n\"\"\"\n#### Now to know the \"closing price\" of each day we will import STOCK PRICE DATA for GOOGLE from \"yahoo.finance\". We will consider \"Close\" price only.\n\"\"\"\n\nread_stock_p=pd.read_csv('..\/input\/nsefinancedata\/stocks.csv')\nread_stock_p\n\"\"\"\n#### Adding a \"Price\" column in our dataframe and fetching the stock price as per the date in our dataframe.\n\"\"\"\nccdata['Prices']=\"\"\nindx=0\nfor i in range (0,len(ccdata)):\n    for j in range (0,len(read_stock_p)):\n        get_tweet_date=ccdata.Date.iloc[i]\n        get_stock_date=read_stock_p.Date.iloc[j]\n        if(str(get_stock_date)==str(get_tweet_date)):\n            #print(get_stock_date,\" \",get_tweet_date)\n            ccdata.at[i,'Prices'] = int(read_stock_p.Close[j])\n            break\n\"\"\"\n#### Prices are fetched but some entires are blank as close price might not be available for that day due to some reason (like holiday, etc.)\n\"\"\"\nprint(ccdata)\n\"\"\"\n#### So we take the mean for the close price and put it in the blank value\n\"\"\"\nmean=0\nsumm=0\ncount=0\nfor i in range(0,len(ccdata)):\n    if(ccdata.Prices.iloc[i]!=\"\"):\n        summ=summ+int(ccdata.Prices.iloc[i])\n        count=count+1\nmean=summ\/count\nfor i in range(0,len(ccdata)):\n    if(ccdata.Prices.iloc[i]==\"\"):\n        ccdata.Prices.iloc[i]=int(mean)\n\"\"\"\n#### Now all the entries have some value\n\"\"\"\nccdata\n\"\"\"\n#### Making \"prices\" column as integer so mathematical operations could be performed easily.\n\"\"\"\nccdata['Prices'] = ccdata['Prices'].apply(np.int64)\n\"\"\"\n#### Adding 4 new columns in our dataframe so that sentiment analysis could be performed.. Comp is \"Compound\" it will tell whether the statement is overall negative or positive. If it has negative value then it is negative, if it has positive value then it is positive. If it has value 0, then it is neutral.\n\"\"\"\nccdata[\"Comp\"] = ''\nccdata[\"Negative\"] = ''\nccdata[\"Neutral\"] = ''\nccdata[\"Positive\"] = ''\nccdata\n\"\"\"\n#### Downloading this package was essential to perform sentiment analysis.\n\"\"\"\nimport nltk\nnltk.download('vader_lexicon')\n\"\"\"\n#### This part of the code is responsible for assigning the polarity for each statement. That is how much positive, negative, neutral you statement is. And also assign the compound value that is overall sentiment of the statement.\n\"\"\"\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport unicodedata\nsentiment_i_a = SentimentIntensityAnalyzer()\nfor indexx, row in ccdata.T.iteritems():\n    try:\n        sentence_i = unicodedata.normalize('NFKD', ccdata.loc[indexx, 'Tweets'])\n        sentence_sentiment = sentiment_i_a.polarity_scores(sentence_i)\n        ccdata.at[indexx, 'Comp'] = sentence_sentiment['compound']\n        ccdata.at[indexx, 'Negative'] = sentence_sentiment['neg']\n        ccdata.at[indexx, 'Neutral'] = sentence_sentiment['neu']\n        ccdata.at[indexx, 'Positive'] = sentence_sentiment['pos']\n    except TypeError:\n        print (stocks_dataf.loc[indexx, 'Tweets'])\n        print (indexx)\nccdata\n\"\"\"\n#### Calculating the percentage of postive and negative tweets, and plotting the PIE chart for the same.\n\"\"\"\nposi=0\nnega=0\nfor i in range (0,len(ccdata)):\n    get_val=ccdata.Comp[i]\n    if(float(get_val)<(0)):\n        nega=nega+1\n    if(float(get_val>(0))):\n        posi=posi+1\nposper=(posi\/(len(ccdata)))*100\nnegper=(nega\/(len(ccdata)))*100\nprint(\"% of positive tweets= \",posper)\nprint(\"% of negative tweets= \",negper)\narr=np.asarray([posper,negper], dtype=int)\nmlpt.pie(arr,labels=['positive','negative'])\nmlpt.plot()\n\"\"\"\n#### Making a new dataframe with necessary columns for providing machine learning.\n\"\"\"\ndf_=ccdata[['Date','Prices','Comp','Negative','Neutral','Positive']].copy()\ndf_\n\"\"\"\n#### Dividing the dataset into train and test.\n\"\"\"\ntrain_start_index = '0'\ntrain_end_index = '6'\ntest_start_index = '7'\ntest_end_index = '9'\ntrain = df_.loc[train_start_index : train_end_index]\ntest = df_.loc[test_start_index:test_end_index]\n\"\"\"\n#### Making a 2D array that will store the Negative and Positive sentiment for Training dataset.\n\"\"\"\nsentiment_score_list = []\nfor date, row in train.T.iteritems():\n    sentiment_score = np.asarray([df_.loc[date, 'Negative'],df_.loc[date, 'Positive']])\n    sentiment_score_list.append(sentiment_score)\nnumpy_df_train = np.asarray(sentiment_score_list)\nprint(numpy_df_train)\n\"\"\"\n#### Making a 2D array that will store the Negative and Positive sentiment for Testing dataset.\n\"\"\"\nsentiment_score_list = []\nfor date, row in test.T.iteritems():\n    sentiment_score = np.asarray([df_.loc[date, 'Negative'],df_.loc[date, 'Positive']])\n    sentiment_score_list.append(sentiment_score)\nnumpy_df_test = np.asarray(sentiment_score_list)\nprint(numpy_df_test)\n\"\"\"\n#### Making 2 dataframe for Training and Testing \"Prices\". You can also make 1-D array for the same.\n\"\"\"\ny_train = pd.DataFrame(train['Prices'])\n#y_train=[91,91,91,92,91,92,91]\ny_test = pd.DataFrame(test['Prices'])\nprint(y_train)\n\"\"\"\n#### Fitting the sentiments(this acts as in independent value) and prices(this acts as a dependent value (like class-lables in iris dataset))\n\"\"\"\n!pip3 install treeinterpreter\nfrom treeinterpreter import treeinterpreter as ti\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import classification_report,confusion_matrix\n\nrf = RandomForestRegressor()\nrf.fit(numpy_df_train, y_train)\n\"\"\"\n#### Making Predictions\n\"\"\"\nprediction, bias, contributions = ti.predict(rf, numpy_df_test)\nprint(prediction)\n\"\"\"\n#### Importing matplotlib library for plotting graph\n\"\"\"\nimport matplotlib.pyplot as plt\n\"\"\"\n#### Defining index position for the test data. Making dataframe for the predicted value.\n\"\"\"\nidx=np.arange(int(test_start_index),int(test_end_index)+198)\npredictions_df_ = pd.DataFrame(data=prediction[0:], index = idx, columns=['Prices'])\npredictions_df_\n\n\"\"\"\n#### Plotting the graph for the Predicted_price VS Actual Price\n\"\"\"\nax = predictions_df_.rename(columns={\"Prices\": \"predicted_price\"}).plot(title='Random Forest predicted prices')#predicted value\nax.set_xlabel(\"Indexes\")\nax.set_ylabel(\"Stock Prices\")\nfig = y_test.rename(columns={\"Prices\": \"actual_price\"}).plot(ax = ax).get_figure()#actual value\nfig.savefig(\"random forest.png\")\nfrom treeinterpreter import treeinterpreter as ti\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import classification_report,confusion_matrix\n\nreg = LinearRegression()\nreg.fit(numpy_df_train, y_train)\nreg.predict(numpy_df_test)\n\n# reg.score(reg.predict(numpy_df_test), y_test)\n\n\"\"\"\nGather The STock DATA from Yahoo FInance\n\"\"\"\ndf = pd.read_csv('..\/input\/googlestockdata\/stocks.csv')\ndf.head(5)\n\"\"\"\nDivide the data into Training and Testing\n\"\"\"\ntraining_set = df.iloc[:800, 1:2].values\ntest_set = df.iloc[800:, 1:2].values\n# Feature Scaling\nsc = MinMaxScaler(feature_range = (0, 1))\ntraining_set_scaled = sc.fit_transform(training_set)\n# Creating a data structure with 60 time-steps and 1 output\nX_train = []\ny_train = []\nfor i in range(60, 800):\n    X_train.append(training_set_scaled[i-60:i, 0])\n    y_train.append(training_set_scaled[i, 0])\nX_train, y_train = np.array(X_train), np.array(y_train)\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n#(740, 60, 1)\nmodel = Sequential()\n#Adding the first LSTM layer and some Dropout regularisation\nmodel.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))\nmodel.add(Dropout(0.2))\n# Adding a second LSTM layer and some Dropout regularisation\nmodel.add(LSTM(units = 50, return_sequences = True))\nmodel.add(Dropout(0.2))\n# Adding a third LSTM layer and some Dropout regularisation\nmodel.add(LSTM(units = 50, return_sequences = True))\nmodel.add(Dropout(0.2))\n# Adding a fourth LSTM layer and some Dropout regularisation\nmodel.add(LSTM(units = 50))\nmodel.add(Dropout(0.2))\n# Adding the output layer\nmodel.add(Dense(units = 1))\n# Compiling the RNN\nmodel.compile(optimizer = 'adam', loss = 'mean_squared_error')\n# Fitting the RNN to the Training set\nhistory = model.fit(X_train, y_train, epochs = 50, batch_size = 32)\n# Getting the predicted stock price of 2017\ndataset_train = df.iloc[:800, 1:2]\ndataset_test = df.iloc[800:, 1:2]\ndataset_total = pd.concat((dataset_train, dataset_test), axis = 0)\ninputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values\ninputs = inputs.reshape(-1,1)\ninputs = sc.transform(inputs)\nX_test = []\n\nfor i in range(60, 519):\n    X_test.append(inputs[i-60:i, 0])\n    \nX_test = np.array(X_test)\nX_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\nprint(X_test.shape)\n# (459, 60, 1)\n\"\"\"\n**Store the predicted Stock Price**\n\"\"\"\npredicted_stock_price = model.predict(X_test)\npredicted_stock_price = sc.inverse_transform(predicted_stock_price)\ndf.columns\n# Visualising the results\nplt.plot(df.loc[800:,'Date'],dataset_test.values, color = 'red', label = 'Real GOOGLE Stock Price')\nplt.plot(df.loc[800:,'Date'][:459],predicted_stock_price, color = 'blue', label = 'Predicted GOOGLE Stock Price')\nplt.xticks(np.arange(0,459,50))\nplt.title('GOOGLE Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel('GOOGLE Stock Price')\nplt.legend()\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'c3b4401a28ced6'}"}
{"id":"111632","text":"# Distribution graphs (histogram\/bar graph) of column data\ndef plotPerColumnDistribution(df, nGraphShown, nGraphPerRow):\n    nunique = df.nunique()\n    df = df[[col for col in df if nunique[col] > 1 and nunique[col] < 50]] # For displaying purposes, pick columns that have between 1 and 50 unique values\n    nRow, nCol = df.shape\n    columnNames = list(df)\n    nGraphRow = (nCol + nGraphPerRow - 1) \/ nGraphPerRow\n    plt.figure(num = None, figsize = (6 * nGraphPerRow, 8 * nGraphRow), dpi = 80, facecolor = 'w', edgecolor = 'k')\n    for i in range(min(nCol, nGraphShown)):\n        plt.subplot(nGraphRow, nGraphPerRow, i + 1)\n        columnDf = df.iloc[:, i]\n        if (not np.issubdtype(type(columnDf.iloc[0]), np.number)):\n            valueCounts = columnDf.value_counts()\n            valueCounts.plot.bar()\n        else:\n            columnDf.hist()\n        plt.ylabel('counts')\n        plt.xticks(rotation = 90)\n        plt.title(f'{columnNames[i]} (column {i})')\n    plt.tight_layout(pad = 1.0, w_pad = 1.0, h_pad = 1.0)\n    plt.show()\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.preprocessing import StandardScaler\n\nclass CustomScaler(BaseEstimator):\n    def __init__(self, columns ):\n        self.scaler = StandardScaler()\n        self.columns = columns\n        self.mean_ = None\n        self.std_ = None\n    \n    def fit(self, X, y=None):\n        self.scaler.fit(X[self.columns], y)\n        self.mean_ = np.mean(X[self.columns])\n        self.std_ = np.std(X[self.columns])\n        return self\n    \n    def transform(self, X, y=None):\n        init_col_order = X.columns\n        X_scaled = pd.DataFrame(self.scaler.transform(X[self.columns]), columns=self.columns,index=X.index)\n        X_not_scaled = X.loc[:, ~X.columns.isin(self.columns)]\n        return pd.concat([X_not_scaled, X_scaled], axis=1)[init_col_order]\n# Correlation matrix\ndef plotCorrelationMatrix(df, graphWidth):\n    filename = df.dataframeName\n    df = df.dropna('columns') # drop columns with NaN\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    if df.shape[1] < 2:\n        print(f'No correlation plots shown: The number of non-NaN or constant columns ({df.shape[1]}) is less than 2')\n        return\n    corr = df.corr()\n    plt.figure(num=None, figsize=(graphWidth, graphWidth), dpi=80, facecolor='w', edgecolor='k')\n    corrMat = plt.matshow(corr, fignum = 1)\n    plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)\n    plt.yticks(range(len(corr.columns)), corr.columns)\n    plt.gca().xaxis.tick_bottom()\n    plt.colorbar(corrMat)\n    plt.title(f'Correlation Matrix for {filename}', fontsize=15)\n    plt.show()\n\n# Scatter and density plots\ndef plotScatterMatrix(df, plotSize, textSize):\n    df = df.select_dtypes(include =[np.number]) # keep only numerical columns\n    # Remove rows and columns that would lead to df being singular\n    df = df.dropna('columns')\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    columnNames = list(df)\n#     if len(columnNames) > 10: # reduce the number of columns for matrix inversion of kernel density plots\n#         columnNames = columnNames[:10]\n    df = df[columnNames]\n    ax = pd.plotting.scatter_matrix(df, alpha=0.75, figsize=[plotSize, plotSize], diagonal='kde')\n    corrs = df.corr().values\n    for i, j in zip(*plt.np.triu_indices_from(ax, k = 1)):\n        ax[i, j].annotate('Corr. coef = %.3f' % corrs[i, j], (0.8, 0.2), xycoords='axes fraction', ha='center', va='center', size=textSize)\n    plt.suptitle('Scatter and Density Plot')\n    plt.show()\n\n\"\"\"\n<img src=\"https:\/\/i.imgur.com\/J4QlqZu.jpg\"\/>\n\n\n## Introduction\nGreetings starter code demonstrating how to read in the data and begin exploring. Click the blue \"Edit Notebook\" or \"Fork Notebook\" button at the top of this kernel to begin editing.\n\n\n\"\"\"\n\"\"\"\n## Exploratory Analysis\n\"\"\"\nimport matplotlib.pyplot as plt # plotting\nimport seaborn as sns\nimport numpy as np # linear algebra\nimport os # accessing directory structure\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCV\nfrom sklearn import metrics\n\"\"\"\nThere is 1 csv file in the current version of the dataset:\n\n\"\"\"\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\ndf = pd.read_csv('\/kaggle\/input\/Boston-house-price-data.csv', delimiter=',')\ndf.sample(5)\ndf.info()\n\"\"\"\n**Analysis:**\n* here we observe that all columns are of numeric datatype\n* we can also observe that all of non-null column values have 506, which is fortunately equals to total rows in dataframe\n* i.e., we dont have any null values in this dataframe\n\"\"\"\nprint('total number of null values : {0}'.format(df.isna().sum().sum()))\ndf.describe()\n\"\"\"\n**Analysis**\n* here if we observe standard-deviation is much larger than mean for few of the columns which we need to normalize\n* we need to check the distribution by ploting the data, and do the required normalizations\n\"\"\"\n\"\"\"\n# Multivariate Analysis\n\"\"\"\nplt.figure(figsize=(11,9))\ncorr = df.corr().round(2)\n\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n# # Want diagonal elements as well\n# mask[np.diag_indices_from(mask)] = False\n\nsns.heatmap(data=corr, annot=True,cmap='coolwarm',mask=mask)\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n**Analysis**\n* columns RAD & TAX are highly positively correlated \n    * **inference**: as the accessibility to radial highways increases so does the porperty TAX\n* columns DIS is highly negatively correlated with INDUS, NOX, AGE\n    * **inference**: as the distances to five boston employment centres increases\n    * proportion of non-retail business acres per town decreases\n    * nitric oxides concentration (parts per 10 million) decreases\n    * proportion of owner-occupied units built prior to 1940 decreases\n* column LSTAT & MEDV are highly negatively correlated\n    * **inference**: as the % lower status of the population increases \n    * Median value of owner-occupied homes decreases\n\"\"\"\n\"\"\"\n# Univariate Analysis\n\"\"\"\nfor col in df.columns:\n    fig,ax = plt.subplots(1,2,figsize=(15,1.5))\n    if len(np.unique(df[col]))<10:\n        sns.countplot(df[col],ax=ax[0])\n    else:\n        sns.distplot(df[col],bins=50 if len(np.unique(df[col]))>50 else None,ax=ax[0])\n        \n    sns.boxplot(df[col],ax=ax[1])\n    plt.suptitle(col,fontsize=20,y=1.2)\n    plt.show()\n\"\"\"\n# Normalization\n\"\"\"\n\"\"\"\n### Now lets select few columns from do some normalization techniques\n\"\"\"\ncolumns = [col for col in df.columns if len(np.unique(df[col]))>50]\ncolumns.remove('MEDV')\ncolumns\nfor col in columns:\n    fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(20,1.5))\n    \n    sns.distplot(df[col],bins=50,ax=ax[0])\n    ax[0].set_title('original')\n    \n    quantile_transformer = preprocessing.QuantileTransformer(output_distribution='normal',n_quantiles=int(len(df)\/20), random_state=0)\n    X_trans = quantile_transformer.fit_transform(df[col].values.reshape((len(df),1)))\n    sns.distplot(X_trans,bins=50,ax=ax[1])\n    ax[1].set_title('normalized')\n    \n    plt.suptitle(col,fontsize=20,y=1.2)\n    plt.show()\n\"\"\"\n# Operations on dataset\n\"\"\"\ncolumns\nc = columns.copy()\nc.append('MEDV')\nX = df[c]\nX_train = X.copy()\n\"\"\"\n### Clipping outliers from train data\n\"\"\"\nfor k, v in X_train.items():\n        q1 = v.quantile(0.25)\n        q3 = v.quantile(0.75)\n        irq = q3 - q1\n        v_col = v[(v <= q1 - 1.5 * irq) | (v >= q3 + 1.5 * irq)]\n        perc = np.shape(v_col)[0] * 100.0 \/ np.shape(X_train)[0]\n        print(\"Column %s outliers = %.2f%%\" % (k, perc))\nlen(X_train)\nQ1 = X_train.quantile(0.25)\nQ3 = X_train.quantile(0.75)\nIQR = Q3 - Q1\n\nX_train = X_train[~((X_train < (Q1 - 1.5 * IQR)) |(X_train > (Q3 + 1.5 * IQR))).any(axis=1)]\nlen(X_train)\n\"\"\"\n### Target Variable MEDV\n\"\"\"\nsns.distplot(X_train['MEDV']);plt.show()\n\"\"\"\n### Independent variables (INPUTS)\n\"\"\"\ncols = 3\nrows = int(len(X_train.drop('MEDV',axis=1).columns)\/cols)\n\nplt.figure(figsize=(15,10))\nfor i,col in enumerate(X_train.drop('MEDV',axis=1).columns):\n    ax = plt.subplot(rows, cols, i+1)\n    sns.distplot(X_train[col],ax=ax)\nX.columns\nX_train, y_train = X_train.drop('MEDV',axis=1), X_train['MEDV']\n\"\"\"\n### LOG Transform target variable for better results\n\"\"\"\ny_train = np.log(y_train)\n\"\"\"\nas the data is small lets not split for the validation data instead go for cross validation\n\"\"\"\n\"\"\"\nlets do normalization on the train and transform test data with it\n\"\"\"\n\"\"\"\n# Normalization\n\"\"\"\nquantile_transformer = preprocessing.QuantileTransformer(output_distribution='normal',n_quantiles=int(len(X_trans)\/20), random_state=0)\nX_train.loc[:,columns] = quantile_transformer.fit_transform(X_train[columns].values.reshape((len(X_train),len(columns))))\ncols = 3\nrows = int(len(X_train.columns)\/cols)\n\nplt.figure(figsize=(15,10))\nfor i,col in enumerate(X_train.columns):\n    ax = plt.subplot(rows, cols, i+1)\n    sns.distplot(X_train[col],ax=ax)\n\"\"\"\n# Standardization\n\"\"\"\nscaler = CustomScaler(columns)#check at the start of the book to find the CustomScaler\nscaler.fit(X_train)\nX_train = scaler.transform(X_train)\n\"\"\"\nnow the data has been scaled\n\"\"\"\ncols = 3\nrows = int(len(X_train.columns)\/cols)\n\nplt.figure(figsize=(15,10))\nfor i,col in enumerate(X_train.columns):\n    ax = plt.subplot(rows, cols, i+1)\n    sns.distplot(X_train[col],ax=ax)\n\"\"\"\n## cutting outliers again after normalization\n\"\"\"\nX = X_train.copy()\nX.loc[:,'MEDV']=y_train\nQ1 = X.quantile(0.25)\nQ3 = X.quantile(0.75)\nIQR = Q3 - Q1\n\nX = X[~((X < (Q1 - 1.5 * IQR)) |(X > (Q3 + 1.5 * IQR))).any(axis=1)]\ny_train = X['MEDV']\nX_train = X.drop('MEDV',axis=1)\nfor k, v in X_train.items():\n        q1 = v.quantile(0.25)\n        q3 = v.quantile(0.75)\n        irq = q3 - q1\n        v_col = v[(v <= q1 - 1.5 * irq) | (v >= q3 + 1.5 * irq)]\n        perc = np.shape(v_col)[0] * 100.0 \/ np.shape(X_train)[0]\n        print(\"Column %s outliers = %.2f%%\" % (k, perc))\n\"\"\"\n# Modeling\n\"\"\"\nscores_map={}\n\"\"\"\n# Linear Regression\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nLR_model = LinearRegression()\nscores = cross_val_score(LR_model,X_train,y_train,cv=10,n_jobs=-1,scoring='neg_mean_squared_error')\nscores_map['LR']=scores\nprint('Logistic Regression negative RMSE {:.3f} (+\/- {:.3f})'.format(scores.mean(),scores.std()))\n\"\"\"\n# Support Vector Machine Regressor (SVR)\n\"\"\"\nfrom sklearn.svm import SVR\n\n\nsvr_rbf = SVR(kernel='rbf')\ngrid = GridSearchCV(svr_rbf, cv=10, param_grid={\"C\": [1e0, 1e1, 1e2, 1e3], \"gamma\": np.logspace(-2, 2, 5)}, scoring='neg_mean_squared_error')\ngrid.fit(X_train, y_train)\nprint(\"Best parameters :\", grid.best_params_)\nprint(\"Best Score :{:.3f}\".format(grid.best_score_))\nsvr_rbf = SVR(kernel='rbf',C=10,gamma=0.01)\n\nscores = cross_val_score(svr_rbf,X_train,y_train,cv=10,n_jobs=-1,scoring='neg_mean_squared_error')\nscores_map['SVR']=scores\nprint('SVR negative RMSE {:.3f} (+\/- {:.3f})'.format(scores.mean(),scores.std()))\n\"\"\"\n# Decision Tree Regressor\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree = DecisionTreeRegressor(random_state=0)\ngrid = GridSearchCV(tree, cv=10, param_grid={\"max_depth\" : [1, 2, 3, 4, 5, 6, 7]}, scoring='neg_mean_squared_error')\ngrid.fit(X_train, y_train)\nprint(\"Best parameters : \", grid.best_params_)\nprint(\"Best Score :{:.3f}\".format(grid.best_score_))\ntree = DecisionTreeRegressor(max_depth=7)\nscores = cross_val_score(tree, X_train, y_train, cv=10, scoring='neg_mean_squared_error')\nscores_map['DTree'] = scores\nprint(\"D.Tree negative RMSE {:.3f} (+\/- {:.3f})\".format(scores.mean(),scores.std()))\n\"\"\"\n# K Nearest Neighbours Regression (KNN)\n\"\"\"\nfrom sklearn.neighbors import KNeighborsRegressor\n\nknn = KNeighborsRegressor()\n\ngrid = GridSearchCV(knn, cv=10, param_grid={\"n_neighbors\" : [2, 3, 4, 5, 6, 7]}, scoring='neg_mean_squared_error')\ngrid.fit(X_train, y_train)\nprint(\"Best parameters :\", grid.best_params_)\nprint(\"Best Score :{:.3f}\".format(grid.best_score_))\nknn = KNeighborsRegressor(n_neighbors=4)\nscores = cross_val_score(knn, X_train, y_train, cv=10, scoring='neg_mean_squared_error')\nscores_map['KNN'] = scores\nprint(\"KNN negative RMSE {:.3f} (+\/- {:.3f})\".format(scores.mean(),scores.std()))\n\"\"\"\n# Gradient Boosting\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingRegressor\n\ngbr = GradientBoostingRegressor(random_state=0)\nparam_grid={'n_estimators':[50,100,150, 200], 'learning_rate': [0.5,0.1,0.05,0.02,0.001]\n            , 'max_depth':[2, 3,4,5,6,7,8], 'min_samples_leaf':[3,5,9,11,14,16]\n            ,'min_samples_split':[2,4,6,8,10], 'alpha':[0.05,0.1,0.3,0.5]}\n# grid = GridSearchCV(gbr, cv=10, param_grid=param_grid, scoring='neg_mean_squared_error')\ngrid = RandomizedSearchCV(gbr, cv=10, param_distributions=param_grid, scoring='neg_mean_squared_error')\ngrid.fit(X_train, y_train)\nprint(\"Best params :\", grid.best_params_)\nprint(\"Best Score :{:.3f}\".format(grid.best_score_))\ngbr = GradientBoostingRegressor(n_estimators=200,min_samples_split=2,min_samples_leaf=3,max_depth=8,learning_rate=0.02,alpha=0.05,   random_state=0)\nscores = cross_val_score(gbr, X_train, y_train, cv=10, scoring='neg_mean_squared_error')\nscores_map['GBR'] = scores\nprint(\"GBR negative RMSE {:.3f} (+\/- {:.3f})\".format(scores.mean(),scores.std()))\n\"\"\"\n# Performance Comparisions\n\"\"\"\nplt.figure(figsize=(15, 7))\nscores_map = pd.DataFrame(scores_map)\nsns.boxplot(data=scores_map)\nplt.xticks(fontsize=30)\nplt.show()\n\"\"\"\n**Analysis**\n* almost all regressors are performing sholder to sholder\n\"\"\"\n\"\"\"\n# Conclusion\nThis concludes your starter analysis! To go forward from here, click the blue \"Edit Notebook\" button at the top of the kernel. This will create a copy of the code and environment for you to edit. Delete, modify, and add code as you please. Happy Kaggling!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'cd17ba68e96394'}"}
{"id":"28985","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n# Importing data:\n\"\"\"\ntrain=pd.read_csv('\/kaggle\/input\/digit-recognizer\/train.csv')\ntest=pd.read_csv('\/kaggle\/input\/digit-recognizer\/test.csv')\nsubmission= pd.read_csv('\/kaggle\/input\/digit-recognizer\/sample_submission.csv')\n\"\"\"\n# Preliminary work :\n\"\"\"\n# Let's take preview on train datas \ntrain.head()\n# Now, we will give preview on test datas\ntest.head()\n# Let's give some statstics on the train datas \ntrain.describe()\n# Hereunder, we will give general informations about train datas.\ntrain.info()\n# We will do the same work for test datas.\n# We start by showing some statstics about the test datas.\ntest.describe()\n# Then , we show some general informations about the test datas .\ntest.info()\n\"\"\"\n**The above brief analyse, show that our datas don't encompasse missing values.**\n\"\"\"\n\"\"\"\n# Preprocessing datas:\n\"\"\"\nxtr=train.iloc[:,1:].to_numpy() # extract train pixels datas .\nxts=test.to_numpy()             # extract test pixels datas.\nYtr=train.iloc[:,0].to_numpy()  # extract train label datas.\nXtr=xtr.reshape(xtr.shape[0],28,28) # reshape the train pixels datas accordingly to the origin image size.\nXts=xts.reshape(xts.shape[0],28,28) # reshape the test pixels datas accordingly to the origin image size.\n\"\"\"\n# Outliers:\n\"\"\"\n\"\"\"\nTo check if there is outliers in our dataset , we will create the boxeplot of the pixels values which should have values between 0 and 255 . Moreover , we will check the values of training labels, which should have values between 0 and 9. \n\"\"\"\nimport matplotlib.pyplot as plt \nmeanprops={\"marker\":\"o\",\"markeredgecolor\":\"black\",\"markeredgecolor\":\"firebrick\"}\nmedianprops={'color':'black'}\nplt.subplot(211)\nplt.boxplot([xtr,xts],labels=['training pixels','test pixels'],meanprops=meanprops,\\\n            medianprops=medianprops,showfliers=True,showmeans=True,patch_artist=True,vert=False)\nplt.subplot(212)\nplt.boxplot([Ytr.flatten()],labels=['labels training datas'],showfliers=True,showmeans=True,meanprops=meanprops,\\\n           medianprops=medianprops,patch_artist=True,vert=False)\nplt.show()\n\"\"\"\n**The box plot above show that neither the pixel datas nor the labels trainig data encompasse outliers.**\n\"\"\"\n\"\"\"\n# Visualization :\n\"\"\"\n# we choice randomly 5 observations from our training dataset to compare the handwritten digit to his \n# correspond label .\nimport random \nsamples=random.sample(range(xtr.shape[0]+1),5)\nj=0\nfor i in samples :\n    j=j+1\n    plt.subplot(150+j)\n    plt.imshow(Xtr[i],cmap=plt.get_cmap('gray'))\n    plt.title(Ytr[i])\nplt.show()\n\"\"\"\n# SVM Classifier:\n\"\"\"\n\"\"\"\n### Contents :\n1. Import required librairies .\n2. Split datas & Implement SVM.\n3. Compute the estimated score of the svm estimator .\n4. Predict the test handwritten digits labels.\n\"\"\"\n\"\"\"\n### 1. Import required librairies :\n\"\"\"\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n### 2.Split datas and implement SVM:\n\"\"\"\n# prepare datas\nxxtr,xxts,ytr,yts=train_test_split(xtr,Ytr,test_size=0.1)\n# Implement svm estimator .\nestimator= SVC()\n# Training the SVM estimator .\nestimator.fit(xxtr,ytr)\n\"\"\"\n### 3. Compute the estimated score of the svm estimator:\n\"\"\"\nsc=estimator.score(xxts,yts)\nprint(\"The estimated score of the SVM method is : {}\".format(sc))\n\"\"\"\n### 4. Predict the test handwritten digits labels:\n\"\"\"\nsubmission['Label']=estimator.predict(xts)\nsubmission.to_csv('svm.csv',index='False')\n\"\"\"\n# Neural network Classifier:\n\"\"\"\n\"\"\"\n### Contents:\n1. Import required librairies.\n2. Preprocessing datas.\n3. Implement Deep Neural Network.\n4. Train & test the DNN.\n5. Results analyse\n6. Predict the test handwritten digits labels.\n\"\"\"\n\"\"\"\n### 1. Import required librairies :\n\"\"\"\nfrom keras.layers import Dense , Flatten \nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping \nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical\n\"\"\"\n### 2. Preprocessing datas:\n\"\"\"\nXtr=Xtr.reshape(Xtr.shape[0],Xtr.shape[1],Xtr.shape[2],1)\nXts=Xts.reshape(Xts.shape[0],Xts.shape[1],Xts.shape[2],1)\nYtr=to_categorical(Ytr)\ndtgen=ImageDataGenerator()\nX_train,X_val,Y_train,Y_val=train_test_split(Xtr,Ytr,test_size=0.1)\n\ntraining=dtgen.flow(X_train,Y_train,batch_size=32)\nvalidation=dtgen.flow(X_val,Y_val,batch_size=32)\n\"\"\"\n### 3.Implement Deep Neural Network (DNN):\n\"\"\"\nNN=Sequential()\n# Add input layer\nNN.add(Dense(128,input_shape=(28,28,1),activation='relu'))\nNN.add(Flatten())\n\n# Add Hidden layers \nNN.add(Dense(256,activation='relu'))\nNN.add(Dense(256,activation='relu'))\n\n# output layer.\n\nNN.add(Dense(10,activation='softmax'))\n\"\"\"\n### 4. Train & test the DNN :\n\"\"\"\n# Compile the neural network \nNN.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\n# Training the DNN.\nhistory=NN.fit_generator(generator=training,steps_per_epoch=training.n,epochs=3,validation_data=validation,\\\n                validation_steps=validation.n)\n\"\"\"\n### 5. Results analyse :\n\"\"\"\nht=history.history\nht.keys()\nepochs=range(1,len(ht['loss'])+1)\nplt.plot(epochs,ht['loss'],'bo')\nplt.plot(epochs,ht['val_loss'],'b+')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.show()\nplt.plot(epochs,ht['accuracy'],'bo')\nplt.plot(epochs,ht['val_accuracy'],'b+')\nplt.xlabel('epochs')\nplt.ylabel('accuracy')\nplt.show()\n\"\"\"\n### 6.Predict the test handwritten digits labels\n\"\"\"\nsubmission1=pd.DataFrame({'ImageId':submission['ImageId']})\nsubmission1.insert(1,'Label',NN.predict_classes(Xts),True)\nsubmission1.to_csv('dnn.csv',index=False)","meta":"{'source': 'AI4Code', 'id': '3549dc398c4f48'}"}
{"id":"130894","text":"\"\"\"\n![](https:\/\/logos-download.com\/wp-content\/uploads\/2016\/03\/Netflix_logo_red.png)\n\n# Introduction\n\nNetflix was conceived in 1997 by Reed Hastings (the current CEO) and Marc Randolph. Both had previous in the West Coast tech scene \u2013 Hastings was the owner of debugging software firm Pure Atria, while Randolph had cofounded, and then sold computer mail order company MicroWarehouse for $700 million.\nNetflix.com started life as a DVD rental service in 1998; an online rival to the then dominant Blockbuster Video. \n\nAt the end of 2019, Netflix subscribers numbered 167.1 million. Of these, 61 million accounts were registered in the US, with the remaining 106.1 million (63%) spread over the rest of the globe.\nInternational growth in Netflix subscriptions has far outpaced domestic growth in recent years, since international users first came to account for the greatest proportion of international users as recently as 2017. Since 2015 the number of international Netflix users has increased nearly fourfold, while domestic users have increased by less than 50%.\n\nOne of the technologies that made netflix the technological giant, that it is today, is recommendations engine.\nA recommendations engine, in simple words, is a piece of code which can recommend users the most related item based on their current item choice or their previous history of choices. In this notebook, I have tried to create a simple recommendations engine based on weighted averages technique and Content based filtering.  \n\"\"\"\n\"\"\"\n# NOTE\n\nI have used some sections of code from Krish Naik's notebook and would like to give credits to him. This project is made for study and learning purposes. I have added my own changes and work as well to make the recommendations system more efficient and useful. The data that I have used is available on Kaggle and I have engineered features according to my needs. \n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport pickle\nimdb_df = pd.read_csv('\/kaggle\/input\/netflix-data\/IMDb movies.csv')\nnetflix_df = pd.read_csv('\/kaggle\/input\/netflix-data\/netflix_titles.csv')\nnetflix_df2 = pd.read_csv('\/kaggle\/input\/netflix-data\/NetflixViewingHistory.csv')\nstreaming_platforms_df = pd.read_csv('\/kaggle\/input\/movies-on-netflix-prime-video-hulu-and-disney\/MoviesOnStreamingPlatforms_updated.csv')\n\"\"\"\n# Data-Engineering\n\"\"\"\nstreaming_platforms_df['title']=streaming_platforms_df['Title']\ndrop=['Unnamed: 0', 'ID','Year', 'Age','Type','Directors','Genres', 'Country', 'Language', 'Runtime','Title','Rotten Tomatoes','IMDb']\nstreaming_platforms_df.drop(drop, axis=1, inplace=True)\nnetflix_df2['title']=netflix_df2.Title\ndrop=['Title','Date']\nnetflix_df2.drop(drop, axis=1,inplace=True)\nnetflix_df2 = netflix_df2.drop_duplicates()\nimdb_df.columns\ndrop = ['imdb_title_id','original_title','worlwide_gross_income','metascore','usa_gross_income','budget',\n       'writer', 'duration', 'country', 'language', 'director','year', 'date_published']\nimdb_df.drop(drop, axis=1, inplace=True)\nimdb_df.head()\nnetflix_df = netflix_df[netflix_df['type']=='Movie']\ndrop = ['show_id', 'cast', 'country','listed_in','rating','release_year','type','date_added','duration','description']\nnetflix_df.drop(drop, axis=1, inplace=True)\nnetflix_df = pd.merge(netflix_df, netflix_df2, how='outer', on='title')\nnetflix_df = netflix_df.drop_duplicates()\ndataset = pd.merge(imdb_df,netflix_df, how='inner',on='title')\ndataset.head()\n\"\"\"\n# Weighted Averages Method\n\nIn weighted averages method, I will be recommending movies based on votes polled by users and average votes(IMDb Score). I could have just recommended movies based on highest IMDb scores but some movies are just not famous or maybe they are newly released and thus it would be more suitable to take user votes into consideration as well.\n\"\"\"\n# Calculate all the components based on the weighted averages formula\nv=dataset['votes']\nR=dataset['avg_vote']\nC=dataset['avg_vote'].mean()\nm=dataset['votes'].quantile(0.70)\ndataset['weighted_average']=((R*v)+ (C*m))\/(v+m)\ndataset.head()\ndf_sorted=dataset.sort_values('weighted_average',ascending=False)\ndf_sorted[['title', 'votes', 'avg_vote', 'weighted_average']].head(20)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"whitegrid\")\nweight_average=df_sorted.sort_values('weighted_average',ascending=False)\nplt.figure(figsize=(12,6))\naxis1=sns.barplot(x=weight_average['weighted_average'].head(20), y=weight_average['title'].head(20), data=weight_average)\nplt.xlim(4, 10)\nplt.title('Best Movies on Netflix by average votes(on IMDb)', weight='bold')\nplt.xlabel('Weighted Average Score', weight='bold')\nplt.ylabel('Movie Title', weight='bold')\n\"\"\"\n# Content Filtering Method\n\nIn content based filtering, I will be using certain features related to the content of movie like genre, actors, description etc to find out the similarity of any given movie with respect to all the other movies. After that, I will be selecting top 10 movies after based on the similarity values. There are certain advantages and disadvantages related to content based filtering method. They are:\n\n### Advantages\n1. Content based filtering does not require user history for making a recommendation. It can just examine the content of the movie to make recommendations. In other words, even if a user if first time using the recommendation system, the recommendation system will work just fine.\n\n### Disadvantages\n1. Content based filtering requires a lot of time to examine all the content of the movies. Since, it is based on content filtering, it needs to process all the movie and their contents in order to make a recommendation. \n2. To examine huge amount of data, it requires a lot of memory which again is a drawback.\n\"\"\"\ndataset['IMDb Score']=dataset['avg_vote']\ndataset.drop('avg_vote',axis=1, inplace=True)\ndataset.head(1)['description']\ndef augmentation(df, col1, col2, col3, col4, col5):\n    index_col1 = df.columns.get_loc(col1)\n    index_col2 = df.columns.get_loc(col2)\n    index_col3 = df.columns.get_loc(col3)\n    index_col4 = df.columns.get_loc(col4)\n    index_col5 = df.columns.get_loc(col5)\n    \n    for row in range(len(df)):\n        count=0\n        cast = str(df.iat[row, index_col2])\n        main_cast = \"\"\n        for i in range(len(cast)):\n            if cast[i]!=',':\n                if count!=3:\n                    main_cast = main_cast+cast[i]\n                else:\n                    break\n            else:\n                count=count+1\n        df.iat[row,index_col3] = str(str(df.iat[row,index_col1])+str(main_cast)+str(df.iat[row,index_col4])+str(df.iat[row, index_col5]))\n        \ndataset[\"Information\"]=\"\"\n\naugmentation(dataset,'description','actors','Information','genre','director')\ndef case_conversion(df, col1, col2):\n    index_col1 = df.columns.get_loc(col1)\n    index_col2 = df.columns.get_loc(col2)\n    \n    for rows in range(len(df)):\n        df.iat[rows, index_col2] = df.iat[rows, index_col1].lower()\n        \ndataset['title_lower'] = \"\"\ncase_conversion(dataset, \"title\", \"title_lower\")\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntfv = TfidfVectorizer(min_df=3,  max_features=None, \n            strip_accents='unicode', analyzer='word',token_pattern=r'\\w{1,}',\n            ngram_range=(1, 6),\n            stop_words = 'english')\n\n# Filling NaNs with empty string\ndataset['Information'] = dataset['Information'].fillna('')\ndataset['description'] = dataset['description'].fillna('None')\ndataset.to_csv('movie_dataset.csv', header=True, index=False)\n# Fitting the TF-IDF on the 'Information' text\ntfv_matrix = tfv.fit_transform(dataset['Information'])\nfrom sklearn.metrics.pairwise import sigmoid_kernel\n\n# Compute the sigmoid kernel\nsig = sigmoid_kernel(tfv_matrix, tfv_matrix)\n# Reverse mapping of indices and movie titles\nindices = pd.Series(dataset.index, index=dataset['title_lower']).drop_duplicates()\n\ndef recommendations(title, sig=sig):\n    # Get the index corresponding to original_title\n    title = title.lower()\n    idx = indices[title]\n\n    # Get the pairwsie similarity scores \n    sig_scores = list(enumerate(sig[idx]))\n\n    # Sort the movies \n    sig_scores = sorted(sig_scores, key=lambda x: x[1], reverse=True)\n\n    # Scores of the 10 most similar movies\n    sig_scores = sig_scores[1:11]\n\n    # Movie indices\n    movie_indices = [i[0] for i in sig_scores]\n\n    # Top 10 most similar movies\n    return dataset.iloc[movie_indices]\n    \ndf = recommendations(\"the green mile\")\ndata = df[['title','genre','description','IMDb Score','actors']].head(10)\ndata\n\"\"\"\n# Conclusion\n\nIn this project, I tried to study, understand and implement some algorithms which are used in modern day recommendations engine. In future, I will be trying to use other techniques out there like Collaborative based RecSys and Hybrid RecSys. Though this notebook, I tried to explain the theoritical aspects along with the practical implementations of what I learned while working on this project. I hope this notebook helps you in some way. Thanks for your time.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f0b23d3df2f22e'}"}
{"id":"73009","text":"# import library\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib_venn import venn2, venn2_circles\nimport seaborn as sns\nfrom tqdm.notebook import tqdm\nimport pathlib\nimport plotly\nimport plotly.express as px\n\"\"\"\n# utils\n\"\"\"\ndef calc_haversine(lat1, lon1, lat2, lon2):\n    \"\"\"Calculates the great circle distance between two points\n    on the earth. Inputs are array-like and specified in decimal degrees.\n    \"\"\"\n    RADIUS = 6_367_000\n    lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])\n    dlat = lat2 - lat1\n    dlon = lon2 - lon1\n    a = np.sin(dlat\/2)**2 + \\\n        np.cos(lat1) * np.cos(lat2) * np.sin(dlon\/2)**2\n    dist = 2 * RADIUS * np.arcsin(a**0.5)\n    return dist\ndef visualize_trafic(df, center, zoom=9):\n    fig = px.scatter_mapbox(df,\n                            \n                            # Here, plotly gets, (x,y) coordinates\n                            lat=\"latDeg\",\n                            lon=\"lngDeg\",\n                            \n                            #Here, plotly detects color of series\n                            color=\"phoneName\",\n                            labels=\"phoneName\",\n                            \n                            zoom=zoom,\n                            center=center,\n                            height=600,\n                            width=800)\n    fig.update_layout(mapbox_style='stamen-terrain')\n    fig.update_layout(margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0})\n    fig.update_layout(title_text=\"GPS trafic\")\n    fig.show()\n    \ndef visualize_collection(df, collection):\n    target_df = df[df['collectionName']==collection].copy()\n    lat_center = target_df['latDeg'].mean()\n    lng_center = target_df['lngDeg'].mean()\n    center = {\"lat\":lat_center, \"lon\":lng_center}\n    \n    visualize_trafic(target_df, center)\ndef add_distance_diff(df):\n    df['latDeg_prev'] = df['latDeg'].shift(1)\n    df['latDeg_next'] = df['latDeg'].shift(-1)\n    df['lngDeg_prev'] = df['lngDeg'].shift(1)\n    df['lngDeg_next'] = df['lngDeg'].shift(-1)\n    df['phone_prev'] = df['phone'].shift(1)\n    df['phone_next'] = df['phone'].shift(-1)\n    \n    df['latDeg_gt_prev'] = df['latDeg_gt'].shift(1)\n    df['latDeg_gt_next'] = df['latDeg_gt'].shift(-1)\n    df['lngDeg_gt_prev'] = df['lngDeg_gt'].shift(1)\n    df['lngDeg_gt_next'] = df['lngDeg_gt'].shift(-1)    \n    \n    df['latDeg_prev_diff'] = df['latDeg'] - df['latDeg_prev']\n    df['latDeg_next_diff'] = df['latDeg_next'] - df['latDeg']\n    df['latDeg_gt_prev_diff'] = df['latDeg_gt'] - df['latDeg_gt_prev']\n    df['latDeg_gt_next_diff'] = df['latDeg_gt_next'] - df['latDeg_gt']\n    \n    df['lngDeg_prev_diff'] = df['lngDeg'] - df['lngDeg_prev']\n    df['lngDeg_next_diff'] = df['lngDeg_next'] - df['lngDeg']\n    df['lngDeg_gt_prev_diff'] = df['lngDeg_gt'] - df['lngDeg_gt_prev']\n    df['lngDeg_gt_next_diff'] = df['lngDeg_gt_next'] - df['lngDeg_gt']\n    \n    df['dist_prev'] = calc_haversine(df['latDeg'], df['lngDeg'], df['latDeg_prev'], df['lngDeg_prev'])\n    df['dist_next'] = calc_haversine(df['latDeg'], df['lngDeg'], df['latDeg_next'], df['lngDeg_next'])\n    \n    df['dist_gt_prev'] = calc_haversine(df['latDeg_gt'], df['lngDeg_gt'], df['latDeg_gt_prev'], df['lngDeg_gt_prev'])\n    df['dist_gt_next'] = calc_haversine(df['latDeg_gt'], df['lngDeg_gt'], df['latDeg_gt_next'], df['lngDeg_gt_next'])\n    \n    df.loc[df['phone']!=df['phone_prev'], ['latDeg_prev', 'lngDeg_prev', 'dist_prev', 'latDeg_gt_prev', 'lngDeg_gt_prev', 'dist_gt_prev', \n                                           'latDeg_prev_diff', 'latDeg_gt_prev_diff', 'lngDeg_prev_diff', 'lngDeg_gt_prev_diff']] = np.nan\n    \n    df.loc[df['phone']!=df['phone_next'], ['latDeg_next', 'lngDeg_next', 'dist_next', 'latDeg_gt_next', 'lngDeg_gt_next', 'dist_gt_next',\n                                           'latDeg_next_diff', 'latDeg_gt_next_diff', 'lngDeg_next_diff', 'lngDeg_gt_next_diff']] = np.nan\n    \n    return df\n# directory setting\nINPUT = '..\/input\/google-smartphone-decimeter-challenge'\ntrain = pd.read_csv(INPUT + '\/' + 'baseline_locations_train.csv')\ntest = pd.read_csv(INPUT + '\/' + 'baseline_locations_test.csv')\nsample_sub = pd.read_csv(INPUT + '\/' + 'sample_submission.csv')\n# ground_truth\np = pathlib.Path(INPUT)\ngt_files = list(p.glob('train\/*\/*\/ground_truth.csv'))\n\ngts = []\nfor gt_file in gt_files:\n    gts.append(pd.read_csv(gt_file))\nground_truth = pd.concat(gts)\n\"\"\"\n# EDA\n\"\"\"\n# preparing data for viz\ntmp1 = ground_truth.copy()\ntmp1['phone'] = tmp1['collectionName'] + '_' + tmp1['phoneName']\ntmp1['phoneName'] = tmp1['phoneName'] + '_GT'\ntmp = train.append(tmp1)\nvisualize_trafic(tmp[tmp['phone']=='2020-05-14-US-MTV-1_Pixel4XLModded'],\n                 center={\"lat\":37.6458, \"lon\":-122.4056}, zoom=19)\nvisualize_trafic(tmp[tmp['phone']=='2020-06-04-US-MTV-1_Pixel4'],\n                 center={\"lat\":37.41634, \"lon\":-122.0805}, zoom=19)\n\"\"\"\nAs you can see in the graph above, the baseline coordinates seem to vary widely,  \neven though the car is stopped at the start or goal and the ground_truth coordinates have not changed.\n\"\"\"\nground_truth = ground_truth.rename(columns={'latDeg':'latDeg_gt', 'lngDeg':'lngDeg_gt', 'heightAboveWgs84EllipsoidM':'heightAboveWgs84EllipsoidM_gt'})\ntrain = train.merge(ground_truth, on=['collectionName', 'phoneName', 'millisSinceGpsEpoch'], how='inner')\ntrain['dist_err'] = calc_haversine(train['latDeg_gt'], train['lngDeg_gt'], train['latDeg'], train['lngDeg'])\ntrain = add_distance_diff(train)\ntrain['speedMps'].hist()\nplt.title('Distribution of \"speedMps\"')\n\"\"\"\nThe speed of the train data is held by ground_truth.  \nLooking at this distribution, we can see that there are many records with speed = 0.\n\"\"\"\ntrain.loc[train['speedMps']==0.0,'speed0'] = 'speed = 0'\ntrain.loc[train['speedMps']>0.0,'speed0'] = 'speed > 0'\nsns.boxplot(x='speed0', y='dist_err', data=train, showfliers = False)\n\"\"\"\nWe just looked at a few examples, but even when looking at the entire train data,  \nthe error appears to be large when the car is stopped.\n\"\"\"\ndef visualize_err_move_dist(df, phone, reject_outlier=True):\n    '''\n    visualize baseline error and relative move distance\n    '''\n    fig, axes = plt.subplots(figsize=(20, 10), nrows=2,sharex=True)\n    df = df[df['phone']==phone]\n    if reject_outlier:\n        th = (df['dist_err'].std() * 3) + df['dist_err'].mean()\n        df = df[df['dist_err']<th]\n    \n    axes[0].plot(df['millisSinceGpsEpoch'], df['dist_err'], label='err(baseline)')\n    axes[1].plot(df['millisSinceGpsEpoch'], df['speedMps'], label='speedMps')\n    axes[1].plot(df['millisSinceGpsEpoch'], df['dist_prev'], label='move dist(baseline)')\n    axes[1].plot(df['millisSinceGpsEpoch'], df['dist_gt_prev'], label='move dist(ground_truth)')\n    axes[0].legend(loc='upper right')\n    axes[1].legend(loc='upper right')\n    axes[0].grid(color='g', linestyle=':', linewidth=0.3)\n    axes[1].grid(color='g', linestyle=':', linewidth=0.3)\n    fig.suptitle(phone, fontsize=16)\nvisualize_err_move_dist(train, '2020-05-14-US-MTV-1_Pixel4XLModded')\n\"\"\"\nLet's check the time series of baseline error and move distance  \nfor the example we just checked on the map.  \n\nAs you can see in the graph below,  \nthe baseline is moving a lot while it is actually stopped at the start and end points.  \n\nI am not sure about the cause,  \nbut I think this approach to reduce the error may be effective.\n\n(supplement)  \nmove_dist(ground_truth) and speedMps are almost identical.   \nIs the speed being calculated based on the coordinates?\n\"\"\"\n\"\"\"\nView all phone results below\n\"\"\"\nphones = train['phone'].unique()\nfor phone in phones:\n    visualize_err_move_dist(train, phone)","meta":"{'source': 'AI4Code', 'id': '866429d79cc577'}"}
{"id":"111488","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n## Libraries Required\n\"\"\"\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn import svm\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n\nwarnings.filterwarnings('ignore')\n\"\"\"\n## Data Path\n\"\"\"\ntrain_data_path = '\/kaggle\/input\/house-prices-advanced-regression-techniques\/train.csv'\ntest_data_path = '\/kaggle\/input\/house-prices-advanced-regression-techniques\/test.csv'\ncured_train_data_path = 'cured_train.csv'\ncured_test_data_path = 'cured_test.csv'\n\"\"\"\n## Initializers\nLets read the data, do some initial level stuffs. Lets concat train and test data for preprocessing and analysis purpose\n\"\"\"\ndataA = pd.read_csv(train_data_path)\ndataB = pd.read_csv(test_data_path)\ndata = dataA.append(dataB)\ndataA.shape, dataB.shape, data.shape\n# Ensure there are no duplicates, by checking the uniquiness of Id field\ndata.Id.unique().size\ndata.head()\ndata.describe()\nlencoder = LabelEncoder()\noencoder = OneHotEncoder(sparse=False)\n#check feature data types\ndef print_dtypes(df):\n  for name, typ in df.dtypes.iteritems():\n    print(f'{name}\\t\\t{typ}')\nprint_dtypes(data)\n\"\"\"\n## Features with Missing Data\n\"\"\"\n# Check for missing Data\ndef get_features_with_missing_data(df):\n  features_with_missing_values = df.isnull().sum().sort_values(ascending=False)\n  for feature, number in features_with_missing_values.iteritems():\n    if number ==0: break\n    print(f'{feature}\\t\\t\\t{number}') \n\nget_features_with_missing_data(data)\n\"\"\"\n## Handle Missing Data\nAs seen in the above output, there are multiple fields which are missing values.\n\nSome fields are allowed to have NA \/ None as value. So any categorical field which has NaN should be checked with related features before replacing them with NA \/ None according to the description file.\n\"\"\"\n\"\"\"\n### PoolQC\nLets Analyse PoolQC missing Values. Note that Pool may not be available for some houses in that case PoolQC value should be 'NA'. In data any NaN in PoolQC with PoolArea == 0 can be considered as house with No Pool and hence replace them with 'NA'\n\"\"\"\nmpqc_with_qa = data[(data.PoolQC.isna()) & (data.PoolArea >0)]\nprint(f'{mpqc_with_qa.shape}, this says that there are 3 missing PoolQC with PoolArea available')\nmpqc_with_qa[['PoolQC', 'PoolArea','LotArea','SalePrice']]\n# Lets find the count of records on each category of PoolQC\npqc_with_qa = data[(data.PoolQC.notna()) & (data.PoolArea >0)]\nprint(f'{pqc_with_qa.shape}, this says that there are only 10 records with pool quality and pool area')\nsns.catplot(data=data, x='PoolQC', kind='count')\nplt.show()\n\"\"\"\nWe can see that PoolQC etries are distributed between Ex, Fa, Gd category but not on TA category. Since we dono the QC of the pool and TA category is missing, lets replace the missing PoolQC value for the records which has PoolArea with TA.\n\"\"\"\nrecord_ids = mpqc_with_qa.index\ndata.at[record_ids, 'PoolQC'] = 'TA'\nmpqc_with_qa = data[(data.PoolQC.isna()) & (data.PoolArea >0)]\n# replace Other Missing value for PoolQC with 'NA'\ndata.PoolQC.fillna('NA', inplace=True)\n\"\"\"\n### MiscFeature\nLets analyse MiscFeature Missing Values. Here, this feature is allowed to have NA. So if not MiscVal is > 0 and MiscFeature is NaN, then we can fill the NaN with 'NA'\n\"\"\"\n# check if any record has MiscVal and not MiscFeature\nmissing_mf = data[(data.MiscFeature.isna()) & (data.MiscVal>0)]\nmissing_mf[['MiscFeature', 'MiscVal', 'SalePrice']]\n\"\"\"\nWe have one record that has MiscVal but MiscFeature and SalePrice is missing. Since this is the only record, we can simply find out the MiscFeature that has MiscVal greater than 15000 and map that Feature to this record.\n\"\"\"\n# Lets plot the MiscFeature Vs MiscVal box plot to find out the Val range of each Feature\nsns.catplot(data=data, x='MiscFeature', y='MiscVal', kind='box')\n\"\"\"\nIts clear that Gar2 Feature has value greater than 15000. So we can map Gar2 for the record with missing MiscFeature which has MiscVal.\n\"\"\"\ndata.at[1089, 'MiscFeature'] = 'Gar2'\nmissing_mf = data[(data.MiscFeature.isna()) & (data.MiscVal>0)]\nmissing_mf[['MiscFeature', 'MiscVal', 'SalePrice']]\n\"\"\"\nWe have replaced the NaN with 'Gar2' for 1089 record. Now we can replace all other NaN with 'NA'\n\"\"\"\ndata.MiscFeature.fillna('NA', inplace=True)\n\"\"\"\n### Alley\nDiscription says that Alley can be 'NA' for house that does not have Alley, so lets simply replace NaN with 'NA'\n\"\"\"\ndata.Alley.fillna('NA', inplace=True)\n\"\"\"\n### Fence\nDiscription says that Fence can be 'NA' for house that does not have Fence, so lets simply replace NaN with 'NA'.\n\"\"\"\ndata.Fence.fillna('NA', inplace=True)\n\"\"\"\n### FireplaceQu\nThis feature can be 'NA' for house that does not have any Fireplace, Lets corss check this with Fireplaces feature, If Fireplaces is > 0 then FireplaceQA cannot be NaN. If so, have to anaylse and fix it else replace NaN with 'NA'.\n\"\"\"\ndata[(data.Fireplaces > 0) & (data.FireplaceQu.isna())].shape\n# Lets replace All NaN with 'NA' for FireplaceQu\ndata.FireplaceQu.fillna('NA', inplace=True)\n\"\"\"\n### LotFrontage\nLinear feet of street connected to property. Lets replace the missing value with median of LotFrontage.\n\"\"\"\nlotData =  data[['LotArea', 'LotFrontage', 'LotConfig']]\nplt.figure(figsize=(2,3))\nsns.boxplot(data=lotData, x='LotFrontage', orient='v')\nlotData.LotFrontage.mean(), lotData.LotFrontage.median()\n\"\"\"\nFrom the plot we can see that 50% quartile falls around ~68. the same is verified by computing the mean and median. Lets replace the missing value with median.\n\"\"\"\ndata.LotFrontage.fillna(data.LotFrontage.median(), inplace=True)\n\"\"\"\n### Garage\nIn this Section lets analyse and understand the contribution of Garage features for SalePrice\n\"\"\"\ngrg_data = data[['YearBuilt','GarageType','GarageYrBlt','GarageFinish','GarageCars','GarageArea','GarageQual','GarageCond', 'MiscFeature', 'SalePrice']]\nfn_gr = grg_data[(grg_data.GarageQual.isna()) & (grg_data.GarageType.notna())] # return the records with GarageType available and GarageQual NotAvailable\nfn_gr\ngrg_features = ['GarageType','GarageYrBlt','GarageFinish','GarageCars','GarageArea','GarageQual','GarageCond']\ndata.at[fn_gr.index, grg_features] = 'NA'\n# fill other NaN with 'NA'\ndata.at[data[grg_data.GarageType.isna()].index, grg_features] = 'NA'\n\"\"\"\n### Basemet\nFollowing are the list of features which have missing values in them. Some features have lesser missing values when compared to other feature.\n\nLets compare the missing features amoung them to find out the records which have missing fields and fix them first.\n\nLater we can replace all NaN with 'NA'\n\n1. BsmtExposure : 82\n2. BsmtCond : 82\n3. BsmtQual : 81\n4. BsmtFinType2 : 80\n5. BsmtFinType1 : 79\n6. BsmtFinSF1 : 1\n7. BsmtFinSF2 : 1\n\n\"\"\"\nbsmt_fts = ['BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1', 'BsmtFinType2', \n 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath',]\nint_fts = bsmt_fts + ['SalePrice']\nbsmt_data = data[int_fts]\n# BsmtExposure\nMissing_BsmtExposure = bsmt_data[(bsmt_data.BsmtExposure.isna()) & (bsmt_data.BsmtFinType1.notna())]\nMissing_BsmtExposure\n# Search for similar records with BsmtExposure, find the category with max value and replace the missing value\nBsmtExposure_samples = bsmt_data[(bsmt_data.BsmtQual=='Gd') & (bsmt_data.BsmtCond=='TA') & \n          (bsmt_data.BsmtFinType1=='Unf') & (bsmt_data.BsmtFinType2=='Unf') &\n          (bsmt_data.BsmtFinSF1==0) & (bsmt_data.BsmtFinSF2==0) ]\nsns.catplot(data=BsmtExposure_samples, x='BsmtExposure', kind='count')\n # above plot shows that most of the other records of similar condition has No Exposure as value.\n data.at[Missing_BsmtExposure.index, 'BsmtExposure'] = 'No'\n# BsmtCond\nMissing_BsmtCond = bsmt_data[(bsmt_data.BsmtCond.isna()) & (bsmt_data.BsmtExposure.notna())]\nMissing_BsmtCond\nMissing_BsmtCond_rc1=bsmt_data[(bsmt_data.BsmtQual=='Gd') & (bsmt_data.BsmtExposure=='Mn') & (bsmt_data.BsmtFinType1=='GLQ') & (bsmt_data.BsmtFinType2=='Rec')]\nsns.catplot(data=Missing_BsmtCond_rc1, x='BsmtCond', kind='count')\nMissing_BsmtCond_rc2=bsmt_data[(bsmt_data.BsmtQual=='TA') & (bsmt_data.BsmtExposure=='No') & (bsmt_data.BsmtFinType1=='BLQ') & (bsmt_data.BsmtFinType2=='Unf')]\nsns.catplot(data=Missing_BsmtCond_rc2, x='BsmtCond', kind='count')\nMissing_BsmtCond_rc3=bsmt_data[(bsmt_data.BsmtQual=='TA') & (bsmt_data.BsmtExposure=='Av') & (bsmt_data.BsmtFinType1=='ALQ') & (bsmt_data.BsmtFinType2=='Unf')]\nsns.catplot(data=Missing_BsmtCond_rc3, x='BsmtCond', kind='count')\n# Replace NaN with TA, as per similar records\ndata.at[Missing_BsmtCond.index, 'BsmtCond'] = 'TA'\nMissing_BsmtQual = bsmt_data[(bsmt_data.BsmtQual.isna()) & (bsmt_data.BsmtCond.notna())]\nMissing_BsmtQual\nMissing_BsmtQual_rc1=bsmt_data[(bsmt_data.BsmtCond=='Fa') & (bsmt_data.BsmtExposure=='No') & (bsmt_data.BsmtFinType1=='Unf') & (bsmt_data.BsmtFinType2=='Unf')]\nMissing_BsmtQual_rc2=bsmt_data[(bsmt_data.BsmtCond=='TA') & (bsmt_data.BsmtExposure=='No') & (bsmt_data.BsmtFinType1=='Unf') & (bsmt_data.BsmtFinType2=='Unf')]\nsns.catplot(data=Missing_BsmtQual_rc1, x='BsmtQual', kind='count')\nsns.catplot(data=Missing_BsmtQual_rc2, x='BsmtQual', kind='count')\ndata.at[Missing_BsmtQual.index, 'BsmtQual'] = 'TA'\nMisssing_BsmtFinType2 = bsmt_data[(bsmt_data.BsmtFinType2.isna()) & (bsmt_data.BsmtCond.notna())]\nMisssing_BsmtFinType2\nMisssing_BsmtFinType2_rc1=bsmt_data[(bsmt_data.BsmtQual=='Gd') &(bsmt_data.BsmtCond=='TA') & \n              (bsmt_data.BsmtExposure=='No') & (bsmt_data.BsmtFinType1=='GLQ') \n              & (bsmt_data.BsmtUnfSF > 0) &(bsmt_data.BsmtFinSF2 > 0)&(bsmt_data.BsmtFinSF1 > 0)]\nsns.catplot(data=Misssing_BsmtFinType2_rc1, x='BsmtFinType2', kind='count')\ndata.at[Misssing_BsmtFinType2.index, 'BsmtFinType2'] = 'ALQ'\nMissing_BsmtFinSF1 = bsmt_data[bsmt_data.BsmtFinSF1.isna()]\nMissing_BsmtFinSF1\nMissing_BsmtFinSF2 = bsmt_data[bsmt_data.BsmtFinSF2.isna()]\nMissing_BsmtFinSF2\n\"\"\"\nBoth Missing BsmtFinSF1 & BsmtFinSF2 belong to same record, simply replace it with 0\n\"\"\"\nMissing_BsmtFullBath = bsmt_data[bsmt_data.BsmtFullBath.isna()]\nMissing_BsmtFullBath\n\"\"\"\nRecord 728 is the one which is missing both BsmtFullBath & BsmtHalfBath, simply replace it with 0\n\"\"\"\ndata.at[660, ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF','BsmtFullBath', 'BsmtHalfBath']] = 0.0\ndata.at[728, ['BsmtFullBath', 'BsmtHalfBath']] = 0.0\n# Replace other missing values with 'NA'\nBsmtNA = bsmt_data[bsmt_data.BsmtQual.isna()]\ndata.at[BsmtNA.index, bsmt_fts] = 'NA'\n\"\"\"\n### MasVnr\n\nFollowing are the list of features with missing values.\n\n1. MasVnrType : 24\n2. MasVnrArea : 23\n\"\"\"\nmasVnr_features = ['MasVnrType', 'MasVnrArea']\nmasVnr_intd_fets = masVnr_features + ['Exterior1st','Exterior2nd','Foundation', 'RoofMatl','SalePrice']\nmasVnr = data[masVnr_intd_fets]\nmissing_masVnr = masVnr[(masVnr.MasVnrType.isna()) & (masVnr.MasVnrArea.notna())]\nmissing_masVnr\n# Lets get records similar to our **missing_masVnr** record\nMasVnrType_samples = masVnr[(masVnr.Exterior1st=='Plywood') &  \n                            (masVnr.MasVnrArea > 0) & (masVnr.Foundation=='CBlock') \n                            & (masVnr.RoofMatl=='CompShg') & masVnr.MasVnrArea.between(190,220)]\nsns.catplot(data=MasVnrType_samples, x='MasVnrType', kind='count')\n\"\"\"\nAbove plot shows that other similar records with MasVnrType avaialble has **BrkFace** as the only value. so lets replace our missing value with BrkFace\n\"\"\"\ndata.at[1150, 'MasVnrType'] = 'BrkFace'\n# Lets replace other missing values with None\nact_missing_masvnr = masVnr[masVnr.MasVnrType.isna()]\ndata.at[act_missing_masvnr.index, masVnr_features] = ['None', 0.0]\n\"\"\"\n### MSZoning\n\"\"\"\nms_features = ['MSSubClass', 'MSZoning']\nms_intd_features = ms_features + ['Street','Neighborhood','BldgType','HouseStyle','YearBuilt','RoofStyle','BsmtQual','Foundation','SalePrice']\nms_data = data[ms_intd_features]\nms_data[ms_data.MSZoning.isna()]\nms_data[(ms_data.Street == 'Pave') & (ms_data.MSSubClass == 20) & (ms_data.HouseStyle.isin(['1Story', '2.5Unf'])) & (ms_data.Neighborhood=='Mitchel') \n      & (ms_data.BldgType=='1Fam')  & (ms_data.YearBuilt.between(1900, 1955, inclusive=True))]\nms_data[(ms_data.YearBuilt==1900) & (ms_data.BldgType=='1Fam') & (ms_data.Neighborhood=='IDOTRR')]\n\"\"\"\nRecords similar to #455 shows that it belongs to C (all)\n\nRecords similar to #756 shows that it belongs to C (all)\n\nRecords similar to #790 shows that it belongs to RM\n\nRecords similar to #1444 shows that it belongs to RL\n\"\"\"\nidx, val = [455, 756, 790, 1444], ['C (all)', 'C (all)', 'RM', 'RL']\nfor i, v in (zip(idx, val)):\n  data.at[i, 'MSZoning'] = v\n\"\"\"\n### Functional\n\"\"\"\nfunc_features = ['Functional']\nfunc_intd_features = func_features + ['Utilities','Street','Neighborhood','BldgType','HouseStyle','YearBuilt','RoofStyle','BsmtQual','Foundation','SalePrice']\nfunc_data = data[func_intd_features]\nmissing_func = func_data[func_data.Functional.isna()]\nmissing_func\nsns.catplot(data=func_data, x='Functional', kind='count')\n# replace missing values with Typ\ndata.at[missing_func.index, 'Functional'] = 'Typ'\n\"\"\"\n### Utilities\n\"\"\"\nsns.catplot(data=data, x='Utilities', kind='count')\ndata[data.Utilities=='NoSeWa'].shape\n\"\"\"\nOnly one record has NoSeWa and all other have AllPub as value for utilities feature, so lets replace the missing value with AllPub\n\"\"\"\ndata.at[data[data.Utilities.isna()].index,'Utilities'] = 'AllPub'\n\"\"\"\n### SaleType\n\"\"\"\nsns.catplot(data=data, x='SaleType', kind='count')\ndata.at[data[data.SaleType.isna()].index, 'SaleType'] = 'WD'\n\"\"\"\n### Electrical\n\"\"\"\nsns.catplot(data=data, x='Electrical', kind='count')\ndata.at[data[data.Electrical.isna()].index, 'Electrical'] = 'SBrkr'\nkit_fe = ['KitchenAbvGr', 'KitchenQual']\nmiss_kit = data[data.KitchenQual.isna()]\nmiss_kit[kit_fe]\n# find out the max kitchnQual for kitchenAbvGr == 1 and replace the NaN with that value\nsns.catplot(data=data[data.KitchenAbvGr==1], x='KitchenQual', kind='count')\ndata.at[miss_kit.index, 'KitchenQual'] = 'TA'\n\"\"\"\n### Exterior\n\"\"\"\next_feat = ['Exterior1st', 'Exterior2nd']\next_int_feat = ext_feat + ['ExterQual','MasVnrType','SalePrice']\next_data = data[ext_int_feat]\ndata[ext_data.Exterior1st.isna()]\n# Check other records with similar feature values and find out which Exterior is used most and replace the missing value\nrecs=data[(data.Neighborhood=='Edwards') & (data.BldgType=='1Fam') & \n          (data.HouseStyle=='1Story') & (data.MasVnrType=='None') &\n           (data.Foundation=='PConc')]\nsns.catplot(data=recs, x='Exterior1st', kind='count')\nsns.catplot(data=recs, x='Exterior2nd', kind='count')\n# replace the missing value with VinylSd\ndata.at[691, ['Exterior1st', 'Exterior2nd']] = 'VinylSd'\nget_features_with_missing_data(data)\n\"\"\"\nAll Missing values have been handled by now. Only field which has missing value is SalePrice which is expected as the belong test data.\n\"\"\"\n\"\"\"\n## Save Data\n\"\"\"\ncured_test_data = data[data.SalePrice.isna()]\ncured_test_data.to_csv(cured_test_data_path, index=False)\ncured_train_data = data[data.SalePrice.notna()]\ncured_train_data.to_csv(cured_train_data_path, index=False)\nf'Train Data: {cured_train_data.shape} | Test Data: {cured_test_data.shape}'","meta":"{'source': 'AI4Code', 'id': 'ccd91a1e95f90b'}"}
{"id":"36988","text":"\"\"\"\n[Credit to https:\/\/www.kaggle.com\/kaggleuser58\/cipher-challenge-iii-level-1]\n\n# Introduction\n\n### Time to share solution of cipher level 2 so you can look at the next level.\nIn the previous Cipher Challenge II one of the levels was a cipher with multiple substitutions generated from a key of length 8 if I remember correct.\n\nThe level 1 of this Cipher Challenge III is the same kind but with a key of length 4, so only 4 substitutions are used for each character mapping.\nSee https:\/\/www.kaggle.com\/kaggleuser58\/cipher-challenge-iii-level-1\n\nThe level 2 of this Cipher Challenge III is a transposition cipher on top of level 1.\nSee https:\/\/www.kaggle.com\/c\/ciphertext-challenge-iii\/discussion\/103969#latest-598262\n\n## The cipher\n- The cipher only apllies to UPPERCASE and LOWERCASE letters.\n- The key only shifts every time an UPPERCASE or LOWERCASE letter is met.\n\n## Padding\nFrom Cipher Challenge II it was found that padding could be done both up front and in the end. Number of padding characters in the end was always equal to or at most 1 character more (if number of characters to pad with was odd) than the number of padding characters up front.\n\n# Level 1 and level 2 - solution\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport tqdm\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n## Read the train, test and sub files\n\"\"\"\ntrain = pd.read_csv('..\/input\/train.csv', index_col='plaintext_id')\ntest = pd.read_csv('..\/input\/test.csv', index_col='ciphertext_id')\nsub = pd.read_csv('..\/input\/sample_submission.csv', index_col='ciphertext_id')\ntrain['length'] = train.text.apply(len)\ntest['length'] = test.ciphertext.apply(len)\ntrain[train['length']<=100]['length'].hist(bins=99)\ntrain.head()\ntest.head(10)\n\"\"\"\n## Functions to decrypt and encrypt from\/to level 1\n\"\"\"\nKEYLEN = 4 # len('pyle')\ndef decrypt_level_1(ctext):\n    key = [ord(c) - ord('a') for c in 'pyle']\n    key_index = 0\n    plain = ''\n    for c in ctext:\n        cpos = 'abcdefghijklmnopqrstuvwxy'.find(c)\n        if cpos != -1:\n            p = (cpos - key[key_index]) % 25\n            pc = 'abcdefghijklmnopqrstuvwxy'[p]\n            key_index = (key_index + 1) % KEYLEN\n        else:\n            cpos = 'ABCDEFGHIJKLMNOPQRSTUVWXY'.find(c)\n            if cpos != -1:\n                p = (cpos - key[key_index]) % 25\n                pc = 'ABCDEFGHIJKLMNOPQRSTUVWXY'[p]\n                key_index = (key_index + 1) % KEYLEN\n            else:\n                pc = c\n        plain += pc\n    return plain\n\ndef encrypt_level_1(ptext, key_index=0):\n    key = [ord(c) - ord('a') for c in 'pyle']\n    ctext = ''\n    for c in ptext:\n        pos = 'abcdefghijklmnopqrstuvwxy'.find(c)\n        if pos != -1:\n            p = (pos + key[key_index]) % 25\n            cc = 'abcdefghijklmnopqrstuvwxy'[p]\n            key_index = (key_index + 1) % KEYLEN\n        else:\n            pos = 'ABCDEFGHIJKLMNOPQRSTUVWXY'.find(c)\n            if pos != -1:\n                p = (pos + key[key_index]) % 25\n                cc = 'ABCDEFGHIJKLMNOPQRSTUVWXY'[p]\n                key_index = (key_index + 1) % KEYLEN\n            else:\n                cc = c\n        ctext += cc\n    return ctext\n\ndef test_decrypt_level_1():\n    c_id = 'ID_4a6fc1ea9'\n    ciphertext = test.loc[c_id]['ciphertext']\n    print('Ciphertxt:', ciphertext)\n    decrypted = decrypt_level_1(ciphertext)\n    print('Decrypted:', decrypted)\n    encrypted = encrypt_level_1(decrypted)\n    print('Encrypted:', encrypted)\n    print(\"Encrypted == Ciphertext:\", encrypted == ciphertext)\n\ntest_decrypt_level_1()    \n\"\"\"\nMake a dictionary for fast lookup of plaintext\n\"\"\"\nplain_dict = {}\nfor p_id, row in train.iterrows():\n    text = row['text']\n    plain_dict[text] = p_id\nprint(len(plain_dict))\n\"\"\"\n## Update sub with level 1 decrypted matching texts\n\"\"\"\nmatched, unmatched = 0, 0\nfor c_id, row in tqdm.tqdm(test[test['difficulty']==1].iterrows()):\n    decrypted = decrypt_level_1(row['ciphertext'])\n    found = False\n    for pad in range(100):\n        start = pad \/\/ 2\n        end = len(decrypted) - (pad + 1) \/\/ 2\n        plain_pie = decrypted[start:end]\n        if plain_pie in plain_dict:\n            p_id = plain_dict[plain_pie]\n            row = train.loc[p_id]\n            sub.loc[c_id] = train.loc[p_id]['index']\n            matched += 1\n            found = True\n            break\n    if not found:\n        unmatched += 1\n        print(decrypted)\n            \nprint(f\"Matched {matched}   Unmatched {unmatched}\")\n\"\"\"\n## Update sub with level 2 decrypted matching texts\n\"\"\"\nimport math\nfrom itertools import cycle\n\ndef rail_pattern(n):\n    r = list(range(n))\n    return cycle(r + r[-2:0:-1])\n\ndef encrypt_level_2(plaintext, rails=21):\n    p = rail_pattern(rails)\n    # this relies on key being called in order, guaranteed?\n    return ''.join(sorted(plaintext, key=lambda i: next(p)))\ndef decrypt_level_2(ciphertext, rails=21):\n    p = rail_pattern(rails)\n    indexes = sorted(range(len(ciphertext)), key=lambda i: next(p))\n    result = [''] * len(ciphertext)\n    for i, c in zip(indexes, ciphertext):\n        result[i] = c\n    return ''.join(result)\nmatched, unmatched = 0, 0\nfor c_id, row in tqdm.tqdm(test[test['difficulty']==2].iterrows()):\n    decrypted = decrypt_level_1(decrypt_level_2(row['ciphertext']))\n    found = False\n    for pad in range(100):\n        start = pad \/\/ 2\n        end = len(decrypted) - (pad + 1) \/\/ 2\n        plain_pie = decrypted[start:end]\n        if plain_pie in plain_dict:\n            p_id = plain_dict[plain_pie]\n            row = train.loc[p_id]\n            sub.loc[c_id] = train.loc[p_id]['index']\n            matched += 1\n            found = True\n            break\n    if not found:\n        unmatched += 1\n        print(decrypted)\n            \nprint(f\"Matched {matched}   Unmatched {unmatched}\")\nsub.to_csv('submit-level-2.csv')\n\"\"\"\n# Level 3 and level 4 - exploration\n\"\"\"\nlevel12_train_index = list(sub[sub[\"index\"] > 0][\"index\"])\nprint(len(level12_train_index))\ntrain34 = train[~train[\"index\"].isin(level12_train_index)].copy()\ntest3 = test[test['difficulty']==3].copy()\ntest4 = test[test['difficulty']==4].copy()\nprint(train34.shape, test3.shape[0] + test4.shape[0])\n\"\"\"\n## Level 3 - Let's see some cipher text\n\"\"\"\ntest3.sort_values(\"length\", ascending=False).head(5)\n\"\"\"\nOK, look like it is too long. Probably each number is one character. Let's count the numbers.\n\"\"\"\ntest3[\"nb\"] = test3[\"ciphertext\"].apply(lambda x: len(x.split(\" \")))\ntest3.sort_values(\"length\", ascending=False).head(5)\n\"\"\"\nLook better, let's see the train set\n\"\"\"\ntrain34.sort_values(\"length\", ascending=False).head(5)\n\"\"\"\nCool, we found an exact match for level 3 and 2 possible matches.\n\"\"\"\nc_id = 'ID_f0989e1c5' # length = 700\nindex = 34509 # length = 671\nsub.loc[c_id] = index # train.loc[p_id]['index']\n\"\"\"\n## Level 4\nEven more, index 34509 could be a text in level 4 as it does not seems to match any cipher text in level 3\n\"\"\"\ntest4.sort_values(\"length\", ascending=False).head(5)\n\"\"\"\nOOM, what are they\n\"\"\"\ntest4.head(1)[\"ciphertext\"].values[0]\n\"\"\"\nThen it must be a base64 text, but base64 is just a encoding method and this text is just a way to hide the real content. Let's do a count as well. Note that we have to count the number of chars in the level 1.\n\"\"\"\nimport base64\n\ndef encode_base64(x):\n    return base64.b64encode(x.encode('ascii')).decode()\n\ndef decode_base64(x):\n    return base64.b64decode(x)\n\ntrain34[\"nb\"] = train34[\"length\"].apply(lambda x: math.ceil(x\/100)*100)\nratio = test3[\"length\"].mean() \/ train34[\"nb\"].mean()\nprint(ratio)\n\ndef get_length_level1(x):\n    n = len(decode_base64(x))\/ratio\n    n = round(n \/ 100) * 100\n    return n\n\ntrain34.head(3)\ntest4[\"nb\"] = test4[\"ciphertext\"].apply(lambda x: get_length_level1(x)) \ntest4.sort_values(\"nb\", ascending=False).head(5)\n\"\"\"\nIt makes sense now. We found a match for level 4\n\"\"\"\nc_id = 'ID_0414884b0' # length = 900\nindex = 42677 # length = 842\nsub.loc[c_id] = index # train.loc[p_id]['index']\n\"\"\"\n##  Let's submit it the score should be a little bit higher\n\"\"\"\nsub.head(3)\n\"\"\"\n# Level 3 - mapping for few pairs\n## 3 easy pairs\nAssume that one number is associated to only a single char, let's find 2 pontential matches as listed above.\n\"\"\"\ndef is_correct_mapping(ct_l2, ct_l3):\n    tmp = pd.DataFrame([(c,n) for c,n in zip(list(ct_l2), ct_l3.split(\" \")) if c.isalpha()])\n    tmp.drop_duplicates(inplace=True)\n    tmp.columns = [\"ch\", \"num\"]\n    tmp = tmp.groupby(\"num\")[\"ch\"].nunique()\n    return tmp.shape[0] == tmp.sum()\n\ndef pad_str(s, special_char = '?'):\n    nb = len(s)\n    nb_round = math.ceil(nb \/ 100) * 100\n    nb_left = (nb_round - nb) \/\/ 2\n    nb_right = nb_round - nb - nb_left\n    \n    left_s = ''.join([special_char] * nb_left)\n    right_s = ''.join([special_char] * nb_right)\n    return left_s + s + right_s\n\ndef is_correct_mapping_low(pt, ct):\n    all_ct_l2 = [encrypt_level_2(encrypt_level_1(pad_str(pt), key_index)) for key_index in range(4)]\n\n    for i, ct_l2 in enumerate(all_ct_l2):\n        if is_correct_mapping(ct_l2, ct):\n            return i\n    return -1\n\ndef find_mapping(ciphertext_id, ct, train_df):\n    nb = len(ct.split(\" \"))\n    nb_low = ((nb \/\/ 100) - 1) * 100\n    \n    rs = []\n    selected_rows = train_df[(train_df[\"length\"] > nb_low) & (train_df[\"length\"] < nb)]\n    for row_id, row in selected_rows.iterrows():\n        pt = row[\"text\"]\n        key_index = is_correct_mapping_low(pt, ct)\n        if key_index >= 0:\n            t = row[\"index\"], key_index\n            rs.append(t)\n    if len(rs) == 1:\n        return rs[0]\n    return -1, -1\nfor ciphertext_id, row in test3[test3[\"nb\"] >= 200].iterrows():\n    ct = row[\"ciphertext\"]\n    index, key_index = find_mapping(ciphertext_id, ct, train34)\n    if index > 0:\n        print(ciphertext_id, index, key_index, \"(length: {})\".format(row[\"nb\"]))\n        sub.loc[ciphertext_id] = index # train.loc[p_id]['index']\nprint(sub[sub[\"index\"] > 0].shape[0], sub[sub[\"index\"] > 0].shape[0]\/sub.shape[0])\nsub.to_csv('submit-level-2-plus.csv')\nsub.head(3)\n\"\"\"\n# Further exploration\n\nkaggleuser58: Have you tried finding the corresponding plaintext letters for each group and see if you can see something if you sort the groups in the correct order - it might help in finding the solution.\n\n\"\"\"\ndict_level3 = {}\nfor ciphertext_id, row in test3[test3[\"nb\"] >= 200].iterrows():\n    ct = row[\"ciphertext\"]\n    index, key_index = find_mapping(ciphertext_id, ct, train34)\n    if index > 0:\n        print(ciphertext_id, index, key_index, \"(length: {})\".format(row[\"nb\"]))\n        dict_level3[ciphertext_id] = (index, key_index) # train.loc[p_id]['index']\ndict_level3[\"ID_11070f053\"] = (40234, 1)\ndict_level3[\"ID_c1694eb06\"] = (43773, 3)\n\nfor ciphertext_id, (index, key_index) in dict_level3.items():\n    sub.loc[ciphertext_id] = index\n    \nprint(sub[sub[\"index\"] > 0].shape[0], sub[sub[\"index\"] > 0].shape[0]\/sub.shape[0])\nsub.to_csv('submit-level-2-plus2.csv')\nsub.head(3)\ndf_mapping = []\nspecial_chars = \"?\"\n\ndef get_mapping(ct_l2, ct):\n    tmp = pd.DataFrame([(c,n) for c,n in zip(list(ct_l2), ct.split(\" \")) if c not in special_chars])\n    tmp.drop_duplicates(inplace=True)\n    tmp.columns = [\"ch\", \"num\"]\n    return tmp\n\nfor ciphertext_id, (index, key_index) in dict_level3.items():\n    ct = test3.loc[ciphertext_id][\"ciphertext\"]\n    pt = train34[train34[\"index\"]==index][\"text\"].values[0]\n    ct_l2 = encrypt_level_2(encrypt_level_1(pad_str(pt), key_index))\n    print(len(ct.split(\" \")), len(pt))\n    tmp = get_mapping(ct_l2, ct)\n    df_mapping.append(tmp)\n\ndf_mapping = pd.concat(df_mapping)\nprint(df_mapping.shape)\ndf_mapping.head(3)\ndf_mapping.reset_index(drop=True, inplace=True)\ndf_mapping.tail(3)\npd.set_option('display.max_rows', 5000)\npd.set_option('display.max_columns', 5000)\npd.set_option('display.max_colwidth', 5000)\npd.set_option('display.width', 5000)\n\ndf_ch_num = df_mapping[[\"ch\", \"num\"]].drop_duplicates().groupby(\"ch\")[\"num\"].apply(list)\ndf_ch_num = df_ch_num.to_frame(\"num\").reset_index()\ndf_ch_num[\"num\"] = df_ch_num[\"num\"].apply(lambda x: np.sort([int(n) for n in x]))\ndf_ch_num[\"num_alpha\"] = df_ch_num[\"num\"].apply(lambda x: np.sort([str(n) for n in x]))\ndf_ch_num[\"num_hex\"] = df_ch_num[\"num\"].apply(lambda x: np.sort([hex(n) for n in x]))\ndf_ch_num\n\"\"\"\n## Frequency analysis on Level 2\n\"\"\"\nfrom collections import Counter\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (20,10)\ntest2 = test[test[\"difficulty\"] == 2].copy()\nfullcipher2 = \"\".join((test2[\"ciphertext\"].values))\ndict_fullcipher2 = Counter(fullcipher2)\ndf_fullcipher2 = pd.DataFrame.from_dict(dict_fullcipher2, orient='index')\ndf_fullcipher2 = df_fullcipher2.reset_index()\ndf_fullcipher2.columns = [\"ch\", \"nb\"]\ndf_fullcipher2.sort_values(\"nb\", ascending=False, inplace=True)\nprint(df_fullcipher2.shape)\ndf_fullcipher2.head()\nprint(df_fullcipher2[\"nb\"].mean(), df_fullcipher2[\"nb\"].median())\ndf_fullcipher2.plot(x=\"ch\", y=[\"nb\"], kind=\"bar\");\n\"\"\"\n## Frequency analysis on Level 3\n\"\"\"\nfullcipher3 = \" \".join((test3[\"ciphertext\"].values))\ndict_fullcipher3 = Counter(fullcipher3.split(\" \"))\ndf_fullcipher3 = pd.DataFrame.from_dict(dict_fullcipher3, orient='index')\ndf_fullcipher3 = df_fullcipher3.reset_index()\ndf_fullcipher3.columns = [\"num\", \"nb\"]\ndf_fullcipher3.sort_values(\"nb\", ascending=False, inplace=True)\nprint(df_fullcipher3.shape)\ndf_fullcipher3.head()\ndf_fullcipher3[df_fullcipher3[\"nb\"] > 1500].plot(x=\"num\", y=[\"nb\"], kind=\"bar\");\n\"\"\"\n* If you find this useful - let me know by giving it a like ;-)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4414e99468bf65'}"}
{"id":"18902","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nsns.set()\nimport matplotlib.pyplot as plt\nimport plotly.graph_objs as go\nfrom plotly.offline import init_notebook_mode, iplot\n%matplotlib inline\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\nasean_countries_survey = ['Indonesia', 'Singapore', 'Thailand', 'Viet Nam', 'Malaysia', 'Philippines']\n# Survey 2017\ndf_17 = pd.read_csv(\"..\/input\/kaggle-survey-2017\/multipleChoiceResponses.csv\", encoding='ISO-8859-1')\ndf17_asean = df_17[df_17['Country'].isin(asean_countries_survey)]\ndf17_rest = df_17[~df_17['Country'].isin(asean_countries_survey)]\ndf_17['Area']=[\"Asean\" if x in asean_countries_survey else \"Others\" for x in df_17['Country']]\n\n# Survey 2018\ndf_18 = pd.read_csv(\"..\/input\/kaggle-survey-2018\/multipleChoiceResponses.csv\")\ndf18_asean = df_18[df_18['Q3'].isin(asean_countries_survey)]\ndf18_rest = df_18[~df_18['Q3'].isin(asean_countries_survey)]\ndf_18['Area']=[\"Asean\" if x in asean_countries_survey else \"Others\" for x in df_18['Q3']]\n\n# Survey 2019\ndf_19 = pd.read_csv(\"..\/input\/kaggle-survey-2019\/multiple_choice_responses.csv\")\ndf_19 = df_19.drop(0, axis=0)\ndf19_asean = df_19[df_19['Q3'].isin(asean_countries_survey)]\ndf19_rest = df_19[~df_19['Q3'].isin(asean_countries_survey)]\ndf_19['Area']=[\"Asean\" if x in asean_countries_survey else \"Others\" for x in df_19['Q3']]\n\"\"\"\n# Motivation for Asean Data Enthusiast\n***\n**Yusnardo Tendio | 16\/11\/2019**\n\nFinally, the kaggle survey dataset competition has begun. This competition has been held three times. I see a decrease in interest in respondents so I want to raise this issue in order to add motivation to all Kagglers especially Asean Kagglers. I hope that this simple writing can provide very broad benefits.\n\nI apologize if there is a grammar error in this paper because English is not my mother language.\n\"\"\"\n\"\"\"\n# Table of contents\n***\n> \n* [Introduction](#introduction)\n\n* [1. Asean Respondent in Kaggle 2019 Survey](#respondent)\n    * [1.1 Comparing Total Respondent by Area](#respondent_by_area)\n    * [1.2 Comparing Respondent by Country in Asean](#respondent_by_asean)\n    * [1.3 Comparing Asean Respondent by Year](#respondent_by_year)\n* [2. Comparative Analysis of Asean & Other Kagglers](#comparative)\n    * [2.1 Age](#age)\n    * [2.2 Gender](#gender)\n    * [2.3 Highest Education Level](#education)\n    * [2.4 Popular Platform to Study Data Science](#platform)\n    * [2.5 Experience Writing Code to Analyse Data](#exp)\n* [3. Motivation from Newbie for Newbie](#motivation)\n    * [3.1 Job Oportunity](#job)\n    * [3.2 Salary Overview](#salary)\n* [4. Conclusion](#conclusion)\n* [References](#ref)\n\"\"\"\n\"\"\"\n# Introduction\n<a id=\"introduction\"><\/a>\n***\n\nI see a decrease in interest based on the number of respondents compared to the previous year. So what is data science? Based on [Datajobs.com](https:\/\/datajobs.com\/what-is-data-science), Data science is a multidisciplinary blend of data inference, algorithmm development, and technology in order to solve analytically complex problems [1]. \n\nThe Association of Southeast Asian Nations, or ASEAN, was established on 8 August 1967 in Bangkok, Thailand, with the signing of the ASEAN Declaration (Bangkok Declaration) by the Founding Fathers of ASEAN, namely Indonesia, Malaysia, Philippines, Singapore and Thailand.\n\nI hope with this kernel, everyone's motivation and passion increases. **Happy reading :)**\n\"\"\"\n\"\"\"\n# 1. Asean Respondent in Kaggle 2019 Survey\n<a id=\"respondent\"><\/a>\n***\n\nWhat kind of distribution does Asean Kaglers have?\n\"\"\"\n\"\"\"\n## Comparing Total Respondents\n<a id='respondent_by_area'> <\/a>\n***\n\nSurprisingly, There are only 3.36% of respondents from ASEAN. Reversed with Asian respondents who are the most respondents compared to other continents [2].\n\"\"\"\ntmp = df_19.Area.value_counts()\nlabels = (np.array(tmp.index))\nsizes = (np.array((tmp \/ tmp.sum())*100))\n\ntrace = go.Pie(labels = labels, values = sizes)\nlayout = go.Layout(\n    title = 'Asean Respondent VS The Rest of The World'\n)\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\niplot(fig, filename = \"Compare_Respondent\")\n\"\"\"\n## Comparing Asean Respondent\n<a id='respondent_by_asean'><\/a>\n***\nKnowing that there are only 3.36% of respondents from ASEAN, I dig deeper into which countries in ASEAN are the biggest contributions. I found that Indonesia, Singapore and Viet Nam were the most respondents from ASEAN. \n\nActually, there are several other ASEAN countries that did not enter this survey such as the Philippines, Brunei Darussalam, Laos, and others. I hope that these countries can join the Kaggle Survey 2020.\n\"\"\"\ntmp = df19_asean.Q3.value_counts()\nlabels = (np.array(tmp.index))\nsizes = (np.array((tmp \/ tmp.sum())*100))\n\ntrace = go.Pie(labels = labels, values = sizes)\nlayout = go.Layout(\n    title = 'Asean Respondent'\n)\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\niplot(fig, filename = \"Asean_Respondent\")\n\"\"\"\n## Comparing Asean Respondents by Year\n<a id='respondent_by_year'><\/a>\n***\nThis section I want to show the problems that I want to raise. It can be seen in the plot below that the respondents from Asean declined when compared to the 2018 Kaggle Survey so I wondered why this could happen.\n\nIt turned out that the total respondents in the 2019 Kaggle Survey overall also experienced a decline from the 2018 Kaggle Survey.\n\nHopefully with this writing, respondents in the 2019 Kaggle Survey have increased again, especially from ASEAN respondents.\n\"\"\"\nimport plotly.graph_objects as go\n\nrespond_2019_asean = df_19.Area.value_counts()['Asean']\nrespond_2018_asean = df_18.Area.value_counts()['Asean']\nrespond_2017_asean = df_17.Area.value_counts()['Asean']\ndata = [[2017, respond_2017_asean], [2018, respond_2018_asean], [2019, respond_2019_asean]]\ncustom = pd.DataFrame(data, columns = ['Year', 'Total_Asean_Respondent']) \n\ntrace = go.Scatter(\n    x = custom.Year,\n    y = custom.Total_Asean_Respondent,\n    mode = 'lines',\n    name = 'Asean Respondent by Year'\n)\n\nlayout = go.Layout(title = 'Asean Respondent by Year')\nfigure = go.Figure(data = trace, layout = layout)\nfigure.show()\nrespond_2019 = df_19['Q1'].count()\nrespond_2018 = df_18['Q1'].count()\nrespond_2017 = df_17['Country'].count()\ndata = [[2017, respond_2017], [2018, respond_2018], [2019, respond_2019]]\ncustom = pd.DataFrame(data, columns = ['Year', 'Total_Respondent']) \n\ntrace = go.Scatter(\n    x = custom.Year,\n    y = custom.Total_Respondent,\n    mode = 'lines',\n    name = 'Total Respondent by Year'\n)\n\nlayout = go.Layout(title = 'Total Respondent by Year')\nfigure = go.Figure(data = trace, layout = layout)\nfigure.show()\n\"\"\"\n# 2. Comparative Analysis of Asean & Other Kagglers\n<a id='comparative'><\/a>\n***\nVery many young people who were respondents in this survey both Asean Kagglers and others. In this section, we know Data Science has good prospects because there is a lot of young people love to learn data :).\n\"\"\"\n\"\"\"\n## Age\n<a id='age'><\/a>\n***\n\"\"\"\nimport plotly.graph_objs as go\n\nasean_age_percentage = ((df_19.groupby('Area').get_group('Asean')['Q1'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Asean')['Q1'].sort_index() .count())*100)\nothers_age_percentage = ((df_19.groupby('Area').get_group('Others')['Q1'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Others')['Q1'].sort_index() .count())*100)\n    \n    \nx = df_19.groupby('Area').get_group('Asean')['Q1'].value_counts().sort_index().index\ny1 = asean_age_percentage\ny2 = others_age_percentage\n\n\ntrace1 = go.Bar(\n    x = x,\n    y = y1,\n    name = 'Asean',\n    marker = dict(\n        color='rgb(49,130,189)'\n    )\n)\ntrace2 = go.Bar(\n    x = x,\n    y = y2,\n    name = 'Others',\n    marker = dict(\n        color='rgb(55, 83, 109)'\n    )\n)\n\nlayout = go.Layout(\n    title = 'Age',\n    xaxis=dict(tickangle=-45, title='Age by Total Respondent Each Area'),\n    barmode='group',\n    yaxis=dict(\n        title='percentage',\n    )\n)\ndata = [trace1, trace2]\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\"\"\"\n## Gender\n<a id='gender'><\/a>\n***\nPredictably, men dominate in this survey in the Asean area. We hope that in the next year's survey strong women will emerge who also want to be serious about learning and community in Kaggle.\n\"\"\"\ntmp = df19_asean.Q2.value_counts()\nlabels = (np.array(tmp.index))\nsizes = (np.array((tmp \/ tmp.sum())*100))\n\ntrace = go.Pie(labels = labels, values = sizes)\nlayout = go.Layout(\n    title = 'Gender of Asean Respondent'\n)\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\niplot(fig, filename = \"Gender_Asean_Respondent\")\n\"\"\"\n## Highest Education Level\n<a id='education'><\/a>\n***\nIn Education section, most of respondents is Bachelor or Master degree.\n\"\"\"\nasean_education_percentage = ((df_19.groupby('Area').get_group('Asean')['Q4'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Asean')['Q4'].sort_index() .count())*100)\nothers_education_percentage = ((df_19.groupby('Area').get_group('Others')['Q4'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Others')['Q4'].sort_index() .count())*100)\n    \n    \nx = df_19.groupby('Area').get_group('Asean')['Q4'].value_counts().sort_index().index\ny1 = asean_education_percentage\ny2 = others_education_percentage\n\n\ntrace1 = go.Bar(\n    x = x,\n    y = y1,\n    name = 'Asean',\n    marker = dict(\n        color='rgb(49,130,189)'\n    )\n)\ntrace2 = go.Bar(\n    x = x,\n    y = y2,\n    name = 'Others',\n    marker = dict(\n        color='rgb(55, 83, 109)'\n    )\n)\n\nlayout = go.Layout(\n    title = 'Highest Education Level',\n    xaxis=dict(tickangle=-20),\n    barmode='group',\n    yaxis=dict(\n        title='percentage',\n    )\n)\ndata = [trace1, trace2]\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\"\"\"\n## Popular Platform To Study Data Science in Asean\n<a id='platform'><\/a>\n***\nFor beginners like me, this section presents several platforms that can be used to increase knowledge about Data Science. Hopefully the plot below can provide a good platform for all of you to learn.\n\"\"\"\nQ13_1 = df19_asean.Q13_Part_1.value_counts()\nQ13_2 = df19_asean.Q13_Part_2.value_counts()\nQ13_3 = df19_asean.Q13_Part_3.value_counts()\nQ13_4 = df19_asean.Q13_Part_4.value_counts()\nQ13_5 = df19_asean.Q13_Part_5.value_counts()\nQ13_6 = df19_asean.Q13_Part_6.value_counts()\nQ13_7 = df19_asean.Q13_Part_7.value_counts()\nQ13_8 = df19_asean.Q13_Part_8.value_counts()\nQ13_9 = df19_asean.Q13_Part_9.value_counts()\nQ13_10 = df19_asean.Q13_Part_10.value_counts()\nQ13_11 = df19_asean.Q13_Part_11.value_counts()\nQ13_12 = df19_asean.Q13_Part_12.value_counts()\n\nQ13_index = [Q13_1.index[0], Q13_2.index[0], Q13_3.index[0], Q13_4.index[0],\n            Q13_5.index[0], Q13_6.index[0], Q13_7.index[0], Q13_8.index[0],\n            Q13_9.index[0], Q13_10.index[0], Q13_11.index[0], Q13_12.index[0]]\nQ13_value = [Q13_1[0], Q13_2[0], Q13_3[0], Q13_4[0],\n            Q13_5[0], Q13_6[0], Q13_7[0], Q13_8[0],\n            Q13_9[0], Q13_10[0], Q13_11[0], Q13_12[0]]\n\nQ13 = pd.Series(Q13_value, index = Q13_index)\n\ntmp = Q13\nlabels = (np.array(tmp.index))\nsizes = (np.array((tmp \/ tmp.sum())*100))\n\ntrace = go.Pie(labels = labels, values = sizes)\nlayout = go.Layout(\n    title = 'Popular Platform To Study Data Science in Asean'\n)\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\niplot(fig, filename = \"Platform_Asean_Respondent\")\nQ13_1 = df19_rest.Q13_Part_1.value_counts()\nQ13_2 = df19_rest.Q13_Part_2.value_counts()\nQ13_3 = df19_rest.Q13_Part_3.value_counts()\nQ13_4 = df19_rest.Q13_Part_4.value_counts()\nQ13_5 = df19_rest.Q13_Part_5.value_counts()\nQ13_6 = df19_rest.Q13_Part_6.value_counts()\nQ13_7 = df19_rest.Q13_Part_7.value_counts()\nQ13_8 = df19_rest.Q13_Part_8.value_counts()\nQ13_9 = df19_rest.Q13_Part_9.value_counts()\nQ13_10 = df19_rest.Q13_Part_10.value_counts()\nQ13_11 = df19_rest.Q13_Part_11.value_counts()\nQ13_12 = df19_rest.Q13_Part_12.value_counts()\n\nQ13_index = [Q13_1.index[0], Q13_2.index[0], Q13_3.index[0], Q13_4.index[0],\n            Q13_5.index[0], Q13_6.index[0], Q13_7.index[0], Q13_8.index[0],\n            Q13_9.index[0], Q13_10.index[0], Q13_11.index[0], Q13_12.index[0]]\nQ13_value = [Q13_1[0], Q13_2[0], Q13_3[0], Q13_4[0],\n            Q13_5[0], Q13_6[0], Q13_7[0], Q13_8[0],\n            Q13_9[0], Q13_10[0], Q13_11[0], Q13_12[0]]\n\nQ13 = pd.Series(Q13_value, index = Q13_index)\n\ntmp = Q13\nlabels = (np.array(tmp.index))\nsizes = (np.array((tmp \/ tmp.sum())*100))\n\ntrace = go.Pie(labels = labels, values = sizes)\nlayout = go.Layout(\n    title = 'Popular Platform To Study Data Science in Non-Asean'\n)\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\niplot(fig, filename = \"Platform_Non_Asean_Respondent\")\n\"\"\"\n## Experience Writing Code to Analyse Data\n<a id='exp'><\/a>\n***\nAnd yes, you need to know how to code. Most of the respondent is 0 - 2 years experience in coding. Let's study together, and be surprised to survey next year that the respondents have good coding skills\n\"\"\"\nasean_exp_percentage = ((df_19.groupby('Area').get_group('Asean')['Q15'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Asean')['Q15'].sort_index() .count())*100)\nothers_exp_percentage = ((df_19.groupby('Area').get_group('Others')['Q15'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Others')['Q15'].sort_index() .count())*100)\n    \n    \nx = df_19.groupby('Area').get_group('Asean')['Q15'].value_counts().sort_index().index\ny1 = asean_exp_percentage\ny2 = others_exp_percentage\n\n\ntrace1 = go.Bar(\n    x = x,\n    y = y1,\n    name = 'Asean',\n    marker = dict(\n        color='rgb(49,130,189)'\n    )\n)\ntrace2 = go.Bar(\n    x = x,\n    y = y2,\n    name = 'Others',\n    marker = dict(\n        color='rgb(55, 83, 109)'\n    )\n)\n\nlayout = go.Layout(\n    title = 'Experience Writing Code to Analyse Data',\n    xaxis=dict(tickangle=-20),\n    barmode='group',\n    yaxis=dict(\n        title='percentage',\n    )\n)\ndata = [trace1, trace2]\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\"\"\"\n# 3. Motivation from Newbie for Newbie\n<a id='motivation'><\/a>\n***\nSo there are some reason why we go this path. I want to show you that the work that awaits you is vast and varied, the following plot below can provide a brief overview of your future job prospects.\n\"\"\"\n\"\"\"\n## Job Oportunity\n<a id='job'><\/a>\n***\n\"\"\"\nasean_job_percentage = df_19['Q5'].value_counts().sort_index()\n    \n    \nx = df_19['Q5'].value_counts().sort_index().index\ny = asean_job_percentage\n\n\ntrace = go.Bar(\n    x = x,\n    y = y,\n    name = 'Asean',\n    marker = dict(\n        color='rgb(49,130,189)'\n    )\n)\n\nlayout = go.Layout(\n    title = 'Job Oportunity',\n    xaxis=dict(tickangle=-20),\n    barmode='group',\n    yaxis=dict(\n        title='percentage',\n    )\n)\nfig = go.Figure(data=trace, layout=layout)\nfig.show()\n\"\"\"\n## Salary\n<a id='salary'><\/a>\n***\nPredictable, most of the respondents have \\\\$ 0-999 year. I think this is happening because so many newbies are responding. But don't be worry there is a lot of people can reach \\> \\\\$ 500.000. This is **FANTASTIC**, right? \n\"\"\"\nasean_salary_percentage = ((df_19.groupby('Area').get_group('Asean')['Q10'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Asean')['Q10'].sort_index() .count())*100)\nothers_salary_percentage = ((df_19.groupby('Area').get_group('Others')['Q10'].value_counts().sort_index()  \/ \n                         df_19.groupby('Area').get_group('Others')['Q10'].sort_index() .count())*100)\n    \n    \nx = df_19.groupby('Area').get_group('Asean')['Q10'].value_counts().sort_index().index\ny1 = asean_salary_percentage\ny2 = others_salary_percentage\n\n\ntrace1 = go.Bar(\n    x = x,\n    y = y1,\n    name = 'Asean',\n    marker = dict(\n        color='rgb(49,130,189)'\n    )\n)\ntrace2 = go.Bar(\n    x = x,\n    y = y2,\n    name = 'Others',\n    marker = dict(\n        color='rgb(55, 83, 109)'\n    )\n)\n\nlayout = go.Layout(\n    title = 'Salary Overview',\n    xaxis=dict(tickangle=-20),\n    barmode='group',\n    yaxis=dict(\n        title='percentage',\n    )\n)\ndata = [trace1, trace2]\nfig = go.Figure(data=data, layout=layout)\nfig.show()\n\"\"\"\n# 4. Conclusion\n<a id='conclusion'><\/a>\n***\nYap, this is the most important part. So in this notebook i want to show you all that Data is most powerful weapon in your hand.\n1. Respondents from Asean are only 3.3 % from all of the respondents. This shows that data science is still lacking interest in ASEAN. And I hope with this notebook a significant improvement can occur <br>\n\n2. The prospect of data going forward is extraordinary. <br>\n\n3. Let's study together\n\n\"\"\"\n\"\"\"\n# References\n<a id='ref'><\/a>\n***\n[1] [https:\/\/datajobs.com\/what-is-data-science](https:\/\/datajobs.com\/what-is-data-science) <br>\n[2] [michau96 - kagglers-continent-fight-2019](https:\/\/www.kaggle.com\/michau96\/kagglers-continent-fight-2019)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '228abc23089b02'}"}
{"id":"3513","text":"\"\"\"\n## CatBoost with Voting\n- Create several types of train_data with kFold, and then create a model for each dataset.\n- Estimate the final result by 'voting method' of the prediction result of each model.\n\"\"\"\nimport numpy as np\nimport pandas as pd\npd.set_option('display.max_columns', None)\nfrom scipy import stats\n\nimport os, sys, datetime\nfrom time import time\nfrom tqdm import tqdm_notebook as tqdm\n\nfrom collections import Counter\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import cohen_kappa_score\n\nfrom catboost import CatBoostClassifier\nimport category_encoders as ce\nKaggle = True\n\nif Kaggle:\n    DIR = '..\/input\/data-science-bowl-2019'\n    task_type = 'CPU'\nelse:\n    DIR = '.\/data-science-bowl-2019'\n    task_type = 'GPU'\n\"\"\"\n## Observe the data\n\"\"\"\ntrain = pd.read_csv(os.path.join(DIR,'train.csv'))\ntrain_labels = pd.read_csv(os.path.join(DIR,'train_labels.csv'))\nspecs = pd.read_csv(os.path.join(DIR,'specs.csv'))\ntest = pd.read_csv(os.path.join(DIR,'test.csv'))\nprint('train:\\t\\t',train.shape)\nprint('train_labels:\\t',train_labels.shape)\nprint('specs:\\t\\t',specs.shape)\nprint('test:\\t\\t',test.shape)\n\"\"\"\n### 1. train\n\"\"\"\ntrain.head()\ntrain[['event_id','game_session','installation_id',\n       'title','type','world']].describe()\nevent_code_n = train['event_code'].nunique()\nprint(\"num of unique 'event_code':\", event_code_n)\nprint(\"'event_code': \",\n      train['event_code'].min(), \"-\", train['event_code'].max())\n# 'event_data' exsample\nprint(train['event_data'][40])\nprint(train['event_data'][41])\nprint(train['event_data'][43])\n\"\"\"\n### 2. train_labels\n\"\"\"\ntrain_labels.head()\ntrain_labels[['game_session','installation_id', 'title']].describe()\n# unique 'title' list\ntrain_labels['title'].unique()\n\"\"\"\n### 3. specs\n\"\"\"\nspecs.head()\nspecs.describe()\n# 'info' exsample\nprint(specs['info'][0])\nprint(specs['info'][6])\nprint(specs['info'][7])\n# 'args' exsample\nprint(specs['args'][0])\nprint(specs['args'][1])\n\"\"\"\n### 4. test\n\"\"\"\ntest.head(8)\ntest[['event_id','game_session','installation_id',\n       'title','type','world']].describe()\n\"\"\"\n## Compile data\nBased on several kernels\n- Hosseinali: https:\/\/www.kaggle.com\/mhviraf\/a-new-baseline-for-dsb-2019-catboost-model\n- Bruno Aquino: https:\/\/www.kaggle.com\/braquino\/catboost-some-more-features\n\"\"\"\n# make 'title' and 'event_code' list\ntitle_list = list(set(train['title'].value_counts().index) \\\n                   .union(set(test['title'].value_counts().index)))\nevent_code_list = list(set(train['event_code'].value_counts().index) \\\n                   .union(set(test['event_code'].value_counts().index)))\n# makes dict 'title to number(integer)'\ntitle2num = dict(zip(title_list, np.arange(len(title_list))))\n# makes dict 'number to title'\nnum2title = dict(zip(np.arange(len(title_list)), title_list))\n# makes dict 'title to win event_code' \n# (4100 except 'Bird Measurer' and 4110 for 'Bird Measurer'))\ntitle2win_code = dict(zip(title2num.values() \\\n                    ,(np.ones(len(title2num))).astype('int') * 4100))\ntitle2win_code[title2num['Bird Measurer (Assessment)']] = 4110\n# Convert 'title' to the number\ntrain['title'] = train['title'].map(title2num)\ntest['title'] = test['title'].map(title2num)\ntrain_labels['title'] = train_labels['title'].map(title2num)\n\n# Convert 'timestamp' to datetime\ntrain['timestamp'] = pd.to_datetime(train['timestamp'])\ntest['timestamp'] = pd.to_datetime(test['timestamp'])\n# Convert the raw data into processed features\ndef get_data(user_sample, test_set=False):\n    '''\n    user_sample : DataFrame from train\/test group by 'installation_id'\n    test_set    : related with the labels processing\n    '''\n    # Constants and parameters declaration\n    user_assessments = []\n    last_type = 0\n    types_count = {'Clip':0, 'Activity':0, 'Assessment':0, 'Game':0}\n    time_first_activity = float(user_sample['timestamp'].values[0])\n    time_spent_each_title = {title:0 for title in title_list}\n    event_code_count = {code:0 for code in event_code_list}\n    accuracy_groups = {0:0, 1:0, 2:0, 3:0}\n    \n    accumu_accuracy_group = 0\n    accumu_accuracy=0\n    accumu_win_n = 0 \n    accumu_loss_n = 0 \n    accumu_actions = 0\n    counter = 0\n    durations = []\n    \n    # group by 'game_session'\n    for i, session in user_sample.groupby('game_session', sort=False):\n        # i      : game_session_id\n        # session: DataFrame from user_sample group by 'game_session'\n        session_type = session['type'].iloc[0]  # Game\/Assessment\/Activity\/Clip\n        session_title = session['title'].iloc[0]\n        \n        if session_type != 'Assessment':\n            time_spent = int(session['game_time'].iloc[-1] \/ 1000)   # [sec]\n            time_spent_each_title[num2title[session_title]] += time_spent\n        \n        if (session_type == 'Assessment') & (test_set or len(session)>1):\n            # search for event_code 4100(4110)\n            all_4100 = session.query(f'event_code == \\\n                                         {title2win_code[session_title]}')\n            # numbers of wins and losses\n            win_n = all_4100['event_data'].str.contains('true').sum()\n            loss_n = all_4100['event_data'].str.contains('false').sum()\n\n            # init features and then update\n            features = types_count.copy()\n            features.update(time_spent_each_title.copy())\n            features.update(event_code_count.copy())\n            features['session_title'] = session_title\n            features['accumu_win_n'] = accumu_win_n\n            features['accumu_loss_n'] = accumu_loss_n\n            accumu_win_n += win_n\n            accumu_loss_n += loss_n\n            \n            features['day_of_the_week'] = (session['timestamp'].iloc[-1]). \\\n                                            strftime('%A')    # Mod 2019-11-17\n\n            if durations == []:\n                features['duration_mean'] = 0\n            else:\n                features['duration_mean'] = np.mean(durations)\n            durations.append((session.iloc[-1, 2] - session.iloc[0, 2] ).seconds)\n\n            # average of the all accuracy of this player\n            features['accuracy_ave'] = accumu_accuracy \/ counter \\\n                                                if counter > 0 else 0\n            accuracy = win_n \/ (win_n + loss_n) \\\n                                   if (win_n + loss_n) > 0 else 0\n            accumu_accuracy += accuracy\n            if accuracy == 0:\n                features['accuracy_group'] = 0\n            elif accuracy == 1:\n                features['accuracy_group'] = 3\n            elif accuracy == 0.5:\n                features['accuracy_group'] = 2\n            else:\n                features['accuracy_group'] = 1\n            features.update(accuracy_groups)\n            accuracy_groups[features['accuracy_group']] += 1\n            # average of accuracy_groups of this player\n            features['accuracy_group_ave'] = \\\n                    accumu_accuracy_group \/ counter if counter > 0 else 0\n            accumu_accuracy_group += features['accuracy_group']\n            \n            # how many actions the player has done in this game_session\n            features['accumu_actions'] = accumu_actions\n            \n            # if test_set, all sessions belong to the final dataset\n            # elif train, needs to be passed throught this clausule\n            if test_set or (win_n + loss_n) > 0:\n                user_assessments.append(features)\n                \n            counter += 1\n        \n        # how many actions was made in each event_code\n        event_codes = Counter(session['event_code'])\n        for key in event_codes.keys():\n            event_code_count[key] += event_codes[key]\n\n        # how many actions the player has done\n        accumu_actions += len(session)\n        if last_type != session_type:\n            types_count[session_type] += 1\n            last_type = session_type\n            \n    # if test_set, only the last assessment must be predicted,\n    # the previous are scraped\n    if test_set:\n        return user_assessments[-1]\n    return user_assessments\n# get_data function is applyed to each installation_id\ncompiled_data = []\ninstallation_n = train['installation_id'].nunique()\nfor i, (ins_id, user_sample) in tqdm(enumerate(train.groupby( \\\n                                     'installation_id', sort=False)),\n                                     total=installation_n):\n    # user_sample : DataFrame group by 'installation_id'\n    compiled_data += get_data(user_sample)\n# the compiled_data is converted to DataFrame and deleted to save memory\nnew_train = pd.DataFrame(compiled_data)\ndel compiled_data\nnew_train.head(10)\n# process test set, the same that was done with the train set\nnew_test = []\nfor ins_id, user_sample in tqdm(test.groupby('installation_id',sort=False),\n                                total=1000):\n    new_test.append(get_data(user_sample, test_set=True))\n    \nnew_test = pd.DataFrame(new_test)\nnew_test.head(10)\n# all_features but 'accuracy_group', that is the label y\nall_features = [x for x in new_train.columns if x not in ['accuracy_group']]\n# categorical feature\ncategorical_features = ['session_title','day_of_the_week']\n# Encode categorical_features to integer(for use with LightGB,XGBoost,etc)\n\n# concatnate train and test data\ntemp_df = pd.concat([new_train[all_features], new_test[all_features]])\n# encode\nencoder = ce.ordinal.OrdinalEncoder(cols = categorical_features)\ntemp_df = encoder.fit_transform(temp_df)\n# dataset\nX, y = temp_df.iloc[:len(new_train),:], new_train['accuracy_group']\nX_test = temp_df.iloc[len(new_train):,:]\nX.head()\ny.head()\nX_test.head()\n\"\"\"\n## Model (CatBoostClassifier)\n\"\"\"\n# makes the model and set the parameters\ndef make_classifier():\n    model = CatBoostClassifier(\n        loss_function='MultiClass',\n        eval_metric=\"WKappa\",\n        task_type=task_type,\n        thread_count=-1,\n        od_type=\"Iter\",\n        early_stopping_rounds=500,\n        random_seed=50,\n        \n        border_count=110,\n        l2_leaf_reg=10,\n        iterations=2000,\n        learning_rate=0.1,\n        depth=6\n    )\n    return model\n# Train and make 5 models\nstart_time = time()\n\nNFOLDS = 5\nfolds = StratifiedKFold(n_splits=NFOLDS, shuffle=True, random_state=42)\nmodels = []\nscores = []\nfor fold, (train_ids, test_ids) in enumerate(folds.split(X, y)):\n    print('\u25cf Fold :', fold+1)\n    model = make_classifier()\n    model.fit(X.loc[train_ids, all_features], y.loc[train_ids], \n              eval_set=(X.loc[test_ids, all_features], y.loc[test_ids]),\n              use_best_model=False,     # The meaning of this parameter does not fall into the trap\n              verbose=500,\n              cat_features=categorical_features)    \n    models.append(model)\n    scores.append(model.get_best_score()['validation']['WKappa'])\n    print('\\n')\n    \nprint('-' * 50)\nprint(\"Average 'WKappa' Score =\", np.mean(scores))\nprint('-' * 50)\nprint('finished in {}'.format( \n    str(datetime.timedelta(seconds=time() - start_time))))\n# Check the effect of 'voting'\npredictions = []\nfor model in models:\n    predictions.append(model.predict(X).astype(int))\npredictions = np.concatenate(predictions, axis=1)\ndf = pd.DataFrame(predictions)\n\nvote = stats.mode(predictions, axis=1)[0].reshape(-1)\ndf['vote'] = vote\ndf['y'] = y\ndf.head(10)\nkappa_score = []\nfor col in df.columns[:NFOLDS+1]:\n    kappa_score.append(cohen_kappa_score(df['y'], df[col]))\nprint('kappa_score:\\n',kappa_score)\nprint('average score:',np.mean(kappa_score[:NFOLDS]))\nprint('voting score :',kappa_score[-1],'\\n')\nprint('Improved from',np.mean(kappa_score[:NFOLDS]),'to',\n      kappa_score[-1],\"by 'voting'\")\n\"\"\"\n## Make submission\n\"\"\"\npredictions = []\nfor model in models:\n    predictions.append(model.predict(X_test))\npredictions = np.concatenate(predictions, axis=1)\n# Voting\npredictions = stats.mode(predictions, axis=1)[0].reshape(-1)\nprint(predictions.shape)\nsubmission = pd.read_csv(os.path.join(DIR,'sample_submission.csv'))\nsubmission['accuracy_group'] = np.round(predictions).astype('int')\nsubmission.head(10)\nsubmission['accuracy_group'].plot(kind='hist')\nsubmission.to_csv('submission.csv', index=None)","meta":"{'source': 'AI4Code', 'id': '069974851d8fad'}"}
{"id":"139038","text":"\"\"\"\nAs you have probably noticed (or calculated), there is no way how to get all the dataset into the RAM given the 16 GB of Kaggle Kernels (for float32 representation of inputs, you would need around 128 GB of RAM just for training dataset itself, if my calculations are correct).\n\"\"\"\nimport sys\nimport numpy as np\n\noneImage8 = np.zeros((1, 512, 512, 4), dtype=np.int8)\noneImage16 = np.zeros((1, 512, 512, 4), dtype=np.float16)\noneImage32 = np.zeros((1, 512, 512, 4), dtype=np.float32)\nprint('Size of all training images, if encoded as int8: ', sys.getsizeof(oneImage8) * 31072 \/ 1024 \/ 1024 \/ 1024, ' GB')\nprint('Size of all training images, if encoded as float16: ', sys.getsizeof(oneImage16) * 31072 \/ 1024 \/ 1024 \/ 1024, ' GB')\nprint('Size of all training images, if encoded as float32: ', sys.getsizeof(oneImage32) * 31072 \/ 1024 \/ 1024 \/ 1024, ' GB')\n\"\"\"\nThis kernel tries to play around with custom data generator for fast on-fly data loading. It's written as a descendant of **keras.utils.Sequence**, which has the nice property to be compatible with the **use_multiprocessing=True** setting in *model.fit_generator()* function.\n\nNow with added caching: If you have enough RAM (e.g. running this script on Google Cloud highmem VC), you can let the Data Generator save all the data into RAM and then use these in the following epochs. Do not try this on Kaggle Kernels with full training dataset, though.\nCurrently, using cache cannot be combined with **use_multiprocessing=True** because this parameter leads to creating multiple DataGenerator objects that do not have any shared variables. Solutions to this are welcome.\n\"\"\"\nimport keras\nfrom keras.utils import Sequence\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nBATCH_SIZE = 16\nSEED = 777\nSHAPE = (512, 512, 4)\nDIR = '..\/input'\nVAL_RATIO = 0.1 # 10 % as validation\nDEBUG = True\nTHRESHOLD = 0.05 # due to different cost of True Positive vs False Positive, this is the probability threshold to predict the class as 'yes'\ndef getTrainDataset():\n    \n    path_to_train = DIR + '\/train\/'\n    data = pd.read_csv(DIR + '\/train.csv')\n\n    paths = []\n    labels = []\n    \n    for name, lbl in zip(data['Id'], data['Target'].str.split(' ')):\n        y = np.zeros(28)\n        for key in lbl:\n            y[int(key)] = 1\n        paths.append(os.path.join(path_to_train, name))\n        labels.append(y)\n\n    return np.array(paths), np.array(labels)\n\ndef getTestDataset():\n    \n    path_to_test = DIR + '\/test\/'\n    data = pd.read_csv(DIR + '\/sample_submission.csv')\n\n    paths = []\n    labels = []\n    \n    for name in data['Id']:\n        y = np.ones(28)\n        paths.append(os.path.join(path_to_test, name))\n        labels.append(y)\n\n    return np.array(paths), np.array(labels)\n\n# credits: https:\/\/github.com\/keras-team\/keras\/blob\/master\/keras\/utils\/data_utils.py#L302\n# credits: https:\/\/stanford.edu\/~shervine\/blog\/keras-how-to-generate-data-on-the-fly\n\nclass ProteinDataGenerator(keras.utils.Sequence):\n            \n    def __init__(self, paths, labels, batch_size, shape, shuffle = False, use_cache = False):\n        self.paths, self.labels = paths, labels\n        self.batch_size = batch_size\n        self.shape = shape\n        self.shuffle = shuffle\n        self.use_cache = use_cache\n        if use_cache == True:\n            self.cache = np.zeros((paths.shape[0], shape[0], shape[1], shape[2]))\n            self.is_cached = np.zeros((paths.shape[0]))\n        self.on_epoch_end()\n    \n    def __len__(self):\n        return int(np.ceil(len(self.paths) \/ float(self.batch_size)))\n    \n    def __getitem__(self, idx):\n        indexes = self.indexes[idx * self.batch_size : (idx+1) * self.batch_size]\n\n        paths = self.paths[indexes]\n        X = np.zeros((paths.shape[0], self.shape[0], self.shape[1], self.shape[2]))\n        # Generate data\n        if self.use_cache == True:\n            X = self.cache[indexes]\n            for i, path in enumerate(paths[np.where(self.is_cached[indexes] == 0)]):\n                image = self.__load_image(path)\n                self.is_cached[indexes[i]] = 1\n                self.cache[indexes[i]] = image\n                X[i] = image\n        else:\n            for i, path in enumerate(paths):\n                X[i] = self.__load_image(path)\n\n        y = self.labels[indexes]\n        \n        return X, y\n    \n    def on_epoch_end(self):\n        \n        # Updates indexes after each epoch\n        self.indexes = np.arange(len(self.paths))\n        if self.shuffle == True:\n            np.random.shuffle(self.indexes)\n\n    def __iter__(self):\n        \"\"\"Create a generator that iterate over the Sequence.\"\"\"\n        for item in (self[i] for i in range(len(self))):\n            yield item\n            \n    def __load_image(self, path):\n        R = Image.open(path + '_red.png')\n        G = Image.open(path + '_green.png')\n        B = Image.open(path + '_blue.png')\n        Y = Image.open(path + '_yellow.png')\n\n        im = np.stack((\n            np.array(R), \n            np.array(G), \n            np.array(B),\n            np.array(Y)), -1)\n        \n        im = np.divide(im, 255)\n        return im\npaths, labels = getTrainDataset()\ntg = ProteinDataGenerator(paths, labels, BATCH_SIZE, SHAPE)\n\"\"\"\nLet's measure the time to get 128 images. Standard methods are around ~4 seconds on Kaggle Kernels.\n\"\"\"\n%%time\nfor i in range(8):\n    im, lbl = tg[i]\n\"\"\"\nLet's test the RAM caching functionality (and measure the loading time):\n\"\"\"\ntg_cache = ProteinDataGenerator(paths[0:200], labels[0:200], BATCH_SIZE, SHAPE, use_cache=True)\n%%time\n#first reading of 128 images should take same time as before\nfor i in range(8):\n    im, lbl = tg_cache[i]\n%%time\n#second reading from RAM should be MUCH faster\nfor i in range(8):\n    im, lbl = tg_cache[i]\n# read data from DB\nim, lbl = tg[0]\n\nfig, ax = plt.subplots(4, 4, figsize=(50,50))\n\nfor row in range(4):\n    for col in range(4):\n        ax[row, col].imshow(im[row*4+col, :, :, 0:3])\n        #plt.imshow(image[row*4+col, :, :, 0:3]) # first three channels are RGB, fourth is yellow\n\nplt.show()\ndel(tg, tg_cache)\n\"\"\"\n# Using in Keras\nLet's try to test the multi_processing.\n\"\"\"\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Activation, Dropout, Flatten, Dense, Input, Conv2D, MaxPooling2D, BatchNormalization\nfrom keras import metrics\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend as K\nimport keras\nimport tensorflow as tf\n\nfrom tensorflow import set_random_seed\nset_random_seed(SEED)\n# credits: https:\/\/www.kaggle.com\/guglielmocamporese\/macro-f1-score-keras\n\ndef f1(y_true, y_pred):\n    #y_pred = K.round(y_pred)\n    y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), THRESHOLD), K.floatx())\n    tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)\n    tn = K.sum(K.cast((1-y_true)*(1-y_pred), 'float'), axis=0)\n    fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)\n    fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)\n\n    p = tp \/ (tp + fp + K.epsilon())\n    r = tp \/ (tp + fn + K.epsilon())\n\n    f1 = 2*p*r \/ (p+r+K.epsilon())\n    f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)\n    return K.mean(f1)\n# some basic useless model\ndef create_model(input_shape):\n    \n    model = Sequential()\n    model.add(Conv2D(8, (3, 3), activation='relu', input_shape=input_shape))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Conv2D(16, (3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Conv2D(32, (3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Conv2D(128, (3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Conv2D(256, (3, 3), activation='relu'))\n    model.add(BatchNormalization(axis=-1))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    model.add(Flatten())\n    model.add(Dropout(0.5))\n    #model.add(Dense(28))\n    #model.add(Activation('relu'))\n    #model.add(Dropout(0.1))\n    model.add(Dense(28))\n    model.add(Activation('sigmoid'))\n    \n    return model\nmodel = create_model((512,512,4))\nmodel.compile(\n    loss='binary_crossentropy', \n    optimizer=Adam(0.0001),\n    metrics=['acc',f1])\n\nmodel.summary()\npaths, labels = getTrainDataset()\n\n# divide to \nkeys = np.arange(paths.shape[0], dtype=np.int)  \nnp.random.seed(SEED)\nnp.random.shuffle(keys)\nlastTrainIndex = int((1-VAL_RATIO) * paths.shape[0])\n\nif DEBUG == True:  # use only small subset for debugging, Kaggle's RAM is limited\n    pathsTrain = paths[0:256]\n    labelsTrain = labels[0:256]\n    pathsVal = paths[lastTrainIndex:lastTrainIndex+256]\n    labelsVal = labels[lastTrainIndex:lastTrainIndex+256]\n    use_cache = True\nelse:\n    pathsTrain = paths[0:lastTrainIndex]\n    labelsTrain = labels[0:lastTrainIndex]\n    pathsVal = paths[lastTrainIndex:]\n    labelsVal = labels[lastTrainIndex:]\n    use_cache = False\n\nprint(paths.shape, labels.shape)\nprint(pathsTrain.shape, labelsTrain.shape, pathsVal.shape, labelsVal.shape)\n\ntg = ProteinDataGenerator(pathsTrain, labelsTrain, BATCH_SIZE, SHAPE, use_cache=use_cache)\nvg = ProteinDataGenerator(pathsVal, labelsVal, BATCH_SIZE, SHAPE, use_cache=use_cache)\n\n# https:\/\/keras.io\/callbacks\/#modelcheckpoint\ncheckpoint = ModelCheckpoint('.\/base.model', monitor='val_f1', verbose=1, save_best_only=True, save_weights_only=False, mode='max', period=1)\nepochs = 50\n\nif DEBUG == True:\n    use_multiprocessing = False # DO NOT COMBINE WITH CACHE! \n    workers = 1 # DO NOT COMBINE WITH CACHE! \nelse:\n    use_multiprocessing = True\n    workers = 2\n\nhist = model.fit_generator(\n    tg,\n    steps_per_epoch=len(tg),\n    validation_data=vg,\n    validation_steps=8,\n    epochs=epochs,\n    use_multiprocessing=use_multiprocessing, # you have to train the model on GPU in order to this to be benefitial\n    workers=workers, # you have to train the model on GPU in order to this to be benefitial\n    verbose=1,\n    callbacks=[checkpoint])\nfig, ax = plt.subplots(1, 2, figsize=(15,5))\nax[0].set_title('loss')\nax[0].plot(hist.epoch, hist.history[\"loss\"], label=\"Train loss\")\nax[0].plot(hist.epoch, hist.history[\"val_loss\"], label=\"Validation loss\")\nax[1].set_title('acc')\nax[1].plot(hist.epoch, hist.history[\"f1\"], label=\"Train F1\")\nax[1].plot(hist.epoch, hist.history[\"val_f1\"], label=\"Validation F1\")\nax[0].legend()\nax[1].legend()\n#fullValGen = ProteinDataGenerator(paths[lastTrainIndex:], labels[lastTrainIndex:], BATCH_SIZE, SHAPE)\n#fullValPred = np.zeros((paths[lastTrainIndex:].shape[0], 28))\n#for i in tqdm(range(len(fullValGen))):\nbestModel = load_model('.\/base.model', custom_objects={'f1': f1})\npathsTest, labelsTest = getTestDataset()\n\ntestg = ProteinDataGenerator(pathsTest, labelsTest, BATCH_SIZE, SHAPE)\nsubmit = pd.read_csv(DIR + '\/sample_submission.csv')\nP = np.zeros((pathsTest.shape[0], 28))\nfor i in tqdm(range(len(testg))):\n    images, labels = testg[i]\n    score = bestModel.predict(images)\n    P[i*BATCH_SIZE:i*BATCH_SIZE+score.shape[0]] = score\nPP = np.array(P)\nprediction = []\n\nfor row in tqdm(range(submit.shape[0])):\n    \n    str_label = ''\n    \n    for col in range(PP.shape[1]):\n        if(PP[row, col] < THRESHOLD):   # to account for losing TP is more costly than decreasing FP\n            #print(PP[row])\n            str_label += ''\n        else:\n            str_label += str(col) + ' '\n    prediction.append(str_label.strip())\n    \nsubmit['Predicted'] = np.array(prediction)\nsubmit.to_csv('datagenerator_model_v1.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'ff9ab9540966b5'}"}
{"id":"46263","text":"\"\"\"\nThis notebook is inspired from [@shivamb's notebook on text generation](https:\/\/www.kaggle.com\/shivamb\/beginners-guide-to-text-generation-using-lstms) and [@thebrownviking20's work on LSTMs](https:\/\/www.kaggle.com\/thebrownviking20\/intro-to-recurrent-neural-networks-lstm-gru)\n\"\"\"\n\"\"\"\nThe goal of this notebook is to generate TripAdvisor reviews with Long Short Term Memory units.\n\"\"\"\n\"\"\"\n# LSTMs\n\"\"\"\n\"\"\"\n![lstm.png](attachment:lstm.png)\n\"\"\"\n\"\"\"\nThe LSTM block learns which elements it should retain over the long term and which elements it should forget. We can consider the states of the Ct memory as the states of a memory acting on the long term and we can see the hidden states ht as the states of a memory acting on the short term.\n\nIt first takes the previous memory state Ct-1 and performs a multiplication with the forget gate f to decide at which degree Ct-1 should be forgotten. The value of the forget gate is between 0 and 1. For example, if it is equal to 0, then Ct-1 is completely forgotten; and if it is equal to 1, then Ct-1 is completely passed on to the rest of the block.\n\nIt then adds the part of Ct-1 retained and the information retained by the I gate.\nThe Ct memory state thus obtained is transferred directly to the next LSTM block. On the other hand, Ct is copied. The tanh function is applied to this copy, then the result is coupled with xt and ht-1, and the final result obtained is filtered by the output gate O. This gives us the hidden state ht of the LSTM block, which is then transferred to the next LSTM block.\n\"\"\"\n\"\"\"\n# Data preparation\n\"\"\"\n\"\"\"\nThe LSTMs are implemented, and the data prepared for the model thanks to the Keras library. The first step is to clean the data, by removing for example the punctuation present in the corpus.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport string\n\n# keras module for building LSTM \nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Embedding, LSTM, Dense, Dropout\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.callbacks import EarlyStopping\nfrom keras.models import Sequential\nimport keras.utils as ku\n\nfrom keras.callbacks import EarlyStopping\ntrip_advisor_data = pd.read_csv('..\/input\/trip-advisor-hotel-reviews\/tripadvisor_hotel_reviews.csv')\ntrip_advisor_data = trip_advisor_data['Review']\ntrip_advisor_data = trip_advisor_data.iloc[:1000]\ndef clean_text(txt):\n    txt = \"\".join(v for v in txt if v not in string.punctuation).lower()\n    txt = txt.encode(\"utf8\").decode(\"ascii\",'ignore')\n    return txt \n\ncorpus = [clean_text(x) for x in trip_advisor_data]\ncorpus[0]\n\"\"\"\nThe next step is tokenization. It is a process of extracting tokens from a corpus. Thus, each sequence of words is converted into a sequence of tokens.\n\"\"\"\ntokenizer = Tokenizer()\n\ndef get_sequence_of_tokens(corpus):\n    ## tokenization\n    tokenizer.fit_on_texts(corpus)\n    total_words = len(tokenizer.word_index) + 1\n    \n    ## convert data to sequence of tokens \n    input_sequences = []\n    for line in corpus:\n        token_list = tokenizer.texts_to_sequences([line])[0]\n        for i in range(1, len(token_list)):\n            n_gram_sequence = token_list[:i+1]\n            input_sequences.append(n_gram_sequence)\n    return input_sequences, total_words\n\ninp_sequences, total_words = get_sequence_of_tokens(corpus)\ninp_sequences[:10]\n\"\"\"\nWord sequences may have different lengths. We need to pad them and equalize their lengths. We use the pad_sequence function of Keras for this purpose. To train a template to generate text, we need to create labels. So for each given word sequence, the goal is to predict the next word.\n\"\"\"\ndef generate_padded_sequences(input_sequences):\n    max_sequence_len = max([len(x) for x in input_sequences])\n    input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))\n    \n    predictors, label = input_sequences[:,:-1],input_sequences[:,-1]\n    label = ku.to_categorical(label, num_classes=total_words)\n    return predictors, label, max_sequence_len\n\npredictors, label, max_sequence_len = generate_padded_sequences(inp_sequences)\n\"\"\"\n# Creating and training the model\n\"\"\"\nearly_stopping = EarlyStopping(\n    monitor='loss', min_delta=0.001, patience=30, verbose=0,\n    mode='min', baseline=None, restore_best_weights=True\n)\ndef create_model(max_sequence_len, total_words):\n    input_len = max_sequence_len - 1\n    model = Sequential()\n    \n    # Add Input Embedding Layer\n    model.add(Embedding(total_words, 10, input_length=input_len))\n    \n    # Add Hidden Layer 1 - LSTM Layer\n    model.add(LSTM(100,return_sequences=True))\n    model.add(Dropout(0.1))\n    \n    # Add Hidden Layer 2 - LSTM Layer\n    model.add(LSTM(100))\n    model.add(Dropout(0.1))\n    \n    # Add Output Layer\n    model.add(Dense(total_words, activation='softmax'))\n\n    model.compile(loss='categorical_crossentropy', optimizer='adam')\n    \n    return model\n\nmodel = create_model(max_sequence_len, total_words)\nmodel.summary()\nmodel.fit(predictors, label, epochs=200, callbacks=[early_stopping], verbose=False)\n\"\"\"\n# Text Generating\n\"\"\"\ndef generate_text(seed_text, next_words, model, max_sequence_len):\n    for _ in range(next_words):\n        token_list = tokenizer.texts_to_sequences([seed_text])[0]\n        token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')\n        predicted = model.predict_classes(token_list, verbose=0)\n        \n        output_word = \"\"\n        for word,index in tokenizer.word_index.items():\n            if index == predicted:\n                output_word = word\n                break\n        seed_text += \" \"+output_word\n    return seed_text.title()\nprint(generate_text(\"this hotel\", 20, model, max_sequence_len))\nprint(generate_text(\"we liked\", 20, model, max_sequence_len))\nprint(generate_text(\"the place\", 20, model, max_sequence_len))\nprint(generate_text(\"everything\", 20, model, max_sequence_len))\nprint(generate_text(\"I think\",20, model, max_sequence_len))","meta":"{'source': 'AI4Code', 'id': '5540c6226f6c43'}"}
{"id":"33507","text":"\"\"\"\n# References\n\n- The competition is https:\/\/www.kaggle.com\/c\/dogs-vs-cats-redux-kernels-edition (it ended long time ago)\n- Pytorch official docs:\n    - [Finetuning Torchvision Models](https:\/\/pytorch.org\/tutorials\/beginner\/finetuning_torchvision_models_tutorial.html)\n    - [Writing Custom Datasets, DataLoaders and Transforms](https:\/\/pytorch.org\/tutorials\/beginner\/data_loading_tutorial.html)\n    - Any other docs refered to train model or whatever, left comments on each section.\n- Refered kernels:\n    - [Dog_vs_Cat Transfer Learning - VGG16 by Pytorch](https:\/\/www.kaggle.com\/bootiu\/dog-vs-cat-transfer-learning-vgg16-by-pytorch)\n\"\"\"\n\"\"\"\n# Import libraries\n\"\"\"\n# Standard library\nimport copy\nimport glob\nimport multiprocessing\nimport os\nimport time\nimport zipfile\n\n# Pytorch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models, transforms\n\n# Related third party\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom skimage import io, transform\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm\n\"\"\"\n# Pre process for each environment\n\"\"\"\n\"\"\"\n### For Kaggle kernel\n\"\"\"\nbase_dir = '..\/input\/dogs-vs-cats-redux-kernels-edition'\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall('..\/data')\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall('..\/data')\n\ntrain_dir = '..\/data\/train'\ntest_dir = '..\/data\/test'\n\"\"\"\n### For Google Colab\n\nIt assumes that downloaded data will be located under `'My Drive\/Data Set\/'`\n\"\"\"\n# with zipfile.ZipFile('.\/drive\/My Drive\/Data Set\/dogs-vs-cats-redux-kernels-edition.zip') as entire_zip:\n#     entire_zip.extractall('.')\n# with zipfile.ZipFile('.\/train.zip') as train_zip:\n#     train_zip.extractall('.')\n# with zipfile.ZipFile('.\/test.zip') as test_zip:\n#     test_zip.extractall('.')\n\n# train_dir = '.\/train'\n# test_dir = '.\/test'\n\"\"\"\n# Global Declarations\n\"\"\"\n\"\"\"\n## Constants\n\nRegarding `input_size`, `mean` and `std`, all pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using `mean = [0.485, 0.456, 0.406]` and `std = [0.229, 0.224, 0.225]`. See [torchvision.models](https:\/\/pytorch.org\/docs\/stable\/torchvision\/models.html) for details. \n\"\"\"\ninput_size = 224\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\n# Number of classes in the dataset\nnum_classes = 2 # dog, cat\n\n# Batch size for training (change depending on how much memory you have)\nbatch_size = 32\n\n# Number of epochs to train for\nnum_epochs = 2\n\n# Flag for feature extracting. When False, we finetune the whole model,\n#   when True we only update the reshaped layer params\nfeature_extract = True\n\n# Switch to perform multi-process data loading\nnum_workers = multiprocessing.cpu_count()\n\"\"\"\n## Helper Functions\n\"\"\"\n# train data file looks '.\/train\/dog.10435.jpg'\n# test data file looks '.\/test\/10435.jpg'\ndef extract_class_from(path):\n    file = path.split('\/')[-1]\n    return file.split('.')[0]\n\"\"\"\nThis `train_model` function comes from https:\/\/pytorch.org\/tutorials\/beginner\/finetuning_torchvision_models_tutorial.html#model-training-and-validation-code.\n\"\"\"\ndef train_model(model, dataloaders, criterion, optimizer, num_epochs=25):\n    since = time.time()\n\n    history = {'accuracy': [],\n               'val_accuracy': [],\n               'loss': [],\n               'val_loss': []}\n\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_acc = 0.0\n\n    for epoch in range(num_epochs):\n        print('Epoch {}\/{}'.format(epoch, num_epochs - 1))\n        print('-' * 10)\n\n        # Each epoch has a training and validation phase\n        for phase in ['train', 'val']:\n            if phase == 'train':\n                model.train()  # Set model to training mode\n            else:\n                model.eval()   # Set model to evaluate mode\n\n            running_loss = 0.0\n            running_corrects = 0\n\n            # Iterate over data.\n            for inputs, labels in tqdm(dataloaders[phase]):\n                inputs = inputs.to(device)\n                labels = labels.to(device)\n\n                # zero the parameter gradients\n                optimizer.zero_grad()\n\n                # forward\n                # track history if only in train\n                with torch.set_grad_enabled(phase == 'train'):\n                    outputs = model(inputs)\n                    loss = criterion(outputs, labels)\n\n                    _, preds = torch.max(outputs, 1)\n\n                    # backward + optimize only if in training phase\n                    if phase == 'train':\n                        loss.backward()\n                        optimizer.step()\n\n                # statistics\n                running_loss += loss.item() * inputs.size(0)\n                running_corrects += torch.sum(preds == labels.data)\n\n            epoch_loss = running_loss \/ len(dataloaders[phase].dataset)\n            epoch_acc = running_corrects.double() \/ len(dataloaders[phase].dataset)\n\n            print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n            # deep copy the model\n            if phase == 'val' and epoch_acc > best_acc:\n                best_acc = epoch_acc\n                best_model_wts = copy.deepcopy(model.state_dict())\n\n            if phase == 'train':\n                history['accuracy'].append(epoch_acc.item())\n                history['loss'].append(epoch_loss)\n            else:\n                history['val_accuracy'].append(epoch_acc.item())\n                history['val_loss'].append(epoch_loss) \n\n        print()\n\n    time_elapsed = time.time() - since\n    print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed \/\/ 60, time_elapsed % 60))\n    print('Best val Acc: {:4f}'.format(best_acc))\n\n    # load best model weights\n    model.load_state_dict(best_model_wts)\n    return model, history\n\"\"\"\n# Load Data\n\"\"\"\nall_train_files = glob.glob(os.path.join(train_dir, '*.jpg'))\ntrain_list, val_list = train_test_split(all_train_files, random_state=42)\nprint(len(train_list))\nprint(len(val_list))\n\"\"\"\n## Check what train data looks like\n\"\"\"\nfig, axes = plt.subplots(nrows=2,\n                         ncols=3,\n                         figsize=(18, 12))\nfor img_path, ax in zip(train_list, axes.ravel()):\n    ax.set_title(img_path)\n    ax.imshow(Image.open(img_path))\n\"\"\"\n## Dataset class\n\nSee https:\/\/pytorch.org\/tutorials\/beginner\/data_loading_tutorial.html#dataset-class for details.\n\"\"\"\nclass DogVsCatDataset(Dataset):\n  \n    def __init__(self, file_list, transform=None):\n        self.file_list = file_list\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.file_list)\n  \n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n       \n        img_name = self.file_list[idx]\n        image = Image.open(img_name)\n        if self.transform:\n            image = self.transform(image)\n    \n        label_category = extract_class_from(img_name)\n        label = 1 if label_category == 'dog' else 0\n    \n        return image, label\n\"\"\"\n## Create dataloaders\n\nSee https:\/\/pytorch.org\/tutorials\/beginner\/finetuning_torchvision_models_tutorial.html#load-data for details.\n\"\"\"\ndata_transforms = {\n    'train': transforms.Compose([\n        transforms.RandomResizedCrop(input_size, scale=(0.5, 1.0)),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ]),\n    'val': transforms.Compose([\n        transforms.Resize(input_size),\n        transforms.CenterCrop(input_size),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ])\n}\n# Create training and validation datasets\nimage_datasets = {\n    'train': DogVsCatDataset(train_list,\n                             transform=data_transforms['train']),\n    'val': DogVsCatDataset(val_list,\n                           transform=data_transforms['val'])\n}\n\n# Create training and validation dataloaders\ndataloaders_dict = {x: DataLoader(image_datasets[x],\n                                  batch_size=batch_size,\n                                  shuffle=True,\n                                  num_workers=num_workers) for x in ['train', 'val']}\n\n# Detect if we have a GPU available\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\"\"\"\n# Initialize and Reshape the Networks\n\nRegarding tuning VGG, see https:\/\/pytorch.org\/tutorials\/beginner\/finetuning_torchvision_models_tutorial.html#vgg.\n\n\n\"\"\"\nmodel_ft = models.vgg16(pretrained=True)\nmodel_ft.classifier[6] = nn.Linear(4096, num_classes)\n\"\"\"\n# Create the Optimizer\n\nSee https:\/\/pytorch.org\/tutorials\/beginner\/finetuning_torchvision_models_tutorial.html#create-the-optimizer for details.\n\"\"\"\n# Send the model to GPU\nmodel_ft = model_ft.to(device)\n\n# Gather the parameters to be optimized\/updated in this run. If we are\n#  finetuning we will be updating all parameters. However, if we are\n#  doing feature extract method, we will only update the parameters\n#  that we have just initialized, i.e. the parameters with requires_grad\n#  is True.\nparams_to_update = model_ft.parameters()\nprint(\"Params to learn:\")\nif feature_extract:\n    params_to_update = []\n    for name,param in model_ft.named_parameters():\n        if param.requires_grad == True:\n            params_to_update.append(param)\n            print(\"\\t\",name)\nelse:\n    for name,param in model_ft.named_parameters():\n        if param.requires_grad == True:\n            print(\"\\t\",name)\n\n# Observe that all parameters are being optimized\noptimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)\n\"\"\"\n# Run Training and Validation Step\n\"\"\"\n# Setup the loss fxn\ncriterion = nn.CrossEntropyLoss()\n\n# Train and evaluate\nmodel_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs)\n\"\"\"\n## Visualize training results\n\nThis procedure comes from https:\/\/www.tensorflow.org\/tutorials\/images\/classification#visualize_training_results.\n\"\"\"\nacc = hist['accuracy']\nval_acc = hist['val_accuracy']\nloss = hist['loss']\nval_loss = hist['val_loss']\nepochs_range = range(num_epochs)\n\nplt.figure(figsize=(24, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\"\"\"\n# Predict\n\"\"\"\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\ntest_data_transform = data_transforms['val']\n\nids = []\nlabels = []\n\nwith torch.no_grad():\n    for test_path in tqdm(test_list):\n        img = Image.open(test_path)\n        img = test_data_transform(img)\n        img = img.unsqueeze(0)\n        img = img.to(device)\n\n        model_ft.eval()\n        outputs = model_ft(img)\n        preds = F.softmax(outputs, dim=1)[:, 1].tolist()\n\n        test_id = extract_class_from(test_path)\n        ids.append(int(test_id))\n        labels.append(preds[0])\n\"\"\"\n## Check how well the prediction went\n\"\"\"\ntemplate = '\"{}\" with {:.2%} confidence'\ndef pred_result_message(pred):\n    if pred > 0.5:\n        return template.format('dog', pred)\n    else:\n        return template.format('cat', 1 - pred)\n\nfig, axes = plt.subplots(nrows=2,\n                         ncols=3,\n                         figsize=(18, 12))\nfor img_path, label, ax in zip(test_list, labels, axes.ravel()):\n    ax.set_title(pred_result_message(label))\n    ax.imshow(Image.open(img_path))\n\"\"\"\n# Generate submittion.csv\n\"\"\"\noutput = pd.DataFrame({'id': ids,\n                       'label': np.round(labels)})\n\noutput.sort_values(by='id', inplace=True)\noutput.reset_index(drop=True, inplace=True)\n\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '3dbdb481c6541d'}"}
{"id":"33055","text":"\"\"\"\n**Content Based Recommender**\n\"\"\"\n\"\"\"\nFor the first part of the recommender system, we are going to build a content based recommender. We are going to extract content from overview, genres, cast, crew and keywords, vectorize the content of each film and compare similarities between films using cosine similarity. The recommender will recommend ten most similar documents given the target document.\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport ast\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# Getting more than one output Line\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\n\"\"\"\nFirst let's Load the datasets\n\"\"\"\ndfmm=pd.read_csv('..\/input\/movies_metadata.csv')\ndfc=pd.read_csv('..\/input\/credits.csv')\ndfk=pd.read_csv('..\/input\/keywords.csv')\ndfr=pd.read_csv('..\/input\/ratings_small.csv')\ndfmm.head()\ndfc.head()\ndfk.head()\ndfr.head()\n\"\"\"\nDrop rows with improper ids and observe the shape of each dataframe\n\"\"\"\ndfmm=dfmm.drop([19730, 29503, 35587])\ndfr=dfr.drop([19730, 29503, 35587])\ndfmm.shape\ndfc.shape\ndfk.shape\ndfr.shape\n\"\"\"\nConvert the datatype of feature 'id' to integer\n\"\"\"\ndataframes=[dfmm, dfc, dfk]\nfor dataframe in dataframes:\n    dataframe['id']=dataframe['id'].astype('int')\nnewdf=dfmm.merge(dfc, on='id')\nnewdf=newdf.merge(dfk, on='id')\nnewdf.head()\n\"\"\"\nCheck null values in the features\n\"\"\"\nnewdf['overview'].fillna('', inplace=True)\nnewdf.drop(newdf[newdf['vote_average'].isnull()].index, inplace=True)\n\"\"\"\nTo extract content from overviews, we tokenize each overview and apply part of speech tagging to each token. We will extract nouns, adjectives and adverbs and use only these words from overviews in our final model\n\"\"\"\ndef get_words(x):\n    bagofwords=[]\n    for i in x:\n        if i[1]=='NN':\n            bagofwords.append(i[0])\n        elif i[1]=='NNS':\n            bagofwords.append(i[0])\n        elif i[1]=='NNP':\n            bagofwords.append(i[0])\n        elif i[1]=='NNPS':\n            bagofwords.append(i[0])\n        elif i[1]=='JJ':\n            bagofwords.append(i[0])\n        elif i[1]=='JJR':\n            bagofwords.append(i[0])\n        elif i[1]=='JJS':\n            bagofwords.append(i[0])\n        elif i[1]=='RB':\n            bagofwords.append(i[0])\n        elif i[1]=='RBR':\n            bagofwords.append(i[0])\n        elif i[1]=='RBS':\n            bagofwords.append(i[0])\n    return bagofwords\ndef clean_words(x):\n    b=nltk.pos_tag(word_tokenize(x))\n    result=get_words(b)\n    return result\nnewdf['bagofwords']=newdf['overview'].apply(clean_words)\nfeatures = ['cast', 'crew', 'keywords', 'genres']\nfor feature in features:\n    newdf.loc[:, feature] = newdf.loc[:, feature].apply(ast.literal_eval)\n\"\"\"\nThe get_keywords function can extract the names of cast, genres and each keyword in keywords.\n\"\"\"\ndef get_keywords(x):\n    names=[i['name'] for i in x]\n    if len(names)>6:\n        names=names[:6]\n    return names\n\"\"\"\nThe get_director_producer function can extract the names of the director and producer of the film.\n\"\"\"\ndef get_director_producer(x):\n    names=[]\n    for i in x:\n        if i['job']=='Director':\n            names.append(i['name'])\n        elif i['job']=='Producer':\n            names.append(i['name'])\n    return names\n            \n\"\"\"\nTransform cast, crew, keywords and genres to the forms we need. And get rid of white space between first names and last names of the all the names, combining first names with last names as single names result in stronger identifiers. For examle, for \"Tom Hanks\", there are many people named \"Tom\", but \"TomHanks would be a strong indicator of whom we are referring to\n\"\"\"\nfeatures_new = ['cast', 'keywords', 'genres']\nfor feature in features_new:\n    newdf[feature]=newdf[feature].apply(get_keywords)\nnewdf['crew']=newdf['crew'].apply(get_director_producer)\nnewdf['crew']=newdf['crew'].map(lambda x: [i.replace(\" \", \"\") for i in x])\nnewdf['cast']=newdf['cast'].map(lambda x: [i.replace(\" \", \"\") for i in x])\n\"\"\"\nCreate the final \"document\" by combining all the content from genres, cast, crew, keywords, and bag of words\n\"\"\"\nnewdf['document']=newdf['genres']+newdf['cast']+newdf['crew']+newdf['keywords']+newdf['bagofwords']\nnewdf['document']=newdf['document'].map(lambda x: ' '.join(x))\nnewdf['document'].head()\n\"\"\"\nBefore we feed the count vectorizer with the \"document\" feature. We will rule out films with too low vote_average and too low vote_count to ensure recommendation quality\n\"\"\"\npd.qcut(newdf['vote_average'], 10).values\npd.qcut(newdf['vote_count'], 4).values\n\"\"\"\nFilms with vote_average less than 90 percent of all the films have vote_average less than 3.5, these films have very limited values to be recommended. Films with vote_count of less than 75 percent of all the films have vote_counts less than 49, these films have too small samples to be considered as statistically significant.\n\"\"\"\nnewdf=newdf[(newdf['vote_average']>3.5) & (newdf['vote_count']>34)]\nnewdf.reset_index(drop=True, inplace=True)\n\"\"\"\nWe compute count vectors for each document. Combining this vectors will give us a matrix where each row represents a document(a movie) and each column represent a word that occurs in the overall vocabulary. The value of each cell is the count of the word occur in the document.\n\"\"\"\nvectorizer = CountVectorizer(stop_words='english')\nmatrix = vectorizer.fit_transform(newdf['document'])\n\"\"\"\nCompute the Cosine Similarity matrix based on the count matrix\n\"\"\"\nsimilarity = cosine_similarity(matrix, matrix)\nsimilarity\ndef recommendation(x):\n    dataset=newdf.copy()\n    ind=dataset[dataset['original_title']==x].index[0]\n    sim=sorted(enumerate(similarity[ind]), key=lambda x: x[1], reverse=True)[1:11]\n    ind2, scores=zip(*sim)\n    recommendation=dataset.loc[ind2, 'original_title']\n    return recommendation\nrecommendation('The Matrix')\nrecommendation('The Prestige')\n\"\"\"\n**Collaborative filtering**\n\"\"\"\n\"\"\"\nThe Content based recommendation is great in recommending films based on content similarity between films. But a major flaw in content based recommender is that it does not take personal affections into account. If a user watches \"The Dark Knight\", it could either mean that the user likes Batman or the user likes Christopher Nolan, or it could be other reasons.\n\"\"\"\n\"\"\"\nCollaborative filtering construct a user-item matrix with user as the index and items as the columns. The value of each cell is the rating the user give the item. For a user-based filtering, we compute euclidean distance between each row to identify similar users, and recommend items similar users have watched. For a item-based filtering, we compute euclidean distance between each column to to identify similar items, and recommend items that are similar to the given item.\n\"\"\"\ndfmm['id']=dfmm['id'].astype('int')\ndfr['movieId']=dfr['movieId'].astype('int')\n\"\"\"\nMerge the tables with ratings and titles\n\"\"\"\ntitles=dfmm['original_title'].tolist()\nids=dfmm['id'].tolist()\nthe_map=dict(zip(ids, titles))\ndfr['title']=dfr['movieId'].map(the_map)\ndfr.shape\n\"\"\"\nPivot the table so the user is the index, title is the column and value of the cell is the rating\n\"\"\"\nuser_item=dfr.pivot_table(index='userId', columns='title', values='rating')\nuser_item.fillna(0, inplace=True)\n\"\"\"\nCompute the cosine similarity of each user\n\"\"\"\nuser_similarity = cosine_similarity(user_item, user_item)\nuser_similarity\nitem_user=user_item.T\nitem_user.head()\n\"\"\"\ncompute the cosine similarity of each item\n\"\"\"\nitem_similarity = cosine_similarity(item_user, item_user)\nitem_similarity\n\"\"\"\nIn order to personalize the recommendation given a user U and a film I, we will get the most similar films of film I and the most similar users of the user U.  Then we average their ratings for each item of the similar films, counting only those among the similar users who have rated the item.  We will recommend only the items that have higher average ratings given by the users\n\"\"\"\ndef filtering_recommendations(x, a):\n    dataset=item_user.copy()\n    df=dataset.reset_index()\n    ind=df[df['title']==x].index[0]\n    sim=sorted(enumerate(item_similarity[ind]), key=lambda x: x[1], reverse=True)[1:51]\n    ind2, scores=zip(*sim)\n    recommendation=df.loc[ind2, 'title']\n    dataset1=user_item.copy()\n    df2=dataset1.reset_index()\n    ind=df2[df2['userId']==a].index[0]\n    sim=sorted(enumerate(user_similarity[ind]), key=lambda x: x[1], reverse=True)[1:51]\n    ind2, scores=zip(*sim)\n    recommendation2=df2.loc[ind2, 'userId']\n    dictionary={}\n    for i in recommendation.index:\n        lis=[]\n        for j in recommendation2.index:\n            if (user_item.iloc[j, i]==0):\n                continue\n            else:\n                lis.append(user_item.iloc[j, i])\n        dictionary[i]=np.mean(lis)\n    keys=[]\n    for i in dictionary.keys():\n        keys.append(i)\n    values=[]\n    for i in dictionary.values():\n        values.append(i)\n    ourdf=pd.Series(values, index=keys)\n    sim3=ourdf.fillna(0).sort_values(ascending=False)[0:9].index\n    combined_recommendation=df.loc[sim3, 'title']\n    return combined_recommendation\nfiltering_recommendations('1984', 2)\nfiltering_recommendations('1984', 200)","meta":"{'source': 'AI4Code', 'id': '3ce7c0c6d0d16c'}"}
{"id":"17254","text":"\"\"\"\n## Pretrained Keras Models for Cross-tabular Data\n\"\"\"\n\"\"\"\nConvolutional Neural Networks are some of the strongest deep learning models, with state-of-the-art performance in problems of exceeding complexity, but can't we benefit from them in non-vision tasks? \n\nHere we will take advantage of keras pretrained CNNs for classifying non-image data. We will use a benchmark dataset of network intrusions, convert the data to image format, extract features with a pretrained model, and use these features to train a Dense-layer classifier.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\nCICDS2017 dataset from https:\/\/www.kaggle.com\/trystanmortimer\/cicids2017\n\"\"\"\ndf = pd.read_csv('..\/input\/cicids2017\/train.csv')\ntest = pd.read_csv('..\/input\/cicids2017\/test.csv')\ndf.head()\n\"\"\"\n### Data Analysis\n\"\"\"\ndf.info()\n#testset number of rows and columns\nprint('number of rows:',test.shape[0])\nprint('number of columns:',test.shape[1])\nprint('')\n# function to identify which columns are numerical, which categorical, store in two variables\n# print some results\n#input:dataframe, preferably with the label column sliced off\n#returns two lists with names of categorical and numeric features\n\ndef column_types(df):\n    numeric_columns = []\n    categorical_columns = []\n    \n    for column in df.columns:\n        if df[column].dtype != 'object':\n            numeric_columns.append(column)\n        else:\n            categorical_columns.append(column)\n    \n    print('number of numeric columns:',len(numeric_columns))\n    print('column names:')\n    print( numeric_columns)\n    print('')\n    \n    print ('number of categorical columns:', len(categorical_columns))\n    print ('column names:', categorical_columns)\n    print('')\n    print('Number of Unique Values:')\n\n    [print ('{}:'.format(column),df[column].nunique()) \n     for column in categorical_columns]\n\n    [print('\\n\\ncolumn {}:\\n'.format(column),df[column].value_counts()) \n     for column in categorical_columns]\n    \n    return numeric_columns, categorical_columns\n\nnumeric_columns, categorical_columns = column_types(df.iloc[:,:-1])\n# report on labels \n#input:dataframe and name of label column\n#displays class information\n\ndef label_report(df,label_column_name):\n    \n    print ('number of classes:', df[label_column_name].nunique())\n    print('')\n    print ('class names:', np.unique(df[label_column_name]))\n    print('')\n    print('Number of Unique Values:')\n    print(df[label_column_name].value_counts())\n\n\nprint('Train Data')\nprint('__________')\nlabel_report(df,'label')\nprint('')\nprint('__________')\nprint('')\nprint('Test Data')\nprint('__________')\nprint('Number of Unique Values:')\nprint(test['label'].value_counts())\n\"\"\"\n### Train Data Resampling\n\"\"\"\n#function to resample dataset in balanced form\n#majority classes may be downsampled, minority classes will be upsampled\n#input:pandas dataframe, output:pandas dataframe\n#params:df, name of label column, number of samples each class will have\n\ndef balanced_sampling(df, label_column_name, n_samples):\n    import numpy as np\n    import pandas as pd\n    \n    #identify majority and minority classes\n    minority_classes = []\n    majority_classes = []\n    for value,index in zip(df['label'].value_counts(),df['label'].value_counts().index):\n        if value<n_samples:\n            minority_classes.append(index)\n        else:\n            majority_classes.append(index)\n    \n    #sample each class\n    #oversample minority classes (replace=True)\n    balanced_df_min = df[df[label_column_name].isin(minority_classes)].groupby(by=df[label_column_name]).\\\n    apply(lambda x: x.sample(n_samples, replace=True))\n    #downsample majority classes (replace=False)\n    balanced_df_maj = df[df[label_column_name].isin(majority_classes)].groupby(by=df[label_column_name]).\\\n    apply(lambda x: x.sample(n_samples, replace=False))\n    #combine dataframes\n    balanced_df = pd.concat((balanced_df_min,balanced_df_maj),axis=0)\n    \n    #shuffle new dataframe\n    #(because it's sorted by class)\n    rand_state = np.random.RandomState(seed=33)\n    indices=np.arange(balanced_df.shape[0])\n    rand_state.shuffle(indices)\n       \n    return balanced_df.iloc[indices].reset_index(drop=True)\n\n\n\ndata=balanced_sampling(df,'label', 200000)\n\n# function that displays information about the resampling results\n#input: original dataframe, new dataframe, name of label column\n\ndef sampling_results(df_orig, df_final, label_column_name):\n    import matplotlib.pyplot as plt\n    import seaborn as sns\n    \n    print('original dataset rows:', df_orig.shape[0])\n    print('new dataset rows:     ', df_final.shape[0])\n    print ('')\n    print ('original dataset: samples per class')\n    print(df_orig[label_column_name].value_counts())\n    print('')\n    print('new dataset contains:')\n    print('{} values per class'.\\\n          format(df_final[label_column_name].value_counts()[0]))\n    \n    plt.figure(figsize=(12,4));\n    sns.countplot(x=label_column_name, data=df_orig, color='Gray');\n    plt.title('original dataset -- samples per class');\n    plt.figure(figsize=(12,4));\n    sns.countplot(x=label_column_name, data=df_final, color='Gray');\n    plt.title('new dataset -- samples per class');\n    \nsampling_results(df,data,'label')\n\"\"\"\n### Data Preparation\n\"\"\"\n#function to prepare input data\n#input:dataframe without labels\n#output1: numpy array of values of dataframe with categorical one-hot encoded\n#                                                        and all data scaled\n#output2: sklearn objects encoder and scaler, to apply .transform on test data, and to use attributes for reference\n\ndef prepare_input_data(df, scaling='minmax'):\n    \n    \n    #scaling\n    if scaling == 'minmax':\n        from sklearn.preprocessing import MinMaxScaler\n        scaler = MinMaxScaler()\n        df = scaler.fit_transform(df)\n    elif scaling == 'standard':\n        from sklearn.preprocessing import StandardScaler\n        scaler == StandardScaler()\n        data = scaler.fit_transform(df)\n\n    return df, scaler\n\n\nx_tr, scaler = prepare_input_data(data.iloc[:,:-1])\n\nx_ts = scaler.transform(test.iloc[:,:-1])\n# export scaled samplings\nnp.save('CICIDS2017_mydata_tr.npy',x_tr)\nnp.save('CICIDS2017_mydata_ts.npy',x_ts[:200000,:])\nnp.save('CICIDS2017_mylabels_tr.npy',data.iloc[:,-1])\nnp.save('CICIDS2017_mylabels_ts.npy',test.iloc[:200000,-1])\nx_tr = np.load('.\/CICIDS2017_mydata_tr.npy')\nx_ts = np.load('.\/CICIDS2017_mydata_ts.npy')\ny_tr = np.load('.\/CICIDS2017_mylabels_tr.npy')\ny_ts = np.load('.\/CICIDS2017_mylabels_ts.npy')\n\nx_tr.shape,y_tr.shape, x_ts.shape,y_ts.shape\n\"\"\"\n### Image Conversion\n\"\"\"\n#convert input data to images\n#converts to square matrices, pads with zeros\n\n#the function converts:\n#1d arrays into 2d images\n#2d arrays into sequence of 2d images (an image for each row)\n\ndef to_image(array):\n    \n    if array.ndim == 1:\n        t = array.shape[0]\n        sqr = int(np.round(np.sqrt(t)))\n        \n        if sqr**2 == t:\n            im=np.reshape(array.copy(),(sqr,sqr))\n\n        else:\n            im = np.zeros((sqr+1,sqr+1))\n            dif = (sqr+1)**2-t\n            im = np.ravel(im)\n            im[:-dif] = array.copy()\n            im = np.reshape(im,(sqr+1,sqr+1))\n            \n        return np.array(im)\n     \n        \n    elif array.ndim ==2:\n        t=array.shape[1]\n        sqr=int(np.round(np.sqrt(t)))\n        \n        if sqr**2 ==t:\n            ims = np.zeros((array.shape[0],sqr,sqr))\n            for i, im in enumerate(ims):\n                im = np.reshape(array[i].copy(),(sqr,sqr))\n        else:\n            ims = np.zeros((array.shape[0],sqr+1,sqr+1))\n            dif = (sqr+1)**2 - t\n            for i, im in enumerate(ims):\n                temp = np.ravel(im)\n                temp[:-dif] = array[i].copy()\n                im = np.reshape(temp,(sqr+1,sqr+1))\n        \n        return np.array(ims)\n      \n        \n    else:\n        print('wrong dimensions, 1d or 2d only')\n\n\n\n        \n\n#convert to rgb, keras pretrained need 3 color channels\n#we copy the first channel to the other two\n\ndef to_rgb(array):\n    \n    images = np.empty((array.shape[0],10,10,3))\n    \n    for i,image in enumerate(array):\n        \n        images[i,:,:,1] = np.squeeze(image)\n        images[i,:,:,2] = np.squeeze(image)\n        \n    return images\n\n\n\n\n\n#transform each image to 80x80x3, to make compatible with InceptionV3 pretrained model\n#we repeat the 10x10x3 matrix horizontally and vertically to get 80x80x3\n\ndef expand(array):\n\n\n    \n    expanded = np.repeat(array,8,axis=2)\n    expanded = np.repeat(expanded,8,axis=1)\n        \n    return expanded\n\"\"\"\nTo see how this layered transformation looks like,we will visualize two images for each class. Note that duplicating the grayscale channel to generate 3 rgb channels may cause individual pixels to exceed the threshold value. Imshow may occassionally display the images weirdly: there seems to be a bug and imshow may display a image in different ways if you run the command more than once, but the internal numerical representations are constant and normal. We will not apply color normalization, as that would distort our non-image data.\n\"\"\"\n#visualize two images for each class\n\nfrom skimage.io import imshow\n\nfor class_ in np.unique(y_tr):\n    indices = np.random.choice \\\n    (np.argwhere(y_tr==class_).flatten(),2)\n    class_ims = to_image(x_tr[indices])\n    class_ims = to_rgb(class_ims)\n    class_ims = expand(class_ims)\n    \n    plt.figure(figsize=(16,4));\n    plt.subplot(1,3,1);\n    imshow(class_ims[0]);\n    plt.title(class_)\n    plt.subplot(1,3,2);\n    imshow(class_ims[1]);\n    plt.title(class_);\n\nprint('image shape:',class_ims[1].shape)\n\"\"\"\nAlso, note that for memory management purposes we will not transform the vectors now, but will embedd image generation into the CNN-training pipeline shortly.\n\"\"\"\n\"\"\"\n### CNN Training\n\"\"\"\nimport tensorflow as tf\nimport keras\nfrom keras import backend as K\nfrom keras import models\nfrom keras.models import Model, load_model\nfrom keras import layers\nfrom keras.layers import Dense,Conv2D,MaxPooling2D, Flatten, Input\nfrom keras.layers.core import Dropout\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, classification_report\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\n\n#weight and notops from pretrained models\n!mkdir ~\/.keras\n!mkdir ~\/.keras\/models\n!cp ..\/input\/keras-pretrained-models\/*notop* ~\/.keras\/models\/\n!cp ..\/input\/keras-pretrained-models\/imagenet_class_index.json ~\/.keras\/models\/\n#we will use an InceptionV3 model\nconv_base = keras.applications.InceptionV3(include_top=False,weights='imagenet',input_shape=(80,80,3))\nconv_base.summary()\n\"\"\"\nNext, we create a complete pipeline, from image transform to feature extraction. For memory management we will do it by chunks and then use the features to train a classifier.\n\"\"\"\n#complete pipeline\n# coefficient 'pack_size' determines chunks that will be processed at each iteration\n# too large 'pack_size' puts burden on memory, too small adds time complexity\ndef pipeline(array, conv_base):\n    \n    array = to_image (array)\n    pack_size = 10000\n    first_dim_fract = array.shape[0]\/\/pack_size\n    array = to_rgb(array)\n    features = []\n\n    for i in (np.arange(first_dim_fract)+1):\n        \n        first_index = (i-1)*pack_size\n        second_index = i*pack_size\n        print('chunk of index:{}-{}'.format(first_index,second_index))\n        temp = expand(array[first_index:second_index])\n        temp = conv_base.predict(temp)\n        features.append(temp)\n    \n    return np.reshape(features,(first_dim_fract*pack_size,1, 1, 2048))\n\"\"\"\nNow we'll extract features and train a classifier. We will only use a slice of the data, 300k train samples,and 100k test samples.\n\"\"\"\n#extract features in chunks to manage memory\ntrain_features = pipeline(x_tr[:100000],conv_base)\ntrain_features = np.append(train_features,pipeline(x_tr[100000:200000],conv_base),axis=0)\ntrain_features = np.append(train_features,pipeline(x_tr[200000:300000],conv_base),axis=0)\nnp.save('CICIDS2017_InceptionV3_train_features.npy',train_features)\n#train_features = np.load('.\/CICIDS2017_InceptionV3_train_features.npy')\ntest_features = pipeline(x_ts[:100000],conv_base)\nnp.save('CICIDS2017_InceptionV3_test_features.npy',test_features)\n#test_features = np.load('')\n#reshape to fit classifier\ntrain_features = np.reshape(train_features,(train_features.shape[0],2048))\ntest_features = np.reshape(test_features,(test_features.shape[0],2048))\n#train a classifier with the feature maps of the pretrained keras model\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(256,activation='relu',input_dim=train_features.shape[1]))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nstop= EarlyStopping(patience=4, verbose=1)\n\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics='accuracy')\nmodel.fit(train_features,y_tr,epochs=30,batch_size=20,callbacks=stop,validation_split=0.1)\n#evaluate performance\n\npred = model.predict(test_features)\npred = np.squeeze((pred>0.5).astype(np.uint8))\nprint('accuracy:',accuracy_score(y_ts[:100000],pred))\nprint('f1-score:',f1_score(y_ts[:100000],pred))\nplt.figure(figsize=(9,7));\nconf=confusion_matrix(y_ts[:100000],pred)\nsns.heatmap(conf, annot=True, fmt='1d');\n\"\"\"\n### Conclusion\n\"\"\"\n\"\"\"\nThe capacity of CNNs to work with cross-tabular, non-image data has been underappreciated, but in this project we've shown that CNNs, arguably the most powerful deep learning models, can be harnessed with great results for tasks other than vision and image recognition.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1f8671159fa591'}"}
{"id":"3425","text":"# 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,sys,shutil\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames[:30]:\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\n# Load the libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport seaborn as sns\nimport cv2\nfrom sklearn.model_selection import train_test_split\n# pd.set_option('display.max_colwidth',0)\n# Load the data and url\n\ntrain_url = r'\/kaggle\/input\/age-prediction-dataset-indian-actors\/train\/' \ntest_url = r'\/kaggle\/input\/age-prediction-dataset-indian-actors\/test\/'\n\ntrain_dir = train_url + 'Train\/'\ntest_dir = test_url + 'Test\/'\n\ntrain_data  = pd.read_csv(train_url + 'train.csv') \ntest_data = pd.read_csv(test_url + 'test.csv')\n# Train data\nprint('Shape of the train data - ',train_data.shape)\ntrain_data.head()\n# Manipulating the dataframe\ntrain_data1=train_data.copy()\ntrain_data1['loc'] = train_dir + train_data['ID']\ntrain_data1.head()\n# Show the image present in the data\ndef read_img(data):\n    classes = ['YOUNG',\"MIDDLE\",'OLD']\n    for c in classes:\n            img = plt.imread(data[data['Class']==c].head(1)['loc'].values[0])\n            print('Shape of the image -',img.shape)\n            plt.title(c)\n            plt.imshow(img)\n            plt.show()\nread_img(train_data1)\n# Train Data\ntrain_data1.drop(columns= ['ID'],inplace=True)\ntrain_data1 = train_data1[['loc','Class']].copy()\ntrain_data1.head()\n# Visulaizing the number of images in the particular class\ntrain_data1.groupby('Class').count().plot(kind='bar',figsize=(20,10))\ntrain_data1['Class'].replace(['YOUNG','MIDDLE','OLD'],[0,1,2],inplace=True)\nnew_images = []\nnew_classes = []\nfor img_loc,classes in zip(train_data1['loc'],train_data1['Class']):\n    img = cv2.imread(img_loc,flags=0)\n    img_resize = cv2.resize(img,(32,32))\n    new_images.append(img_resize.astype('float32'))\n    new_classes.append(classes)\n\nplt.imshow(new_images[0])\nplt.title(new_classes[0])\n# Code to Image Data Generator\ngenerator = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=15,\n                                                            horizontal_flip=True,\n                                                            data_format='channels_last')\n\n# generator.flow_from_dataframe() ____________________Please check this one! Exclusive!\n# Train sets\ntrain_x = np.stack(new_images)\ntrain_y = np.stack(new_classes)\n# Splitting the data set\nX_train,X_val,y_train,y_val = train_test_split(train_x,train_y,test_size=0.2,random_state=42)\n\nX_train.shape,y_train.shape,X_val.shape,y_val.shape\n# Manipulating the target values\ny_train = tf.keras.utils.to_categorical(y_train,num_classes=3)\ny_val = tf.keras.utils.to_categorical(y_val,num_classes=3)\n\"\"\"\n# Modeling Part\n\"\"\"\n# Assemble the model components --->>> Keras Framework\nfrom keras import Sequential\nfrom keras.callbacks import EarlyStopping,ModelCheckpoint\nfrom keras import Input,regularizers,optimizers,losses,metrics,layers\nfrom keras import Model,optimizers\nfrom keras.utils import plot_model\nfrom keras.losses import CategoricalCrossentropy\ntrain_x.shape\n\"\"\"\n# Data Augmentation\n\"\"\"\n# Augmentation on the data\ndata_augmentation = Sequential([\n    layers.experimental.preprocessing.RandomFlip('horizontal'),\n    layers.experimental.preprocessing.RandomRotation(0.1)\n])\n\"\"\"\n# Model\n\"\"\"\n# Function for model \ndef model():\n    inputs = Input(shape=(32,32,1))\n    # Data Augmentation\n    x = data_augmentation(inputs)\n    \n    # Entry block\n    x = layers.experimental.preprocessing.Rescaling(1.\/255)(x)\n    x = layers.Conv2D(32,(3,3),(2,2),padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n    x = layers.Conv2D(64,(3,3),(2,2),padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n    \n    residual1 = x\n    \n    for FilterSize in [128,256,512]:\n        x = layers.Activation('relu')(x)\n        x = layers.SeparableConv2D(FilterSize,(3,3),(2,2),padding='same')(x)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation(tf.nn.relu)(x)\n        \n        x = layers.SeparableConv2D(FilterSize,(3,3),(2,2),padding='same')(x)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation(tf.nn.relu)(x)\n        \n        x = layers.MaxPool2D((3,3),(2,2),padding='same')(x)\n        \n        residual = layers.Conv2D(FilterSize,(1,1),(2,2),padding='same')(residual1)\n        \n        x = layers.add([x,residual])\n        \n        FinalResidual = x\n    \n    x = layers.SeparableConv2D(1024,(3,3),(2,2),padding='same')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n    \n    x = layers.Flatten()(x)\n    \n    x = layers.Dropout(0.5)(x)\n    \n    output = layers.Dense(3,activation=tf.nn.softmax)(x)\n    \n    return Model(inputs = inputs,outputs=output)\n\n# Intialize the model\nmodel = model()\n\n# Plot the model architecture\nplot_model(model,show_shapes =True)\n\"\"\"\n## Training the model\n\"\"\"\nepochs = 200\n\ncallbacks = [  \n    ModelCheckpoint(filepath = 'save_at_{epoch}.h5',save_best_only=True),\n    EarlyStopping(monitor='val_loss',patience=20)\n]\n\nmodel.compile(optimizer=optimizers.SGD(0.01,momentum=0.9),\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n# CategoricalCrossentropy()\n\nhistory = model.fit(X_train,y_train,\n          batch_size=32,\n          validation_batch_size=8,\n          validation_data=(X_val,y_val),\n          callbacks=callbacks,epochs=epochs)\n# History plots\nplt.figure(figsize=(10,7))\nplt.plot(history.history['loss'],'b')\nplt.plot(history.history['val_loss'],'r')\nplt.legend(labels = ['loss','val_loss'])\nplt.title('LOSS',fontsize=20)\nplt.show()\nplt.figure(figsize=(10,7))\nplt.plot(history.history['accuracy'],'b')\nplt.plot(history.history['val_accuracy'],'r')\nplt.legend(labels = ['loss','val_loss'])\nplt.title('LOSS',fontsize=20)\nplt.show()\n\"\"\"\n# Test Data\n\"\"\"\n# Test data\ntest_data['loc'] = test_dir+test_data[\"ID\"]\ntest_data1 = test_data['loc'].copy()\ntest_data2 = []\nfor image in test_data1:\n    img = cv2.imread(image,flags=0)\n    img = cv2.resize(img,(32,32))\n    test_data2.append(img.astype('float32'))\n\ntest_data2 = np.stack(test_data2)    \n\"\"\"\n## Predictions on train dataset\n\"\"\"\n#### Train set\n# loc = int(input('Enter the number-'))\nloc = 0\n# test_img = test_data2[loc]\ntest_img = train_x[loc]\nplt.imshow(test_img)\n\nimg_array = tf.keras.preprocessing.image.img_to_array(test_img)\nimg_array = tf.expand_dims(img_array,0)\nimg_array.shape\npredicted = model.predict(img_array)\n\n\n\ndef caption(pred):\n    cap = np.argmax(pred)\n    if cap==0:\n        return 'Young'\n    elif cap==1:\n        return 'Middle'\n    elif cap == 2:\n        return 'Old'# Young=0, Middle=1,Old=2\n    \ncap = caption(predicted[0])\nprint(predicted[0])\nplt.title(cap)\nplt.show()\n\"\"\"\n## Predictions on test Data set\n\"\"\"\n# Test set\n# loc = int(input('Enter the number-'))\nloc = 0\ntest_img = test_data2[loc]\nplt.imshow(test_img)\n\nimg_array = tf.keras.preprocessing.image.img_to_array(test_img)\nimg_array = tf.expand_dims(img_array,0)\nimg_array.shape\npredicted = model.predict(img_array)\n\n\n# Getting the predicted captions of the Image\ndef caption(pred):\n    cap = np.argmax(pred)\n    if cap==0:\n        return 'Young'\n    elif cap==1:\n        return 'Middle'\n    elif cap == 2:\n        return 'Old'# Young=0, Middle=1,Old=2\n    \ncap = caption(predicted[0])\nprint(predicted[0])\nplt.title(cap)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '06700a3840ef3d'}"}
{"id":"52319","text":"\"\"\"\n- First of all, congratulations to all kagglers and thanks to organizers. I have learned a lot from this competition, so I would like to share my solution here. I hope some pepole find new ideas from my solution.\n- I got some ideas from the following great notebooks.  \nhttps:\/\/www.kaggle.com\/yanamal\/learning-factor-analysis-are-tags-skills\/notebook  \nhttps:\/\/www.kaggle.com\/gilfernandes\/riiid-self-attention-transformer  \nhttps:\/\/www.kaggle.com\/its7171\/cv-strategy\n\"\"\"\n# installation without internet\n!pip install ..\/input\/python-datatable\/datatable-0.11.0-cp37-cp37m-manylinux2010_x86_64.whl\n!pip install ..\/input\/pandarallel151whl\/pandarallel-1.5.1-py3-none-any.whl\nimport riiideducation\n\nimport os\nimport gc\nimport cv2\nimport joblib\nimport random\nimport warnings\nimport numpy as np \nimport pandas as pd\nimport datatable as dt\nimport tensorflow as tf \nimport matplotlib.pyplot as plt \nimport seaborn as sns\nfrom tqdm.notebook import tqdm\nfrom datetime import datetime\nfrom IPython.display import display\nfrom pandarallel import pandarallel\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, KFold, TimeSeriesSplit, GroupKFold, GroupShuffleSplit\n\nimport lightgbm as lgb\nimport optuna\nimport optuna.integration.lightgbm as optuna_lgb\nfrom optuna.visualization import plot_optimization_history\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\n\ndef seed_everything(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    session_conf = tf.compat.v1.ConfigProto(\n        intra_op_parallelism_threads=1,\n        inter_op_parallelism_threads=1\n    )\n    sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)\n    tf.compat.v1.keras.backend.set_session(sess)\n\nwarnings.simplefilter('ignore')\npd.set_option(\"max_columns\", 150)\npd.set_option('display.max_rows', 150)\nseed_everything(42)\npandarallel.initialize()\ndef get_deviation_value(ans_cor_rate, std, method=\"p\"):\n    if method == \"p\":\n        return (1-ans_cor_rate)*(std\/1.5+1)\n    else:\n        return (ans_cor_rate)*(std\/1.5+1)\n\ndev_vals = []\nfor a in np.arange(0,1.01,0.1):\n    a = round(a,1)\n    for s in np.arange(0, 1.501, 0.1):\n        s = round(s,1)\n        dev_vals.append([a, s, round(get_deviation_value(a,s),1)])\n\nplt.plot(np.array(dev_vals)[:,2])\ndef reduce_mem_usage(df, verbose=True, y=[]):\n    numerics  = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() \/ 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col in y or col_type not in numerics:\n            continue\n        c_min = df[col].min()\n        c_max = df[col].max()\n        if str(col_type)[:3] == 'int':\n            if   c_min > np.iinfo(np.int8).min  and c_max < np.iinfo(np.int8).max:\n                df[col] = df[col].astype(np.int8)\n            elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                df[col] = df[col].astype(np.int16)\n            elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                df[col] = df[col].astype(np.int32)\n            elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                df[col] = df[col].astype(np.int64)  \n        else:\n            if   c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                df[col] = df[col].astype(np.float16)\n            elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                df[col] = df[col].astype(np.float32)\n            else:\n                df[col] = df[col].astype(np.float64)\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    if verbose:\n        print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) \/ start_mem))\n    return df\n\ndef showStats(df):\n    stats = []\n    for col in df.columns:\n        stats.append((col,\n                      df[col].nunique(),\n                      df[col].value_counts().index[0],\n                      df[col].value_counts().values[0],\n                      df[col].isnull().sum() * 100 \/ df.shape[0],\n                      df[col].value_counts(normalize=True, dropna=False).values[0] * 100,\n                      df[col].dtype))\n    df_stats = pd.DataFrame(stats, columns=['Feature name', 'Unique values', 'Most frequent item', 'Freuquence of most frequent item',\n                                            'Missing values(%)', 'Values in the biggest category(%)', 'Type'])\n    display(df_stats)\n# You can only call make_env() once, so don't lose it!\nenv = riiideducation.make_env()\n#=========================\nDEBUG     = False\nTUNE      = False\nENSEMBLE  = True\nS         = 0.3\nL         = 0.7\n#=========================\n\"\"\"\n# Load data\n\"\"\"\n%%time\ntrain   = reduce_mem_usage(dt.fread(\"..\/input\/riiid-test-answer-prediction\/train.csv\").to_pandas())\ndf_qs   = reduce_mem_usage(pd.read_csv('..\/input\/riiid-test-answer-prediction\/questions.csv'))\ndf_lecs = reduce_mem_usage(pd.read_csv('..\/input\/riiid-test-answer-prediction\/lectures.csv'))\nprint(train.shape, df_qs.shape, df_lecs.shape)\ndisplay(train.head(2))\ndisplay(df_qs.head(2))\ndisplay(df_lecs.head(2))\n# Modify some features\ntrain.prior_question_elapsed_time    = (train.prior_question_elapsed_time.fillna(0)).astype(int)\ntrain.prior_question_had_explanation = (train.prior_question_had_explanation.fillna(False) * 1).astype(int)\ntrain.content_type_id                = (train.content_type_id * 1).astype(int)\ntrain = reduce_mem_usage(train)\n# Split to qa data and lecture data\ntrain_lec = train.query(\"content_type_id==1\").copy()\ntrain_lec.reset_index(drop=True, inplace=True)\n\ntrain.drop(train.loc[train.content_type_id==1].index, inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n\n# Rename to question_id\ntrain    .rename(columns={\"content_id\": \"question_id\"}, inplace=True)\ntrain_lec.rename(columns={\"content_id\": \"question_id\"}, inplace=True)\n\ngc.collect()\ntrain.shape, train_lec.shape\n\"\"\"\n# Feature enginnering\n\"\"\"\ndef intervaled_cumsum(ar, idx):\n    # Make a copy to be used as output array\n    out = ar.copy()\n    # Get cumumlative values of array\n    arc = ar.cumsum()\n    # Place differentiated values that when cumumlatively summed later on would\n    # give us the desired intervaled cumsum\n    out[idx[0]]    = ar[idx[0]] - arc[idx[0]-1]\n    out[idx[1:-1]] = ar[idx[1:-1]] - np.diff(arc[idx[:-1]-1])\n    return out.cumsum()\n\ndef shift_to_prior(ary, sizes_cumsum):\n    shifted = np.r_[np.array([0]), ary]\n    shifted[sizes_cumsum] = 0\n    return shifted[:-1]\n\ndef get_hist_and_training_data(ary):\n    return ary[sizes_qcumsum-1], ary[ext_user_bol]    \ndef cut(df, t_col, n_col):\n    df = df.copy()\n    df[n_col] = pd.cut(df[t_col], [-0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1], labels=False)\n    df[n_col] = df[n_col].fillna(99).astype(\"int8\")\n    return df\n\ndef add_que_rate_class(df):\n    df = df.copy()\n    df[\"question_rate_class\"] = 0\n    for sta, end in zip(np.arange(0.3, 1.0, 0.1), np.arange(0.4, 1.1, 0.1)):\n        sta = round(sta,1)\n        end = round(end,1)\n        end = 1.1 if end==1 else end\n        df.loc[(sta <= df.question_rate)&(df.question_rate < end), \"question_rate_class\"] = int(sta*10)\n    return df\n\ndef get_user_items_dict(ary, sizes_cumsum):\n    end   = sizes_cumsum\n    sta   = np.hstack([np.array([0]), end[:-1]])\n    users = np.unique(ary[:,0])\n\n    d = {}\n    for u, s, e in zip(users, sta, end):\n        d[u] = ary[s:e, 1:]\n    return d\n\ndef change_rate_with_num(df, t_col, n_col, method=\"respectively\", n1=5, n2=3):\n    df = df.copy()\n    if method == \"respectively\":\n        df.loc[(df[n_col] < n1)&(df[t_col] <= 0.3), t_col] = 0.3\n        df.loc[(df[n_col] < n1)&(0.3 < df[t_col])&(df[t_col] <= 0.7), t_col] = 0.5\n        df.loc[(df[n_col] < n1)&(0.7 < df[t_col]),  t_col] = 0.7\n    else:\n        df.loc[(df[n_col] < n2), t_col] = 0.5\n    return df\n\ndef change_rate_high_low(df, t_col, h=0.9, l=0.1):\n    df = df.copy()\n    df.loc[df[t_col] < l, t_col] = l\n    df.loc[df[t_col] > h, t_col] = h\n    return df\n# Define some parameters for training models\nCV           = 4\nMODEL_NUM    = 1\nUSE_USER_NUM = 10000\nif DEBUG:\n    USE_USER_NUM  = 500\nif TUNE:\n    TRAIN_RATE, TUNE_RATE, TEST_RATE = 0.4, 0.3, 0.3\nelse:\n    TRAIN_RATE, TEST_RATE = 0.7, 0.3\n    \nprint(\"%s users reduce to %s\" % (train.user_id.nunique(), USE_USER_NUM))\nuser_ids     = train.user_id.unique()\n# Random shuffle\nrandom.shuffle(user_ids)\n# Get user ids for training and test\next_user     = user_ids[:USE_USER_NUM]\next_user_bol = np.isin(np.array(train.user_id), np.sort(ext_user))\n\n# Get the number of user row\nsizes_quser     = np.array(train.user_id.value_counts().sort_index().values, dtype=\"int16\")\nsizes_qcumsum   = sizes_quser.cumsum()\n# Get unique user ids\nunique_user_ids = np.array(train.user_id)[sizes_qcumsum-1]\n# Caluculate elapsed time stats\ndf_etime = pd.DataFrame({\"question_id\"                : np.array(train.question_id[:-1]),\n                         \"prior_question_elapsed_time\": np.array(train.prior_question_elapsed_time[1:])})\ndf_etime = df_etime.loc[df_etime.prior_question_elapsed_time!=0].copy()\ndf_etime.prior_question_elapsed_time = df_etime.prior_question_elapsed_time \/ (1000*3600)\ndf_etime[\"etime_kurt\"] = df_etime.prior_question_elapsed_time\ndf_etime[\"etime_std\"]  = df_etime.prior_question_elapsed_time\ndf_etime[\"etime_skew\"] = df_etime.prior_question_elapsed_time\ndf_etime_kurt = df_etime.groupby(\"question_id\", as_index=False).etime_kurt.apply(pd.DataFrame.kurt)\ndf_etime_rate = df_etime.groupby(\"question_id\", as_index=False).agg({\"prior_question_elapsed_time\": \"mean\",\n                                                                     \"etime_std\" : \"std\",\n                                                                     \"etime_skew\": \"skew\"})\ndf_etime_rate.rename(columns={\"prior_question_elapsed_time\": \"etime_mean\"}, inplace=True)\ndf_etime_rate = df_etime_rate.merge(df_etime_kurt, on=\"question_id\")\ndf_etime_rate.fillna(0, inplace=True)\ndf_etime_rate.question_id = df_etime_rate.question_id.astype(\"int32\")\ndf_etime_rate.etime_mean  = df_etime_rate.etime_mean .astype(\"float32\")\ndf_etime_rate.etime_std   = df_etime_rate.etime_std  .astype(\"float32\")\ndf_etime_rate.etime_kurt  = df_etime_rate.etime_kurt .astype(\"float32\")\ndf_etime_rate.etime_skew  = df_etime_rate.etime_skew .astype(\"float32\")\n\n# Make dictionary for prediction phase\nd_etime = dict(zip(df_etime_rate.question_id, df_etime_rate.etime_mean))\n\ndel df_etime, df_etime_kurt\ngc.collect()\n\nprint(df_etime_rate.shape)\ndf_etime_rate.head(2)\n# Calculate the difference between a user elapsed time and the average elapsed time\ndf_etmie_rate = train[[\"row_id\",\"user_id\",\"question_id\",\"prior_question_elapsed_time\"]].copy()\ndf_etmie_rate.rename(columns={\"prior_question_elapsed_time\":\"lag_etime\"}, inplace=True)\ndf_etmie_rate.lag_etime = df_etmie_rate.lag_etime \/ (1000*3600)\ndf_etmie_rate.lag_etime = df_etmie_rate.groupby(\"user_id\").lag_etime.shift(-1)\ndf_etmie_rate = df_etmie_rate.merge(df_etime_rate[[\"question_id\",\"etime_mean\"]], on=\"question_id\")\ndf_etmie_rate.lag_etime = df_etmie_rate.lag_etime - df_etmie_rate.etime_mean\ndf_etmie_rate.sort_values(\"row_id\", inplace=True)\ndf_etmie_rate.reset_index(drop=True, inplace=True)\n\n# Calculate elapsed time rate\ndf_etmie_rate[\"num\"]        = 1\ndf_etmie_rate[\"num\"]        = df_etmie_rate.groupby(\"user_id\").num.shift(1)\ndf_etmie_rate[\"num\"]        = df_etmie_rate.groupby(\"user_id\").num.cumsum()\ndf_etmie_rate[\"num_etime\"]  = df_etmie_rate.groupby(\"user_id\").lag_etime.shift(1)\ndf_etmie_rate[\"num_etime\"]  = df_etmie_rate.groupby(\"user_id\").num_etime.cumsum()\ndf_etmie_rate[\"etime_rate\"] = df_etmie_rate.num_etime \/ df_etmie_rate.num\ndf_etmie_rate.fillna(0, inplace=True)\n\n# Save memory\ndf_etmie_rate.num_etime  = df_etmie_rate.num_etime .astype(\"float32\")\ndf_etmie_rate.etime_rate = df_etmie_rate.etime_rate.astype(\"float32\")\ndf_etmie_rate.drop([\"row_id\",\"user_id\",\"question_id\",\"lag_etime\",\"etime_mean\",\"num\"], axis=1, inplace=True)\n\nprint(df_etmie_rate.shape)\ndisplay(df_etmie_rate.head(3))\n\n# Store for history and training\nar_etmie_rate = np.array(df_etmie_rate)\nhist_ar_etmie_rate, ar_etmie_rate = get_hist_and_training_data(ar_etmie_rate)\nhist_ar_etmie_rate, ar_etmie_rate = hist_ar_etmie_rate[:,0], ar_etmie_rate[:,1]\n\ndel df_etmie_rate\ngc.collect()\n# Run a one hot encoding for lecture features\ndf_lecs = df_lecs.join(pd.DataFrame(pd.get_dummies(df_lecs.type_of)))\ndf_lecs.rename(columns={\"lecture_id\"      :\"question_id\",\n                        \"solving question\":\"solving_question\"}, inplace=True)\ndf_lecs.drop([\"tag\",\"type_of\"], axis=1, inplace=True)\ndf_lecs = reduce_mem_usage(df_lecs)\n\n# Make tag features and merge with question dataframe\ntags     = sum(df_qs.tags.apply(lambda x: [] if x is np.nan else x.split(\" \")), [])\ndf_tags  = pd.DataFrame(pd.Series(tags).value_counts(), columns=[\"tag\"])\ntags_num = df_tags.to_dict()[\"tag\"]\ndf_tags.reset_index(inplace=True)\ndf_tags.columns  = [\"tag\",\"num\"]\ndf_tags[\"total\"] = df_qs.shape[0]\ndf_tags[\"tfidf\"] = 1 * np.log(df_tags.total \/ df_tags.num)  # TF is always 1\ndf_tags.index = df_tags.tag\ntags_tfidf    = df_tags[[\"tfidf\"]].to_dict()[\"tfidf\"]\ndf_tags = pd.DataFrame(list(df_qs.tags.apply(lambda x: [] if x is np.nan else x.split(\" \"))),\n                       columns=[\"tag\"+str(t) for t in range(1,7)])\ndf_tags = df_tags.fillna(0).astype(\"int16\")\ndf_tags = df_qs[[\"question_id\"]].join(df_tags)\ndf_qs[\"tag_rel\"]       = df_qs.tags.apply(lambda x: 0 if x is np.nan else sum([tags_num[t]   for t in x.split(\" \")]))\ndf_qs[\"tag_tfidf_sum\"] = df_qs.tags.apply(lambda x: 0 if x is np.nan else sum([tags_tfidf[t] for t in x.split(\" \")]))\n#df_qs[\"tag_tfidf_max\"] = df_qs.tags.apply(lambda x: 0 if x is np.nan else max([tags_tfidf[t] for t in x.split(\" \")]))\n#df_qs[\"tag_tfidf_min\"] = df_qs.tags.apply(lambda x: 0 if x is np.nan else min([tags_tfidf[t] for t in x.split(\" \")]))\ndf_qs[\"num_tag\"]       = df_qs.tags.apply(lambda x: 0 if x is np.nan else len(x.split(\" \")))\ndf_qs.drop([\"correct_answer\",\"tags\"], axis=1, inplace=True)\ndf_qs = df_qs.merge(df_tags, on=\"question_id\")\ndf_qs = reduce_mem_usage(df_qs)\n\ndel df_tags, tags_num, tags_tfidf\ngc.collect()\n\nprint(df_lecs.shape, df_qs.shape)\ndisplay(df_lecs.head(2))\ndisplay(df_qs.head(2))\n# Merge with question dataframe\ntrain = train.merge(df_qs[[\"question_id\",\"bundle_id\",\"part\",\"tag1\"]], on='question_id', how='left')\ntrain = reduce_mem_usage(train)\n# Calculate answering stats for each question and explanation\ndf_que_exp_rate = train[[\"question_id\",\"prior_question_had_explanation\",\"answered_correctly\"]].copy()\ndf_que_exp_rate[\"cnt\"] = 1\ndf_que_exp_rate = df_que_exp_rate.groupby([\"question_id\",\"prior_question_had_explanation\"], as_index=False).agg({\"answered_correctly\":\"mean\", \"cnt\":\"count\"})\ndf_que_exp_rate.rename(columns={\"answered_correctly\":\"question_rate\"}, inplace=True)\ndf_que_exp_rate = change_rate_with_num(df_que_exp_rate, \"question_rate\", \"cnt\", n1=20)\ndf_que_exp_rate = change_rate_with_num(df_que_exp_rate, \"question_rate\", \"cnt\", method=\"bundle\", n2=5)\ndf_que_exp_rate.drop(\"cnt\", axis=1, inplace=True)\n# Merge with base dataframe\ndf_que_exp_base = pd.DataFrame({\"question_id\":                    np.repeat(np.array(df_qs.question_id), 2),\n                                \"prior_question_had_explanation\": np.tile([0,1], df_qs.shape[0])})\ndf_que_exp_rate = df_que_exp_base.merge(df_que_exp_rate, on=[\"question_id\",\"prior_question_had_explanation\"], how=\"left\")\ndf_que_exp_rate.fillna(0.5, inplace=True)\ndf_que_exp_rate = add_que_rate_class(df_que_exp_rate)\ndf_que_exp_rate.question_rate       = df_que_exp_rate.question_rate.astype(\"float32\")\ndf_que_exp_rate.question_rate_class = df_que_exp_rate.question_rate_class.astype(\"int8\")\ndf_que_exp_rate = reduce_mem_usage(df_que_exp_rate)\n\nprint(df_que_exp_rate.shape)\ndf_que_exp_rate.head(2)\n# Calculate answering stats for each question and bundle id\ndf = train[[\"user_id\",\"question_id\",\"bundle_id\",\"user_answer\",\"answered_correctly\"]].copy()\ndf_question_rate = df_qs[[\"question_id\",\"bundle_id\"]].copy()\nfor c in [\"question_id\", \"bundle_id\"]:\n    c_name  = c[:-3]\n    df[c_name+\"_kurt\"] = df.user_answer\n    df[c_name+\"_skew\"] = df.user_answer\n    df_kurt = df.groupby(c, as_index=False)[c_name+\"_kurt\"].apply(pd.DataFrame.kurt)\n    df_rate = df.groupby(c, as_index=False).agg({\"answered_correctly\": \"mean\",\n                                                 \"user_answer\"       : \"std\",\n                                                 c_name+\"_skew\"      : \"skew\"})\n    df_rate.rename(columns={\"answered_correctly\":c_name+\"_rate\",\n                            \"user_answer\"       :c_name+\"_std\"}, inplace=True)\n    df_rate = df_rate.merge(df_kurt, on=c)\n    df_question_rate = df_question_rate.merge(df_rate, on=c, how=\"left\")\n    df_question_rate.fillna(0, inplace=True)\n    \n# Rate 0 question will be replaced to second min value\nmin2_val = sorted(df_question_rate.question_rate.unique())[1]\nins_row  = df_question_rate[df_question_rate.question_rate == min2_val].iloc[:,2:]\ndf_question_rate.loc[df_question_rate.question_rate == 0, ins_row.columns] = ins_row.values\n\n# Add deviation calculated by mean and std\ndf_question_rate[\"deviation_p\"] = df_question_rate[[\"question_rate\",\"question_std\"]].apply(lambda x: get_deviation_value(x[0],x[1], \"p\"), axis=1)\ndf_question_rate[\"deviation_m\"] = df_question_rate[[\"question_rate\",\"question_std\"]].apply(lambda x: get_deviation_value(x[0],x[1], \"m\"), axis=1)\n# Add question rate class\ndf_question_rate = add_que_rate_class(df_question_rate)\ndf_question_rate.bundle_id           = df_question_rate.bundle_id.astype(\"int16\")\ndf_question_rate.question_rate_class = df_question_rate.question_rate_class.astype(\"int8\")\ndf_question_rate = reduce_mem_usage(df_question_rate)\n\n# Calculate answering stats for each part\ndf_part_rate = train.groupby(\"part\", as_index=False).answered_correctly.mean()\ndf_part_rate.rename(columns={\"answered_correctly\": \"part_rate\"}, inplace=True)\ndf_part_rate = reduce_mem_usage(df_part_rate)\n\ndel df, df_kurt, df_rate, min2_val, ins_row\ngc.collect()\n\nprint(df_question_rate.shape, df_part_rate.shape)\ndisplay(df_question_rate.head(2))\ndisplay(df_part_rate.head(2))\ndf_question_rate = df_question_rate.merge(df_que_exp_rate, on=\"question_id\", suffixes=(\"\", \"_exp\"))\n\ndel df_que_exp_rate\ngc.collect()\nfig, axes = plt.subplots(nrows=2, ncols=3, figsize=(13, 5))\ndf_question_rate.question_rate.hist(ax=axes[0,0])\ndf_question_rate.question_std .hist(ax=axes[0,1])\ndf_question_rate.question_skew.hist(ax=axes[0,2])\ndf_question_rate.question_kurt.hist(ax=axes[1,0])\ndf_question_rate.deviation_p  .hist(ax=axes[1,1])\ndf_part_rate.part_rate        .plot(ax=axes[1,2])\n# Merge with DataFrame for caluculating answer rate and deviation\ntrain = train.merge(df_question_rate[[\"question_id\",\"prior_question_had_explanation\",\"question_rate_exp\",\"deviation_p\",\"deviation_m\"]],\n                    on=[\"question_id\",\"prior_question_had_explanation\"])\n\n# Sort to original order\ntrain.sort_values(by=\"row_id\", inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n# Calculate correct answer rate and deviation for each user\nans  = np.array(train.answered_correctly, dtype=\"int16\")\nnum  = np.ones (train.shape[0], dtype=\"int16\")\nexp  = np.array(train.prior_question_had_explanation, dtype=\"int16\")\ndevp = ans  * np.array(train.deviation_p, dtype=\"float64\")\ndevm = devp + np.where(ans==0, -1, 0) * np.array(train.deviation_m, dtype=\"float64\")\n\nans_cumsum  = intervaled_cumsum(ans,  sizes_qcumsum).astype(\"int16\")\nnum_cumsum  = intervaled_cumsum(num,  sizes_qcumsum).astype(\"int16\")\nexp_cumsum  = intervaled_cumsum(exp,  sizes_qcumsum).astype(\"int16\")\ndevp_cumsum = intervaled_cumsum(devp, sizes_qcumsum).astype(\"float32\")\ndevm_cumsum = intervaled_cumsum(devm, sizes_qcumsum).astype(\"float32\")\nans_rate    = (ans_cumsum \/ num_cumsum).astype(\"float32\")\nstudy_rate  = (exp_cumsum \/ shift_to_prior(num_cumsum, sizes_qcumsum)).astype(\"float32\")\nstudy_rate[np.isnan(study_rate)] = 0\nstudy_rate[np.isinf(study_rate)] = 0\n\n# Store for history and training\nhist_ans_cumsum,  ans_cumsum  = get_hist_and_training_data(ans_cumsum)\nhist_num_cumsum,  num_cumsum  = get_hist_and_training_data(num_cumsum)\nhist_exp_cumsum,  exp_cumsum  = get_hist_and_training_data(exp_cumsum)\nhist_devp_cumsum, devp_cumsum = get_hist_and_training_data(devp_cumsum)\nhist_devm_cumsum, devm_cumsum = get_hist_and_training_data(devm_cumsum)\nhist_ans_rate,    ans_rate    = get_hist_and_training_data(ans_rate)\nhist_study_rate,  _           = get_hist_and_training_data(study_rate)\n\ntrain.drop([\"deviation_p\",\"deviation_m\"], axis=1, inplace=True)\ndel ans, num, exp, devp, devm\ngc.collect()\n%%time\n# Make column names to merge with train later\nnum_part_cols  = [\"num_part\"+str(p)     for p in range(1,8)]\nans_part_cols  = [\"ans_part\"+str(p)     for p in range(1,8)]\npart_rate_cols = [\"part\"+str(p)+\"_rate\" for p in range(1,8)]\npart_cols      = ans_part_cols + num_part_cols\n\n# Make cumsum array for each part\nar_part_num  = np.array(pd.get_dummies(train.part))\nar_part_ans  = ar_part_num * np.array(train.answered_correctly).reshape(-1,1)\nar_part      = np.hstack([ar_part_ans, ar_part_num]).astype(\"int16\")\ndel ar_part_num, ar_part_ans\ngc.collect()\n\n# Calculate correct answer rate for each part\nfor i in range(ar_part.shape[1]):\n    ar_part[:,i] = intervaled_cumsum(ar_part[:,i], sizes_qcumsum)\nar_part_rate = (ar_part[:,:7] \/ ar_part[:,7:]).astype(\"float32\")\nnp.nan_to_num(ar_part_rate, copy=False)\n\n# Store for history and training\nhist_ar_part_rate, _  = get_hist_and_training_data(ar_part_rate)\nhist_ar_part, ar_part = get_hist_and_training_data(ar_part)\n# Calculate answering ability for each question difficulty\nabi_cols      = []\nabi_rate_cols = []\nfor sta, end in zip([0.0] + list(np.arange(0.3, 1.0, 0.1)),\n                    [0.3] + list(np.arange(0.4, 1.1, 0.1))):\n    sta = round(sta,1)\n    end = round(end,1)\n    abi_cols      += [\"ans_abi\" +str(int(sta*10)), \"num_abi\"+str(int(sta*10))]\n    abi_rate_cols += [\"abi_rate\"+str(int(sta*10))]\n    end = 1.1 if end == 1 else end\n    print(\"Target question rate is from %s to %s\" % (sta, end))\n    \n    # Replace the ranged data to 0\n    df_ability = train[[\"answered_correctly\",\"question_rate_exp\"]].copy()\n    df_ability[\"num\"] = 1\n    df_ability.loc[(df_ability[\"question_rate_exp\"] <= sta)|(end < df_ability[\"question_rate_exp\"]), [\"answered_correctly\",\"num\"]] = 0\n    abians = np.array(df_ability.answered_correctly, dtype=\"int16\")\n    abinum = np.array(df_ability.num, dtype=\"int16\")\n    del df_ability\n    gc. collect()\n    \n    # Calculate cumsum\n    abians_cumsum = intervaled_cumsum(abians, sizes_qcumsum).astype(\"int16\")\n    abinum_cumsum = intervaled_cumsum(abinum, sizes_qcumsum).astype(\"int16\")\n    del abians, abinum\n    gc. collect()\n    \n    # Store for history and training\n    abians_num = np.array([abians_cumsum, abinum_cumsum]).T\n    hist_abians_num, abians_num = get_hist_and_training_data(abians_num)\n    if sta == 0:\n        hist_ar_ability = hist_abians_num\n        ar_ability      = abians_num\n    else:\n        hist_ar_ability = np.hstack([hist_ar_ability, hist_abians_num])\n        ar_ability      = np.hstack([ar_ability,      abians_num])\n    del abians_cumsum, abinum_cumsum, abians_num, hist_abians_num\n    gc. collect()\n    \n# Sort to ans -> num order\nabi_cols        = sorted(abi_cols)\nabi_rate_cols   = sorted(abi_rate_cols)\nhist_ar_ability = np.hstack([hist_ar_ability[:,::2], hist_ar_ability[:,1::2]])\nar_ability      = np.hstack([ar_ability[:,::2],      ar_ability[:,1::2]])\n# Make correct answer rate classes(i.e. class 0 is based on from 0 to 0.1)\nar_class = np.hstack([unique_user_ids.reshape(-1,1),\n                      hist_num_cumsum.reshape(-1,1),\n                      hist_ans_rate  .reshape(-1,1),\n                      hist_study_rate.reshape(-1,1),\n                      hist_ar_part[:,7:],\n                      hist_ar_part_rate])\ndf_class = pd.DataFrame(ar_class, columns=[\"user_id\",\"num_que\",\"ans_rate\",\"study_rate\"]+num_part_cols+part_rate_cols)\ndel ar_class, hist_ans_rate, hist_study_rate, hist_ar_part_rate\ngc.collect()\n\n# The rates that the number of answering is small will replace to Nan\ndf_class.loc[df_class.num_que < 5, [\"ans_rate\",\"study_rate\"]] = np.nan\nfor p in range(1,8):\n    df_class.loc[df_class[\"num_part\"+str(p)] < 5, \"part\"+str(p)+\"_rate\"] = np.nan\n\n# Make classes and calculate correct answer rate based on them\ndf_class = cut(df_class, \"ans_rate\",   \"ans_class\")\ndf_class = cut(df_class, \"study_rate\", \"study_class\")\nfor p in range(1,8):\n    df_class = cut(df_class, \"part\"+str(p)+\"_rate\", \"part\"+str(p)+\"_class\")\n    \n# Save memory\ndf_class.user_id    = df_class.user_id.astype(\"int32\")\ndf_class.ans_rate   = df_class.ans_rate.astype(\"float32\")\ndf_class.study_rate = df_class.study_rate.astype(\"float32\")\ndf_class = df_class[[\"user_id\"] + [c for c in df_class.columns if -1 < c.find(\"class\")]]\ndf_class = reduce_mem_usage(df_class)\n\nprint(df_class.shape)\ndf_class.head()\n%%time\ndef make_rate_class(df, m_col):\n    df_rc = df.groupby([m_col, \"question_id\"], as_index=False).agg(aggs)\n    df_rc = df_rc.loc[df_rc[m_col] != 99].copy()\n    df_rc = change_rate_with_num(df_rc, \"ans_rate_class\", \"ans_cnt\")\n    df_rc.drop(\"ans_cnt\", axis=1, inplace=True)\n    return reduce_mem_usage(df_rc)\n\ndf_ans_class = train[[\"user_id\",\"question_id\",\"answered_correctly\"]].merge(df_class, on=\"user_id\")\ndf_ans_class[\"ans_cnt\"] = df_ans_class.answered_correctly\ndf_ans_class.rename(columns={\"answered_correctly\": \"ans_rate_class\"}, inplace=True)\ndel df_class\ngc.collect()\n\n# Make dataframe that grouped by each class feature\n# Answer rate that the number of answering is so small will be changed to 0.3\/0.5\/0.7\ndf_parts = []\naggs     = {\"ans_rate_class\":\"mean\", \"ans_cnt\":\"count\"}\ndf_ans_rate_class   = make_rate_class(df_ans_class, \"ans_class\")\ndf_study_rate_class = make_rate_class(df_ans_class, \"study_class\")\ndf_study_rate_class.rename(columns={\"ans_rate_class\":\"study_rate_class\"}, inplace=True)\nfor p in range(1,8):\n    df_part_rate_class = make_rate_class(df_ans_class, f\"part{p}_class\")\n    df_part_rate_class.rename(columns={\"ans_rate_class\":f\"part{p}_rate_class\"}, inplace=True)\n    df_parts.append(df_part_rate_class)\n        \n# Merge with all dataframes\nlo = [\"base_class\",\"question_id\"]\ndf_ans_class = pd.DataFrame({\"base_class\" : np.repeat(np.arange(0,10), df_qs.question_id.nunique()),\n                             \"question_id\": np.tile  (df_qs.question_id.unique(), 10)})\ndf_ans_class = df_ans_class.merge(df_ans_rate_class, left_on=lo, right_on=[\"ans_class\", \"question_id\"], how=\"left\")\ndf_ans_class.drop(\"ans_class\", axis=1, inplace=True)\ndel df_ans_rate_class\n\ndf_ans_class = df_ans_class.merge(df_study_rate_class, left_on=lo, right_on=[\"study_class\", \"question_id\"], how=\"left\")\ndf_ans_class.drop(\"study_class\", axis=1, inplace=True)\ndel df_study_rate_class\n\nfor p, df in enumerate(df_parts):\n    df_ans_class = df_ans_class.merge(df, left_on=lo, right_on=[f\"part{p+1}_class\",\"question_id\"], how=\"left\")\n    df_ans_class.drop(f\"part{p+1}_class\", axis=1, inplace=True)\ndel df_parts\n\n# Modify\ndf_ans_class.fillna(0.5, inplace=True)\ndf_ans_class = reduce_mem_usage(df_ans_class)\n\ngc.collect()\n\nprint(df_ans_class.shape)\ndf_ans_class.head()\nc = 5; r = 2; u = 0\nfig, axes = plt.subplots(nrows=r, ncols=c, figsize=(13, 6))\n\nfor _r in range(r):\n    for _c in range(c):\n        if 9 < u: continue\n        df_ans_class.loc[df_ans_class.base_class==u].ans_rate_class.hist(ax=axes[_r,_c])\n        u += 1\ndel fig, axes\ngc.collect()\nc = 5; r = 2; u = 0\nfig, axes = plt.subplots(nrows=r, ncols=c, figsize=(13, 6))\n\nfor _r in range(r):\n    for _c in range(c):\n        if 9 < u: continue\n        df_ans_class.loc[df_ans_class.base_class==u].study_rate_class.hist(ax=axes[_r,_c])\n        u += 1\ndel fig, axes\ngc.collect()\nc = 5; r = 2; u = 0\nfig, axes = plt.subplots(nrows=r, ncols=c, figsize=(13, 6))\n\nfor _r in range(r):\n    for _c in range(c):\n        if 9 < u: continue\n        df_ans_class.loc[df_ans_class.base_class==u].part7_rate_class.hist(ax=axes[_r,_c])\n        u += 1\ndel fig, axes\ngc.collect()\n# Saved memory concat\nadd_a_cols = [c for c in train_lec.columns if c not in train.columns]\nadd_b_cols = [c for c in train.columns if c not in train_lec.columns]\nfor c in add_a_cols: train[c]     = 0\nfor c in add_b_cols: train_lec[c] = 0\ntrain_lec = train_lec[train.columns]\ntrain_lec = reduce_mem_usage(train_lec)\ntrain     = reduce_mem_usage(train)\ntrain     = reduce_mem_usage(pd.concat([train, train_lec]))\n\ndel train_lec\ngc.collect()\n\n# Sort to original order\ntrain.sort_values(by=\"row_id\", inplace=True)\ntrain.reset_index(drop=True, inplace=True)\ntrain.shape\n# Store all timestamps for calculating the gap of continuous\nsizes_all_user   = np.array(train.user_id.value_counts().sort_index().values, dtype=\"int16\")\nsizes_all_cumsum = sizes_all_user.cumsum()\n\nt_ary       = np.array(train[[\"user_id\",\"timestamp\"]])\nd_timestamp = get_user_items_dict(t_ary, sizes_all_cumsum)\nfor key, item in d_timestamp.items():\n    d_timestamp[key] = np.unique(item)\n\ndel t_ary\ngc.collect()\n# Remove lecture rows and some columns\ntrain.drop([\"bundle_id\",\"question_rate_exp\",\"user_answer\"], axis=1, inplace=True)\ntrain.drop(train.loc[train.content_type_id==1].index, inplace=True)\ntrain.drop([\"content_type_id\"], axis=1, inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n\n# Make Listening(0) and Reading(1)\ntrain[\"LorR\"] = 0\ntrain.loc[train.part.isin([5,6,7]), \"LorR\"] = 1\n\ntrain = reduce_mem_usage(train)\n# Store latest data for prediction of real world data\nar_history = np.hstack([unique_user_ids.reshape(-1,1),\n                        hist_ans_cumsum.reshape(-1,1),\n                        hist_num_cumsum.reshape(-1,1),\n                        hist_exp_cumsum.reshape(-1,1),\n                        hist_devp_cumsum.reshape(-1,1),\n                        hist_devm_cumsum.reshape(-1,1),\n                        hist_ar_etmie_rate.reshape(-1,1),\n                        hist_ar_part,\n                        hist_ar_ability])\ndf_history = pd.DataFrame(ar_history, columns=[\"user_id\",\"num_ans\",\"num_que\",\"num_exp\",\"num_devp\",\"num_devm\",\"num_etime\"]+part_cols+abi_cols)\nfor c in df_history.columns:\n    if c not in [\"num_devp\",\"num_devm\",\"num_etime\"]:\n        df_history[c] = df_history[c].astype(int)\ndf_history = reduce_mem_usage(df_history)\ndf_history.sort_values(by=\"user_id\", inplace=True)\ndf_history.reset_index(drop=True, inplace=True)\n\ndel hist_ans_cumsum, hist_num_cumsum, hist_exp_cumsum, hist_devp_cumsum, hist_devm_cumsum, hist_ar_etmie_rate, hist_ar_part, hist_ar_ability\ngc.collect()\n\nprint(df_history.shape)\ndf_history.head()\nprint(train.shape)\ntrain.head()\n\"\"\"\n# Make training data\n\"\"\"\ndef get_attempt_que(u, r, q):\n    # u: user_id\n    # r: row_id\n    # q: question_id\n    if u in d.keys():\n        ua = d[u]\n        return np.count_nonzero((ua[:,0] < r) * (ua[:,1] == q))\n    return 0\n\ndef get_attempt_curt_part(u, r, p):\n    # u: user_id\n    # r: row_id\n    # p: part\n    if u in d.keys():\n        ua = d[u]\n        return np.count_nonzero(ua[ua[:,0]<r][-5:,2] == p)\n    return 0\n\ndef get_attempt_tags(u, r, t):\n    # u: user_id\n    # r: row_id\n    # t: tags\n    if u in d.keys():\n        ua = d[u]\n        return np.count_nonzero((ua[:,0] < r) * (ua[:,3] == t))\n    return 0\n\ndef get_attempt_curt_ans_rate(u, r):\n    # u : user_id\n    # r : row_id\n    if u in d.keys():\n        ua = d[u]\n        return np.mean(ua[ua[:,0]<r][-10:, 4])\n    return 0\n\ndef get_lagtime(u, t, l):\n    # u: user_id\n    # t: timestamp\n    # l: lag(-1 is lag1, -2 is lag2, -3 is lag3)\n    if u in d_timestamp.keys():\n        ul = d_timestamp[u]\n        ul = ul[ul < t]\n        if   ul.shape[0] >= 3:\n            return ul[l]\n        elif ul.shape[0] == 2 and l != -3:\n            return ul[l]\n        elif ul.shape[0] == 1 and l == -1:\n            return ul[l]\n    return 0\n\ndef get_noplay_days(u, t):\n    # u: user_id\n    # t: normalized timestamp\n    if u in d_timestamp.keys():\n        ul = d_timestamp[u] \/ (1000*3600)\n        ul = ul[ul <= t]\n        if 1 < ul.shape[0]:\n            di = np.diff(ul)\n            return np.where(di<24,0,di).sum()\n    return 0\n\ndef get_attempt_thedaybefore(u, t, d):\n    # u: user_id\n    # t: normalized timestamp\n    # d: days(7 is 1 week ago, 1 is 24 hours ago, 0.5 is 12 hours ago)\n    if u in d_timestamp.keys():\n        ul = d_timestamp[u] \/ (1000*3600)\n        return np.count_nonzero((t-d <= ul) * (ul < t))\n    return 0\n\ndef cut_and_merge_with_class(df, df_class, t_col, c_col):\n    df = df.copy()\n    df[\"base_class\"] = pd.cut(df[t_col], [-0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1], labels=False)\n    return df.merge(df_class[[\"question_id\",\"base_class\",c_col]], on=[\"question_id\",\"base_class\"], sort=False)\ndata  = train[train.user_id.isin(ext_user)].copy()\ndata.reset_index(drop=True, inplace=True)\n\n# Store all user id for calculating attempt\nq_ary = np.array(train[[\"user_id\",\"row_id\",\"question_id\",\"part\",\"tag1\",\"answered_correctly\"]])\nq_ary = q_ary[np.argsort(q_ary[:,1])]\ndel train\ngc.collect()\n\ntrain = data.copy()\nsizes_train_user   = np.array(train.user_id.value_counts().sort_index().values, dtype=\"int16\")\nsizes_train_cumsum = sizes_train_user.cumsum()\ndel data\ngc.collect()\n\ntrain.shape\n%%time\n# CV strategy\ndef rand_time(max_time_stamp):\n    interval = MAX_TIME_STAMP - max_time_stamp\n    rand_time_stamp = random.randint(0,interval)\n    return rand_time_stamp\n\nmax_timestamp_u = train[['user_id','timestamp']].groupby(['user_id']).agg(['max']).reset_index()\nmax_timestamp_u.columns = ['user_id', 'max_time_stamp']\nMAX_TIME_STAMP  = max_timestamp_u.max_time_stamp.max()\n\nmax_timestamp_u['rand_time_stamp'] = max_timestamp_u.max_time_stamp.apply(lambda x: rand_time(x))\ntrain = train.merge(max_timestamp_u, on='user_id')\ntrain['viretual_time_stamp'] = train.timestamp + train['rand_time_stamp']\ntrain.sort_values(['viretual_time_stamp', 'row_id'], inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n\ntrain_num = int(train.shape[0] * TRAIN_RATE)\nif TUNE:\n    tune_num = int(train.shape[0] * TUNE_RATE)\n    test_num = train.shape[0] - (train_num + tune_num)\nelse:\n    test_num = train.shape[0] - train_num\n    tune_num = 0\nprint(train_num, test_num, tune_num)\n\n# Add CV group\ntrain[\"cv_group\"] = 9\nsta = 0\nfor c in range(CV):\n    end = int(train_num\/CV)*(c+1) if (c+1) != CV else train_num\n    train.loc[sta:end, \"cv_group\"] = c\n    print(\"CV:%s -- Start with %07d and end with %07d. Num of user is %s and mean correct answer rate is %f\" % (c, sta, end, train.loc[train.cv_group==c].user_id.nunique(), train.loc[train.cv_group==c].answered_correctly.mean()))\n    sta = end\nif TUNE:\n    train.loc[train_num+1:train_num+tune_num, \"cv_group\"] = 5\n    train.loc[train_num+tune_num+1:,          \"cv_group\"] = 4\nelse:\n    train.loc[train_num+1:train_num+test_num, \"cv_group\"] = 4\n\ntrain.sort_values('row_id', inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n# Add correct answer rate after shifting to prior\ndevp_rate = (devp_cumsum \/ num_cumsum).astype(\"float32\")\ndevm_rate = (devm_cumsum \/ num_cumsum).astype(\"float32\")\ntrain[\"ans_rate\"]   = shift_to_prior(ans_rate,   sizes_train_cumsum).astype(\"float32\")\ntrain[\"devp_rate\"]  = shift_to_prior(devp_rate,  sizes_train_cumsum).astype(\"float32\")\ntrain[\"devm_rate\"]  = shift_to_prior(devm_rate,  sizes_train_cumsum).astype(\"float32\")\ntrain[\"num_que\"]    = shift_to_prior(num_cumsum, sizes_train_cumsum).astype(\"int16\")\ntrain[\"num_exp\"]    = exp_cumsum.astype(\"int16\")\ntrain[\"study_rate\"] = (train.num_exp \/ train.num_que).replace([np.inf,-np.inf], np.nan).fillna(0).astype(\"float32\")\n\ntrain = reduce_mem_usage(train)\n\ndel ans_rate, devp_rate, devm_rate, num_cumsum, exp_cumsum\ngc.collect()\n# Calculate correct answer rate for each part\nar_part_rate = ar_part[:,:7] \/ ar_part[:,7:]\nnp.nan_to_num(ar_part_rate, copy=False)\nar_part_rate = ar_part_rate.astype(\"float32\")\n\n# Shift to prior\nfor i in range(ar_part_rate.shape[1]):\n    ar_part_rate[:,i] = shift_to_prior(ar_part_rate[:,i], sizes_train_cumsum)\nfor i in range(ar_part.shape[1]):\n    ar_part[:,i]      = shift_to_prior(ar_part[:,i],      sizes_train_cumsum)\n\nar_part_rate.shape, ar_part.shape\n# Calculate answering ability for each question difficulty\nar_ability_rate = ar_ability[:,:8] \/ ar_ability[:,8:]\nnp.nan_to_num(ar_ability_rate, copy=False)\nar_ability_rate = ar_ability_rate.astype(\"float32\")\n\n# Shift to prior\nfor i in range(ar_ability_rate.shape[1]):\n    ar_ability_rate[:,i] = shift_to_prior(ar_ability_rate[:,i], sizes_train_cumsum)\n\nar_ability_rate.shape\ntrain = train.join(pd.DataFrame(ar_part_rate,    columns=part_rate_cols))\ntrain = train.join(pd.DataFrame(ar_part[:,7:],   columns=num_part_cols))\ntrain = train.join(pd.DataFrame(ar_ability_rate, columns=abi_rate_cols))\ntrain = train.join(pd.DataFrame(ar_etmie_rate,   columns=[\"etime_rate\"]))\n\ntrain.sort_values(\"row_id\", inplace=True)\ntrain.reset_index(drop=True, inplace=True)\n\ndel ar_part_rate, ar_part, ar_ability_rate\ngc.collect()\ntrain.shape\n%%time\nprint(\"Calculating the gap of continuous\")\ntrain[\"lagtime1\"]  = (train[[\"user_id\",\"timestamp\"]].parallel_apply(lambda x: get_lagtime(x[0], x[1], -1), axis=1) \/ (1000*3600)).astype(\"float32\")\ntrain[\"lagtime2\"]  = (train[[\"user_id\",\"timestamp\"]].parallel_apply(lambda x: get_lagtime(x[0], x[1], -2), axis=1) \/ (1000*3600)).astype(\"float32\")\ntrain[\"lagtime3\"]  = (train[[\"user_id\",\"timestamp\"]].parallel_apply(lambda x: get_lagtime(x[0], x[1], -3), axis=1) \/ (1000*3600)).astype(\"float32\")\ntrain[\"timestamp\"] = (train.timestamp \/ (1000*3600)).astype(\"float32\")\ntrain[\"lagtime1\"]  = (train.timestamp - train.lagtime1).astype(\"float32\")\ntrain[\"lagtime2\"]  = (train.timestamp - train.lagtime2).astype(\"float32\")\ntrain[\"lagtime3\"]  = (train.timestamp - train.lagtime3).astype(\"float32\")\n\n#print(\"Calculating the number of attempt within 12 hours\/24 hours\/1 week\")\n#train[\"attempt_12hours\"] = train[[\"user_id\",\"timestamp\"]].apply(lambda x: get_attempt_thedaybefore(x[0], x[1], 0.5), axis=1)\n#train[\"attempt_24hours\"] = train[[\"user_id\",\"timestamp\"]].apply(lambda x: get_attempt_thedaybefore(x[0], x[1], 1),   axis=1)\n#train[\"attempt_1week\"]   = train[[\"user_id\",\"timestamp\"]].apply(lambda x: get_attempt_thedaybefore(x[0], x[1], 7),   axis=1)\n\nprint(\"Calculating total of no play days\")\ntrain[\"noplay_days\"]    = (train[[\"user_id\",\"timestamp\"]].parallel_apply(lambda x: get_noplay_days(x[0], x[1]), axis=1)).astype(\"float32\")\n\n# Add elapsed days\ntrain[\"elapsed_days\"]   = (train.timestamp \/ 24).astype(\"int32\")\n\n# Add rate of timestamp\ntrain[\"noplay_rate\"]    = (train.noplay_days  \/ train.num_que).fillna(0).astype(\"float32\")\ntrain[\"timestamp_rate\"] = (train.timestamp    \/ train.num_que).fillna(0).astype(\"float32\")\ntrain[\"elapsed_rate\"]   = (train.elapsed_days \/ train.num_que).fillna(0).astype(\"float32\")\n%%time\nd = get_user_items_dict(q_ary, sizes_qcumsum)\n    \nprint(\"Calculating the number of attempt against the same question\")\ntrain[\"attempt_que\"]    = train[[\"user_id\",\"row_id\",\"question_id\"]].parallel_apply(lambda x: get_attempt_que(x[0], x[1], x[2]), axis=1)\n\ntags_cols = [\"tag\"+str(t) for t in range(1,7)]\nprint(\"Calculating the number of attempt against the same tag\")\ntrain[\"attempt_tags\"]   = train[[\"user_id\",\"row_id\",\"tag1\"]].parallel_apply(lambda x: get_attempt_tags(x[0], x[1], x[2]), axis=1)\n\nprint(\"Calculating the current correct answer rate\")\ntrain[\"attempt_curtar\"] = train[[\"user_id\",\"row_id\"]].parallel_apply(lambda x: get_attempt_curt_ans_rate(x[0], x[1]), axis=1)\n\n#print(\"Calculating the number of attempt against the same part\")\n#train[\"attempt_curtp\"]  = train[[\"user_id\",\"row_id\",\"part\"]].apply(lambda x: get_attempt_curt_part(x[0], x[1], x[2]), axis=1)\n\n#print(\"Calculating the number of attempt against the same question format\")\n#train[\"attempt_curtLR\"] = train[[\"user_id\",\"row_id\",\"LorR\"]].apply(lambda x: get_attempt_curt_LR(x[0], x[1], x[2]), axis=1)\n%%time\ntrain = cut_and_merge_with_class(train, df_ans_class, \"ans_rate\",   \"ans_rate_class\")\ntrain = cut_and_merge_with_class(train, df_ans_class, \"study_rate\", \"study_rate_class\")\nfor p in range(1,8):\n    train = cut_and_merge_with_class(train, df_ans_class, f\"part{p}_rate\", f\"part{p}_rate_class\")\ntrain.drop(\"base_class\", axis=1, inplace=True)\ntrain.shape\ntrain = train.merge(df_qs.drop([\"part\",\"tag1\"], axis=1), on=\"question_id\")\ntrain = train.merge(df_question_rate, on=[\"question_id\",\"bundle_id\",\"prior_question_had_explanation\"])\ntrain = train.merge(df_etime_rate,    on=\"question_id\")\ntrain = train.merge(df_part_rate,     on=\"part\")\n\ngc.collect()\nt_cols = [\"ans_rate_class\",\"study_rate_class\"] + [\"part\"+str(p)+\"_rate_class\" for p in range(1,8)]\nn_cols = [\"num_que\",       \"num_que\"]          + num_part_cols\nfor t, n in zip(t_cols, n_cols):\n    train = change_rate_with_num(train, t, n, method=\"respectively\")\n    train = change_rate_with_num(train, t, n, method=\"bundle\")\n# Make chance of making a mistake features\ntrain[\"prob_mistake_que\"] = train.num_que.apply(lambda x: 0.6*x**(-0.2) if x!=0 else 0.6)\npart_mistake_cols = []\nfor p in range(1,8):\n    part_mistake_cols.append(\"prob_mistake_part\"+str(p))\n    train[\"prob_mistake_part\"+str(p)] = train[\"num_part\"+str(p)].apply(lambda x: 0.6*x**(-0.2) if x!=0 else 0.6)\nall_prob_mistake = np.array(train[part_mistake_cols])\ntrain[\"prob_mistake_part_curt\"] = np.nanmax(np.identity(8) [train.part][:,1:]*all_prob_mistake, axis=1)\n    \n# Make current part\/part rate\/ability features\nall_part_rate  = np.array(train[[\"part1_rate\",\"part2_rate\",\"part3_rate\",\"part4_rate\",\"part5_rate\",\"part6_rate\",\"part7_rate\"]])\nall_part_ratec = np.array(train[[\"part1_rate_class\",\"part2_rate_class\",\"part3_rate_class\",\"part4_rate_class\",\"part5_rate_class\",\"part6_rate_class\",\"part7_rate_class\"]])\nall_abi_rate   = np.array(train[[\"abi_rate0\",\"abi_rate3\",\"abi_rate4\",\"abi_rate5\",\"abi_rate6\",\"abi_rate7\",\"abi_rate8\",\"abi_rate9\"]])\ntrain[\"part_rate_curt\"]  = np.nanmax(np.identity(8) [train.part][:,1:]*all_part_rate, axis=1)\ntrain[\"part_ratec_curt\"] = np.nanmax(np.identity(8) [train.part][:,1:]*all_part_ratec, axis=1)\ntrain[\"abi_rate_curt\"]   = np.nanmax(np.identity(10)[train.question_rate_class_exp][:,[0,3,4,5,6,7,8,9]]*all_abi_rate, axis=1)\ntrain[\"part_ratec_mean\"] = np.nan_to_num(all_part_ratec).sum(1) \/ 7\n\ndel all_part_rate, all_part_ratec, all_abi_rate\ngc.collect()\n\n# Make harmonic features\n# Comparison between:\n#  - a correct answer rate against all questions and a correct answer rate against the part\n#  - a correct answer rate of someone who looks like you and a correct answer rate of the question\n#  - a correct answer rate of someone who looks like you and a correct answer rate against the part\n#  - a correct answer rate against the part and a correct answer rate of the part\n#  - a correct answer rate of someone who looks like you and a correct answer rate of the question\n#  - a correct answer rate of the part and a correct answer rate of the question\n#  - a correct answer rate against questions difficulty and a correct answer rate of the question\ntrain[\"harmonic_ar_prc\"]   = 2 * (train.ans_rate         * train.part_rate_curt)    \/ (train.ans_rate         + train.part_rate_curt)\ntrain[\"harmonic_arc_qr\"]   = 2 * (train.ans_rate_class   * train.question_rate_exp) \/ (train.ans_rate_class   + train.question_rate_exp)\ntrain[\"harmonic_arc_prcc\"] = 2 * (train.ans_rate_class   * train.part_ratec_curt)   \/ (train.ans_rate_class   + train.part_ratec_curt)\ntrain[\"harmonic_prc_pr\"]   = 2 * (train.part_rate_curt   * train.part_rate)         \/ (train.part_rate_curt   + train.part_rate)\ntrain[\"harmonic_prcc_qr\"]  = 2 * (train.part_ratec_curt  * train.question_rate_exp) \/ (train.part_ratec_curt  + train.question_rate_exp)\ntrain[\"harmonic_qr_pr\"]    = 2 * (train.part_rate        * train.question_rate_exp) \/ (train.part_rate        + train.question_rate_exp)\ntrain[\"harmonic_abrc_qr\"]  = 2 * (train.abi_rate_curt    * train.question_rate_exp) \/ (train.abi_rate_curt    + train.question_rate_exp)\ntrain[\"harmonic_arc_src\"]  = 2 * (train.ans_rate_class   * train.study_rate_class)  \/ (train.ans_rate_class   + train.study_rate_class)\ntrain[\"harmonic_prcc_src\"] = 2 * (train.part_ratec_curt  * train.study_rate_class)  \/ (train.part_ratec_curt  + train.study_rate_class)\ntrain[\"harmonic_src_qr\"]   = 2 * (train.study_rate_class * train.question_rate_exp) \/ (train.study_rate_class + train.question_rate_exp)\n\n# Make rate features\ntrain[\"rate_arc_prcc\"]   = train.ans_rate_class  \/ train.part_ratec_curt\ntrain[\"rate_arc_src\"]    = train.ans_rate_class  \/ train.study_rate_class\ntrain[\"rate_prcc_src\"]   = train.part_ratec_curt \/ train.study_rate_class\ntrain[\"rate_arc_qr\"]     = train.ans_rate_class  \/ train.question_rate_exp\ntrain[\"rate_qr_pr\"]      = train.part_rate       \/ train.question_rate_exp\ntrain[\"rate_prcc_prccm\"] = train.part_ratec_curt \/ train.part_ratec_mean\ntrain.fillna(0, inplace=True)\ntrain.sort_values(by=\"row_id\", inplace=True)\ntrain.reset_index(drop=True, inplace=True)\ndef plot(rs, re, c, t_col):\n    u = 0\n    for _r in range(rs, re):\n        for _c in range(c):\n            train.loc[train.user_id==ids[u]].plot(x=\"num_que\", y=t_col, ax=axes[_r,_c])\n            u += 1\nc = 4; r = 2\nids = train.user_id.unique()\nrandom.shuffle(ids)\nfig, axes = plt.subplots(nrows=r*3, ncols=c, figsize=(14, 10))\n\nplot(0,   r,   c, \"ans_rate\")\nplot(r,   r*2, c, \"devm_rate\")\nplot(r*2, r*3, c, \"devp_rate\")\n\ndel ids, fig, axes\ngc.collect()\nfig, axes = plt.subplots(nrows=3, ncols=3, figsize=(13, 6))\ntrain.part_ratec_mean  .hist(ax=axes[0,0])\ntrain.harmonic_ar_prc  .hist(ax=axes[0,1])\ntrain.harmonic_arc_qr  .hist(ax=axes[0,2])\ntrain.harmonic_arc_prcc.hist(ax=axes[1,0])\ntrain.harmonic_prc_pr  .hist(ax=axes[1,1])\ntrain.harmonic_prcc_qr .hist(ax=axes[1,2])\ntrain.harmonic_qr_pr   .hist(ax=axes[2,0])\ntrain.rate_arc_qr      .hist(ax=axes[2,1])\ntrain.rate_qr_pr       .hist(ax=axes[2,2])\nprint(train.shape)\ntrain.head()\n#showStats(train.drop([\"row_id\",\"user_id\"], axis=1))\n\"\"\"\n# LGBM training \n\"\"\"\nclass BaseModel(object):\n    \"\"\"\n    Base Model Class:\n\n    train_df         : train pandas dataframe\n    test_df          : test pandas dataframe\n    target           : target column name (str)\n    features         : list of feature names\n    categoricals     : list of categorical feature names\n    n_splits         : K in KFold (default is 3)\n    cv_method        : options are .. KFold, StratifiedKFold, TimeSeriesSplit, GroupKFold, or GroupShuffleSplit\n    group            : group feature name when GroupKFold or StratifiedGroupKFold are used\n    task             : options are .. regression, multiclass, or binary\n    param            : dict of parameter, set that if you already define\n    parameter_tuning : bool, only for LGB\n    seed             : seed (int)\n    verbose          : bool\n    \"\"\"\n\n    def __init__(self, train_df, test_df, target, features, \n                 valid_df=None, tune_df=None, categoricals=[], alpha=0, \n                 n_splits=3, cv_method=\"KFold\", group=None,\n                 task=\"regression\", params=None, parameter_tuning=False,\n                 tuning_type=\"optuna_tuner\", seed=42, verbose=True):\n        self.train_df     = train_df\n        self.test_df      = test_df\n        self.valid_df     = valid_df\n        self.tune_df      = tune_df\n        self.target       = target\n        self.features     = features\n        self.n_splits     = n_splits\n        self.categoricals = categoricals\n        self.alpha        = alpha\n        self.cv_method    = cv_method\n        self.group        = group\n        self.task         = task\n        self.parameter_tuning = parameter_tuning\n        self.seed    = seed\n        self.cv      = self.get_cv()\n        self.verbose = verbose\n        self.tuning_type = tuning_type\n        if params is None:\n            self.params  = self.get_params()\n        else:\n            self.params  = params\n        self.y_pred, self.y_valid, self.score, self.models, self.oof, self.y_val, self.fi_df = self.fit()\n\n    def train_model(self, train_set, val_set):\n        raise NotImplementedError\n\n    def get_params(self):\n        raise NotImplementedError\n\n    def convert_dataset(self, x_train, y_train, x_val, y_val):\n        raise NotImplementedError\n\n    def calc_metric(self, y_true, y_pred): # this may need to be changed based on the metric of interest\n        if   self.task in (\"multiclass\",\"nn_multiclass\"):\n            preds = np.argmax(y_pred, axis=1) if y_true.shape != y_pred.shape else y_pred\n            return f1_score(y_true, preds, average='macro')                \n        elif self.task == \"binary\":\n            return roc_auc_score(y_true, y_pred, average='macro')\n        elif self.task in (\"regression\",\"quantile\"):\n            return np.sqrt(mean_squared_error(y_true, y_pred))\n    \n    def get_cv(self):\n        if self.cv_method == \"KFold\":\n            cv = KFold(n_splits=self.n_splits, shuffle=True, random_state=self.seed)\n            return cv.split(self.train_df)\n        if self.cv_method == \"StratifiedKFold\":\n            cv = StratifiedKFold(n_splits=self.n_splits, shuffle=True, random_state=self.seed)\n            return cv.split(self.train_df, self.train_df[self.target])\n        if self.cv_method == \"TimeSeriesSplit\":\n            cv = TimeSeriesSplit(max_train_size=None, n_splits=self.n_splits)\n            return cv.split(self.train_df)\n        if self.cv_method == \"GroupKFold\":\n            if self.group in self.features:\n                self.features.remove(self.group)\n            if self.group in self.categoricals:\n                self.categoricals.remove(self.group)\n            cv = GroupKFold(n_splits=self.n_splits)\n            return cv.split(self.train_df[self.features+self.categoricals], self.train_df[self.target], self.train_df[self.group])\n        if self.cv_method == \"GroupShuffleSplit\":\n            if self.group in self.features:\n                self.features.remove(self.group)\n            if self.group in self.categoricals:\n                self.categoricals.remove(self.group)\n            cv = GroupShuffleSplit(n_splits=self.n_splits, random_state=self.seed)\n            return cv.split(self.train_df[self.features+self.categoricals], self.train_df[self.target], self.train_df[self.group])\n\n    def fit(self):\n        # Initialize\n        y_vals = np.zeros((self.train_df.shape[0], ))\n        if self.task in (\"multiclass\",\"nn_multiclass\"):\n            col_len = self.train_df[self.target].nunique()\n        else:\n            col_len = 1\n        oof_pred = np.zeros((self.train_df.shape[0], col_len))\n        y_pred   = np.zeros((self.test_df.shape[0],  col_len))\n        y_valid  = np.zeros((self.valid_df.shape[0], col_len)) if self.valid_df is not None else None\n        models   = []\n        \n        if self.group is not None:\n            if self.group in self.features:\n                self.features.remove(self.group)\n            if self.group in self.categoricals:\n                self.categoricals.remove(self.group)\n                \n        fi = np.zeros((self.n_splits, len(self.features+self.categoricals)))\n        if y_valid is not None:\n            x_valid = self.valid_df[self.features+self.categoricals].copy()\n            del self.valid_df\n            gc.collect()\n        x_test = self.test_df[self.features+self.categoricals]\n\n        # Fitting with out of fold\n        for fold, (train_idx, val_idx) in enumerate(self.cv):\n            # Prepare train and test dataset\n            x_train = self.train_df.iloc[train_idx, :][self.features+self.categoricals]\n            y_train = self.train_df.iloc[train_idx, :][self.target]\n            x_val   = self.train_df.iloc[val_idx, :][self.features+self.categoricals]\n            y_val   = self.train_df.iloc[val_idx, :][self.target]\n            train_set, val_set = self.convert_dataset(x_train, y_train, x_val, y_val)\n            del x_train, y_train\n            gc.collect()\n            \n            # Fit model\n            model, importance = self.train_model(train_set, val_set)\n            fi[fold, :]       = importance\n            y_vals[val_idx]   = y_val\n            \n            # Get some scores\n            oof_pred[val_idx] = model.predict(x_val, num_iteration=model.best_iteration).reshape(oof_pred[val_idx].shape)\n            if y_valid is not None:\n                y_valid += model.predict(x_valid, num_iteration=model.best_iteration).reshape(y_valid.shape) \/ self.n_splits\n            y_pred += model.predict(x_test, num_iteration=model.best_iteration).reshape(y_pred.shape) \/ self.n_splits\n            \n            print('Partial score of fold {} is: {}'.format(fold, self.calc_metric(y_val, oof_pred[val_idx])))\n            models.append(model)\n            \n            del train_set, val_set, x_val, y_val\n            gc.collect()\n        \n        # Create feature importance data frame\n        fi_df = pd.DataFrame()\n        for n in np.arange(self.n_splits):\n            tmp = pd.DataFrame()\n            tmp[\"features\"]   = self.features+self.categoricals\n            tmp[\"importance\"] = fi[n, :]\n            tmp[\"fold\"]       = n\n            fi_df = pd.concat([fi_df, tmp], ignore_index=True)\n        gfi   = fi_df[[\"features\", \"importance\"]].groupby([\"features\"]).mean().reset_index()\n        fi_df = fi_df.merge(gfi, on=\"features\", how=\"left\", suffixes=('', '_mean'))\n        \n        # Calculate oof score\n        loss_score = self.calc_metric(y_vals, oof_pred)\n        print('Our oof loss score is: ', loss_score)\n        \n        return y_pred, y_valid, loss_score, models, oof_pred, y_vals, fi_df\n\n    def plot_feature_importance(self, rank_range=[1, 100]):\n        fig, ax   = plt.subplots(1, 1, figsize=(16, 12))\n        sorted_df = self.fi_df.sort_values(by=\"importance_mean\", ascending=False).reset_index()\n        sns.barplot(data=sorted_df.iloc[self.n_splits*(rank_range[0]-1) : self.n_splits*rank_range[1]],\n                    x=\"importance\", y=\"features\", orient='h')\n        ax.set_xlabel(\"feature importance\")\n        ax.spines['top'].set_visible(False)\n        ax.spines['right'].set_visible(False)\n        return sorted_df\n    \nclass LgbModel(BaseModel):\n    \"\"\"\n    LGB wrapper\n    \"\"\"\n    def train_model(self, train_set, val_set):\n        verbosity = 100 if self.verbose else 0\n        model = lgb.train(self.params, train_set, num_boost_round=3000,\n                          valid_sets=[train_set, val_set], verbose_eval=verbosity)\n        fi = model.feature_importance(importance_type=\"gain\")\n        return model, fi\n\n    def convert_dataset(self, x_train, y_train, x_val=None, y_val=None):\n        train_set   = lgb.Dataset(x_train, y_train, categorical_feature=self.categoricals)\n        if x_val is not None:\n            val_set = lgb.Dataset(x_val,   y_val,   categorical_feature=self.categoricals)\n            return train_set, val_set\n        return train_set\n\n    def get_params(self):\n        # Fast fit parameters\n        params = {\n            'boosting_type'    : \"gbdt\",\n            'objective'        : self.task,\n            \"subsample\"        : 0.4,\n            \"subsample_freq\"   : 1,\n            'max_depth'        : 4,\n            'min_data_in_leaf' : 50,\n            'learning_rate'    : 0.05,\n            'early_stopping_rounds' : 100,\n            'bagging_seed'     : 11,\n            'random_state'     : 42,\n            'verbosity'        : -1\n        }\n\n        # List is here: https:\/\/lightgbm.readthedocs.io\/en\/latest\/Parameters.html\n        if   self.task == \"regression\":\n            params[\"metric\"]    = \"regression_l2\"\n        elif self.task == \"quantile\":\n            params[\"metric\"]    = \"quantile\"\n            params[\"alpha\"]     = self.alpha\n        elif self.task == \"binary\":\n            params[\"metric\"]    = \"auc\"  # binary_logloss\n        elif self.task == \"multiclass\":\n            params[\"metric\"]    = \"multi_logloss\"\n            params[\"num_class\"] = len(self.train_df[self.target].unique())\n            \n        # Bayesian Optimization by Optuna\n        if self.parameter_tuning:\n            # Define objective function\n            def get_dataset():\n                if self.tune_df is not None:\n                    tune = self.tune_df.copy()\n                else:\n                    tune = self.train_df.copy()\n                if self.group is not None:\n                    train_num = int(tune.shape[0] * 0.7)\n                    test_num  = tune.shape[0] - train_num\n                    train_x   = tune.head(train_num)[self.features+self.categoricals].reset_index(drop=True)\n                    train_y   = tune.head(train_num)[[self.target]].reset_index(drop=True)\n                    test_x    = tune.tail(test_num)[self.features+self.categoricals].reset_index(drop=True)\n                    test_y    = tune.tail(test_num)[[self.target]].reset_index(drop=True)\n                else:\n                    train_x, test_x, train_y, test_y = train_test_split(tune[self.features+self.categoricals], \n                                                                        tune[self.target], test_size=0.3, random_state=self.seed)\n                if self.categoricals != []:\n                    dtrain = lgb.Dataset(train_x, train_y, categorical_feature=self.categoricals)\n                    dtest  = lgb.Dataset(test_x,  test_y,  categorical_feature=self.categoricals)\n                else:\n                    dtrain = lgb.Dataset(train_x, train_y)\n                    dtest  = lgb.Dataset(test_x,  test_y)\n                return dtrain, dtest, test_x, test_y\n            \n            def objective(trial):\n                # Split train and test data\n                dtrain, dtest, test_x, test_y = get_dataset()\n                # Parameters to be explored\n                hyperparams = {'max_depth'         : trial.suggest_int('max_depth', 4, 16),\n                               'max_bin'           : trial.suggest_int('max_bin', 200, 1000),\n                               'num_leaves'        : trial.suggest_int('num_leaves', 200, 1000),\n                               'min_data_in_leaf'  : trial.suggest_int('min_data_in_leaf', 1, 300),\n                               'min_child_samples' : trial.suggest_int('min_child_samples', 5, 100),\n                               'feature_fraction'  : trial.suggest_uniform('feature_fraction', 0.2, 1.0),\n                               'bagging_fraction'  : trial.suggest_uniform('bagging_fraction', 0.2, 1.0),\n                               'bagging_freq'      : trial.suggest_int('bagging_freq', 0, 7),\n                               'lambda_l1'         : trial.suggest_loguniform('lambda_l1', 1e-8, 10.0),\n                               'lambda_l2'         : trial.suggest_loguniform('lambda_l2', 1e-8, 10.0),\n                               'early_stopping_rounds' : 150}\n                # LGBM\n                params.update(hyperparams)\n                verbosity = 100 if self.verbose else 0\n                model = lgb.train(params, dtrain, valid_sets=dtest, \n                                  num_boost_round=1000, verbose_eval=verbosity)\n                pred  = model.predict(test_x)\n                return self.calc_metric(test_y, pred)\n\n            if self.tuning_type == \"optuna_tuner\":\n                dtrain, dtest, _, _ = get_dataset()\n                verbosity = 100 if self.verbose else 0\n                tuner_params = {\"objective\": params[\"objective\"],\n                                \"metric\"   : params[\"metric\"]}\n                # Run optimization\n                model  = optuna_lgb.train(tuner_params, dtrain, valid_sets=dtest, \n                                          num_boost_round=1000, early_stopping_rounds=50,\n                                          verbose_eval=verbosity)\n                print('Best params:')\n                for key, value in model.params.items():\n                    print('  {}: {}'.format(key, value))\n                params = model.params\n                params[\"feature_pre_filter\"] = True\n            else:\n                # Run optimization\n                study = optuna.create_study(direction='maximize')  # if uses loss, should use minimize\n                study.optimize(objective, n_trials=40)\n                print('Number of finished trials: {}'.format(len(study.trials)))\n                trial = study.best_trial\n                print('Best trial:')\n                print('  Value: {}'.format(trial.value))\n                print('  Params: ')\n                for key, value in trial.params.items():\n                    print('    {}: {}'.format(key, value))\n                params.update(trial.params)\n                # Plot history\n                plot_optimization_history(study)\n            \n        return params\nnot_use_cols = [\"row_id\",\"user_id\",\"user_answer\",\"prior_question_had_explanation\",\n                \"question_rate_class\",\"question_rate_class_exp\",'part_rate_curt','part_ratec_curt',\"abi_rate_curt\",\n                \"cv_group\",\"max_time_stamp\",\"rand_time_stamp\",\"viretual_time_stamp\"]\nnot_use_cols = not_use_cols + ans_part_cols + num_part_cols + part_mistake_cols + tags_cols\nN = 20000 if 20000 < train.shape[0] else train.shape[0]\ndf_corr = train.drop([c for c in train.columns if c in not_use_cols], axis=1).sample(n=N).corr()\ndf_corr\ndf_corr[[\"answered_correctly\"]].abs().sort_values(\"answered_correctly\")[[\"answered_correctly\"]]\nnot_use_cols += [\"prior_question_elapsed_time\",'bundle_id',\"bundle_skew\",\"num_solving_question\",\n                 \"num_intention\",\"num_lec\",\"num_concept\",\"num_concept\",\"num_tag\",'deviation_m',\"LorR\",'part']\ncategoricals  = []\nkeep_cols     = [\"user_id\"]\ntarget   = \"answered_correctly\"\ngroup    = \"cv_group\"  #\"user_id\"\nfeatures = [c for c in train.columns if c not in not_use_cols+categoricals+[target]]\n\nprint(len(features+categoricals))\nprint(\"Numeric features\")\ndisplay(sorted(features))\nprint(\"Categorical features\")\nprint(sorted(categoricals))\nuser_ids = train.user_id.unique()\nrandom.shuffle(user_ids)\n\nuse_features = [target, group] + keep_cols + features + categoricals\n\ntrains = []\nfor i in range(1, MODEL_NUM+1):\n    print(\"Model %s will be from 0 to %s in cv_group\" % (i, CV-1))\n    train_data = train.loc[train.cv_group.isin(np.arange(CV)), use_features].copy()\n    train_data.reset_index(drop=True, inplace=True)\n    trains.append(train_data)\n    \ntest_data = train.loc[train.cv_group==CV, use_features].copy()\ntest_data.reset_index(drop=True, inplace=True)\n\nif TUNE:\n    tune_data = train.loc[train.cv_group==CV+1, use_features].copy()\n    tune_data.reset_index(drop=True, inplace=True)\nelse:\n    tune_data = pd.DataFrame()\n\ndel train, train_data\ngc.collect()\nprint(\"Training data\")\nfor i, train_data in enumerate(trains):\n    print(\"No.\", i+1)\n    print(train_data.shape, train_data.cv_group.unique(), train_data.user_id.nunique())\n    display(train_data.head())\n    \nprint(\"Test data\")\nprint(test_data.shape, test_data.cv_group.unique(), test_data.user_id.nunique())\ndisplay(test_data.head())\n\nif TUNE:\n    print(\"Tune data\")\n    print(tune_data.shape, tune_data.cv_group.unique(), tune_data.user_id.nunique())\n    display(tune_data.head())\n    \ndel train_data\ngc.collect()\n# For making a baseline\nparams1 = {\n    'objective': 'binary',\n    \"boosting_type\": \"gbdt\",\n    \"metric\": 'auc',\n    'learning_rate': 0.1,\n    \"max_depth\": 4,\n    \"max_bin\": 853,\n    \"num_leaves\": 492,\n    \"min_data_in_leaf\": 229,\n    \"min_child_samples\": 55,\n    \"feature_fraction\": 0.7894275993264507,\n    \"bagging_fraction\": 0.8305608180096481,\n    \"bagging_freq\": 6,\n    \"lambda_l1\": 0.00010208001912287773,\n    \"lambda_l2\": 9.315928833771094,\n    'early_stopping_rounds' : 100,\n    'random_state': 42,\n    \"bagging_seed\": 11,\n    \"verbosity\": -1}\n\n# Got from public\nparams2 = {\n    'objective': 'binary',\n    \"boosting_type\": \"gbdt\",\n    \"metric\": 'auc',\n    'learning_rate': 0.05,\n    'max_depth': 4,\n    'max_bin': 700,\n    'num_leaves': 350,\n    'min_child_weight': 0.03454472573214212,\n    'feature_fraction': 0.58,\n    'bagging_fraction': 0.58,\n    'reg_alpha': 0.3899927210061127,\n    'reg_lambda': 0.6485237330340494,\n    'early_stopping_rounds' : 100,\n    'random_state': 42,\n    \"bagging_seed\": 11,\n    \"verbosity\": -1}\n\n# The best params from user_id group k-fold\nparams3 = {\n    'objective': 'binary',\n    \"boosting_type\": \"gbdt\",\n    \"metric\": 'auc',\n    'learning_rate': 0.05,\n    \"max_depth\": 9,\n    \"max_bin\": 872,\n    \"num_leaves\": 743,\n    \"min_data_in_leaf\": 274,\n    \"min_child_samples\": 27,\n    \"feature_fraction\": 0.5922083852690104,\n    \"bagging_fraction\": 0.7638997668812837,\n    \"bagging_freq\": 5,\n    \"lambda_l1\": 4.603407547894731e-07,\n    \"lambda_l2\": 4.833680631174746e-07,\n    'early_stopping_rounds' : 200,\n    'random_state': 42,\n    \"bagging_seed\": 11,\n    \"verbosity\": -1}\n\n# The best params from cv_group group k-fold\nparams4 = {\n    'objective': 'binary',\n    \"boosting_type\": \"gbdt\",\n    \"metric\": 'auc',\n    'learning_rate': 0.05,\n    \"max_depth\": 8,\n    \"max_bin\": 990,\n    \"num_leaves\": 885,\n    \"min_data_in_leaf\": 214,\n    \"min_child_samples\": 89,\n    \"feature_fraction\": 0.4990107527526446,\n    \"bagging_fraction\": 0.9513631160877628,\n    \"bagging_freq\": 7,\n    \"lambda_l1\": 4.856465786762882e-05,\n    \"lambda_l2\": 1.6804951000850403e-08,\n    'early_stopping_rounds' : 200,\n    'random_state': 42,\n    \"bagging_seed\": 11,\n    \"verbosity\": -1}\n\nif TUNE:\n    params = [None] * MODEL_NUM\nelif MODEL_NUM == 1:\n    params = [params3]\nelse:\n    params = [params3, params4]\ntuning_type = \"optuna\"\n%%time\nlgbms = []\nfor idx, train_data in enumerate(trains):\n    if DEBUG:\n        lgbm = LgbModel(train_data.sample(n=30000).reset_index(drop=True), test_data,\n                        target, features, categoricals=categoricals,\n                        task=\"binary\", params=None, parameter_tuning=TUNE, tuning_type=tuning_type,\n                        tune_df=tune_data, cv_method=\"GroupKFold\", n_splits=4, group=group, verbose=False)\n    else:\n        lgbm = LgbModel(train_data, test_data, \n                        target, features, categoricals=categoricals,\n                        task=\"binary\", params=params[idx], parameter_tuning=TUNE, tuning_type=tuning_type,\n                        tune_df=tune_data, cv_method=\"GroupKFold\", n_splits=4, group=group, verbose=False)\n    lgbms.append(lgbm)\n    del lgbm\n    gc.collect()\nfor lgbm in lgbms:\n    _ = lgbm.plot_feature_importance()\nfor lgbm in lgbms:\n    score = roc_auc_score(test_data.answered_correctly, lgbm.y_pred)\n    fpr, tpr, thresholds = roc_curve(test_data.answered_correctly, lgbm.y_pred)\n    print(score)\n    plt.plot(fpr, tpr)\nshow_cols = [\"correct\",\"answered_correctly\",\"predict\",\"predict_prob\",\"user_id\"]+features\ntest_data[\"predict_prob\"] = lgbm.y_pred\ntest_data[\"predict\"]      = test_data.predict_prob.apply(lambda x: 1 if x>0.5 else 0)\ntest_data[\"correct\"]      = test_data[[\"answered_correctly\",\"predict\"]].apply(lambda x: 1 if x[0]==x[1] else 0, axis=1)\ntest_data.sort_values(\"predict_prob\", ascending=False, inplace=True)\ntest_data[show_cols].head()\ndf_res_sorted = test_data.loc[(test_data.correct==0), show_cols].sort_values(\"predict_prob\", ascending=False)\ndf_res_sorted.head(20)\nfor u in df_res_sorted.user_id.unique()[:3]:\n    test_data.loc[test_data.user_id==u, show_cols].to_csv(\"debug_\"+str(u)+\".csv\", index=False)\nmodels = []\nfor lgbm in lgbms:\n    models += lgbm.models\nprint(len(models))\n\ndel lgbms, train_data, tune_data\ngc.collect()\n\"\"\"\n# Load SAKT model\n\"\"\"\ndef future_mask(seq_length):\n    future_mask = np.triu(np.ones((seq_length, seq_length)), k=1).astype('bool')\n    return torch.from_numpy(future_mask)\nclass FFN(nn.Module):\n    def __init__(self, state_size=200, forward_expansion=1, bn_size=(180-1), dropout=0.2):\n        super(FFN, self).__init__()\n        self.state_size = state_size\n        \n        self.lr1     = nn.Linear(state_size, forward_expansion * state_size)\n        self.relu    = nn.ReLU()\n        self.bn      = nn.BatchNorm1d(bn_size)\n        self.lr2     = nn.Linear(forward_expansion * state_size, state_size)\n        self.dropout = nn.Dropout(dropout)\n        \n    def forward(self, x):\n        x = self.relu(self.lr1(x))\n        x = self.bn(x)\n        x = self.lr2(x)\n        return self.dropout(x)\n    \nclass TransformerBlock(nn.Module):\n    def __init__(self, embed_dim, heads=8, dropout=0.1, forward_expansion=1):\n        super(TransformerBlock, self).__init__()\n        self.multi_att      = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=heads, dropout=dropout)\n        self.dropout        = nn.Dropout(dropout)\n        self.layer_normal   = nn.LayerNorm(embed_dim)\n        self.ffn            = FFN(embed_dim, forward_expansion=forward_expansion, dropout=dropout)\n        self.layer_normal_2 = nn.LayerNorm(embed_dim)\n        \n    def forward(self, value, key, query, att_mask):\n        att_output, att_weight = self.multi_att(value, key, query, attn_mask=att_mask)\n        att_output = self.dropout(self.layer_normal(att_output + value))\n        att_output = att_output.permute(1, 0, 2) # att_output: [s_len, bs, embed] => [bs, s_len, embed]\n        x = self.ffn(att_output)\n        x = self.dropout(self.layer_normal_2(x + att_output))\n        return x.squeeze(-1), att_weight\n    \nclass Encoder(nn.Module):\n    def __init__(self, n_skill, max_seq=180, embed_dim=128, dropout=0.1, forward_expansion=1, num_layers=1, heads=8):\n        super(Encoder, self).__init__()\n        self.n_skill, self.embed_dim = n_skill, embed_dim\n        self.embedding     = nn.Embedding(2 * n_skill + 1, embed_dim)\n        self.pos_embedding = nn.Embedding(max_seq - 1,     embed_dim)\n        self.e_embedding   = nn.Embedding(n_skill + 1,     embed_dim)\n        self.layers        = nn.ModuleList([TransformerBlock(embed_dim, forward_expansion = forward_expansion) for _ in range(num_layers)])\n        self.dropout       = nn.Dropout(dropout)\n        \n    def forward(self, x, question_ids):\n        device = x.device\n        x      = self.embedding(x)\n        pos_id = torch.arange(x.size(1)).unsqueeze(0).to(device)\n        pos_x  = self.pos_embedding(pos_id)\n        x      = self.dropout(x + pos_x)\n        x      = x.permute(1, 0, 2) # x: [bs, s_len, embed] => [s_len, bs, embed]\n        e      = self.e_embedding(question_ids)\n        e      = e.permute(1, 0, 2)\n        for layer in self.layers:\n            att_mask      = future_mask(e.size(0)).to(device)\n            x, att_weight = layer(e, x, x, att_mask=att_mask)\n            x = x.permute(1, 0, 2)\n        x = x.permute(1, 0, 2)\n        return x, att_weight\n\nclass SAKTModel(nn.Module):\n    def __init__(self, n_skill, max_seq=180, embed_dim=128, dropout=0.1, forward_expansion=1, enc_layers=1, heads=8):\n        super(SAKTModel, self).__init__()\n        self.encoder  = Encoder(n_skill, max_seq, embed_dim, dropout, forward_expansion, num_layers=enc_layers)\n        self.pred     = nn.Linear(embed_dim+1, 1)\n        \n    def forward(self, x1, x2, question_ids):\n        device = x1.device\n        x, att_weight = self.encoder(x1, question_ids)\n        x = torch.cat([x, x2.unsqueeze(2)], dim=2).to(device)\n        x = self.pred(x)\n        return x.squeeze(-1), att_weight\n%%time\ndevice  = torch.device(\"cpu\")\nskills  = joblib.load(\"\/kaggle\/input\/riiid-sakt-model-dataset-public\/skills.pkl.zip\")\nn_skill = len(skills)\ngroup   = joblib.load(\"\/kaggle\/input\/riiid-sakt-model-dataset-own\/group.pkl.zip\")\nlags    = joblib.load(\"\/kaggle\/input\/riiid-sakt-model-dataset-own\/lags.pkl.zip\")\n\nnn_model = SAKTModel(n_skill, max_seq=180, embed_dim=128, forward_expansion=1, enc_layers=1, heads=8, dropout=0.1)\nnn_model.load_state_dict(torch.load(\"\/kaggle\/input\/riiid-sakt-model-dataset-own\/sakt_model.pt\", map_location='cpu'))\n\nnn_model.to(device)\nnn_model.eval()\nclass TestDataset(Dataset):\n    def __init__(self, samples, lags, test_df, max_seq=180): \n        super(TestDataset, self).__init__()\n        self.samples  = samples\n        self.lags     = lags\n        self.user_ids = [x for x in test_df[\"user_id\"].unique()]\n        self.test_df  = test_df\n        self.n_skill  = n_skill\n        self.max_seq  = max_seq\n    \n    def __len__(self):\n        return self.test_df.shape[0]\n    \n    def __getitem__(self, index):\n        test_info = self.test_df.iloc[index]\n\n        user_id      = test_info[\"user_id\"]\n        target_id    = test_info[\"question_id\"]\n        lagtime_mean = test_info[\"lagtime_mean\"]\n\n        q  = np.zeros(self.max_seq, dtype=int)\n        qa = np.zeros(self.max_seq, dtype=int)\n        l  = np.zeros(self.max_seq, dtype=float)\n\n        if user_id in self.samples.index:\n            q_, qa_ = self.samples[user_id]\n            l_      = self.lags[user_id]\n            seq_len = len(q_)\n            if seq_len >= self.max_seq:\n                q  = q_ [-self.max_seq:]\n                qa = qa_[-self.max_seq:]\n                l  = l_ [-self.max_seq:]\n            else:\n                q [-seq_len:] = q_\n                qa[-seq_len:] = qa_\n                l [-seq_len:] = l_\n        \n        x1  = q[1:].copy()\n        x1 += (qa[1:] == 1) * self.n_skill\n        x2  = l[1:].copy()\n        questions = np.append(q[2:], [target_id])\n        \n        return x1, x2, questions\n\"\"\"\n# Prediction\n\"\"\"\ndef insert_new_data_to_hist(ary, ins):\n    ary = ary.copy()\n    ary = np.vstack([ary, ins])\n    ary = ary[np.argsort(ary[:,0])]  # Sort by user_id\n    return ary\n\ndef groupby_with_numpy(ary, t_idxs, qucnt):\n    ary = ary.copy()\n    g   = sum([[i+1 for _ in range(c)] for i, c in enumerate(qucnt)], [])\n    r   = np.zeros((qucnt.shape[0], t_idxs.shape[0]))\n    for i, t in enumerate(t_idxs):\n        r[:,i] = np.bincount(g, ary[:,t])[1:]\n    return r\n\ndef add_mistake_feat(df, t_col, n_col):\n    df = df.copy()\n    if df[n_col].min() == 0:\n        df[t_col] = df[n_col].apply(lambda x: 0.6*x**(-0.2) if x!=0 else 0.6)\n    else:\n        df[t_col] = 0.6*df[n_col]**(-0.2)\n    return df\n\ndef get_num_etimes(df):\n    num_etimes = []\n    for u, et in np.array(df[[\"user_id\",\"prior_question_elapsed_time\"]]):\n        if u in d.keys():\n            etime_mean = d_etime[d[u][-1, 1]]\n            et_norm    = et \/ (1000*3600)\n            num_etimes.append(et_norm - etime_mean)\n        else:\n            num_etimes.append(0)\n    return num_etimes\n\ndef add_to_timedict(df):\n    for u, t in np.array(df[[\"user_id\",\"timestamp\"]]):\n        if u in d_timestamp.keys():\n            d_timestamp[u] = np.unique(np.hstack([d_timestamp[u], np.array([t])]))\n        else:\n            d_timestamp[u] = np.array([t])\n\ndef add_to_history(df, new_row_id):\n    for r in np.array(df[[\"user_id\",\"question_id\",\"part\",\"tag1\"]]):\n        if r[0] in d.keys():\n            d[r[0]] = np.vstack([d[r[0]], np.hstack([np.array(new_row_id), r[1:], np.array(0)])])\n        else:\n            d[r[0]] = np.array([np.hstack([np.array(new_row_id), r[1:], np.array(0)])])\n            \ndef upd_history_ans(df):\n    for r in np.array(df[[\"user_id\",\"answered_correctly\"]]):\n        if r[0] in d.keys() and r[1] == 1:\n            d[r[0]][-1,-1] = r[1]\ndf_lecs.drop([\"part\",\"starter\"], axis=1, inplace=True)\ndf_qs = df_qs.merge(df_question_rate, on=[\"question_id\",\"bundle_id\"]).merge(df_part_rate, on=\"part\").merge(df_etime_rate, on=\"question_id\")\ndf_qs.sort_values(\"question_id\", inplace=True)\ndf_qs.reset_index(drop=True, inplace=True)\ndf_qs[\"LorR\"] = 0\ndf_qs.loc[df_qs.part.isin([5,6,7]), \"LorR\"] = 1\n\nprint(df_lecs.shape, df_qs.shape)\ndisplay(df_lecs.head(2))\ndisplay(df_qs.head(2))\nsort_cols    = ['user_id',\"num_exp\",'num_ans','num_devp','num_devm',\"num_etime\",'num_que'] + part_cols + abi_cols\nar_hist      = np.array(df_history[sort_cols])\nar_qs        = np.array(df_qs)[:,0]\nar_ans_class = np.array(df_ans_class)[:,1]\niter_test = env.iter_test()\n#(test_df, sample_prediction_df) = next(iter_test)\n#test_df_bk = test_df.copy()\n#idx = 0\nt_cols  = [\"ans_rate_class\",\"study_rate_class\"] + [f\"part{p}_rate_class\" for p in range(1,8)]\nn_cols  = [\"num_que\",       \"num_que\"]          + num_part_cols\nr_cols  = ['row_id','timestamp','user_id','question_id','content_type_id','task_container_id','prior_question_elapsed_time','prior_question_had_explanation']\ndf_test = pd.DataFrame()\n%%time\nfor idx, (test_df, sample_prediction_df) in enumerate(iter_test):\n    # Modify DataFrame\n    test_df.prior_question_had_explanation = (test_df.prior_question_had_explanation.fillna(False) * 1).astype(int)\n    test_df.prior_question_elapsed_time    = test_df.prior_question_elapsed_time.fillna(0).astype(int)\n    \n    # Get prior correct answer\n    prior_ans = eval(test_df.prior_group_answers_correct.values[0])\n\n    # DataFrame to array\n    test_ary = np.array(test_df)[:,:8]\n    lec_ary  = test_ary[test_ary[:,4]==1, 2:4]\n    test_ary = test_ary[test_ary[:,4]==0, :]\n\n    # Make user information\n    qusers, qucnt = np.unique(np.sort(test_ary[:,2]), return_counts=True)\n    qusers        = qusers.astype(\"int32\")\n    existing_qusers_bol = np.isin(ar_hist[:,0], qusers)\n    not_existing_qusers = qusers[~np.isin(qusers, ar_hist[existing_qusers_bol, 0])]\n\n    # Store some information\n    questions = np.unique(test_ary[:,3].astype(\"int32\"))\n    group_num = test_df.index[:test_ary.shape[0]]\n    \n    # Add the number of correct answering to history\n    if len(prior_ans) != 0 and prior_ans is not None and prior_ans is not np.nan:\n        # Delete lecture data\n        prior_ans = np.array([a for a in prior_ans if a != -1])\n        if 0 < len(prior_ans) and len(prior_ans) == len(prior_test_user_ids) == len(prior_test_devp):\n            df_prev['answered_correctly'] = prior_ans\n            upd_history_ans(df_prev)\n            # Update for SAKT model\n            if ENSEMBLE:\n                prev_group = df_prev.groupby('user_id').apply(lambda x: (x['question_id'].values,\n                                                                         x['answered_correctly'].values,\n                                                                         x[\"lagtime_mean\"].values))\n                for prev_user_id in prev_group.index:\n                    if prev_user_id in group.index:\n                        group[prev_user_id] = (np.append(group[prev_user_id][0], prev_group[prev_user_id][0])[-180:], \n                                               np.append(group[prev_user_id][1], prev_group[prev_user_id][1])[-180:])\n                        lags [prev_user_id] = (np.append(lags [prev_user_id],    prev_group[prev_user_id][2])[-180:])\n\n                    else:\n                        group[prev_user_id] = (prev_group[prev_user_id][0], prev_group[prev_user_id][1])\n                        lags [prev_user_id] = prev_group[prev_user_id][2]\n            # Update for LGBM\n            ans_ary = np.array([prior_test_user_ids,\n                                prior_ans,\n                                prior_test_devp.fillna(9),\n                                prior_test_devm,\n                                prior_test_etime]).T\n            ans_ary = ans_ary[ans_ary[:,2]!=9]\n            if 0 < ans_ary.shape[0]:\n                # The data answered correctly should be aggregated\n                ans_ary[:,2] *= ans_ary[:,1]\n                ans_ary[:,3]  = ans_ary[:,2] + np.where(ans_ary[:,1]==0, -1, 0) * ans_ary[:,3]\n                # Calculate ans and num for each part and user ability\n                part_ans_ary  = prior_test_part * ans_ary[:,1].reshape(-1,1)\n                abi_ans_ary   = prior_test_qc   * ans_ary[:,1].reshape(-1,1)\n                ans_ary = np.hstack([ans_ary,\n                                     np.ones(ans_ary.shape[0]).reshape(-1,1),\n                                     part_ans_ary,\n                                     prior_test_part,\n                                     abi_ans_ary,\n                                     prior_test_qc])\n                ans_ary = ans_ary[np.argsort(ans_ary[:,0])]\n                if len(prior_test_user_ids) != len(np.unique(prior_test_user_ids)):\n                    # Group by user_id because of existing some questions in the user\n                    _, qacnt = np.unique(ans_ary[:,0], return_counts=True)\n                    ans_ary  = groupby_with_numpy(ans_ary, np.arange(1, ans_ary.shape[1]), qacnt)\n                else:\n                    ans_ary  = ans_ary[:,1:]\n                # Update existing data\n                ar_hist[prior_hist_equb, 2:] += ans_ary\n    \n    # Add new users to history\n    if 0 < not_existing_qusers.shape[0]:\n        ins_exp = np.hstack([not_existing_qusers.reshape(-1,1),\n                             np.zeros((not_existing_qusers.shape[0], ar_hist.shape[1]-1))])\n        ar_hist = insert_new_data_to_hist(ar_hist, ins_exp)\n        existing_qusers_bol = np.isin(ar_hist[:,0], qusers)\n    # Update existing data\n    if 0 < test_ary.shape[0]:\n        ary = test_ary[:,[2,7]].copy()\n        ary = ary.astype(int)\n        ary = ary[np.argsort(ary[:,0])]\n        ar_hist[existing_qusers_bol, 1] += groupby_with_numpy(ary, np.array([1]), qucnt).flatten()\n\n    # ========================================\n    # Prediction with LGBM\n    # Merge with some DataFrames\n    df_hist = pd.DataFrame(ar_hist[existing_qusers_bol], columns=sort_cols)\n    df_test = pd.DataFrame(test_ary, columns=r_cols)\n    df_test = df_test.merge(df_hist, on=\"user_id\", sort=False)\n    df_test = df_test.merge(df_qs[np.isin(ar_qs, questions)], on=[\"question_id\",\"prior_question_had_explanation\"], sort=False)\n    \n    # Make features\n    df_test[\"ans_rate\"]   = (df_test.num_ans   \/ df_test.num_que).fillna(0)\n    df_test[\"devp_rate\"]  =  df_test.num_devp  \/ df_test.num_que\n    df_test[\"devm_rate\"]  =  df_test.num_devm  \/ df_test.num_que\n    df_test[\"etime_rate\"] =  df_test.num_etime \/ df_test.num_que\n    ar_study_rate = np.array(df_test.num_exp \/ df_test.num_que)\n    ar_study_rate[np.isnan(ar_study_rate)] = 0\n    ar_study_rate[np.isinf(ar_study_rate)] = 0\n    ar_study_rate[1 < ar_study_rate]       = 1\n    df_test[\"study_rate\"] = ar_study_rate\n    df_class = df_ans_class[np.isin(ar_ans_class, questions)].copy()\n    df_test  = cut_and_merge_with_class(df_test, df_class, \"ans_rate\",   \"ans_rate_class\")\n    df_test  = cut_and_merge_with_class(df_test, df_class, \"study_rate\", \"study_rate_class\")\n    df_test  = add_mistake_feat(df_test, \"prob_mistake_que\", \"num_que\")\n    for p in range(0,10):\n        if p in [0,3,4,5,6,7,8,9]:\n            df_test[f\"abi_rate{p}\"]  = (df_test[f\"ans_abi{p}\"]  \/ df_test[f\"num_abi{p}\"]).fillna(0)\n        if p in [1,2,3,4,5,6,7]:\n            df_test[f\"part{p}_rate\"] = (df_test[f\"ans_part{p}\"] \/ df_test[f\"num_part{p}\"]).fillna(0)\n            df_test = add_mistake_feat(df_test, f\"prob_mistake_part{p}\", f\"num_part{p}\")\n            df_test = cut_and_merge_with_class(df_test, df_class, f\"part{p}_rate\", f\"part{p}_rate_class\")\n    for t, n in zip(t_cols, n_cols):\n        if df_test[n].min() < 5:\n            # Replace to 0.3\/0.5\/0.7 for small answering\n            df_test = change_rate_with_num(df_test, t, n, method=\"respectively\")\n            df_test = change_rate_with_num(df_test, t, n, method=\"bundle\")\n    df_test[\"lagtime1\"]       = (df_test[[\"user_id\",\"timestamp\"]].apply(lambda x: get_lagtime(x[0], x[1], -1), axis=1) \/ (1000*3600)).astype(\"float32\")\n    df_test[\"lagtime2\"]       = (df_test[[\"user_id\",\"timestamp\"]].apply(lambda x: get_lagtime(x[0], x[1], -2), axis=1) \/ (1000*3600)).astype(\"float32\")\n    df_test[\"lagtime3\"]       = (df_test[[\"user_id\",\"timestamp\"]].apply(lambda x: get_lagtime(x[0], x[1], -3), axis=1) \/ (1000*3600)).astype(\"float32\")\n    df_test[\"lagtime_mean\"]   = (df_test.lagtime1 + df_test.lagtime2 + df_test.lagtime3) \/ 3\n    df_test[\"timestamp\"]      = (df_test.timestamp \/ (1000*3600)).astype(\"float32\")\n    df_test[\"lagtime1\"]       = (df_test.timestamp - df_test.lagtime1).astype(\"float32\")\n    df_test[\"lagtime2\"]       = (df_test.timestamp - df_test.lagtime2).astype(\"float32\")\n    df_test[\"lagtime3\"]       = (df_test.timestamp - df_test.lagtime3).astype(\"float32\")\n    df_test[\"lagtime_mean\"]   = np.log((df_test.timestamp - df_test.lagtime_mean) + 1).astype(\"float32\")\n    df_test[\"noplay_days\"]    = (df_test[[\"user_id\",\"timestamp\"]].apply(lambda x: get_noplay_days(x[0], x[1]), axis=1)).astype(\"float32\")\n    df_test[\"elapsed_days\"]   = (df_test.timestamp \/ 24).astype(\"int32\")\n    df_test[\"noplay_rate\"]    = (df_test.noplay_days  \/ df_test.num_que).astype(\"float32\")\n    df_test[\"timestamp_rate\"] = (df_test.timestamp    \/ df_test.num_que).astype(\"float32\")\n    df_test[\"elapsed_rate\"]   = (df_test.elapsed_days \/ df_test.num_que).astype(\"float32\")\n    df_test[\"attempt_que\"]    = df_test[[\"user_id\",\"question_id\"]].apply(lambda x: get_attempt_que(x[0], 101230332+idx, x[1]), axis=1)\n    df_test[\"attempt_tags\"]   = df_test[[\"user_id\",\"tag1\"]].apply(lambda x: get_attempt_tags(x[0], 101230332+idx, x[1]), axis=1)\n    df_test[\"attempt_curtar\"] = df_test[[\"user_id\"]].apply(lambda x: get_attempt_curt_ans_rate(x[0], 101230332+idx), axis=1)\n    all_prob_mistake = np.array(df_test[part_mistake_cols])\n    all_part_rate    = np.array(df_test[[\"part1_rate\",\"part2_rate\",\"part3_rate\",\"part4_rate\",\"part5_rate\",\"part6_rate\",\"part7_rate\"]])\n    all_part_ratec   = np.array(df_test[[\"part1_rate_class\",\"part2_rate_class\",\"part3_rate_class\",\"part4_rate_class\",\"part5_rate_class\",\"part6_rate_class\",\"part7_rate_class\"]])\n    all_abi_rate     = np.array(df_test[[\"abi_rate0\",\"abi_rate3\",\"abi_rate4\",\"abi_rate5\",\"abi_rate6\",\"abi_rate7\",\"abi_rate8\",\"abi_rate9\"]])\n    one_hot_part     = np.identity(8) [df_test.part][:,1:]\n    one_hot_ability  = np.identity(10)[df_test.question_rate_class_exp][:,[0,3,4,5,6,7,8,9]]\n    df_test[\"prob_mistake_part_curt\"] = np.nanmax(one_hot_part*all_prob_mistake, axis=1)\n    df_test[\"part_rate_curt\"]         = np.nanmax(one_hot_part*all_part_rate,    axis=1)\n    df_test[\"part_ratec_curt\"]        = np.nanmax(one_hot_part*all_part_ratec,   axis=1)\n    df_test[\"abi_rate_curt\"]          = np.nanmax(one_hot_ability*all_abi_rate,  axis=1)\n    df_test[\"part_ratec_mean\"]        = np.nan_to_num(all_part_ratec).sum(1) \/ 7\n    df_test[\"harmonic_ar_prc\"]        = 2 * (df_test.ans_rate         * df_test.part_rate_curt)    \/ (df_test.ans_rate         + df_test.part_rate_curt)\n    df_test[\"harmonic_arc_qr\"]        = 2 * (df_test.ans_rate_class   * df_test.question_rate_exp) \/ (df_test.ans_rate_class   + df_test.question_rate_exp)\n    df_test[\"harmonic_arc_prcc\"]      = 2 * (df_test.ans_rate_class   * df_test.part_ratec_curt)   \/ (df_test.ans_rate_class   + df_test.part_ratec_curt)\n    df_test[\"harmonic_prc_pr\"]        = 2 * (df_test.part_rate_curt   * df_test.part_rate)         \/ (df_test.part_rate_curt   + df_test.part_rate)\n    df_test[\"harmonic_prcc_qr\"]       = 2 * (df_test.part_ratec_curt  * df_test.question_rate_exp) \/ (df_test.part_ratec_curt  + df_test.question_rate_exp)\n    df_test[\"harmonic_qr_pr\"]         = 2 * (df_test.part_rate        * df_test.question_rate_exp) \/ (df_test.part_rate        + df_test.question_rate_exp)\n    df_test[\"harmonic_abrc_qr\"]       = 2 * (df_test.abi_rate_curt    * df_test.question_rate_exp) \/ (df_test.abi_rate_curt    + df_test.question_rate_exp)\n    df_test[\"harmonic_arc_src\"]       = 2 * (df_test.ans_rate_class   * df_test.study_rate_class)  \/ (df_test.ans_rate_class   + df_test.study_rate_class)\n    df_test[\"harmonic_prcc_src\"]      = 2 * (df_test.part_ratec_curt  * df_test.study_rate_class)  \/ (df_test.part_ratec_curt  + df_test.study_rate_class)\n    df_test[\"harmonic_src_qr\"]        = 2 * (df_test.study_rate_class * df_test.question_rate_exp) \/ (df_test.study_rate_class + df_test.question_rate_exp)\n    df_test[\"rate_arc_prcc\"]          = df_test.ans_rate_class  \/ df_test.part_ratec_curt\n    df_test[\"rate_arc_src\"]           = df_test.ans_rate_class  \/ df_test.study_rate_class\n    df_test[\"rate_prcc_src\"]          = df_test.part_ratec_curt \/ df_test.study_rate_class\n    df_test[\"rate_arc_qr\"]            = df_test.ans_rate_class  \/ df_test.question_rate_exp\n    df_test[\"rate_qr_pr\"]             = df_test.part_rate       \/ df_test.question_rate_exp\n    df_test[\"rate_prcc_prccm\"]        = df_test.part_ratec_curt \/ df_test.part_ratec_mean\n\n    # Store prior infomation for next batch\n    prior_hist_equb     = existing_qusers_bol\n    prior_test_user_ids = np.array(df_test.user_id).astype(\"int32\")\n    prior_test_part     = one_hot_part\n    prior_test_qc       = one_hot_ability\n    prior_test_devp     = df_test.deviation_p\n    prior_test_devm     = df_test.deviation_m\n    prior_test_etime    = get_num_etimes(df_test)\n\n    # Fill Nan by 0\n    df_test.fillna(0, inplace=True)\n    \n    # Sort to default order\n    df_test.sort_values(\"row_id\",  inplace=True)\n    df_test.reset_index(drop=True, inplace=True)\n    \n    if idx < 1:\n        display(test_df)\n        display(df_test[features+categoricals])\n\n    # Prediction\n    reults = np.zeros(df_test.shape[0])\n    for model in models:\n        reults += model.predict(df_test[features+categoricals], num_iteration=model.best_iteration) \/ len(models)\n        \n    # ========================================\n    # Prediction with SAKT model\n    if ENSEMBLE:\n        outs = []\n        test_dataset    = TestDataset(group, lags, df_test[[\"user_id\",\"question_id\",\"lagtime_mean\"]])\n        test_dataloader = DataLoader(test_dataset, batch_size=df_test.shape[0], shuffle=False)\n        for item in test_dataloader:\n            x1 = item[0].to(device).long()\n            x2 = item[1].to(device).float()\n            target_id = item[2].to(device).long()\n            with torch.no_grad():\n                output, att_weight = nn_model(x1, x2, target_id)\n            outs.extend(torch.sigmoid(output)[:, -1].view(-1).data.cpu().numpy())\n            \n    # ========================================\n    # Submit and post processing for the next batch\n    if ENSEMBLE:\n        df_test['answered_correctly'] = S * np.array(outs) + L * reults\n    else:\n        df_test['answered_correctly'] = reults\n\n    # Add current timestamp to time dict\n    add_to_timedict(test_df)\n    # Add current data to history\n    add_to_history(df_test, 101230332+idx)\n    # Store for updating knowledges for SAKT model\n    df_prev = df_test[['user_id','question_id',\"lagtime_mean\"]].copy()\n        \n    # Submit to predict function\n    df_test = df_test[['row_id', 'answered_correctly']].copy()\n    df_test.index = group_num\n    env.predict(df_test)","meta":"{'source': 'AI4Code', 'id': '604b9864be26cf'}"}
{"id":"67072","text":"\"\"\"\n# Terrorism In Turkey 1996-2017\n\"\"\"\n\"\"\"\nThis kernel about the terrorism actions in Turkey between 1996 and 2017. I visualized the number of killed and wounded in actions which occured in the east and west sides of Turkey. You can find whole dataset here: https:\/\/www.kaggle.com\/northon\/globalterrorismdatabase-compact . I changed this dataset for my purpose: https:\/\/www.kaggle.com\/egebozoglu\/terrorism-in-turkey-19962017\n\n\"\"\"\n\"\"\"\n## Relevant Libraries\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt # data visualization\nimport seaborn as sns\nsns.set()\n\n\n\"\"\"\n## Import the Data\n\"\"\"\ntr = pd.read_csv(\"..\/input\/TableOfTurkey.csv\") ## https:\/\/www.kaggle.com\/egebozoglu\/terrorism-in-turkey-19962017\ntr.head()\ntr.describe(include=\"all\")\n\"\"\"\n## Take the numbers of 'Killed' and 'Wounded' for West. \n\"\"\"\nistkill = tr[tr[\"city\"] == \"Istanbul\"][\"Killed\"].sum()\nistwound = tr[tr[\"city\"] == \"Istanbul\"][\"Wounded\"].sum()\n\nankkill = tr[tr[\"city\"] == \"Ankara\"][\"Killed\"].sum()\nankwound = tr[tr[\"city\"] == \"Ankara\"][\"Wounded\"].sum()\n\nizmkill = tr[tr[\"city\"] == \"Izmir\"][\"Killed\"].sum()\nizmwound = tr[tr[\"city\"] == \"Izmir\"][\"Wounded\"].sum()\n\nwestkill = istkill + izmkill + ankkill\nwestwound = istwound + izmwound + ankwound\nwestintwound = int(westwound)\n\"\"\"\n## Do the same for East.\n\"\"\"\ncizkill = (tr[tr[\"city\"] == \"Cizre\"][\"Killed\"].sum()) + (tr[tr[\"city\"] == \"Cizre district\"][\"Killed\"].sum())\ncizwound = (tr[tr[\"city\"] == \"Cizre\"][\"Wounded\"].sum()) + (tr[tr[\"city\"] == \"Cizre district\"][\"Wounded\"].sum())\n\ndiykill = tr[tr[\"city\"] == \"Diyarbakir\"][\"Killed\"].sum()\ndiywound = tr[tr[\"city\"] == \"Diyarbakir\"][\"Wounded\"].sum()\n\nsirkill = tr[tr[\"city\"] == \"Sirnak\"][\"Killed\"].sum()\nsirkwound = tr[tr[\"city\"] == \"Sirnak\"][\"Wounded\"].sum()\n\nyukskill = (tr[tr[\"city\"] == \"Yuksekova\"][\"Killed\"].sum()) + (tr[tr[\"city\"] == \"Yuksekova district\"][\"Killed\"].sum())\nyukswound = (tr[tr[\"city\"] == \"Yuksekova\"][\"Wounded\"].sum()) + (tr[tr[\"city\"] == \"Yuksekova district\"][\"Wounded\"].sum())\n\ncukkill = tr[tr[\"city\"] == \"Cukurca\"][\"Killed\"].sum()\ncukwound = tr[tr[\"city\"] == \"Cukurca\"][\"Wounded\"].sum()\n\nvankill = tr[tr[\"city\"] == \"Van\"][\"Killed\"].sum()\nvanwound = tr[tr[\"city\"] == \"Van\"][\"Wounded\"].sum()\n\nbingkill = tr[tr[\"city\"] == \"Bingol\"][\"Killed\"].sum()\nbingwound = tr[tr[\"city\"] == \"Bingol\"][\"Wounded\"].sum()\n\nsemdkill = (tr[tr[\"city\"] == \"Semdinli\"][\"Killed\"].sum()) + (tr[tr[\"city\"] == \"Semdinli district\"][\"Killed\"].sum())\nsemdwound = (tr[tr[\"city\"] == \"Semdinli\"][\"Wounded\"].sum()) + (tr[tr[\"city\"] == \"Semdinli district\"][\"Wounded\"].sum())\n\neastkill = semdkill + bingkill + vankill + cizkill + cukkill + diykill + sirkill + yukskill\neastwound = semdwound + bingwound + vanwound + cizwound + cukwound + diywound + sirkwound + yukswound\neastintwound = int(eastwound)\n\"\"\"\n## Prepare the data with Numpy Arrays\n\"\"\"\nn_groups = 2\ny = np.array([eastkill,westkill])\nz = np.array([eastwound,westwound])\n\"\"\"\n## It's time to use Matplotlib for visualize our analysis\n\"\"\"\nfig, ax = plt.subplots(figsize=(10,6))\nindex = np.arange(n_groups)\nbar_widht = 0.2\nopacity = 0.8\n\nkilled = plt.bar(index, y, bar_widht, alpha=opacity, color = \"r\",label=\"KILLED\")\nwounded = plt.bar(index+bar_widht, z, bar_widht, alpha=opacity, color = \"g\", label=\"WOUNDED\")\n\nplt.xlabel(\"REGION\",size=18)\nplt.ylabel(\"NUMBER\",size=18)\nplt.title(\"TERRORISM IN TURKEY (East-West)\",size=25)\nplt.xticks(index + bar_widht, ((\"EAST, Killed:\", eastkill, \"Wounded:\", eastintwound),(\"WEST, Killed:\", westkill, \"Wounded:\",westintwound)))\nplt.legend()\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': '7b8e89721c781e'}"}
{"id":"109628","text":"\"\"\"\n# Audiobooks Customer Return Prediction\n\"\"\"\n\"\"\"\n# Information about Input data\n\nThe data in CSV is without headers and some level of pre-processing is already done. \nFor instance, the missing values of rating field are filled with the mean value (8.91)\n\nThe columns are as follows (in order)\n\n1. Customer ID\n2. Total minutes of all the audio books purchased\n3. Average minutes of all the audio books purchased\n4. Total price\n5. Average price\n6. Review ( 0 = Did not submit review, 1 = Submitted review )\n7. Review out of 10\n8. Minutes listened\n9. Completion percent\n10. Support requests made\n11. ( Last visited date - Purchase date )\n12. Customer returned to buy new audiobook (Target value) ( 1 = Customer returned, 0 = Customer did not return )\n\"\"\"\n\"\"\"\n## Imports\n\"\"\"\nimport numpy as np\nfrom sklearn import preprocessing\nimport tensorflow as tf\n\"\"\"\n## Preprocessing\n\n1. Shuffling the data to remove any time bias.\n2. Balancing the target data as 50\/50 to remove the learning bias.\n3. Standardizing the inputs\n4. Shuffling again to make sure train, validation and test data set are unbiased\n\nThere are 10 input fields except ID column and 1 Target field.\n\"\"\"\n# Extract\nraw_csv_data = np.loadtxt('..\/input\/audiobook-store-customer\/Audiobooks_data.csv',delimiter=',')\n\n\n# Shuffle\nshuffled_indices = np.arange(raw_csv_data.shape[0])\nnp.random.shuffle(shuffled_indices)\nshuffled_inputs = raw_csv_data[shuffled_indices]\n\n\n# Separate Input and Target\ninputs_all = shuffled_inputs[:,1:-1]\ntargets_all = shuffled_inputs[:,-1]\n\n\n# Balance data set by removing the excessive 0 targets as it will bias the learnig of model\none_targets_count = int(np.sum(targets_all))\nzero_targets_count = 0\nindices_to_remove = []\n\nfor i in range(targets_all.shape[0]):\n    if targets_all[i] == 0:\n        zero_targets_count += 1\n        if zero_targets_count > one_targets_count:\n            indices_to_remove.append(i)\n            \nbalanced_inputs_all = np.delete(inputs_all, indices_to_remove, axis=0)\nbalanced_targets_all = np.delete(targets_all, indices_to_remove, axis=0)\n\n\n# Standardize the input values\nstd_inputs = preprocessing.scale(balanced_inputs_all)\n\n\n# Shuffle again\nshuffled_indices = np.arange(inputs.shape[0])\nnp.random.shuffle(shuffled_indices)\n\ninputs = std_inputs[shuffled_indices]\ntargets = balanced_targets_all[shuffled_indices]\n\"\"\"\n# Split the dataset into Train, Validation, and Test sets\n\nDataset is split in 80\/10\/10 parts. \n\"\"\"\n# Total samples\nsamples = inputs.shape[0]\n\n# Split count\ntrain_samples_count = int(0.8 * samples)\nvalidation_samples_count = int(0.1 * samples)\ntest_samples_count = samples - train_samples_count - validation_samples_count\n\n# Creating train set\ntrain_inputs = inputs[:train_samples_count]\ntrain_targets = targets[:train_samples_count]\n\n# Creating validation set\nvalidation_inputs = inputs[train_samples_count:train_samples_count+validation_samples_count]\nvalidation_targets = targets[train_samples_count:train_samples_count+validation_samples_count]\n\n# Creating test set\ntest_inputs = inputs[train_samples_count+validation_samples_count:]\ntest_targets = targets[train_samples_count+validation_samples_count:]\n\n# Print the number of targets that are 1s, the total number of samples, and the proportion for training, validation, and test.\nprint(\"---Train---\")\nprint(np.sum(train_targets), train_samples_count, np.sum(train_targets) \/ train_samples_count)\nprint(\"---Validation---\")\nprint(np.sum(validation_targets), validation_samples_count, np.sum(validation_targets) \/ validation_samples_count)\nprint(\"---Test---\")\nprint(np.sum(test_targets), test_samples_count, np.sum(test_targets) \/ test_samples_count)\n\"\"\"\n# Create *.npz for model\n\"\"\"\nnp.savez('.\/Audiobooks_data_train', inputs=train_inputs, targets=train_targets)\nnp.savez('.\/Audiobooks_data_validation', inputs=validation_inputs, targets=validation_targets)\nnp.savez('.\/Audiobooks_data_test', inputs=test_inputs, targets=test_targets)\n\"\"\"\n# Load npz files\n\"\"\"\n# Train set\nnpz = np.load('Audiobooks_data_train.npz')\ntrain_inputs, train_targets = npz['inputs'].astype(np.float), npz['targets'].astype(np.int)\n\n# Validation set\nnpz = np.load('Audiobooks_data_validation.npz')\nvalidation_inputs, validation_targets = npz['inputs'].astype(np.float), npz['targets'].astype(np.int)\n\n# Test set\nnpz = np.load('Audiobooks_data_test.npz')\ntest_inputs, test_targets = npz['inputs'].astype(np.float), npz['targets'].astype(np.int)\n\"\"\"\n# Model \n\"\"\"\ninput_size = 10\noutput_size = 2\n\n# Configuring the NN values. Hidden layers = 2\nhidden_layer_size = 50\nbatch_size = 120\nmax_epochs = 100\n\n# Early stopping mechanism with 2 patience level. Which means the model will continue learing until the error has been minimized \n# and cannot minimize further. The model will stop learning after 2 (patience level) such instances\nearly_stopping = tf.keras.callbacks.EarlyStopping(patience=2)\n        \nmodel = tf.keras.Sequential([\n    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # 1st hidden layer\n    tf.keras.layers.Dense(hidden_layer_size, activation='relu'), # 2nd hidden layer    \n    tf.keras.layers.Dense(output_size, activation='softmax') # output layer\n])\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(train_inputs, \n          train_targets, \n          batch_size=batch_size, \n          epochs=max_epochs, \n          callbacks=[early_stopping], \n          validation_data=(validation_inputs, validation_targets), \n          verbose = 2 \n          )  \n\"\"\"\n# Testing the model\n\"\"\"\ntest_loss, test_accuracy = model.evaluate(test_inputs, test_targets,verbose=0)\nprint('\\nTest loss: {0:.2f}. Test accuracy: {1:.2f}%'.format(test_loss, test_accuracy*100.))","meta":"{'source': 'AI4Code', 'id': 'c971c03bdd260d'}"}
{"id":"56986","text":"import random, re, math, os, shutil\nimport numpy as np, pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm.notebook import trange, tqdm\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nimport tensorflow as tf, tensorflow.keras.backend as K\nfrom kaggle_datasets import KaggleDatasets\nprint('Tensorflow version ' + tf.__version__)\nfrom sklearn.model_selection import KFold\n\n\"\"\"\n# TPU\/ GPU\/ CPU Configuration\n\"\"\"\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n# Data access\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path('hackerearthaicrowddata')\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification')\nGCS_PATH = GCS_DS_PATH  + '\/train_tfrecords\/'\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '*.tfrec')[:13]\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '*.tfrec')[13:]\nTEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '\/test_tfrecords\/*.tfrec')\nprint(len(TRAINING_FILENAMES), len(VALIDATION_FILENAMES), len(TEST_FILENAMES))\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Configuration\nIMAGE_SIZE = [512,512]\nEPOCHS = 2\nFOLDS = 3\nSEED = 777\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync #previously 16\n\"\"\"\n# Mixed Precision and\/or XLA\nThe following booleans can enable mixed precision and\/or XLA on GPU\/TPU. By default TPU already uses some mixed precision but we can add more. These allow the GPU\/TPU memory to handle larger batch sizes and can speed up the training process. The Nvidia V100 GPU has special Tensor Cores which get utilized when mixed precision is enabled. Unfortunately Kaggle's Nvidia P100 GPU does not have Tensor Cores to receive speed up.\n\"\"\"\nMIXED_PRECISION = False\nXLA_ACCELERATE = False\n\nif MIXED_PRECISION:\n    from tensorflow.keras.mixed_precision import experimental as mixed_precision\n    if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')\n    else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')\n    mixed_precision.set_policy(policy)\n    print('Mixed precision enabled')\n\nif XLA_ACCELERATE:\n    tf.config.optimizer.set_jit(True)\n    print('Accelerated Linear Algebra enabled')\nCLASSES = ['0', '1', '2', '3', '4']\n\"\"\"\n# Checkpoints and LRSchedulers\n\"\"\"\n# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) \/ LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nrng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.figure(figsize=(10,6))\nplt.plot(rng, y, '*-')\nplt.grid(axis='both')\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))\n\n\n\nearly_stopping = tf.keras.callbacks.EarlyStopping( monitor='val_loss', \n                                                  min_delta=0.001, \n                                                  patience=3, \n                                                  verbose=0, \n                                                  mode='auto',\n                                                  baseline=None, \n                                                  restore_best_weights=True)\n\ncheckpoint = tf.keras.callbacks.ModelCheckpoint('weights-epoch-{epoch:02d}-val_loss-{val_loss:.2f}.hdf5', \n                                                monitor='val_loss', \n                                                save_best_only=True,\n                                                save_weights_only=True, \n                                                mode='auto', save_freq='epoch')\n\ncallbacks = [lr_callback, early_stopping, checkpoint]\n\"\"\"\n# Dataset Helper Functions:\n\"\"\"\ndef to_float32(image, label):\n    return tf.cast(image, tf.float32), label\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    #image = tf.cast(image, tf.float32) \/ 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"target\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element   \n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['target'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.keras.preprocessing.image.random_rotation(image, 15)\n    image = tf.image.random_jpeg_quality(image, 75, 95)\n\n    \n#     image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize\/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize\/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)\/\/rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE\/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE\/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING\/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\n\"\"\"\n# Dataset Summary\n\n\"\"\"\nNUM_TRAINING_IMAGES = int( count_data_items(TRAINING_FILENAMES))\nNUM_VALIDATION_IMAGES = int( count_data_items(VALIDATION_FILENAMES))\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\n\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\"\"\"\n# First Look at the Data\n\"\"\"\n# Peek at training data\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)\ndisplay_batch_of_images(next(train_batch))\nwith strategy.scope():\n    #img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.xception.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n    #pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False)\n    \n#     img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.vgg16.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n#     pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False)\n\n    pretrained_model = tf.keras.applications.DenseNet169(include_top=False, weights=\"imagenet\", input_shape=[*IMAGE_SIZE, 3])\n    \n    pretrained_model.trainable = False # False = transfer learning, True = fine-tuning\n    \n    model = tf.keras.Sequential([\n#         img_adjust_layer,\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel.summary()\n# TPUs need images in float format\ntraining_dataset = get_training_dataset().map(to_float32)\nvalidation_dataset = get_validation_dataset().map(to_float32)\nhistory = model.fit(training_dataset, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=20, \n                    validation_data=validation_dataset,\n                    callbacks = callbacks)\npretrained_model.trainable = True # False = transfer learning, True = fine-tuning\nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel.summary()\nhistory2 = model.fit(training_dataset, \n                     steps_per_epoch=STEPS_PER_EPOCH, \n                     epochs=3, \n                     validation_data=validation_dataset,\n                     callbacks = callbacks)\nmodel.save('saved_model_denseNet_169_full.h5')\n# load our test dataset for EDA\ntesting_dataset = get_test_dataset()\ntesting_dataset = testing_dataset.unbatch().batch(20)\ntest_batch = iter(testing_dataset)\ntest_ds = get_test_dataset(ordered=True) \ntest_ds = test_ds.map(to_float32)\n\nprint('Computing predictions...')\ntest_images_ds = testing_dataset\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\ntest_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\ntest_ds = test_ds.map(to_float32)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\n# print('Generating submission.csv file...')\n# test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n# test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n# np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n# !head submission.csv\npredictions.tolist()\nsub = pd.read_csv('..\/input\/cassava-leaf-disease-classification\/sample_submission.csv')\nsub['label'] = predictions.tolist()\nsub.to_csv('submission.csv', index= False)","meta":"{'source': 'AI4Code', 'id': '69242736c5a6ac'}"}
{"id":"43367","text":"\"\"\"\n# Introduction\n\nHello everyone! This is my data analysis with the video game sales dataset. I am actually very excited to explore more about this dataset because I am myself a video game fan. So let's load the data and take a quick look!\n\"\"\"\n# 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\nimport pandas as pd\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport math\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import GridSearchCV\nimport plotly.express as px\nfrom sklearn.model_selection import train_test_split, KFold, cross_validate, cross_val_score\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\nfull_data = pd.read_csv('\/kaggle\/input\/videogamesales\/vgsales.csv')\nfull_data.head()\nprint(full_data.columns.unique())\nlen(full_data.columns.unique())\nfull_data.info()\nprint(full_data.columns[full_data.isna().any()].unique())\nlen(full_data.columns[full_data.isna().any()].unique())\n\"\"\"\nOK, so we see that this dataset contains 11 columns of information.\n\n\n**The columns are:**\n\n* Rank - Ranking of overall sales, integer\n\n* Name - The games name\n\n* Platform - Platform of the games release (i.e. PC,PS4, etc.), object\n\n* Year - Year of the game's release, float\n\n* Genre - Genre of the game ,object\n\n* Publisher - Publisher of the game, object\n\n* NA_Sales - Sales in North America (in millions), float\n\n* EU_Sales - Sales in Europe (in millions), float\n\n* JP_Sales - Sales in Japan (in millions), float\n\n* Other_Sales - Sales in the rest of the world (in millions), float\n\n* Global_Sales - Total worldwide sales, float\n\n\nWe also see that two of the columns contain missing values. Let's take a quick look at these two columns.\n\"\"\"\n\"\"\"\n**Year**\n\"\"\"\nfull_data['Year'].isna().sum()\nfull_data['Year'].isna().sum() \/ full_data['Year'].count() * 100\n\"\"\"\nSince only 1.6% of the data has missing values, I think it is OK to fill the missing value. So let's take a deeper look at the data and how we can impute missing values.\n\"\"\"\nfull_data.loc[full_data['Year'].isna()].head()\nplt.figure(figsize=(15, 10))\nplt.title(\"Years\")\nsns.distplot(a=full_data['Year'])\nplt.show()\n\nfull_data['Year'].value_counts() \/ full_data['Year'].dropna().count() * 100\n\"\"\"\nSince there is not a single year that is very common, I will not fill missing values with the median or something similar. Instead, let's see if we can use a classifier to predict missing values. First, let's see which columns are most correlated with Years:\n\"\"\"\nyear_corr = full_data.corr()[\"Year\"]\nyear_corr.abs().sort_values(ascending=False)[1:]\n\"\"\"\nSo Rank and JP_Sales are the two numerical variables that are correlated with Year. Let's now see if there are categorical variables that are correlated:\n\"\"\"\n\"\"\"\n**Platform**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Platform vs. Year\")\nsns.scatterplot(x=full_data['Platform'], y=full_data['Year'])\nplt.show()\n\"\"\"\nThe platform seems to be an indication of the year because there are platforms that didn't release games during the 1980s. So I will include this feature as an input to the model.\n\"\"\"\n\"\"\"\n**Genre**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Genre vs. Year\")\nsns.scatterplot(x=full_data['Genre'], y=full_data['Year'])\nplt.show()\n\"\"\"\nI cannot see a trend here. It seems like each year there are games with every genre created.\n\"\"\"\n\"\"\"\n**Publisher**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Publisher vs. Year\")\nsns.scatterplot(x=full_data['Publisher'], y=full_data['Year'])\nplt.show()\n\"\"\"\nAlthough not very clear, we can see that certain publishers never released games during 1980s. So publisher perhaps can also be an useful variable to add to our model.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nyear_num_features = ['Rank', 'JP_Sales']\nyear_cat_features = ['Publisher', 'Platform']\nyear_features = year_num_features + year_cat_features\n\nnum_transformer = SimpleImputer(strategy=\"constant\")\n\ncat_transformer = Pipeline(steps=[\n    (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n    (\"onehot\", OneHotEncoder(handle_unknown='ignore'))])\n\npreprocessor = ColumnTransformer(transformers=[(\"num\", num_transformer, year_num_features),\n                                               (\"cat\", cat_transformer, year_cat_features)])\n\nyear_X = full_data.dropna()[year_features]\nyear_Y = full_data.dropna()['Year']\n\nyear_X_train, year_X_test, year_y_train, year_y_test = train_test_split(year_X, year_Y, test_size=0.33, random_state=42)\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nbase_models = [(\"Ada_model\", AdaBoostClassifier(random_state=42)),\n               (\"RF_model\", RandomForestClassifier(random_state=42)),\n               (\"KN_model\", KNeighborsClassifier())]\n\nkfolds = 4 # 4 = 75% train, 25% validation\nsplit = KFold(n_splits=kfolds, shuffle=True, random_state=42)\n\nfor name, model in base_models:\n    model_steps = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model)])\n    \n    model_steps.fit(year_X_train, year_y_train)\n\n    model_preds = model_steps.predict(year_X_test)\n\n    print(f\"{name} accuracy: {accuracy_score(year_y_test, model_preds)}\")\n\"\"\"\nSince Random Forest has the best performance, let's fill missing values using the year it predicts\n\"\"\"\nfinal_year_X_train = full_data[full_data['Year'].notnull()][year_features]\nfinal_year_y_train = full_data[full_data['Year'].notnull()][['Year']]\n\nfinal_year_X_test = full_data[full_data['Year'].isnull()][year_features]\nmodel_steps = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', RandomForestClassifier(random_state=42))])\n\nmodel_steps.fit(final_year_X_train, np.ravel(final_year_y_train))\n\nfinal_model_preds = model_steps.predict(final_year_X_test)\nfull_data.loc[full_data['Year'].isnull(), 'Year'] = final_model_preds\nfull_data['Year'].isna().sum()\n\"\"\"\nNow we have successfully filled the missing values in Year using predictions from a Random Forest Classifier.\n\"\"\"\n\"\"\"\n**Publisher**\n\"\"\"\nfull_data['Publisher'].isna().sum()\nprint(len(full_data['Publisher'].unique()))\nprint(full_data['Publisher'].unique())\nfull_data.loc[full_data['Publisher'].isna()].head(20)\n\"\"\"\nI don't want to drop data, so here I will just give them a Publisher value of 'Unknown'\n\"\"\"\nfull_data.loc[full_data['Publisher'].isna(), 'Publisher'] = 'Unknown'\nfull_data['Publisher'].isna().sum()\n\"\"\"\n# Univariate Data Analysis\n\nNow we have take a quick look at the data. I say we can see more distributions of variables regarding video game sales. (Rank and names obviously don't need to be examined individually)\n\"\"\"\n\"\"\"\n**Platform**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Platforms\")\nsns.countplot(x=full_data['Platform'], order=full_data['Platform'].value_counts().index)\nplt.show()\n\nprint(full_data['Platform'].value_counts() \/ full_data.shape[0] * 100)\n\"\"\"\nSo we see that the most popular platforms are like DS, PS2, PS3, PC, and etc. This follows our expectations.\n\"\"\"\n\"\"\"\n**Year**\n\"\"\"\nplt.figure(figsize=(35, 10))\nplt.title(\"Year\")\nsns.countplot(x=full_data['Year'], order=full_data['Year'].value_counts().index)\nplt.show()\n\nprint(full_data['Year'].value_counts() \/ full_data.shape[0] * 100)\n\"\"\"\nWe see that most games were released around 2010, which I think is partly due to the time this dataset was collected and partly because that time period was when devices like computer or game station really gained popularity.\n\"\"\"\n\"\"\"\n**Genre**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Genre\")\nsns.countplot(x=full_data['Genre'], order=full_data['Genre'].value_counts().index)\nplt.show()\n\nprint(full_data['Genre'].value_counts() \/ full_data.shape[0] * 100)\n\"\"\"\nThis shows that the most popular genres are action and sports. Again, this kinda follows our expectations. Action games are usually the most popular kind.\n\"\"\"\n\"\"\"\n**Publisher**\n\nSince there are too many publishers, let's just focus on the top 10 most popular publishers.\n\"\"\"\ntop_ten = full_data['Publisher'].value_counts().head(10)\nplt.figure(figsize=(15, 10))\nplt.title(\"Publisher\")\nsns.countplot(x=full_data['Publisher'], order=top_ten.index)\nplt.show()\n\nprint(top_ten \/ full_data.shape[0] * 100)\n\"\"\"\nSo basically the companies that sell the most amount of games are like EA, Activision, NBG, Ubisoft, and others. These companies are indeed the most famous ones out there.\n\"\"\"\n\"\"\"\n**Sales in North America**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"North America Sales\")\nsns.distplot(a=full_data['NA_Sales'], kde=False)\nplt.show()\n\nprint(full_data['NA_Sales'].describe())\nplt.figure(figsize=(15, 10))\nplt.title(\"North America Sales\")\nsns.boxplot(x=full_data['NA_Sales'])\nplt.show()\n\nprint(full_data['NA_Sales'].describe())\n\"\"\"\nOK, so we see that the sales in North America is highly right-skewed. Most companies will not even make a million sales in NA, but there is a game that sold 41.49 million times! I wonder what game that is. Let's check out.\n\"\"\"\nfull_data.loc[full_data['NA_Sales'] == 41.49]\n\"\"\"\nWii Sports it is. Also, this is actually the #1 game in the rank! No wonder why the game is this popular in North America.\n\"\"\"\n\"\"\"\n**Sales in Europe**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Europe Sales\")\nsns.distplot(a=full_data['EU_Sales'], kde=False)\nplt.show()\n\nprint(full_data['EU_Sales'].describe())\nplt.figure(figsize=(15, 10))\nplt.title(\"Europe Sales\")\nsns.boxplot(x=full_data['EU_Sales'])\nplt.show()\n\nprint(full_data['EU_Sales'].describe())\n\"\"\"\nAgain, the distribution is highly right skewed. This again indicates that the video game market is somewhat an oligopoly. Most companies will only have a small share in the market, but there are a few that will sell exponentially more. Also, let's check which game has the most sales in Europe. \n\"\"\"\nfull_data.loc[full_data['EU_Sales'] == 29.02]\n\"\"\"\nWell, it is again Wii Sports.\n\"\"\"\n\"\"\"\n**Sales in Japan**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Japan Sales\")\nsns.distplot(a=full_data['JP_Sales'], kde=False)\nplt.show()\n\nprint(full_data['JP_Sales'].describe())\nplt.figure(figsize=(15, 10))\nplt.title(\"Japan Sales\")\nsns.boxplot(x=full_data['JP_Sales'])\nplt.show()\n\nprint(full_data['JP_Sales'].describe())\n\"\"\"\nStill right-skewed, and the game that has the most sale is:\n\"\"\"\nfull_data.loc[full_data['JP_Sales'] == 10.22]\n\"\"\"\nWow! This time it is not Wii Sport! It is actually Pokemon Red\/Blue! This is actually a surprise to me. I would though that since Wii Sport is the number 1 game and is from Japan, Wii Sport would be the number 1 at Japan too. I guess this is the beauty of data analysis.\n\"\"\"\n\"\"\"\n**Sales in the rest of the world**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Other Sales\")\nsns.distplot(a=full_data['Other_Sales'], kde=False)\nplt.show()\n\nprint(full_data['Other_Sales'].describe())\nplt.figure(figsize=(15, 10))\nplt.title(\"Other Sales\")\nsns.boxplot(x=full_data['Other_Sales'])\nplt.show()\n\nprint(full_data['Other_Sales'].describe())\nfull_data.loc[full_data['Other_Sales'] == 10.57]\n\"\"\"\nOK, now for the other parts of the world, GTA San Andreas is actully the most sold game. Again, an interesting thing to learn. \n\"\"\"\n\"\"\"\n**Global Sales**\n\"\"\"\nplt.figure(figsize=(15, 10))\nplt.title(\"Global Sales\")\nsns.distplot(a=full_data['Global_Sales'], kde=False)\nplt.show()\n\nprint(full_data['Global_Sales'].describe())\nplt.figure(figsize=(15, 10))\nplt.title(\"Global Sales\")\nsns.boxplot(x=full_data['Global_Sales'])\nplt.show()\n\nprint(full_data['Global_Sales'].describe())\nfull_data.loc[full_data['Global_Sales'] == 82.74]\n\"\"\"\nNow the global sales is shown. Again, it is visualized, and the game with the most sales is Wii Sport, which is indeed ranked #1 in our dataset.\n\"\"\"\n\"\"\"\n# Define the Question\n\"\"\"\n\"\"\"\nNow we have looked at the data, I begin to be curious about what factors will affect the global sales of a game. Obviously when predicting about this, we cannot use any of the region sale information or the rank as parameters for our model because that is data leakage. Therefore, we are left to only the Platform, Year, Genre, and Publisher columns. So I say let's now work on making a prediction of the global sales based on these four columns and see how accurate the prediction is.\n\"\"\"\n\"\"\"\n# Other Parameters vs. Global Sales\n\nNow since we are curious in how other parameters may affect the final global sales, let's actually visualize the associations between global sales and other parameters we are interested in. \n\"\"\"\n\"\"\"\n**Year vs. Global Sales**\n\"\"\"\nplt.figure(figsize=(35, 10))\nplt.title(\"Year\")\nsns.scatterplot(x=full_data['Year'], y=full_data['Global_Sales'])\nplt.show()\n\"\"\"\nThere isn't really an association between the year and the global sales of games. It is shown that most games would only make minimal global sales despite which year it is. So the global sale isn't really something that depends on the time.\n\"\"\"\n\"\"\"\n**Platform vs. Global Sales**\n\"\"\"\nplt.figure(figsize=(35, 10))\nplt.title(\"Platform\")\nsns.barplot(x=full_data['Platform'], y=full_data['Global_Sales'])\nplt.show()\n\nfor plat in full_data['Platform'].unique():\n    print(plat, \" \", full_data.loc[full_data['Platform'] == plat, 'Global_Sales'].median())\n\"\"\"\nSo now there seems to be a little trend. It seems like games on platforms like Wii, NES, GB do have a higher global sales comparing to games on platforms like SAT. It is very likely that since devices like Wii are more popular, people are more likely to invest money on games that are on these platforms. \n\"\"\"\n\"\"\"\n**Genre vs. Global Sales**\n\"\"\"\nplt.figure(figsize=(35, 10))\nplt.title(\"Genre\")\nsns.barplot(x=full_data['Genre'], y=full_data['Global_Sales'])\nplt.show()\n\nfor genr in full_data['Genre'].unique():\n    print(genr, \" \", full_data.loc[full_data['Genre'] == genr, 'Global_Sales'].median())\n\"\"\"\nAgain, small association between the genre of the game and the global sales. However, still not a significant association.\n\"\"\"\n\"\"\"\n**Publisher vs. Global Sales**\n\"\"\"\nsale_pbl = full_data[['Publisher', 'Global_Sales']]\nsale_pbl = sale_pbl.groupby('Publisher')['Global_Sales'].sum().sort_values(ascending=False).head(20)\nsale_pbl = pd.DataFrame(sale_pbl).reset_index()\n# sale_pbl\nplt.figure(figsize=(15, 10))\nsns.barplot(x='Publisher', y='Global_Sales', data=sale_pbl)\nplt.xticks(rotation=90)\n\"\"\"\nThe publisher also seems to have an effect on the global sales. Essentially, companies like Nintendo or EA are more likely to make games that have high sales. \n\"\"\"\n\"\"\"\nIn conclusion, among these four parameters, it seems like the Year doesn't have a huge impact on the global sale, but the other three parameters all have an impact to certain extent. \n\"\"\"\n\"\"\"\n# Model\n\"\"\"\nnum_features = []\ncat_features = ['Platform', 'Genre', 'Publisher']\n\nfeatures = num_features + cat_features\nX = full_data.drop([\"Global_Sales\"], axis=1)[features]\ny = full_data[\"Global_Sales\"]\n\nnum_transformer = SimpleImputer(strategy=\"constant\")\n\ncat_transformer = Pipeline(steps=[\n    (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n    (\"onehot\", OneHotEncoder(handle_unknown='ignore'))])\n\npreprocessor = ColumnTransformer(transformers=[(\"num\", num_transformer, num_features),\n                                               (\"cat\", cat_transformer, cat_features)])\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\n\nbase_models = [(\"DT_model\", DecisionTreeRegressor(random_state=42)),\n               (\"RF_model\", RandomForestRegressor(random_state=42,n_jobs=-1)),\n               (\"GB_model\", GradientBoostingRegressor(random_state=42)),\n               (\"Ada_model\", AdaBoostRegressor(random_state=42)),\n               (\"KNN_model\", KNeighborsRegressor(n_jobs=-1))]\n\nkfolds = 4 # 4 = 75% train, 25% validation\nsplit = KFold(n_splits=kfolds, shuffle=True, random_state=42)\n\nfor name, model in base_models:\n    model_steps = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model)])\n    \n    model_steps.fit(X_train, y_train)\n\n    model_preds = model_steps.predict(X_test)\n\n    print(f\"{name} mean squared error result: {mean_squared_error(y_test, model_preds)}\")\n\"\"\"\nSo these are the performances of baseline models. From the results we can see Random Forest is again the best baseline model.\n\"\"\"\nparam_grid = { \n    'n_estimators': [100, 500, 1000],\n    'max_depth' : [3, 5, 8, None],\n    'max_features': ['auto', 'sqrt', 'log2']\n}\nfinal_RF_model = RandomForestRegressor(random_state=42, n_estimators=100, max_depth=None, max_features='auto')\n\nmodel_steps = Pipeline(steps=[('preprocessor', preprocessor), ('model', final_RF_model)])\n\nmodel_steps.fit(X_train, y_train)\n\nmodel_preds = model_steps.predict(X_test)\n\nprint(\"Mean Squared Error: \", mean_squared_error(y_test, model_preds))\n\"\"\"\nAfter tuning parameters, I found the default parameters actually have the lowest error. So the final performance of our model is a 3.17 mean squred error when predicting global sales for a video game.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4fe5b90502ac41'}"}
{"id":"88520","text":"\"\"\"\n# Explore Data Science job offers by Company, Location, Industry etc.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\nimport os\ndf = pd.read_csv('..\/input\/data-scientist-jobs\/DataScientist.csv')\ndf.head()\n# remove redundant columns\ndf = df.drop('Unnamed: 0', 1)\ndf = df.drop('index', 1)\ndf.head()\ndf.shape\ndf.columns\n# job titles\ndf['Job Title'].value_counts()\n# show top 25 only\ntemp = df['Job Title'].value_counts()\nsns.barplot(x=temp.index[0:25], y=temp[0:25])\nplt.title('Top 25 - Job Title')\nplt.xticks(rotation=90)\nplt.grid()\nplt.show()\ndf['Salary Estimate'].value_counts()\n# show top 25 only\ntemp = df['Salary Estimate'].value_counts()\nsns.barplot(x=temp.index[0:25], y=temp[0:25])\nplt.title('Top 25 - Salary Estimate')\nplt.xticks(rotation=90)\nplt.grid()\nplt.show()\n\"\"\"\n### The previous evaluation is actually not very helpful. We extract the lower and upper bounds as numeric values in the following.\n\"\"\"\n# Filter out the hourly rates! Set to minus one is this case.\ndef aux1(i_string):    \n    if (i_string.find('Per Hour')>0):\n        return -1\n    else:\n        return pd.to_numeric((i_string.split('K')[0]).split('$')[1])\n\ndef aux2(i_string):\n     if (i_string.find('Per Hour')>0):\n        return -1\n     else:\n        return pd.to_numeric((i_string.split('K')[1]).split('$')[1])\ndf['Salary_LoB'] = list(map(aux1, df['Salary Estimate']))\ndf['Salary_UpB'] = list(map(aux2, df['Salary Estimate']))\ndf.shape\n# for the sake of simplicity: remove the rows with hourly rates... \ndf = df[df['Salary_LoB']!=-1]\ndf.shape\n\"\"\"\n#### So we have lost only a few rows by that...\n\"\"\"\ndf['Salary_Mid'] = (df['Salary_LoB'] + df['Salary_UpB'])\/2\ndf.Salary_LoB.hist(bins=25)\nplt.title('Salary Lower Bound (in 1000 USD)')\nplt.show()\ndf.Salary_LoB.describe()\ndf.Salary_UpB.hist(bins=25)\nplt.title('Salary Upper Bound (in 1000 USD)')\nplt.show()\ndf.Salary_UpB.describe()\ndf.Salary_Mid.hist(bins=25)\nplt.title('Salary Mid Point of range (in 1000 USD)')\nplt.show()\ndf.Salary_Mid.describe()\n# Rating\ndf.Rating.plot(kind='hist')\nplt.title('Rating')\nplt.grid()\nplt.show()\n# Companies\ndf['Company Name'].value_counts()\n# utility function for text cleaning\ndef chop_name(i_string):\n    return i_string.split('\\n')[0]\n# show top 25 only\ntemp = df['Company Name'].value_counts()\nsns.barplot(x=list(map(chop_name,temp.index[0:25])), y=temp[0:25])\nplt.title('Top 25 - Company Name')\nplt.xticks(rotation=90)\nplt.grid()\nplt.show()\n# add clean company name as addition column\ndf['Company'] = list(map(chop_name,df['Company Name']))\ndf['Headquarters'].value_counts()\n# show top 25 only\ntemp = df['Headquarters'].value_counts()\nsns.barplot(x=temp.index[0:25], y=temp[0:25])\nplt.title('Top 25 - Headquarters')\nplt.xticks(rotation=90)\nplt.grid()\nplt.show()\n# Size\ndf['Size'] = df['Size'].replace(\"-1\",\"Unknown\") # merge \"-1\" into \"Unknown\"\ndf['Size'].value_counts().plot(kind='bar')\nplt.grid()\nplt.show()\ndf.Founded.plot(kind='hist')\nplt.title('Founded')\nplt.grid()\nplt.show()\n# show Founded w\/o missings (-1)\ntemp = df.Founded[df.Founded>-1]\nplt.hist(temp,50)\nplt.title('Founded, excluding missing values')\nplt.grid()\nplt.show()\n# Founded summary\ntemp.describe()\n# Type of ownership\ndf['Type of ownership'] = df['Type of ownership'].replace(\"-1\",\"Unknown\") # merge \"-1\" into \"Unknown\"\ndf['Type of ownership'].value_counts().plot(kind='bar')\nplt.grid()\nplt.show()\ndf['Industry'].value_counts()\n# show top 25 only\ntemp = df['Industry'].value_counts()\nsns.barplot(x=temp.index[0:25], y=temp[0:25])\nplt.title('Top 25 - Industry')\nplt.xticks(rotation=90)\nplt.grid()\nplt.show()\ndf['Sector'].value_counts().plot(kind='bar')\nplt.title('Sector')\nplt.grid()\nplt.show()\n# Revenue\ndf['Revenue'] = df['Revenue'].replace(\"-1\",\"Unknown \/ Non-Applicable\") # merge \"-1\" into \"Unknown...\"\ndf['Revenue'].value_counts().plot(kind='bar')\nplt.title('Revenue')\nplt.grid()\nplt.show()\ndf['Easy Apply'].value_counts().plot(kind='bar')\nplt.title('Easy Apply')\nplt.grid()\nplt.show()\n# means by company\ndf_means = df.groupby('Company').mean()\ndf_means.head(25)\n\"\"\"\n#### A few examples\n\"\"\"\nsel_company = 'Amazon'\ndf_means[df_means.index==sel_company]\ndf_temp = df[df.Company==sel_company]\ndf_temp.Salary_Mid.hist()\nplt.title(sel_company)\nplt.show()\nsel_company = 'Apple'\ndf_means[df_means.index==sel_company]\ndf_temp = df[df.Company==sel_company]\ndf_temp.Salary_Mid.hist()\nplt.title(sel_company)\nplt.show()\nsel_company = 'Humana'\ndf_means[df_means.index==sel_company]\ndf_temp = df[df.Company==sel_company]\ndf_temp.Salary_Mid.hist()\nplt.title(sel_company)\nplt.show()\nsel_company = 'Google'\ndf_means[df_means.index==sel_company]\ndf_temp = df[df.Company==sel_company]\ndf_temp.Salary_Mid.hist()\nplt.title(sel_company)\nplt.show()\n\"\"\"\n# Job Descriptions\n\"\"\"\nstopwords = set(STOPWORDS)\ntext = \" \".join(txt for txt in df['Job Description'])\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n### Company specific wordclouds\n\"\"\"\nsel_company = 'Apple'\ndf_temp = df[df.Company==sel_company]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\nsel_company = 'Amazon'\ndf_temp = df[df.Company==sel_company]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\nsel_company = 'Google'\ndf_temp = df[df.Company==sel_company]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\nsel_company = 'Facebook'\ndf_temp = df[df.Company==sel_company]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n### Sector specific wordclouds\n\"\"\"\nsel_sector = 'Information Technology'\ndf_temp = df[df.Sector==sel_sector]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\nsel_sector = 'Finance'\ndf_temp = df[df.Sector==sel_sector]\ntext = \" \".join(txt for txt in df_temp['Job Description'])\n\nwordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=500,\n                      width = 600, height = 400,\n                      background_color=\"white\").generate(text)\nplt.figure(figsize=(12,8))\nplt.imshow(wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n# Find out the \"best\" jobs\n\"\"\"\n# filter \"cool\" jobs\nmin_Rating = 4.5\nmin_SalaryLoB = 150\n\ncool_jobs = df[(df.Rating>=min_Rating) & (df.Salary_LoB>=min_SalaryLoB)]\ncool_jobs.shape\ncool_jobs\n# show location of selected jobs\ncool_jobs.Location.value_counts().plot(kind='bar')\nplt.grid()\nplt.show()\n# filter further, e. g. by location\ncool_jobs_NY = cool_jobs[cool_jobs.Location=='New York, NY']\ncool_jobs_NY\n\"\"\"\n# Compare two locations\n\"\"\"\n# select two locations \nlocation_1 = df[df.Location == 'San Jose, CA']\nlocation_2 = df[df.Location == 'New York, NY']\nprint('New York # Jobs:', location_1.shape[0])\nprint('San Jose # Jobs:', location_2.shape[0])\nprint('Rating New York: ', np.round(location_1.Rating.mean(),2))\nprint('Rating San Jose: ', np.round(location_2.Rating.mean(),2))\nprint('Mid Point Salary New York: ', np.round(location_1.Salary_Mid.mean(),2))\nprint('Mid Point Salary San Jose: ', np.round(location_2.Salary_Mid.mean(),2))\n\"\"\"\n### If you are interested look also at my notebook for Data Engineer Jobs:\nhttps:\/\/www.kaggle.com\/docxian\/data-engineer-jobs\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a25c4fdd4555a5'}"}
{"id":"54519","text":"\"\"\"\n# Bengali.AI: Self-supervised pretraining with Context Encoders (fastai2)\n\nThis notebook implements the paper [Context Encoders: Feature Learning by Inpainting](https:\/\/arxiv.org\/abs\/1604.07379) by Deepak Pathak, Philipp Krahenbuhl, Jeff Donahue, Trevor Darrell and Alexei A. Efros.\n\nMy hypothesis is that a model that can successfully fill in the blanks with Bengali handwritten characters, has a pretty darn good understanding of the Bengali language and thus can be repurposed to classify constituent elements of the characters.\n\n\n## 0. Table of contents\n\n1. Context Encoders overview\n2. Libraries and hyperparams\n3. Generating input and targets\n4. Building the model\n5. Training\n6. Visualising the results\n\"\"\"\n\"\"\"\n## 1. Context Encoders overview\n\nThe Context Encoders paper describes a simple pre-training task: remove stuff from images and have the model try to predict what was removed.\n\n[![image.png](https:\/\/i.postimg.cc\/xTdGCDZC\/image.png)](https:\/\/postimg.cc\/K4d3qVxS)\n\nThe paper describes a number of different techniques for removing stuff. The simplest is to just extract a region from the centre of the image which is what I'm doing in this kernel. In future, I might try the other techniques - I am a little concerned that the task may be a little too easy.\n\nI have made a slight modification to the paper by using EfficientNet-B0 instead of AlexNet for the encoder. Also, I'm only concerning myself with Reconstruction Loss (L2) as I don't mind blurry reconstructions just that the weights can be transferred to the classification task.\n\nIt uses the development version of fastai2.\n\"\"\"\n\"\"\"\n## 2. Libraries and hyperparams\n\"\"\"\n\"\"\"\nThe library makes use of the development version of [fastai2](https:\/\/github.com\/fastai\/fastai2). Since it isn't available in kernels yet, I'll install it alongside [EfficientNet-PyTorch](https:\/\/github.com\/zhoudaxia233\/EfficientUnet-PyTorch).\n\"\"\"\n!pip install git+https:\/\/github.com\/fastai\/fastai2 > \/dev\/null\n!pip install efficientnet-pytorch > \/dev\/null\nfrom pathlib import Path\n\nimport pandas as pd\n\nimport torch\nfrom efficientnet_pytorch import EfficientNet\nfrom torch.utils import model_zoo\n\nfrom fastai2.basics import *\nfrom fastai2.data.all import *\nfrom fastai2.callback.all import *\nfrom fastai2.vision.all import *\nDATA_PATH = Path('\/kaggle\/input\/bengaliai-cv19')\nIMAGE_DATA_PATH = Path('\/kaggle\/input\/grapheme-imgs-128x128')\nOUTPUT_PATH = Path('\/kaggle\/working')\n\nVALID_PCT = 0.2\nSEED = 420\nBATCH_SIZE = 64\nCROP_SIZE = 32\nIMG_SIZE = 128\ntrain_df = pd.read_csv(DATA_PATH\/'train.csv')\n\"\"\"\n## 3. Generating input and targets\n\"\"\"\n\"\"\"\nI'm using 2 transforms: one to remove the centre of an image (the `X`) and another to return just the centre (the `y`).\n\"\"\"\nclass ImageWithCenterRemoved(Transform):\n    \"\"\"Transform that removes the center part of an image.\"\"\"\n    \n    order = 6\n\n    def __init__(self, crop_size=CROP_SIZE):\n        self.crop_size = crop_size\n\n    def encodes(self, x:PILImageBW) -> PILImageBW:\n        x = array(x)\n    \n        start_height = tuple(IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2))\n        start_width = tuple(IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2)) \n        \n        x[\n            ...,\n            start_height:start_height+self.crop_size,\n            start_width:start_width+self.crop_size\n        ] = 0\n    \n        return PILImageBW(Image.fromarray(x))\n    \n    def encodes(self, x:TensorImage):\n        start_height = IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2)\n        start_width = IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2)\n        \n        x[\n            ...,\n            start_height:start_height+self.crop_size,\n            start_width:start_width+self.crop_size\n        ] = 0\n        \n        return TensorImage(x)\n    \n    \nclass ImageWithOnlyCenter(Transform):\n    \"\"\"Transform that keeps only the center part of an image.\"\"\"\n    \n    order = 6\n    \n    def __init__(self, crop_size=CROP_SIZE):\n        self.crop_size = crop_size\n\n    def encodes(self, x:TensorImage) -> PILImageBW:\n        start_height = IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2)\n        start_width = IMG_SIZE \/\/ 2 - (CROP_SIZE \/\/ 2)\n        \n        output = x[\n            ...,\n            start_height:start_height + self.crop_size,\n            start_width:start_width + self.crop_size\n        ]\n\n        return TensorImage(output)\nitems = get_image_files(IMAGE_DATA_PATH)\n\"\"\"\nNext I create a `Datasets` instance splitting the data into a 80\/20 train\/val split.\n\"\"\"\nx_tfms = [PILImageBW.create, ToTensor, ImageWithCenterRemoved()]\ny_tfms = [PILImageBW.create, ToTensor, ImageWithOnlyCenter()]\ntfms = [x_tfms, y_tfms]\n\nsplitter = RandomSplitter(VALID_PCT, seed=SEED)\n\ntds = Datasets(items, tfms, splits=splitter(items))\nimagenet_stats\n\"\"\"\nLastly, I use the ImageNet stats to normalise the data, since I will be using a pretrained EfficientNet-B0 model.\n\"\"\"\ndl_tfms = [IntToFloatTensor,  Normalize(mean=0.485, std=0.229)]\n\ntrain_dl = TfmdDL(tds.train, bs=BATCH_SIZE, after_batch=dl_tfms)\nvalid_dl = TfmdDL(tds.valid, bs=BATCH_SIZE, after_batch=dl_tfms)\n\"\"\"\nAs you can see, we're now successfully cutting the centre out of an image and have the centre crop as the label.\n\"\"\"\ntrain_dl.show_batch()\n\"\"\"\nLastly, I'll put the data into a `DataLoaders` class (formally `DataBunch`).\n\"\"\"\ndata = DataLoaders(train_dl, valid_dl)\n\"\"\"\n## 4. Building the model\n\"\"\"\n\"\"\"\nThe model described below is very similar to a [Unet](https:\/\/arxiv.org\/abs\/1505.04597) model. In that it has an encoder which is responsible for generating a series of downsampled features, then a decoder which upsamples the generates features using a series of fractionally-strided convolution operations.\n\n[![image.png](https:\/\/i.postimg.cc\/BZ2DnZN4\/image.png)](https:\/\/postimg.cc\/t7C7rjLM)\n\nNote that I am omitting the Adversarial Loss, which is more concerned with real looking results - I only want transferability.\n\nFor the encoder, I simply repurpose the [EfficientNet-PyTorch](https:\/\/github.com\/lukemelas\/EfficientNet-PyTorch) model by removing the final classification layers of the model.\n\"\"\"\nclass EfficientNetEncoder(EfficientNet):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        \n        # the initial layer to convolve into 3 channels\n        # idea from https:\/\/www.kaggle.com\/aleksandradeis\/bengali-ai-efficientnet-pytorch-starter\n        self.input_conv = nn.Conv2d(in_channels=1, out_channels=3, kernel_size=1)\n\n    def forward(self, inputs):\n        x = self.input_conv(inputs)\n        return self.extract_features(x)\n    \n    @classmethod\n    def load_pretrained(cls):\n        model_name = 'efficientnet-b0'\n        model = cls.from_name(model_name, override_params={'num_classes': 1})\n        model_dict = model.state_dict()\n\n        state_dict = model_zoo.load_url('https:\/\/publicmodels.blob.core.windows.net\/container\/aa\/efficientnet-b0-355c32eb.pth')\n        state_dict_no_fc = {k: v for k, v in state_dict.items() if not k.startswith('_fc')}\n        model_dict.update(state_dict_no_fc)\n        \n        model.load_state_dict(model_dict)\n\n        return model\n\"\"\"\nFor the decoder, I create a series of fractional convolutions that upsamples the image to the size of the crop. The paper uses BatchNorm and ReLU in the decoder, so I'm doing the same here.\n\"\"\"\ndef up_conv(in_channels, out_channels):\n    return nn.Sequential(\n        nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2),\n        nn.BatchNorm2d(out_channels),\n        nn.ReLU(inplace=True)\n    )\nclass Decoder(nn.Module):\n\n    def __init__(self, encoder, n_channels, out_channels=1):\n        super().__init__()\n\n        self.encoder = encoder\n\n        self.up_conv1 = up_conv(n_channels, 256)    \n        self.up_conv2 = up_conv(256, 128)    # 8x8\n        self.up_conv3 = up_conv(128, 64)    # 16x16\n        self.final_conv = nn.Conv2d(64, out_channels, kernel_size=1)\n    \n    def forward(self, x):\n        x = self.encoder(x)     # input: 1x128x128, output: 1280x4x4\n        x = self.up_conv1(x)    # input: 1280x4x4, output: 256x8x8\n        x = self.up_conv2(x)    # input: 256x8x8, output: 128x16x16\n        x = self.up_conv3(x)    # input: 128x16x16, output: 64x32x32\n        x = self.final_conv(x)  # input: 64x32x32, output: 1x32x32\n        \n        return x\nencoder = EfficientNetEncoder.load_pretrained()\nmodel = Decoder(encoder, n_channels=1280)  # 1280: EfficientNet b0 output. To do: don't hardcode this.\n\"\"\"\n## 5. Training\n\"\"\"\n\"\"\"\nWith everything in place, the model can just be trained like we normally would in Fast.ai. I'm using standard [OneCycle](https:\/\/mc.ai\/finding-good-learning-rate-and-the-one-cycle-policy\/) training as is familiar to people who have done the Fast.ai course or used the library.\n\"\"\"\nif torch.cuda.is_available():\n    print('Cuda available')\n    model = model.cuda()\n    data = data.cuda()\nlearner = Learner(data, model, loss_func=nn.MSELoss())\n# learner.lr_find()\nlearner.fit_one_cycle(4, 1e-3)\nlearner.recorder.plot_loss()\nlearner.validate()\n\"\"\"\n## 6. Visualising results\n\"\"\"\nlearner.show_results(ds_idx=1)\n\"\"\"\nThat looks pretty good.\n\nIn an upcoming kernel, I'll do a mini-ableation study to see if these weights are useful for transfer learning on the competition's multilabel classification problem.\n\"\"\"\nlearner.save('model_cycle_1')","meta":"{'source': 'AI4Code', 'id': '645e106cd9c9de'}"}
{"id":"90138","text":"\"\"\"\n# K Nearest Neighbors with Python\n\nYou've been given a classified data set from a company! They've hidden the feature column names but have given you the data and the target classes. \n\nWe'll try to use KNN to create a model that directly predicts a class for a new data point based off of the features.\n\nLet's grab it and use it!\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ndf = pd.read_csv(\"..\/input\/Classified Data\",index_col=0)\ndf.head()\n\"\"\"\n## Standardize the Variables\n\nBecause the KNN classifier predicts the class of a given test observation by identifying the observations that are nearest to it, the scale of the variables matters. Any variables that are on a large scale will have a much larger effect on the distance between the observations, and hence on the KNN classifier, than variables that are on a small scale.\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(df.drop('TARGET CLASS',axis=1))\nscaled_features = scaler.transform(df.drop('TARGET CLASS',axis=1))\ndf_feat = pd.DataFrame(scaled_features,columns=df.columns[:-1])\ndf_feat.head()\nsns.pairplot(df,hue='TARGET CLASS')\ndf['TARGET CLASS'].value_counts()\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(df_feat,df['TARGET CLASS'],test_size=0.3)\n\"\"\"\n## Using KNN\n\nRemember that we are trying to come up with a model to predict whether someone will TARGET CLASS or not. We'll start with k=1.\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier(n_neighbors=1)\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\n\"\"\"\n### Predictions and Evaluations\nLet's evaluate our KNN model!\n\"\"\"\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import cross_val_score\nprint(confusion_matrix(y_test,pred))\nprint(classification_report(y_test,pred))\n\"\"\"\n### Choosing a K Value\nLet's go ahead and use the elbow method to pick a good K Value:\n\"\"\"\naccuracy_rate = []\nfor i in range(1,40):\n    knn = KNeighborsClassifier(n_neighbors=i)\n    score = cross_val_score(knn,df_feat,df['TARGET CLASS'],cv=10)\n    accuracy_rate.append(score.mean())  \nerror_rate = []\nfor i in range(1,40):\n    knn = KNeighborsClassifier(n_neighbors=i)\n    score = cross_val_score(knn,df_feat,df['TARGET CLASS'],cv=10)\n    error_rate.append(1-score.mean())  \nerror_rate\nerror_rate = []\nfor i in range(1,40):\n    knn = KNeighborsClassifier(n_neighbors=i)\n    knn.fit(X_train,y_train)\n    pred_i = knn.predict(X_test)\n    error_rate.append(np.mean(pred_i != y_test))\nerror_rate\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', marker='o',\n        markerfacecolor='red', markersize=10)\n#plt.plot(range(1,40),accuracy_rate,color='blue', linestyle='dashed', marker='o',\n#         markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')\n\"\"\"\nHere we can see that that after arouns K>23 the error rate just tends to hover around 0.06-0.05 Let's retrain the model with that and check the classification report!\n\"\"\"\n# NOW WITH K=23\nknn = KNeighborsClassifier(n_neighbors=23)\n\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\n\nprint('WITH K=23')\nprint('\\n')\nprint(confusion_matrix(y_test,pred))\nprint('\\n')\nprint(classification_report(y_test,pred))","meta":"{'source': 'AI4Code', 'id': 'a5520768008504'}"}
{"id":"114338","text":"# import the necessary libraries\nimport numpy as np \nimport pandas as pd \n\n# Visualisation libraries\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set()\nfrom plotly.offline import init_notebook_mode, iplot \nimport plotly.graph_objs as go\nimport plotly.offline as py\nimport pycountry\npy.init_notebook_mode(connected=True)\nimport folium \nfrom folium import plugins\nfrom folium.plugins import MarkerCluster\n\n\n# Graphics in retina format \n%config InlineBackend.figure_format = 'retina' \n\n# Increase the default plot size and set the color scheme\nplt.rcParams['figure.figsize'] = 8, 5\n#plt.rcParams['image.cmap'] = 'viridis'\n\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# Disable warnings \nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n# COVID-19 Visual Analysis\n\nOn 31 December 2019, WHO was informed of a cluster of cases of pneumonia of unknown cause detected in Wuhan City, Hubei Province of China. 2019 Novel Coronavirus (COVID-19) is a virus (more specifically, a coronavirus) identified as the cause of an outbreak of respiratory illness first detected in Wuhan, China.\n\nIn addition to providing care to patients and isolating new cases as they are identified, Chinese public health officials have reported that they remain focused on continued contact tracing, conducting environmental assessments at the wholesale market, and investigations to identify the pathogen causing the outbreak. *(source: WHO)\n\"\"\"\n# Reading the dataset\ndata= pd.read_csv(\"\/kaggle\/input\/2020-corona-virus-timeseries\/COVID-19_geo_timeseries_ver_0311.csv\")\ndata.head()\ndata = data[data.data_source=='jhu']\n# Convert Last Update column to datetime64 format\ndata['update_time'] = pd.to_datetime(data['update_time'])\nprint(data['update_time'].dtype)\n# Extract date from the timestamp\ndata['update_date'] = data['update_time'].dt.date\nfrom matplotlib import pyplot as plt\nimport plotly.graph_objects as go\nfrom fbprophet import Prophet\nimport pycountry\nimport plotly.express as px\n\ndf = data[data.data_source=='jhu']\ndf_agg = df.groupby('update_date').agg({'confirmed_cases':'sum','deaths':'sum','recovered':'sum'}).reset_index()\nfig = go.Figure()\nfig.add_trace(go.Bar(x=df_agg['update_date'],\n                y=df_agg['confirmed_cases'],\n                name='Confirmed',\n                marker_color='blue'\n                ))\nfig.add_trace(go.Bar(x=df_agg['update_date'],\n                y=df_agg['deaths'],\n                name='Deaths',\n                marker_color='Red'\n                ))\nfig.add_trace(go.Bar(x=df_agg['update_date'],\n                y=df_agg['recovered'],\n                name='Recovered',\n                marker_color='Green'\n                ))\n\nfig.update_layout(\n    title='Worldwide Corona Virus Cases - Confirmed, Deaths, Recovered',\n    xaxis_tickfont_size=14,\n    yaxis=dict(\n        title='Number of Cases',\n        titlefont_size=16,\n        tickfont_size=14,\n    ),\n    legend=dict(\n        x=0,\n        y=1.0,\n        bgcolor='rgba(255, 255, 255, 0)',\n        bordercolor='rgba(255, 255, 255, 0)'\n    ),\n    barmode='group',\n    bargap=0.15, # gap between bars of adjacent location coordinates.\n    bargroupgap=0.1 # gap between bars of the same location coordinate.\n)\nfig.show()\n# Quick glimpse of the data info\ndata.info()\n\"\"\"\n## Countries affected by the COVID-19\n\"\"\"\n# Countries affected\ncountries = data[(data['country']!='Others') & (data['country']!='Undisclosed')]['country'].unique().tolist()\n# Use this print trick to get more readable list output\nprint(*countries, sep = \"\\n\")\nprint(\"\\nTotal countries affected by COVID-19: \",len(countries))\n\"\"\"\n## Current status worldwide as of Feb 12, 2020\n\"\"\"\n# get the latest timestamp\nlatest_date = data['update_time'].max()\n# extract year, month, day from the latest timestamp so we can use it just report the latest data\nyear = latest_date.year\nmonth = latest_date.month\n# adjust for timezone\nday = latest_date.day - 1\n\n# Filter to only include the latest day data\nfrom datetime import date\ndata_latest = data[data['update_time'] > pd.Timestamp(date(year,month,day))]\ndata_latest.head()\n# Creating a dataframe with total no of confirmed cases for every country as of the latest available date\naffected_country_latest = data_latest.groupby(['country','country_code','region','latitude','longitude','country_flag']).agg({'update_time': np.max}).reset_index()\nkey = ['country','country_code','region','latitude','longitude','country_flag','update_time']\nglobal_cases = pd.merge(data_latest, affected_country_latest, how='inner', on=key).drop_duplicates().groupby(key).max().sort_values(by=['confirmed_cases'],ascending=False).reset_index()\nglobal_cases.index+=1\nglobal_cases_columns = global_cases.columns.tolist()\nglobal_cases_columns.remove('update_time')\nglobal_cases = global_cases[global_cases_columns]\nglobal_cases\n\"\"\"\n## Generating world map\n\"\"\"\nshape_url = '\/kaggle\/input\/python-folio-country-boundaries\/world-countries.json'\nworld_geo = shape_url\n\nm = folium.Map(location=[35.86166,104.195397], zoom_start=3,tiles='Stamen Toner')\n\nfolium.Choropleth(\n    geo_data=world_geo,\n    name='choropleth',\n    data=global_cases,\n    columns=['country', 'confirmed_cases'],\n    key_on='feature.properties.name',\n    fill_color='OrRd',\n    fill_opacity=0.7,\n    line_opacity=0.2,\n    legend_name='Number of Confirmed Cases'\n).add_to(m)\n\nfor lat, lon, value, name in zip(global_cases['latitude'], global_cases['longitude'], global_cases['confirmed_cases'], global_cases['country']):\n    folium.CircleMarker(\n        [lat, lon],\n        radius=10,\n        popup = ('<strong>Country<\/strong>: ' + str(name).capitalize() + '<br>'\n                 '<strong>Confirmed Cases<\/strong>: ' + str(value) + '<br>'),        \n        color='orange',\n        fill=True,\n        fill_color='orange',\n        fill_opacity=0.7\n    ).add_to(m)\n\nfolium.LayerControl().add_to(m)\n\nm\n\"\"\"\n# Interactive World Map with Time Steps (All Dates)\n\"\"\"\n# Creating a dataframe with total no of confirmed cases for every country for all available dates\nkey1 = ['country','country_code','region','latitude','longitude','country_flag','update_date']\nkey2 = ['country','country_code','region','latitude','longitude','country_flag','update_date','confirmed_cases','deaths','recovered']\nkey3 = ['country','country_code','region','latitude','longitude','country_flag']\ndf_full = data[data.data_source == 'jhu'][key2].drop_duplicates().groupby(key1).max().reset_index()\n# df_full = data[key2].drop_duplicates().groupby(key1).max().sort_values(by=['country','update_date']).groupby(key3).cumsum().sort_values(by=['confirmed_cases','update_date'],ascending=[False,False]).reset_index()\n# df_full = df_full.groupby(key1).agg({'confirmed_cases':np.cumsum, 'deaths':np.cumsum ,'recovered':np.cumsum}).reset_index()\ndf_full[['confirmed_cases','deaths','recovered']] = df_full[['confirmed_cases','deaths','recovered']].fillna(0)\ndf_full['log_confirmed_cases'] = np.log(df_full['confirmed_cases'])\ndf_full.sort_values(by=['confirmed_cases','update_date'],ascending=[False,False]).head(10)\nimport plotly\nimport plotly.graph_objs as go\nfrom datetime import datetime\nfrom datetime import timedelta\n\nscl = [[0.0, '#e7e1ef'],[0.2, '#d4b9da'],[0.4, '#c994c7'], \n       [0.6, '#df65b0'],[0.8, '#dd1c77'],[1.0, '#980043']] # reds\n\ndata_slider = []\nall_dates = df_full['update_date'].sort_values().unique()\nfor m,d in zip(pd.DatetimeIndex(all_dates).month,pd.DatetimeIndex(all_dates).day):\n    df_selected = df_full[(pd.DatetimeIndex(df_full['update_date']).month==m) & (pd.DatetimeIndex(df_full['update_date']).day==d)]\n    df_selected['text'] =   'Date: '+ df_selected['update_date'].astype(str) \\\n                            + '<br>' + 'Confirmed Cases: ' + df_selected['confirmed_cases'].astype(str) \\\n                            + '<br>' + 'Deaths: '+ df_selected['deaths'].astype(str) \\\n                            + '<br>' + 'Recovered: '+ df_selected['recovered'].astype(str)\n    data_one_day = dict(\n        type='choropleth',\n        colorscale = scl,\n        autocolorscale=False,\n        locations = df_selected['country'].tolist(),\n        z = df_selected['log_confirmed_cases'].tolist(),\n        locationmode = 'country names',\n        text = df_selected['text'],\n        colorbar_title = 'Confirmed Cases (Logarithm)'\n    )\n    data_slider.append(data_one_day)\n\nsteps = []\nfor i in range(len(data_slider)):\n    step = dict(method='restyle',\n                args=['visible', [False] * len(data_slider)],\n                label=(datetime.strptime('2020-01-21','%Y-%m-%d') + timedelta(days=i)).strftime('%Y-%m-%d')\n               )\n    step['args'][1][i] = True\n    steps.append(step)\n\nsliders = [dict(active=0, pad={\"t\": 1}, steps=steps)]  \n\nlyt = dict(\n    geo=dict(scope='world'), \n    sliders=sliders, \n    title_text = 'COVID-19 Trend Analysis (World)' + '<br>' + '(Hover for breakdown)'\n)\nfig = dict(data=data_slider, layout=lyt)\nplotly.offline.iplot(fig)\n\"\"\"\n# China Visual Analysis by Provinces\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\n#Mainland China\nkey = ['province','country']\nChina = data_latest[data_latest['country']=='China'].groupby(key).agg({'confirmed_cases':np.max,'deaths':np.max,'recovered':np.max,'update_date':np.max}).fillna(0).reset_index()\nChina['log_confirmed_cases'] = np.log(China['confirmed_cases'])\nChina['log_recovered'] = np.log(China['recovered'])\nChina['log_deaths'] = np.log(China['deaths'])\nChina['norm_confirmed_cases'] = scaler.fit_transform(China[['confirmed_cases']])\nChina['norm_recovered'] = scaler.fit_transform(China[['recovered']])\nChina['norm_deaths'] = scaler.fit_transform(China[['deaths']])\nChina = China.sort_values(by='confirmed_cases',ascending=False)\nChina\n\"\"\"\n## Confirmed vs Recovered figures of Provinces of China\nDue to the total number of cases in Hubei Province is much larger than the rest provinces, for better visualization, it's not shown here.\n\"\"\"\nf, ax = plt.subplots(figsize=(12, 8))\n\nsns.set_color_codes(\"pastel\")\n\nsns.barplot(x=\"confirmed_cases\", y=\"province\", data=China[1:],\n            label=\"confirmed_cases\", color=\"r\")\n\nsns.set_color_codes(\"muted\")\nsns.barplot(x=\"recovered\", y=\"province\", data=China[1:],\n            label=\"recovered\", color=\"g\")\n\n# Add a legend and informative axis label\nax.legend(ncol=2, loc=\"lower right\", frameon=True)\nax.set(xlim=(0, 1500), ylabel=\"\",xlabel=\"# cases\",title=\"Confirmed vs Recovered\")\nsns.despine(left=True, bottom=True)\n# prepare China Mainland data\nchina_coordinates= pd.read_csv(\"..\/input\/chinese-cities\/china_coordinates.csv\")\nchina_coordinates.rename(columns={'admin':'province'},inplace=True)\nchina_coordinates = china_coordinates[(china_coordinates.capital == 'admin') | (china_coordinates.capital == 'primary')]\nchina_merged = China.merge(china_coordinates,on='province', how='left')\n\nkey_china = ['province','lat','lng','confirmed_cases','recovered','deaths','log_confirmed_cases','log_recovered','log_deaths','norm_confirmed_cases','norm_recovered','norm_deaths']\nchina_merged = china_merged[key_china].dropna()\nchina_merged\n\"\"\"\n# [Interactive] Heat Map of Confirmed Cases by China's Provinces\n\"\"\"\nimport json\nimport branca\nlatitude = 30.86166\nlongitude = 114.195397\n\nchina_shape_url = '\/kaggle\/input\/china-regions-map\/china-provinces.json'\n\nchina_confirmed_colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 2000)\nchina_confirmed_series = china_merged.set_index('province')['confirmed_cases']\n\ndef confirmed_style_function(feature):\n    china_show = china_confirmed_series.get(str(feature['properties']['NAME_1']), None)\n    return {\n        'fillOpacity': 0.5,\n        'weight': 0,\n        'fillColor': '#black' if china_show is None else china_confirmed_colorscale(china_show)\n    }\n\nchina_confirmed_map = folium.Map(location=[latitude, longitude], zoom_start=4.5,tiles='Stamen Toner')\n\nfolium.TopoJson(\n    json.load(open(china_shape_url)),\n    'objects.CHN_adm1',\n    style_function=confirmed_style_function\n).add_to(china_confirmed_map)\n\nfor lat, lon, rd, value, name in zip(china_merged['lat'], china_merged['lng'], china_merged['log_confirmed_cases'], china_merged['confirmed_cases'], china_merged['province']):\n    folium.CircleMarker([lat, lon],\n                        radius=rd*4,\n                        tooltip = ('Province: ' + str(name).capitalize() + '<br>'\n                        'Confirmed Cases: ' + str(f\"{int(value):,}\") + '<br>'),\n                        color='none',\n                        fill_color='purple',\n                        fill_opacity=0.5 ).add_to(china_confirmed_map)\n\nchina_confirmed_map\n\"\"\"\n# [Interactive] Heat Map of Deceased Cases by China's Provinces\n\"\"\"\nchina_deceased_colorscale = branca.colormap.linear.PuRd_09.scale(0, 20)\nchina_deceased_series = china_merged.set_index('province')['deaths']\n\ndef deceased_style_function(feature):\n    china_show = china_deceased_series.get(str(feature['properties']['NAME_1']), None)\n    return {\n        'fillOpacity': 0.5,\n        'weight': 0,\n        'fillColor': '#black' if china_show is None else china_deceased_colorscale(china_show)\n    }\n\nchina_deceased_map = folium.Map(location=[latitude, longitude], zoom_start=4.5,tiles='Stamen Toner')\n\nfolium.TopoJson(\n    json.load(open(china_shape_url)),\n    'objects.CHN_adm1',\n    style_function=deceased_style_function\n).add_to(china_deceased_map)\n\nfor lat, lon, rd, value, name in zip(china_merged['lat'], china_merged['lng'], china_merged['log_deaths'], china_merged['deaths'], china_merged['province']):\n    folium.CircleMarker([lat, lon],\n                        radius=rd*4,\n                        tooltip = ('Province: ' + str(name).capitalize() + '<br>'\n                        'Deaths: ' + str(f\"{int(value):,}\") + '<br>'),\n                        color='red',\n                        fill_color='black',\n                        fill_opacity=0.5 ).add_to(china_deceased_map)\nchina_deceased_map\n\n\"\"\"\n# [Interactive] Heat Map of Recovered Cases by China's Provinces\n\"\"\"\nchina_recovered_colorscale = branca.colormap.linear.YlGn_09.scale(0, 500)\nchina_recovered_series = china_merged.set_index('province')['recovered']\n\ndef recovered_style_function(feature):\n    china_show = china_recovered_series.get(str(feature['properties']['NAME_1']), None)\n    return {\n        'fillOpacity': 0.5,\n        'weight': 0,\n        'fillColor': '#black' if china_show is None else china_recovered_colorscale(china_show)\n    }\n\nchina_recovered_map = folium.Map(location=[latitude, longitude], zoom_start=4.5,tiles='Stamen Toner')\n\nfolium.TopoJson(\n    json.load(open(china_shape_url)),\n    'objects.CHN_adm1',\n    style_function=recovered_style_function\n).add_to(china_recovered_map)\n\nfor lat, lon, rd, value, name in zip(china_merged['lat'], china_merged['lng'], china_merged['log_recovered'], china_merged['recovered'], china_merged['province']):\n    folium.CircleMarker([lat, lon],\n                        radius=rd*4,\n                        tooltip = ('Province: ' + str(name) + '<br>'\n                        'Recovered: ' + str(f\"{int(value):,}\") + '<br>'),\n                        color='none',\n                        fill_color='#6baed6',\n                        fill_opacity=0.5 ).add_to(china_recovered_map)\nchina_recovered_map","meta":"{'source': 'AI4Code', 'id': 'd227e0f5b010fe'}"}
{"id":"60703","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom PIL import Image\nfrom numpy import asarray\nimport cv2\nimport matplotlib.pyplot as plt\nimport os\n\ndata=[]\nlabel=[]\n\ndir=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','del','nothing','space']\nfor i in dir:\n    j=0\n    print(i)\n    for file in os.listdir('\/kaggle\/input\/asl-alphabet\/asl_alphabet_train\/asl_alphabet_train\/{}'.format(i)):\n        img = Image.open(os.path.join('\/kaggle\/input\/asl-alphabet\/asl_alphabet_train\/asl_alphabet_train\/',i,str(file)))\n        ndata = asarray(img)\n        ndata=cv2.resize(ndata,(100,100)).flatten()\n        data.append(ndata)\n        label.append(i)\n        j+=1\n        if j>1000:\n            break       \nprint(len(data))\ntest_data=[]\ntest_lable=[]\nfor file in os.listdir('\/kaggle\/input\/asl-alphabet\/asl_alphabet_test\/asl_alphabet_test\/'):\n    img = Image.open(os.path.join('\/kaggle\/input\/asl-alphabet\/asl_alphabet_test\/asl_alphabet_test\/',str(file)))\n    ndata = asarray(img)\n    ndata=cv2.resize(ndata,(100,100)).flatten()\n    test_data.append(ndata)\n  \n\nprint(len(test_data))\n\"\"\"\nDecision Tree Classification\n\"\"\"\n#label encoder\nfrom sklearn import preprocessing\n \n# label_encoder object knows how to understand word labels.\nlabel_encoder = preprocessing.LabelEncoder()\n \n# Encode labels in column 'species'.\nlabel= label_encoder.fit_transform(label)\nprint(np.unique(label))\ntest_label = []\nfor i in np.unique(label):\n    if i!= 26:\n        test_label.append(i)\nfrom sklearn.tree import DecisionTreeRegressor \n\ntreemodel = DecisionTreeRegressor(random_state = 0) \n\ntreemodel.fit(data,label)\npred=treemodel.predict(test_data)\npred\nfrom sklearn.metrics import confusion_matrix,accuracy_score\n\nscore = accuracy_score(test_label,pred)\nprint(score)\nmatrix= confusion_matrix(test_label,pred)  \nmatrix\n\"\"\"\n**logistic regression**\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlogisticRegr = LogisticRegression(solver=\"liblinear\")\nlogisticRegr.fit(data,label)\n\nsco=logisticRegr.score(test_data,test_label)\nprint(sco)\n\"\"\"\n**KNN classifier**\n\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier  \nclassifier= KNeighborsClassifier(n_neighbors=6, metric='minkowski', p=2 ) \nclassifier.fit(data,label)\n\npred=classifier.predict(test_data)\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\nmatrixx= confusion_matrix(test_label, pred)  \nprint(\"confusion matrix:\")\nprint(matrixx)\nprint(\"accuracy:\")\nprint(accuracy_score(testY,pred))","meta":"{'source': 'AI4Code', 'id': '6fe4988125cdd4'}"}
{"id":"23219","text":"\"\"\"\n# <span style= color:Aquamarine>Introduction\nWhile the MNIST Dataset , has many good notebooks , this notebooks seems to explain some concepts which might be useful for beginners . Have a look!!\n\"\"\"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n%matplotlib inline \nimport matplotlib as mpl \nimport matplotlib.pyplot as plt \nimport seaborn as sns\nsns.set_style(\"darkgrid\")\nmpl.rc(\"axes\",labelsize=16)\nmpl.rc(\"xtick\",labelsize=14)\nmpl.rc(\"ytick\",labelsize=14)\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\ntrain=pd.read_csv('\/kaggle\/input\/digit-recognizer\/train.csv')\ntest=pd.read_csv('\/kaggle\/input\/digit-recognizer\/test.csv')\ntrain.info()\ntest.info()\ntrain.head()\ntrain_label=train.label\ntrain_data=train.drop(\"label\",axis=1)\nprint(train_label)\nprint(train_data)\ntest.head()\nfrom xgboost import XGBClassifier\nxgb=XGBClassifier()\nsmldata=train_data[0:200]\nsmllabel=train_label[0:200]\nsmldata2=train_data[200:400]\nsmllabel2=train_label[200:400]\nxgb.fit(smldata,smllabel)\ninitial_predictions=xgb.predict(smldata2)\nprint(initial_predictions[0:5])\nprint(train_label[200:205])\nfrom sklearn.metrics import mean_absolute_error\ninit_diff=mean_absolute_error(smllabel,initial_predictions)\nprint(np.sqrt(init_diff))\ntrain_all=train_data.to_numpy()\nsome_digit= train_data.loc[36000]\nsome_digit_image=some_digit.values.reshape(28,28)\nplt.imshow(some_digit_image,cmap='Greys_r',interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.show()\ntrain_data.shape\n\"\"\"\n# <span style= color:Green>Plotting Digits \n\"\"\"\ndef plot_digit(data):\n    image=data.values.reshape(28,28)\n    plt.imshow(image,cmap='Greys_r',interpolation='nearest')\n    plt.axis(\"off\")\n    \nplot_digit(train_data.loc[1])\nprint(type(train_data.loc[1]))\ndef plot_digits(instances, images_per_row=10, **options):\n    flx=instances.to_numpy()\n    size = 28\n    images_per_row = min(len(instances), images_per_row)\n    images = [instance.reshape(size,size) for instance in flx]\n    n_rows = (len(instances) - 1) \/\/ images_per_row + 1\n    row_images = []\n    n_empty = n_rows * images_per_row - len(instances)\n    images.append(np.zeros((size, size * n_empty)))\n    for row in range(n_rows):\n        rimages = images[row * images_per_row : (row + 1) * images_per_row]\n        row_images.append(np.concatenate(rimages, axis=1))\n    image = np.concatenate(row_images, axis=0)\n    plt.imshow(image, cmap = \"Greys_r\", **options)\n    plt.axis(\"off\")\nplt.figure(figsize=(10,10))\nplot_digits(train_data[5:69],images_per_row=10)\nshuffle_index=np.random.permutation(42000)\ntrain_shuffle,label_shuffle=train_data.loc[shuffle_index],train_label.loc[shuffle_index]\ntrain_5=(label_shuffle==5)\n\"\"\"\n## <span style=color:Purple>Using SGD Classifier\n\"\"\"\nfrom sklearn.linear_model import SGDClassifier\nsgd_clf=SGDClassifier(max_iter=5,tol=-np.infty,random_state=17)\nsgd_clf.fit(train_shuffle,train_5)\nsgd_clf.predict([some_digit])\nfrom sklearn.model_selection import cross_val_score\ncross_val_score(sgd_clf,train_shuffle,train_5,cv=3,scoring=\"accuracy\")\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.base import clone\nskfolds=StratifiedKFold(n_splits=3)\n\nfor train_index,test_index in skfolds.split(train_shuffle, train_5):\n    clone_clf=clone(sgd_clf)\n    train_shuffle_folds=train_shuffle.loc[train_index]\n    train_5_folds=train_5.loc[train_index]\n    Test_shuffle_folds=train_shuffle.loc[test_index]\n    Test_5_folds=train_5.loc[test_index]\n    \n    clone_clf.fit(train_shuffle_folds,train_5_folds)\n    pred=clone_clf.predict(Test_shuffle_folds)\n    n_correct=sum(pred==Test_5_folds)\n    print(n_correct\/len(pred))\nfrom sklearn.base import BaseEstimator \nclass Never5Estimator(BaseEstimator):\n    def fit(self,X,y=None):\n        pass\n    def predict(self,X):\n        return np.zeros((len(X),1),dtype=bool)\n\nnever_5_clf=Never5Estimator()\ncross_val_score(never_5_clf,train_shuffle,train_5,cv=3,scoring=\"accuracy\")\nfrom sklearn.model_selection import cross_val_predict\ntrain_pred=cross_val_predict(sgd_clf,train_shuffle,train_5,cv=3)\n\"\"\"\n# <span style= color:skyblue >Confusion Matrix\n\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(train_5,train_pred)\nfrom sklearn.metrics import precision_score, recall_score\nprecision_score(train_5,train_pred)\n2809\/(2809+712)\nrecall_score(train_5,train_pred)\n2809\/(2809+986)\nfrom sklearn.metrics import f1_score\nf1_score(train_5,train_pred)\nscores=sgd_clf.decision_function([some_digit])\nscores\nthreshold=0\nsome_digit_pred=(scores >threshold)\nsome_digit_pred\nthreshold=140000\nsome_digit_pred=(scores >threshold)\nsome_digit_pred\nscores=cross_val_predict(sgd_clf,train_shuffle,train_5,cv=3,method='decision_function')\nscores.shape\n\"\"\"\n# <span style=color:Coral>Precision Recall Curve\nPrecision-Recall is a useful measure of success of prediction when the classes are very imbalanced. In information retrieval, precision is a measure of result relevancy, while recall is a measure of how many truly relevant results are returned.\n\nThe precision-recall curve shows the tradeoff between precision and recall for different threshold. A high area under the curve represents both high recall and high precision, where high precision relates to a low false positive rate, and high recall relates to a low false negative rate. High scores for both show that the classifier is returning accurate results (high precision), as well as returning a majority of all positive results (high recall).\n\nA system with high recall but low precision returns many results, but most of its predicted labels are incorrect when compared to the training labels. A system with high precision but low recall is just the opposite, returning very few results, but most of its predicted labels are correct when compared to the training labels. An ideal system with high precision and high recall will return many results, with all results labeled correctly.\n\n![image.png](attachment:image.png)\n\"\"\"\nfrom sklearn.metrics import precision_recall_curve\nprecisions, recalls , thresholds =precision_recall_curve(train_5,scores)\nprint(precisions)\nprint(thresholds)\ndef plot_precision_recall_vs_thresholds(precisions,recalls,thresholds):\n    plt.plot(thresholds,precisions[:-1],\"b--\",label=\"Precision\",linewidth=2)\n    plt.plot(thresholds,recalls[:-1],\"g-\",label=\"Recall\",linewidth=2)\n    plt.xlabel(\"Threshold\",fontsize=16)\n    plt.legend(loc=\"upper right\",fontsize=16)\n    plt.ylim([0,1])\n    \nplt.figure(figsize=(14,8))\nplot_precision_recall_vs_thresholds(precisions,recalls,thresholds)\nplt.xlim([-800000,700000])\nplt.show()\n(train_pred==(scores >0)).all()\ntrain_pred_90=(scores > 170000)\nprecision_score(train_5,train_pred_90)\nrecall_score(train_5,train_pred_90)\n\"\"\"\n# <span style= color:Thistle>Precision vs Recall Plot\n\"\"\"\ndef plot_precision_vs_recall(precisions,recalls):\n    plt.plot(recalls,precisions,\"b-\",linewidth=2)\n    plt.xlabel('Recall',fontsize=14)\n    plt.ylabel('Precision',fontsize=14)\n    plt.axis([0,1,0,1])\n    \nplt.figure(figsize=(14,8))\nplot_precision_vs_recall(precisions,recalls)\nplt.title(\"Precision vs Recall Plot\")\nplt.show()\nfrom sklearn.metrics import roc_curve\nfpr,tpr, thresholds=roc_curve(train_5,scores)\n\n\"\"\"\n# <span style= color:Maroon>Recieving Operator Characterstic Curve \nAUC - ROC curve is a performance measurement for classification problem at various thresholds settings. ROC is a probability curve and AUC represents degree or measure of separability. It tells how much model is capable of distinguishing between classes. Higher the AUC, better the model is at predicting 0s as 0s and 1s as 1s. By analogy, Higher the AUC, better the model is at distinguishing between patients with disease and no disease.\nThe ROC curve is plotted with TPR against the FPR where TPR is on y-axis and FPR is on the x-axis.\n![image.png](attachment:image.png)\n![image.png](attachment:image.png)\n![image.png](attachment:image.png)\n\"\"\"\ndef plot_roc_curve(fpr,tpr,label=None):\n    plt.plot(fpr,tpr,linewidth=2,label=label)\n    plt.plot([0,1],[0,1],'r--')\n    plt.axis([0,1,0,1])\n    plt.xlabel('False Positive Rate',fontsize=16)\n    plt.ylabel('True Postive Rate',fontsize=16)\n    \nplt.figure(figsize=(14,8))\nplot_roc_curve(fpr,tpr)\nplt.title('Recieving Operator Characterstic Curve')\nplt.show()\nfrom sklearn.metrics import roc_auc_score\nroc_auc_score(train_5,scores)\nfrom xgboost import XGBClassifier\nxgb_clf=XGBClassifier(n_estimators=10,random_state=17)\nproba_xgb=cross_val_predict(xgb_clf,train_shuffle,train_5,cv=3,method=\"predict_proba\")\nscores_xgb=proba_xgb[:,1]\nfpr_xgb,tpr_xgb,thresholds_xgb=roc_curve(train_5,scores_xgb)\nplt.figure(figsize=(14,8))\nplt.plot(fpr,tpr,\"b:\",linewidth=2,label=\"SGD\")\nplot_roc_curve(fpr_xgb,tpr_xgb,\"XGB\")\nplt.legend(loc=\"lower right\",fontsize=16)\nplt.title('Recieving Operator Characterstic Curve')\nplt.show()\nroc_auc_score(train_5,scores_xgb)\nxgb_pred=cross_val_predict(xgb_clf,train_shuffle,train_5,cv=3)\nprecision_score(train_5,xgb_pred)\nrecall_score(train_5,xgb_pred)\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\ntrain_scaled=scaler.fit_transform(train_data)\ntest_scaled=scaler.fit_transform(test)\nsgd_clf.fit(train_data,train_label)\nsgd_clf.predict([some_digit])\nsome_digit_scores=sgd_clf.decision_function([some_digit])\nsome_digit_scores\nnp.argmax(some_digit_scores)\nsgd_clf.classes_[1]\nxgb_clf.fit(train_all,train_label)\nsome_digit=train_all[15030]\nxgb_clf.predict(train_all[34:36])\ncross_val_score(sgd_clf,train_data, train_label,cv=3,scoring=\"accuracy\")\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\ntrain_scaled=scaler.fit_transform(train_data.astype(np.float64))\ncross_val_score(sgd_clf,train_scaled,train_label,cv=3,scoring=\"accuracy\")\npredictions=cross_val_predict(sgd_clf,train_scaled,train_label,cv=3)\nconf_mx=confusion_matrix(train_label,predictions)  \n\"\"\"\n# <span style= color:Navy>Confusion Matrix Plot\n\n\"\"\"\ndef plot_confusion_matrix(matrix):\n    fig=plt.figure(figsize=(8,8))\n    ax=fig.add_subplot(111)\n    cax=ax.matshow(matrix)\n    fig.clorbar(cax)\nplt.matshow(conf_mx,cmap=\"Greens_r\")\nplt.show()\nrow_sums=conf_mx.sum(axis=1,keepdims=True)\nnorm_conf_mx=conf_mx\/row_sums\nnp.fill_diagonal(norm_conf_mx,0)\nplt.matshow(norm_conf_mx,cmap=\"Greens_r\")\nplt.show()\ncl_a,cl_b=3,5\nX_aa=train_data[(train_label==cl_a) & (predictions == cl_a)]\nX_ab=train_data[(train_label==cl_a) & (predictions == cl_b)]\nX_ba=train_data[(train_label==cl_b) & (predictions == cl_a)]\nX_bb=train_data[(train_label==cl_b) & (predictions == cl_b)]\n\nplt.figure(figsize=(8,8))\nplt.subplot(221); plot_digits(X_aa[:25], images_per_row=5)\nplt.subplot(222); plot_digits(X_ab[:25], images_per_row=5)\nplt.subplot(223); plot_digits(X_ba[:25], images_per_row=5)\nplt.subplot(224); plot_digits(X_bb[:25], images_per_row=5)\nplt.show()\n\"\"\"\n## <span style= color:Aquamarine>Using KNN Classifier \n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\n\ntrain_large=(train_label >=7)\ntrain_odd=(train_label % 2==1)\ntrain_multilabel=np.c_[train_large,train_odd]\n\nknn_clf=KNeighborsClassifier()\nknn_clf.fit(train_data,train_multilabel)\nknn_clf.predict([some_digit])\n\"\"\"\n# <span style= color:Orange>Adding Noise to Images \n\"\"\"\nnoise = np.random.randint(0, 100, (len(train), 784))\nX_train_mod = train_all + noise\nnoise = np.random.randint(0, 100, (len(test), 784))\ntest_all=test.to_numpy()\nX_test_mod = test + noise\ny_train_mod = train\ny_test_mod = test\nX_test_mod.info()\nsome_index=5500\nplt.subplot(121); plot_digit(X_test_mod.loc[some_index])\nplt.subplot(122); plot_digit(y_test_mod.loc[some_index])\nplt.show()","meta":"{'source': 'AI4Code', 'id': '2ab7759385a44c'}"}
{"id":"126904","text":"\"\"\"\n#Philippines: Energy Use \n\n*Author:* Lj Miranda|| *Website:* ljvmiranda.wordpress.com\n\nThis is a simplified version of the study performed by Lj Miranda who used the World Development Indicators data set shared by Kaglle for investigating the country's energy use. He was, particularly interested to how the Philippines has been\nperforming over time, as well as how it performs compared with its South-East Asian Neighbors.\n\n***This is an exercice to evaluate the initial skills you have developed along the exercices done in the ICT course of your master programs. ***\n\"\"\"\n\"\"\"\n##Task 1\n\n**Refer to the data set shared in the data lab https:\/\/www.kaggle.com\/worldbank\/world-development-indicators. Have a thorough look to the files it is consists in, their format, their associated metadata and their quantitative profile computed by Kaggle.**\n\"\"\"\n\"\"\"\n**Question 1.1 Explain the purpose of the following lines.**\n\"\"\"\n#Import Libraries\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pylab import fill_between\n\n#Read Datasets\ncountry = pd.read_csv('..\/input\/Country.csv')\ncountry_notes = pd.read_csv('..\/input\/CountryNotes.csv')\nindicators = pd.read_csv('..\/input\/Indicators.csv')\n\n#Stylistic Options\ntableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),    \n             (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),    \n             (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),    \n             (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),    \n             (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]  \n\nfor i in range(len(tableau20)):    \n    r, g, b = tableau20[i]    \n    tableau20[i] = (r \/ 255., g \/ 255., b \/ 255.)\n    \n\n\"\"\"\n##1. Computing the percentage of the population that has access to electricity\n\"\"\"\n\"\"\"\n###1.1 Access to electricity over time\n\"\"\"\n\ndf_elec_rural = indicators[(indicators.CountryName=='Philippines')&(indicators.IndicatorCode=='EG.ELC.ACCS.RU.ZS')]\ndf_elec_urban = indicators[(indicators.CountryName=='Philippines')&(indicators.IndicatorCode=='EG.ELC.ACCS.UR.ZS')]\ndf_elec_pop = indicators[(indicators.CountryName=='Philippines')&(indicators.IndicatorCode=='EG.ELC.ACCS.ZS')]\n\n\n\"\"\"\n##Task 2\n\n**Question 2.1 What is the purpose of the previous lines. Explain.**\n\n**Question 2.2 What type of operations are performed? **\n\n**Question 2.3 Are they applied to a DataFrame? **\n\n**Question 2.4 If not is it possible to work on DataFrames? Give the corresponding code.**\n\"\"\"\n# Plot Access Line Chart for Rural and Urban Communities\nfig = plt.figure()\n\nplt.plot(df_elec_rural.Year,df_elec_rural.Value,'o-',label='Rural',color=tableau20[0])\nplt.plot(df_elec_urban.Year,df_elec_urban.Value,'o-',label='Urban',color=tableau20[2])\nplt.plot(df_elec_pop.Year,df_elec_pop.Value,'o-',label='General',color=tableau20[1])\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Population',  fontsize=14)\nplt.title('Access to Electricity', fontsize=14)\n\nfig.savefig('access_electricity.pdf',format='pdf', dpi=300)\n\"\"\"\nThe chart above shows the population's access to electricity over a period of 20 years. Although there was a sharp division of resources in the 90s, access to this need is being \nresolved as time progresses. It is commendable that the government (as well as the private companies) \nhas started putting effort to provide electricity to rural communities at the onset of the millenium.\n\nIt is also interesting to note that the years with a steeper slope started in 2010, and this can be \ncredited to the previous administration (and the corresponding electricity conglomerates) for continuing \nthe steep rise done in the previous years.\n\"\"\"\n\"\"\"\n###1.2 Comparison to South-East Asian (SEA) countries\nNote: *It seems that there is no South-East Asian tag in the World Bank dataset (there is an East Asia & Pacific tag), So we need to remove the countries that are not part of the ASEAN, so a workaround is to arrange the columns for each SEA country manually.*\n\"\"\"\n\"\"\"\n##Task 3\n\n**Question 3.1 Inspired on the previous lines used to filter indicators from Philippines, write the code to obtain electricity pop indicators 'EG.ELC.ACCS.ZS' from the following ASEAN countries: Brunei, Cambodia, Indonesia, Lao PDR, Malasya, Myanmar, Philippines, Singapore, Thailand, Timor-Leste, Vietnam.**\n\"\"\"\n# Response Q 3.1 \n\n\"\"\"\n**Question 3.2 Modify the following code so that you can plot your previous results**\n\"\"\"\nfig = plt.figure()\n\nplt.plot(df_br_elec_pop.Year,df_br_elec_pop.Value,'o-',label='Brunei',color=tableau20[0])\nplt.plot(df_ca_elec_pop.Year,df_ca_elec_pop.Value,'o-',label='Cambodia',color=tableau20[1])\nplt.plot(df_in_elec_pop.Year,df_in_elec_pop.Value,'o-',label='Indonesia',color=tableau20[2])\n\nplt.plot(df_la_elec_pop.Year,df_la_elec_pop.Value,'o-',label='Lao PDR',color=tableau20[3])\nplt.plot(df_ma_elec_pop.Year,df_ma_elec_pop.Value,'o-',label='Malaysia',color=tableau20[4])\nplt.plot(df_my_elec_pop.Year,df_my_elec_pop.Value,'o-',label='Myanmar',color=tableau20[5])\n\nplt.plot(df_ph_elec_pop.Year,df_ph_elec_pop.Value,'o-',label='Philippines',color=tableau20[6])\nplt.plot(df_si_elec_pop.Year,df_si_elec_pop.Value,'o-',label='Singapore',color=tableau20[7])\nplt.plot(df_th_elec_pop.Year,df_th_elec_pop.Value,'o-',label='Thailand',color=tableau20[8])\n\nplt.plot(df_ti_elec_pop.Year,df_ti_elec_pop.Value,'o-',label='Timor-Leste',color=tableau20[9])\nplt.plot(df_vi_elec_pop.Year,df_vi_elec_pop.Value,'o-',label='Vietnam',color=tableau20[10])\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Population',  fontsize=14)\nplt.title('Access to Electricity for SEA Countries', fontsize=14)\nplt.ylim([0,110])\nfig.savefig('access_electricity_sea.pdf',format='pdf', dpi=300)\n\"\"\"\nOne can observe that both Philippines and Indonesia started out similarly in the 90s, \nyet because of the steepness of Indonesia's slope in the chart, it was able to follow the \nleading countries&mdash;even overtaking Thailand in the year 2000. \nHowever, it may also be important to investigate the state of these countries before \n1990s in order to see how this progression came to be.\n\nTop-performing countries in achieving the goal of universal access to electricity are\nSingapore, Malaysia, and Thailand. Achieving almost a 100% by the turn of 2012. Singapore, \non the other hand, is a consistent performer, allowing its population to have access to \nelectricity for 20 years.\n\"\"\"\n\"\"\"\n## What constitutes Philippines energy mix?\n\nEqually important in understanding the country's energy use is to know where our energy is being \nsourced from. This section will look into the different sources of energy&mdash;fossil fuels (coal, \nnatural gas, petroleum), hydroelectric, and renewable in order to gain insight to where most of our\nelectricity is coming from. \n\nMoreover, a comparison with the SEA top-performers (in terms of providing electricity access) \nwill be done in order to assess where the huge bulk of the electricity\\textemdash that they are \nsourcing effectively to the population&mdash;is coming from. \n\nLastly, it is also important to investigate the country's adoption to renewable energy, \nand compare this with our SEA neighbors. This can help identify trends, especially that using \nfossil fuels contributes much to our carbon footprint&mdash;given the devastating results of \nglobal warming and climate change.\n\"\"\"\n\"\"\"\n##Task 4\n\n**Question 4.1 Energy Mix in the Philippines: write a piece of code that creates four groups of different energy sources used in the country:**\n\n**- df_elec_fosl for fosile energy sources EG.ELC.FOSL.ZS**\n\n**- df_elec_hydro for hydroelectric sources 'EG.ELC.HYRO.ZS'**\n\n**- df_elec_nucl for nucleaur sources  'EG.ELC.NUCL.ZS'**\n\n**- df_elec_rnwx for renewable sources 'EG.ELC.RNWX.ZS'\n**\n\"\"\"\n# Response 4.1 \n\nfig = plt.figure()\n\nplt.plot(df_elec_fosl.Year,df_elec_fosl.Value,label='Fossil Fuels',color=tableau20[6])\nplt.plot(df_elec_hydro.Year,df_elec_hydro.Value,label='Hydroelectric',color=tableau20[0])\nplt.plot(df_elec_nucl.Year,df_elec_nucl.Value,label='Nuclear',color=tableau20[3])\nplt.plot(df_elec_rnwx.Year,df_elec_rnwx.Value,label='Renewable',color=tableau20[4])\n\n\nfill_between(df_elec_fosl.Year,df_elec_fosl.Value,0,alpha=0.5,color=tableau20[6])\nfill_between(df_elec_hydro.Year,df_elec_hydro.Value,0,alpha=0.5,color=tableau20[0])\nfill_between(df_elec_nucl.Year,df_elec_nucl.Value,0,alpha=0.5,color=tableau20[3])\nfill_between(df_elec_rnwx.Year,df_elec_rnwx.Value,0,alpha=0.5,color=tableau20[4])\nfill_between(df_elec_rnwx.Year,df_elec_rnwx.Value,0,alpha=0.5,color=tableau20[4])\n#fill_between(x,y2,0,color='magenta')\n#fill_between(x,y3,0,color='red')\n\nplt.legend(loc=1, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Total Energy Produce',  fontsize=14)\nplt.title('Energy Mix in the Philippines (1971-2012)', fontsize=18)\n\n\nfig.savefig('energy_mix.pdf',format='pdf', dpi=300)\n\"\"\"\n**Question 4.2 Energy Mix in the Philippines: write a piece of code that creates  groups for natural gas, coal and petroleum used in this country**\n\n**- df_elec_ngas  'EG.ELC.NGAS.ZS'**\n\n**- df_elec_coal  'EG.ELC.COAL.ZS'**\n\n**- df_elec_petr  'EG.ELC.PETR.ZS'**\n\"\"\"\n#Response Q 4.2\n\nfig = plt.figure()\n\nplt.plot(df_elec_ngas.Year,df_elec_ngas.Value,label='Natural Gas',color=tableau20[9])\nplt.plot(df_elec_coal.Year,df_elec_coal.Value,label='Coal',color=tableau20[10])\nplt.plot(df_elec_petr.Year,df_elec_petr.Value,label='Petroleum',color=tableau20[11])\n\nfill_between(df_elec_petr.Year,df_elec_petr.Value,0,alpha=0.5,color=tableau20[11])\nfill_between(df_elec_coal.Year,df_elec_coal.Value,0,alpha=0.5,color=tableau20[10])\nfill_between(df_elec_ngas.Year,df_elec_ngas.Value,0,alpha=0.5,color=tableau20[9])\n\n\n\nplt.legend(loc=1, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Total Energy Produce',  fontsize=14)\nplt.title('Fossil Fuel Mix in the Philippines (1971-2012)', fontsize=18)\n\n\nfig.savefig('fossil_fuel_mix.pdf',format='pdf', dpi=300)\n\"\"\"\nIt is evident that the country is still reliant to fossil fuels as a main source of energy. \nHydroelectric easily caught up and is a stable source to the fifth of our energy supply in the country. \nInterestingly, the contribution of renewable energy in the country is comparable to that of \nhydroelectric&mdash; and by combining the two together, one can see that these \"clean\" sources of \nenergy contributes more than a fourth of our total energy mix. \n\n\nLooking at the country's fossil fuel mix, one can see that our use of petroleum has significantly \ndropped for the last 20 years. This has been replaced by other fossil fuels such as natural gas \n(during the 1980s) and coal (during the 2000s).  \n\n\"\"\"\n\"\"\"\n###2.2 Comparison to SEA Neighbors\nThis section looks into the position of the Philippines with respect to the\nuse of fossil fuels and the adoption of renewable energy through time.\n\"\"\"\n\"\"\"\n####2.2.1 Fossil Fuel Use\n\"\"\"\n\"\"\"\n##Task 5\n\n**Question 5.1 Write a piece of code that gets the indicators of fossil fuel use EG.ELC.FOSL.ZS for the following countries: Brunei, Cambodia, Indonesia, Lao PDR, Malaysia, Myanmar, Philippines, Singapore, Thailand, Timor-Leste, Vietnam**\n\n- df_br_elec_pop \n- df_ca_elec_pop \n- df_in_elec_pop \n- df_la_elec_pop \n- df_ma_elec_pop \n- df_my_elec_pop \n- df_ph_elec_pop\n- df_si_elec_pop \n- df_th_elec_pop \n- df_ti_elec_pop \n- df_vi_elec_pop \n\"\"\"\n# Response Q 5.1 \n\nfig = plt.figure()\n\nplt.plot(df_si_elec_pop.Year,df_si_elec_pop.Value,label='Singapore',color=tableau20[7])\nplt.plot(df_ma_elec_pop.Year,df_ma_elec_pop.Value,label='Malaysia',color=tableau20[4])\nplt.plot(df_th_elec_pop.Year,df_th_elec_pop.Value,label='Thailand',color=tableau20[8])\nplt.plot(df_vi_elec_pop.Year,df_vi_elec_pop.Value,label='Vietnam',color=tableau20[10])\nplt.plot(df_in_elec_pop.Year,df_in_elec_pop.Value,label='Indonesia',color=tableau20[2])\nplt.plot(df_ph_elec_pop.Year,df_ph_elec_pop.Value,label='Philippines',color=tableau20[6])\nplt.plot(df_la_elec_pop.Year,df_la_elec_pop.Value,label='Lao PDR',color=tableau20[3])\nplt.plot(df_my_elec_pop.Year,df_my_elec_pop.Value,label='Myanmar',color=tableau20[5])\nplt.plot(df_br_elec_pop.Year,df_br_elec_pop.Value,label='Brunei',color=tableau20[0])\nplt.plot(df_ti_elec_pop.Year,df_ti_elec_pop.Value,label='Timor-Leste',color=tableau20[9])\nplt.plot(df_ca_elec_pop.Year,df_ca_elec_pop.Value,label='Cambodia',color=tableau20[1])\n\n\nplt.legend(loc=1, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Energy Production',  fontsize=14)\nplt.title('Fossil Fuel Use for SEA Countries', fontsize=18)\n\nplt.ylim([0,110])\nplt.xlim([1990,2019])\nfig.savefig('fossil_fuel_electricity_sea.pdf',format='pdf', dpi=300)\nfig.savefig('fossil_fuel_electricity_sea.png',format='png', dpi=300)\n\"\"\"\n**Question 5.2 Which are the  top-players in providing access to electricity in their respective\npopulation?** \n\nThese countries are sourcing their energy mostly from fossil fuels.\n\n**Question 5.3 What is the position of the Philippines of fossil fuel that constitutes the energy mix?**\n\n**Question 5.4 What is the percentage interval of fossil fuel energy mix of Myanmar?**\n\"\"\"\n\"\"\"\n####2.2.2 Renewable Energy Adoption\n\"\"\"\n\"\"\"\n##Task 6\n\n**Question 6.1 Write a similar piece of code but now to get numbers on Renewable Energy Adoption 'EG.ELC.RNWX.ZS for the following countries: Brunei, Cambodia, Indonesia, Lao PDR, Malaysia, Myanmar, Philippines, Singapore, Thailand, Timor-Leste, Vietnam**\n\n- df_br_elec_pop\n- df_ca_elec_pop\n- df_in_elec_pop\n- df_la_elec_pop\n- df_ma_elec_pop\n- df_my_elec_pop\n- df_ph_elec_pop\n- df_si_elec_pop\n- df_th_elec_pop\n- df_ti_elec_pop\n- df_vi_elec_pop\n\"\"\"\n# Response Q 6.1\n\nfig = plt.figure()\n\nplt.plot(df_si_elec_pop.Year,df_si_elec_pop.Value,label='Singapore',color=tableau20[7])\nplt.plot(df_ma_elec_pop.Year,df_ma_elec_pop.Value,label='Malaysia',color=tableau20[4])\nplt.plot(df_th_elec_pop.Year,df_th_elec_pop.Value,label='Thailand',color=tableau20[8])\nplt.plot(df_vi_elec_pop.Year,df_vi_elec_pop.Value,label='Vietnam',color=tableau20[10])\nplt.plot(df_in_elec_pop.Year,df_in_elec_pop.Value,label='Indonesia',color=tableau20[2])\nplt.plot(df_ph_elec_pop.Year,df_ph_elec_pop.Value,label='Philippines',color=tableau20[6])\nplt.plot(df_la_elec_pop.Year,df_la_elec_pop.Value,label='Lao PDR',color=tableau20[3])\nplt.plot(df_my_elec_pop.Year,df_my_elec_pop.Value,label='Myanmar',color=tableau20[5])\nplt.plot(df_br_elec_pop.Year,df_br_elec_pop.Value,label='Brunei',color=tableau20[0])\nplt.plot(df_ti_elec_pop.Year,df_ti_elec_pop.Value,label='Timor-Leste',color=tableau20[9])\nplt.plot(df_ca_elec_pop.Year,df_ca_elec_pop.Value,label='Cambodia',color=tableau20[1])\n\n\nplt.legend(loc=1, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('% of Energy Production',  fontsize=14)\nplt.title('Renewable Energy Adoption for SEA Countries', fontsize=18)\n\nplt.ylim([0,30])\nplt.xlim([1990,2019])\nfig.savefig('renewable_electricity_sea.pdf',format='pdf', dpi=300)\nfig.savefig('renewable_electricity_sea.png',format='png', dpi=300)\n\"\"\"\nThe figure above shows the renewable energy adoption of different SEA\ncountries over time.\n\n**Question 6.2 How is Philippines doing in the renewable energy race with respect to other countries?**\n\"\"\"\n\"\"\"\n##3. How are we consuming our energy?\nWith the knowledge of the country's energy sources, the next step is to un-\nderstand how we consume that energy. This section will first look into the\ncountry's electric power consumption over time, then look at our consumption footprint&mdash;particularly that of carbon emissions and other greenhouse\ngases.\n\n\"\"\"\n\"\"\"\n###3.1 Electric power consumption over time\n\"\"\"\n\"\"\"\n##Task 7\n\n**Question 7.1 Obtain data about the electric power consumption of Philippines over time EG.USE.ELEC.KH.PC**\n\n- df_elec_use\n\"\"\"\n#Response Q 7.1\n\nfig = plt.figure()\n\nplt.plot(df_elec_use.Year,df_elec_use.Value,color=tableau20[3])\n\n#plt.legend(loc=4, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('kWh per capita',  fontsize=14)\nplt.title('Electric Power Consumption in the Philippines', fontsize=18)\n\n\nfig.savefig('electric_consumption.pdf',format='pdf', dpi=300)\nfig.savefig('electric_consumption.png',format='png', dpi=300)\n\"\"\"\n**Question 7.2 According to the chart how much has the power consumption increased in the country over time?**\n\"\"\"\n\"\"\"\n###3.2 Consumption footprint\n\"\"\"\n\"\"\"\n##Task 8\n\n**Question 8.1 Write a piece of code to compute indicators in Philippines that will play a role to compute its consumption footprint, i.e., CO2 generated by: emisions (EN.ATM.CO2E.KT), liquid fuel (EN.ATM.CO2E.LF.KT), solid fuel (EN.ATM.CO2E.SF.KT), and gaseous fuel (EN.ATM.CO2E.GF.KT).**\n\n- df_elec_emi \n- df_elec_gf\n- df_elec_lf \n- df_elec_sf \n\n\"\"\"\n# Response Q 8.1\n\nfig = plt.figure()\n\nplt.plot(df_elec_emi.Year,df_elec_emi.Value,label='C0$_2$ emissions',color=tableau20[1])\nplt.plot(df_elec_lf.Year,df_elec_lf.Value,label='C0$_2$ emissions from liquid fuel',color=tableau20[3])\nplt.plot(df_elec_sf.Year,df_elec_sf.Value,label='C0$_2$ emissions from solid fuel',color=tableau20[4])\nplt.plot(df_elec_gf.Year,df_elec_gf.Value,label='C0$_2$ emissions from gaseous fuel',color=tableau20[2])\n\nfill_between(df_elec_emi.Year,df_elec_emi.Value,0,alpha=0.5,color=tableau20[1])\nfill_between(df_elec_lf.Year,df_elec_lf.Value,0,alpha=0.5,color=tableau20[3])\nfill_between(df_elec_sf.Year,df_elec_sf.Value,0,alpha=0.5,color=tableau20[4])\nfill_between(df_elec_gf.Year,df_elec_gf.Value,0,alpha=0.5,color=tableau20[2])\n\nplt.legend(loc=2, borderaxespad=1.)\nplt.xlabel('Years',  fontsize=14)\nplt.ylabel('kt (kilotons)',  fontsize=14)\nplt.title('Carbon Footprint in the Philippines', fontsize=18)\n\n\nfig.savefig('co2_emissions.pdf',format='pdf', dpi=300)\nfig.savefig('co2_emissions.png',format='png', dpi=300)\n\"\"\"\nThese unprecedented e\u000bects are what we often call as our consumption footprint, for it leaves traces in nature that we may not expect. This section looks into our carbon footprint and different greenhouse gases, taken mainly from our use of fossil fuels as energy source, and through our continued consumption of electricity (managed or not).\n\nSimilar to the rise of our electric consumption, Philippines carbon footprint has increased steadily for the last few years. Different sources have contributed to this, the first mainly by liquid fuel, then followed by solid fuel and then by gaseous fuel. It is expected that this trend will continue to rise, and its effects might be felt if left unmitigated.\n\"\"\"\n\"\"\"\n##Conclusion\nThis report looks into World Bank's World Development Indicators in order\nto understand the energy situation in the Philippines. Three aspects were\nconsidered|the access to electricity of the population, the energy mix, and\nthe energy consumption and footprint.\n\nThe country's access to electricity is being resolved through time, increasing the \nrural population's access for the last twenty years. However,\nmuch work is to be done, for the country is only 6th compared to its SEA\nneighbors in this category. However, much can be said in the country's energy mix, \nfor the use of fossil fuels (although still in majority) is being\noffset by hydroelectric and renewable sources of energy. In fact, the country\nis leading among its SEA neighbors with respect to the renewable energy\nadoption. Lastly, the electricity consumption of the country is still on the\nrise, and will still be, given the trend for the last twenty years. This can\nthen be followed by an increasing carbon footprint, which may lead to unprecedented effects if left unmitigated.\n\"\"\"\n\"\"\"\n##Task 9\n\n**Question 9.1 Analyse the experiment that has been developed and draw the steps of the pipeline that has implemented the experiment. Uplead the figure below.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e95a622e603604'}"}
{"id":"39973","text":"# 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\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly as py\n\nimport plotly.graph_objs as go\nfrom sklearn.cluster import KMeans\n\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nfrom sklearn.cluster import AgglomerativeClustering\n\nimport warnings\nimport os\n#\u00e7al\u0131\u015fma dizinimiz.\nprint(os.listdir(\"..\/input\"))\n# We read the data.\ndata = pd.read_csv('..\/input\/customer-segmentation-tutorial-in-python\/Mall_Customers.csv')\ndata.head()\ndata.shape\ndata.info()\ndata.describe()\ndata.dtypes\nprint(pd.isnull(data).sum())\ndata.corr()\nplt.figure(figsize=(4,4))\nsns.heatmap(data.corr(),annot=True)\nplt.show()\nsns.pairplot(data)\nplt.show()\nlabels=['Male','Female']\nsizes=[data.query('Gender==\"Male\"').Gender.count(),data.query('Gender==\"Female\"').Gender.count()]\nexplode = [0, 0.1]\ncolors = ['#12b3ff','#ffaaB9']\nplt.pie(sizes,labels=labels,colors=colors,explode=explode,shadow = False, autopct = '%.2f%%')\nplt.show()\nplt.figure(figsize=(15,4))\nsns.countplot(data.Age)\nplt.xlabel('Age')\nplt.ylabel('Number of People')\nplt.show()\nplt.figure(1 , figsize = (15 , 6))\nfor gender in ['Male' , 'Female']:\n    plt.scatter(x = 'Age' , y = 'Annual Income (k$)' , data = data[data['Gender'] == gender] ,\n                s = 200 , alpha = 0.5 , label = gender)\nplt.xlabel('Age'),\nplt.ylabel('Annual Income') \nplt.title('Age vs Annual Income')\nplt.legend()\nplt.show()\nplt.figure(figsize=(20,7))\ngender = ['Male', 'Female']\nfor i in gender:\n    plt.scatter(x='Age',y='Spending Score (1-100)', data=data[data['Gender']==i],s = 200 , alpha = 0.5 , label = i)\nplt.legend()\nplt.xlabel(\"Age\")\nplt.ylabel(\"Spending Score (1-100)\")\nplt.title(\"Spending Score According to Age\")\nplt.show()\nplt.figure(1 , figsize = (15 , 7))\nn = 0 \nfor cols in ['Age' , 'Annual Income (k$)' , 'Spending Score (1-100)']:\n    n += 1 \n    plt.subplot(1 , 3 , n)\n    plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)\n    sns.violinplot(x = cols , y = 'Gender' , data = data, palette = 'vlag')\n    sns.swarmplot(x = cols , y = 'Gender' , data = data)\n    plt.ylabel('Gender' if n == 1 else '')\n    plt.title('Boxplots & Swarmplots' if n == 2 else '')\nplt.show()\n#We have determined that we will use the attributes in columns 2 through 4.\nX=data.iloc[:, [2,4]].values\n\"\"\"\n**Elbow Method**\n\"\"\"\n# We use the bracket method to find the number of clusters.\n#For this, we must first find WCSS(the within\u200b-cluster sum of squares).\n#We will calculate the variation of WCSS with the number of clusters.\n#WCSS(the sum of the squares of the distances of each data point in all clusters from their respective center points\u0131)\n\n\n# We create an empty list.\nwcss = []\n#For the number of clusters, we create an increasing list from 1 to 10 with the range() function.\nfor i in range(1,11):\n    #K-means s\u0131n\u0131f\u0131ndan bir nesne \u00fcretiyoruz.\n    kmeans = KMeans(n_clusters= i, max_iter = 300, init='k-means++', n_init = 10, random_state=0)\n    #K\u00fcmeleme i\u015flemi yap\n    kmeans.fit(X)\n    wcss.append(kmeans.inertia_)\n#While creating an object we are sending some parameters to the constructor function (__init__).\n#The first of these is n_clusters, which is the number of clusters.\n#The for loop gives the number of clusters as a parameter to n_clusters, increasing by one each time it returns with the variable i. \n#The init parameter specifies the ideal cluster centers to select the starting points.\n#The kmeans++ parameter saves us from the random initialization trap, it allows us to choose good starting points.\n#The next parameter max_iter determines the maximum number of iterations the algorithm can take to reach its final state, the default is 300.\n#n_init determines how many different points the cluster center starting point can start from.\n#The last parameter, random_state, ensures that anyone who executes these operations will get the same results. \n#After the object is created, we perform the data fit with the object with the fit() method.\n#We give the X that we created earlier as a parameter.\n#We add the inerita_ property of the kmeans object to the wcss list we created before the for loop.  \nplt.figure(figsize=(10,3))\nplt.plot(range(1,11),wcss)\nplt.xlabel(\"number of k (cluster) value\")\nplt.ylabel(\"wcss\")\nplt.show()\n\"\"\"\n**K-Means**\n\"\"\"\n\n#We see from the chart that the ideal number of clusters would be 4. Now we repeat the working line for the set number 5 in the for loop.\n#We are creating an object of class K-means.\nkmeansmodel = KMeans(n_clusters= 4, init='k-means++', max_iter = 300, n_init = 10, random_state=0)\n\n\n#Cluster and predict\ny_kmeans= kmeansmodel.fit_predict(X)\n\n\n# We have determined the cluster center points.\ncentroids1 = kmeansmodel.cluster_centers_\n\n# Shows clusters on graph\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, label = 'Cluster 1')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, label = 'Cluster 3')\nplt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, label = 'Cluster 4')\n\nplt.scatter(x = centroids1[: , 0] , y =  centroids1[: , 1] , s = 300 , c = 'yellow' , alpha = 0.8)\nplt.title('Clusters of Customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\n\nplt.legend()\nplt.show()\nx = data[['Age', 'Spending Score (1-100)', 'Annual Income (k$)']].values\nkm = KMeans(n_clusters = 5, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\nkm.fit(x)\nlabels = km.labels_\ncentroids = km.cluster_centers_\nimport plotly.offline as py\nfrom plotly.offline import init_notebook_mode, iplot\n\ndata['labels'] =  labels\ntrace1 = go.Scatter3d(\n    x= data['Age'],\n    y= data['Spending Score (1-100)'],\n    z= data['Annual Income (k$)'],\n    mode='markers',\n     marker=dict(\n        color = data['labels'], \n        size= 10,\n        line=dict(\n            color= data['labels'],\n            width= 12\n        ),\n        opacity=0.8\n     )\n)\ndf = [trace1]\n\nlayout = go.Layout(\n    title = 'Character vs Gender vs Alive or not',\n    margin=dict(\n        l=0,\n        r=0,\n        b=0,\n        t=0  \n    ),\n    scene = dict(\n            xaxis = dict(title  = 'Age'),\n            yaxis = dict(title  = 'Spending Score'),\n            zaxis = dict(title  = 'Annual Income')\n        )\n)\n\nfig = go.Figure(data = df, layout = layout)\npy.iplot(fig)\n# We imported the AgglomerativeClustering class\nfrom sklearn.cluster import AgglomerativeClustering\n# We generated an object from AgglomerativeClustering class\n# n_clusters = Number of clusters we will allocate\n# linkage and affinity = distance measurement methods\n# Changing the linkage and affinity parameters affects the success rate.\nag=AgglomerativeClustering(n_clusters=4,affinity='euclidean',linkage='ward')\n\n#Make clustering and prediction\npredict=ag.fit_predict(x)\n# Dendogram graph display\nimport scipy.cluster.hierarchy as sch\n# x = our data\n# method = We give the same parameter as the linkage parameter of AgglomerativeClustering. ( 'ward' )\ndendrogram=sch.dendrogram(sch.linkage(x,method='ward'))\nplt.show()","meta":"{'source': 'AI4Code', 'id': '499dbbbd0020c6'}"}
{"id":"15135","text":"\"\"\"\n<a class=\"anchor\" id=\"0\"><\/a>\n# **A Guide on XGBoost hyperparameters tuning**\n\n\nHello friends,\n\n\nIn my previous kernel [XGBoost + k-fold CV + Feature Importance](https:\/\/www.kaggle.com\/prashant111\/xgboost-k-fold-cv-feature-importance), we have discussed XGBoost and develop a simple baseline XGBoost model. \n\n\nNow, XGBoost algorithm provides large range of hyperparameters. We should know how to tune these hyperparameters to improve and take full advantage of the XGBoost model.\n\n\nHence, in this kernel, we will discuss main hyperparameters of the XGBoost model and how to tune these hyperparameters.\n\n\nSo, let's get started.\n\n\n\"\"\"\n\"\"\"\n**If this helped in your learning, then please <font color=\"red\"><b>UPVOTE<\/b><\/font>  \u2013 as they are the source of motivation!**\n\n**Happy Learning**\n\n\"\"\"\n\"\"\"\n# **Table of Contents** <a class=\"anchor\" id=\"0.1\"><\/a>\n\n\n- 1 [What are hyperparameters](#1)\n- 2 [XGBoost hyperparameters](#2)\n   - 2.1 [General Parameters](#2.1)\n      - 2.1.1 [booster](#2.1.1)\n      - 2.1.2 [verbosity](#2.1.2)\n      - 2.1.3 [nthread](#2.1.3)\n   - 2.2 [Booster Parameters](#2.2)\n      - 2.2.1 [eta](#2.2.1)\n      - 2.2.2 [gamma](#2.2.2)\n      - 2.2.3 [max_depth](#2.2.3)\n      - 2.2.4 [min_child_weight](#2.2.4)\n      - 2.2.5 [max_delta_step](#2.2.5)\n      - 2.2.6 [subsample](#2.2.6)\n      - 2.2.7 [colsample_bytree, colsample_bylevel, colsample_bynode](#2.2.7) \n      - 2.2.8 [lambda](#2.2.8)\n      - 2.2.9 [alpha](#2.2.9)\n      - 2.2.10 [tree_method](#2.2.10)\n      - 2.2.11 [scale_pos_weight](#2.2.11)\n      - 2.2.12 [max_leaves](#2.2.12)\n   - 2.3 [Learning Task Parameters](#2.3)\n      - 2.3.1 [objective](#2.3.1)\n      - 2.3.2 [eval_metric](#2.3.2)\n      - 2.3.3 [seed](#2.3.3)\n- 3 [Basic Setup](#3)\n   - 3.1 [Import libraries](#3.1)\n   - 3.2 [Read dataset](#3.2)\n   - 3.3 [Declare feature vector and target variable](#3.3)\n   - 3.4 [Split data into separate training and test set](#3.4)\n- 4 [Bayesian Optimization with HYPEROPT](#4)\n   - 4.1 [What is HYPEROPT](#4.1)\n   - 4.2 [4 Parts of Optimization Process](#4.2)\n   - 4.3 [Bayesian Optimization Implementation](#4.3)\n      - 4.3.1 [Initialize domain space for range of values](#4.3.1)\n      - 4.3.2 [Define objective function](#4.3.2)\n      - 4.3.3 [Optimization algorithm](#4.3.3)\n      - 4.3.4 [Print Results](#4.3.4)\n- 5 [Results and Conclusion](#5)\n- 6 [References](#6)\n\n\n\n\n\n\"\"\"\n\"\"\"\n# **1. What are hyperparameters** <a class=\"anchor\" id=\"1\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- In this kernel, we will discuss the critical problem of hyperparameter tuning in XGBoost model.\n\n- **Hyperparameters** are certain values or weights that determine the learning process of an algorithm.\n\n- As stated earlier, XGBoost provides large range of hyperparameters. We can leverage the maximum power of XGBoost by tuning its hyperparameters.\n\n- The most powerful ML algorithm like XGBoost is famous for picking up patterns and regularities in the data by automatically tuning thousands of learnable parameters. \n\n- In tree-based models, like XGBoost the learnable parameters are the choice of decision variables at each node.\n\n- XGBoost is a very powerful algorithm. So, it will have more design decisions and hence large hyperparameters. These are parameters specified by hand to the algo and fixed throughout a training phase.\n\n- In tree-based models, hyperparameters include things like the maximum depth of the tree, the number of trees to grow, the number of variables to consider when building each tree, the minimum number of samples on a leaf and the fraction of observations used to build a tree.\n\n- Although we focus on optimizing XGBoost hyperparameters in this kernel, the concepts discussed in this kernel applies to any other advanced ML algorithm as well.\n\n\"\"\"\n\"\"\"\n# **2. XGBoost hyperparameters** <a class=\"anchor\" id=\"2\"><\/a>\n\n[Table of Contents](#0.1)\n\n- Generally, the XGBoost hyperparameters have been divided into 4 categories. They are as follows -\n\n  - 1. General parameters\n  - 2. Booster parameters\n  - 3. Learning task parameters\n  - 4. Command line parameters\n \n- Before running a XGBoost model, we must set three types of parameters - **general parameters**, **booster parameters** and **task parameters**.\n\n- The fourth type of parameters are **command line parameters**. They are only used in the console version of XGBoost. So, we will skip these parameters and limit our discussion to the first three type of parameters.\n\"\"\"\n\"\"\"\n## **2.1 General Parameters** <a class=\"anchor\" id=\"2.1\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- These parameters guide the overall functioning of the XGBoost model. \n\n- In this section, we will discuss three hyperparameters - **booster**, **verbosity** and **nthread**.\n\n- Please visit [XGBoost General Parameters](https:\/\/xgboost.readthedocs.io\/en\/latest\/parameter.html#general-parameters) for detailed discussion on general parameters.\n\"\"\"\n\"\"\"\n### **2.1.1 booster** <a class=\"anchor\" id=\"2.1.1\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **booster[default = gbtree]**\n\n   - **booster** parameter helps us to choose which booster to use.\n   - It helps us to select the type of model to run at each iteration. \n   - It has 3 options - **gbtree**, **gblinear** or **dart**.\n   \n       - **gbtree** and **dart** - use tree-based models, while\n       - **gblinear** uses linear models. \n   \n\"\"\"\n\"\"\"\n### **2.1.2 verbosity** <a class=\"anchor\" id=\"2.1.2\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **verbosity[default = 1]**\n\n    - Verbosity of printing messages. \n    - Valid values are 0 (silent), 1 (warning), 2 (info), 3 (debug).\n\"\"\"\n\"\"\"\n### **2.1.3 nthread** <a class=\"anchor\" id=\"2.1.3\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **nthread [default = maximum number of threads available if not set]**\n\n   - This is number of parallel threads used to run XGBoost.\n   - This is used for parallel processing and number of cores in the system should be entered.\n   - If you wish to run on all cores, value should not be entered and algorithm will detect automatically.\n\"\"\"\n\"\"\"\nThere are other general parameters like **disable_default_eval_metric [default=0]**, **num_pbuffer [set automatically by XGBoost, no need to be set by user]** and **num_feature [set automatically by XGBoost, no need to be set by user]**.\n\nSo, these parameters are taken care by XGBoost algorithm itself. Hence,we will not discuss these further.\n\"\"\"\n\"\"\"\n## **2.2 Booster Parameters** <a class=\"anchor\" id=\"2.2\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- We have 2 types of boosters - **tree booster** and **linear booster**.\n- We will limit our discussion to **tree booster** because it always outperforms the **linear booster** and thus the later is rarely used.\n- Please visit, [Parameters for Tree Booster](https:\/\/xgboost.readthedocs.io\/en\/latest\/parameter.html#parameters-for-tree-booster), for detailed discussion on booster parameters.\n\n\"\"\"\n\"\"\"\n### **2.2.1 eta** <a class=\"anchor\" id=\"2.2.1\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **eta [default=0.3, alias: learning_rate]**\n\n  - It is analogous to learning rate in GBM.\n  - It is the step size shrinkage used in update to prevent overfitting. \n  - After each boosting step, we can directly get the weights of new features, and eta shrinks the feature weights to make the boosting process more conservative.\n  - It makes the model more robust by shrinking the weights on each step.\n  - range : [0,1]\n  - Typical final values : 0.01-0.2.\n\n\n\"\"\"\n\"\"\"\n### **2.2.2 gamma** <a class=\"anchor\" id=\"2.2.2\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **gamma [default=0, alias: min_split_loss]**\n\n   - A node is split only when the resulting split gives a positive reduction in the loss function. \n   - Gamma specifies the minimum loss reduction required to make a split.\n   - It makes the algorithm conservative. The values can vary depending on the loss function and should be tuned.\n   - The larger gamma is, the more conservative the algorithm will be.\n   - Range: [0,\u221e]\n\"\"\"\n\"\"\"\n### **2.2.3 max_depth** <a class=\"anchor\" id=\"2.2.3\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **max_depth [default=6]**\n\n    - The maximum depth of a tree, same as GBM.\n    - It is used to control over-fitting as higher depth will allow model to learn relations very specific to a particular sample.\n    - Increasing this value will make the model more complex and more likely to overfit. \n    - The value 0 is only accepted in lossguided growing policy when tree_method is set as hist and it indicates no limit on depth. \n    - We should be careful when setting large value of max_depth because XGBoost aggressively consumes memory when training a deep tree.\n    - range: [0,\u221e] (0 is only accepted in lossguided growing policy when tree_method is set as hist.\n    - Should be tuned using CV.\n    - Typical values: 3-10\n\"\"\"\n\"\"\"\n### **2.2.4 min_child_weight** <a class=\"anchor\" id=\"2.2.4\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **min_child_weight [default=1]**\n\n   - It defines the minimum sum of weights of all observations required in a child.\n   - This is similar to min_child_leaf in GBM but not exactly. This refers to min \u201csum of weights\u201d of observations while GBM has min \u201cnumber of observations\u201d.\n   - It is used to control over-fitting. \n   - Higher values prevent a model from learning relations which might be highly specific to the particular sample selected for a tree.\n   - Too high values can lead to under-fitting. \n   - Hence, it should be tuned using CV.\n   - The larger min_child_weight is, the more conservative the algorithm will be.\n   - range: [0,\u221e]\n\"\"\"\n\"\"\"\n### **2.2.5 max_delta_step** <a class=\"anchor\" id=\"2.2.5\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **max_delta_step [default=0]**\n\n   - In maximum delta step we allow each tree\u2019s weight estimation to be. \n   - If the value is set to 0, it means there is no constraint. \n   - If it is set to a positive value, it can help making the update step more conservative.\n   - Usually this parameter is not needed, but it might help in logistic regression when class is extremely imbalanced.\n   - Set it to value of 1-10 might help control the update.\n   - range: [0,\u221e]\n\n\n\n\"\"\"\n\"\"\"\n### **2.2.6 subsample** <a class=\"anchor\" id=\"2.2.6\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **subsample [default=1]**\n\n   - It denotes the fraction of observations to be randomly samples for each tree.\n   - Subsample ratio of the training instances. \n   - Setting it to 0.5 means that XGBoost would randomly sample half of the training data prior to growing trees.      - This will prevent overfitting. \n   - Subsampling will occur once in every boosting iteration.\n   - Lower values make the algorithm more conservative and prevents overfitting but too small values might lead to under-fitting.\n   - Typical values: 0.5-1\n   - range: (0,1]\n\"\"\"\n\"\"\"\n### **2.2.7 colsample_bytree, colsample_bylevel, colsample_bynode** <a class=\"anchor\" id=\"2.2.7\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **colsample_bytree, colsample_bylevel, colsample_bynode [default=1]**\n\n   - This is a family of parameters for subsampling of columns.\n\n   - All **colsample_by** parameters have a range of (0, 1], the default value of 1, and specify the fraction of columns to be subsampled.\n\n   - **colsample_bytree** is the subsample ratio of columns when constructing each tree. Subsampling occurs once for every tree constructed.\n\n   - **colsample_bylevel** is the subsample ratio of columns for each level. Subsampling occurs once for every new depth level reached in a tree. Columns are subsampled from the set of columns chosen for the current tree.\n\n   - **colsample_bynode** is the subsample ratio of columns for each node (split). Subsampling occurs once every time a new split is evaluated. Columns are subsampled from the set of columns chosen for the current level.\n\n   - **colsample_by*** parameters work cumulatively. For instance, the combination **{'colsample_bytree':0.5, 'colsample_bylevel':0.5, 'colsample_bynode':0.5}** with 64 features will leave 8 features to choose from at each split.\n\n\"\"\"\n\"\"\"\n### **2.2.8 lambda** <a class=\"anchor\" id=\"2.2.8\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **lambda [default=1, alias: reg_lambda]**\n\n    - L2 regularization term on weights  (analogous to Ridge regression).\n    - This is used to handle the regularization part of XGBoost. \n    - Increasing this value will make model more conservative.\n\"\"\"\n\"\"\"\n### **2.2.9 alpha** <a class=\"anchor\" id=\"2.2.9\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **alpha [default=0, alias: reg_alpha]**\n\n    - L1 regularization term on weights (analogous to Lasso regression).\n    - It can be used in case of very high dimensionality so that the algorithm runs faster when implemented.\n    - Increasing this value will make model more conservative.\n\"\"\"\n\"\"\"\n### **2.2.10 tree_method** <a class=\"anchor\" id=\"2.2.10\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **tree_method string [default= auto]**\n\n   - The tree construction algorithm used in XGBoost. \n\n   - XGBoost supports `approx`, `hist` and `gpu_hist` for distributed training. Experimental support for external memory is available for `approx` and `gpu_hist`.\n\n   - Choices: `auto`, `exact`, `approx`, `hist`, `gpu_hist`\n\n      - **auto**: Use heuristic to choose the fastest method.\n         - For small to medium dataset, exact greedy (exact) will be used.\n\n         - For very large dataset, approximate algorithm (approx) will be chosen.\n\n         - Because old behavior is always use exact greedy in single machine, user will get a message when approximate algorithm is chosen to notify this choice.\n\n     - **exact**: Exact greedy algorithm.\n\n     - **approx**: Approximate greedy algorithm using quantile sketch and gradient histogram.\n\n     - **hist**: Fast histogram optimized approximate greedy algorithm. It uses some performance improvements such as bins caching.\n\n     - **gpu_hist**: GPU implementation of hist algorithm.\n\"\"\"\n\"\"\"\n### **2.2.11 scale_pos_weight** <a class=\"anchor\" id=\"2.2.11\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **scale_pos_weight [default=1]**\n\n     - It controls the balance of positive and negative weights, \n     - It is useful for imbalanced classes. \n     - A value greater than 0 should be used in case of high class imbalance as it helps in faster convergence.\n     - A typical value to consider: `sum(negative instances) \/ sum(positive instances)`.\n\n\"\"\"\n\"\"\"\n### **2.2.12 max_leaves** <a class=\"anchor\" id=\"2.2.11\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **max_leaves [default=0]**\n\n  - Maximum number of nodes to be added. \n  - Only relevant when `grow_policy=lossguide` is set.\n\"\"\"\n\"\"\"\n- There are other hyperparameters like `sketch_eps`,`updater`, `refresh_leaf`, `process_type`, `grow_policy`, `max_bin`, `predictor` and `num_parallel_tree`.\n\n- For detailed discussion of these hyperparameters, please visit [Parameters for Tree Booster](https:\/\/xgboost.readthedocs.io\/en\/latest\/parameter.html#parameters-for-tree-booster)\n\"\"\"\n\"\"\"\n## **2.3 Learning Task Parameters** <a class=\"anchor\" id=\"2.3\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- These parameters are used to define the optimization objective the metric to be calculated at each step.\n\n- They are used to specify the learning task and the corresponding learning objective. The objective options are below:\n\n\n\"\"\"\n\"\"\"\n### **2.3.1 objective** <a class=\"anchor\" id=\"2.3.1\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n\n- **objective [default=reg:squarederror]**\n\n- It defines the loss function to be minimized. Most commonly used values are given below -\n\n     - **reg:squarederror** : regression with squared loss.\n     \n     - **reg:squaredlogerror**: regression with squared log loss 1\/2[log(pred+1)\u2212log(label+1)]2.               - All input labels are required to be greater than -1. \n     \n     - **reg:logistic** : logistic regression\n     \n     - **binary:logistic** : logistic regression for binary classification, output probability\n     \n     - **binary:logitraw**: logistic regression for binary classification, output score before logistic transformation\n\n     - **binary:hinge** : hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.\n     \n     - **multi:softmax** : set XGBoost to do multiclass classification using the softmax objective, you also need to set num_class(number of classes)\n\n     - **multi:softprob** : same as softmax, but output a vector of ndata * nclass, which can be further reshaped to ndata * nclass matrix. The result contains predicted probability of each data point belonging to each class.                            \n                             \n      \n      \n\"\"\"\n\"\"\"\n### **2.3.2 eval_metric** <a class=\"anchor\" id=\"2.3.2\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **eval_metric [default according to objective]**\n\n\n- The metric to be used for validation data.\n- The default values are **rmse for regression**, **error for classification** and **mean average precision for ranking**.\n- We can add multiple evaluation metrics.\n- Python users must pass the metrices as list of parameters pairs instead of map.\n- The most common values are given below -\n\n   - **rmse** : [root mean square error](https:\/\/en.wikipedia.org\/wiki\/Root-mean-square_deviation)\n   - **mae** : [mean absolute error](https:\/\/en.wikipedia.org\/wiki\/Mean_absolute_error)\n   - **logloss** : [negative log-likelihood](https:\/\/en.wikipedia.org\/wiki\/Likelihood_function#Log-likelihood)\n   - **error** : Binary classification error rate (0.5 threshold).  It is calculated as `#(wrong cases)\/#(all cases)`. For the predictions, the evaluation will regard the instances with prediction value larger than 0.5 as positive instances, and the others as negative instances.\n   - **merror** : Multiclass classification error rate. It is calculated as `#(wrong cases)\/#(all cases)`.\n   - **mlogloss** : [Multiclass logloss](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.metrics.log_loss.html)\n   - **auc**: [Area under the curve](https:\/\/en.wikipedia.org\/wiki\/Receiver_operating_characteristic#Area_under_curve)\n   - **aucpr** : [Area under the PR curve](https:\/\/en.wikipedia.org\/wiki\/Precision_and_recall)\n\n\"\"\"\n\"\"\"\n### **2.3.3 seed** <a class=\"anchor\" id=\"2.3.2\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **seed [default=0]**\n\n  - The random number seed.\n  - This parameter is ignored in R package, use set.seed() instead.\n  - It can be used for generating reproducible results and also for parameter tuning.\n\"\"\"\n\"\"\"\n# **3. Basic Setup** <a class=\"anchor\" id=\"3\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\n\"\"\"\n### **3.1 Import libraries** <a class=\"anchor\" id=\"3.1\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\n# import pandas for data wrangling\nimport pandas as pd\n\n\n# import numpy for Scientific computations\nimport numpy as np\n\n\n# import machine learning libraries\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\n\n\n# import packages for hyperparameters tuning\nfrom hyperopt import STATUS_OK, Trials, fmin, hp, tpe\n\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n\n\"\"\"\n### **3.2 Read dataset** <a class=\"anchor\" id=\"3.2\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\ndata = '\/kaggle\/input\/wholesale-customers-data-set\/Wholesale customers data.csv'\n\ndf = pd.read_csv(data)\n\"\"\"\nI will skip the EDA part, as I have done it in previous kernel - [XGBoost + k-fold CV + Feature Importance](https:\/\/www.kaggle.com\/prashant111\/xgboost-k-fold-cv-feature-importance).\n\"\"\"\n\"\"\"\n### **3.3 Declare feature vector and target variable** <a class=\"anchor\" id=\"3.3\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\nX = df.drop('Channel', axis=1)\n\ny = df['Channel']\n\"\"\"\n- Now, let's take a look at feature vector(X) and target variable(y).\n\"\"\"\nX.head()\ny.head()\n\"\"\"\n- We can see that the y label contain values as 1 and 2.\n\n- We will need to convert it into 0 and 1 for further analysis.\n\n- We will do it as follows -\n\"\"\"\n# convert labels into binary values\n\ny[y == 2] = 0\n\ny[y == 1] = 1\n# again preview the y label\n\ny.head()\n\"\"\"\nWe can see that our target variable (y) has been converted into 0 and 1.\n\"\"\"\n\"\"\"\n### **3.4 Split data into separate training and test set** <a class=\"anchor\" id=\"3.4\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)\n\"\"\"\n# **4. Bayesian Optimization with HYPEROPT** <a class=\"anchor\" id=\"4\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- **Bayesian optimization** is optimization or finding the best parameter for a machine learning or deep learning algorithm. \n\n- **Optimization** is the process of finding a minimum of cost function , that determines an overall better performance of a model on both train-set and test-set.\n\n- In this process, we train the model with various possible range of parameters until a best fit model is obtained. \n\n- **Hyperparameter tuning** helps in determining the optimal tuned parameters and return the best fit model, which is the best practice to follow while building an ML or DL model.\n\n- In this section, we discuss one of the most accurate and successful hyperparameter tuning method, which is **Bayesian Optimization with HYPEROPT**.\n\n- Please see my kernel [Bayesian Optimization using HYPEROPT](https:\/\/www.kaggle.com\/prashant111\/bayesian-optimization-using-hyperopt), for more information on the optimization process using HYPEROPT.\n\n- So, we will start with **HYPEROPT**.\n\n\"\"\"\n\"\"\"\n## **4.1 What is HYPEROPT** <a class=\"anchor\" id=\"4.1\"><\/a>\n\n[Table of Contents](#0.1)\n\n- **HYPEROPT** is a powerful python library that search through an hyperparameter space of values and find the best possible values that yield the minimum of the loss function. \n\n- Bayesian Optimization technique uses Hyperopt to tune the model hyperparameters. Hyperopt is a Python library which is used to tune model hyperparameters.\n\n- More information on Hyperopt can be found at the following link:-\n\nhttps:\/\/hyperopt.github.io\/hyperopt\/?source=post_page\n  \n\n\"\"\"\n\"\"\"\n## **4.2 4 parts of Optimization Process** <a class=\"anchor\" id=\"4.2\"><\/a>\n\n[Table of Contents](#0.1)\n\nThe optimization process consists of 4 parts which are as follows-\n\n\n- **1. Initialize domain space**\n\nThe domain space is the input values over which we want to search.\n\n\n- **2. Define objective function**\n  \nThe objective function can be any function which returns a real value that we want to minimize. In this case, we want to minimize the validation error of a machine learning model with respect to the hyperparameters. If the real value is accuracy, then we want to maximize it. Then the function should return the negative of that metric.\n\n\n- **3. Optimization algorithm**\n\nIt is the method used to construct the surrogate objective function and choose the next values to evaluate.\n\n\n- **4. Results**\n\nResults are score or value pairs that the algorithm uses to build the model.\n\"\"\"\n\"\"\"\n## **4.3 Bayesian Optimization implementation** <a class=\"anchor\" id=\"4.3\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\n\"\"\"\n### **4.3.1 Initialize domain space for range of values** <a class=\"anchor\" id=\"4.3.1\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\nspace={'max_depth': hp.quniform(\"max_depth\", 3, 18, 1),\n        'gamma': hp.uniform ('gamma', 1,9),\n        'reg_alpha' : hp.quniform('reg_alpha', 40,180,1),\n        'reg_lambda' : hp.uniform('reg_lambda', 0,1),\n        'colsample_bytree' : hp.uniform('colsample_bytree', 0.5,1),\n        'min_child_weight' : hp.quniform('min_child_weight', 0, 10, 1),\n        'n_estimators': 180,\n        'seed': 0\n    }\n\"\"\"\nThe available hyperopt optimization algorithms are -\n\n- **hp.choice(label, options)** \u2014 Returns one of the options, which should be a list or tuple.\n\n- **hp.randint(label, upper)** \u2014 Returns a random integer between the range [0, upper).\n\n- **hp.uniform(label, low, high)** \u2014 Returns a value uniformly between low and high.\n\n- **hp.quniform(label, low, high, q)** \u2014 Returns a value round(uniform(low, high) \/ q) * q, i.e it rounds the decimal values and returns an integer.\n\n- **hp.normal(label, mean, std)** \u2014 Returns a real value that\u2019s normally-distributed with mean and standard deviation sigma.\n\"\"\"\n\"\"\"\n### **4.3.2 Define objective function** <a class=\"anchor\" id=\"4.3.2\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\ndef objective(space):\n    clf=xgb.XGBClassifier(\n                    n_estimators =space['n_estimators'], max_depth = int(space['max_depth']), gamma = space['gamma'],\n                    reg_alpha = int(space['reg_alpha']),min_child_weight=int(space['min_child_weight']),\n                    colsample_bytree=int(space['colsample_bytree']))\n    \n    evaluation = [( X_train, y_train), ( X_test, y_test)]\n    \n    clf.fit(X_train, y_train,\n            eval_set=evaluation, eval_metric=\"auc\",\n            early_stopping_rounds=10,verbose=False)\n    \n\n    pred = clf.predict(X_test)\n    accuracy = accuracy_score(y_test, pred>0.5)\n    print (\"SCORE:\", accuracy)\n    return {'loss': -accuracy, 'status': STATUS_OK }\n\"\"\"\n### **4.3.3 Optimization algorithm** <a class=\"anchor\" id=\"4.3.3\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\ntrials = Trials()\n\nbest_hyperparams = fmin(fn = objective,\n                        space = space,\n                        algo = tpe.suggest,\n                        max_evals = 100,\n                        trials = trials)\n\"\"\"\n- Here **best_hyperparams** gives us the optimal parameters that best fit model and better loss function value. \n\n- **trials** is an object that contains or stores all the relevant information such as hyperparameter, loss-functions for each set of parameters that the model has been trained. \n\n- **\u2018fmin\u2019** is an optimization function that minimizes the loss function and takes in 4 inputs - fn, space, algo and max_evals.\n\n- Algorithm used is **tpe.suggest**.\n\"\"\"\n\"\"\"\n### **4.3.4 Print Results** <a class=\"anchor\" id=\"4.3.4\"><\/a>\n\n[Table of Contents](#0.1)\n\"\"\"\nprint(\"The best hyperparameters are : \",\"\\n\")\nprint(best_hyperparams)\n\n\"\"\"\n- The above result give best set of hyperparameters.\n\n\n\"\"\"\n\"\"\"\n# **5. Results and Conclusion** <a class=\"anchor\" id=\"5\"><\/a>\n\n[Table of Contents](#0.1)\n\n\n- In this kernel, we have discussed the XGBoost hyperparameters which are divided into 3 categories - general parameters, booster parameters and learning task parameters.\n\n- We have discussed **Bayesian Optimization with HYPEROPT**.\n\n- We have discussed the 4 parts of optimization process.\n\n- We have found the best hyperparameters for the XGBoost ML model. \n\n- The same technique can be applied to find the optimum hyperparameters for any other ML model.\n\"\"\"\n\"\"\"\n# **6. References** <a class=\"anchor\" id=\"6\"><\/a>\n\n[Table of Contents](#0.1)\n\nThe ideas and concepts in this kernel are taken from the following websites.\n\n\n-\thttps:\/\/xgboost.readthedocs.io\/en\/latest\/tutorials\/param_tuning.html\n\n\n-\thttps:\/\/xgboost.readthedocs.io\/en\/latest\/parameter.html#general-parameters\n\n\n-\thttps:\/\/medium.com\/analytics-vidhya\/hyperparameter-tuning-hyperopt-bayesian-optimization-for-xgboost-and-neural-network-8aedf278a1c9\n\n\n-   https:\/\/www.analyticsvidhya.com\/blog\/2016\/03\/complete-guide-parameter-tuning-xgboost-with-codes-python\/\n\n\n-\thttps:\/\/www.kaggle.com\/yassinealouini\/hyperopt-the-xgboost-model\n\n\"\"\"\n\"\"\"\nSo, now we will come to the end of this kernel.\n\nI hope you find this kernel useful and enjoyable.\n\nYour comments and feedback are most welcome.\n\nThank you\n\n\"\"\"\n\"\"\"\n[Go to Top](#0)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1baa8c02fa3c43'}"}
{"id":"103825","text":"\"\"\"\n# Import library\n\"\"\"\nimport os\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import datasets, transforms, models\nfrom torchvision.utils import make_grid,save_image\nimport cv2\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader, ConcatDataset\n%matplotlib inline\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(device)\n\"\"\"\n# Prepare data\n\"\"\"\n#Hyperparameter\nbatch_size = 8\nimage_size = 64\nnormalization_stats = (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)\ndata_dir = r'..\/input\/pokemon-images-dataset\/pokemon'\nnormal_dataset = datasets.ImageFolder(data_dir, transform=transforms.Compose([\n    transforms.Resize(image_size),\n    transforms.CenterCrop(image_size),\n    transforms.ToTensor(),\n    transforms.Normalize(*normalization_stats)]))\n\n# Augment the dataset with mirrored images\nmirror_dataset = datasets.ImageFolder(data_dir, transform=transforms.Compose([\n    transforms.Resize(image_size),\n    transforms.CenterCrop(image_size),\n    transforms.RandomHorizontalFlip(p=1.0),\n    transforms.ToTensor(),\n    transforms.Normalize(*normalization_stats)]))\n\n# Augment the dataset with color changes\ncolor_jitter_dataset = datasets.ImageFolder(data_dir, transform=transforms.Compose([\n    transforms.Resize(image_size),\n    transforms.CenterCrop(image_size),\n    transforms.ColorJitter(0.5, 0.5, 0.5),\n    transforms.ToTensor(),\n    transforms.Normalize(*normalization_stats)]))\ndata_loader = DataLoader(dataset=ConcatDataset([normal_dataset,mirror_dataset,color_jitter_dataset]), batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False)\n\"\"\"\n# Display some image\n\"\"\"\ndef denorm(image):\n    return image * normalization_stats[1][0] + normalization_stats[0][0]\ndef show_images(images, nmax=64):\n    fig, ax = plt.subplots(figsize=(20, 20))\n    ax.set_xticks([]); ax.set_yticks([])\n    ax.imshow(make_grid(denorm(images.detach()[:nmax]), nrow=8).permute(1, 2, 0))\n    \ndef show_batch(dataloader, nmax=64):\n    for images, _ in dataloader:\n        show_images(images, nmax)\n        break\nshow_batch(data_loader)\n\"\"\"\n# Model\n\"\"\"\ndiscriminator = nn.Sequential(\n    # Input is 3 x 64 x 64\n    nn.Conv2d(3, 64, kernel_size=4, stride=2, padding=1, bias=False),\n    nn.BatchNorm2d(64),\n    nn.LeakyReLU(0.2, inplace=True),\n    # Layer Output: 64 x 32 x 32\n    \n    nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1, bias=False),\n    nn.BatchNorm2d(128),\n    nn.LeakyReLU(0.2, inplace=True),\n    # Layer Output: 128 x 16 x 16\n    \n    nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False),\n    nn.BatchNorm2d(128),\n    nn.LeakyReLU(0.2, inplace=True),\n    # Layer Output: 128 x 8 x 8\n    \n    nn.Conv2d(128, 128, kernel_size=4, stride=2, padding=1, bias=False),\n    nn.BatchNorm2d(128),\n    nn.LeakyReLU(0.2, inplace=True),\n    # Layer Output: 128 x 4 x 4\n    \n    # With a 4x4, we can condense the channels into a 1 x 1 x 1 to produce output\n    nn.Conv2d(128, 1, kernel_size=4, stride=1, padding=0, bias=False),\n    nn.Flatten(),\n    nn.Sigmoid()\n)\ndiscriminator.to(device)\nseed_size = 16\ngenerator = nn.Sequential(\n    # Input seed_size x 1 x 1\n    nn.ConvTranspose2d(seed_size, 128, kernel_size=4, padding=0, stride=1, bias=False),\n    nn.BatchNorm2d(128),\n    nn.ReLU(True),\n    # Layer output: 256 x 4 x 4\n    \n    nn.ConvTranspose2d(128, 128, kernel_size=4, padding=1, stride=2, bias=False),\n    nn.BatchNorm2d(128),\n    nn.ReLU(True),\n    # Layer output: 128 x 8 x 8\n    \n    nn.ConvTranspose2d(128, 128, kernel_size=4, padding=1, stride=2, bias=False),\n    nn.BatchNorm2d(128),\n    nn.ReLU(True),\n    # Layer output: 64 x 16 x 16\n    \n    nn.ConvTranspose2d(128, 64, kernel_size=4, padding=1, stride=2, bias=False),\n    nn.BatchNorm2d(64),\n    nn.ReLU(True),\n    # Layer output: 32 x 32 x 32\n    \n    nn.ConvTranspose2d(64, 3, kernel_size=4, padding=1, stride=2, bias=False),\n    nn.Tanh()\n    # Output: 3 x 64 x 64\n)\ngenerator.to(device)\n\"\"\"\n# Training\n\"\"\"\ndef train_discriminator(real_pokemon, disc_optimizer):\n    # Reset the gradients for the optimizer\n    disc_optimizer.zero_grad()\n    \n    # Train on the real images\n    real_predictions = discriminator(real_pokemon)\n    # real_targets = torch.zeros(real_pokemon.size(0), 1, device=device) # All of these are real, so the target is 0.\n    real_targets = torch.rand(real_pokemon.size(0), 1, device=device) * (0.1 - 0) + 0 # Add some noisy labels to make the discriminator think harder.\n    real_loss = F.binary_cross_entropy(real_predictions, real_targets) # Can do binary loss function because it is a binary classifier\n    real_score = torch.mean(real_predictions).item() # How well does the discriminator classify the real pokemon? (Higher score is better for the discriminator)\n    \n    # Make some latent tensors to seed the generator\n    latent_batch = torch.randn(batch_size, seed_size, 1, 1, device=device)\n    \n    # Get some fake pokemon\n    fake_pokemon = generator(latent_batch)\n    \n    # Train on the generator's current efforts to trick the discriminator\n    gen_predictions = discriminator(fake_pokemon)\n    # gen_targets = torch.ones(fake_pokemon.size(0), 1, device=device)\n    gen_targets = torch.rand(fake_pokemon.size(0), 1, device=device) * (1 - 0.9) + 0.9 # Add some noisy labels to make the discriminator think harder.\n    gen_loss = F.binary_cross_entropy(gen_predictions, gen_targets)\n    gen_score = torch.mean(gen_predictions).item() # How well did the discriminator classify the fake pokemon? (Lower score is better for the discriminator)\n    \n    # Update the discriminator weights\n    total_loss = real_loss + gen_loss\n    total_loss.backward()\n    disc_optimizer.step()\n    return total_loss.item(), real_score, gen_score\ndef train_generator(gen_optimizer):\n    # Clear the generator gradients\n    gen_optimizer.zero_grad()\n    \n    # Generate some fake pokemon\n    latent_batch = torch.randn(batch_size, seed_size, 1, 1, device=device)\n    fake_pokemon = generator(latent_batch)\n    \n    # Test against the discriminator\n    disc_predictions = discriminator(fake_pokemon)\n    targets = torch.zeros(fake_pokemon.size(0), 1, device=device) # We want the discriminator to think these images are real.\n    loss = F.binary_cross_entropy(disc_predictions, targets) # How well did the generator do? (How much did the discriminator believe the generator?)\n    \n    # Update the generator based on how well it fooled the discriminator\n    loss.backward()\n    gen_optimizer.step()\n    \n    # Return generator loss\n    return loss.item()\n\"\"\"\n# Save result\n\"\"\"\nimport os\nfrom torchvision.utils import save_image\n\nRESULTS_DIR = 'results'\nos.makedirs(RESULTS_DIR, exist_ok=True)\n\ndef save_results(index, latent_batch, show=True):\n    # Generate fake pokemon\n    fake_pokemon = generator(latent_batch)\n    \n    # Make the filename for the output\n    fake_file = \"result-image-{0:0=4d}.png\".format(index)\n    \n    # Save the image\n    save_image(denorm(fake_pokemon), os.path.join(RESULTS_DIR, fake_file), nrow=8)\n    print(\"Result Saved!\")\n    \n    if show:\n        fig, ax = plt.subplots(figsize=(20, 20))\n        ax.set_xticks([]); ax.set_yticks([])\n        ax.imshow(make_grid(fake_pokemon.cpu().detach(), nrow=8).permute(1, 2, 0))\nfrom tqdm.notebook import tqdm\nimport torch.nn.functional as F\n\n# Static generation seed batch\nfixed_latent_batch = torch.randn(64, seed_size, 1, 1, device=device)\n\ndef train(epochs, learning_rate, start_idx=1):\n    # Empty the GPU cache to save some memory\n    torch.cuda.empty_cache()\n    \n    # Track losses and scores\n    disc_losses = []\n    disc_scores = []\n    gen_losses = []\n    gen_scores = []\n    \n    # Create the optimizers\n    disc_optimizer = torch.optim.Adam(discriminator.parameters(), lr=learning_rate, betas=(0.5, 0.9))\n    gen_optimizer = torch.optim.Adam(generator.parameters(), lr=learning_rate, betas=(0.5, 0.9))\n    \n    # Run the loop\n    for epoch in range(epochs):\n        # Go through each image\n        for real_img, _ in tqdm(data_loader):\n            real_img = real_img.to(device)\n            # Train the discriminator\n            disc_loss, real_score, gen_score = train_discriminator(real_img, disc_optimizer)\n\n            # Train the generator\n            gen_loss = train_generator(gen_optimizer)\n        \n        # Collect results\n        disc_losses.append(disc_loss)\n        disc_scores.append(real_score)\n        gen_losses.append(gen_loss)\n        gen_scores.append(gen_score)\n        \n        # Print the losses and scores\n        print(\"Epoch [{}\/{}], gen_loss: {:.4f}, disc_loss: {:.4f}, real_score: {:.4f}, gen_score: {:.4f}\".format(\n            epoch+start_idx, epochs, gen_loss, disc_loss, real_score, gen_score))\n        \n        # Save the images and show the progress\n        save_results(epoch + start_idx, fixed_latent_batch, show=False)\n    \n    # Return stats\n    return disc_losses, disc_scores, gen_losses, gen_scores\nlearning_rate = 3e-4\nepochs = 50\nhistory = train(epochs, learning_rate)\n\"\"\"\n# Show some fake images\n\"\"\"\nfrom IPython.display import Image\nImage('.\/results\/result-image-0010.png')\nImage('.\/results\/result-image-0025.png')\nImage('.\/results\/result-image-0050.png')\n# Image('.\/results\/result-image-0075.png')\n# Image('.\/results\/result-image-0100.png')\ndisc_losses, disc_scores, gen_losses, gen_scores = history\n\"\"\"\n# Plotting\n\"\"\"\n# Plot generator and discriminator losses\nplt.plot(disc_losses, '-')\nplt.plot(gen_losses, '-')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend(['Discriminator', 'Generator'])\nplt.title('Losses');\n# Plots scores vs. epochs\nplt.plot(disc_scores, '-')\nplt.plot(gen_scores, '-')\nplt.xlabel('Epoch')\nplt.ylabel('Score')\nplt.legend(['Real', 'Fake'])\nplt.title('Scores');","meta":"{'source': 'AI4Code', 'id': 'bebe8a05fa5f56'}"}
{"id":"103880","text":"\"\"\"\nThe aim of the project is to identify the accuracy of R2 score for different tree-based models, covering:\n- Decision Tree\n- Random Forest\n- XG Boost\n- LightGBM\n\nMeanwhile, the cross validation will be also adopted for model evaluation\n\nThe use of data cleaning is firstly adopted for the input of regression model. \n\n\n\"\"\"\nimport re\nimport sys\nimport time\nimport datetime\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib as mpl\nimport numpy as np\nimport seaborn as sns\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn import linear_model\nimport statsmodels.api as sm\nimport sklearn.model_selection as ms\nfrom sklearn import neighbors\nfrom sklearn import tree\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import KDTree\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split,cross_val_score, ShuffleSplit\nfrom sklearn.model_selection import StratifiedKFold,KFold,GridSearchCV,RandomizedSearchCV\nfrom sklearn import metrics\nfrom sklearn.metrics import r2_score,mean_squared_error,confusion_matrix\n\nfrom xgboost import XGBRegressor \nfrom lightgbm import LGBMRegressor \n\nfrom tensorflow import keras\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\ndatabase = pd.read_csv(r\"..\/input\/google-play-store-apps\/googleplaystore.csv\")# store wine type as an attribute\n\n\n\n#############################################################  \n######Data Cleaning\n\ni = database[database['Category'] == '1.9'].index\ndatabase.loc[i]\ndatabase = database.drop(i)\n\ndatabase = database[pd.notnull(database['Last Updated'])]\ndatabase = database[pd.notnull(database['Content Rating'])]\n\n\nCategoryList = database['Category'].unique().tolist() \nCategoryList = ['cat_' + word for word in CategoryList]\ndatabase = pd.concat([database, pd.get_dummies(database['Category'], prefix='cat')], axis=1)\n\n\ndatabase['Rating'] = database['Rating'].fillna(database['Rating'].median())\ndatabase['Installs'] = database['Installs'].apply(lambda x : x.strip('+').replace(',', ''))\ndatabase['Type'] = pd.get_dummies(database['Type'])\ndatabase['Price'] = database['Price'].apply(lambda x : x.strip('$'))\ndatabase['Last Updated'] = database['Last Updated'].apply(lambda x : time.mktime(datetime.datetime.strptime(x, '%B %d, %Y').timetuple()))\n\n\n#######################################################\n###### Encoding\n\nLE = preprocessing.LabelEncoder()\ndatabase['App'] = LE.fit_transform(database['App'])\ndatabase['Genres'] = LE.fit_transform(database['Genres'])\ndatabase['Content Rating'] = LE.fit_transform(database['Content Rating'])\n\n\n########################################################\n###### Size\n\n\nk_indices = database['Size'].loc[database['Size'].str.contains('k')].index.tolist()\nconverter = pd.DataFrame(database.loc[k_indices, 'Size'].apply(lambda x: x.strip('k')).astype(float).apply(lambda x: x \/ 1024).apply(lambda x: round(x, 3)).astype(str))\ndatabase.loc[k_indices,'Size'] = converter\n\ndatabase['Size'] = database['Size'].apply(lambda x: x.strip('M'))\ndatabase[database['Size'] == 'Varies with device'] = 0\ndatabase['Size'] = database['Size'].astype(float)\n\n\"\"\"\nAfter the shuffled the database, the features of the dataset are selected and listed below:\n\n- App \n- Reviews\n- Size\n- Installs\n- Type \n- Price\n- Content Rating \n- Genres, \n- Last Updated\n\nThe output I want to evaluate is Rating \n\"\"\"\n########################################################\n###### Feature Selection\n\nshuffled_database = database.reindex(np.random.permutation(database.index))\n\n\nfeatures = ['App', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content Rating', 'Genres', 'Last Updated']\nshuffled_database[features]=shuffled_database[features].astype(float)\nX = shuffled_database[features]\ny = shuffled_database['Rating']\n\n\n#######################################################\n##### Train Test Split\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30, random_state=10)\n\n###################################################################\n### DecisionTreeRegressor\n\nDT_Regression = tree.DecisionTreeRegressor(criterion='mae', max_depth=5, min_samples_leaf=5, random_state=42)\nDT_Regression.fit(X_train,y_train)\ny_DT_pred=DT_Regression.predict(X_test)\nDT_Regression_score=DT_Regression.score(X_test,y_test)\n\n\nprint(\"with train test split_DecisionTreeRegression\", DT_Regression_score)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_DT_pred))\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_DT_pred))\nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_DT_pred)), '\\n')\n###################################################################\n### RandomForestRegressor\n\nRF_Regression= RandomForestRegressor(random_state=20)\nRF_Regression.fit(X_train,y_train)\ny_RF_pred=RF_Regression.predict(X_test)\nRF_Regression_score=RF_Regression.score(X_test,y_test)\n\nprint(\"with train test split_RandomForestRegression\", RF_Regression_score)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_RF_pred))\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_RF_pred))\nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_RF_pred)), '\\n')\n\n###################################################################\n### XGBRegressor\n\n\nXGB_Regression= XGBRegressor(random_state=20)\nXGB_Regression.fit(X_train,y_train)\ny_XBG_pred=XGB_Regression.predict(X_test)\nRF_Regression_score=XGB_Regression.score(X_test,y_test)\n\nprint(\"with train test split_XGBRegression\", RF_Regression_score)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_XBG_pred))\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_XBG_pred))\nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_XBG_pred)), '\\n')\n\n###################################################################\n### LightGBM\n\n\nLGBM_Regression = LGBMRegressor(random_state=20)\nLGBM_Regression.fit(X_train,y_train)\ny_LGBM_pred=LGBM_Regression.predict(X_test)\nLGBM_Regression_socre=LGBM_Regression.score(X_test,y_test)\n\nprint(\"with train test split_LGBM_Regression\", LGBM_Regression_socre)\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_LGBM_pred))\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_LGBM_pred))\nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_LGBM_pred)), '\\n')\n\"\"\"\nThe cross validation is performed in order to evaluate the model with multiple train-test splits. But it is more time consuming compared to train test split\n\"\"\"\n####################################################\n## Result with Cross Validation Score and Prediction\n\nscore_CV_XGB_Regression = cross_val_score(XGB_Regression,X,y,cv=5 ,scoring='r2')\nprint(\"with CV XGB_Regression\", score_CV_XGB_Regression.mean())","meta":"{'source': 'AI4Code', 'id': 'bed68b5d741a3a'}"}
{"id":"15328","text":"# 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 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\n\"\"\"\n\n\n\n\n# Convolutional Neural Networks with KERAS\n\"\"\"\n\"\"\"\nIn this practice, we are going to implement two convolutional neural networks to recognize the digits of the MNIST reference data set. In addition, we will also train a simple super-resolution model. Specifically, the following three points will be implemented:\n\n1. A convolutional neural network of one layer\n2. A deep convolutional neural network with x layers\n3. A super-resolution model\n\nIn all three cases, the Keras library will be used for model implementation, compilation, and training. Next we will also use Keras to predict the image classification of the test set.\n\n\"\"\"\n\"\"\"\n# 0 Initialization and load data\n\n\"\"\"\n\"\"\"\nThe following code loads the necessary packages for the practice and also reads the data that we will use to train the neural network. The MNIST Dataset corresponds to images of digits from 0 to 9 of size 28x28 pixels.\n\"\"\"\nimport numpy as np\nimport keras\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D\nimport matplotlib.pyplot as plt\n\n# Download the MNIST dataset and partition train \/ test\ntrain = pd.read_csv(\"..\/input\/digit-recognizer\/train.csv\") \ntest = pd.read_csv(\"..\/input\/digit-recognizer\/test.csv\") \n\nx_train_orig = np.array(train.iloc[:, :-1].values)\ny_train_orig = np.array(train.iloc[:, 1].values)\nx_test_orig = np.array(test.iloc[:, :-1].values)\ny_test_orig = np.array(test.iloc[:, 1].values)\n\n# Checking an example\nfirst_image = x_train_orig[0]\nfirst_image = np.array(first_image, dtype='float')\npixels = first_image.reshape((28, 28))\nplt.imshow(pixels, cmap='gray')\nplt.show()\n# Shape\nx_train_orig[0].shape\n\"\"\"\n## 1. Convolutional Neural Network with one layer\n\n\"\"\"\n\"\"\"\nNext we will implement a convolutional neural network of one layer and we will do the training and test on the MNIST dataset. We have 60,000 images to train and 10,000 to test.\n\"\"\"\n\"\"\"\n### 1.1 Pre-processing data\n\nThe first step in training a neural network is to pre-process the training and test data to match the input of the neural network.\n\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n\n<strong> Adjust dimensions in images (X input): <\/strong> Adjust the size of the training and test data using 4 dimensions (the last dimension has to be 1 to indicate that the images are in gray scale). TIP: use the number of training and test data and the size of the images.\n<\/div>\n\"\"\"\n\"\"\"\n<div style=\"background-color: #C7FCE5; border-color: #61FEBA; border-left: 5px solid #61FEBA; padding: 0.5em;\">\nWe have 'reshaped' x_train_orig and x_test_orig since our CNN will only accept a four-dimensional vector. Also, we set our tuple consisting of:\n     <ul>\n         <li> the 60,000 images that we have in training camp, <\/li>\n         <li> 28 the height of the image, <\/li>\n         <li> 28 the width of the image and <\/li>\n         <li> 1 which will be the number of channels. (1 for grayscale and 3 for RGB colors) <\/li>\n     <\/ul>\n<\/div>\n\"\"\"\nprint('Training data shape : ', x_train_orig.shape, y_train_orig.shape)\n\nprint('Testing data shape : ', x_test_orig.shape, y_test_orig.shape)\n\nnCols, nDims = 784, 1\ninput_shape = (nRows, nCols, nDims)\nx_train = x_train_orig.reshape(x_train_orig.shape, nCols, nDims, 1)\nx_test = x_test_orig.reshape(x_test_orig.shape, nCols, nDims, 1)\nprint(nRows, nCols, nDims, 1)\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong> Coding the output (Y output): <\/strong> Coding the values of the output tags into a one-hot vector. For example, the output vector for an image containing a 5 would be: [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.]. TIP: Keras.utils to_categorical function can be used.\n<\/div>\n\"\"\"\nx_train = x_train \/ 255\nx_test = x_test \/ 255\n\nnum_classes = 10\ny_train = to_categorical(y_train_orig, num_classes)\ny_test = to_categorical(y_test_orig, num_classes)\ny_train[5]\n\"\"\"\n### 1.2 Model Creation\n\n\nWe are going to use a Keras Sequential model since it is very easy to use. These types of models allow us to build the model layer by layer. Specific:\n\n- The first layer we will add will be a convolutional layer with the following properties:\n\u00a0\u00a0\u00a0\u00a0 - Number of kernels (neurons) first layer: 64 neurons\n\u00a0\u00a0\u00a0\u00a0 - Kernels size: 3x3\n\u00a0\u00a0\u00a0\u00a0 - Activation of kernels: ReLU\n- Next we will add a Flatten layer to connect the output of the convolutional layer with the input of a dense layer.\n- Finally, we will add a dense output layer, and therefore it will have as many neurons as we want to predict classes. The activation of this last layer will be Softmax. The final prediction of the model will then be the class with the highest probability.\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Model construction<\/strong>\n<\/div>\n\"\"\"\nnum_classes = 10\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n                 activation='relu',\n                 input_shape=(28,28,1)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(num_classes, activation='softmax'))\n\"\"\"\n### 1.3 Build the model\n\nOnce the model is defined, it must be compiled so that Keras prepares the training. For this we are going to use the ADAM optimization algorithm, the cost function \"categorical_crossentropy\" and the \"accuracy\" metric\n\"\"\"\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\"\"\"\n### 1.4 Model training\n\nWe now train the model. To do this, we will make the model see each image 9 different times, and we will use the test set to validate the process.\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Training the model<\/strong> \n<\/div>\n\"\"\"\n#Entrenamiento del modelo\nn_epochs_onelayer = 9\nmfit_onelayer = model.fit(x_train, y_train,\n                              epochs=n_epochs_onelayer,\n                              verbose=1,\n                              validation_data=(x_test, y_test))\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\"\"\"\n### 1.5  Accuracy evolution\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\nVisualize the evolution of accuracy in the training and test set according to the times.\n<\/div>\n\"\"\"\n# plot del training loss y el accuracy\ndef plot_prediction(n_epochs, mfit):\n\n    # Plot training & validation loss values\n    plt.plot(mfit.history['loss'])\n    plt.plot(mfit.history['val_loss'])\n    title = 'Model loss (' + str(n_epochs) + ' epochs)'\n    plt.title(title)\n    plt.ylabel('Loss')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()\n    \n    return plt\nplot_prediction(n_epochs_onelayer, mfit_onelayer)\nmfit_onelayer\n\"\"\"\n### 1.6 Prediction\n\nFinally we can make the prediction for four of the images in the test set and see if the results are correct or not\n\"\"\"\n# Hacemos la predicci\u00f3n para las 4 primeras im\u00e1genes del set de test\nprint(model.predict(x_test[:4]))\n\n# Mostramos el ground truth para las primeras 4 im\u00e1genes\ny_test[:4]\n\"\"\"\n## 2. Deep CNN + Dropout \n\"\"\"\n\"\"\"\nIn the previous exercise we have implemented a single layer convolutional network. Now we are going to implement a deep convolutional neural network and we will see how this translates into better performance in the results. We will initialize and pre-process the data first.\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Coding the Y output tags<\/strong> \n<\/div>\n\"\"\"\ny_train = to_categorical(y_train_orig)\ny_test = to_categorical(y_test_orig)\n\"\"\"\nIn this case we will use a Keras Sequential model again that will consist of:\n- Two convolution layers of 32 and 64 kernels respectively of 3x3 size, and with a reluctance activation function\n- A MaxPooling layer with a size of 2x2\n- A Dropout layer with a rate = 0.25\n- A Flatten layer\n- A dense layer with 128 neurons and a brilliant activation function\n- A Dropout layer with a rate = 0.5\n- A dense layer with softmax activation function\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Development<\/strong> \n<\/div>\n\"\"\"\ndef creaModeloRedNeuronalProfunda():\n    num_classes = 10\n\n    model = Sequential()\n\n    ##TODO: A\u00f1adir las capas\n    model.add(Conv2D(32, kernel_size=(3, 3),\n                 activation='relu',\n                 input_shape=(28,28,1)))\n    model.add(Conv2D(64, (3, 3), padding='valid', activation='relu'))\n    model.add(Dropout(0.25))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu'))\n    model.add(Dropout(0.5))\n    model.add(Dense(num_classes, activation='softmax'))\n    \n    return model\n\n\"\"\"\nWe then compile, train and evaluate the model. For compilation we will use the cost function \"categorical_crossentropy\" and the metric \"accuracy\" again, but in this case we will use the Adadelta optimizer.\n\nWe will train the model for 12 periods, using a batch_size of 128, and the test set to validate. Finally we will also use the test set to evaluate the model.\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Training<\/strong> \n<\/div>\n\"\"\"\nbatch_size = 128\nn_epochs = 12 \n\ndeep_model = creaModeloRedNeuronalProfunda()\n\ndeep_model.compile(optimizer='adadelta',\n                   loss='categorical_crossentropy',\n                   metrics=['accuracy'])\n\ndeep_model.summary()\nmfit = deep_model.fit(x_train, y_train, batch_size=batch_size, epochs=n_epochs, verbose=1, \n                   validation_data=(x_test, y_test))\n\n\n# Evaluation in test\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n# Visualizci\u00f3n de la evoluci\u00f3n de la m\u00e9trica accuracy\nplot_prediction(n_epochs, mfit)\n# Prediction\nprint(model.predict(x_test[:4]))\ny_test[:4]\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Analysis<\/strong>\n<\/div>\n\"\"\"\n\"\"\"\nBy looking at the graphs of the Accuracy measurement of a '* normal convolutional network *' and a deep '* CNN + Dropout *' we can assure that ** this second ** method (CNN + Dropout) has a higher ** accuracy ** comparing it to the first one. In addition, it greatly minimizes the cost function (** loss function **), obtaining much smaller * loss * values. The two layers *** dropout *** probability ** 0.25 and 0.5 ** contribute to the model ** with much more outstanding results, allowing a noticeable increase in the generalizability of the network ** and consequently better results are obtained. On the other hand, ** CNN + Dropout training is much faster ** for each epoch (epoch).\n\nIncreasing the number of intermediate layers can be a possible improvement of the model and an increase in the processing and classification capacity, but we must take into account and adjust the possible over-specialization that this may imply.\n\"\"\"\n\"\"\"\n## 3. CNN applying for super resolution (encoder-decoder)\n\"\"\"\n\"\"\"\nIn this exercise we will build a convolutional neural network such that, given low resolution images, it allows us to obtain the same images but with a higher resolution. To do this, from the same MNIST dataset we will create low-resolution images with which we will train our model.\n\"\"\"\n\"\"\"\nFirst we reduce the resolution of the images:\n\"\"\"\nx_train = x_train_orig[:, ::2, ::2]\nx_test = x_test_orig[:, ::2, ::2]\n\"\"\"\nAnd we normalize the pixel values and adjust the dimensions of the data:\n\"\"\"\n# Normalizamos los valores de los p\u00edxeles\nx_train = x_train \/ 255.0\nx_test = x_test \/ 255.0\n\ny_train = x_train_orig \/ 255.0\ny_test = x_test_orig \/ 255.0\n\n# Ajustamos las dimensiones de los datos\nx = np.expand_dims(x_train, axis=3)\ny = np.expand_dims(y_train, axis=3)\n\nx_test_final = np.expand_dims(x_test, axis=3)\ny_test_final = np.expand_dims(y_test, axis=3)\ny_test.shape\n\ny.shape\n\"\"\"\n### 3.1 Model creation and training\n\n\"\"\"\n\"\"\"\nNext we will create and train the model with the following characteristics:\n\n- A convolutional layer of 32 kernels of 3x3 size, and with a relu activation function.\n- A MaxPooling layer with a size of 2x2.\n- Another convolutional layer of 32 kernels of 3x3 size, and with relu activation function.\n- A deconvolutionary layer with 32 kernels, size 3x3, stride 2x2, and relu activation function.\n- A last deconvolutionary layer with a single kernel of size 3x3, stride 2x2, and activation function sigmoid.\n\nAll convolutional and deconvolutionary layers have to have the padding parameter \"sames\", so that the size of the images is not affected in these layers.\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Model creation<\/strong>\n<\/div>\n\"\"\"\ndef creaModeloRedNeuronalConvolucional():\n    num_classes = 10\n\n    model = Sequential()\n\n    # Add layer  \n    model.add(Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', input_shape=(14, 14, 1)))    \n    model.add(MaxPooling2D(pool_size=(2,2)))\n    model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\n    # deconvolutional layer\n    model.add(keras.layers.Conv2DTranspose(32, (3, 3), strides=(2, 2), padding='same', activation='relu'))\n    model.add(keras.layers.Conv2DTranspose(1, (3, 3), strides=(2, 2), padding='same', activation='sigmoid'))\n    \n    return model\n# Model creation\nconvolutional_network = creaModeloRedNeuronalConvolucional()\n\nconvolutional_network.summary()\n#Entrenar y compilar el modelo\nconvolutional_network.compile(loss='binary_crossentropy',\n              optimizer='Adadelta',\n              metrics=['accuracy'])\nn_epochs = 12 \nconvolutional_network.fit(x, y, epochs=n_epochs, validation_data=(x_test_final, y_test_final))\n\"\"\"\n### 3.2 Predicci\u00f3n de algunas im\u00e1genes del conjunto de test\n\"\"\"\n\"\"\"\n<div style=\"background-color: #EDF7FF; border-color: #7C9DBF; border-left: 5px solid #7C9DBF; padding: 0.5em;\">\n<strong>Ejercicio [1 pto.]:<\/strong> Visualizar tres im\u00e1genes al azar del conjunto de test. Mostrar la versi\u00f3n original de la imagen, la versi\u00f3n con resoluci\u00f3n reducida, y la predicci\u00f3n del modelo.\n<\/div>\n\"\"\"\n# Predicci\u00f3n de tres im\u00e1genes del conjunto de test\nn_images = 3\nidx_images = np.random.randint(x_test.shape[0], size=n_images)\n\nimages = np.expand_dims(np.stack([x_test[i] for i in idx_images]), axis=3)\n\npred = convolutional_network.predict(images)\n\n# Ajustamos las dimensiones de las im\u00e1genes predichas al formato adecuado y desnormalizamos los p\u00edxeles\npred = np.squeeze(pred)\npred = pred * 255.0\ndef drawImage(i, pred, alto, ancho):\n  #Visualizamos la imagen i del dataset\n  first_image = pred[i]\n  first_image = np.array(first_image, dtype='float')\n  pixels = first_image.reshape((alto, ancho))\n  plt.imshow(pixels, cmap='gray')\n  plt.show()\n#Visualizamos la primera imagen \ndrawImage(0, images, 14, 14)\ndrawImage(0, pred, 28, 28)\n\n\"\"\"\nHere we can observe first the reduced image and secondly the image predicted from our neural network model. Next we will do the same with the other 2 remaining examples.\n\"\"\"\n#Visualizamos la segunda imagen \ndrawImage(1, images, 14, 14)\ndrawImage(1, pred, 28, 28)\n\n#Visualizamos la tercera imagen \ndrawImage(2, images, 14, 14)\ndrawImage(2, pred, 28, 28)","meta":"{'source': 'AI4Code', 'id': '1bff8fbc6648f8'}"}
{"id":"91848","text":"\"\"\"\n## Importing Libraries\n\"\"\"\n!pip install tensor-sensor\nimport tsensor\nimport numpy as np\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding, GlobalAveragePooling1D\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n## Tokenization\n\"\"\"\n# Tokenising sentences\nsentences = [\n    'The quick brown fox jumps over the lazy dog.'\n]\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(sentences)\nprint(\"Word Index       :\", tokenizer.word_index)\ntrain_sequence = tokenizer.texts_to_sequences(sentences)\ntrain_sequence = np.array(train_sequence)\nprint(\"Sentence Sequence :\", train_sequence)\n\"\"\"\n## Creating Embedding Layer\n\"\"\"\n# Create a random embedding layer\nembedding = Embedding(input_dim=len(train_sequence[0]), output_dim=128)\n# Get the embeddings of the train sample\ntrain_sample = embedding(train_sequence)\nprint(\"Shape of Input          :\", train_sequence.shape)\nprint(\"Shape of Embedded Input :\", train_sample.shape)\nwith tsensor.explain(fontname='Hack', dimfontname='Hack'):\n    train_sample = embedding(train_sequence)\ntrain_sample[0]\n\"\"\"\n## Average Across Tokens\n\"\"\"\nGlobalAveragePooling1D()(train_sample)\nwith tsensor.explain(fontname='Hack', dimfontname='Hack'):\n    z = GlobalAveragePooling1D()(train_sample)\n\"\"\"\n## Create Word Embeddings for More than One Sentence\n\"\"\"\n# More than one sentence\n\ntest_corpus = [\n    'The quick brown fox jumps over the lazy dog.',\n    'The quick brown fox.',\n    'The lazy dog',\n    'The dog',\n    'Dog and the fox',\n    'Hello, world!'\n]\n\nencoded_sentences = tokenizer.texts_to_sequences(test_corpus)\ni = 1\nfor sentence, encoded_sentence in zip(test_corpus, encoded_sentences):\n    print(\"Sentence\",str(i) + \" :\", sentence)\n    print(\"Sequence   :\", encoded_sentence)\n    print(\"---------------------------------------------------------\")\n    i+=1\n\"\"\"\n## Padding Sequences\n\"\"\"\n# Length of each sentence in the corpus\nprint(\"Length :\", [len(sentence) for sentence in encoded_sentences])\n# Length of the longest sentence\nprint(\"Max Length :\", max([len(sentence) for sentence in encoded_sentences]))\nMAX_SEQUENCE_LENGTH = 9\n# Padding sequence that are shorter than the longest sequence\nX = pad_sequences(encoded_sentences, maxlen=MAX_SEQUENCE_LENGTH)\nX","meta":"{'source': 'AI4Code', 'id': 'a87e6e8d63db49'}"}
{"id":"71249","text":"\"\"\"\n# Dubai Satellite Imagery Semantic Segmentation\nHumans in the Loop has published an open access dataset annotated for a joint project with the Mohammed Bin Rashid Space Center in Dubai, the UAE. \n\nThe dataset consists of aerial imagery of Dubai obtained by MBRSC satellites and annotated with pixel-wise semantic segmentation in 6 classes. The images were segmented by the trainees of the Roia Foundation in Syria.\n\nOriginal Dataset Link: https:\/\/humansintheloop.org\/resources\/datasets\/semantic-segmentation-dataset\/\n\"\"\"\n\"\"\"\n# Installing & Importing Libraries\n\"\"\"\n!pip install keract\nimport keract\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport albumentations as A\nfrom IPython.display import SVG\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport os, re, sys, random, shutil, cv2\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam, Nadam\nfrom tensorflow.keras import applications, optimizers\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.utils import model_to_dot, plot_model\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger, LearningRateScheduler\nfrom tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, MaxPool2D, Conv2DTranspose, Concatenate, ZeroPadding2D, Dropout\n\"\"\"\n# Data Augmentation using Albumentations Library\n[Albumentations](https:\/\/albumentations.ai\/) is a Python library for fast and flexible image augmentations. Albumentations efficiently implements a rich variety of image transform operations that are optimized for performance, and does so while providing a concise, yet powerful image augmentation interface for different computer vision tasks, including object classification, segmentation, and detection.\n\nData augmentation is done by the following techniques:\n\n1. Random Cropping\n2. Horizontal Flipping\n3. Vertical Flipping\n4. Rotation\n5. Random Brightness & Contrast\n6. Contrast Limited Adaptive Histogram Equalization (CLAHE)\n7. Grid Distortion\n8. Optical Distortion\n\"\"\"\ndef augment(width, height):\n    transform = A.Compose([\n        A.RandomCrop(width=width, height=height, p=1.0),\n        A.HorizontalFlip(p=1.0),\n        A.VerticalFlip(p=1.0),\n        A.Rotate(limit=[60, 300], p=1.0, interpolation=cv2.INTER_NEAREST),\n        A.RandomBrightnessContrast(brightness_limit=[-0.2, 0.3], contrast_limit=0.2, p=1.0),\n        A.OneOf([\n            A.CLAHE (clip_limit=1.5, tile_grid_size=(8, 8), p=0.5),\n            A.GridDistortion(p=0.5),\n            A.OpticalDistortion(distort_limit=1, shift_limit=0.5, interpolation=cv2.INTER_NEAREST, p=0.5),\n        ], p=1.0),\n    ], p=1.0)\n    \n    return transform\ndef visualize(image, mask, original_image=None, original_mask=None):\n    fontsize = 16\n\n    if original_image is None and original_mask is None:\n        f, ax = plt.subplots(2, 1, figsize=(10, 10), squeeze=True)\n        f.set_tight_layout(h_pad=5, w_pad=5)\n\n        ax[0].imshow(image)\n        ax[1].imshow(mask)\n    else:\n        f, ax = plt.subplots(2, 2, figsize=(16, 12), squeeze=True)\n        plt.tight_layout(pad=0.2, w_pad=1.0, h_pad=0.01)\n\n        ax[0, 0].imshow(original_image)\n        ax[0, 0].set_title('Original Image', fontsize=fontsize)\n\n        ax[1, 0].imshow(original_mask)\n        ax[1, 0].set_title('Original Mask', fontsize=fontsize)\n\n        ax[0, 1].imshow(image)\n        ax[0, 1].set_title('Transformed Image', fontsize=fontsize)\n\n        ax[1, 1].imshow(mask)\n        ax[1, 1].set_title('Transformed Mask', fontsize=fontsize)\n        \n    plt.savefig('sample_augmented_image.png', facecolor= 'w', transparent= False, bbox_inches= 'tight', dpi= 100)\nimage = cv2.imread(\"..\/input\/dubai-aerial-imagery-dataset\/train_images\/train\/image_t8_007.jpg\")\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nmask = cv2.imread(\"..\/input\/dubai-aerial-imagery-dataset\/train_masks\/train\/image_t8_007.png\")\nmask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)\n\ntransform = augment(1920, 1280)\ntransformed = transform(image=image, mask=mask)\ntransformed_image = transformed['image']\ntransformed_mask = transformed['mask']\n\ncv2.imwrite('.\/image.png',cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB))\ncv2.imwrite('.\/mask.png',cv2.cvtColor(transformed_mask, cv2.COLOR_BGR2RGB))\n\nvisualize(transformed_image, transformed_mask, image, mask)\n\"\"\"\n# Saving Augmented Images to Disk\nI have already performed data augmentation and saved the images. I am not running it's code in this notebook. It is a very time consuming process, so be patient while the code cell runs!\n\"\"\"\n!mkdir aug_images\n!mkdir aug_masks\nimages_dir = '..\/input\/dubai-aerial-imagery-dataset\/train_images\/train\/'\nmasks_dir = '..\/input\/dubai-aerial-imagery-dataset\/train_masks\/train\/'\nfile_names = np.sort(os.listdir(images_dir)) \nfile_names = np.char.split(file_names, '.')\nfilenames = np.array([])\nfor i in range(len(file_names)):\n    filenames = np.append(filenames, file_names[i][0])\ndef augment_dataset(count):\n    '''Function for data augmentation\n        Input:\n            count - total no. of images after augmentation = initial no. of images * count\n        Output:\n            writes augmented images (input images & segmentation masks) to the working directory\n    '''\n    transform_1 = augment(512, 512)\n    transform_2 = augment(480, 480)\n    transform_3 = augment(512, 512)\n    transform_4 = augment(800, 800)\n    transform_5 = augment(1024, 1024)\n    transform_6 = augment(800, 800)\n    transform_7 = augment(1600, 1600)\n    transform_8 = augment(1920, 1280)\n    \n    i = 0\n    for i in range(count):\n        for file in filenames:\n            tile = file.split('_')[1]\n            img = cv2.imread(images_dir+file+'.jpg')\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n            mask = cv2.imread(masks_dir+file+'.png')\n            mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)\n            \n            if tile == 't1':\n                transformed = transform_1(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t2':\n                transformed = transform_2(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t3':\n                transformed = transform_3(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t4':\n                transformed = transform_4(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t5':\n                transformed = transform_5(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t6':\n                transformed = transform_6(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t7':\n                transformed = transform_7(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n            elif tile =='t8':\n                transformed = transform_8(image=img, mask=mask)\n                transformed_image = transformed['image']\n                transformed_mask = transformed['mask']\n                \n            cv2.imwrite('.\/aug_images\/aug_{}_'.format(str(i+1))+file+'.jpg',cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB))\n            cv2.imwrite('.\/aug_masks\/aug_{}_'.format(str(i+1))+file+'.png',cv2.cvtColor(transformed_mask, cv2.COLOR_BGR2RGB))\naugment_dataset(8)\n!zip -r aug_images.zip '.\/aug_images\/'\n!zip -r aug_masks.zip '.\/aug_masks\/'\n!rm -rf '.\/aug_images\/'\n!rm -rf '.\/aug_masks\/'\n\"\"\"\n# Working with Augmented Dataset\n\"\"\"\ntrain_images = \"..\/input\/augmented-dubai-aerial-imagery-dataset\/train_images\/\"\ntrain_masks = \"..\/input\/augmented-dubai-aerial-imagery-dataset\/train_masks\/\"\nval_images = \"..\/input\/augmented-dubai-aerial-imagery-dataset\/val_images\/\"\nval_masks = \"..\/input\/augmented-dubai-aerial-imagery-dataset\/val_masks\/\"\nfile_names = np.sort(os.listdir(train_images + 'train\/')) \nfile_names = np.char.split(file_names, '.')\nfilenames = np.array([])\nfor i in range(len(file_names)):\n    filenames = np.append(filenames, file_names[i][0])\ndef show_data(files, original_images_dir, label_images_dir):\n\n    for file in files:\n        fig, axs = plt.subplots(1, 2, figsize=(15, 6), constrained_layout=True)\n        \n        axs[0].imshow(cv2.resize(cv2.imread(original_images_dir+'train\/'+str(file)+'.jpg'), (2000,1400)))\n        axs[0].set_title('Original Image', fontdict = {'fontsize':14, 'fontweight': 'medium'})\n        axs[0].set_xticks(np.arange(0, 2001, 200))\n        axs[0].set_yticks(np.arange(0, 1401, 200))\n        axs[0].grid(False)\n        axs[0].axis(True)\n\n        semantic_label_image = cv2.imread(label_images_dir+ 'train\/'+str(file)+'.png')\n        semantic_label_image = cv2.cvtColor(semantic_label_image, cv2.COLOR_BGR2RGB)\n        semantic_label_image = cv2.resize(semantic_label_image, (2000,1400))\n        axs[1].imshow(semantic_label_image)\n        axs[1].set_title('Semantic Segmentation Mask', fontdict = {'fontsize':14, 'fontweight': 'medium'})\n        axs[1].set_xticks(np.arange(0, 2001, 200))\n        axs[1].set_yticks(np.arange(0, 1401, 200))\n        axs[1].grid(False)\n        axs[1].axis(True)\n\n        plt.savefig('.\/sample_'+file, facecolor= 'w', transparent= False, bbox_inches= 'tight', dpi= 100)\n        plt.show()\n\n        \nfiles = ['image_t4_001', 'image_t4_005', 'image_t6_002', 'image_t7_002', 'image_t8_003', 'image_t8_004', 'image_t8_006']    \nshow_data(files, train_images, train_masks)    \naugmented_files = ['image_t1_002', 'image_t3_002', 'image_t4_006', 'image_t5_004', 'image_t6_007']\ndims = np.array([(512, 512), (512, 512), (800, 800), (800, 800), (800, 800)])\n\ndef show_augmented_images(files, original_images_dir, label_images_dir):\n    dim_index = 0\n    for file in files:\n        count_img = 1\n        count_msk = 1\n        fig, axs = plt.subplots(3, 6, figsize=(25, 12), constrained_layout=True)\n        for i in range(3):\n            for j in range(6):\n                if i == 0 and j == 0:\n                    axs[i][j].imshow(cv2.resize(cv2.cvtColor(cv2.imread(original_images_dir+'train\/'+str(file)+'.jpg'), cv2.COLOR_BGR2RGB), tuple(dims[dim_index])))\n                    axs[i][j].set_title('Original Image: {}.jpg'.format(file), fontdict = {'fontsize':12, 'fontweight': 'medium'})\n                    axs[i][j].set_xticks(np.arange(0, dims[dim_index][0]+1, 100))\n                    axs[i][j].set_yticks(np.arange(0, dims[dim_index][1]+1, 100))\n                    axs[i][j].grid(False)\n                    axs[i][j].axis(True)\n                elif i == 0 and j == 1:\n                    axs[i][j].imshow(cv2.resize(cv2.cvtColor(cv2.imread(label_images_dir+'train\/'+str(file)+'.png'), cv2.COLOR_BGR2RGB), tuple(dims[dim_index])))\n                    axs[i][j].set_title('Original Mask: {}.png'.format(file), fontdict = {'fontsize':12, 'fontweight': 'medium'})\n                    axs[i][j].set_xticks(np.arange(0, dims[dim_index][0]+1, 100))\n                    axs[i][j].set_yticks(np.arange(0, dims[dim_index][1]+1, 100))\n                    axs[i][j].grid(False)\n                    axs[i][j].axis(True)\n                else:\n                    if j%2 == 0:\n                        axs[i][j].imshow(cv2.resize(cv2.cvtColor(cv2.imread(original_images_dir+'train\/aug_'+str(count_img)+'_'+str(file)+'.jpg'), cv2.COLOR_BGR2RGB), tuple(dims[dim_index])))\n                        axs[i][j].set_title('Augmented Image: aug_{}.jpg'.format(str(count_img)+'_'+str(file)), fontdict = {'fontsize':12, 'fontweight': 'medium'})\n                        axs[i][j].set_xticks(np.arange(0, dims[dim_index][0]+1, 100))\n                        axs[i][j].set_yticks(np.arange(0, dims[dim_index][1]+1, 100))\n                        axs[i][j].grid(False)\n                        axs[i][j].axis(True)\n                        count_img += 1\n                    elif j%2 != 0:\n                        axs[i][j].imshow(cv2.resize(cv2.cvtColor(cv2.imread(label_images_dir+'train\/aug_'+str(count_msk)+'_'+str(file)+'.png'), cv2.COLOR_BGR2RGB), tuple(dims[dim_index])))\n                        axs[i][j].set_title('Augmented Mask: aug_{}.png'.format(str(count_msk)+'_'+str(file)), fontdict = {'fontsize':12, 'fontweight': 'medium'})\n                        axs[i][j].set_xticks(np.arange(0, dims[dim_index][0]+1, 100))\n                        axs[i][j].set_yticks(np.arange(0, dims[dim_index][1]+1, 100))\n                        axs[i][j].grid(False)\n                        axs[i][j].axis(True)\n                        count_msk += 1\n\n        plt.savefig('aug_image_'+file, facecolor= 'w', transparent= False, bbox_inches= 'tight', dpi= 100)\n        dim_index += 1\n        plt.show()\n\nshow_augmented_images(augmented_files, train_images, train_masks)\nclass_dict_df = pd.read_csv('..\/input\/dubai-aerial-imagery-dataset\/class_dict.csv', index_col=False, skipinitialspace=True)\nclass_dict_df\nlabel_names= list(class_dict_df.name)\nlabel_codes = []\nr= np.asarray(class_dict_df.r)\ng= np.asarray(class_dict_df.g)\nb= np.asarray(class_dict_df.b)\n\nfor i in range(len(class_dict_df)):\n    label_codes.append(tuple([r[i], g[i], b[i]]))\n    \nlabel_codes, label_names\n\"\"\"\n# Create Useful Label & Code Conversion Dictionaries\n\nThese will be used for:\n\n* One hot encoding the mask labels for model training\n* Decoding the predicted labels for interpretation and visualization\n\"\"\"\ncode2id = {v:k for k,v in enumerate(label_codes)}\nid2code = {k:v for k,v in enumerate(label_codes)}\n\nname2id = {v:k for k,v in enumerate(label_names)}\nid2name = {k:v for k,v in enumerate(label_names)}\nid2code\nid2name\n\"\"\"\n# Define Functions for One Hot Encoding RGB Labels & Decoding Encoded Predictions\n\"\"\"\ndef rgb_to_onehot(rgb_image, colormap = id2code):\n    '''Function to one hot encode RGB mask labels\n        Inputs: \n            rgb_image - image matrix (eg. 256 x 256 x 3 dimension numpy ndarray)\n            colormap - dictionary of color to label id\n        Output: One hot encoded image of dimensions (height x width x num_classes) where num_classes = len(colormap)\n    '''\n    num_classes = len(colormap)\n    shape = rgb_image.shape[:2]+(num_classes,)\n    encoded_image = np.zeros( shape, dtype=np.int8 )\n    for i, cls in enumerate(colormap):\n        encoded_image[:,:,i] = np.all(rgb_image.reshape( (-1,3) ) == colormap[i], axis=1).reshape(shape[:2])\n    return encoded_image\n\n\ndef onehot_to_rgb(onehot, colormap = id2code):\n    '''Function to decode encoded mask labels\n        Inputs: \n            onehot - one hot encoded image matrix (height x width x num_classes)\n            colormap - dictionary of color to label id\n        Output: Decoded RGB image (height x width x 3) \n    '''\n    single_layer = np.argmax(onehot, axis=-1)\n    output = np.zeros( onehot.shape[:2]+(3,) )\n    for k in colormap.keys():\n        output[single_layer==k] = colormap[k]\n    return np.uint8(output)\n\"\"\"\n# Creating Custom Image Data Generators\n## Defining Data Generators\n\"\"\"\n# Normalizing only frame images, since masks contain label info\ndata_gen_args = dict(rescale=1.\/255)\nmask_gen_args = dict()\n\ntrain_frames_datagen = ImageDataGenerator(**data_gen_args)\ntrain_masks_datagen = ImageDataGenerator(**mask_gen_args)\nval_frames_datagen = ImageDataGenerator(**data_gen_args)\nval_masks_datagen = ImageDataGenerator(**mask_gen_args)\n\n# Seed defined for aligning images and their masks\nseed = 1\n\"\"\"\n# Custom Image Data Generators for Creating Batches of Frames and Masks\n\"\"\"\ndef TrainAugmentGenerator(train_images_dir, train_masks_dir, seed = 1, batch_size = 8, target_size = (512, 512)):\n    '''Train Image data generator\n        Inputs: \n            seed - seed provided to the flow_from_directory function to ensure aligned data flow\n            batch_size - number of images to import at a time\n            train_images_dir - train images directory\n            train_masks_dir - train masks directory\n            target_size - tuple of integers (height, width)\n            \n        Output: Decoded RGB image (height x width x 3) \n    '''\n    train_image_generator = train_frames_datagen.flow_from_directory(\n    train_images_dir,\n    batch_size = batch_size, \n    seed = seed, \n    target_size = target_size)\n\n    train_mask_generator = train_masks_datagen.flow_from_directory(\n    train_masks_dir,\n    batch_size = batch_size, \n    seed = seed, \n    target_size = target_size)\n\n    while True:\n        X1i = train_image_generator.next()\n        X2i = train_mask_generator.next()\n        \n        #One hot encoding RGB images\n        mask_encoded = [rgb_to_onehot(X2i[0][x,:,:,:], id2code) for x in range(X2i[0].shape[0])]\n        \n        yield X1i[0], np.asarray(mask_encoded)\n\ndef ValAugmentGenerator(val_images_dir, val_masks_dir, seed = 1, batch_size = 8, target_size = (512, 512)):\n    '''Validation Image data generator\n        Inputs: \n            seed - seed provided to the flow_from_directory function to ensure aligned data flow\n            batch_size - number of images to import at a time\n            val_images_dir - validation images directory\n            val_masks_dir - validation masks directory\n            target_size - tuple of integers (height, width)\n            \n        Output: Decoded RGB image (height x width x 3) \n    '''\n    val_image_generator = val_frames_datagen.flow_from_directory(\n    val_images_dir,\n    batch_size = batch_size, \n    seed = seed, \n    target_size = target_size)\n\n\n    val_mask_generator = val_masks_datagen.flow_from_directory(\n    val_masks_dir,\n    batch_size = batch_size, \n    seed = seed, \n    target_size = target_size)\n\n\n    while True:\n        X1i = val_image_generator.next()\n        X2i = val_mask_generator.next()\n        \n        #One hot encoding RGB images\n        mask_encoded = [rgb_to_onehot(X2i[0][x,:,:,:], id2code) for x in range(X2i[0].shape[0])]\n        \n        yield X1i[0], np.asarray(mask_encoded)\n\"\"\"\n# Model\n\"\"\"\nbatch_size = 16\nnum_train_samples = len(np.sort(os.listdir(train_images+'train')))\nnum_val_samples = len(np.sort(os.listdir(val_images+'val')))\nsteps_per_epoch = np.ceil(float(num_train_samples) \/ float(batch_size))\nprint('steps_per_epoch: ', steps_per_epoch)\nvalidation_steps = np.ceil(float(4 * num_val_samples) \/ float(batch_size))\nprint('validation_steps: ', validation_steps)\n\"\"\"\n## InceptionResNetV2-UNet\n\"\"\"\ndef conv_block(input, num_filters):\n    x = Conv2D(num_filters, 3, padding=\"same\")(input)\n    x = BatchNormalization()(x)\n    x = Activation(\"relu\")(x)\n\n    x = Conv2D(num_filters, 3, padding=\"same\")(x)\n    x = BatchNormalization()(x)\n    x = Activation(\"relu\")(x)\n\n    return x\n\ndef decoder_block(input, skip_features, num_filters):\n    x = Conv2DTranspose(num_filters, (2, 2), strides=2, padding=\"same\")(input)\n    x = Concatenate()([x, skip_features])\n    x = conv_block(x, num_filters)\n    return x\n\ndef build_inception_resnetv2_unet(input_shape):\n    \"\"\" Input \"\"\"\n    inputs = Input(input_shape)\n\n    \"\"\" Pre-trained InceptionResNetV2 Model \"\"\"\n    encoder = InceptionResNetV2(include_top=False, weights=\"imagenet\", input_tensor=inputs)\n\n    \"\"\" Encoder \"\"\"\n    s1 = encoder.get_layer(\"input_1\").output           ## (512 x 512)\n\n    s2 = encoder.get_layer(\"activation\").output        ## (255 x 255)\n    s2 = ZeroPadding2D(( (1, 0), (1, 0) ))(s2)         ## (256 x 256)\n\n    s3 = encoder.get_layer(\"activation_3\").output      ## (126 x 126)\n    s3 = ZeroPadding2D((1, 1))(s3)                     ## (128 x 128)\n\n    s4 = encoder.get_layer(\"activation_74\").output      ## (61 x 61)\n    s4 = ZeroPadding2D(( (2, 1),(2, 1) ))(s4)           ## (64 x 64)\n\n    \"\"\" Bridge \"\"\"\n    b1 = encoder.get_layer(\"activation_161\").output     ## (30 x 30)\n    b1 = ZeroPadding2D((1, 1))(b1)                      ## (32 x 32)\n\n    \"\"\" Decoder \"\"\"\n    d1 = decoder_block(b1, s4, 512)                     ## (64 x 64)\n    d2 = decoder_block(d1, s3, 256)                     ## (128 x 128)\n    d3 = decoder_block(d2, s2, 128)                     ## (256 x 256)\n    d4 = decoder_block(d3, s1, 64)                      ## (512 x 512)\n    \n    \"\"\" Output \"\"\"\n    dropout = Dropout(0.3)(d4)\n    outputs = Conv2D(6, 1, padding=\"same\", activation=\"softmax\")(dropout)\n\n    model = Model(inputs, outputs, name=\"InceptionResNetV2-UNet\")\n    return model\nK.clear_session()\n\ndef dice_coef(y_true, y_pred):\n    return (2. * K.sum(y_true * y_pred) + 1.) \/ (K.sum(y_true) + K.sum(y_pred) + 1.)\n\nmodel = build_inception_resnetv2_unet(input_shape = (512, 512, 3))\nmodel.compile(optimizer=Adam(lr = 0.0001), loss='categorical_crossentropy', metrics=[dice_coef, \"accuracy\"])\nmodel.summary()\n\"\"\"\n### Model Layout\n\"\"\"\nSVG(model_to_dot(model).create(prog='dot', format='svg'))\nplot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True, expand_nested=True)\n\"\"\"\n# Model Training\n\"\"\"\ndef exponential_decay(lr0, s):\n    def exponential_decay_fn(epoch):\n        return lr0 * 0.1 **(epoch \/ s)\n    return exponential_decay_fn\n\nexponential_decay_fn = exponential_decay(0.0001, 60)\n\nlr_scheduler = LearningRateScheduler(\n    exponential_decay_fn,\n    verbose=1\n)\n\ncheckpoint = ModelCheckpoint(\n    filepath = 'InceptionResNetV2-UNet.h5',\n    save_best_only = True, \n#     save_weights_only = False,\n    monitor = 'val_loss', \n    mode = 'auto', \n    verbose = 1\n)\n\nearlystop = EarlyStopping(\n    monitor = 'val_loss', \n    min_delta = 0.001, \n    patience = 12, \n    mode = 'auto', \n    verbose = 1,\n    restore_best_weights = True\n)\n\ncsvlogger = CSVLogger(\n    filename= \"model_training.csv\",\n    separator = \",\",\n    append = False\n)\n\ncallbacks = [checkpoint, earlystop, csvlogger, lr_scheduler]\nhistory = model.fit(\n    TrainAugmentGenerator(train_images_dir = train_images, train_masks_dir = train_masks, target_size = (512, 512)), \n    steps_per_epoch=steps_per_epoch,\n    validation_data = ValAugmentGenerator(val_images_dir = val_images, val_masks_dir = val_masks, target_size = (512, 512)), \n    validation_steps = validation_steps, \n    epochs = 50,\n    callbacks=callbacks,\n    use_multiprocessing=False,\n    verbose=1\n)\ndf_result = pd.DataFrame(history.history)\ndf_result\n\"\"\"\n## Training Results\n\"\"\"\nfig, ax = plt.subplots(1, 4, figsize=(40, 5))\nax = ax.ravel()\nmetrics = ['Dice Coefficient', 'Accuracy', 'Loss', 'Learning Rate']\n\nfor i, met in enumerate(['dice_coef', 'accuracy', 'loss', 'lr']): \n    if met != 'lr':\n        ax[i].plot(history.history[met])\n        ax[i].plot(history.history['val_' + met])\n        ax[i].set_title('{} vs Epochs'.format(metrics[i]), fontsize=16)\n        ax[i].set_xlabel('Epochs')\n        ax[i].set_ylabel(metrics[i])\n        ax[i].set_xticks(np.arange(0,46,4))\n        ax[i].legend(['Train', 'Validation'])\n        ax[i].xaxis.grid(True, color = \"lightgray\", linewidth = \"0.8\", linestyle = \"-\")\n        ax[i].yaxis.grid(True, color = \"lightgray\", linewidth = \"0.8\", linestyle = \"-\")\n    else:\n        ax[i].plot(history.history[met])\n        ax[i].set_title('{} vs Epochs'.format(metrics[i]), fontsize=16)\n        ax[i].set_xlabel('Epochs')\n        ax[i].set_ylabel(metrics[i])\n        ax[i].set_xticks(np.arange(0,46,4))\n        ax[i].xaxis.grid(True, color = \"lightgray\", linewidth = \"0.8\", linestyle = \"-\")\n        ax[i].yaxis.grid(True, color = \"lightgray\", linewidth = \"0.8\", linestyle = \"-\")\n        \nplt.savefig('model_metrics_plot.png', facecolor= 'w',transparent= False, bbox_inches= 'tight', dpi= 150)\n\"\"\"\n## Predictions\n\"\"\"\nmodel.load_weights(\".\/InceptionResNetV2-UNet.h5\")\ntesting_gen = ValAugmentGenerator(val_images_dir = val_images, val_masks_dir = val_masks, target_size = (512, 512))\ncount = 0\nfor i in range(2):\n    batch_img,batch_mask = next(testing_gen)\n    pred_all= model.predict(batch_img)\n    np.shape(pred_all)\n    \n    for j in range(0,np.shape(pred_all)[0]):\n        count += 1\n        fig = plt.figure(figsize=(20,8))\n\n        ax1 = fig.add_subplot(1,3,1)\n        ax1.imshow(batch_img[j])\n        ax1.set_title('Input Image', fontdict={'fontsize': 16, 'fontweight': 'medium'})\n        ax1.grid(False)\n\n        ax2 = fig.add_subplot(1,3,2)\n        ax2.set_title('Ground Truth Mask', fontdict={'fontsize': 16, 'fontweight': 'medium'})\n        ax2.imshow(onehot_to_rgb(batch_mask[j],id2code))\n        ax2.grid(False)\n\n        ax3 = fig.add_subplot(1,3,3)\n        ax3.set_title('Predicted Mask', fontdict={'fontsize': 16, 'fontweight': 'medium'})\n        ax3.imshow(onehot_to_rgb(pred_all[j],id2code))\n        ax3.grid(False)\n\n        plt.savefig('.\/prediction_{}.png'.format(count), facecolor= 'w', transparent= False, bbox_inches= 'tight', dpi= 200)\n        plt.show()\n\"\"\"\n## Model's Activations (Outputs) Visualization\n\"\"\"\nimage = load_img('..\/input\/augmented-dubai-aerial-imagery-dataset\/val_images\/val\/image_t4_008.jpg', target_size= (512, 512))\nimage = img_to_array(image)\nimage = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\nimage = preprocess_input(image)\ny_hat = model.predict(image)\nlayers=['conv2d', 'conv2d_4', 'conv2d_8', 'conv2d_10', 'conv2d_22', 'conv2d_28', 'conv2d_34', 'conv2d_40', 'conv2d_52', 'conv2d_61', 'conv2d_67', 'conv2d_70']\nactivations= keract.get_activations(model, image, layer_names= layers, nodes_to_evaluate= None, output_format= 'simple', auto_compile= True)\nkeract.display_activations(activations, cmap='viridis', save= False, directory= '.\/activations')","meta":"{'source': 'AI4Code', 'id': '830eb50d30d5e9'}"}
{"id":"82882","text":"# 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\n\"\"\"\n## What's in this Kernel?\n- Data Exploration\n- Date(Text) Clearning\n- BERT Model using K-train\n\"\"\"\n\"\"\"\n## install \"Ktrain\" using pip\n\"\"\"\n!pip install ktrain\n\"\"\"\n## What is K-Train\n\nktrain is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, ktrain is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners.\n\nknow more about it \n-https:\/\/github.com\/amaiya\/ktrain\n\n\n\"\"\"\n\"\"\"\n### Importing required libraries\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom nltk.corpus import stopwords\nfrom nltk.util import ngrams\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom collections import defaultdict\nfrom collections import  Counter\nplt.style.use('ggplot')\nstop=set(stopwords.words('english'))\nimport re\nfrom nltk.tokenize import word_tokenize\nimport gensim\nimport string\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tqdm import tqdm\nfrom keras.models import Sequential\nfrom keras.layers import Embedding,LSTM,Dense,SpatialDropout1D\nfrom keras.initializers import Constant\nfrom sklearn.model_selection import train_test_split\nfrom keras.optimizers import Adam\nimport ktrain\nfrom ktrain import text\n\n\nimport matplotlib as mpl\nfrom cycler import cycler\nplt.style.use('ggplot')\n\"\"\"\n### load the dataset check head\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/nlp-getting-started\/train.csv\")\ntest = pd.read_csv(\"..\/input\/nlp-getting-started\/test.csv\")\n\ntrain.head(3)\n\"\"\"\n## check the shape of the data\n\"\"\"\ntrain.shape, test.shape\n\"\"\"\n## Data Exploration (EDA)\n\"\"\"\n# check for class distribution\nsns.countplot(train['target'])\n\n# class(0) :- No Disaster\n# class(1) :- Disaster\n\"\"\"\n## No of character in tweet\n\"\"\"\n# check no of character in tweet\nplt.style.use('seaborn-dark')\nfig, ax = plt.subplots(1,2,figsize=(10,5))\n\n# for target 0 \nax[0].hist(train[train['target']==0]['text'].str.len(),color='b',bins=20)\nax[0].set_title(\"Not Disaster Tweets len\");\n\n# for target 1\nax[1].hist(train[train['target']==1]['text'].str.len(),color='c',bins=20)\nax[1].set_title(\"Disaster Tweets len\");\n\n\"\"\"\n## No of words in tweet\n\"\"\"\n# check no of character in tweet\nfig, ax = plt.subplots(1,2,figsize=(10,5))\n\n# for target 0 \nax[0].hist(train[train['target']==0]['text'].str.split().map(lambda x:len(x)),color='b',bins=20)\nax[0].set_title(\"Not Disaster Tweets len\");\n\n# for target 1\nax[1].hist(train[train['target']==1]['text'].str.split().map(lambda x:len(x)),color='c',bins=20)\nax[1].set_title(\"Disaster Tweets len\");\n\nplt.show()\n\n\"\"\"\n## Stopwords counts\n\"\"\"\ndef create_corpus(target):\n    corpus = []\n    for x in train[train['target'] == target]['text'].str.split():\n        for i in x:\n            corpus.append(i)\n    return corpus\n\n# for class 0\ncorpus = create_corpus(0)\n\ndic = defaultdict(int)\nfor word in corpus:\n    if word in stop:\n        dic[word]+=1\n        \ntop = sorted(dic.items(),key=lambda x:x[1], reverse=True)[:10]\n\n\nx, y = zip(*top)\n# print(x,y)\nb = pd.DataFrame({\n    'value':x,\n    'count':y\n})\n\n# b.head()\nsns.barplot(x='value',y='count',data=b);\n\n# for class 1\ncorpus=create_corpus(1)\n\ndic=defaultdict(int)\nfor word in corpus:\n    if word in stop:\n        dic[word]+=1\n\ntop=sorted(dic.items(), key=lambda x:x[1],reverse=True)[:10] \n    \n\n\nx,y=zip(*top)\nc = pd.DataFrame({\n    'value':x,\n    'count':y\n})\n\n# b.head()\nsns.barplot(x='value',y='count',data=c)\n\"\"\"\n## Check for null values\n\"\"\"\n# for train\nsns.heatmap(train.isnull());\n\n# location and so many null values\n# for test\nsns.heatmap(test.isnull());\n\n# location and so many null values\n\"\"\"\n## Data(Text) Cleaning\n\"\"\"\nimport nltk \nfrom nltk.corpus import stopwords\nstop_words = stopwords.words('english')\n\"\"\"\n## Most Important Step (Text clearning)\n- Remove Urls\n- Remove Mentions\n- Remove Hastags\n- Remove HTML tags\n- Remove Punctuations\n- Remove Stop Words\n\"\"\"\ndef clean(text):\n\n    #     remove urls\n    text = re.sub(r'https?:\/\/\\S+|www\\.\\S+', \" \", text)\n\n    #     remove mentions\n    text = re.sub(r'@\\w+',' ',text)\n\n    #     remove hastags\n    text = re.sub(r'#\\w+', ' ', text)\n\n    #     remove digits\n    text = re.sub(r'\\d+', ' ', text)\n\n    #     remove html tags\n    text = re.sub('r<.*?>',' ', text)\n    \n    #remove puct\n    text = text.translate(str.maketrans(\"\",\"\",string.punctuation))\n    \n    #     remove stop words \n    text = text.split()\n    text = \" \".join([word for word in text if not word in stop_words])\n    \n      \n    return text\n\"\"\"\n## Removing Emojis\n\"\"\"\ndef remove_emoji(text):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    return emoji_pattern.sub(r'', text)\n\"\"\"\n### Apply text cleaning on datasets\n\"\"\"\ntrain['text'] = train['text'].apply(lambda x:clean(x))\ntrain['text'] = train['text'].apply(lambda x:remove_emoji(x))\n\ntest['text'] = test['text'].apply(lambda x:clean(x))\ntest['text'] = test['text'].apply(lambda x:remove_emoji(x))\ntrain.head()\n\"\"\"\n### By looking at the datset we can get a sense that we only need 2 cloumns (Text and target) \n- So taking only these columns\n\nand making copy\n\"\"\"\ndf_train = train.iloc[:,3:].copy()\ndf_test = test.iloc[:,3:].copy()\ndf_train.head()\ndf_test.head()\n\"\"\"\n### What is bert\n- BERT (Bidirectional Encoder Representations from Transformers) is a deep learning model developed by Google. It represented one of the major machine learning breakthroughs of the year, as it achieved state-of-the-art results across 11 different Natural Language Processing (NLP) tasks. Moreover, Google open-sourced the code and made pretrained models available for download similar to computer vision models pretrained on ImageNet. For these reasons, there continues to be a great deal of interest in BERT (even as other models slightly overtake it).\n\"\"\"\n\"\"\"\n- We will first use the \"texts_from_df\" function to load the data from the data frames\n- then pass train data set along with the text and target columns\n- BERT can handle a maximum length to 512, but we only use 400 to reduce memory and improve speed.\n- We need to process text a specific way for use with BERT. for that use preprocess_mode = 'bert'\n\n\"\"\"\n(X_train,y_train),(X_test,y_test),preprocess = text.texts_from_df(train_df=df_train, text_column='text',\n                  label_columns='target',\n                   val_df= df_test,\n                    maxlen=400,\n                   preprocess_mode='bert'\n                  )\n\"\"\"\n- for text classification we are usign BERT so need to pass name = 'bert'\n- passing our train_data \n- then pass preprocess\n\"\"\"\nmodel = text.text_classifier(name='bert',\n                            train_data = (X_train,y_train),\n                            preproc=preprocess)\n\"\"\"\n- train the model using train_data, val_data and batch_size\n\"\"\"\n# get learning rate\nlearner = ktrain.get_learner(model=model,\n                            train_data = (X_train,y_train),\n                             val_data=(X_test,y_test),\n                             batch_size = 6\n                            )\n\"\"\"\n- Finding the best learning rate for the model\n\n#### Note:- It will take a lot of time even on GPU (in my case it took more then 2 hour)\n\"\"\"\nlearner.lr_find(max_epochs=2)\nlearner.lr_plot()\nlearner.fit_onecycle(lr=2e-5,epochs=2)\nlearner\n\"\"\"\n- Now time for prediction\n\"\"\"\npredictor = ktrain.get_predictor(learner.model, preprocess)\ny_list = []\n\"\"\"\n- Because as predict it will going to predict either \n- target or not target so mapping these values with 1 and 0\n\"\"\"\nfor i in range(len(df_test['text'])):\n    text = df_test['text'][i]\n    y_pred =  predictor.predict(text)\n    if y_pred == 'target':\n        y_list.append(1)\n    else:\n        y_list.append(0)\nlen(y_list)\n\nsns.countplot(y_list)\n\"\"\"\n- Reading the submission file\n\"\"\"\nsample_sub=pd.read_csv('..\/input\/nlp-getting-started\/sample_submission.csv')\nsub=pd.DataFrame({'id':sample_sub['id'].values.tolist(),'target':y_pre})\nsub.to_csv('submission.csv',index=False)\nsub.head()\n\"\"\"\n# If you like the kernal please do a UpVote\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '982abba89072d0'}"}
{"id":"135174","text":"\"\"\"\n# Inroduction\n\nRMS Titanic was a British passenger liner, operated by the White Star Line, which sank in the North Atlantic Ocean on 15 April 1912 after striking an iceberg during her maiden voyage from Southampton, UK, to New York City. Of the estimated 2,224 passengers and crew aboard, more than 1,500 died, which made the sinking possibly one of the deadliest for a single ship up to that time.\n\n<font color = \"blue\">\n\nContent:\n   \n    \n1. [Load and Check Data](#1)\n1. [Variable Description](#2)\n    1. [Univariate Variable Analysis](#3)\n    1. [Categorical Variable Analysis](#4)\n    1. [Numerical Variable Analysis](#5)\n1. [Basic Data Analysis](#6)\n1. [Outlier Detection](#7)\n1. [Missing Value](#8)\n    1. [Find Missing Value](#9)\n    1. [Fill Missing Value](#10)\n1. [Visualization](#11)\n    1. [Correlation Between Sibsp -- Parch -- Age -- Fare -- Survived](#12)\n    1. [SibSp -- Survived](#13)\n    1. [Parch -- Survived](#14)\n    1. [Pclass -- Survived](#15)\n    1. [Age -- Survived](#16)\n    1. [Pclass -- Survived -- Age](#17)\n    1. [Embarked -- Sex -- Pclass -- Survived](#18)\n    1. [Embarked -- Sex -- Fare -- Survived](#19)\n    1. [Fill Missing: Age Feature](#20)\n1. [Feature Engineering](#21)\n    1. [Name -- Title](#22)\n    1. [Family Size](#23)\n    1. [Embarked](#24)\n    1. [Ticket](#25)\n    1. [Pclass](#26)\n    1. [Sex](#27)\n    1. [Drop Passenger ID and Cabin](#28)\n1. [Modeling](#29)\n    1. [Train - Test Split](#30)\n    1. [Simple Logistic Regression](#31)\n    1. [Hyperparameter Tuning -- Grid Search -- Cross Validation](#32)\n    1. [Ensemble Modeling](#33)\n    1. [Prediction and Submission](#34)\n        \n\n\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\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\n\"\"\"\n<a id=\"1\"><\/a>\n## Load and Check Data\n\"\"\"\ntrain_df = pd.read_csv(\"\/kaggle\/input\/titanic-machine-learning-from-disaster\/train.csv\")\ntest_df = pd.read_csv(\"\/kaggle\/input\/titanic-machine-learning-from-disaster\/test.csv\")\ntest_PassengerId  = test_df[\"PassengerId\"]\ntrain_df.head()\n\"\"\"\n<a id=\"2\"><\/a>\n## Variable Description\n\n![image.png](attachment:e18ad50c-94b7-413b-b21e-4799a0f00881.png)\n\n![image.png](attachment:637460f4-2334-4986-9d3f-ff6dedfdb5b3.png)\n\"\"\"\ntrain_df.info()\n\"\"\"\n<a id=\"1\"><\/a>\n\n\"\"\"\n\"\"\"\n<a id=\"3\"><\/a>\n\n## Univariate Variable Analysis\n\nCategorical Variable Analysis :  Survived, Sex, Pclass, Embarked, Cabin, Name, Ticket, Sibsp and Parch\n\nNumerical Variable Analysis :   Fare, Age and PassengerId\n\"\"\"\n\"\"\"\n<a id=\"4\"><\/a>\n### Categorical Variable Analysis\n\n\"\"\"\ndef bar_plot(variable): \n\n    ### input: variable ex: \"Sex\"\n    ### output: barplot & value count \n\n    \n    # get feature\n    var = train_df[variable]\n    \n    # count number of categorical variable\n    varValue = var.value_counts()\n    \n    # visualize\n    plt.figure(figsize = (9,3))\n    plt.bar(varValue.index, varValue)\n    plt.xticks(varValue.index, varValue.index.values)\n    plt.ylabel(\"Frequency\")\n    plt.title(variable)\n    plt.show()\n    print(\"{}: \\n  {}\".format(variable,varValue))\ntrain_df.columns\ncategory1 = ['Survived', 'Pclass', 'Sex', 'SibSp','Parch','Embarked']\nfor c in category1:\n    bar_plot(c)\n    \n    ## **Conclusion**\n    # 'Survived';  inbalance variable\n    # 'Pclass';    related Embarked\n    # 'Sex';       inbalance variable\n    # 'SibSp';\n    # 'Parch';\n    # 'Embarked';  related Pclass\ncategory2 = [\"Cabin\",\"Name\",\"Ticket\"]\nfor c in category2:\n    print(\"{} \\n\".format(train_df[c].value_counts()))\n\"\"\"\n<a id=\"5\"><\/a>\n### Numerical Variable Analysis\n\"\"\"\ndef plot_hist(variable):\n    plt.figure(figsize = (9,3))\n    plt.hist(train_df[variable], bins = 50)\n    plt.xlabel(variable)\n    plt.ylabel(\"Frequency\")\n    plt.title(\"{} distribution with hist\".format(variable))\n    plt.show()\nnumericVar = [\"Fare\",\"Age\",\"PassengerId\"]\nfor n in numericVar:\n    plot_hist(n)\n    \n    ## **Conclusion**\n    # \"Fare\" ;         \n    # \"Age\" ;         \n    # \"PassengerId\" ;  rubbish\n\n\"\"\"\n<a id=\"6\"><\/a>\n## Basic Data Analysis\n\n* Pclass - Survived\n* Sex - Survived\n* SibSp - Survived\n* Parch - Survived\n\"\"\"\ntrain_df[[\"Pclass\" , \"Survived\"]]\n# Pclass - Survived\ntrain_df[[\"Pclass\" , \"Survived\"]].groupby([\"Pclass\"], as_index = False).mean().sort_values(by=\"Survived\", ascending = False)\n# Sex - Survived\ntrain_df[[\"Sex\" , \"Survived\"]].groupby([\"Sex\"], as_index = False).mean().sort_values(by=\"Survived\", ascending = False)\n# SibSp - Survived\ntrain_df[[\"SibSp\" , \"Survived\"]].groupby([\"SibSp\"], as_index = False).mean().sort_values(by=\"Survived\", ascending = False)\n# SibSp - Survived\ntrain_df[[\"Parch\" , \"Survived\"]].groupby([\"Parch\"], as_index = False).mean().sort_values(by=\"Survived\", ascending = False)\n\"\"\"\n<a id=\"7\"><\/a>\n## Outlier Detection\n\"\"\"\n# Exp 1\n# Check list\na = [\"a\",\"a\",\"b\",\"a\",\"c\",\"a\",\"b\"]\nCounter(a)\n\ndef detect_outliers(df,features):\n    outlier_indices= []\n    \n    for c in features:\n        # 1st quartile\n        Q1 = np.percentile(df[c],25)\n        \n        # 3rd quartile\n        Q3 = np.percentile(df[c],75)\n\n        # IQR\n        IQR = Q3 - Q1\n        \n        # Outlier step\n        outlier_step = IQR * 1.5\n        \n        # Detect outlier and their indeces\n        outlier_list_col = df[(df[c] < Q1- outlier_step) | (df[c] >  Q3 + outlier_step)].index\n                               \n        # Store indeces\n        outlier_indices.extend(outlier_list_col)\n                               \n    outlier_indices = Counter(outlier_indices)\n    multiple_outliers = list(i for i, v in outlier_indices.items() if v > 2) # look for Exp1; i = a,b... v = count\n                                                            \n    return multiple_outliers    \ntrain_df.iloc[detect_outliers(train_df,[\"Age\",\"SibSp\",\"Parch\",\"Fare\"])]\n# Drop ouyliers\ntrain_df = train_df.drop(detect_outliers(train_df,[\"Age\",\"SibSp\",\"Parch\",\"Fare\"]), axis = 0).reset_index(drop = True)\n\n\"\"\"\n<a id=\"8\"><\/a>\n## Missing Value\n* Find Missing Value\n* Fill Missing Value\n\"\"\"\ntrain_df_len = len(train_df)\ntrain_df = pd.concat([train_df,test_df],axis = 0).reset_index(drop = True)\ntrain_df.head()\n\"\"\"\n<a id=\"9\"><\/a>\n### Find Missing Value\n\"\"\"\ntrain_df.columns[train_df.isnull().any()]\ntrain_df.isnull().sum()\n\"\"\"\n<a id=\"10\"><\/a>\n### Fill Missing Value\n* Embarked has 2,\n* Fare has only 1,\n* Age has 256,\n* Cabin has 1007  missing value\n\"\"\"\ntrain_df[train_df[\"Embarked\"].isnull()]\ntrain_df.boxplot(column = \"Fare\", by=\"Embarked\")\nplt.show()\n# \ntrain_df[\"Embarked\"] = train_df[\"Embarked\"].fillna(\"C\")\ntrain_df[train_df[\"Embarked\"].isnull()]\ntrain_df[train_df[\"Fare\"].isnull()]\ntrain_df[train_df[\"Pclass\"] == 3]\nnp.mean(train_df[train_df[\"Pclass\"] == 3][\"Fare\"])\ntrain_df[\"Fare\"] = train_df[\"Fare\"].fillna(np.mean(train_df[train_df[\"Pclass\"] == 3][\"Fare\"]))\ntrain_df[train_df[\"Fare\"].isnull()]\n\"\"\"\n<a id=\"11\"><\/a>\n## Visualization\n\"\"\"\n\"\"\"\n<a id=\"12\"><\/a>\n### Correlation Between Sibsp -- Parch -- Age -- Fare -- Survived\n\"\"\"\nlist1 = [\"SibSp\" , \"Parch\" , \"Age\" , \"Fare\" , \"Survived\"]\nsns.heatmap(train_df[list1].corr(),annot = True, fmt = \".2f\")\n\"\"\"\n<a id=\"13\"><\/a>\n### SibSp -- Survived\n\"\"\"\ng = sns.factorplot(x = \"SibSp\" , y = \"Survived\", data = train_df, kind = \"bar\", size = 6 )\ng.set_ylabels(\"Survived Probability\")\nplt.show()\n\n\"\"\"\n* Having a lot of SibSp have less chance to survive.\n* if sibsp == 0 or 1 or 2, passenger has more chance to survive\n* we can consider a new feature describing these categories.\n\"\"\"\n\"\"\"\n<a id=\"14\"><\/a>\n### Parch -- Survived\n\"\"\"\ng = sns.factorplot(x = \"Parch\", y = \"Survived\", data = train_df, kind = \"bar\", size = 6)\ng.set_ylabels(\"Survived Probability\")\nplt.show()\n\n\"\"\"\n* Sibsp and parch can be used for new feature extraction with th = 3\n* small familes have more chance to survive.\n* there is a std in survival of passenger with parch = 3\n\"\"\"\n\"\"\"\n<a id=\"15\"><\/a>\n### Pclass -- Survived\n\"\"\"\ng = sns.factorplot(x = \"Pclass\", y = \"Survived\", data = train_df, kind = \"bar\", size = 6)\ng.set_ylabels(\"Survived Probability\")\nplt.show()\n\"\"\"\n* It's a clear feature for train our model.\n\"\"\"\n\"\"\"\n<a id=\"16\"><\/a>\n### Age -- Survived\n\"\"\"\ng = sns.FacetGrid(train_df, col = \"Survived\")\ng.map(sns.distplot, \"Age\", bins = 25)\nplt.show()\n\"\"\"\n* age <= 10 has a high survival rate,\n* oldest passengers (80) survived,\n* large number of 20 years old did not survive,\n* most passengers are in 15-35 age range,\n* use age feature in training\n* use age distribution for missing value of age\n\"\"\"\n\"\"\"\n<a id=\"17\"><\/a>\n### Pclass -- Survived -- Age\n\"\"\"\ng = sns.FacetGrid(train_df, col = \"Survived\", row = \"Pclass\", size = 3)\ng.map(plt.hist, \"Age\", bins = 25)\ng.add_legend()\nplt.show()\n\"\"\"\n* pclass is important feature for model training.\n\n\"\"\"\n\"\"\"\n<a id=\"18\"><\/a>\n### Embarked -- Sex -- Pclass -- Survived\n\"\"\"\ng = sns.FacetGrid(train_df, row= \"Embarked\", size = 3)\ng.map(sns.pointplot,  \"Pclass\" , \"Survived\" , \"Sex\")\ng.add_legend()\nplt.show()\n\"\"\"\n* Female passengers have much better survival rate than males.\n* males have better surv\u015fval rate in pclass 3 in C.\n* embarked and sex will be used in training.\n\"\"\"\n\"\"\"\n<a id=\"19\"><\/a>\n### Embarked -- Sex -- Fare -- Survived\n\"\"\"\ng = sns.FacetGrid(train_df, row = \"Embarked\", col = \"Survived\", size = 3)\ng.map(sns.barplot, \"Sex\", \"Fare\")\ng.add_legend()\nplt.show()\n\"\"\"\n* Passsengers who pay higher fare have better survival. Fare can be used as categorical for training.\n\n\"\"\"\n\"\"\"\n<a id=\"20\"><\/a>\n### Fill Missing: Age Feature\n\"\"\"\ntrain_df[train_df[\"Age\"].isnull()]\nsns.factorplot(x = \"Sex\", y = \"Age\", data = train_df, kind=\"box\")\nplt.show()\n\"\"\"\n* Sex is not informative for age prediction, age distribution seems to be same.\n\n\n\"\"\"\nsns.factorplot(x = \"Sex\", y = \"Age\", data = train_df, kind = \"box\", hue = \"Pclass\")\nplt.show()\n\"\"\"\n* 1st class passengers are older than 2nd, and 2nd is older than 3rd class.\n\n\n\"\"\"\nsns.factorplot(x = \"Parch\", y = \"Age\", data = train_df, kind = \"box\")\nsns.factorplot(x = \"SibSp\", y = \"Age\", data = train_df, kind = \"box\")\n\nplt.show()\ntrain_df[\"Sex_N\"] = [1 if i == \"male\" else 0  for i in train_df[\"Sex\"]]\nsns.heatmap(train_df[[\"Age\",\"Sex_N\",\"SibSp\",\"Parch\",\"Pclass\"]].corr(), annot = True)\nplt.show()\n\"\"\"\n* Age is not correlated with sex but it is correlated with parch, sibsp and pclass.\n\n\n\"\"\"\ntrain_df[train_df[\"Age\"].isnull()]\ntrain_df[\"Age\"][train_df[\"Age\"].isnull()]\ntrain_df.head()\nindex_nan_age = list(train_df[\"Age\"][train_df[\"Age\"].isnull()].index)\nfor i in index_nan_age:\n    age_pred = train_df[\"Age\"][((train_df[\"SibSp\"] == train_df.iloc[i][\"SibSp\"])\n                               &\n                               (train_df[\"Parch\"] == train_df.iloc[i][\"Parch\"])\n                               &\n                               (train_df[\"Pclass\"] == train_df.iloc[i][\"Pclass\"])                    \n                               )].median()\n    age_med = train_df[\"Age\"].median()\n    \n    if not np.isnan(age_pred):\n        train_df[\"Age\"].iloc[i] = age_pred\n    else:\n        train_df[\"Age\"].iloc[i] = age_med\ntrain_df[train_df[\"Age\"].isnull()]\n\"\"\"\n<a id=\"21\"><\/a>\n# Feature Engineering\n\n* Name -- Title\n* Family Size\n* Embarked\n* Ticket\n* Pclass\n* Sex\n* Drop Passenger ID and Cabin\n\"\"\"\n\"\"\"\n<a id=\"22\"><\/a>\n## Name -- Title\n\"\"\"\ntrain_df[\"Name\"].head()\ns = \"Futrelle, Mrs. Jacques Heath (Lily May Peel)\"\ns.split(\".\")[0].split(\",\")[1].strip()\nname = train_df[\"Name\"]\ntrain_df[\"Title\"] = [i.split(\".\")[0].split(\",\")[-1].strip() for i in name]\ntrain_df[\"Title\"].head(10)\nsns.countplot(x = \"Title\", data = train_df)\nplt.xticks(rotation = 60)\nplt.show()\ntrain_df[\"Title\"].unique()\n# convert to categuniquel\ntrain_df[\"Title_N\"] = train_df[\"Title\"].replace(['Don', 'Rev', 'Dr',\n       'Major', 'Lady', 'Sir', 'Col', 'Capt', 'the Countess',\n       'Jonkheer', 'Dona'],\"Other\")\n\ntrain_df[\"Title_N\"] = [0 if i == \"Master\" else 1 if i == \"Miss\" or i == \"Ms\" or i == \"Mlle\" or i == \"Mrs\" else 2 if i == \"Mr\" else 3 for i in train_df[\"Title\"]]\ntrain_df[\"Title_N\"].head(20)\nsns.countplot(x = \"Title_N\", data = train_df)\nplt.xticks(rotation = 60)\nplt.show()\ng = sns.factorplot(x = \"Title_N\", y = \"Survived\", data = train_df, kind = \"bar\")\ng.set_xticklabels([\"Master\",\"Mrs\",\"Mr\",\"Other\"])\ng.set_ylabels(\"Survival Probability\")\nplt.show()\ntrain_df.drop(labels = [\"Name\"], axis = 1, inplace = True)\ntrain_df.head()\ntrain_df = pd.get_dummies(train_df,columns = [\"Title_N\"])\ntrain_df.head()\n\"\"\"\n<a id=\"23\"><\/a>\n## Family Size\n\"\"\"\ntrain_df[\"Fsize\"] = train_df[\"SibSp\"] + train_df[\"Parch\"] + 1\ntrain_df.head()\ng = sns.factorplot(x = \"Fsize\", y = \"Survived\", data = train_df, kind = \"bar\")\ng.set_ylabels(\"Survival\")\nplt.show()\ntrain_df[\"Family_Scategory\"] = [    0 if i > 4.5\n                               else 2 if i < 2\n                               else 1 \n                           \n                               for i in train_df[\"Fsize\"]]\ntrain_df.head(10)\n## train_df[\"Family_size\"] = [1 if i < 5 else 0 for i in train_df[\"Fsize\"]] (model upgraded )\nsns.countplot(x = \"Family_Scategory\", data = train_df )\nplt.show()\ng = sns.factorplot(x = \"Family_Scategory\", y = \"Survived\", data = train_df, kind = \"bar\")\ng.set_xticklabels([\"LargeFamily\",\"SmallFamily\",\"AloneCowBoy\"])\ng.set_ylabels(\"Survival Probability\")\nplt.show()\n\"\"\"\n* Small familes have more chance to survive than large families.\n* Also AloneCowBoy have more chance to survive than large families.\n\"\"\"\ntrain_df = pd.get_dummies(train_df, columns = [\"Family_Scategory\"] )\ntrain_df.head()\n\"\"\"\n<a id=\"24\"><\/a>\n## Embarked\n\"\"\"\ntrain_df[\"Embarked\"].head()\nsns.countplot(x = \"Embarked\",data = train_df)\nplt.show()\ntrain_df = pd.get_dummies(train_df, columns=[\"Embarked\"])\ntrain_df.head()\n\"\"\"\n<a id=\"25\"><\/a>\n## Ticket\n\"\"\"\ntrain_df[\"Ticket\"].head(20)\na = \" A\/5. 2151  \"\na.replace(\".\",\"\")\na = \" A\/5. 2151  \"\na.replace(\".\",\"\").replace(\"\/\",\"\")\na = \" A\/5. 2151  \"\na.replace(\".\",\"\").replace(\"\/\",\"\").strip()\na = \" A\/5. 2151  \"\na.replace(\".\",\"\").replace(\"\/\",\"\").strip().split(\" \")\na = \" A\/5. 2151  \"\na.replace(\".\",\"\").replace(\"\/\",\"\").strip().split(\" \")[0]\ntickets = []\nfor i in list(train_df[\"Ticket\"]):\n    if not i.isdigit():\n            tickets.append(i.replace(\".\",\"\").replace(\"\/\",\"\").strip().split(\" \")[0])\n    else:\n            tickets.append(\"x\")\ntrain_df[\"Ticket_N\"] = tickets\ntrain_df[\"Ticket_N\"].head(20)\ntrain_df.head()\ntrain_df = pd.get_dummies(train_df, columns = [\"Ticket_N\"], prefix = \"T\")\ntrain_df.head()\n\"\"\"\n<a id=\"26\"><\/a>\n## Pclass\n\"\"\"\ntrain_df[\"Pclass\"] = train_df[\"Pclass\"].astype(\"category\")\ntrain_df = pd.get_dummies(train_df, columns = [\"Pclass\"])\ntrain_df.head()\n\"\"\"\n<a id=\"27\"><\/a>\n## Sex\n\"\"\"\ntrain_df[\"Sex\"] = train_df[\"Sex\"].astype(\"category\")\ntrain_df = pd.get_dummies(train_df, columns = [\"Sex\"])\ntrain_df.head()\n\"\"\"\n<a id=\"28\"><\/a>\n## Drop Passenger ID and Cabin\n\"\"\"\ntrain_df.columns\ntrain_df.head()\ntrain_df.drop(labels = ['PassengerId', 'Cabin', 'Title', 'Fsize', 'Parch', 'SibSp', \"Ticket\", \"Sex_N\" ] , axis = 1, inplace = True)\n\"\"\"\n<a id=\"29\"><\/a>\n# Modeling\n\"\"\"\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier,VotingClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\n\"\"\"\n<a id=\"30\"><\/a>\n## Train - Test Split\n\"\"\"\ntrain_df_len\ntest = train_df[train_df_len:]\ntest.drop(labels = [\"Survived\"], axis = 1, inplace = True)\ntest.head()\ntrain = train_df[:train_df_len]\nX_train = train.drop(labels = \"Survived\", axis = 1)\ny_train = train[\"Survived\"]\nX_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size = 0.33, random_state = 42)\n\nprint(\"X_train\",len(X_train))\nprint(\"X_test\",len(X_test))\nprint(\"y_train\",len(y_train))\nprint(\"y_test\",len(y_test))\nprint(\"test\",len(test))\ntest.info()\n\"\"\"\n<a id=\"31\"><\/a>\n## Simple Logistic Regression\n\"\"\"\nlogreg = LogisticRegression(solver='liblinear')\nlogreg.fit(X_train,y_train)\nacc_log_train = round(logreg.score(X_train,y_train)*100,2)\nacc_log_test = round(logreg.score(X_test,y_test)*100,2)\nprint(\"Training Accuracy: % {}\".format(acc_log_train))\nprint(\"Testing Accuracy: % {}\".format(acc_log_test))\n## https:\/\/www.udemy.com\/course\/machine-learning-ve-python-adan-zye-makine-ogrenmesi-4\/learn\/lecture\/17902832#questions\n\"\"\"\n<a id=\"32\"><\/a>\n## Hyperparameter Tuning -- Grid Search -- Cross Validation\n\nWe will compare 5 ml classifier and evaluate mean accuracy of each of them by stratified cross validation.\n\n* Decision Tree\n* SVM\n* Random Forest\n* KNN\n* Logistic Regression\n\"\"\"\nrandom_state = 42\nclassifier = [DecisionTreeClassifier(random_state = random_state),\n             SVC(random_state = random_state),\n             RandomForestClassifier(random_state = random_state),\n             LogisticRegression(random_state = random_state),\n             KNeighborsClassifier()]\n\ndt_param_grid = {\"min_samples_split\" : range(10,500,20),\n                \"max_depth\": range(1,20,2)}\n\nsvc_param_grid = {\"kernel\" : [\"rbf\"],\n                 \"gamma\": [0.001, 0.01, 0.1, 1],\n                 \"C\": [1,10,50,100,200,300,1000]}\n\nrf_param_grid = {\"max_features\": [1,3,10],\n                \"min_samples_split\":[2,3,10],\n                \"min_samples_leaf\":[1,3,10],\n                \"bootstrap\":[False],\n                \"n_estimators\":[100,300],\n                \"criterion\":[\"gini\"]}\n\nlogreg_param_grid = {\"C\":np.logspace(-3,3,7),\n                    \"penalty\": [\"l1\",\"l2\"]}\n\nknn_param_grid = {\"n_neighbors\": np.linspace(1,19,10, dtype = int).tolist(),\n                 \"weights\": [\"uniform\",\"distance\"],\n                 \"metric\":[\"euclidean\",\"manhattan\"]}\nclassifier_param = [dt_param_grid,\n                   svc_param_grid,\n                   rf_param_grid,\n                   logreg_param_grid,\n                   knn_param_grid]\ncv_result = []\nbest_estimators = []\nfor i in range(len(classifier)):\n    clf = GridSearchCV(classifier[i], param_grid=classifier_param[i], cv = StratifiedKFold(n_splits = 10), scoring = \"accuracy\", n_jobs = -1,verbose = 1)\n    clf.fit(X_train,y_train)\n    cv_result.append(clf.best_score_)\n    best_estimators.append(clf.best_estimator_)\n    print(cv_result[i])\ncv_results = pd.DataFrame({\"Cross Validation Means\":cv_result, \"ML Models\":[\"DecisionTreeClassifier\", \"SVM\",\"RandomForestClassifier\",\n             \"LogisticRegression\",\n             \"KNeighborsClassifier\"]})\n\ng = sns.barplot(\"Cross Validation Means\", \"ML Models\", data = cv_results)\ng.set_xlabel(\"Mean Accuracy\")\ng.set_title(\"Cross Validation Scores\")\nplt.show()\nbest_estimators\n\"\"\"\n<a id=\"33\"><\/a>\n## Ensemble Modeling\n\"\"\"\nvotingC = VotingClassifier(estimators = [(\"DecisionTreeClassifier\",best_estimators[0]),\n                                        (\"SVC\",best_estimators[1]),\n                                        (\"RandomForestClassifier\",best_estimators[2])],\n                                        voting = \"hard\", n_jobs = -1)\nvotingC = votingC.fit(X_train, y_train)\nprint(accuracy_score(votingC.predict(X_test),y_test))\n\"\"\"\n<a id=\"34\"><\/a>\n## Prediction and Submission\n\"\"\"\ntest_survived = pd.Series(votingC.predict(test), name = \"Survived\").astype(int)\nresults = pd.concat([test_PassengerId, test_survived],axis = 1)\nresults.to_csv(\"titanic.csv\", index = False)","meta":"{'source': 'AI4Code', 'id': 'f880bc52a3af0f'}"}
{"id":"32002","text":"#https:\/\/www.analyticsvidhya.com\/blog\/2018\/02\/the-different-methods-deal-text-data-predictive-python\/\n# 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)\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport pickle\nfrom multiprocessing import Pool\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\n#libraries to import ! you should read about every one og them ! \n\nimport pandas as pd\nimport numpy as np\nimport re\nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom textblob import TextBlob\nfrom sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn import decomposition, ensemble\n\nimport pandas, xgboost, numpy, textblob, string\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix, accuracy_score, mean_squared_error, r2_score, roc_auc_score, roc_curve, classification_report\nfrom sklearn.model_selection import train_test_split\n\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\ntrain_data = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/train.tsv\/train.tsv', sep=\"\\t\")\ntest_data = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/test.tsv\/test.tsv', sep=\"\\t\")\nsub = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/sampleSubmission.csv', sep=\",\")\ntrain = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/train.tsv\/train.tsv', sep=\"\\t\")\ntest = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/test.tsv\/test.tsv', sep=\"\\t\")\nsub = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/sampleSubmission.csv', sep=\",\")\ntrain_data.rename(columns={'Phrase':'text' , 'Sentiment':'target'}, inplace=True)\ntest_data.rename(columns={'Phrase':'text'}, inplace=True)\ntrain_data['text'][1]\n\"\"\"\nThe regular expression above is meant to find any four digits at the beginning of a string, which suffices for our case. The above is a raw string (meaning that a backslash is no longer an escape character), which is standard practice with regular expressions.\nregex = r'^(\\d{4})'\n\n\"\"\"\nimport re\ndef  clean_text(df, text_field, new_text_field_name):\n    df[new_text_field_name] = df[text_field].str.lower() #lowercase\n    df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\\/\\\/\\S+)|^rt|http.+?\", \"\", elem))  \n    # remove numbers\n    #remove.............. (#re sub \/ search\/ ..)\n    df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"\\d+\", \"\", elem))\n    \n    return df\n#read about dataframes ! TABLEAU !! \n#data_clean : new dataframe\ndata_clean = clean_text(train_data, 'text', 'text_clean')\ndata_clean_test = clean_text(test_data,'text', 'text_clean')\ndata_clean.head()\nimport nltk.corpus\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nstop = stopwords.words('english')\nstop #the list of the stopwords ! \ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))\ndata_clean.head()\n#Tokenization : word_tokenize ! \nimport nltk \nnltk.download('punkt')\nfrom nltk.tokenize import sent_tokenize, word_tokenize\ndata_clean['text_tokens'] = data_clean['text_clean'].apply(lambda x: word_tokenize(x))\ndata_clean.head()\n#stemming #PorterStemmer \nfrom nltk.stem import PorterStemmer \nfrom nltk.tokenize import word_tokenize\ndef word_stemmer(text):\n    stem_text = [PorterStemmer().stem(i) for i in text]\n    return stem_text\ndata_clean['text_clean_tokens'] = data_clean['text_tokens'].apply(lambda x: word_stemmer(x))\ndata_clean.head()\nnltk.download('wordnet')\nfrom nltk.stem import WordNetLemmatizer\ndef word_lemmatizer(text):\n    lem_text = [WordNetLemmatizer().lemmatize(i) for i in text]\n    return lem_text\ndata_clean['text_clean_tokens'] = data_clean['text_tokens'].apply(lambda x: word_lemmatizer(x))\ndata_clean.head()\ndef remove_URL(text):\n    url = re.compile(r'https?:\/\/\\S+|www\\.\\S+')\n    return url.sub(r'',text)\n\n\n\ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: remove_URL(x))\ndef remove_html(text):\n    html=re.compile(r'<.*?>')\n    return html.sub(r'',text)\n\ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: remove_html(x))\n# Reference : https:\/\/gist.github.com\/slowkow\/7a7f61f495e3dbb7e3d767f97bd7304b\ndef remove_emoji(text):\n    emoji_pattern = re.compile(\"[\"\n                           u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                           u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                           u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                           u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                           u\"\\U00002702-\\U000027B0\"\n                           u\"\\U000024C2-\\U0001F251\"\n                           \"]+\", flags=re.UNICODE)\n    return emoji_pattern.sub(r'', text)\n\ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: remove_emoji(x))\nimport string\ndef remove_punct(text):\n    table=str.maketrans('','',string.punctuation)\n    return text.translate(table)\n\ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: remove_punct(x))\nfreq = pd.Series(' '.join(data_clean['text_clean']).split()).value_counts()[:10]\n\nfreq = list(freq.index)\ndata_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: \" \".join(x for x in x.split() if x not in freq))\nX_train, X_test, Y_train, Y_test = train_test_split(data_clean['text_clean'], \n                   \n                                                    data_clean['target'], \n                                                    test_size = 0.2,\n                                                    random_state = 10)\n\n#HYPERPARAMETERS ! \n#SPLITTING THE DATA ! \n\ntfidf = TfidfVectorizer(encoding='utf-8',\n                       ngram_range=(1,3),\n                       max_df=1.0,\n                       min_df=10,\n                       max_features=500,\n                       norm='l2',\n                       sublinear_tf=True)\ntrain_features = tfidf.fit_transform(X_train).toarray()\nprint(train_features.shape)\ntest_features = tfidf.transform(X_test).toarray()\nprint(test_features.shape)\ntrain_labels = Y_train\ntest_labels = Y_test\n\nimport pandas as pd\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nmnb_classifier = MultinomialNB()\nmnb_classifier.fit(train_features, train_labels)\nmnb_prediction = mnb_classifier.predict(test_features)\ntraining_accuracy = accuracy_score(train_labels, mnb_classifier.predict(train_features))\nprint(training_accuracy)\ntesting_accuracy = accuracy_score(test_labels, mnb_prediction)\nprint(testing_accuracy)\nprint(classification_report(test_labels, mnb_prediction))\nconf_matrix = confusion_matrix(test_labels, mnb_prediction)\nprint(conf_matrix)\n\"\"\"\n***Logistic Regression*****\n\"\"\"\nloj = linear_model.LogisticRegression()\nloj_model = loj.fit(train_features, train_labels)\ny_pred = loj_model.predict(test_features)\n\n\naccuracy_score(test_labels,y_pred)\n\"\"\"\n**Testing** \n\"\"\"\ntest_vectorizer =tfidf.transform( data_clean_test['text_clean']).toarray()\ntest_vectorizer.shape\nfinal_predictions = mnb_classifier.predict(test_vectorizer)\nfinal_predictions\nsubmission_df = pd.DataFrame()\nsubmission_df['PhraseId'] = data_clean_test['PhraseId']\nsubmission_df['target'] = final_predictions\nsubmission_df\nsubmission_df['target'].value_counts()\nsubmission = submission_df.to_csv('Result.csv',index = False)\n\"\"\"\ncnn \n**What are Convolutional Neural Networks and why are they important?**\n\nConvolutional Neural Networks (ConvNets or CNNs) are a category of Neural Networks that have proven very effective in areas such as image recognition and classification. ConvNets have been successful in identifying faces, objects and traffic signs apart from powering vision in robots and self driving cars.\n\nThere are four main operations in the ConvNet :\n\n1- Convolution : The Convolution Step\nConvNets derive their name from the \u201cconvolution\u201d operator. The primary purpose of Convolution in case of a ConvNet is to extract features from the input image. Convolution preserves the spatial relationship between pixels by learning image features using small squares of input data.\nNote : in practice a CNN learnes the values of these filtres on its own during the training process (although we still need to specify parameters such as nbr of filtres,filter size, architecture of the network etc.. before the training process) \nthe more number of filtres we have , the more features get extractedand the better our network becomes at recognizinf pattaerns in unseen cases. \n\nthe size of the feature Map (convolved feature) is controlled by 3 parameters : depth,stride,zero-padding. \n\n\nKeywords : Filter ** Kernel ** feature detector ** stride ** matrices ** dot product **  Feature Map ** \n\n2- Non Linearity (ReLU) : RELU stands for rectified Linear unit and is a non linear operation.  output = MAx(zero, input).\nrelu is applied per pixel and replaces all negative pixel values in the feature map by zero. \nthe purpos of relu is to introduce non linearity in our convnet. \n\ninput feature map ( black = negative , white = positive values ) ===RELU=== rectified feature Map ( only non-negative values) \n[there are other non linear functions such as tanh or sigmoid can also be used instead of relu) but relu has been found to perform better in most situations. \n] \n3- Pooling or Sub Sampling : spatial pooling reduces the dimentionality of each feature map but retains the most important information. \nspatial pooling can be of different types : Max, average,sum,etc..\n\nthe function of pooling is to progressively reduce the spatial size of the input representation. in particular pooling : 1- makes the input representations smaller and more manageable. 2- reduces the nbr of p\u00e2rameters and computations in the network, therefore controlling overfitting. 3- makes the network invariant to small transformations and distortions.\n\n\n4- Classification (Fully Connected Layer) : The Fully Connected layer is a traditional Multi Layer Perceptron that uses a softmax activation function in the output layer (other classifiers like SVM can also be used, but will stick to softmax in this post). The term \u201cFully Connected\u201d implies that every neuron in the previous layer is connected to every neuron on the next layer\n\nThe output from the convolutional and pooling layers represent high-level features of the input image. The purpose of the Fully Connected layer is to use these features for classifying the input image into various classes based on the training dataset.\n\nThese operations are the basic building blocks of every Convolutional Neural Network, so understanding how these work is an important step to developing a sound understanding of ConvNets. \n\n\n\"\"\"\nseed = 0\n\nimport random\nimport numpy as np\nimport tensorflow as tf\ntf.random.set_seed(seed) \nimport pandas as pd\n\ntrain = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/train.tsv\/train.tsv',  sep=\"\\t\")\ntest = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/test.tsv\/test.tsv',  sep=\"\\t\")\ntrain.head()\ntrain['Sentiment'].value_counts()\ndef format_data(train, test, max_features, maxlen):\n    \"\"\"\n    Convert data to proper format.\n    1) Shuffle\n    2) Lowercase\n    3) Sentiments to Categorical\n    4) Tokenize and Fit\n    5) Convert to sequence (format accepted by the network)\n    6) Pad\n    7) Voila!\n    \"\"\"\n    from keras.preprocessing.text import Tokenizer\n    from keras.preprocessing.sequence import pad_sequences\n    from keras.utils import to_categorical\n    \n    train = train.sample(frac=1).reset_index(drop=True)\n    train['Phrase'] = train['Phrase'].apply(lambda x: x.lower())\n    test['Phrase'] = test['Phrase'].apply(lambda x: x.lower())\n\n    X = train['Phrase']\n    test_X = test['Phrase']\n    Y = to_categorical(train['Sentiment'].values)\n\n    tokenizer = Tokenizer(num_words=max_features)\n    tokenizer.fit_on_texts(list(X))\n\n    X = tokenizer.texts_to_sequences(X)\n    X = pad_sequences(X, maxlen=maxlen)\n    test_X = tokenizer.texts_to_sequences(test_X)\n    test_X = pad_sequences(test_X, maxlen=maxlen)\n\n    return X, Y, test_X\n\nmaxlen = 125\nmax_features = 15000\n\nX, Y, test_X = format_data(train, test, max_features, maxlen)\nX\nY\ntest_X\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.25, random_state=seed)\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Conv1D, GRU, BatchNormalization\nfrom tensorflow.keras.layers import Bidirectional, GlobalMaxPool1D, MaxPooling1D, Add, Flatten\nfrom tensorflow.keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, concatenate, SpatialDropout1D\nfrom keras.models import Model, load_model\nfrom keras import initializers, regularizers, constraints, optimizers, layers, callbacks\nfrom keras import backend as K\nfrom keras.engine import InputSpec, Layer\nfrom keras.optimizers import Adam\nfrom tensorflow.keras import Sequential\n\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, Callback, EarlyStopping\n\n\nmodel = Sequential()\n\n# Input \/ Embdedding\nmodel.add(Embedding(max_features, 150, input_length=maxlen))\n\n# CNN\nmodel.add(SpatialDropout1D(0.2))\n\nmodel.add(Conv1D(32, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPooling1D(pool_size=2))\n\nmodel.add(Conv1D(64, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPooling1D(pool_size=2))\n\nmodel.add(Flatten())\n\n# Output layer\nmodel.add(Dense(5, activation='sigmoid'))\nepochs = 5\nbatch_size = 32\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(X_train, Y_train, validation_data=(X_val, Y_val), epochs=epochs, batch_size=batch_size, verbose=1)\nsub = pd.read_csv('..\/input\/moviereviewsentimentanalysiskernelsonly\/sampleSubmission.csv')\n\nsub['Sentiment'] = model.predict_classes(test_X, batch_size=batch_size, verbose=1)\nsub.to_csv('sub_cnn.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '3ae7a615314c1b'}"}
{"id":"52049","text":"\"\"\"\n# How Many Bikes City Needs?\n### Predict Demand and User Behaviour at a Bike Sharing Service\n\nData set contains description of **bike rides in Chicago** for a period from April 2020 till April 2021 - a total of **3,826,978 samples** and **713 bike stations**. Each sample contains start and end station name, ID, latitude, longitude, time, bike type and user category. User ID is not available.\n\nWith the available data we can solve several tasks:\n- **Predict total number of bikes rented at each bike station daily.** Input features include location, temporal features, categorical features defining station type and demand in previous periods.\n- **Predict ride duration and end point coordinates for each individual ride.** Input features include location, temporal features, categorical features defining bike type, user type and station type.\n\n**Models:**\n- XGBoost regression model\n- TensorFlow neural networks\n\"\"\"\nimport os\nimport gc\nimport random\nimport json\nimport glob\n\nimport numpy as np\nimport pandas as pd\n\nfrom xgboost import XGBRegressor\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nDIRECTORY = '..\/input\/cyclistic-bike-share'\ndef set_display():\n    \"\"\"Function sets display options for charts and pd.DataFrames.\n    \"\"\"\n    # Plots display settings\n    plt.style.use('fivethirtyeight')\n    plt.rcParams['figure.figsize'] = 12, 8\n    plt.rcParams.update({'font.size': 14})\n    # DataFrame display settings\n    pd.set_option('display.max_columns', None)\n    pd.set_option('display.max_rows', None)\n    pd.options.display.float_format = '{:.4f}'.format\n    \n    \nset_display()\n\"\"\"\n## Load the Data\n\"\"\"\n# Read the data from all csv files.\npaths = glob.glob(f'{DIRECTORY}\/*.csv')\ndata = pd.concat((pd.read_csv(path) for path in paths), ignore_index=True)\n\nprint(f'Data shape: {data.shape}')\ndata.head()\n# ID and date columns have object data type.\ndata.dtypes\n# There are missing values in station name and ID columns\n# and some latitude and longitude columns.\ndata.isna().sum()\n\"\"\"\n## Data Processing and Analysis\n\"\"\"\n\"\"\"\n#### Treating missing values\n\nData set contains missing values in the station name and ID columns, while all start coordinates and most of the end coordinates are present. Attempt to fill in missing values based on the coordinates fails. For any station both latitude and longutude vary slightly, and coordinates in samples with missing station name do not match with any known locations, even when coordinates are rounded to 3 decimal points.\n\nSeveral approaches could be applied to this problem:\n- Drop and ignore the samples with missing station names.\n- Introduce a new category \"station_unknown\" and use it to replace all missing values. Testing showed that it made the model accuracy worse compared to dropping the samples with incomplete information.\n- Apply nearest neighbours algorithm to assign station names based on the most similar coordinates. This approach is better than introducing \"station_unknown\" category but still makes the model worse compared to dropping the samples with NaNs.\n\nWe cannot be sure if missing values in station name columns result from data incompleteness or if the bikes actually could be taken from some locations outside the bike rent stations and left outside the stations when the ride is over. In this version of the notebook we drop the incomplete samples, because this approach leads to a better accuracy.\n\"\"\"\n# Cleaning data types for date columns.\ndata['started_at'] = pd.to_datetime(data['started_at'])\ndata['ended_at'] = pd.to_datetime(data['ended_at'])\ndata.head()\n# All the bike stations are located in the city of Chicago\n# with coordinates varying in a narrow range.\nstats = data.describe()\nstats\n# Data covers 13 months starting from April 2021 till April 2021.\nprint(f'Time span: {data[\"started_at\"].min()} - {data[\"started_at\"].max()}')\n# Feature analysis\nfor feature in ('start_station_name', 'end_station_name'):\n    print(f'Feature \"{feature}\": {data[feature].nunique()} unique values')\n# Categorical features\nfig, ax = plt.subplots(1, 2, figsize=(16, 8))\ndata['rideable_type'].value_counts().plot.pie(\n    autopct='%1.2f%%', ax=ax[0], fontsize=12, startangle=135)\ndata['member_casual'].value_counts().plot.pie(\n    autopct='%1.2f%%', ax=ax[1], fontsize=12, startangle=135)\nplt.suptitle('Categorical Features', fontsize=20)\nplt.show()\n\"\"\"\nThere are three types of bikes. The most popular category is docked bike (67.5% of data samples). Electric bikes and classic bikes are less popular. Bike users come from two major categories. Most of the users are \"members\" (59%). Casual users account for about 41% of data samples.\n\"\"\"\n# Frequency of start and end points in the data set.\nfig, ax = plt.subplots(1, 2, figsize=(16, 8))\nax[0].hist(data['start_station_name'].value_counts(), bins=20)\nax[1].hist(data['end_station_name'].value_counts(), bins=20)\nax[0].set(xlabel='Start station frequency')\nax[1].set(xlabel='End station frequency')\nplt.suptitle('Bike Station Popularity', fontsize=20)\nplt.show()\n\"\"\"\nBike rent stations differ in popularity: while most stations attract relatively small number of users, some locations see tens of thousands of users a year.\n\"\"\"\n# Range of coordinates and seasonality\ndata.hist(bins=20, figsize=(16, 16))\nplt.suptitle('Seasonality and Station Coordinates')\nplt.show()\n\"\"\"\nThe two upper charts show overall number of bikes rented across all stations. There is a strong seasonality with demand rising in the summer and falling in the winter months.\n\nBike stations are located in a city of Chicago. Longitude and latitude coordinates are relatively close to each other with most frequent values being in the middle (city center).\n\"\"\"\n\"\"\"\n#### Feature engineering\n\"\"\"\n# Rent duration\ndata['duration'] = (data['ended_at'] - data['started_at']) \/ np.timedelta64(60, 's')  # In minutes\n\n# Location features\ndata['same_station'] = (data['start_station_name'] == data['end_station_name']).astype(int)\ndata['park'] = data['start_station_name'].str.lower().str.contains('park')\ndata['park'] = data['park'].fillna(0).astype(int)\n\n# Temporal features\ndata['year'] = data['started_at'].dt.year\ndata['month'] = data['started_at'].dt.month\ndata['weekofyear'] = data['started_at'].dt.isocalendar().week\ndata['dayofyear'] = data['started_at'].dt.dayofyear\ndata['day'] = data['started_at'].dt.day\ndata['dayofweek'] = data['started_at'].dt.dayofweek\ndata['hour'] = data['started_at'].dt.hour\n# Demand analysis with respect to rent duration and start \/ end points.\nfig, ax = plt.subplots(1, 2, figsize=(16, 8))\ndata['same_station'].value_counts().plot.pie(\n    explode=[0, 0.25], autopct='%1.2f%%', ax=ax[0], fontsize=12, startangle=135)\ndata['duration'].hist(bins=20, ax=ax[1], log=True)\nplt.suptitle('Bike Demand', fontsize=20)\nax[1].set(ylabel='Frequency')\nax[1].set(xlabel='Duration, minutes')\nax[1].legend()\nplt.show()\n\"\"\"\nMost users take the bike in one location and return it to another station. Only 10% of users return the bike to the same station where they rented it.\n\nRent duration is exponentially distributed: most users rent bikes for short rides, but there are users who rent bikes for longer periods of time (up to 1-1.5 months). Also, the chart shows errors in the data set, where rent duration is negative, which means that either the start or the end time is incorrect.\n\"\"\"\ndata['park'].value_counts().plot.pie(\n    autopct='%1.2f%%', fontsize=12, startangle=135)\nplt.suptitle('Proximity to Park', fontsize=20)\nplt.show()\n\"\"\"\nBased on the analysis on station names only about 4% of bike stations are located near park areas.\n\"\"\"\n# Since the data covers 13 months, we drop the latast month\n# to be able to show how demand is distributed throughout the year.\nfor feature in ('month', 'weekofyear', 'dayofyear', 'day',\n                'dayofweek', 'hour'):\n    grouped_data = data[data['started_at'] < '2021-04'].groupby(by=feature)['ride_id'].count()\n    grouped_data = grouped_data \/ grouped_data.sum()\n    plt.bar(grouped_data.index, grouped_data.values)\n    plt.title(f'Bike Demand by {feature}')\n    plt.ylabel('Percentage of total demand')\n    plt.show()\n\"\"\"\nThe charts above demonstrate several strong patterns in the data:\n- Seasonality: demand is the highest in the summer and lowest in winter months. Visuble growth in demand starts in June, and decline starts in September. Peak demand is seen in August. The lowest demand is seen in February. Relative spike in demand for bikes is seen in March. The same general outlook is seen on the charts with monthly, weekly and dayly rent events.\n- During the month the demand shifts in a narrow range. It's not obvious from the chart, what factors drive these changes. First day of each month usually demonstrates lower demand compared to average. Low demand in the last day obviously can be explained by the fact that not every month has 31 days.\n- During the week the highest demand is seen on Saturday and the lowest - at the beginning of the week. The number of users grows gradually from Monday till Friday with a sharp spike on Saturday. On Sunday demand is still higher than on weekdays but much lower compared to Saturday.\n- During the day the demand is steadily growing reaching the maximum at about 5 p.m. and then decreases till the night and early morning hours.\n\"\"\"\n\"\"\"\n## Convert Data into Daily Format\n\"\"\"\n# Sum up the number of rents per day for each bike station.\ndaily_data = data.groupby(by=['start_station_name', 'dayofyear']).agg(\n    {'ride_id': 'count', 'start_lat': 'min', 'start_lng': 'min',\n     'park': 'min', 'year': 'min', 'month': 'min',\n     'weekofyear': 'min', 'day': 'min', 'dayofweek': 'min'}).reset_index()\n\ndaily_data = daily_data.rename(columns={'ride_id': 'n_bikes'})\n\nprint('Data shape:', daily_data.shape)\ndaily_data.head()\ndaily_data.describe()\ndaily_data['n_bikes'].hist(bins=100)\nplt.ylabel('Frequency')\nplt.xlabel('N bikes rented')\nplt.title('Daily Bike Rents')\nplt.show()\n\"\"\"\nFor most bike stations daily demand level does not exceed 10-20 bikes a day. However, at some locations the demand is much higher and increases significantly in high summer season.\n\nTransformed daily data set has one problem we have to deal with: it does not contain samples for stations where no bikes were rented during the day. Total number of stations is 713. Period from April 2020 till April 2021 covers 395 days. The data set contains 185,982 rows. Dividing 185,982 samples by 713 unique stations we get 260.8, which is less than the expected number of days. We will fill in missing rows with 0 bikes rented before creating and training the model.\n\"\"\"\n# Days when no bikes were rented at the station are missing in the data set.\n# Create a new DataFrame for all possible combinations of station name\n# and days of the period from April 2020 till April 2021.\nstations = daily_data['start_station_name'].unique().tolist()\nprint('Unique stations:', len(stations))\nall_days_stations = pd.DataFrame(columns=stations)\nall_days_stations['date'] = pd.date_range(start='2020-04-01', end='2021-04-30', freq='D')\nall_days_stations = all_days_stations.fillna(0)\nprint('Data shape before melt:', all_days_stations.shape)\nprint('Dates range:', all_days_stations['date'].min(), all_days_stations['date'].max())\n\n# We need station name, year and day of year columns\n# to join this data with the original DataFrame.\nall_days_stations['year'] = all_days_stations['date'].dt.year\nall_days_stations['dayofyear'] = all_days_stations['date'].dt.dayofyear\n\nall_days_stations = pd.melt(\n    all_days_stations, id_vars=['year', 'dayofyear'],\n    value_vars=stations, var_name='start_station_name', value_name='n_bikes')\n\nprint('Data shape after melt:', all_days_stations.shape)\nall_days_stations.head()\n# Combine with the original data.\ndaily_data = pd.merge(all_days_stations.drop('n_bikes', axis=1),\n                      daily_data, on=['start_station_name', 'year', 'dayofyear'],\n                      how='left')\nprint('Data shape:', daily_data.shape)\ndaily_data.head()\n# Fill in missing values.\ndaily_data['n_bikes'] = daily_data['n_bikes'].fillna(0)\n\n# Fill in missing values for location and time features\n# by copying previous values in a sorted DataFrame.\ndaily_data.sort_values(\n    by=['start_station_name', 'n_bikes'],\n    ascending=False, inplace=True)\ndaily_data[['start_lat', 'start_lng', 'park']] = daily_data[\n    ['start_lat', 'start_lng', 'park']].fillna(method='ffill')\n\ndaily_data.sort_values(\n    by=['year', 'dayofyear', 'n_bikes'],\n    ascending=False, inplace=True)\ndaily_data[['year', 'month', 'weekofyear', 'day', 'dayofweek']] = daily_data[\n    ['year', 'month', 'weekofyear', 'day', 'dayofweek']].fillna(method='ffill')\n# Fix data types\nfor feature in ('weekofyear', 'month', 'year'):\n    daily_data[feature] = daily_data[feature].astype(int)\n# Demand Heat-Map\ndemand_by_period = daily_data.pivot_table(\n    index='year', columns='month', values='n_bikes', aggfunc='sum')\nax = sns.heatmap(demand_by_period, center=0, annot=False, cmap='RdBu_r')\nl, r = ax.get_ylim()\nax.set_ylim(l + 0.5, r - 0.5)\nplt.yticks(rotation=0)\nplt.title('Demand by Period')\nplt.show()\n\"\"\"\nDemand Heat-Map shows that 2021 differs from the previous year by significantly lower demand for bikes in April. Later data is not available. However, it's likely that because of the pandemic demand patterns for the entire year 2021 are not exactly the same as in 2020. In this situation we cannot simply use the data from a comparable period of the previous year to predict bike rents for the latest month. We need to train a model that takes into account multiple factors and constantly retrain it adding most recent data to catch any sudden changes in the users' behaviour.\n\"\"\"\ndemand_by_station = daily_data.pivot_table(\n    index='start_station_name', columns='month', values='n_bikes', aggfunc='sum')\nax = sns.heatmap(demand_by_station, center=0, annot=False, cmap='RdBu_r')\nl, r = ax.get_ylim()\nax.set_ylim(l + 0.5, r - 0.5)\nplt.yticks(rotation=0)\nplt.title('Demand by Station')\nplt.show()\n\"\"\"\nNumber of bikes rented at every individual bike station varies in a wide range depending on the season and location. This difference would be reflected in a \"cluster\" feature, which we will introduce groupping the stations into 10 clusters depending on their popularity.\n\"\"\"\n\"\"\"\n#### Feature engineering for daily data\n\"\"\"\n# Group the bike stations into clusters according to their popularity.\n# To avoid data leakage we do not use the entire data set to group the stations.\n# We take the data up till March 2021 and bin total number of rent events\n# for each station during that period.\nrents_by_station = daily_data[\n    ~((daily_data['year'] == 2021) & (daily_data['month'] == 4))\n].groupby(by='start_station_name')['n_bikes'].sum()\n\nbins = pd.cut(rents_by_station, bins=10, labels=[i for i in range(10)])\ncluster_dict = dict(zip(rents_by_station.index, bins))\n\nwith open('station_clusters.json', 'w') as f:\n    json.dump(cluster_dict, f, indent=2)\n\ndaily_data['cluster'] = daily_data['start_station_name'].apply(lambda x: cluster_dict[x])\ndaily_data.head()\n# Distribution of stations between clusters.\nclusters = daily_data['cluster'].value_counts() \/ 395  # 395 days for each bike station.\nplt.bar(clusters.index, clusters.values)\nplt.xlabel('Cluster IDs')\nplt.ylabel('Number of stations')\nplt.title('Station Clusters')\nplt.show()\n# Lagged target values: the number of bikes rented at the same station\n# the previous day and 7 days before the predicted day.\n# To get the lagged target values for each station separately\n# we sort the data by station and year and day of year\n# and shift target values in a grouped DataFrame.\ndaily_data.sort_values(\n    by=['start_station_name', 'year', 'dayofyear'],\n    inplace=True)\n\nfor num in (1, 7):\n    daily_data[f'lag_{num}'] = daily_data.groupby(\n        by='start_station_name')['n_bikes'].shift(num)\n    \n# Rolling mean of the target for the last 7 days before the predicted day.\ndaily_data['rol_week'] = daily_data.groupby(\n        by='start_station_name')['lag_1'].transform(lambda x: x.rolling(7).mean())\n# Save the data for future use.\ndaily_data.to_csv('daily_data.csv', index=False)\n# Correlation matrix\ncorrelation = daily_data.corr()\nax = sns.heatmap(correlation, center=0, annot=True, cmap='RdBu_r', fmt='0.2f')\nl, r = ax.get_ylim()\nax.set_ylim(l + 0.5, r - 0.5)\nplt.yticks(rotation=0)\nplt.title('Correlation Matrix')\nplt.show()\n\"\"\"\nAvailable data covers 13 months. Two approaches for training and validation are possible:\n- Use the data from April 2020 till March 2021 for training and the data for April 2021 for validation.\n- Use some portions of the data for each month (for example the last week of each month for validation).\n\"\"\"\n# Select row indexes for every fourth week of the data set for validation.\nvalid_idx = daily_data[daily_data['weekofyear'] % 4 == 0].index\ndata_valid = daily_data.loc[valid_idx, :]\ndata_train = daily_data.drop(data_valid.index)\nprint(f'Train data shape: {data_train.shape}\\n'\n      f'Validation data shape: {data_valid.shape}')\ny_train = data_train.pop('n_bikes')\ny_valid = data_valid.pop('n_bikes')\n\"\"\"\n## Predict Daily Demand for Bikes per Station\n\"\"\"\n\"\"\"\n### XGBoost model\n\nFor this model we drop station names assuming that geographical coordinates, station clusters, temporal features and lagging target values will be enough to predict daily bike rents.\n\nTesting showed that encoding 713 bike station names and using this as an input feature does not improve XGBoost model accuracy but decreases the impact of other features.\n\"\"\"\ndata_train.drop('start_station_name', axis=1, inplace=True)\ndata_valid.drop('start_station_name', axis=1, inplace=True)\ndata_train.head()\nEARLY_ROUNDS = 50\n\nmodel = XGBRegressor(\n    n_estimators=500,\n    objective='reg:squarederror', \n    booster='gbtree'\n)\n\nmodel.fit(data_train, y_train, eval_set=[(data_valid, y_valid)],\n          eval_metric='rmse', early_stopping_rounds=EARLY_ROUNDS)\n# Save the regressor.\nmodel.save_model('xgb_demand_model.bin')\nprint(f'Validation RMSE = {model.best_score}')\n# Check the feature importance.\nimportance = pd.DataFrame({\n    'features': data_train.columns,\n    'importance': model.feature_importances_\n})\nimportance.sort_values(by='importance', inplace=True)\n\nplt.barh(importance['features'], importance['importance'])\nplt.title('XGBoost Feature Importance')\nplt.show()\n\"\"\"\nXGBoost model RMSE is about 9.5 bikes a day while the target values vary between 1 and 758 with a standard deviation of 28.\n\nAll the features that are used in the input data are meaningful to the model with seasonal and temporal features being the most important (week of the year, month and year). Location features including proximity to parks are in the middle of the importance ranking. Day features are the less important.\n\"\"\"\n# Check the actual magnitude of errors and their distribution.\ndata_valid['prediction'] = model.predict(data_valid)\ndata_valid['n_bikes'] = y_valid\ndata_valid['mae'] = (data_valid['prediction'] - data_valid['n_bikes']).abs()\n\nprint('XGBoost Validation MAE:', data_valid['mae'].mean())\n\nplt.hist(data_valid['mae'], bins=100)\nplt.xlabel('Error, bikes a day')\nplt.ylabel('Frequency')\nplt.title('XGBoost Mean Absolute Error')\nplt.show()\n\"\"\"\nWe can conclude that basic XGBoost model is relatively good at predicting daily demand for bikes at various rent stations. Occasional large errors, most likely, come from rare special events at unique locations where a large number of bikes was rented at once and overestimation of demand for stations lokated in the city center.\n\"\"\"\n# The largest errors.\ndata_valid[data_valid['mae'] > 100]\n\"\"\"\n### Neural network with TensorFlow\nFor this model we can use stations names as a categorical feature without any concern about the dimensionality of the input data. Other original and engineered features also can be used. The model takes 2 inputs: an array of numerical features and an array with categorical values for station name and outputs a single value - expected number of bikes rented at this station on a given day.\n\"\"\"\ndef set_seed(seed=42):\n    \"\"\"Utility function to use for reproducibility.\n    :param seed: Random seed\n    :return: None\n    \"\"\"\n    np.random.seed(seed)\n    random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n    \n    \nset_seed()\n# Drop samples with NaN values from the daily data.\ndaily_data = daily_data.dropna()\n\n# Update training and validation subsets.\nvalid_idx = daily_data[daily_data['weekofyear'] % 4 == 0].index\ndata_valid = daily_data.loc[valid_idx, :]\ndata_train = daily_data.drop(data_valid.index)\n\nprint(f'Train data shape: {data_train.shape}\\n'\n      f'Validation data shape: {data_valid.shape}')\n\ndata_train.head()\n# Move categorical columns into a separate input array.\ndata_train_cat = data_train.pop('start_station_name')\ndata_valid_cat = data_valid.pop('start_station_name')\n\n# Move target values into separate variables.\ny_train = data_train.pop('n_bikes')\ny_valid = data_valid.pop('n_bikes')\ndef get_category_encoding_layer(cat_feature: np.array, dtype: str,\n                                max_tokens=None):\n    \"\"\"Function creates category encoding layer\n    with string or integer lookup index.\n    :param cat_feature: Array containing categorical input data for one feature\n    :param dtype: String describing data type of the categorical feature (one of 'string' or 'int64')\n    :param max_tokens: Maximum number of tokens in the lookup index\n    :return: Lambda function with categorical encoding layers and lookup index\n    \"\"\"\n    # Lookup layer which turns strings or integers into indices\n    if dtype == 'string':\n        index = tf.keras.layers.experimental.preprocessing.StringLookup(\n            max_tokens=max_tokens)\n    else:  # 'int64'\n        index = tf.keras.layers.experimental.preprocessing.IntegerLookup(\n            max_tokens=max_tokens)\n    # Learn the data scale\n    index.adapt(cat_feature)\n    # Category encoding layer\n    encoder = tf.keras.layers.experimental.preprocessing.CategoryEncoding(\n        max_tokens=index.vocab_size())\n    return lambda feature: encoder(index(feature))\n# Create normalization layer and adapt it to the numerical data.\nnormalizer = tf.keras.layers.experimental.preprocessing.Normalization(axis=None)\nnormalizer.adapt(data_train.sample(n=30_000))\n\n# Create  encoding layer for categorical feature.\nencoding_layer = get_category_encoding_layer(\n    data_train_cat.drop_duplicates().values, dtype='string')\n# Model input layers\nnum_input = tf.keras.Input(shape=(data_train.shape[1],), dtype=tf.float32)\ncat_input = tf.keras.Input(shape=(1,), dtype='string')\n\n# Process inputs separately and combine.\nx_1 = normalizer(num_input)\nx_2 = encoding_layer(cat_input)\nx = tf.keras.layers.concatenate([x_1, x_2])\n\nx = tf.keras.layers.Dense(\n    128, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\nx = tf.keras.layers.Dense(\n    64, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\nx = tf.keras.layers.Dense(\n    32, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\n\noutput = tf.keras.layers.Dense(1)(x)\n\nmodel = tf.keras.Model([num_input, cat_input], output)\n\nmodel.compile(optimizer='adam',\n              loss='mse',\n              metrics=[tf.keras.metrics.MeanAbsoluteError(),\n                       tf.keras.metrics.RootMeanSquaredError()]\n              )\n# Visualize the model graph\ntf.keras.utils.plot_model(model, show_shapes=True, show_dtype=True)\n# Train the model\nhistory = model.fit(x=[data_train, data_train_cat], y=y_train,\n                    epochs=20, batch_size=64)\n# Save the model\nmodel.save('tf_demand_model')\n# Check the magnitude of validation errors and their distribution.\ndata_valid['prediction'] = model.predict(x=[data_valid, data_valid_cat], batch_size=512)\ndata_valid['n_bikes'] = y_valid\n\ndata_valid['mae'] = (data_valid['prediction'] - data_valid['n_bikes']).abs()\nprint('Validation MAE =', data_valid['mae'].mean())\nplt.hist(data_valid['mae'], bins=100)\nplt.xlabel('Error, bikes a day')\nplt.ylabel('Frequency')\nplt.title('Neural Net Mean Absolute Error')\nplt.show()\n\"\"\"\n## Predict rent duration and end coordinates for individual rides\nThe model takes **4 inputs**: array of numarical features and 3 arrays of categorical values (for bike type, station name and user category) and outputs an array that contains **3 values**: expected **ride duration** in minutes, predicted **end point latitude and longitude**.\n\"\"\"\n# Drop samples with missing start station name or end coordinates\n# from the original data for individual rides.\ndata = data.dropna(subset=['start_station_name', 'end_lat', 'end_lng'])\n\n# Array of all station names.\nunique_stations = data['start_station_name'].drop_duplicates().values\n\n# Remove samples with negative ride duration.\ndata = data[data['duration'] > 0]\n\n# Drop samples with too large ride duration (outliers).\nthreshold = round(data['duration'].quantile(0.97), 2)\nprint(f'97% quantile for ride duration: {threshold} minutes')\ndata = data[data['duration'] <= threshold]\n\n# Drop unnecessary columns\ndata.drop(labels=['same_station', 'ride_id', 'started_at', 'ended_at',\n                  'start_station_id', 'end_station_id', 'end_station_name'],\n          axis=1, inplace=True)\n\n# Add categorical column with station clusters for start points.\ndata['cluster'] = data['start_station_name'].apply(lambda x: cluster_dict[x])\n# Split the data into train and validation sets.\ndata_valid = data.sample(frac=0.15, random_state=0)\ndata_train = data.drop(data_valid.index)\n\nprint(f'Train data shape: {data_train.shape}\\n'\n      f'Validation data shape: {data_valid.shape}')\n# Define the target values: one for ride duration\n# and two for end point coordinates.\ntarget_columns = ['duration', 'end_lat', 'end_lng']\n\ny_train = data_train[target_columns]\ny_valid = data_valid[target_columns]\n\ndata_train.drop(labels=target_columns, axis=1, inplace=True)\ndata_valid.drop(labels=target_columns, axis=1, inplace=True)\ntf.keras.backend.clear_session()\ndel daily_data, data_train_cat, data_valid_cat\ngc.collect()\n# Process numerical and categorical features separately.\ncat_features = ['rideable_type', 'start_station_name', 'member_casual']\nnum_features = [col for col in data_train.columns if col not in cat_features]\n\nprint('Categorical features:', cat_features)\nprint('Numerical features:', num_features)\ndata_train_bike = data_train.pop('rideable_type')\ndata_train_station = data_train.pop('start_station_name')\ndata_train_user = data_train.pop('member_casual')\n\ndata_valid_bike = data_valid.pop('rideable_type')\ndata_valid_station = data_valid.pop('start_station_name')\ndata_valid_user = data_valid.pop('member_casual')\ndata_train = data_train.astype(np.float32)\ndata_valid = data_valid.astype(np.float32)\n# Normalization layer for numerical features.\nnormalizer = tf.keras.layers.experimental.preprocessing.Normalization(axis=None)\nnormalizer.adapt(data_train.sample(n=30_000))  # Adapt to a fraction of train data.\n\n# Three encoding layers for categorical features.\nencoding_layer_bike = get_category_encoding_layer(\n    data_train_bike.drop_duplicates().values, dtype='string')  # Learn all unique values.\nencoding_layer_station = get_category_encoding_layer(unique_stations, dtype='string')\nencoding_layer_user = get_category_encoding_layer(\n    data_train_user.drop_duplicates().values, dtype='string')\n# Model input layers\nnum_input = tf.keras.Input(shape=(data_train.shape[1],),\n                           dtype=tf.float32, name='numeric')\n\ncat_input_bike = tf.keras.Input(shape=(1,), dtype='string', name='bike')\ncat_input_station = tf.keras.Input(shape=(1,), dtype='string', name='station')\ncat_input_user = tf.keras.Input(shape=(1,), dtype='string', name='user')\n# Process inputs separately and combine.\nx_1 = normalizer(num_input)\nx_2 = encoding_layer_bike(cat_input_bike)\nx_3 = encoding_layer_station(cat_input_station)\nx_4 = encoding_layer_user(cat_input_user)\n\nx = tf.keras.layers.concatenate([x_1, x_2, x_3, x_4])\n\nx = tf.keras.layers.Dense(\n    128, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\nx = tf.keras.layers.Dense(\n    64, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\nx = tf.keras.layers.Dense(\n    32, activation='relu',\n    kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)\n\noutput = tf.keras.layers.Dense(3)(x)\n\nmodel = tf.keras.Model([num_input, cat_input_bike, cat_input_station, cat_input_user], output)\n\nmodel.compile(optimizer='adam',\n              loss='mse',\n              metrics=[tf.keras.metrics.MeanAbsoluteError(),\n                       tf.keras.metrics.RootMeanSquaredError()]\n              )\n# Visualize the model graph\ntf.keras.utils.plot_model(model, show_shapes=True, show_dtype=True)\ndel data\ngc.collect()\nhistory = model.fit(\n    x=[data_train, data_train_bike, data_train_station, data_train_user],\n    y=y_train, epochs=5, batch_size=1024, shuffle=False)\n# Save the model\nmodel.save('tf_user_model')\n# Check the magnitude of validation errors and their distribution.\nprediction = model.predict(\n    x=[data_valid, data_valid_bike, data_valid_station, data_valid_user],\n    batch_size=1024)\n\nerrors = np.abs(prediction - y_valid.values)\n\nfor i, target in enumerate(target_columns):\n    print(f'{target} MAE = {np.mean(errors[:, i])}')\n\n    plt.hist(errors[:, i], bins=100)\n    plt.xlabel('Error')\n    plt.ylabel('Frequency')\n    plt.title(f'Mean Absolute Error: {target}')\n    plt.show()","meta":"{'source': 'AI4Code', 'id': '5fc88734a52b60'}"}
{"id":"97942","text":"\"\"\"\n# Understanding the dataset\n\"\"\"\n\"\"\"\n# The dataset provided for this competition is as follows\n\"\"\"\n\"\"\"\n# ![Screenshot%202020-11-04%20at%203.02.16%20PM.png](attachment:Screenshot%202020-11-04%20at%203.02.16%20PM.png)\n\"\"\"\n\"\"\"\nYou can read more about the dataset\n[here](http:\/\/https:\/\/www.kaggle.com\/c\/siim-isic-melanoma-classification\/data)\n\"\"\"\n\"\"\"\nLet us print the dataset \n\"\"\"\nprint(\"There are following directories and files in this dataset\")\nprint(*list(os.listdir(\"..\/input\/siim-isic-melanoma-classification\")),sep = \"\\n\")\n\"\"\"\n# Choosing the data for model training\n\"\"\"\n\"\"\"\nWe will now count the number of images in the following directories:\n\n1. jpeg -> train\n2. train\n\n\"\"\"\nimport glob\ntrain_images_jpg_format = glob.glob('..\/input\/siim-isic-melanoma-classification\/jpeg\/train\/*.jpg')\nlen(train_images_jpg_format)\nimport glob\ntrain_images_dcm_format = glob.glob('..\/input\/siim-isic-melanoma-classification\/train\/*.dcm')\nlen(train_images_dcm_format)\n\"\"\"\nAs we can see above the number of images in the DICOM format and JPEG format are same. So we will be using JPEG format images in this notebook for training and prediction purpose.\n\"\"\"\n\"\"\"\n# We will use JPEG format of images and treat this problem as an image classification problem with 2 cateories.\n\"\"\"\n\"\"\"\n# Importing necessary libraries\n\n\"\"\"\n\"\"\"\nImport Pandas - For data analysis\nImport Fastai - For training of deep learning model and predictions.\n\n**Note**: We are using Fastai version 2 (Not previous version of Fastai- which is version 1).\n\n\"\"\"\nimport pandas as pd\n\nimport fastai\nfrom fastai.vision.all import *\n\"\"\"\n# Defining the variables and assigning the paths for this notebook\n\n\"\"\"\npath = Path('..\/input\/input\/siim-isic-melanoma-classification\/')\nimage_path = Path('..\/input\/siim-isic-melanoma-classification\/jpeg\/train')\ntraining_data_file = Path('..\/input\/siim-isic-melanoma-classification\/train.csv')\nsample_submission_file = Path('..\/input\/siim-isic-melanoma-classification\/sample_submission.csv')\n\"\"\"\n# Analysing the data\n\"\"\"\ntrain_df = pd.read_csv(training_data_file)\nprint(\"Size of Training data \\n\", train_df.shape)\nprint(\"----------------------------------------------------------\")\nprint(\"\\nFirst few samples of data are \\n\",train_df.head())\n\"\"\"\nLet us print the number of data samples with output as category \"1\"  \n\"\"\"\ntrain_df_output_1 = train_df[train_df['target']==1]\ntrain_df_output_1.shape\n\"\"\"\nLet us print the number of data samples with output as category \"0\"  \n\"\"\"\ntrain_df_output_0 = train_df[train_df['target']==0]\ntrain_df_output_0.shape\n\"\"\"\n# Selecting a subset of data for training purpose\n\"\"\"\n\"\"\"\nWe will select all the training data which has the output category as \"1\" and 0.3 % of training data which has the output category as \"0\" to have equal number of inputs with the same category of output.\n\"\"\"\ntrain_df_output_0 = train_df[train_df['target']==0].sample(frac=0.03,random_state=111)\ntrain_df_output_0.shape\n\"\"\"\nLet us join the inputs selected from both the categories and call it a \"new_df\".\n\"\"\"\nnew_df = pd.concat([train_df_output_0,train_df_output_1]).reset_index(drop=True)\nnew_df.shape\n\"\"\"\n# Creating the image data loader\n\"\"\"\nimage_data_loader = ImageDataLoaders.from_df(new_df, path=image_path,\n                               seed=42, fn_col=0, \n                               suff='.jpg', label_col=7, \n                               item_tfms=Resize(128), \n                               batch_tfms=aug_transforms(flip_vert=True, max_warp=0.), \n                               bs=128, val_bs=None, shuffle_train=True)\n\"\"\"\nLet us check the device type of our \"ImageDataLoader\" to make sure that we are using \"GPU\" \n\"\"\"\nimage_data_loader.device\n\"\"\"\nLet us check few random images from our ImageDataLoader's batch to make sure that images and labels appears correctly in it.\n\"\"\"\nimage_data_loader.show_batch()\n\n\"\"\"\n# Trainnig the image recognizer model\n\"\"\"\n\"\"\"\nWe create a CNN (convolutional neural network) with the following specific details:\n\n* What data we want to train it on?\n<\/br>\n  Our data to be used for training is \"image_data_loader\"\n  \n* Which architecture to use?\n<\/br>\n  We are using Resnet34 \n  \n* what metric to use for our training evaluation?\n  <\/br>\n  We have specified it as \"error_rate\"\n\"\"\"\nlearn = cnn_learner(image_data_loader, resnet34, metrics=error_rate)\n\"\"\"\nLet us train the model for 4 epochs\n\"\"\"\nlearn.fine_tune(2)\nsub = pd.read_csv(sample_submission_file)\nsub.head()\nfor i in range(10982):\n    x = sub.at[i,'image_name']\n    test_image = Path(\"..\/input\/siim-isic-melanoma-classification\/jpeg\/test\/\" + x + \".jpg\")\n    pr1,_,pr2 = learn.predict(test_image)\n    sub.at[i,'target'] = float(pr2[int(pr1)])\nsub.head()\n\nsub.to_csv('my_submission_file.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'b3e24d14117a0b'}"}
{"id":"42236","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\ndf = pd.read_csv('..\/input\/amazon_alexa.tsv',encoding='utf-8',delimiter='\\t')\ndf.head()\ndf.info()\nfrom nltk.tokenize import word_tokenize\nfrom string import punctuation\nfrom nltk.corpus import stopwords \nfrom nltk.stem import SnowballStemmer\ndef data_clean(text):\n    \n    line = word_tokenize(text)\n    line = [word for word in line if word not in punctuation ]\n    line = [word for word in line if word not in stopwords.words('english')]\n    line = ' '.join(line)\n    return line\nx = 'Sometimes while playing a game, you can answer.'\ndata_clean(x)\ndf['clean_reviews'] = df['verified_reviews'].apply(data_clean)\ndf.head()\n\"\"\"\n# Tf-Idf Model\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvec = TfidfVectorizer()\nX = vec.fit_transform(df['clean_reviews'])\nvec.vocabulary_\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, df['feedback'], test_size=0.33, random_state=101)\n\"\"\"\n### Logistic Reg\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlog = LogisticRegression()\nlog.fit(X_train,y_train)\nlog_pred = log.predict(X_test)\nfrom sklearn.metrics import confusion_matrix,classification_report\nprint(confusion_matrix(y_test,log_pred))\nprint('\\n')\nprint(classification_report(y_test,log_pred))\n\"\"\"\n### KNN Classifier\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier \nknn = KNeighborsClassifier()\nknn.fit(X_train,y_train)\nknn_pred = knn.predict(X_test)\nprint(confusion_matrix(y_test,knn_pred))\nprint('\\n')\nprint(classification_report(y_test,knn_pred))","meta":"{'source': 'AI4Code', 'id': '4dd7d3407adc24'}"}
{"id":"96840","text":"\"\"\"\nThe purpose of this notebook is to present the benefits of hierarchical clustering for data analysis and for improving the representation of correlation heatmaps. For this notebook, we use the *breast-cancer-wisconsin* dataset. \n\n# Correlation coefficient\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Load data \ndata = pd.read_csv(\"..\/input\/breast-cancer-wisconsin-data\/data.csv\")\n\n# Show dataframe\ndata\n\"\"\"\nWe will get rid of some of the columns, including `id`, `diagnosis` and `Unnamed: 32`. `id` won't apport any important information to the model, `diagnosis` is the target and `Unnamed: 32` just contains *NaN* values.\n\"\"\"\ndata = data.drop([\"id\"], axis=1)\ndata = data.drop([\"diagnosis\"], axis=1)\ndata = data.drop([\"Unnamed: 32\"], axis=1)\n\"\"\"\nTo measure the interplay between the different features, we will calculate the correlation coefficient between pairs. The correlation between two features gives us a degree of their relation. This relation can be linear or nonlinear. For this notebook, we will use linear correlation calculating the [Pearson Correlation Coefficient](https:\/\/en.wikipedia.org\/wiki\/Pearson_correlation_coefficient) ($\\rho$). \n\nCorrelation ranges from -1 to 1, where -1 indicates anticorrelation (or negative correlation), 0 no correlation and 1 correlation (or positive correlation). The following plot shows a pair of signals with their respective correlation.\n\"\"\"\nimport numpy as np\n\nplt.figure(figsize=(14,3))\n\nline1 = np.array([2, 1, 1, 2])\nline2 = np.array([1, 2, 2, 1])\n\nplt.subplot(131)\nplt.plot(line1, color='royalblue')\nplt.plot(line2, color='lightcoral')\nplt.title(np.corrcoef(line1, line2)[1,0], fontsize=18)\n\nline1 = np.array([2, 1, 1, 2])\nline2 = np.array([1, 2, 2, 3])\n\nplt.subplot(132)\nplt.plot(line1, color='royalblue')\nplt.plot(line2, color='lightcoral')\nplt.title(round(np.corrcoef(line1, line2)[1,0],2), fontsize=18)\n\nline1 = np.array([2, 1, 1, 2])\nline2 = 2*line1\n\nplt.subplot(133)\nplt.plot(line1, color='royalblue')\nplt.plot(line2, color='lightcoral')\nplt.title(np.corrcoef(line2, 2*line2)[1,0], fontsize=18);\n\n\"\"\"\nThe three plots show a negative correlation, no correlation, and positive correlation, respectively. \n\nLinear correlation is helpful in gaining quick intuition about the relation between two signals. However, it has some drawbacks. For instance, it won't account for sequential displacements (we would need to use lags) or non-linearities. Also, keep in mind that [correlation doesn't necessary mean causation](https:\/\/www.tylervigen.com\/spurious-correlations). \n\nIn the next figure, we plot a heatmap with all the correlations between features:\n\"\"\"\nplt.figure(figsize=(15,10))\ncorrelations = data.corr()\nsns.heatmap(round(correlations,2), cmap='RdBu', annot=True, \n            annot_kws={\"size\": 7}, vmin=-1, vmax=1);\n\"\"\"\nAt first sight, we see many positive correlations (blue). However, this heatmap is messy. For visualization purposes, it would be better to group features that are highly correlated together. To do so, we will do [hierarchical clustering](https:\/\/en.wikipedia.org\/wiki\/Hierarchical_clustering). \n\n# Hierarchical Clustering\n\nHierarchical clustering is a method to find hierarchy within our data. This hierarchy allows ordering the data in clusters. It arranges the data using a dissimilarity matrix (also called distance matrix), which gives information on how far are two features. The distance can be computed in many different ways. Since we're using the Pearson Correlation Coefficient, the distance matrix will be calculated as follows:\n\n$$\nd(X, Y) = 1 - \\big | \\ \\rho_{X, Y} \\ \\big |\n$$ \n\nFor negative and positive correlations, the distance will be close to zero. If there is no correlation whatsoever, the distance will be $\\approx 0$.\n\nAfter computing the distance matrix, we have to group features hierarchically according to their distances. Then we can visualize the relationship between features in a tree diagram called dendrogram.. \n\"\"\"\nfrom scipy.cluster.hierarchy import linkage, dendrogram, fcluster\nfrom scipy.spatial.distance import squareform\n\nplt.figure(figsize=(12,5))\ndissimilarity = 1 - abs(correlations)\nZ = linkage(squareform(dissimilarity), 'complete')\n\ndendrogram(Z, labels=data.columns, orientation='top', \n           leaf_rotation=90);\n\"\"\"\nInitially, before starting the algorithm, each feature is a cluster. The algorithms take close features and combine them into a brand new cluster. Iteratively, the algorithm keeps grouping clusters until there is only one. Each leaf in the dendrogram represents a feature and each node a cluster. The *y-axis* shows the distance between points (ranging from 0 to 1). The number of clusters in our data will depend on which distance we take as a threshold. If we select a small distance, more clusters will be formed. Conversely, if we choose a large distance as a threshold, we would less clusters. \n\n\n\"\"\"\n# Clusterize the data\nthreshold = 0.8\nlabels = fcluster(Z, threshold, criterion='distance')\n\n# Show the cluster\nlabels\n\"\"\"\n`label` shows which cluster each of the features belongs to. Finally, to observe the clusters in the correlation plot, we have to rearrange the features in the dataframe according to the cluster output.\n\"\"\"\nimport numpy as np\n\n# Keep the indices to sort labels\nlabels_order = np.argsort(labels)\n\n# Build a new dataframe with the sorted columns\nfor idx, i in enumerate(data.columns[labels_order]):\n    if idx == 0:\n        clustered = pd.DataFrame(data[i])\n    else:\n        df_to_append = pd.DataFrame(data[i])\n        clustered = pd.concat([clustered, df_to_append], axis=1)\n\"\"\"\nFinally, we plot the clustered correlation plot:\n\"\"\"\nplt.figure(figsize=(15,10))\ncorrelations = clustered.corr()\nsns.heatmap(round(correlations,2), cmap='RdBu', annot=True, \n            annot_kws={\"size\": 7}, vmin=-1, vmax=1);\n\"\"\"\nSince our threshold was set at 0.7, we will be able to see five different clusters (grouped in the main diagonal). The biggest one corresponds to the red tree in the dendrogram. Since these features are related to the geometry of cancer, they form a robust cluster. Another distinct cluster is formed just by `texture_mean` and `texture_worst`, in green in the dendrogram. Note that in order for this cluster to disappear, we'd have to decrease the threshold considerably. The remaining clusters are less recognizable, given that their distances are higher.\n\nThe following plot shows the different clusters using a different threshold.\n\"\"\"\nplt.figure(figsize=(15,10))\n\nfor idx, t in enumerate(np.arange(0.2,1.1,0.1)):\n    \n    # Subplot idx + 1\n    plt.subplot(3, 3, idx+1)\n    \n    # Calculate the cluster\n    labels = fcluster(Z, t, criterion='distance')\n\n    # Keep the indices to sort labels\n    labels_order = np.argsort(labels)\n\n    # Build a new dataframe with the sorted columns\n    for idx, i in enumerate(data.columns[labels_order]):\n        if idx == 0:\n            clustered = pd.DataFrame(data[i])\n        else:\n            df_to_append = pd.DataFrame(data[i])\n            clustered = pd.concat([clustered, df_to_append], axis=1)\n            \n    # Plot the correlation heatmap\n    correlations = clustered.corr()\n    sns.heatmap(round(correlations,2), cmap='RdBu', vmin=-1, vmax=1, \n                xticklabels=False, yticklabels=False)\n    plt.title(\"Threshold = {}\".format(round(t,2)))\n\"\"\"\nSeaborn also includes a function *clustermap* to plot the correlation heatmats with dendrograms.\n\"\"\"\nsns.clustermap(correlations, method=\"complete\", cmap='RdBu', annot=True, \n               annot_kws={\"size\": 7}, vmin=-1, vmax=1, figsize=(15,12));\n\"\"\"\n\n# Conclusions\n\nHierarchical clustering can be helpful in understanding our data better. It also improves the visual representation of correlation heatmaps, making it easier to find groups of correlated features.\n\"\"\"\n\"\"\"\n# References\n1. [Hierarchical Clustering with Python and Scikit Learn](https:\/\/stackabuse.com\/hierarchical-clustering-with-python-and-scikit-learn\/)\n2. [Scipy Hierarchical Clustering](https:\/\/docs.scipy.org\/doc\/scipy\/reference\/cluster.hierarchy.html)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b1e71eb9b71ac7'}"}
{"id":"90399","text":"# loading libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nimport seaborn as sns\n# loading dataset and checking the shape and data head\nbreast_cancer = pd.read_csv('..\/input\/breast-cancer-wisconsin-data\/data.csv')\nprint(\"shape of the data: \", breast_cancer.shape)\nbreast_cancer.head()\n# checking the data info \nbreast_cancer.info()\n# dropping the Unnamed: 32 column since all the values are empty\nbreast_cancer = breast_cancer.drop(['Unnamed: 32'], axis=1)\n\n# checking sum of null values \nbreast_cancer.isnull().sum()\n# encoding categorical variables on diagnosis column\nprint(\"unique values\", breast_cancer['diagnosis'].unique())\nprint(\"before encoding -->\")\nprint(breast_cancer['diagnosis'].tail())\n\nenc = LabelEncoder()\nbreast_cancer['diagnosis'] = enc.fit_transform(breast_cancer['diagnosis'])\n\nprint(\"after encoding -->\")\nprint(breast_cancer['diagnosis'].tail())\n# checking feature correlation\nb_corr = breast_cancer.corr()\nb_corr\n\nplt.figure(figsize=(25,10))\nsns.heatmap(b_corr, cmap = sns.color_palette(\"vlag\", as_cmap=True), annot=True)\n# dropping features based on correlation\nbreast_cancer = breast_cancer.drop(['id', 'symmetry_mean', 'concavity_se', 'compactness_se' ], axis=1)\n# Splitting the dataset into features and labels\n# diagnosis column indicates the labels\nfeatures = breast_cancer.drop(['diagnosis'], axis=1)\nlabels = breast_cancer[['diagnosis']]\nprint(\"features shape\", features.shape)\nprint(\"label shape\", labels.shape)\n\n# splitting test and train data\nX_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)\nprint(\"training data shape\", X_train.shape)\nprint(\"testing data shape\", X_test.shape)\n# scaling all the values between 0-1\nscaler = MinMaxScaler(copy=False)\nscaler.fit(X_train)\nscaler.transform(X_train)\nscaler.transform(X_test)\n\n# data head after scaling\nprint(\"minimum value\", X_train.min(axis=0).values)\nprint(\"maximum value\", X_train.max(axis=0).values)\nX_train.head()\n# logistic regression model\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train.values.ravel())\ny_pred = model.predict(X_test)\nlg_accuracy = accuracy_score(y_test, y_pred)\nprint(\"Accuracy using logistic regression: \", lg_accuracy)\n# Decision tree model\nclf = DecisionTreeClassifier(criterion='entropy', random_state=42)\nclf.fit(X_train,y_train)\ny_pred = clf.predict(X_test)\ndt_accuracy = accuracy_score(y_test, y_pred)\nprint(\"Accuracy using decision tree: \", dt_accuracy)\n# plotting bar chart\nsns.set_style(\"whitegrid\")\nsns.set(rc={'figure.figsize':(6,6)})\n\nax = sns.barplot(x=['Logistic regression', 'Decision tree'], y=[lg_accuracy, dt_accuracy])\nax.set(xlabel='Models', ylabel='Accuracy', title='Classification Model Comparison')\n\na = int(lg_accuracy * 100)\nb = int(dt_accuracy * 100)\nax.text(0, lg_accuracy, str(a)+'%')\nax.text(1, dt_accuracy, str(b)+'%')\nplt.show()\nfrom sklearn import svm\nsvm_clf = svm.SVC()\n\nsvm_clf.fit(X_train,y_train.values.ravel())\n\nprint(\"Training accuracy of the model is\", (svm_clf.score(X_train, y_train)))\nsvm_accuracy = svm_clf.score(X_test, y_test)\nprint(\"Testing accuracy of the model is\", svm_accuracy)\nfrom sklearn.neural_network import MLPClassifier\nmlp_clf = MLPClassifier(hidden_layer_sizes=(7), activation=\"relu\", random_state=1, max_iter=10000)\n\nmlp_clf.fit(X_train, y_train.values.ravel())\n\nprint(\"Training accuracy of the model is\", (mlp_clf.score(X_train, y_train)))\nnn_accuracy = mlp_clf.score(X_test, y_test)\nprint(\"Testing accuracy of the model is\", nn_accuracy)\nfrom sklearn.ensemble import RandomForestClassifier\nrf_clf = RandomForestClassifier(n_estimators=50)\n\nrf_clf.fit(X_train, y_train.values.ravel())\n                            \nprint(\"Training accuracy of the model is\", (rf_clf.score(X_train, y_train)))\nrf_accuracy = rf_clf.score(X_test, y_test)\nprint(\"Testing accuracy of the model is\", rf_accuracy)                             \n# plotting bar chart\nsns.set_style(\"whitegrid\")\nsns.set(rc={'figure.figsize':(6,6)})\n\nax = sns.barplot(x=['svm', 'nn', 'rf'], y=[svm_accuracy, nn_accuracy, rf_accuracy])\nax.set(xlabel='Models', ylabel='Accuracy', title='Classification Model Comparison')\n\na = int(svm_accuracy * 100)\nb = int(nn_accuracy * 100)\nc = int(rf_accuracy * 100)\nax.text(0, svm_accuracy, str(a)+'%')\nax.text(1, nn_accuracy, str(b)+'%')\nax.text(2, rf_accuracy, str(c)+'%')\nplt.show()\n# Performing dimensionality reduction using PCA\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=15)\npca.fit(X_train)\nX_train_pca = pca.fit_transform(X_train)\nX_test_pca = pca.fit_transform(X_test)\n\nprint(X_train_pca)\nsum(pca.explained_variance_ratio_)\nfrom sklearn import svm\nsvm_model = svm.SVC()\n\nsvm_model.fit(X_train_pca, y_train.values.ravel())\n\nprint(\"Training accuracy of the model is\", (svm_model.score(X_train_pca, y_train)))\npca_svm_accuracy = svm_model.score(X_test_pca, y_test)\nprint(\"Testing accuracy of the model is\", pca_svm_accuracy)\nfrom sklearn.neural_network import MLPClassifier\nmlpc_model = MLPClassifier(hidden_layer_sizes=(7), activation=\"relu\", random_state=1, max_iter=10000)\n\nmlpc_model.fit(X_train_pca, y_train.values.ravel())\n\nprint(\"Training accuracy of the model is\", (mlpc_model.score(X_train_pca, y_train)))\npca_nn_accuracy = mlpc_model.score(X_test_pca, y_test)\nprint(\"Testing accuracy of the model is\", pca_nn_accuracy)\nfrom sklearn.ensemble import RandomForestClassifier\nrf_model = RandomForestClassifier(n_estimators=50)\n\nrf_model.fit(X_train_pca, y_train.values.ravel())\n                            \nprint(\"Training accuracy of the model is\", (rf_model.score(X_train_pca, y_train)))\npca_rf_accuracy = rf_model.score(X_test_pca, y_test)\nprint(\"Testing accuracy of the model is\", pca_rf_accuracy)                             \n# plotting bar chart for models with pca\nsns.set_style(\"whitegrid\")\nsns.set(rc={'figure.figsize':(6,6)})\n\nax = sns.barplot(x=['svm_pca', 'nn_pca', 'rf_pca'], y=[pca_svm_accuracy, pca_nn_accuracy, pca_rf_accuracy])\nax.set(xlabel='Models', ylabel='Accuracy', title='Classification Model Comparison')\n\na = int(pca_svm_accuracy * 100)\nb = int(pca_nn_accuracy * 100)\nc = int(pca_rf_accuracy * 100)\nax.text(0, pca_svm_accuracy, str(a)+'%')\nax.text(1, pca_nn_accuracy, str(b)+'%')\nax.text(2, pca_rf_accuracy, str(c)+'%')\nplt.show()\n# plotting bar chart\nsns.set_style(\"whitegrid\")\nsns.set(rc={'figure.figsize':(10,10)})\n\nax = sns.barplot(x=['SVM', 'NN', 'RF', 'SVM(with pca)', 'NN(with pca)', 'RF(with pca)'], y=[svm_accuracy, nn_accuracy, rf_accuracy, pca_svm_accuracy, pca_nn_accuracy, pca_rf_accuracy])\nax.set(xlabel='Models', ylabel='Accuracy', title='Classification Model Comparison')\n\na = int(svm_accuracy * 100)\nb = int(nn_accuracy * 100)\nc = int(rf_accuracy * 100)\nx = int(pca_svm_accuracy * 100)\ny = int(pca_nn_accuracy * 100)\nz = int(pca_rf_accuracy * 100)\nax.text(0, svm_accuracy, str(a)+'%')\nax.text(1, nn_accuracy, str(b)+'%')\nax.text(2, rf_accuracy, str(c)+'%')\nax.text(3, pca_svm_accuracy, str(x)+'%')\nax.text(4, pca_nn_accuracy, str(y)+'%')\nax.text(5, pca_rf_accuracy, str(z)+'%')\n\nplt.show()\n\"\"\"\nways to find the most representative features:\n\"\"\"\n#Univariate feature selection\n#Selected 20 features according to the k highest scores and using knn\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.neighbors import KNeighborsClassifier\n\nselect_feature = SelectKBest(chi2, k=20).fit(X_train, y_train)\n\nx_train_2 = select_feature.transform(X_train)\nx_test_2 = select_feature.transform(X_test)\nprint('Score list:', select_feature.scores_)\nprint('Feature list:', X_train.columns)\n\nknn=KNeighborsClassifier()\nprint(\"for Selected features\")\nknn.fit(x_train_2, y_train.values.ravel())\nprint(\"Test set accuracy: {:.2f}\".format(knn.score(x_test_2, y_test.values.ravel())))\nprint(\"for all features\")\nknn.fit(X_train, y_train.values.ravel())\nprint(\"Test set accuracy: {:.2f}\".format(knn.score(X_test, y_test.values.ravel())))\n#Recursive feature elimination (RFE)\nfrom sklearn.feature_selection import RFE\nfrom sklearn.ensemble import RandomForestClassifier\n# Create the RFE object and rank each pixel\nclf_rf_3 = RandomForestClassifier()      \nrfe = RFE(estimator=clf_rf_3, n_features_to_select=10\n          , step=1)\nrfe = rfe.fit(X_train, y_train.values.ravel())\nprint('Chosen best features by rfe:',X_train.columns[rfe.support_])\n#Recursive feature elimination with cross validation\n#finding optimal number of features needed for best accuracy\n# The \"accuracy\" scoring is proportional to the number of correct classifications\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.ensemble import RandomForestClassifier\nclf_rf_4 = RandomForestClassifier() \nrfecv = RFECV(estimator=clf_rf_4, step=1, cv=5,scoring='accuracy')   #5-fold cross-validation\nrfecv = rfecv.fit(X_train, y_train.values.ravel())\n\nprint('Optimal number of features :', rfecv.n_features_)\nprint('Best features :', X_train.columns[rfecv.support_])","meta":"{'source': 'AI4Code', 'id': 'a5c68f75bf20e6'}"}
{"id":"20677","text":"# # 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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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\nimport pandas as pd\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport lightgbm as lgb\nimport shap\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n# Helpful function \n\"\"\"\ndef create_missing_table(input_dataframe: pd.DataFrame):\n    total = len(input_dataframe)\n    naCount = input_dataframe.isnull().sum()\n    zeroCount = len(input_dataframe) - input_dataframe.fillna(1).astype(bool).sum()\n    zeroPercent = (zeroCount\/len(input_dataframe)*100).round().map(lambda n: '{0:.1f} %'.format(n))\n    naPercent = (input_dataframe.isnull().sum()\/len(input_dataframe)*100).round().map(lambda n: '{0:.1f} %'.format(n))\n    uniqCount = input_dataframe.nunique()\n    hitRate = (input_dataframe.notnull().sum()\/len(input_dataframe)*100).round().map(lambda n: '{0:.1f} %'.format(n))\n    return pd.DataFrame({'count_total': total, 'count_unique': uniqCount, 'count_zero':zeroCount,'percentile_zero':zeroPercent, 'count_missing': naCount,'percentile_missing':naPercent, 'hit_rate':hitRate})\ndef describe_category(dataframe, column_name, ignore_zero=False, figsize=(11,7)):\n    \"\"\"\n    plot describe category with percentage\n    \"\"\"\n    if ignore_zero:\n        dataframe = dataframe[dataframe[column_name] != 0]\n    value_count = dataframe[column_name].value_counts().sort_index()\n    df_value_count = pd.DataFrame({column_name: value_count.index, \"count\": value_count.values})\n    sum_class = df_value_count[\"count\"].sum()\n    df_value_count[\"percentage\"] = df_value_count[\"count\"]\/sum_class*100\n    display(df_value_count)\n    \n    fig, ax = plt.subplots(figsize = figsize)\n    ax = sns.barplot(data=df_value_count, x=column_name, y=\"count\")\n    ax.set_ylim(0, df_value_count[\"count\"].max()*1.2)\n    for p, percentage in zip(ax.patches, list(df_value_count[\"percentage\"])):\n        ax.annotate(\"%.2f\" % percentage +\" %\", (p.get_x() + p.get_width() \/ 2., p.get_height()),\n             ha='center', va='center', rotation=0, xytext=(0, 20), textcoords='offset points')  #vertical bars\n    plt.show()\n\"\"\"\n# Load data\n\"\"\"\ntrain_path = \"\/kaggle\/input\/tabular-playground-series-may-2021\/train.csv\"\ntest_path = \"\/kaggle\/input\/tabular-playground-series-may-2021\/test.csv\"\ntrain_df = pd.read_csv(train_path)\ntest_df = pd.read_csv(test_path)\ntrain_df.head()\ntest_df.head()\n\"\"\"\n# Training data\n\"\"\"\n\"\"\"\n## 1D eda\n\"\"\"\ntrain_df[\"target\"].value_counts()\n\"\"\"\nThis is multi-classification problem.<br>\nEach data point have 1 class only. <br>\nClass are not balance.<br>\n\"\"\"\n\"\"\"\n## Check zeros and missing\n\"\"\"\ncreate_missing_table(train_df)\n\"\"\"\nA lot of zero. Most feature have > 80% zero.\n\n\"\"\"\n\"\"\"\nLet see value of some feature\n\"\"\"\ntrain_df[\"feature_1\"].value_counts()\ntrain_df[\"feature_10\"].value_counts()\n\"\"\"\nThey have very small number of unique value. Seem like all category\n\"\"\"\n# describe_category(train_df, \"feature_10\", ignore_zero=True, figsize=(20,7))\n\"\"\"\n## Draw distribution of feature\n\"\"\"\nfeature_list = list(train_df.columns)\nfeature_list.remove(\"id\")\nfeature_list.remove(\"target\")\nfeature_list\nfor feature_name in feature_list:\n    print(\"=============  \" + feature_name + \"  ===================\")\n    describe_category(train_df, feature_name, ignore_zero=True, figsize=(20,7))\n    print(\"=========================================================\")\n\"\"\"\n### Negative value\n\nFeature 42, 39, 38, 35, 31, 30, 19\n\"\"\"\n\"\"\"\n# 2D \n\"\"\"\n\"\"\"\n## Correlation\n\"\"\"\ntrain_corr = train_df.corr()\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(train_corr, dtype=bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(25, 20))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(train_corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n            square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\"\"\"\nWe do not see strong correlation between feature.\n\"\"\"\n\"\"\"\n# Baseline Model\n\"\"\"\n\"\"\"\nLet use LightGBM because it train fast and decent performance. \n\"\"\"\nlgbm_params = {\n    'boosting': 'gbdt',\n    'learning_rate': 0.01, \n    'num_leaves': 300, \n    'objective': 'multiclass',\n    'num_class':4,\n    'metric': 'multi_logloss',\n}\n\"\"\"\n## Preprocess data\n\"\"\"\ndef convert_text_to_class(str_class):\n    if str_class == \"Class_1\":\n        return 0\n    elif str_class == \"Class_2\":\n        return 1\n    elif str_class == \"Class_3\":\n        return 2\n    elif str_class == \"Class_4\":\n        return 3\nX = train_df[feature_list]\ny = train_df[\"target\"].apply(convert_text_to_class)\ny.value_counts()\n# for feature_name in feature_list:\n#     X[feature_name] = X[feature_name].astype(np.float32)\ndata = lgb.Dataset(X, label=y, free_raw_data=False)\n\"\"\"\n## 5 Fold cross validation \n\"\"\"\nboost_round = 200\ncv_result = lgb.cv(lgbm_params, data, num_boost_round=boost_round, early_stopping_rounds=20, nfold=5, verbose_eval=100)\nprint(\"CV 5 Fold result\")\nprint(\"multi_logloss-mean :\" ,cv_result[\"multi_logloss-mean\"][-1])\nprint(\"multi_logloss-stdv :\" ,cv_result[\"multi_logloss-stdv\"][-1])\nprint(cv_result.keys())\n\"\"\"\n## Shape value \n\"\"\"\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=3041975)\ntrain_data = lgb.Dataset(X_train, label=y_train, free_raw_data=False)\nval_data = lgb.Dataset(X_val, label=y_val, reference=train_data ,free_raw_data=False)\n%%time\nboost_round = 500\nmodel = lgb.train(lgbm_params, train_data, valid_sets=[val_data], num_boost_round = boost_round, verbose_eval=100, early_stopping_rounds=50)\n%%time\nexplainer = shap.TreeExplainer(model)\nX_very_small = X.sample(500)\n%%time\nshap_values = explainer.shap_values(X_very_small)\nshap.summary_plot(shap_values[1], X_very_small, plot_type='dot', max_display=50)\n\"\"\"\n# Make submission\n\"\"\"\nX_test = test_df[feature_list]\npred = model.predict(X_test)\ny_test = pd.DataFrame(pred)\nsubmission = y_test.copy()\nsubmission.columns = [\"Class_1\", \"Class_2\", \"Class_3\", \"Class_4\"]\nsubmission[\"id\"] = test_df[\"id\"]\n# submission.columns = [\"id\", \"Class_1\", \"Class_2\", \"Class_3\", \"Class_4\"]\nsubmission.head()\nsubmission = submission[[\"id\", \"Class_1\", \"Class_2\", \"Class_3\", \"Class_4\"]]\nsubmission.head()\nsubmission.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '25eeaa45bdc781'}"}
{"id":"79023","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nnp.seterr(divide='ignore')\n\ndataset = pd.read_csv('\/kaggle\/input\/students-performance-in-exams\/StudentsPerformance.csv')\ndataset.head()\nprint(\"possible value of 'parental level of education'\")\ndataset['parental level of education'].unique()\n\"\"\"\n## Preprocessing\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\n\ndataset['gender'] = dataset['gender'].apply(lambda x: [0, 1][x == 'male'])\ndataset['parental level of education'] = dataset['parental level of education'].apply(\n    lambda x: [0, 1][x in ['high school', 'some high school', 'some college']]\n)\ndataset['lunch'] = dataset['lunch'].apply(lambda x: [0, 1][x == 'standard'])\ndataset['test preparation course'] = dataset['test preparation course'].apply(lambda x: [0, 1][x == 'none'])\n\n# for key in ['group A', 'group B', 'group C', 'group D', 'group E']:\n#     dataset[key] = dataset['race\/ethnicity'].apply(lambda x: [0, 1][x == key])\ndataset = dataset.drop(['race\/ethnicity'], axis=1)\n\ndataset['passed math'] = dataset['math score'].apply(lambda x: [0, 1][x >= 60])\ndataset = dataset.drop(['math score'], axis=1)\n\nscaler = MinMaxScaler()\nscaler.fit(dataset[['reading score']])\ndataset['reading score'] = scaler.transform(dataset[['reading score']])\n\nscaler = MinMaxScaler()\nscaler.fit(dataset[['writing score']])\ndataset['writing score'] = scaler.transform(dataset[['writing score']])\n\"\"\"\n## Predict student will pass or fail on Math\n\"\"\"\ny = dataset['passed math']\nX = dataset.drop(['passed math'], axis=1)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=10)\nX_train\nfrom sklearn.neighbors import KDTree\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\n\nclass KNNClassifier():\n\n    def __init__(\n        self,\n        n_neighbors=5,\n        weights='uniform',\n        algorithm='brute',\n        leaf_size=30,\n    ):\n        if int(n_neighbors) <= 0:\n            raise Exception('n_neighbors should be a positive integer')\n        if weights not in ['uniform', 'distance'] and not callable(weights):\n            raise Exception(\"weights should be 'uniform' or 'distance' or a callable\")\n        if algorithm not in ['brute', 'kd_tree']:\n            raise Exception(\"algorithm should be either 'brute' or 'kd_tree'\")\n        if int(leaf_size) <= 0:\n            raise Exception('leaf_size should be a positive integer')\n        self.K = int(n_neighbors)\n        self.weights = weights\n        self.algorithm = algorithm\n        self.leaf_size = leaf_size\n\n    def fit(self, X, y):\n        self.X = np.array(X)\n        self.y = np.array(y)\n        # build a k-d tree\n        if self.algorithm == 'kd_tree':\n            self.kd_tree = KDTree(self.X, leaf_size=self.leaf_size)\n\n    def compute_k_nearest(self, x_predict):\n        if self.algorithm == 'brute':\n            # Euclidean metric\n            dists = np.array([np.linalg.norm(x_predict - x) for x in self.X])\n            k_nearest_indices = np.argsort(dists)[:self.K]\n            k_nearest_dists = dists[k_nearest_indices]\n            return k_nearest_dists, k_nearest_indices\n        else:\n            k_nearest_dists, k_nearest_indices = self.kd_tree.query(np.array([x_predict]), self.K)\n            return k_nearest_dists[0], k_nearest_indices[0]\n\n    def compute_weights(self, dists):\n        if self.weights == 'uniform':\n            return np.ones(dists.shape[0])\n        elif self.weights == 'distance':\n            return np.reciprocal(dists.astype(np.float32))\n        else:\n            return self.weights(dists)\n\n    def predict(self, X):\n        X_predict = np.array(X)\n        y_predict = np.empty(X_predict.shape[0])\n        for i in range(X_predict.shape[0]):\n            k_nearest_dists, k_nearest_indices = self.compute_k_nearest(X_predict[i])\n            y_k_nearest = self.y[k_nearest_indices]\n            weights = self.compute_weights(k_nearest_dists)\n            y_predict[i] = np.argmax(np.bincount(y_k_nearest, weights=weights))\n        return y_predict\n\n\nknn = KNNClassifier(n_neighbors=5, weights='distance', algorithm='kd_tree')\nknn.fit(X_train, y_train)\ny_predict = knn.predict(X_test)\naccuracy = accuracy_score(y_test, y_predict)\nprecision, recall, fscore, support = precision_recall_fscore_support(y_test, y_predict, average='weighted')\nprint('Accuracy:', accuracy)\nprint('Precision:', precision)\nprint('Recall:', recall)\nprint('F score:', fscore)\n# print('Support:', support)\n\"\"\"\n\u4f7f\u7528 Sklean \u9a57\u7b97\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KDTree\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\n\nknn = KNeighborsClassifier(n_neighbors=5, weights='distance', algorithm='kd_tree')\nknn.fit(X_train, y_train)\ny_predict = knn.predict(X_test)\naccuracy = accuracy_score(y_test, y_predict)\nprecision, recall, fscore, support = precision_recall_fscore_support(y_test, y_predict, average='weighted')\nprint('Accuracy:', accuracy)\nprint('Precision:', precision)\nprint('Recall:', recall)\nprint('F score:', fscore)\n# print('Support:', support)\n\nimport matplotlib.pyplot as plt\n\nx = []\nuniform_y = []\ndistance_y = []\nfor k in range(1, 50):\n    knn = KNNClassifier(n_neighbors=k, weights='uniform', algorithm='kd_tree')\n    knn.fit(X_train, y_train)\n    y_predict = knn.predict(X_test)\n    accuracy = accuracy_score(y_test, y_predict)\n    x.append(k)\n    uniform_y.append(accuracy)\n    knn = KNNClassifier(n_neighbors=k, weights='distance', algorithm='kd_tree')\n    knn.fit(X_train, y_train)\n    y_predict = knn.predict(X_test)\n    accuracy = accuracy_score(y_test, y_predict)\n    distance_y.append(accuracy)\n\nfig, axes = plt.subplots(1, 2, figsize=(16, 5), sharey=True)\naxes[0].set_xlabel('k')\naxes[1].set_xlabel('k')\naxes[0].set_ylabel('accuracy')\naxes[0].plot(x, uniform_y)\naxes[0].axvline(x=5, color='red')\naxes[1].plot(x, distance_y)\naxes[1].axvline(x=5, color='red')\nfig.show()","meta":"{'source': 'AI4Code', 'id': '91210c16611228'}"}
{"id":"33195","text":"import numpy as np \nimport pandas as pd \nfrom pandas import datetime\npd.set_option('display.max_columns', None)  \npd.set_option('display.expand_frame_repr', False)\npd.set_option('max_colwidth', None)\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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\n\nfrom copy import deepcopy\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom tensorflow.keras.preprocessing.sequence import TimeseriesGenerator # Generates batches for sequence data\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,LSTM\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n#import warnings\n#warnings.filterwarnings(\"ignore\")\n\"\"\"\nIt was written that prices-split-adjusted was done on the basis of prices, so we will use only 'adjusted' one. Let's load the other data and see if it is useful to predict close price.\n\"\"\"\nprices = pd.read_csv('\/kaggle\/input\/nyse\/prices-split-adjusted.csv')\nfundamentals = pd.read_csv('\/kaggle\/input\/nyse\/fundamentals.csv')\nsecurities = pd.read_csv('\/kaggle\/input\/nyse\/securities.csv')\nprices.head(10)\nsecurities.head(10)\nfundamentals.head(10)\n\"\"\"\nSo, we have seen that 'prices' contains date, symbol, volume and prices variables like open, close, high and low. \n\n\"Fundamentals' doesn't look very promicing in predicting price.\n\n'Securities' contains additional info about the companies, like their sectors, full titles, headquarters, etc. Let's explore what companies are in Information Technology sector.\n\"\"\"\nsecurities[securities['GICS Sector'] == 'Information Technology']['Security'].unique()\n#let's have a look at how things went for 'Visa Inc.'\nsecurities[securities['Security']=='Visa Inc.'] #to get ticker symbol, it's \"V\"\nvisa = prices[prices['symbol']==\"V\"] #making a subset of prices as a new set for Visa Inc\nvisa = visa.drop('symbol', 1)\nvisa\n\"\"\"\nWe got 1762 rows and 7 columns, let's explore them.\n\"\"\"\nimport pandas_profiling\nprofile = pandas_profiling.ProfileReport(visa)\nprofile\n\"\"\"\nFrom profile report we can conclude that there are no missing values, prices have range from 16 to 84 and there is a strong correlation between prices variables. Another important note is that date column is categorical, not a datetime object. We need to fix this.\n\"\"\"\nvisa['date'] = pd.to_datetime(visa['date'])\nvisa.info()\npx.line(visa, x = 'date', y = ['open', 'close'])\npx.line(visa, x = 'date', y = ['low', 'high'])\npx.line(visa, x = 'date', y = ['volume'])\n\"\"\"\nGeneral trend shows increasing of prices year by year while the volume is decreasing (with some outliers).\n\"\"\"\ndf1 = deepcopy(visa) #for Neural Prophet, contains 'date'\ndf = deepcopy(visa) #for LSTM, dropping 'date' as a column, using as index\ndf.set_index(\"date\", inplace=True)\n#scaling values in order to look at all of them on one graph\nfor feature in ['open', 'close', 'high', 'low', 'volume']:\n    sc = MinMaxScaler()\n    visa[feature] = sc.fit_transform(visa[feature].values.reshape(-1,1))\n    \n#looking at all numerical features at once    \npx.line(visa, x = 'date', y = ['open', 'close', 'high', 'low', 'volume'])\nlen(df) # 1762\ntest_point = 50 #We want to predict for the last 50 values\ntest_index = int(len(df) - test_point) #1712\ntrain = df.iloc[:test_index,1:2] #to get the first 1712 values of the index and vwap\ntest = df.iloc[test_index:,1:2] #to get the last 50 values of the index and vwap\ntrain #to look at output (under cut)\nscaler = MinMaxScaler() #scaler for df dataset\nscaler.fit(train) #fit the scaler on train set\nMinMaxScaler(copy=True, feature_range=(0, 1))\nscaled_train = scaler.transform(train) #transform on train and test sets separately\nscaled_test = scaler.transform(test)\nlength = 49 #for input shape\nbatch_size = 1\nn_features=1 #target variable\n\n#creating generators for fitting a model\ngenerator = TimeseriesGenerator(scaled_train,scaled_train, length=length,batch_size=batch_size)\nvalidation_generator = TimeseriesGenerator(scaled_test,scaled_test,length=length,batch_size=batch_size)\n\n#very simple Sequantial model\nmodel = Sequential()\nmodel.add(LSTM(50,input_shape=(length,n_features)))\nmodel.add(Dense(1))\n\n#adam optimizer, loss = mean squared error\nmodel.compile(optimizer = 'adam',loss='mse',metrics=['accuracy'])\n\nmodel.fit_generator(generator,epochs=20,validation_data=validation_generator)\ntest_predictions = [] #variable for predictions\nfirst_eval_batch = scaled_train[-length:] #(49,1)\ncurrent_batch = first_eval_batch.reshape(1,length,n_features) #reshape to (1,49,1)\n\n#using a loop to predict: predict the first value,add the resut to test predictions \n#and replace the value in current batch. To make next predictions on the previous predictions\nfor i in range(len(test)):\n    current_pred = model.predict(current_batch)[0]\n    test_predictions.append(current_pred)\n    current_batch = np.append(current_batch[:,1:,:],\n                              [[current_pred]],axis = 1)\n#inversing predictions from scaled to normal\ntrue_predictions = scaler.inverse_transform(test_predictions)\ntest['LSTM Predictions'] = true_predictions #add predictions to test set\ntest.plot(figsize=(12,8)) #plotting\ndf1 = df1[[\"date\", \"close\"]]\ndf1.rename(columns={\"date\": \"ds\", \"close\": \"y\"}, inplace=True)\ndf_train = df1.iloc[:test_index] #splitting data for not scaled train set\n#we already have test set as test\n!pip install git+https:\/\/github.com\/ourownstory\/neural_prophet.git  \n!pip install livelossplot    #it will allow us to use plot_live_live parameter \n#in the train function to get live training and validation plots.\nfrom neuralprophet import NeuralProphet\nmodel = NeuralProphet(n_changepoints=10,\n                      trend_reg=0.1,\n                      yearly_seasonality=False,\n                      weekly_seasonality=False,\n                      daily_seasonality=True)\nmetrics = model.fit(df_train, validate_each_epoch=True, \n                    valid_p=0.2, freq='D', \n                    plot_live_loss=True, \n                    epochs=100)\nfuture = model.make_future_dataframe(df_train, \n                periods=50) #predict for 50 days\nforecast = model.predict(future)\ntest[\"Forecast_Prophet\"] = forecast.yhat1.values\ntest.plot(figsize=(14, 7)) #plotting\nfrom sklearn.metrics import mean_absolute_error\nprint(\"Results for the test set:\")\nprint(\"MAE of LSTM:\", mean_absolute_error(test.close, \n                            test['LSTM Predictions']))\nprint(\"MAE of Neural Prophet:\", \n      mean_absolute_error(test.close, test.Forecast_Prophet))\n\"\"\"\nWe can look at MAE scores and admit that LSTM does a better job, but here it is even more obvious if we look on the graph. LSTM shows a nice generalization for 50 days. However, if we needed prediction for 20 days, Neural Prophet could be a better choice.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3d2a6dc9cf01bf'}"}
{"id":"1279","text":"\"\"\"\n# 1.Loading the libraries\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n# 2.Importing the data\n\"\"\"\nsuicides=pd.read_csv('..\/input\/suicide-rates-overview-1985-to-2016\/master.csv')\n\"\"\"\n# 3.Understanding the data\n\"\"\"\nsuicides.head()\nsuicides.generation.unique() # For finding how many generations there are\nsuicides.columns\n\"\"\"\nSo the columns are:\n1. country \n2. year\n3. sex \n4. age \n5. suicides_no = the number of males\/ females with age in an interval that committed suicide in the specified year & country. For example, the first row says that 21 males between 15- 24 years from Albania committed suicide in 1987.\n6. population = total males \/ females with age in an interval in the specified year & country. For example, the first row says that in Albania in 1987 there were 312900 of males with age between 15-24 years.\n7. suicides\/100k pop= the number of suicides reported to 100,000 people. The formula is : suicides_no * 100,000\/population\n8. country-year\n9. HDI for year (Human Development Index)= statistic composite index of life expectancy, education, and per capita income indicators, which are used to rank countries into four tiers of human development. A country scores a higher HDI when the lifespan is higher, the education level is higher, and the gross national income (GNI) per capita is higher.\n10. gdp_for_year (Gross Domestic Product)= measures the value of economic activity within a country. Strictly defined, GDP is the sum of the market values, or prices, of all final goods and services produced in an economy during a period of time (in this case, one year).\n11. gdp_per_capita= it's a measure of a country's economic output that accounts for its number of people. It divides the country's gross domestic product by its total population. That makes it the best measurement of a country's standard of living. It tells you how prosperous a country is.\n12. generation: There are 6 generations in our data (I will write the periods for each generation):\n      1. G.I. Generation (or Greatest Generation): 1910-1924 \n      2. Silent: 1925-1945\n      3. Boomers: 1946-1964 \n      4. Generation X:  1965-1979\n      5. Millenials: 1980-1994\n      6. Generation Z: 1995-2012\n           \n \n\"\"\"\n\"\"\"\n# 4.Cleaning the data\n\"\"\"\nsuicides.shape \nsuicides.info()\n\"\"\"\nSo there are 27820 entries and 12 features. \nThe type of GDP\/year should be int, not string.\n\"\"\"\nsuicides[' gdp_for_year ($) ']=suicides[' gdp_for_year ($) '].str.replace(',','').astype(int) \n# Because I can't convert the string with the commas in it, I need to remove them and then converting the string.\n\nsuicides.head()\nsuicides.isnull().any() # Verifying if there are any null values.\nsuicides.isnull().sum() # Counting all the null entries, adding 1 tot the sum everytime it's true that the value is null.\n\"\"\"\nThere are way too many null values for HDI, and also it's not a very important feature for our future analysis. So we're gonna eliminate it.\n\"\"\"\ndel suicides['HDI for year']\nsuicides.columns # It was successfully deleted.\n\"\"\"\nHow many countries are studied in this dataset?\n\"\"\"\nlen(suicides.country.unique()) \n# 101 countries.\n\"\"\"\nI'm gonna change some names of columns for an easier work when I'm gonna use them.\n\"\"\"\nsuicides.rename(columns={'suicides\/100k pop':'suicides\/100k',' gdp_for_year ($) ':'gdp\/year','gdp_per_capita ($)':'gdp\/capita'},inplace=True)\n# We already know that the currency is $.\n\"\"\"\n# 5.Vizualising the data\n\"\"\"\nsuicides.drop('year',axis=1).describe()\n\"\"\"\n**Number of suicides per country **\n\"\"\"\nsuicides.groupby('country').suicides_no.sum().sort_values(ascending=False)\n# The country with the most suicides is Russia, followed by USA and Japan\n# The last 2 countries have 0 suicides, so we don't need them in our analysis about the number of suicides \nsuicides=suicides[(suicides.country!='Saint Kitts and Nevis') & (suicides.country!='Dominica')]\ntotal_suicides=pd.DataFrame(suicides.groupby('country').suicides_no.sum().sort_values(ascending=False))\n# I'm gonna save the results to a DataFrame so I can plot them\ntotal_suicides=total_suicides.reset_index()\n# I don't want countries as index\ntotal_suicides.head()\nplt.figure(figsize=(10,20))\nsns.barplot(y='country',x='suicides_no',data=total_suicides)\nplt.title('Number of suicides aprox. 1985-2016') # It's aprox because the years for each country aren't quite the same\nplt.ylabel('Countries')\nplt.xlabel('Number of suicides')\n\"\"\"\nI will sectionate the figure because the countries with a small number of suicides aren't visible.\n\"\"\"\nplt.figure(figsize=(10,20))\nsns.barplot(y=total_suicides[total_suicides.suicides_no<7000].country,\n            x=total_suicides[total_suicides.suicides_no<7000].suicides_no,data=total_suicides)\nplt.title('Number of suicides aprox. 1985-2016')\nplt.ylabel('Countries')\nplt.xlabel('Number of suicides')\n\n# I chosed the suicides_no < 7000 just by looking at the figure and trying multiple times another values,\n# finding this number appropiate.\n\"\"\"\n**The evolution of number of suicides globally**\n\"\"\"\nfrom bokeh.io import output_notebook, output_file, show\nfrom bokeh.plotting import figure\noutput_notebook()\n\nsuicides_globally=suicides.groupby('year').sum().suicides_no.values\nyears=suicides.year.sort_values(ascending=True).unique()\nyears\n\np1 = figure(plot_height=400, plot_width=900, title='Evolution of suicides over the world per year', tools='pan,box_zoom')\n\np1.line(x=years, y=suicides_globally, line_width=2, color='aquamarine')\np1.circle(x=years, y=suicides_globally, size=5, color='green')\nshow(p1)\n    \n\"\"\"\nWe observe that in 2016 the number of suicides is very low, so let's check the number of countries studied  this year.\n\"\"\"\nlen(suicides[suicides.year==2016].country.unique())\n#There are only 16 countries studied this year, so we don't need the value in our analysis.\nsuicides_globally=suicides[suicides.year!=2016].groupby('year').sum().suicides_no.values\nyears=suicides[suicides.year!=2016].year.sort_values(ascending=True).unique()\np1 = figure(plot_height=400, plot_width=900, title='Evolution of suicides over the world per year', tools='pan,box_zoom')\n\np1.line(x=years, y=suicides_globally, line_width=2, color='aquamarine')\np1.circle(x=years, y=suicides_globally, size=5, color='green')\nshow(p1)\n\"\"\"\nThere is a very big increasing of the number of suicides from the year 1988; the peak is in the 1998-2003, then there is a slow decreasing.\n\"\"\"\n\"\"\"\n**Number of suicides by gender**\n\"\"\"\nsuicides_gender=pd.DataFrame(suicides.groupby(['country','sex']).suicides_no.sum())\nsuicides_gender=suicides_gender.reset_index()\nsuicides_gender.head()\nplt.figure(figsize=(10,25))\nsns.barplot(x=suicides_gender[suicides_gender.suicides_no > 7000].suicides_no,\n            y=suicides_gender[suicides_gender.suicides_no > 7000].country,data=suicides_gender,hue='sex')\n\n\nplt.figure(figsize=(10,25))\nsns.barplot(x=suicides_gender[suicides_gender.suicides_no < 7000].suicides_no,\n            y=suicides_gender[suicides_gender.suicides_no < 7000].country,data=suicides_gender,hue='sex')\nsuicides.groupby('sex').suicides_no.sum()\nsuicides.groupby('sex').suicides_no.sum().male\/suicides.groupby('sex').suicides_no.sum().female * 100\n\"\"\"\nMen are 3 times more likely to committ suicide than women.\n\"\"\"\n\"\"\"\n**Evolution of number of suicides by gender globally**\n\"\"\"\ngenders=suicides.groupby(['year','sex']).sum().suicides_no\nfemale=genders.loc[:2015,'female'].values\nmale=genders.loc[:2015,'male'].values\n\n\np2=figure(plot_height=500,plot_width=900,title='Evolution of number of suicides by gender globally',tools='pan, box_zoom')\np2.circle(x=years,y=male,color='purple',size=5)\np2.line(x=years,y=male,color='purple',legend='male',line_width=2)\np2.circle(x=years,y=female,color='orange',size=5)\np2.line(x=years,y=female,color='orange',legend='female',line_width=2)\nshow(p2)\n\n\"\"\"\n**Number of suicides by age**\n\"\"\"\nsuicides.groupby('age').sum().suicides_no\nplt.figure(figsize=(10,5))\nsuicides_age=suicides.groupby('age').sum().suicides_no.values\nage=suicides.groupby('age').sum().reset_index().age.values\nsns.barplot(x=age,y=suicides_age)\nplt.title('Number of suicides by age')\n\"\"\"\nPeople with age between 35-54 year comitted suicide the most.\n\"\"\"\n\"\"\"\n**Evolution of number of suicides by age globally**\n\"\"\"\nsuicides_age=suicides.groupby(['year','age']).sum().suicides_no\nsuicides_age\nage15_24=suicides_age.loc[:2015,'15-24 years'].values\nage25_34=suicides_age.loc[:2015,'25-34 years'].values\nage35_54=suicides_age.loc[:2015,'35-54 years'].values\nage5_14=suicides_age.loc[:2015,'5-14 years'].values\nage_above75=suicides_age.loc[:2015,'75+ years'].values\np3=figure(plot_height=500,plot_width=1000,title='Evolution of number of suicides by age globally',tools='pan,box_zoom')\np3.circle(x=years,y=age35_54,color='darkorchid',size=5)\np3.circle(x=years,y=age25_34,color='turquoise',size=5)\np3.circle(x=years,y=age15_24,color='limegreen',size=5)\np3.circle(x=years,y=age5_14,color='tomato',size=5)\np3.circle(x=years,y=age_above75,color='blue',size=5)\np3.line(x=years,y=age35_54,color='darkorchid',line_width=2,legend='35-54 years')\np3.line(x=years,y=age25_34,color='turquoise',line_width=2,legend='25-34 years')\np3.line(x=years,y=age15_24,color='limegreen',line_width=2,legend='15-24 years')\np3.line(x=years,y=age5_14,color='tomato',line_width=2,legend='5-14 years')\np3.line(x=years,y=age_above75,color='blue',line_width=2,legend='75+ years')\nshow(p3)\n\"\"\"\n**Number of suicides by generation**\n\"\"\"\nsuicides.groupby('generation').sum().suicides_no\nplt.figure(figsize=(10,5))\ngenerations=suicides.groupby('generation').sum().suicides_no.reset_index().generation\nsuicides_gen=suicides.groupby('generation').sum().suicides_no.values\nsns.barplot(x=generations,y=suicides_gen)\nplt.xlabel('Generation')\nplt.title('Number of suicides by generation')\n\"\"\"\nThe Boomers comitted suicide the most.\n\"\"\"\n\"\"\"\nNow let's check the correlation between values.\n\"\"\"\nplt.figure(figsize=(10,8))\nsns.heatmap(suicides.corr(),annot=True,cmap=\"BuPu\")\n\"\"\"\nWe can also get some economic conclusions from our data.\nThe correlations that we are interested in are :\n1. gdp\/year - population: it's logical that if there are more people in a country GDP will be bigger; 0.71 it's a high positive correlation\n2. suicides_no - population: more people => more suicides\n3. gdp\/year - suicides: big salaries => more people => more suicides\n\"\"\"\nsns.pairplot(suicides.drop('year',axis=1),hue='sex',palette='bright')\n\"\"\"\n**Identifying countries by population and number of suicides in 2015 with Bokeh**\n\"\"\"\ngdp_year=suicides[suicides.year==2015]['gdp\/year'].drop_duplicates().values\npop=suicides[suicides.year==2015].groupby('country').sum().population.values\nno_suicides=suicides[suicides.year==2015].groupby('country').sum().suicides_no.values\nctry=suicides[suicides.year==2015].groupby('country').sum().reset_index().country.values\n\ns=pd.DataFrame()\ns['country']=ctry\ns['pop']=pop\ns['no_suicides']=no_suicides\ns['gdp_year']=gdp_year\n\ns.head()\nfrom bokeh.models import HoverTool\nfrom bokeh.models import ColumnDataSource\nsource=ColumnDataSource(s)\np4=figure(plot_height=500,plot_width=900,title='Identifying countries by population, number of suicides and GDP in 2015',tools='pan,box_zoom,wheel_zoom,reset')\np4.diamond(x='pop',y='no_suicides',size=10,color='green',source=source)\np4.add_tools(HoverTool(tooltips=[('population','@pop'),('number suicides','@no_suicides'),('country','@country'),('GDP','@gdp_year')]))\np4.xaxis.axis_label='Population'\np4.yaxis.axis_label='Number of suicides'\np4.xaxis.axis_label_standoff = 30 # Distance of the xaxis label from the xaxis \nshow(p4)","meta":"{'source': 'AI4Code', 'id': '02653d3ea99a20'}"}
{"id":"21327","text":"! ls ..\/input\/severstal-unet-se-resnext50\n\"\"\"\n### Install MLComp library(offline version):\n\"\"\"\n\"\"\"\nAs the competition does not allow commit with the kernel that uses internet connection, we use offline installation\n\"\"\"\n! python ..\/input\/mlcomp\/mlcomp\/setup.py\n\"\"\"\n### Import required libraries\n\"\"\"\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport cv2\nimport albumentations as A\nfrom tqdm import tqdm_notebook\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.jit import load\n\nfrom mlcomp.contrib.transform.albumentations import ChannelTranspose\nfrom mlcomp.contrib.dataset.classify import ImageDataset\nfrom mlcomp.contrib.transform.rle import rle2mask, mask2rle\nfrom mlcomp.contrib.transform.tta import TtaWrap\n\"\"\"\n### Load models\n\"\"\"\n\"\"\"\nCatalyst allows to trace models. That is an extremely useful features in Pytorch since 1.0 version: \n\nhttps:\/\/pytorch.org\/docs\/stable\/jit.html\n\nNow we can load models without re-defining them\n\"\"\"\neff_net = load('..\/input\/severstaleffnet\/traced_effnetb7_mixup_retrain.pth').cuda()\ncls = load('..\/input\/severstall-effnetb0-fimal-stage\/traced_effnetb0_averaged.pth').cuda()\nimport functools\nimport math\nimport re\nfrom collections import OrderedDict\n\nimport torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\nfrom torch.utils import model_zoo\nfrom torchvision.models.densenet import DenseNet\nfrom torchvision.models.resnet import BasicBlock, ResNet\n\n__all__ = ['SENet', 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152',\n           'se_resnext50_32x4d', 'se_resnext101_32x4d']\n\npretrained_settings = {\n    'senet154': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/senet154-c7b49a05.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n    'se_resnet50': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/se_resnet50-ce0d4300.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n    'se_resnet101': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/se_resnet101-7e38fcc6.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n    'se_resnet152': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/se_resnet152-d17c99b7.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n    'se_resnext50_32x4d': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/se_resnext50_32x4d-a260b3a4.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n    'se_resnext101_32x4d': {\n        'imagenet': {\n            'url': 'http:\/\/data.lip6.fr\/cadene\/pretrainedmodels\/se_resnext101_32x4d-3b2fe3d8.pth',\n            'input_space': 'RGB',\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],\n            'num_classes': 1000\n        }\n    },\n}\n\n\nclass SEModule(nn.Module):\n\n    def __init__(self, channels, reduction):\n        super(SEModule, self).__init__()\n        self.avg_pool = nn.AdaptiveAvgPool2d(1)\n        self.fc1 = nn.Conv2d(channels, channels \/\/ reduction, kernel_size=1,\n                             padding=0)\n        self.relu = nn.ReLU(inplace=True)\n        self.fc2 = nn.Conv2d(channels \/\/ reduction, channels, kernel_size=1,\n                             padding=0)\n        self.sigmoid = nn.Sigmoid()\n\n    def forward(self, x):\n        module_input = x\n        x = self.avg_pool(x)\n        x = self.fc1(x)\n        x = self.relu(x)\n        x = self.fc2(x)\n        x = self.sigmoid(x)\n        return module_input * x\n\n\nclass Bottleneck(nn.Module):\n    \"\"\"\n    Base class for bottlenecks that implements `forward()` method.\n    \"\"\"\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.relu(out)\n\n        out = self.conv3(out)\n        out = self.bn3(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out = self.se_module(out) + residual\n        out = self.relu(out)\n\n        return out\n\n\nclass SEBottleneck(Bottleneck):\n    \"\"\"\n    Bottleneck for SENet154.\n    \"\"\"\n    expansion = 4\n\n    def __init__(self, inplanes, planes, groups, reduction, stride=1,\n                 downsample=None):\n        super(SEBottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(inplanes, planes * 2, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes * 2)\n        self.conv2 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,\n                               stride=stride, padding=1, groups=groups,\n                               bias=False)\n        self.bn2 = nn.BatchNorm2d(planes * 4)\n        self.conv3 = nn.Conv2d(planes * 4, planes * 4, kernel_size=1,\n                               bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * 4)\n        self.relu = nn.ReLU(inplace=True)\n        self.se_module = SEModule(planes * 4, reduction=reduction)\n        self.downsample = downsample\n        self.stride = stride\n\n\nclass SEResNetBottleneck(Bottleneck):\n    \"\"\"\n    ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe\n    implementation and uses `stride=stride` in `conv1` and not in `conv2`\n    (the latter is used in the torchvision implementation of ResNet).\n    \"\"\"\n    expansion = 4\n\n    def __init__(self, inplanes, planes, groups, reduction, stride=1,\n                 downsample=None):\n        super(SEResNetBottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False,\n                               stride=stride)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1,\n                               groups=groups, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * 4)\n        self.relu = nn.ReLU(inplace=True)\n        self.se_module = SEModule(planes * 4, reduction=reduction)\n        self.downsample = downsample\n        self.stride = stride\n\n\nclass SEResNeXtBottleneck(Bottleneck):\n    \"\"\"\n    ResNeXt bottleneck type C with a Squeeze-and-Excitation module.\n    \"\"\"\n    expansion = 4\n\n    def __init__(self, inplanes, planes, groups, reduction, stride=1,\n                 downsample=None, base_width=4):\n        super(SEResNeXtBottleneck, self).__init__()\n        width = math.floor(planes * (base_width \/ 64)) * groups\n        self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False,\n                               stride=1)\n        self.bn1 = nn.BatchNorm2d(width)\n        self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,\n                               padding=1, groups=groups, bias=False)\n        self.bn2 = nn.BatchNorm2d(width)\n        self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * 4)\n        self.relu = nn.ReLU(inplace=True)\n        self.se_module = SEModule(planes * 4, reduction=reduction)\n        self.downsample = downsample\n        self.stride = stride\n\n\nclass SENet(nn.Module):\n\n    def __init__(self, block, layers, groups, reduction, dropout_p=0.2,\n                 inplanes=128, input_3x3=True, downsample_kernel_size=3,\n                 downsample_padding=1, num_classes=1000):\n        \"\"\"\n        Parameters\n        ----------\n        block (nn.Module): Bottleneck class.\n            - For SENet154: SEBottleneck\n            - For SE-ResNet models: SEResNetBottleneck\n            - For SE-ResNeXt models:  SEResNeXtBottleneck\n        layers (list of ints): Number of residual blocks for 4 layers of the\n            network (layer1...layer4).\n        groups (int): Number of groups for the 3x3 convolution in each\n            bottleneck block.\n            - For SENet154: 64\n            - For SE-ResNet models: 1\n            - For SE-ResNeXt models:  32\n        reduction (int): Reduction ratio for Squeeze-and-Excitation modules.\n            - For all models: 16\n        dropout_p (float or None): Drop probability for the Dropout layer.\n            If `None` the Dropout layer is not used.\n            - For SENet154: 0.2\n            - For SE-ResNet models: None\n            - For SE-ResNeXt models: None\n        inplanes (int):  Number of input channels for layer1.\n            - For SENet154: 128\n            - For SE-ResNet models: 64\n            - For SE-ResNeXt models: 64\n        input_3x3 (bool): If `True`, use three 3x3 convolutions instead of\n            a single 7x7 convolution in layer0.\n            - For SENet154: True\n            - For SE-ResNet models: False\n            - For SE-ResNeXt models: False\n        downsample_kernel_size (int): Kernel size for downsampling convolutions\n            in layer2, layer3 and layer4.\n            - For SENet154: 3\n            - For SE-ResNet models: 1\n            - For SE-ResNeXt models: 1\n        downsample_padding (int): Padding for downsampling convolutions in\n            layer2, layer3 and layer4.\n            - For SENet154: 1\n            - For SE-ResNet models: 0\n            - For SE-ResNeXt models: 0\n        num_classes (int): Number of outputs in `last_linear` layer.\n            - For all models: 1000\n        \"\"\"\n        super(SENet, self).__init__()\n        self.inplanes = inplanes\n        if input_3x3:\n            layer0_modules = [\n                ('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1,\n                                    bias=False)),\n                ('bn1', nn.BatchNorm2d(64)),\n                ('relu1', nn.ReLU(inplace=True)),\n                ('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1,\n                                    bias=False)),\n                ('bn2', nn.BatchNorm2d(64)),\n                ('relu2', nn.ReLU(inplace=True)),\n                ('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1,\n                                    bias=False)),\n                ('bn3', nn.BatchNorm2d(inplanes)),\n                ('relu3', nn.ReLU(inplace=True)),\n            ]\n        else:\n            layer0_modules = [\n                ('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2,\n                                    padding=3, bias=False)),\n                ('bn1', nn.BatchNorm2d(inplanes)),\n                ('relu1', nn.ReLU(inplace=True)),\n            ]\n        # To preserve compatibility with Caffe weights `ceil_mode=True`\n        # is used instead of `padding=1`.\n        layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2,\n                                                    ceil_mode=True)))\n        self.layer0 = nn.Sequential(OrderedDict(layer0_modules))\n        self.layer1 = self._make_layer(\n            block,\n            planes=64,\n            blocks=layers[0],\n            groups=groups,\n            reduction=reduction,\n            downsample_kernel_size=1,\n            downsample_padding=0\n        )\n        self.layer2 = self._make_layer(\n            block,\n            planes=128,\n            blocks=layers[1],\n            stride=2,\n            groups=groups,\n            reduction=reduction,\n            downsample_kernel_size=downsample_kernel_size,\n            downsample_padding=downsample_padding\n        )\n        self.layer3 = self._make_layer(\n            block,\n            planes=256,\n            blocks=layers[2],\n            stride=2,\n            groups=groups,\n            reduction=reduction,\n            downsample_kernel_size=downsample_kernel_size,\n            downsample_padding=downsample_padding\n        )\n        self.layer4 = self._make_layer(\n            block,\n            planes=512,\n            blocks=layers[3],\n            stride=2,\n            groups=groups,\n            reduction=reduction,\n            downsample_kernel_size=downsample_kernel_size,\n            downsample_padding=downsample_padding\n        )\n        self.avg_pool = nn.AvgPool2d(7, stride=1)\n        self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None\n        self.last_linear = nn.Linear(512 * block.expansion, num_classes)\n\n    def _make_layer(self, block, planes, blocks, groups, reduction, stride=1,\n                    downsample_kernel_size=1, downsample_padding=0):\n        downsample = None\n        if stride != 1 or self.inplanes != planes * block.expansion:\n            downsample = nn.Sequential(\n                nn.Conv2d(self.inplanes, planes * block.expansion,\n                          kernel_size=downsample_kernel_size, stride=stride,\n                          padding=downsample_padding, bias=False),\n                nn.BatchNorm2d(planes * block.expansion),\n            )\n\n        layers = []\n        layers.append(block(self.inplanes, planes, groups, reduction, stride,\n                            downsample))\n        self.inplanes = planes * block.expansion\n        for i in range(1, blocks):\n            layers.append(block(self.inplanes, planes, groups, reduction))\n\n        return nn.Sequential(*layers)\n\n    def features(self, x):\n        x = self.layer0(x)\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n        return x\n\n    def logits(self, x):\n        x = self.avg_pool(x)\n        if self.dropout is not None:\n            x = self.dropout(x)\n        x = x.view(x.size(0), -1)\n        x = self.last_linear(x)\n        return x\n\n    def forward(self, x):\n        x = self.features(x)\n        x = self.logits(x)\n        return x\n\n\ndef initialize_pretrained_model(model, num_classes, settings):\n    assert num_classes == settings['num_classes'], \\\n        'num_classes should be {}, but is {}'.format(\n            settings['num_classes'], num_classes)\n    model.load_state_dict(model_zoo.load_url(settings['url']))\n    model.input_space = settings['input_space']\n    model.input_size = settings['input_size']\n    model.input_range = settings['input_range']\n    model.mean = settings['mean']\n    model.std = settings['std']\n\n\ndef senet154(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEBottleneck, [3, 8, 36, 3], groups=64, reduction=16,\n                  dropout_p=0.2, num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['senet154'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\ndef se_resnet50(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEResNetBottleneck, [3, 4, 6, 3], groups=1, reduction=16,\n                  dropout_p=None, inplanes=64, input_3x3=False,\n                  downsample_kernel_size=1, downsample_padding=0,\n                  num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['se_resnet50'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\ndef se_resnet101(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEResNetBottleneck, [3, 4, 23, 3], groups=1, reduction=16,\n                  dropout_p=None, inplanes=64, input_3x3=False,\n                  downsample_kernel_size=1, downsample_padding=0,\n                  num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['se_resnet101'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\ndef se_resnet152(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEResNetBottleneck, [3, 8, 36, 3], groups=1, reduction=16,\n                  dropout_p=None, inplanes=64, input_3x3=False,\n                  downsample_kernel_size=1, downsample_padding=0,\n                  num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['se_resnet152'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\ndef se_resnext50_32x4d(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEResNeXtBottleneck, [3, 4, 6, 3], groups=32, reduction=16,\n                  dropout_p=None, inplanes=64, input_3x3=False,\n                  downsample_kernel_size=1, downsample_padding=0,\n                  num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['se_resnext50_32x4d'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\ndef se_resnext101_32x4d(num_classes=1000, pretrained='imagenet'):\n    model = SENet(SEResNeXtBottleneck, [3, 4, 23, 3], groups=32, reduction=16,\n                  dropout_p=None, inplanes=64, input_3x3=False,\n                  downsample_kernel_size=1, downsample_padding=0,\n                  num_classes=num_classes)\n    if pretrained is not None:\n        settings = pretrained_settings['se_resnext101_32x4d'][pretrained]\n        initialize_pretrained_model(model, num_classes, settings)\n    return model\n\n\nclass SENetEncoder(SENet):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.pretrained = False\n\n        del self.last_linear\n        del self.avg_pool\n\n    def forward(self, x):\n        for module in self.layer0[:-1]:\n            x = module(x)\n\n        x0 = x\n        x = self.layer0[-1](x)\n        x1 = self.layer1(x)\n        x2 = self.layer2(x1)\n        x3 = self.layer3(x2)\n        x4 = self.layer4(x3)\n\n        features = [x4, x3, x2, x1, x0]\n        return features\n\n    def load_state_dict(self, state_dict, **kwargs):\n        state_dict.pop('last_linear.bias')\n        state_dict.pop('last_linear.weight')\n        super().load_state_dict(state_dict, **kwargs)\n\n\nsenet_encoders = {\n    'senet154': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['senet154'],\n        'out_shapes': (2048, 1024, 512, 256, 128),\n        'params': {\n            'block': SEBottleneck,\n            'dropout_p': 0.2,\n            'groups': 64,\n            'layers': [3, 8, 36, 3],\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n\n    'se_resnet50': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['se_resnet50'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': SEResNetBottleneck,\n            'layers': [3, 4, 6, 3],\n            'downsample_kernel_size': 1,\n            'downsample_padding': 0,\n            'dropout_p': None,\n            'groups': 1,\n            'inplanes': 64,\n            'input_3x3': False,\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n\n    'se_resnet101': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['se_resnet101'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': SEResNetBottleneck,\n            'layers': [3, 4, 23, 3],\n            'downsample_kernel_size': 1,\n            'downsample_padding': 0,\n            'dropout_p': None,\n            'groups': 1,\n            'inplanes': 64,\n            'input_3x3': False,\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n\n    'se_resnet152': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['se_resnet152'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': SEResNetBottleneck,\n            'layers': [3, 8, 36, 3],\n            'downsample_kernel_size': 1,\n            'downsample_padding': 0,\n            'dropout_p': None,\n            'groups': 1,\n            'inplanes': 64,\n            'input_3x3': False,\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n\n    'se_resnext50_32x4d': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['se_resnext50_32x4d'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': SEResNeXtBottleneck,\n            'layers': [3, 4, 6, 3],\n            'downsample_kernel_size': 1,\n            'downsample_padding': 0,\n            'dropout_p': None,\n            'groups': 32,\n            'inplanes': 64,\n            'input_3x3': False,\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n\n    'se_resnext101_32x4d': {\n        'encoder': SENetEncoder,\n        #         'pretrained_settings': pretrained_settings['se_resnext101_32x4d'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': SEResNeXtBottleneck,\n            'layers': [3, 4, 23, 3],\n            'downsample_kernel_size': 1,\n            'downsample_padding': 0,\n            'dropout_p': None,\n            'groups': 32,\n            'inplanes': 64,\n            'input_3x3': False,\n            'num_classes': 1000,\n            'reduction': 16\n        },\n    },\n}\n\n\nclass ResNetEncoder(ResNet):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.pretrained = False\n        del self.fc\n\n    def forward(self, x):\n        x0 = self.conv1(x)\n        x0 = self.bn1(x0)\n        x0 = self.relu(x0)\n\n        x1 = self.maxpool(x0)\n        x1 = self.layer1(x1)\n\n        x2 = self.layer2(x1)\n        x3 = self.layer3(x2)\n        x4 = self.layer4(x3)\n\n        return [x4, x3, x2, x1, x0]\n\n    def load_state_dict(self, state_dict, **kwargs):\n        state_dict.pop('fc.bias')\n        state_dict.pop('fc.weight')\n        super().load_state_dict(state_dict, **kwargs)\n\n\nresnet_encoders = {\n    'resnet18': {\n        'encoder': ResNetEncoder,\n        #         'pretrained_settings': pretrained_settings['resnet18'],\n        'out_shapes': (512, 256, 128, 64, 64),\n        'params': {\n            'block': BasicBlock,\n            'layers': [2, 2, 2, 2],\n        },\n    },\n\n    'resnet34': {\n        'encoder': ResNetEncoder,\n        #         'pretrained_settings': pretrained_settings['resnet34'],\n        'out_shapes': (512, 256, 128, 64, 64),\n        'params': {\n            'block': BasicBlock,\n            'layers': [3, 4, 6, 3],\n        },\n    },\n\n    'resnet50': {\n        'encoder': ResNetEncoder,\n        #         'pretrained_settings': pretrained_settings['resnet50'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 4, 6, 3],\n        },\n    },\n\n    'resnet101': {\n        'encoder': ResNetEncoder,\n        #         'pretrained_settings': pretrained_settings['resnet101'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 4, 23, 3],\n        },\n    },\n\n    'resnet152': {\n        'encoder': ResNetEncoder,\n        #         'pretrained_settings': pretrained_settings['resnet152'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 8, 36, 3],\n        },\n    },\n}\n\n\nclass DenseNetEncoder(DenseNet):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.pretrained = False\n        del self.classifier\n        self.initialize()\n\n    @staticmethod\n    def _transition(x, transition_block):\n        for module in transition_block:\n            x = module(x)\n            if isinstance(module, nn.ReLU):\n                skip = x\n        return x, skip\n\n    def initialize(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n    def forward(self, x):\n\n        x = self.features.conv0(x)\n        x = self.features.norm0(x)\n        x = self.features.relu0(x)\n        x0 = x\n\n        x = self.features.pool0(x)\n        x = self.features.denseblock1(x)\n        x, x1 = self._transition(x, self.features.transition1)\n\n        x = self.features.denseblock2(x)\n        x, x2 = self._transition(x, self.features.transition2)\n\n        x = self.features.denseblock3(x)\n        x, x3 = self._transition(x, self.features.transition3)\n\n        x = self.features.denseblock4(x)\n        x4 = self.features.norm5(x)\n\n        features = [x4, x3, x2, x1, x0]\n        return features\n\n    def load_state_dict(self, state_dict):\n        pattern = re.compile(\n            r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n        for key in list(state_dict.keys()):\n            res = pattern.match(key)\n            if res:\n                new_key = res.group(1) + res.group(2)\n                state_dict[new_key] = state_dict[key]\n                del state_dict[key]\n\n        # remove linear\n        state_dict.pop('classifier.bias')\n        state_dict.pop('classifier.weight')\n\n        super().load_state_dict(state_dict)\n\n\ndensenet_encoders = {\n    'densenet121': {\n        'encoder': DenseNetEncoder,\n        #         'pretrained_settings': pretrained_settings['densenet121'],\n        'out_shapes': (1024, 1024, 512, 256, 64),\n        'params': {\n            'num_init_features': 64,\n            'growth_rate': 32,\n            'block_config': (6, 12, 24, 16),\n        }\n    },\n\n    'densenet169': {\n        'encoder': DenseNetEncoder,\n        #         'pretrained_settings': pretrained_settings['densenet169'],\n        'out_shapes': (1664, 1280, 512, 256, 64),\n        'params': {\n            'num_init_features': 64,\n            'growth_rate': 32,\n            'block_config': (6, 12, 32, 32),\n        }\n    },\n\n    'densenet201': {\n        'encoder': DenseNetEncoder,\n        #         'pretrained_settings': pretrained_settings['densenet201'],\n        'out_shapes': (1920, 1792, 512, 256, 64),\n        'params': {\n            'num_init_features': 64,\n            'growth_rate': 32,\n            'block_config': (6, 12, 48, 32),\n        }\n    },\n\n    'densenet161': {\n        'encoder': DenseNetEncoder,\n        #         'pretrained_settings': pretrained_settings['densenet161'],\n        'out_shapes': (2208, 2112, 768, 384, 96),\n        'params': {\n            'num_init_features': 96,\n            'growth_rate': 48,\n            'block_config': (6, 12, 36, 24),\n        }\n    },\n\n}\n\nencoders = {}\nencoders.update(resnet_encoders)\n# encoders.update(dpn_encoders)\n# encoders.update(vgg_encoders)\nencoders.update(senet_encoders)\nencoders.update(densenet_encoders)\n\n\ndef get_encoder(name, encoder_weights=None):\n    Encoder = encoders[name]['encoder']\n    encoder = Encoder(**encoders[name]['params'])\n    encoder.out_shapes = encoders[name]['out_shapes']\n\n    if encoder_weights is not None:\n        settings = encoders[name]['pretrained_settings'][encoder_weights]\n        encoder.load_state_dict(model_zoo.load_url(settings['url']))\n\n    return encoder\n\n\ndef get_encoder_names():\n    return list(encoders.keys())\n\n\ndef get_preprocessing_params(encoder_name, pretrained='imagenet'):\n    settings = encoders[encoder_name]['pretrained_settings']\n\n    if pretrained not in settings.keys():\n        raise ValueError('Avaliable pretrained options {}'.format(settings.keys()))\n\n    formatted_settings = {}\n    formatted_settings['input_space'] = settings[pretrained].get('input_space')\n    formatted_settings['input_range'] = settings[pretrained].get('input_range')\n    formatted_settings['mean'] = settings[pretrained].get('mean')\n    formatted_settings['std'] = settings[pretrained].get('std')\n    return formatted_settings\n\n\ndef get_preprocessing_fn(encoder_name, pretrained='imagenet'):\n    params = get_preprocessing_params(encoder_name, pretrained=pretrained)\n    return functools.partial(preprocess_input, **params)\n\n\nclass Model(nn.Module):\n\n    def __init__(self):\n        super().__init__()\n\n    def initialize(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n\nclass EncoderDecoder(Model):\n\n    def __init__(self, encoder, decoder, activation):\n        super().__init__()\n        self.encoder = encoder\n        self.decoder = decoder\n\n        if callable(activation) or activation is None:\n            self.activation = activation\n        elif activation == 'softmax':\n            self.activation = nn.Softmax(dim=1)\n        elif activation == 'sigmoid':\n            self.activation = nn.Sigmoid()\n        else:\n            raise ValueError('Activation should be \"sigmoid\"\/\"softmax\"\/callable\/None')\n\n    def forward(self, x):\n        \"\"\"Sequentially pass `x` trough model`s `encoder` and `decoder` (return logits!)\"\"\"\n        x = self.encoder(x)\n        x = self.decoder(x)\n        return x\n\n    def predict(self, x):\n        \"\"\"Inference method. Switch model to `eval` mode, call `.forward(x)`\n        and apply activation function (if activation is not `None`) with `torch.no_grad()`\n        Args:\n            x: 4D torch tensor with shape (batch_size, channels, height, width)\n        Return:\n            prediction: 4D torch tensor with shape (batch_size, classes, height, width)\n        \"\"\"\n        if self.training:\n            self.eval()\n\n        with torch.no_grad():\n            x = self.forward(x)\n            if self.activation:\n                x = self.activation(x)\n\n        return x\n\n\nclass DecoderBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, use_batchnorm=True, attention_type=None):\n        super().__init__()\n        if attention_type is None:\n            self.attention1 = nn.Identity()\n            self.attention2 = nn.Identity()\n        elif attention_type == 'scse':\n            self.attention1 = SCSEModule(in_channels)\n            self.attention2 = SCSEModule(out_channels)\n\n        self.block = nn.Sequential(\n            Conv2dReLU(in_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm),\n            Conv2dReLU(out_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm),\n        )\n\n    def forward(self, x):\n        x, skip = x\n        x = F.interpolate(x, scale_factor=2, mode='nearest')\n        if skip is not None:\n            x = torch.cat([x, skip], dim=1)\n            x = self.attention1(x)\n\n        x = self.block(x)\n        x = self.attention2(x)\n        return x\n\n\nclass CenterBlock(DecoderBlock):\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass UnetDecoder(Model):\n\n    def __init__(\n            self,\n            encoder_channels,\n            decoder_channels=(256, 128, 64, 32, 16),\n            final_channels=1,\n            use_batchnorm=True,\n            center=False,\n            attention_type=None\n    ):\n        super().__init__()\n\n        if center:\n            channels = encoder_channels[0]\n            self.center = CenterBlock(channels, channels, use_batchnorm=use_batchnorm)\n        else:\n            self.center = None\n\n        in_channels = self.compute_channels(encoder_channels, decoder_channels)\n        out_channels = decoder_channels\n\n        self.layer1 = DecoderBlock(in_channels[0], out_channels[0],\n                                   use_batchnorm=use_batchnorm, attention_type=attention_type)\n        self.layer2 = DecoderBlock(in_channels[1], out_channels[1],\n                                   use_batchnorm=use_batchnorm, attention_type=attention_type)\n        self.layer3 = DecoderBlock(in_channels[2], out_channels[2],\n                                   use_batchnorm=use_batchnorm, attention_type=attention_type)\n        self.layer4 = DecoderBlock(in_channels[3], out_channels[3],\n                                   use_batchnorm=use_batchnorm, attention_type=attention_type)\n        self.layer5 = DecoderBlock(in_channels[4], out_channels[4],\n                                   use_batchnorm=use_batchnorm, attention_type=attention_type)\n        self.final_conv = nn.Conv2d(out_channels[4], final_channels, kernel_size=(1, 1))\n\n        self.initialize()\n\n    def compute_channels(self, encoder_channels, decoder_channels):\n        channels = [\n            encoder_channels[0] + encoder_channels[1],\n            encoder_channels[2] + decoder_channels[0],\n            encoder_channels[3] + decoder_channels[1],\n            encoder_channels[4] + decoder_channels[2],\n            0 + decoder_channels[3],\n        ]\n        return channels\n\n    def forward(self, x):\n        encoder_head = x[0]\n        skips = x[1:]\n\n        if self.center:\n            encoder_head = self.center(encoder_head)\n\n        x = self.layer1([encoder_head, skips[0]])\n        x = self.layer2([x, skips[1]])\n        x = self.layer3([x, skips[2]])\n        x = self.layer4([x, skips[3]])\n        x = self.layer5([x, None])\n        x = self.final_conv(x)\n\n        return x\n\n\nclass Conv2dReLU(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, padding=0,\n                 stride=1, use_batchnorm=True, **batchnorm_params):\n        super().__init__()\n\n        layers = [\n            nn.Conv2d(in_channels, out_channels, kernel_size,\n                      stride=stride, padding=padding, bias=not (use_batchnorm)),\n            nn.ReLU(inplace=True),\n        ]\n\n        if use_batchnorm:\n            layers.insert(1, nn.BatchNorm2d(out_channels, **batchnorm_params))\n\n        self.block = nn.Sequential(*layers)\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass Unet(EncoderDecoder):\n    \"\"\"Unet_ is a fully convolution neural network for image semantic segmentation\n    Args:\n        encoder_name: name of classification model (without last dense layers) used as feature\n            extractor to build segmentation model.\n        encoder_weights: one of ``None`` (random initialization), ``imagenet`` (pre-training on ImageNet).\n        decoder_channels: list of numbers of ``Conv2D`` layer filters in decoder blocks\n        decoder_use_batchnorm: if ``True``, ``BatchNormalisation`` layer between ``Conv2D`` and ``Activation`` layers\n            is used.\n        classes: a number of classes for output (output shape - ``(batch, classes, h, w)``).\n        activation: activation function used in ``.predict(x)`` method for inference.\n            One of [``sigmoid``, ``softmax``, callable, None]\n        center: if ``True`` add ``Conv2dReLU`` block on encoder head (useful for VGG models)\n        attention_type: attention module used in decoder of the model\n            One of [``None``, ``scse``]\n    Returns:\n        ``torch.nn.Module``: **Unet**\n    .. _Unet:\n        https:\/\/arxiv.org\/pdf\/1505.04597\n    \"\"\"\n\n    def __init__(\n            self,\n            encoder_name='resnet34',\n            encoder_weights='imagenet',\n            decoder_use_batchnorm=True,\n            decoder_channels=(256, 128, 64, 32, 16),\n            classes=1,\n            activation='sigmoid',\n            center=False,  # usefull for VGG models\n            attention_type=None\n    ):\n        encoder = get_encoder(\n            encoder_name,\n            encoder_weights=encoder_weights\n        )\n\n        decoder = UnetDecoder(\n            encoder_channels=encoder.out_shapes,\n            decoder_channels=decoder_channels,\n            final_channels=classes,\n            use_batchnorm=decoder_use_batchnorm,\n            center=center,\n            attention_type=attention_type\n        )\n\n        super().__init__(encoder, decoder, activation)\n\n        self.name = 'u-{}'.format(encoder_name)\n# Loading model plain torch. You need the source code that defines them in order to load them\nunet2 = Unet('se_resnext50_32x4d', classes=4, encoder_weights=None, activation='softmax')\nckpt_path = '..\/input\/weight-segmentation\/se_resnext50_32x4d_Unet_checkpoint_185.pth'\ndevice = torch.device('cuda')\nunet2 = unet2.to(device)\nunet2.eval()\nprint() # So we don't see long info\n# state = torch.load(ckpt_path, map_location=lambda storage, loc: storage)\n# unet2.load_state_dict(state[\"state_dict\"])\n\"\"\"\n### Models' mean aggregator\n\"\"\"\nclass Model:\n    def __init__(self, models):\n        self.models = models\n    \n    def __call__(self, x):\n        res = []\n        x = x.cuda()\n        with torch.no_grad():\n            p, label = self.models[0](x)\n            res.append(p)\n            for m in self.models[1:]:\n                res.append(m(x)[0])\n        res = torch.stack(res)\n        return torch.mean(res, dim=0), label\n\nmodel = eff_net\n\"\"\"\n### Create TTA transforms, datasets, loaders\n\"\"\"\ndef create_transforms(additional):\n    res = list(additional)\n    # add necessary transformations\n    res.extend([\n        A.Normalize(\n            mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)\n        ),\n        ChannelTranspose()\n    ])\n    res = A.Compose(res)\n    return res\n\nimg_folder = '\/kaggle\/input\/severstal-steel-defect-detection\/test_images'\nbatch_size = 1\nnum_workers = 0\n\n# Different transforms for TTA wrapper\ntransforms = [\n    [],\n    [A.HorizontalFlip(p=1)],\n    [A.VerticalFlip(p=1)],\n]\n\ntransforms = [create_transforms(t) for t in transforms]\ndatasets = [TtaWrap(ImageDataset(img_folder=img_folder, transforms=t), tfms=t) for t in transforms]\nloaders = [DataLoader(d, num_workers=num_workers, batch_size=batch_size, shuffle=False) for d in datasets]\n\"\"\"\n### Loaders' mean aggregator\n\"\"\"\ndef tta_mean(preds):\n    preds = torch.stack(preds)\n    preds = torch.mean(preds, dim=0)\n    return preds.detach().cpu().numpy()\n\nthresholds = [0.6, 0.99, 0.6, 0.6] # [0.5, 0.5, 0.5, 0.5] | [0.55, 0.55, 0.55, 0.55] | [0.6, 0.99, 0.6, 0.6]\ncls_tresholds = [0.2, 0.25, 0.2, 0.1]\nmin_area = [600, 600, 1000, 2000] # instead of 900 -> 1000 in old version\n\nres = []\n# Iterate over all TTA loaders\ntotal = len(datasets[0])\/\/batch_size\nwith torch.no_grad():\n    for loaders_batch in tqdm_notebook(zip(*loaders), total=total):\n        preds = []\n        preds_aux = []\n        image_file = []\n        labels = []\n        for i, batch in enumerate(loaders_batch):\n            features = batch['features'].cuda()\n            pred_aux, label = cls(features)\n            pred_raw, _ = model(features)\n            labels.append(label)\n            p = torch.sigmoid(pred_raw)\n            p_aux = torch.sigmoid(pred_aux)\n            image_file = batch['image_file']\n\n            # inverse operations for TTA\n            p = datasets[i].inverse(p)\n            p_aux = datasets[i].inverse(p_aux)\n            preds.append(p)\n            preds_aux.append(p_aux)\n    \n        # TTA mean\n        preds = tta_mean(preds)\n        preds_aux = tta_mean(preds_aux)\n        labels = tta_mean(labels)\n        labels = labels[0] \n    \n        # Batch post processing\n        for p, p_aux, file in zip(preds, preds_aux, image_file):\n            file = os.path.basename(file)\n            # Image postprocessing\n            for i in range(4):\n                p_channel = np.zeros((256, 1600), dtype=np.uint8)\n                imageid_classid = file+'_'+str(i+1)\n                if labels[i] > cls_tresholds[i]:\n                    p_channel = p[i]\n                    p_channel = (p_channel>thresholds[i]).astype(np.uint8)\n                    if p_channel.sum() < min_area[i]:\n                        p_channel = np.zeros(p_channel.shape, dtype=p_channel.dtype)\n                    else:\n                        p_channel = (p[i] + p_aux[i]) \/ 2  # Take mean\n                        p_channel = (p_channel>thresholds[i]).astype(np.uint8)\n                        if p_channel.sum() < min_area[i]:\n                            p_channel = np.zeros(p_channel.shape, dtype=p_channel.dtype)\n\n                res.append({\n                    'ImageId_ClassId': imageid_classid,\n                    'EncodedPixels': mask2rle(p_channel)\n                })\n        \ndf = pd.DataFrame(res)\ndf.to_csv('submission.csv', index=False)\n\"\"\"\nSave predictions\n\"\"\"\ndf = pd.DataFrame(res)\ndf = df.fillna('')\ndf.to_csv('submission.csv', index=False)\n\"\"\"\nHistogram of predictions\n\"\"\"\ndf['Image'] = df['ImageId_ClassId'].map(lambda x: x.split('_')[0])\ndf['Class'] = df['ImageId_ClassId'].map(lambda x: x.split('_')[1])\ndf['empty'] = df['EncodedPixels'].map(lambda x: not x)\ndf[df['empty'] == False]['Class'].value_counts()\n\"\"\"\n### Visualization\n\"\"\"\n# %matplotlib inline\n\n# df = pd.read_csv('submission.csv')[:40]\n# df['Image'] = df['ImageId_ClassId'].map(lambda x: x.split('_')[0])\n# df['Class'] = df['ImageId_ClassId'].map(lambda x: x.split('_')[1])\n\n# for i, row in enumerate(df.itertuples()):\n# #     img_path = '\/kaggle\/input\/tmk-pics\/IMG_99642' + str(i \/\/ 4) + '_crop.jpg'\n#     print(row)\n#     img_name = row.ImageId_ClassId\n#     img_name = img_name.rsplit('_', 1)[0]\n#     img_path = '\/kaggle\/input\/tmk-pics\/' + img_name\n#     img = cv2.imread(img_path)\n#     mask = rle2mask(row.EncodedPixels, (1600, 256)) \\\n#         if isinstance(row.EncodedPixels, str) else np.zeros((256, 1600))\n# #     if mask.sum() == 0:\n# #         continue\n    \n#     fig, axes = plt.subplots(1, 2, figsize=(20, 60))\n    \n#     axes[0].imshow(img\/255)\n#     cv2.imwrite('.\/mask_' + img_name, mask*60)\n#     axes[1].imshow(mask*60)\n#     axes[0].set_title(row.Image)\n#     axes[1].set_title(row.Class)\n#     plt.show()","meta":"{'source': 'AI4Code', 'id': '2727e3d7feafa1'}"}
{"id":"26019","text":"\"\"\"\n# Anime Japan\n\"\"\"\n\"\"\"\n## Table of Contents\n\"\"\"\n\"\"\"\n- [Part1 Introduction](#introduction)\n\n- [Part2 2017 Top 3 Movie Markets Globally](#top3_movie_markets)\n\n- [Part3 Comparison Analysis of Top 3 Movie Markets](#comparison)\n   - [1. Preference on Movie Genres by Country](#preference_genres)\n       - [1) Box Office Contributions by Movie Genres to Top 20 Movies in Each Market](#box_office_contribution_genres)\n       - [2) Box Office Contributions by Key Movie Genres to Top 20 Movies in Each Market](#box_office_contribution_key_genres)\n       - [3) Proportion of Animations in Top 20 Movies](#proportion_elements)\n   - [2. Preference on Plots by Country](#preference_plots)\n       - [1) Preference of US\/Canada](#preference_us\/canada)\n       - [2) Preference of China](#preference_china)\n       - [3) Preference of Japan](#preference_japan)\n- [Appendix](#appendix)\n   - [Market Share - Full Version with All Countries Shown](#market_share_full)\n   - [Movie Elements Preference - Full Version with Legends](#preference_elements_full)\n\"\"\"\n\"\"\"\n<a id='introduction'><\/a>\n\"\"\"\n\"\"\"\n## Part 1 Introduction\n\"\"\"\n\"\"\"\nI love watching movies, and I know that people have different tastes in movies because of their differences on culture backgrounds, characteristics and value systems. But how about on an aggregated level such as country? What are the most appreciated movies by people in different countries? Are there any differences? \n\"\"\"\n\"\"\"\nMovie Box Mojo is a website that provides up-to-date movie box office data around the world. It also has movie ranking list on domestic box office of most of major movie markets. By scraping movie data from this website and merging to the movie ranking list, we can have most of the movie summary data to do the analysis, such as genre, gross and budget.But for some foreign movies, the movie summary data are not available or complete in Movie Box Mojo's data.\n\nSo I completed the missing data by integrating IMDB's movie summary, including missing genre information of some foreign movies and all the movie plots summary.\n\"\"\"\n\"\"\"\n<a id='top3_movie_markets'><\/a>\n\"\"\"\n\"\"\"\n##  Part 2   2017 Top 3 Movie Markets Globally\n\"\"\"\n\"\"\"\nFirst, let's choose our focus of this study based on the global ranking of movie box office.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport string\nfrom wordcloud import WordCloud, ImageColorGenerator\nfrom plotly import graph_objs as go, offline as offline, plotly as py\noffline.init_notebook_mode(connected=True)\n% matplotlib inline\n# read in market share data\ndf_market = pd.read_excel('..\/input\/World_movie_market_2017.xlsx', header=None, names=['country','box_office'])\n# calculate revenue of all the other countries besides the top 3\nrevenue_others = df_market.box_office[3:].sum()\ndf_market.iloc[21,1] = revenue_others\ndf_market = df_market.iloc[[0,1,2,21],:]\ncolors = ['rgba(0, 109, 204, 1)', 'rgba(204, 102, 0, 1)', 'rgba(119, 204, 0, 1)']\nfor i in range(0,19):\n    colors.append('rgba(230, 230, 230, 1)')\n\nfig = {\n  'data': [\n    {\n        'values': list(df_market['box_office'].values.flatten()),\n        'labels': list(df_market['country'].values.flatten()),\n        'marker': {'colors': colors},\n        'hoverinfo':'label+percent',\n        'textinfo':'label+percent',\n        'textposition':'outside',\n        'hole': .7,\n        'type': 'pie',\n        'sort':False,\n        'showlegend':False,\n        'textfont': \n            {\n                'color':'rgba(0, 0, 0, 1)', \n                'size':20\n            }\n    },\n    ],\n    'layout': {\n        'title':'2017 Global Movie Markets Share by Box Office',\n        'titlefont': {\n          'size': 30},\n        'margin':{\n            't':150,\n            'b':80\n        },\n        'annotations': [\n            {\n                'font': {\n                    'size': 35\n                },\n                'showarrow': False,\n                'text': 'Top 3',\n                'x': 0.5,\n                'y': 0.75\n            },\n            {\n                'font': {\n                    'size': 35\n                },\n                'showarrow': False,\n                'text': '>',\n                'x': 0.5,\n                'y': 0.55\n            },\n            {\n                'font': {\n                    'size': 50\n                },\n                'showarrow': False,\n                'text': '50%',\n                'x': 0.5,\n                'y': 0.40\n            },\n      ]\n    }\n}\n\n\noffline.iplot(fig)\n\"\"\"\n50%+ of global movie box office is from only 3 countries\/regions: US\/Canada, China and Japan. The movie box office distributes in a very concentrating way. So the following comparison analysis will only focus on the 3 most important movie markets.\n\"\"\"\n\"\"\"\n<a id='comparison'><\/a>\n\"\"\"\n\"\"\"\n## Part 3 Comparison Analysis of Top 3 Movie Markets\n\"\"\"\n\"\"\"\nThe rest of the analysis are based on top 20 movies in each market. The reason for picking only the top 20 movies is that those movies are a good representation of the country's preferences on movies. Those can be taken as the most beloved movies.\n\"\"\"\n\"\"\"\n<a id='preference_genres'><\/a>\n\"\"\"\n\"\"\"\n### 1. Preference on Movie Genres by Country\n\"\"\"\n\"\"\"\n<a id='box_office_contribution_genres'><\/a>\n\"\"\"\n\"\"\"\n### 1) Box Office Contributions by Movie Genres to Top 20 Movies in Each Market\n\"\"\"\n# read in data and clean\ndf_rank = pd.read_excel('..\/input\/movie_top3_top20.xlsx')\n\ndf_rank.replace('Adventrue','Adventure',inplace=True)\ndf_rank.replace('Comic-Based','Comic',inplace=True)\ndf_rank.replace('Music','Musical',inplace=True)\ndf_rank.replace('\\xa0War', 'War', inplace=True)\ndf_rank.country.replace('US', 'US\/Canada', inplace=True)\n# attract movie genre, country and domestic gross\ncountry_lis = ['Japan', 'China', 'US\/Canada']\ndf_country_genre = pd.DataFrame()\ndf_country_genre_ratio = pd.DataFrame()\n\nfor country in country_lis:\n    df_country = df_rank[df_rank.country==country].iloc[:,[1,2,7,8,9,10,11,12,13,14]].reset_index(drop=True)\n    country_top20_total = df_rank.loc[df_rank.country==country,'gross'].sum()\n    for i in range(2,9):\n        df_genre = df_country.iloc[:,[0,1,i]].reset_index(drop=True)\n        df_genre.columns = ['gross','country','genre']\n        df_country_genre = pd.concat([df_country_genre,df_genre], axis=0, sort=True).reset_index(drop=True).dropna(axis=0)\n    df_country_genre = df_country_genre.groupby(['country','genre'], as_index=False).sum()\n# Caculate ratio of genre gross by total gross\ndf_country_genre_total = df_country_genre[['country','gross']].groupby('country', as_index=False).sum() \ndf_country_genre_total.rename(columns={'gross':'total'}, inplace=True)\ndf_country_genre_ratio = df_country_genre.merge(df_country_genre_total, on='country',how='left')\ndf_country_genre_ratio['ratio'] = df_country_genre_ratio['gross']\/df_country_genre_ratio['total']\n# Restructure data \ngenre_lis = df_country_genre.genre.unique()\ngenre_ratio_lis = []\ndf_genre_ratio = pd.DataFrame()\n\nfor i in range(0,len(country_lis)):\n    genre_ratio_lis = []\n    country = country_lis[i]\n    genre_ratio_lis.append(country)\n    for j in range(0, len(genre_lis)):\n        if len(df_country_genre_ratio.loc[\n            (df_country_genre_ratio.country==country_lis[i])& (df_country_genre_ratio.genre==genre_lis[j])])>0:\n            ratio = df_country_genre_ratio.loc[\n                (df_country_genre_ratio.country==country_lis[i])& (df_country_genre_ratio.genre==genre_lis[j]), 'ratio'].values[0]\n        else:\n            ratio = 0\n        genre_ratio_lis.append(ratio)\n    genre_ratio_s = pd.Series(genre_ratio_lis, name=False)\n    df_genre_ratio = pd.concat((df_genre_ratio, genre_ratio_s), axis=1)\n    \n\ndf_genre_ratio.columns = df_genre_ratio.iloc[0,:]\ndf_genre_ratio = df_genre_ratio.drop(0).reset_index()\ndf_genre_ratio['genre'] = pd.Series(genre_lis)\ngenre_lis = df_country_genre.genre.unique()\ncolors = {'Action':'rgba(194, 0, 0, 1)', 'Adventure':'rgba(37, 0, 204, 1)', 'Animation':'rgba(204, 0, 139, 1)',\n              'Comedy':'rgba(48, 204, 0, 1)', 'Comic':'rgba(226, 145, 24, 1)', 'Drama':'rgba(204, 71, 0, 1)', \n              'Family':'rgba(116, 0, 204, 1)', 'Fantasy':'rgba(204, 146, 0, 1)', 'Sci-Fi':'rgba(63, 0, 158, 1)', \n             'Thriller':'rgba(147, 21, 21, 1)', 'Biography':'rgba(230, 230, 230, 1)', 'Crime':'rgba(220, 220, 220, 1)',\n             'History':'rgba(200, 200, 200, 1)', 'Horror':'rgba(180, 180, 180, 1)', 'Musical':'rgba(160, 160, 160, 1)', \n              'Mystery':'rgba(140, 140, 140, 1)', 'Romance':'rgba(120, 120, 120, 1)', 'War':'rgba(100, 100, 100, 1)',\n              'Sport':'rgba(80, 80, 80, 1)' }\n\n\ntrace = [go.Bar(x=list(df_genre_ratio.loc[df_genre_ratio.genre==genre,country_lis].values.flatten()), \n                y=country_lis, name=genre, orientation = 'h', marker=dict(color=colors[genre])) for genre in genre_lis]\ndata = trace\nlayout = go.Layout(title='Contributions of Movie Genres to Total Gross($) by Market', titlefont=dict(size=20),\n                   yaxis=dict(title='Market', showline=True, titlefont=dict(size=16), tickfont=dict(size=15)),\n                   xaxis=dict(title='Accumulated Ratio of Total Gross($)', showline=True, \n                              titlefont=dict(size=16), tickfont=dict(size=15),tickformat=\".0%\"), \n                   showlegend=False, barmode='stack', margin=dict(l=120))\n\n\nannotations = []\n\nfor country in country_lis:\n    for i in range(0, len(df_genre_ratio)):\n        ratio = df_genre_ratio[country][i]\n        genre = df_genre_ratio['genre'][i]\n        if ratio>0.08:\n            x = df_genre_ratio[country][0:i+1].sum()-0.048\n            text = df_genre_ratio['genre'][i]\n            annotations.append(dict(x=x, y=country, text=text,\n                                  font=dict(family='Calibri', size=15,\n                                  color='rgba(245, 246, 249, 1)'),\n                                  showarrow=False))\nlayout['annotations'] = annotations\nfig = go.Figure(data=data, layout=layout)\noffline.iplot(fig)\n\"\"\"\nUS, China and Japan have very different tastes on movie genres. Though they all show great interests in Action, Adventure and Fantasy, US prefers more Sci-Fi, China likes more Comedy and Thriller, while Japan loves Animation and Family elements. Japan is especially interesting in regarding to its preference on Animation.\n\"\"\"\n\"\"\"\n<a id='box_office_contribution_key_genres'><\/a>\n\"\"\"\n\"\"\"\n### 2) Box Office Contributions by Key Movie Genres to Top 20 Movies in Each Market\n\"\"\"\n# Restructure data to row as country, genre as column\nkey_genre_lis = ['Adventure','Animation','Fantasy']\ndf_country_ratio = pd.DataFrame()\n\nfor i in range(0,len(key_genre_lis)):\n    country_ratio_lis = []\n    genre = key_genre_lis[i]\n    country_ratio_lis.append(genre)\n    for j in range(0, len(country_lis)):\n        if len(df_country_genre_ratio.loc[\n            (df_country_genre_ratio.genre==key_genre_lis[i])& (df_country_genre_ratio.country==country_lis[j])])>0:\n            ratio = df_country_genre_ratio.loc[\n                (df_country_genre_ratio.genre==key_genre_lis[i])& (\n                    df_country_genre_ratio.country==country_lis[j]), 'ratio'].values[0]\n        else:\n            ratio = 0\n        country_ratio_lis.append(ratio)\n    country_ratio_s = pd.Series(country_ratio_lis, name=False)\n    df_country_ratio = pd.concat((df_country_ratio, country_ratio_s), axis=1)\n    \n\ndf_country_ratio.columns = df_country_ratio.iloc[0,:]\ndf_country_ratio = df_country_ratio.drop(0).reset_index()\ndf_country_ratio['country'] = pd.Series(country_lis)\ntrace = [go.Bar(x=list(df_country_ratio.loc[df_country_ratio.country==country,key_genre_lis].values.flatten()), \n                y=key_genre_lis, name=country, orientation = 'h') for country in country_lis]\ndata = trace\nlayout = go.Layout(title=\"Contributions of Key Genres to Totle Box Office Revenue by Market\",\n                   titlefont=dict(size=20),\n                   yaxis=dict(showline=True, tickfont=dict(size=20)),\n                   xaxis=dict(title='Percentage of Box Office Revenue($)', titlefont=dict(size=20),\n                              showline=False, tickfont=dict(size=20),tickformat=\".0%\"), \n                   showlegend=True,\n                   legend=dict(font=dict(size=20)), margin=dict(l=100))\n\n\nfig = go.Figure(data=data, layout=layout)\noffline.iplot(fig)\n\"\"\"\nWhen focusing on the top 3 high contributing movie elements in Japan, the special preference on Animation is very outstanding. The contribution of animation genres to gross in the other two countries are much smaller than in Japan, while Fantasy and Adventure seem to be popular in all countries. \n\"\"\"\n\"\"\"\n<a id='proportion_elements'><\/a>\n\"\"\"\n\"\"\"\n### 3)  Proportion of Animations in Top 20 Movies in the 3\n\"\"\"\ndf_rank['animation'] = np.where(df_rank.genre_1=='Animation', 1, \n                                np.where(df_rank.genre_2=='Animation', 1, \n                                         np.where(df_rank.genre_3=='Animation', 1, \n                                                  np.where(df_rank.genre_4=='Animation', 1, \n                                                           np.where(df_rank.genre_5=='Animation', 1, \n                                                                    np.where(df_rank.genre_6=='Animation', 1, \n                                                                             np.where(df_rank.genre_7=='Animation', 1,\n                                                                                      np.where(df_rank.genre_8=='Animation', 1, 0 ) )))))))\ndf_animation = df_rank[['title','country','animation']].groupby(['country','animation'], as_index=False).count()\ndf_animation.rename(columns={'title':'ani_proportion'}, inplace=True)\ndf_animation['ani_proportion'] = df_animation['ani_proportion']\/20\ndf_animation['non_ani_proportion'] = 1-df_animation.ani_proportion\ndf_animation = df_animation.drop('animation', axis=1)\ndf_animation = df_animation.iloc[[1,3,5],:].transpose()\ndf_animation.columns = df_animation.iloc[0,:]\ndf_animation.drop('country', axis=0, inplace=True)\nx = list(df_animation.loc[df_animation.index=='ani_proportion',country_lis].values.flatten())\ny = country_lis\n\ncolor_japan = 'rgba(204, 0, 139, 1)'\ncolor_others = 'rgba(140, 140, 140, 1)'\ntext_color_japan = 'rgba(204, 0, 0, 1)'\ntext_color_others = 'rgba(140, 140, 140, 1)'\n\ncolors  = [color_japan if y[i]=='Japan' else color_others for i in range(0,len(y))]\ntext_size = [30 if y[i]=='Japan' else 20 for i in range(0,len(y))]\ntext_color  = [text_color_japan if y[i]=='Japan' else text_color_others for i in range(0,len(y))]\n\n\ntrace = [go.Bar(x=x, y=y, orientation = 'h', text=[str(round((ratio)*100))+'%' for ratio in x], textposition='outside',\n                textfont=dict(size=text_size, color=text_color), marker=dict(color=colors))] \n\ndata = trace\nlayout = go.Layout(title='Year 2017 Percentage of Animation Movies of Top 20 movies among Top 3 Markets',\n                   font=dict(size=13),\n                   yaxis=dict(showline=True, tickfont=dict(size=15)),\n                   xaxis=dict(title='Percentage of Top 20 Movies', showline=False, \n                              titlefont=dict(size=15), ticks='',showticklabels=False, range=(0,0.5)),\n                   margin=dict(l=200)\n                  )\nfig = go.Figure(data=data, layout=layout)\noffline.iplot(fig)\n\"\"\"\n40% of Japan's top 20 movies in 2017 are animations! Japan has a very strong cartoon culture, and it seems that this culture has a real big influence on Japanese people's movie preferences.\n\"\"\"\n\"\"\"\n<a id='preference_plots'><\/a>\n\"\"\"\n\"\"\"\n### 2. Preference on Plots by Country\n\"\"\"\n\"\"\"\nBesides preferences on genre, I am also very curious on what types of plots are appreciated most by the 3 major markets. It can be a reflection of a country's culture and values. \n\"\"\"\n\"\"\"\n<a id='preference_us\/canada'><\/a>\n\"\"\"\n\"\"\"\n### 1) Preference of US\/Canada\n\"\"\"\n# replace punctuations \nreplace_punctuation = str.maketrans(string.punctuation, ' '*len(string.punctuation))\ndf_rank.plots_summary = df_rank.plots_summary.apply(lambda txt: txt.translate(replace_punctuation))\n\n# lower case\ndf_rank.plots_summary = df_rank.plots_summary.apply(lambda txt: txt.lower())\n# plots summary by country\nplots_summary_us = df_rank.loc[df_rank.country=='US\/Canada'].plots_summary.sum(axis=0)\nplots_summary_china = df_rank.loc[df_rank.country=='China'].plots_summary.sum(axis=0)\nplots_summary_japan = df_rank.loc[df_rank.country=='Japan'].plots_summary.sum(axis=0)\nplots_summary_uk = df_rank.loc[df_rank.country=='Britain'].plots_summary.sum(axis=0)\nplots_summary_india = df_rank.loc[df_rank.country=='India'].plots_summary.sum(axis=0)\nstop_words = [\"a\", \"about\", \"above\", \"above\", \"across\", \"after\", \"afterwards\", \n              \"again\", \"against\", \"all\", \"almost\", \"alone\", \"along\", \"already\", \n              \"also\",\"although\",\"always\",\"am\",\"among\", \"amongst\", \"amoungst\", \"amount\",  \n              \"an\", \"and\", \"another\", \"any\",\"anyhow\",\"anyone\",\"anything\",\"anyway\", \"anywhere\", \n              \"are\", \"around\", \"as\",  \"at\", \"back\",\"be\",\"became\", \"because\",\"become\",\"becomes\", \n              \"becoming\", \"been\", \"before\", \"beforehand\", \"behind\", \"being\", \"below\", \"beside\", \n              \"besides\", \"between\", \"beyond\", \"bill\", \"both\", \"bottom\",\"but\", \"by\", \"call\", \"can\", \n              \"cannot\", \"cant\", \"co\", \"con\", \"could\", \"couldnt\", \"cry\", \"de\", \"describe\", \"detail\", \n              \"do\", \"done\", \"down\", \"due\", \"during\", \"each\", \"eg\", \"eight\", \"either\", \"eleven\",\"else\", \n              \"elsewhere\", \"empty\", \"enough\", \"etc\", \"even\", \"ever\", \"every\", \"everyone\", \"everything\", \n              \"everywhere\", \"except\", \"few\", \"fifteen\", \"fify\", \"fill\", \"find\", \"fire\", \"first\", \"five\", \n              \"for\", \"former\", \"formerly\", \"forty\", \"found\", \"four\", \"from\", \"front\", \"full\", \"further\", \n              \"get\", \"give\", \"go\", \"had\", \"has\", \"hasnt\", \"have\", \"he\", \"hence\", \"her\", \"here\", \"hereafter\",\n              \"hereby\", \"herein\", \"hereupon\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"however\", \n              \"hundred\", \"ie\", \"if\", \"in\", \"inc\", \"indeed\", \"interest\", \"into\", \"is\", \"it\", \"its\", \"itself\", \n              \"keep\", \"last\", \"latter\", \"latterly\", \"least\", \"less\", \"ltd\", \"made\", \"many\", \"may\", \"me\", \"meanwhile\",\n              \"might\", \"mill\", \"mine\", \"more\", \"moreover\", \"most\", \"mostly\", \"move\", \"much\", \"must\", \"my\", \"myself\", \n              \"name\", \"namely\", \"neither\", \"never\", \"nevertheless\", \"next\", \"nine\", \"no\", \"nobody\", \"none\", \"noone\",\n              \"nor\", \"not\", \"nothing\", \"now\", \"nowhere\", \"of\", \"off\", \"often\", \"on\", \"once\", \"one\", \"only\", \"onto\", \n              \"or\", \"other\", \"others\", \"otherwise\", \"our\", \"ours\", \"ourselves\", \"out\", \"over\", \"own\",\"part\", \"per\", \n              \"perhaps\", \"please\", \"put\", \"rather\", \"re\", \"same\", \"see\", \"seem\", \"seemed\", \"seeming\", \"seems\", \n              \"serious\", \"several\", \"she\", \"should\", \"show\", \"side\", \"since\", \"sincere\", \"six\", \"sixty\", \"so\", \n              \"some\", \"somehow\", \"someone\", \"something\", \"sometime\", \"sometimes\", \"somewhere\", \"still\", \"such\", \n              \"system\", \"take\", \"ten\", \"than\", \"that\", \"the\", \"their\", \"them\", \"themselves\", \"then\", \"thence\", \n              \"there\", \"thereafter\", \"thereby\", \"therefore\", \"therein\", \"thereupon\", \"these\", \"they\", \"thickv\", \n              \"third\", \"this\", \"those\", \"though\", \"three\", \"through\", \"throughout\", \"thru\", \"thus\", \"to\", \n              \"together\", \"too\", \"top\", \"toward\", \"towards\", \"twelve\", \"twenty\", \"two\", \"un\", \"under\", \"until\", \"up\", \n              \"upon\", \"us\", \"very\", \"via\", \"was\", \"we\", \"well\", \"were\", \"what\", \"whatever\", \"when\", \"whence\", \n              \"whenever\", \"where\", \"whereafter\", \"whereas\", \"whereby\", \"wherein\", \"whereupon\", \"wherever\", \"whether\",\n              \"which\", \"while\", \"whither\", \"who\", \"whoever\", \"whole\", \"whom\", \"whose\", \"why\", \"will\", \"with\",\n              \"within\", \"without\", \"would\", \"yet\", \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"the\",'yes',\n              'character','reference','feng']\nwc = WordCloud(background_color=\"white\", max_words=6,\n               stopwords=stop_words, width=1280, height=628)\nwc.generate(plots_summary_us)\nplt.figure(figsize=(10,10))\nplt.imshow(wc, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\nWorld, new, old, power, game, discover, man are popular plots elements in US\/Canada. The moviegoers there show a great care about the big matters. Also their taste seems to be very masculine, all about power and game. \n\"\"\"\n\"\"\"\n<a id='preference_china'><\/a>\n\"\"\"\n\"\"\"\n### 2) Preference of China\n\"\"\"\nwc.generate(plots_summary_china)\nplt.figure(figsize=(10,10))\nplt.imshow(wc, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\nFinds, team, deadly, China, army are among plot elements that pop up in the word cloud of China's top 20 movies' plots summaries. China's moviegoers don't care about world as much as US. But they show more interests on their own country. It seems that they are more teased by tense stories.\n\"\"\"\n\"\"\"\n<a id='preference_japan'><\/a>\n\"\"\"\n\"\"\"\n### 3) Preference of Japan\n\"\"\"\nwc.generate(plots_summary_japan)\nplt.figure(figsize=(10,10))\nplt.imshow(wc, interpolation=\"bilinear\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\nMysterious, sakura, girl, friend are outstandingly popular movie plots in Japan, which is very different from US\/Canada and China. It seems that Japanese people not only prefer animation world more to real world they also show a preference on plots about youth, girl, flowers, friends, which are much softer than the other two countries' tastes. Their taste is quite feminine, a total opposite to US\/Canada. No wonder Japan is the origin of 'Lolita Fashion'.\n\"\"\"\n\"\"\"\n<a id='appendix'><\/a>\n\"\"\"\n\"\"\"\n## Appendix\n\"\"\"\n\"\"\"\n<a id='market_share_full'><\/a>\n\"\"\"\n\"\"\"\n### Market Share - Full Version with All Countries Shown\n\"\"\"\ndf_market_full = pd.read_excel('..\/input\/World_movie_market_2017.xlsx', header=None, names=['country','box_office'])\nfig = {\n  \"data\": [\n    {\n      \"values\": list(df_market_full['box_office'].values.flatten()),\n      \"labels\": list(df_market_full['country'].values.flatten()),\n      \"hoverinfo\":\"label+percent\",\n        'textinfo':'label+percent',\n        'textposition':'outside',\n      \"hole\": .7,\n      \"type\": \"pie\",\n        'sort':False,\n        'showlegend':True\n    },\n    ],\n  \"layout\": {\n        \"title\":\"2017 Global Movie Markets Share\",\n\n    }\n}\n    \n\noffline.iplot(fig)\n\"\"\"\n<a id='preference_elements_full'><\/a>\n\"\"\"\n\"\"\"\n### Movie Elements Preference - Full Version with Legends\n\"\"\"\ntrace = [go.Bar(x=list(df_genre_ratio.loc[df_genre_ratio.genre==genre,country_lis].values.flatten()), \n                y=country_lis, name=genre, orientation = 'h') for genre in genre_lis]\ndata = trace\nlayout = go.Layout(title='Preference on Movie Genre by Market', font=dict(size=17),\n                   yaxis=dict(title='Market', showline=True, titlefont=dict(size=16), tickfont=dict(size=15)),\n                   xaxis=dict(title='Accumulated Ratio of Total Gross($)', showline=True, \n                              titlefont=dict(size=16), tickfont=dict(size=15), tickformat=\".0%\"), \n                   legend=dict(font=dict(size=10)),barmode='stack', margin=dict(l=120))\n\n\nannotations = []\n\nfor country in country_lis:\n    for i in range(0, len(df_genre_ratio)):\n        ratio = df_genre_ratio[country][i]\n        genre = df_genre_ratio['genre'][i]\n        if ratio>0.07:\n            x = df_genre_ratio[country][0:i+1].sum()-0.05\n            text = df_genre_ratio['genre'][i]\n            annotations.append(dict(x=x, y=country, text=text,\n                                  font=dict(family='Calibri', size=17,\n                                  color='rgba(245, 246, 249, 1)'),\n                                  showarrow=False))\nlayout['annotations'] = annotations\nfig = go.Figure(data=data, layout=layout)\noffline.iplot(fig)","meta":"{'source': 'AI4Code', 'id': '2feb5ed49afcde'}"}
{"id":"20492","text":"\"\"\"\nIn this study, we are training a logistic regression classifier on a set of ham and spam emails to flag spam emails. The cross-validation method is implemented to obtain a better evaluation of the model performance. In the first step, the data are fetched.\n\"\"\"\nimport os\nHAM_DIR = \"..\/input\/ham-and-spam-dataset\/hamnspam\/ham\/\"\nSPAM_DIR = \"..\/input\/ham-and-spam-dataset\/hamnspam\/spam\/\"\nham_filenames = [name for name in sorted(os.listdir(HAM_DIR)) if len(name) > 20]\nspam_filenames = [name for name in sorted(os.listdir(SPAM_DIR)) if len(name) > 20]\nprint('Number of ham files:' , len(ham_filenames) )\nprint('Number of spam files:' , len(spam_filenames) )\n\"\"\"\nThe email objects are collected via email parser library.\n\"\"\"\nimport email\nimport email.policy\n\ndef load_email( is_spam, filename ):\n    directory = SPAM_DIR if is_spam else HAM_DIR\n    with open(os.path.join( directory, filename ), \"rb\") as f:\n        return email.parser.BytesParser(policy=email.policy.default).parse(f)\n\nham_emails = [load_email(is_spam=False, filename=name) for name in ham_filenames]\nspam_emails = [load_email(is_spam=True, filename=name) for name in spam_filenames]\n\"\"\"\nThe main dataset is split into training and test datasets.\n\"\"\"\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nX = np.array(ham_emails + spam_emails)\ny = np.array([0] * len(ham_emails) + [1] * len(spam_emails))\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\"\"\"\nUsing the following functions, the emails' content are preprocesssed, making certain that the resulting texts do not contain html codes, upper case letters, digit numbers, or punctuations.\n\"\"\"\nimport re\nfrom html import unescape\n\ndef html_to_plain_text(html):\n    text = re.sub('<head.*?>.*?<\/head>', '', html, flags=re.M | re.S | re.I)\n    text = re.sub('<a\\s.*?>', ' HYPERLINK ', text, flags=re.M | re.S | re.I)\n    text = re.sub('<.*?>', '', text, flags=re.M | re.S)\n    text = re.sub(r'(\\s*\\n)+', '\\n', text, flags=re.M | re.S)\n    return unescape(text)\n\ndef email_to_text(email):\n    html = None\n    for part in email.walk():\n        ctype = part.get_content_type()\n        if not ctype in (\"text\/plain\", \"text\/html\"):\n            continue\n        try:\n            content = part.get_content()\n        except: # in case of encoding issues\n            content = str(part.get_payload())\n        if ctype == \"text\/plain\":\n            return content\n        else:\n            html = content\n    if html:\n        return html_to_plain_text(html)\nimport nltk\nstemmer = nltk.PorterStemmer()\n\nfrom collections import Counter\n\nimport re\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass EmailToWordCounterTransformer(BaseEstimator, TransformerMixin):\n    def __init__(self, strip_headers=True, lower_case=True, remove_punctuation=True,\n                 replace_urls=True, replace_numbers=True, stemming=True):\n        self.strip_headers = strip_headers\n        self.lower_case = lower_case\n        self.remove_punctuation = remove_punctuation\n        self.replace_urls = replace_urls\n        self.replace_numbers = replace_numbers\n        self.stemming = stemming\n    def fit(self, X, y=None):\n        return self\n    def transform(self, X, y=None):\n        X_transformed = []\n        for email in X:\n            text = email_to_text(email) or \"\"\n            if self.lower_case:\n                text = text.lower()\n            if self.replace_urls:\n                urls = list(set(re.findall( r'(https?:\/\/\\S+)' , text )))\n                urls.sort(key=lambda url: len(url), reverse=True)\n                for url in urls:\n                    text = text.replace(url, \" URL \")\n            if self.replace_numbers:\n                text = re.sub(r'\\d+(?:\\.\\d*(?:[eE]\\d+))?', 'NUMBER', text)\n            if self.remove_punctuation:\n                text = re.sub(r'\\W+', ' ', text, flags=re.M)\n            word_counts = Counter(text.split())\n            if self.stemming and stemmer is not None:\n                stemmed_word_counts = Counter()\n                for word, count in word_counts.items():\n                    stemmed_word = stemmer.stem(word)\n                    stemmed_word_counts[stemmed_word] += count\n                word_counts = stemmed_word_counts\n            X_transformed.append(word_counts)\n        return np.array(X_transformed)\n\"\"\"\nThe following functions computes the most frequent vocabularies in the body of ham emails and determines their frequency in each email. Transformed emails will be vectors of numbers.\n\"\"\"\nfrom scipy.sparse import csr_matrix\n\nclass WordCounterToVectorTransformer(BaseEstimator, TransformerMixin):\n    def __init__(self, vocabulary_size=1000):\n        self.vocabulary_size = vocabulary_size\n    def fit(self, X, y=None):\n        total_count = Counter()\n        for word_count in X:\n            for word, count in word_count.items():\n                total_count[word] += min(count, 10)\n        most_common = total_count.most_common()[:self.vocabulary_size]\n        self.most_common_ = most_common\n        self.vocabulary_ = {word: index + 1 for index, (word, count) in enumerate(most_common)}\n        return self\n    def transform(self, X, y=None):\n        rows = []\n        cols = []\n        data = []\n        for row, word_count in enumerate(X):\n            for word, count in word_count.items():\n                rows.append(row)\n                cols.append(self.vocabulary_.get(word, 0))\n                data.append(count)\n        solu = csr_matrix((data, (rows, cols)), shape=(len(X), self.vocabulary_size + 1))\n        return solu\n\"\"\"\nAfter defining the preprocessing functions, the data are run through the following data transformation steps.\n\"\"\"\nfrom sklearn.pipeline import Pipeline\n\npreprocess_pipeline = Pipeline([\n    (\"email_to_wordcount\", EmailToWordCounterTransformer()),\n    (\"wordcount_to_vector\", WordCounterToVectorTransformer()),\n])\n\nX_train_transformed = preprocess_pipeline.fit_transform(X_train)\n\"\"\"\nThe transformed emails are fed to a logistic regression classifier. The data are trained using *k*-folds cross-validation technique.\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_score\n\nlog_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\nscore = cross_val_score(log_clf, X_train_transformed, y_train, cv=3, verbose=3)\nprint('\\nScores for all folds: ', score )\nprint('\\nAverage Score: ', score.mean() )\nprint('\\nStandard deviation of Scores: ', score.std() )\n\"\"\"\nThe transformed test dataset is now used to make new predictions. Precision, recall, thresholds, and scores will be computed accordingly.\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_predict\n\ny_scores = cross_val_predict(log_clf, X_train_transformed, y_train, cv=3, method=\"decision_function\")\n\nfrom sklearn.metrics import precision_recall_curve\nprecisions, recalls, thresholds = precision_recall_curve(y_train, y_scores)\n\"\"\"\nThe precision-recall vs. threshold and the precision-recall plots are presented respectively.\n\"\"\"\nimport matplotlib.pyplot as plt\ndef plot_precision_recall_vs_threshold(precisions, recalls, thresholds):\n    plt.plot(thresholds, precisions[:-1], \"b--\", label=\"Precision\", linewidth=2)\n    plt.plot(thresholds, recalls[:-1], \"g-\", label=\"Recall\", linewidth=2)\n    plt.xlabel(\"Threshold\", fontsize=16)\n    plt.legend(loc=\"upper left\", fontsize=16)\n    plt.ylim([0, 1])\n\nplt.figure(figsize=(8, 4))\nplot_precision_recall_vs_threshold(precisions, recalls, thresholds)\nplt.show()\ndef plot_precision_vs_recall(precisions, recalls):\n    plt.plot(recalls, precisions, \"b-\", linewidth=2)\n    plt.xlabel(\"Recall\", fontsize=16)\n    plt.ylabel(\"Precision\", fontsize=16)\n    plt.axis([0, 1, 0, 1])\n\nplt.figure(figsize=(8, 6))\nplot_precision_vs_recall(precisions, recalls)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '25908bdf5a66f0'}"}
{"id":"3402","text":"\"\"\"\n# Chapter 4: Comments and Documentation\n\"\"\"\n\"\"\"\n## Single line, inline and multiline comments\n\"\"\"\n\"\"\"\nComments are used to explain code when the basic code itself isn't clear.\nPython ignores comments, and so will not execute code in there, or raise syntax errors for plain English sentences.\n\"\"\"\n\"\"\"\n### Single line comment:\n\"\"\"\n\"\"\"\nSingle-line comments begin with the hash character (#) and are terminated by the end of line.\n\"\"\"\n#This is a single line comment in Python\n\"\"\"\n### Inline comment:\n\"\"\"\nprint(\"Hello World\") # This line prints \"Hello World\"\n\"\"\"\n### multiple lines comments \n\"\"\"\n\"\"\"\nComments spanning multiple lines have \"\"\" or ''' on either end. This is the same as a multiline string, but\nthey can be used as comments:\n\"\"\"\n\"\"\"\nThis type of comment spans multiple lines.\nThese are mostly used for documentation of functions, classes and modules.\n\"\"\"\n\"\"\"\n## Programmatically accessing docstrings\n\"\"\"\n\"\"\"\nDocstrings are - unlike regular comments - stored as an attribute of the function they document, meaning that you\ncan access them programmatically.\n\"\"\"\ndef func():\n    \"\"\"This is a function that does nothing at all\"\"\"\n    return\n\nprint(func.__doc__)\n\"\"\"\n## Write documentation using docstrings\n\"\"\"\n\"\"\"\nA docstring is a multi-line comment used to document modules, classes, functions and methods. It has to be the\nfirst statement of the component it describes.\n\"\"\"\ndef hello(name):\n    \"\"\"Greet someone.\n    Print a greeting (\"Hello\") for the person with the given name.\n    \"\"\"\n    print(\"Hello \"+name)\nclass Greeter:\n    \"\"\"An object used to greet people.\n    It contains multiple greeting functions for several languages\n    and times of the day.\n    \"\"\"\nhelp(hello)","meta":"{'source': 'AI4Code', 'id': '06663ad8fb127e'}"}
{"id":"33062","text":"\"\"\"\n#What is the ACE2 receptor, how is it connected to coronavirus and why might it be key to treating COVID-19?\nAuthors: Krishna Sriram: Postdoctoral Fellow, University of California San Diego Paul Insel: Professor of Pharmacology and Medicine, University of California San Diego Rohit Loomba: Professor of Medicine, University of California San Diego\n\nIn the search for treatments for COVID-19, many researchers are focusing their attention on a specific protein that allows the virus to infect human cells. Called the angiotensin-converting enzyme 2, or ACE2 \u201creceptor,\u201d the protein provides the entry point for the coronavirus to hook into and infect a wide range of human cells.\n\nACE2 is a protein on the surface of many cell types. It is an enzyme that generates small proteins \u2013 by cutting up the larger protein angiotensinogen \u2013 that then go on to regulate functions in the cell.\n\nUsing the spike-like protein on its surface, the SARS-CoV-2 virus binds to ACE2 \u2013 like a key being inserted into a lock \u2013 prior to entry and infection of cells. Hence, ACE2 acts as a cellular doorway \u2013 a receptor \u2013 for the virus that causes COVID-19. https:\/\/theconversation.com\/what-is-the-ace2-receptor-how-is-it-connected-to-coronavirus-and-why-might-it-be-key-to-treating-covid-19-the-experts-explain-136928\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRoVtDbEHRZT87BQEE1ZOFMtTFjzPy9FM2flAXK616QtzxSUqHj&usqp=CAU',width=400,height=400)\n\"\"\"\nyoutube.com\n\"\"\"\n# 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)\nimport json\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.offline as py\nimport plotly.graph_objs as go\nimport plotly.offline as py\nimport plotly.express as px\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\n\"\"\"\nWhen the SARS-CoV-2 virus binds to ACE2, it prevents ACE2 from performing its normal function to regulate ANG II signaling. Thus, ACE2 action is \u201cinhibited,\u201d removing the brakes from ANG II signaling and making more ANG II available to injure tissues. This \u201cdecreased braking\u201d likely contributes to injury, especially to the lungs and heart, in COVID-19 patients.\n\nACE2 is present in all people but the quantity can vary among individuals and in different tissues and cells. Some evidence suggests that ACE2 may be higher in patients with hypertension, diabetes and coronary heart disease.\n\nA lack of ACE2 is associated with severe tissue injury in the heart, lungs and other tissue types.\n\nThe SARS-CoV-2 virus requires ACE2 to infect cells but the precise relationship between ACE2 levels, viral infectivity and severity of infection are not well understood.https:\/\/theconversation.com\/what-is-the-ace2-receptor-how-is-it-connected-to-coronavirus-and-why-might-it-be-key-to-treating-covid-19-the-experts-explain-136928\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcSzlOglfPd6vMn2Na45hnvsZENqhAnB7bHxtbsB4OoHToycMpcQ&usqp=CAU',width=400,height=400)\n\"\"\"\ncebm.net\n\"\"\"\ndf = pd.read_csv('..\/input\/trec-covid-information-retrieval\/topics-rnd3.csv', encoding='ISO-8859-2')\ndf.head()\n\"\"\"\n#Codes from Mario Filho https:\/\/www.kaggle.com\/mariofilho\/live26-https-youtu-be-zseefujo0zq\n\"\"\"\nfig,ax = plt.subplots(1,1, figsize=(8,8))\ndegree = df.groupby(['topic-id', 'query']).size().unstack()#.fillna(0)\ndegree = degree.div(degree.sum(axis=1), axis=0)\nsns.heatmap(degree, cmap='viridis')\n\"\"\"\nWhen the amount of ACE2 is reduced because the virus is occupying the receptor, individuals may be more susceptible to severe illness from COVID-19. That is because enough ACE2 is available to facilitate viral entry but the decrease in available ACE2 contributes to more ANG II-mediated injury. In particular, reducing ACE2 will increase susceptibility to inflammation, cell death and organ failure, especially in the heart and the lung.\n\nThe lungs are the primary site of injury by SARS-CoV-2 infection, which causes COVID-19. The virus reaches the lungs after entry in the nose or mouth.\n\nThe virus also impacts other tissues that express ACE2, including the heart, where damage and inflammation (myocarditis) can occur. The kidneys, liver and digestive tract can also be injured. Blood vessels may also be a site for damage.\n\nAbnormally high ANG II activity can be a key factor that determines severity of damage in patients with COVID-19. https:\/\/theconversation.com\/what-is-the-ace2-receptor-how-is-it-connected-to-coronavirus-and-why-might-it-be-key-to-treating-covid-19-the-experts-explain-136928\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRCF3mA9DUiwQetDt7XHTFivmdly1woDMLsNYzgjUfGGIcAcK0V&usqp=CAU',width=400,height=400)\n\"\"\"\nepistemonikos.cl\n\"\"\"\nfrom category_encoders import OneHotEncoder\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler\n\ncols_selected = ['query']\nohe = OneHotEncoder(cols=cols_selected, use_cat_names=True)\ndf_t = ohe.fit_transform(df[cols_selected+['topic-id']])\n\n#scaler = MaxAbsScaler()\nX = df_t.iloc[:,:-1]\ny = df_t.iloc[:, -1].fillna(df_t.iloc[:, -1].mean()) \/ df_t.iloc[:, -1].max()\n\nmdl = Ridge(alpha=0.1)\nmdl.fit(X,y)\n\npd.Series(mdl.coef_, index=X.columns).sort_values().head(10).plot.barh()\n\"\"\"\nAngiotensin converting enzyme (ACE, aka ACE1) is another protein, also found in tissues such as the lung and heart, where ACE2 is present. Drugs that inhibit the actions of ACE1 are called ACE inhibitors.\n\nThese drugs block the actions of ACE1 but not ACE2. ACE1 drives the production of ANG II. In effect, ACE1 and ACE2 have a \u201cyin-yang\u201d relationship; ACE1 increases the amount of ANG II, whereas ACE2 reduces ANG II.\n\nBy inhibiting ACE1, ACE inhibitors reduce the levels of ANG II and its ability to increase blood pressure and tissue injury. ACE inhibitors are commonly prescribed for patients with hypertension, heart failure and kidney disease.\nhttps:\/\/theconversation.com\/what-is-the-ace2-receptor-how-is-it-connected-to-coronavirus-and-why-might-it-be-key-to-treating-covid-19-the-experts-explain-136928\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRPokyIGsHzP0Xx4a2VsCRnsJ1_5SXcM-Zfm0qiQh7WvEHn3KFe&usqp=CAU',width=400,height=400)\n\"\"\"\nnzdoctor.co.nz\n\"\"\"\ndf['topic-id'].hist(figsize=(10,5), bins=20)\n\"\"\"\n#High expression of ACE2 receptor of 2019-nCoV on the epithelial cells of oral mucosa\nCitation: Xu, H., Zhong, L., Deng, J. et al. High expression of ACE2 receptor of 2019-nCoV on the epithelial cells of oral mucosa. Int J Oral Sci 12, 8 (2020). https:\/\/doi.org\/10.1038\/s41368-020-0074-x\n\nThe ACE2 expressed on the mucosa of oral cavity.This receptor was highly enriched in epithelial cells of tongue. Those findings have explained the basic mechanism that the oral cavity is a potentially high risk for 2019-nCoV infectious susceptibility and provided a piece of evidence for the future `prevention strategy in dental clinical practice` as well as daily life.\n\nHigh ACE2 expression was identified in type II alveolar cells (AT2) of lung, and many others. These findings indicated that those organs with high ACE2-expressing cells should be considered as potential high risk for 2019-nCoV infection.\n\nThe ACE2 could be expressed in the oral cavity, and was highly enriched in epithelial cells. Moreover, among different oral sites, ACE2 expression was higher in tongue than buccal and gingival tissues. These findings indicate that the mucosa of oral cavity may be a potentially high risk route of 2019-nCov infection.\n\nWhen the authors combined the base of tongue, floor of mouth and oral cavity as other sites, and compared them with oral tongue, they found the obvious tendency that the mean expression of ACE2 was higher in oral tongue (13 tissues) than others (19 tissues).https:\/\/www.nature.com\/articles\/s41368-020-0074-x#citeas\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRZpieBNSe48nNKrJmlVdKqS1hjRH0tc1LEsZvNrs6iwH404UF2&usqp=CAU',width=400,height=400)\n\"\"\"\nnature.com - High expression of ACE2 receptor of 2019-nCoV on the epithelial cells of oral mucosa Citation: Xu, H., Zhong, L., Deng, J. et al. High expression of ACE2 receptor of 2019-nCoV on the epithelial cells of oral mucosa. Int J Oral Sci 12, 8 (2020). https:\/\/doi.org\/10.1038\/s41368-020-0074-x\n\"\"\"\nsns.countplot(df['topic-id'],linewidth=3,palette=\"Set2\",edgecolor='black')\nplt.show()\nsns.countplot(x=\"query\",data=df,palette=\"GnBu_d\",edgecolor=\"black\")\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\n# changing the font size\nsns.set(font_scale=1)\nax = df['query'].value_counts().plot.barh(figsize=(14, 6))\nax.set_title('Query Distribution', size=18)\nax.set_ylabel('Query', size=14)\nax.set_xlabel('', size=14)\nimport matplotlib.ticker as ticker\nax = sns.distplot(df['topic-id'])\nplt.xticks(rotation=45)\nax.xaxis.set_major_locator(ticker.MultipleLocator(2))\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nsns.boxplot(x='topic-id', y='question', data=df, palette='rainbow')\nfig = px.bar(df[['query','topic-id']].sort_values('topic-id', ascending=False), \n                        y = \"topic-id\", x= \"query\", color='topic-id', template='ggplot2')\nfig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', color='crimson', size=14))\nfig.update_layout(title_text=\"TREC Covid-19 Information Retrieval\")\n\nfig.show()\nfig = px.parallel_categories(df, color=\"topic-id\", color_continuous_scale=px.colors.sequential.Viridis)\nfig.show()\nace = pd.read_csv('..\/input\/cusersmarildownloadsangiotensincsv\/angiotensin.csv', sep=';')\nace\nsns.countplot(ace['Genotyping'],linewidth=3,palette=\"Set2\",edgecolor='black')\nplt.show()\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcScZPkwZI41pI2V3O14mHGkagR7K7GbdceJNl_xHV_sPL8qVzvw&usqp=CAU',width=400,height=400)\n\"\"\"\nadvbiores.net\n\"\"\"\nsns.countplot(ace['End_point'],linewidth=3,palette=\"Set2\",edgecolor='black')\nplt.show()\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wCEAAkGBxITEBUTExASFhUWFRoaGBgWFRYbHhsWFRcWGh0WGRgdHikgGRolIhsWITElJikrLi4uGB8zODMuNygtLisBCgoKDg0OGxAQGy0lICYtLS0tLy0tLS0tLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf\/AABEIAKgBLAMBEQACEQEDEQH\/xAAbAAEAAQUBAAAAAAAAAAAAAAAABQIDBAYHAf\/EAEEQAAEDAgMDCAcGBgICAwAAAAECAxEABAUSIQYxURMUIkFhcZLRBzJSU4GRsRYjQnKhwRUkM3Oy0mKCg6Lh8PH\/xAAbAQEAAwEBAQEAAAAAAAAAAAAAAQIDBAUGB\/\/EADcRAAIBAgQDBAoCAQQDAAAAAAABAgMRBBIhMQVBURMUYZEVIjJScYGhseHwBsHRIzNC8SSCov\/aAAwDAQACEQMRAD8A63zZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgHNm\/do8I8qAc2b92jwjyoBzZv3aPCPKgILHmEcoOgj1B+EcVUBsFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAQWPf1B+QfVVATc0AmgFAJoBQCaATQCaATQCaATQCaAUAmgE0AoBQCgE0BSXADBIk9UiouiVFtXSKpqSBNAW330oSVLUlKRvKiAB8TUN21ZaMZTeWKuzy2ukOJzNrStJ60qBGnaKJp7E1Kc6css00\/EuzUlClLgJgEEjfBFRdEtNK7LDeINKcLYdbKxvQFpzaf8ZmozK9r6mjoVVDtHF5ettPMyZqxkUrcA3kDvNRexKi5bIqmpIE0AmgE0AmgE0AmgE0BBY8fvB+QfVVATk0BbfdyoUrgCfkKA5L6ML1+5xV91Tzqm0ocOUuLKZWsJQMsxuzfKt5pKCRlBts2H0w4qtmySltxaFOOAShRSYGp1GvVVKSvItN2RLejvMjCmFOuKUVJLhU4ok5VqKhKlHcExUVPadiY7Hr3pAwxK8hvETxCVqHiCSP1p2cugzxJheMW4Y5wXkcjE8oDKY4yKrZ3sTcYVjDFy2XWHUuIBIKhOhABIM9hHzo01uE09izhu0dpcOqaZuELcQCVJTMgAgE7tYJAqXFpXCaeh5cbSWiH0267hAeUQAjWSVGAN3XUZXa4utiVmoJIfarGRbWynPxHRA4qNZ1aipxcjswGEli68aUee\/guZyzDMTuUXLDjjzsLcSqCtUFBXB0mIOteXGdRSjKT3PvK+Gwk8PVpU4K8VbZb2vudfxfEkW7KnV7kjdxPUBXrTkopyZ+eYehOvUjThu3Y5vZrv8UcUQ8WmknWCQkTuSANVq7\/ANK85OriJaOyPs6kMBwemlKOeb62v+ETmBbOXtrdIPOStjXlOkd2UwMhJ1mNRW9OhUpzXrXR5eN4rg8Vh5Lsss+VrffTka6wq5vsQcbRdONiVGQpUBKNPVBHXHzrB56tZxUrHrQWHwHDadWpSUm7bpX113+Bs+E7H3Db6HF4g4tKFBRT0+lGsGVxHwrohhpxkm5nj4njeHq0pU4YdRbVr6afQ3Oa6z500K6wi3uMUC+fArSsHkgkz930soVMDdO7jXHOnGdZetquR9JhsXiMNw6SVH1ZX9a+mumxti8dtg6Wi+gOAElJO6ASZO7cCa6XUjmy31PEjg68qXaqLy7X+hj2m1Vm46GkXCSsmAIUATwCiIJ+NVVenJ5UzepwrGU6fazptL95bkH6U7vLaoR7a\/8AHWssZK1P4nd\/G6PaY1P3U3\/X9jZfHLS0smWnX0pWU5iIUSC4SoZoBjQjfVaNWnTppNmvEsDisbi6lSlBtJ28tNLm1XF02pgrDqQgoJCwdII9aa68yavyPAdKcZ9m1617W8TUNi8IYZL1y3dh8hBSYQUxPSMyekTA\/WuTDU4qTkpXPf4zja86UKFSlktrve9tNOhBbD3rSbx+5ecSlKUqgn2nFaAdZMA1hQku1lOTPV4rQqdxo4WlG7dtF4LX6s6NhOO29zPIuheXeIII7YIBiu+nVhU9lnyWKwGIwtu2ja5qm1eE291eoQu+CFaJ5LIVHXqBmAT21z16cZzScreB7HCcXXwmGnOFHMn\/AMr2tZHu2e2JZKW7V1BUNF6Zojq1qMTiMmkXqW4NwbvUnUxEXltdcrmz4DjDb7QyvIcWlCeUy6AKI1MdQkGuilUU1o7s8fHYOph5vNBxi28t+hj3e19k2rKq4TPXlClR3lINRLEU4uzZrR4Rja0c8Kbt5fck7G\/aeRnacStPFJ6+B4GtIzjJXizjr4erQlkqRafiYatpLQKWk3CJbEqEnQAgcNdSPnVXVgm1fY2WAxMoxmoO0tvEqttobVbJeS8nk0nKVKlMKEaagcRSNWDjmT0FXAYilVVGUHmey3Me02usnFhtFwnMTABChJOgAJEE1WOIpydkzarwfG0oZ5U3b5E3NbHmkFj39QfkH1VQE3NAQe219yNg+vrDZjvI0q0VdpESdlc4\/sNs\/iTrS3rF8NJKghR5QoKigSNyTIGb610TlFOzMIxlbQw9tLe\/Q6hi8uOWWRKBnKgCrQbwNTSDjuhJPZm2elfEVtNW+HtEhIbSFAfiygJSk9hP0rOkrtyZeb0SJXGthbK2wtZLYLqG5LpJzFcakcBO4VHaSciciSNe2KQpzA8QQZyhZy9ii2kqjh+E\/Gr1NJoiGsWY2y20PNcEuoMLXcFKO9bLQJ+GUmpnHNNIiMrRKPRko2uJqDvRItllU9UhtyD2wKVNY6CGkiT9Hlsq+xZ6+WDkaJUmfbWClA+Ccyu+KrP1YWEfWlc7DNYGxyfa7FkXd8lpTmRhtWUq\/wAlade8CvMxNRTqKF9EfccFwVTC4OWIUbzktF4cvPf4Fjbu8t3HGjbLSUobCYSCMuWABqOyq4qcJZcj2N+A4bE0u17xFrM7683rcnfSZflVvbgHRwBffKZFb4uf+kvE8n+OYdLHTv8A8U\/vb7GybD2obsGQPxJzk8Ssz9IHwrfDRSpI8vjdWVTHVL8nZfIkcZueTt3V8EH6Vs3ZXPNpwc5qC5tLzOVbH4ZeOqcdtnUtqEJUomJzawNDwH6V5OHhUm3KDsfoPFsTg8PCFHEQclyS8NOqOkbM2d22lfOnw6okZY1gAGdYGp\/avRoxqRvndz43iVfCVZR7tDKuf7dktcO5UKVwST8hWx5trnNvR0nlL5987koUfitQj9AqvOwvrVpSPs+Of6HDqNDrb6LX6kbh1hz7E3ElRCCVKWRvyJIEDvJSPjWeTtq7XI6u3XDuFU5WvLS3xd3f5FWPYY03ibTNukpGZsbyYJUNZOtK1OMasYx8BwzGVq3D6tXEO\/tW8iQ9KL5XctNJ1IG7tUdK0xzbcYnF\/FoKEateWysvLVlva3Zti0s296nioZlknU9YA3AVFahGnSvzNOF8VxGLx+VaQs9PDl8zNddLWAIBOqwY7luKI\/QitE3DDfvM5akI1+OWWyav\/wCqPMB+4wR1zrdUsj4QiP8A1PzqMP6lByJ4v\/5HFoUemVf2zD2A2XbfQt58EoBypTJAJABKjG+JAHxrPCUFNZpHd\/IOLVMPNUaLs7Xb5\/BFvYZATiqg36gDgP5R\/wDMUoJLENR21I4pUlU4PCdX2nlfz\/6Lmzv8xjSnOpKlq8Iyj9SKtH18S30\/oyrru3A4x5yt\/wDTv9jEx\/DmlYqlhtEJU4gKgnXMrpHU8JqmIgnWUV8zfhOKq0+Fzqzfs3UfCy0+pN7apasbfkbZHJl89MgknKnqkmf\/ANrfEKNGnaCtc83hDq8SxaliHmUFcv4NsjbJw\/O62FOLazlRnoyJSBwgR8amjhoZLyWplxPjWJeKlGjK0YuyS526kV6M3yg3RBORLQPxBMHviaxwLtKVtj0f5PFOlSbXrX\/r\/JH7H4IL65cU4TySTmWAYKionKmeoaE\/D41nRp9tUbex2cSxno3B04U161rLwstWSe32BlllpLDagwkqJAJVC1fiM61tiqLjBKC0PN4FxBVsVOeJl67SSei+RJbJv4bcqbCbVLb7YCgI3lEHMFD1oOuutWoSozsrWaMeK0eI4XNKVRyhLTfrya5fI3qa7j5cg8dP3g\/IPqqgJqaA0z0qMPu2XJMNLcKlpkIEwAZ1q9NpSuys720M70dYUu2w5ptxJS4Spa0neCtRIB7Yy0qO8hBWRpmLYFdXOPIcVbu8gh1slZHRytHPv7SI+NXjJKHiUlFuRk+lXZi5deburdBcygApTqQUmQQOulKSWjJqRb2MDGMQxfFG024sFMpJGdSgtCTHWSsCE9gk1KUIu9yrcpaWN5w3ZpNthirVHTUUKKlR67ihqY4bgOwCspSu7miVlY5fsdsXduXTSLi3dQwhfKLziASker2lUAdxNbymrNoyjB31MvbjZy9XiTqre3dUlwRmSNCFDKQVbgIqKco5dSZp30OobH4AmytEMCCr1nFD8Tiok9wgJHYkVjOWZ3NIqyse7V3LqLZXItrWtXRGUTE9dY1ZSjFuK1O7AUqVTERjVklHm39jXtj9jG+RK7tmXFq0SomUpHGDvJk90Vy0MMst6i1Pd4vxyfaqGEnaKW65v8GNtvsolKEG0tjMnMEAnSKjE4dZfUWpbgvGanbtYqp6tufUysU2eduMNtxlKXmkAZFaGEjLHZoBV5UZVKKXNHPQ4lTwnE6lVO8JN6rx1+5FYNi2J2zYYFopYE5czazlkzGYGCN9YU6lemsuU9PF4XhWLn27rWvvZrX5PW5MX7V+vDnQ8grdcXohIHRbgCIHxPXXQ1VdKWbdnkRlgIcQpdi7QjvJ82tf8ELs8\/iVo2pDdiSFKzEqQuZgCNCNNK5qTrUlZRPb4hHhuOqKpUr2sraNf4N62avbl1oquWQ0rMQlIBHRgakEnrmu6jKco3mrHynEaGGo1FHDzzK2r8SvaUr5o6G0qUspIATv1q9S+V2OfCqDrwU3ZXV\/hc1fYrC3mLO5UppaXF6JSRqUpTpp3qV8q5cJTlCLbWp738gxlLE16cack4rny1ev0KvRthDzRecebUgqCQnMIJ1JV8PVqMJSlFtyRf8AkONoVoUqVGSaXTyRi4ZhL7mLl9xlaW0qUrMoQNEkJg98U7OUsRma0LPGUKXB1RhJOb3XPV3YucJfexhLimVhpLiTmI0yo6Q179KVKcp107aIYTGUMPwmcFNZ5X0566fYv+kiyuHltIaZWsAEkpEiTpVsZCU0lFGP8cxFDDzqVKsktElf6\/Y924w1421swy0tYQkA5QT6qQKYmEuyUIocFxVFY6pXrSSve1\/F\/wCD3aPDXk4Zb27bS1KATnCRMGJO7tJpVhJUFCK6EYLFUZ8VliKkko3k035IibK6xK1YNqm1UQr1VBCiU59SJGnz3VjCVelHKonp4ilwvH1u8Sq2tur2vb4\/0TWyWzrlsw884kl9xBASNSkb4n2iYnuFb4ag4JyluzyuN8Tp4qUaFH2I\/wDXkkWvRvhDzbjzrzSkFQATmETJJVHyTVMJTlGUpSR0fyDG0KlKlRoyTS3t4JJERiNndsYmbhFstzpkphKlAgpKerdvrOrGpGtnSudeAr4Svwzu1Soovn13vz3JfbLB7m6t2XeTHKpT0209WbWBJ3itsRTnUpp8zzuEY7D4LGTjmvB6J\/DZ\/BkcvE8Set02ibNaSEhCl5VJlKRG8wB3zWXaVpRyKPzO94PhlOv3mVZNXzZdHrvy1JdjZ5dphryEArfdHSyCdepI4ga\/M1tToulSaW55mL4jDHY6nKWlNNb9L6tmR6OMKcYt3C6goUtzcoQcqUiP1KqYSm4ReZFv5FjaeJrxVKV0ly6\/tinFtob1l5aeYl1r8BSFfqQFT8hU1KtSEtI3RlguH4PE0U5Vsk9bp\/Tp9yN2N2efN4bt5rkUjMUo3ElaSn1eoAE741rKhRk6naSVj0OKcQoU8EsHSnnel34LX98DoM13nyZB46fvB+QfVVATVAJoBQCaATQCaAUAmgE0AoBNAKATQCgE0AmgE0AoBQCaATQCgE0AmgE0AmgE0AoBNAJoBQCaATQCgE0AmgFAQeOn7wfkH1VQE1QCgE0AmgFAKAUAoBQCaAUAoBQCgFAKAUAoBQCaAUAoBQCgFAKAUAoBQCgFAKATQCgFAKAUBB45\/UH5R9VUBNTQCaA0L0q7Sv2rbSWHC2tZJJASTlSOqQRwrSlFSepScrLQgMXu8cs2UXLl4hSDl0hBjNEBQLY4xoausjdrFXnWpvezu1Lb1g3dPrbZzSlRUoJTnQopMFR3EiR31lKNpWReLurkkMbtuVS1zlnlFiUoC0yoESCBOumtRZk3GI41bMRy1w03O4LWkE9wOpoot7C6Rdw\/EmX052Xm3EzEoUFAHgY3GjTW5NynEcWYYALz7bYO7OoJnunfRJvYXscy9LOMh4W7du8FpXJBbXIJnKBKTxNa0o6tsyqM6Rz+3tw0y5cNIVlSlIW4kFUAJ0BMk7vnWdm9UaF+\/wASZYSFPPNtJJgFxaUieEk1CTexJe5wnJnzpyROaRGUiZndHbUAwLTaOzdc5Nu7YWvqSlxJJ7hOvwqzi1yIujKv8SZZTmeebbTxWoJH61CTexNy3huMW9xPIXDTsb8i0kjvA1FGmtyLozZqCTAxHHLZggPXLTZO4LWkE\/AmpSb2Iujme3F5zrFrRlp0qQVN6oXoQtYlQIMHQEzW1NWi2zObvJI6g7izCXeSU+0HIJyFxIVABJOWZiAT8Kxs9zQxBtPZZSvnttlCspUXUAZomJJ31OV9BdEi7dISjlFLSEATmKgExvnNuiq25E3KLG\/aeRnZdbcRMZm1JUJHVIMTUtNbgvrWAJJAA6zUAjLfaSzW5yaLy3UsmAkOoJJ4ATqe6rZX0IujMvsQaZTnddQ2nitQSPmahK+xNzHw3HbW4JDNyy4RqQhaSQOMTMUcWt0RdMuX2KsMkB59psq9XlFpTPdJ1ok3sTcuX2INMpzPOttp3ZlqSkT3k0Sb2BWi6QUBwLSUEZgsKBSUnXMFbiO2luQMC12ks3CoIu7dRSCVAOIMAbzv3DjUuLRF0WMbxtrmD1w06hxKUKhTagoSBuBBiaKLvYN6XNJ9FF81b2rz1zcIRyjwSkuORORIJIk6mVH5VrVV3ZGdPRXZ0u2ukOoC2nErSodFSSFA9oI31g01uanPcd2EfUh19zEni50lJSMwQkTISOlpA4RWqqJaWM3C\/Mueh3HH32n2nVqWGuTKFKMmHM8ozHUgZJ19ruqa0UtRTd0dEmsTQhMcP3g\/KPqqgJmaATQHGfStc8piLbYSpeRKeimZUVHVIidTH610UtmzGpvYzMcucSxUJZRYKYaCpJXmA03FSlJGg4AE1CUYathuUtLFr0lWqbW0tLJBnJKjp6ytZMdqlTSm80mxNWSRMsbKs4dbc+cK13TaCqc3RC1IKcoT1wDAnhVXNyeVbFlFRV2Rno\/2XRfh28vczhUspSCojUAFSjB3agAbhB7KtUnl0RWEc2rMTYuLbGnUNE8klDoUJPqITmE8YVA+JqZ6wTYjpKyPdmcOGL4g+9cqUWmx6oJGiioITI3CEqJjrpJ5IpIJZ27mIxgbKcdat2ZLaXkqIJmMg5QieHRG\/jUqTcLsiyU7Ik8b\/mdomW96W1on\/wAYLh+gqsNKbZaWsyv0wvF25t7ZJ1P6KcISn6mlHS7FTkj30iXbj12xhjKilHQSY3STlE8QkAmKU0knJierUTZU+j2wZLbqUuBTCkuTnJzKbIUMwOm8A6RVO0ky2SKOdNY0zdX67i9bfeaE8m20mRv6IPSECJPaewVtlcY2RndN3ZObF4K6vFE3TNq7bWyc2iwUykoIyAHfJIPWBl3zFUnK0bN3ZaC1ujp2N34Yt3Xj+BBV8hWKV3Y0bsjlmwmzaMSU\/d3hWsZ8oAUR0oCiZGsJBSAO+t5yyWSMoxzasxtgsMb\/AI2UtkltjlViewcnqewr\/SpnJ5PiIL1tChWHqxHGnWwspRKs6hvDSISoDtJIT\/2+FQnlhcNZpEr6Qtk2LSwTyCVQHgpRUrMZUkI38KiE25akzilHQsbVbQZsHsmEmXHW0BQG+G+idO0iI7aRj67fQSl6p0XY7B+aWTTJ9YJzL\/uL6SvkTHcBWU5Xdy8VZGj+lXFHHbhmwaVGcpzdpWrKkH\/jvJ7q0pLeRSo+ROo9G9g2ltUOZmilZVnMrKCFdIHQAxuAHZVXVkW7NGp4PbHGMUdVcKUWGQSEgkaZsqUiN0wVEjXSK0byQVtyls8tdjF2ow1uzxa3FqCg52yACTBUsJjXWCCRFINyi7iSSkrGftr\/ADOO27G8JW2D3Zsyh8k1FPSDZM9ZJGR6arwksMp1VJVA47gP1qKK1bFV7Is+ki5WOa4YyYAS2gidCei2hJ7Jqaa3kxNvSKLHpA2QtLK1bU0V8rISVFR6enSJG4aToKmE3KViJRUUX8V\/l9nGG9xehR\/8iiv\/ABNRvUJ2gYNtse0nB1Xj5WXFNlTSQogISZKdOsq366aipc3msiFFZbs2z0NtqGHrJOin1FPYAlAMfEKqlb2i9PYh8SxK9xHEH8PauEtNJBKjknopygyRqZKgIkVMVGMczKttysbzsns41Ysck2SoqOZazvUqI3dQA0A\/eaznNyd2XjFRVkTU1UsQmOf1B+UfVVATU0AmgOaYXs\/dLx03TrKksoUpQUcsGGylIGs7zO7qrbMlCxnZ5rnS5rE0Ob7WYDc3WLMK5BRYQpvMuUxlCsyuudwA+NawklFmcotyRuO1mFm6tHWUmFKGk8eqs4uzuXaurHOsCdxizYXaN2BVKlFK9+Uq3wZgjr1jfW0skne5ks0dLGwbFbFLYbeduFA3D6CmAZyJVqQVdalGCY0EADrqk530ReMbbmsbO4di1i480xaBXK5U51eqMhVlWFZgB6x0NaScJJXZRKUXoiW2A2YumsRcfuEKhKFQ4Y6biymSNZiM3VVZzTjZExi812YF9hWI22KruWLUu5irKYlJC05TOogipi4uNmyGpKV0VYbstfrxVl+6bzDMHHFgpypKQopQNZMEI3cTv3lniotInK27sydtMAvW8RTe2rRdgpUABMKTOhTIJBGmlRCUcuViad7o2DAnsTulOG7aRbslopSgDpKWoiFHUkACeG+qSUVsWjme5qezjGJ4Wt1CLAvpWRqD7MwoETGh1BFaScZrVlIqUG9DoGy15fOha7xhDIkcmgGVRrJUcx7I3ddZSSWxpFt7mTtPh5uLR5lJgrQQO8ioTs7ktXVjmezlpjDLLlo1a5ErUSXV\/hkAHKqYOgEaE1vJwbu2ZRzrREx6N9nbi252660pKlJCG80SqCok6E7+hVakk7WLQjYu+i\/ALhl65fuWVNqXATmKZMqUpe4nT1KipJNJIQi022TfpJbSrDXpIECRPEbhVYe0i0\/ZNE9Fmzin3hdOglpgw2DuU5JOn\/FJJP5iOBrWpKysZwjd3Z2Oa5zY5jt\/s7d8+bvLZsuFOUwNSFNmRKZ1B7K2pyVmmZTi73RO7PXeKXLpN0wi3Y5NQyx0lLVoDqSQBqerq31WSgloWi5Pc1LCcPxLDLl4s2fLoc0kaggElJkGQRJmR11e8ZpXdilpRehL7LbK3T17z+\/AQoGUN6E5huJAJCUp3gTJPDrrKSUcsS0Ytu7I3HsHxBjFzdsWxe6WZGkjVBQQdQRoT86tGUXCzIkmpXRbGy+Iv4iw9dNky4hbhSU5W0oVmDe\/XdGk795pniotIjLK92Z3pC2fuzfNXlu0XcpQqAJhbSgoSOsTUU5JJplpp3ujV9uX7591oXSUtuL0bZT+HMQATqYJJrSGVbFJXe5uHpMwK5eRbsWzClobTEjKAMqcomSOqsqckm2y802rIlNvsMeVhyLa2aUuMiYTHqoA4kcKrBrNdlpL1bIlNkcPXbYa00UQ6lsqUnT+oslRGmm8xUTd5XEVZWIzYNeJKdfVeoyIMZElDaelJmMupAEb+Iq08tlYiOa+puU1mXE0BCY4fvB+UfVVATE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgPZoDyaATQCaATQCaA1bbLZV2+UhJuuTZTqUBuSTxnMB3aVeE1HkUlHMbDh1k2w0hptOVCEgJHYOs8Sd5PbVW7u5ZKxkTUEiaATQCaATQCaATQGo7SbJPv3HLs4g6wcoTlGaIE+yoca0jNJWaKSi3sy1gOwCGrgXNxcuXLqTKSvQBQ3KIJJUR1awN8bqOpdWQULO7Nzmsy4mgE0AmgE0AmgIXGz94Pyj6qoCZmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgITG\/wCoPyj6qoCZoBQCgFAKA8mgIq9xzI4pAaSQkkSVGSRoTpurrhhk4ptnmVcfKE3FLYs\/aM+5R4ledW7qupn6Sn7qH2jPuUeJXnTuq6j0lP3UPtGfco8SvOndV1HpKfuofaM+5R4ledO6rqPSU\/dQ+0Z9yjxK86d1XUekp+6h9oz7lHiV507quo9JT91D7Rn3KPErzp3VdR6Sn7qJppwKSlQEBSQY4SJieuuSUcraPTpTzwUupVVTQSACSYA3n\/7vPZVKlSNOOaWxaEJTkoxWpXkzAFKTlIBHxANRCpGUVLqTODjJxfIcir2TV8y6lbDkVeyaZl1FhyKvZNMy6iw5FXsmmZdRYFpQ1ymiaZBRUgo5VM5cwmJiRMcYoTZ7nhfQFZStObhIn5UFna543coUYStJPAKBPyqLhxa1aPW30qJCVJJSYUAQYPA8DU3FmtTxy4QlSUqUkKUYSCRJI1gDrqLhRb2PHrttBhTiEmCYKgDA3kDsqbhJvYc6Rk5TOnJE5pEQeud0UGV3y21LqVAgEEEHcR1jjQg9oBQCgFAKAhcaP3g\/KPqaAmKAUAoBQCgPCaA1TFf67v8AcV\/ka9Sn7CPnK\/8AuS+Ji1cxFATv8PbytpOQKQpvlCCM2V09LMOrLKB8TXNnd2\/jY7uxjZLS6tfrr1+hbZbJcUFsBASlcQzOojSDosjt1131LaSVn05kRTc3mjbfl+3Iq49dWnX7IT\/6j1e6t47HJLd\/9FupKigNwsv6Lf8AbT9K8yr7b+J9Fhf9mPwL1Zm5gYqpRj2B1cFR+LiT1Hh8a8XiKqZrv2eR7HDXTtZe1+7GAGz7J+VecoN8j0nOPVDkj7J+Rpkl0Yzx6ockfZPyNMkujGePVDkj7J+Rpkl0Yzx6ockfZPyNMkujGePVGbhLZC1aEdA9Xamu\/h0Wq2q5HDxCUXR0fNGepUAk7hXuHhnPkXaw+L3IvKXinP0cvJHoRvnQyd0aCsb65j0lFZOyvyvbx3M3B1W2V0P5Oc8sqM46ROmTL1x3VKy313M6qqZVk9m3L6l3YVTcAZrfPC+iEjlfXOqlTqI7NxFKdhi77620+GxYXiDwfcQhzJmu0olKUTCk92p76Nu\/zEIRcYtrk39SwLh11bAU8rOm4dQHITmhKJHVE6kbqau3xLJRSbS3inYocxJxxDedQUSi4SSUpkhGYDWNNw3RUXb+pGSKbaXuvzKGcScDBQh7lEC1zKBSkhtYygJ3d4gzO+oTdvkaTgnO7VvWXzKxfONLuFpdPKFpopTCekCkyQmNyezjrU3au\/ArljKMU1pmf78y\/dY08hD3JXJdQkNlLkJMKUdUyBG7q6qZnrZkKlFuOaNtX5WJBV641eIaXcrcSVJSAkt5syiZLiMslPaIgCpu07GahGcG1G3nY2utTjFAKAhcaP3g\/KPqqgJeaATQCaATQCaAUBHXWFoWsrOYFRkwoRJ3kAp0rojiJRVjhqYCE5OV3qYl1h7LaczjhSOJWn5Do6nuqXi2t7ER4Upu0W2RIu2VKytN3Lh\/45QPjKZA7wKz7+3srnT6BUVepOxlIw65VrySUTvzvSfjlQQfnVlip+6jKXDKC2qSfy\/Jccw+6EEBCoED79QMcBKP3p3mXuoLh9J71JfvzMC5u0tn+Yt7pE\/izIWnxRH71HfZLeJouCQnrCpf7khh7Vs8PunVKPWMwCh3pKZqyxje1jGfCMntNmb\/AAVHFfiT\/rVu9S6Gfo2HvMlGxCQBoAAAJnQCN\/Wa5pSzO7O+EFCKiuRVNQWPFDu4a7iOB7KrKCkrS2LRk4u63PSRpGYAAAAqPUAOqkIKMVFchKTlJyfM8+KvErzqxUfFXiV50A+KvErzoB8VeJXnQD4n5nzoD00BTlERAjhFBcZBMwJ4wKC4SgDckDuAoTdjKOA+XXQi4CBwHy40F2QWxeJqurNDziWwoqcScqYEIcUkQCT1CguycDadeiNd+goTdnuQb4Hy6qEXAbTEZRHCBQm4yiZgTxjX50FyqaECaATQENjR+8H5R9VUBLzQCaATQCaATQCaAiMexoMjKmFOEaA7kj2lfsOus6lRROvC4V1nd7EJhWFLuVcs8tWXiTqrsT7KO74cazjBz1kdtfEQw67OktTbbZhDacqEhKR1Afr2mt0rbHkyk5O8mXZqSomgPFAEQQCDvBoNjUse2Xj762lKk65Ekj4o4Hs+XbjKnziehQxd\/Uqaoq2Z2nKyGnz0jole7MfZVwV29ffvQqX0ZGJwqis8NjbJrY4BNAJoBNAJoBNAJoBNAJoBNAJoBNAJoBNAeZwIkjUx8eFAap6MFD+HNiRPKPadzy6A2yaATQCaATQCaATQCaAhsaP3g\/KPqaAlpoBNAJoBNAJoDExLEkMpCl5oJgQknWJieqe2qykorU1pUZVZWiaIp3O7mdJ6a5WQCTB6gBru6I+FcieaV2fQOLpUbQ5I6IzASABAgQIiBGgjqrtPm223qVTQgTQCaATQCaA0DbPDg2+FpEJdk6dSxv8AnIPfNc9WNnc9fBVc8Mr5fY2zZvEC9bpUo9IdFXapPX8RB+NbQd0efiaXZ1GlsSc1YwE0AmgE0AmgE0AmgE0AmgE0AmgE0AmgIfavBzdWxQlWV1Cg4yv2XW9Un9vjQGqeirAnUpNzcBQUM7bSDIyJLhU4Y4qXPwFAdDmgE0AmgE0AmgE0AmgIfGT0x+X91UBLTQCaAu2rCnFZUxME6mBAjzFUlKzSRaMU1dmd\/BHeLfiV\/rS8+i8\/wTaHV+X5H8Ed4t+JX+tLz6Lz\/AtDq\/35lq52cW4goXyZSoajMr\/XQ1DzvdLz\/BaEoxakm\/L8kZhOwqmVZittap6JJIyjsGX1u35RVIU5R5Lz\/B018X2qtdpfviZNw0UKKVRI4btRNaRle9zjkrWsW5q5UTQCaATQFbbaleqlSo4An6VRzSdiyg2rkZtFs67coSkJUkpVMltR0giPp8qpNqXXyZ04efZSb080NndnnrZC0kKVmVOjahGkUg1Fc\/JjET7Vpqy+aJfmrnunPCfKr9ovHyZz5H1XmeG1c9254VeVO0Xj5MZH1XmWQqrJ31RVqzsxNSQJoBNAJoBNAJoBNAave7SLS4tISISopH\/UxwrjnXkpNI+hwvDKM6UZyvdltraN5SglKMyjoANSTwACaqq82bS4XhYq7ul8Sq42hfQrKtsoVwUIPyKaOvNbkR4ZhZq8Xf4MoRtM6SAEySYAGpJPUBlp3iZL4Vhkru\/mV3G0L7asq2yhQ\/CoQdewpo681uRDhmFmrx1XxLf2pc4D5jyp3iZb0Th\/HzK3No3khJUiMwzJmNUyRI03SD8qdvMiPDMLK9r6eJR9qHPZH6eVO8TJ9E4fx8yewPEC81nUACFEadka\/rXVSk5RuzwsbQjRrOEdiQmtDkE0AmgIfGT94Py\/uaAlpoBNASOz39f\/AKK+qKo\/bXz\/AKLr2H8V\/ZsbqiEkhJUQCQBGpHVrprVyhzVGx9ypGS4tbd3O9avqMheV03COdj7wCEqbA6KdCAoazFATu0uBvOPSy0MgTZgAFIA5C+Q6sAEiAEAn4QOFAbhQGrY3\/XV8P8RWcPal+8i8tl+8zBmtCgmgE0AmgJ3Zr1V\/mH0rOPtP5F5eyvmSOI3iWWXHl+q2hS1dyASY7dK0KGgWWJ4g5yTT1zcMPc4bSvI1biWrhlS5AcZV6jiHW0kbwgEyTQG32l44cRuGio8ki3t1JEDRbi7kLMxJkIb0nSO2gJmgNIVvPefrVKXsIvU9tiauUE0AmgE0AmgE0AmgOa4q7\/MPf3V\/5GvPqL12fWYOVqEPgXMDxFLNy26qSlCpOWJiCNNaiDtJNlsQnUpSguZKK2kQhjk28yloQlKHHEIJP3ilqEEqypg5RBnfurRz0sjlWFlKeaeie6T8LL58yu7xphu+bW2n7pCVTkyzmeC1KKT1lBXlH9sVLklO62IhRqToNSfrPr4bfb6lu3xe2bZW2C44YXqtpH3gW3lSkkqJbCFdIRUKUUrbkypVZzUtFts9tdfjfYlsNxmyU6o6I3r+8Q2kAq5uMiSVQQMiydRooxvq8ZQuc1WjXUbb8tG\/F\/2ROMY+2tpTPrFIASoISBmS84pS0\/iCVJUIFUlJONjqoUJQmp7fPlZb\/M17lqxsehnN22LVNsf7iv2ruo+wfM8Sd67J6a1OATQCaAh8YPTH5f3NASs0AmgKkOEGQSDxBIqsop7kqTWxd5877xfiNR2a8fNls78PJDnzvvF+I07NePmxnfh5Ic+d94vxGnZrx82M78PJDnzvvF+I07NePmxnfh5IsqWSZJJJ3kmT86mMVHYq5N7nk1YgTQCaATQGVZYgtqcuWDxB3\/A1Rxd7pl8ytZoyv487wb+Sv9qi0+v0\/IvHo\/P8D+PO+y38lf7UtPr9PyLx6Pz\/AAP487wb+Sv9qWn1+n5F49H5\/gHHneCPkfOlp9fp+ReHT6\/gi5q8Y5VYrJ3dxNSQJoBNAJoBNAJoBNARd3gFu4srU30jvIJEnjpVXCL3RtDEVYK0ZOxZ+zFr7CvErzqOzj0Ld7re8x9mLX2FeNXnTs49B3ut7zH2YtfYV4ledOzj0He63vMfZi19hXjVTs49B3ut7zH2YtfYV41U7OPQd7re8x9mLX2FeJXnTs49B3ut7zH2YtfYV4ledOzj0He63vMk7O1Q0gIbSEpHV37z31ZKxjKTk7tl+akqJoBNAQ+Mnpj8v7mgP\/\/Z',width=400,height=400)\n\"\"\"\nyoutube.com\n\"\"\"\nsns.countplot(ace['Country'],linewidth=3,palette=\"Set3\",edgecolor='black')\nplt.show()\nsns.countplot(x=ace['Selection'],palette='coolwarm',linewidth=2,edgecolor='black')\nplt.figure(figsize=(18,6))\nplt.subplot(1, 2, 1)\nsns.countplot(x=ace['LVH_GG'],hue=ace['Outcomer'],palette='summer',linewidth=3,edgecolor='white')\nplt.title('Outcomer')\nplt.subplot(1, 2, 2)\nsns.countplot(x=ace['LVH_GG'],hue=ace['Comparability'],palette='hot',linewidth=3,edgecolor='white')\nplt.title('Comparability')\nplt.show()\nfig = px.bar(ace, x= \"Country\", y= \"LVH_GG\", color_discrete_sequence=['crimson'],)\nfig.show()\n#word cloud\nfrom wordcloud import WordCloud, ImageColorGenerator\ntext = \" \".join(str(each) for each in df.narrative)\n# Create and generate a word cloud image:\nwordcloud = WordCloud(max_words=200,colormap='Set2', background_color=\"black\").generate(text)\nplt.figure(figsize=(10,6))\nplt.figure(figsize=(15,10))\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='Bilinear')\nplt.axis(\"off\")\nplt.figure(1,figsize=(12, 12))\nplt.show()\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcR0jMf0aHqO1YutEMPn6P_2tcElzbpxgwehHdEik-Rh9GB9N66y&usqp=CAU',width=400,height=400)\n\"\"\"\nhealthcare-in-europe.com\n\"\"\"\n\"\"\"\nKaggle Notebook Runner: Mar\u00edlia Prata   @mpwolke\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3cea6de14c986e'}"}
{"id":"45904","text":"\"\"\"\nThis is a synthetic dataset that is based on a real dataset. These datasets are based on Kaggle's May 2021 tabular competition.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\nRead the files\n\"\"\"\n#Reading train file:\ntrain = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/train.csv')\n#Reading test file:\ntest = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/test.csv')\n#reading sample submission\nsubmission = pd.read_csv('\/kaggle\/input\/tabular-playground-series-may-2021\/sample_submission.csv')\n\ntrain\ntest\nsubmission\n\"\"\"\nCheck for null values\n\"\"\"\ntrain.isnull().sum().sum()\ntest.isnull().sum().sum()\n\"\"\"\nAnalyse target\n\"\"\"\nimport matplotlib.pyplot as plt\n\ntrain.groupby('target').target.count().plot.bar(ylim=0)\nplt.show()\n\n\"\"\"\nMap target\n\"\"\"\nclasses = {\"Class_1\": 1, \"Class_2\": 2, \"Class_3\": 3, \"Class_4\":4}\n\ntrain.target = train.target.map(classes)\ntrain.target\n\"\"\"\nDrop target from train\n\"\"\"\ntarget = train.target\n\ntrain.drop('target', axis = 1, inplace = True)\ntrain\n\"\"\"\nCombine train and test\n\"\"\"\ncombi = train.append(test)\ncombi\n\"\"\"\nDrop ID from combi\n\"\"\"\ncombi.drop('id', axis = 1, inplace = True)\ncombi\n\"\"\"\nNormalise combi\n\"\"\"\ncombi = (combi.max() - combi) \/ (combi.max() - combi.min())\ncombi\n\"\"\"\nDefine X and y\n\"\"\"\ny = target\nX = combi[: len(train)]\nX_test = combi[len(train) :]\ny.shape\nX.shape\nX_test.shape\n\"\"\"\nSMOTE\n\"\"\"\npip install smote-variants\nimport smote_variants as sv\n\noversampler= sv.MulticlassOversampling(sv.distance_SMOTE())\nX_samp, y_samp= oversampler.sample(X, y)\nX_samp.shape, y_samp.shape\n\"\"\"\nSplit into training and validation\n\"\"\"\n#split train set for testing\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X_samp, y_samp, test_size=0.10, random_state=1, stratify=y_samp)\nX_train.shape, y_train.shape, X_val.shape, y_train.shape, X_test.shape\n\"\"\"\nSelect model\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression(C=100, class_weight= 'balanced', multi_class='multinomial', random_state=1, max_iter=20000).fit(X_train, y_train)\nmodel.score(X_train, y_train)\n\"\"\"\nPredict on validation set\n\"\"\"\ny_pred = model.predict(X_val)\nmodel.score(X_val, y_val)\ny_pred\n\"\"\"\nPredict on test set\n\"\"\"\nprediction = model.predict(X_test)\nprediction.shape\n\"\"\"\nOne hot encode prediction\n\"\"\"\npredictions = pd.get_dummies(prediction)\npredictions.columns=['Class_1', 'Class_2', 'Class_3', 'Class_4']\npredictions\n\"\"\"\nPrepare submission\n\"\"\"\nsubmission.Class_1 = predictions.Class_1\nsubmission.Class_2 = predictions.Class_2\nsubmission.Class_3 = predictions.Class_3\nsubmission.Class_4 = predictions.Class_4\nsubmission.to_csv('submission.csv', index=False)\nsubmission = pd.read_csv(\"submission.csv\")\nsubmission\n","meta":"{'source': 'AI4Code', 'id': '5499ae4daa9117'}"}
{"id":"115306","text":"import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set_style('whitegrid')\nfrom sklearn.cluster import KMeans\nfrom copy import deepcopy\ncust_df= pd.read_csv('..\/input\/Mall_Customers.csv')\ncust_df.head()\ncust_df.describe()\ncust_df.shape\nplt.figure(figsize=(5,5))\nsns.distplot(cust_df['Age'] , bins =50)\n\nplt.figure(figsize=(5,5))\nsns.distplot(cust_df['Spending Score (1-100)'] , bins =50)\nplt.figure(figsize=(5,5))\nsns.countplot(\"Gender\",data = cust_df)\nplt.figure(figsize=(5,5))\nsns.lmplot(x=\"Annual Income (k$)\",y=\"Spending Score (1-100)\",data=cust_df,hue= \"Gender\")\nX1 = cust_df[['Annual Income (k$)' , 'Spending Score (1-100)']]\ninertia = []\nfor n in range(1 , 11):\n    algorithm = (KMeans(n_clusters = n ,init='k-means++', n_init = 10 ,max_iter=300, \n                        tol=0.0001,  random_state= None  , algorithm='auto') )\n    algorithm.fit(X1)\n    inertia.append(algorithm.inertia_)\nplt.plot(range(1,11), inertia)\nplt.title('The elbow method')\nplt.xlabel('The number of clusters')\nplt.ylabel('Inertia')\nplt.show()\n\"\"\"\nElbow point is at 5. Therefore Value of k is 5\n\"\"\"\nf1 = cust_df['Annual Income (k$)'].values\nf2 = cust_df['Spending Score (1-100)'].values\nX = np.array(list(zip(f1, f2)))\nplt.scatter(f1, f2, c='black', s=7)\nk=5\nC_x = np.random.randint(0, np.max(X)-20, size=k)\nC_y = np.random.randint(0, np.max(X)-20, size=k)\nC = np.array(list(zip(C_x, C_y)), dtype=np.float32)\nprint(C)\nplt.scatter(f1, f2, c='#050505', s=7)\nplt.scatter(C_x, C_y, marker='*', s=200, c='g')\n#Euclidian calculator\ndef dist(a, b, ax=1):\n    return np.linalg.norm(a - b, axis=ax)\n# To store the value of centroids when it updates\nC_old = np.zeros(C.shape)\n# Cluster Lables(0, 1, 2)\nclusters = np.zeros(len(X))\n# Error func. - Distance between new centroids and old centroids\nerror = dist(C, C_old, None)\n# Loop will run till the error becomes zero\nwhile error != 0:\n    # Assigning each value to its closest cluster\n    for i in range(len(X)):\n        distances = dist(X[i], C)\n        cluster = np.argmin(distances)\n        clusters[i] = cluster\n    # Storing the old centroid values\n    C_old = deepcopy(C)\n    # Finding the new centroids by taking the average value\n    for i in range(k):\n        points = [X[j] for j in range(len(X)) if clusters[j] == i]\n        C[i] = np.mean(points, axis=0)\n    error = dist(C, C_old, None)\ncolors = ['r', 'g', 'b', 'y', 'c', 'm']\n\nfig, ax = plt.subplots()\nfor i in range(k):\n        points = np.array([X[j] for j in range(len(X)) if clusters[j] == i])\n        ax.scatter(points[:, 0], points[:, 1], s=7, c=colors[i])\nax.scatter(C[:, 0], C[:, 1], marker='*', s=200, c='#050505')","meta":"{'source': 'AI4Code', 'id': 'd3f43898023d2f'}"}
{"id":"127655","text":"# 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\ndata = pd.read_csv('\/kaggle\/input\/120-years-of-olympic-history-athletes-and-results\/athlete_events.csv')\n\ndata.head()\ndata.dtypes\ndata.isna().sum()\ndata.Medal = data.Medal.fillna('Loser')\n\ndata.isnull().sum()\ndata.head()\ndata.Age = data.Age.fillna(data.Age.mean())\n\ndata.isna().sum()\ndata.Height = data.Height.fillna(data.Height.mean())\n\ndata.isna().sum()\ndata.Weight = data.Weight.fillna(data.Weight.mean())\n\ndata.isna().sum()\n\"\"\"\n1. Select all data for football in Summer olympics from 2004 to 2016\n\n2. Select all gold medalists in Summer olympics for Netherlands after 1996\n\"\"\"\ndata[(data.Sport=='Football') & (data.Year<=2016) & (data.Year >= 2004) & (data.Season == 'Summer')]\ndata[(data.Medal == 'Gold') & (data.Season == 'Summer') & (data.Team == 'Netherlands') & (data.Year > 1996)]\n\"\"\"\n3. Select all Gold medalists from China with age less than 24 in Summer Olympics\n\n4. Select all football players from Argentina and Spain who won atleast Silver on or after 2004 olympics\n\n5. Select players from India who won Bronze medals after 1988 olympics\n\"\"\"\ndata[(data.Medal == \"Gold\") & (data.Age < 24) &(data.Season == 'Summer') & (data.Team == 'China')]\n# data[((data.Medal == \"Gold\") | (data.Medal =='Silver'))]\ndata.head()\ndata[data.Team=='India'].groupby(['Sport','Sex'])#.count()\n\"\"\"\n1. Which Team won most gold medals in Basketball?\n\"\"\"\ndata[(data.Medal == 'Gold') & (data.Sport == 'Basketball')].groupby('Team').count()['Medal'].sort_values(ascending=False)\n\"\"\"\n2. In which sport India won the most gold medals after independence\n\n3. In which city, Australia won the most gold medals?\n\n4. How many Iranian females have won a medal before 1992? and how many after?\n\n5. Which gender have won most medals for Israel in Summer Olympics?\n\n6. Who is the oldest Indian to win a medal?\n\"\"\"\ndata[(data.Team == 'India') & (data.Year > 1947) & (data.Medal == 'Gold')].groupby('Sport').count()['Medal']\ndata[(data.Team == 'Australia') & (data.Medal == 'Gold')].groupby('City').count()['Medal'].sort_values(ascending=False)\ndata[(data.Team == 'Iran') & (data.Sex == 'F') & (data.Medal != 'Loser') & (data.Year > 1992)].count()[0]\ndata[(data.Season == 'Summer') & (data.Team == 'Israel') & (data.Medal != 'Loser')].groupby('Sex').count().iloc[:,0]\ndata[(data.Medal !='Loser') & (data.Team == 'India')].sort_values('Age',ascending=False).iloc[0,[1,3]]","meta":"{'source': 'AI4Code', 'id': 'eac43a56cc0391'}"}
{"id":"54618","text":"\"\"\"\n## With fastai.\n\nIssues,\n1. Need more than 9 hr on kaggle p100.\n1. `acc_steel` is nan. Debug it.\n\"\"\"\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\nimport time\n\nfrom itertools import groupby\n\nfrom fastai.vision import *\nfrom fastai.callbacks.hooks import *\nfrom fastai.utils.mem import *\nimport fastai; \nfastai.__version__\n\"\"\"\nWe are pre created labels in https:\/\/www.kaggle.com\/nikhilikhar\/steel-create-labels?scriptVersionId=18627876\n\nWe want to access the output directly in this Kernel. We will unzip label mask in `..\/labels`\n\"\"\"\n!pwd\n# !ls -R ..\/input\/steel-create-labels\/\n! apt install  -y unzip \n! mkdir -p ..\/labels\/\n! unzip ..\/input\/steel-create-labels\/labels-img.zip -d ..\/labels\/\nstart = time.time()\npath = Path('..\/input')\npath_lbl = Path('..\/labels')\n\npath_img = path\/'severstal-steel-defect-detection\/train_images'\npath_test = path\/'severstal-steel-defect-detection\/test_images'\n# path_lbl.ls(), path_img.ls()\n\"\"\"\nhttps:\/\/forums.fast.ai\/t\/unet-segmentation-mask-converter-to-help-against-common-errors-problems\/42949\n\"\"\"\n\"\"\"\n# Data\n\"\"\"\nfnames = get_image_files(path_img)\nfnames[:3]\nlbl_names = get_image_files(path_lbl)\nlbl_names[:3]\nimg_f = fnames[0]\nimg = open_image(img_f)\nimg.show(figsize=(5,5))\ndef get_y_fn(x):\n    x = Path(x)\n    return path_lbl\/f'{x.stem}.png'\nmask = open_mask(get_y_fn(img_f))\nmask.show(figsize=(5,5), alpha=1)\ncodes = ['0','1','2','3', '4'] # ClassId = codes + 1\nfree = gpu_mem_get_free_no_cache()\nbs = 4\nprint(f\"using bs={bs}, have {free}MB of GPU RAM free\")\ntrain_df = pd.read_csv(path\/\"severstal-steel-defect-detection\/train.csv\")\ntrain_df[['ImageId', 'ClassId']] = train_df['ImageId_ClassId'].str.split('_', expand=True)\ntrain_df.head()\nimage_df = pd.DataFrame(train_df['ImageId'].unique())\nimage_df.head()\n# 12k\n# image_df = image_df.iloc[:1000]\nname2id = {v:k for k,v in enumerate(codes)}\nvoid_code = 4\nwd=1e-2\n\ndef acc_steel(input, target):\n#     import pdb; pdb.set_trace()\n    target = target.squeeze(1)\n    mask = target != void_code\n    return (input.argmax(dim=1)[mask]==target[mask]).float().mean()\n\ndef dice(pred, targs):\n    pred = (pred>0).float()\n    return 2. * (pred*targs).sum() \/ (pred+targs).sum()\n\ndef iou(input:Tensor, targs:Tensor) -> Rank0Tensor:\n    \"IoU coefficient metric for binary target.\"\n    n = targs.shape[0]\n    input = input.argmax(dim=1).view(n,-1)\n    targs = targs.view(n,-1)\n    intersect = (input*targs).sum().float()\n    union = (input+targs).sum().float()\n    return intersect \/ (union-intersect+1.0)\n\nmetrics = [acc_steel, iou]\nsize = 256#, 1600\n\ndef no_tfms(self, x, **kwargs): return x\nEmptyLabel.apply_tfms = no_tfms\n\nsrc = (SegmentationItemList.from_df(image_df, path_img,)\n       .split_by_rand_pct(valid_pct=0.2, seed=33)\n       .label_from_func(get_y_fn, classes=codes)\n       .add_test_folder('..\/test_images')\n      )\ndata = (src.transform(get_transforms(flip_vert=True, ), size=size, tfm_y=True)\n       .databunch(bs=bs)\n       .normalize()\n       )\nprint(\"TEST ==> {}\\n VALID ==> {}\\n ==> TRAIN {}\".format(data.test_ds, data.valid_ds, data.train_ds))\n# len(path_test.ls()) # => 1801\ndata.show_batch(2, figsize=(20,5))\ndata.show_batch(2, figsize=(20,5),ds_type=DatasetType.Valid)\n\"\"\"\n# Model\n\"\"\"\n# learner, include where to save pre-trained weights (default is in non-write directory)\nlearn = unet_learner(data, models.resnet18, metrics=metrics, wd=wd, \n                     model_dir=\"\/kaggle\/working\/models\")\n\n# print(learn.model)\n# lr_find(learn)\n# learn.recorder.plot(skip_end=15)\n# Got nan with acc_steel at lr = 1e-3\nlr=3e-4\nepoch = 10\nlearn.fit_one_cycle(epoch, slice(lr), pct_start=0.9)\nlearn.save('stage-1')\nlearn.export(\"\/kaggle\/working\/steel-1.pkl\")\nlearn.show_results()\nlearn.unfreeze()\nlrs = slice(lr\/400,lr\/4)\nlearn.fit_one_cycle(epoch, lrs, pct_start=0.8)\n\nlearn.recorder.plot_losses()\nlearn.show_results()\nlearn.save('stage-2')\nlearn.export(\"\/kaggle\/working\/steel-2.pkl\")\n\"\"\"\n## Finish of training for part-1\nTraining with new learner is pending. See at, \n\"\"\"\n# learn.destroy()\n# free = gpu_mem_get_free_no_cache()\n# # the max size of bs depends on the available GPU RAM\n# if free > 8200: bs=3\n# else:           bs=1\n# print(f\"Using bs={bs}, have {free}MB of GPU RAM free\")\n# data = (src.transform(get_transforms(), size=size, tfm_y=True)\n#         .databunch(bs=bs)\n#         .normalize())\n# learn = unet_learner(data, models.resnet18, metrics=metrics, wd=wd, model_dir=\"\/kaggle\/working\/models\")\n# learn.load(\"\/kaggle\/working\/models\/stage-2\")\n# lr_find(learn)\n# learn.recorder.plot()\n# lr=1e-3\n# learn.fit_one_cycle(epoch, slice(lr), pct_start=0.8)\n# learn.recorder.plot_losses()\n# learn.recorder.plot_metrics()\n# learn.show_results(rows=5, figsize=(20,5))\n# learn.unfreeze()\n# lrs = slice(1e-6,lr\/10)\n# learn.fit_one_cycle(epoch, lrs)\n# learn.recorder.plot_losses()\n# learn.recorder.plot_metrics()\n# learn.show_results(rows=5, figsize=(20,5))\n# learn.save('stage-2-big')\n# learn.export(\"\/kaggle\/working\/steel-2-big.pkl\")\n\"\"\"\n## Finish of training for part-2\nTraining with new learner is pending. See at, \n\"\"\"\nlearn.predict(open_image(\"..\/input\/severstal-steel-defect-detection\/test_images\/38b9631df.jpg\"))[1].data.numpy().flatten()\n# def get_predictions(path_test, learn):\n#     # predicts = get_predictions(path_test, learn)\n#     learn.model.cuda()\n#     files = list(path_test.glob(\"**\/*.jpg\"))    #<---------- HERE\n#     test_count = len(files)\n#     results = {}\n#     for i, img in enumerate(files):\n#         results[img.stem] = learn.predict(open_image(img))[1].data.numpy().flatten()\n    \n#         if i%20==0:\n#             print(\"\\r{}\/{}\".format(i, test_count), end=\"\")\n#     return results    \n\n# results = get_predictions(path_test, learn)\ndef encode(input_string):\n    return [(len(list(g)), k) for k,g in groupby(input_string)]\n\ndef run_length(label_vec):\n    encode_list = encode(label_vec)\n    index = 1\n    class_dict = {}\n    for i in encode_list:\n        if i[1] != len(codes)-1:\n            if i[1] not in class_dict.keys():\n                class_dict[i[1]] = []\n            class_dict[i[1]] = class_dict[i[1]] + [index, i[0]]\n        index += i[0]\n    return class_dict\n\n# https:\/\/www.kaggle.com\/nikhilikhar\/pytorch-u-net-steel-1-submission\/output#Export-File\ndef get_predictions(path_test, learn):\n    # predicts = get_predictions(path_test, learn)\n    learn.model.cuda()\n    files = list(path_test.glob(\"**\/*.jpg\"))    #<---------- HERE\n    test_count = len(files)\n    results = []\n    for i, img in enumerate(files):\n        img_name = img.stem + '.jpg'\n        pred = learn.predict(open_image(img))[1].data.numpy().flatten()\n        class_dict = run_length(pred)\n        if len(class_dict) == 0:\n            for i in range(4):\n                results.append([img_name+ \"_\" + str(i+1), ''])\n        else:\n            for key, val in class_dict.items():\n                results.append([img_name + \"_\" + str(key+1), \" \".join(map(str, val))])\n            for i in range(4):\n                if i not in class_dict.keys():\n                    results.append([img_name + \"_\" + str(i+1), ''])\n        \n        \n        if i%20==0:\n            print(\"\\r{}\/{}\".format(i, test_count), end=\"\")\n    return results    \n\nsub_list = get_predictions(path_test, learn)\n\n\nsubmission_df = pd.DataFrame(sub_list, columns=['ImageId_ClassId', 'EncodedPixels'])\nsubmission_df.head()\nsubmission_df.to_csv(\"submission.csv\", index=False)\nend = time.time()\nhours, rem = divmod(end-start, 3600)\nminutes, seconds = divmod(rem, 60)\nprint(\"Execution Time  {:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds))","meta":"{'source': 'AI4Code', 'id': '649aeaea4ece34'}"}
{"id":"49012","text":"# 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\nos.chdir(\"..\/input\")\nos.listdir()\n\"\"\"\n## Data Read\n\"\"\"\ndf=pd.read_csv(\"..\/input\/eeg-clean\/eeg_clean.csv\")\n\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\ndf.head()\ndf.info()\ndf.isnull().sum()\nprint(df[\"eye\"].value_counts())\ndf.eye=[1 if each ==\"Open\" else 0 for each in df.eye]\ndf.info()\ny = df[\"eye\"].values\nX = df.drop(['eye'], axis=1).values\n# Data Standardization \nfrom sklearn.preprocessing import StandardScaler\nScaler=StandardScaler()\nX=Scaler.fit_transform(X)\n\nX[0:3]\nfrom sklearn.model_selection import train_test_split\n# shuffle and split training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,\n                                                    random_state=0)\n# Multi Layer Perceptron Artificial Neural Network\nfrom sklearn.neural_network import MLPClassifier \n\n# Setting up a primitive (non-validated) model\nmlpc = MLPClassifier(random_state = 0)# ANN model object created\n\nmlpc.fit(X_train, y_train) # ANN model object fit\n# Forecasting on the Unvalidated Model\ny_pred = mlpc.predict(X_test) # model prediction process over test set\nimport sklearn.metrics as metrics\n\n# Accuracy\n\nprint(\"Accuracy:\",metrics.accuracy_score(y_test,y_pred))\n\n# f1 score\n\nprint(\"f1_weighted:\",metrics.f1_score(y_test, y_pred,average='weighted'))\n\"\"\"\n## Grid Search Cross Validation\n\"\"\"\n# Cross Validation Process\n# Parameters for CV created in dictionary structure\n# INFORMATION ABOUT THE INPUTED PARAMETERS\n# alpha: float, default = 0.0001 L2 penalty (regularization term) parameter. (penalty parameter)\n   \nmlpc_params = {\"alpha\": [0.1, 0.01, 0.001],\n              \"hidden_layer_sizes\": [(100,100),\n                                     (100,100,100)],\n              \"solver\" : [\"adam\",\"sgd\"],\n              \"activation\": [\"relu\",\"logistic\"]}\n\nfrom sklearn.model_selection import GridSearchCV\n\n\n\n\nmlpc = MLPClassifier(random_state = 0) # ANN model object created\n\n# Model CV process \nmlpc_cv_model = GridSearchCV(mlpc, mlpc_params, \n                         cv = 5, # To make a 5-fold CV\n                         n_jobs = -1, # Number of jobs to be run in parallel (-1: means to use all processors)\n                         verbose = 2) # Controls the level of detail: higher means more messages gets value as integer.\n\nmlpc_cv_model.fit(X_train, y_train) \n\n\n# The best parameter obtained as a result of CV process\n\nprint(\"The best parameters: \" + str(mlpc_cv_model.best_params_))\n# Setting the Final Model with the best parameter\n\nmlpc_tuned = mlpc_cv_model.best_estimator_\n\n# Fitting Final Model\nmlpc_tuned.fit(X_train, y_train)\n# K-fold f1_weighted\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\n# K fold\nkf = KFold(shuffle=True, n_splits=5) # To make a 5-fold CV\n\ncv_results_kfold = cross_val_score(mlpc_tuned, X_test, y_test, cv=kf, scoring= 'f1_weighted')\n\nprint(\"K-fold Cross Validation f1_weigted Results: \",cv_results_kfold)\nprint(\"K-fold Cross Validation f1_weigted Results Mean: \",cv_results_kfold.mean())\n# K-fold accuracy\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\n# K fold\nkf = KFold(shuffle=True, n_splits=5) # To make a 5-fold CV\n\ncv_results_kfold = cross_val_score(mlpc_tuned, X_test,y_test, cv=kf, scoring= 'accuracy')\n\nprint(\"K-fold Cross Validation accuracy Results: \",cv_results_kfold)\nprint(\"K-fold Cross Validation accuracy Results Mean: \",cv_results_kfold.mean())\n# Tune Model Prediction\n# Prediction process of Final Model over test set\ny_pred = mlpc_tuned.predict(X_test)\n# Accuracy and f1_weighted value of Final Model\n\n# %% f1 score\nimport sklearn.metrics as metrics\nprint(\"f1_weighted:\",metrics.f1_score(y_test, y_pred,average='weighted'))\n\n# %% Accuracy\n\nprint(\"accuracy:\",metrics.accuracy_score(y_test, y_pred))\n#%% Confusion Matrix and Classification Report\nfrom sklearn.metrics import confusion_matrix, classification_report \n\n# Classification Report\nmodel_report = classification_report(y_test, y_pred)\nprint(model_report)\n# Confusion Matrix\n# multilabel-indicator is not supported so np.argmax should be used!\nmodel_conf = confusion_matrix(y_test,y_pred)\nprint(model_conf)\n#%% ROC-AUC Curve\nimport matplotlib.pyplot as plt\n\n\n\nprobs=mlpc_tuned.predict_proba(X_test)\nfpr,tpr,threshold=metrics.roc_curve(y_test,y_pred)\nroc_auc=metrics.auc(fpr,tpr)\n\n\n\n\nplt.title(\"ROC\")\nplt.plot(fpr,tpr,label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy',  linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.0])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()","meta":"{'source': 'AI4Code', 'id': '5a41ee1dd87a6e'}"}
{"id":"133995","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n# Read datas\nmedian_house_hold_in_come = pd.read_csv('..\/input\/MedianHouseholdIncome2015.csv', encoding=\"windows-1252\")\npercentage_people_below_poverty_level = pd.read_csv('..\/input\/PercentagePeopleBelowPovertyLevel.csv', encoding=\"windows-1252\")\npercent_over_25_completed_highSchool = pd.read_csv('..\/input\/PercentOver25CompletedHighSchool.csv', encoding=\"windows-1252\")\nshare_race_city = pd.read_csv('..\/input\/ShareRaceByCity.csv', encoding=\"windows-1252\")\nkill = pd.read_csv('..\/input\/PoliceKillingsUS.csv', encoding=\"windows-1252\")\npercentage_people_below_poverty_level.head()\npercentage_people_below_poverty_level.info()\npercentage_people_below_poverty_level.poverty_rate.value_counts()\npercentage_people_below_poverty_level['Geographic Area'].unique()#show us the states of USA\n#len (percentage_people_below_poverty_level['Geographic Area'].unique())#show us the states of USA\n# Poverty rate of each state\npercentage_people_below_poverty_level.poverty_rate.replace(['-'],0.0,inplace = True)\npercentage_people_below_poverty_level.poverty_rate = percentage_people_below_poverty_level.poverty_rate.astype(float)#poverty_rate can not be object\narea_list = list(percentage_people_below_poverty_level['Geographic Area'].unique())\narea_poverty_ratio = []\nfor i in area_list:\n    x = percentage_people_below_poverty_level[percentage_people_below_poverty_level['Geographic Area']==i]#take one state but all rows\n    area_poverty_rate = sum(x.poverty_rate)\/len(x)#x state avarage of poverty\n    area_poverty_ratio.append(area_poverty_rate)#add avarage the series\ndata = pd.DataFrame({'area_list': area_list,'area_poverty_ratio':area_poverty_ratio})#new dataframe list two column\nnew_index = (data['area_poverty_ratio'].sort_values(ascending=False)).index.values#change index by poverty ratio sequence \n#print (type(new_index)) this is an array\n#print (new_index)\nsorted_data = data.reindex(new_index)#reindex command is regenarate index by new_index\n# visualization\nplt.figure(figsize=(15,10))\nsns.barplot(x=sorted_data['area_list'], y=sorted_data['area_poverty_ratio'])\nplt.xticks(rotation= 45)\nplt.xlabel('States')\nplt.ylabel('Poverty Rate')\nplt.title('Poverty Rate Given States')\nkill.info()\nkill.head()\nkill.name.value_counts()\nseperate= kill.name[kill.name !='TK TK'].str.split()\n#print(seperate) #like an array :  [Tim, Elliot]\na,b=zip(*seperate)#zip is use to transform array to tuple \n#print(a,b) --('Tim', 'Lewis', 'John',.... ) name and surname\nname_list=a+b\n#print (name_list)\nname_count = Counter(name_list) \n#print(name_count)\nmost_common_names = name_count.most_common(15) #most used 15 names and numbers in sheet\nx,y = zip(*most_common_names)#x replace of name y is taking numbers\n#print (x,y)\nx,y = list(x),list(y)#tupbles to array transform\n#print (x,y)\nplt.figure(figsize=(15,10))\nax= sns.barplot(x=x, y=y,palette = sns.cubehelix_palette(len(x)))#different diagram types cubehelix_palette by seaborn\nplt.xlabel('Name or Surname of killed people')\nplt.ylabel('Frequency')\nplt.title('Most common 15 Name or Surname of killed people')\n\n\npercent_over_25_completed_highSchool.head()\n\npercent_over_25_completed_highSchool.info()\nx=percent_over_25_completed_highSchool[percent_over_25_completed_highSchool['Geographic Area']=='AL']\nx\n# High school graduation rate of the population that is older than 25 in states\npercent_over_25_completed_highSchool.percent_completed_hs.replace('-',0.0,inplace=True)\npercent_over_25_completed_highSchool.percent_completed_hs=percent_over_25_completed_highSchool.percent_completed_hs.astype(float)\narea_list =list (percent_over_25_completed_highSchool['Geographic Area'].unique())\narea_highschool=[]\nfor i in area_list:\n    x=percent_over_25_completed_highSchool[percent_over_25_completed_highSchool['Geographic Area']==i]\n    area_highschool_rate=sum(x.percent_completed_hs)\/len(x)\n    area_highschool.append(area_highschool_rate)\ndata=pd.DataFrame({'area_list':area_list,'area_highschool_ratio': area_highschool})\nnew_index=data.area_highschool_ratio.sort_values(ascending=True).index.values\n#print(new_index)\nsorted_data2=data.reindex(new_index)\n\nplt.figure(figsize=(15,10))\nsns.barplot(x=sorted_data2['area_list'],y=sorted_data2['area_highschool_ratio'])\nplt.xticks(rotation=90)\nplt.xlabel('States')\nplt.ylabel('High School Graduate Rate')\nplt.title(\"Percentage of Given State's Population Above 25 that Has Graduated High School\")\n    \nshare_race_city.head()\nshare_race_city.info()\n# Percentage of state's population according to races that are black,white,native american, asian and hispanic\nshare_race_city.replace(['-'],0.0,inplace = True)\nshare_race_city.replace(['(X)'],0.0,inplace = True)\nshare_race_city.loc[:,['share_white','share_black','share_native_american','share_asian','share_hispanic']] = share_race_city.loc[:,['share_white','share_black','share_native_american','share_asian','share_hispanic']].astype(float)\narea_list = list(share_race_city['Geographic area'].unique())\nshare_white = []\nshare_black = []\nshare_native_american = []\nshare_asian = []\nshare_hispanic = []\nfor i in area_list:\n    x = share_race_city[share_race_city['Geographic area']==i]\n    share_white.append(sum(x.share_white)\/len(x))\n    share_black.append(sum(x.share_black) \/ len(x))\n    share_native_american.append(sum(x.share_native_american) \/ len(x))\n    share_asian.append(sum(x.share_asian) \/ len(x))\n    share_hispanic.append(sum(x.share_hispanic) \/ len(x))\n\n# visualization\nf,ax = plt.subplots(figsize = (9,15))\nsns.barplot(x=share_white,y=area_list,color='green',alpha = 0.5,label='White' )\nsns.barplot(x=share_black,y=area_list,color='blue',alpha = 0.7,label='African American')\nsns.barplot(x=share_native_american,y=area_list,color='cyan',alpha = 0.6,label='Native American')\nsns.barplot(x=share_asian,y=area_list,color='yellow',alpha = 0.6,label='Asian')\nsns.barplot(x=share_hispanic,y=area_list,color='red',alpha = 0.6,label='Hispanic')\n\nax.legend(loc='lower right',frameon = True)     # legendlarin gorunurlugu\nax.set(xlabel='Percentage of Races', ylabel='States',title = \"Percentage of State's Population According to Races \")\nplt.show()\n# high school graduation rate vs Poverty rate of each state\nsorted_data['area_poverty_ratio'] = sorted_data['area_poverty_ratio']\/max( sorted_data['area_poverty_ratio'])\nsorted_data2['area_highschool_ratio'] = sorted_data2['area_highschool_ratio']\/max( sorted_data2['area_highschool_ratio'])\ndata = pd.concat([sorted_data,sorted_data2['area_highschool_ratio']],axis=1)\ndata.sort_values('area_poverty_ratio',inplace=True)\n\n# visualize\nf,ax1 = plt.subplots(figsize =(20,10))\nsns.pointplot(x='area_list',y='area_poverty_ratio',data=data,color='lime',alpha=0.8)\nsns.pointplot(x='area_list',y='area_highschool_ratio',data=data,color='red',alpha=0.8)\nplt.text(40,0.6,'high school graduate ratio',color='red',fontsize = 17,style = 'italic')\nplt.text(40,0.55,'poverty ratio',color='lime',fontsize = 18,style = 'italic')\nplt.xlabel('States',fontsize = 15,color='blue')\nplt.ylabel('Values',fontsize = 15,color='blue')\nplt.title('High School Graduate  VS  Poverty Rate',fontsize = 20,color='blue')\nplt.grid()\n# Visualization of high school graduation rate vs Poverty rate of each state with different style of seaborn code\n# joint kernel density\n# pearsonr= if it is 1, there is positive correlation and if it is, -1 there is negative correlation.\n# If it is zero, there is no correlation between variables\n# Show the joint distribution using kernel density estimation \ng = sns.jointplot(data.area_poverty_ratio, data.area_highschool_ratio, kind=\"kde\", height=7)\nplt.savefig('graph.png')#save the figure kaggle's page. \n\nplt.show()\n\"\"\"\nAbove graph shows that the number of people is graduate from high school go up while poverty is down. Which means graduate from school connected to wealthy. \nBut something about poverty is point of 0.5. Mostly graduate from high school people poverty is 0.5 poverty ratio. Maybe it is show that the American people has poverty percentage is mostly 0.5.\n\"\"\"\n# you can change parameters of joint plot\n# kind : { \u201cscatter\u201d | \u201creg\u201d | \u201cresid\u201d | \u201ckde\u201d | \u201chex\u201d }\n# Different usage of parameters but same plot with previous one\ng = sns.jointplot(\"area_poverty_ratio\", \"area_highschool_ratio\", data=data,height=5, ratio=3, color=\"r\")\n#combine tow gragh with plot_joint. n_levels is number of line in the graph.\ng = (sns.jointplot(\"area_poverty_ratio\", \"area_highschool_ratio\", data=data,height=5, ratio=3, color=\"r\").plot_joint(sns.kdeplot, zorder=0, n_levels=6))\ng = sns.jointplot(data.area_poverty_ratio, data.area_highschool_ratio, kind=\"reg\", height=7)\nplt.show()\nkill.head()\nkill.race.value_counts()\n#pie chart is member of matplot libraray\nkill.race.dropna(inplace=True)#delete nan value rows\nlabels=kill.race.value_counts().index#assign of grouped value of race in index\ncolors = ['grey','blue','red','yellow','green','brown']\nexplode = [0.1,0.1,0.1,0.1,0.1,0.1] #throw the slice\nsizes = kill.race.value_counts().values#value count of numbers in to sizes \n\nplt.figure(figsize=(7,7))\nplt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%')\nplt.title('Killed People According to Races',color='black',fontsize=15)\n# kdeplot\nsns.kdeplot(data.area_poverty_ratio, data.area_highschool_ratio, shade=True, cut=3)#cut is size of shape in the graph, shade is fill in shape with color\nplt.show()\n# Show each distribution with both violins and points\n# Use cubehelix to get a custom sequential palette\npal = sns.cubehelix_palette(2, rot=-.5, dark=.3)#it is like cumulation of each part on the same graph\nsns.violinplot(data=data, palette=pal, inner=\"points\")#use data dataframe and pal for palette and inner=\"points\" is point in the shape\nplt.show()\n#correlation map\n# Visualization of high school graduation rate vs Poverty rate of each state with different style of seaborn code\nf,ax = plt.subplots(figsize=(5, 5))\nsns.heatmap(data.corr(), annot=True, linewidths=0.5,linecolor=\"red\", fmt= '.1f',ax=ax)\n#annot=True is visualation of numbers in the rectangle\n#ax=ax is establish the heatmap in to the generated plot. \nplt.show()\n\"\"\"\n**Gender - Age - Manner of Death with Box Plot**\n\nGraph on the below explain that killed man by shot average age is little than killed by shot and Tasered. And we can see that killed male or female average age is close. But killed man numbers and killed female numbers is different but in this chart the shapes size are same. So, in this chart shape about only manner of death, not about count.\n\"\"\"\nkill.head()\nkill.head()\n\na=kill.groupby(['state','race'], as_index=False).agg({\"id\": \"count\"})\na=a.sort_values('id', ascending=False)\n\na.head()\n#Killed people and number of races state by state\n#for example most people killed in CA and their races is Hispanic, second is white\nf,ax1 = plt.subplots(figsize =(20,10))\nsns.swarmplot(x=\"state\", y=\"id\",hue=\"race\", data=a)\nplt.show()\n# visualize\nf,ax1 = plt.subplots(figsize =(20,10))\nsns.pointplot(x='state',y='id',data=a,color='lime',alpha=0.8)\nplt.text(40,0.6,'high school graduate ratio',color='red',fontsize = 17,style = 'italic')\nplt.text(40,0.55,'poverty ratio',color='lime',fontsize = 18,style = 'italic')\nplt.xlabel('States',fontsize = 15,color='blue')\nplt.ylabel('COUNTS',fontsize = 15,color='blue')\nplt.title('Killed People - States',fontsize = 20,color='blue')\nplt.grid()\n#x is gender, y is age and distirbution about manner of death. we use as data 'kill' and colouring palette 'PRGn'=Purple-Green\nsns.boxplot(x='gender', y='age',hue='manner_of_death', data=kill, palette='PRGn')\nplt.show()\n\"\"\"\nDifference from boxplot we can see the actual counts and nice design, but we cant see the average ages\nNot: Swarmplot performance is down when records 10K. \n\"\"\"\nsns.swarmplot(x=\"gender\", y=\"age\",hue=\"manner_of_death\", data=kill)\nplt.show()\n#Pairplot shows us to 4 chart and 2 is point others line plot. And x  and y values are changing.\nsns.pairplot(data)\nplt.show()\nsns.countplot(kill.gender)\n#sns.countplot(kill.manner_of_death)\nplt.title(\"gender\",color = 'blue',fontsize=15)\nsns.countplot(kill.manner_of_death)\nplt.title(\"manner of death\" , color='blue', fontsize=15)\narmed=kill.armed.value_counts()#armed occur from two colomns that index is name of arm and values is number of used.\n#print(armed)\nplt.figure(figsize=(10,7))\nsns.barplot(x=armed[:7].index,y=armed[:7].values)\nplt.xlabel('Weapon Types')\nplt.ylabel('Weapon Numbers')\nplt.title('Kill weapon',color = 'blue',fontsize=15)\nplt.show()\nabove25=['above25' if i>25 else 'below25' for i in kill.age]#we choose and create a list \ndf=pd.DataFrame({'age':above25})\n#print (df)\nsns.countplot(x=df.age)#we determine the x axis here\nplt.ylabel('Number of Killed People')\nplt.title('Age of killed people',color = 'blue',fontsize=15)\nplt.show()\nsns.countplot(data=kill, x='race')#another using of countplot; we can give data and x axis like this <-\nplt.title('Race of killed people',color = 'blue',fontsize=15)\nplt.show()\nkill.head()\n#a=kill.set_index(['race','city']).count(level=\"race\")\n#kill.city.dropna(inplace=True)\na=kill.sort_values(by=['race'])\na\narea_list = list(kill['city'].unique())\nshare_white1 = []\nshare_black1 = []\nshare_native_american1 = []\nshare_asian1 = []\nshare_hispanic1 = []\nfor i in area_list:\n    x = kill[kill['city']==i]\n# Most dangerous cities\ncity=kill.city.value_counts()\nplt.figure(figsize=(12,10))\nsns.barplot(x=city[:12].index, y=city[:12].values)\nplt.xticks(rotation=45)\nplt.xlabel('Cities')\nplt.ylabel('Number of Killed People')\nplt.title(' Most dangerous cities',color = 'blue',fontsize=15)\nplt.show()\n\n\n# Most dangerous cities\nstates=kill.state.value_counts()\nplt.figure(figsize=(12,10))\nsns.barplot(x=states[:12].index, y=states[:12].values)\nplt.xticks(rotation=45)\nplt.xlabel('States')\nplt.ylabel('Number of Killed People')\nplt.title(' Most dangerous states',color = 'blue',fontsize=15)\nplt.show()\nsns.countplot(kill.signs_of_mental_illness)\nplt.xlabel('Mental illness')\nplt.ylabel('Number of Mental illness')\nplt.title('Having mental illness or not',color = 'blue', fontsize = 15)\nplt.show()\nsns.countplot(kill.threat_level)\nplt.xlabel('Threat Types')\nplt.title('Threat types',color = 'blue', fontsize = 15)\nplt.show()\n# Flee types\nsns.countplot(kill.flee)\nplt.xlabel('Flee Types')\nplt.title('Flee types',color = 'blue', fontsize = 15)","meta":"{'source': 'AI4Code', 'id': 'f66ba010780cb8'}"}
{"id":"94741","text":"# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\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\n\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\ndf_train=pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\ndf_test=pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\nprint(len(df_train.columns))\nprint(len(df_test.columns))\nnavalues= df_train.isnull().sum().sort_values(ascending=False)\npercent = (df_train.isnull().sum()\/df_train.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([navalues, percent], axis=1, keys=['navalues_train', 'Percent'])\nmissing_data.head(20)\n#dropping values of train\ndf_train=df_train.drop(missing_data[missing_data['navalues_train']>1].index,1)\ndf_train = df_train.drop(df_train.loc[df_train['Electrical'].isnull()].index)\nprint(df_train.isnull().sum().max())\n\ndf_train.head(5)\ndf_train1=df_train[['MSSubClass','OverallQual','LotArea','OverallCond','YearBuilt','TotalBsmtSF','TotRmsAbvGrd','YrSold','SalePrice']]\ncorrmat = df_train1.corr()\ntop_corr_features = corrmat.index\nplt.figure(figsize=(20,20))\n#plot heat map\ng=sns.heatmap(df_train1[top_corr_features].corr(),annot=True,cmap=\"RdYlGn\")\ntrain=df_train1[['OverallQual','LotArea','YearBuilt','TotalBsmtSF','TotRmsAbvGrd','SalePrice']]\n\nX = train.iloc[:, :-1].values\ny = train.iloc[:, -1].values\ntestfeat=df_test[['OverallQual','LotArea','YearBuilt','TotalBsmtSF','TotRmsAbvGrd']]\ntestfeat.isnull().sum().sum()\nnavalues= testfeat.isnull().sum().sort_values(ascending=False)\nprint(navalues)\ntestfeat['TotalBsmtSF'].fillna((testfeat['TotalBsmtSF'].mean()), inplace=True)\ntestfeat.isnull().sum().sum()\nXtestfeat=testfeat.iloc[:, :].values\ny=y.reshape(len(y),1)\n\"\"\"\n# Linear Regression\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.2,random_state=1)\nfrom sklearn.linear_model import LinearRegression\nlm= LinearRegression()\nlm.fit(X_train,y_train)\nypred=lm.predict(X_test)\nnp.set_printoptions(precision=2)\nprint(np.concatenate((ypred,y_test),1))\nfrom sklearn.metrics import r2_score\nr2_score(y_test, ypred)\nfrom sklearn import metrics\nprint('MAE:', metrics.mean_absolute_error(y_test, ypred))\nprint('MSE:', metrics.mean_squared_error(y_test, ypred))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, ypred)))\n\"\"\"\n# Support Vector Regression\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.2,random_state=1)\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nsc_y = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\ny_train = sc_y.fit_transform(y_train)\nfrom sklearn.svm import SVR\nSVregressor = SVR(kernel = 'rbf')\nSVregressor.fit(X_train, y_train)\ny_predSVM =sc_y.inverse_transform(SVregressor.predict(sc_X.transform(X_test)))\nnp.set_printoptions(precision=2)\nprint(np.concatenate((y_predSVM.reshape(len(y_predSVM),1), y_test.reshape(len(y_test),1)),1))\nfrom sklearn.metrics import r2_score\nr2_score(y_test, y_predSVM)\n\"\"\"\n# Decision Tree Regression\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)\nfrom sklearn.tree import DecisionTreeRegressor\nDTregressor = DecisionTreeRegressor(random_state = 1)\nDTregressor.fit(X_train, y_train)\ny_predDT = DTregressor.predict(X_test)\nnp.set_printoptions(precision=2)\nprint(np.concatenate((y_predDT.reshape(len(y_predDT),1), y_test.reshape(len(y_test),1)),1))\nfrom sklearn.metrics import r2_score\nr2_score(y_test, y_predDT)\n\"\"\"\n# Random Forest\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)\nfrom sklearn.ensemble import RandomForestRegressor\nRFregressor = RandomForestRegressor(n_estimators = 10, random_state = 0)\nRFregressor.fit(X_train, y_train)\ny_predRF = RFregressor.predict(X_test)\nnp.set_printoptions(precision=2)\nprint(np.concatenate((y_predRF.reshape(len(y_predRF),1), y_test.reshape(len(y_test),1)),1))\nfrom sklearn.metrics import r2_score\nr2_score(y_test, y_predRF)\n\"\"\"\n# Since SVR has the best R2 Score\n\"\"\"\ntestpredSVM=sc_y.inverse_transform(SVregressor.predict(sc_X.transform(Xtestfeat)))\ntestpredSVM\ntestpred=pd.DataFrame(testpredSVM)\nsub_df=pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/sample_submission.csv')\ndatasets=pd.concat([sub_df['Id'],testpred],axis=1)\ndatasets.columns=['Id','SalePrice']\ndatasets.to_csv('sample_submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'adec30516bc274'}"}
{"id":"134075","text":"# 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\n!unzip -q -o '\/kaggle\/input\/dogs-vs-cats-redux-kernels-edition\/train.zip'\n!unzip -q -o '\/kaggle\/input\/dogs-vs-cats-redux-kernels-edition\/test.zip'\n# test\/10007.jpg\n# train\/cat.4511.jpg\nfrom PIL import Image\n\nImage.open('train\/cat.4511.jpg')\nimport glob\n\ntrain = pd.DataFrame({'path' : glob.glob('train\/*')})\ntrain.head(2)\ntrain['target'] = train['path'].apply(lambda x: x.split('\/')[1].split('.')[0])\ntrain\nfrom keras.preprocessing.image import ImageDataGenerator\n\"\"\"\n## 1. \uc810\uc218 \uc62c\ub9ac\uae30 -> data augmentation\n\"\"\"\nidg = ImageDataGenerator()\nidg2 = ImageDataGenerator(horizontal_flip = True, brightness_range = [0.2,1.0])\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_valid = train_test_split(train, test_size = 0.2, random_state = 42, \n                                   stratify = train['target'])\nx_valid['target'].value_counts()\nx_train['target'].value_counts()\ntrain_generator = idg2.flow_from_dataframe(x_train, x_col = 'path', y_col = 'target',\n                                         target_size = (300,300))\nvalid_generator = idg.flow_from_dataframe(x_valid, x_col = 'path', y_col = 'target',\n                                         target_size = (300,300))\nimport matplotlib.pyplot as plt\n\n\nplt.figure(figsize = (12,12))\nfor i in range(0,15):\n    plt.subplot(5,3,i+1)\n    for x, y in train_generator:\n        image = x[0]\n        plt.imshow(image.astype('uint8'))\n        break\n# plt.tight_layout()\nplt.show()\n\"\"\"\n## 2. \uc810\uc218\uc62c\ub9ac\uae30 --> \ubaa8\ub378\uc744 B0 -> B1\n\"\"\"\nfrom tensorflow.keras import Sequential\n\nfrom tensorflow.keras.layers import *\n\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications import EfficientNetB1\neb0 = EfficientNetB0(include_top = False, pooling = 'avg')\neb1 = EfficientNetB1(include_top = False, pooling = 'avg')\nmodel = Sequential()\n\nmodel.add(eb1)\nmodel.add(Dense(2, activation = 'softmax'))\n\nfrom tensorflow.keras.optimizers import SGD\n\nmodel.compile(metrics = ['acc'], loss = 'categorical_crossentropy',\n             optimizer = SGD(momentum = 0.9 , nesterov = True, lr = 0.01))\nmodel.summary()\n\"\"\"\n## 3. \uc810\uc218\uc62c\ub9ac\uae30-  callback \ud568\uc218 \ucd94\uac00\n\"\"\"\n##callback\n\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nes = EarlyStopping(patience = 5, verbose = 1)\n\nmc = ModelCheckpoint('best.h5', save_best_only = True, verbose = 1)\n\nrl = ReduceLROnPlateau(patience = 3, verbose = 1)\nmodel.fit(train_generator, epochs = 100, callbacks = [es, mc, rl], validation_data = valid_generator)\ntest = pd.DataFrame({'path' : glob.glob('test\/*')})\ntest_generator = idg.flow_from_dataframe(test, x_col = 'path', y_col = None,\n                                        class_mode = None, target_size = (300,300),\n                                        shuffle = False)\nresult  = model.predict(test_generator, verbose=  1)\nresult\nfrom keras.preprocessing.image import load_img\n\n\nn = 10\nfor i, (index, row) in enumerate(test.iterrows()):\n    if i >= n:\n        break\n    fig = plt.figure(figsize=(8, 32))\n    img = load_img(row['path'], target_size=(100, 100))\n    subfig = fig.add_subplot(n, 1, i + 1)\n    pred = result[i][0]\n    pred_label = 'cat' if pred > 0.5 else 'dog'\n    pred = pred if pred > 0.5 else 1-pred\n    plt.title('Looks like a {0} with probability {1}'.format(pred_label, pred))\n    f = plt.imshow(img)\n    f.axes.get_xaxis().set_visible(False)\n    f.axes.get_yaxis().set_visible(False)\nsub= pd.read_csv('\/kaggle\/input\/dogs-vs-cats-redux-kernels-edition\/sample_submission.csv')\nsub\nsub['id'] = test['path'].apply(lambda x : x.split('\/')[1].split('.')[0] )\nsub['label'] = result[:,1].clip(0.005, 0.995)\nsub\nsub.to_csv('base.csv', index = 0)\n\"\"\"\n### 4. \uc810\uc218\uc62c\ub9ac\uae30 - Ensemble (Blending, Stacking..) Blending\n\"\"\"\n# csv1 = pd.read_csv('\/kaggle\/input\/ensemble\/DogVsCats_submission (7).csv')\n# csv2 = pd.read_csv('\/kaggle\/input\/ensemble\/DogVsCats_submission (1) (3).csv')\n\n# csv1 = csv1.sort_values('id').reset_index(drop = True)\n# csv2 = csv2.sort_values('id').reset_index(drop = True)\n\n# sub = pd.read_csv('\/kaggle\/input\/dogs-vs-cats-redux-kernels-edition\/sample_submission.csv')\n# sub['label'] = (csv1['label'] * 0.5) + (csv2['label'] *0.5)\n# sub.to_csv('sub1.csv', index = 0)","meta":"{'source': 'AI4Code', 'id': 'f68e4dcba34ad8'}"}
{"id":"96510","text":"# 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)\nimport plotly.express as px\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\n\"\"\"\n# Data Preparation\n\"\"\"\n# pulling in the main datasets\ndata_gb = pd.read_csv('\/kaggle\/input\/youtube-new\/GBvideos.csv') # uk\ndata_ca = pd.read_csv('\/kaggle\/input\/youtube-new\/CAvideos.csv') # canada\ndata_us = pd.read_csv('\/kaggle\/input\/youtube-new\/USvideos.csv') # us\ndata_in = pd.read_csv('\/kaggle\/input\/youtube-new\/INvideos.csv') # india\ndata_de = pd.read_csv('\/kaggle\/input\/youtube-new\/DEvideos.csv') # germany\n\n# add new columns to identify the region\ndata_gb['region'] = 'UK'\ndata_ca['region'] = 'Canada'\ndata_us['region'] = 'US'\ndata_in['region'] = 'India'\ndata_de['region'] = 'Germany'\n\n# to make sure that the structure of the datasets are the same\nprint(data_gb.columns == data_ca.columns)\nprint(data_gb.columns == data_us.columns)\nprint(data_gb.columns == data_in.columns)\nprint(data_gb.columns == data_de.columns)\ndata_us.info()\ndata_us.sample(5)\n#pulling in the category datasets\ndata_gb_cat_json = pd.read_json('\/kaggle\/input\/youtube-new\/GB_category_id.json')\ndata_gb_cat = pd.json_normalize(data_gb_cat_json['items'])\n\ndata_ca_cat_json = pd.read_json('\/kaggle\/input\/youtube-new\/CA_category_id.json')\ndata_ca_cat = pd.json_normalize(data_ca_cat_json['items'])\n\ndata_us_cat_json = pd.read_json('\/kaggle\/input\/youtube-new\/US_category_id.json')\ndata_us_cat = pd.json_normalize(data_us_cat_json['items'])\n\ndata_in_cat_json = pd.read_json('\/kaggle\/input\/youtube-new\/IN_category_id.json')\ndata_in_cat = pd.json_normalize(data_in_cat_json['items'])\n\ndata_de_cat_json = pd.read_json('\/kaggle\/input\/youtube-new\/DE_category_id.json')\ndata_de_cat = pd.json_normalize(data_de_cat_json['items'])\n\n# change the id column to 'int64' so that we can match them in the merge function below (need to have the same datatype)\ndata_gb_cat['id'] = data_gb_cat['id'].astype('int64')\ndata_ca_cat['id'] = data_ca_cat['id'].astype('int64')\ndata_us_cat['id'] = data_us_cat['id'].astype('int64')\ndata_in_cat['id'] = data_in_cat['id'].astype('int64')\ndata_de_cat['id'] = data_de_cat['id'].astype('int64')\n# these are the columns we will keep\ncols_to_keep = ['region','title', 'channel_title','snippet.title','publish_time','views','likes','dislikes','comment_count','comments_disabled','ratings_disabled']\n#merging the main datasets and the category datasets\ndata_gb_new = data_gb.merge(data_gb_cat, left_on='category_id', right_on='id', how='left')\ndata_gb_new = data_gb_new[cols_to_keep]\n\ndata_ca_new = data_ca.merge(data_gb_cat, left_on='category_id', right_on='id', how='left')\ndata_ca_new = data_ca_new[cols_to_keep]\n\ndata_us_new = data_us.merge(data_gb_cat, left_on='category_id', right_on='id', how='left')\ndata_us_new = data_us_new[cols_to_keep]\n\ndata_in_new = data_in.merge(data_gb_cat, left_on='category_id', right_on='id', how='left')\ndata_in_new = data_in_new[cols_to_keep]\n\ndata_de_new = data_de.merge(data_gb_cat, left_on='category_id', right_on='id', how='left')\ndata_de_new = data_de_new[cols_to_keep]\n\"\"\"\n# Combining data from different regions\n\"\"\"\ndata_final = pd.concat([data_gb_new, data_ca_new, data_us_new, data_in_new, data_de_new], axis=0)\ndata_final.rename(columns={'snippet.title' : 'video_category'}, inplace=True)\ndata_final.shape[0] - data_final.count() # nan values under 'video category' column\ndata_final[data_final['video_category'].isnull() == True]\n\"\"\"\n# Data Cleanup\n\"\"\"\n# fill the nan values under 'video_category' with 'No category'\ndata_final['video_category'].fillna('No category', inplace=True)\ndata_final['upload_date'] = pd.to_datetime(data_final['publish_time'].str[:10], format='%Y-%m-%d')\ndata_final['upload_date_year_month'] = pd.to_datetime(data_final['publish_time'].str[:7], format='%Y-%m')\n\ndata_final['upload_year'] = data_final['upload_date'].dt.year\ndata_final['upload_month'] = data_final['upload_date'].dt.month\n\ndata_final.drop('publish_time', axis=1, inplace=True)\ndata_final['likes_%_of_view'] = (data_final['likes'] \/ data_final['views']) * 100 # percentage of likes as a proportion of views\ndata_final['dislikes_%_of_view'] = (data_final['dislikes'] \/ data_final['views']) * 100 # percentage of dislikes as a proportion of views\ndata_final['comment_%_of_view'] = (data_final['comment_count'] \/ data_final['views']) * 100 # percentage of comment count as a proportion of views\n\ndata_final['comments_disabled'].replace({False : 'No', True:'Yes'}, inplace=True)\ndata_final['ratings_disabled'].replace({False : 'No', True:'Yes'}, inplace=True)\n\"\"\"\n# Basic Data Exploration on Cleaned-Up Dataset\n\"\"\"\ndata_final.info()\ndata_final.sample(5)\ndata_final.groupby('upload_year')[['views','likes','dislikes','comment_count']].sum().reset_index()\n\n# observations:\n#1 from 2016 to 2017, major increase in views\na = data_final.pivot_table(index='upload_year', columns='region', aggfunc='sum', values='views')\na[[i for i in a.columns if i not in ['region','upload_year']]] = a[[i for i in a.columns if i not in ['region','upload_year']]] \/ 1000000\na.rename(columns=lambda x : x + ' Views in M', inplace=True)\n\n# generating the percentage change in views for each year for each region\nb = a[[i for i in a.columns if i not in ['region','upload_year']]].pct_change() * 100\nb.rename(columns=lambda x : x + ' % Change', inplace=True)\n\nc = pd.concat([a,b], axis=1).sort_index(axis=1)\nc.round(1)\n\n# observations\n#1 2017 and 2018 was where most regions experienced 'significant' growth in viewership of Youtube videos\n\"\"\"\n# Data Visualization\n\"\"\"\n\"\"\"\n# Views Across Region Over Time\n\"\"\"\ndata_selected_year = data_final[data_final['upload_year'].isin([2017,2018])]\ndata_selected_year_by_year = data_selected_year.groupby(['upload_date_year_month','region'])[['views']].sum().reset_index()\n\n\nfig = px.line(data_selected_year_by_year, x='upload_date_year_month', y='views', color='region')\nfig.update_layout(title_text='Views Across Regions from 2017 to 2018', title_font_size=20, legend_title_text='Region',\\\n                 legend=dict(\n                            yanchor='top',\n                            y=0.99,\n                            xanchor='right',\n                            x=0.999)\n                 )\n\nfig.update_xaxes(showgrid = False)\nfig.update_yaxes(showgrid = False)\n\nfig.show()\n\"\"\"\n**Commentary:**\n\n* Views from UK was 'significantly' higher than other regions\n\n* Views from US was picking up in early 2018 and catching up to UK\n\n* Views from other regions were relatively consistent\n\"\"\"\n\"\"\"\n# Distribution of Likes\n\"\"\"\nfig = px.box(data_final, x = 'comments_disabled', y='likes_%_of_view', labels={'likes_%_of_view' : 'Percentage of Likes as a Proportion of Video Views'})\n\nfig.update_layout(title_text='Distribution of Likes % between Videos with Comments Enabled\/Disabled')\n\nfig.update_xaxes(showgrid = False)\nfig.update_yaxes(showgrid = False)\n\nfig.show()\n\"\"\"\n**Commentary:**\n\n* Videos with comments enabled generally have a wider spread of likes % as compared to videos with comments disabled\n\"\"\"\n\"\"\"\n# Views & Likes Across Regions\n\"\"\"\nfig = px.scatter(data_final, x='views',y = 'likes', color='region', facet_col='region', labels={'views':'Number of Views', 'likes':'Number of Likes'}, marginal_x ='histogram', height=1000, trendline='ols', trendline_color_override='black')\n\nfig.update_layout(title_text='Visual View Between Number of Views and Likes Across Regions', title_font_size=20, showlegend=False)\n\nfig.update_xaxes(showgrid = False)\nfig.update_yaxes(showgrid = False)\n\nfig.show()\n\"\"\"\n**Commentary:** \n\n* More views generally translate to more likes\n\"\"\"\n\"\"\"\n# Views & Like % Across Region\n\"\"\"\nfig = px.scatter(data_final, x='likes_%_of_view',y = 'views', color='region', facet_col='region', labels={'views':'Number of Views', 'likes_%_of_view':'% of Likes'}, marginal_x ='histogram', height=1000)\n\nfig.update_layout(title_text='Visual View Between Number of Views and and Percentage of Likes Across Regions', title_font_size=20, showlegend=False)\n\nfig.update_xaxes(showgrid = False)\nfig.update_yaxes(showgrid = False)\n\nfig.show()\n\"\"\"\n**Commentary** \n\n* When looking at the percentage of likes as a proportion of the video view count, videos with LOWER VIEW COUNT, generally have a HIGHER percentage of likes as a proportion of their video view count\n\"\"\"\n\"\"\"\n# Breakdown of Video Views by Category and Region\n\"\"\"\nfig = px.treemap(data_final, path=['video_category','region'], values='views', color='region')\n\nfig.update_layout(title_text='Breakdown of Video Views by Category and Region', title_font_size=20, showlegend=False)\n\nfig.show()\n\"\"\"\n**Commentary:**\n\n* Videos in the 'Music' category garnered the most views\n* UK dominated in most of the top categories \n\"\"\"\n\"\"\"\n# Views & Likes Across Video Categories\n\"\"\"\nfig = px.scatter(data_final, x='views',y = 'likes', color='region', facet_col='video_category', labels={'views':'Number of Views', 'likes':'Number of Likes'},facet_col_wrap = 4, height = 1000, opacity = 0.5)\nfig.update_layout(title_text='Visual View Between Number of Views and Likes Across Video Categories', title_font_size=20)\n\nfig.update_xaxes(showgrid = False)\nfig.update_yaxes(showgrid = False)\n\nfig.show()","meta":"{'source': 'AI4Code', 'id': 'b14a547be2a507'}"}
{"id":"1789","text":"\"\"\"\nHi, these kernel is forked by **BaselineModeling** And just copy the part of extra Meta-images and sentiment featuers.\nAnd save it to .csv\n\"\"\"\nimport gc\nimport glob\nimport os\nimport json\nimport matplotlib.pyplot as plt\nimport pprint\n\nimport numpy as np\nimport pandas as pd\n\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\nfrom PIL import Image\n\n%matplotlib inline\n\npd.options.display.max_rows = 128\npd.options.display.max_columns = 128\nplt.rcParams['figure.figsize'] = (12, 9)\n\"\"\"\n### load core DFs (train and test):\n\"\"\"\nos.listdir('..\/input\/test\/')\ntrain = pd.read_csv('..\/input\/train\/train.csv')\ntest = pd.read_csv('..\/input\/test\/test.csv')\nsample_submission = pd.read_csv('..\/input\/test\/sample_submission.csv')\n\"\"\"\n### load mapping dictionaries:\n\"\"\"\nlabels_breed = pd.read_csv('..\/input\/breed_labels.csv')\nlabels_state = pd.read_csv('..\/input\/color_labels.csv')\nlabels_color = pd.read_csv('..\/input\/state_labels.csv')\n\"\"\"\n### additional data:\n\nWe have also additional information about pets available in form of:\n\n- images\n- metadata\n- sentiment\n\nIntegration of those will enable us to possibly improve the score.\nInformation derived from example from images should be very important, as picture of a pet influences the way we look at an animal in a significant way.\n\"\"\"\ntrain_image_files = sorted(glob.glob('..\/input\/train_images\/*.jpg'))\ntrain_metadata_files = sorted(glob.glob('..\/input\/train_metadata\/*.json'))\ntrain_sentiment_files = sorted(glob.glob('..\/input\/train_sentiment\/*.json'))\n\nprint('num of train images files: {}'.format(len(train_image_files)))\nprint('num of train metadata files: {}'.format(len(train_metadata_files)))\nprint('num of train sentiment files: {}'.format(len(train_sentiment_files)))\n\n\ntest_image_files = sorted(glob.glob('..\/input\/test_images\/*.jpg'))\ntest_metadata_files = sorted(glob.glob('..\/input\/test_metadata\/*.json'))\ntest_sentiment_files = sorted(glob.glob('..\/input\/test_sentiment\/*.json'))\n\nprint('num of test images files: {}'.format(len(test_image_files)))\nprint('num of test metadata files: {}'.format(len(test_metadata_files)))\nprint('num of test sentiment files: {}'.format(len(test_sentiment_files)))\n\"\"\"\n### train analysis:\n\"\"\"\nplt.rcParams['figure.figsize'] = (12, 9)\nplt.style.use('ggplot')\n\n\n# Images:\ntrain_df_ids = train[['PetID']]\nprint(train_df_ids.shape)\n\ntrain_df_imgs = pd.DataFrame(train_image_files)\ntrain_df_imgs.columns = ['image_filename']\ntrain_imgs_pets = train_df_imgs['image_filename'].apply(lambda x: x.split('\/')[-1].split('-')[0])\ntrain_df_imgs = train_df_imgs.assign(PetID=train_imgs_pets)\nprint(len(train_imgs_pets.unique()))\n\npets_with_images = len(np.intersect1d(train_imgs_pets.unique(), train_df_ids['PetID'].unique()))\nprint('fraction of pets with images: {:.3f}'.format(pets_with_images \/ train_df_ids.shape[0]))\n\n# Metadata:\ntrain_df_ids = train[['PetID']]\ntrain_df_metadata = pd.DataFrame(train_metadata_files)\ntrain_df_metadata.columns = ['metadata_filename']\ntrain_metadata_pets = train_df_metadata['metadata_filename'].apply(lambda x: x.split('\/')[-1].split('-')[0])\ntrain_df_metadata = train_df_metadata.assign(PetID=train_metadata_pets)\nprint(len(train_metadata_pets.unique()))\n\npets_with_metadatas = len(np.intersect1d(train_metadata_pets.unique(), train_df_ids['PetID'].unique()))\nprint('fraction of pets with metadata: {:.3f}'.format(pets_with_metadatas \/ train_df_ids.shape[0]))\n\n# Sentiment:\ntrain_df_ids = train[['PetID']]\ntrain_df_sentiment = pd.DataFrame(train_sentiment_files)\ntrain_df_sentiment.columns = ['sentiment_filename']\ntrain_sentiment_pets = train_df_sentiment['sentiment_filename'].apply(lambda x: x.split('\/')[-1].split('.')[0])\ntrain_df_sentiment = train_df_sentiment.assign(PetID=train_sentiment_pets)\nprint(len(train_sentiment_pets.unique()))\n\npets_with_sentiments = len(np.intersect1d(train_sentiment_pets.unique(), train_df_ids['PetID'].unique()))\nprint('fraction of pets with sentiment: {:.3f}'.format(pets_with_sentiments \/ train_df_ids.shape[0]))\n# Images:\ntest_df_ids = test[['PetID']]\nprint(test_df_ids.shape)\n\ntest_df_imgs = pd.DataFrame(test_image_files)\ntest_df_imgs.columns = ['image_filename']\ntest_imgs_pets = test_df_imgs['image_filename'].apply(lambda x: x.split('\/')[-1].split('-')[0])\ntest_df_imgs = test_df_imgs.assign(PetID=test_imgs_pets)\nprint(len(test_imgs_pets.unique()))\n\npets_with_images = len(np.intersect1d(test_imgs_pets.unique(), test_df_ids['PetID'].unique()))\nprint('fraction of pets with images: {:.3f}'.format(pets_with_images \/ test_df_ids.shape[0]))\n\n\n# Metadata:\ntest_df_ids = test[['PetID']]\ntest_df_metadata = pd.DataFrame(test_metadata_files)\ntest_df_metadata.columns = ['metadata_filename']\ntest_metadata_pets = test_df_metadata['metadata_filename'].apply(lambda x: x.split('\/')[-1].split('-')[0])\ntest_df_metadata = test_df_metadata.assign(PetID=test_metadata_pets)\nprint(len(test_metadata_pets.unique()))\n\npets_with_metadatas = len(np.intersect1d(test_metadata_pets.unique(), test_df_ids['PetID'].unique()))\nprint('fraction of pets with metadata: {:.3f}'.format(pets_with_metadatas \/ test_df_ids.shape[0]))\n\n\n\n# Sentiment:\ntest_df_ids = test[['PetID']]\ntest_df_sentiment = pd.DataFrame(test_sentiment_files)\ntest_df_sentiment.columns = ['sentiment_filename']\ntest_sentiment_pets = test_df_sentiment['sentiment_filename'].apply(lambda x: x.split('\/')[-1].split('.')[0])\ntest_df_sentiment = test_df_sentiment.assign(PetID=test_sentiment_pets)\nprint(len(test_sentiment_pets.unique()))\n\npets_with_sentiments = len(np.intersect1d(test_sentiment_pets.unique(), test_df_ids['PetID'].unique()))\nprint('fraction of pets with sentiment: {:.3f}'.format(pets_with_sentiments \/ test_df_ids.shape[0]))\n\n\n# are distributions the same?\nprint('images and metadata distributions the same? {}'.format(\n    np.all(test_metadata_pets == test_imgs_pets)))\n\"\"\"\n### data parsing & feature extraction:\n\nAfter taking a look at the data, we know its structure and can use it to extract additional features and concatenate them with basic train\/test DFs.\n\"\"\"\nclass PetFinderParser(object):\n    \n    def __init__(self, debug=False):\n        \n        self.debug = debug\n        self.sentence_sep = ' '\n        \n        # Does not have to be extracted because main DF already contains description\n        self.extract_sentiment_text = False\n        \n        \n    def open_metadata_file(self, filename):\n        \"\"\"\n        Load metadata file.\n        \"\"\"\n        with open(filename, 'r') as f:\n            metadata_file = json.load(f)\n        return metadata_file\n            \n    def open_sentiment_file(self, filename):\n        \"\"\"\n        Load sentiment file.\n        \"\"\"\n        with open(filename, 'r') as f:\n            sentiment_file = json.load(f)\n        return sentiment_file\n            \n    def open_image_file(self, filename):\n        \"\"\"\n        Load image file.\n        \"\"\"\n        image = np.asarray(Image.open(filename))\n        return image\n        \n    def parse_sentiment_file(self, file):\n        \"\"\"\n        Parse sentiment file. Output DF with sentiment features.\n        \"\"\"\n        \n        file_sentiment = file['documentSentiment']\n        file_entities = [x['name'] for x in file['entities']]\n        file_entities = self.sentence_sep.join(file_entities)\n\n        if self.extract_sentiment_text:\n            file_sentences_text = [x['text']['content'] for x in file['sentences']]\n            file_sentences_text = self.sentence_sep.join(file_sentences_text)\n        file_sentences_sentiment = [x['sentiment'] for x in file['sentences']]\n        \n        file_sentences_sentiment = pd.DataFrame.from_dict(\n            file_sentences_sentiment, orient='columns').sum()\n        file_sentences_sentiment = file_sentences_sentiment.add_prefix('document_').to_dict()\n        \n        file_sentiment.update(file_sentences_sentiment)\n        \n        df_sentiment = pd.DataFrame.from_dict(file_sentiment, orient='index').T\n        if self.extract_sentiment_text:\n            df_sentiment['text'] = file_sentences_text\n            \n        df_sentiment['entities'] = file_entities\n        df_sentiment = df_sentiment.add_prefix('sentiment_')\n        \n        return df_sentiment\n    \n    def parse_metadata_file(self, file):\n        \"\"\"\n        Parse metadata file. Output DF with metadata features.\n        \"\"\"\n        \n        file_keys = list(file.keys())\n        \n        if 'labelAnnotations' in file_keys:\n            file_annots = file['labelAnnotations'][:int(len(file['labelAnnotations']) * 0.3)]\n            file_top_score = np.asarray([x['score'] for x in file_annots]).mean()\n            file_top_desc = [x['description'] for x in file_annots]\n        else:\n            file_top_score = np.nan\n            file_top_desc = ['']\n        \n        file_colors = file['imagePropertiesAnnotation']['dominantColors']['colors']\n        file_crops = file['cropHintsAnnotation']['cropHints']\n\n        file_color_score = np.asarray([x['score'] for x in file_colors]).mean()\n        file_color_pixelfrac = np.asarray([x['pixelFraction'] for x in file_colors]).mean()\n\n        file_crop_conf = np.asarray([x['confidence'] for x in file_crops]).mean()\n        \n        if 'importanceFraction' in file_crops[0].keys():\n            file_crop_importance = np.asarray([x['importanceFraction'] for x in file_crops]).mean()\n        else:\n            file_crop_importance = np.nan\n\n        df_metadata = {\n            'annots_score': file_top_score,\n            'color_score': file_color_score,\n            'color_pixelfrac': file_color_pixelfrac,\n            'crop_conf': file_crop_conf,\n            'crop_importance': file_crop_importance,\n            'annots_top_desc': self.sentence_sep.join(file_top_desc)\n        }\n        \n        df_metadata = pd.DataFrame.from_dict(df_metadata, orient='index').T\n        df_metadata = df_metadata.add_prefix('metadata_')\n        \n        return df_metadata\n    \n\n# Helper function for parallel data processing:\ndef extract_additional_features(pet_id, mode='train'):\n    \n    sentiment_filename = '..\/input\/{}_sentiment\/{}.json'.format(mode, pet_id)\n    try:\n        sentiment_file = pet_parser.open_sentiment_file(sentiment_filename)\n        df_sentiment = pet_parser.parse_sentiment_file(sentiment_file)\n        df_sentiment['PetID'] = pet_id\n    except FileNotFoundError:\n        df_sentiment = []\n\n    dfs_metadata = []\n    metadata_filenames = sorted(glob.glob('..\/input\/{}_metadata\/{}*.json'.format(mode, pet_id)))\n    if len(metadata_filenames) > 0:\n        for f in metadata_filenames:\n            metadata_file = pet_parser.open_metadata_file(f)\n            df_metadata = pet_parser.parse_metadata_file(metadata_file)\n            df_metadata['PetID'] = pet_id\n            dfs_metadata.append(df_metadata)\n        dfs_metadata = pd.concat(dfs_metadata, ignore_index=True, sort=False)\n    dfs = [df_sentiment, dfs_metadata]\n    \n    return dfs\n\n\npet_parser = PetFinderParser()\n# Unique IDs from train and test:\ndebug = False\ntrain_pet_ids = train.PetID.unique()\ntest_pet_ids = test.PetID.unique()\n\nif debug:\n    train_pet_ids = train_pet_ids[:1000]\n    test_pet_ids = test_pet_ids[:500]\n\n\n# Train set:\n# Parallel processing of data:\ndfs_train = Parallel(n_jobs=6, verbose=1)(\n    delayed(extract_additional_features)(i, mode='train') for i in train_pet_ids)\n\n# Extract processed data and format them as DFs:\ntrain_dfs_sentiment = [x[0] for x in dfs_train if isinstance(x[0], pd.DataFrame)]\ntrain_dfs_metadata = [x[1] for x in dfs_train if isinstance(x[1], pd.DataFrame)]\n\ntrain_dfs_sentiment = pd.concat(train_dfs_sentiment, ignore_index=True, sort=False)\ntrain_dfs_metadata = pd.concat(train_dfs_metadata, ignore_index=True, sort=False)\n\nprint(train_dfs_sentiment.shape, train_dfs_metadata.shape)\n\n\n# Test set:\n# Parallel processing of data:\ndfs_test = Parallel(n_jobs=6, verbose=1)(\n    delayed(extract_additional_features)(i, mode='test') for i in test_pet_ids)\n\n# Extract processed data and format them as DFs:\ntest_dfs_sentiment = [x[0] for x in dfs_test if isinstance(x[0], pd.DataFrame)]\ntest_dfs_metadata = [x[1] for x in dfs_test if isinstance(x[1], pd.DataFrame)]\n\ntest_dfs_sentiment = pd.concat(test_dfs_sentiment, ignore_index=True, sort=False)\ntest_dfs_metadata = pd.concat(test_dfs_metadata, ignore_index=True, sort=False)\n\nprint(test_dfs_sentiment.shape, test_dfs_metadata.shape)\n\"\"\"\n### group extracted features by PetID:\n\"\"\"\n# Extend aggregates and improve column naming\naggregates = ['mean', 'sum', 'var']\n\n\n# Train\ntrain_metadata_desc = train_dfs_metadata.groupby(['PetID'])['metadata_annots_top_desc'].unique()\ntrain_metadata_desc = train_metadata_desc.reset_index()\ntrain_metadata_desc[\n    'metadata_annots_top_desc'] = train_metadata_desc[\n    'metadata_annots_top_desc'].apply(lambda x: ' '.join(x))\n\nprefix = 'metadata'\ntrain_metadata_gr = train_dfs_metadata.drop(['metadata_annots_top_desc'], axis=1)\nfor i in train_metadata_gr.columns:\n    if 'PetID' not in i:\n        train_metadata_gr[i] = train_metadata_gr[i].astype(float)\ntrain_metadata_gr = train_metadata_gr.groupby(['PetID']).agg(aggregates)\ntrain_metadata_gr.columns = pd.Index(['{}_{}_{}'.format(\n            prefix, c[0], c[1].upper()) for c in train_metadata_gr.columns.tolist()])\ntrain_metadata_gr = train_metadata_gr.reset_index()\n\n\ntrain_sentiment_desc = train_dfs_sentiment.groupby(['PetID'])['sentiment_entities'].unique()\ntrain_sentiment_desc = train_sentiment_desc.reset_index()\ntrain_sentiment_desc[\n    'sentiment_entities'] = train_sentiment_desc[\n    'sentiment_entities'].apply(lambda x: ' '.join(x))\n\nprefix = 'sentiment'\ntrain_sentiment_gr = train_dfs_sentiment.drop(['sentiment_entities'], axis=1)\nfor i in train_sentiment_gr.columns:\n    if 'PetID' not in i:\n        train_sentiment_gr[i] = train_sentiment_gr[i].astype(float)\ntrain_sentiment_gr = train_sentiment_gr.groupby(['PetID']).agg(aggregates)\ntrain_sentiment_gr.columns = pd.Index(['{}_{}_{}'.format(\n            prefix, c[0], c[1].upper()) for c in train_sentiment_gr.columns.tolist()])\ntrain_sentiment_gr = train_sentiment_gr.reset_index()\n\n\n# Test\ntest_metadata_desc = test_dfs_metadata.groupby(['PetID'])['metadata_annots_top_desc'].unique()\ntest_metadata_desc = test_metadata_desc.reset_index()\ntest_metadata_desc[\n    'metadata_annots_top_desc'] = test_metadata_desc[\n    'metadata_annots_top_desc'].apply(lambda x: ' '.join(x))\n\nprefix = 'metadata'\ntest_metadata_gr = test_dfs_metadata.drop(['metadata_annots_top_desc'], axis=1)\nfor i in test_metadata_gr.columns:\n    if 'PetID' not in i:\n        test_metadata_gr[i] = test_metadata_gr[i].astype(float)\ntest_metadata_gr = test_metadata_gr.groupby(['PetID']).agg(aggregates)\ntest_metadata_gr.columns = pd.Index(['{}_{}_{}'.format(\n            prefix, c[0], c[1].upper()) for c in test_metadata_gr.columns.tolist()])\ntest_metadata_gr = test_metadata_gr.reset_index()\n\n\ntest_sentiment_desc = test_dfs_sentiment.groupby(['PetID'])['sentiment_entities'].unique()\ntest_sentiment_desc = test_sentiment_desc.reset_index()\ntest_sentiment_desc[\n    'sentiment_entities'] = test_sentiment_desc[\n    'sentiment_entities'].apply(lambda x: ' '.join(x))\n\nprefix = 'sentiment'\ntest_sentiment_gr = test_dfs_sentiment.drop(['sentiment_entities'], axis=1)\nfor i in test_sentiment_gr.columns:\n    if 'PetID' not in i:\n        test_sentiment_gr[i] = test_sentiment_gr[i].astype(float)\ntest_sentiment_gr = test_sentiment_gr.groupby(['PetID']).agg(aggregates)\ntest_sentiment_gr.columns = pd.Index(['{}_{}_{}'.format(\n            prefix, c[0], c[1].upper()) for c in test_sentiment_gr.columns.tolist()])\ntest_sentiment_gr = test_sentiment_gr.reset_index()\nprint(train_metadata_gr.shape, test_metadata_gr.shape)\nprint(\"sentiment\", train_sentiment_gr.shape, test_sentiment_gr.shape)\n\n\ntrain_metadata_gr = train_metadata_gr.merge(\n    train_metadata_desc, how='left', on='PetID')\nprint(\"Train_metadata_gr\",train_metadata_gr.shape)\n\ntrain_sentiment_gr = train_sentiment_gr.merge(\n    train_sentiment_desc, how='left', on='PetID')\nprint(\"Train_sentiment_gr\",train_sentiment_gr.shape)\n\ntest_metadata_gr = test_metadata_gr.merge(\n    test_metadata_desc, how='left', on='PetID')\nprint(\"Test_metadata_gr\",test_metadata_gr.shape)\n\ntest_sentiment_gr = test_sentiment_gr.merge(\n    test_sentiment_desc, how='left', on='PetID')\nprint(\"Test_sentiment_gr\",test_sentiment_gr.shape)\ntrain_metadata_gr.to_csv('train_dfs_metadata.csv', index=False)\ntrain_sentiment_gr.to_csv('train_dfs_sentiment.csv', index=False)\ntest_metadata_gr.to_csv('test_dfs_metadata.csv', index=False)\ntest_sentiment_gr.to_csv('test_dfs_sentiment_gr.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '0365524dbeca30'}"}
{"id":"85575","text":"\"\"\"\n### Car Price prediction\n\"\"\"\n\"\"\"\n## \u0412 baseline \u043c\u044b \u0441\u0434\u0435\u043b\u0430\u0435\u043c \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435:\n* \u041f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \"\u043d\u0430\u0438\u0432\u043d\u0443\u044e\"\/baseline \u043c\u043e\u0434\u0435\u043b\u044c, \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u044b\u0432\u0430\u044e\u0449\u0443\u044e \u0446\u0435\u043d\u0443 \u043f\u043e \u043c\u043e\u0434\u0435\u043b\u0438 \u0438 \u0433\u043e\u0434\u0443 \u0432\u044b\u043f\u0443\u0441\u043a\u0430 (\u0441 \u043d\u0435\u0439 \u0431\u0443\u0434\u0435\u043c \u0441\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u0442\u044c \u0434\u0440\u0443\u0433\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438)\n* \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u0438 \u043e\u0442\u043d\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c\u00a0\u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\n* \u0421\u0434\u0435\u043b\u0430\u0435\u043c \u043f\u0435\u0440\u0432\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442\u043d\u043e\u0433\u043e \u0431\u0443\u0441\u0442\u0438\u043d\u0433\u0430 \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e CatBoost\n* \u0421\u0434\u0435\u043b\u0430\u0435\u043c \u0432\u0442\u043e\u0440\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043d\u0435\u0439\u0440\u043e\u043d\u043d\u044b\u0445 \u0441\u0435\u0442\u0435\u0439 \u0438 \u0441\u0440\u0430\u0432\u043d\u0438\u043c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b\n* \u0421\u0434\u0435\u043b\u0430\u0435\u043c multi-input \u043d\u0435\u0439\u0440\u043e\u043d\u043d\u0443\u044e \u0441\u0435\u0442\u044c \u0434\u043b\u044f \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0442\u0430\u0431\u043b\u0438\u0447\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0438 \u0442\u0435\u043a\u0441\u0442\u0430 \u043e\u0434\u043d\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e\n* \u0414\u043e\u0431\u0430\u0432\u0438\u043c \u0432 multi-input \u0441\u0435\u0442\u044c \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0443 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439\n* \u041e\u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0438\u043c \u0430\u043d\u0441\u0430\u043c\u0431\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0433\u0440\u0430\u0434\u0438\u0435\u043d\u0442\u043d\u043e\u0433\u043e \u0431\u0443\u0441\u0442\u0438\u043d\u0433\u0430 \u0438 \u043d\u0435\u0439\u0440\u043e\u043d\u043d\u043e\u0439 \u0441\u0435\u0442\u0438 (\u0443\u0441\u0440\u0435\u0434\u043d\u0435\u043d\u0438\u0435 \u0438\u0445 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0439)\n\"\"\"\n!pip install -q tensorflow==2.3\n#\u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439\n!pip install albumentations -q\nimport random\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport sys\nimport PIL\nimport cv2\nimport re\n\nfrom catboost import CatBoostRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\n# # keras\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nimport albumentations\n\n# plt\nimport matplotlib.pyplot as plt\n#\u0443\u0432\u0435\u043b\u0438\u0447\u0438\u043c \u0434\u0435\u0444\u043e\u043b\u0442\u043d\u044b\u0439 \u0440\u0430\u0437\u043c\u0435\u0440 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 5\n#\u0433\u0440\u0430\u0444\u0438\u043a\u0438 \u0432 svg \u0432\u044b\u0433\u043b\u044f\u0434\u044f\u0442 \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u0442\u043a\u0438\u043c\u0438\n%config InlineBackend.figure_format = 'svg' \n%matplotlib inline\nprint('Python       :', sys.version.split('\\n')[0])\nprint('Numpy        :', np.__version__)\nprint('Tensorflow   :', tf.__version__)\ndef mape(y_true, y_pred):\n    return np.mean(np.abs((y_pred - y_true)\/y_true))\n# \u0432\u0441\u0435\u0433\u0434\u0430 \u0444\u0438\u043a\u0441\u0438\u0440\u0443\u0439\u0442\u0435 RANDOM_SEED, \u0447\u0442\u043e\u0431\u044b \u0432\u0430\u0448\u0438 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u044b \u0431\u044b\u043b\u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u044b!\nRANDOM_SEED = 42\nnp.random.seed(RANDOM_SEED)\n!pip freeze > requirements.txt\n\"\"\"\n# DATA\n\"\"\"\n\"\"\"\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0442\u0438\u043f\u044b \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432:\n\n* bodyType - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* brand - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* color - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* description - \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u044b\u0439\n* engineDisplacement - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0439 \u043a\u0430\u043a \u0442\u0435\u043a\u0441\u0442\n* enginePower - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0439 \u043a\u0430\u043a \u0442\u0435\u043a\u0441\u0442\n* fuelType - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* mileage - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439\n* modelDate - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439\n* model_info - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* name - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439, \u0436\u0435\u043b\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0441\u043e\u043a\u0440\u0430\u0442\u0438\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c\n* numberOfDoors - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* price - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439, \u0446\u0435\u043b\u0435\u0432\u043e\u0439\n* productionDate - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439\n* sell_id - \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435 (\u0444\u0430\u0439\u043b \u0434\u043e\u0441\u0442\u0443\u043f\u0435\u043d \u043f\u043e \u0430\u0434\u0440\u0435\u0441\u0443, \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u043d\u043e\u043c\u0443 \u043d\u0430 sell_id)\n* vehicleConfiguration - \u043d\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f (\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0446\u0438\u044f \u0434\u0440\u0443\u0433\u0438\u0445 \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432)\n* vehicleTransmission - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* \u0412\u043b\u0430\u0434\u0435\u043b\u044c\u0446\u044b - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* \u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435 - \u0447\u0438\u0441\u043b\u043e\u0432\u043e\u0439, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0439 \u043a\u0430\u043a \u0442\u0435\u043a\u0441\u0442\n* \u041f\u0422\u0421 - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* \u041f\u0440\u0438\u0432\u043e\u0434 - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n* \u0420\u0443\u043b\u044c - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439\n\"\"\"\nDATA_DIR = '..\/input\/sf-dst-car-price-prediction-part2\/'\ntrain = pd.read_csv(DATA_DIR + 'train.csv')\ntest = pd.read_csv(DATA_DIR + 'test.csv')\nsample_submission = pd.read_csv(DATA_DIR + 'sample_submission.csv')\ntrain.info()\ntrain.nunique()\n\"\"\"\n# Model 1: \u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \"\u043d\u0430\u0438\u0432\u043d\u0443\u044e\" \u043c\u043e\u0434\u0435\u043b\u044c \n\u042d\u0442\u0430 \u043c\u043e\u0434\u0435\u043b\u044c \u0431\u0443\u0434\u0435\u0442 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0441\u0440\u0435\u0434\u043d\u044e\u044e \u0446\u0435\u043d\u0443 \u043f\u043e \u043c\u043e\u0434\u0435\u043b\u0438 \u0438 \u0433\u043e\u0434\u0443 \u0432\u044b\u043f\u0443\u0441\u043a\u0430. \nC \u043d\u0435\u0439 \u0431\u0443\u0434\u0435\u043c \u0441\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u0442\u044c \u0434\u0440\u0443\u0433\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438.\n\n\n\"\"\"\n# split \u0434\u0430\u043d\u043d\u044b\u0445\ndata_train, data_test = train_test_split(train, test_size=0.15, shuffle=True, random_state=RANDOM_SEED)\n# \u041d\u0430\u0438\u0432\u043d\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c\npredicts = []\nfor index, row in pd.DataFrame(data_test[['model_info', 'productionDate']]).iterrows():\n    query = f\"model_info == '{row[0]}' and productionDate == '{row[1]}'\"\n    predicts.append(data_train.query(query)['price'].median())\n\n# \u0437\u0430\u043f\u043e\u043b\u043d\u0438\u043c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u043d\u044b\u0435 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u044f\npredicts = pd.DataFrame(predicts)\npredicts = predicts.fillna(predicts.median())\n\n# \u043e\u043a\u0440\u0443\u0433\u043b\u0438\u043c\npredicts = (predicts \/\/ 1000) * 1000\n\n#\u043e\u0446\u0435\u043d\u0438\u0432\u0430\u0435\u043c \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c\nprint(f\"\u0422\u043e\u0447\u043d\u043e\u0441\u0442\u044c \u043d\u0430\u0438\u0432\u043d\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u043e \u043c\u0435\u0442\u0440\u0438\u043a\u0435 MAPE: {(mape(data_test['price'], predicts.values[:, 0]))*100:0.2f}%\")\n\"\"\"\n# EDA\n\"\"\"\n\"\"\"\n\u041f\u0440\u043e\u0432\u0435\u0434\u0435\u043c \u0431\u044b\u0441\u0442\u0440\u044b\u0439 \u0430\u043d\u0430\u043b\u0438\u0437 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043d\u0438\u043c\u0430\u0442\u044c, \u0441\u043c\u043e\u0436\u0435\u0442 \u043b\u0438 \u0441 \u044d\u0442\u0438\u043c\u0438 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043d\u0430\u0448 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c.\n\"\"\"\n\"\"\"\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c, \u043a\u0430\u043a \u0432\u044b\u0433\u043b\u044f\u0434\u044f\u0442 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432:\n\"\"\"\n#\u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c, \u043a\u0430\u043a \u0432\u044b\u0433\u043b\u044f\u0434\u044f\u0442 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ndef visualize_distributions(titles_values_dict):\n  columns = min(3, len(titles_values_dict))\n  rows = (len(titles_values_dict) - 1) \/\/ columns + 1\n  fig = plt.figure(figsize = (columns * 6, rows * 4))\n  for i, (title, values) in enumerate(titles_values_dict.items()):\n    hist, bins = np.histogram(values, bins = 20)\n    ax = fig.add_subplot(rows, columns, i + 1)\n    ax.bar(bins[:-1], hist, width = (bins[1] - bins[0]) * 0.7)\n    ax.set_title(title)\n  plt.show()\n\nvisualize_distributions({\n    'mileage': train['mileage'].dropna(),\n    'modelDate': train['modelDate'].dropna(),\n    'productionDate': train['productionDate'].dropna()\n})\n\"\"\"\n\u0418\u0442\u043e\u0433\u043e:\n* CatBoost \u0441\u043c\u043e\u0436\u0435\u0442 \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u043c\u0438 \u0438 \u0432 \u0442\u0430\u043a\u043e\u043c \u0432\u0438\u0434\u0435, \u043d\u043e \u0434\u043b\u044f \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u0438 \u043d\u0443\u0436\u043d\u044b \u043d\u043e\u0440\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435.\n\"\"\"\n\"\"\"\n# PreProc Tabular Data\n\"\"\"\n#\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0432\u0441\u0435 \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043a\u0430\u043a \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0435 \u0431\u0435\u0437 \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438\ncategorical_features = ['bodyType', 'brand', 'color', 'engineDisplacement', 'enginePower', 'fuelType', 'model_info', 'name',\n  'numberOfDoors', 'vehicleTransmission', '\u0412\u043b\u0430\u0434\u0435\u043b\u044c\u0446\u044b', '\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435', '\u041f\u0422\u0421', '\u041f\u0440\u0438\u0432\u043e\u0434', '\u0420\u0443\u043b\u044c']\n\n#\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0432\u0441\u0435 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\nnumerical_features = ['mileage', 'modelDate', 'productionDate']\n# \u0412\u0410\u0416\u041d\u041e! \u0434\u0440\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0439 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0442\u0440\u0435\u0439\u043d \u0438 \u0442\u0435\u0441\u0442 \u0432 \u043e\u0434\u0438\u043d \u0434\u0430\u0442\u0430\u0441\u0435\u0442\ntrain['sample'] = 1 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0440\u0435\u0439\u043d\ntest['sample'] = 0 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0435\u0441\u0442\ntest['price'] = 0 # \u0432 \u0442\u0435\u0441\u0442\u0435 \u0443 \u043d\u0430\u0441 \u043d\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f price, \u043c\u044b \u0435\u0433\u043e \u0434\u043e\u043b\u0436\u043d\u044b \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u0442\u044c, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043f\u043e\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u043e \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043d\u0443\u043b\u044f\u043c\u0438\n\ndata = test.append(train, sort=False).reset_index(drop=True) # \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c\nprint(train.shape, test.shape, data.shape)\n\"\"\"\n## engineDisplacement\n\"\"\"\ndata['engineDisplacement']\ndata['engineDisplacement'].describe()\ndef to_float(column, pattern):\n    new_column = []\n    for string in column:\n        if pattern.match(string) != None:\n            new_column.append(float(pattern.match(string)[0]))\n        else:\n            new_column.append(2.0)\n    return new_column\ndata['engineDisplacement'] = to_float(data['engineDisplacement'], re.compile('[0-9]\\.[0-9]'))\ndata['engineDisplacement'].describe()\n\"\"\"\n## enginePower\n\"\"\"\ndata['enginePower'].unique()\ndata['enginePower'].describe()\ndef to_int(column, pattern):\n    new_column = []\n    for string in column:\n        if pattern.match(string) != None:\n            new_column.append(int(pattern.match(string)[0]))\n        else:\n            new_column.append(255)\n    return new_column\ndata['enginePower'] = to_int(data['enginePower'], re.compile('[0-9]*'))\ndata['enginePower'].describe()\n\"\"\"\n## \u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435\n\"\"\"\ndata['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435']\ndata['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435'].isna().value_counts()\ndata['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435'].describe()\ndata['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435'].fillna(1.66)\ndef years_to_float(column, pattern):\n    new_column = []\n    for string in column:\n        if type(string) == str:\n            list = re.findall(pattern, string)\n            list = [int(value) for value in list if value != '']\n            if len(list) > 0:\n                if len(list) == 1:\n                    new_column.append(list[0])\n                elif len(list) == 2:\n                    new_column.append(list[0] + list[1]\/12)\n        else: \n            new_column.append(1.66)\n    return new_column\ndata['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435'] = years_to_float(data['\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435'], re.compile('[0-9]*'))\n\"\"\"\n## name\n\"\"\"\ndata['name']\ncategorical_features = ['bodyType', 'brand', 'color', 'fuelType', 'model_info', 'name',\n  'numberOfDoors', 'vehicleTransmission', '\u0412\u043b\u0430\u0434\u0435\u043b\u044c\u0446\u044b', '\u041f\u0422\u0421', '\u041f\u0440\u0438\u0432\u043e\u0434', '\u0420\u0443\u043b\u044c']\n\nnumerical_features = ['mileage', 'modelDate', 'productionDate', 'engineDisplacement', 'enginePower', '\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435']\ndef preproc_data(df_input):\n    '''includes several functions to pre-process the predictor data.'''\n    \n    df_output = df_input.copy()\n    \n    # ################### 1. \u041f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 ############################################################## \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043d\u0435 \u043d\u0443\u0436\u043d\u044b\u0435 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\n    df_output.drop(['description','sell_id',], axis = 1, inplace=True)\n    \n    \n    # ################### Numerical Features ############################################################## \n    # \u0414\u0430\u043b\u0435\u0435 \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438\n    for column in numerical_features:\n        df_output[column].fillna(df_output[column].median(), inplace=True)\n    # \u0442\u0443\u0442 \u0432\u0430\u0448 \u043a\u043e\u0434 \u043f\u043e \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0435 NAN\n    # ....\n    \n    # \u041d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\n    scaler = MinMaxScaler()\n    for column in numerical_features:\n        df_output[column] = scaler.fit_transform(df_output[[column]])[:,0]\n    \n    \n    \n    # ################### Categorical Features ############################################################## \n    # Label Encoding\n    for column in categorical_features:\n        df_output[column] = df_output[column].astype('category').cat.codes\n        \n    # One-Hot Encoding: \u0432 pandas \u0435\u0441\u0442\u044c \u0433\u043e\u0442\u043e\u0432\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f - get_dummies.\n    df_output = pd.get_dummies(df_output, columns=categorical_features, dummy_na=False)\n    # \u0442\u0443\u0442 \u0432\u0430\u0448 \u043a\u043e\u0434 \u043d\u0435 Encoding \u0444\u0438\u0447\u0435\u0439\n    # ....\n    \n    \n    # ################### Feature Engineering ####################################################\n    # \u0442\u0443\u0442 \u0432\u0430\u0448 \u043a\u043e\u0434 \u043d\u0435 \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044e \u043d\u043e\u0432\u044b\u0445 \u0444\u0438\u0447\u0435\u0439\n    # ....\n    \n    \n    # ################### Clean #################################################### \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0435\u0449\u0435 \u043d\u0435 \u0443\u0441\u043f\u0435\u043b\u0438 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c, \n    df_output.drop(['vehicleConfiguration'], axis = 1, inplace=True)\n    \n    return df_output\n# \u0417\u0430\u043f\u0443\u0441\u043a\u0430\u0435\u043c \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u0447\u0442\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c\ndf_preproc = preproc_data(data)\ndf_preproc.sample(10)\ndf_preproc.info()\n\"\"\"\n## Split data\n\"\"\"\n# \u0422\u0435\u043f\u0435\u0440\u044c \u0432\u044b\u0434\u0435\u043b\u0438\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u0443\u044e \u0447\u0430\u0441\u0442\u044c\ntrain_data = df_preproc.query('sample == 1').drop(['sample'], axis=1)\ntest_data = df_preproc.query('sample == 0').drop(['sample'], axis=1)\n\ny = train_data.price.values     # \u043d\u0430\u0448 \u0442\u0430\u0440\u0433\u0435\u0442\nX = train_data.drop(['price'], axis=1)\nX_sub = test_data.drop(['price'], axis=1)\ntest_data.info()\n\"\"\"\n# Model 2: CatBoostRegressor\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, shuffle=True, random_state=RANDOM_SEED)\nmodel = CatBoostRegressor(iterations = 5000,\n                          #depth=10,\n                          #learning_rate = 0.5,\n                          random_seed = RANDOM_SEED,\n                          eval_metric='MAPE',\n                          custom_metric=['RMSE', 'MAE'],\n                          od_wait=500,\n                          #task_type='GPU',\n                         )\nmodel.fit(X_train, y_train,\n         eval_set=(X_test, y_test),\n         verbose_eval=100,\n         use_best_model=True,\n         #plot=True\n         )\ntest_predict_catboost = model.predict(X_test)\nprint(f\"TEST mape: {(mape(y_test, test_predict_catboost))*100:0.2f}%\")\n\"\"\"\n> TEST mape: 12.41%\n\"\"\"\n\"\"\"\n### Submission\n\"\"\"\nsub_predict_catboost = model.predict(X_sub)\nsample_submission['price'] = sub_predict_catboost\nsample_submission.to_csv('catboost_submission.csv', index=False)\n\"\"\"\n# Model 3: Tabular NN\n\"\"\"\n\"\"\"\n\u041f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u043e\u0431\u044b\u0447\u043d\u0443\u044e \u0441\u0435\u0442\u044c:\n\"\"\"\nX_train.head(5)\n\"\"\"\n## Simple Dense NN\n\"\"\"\nmodel = Sequential()\nmodel.add(L.Dense(512, input_dim=X_train.shape[1], activation=\"relu\"))\nmodel.add(L.Dropout(0.5))\nmodel.add(L.Dense(256, activation=\"relu\"))\nmodel.add(L.Dropout(0.5))\nmodel.add(L.Dense(1, activation=\"linear\"))\nmodel.summary()\n# Compile model\noptimizer = tf.keras.optimizers.Adam(0.01)\nmodel.compile(loss='MAPE',optimizer=optimizer, metrics=['MAPE'])\ncheckpoint = ModelCheckpoint('..\/working\/best_model.hdf5' , monitor=['val_MAPE'], verbose=0  , mode='min')\nearlystop = EarlyStopping(monitor='val_MAPE', patience=50, restore_best_weights=True,)\ncallbacks_list = [checkpoint, earlystop]\n\"\"\"\n### Fit\n\"\"\"\nhistory = model.fit(X_train, y_train,\n                    batch_size=512,\n                    epochs=500, # \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438 \u043c\u044b \u043e\u0431\u0443\u0447\u0430\u0435\u043c \u043f\u043e\u043a\u0430 EarlyStopping \u043d\u0435 \u043e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435\n                    validation_data=(X_test, y_test),\n                    callbacks=callbacks_list,\n                    verbose=0,\n                   )\nplt.title('Loss')\nplt.plot(history.history['MAPE'], label='train')\nplt.plot(history.history['val_MAPE'], label='test')\nplt.show();\nmodel.load_weights('..\/working\/best_model.hdf5')\nmodel.save('..\/working\/nn_1.hdf5')\ntest_predict_nn1 = model.predict(X_test)\nprint(f\"TEST mape: {(mape(y_test, test_predict_nn1[:,0]))*100:0.2f}%\")\n\"\"\"\n> TEST mape: 13.35%\n\"\"\"\nsub_predict_nn1 = model.predict(X_sub)\nsample_submission['price'] = sub_predict_nn1[:,0]\nsample_submission.to_csv('nn1_submission.csv', index=False)\n\"\"\"\n\u0420\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0438 \u0434\u043b\u044f \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u0438\u044f Model 3:    \n* \u0412 \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u044c \u0436\u0435\u043b\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u043e\u0434\u0430\u0432\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u0441 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435\u043c, \u0431\u043b\u0438\u0437\u043a\u0438\u043c \u043a \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u043c\u0443, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043e\u0442 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0438\u043c\u0435\u0435\u0442 \u0441\u043c\u044b\u0441\u043b \u0432\u0437\u044f\u0442\u044c \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043f\u0435\u0440\u0435\u0434 \u043d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0435\u0439. \u041f\u0440\u0438\u043c\u0435\u0440:\n`modelDateNorm = np.log(2020 - data['modelDate'])`\n\u0421\u0442\u0430\u0442\u044c\u044f \u043f\u043e \u0442\u0435\u043c\u0435: https:\/\/habr.com\/ru\/company\/ods\/blog\/325422\n\n* \u0418\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u0435 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0438\u0437 \u0442\u0435\u043a\u0441\u0442\u0430:\n\u041f\u0430\u0440\u0441\u0438\u043d\u0433 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 'engineDisplacement', 'enginePower', '\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435' \u0434\u043b\u044f \u0438\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u044f \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439.\n\n* C\u043e\u043a\u0440\u0430\u0449\u0435\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u0438 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\n\u041f\u0440\u0438\u0437\u043d\u0430\u043a name 'name' \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0434\u0430\u043d\u043d\u044b\u0435, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0443\u0436\u0435 \u0435\u0441\u0442\u044c \u0432 \u0434\u0440\u0443\u0433\u0438\u0445 \u0441\u0442\u043e\u043b\u0431\u0446\u0430\u0445 ('enginePower', 'engineDisplacement', 'vehicleTransmission'), \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u044d\u0442\u0438 \u0434\u0430\u043d\u043d\u044b\u0435 \u043c\u043e\u0436\u043d\u043e \u0443\u0434\u0430\u043b\u0438\u0442\u044c. \u0417\u0430\u0442\u0435\u043c \u0441\u043b\u0435\u0434\u0443\u0435\u0442 \u0435\u0449\u0435 \u0441\u0438\u043b\u044c\u043d\u0435\u0435 \u0441\u043e\u043a\u0440\u0430\u0442\u0438\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0432\u044b\u0434\u0435\u043b\u0438\u0432 \u043d\u0430\u043b\u0438\u0447\u0438\u0435 xDrive \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430.\n\"\"\"\n\"\"\"\n# Model 4: NLP + Multiple Inputs\n\"\"\"\ndata.description\n# TOKENIZER\n# The maximum number of words to be used. (most frequent)\nMAX_WORDS = 100000\n# Max number of words in each complaint.\nMAX_SEQUENCE_LENGTH = 256\n# split \u0434\u0430\u043d\u043d\u044b\u0445\ntext_train = data.description.iloc[X_train.index]\ntext_test = data.description.iloc[X_test.index]\ntext_sub = data.description.iloc[X_sub.index]\n\"\"\"\n### Tokenizer\n\"\"\"\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom tqdm import tqdm\nfrom keras.preprocessing.text import text_to_word_sequence\n\nlemmatizer = WordNetLemmatizer()\ntokenize = Tokenizer(num_words=MAX_WORDS)\nstop_words = set(stopwords.words(\"russian\"))\n\ndef preprocces(X):\n  X_proccess = []\n  stemmer = PorterStemmer()\n\n  for x in tqdm(X):\n    \n    x = x.lower()\n    x = text_to_word_sequence(x)\n    tokenize.fit_on_texts(x)\n    x = [word for word in x if word.isalnum()]\n    x = [lemmatizer.lemmatize(w) for w in x]\n    x = [word for word in x if not word in stop_words]\n    X_proccess.append(' '.join(x))\n  return X_proccess\n\n\ntext_train_proc = preprocces(text_train)\ntext_test_proc = preprocces(text_test)\ntext_sub_proc = preprocces(text_sub)\n%%time\ntext_train_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_train_proc), maxlen=MAX_SEQUENCE_LENGTH)\ntext_test_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_test_proc), maxlen=MAX_SEQUENCE_LENGTH)\ntext_sub_sequences = sequence.pad_sequences(tokenize.texts_to_sequences(text_sub_proc), maxlen=MAX_SEQUENCE_LENGTH)\n\nprint(text_train_sequences.shape, text_test_sequences.shape, text_sub_sequences.shape, )\n# \u0432\u043e\u0442 \u0442\u0430\u043a \u0442\u0435\u043f\u0435\u0440\u044c \u0432\u044b\u0433\u043b\u044f\u0434\u0438\u0442 \u043d\u0430\u0448 \u0442\u0435\u043a\u0441\u0442\nprint(text_train.iloc[6])\nprint(text_train_sequences[6])\n\"\"\"\n### RNN NLP\n\"\"\"\nmodel_nlp = Sequential()\nmodel_nlp.add(L.Input(shape=MAX_SEQUENCE_LENGTH, name=\"seq_description\"))\nmodel_nlp.add(L.Embedding(len(tokenize.word_index)+1, MAX_SEQUENCE_LENGTH,))\nmodel_nlp.add(L.LSTM(256, return_sequences=True))\nmodel_nlp.add(L.Dropout(0.5))\nmodel_nlp.add(L.LSTM(128,))\nmodel_nlp.add(L.Dropout(0.25))\nmodel_nlp.add(L.Dense(64, activation=\"relu\"))\nmodel_nlp.add(L.Dropout(0.25))\n\"\"\"\n### MLP\n\"\"\"\nmodel_mlp = Sequential()\nmodel_mlp.add(L.Dense(512, input_dim=X_train.shape[1], activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\nmodel_mlp.add(L.Dense(256, activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\n\"\"\"\n### Multiple Inputs NN\n\"\"\"\ncombinedInput = L.concatenate([model_nlp.output, model_mlp.output])\n# being our regression head\nhead = L.Dense(64, activation=\"relu\")(combinedInput)\nhead = L.Dense(1, activation=\"linear\")(head)\n\nmodel = Model(inputs=[model_nlp.input, model_mlp.input], outputs=head)\nmodel.summary()\n\"\"\"\n### Fit\n\"\"\"\n# optimizer = tf.keras.optimizers.Adam(0.01)\n# model.compile(loss='MAPE',optimizer=optimizer, metrics=['MAPE'])\n# checkpoint = ModelCheckpoint('..\/working\/best_model.hdf5', monitor=['val_MAPE'], verbose=0, mode='min')\n# earlystop = EarlyStopping(monitor='val_MAPE', patience=10, restore_best_weights=True,)\n# callbacks_list = [checkpoint, earlystop]\n# history = model.fit([text_train_sequences, X_train], y_train,\n#                     batch_size=512,\n#                     epochs=500, # \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438 \u043c\u044b \u043e\u0431\u0443\u0447\u0430\u0435\u043c \u043f\u043e\u043a\u0430 EarlyStopping \u043d\u0435 \u043e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435\n#                     validation_data=([text_test_sequences, X_test], y_test),\n#                     callbacks=callbacks_list\n#                    )\n# plt.title('Loss')\n# plt.plot(history.history['MAPE'], label='train')\n# plt.plot(history.history['val_MAPE'], label='test')\n# plt.show();\n# model.load_weights('..\/working\/best_model.hdf5')\n# model.save('..\/working\/nn_mlp_nlp.hdf5')\n# test_predict_nn2 = model.predict([text_test_sequences, X_test])\n# print(f\"TEST mape: {(mape(y_test, test_predict_nn2[:,0]))*100:0.2f}%\")\n\"\"\"\n> TEST mape: 13.71%\n\"\"\"\n# sub_predict_nn2 = model.predict([text_sub_sequences, X_sub])\n# sample_submission['price'] = sub_predict_nn2[:,0]\n# sample_submission.to_csv('nn2_submission.csv', index=False)\n\"\"\"\n\u0418\u0434\u0435\u0438 \u0434\u043b\u044f \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u0438\u044f NLP \u0447\u0430\u0441\u0442\u0438:\n* \u0412\u044b\u0434\u0435\u043b\u0438\u0442\u044c \u0438\u0437 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0439 \u0447\u0430\u0441\u0442\u043e \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u044e\u0449\u0438\u0435\u0441\u044f \u0431\u043b\u043e\u043a\u0438 \u0442\u0435\u043a\u0441\u0442\u0430, \u0437\u0430\u043c\u0435\u043d\u0438\u0432 \u0438\u0445 \u043d\u0430 \u043a\u043e\u0434\u043e\u0432\u044b\u0435 \u0441\u043b\u043e\u0432\u0430 \u0438\u043b\u0438 \u0443\u0434\u0430\u043b\u0438\u0432\n* \u0421\u0434\u0435\u043b\u0430\u0442\u044c \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0443 \u0442\u0435\u043a\u0441\u0442\u0430, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u043b\u0435\u043c\u043c\u0430\u0442\u0438\u0437\u0430\u0446\u0438\u044e - \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0441\u0442\u0430\u0432\u044f\u0449\u0438\u0439 \u0432\u0441\u0435 \u0441\u043b\u043e\u0432\u0430 \u0432 \u0444\u043e\u0440\u043c\u0443 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e (\u0433\u043b\u0430\u0433\u043e\u043b\u044b \u0432 \u0438\u043d\u0444\u0438\u043d\u0438\u0442\u0438\u0432 \u0438 \u0442. \u0434.), \u0447\u0442\u043e\u0431\u044b \u0442\u043e\u043a\u0435\u043d\u0430\u0439\u0437\u0435\u0440 \u043d\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u044b\u0432\u0430\u043b \u0440\u0430\u0437\u043d\u044b\u0435 \u0444\u043e\u0440\u043c\u044b \u0441\u043b\u043e\u0432\u0430 \u0432 \u0440\u0430\u0437\u043d\u044b\u0435 \u0447\u0438\u0441\u043b\u0430\n\u0421\u0442\u0430\u0442\u044c\u044f \u043f\u043e \u0442\u0435\u043c\u0435: https:\/\/habr.com\/ru\/company\/Voximplant\/blog\/446738\/\n* \u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043d\u0430\u0434 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430\u043c\u0438 \u043e\u0447\u0438\u0441\u0442\u043a\u0438 \u0438 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438 \u0442\u0435\u043a\u0441\u0442\u0430\n\"\"\"\n\"\"\"\n# Model 5: \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438\n\"\"\"\n\"\"\"\n### Data\n\"\"\"\n# \u0443\u0431\u0435\u0434\u0438\u043c\u0441\u044f, \u0447\u0442\u043e \u0446\u0435\u043d\u044b \u0438 \u0444\u043e\u0442\u043e \u043f\u043e\u0434\u0433\u0440\u0443\u0437\u0438\u043b\u0438\u0441\u044c \u0432\u0435\u0440\u043d\u043e\nplt.figure(figsize = (12,8))\n\nrandom_image = train.sample(n = 9)\nrandom_image_paths = random_image['sell_id'].values\nrandom_image_cat = random_image['price'].values\n\nfor index, path in enumerate(random_image_paths):\n    im = PIL.Image.open(DATA_DIR+'img\/img\/' + str(path) + '.jpg')\n    plt.subplot(3, 3, index + 1)\n    plt.imshow(im)\n    plt.title('price: ' + str(random_image_cat[index]))\n    plt.axis('off')\nplt.show()\nsize = (320, 240)\n\ndef get_image_array(index):\n    images_train = []\n    for index, sell_id in enumerate(data['sell_id'].iloc[index].values):\n        image = cv2.imread(DATA_DIR + 'img\/img\/' + str(sell_id) + '.jpg')\n        assert(image is not None)\n        image = cv2.resize(image, size)\n        images_train.append(image)\n    images_train = np.array(images_train)\n    print('images shape', images_train.shape, 'dtype', images_train.dtype)\n    return(images_train)\n\nimages_train = get_image_array(X_train.index)\nimages_test = get_image_array(X_test.index)\nimages_sub = get_image_array(X_sub.index)\n\"\"\"\n### albumentations\n\"\"\"\nfrom albumentations import (\n    HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,\n    Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,\n    IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine,\n    IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose\n)\n\n\n#\u043f\u0440\u0438\u043c\u0435\u0440 \u0432\u0437\u044f\u0442 \u0438\u0437 \u043e\u0444\u0438\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438: https:\/\/albumentations.readthedocs.io\/en\/latest\/examples.html\naugmentation = Compose([\n    HorizontalFlip(),\n    OneOf([\n        IAAAdditiveGaussianNoise(),\n        GaussNoise(),\n    ], p=0.2),\n    OneOf([\n        MotionBlur(p=0.2),\n        MedianBlur(blur_limit=3, p=0.1),\n        Blur(blur_limit=3, p=0.1),\n    ], p=0.2),\n    ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=15, p=1),\n    OneOf([\n        OpticalDistortion(p=0.3),\n        GridDistortion(p=0.1),\n        IAAPiecewiseAffine(p=0.3),\n    ], p=0.2),\n    OneOf([\n        CLAHE(clip_limit=2),\n        IAASharpen(),\n        IAAEmboss(),\n        RandomBrightnessContrast(),\n    ], p=0.3),\n    HueSaturationValue(p=0.3),\n], p=1)\n\n#\u043f\u0440\u0438\u043c\u0435\u0440\nplt.figure(figsize = (12,8))\nfor i in range(9):\n    img = augmentation(image = images_train[0])['image']\n    plt.subplot(3, 3, i + 1)\n    plt.imshow(img)\n    plt.axis('off')\nplt.show()\ndef make_augmentations(images):\n  print('\u043f\u0440\u0438\u043c\u0435\u043d\u0435\u043d\u0438\u0435 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0439', end = '')\n  augmented_images = np.empty(images.shape)\n  for i in range(images.shape[0]):\n    if i % 200 == 0:\n      print('.', end = '')\n    augment_dict = augmentation(image = images[i])\n    augmented_image = augment_dict['image']\n    augmented_images[i] = augmented_image\n  print('')\n  return augmented_images\n\"\"\"\n## tf.data.Dataset\n\u0415\u0441\u043b\u0438 \u0432\u0441\u0435 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u043c\u044b \u0431\u0443\u0434\u0435\u043c \u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0432 \u043f\u0430\u043c\u044f\u0442\u0438, \u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0432\u043e\u0437\u043d\u0438\u043a\u043d\u0443\u0442\u044c \u043f\u0440\u043e\u0431\u043b\u0435\u043c\u0430 \u0435\u0435 \u043d\u0435\u0445\u0432\u0430\u0442\u043a\u0438. \u041d\u0435 \u0445\u0440\u0430\u043d\u0438\u0442\u0435 \u0432\u0441\u0435 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u0432 \u043f\u0430\u043c\u044f\u0442\u0438 \u0446\u0435\u043b\u0438\u043a\u043e\u043c!\n\n\u041c\u0435\u0442\u043e\u0434 .fit() \u043c\u043e\u0434\u0435\u043b\u0438 keras \u043c\u043e\u0436\u0435\u0442 \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0442\u044c \u043b\u0438\u0431\u043e \u0434\u0430\u043d\u043d\u044b\u0435 \u0432 \u0432\u0438\u0434\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432 \u0438\u043b\u0438 \u0442\u0435\u043d\u0437\u043e\u0440\u043e\u0432, \u043b\u0438\u0431\u043e \u0440\u0430\u0437\u043d\u043e\u0433\u043e \u0440\u043e\u0434\u0430 \u0438\u0442\u0435\u0440\u0430\u0442\u043e\u0440\u044b, \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0430\u0438\u0431\u043e\u043b\u0435\u0435 \u0441\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u043c \u0438 \u0433\u0438\u0431\u043a\u0438\u043c \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f [tf.data.Dataset](https:\/\/www.tensorflow.org\/guide\/data). \u041e\u043d \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u0442 \u0441\u043e\u0431\u043e\u0439 \u043a\u043e\u043d\u0432\u0435\u0439\u0435\u0440, \u0442\u043e \u0435\u0441\u0442\u044c \u043c\u044b \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u043c, \u043e\u0442\u043a\u0443\u0434\u0430 \u0431\u0435\u0440\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u0438 \u043a\u0430\u043a\u0443\u044e \u0446\u0435\u043f\u043e\u0447\u043a\u0443 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0439 \u0441 \u043d\u0438\u043c\u0438 \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u043c. \u0414\u0430\u043b\u0435\u0435 \u043c\u044b \u0431\u0443\u0434\u0435\u043c \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 tf.data.Dataset.\n\nDataset \u0445\u0440\u0430\u043d\u0438\u0442 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043e \u043a\u043e\u043d\u0435\u0447\u043d\u043e\u043c \u0438\u043b\u0438 \u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u043e\u043c \u043d\u0430\u0431\u043e\u0440\u0435 \u043a\u043e\u0440\u0442\u0435\u0436\u0435\u0439 (tuple) \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u0438 \u043c\u043e\u0436\u0435\u0442 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0442\u044c \u044d\u0442\u0438 \u043d\u0430\u0431\u043e\u0440\u044b \u043f\u043e \u043e\u0447\u0435\u0440\u0435\u0434\u0438. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u043f\u0430\u0440\u044b (input, target) \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u0438. \u0421 \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \u043c\u043e\u0436\u043d\u043e \u043e\u0441\u0443\u0449\u0435\u0441\u0442\u0432\u043b\u044f\u0442\u044c \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043e\u0441\u0443\u0449\u0435\u0441\u0442\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043f\u043e \u043c\u0435\u0440\u0435 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 ([lazy evaluation](https:\/\/ru.wikipedia.org\/wiki\/%D0%9B%D0%B5%D0%BD%D0%B8%D0%B2%D1%8B%D0%B5_%D0%B2%D1%8B%D1%87%D0%B8%D1%81%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F)).\n\n`tf.data.Dataset.from_tensor_slices(data)` - \u0441\u043e\u0437\u0434\u0430\u0435\u0442 \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0438\u0437 \u0434\u0430\u043d\u043d\u044b\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u044f\u044e\u0442 \u0441\u043e\u0431\u043e\u0439 \u043b\u0438\u0431\u043e \u043c\u0430\u0441\u0441\u0438\u0432, \u043b\u0438\u0431\u043e \u043a\u043e\u0440\u0442\u0435\u0436 \u0438\u0437 \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432. \u0414\u0435\u043b\u0435\u043d\u0438\u0435 \u043e\u0441\u0443\u0449\u0435\u0441\u0442\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043f\u043e \u043f\u0435\u0440\u0432\u043e\u043c\u0443 \u0438\u043d\u0434\u0435\u043a\u0441\u0443 \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0430. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 `data = (np.zeros((128, 256, 256)), np.zeros(128))`, \u0442\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0431\u0443\u0434\u0435\u0442 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c 128 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043e\u0434\u0438\u043d \u043c\u0430\u0441\u0441\u0438\u0432 256x256 \u0438 \u043e\u0434\u043d\u043e \u0447\u0438\u0441\u043b\u043e.\n\n`dataset2 = dataset1.map(func)` - \u043f\u0440\u0438\u043c\u0435\u043d\u0435\u043d\u0438\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043a \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0443; \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0434\u043e\u043b\u0436\u043d\u0430 \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0442\u044c \u0441\u0442\u043e\u043b\u044c\u043a\u043e \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u043e\u0432, \u043a\u0430\u043a\u043e\u0432 \u0440\u0430\u0437\u043c\u0435\u0440 \u043a\u043e\u0440\u0442\u0435\u0436\u0430 \u0432 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 1 \u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0442\u044c \u0441\u0442\u043e\u043b\u044c\u043a\u043e, \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043d\u0443\u0436\u043d\u043e \u0438\u043c\u0435\u0442\u044c \u0432 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 2. \u041f\u0443\u0441\u0442\u044c, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u0438 \u043c\u0435\u0442\u043a\u0438, \u0430 \u043d\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u0438\u0437 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439, \u0442\u043e\u0433\u0434\u0430 \u043c\u044b \u043d\u0430\u043f\u0438\u0448\u0435\u043c \u0442\u0430\u043a: `dataset2 = dataset.map(lambda img, label: img)`.\n\n`dataset2 = dataset1.batch(8)` - \u0433\u0440\u0443\u043f\u043f\u0438\u0440\u043e\u0432\u043a\u0430 \u043f\u043e \u0431\u0430\u0442\u0447\u0430\u043c; \u0435\u0441\u043b\u0438 \u0434\u0430\u0442\u0430\u0441\u0435\u0442 2 \u0434\u043e\u043b\u0436\u0435\u043d \u0432\u0435\u0440\u043d\u0443\u0442\u044c \u043e\u0434\u0438\u043d \u044d\u043b\u0435\u043c\u0435\u043d\u0442, \u0442\u043e \u043e\u043d \u0431\u0435\u0440\u0435\u0442 \u0438\u0437 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 1 \u0432\u043e\u0441\u0435\u043c\u044c \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432, \u0441\u043a\u043b\u0435\u0438\u0432\u0430\u0435\u0442 \u0438\u0445 (\u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u0438\u043d\u0434\u0435\u043a\u0441 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430 - \u043d\u043e\u043c\u0435\u0440 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430) \u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442.\n\n`dataset.__iter__()` - \u043f\u0440\u0435\u0432\u0440\u0430\u0449\u0435\u043d\u0438\u0435 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 \u0432 \u0438\u0442\u0435\u0440\u0430\u0442\u043e\u0440, \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u043c\u043e\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0430\u0442\u044c \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u043c\u0435\u0442\u043e\u0434\u043e\u043c `.__next__()`. \u0418\u0442\u0435\u0440\u0430\u0442\u043e\u0440, \u0432 \u043e\u0442\u043b\u0438\u0447\u0438\u0435 \u043e\u0442 \u0441\u0430\u043c\u043e\u0433\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430, \u0445\u0440\u0430\u043d\u0438\u0442 \u043f\u043e\u0437\u0438\u0446\u0438\u044e \u0442\u0435\u043a\u0443\u0449\u0435\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430. \u041c\u043e\u0436\u043d\u043e \u0442\u0430\u043a\u0436\u0435 \u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0442\u044c \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0446\u0438\u043a\u043b\u043e\u043c for.\n\n`dataset2 = dataset1.repeat(X)` - \u0434\u0430\u0442\u0430\u0441\u0435\u0442 2 \u0431\u0443\u0434\u0435\u0442 \u043f\u043e\u0432\u0442\u043e\u0440\u044f\u0442\u044c \u0434\u0430\u0442\u0430\u0441\u0435\u0442 1 X \u0440\u0430\u0437.\n\n\u0415\u0441\u043b\u0438 \u043d\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c \u0438\u0437 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430 1000 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 \u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0438\u0445 \u043a\u0430\u043a \u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0435, \u0430 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0435 \u043a\u0430\u043a \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0438\u0435, \u0442\u043e \u043c\u044b \u043d\u0430\u043f\u0438\u0448\u0435\u043c \u0442\u0430\u043a:\n\n`test_dataset = dataset.take(1000)\ntrain_dataset = dataset.skip(1000)`\n\n\u0414\u0430\u0442\u0430\u0441\u0435\u0442 \u043f\u043e \u0441\u0443\u0442\u0438 \u043d\u0435\u0438\u0437\u043c\u0435\u043d\u0435\u043d: \u0442\u0430\u043a\u0438\u0435 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u0438, \u043a\u0430\u043a map, batch, repeat, take, skip \u043d\u0438\u043a\u0430\u043a \u043d\u0435 \u0437\u0430\u0442\u0440\u0430\u0433\u0438\u0432\u0430\u044e\u0442 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442. \u0415\u0441\u043b\u0438 \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0445\u0440\u0430\u043d\u0438\u0442 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b [1, 2, 3], \u0442\u043e \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0432 3 \u0440\u0430\u0437\u0430 \u043f\u043e\u0434\u0440\u044f\u0434 \u0444\u0443\u043d\u043a\u0446\u0438\u044e dataset.take(1) \u043c\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u043c 3 \u043d\u043e\u0432\u044b\u0445 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430, \u043a\u0430\u0436\u0434\u044b\u0439 \u0438\u0437 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0432\u0435\u0440\u043d\u0435\u0442 \u0447\u0438\u0441\u043b\u043e 1. \u0415\u0441\u043b\u0438 \u0436\u0435 \u043c\u044b \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e dataset.skip(1), \u043c\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442, \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u044e\u0449\u0438\u0439 \u0447\u0438\u0441\u043b\u0430 [2, 3], \u043d\u043e \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442 \u0432\u0441\u0435 \u0440\u0430\u0432\u043d\u043e \u0431\u0443\u0434\u0435\u0442 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0442\u044c [1, 2, 3] \u043a\u0430\u0436\u0434\u044b\u0439 \u0440\u0430\u0437, \u043a\u043e\u0433\u0434\u0430 \u043c\u044b \u0435\u0433\u043e \u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c.\n\ntf.Dataset \u0432\u0441\u0435\u0433\u0434\u0430 \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u0442\u0441\u044f \u0432 graph-\u0440\u0435\u0436\u0438\u043c\u0435 (\u0432 \u043f\u0440\u043e\u0442\u0438\u0432\u043e\u043f\u043e\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c eager-\u0440\u0435\u0436\u0438\u043c\u0443), \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043b\u0438\u0431\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f (`.map()`) \u0434\u043e\u043b\u0436\u043d\u044b \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0442\u044c \u0442\u043e\u043b\u044c\u043a\u043e tensorflow-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u043b\u0438\u0431\u043e \u043c\u044b \u0434\u043e\u043b\u0436\u043d\u044b \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c tf.py_function \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043e\u0431\u0435\u0440\u0442\u043a\u0438 \u0434\u043b\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0439, \u0432\u044b\u0437\u044b\u0432\u0430\u0435\u043c\u044b\u0445 \u0432 `.map()`. \u041f\u043e\u0434\u0440\u043e\u0431\u043d\u0435\u0435 \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u0442\u044c [\u0437\u0434\u0435\u0441\u044c](https:\/\/www.tensorflow.org\/guide\/data#applying_arbitrary_python_logic).\n\"\"\"\n# NLP part\ntokenize = Tokenizer(num_words=MAX_WORDS)\nlemmatizer = WordNetLemmatizer()\nstop_words = set(stopwords.words(\"russian\"))\n\ndef preprocces(X):\n    X_proccess = []\n    stemmer = PorterStemmer()\n\n    for x in tqdm(X):\n        x = x.lower()\n        x = text_to_word_sequence(x)\n        tokenize.fit_on_texts(x)\n        x = [word for word in x if word.isalnum()]\n        x = [lemmatizer.lemmatize(w) for w in x]\n        x = [word for word in x if not word in stop_words]\n        X_proccess.append(' '.join(x))\n    return X_proccess\n\ndata.description = preprocces(data.description)\ndef process_image(image):\n    return augmentation(image = image.numpy())['image']\n\ndef tokenize_(descriptions):\n    return sequence.pad_sequences(tokenize.texts_to_sequences(descriptions), maxlen = MAX_SEQUENCE_LENGTH)\n\ndef tokenize_text(text):\n    return tokenize_([text.numpy().decode('utf-8')])[0]\n\ndef tf_process_train_dataset_element(image, table_data, text, price):\n    im_shape = image.shape\n    [image,] = tf.py_function(process_image, [image], [tf.uint8])\n    image.set_shape(im_shape)\n    [text,] = tf.py_function(tokenize_text, [text], [tf.int32])\n    return (image, table_data, text), price\n\ndef tf_process_val_dataset_element(image, table_data, text, price):\n    [text,] = tf.py_function(tokenize_text, [text], [tf.int32])\n    return (image, table_data, text), price\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((\n    images_train, X_train, data.description.iloc[X_train.index], y_train\n    )).map(tf_process_train_dataset_element)\n\ntest_dataset = tf.data.Dataset.from_tensor_slices((\n    images_test, X_test, data.description.iloc[X_test.index], y_test\n    )).map(tf_process_val_dataset_element)\n\ny_sub = np.zeros(len(X_sub))\nsub_dataset = tf.data.Dataset.from_tensor_slices((\n    images_sub, X_sub, data.description.iloc[X_sub.index], y_sub\n    )).map(tf_process_val_dataset_element)\n\n#\u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u0447\u0442\u043e \u043d\u0435\u0442 \u043e\u0448\u0438\u0431\u043e\u043a (\u043d\u0435 \u0431\u0443\u0434\u0435\u0442 \u0432\u044b\u0431\u0440\u043e\u0448\u0435\u043d\u043e \u0438\u0441\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435):\ntrain_dataset.__iter__().__next__();\ntest_dataset.__iter__().__next__();\nsub_dataset.__iter__().__next__();\n\"\"\"\n### \u0421\u0442\u0440\u043e\u0438\u043c \u0441\u0432\u0435\u0440\u0442\u043e\u0447\u043d\u0443\u044e \u0441\u0435\u0442\u044c \u0434\u043b\u044f \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0431\u0435\u0437 \"\u0433\u043e\u043b\u043e\u0432\u044b\"\n\"\"\"\n#\u043d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u0432\u043a\u043b\u044e\u0447\u0435\u043d\u0430 \u0432 \u0441\u043e\u0441\u0442\u0430\u0432 \u043c\u043e\u0434\u0435\u043b\u0438 EfficientNetB3, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043d\u0430 \u0432\u0445\u043e\u0434 \u043e\u043d\u0430 \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442 \u0434\u0430\u043d\u043d\u044b\u0435 \u0442\u0438\u043f\u0430 uint8\nefficientnet_model = tf.keras.applications.efficientnet.EfficientNetB3(weights = 'imagenet', include_top = False, input_shape = (size[1], size[0], 3))\nefficientnet_output = L.GlobalAveragePooling2D()(efficientnet_model.output)\n#\u0441\u0442\u0440\u043e\u0438\u043c \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u044c \u0434\u043b\u044f \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0442\u0430\u0431\u043b\u0438\u0447\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445\ntabular_model = Sequential([\n    L.Input(shape = X.shape[1]),\n    L.Dense(512, activation = 'relu'),\n    L.Dropout(0.5),\n    L.Dense(256, activation = 'relu'),\n    L.Dropout(0.5),\n    ])\n# NLP\nnlp_model = Sequential([\n    L.Input(shape=MAX_SEQUENCE_LENGTH, name=\"seq_description\"),\n    L.Embedding(len(tokenize.word_index)+1, MAX_SEQUENCE_LENGTH,),\n    L.LSTM(256, return_sequences=True),\n    L.Dropout(0.5),\n    L.LSTM(128),\n    L.Dropout(0.25),\n    L.Dense(64),\n    ])\n#\u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0432\u044b\u0445\u043e\u0434\u044b \u0442\u0440\u0435\u0445 \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u0435\u0439\ncombinedInput = L.concatenate([efficientnet_output, tabular_model.output, nlp_model.output])\n\n# being our regression head\nhead = L.Dense(256, activation=\"relu\")(combinedInput)\nhead = L.Dense(1,)(head)\n\nmodel = Model(inputs=[efficientnet_model.input, tabular_model.input, nlp_model.input], outputs=head)\nmodel.summary()\noptimizer = tf.keras.optimizers.Adam(0.005)\nmodel.compile(loss='MAPE',optimizer=optimizer, metrics=['MAPE'])\ncheckpoint = ModelCheckpoint('..\/working\/best_model.hdf5', monitor=['val_MAPE'], verbose=0, mode='min')\nearlystop = EarlyStopping(monitor='val_MAPE', patience=10, restore_best_weights=True,)\ncallbacks_list = [checkpoint, earlystop]\nhistory = model.fit(train_dataset.batch(30),\n                    epochs=100,\n                    validation_data = test_dataset.batch(30),\n                    callbacks=callbacks_list\n                   )\nplt.title('Loss')\nplt.plot(history.history['MAPE'], label='train')\nplt.plot(history.history['val_MAPE'], label='test')\nplt.show();\nmodel.load_weights('..\/working\/best_model.hdf5')\nmodel.save('..\/working\/nn_final.hdf5')\ntest_predict_nn3 = model.predict(test_dataset.batch(30))\nprint(f\"TEST mape: {(mape(y_test, test_predict_nn3[:,0]))*100:0.2f}%\")\nsub_predict_nn3 = model.predict(sub_dataset.batch(30))\nsample_submission['price'] = sub_predict_nn3[:,0]\nsample_submission.to_csv('nn3_submission.csv', index=False)\n\"\"\"\n\n#### \u041e\u0431\u0449\u0438\u0435 \u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0430\u0446\u0438\u0438:\n* \u041f\u043e\u043f\u0440\u043e\u0431\u043e\u0432\u0430\u0442\u044c \u0440\u0430\u0437\u043d\u044b\u0435 \u0430\u0440\u0445\u0438\u0442\u0435\u043a\u0442\u0443\u0440\u044b\n* \u041f\u0440\u043e\u0432\u0435\u0441\u0442\u0438 \u0431\u043e\u043b\u0435\u0435 \u0434\u0435\u0442\u0430\u043b\u044c\u043d\u044b\u0439 \u0430\u043d\u0430\u043b\u0438\u0437 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432\n* \u041f\u043e\u043f\u0440\u043e\u0431\u043e\u0432\u0430\u0442\u044c \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0435 \u043f\u043e\u0434\u0445\u043e\u0434\u044b \u0432 \u0443\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u0438\u0435 LR \u0438 \u043e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u0442\u043e\u0440\u044b\n* \u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 \u0442\u0430\u0440\u0433\u0435\u0442\u043e\u043c\n* \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c Fine-tuning\n\n#### Tabular\n* \u0412 \u043d\u0435\u0439\u0440\u043e\u0441\u0435\u0442\u044c \u0436\u0435\u043b\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u043f\u043e\u0434\u0430\u0432\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u0441 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435\u043c, \u0431\u043b\u0438\u0437\u043a\u0438\u043c \u043a \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u043c\u0443, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043e\u0442 \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0438\u043c\u0435\u0435\u0442 \u0441\u043c\u044b\u0441\u043b \u0432\u0437\u044f\u0442\u044c \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043f\u0435\u0440\u0435\u0434 \u043d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0435\u0439. \u041f\u0440\u0438\u043c\u0435\u0440:\n`modelDateNorm = np.log(2020 - data['modelDate'])`\n\u0421\u0442\u0430\u0442\u044c\u044f \u043f\u043e \u0442\u0435\u043c\u0435: https:\/\/habr.com\/ru\/company\/ods\/blog\/325422\n\n* \u0418\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u0435 \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0438\u0437 \u0442\u0435\u043a\u0441\u0442\u0430:\n\u041f\u0430\u0440\u0441\u0438\u043d\u0433 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 'engineDisplacement', 'enginePower', '\u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435' \u0434\u043b\u044f \u0438\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u044f \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439.\n\n* C\u043e\u043a\u0440\u0430\u0449\u0435\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u0438 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\n\u041f\u0440\u0438\u0437\u043d\u0430\u043a name 'name' \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u0434\u0430\u043d\u043d\u044b\u0435, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0443\u0436\u0435 \u0435\u0441\u0442\u044c \u0432 \u0434\u0440\u0443\u0433\u0438\u0445 \u0441\u0442\u043e\u043b\u0431\u0446\u0430\u0445 ('enginePower', 'engineDisplacement', 'vehicleTransmission'). \u041c\u043e\u0436\u043d\u043e \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u044d\u0442\u0438 \u0434\u0430\u043d\u043d\u044b\u0435. \u0417\u0430\u0442\u0435\u043c \u043c\u043e\u0436\u043d\u043e \u0435\u0449\u0435 \u0441\u0438\u043b\u044c\u043d\u0435\u0435 \u0441\u043e\u043a\u0440\u0430\u0442\u0438\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0440\u043d\u043e\u0441\u0442\u044c, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 \u0432\u044b\u0434\u0435\u043b\u0438\u0432 \u043d\u0430\u043b\u0438\u0447\u0438\u0435 xDrive \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430.\n\n* \u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043d\u0430\u0434 Feature engineering\n\n\n\n#### NLP\n* \u0412\u044b\u0434\u0435\u043b\u0438\u0442\u044c \u0438\u0437 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0439 \u0447\u0430\u0441\u0442\u043e \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u044e\u0449\u0438\u0435\u0441\u044f \u0431\u043b\u043e\u043a\u0438 \u0442\u0435\u043a\u0441\u0442\u0430, \u0437\u0430\u043c\u0435\u043d\u0438\u0432 \u0438\u0445 \u043d\u0430 \u043a\u043e\u0434\u043e\u0432\u044b\u0435 \u0441\u043b\u043e\u0432\u0430 \u0438\u043b\u0438 \u0443\u0434\u0430\u043b\u0438\u0432\n* \u0421\u0434\u0435\u043b\u0430\u0442\u044c \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0443 \u0442\u0435\u043a\u0441\u0442\u0430, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u043b\u0435\u043c\u043c\u0430\u0442\u0438\u0437\u0430\u0446\u0438\u044e - \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0441\u0442\u0430\u0432\u044f\u0449\u0438\u0439 \u0432\u0441\u0435 \u0441\u043b\u043e\u0432\u0430 \u0432 \u0444\u043e\u0440\u043c\u0443 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e (\u0433\u043b\u0430\u0433\u043e\u043b\u044b \u0432 \u0438\u043d\u0444\u0438\u043d\u0438\u0442\u0438\u0432 \u0438 \u0442. \u0434.), \u0447\u0442\u043e\u0431\u044b \u0442\u043e\u043a\u0435\u043d\u0430\u0439\u0437\u0435\u0440 \u043d\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u044b\u0432\u0430\u043b \u0440\u0430\u0437\u043d\u044b\u0435 \u0444\u043e\u0440\u043c\u044b \u0441\u043b\u043e\u0432\u0430 \u0432 \u0440\u0430\u0437\u043d\u044b\u0435 \u0447\u0438\u0441\u043b\u0430\n\u0421\u0442\u0430\u0442\u044c\u044f \u043f\u043e \u0442\u0435\u043c\u0435: https:\/\/habr.com\/ru\/company\/Voximplant\/blog\/446738\/\n* \u041f\u043e\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043d\u0430\u0434 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u0430\u043c\u0438 \u043e\u0447\u0438\u0441\u0442\u043a\u0438 \u0438 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438 \u0442\u0435\u043a\u0441\u0442\u0430\n\n\n\n#### CV\n* \u041f\u043e\u043f\u0440\u043e\u0431\u043e\u0432\u0430\u0442\u044c \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0435 \u0430\u0443\u0433\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0438\n* Fine-tuning\n\"\"\"\n\"\"\"\n# Blend\n\"\"\"\nblend_predict = (test_predict_catboost + test_predict_nn3[:,0]) \/ 2\nprint(f\"TEST mape: {(mape(y_test, blend_predict))*100:0.2f}%\")\nblend_sub_predict = (sub_predict_catboost + sub_predict_nn3[:,0]) \/ 2\nsample_submission['price'] = blend_sub_predict\nsample_submission.to_csv('blend_submission.csv', index=False)\n\"\"\"\n# Model Bonus: \u043f\u0440\u043e\u0431\u0440\u043e\u0441 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\n\"\"\"\n# MLP\nmodel_mlp = Sequential()\nmodel_mlp.add(L.Dense(512, input_dim=X_train.shape[1], activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\nmodel_mlp.add(L.Dense(256, activation=\"relu\"))\nmodel_mlp.add(L.Dropout(0.5))\n# FEATURE Input\n# Iput\nproductiondate = L.Input(shape=[1], name=\"productiondate\")\n# Embeddings layers\nemb_productiondate = L.Embedding(len(X.productionDate.unique().tolist())+1, 20)(productiondate)\nf_productiondate = L.Flatten()(emb_productiondate)\ncombinedInput = L.concatenate([model_mlp.output, f_productiondate,])\n# being our regression head\nhead = L.Dense(64, activation=\"relu\")(combinedInput)\nhead = L.Dense(1, activation=\"linear\")(head)\n\nmodel = Model(inputs=[model_mlp.input, productiondate], outputs=head)\nmodel.summary()\noptimizer = tf.keras.optimizers.Adam(0.01)\nmodel.compile(loss='MAPE',optimizer=optimizer, metrics=['MAPE'])\nhistory = model.fit([X_train, X_train.productionDate.values], y_train,\n                    batch_size=512,\n                    epochs=500, # \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438 \u043c\u044b \u043e\u0431\u0443\u0447\u0430\u0435\u043c \u043f\u043e\u043a\u0430 EarlyStopping \u043d\u0435 \u043e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435\n                    validation_data=([X_test, X_test.productionDate.values], y_test),\n                    callbacks=callbacks_list\n                   )\nmodel.load_weights('..\/working\/best_model.hdf5')\ntest_predict_nn_bonus = model.predict([X_test, X_test.productionDate.values])\nprint(f\"TEST mape: {(mape(y_test, test_predict_nn_bonus[:,0]))*100:0.2f}%\")\n# ","meta":"{'source': 'AI4Code', 'id': '9cf62555b0756f'}"}
{"id":"7502","text":"\"\"\"\n**Mechanisms of Action (MoA)**\n\n\u0412 \u0444\u0430\u0440\u043c\u0430\u043a\u043e\u043b\u043e\u0433\u0438\u0438 \u0442\u0435\u0440\u043c\u0438\u043d \u00ab\u041c\u0435\u0445\u0430\u043d\u0438\u0437\u043c \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439\u00bb (MoA) \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0441\u044f \u043a \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u043e\u043c\u0443 \u0431\u0438\u043e\u0445\u0438\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u043c\u0443 \u0432\u0437\u0430\u0438\u043c\u043e\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044e, \u043f\u043e\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u043e\u043c \u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u043b\u0435\u043a\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442 \u0441\u0432\u043e\u0439 \u0444\u0430\u0440\u043c\u0430\u043a\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u044d\u0444\u0444\u0435\u043a\u0442. \u041c\u0435\u0445\u0430\u043d\u0438\u0437\u043c \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f \u043e\u0431\u044b\u0447\u043d\u043e \u0432\u043a\u043b\u044e\u0447\u0430\u0435\u0442 \u0443\u043f\u043e\u043c\u0438\u043d\u0430\u043d\u0438\u0435 \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u044b\u0445 \u043c\u043e\u043b\u0435\u043a\u0443\u043b\u044f\u0440\u043d\u044b\u0445 \u043c\u0438\u0448\u0435\u043d\u0435\u0439, \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c\u0438 \u0441\u0432\u044f\u0437\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u043b\u0435\u043a\u0430\u0440\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u043e, \u0442\u0430\u043a\u0438\u0445 \u043a\u0430\u043a \u0444\u0435\u0440\u043c\u0435\u043d\u0442 \u0438\u043b\u0438 \u0440\u0435\u0446\u0435\u043f\u0442\u043e\u0440. \u0420\u0435\u0446\u0435\u043f\u0442\u043e\u0440\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b \u0438\u043c\u0435\u044e\u0442 \u0441\u043f\u0435\u0446\u0438\u0444\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u0441\u0440\u043e\u0434\u0441\u0442\u0432\u043e \u043a \u043f\u0440\u0435\u043f\u0430\u0440\u0430\u0442\u0430\u043c, \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u043d\u043e\u0435 \u043d\u0430 \u0445\u0438\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0435 \u043f\u0440\u0435\u043f\u0430\u0440\u0430\u0442\u0430, \u0430 \u0442\u0430\u043a\u0436\u0435 \u043d\u0430 \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u043e\u043c \u0432\u043e\u0437\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u0442\u0430\u043c \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442.\n\n\u0412 \u043a\u043e\u043d\u043a\u0443\u0440\u0441\u0435 \u0440\u0435\u0448\u0430\u0435\u0442\u0441\u044f \u0437\u0430\u0434\u0430\u0447\u0430, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0437\u0430\u043a\u043b\u044e\u0447\u0430\u0435\u0442\u0441\u044f \u0432 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0438 \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u0446\u0435\u043b\u0435\u0439 \u043e\u0442\u0432\u0435\u0442\u043d\u044b\u0445 \u043c\u0435\u0440, \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u043c\u044b\u0445 \u0432 \u0440\u0430\u043c\u043a\u0430\u0445 \u041c\u0435\u0445\u0430\u043d\u0438\u0437\u043c\u0430 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439 (\u041c\u041e\u0414) \u0432 \u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u0438 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0445 \u043e\u0431\u0440\u0430\u0437\u0446\u043e\u0432. \u041f\u0440\u043e\u0431\u044b \u2013 \u044d\u0442\u043e \u043f\u0440\u0435\u043f\u0430\u0440\u0430\u0442\u044b, \u043f\u0440\u043e\u0444\u0438\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 \u0432 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0445 \u0432\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0442\u043e\u0447\u043a\u0430\u0445 \u0438 \u0434\u043e\u0437\u0430\u0445. \u041d\u0430\u0431\u043e\u0440 \u0434\u0430\u043d\u043d\u044b\u0445 \u0441\u043e\u0441\u0442\u043e\u0438\u0442 \u0438\u0437 \u0440\u0430\u0437\u043b\u0438\u0447\u043d\u044b\u0445 \u0433\u0440\u0443\u043f\u043f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0438 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u0431\u043e\u043b\u0435\u0435 \u0434\u0432\u0443\u0445\u0441\u043e\u0442 \u043c\u0438\u0448\u0435\u043d\u0435\u0439 \u0444\u0435\u0440\u043c\u0435\u043d\u0442\u043e\u0432 \u0438 \u0440\u0435\u0446\u0435\u043f\u0442\u043e\u0440\u043e\u0432.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nPATH = '\/kaggle\/input\/lish-moa\/'\ntrain_df = pd.read_csv(PATH + 'train_features.csv')\ntest_df = pd.read_csv(PATH + 'test_features.csv')\n\ntarget_df = pd.read_csv(PATH + 'train_targets_scored.csv')\nsub_df = pd.read_csv(PATH + 'sample_submission.csv')\ntrain_df.head()\n\"\"\"\n**\u041f\u0440\u0438\u0437\u043d\u0430\u043a\u0438**\n- `sig_id` - \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0439 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043e\u0431\u0440\u0430\u0437\u0446\u0430\n- \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0441 \u043f\u0440\u0435\u0444\u0438\u043a\u0441\u043e\u043c `g`- \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u043c\u0438 \u044d\u043a\u0441\u043f\u0440\u0435\u0441\u0441\u0438\u0438 \u0433\u0435\u043d\u043e\u0432, \u0438 \u0438\u0445 772 (\u043e\u0442 `g-0` \u0434\u043e `g-771`).\n- \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0441 \u043f\u0440\u0435\u0444\u0438\u043a\u0441\u043e\u043c `c` - \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043a\u0430\u043c\u0438 \u0436\u0438\u0437\u043d\u0435\u0441\u043f\u043e\u0441\u043e\u0431\u043d\u043e\u0441\u0442\u0438 \u043a\u043b\u0435\u0442\u043e\u043a, \u0438\u0445 100 (\u043e\u0442 `c-0` \u0434\u043e `c-99`).\n- `cp_type` - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0441 \u0434\u0432\u0443\u043c\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f\u043c\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442, \u0447\u0442\u043e \u043e\u0431\u0440\u0430\u0437\u0446\u044b \u043e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u044e\u0442\u0441\u044f \u0441\u043e\u0441\u0442\u0430\u0432\u043e\u043c \u0438\u043b\u0438 \u0443\u043f\u0440\u0430\u0432\u043b\u044f\u044e\u0449\u0438\u043c \u0432\u043e\u0437\u043c\u0443\u0449\u0435\u043d\u0438\u0435\u043c (trt_cp \u0438\u043b\u0438 ctl_vehicle)\n- `cp_time` - \u044d\u0442\u043e \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u043b\u0435\u0447\u0435\u043d\u0438\u044f (24, 48 \u0438\u043b\u0438 72 \u0447\u0430\u0441\u0430)\n- `cp_dose` - \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0441 \u0434\u0432\u0443\u043c\u044f \u043a\u0430\u0442\u0435u\u043e\u0440\u0438\u044f\u043c\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442, \u0447\u0442\u043e \u0434\u043e\u0437\u0430 \u043d\u0438\u0437\u043a\u0430\u044f \u0438\u043b\u0438 \u0432\u044b\u0441\u043e\u043a\u0430\u044f (`D1` \u0438\u043b\u0438 `D2`)\n\"\"\"\ntrain_df.drop(['sig_id'], axis=1, inplace=True)\ntest_df.drop(['sig_id'], axis=1, inplace=True)\ntarget_df.head()\ntarget_df.drop(['sig_id'], axis=1, inplace=True)\ntarget_df.sum(axis=1).sample(20)\n\"\"\"\n**\u041f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430**\n\"\"\"\nidx = len(train_df)\ndata_df = pd.concat([train_df, test_df], axis = 0)\ndel train_df, test_df\nfrom sklearn.preprocessing import LabelEncoder\n\nenc = LabelEncoder()\n\ncategory_cols = ['cp_dose', 'cp_type']\n\nfor cols in category_cols:\n    data_df[cols] = enc.fit_transform(data_df[cols])\nX_train = data_df.iloc[:idx,:]\nX_test = data_df.iloc[idx:,:]\ny_train = target_df\n\"\"\"\n**\u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438**\n\"\"\"\nfrom xgboost import XGBClassifier\n\nmodel = XGBClassifier(\n            n_estimators=500,\n            seed=42,\n            learning_rate=0.1,\n            max_depth=5, \n            colsample_bytree=1,\n            subsample=1,\n            tree_method='gpu_hist')\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import log_loss\n\ncolumns = target_df.columns\nsubmission = sub_df.copy()\nsubmission.loc[:,columns] = 0\n\nfor c, column in enumerate(columns):\n    y = y_train[column]\n    loss = 0\n    \n    kf = KFold(n_splits=5, random_state=42, shuffle=True)  \n    for ix, (train_idx, val_idx) in enumerate(kf.split(X_train)):\n              \n        X_train_cv, X_val_cv = X_train.iloc[train_idx], X_train.iloc[val_idx]\n        y_train_cv, y_val_cv = y.iloc[train_idx], y.iloc[val_idx]\n    \n        model.fit(\n            X_train_cv, y_train_cv, \n            eval_set=[(X_val_cv,  y_val_cv)], \n            eval_metric = \"logloss\", \n            early_stopping_rounds=30, \n            verbose=0)\n        \n        val_preds = model.predict(X_val_cv)\n        \n        loss += log_loss(y_val_cv,val_preds, labels=[0,1])\n        \n        preds = model.predict_proba(X_test)[:,1]\n        submission[column] += preds\/5\n                         \n    print(\"model \"+str(c+1)+\": loss =\"+str(loss\/5))\nsubmission.loc[test['cp_type']==1, target_df.columns] = 0\nsubmission.to_csv('submission.csv', index=False)\nfrom sklearn.multioutput import MultiOutputClassifier\n\nmo_model = MultiOutputClassifier(model)\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import log_loss\n\ntest_preds = np.zeros((X_test.shape[0], y_train.shape[1]))\n\nkf = KFold(n_splits=5, random_state=42, shuffle=True)\n\nloss = []\n\nfor ix, (train_idx, val_idx) in enumerate(kf.split(X_train)):\n    \n    X_train_cv, X_val_cv = X_train.iloc[train_idx], X_train.iloc[val_idx]\n    y_train_cv, y_val_cv = y_train.iloc[train_idx], y_train.iloc[val_idx]\n    \n    \n    mo_model.fit(X_train_cv, y_train_cv)\n    val_preds = model.predict_proba(X_val_cv) \n    val_preds = np.array(val_preds)[:,:,1].T #(num_labels,num_samples,prob_0\/1)\n    \n    loss.append(log_loss(np.ravel(y_val_cv), np.ravel(val_preds)))\n    \n    preds = model.predict_proba(X_test)\n    preds = np.array(preds)[:,:,1].T #(num_labels,num_samples,prob_0\/1)\n    test_preds += preds \/ 5 \n\nprint(loss)\nprint('Mean CV loss across folds', np.mean(loss))\nmask = X_test['cp_type']=='ctl_vehicle'\ntest_preds[mask] = 0\nsub_df.iloc[:,1:] = test_preds\nsub_df.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '0df2232c46205b'}"}
{"id":"54866","text":"# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express  as px\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot\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\ndf_train=pd.read_csv('..\/input\/new-york-city-taxi-fare-prediction\/train.csv',nrows=1000000)\ndf_test=pd.read_csv('..\/input\/new-york-city-taxi-fare-prediction\/test.csv')\ndf_train.head()\ndf_train.describe()\n#we can see that fare is in negative, and also according to google max and min lat is [90,-90]\n#and long is[180,-180].So we will remove the data points \/outliers \n#we will check the dist plot of fare\n(df_train['fare_amount'].hist(bins=50))\n#data dist is skewed\n#according to passengers_counts max is 208,lets check it\n\na=df_train[df_train['passenger_count']<=6]\na\n# mostly its an error, we will remove this also\nsns.countplot(a['passenger_count'])\n#1 passengers are more, followed  by 2 and 5\n#df_train[(df_train['pickup_latitude']<=90) & (df_train['pickup_latitude']>=-90) ]\ntrain=df_train[(df_train['pickup_longitude'].between(-180,180)) & (df_train['pickup_latitude'].between(-90,90))]\ntrain=train[train['fare_amount']>=0]#amt cannot be negative\ntrain=train[(train['dropoff_longitude'].between(-180,180)) &(train['dropoff_latitude'].between(-90,90))]\n\n\ntest=df_test[(df_test['pickup_longitude'].between(-180,180)) & (df_test['pickup_latitude'].between(-90,90))]\n#test=test[test['fare_amount']>=0]\ntest=test[(test['dropoff_longitude'].between(-180,180)) &(test['dropoff_latitude'].between(-90,90))]\n\ntrain.describe()\n#passenger count is 208,lets check it\ntrain[train['passenger_count']==208]#its noise data, we will remove it\ntrain=train[train['passenger_count']<=6]\ntest=test[test['passenger_count']<=6]\n\ntrain.head()\ntrain.info()\n#train['key']=pd.to_datetime(train['key'])#its just unique string in both train and test.\ntrain['pickup_datetime']=pd.to_datetime(train['pickup_datetime'])\ntest['pickup_datetime']=pd.to_datetime(test['pickup_datetime'])\ntest.info()\ntrain['day']=train['pickup_datetime'].dt.day\ntrain['month']=train['pickup_datetime'].dt.month\ntrain['year']=train['pickup_datetime'].dt.year\ntrain['hour']=train['pickup_datetime'].dt.hour\ntrain['dayofweek']=train['pickup_datetime'].dt.dayofweek\n\n#test\ntest['day']=test['pickup_datetime'].dt.day\ntest['month']=test['pickup_datetime'].dt.month\ntest['year']=test['pickup_datetime'].dt.year\ntest['hour']=test['pickup_datetime'].dt.hour\ntest['dayofweek']=test['pickup_datetime'].dt.dayofweek\ntest.head()\n\"\"\"\nNow calculating the distance between 2 pts using their coordinates     This can be done by using Haversine formula\n\n\na = sin\u00b2(\u03c6B - \u03c6A\/2) + cos \u03c6A * cos \u03c6B * sin\u00b2(\u03bbB - \u03bbA\/2)\nc = 2 * atan2( \u221aa, \u221a(1\u2212a) )\nd = R \u22c5 c\n\n\u03c6 is latitude of B,\u03bb is longitude R is earth\u2019s radius (mean radius = 6,371km)\nlat and long need to be in radians\n\"\"\"\nimport numpy as np\n\ndef haversine(df):\n    \n    \n    lat1= np.radians(df[\"pickup_latitude\"])\n    lat2 = np.radians(df[\"dropoff_latitude\"])\n    #### Based on the formula  x1=drop_lat,x2=dropoff_long \n    dlat = np.radians(df['dropoff_latitude']-df[\"pickup_latitude\"])\n    dlong = np.radians(df[\"dropoff_longitude\"]-df[\"pickup_longitude\"])\n    a = np.sin(dlat\/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlong\/2)**2\n\n    c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))\n    r = 6371 # Radius of earth in kilometers. Use 3956 for miles\n    return c * r\n\n\n\n#for i in range(len(t))\ntrain['dist']=haversine(train)\ntest['dist']=haversine(test)\ntest.head()\n##)\ntrain['dist'].describe()\n# there is huge diff between 75% and max \ntest['dist'].describe()\ntrain[train['dist']>=100]\n# we can see that either the pickup lat\/long is zero or dropoff lat\/long is 0\ntrain[(((train['pickup_latitude']==0)|(train['pickup_longitude']==0))&((train['dropoff_latitude']==0)|(train['dropoff_longitude']==0)))].head()\n\n#dist is large bcz either lat or long is not avialable,\n#fare amt is also less even though dist is very large, this is noise , we can impute dist value for which fare amt is not zero\n#so we will drop rows that have both lat and long 0 for pickup and dropoff\n#pickup 0\ntrn=train.copy()\na=trn[(((trn['pickup_latitude']==0)&(trn['pickup_longitude']==0))&((trn['dropoff_latitude']==0)|(trn['dropoff_longitude']==0)))].index\ntrn.drop(a,axis=0,inplace=True)\n\ntst=test.copy()\ntst[(((tst['pickup_latitude']==0)&(tst['pickup_longitude']==0)))]\n#no data is present\n#dropping row which has fare_amt=0 and also lat\/long=0\nb=trn[((trn['pickup_latitude']==0)&(trn['pickup_longitude']==0))&((trn['dropoff_latitude']!=0)|(trn['dropoff_longitude']!=0))&(trn['fare_amount']==0)].index\ntrn.drop(b,axis=0,inplace=True)\n\n#no data for test\n#vice versa \nb=trn[((trn['pickup_latitude']!=0)&(trn['pickup_longitude']!=0))&((trn['dropoff_latitude']==0)|(trn['dropoff_longitude']==0))&(trn['fare_amount']==0)].index\ntrn.drop(b,axis=0,inplace=True)\n\n#no data for test\ntrn.describe()\n#fareamt and dist have min 0\ntst.describe()\n#same lat and long for pickup and dropoff hence zero fare and  dist, drop them\nsame=trn[(trn['fare_amount']==0) & (trn['dist']==0) & (trn['pickup_latitude']==trn['dropoff_latitude'])].index\ntrn.drop(same,axis=0,inplace=True)\n\n\n\"\"\"\nTAKING CARE OF DISTANCE IMPUTATION\n\"\"\"\n\n\nfare_up=trn[(trn['fare_amount']==0) & (trn['dist']!=0)]\n\n#we wil impute value,accrding to google, on weekend initial charge=3$ and 1.5$\/km and night\n# we wil impute value,accrding to google, on weekdays initial charge=2.5$ and 1.5$\/km\n#fare=initial+dist*1.5$\n#so dist=(fare-initial)\/1.5\n\n#Mon_friday Morning 6am-8pm \nfare_up_mor=fare_up[fare_up['hour'].between(6,19,inclusive=True) & (fare_up['dayofweek'].between(1,5))]\nfare_up_mor['fare_amount']=fare_up.apply(lambda x : 2.5+(fare_up['dist']*1.5))\nfare_up.update(fare_up_mor)\n\n#Mon-Friday 8pm-6pm\nfare_up_night=fare_up[((fare_up['hour']<6) | (fare_up['hour']>=20)) & (fare_up['dayofweek'].between(1,5))]\nfare_up_night['fare_amount']=fare_up.apply(lambda x : 3+(fare_up['dist']*1.5))\nfare_up.update(fare_up_night)\n\n#saturday and sunday all day\nfare_up_wkend=fare_up[(fare_up['dayofweek']==0) | (fare_up['dayofweek']==6)]\nfare_up_wkend['fare_amount']=fare_up.apply(lambda x : 3+(fare_up['dist']*1.5))\nfare_up.update(fare_up_wkend)\n\n\ntrn.update(fare_up)\n\"\"\"\n#FARE IMPUTATION\n\"\"\"\ntrn[(trn['fare_amount']!=0) & (trn['dist']==0)]\n#seems dist value does not go accordingly with fare , so we will try to impute for those datapts for which price is too high and dist traveeled is too low\ndist_up=trn[(trn['fare_amount']>100) & (trn['dist']<5)]\n\n##Mon_friday Morning 6am-8pm \ndist_up_mor=dist_up[dist_up['hour'].between(6,19,inclusive=True) & (dist_up['dayofweek'].between(1,5))]\ndist_up_mor['dist']=dist_up.apply(lambda x :((dist_up['fare_amount']-2.5)\/1.5))\ndist_up.update(dist_up_mor)\n\n#Mon-Friday 8pm-6pm\ndist_up_night=dist_up[((dist_up['hour']<6) | (dist_up['hour']>=20)) & (dist_up['dayofweek'].between(1,5))]\ndist_up_night['dist']=dist_up.apply(lambda x : ((dist_up['fare_amount']-2.5)\/1.5))\ndist_up.update(dist_up_night)\n\n#saturday and sunday all day\ndist_up_wkend=dist_up[(dist_up['dayofweek']==0) | (dist_up['dayofweek']==6)]\ndist_up_wkend['dist']=dist_up.apply(lambda x : ((dist_up['fare_amount']-2.5)\/1.5))\ndist_up.update(dist_up_wkend)\n\n\ntrn.update(dist_up)\ntrn.describe()\n#1> does dist  affects fare\nsns.scatterplot(train[train['dist']<100]['dist'],train['fare_amount'])\n\n#we can see that there is some linearity\n#2>fare price wrt to hours\nplt.figure(figsize=(20,6))\nsns.barplot(train['hour'],train[train['fare_amount']<100]['fare_amount'])\n#fareamt wrt to weekdays and weekends\nplt.figure(figsize=(20,6))\nsns.boxplot(train['dayofweek'],train[train['fare_amount']<100]['fare_amount'])\nplt.figure(figsize=(20,6))\nsns.barplot(train['year'],train[train['fare_amount']<100]['fare_amount'])\n\n#Mean priec has increased over the year\ntrn.groupby(['month'])['passenger_count'].count().sort_values(ascending=False).plot(kind='bar')\n#During first 6 months  most people availing cab\nplt.figure(figsize=(15,5))\nsns.countplot(trn['hour'])# most person avail cab in the evening and least in midnight\ntrn.describe()\n#so if we look at test data, max dist is 99 and our trn data its 12594, \nind=trn[trn['dist']>100].sort_values(by='dist',ascending=False).index\n\ntrn.loc[ind]\n\n# for now we can will drop this\n\ntrn=trn.drop(ind,axis=0)\nmaxprice=trn['fare_amount'].sort_values(ascending=False).index\ntrn.loc[maxprice]\nplt.figure(figsize=(10,7))\nsns.heatmap(trn.corr(),annot=True)\n#modelling\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import r2_score,mean_absolute_error,mean_squared_error\nprint(f'trains shape{trn.shape}  test shape{tst.shape}')\nX=trn[['pickup_longitude',\n       'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude',\n       'passenger_count', 'day', 'month', 'year', 'hour', 'dayofweek', 'dist']]\ny=trn['fare_amount']\nx_train,x_test,val_train,val_test=train_test_split(X,y,test_size=0.3)\nlr=LinearRegression()\n##def fit(x_train,val_train,)\nlr.fit(x_train,val_train)\ny_hat=lr.predict(x_test)\nprint('R2 value is',r2_score(val_test,y_hat))\nprint('MAE',mean_absolute_error(val_test,y_hat))\nprint('SMAE',mean_squared_error(val_test,y_hat)**0.5)\n\ntest.columns\ntest=test[['pickup_longitude', 'pickup_latitude',\n       'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'day',\n       'month', 'year', 'hour', 'dayofweek', 'dist']]\n\ndt=DecisionTreeRegressor()\n\ndt.fit(x_train,val_train)\ny_hat=dt.predict(test)\n\nsubmission = pd.read_csv('..\/input\/new-york-city-taxi-fare-prediction\/sample_submission.csv')\nsubmission['fare_amount'] = y_hat\nsubmission.to_csv('submission_1.csv', index=False)\n","meta":"{'source': 'AI4Code', 'id': '6511c89349cff8'}"}
{"id":"85755","text":"\"\"\"\n#### Hi all.  \ud83d\ude4b\u2022\u2642\ufe0f \n\n#### We continue our **Beginner-Intermediate Friendly Machine Learning series**, which would help anyone who wants to learn or refresh the basics of ML.\n\n#### What we have covered: \n\n#### [Beginner Friendly Detailed Explained EDAs \u2013 For anyone at the beginnings of DS\/ML journey](https:\/\/www.kaggle.com\/general\/253911#1393015) \u2714\ufe0f\n\n#### [BIAS & VARIANCE TRADEOFF](https:\/\/www.kaggle.com\/kaanboke\/ml-basics-bias-variance-tradeoff) \u2714\ufe0f\n\n#### [LINEAR ALGORITHMS](https:\/\/www.kaggle.com\/kaanboke\/ml-basics-linear-algorithms)  \u2714\ufe0f\n\n#### [NONLINEAR ALGORITHMS](https:\/\/www.kaggle.com\/kaanboke\/nonlinear-algorithms)  \u2714\ufe0f\n\n#### [The Most Used Methods to Deal with MISSING VALUES](https:\/\/www.kaggle.com\/kaanboke\/the-most-used-methods-to-deal-with-missing-values)  \u2714\ufe0f\n\n#### [Beginner Friendly End to End ML Project- Classification with Imbalanced Data](https:\/\/www.kaggle.com\/kaanboke\/beginner-friendly-end-to-end-ml-project-enjoy)  \u2714\ufe0f\n\n#### [How to Prevent the Data Leakage ?](https:\/\/www.kaggle.com\/kaanboke\/how-to-prevent-the-data-leakage) \u2714\ufe0f\n\n#### In this notebook we will  cover one of the important concepts of the **Machine Learning Evaluation Metrics**\n#### Enjoy \ud83e\udd18\n\"\"\"\n\"\"\"\n#### **By the way, when you like the topic, you can show it by supporting** \ud83d\udc4d\n\n####  **Feel free to leave a comment in the notebook**. \n\n#### All the best \ud83e\udd18\n\"\"\"\n\"\"\"\n![](https:\/\/miro.medium.com\/max\/1400\/1*FUZS9K4JPqzfXDcC83BQTw.png)\n\"\"\"\n\"\"\"\nImage Credit: https:\/\/miro.medium.com\/\n\"\"\"\n\"\"\"\n<a id=\"toc\"><\/a>\n\n<h3 class=\"list-group-item list-group-item-action active\" data-toggle=\"list\" role=\"tab\" aria-controls=\"home\">Table of Contents<\/h3>\n    \n* [What is Evaluation Metrics?](#0)\n* [Classification Evalution Metrics](#1)\n    * [Confusion Matrix](#2)\n    * [Accuracy](#3)\n    * [Precision & Recall](#4)\n    * [F Score (F Measure)](#5)\n    * [ROC Curve (AUC)](#6)\n    * [Log Loss](#7)\n  \n  \n* [Regression Evaluation Metrics](#8)    \n    * [Mean Absolute Error(MAE)](#9)\n    * [Mean Squared Error (MSE)](#10)    \n    * [Root Mean Squared Error (RMSE)](#11)\n    * [R Squared (R2)](#12)\n\n\n* [Conclusion](#13)\n* [References & Further Reading](#14)\n\"\"\"\n\"\"\"\n<a id=\"0\"><\/a>\n<font color=\"lightseagreen\" size=+2.5><b>What is Evaluation Metrics? & Why We Need Them?<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\n\"\"\"\n\"\"\"\n![](https:\/\/www.magazine.etnfocus.com\/wp-content\/uploads\/2017\/08\/metrics.jpg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.magazine.etnfocus.com\n\"\"\"\n\"\"\"\n- In machine learning, evaluation metrics are used to measure the performance of machine learning models\/algorithms.\n- Evaluation metrics are crucial. Based on the model performance we are giving decisions.\n- We should remember that we are not just only looking for a better model, also looking for our end goal.\n- Let's imagine our end goal is to make an application to detect fraud.\n- We develop our model based on the data in hand, which contains 99.5% non-fraud cases and %.5 fraud cases.\n- Without using the correct evaluation metric on this imbalanced data we will deploy the model with poor performance and prediction on the real data.\n\"\"\"\n\"\"\"\n- In this study we will divide our evaluation metrics into two categories.\n    - Classification Evaluation Metrics\n    - Regression Evaluation Metrics\n \n - Ok let's start.\n\"\"\"\n\"\"\"\n![](https:\/\/www.negotiations.com\/wp-content\/uploads\/2017\/05\/negotiation-success.jpg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.negotiations.com\n\"\"\"\n\"\"\"\n<a id=\"1\"><\/a>\n<font color=\"lightseagreen\" size=+2.5><b>Classification Evaluation Metrics<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- Classification problems are the most common problems in the Machine Learning.\n- It would be a good idea to refresh our knowledge on the classification evaluation metrics.\n- In the classification part of the study, we will use Credit Card Fraud dataset.\n\"\"\"\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \n\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler,PowerTransformer\nfrom sklearn.model_selection import train_test_split, RepeatedStratifiedKFold,cross_val_score,GridSearchCV\nfrom sklearn.linear_model import LinearRegression,LogisticRegression\nfrom sklearn.pipeline import Pipeline,make_pipeline\nfrom sklearn.metrics import mean_squared_error,classification_report,make_scorer,accuracy_score,plot_roc_curve,auc,roc_curve\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.model_selection import KFold\n\nimport cufflinks as cf\nimport plotly.offline\ncf.go_offline()\ncf.set_config_file(offline=False, world_readable=True)\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n<a id=\"2\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Confusion Matrix<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- Before starting the evaluation metrics, we should be on the same page.\n- Let's refresh the basics.\n\"\"\"\n\"\"\"\n![](https:\/\/www.superheuristics.com\/wp-content\/uploads\/2021\/03\/Blog_image_confusion-matrix.png)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.superheuristics.com\n\"\"\"\n\"\"\"\n- **True Positive**: Predicted vale is positive and we predicted correctly. \n- Real Transaction --> Fraud  and our model correctly predict as fraud.\n\"\"\"\n\"\"\"\n- **False Negative**: Predicted value is negative, but actual value is positive. Our prediction is false.\n   - We predict non-fraud, benign, but actual value is fraud or malign.\n   - Which is also called **Type 2 error**.\n\"\"\"\n\"\"\"\n- **False Positive**: Our prediction is positive but actual value is negative. Our prediction is false.\n   - We predict as fraud or malign but actual value is non-fraud or benign.\n   - Which is also called as **Type 1 error**.\n\"\"\"\n\"\"\"\n- **True Negative** : We predict as negative and our prediction is correct. Actual value is negative ( non-fraud, benign, etc.)\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/www.publichealthnotes.com\/wp-content\/uploads\/2020\/04\/slide_9.jpg\" width=\"600\">\n\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.publichealthnotes.com\n\"\"\"\n\"\"\"\n<a id=\"3\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Accuracy<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- One of the most common evaluation metrics, we can see in the real world and also in the Kaggle.\n- Accuracy is better to use with balanced classification problem and when all predictions and prediction errors are equally important (for example using iris dataset. Every class has equal instances).\n\n- Balanced Data: Target has equal or almost equal number of instances.\n- Prediction Errors are  equally important: Predicting  Class A, Class B or Probability of detecting fraud or detecting non fraud\n- Is it really possible in the real life?\n- I can't say, it is impossible, but fair to say it is rare.\n- Most of the classification problem, we handle in ML, has imbalanced data and consequences of the prediction errors are rarely same.\n- When we have the imbalanced data, accuracy is not a good evaluation metric to use.\n\n\"\"\"\n\"\"\"\n- Formula for the accuracy is easy one: Total number of correct predictions divided by the total number of predictions.\n\"\"\"\n\"\"\"\n![](https:\/\/www.mydatamodels.com\/wp-content\/uploads\/2020\/10\/2.-Accuracy-formula-machine-learning-algorithms.png)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.mydatamodels.com\n\"\"\"\n\"\"\"\n- It is clearly seen in the formula, why accuracy is not a good measure for the imbalanced data.\n- Imagine we have  a data...\n- Just kidding, you don't need to imagine we have real data to see.\n- We will use credit card fraud data to estimate fraud cases.\n- This is imbalanced data. Be careful !!!\n\"\"\"\ndf_credit = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\ndf_credit.head()\ndf_credit['Class'].value_counts(normalize=True)\n\"\"\"\n- When we look at the formula above, if we put 100 cases as non-fraud, based on the equation we can get 99.8% accuracy\n-  99.8% accuracy !!!!\n- It is great isn't it ?\n- Let's see all of this by using Dummy Classifier.\n\"\"\"\n\ndf_credit = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\n\nX = df_credit.drop('Class', axis=1)\ny = df_credit['Class']\n\nmodel =DummyClassifier(strategy='most_frequent')\n\n#pipeline = Pipeline(steps=[('imp', SimpleImputer(strategy='median')),('s',MinMaxScaler()),('m', model)]) \n\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=42)\n\nresult = cross_val_score(model, X, y,  scoring='accuracy',cv=cv, n_jobs=-1)\n\nprint(f'{round(np.mean(result),6)}')\n\"\"\"\n- Ok we have 99.8% accuracy on the credit card fraud, without learning anything, why we are bothering ourselves to build a model?\n\n- We can easily select every case as a non-fraud and 99.8 out of 100 times, we are right.\n\n- Why aren't we celebrating it?\n\"\"\"\n\"\"\"\n #### **What is the problem with the accuracy metric for the imbalanced data?**\n\n- Accuracy metric with imbalanced data gives us the accuracy on the majority class (non-fraud)\n- We can reach to 99.8% accuracy without building a machine leraning model, by always predicting the non-fraud.\n- The problem here is that accuracy is an inadequate measure for quantifying predictive performance in this imbalanced setting.\n- Accuracy does not report the correct score for the imbalanced data.\n- As we have seen overwhelming number of non-fraud instances (99.8%) surprass the fraud instances.\n- Even Dummy Classifier can get the 99.8% accuracy score.\n\"\"\"\n\"\"\"\n<div class=\"alert alert-block alert-info\">\n<b>Rule of Thumb:<\/b> Do not use accuracy score metric with the imbalanced data.\n<\/div>\n\"\"\"\n\"\"\"\n<a id=\"4\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Precision & Recall<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n#### **Precision**\n- Precision gives us accuracy of the positive classs (fraud case, cancer case, malign case, etc).\n- Main aim of the precision is the minimize the false positive (Type 1 error)\n\"\"\"\n\"\"\"\n![](https:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/2\/26\/Precisionrecall.svg\/600px-Precisionrecall.svg.png)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/en.wikipedia.org\n\"\"\"\n\"\"\"\n#### **Recall**\n- Recall gives us the score of the number of correct positive predictions made out of all correct positive predictions.\n- Main aim ofthe recall is the minimize the false negative (Type 2 error).\n\"\"\"\n\"\"\"\n![](https:\/\/i.pinimg.com\/originals\/aa\/91\/7a\/aa917a42422eaedb18224224519e48f0.jpg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.pinterest.com\n\"\"\"\n\"\"\"\n<div class=\"alert alert-block alert-info\">\n<b>Precision & Recall --> Which one to use and When ?<\/b> \n     <ul style=\"list-style-type:none\">\n         <li><b>Precision:<\/b>  When our aim is to minimize false positive (Only fraud case, not include non-fraud transaction as a fraud transaction)<\/li>\n         <li><b>Recall : <\/b> When our aim is to minimize false negative (Every cancer patient should be classified as  a cancer patient, not classified as a healthy one)<\/li>\n      <\/ul>\n    \n   \n<\/div>\n\n\"\"\"\n\"\"\"\n<a id=\"5\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>F Score (F Measure)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- In real life we want to get perfect prediction on the positive class\n- Which means that we are looking high recall and high precision.\n- We have to balance them to get what we want.\n- F score provides us a score which combines precision and recall into a single measure without losing  their properties.\n\"\"\"\n\"\"\"\n![](https:\/\/i.ytimg.com\/vi\/fcO9820wCXE\/hqdefault.jpg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.youtube.com\/channel\/UCeoF_5Kw0YyWOqhAbQGrxJQ\n\"\"\"\n\ndef classification_report_with_validation(y_true, y_pred):\n    real_values.extend(y_true)\n    predicted_values.extend(y_pred)\n    return accuracy_score(y_true, y_pred)\n\n\ndf_credit = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\n\nX = df_credit.drop('Class', axis=1)\ny = df_credit['Class']\n\nreal_values = []\npredicted_values = []\n\nmodel =LogisticRegression(solver='liblinear')\n\npipeline = Pipeline(steps=[('s',MinMaxScaler()),('m', model)]) \n\ncv = KFold(n_splits=10, random_state=42)\n\nresult = cross_val_score(pipeline, X, y,  scoring=make_scorer(classification_report_with_validation),cv=cv)\n\nprint(classification_report(real_values, predicted_values)) \n\"\"\"\n- We didn't make any extensive exploratory analysis with the data. \n- We have just used it for showing the usage of the classification metrics on the imbalanced data.\n- For having said that precision: .93 , recall : 77 and f1 score: .83\n- And accuracy is 1.00 !!!\n\"\"\"\n\"\"\"\n- As we have mentioned before, deciding which metric to use very crucial step on the Machine Learning projects.\n- Stakeholders \/ customers concerns should be taken into consideration before deciding which metric to use.\n\n- In fraud detection case, if our customer aims to reduce false negative:\n    - Which means every fraud case should be defined as a fraud case\n    - Missing the prediction of the fraud case should be minimum\n    - We have to focus on how to reduce wrongly classified non-fraud cases.\n    - In that case we are looking for minimizin type 2 error and increasing the positive rate.\n    - We are looking for higher score recall for fraud case.\n    \n    \n- In fraud detection case, if our customer aims to reduce false positive:\n    - Which means we want to be sure that positive case should be positive case, not the others\n    - We do not want to classify our loyal customer's transaction as a fraud transaction and block his\/her account.\n    - We have to focus on wrongly classified positive case.\n    - In that case we are looking for minimizin type 1 error and decreasing the false positive rate.\n    - We are looking for higher score precision for fraud case.\n \n \n- If we want to reduce the risk of the fraud without losing our customer:\n    - We want to make a balance between precision and recall\n    - It would be good idea to focus on F score\n\n\"\"\"\n\"\"\"\n<a id=\"6\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>ROC Curve (AUC)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- ROC Curve (receiver operating characteristic curve- AUC) measures model's ability to make distinction between two classes (positive & negative).\n- ROC Curve score close to 1, represents better model.\n- ROC Curve shows false positive rate against the true positive rate (recall)\n- What we are looking for : **High recall and low false positive rate**\n- ROC Curve should be as close as possible to the top left corner.\n- No matter how imbalanced  data we have,predicting randomly always produces an AUC of 0.5.\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/els-jbs-prod-cdn.jbs.elsevierhealth.com\/cms\/attachment\/36cdb4ec-0c7d-48cb-9a4d-7cb463f8b7c3\/gr1.jpg\" width=\"600\">\n\"\"\"\n\"\"\"\nimage credit: https:\/\/www.jtcvs.org\/article\/S0022-5223(18)32875-7\n\"\"\"\ndf_credit = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\n\nX = df_credit.drop('Class', axis=1)\ny = df_credit['Class']\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1, stratify=y)\n\npipeline = make_pipeline(MinMaxScaler(), LogisticRegression(solver='liblinear'))\n\npipeline.fit(X_train,y_train)\nprobs = pipeline.predict_proba(X_test)\nfpr1, tpr1, thresholds = roc_curve(y_test, probs[:, 1], pos_label=1)\nroc_auc1 = auc(fpr1, tpr1)\n\n\nfig, ax = plt.subplots(figsize=(7.5, 7.5))\n \nplt.plot(fpr1, tpr1, label='ROC Curve 1 (AUC = %0.2f)' % (roc_auc1))\nplt.plot([0, 1], [0, 1], linestyle='--', color='red', label='Random Classifier')   \nplt.plot([0, 0, 1], [0, 1, 1], linestyle=':', color='green', label='Perfect Classifier')\nplt.xlim([-0.05, 1.05])\nplt.ylim([-0.05, 1.05])\nplt.xlabel('False positive rate')\nplt.ylabel('True positive rate')\nplt.legend(loc=\"lower right\")\nplt.show()\n\"\"\"\n- Higher value of True Positive Rate (TPR) means that false negative is very low. Model correctly predicted positive class.\n\n- Lower value of False Positive Rate means that false positive is very low. Model correctly predicted negative class.\n\"\"\"\n\"\"\"\n<div class=\"alert alert-block alert-info\">\n<b>Note:<\/b>  ROC Curve (AUC) is often more meaningful than using accuracy metric for classification problems with imbalanced data.\n<\/div>\n\"\"\"\n\"\"\"\n<a id=\"7\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Log Loss<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- Logarithmic loss or log loss metric is based on probabilities.\n- The log loss function calculates the negative log likelihood for probability predictions made by the binary classification model.\n\n\n\"\"\"\n\"\"\"\n![](https:\/\/i.stack.imgur.com\/UN1Pk.png)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/stackoverflow.com\n\"\"\"\n\"\"\"\n- What we are looking for  is the lowest level loss. The best possible log loss is 0.0\n- Any model with lower log-loss value brings us better predictions.\n\"\"\"\n\"\"\"\n- Below code-snippet is generated by using code recipe in the [Imbalanced Classification with Python](https:\/\/machinelearningmastery.com\/imbalanced-classification-with-python\/). I have made changes and modified it to adjust to the problem at hand.\n\"\"\"\n# log loss for naive probability predictions.\nfrom sklearn.metrics import log_loss\n# generate 2 class dataset\ndf_credit = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\n\nX = df_credit.drop('Class', axis=1)\ny = df_credit['Class']\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42, stratify=y)\n\n\n# no skill prediction 0\nprobabilities = [[1, 0] for _ in range(len(y_test))]\navg_logloss = log_loss(y_test, probabilities)\nprint('P(class0=1): Log Loss=%.3f' % (avg_logloss))\n# no skill prediction 1\nprobabilities = [[0, 1] for _ in range(len(y_test))]\navg_logloss = log_loss(y_test, probabilities)\nprint('P(class1=1): Log Loss=%.3f' % (avg_logloss))\n# baseline probabilities\nprobabilities = [[0.99, 0.01] for _ in range(len(y_test))]\navg_logloss = log_loss(y_test, probabilities)\nprint('Baseline: Log Loss=%.3f' % (avg_logloss))\n# perfect probabilities\navg_logloss = log_loss(y_test, y_test)\nprint('Perfect: Log Loss=%.3f' % (avg_logloss))\n\"\"\"\n- We have used log loss() function of the scikit-learn.\n- It took the predicted probability for each class as input and returned the average log loss.\n- Predicting certainty for fraud and non fraud label is punished with large log loss scores.\n- Since dataset has .5% minority class instances,  being certain for the minority class in all cases results in a much larger log loss score.\n- Baseline did better job by using target distribution.\n- Any model brings us lower than baseline log loss score would make prediction with skill.\n- Perfect log loss score: 0.0 means that there is no difference between prediction and the real values.\n\"\"\"\n\"\"\"\n<a id=\"8\"><\/a>\n<font color=\"lightseagreen\" size=+2.5><b>Regression Evaluation Metrics<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- It would be good idea to refresh our knowledge on the regression evaluation metrics.\n- We will look at \n    - Mean Absolute Error, \n    - Mean Squared Error\n    - Root Mean Squared Error\n    - R2\n- First we will see their definitions and formulas and then see them in the action.\n- In this study, we will use Boston House  prices dataset.\n\"\"\"\ncolumn_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']\ndf_boston= pd.read_csv('..\/input\/boston-house-prices\/housing.csv',header=None, delimiter=r\"\\s+\", names=column_names)\ndf_boston = df_boston.drop('CHAS', axis=1)\ndf_boston.head()\ndf_boston['MEDV'].describe()\n\"\"\"\n <a id=\"9\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Mean Absolute Error (MAE)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- As shown below, MAE is average absolute differences between  our predicitions and the real value.\n- MAE is easily interpretable\n- Lower the MAE, better the prediction.\n\"\"\"\n\"\"\"\n![](https:\/\/i.imgur.com\/19LNbyQ.jpg)\n\"\"\"\n\"\"\"\nimage credit : https:\/\/stackoverflow.com\/questions\/56401346\/mean-absolute-error-in-tensorflow-without-built-in-functions\/56401550\n\"\"\"\nX = df_boston.drop('MEDV',axis=1)\ny = df_boston['MEDV']\npipeline = make_pipeline(PowerTransformer(method='yeo-johnson'), LinearRegression())\ncv = KFold(n_splits=10, random_state=42)\nresults = cross_val_score(pipeline, X, y, cv=cv, scoring='neg_mean_absolute_error')\nprint(f'MAE: {round(results.mean()*-1,3)}, ({round(results.std(),3)})')\n\"\"\"\n<a id=\"10\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Mean Squared Error (MSE)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- MSE is the squarred average squared differences between predicted value and the real value.\n- Lower the MSE, better the prediction.\n\"\"\"\n\"\"\"\n![](https:\/\/cdn-images-1.medium.com\/max\/959\/1*WDKhO-z7rti70ZTv59yJ9A.jpeg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/cdn-images-1.medium.com\n\"\"\"\nX = df_boston.drop('MEDV',axis=1)\ny = df_boston['MEDV']\npipeline = make_pipeline(PowerTransformer(method='yeo-johnson'), LinearRegression())\ncv = KFold(n_splits=10, random_state=42)\nresults = cross_val_score(pipeline, X, y, cv=cv, scoring='neg_mean_squared_error')\nprint(f'MSE: {round(results.mean()*-1,3)}, ({round(results.std(),3)})')\n\"\"\"\n<a id=\"11\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>Root Mean Squared Error (RMSE)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- RMSE is basically square root of the MSE\n- By taking the square root of the MSE, units are converted  back to the original units of the target variable.\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/programmerah.com\/wp-content\/uploads\/2020\/11\/20190714113817886.png\" width=\"600\">\n\"\"\"\n\"\"\"\nimage credit: https:\/\/programmerah.com\n\"\"\"\nX = df_boston.drop('MEDV',axis=1)\ny = df_boston['MEDV']\npipeline = make_pipeline(PowerTransformer(method='yeo-johnson'), LinearRegression())\ncv = KFold(n_splits=10, random_state=42)\nresults = cross_val_score(pipeline, X, y, cv=cv, scoring='neg_mean_squared_error')\nprint(f'RMSE: {round(np.sqrt(results.mean()*-1),3)}, ({round(results.std(),3)})')\n\"\"\"\n<a id=\"12\"><\/a>\n<font color=\"lightseagreen\" size=+1.5><b>R Squared (R2)<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- Most of the applications in default uses R squared as a metric for the regression problems.\n- R squared gives us the proportion of the target variable is explained by the feature(s).\n- R squared provides an indication of the goodness of fit of a set of predictions to the actual values.\n\"\"\"\n\"\"\"\n![](https:\/\/slidetodoc.com\/presentation_image\/7d85c6a301ba5b97b7d3b73273b073d0\/image-13.jpg)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/slidetodoc.com\/class-5-thurs-sep-23-example-of-using\n\"\"\"\nX = df_boston.drop('MEDV',axis=1)\ny = df_boston['MEDV']\npipeline = make_pipeline(PowerTransformer(method='yeo-johnson'), LinearRegression())\ncv = KFold(n_splits=10, random_state=42)\nresults = cross_val_score(pipeline, X, y, cv=cv, scoring='r2')\nprint(f'R Squared: {round(results.mean(),3)}, ({round(results.std(),3)})')\n\"\"\"\n<a id=\"13\"><\/a>\n<font color=\"darkblue\" size=+1.5><b>Conclusion<\/b><\/font>\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\"\"\"\n\"\"\"\n- We have covered one of the most important concepts of the Machine Learning.\n- We have looked at both classification metrics and regression metrics.\n- We have talked about the misusages of the metrics and the correct ones.\n\n- Evaluation metrics are crucial. Based on the model performance we are giving decisions.\n- We should remember that we are not just only looking for a better model, also looking for our end goal.\n- Before deciding evaluation metrics, it would be a good idea to talk your customer, stakeholders and relevant people to clarify their goals and what they realy want.\n- And please remember that most of the classification problems in the real life have imbalanced data.\n\n\"\"\"\n\"\"\"\n#### **By the way, when you like the topic, you can show it by supporting** \ud83d\udc4d\n\n####  **Feel free to leave a comment in the notebook**. \n\n#### All the best \ud83e\udd18\n\"\"\"\n\"\"\"\n- **Enjoy** \ud83e\udd18\n\"\"\"\n\"\"\"\n![](https:\/\/media.giphy.com\/media\/l2JJsJQY6yj9HLaZW\/giphy.gif)\n\"\"\"\n\"\"\"\nimage credit: https:\/\/giphy.com\n\"\"\"\n\"\"\"\n<a id=\"14\"><\/a>\n<font color=\"darkblue\" size=+1.5><b>References & Further Reading<\/b><\/font>\n\n\n<a href=\"#toc\" class=\"btn btn-primary btn-sm\" role=\"button\" aria-pressed=\"true\" style=\"color:white\" data-toggle=\"popover\">Table of Contents<\/a>\n\n\n[Machine Learning - Beginner &Intermediate-Friendly BOOKS](https:\/\/www.kaggle.com\/general\/255972)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9d4c8b77d81a9b'}"}
{"id":"85264","text":"\"\"\"\n\n# About the Notebook\n\nHi Everyone!!, This notebook  is easily understandable to the beginner. This verbosity tries to explain everything I could possibly know. Once you get through the kernel, you can find this useful and straightforward. I attempted to explain things as simple as possible.\n\nIn this notebook, I extensively use Feature Engineering on Numerical Variable which can be further classified into discrete and continuous variables. \n\nKeep Learning,\n\nSantosh\n\n\"\"\"\n\"\"\"\nNumerical variables\n\nThe values of a numerical variable are numbers. They can be further classified into discrete and continuous variables. Discrete numerical variable\n\nA variable which values are whole numbers (counts) is called discrete. For example, the number of items bought by a customer in a supermarket is discrete. The customer can buy 1, 25, or 50 items, but not 3.7 items. It is always in the form of integer number not to float number. The following are examples of discrete variables:\n\nNumber of active bank accounts of a borrower (1, 4, 7, ...)\nNumber of pets in the family\nNumber of children in the family\nnumber of cars \n\nContinuous numerical variable\n\nA variable that may contain any value within some range is called continuous. For example, the total amount paid by a customer in a supermarket is continuous. The customer can pay, GBP 20.5, GBP 13.10, GBP 83.20 and so on. Other examples of continuous variables are:\n\nHouse price (in principle, it can take any value) (GBP 350000, 57000, 1000000, ...)\nTime spent surfing a website (3.4 seconds, 5.10 seconds, ...)\nTotal debt as percentage of total income in the last month (0.2, 0.001, 0, 0.75, ...)\n\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\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# Any results you write to the current directory are saved as output.\n# let's load the dataset with just a few columns and a few rows\n# to speed up  things\n\nuse_cols = [\n    'loan_amnt', 'int_rate', 'annual_inc', 'open_acc', 'loan_status',\n    'open_il_12m'\n]\n\ndata = pd.read_csv(\n    '..\/input\/lending-club-loan-data\/loan.csv', usecols=use_cols).sample(\n        10000, random_state=44)  # set a seed for reproducibility\n\ndata.head()\n\"\"\"\nContinuous Variables\u00b6\n\"\"\"\n# let's look at the values of the variable loan_amnt\n# this is the amount of money requested by the borrower\n# in US dollars\n\ndata.loan_amnt.unique()\n # let's make an histogram to get familiar with the\n# distribution of the variable\n\nfig = data.loan_amnt.hist(bins=50)\nfig.set_title('Loan Amount Requested')\nfig.set_xlabel('Loan Amount')\nfig.set_ylabel('Number of Loans')\n\"\"\"\n\n\nThe values of the variable vary across the entire range of the variable. This is characteristic of continuous variables.\n\nThe taller bars correspond to loan sizes of 10000, 15000, 20000, and 35000. There are more loans disbursed for those loan amount values. This indicates that most people tend to ask for these loan amounts. Likely, these particular loan amounts are pre-determined and offered as such in the Lending Club website.\n\nLess frequent loan values, like 23,000 or 33,000 could be requested by people who require a specific amount of money for a definite purpose.\n\n\"\"\"\n# let's do the same exercise for the variable interest rate,\n# which is charged by lending club to the borrowers\n\ndata.int_rate.unique()\n# let's make an histogram to get familiar with the\n# distribution of the variable\n\nfig = data.int_rate.hist(bins=30)\nfig.set_title('Interest Rate')\nfig.set_xlabel('Interest Rate')\nfig.set_ylabel('Number of Loans')\n\"\"\"\nHere , we saw that the values of the variable vary continuously across the variable range.\n\"\"\"\n# and now,let's explore the income declared by the customers,\n# that is, how much they earn yearly.\n\nfig = data.annual_inc.hist(bins=100)\nfig.set_xlim(0, 400000)\nfig.set_title(\"Customer's Annual Income\")\nfig.set_xlabel('Annual Income')\nfig.set_ylabel('Number of Customers')\n\"\"\"\nThe majority of salaries are concentrated towards values in the range 30-70 k, with only a few customers earning higher salaries. Again, the values of the variable, vary continuosly across the variable range.\n\n\n**Discrete Variables**\n\nLet's explore the variable \"Number of open credit lines in the borrower's credit file\" (open_acc in the dataset). This is, the total number of credit items (for example, credit cards, car loans, mortgages, etc) that is known for that borrower. By definition it is a discrete variable, because a borrower can have 1 credit card, but not 3.5 credit cards.\n\n\"\"\"\n# let's inspect the values of the variable\n\ndata.open_acc.dropna().unique()\n# let's make an histogram to get familiar with the\n# distribution of the variable\n\nfig = data.open_acc.hist(bins=100)\nfig.set_xlim(0, 30)\nfig.set_title('Number of open accounts')\nfig.set_xlabel('Number of open accounts')\nfig.set_ylabel('Number of Customers')\n\"\"\"\n\n\nHistograms of discrete variables have this typical broken shape, as not all the values within the variable range are present in the variable. As I said, the customer can have 3 credit cards, but not 3,5 credit cards.\n\nLet's look at another example of a discrete variable in this dataset: Number of installment accounts opened in past 12 months (open_il_12m in the dataset). Installment accounts are those that at the moment of acquiring them, there is a set period and amount of repayments agreed between the lender and borrower. An example of this is a car loan, or a student loan. The borrower knows that they are going to pay a certain, fixed amount over for example 36 months.\n\n\"\"\"\n# let's inspect the variable values\n\ndata.open_il_12m.unique()\n# let's make an histogram to get familiar with the\n# distribution of the variable\n\nfig = data.open_il_12m.hist(bins=50)\nfig.set_title('Number of installment accounts opened in past 12 months')\nfig.set_xlabel('Number of installment accounts opened in past 12 months')\nfig.set_ylabel('Number of Borrowers')\n\"\"\"\nThe majority of the borrowers have none or 1 installment account, with only a few borrowers having more than 2.\n\"\"\"\n\"\"\"\n\n**A variation of discrete variables: the binary variable******************\n\nBinary variables, are discrete variables, that can take only 2 values, therefore binary.\n\nIn the next cells I will create an additional variable, called defaulted, to capture the number of loans that have defaulted. A defaulted loan is a loan that a customer has failed to re-pay and the money is lost.\n\nThe variable takes the values 0 where the loans are ok and being re-paid regularly, or 1, when the borrower has confirmed that will not be able to re-pay the borrowed amount.\n\n\"\"\"\n# let's inspect the values of the variable loan status\n\ndata.loan_status.unique()\n# let's create one additional variable called defaulted.\n# This variable indicates if the loan has defaulted, which means,\n# if the borrower failed to re-pay the loan, and the money\n# is deemed lost.\n\ndata['defaulted'] = np.where(data.loan_status.isin(['Default']), 1, 0)\ndata.defaulted.mean()\n# the new variable takes the value of 0\n# if the loan is not defaulted\n\ndata.head(10)\n# the new variable takes the value 1 for loans that\n# are defaulted\n\ndata[data.loan_status.isin(['Default'])].head()\n# A binary variable, can take 2 values. For example,\n# the variable defaulted that we just created:\n# either the loan is defaulted (1) or not (0)\n\ndata.defaulted.unique()\n# let's make a histogram, although histograms for\n# binary variables do not make a lot of sense\n\nfig = data.defaulted.hist()\nfig.set_xlim(0, 2)\nfig.set_title('Defaulted accounts')\nfig.set_xlabel('Defaulted')\nfig.set_ylabel('Number of Loans')\n\"\"\"\n\n\nAs we can see, the variable shows only 2 values, 0 and 1, and the majority of the loans are ok.\n\nThat is all for this demonstration. I hope you enjoyed the notebook, and see you in the next one.\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9c78d9e4ae7166'}"}
{"id":"62829","text":"# 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\n\"\"\"\n# Importing the libraries Needed.\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport re\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score,confusion_matrix\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport gensim\nfrom sklearn.naive_bayes import MultinomialNB\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\"\"\"\n# Reading the files\n\"\"\"\ntrain_df = pd.read_csv('..\/input\/nlp-getting-started\/train.csv')\ntest_df =  pd.read_csv('..\/input\/nlp-getting-started\/test.csv')\nsubmission =pd.read_csv('\/kaggle\/input\/nlp-getting-started\/sample_submission.csv')\ntrain_df.head()\n\"\"\"\n# Info about the Data.\nid -> a unique identifier for each tweet.\n\ntext -> the text of the tweet.\n\nlocation -> the location the tweet was sent from (may be blank).\n\nkeyword -> a particular keyword from the tweet (may be blank).\n\ntarget -> in train.csv only, this denotes whether a tweet is about a real disaster (1) or not (0).\n\"\"\"\ntrain_df.shape, test_df.shape\n\"\"\"\nSince it is a NLP problem we will get rid of Location and keyword Column\n\"\"\"\nlabels = train_df['target']\ntrain_df = train_df.drop(['keyword','location','target'],axis = 1)\ntest_df = test_df.drop(['keyword','location'],axis = 1)\n\n\ntrain_df.shape,test_df.shape\nlabels.head()\nlabels.value_counts().plot(kind = 'bar')\n\"\"\"\nTrain set is not highly imbalanced so we can go on with dataset, Otherwise we would have over\nsampled the data\n\"\"\"\ntrain_df[labels == 0].head()\ntrain_df[labels == 1].head()\ntest_df.head()\n\"\"\"\nDistribution of lengths of tweets in test and train dataset\n\"\"\"\ntrain_length = train_df['text'].str.len()\ntest_length = test_df['text'].str.len()\nplt.figure(figsize = (8,3))\nplt.hist(train_length,bins = 30, label = \"train_texts\")\nplt.hist(test_length,bins = 30, label = \"test_texts\")\nplt.xlim(0,180)\nplt.legend()\nplt.show()\n\"\"\"\nLets combine the train and test dataset and apply cleaning process on texts together.\n\"\"\"\ncombined_data = pd.concat([train_df,test_df],ignore_index = True)\ncombined_data.shape\n\"\"\"\ncleaning text file and appending it to dataframe\n\"\"\"\n#stemmer = PorterStemmer()\nlemmatizer = WordNetLemmatizer()\nclean = []\nfor i in range(0,len(combined_data)):\n    clean_text = re.sub('[^a-zA-Z]',' ',combined_data['text'][i])\n    clean_text = clean_text.lower()\n    clean_text = clean_text.split()\n    \n    clean_text = [lemmatizer.lemmatize(word) for word in clean_text if word not in stopwords.words('english')]\n    #clean_text = [stemmer.stem(word) for word in clean_text if word not in stopwords.words('english')]\n    clean_text = ' '.join(clean_text)\n    clean.append(clean_text)\n\ncombined_data['clean_text']= clean\ncombined_data.head()\n\"\"\"\n# Creating Bag of Words from the Combined dataset\n\"\"\"\n\"\"\"\ncv = CountVectorizer(max_features = 3000)\nbg = cv.fit_transform(combined_data['clean_text']).toarray()\n\"\"\"\n\"\"\"\nbg.shape\n\"\"\"\n\"\"\"\nWe can see that there are 24464 different features made using the bag of words.\nThese 24464 count nothing but the unique words from the combined dataset.\n\"\"\"\n\"\"\"\n# Creating TFidfVectors\n\n\"\"\"\ntfidf = TfidfVectorizer(max_features = 2500)\ntfidfvectors = tfidf.fit_transform(combined_data['clean_text']).toarray()\ntfidfvectors.shape\n\"\"\"\nLets Split the data Into Orginal train and test shape.\n\"\"\"\ntrain = tfidfvectors[:7613]\ntest = tfidfvectors[7613:]\n\"\"\"\nTraining the meodel using train dataset\n\"\"\"\nX_train,X_test,y_train,y_test = train_test_split(train,labels,test_size = 0.2,\n                                                 random_state = 48)\n\"\"\"\nTraining the model using NaiveBayes Classifier\n\"\"\"\nmodel = MultinomialNB().fit(X_train,y_train)\ny_predict = model.predict(X_test)\ny_train_predict = model.predict(X_train)\n\"\"\"\nCreating Confusion matrix and analysing our model performance\n\"\"\"\nconfusion_matrix(y_test,y_predict)\nf1_score(y_test,y_predict)\nf1_score(y_train,y_train_predict)\npredict = model.predict(test)\nsubmission.head()\nsubmission['target'] = predict\nsubmission.head()\nsubmission.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': '73d06162a7db24'}"}
{"id":"95229","text":"\"\"\"\n## Skeleton for training and inference with pytorch-lightning\n\nThis notebook shows how pytorch-lightning can be used to realize the whole processing pipeline from training to inference and submission in some few lines of code.\n\nVarious code snippets are taken from [https:\/\/www.kaggle.com\/jiashenliu\/introduction-to-financial-concepts-and-data] and [https:\/\/www.kaggle.com\/gunesevitan\/optiver-realized-volatility-prediction-1d-cnn]. Many thanks!\n\n\"\"\"\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.callbacks import LearningRateMonitor\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom pathlib import Path\nimport pyarrow.parquet as pq\nfrom sklearn.metrics import r2_score\n\ndata_path=Path('..\/input\/optiver-realized-volatility-prediction')\ndef ffill(data_df): \n    data_df = data_df.set_index(['seconds_in_bucket'])\n    data_df = data_df.reindex(np.arange(0,600), method='ffill')\n    return data_df.reset_index()\n\ndef log_return(list_stock_prices):\n    return np.log(list_stock_prices).diff() \n\ndef realized_volatility(series_log_return):\n    return np.sqrt(np.sum(series_log_return**2))\n\ndef rmspe(y_true, y_pred):\n    return  (np.sqrt(np.mean(np.square((y_true - y_pred) \/ y_true))))\n\nfrom torch.utils.data import Dataset\nimport pyarrow.parquet as pq\n \nclass OptiverDataset(Dataset):\n    \n    def __init__(self, data_path, mode = \"train\", transform = None, ffill = False): \n        \"\"\" mode must be train or test \"\"\"\n        super().__init__()\n        self.mode = mode\n        self.transform = transform\n        self.ffill = ffill\n        train_df = pd.read_csv(data_path\/f\"{mode}.csv\")\n        self.train_grouped = train_df.groupby(['stock_id','time_id'])        \n        book_df = pq.read_table(data_path \/ f\"book_{mode}.parquet\").to_pandas()         \n        self.book_grouped = book_df.groupby(['stock_id','time_id'])        \n        self.indices = list(self.book_grouped.indices.keys())\n    \n    def __getitem__(self, idx):   \n        grp_name = self.indices[idx]\n        df = self.book_grouped.get_group(grp_name)\n        if self.ffill:\n            df = ffill(df)        \n        if self.transform:\n            x = self.transform(df)\n        else:\n            x = df[['bid_price1', 'ask_price1', 'bid_price2', 'ask_price2']].to_numpy(np.float32)\n            \n        if self.mode == \"test\":\n            row_id = self.train_grouped.get_group(grp_name)['row_id'].values[0]\n            return x, row_id\n        else:\n            y = self.train_grouped.get_group(grp_name)['target'].to_numpy(np.float32)\n            return x, y\n    \n    def __len__(self):\n        return len(self.indices)\n    \nfrom torch.utils.data import DataLoader, random_split\n\nclass OptiverDataModule(pl.LightningDataModule):\n    def __init__(self, data_path, train_batch_size = 32, val_batch_size = 32, transform=None):\n        super().__init__()\n        self.data_path = data_path\n        self.train_batch_size = train_batch_size\n        self.val_batch_size = val_batch_size\n        self.transform = transform\n        self.train_dataset = None\n        self.val_dataset = None\n     \n    def create_datasets(self):\n        dataset = OptiverDataset(self.data_path, mode= \"train\", transform = self.transform)\n        dataset_len = len(dataset)\n        train_dataset_len = int(dataset_len*0.8)\n        val_dataset_len = dataset_len - train_dataset_len\n        self.train_dataset, self.val_dataset = random_split(\n            dataset, [train_dataset_len, val_dataset_len], generator=torch.Generator().manual_seed(42))\n        \n    def train_dataloader(self):\n        if not self.train_dataset:\n            self.create_datasets()\n        dataloader = DataLoader(\n            self.train_dataset, \n            batch_size=self.train_batch_size, \n            shuffle=True,\n            num_workers = 4)\n        return dataloader\n    \n    def val_dataloader(self):\n        if not self.val_dataset:\n            self.create_datasets()\n        dataloader = DataLoader(\n            self.val_dataset, \n            batch_size=self.val_batch_size, \n            shuffle=False,\n            num_workers = 4)\n        return dataloader\n    \n    def test_dataloader(self):\n        dataloader = DataLoader(\n            OptiverDataset(self.data_path, mode= \"test\", transform = self.transform),\n            batch_size=1,\n            num_workers = 4)\n        return dataloader\nimport torch.optim\nimport torch.nn\nimport torch.nn.functional as F\n\nclass SimplestLinearModule(pl.LightningModule):\n    def __init__(self, learning_rate = 0.01):\n        super().__init__()    \n        self.learning_rate = learning_rate\n        self.linear = torch.nn.Linear(1, 1)  # One in and one out\n        \n    def forward(self, input):\n        x = self.linear(input)\n        return F.leaky_relu(x)\n    \n    def training_step(self, batch, batch_idx):\n        x, target = batch\n        prediction = self.forward(x)\n        loss = torch.sqrt( F.mse_loss(prediction, target) + 1e-24)\n        self.log(\"loss\", loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)    \n        return loss\n    \n    def validation_step(self, batch, batch_idx):\n        x, target = batch\n        prediction = self.forward(x)\n        loss = torch.sqrt( F.mse_loss(prediction, target) + 1e-24)\n        self.log(\"val_loss\", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True)   \n        return prediction, target\n    \n    def validation_epoch_end(self, validation_step_outputs):\n        y_pred = [p for p,t in validation_step_outputs]\n        y_true = [t for p,t in validation_step_outputs]                \n        y_pred = torch.cat(y_pred, dim=0).view(-1).cpu().numpy()\n        y_true = torch.cat(y_true, dim=0).view(-1).cpu().numpy()\n        R2 = round(r2_score(y_true, y_pred),3)\n        RMSPE = round(rmspe(y_true, y_pred),3)\n        self.log(\"R2\", R2, on_step=False, on_epoch=True, prog_bar=True, logger=True) \n        self.log(\"RMSPE\", RMSPE, on_step=False, on_epoch=True, prog_bar=True, logger=True)   \n\n    def test_step(self, batch, batch_idx):  \n        x, row_id = batch\n        prediction = self.forward(x)\n        return row_id, prediction.cpu().numpy()\n    \n    def test_epoch_end(self, test_step_outputs):\n        ## write submission file:\n        ## row_id target\n        submission = pd.DataFrame({\n            'row_id' : [row_id[0] for row_id, target in test_step_outputs], # row_id is a tuple\n            'target' : [target[0,0] for row_id, target in test_step_outputs]}) # assumes test batch size is 1\n        submission.to_csv('submission.csv', index=None)\n        submission\n\n    def configure_optimizers(self):\n        #optimizer = torch.optim.SGD(self.linear.parameters(), lr = self.learning_rate )\n        #optimizer =torch.optim.Adam(self.parameters(), lr=self.learning_rate)\n        optimizer = torch.optim.RMSprop(self.linear.parameters(), lr = self.learning_rate )\n        scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode = 'min', patience=5)\n        return {\n            \"optimizer\" : optimizer, \n            \"lr_scheduler\" : {\n                \"scheduler\": scheduler,\n                \"monitor\": \"val_loss\",\n            }}\n\ndef realized_volatility_feature(df):\n    wap = (df['bid_price1'] * df['ask_size1'] + df['ask_price1'] * df['bid_size1']) \/\\\n                  (df['bid_size1'] + df['ask_size1'])\n    r = log_return(wap).to_numpy(dtype=np.float32)\n    r = r[~np.isnan(r)]\n    return np.array([realized_volatility(r)], dtype=np.float32)\n    \ndatamodule = OptiverDataModule(\n    data_path=Path('..\/input\/optiver-realized-volatility-prediction'),\n    train_batch_size = 256, val_batch_size = 256,\n    transform = realized_volatility_feature)\n\nmodule = SimplestLinearModule(learning_rate = 1e-4)\n\ncheckpoint_callback = ModelCheckpoint(monitor='val_loss')\nlr_monitor = LearningRateMonitor(logging_interval='step')\n\ntrainer = pl.Trainer(\n    gpus=0,\n    callbacks=[checkpoint_callback, lr_monitor],\n    #limit_train_batches=0.25,\n    #limit_val_batches=0.25,\n    max_epochs = 20\n)\n\n\ntrainer.fit(module, datamodule)\n\"\"\"\n## Performance of the Naive Prediction\nAccording to [https:\/\/www.kaggle.com\/jiashenliu\/introduction-to-financial-concepts-and-data], \nperformance of the naive prediction is:\n\nR2 score: 0.628 \n\nRMSPE: 0.341\n\"\"\"\ntrainer.test(ckpt_path=\"best\")\n\n!cat submission.csv","meta":"{'source': 'AI4Code', 'id': 'aecfcc014245e9'}"}
{"id":"22678","text":"\"\"\"\n# 0.Introduction\n\n**The goal of this notebook is to discuss Shapley values and resulting SHAP**. This algorithm is the answer for the arguably most annoying shortcoming of machine elarning: 'interpretability'. I will discuss how we can use SHAP and provide some theoretical background. As the goal of the notebook is Shapley structure, I will not discuss granularly data preparation nor modeling.\n\n**Content:**\n1. Data preparation\n2. Model: Sequantial Model Assembling + Gradient Boosting\n3. Shapley values\n\nThe main sources of knowledge for this notebook are:\n1. [https:\/\/christophm.github.io\/interpretable-ml-book\/](https:\/\/christophm.github.io\/interpretable-ml-book\/)\n2. [https:\/\/en.wikipedia.org\/wiki\/Shapley_value](https:\/\/en.wikipedia.org\/wiki\/Shapley_value)\n\n**For the readability I hide some lines of code, please uncover it if desired.**\n\"\"\"\n\"\"\"\n# 1.Data preparation\n\nThis is the regular step performed before modeling. I aim on loading the data, checking and cleaning. \n\n**1.1.Libraries**\n\nFirst I choose some libraries which can be useful:\n\"\"\"\nimport numpy as np\nfrom numpy.random import seed\nimport pandas as pd \nimport matplotlib\nimport seaborn as sns\nimport holoviews as hv\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\n\nimport nltk\nfrom nltk.stem import PorterStemmer, WordNetLemmatizer\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords\n\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import Pipeline\nimport xgboost as xgb\n\nfrom keras import Sequential\nfrom keras.layers import Dense\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport os\nimport collections\n\nimport shap\n\nshap.initjs()\n\nRandomState = 123\nseed(RandomState)\ntf.random.set_seed(RandomState)\n\nprint('Libraries correctly loaded')\n\"\"\"\n**1.2.Data cleaning**\n\nSecond, include the data:\n\"\"\"\ndf_path = \"..\/input\/us-airbnb-open-data\/AB_US_2020.csv\"\nusecols=['id','name','latitude','longitude','room_type','price','minimum_nights','number_of_reviews',\n         'last_review','reviews_per_month','calculated_host_listings_count','availability_365','city']\n\ndf = pd.read_csv(df_path,usecols=usecols,index_col='id')\n\nprint('Number of rows: '+ format(df.shape[0]) +', number of features: '+ format(df.shape[1]))\ndf.head(5)\nMissing_Percentage = (df.isnull().sum()).sum()\/np.product(df.shape)*100\nprint(\"The number of missing entries before cleaning: \" + str(round(Missing_Percentage,5)) + \" %\")\ndf.info()\n\"\"\"\nSome corrections:\n\"\"\"\ndf['name'] = df['name'].fillna('')\ndf['last_review'] = df['last_review'].fillna('01\/01\/00')\ndf['reviews_per_month'] = df['reviews_per_month'].fillna(0)\ndf.info()\n\"\"\"\nThe data is cleaned. Let's define states' variable:\n\"\"\"\nstates_dic = {'Asheville':'NC','Austin':'TX','Boston':'MA','Broward County':'FL','Cambridge':'MA','Chicago':'IL','Clark County':'NV','Columbus':'OH','Denver':'CO','Hawaii':'HI','Jersey City':'NJ',\n             'Los Angeles':'SC','Nashville':'TN','New Orleans':'MS','New York City':'NY','Oakland':'CA','Pacific Grove':'CA','Portland':'OR','Rhode Island':'RI','Salem':'MA','San Clara Country':'CA',\n             'Santa Cruz County':'CA','San Diego':'CA','San Francisco':'CA','San Mateo County':'CA','Seattle':'WA','Twin Cities MSA':'MN','Washington D.C.':'DC'}\n\ndf['state'] = df['city'].apply(lambda x : states_dic[x])\n\"\"\"\n# 2.Model: Sequantial Model Assembling + Gradient Boosting\n\nIn this chapter I use the approach from [this notebook](https:\/\/www.kaggle.com\/thomaskonstantin\/u-s-airbnb-analysis-and-price-prediction#notebook-container). Please upvote this guy if you like. There will be some differences with my approach:\n* I cap the extreme values for price applying max for quantile 0.95, but I don't remove another extreme level data as I find it relevant for analysis\n* The data is divded into train and test and results are produced on the basis of test\n\nAforementioned capping:\n\"\"\"\nupper_bound = 0.95\ndf.loc[df['price'] >= df['price'].quantile(upper_bound), ['price']] = df['price'].quantile(upper_bound)\ndf_final = df.drop(columns= ['price'])\nTarget = df.price\n\"\"\"\n**2.1.NLP cleaning**\n\nSome cleaning functions which I defined in my [another NLP notebook](https:\/\/www.kaggle.com\/jjmewtw\/total-bible-text-study-eda-cluster-bert-nlp). They offer complex cleaning offer:\n\"\"\"\nps = PorterStemmer()\n\ndef lower_column_t(data):\n    values = data['name']\n    values = values.lower()\n    data['name'] = values\n    return data\n\ndef clean_interpunction(data):\n    values = data['name']\n    values = values.replace('.','')\n    values = values.replace(';','')\n    values = values.replace(':','')\n    values = values.replace(',','')\n    values = values.replace(\"'\",\"\")\n    values = values.replace('\"','')\n    values = values.replace('\/',' ')\n    values = values.replace('-',' ')\n    values = values.replace('+',' ')\n    values = values.replace('#',' ')\n    values = values.replace('!','')\n    values = values.replace('(',' ')\n    values = values.replace(')',' ')\n    values = values.replace('*',' ')\n    values = values.replace('|',' ')\n    values = values.replace('&',' and ')\n    values = values.replace('@',' at ')\n    data['name'] = values\n    return data\n\ndef stem(a):\n    p = nltk.PorterStemmer()\n    b = []\n    for line in a:\n\n        split_line = line.split(' ')\n        length=len(split_line)\n        new_line = []\n\n        for word in range(length):\n            if word == 0:\n                new_line.append(str(p.stem(split_line[word])))\n            else:\n                new_line[0] = new_line[0] + ' ' + (str(p.stem(split_line[word])))\n\n        b.append(new_line[0])\n\n    return b\n\ndef lem(a):\n    p = nltk.WordNetLemmatizer()\n    b = []\n    for line in a:\n\n        split_line = line.split(' ')\n        length=len(split_line)\n        new_line = []\n\n        for word in range(length):\n            if word == 0:\n                new_line.append(str(p.lemmatize(split_line[word], pos=\"v\")))\n            else:\n                new_line[0] = new_line[0] + ' ' + (str(p.lemmatize(split_line[word], pos=\"v\")))\n\n        b.append(new_line[0])\n\n    return b\n\ndef tokenize(a):  \n    b = []\n    for line in a:\n        b.append(word_tokenize(line))\n                 \n    return b\n\ndef flatten(a):\n    b = []\n    for line in a:\n        b = ' '.join(line)\n    \n    return b\n\ndef count_words(a):\n    b=0\n    for line in a:\n        b = b + sum([i.strip(string.punctuation).isalpha() for i in line.split()])\n        \n    return b\n\ndef generate_ngrams(text, n_gram=1):\n    token = [token for token in text.lower().split(' ') if token != '' if token not in sw]\n    ngrams = zip(*[token[i:] for i in range(n_gram)])\n    return [' '.join(ngram) for ngram in ngrams]\n\"\"\"\nCleaning is applied on the variable 'name'. The results:\n\"\"\"\ndf_final_prep = df_final\n\ndf_final_prep = df_final_prep.apply(lower_column_t, axis=1)\ndf_final_prep = df_final_prep.apply(clean_interpunction, axis=1)\ndf_final_prep['name']=stem(df_final_prep.name)\n\ndf_final_prep\n\"\"\"\n**2.2.Sequantial Model Assembling**\n\nAs mentioned the data is divided into train and test:\n\"\"\"\nx_train,x_test,y_train,y_test = train_test_split(df_final_prep,Target,test_size=0.2,random_state=RandomState)\n\"\"\"\nApplying vocabulary counter on the train set, top ten words:\n\"\"\"\nvocab = collections.Counter(' '.join(x_train['name']).split(' '))\n\nvocab.most_common(10)\n\"\"\"\nAnd the number of words in total vocabulary:\n\"\"\"\nMAX_LENGTH = max(x_train['name'].apply(lambda x: len(x)))\nVOCAB_SIZE = len(vocab.keys())\nVECTOR_SPACE = 100\nVOCAB_SIZE\n\"\"\"\nApplying the sequential model as in the reference notebook, but on the basis of train data set keeping the same size of evaluation set.\n\"\"\"\nencoded_docs = [tf.keras.preprocessing.text.one_hot(d,VOCAB_SIZE) for d in x_train.name]\n\npadded_docs = tf.keras.preprocessing.sequence.pad_sequences(encoded_docs,maxlen=MAX_LENGTH,padding='post')\n\nn = 1000\n\npadded_docs_eval = padded_docs[0:n]\npadded_docs = padded_docs[n:]\nY = y_train[n:]\nY_eval = y_train[:n]\n\nFCNN_MODEL = Sequential([\n    tf.keras.layers.Embedding(VOCAB_SIZE,VECTOR_SPACE,input_length=MAX_LENGTH),\n    tf.keras.layers.Flatten(),\n    Dense(activation='relu',units=5),\n    Dense(activation='relu',units=1)\n])\n\nFCNN_MODEL.compile(optimizer='adam', loss='mse', metrics=['mae'])\n\ntf.keras.utils.plot_model(FCNN_MODEL,show_shapes=True)\n\"\"\"\nApplying the model with 4 epochs and 75 for batch size. This can be further calibrated in your own version of this notebook.\n\"\"\"\nhistory = FCNN_MODEL.fit(padded_docs, Y,validation_data=(padded_docs_eval,Y_eval), epochs=4, batch_size=75)\n\"\"\"\nAnd the predictions for train data set:\n\"\"\"\nencoded_docs = [tf.keras.preprocessing.text.one_hot(d,VOCAB_SIZE) for d in x_train.name]\n\ndosc_prep = tf.keras.preprocessing.sequence.pad_sequences(encoded_docs,maxlen=MAX_LENGTH,padding='post')\n\npredictions = FCNN_MODEL.predict(dosc_prep)\npredictions = predictions.reshape(-1)\npredictions\n\"\"\"\nThis is the enhanced train data set. You can see that dummy transformation was applied for state variable, and room type one. I kept all the nuemric variables. I think the most iinteresting factor here is variable 'Name predicted'. This is the value predicted by Sequential model only on the basis of string variable 'name'. I added it to the data set:\n\"\"\"\ndf_train_2 = x_train\n\nFactorsToDrop = ['name','last_review','city']\n\ndf_train_2 = df_train_2.drop(columns = FactorsToDrop)\ndf_train_2 = pd.get_dummies(df_train_2)\ndf_train_2.insert(0, \"Actual value\", y_train, True)\ndf_train_2.insert(1, \"Name predicted\", predictions, True)\ndf_train_2\n\"\"\"\n**2.3.Gradient Boosting Machine**\n\nThe next idea is to define Gradient Boosting Regressors taking two different approaches: data set will contain 'Name predicted', second one will not. I will look how they perform between each other:\n\"\"\"\nRF_withName = xgb.XGBRegressor(random_state=RandomState)\nRF_withoutName = xgb.XGBRegressor(random_state=RandomState)\n\nRF_withName_fit = RF_withName.fit(df_train_2.drop(columns = 'Actual value'),df_train_2['Actual value'])\nRF_withoutName_fit = RF_withoutName.fit(df_train_2.drop(columns = ['Actual value','Name predicted']),df_train_2['Actual value'])\n\"\"\"\nThe table with resulting predictions on the test data set:\n\"\"\"\nencoded_docs = [tf.keras.preprocessing.text.one_hot(d,VOCAB_SIZE) for d in x_test.name]\n\ndosc_prep = tf.keras.preprocessing.sequence.pad_sequences(encoded_docs,maxlen=MAX_LENGTH,padding='post')\n\npredictions = FCNN_MODEL.predict(dosc_prep)\npredictions = predictions.reshape(-1)\n\nx_test_2 = x_test\n\nFactorsToDrop = ['name','last_review','city']\n\nx_test_2 = x_test_2.drop(columns = FactorsToDrop)\nx_test_2 = pd.get_dummies(x_test_2)\nx_test_2.insert(0, \"Name predicted\", predictions, True)\n\nResults = pd.DataFrame({'Prediction only with Name':predictions,'Prediction RF with Name':RF_withName_fit.predict(x_test_2),'Prediction RF without Name':RF_withoutName_fit.predict(x_test_2.drop(columns = 'Name predicted'))})\nResults.insert(0, \"Actual value\", y_test.values, True)\nResults\n\"\"\"\n**2.4.Root Mean Square Error**\n\nLet's look at RMSE:\n\"\"\"\ndef f_rmse(predictions, targets):\n    return np.sqrt(np.mean((predictions-targets)**2))\n\nModel_Average_RMSE =     f_rmse(Results['Actual value'], y_train.mean())   \nOnlyName_RMSE =      f_rmse(Results['Actual value'].values, Results['Prediction only with Name'].values)    \nRF_withName_RMSE =      f_rmse(Results['Actual value'].values, Results['Prediction RF with Name'].values)    \nRF_withoutName_RMSE =      f_rmse(Results['Actual value'].values, Results['Prediction RF without Name'].values)  \n\nFinal = pd.DataFrame({'RMSE': [Model_Average_RMSE,OnlyName_RMSE,RF_withName_RMSE,RF_withoutName_RMSE],'Name': ['Model_Average','OnlyName','GBM_withName','GBM_withoutName']})\n\nplt.plot(Final['Name'],Final['RMSE'])\nplt.ylabel('RMSE results')\nplt.show()\n\"\"\"\nModel average is the worst, no surprise but good quality check. If it was not a case, it would mean that our predictions are worse than bad. If we use only name factor, we can see already the improvement by approximately 30%, GBM without 'name' gives sligtly better performance than 'name' alone. The best is GBM with name, which leads to more than 40% improvement. This is quite okay, but as I said this model can be much imporved by calibration. Both Sequential and GBM as none of them was calibrated. You can try it by yourself.\n\"\"\"\n\"\"\"\n# 3.Shapley values\n\nI will now focus on the central poit of this notebook - Shapley approach. First, if you wanted to find here some theoretical background, I am providing it just in a sec. In other case just jump to results.\n\n**3.1.Theoretical background**\n\nWhat are Shapley values? The Shapley value is a solution concept in cooperative game theory. To each cooperative game it assigns a unique distribution (among the players) of a total surplus generated by the coalition of all players. The Shapley value is characterized by a collection of desirable properties.\n\nLet's assume that coalitional games is defined:\n* set of players N\n* and function v which maps subsets of players to numbers: $v: 2^N \\rightarrow R$\n* coalition of players S (subset of N)\n\nThe use of function $v(S)$: called the worth of coalition S, describes the total expected sum of payoffs the members of S can obtain by cooperation. The Shapley value is one way to distribute the total gains to the players, assuming that they all collaborate.\n\nThis can be given by this complicated formula:\n\n$\\phi_i(v)=\\frac1{|N|!}\\sum_{S\\subseteq N\\setminus\\{i\\}}|S|!(|N|-|S|-1)!\\left(v(S\\cup\\{i\\})-v(S)\\right)$\n\nwhat can be better understood as:\n\n$\\phi_i(v) = \\frac{1}{number \\: of \\: players} \\sum_{coalitions \\: excluding \\: i} \\frac{marginal \\: contribution \\: of \\: i \\: to \\: coalition}{number \\: of \\: coalitions \\: excluding \\: i}$\n\nLet's break it down:\n\nFor example, we have apartment located in Texas, 50m2 with low number of reviews. Let's assume prediction equals to 100 US dollar. The average prediction for all apartment in the market is 120. We would like to understand how much features contributed such that we have this value.\n\nThis is a place where we can directly apply Shapley approach. The \"game\" is the prediction task for a single instance of the dataset. The \"gain\" is the actual prediction for this instance minus the average prediction for all instances. The \"players\" are the feature values of the instance that collaborate to receive the gain (= predict a certain value).\n\nAlgorithm will then gradually exclude given combinations, for example marking the driver of biggest differences the fact that flat is in Texas istead of New York. It can also say that the flat's size or low number of reviews is responsible. \n\nHow to calculate it in practice?\n\nThe Shapley value is the average marginal contribution of a feature value across all possible coalitions. [More granular description](https:\/\/christophm.github.io\/interpretable-ml-book\/shapley.html).\n\nWhat is SHAP?\n\nThe goal of SHAP is to explain the prediction of an instance x by computing the contribution of each feature to the prediction. The SHAP explanation method computes Shapley values from coalitional game theory. The feature values of a data instance act as players in a coalition. Shapley values tell us how to fairly distribute the \"payout\" (= the prediction) among the features. A player can be an individual feature value, e.g. for tabular data. \n\"\"\"\n\"\"\"\n**3.2.Results**\n\nI will look at some flats from our AiRbnb data set and analyze what is the opition of algorithm about them. To remind if you omitted chapter 1 and 2: we have two algorithms:\n* Sequantial Model Assembling only on 'name' + Gradient Boosting Machine on all data\n* Gradient Boosting Machine on all data\n\nFunctions from shap package are quite heavy computiation-wise. I choose just 5000 flats from the test set with given predictions:\n\"\"\"\nshp_df = x_test_2.sample(n=5000, replace=False, weights=None, random_state=RandomState)\nshp_df_2 = shp_df.drop(columns = ['Name predicted'])\n\"\"\"\nHere, I define:\n* tree explainer (TreeSHAP): Lundberg proposed TreeSHAP in 2018, as a variant of SHAP for tree-based machine learning models such as decision trees, random forests and gradient boosted trees. TreeSHAP was introduced as a fast, model-specific alternative to KernelSHAP, but it turned out that it can produce unintuitive feature attributions.\n* Shap values given on the basis of this explainer\n\"\"\"\nexplainer_withName = shap.TreeExplainer(RF_withName_fit, feature_dependence=\"feature_perturbation\")\nshap_values_withName = explainer_withName.shap_values(shp_df)\n\nexplainer_withoutName = shap.TreeExplainer(RF_withoutName_fit, feature_dependence=\"feature_perturbation\")\nshap_values_withoutName = explainer_withoutName.shap_values(shp_df_2)\n\"\"\"\nLet's look at some statistics from the test data set. It will be interesting to observe how chosen by me records perform aginst the general values.\n\"\"\"\nx_test_2[['Name predicted','latitude','longitude', 'minimum_nights','number_of_reviews','reviews_per_month','calculated_host_listings_count','availability_365']].describe()\n\"\"\"\nI choose the flat 505 from randomly drawn sample from the test set.\n\"\"\"\ni = 505\n\nid_505 = ((shp_df.iloc[i:(i+1)].reset_index()).id).values[0]\n\nprint(\"The index of this first guy: \" + format(id_505))\n\"\"\"\nWe have the flat '20 minutes' from Manhattan. The room is in New Jersey. It is just a room, havig ittle number of reviews (avg is 34). But the flat is trending as it receives around 2.5 reviews monthly vs quantile 75% at level 1.62. The price is very low: 60 US dollar.\n\"\"\"\ndf.loc[id_505]\n\"\"\"\nSecond flat is located in Austin, Texas.\n\"\"\"\nj = 515\n\nid_515 = ((shp_df.iloc[j:(j+1)].reset_index()).id).values[0]\n\nprint(\"The index of the second guy: \" + format(id_515))\n\"\"\"\nAs mentioned in the title, it is 'new listing', called also 'peaceful retreat'. This is entire home\/apartment. Not many reviews on the account, also not many new reviews. The price is high: 378 $.\n\"\"\"\ndf.loc[id_515]\n\"\"\"\nResults for New Jersey guy using GBM with Name:\n\"\"\"\nshap.force_plot(explainer_withName.expected_value, shap_values_withName[i], features=shp_df.iloc[i], feature_names=shp_df.columns)\n\"\"\"\nResults for New Jersey guy using GBM wihout Name:\n\"\"\"\nshap.force_plot(explainer_withoutName.expected_value, shap_values_withoutName[i], features=shp_df_2.iloc[i], feature_names=shp_df_2.columns)\n\"\"\"\nThe price estimation difference is only 5$. In the first algorithm 'name' factor plays great role loweirng the price by more than 50 dollar! It is interesting that title with 'Manhattan' led to lower price. Probably word 'room' lowers a lot. Indeed room type plays a big role in both estimations, but in first case it lowers, in second it increases the price. It seems to confirm my assumption then. In contrary, reviews per month lower the price for both of them. \n\nTime for Texas guy:\n\nFirst algorithm with name on the board. Multiple increasing factors. 'Name' leads to approx. 320 dollar increase, vast number:\n\"\"\"\nshap.force_plot(explainer_withName.expected_value, shap_values_withName[j], features=shp_df.iloc[j], feature_names=shp_df.columns)\n\"\"\"\nValue is significantly lower (110$ lower). Probably because of information from the name variable:\n\"\"\"\nshap.force_plot(explainer_withoutName.expected_value, shap_values_withoutName[j], features=shp_df_2.iloc[j], feature_names=shp_df_2.columns)\n\"\"\"\nLet's look at 10 different values for algorithm with name:\n\"\"\"\ni = 505\nj = 510\n\nshap.force_plot(explainer_withName.expected_value, shap_values_withName[i:j], features=shp_df.iloc[i:j], feature_names=shp_df.columns)\n\"\"\"\nAnd same 10 records for algorithm without name:\n\"\"\"\ni = 505\nj = 510\n\nshap.force_plot(explainer_withoutName.expected_value, shap_values_withoutName[i:j], features=shp_df_2.iloc[i:j], feature_names=shp_df_2.columns)\n\"\"\"\nAnother interesting graph is the SHAP value plot for all biggest factors. Far the most relevant is our 'name' factor: \n\"\"\"\nshap.summary_plot(shap_values_withName, features=shp_df, feature_names=shp_df.columns)\n\"\"\"\nThe SHAP value for two factors at once:\n\"\"\"\nshap.dependence_plot('Name predicted', shap_values_withName, shp_df)\nshap.dependence_plot('number_of_reviews', shap_values_withName, shp_df)\n\"\"\"\nIf you think that this notebook helpd a bit in SHAPing your knowledge, please upvote it.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '29b026bfc4e861'}"}
{"id":"105193","text":"# 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 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\ndf=pd.read_csv('\/kaggle\/input\/insurance\/insurance.csv')\ndf.head()\ndf.info()\ndf['region'].unique()\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n#visualising the dependency of region on insurance\nsns.barplot(x='region',y='charges',data=df)\nsns.boxplot(x='charges',data=df)\nsns.boxplot(x='charges',y='region',data=df)\ndf.hist()\n#correlation between the columns\nplt.rcParams['figure.figsize']=(12,8)\ncorr=df.corr()\nsns.heatmap(corr,fmt='0.2f',annot=True,cmap=plt.cm.Blues)\n#converting the object dtypes to int64\ndf['sex']=df['sex'].map({'male':0,'female':1})\ndf['smoker']=df['smoker'].map({'yes':1,'no':0})\ndf['region']=df['region'].map({'southwest':1,'southeast':2,'northwest':3,'northeast':4})\n#columns and labels from the dataset\nX=df.iloc[:,:-1]\ny=df.iloc[:,-1]\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=123)\n\"\"\"\n# Linear Regression\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error,mean_squared_error\nlr=LinearRegression()\nlr.fit(X_train,y_train)\n\npreds=lr.predict(X_test)\nprint('mean absolute error:',mean_absolute_error(preds,y_test))\nresults=pd.DataFrame({'y_test':y_test.values,'predictions':preds})\nresults.head()\nlr.score(X_train,y_train)\n#Scaling the data\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\nX_train_scaled=scaler.fit_transform(X_train)\nX_test_scaled=scaler.fit(X_test)\n\"\"\"\n# Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\ndt=DecisionTreeRegressor()\ndt.fit(X_train,y_train)\ndt.score(X_train,y_train)\ndt_preds=dt.predict(X_test)\nprint('mean squared error',mean_squared_error(dt_preds,y_test))\nprint('mean absolute error',mean_absolute_error(dt_preds,y_test))\nfrom sklearn.model_selection import GridSearchCV\nparams={'max_depth':np.arange(2,10),'min_samples_leaf':np.arange(2,8)}\ndt_best=GridSearchCV(estimator=dt,param_grid=params,verbose=1,cv=5)\ndt_best.fit(X_train,y_train)\ndt_best.best_params_,dt_best.best_score_\npreds_best=dt_best.predict(X_test)\nprint('mean squared error',mean_squared_error(preds_best,y_test))\nprint('mean absolute error',mean_absolute_error(preds_best,y_test))","meta":"{'source': 'AI4Code', 'id': 'c13b9cd2c1b986'}"}
{"id":"88931","text":"# 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\nimport numpy as np \nimport pandas as pd \nimport re\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib_venn import venn2\nimport category_encoders as ce\n%matplotlib inline\n\n#from xfeat import (SelectCategorical, LabelEncoder, Pipeline, ConcatCombination, SelectNumerical, \n#                   ArithmeticCombinations, TargetEncoder, aggregation, GBDTFeatureSelector, GBDTFeatureExplorer)\n\nfrom catboost import CatBoost\nfrom catboost import CatBoostClassifier\nfrom catboost import Pool\nfrom catboost import cv\nfrom sklearn.metrics import mean_squared_log_error\nimport lightgbm as lgb\nimport xgboost as xgb\nfrom tqdm import tqdm\n\nimport os\nfrom glob import glob\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.decomposition import PCA\nfrom scipy import stats\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import metrics\n\nimport shap\n\nfrom optuna.integration import _lightgbm_tuner as lgb_tuner\nimport optuna\nfrom collections import Counter\npd.set_option('display.max_columns', 100)\n\nimport warnings\nwarnings.filterwarnings('ignore')\ntrain_df = pd.read_csv(\"..\/input\/tabular-playground-series-feb-2021\/train.csv\")\ntest_df = pd.read_csv(\"..\/input\/tabular-playground-series-feb-2021\/test.csv\")\nsubmission = pd.read_csv(\"..\/input\/tabular-playground-series-feb-2021\/sample_submission.csv\")\ntrain_df.head()\ntest_df.head()\nfig = plt.figure(figsize = (16,8))\nfor i in range(0,10):\n    ax = fig.add_subplot(2,5,i+1)\n    sns.countplot(train_df[\"cat\"+str(i)])\n    plt.title(\"train\")\n    plt.tight_layout()\nfig = plt.figure(figsize = (16,8))\nfor i in range(0,10):\n    ax = fig.add_subplot(2,5,i+1)\n    sns.countplot(test_df[\"cat\"+str(i)])\n    plt.title(\"test\")\n    plt.tight_layout()\nfig = plt.figure(figsize = (16,16))\nfor i in range(0,14):\n    ax = fig.add_subplot(4,4,i+1)\n    sns.distplot(train_df[\"cont\"+str(i)], label='train')\n    sns.distplot(test_df[\"cont\"+str(i)], label='test')\n    plt.legend()\n    plt.title(\"cont\"+str(i))\n    plt.tight_layout()\n\"\"\"\n# preprocess\n\"\"\"\n# https:\/\/www.guruguru.science\/competitions\/13\/discussions\/41b4ac2d-690b-4ba5-8ff7-be3639578bc1\/\n\n# BaseBlock \nclass BaseBlock(object):\n    def fit(self, input_df, y=None):\n        return self.transform(input_df)\n    \n    def transform(self, input_df):\n        raise NotImplementedError()\n\n# OneHotEncoding\nclass OneHotEncodingBlock(BaseBlock):\n    def __init__(self, cols):\n        self.cols = cols\n        self.encoder = None\n        \n    def fit(self, input_df, y=None):\n        self.encoder = ce.OneHotEncoder(use_cat_names=True)\n        self.encoder.fit(input_df[self.cols])\n        return self.transform(input_df[self.cols])\n    \n    def transform(self, input_df):\n        return self.encoder.transform(input_df[self.cols]).add_prefix(\"OHE_\")\n    \n# CountEncoding\nclass CountEncodingBlock(BaseBlock):\n    def __init__(self, cols):\n        self.cols = cols\n        self.encoder = None\n    \n    def fit(self, input_df, y=None):\n        return self.transform(input_df[self.cols])\n\n    def transform(self, input_df):\n        self.encoder = ce.CountEncoder()\n        self.encoder.fit(input_df[self.cols])\n        return self.encoder.transform(input_df[self.cols]).add_prefix(\"CE_\")\n    \n# OrdinalEncoding\nclass OrdinalEncodingBlock(BaseBlock):\n    def __init__(self, cols):\n        self.cols = cols\n        self.encoder = None\n        \n    def fit(self, input_df, y=None):\n        self.encoder = ce.OrdinalEncoder()\n        self.encoder.fit(input_df[self.cols])\n        return self.transform(input_df[self.cols])\n    \n    def transform(self, input_df):\n        return self.encoder.transform(input_df[self.cols]).add_prefix(\"OE_\")\ndef get_ce_features(input_df):\n    _input_df = pd.concat([input_df], axis=1)\n\n    cols = [\n        \"cat0\",\n        \"cat1\",\n        \"cat2\",\n        \"cat3\",\n        \"cat4\",\n        \"cat5\",\n        \"cat6\",\n        \"cat7\",\n        \"cat8\",\n        \"cat9\",\n    ]\n    encoder = CountEncodingBlock(cols=cols)\n    output_df = encoder.fit(_input_df.astype(str))\n    return output_df\n\ndef get_oe_features(input_df):\n    _input_df = pd.concat([input_df])\n    cols = [\n        \"cat0\",\n        \"cat1\",\n        \"cat2\",\n        \"cat3\",\n        \"cat4\",\n        \"cat5\",\n        \"cat6\",\n        \"cat7\",\n        \"cat8\",\n        \"cat9\",\n    ]\n    encoder = OrdinalEncodingBlock(cols=cols)\n    output_df = encoder.fit(input_df)\n    return output_df\n\n\ndef get_ohe_features(input_df):\n    cols = [\n        \"cat0\",\n        \"cat1\",\n        \"cat2\",\n        \"cat3\",\n        \"cat4\",\n        \"cat5\",\n        \"cat6\",\n        \"cat7\",\n        \"cat8\",\n        \"cat9\",\n    ]\n    encoder = OneHotEncodingBlock(cols=cols)\n    output_df = encoder.fit(input_df)\n    return output_df\ndef create_continuous_features(input_df):\n    use_columns = [\"cont0\",\"cont1\",\"cont2\",\"cont3\",\"cont4\",\n                   \"cont5\",\"cont6\",\"cont7\",\"cont8\",\"cont9\",\n                   \"cont10\",\"cont11\",\"cont12\",\"cont13\"\n                  ]\n    output_df = input_df[use_columns]\n    return output_df\n# propress\ndef to_features(train, test):\n    input_df = pd.concat([train, test]).reset_index(drop=True)\n\n    processes = [\n        get_oe_features,\n        get_ce_features,\n        get_ohe_features,\n        create_continuous_features\n    ]\n\n    output_df = pd.DataFrame()\n    for func in tqdm(processes):\n        _df = func(input_df)\n        assert len(_df) == len(input_df), func.__name__\n        output_df = pd.concat([output_df, _df], axis=1)\n\n    train_x = output_df.iloc[:len(train)] \n    test_x = output_df.iloc[len(train):].reset_index(drop=True)\n    return train_x, test_x\ntarget_data = \"target\" \n\ntrain_x, test_x = to_features(train_df, test_df)\ntrain_ys = train_df[target_data]\ntrain_x.info()\ntrain_ys\nfrom contextlib import contextmanager\nfrom time import time\n\n@contextmanager\ndef timer(logger=None, format_str='{:.3f}[s]', prefix=None, suffix=None):\n    if prefix: format_str = str(prefix) + format_str\n    if suffix: format_str = format_str + str(suffix)\n    start = time()\n    yield\n    d = time() - start\n    out_str = format_str.format(d)\n    if logger:\n        logger.info(out_str)\n    else:\n        print(out_str)\ndef fit_lgbm(X, y, cv, params: dict=None, verbose: int=50):\n    metric_func = mean_squared_error\n\n    if params is None:\n        params = {}\n\n    models = []\n\n    oof_pred = np.zeros_like(y, dtype=np.float)\n\n    for i, (idx_train, idx_valid) in enumerate(cv): \n\n        x_train, y_train = X[idx_train], y[idx_train]\n        x_valid, y_valid = X[idx_valid], y[idx_valid]\n\n        clf = lgb.LGBMRegressor(**params)\n\n        with timer(prefix='fit fold={} '.format(i + 1)):\n            clf.fit(x_train, y_train, \n                    eval_set=[(x_valid, y_valid)],  \n                    early_stopping_rounds=verbose,\n                    verbose=verbose)\n\n        pred_i = clf.predict(x_valid)\n\n        oof_pred[idx_valid] = pred_i\n        models.append(clf)\n\n        print(f'Fold {i} RMSE: {metric_func(y_valid, pred_i) ** .5:.4f}')\n        \n    score = metric_func(y, oof_pred) ** .5\n    print('FINISHED | Whole RMSE: {:.4f}'.format(score))\n    return oof_pred, models\ndef fit_xgb(X, y, cv, params: dict=None, verbose: int=50):\n    metric_func = mean_squared_error\n    if params is None:\n        params = {}\n\n    models = []\n    oof_pred = np.zeros_like(y, dtype=np.float)\n\n    for i, (idx_train, idx_valid) in enumerate(cv): \n        x_train, y_train = X[idx_train], y[idx_train]\n        x_valid, y_valid = X[idx_valid], y[idx_valid]\n        \n        model_xgb = xgb.XGBRegressor(**params)\n\n        with timer(prefix='fit fold={} '.format(i + 1)):\n            model_xgb.fit(x_train, y_train, eval_set=[(x_valid, y_valid)])\n            \n        #print(model_xgb.best_score())\n        \n        pred_i = model_xgb.predict(x_valid)\n\n        oof_pred[idx_valid] = pred_i\n        models.append(model_xgb)\n\n        print(f'Fold {i} RMSE: {metric_func(y_valid, pred_i) ** .5:.4f}')\n\n    score = metric_func(y, oof_pred) ** .5\n    print('FINISHED | Whole RMSE: {:.4f}'.format(score))\n    return oof_pred, models\ndef fit_cb(X, y, cv, params: dict=None, verbose: int=50):\n    metric_func = mean_squared_error\n    if params is None:\n        params = {}\n\n    models = []\n    oof_pred = np.zeros_like(y, dtype=np.float)\n\n    for i, (idx_train, idx_valid) in enumerate(cv): \n        x_train, y_train = X[idx_train], y[idx_train]\n        x_valid, y_valid = X[idx_valid], y[idx_valid]\n        \n        train_pool = Pool(x_train, label = y_train)\n        valid_pool = Pool(x_valid, label = y_valid)\n        \n        model_cb = CatBoost(params)\n\n        with timer(prefix='fit fold={} '.format(i + 1)):\n            model_cb.fit(train_pool,\n              # valid_data\n              eval_set = valid_pool,\n              use_best_model = True,\n              silent = True,\n              plot = False)\n            \n        print(model_cb.get_best_score())\n        \n        pred_i = model_cb.predict(x_valid)\n\n        oof_pred[idx_valid] = pred_i\n        models.append(model_cb)\n\n        print(f'Fold {i} RMSE: {metric_func(y_valid, pred_i) ** .5:.4f}')\n\n    score = metric_func(y, oof_pred) ** .5\n    print('FINISHED | Whole RMSE: {:.4f}'.format(score))\n    return oof_pred, models\n\"\"\"\n# Stratified_folds_for_regression\n\nthanks for good information!\nhttps:\/\/www.kaggle.com\/c\/tabular-playground-series-feb-2021\/discussion\/216576\n\"\"\"\ndef create_stratified_folds_for_regression(data_df, n_splits=5):\n    \"\"\"\n    @param data_df: training data to split in Stratified K Folds for a continous target value\n    @param n_splits: number of splits\n    @return: the training data with a column with kfold id\n    \"\"\"\n    data_df['kfold'] = -1\n    # randomize the data\n    data_df = data_df.sample(frac=1).reset_index(drop=True)\n    # calculate the optimal number of bins based on log2(data_df.shape[0])\n    num_bins = np.int(np.floor(1 + np.log2(len(data_df))))\n    print(f\"Num bins: {num_bins}\")\n    # bins value will be the equivalent of class value of target feature used by StratifiedKFold to \n    # distribute evenly the classed over each fold\n    data_df.loc[:, \"bins\"] = pd.cut(pd.to_numeric(data_df['target'], downcast=\"signed\"), bins=num_bins, labels=False)\n    kf = StratifiedKFold(n_splits=n_splits)\n    \n    # set the fold id as a new column in the train data\n    for f, (t_, v_) in enumerate(kf.split(X=data_df, y=data_df.bins.values)):\n        data_df.loc[v_, 'kfold'] = f\n    \n    # drop the bins column (no longer needed)\n    data_df = data_df.drop(\"bins\", axis=1)\n    \n    return data_df\ndef kfold_splits(n_splits, train_df):\n    \"\"\"\n    Returns a collection of (fold, train indexes, validation indexes)\n    @param n_splits: number of splits\n    @param train_df: training data\n    @return: a collection of (fold, train indexes, validation indexes)\n    \"\"\"\n    \n    # not append \"fold\" => my function\n    all_folds = list(range(0, n_splits))\n    kf_splits = []\n    for fold in range(0, n_splits):\n        train_folds = [x for x in all_folds if x != fold]\n        trn_idx = train_df[train_df.kfold!=fold].index\n        val_idx = train_df[train_df.kfold==fold].index\n        kf_splits.append((trn_idx, val_idx))\n    return kf_splits\ntrain_df_re = pd.concat([train_x, train_ys], axis=1)\nn_splits = 9\ntrain_df_re = create_stratified_folds_for_regression(train_df_re, n_splits)\nstratified_cv = kfold_splits(n_splits, train_df_re)\n\"\"\"\n# optuna\n\"\"\"\ndef fit_lgbm_param_optuna(X, \n             y, \n             cv, \n             params: dict=None, \n             verbose: int=50):\n    metric_func = mean_squared_error\n\n    if params is None:\n        params = {}\n\n    models = []\n\n    oof_pred = np.zeros_like(y, dtype=np.float)\n\n    for i, (idx_train, idx_valid) in enumerate(cv): \n\n        x_train, y_train = X[idx_train], y[idx_train]\n        x_valid, y_valid = X[idx_valid], y[idx_valid]\n\n        clf = lgb.LGBMRegressor(**params)\n\n        with timer(prefix='fit fold={} '.format(i + 1)):\n            clf.fit(x_train, y_train, \n                    eval_set=[(x_valid, y_valid)],  \n                    early_stopping_rounds=verbose,\n                    verbose=verbose)\n\n        pred_i = clf.predict(x_valid)\n\n        oof_pred[idx_valid] = pred_i\n        models.append(clf)\n\n    score = metric_func(y, oof_pred) ** .5\n    return score\n\ndef objective(trial):\n    \n    #fold = KFold(n_splits=5, shuffle=True, random_state=71)\n    #cv = list(fold.split(train_x, train_ys))\n    optuna_paramas_lgb = {\n        'num_leaves': trial.suggest_int('num_leaves', 32, 512),\n        'boosting_type': 'gbdt',\n        'max_bin': trial.suggest_int('max_bin', 700, 900),\n        'objective': 'huber',\n        'metric': 'mae',\n        'learning_rate': trial.suggest_float('learning_rate',0.0155,0.05),\n        'random_state' : 71,\n        'max_depth': trial.suggest_int('max_depth', 4, 16),\n        'min_child_weight': trial.suggest_int('min_child_weight', 1, 16),\n        'feature_fraction': trial.suggest_uniform('feature_fraction', 0.4, 1.0),\n        'bagging_fraction': trial.suggest_uniform('bagging_fraction', 0.4, 1.0),\n        'bagging_freq': trial.suggest_int('bagging_freq', 1, 8),\n        'min_child_samples': trial.suggest_int('min_child_samples', 4, 80),\n        'lambda_l1': trial.suggest_loguniform('lambda_l1', 1e-8, 1.0),\n        'lambda_l2': trial.suggest_loguniform('lambda_l2', 1e-8, 1.0),\n        'early_stopping_rounds': 10\n            \n}\n    score = fit_lgbm_param_optuna(train_x.values,  train_ys, stratified_cv, params=optuna_paramas_lgb)\n    \n    return score\n\n#study = optuna.create_study(direction=\"minimize\", study_name='lgbm_train')\n#study.optimize(objective, n_trials=50)\n#study.best_params\n\n\"\"\"\nlgb\n{'num_leaves': 385,\n 'max_bin': 887,\n 'learning_rate': 0.049867328104748844,\n 'max_depth': 14,\n 'min_child_weight': 10,\n 'feature_fraction': 0.4511004151880547,\n 'bagging_fraction': 0.6559039807249963,\n 'bagging_freq': 2,\n 'min_child_samples': 77,\n 'lambda_l1': 4.638151021025029e-08,\n 'lambda_l2': 0.2937304195136803}\"\"\"\ndef fit_xgb_optuna(X, y, cv, params: dict=None, verbose: int=50):\n    metric_func = mean_squared_error\n    if params is None:\n        params = {}\n\n    models = []\n    oof_pred = np.zeros_like(y, dtype=np.float)\n\n    for i, (idx_train, idx_valid) in enumerate(cv): \n        x_train, y_train = X[idx_train], y[idx_train]\n        x_valid, y_valid = X[idx_valid], y[idx_valid]\n        \n        model_xgb = xgb.XGBRegressor(**params)\n\n        with timer(prefix='fit fold={} '.format(i + 1)):\n            model_xgb.fit(x_train, y_train, eval_set=[(x_valid, y_valid)])\n            \n        #print(model_xgb.best_score())\n        \n        pred_i = model_xgb.predict(x_valid)\n\n        oof_pred[idx_valid] = pred_i\n        models.append(model_xgb)\n\n    score = metric_func(y, oof_pred) ** .5\n\n    return score\n\ndef objective_xgb(trial):\n    \n    fold = KFold(n_splits=5, shuffle=True, random_state=71)\n    cv = list(fold.split(train_x, train_ys))\n    optuna_paramas_xgb = {\n        'booster': 'gbtree',\n        'max_bin': trial.suggest_int('max_bin', 700, 900),\n        'objective': 'reg:squarederror',\n        'eval_metric': 'mae',\n        'learning_rate': trial.suggest_float('learning_rate',0.0155,0.05),\n        'random_state' : 71,\n        'max_depth': trial.suggest_int('max_depth', 4, 16),\n        'min_child_weight': trial.suggest_int('min_child_weight', 1, 16),\n        'subsample': trial.suggest_uniform('subsample', 0.4, 1.0),\n        'lambda': trial.suggest_loguniform('lambda', 1e-8, 1.0),\n        'alpha': trial.suggest_loguniform('alpha', 1e-8, 1.0),\n        'early_stopping_rounds': 10\n    }\n    \n    score = fit_xgb_optuna(train_x.values,  train_ys, stratified_cv, params=optuna_paramas_xgb)\n    \n    return score\n\n#study = optuna.create_study(direction=\"minimize\", study_name='xgb_train')\n#study.optimize(objective_xgb, n_trials=10)\n#study.best_params\n\"\"\"\n{'max_bin': 830,\n 'learning_rate': 0.048518442248912635,\n 'max_depth': 15,\n 'min_child_weight': 7,\n 'subsample': 0.9080463485454009,\n 'lambda': 5.370896698434827e-07,\n 'alpha': 0.005799175899438967}\"\"\"\nparams_best = {\n    'num_leaves': 385,\n    'max_bin': 887,\n    'learning_rate': 0.049867328104748844,\n    'max_depth': 14,\n    'min_child_weight': 10,\n    'feature_fraction': 0.4511004151880547,\n    'bagging_fraction': 0.6559039807249963,\n    'bagging_freq': 2,\n    'min_child_samples': 77,\n    'lambda_l1': 4.638151021025029e-08,\n    'lambda_l2': 0.2937304195136803,\n    \"random_state\": 71,\n    \"num_boost_round\": 50000,\n    \"early_stopping_rounds\": 100,\n    'objective': 'regression',\n    'metric': 'rmse',\n    \"boosting\": \"gbdt\",\n}\n\n#fold = KFold(n_splits=5, shuffle=True, random_state=71)\n#cv = list(fold.split(train_x, train_ys))\n\noof, models = fit_lgbm(train_x.values, train_ys, stratified_cv, params=params_best)\nimport xgboost as xgb\nparams_xgb = {\n        'max_bin': 830,\n 'learning_rate': 0.048518442248912635,\n 'max_depth': 15,\n 'min_child_weight': 7,\n 'subsample': 0.9080463485454009,\n 'lambda': 5.370896698434827e-07,\n 'alpha': 0.005799175899438967\n}\n\nfold = KFold(n_splits=5, shuffle=True, random_state=71)\ncv = list(fold.split(train_x, train_ys))\n\noof_xgb, models_xgb = fit_xgb(train_x.values, train_ys, stratified_cv, params=params_xgb)\nparams_cb = {\n    'loss_function': 'RMSE',\n    'max_depth': 3, \n    'learning_rate': 0.08, \n    'subsample': 0.8, \n    #'colsample_bytree': 0.7,\n    'num_boost_round': 1000,\n    'early_stopping_rounds': 100,\n}\n\noof_cb, models_cb = fit_cb(train_x.values, train_ys, stratified_cv, params=params_cb)\ndef visualize_importance(models, feat_train_df):\n\n    feature_importance_df = pd.DataFrame()\n    for i, model in enumerate(models):\n        _df = pd.DataFrame()\n        _df['feature_importance'] = model.feature_importances_\n        _df['column'] = feat_train_df.columns\n        _df['fold'] = i + 1\n        feature_importance_df = pd.concat([feature_importance_df, _df], axis=0, ignore_index=True)\n\n    order = feature_importance_df.groupby('column')\\\n        .sum()[['feature_importance']]\\\n        .sort_values('feature_importance', ascending=False).index[:50]\n\n    fig, ax = plt.subplots(figsize=(max(6, len(order) * .4), 7))\n    sns.boxenplot(data=feature_importance_df, x='column', y='feature_importance', order=order, ax=ax, palette='viridis')\n    ax.tick_params(axis='x', rotation=90)\n    ax.grid()\n    fig.tight_layout()\n    return fig, ax\nfig, ax = visualize_importance(models, train_x)\npred_lgb = np.array([model.predict(test_x.values) for model in models])\npred_lgb = np.mean(pred_lgb, axis=0)\npred_lgb = np.where(pred_lgb < 0, 0, pred_lgb)\npred_xgb = np.array([model.predict(test_x.values) for model in models_xgb])\npred_xgb = np.mean(pred_xgb, axis=0)\npred_xgb = np.where(pred_xgb < 0, 0, pred_xgb)\npred_cb = np.array([model.predict(test_x.values) for model in models_cb])\npred_cb = np.mean(pred_cb, axis=0)\npred_cb = np.where(pred_cb < 0, 0, pred_cb)\n#oof_em = (oof+oof_xgb+oof_cb)\/3\noof_em = oof*0.3+oof_xgb*0.1+oof_cb*0.6\n\nmetric_func = mean_squared_error\n\nscore = metric_func(train_ys, oof_em) ** .5\n\nprint(score)\n#0.8439838083404265\n#pred = (pred_lgb + pred_xgb + pred_cb)\/3\npred_em = pred_lgb*0.3 + pred_xgb*0.1 +pred_cb*0.6\nsubmission[\"target\"] = pred_em\nsubmission.to_csv('.\/submission.csv', index=False)\nfig, ax = plt.subplots(figsize=(8, 8))\nsns.distplot(oof, label='Test Predict')\nsns.distplot(submission[\"target\"], label='Out Of Fold')\nax.legend()\nax.grid()","meta":"{'source': 'AI4Code', 'id': 'a3164b96d21381'}"}
{"id":"26461","text":"\"\"\"\n# Introduction\n\n* SongSim is method found by **Collin Morris** for visualizing the songs' repetitive parts and intends to find patterns in them. \n* Github link for SongSim: https:\/\/github.com\/colinmorris\/SongSim\n* If you do not know JavaScript and CSS you check out my Python version for it:\n* Github link for Python version: https:\/\/github.com\/bayhippo\/SongSim-in-Python\n\n## How It Works\n\n* SongSim uses self-similarity matrices to visualize patterns of repetition in text. The cell at position (x, y) is filled in if the xth and yth words of the song are the same.\n\n<img src = \"https:\/\/colinmorris.github.io\/SongSim\/img\/about\/barbie.png\" width = \"450\" height = \"450\" \/> \n\n* You can find more information about the patterns here: https:\/\/colinmorris.github.io\/SongSim\/#\/about\/advanced\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sys\nfrom wordcloud import WordCloud\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# Preprocessing\n\"\"\"\ndata = pd.read_csv(\"\/kaggle\/input\/pink-floyd-lyrics\/pink_floyd_lyrics.csv\")\ndata.head()\ndata = data.dropna()\ndata.info()\ndata.album.unique()\ndarkside = data[data[\"album\"] == \"The Dark Side of the Moon\"]\nwish = data[data[\"album\"] == \"Wish You Were Here\"]\nwall = data[data[\"album\"] == \"The Wall\"]\nanimals = data[data[\"album\"] == \"Animals\"]\nmeddle = data[data[\"album\"] == \"Meddle\"]\ndarkside = darkside.reset_index()\nwish = wish.reset_index()\nwall = wall.reset_index()\nanimals = animals.reset_index()\nmeddle = meddle.reset_index()\n\"\"\"\n# Functions\n\"\"\"\ndef SongSim(lyr, show_table = False, fig_size = (8, 8), ticks = False, title = \"SongSim Table\"):\n    \n    \"\"\"\n    SongSim is a method that creates a similarity matrix for n length text.\n    I inspired by Collin Morris and when I looked his github page for the source code\n    for this but I did not know that it written in css and javascript \n    so I created a python version for SongSim.\n    Github link of actual SongSim: https:\/\/github.com\/colinmorris\/SongSim\n    \"\"\"\n    \n    if type(lyr) is str:\n        \n        punctuations = '''!()-[]{};:'\"\\,<>.\/?@#$%^&*_~'''\n        lyrics = \"\"\n        for char in lyr:\n            if char not in punctuations:\n                lyrics = lyrics + char\n                \n        lyrics = lyrics.lower()\n        lyrics = lyrics.split()\n        \n    else:\n        \n        lyrics = lyr.copy()\n        \n    raw_corrs = []\n    for current_word in lyrics:\n        for word in lyrics:\n            if current_word == word:\n                raw_corrs.append(1)\n\n            else:\n                raw_corrs.append(0)\n\n    corrs = []\n    for length, _ in enumerate(lyrics, start = 1):\n        length *= len(lyrics)\n        corrs.append(raw_corrs[(length - len(lyrics)):length])\n\n    corrs = np.array(corrs)\n\n    uniq, count = np.unique(lyrics, return_counts = True)\n    freq_names = {}\n    for name, freq in zip(uniq, count):\n        freq_names[name] = freq\n\n    freq_names2 = freq_names.copy()\n\n    corrs_dict = {}\n    for indx, c_name in enumerate(lyrics):\n        if c_name in corrs_dict:\n            freq_names2[c_name] -= 1 \n            label = freq_names[c_name] - freq_names2[c_name]\n            corrs_dict[c_name + str(label)] = corrs[indx]\n\n        else:\n            corrs_dict[c_name] = corrs[indx]\n\n    corrs_df = pd.DataFrame(data = corrs_dict)\n\n    songsim = corrs_df.corr()\n    for colmn in songsim.columns:\n        for indx, corr_val in enumerate(songsim[colmn]):\n            if corr_val != 1:\n                songsim[colmn][indx] = 0\n\n            else:\n                continue\n                \n    if show_table == True:\n        f,ax = plt.subplots(figsize = fig_size)\n        res = sns.heatmap(songsim,linecolor = \"none\", xticklabels = ticks, yticklabels = ticks, ax=ax,cmap = \"Greys\", cbar = False)\n        plt.title(title)\n\n        for _, spine in res.spines.items(): \n            spine.set_visible(True) \n            spine.set_linewidth(2) \n\n        plt.show()\n    \n    return songsim\ndef clear_lyrics(lyr):\n    \n    if type(lyr) is str:\n        \n        punctuations = '''!()-[]{};:'\"\\,<>.\/?@#$%^&*_~'''\n        lyrics = \"\"\n        for char in lyr:\n            if char not in punctuations:\n                lyrics = lyrics + char\n                \n        lyrics = lyrics.lower()\n        clean = lyrics.split()\n    \n    return clean\ndef plot_gallery(data):\n\n    fig, ax = plt.subplots(int(len(data[\"lyrics\"])\/2),2, figsize = (12,(len(data[\"lyrics\"])-1)*3))\n\n    count = 0\n    for r in range(0,int(len(data[\"lyrics\"])\/2)):\n        for c in range(0,2):\n            \n            table= SongSim(data[\"lyrics\"][count])\n            res = sns.heatmap(table, xticklabels = False, yticklabels = False, ax=ax[r,c],cmap = \"Greys\", cbar = False)\n            ax[r,c].set_title(data[\"song_title\"][count])\n\n            for _, spine in res.spines.items(): \n                spine.set_visible(True) \n                spine.set_linewidth(2) \n\n            count += 1\n\n    plt.show()\n    \n    if len(data[\"lyrics\"])%2 == 1:\n        fig, ax = plt.subplots(figsize = (5.5,5.5))\n        \n        table = SongSim(data[\"lyrics\"][count])\n        \n        res = sns.heatmap(table, xticklabels = False, yticklabels = False, ax=ax,cmap = \"Greys\", cbar = False)\n        ax.set_title(data[\"song_title\"][count])\n\n        for _, spine in res.spines.items(): \n            spine.set_visible(True) \n            spine.set_linewidth(2) \n            \n        plt.show()\n\"\"\"\n# Gallery\n\"\"\"\n\"\"\"\n## The Dark Side of the Moon\n\n<img src = \"https:\/\/i.imgur.com\/s349HdQ.jpg\" width = \"400\" height = \"400\" \/>\n\"\"\"\nplot_gallery(darkside)\n\"\"\"\n### The Interesting one: Eclipse\n\n* Eclipse is an interesting one because it has repeating diagonlas. This is a very common pattern in pop music, normally they are long diagonals but in Eclpise they are very short and they represent the \"(and) all that you...\" part.\n\"\"\"\ncleared = clear_lyrics(darkside[\"lyrics\"][8])\nsong_as_txt = ' '.join([text for text in cleared])\n\nfig = plt.figure(figsize = (12,12))\nfig.suptitle('The Interesting one: Eclipse',fontsize = 15)\n\nwordcloud = WordCloud(width=800, height=300, random_state=42, max_font_size=100, relative_scaling=0.5, background_color='white').generate(song_as_txt)\n\nax1 = plt.subplot(212)\nax1.imshow(wordcloud)\nax1.axis('off')\nax1.set_title(\"WordCloud\")\n\n\nax2 = plt.subplot(221)\nres = sns.heatmap(SongSim(darkside[\"lyrics\"][8]),linecolor = \"none\", xticklabels = False, yticklabels = False, ax=ax2,cmap = \"Greys\", cbar = False)\nax2.set_title(\"Eclipse\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\n    \nax3 = plt.subplot(222)\nres = sns.heatmap(SongSim(cleared[0:20]),linecolor = \"none\", xticklabels = True, yticklabels = True, ax=ax3,cmap = \"Greys\", cbar = False)\nax3.set_title(\"Repeating Diagonals\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\nplt.show()\n\"\"\"\n## Wish You Were Here\n\n<img src = \"https:\/\/i.imgur.com\/lcJLwrw.jpg\" width = \"400\" height = \"400\" \/>\n\"\"\"\nplot_gallery(wish)\n\"\"\"\n### The Interesting one: Shine on You Crazy Diamond\n\n* Just like the Eclipse this song has diagonals as well but they are standalone verses this time. The verse is: \"Shine on you crazy diamond\".\n\"\"\"\ncleared = clear_lyrics(wish[\"lyrics\"][0])\nsong_as_txt = ' '.join([text for text in cleared])\n\nfig = plt.figure(figsize = (12,12))\nfig.suptitle('The Interesting one: Shine on You Crazy Diamond',fontsize = 15)\n\nwordcloud = WordCloud(width=800, height=300, random_state=42, max_font_size=100, relative_scaling=0.5, background_color='white').generate(song_as_txt)\n\nax1 = plt.subplot(212)\nax1.imshow(wordcloud)\nax1.axis('off')\nax1.set_title(\"WordCloud\")\n\n\nax2 = plt.subplot(221)\nres = sns.heatmap(SongSim(wish[\"lyrics\"][0]),linecolor = \"none\", xticklabels = False, yticklabels = False, ax=ax2,cmap = \"Greys\", cbar = False)\nax2.set_title(\"Shine on You Crazy Diamond\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\n    \nax3 = plt.subplot(222)\nres = sns.heatmap(SongSim(cleared[10:15]),linecolor = \"none\", xticklabels = True, yticklabels = True, ax=ax3,cmap = \"Greys\", cbar = False)\nax3.set_title(\"Repeating Diagonal\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\nplt.show()\n\"\"\"\n## The Wall\n\n<img src = \"https:\/\/i.imgur.com\/XbUApDM.jpg\" width = \"400\" height = \"400\" \/>\n\"\"\"\nplot_gallery(wall)\n\"\"\"\n### The Interesting one: Stop\n\n* This song uses another common pattern: Checkerboards. Checkerboards represents repeating verses in a song. The length of spacing betwen blocks shows the length of the verse ([length of the verse]-1). In Stop the verse is: \"have to know\". \n\"\"\"\ncleared = clear_lyrics(wall[\"lyrics\"][23])\nsong_as_txt = ' '.join([text for text in cleared])\n\nfig = plt.figure(figsize = (12,12))\nfig.suptitle('The Interesting one: Stop',fontsize = 15)\n\nwordcloud = WordCloud(width=800, height=300, random_state=42, max_font_size=100, relative_scaling=0.5, background_color='white').generate(song_as_txt)\n\nax1 = plt.subplot(212)\nax1.imshow(wordcloud)\nax1.axis('off')\nax1.set_title(\"WordCloud\")\n\n\nax2 = plt.subplot(221)\nres = sns.heatmap(SongSim(wall[\"lyrics\"][23]),linecolor = \"none\", xticklabels = False, yticklabels = False, ax=ax2,cmap = \"Greys\", cbar = False)\nax2.set_title(\"Stop\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\n    \nax3 = plt.subplot(222)\nres = sns.heatmap(SongSim(cleared[36:48]),linecolor = \"none\", xticklabels = True, yticklabels = True, ax=ax3,cmap = \"Greys\", cbar = False)\nax3.set_title(\"Repeating Checkerboard\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\nplt.show()\n\"\"\"\n## Animals\n\n<img src = \"https:\/\/i.imgur.com\/3sAwUk9.jpg\" width = \"400\" height = \"400\" \/>\n\"\"\"\nplot_gallery(animals)\n\"\"\"\n### The Interesting one: Pigs (Three Different Ones)\n\n* This one uses short diagonals as well. Verse: \"Haha, charade you are\".\n\"\"\"\ncleared = clear_lyrics(animals[\"lyrics\"][2])\nsong_as_txt = ' '.join([text for text in cleared])\n\nfig = plt.figure(figsize = (12,12))\nfig.suptitle('The Interesting one: Pigs (Three Different Ones)',fontsize = 15)\n\nwordcloud = WordCloud(width=800, height=300, random_state=42, max_font_size=100, relative_scaling=0.5, background_color='white').generate(song_as_txt)\n\nax1 = plt.subplot(212)\nax1.imshow(wordcloud)\nax1.axis('off')\nax1.set_title(\"WordCloud\")\n\n\nax2 = plt.subplot(221)\nres = sns.heatmap(SongSim(animals[\"lyrics\"][2]),linecolor = \"none\", xticklabels = False, yticklabels = False, ax=ax2,cmap = \"Greys\", cbar = False)\nax2.set_title(\"Pigs (Three Different Ones)\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\n    \nax3 = plt.subplot(222)\nres = sns.heatmap(SongSim(cleared[6:10]),linecolor = \"none\", xticklabels = True, yticklabels = True, ax=ax3,cmap = \"Greys\", cbar = False)\nax3.set_title(\"Repeating Diagonal\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\nplt.show()\n\"\"\"\n## Meddle\n\n<img src = \"https:\/\/i.imgur.com\/uiGgsWV.jpg\" width = \"400\" height = \"400\" \/>\n\"\"\"\nplot_gallery(meddle)\n\"\"\"\n### The Interesting one: A Pillow of Winds\n\n* This one has long diagonals. Verse: \"Sleepy time, and I lie with my love by my side and she's breathing low\".\n\"\"\"\ncleared = clear_lyrics(meddle[\"lyrics\"][1])\nsong_as_txt = ' '.join([text for text in cleared])\n\nfig = plt.figure(figsize = (12,12))\nfig.suptitle('The Interesting one: A Pillow of Winds',fontsize = 15)\n\nwordcloud = WordCloud(width=800, height=300, random_state=42, max_font_size=100, relative_scaling=0.5, background_color='white').generate(song_as_txt)\n\nax1 = plt.subplot(212)\nax1.imshow(wordcloud)\nax1.axis('off')\nax1.set_title(\"WordCloud\")\n\n\nax2 = plt.subplot(221)\nres = sns.heatmap(SongSim(meddle[\"lyrics\"][1]),linecolor = \"none\", xticklabels = False, yticklabels = False, ax=ax2,cmap = \"Greys\", cbar = False)\nax2.set_title(\"A Pillow of Winds\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\n    \nax3 = plt.subplot(222)\nres = sns.heatmap(SongSim(cleared[10:25]),linecolor = \"none\", xticklabels = True, yticklabels = True, ax=ax3,cmap = \"Greys\", cbar = False)\nax3.set_title(\"Repeating Diagonal\")\n\nfor _, spine in res.spines.items(): \n    spine.set_visible(True) \n    spine.set_linewidth(2) \n\nplt.show()\n\"\"\"\n# Conclusion\n* **We analyzed the songs and created a gallery.**\n* **We have seen that Pink Floyd is not that repetitive and does not follow a certain pattern in their songs. That is an expected result because they are a Progressive Rock band.**\n* **If there is something wrong with this kernel please let me know in the comments.**\n\n### **My other kernels: https:\/\/www.kaggle.com\/mrhippo\/notebooks**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '30bc9b94189139'}"}
{"id":"12631","text":"\"\"\"\n<br>\n<h1 style = \"font-size:60px; font-family:Garamond ; font-weight : normal; background-color: #f6f5f5 ; color : #fe346e; text-align: center; border-radius: 100px 100px;\"> Handling Missing Values<\/h1>\n<br>\n\n![](https:\/\/fintechprofessor.com\/wp-content\/uploads\/2019\/12\/close-up-texture-of-a-white-jigsaw-puzzle-in-assembled-state-with-missing-elements-forming-a-blue-pad_t20_WxKR61.jpg)\n\"\"\"\n\"\"\"\n<div class = 'alert alert-info' style = 'color:blue'> \ud83d\udca1 This notebook is part of the <a href=\"http:\/\/iitg.ac.in\/sa\/caciitg\/course\" style=\"color: #002d5e\">Summer Analytics 2021<\/a> course curated by <a href=\"https:\/\/www.linkedin.com\/company\/caciitg\/mycompany\/\" style=\"color: black\">Consulting & Analytics Club, IIT Guwahati<\/a>. This notebook intends to introduce the readers to various different Imputaion techniques and How to deal with missing values in general with the help of <i>pandas<\/i> and <i>sklearn<\/i><\/div>\n\"\"\"\n\"\"\"\n<h1 style = \"font-family: garamond; font-size: 40px; font-style: normal; letter-spcaing: 3px; background-color: #f6f5f5; color :#fe346e; border-radius: 100px 100px; text-align:center \" >Table of Contents<\/h1>\n\n\n* [1. Introduction](#1)\n    * [1.1 Import Required Libraries](#1.1)\n    * [1.2 Exploring the Data](#1.2)\n    * [1.3 Helper Function](#1.3)\n* [2. Dropping Rows and Columns](#2)\n    * [2.1 Dropping Rows with Missing Values](#2.1)\n    * [2.2 Dropping Columns with Missing Values](#2.2)\n* [3. Univariate vs Multivariate Imputation](#3)\n    * [3.1 Univariate Imputation](#3.1)\n        * [3.1.1 Simple Imputer](#3.1.1)\n    * [3.2 Multivariate Imputation](#3.2)\n        * [3.2.1 KNN Imputer](#3.2.1)\n        * [3.2.2 Iterative Imputer](#3.2.2)\n* [4. Missing Indicator](#4)\n* [5. Missing Indicator + Iterative Imputer](#5)\n* [6. Further Readings](#6)\n\"\"\"\n\"\"\"\n<a id = '1'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 1. Introduction <\/h2>\n\"\"\"\n\"\"\"\n<a id = '1.1'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">1.1 Import Required Libraries<\/h2>\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.impute import SimpleImputer\n\nfrom sklearn.impute import KNNImputer\n\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\n\n# displays all the columns\npd.set_option('display.max_columns', None)\nplt.rcParams[\"figure.figsize\"] = (18, 8);\n\"\"\"\n<a id = '1.2'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight:normal; border-radius: 100px 100px; text-align: center\">1.2 Exploring the Data <\/h2>\n\"\"\"\ndf = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\ndf.head()\ndf.shape\ndf.info()\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">We have 81 columns in total, 80 of them are feature columns and <code>SalePrice<\/code> is the target column<\/span>\n\"\"\"\nfeature_cols = [col for col in df.columns if col not in ['SalePrice']]\ntarget_cols = ['SalePrice']\n\ncat_cols = [col for col in feature_cols if df[col].dtype == 'O']\ncont_cols = [col for col in feature_cols if col not in cat_cols]\nsns.heatmap(df.isnull(), cmap='Blues', cbar=False, yticklabels=False, xticklabels=df.columns);\n\"\"\"\n<a id = '1.3'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">1.3 Helper Function<\/h2>\n\"\"\"\ndef encode_missing_columns(df, col):\n    le = LabelEncoder()\n    \n    # gets unique values w\/o NaN\n    unique_without_nan = pd.Series([i for i in df[col].unique() if type(i) == str])\n    le.fit(unique_without_nan) # Fit on unique values\n    \n    # Set transformed col leaving np.NaN as they are\n    df[col] = df[col].apply(lambda x: le.transform([x])[0] if type(x) == str else x)\n\"\"\"\nLet's take an example to understand what this function is doing <br>\nSuppose we have a column `['apple', 'mango', 'banana', 'apple', 'banana', NaN]`\n\"\"\"\ndemo_col = pd.Series(['apple', 'mango', 'banana', 'apple', 'banana', np.NaN])\nprint(f'Unique Values in the Column: {demo_col.unique()}')\nprint(f'Unique Values of type string: {[i for i in demo_col.unique() if type(i) == str]}')\nle = LabelEncoder()\nunique_without_nan = pd.Series([i for i in demo_col.unique() if type(i) == str])\nle.fit(unique_without_nan)\ndemo_col.apply(lambda x: le.transform([x])[0] if type(x) == str else x)\n\"\"\"\n<a id = '2'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 2. Dropping Rows and Columns <\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">This isn't an imputation technique, but this might be the first thing that comes in mind to deal with missing values<\/span>\n\"\"\"\n\"\"\"\n<a id = '2.1'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">2.1 Dropping Rows with Missing Values<\/h2>\n\"\"\"\nsum(df.isna().sum(axis=1) > 0)\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">If we drop all the rows with any missing value we aren't left with any row<\/span>\n\"\"\"\n\"\"\"\n<a id = '2.2'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">2.2 Dropping Columns with Missing Values<\/h2>\n\"\"\"\nsum(df.isna().sum(axis=0) > 0)\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">If we drop all columns with missing values we lose 19 columns<\/span>\n\"\"\"\n\"\"\"\n<a id = '3'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 3. Univariate vs Multivariate Imputation <\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">One type of imputation algorithm is univariate, which imputes values in the i-th feature dimension using only non-missing values in that feature dimension (e.g. <code>SimpleImputer<\/code>). By contrast, multivariate imputation algorithms use the entire set of available feature dimensions to estimate the missing values (e.g. <code>IterativeImputer<\/code>).<\/span>\n\"\"\"\n\"\"\"\n<a id = '3.1'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">3.1 Univariate Imputation<\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">We can impute missing values with a provided constant value, or using the statistics (mean, median or most frequent) of each column.<\/span>\n\"\"\"\n\"\"\"\n<a id = '3.1.1'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 28px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">3.1.1 Simple Imputer<\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Imputing Continuous Variables<\/span>\n\"\"\"\ndf_simple_imputer = df.copy()\nimputer = SimpleImputer(strategy='mean')\n\ndf_simple_imputer[cont_cols] = imputer.fit_transform(df_simple_imputer[cont_cols])\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Imputing Categorical Variables<\/span>\n\"\"\"\nimputer = SimpleImputer(strategy='most_frequent')\n\ndf_simple_imputer[cat_cols] = imputer.fit_transform(df_simple_imputer[cat_cols])\nsns.heatmap(df_simple_imputer.isnull(), cmap='Blues', cbar=False, yticklabels=False, xticklabels=df.columns);\n\"\"\"\n<a id = '3.2'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 35px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">3.2 Multivariate Imputation<\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">A strategy for imputing missing values by modeling each feature with missing values as a function of other features<\/span>\n\"\"\"\n\"\"\"\n<a id = '3.2.1'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 28px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">3.2.1 KNN Imputer<\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">KNNImputer doesn't work on strings so we need to encode the strings into float or int keeping the <code>NaN<\/code> values<\/span> <br>\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">This is where we will use the helper function we defined earlier<\/span>\n\"\"\"\ndf_knn_imputer = df.copy()\nfor col in cat_cols:\n    encode_missing_columns(df_knn_imputer, col)\nknn_imputer = KNNImputer(n_neighbors=5)\n\ndf_knn_imputer[feature_cols] = knn_imputer.fit_transform(df_knn_imputer[feature_cols])\nsns.heatmap(df_knn_imputer.isnull(), cmap='Blues', cbar=False, yticklabels=False, xticklabels=df.columns);\n\"\"\"\n<a id = '3.2.2'><\/a>\n\n<h2 style = \"background-color: #f6f5f5; color : #fe346e; font-size: 28px; font-family:garamond; font-weight: normal; border-radius: 100px 100px; text-align: center\">3.2.2 Iterative Imputer<\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Like KNNImputer, Iterative Imputer also doesn't work on strings<\/span>\n\"\"\"\ndf_iterative_imputer = df.copy()\nfor col in cat_cols:\n    encode_missing_columns(df_iterative_imputer, col)\nitr_imputer = IterativeImputer()\n\ndf_iterative_imputer[feature_cols] = itr_imputer.fit_transform(df_iterative_imputer[feature_cols])\nsns.heatmap(df_iterative_imputer.isnull(), cmap='Blues', cbar=False, yticklabels=False, xticklabels=df.columns);\n\"\"\"\n<a id = '4'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 4. Missing Indicator <\/h2>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Most of the times the missing values are not randomly distributed across observations but are distributed within one or more sub-samples. Therefore, missingness itself might be a good indicator to classify the labels<\/span>\n\"\"\"\nfrom sklearn.impute import MissingIndicator\ndf_miss = df.copy()\nmiss_indicator = MissingIndicator()\n\nX_miss = miss_indicator.fit_transform(df_miss[feature_cols])\nX_miss.shape\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">Recall that in <a href=\"#2.2\">Section 2.2<\/a> we had seen that if we drop all columns with missing values we lose 19 columns<\/span>\n\"\"\"\n\"\"\"\n<a id = '5'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 5. Missing Indicator + Iterative Imputer <\/h2>\n\"\"\"\ndf_miss_itr = df.copy()\nfor col in cat_cols:\n    encode_missing_columns(df_miss_itr, col)\n# setting add_indicator=True returns missing indicators alongwith the imputed dataframe\nitr_imputer = IterativeImputer(add_indicator=True) \n\nX = itr_imputer.fit_transform(df_miss_itr[feature_cols])\nX.shape\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 1.5em; font-weight: 300;\">We have 99 feature columns now (80 original features + 19 missing indicator features) and 1 target column<\/span>\n\"\"\"\n\"\"\"\n<a id = '6'><\/a>\n<h2 style = \"font-family:garamond; font-size:50px; background-color: #f6f6f6; color : #fe346e; border-radius: 100px 100px; text-align:center\"> 6. Further Readings <\/h2>\n\"\"\"\n\"\"\"\n1. [KNN Imputer Algorithm](https:\/\/www.youtube.com\/watch?v=AHBHMQyD75U&list=PLlg4M31xJeYa7XcJZWypot8l7R-0E65Ls)\n2. [Iterative Imputer Algorithm](https:\/\/www.youtube.com\/watch?v=WPiYOS3qK70&list=PLlg4M31xJeYa7XcJZWypot8l7R-0E65Ls)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '171db65c404239'}"}
{"id":"51977","text":"# 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\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndf_train=pd.read_csv('..\/input\/titanic\/train.csv')\ndf_test=pd.read_csv('..\/input\/titanic\/test.csv')\nPassengerId=df_test['PassengerId']\ndf_train.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True)\ndf_test.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True)\ndf_train.isnull().sum()\/len(df_train)*100\n# Removing Cabin\ndf_train.drop(['Cabin'],axis=1,inplace=True)\ndf_test.drop(['Cabin'],axis=1,inplace=True)\n# Removing rows where embarked is null\n\ndf_train.dropna(subset=['Embarked'],inplace=True)\n\ndf_train['Embarked'].isnull().sum()\nage_train_series=df_train.groupby(['Pclass','Sex'])['Age'].transform('median')\nage_test_series=df_test.groupby(['Pclass','Sex'])['Age'].transform('median')\ndf_train['Age']=df_train['Age'].fillna(age_train_series)\ndf_test['Age']=df_test['Age'].fillna(age_test_series)\ndf_test.isnull().sum()\nFare_test_series=df_test.groupby(['Pclass'])['Fare'].transform('median')\ndf_test['Fare']=df_test['Fare'].fillna(Fare_test_series)\ndf_train=pd.get_dummies(df_train,drop_first=True)\n\ndf_test=pd.get_dummies(df_test,drop_first=True)\nfrom sklearn.model_selection import train_test_split\nX = df_train.drop('Survived',axis=1)\n\n# Putting response variable to y\ny = df_train['Survived']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, random_state=42)\nX_train.shape, X_test.shape\n\"\"\"\n### RANDOM FOREST WITHOUT HYPERPARAMETER TUNING\n\"\"\"\n from sklearn.ensemble import RandomForestClassifier\nrf=RandomForestClassifier(random_state=42,n_estimators=100,max_depth=4,min_samples_leaf=15,max_features=3)\nrf.fit(X_train,y_train)\nfrom sklearn.metrics import accuracy_score\naccuracy_score(y_test,rf.predict(X_test))\npredictions=rf.predict(df_test)\ntitanic_4=pd.DataFrame({'PassengerId':PassengerId,'Survived':predictions})\ntitanic_4.to_csv('My_4th_submission',index=False)\n\npd.read_csv('My_4th_submission')","meta":"{'source': 'AI4Code', 'id': '5fa663cdf86d92'}"}
{"id":"4352","text":"# 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\n\"\"\"\nThis is a basic baseline using LightAutoML preset pipeline. Read the docs [here](https:\/\/lightautoml.readthedocs.io\/en\/latest\/)\n\"\"\"\n#Installing LightAutoML\n!pip install lightautoml\nfrom lightautoml.automl.presets.tabular_presets import TabularAutoML\nfrom lightautoml.tasks import Task\n#Reading the data\ntest = pd.read_csv('..\/input\/tabular-playground-series-sep-2021\/test.csv')\ntrain = pd.read_csv('..\/input\/tabular-playground-series-sep-2021\/train.csv')\nsubmission = pd.read_csv('..\/input\/tabular-playground-series-sep-2021\/sample_solution.csv')\ntrain.head()\ntest.head()\n#Training the model using the preset pipeline.\nautoml = TabularAutoML(task = Task('binary'))\nroles = {'target': 'claim',\n        'drop':['id']}\noof_pred = automl.fit_predict(train, roles = roles)\n#Getting our predictions\ntest_pred = automl.predict(test)\ntest_pred\ntest_pred_df = pd.DataFrame(test_pred.data)\ntest_pred_df\nsubmission['claim'] = test_pred_df\nsubmission\n#Saving our predictions\nsubmission.to_csv('submission', index = False)","meta":"{'source': 'AI4Code', 'id': '081802c9edc6e5'}"}
{"id":"76250","text":"\"\"\"\n# Hi all. \ud83d\ude4b\n\"\"\"\n\"\"\"\nToday, we will create models with famous trio (**XGBoost** & **LightGBM** & **Catboost**) that predict behavior to retain customers. We will analyze all relevant customer data and develop focused customer retention programs.\n\"\"\"\n\"\"\"\nWe will also deal with imbalanced data by using the famous trio modles and hyperparameter tunning with **OPTUNA**.\n\"\"\"\n\"\"\"\n# Table of Contents\n- Data\n\n- Problem at Hand and Metric to Use?\n\n- Exploratory Data Analysis\n\n    - Target Variable\n\n    - Numerical Features\n\n    - Categorical Features\n\n- Famous Trio and Imbalanced Data\n\n    - CATBOOST \/ OPTUNA\n\n    - XGBOOST \/ OPTUNA\n\n    - LIGHTGBM \/OPTUNA\n\n- Model Comparision\n\n- Conclusion\n\"\"\"\n\"\"\"\n# Data\nThis dataset is about predicting whether a customer will change telecommunications provider, something known as \"churning\".\n\nThe training dataset contains 4250 samples. Each sample contains 19 features and 1 boolean variable \"churn\" which indicates the class of the sample. The 19 input features and 1 target variable are:\n\n![image.png](attachment:11dae1ed-7c24-4d7f-8948-aac71aad2c37.png)\n\"\"\"\n\"\"\"\n# Problem at Hand and Metric to Use?\n- After analyzing data and data dictionary we see that we have a **classification** problem.\n- We wil make classification on the target variable **Churn**.\n- For this purpose we will look at the balance of the target variable.\n- Since our target variable has imblanced data we are not going to use **Accuracy** score.\n- Based on the problem on the hand, we will use **Recall** score.\n\"\"\"\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\nfrom sklearn.model_selection import cross_val_score,cross_val_predict, train_test_split\nfrom sklearn.preprocessing import OneHotEncoder,StandardScaler,PowerTransformer,LabelEncoder\n\nfrom sklearn.metrics import accuracy_score,classification_report, recall_score,confusion_matrix, roc_auc_score, precision_score, f1_score, roc_curve, auc, plot_confusion_matrix,plot_roc_curve\n\n\nimport optuna\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom catboost import CatBoostClassifier\n\nimport optuna\nimport lightgbm as lgb\nfrom xgboost import XGBClassifier\n#from lightgbm import LGBMClassifier, plot_importance\nfrom catboost import CatBoostClassifier\n\n\n#importing plotly and cufflinks in offline mode\nimport cufflinks as cf\nimport plotly.offline\ncf.go_offline()\ncf.set_config_file(offline=False, world_readable=True)\n\n\nimport plotly \nimport plotly.express as px\nimport plotly.graph_objs as go\nimport plotly.offline as py\nfrom plotly.offline import iplot\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\n\nimport shap \n\nimport missingno as msno\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\npd.set_option('max_columns',100)\npd.set_option('max_rows',900)\n\npd.set_option('max_colwidth',200)\ndata = pd.read_csv(\"..\/input\/customer-churn-prediction-2020\/train.csv\")\ndata.head()\ndf1 = data.copy()\ndf1.head()\nprint(f\"We have {df1.shape[0]} rows and {df1.shape[1]} columns in our dataset.\")\ndf1.duplicated().sum()\ndef missing (df1):\n    missing_number = df1.isnull().sum().sort_values(ascending=False)\n    missing_percent = (df1.isnull().sum()\/df1.isnull().count()).sort_values(ascending=False)\n    missing_values = pd.concat([missing_number, missing_percent], axis=1, keys=['Missing_Number', 'Missing_Percent'])\n    return missing_values\n\nmissing(df1)\n\"\"\"\nWe have neither duplicated nor missing value (some deeper checks might always be needed to be 100% sure).\n\"\"\"\ndf1.info()\n\"\"\"\n**Based on our preliminary analysis, we conclude that**:\n- We won't drop any column.\n- For **CatBoost** model, types of columns with int64 will be converted into float type.\n- We will look at the cardinality of the categorical variables.\n- And finally, we will convert **churn** column to numeric type by using **label encoding**.\n\"\"\"\n\"\"\"\n## Target Variable\n\"\"\"\ndf1.churn.value_counts()\ndf1.churn.value_counts(normalize=True)\ny = df1['churn']\nprint(f'Percentage of Churn:  {round(y.value_counts(normalize=True)[1]*100,2)} %  --> ({y.value_counts()[1]} customers)')\nprint(f'Percentage Non_Churn: {round(y.value_counts(normalize=True)[0]*100,2)}  %  --> ({y.value_counts()[0]} customers)')\ny.iplot(kind=\"hist\", title=\"Churns vs. NonChurns\");\n\"\"\"\n- It is obvious that we have imbalanced data.\n- Almost 14% of the customers (598 customers) didn't continue with the company and churned.\n- Almost 86% of the customers (3562 customers) continue with the company and didn't churn.\n\"\"\"\n# We converted type of \"churn\" from object to int\nle = LabelEncoder()\ndf1.churn = le.fit_transform(df1.churn)\ndf1.info()\n\"\"\"\n- We converted **churn** column into numeric type.\n\"\"\"\nnumerical= df1.select_dtypes(include = 'number').columns\n\ncategorical = df1.select_dtypes(include = 'object').columns\n\nprint(f'Numerical Columns:  {df1[numerical].columns}')\nprint('\\n')\nprint(f'Categorical Columns: {df1[categorical].columns}')\n\"\"\"\n- For ease of usage, we got the list of the **numerical** and **categorical** features.\n\"\"\"\n\"\"\"\n## Numerical Features\n\"\"\"\ncol_int = []\n\nfor col in numerical:\n    if df1[col].dtype == \"int64\":\n        col_int.append(col)\n\ncol_int.remove(\"churn\")\ncol_int\nfor i in col_int:\n    df1[i] = df1[i].astype(float)\n\"\"\"\n- We have just converted all types of all columns (except for **churn**) with int64 into float type.\n\"\"\"\ndf1.info()\ndf1[numerical].describe()\n# df1.describe()\nplt.figure(figsize=(16, 8))\nsns.heatmap (df1[numerical].corr(), annot=True, fmt= '.2f', vmin=-1, vmax=1, center=0, cmap='coolwarm');\n\"\"\"\n- We can see in heatmap that we have some multicollinerity. \n- We need to drop one of each highly correleated column pairs.\n\"\"\"\ndrop_col = ['total_day_charge', 'total_eve_charge', 'total_night_charge', 'total_intl_charge']\ndf1 = df1.drop(drop_col, axis=1)\ndf1.shape\nnumerical= df1.select_dtypes(include = 'number').columns\nnumerical\nplt.figure(figsize=(16, 8))\nsns.heatmap (df1[numerical].corr(), annot=True, fmt= '.2f', vmin=-1, vmax=1, center=0, cmap='coolwarm');\n\"\"\"\n- We got rid of multicollinear columns.\n- **total_day_minutes** has the highest correleation with **churn**.\n- Overall, there is low correleations among features.\n\n\"\"\"\n\"\"\"\n## Categorical Features\n\"\"\"\ndf1[categorical].nunique()\n\"\"\"\n- Great news! We do not have a high cardinality or zero variance issues.\n\"\"\"\nfor column in df1[categorical]:\n    print(f\"{column}: {df1[column].unique()}\")\n\"\"\"\n### state vs. churn\n\"\"\"\nfor i in df1[\"state\"].unique():\n    print(f'A customer from state of {i} has a probability of {round(df1[df1[\"state\"]==i][\"churn\"].mean()*100,2)} % churn.')\nfig = px.histogram(data_frame=df1, x=\"state\", color=\"churn\", width=1200, height=400)\nfig.show()\n\"\"\"\n- While **CA** (California) has the highest rate of churn, **VA** (Virginia) has the lowest churn rate.\n- Overall churn rates among states range from 5 percent to 25 percent.\n\"\"\"\n\"\"\"\n### area_code vs. churn\n\"\"\"\narea_code: ['area_code_415' 'area_code_408' 'area_code_510']\n    \nprint(f'A customer with area_code_415 has a probability of {round(df1[df1[\"area_code\"]==\"area_code_415\"][\"churn\"].mean()*100,2)} % churn.')\nprint()\nprint(f'A customer with area_code_408 has a probability of {round(df1[df1[\"area_code\"]==\"area_code_408\"][\"churn\"].mean()*100,2)} % churn.')\nprint()\nprint(f'A customer with area_code_510 has a probability of {round(df1[df1[\"area_code\"]==\"area_code_510\"][\"churn\"].mean()*100,2)} % churn.')\nfig = px.histogram(data_frame=df1, x=\"area_code\", color=\"churn\", width=420, height=420)\nfig.show()\n\"\"\"\n- It seems that there is not much difference among **area_codes** on churn rate.\n- We may drop it later.\n\"\"\"\n\"\"\"\n### international_plan vs. churn \n\"\"\"\nprint(f'A customer with an international plan has a probability of {round(df1[df1[\"international_plan\"]==\"yes\"][\"churn\"].mean()*100,2)} % churn.')\nprint()\nprint(f'A customer wwithout an international plan has a probability of {round(df1[df1[\"international_plan\"]==\"no\"][\"churn\"].mean()*100,2)} % churn.')\nfig = px.histogram(data_frame=df1, x=\"international_plan\", color=\"churn\", width=420, height=420)\nfig.show()\n\"\"\"\n- Customers with an international plan is almost 4 times more likely to churn than those without international plan.\n\"\"\"\n\"\"\"\n### voice_mail_plan vs. churn\n\"\"\"\nprint(f'A customer with a voice mail plan has a probability of {round(df1[df1[\"voice_mail_plan\"]==\"yes\"][\"churn\"].mean()*100,2)} % churn.')\nprint()\nprint(f'A customer wwithout a vocie mail plan has a probability of {round(df1[df1[\"voice_mail_plan\"]==\"no\"][\"churn\"].mean()*100,2)} % churn.')\nfig = px.histogram(data_frame=df1, x=\"voice_mail_plan\", color=\"churn\", width=420, height=420)\nfig.show()\n\"\"\"\n- Customers without a voice mail plan is almost 2.5 times more likely to churn than those with voice mail plan.\n\"\"\"\n\"\"\"\n# Famous Trio and Imbalanced Data\n\"\"\"\n\"\"\"\n- Now, let's look at the **CatBoost**, **XGBoost**, and **LightGBM** and see how they handle imbalanced data internally.\n- By giving an opportunity to focus more on the minority class and accordingly tunning the training, they do good job even on imbalanced data.\n\"\"\"\n\"\"\"\n- CatBoost, XGBoost, and LightGBM use **scale_pos_weight** hyperparameter to tune the training algorithm for the imbalanced data.\n\n- By defualt, **scale_pos_weight** is 1.\n\n- Both major class and minority class get the same weight in balanced data. However, when dealing with imbalanced data, story changes a bit.\n\n- Formula for calculating value of **scale_pos_weight**: \n    - Number of Non-churned (**majority**) customer: 5174\n    - Number of Churned customer(**minority**): 1869\n    - **scale_pos_weight** = 5174 \/ 1869 or almost 3\n- By adjusting the weight, minority class gets 3 times more impact and 3 times more correction than errors made on the majority class.\n\n**Note1**: If we use extreme values for the **scale_pos_weight**, we can overfit the minority class and model could make worse predictions.\n\n**Note2**: While **CatBoost** and **LightGBM** can handle categorical features, **XGBoost** cannot. You have to convert categorical features before creating your model.\n\"\"\"\n\"\"\"\n## CATBOOST\n\"\"\"\n\"\"\"\n![image.png](attachment:c30320f4-9693-4166-b972-26b5c751919a.png)\n\"\"\"\n\"\"\"\n- It is an Boosting algorithm that was created by Yandex.\n- It can handle both missing values and categorical values internally.\n\"\"\"\n\"\"\"\n### CatBoost - scale_pos_weight = 5\n\"\"\"\nnumerical_1 = ['account_length', 'number_vmail_messages', 'total_day_minutes',\n       'total_day_calls', 'total_eve_minutes', 'total_eve_calls',\n       'total_night_minutes', 'total_night_calls', 'total_intl_minutes',\n       'total_intl_calls', 'number_customer_service_calls']\nnumerical_1\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\ndf1 = df.copy()\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\n\n#for i in numerical_1:\n    #df1[i] = df1[i].astype(float)\n\n    \nX= df1.drop('churn', axis=1)\ny= df1['churn']\n\ncategorical_features_indices = np.where(X.dtypes != np.float)[0]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# With scale_pos_weight=5, minority class gets 5 times more impact and 5 times more correction than errors made on the majority class.\ncatboost_5 = CatBoostClassifier(verbose=False,random_state=0,scale_pos_weight=5)\n\ncatboost_5.fit(X_train, y_train,cat_features=categorical_features_indices,eval_set=(X_test, y_test))\ny_pred = catboost_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['Catboost_adjusted_weight_5']\nresult_df1 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df1\nfig, ax = plt.subplots(figsize=(10, 6))\nplot_confusion_matrix(catboost_5, X_test, y_test, cmap=plt.cm.plasma, ax=ax);\n\"\"\"\n### OPTUNA - Hyperparameter Tunning\n\"\"\"\ndef objective(trial):\n    df = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\n    df1 = df.copy()\n    \n    le = LabelEncoder()\n    df1['churn']=le.fit_transform(df1['churn'])\n    \n    X= df1.drop('churn', axis=1)\n    y= df1['churn']\n    \n    categorical_features_indices = np.where(X.dtypes != np.float)[0]\n    \n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n    param = {\n        \"objective\": \"Logloss\",\n        \"colsample_bylevel\": trial.suggest_float(\"colsample_bylevel\", 0.01, 0.1),\n        \"depth\": trial.suggest_int(\"depth\", 1, 12),\n        \"boosting_type\": trial.suggest_categorical(\"boosting_type\", [\"Ordered\", \"Plain\"]),\n        \"bootstrap_type\": trial.suggest_categorical(\n            \"bootstrap_type\", [\"Bayesian\", \"Bernoulli\", \"MVS\"]\n        ),\n        \"used_ram_limit\": \"3gb\",\n    }\n\n    if param[\"bootstrap_type\"] == \"Bayesian\":\n        param[\"bagging_temperature\"] = trial.suggest_float(\"bagging_temperature\", 0, 10)\n    elif param[\"bootstrap_type\"] == \"Bernoulli\":\n        param[\"subsample\"] = trial.suggest_float(\"subsample\", 0.1, 1)\n\n    cat_cls = CatBoostClassifier(verbose=False,random_state=0,scale_pos_weight=1.2, **param)\n\n    cat_cls.fit(X_train, y_train, eval_set=[(X_test, y_test)], cat_features=categorical_features_indices,verbose=0, early_stopping_rounds=100)\n\n    preds = cat_cls.predict(X_test)\n    pred_labels = np.rint(preds)\n    accuracy = accuracy_score(y_test, pred_labels)\n    return accuracy\n\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=100, timeout=600)\n\n    print(\"Number of finished trials: {}\".format(len(study.trials)))\n\n    print(\"Best trial:\")\n    trial = study.best_trial\n\n    print(\"  Value: {}\".format(trial.value))\n\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\n\"\"\"\n- Ok let's use our **CatBoost** model with new parameters.\n\"\"\"\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\ndf1 = df.copy()\n\n#for target feature\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\n\nX=df1.drop('churn', axis=1)\ny=df1['churn']\n\n#indeces of categorical observations\ncategorical_features_indices = np.where(X.dtypes != np.float)[0]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n#since our dataset is not imbalanced, we do not have to use scale_pos_weight parameter to counter balance our results\n#catboost_5 = CatBoostClassifier(verbose=False,random_state=0,scale_pos_weight=5)\ncatboost_5 = CatBoostClassifier(verbose=False,random_state=0,\n                                 colsample_bylevel=0.091134936724785,\n                                 depth=9,\n                                 boosting_type=\"Ordered\",\n                                 bootstrap_type=\"MVS\")\n\ncatboost_5.fit(X_train, y_train,cat_features=categorical_features_indices,eval_set=(X_test, y_test), early_stopping_rounds=100)\ny_pred = catboost_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['Catboost_adjusted_weight_5_optuna']\nresult_df2 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df2\n\"\"\"\n- With **OPTUNA** hyperparameters, we managed to increase our **Accuracy** score by 2%.\n\n\n![image.png](attachment:b3f5c277-ef75-4395-88af-c6653493bb3f.png)\n\"\"\"\n\"\"\"\n## LightGBM\n\"\"\"\n\"\"\"\n![image.png](attachment:f9f51bdc-d385-4a11-9bb4-d226f9760a62.png)\n\"\"\"\n\"\"\"\nIt was developed by Microsoft \n\"\"\"\n\"\"\"\n### LightGBM - scale_pos_weight = 5\n\"\"\"\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\ndf1 = df.copy()\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\n                 \ndf1= pd.get_dummies(df1)\nX= df1.drop('churn', axis=1)\ny= df1['churn']\n\nfor col in X.columns:\n    col_type = X[col].dtype\n    if col_type == 'object' or col_type.name == 'category':\n        X[col] = X[col].astype('category')\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nlgbmc_5=LGBMClassifier(random_state=0,scale_pos_weight=5)\n\nlgbmc_5.fit(X_train, y_train,categorical_feature = 'auto',eval_set=(X_test, y_test),feature_name='auto', verbose=0)\n\ny_pred = lgbmc_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['LightGBM_adjusted_weight_5']\nresult_df3 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df3\n\"\"\"\nWith our defult parameters, we got almost 0.96 as accuracy score.\n\"\"\"\n\"\"\"\n### OPTUNA - Hyperparameter Tunning\n\"\"\"\ndef objective(trial):\n    df = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\n    df1 = df.copy()\n    le = LabelEncoder()\n    df1['churn']=le.fit_transform(df1['churn'])\n   \n    \n    X= df1.drop('churn', axis=1)\n    y= df1['churn']\n    \n    for col in X.columns:\n        col_type = X[col].dtype\n        if col_type == 'object' or col_type.name == 'category':\n            X[col] = X[col].astype('category')    \n    \n    param = {\n        \"objective\": \"binary\",\n        \"metric\": \"binary_logloss\",\n        \"verbosity\": -1,\n        \"boosting_type\": \"dart\",\n        \"num_leaves\": trial.suggest_int(\"num_leaves\", 2,2000),\n        \"max_depth\": trial.suggest_int(\"max_depth\", 3, 12),\n        \"lambda_l1\": trial.suggest_float(\"lambda_l1\", 1e-8, 10.0, log=True),\n        \"lambda_l2\": trial.suggest_float(\"lambda_l2\", 1e-8, 10.0, log=True),\n        \"num_leaves\": trial.suggest_int(\"num_leaves\", 2, 256),\n        \"feature_fraction\": trial.suggest_float(\"feature_fraction\", 0.4, 1.0),\n        \"bagging_fraction\": trial.suggest_float(\"bagging_fraction\", 0.4, 1.0),\n        \"bagging_freq\": trial.suggest_int(\"bagging_freq\", 1, 7),\n        \"min_child_samples\": trial.suggest_int(\"min_child_samples\", 5, 100),\n    }\n    \n    lgbmc_adj=lgb.LGBMClassifier(random_state=0,scale_pos_weight=5,**param)\n    lgbmc_adj.fit(X_train, y_train,categorical_feature = 'auto',eval_set=(X_test, y_test),feature_name='auto', verbose=0, early_stopping_rounds=100)\n\n    preds = lgbmc_adj.predict(X_test)\n    pred_labels = np.rint(preds)\n    accuracy = accuracy_score(y_test, pred_labels)\n    return accuracy\n\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=100)\n\n    print(\"Number of finished trials: {}\".format(len(study.trials)))\n\n    print(\"Best trial:\")\n    trial = study.best_trial\n\n    print(\"  Value: {}\".format(trial.value))\n\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\n\"\"\"\nWith parameters provided by **OPTUNA**, our accuracy score is almost 0.96.\n\"\"\"\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv('..\/input\/customer-churn-prediction-2020\/train.csv')\ndf1 = df.copy()\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\n\nX= df1.drop('churn', axis=1)\ny= df1['churn']\n\n#if you want a variable to be perecived as categorical then you need to covert it to object type\nfor col in X.columns:\n    col_type = X[col].dtype\n    if col_type == 'object' or col_type.name == 'category':\n        X[col] = X[col].astype('category')\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nlgbmc_5=lgb.LGBMClassifier(random_state=0,scale_pos_weight=5,\n                           num_leaves=724,\n                           max_depth=9,\n                           lambda_l1=8.142384644362947e-06,\n                           lambda_l2=3.432798202818561e-08,\n                           feature_fraction=0.5164384666114301,\n                           bagging_fraction=0.7323707200247135,\n                           bagging_freq=5,\n                           min_child_samples=5)\n\n#y_train,categorical_feature = 'auto' takes all categoricals automatically\nlgbmc_5.fit(X_train, y_train,categorical_feature = 'auto',eval_set=(X_test, y_test),feature_name='auto', verbose=0, early_stopping_rounds=100)\n\ny_pred = lgbmc_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['LightGBM_adjusted_weight_5_optuna']\nresult_df4 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df4\n\"\"\"\nWith **OPTUNA** parameters in **LightGBM**, our accuracy score did not change much. \n\"\"\"\n\"\"\"\n## XGBoost\n\"\"\"\n\"\"\"\n![image.png](attachment:775354cf-ce1c-47d3-9e91-5a24c8013cba.png)\n\"\"\"\n\"\"\"\n### XGBoost - scale_pos_weight = 5\n\"\"\"\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv(\"..\/input\/customer-churn-prediction-2020\/train.csv\")\ndf1 = df.copy()\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\n#Since XGBoost does not handle categorical values itself, we use get_dummies to convert categorical variables into numeric variables.\ndf1= pd.get_dummies(df1)\nX= df1.drop('churn', axis=1)\ny= df1['churn']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nxgbc_5 = XGBClassifier(random_state=0)\n\nxgbc_5.fit(X_train, y_train)\ny_pred = xgbc_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['XGBoost_adjusted_weight_5']\nresult_df5 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df5\n\"\"\"\nWith defualt parameters, we got 0.95 as accuracy score.\n\"\"\"\n\"\"\"\n### OPTUNA - Hyperparameter Tunning\n\"\"\"\nimport numpy as np\nimport optuna\n\nimport sklearn.datasets\nimport sklearn.metrics\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\n\ndef objective(trial):\n    \n    df = pd.read_csv(\"..\/input\/customer-churn-prediction-2020\/train.csv\")\n    df1 = df.copy()\n    le = LabelEncoder()\n    df1['churn']=le.fit_transform(df1['churn'])\n\n    df1= pd.get_dummies(df1)\n    X= df1.drop('churn', axis=1)\n    y= df1['churn']\n    \n    #(data, target) = sklearn.datasets.load_breast_cancer(return_X_y=True)\n    train_x, valid_x, train_y, valid_y = train_test_split(X, y, test_size=0.25)\n    dtrain = xgb.DMatrix(train_x, label=train_y)\n    dvalid = xgb.DMatrix(valid_x, label=valid_y)\n\n    param = {\n        \"verbosity\": 0,\n        \"objective\": \"binary:logistic\",\n        # use exact for small dataset.\n        \"tree_method\": \"exact\",\n        # defines booster, gblinear for linear functions.\n        \"booster\": trial.suggest_categorical(\"booster\", [\"gbtree\", \"gblinear\", \"dart\"]),\n        # L2 regularization weight.\n        \"lambda\": trial.suggest_float(\"lambda\", 1e-8, 1.0, log=True),\n        # L1 regularization weight.\n        \"alpha\": trial.suggest_float(\"alpha\", 1e-8, 1.0, log=True),\n        # sampling ratio for training data.\n        \"subsample\": trial.suggest_float(\"subsample\", 0.2, 1.0),\n        # sampling according to each tree.\n        \"colsample_bytree\": trial.suggest_float(\"colsample_bytree\", 0.2, 1.0),\n    }\n\n    if param[\"booster\"] in [\"gbtree\", \"dart\"]:\n        # maximum depth of the tree, signifies complexity of the tree.\n        param[\"max_depth\"] = trial.suggest_int(\"max_depth\", 3, 9, step=2)\n        # minimum child weight, larger the term more conservative the tree.\n        param[\"min_child_weight\"] = trial.suggest_int(\"min_child_weight\", 2, 10)\n        param[\"eta\"] = trial.suggest_float(\"eta\", 1e-8, 1.0, log=True)\n        # defines how selective algorithm is.\n        param[\"gamma\"] = trial.suggest_float(\"gamma\", 1e-8, 1.0, log=True)\n        param[\"grow_policy\"] = trial.suggest_categorical(\"grow_policy\", [\"depthwise\", \"lossguide\"])\n\n    if param[\"booster\"] == \"dart\":\n        param[\"sample_type\"] = trial.suggest_categorical(\"sample_type\", [\"uniform\", \"weighted\"])\n        param[\"normalize_type\"] = trial.suggest_categorical(\"normalize_type\", [\"tree\", \"forest\"])\n        param[\"rate_drop\"] = trial.suggest_float(\"rate_drop\", 1e-8, 1.0, log=True)\n        param[\"skip_drop\"] = trial.suggest_float(\"skip_drop\", 1e-8, 1.0, log=True)\n\n    bst = xgb.train(param, dtrain)\n    preds = bst.predict(dvalid)\n    pred_labels = np.rint(preds)\n    accuracy = sklearn.metrics.accuracy_score(valid_y, pred_labels)\n    return accuracy\n\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=100, timeout=600)\n\n    print(\"Number of finished trials: \", len(study.trials))\n    print(\"Best trial:\")\n    trial = study.best_trial\n\n    print(\"  Value: {}\".format(trial.value))\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\n\"\"\"\n**OPTUNA** parameters give us a higher Accuracy score (0.96)\n\"\"\"\nfrom  xgboost import XGBClassifier\naccuracy= []\nrecall =[]\nroc_auc= []\nprecision = []\n\n\ndf = pd.read_csv(\"..\/input\/customer-churn-prediction-2020\/train.csv\")\ndf1 = df.copy()\nle = LabelEncoder()\ndf1['churn']=le.fit_transform(df1['churn'])\n\ndf1= pd.get_dummies(df1)\nX= df1.drop('churn', axis=1)\ny= df1['churn']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nxgbc_5 = XGBClassifier(random_state=0,\n     booster=\"gbtree\",\n     lambda_=1.0747585763388536e-08,\n     alpha=4.888494937862174e-05,\n     subsample=0.9424632124541714,\n     colsample_bytree=0.9950004607929119,\n     max_depth=9,\n     min_child_weight=3,\n     eta=0.053153334432134325,\n     gamma=0.0017328227799719943,\n     grow_policy=\"lossguide\")\n\nxgbc_5.fit(X_train, y_train)\ny_pred = xgbc_5.predict(X_test)\n\naccuracy.append(round(accuracy_score(y_test, y_pred),4))\nrecall.append(round(recall_score(y_test, y_pred),4))\nroc_auc.append(round(roc_auc_score(y_test, y_pred),4))\nprecision.append(round(precision_score(y_test, y_pred),4))\n\nmodel_names = ['XGBoost_adjusted_weight_5_optuna']\nresult_df6 = pd.DataFrame({'Accuracy':accuracy,'Recall':recall, 'Roc_Auc':roc_auc, 'Precision':precision}, index=model_names)\nresult_df6\n\"\"\"\nAfter applying **OPTUNA** parameters to our **XGBoost** model, we get silightly higher score than the one with default parameters.\n\"\"\"\n\"\"\"\n# Model Comparion\n\"\"\"\nresult_final= pd.concat([result_df1,result_df2,result_df3,result_df4,result_df5,result_df6],axis=0)\nresult_final\nresult_final.sort_values(by=['Accuracy'], ascending=True,inplace=True)\nfig = px.bar(result_final, x='Accuracy', y=result_final.index,title='Model Comparison',height=600,labels={'index':'MODELS'})\nfig.show()\n\"\"\"\n# Conclusion\n\"\"\"\n\"\"\"\n- We have developed model to classifiy churn cases.\n\n- First, we made the detailed exploratory analysis.\n\n- We have decided which metric to use (**Accuracy** - since the author of the dataset required so).\n\n- We looked in detail **Catboost**, **LightGBM**, and **XGBoost** models.\n\n- We made hyperparameter tuning of for each model with **OPTUNA** to see the improvement.\n\"\"\"\n\"\"\"\n![image.png](attachment:54868641-bc9b-4d60-9e7f-a283c4f130f0.png)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8c269f1e0a05fc'}"}
{"id":"80991","text":"# 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 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\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ndf=pd.read_csv('\/kaggle\/input\/sms-spam-collection-dataset\/spam.csv',encoding='iso-8859-1')\n\ndf\ndf=df.iloc[:,0:2].values\ndf=pd.DataFrame(df)\ndf.columns=['type','text']\ndf\ny=df['type']\nx=df['text']\nfrom sklearn.preprocessing import LabelEncoder\nleb = LabelEncoder()\ny=leb.fit_transform(y) \n\ny\nx\n# library to clean data \nimport re  \nimport nltk  \nnltk.download('stopwords') \nfrom nltk.corpus import stopwords \n# Stemming\nfrom nltk.stem.porter import PorterStemmer \ncorpus = []  \n  \nfor i in range(0, 5572):  \n      \n    review = re.sub(r'\\b[\\w\\-.]+?@\\w+?\\.\\w{2,4}\\b', 'emailaddr', df['text'][i])\n    review  = re.sub(r'(http[s]?\\S+)|(\\w+\\.[A-Za-z]{2,4}\\S*)', 'httpaddr',\n                     review)\n    review  = re.sub(r'\u00a3|\\$', 'moneysymb', review)\n    review = re.sub(\n        r'\\b(\\+\\d{1,2}\\s)?\\d?[\\-(.]?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}\\b',\n        'phonenumbr', review)\n    review  = re.sub(r'\\d+(\\.\\d+)?', 'numbr', review)\n\n    # collapse whitespace (spaces, line breaks, tabs) into a single space.\n    # eliminate any leading or trailing whitespace.\n    review  = re.sub(r'[^\\w\\d\\s]', ' ', review)\n    review = re.sub(r'\\s+', ' ', review)\n    review = re.sub(r'^\\s+|\\s+?$', '', review)\n\n    review = review.lower()  \n    review = review.split()  \n    ps = PorterStemmer()   \n    review = [ps.stem(word) for word in review \n                if not word in set(stopwords.words('english'))]  \n    review = ' '.join(review)   \n    corpus.append(review)  \n# to extract useful ngrams and create bag of words\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n# to create bag of words model\nvectorizer = TfidfVectorizer(ngram_range=(1, 2))\nX_ngrams = vectorizer.fit_transform(corpus)\nX_ngrams.shape\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn import svm\n\nX_train, X_test, y_train, y_test = train_test_split( X_ngrams,y,test_size=0.3)\n\nclf = svm.LinearSVC(loss='hinge',random_state=0)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nmetrics.f1_score(y_test, y_pred)\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\ncm\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nprecision,recall,thresholds=precision_recall_curve(y_test,y_pred)\nauc_recall_pre=auc(recall,precision)\nauc_recall_pre\nfrom sklearn.metrics import roc_curve\nfalse_positive,true_positive,_=roc_curve(y_test,y_pred)\nplt.plot(false_positive,true_positive,label='Linear SVM')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC_curve')\nplt.legend()\nplt.show()\n# Using Artificial Neural Network\n\"\"\"\n## ANN\n\"\"\"\nimport tensorflow as tf\nann = tf.keras.models.Sequential()\n\n# Adding the input layer and the first hidden layer\nann.add(tf.keras.layers.Dense(units=10000, kernel_initializer='normal',activation='relu',input_dim=36228))\n\n# Adding the second hidden layer\nann.add(tf.keras.layers.Dense(units=5000,kernel_initializer='normal', activation='relu'))\n\n# Adding the second hidden layer\nann.add(tf.keras.layers.Dense(units=1000,kernel_initializer='normal', activation='relu'))\n\n# Adding the output layer\nann.add(tf.keras.layers.Dense(units=1, kernel_initializer='normal',activation='sigmoid'))\n# compiling model\nann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\nann.summary()\n\nann.fit(X_train.todense(), y_train, validation_split=0.15,batch_size = 300, epochs = 15)\ny_pred=ann.predict(X_test.todense())\ny_pred\ny_pred = (y_pred > 0.5)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\nfrom sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)","meta":"{'source': 'AI4Code', 'id': '94b1d227830811'}"}
{"id":"23053","text":"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\nimport sklearn.metrics as metrics\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\n\n\n\n\n\"\"\"\n**Explore the Data**\n\"\"\"\n\"\"\"\nTo read the required csv file\n\"\"\"\ndiabete=pd.read_csv('\/kaggle\/input\/pima-indians-diabetes-database\/diabetes.csv')\ndiabete.head()\ndiabete.tail()\n\"\"\"\nThere are 767 rows in the dataset\n\"\"\"\ndiabete.describe()\ndiabete.info()\ndiabete.isna().sum()\n\nprint(\"Dataset shape is\", diabete.shape)\n\"\"\"\n**Visualization of the dataset**\n\"\"\"\nsns.pairplot(diabete)\n\"\"\"\n**Finding the correlation**\n\"\"\"\ndiabe_corr=diabete.corr()\nsns.heatmap(diabe_corr)\n#Replace the zeros\nfeature_col=['Pregnancies','Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']\nfor column in feature_col:\n    diabete[column]=diabete[column].replace(0,np.NaN)\n    mean=diabete[column].mean(skipna=True)\n    diabete[column]=diabete[column].replace(np.NaN,mean)  \n\"\"\"\n**Spliting the dataset**\n\"\"\"\nx=diabete[feature_col]\ny=diabete[['Outcome']]\n#spliting the dataset into train and test\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.2,random_state=0 )\n#feature scaling\nscalar=StandardScaler()\nx_train=scalar.fit_transform(x_train)\nx_test=scalar.transform(x_test) \n\"\"\"\n**Define the model : init K-NN**\n\"\"\"\nclf=KNeighborsClassifier(n_neighbors=11,p=2,metric='euclidean')\nclf.fit(x_train,y_train)\ny_predict=clf.predict(x_test)\n\n\"\"\"\n**Evaluate the model**\n\"\"\"\n\nprint(confusion_matrix(y_test,y_predict))\n\n\nprint(f1_score(y_test,y_predict))\nprint(accuracy_score(y_test,y_predict))\n#Function to perform training with entropy\nclf=DecisionTreeClassifier(criterion='entropy',max_depth=3,random_state=100,min_samples_split=4)\nclf.fit(x_train,y_train)\ny_predict=clf.predict(x_test)\ny_predict\n#Checking the accuracy\nprint(\"the accuracy is\",metrics.accuracy_score(y_predict,y_test))\nfrom sklearn import tree\nplt.figure(figsize=(16,7),dpi=200)\ntree.plot_tree(clf,feature_names=feature_col,class_names=[\"0\",\"1\"],filled=True,rounded=True);","meta":"{'source': 'AI4Code', 'id': '2a619add29a97b'}"}
{"id":"116730","text":"\"\"\"\n# **Set Up**\n\"\"\"\n\"\"\"\nHandle imports and initialize a few directory paths\n\"\"\"\n# 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)\nimport os,cv2,keras\nimport json\nimport math\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.applications import ResNet50#, preprocess_input\nimport numpy as np\nimport tensorflow as tf\nimport keras.layers as KL\nimport keras.backend as K\nfrom keras.utils import Sequence\nimport time\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\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\n\n#Set random seeds\nseed = 232\nnp.random.seed(seed)\n#tf.set_random_seed(seed)\n\n#set image inputs\ndataset_path = '\/kaggle\/input\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/'\ntrainingImageDirPath = '\/kaggle\/input\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/train_images\/'\ntrainingAnnotationsPath = '\/kaggle\/input\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/train_annotations.json'\ntestingImageDirPath = '\/kaggle\/input\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/vinbigdata-coco-dataset-with-wbf-3x-downscaled\/val_images\/'\n#trainingAnnotationsPath = '\/kaggle\/input\/vinbigdata-chest-xray-abnormalities-detection\/train.csv'\n\n\"\"\"\n**Demo**\n\nCheck out some xrays\n\"\"\"\n#Plot some examples\nfig, ax = plt.subplots(2, 1, figsize=(15, 7))\nax = ax.ravel()\nplt.tight_layout()\n\nfor i, _set in enumerate(['train_images\/', 'val_images\/']):\n    set_path = dataset_path+_set\n    ax[i].imshow(plt.imread(set_path+os.listdir(set_path)[0]), cmap='gray')\n    ax[i].set_title('Example Image'.format(_set))\n\"\"\"\n**HELPER FUNCTIONS**\n\"\"\"\n\"\"\"\n**Build Constants**\n\nInitialize some constants\n\"\"\"\n#RCNN Constants\n#We will only use square images, what is the n in nxn?\nN_REGION_IMG_SIZE = 120\nN_RPN_TRAIN_IMAGE_SIZE = 227\nN_INPUT_CHANNELS = 3\n\nRPN_INPUT_SHAPE = (N_RPN_TRAIN_IMAGE_SIZE, N_RPN_TRAIN_IMAGE_SIZE, N_INPUT_CHANNELS)\nANCHOR_STRIDE = 2\nANCHOR_SCALES = (32, 64, 128, 256, 512)\nANCHORS_PER_LOCATION = len(ANCHOR_SCALES)^2\n#TRAIN_ANCHORS_PER_IMAGE = 36\nRPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])\nN_FEATURE_MAP_SIZE = 13\nANCHOR_IOU_FG_THRESHOLD = 0.5\nANCHOR_IOU_BG_THRESHOLD = 0.1\n#How many anchors we should validate and find loss with?\nTRAINING_SET_SIZE = 10\n\n\n#This constant must be hand written to match the AlexNet\nFEATURE_MAP_SHAPE = (1, 13, 13, 256)\n\n\nLEARNING_RATE = 0.001\nLEARNING_MOMENTUM = 0.9\nBATCH_SIZE = 8\nEPOCHS = 10\n\"\"\"\n**Compute IOU Data**\n\nCompute the IOU data of two rectangles. The IOU of two rectangles is the ratio of how much of the rectangles overlap to the amount that the rectangles don't overlap, measured in 2-D area.\n\"\"\"\ndef computeIouList(rect1, rect2List):\n    rect1area= (rect1[2] - rect1[0]) * (rect1[3] - rect1[1])\n    rect2area = (rect2List[:, 2] - rect2List[:, 0]) * (rect2List[:, 3] - rect2List[:, 1]) # area = width * height\n    \n    #Get X, y coordinates of intersecting rectangle\n    xMin = np.maximum(rect1[0], rect2List[:, 0])\n    yMin = np.maximum(rect1[1], rect2List[:, 1])\n    xMax = np.minimum(rect1[2], rect2List[:, 2])\n    yMax = np.minimum(rect1[3], rect2List[:, 3])\n    \n    #get area of intersecting rectangle\n    intersection = np.maximum(0, xMax - xMin + 1) * np.maximum(0, yMax - yMin + 1)\n    union = rect1area + rect2area[:] - intersection[:]\n    iou = intersection \/ union\n    \n    return iou\n\"\"\"\n**Get Images From Rect Data**\n\nIt is important that all of our regions are squares, so that they are compatible with the neural network that we build. For this reason we must resize all the images we pull in by a constant value.\n\"\"\"\n#Perform Preprocessing on Rect Proposals\ndef GetRectImageData(rects, image):\n    props = []\n    \n    (x, y, x2, y2) = rects\n    (x, y, x2, y2) = (int(x), int(y), int(x2), int(y2))\n        \n    #extract rect from image\n    rect = image[y:x2, x:y2]\n    #convert color\n    RGBrect = cv2.cvtColor(rect, cv2.COLOR_BGR2RGB)\n    #Resize rects to NxN\n    squareRect = cv2.resize(RGBrect, (N_REGION_RPN_TRAIN_IMAGE_SIZE, N_REGION_RPN_TRAIN_IMAGE_SIZE))\n        \n    return squareRect\n        \n\"\"\"\n**Generate Anchors**\n\nGiven a feature map, we want to generate some anchors. We will use the constants for image size and anchor stride for this calculation. The challenge is that we are trying to generate evenly spaced anchor points in a full size image using a feature map. Most of this function consists of generating every possible combination of box shape and size, then spacing them out evenly throughout the possible range of values in the image.\n\"\"\"\ndef GetAnchors(featureMapNSide):\n    featureStrides = int(N_RPN_TRAIN_IMAGE_SIZE\/featureMapNSide) # 512\/13 ~= 39\n\n    # All combinations of anchor points\n    #ex: Range from 0 to 13 with a stride of 1\n    # (0,2,3,6,...10,12) * 39 = (0, 39, 78, 117 ... 507)\n    start = int(ANCHOR_STRIDE\/2)\n    end = int(N_RPN_TRAIN_IMAGE_SIZE - start* featureStrides)\n    print(end)\n    \n    x = np.arange(start*featureStrides, end, ANCHOR_STRIDE * featureStrides)\n    y = np.arange(start*featureStrides, end, ANCHOR_STRIDE * featureStrides)\n    x, y = np.meshgrid(x, y)  #shapes: 39x39\n    \n    #print(x)\n    #print(x[0][5])\n\n    # All combinations of indices, and shapes\n    anchorBBoxes = []\n    scale = len(x)\n    for idy in range(scale):\n        for idx in range(scale):\n            for width in ANCHOR_SCALES:\n                for height in ANCHOR_SCALES:\n                    BBox = (x[idy][idx] - width\/2, y[idy][idx] - height\/2, x[idy][idx] + width\/2, y[idy][idx] + height\/2)\n                    anchorBBoxes.append(BBox)\n\n    # Anchors are created for each feature map\n    #print('Num of generated anchors:\\t',len(anchorBBoxes))\n    anchors = np.reshape(anchorBBoxes, (scale, scale, len(ANCHOR_SCALES), len(ANCHOR_SCALES), 4))\n    return anchors\n\"\"\"\n**Calculate Anchor Ground Truth Data**\n\nWe need to get the indicies, the deltas of the boxes, and the labels for the ground truth data. Many things happen in this function. The first thing that happens is that we load the deltas for the boxes from the ground truth, then we find the IOUs of the boxes from the ground truth. If the IOU is above a certain amount, we label that anchor as foreground, and save it to an array which will get sent to the neural network.\n\"\"\"\n\n#Make sure BBoxes is a np.array before adding\n#This won't be implemented with batching\ndef CalculateDeltasAndLabels(BBoxes, anchors):  \n    #Get anchors in 1-d Array\n    linearAnchors = np.ndarray.flatten(anchors)\n    anchorCount = (anchors.shape[0] * anchors.shape[1] * anchors.shape[2] * anchors.shape[3])\n    boxCount = len(BBoxes)\n    \n    fgAnchors = []\n    bgAnchors = []\n    \n    deltasOut = np.zeros((anchorCount, 4))\n    bboxIous = np.zeros((boxCount,anchorCount)) #Intersection over union score for each bbox-anchor pair\n    bboxDeltas = np.zeros((boxCount,anchorCount, 4)) #desired delta x,y,h,w for each bbox-anchor pair --> RPN shoult predict these\n    \n    #For each box, calculate the boxes, distance from each anchor\n    for bboxnum, bbox in enumerate(BBoxes):\n        #Calculate Bounding Box Deltas\n        AnchorsArray = np.reshape(anchors, (anchorCount,4))\n        aw = AnchorsArray[:,2] - AnchorsArray[:,0]\n        ah = AnchorsArray[:,3] - AnchorsArray[:,1]\n        acx = AnchorsArray[:,0] + aw[:]\/2\n        acy = AnchorsArray[:,1] + ah[:]\/2\n        \n        (bbw, bbh) = (bbox[2] - bbox[0], bbox[3] - bbox[1])\n        (bcx, bcy) = (bbox[0] + bbw\/2, bbox[1] - bbh\/2)\n        \n        deltasGroup = (bbw - aw[:], bbh - ah[:], bcx - acx[:], bcy - acy[:])\n        \n        bboxDeltas[bboxnum] = list(zip(*deltasGroup))\n        #Calculate IOU\n        bboxIous[bboxnum] = computeIouList(bbox, AnchorsArray)\n\n    #For each anchor, find the nearest BBox and the IOU\n    for anchor in range(anchorCount):\n        bestBboxix = np.argmax(bboxIous[:,anchor])\n        deltasOut[anchor] = bboxDeltas[bestBboxix, anchor]  \n        iou = bboxIous[bestBboxix, anchor]\n        \n        if iou > ANCHOR_IOU_FG_THRESHOLD:\n            fgAnchors.append([0,anchor])\n            \n        elif iou < ANCHOR_IOU_BG_THRESHOLD:\n            bgAnchors.append([0,anchor])\n            \n    if fgAnchors == []:\n        fgAnchors = np.array([[-1,-1]])\n    if bgAnchors == []:\n        bgAnchors = np.array([[-1,-1]])\n    \n    return  np.array(fgAnchors), np.array(bgAnchors), deltasOut\n\"\"\"\n# **TRAIN THE NETWORK**\n\"\"\"\n\"\"\"\n***Data Pre-processing***\n\nWe want to load the imageURLS and bounding boxe data for every photo in the directory. We can do this because it won't take too much memory but we should not load any images except in a fit generator for the model.\n\"\"\"\n#load images into Local memory\ntrainingImagePaths = os.listdir(trainingImageDirPath)\n\nindex = 0\nimgDirSize = len(trainingImagePaths)\n\nannotationsFile = open(trainingAnnotationsPath)\ntrainingMetadata = json.load(annotationsFile)\n\ndataCollection = []\nfor imgPath in trainingImagePaths:\n    matchedImageMetadata = None\n    \n    #GET IMAGE METADATA\n    for imageMetadata in trainingMetadata['images']:\n        if imageMetadata['file_name'] == str(\"train_images\/\" + imgPath):\n            matchedImageMetadata = imageMetadata\n            break\n    \n    #GET ANNOTATIONS FOR IMAGE\n    BBoxesDims = []\n    for annotationsData in trainingMetadata['annotations']:\n        if (annotationsData['image_id'] != matchedImageMetadata['id']):\n            continue\n            \n        bboxDims = annotationsData[\"bbox\"]\n        bboxDims[2] = bboxDims[0] +  bboxDims[2]\n        bboxDims[3] = bboxDims[1] +  bboxDims[3]\n        BBoxesDims.append(bboxDims)\n        \n    dataCollection.append({\"imgPath\":imgPath,\"bboxesDims\":BBoxesDims})#\"img\": img,\"bboxesDims\": BBoxesDims})\n    \n    if (math.remainder(index,250) == 0):\n        print(\"Progress: \" + str(index) + \" out of \" + str(imgDirSize) + \" images processed\")\n    index += 1\n\nprint(\"Done Loading\")\n#loop over images\n\"\"\"\n***Feature Map Extractor***\n\nWe use the first 5 layers of an Alex Net to extract a feature map from the input data. \n\"\"\"\ndef RunPartialAlexNet(inputTensor):\n    x = KL.ZeroPadding2D((3, 3))(inputTensor)\n    y = KL.Conv2D(filters=96, kernel_size=(11,11), strides=(4,4), activation='relu', input_shape=RPN_INPUT_SHAPE)(x)\n    y = KL.BatchNormalization()(y)\n    y = KL.MaxPool2D(pool_size=(3,3), strides=(2,2))(y)\n    L1 = y#KL.UpSampling2D(size=(2,2))(y)\n    y = KL.Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), activation='relu', padding=\"same\")(L1)\n    y = KL.BatchNormalization()(y)\n    y = KL.MaxPool2D(pool_size=(3,3), strides=(2,2))(y)\n    L2 = y#KL.UpSampling2D(size=(2,2))(y)\n    y = KL.Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), activation='relu', padding=\"same\")(L2)\n    y = KL.BatchNormalization()(y)\n    L3 = y#KL.UpSampling2D(size=(2,2))(y)\n    y = KL.Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), activation='relu', padding=\"same\")(L3)\n    y = KL.BatchNormalization()(y)\n    L4 = y#KL.UpSampling2D(size=(2,2))(y)\n    y = KL.Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), activation='relu', padding=\"same\", name=\"LastLayer\")(L4)\n    L5 = y#KL.UpSampling2D(size=(3,3))(y)\n    \n    return [L1, L2, L3, L4, L5]\n\n\"\"\"\n***Build Data Generator***\n\"\"\"\n\"\"\"\nDo to the massive size of the data, we had to use a tensorflow input generator. This allows us to avoid loading all of the images into memory at the same time. The __getitem__ function is called once for each image, with a total of __len__ times. At that time we calculate the ground truth data, get the feature map, and build this data as inputs to send to the network.\n\"\"\"\n#FeatureMapSize is actually programmatic but it's found after the point where we need\nclass RPNInputGenerator(Sequence):\n    def __init__(self, DataCollection, mode = 'train'):\n        self.DataCollection = DataCollection\n        self.anchors = None\n        self.mode = mode\n        \n    def __len__(self):\n        return int(len(self.DataCollection))\n        \n    def __getitem__(self, idx):\n        idxData = self.DataCollection[idx]\n            \n        img = cv2.imread(trainingImageDirPath + '\/' + idxData[\"imgPath\"])\n        (H,W,_) = img.shape\n\n        featureMap = self.GetFeatureMap(img)\n        \n        if (self.mode == 'train'):\n            BBoxes = idxData[\"bboxesDims\"]\n            BBoxesConverted = self.ConvertBoundingBoxes(BBoxes, H, W)\n        \n            if (self.anchors is None):\n                FeatureMapShape = featureMap.shape[1]\n                self.anchors = GetAnchors(FeatureMapShape)\n            \n            fgAnchors, bgAnchors, gtDeltas = CalculateDeltasAndLabels(BBoxesConverted, self.anchors)\n        \n            inputs = [featureMap, fgAnchors, bgAnchors, gtDeltas]\n        else:\n            inputs = [featureMap]\n        \n        return inputs\n\n    def GetFeatureMap(self, img):\n        RGBimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        #Resize rects to 227\n        resizedImg = cv2.resize(RGBimg, (N_RPN_TRAIN_IMAGE_SIZE, N_RPN_TRAIN_IMAGE_SIZE))\n                            \n        input = resizedImg.reshape((1,) + resizedImg.shape)\n        \n        tfInput = tf.constant(input, dtype=tf.float32)\n        \n        #Get feature map\n        [_,_,_,_,featureMap] = RunPartialAlexNet(tfInput)\n        \n        return featureMap\n    \n    def ConvertBoundingBoxes(self, BoundingBoxes, H, W):\n        HRatio = (N_RPN_TRAIN_IMAGE_SIZE\/H)\n        WRatio = (N_RPN_TRAIN_IMAGE_SIZE\/W)\n        \n        newBoxes = []\n        for Bbox in BoundingBoxes:\n            xn = int(np.multiply(Bbox[0], WRatio))\n            yn = int(np.multiply(Bbox[1], HRatio))\n            xm = int(np.multiply(Bbox[2], WRatio))\n            ym = int(np.multiply(Bbox[3], HRatio))\n            \n            newBox = (xn, yn, xm, ym)\n            \n            newBoxes.append(newBox)\n            \n        return np.array(newBoxes)\n\"\"\"\n***Build RPN***\n\"\"\"\n\"\"\"\nIn this section we build the RPN. An RPN (Region proposal network) is a network which is trained to identify regions in an image where it is likely that objects will exist. The core of the RPN is a CNN which is given a feature map and gives out 2 sets of outputs: foreground or background labels, and bounding box deltas.\n\nTo understand what bounding box deltas represent, refer to the previous section on anchor points. To reiterate, anchor points are spread throughout the image and multiple bounding boxes are drawn with the anchor point in the center. The bounding box deltas then represent the predicted difference between anchor point box and the actual regions.\n\nThe labels are a binary classification of whether or not the network perceives the items to be abnormalities in the image.\n\"\"\"\n\"\"\"\n*RPN Loss Function*\n\nThe loss function is the main focus of our RPN. This function is actually a combination of two loss functions at once, one which calculates the categorical crossentropy of the labels, and one which calculates the smooth l1 loss of the box deltas. Essentially, we calculate these values by comparing the values of each anchor.\n\nThere are some manipulations we have to do in order to get the data to work though. For example, since we do not care about calculating the delta loss for incorrect labels so we only use anchors indicated as foreground. There is also one special case. If there are no anchors identified as foreground in the image, either because there wasn't an accurate enough anchor box proposal, or because there does not exist any abnormalities in the image, we instead use the background anchors for label loss and assume the delta loss is 0.\n\n\"\"\"\ndef smoothL1(yK,yP):\n    x = tf.abs(yK-yP)\n    mask = tf.cast(tf.less(x,1.0), \"float32\")\n\n    # Loss calculation for smooth l1\n    loss = (mask * (0.5 * x ** 2)) + (1 - mask) * (x - 0.5)\n    return loss\n\n@tf.function\ndef rpnLoss(rpnLogits, rpnDeltas, gtDeltas, fgAnchors, bgAnchors):\n    #Get Predicted Labels of anchors meant to be foreground\n    #If there are no fg anchors, we can use bg anchors to get loss\n    anchorsToUse = fgAnchors\n    if (tf.reduce_all(tf.equal(fgAnchors\n                               ,tf.constant([[-1,-1]])))):\n        anchorsToUse = bgAnchors\n    \n    selPredictedLabels = tf.gather_nd(rpnLogits, anchorsToUse, name=\"GetPredictedLabels\")\n    onepy = np.ones(1000)\n    gtLabels = tf.gather(onepy, anchorsToUse[:,1], name=\"GetGTLabels\")\n    \n    #Compare labels\n    lf = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n    classLoss = lf(gtLabels, selPredictedLabels)\n    classLoss = tf.reduce_mean(classLoss)\n    \n    #If there are no fg anchors, deltas loss is 0, we cannot use bg anchors for delta loss\n    if (not tf.reduce_all(tf.equal(fgAnchors\n                               ,tf.constant([[-1,-1]])))):\n        selRpnDeltas = tf.cast(tf.gather_nd(rpnDeltas, fgAnchors, name=\"selRpnDeltas\"),tf.float32)\n        selGtDeltas = tf.cast(tf.gather(gtDeltas, fgAnchors[:,1], name=\"selGtDeltas\"), tf.float32)\n        \n        #Compare the deltas\n        deltaLoss = smoothL1(selGtDeltas, selRpnDeltas)\n        deltaLoss = tf.reduce_mean(deltaLoss)\n    else:\n        #deltaLoss = smoothL1(selRpnDeltas, selRpnDeltas)\n        deltaLoss = tf.constant(0.0)\n    \n    return classLoss, deltaLoss\n\"\"\"\n*Function to Build RPN Model*\n\nThe core CNN which makes up the RPN is a simple CNN with 3 significant layers. The input is in the form a feature map, derived from passing the resized, original image into the first 5 layers of an AlexNet. The first layer is a convolution on the input which morphs the channels to 512. Then there are two other layers, a classification layer with a depth of two multiplied by the amount of anchor boxes at each anchor point. The two represents the binary classification. The final layer has a depth of four multiplied by the amount of anchor boxes at each point. Here, the four represents the movement of the top left corner of the bounding box, expressed in (x,y) coordinates, and movement of the center of the bounding box, expressed in (x,y) coordinates.\n\"\"\"\ndef BaseRPN(featureMap):\n    initializer = tf.keras.initializers.GlorotNormal(seed = None)\n    input_ = tf.keras.layers.Input(shape=featureMap.shape, name=\"rpn_INPUT\")\n\n    #Shared base convolution for all methods\n    shared = tf.keras.layers.Conv2D(512, (3,3), padding='same', activation='relu'\n                    , strides=1, name='rpnSharedConvolution',kernel_initializer=initializer)(input_)\n    \n    #CLS LAYER\n    #Generate Anchor classification [batch, height, width, ANCHORS_PER_LOCATION * w]\n    x = tf.keras.layers.Conv2D(2*ANCHORS_PER_LOCATION, (1, 1), padding='valid'\n                    , activation='linear',name='rpnClassification',kernel_initializer=initializer)(shared) \n    \n    #Reshape to [batch, anchors, 2]\n    rpnClassLogits = tf.keras.layers.Lambda(lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 2]))(x)\n    #Softmax on last dimension\n    rpnProbs = tf.keras.layers.Activation(\"softmax\", name=\"rpn_class_xxx\")(rpnClassLogits) # --> BG\/FG\n    \n    #REG LAYER\n    # Bounding box refinement. [batch, H, W, anchors per location * depth]\n    #Depth is [x,y, log(w) log(h)]\n    #Also generate 4 delta coordinates\n    x = tf.keras.layers.Conv2D(ANCHORS_PER_LOCATION*4, (1, 1), padding=\"valid\", activation='linear', name='rpnPredictBoundingBoxes',kernel_initializer=initializer)(shared) \n    # Reshape to [batch, anchors, 4]\n    rpnBBox = tf.keras.layers.Lambda(lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 4]))(x)\n    \n    outputs = [rpnClassLogits, rpnProbs, rpnBBox]\n    rpnModel = tf.keras.models.Model([input_], outputs, name=\"RPNModel\")\n\n    return rpnModel\n\n#Build RPN model, handling a single feature map per img\ndef buildRPNModel(mode='train'):\n        rpnInput = KL.Input(shape=FEATURE_MAP_SHAPE, name=\"FeatureMap\")\n        \n        rpNetwork = BaseRPN(rpnInput)\n        \n        rpnOutputs = rpNetwork(rpnInput)\n        \n        rpnLogits, rpnProbs, rpnDeltas = rpnOutputs\n\n        fgAnchors = KL.Input(shape=[None,2], name=\"fgAnchors\", dtype=tf.int32)\n        bgAnchors = KL.Input(shape=[None,2], name=\"bgAnchors\", dtype=tf.int32)\n        gtDeltas = KL.Input(shape=[None, 4], name=\"gtDeltas\", dtype=tf.float32)\n        \n        classLoss, deltaLoss = KL.Lambda(lambda x: rpnLoss(*x), name=\"rpnLossFn\")(\n                                   [rpnLogits, rpnDeltas, gtDeltas, fgAnchors, bgAnchors])\n                                   \n        # Inputs and outputs of the model\n        if mode == 'train':\n            inputs = [rpnInput, fgAnchors, bgAnchors, gtDeltas]\n            outputs = [rpnLogits, rpnProbs, rpnDeltas, classLoss, deltaLoss]\n        elif mode == 'inference':\n            inputs = [rpnInput]\n            outputs = [rpnProbs, rpnDeltas]\n            \n        return tf.keras.models.Model(inputs, outputs, name=\"RPN\")\n\"\"\"\n*Compile the RPN*\n\nWe use a learning rate of .0001, momentum of 0.9, and clipnorm of 0.5. These values are empirically derived from a Mask RCNN developed by Matterport, Inc in Sunnyvale, CA. Alot of the internal infrastructure of our implementation is actually based off of their work, with major modifications of course to simplify and adapt the implementation to our data set.\n\nWhen compiling, we manually add our loss function as the metrics for the network as well.\n\"\"\"\nOptimizer = tf.keras.optimizers.SGD(learning_rate=0.0001\n                                   , momentum= 0.9,clipnorm=0.5)\n\nRpnNetwork = buildRPNModel('train')\n\nRpnNetwork.summary()\n\nlossLayer = RpnNetwork.get_layer('rpnLossFn')\nlossFn = tf.reduce_mean(lossLayer.output, keepdims=True)\nRpnNetwork.add_loss(lossFn)\n\nRpnNetwork.compile(optimizer=Optimizer, loss=[None] * len(RpnNetwork.outputs))\n\nlossLayer = RpnNetwork.get_layer('rpnLossFn')\nRpnNetwork.metrics.append(lossLayer)\n\n\"\"\"\n*Train The Model*\n\nInitialize the RPN input generator. Send it to the network.\n\"\"\"\nInputs = RPNInputGenerator(dataCollection, 'train')\n\nRpnNetwork.fit_generator(Inputs, len(Inputs), epochs=EPOCHS)\n#dataCollection\n#rn50.fit_generator(Inputs, len(Inputs), epochs=EPOCHS)\ntf.keras.models.save_model(RpnNetwork, '\/kaggle\/working\/saved_models\/TrainedRPN-05-14-1.h5')\n\n\"\"\"\n***PUT CODE HERE TO TRAIN THE CNN***\n\"\"\"\n\"\"\"\n# **Test the Trained Network**\n\"\"\"\n\"\"\"\n**Load Regions**\n\n*Load Trained RPN*\n\"\"\"\n# Load the Model back from file\n#with open(ModelFileName, 'rb') as file:  \n#    RpnNetwork = pickle.load(file)\n    \nRPNTrained = tf.keras.models.load_model('\/kaggle\/working\/saved_models\/TrainedRPN-05-14-1.h5')\n\n\"\"\"\nSimilar to training, load only image paths, but do not load images.\n\"\"\"\n#load images into Local memory\ntestingImagePaths = os.listdir(testingImageDirPath)\n\nindex = 0\nimgDirSize = len(testingImagePaths)\n\ndataCollection = []\nfor imgPath in testingImagePaths:\n    matchedImageMetadata = None\n    \n    dataCollection.append({\"imgPath\":imgPath})\n    \n    if (math.remainder(index,250) == 0):\n        print(\"Progress: \" + str(index) + \" out of \" + str(imgDirSize) + \" images processed\")\n    index += 1\n    \nprint(\"Done Loading\")\n#loop over images\nInputGenerator = RPNInputGenerator(DataCollection, mode = 'inference')\nregions = []\nfor ix in range(InputGenerator.__len__()):\n    input = InputGenerator.__getitem__(ix)\n    Probs, BBoxes = RPNTrained.Predict(input)\n    \n    \n    \nConvertBBoxes->","meta":"{'source': 'AI4Code', 'id': 'd6c2f05dfe7c2a'}"}
{"id":"15996","text":"# 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\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\n\"\"\"\n#**WORLD COVID19 VACCINATION ANALYSIS**\n\"\"\"\n\"\"\"\n![photo.jpg](data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABMNDxEPDBMREBEWFRMXHTAfHRsbHTsqLSMwRj5KSUU+RENNV29eTVJpU0NEYYRiaXN3fX59S12Jkoh5kW96fXj\/2wBDARUWFh0ZHTkfHzl4UERQeHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHj\/wgARCAJEBC0DASIAAhEBAxEB\/8QAGgAAAwEBAQEAAAAAAAAAAAAAAAECAwQFBv\/EABkBAQEBAQEBAAAAAAAAAAAAAAABAgMEBf\/aAAwDAQACEAMQAAAB3G9ySghWiFZWa0RmtBMp2islpMQxHRvh0yyrRnO01itpTOdlXPn05GWkKO3fg6ZeisnG94aGjiinLG04AAAAAAAAAJFzuOmHMveSee94jMneExtOppLqHmaPNy6vNzWrzM3UyDUzS6rNS6mYuryJdr5iXtfPvz0AKAA0I2gYgYAAAgoTSCaEmqUtWLfn6JaBZoBQAIBBNUgQIESCkgM2ObRQklBC0RC0RC0DJazWMbwYxtCa9PP0yhQQrRK0RkaIyy6Jrky68Ez2wcdl8uq9OvPqbVncW5ZTTGJwAAMEMExBxuemJcm8SLDedMEdOYhK2qhsoGKGSS24JrQgNDNzWiglsklsklszJbJcunTx6x1kvGmAAAxCMTBoGgoBAAiTVJCRIVLp5umVgSgAIEAQIKEIEKwQgQCY5sY0RQSUEFolWETojKdZMY2mjox3lY2klkZlqpKDONoOfHqyrlnozM9IcdG2G5rpnoXUUW5qGBDAgAACiKxs5U135XkZ3OJWfXkIV0CJbrOk0rNyXMpqiHnVOHLRLlokWyDOrIctEktOSLcUVedWdO\/F04ugLO2IRuWMBGIpoAAQQqEIJFYS0HRz9GdUgABAQCChCBCQQqE1KAK2yUoaJsEMEqCVSJVzUzckToidZ0HSqAYSrCFckzUVMWjLLpiuY3lFtlqa6Z6S1SZVTUNohiYAgADDfDU5SY78UZHTmoa1CXLSETVOGWS4aRLThy2SynJFEk06zXPWytxmujAHLtpyy3Ds0156Z7nhty6ty5WIShFjEDEIxFCEEtWJAICaN8NpaEIxFgIASGhIIVrQQhqaAJdG3cpjAYAAhoSaFNKpVBJTJsqFQDBiAJmoFFqpdUZrUMJ3lOc1ir1x1l0qLG0RQmMRDEIAh46zqefhsenz462LhltlvERc3UqlNIAdQS2JomE02goUZtTJy3WuWhS1SaPLWOd1GrTh1VQy3Dudeni3xeoh8u1EiWSWUSWUSJSkGkrGhK0E0AZ0a50lCWs0SJSSKSKaRAAoBKASoZLsx6wAwAAASaEmqQwRQIohMYMYhhKcillJtibcJWETojKN4rGhGt52U5Y3LkYgYgaEjSzrLDfl78amDpzWemOgqhoTmaaBUNQ7zZohomss6qJfHpTnUNZNZ1157k9DTy+7G+fn9TDU4Xrhq05dlOXVVm07NOXfh2sgzrQgssgubUCWpLKEKwM0AmhjzUOLKIN4sgqhEMTACVicoBKA5UxmrT3zYAxAJoE0IYJsE2CbCRobTGhQpapMoTbExwhglSJnSayjbOpuGmjh1RIWSJRMF5ytZBLUfN0Tc8yc9eKy1w1prXFXNRNJw5qhOwcuHWeHLekjxtWVZVzOs2Q5dNMN5K216MajQJrHzvUw1ngcnWXWdWUIS9+asdOkyPP6djF3OpkWaOHc24pKaJW04GGaMcph0cmpTh6lOKShMYnDAUacoMgYKA41A6cmIGIAAAAGAwAbhDCZqaYIaEAwGMGOExwhgkypVIiNJrKbzqqzqy0iyiCwTSCJ1AU2W8osrCZ6c5mstavPbJZGTScuFUsMSOW21pmunesynAOKmquu3LHsbxq6ihuOY7M89zzuX1vN65zcmmlZPWdHFJqRXL0oU8eulZ3mXcVc3U0jY4YMGOBgHH2cVo5qqaaNqgY5AGDCUYAMAA1BdOTEDAAGAwBkAwBkACxNxYIKGMGAMcDTgAABUNIk1SmprPPXOoErLarWQFYBIZzh0575Ym8aTK1FFZ63tOd5SkmgTlQnKZ3lz0Orwgp9Jam2XGjxvHp23xouXK6lRq+DuMa25zTbj1Lw6sbPIXXx9s0SW6VlVztWVXGhDx3ulfl9DovAoaFDsGNBgAAcXbxqqVK2UJtoAwY0TAGAAACXUDpxAYAwYAxwmEDAAAAWM9M9QaoKTBjgacAAAKAAmkQFTNTUZ6Z1mF6ywLkc52XnC3nDLbPtygFdMClled3ltlPHpuYUl1mVRFxSfTjOWe\/LTM7aNV1YT0WY6DTgaYuPpzHtmk7UxeWemU1rk65eXzva4t580J6qqKsu8q1jQls67cu\/Lv0XGvl9A28xNgDAAAEHJ1cm5dRorZWSbIBgAwAAAEAAjYZ14pjBgDHADgAUAAAACM9J1ExjaqAHAAoAAAAAgRJqlNRU5aZWDDpgg4dZ05ojtnXbm7WYjo52ZB6qmkuc3N3E6k1g9li4PSM1UiHeQXnq5M+nH0eejRNW0SmWuRs5uDk6w4t42K35Oorj6w4+rmSd2VVL5XH7Pl9sZOX0XWdXOhLua0yad+\/H1+T16g+G02CGgBAnIcfXwdee+mGum1RfLbB5oAAAAgABCGkHSx9eKY4TGAOABQAAAAAAhUrAGMHAAoAAAAAIQQUIQpcaRDN4MtcNYz4dMO+UIu9e3j7c89uTt5sOZpdc2JolU2zLlsBk56znWSa57QLNvq4t5NXUR3PHeaxm2a47OXLbKTdqoxy7OMHvgnVpz7rGHXwp0b+Z3GnF3QeCu7g9GHUvTRxVy3LTft8zt5dO3THXyehgZCEohAhB53f53flrty7dcdWmGvDro5rnoAlAQAgEhoQCS9wzpwBgDIAFAAAAABA0JBMoY4AAAUAAAECCFTQgRNEObMgfTnhj08fXlnjUdNS5tvbs5OvPLfLbLlvhis++acNaSaJUlAdJMjBVOOkpnPUsM3r14+rWI7+ZY12YdErn0cvRBG2a3fP0AxxxLpxTH0OPY6IsXljeU2rn6DDy\/Z5tzyKF3zVTVywEe2LPU34uvx+rVC47AQS5BEqeb6Hm9+Na4X6ePVvyb8OvReV8eliMaAQIQIQISglHpgdOA01AAAAENAAJGhU0IpzYAQAKAAgQEUIQ0KgSCSbDOoskZ158cdHH25Tk5vVXGi9HXy9eOW3Pvx43yy32idCA0illoAJMlympz0gFy00CnRz0nfM9Ej6PP7s6qpqUYENZnS89IObpk8+ejoSrBTl6knF1RB15aNfN8\/2\/M7Yxcvrm2mymkdPf5ffw7dbzvy9xChIQkTKed6Hnejirh+rhtvy7c99WvPr5+2rh89sRAhAhKSKBCPXA6cABQENNACGhU0JGkqZKNbz0yAFAQAAhWAkNSqZKqlIhJNEVNiEdOXJjvy98TIOppGzO\/Vh1c8vzvQ89crT6ZqRJUuFE00xADRnnrjjpAHDoNPUGFadvndKduBph1Vy9KukSvLXMnoy1gadAEAAAHKdPOj6eDsHz9WZ4i6+T1c6qKsE0j7eHpx09C8dPF6WicnIpSSQ4O3i9HKWj1+a9cNMb6dubbh23rOuPSklk0SrSUNKRiR7QHTiJoaBARQJDQgEqEkNSl6NcN8wBACAFQiackDlSUSqpJWNCCWrJqK6c+Xk7eLtiBVej6cuqc9torjufO6eTrgBaCltMmgBoIRQgiAnSJ1jnqWjlWJ6DRXV3eV6Ek9eeOb3NOVgDaYNMAIAAADPRpmQjoM9DHzPXw3PJpHo5tMsW2OmNd23Nt4vXcpc65JHJIcnVy+jjIHr4OouXbXDXh23rK\/P1tSZtSlFSkNJDSR7yDpwBFAgBKmlJSmVpTJSlFKQ6ejm6JAQCECJpyoWoUjSRRJYxIYlTQJNLbeOXg9bg7cuXQvpa7MunlHlrz51zxE9siTbBoYCMEDTDOufGioeOmss64zVT59jQUJ6HRz1Z6s493K49HF1ltNWANoGAAEAAABydcJl0ceh056C8HB7Hm9+WIHWFxWXXtz6eL12pXLVKUNJBjovRxxKn18CpcumuOnHrtWVefrZKxqlIUpRSSGkj6AR04AlTSQ1MlTMlTMrahFqAtSV19PL05gJU5JHCyKmEtEyWpKpyxoEBMAesvZGsrl61c+XppPblu8s86WLy6SSs50uQGTQOaoEwlZY0IOWwAqorrlRpnigHPQIinL3NO7zui59Pm6DnrWufdW0xgDAAXAegcfYAEABhn1YptWWqzh052eMu7h9PIaK6NMb8XrtSuWqUouUIa49fXnyx04+vhk2rKqK5ddXnXn7USuerUCUQFEopJH0SS68WpVVMyVMyjmZtahRagWyAtwHd08nTI5U04WYZmY1MrZAaPOi6hlCYwdhotN8wCBAkcnZnvPnx28vbEY6RdiBockNwLZJZUBLKZz0gIExUwRxUwAY0JkAFjafR2+p4Pp4i6Xy5vY5pWEF48jM+vewaYgIAAmg49lslIa5eZ6mW8eUNejGlZ14\/TUk8d0QVakkr0fM9bpjHHry78uSOjLpnNhjdOH5+1JLGqUhRIlKQokPoFE9eNzE1czNlSpCSEalLRDmqcOWyWdvTx7pWcZ2aRKsM3nYKVNaEVm1UNdHnRdZ6F2X05jCQQkaRRncamON59eWGW+G+sinntipU6esqm9RTokyVzjUjM2RkqYgkOdAYhgmmDT2Onmq59zLj7+VW3L0S8\/H1dhh1JqDAAgAEAAIYAOWPHaTi4PY8\/tzwcvh2ETy2xJKJY\/Z8X295ee0dMc2XVlvPLHRksJrj1Elz0yRKSBiBiD2phd+NKQYiwkmwhyiQlYnnTpOabTl3rFXNCestCSc6y1kSM6tzeejYZrcta6Ofq3jSk7gJEaaqWKlFRc8+e2HblOek63mrTcNsQwGCAxIz1iblNZ0AQQ550AxWD2QykMhMLBp1fqeRvJ6U7ZctdFY6q2goCAAAKQ0AAgIGgbQQotPLy9fyJqU55bBFjELXt+F7ms6ylvCiprLPeDmz6McbzmpxpCQxAxBRLPTcvtxbToTSKWrIm5uZVEqoedjbmgblls1lsdyouLM89IuIoubKHjbHU1Boh9WW\/TmwJJTLGmEqkRzPLtykM9y5HbE6JYGlAFBpGAKblc1c52hxmwBw0A6GG4AUAAADTptFnZ6PjelyHTnGNaO8joE1AIAAAEBSGCDOK5ueLK6p5j0eLuiXx5qOWxADQP2PG9Ted5zW82QFksnHfPGubPfLOs01AgGIGIPTc1250JgmrEmklUElNZbeaqKVUVLkObLE7lRU2SqLJbedA6mii5U6oeie+RLiwoAEwy1zsyx6OLrzzVrpW00FSSFSalgoAAgaGTNprPHXLh0AMVtPYAsAKBggIGnTadj3xes+3z83o+bc3z9Mue2YaDJUNABQAJRzo+HrwHeM6nocuPrM+V6\/jdKvzfe8Lj0lNZ0NA+\/z+zedTJ9eetZXZTlS2pM2Md8caxm4xpAlYgYmejUvrinLGIsEAAwY5VTcKmxN0vPnpkWJ2EtWDVQmUpTqCilGUMc75SyrFnpBDZqNJGOVadOWGWhuSWiSkQtJthVLQAoAAIacLzoPL2GPQB7gAAykBCYADClWsjDUfo+Zvh31th5um8XNaPHZQCAOat+NwmHTyzZtywtxua1nTv8AN1k35byO7g2w5bzTOPZAB0c+vXGhD7c9LxpNlmRoZhWbnnuIqeXRJqUAAA9CorrmnNQAAANpjpUNlAyoTbOXDfnq3LBMC89CqVhRUDbFadhNLfMBBFKyGGo8657JInryTlW2ZBss2UhWktSoC0AAAOffl59Ex89gzcBlgAAykMEMgB2DRVCdgmjt9LwvW8+lvK56WjyrdMl4ubdWZVzRvN4h0gDpNEEp5tVnWpvhthw1IHHqhoNM9O2GI7c24DQgLcNKlrnuZqeO0BnSAAGdtRXXFuXLQmAErcsus6NKiktzQ3LOXn357LqLVpkTci7Xloml52U0DUuyhPfNAAjOwBahy9HNvnCtdMxN5tShNtyFOAshlJMaCxhEucBy6jHQBYADAACwABpgAAFMQMSH08jy97Pn6fPvauXpVkcCdPl0d+WI1qgAnJmuQlBlTcaRcXOWaufP1SZmq5rtgA78wBQCHSpBMyhUufSVS56QGaAHZUvpiqmlbTlYACB1DjSs2avN1oZhjhrlc1cWtNOVJqHplRvWNGpkq0eOms7ie+ZNJCZVjXObzWG+O+ZFRoocuiTTSABoGAMCxgoMNFnUOiakpCGABYDBAxDAAoAAAEECCVNMv0fL2xnu1quN83PeO3PPSb3Fl0c1qRM2Ic0Aqbl2TqdnOc6tdcZTpHLrmNeXsVL64YHowA0GVBTqZg0nUznSc6ibnj0SZz2gM3safTLqah1LVgAIhiCnDKcBbgWM7i5dzRTQoChkspyLRIXrjrrO7T6cUqQ+dG8Z8m\/H2nc+PqmZi4sibh0kpLI1KCFbTsGmjNRnE0S5mhGa1S5LWVzbU0AAAAAAUAoAQASiAYANM7\/R8H1+O8I7MbxiuzKzysrjrpAZ0CKAqFY5m9efpzHj7Xjbk56RtmmvJ6E1VgM78wYO5qS9J1kmdps552z0ynSMdJVTw6IZjXW09ZbTWhBSFDEikgokWnIU5ZE1Fl1FRQgBIbkKcity4vXO7elB3800ue5trn1nGTTswSTfYuTpzzIvJSLzbBOUEwa67MejRTlC0m5idJtgtLIxZnRLlOszWauZpAKAUIAQSgECZCGA0UwdhrmHqeh876nC9nL0Y4vkR1YejnmMWSqlmqmSRO2\/Q87W49jh6Vx6eZn3cno54Fxx6zpG3PUlnblAyipqtdsNstZbjHPoz0546MzFaTz3Ctc9dLZKOZ5erQzJ00MwsgLJN+aiTWKcOLc0sxorlMYIQ0kMRLRLLvPRq3Lt6lF9vMs6y3y049cemXntzWxN566KgzeiM9GFnrnKi9jm33pznSRigcoqFznWLmFSpKlbJSWVYYzrE3mqlsQKIM0QQMAAAChggwpsdgAjqEdRymXo83ORq59PlrhOnm1OeOrDpJ1npje+OcXujpnGvLnr5vRyjVaY1C1nNynWdIdFj0zuNqyvNtFS5Z9E6nLHTnWK0k3G\/L2znR8fo5GueOyKCSqTMF28DEa5NyyqhtWKrgVSJNEqpARA0l00xtrUh3W3Tx9XTjGd8\/fyS4e855Wr1hNNJgomIg2jpulnjBSuU3SzbedA3NROiTGdo3jMpWSNUgSqKlrOLidUgmhNZDAAKBgmOxMdJjQY7EMRDBJipMlXZxvN7+Xp05MZ0nWFznRq49O3Nz1XQdOdT5\/o46nk9PPr1zqh80q1ZC0VTTcpRWa7VyisMcenLeeads+k0Y\/H3W\/Nrx928sknTn1XD0OTqTyU1vigWuTEx1FLpUXc0mzJXJM1MSCGgWqhtaXGlt6Z1qacvVz+nxYzUdMpWmsVUZ6MDRgIejyepiZzpOcyU0l0KmyVDBJyKXnrCkjeKUTdWolq4UzRIpsAlAIBlA3YhlgNiG7ENomNEMENKkwSYqVKXfp4u7k5tK1mYFWemPZq5TNMZD1OXm7OPrz0vLTGqHUSaOXN6VLndOWaapiSGdxrOWe0dMJqvJ6c6nPh9Hp50Y69JzFzfVxCiZ18MpmuKAVuaXTXLXWWxxGe2ZE3MRNyIEOpprS87t00z10vLatcvOnpx9XlSTrni4x1YO0D0I11a5RKp1ExsjTlAQJzRDx1ghR0yQodLmVnVJJWglQxUNom3SG7JbdiKETYiGxDEBggBKkqVJUAJMU3w3y6tH0+fpjs1mwgrIWHXlbRrnHJ1cm16Za56baZ7ctN1WNQ7FlObCSd4CVrFSTcktak1L8ftjPaePuzNDHXMsIKBDOvhhXOuclITGaa47altOJjSDNXMsRpJA0DTL1y0t10z01NLi7l8vW9Z8ifUw68vLXVTXJfX3RzdIudE5saT3kEI2gBJHLz1FlUb5znWd6TLnPQETTEDB2JlWJt2IoRNtJbaIopDEQyEMEMEMEmKppKgBJpXti49q\/N9HzdWms1c18nXk6VdeDlSpy74a09cdM76duXfnvorK+erlShBG8OUt82kXLSVCFQ5rxe6qmpWAJMWZtRCtETojMtJDYPTO9TS87lc1JM2pYnSTOdEkFAaZ3Wumem86XF2U5EolstMJTmwRI5UlKJ6c9nhes6Cc0IEWd56xMVG0Z3DrMtZ2hkoDsGVYMq5TbsQ2iY0TZIhgkxUMENAAAAACmpUTFU0lGmPv4Kj2sefLjU1Xbg0SOUqMdcnQqW1prheXVpy3i7zmmalLeGkMtJWtJU0hSovw+26mpW01BksqkSqCCkSrVkqxMrks2qLmmMlSqVlUkmbVklCRQWaXnpqaVDubcNKciUSrHJNhMwlTCKmVV1lXbjvpz6RqkptZXG+c51F3MVLpKZnSGAyrCitYG2yhsQxBhIJgk5ViagCAAAlAAGJM3DSaapVKqkymtmExsNyQZubpglWdy0mNXU2zVS5myRGhI0la0JWkKIS1YeH2XQS0wUAlQAkAAWIBEBZmwNLCaoBUghAUAWSAykBVhc2w1lsEaCxAIoC5ygNZhBKkGdug7crsNc9AJc4DciAdJkG0glGBVBrNsGGwQYSDAABIBILoAgYIAAgUAGAikGpYKIBMLd6CcmBMygusrBpIFUgowKsGXQMAASAkDSAUQCAX\/\/xAAoEAABAwMEAgIDAQEBAAAAAAABAAIRAxAwEiAhQDFQIjIEE0EzYEL\/2gAIAQEAAQUC6TMEbQmlA9dxgFxNiFqARPEonLKlSpUqVKlSpWpB3cHj0lLDCI2AoFTYdMmETNiYUrSSTwMk5mntjx6SljIRFwVKlDpuMlSiJRgAu47YTT2h49JSyEIi4KCCHRc6bFAKU\/nvNKHZHj0lPIUUbhBBDO7wps88egaeyPHpGZIRChEWCCCGeoeFCc6FMo4ZU9YFA9gePSNzFFRYIIZ6n1mzgv4T6FpQ648ekGaFChRYIZ6vhOKnrTYFoWpeQcLT1x49IM8KFChBDPU+pKKDVCPSm4Fgm8JwwgoH\/jIUWGc+CNjuiVOyLBAo4Wn\/AJAZ3iCVKJsc5OwCwTQE3QnU2lOEI4Agf+d1J3KOw5i7YNo4NN6qxACqNjA0+6PoJU7HXKOw4OAi6bi87IlNBQbYiQ4QdwQKlT0j59Ie\/O4i5NgnFBHfrjfOxoTGbCqjZG8G0qVKnOfPpD6Ypzl5vFo3E3FoU7AJTacprQNx4VVsY56B+3pD6SUXIuuUE4oInaTcKLeUbtams2kwJc8j4OtUbpO4dM\/b0h9FKlTeUE5DlHcbATYKeLwmMlAAbqo4Y8FEtlOEpw1tPHZP29IeubjaUXIuU7SmFEWO8NRQt4tFms2kgAF1U2qGFpa1UvqnhVBI7B+3pHdc2G4o7zYPkInafAbY2mzeE0FyAA2kwC7URqcGMgpw1DQAtbimmQnCDUbBwAoZj9vSO7kouWtakcUwtSlTZthCcQibAIBMpxvezWIZTQqByYdNSxYCXvDE17hY8h7ZB4wtKCGQ\/Yekd1zsJTnouUoY4UbAigUbBNYSmgDYTC5JvVHJmqhpYmVA67obUl1RAizgqrZwtKahkP2HpD1jsJT3ImwTE4YYud3laV4cPGwhRIBm\/kPMJjAFpP7Rc6nJwDE0yE8QqjYOBhQyH7BD0Z6x2PKJuEyzhthRuO1qCLZVN0XJJTTC\/hXM3fTD1\/iAxz1SMVC8Ns\/VAa1qL4K8p7EeDvYU1DGfsEEPRHrGxTinbAmWeN07juaUE4Km6QjwWiAF5Q5LTBvUBD2OJDn8hsizobUaHPTSLOEiqzjAwoY3fYIIIe3\/AKn2dsam2cj0Qmm30cLHyzgpwkcoGRdzXPdqDVD2EGQnNDlUfCa5rBq+KIVVul29h5aUMTvsggh7lyKNwmptnp2Q7mlBESKToKKbymtAtEGSDeo3UJZTXycmPZd1NrjLQmgmxHDm6mkQd7Chid9kEEEPanxZx5RuE1NtUR6bSgnhU36ht4aA7m7mtajrqAlppt+tjppqHvTJhOVdk4GFNxO+1ggh6AdUoeE9HYE1C1U5TvCaUEfg5pna4LmNXFnCWsbUBDGtNyJT6mlNaSQZvUZpO5vlpQwu+1gggh3x1T4\/kpxnaE1BFP8AOQo72lBeQw6HbSOQADhqCHCaiD2tKIkPbraRB3MKGF3m4QQ77esLPEI7AmoIp2Uo4GOTX8vbqFJ0jY4EprABiJIqtEpshqKrjncxDCfNwgh32db+p5RuE0IWceCcpwhM5QT\/AIlpkZ3sD01oYNYvCqs0naxDCfNwgh36fYeEbhNCClVDc45xNKaV5DDod0KicW6Wumx5Dm6mkQdjUMJ87Ah36XXCenWCCaLORRyOOw4GOQT2yKbpHQHDhw6x4Vdu0IYTtCHfpdcBOCcLBNCFnlTkOak5Hwfi4HoGYggUzeFUbpNwh66jgnMBd7bMCCJgak42COEmM4MJjpWj4sJa7oOaJKb4RCeNbTwbjD\/D6SjulE5hsKe2EDC1JzpRscJRPRpuhNqSqjZDHSN5ICqVlQJ3ESNOkF\/NjwazNgw\/+SEfR0NpRNpyjaU9sIqUTjJ6dJDw8aHA7n1A1S55ZSjA6SOAKZuFUbpNhhH0IRCPoqGyUSj1JRhOAKLbHugwqL0RIp\/F13ODQ+qSGUy5NaGjD+sTdyeNbTxYYW\/QohEeioXlT1+E7y7jZPcpugtMioNQY6Qn1gEA6oadIN6P1NZmNn0RRCIzypU9CiiUSpzBDAUfGlFGxChQoUdqm9NCcNDvIFDkCB0SJA8VWQRhZ\/nYohEZpU9GmiVOwo4m4SE7xyiEch6jTCY\/jymfE9RwUB7Xt0nBT\/z2FEI94bijhCbicpR6ZzsPLYioJTDIsDPR\/YJ8Go3U08YGf57ij6M4moXO4p5ufRUnFAJ3wejKBGrMSGg1JLxCY\/4sMiu3Az6Sp2lFHuHoNxP8qUT0j0WmCyoiJFPhFShlLwtfyIg6SacwqDg5tYcHe0\/Cd5RR7bugMJKKJ9NTMEHipymO1CEIGR7jE8kal\/KT5VdkGm7SZD1+SyN7frgKPbf0Bicio6TupScgF9HqAEHThLkXQXApzRMwtSHB4q03CDRqaTWh7T52jxgKPbqdIob3KEekfPTBhMqSCyVTNuUNxICqvWsgha9Imwt+MVXHzVN3FT7bR4wnt1eyV5JR6Ljx1aToIMioEDIK4G19SEShyiNK1cE7aT9Lqj9TkE\/zilT363VOxy8Jx6Tjz1qD7D4O8o8IeEeAakqoPkx0J3xTnycAQR8+qrbxmOx7rHZKnIeB1wYNN0h7dQYZBQHNnt0O\/mrGPW194zHY\/puPPYpPggp3BGyq5ulxOQetr4BlcYQu47Dmce3SfILwmSLFwan1iczfW1skqVKG8lfw9I9xpTC0Bz9SLzoJkmwWlEYm+tq5Zs3bHL3Qi6QxyPr2lUoghOago5iEXI4QFpDW+sfkm7dk2qBaVMFrpR9fRevIf5EaabNRrNARwhBDkvZpucY7z87drncnwXFf0GEDI2nBEqFHfBg03SC2V+tNaAq\/0OKVT+z2yw8WOMIXPadnFwTYjl\/0mzyE0wgZyNE+jY7SmPk6QnfFVf8AM7o2BUYUqs3nIELlHsu6bnnUncoBPHFgYQM2Njua1R6QGFSrpz2uB5T2GS2LwosTsaUw6hCc3g7B43BDaR2HZRceDYiUfrqXhVDIFxwgZR3NbK0D1Oor9pX7JTAxyqtAdChCmSnUoRFwqfCBkx8qrLQoQHG8bYUKNx6B6DEbNRTRzUCO6UbAIMWkewaUxoh9SFrkuUIBNEJ1SUwwT9XvGj9Zg9CERuPoGnlFA8l3Mxb+nePLRx1T3aT4VRsrSgOA2UYYiZTWytOkaiU0LwKrbDxmIRR2Ffrev1vRBCDSUQQgCV+t\/ZCHINz4sTvptk7I6R71NyNi9eVTpyiW0xy8tahARThIcII8ZyjsmH0nF35H5RIqNH7qv5Dvl+OdYc3RV\/L\/AM8AziwRRvCOCm2B7SmiimtlBsI1UGprbg2rM6JR2OX4\/wDt+X9\/xD8vyP8Ab8T71zNf8v6YB03WNijuptl2Y+naYX2GhDhP5TGINAR2FyJR8jbChRlcqbgw1agqIGC6oHoVdLWkA1KwqDAOgLvCOx26mzSMhRN5U+lY6F+yV5TaewqeJm58hBC8KMz+g3oBC72RsO2lTjMbz6djZTaaAi5s8xtPlBBDou6Dc4QQ2GkURpJ8XDSVSpgDKfVsdBaZFynOjcfKCCHRIlaStBWgrStKhRhGcIIbXsD1+gQ6i4L9Lk2hzmNz6qk+NlR0b\/6gggUPQDOEEO2fV0n2qOgYggUCpUqfWBDoz7bwhV+JJOUKVPeKGcdQbD7AbJ2H0zkEMwyyp98fVOQ7R92N3\/q56n\/\/xAAoEQACAQMFAAEEAwEBAAAAAAAAARECECADITAxQBITQVBRFDJxI2H\/2gAIAQMBAT8B9jdpykkknxL8K3ZuCZ4II\/LOzeMCXGn+QZJPKsVvxv8ACtEWXFNpwpcPjf4WokWa3IJutyGnjTuuJ\/g5s97Ui3FgqbTeBKzw03uQQQQRlBH4ORiFgkPCOGiubQR+JdRLsiIeCJJss3dnRRqCea97dpPksEQmfEi6IInhd3bTr+3BPvbIGiLok+RNo5esOilysqxP2sYt97fcqyV2hcbx039stUTE\/bUK33H0IjyPDopc46vQhP2xuJDF2VdWnFXYuR4abx1urIXsVqikqzXko7x1erIXrZT3aoR3wLBcjV6exYavVkU+tnTGykYqckvG1ZCw1erIpF6XZqbSJHeKV2LwO9OGpekXoeFVlxLFbclStT1hXdC8U8lN5JJ45nkaKOsKroXO7yLCp4uyJxV1n1y04PBc7wWDxqfAuNciwfmjifEuJOeFuCZFUK9WEifr7FwLj64Jsrad6sV5Xi3aD4kZULkpxbxZp3qxXleNVleCLrfmmzcDqyfRTVF6sUxPyVdYfIfYhZrYnlf\/AIRUkIYsW7U1WqyTE\/HV1duSlDQhZSSSSTyLfYdMEbCyqUCEVZoXG84tMDdo2gdMCFduBucZJ5E\/2Rl0PdHRSyvgTJtp6Crpk\/jL9n8Zfs\/jL9ldPxqjB5K1S3GdiQrRAh1JDrJtGSfOjY6OyY6GbibfDNtFpUIlEnyRrf3eD4NVfcqdlg3F4Iu1ghcyY1O6P9t0JFSFx0L\/AJSLbS+SGl9Ee9VDZrf3eD4HuaihiJyjFu0EEeDtbFNP7P8ACItInvnJJNtJTpwKlJQj6dPQ6E3Jrf3eD4a6fkjqy4WxISI8an73qri1GTZJN9HUpVENn1aP2fVo\/Z9Wj9mq5rlczSZ8cHi3ZcM8ic2rrjZCJKbK0jZPtZN2IXlTgqr22vBTeRsn2TapECd0LwrBvFXn3qzwXiWDu7Li\/8QAKhEAAQMDBAIBBAIDAAAAAAAAAQACERAgMAMhMUASQVAEEyJRMkJgYXH\/2gAIAQIBAT8B7gFPG+FCiyMx+FaIoAgIzEZT8IOaAdFw+QbyoUY5vI+PCClDAUcDhjHwkJqjATCJQEqKEQvK1wxN+DAoNsBfSLCaNNjhiHwsIC5zkBZNrTY5iIhSpU2jpjoBq8VFzigKnZE3jewtTmx2hkFIQahY7YrzCkUcKSicLTa9qIuaiOkMYo1sqIRQsheAURQ0nG02vF2knBHuBBARR3CabjWVGMIGbNQI26HKcER3W1chzeUczTFhTxboclEJwR7QoKuTebzYcjDZqBGz6fk0cE7tCgq5MvdQZggZq\/hOs+n5NCnI9oIcUKKaIGB7UKuyNdFXcJ9n0\/NCnI9obJho4oXudCaVyiKChyMPqhT7NDmhTkeyBQGFMjZeN5dVpT6g5QmmQitSzS5QNHI9gCxphAzcVFQnVFHD3kY6KaljECpTk7uBCklCUBeaRZEZGO9LUsbSUSjnFhsbaELzVxvInK\/exthziw2erWjEdhQXvGQ\/qxthzjIE3FqH1hiUR44QEfxTmzujVihRQhEdgV4wnZcoYXtlTdEoNo7hBaorp2QndUWgKMOofSAx6jfdoaosC1a6XNrkeoKijcM5TuooBKa2LYQTmyiIppc2kIhR0281heKGE5ngxsmf7oLpij2ohaXNxCI6beagQgiI7DxG68pQd+Vs003SinhaXNoNCER0hQCUBOGejEp7COEFM0lcqEQgfEoO8k8LT5umhCihfBX3F9xfcQMjIEE1c9zxC8URCkhchEwvGdyhsVsU5oF808aO5sbxkagMMqag9NwlccoStgiZUppgp2AVP8l\/Zf2X7TeMgTDNzjeOo7You\/S\/6ppC9I0lTYEKO\/kpUqU3jK0wgZsc6FM3AdV0RujHqobNSjZCixzTK8SvErxKbxmBI4Q1FKLlyhaEOqU5sUY2woikIBR3QoqOuWyms\/dxChQo7wNIoP8AAB8T\/8QAMBAAAQICCAYCAgEFAAAAAAAAAQARECECEiAwMUBQYCJBUWFwcTKRA6FigIGQscH\/2gAIAQEABj8C8MHwMfAx8DH\/ABvt4Emmg3geY3xO8lFt7SvJ2Xzh3W+bO4nNqUgmd4Mc2dwytOmax3zR2a2RYKdlyu0WHNcWMXCrDMnZzG\/7KVri+lwyCd4MnpF1wiSeHbMnbk7ieKbBVXcRdMpiUWzB3B0FgUuSkF1KaNakpfFVXi+XO33X\/bIo0V1KrEysMAyx4k8Hy521VMZSHVSEusJzKxss7lPSKNEYKZhwriM1hwxbLH3tp7BeJdVR92KzOnpSTfjCFeZEXphwmHxVXpF8qfe2+0eL6VXrHp2FniPCqv4x\/dVynhNVQpTKfLn3tyqYy+4maEpWMVKZT0pBVRFyuHFPTi2UO3HXe2zNYNNk\/JMBxIPHCcGMHVYZM7dcWndS+yg8osh0TtZbmq1IxbJnb1U4WsE\/7uq6\/iquVO3+9nFrxsAqYCnB0+ROinWqwyM7LHInRTrdU5EdEP8AS6R76qdmnhmutKLqsNUOuVhkS2K4iy7RY6oddqnI1sVxY8lPVjrrrvcTXCsJW5JounF6NFOvVuVvquq4p3Elw9ZlHpGrej1op15lVNialJTkFK67dLDp7wetFOv94sMYdTkeye7o+tFOwK3KE8FLJ1Td0fWinYNU5V7uj63NLHKsn5XVH1ud+UCmF\/NMnU4PcUfW6KpyDDFT5pk5ux63RJPfFuUBT+4VYhPbGijYnYxlhclplPiFW5j9hOMDF7ErY0UbFqnGEpW5rsnUsDh2TdLLRZHSxsWsLhghSRolTxTWnT6cNiNBuRhKx2wMGOBXfVxsfvZ\/iUx5ayNj1rJGtDY7JjCaYS1sbKnrg8DDZZ6wHhIeBmTb34limvp76nCV0wTKW\/p2HKYQrKWO\/GTi4blF8x8KX0vhS+lNSBKmFIOvgfrcEo905zdE90CUG6Jz0mqgkAjQpTCZD3uJqCmp2ZZeih6RCKPqA97qOWdnPtfFj7ThcYn1CagG7pyHTGj+9vyCkp7Lc7+kVO05x8ATWKlOE9caww8Bt4In\/Vb\/AP\/EACkQAAMAAgICAgICAwEBAQEAAAABERAhIDEwQUBRYXGRoVCBwbHx0eH\/2gAIAQEAAT8h4whCEIQg0NZR75aINDRMGhoeHyFExMTL8Nu06OyjHoUSqN+8iwmITKJlzfKABt+Uzo\/XxoQhCEIQhBoaGiZIQhCEIQeA0NcaJjCfwk9i8aok9TcsZQHxWUylLhSlKUpSlKUpflbx1fr40IQhCEIQg0NDQ0TNCExBohBrIMTmNBBhMTF524UGddmxfgvULeK40pSlKUpSlLilLhjR8rr\/AF8eEIQhCEIQaGhoaE4piEIQayDUFgcYYTExeV6Q1vxhaQQ1vY1ZbyudKUpSlKUpSlKUomQGvyer9fIhCEIQhCDQ0NDQoWIQhCEINDQgghMMONgheVo57HvMM6Co+KExZpSlKUpS4pSlLm5TwJ\/I6v18iEIQhCEINDQ0NCS5hCEITEGh4DxIJwiELySwW2NSGnOlyUped4XwQLfI6P1\/gmNDQnYhcIQhMMY0IIMTgEIXltClNiiGwo80pSlKUvOlEVHZPBSA3x+j\/CQQS8LHiDDDDCWRCwvIMgi3hrL8NLwpcQui0U9Vm76SHLrvwk8Cfxuj4c+BCCE5sY8QhMjDyELy7CAjY4QXDHxvho\/oN0Ro2MR0b26PejrwSfkqUvhXS4350IJeBjxCEIQgww1gheVaxuwhjDGPkn4GwQmJsWlY3OjbsXKF3zpcCeaUpSlKUpS+GlKUvzYQnheIQhCEIQaGiYLzf7HDpgeF8FE+PoRRFwLQxRW0P1JCHSn6GtQk8DzFSlKUpSlKXxUpSlL8yEJ4XiEIQmYQaGhoQvI3B\/Q1DFw3oasSPfgQnj1fRbS6ytiYqRaJ6GD8uiuzVEwL6uudwJ6KUpSlKUvjb2UpS\/4g\/HBoaGhCfhcDspRsXYhiCEZIdmngbT9\/oY3\/ADKfYtnWFE5ig99\/yLW3tjVUKDjJMpS8GnAKUpSl8jbFKX\/EH5WMawmXhcUf15UQ+4SEEWsiGzQ+hq+N3h9Xf7K294SpEuhL7LDbK2Mv\/DRVn4EklpZX2uxE3Z0UpeNeIUvlb+Yv+YMaHilKUpRu4vGkp0oQSG2h5ETFw55T7Oz7MYuXfoOidfZ0Pf2Lilfhl0dYpSlxRPFwpcLyf3P80YxlKXmylw0lRqqicRTY+tm4fAi5s8QVLs7HSwTeFsvH2\/ok\/wChdcV2eGDtDwY1VCWk38OaUohsPCEIXk\/uf5qxjzeTGxqPE2McEDpYEgtjUz2P6WQ1BPsVQLb2a9DVYi6NRfYt0yi4e1Tc9DmGRDrVxBrsQxPqJUeaJiYmWFIJCEhIXj\/uC\/zNjweE4sSKYUo2M6m+\/wDR94tdFMWUOvof4LdjzSE+xp4aZoSuFYhLrfx1xqiFj0ovq4ciTAl9qwz7feGr7+HFKJiYmUTEISEiEJ4f7Ahf5cxjwYm+Lw7jxS4bweAFplBDedoR9xKvwQmNlG2fZ0fjCticV2Z2bXpBkEn6R91v6wmgbfSDQrkglaY33sfo3xTEy8IiE8f9gQv8uYxjO3wcCV7IGhsNZmGMaGhN7G3YsFeF2KyElEbilCji2zsPXzVGw\/PN9j5vSxCU5U2EX2+jYTc9CKDKj9+hG0fFYon5y\/sYL\/B+nxGMeCWKTyiGw9ZmGPDJlmWgw2DDEPwKEsS4IStlQ39X2+D9Sp2UKSS9kKNy4jXp5WAqfR0Uguimli6vsglb95WFwgxvKb+QYQv8F6k+Gx4PbzJFHgvDnwY0QmEIJxTEEOq9DppOCaa06U6Krqj2r\/udhdZaUGqmPbX+4bK\/8BJnJOvyMmqncNJ9qjNcxCFNaCD9sfoGdX0+CzRMohxeNv5hhhC\/wPp8RjGF1i7NcNheG1ok+EwYnBrQnFoxiTXZYCwlf7jC12fdh3p2I1H+IvSFFvT39cFF6a9ijNj6GukjcVl0lJvH7kY235jF39iw1EZqb\/6EcHlC4QY3kP8Azhhhhf5UxnrhoaB2PCFOh6wMomUow3xQfC53WnaEfmxT3G01pDmJVdn0MmtdDSSNVCaF6\/giKqQTT6yprIcUBrfYfbSFozlboM6K2gvON4KC0e8oXBPZdDi8Tfzhhxhhf4B\/FZa2K9F1sZDwhDqLo6vGlKN830Pi0ZRYrquwyaqwt9v0o7uU7JL0Jo7ixdpezaXT0SqJTh0wQaoDQbt\/Ypae8JotQvqr\/hpVuEkNqnok\/wAMb+LgsohgN4Wz+2ExhxhP\/KMbF28Mkh6ds9sOoujoztxhOL5oMemgP6EELqrT+xH70vv2xDF\/OG7Gib\/2egm1PfBs1Gzo\/wD4RLapJpN6\/GYEHoqmFTZpi0tFBa9kMYnhcUy6HF4Gf22IYccYT\/yNGxsfYui6HMUcfErobR2xCCWHyeHzlVHawLvilU3W\/ZZ2bSq8K5XufkT06ehEiYVpHaY7Psm3Q169fgeKY8JNCLIuO4YXgZ\/YwmMOMJ\/45SlKNlG08EESHHwoKejZhImX4T4tGUNhX6piETXGrSRD2a\/yMim5+nm8EZqGPKbPgjsrBWrY1TCEqdJSRt+mO\/HlcGmE3B8Gf2MIYccYT+bT38tKUpcPD7Ceg4Q9hsbyogpojZiCRMvwG0XlNj6GlJjvYOhO8Wbqn9v0UFpv23ijqql2hH1uCcfzmNA+0Mg8Lgu8D8mPH9rKGHGEy\/KpSnv5KUpSlKPDOo1SofKFFFOp2eKUpRv4BoEaG8XaNI+guGlUvZDd\/vxNVbEm1ErUv02Kgu2Ejg0kWub6HKUpS4Yz+9lDDjCZSlxS\/EpSl8k2NlKUpeKcFLPgTAoiQo8UpS8\/Q+GubQRMMJ9Z7EIa+Ag\/A0T\/AG2Jj1195a30M\/R8ziZS4pcM\/vcTDCZSlKUpSlL5qUpSl8c2NlKUvJjO0RO+EhcWgxXRBeCh6xdDCGhrnBlkNKD6NiafQn8DSmm\/dImGv0h1Gmy9PCBaT6DIPj3HEylKUo2U7P3wWDCZSlKUpSlL46UpSlKUviGxsbKXx10IQQU0ENENs6FO8LCwsPoRBYWE8EmPVo67tHfdr4Ldo3emVr2d\/jK1H+xLXE7jiZSlKUbKJt8FgwmUpSlKUpSl8FKUpSlKUpeXSlGxspS+OSwbiC4EG0Lg9huk8DF0NE2d4Qhj5pxnSRsa3W+yiq+AoKm5vc7IL69b3iHt1Mbwew4mUpSlKNjQ1lCExMpSlKUpSlLzpSjY2UpSlKU\/48aNjYw2UpSl8U9nvGiokxDdsoTiPKw9ogG2+CeH4HsP1Z2L7HPr9MXwFKJt9PoRJVq\/Reip9sWR+0Qjg8rsYTKUpS4pNP0INZQmJlKUpSlKUpeNKUbGxsbKUpSlKf8APi2PAbKUpS+BKxKZSoqq6xpwOgns6F4LK7NCSns75JjH4KBWhrnaP1TsXNBWiHNR4vsdTT6O+SIM7i1\/kQkTbfr6z+kfGmKUpSlyl\/BgQayhMpSlKUpSlLmlKUbGxsbGylKUpSn\/ABxSlGwN4UpSlLylF4vuQ7gzQtjXjsayxPCKNfgWH4XVNgyLt2Iaq5IHNh\/mXr6E7bDrmkLR\/Y\/20AxtK2nTeGqobJsNysUpSlKUov8ACyCEzSlKUpSlKXFKUpRsbGxsbKUpSlKUb\/yUbGx4DDY2UpSifKCXDoqIHZ7OsJEwTxSjYmMuiE+G5hjUYqz2M3f6xZoGO7U\/snMEgnibqbfsEp1lXI7Qn7QlTgpSlLlf4wmQa4UpSlKUpS4o2NjZSjY2NjZSlKUuW\/8AI2NjDFGxspS5TKXCEhISx3jRUaSEmdET7DxobqGy4NlKIhCDRPiYkF0XQ\/drsuj2CKRbf2bZ\/BP5R62FxpS4\/rBoTINc6UpS8DDFKUo2NjZSl5N\/5yLFKNjY2UvClKbCE41NjjIkI6H7DpMdTRtmzIggkQmGNc35E4xvRTZCTt2KfgZR7\/RCpJF8LQG7dhslyXh\/UYaEyDQ\/MUpcsbG\/C8w9s0YYbKIXFCCzcNwUFCjNdCsU7ESGQhCE5n8OgW4L1a0N\/SfF9DtDAf8Ajw+f9BhjGhMCDH4qUvFjH4XlG6LL4CEQnDsILD7LhogkO0bQ1gzo9og\/Ex8W88kHYdnoP3\/sRYI6O\/Beq6PU7CwSo\/A\/8Ao2N4Y0IIPxXmxj8S4PB4SEhEIQgmxOBCHijFuhXgaJ4WMeX8BaKpRMokF7dietHUlopI\/357gbVr6GPHTFKRpCLgY+TfxB4KUuEEEH8B8IQnCHoIWGMeIJYQiEIILh3wehmHTQ2HeX4mNZf4OwKKezTP2M3\/hEqhXp\/wCkNr8+Wju9Tb2rRr6PuDXv7FDBhCextIRpxrn\/ABLClKXDEEEH8KEIQhCEPQXB4hCZQkQguWzvLyJRSQ3WJC8zRB6H8KCLY9nZEEOvwO3Sc+\/H0Nbi9l9ouGnCdCn\/AESIm7PZVX+hl10NuhaovSc2\/gKUuaUYgg\/hQhCEIQmBcHiEykJCQkTg7ZNYuGNbGiNsGL4DzXwlhjcbEwZXaIK\/X2dpPCSo0PQ72X1+BZwxEFg9yNXZTGaEGqfY16O76PsAkZcn\/iKUTE8Upcj+HCEIQhMC4PhCCQkQS4kw8JlGbiwykITzNfiLBkBiujPwCJ9jb7RJ+RqtckFaIbFHG+uyAiWnpCqTTe32+h\/k20\/wP66G7gmbWZMIam5k2n6KUTEylKUbwfxIQhCEwrisJEEiEJhHoYll4hB4igmjYS+BL4zsRWoYmuxdirIWtN7Qntq3xS3ax79qen+GOnh2bfu0N0\/q3SmVoptwpydCHnNT0ilKJ5KUox\/FhCZ\/6i4oWEhIhCYQ+ZFOgtjSUpSlG8PxW\/T43Qy0do\/qAaiMToi\/Y7e2Go\/o9n8T6JM\/6FM03uHTzUvv7HWZeNLvDHY3bkus0pSlLhj+EhC5f9xcyEJYXB8GzpnohoTuTZclLl83+QOwdqffo0D6diX9jHav7eUPaX2obSd9e6f2h7OPQ3ebFjsLSHyXXiY\/hIQhcf8AqIXFhCFxXLYZR7E2IeHmlKUpedtPlVVFrTr2NVVwWZ239DETdS68DeWdxj5evnIQsUpRv\/YhcmExCZSlE+MPWQ1WxlhRiQ0PzoqLv5FwnGKgyCNv6HfHT6wu2PSo9jQ1wfCYeDINf4NCYmUpSn\/UQhcUxMTLkYfgm2xtIaTELotoca3hsbH5WiH2QnyYMqvYzqIprY3YrE+hM2HsSeHmcGJog0NDXD1zSIQhPiUpSlLgQhckxMpcLjcM6KZTKOoPRg8MY8PxUeyEIQnyPvEbVC+n0SYuzSDYQ6GrKN87sf5XLGPwpCRCDQ0Mfw6UpS4kIXNMuF4fQvs2eKzBs0kjEGMY\/JCEIQhCfIk4xhqwr0enR2Ihn\/eL5wSYVuGInh+IhCCRBoaGP4lKUp6CwvGjvliU2P1Qz3HPY63yUaGMaEsEPkmChYQhCEIQaJ8bcI9+JQ0etm4Wien2d+aQtYWEVISoPxELBCDQg0Mfx\/XzI7no6GmM7JCYh6RFSDWEhB4eHzu2SEIQhCZg0NE+M1hS9lOjUjZv2d+SEwtiTsdlps026FKkMfBLRCcFwGhBBoaJ8b18NLlCELop0zRLo21TuRuIhqjQ9hKDwTwXBdi5WJF0QniaGhr4zGFLTHQBChJ9DOyITBCTB2JwTGJ1H7Yhp9mL6CDRMJoQhMrBhPDQ1gaGiEJwqKvsq+yr7KUpfB6i5XF4lh7gWyyjpGG4i1Ro9RvDNiTCD4e8JGLiDQ14IQaGvj1oS+mNy32R1DuNKjOn0IU9IbDFveRCsR7LoT7IbJG9nS0JhuaBBoaIQQhhMuGhhhhohPGXNHqTw0TELFH9YenS9m+njIS09jUb1wsFfY2Gvo+8gLRcIWINDXgg0NDXyrOis2m4EarsoiDwPpI70ENS0Omv0GPYwmUaOCYiDQ0QhBCEIWIPAaGviX46JiZSki8EoUcXYRVtsW3a6Ej5pYJciQkTEGhrwv5zvHjFp0psNbQn5mPfY1xrZk\/oKrRNBNwUfTMIQhBCEIRBrAgnBW2kuz\/6A\/8AoBjEaf0z+rRDXYv2h7Hfoj\/6LwrL8KEy5Pgv2Pbowbujotz3BJhoghCcYNDXgeD+YnGXUZ1P2MSDrDdmiS7+gvqpc6ovsso0A+gswhCEEhISEstCCDWVUdKh6nd\/8GKzT+gr1iQOXUXSPUcqp3\/pqPxgWGPL4rCwQ8Z1xg\/oUeB2bkaIQhCEJxYx4pSlKNjfzu5qht4aW3\/JJT\/2b7sz3i\/Q9ltM9lGFrT9CeYQhBISEicHgg1n1P\/d\/5jkJ7trQs\/0\/+CbgnT6i8fFl5fFCEIQj0LsZTYhDTnUiiGiEITwNjDY2UpRspfLPhUCSGqL7G38H0L\/Z+9GLvD06U6N5\/aGEIhOAhOFwxjWfUWXdHXQiNsgMUyNC1Vj2FLeds6yhXt3Cpajuv\/48toeGPihCwQjRcII7O84pNuH7N+RjYGxsYYpS+aEIT4L3\/A1hBeqHsES6LsZoNFsUw+sdv74BISyQmaUpRj4enwSFhoay+KELIiJqMZstoQmPo74mep\/ryMbGGxsYpfBCExMTMJ8OmEhPQbyTqEaezsQxs7f2LgkiEy2NjZS8\/XwLwewhYY8vihcAsSqM7yH+GOgkY\/B0CYlJF8NLhsYbGxsfkhCEIQhCfAeZYnAxYdFdnb2JFg3oe2dv7Fg4wssbGxsvgQ6IfqPyI\/QX+CvwWWJeGhYY8QaGicFwCFlRP5HSTDHQJ\/cGd+hJJRIfClLybGGMYfjhMTEIT49lCdWGRezPSG8MfYQw2JilGxsbLwpeCF4YQhCcCELDxBoaIQmFwCF46UpSlLwYxjwY\/BMThMT5PvHZ0fbLe+8IZSj7H28IbILAw2XhSlyhC8UIQhCYQuMJiEITgIQubxRso2N4JiYuDGMbGMfOEITM+UsJ1T\/cGNy9DZcMfeUJjCwUvCl4oQvHCEIQ0gwvDCEwsELncUbGxso2UomMJ5YYxjHzSIT5D4MeFiUSLg9Z6G8Jj74IQhMpfGhCF44QmPTIucIQhMkLFLmlGxsbGGKUpRMTEyjGMYx8oJEIT5DHyQj0LD6EaPg+CF50IQvP6YLxPghC8DwfY+SEIQxjGMfFC+Yx8kLhYeGH1yIQvP8A\/9oADAMBAAIAAwAAABBOsYgLvWs\/49Td3G1re\/m2MMMMM\/8Ay8UWS1fPUzD0XVAMn8wtlPDCdV3w4cG8o9Vs7YYs1p2eak8fd9Vm+4HvwgTXxLPxxlqjUh2vYGvGVYcXTNRaNBQH\/uck7wrsw8wdn4CBF50thB1ZR+I4xD1hB0omygMJVPPBZaTXq6Zx4brbdKKE17ij0nuzNc7doIdSQzP4aH92gmjnPbf1UqpPP73NeUBBM0plZF4wWUZM64abudHIOCzRyWPRpXV9\/h0R59d6houD8b2KzPVN3rR8ojnZpzQYgPdqJXY+\/wB0WUePFuZretQ36GJgCYjazXxTSSvfHPJtKxgD4QQdY3XaUxYFFm6cfzTDk39HvKK9\/l1hyOFdkN5+bY6bghcDu+CM9QwW1dNvqurzNu9ihmqb1TdR5ppdQ+T62sb\/AN9cTMVwUTWBf6D3q\/keZbEEAoMBvOvcVIw6J3S2b6WKtN8WzMRp8+289UXnV1Wdf0GsNHvs7pEzI3SQ9LDROt+1bEh96mATTaWAQzqQDZz6ahxXjN2abAGc8f8AVXRTGzXjF5L9sj9P5d8kuRfODHuVaSDUpsNJjW2m51cVlkX5Gk9hRTvYwehthBEjTfl5njd8xbtxLd88Xp\/99ejgxPw8rQkQjqZ\/Wv5ExkV6RGot7X8Z2SGGoYZ2WaCCaiT\/ABeSxvPPGfy2\/PPOG\/51\/Nksm+WjABs87EUk7kO2zkGCXoeAWIelolhtr1yWjihuhmqa+WzvPOIs303PPMi2T7PE2LHlxxzFKS37R\/e1eJL5s9GZe1cxkn7QxvvOfZe\/hprAZF8U3POIil143\/OMm1V5m\/5h2ns4Pj1mK7e8Ze+SyDO88\/itfLc75MRolJD9L5QoHPeJh6nOJmp1dyV\/OG6f1a\/d1ZUqlvKAnmQeiB3PseKtKKmt\/m6WEjQh6yAOZx4qZ7KEQGswwpltnF3bV\/Nunay4WfIj2Q12HJ3xljttsP4gDyZNIqdvvihXmav7FNQgWpztIHdDh4wlkyb84eTnx541VRxZYEDAy\/stf7GO\/wD8XkflSg3bWij777sM1y7H+xJdWMJlTphZ+sdMmuEUST5oEn\/UxS426wrbM2JAZhQlbhHw0e0jq7bxSTz777t8Bnykf+uom4qB3TkQBSu3u9\/IJ93+1MeCdSjmuux1aQFKN8hDo5LX\/AxSfIbxRDTz758Di\/1QBRnKSNBjY22dbugYuCtgWVcDybSBmXFVmB8t9\/wcx3go9Df8xBfgKjwSiQj7668gehVYxsPpPupBgF0C8JXbeuq50wYFnwMFkpWh\/wBA6ATg3ASDr+8d\/jrg5Z39swCC+mCMUgX2nbQGhVYOrTzzB+jMKAfkIm2bkHcHOu6Llon7Tqrem\/aUOP8A2oMoarvLOAjgNKPrrl\/5uVGi4q9GrPPCI6FiMVbkHsPUB6P\/AD3xAIV514DoUTfebKLfue8k2wT5Kdz64LzDq13A1qF0Kao7gp001lrSL5D6my7v41tRiiNmqvkZRSXmEE9sBBUh7zD7yaBmVnPYwR2pi6D364ouG64UMYxiG4130yOVhrokuwEBy2Xox2YPKfF20MdTX5x7D65qmLmfUg4RsnoP09\/r61LL8Pgp776jr74DBBrMIvpRD7KFAb9zRDpdoB7zz9DzTF7DBZkxwaVPG7KpoiBoIurbwK0EdAWr7qkZ3445XmmOlehO2Fqj6rQdBOMHappXoWgV4Z32h7xyYniDaDoWpJSqJBLWEAYIuhA4IeD4A38cAD2mI8MJzjzFMpUcIDGHZVb+obJ3HjBTyBtql2FIVV+5y3eIzw0BkAeX19m5SujAsMH+YbPCNnTaE\/quEk2CmcYOsHzPaGYIJ7CbWF0XpyoliazAun8mz3VQT0uPYbB\/RRed1ySGwoKeWCe13O+jNs4QlchaBSExApPbLliFPMRlbsE+srCKOp2XYstDJ3TIJfWPCCE4y9PPh83pIj06sAu0P7FSf\/Y198Xbm8NlJ+MMyfaIIUPdNi2l7IM\/L4P9khnpVOAYgfbqPY8AHHPe1YrlfiGJM86YyUEMGImn2hheMxamjoD+slJrwX1\/gCIQRWV\/kF2DGC82YLTmlcqE+lHTNXzkQTwNl7pTTka9c2VH2U5zA0Ihu\/uYs1K08rF+h35xTq6QZaztjLGArnwgH5Vf8XA3lPZLVJZuTMqfRenEMVvD+IClcdp8M\/ZA0gqhfag51E9\/J4CVXiag44o\/bTlgP+Z6h2YMHStoUnVhaK9Rtmf67Gmlcv8AQBDzzjaaPfGyLmBoZrY8fyCbLzSyhIbiSjvZuleCbKO5wsPTxV\/S\/wAv+w+GcmQzyCDK82stvvjl12lqH6CHQwNBLwGwrS\/R7Y\/+5lE\/fFxq3QxXBPr5eau6tSxEWgGl3jRWFD21yk4xut597oy\/StMssutzHzdimvHwfovoY4YPHA4AIXn3Anfo4Iwnow\/PgAf\/AEGCMIL+AKMN5\/8ACD9cCf8Av3on4ofHf\/n4\/wD\/xAAlEQEBAQACAgICAgIDAAAAAAABABEQISAxMEFAUWGxUHGBweH\/2gAIAQMBAT8Q+E\/DR9WnqXjHfu2eSBt2oGyCNPUO\/wCAfX4W3VrB2JXtBLbDFlkQhBBxuPynw58X1+CsLuP1e2DhNtcAQcEFng31PxhZnwZZ+W+px7ntuRkFllkHBwFjBL9+H+p4s+AIIZ5hBZ+Ieb2SL3BJ9+DLbeA2DJWI\/uNHLyCScPIQQXr45BBBZ+VsuTyW9R2I4JIYPpGJBKt6dkDsjqInhnCSSWWWQQQQ6sssssss\/K2WVbHGX8QZKwg7lnOnuMDqZ22ZKfVjwPu9zxhi7TGPBllnCbyZZZZZ+Sy8Msklr\/EFbe5d7Jxn2yy3YP3wftBnPuzLJL07CO7pmMyyzkLLLLLPykl\/XJEpZE9M+zA7Pvgz9CfpeoaQZ5ASP1wLVaX0sDP+FZdcIPc\/sh7juwjYO5e7akw21OiKsg9xAB5kPst2YXq+xD5LkfmlyXbPojfbd2F0c4GUZ4Gp7nRCFg9vwJbw9uGYdaXeeSwOIfzH3ksLu1w9mPW2bMLHC4Ls2WERwcPLwNL\/AHMklmw8egfnQ+73jhPqKYeuHq3ghjjMYeDxPAfZPc8DrSwb4F6pcR+U+uH0Nlel90vS9HDdjg8A2\/hD8PrgYzN7urPH0ROUfkt3kdYMl1H7n2TsDA\/BTHYd9RyeRIJP6nh5Dw9XDnH5Qx4PUtchhKKDuzLOAsgwlym3Ry9fHt2Tx0Hi9XJR+QnHZn3XXDXWYEhZ47usmx0w8sIkfHk8exevh6PzQs4yT042c6tO46QZPU2d2\/vkeBJ67uk6h+ICYyY5HuXXG23YJI+I3jbfB423yQS68gS6OmydF6ss6s6gPB8TLWXrwzxONPUT5bdiSzwtt522222GHltt4DDyuS74M9vq9PUBdEiYQY5PFI5D4cnSU2229JJPjFthiOHwsxQxx9HG8+jB30yibbPC5HnqtL+fk6dec+EzZBEce1kydwiOFrvj25AreobfBQx2\/Cw6fi3hffj222GHxyySyyCCOEkngGRwzMcJE2H9TDD4jHrfgZsPnvAwX+8B7npz6S22xwDxyyyyzxyyzwfUwTxuSdmWFsMMPgNcvXU+O8PA60szs4OdlC1Nodk9zezl9E87OPLLLPLLLPD0nh4IIX1duHWyPD7JeN8V5JZ038c+r9PhmQ6hgvPqcZZZwPmOM8PXlQNb+ZW93aCzkzgKyADPjyz9QM1hhiLHfGQW8HqQ7x6ng8gPyPvwyyzwF+29s4hCOXjLHBvxHGjuPsO5ayLbBeuMtjqG+qL1Odlt5AfjffmO3IBInbLkHl4z9RzCb5Z4vGpWp3de\/uPXLLt1mNryc9L1PFInKPhy9vIJ6JM5dwH\/ADdDhAh31d725KMr1DbbEIPIeew7EJhDnTbbzqthWK7ivQ8CyyOA4CG+\/DbGx+uCL28hxkiR0SntZOt2dZ7u7S3wG51douxJlttsPAfC8vf3Z1duodZCrGe3U5ZCI7GLpHxOMt57k\/v+2G9NjckHFv639cEXt4kRwkGfZlruNzvnBsliQ4xZISnBHwO22y8nGDpFBAzUO9EB\/JsPdoX7TwQQQWSTwO\/tj\/3DH2B\/3GCfof8AmT7Bf1v64IvbyOADGXuu0do7OXt\/1JwCzhsoNilIHG22222y2+GxAoe12UH10gTZB7hUHGQQWcMY8DNeu\/7b60XV+n6+ocvZ\/u\/rf14e3kWyxYSPVs7vTjNkzqTw2ztOEgRxttsttttttvBwWo9QjDgup7tc1b2YiCyXOBrF4Ddj\/wB8JIDej\/zwffnsst72cvVtmx5MCO2MHgsstvDbbbeNth4Js3MOz3P0vvwoZ4Lu23wyyyyzxCyyzlZZeVtvZPIu8OEI5WWW2223zOCZFpH09p7sjkHmvIIOAgsss8QiyyZ4Z52XgNqbMw6ZZdYctllltttiPhE2EvAWclmLxllkER5PJHLPDPDw33w+ng31HvgRMz5HgeIn1e3BfTj0mZ4I4Iv\/xAAfEQEBAQACAwEBAQEAAAAAAAABABEQISAwMUFAUWH\/2gAIAQIBAT8Q8N8jjbfcG\/Iw7gTux1lgcMkknJizLOEMmP8Aa3l8Nt9v1Nhkj1B4nweV40PWfyn2PidBGfs\/1jvhnl5yWZ5PUHL36d\/mfH4Rq1mMcvDxlkuTNeMggk2yY5OTlbd9G2\/xbw+fRGWfJbfHk8LCWxkkQWQWWpfODnOVll35bLLb7Tw3yyyyyE3zAifIxaSTBPcnYYCbDvcWWWTEcHKy2314bbbLb6z5ycbbbbD4ZZBsNk9R3Fs28aBN8Lt+x\/u3OFD7K8YdRFluXx7httttll4fdttttttvsPnhs+BwRBZEEENsfvDflvG3RaWZK8P+Z78Nengs3geHM2XlW22222+348N8SIhg4JmMRA4b84\/MkYJJER8hyWN4GzbcnXUNttvJ3xtv8Hxwz5EcDgTIciJOhDnfV1dQ65AMBm8P8Z9Gbwc6G2T5Hd\/jPj0kQ140QPiWGz08HXAwdMtmEk85579QRwmlm2Z4jV4R\/CfPScHDY7YM5O7kbbYaSSxqcOnrWO2SOdTY4+I1csn8+cEEXczn55t8nZsxk2TPN8N0d8jTGzfRAH8D45ZZwX1dTE64\/Zx3zfV+8BD2b9Ph+\/geAnAJ9798DwOOjdbYzrl378\/jq1Hvk9kifZ9SR2ybydgx8gYfwH7znoQkvxwsJK+iBFv0JZbFp7h9eyOO0GPh9OR\/gv3jPI56IEzj8iKvnkwkGelkxIs0hjPpeNzXHzffh1UPqeekPDOS227l23cAJe4A+Xzxy6LN+8aQlheBNLse59SR0h2viHfg8XA+hyyyyyzwzjLLPHSejDlF1HEk43gMzJLQz2CzgTMHfXol6vvjOOq8R6BllllkkngFlkngGuXznOBmR6y1ey\/0sk2SSyeiWsEwIk0yd++M9Whq+\/D7hyORfHLOAskkngWcBCeR1s2RwHS35iyy7MiCyyIjFuues6ljfD74GXg+pmePjgh4NnB1jj85x79KT7L7CDjOAgl3Tg9GWbDdV85+2yySEno22XwXURbLyfZg5xDfvpS7MQbBznBE4Zau\/SrDW\/lqBHHeR2xwZyD5bbbbbyW2228n2JfzhsHfUPxHy23yQNbtbCCznIIIgG2tx8DgXxAfbIbiPQMB3ydWyyyYJ8ttt8S223w+o4OGXq+u\/Rt0Y4A8M4CImwcQ6X3glfsAk4+yn2HP28GEPafOd8Pvka9X\/GPfhvi4LtdYPVt1Yyxw4T4hmcN9tX1YtnXH24znTjfYPnpiO2EINvmON8u1llngRzsvCIGdTMOpdQv7LfYD8tnSDS1LBy+3LDBvLp6x68tlG6mQxf20aR4ENvhlnnvJZKsQAWo\/yWzbbc4IrtjyHVk32ttnk+80nqPnmu+NXVoP+Wh1x8bZYhj5wHxzwbbeSJAxuwjR1gDThFuuomphJpAOuPorYsktyI98bxbDLX+Wv8tf5dx4HzzJ73D6wA2MG2\/lkkwR1Ov3jYfNl8MiOUH7YfLe7sz7gHUJocDQhoZD8bsCIeGbYmbyKuRLLG+fgfPMn+RJYfON5bdtkTNh4N8G3wyyCI8ROMb1iXy\/Vl\/5J\/xNpdw4G2WWWGUPD+J7wwsOgF8\/A+eREsdgHK95E2HUNsvJCDlZeMgsss9J7X5dE0e+0pghPyB6MLeDN4CHJ4mUu2\/sIML5+B88yJXsA04fsKQCEtY8C0gy23wyyCyz1BQhwL7G6+EEOC8BEIEHDGhf87\/jf8YIB8D55kc6BO7P+2PyVWso4yyEM4ecsg9wExkcWnbMEEOJI4BMgs9X55ZER5F38QnkIP4SOS7s+QbB4DSkyyz2PgcngFlllkw7MyHDZBBZ\/E2QZ45ZZ7mfA4I4OTh8ZyxH8Twe3\/\/EACgQAQEBAAICAgIBBQEBAQEAAAEAESExEEFRYSBxgZGhscHwMNHx4f\/aAAgBAQABPxAILJJJjGMYxj5Al1LG5\/pn+7LLRn6+HHx\/Sx9XdxCXGzS+20CPwqEGGGH\/ANAs5uYDV4CAxB8CM5bzLsqBJDG\/EwALkaKDn1ArnB8TrcctTqbT5m5zYQgMsHmA+3IPfRDnw76sH39wA1cLK8Qfmfi2\/mX82vbC+WF8w\/mEPcCgwBo8fjttsNv5vhm2Z8MsuL+3f4\/J8MzMyyyyy2wQWTGMYxjWtfwqOI4uX9H+41MYx4zePNz8CYzhIQo7Z5zcfcaue6fAMMMMP\/lkHju3L6uYeA4C1HPE+C8rlhaLKPFre8nqSrnUkGscdRrEGFhfIB7h7z3CDu32vgeB848BwicI598y6Cw6b523yW22w+Xy+WWWWUt\/Zv8AH\/gyyyyyyyyy2wQWeDGMYx8bX8ao4hz\/AB\/3BcvUxxZN+nzmiZZbxMbhDHqZCcSfNuGsW8NqHnFDDDD5PGQeQ8AFeAmE5OhhDqgDhjFejmGhcINcOZaVVtCUh4jmDmMEEOS5zEIU1GL4x6x9p8BwjhDGJ+1zhsXdjcbaJo\/gNtsMPgbZ8LL4WWWWWWWb+xf4\/NZZZZZZZZZZbYIILPB\/AGMYx\/Gq5P8AH\/cEHEnEm+GcT9JzMZuXdPrIsmj7vkbl7uE8lpKGIiCDwFn4IRfRsgFzXEO8pzKcHiDnevmMgHH3JwOmQuZtueDuIQOcQcRLhLDE16j7XSL9bfzcvAnCTN5RCc3dozbEO3f4j+A22\/gyyyzLLLMv6b\/HnfG2yyyyyyyyyyy+Agggs\/IDGMfxAuD\/AB\/3CDidfgOFynwGuy225eri9Q5LvO3TcBLc5l9yhiPBZZZJZ52W+rN1AAdx1rAes+4N1dk+5Zfi35tn9xbyyISUnl3du79o+1r1HyjwE2ftHDuc20he4YfuIMPNhjbgfFoS2y+Bhhthttl8L4WWWWZZmX9N\/i22222WWWWWWWWWWZ8BBBBZ+QGMY\/iAdH3z\/cEEcI8DGK9WTq+O28PdIdShkGKZvj08Hh4Ef+KyY+l5nkc66gNOQEA1eiGuMlpA5ld5mZct2GMe4IdxgnhP3uXUfKH7LX0kPyw24Qyg\/cLCw\/PgPNvMMMJ7hPUMi0bINuy82w2w+Bttttt8LLLLLLLMz\/pv8W22+NllllllllllnyEEEEFlllkklkkkkPBpYP8AD\/cIwWWT4GMTPAD3B8QZ1CvVy9Rn1HEupDkhDwIjxvPhbfK2db36gHn4nRsT5T9fYtJ7uXcuOJZeYxH2j7Wh4Zfzb9vgTYYYdttfU4Lkw96SHrX4IVYD+pR2Y24wwwwwwxynQLCnMvjYYYYbbbbbfCyyy7LLPhl\/SP8AFttvhZZZZZZZZZZ\/AIIIIILLLJJJJJJJJJnM\/wAeAMiyySySTPBSXItDryuPqyep9XQuvgeBEOQ+V8bLKg0X1dO6vFtzd9WKT8wYyfMu5bYYbbfqX6tjhHS3mObcfDgdsq8rh9yTBr8sNAqDEFX3SdAnwEMAY7yGPx8kMMPEPEMMNm7ahjzbHfgbYYbYbbbbbbZbZZZ\/Bf0D\/Ftttssttttsssv45ECCCCDzkkkzMlnkwWIEEEFkkpeCL1Go49T9Z4dT9L6bDktDjPgnekRDDFtttsttsdPp2yYd22p3ajRCAMyzeJMukPiRks4tzqFsO3qyT7h+4bchkArgfMIcFfmVau2tMuEriHGBIGRPUa4SLnnGRWMMMMMMMNkWgcw6Ww8222222254MYssssvnJ5+otttl8Fttlll\/LLIIIIILLLJmZmSSzyZbBBBBZPEvEpSRpiHDweE+J9Fiyzh8XEQww2w2+FttiM+xl2HZ3AB1YQkBzmQPB4cuIWeHvx1ckOuR+5PjuyHIZcLXheDsnXBwXLnYh4CcmK\/ULsR+IFh5ta3agcTiQ4Y4hhhhhiCHS3AW2LYYhDyHwMY+BbZfOQQ4B9fkDbbbbf8AwyCCCCDyzMzJZZEIQMgggssmWUnNyiEPAxjfpvruDKcMMMMPgbbZZdll4th9crAuQDla7jaTZZPKfK3ckQh4kTmDZMi3D5+rv5Pu09yDt\/iE8BhI47MGBzIOPTJ\/ik9dD7O5yks4RKh5On0ypzqF98Www8kMML6tRzaA73cj8AeB8DHwbbb+AeA5nCn5A222238ss8BBBBZ4ZmZkssiEIEmMEHlJlPLEIQhAsmPL8A+LOGG3iGG2222WX7hGrI6APu1ouyG8dMpkYBSpFispoJlttt8c+pJcMomDjcCSA7WUOp8n3DrrwfNodf1yKvX7jHk37jA4guBr8wzxnEzheZQ3ibQUrg+obUI4DvY2uBOVkxOUOEMMMMMcrjzzpT7fl\/lDzHfjfJBBBYI+F\/ENt8bb+QQWWRER5Z8NlkEEEEEEMSGI8LLKCCCCCCCyySfIsGWXBDbbDbbbbEdX\/wCz6Dg+fcpd3fuQMCI\/EvIOIm6yNwkS5LTguZ3ux6QxDsMPM5vN+o+4XcBV6y2aV9Hv+bmXAcA6I0dQIV6uHVh8RUAYRwxeJ1wPEJ7eLcZ1DoJ\/MA0zj2+pANfJGAz4uHthZZj19QERTplOnfEQhBttlWzoc37R+L2kHmGI8Hgggg+LAvt\/z4EIMMMMR+AQQQQeAiIttlnxngIIIIILI9fzEMMvEsrOYIIIILLLLJLIQ4u6ePEcIZeYYmzjnqy0P8zryurPEtrYtoYcxdA5JS1I0l6erLbcog8nu3CFIX3DPUY6baarn82VEFw56\/UpKVeVWDJFnFoAa\/LOu6ZJzOJ\/gh2HiagDV6IgEV+0LzB7D2etIkAAYZEPrZ02wWbAHZOpHhGPpEIOksPVwZcy0cR4temH7Y17hhhhiPBBBB4yD7f5iDDDDDEREQQQQQWeT8NlnzkEEEEEHg9fzBHUMsr6s3uCCCCCCLJJJkkhx4hkOMQjGEwcvqVZuHxbnqdHUp7lF4vXMIWPfUfgoUgZa0+pHFnodTHLA9Eo5YC5ICV2NFmcvUoguHxBvMHN1KwPXzJrAw+IACB8EIcHMtdYYbXTgHKsghnZZ\/j5uQI45Xv+PX6lxDF92iQaZvEkqDq5224Rz7g+2NdW6whE69yZw26cyjmNEbiDxKIiIiCCDy\/6r\/MMMREREEEEEEEH5bbbb5yCCCCCCLPB6\/my2WWyCCCCCCCyyyTwkkkI8MMiHDw3iVDi57zmVDe4V2UJfE4n3knssFncyRdi53NvHd+tgMehA4OrDv5tlCSNpuPcYC+iVAeLITwSGdv8WwO8fMBsBvy2qw6+YBB692mxVgcvUYTncCc\/zCSmhhtj9nuOAMAOADCGGGfOB6N5WWAPtemYcDTexgRZZHJ0cX4kRj8Lde8hyIcI0S4sOEtH3DO+rPjq3atxfcEEEEEEEHNnn+9f5iCCCCCCCCCCCCCD8dttt85BBBBBBBBZZen8+Nt8BBBBBBB+CeGZkhDuPcsPEQ2HN235uZ4JZ7jDljbzfXxO+Dj6tPVnklebpcAuI+4fjlnjuP0srCxbDzzCSa+Jx04jAfbKuOCDicvze1WwA35ZOCclGh4kQyd1zg7esjFzTFnf6PmyWDmL2v7hw+oZc2A5QOuWP8fcHLrqO09\/4hRgNNP6x2yeDnkhE053nZ9VhdH7iYzsJFDEbYebj5zThh6+ICXbjwHi4PAIIIIIIIPwH9V\/mEEEEEEEEEEEEH57b4Iggggggiyyzz6fzL4OYIIIIILMg\/F7nvwzCEObhDIosdbIsDk8Fw98xa15kTzx8Tt5s5l0uCa85ZF8sIul7fDYiqeuU+zi0ODzOpjZnXgdQYHbZ3BMx4EIz692Dvb1K6OGOWvUCD6Y216eTbshHTDv+fUYQg6HR\/8AWHOOv4y37h4jqZgAe3v6\/cBBo4dwP49swMaQ5ff7YRIVCWaGf93L0vkOo\/UhmsEC\/Hqzj7mebHZ8kACCHJ92\/wAW+By8HKc2hko6t+HufxHW4DwEIYgggsjysf6j\/MIQQQQQQQQQWfnvkiCCCCCCyCz8eGfzLHMRBEQWR+T4Z\/A+3iyFMIJg58N9TcUmqt7O7cGwW7cGEuHW2OjiPDLo4nG\/Njg5smBzaHd5tTnht2MeD+Z8Fn+7d0cDyxxAwQV\/m5dLiy5dbIThjVTqwnPue39WSAdvyv3bvqPAztnjgDt+iB+Ao9gf3KBJwMGn7kTk4xuJ9vuGe8J2I8j8wjgmgvKfdqifKHGTAaJz+56RNPdr43vPiRsN5Bz1LxDkMPV0WTcrU5G0c3mex5IhAggsg\/BZZb+x\/mMIIIIIIIIPy3xvkggggggizxn5en82xBBBEHg\/N8M+T3nIgHbYAZ64jrbqAdyjolnNZRY0nu5pJ7yF2z13LjueszrJvqe4Uvo5+o94f6zroJ6hlpzAM\/dq9zL2O9wabS8ScnqXL09HqDgPUHAQY9Z\/F\/Fn15PUQaQiPxBB9odl\/RGEiIKof54hBlTh3Ht\/xH97QOYsVQxPT+7FgcYEhAqM0OvuEQiI8j8zgNEy4EY7fUpDEcyWGE9w8S4hiYIlsHzLghxBBBBB52XmWWX9R\/mXiEEEEEFln4bLLLb4yCCCCCCILP8Aw\/3WQQQREH\/i+XwU+ZdxDr2w7t9oyq5M6DhIq7PubbHfMHg9yzywDlmHF7BJ79w4Zq1jh1OWC92jbRjYFkVXbTPovBEHC\/b83G0Ha+4R6I3eI3OZsIPv3c7KOhf7Hr\/+wPbHFvUBZYY3o\/Xvf9THMMwcHzr\/AASEODjTgD6+Ldj94T9W9Rh3+v3KEG3huPxKT5EpxZ2Iif6MTA4ckL8JwPu2HiUOz2Hq3mHOZAN4bgMZaQcQcQQfgssst\/U\/+fA\/AIILLPx2WWWW3wEEEEEEQQf+J3+rwCCCCCD\/AMHwzPgpdy1PRAZ3aECOytjIryyn3doiYnq4dPUeWHG1bIcSS4+cAeJI8TOHbMm3LeLB2wPufdziNURLyPU6dE0yA7g93Q\/XMSSC5pGgJ3BofMIcH9QN9HzIAOeipj\/H14JwYGInDZNFDCxx+H1cwBKK8i+vh\/cwUSJQAmB9sKEH2IkQuAPhN5jyOxDg\/bNJcsD2fGSMGI1PhkjSDeJPi1ke4YfkhhnDxbHCyRO5Q31aBPSCCyyZZZZZbIfv\/l8fRPfAgs\/FZZZZbbbIIIIIIILP\/Lv\/AC8BEEEH\/g2zL4WV1shfiK693OMsW9R61+7Zczr3DzHkjwxvL4tCVGHw6nXMAcyPfV08Ty7IQTB4m+fC83adQIA5pHsuHU6qCPD9y0+\/cYCvAGr8Qhwf0j3hF1TcVir7ySTlRoPS\/wCY9YjhaJ9\/xvcyaiY1AGGZGJoiPOmcwQRBJ0u3HXMgnamMD1uf9tppkJgj\/BaACKrnCJF4TgQmSBwLcfkPmKnR3F\/eSAXgdRsImjo8j9RqGiQIHyr7nZYjjbxDPmXHgeYbFN7924ZzLiPOyyyyy22X\/By+f0nDH4rLLLLLLbZBBEEEH\/nt6\/zERBB+a2+Fl8LLKU9fhsccQjGDWPMrbW8st2y5iOfys3+E26XFf3GINge5ARerln6vqO82zjm4lOoZsScz7hDs7x\/eRmsSjRNctUOAxHshE+RM+rUigDk2AkNgeBAViukeMsQvYJpEEDoBOJ6Q9zKZs0YfeRCoQc4+YIOPfHV73kgbiGG5z\/MdPLwrgmffPx+7MK3Cav6\/nuzQ5Q3nN\/vABgYfq+j3FgFVnJvxJKWdFeA+Jwqhi\/Ny58SpTk5P3cU8OG6WPB5x49w\/MwMsD6uCfB4fCyyy2y92H\/Ry3TdPN12kofG2yyyyy2yy2+Agggg\/8tt8wgggj818L4WWWWWcpD6chc2bHl92xGtsTZzZ7bv4DwhCfxXaeUUfzLKpO\/F\/MFnv48HVDs8M+\/C6DccsA96j3GPamJ8EZTRNL7\/3BglrnBP22EQ0hoPiYoIp2DuQkLRvYHxCmL6gK\/G\/H6tgMKIgI\/qIj1LQHqq9nrIcNXNXPfx8zshAI4cf+6usQacZ4JBBEE9wa65ijgIochLnM3TPBE5GXQiZkSCb3\/Uow1ujc7y9w5xEvHvwzh6e4kNYM4bZZZZZZZfA\/wDo9tldd03T4httllllllltlt8BEFn\/AI7422WeYII\/JZbfC2yyyyyyuBsK\/dxKNctinUVWz03uHCEPCwMy5Wuwwvqxjh4JkdzZjAxLgoWT3JJBfrrFo99EDLt6lZ+Ds3xcn2plzjUPqSQr4Q35Ms2qvKnV\/cG56tAxlc7dYfVngL+Va9v1dRBCt0Dz0nw\/MJc14XTPTn4J13FyuGfQ8P7laWDBeDb8dffg1zD0OD+51LOODQftgkHqX\/EAToGH6gYffUager7iQRGHjwO\/DD92T3YDaktJZZZZZZZX\/a+WWWGXTdPkBtllllltllttssgs\/wDLbZZZY5gg\/Jl8LbLLLLLPgeyQQchB51ZY33LteJAdw6z3x3jsMCR2sGfM9UHxEJpJkOJOYmZeI8snF28JZGjpceKE+Dnr23qPkEiDVxwjcDM4jDg6iO5NEEHOHOn5lCFcrlX6P9SsIDYan67P02BxsOXf88WXbHGOFcfzPtnLD9es9\/ucWg53kd\/3aQZA687\/AN\/jwgEeR4T6k4GhRmkr1I6JwjAg45d3w6PV2QYHHbHaQ8ZLY5nqeGGzx8tqT0lllllyWWV\/f\/8ALDZP4b8UNtsstsssssttn\/ntsssssst2CD8d8L4W2W2Y6mPgM\/oDERvxOoxc5m5yXKz3t3kObZIgjiIo+C7XbkiBjBxLiXib1PU8E9J8w1ng2XNvjYsBsxzmWQjyJGy1uQnIETj6jmCyGQ0RTU3B7f7SnaBOeTH0EGhwc7Nj9Y+Aa404eezr+8lNM0UxF5493MO9V3+1mf8A55SEtNNOpjHXozghrCGgvr7sOg+ycEemSD4uGY8cnhiHyYcbEf4tgtCWW2VsvcvMr+\/\/AOWGXg6fDweDZbZZZZZZZbbP\/LZZZZZZZj3+j81tmWW2YxjGLKWYY7yzI+JFfiU8xBzEs89QfVtlzGTZzKX\/ADo0+LGWcyceC7MT83vWeTixjAdJ1DsQR4TmeLfQykhGRoicvuIceoiPiPh6uaSnD6H\/AL\/F6qIjr6D1GIJzpvHUXuzmz8P6TGBsT192kScgGbBdzHHHG2jydXHHZyPwwqBlMyTI68ep58PA2wc7cFstssvMuZS9392\/z4Gd1eHo8RFttltllllt\/PfCyyyyyyzGMe\/0\/wC\/wfKy2yyzGMYxjFsstE+SGs+GxI9ZAn3YKErsQ1uqfdbALvv7qXmATx4jnzZxuS3zux8XGYx5bnxJngjyOOxGF4JW\/A8DEaYWj9ydXwJMTT3EWaWUpeABv8PqBAcdKV\/d6PiPOWc+DvwCAETETjJSEcB6SIiSqDgfp9Tm6QF3Zm+65LZto5z1CwsT3e47ut8NxkcJjGMWUuXi\/vH+fAy5ui6Lo8R4GLMYssstv4742WWW2WWWYxjHv9H+\/Cyyy+Flll8GE+BjGLLMuZ8WwHvm4Ds6B0T55nIN5tm6izMjhEj9Wz+7dZxzO7tGrYdvbJpDrGAt3q2suSTIi2WLRvzBVeTm4weuiQTVOCdIRNIdIY8ER+D49z4GGhWiPIzkebyjuJAdOGeN\/fufsyQRHpnIh6tkVDkuQ9R4y67lz\/NsXBMYsxiyux9v8+RlzdV0eI8DGMYxjGb53xtsststssxjGMYt\/p\/343wssvjZfIMYcJi22y7sspYjnUnIc7BpLir2Fsx6cXNH2gCwoZQrMWQQwXuDSOLRJYdyVhBpz\/M4XwFo8S4uDfm7LMiJ6gslPmMn+GQAKOZkyNqtjwRHgOp4i+fwzeI+Y7koFdDXfXH9YKoVHgK+uId4SXsCz3GhuPr5iJaGa9zIkRhh5mf3LBcRBnExjGPgPC7\/ANv8z4GcvJHgYxjGMYzbfG2yyy22zGMYxjGMW\/0\/7ltll22WWXwY3bMZsttttssssVH4meB7nF\/cfK3erF6sgRgmq\/EKiZrO7ZKx6lPUmZHTKjx1A5Zs1HjOLUD3xDzPks468CZvg8Ge7LOueZiF49wFrs9XOhG0fuwQZxJCZxDEMR3559Xrw+MgkAVeA1kByQpplwiWmt4EInCOexvcwbPw+SFhw95bnHsjy8PN91wTGMflPgM5r5WTwSl5I8DGMYxjHwbbLLLbbMYxjWtYxjF\/h\/uWWW3wYzH3fbO\/c\/aYvFvlbbbZg1z5gxjR47uVh03FvRbu5CA8EIzTbcB5tU77n4Sh5h5uHguodMbo6YdIMdWKvwSIuh0cfu5WvLZLJ6QP5hzMNtuQnphm0IFC8y5ycGxVAsAiJNE0YdjwdeC22PGzzZGPchkRgcONgw259h+NskDbstTd\/wD7IRHkeMkGIQ42dCcPUddeePa4jm4pjGPLuY8vq5Lc355sGTwp+aPAxjGMYx8iy2yyzGPkrWtax8C3\/j5llltmYWPuy92s+BjCDLLL4GXi2RZcMI4xkNB+7n6hWpxBwCNEepg7xKEFVlBrI3mxmXuHbpE9TdnN5j+iBU59H3coq+S5u8nqPM9+dthhjSOJYIbZUIg6+JEHXNKHwR4PwH78JZ4OpShYCcH5uNOfbeslwSY5vdzZwnIxqn3H3OAxGPDwWWXBOWdPfU+0x4WzyZ22dh\/tY+rCSJ+YPAxjGMYx8CyyyzGPkv2+FrX8cLf+Pm2WWWwsju7MZXtv3mp9NzjUPUNstsTwSchZAyTnmA9QsZuyKHL+0IyAdbrHUc1C44mcDuMO27eo3eblJzuw6fMumS04cs+A6f0lVq7ZZ5HG4rrdrZ8kMdRlvUSenXMeznMJ3GI\/AH5lpEQw+UZA7WYgUR1j\/HxJDGEbwvlu4JAWjwyWcKHLVPghUVYg3H3HR+oeY8A9DIqCibdLvd3HZcBCzieXMzpPTwWW3X5D\/a7uLHbBsyGXgPAxjGMYx8CyzGMfwq\/b4Wtfv5CEXH\/HuWYx7WI8ya542P3m84xEINvM9xEaZCAtvxbxDp2WjwHJ8wurfv1asGC7kBOabbHuFHfdj2kIYdk9HuTMl45nxxzGHV69SWnB6nXlebJPxWJLdvOeCIhR0lBXn4kHnx1C9+gRNBE0h3GPB4MDiah0fu4MOXU0+D9RivIIboP+4DgAB6DLvmYi49znqca74bhM6sNB2OQBTB7XHOTz3Ey6TIdhTp+SUccPPhcuA\/xHCV6mOHwfAzdPn\/AXdxd3FjOI4hiEYx\/MBsxjGt+38VVrX8IITg\/69zMIfVgNop4e\/wAt1GImkMPEMRC3i5wyDDMkc5LMIAfvuAOOp04NSyzN9ENhB9TtOFJy89WN4kJ2QOMfDrwc0jqFwJSb3PCTmziz8TmeJ7gmfARERhFHfTMl37nIaDJMnN1PxMDH+IY5+ZccD17bBBbyjiP36u6+7m6v8fMOMHa+1+358hxZZxep8cnJP0m61gvzAAAAcB1keOEc5OPZJgCDPsfiVVvDLdIZjODctukvFtsv\/GFrvF3cXdxZyZHEPgxj+YDZ8X7fC\/efv+Kgx8ghBhsD\/r34c\/d90zuM67biuZnh34coYbgiEHXJbxM+rLi90vPDzKp24DNlHbIHPTKxDPuWLl+fiFvEOMI05NyyI\/FivDfv\/Ww+yD0x9o08QTMhdMDqB68DykksvdkHPhcvfjLLIPBEb6sDfm2Dq5FlznE7jJ1OAPe2BKgBusa9N29EPB05XQWLn269H6vXUdT+Sy\/idTyfNgj+0+G4EzM1yRHLrbLL6+ZciE5Sw\/7vRaWvq7uLs4s5Mni222X8gbbP2vsvsmtY\/gAY+AYYYYbI1\/zmAi1L07O51cTc1yTDlDsMPEQh7bHXVxEY7gBMu2cMZR7LgH1LglyEyAQDktCr7bMBdLZ9rdBJOQWrZcfNg3BA3i4MEN8GZJn82WcycwSyXnwQfgeCJtCDjdEmS8x6mE6uA9fcuGCGfx8wI1Lp7IYQOgj8fV68MzMS2w2kSL2cP3I2GPmdw47lw28PMvFsvhu29c2893\/W+CTwa3ZfR4xk8S222222222z9p+01jNll5BbbYYiIs+3vP8AdjuMpLCvcMwMgVL2Rp7ld4iGGfNtkbqXIA6fE+\/mAcyXOQ1pBydQXgB3cgUM46iJwcyPiRvUDOo+EKCDnmA8esgY\/MHfGWWS4S8+Q\/AJII7vcd2Tb08hK1ofqdGc3U+yOOIY8Bx1Z+TJweHxsPgnQP2fskCguYme52IadGX5ZHOS2222w8X\/ABvgllYtrX1fRYwzwWWW222222a+TZZZSlL4IIIIIJD9stHMOIMllxLXJcvqeU9w56IcEQmWRHTYB93S7m8PWTzwjnuB7kBgczmu8yHTix5WgBO4nEXBjBkPqziyzPXkvicejIOcjr+o2SeAsOPwD\/xCDm596YEickQEznGxl4PA+5adyAq4HbB6QPjwT1HX4JepjyMJKAul71DisoCj38zBM3NGdQRHMl4ll8jbZf8ANwT5quw22u+w2Myy222222+Awx4Zl5EsggggggnTPu2vMFllxlzdmzPVycHEBkPiNRXF2nQpYGeDqWOHsihrIWbmEaGvcJ2EdclCKK5uB5kbZxckzLLOIOIIIvfgO9Icz+o76lgy75IInq9eMsjwRNWnYwDti+5AXbN6zg+H5gQrh9\/MH0iA54D3sgQUNBwZb\/SGzbrifwb+J8ZHeThsNz9siNl\/kfcR2ExD02hxA4kZCHq3u73dLtPnevGZfH+Ivsn7T9\/DlPJaF32GwyZbbbbfIwxHhnwSSSIQgQQRBj9tjyQ4JCRjK57Jq\/6u8RAEOeIPuNXMnnZ4x48bkguxv6RhxOZ6kEziwG4weII1JHCFwR7NmFkJGfGcTbDer+IfXgSC5M\/AI\/I\/A6jTrucg9RnrcdSOKnp8T3iTlfJBu3N3j3DKkY4Fq\/u0G5wNB6fKfMh6s8nc9+Hq6IzUwcPBvxv3JY4TQ5+gfucdPIAdPn+OLKI0555fu4BqZ1YlgeE+5jDd4MnSBHJ\/U+PXERYDvX+An7Tv3EIQbkW23dYQn8dthhi2WWZkk8CEIQhCHH+f+vEcl4l0b2k3T1O+Dcjo8RMgh4DR1c04siODxkMKoc4I75u3EcCs+5btcmJxpblya30t2zZJJLI8jblvv5k0gziYsMtV8EeD\/wASOvuN2CFD1sXdOtkMPH0fn6gMcek+GBcIO1DuWhE4p7Y68JBNknlJQKoHBPxVqjjp2f5sSSXTDXe+\/uIACgQ5Og\/z\/qCJLeY5PqJGNR0\/MvLm6fEFTp5PkiNBc5IBWDwz\/qfGw22J70f8E\/eKQbYnK5F3XdHmZ\/Ihh8LLMyWeBCEIQhDj\/L\/U4epZbSOSc3I6v0gg+Ti5O+PwkORDJlw1lcjqM8pQYKym2Mwh5MTv1JT93F1gdHcOOYIOJkkDufx2HwnxZAMd+SCPHqyyCfxI8BTkgLAfdyQHzYJOE5D03GHCPH8XKIi0RufxI9aHFXFfojrjf02T4zn+ZO\/3ZZ8Tywe5cc959xnaXEdC7\/kYlqPdOv8A7G8yBg6J0+z6yA5pV11lmbgygIjwnzAeyOT3siMEchHKpx+vuyxCeVPiZjsU\/ifxxL4H+PE882YV0S4j3HmZ\/IYYfKz4yCCIQhCEIcf5\/wCp8Q2y8cSYBkPUHEQnD1ZR4AakGF07LeCENzmXhm62ovE+93Pi6dywm+4x16gA5G2xkyI4kkkkkku\/PVsmyALbD68ERZH5ZZx1B9QcxBHzY+pDT0xod5lpFx631GHE6fs9SAxoc49f0kEAeXgp8Q7IT68ZJySWTIAe3+n+4ugfh7E4R\/XDIFcEHXr2fcw6lwPp5\/lsgpdmz0uxPZceAHPAYfxLyv6os5J+dhmg+4jca8zR\/V6mo8wDDg3q93v8MD+n+PA8f744zXx6EvFn8hhhhtl8kEEEQhCEIcf5f6lD4WXhjyWceA4eAhCBHmeIuGRdb1OY2B5uF7sbxaHbcfgh9vCwjfqHSyk4ssskJPiSSzqzynEHN7tPO3jxkEHFnXgsggkvuz7s4gg5gggs4k\/rAWoSoRIs3Th8kZYxN\/U\/CD0uG+tt1MoMHgjE48ce5QOXDvn\/AOy8jPVeiwLOHvJ836f85OUjlryDzj+\/T\/EaOtOAG6J\/Q+GIiJEJvJv\/AGyNdXfAc2BzJyAQcxOLdkTgPeT5lwktT78P4f0o8CE+2PtM\/eK8J7KZ\/IYYh\/EiCCCIQgQXF\/49T0h+7fuepnz9Q39QeQIQgQxuhJrkGGeE2OQJzL5gKxFjZ13qFwQ1f3cbO8wLEGS6+T3+BM\/qzvTmIg6H94ILII8f9sFlkweMs2CCOGG3TqS1WkAJw9SHPiJzYd7oq+H4hXmExLEFoco5D6+7cbHeFMX7S\/dqJoFQhAnG4O09LK6YAKDB+\/31HQBgFe+nn2MwatQDgJ2\/x3+iTNygfDhxz9yl5bIureZxtp1DchY5PRIUfPh8jLh+i22IU8ZCLKUz+QxDDD+BHgIQQQQQXF\/69T9bD9x+r+JI7uhCPgCEEENyfOq8MhwEjtCSacW8luUH93Y265AkhaIQ8x9o37um7LOepSw+GSOeIUV5zj9zqq9rsEEFkHMcMX8+M3zkdwQeTM5uLjmeo0jmMQ685CwUHKPST8r0h9vzYBMx0puWAdDy3Z8B6tPUmn\/2cIrhdHyf7gJch5z9H7Jgdk7oYv2z6VV+WT7iCTgvqeJKw3v1czi0fqHLPh89H6LbbbbYYYbfIk\/kMMMMfgRKUvAiPD5\/69S5LtDxBJ3J8FyE7M4NgsPcodT5l5Zbbqw3WAMinUcJYbF\/c04m2uWMZfiWOHEY9x944zxibsNtvMc+r31h83FrQ\/z4CPAXRe7ts5uPdxmSYRe73Fx7uPXgcYRzZT1bL7kEXiEceE2BCvQfJCaCJpD4PmfnFgdh\/cCkDB6CznwnG2bzPFvHM9Npx6g9wZxdo9pYZ8kNkzZ6jqyI6frxv4ER4SSSST8RhhhiPwGGUpQxDwaP\/XqcoYvmYcd8GxOD3A+ZHpn7XN3HUId3uzmde8lObKyEjH4hxx3OCtp514A5gEt2e5ju19Wvu22G5h+PB6tIETlx+rP6+4ILPGcWcdwWEFnjIPAfluWvc+jL6l0HIChoe47DYzHO3GsirevqN75+MmKJ9Hb+p5D0b7f5tdKqrqvuFOLDS6OI+71KHDiVWxYUnFwvnDfU\/Ti0HJMvd78HX8fhlkEEFkkkkkln4EQwxH4DDLyBCHhWv\/HryKPXhPGTnnzMfa\/awO7VvVvE8G8bYDDJTFN+53Xr5ncHB7sgHRmRDwNQl27dnrPM+djl8EfEcREe3b6gqXvY+l+lmeo7s5s+b4zxnEHHn0xesjuOpbdPGyy\/0t75m1yQzUPqPk333u4gYnIh0y5gxi7NFEe5N307tA+oix9yKMiYHmM\/m6S+5deuWMd38ZDxbduJehaA3wJyZ3MPMmPk6fhkEHgPAxiSSSfgRERH4bDDEIQ8f7y1\/n\/q63a6xe8vmYebJuPuPvfvP2lvTJ02OHMJYYMKd3NJwcxfIr6I0AiwZtj2nV3m9rfgS+Il5ljuO\/B9+B4+5AbnMFa\/hv0v0s+bjTL3Ze+p8Fvj4\/A+7TZeJePD+vH9YOd+IBxOlrA1maHKZz2P9oED08XN+DKEePcHNHWWqryyLku4AJdb1928cwuZ8ykI6vcbTlzm4\/1k+owwYd2YeDo8hBB5Ir5gISST5IiIYbbbfIwxCHkPf6v9eTpHBbx42GHDwHGV6Y1DLn+bnOLEeZuQ51uB82cAZw35TIGjs4hpn13E28DACcNm3t5FP1I7Z8THXd\/ML76i92wrwT\/Nn636eH6z9Z49TiSL\/N\/nyTH47bLxLbExfcOO+ycGgaHxbY7jbuCaoGGnG6fN7k4g+5IbKU93PfqzCW3wJ6g5e5o6bxYhy3g5u4A9udRmcerownkk5kjosggghHwbk8evDhCEkknkiIhh87LbbDDHkEWv8\/8AV0jwGGWW2GG2WGUoOBCPHcNMyNq9XDoZ7+Yuu8d8QWcD4iwqmzL6XuHJd+JtYQfAGc2B4kPdnGHmGPuMvnJrgcswzn3P08WPg+1+s\/W+mcMke\/HMR34JbZZQ6bfDfXgsg4g9zAnIxGdvc2FH9wjxjevUripAT1HJAoBZmjbn55gumXmWBzC3eYA47YTduTgkrJpoL8TnAmcMqrdHIQnmSSDg\/UFkEHlG2hdfH2+IQkkksiIiGG22W222GG222GXP8\/8AUc8Q5hDzHUtssMMNvgbncTDB1uSAet4\/VnEXuNI4TiYO+sljyPVhpOJQBrvcvZ7u1cseZCybK929tRlb3Y5sbsdTaByCMDA8HwPKfBlnfE678i4mT8m2W4v3bLZHHg6fIfVxtc9kM8BeRhuruXGFVzfiCBRecP5SfMkkkGxds4OD9Su8sF4HMJ9n4nrAOd+YRNFHD9QIOXlyHHuPEhvMhllxP0eTPBPmfV1INLYu38HGJJZEREPjZbbbbbbbYYYb\/b\/qO4YbbZeZbeYhN225scBuKP3LRz6sPDcMv7idRdcXZ7vtybgV49zmM53LLdzOWB9QBneertXG9fF9oYIfUnWDJHrwW93qK4DVjYNfm4AY\/M4eFZ4dSfUkklklln1JaHdy2FnEceD3brL468j\/AF855Ln1G2QcRBFMe4oSPWtoRsfTLmBHv9RILF0fmSxB+MlHrwIi8EDswdBO9uJhg3R7Y2uI6Nj8mDkOeYXLkzu2s498TiidT7wdygxJ4ebVPkP8eLGJBd5dXVcU8lpb30X1+Fj4AgtDtD9x8h\/W+h\/W+p\/W+p\/Wx8n9ZPyf1kfJ\/WB6dttthhiG5Ofv\/UHIPmNOrfmW2ZvhsPUOwhDlzP1Dkz4jh16iHHJItQ+oRBfmOYNzobZL29fEETzabJCE6hx9wdf3Ozdy4x14B3g2XlrG5kDYQMIxxly+m+1r0SHGSWcSSOcWcc2WTqfAwkyW2ZbZ8nXg8l8XuCCCLX1HUUndQTrmFg4Gb3siENOP3NBEaC5v8woEPAO59RpqYfEJBzeNhQDj7blYXskOObEZayHjg+YtTEcsp5Vyv3a0PysjQw5k8me5CyfSwDOgPwo+DtcbDxGrNtL6r6r6vC+AIL1\/8Pa222GGGUN\/qiZepmXwuyxw8DPc4Z0ZajPbmQw0ieu4Lku899ltKKk+jHV4gwWOEHnfuAp8PMIg7yCyzphPRjGDmEOElF1blRFm8243BYOBk+kb67h83CDTZ0WkguSPxJJZZZZOvBwNkzMvxa+58\/xHffkN8EC3uO\/AWb5STwJakfq2dVflYAC8bLJDc3qcR4e84h9Xfr1D36ziRW5Djn6hA4DkPbEPB8ce5AnhOPmQGCN+ywIw4fIPbONclp0cjkXsgIfqfIGsIMnk5y2DSb9V9Fn6sLIIL0\/n\/wAdtthhhhuWQWTweGZeYZZcjDbeI4dxMJenhjouywee5EuAcSAxOepMA\/rBFjVVsdoPFsfdnwbBztm82cWZKyF8mIlOQkTx7juBzJnmaMFk8NuXXm5OOJJLO7PUmcScTPUITwy23p8Zvj3J4O7ObIOILPUEQWWWWSL15Y06nW7HrYBgq+o1AhBqtTqwQw9sQbnw\/EsUvwRQBT2\/EHdPv2yAV+H5gIGetsYOV7troWGOLaJ9F3Jsxj4CCEYwjRal9F28WEnMEECipwD7zC\/7L\/V\/2X+pydejH+9ocR8z\/iyjfwg\/3lyY7GU\/pfL\/AC\/\/ACnztsMMMt7g+LIcyZbrJJzdW8Sw4yy6o+0K+4Jj\/MPK8kOE6z3DhdsDkckDtYdahNpvFp4HIU0HjObX17LeT6l5sl4kH02SMOiS4NLe5fJBNPUcOIOILOOpOJ+lr2QnpkyZ7l5lnqXuUuWxsvjuyI7sg\/vdcXqCyCD6gz1BBtlnHVn1Z9Wc9SeHwyaHph71CQ6Tn0WgasPiRmBeNghVVe5QRnx829BjwO59h1wPAQg44+UkHA\/dzYeGFjNyZ0Obf0g\/xLbNsmPgKfjWAk48XfdtyQQRabEs+kWXu64bwGuIxa4Kz2xDYY+zmZ\/LdZSOo3v\/AHYowAcs9f7JMixXszeJoI9n\/DMvjbYYYZbvhgnMCEnM3abbYeZQy2GseLjfT3FVnSWhQY9OZdrq0b2R44OJ4h85ZAoD25HqOzPB+106vTiPhEOHUcIJJnqG6XGXPEpsjZEnma3lefAst2NlnNkFkFm8wWc9QQWQQQWWeMzmbJ8Z4\/cV4\/E37n2epOOsgVctcgDtSo3XhfKvvJ3eu67zzYgGHokhgwJIcebF7PUmY+ZzQq+ovGx4J9niHYN8ClPr+CpiDPC+A3wcsQX+y\/4Ptf8AB9t1vJ\/hu\/5kW9Iv7JvjDH+p\/wDGJHVq\/e8\/5v7b\/hmZ8bDDDc9hwfEf2k4hzJJCSXxspR3PFx5h1n1YLC0O5DQRfjmXGOI8nd7mAzjeYAdAZ4FbwWogNgPUFnhJz3PcQa2q83B34Xn3PefvfbNavMvEEkWWQWcwWQRA+LGCCCILLLJJJs+rOfHbk4opkAR5+pbWcDKHGH+YJG4OM3uVAy55RE66jtkTNvQtuPXEww8QAAD8yOBV9suz5f58D2GxqPrH0j6R9IpizJZZiy2O3JEF\/v8A9S8UfQPXWPP8z4IYJo\/pn+5oCtE9SYIsMWn2Owsa5aR\/qOYFwHd98OxwpgeXeT3MkmfIw3Nf4ggk0y5oZMId2XXgepcl1ncsjycR46\/ix9zvEE05h5pEznuc1zIfojrYefBEwar1ECmlr9Sj1JJzdwQR4ZZZZ3CDJzzYnLc\/d9l9k853Kl8P78BBzBsHMHFn1B9WfUEQh4Mggg2yySbJ9ySXqbOI4RhO8jsyRQT29SyI\/khE5Pqw4AD4nqe7mW1pbhcej2yBqh6JPyJE3XmX9V\/mUthttfTH0j6ReEksxjGKU9xBf7f9f+HzJJJPgi7v8R4hBzd1zMkkJ6+\/C8x4rqMMCHMeJaAROpnsfZ6kYj6IVT7kCxsu\/d3x6hHJbncGoHK8E7wDmj4l3wzH3FsXuZZWZcrd1xtwM79zNt55lLi\/dztnMQhA8A+IS8wQeBysyDmyyCCSySTwn1Oe7OOLJg7gnMGfcIBADuL4GyjkumxRU9Xcdhai5XOWr1diAbMDnd\/tH6v7l\/mc7lkOvEeBJcsPIMYssssRdf5\/+A0ZJJJLIIv9UTOIdQQj3JJCTmZifM+rtdLsXrDYQBEzHqEuo5Axkr+zE\/37stDr7nFc3mzGFLk3G9hbh26D6nX6mXC3Z\/V\/ER7tmftLzYCbbqfF2eLulLbfxL7y33B7sgg+oPqyIQhDUco8jLIILILJLLJJOJ7\/AABseskY9RtEdtxgpxPHIaM6V5f0LllavKrze7TLAx7jVqb2HzYR3Bs47xrH+Zz8BcTMiWWfgIxbZZZbYZXOgZu7fd\/d\/wDL\/wDQf\/l9n93\/AMsff\/P4k\/f93\/yS+P6z9Epu5JJZJZBBPF\/iZdIhGSZyeBRtmQR349i9JcXXwIcO8i+gjoOydGm+3q5ojeEhhwU63qOEsuocrGgAGGdS22WW7eTYZbZcuDuTOrfMrgnyz7nu9222R4CCOUQIgRCEyyzwFlkElnMnPhOLOPCc2SScREfPuU0cX3FsdMcQTknBQfadhCq6a\/cAm8CQgc5Oyj7njxzf3DLwZ5fZfbHGeP4Os222YxbYZShjwkklkkxjGMyC4LPid0nqEk+QK9SvfgHPj6S4lzPiUMttvNnMnPc8S2yzhn7Tl5eLO9wX3A9eGtvzMgOf6z\/mXd7+ClLNln1BvqCCIEQILI1B4Z9QWeM\/dn7\/AAP3HnJJJPDMEEeoUdHqBB3fUIBC3Beo+vu0lSp5fmD33vcXNziXLxI6ZEFn98wzyxsM5vsuDueHd9nhZtssxjFtlKUR4SSSSSSYxj5Bg83fi3DxLJJMYk\/Sdep8QeHYnOeEPkYZZZM+A\/fi4fq+HJ+3Pxcvxc+LLTuH7tnqTzk+ZeJ3tdp85xBxBvqIQ4RwgsiBBZx44y9Z4Txln1+WbM9THfhJ4h9y48MAUSQyGnrZSyr\/AEg55YDtOLc11rcqzrkuVZI3Z+2IZ2Xh+y\/adzFtlmM2WW2UpRHjJJJJLLJjHyOT7bAk+eCHiObJJJJO5J8DAz1d5cfc+PuUMMNsMM8JZxY+7XjbXXZ48Nqcv8XBzqPvcvcu83Bzf49SgXaSlKXLLZ78JAvUfcG8+AhAg8BBBZnhn8C238iTwe48dLtHgdQlh8wZECqZHJ95CI50fdsOOHdzmHUtQywef6S9DCeVWI8HPwEYstttsttstv4sQWSSSSSSWTGMSDv8v9WuIPEGCSTmSSTu5Ez9J+ngGJLqXUociHK235kHVy9wZyxh3H82gu4fNtxufU89nPB+5\/8AqOXmvXGiQnNkclku\/BMknjII1dEQ+kQOILIIObIPKy2w9222+Vthgsva9oh2SfAirhYGAh792Pzks4dtvA2Qpsnu3Lccnzs9sQQhBEWyyyy2yyyy2\/ixHl8Mz5ZmHP8AL\/UOPEjwz3Pc+7OJOPB6897r4ERbbxLzMuJTiTf3K8y8yuS9w3byvgle3n73ae5\/AOoIOIjweS9zPU9T1Pg6ib4viZ8HuJ8Pbwep6f3Pc93cgOo8D1OVCSpfguj9THd08H4AjyzM+WZ8f\/\/Z)\n\"\"\"\n\"\"\"\n**Importing essential libraries**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport matplotlib.patches as mpatches\ndata = pd.read_csv(\"..\/input\/covid-world-vaccination-progress\/country_vaccinations.csv\")\ndata.head()\ndata.info()\ndata.isnull().sum()\n\"\"\"\n**DATA CLEANING**\n\"\"\"\n\"\"\"\n*   Here we check if any kind of NULL values are there.\n*   If found, we replace those with 0, assuming nothing happened there.\n\n\n\n\n\"\"\"\ndata.fillna(0,inplace=True)\ndata.isnull().sum()\n\"\"\"\n**SOME BASIC INFORMATION**\n\"\"\"\nprint(\"Vaccination date starts from \",data[\"date\"].min(),\" till \",data[\"date\"].max())\nprint(\"Total Countries vaccinated :\",len(data[\"country\"].unique()))\nprint(\"Total no. of vaccines used\",len(data[\"vaccines\"].unique()))\n\ndata.country.unique()\nplt.subplots(figsize=(8, 8))\nsns.heatmap(data.corr(), annot=True)\nplt.show()\n\"\"\"\n**DATA VISUALISATION**\n\"\"\"\ncountrywise = data[data[\"date\"]==data[\"date\"].max()].groupby([\"country\"]).agg({\"total_vaccinations\":\"sum\",\"people_vaccinated\":\"sum\",\"people_fully_vaccinated\":\"sum\"})\ncountrywise.head()\ntop_10_countries_vaccinated = countrywise.sort_values([\"total_vaccinations\"],ascending=False).head(10)\ntop_10_worst_countries_vaccinated = countrywise.sort_values([\"total_vaccinations\"],ascending=False).tail(5)\nplt.figure(figsize=(15,8))\nsns.catplot(x=top_10_countries_vaccinated[\"total_vaccinations\"],y=top_10_countries_vaccinated.index,data=top_10_countries_vaccinated,ci=None,kind='bar',aspect=2,legend_out=False)\nplt.title(\"disttribution of total vaccinated\")\nplt.show()\n\"\"\"\nFrom above graph we conclude that :\n*   United States leads in vaccination distribution.\n*   followed by , India ranks at 2nd and then by Brazil.\n\n\n\"\"\"\nplt.figure(figsize=(15,5))\nsns.catplot(x=\"total_vaccinations\",y=top_10_worst_countries_vaccinated.index,data=top_10_worst_countries_vaccinated,kind='bar',palette='Blues',ci=None,aspect=2,legend_out=False)\nplt.title(\"disttribution of total vaccinations\")\nplt.show()\n\"\"\"\nFrom above see:\n*   Montenego ,Tsunisia and Suriname are lowest in vaccination distribution.\n\n\n\n\"\"\"\n\"\"\"\n**TOP 10 COUNTRIES THAT ARE VACCINATED PER HUNDRED**\n\"\"\"\ncountrywise_per_hundred = data[data[\"date\"]==data[\"date\"].max()].groupby([\"country\"]).agg({\"total_vaccinations_per_hundred\":\"sum\",\"people_vaccinated_per_hundred\":\"sum\",\"people_fully_vaccinated_per_hundred\":\"sum\"})\ntop_10_countries_vaccinated_100 = countrywise_per_hundred.sort_values(\"total_vaccinations_per_hundred\",ascending=False).head(10)\nsns.catplot(data=top_10_countries_vaccinated_100,x=top_10_countries_vaccinated_100.index,y='total_vaccinations_per_hundred',kind='bar',palette='Blues',ci=None,legend_out=False,aspect =2)\nplt.ylabel('Total vaccinated population per hundred')\nplt.xlabel('Countries')\nplt.xticks(rotation=90)\nplt.show()\ndef anime(value, title,color) : \n    \n    \n    data.sort_values(by='date', inplace = True)\n    \n    if color == None : \n        \n        map = px.choropleth(data, locations =\"country\",\n                                    locationmode = \"country names\", \n                                    color=value,\n                                    hover_name=\"country\",\n                                    animation_frame=\"date\")\n    \n    else : \n        \n        map = px.choropleth(data, locations =\"country\",\n                                locationmode = \"country names\", \n                                color=value,\n                                hover_name=\"country\",\n                                animation_frame=\"date\",\n                                color_continuous_scale= color)\n\n    map.update_layout(\n        title_text = title,\n        title_x = 0.5,\n        geo=dict(showocean=True, oceancolor=\"#7af8ff\",\n                showland=True, landcolor=\"white\",\n                showframe = False))\n    \n    return map.show()\n\"\"\"\n**COUNTRY WISE DAILY VACCINATIONS**\n\"\"\"\nplot = px.line(data, x = 'date', y ='daily_vaccinations', color = 'country')\n\nplot.update_layout(\n    title={\n            'text' : \"Daily vaccination trend\",\n            'y':0.95,\n            'x':0.5\n        },\n    xaxis_title=\"Date\",\n    yaxis_title=\"Daily Vaccinations\"\n)\n\nplot.show()\n\nanime(\"daily_vaccinations\",\"daily vaccination around the globe\",None)\n\"\"\"\n**COUNTRY WISE DAILY VACCINATIONS PER MILLION**\n\"\"\"\nplot_1 = px.line(data, x = 'date', y ='daily_vaccinations_per_million', color = 'country')\n\nplot_1.update_layout(\n    title={\n            'text' : \"Daily vaccination per million trend\",\n            'y':0.95,\n            'x':0.5\n        },\n    xaxis_title=\"Date\",\n    yaxis_title=\"Daily Vaccinations per million\"\n)\n\nplot_1.show()\n\nanime(\"daily_vaccinations_per_million\",\"daily vaccinations per million around globe\",None)\n\"\"\"\n**MOST USED VACCINES**\n\"\"\"\ndata[\"vaccines\"].unique()\nvaccine = data.groupby([\"vaccines\",\"date\"]).sum().reset_index()\nvaccine = vaccine.groupby([\"vaccines\"]).max()\nplt.figure(figsize=(15,10))\nsns.catplot(x=\"total_vaccinations\",y=vaccine.index,data=vaccine,kind='bar',aspect=3,ci=None)\nplt.title(\"Most used vaccine\")\nplt.show()\n\"\"\"\n# TRACKING VACCINATION IN INDIA\n\"\"\"\ndata_ind = data[data[\"country\"]==\"India\"]\ndata_ind.tail()\n\"\"\"\n**SOME BASIC INFORMATIONS**\n\"\"\"\nprint(\"Basic information about Vaccination in India :-\")\nprint(\"Vaccinations starts from \",data_ind[\"date\"].min(),\" till \",data_ind[\"date\"].max())\nprint(\"Total number of vaccinations administered :-\",data_ind[\"total_vaccinations\"].iloc[-1])\nprint(\"Total number of vaccinations done per hundred people:- \",data_ind[\"total_vaccinations_per_hundred\"].iloc[-1])\nX = data_ind[\"date\"]\nY1=data_ind[\"total_vaccinations\"]\nY2 = data_ind[\"people_fully_vaccinated\"]\nY3 = data_ind[\"people_vaccinated\"]\n\nplt.figure(figsize=(8,5))\nplt.plot(X,Y1,linewidth=4,label=\"total vaccinations\")\nplt.plot(X,Y2,linewidth=3,label=\"people fully vaccinated\")\nplt.plot(X,Y3,linewidth=3,label=\"people vaccinated\")\nplt.xticks(rotation=90)\nplt.legend()\nplt.show()\nz1=data_ind[\"people_vaccinated_per_hundred\"]\nz2=data_ind[\"people_fully_vaccinated_per_hundred\"]\nz3=data_ind[\"total_vaccinations_per_hundred\"]\n\n\nplt.figure(figsize=(8,5))\nplt.plot(X,z1,linewidth=3,label=\"people vaccinated per hundred\")\nplt.plot(X,z2,linewidth=3,label=\"people fully vaccinated per hundred\")\nplt.plot(X,z3,linewidth=4,label=\"total vaccination per hundred\")\nplt.xticks(rotation=90)\nplt.legend()\nplt.show()\n\"\"\"\n**MOST USED VACCINE IN INDIA**\n\"\"\"\ndata_ind.vaccines.unique()\nvaccine_ind = data_ind.groupby([\"vaccines\",\"date\"]).sum().reset_index()\nvaccine_ind=vaccine_ind.groupby([\"vaccines\"]).max()\n\n#plotting graph for most used vaccines\nplt.figure(figsize=(15,5))\nsns.catplot(x=\"total_vaccinations\",y=vaccine_ind.index,data=vaccine_ind,kind='bar',ci=None,aspect=2)\nplt.show()\n\"\"\"\nSo , its obvious from the graph that Covaxin , is the sole used vaccine in india \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1d264e095e5da4'}"}
{"id":"109420","text":"\"\"\"\n# Explanation of this notebook\n- This code is a simple solution for those who have taken the Intermediate ML courses in Kaggle.\n- This code is not for the explanation of the lecture, but for creating a file for submission with the techniques learned in the course.\n- The following steps were used to analyze the data.\n1. Create a data set that will be used in this analyses\n2. Prepare to use pipeline for analysis\n3. Finally, fit and predict\n- This code is very simple, but it gave good results(Top5%!).\n- If you find any mistakes or problems with this code, please let me know in the comments!\n- Lastly, I'd love it if you'd give me a like!\n\"\"\"\n# 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\n\"\"\"\n# 0.Import libraries and CSV files\n\"\"\"\n# Import helpful libraries\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom xgboost import XGBRegressor\n\n#Importing CSV files\nX_train_full=pd.read_csv(\"\/kaggle\/input\/home-data-for-ml-course\/train.csv\")\nX_test_full=pd.read_csv(\"\/kaggle\/input\/home-data-for-ml-course\/test.csv\")\n\n\"\"\"\n# 1.Create a data set that will be used in this analyses\n\"\"\"\n#Check if there are any rows with missing target values, and if so, delete them\n#missing_val_count_by_column = (X_train_full.isnull().sum())\n#print(missing_val_count_by_column[missing_val_count_by_column > 0])\n#X_train_full.dropna(axis=0, subset=['SalePrice'], inplace=True)\n\n#Create y_train,X_train_full\ny_train=X_train_full.SalePrice\nX_train_full.drop(['SalePrice'], axis=1, inplace=True)\n\n#Separate numeric data columns from categorical data columns\nX_train_full_num = X_train_full.select_dtypes(exclude=['object'])\nX_train_full_cat = X_train_full.select_dtypes(include=['object'])\nX_test_full_num = X_test_full.select_dtypes(exclude=['object'])\nX_test_full_cat = X_test_full.select_dtypes(include=['object'])\n\n#Remove columns with missing values in the category data\ncols_with_missing1 = [col for col in X_train_full_cat.columns if X_train_full_cat[col].isnull().any()] \ncols_with_missing2 = [col for col in X_test_full_cat.columns if X_test_full_cat[col].isnull().any()] \nbad_cat_list=list(set(cols_with_missing1)|set(cols_with_missing2))\nall_cat_list = [col for col in X_train_full_cat.columns]\nnomissing_cat_list=list(set(all_cat_list)-set(bad_cat_list))\nX_train_full_cat_nomissing=X_train_full_cat[nomissing_cat_list]\nX_test_full_cat_nomissing=X_test_full_cat[nomissing_cat_list]\n\n#Finally, we will create a data set that will be used in this analyses.\nX_train_full_final=pd.concat([X_train_full_num,X_train_full_cat_nomissing],axis=1)\nX_test_full_final=pd.concat([X_test_full_num,X_test_full_cat_nomissing],axis=1)\n\n\n\"\"\"\n# 2.Prepare to use pipeline for analysis\n\"\"\"\n# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='mean')\n\n# Preprocessing for categorical data\ncategorical_transformer = Pipeline(steps=[('ordinal',OrdinalEncoder())])\n\n# Bundle preprocessing for numerical and categorical data\nnumerical_cols = [cname for cname in X_train_full_num.columns if X_train_full[cname].dtype in ['int64', 'float64']]\ncategorical_cols = [cname for cname in X_train_full_cat_nomissing.columns if X_train_full[cname].dtype == \"object\"]\npreprocessor = ColumnTransformer(transformers=[('num', numerical_transformer, numerical_cols),('cat', categorical_transformer, categorical_cols)])\n\n# Define model\n#This model has already been selected as the best one in the first intermediate course\n#So, using cross-validation may give better results (that's my future to-do)\nmodel = XGBRegressor(n_estimators=1000,learning_rate=0.05,n_jobs=4,random_state=0)\n\n# Bundle preprocessing and modeling code in a pipeline\nclf = Pipeline(steps=[('preprocessor', preprocessor),('model', model)])\n\n\"\"\"\n# 3. Finally, fit and predict\n\"\"\"\nclf.fit(X_train_full_final,y_train)\npreds=clf.predict(X_test_full_final)\noutput = pd.DataFrame({'Id': X_test_full.Id,'SalePrice': preds})\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'c9165016d958ec'}"}
{"id":"15969","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\n\npd.set_option('display.max_columns', 100)\npd.set_option('display.max_rows', 2000)\nh_train=pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\")\nh_train.head()\nh_train.dtypes.head()\nh_train.isnull().sum().head()\ntotal_missing=h_train.isnull().sum().sort_values()\npercMissing = h_train.isnull().sum() \/ h_train.isnull().count().sort_values()*100\nmissing = pd.concat([total_missing, percMissing], axis = 1, keys = ['total #', '%'])\nmissing[missing['total #'] > 0]\n## as we can see there are 4 features having  more than 80% null value it's better to drop that features rather than try to fill them\n\nh_train.drop([\"PoolQC\",\"MiscFeature\",\"Fence\",\"Alley\"],axis=1,inplace=True)\n\"\"\"\n### analysing 'SalePrice\n\"\"\"\nh_train['SalePrice'].describe()\nsns.distplot(h_train['SalePrice']);\n\"\"\"\n#### We have positive skewness.\n\"\"\"\n#skewness and kurtosis\nprint(\"Skewness: %f\" % h_train['SalePrice'].skew())\nprint(\"Kurtosis: %f\" % h_train['SalePrice'].kurt())\n#scatter plot GrLivArea\/saleprice\nvar = 'GrLivArea'\ndata = pd.concat([h_train['SalePrice'], h_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));\n\"\"\"\n#### linear relationship\n\"\"\"\n#scatter plot totalbsmtsf\/saleprice\nvar = 'TotalBsmtSF'\ndata = pd.concat([h_train['SalePrice'], h_train[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));\n\"\"\"\n#### linear but not as above\n\"\"\"\n# Relationship with categorical features\nsns.barplot(h_train.OverallQual,h_train.SalePrice)\n\"\"\"\n#### As we can see that higher the Quality higher the price\n\"\"\"\nplt.subplots(figsize=(12, 9))\nsns.heatmap(h_train.corr())\n#'SalePrice' correlation matrix (zoomed heatmap style) take only those columns from upper heatmap\ncol=h_train[['SalePrice','GarageYrBlt','OverallQual','GarageCars','GrLivArea','GarageArea','TotalBsmtSF','1stFlrSF','YearBuilt','TotRmsAbvGrd']]\ncol.corr()\n\nh_train.shape\nprint(\"Find most important features relative to target\")\ncorr = h_train.corr()\ncorr.sort_values([\"SalePrice\"], ascending = False, inplace = True)\nprint(corr.SalePrice)\nsns.set()\ncols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\nsns.pairplot(h_train[cols], size = 2.5)\nplt.show();\n\"\"\"\n###  These all the columns which have null values\n###  Take one coloumn at a time for missing values\n\"\"\"\nh_train[['FireplaceQu','LotFrontage','BsmtCond','BsmtExposure','BsmtFinType1','BsmtFinType2',\n        'BsmtQual','Electrical','GarageCond','GarageFinish','GarageQual','GarageType','GarageYrBlt','MasVnrArea','MasVnrType']].dtypes\nh_train.shape\n\"\"\"\n### As we can see only three variable are float so we can check their corelation with SalePrice\n\"\"\"\nh_train[['LotFrontage','SalePrice']].corr()\nsns.scatterplot(x = 'SalePrice', y = 'LotFrontage', data = h_train)\nh_train[['GarageYrBlt','SalePrice']].corr()\nsns.scatterplot(x = 'SalePrice', y = 'GarageYrBlt', data = h_train)\nh_train[['MasVnrArea','SalePrice']].corr()\nsns.scatterplot(x = 'SalePrice', y = 'MasVnrArea', data = h_train)\n\"\"\"\n### As we can see there is a correlation with SalePrice so we can not simply delete null values so we can replace null with median so spread will not change\n\"\"\"\nh_train['LotFrontage'].replace(np.nan,h_train.LotFrontage.mean(),inplace=True)\nh_train['GarageYrBlt'].replace(np.nan,h_train.GarageYrBlt.mean(),inplace=True)\nh_train['MasVnrArea'].replace(np.nan,h_train.MasVnrArea.mean(),inplace=True)\nh_train.isnull().sum()\nh_train.drop(h_train.loc[h_train['Electrical'].isnull()].index,inplace=True)\nh_train['Electrical'].isnull().sum()\nh_train.shape\n\"\"\"\n#### Now we handle numerical values so its time to fill categorical values\n\"\"\"\n# h_train['Alley'].unique()\n# h_train['Alley'].replace(np.nan,'No_alley_access',inplace=True)\n\n# sns.countplot(data=h_train,x='Alley')\n\n# #nan replaced with No alley access as per the Data Dictionary\n#BsmtQual\nh_train['BsmtQual'].unique()\n\n\n# as per the Data Dictionary nan stands for \"No Basement\"\n#so,\nh_train['BsmtQual'].replace(np.nan,'No_Basement',inplace=True)\n\nsns.countplot(data=h_train,x='BsmtQual')\n#BsmtCond\nh_train['BsmtCond'].unique()\n\n# as per the Data Dictionary nan stands for \"No Basement\"\n#so,\nh_train['BsmtCond'].replace(np.nan,'No_Basement',inplace=True)\n\nsns.countplot(data=h_train,x='BsmtCond')\n#BsmtExposure\nh_train['BsmtExposure'].unique()\n\n# as per the Data Dictionary nan stands for \"No Basement\"\n#so,\nh_train['BsmtExposure'].replace(np.nan,'No_Basement',inplace=True)\n\nsns.countplot(data=h_train,x='BsmtExposure')\n#BsmtFinType1\nh_train['BsmtFinType1'].unique()\n\n# as per the Data Dictionary nan stands for \"No Basement\"\n#so,\nh_train['BsmtFinType1'].replace(np.nan,'No_Basement',inplace=True)\n\nsns.countplot(data=h_train,x='BsmtFinType1')\n#BsmtFinType2\nh_train['BsmtFinType2'].unique()\n\n# as per the Data Dictionary nan stands for \"No Basement\"\n#so,\nh_train['BsmtFinType2'].replace(np.nan,'No_Basement',inplace=True)\n\nsns.countplot(data=h_train,x='BsmtFinType2')\n#FireplaceQu\nh_train['FireplaceQu'].unique()\n\n# as per the Data Dictionary nan stands for \"No Fireplace\"\n#so,\nh_train['FireplaceQu'].replace(np.nan,'No_Fireplace',inplace=True)\n\nsns.countplot(data=h_train,x='FireplaceQu')\n#GarageType\nh_train['GarageType'].unique()\n\n# as per the Data Dictionary nan stands for \"No Garage\"\n#so,\nh_train['GarageType'].replace(np.nan,'No_Garage',inplace=True)\n\nsns.countplot(data=h_train,x='GarageType')\n#GarageFinish\nh_train['GarageFinish'].unique()\n\n# as per the Data Dictionary nan stands for \"No Garage\"\n#so,\nh_train['GarageFinish'].replace(np.nan,'No_Garage',inplace=True)\n\nsns.countplot(data=h_train,x='GarageFinish')\n\n#GarageQual\nh_train['GarageQual'].unique()\n\n# as per the Data Dictionary nan stands for \"No Garage\"\n#so,\nh_train['GarageQual'].replace(np.nan,'No_Garage',inplace=True)\n\nsns.countplot(data=h_train,x='GarageQual')\n#GarageCond\nh_train['GarageCond'].unique()\n\n# as per the Data Dictionary nan stands for \"No Garage\"\n#so,\nh_train['GarageCond'].replace(np.nan,'No_Garage',inplace=True)\n\nsns.countplot(data=h_train,x='GarageCond')\n# #PoolQC\n# h_train['PoolQC'].unique()\n\n# # as per the Data Dictionary nan stands for \"No Pool\"\n# #so,\n# h_train['PoolQC'].replace(np.nan,'No_Pool',inplace=True)\n\n# sns.countplot(data=h_train,x='PoolQC')\n# #Fence\n# h_train['Fence'].unique()\n\n# # as per the Data Dictionary nan stands for \"No Fence\"\n# #so,\n# h_train['Fence'].replace(np.nan,'No_Fence',inplace=True)\n\n# sns.countplot(data=h_train,x='Fence')\n\n# #MiscFeature\n# h_train['MiscFeature'].unique()\n\n# # as per the Data Dictionary nan stands for \"None\"\n# #so,\n# h_train['MiscFeature'].replace(np.nan,'None',inplace=True)\n\n# sns.countplot(data=h_train,x='MiscFeature')\nh_train.shape\n#MasVnrType\nh_train['MasVnrType'].unique()\n\n#in this there is no designation for nan so we are removing the nan values\nh_train.drop(h_train.loc[h_train['MasVnrType'].isnull()].index,inplace=True)\nsns.heatmap(h_train.isnull())\n\"\"\"\n##### Now we are clear with the Nan values present in Dataset\n\"\"\"\n\"\"\"\n### Now its for outliers\n\"\"\"\n# #standardizing data\n# saleprice_scaled = StandardScaler().fit_transform(h_train['SalePrice'][:,np.newaxis]);\n# low_range = saleprice_scaled[saleprice_scaled[:,0].argsort()][:10]\n# high_range= saleprice_scaled[saleprice_scaled[:,0].argsort()][-10:]\n# print('outer range (low) of the distribution:')\n# print(low_range)\n# print('\\nouter range (high) of the distribution:')\n# print(high_range)\n# sns.distplot(h_train['SalePrice'], fit=norm);\n# fig = plt.figure()\n# res = stats.probplot(h_train['SalePrice'], plot=plt)\n# h_train['SalePrice'].quantile([0.1,0.2,0.3,0.4])\n# ### as we can see from above graph there is one outlier at -3 std and 2 at +3 std and same we can see below also\n\n# h_train['SalePrice'].quantile([0.97,0.98,0.99,1])\n\"\"\"\nOk, 'SalePrice' is not normal. It shows 'peakedness', positive skewness and does not follow the diagonal line.\n\nBut everything's not lost. A simple data transformation can solve the problem. This is one of the awesome things you can learn in statistical books: in case of positive skewness, log transformations usually works well. When I discovered this, I felt like an Hogwarts' student discovering a new cool spell.\n\n\"\"\"\n# #applying log transformation\n# h_train['SalePrice'] = np.log(h_train['SalePrice'])\n# #transformed histogram and normal probability plot\n# sns.distplot(h_train['SalePrice'], fit=norm);\n# fig = plt.figure()\n# res = stats.probplot(h_train['SalePrice'], plot=plt)\n# h_train['SalePrice'].quantile([0.1,0.2,0.3,0.4])\n# h_train['SalePrice'].quantile([0.97,0.98,0.99,1])\n# h_train.drop(h_train[h_train['SalePrice']<11.728037].index,axis=0,inplace=True)\n# h_train.drop(h_train[h_train['SalePrice']>12.993142].index,axis=0,inplace=True)\n# h_train=h_train.drop('Id',axis=1)\n# h_train.shape\n# #LotFrontage\n# sns.distplot(h_train['LotFrontage'], fit=norm);\n# fig = plt.figure()\n# res = stats.probplot(h_train['LotFrontage'], plot=plt)\n# h_train['LotFrontage'].quantile([0.1,0.2,0.3,0.4])\n# h_train['LotFrontage'].quantile([0.96,0.97,0.98,0.99,1])\n# h_train.drop(h_train[h_train['LotFrontage']>139.2].index,axis=0,inplace=True)\n# h_train.shape\n# #LotArea\n# sns.distplot(h_train['GrLivArea'], fit=norm);\n# fig = plt.figure()\n# res = stats.probplot(h_train['GrLivArea'], plot=plt)\n# h_train['GrLivArea'].quantile([0.1,0.2,0.3,0.4])\n# h_train['GrLivArea'].quantile([0.97,0.98,0.99,1])\n# h_train.drop(h_train[h_train['GrLivArea']>2931.84].index,axis=0,inplace=True)\n# h_train.shape\n# sns.distplot(h_train['TotalBsmtSF'], fit=norm);\n# fig = plt.figure()\n# res = stats.probplot(h_train['TotalBsmtSF'], plot=plt)\n# h_train['TotalBsmtSF'].quantile([0.1,0.2,0.3,0.4])\n# h_train['TotalBsmtSF'].quantile([0.97,0.98,0.99,1])\n# h_train.drop(h_train[h_train['TotalBsmtSF']<814.0].index,axis=0,inplace=True)\n# h_train.drop(h_train[h_train['TotalBsmtSF']>2077.84].index,axis=0,inplace=True)\n# h_train.shape\n\"\"\"\n## Now its for model building\n\"\"\"\nh_train.drop('Id',axis=1,inplace=True)\nh_train.corr()\nh1_train=h_train[[\"SalePrice\",\"OverallQual\",\"YearBuilt\",\"TotalBsmtSF\",\"1stFlrSF\",\"GrLivArea\",\"FullBath\",\"GarageCars\",\"GarageArea\",\"TotRmsAbvGrd\"]]\n# These are the best correlation with saleprice\n# OverallQual      0.790982\n# GrLivArea        0.708624\n# GarageCars       0.640409\n# GarageArea       0.623431\n# TotalBsmtSF      0.613581\n# 1stFlrSF         0.605852\n# FullBath         0.560664\n# TotRmsAbvGrd     0.533723\n# YearBuilt        0.522897\nh1_train.shape\nh1_train['TotRmsAbvGrd'].dtype\nh1_train_dum=pd.get_dummies(h1_train,drop_first=True)\nh1_train_dum.shape\n\"\"\"\n#### As we can see TotRmsAbvGrd,1stFlrSF and GarageYrBlt are less correlated\n\"\"\"\nx=h1_train_dum.drop(['SalePrice'],axis=1)\ny=h1_train_dum['SalePrice']\nx.shape\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x, y , test_size=0.2 , random_state=21 )\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import metrics\nclf = RandomForestRegressor()\n\nparam_dist = {\"n_estimators\": [50, 100, 150,200]}\n\nclf.fit(x_train, y_train)\ny_pred=clf.predict(x_test)\nprint('MAE:',metrics.mean_absolute_error(y_test,y_pred))\n\nprint('*'*20)\n\n\nprint('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,y_pred)))\nprint('*'*20)\n\n\nr2_score=metrics.r2_score(y_test,y_pred)\nprint('r2_score:',r2_score)\nfrom sklearn.linear_model import LinearRegression\nclf_lr=LinearRegression()\n\nclf_lr.fit(x_train,y_train)\ny_pred_lr=clf_lr.predict(x_test)\nprint('MAE:',metrics.mean_absolute_error(y_test,y_pred_lr))\n\nprint('*'*20)\n\n\nprint('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,y_pred_lr)))\nprint('*'*20)\n\n\nr2_score=metrics.r2_score(y_test,y_pred_lr)\nprint('r2_score:',r2_score)\n\"\"\"\n## Cross validation\n\"\"\"\nfrom sklearn.model_selection import cross_val_score,KFold\nkf=KFold(n_splits=5)\nRFRegressor=RandomForestRegressor(random_state=5)\n\nscore=cross_val_score(RFRegressor,x,y,cv=kf,scoring='neg_mean_squared_error')\n\nr=score.mean()\nprint(r)\nfrom math import sqrt\n\nsqrt(-r)\n## use this\nkf=KFold(n_splits=5)\nLRegressor=LinearRegression()\n\nscore=cross_val_score(LRegressor,x,y,cv=kf,scoring='neg_mean_squared_error')\n\nr=score.mean()\nprint(r)\nfrom math import sqrt\n\nsqrt(-r)\nimport xgboost as xgb\nmodel = xgb.XGBRegressor()\n\nmodel.fit(x_train,y_train)\ny_pred_xgb=model.predict(x_test)\n\ny_pred_xgb\nprint('MAE:',metrics.mean_absolute_error(y_test,y_pred_xgb))\n\nprint('*'*20)\n\n\nprint('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,y_pred_xgb)))\nprint('*'*20)\n\n\nr2_score=metrics.r2_score(y_test,y_pred_xgb)\nprint('r2_score:',r2_score)\n\"\"\"\n## XGB with CV\n\"\"\"\nkf=KFold(n_splits=5)\nxgbRegressor=xgb.XGBRegressor()\n\nscore=cross_val_score(xgbRegressor,x,y,cv=kf,scoring='neg_mean_squared_error')\n\nr=score.mean()\nprint(r)\nfrom math import sqrt\n\nsqrt(-r)\n\"\"\"\n# Test data\n\"\"\"\nh_test=pd.read_csv(\"test.csv\")\nh_test.head()\nh_test.shape\ntotal_missing_t=h_test.isnull().sum().sort_values()\npercMissing_t = h_test.isnull().sum() \/ h_test.isnull().count().sort_values()*100\nmissing_t = pd.concat([total_missing_t, percMissing_t], axis = 1, keys = ['total #', '%'])\nmissing_t[missing_t['total #'] > 0]\n# h_test['Alley'].replace(np.nan,'No_alley_access',inplace=True)\n\n# #sns.countplot(data=h_train,x='Alley')\n#BsmtCond\n# h_test['BsmtCond'].replace(np.nan,'No_Basement',inplace=True)\n #BsmtExposure\n# h_test['BsmtExposure'].replace(np.nan,'No_Basement',inplace=True)\nh1_test=h_test[[\"OverallQual\",\"YearBuilt\",\"TotalBsmtSF\",\"1stFlrSF\",\"GrLivArea\",\"FullBath\",\"GarageCars\",\"GarageArea\",\"TotRmsAbvGrd\"]]\nh1_test.isnull().sum()\n#GarageCars\nh1_test.dtypes\n# h_test['GarageCars'].replace(np.nan,'No_Basement',inplace=True)\nh1_test.drop(h1_test.loc[h1_test['GarageCars'].isnull()].index,inplace=True)\nh1_test.drop(h1_test.loc[h1_test['TotalBsmtSF'].isnull()].index,inplace=True)\nh1_test_dum=pd.get_dummies(h1_test,drop_first= True)\ny_pred_xgb_test=model.predict(h1_test_dum)\ny_pred_xgb_test=pd.DataFrame(y_pred_xgb_test)\ny_pred_xgb_test.head()\nsample=pd.read_csv('sample_submission.csv')\nsample.head()\nsubmit=pd.concat([sample.Id,y_pred_xgb_test],axis=1)\nsubmit.head()\nsubmit.columns=[\"Id\",\"SalePrice\"]\n# sns.lmplot(\"Id\",\"SalePrice\",data=submit,fit_reg=True)\nsubmit.to_csv(\"Submission_HLP_kaggle.csv\",index=False)\nsubmit.shape\nsubmit.loc[submit[\"SalePrice\"].isnull()]\n\"\"\"\n# Hyperparameter Tuning\n\"\"\"\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom numpy import nan\nimport xgboost as xgb\nmodel = xgb.XGBRegressor()\n\nmodel.fit(x_train,y_train)\nBooster=[\"gbtree\",\"gblinear\"]\nbase_score=[0.25,0.50,0.75,1]\nn_estimators=[100,500,900,1000,1500]\nmax_depth=[2,3,5,10,15]\nBooster=[\"gbtree\",\"gblinear\"]\nlearning_rate=[0.05,0.1,0.15,0.20]\nmin_child_weight=[1,2,3,4]\n\nhyperparameter_grid={\n    \"n_estimators\":n_estimators,\n    \"max_depth\":max_depth,\n    \"Booster\":Booster,\n    \"learning_rate\":learning_rate,\n    \"min_child_weight\":min_child_weight,\n    \"base_score\":base_score\n    \n}\n\nrandom_cv=RandomizedSearchCV(estimator=model,\n                            param_distributions=hyperparameter_grid,\n                            cv=5,n_iter=50,\n                            scoring=\"neg_mean_absolute_error\",n_jobs=4,\n                            verbose=5,\n                            return_train_score=True,\n                            random_state=42)\nrandom_cv.fit(x_train,y_train)\nrandom_cv.best_estimator_\nregressor=xgb.XGBRegressor(Booster='gbtree', base_score=0.5, booster=None,\n             colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1,\n             gamma=0, gpu_id=-1, importance_type='gain',\n             interaction_constraints=None, learning_rate=0.15, max_delta_step=0,\n             max_depth=2, min_child_weight=2, missing=nan,\n             monotone_constraints=None, n_estimators=100, n_jobs=0,\n             num_parallel_tree=1, objective='reg:squarederror', random_state=0,\n             reg_alpha=0, reg_lambda=1, scale_pos_weight=1, subsample=1,\n             tree_method=None, validate_parameters=False, verbosity=None)\nregressor.fit(x_train,y_train)\ny_pred_ran=regressor.predict(h1_test_dum)\ny_pred_ran\ny_pred_ran=pd.DataFrame(y_pred_ran)\nsubmit_ran=pd.concat([sample.Id,y_pred_ran],axis=1)\nsubmit_ran.head()\nsubmit_ran.columns=[\"Id\",\"SalePrice\"]\nsubmit_ran.to_csv(\"Submission_HLP_ran_kaggle.csv\",index=False)","meta":"{'source': 'AI4Code', 'id': '1d1cc26aedb41e'}"}
{"id":"117347","text":"\"\"\"\n# Joseph Stewart, 4820862\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import TimeSeriesSplit\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedKFold\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\n\n\ntrain_data = pd.read_csv(\"\/kaggle\/input\/cap-4611-2021-fall-assignment-1\/train.csv\")\nsub_data = pd.read_csv(\"\/kaggle\/input\/cap-4611-2021-fall-assignment-1\/test.csv\")\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ntrain_data.head()\n\"\"\"\n# Restrict analysis to data with just HHS region that is United States.\n\"\"\"\ntrain_data = train_data[train_data['HHS Region'] == 'United States']\ntrain_data\n\"\"\"\n# Remove Total Deaths and ID\n\"\"\"\ntrain_data = train_data.drop(axis=1, columns=['Total Deaths', 'id'])\ntrain_data\ntrain_data.describe()\n\"\"\"\n# Remove Date As Of, Year, and group, as they are not important. \n\"\"\"\n\"\"\"\n# Remove Week Ending Date b\/c same as End Date.\n# Remove End Date b\/c linear to start date.\n\"\"\"\ntrain_data = train_data.drop(axis=1, columns=['Data As Of', 'Year', 'Group', 'Week-Ending Date', 'End Date', 'Month'])\ntrain_data\n\"\"\"\n# HHS Region no longer important b\/c 1 value\n\"\"\"\ntrain_data = train_data.drop(axis=1, columns=['HHS Region', 'Footnote'])\ntrain_data\ntrain_data.describe()\nmissing = train_data.isnull().sum()\nmissing = missing[missing > 0]\nmissing.sort_values(inplace = True)\nprint(missing)\n\"\"\"\n# Drop unknown Race and Hispanical Origin Group\n\"\"\"\ntrain_data = train_data[train_data['Race and Hispanic Origin Group'] != 'Unknown']\ntrain_data\n\"\"\"\n# Convert Race and Hispanic Origin Group into numerical index\n\"\"\"\ntrain_data['Race and Hispanic Origin Group'].unique()\ntrain_data = train_data.replace(dict.fromkeys(['Hispanic'], 0))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic American Indian or Alaska Native'], 1))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic Asian'], 2))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic Black'], 3))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic More than one race'], 4))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic Native Hawaiian or Other Pacific Islander'], 5))\ntrain_data = train_data.replace(dict.fromkeys(['Non-Hispanic White'], 6))\ntrain_data\n\"\"\"\n# Convert Age Group to numerical index\n\"\"\"\ntrain_data['Age Group'].unique()\ntrain_data = train_data.replace(dict.fromkeys(['0-4 years'], 0))\ntrain_data = train_data.replace(dict.fromkeys(['5-17 years'], 5))\ntrain_data = train_data.replace(dict.fromkeys(['18-29 years'], 18))\ntrain_data = train_data.replace(dict.fromkeys(['30-39 years'], 30))\ntrain_data = train_data.replace(dict.fromkeys(['40-49 years'], 40))\ntrain_data = train_data.replace(dict.fromkeys(['50-64 years'], 50))\ntrain_data = train_data.replace(dict.fromkeys(['65-74 years'], 65))\ntrain_data = train_data.replace(dict.fromkeys(['75-84 years'], 75))\ntrain_data = train_data.replace(dict.fromkeys(['85 years and over'], 85))\n\ntrain_data\n\"\"\"\n# Convert 'Start Date' into numerical index\n\"\"\"\n#train_data['Start Date'].unique()\n#train_data.shape\n#train_data.reindex\n#train_data.loc[63, 'Start Date']\n#index_marker = 0\n#curr_date = '12\/29\/2019'\n#for x in range(4663):\n#    if train_data.at[x, 'Start Date'] == curr_date:\n#        train_data.at[x, 'Start Date'] = index_marker\n#    else:\n#        curr_date = train_data.at[x, 'Start Date']\n#        index_marker = index_marker+1\n#        train_data.at[x, 'Start Date'] = index_marker\ntrain_data.shape\n\"\"\"\n# Drop MMWR missing\n\"\"\"\ntrain_data = train_data.dropna(subset=['MMWR Week'])\n\"\"\"\n# Verify the drop\n\"\"\"\nmissing = train_data.isnull().sum()\nmissing = missing[missing > 0]\nmissing.sort_values(inplace = True)\nprint(missing)\n\"\"\"\n# Examine data relationships & outliers\n\"\"\"\ntrain_data.hist(figsize=(12,5), layout=(2,3))\nplt.show()\nsns.boxplot(train_data['Age Group'])\nsns.boxplot(train_data['MMWR Week'])\nsns.boxplot(train_data['Race and Hispanic Origin Group'])\nsns.boxplot(train_data['COVID-19 Deaths'])\nprint(np.where(train_data['COVID-19 Deaths']<5))\n\"\"\"\n# Scatterplots\n\"\"\"\nfig, ax = plt.subplots(figsize = (18, 10))\nax.scatter(train_data['COVID-19 Deaths'], train_data['Age Group'])\n\nax.set_xlabel('COVID-19 Deaths in the US')\nax.set_ylabel('Age Group (# signifies youngest person in age group)')\nplt.show()\n\"\"\"\n# Deaths in Age<17 range are most likely outliers, but will leave them for now.\n\"\"\"\nfig, ax = plt.subplots(figsize = (18, 10))\nax.scatter(train_data['COVID-19 Deaths'], train_data['Race and Hispanic Origin Group'])\n\nax.set_xlabel('COVID-19 Deaths in the US')\nax.set_ylabel('Race and Hispanic Origin Group')\nplt.show()\n\n# For reference, from earlier\n#train_data = train_data.replace(dict.fromkeys(['Hispanic'], 0))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic American Indian or Alaska Native'], 1))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic Asian'], 2))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic Black'], 3))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic More than one race'], 4))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic Native Hawaiian or Other Pacific Islander'], 5))\n#train_data = train_data.replace(dict.fromkeys(['Non-Hispanic White'], 6))\n\"\"\"\n# Train_test_split data into train & test data\n\"\"\"\nfeatures = ['Start Date', 'MMWR Week', 'Race and Hispanic Origin Group', 'Age Group']\ntarget = ['COVID-19 Deaths']\n\nX = pd.get_dummies(train_data[features])\ny = pd.get_dummies(train_data[target])\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = .60)\nX_train.shape\nX_train.head()\nX_test.shape\n\"\"\"\n# Run models on training data\n\"\"\"\nimport statsmodels.api as sm\nfrom sklearn.metrics import accuracy_score\n\"\"\"\n# Ordinary Least Squares\n\"\"\"\nols_model = sm.OLS(y, X).fit()\n#ols.fit(X, y)\nsummary = ols_model.summary()\nsummary\npredOLS = ols_model.predict(X_test)\nprint(predOLS)\npredOLS.shape\naccOLS = accuracy_score(y_test, predOLS.round())\naccOLS\n\"\"\"\n# Ridge Regression Model\n\"\"\"\nfrom sklearn.linear_model import Ridge\nridge_reg = Ridge()\nridge_reg.fit(X_train, y_train)\nridge_pred = ridge_reg.predict(X_test)\nridge_pred.shape\nacc_ridge = accuracy_score(y_test, ridge_pred.round())\nacc_ridge\n\"\"\"\n# Lasso Regression Model\n\"\"\"\nfrom sklearn.linear_model import Lasso\nlasso_reg = Lasso(normalize=True)\nlasso_reg.fit(X_train,y_train)\nlasso_pred = lasso_reg.predict(X_test)\nlasso_pred.shape\nacc_lasso = accuracy_score(y_test, lasso_pred.round())\nacc_lasso\n\"\"\"\n# Elastic Net Regression\n\"\"\"\nfrom sklearn.linear_model import ElasticNet\nelastic_reg = ElasticNet(alpha=1.0, l1_ratio=0.4)\nelastic_reg.fit(X_train,y_train)\nelastic_pred = elastic_reg.predict(X_test)\nacc_elastic = accuracy_score(y_test, elastic_pred.round())\nacc_elastic\n#cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\n#scores = cross_val_score(elastic_reg, X_train, y_train, scoring='neg_mean_absolute_error', cv=cv, n_jobs=-1)\n\"\"\"\n# Compare models\n\"\"\"\naccOLS\nacc_ridge\nacc_lasso\nacc_elastic\n\"\"\"\n# Run elastic model on submission data\n\"\"\"\nprint(elastic_pred)\nsub_data.shape\nelastic_pred.shape\nelastic_pred.resize((1152,))\nridge_pred.resize((1152,))\noutput = pd.DataFrame({'id':sub_data.id, 'COVID-19 Deaths': elastic_pred})\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'd7e2dcb7f87458'}"}
{"id":"94178","text":"#imports\nimport tensorflow as tf\nimport time\nfrom tqdm import tqdm\nfrom glob import glob\nimport cv2\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\nfrom random import sample\nimport random\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport cv2\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport PIL\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\n\n#imports for capsule neural network in particular\nimport gc\nimport os\nimport nltk\nimport tqdm\nimport numpy as np\nimport pandas as pd\nnltk.download(\"punkt\")\n\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom keras.engine import Layer\nfrom keras.layers import Activation, Add, Bidirectional, Conv1D, Dense, Dropout, Embedding, Flatten\nfrom keras.layers import concatenate, GRU, Input, LSTM, MaxPooling1D\nfrom keras.layers import GlobalAveragePooling1D,  GlobalMaxPooling1D, SpatialDropout1D\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.preprocessing import text, sequence\nfrom sklearn.metrics import accuracy_score, roc_auc_score, log_loss\nfrom sklearn.model_selection import train_test_split\nfrom keras import initializers, regularizers, constraints, optimizers, layers, callbacks\nimport keras.backend as K\nimport numpy as np\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom datetime import datetime\n\n\n%load_ext tensorboard\n#configuration section\nimageSize = 160\nimageWidth = 28 #downscale the image to x by x pixels\nimageHeight = 28 #original dimensions are 640 x 480\nepochNum = 50 #epochs are the number of times we pass through the data\nbatchSize = 8 #number of samples we work through before updating the model\nmaxFiles = 1000 #number to load for each category\ncolorDepth = 1 #3 for RGB\nclasses = 10 #number of classifications we want to bother with\nlearningRate = 0.0001 #this is how fast our model learns, lower = more accurate but takes longer\n# Parameters Based on Paper\nepsilon = 1e-7\nm_plus = 0.9\nm_minus = 0.1\nlambda_ = 0.5\nalpha = 0.0005\nepochs = 30\nno_of_secondary_capsules = 10\n\noptimizer = tf.keras.optimizers.Adam()\nparams = {\n    \"no_of_conv_kernels\": 16,\n    \"no_of_primary_capsules\": 32,\n    \"no_of_secondary_capsules\": 10,\n    \"primary_capsule_vector\": 8,\n    \"secondary_capsule_vector\": 16,\n    \"r\":3,\n}\n\n\n# checkpoint_path = '.\/logs\/model\/capsule'\n\n# stamp = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\n# logdir = '.\/logs\/func\/%s' % stamp\n# writer = tf.summary.create_file_writer(logdir)\n\n# scalar_logdir = '.\/logs\/scalars\/%s' % stamp\n# file_writer = tf.summary.create_file_writer(scalar_logdir + \"\/metrics\")\n# Load the dataset from Kaggle\ndef get_cv2_image(path, img_size, color_type):\n    # Loading as Grayscale image\n    if color_type == 1:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    # Loading as color image\n    elif color_type == 3:\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\n    # Reduce size\n    img = cv2.resize(img[:500], img_size) \n    return img\n\ndef load_data(img_size , color_type):\n    start_time = time.time()\n    training_images = []\n    training_labels = []\n\n    # Loop over the training folder \n    for class_ in tqdm(range(classes)):\n        \n        print('Loading directory c{}'.format(class_))\n        files = glob(os.path.join('..\/input\/state-farm-distracted-driver-detection\/imgs\/train', 'c' + str(class_), '*.jpg'))\n        \n        for file in files:\n            img = get_cv2_image(file, img_size , color_type)\n            training_images.append(img)\n            training_labels.append(class_) \n    \n    print(\"Data Loaded in {} Min\".format((time.time() - start_time)\/60))\n    return training_images, training_labels \n\n\n\ntrain_X, train_y = load_data( (imageWidth,imageHeight) , colorDepth)\n# train_X = train_X[2:]\n# train_y = train_y[2:]\ntrain_X = np.array(train_X).reshape(len(train_X),imageWidth,imageHeight,colorDepth)\ntrain_X = tf.cast(train_X, dtype=tf.float32)\n\ntrain_y = np.array(train_y)\ntrain_X = train_X \/ 255.0\n\n\ndataset = tf.data.Dataset.from_tensor_slices((train_X, train_y))\n\ndataset = dataset.shuffle(buffer_size=len(dataset), reshuffle_each_iteration=True)\n\n\n\n\ntrain_dataset = dataset.take(int(len(dataset)*0.85))\ntest_dataset = dataset.skip(int(len(dataset)*0.85))\n\ntraining_dataset_size = len(dataset)\ntrain_size = len(train_dataset)\ntest_size = len(test_dataset)\n\ndataset = dataset.batch(batch_size=32)\ntrain_dataset = train_dataset.batch(batch_size=32)\ntest_dataset = test_dataset.batch(batch_size=32)\n\n\n\ncount = 0\nfor a, b in train_dataset:\n    count += 1\n    print(b)\n    if(count > 10):\n        break\n\n\n\n\nprint((training_dataset_size))\nprint(train_size)\n\n\n\nclass CapsuleNetwork(tf.keras.Model):\n    def __init__(self, no_of_conv_kernels, no_of_primary_capsules, primary_capsule_vector, no_of_secondary_capsules, secondary_capsule_vector, r):\n        super(CapsuleNetwork, self).__init__()\n        self.no_of_conv_kernels = no_of_conv_kernels\n        self.no_of_primary_capsules = no_of_primary_capsules\n        self.primary_capsule_vector = primary_capsule_vector\n        self.no_of_secondary_capsules = no_of_secondary_capsules\n        self.secondary_capsule_vector = secondary_capsule_vector\n        self.r = r\n        \n        \n        with tf.name_scope(\"Variables\") as scope:\n            self.convolution = tf.keras.layers.Conv2D(self.no_of_conv_kernels, [9,9], strides=[1,1], name='ConvolutionLayer', activation='relu')\n            self.primary_capsule = tf.keras.layers.Conv2D(self.no_of_primary_capsules * self.primary_capsule_vector, [9,9], strides=[2,2], name=\"PrimaryCapsule\")\n            self.w = tf.Variable(tf.random_normal_initializer()(shape=[1, 1152, self.no_of_secondary_capsules, self.secondary_capsule_vector, self.primary_capsule_vector]), dtype=tf.float32, name=\"PoseEstimation\", trainable=True)\n            self.dense_1 = tf.keras.layers.Dense(units = 256, activation='relu')\n            self.dense_2 = tf.keras.layers.Dense(units = 512, activation='relu')\n            self.dense_3 = tf.keras.layers.Dense(units = 784, activation='sigmoid', dtype='float32')\n        \n    def build(self, input_shape):\n        pass\n        \n    def squash(self, s):\n        with tf.name_scope(\"SquashFunction\") as scope:\n            s_norm = tf.norm(s, axis=-1, keepdims=True)\n            return tf.square(s_norm)\/(1 + tf.square(s_norm)) * s\/(s_norm + epsilon)\n    \n    @tf.function\n    def call(self, inputs):\n        input_x, y = inputs\n        # input_x.shape: (None, 28, 28, 1)\n        # y.shape: (None, 10)\n        \n        x = self.convolution(input_x) # x.shape: (None, 20, 20, 256)\n        x = self.primary_capsule(x) # x.shape: (None, 6, 6, 256)\n        \n        with tf.name_scope(\"CapsuleFormation\") as scope:\n            u = tf.reshape(x, (-1, self.no_of_primary_capsules * x.shape[1] * x.shape[2], 8)) # u.shape: (None, 1152, 8)\n            u = tf.expand_dims(u, axis=-2) # u.shape: (None, 1152, 1, 8)\n            u = tf.expand_dims(u, axis=-1) # u.shape: (None, 1152, 1, 8, 1)\n            u_hat = tf.matmul(self.w, u) # u_hat.shape: (None, 1152, 10, 16, 1)\n            u_hat = tf.squeeze(u_hat, [4]) # u_hat.shape: (None, 1152, 10, 16)\n\n        \n        with tf.name_scope(\"DynamicRouting\") as scope:\n            b = tf.zeros((input_x.shape[0], 1152, self.no_of_secondary_capsules, 1)) # b.shape: (None, 1152, 10, 1)\n            for i in range(self.r): # self.r = 3\n                c = tf.nn.softmax(b, axis=-2) # c.shape: (None, 1152, 10, 1)\n                s = tf.reduce_sum(tf.multiply(c, u_hat), axis=1, keepdims=True) # s.shape: (None, 1, 10, 16)\n                v = self.squash(s) # v.shape: (None, 1, 10, 16)\n                agreement = tf.squeeze(tf.matmul(tf.expand_dims(u_hat, axis=-1), tf.expand_dims(v, axis=-1), transpose_a=True), [4]) # agreement.shape: (None, 1152, 10, 1)\n                # Before matmul following intermediate shapes are present, they are not assigned to a variable but just for understanding the code.\n                # u_hat.shape (Intermediate shape) : (None, 1152, 10, 16, 1)\n                # v.shape (Intermediate shape): (None, 1, 10, 16, 1)\n                # Since the first parameter of matmul is to be transposed its shape becomes:(None, 1152, 10, 1, 16)\n                # Now matmul is performed in the last two dimensions, and others are broadcasted\n                # Before squeezing we have an intermediate shape of (None, 1152, 10, 1, 1)\n                b += agreement\n                \n        with tf.name_scope(\"Masking\") as scope:\n            y = tf.expand_dims(y, axis=-1) # y.shape: (None, 10, 1)\n            y = tf.expand_dims(y, axis=1) # y.shape: (None, 1, 10, 1)\n            mask = tf.cast(y, dtype=tf.float32) # mask.shape: (None, 1, 10, 1)\n            v_masked = tf.multiply(mask, v) # v_masked.shape: (None, 1, 10, 16)\n            \n        with tf.name_scope(\"Reconstruction\") as scope:\n            v_ = tf.reshape(v_masked, [-1, self.no_of_secondary_capsules * self.secondary_capsule_vector]) # v_.shape: (None, 160)\n            reconstructed_image = self.dense_1(v_) # reconstructed_image.shape: (None, 512)\n            reconstructed_image = self.dense_2(reconstructed_image) # reconstructed_image.shape: (None, 1024)\n            reconstructed_image = self.dense_3(reconstructed_image) # reconstructed_image.shape: (None, 784)\n        \n        return v, reconstructed_image\n\n    @tf.function\n    def predict_capsule_output(self, inputs):\n        x = self.convolution(inputs) # x.shape: (None, 20, 20, 256)\n        x = self.primary_capsule(x) # x.shape: (None, 6, 6, 256)\n        \n        with tf.name_scope(\"CapsuleFormation\") as scope:\n            u = tf.reshape(x, (-1, self.no_of_primary_capsules * x.shape[1] * x.shape[2], 8)) # u.shape: (None, 1152, 8)\n            u = tf.expand_dims(u, axis=-2) # u.shape: (None, 1152, 1, 8)\n            u = tf.expand_dims(u, axis=-1) # u.shape: (None, 1152, 1, 8, 1)\n            u_hat = tf.matmul(self.w, u) # u_hat.shape: (None, 1152, 10, 16, 1)\n            u_hat = tf.squeeze(u_hat, [4]) # u_hat.shape: (None, 1152, 10, 16)\n\n        \n        with tf.name_scope(\"DynamicRouting\") as scope:\n            b = tf.zeros((inputs.shape[0], 1152, self.no_of_secondary_capsules, 1)) # b.shape: (None, 1152, 10, 1)\n            for i in range(self.r): # self.r = 3\n                c = tf.nn.softmax(b, axis=-2) # c.shape: (None, 1152, 10, 1)\n                s = tf.reduce_sum(tf.multiply(c, u_hat), axis=1, keepdims=True) # s.shape: (None, 1, 10, 16)\n                v = self.squash(s) # v.shape: (None, 1, 10, 16)\n                agreement = tf.squeeze(tf.matmul(tf.expand_dims(u_hat, axis=-1), tf.expand_dims(v, axis=-1), transpose_a=True), [4]) # agreement.shape: (None, 1152, 10, 1)\n                # Before matmul following intermediate shapes are present, they are not assigned to a variable but just for understanding the code.\n                # u_hat.shape (Intermediate shape) : (None, 1152, 10, 16, 1)\n                # v.shape (Intermediate shape): (None, 1, 10, 16, 1)\n                # Since the first parameter of matmul is to be transposed its shape becomes:(None, 1152, 10, 1, 16)\n                # Now matmul is performed in the last two dimensions, and others are broadcasted\n                # Before squeezing we have an intermediate shape of (None, 1152, 10, 1, 1)\n                b += agreement\n        return v\n\n    @tf.function\n    def regenerate_image(self, inputs):\n        with tf.name_scope(\"Reconstruction\") as scope:\n            v_ = tf.reshape(inputs, [-1, self.no_of_secondary_capsules * self.secondary_capsule_vector]) # v_.shape: (None, 160)\n            reconstructed_image = self.dense_1(v_) # reconstructed_image.shape: (None, 512)\n            reconstructed_image = self.dense_2(reconstructed_image) # reconstructed_image.shape: (None, 1024)\n            reconstructed_image = self.dense_3(reconstructed_image) # reconstructed_image.shape: (None, 784)\n        return reconstructed_image\ntf.summary.trace_on(graph=True, profiler=True)\nkeras.backend.clear_session()\nmodel = CapsuleNetwork(**params)\n\n\ndef safe_norm(v, axis=-1, epsilon=1e-7):\n    v_ = tf.reduce_sum(tf.square(v), axis = axis, keepdims=True)\n    return tf.sqrt(v_ + epsilon)\n\ndef loss_function(v, reconstructed_image, y, y_image):\n    prediction = safe_norm(v)\n    prediction = tf.reshape(prediction, [-1, no_of_secondary_capsules])\n    \n    left_margin = tf.square(tf.maximum(0.0, m_plus - prediction))\n    right_margin = tf.square(tf.maximum(0.0, prediction - m_minus))\n    \n    l = tf.add(y * left_margin, lambda_ * (1.0 - y) * right_margin)\n    \n    margin_loss = tf.reduce_mean(tf.reduce_sum(l, axis=-1))\n    \n    y_image_flat = tf.reshape(y_image, [-1, 784])\n    reconstruction_loss = tf.reduce_mean(tf.square(y_image_flat - reconstructed_image))\n    \n    loss = tf.add(margin_loss, alpha * reconstruction_loss)\n    \n    return loss\ndef train(x,y):\n    y_one_hot = tf.one_hot(y, depth=10)\n    with tf.GradientTape() as tape:\n        v, reconstructed_image = model([x, y_one_hot])\n        loss = loss_function(v, reconstructed_image, y_one_hot, x)\n    grad = tape.gradient(loss, model.trainable_variables)\n    optimizer.apply_gradients(zip(grad, model.trainable_variables))\n    return loss\n\ndef get_loss(x,y):\n    y_one_hot = tf.one_hot(y, depth=10)\n    with tf.GradientTape() as tape:\n        v, reconstructed_image = model([x, y_one_hot])\n        loss = loss_function(v, reconstructed_image, y_one_hot, x)\n    return loss\n\n\nprint(train_X.shape)\nprint(train_y.shape)\n\n_ = train(train_X[:1],train_y[:1])\n# with writer.as_default():\n#     tf.summary.trace_export(name=\"my_func_trace\", step=0, profiler_outdir=logdir)\n\n# tf.summary.trace_off()\nmodel.save_weights('my_model_weights.h5')\nmodel.summary()\ndef predict(model, x):\n    pred = safe_norm(model.predict_capsule_output(x))\n    pred = tf.squeeze(pred, [1])\n    return np.argmax(pred, axis=1)[:,0]\n\n# checkpoint = tf.train.Checkpoint(model=model)\n# %tensorboard --logdir .\/logs\n\ncount = 10\ntrain_dataset = train_dataset.shuffle(64)\nfor x,y in train_dataset:\n    print(predict(model, x))\n    #print(x)\n    print(y)\n    count -= 1\n    if count < 0:\n        break\ndef reset_weights(model):\n    session = tensorflow.keras.backend.get_session()\n    for layer in model.layers: \n        if hasattr(layer, 'kernel_initializer'):\n            layer.kernel.initializer.run(session=session)\n\n    \nlosses = []\naccuracy = []\ntest_acc = []\n\ntest_losses = []\n#keras.backend.clear_session()\n#model.load_weights('my_model_weights.h5')\nK.get_session().close()\nK.set_session(tf.Session())\nK.get_session().run(tf.global_variables_initializer())\nfor i in range(1, epochs+1, 1):\n\n    loss = 0\n    with tqdm(total=len(train_dataset)) as pbar:\n        \n        description = \"Epoch \" + str(i) + \"\/\" + str(epochs)\n        pbar.set_description_str(description)\n\n        for X_batch, y_batch in train_dataset:\n\n            loss += train(X_batch,y_batch)\n            pbar.update(1)\n\n        loss \/= len(train_dataset)\n        losses.append(loss.numpy())\n        \n        training_sum = 0\n\n        print_statement = \"Loss :\" + str(loss.numpy()) + \" Evaluating Accuracy ...\"\n        pbar.set_postfix_str(print_statement)\n\n        for X_batch, y_batch in train_dataset:\n            training_sum += sum(predict(model, X_batch)==y_batch.numpy())\n        accuracy.append(training_sum\/train_size)\n        \n        training_sum = 0\n        test_loss = 0\n        \n        for X_batch, y_batch in test_dataset:\n            training_sum += sum(predict(model, X_batch)==y_batch.numpy())\n            test_loss += get_loss(X_batch, y_batch)\n        \n        test_loss \/= len(test_dataset)\n        test_losses.append(test_loss)\n        test_acc.append(training_sum\/test_size)\n            \n\n#         with file_writer.as_default():\n#             tf.summary.scalar('Loss', data=loss.numpy(), step=i)\n#             tf.summary.scalar('Accuracy', data=accuracy[-1], step=i)\n#             tf.summary.scalar('Test Acc', data = test_acc[-1], step=i)\n        \n        print_statement = \"Loss :\" + str(loss.numpy()) + \" Accuracy :\" + str(accuracy[-1])  + \" Test Acc :\" + str(test_acc[-1])\n\n#         if i % 10 == 0:\n#             print_statement += ' Checkpoint Saved'\n#             checkpoint.save(checkpoint_path)\n        \n        pbar.set_postfix_str(print_statement)\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.plot(losses, label = \"train\")\nplt.plot(test_losses, label = \"test\")\nplt.title('Loss over Time')\nplt.xlabel('Loss')\nplt.ylabel('Epoch')\nplt.legend()\nplt.show()\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.plot(accuracy, label = \"train\")\nplt.plot(test_acc, label = \"test\")\nplt.title('Accuracy over Time')\nplt.xlabel('Accuracy')\nplt.ylabel('Epoch')\nplt.legend()\nplt.show()\n\"\"\"\nOLD TRAINING, IGNORE PAST THIS POINT\n\"\"\"\nlosses = []\naccuracy = []\nfor i in range(1, epochs+1, 1):\n\n    loss = 0\n    with tqdm(total=len(dataset)) as pbar:\n        \n        description = \"Epoch \" + str(i) + \"\/\" + str(epochs)\n        pbar.set_description_str(description)\n\n        for X_batch, y_batch in dataset:\n\n            loss += train(X_batch,y_batch)\n            pbar.update(1)\n\n        loss \/= len(dataset)\n        losses.append(loss.numpy())\n        \n        training_sum = 0\n\n        print_statement = \"Loss :\" + str(loss.numpy()) + \" Evaluating Accuracy ...\"\n        pbar.set_postfix_str(print_statement)\n\n        for X_batch, y_batch in dataset:\n            training_sum += sum(predict(model, X_batch)==y_batch.numpy())\n        accuracy.append(training_sum\/training_dataset_size)\n\n        with file_writer.as_default():\n            tf.summary.scalar('Loss', data=loss.numpy(), step=i)\n            tf.summary.scalar('Accuracy', data=accuracy[-1], step=i)\n        \n        print_statement = \"Loss :\" + str(loss.numpy()) + \" Accuracy :\" + str(accuracy[-1])\n\n#         if i % 10 == 0:\n#             print_statement += ' Checkpoint Saved'\n#             checkpoint.save(checkpoint_path)\n        \n        pbar.set_postfix_str(print_statement)\n# Load the dataset from Kaggle\ndef get_cv2_image(path, img_size, color_type):\n    # Loading as Grayscale image\n    if color_type == 1:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    # Loading as color image\n    elif color_type == 3:\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\n    # Reduce size\n    img = cv2.resize(img[:500], img_size) \n    return img\n\ndef load_data(img_size , color_type, training):\n    start_time = time.time()\n    training_images = []\n    training_labels = []\n\n    # Loop over the training folder \n    for class_ in tqdm(range(classes)):\n        \n        print('Loading directory c{}'.format(class_))\n        if(training):\n            files = glob(os.path.join('..\/input\/state-farm-distracted-driver-detection\/imgs\/train', 'c' + str(class_), '*.jpg'))\n        else:\n            files = glob(os.path.join('..\/input\/state-farm-distracted-driver-detection\/imgs\/test', 'c' + str(class_), '*.jpg'))\n        \n        for file in files:\n            img = get_cv2_image(file, img_size , color_type)\n            training_images.append(img)\n            training_labels.append(class_) \n    \n    print(\"Data Loaded in {} Min\".format((time.time() - start_time)\/60))\n    return training_images, training_labels \n\ntrain_X, train_y = load_data( (imageWidth,imageHeight) , colorDepth, True)\ntest_X, test_y = load_data( (imageWidth,imageHeight) , colorDepth, False)\n\ntrain_y = np_utils.to_categorical(train_y, classes)\ntest_y = np_utils.to_categorical(test_y, classes)\n\n#now we prep our data\nnpLabels = np_utils.to_categorical(labels, classes) #we're casting the list of ints as a list of class labels\ntrainingImages, validationImages, trainingLabels, validationLabels = train_test_split(images, npLabels, test_size=0.15,shuffle=True)\n\n#transform our images into array that can be fed into the machine learning model\ntrainingImages = np.array(trainingImages).reshape(len(trainingImages),imageWidth,imageHeight,colorDepth)\nvalidationImages = np.array(validationImages).reshape(len(validationImages),imageWidth,imageHeight,colorDepth)\n\nprint(type(trainingImages))\nresNet  = tf.keras.applications.resnet.ResNet50(include_top = False,weights = 'imagenet',input_shape = (imageWidth,imageHeight,colorDepth))\nresNet.summary()\n#resnet50 has some random output, we need to add a final layer that fits the output of our problem\n#preppedOutput = resNet.output #set this layer to the output layer of initial model\n#preppedOutput = tf.keras.layers.Flatten()(preppedOutput) #this takes our many dimensional output, and converts it to a longer 1 dimensional output\n\n#add a dense fully connected output with a number of nodes equal to our classes\n#ourOutput =tf.keras.layers.Dense(classes,activation = tf.nn.softmax)(preppedOutput)\n#finalModel = tf.keras.models.Model(inputs=resNet.inputs, outputs=ourOutput)\n\n#let's use a simple bread and butter model model and compare the two!\nsimpleModel = Sequential([\n  layers.experimental.preprocessing.Rescaling(1.\/255, input_shape=(100, 100, colorDepth)),\n  layers.Conv2D(16, 3, padding='same', activation='relu'),\n  layers.MaxPooling2D(),\n  layers.Conv2D(32 * 8, [9,9], strides=[2,2], name=\"PrimaryCapsule\"),\n  layers.Conv2D(32, 3, padding='same', activation='relu'),\n  layers.MaxPooling2D(),\n  layers.Conv2D(64, 3, padding='same', activation='relu'),\n  layers.Dropout(0.5),\n  layers.MaxPooling2D(),\n  layers.Flatten(),\n  layers.Dense(128, activation='relu'),\n  layers.Dense(classes)\n])\n\n\n\n#compile the model with the learning rate specified above, and standard loss config from resnet example\n#finalModel.compile(optimizer=tf.keras.optimizers.Adam(learningRate),\n#              loss=tf.keras.losses.CategoricalCrossentropy(from_logits = False),\n#              metrics=['accuracy'])\n\nsimpleModel.compile(optimizer=tf.keras.optimizers.Adam(learningRate),\n              loss=tf.keras.losses.CategoricalCrossentropy(from_logits = False),\n              metrics=['accuracy'])\n\n#print model details\n#finalModel.summary()\nsimpleModel.summary()\nmodel2 = Sequential()\nmodel2.add(Dense(500, input_dim=2, activation='relu'))\n\nmodel2.add(Dense(1, activation='sigmoid'))\nmodel2.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel2.summary()\n#train resnet model\ntrainingResNet = finalModel.fit(\n      x = train_X,y=train_y,#training data\n      validation_data=(test_X,test_y), #validation data\n      batch_size = batchSize,\n      epochs=epochNum,\n      verbose=1)\n#train our simple model\ntrainingSimple = simpleModel.fit(\n      x = train_X,y=train_y,#training data\n      validation_data=(test_X,test_y), #validation data\n      batch_size = batchSize,\n      epochs=epochNum,\n      verbose=1)","meta":"{'source': 'AI4Code', 'id': 'acdff54941c8f9'}"}
{"id":"111002","text":"\"\"\"\n<center><font size=\"6\">FASHION MNIST: EASY WAY TO IMPLEMENT A CONVOLUTIONAL NEURAL NETWORK (CNN)<\/font><\/center>\n\n<br>\n\n<img src=\"https:\/\/raw.githubusercontent.com\/OriolGilabertLopez\/MachineLearning\/master\/Projects\/MachineLearning\/FashionMNIST\/Auxiliars\/Images\/Clothes.JPG\" width=\"900px\">\n\"\"\"\n\"\"\"\n# <a id='0'>Content<\/a>\n\n- <a href='#1'>1. INTRODUCCI\u00d3N<\/a>  \n- <a href='#2'>2. IMPORTACI\u00d3N DE DATOS<\/a>  \n- <a href='#3'>3. CONJUNTO DE DATOS<\/a>  \n    - <a href='#3.1'>3.1. Categorias de los datos<\/a>\n    - <a href='#3.2'>3.2. \u00bfC\u00f3mo son las im\u00e1genes?<\/a>\n- <a href='#4'>4. QUICK VIEW DE LOS DATOS<\/a>  \n    - <a href='#4.1'>4.1. Distribuci\u00f3n por clases<\/a>\n    - <a href='#4.2'>4.2. Visualizando la matriz como im\u00e1genes<\/a>\n        - <a href='#4.2.1'>4.2.1. Muestra train<\/a>\n        - <a href='#4.2.2'>4.2.1. Muestra test<\/a>\n- <a href='#5'>5. PREPROCESAMIENTO DE LOS DATOS<\/a>  \n    - <a href='#5.1'>5.1. Feature Engineering<\/a>\n    - <a href='#5.2'>5.2. Split del datset train para el entrenamiento del modelo<\/a>\n- <a href='#6'>6. MODELO<\/a>  \n    - <a href='#6.1'>6.1. Partes del Modelo<\/a>\n        - <a href='#6.1.1'>6.1.1. Modelo Parte 1<\/a>\n        - <a href='#6.1.2'>6.1.2. Modelo Parte 2<\/a>\n        - <a href='#6.1.3'>6.1.3. Modelo Parte 3<\/a>\n    - <a href='#6.2'>6.2. Evaluaci\u00f3n del modelo<\/a>\n    - <a href='#6.3'>6.3. Predicciones en base al modelo<\/a>\n    - <a href='#6.4'>6.4. Matriz de Confusi\u00f3n: Evaluaci\u00f3n de las Predicciones<\/a>\n- <a href='#7'>7. CONCLUSIONES<\/a>  \n- <a href='#8'>8. REFERENCIAS<\/a>  \n\"\"\"\n\"\"\"\n<a id=\"1\"><\/a>\n# 1. INTRODUCCI\u00d3N\n\nActualmente, la clasificaci\u00f3n de cualquier objeto por imagen es una realidad gracias el Machine Learning. Una herramienta tan potente como \u00e9sta ha dado vida a abrir nuevas investigaciones en el mundo de la estad\u00edstica, biolog\u00eda y cualquier rama que use las ciencias computacionales. \n\n\u00a1Vamos!\n\n<br>\n\n__\u00bfQu\u00e9 encontraras en este notebook?__\n * __An\u00e1lisis Descriptivo:__ Estudiaremos con una descriptiva b\u00e1sica los datos. Hay que conocerlos antes de actuar\n * __Selecci\u00f3n del Modelo:__ Seleccionaremos una __R__ed __N__ueronal __C__onvolucional  como modelo para la clasificaci\u00f3n de las im\u00e1genes\n * __Construcci\u00f3n del Modelo:__ Estudiaremos el overfitting para que el modelo generalice las predicciones (no s\u00f3lo lo haga para sus datos de entrenamiento). Se pondr\u00e1n caps de regularizaci\u00f3n, filtros, se aplicara reducci\u00f3n de la dimensionalidad... \n * __Selecci\u00f3n del Algortimo de Optimizaci\u00f3n:__ Seleccionaremos un algoritmo adecuado para la optimizaci\u00f3n del modelo en cuanto a su convergencia que, seg\u00fan pruebas realizadas en algunos estudios, marcan la diferencia entre los buenos resultados y los malos. En nuestro caso, creemos adecuado aplicar el algoritmo de optimizaci\u00f3n __Adam__, una extensi\u00f3n del algoritmo Stochastic Gradiente Descent (SGD)\n * __Valorac\u00f3n del Modelo:__ Valoraremos la __precisi\u00f3n\/accuracy__ y la __p\u00e9rdida\/loss__ del conjuntos de datos de validaci\u00f3n. \n * __Predicciones:__ Haremos las predicciones con los datos test\n * __Valoraci\u00f3n de las Predicciones:__ Sacaremos una matriz de confusion para evaluar la calidad de las predicciones\n\"\"\"\n\"\"\"\n<a id=\"2\"><\/a>\n# 2. IMPORTACI\u00d3N DE DATOS\n\nEl primer paso que debemos realizar es importar los datos, visualizarlos y tener una idea general de como son y como se distribuyen. Nuestra ruta para importar las im\u00e1genes es la siguiente: _`\/kaggle\/input\/fashionmnist\/...`_\n\nPara ello, debemos cargar antes los datos al notebook (`+ Add data`) y seguidamente leemos los paths con la ayuda de la libreria `import pandas`. El c\u00f3digo es el siguiente: \n\"\"\"\nimport pandas as pd\n\ntrainData = pd.read_csv('\/kaggle\/input\/fashionmnist\/fashion-mnist_train.csv')       \ntestData = pd.read_csv('\/kaggle\/input\/fashionmnist\/fashion-mnist_test.csv')  \n\"\"\"\n<a id=\"3\"><\/a>\n# 3. CONJUNTO DE DATOS\n\n<br>\n    \nNuestro conjunto de datos esta formado por 70.000 im\u00e1genes, el cual est\u00e1 dividido en dos subconjuntos:  __train__ y __test__. Los conjuntos de datos tienen las siguientes caracter\u00edsticas:\n * __Train:__ Se utilizar\u00e1 para entrenar el modelo. Este set contiene el 85% de todas las imagenes, es decir, un total de 60.000 im\u00e1genes donde cada una esta formada por 784 p\u00edxeles.\n * __Test:__ Se utilizar\u00e1 para probar el modelo. Este set contiene el 15% de todas las imagenes, es decir, un total de 10.000 im\u00e1genes donde cada una esta formada por 784 p\u00edxeles.\n<br>\n\n\n## 3.1. Categorias de los datos\n\n |   \u00cdndice    |        Categoria          |\n |-------------|---------------------------|\n |      0      |      Camiseta \/ top       |    \n |      1      |        Pantal\u00f3n           |\n |      2      |         Jersey            |\n |      3      |        Vestido            |\n |      4      |        Abrigo             |\n |      5      |       Sandalia            |\n |      6      |        Camisa             |\n |      7      |  Zapatilla de deporte     |\n |      8      |        Bolsa              |\n |      9      |        Bot\u00edn              |\n\n\n<br>\n\n<a id=\"3.2\"><\/a>\n## 3.2. \u00bfC\u00f3mo son las im\u00e1genes? \n\nCada imagen es una matriz cuadrada I$_{i}$ $\\in$ M$_{m,n}$ d\u00f3nde m,n = 28 p\u00edxeles. Cada uno de los p\u00edxeles que describen la matriz representa el brillo (o color) de dicho p\u00edxel. En el caso m\u00e1s sencillo de im\u00e1genes binarias, el valor del p\u00edxel es un n\u00famero de un bit que indica el primer plano o el fondo del imagen. Un ejemplo sencillo es el s\u00edmbolo del _Yin y el  Yang_. Pero nosotros estamos en una situaci\u00f3n diferente, donde cada imagen tiene tonalidades diferentes ya que estamos en un caso donde el color es una escala de grises. \n<br>\n\nEn este caso, estamos en un formato de imagen tipo byte (el n\u00famero se almacena como un entero de 8 bits, es decir, un byte) lo que nos da un rango de posibles valores que fluct\u00faan entre 0 y 255 donde, normalmente, 255 es el blanco y 0 el negro.\n\n<br>\n<a id=\"3.3\"><\/a>\n\n## 3.3. \u00bfSe puede utilizar Deep Learning para este conjunt de datos? \nEn este escenario, tenemos que cada imagen tiene un total de 785 p\u00edxeles (28x28), es decir, tenemos un total aproximado de 55 millones de valores para todo el conjunto de datos, por lo tanto, es una cifra aceptable para un proyecto de DL\n\n\"\"\"\n\"\"\"\n<a id=\"4\"><\/a>\n# 4. QUICK VIEW DE LOS DATOS\n\n<br>\nLo primero que debemos hacer es visualizar las dimensi\u00f3n del dataset:\n\"\"\"\nprint('\\t Filas,  Columnas', )\nprint('Train:\\t', trainData.shape)\nprint('Test:\\t', testData.shape)\n\"\"\"\nSeguidamente, debemos comprobar si existen datos faltantes:\n\"\"\"\ndef cehck_nulls(data):\n    if data.isnull().any().any() == False:\n        return print('los datos NO conetienen valores Null')\n    else:\n        return print('los datos SI conetienen valores Null')\n\ncehck_nulls(trainData)\ncehck_nulls(testData)\n\"\"\"\n<a id=\"4.1\"><\/a>\n## 4.1. Distribuci\u00f3n por clases\n\n\"\"\"\n\"\"\"\nNo menos importante es visualizar la matriz de datos, pues nos es imprescindible para manejarlos y saber con cual de las columnas asociar las etiquetas. Para ello, mostramos las 3 primeras y \u00faltimas filas del data set Train (idem por el test):\n\"\"\"\ntrainData.head(4).append(trainData.tail(3))\n\"\"\"\nComo podemos observar, la primera columna `label` (no confindir con el \u00edndice) es la que nos referencia que tipo de prenda es, por ejemplo, la primera fila el valor de `label` es 2, por lo que nosotros podemos afirmar que ese conjunto de p\u00edxeles conforman la prenda __jersey__. Crearemos una nueva columna llamada `labelName` (qualitativa) que ser\u00e1 la transcripcion de `label` (quantitativa):\n\n\"\"\"\nlabels = {  0: \"Camiseta \/ Top\",\n            1: \"Pantal\u00f3n\",\n            2: \"Jersey\",\n            3: \"Vestido\",\n            4: \"Abrigo\",\n            5: \"Sandalia\",\n            6: \"Camisa\",\n            7: \"Zapatilla de deporte\",\n            8: \"Bolsa\",\n            9: \"Botines\"\n         }\n\nn_cat = len(labels)\n\ndef add_column_from_dict(data, col, new_col, dict_):\n    data[new_col] = data[col].map(dict_)\n    return data\n\nadd_column_from_dict(trainData, 'label', 'labelName', labels)\nadd_column_from_dict(testData, 'label', 'labelName', labels)\n\"\"\"\nSegidamente, crearemos una funci\u00f3n llamada `pie_plot()` que nos graficar\u00e1 la distribuci\u00f3n de prendas de ropa seg\u00fan el conjuto de datos introducidos:\n\"\"\"\nimport matplotlib.pyplot as plt\n\ndef pie_plot(data, plotTitle):\n    \n    aux = data['labelName'].value_counts().to_frame('Freq')\n    aux['labelName'] = aux.index \n    valores = aux['Freq']\n    \n    def pct_abs(values):\n        def funct(pct):\n            total = sum(values)\n            val = int(round(pct * total \/ 100.0))\n            return '{p:.2f}%\\n({v:d} it'.format(p = pct,v = val)\n        return funct\n\n\n    plt.figure(figsize = (16,8))\n\n    ax1 = plt.subplot(121, aspect = 'equal')\n    aux.plot(kind = 'pie', \n             y = 'Freq', \n             ax = ax1,\n             autopct = pct_abs(valores), \n             labels = aux['labelName'], \n             legend = False,\n             title = plotTitle,\n             fontsize = 10)\n\n    # plot table\n    ax2 = plt.subplot(122)\n    plt.axis('off')\n    plt.show()\n    \n    \nplot1 = pie_plot(trainData,'Distribuci\u00f3n de la ropa para el conjunto de datos TRAIN')\nplot2 = pie_plot(testData, 'Distribuci\u00f3n de la ropa para el conjunto de datos TEST')\nplt.show()\n\"\"\"\nObservamos que cada prenda de ropa se distribuye por igal para cada uno de los conjuntos de datos (10 calses donde cada clase representa un 10% del total).\n\"\"\"\n\"\"\"\n<a id=\"4.2\"><\/a>\n## 4.2. Visualizando la matriz como im\u00e1genes\n\n<br>\n\nProcedemos a cear una funci\u00f3n que nos graficar\u00e1 la prenda seleccionadndo una fila de la matriz (1 fila = 1 prenda). Para ello, redimensionamos la fila de p\u00edxeles (una fila = una imagen, es decir, un vector $V = (v_1, v_2, ..., v_n)$ donde $n$ = 784 ) a una matriz de I $\\in$ M$_{m,n}$, donde $m, n = 28$.\n\n\"\"\"\nimport numpy as np\n\ndef plot_image_sample(data, label_number, DataSetType, pf, pc):\n    \n    type_data = ('TRAIN' if DataSetType.lower().find(\"train\") == label_number else 'TEST')\n    \n    # Obtenemos la etiqueta (diccionario)\n    etiqueta = labels[label_number]\n    # Eliminamos la primera columna (codigo etiqueta) y la \u00faltima (nombre etiqueta)\n    aux = data[data[\"label\"] == label_number].sample(1)\n    aux2 = aux.iloc[:, 1:-1]\n    img = np.array(aux2).reshape(pf, pc)\n\n    plt.imshow(img, cmap = 'gray')\n    plt.grid(True)\n    plot = plt.title('Ropa: ' + str(etiqueta) + '\\nDatos: ' + str(type_data))\n    \n\ndef matrix_image_sample(data, label_number, pf ,pc):\n    \n    pd.options.display.max_columns = None\n    aux = data[data[\"label\"] == label_number].sample(1)\n    aux2 = aux.iloc[:, 1:-1]\n    img = pd.DataFrame(np.array(aux2).reshape(pf, pc))\n\n    return img \n\"\"\"\n<a id=\"4.2.1\"><\/a>\n## 4.2.1. Muestra train\n\nComo ya hemos hablado antes, mostramos la imagen con una dimension de 28x28. Para ello, definimos dos parametros _**pf**_ y _**pc**_:\n\n   * **pf** $\\rightarrow$ 28 ( _p\u00edxeles fila_ )\n   * **pc** $\\rightarrow$ 28 ( _p\u00edxeles columna_ )\n \nProcedemos a visualizar para una prenda de ropa su matrix de datos y su apariencia real: \n\"\"\"\npf = 28\npc = 28\n\nplot_image_sample(trainData, 9, 'train', pf, pc)\nmatrix_image_sample(trainData, 9, pf, pc)\n\"\"\"\n<a id=\"4.2.2\"><\/a>\n## 4.2.2. Muestra test\n\n\"\"\"\nplot_image_sample(testData, 3, 'Test', pf, pc)\nmatrix_image_sample(testData, 3, pf, pc)\n\"\"\"\n<a id=\"5\"><\/a>\n# 5. PREPROCESAMIENTO DE LOS DATOS\n\n<a id=\"5.1\"><\/a>\n\n##\u00a05.1. Feature Engineering\n\n<br>\n\nLa __feature engineering__ es simplemente un proceso ed exploracion de datos, por ejemplo, saber si nuestros datos se deben __escalar__, __estandarizar__, __normalizar__ o __transformar__ (algunas redundantes). \n<br>\n\nRealmente, para la __feature engineering__ no existe una regla f\u00e1cil o com\u00fan que debamos utilizar, pero con experiencia, se puede llegar a ciertas conclusiones. Por ejemplo, se sabe que dividir por 255 una matriz de datos cuando \u00e9sta representa valores asociados a escalas de grises (de 0 a 255), produce una mejora en la convergencia de algunas funciones como puede ser la sigmoide, la cual trabaja con valores $x \\in$ $[0, 1]$. Adem\u00e1s, esto puede causar una explosi\u00f3n del gradiente (no entraremos ahora en esto). Sin afirmar nada pero como regla general, yo escalaria los datos primero y luego entrenaria el modelo.\n<br>\n\nPor otro lado, si los datos est\u00e1n normalizados o centrados en cero, los valores de los p\u00edxeles son peque\u00f1os (a\u00fan siendo valores peque\u00f1os, estos no pierden la representatividad de la imagen original) y, por lo tanto, el c\u00e1lculo requerido y el tiempo para la convergencia del modelo se reducen significativamente. \n\n\nPensad que durante la __forward propagation__ (propagaci\u00f3n hacia adelante), se realizan productos sobre los valores de los p\u00edxeles con la matriz de peso para esa capa en particular. Ahora, multiplicar esos grandes valores de p\u00edxeles requiere muchos recursos computacionales y de tiempo. Y, por lo tanto, el modelo converge muy lentamente.\n\n\n\n\"\"\"\nimport keras\n\ndef preprocesamiento(data, pf, pc):\n    \n    out_Y = keras.utils.to_categorical(data.label, len(labels))\n    x_vect = data.values[:,1:-1]  #transformamos el dataFrame en un ndarray, seleccionando solo los p\u00edxeles\n    x_scaled = x_vect \/ 255 # Dividimos por 255 por literatura (convergencia del gradiente, evita le colapso)\n    n_img = data.shape[0]\n    out_X = x_scaled.reshape(n_img, pf, pc, 1) # redimensionamos el vector a (1,784) a (28, 28, 1)  \n    \n    out_X = out_X.astype(float)\n    out_Y = out_Y.astype(float)\n    \n    return out_X, out_Y\n\"\"\"\n<u>__\u00bfQu\u00e9 es lo que hace \u00e9sta funci\u00f3n?__<\/u>\n\n\nSi somos un poco curosos, observamos que:\n\n 1. Separamos la variable quantitativa `label` y la asociamos a la variable`out_Y`, la cual devolver\u00e1 la _respuesta_. Destacar que la respuesta es ahora un vector, por ejemplo, si:\n \n     * `label = 0` $\\rightarrow$ `(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)`\n     * `label = 1` $\\rightarrow$ `(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)`\n     * $\\vdots$              \n     * `label = 9` $\\rightarrow$ `(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)`\n     \n 2. Seleccionamos solo las columnas referente a los p\u00edxeles, es decir, quitamos las varibles referentes a las etiquetas (`label` y `labelName`). El resultado lo asociamos a la variable `x_vect`.\n 3. Procedemos a realizar el reescalado de los datos, cogiendo todo el vector y dividi\u00e9ndola por 255. El resultado lo asociamos a la variable `x_scaled`.\n 4. Redimensionamos cada una de las im\u00e1genes a (28, 28, 1), el formato ideal para introducirlo al modelo\n\n\n\n\n\"\"\"\nx_train, y_train = preprocesamiento(trainData, pf, pc)\nx_test, y_test = preprocesamiento(testData, pf, pc)\n\"\"\"\n<a id=\"5.2\"><\/a>\n## 5.2. Split del datset train para el entrenamiento del modelo\n\n\n\"\"\"\n\"\"\"\nNormalmente lo que se hace es coger los datos train y dividir dicho set en dos, una parte para entrenar el modelo y otra parte para validarlo. Luego, se predice con los datos test original (no del train)\n\nEs decir, del conjunto de datos total:\n\"\"\"\n\"\"\"\n\n<img src=\"https:\/\/raw.githubusercontent.com\/OriolGilabertLopez\/MachineLearning\/master\/Projects\/MachineLearning\/FashionMNIST\/Auxiliars\/Images\/FullData_Tran%26Val.png\" width=\"400px\">\n<br>\n\"\"\"\n\"\"\"\nEscogemos solo el set train (azul) y lo dividimos en 80% train y 20 test (o validaci\u00f3n) de la siguiente manera:\n\"\"\"\n\"\"\"\n\n<img src=\"https:\/\/raw.githubusercontent.com\/OriolGilabertLopez\/MachineLearning\/master\/Projects\/MachineLearning\/FashionMNIST\/Auxiliars\/Images\/SplitTrain_with_Train%26Val.png\" width=\"400px\">\n\n\n<br>\n\"\"\"\n\"\"\"\nExiste una funci\u00f3n en __sklearn__ que realiza dicho split del dataset automaticamente. Seg\u00fan la literatura (concretamente lo menciona __Aur\u00e9lien G\u00e9ron__ en el manual __Hand on machine learning with scikit-learn and tensorflow pdf__) el valor de la semilla (si se deseja fijar y mantener su reproducibilidad) se fija normalmente en el valor __42__.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, Y_train, Y_val = train_test_split(x_train, y_train, test_size = 0.3, random_state = 42)\n\"\"\"\nUnificamos el datatype del vector a un `float`\n\"\"\"\n\"\"\"\nAhora, por ejemplo, las distribuci\u00f3n de las prendas de ropa es la siguiente:\n\"\"\"\ndef proc_data_to_plot(data):\n\n    freq = []\n    for i in range(len(data)):\n        freq.append(np.argmax(data[i]))\n        \n    return pd.DataFrame(freq, columns = ['Label'])\n    \n    \n    \nTrain_labels_to_plot = proc_data_to_plot(Y_train) \nVal_labels_to_plot = proc_data_to_plot(Y_val) \n\nTrain_labels_to_plot = add_column_from_dict(Train_labels_to_plot, 'Label', 'labelName', labels)\nVal_labels_to_plot = add_column_from_dict(Val_labels_to_plot, 'Label', 'labelName', labels)\n\n\nplot1 = pie_plot(Train_labels_to_plot,'Distribuci\u00f3n de la ropa para el conjunto de datos TRAIN')\nplot2 = pie_plot(Val_labels_to_plot, 'Distribuci\u00f3n de la ropa para el conjunto de datos de VALIDACION')\nplt.show()\n\"\"\"\n<a id=\"6\"><\/a>\n# 6. MODELO\n\n\"\"\"\n\"\"\"\nEn python exisen varias maneras de implementar un modelo, en nuestro caso, usearemos el __secuencial__ (`model = Sequential()`). Este funciona a\u00f1adiendo capas de c\u00f3digo como se puede observar en el sigueinte chunk.\n\n\n<a href='#6.1'><\/a>\n\n## 6.1 Partes del Modelo\n\n<a id=\"6.1.1\"><\/a>\n### 6.1.1 Modelo Parte 1\n    \n* __LeakyReLU__:  Definimos la funcion __LeakyReLU__ como funcion de activaci\u00f3n. Esta funci\u00f3n es m\u00e1s eficaz que la ReLU comunmente conocida.  \n* __Capa convolucional 2D (Conv2D)__:\n    * __Filtros__: Numero de filtros (kernels) utilizados en esta capa son 32\n    * __kernel_size__: Dimmensi\u00f3n del Kernel: (3 x 3)\n    * __activation__: Utilitzamos la funci\u00f3n `LeakyReLU`\n    * __kernel_initializer__: Funci\u00f3n utilizada para inicializarel kernel: `he_normal`. Solo se utiliza en la primera capa. Esta [funcion](http:\/\/man.hubwiz.com\/docset\/TensorFlow.docset\/Contents\/Resources\/Documents\/api_docs\/python\/tf\/keras\/initializers\/he_normal.html) se basa en muestras de una distribuci\u00f3n normal truncada centrada en $0$ con $sd = \\sqrt(\\frac{2}{fan_{in}})$ donde $fan_{in}$ es el n\u00famero de unidades de entrada en el tensor (\"vector\").\n    * __input_shape__: Dimensi\u00f3n de la imagen presentada a la CNN: en nuestro caso es una imagen de 28 x 28. La entrada y salida del Conv2D es un tensor 4D.\n* __MaxPooling2D__: La capa de reducci\u00f3n o pooling se coloca generalmente despu\u00e9s de la capa convolucional. La funci\u00f3n principal radica en la reducci\u00f3n de las dimensiones (anchura y altura) de entrada para la siguiente capa convolucional. Esto est\u00e1 muy bien, pero la reducci\u00f3n del volumen de datos conlleva intr\u00ednsecamente la p\u00e9rdida de informaci\u00f3n, sin embargo, la reducci\u00f3n de la informaci\u00f3n puede ser algo banefici\u00f3s para la red por tres razones:\n    \n     * Reduce la sobrecarga de c\u00e1lculos para las pr\u00f3ximas capas de la red \n     * Reduce el overfitting (o el sobreajustmanet)\n     * Favorece una computaci\u00f3n ligera\n  \n  Sin alargarme m\u00e1s, en nuestro caso aplicamos un reduccion de (2, 2), reducimos 2 en $y$ y 2 en $x$\n         \n* __Dropout__: En redes neuronales profundas, tener una gran cantidad de par\u00e1metros hace que el overfitting tome un rol importante en las predicciones. El overfitting es un problema frecuente que requiere de t\u00e9cnicas para su regulaci\u00f3n. As\u00ed pues, la t\u00e9cnica de regularizaci\u00f3n m\u00e1s popular para redes neuronales profundas es, sin duda, el __dropout__. La idea clave es que, en cada uno de los pasos del entrenamiento, desactive aleatoriamente neuronas (incluyendo las neuronas de entrada, pero excluyendo las neuronas de salida). Concretamente, cada neurona est\u00e1 determinada por una probabilidad $p$ de ser temporalmente abandonadas, lo que se llama en ingl\u00e9s neuronas en estado _dropped-out_. Esto significa que, las neuronas que pertenezcan en este estado ser\u00e1n totalmente ignoradas durante el entrenamiento. El hiperparam\u00e8metre $p$ se denomina __tasa de abandono__ o __dropout rate__ y normalmente se sit\u00faa en el 50%, es decir, $p$ = 0.5. Este valor $p$ es totalmente fluctuable y no se rigue por reglas concretas. \n\n  Pues en nuestro caso fijaremos este parametro en $p$ = 0.3\n\n_Code:_\n\n`model = Sequential()\nLeakyReLU = lambda x: tf.keras.activations.relu(x, alpha=0.1)\nmodel.add(Conv2D(32, \n                 kernel_size = (3, 3),\n                 activation = LeakyReLU,\n                 padding=\"same\",\n                 input_shape=(pf, pc, 1)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.3)`\n\n                  \n\n\n\n<a id=\"6.1.2\"><\/a>\n### 6.1.2 Modelo Parte 2\n    \n\n  \n* __Capa convolucional 2D__:\n    * __Filtros__: 64\n    * __kernel_size__: (3 x 3)\n    * __activation__: Utilitzamos la funci\u00f3n `LeakyReLU`\n    * __input_shape__: 28 x 28\n* __MaxPooling2D__: (2, 2)\n* __Dropout__: 0.5\n\n_Code:_\n\n`model.add(Conv2D(64, \n                  kernel_size = (3, 3),\n                  activation = LeakyReLU,\n                  input_shape=(pf, pc, 1)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.5))`\n\n\n\n\n\n<a id=\"6.1.3\"><\/a>\n### 6.1.3 Modelo Parte 3\n    \n\n\n* __Capa convolucional 2D__:\n    * __Filtros__: 128\n    * __kernel_size__: (3 x 3)\n    * __activation__: Utilitzamos la funci\u00f3n `LeakyReLU`\n* __Flatten__: Esta capa aplana la entrada y Se usa sin parametros \n* __Dense__:\n    * __unidades__: 128 (debe ser positivo)\n    * __activation__: Utilitzamos la funci\u00f3n `LeakyReLU`\n.\n* __Dropout__: 0.3\n* __Dense - Fully Connected__: Esta es la capa final (completamente conectada). \n    * __unidades__: Numero de categorias a predecir, en nuestro caso, 10.\n    * __activation__: `softmax` (est\u00e1ndar para la clasificaci\u00f3n multiclase)\n    \n\n\n_Code:_\n\n`model.add(Conv2D(128, (3, 3), activation = LeakyReLU))\nmodel.add(Flatten())                               \nmodel.add(Dense(128, activation = LeakyReLU))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(n_cat, activation = 'softmax'))`               \n\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense, Flatten, Conv2D, Dropout, MaxPooling2D\n\n\n\n#Parte 1 del modelo\nmodel = Sequential()\n\nLeakyReLU = lambda x: tf.keras.activations.relu(x, alpha=0.1)\nmodel.add(Conv2D(32, \n                 kernel_size = (3, 3),\n                 activation = LeakyReLU,\n                 padding=\"same\",\n                 input_shape=(pf, pc, 1)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.3))\n\n\n#Parte 2 del modelo\nmodel.add(Conv2D(64, \n                 kernel_size = (3, 3), \n                 activation = LeakyReLU,\n                 padding=\"same\"))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Dropout(0.5))\n\n\n#Parte 3 del modelo\nmodel.add(Conv2D(128, (3, 3), activation = LeakyReLU))\nmodel.add(Flatten())                               # Flatemos el tensor de pixeles:\nmodel.add(Dense(128, activation = LeakyReLU))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(n_cat, activation = 'softmax'))    #\u00a0La ultima capa debe ser el n\u00ba de lables a predecir\n\n\n\"\"\"\nAhora que hemos definido como sera la red neuronal ahora, debemos elegir la __funci\u00f3n de coste__, un __optimizador__ y las __m\u00e9tricas de rendimiento__, es decir, la __compilaci\u00f3n__ del modelo.\n\nEn nuestero caso eligiremos lo siguiente:\n\n* __FUNCI\u00d3N DE COSTE__ --> `categorical_crossentrop`: Para un problema de clasificaci\u00f3n como el nestro que tiene 10 clases posibles etiquetas, necesitamos usar la funci\u00f3n de p\u00e9rdida llamada `categ\u00f3rica_crossentropy`. \n* __OPTIMIZADOR__ --> `adam`: Una de las partes m\u00e1s importantes del modelo es la elecci\u00f3n del m\u00e9todo de optimizaci\u00f3n. La elecci\u00f3n del algoritmo de optimitzaci\u00f323 marca la diferencia entre buenas y malas predicciones. En nuestro caso, hemos seleccionado el algoritmo de optimizaci\u00f3n [Adam](https:\/\/machinelearningmastery.com\/adam-optimization-algorithm-for-deep-learning\/) (existen otros como  el stochastic gradiente descent (SGD), Mini-batch gradiente descent (MBGD), ...), el cual es extensi\u00f3n del SGD. Adam, seg\u00fan los autorses, es computacionalmente eficiente, necesita pocos requisitos de memoria y, adem\u00e1s, es adecuado para grandes cantidades de datos.\n\n* __M\u00c9TRICA DE RENDIMIENTO__ --> `Accuracy`. Nos ayudar\u00e1 a validar el modelo \n\"\"\"\nmodel.compile(loss = keras.losses.categorical_crossentropy,\n              optimizer = 'adam',\n              metrics = ['accuracy'])\nmodel.summary()\nfrom keras.utils.vis_utils import model_to_dot\nfrom IPython.display import SVG\n\n\nSVG(model_to_dot(model).create(prog='dot', format='svg'))\nbatch = 70\nepocas = 50\n \ntrain_model = model.fit(X_train, Y_train,\n                        batch_size = batch,\n                        epochs = epocas,\n                        verbose = 1,\n                        validation_data = (X_val, Y_val))\n\"\"\"\n<a id=\"6.2\"><\/a>\n## 6.2 Evaluaci\u00f3n del modelo\n\n\n\"\"\"\nscore = model.evaluate(x_test, y_test, verbose = 0)\nprint('Perdida\/Loss Test:', score[0])\nprint('Precision\/Accuracy Test:', score[1])\nimport plotly.graph_objs as go\n\ndef interpolation_tracer(x, y, text, mode):\n    fig.add_trace(go.Scatter(x = x, \n                             y = y, \n                             name = text,\n                             mode = mode))\n    fig.update_yaxes(range=[0,1])\n    fig.update_xaxes(title_text = '\u00c9pocas')\n    fig.update_yaxes(title_text = 'Loss & Accuracy')\n    \ndef layout_plot(Titulo):\n    fig.update_layout(title = {'text': Titulo},\n                      xaxis_title = \"Accuracy\",\n                      yaxis_title = \"\u00c9pocas\",\n                      legend_title = \"Leyenda\",\n                      font = dict(family = \"Courier New, monospace\",\n                                  size = 18,\n                                  color = \"RebeccaPurple\"))\nhist = train_model.history\nacc = hist['accuracy']\nval_acc = hist['val_accuracy']\nloss = hist['loss']\nval_loss = hist['val_loss']\nepochs = list(range(1, len(acc) + 1))\n    \nfig = go.Figure()\ninterpolation_tracer(epochs, acc, 'Training accuracy', 'lines+markers')\ninterpolation_tracer(epochs, val_acc, 'Validation accuracy', 'lines+markers')\nlayout_plot('<b>Accuracy<\/b> entrenamiento y validaci\u00f3n')\nfig.show()\n\nfig = go.Figure()\ninterpolation_tracer(epochs,loss,'Training loss', 'lines+markers')\ninterpolation_tracer(epochs,val_loss,'Validation loss', 'lines+markers')\nlayout_plot('<b>Loss<\/b> entrenamiento y validaci\u00f3n')\nfig.show()\n\n\n\"\"\"\nAl entrenar un modelo de machine learning, una de las principales cosas que desea evitar ser\u00eda el overfitting (sobreajuste). \nEl overfitting _aparece_ cuando el __modelo se ajusta bien a los datos de entrenamiento, pero no puede generalizar y hacer predicciones precisas de datos que no ha visto antes__. \n\n\nLas m\u00e9tricas del conjunto de entrenamiento nos permitem ver c\u00f3mo progresa nuestro modelo en t\u00e9rminos del entrenamiento, pero son las m\u00e9tricas del conjunto de validaci\u00f3n las que nos permitiran obtener una medida de la calidad del modelo: qu\u00e9 tan bien es capaz de hacer nuevas predicciones basadas en datos que no ha visto antes.\n\n\nUn gr\u00e1fico de curvas de aprendizaje muestra sobreajuste si:\n* El evolutivo de la __training loss__ contin\u00faa disminuyendo con la experiencia.\n* El evolutivo de la __training loss__ disminuye hasta llegar a un punto de inflexi\u00f3n y comienza a aumentar nuevamente.\n\n\nEl punto de inflexi\u00f3n en la p\u00e9rdida de validaci\u00f3n puede ser el punto en el que el entrenamiento podr\u00eda detenerse ya que la experiencia despu\u00e9s de ese punto muestra la din\u00e1mica del overfitting.\n\nComo nos podemos imagniar, un buen ajuste es el objetivo de nuestro modelo. Un buen ajuste se identifica por una p\u00e9rdida de entrenamiento y validaci\u00f3n que disminuye hasta llegar a un punto de estabilidad con una brecha m\u00ednima entre los dos valores de p\u00e9rdida final.\n\nLa p\u00e9rdida del modelo casi siempre ser\u00e1 menor en el conjunto de datos de entrenamiento que en el conjunto de datos de validaci\u00f3n. Esto significa que debemos esperar cierta brecha entre ambas curvas, esta brecha se conoce como la __brecha de generalizaci\u00f3n__.\n\nSabiendo todo esto, podemos decir que nuestro modelo en general no presneta overfitting (o muy poquito) y, por este motivo, nuestras curvas de aprendizaje nos dan a entender que nuestro modelo tiene un buen ajuste. En otras palabas:\n\n* El evolutivo de la __training loss__ disminuye hasta llegar a un punto de estabilidad.\n* El evolutivo de la __training loss__ disminuye hasta llegar a un punto de estabilidad y presentna una peque\u00f1a brecha respecto la __training loss__.\n\n__NOTA:__ El entrenamiento continuo de un buen ajuste probablemente conducir\u00e1 a un sobreajuste.\n\n\"\"\"\n\"\"\"\n<a id=\"6.3\"><\/a>\n\n## 6.3 Predicciones en base al modelo\n\nAhora viene lo divertido, probar el modelo! Para ello, antens nos hemos reservado en conjunto de datos test. Con la funci\u00f3n `predict_classes()` llevaremos a cabo esta tarea.\n\nVamos a realizar las predicciones:\n\"\"\"\npred = model.predict_classes(x_test)\n\"\"\"\nparo... realmente que es lo que deberia haber predicho?. Para saber que es lo que deberia haber predicho sacamos las etiquetas reales del conjunto de entrenamiento:\n\"\"\"\ny_true = testData.iloc[:,0].to_numpy()\n\"\"\"\nComparamos las etiquetas predecidas con las reales (`pred[:10000] == y_true[:10000]`). Luego, sacamos aquellas que hayan hecho match, es decir, que has sido predecidas correctamente (` == True`). Con la funci\u00f3n `np.where()` sacamos el valor de indice (posici\u00f3n) de la etiqueta para saber a que n\u00famero se refiere y, finalmente, con `[0]` convertimos el resultado de `tupla` a `numpy.ndarray`.   \n\"\"\"\nn = len(pred[:10000])\n\nGoodPred = np.where((pred[:10000] == y_true[:10000]) == True)[0]\nBadPred  = np.where((pred[:10000] == y_true[:10000]) == False)[0]\n\nprint('Se han predicho correctamente ' + str(GoodPred.shape[0]) + \n      ' clases de ' + str(n) + '.\\tAcc: ' + str(round((GoodPred.shape[0]\/n)*100, 2)) + '%')\n\nprint('Se han predicho err\u00f3neamente ' + str(BadPred.shape[0]) +\n      ' clases de ' + str(n) + '.\\tAcc: ' + str(round((BadPred.shape[0]\/n)*100, 2)) + '%')\n\"\"\"\n<a id=\"6.4\"><\/a>\n\n## 6.4 Matriz de Confusi\u00f3n: Evaluaci\u00f3n de las Predicciones\n\n\nUna buena herramienta para visualizar sobre que objetos hemos predicho mal, es la matriz de confusi\u00f3n (o clasificaci\u00f3n). Esta matriz muestra como ha clasificado el modelo cada cinjunto de prendas. \n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\ndef Matriz_de_confusion(cm, clases,  normalize = False, title = 'Matriz de confusi\u00f3n', cmap = plt.cm.Oranges):\n    \n    plt.figure(figsize=(10 , 10) , dpi= 70)\n    plt.imshow(cm , \n               interpolation = 'nearest' , \n               cmap = cmap ) \n    plt.suptitle(title, fontsize=20)\n    tick_marks = np.arange(len(clases))\n    plt.xticks(tick_marks, \n               clases,\n               rotation = 45 )\n    plt.yticks(tick_marks, \n               clases)\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max()\/2.\n    for i, j in itertools.product(range(cm.shape[0]) , range(cm.shape[1]) ):\n        plt.text(j, i, format(cm[i, j] , fmt), \n        horizontalalignment = \"center\" ,\n        color=\"white\" if cm[ i, j] > thresh else \"black\" )\n        \n    plt.ylabel('Etiquetas reales')\n    plt.xlabel('Etiquetas predichas') \nnp.set_printoptions(precision = 2)\nsetLabels = [str(key) + str(': ') + labels[key] for key in labels]\n\n\nMatriz_de_confusion(confusion_matrix(y_true, pred), \n                    clases = setLabels )\n\"\"\"\n__INTERPRETACI\u00d3N__:\n\n\n__Ejes:__\n* En el __eje _x___ tenemos las etiquetas (o prendas) que el modelo ha predicho \n* En el __eje _y___ tenemos las etiquetas (o prendas) reales del dataset test\n\n\n\n__Valores:__\n* Caso de la etiqueta __0: Camiseta\/Top__: \n\n    1. El modelo ha predicho __895__ prendas de ropa como __Camiseta\/Top__ que realmente eran __Camiseta\/Top__\n    2. El modelo ha predicho __1__ prendas de ropa como __Pantal\u00f3n__ cuando realmente eran __Camiseta\/Top__\n    3. El modelo ha predicho __25__ prendas de ropa como __Jerseys__ cuando realmente eran __Camiseta\/Top__\n    4. El modelo ha predicho __15__ prendas de ropa como __Vestido__ cuando realmente eran __Camiseta\/Top__\n    5. El modelo ha predicho __2__ prendas de ropa como __Abrigo__ cuando realmente eran __Camiseta\/Top__\n    6. El modelo __no ha predicho ninguna Sandalia__ siendo en realida un __Camiseta\/Top__. El modelo distingue bien entre __Sandalias__ y __Camiseta\/Top__\n    7. Etc\u00e9tera\n    \n    As\u00ed pues, nos fijamos que la diagonal representa el n\u00famero de predicciones correctas y fuera de ella el n\u00famero de predicciones err\u00f3neas. \n\n\n__Valores Marginales:__\n* __Marginal de Y _(suma fila i-\u00e9ssima)___: N\u00famero de etiquetas reales. \n    1. El n\u00famero de etiquetas reales coinciden con el la suma de los marginales fila\n    2. Ex: __9: Botines__: 2 + 26 + 972 = __1000__ prendas\/etiquetas reales\n    3. Etc\u00e9tera\n \n \n* __Marginal de X _(suma columna i-\u00e9ssima)___:  N\u00famero de etiquetas predichas.\n    1. La suma de una columa no tiene por que ser el igual al n\u00famero de etiquetas reales para esa prenda, solo seria as\u00ed si el modelo fuese 100% eficaz.\n    2. Ex: __8: Bolsa__: 4 + 1 + 3 + 987 = __995__ Bolsas predichas, de las cuales  987 lo ha hecho satisfactoriamente.\n    3. Ex: __9: Botines__: 3 + 35 + 972 = __1013__ Botines predichos, de las cuales  972 lo ha hecho satisfactoriamente.\n    4. Etc\u00e9tera\n\"\"\"\n\"\"\"\n<a id=\"7\"><\/a>\n# 7. CONCLUSIONES\n\nPara resolver este complejo problema, hemos aplicado t\u00e9cnicas del Deep Learning para la predicci\u00f3n de art\u00edculos de ropa con im\u00e1genes. Hemos observado que lesprediccions hechas han sido bastante buenas, con un total de __9272__ predicciones correctas respecto __728__ err\u00f3neas. \n\nConcluimos que no ha existido overfitting ya que hemos aplicado t\u00e9cnicas de reducci\u00f3n de la dimensionalidad (MaxPooling2D), capas de regularizaci\u00f3n (Dropouts), 50 epocas, un batch size de 70 (no se ha estudiado). \n\n\nFinalmente, con el modelo entrenado, hemos comprobado que predice bastante bien dentro lo que cabe para la resoluci\u00f3n de las im\u00e1genes. Para confirmar que nuestro modelo puede generalizar, hemos introducido datos nuevos al modelo y este los ha predicho bien. \n\nConfirmamos que el modelo es bueno obteniendo una precisi\u00f3n de ~ 0.927 para los datos test.\n\"\"\"\n\"\"\"\n<a id=\"8\"><\/a>\n# 8. REFERANCIAS\n\"\"\"\n\"\"\"\n[1] Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Editio, Aur\u00e9lien G\u00e9roN. [https:\/\/www.oreilly.com](https:\/\/www.oreilly.com\/library\/view\/hands-on-machine-learning\/9781492032632\/)\n\n[2] How to use Learning Curves to Diagnose Machine Learning Model Performance, Jason Brownlee. [https:\/\/machinelearningmastery.com](https:\/\/machinelearningmastery.com\/learning-curves-for-diagnosing-machine-learning-model-performance\/)\n\n[3] Activation Functions : Sigmoid, ReLU, Leaky ReLU and Softmax basics for Neural Networks and Deep Learning \n[https:\/\/medium.com](https:\/\/medium.com\/@himanshuxd\/activation-functions-sigmoid-relu-leaky-relu-and-softmax-basics-for-neural-networks-and-deep-8d9c70eed91e)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'cbfb163aff68a2'}"}
{"id":"4693","text":"\"\"\"\n# Introduction: Business Problem <a name=\"introduction\"><\/a>\n\"\"\"\n\"\"\"\n## Business Use-case <a name=\"usecase\"><\/a>\n\"\"\"\n\"\"\"\nUP! Sports is a (hypothetical) retail company selling sporting goods, equipment, sports apparel, and much more, for various sporting activities, all under one roof.\n\nBusiness is booming and the company has decided to expand its operations. For\nthe same, the company is looking to setup stores in Canada, starting with the\ncity of Toronto, Ontario. However, the company wants to make this decision using a strategic and methodical approach.\n\n\"\"\"\n\"\"\"\nAcknowledging the power of data and analytics, UP! Sports has decided to use a data science based approach to support their decision-making process for business expansion.\n\"\"\"\n\"\"\"\n## Task Description <a name=\"task\"><\/a>\n\"\"\"\n\"\"\"\nThe task is to identify and group neighborhoods in the city of Toronto, Ontario that the company must target and setup their operations and stores in. Since the company specializes in sports-related consumer goods, the ideal neighborhood(s) or groups of neighborhoods for the company would be neighborhoods with many sport-related facilities, such as gyms, yoga classes, soccer fields, and so on.\n\nThus, the task is to identify such neighborhoods and present an analysis, outlining which neighborhood(s) should UP! Sports setup their retail stores in, as well as the rationale behind the same.\n\"\"\"\n\"\"\"\n# Data <a name=\"data\"><\/a>\n\"\"\"\n\"\"\"\n## Data Description <a name=\"datadesc\"><\/a>\n\"\"\"\n\"\"\"\nThe data that will be used for this business use-case is location data for neighborhoods in Toronto, Ontario, Canada. This data will be collected through Wikipedia, along with the Foursquare API.\n\nThe Wikipedia page \"List of postal codes of Canada: M\" gives details and list of all postal codes in Toronto, Ontario.\n\n[List of postal Codes of Canada: M](https:\/\/en.wikipedia.org\/wiki\/List_of_postal_codes_of_Canada:_M)\n\"\"\"\n\"\"\"\nTherefore, data for all neighborhoods in Toronto, including their names, respective boroughs and postal codes will be collected from Wikipedia by web scraping.\n\nFurther, data about all different venues in each neighborhood will be collected using the Foursquare Places API, using latitude and longitude values, which will be collected using geospatial data.\n\n\"\"\"\n\"\"\"\nThe final data will include the following:\n1. Neighborhood name\n2. Borough name\n3. Postal Code\n4. Latitude and longitude values\n5. Venues in each neighborhood\n\nThis data will be analyzed to provide a solution to the discussed business problem.\n\"\"\"\n\"\"\"\n## Data Collection <a name=\"collection\"><\/a>\n\"\"\"\n# For getting Wikipedia page from URL through get request\nimport requests\n\n# For scraping information from the HTML source\n!pip install bs4\nfrom bs4 import BeautifulSoup\n\n# To create the DataFrame for neighborhood data\nimport pandas as pd\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\n# For handling arrays and vectors\nimport numpy as np\n\n# Supress warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\nIn the following code cell,  data is scraped from the Wikipedia page titled 'List of postal codes of Canada: M'. The scraped web page is transformed into a Pandas DataFrame.\n\"\"\"\n# Get the HTML source\nsource = requests.get(\"https:\/\/en.wikipedia.org\/wiki\/List_of_postal_codes_of_Canada:_M\")\nsoup = BeautifulSoup(source.text, 'lxml')\n\n# Initialise empty list to store table contents\ntable_contents = []\n\n# Scrape all information in the HTML 'table' tag\ntable = soup.find('table')\n# Scrape information in table rows i.e., HTML 'td' tag\nfor row in table.findAll('td'):\n    # Store record of DataFrame\n    cell = {}\n    # Drop record if borough is 'Not assigned'\n    if row.span.text=='Not assigned':\n        pass\n    else:\n        # Add PostalCode, Borough and Neighborhood to record\n        cell['Postal Code'] = row.p.text[:3]\n        cell['Borough'] = (row.span.text).split('(')[0]\n        cell['Neighborhood'] = (((((row.span.text).split('(')[1]).strip(')')).replace(' \/',',')).replace(')',' ')).strip(' ')\n        table_contents.append(cell)\n\n# Create Pandas DataFrame\ntoronto_DF = pd.DataFrame(table_contents)\n\n# Replace Borough values with appropriate name\ntoronto_DF['Borough'] = toronto_DF['Borough'].replace({'Downtown TorontoStn A PO Boxes25 The Esplanade':'Downtown Toronto', \n                                                     'East TorontoBusiness reply mail Processing Centre969 Eastern':'East Toronto Business', \n                                                     'EtobicokeNorthwest':'Etobicoke Northwest',\n                                                     'East YorkEast Toronto':'East York\/East Toronto', \n                                                     'MississaugaCanada Post Gateway Processing Centre':'Mississauga'})\n\n# Number of neighborhods in Toronto\nprint('There are {} neighborhoods in Toronto, Ontario.\\n'.format(toronto_DF.shape[0]))\n\n# Diaplay first 10 records\ntoronto_DF.head(10)\n\"\"\"\nFinally, here I have added the columns for latitude and longitude values by joining the DataFrame created above with the geospatial dataset.\n\"\"\"\n# Get geospatial data for latitue and longitude values\ngeospatial_data = pd.read_csv('..\/input\/geospatial-coordinates\/Geospatial_Coordinates.csv')\n\n# Join DataFrame with geospatial DataFrame to get columns for latitude and longitue of each neighborhoopd\ntoronto_DF = toronto_DF.join(geospatial_data.set_index('Postal Code'), on='Postal Code')\n\n# Display first 10 records\ntoronto_DF.head(10)\n\"\"\"\nIn the following code cell, I have used geopy to get the coordinates for Toronto using reverse geocoding.\n\"\"\"\n# # To get latitude and longitude values for given address\nfrom geopy.geocoders import Nominatim\n\n# Create a Nominatim object for geolocation\ngeolocator = Nominatim(user_agent=\"ny_explorer\")\n\n# Get latitue and longitude values for Toronto\nlocation = geolocator.geocode('Toronto')\ntor_lat = location.latitude\ntor_lon = location.longitude\n\n# Display latitude and longitude values for Toronto\nprint('The geograpical coordinates of Toronto are {}, {}.'.format(tor_lat, tor_lon))\n\"\"\"\nNext, I have created a map for Toronto using folium. I have highlighted the different neighborhoods scraped in the previous few code cells.\n\"\"\"\n# To plot interactive maps\nimport folium\n\n# Matplotlib and associated packages\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\n\n# Create map of Toronto using latitude and longitude values\ntoronto_map = folium.Map(location=[tor_lat, tor_lon], zoom_start=11)\n\n# List of all boroughs\nboroughs = list(toronto_DF['Borough'].unique())\n\n# Set colour scheme for boroughs\ncolors_array = cm.rainbow(np.linspace(0, 1, len(boroughs)))\nrainbow = [colors.rgb2hex(i) for i in colors_array]\n\n# Add markers to map\nfor lat, lon, borough, neighborhood in zip(toronto_DF['Latitude'], toronto_DF['Longitude'], toronto_DF['Borough'], toronto_DF['Neighborhood']):\n    label = 'Neighborhood: {}\\nBorough: {}'.format(neighborhood, borough)\n    label = folium.Popup(label, parse_html=True)\n    folium.CircleMarker([lat, lon], \n                        radius=5, \n                        popup=label, \n                        color=rainbow[boroughs.index(borough)], \n                        fill=True, \n                        fill_color='#3186cc', \n                        fill_opacity=0.7, \n                        parse_html=False).add_to(toronto_map)  \n\n# Display map for Toronto   \ntoronto_map\n\"\"\"\nNext, the Foursquare API is used to get data about venues near each neighborhood in Toronto. For this, the Foursquare API needs to be configured with the client ID and client secret.\n\"\"\"\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\n\n# Your Foursqaure API Client ID\nCLIENT_ID = user_secrets.get_secret(\"foursquare-client-id\")\n\n# Your Foursquare API CLient secret\nCLIENT_SECRET = user_secrets.get_secret(\"foursquare-client-secret\")\n\n# Foursquare API version\nVERSION = '20180604'\n\nLIMIT = 100\nradius = 500\n\n# URL for getting data from Foursquare API\nurl = 'https:\/\/api.foursquare.com\/v2\/venues\/search?client_id={}&client_secret={}&ll={},{}&v={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, tor_lat, tor_lon, VERSION, radius, LIMIT)\n\"\"\"\nIn the next 2 code cells, I have gathered data about venues in and around Toronto, along with all related information for the venues, through the Foursquare API.\n\nFinally, I have created a DataFrame that stores details about various different venues in the different neighborhoods of Toronto, along with their coordinates and venue types (catageories).\n\"\"\"\n# Function to get nearby venues\ndef getNearbyVenues(boroughs, neighborhoods, latitudes, longitudes, radius=500):\n    venues_list=[]\n    for borough, neighborhood, lat, lng in zip(boroughs, neighborhoods, latitudes, longitudes):\n        # URL to get data about venues from Foursquare API\n        url = 'https:\/\/api.foursquare.com\/v2\/venues\/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT)   \n        \n        # Get data through get request\n        results = requests.get(url).json()[\"response\"]['groups'][0]['items']\n        \n        # Add results to list of all venues\n        venues_list.append([(borough, neighborhood, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results])\n\n    # Create DataFrame for nearby venues\n    nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])\n    nearby_venues.columns = ['Borough', 'Neighborhood', 'Neighborhood Latitude', 'Neighborhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category']\n    \n    # Return DataFrame of nearby venues\n    return(nearby_venues)\n# Get nearby venues for Toronto\ntoronto_venues = getNearbyVenues(boroughs=toronto_DF['Borough'], neighborhoods=toronto_DF['Neighborhood'], latitudes=toronto_DF['Latitude'], longitudes=toronto_DF['Longitude'])\n\n# Print number of nearby venues returned\nprint('Foursquare retured {} nearby venues for Toronto.'.format(toronto_venues.shape[0]))\n\n# Print number of unique venue categories\nprint('There are {} uniques categories of venues.\\n'.format(len(toronto_venues['Venue Category'].unique())))\n\n# Display first 10 records for nearby venues for Toronto\ntoronto_venues.head(10)\n\"\"\"\n# Methodology <a name=\"methodology\"><\/a>\n\"\"\"\n\"\"\"\nTo solve the problem at hand, neighborhoods and boroughs that have a **high density of sports related venues**, such as gyms, stadiums, etc., have to be identified.\n\nTo do this, we have already collected the required data, through web scraping and through the Foursquare API.\n\nThe first step of the analysis involves filtering the collected data to **include only those venues that are related to sporting activities.**\n\nAfter filtering out such venues, some basic **exploratory analysis** is done to get more insight on the available data. This involves plotting some charts and maps to visualize the data. Through these visualizations, we will be able to **identify the boroughs that have a high density of sports related venues.**\n\nFinally, **the selected venues are clustered** to identify cluster centers, which will become the **target locations** for the company. For this, **k-means clustering algorithm** is used.\n\"\"\"\n\"\"\"\n# Analysis <a name=\"analysis\"><\/a>\n\"\"\"\n\"\"\"\n## Exploratory Data Analysis <a name=\"eda\"><\/a>\n\"\"\"\n\"\"\"\nSince we are only interested in venues related to sporting activities, such as gyms, yoga classes, etc., I have filtered the DataFrame for venues in and around Toronto to include only such venues.\n\"\"\"\n# List of required venue types\nvenue_categories = ['Athletics & Sports', 'Baseball Field', 'Baseball Stadium', 'Basketball Court', 'Basketball Stadium',\n                    'Beach', 'Climbing Gym', 'College Gym', 'College Rec Center', 'College Stadium',\n                    'Curling Ice', 'Field', 'Golf Course', 'Gym', 'Gym \/ Fitness Center',\n                    'Gym Pool', 'Hockey Arena', 'Martial Arts School', 'Park', 'Playground',\n                    'Pool', 'Skate Park', 'Skating Rink', 'Soccer Field', 'Sporting Goods Shop',\n                    'Sports Bar', 'Stadium', 'Supplement Shop', 'Swim School', 'Tennis Court', 'Yoga Studio']\n\n# Filter toronto_venues DataFrame\ntoronto_sports_venues = toronto_venues[toronto_venues['Venue Category'].isin(venue_categories)].reset_index()\ntoronto_sports_venues.drop(['index'], axis=1, inplace=True)\n\n# Print number of sports venues\nprint('There are {} sports related venues in and around Toronto.\\n'.format(toronto_sports_venues.shape[0]))\n\n# Display first 10 records\ntoronto_sports_venues.head(10)\n\"\"\"\nHere, I have plotted a horizontal bar chart showing the number of sports related venues in each borough.\n\"\"\"\nboroughs = toronto_sports_venues.groupby('Borough').count().Venue.sort_values(ascending=False).reset_index()\nx = list(boroughs['Borough'])\ny = list(boroughs['Venue'])\nplt.figure(figsize=(16, 12))\nplt.barh(x, y)\nplt.title('Number of sports venues per borough', fontdict=dict(fontsize=15), fontweight=\"bold\")\nplt.xlabel('Number of sports venues', fontdict=dict(fontsize=15), fontweight=\"bold\")\nplt.ylabel('Borough', fontdict=dict(fontsize=15), fontweight=\"bold\")\nplt.xticks(fontsize='large', weight='bold')\nplt.yticks(fontsize='large', weight='bold')\nfor i, v in enumerate(y):\n    plt.text(v+0.5, i-0.15, str(v), fontdict=dict(fontsize=15), fontweight='bold')\nplt.show()\n\"\"\"\nBy far, Downtown Toronto has the greatest number of sports related venues (76).\n\nNorth York ranks 2nd in terms of the number of sports venues in the borough. However, these venues are scattered around North York i.e., the density of sports related venues in North York is quite low (see map in next code cell).\n\nTargeting neighborhoods in Downtown Toronto can be a great starting point for the company to set up their first store in Toronto, Ontario.\n\"\"\"\n\"\"\"\nFurther, let's take a look at a map of Toronto showing the different sports venues, based on the data collected so far.\n\"\"\"\n# Create map of Toronto using latitude and longitude values\ntoronto_sports_map = folium.Map(location=[tor_lat, tor_lon], zoom_start=11)\n\n# List of all boroughs\nboroughs = list(toronto_DF['Borough'].unique())\n\n# Set colour scheme for boroughs\ncolors_array = cm.rainbow(np.linspace(0, 1, len(boroughs)))\nrainbow = [colors.rgb2hex(i) for i in colors_array]\n\n# Add markers to map\nfor lat, lon, venue, category, borough, neighborhood in zip(toronto_sports_venues['Venue Latitude'], toronto_sports_venues['Venue Longitude'], toronto_sports_venues['Venue'], toronto_sports_venues['Venue Category'], toronto_sports_venues['Borough'], toronto_sports_venues['Neighborhood']):\n    label = 'Venue Name: {}\\nVenue Category: {}\\nNeighborhood: {}\\nBorough: {}'.format(venue, category, neighborhood, borough)\n    label = folium.Popup(label, parse_html=True)\n    folium.CircleMarker([lat, lon], \n                        radius=5, \n                        popup=label, \n                        color=rainbow[boroughs.index(borough)], \n                        fill=True, \n                        fill_color='#3186cc', \n                        fill_opacity=0.7, \n                        parse_html=False).add_to(toronto_sports_map)  \n\n# Display the map for sports venues in and around Toronto   \ntoronto_sports_map\n\"\"\"\nAs expected, a lot of the sports venues are located close to each other in the borough of Downtown Toronto (as shown on the map in dark blue colour).\n\nA considerably high density of sports related venues is also observed in the surrounding boroughs of Central Toronto, East Toronto, East Toronto Business, West Toronto and East York.\n\"\"\"\n\"\"\"\n## Clustering Venues <a name=\"clustering\"><\/a>\n\"\"\"\n\"\"\"\nFor further analysis, let's narrow down our focus to these selected boroughs having a high density of sports related venues and find some suitable neighborhoods in these boroughs.\n\nTo select suitable neighborhoods in these boroughs, I have performed clustering based on the latitude and longitude values of each neighborhood. The cluster centroids will then correspond to the required suitable neighborhoods.\n\"\"\"\n# List of selected boroughs\nselected_boroughs = ['Downtown Toronto', 'Central Toronto', 'East Toronto', 'East Toronto Business', 'West Toronto', 'East York']\n\n# Filter DataFrame for sports venues for selected boroughs only\ntoronto_sports_venues_filtered = toronto_sports_venues[toronto_sports_venues['Borough'].isin(selected_boroughs)]\n\n# Keep only required columns\ncols = ['Borough', 'Neighborhood', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category']\ntoronto_sports_venues_filtered = toronto_sports_venues_filtered[cols].reset_index()\ntoronto_sports_venues_filtered.drop(['index'], axis=1, inplace=True)\ntoronto_sports_venues_filtered.head(10)\n\"\"\"\nNext, I have clustered the venues into 4 clusters based on the venue coordinates using k-means clustering algorithm.\n\"\"\"\n# For k-means clustering\nfrom sklearn.cluster import KMeans\n\n# Set number of clusters\nkclusters = 4\n\n# DataFrame with data for clustering\ntoronto_sports_clustering = toronto_sports_venues_filtered[['Venue Latitude', 'Venue Longitude']]\n\n# Run k-means clustering\nkmeans = KMeans(n_clusters=kclusters, random_state=0).fit(toronto_sports_clustering)\n\n# Add cluster labels\ntoronto_sports_venues_clustered = toronto_sports_venues_filtered\ntoronto_sports_venues_clustered.insert(loc=6, column='Cluster Label', value=kmeans.labels_)\n\"\"\"\nLet's now plot the clustered venues using folium.\n\"\"\"\n# Plotting map\nmap_clusters = folium.Map(location=[tor_lat, tor_lon], zoom_start=12)\n\n# Set color scheme for the clusters\nx = np.arange(kclusters)\nys = [i + x + (i*x)**2 for i in range(kclusters)]\ncolors_array = cm.tab10(np.linspace(0, 1, len(ys)))\ntab10 = [colors.rgb2hex(i) for i in colors_array]\n\n# Add markers to the map\nmarkers_colors = []\nfor lat, lon, venue, category, cluster in zip(toronto_sports_venues_clustered['Venue Latitude'], toronto_sports_venues_clustered['Venue Longitude'], toronto_sports_venues_clustered['Venue'], toronto_sports_venues_clustered['Venue Category'], toronto_sports_venues_clustered['Cluster Label']):\n    label = folium.Popup('Venue Name: {}\\nVenue Category: {}\\n(Cluster {})'.format(venue, category, str(cluster)), parse_html=True)\n    folium.CircleMarker([lat, lon], \n                        radius=5, \n                        popup=label, \n                        color=tab10[int(cluster)], \n                        fill=True, \n                        fill_color=tab10[int(cluster)], \n                        fill_opacity=1.0).add_to(map_clusters)\n\n# Display map with clusters\nmap_clusters\n\"\"\"\nThe following code cell creates a DataFrame to store the details about the cluster centers identified using k-means clustering performed above. It includes the latitude and longitude of the target location (cluster center), as well as the address.\n\"\"\"\n# Coordinates of cluster centers\nlatitudes, longitudes, addresses = [], [], []\nfor center in kmeans.cluster_centers_:\n    latitudes.append(center[0])\n    longitudes.append(center[1])\n    location = geolocator.reverse(\"{}, {}\".format(center[0], center[1]))\n    addresses.append(location.address)\n\n# Create DataFrame\nselected_locations = pd.DataFrame({'Latitude':latitudes, 'Longitude':longitudes, 'Address':addresses})\nselected_locations\n\"\"\"\nLet's plot these target location on a map to visualize the options.\n\"\"\"\n# Plotting map\nselected_locations_map = folium.Map(location=[tor_lat, tor_lon], zoom_start=12)\n\n# Set color scheme for the clusters\nx = np.arange(kclusters)\nys = [i + x + (i*x)**2 for i in range(kclusters)]\ncolors_array = cm.tab10(np.linspace(0, 1, len(ys)))\ntab10 = [colors.rgb2hex(i) for i in colors_array]\n\n# Add markers to the map\nmarkers_colors = []\nfor lat, lon, addr in zip(selected_locations['Latitude'], selected_locations['Longitude'], selected_locations['Address']):\n    label = folium.Popup('Address: ' + addr, parse_html=True)\n    folium.CircleMarker([lat, lon], \n                        radius=5, \n                        popup=label, \n                        color=tab10[1], \n                        fill=True, \n                        fill_color=tab10[1], \n                        fill_opacity=1.0).add_to(selected_locations_map)\n\n# Display map with clusters\nselected_locations_map\n\"\"\"\n# Results and Discussion <a name=\"results\"><\/a>\n\"\"\"\n\"\"\"\nOur analysis shows that there are **168 sports related venues** in and around Toronto, Ontario, located in **103 neighborhoods.**\n\nA high density of such venues is observed in **Downtown Toronto** as well as the surrounding boroughs of **East Toronto, East Toronto Business, Central Toronto, West Toronto, and East York.**\n\nUpon grouping these venues into 4 different clusters, we have identified 4 locations that the company can target in order to setup their first retail store in Toronto, Ontario, Canada.\n\nThese locations are:\n\n1. 382, Shaw Street, University\u2014Rosedale, Old Toronto, Toronto, Golden Horseshoe, Ontario, M6G 1C5, Canada\n\n2. 12, Glebemount Avenue, Danforth Village, Beaches\u2014East York, Old Toronto, Toronto, Golden Horseshoe, Ontario, M4C 1K9, Canada\n\n3. 357, Manor Road East, Davisville, Don Valley West, Old Toronto, Toronto, Golden Horseshoe, Ontario, M4S 1S3, Canada\n\n4. Tim Hortons, Grand Opera Lane, King East, Toronto Centre, Old Toronto, Toronto, Golden Horseshoe, Ontario, M5H, Canada\n\nTherefore, the results of our analysis provide valuable information to the company which can be used to solve the problem at hand.\n\"\"\"\n\"\"\"\n# Conclusion <a name=\"conclusion\"><\/a>\n\"\"\"\n\"\"\"\nHence, we have successfully identified 4 prime locations that can be targetted by UP! Sports as locations to setup their first retail store in Toronto, Ontario, Canada.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '08b93acb9b01e5'}"}
{"id":"133664","text":"# 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\n\"\"\"\n![](https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcTs2mQUEvVkSBa0j1z0LHkM6taXr-9BDXiMLA&usqp=CAU)home.hellodriven.com\n\"\"\"\n!pip install -U spacy\n!python -m spacy download en_core_web_lg\n!python -m spacy download en_core_web_sm\n!pip install wordcloud\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n#Code by Paul Mooney\n\nfriston_file = '..\/input\/open-access-karl-fristons-papers-txt\/23133414.txt'\nwith open(friston_file) as f: # The with keyword automatically closes the file when you are done\n    print (f.read(3000))\nimport spacy\nnlp = spacy.load(\"en_core_web_sm\")\n\ndoc = nlp(\"So, why are you reading this paper?\")\nfor token in doc:\n    print(token.text, token.pos_, token.dep_)\n# Create a nlp object\ndoc = nlp(\"The answer is fairly simple: you are compelled to selectively sample sensory input that conforms to your predictions\")\nnlp.pipe_names\nnlp.disable_pipes('tagger', 'parser')\nnlp.pipe_names\n\"\"\"\n#Tokenization\n\"\"\"\nimport spacy\n\nnlp = spacy.load('en_core_web_sm')\ndoc = nlp(\"in which behavior is cast as active Bayesian inference that is constrained by prior beliefs\")\nfor token in doc:\n    print(token.text)\n\"\"\"\n#Part-Of-Speech (POS) Tagging\n\"\"\"\nnlp = spacy.load('en_core_web_sm')\n\n# Create an nlp object\ndoc = nlp(\"If behavior is optimal, then it maximizes value\")\n \n# Iterate over the tokens\nfor token in doc:\n    # Print the token and its part-of-speech tag\n    print(token, token.tag_, token.pos_, spacy.explain(token.tag_))\nfrom spacy import displacy\n\ndoc = nlp(\"The same objective: to maximize the Bayesian model evidence averaged over time.\")\ndisplacy.render(doc, style=\"dep\" , jupyter=True)\nnlp = spacy.load('en_core_web_sm')\n\n# Create an nlp object\ndoc = nlp(\"The principle of least action, the principle of maximum entropy, the principle of minimum redundancy and the principle of maximum information transfer.\")\n \n# Iterate over the tokens\nfor token in doc:\n    # Print the token and its part-of-speech tag\n    print(token.text, \"-->\", token.dep_)\nspacy.explain(\"nsubj\"), spacy.explain(\"ROOT\"), spacy.explain(\"aux\"),spacy.explain('nmod'), spacy.explain(\"advcl\"), spacy.explain(\"dobj\")\n\"\"\"\n#Lemmatization\n\"\"\"\nnlp = spacy.load('en_core_web_sm')\n\n# Create an nlp object\ndoc = nlp(\"Cost functions that are used to guide action in optimal control can be absorbed into prior beliefs in active inference.\")\n \n# Iterate over the tokens\nfor token in doc:\n    # Print the token and its part-of-speech tag\n    print(token.text, \"-->\", token.lemma_)\n\"\"\"\n#Sentence Boundary Detection (SBD)\n\"\"\"\nnlp = spacy.load('en_core_web_sm')\n\n# Create an nlp object\ndoc = nlp(\"Solutions based upon cost or reward functions that are an integral part of optimal control theory and reinforcement learning\")\n \nsentences = list(doc.sents)\nlen(sentences)\nfor sentence in sentences:\n     print (sentence)\n\"\"\"\n#Named Entity Recognition (NER)\n\"\"\"\nnlp = spacy.load(\"en_core_web_sm\")\ndoc = nlp(\"Solution to this variational problem is given by a stochastic controller called the Bayesian control rule, which implements adaptive behavior as a mixture of experts.\")\n#See the entity present\nprint(doc.ents)\nfor ent in doc.ents:\n    print(ent.text, ent.start_char, ent.end_char, ent.label_)\n\"\"\"\n#Entity Detection\n\"\"\"\nfrom spacy import displacy\nnlp = spacy.load(\"en_core_web_sm\")\ndoc= nlp(u\"\"\"This work\nillustrates the close connections between minimizing (relative)\nentropy and the ensuing active Bayesian inference that we will appeal\nto the later.In summary, current approaches to partially observed MDPs\nand stochastic optimal control minimize cumulative cost using the same\nprocedures employed by maximum likelihood and approximate Bayesian\ninference schemes. Indeed, the formal equivalence between optimal\ncontrol and estimation was acknowledged by Kalman at the inception of\nBayesian filtering schemes. \"\"\")\n\nentities=[(i, i.label_, i.label) for i in doc.ents]\nentities\ndisplacy.render(doc, style = \"ent\",jupyter = True)\nnlp = spacy.load(\"en_core_web_lg\")\ntokens = nlp(\"Relationship between entropy, surprise and Bayesian model evidence in Section \u201cBayes-optimal control without cost functions,\u201d The motivation for free energy minimization in more detail.\")\n\nfor token in tokens:\n    print(token.text, token.has_vector, token.vector_norm, token.is_oov)\nnlp = spacy.load(\"en_core_web_lg\")  # make sure to use larger model!\ntokens = nlp(\"Free energy principle states that the sufficient statistics of the conditional probability and action minimize free energy The first equality in Equation expresses free energy as a Gibbs energy (expected under the conditional distribution) minus the entropy of the conditional distribution.\")\n\nfor token1 in tokens:\n    for token2 in tokens:\n        print(token1.text, token2.text, token1.similarity(token2))\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\nnlp = spacy.load(\"en_core_web_lg\")  # make sure to use larger model!\ntokens = nlp(\"Free utility is fundamentally different from variational free energy,it is a functional of choice probabilities over hidden states. Variational free energy is a function of observed states. Crucially, free utility depends on a cost function, while free energy does not. The free energy principle is based on the invariant or ergodic solution 2012. In other words, value is (log) evidence or negative surprise.\")\n\nnewText =''\nfor word in tokens:\n if word.pos_ in ['ADJ', 'NOUN']:\n  newText = \" \".join((newText, word.text.lower()))\n\nwordcloud = WordCloud(stopwords=STOPWORDS, colormap='Reds', background_color=\"blue\").generate(newText)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n![](https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcTvuNlT2OyjZ9vcUoNgz_20HfnL6tszy18lXw&usqp=CAU)youtube.com\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f5cdc67983cb3a'}"}
{"id":"49200","text":"\"\"\"\n#                                      ICMR Healthcare  Cancer Type Detections  and Gene Type Analysis \n\n* Data Analyst : Sheri Prashanth Reddy \n\n## DESCRIPTION\n\n### Problem Statement: \n\nICMR wants to analyze different types of cancers, such as breast cancer, renal cancer, colon cancer, lung cancer, and prostate cancer becoming a cause of worry in recent years. They would like to identify the probable cause of these cancers in terms of genes responsible for each cancer type. This would lead us to early identification of each type of cancer reducing the fatality rate.\n\n### Dataset Details: \n\nThe input dataset contains 802 samples for the corresponding 802 people who have been detected with different types of cancer. Each sample contains expression values of more than 20K genes. Samples have one of the types of tumors: BRCA, KIRC, COAD, LUAD, and PRAD.\n\n\n### Project Tasks are divided in 4 weeks \n\"\"\"\n\"\"\"\n## Week 1:-  Exploratory Data Analysis\n\n\n#### Project Task: Week 1:\n\nExploratory Data Analysis:\n\nMerge both the datasets.\n\nPlot the merged dataset as a hierarchically-clustered heatmap.\n\nPerform Null-hypothesis testing.\n \n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\ncolors = ['royalblue','red','deeppink', 'maroon', 'mediumorchid', 'tan', 'forestgreen', 'olive', 'goldenrod', 'lightcyan', 'navy']\nvectorizer = np.vectorize(lambda x: colors[x % len(colors)])\n\nimport warnings\nwarnings.filterwarnings(action='ignore',category=DeprecationWarning)\nwarnings.filterwarnings(action='ignore',category=FutureWarning)\n\"\"\"\n### Week1: Load Data in dataframe for labels and the data \n\"\"\"\nlabel = pd.read_csv('\/kaggle\/input\/icmr-health-care\/labels.csv',delimiter=',',engine='python')\ndata = pd.read_csv('\/kaggle\/input\/icmr-health-care\/data.csv',delimiter=',',engine='python')\ndata.describe()\n\"\"\"\n### Week1:- Merge data set \n\"\"\"\nmaster_data = pd.merge(label,data)\nmaster_data.head()\nmaster_data.isnull().sum()\nmaster_data.describe()\n\"\"\"\n### Week1:- Plot the merged dataset as a hierarchically-clustered heatmap.\n\"\"\"\nheatmap_data = pd.pivot_table(master_data, index=['Class'])\n                              \nheatmap_data.head()\nsns.clustermap(heatmap_data)\nplt.savefig('heatmap_with_Seaborn_clustermap_python.jpg',\n            dpi=150, figsize=(8,12))\nsns.clustermap(heatmap_data, figsize=(18,12))\nplt.savefig('clustered_heatmap_with_dendrograms_Seaborn_clustermap_python.jpg',dpi=150)\n\n\"\"\"\n### Week1:- Perform Null Hypothesis testing \n\"\"\"\n\"\"\"\n### Checking histogram to check if the data is normally distributed \n\"\"\"\nplt.figure(figsize=(14,6))\nplt.hist(master_data['Class'])\nplt.show()\nnon_cat_data = master_data.drop(['Unnamed: 0'], axis=1)\nnon_cat_data\n\"\"\"\n### Week1:- F Test\n\nF-tests are named after its test statistic, F, which was named in honor of Sir Ronald Fisher. The F-statistic is simply a ratio of two variances. Variances are a measure of dispersion, or how far the data are scattered from the mean. Larger values represent greater dispersion.\n\nVariance is the square of the standard deviation. For us humans, standard deviations are easier to understand than variances because they\u2019re in the same units as the data rather than squared units. However, many analyses actually use variances in the calculations.\n\nF-statistics are based on the ratio of mean squares. The term \u201cmean squares\u201d may sound confusing but it is simply an estimate of population variance that accounts for the degrees of freedom (DF) used to calculate that estimate.\n\"\"\"\ndf_f_test=master_data\ndef f_test(df_f_test,gene):  \n    df_anova = df_f_test[[gene,'Class']]\n    grps = pd.unique(df_anova.Class.values)\n    grps\n    d_data = {grp:df_anova[gene][df_anova.Class == grp] for grp in grps}\n    F, p = stats.f_oneway(d_data['LUAD'], d_data['PRAD'], d_data['BRCA'], d_data['KIRC'], d_data['COAD'])\n    print(\"p_values:-\",p)\n    if p<0.05:\n        print(\"reject null hypothesis\")\n    else:\n        print(\"accept null hypothesis\")\n        \n    return \nf_test(df_f_test,\"gene_3\")\nf_test(df_f_test,\"gene_7\")\nf_test(df_f_test,\"gene_20524\")\nf_test(df_f_test,\"gene_5\")\nf_test(df_f_test,\"gene_5\")\ndf_cat_data = master_data\ndf_cat_data['Class'] = df_cat_data['Class'].map({'PRAD': 1, 'LUAD': 2, 'BRCA': 3, 'KIRC': 4, 'COAD': 5}) \ndf_cat_data = df_cat_data.drop(['Unnamed: 0'],axis=1)\n\"\"\"\n### Shapiro test \n\n#### The null hypothesis for the Shapiro-Wilk test is that a variable is normally distributed in some population. A different way to say the same is that a variable's values are a simple random sample from a normal distribution. As a rule of thumb, we reject the null hypothesis if p < 0.05\n\"\"\"\nfrom scipy.stats import shapiro\nstat, p = shapiro(df_cat_data)\nprint('stat=%.2f, p=%.30f' %(stat, p))\n\nif p > 0.05:\n    print('Normal Distribution')\nelse:\n    print('Not Normal')\n\"\"\"\n### k2test - In statistics, D'Agostino's K2 test, named for Ralph D'Agostino, is a goodness-of-fit measure of departure from normality, that is the test aims to establish whether or not the given sample comes from a normally distributed population\n\"\"\"\n#K2 normality test \nfrom scipy.stats import normaltest\nk2_test = df_cat_data['Class']\n\nstat, p = normaltest(k2_test)\nprint('stat=%.2f, p=%.30f' %(stat, p))\n\nif p > 0.05:\n    print('Normal Distribution')\nelse:\n    print('Not Normal')\n\n\"\"\"\n## Week 2:- Dimensionality Reduction\n\n#### Project Task: Week 2: \n\nDimensionality Reduction:\n\nEach sample has expression values for around 20K genes. However, it may not be necessary to include all 20K genes expression values to analyze each cancer type. Therefore, we will identify a smaller set of attributes which will then be used to fit multiclass classification models. So, the first task targets the dimensionality reduction using various techniques such as,\nPCA, LDA, and t-SNE.\nInput: Complete dataset including all genes (20531)\nOutput: Selected Genes from each dimensionality reduction method\n \n\"\"\"\n\"\"\"\n### Dimensionality Reduction using PCA \n\"\"\"\n# Define data \ndf_pca = master_data.drop(['Unnamed: 0'], axis=1)\ndf_pca = df_pca.drop(['Class'], axis=1)\ndf_pca.head()\ndf_pca.values.shape\nx_pca = df_pca.values\n\"\"\"\n### Week2:- Scaling the data using standard scaler method\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_Scaled = scaler.fit_transform(x_pca)\nX_Scaled\n\"\"\"\n### Week2:- Perform PCA with n_components=2\n\n#### Principal Component Analysis, or PCA, is a dimensionality-reduction method that is often used to reduce the dimensionality of large data sets, by transforming a large set of variables into a smaller one that still contains most of the information in the large set.\n\n#### Reducing the number of variables of a data set naturally comes at the expense of accuracy, but the trick in dimensionality reduction is to trade a little accuracy for simplicity. Because smaller data sets are easier to explore and visualize and make analyzing data much easier and faster for machine learning algorithms without extraneous variables to process.\n\n#### So to sum up, the idea of PCA is simple \u2014 reduce the number of variables of a data set, while preserving as much information as possible.\n\n\"\"\"\n# Import PCA from sklearn and define the n_components as 2 \nfrom sklearn.decomposition import PCA\npca_with_2=PCA(n_components=2)\n#Perform fit transform on the scaled data\nX_pca_with_2 = pca_with_2.fit_transform(X_Scaled)\nX_pca_with_2.shape\nX_pca_with_2\n# Put the data back on the 2 columns defined \ndf_pca = pd.DataFrame(X_pca_with_2)\ndf_pca.columns = ['pca1','pca2']\n\n# Add the convereted categorical data for \ndf_pca['cancer_type']=df_cat_data['Class']\ndf_pca\n# Present the data on the 5 clusters using seaborn maps \nsns.scatterplot(x='pca1',y='pca2', hue = 'cancer_type',data=df_pca)\n\"\"\"\n### Week2:- PCA with n_components=.995\n\"\"\"\npca_with_995=PCA(.995)\nX_pca_with_995 = pca_with_995.fit_transform(x_pca)\nX_pca_with_995.shape\nX_pca_with_995\ndf_pca_995 = pd.DataFrame(X_pca_with_995)\ndf_pca_995['cancer_type']=df_cat_data['Class']\ndf_pca_995\nsns.scatterplot(x=0,y=1,hue = 'cancer_type', data=df_pca_995)\n\"\"\"\n### Week2:- Dimensionality reduction using  TSNE\n\nT-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.\n\n\n\"\"\"\ndf_tsne_data = master_data\nnon_numeric = ['Unnamed: 0','Class']\ndf_tsne_data = df_tsne_data.drop(non_numeric, axis=1)\ndf_tsne_data\n#import T-SNE from sklearn\nfrom sklearn.manifold import TSNE\nm = TSNE(learning_rate=50)\ntnse_features = m.fit_transform(df_tsne_data)\ntnse_features[1:4,:]\ndf_tsne_data['x'] = tnse_features[:,0]\ndf_tsne_data['y'] = tnse_features[:,1]\n\nimport seaborn as sns\nsns.scatterplot(x='x',y='y',data=df_tsne_data)\nplt.show()\ndf_tsne_data['cancer_type']=df_cat_data['Class']\nsns.scatterplot(x='x',y='y',hue = 'cancer_type', data=df_tsne_data)\nplt.show()\n\"\"\"\n### Week2:- Dimensionality reduction using LDA \n\n#### Linear Discriminant Analysis, or LDA for short, is a predictive modeling algorithm for multi-class classification. It can also be used as a dimensionality reduction technique, providing a projection of a training dataset that best separates the examples by their assigned class.\n\n#### The ability to use Linear Discriminant Analysis for dimensionality reduction often surprises most practitioners.\n\"\"\"\ndf_lda = master_data.drop(['Unnamed: 0'], axis=1)\ndf_lda = df_lda.drop(['Class'], axis=1)\nx_lda = df_lda\nx_lda\nx_lda.shape\ny_lda = master_data['Class']\ny_lda.values\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nlda = LDA(n_components=2)\nx_r2 = lda.fit(x_lda,y_lda).transform(x_lda)\nlda.explained_variance_ratio_\nx_r3 = pd.DataFrame(data=x_r2)\nx_r3['y']=y_lda\nx_r3\nsns.scatterplot(x=0,y=1,hue = 'y', data=x_r3)\n\"\"\"\n## Project Task: Week 3: Clustering Genes and Samples:\n\n#### Project Task: Week 3: \n\nClustering Genes and Samples:\n\nOur next goal is to identify groups of genes that behave similarly across samples and identify the distribution of samples corresponding to each cancer type. Therefore, this task focuses on applying various clustering techniques, e.g., k-means, hierarchical, and mean-shift clustering, on genes and samples.\n\n \n\nFirst, apply the given clustering technique on all genes to identify:\n\nGenes whose expression values are similar across all samples\n\nGenes whose expression values are similar across samples of each cancer type \n\n \n\nNext, apply the given clustering technique on all samples to identify:\n\nSamples of the same class (cancer type) which also correspond to the same cluster\n\nSamples identified to be belonging to another cluster but also to the same class (cancer type)\n\n \n\n\n### KMEANS Clustering with PCA = 2\n\"\"\"\nfrom sklearn.cluster import KMeans\nclusters = KMeans(5, n_init = 5)\nclusters.fit(X_pca_with_2)\n\nclusters.labels_\npca_with_2_data_frame = pd.DataFrame(data=X_pca_with_2,columns=['pca1','pca2'])\npca_with_2_data_frame.head()\npca_with_2_data_frame['Cls_label'] = clusters.labels_\npca_with_2_data_frame['given_cancer_type'] = label.Class.values\npca_with_2_data_frame\nbrca = pca_with_2_data_frame.groupby('given_cancer_type').get_group('BRCA')\nbrca.Cls_label.value_counts()\nluad = pca_with_2_data_frame.groupby('given_cancer_type').get_group('LUAD')\nluad.Cls_label.value_counts()\ncoad = pca_with_2_data_frame.groupby('given_cancer_type').get_group('COAD')\ncoad.Cls_label.value_counts()\nprad = pca_with_2_data_frame.groupby('given_cancer_type').get_group('PRAD')\nprad.Cls_label.value_counts()\nkirc = pca_with_2_data_frame.groupby('given_cancer_type').get_group('KIRC')\nkirc.Cls_label.value_counts()\nclusters.cluster_centers_\nkmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10, random_state=0)\npred_y = kmeans.fit_predict(X_pca_with_2)\nplt.scatter(X_pca_with_2[:,0], X_pca_with_2[:,1])\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red')\nplt.show()\n\"\"\"\n## KMEANS Clustering with PCA = .995\n\"\"\"\nfrom sklearn.cluster import KMeans\nclusters_995 = KMeans(5, n_init = 5)\nclusters_995.fit(X_pca_with_995)\nclusters_995.labels_\npca_with_995_data_frame = pd.DataFrame(data=X_pca_with_995)\npca_with_995_data_frame.head()\npca_with_995_data_frame['Cls_label'] = clusters.labels_\npca_with_995_data_frame['given_cancer_type'] = label.Class.values\npca_with_995_data_frame.shape\nbrca_995 = pca_with_995_data_frame.groupby('given_cancer_type').get_group('BRCA')\nbrca_995.Cls_label.value_counts()\nluad_995 = pca_with_995_data_frame.groupby('given_cancer_type').get_group('LUAD')\nluad_995.Cls_label.value_counts()\ncoad_995 = pca_with_995_data_frame.groupby('given_cancer_type').get_group('COAD')\ncoad_995.Cls_label.value_counts()\nprad_995 = pca_with_995_data_frame.groupby('given_cancer_type').get_group('PRAD')\nprad_995.Cls_label.value_counts()\nkirc_995 = pca_with_995_data_frame.groupby('given_cancer_type').get_group('KIRC')\nkirc_995.Cls_label.value_counts()\nkmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10, random_state=0)\npred_y = kmeans.fit_predict(X_pca_with_995)\nplt.scatter(X_pca_with_995[:,0], X_pca_with_995[:,1])\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red')\nplt.show()\n\"\"\"\n## Week 4: Build Classification Models\n\n#### Project Task: Week 4: \n\nBuilding Classification Model(s) with Feature Selection:\n\nOur final task is to build a robust classification model(s) for identifying each type of cancer.\n\nSub-tasks:\n\nBuild a classification model(s) using multiclass SVM, Random Forest, and Deep Neural Network to classify the input data into five cancer types\n\nApply the feature selection algorithms, forward selection, and backward elimination to refine selected attributes (selected in Task-2) using the classification model from the previous step\n\nValidate the genes selected from the last step using statistical significance testing (t-test for one vs. all and F-test)\n \n\"\"\"\n\"\"\"\n### Build decision tree clasifier\n\n#### Decision Tree is a Supervised Machine Learning Algorithm that uses a set of rules to make decisions, similarly to how humans make decisions. One way to think of a Machine Learning classification algorithm is that it is built to make decisions. You usually say the model predicts the class of the new, never-seen-before input but, behind the scenes, the algorithm has to decide which class to assign.\n\n\"\"\"\nml_x = x_lda\nml_y = y_lda\nml_x.shape,ml_y.shape\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(ml_x,ml_y,test_size=0.30,random_state=30)\nfrom sklearn import tree\ndt_clf = tree.DecisionTreeClassifier(max_depth=5)\ndt_clf.fit(x_train,y_train)\ndt_clf.score(x_test,y_test)\n\ny_pred=(dt_clf.predict(x_test))\ndt_clf.score(x_test,y_test)\n\"\"\"\n### SVM \n\n#### Support vector machine algorithm is used to find a hyperplane in an N-dimensional space(N \u2014 the number of features) that distinctly classifies the data points.\n\"\"\"\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.svm import SVC\nsv_clf = SVC(probability=True, kernel='linear')\nsv_clf.fit(x_train,y_train)\nsv_clf.score(x_test,y_test)\n\n\ny_pred = sv_clf.predict(x_test)\nprint(accuracy_score(y_test,y_pred))\n\n\"\"\"\n### Random Forest \n\n#### Random forest, like its name implies, consists of a large number of individual decision trees that operate as an ensemble. Each individual tree in the random forest spits out a class prediction and the class with the most votes becomes our model\u2019s prediction. The fundamental concept behind random forest is a simple but powerful one \u2014 the wisdom of crowds. In data science speak, the reason that the random forest model works so well is: A large number of relatively uncorrelated models (trees) operating as a committee will outperform any of the individual constituent models.\n\"\"\"\nfrom sklearn import ensemble\nrf_clf = ensemble.RandomForestClassifier(n_estimators=100)\nrf_clf.fit(x_train,y_train)\nrf_clf.score(x_test,y_test)\n\"\"\"\n### Naive Bayes Classifier \n\n#### A Naive Bayes classifier is a probabilistic machine learning model that\u2019s used for classification task. The crux of the classifier is based on the Bayes theorem.\n\n#### Bayes Theorem:\n\n#### Using Bayes theorem, we can find the probability of A happening, given that B has occurred. Here, B is the evidence and A is the hypothesis. The assumption made here is that the predictors\/features are independent. That is presence of one particular feature does not affect the other. Hence it is called naive.\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\ngb_clf = GaussianNB()\ngb_clf.fit(x_train,y_train)\ngb_clf.score(x_test,y_test)\n\"\"\"\ngb_clf = ensemble.GradientBoostingClassifier(n_estimators=40)\ngb_clf.fit(x_train,y_train)\ngb_clf.score(x_test,y_test)\n\"\"\"\n\"\"\"\n### KNN Classifier\n\n#### K-nearest neighbors (KNN) algorithm is a type of supervised ML algorithm which can be used for both classification as well as regression predictive problems. However, it is mainly used for classification predictive problems in industry. The following two properties would define KNN well \u2212\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_clf = KNeighborsClassifier(n_neighbors=5)\nknn_clf.fit(x_train,y_train)\nknn_clf.score(x_test,y_test)\n\"\"\"\n## Recurcive Feature Elimination \n\"\"\"\n# automatically select the number of features for RFE\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.pipeline import Pipeline\n# define dataset\nX, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n# create pipeline\nrfe = RFECV(estimator=DecisionTreeClassifier())\nmodel = DecisionTreeClassifier()\npipeline = Pipeline(steps=[('s',rfe),('m',model)])\n# evaluate model\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\nn_scores = cross_val_score(pipeline, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n# report performance\nprint('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))\n\"\"\"\n## One way F test \n\"\"\"\ndf_tsne = pd.DataFrame(data=tnse_features,columns=['tsne1','tsne2'])\ndf_tsne['cancer_type']=label['Class']\ndf_tsne\ndf_anova_tsne = df_tsne[['tsne2','cancer_type']]\ngrps_tsne = pd.unique(df_anova_tsne.cancer_type.values)\n\nd_data = {grp:df_anova_tsne['tsne2'][df_anova_tsne.cancer_type == grp] for grp in grps_tsne}\n\nF, p = stats.f_oneway(d_data['LUAD'], d_data['PRAD'], d_data['BRCA'], d_data['KIRC'], d_data['COAD'])\n\nif p<0.05:\n    print(\"reject null hypothesis\")\nelse:\n    print(\"accept null hypothesis\")\ndf_anova_tsne = df_tsne[['tsne1','cancer_type']]\ngrps_tsne = pd.unique(df_anova_tsne.cancer_type.values)\n\nd_data = {grp:df_anova_tsne['tsne1'][df_anova_tsne.cancer_type == grp] for grp in grps_tsne}\n\nF, p = stats.f_oneway(d_data['LUAD'], d_data['PRAD'], d_data['BRCA'], d_data['KIRC'], d_data['COAD'])\n\nif p<0.05:\n    print(\"reject null hypothesis\")\nelse:\n    print(\"accept null hypothesis\")\n\"\"\"\n## DNN \n\nThe neural network needs to learn all the time to solve tasks in a more qualified manner or even to use various methods to provide a better result. When it gets new information in the system, it learns how to act accordingly to a new situation.\n\nLearning becomes deeper when tasks you solve get harder. Deep neural network represents the type of machine learning when the system uses many layers of nodes to derive high-level functions from input information. It means transforming the data into a more creative and abstract component.\n\nIn order to understand the result of deep learning better, let's imagine a picture of an average man. Although you have never seen this picture and his face and body before, you will always identify that it is a human and differentiate it from other creatures. This is an example of how the deep neural network works. Creative and analytical components of information are analyzed and grouped to ensure that the object is identified correctly. These components are not brought to the system directly, thus the ML system has to modify and derive them. \n\"\"\"\nfeatures=master_data.drop(['Unnamed: 0'],axis=1)\nfeatures=features.drop(['Class'],axis=1)\ntarget=master_data['Class']\nfeatures.head()\ntarget.head()\nf1=features.values\ny1 = pd.get_dummies(y_lda)\nfrom sklearn.model_selection import train_test_split\n\n#y1 = pd.get_dummies(Xg_fea.Pos_Neg)\n\nX1_train, X1_valid, y1_train, y1_valid = train_test_split(f1,y1, test_size = 0.10, random_state=42)\nX1_train.shape,X1_valid.shape,y1_valid.shape,y1_train.shape\n\"\"\"\n### Define the model \n\n#### The ReLU function is f(x)=max(0,x). Usually this is applied element-wise to the output of some other function, such as a matrix-vector product. In MLP usages, rectifier units replace all other activation functions except perhaps the readout layer. But I suppose you could mix-and-match them if you'd like. One way ReLUs improve neural networks is by speeding up training. The gradient computation is very simple (either 0 or 1 depending on the sign of x). Also, the computational step of a ReLU is easy: any negative elements are set to 0.0 -- no exponentials, no multiplication or division operations. Gradients of logistic and hyperbolic tangent networks are smaller than the positive portion of the ReLU. This means that the positive portion is updated more rapidly as training progresses. However, this comes at a cost. The 0 gradient on the left-hand side is has its own problem, called \"dead neurons,\" in which a gradient update sets the incoming values to a ReLU such that the output is always zero; modified ReLU units such as ELU (or Leaky ReLU etc.) can minimize this. Source : StackExchange\n\n#### Optimizer is chosen SGD\n\n\n\"\"\"\nimport tensorflow as tf\n#Initialize Sequential model\nmodel = tf.keras.models.Sequential()\n\n#adding layers of inout\nmodel.add(tf.keras.layers.Dense(10000, input_dim=20531, activation='relu', kernel_initializer='he_uniform'))\n\n\n#Normalize the data\nmodel.add(tf.keras.layers.BatchNormalization())\n\n#Add 1st hidden layer\nmodel.add(tf.keras.layers.Dense(5000, activation='relu'))\n\n#Add 2nd hidden layer\nmodel.add(tf.keras.layers.Dense(2000, activation='relu'))\n\n#Add 3rd hidden layer\nmodel.add(tf.keras.layers.Dense(1000, activation='relu'))\n\n#Add 4th hidden layer\nmodel.add(tf.keras.layers.Dense(500, activation='relu'))\n\n#Add 5th hidden layer\nmodel.add(tf.keras.layers.Dense(200, activation='relu'))\n\n#Add 6th hidden layer\nmodel.add(tf.keras.layers.Dense(100, activation='relu'))\n\n#Add OUTPUT layer\nmodel.add(tf.keras.layers.Dense(5, activation='softmax'))\n\n#Create optimizer with non-default learning rate\nsgd_optimizer = tf.keras.optimizers.SGD(learning_rate=0.03)\n\n#Compile the model\nmodel.compile(optimizer=sgd_optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()\nhistory = model.fit(X1_train,y1_train,          \n          validation_data=(X1_valid,y1_valid),\n          epochs=5,\n          batch_size=32)\nxyz = model.predict(X1_valid)\ny_pr=[]\nfor k in xyz:\n    #np.argmax(k)\n    #print(np.argmax(k))\n    y_pr.append(np.argmax(k))\n    \ny_val=[]\nfor k in y1_valid.values:\n    #np.argmax(k)\n    #print(np.argmax(k))\n    y_val.append(np.argmax(k))\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_val, y_pr)\n\"\"\"\n### Evaluvate the model \n\"\"\"\n_, train_acc = model.evaluate(X1_train, y1_train, verbose=0)\n_, test_acc = model.evaluate(X1_valid, y1_valid, verbose=0)\nprint('Train: %.3f, Test: %.3f' % (train_acc, test_acc))\n\"\"\"\n### Plot History \n\"\"\"\nplt.plot(history.history['accuracy'], label='train')\nplt.plot(history.history['val_accuracy'], label='test')\nplt.xlabel('# of epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '5a9473501396ec'}"}
{"id":"7673","text":"\"\"\"\n### \u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435 ###\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\ntrain=pd.read_csv('..\/input\/titanic\/train.csv')\ntrain.shape\ntrain.head()\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430\u043b\u0438\u0447\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\ntrain.isnull().sum()\n# \u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0430 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439\ntrain['Survived'].value_counts()\ntrain['Survived'].value_counts(normalize=True)\n# \u041e\u0431\u0449\u0430\u044f \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0447\u0438\u0441\u043b\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u0445\ntrain.describe()\ntrain['Sex'].value_counts()\n\"\"\"\n### \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\n\"\"\"\n# \u041a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\nembark=pd.get_dummies(train['Embarked'])\ngender=pd.get_dummies(train['Sex'])\n# \u041f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430 \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u044e\u0442\u0441\u044f \u0441\u0440\u0435\u0434\u043d\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\u043c 30\ntrain['Age'].fillna(30,inplace=True)\ntrain['Age']=train['Age'].astype('int')\n# \u0412\u043e\u0437\u0440\u0430\u0441\u0442 \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d \u043d\u0430 6 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0439\ndef age_grp(age):\n    if age<13:\n        return '<13'\n    elif (age>=13) &(age<18):\n        return '13-18'\n    elif (age>=18) &(age<=24):\n        return '18-24'\n    elif (age>=25) &(age<=34):\n        return '25-34'\n    elif (age>=35) &(age<=44):\n        return '35-44'\n    else:\n        return '45+'\ntrain['Age_grp']=train['Age'].apply(lambda x: age_grp(x))\nage=pd.get_dummies(train['Age_grp'])\ntrain_df=pd.concat([train,embark,gender,age],axis=1)\ntrain_df.columns\ndef is_var(val):\n    if val>0:\n        return 1\n    else:\n        return 0\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 - Family - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0447\u043b\u0435\u043d\u043e\u0432 \u043e\u0434\u043d\u043e\u0439 \u0441\u0435\u043c\u044c\u0438 \u043d\u0430 \u0422\u0438\u0442\u0430\u043d\u0438\u043a\u0435\ntrain_df['Family']=train_df['Parch'] + 1 + train_df['SibSp']\ntrain_df['Parch']=train_df['Parch'].apply(lambda x: is_var(x))\ntrain_df['SibSp']=train_df['SibSp'].apply(lambda x: is_var(x))\nsel_cols=['Fare', \n    'Pclass', 'SibSp',\n       'Parch',  'C', 'Q',\n       'S', 'female', 'male', '18-24', '25-34', '35-44', '45+', '<13','13-18', 'Family'\n]\ntrain_df.fillna(0,inplace=True)\nX=train_df[sel_cols]\ny=train_df['Survived']\ntrain_X,val_X,train_y,val_y=train_test_split(X,y,test_size=0.3,random_state=1)\n\"\"\"\n### \u041b\u043e\u0433\u0438\u0441\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u044f ###\n\"\"\"\nlr=LogisticRegression(max_iter=400)\nlr.fit(train_X,train_y)\nlr.score(train_X,train_y)\nlr.score(val_X,val_y)\n\"\"\"\n### \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 ###\n\"\"\"\ntest=pd.read_csv('..\/input\/titanic\/test.csv')\ntest.shape\ntest.columns\n# \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0430\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u043d\u043e \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435\nembark=pd.get_dummies(test['Embarked'])\ngender=pd.get_dummies(test['Sex'])\ntest['Age'].fillna(30,inplace=True)\ntest['Age']=test['Age'].astype('int')\ntest['Age_grp']=test['Age'].apply(lambda x: age_grp(x))\nage=pd.get_dummies(test['Age_grp'])\ntest_df=pd.concat([test,embark,gender,age],axis=1)\ntest_df['Family']=test_df['Parch']+1+test_df['SibSp']\ntest_df['Parch']=test_df['Parch'].apply(lambda x: is_var(x))\ntest_df['SibSp']=test_df['SibSp'].apply(lambda x: is_var(x))\ntest_df.fillna(0,inplace=True)\ntest_X=test_df[sel_cols]\ntest_X.columns\ntest_y=lr.predict(test_X)\n\"\"\"\n### \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0444\u0430\u0439\u043b\u0430 \u0434\u043b\u044f \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 \u043d\u0430 Kaggle ###\n\"\"\"\nsub=pd.read_csv('..\/input\/titanic\/gender_submission.csv')\nsub['Survived']=test_y\nsub.head()\nsub.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': '0e4b2c7ad6fbd5'}"}
{"id":"60449","text":"\"\"\"\n## \ucc28\ubcc4\uc810\n- \ub7ec\ub2dd\ub808\uc774\ud2b8 0.01->0.0001\n- \uc5d0\ud3ec\ud06c 2000->2500\n- \uad6c\uc870\ub97c 13\uce35\uc5d0\uc11c 10\uce35\uc73c\ub85c\n- \ud65c\uc131\ud568\uc218 ELU -> leakyReLU\n- optimizer : Adagrad->Adam\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nimport torch\nimport random\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nrandom.seed(777)\ntorch.manual_seed(777)\nif device == 'cuda' :\n    torch.cuda.manual_seed_all(777)\n\n# \ud559\uc2b5 \ud30c\ub77c\ubbf8\ud130 \uc124\uc815\nlearning_rate = 0.0001\ntraining_epochs = 2500\nbatch_size = 15\n\n# Data load\ntrain_data = pd.read_csv('..\/input\/crime-types\/train_data.csv', header=None, skiprows=1, usecols=range(0, 13))\ntest_data = pd.read_csv('..\/input\/crime-types\/test_data.csv', header=None, skiprows=1, usecols=range(0, 12))\n\n# Data \ud30c\uc2f1\nx_train_data = train_data.loc[:, 1:13]\ny_train_data = train_data.loc[:, 0]\n\n# \ud30c\uc2f1\ud55c Data\ub97c numpy\uc758 array\ub85c \ubcc0\ud658\nx_train_data = np.array(x_train_data)\ny_train_data = np.array(y_train_data)\n\ntest_data = np.array(test_data)\n\n# \ubcc0\ud658\ud55c numpy\uc758 array\ub97c Tensor\ub85c \ubcc0\ud658\nx_train_data = torch.FloatTensor(x_train_data)\ny_train_data = torch.LongTensor(y_train_data)\n\ntest_data = torch.FloatTensor(test_data)\n\n# data_loader\uc5d0 \uc774\uc6a9\ud560 \ud558\ub098\uc758 train Dataset\uc73c\ub85c \ubcc0\ud658\ntrain_dataset = torch.utils.data.TensorDataset(x_train_data, y_train_data)\n\n# data_loader \uc124\uc815\ndata_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n                                          batch_size=batch_size,\n                                          shuffle=True,\n                                          drop_last=True)\n\n# \ubaa8\ub378 \uc124\uacc4\nlinear1 = torch.nn.Linear(12, 256, bias=True)\nlinear2 = torch.nn.Linear(256, 256, bias=True)\nlinear3 = torch.nn.Linear(256, 256, bias=True)\nlinear4 = torch.nn.Linear(256, 512, bias=True)\nlinear5 = torch.nn.Linear(512, 1024, bias=True)\nlinear6 = torch.nn.Linear(1024, 1024, bias=True)\nlinear7 = torch.nn.Linear(1024, 512, bias=True)\nlinear8 = torch.nn.Linear(512, 512, bias=True)\nlinear9 = torch.nn.Linear(512, 256, bias=True)\nlinear10 = torch.nn.Linear(256, 7, bias=True)\nleakyrelu = torch.nn.LeakyReLU()\n\ntorch.nn.init.xavier_normal_(linear1.weight)\ntorch.nn.init.xavier_normal_(linear2.weight)\ntorch.nn.init.xavier_uniform_(linear3.weight)\ntorch.nn.init.xavier_normal_(linear4.weight)\ntorch.nn.init.xavier_uniform_(linear5.weight)\ntorch.nn.init.xavier_normal_(linear6.weight)\ntorch.nn.init.xavier_normal_(linear7.weight)\ntorch.nn.init.xavier_normal_(linear8.weight)\ntorch.nn.init.xavier_uniform_(linear9.weight)\ntorch.nn.init.xavier_normal_(linear10.weight)\n\nmodel = torch.nn.Sequential(linear1, leakyrelu,\n                            linear2, leakyrelu,\n                            linear3, leakyrelu,\n                            linear4, leakyrelu,\n                            linear5, leakyrelu,\n                            linear6, leakyrelu,\n                            linear7, leakyrelu,\n                            linear8, leakyrelu,\n                            linear9, leakyrelu,\n                            linear10).to(device)\n\nloss = torch.nn.CrossEntropyLoss().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n# \ubaa8\ub378 \ud559\uc2b5\ntotal_batch = len(data_loader)\n\nfor epoch in range(training_epochs) :\n    avg_cost = 0\n\n    for X, Y in data_loader :\n\n        X = X.to(device)\n        Y = Y.to(device)\n\n        optimizer.zero_grad()\n        hypothesis = model(X)\n        cost = loss(hypothesis, Y)\n        cost.backward()\n        optimizer.step()\n\n        avg_cost += cost \/ total_batch\n\n    print('Epoch : {:4d}'.format(epoch+1), 'Cost : {:.9f}'.format(avg_cost))\n\nprint('Learning Finishied')\n\n# \ubaa8\ub378 \ud3c9\uac00\nwith torch.no_grad() :\n    test_data = test_data.to(device)\n\n    prediction = model(test_data)\n    prediction = torch.argmax(prediction, 1)\n    prediction = prediction.cpu().numpy().reshape(-1, 1)\n\nsubmit = pd.read_csv('submission_format.csv')\n\nfor i in range(len(prediction)) :\n    submit['Lable'][i] = prediction[i].item()\n\nsubmit.to_csv('result.csv', index=False, header=True)\n ","meta":"{'source': 'AI4Code', 'id': '6f6a088a406baa'}"}
{"id":"91702","text":"\"\"\"\n#### NLMK Kaggle InClass competition\n__The prediction of rolls wear in the hot strip mill (RAAI Summer School 2019, NLMK)__\n\n\u041f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0438\u0437\u043d\u043e\u0441\u0430 \u0432\u0430\u043b\u043a\u043e\u0432 \u043f\u0440\u043e\u043a\u0430\u0442\u043d\u043e\u0433\u043e \u0441\u0442\u0430\u043d\u0430:\n\n[C\u0442\u0440\u0430\u043d\u0438\u0446\u0430 \u043d\u0430 Kaggle](#https:\/\/www.kaggle.com\/c\/prediction-of-rolls-wear-in-hot-strip-mill2\/leaderboard)\n\"\"\"\n\"\"\"\n<a id='start'><\/a>\n [\u0412 \u043d\u0430\u0447\u0430\u043b\u043e](#start)\n \n 1. __[Data preprocessing](#prep)__\n \n 2. __[Feature engineering](#f_eng)__\n \n 3. __[Making data for model](#final_prep)__\n \n 4. __[Experiments results](#exp_res)__\n \n \u0412 \u0440\u0435\u0448\u0435\u043d\u0438\u0438 \u043d\u0430 Kaggle \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0430 \u0438\u0442\u043e\u0433\u043e\u0432\u0430\u044f \u043c\u043e\u0434\u0435\u043b\u044c.\n \u041f\u0430\u0439\u043f\u043b\u0430\u0439\u043d \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0440\u044f\u0434\u043e\u043c \u043f\u0440\u043e\u0431 \u0438 \u043e\u0448\u0438\u0431\u043e\u043a \u0432\u043a\u043b\u044e\u0447\u0430\u043b \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 baseline \u043c\u043e\u0434\u0435\u043b\u0438, \n \u0434\u043b\u044f \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u0431\u044b\u043b\u0430 \u0432\u044b\u0431\u0440\u0430\u043d\u0430 \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u044f \u0432 3 \u0432\u0430\u0440\u0438\u0430\u0446\u0438\u044f\u0445: \u0431\u0435\u0437 \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u0438\u0437\u0430\u0446\u0438\u0438, c L2, \u0441 L1 \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u0438\u0437\u0430\u0446\u0438\u0435\u0439.\n \u041f\u043e \u0438\u0442\u043e\u0433\u0430\u043c \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f baseline \u043c\u043e\u0434\u0435\u043b\u0438, \u0433\u0440\u0435\u0431\u043d\u0435\u0432\u0430\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u044f \u0434\u0430\u043b\u0430 \u0430\u0434\u0435\u043a\u0432\u0430\u0442\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0438\u043c\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u043e\u0432 \u0438 \u043b\u0443\u0447\u0448\u0438\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e \u0442\u0435\u0441\u0442\u0443.\n \u0412\u0441\u0435 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u044f \u0432 \u043f\u0435\u0440\u0432\u043e\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e\u043c \u0432\u0438\u0434\u0435 \u0441\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u043b\u0438\u0441\u044c \u0441 ridge \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u0435\u0439.\n \u0414\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0438\u0439 \u0430\u043d\u0430\u043b\u0438\u0437 \u0443\u0436\u0435 \u043d\u0430 \u043f\u0440\u0435\u0434\u0432\u0430\u0440\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0442\u0435\u0441\u0442\u0430\u0445 \u043f\u043e\u043a\u0430\u0437\u0430\u043b \u043f\u043e\u0442\u0435\u043d\u0446\u0438\u0430\u043b XGBoost.\n \u0412 \u0441\u0438\u043b\u0443 \u043d\u0430\u043b\u0438\u0447\u0438\u044f \u0431\u043e\u043b\u044c\u0448\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0438\u0442\u043e\u0433\u043e\u0432\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u044c\u044e \u0441\u0442\u0430\u043b \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u0431\u0443\u0441\u0442\u0438\u043d\u0433 CatBoost.\n\n\"\"\"\n\"\"\"\n\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0444\u0430\u0439\u043b\u043e\u0432 \u0441 \u0434\u0430\u043d\u043d\u044b\u043c\u0438\n\n    Ruloni.csv - \u0440\u0443\u043b\u043e\u043d\u044b, \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 \u0441\u0442\u0430\u043d\u0435 \u0433\u043e\u0440\u044f\u0447\u0435\u0439 \u043f\u0440\u043e\u043a\u0430\u0442\u043a\u0438 \u0437\u0430 2018 \u0433\u043e\u0434\n    Valki.csv - \u0440\u0430\u0431\u043e\u0447\u0438\u0435 \u0432\u0430\u043b\u043a\u0438 \u0447\u0438\u0441\u0442\u043e\u0432\u044b\u0445 \u043a\u043b\u0435\u0442\u0435\u0439\n    Zavalki.csv - \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0430 \u0432\u0430\u043b\u043a\u043e\u0432 \u043d\u0430 \u0441\u0442\u0430\u043d\u0435 (I-III \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u044b 2018 \u0433\u043e\u0434\u0430)\n    Test.csv - \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0430 \u0432\u0430\u043b\u043a\u043e\u0432 \u0432 IV \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u0435 2018, \u0438\u0437\u043d\u043e\u0441 \u043d\u0435 \u0443\u043a\u0430\u0437\u0430\u043d, \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u043e \u043f\u043e\u043b\u0435 id \u0434\u043b\u044f \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 \u043f\u0440\u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0435, \u0441\u043c. \u0444\u0430\u0439\u043b sample_test.csv\n    sample_test.csv - \u0444\u0430\u0439\u043b-\u0448\u0430\u0431\u043b\u043e\u043d \u0434\u043b\u044f \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 \u043d\u0430 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443 (\u0441\u0430\u0431\u043c\u0438\u0442\u0430)\n\n\u0421\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0430 \u0442\u0430\u0431\u043b\u0438\u0446 \u0432 \u0444\u0430\u0439\u043b\u0430\u0445\n\n    Ruloni.csv\n    \u041c\u0430\u0440\u043a\u0430 - \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043c\u0430\u0440\u043a\u0438 \u0441\u0442\u0430\u043b\u0438\n    \u041c\u0430\u0441\u0441\u0430 - \u043c\u0430\u0441\u0441\u0430 \u043f\u0440\u043e\u043a\u0430\u0442\u0430\u043d\u043d\u043e\u0433\u043e \u0440\u0443\u043b\u043e\u043d\u0430 (\u0442)\n    \u0422\u043e\u043b\u0449\u0438\u043d\u0430 - \u0442\u043e\u043b\u0449\u0438\u043d\u0430 \u043f\u043e\u043b\u043e\u0441\u044b \u043c\u0435\u0442\u0430\u043b\u043b\u0430 (\u043c\u043c)\n    \u0428\u0438\u0440\u0438\u043d\u0430 - \u0448\u0438\u0440\u0438\u043d\u0430 \u043f\u043e\u043b\u043e\u0441\u044b \u043c\u0435\u0442\u0430\u043b\u043b\u0430 (\u043c\u043c)\n    \u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 - \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043c\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0440\u0443\u043b\u043e\u043d\u0430\n    \n    \n    Valki.csv\n    \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b_\u0432\u0430\u043b\u043a\u0430 - \u043d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u0430 \u0432\u0430\u043b\u043a\u0430\n    \u043d\u043e\u043c\u0435\u0440_\u0432\u0430\u043b\u043a\u0430 - \u0443\u0447\u0451\u0442\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0432\u0430\u043b\u043a\u0430\n    \n    \n    Zavalki.csv\n    \u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438 - \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043c\u044f \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 \u0432\u0430\u043b\u043a\u0430 \u0432 \u0441\u0442\u0430\u043d\n    \u0434\u0430\u0442\u0430_\u0432\u044b\u0432\u0430\u043b\u043a\u0438 - \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043c\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f \u0432\u0430\u043b\u043a\u0430 \u0438\u0437 \u0441\u0442\u0430\u043d\u0430\n    \u043d\u043e\u043c\u0435\u0440_\u043a\u043b\u0435\u0442\u043a\u0438 - \u043d\u043e\u043c\u0435\u0440 \u043a\u043b\u0435\u0442\u0438 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 (\u043a\u043b\u0435\u0442\u0438 8-12)\n    \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435_\u0432_\u043a\u043b\u0435\u0442\u0438 - \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u0432 \u043a\u043b\u0435\u0442\u0438 (\u0432\u0435\u0440\u0445 \u0438\u043b\u0438 \u043d\u0438\u0437)\n    \u043d\u043e\u043c\u0435\u0440_\u0432\u0430\u043b\u043a\u0430 - \u0443\u0447\u0451\u0442\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0432\u0430\u043b\u043a\u0430\n    \u0438\u0437\u043d\u043e\u0441 - \u0443\u043c\u0435\u043d\u044c\u0448\u0435\u043d\u0438\u0435 \u0434\u0438\u0430\u043c\u0435\u0442\u0440\u0430 \u0432\u0430\u043b\u043a\u0430 \u043f\u0440\u0438 \u0440\u0430\u0431\u043e\u0442\u0435 \u0438 \u043f\u043e\u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0439 \u0448\u043b\u0438\u0444\u043e\u0432\u043a\u0435 (\u044d\u0442\u0443 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u0443 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043d\u0430\u0443\u0447\u0438\u0442\u044c\u0441\u044f \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c)\n    \n    \n    Test.csv\n    id - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 \u0432\u0430\u043b\u043a\u0430 (\u044d\u0442\u043e\u0442 \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0434\u043e\u043b\u0436\u0435\u043d \u0431\u044b\u0442\u044c \u0432 \u0444\u0430\u0439\u043b\u0435 \u0441 \u0432\u0430\u0448\u0438\u043c \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u043e\u043c sample_test.csv)\n    \u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438 - \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043c\u044f \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 \u0432\u0430\u043b\u043a\u0430 \u0432 \u0441\u0442\u0430\u043d\n    \u0434\u0430\u0442\u0430_\u0432\u044b\u0432\u0430\u043b\u043a\u0438 - \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043c\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f \u0432\u0430\u043b\u043a\u0430 \u0438\u0437 \u0441\u0442\u0430\u043d\u0430\n    \u043d\u043e\u043c\u0435\u0440_\u043a\u043b\u0435\u0442\u043a\u0438 - \u043d\u043e\u043c\u0435\u0440 \u043a\u043b\u0435\u0442\u0438 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 (\u043a\u043b\u0435\u0442\u0438 8-12)\n    \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435_\u0432_\u043a\u043b\u0435\u0442\u0438 - \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u0432 \u043a\u043b\u0435\u0442\u0438 (\u0432\u0435\u0440\u0445 \u0438\u043b\u0438 \u043d\u0438\u0437)\n    \u043d\u043e\u043c\u0435\u0440_\u0432\u0430\u043b\u043a\u0430 - \u0443\u0447\u0451\u0442\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0432\u0430\u043b\u043a\u0430\n    sample_test.csv\n    id - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0438 \u0432\u0430\u043b\u043a\u043e\u0432 \u0438\u0437 \u0444\u0430\u0439\u043b\u0430 Test.csv\n    iznos - \u0432\u0430\u0448 \u043f\u0440\u043e\u0433\u043d\u043e\u0437 \u0438\u0437\u043d\u043e\u0441\u0430 \u0432\u0430\u043b\u043a\u0430\n\n\"\"\"\nINPUT_DIR = r'..\/input'\nimport os\nprint(os.listdir(INPUT_DIR))\nimport os\nimport time\nimport tqdm\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom catboost import Pool, CatBoostRegressor\nimport hyperopt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nsns.set()\n\"\"\"\n#### Data preprocessing\n<a id='prep'><\/a>\n [\u0412 \u043d\u0430\u0447\u0430\u043b\u043e](#start)\n\"\"\"\n# \u0427\u0442\u0435\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\ndf_ruloni = pd.read_csv(os.path.join(INPUT_DIR, 'Ruloni.csv'))\ndf_ruloni_copy = df_ruloni.copy()\ndf_valki = pd.read_csv(os.path.join(INPUT_DIR, 'Valki.csv'))\ndf_zavalki = pd.read_csv(os.path.join(INPUT_DIR, 'Zavalki.csv'))\n\ndf_ruloni.rename({'\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438':'\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'}, axis=1, inplace=True)\ndf_test = pd.read_csv(os.path.join(INPUT_DIR, 'Test.csv'))\ndf_sample_test = pd.read_csv(os.path.join(INPUT_DIR, 'sample_test.csv'))\n# \u0417\u0430\u043f\u0438\u0448\u0435\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u044b \u043f\u0430\u0440\u0442\u0438\u0439\ndf_ruloni['party'] = 1e10\n\n# \u041f\u043e \u0434\u0430\u0442\u0430\u043c \u0437\u0430\u0432\u0430\u043b\u043a\u0438 \u0442\u0440\u0435\u0439\u043d\u0430\ndates = df_zavalki['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'].unique().tolist()\n# \u041f\u043e \u0434\u0430\u0442\u0430\u043c \u0437\u0430\u0432\u0430\u043b\u043a\u0438 \u0442\u0435\u0441\u0442\u0430\ntest_dates = df_test['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'].unique().tolist()\ndates = dates + test_dates\n\ni = 0\nfor f in tqdm.tqdm_notebook(dates[1:]):\n    #print(f'{f} < x <{dates[i]}')  \n    df_ruloni.loc[(df_ruloni['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'] < f)&\n                  (df_ruloni['party'] >= i), 'party'] = i\n    i+=1\n\n# \u041a\u043e\u0440\u0440\u0435\u043a\u0442\u0438\u0440\u043e\u0432\u043a\u0430 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0439 \u043e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0435\u043c\u043e\u0439 \u043f\u0430\u0440\u0442\u0438\u0438\n# <2018-12-31 21:03:39\ndf_ruloni.loc[(df_ruloni['party']==1e10)&\n              (df_ruloni['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438']<'2018-12-31 21:03:39'), 'party'] = 2413\ndf_ruloni.loc[df_ruloni['party']==1e10, 'party'] = 2414\ndf_ruloni.tail()\n# \u0415\u0449\u0435 \u0434\u043e\u0431\u0430\u0432\u0438\u043c \u0434\u043b\u044f \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u044f, \u0447\u0442\u043e \u0448\u043b\u043e \u043f\u043e \u043f\u043e\u0440\u044f\u0434\u043a\u0443 \u0432 \u043f\u0430\u0440\u0442\u0438\u0438\ndf_ruloni['\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430'] = None\nfor i in tqdm.tqdm_notebook(range(2414+1)):\n    l = df_ruloni[df_ruloni['party']==i].shape[0]\n    df_ruloni.loc[df_ruloni['party']==i, '\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430'] = [x for x in range(1, l+1)]\n# \u0414\u043b\u044f df_ruloni \u0434\u0430\u0442\u0443 \u0437\u0430\u0432\u0430\u043b\u043a\u0438 \u0434\u043e\u0431\u0430\u0432\u0438\u043c \u043d\u0430\u0447\u0430\u043b\u044c\u043d\u0443\u044e, \u0447\u0442\u043e\u0431\u044b \u0441\u043e\u043f\u043e\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u0441 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u043c\u0438 \u0434\u0430\u043d\u043d\u044b\u043c\u0438\nfor i in tqdm.tqdm_notebook(range(2414+1)):\n    d = df_ruloni[df_ruloni['party']==i]['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'].iloc[0]\n    df_ruloni.loc[df_ruloni['party']==i, '\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'] = d\ndf_ruloni.head()\ndf_ruloni['\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430'].max()\n# \u0422\u043e\u043d\u043d\u0430\u0436 \ntonn = pd.DataFrame(df_ruloni.groupby(['party'])['\u041c\u0430\u0441\u0441\u0430'].sum())\ntonn.reset_index(inplace=True, drop=False)\nmass_std = tonn['\u041c\u0430\u0441\u0441\u0430'].std()\nmass_mean = tonn['\u041c\u0430\u0441\u0441\u0430'].mean()\nplt.hist(tonn['\u041c\u0430\u0441\u0441\u0430'], bins = 20)\nplt.plot([mass_mean+ 3*mass_std for x in range(100)], [x*2 for x in range(100)])\nplt.plot([mass_mean- 3*mass_std for x in range(100)], [x*2 for x in range(100)])\nplt.show()\ndf_ruloni['\u0428\u0438\u0440\u0438\u043d\u0430'].hist(bins=20)\nplt.show()\ndf_ruloni['\u0422\u043e\u043b\u0449\u0438\u043d\u0430'].hist(bins=20)\nplt.show()\n# \u0415\u0434\u0438\u043d\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u044f\u0432\u043d\u044b\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c - \u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438\nmarki = pd.get_dummies(df_ruloni['\u041c\u0430\u0440\u043a\u0430'])\ndf_ruloni = pd.concat([df_ruloni, marki], axis=1)\ndel df_ruloni['\u041c\u0430\u0440\u043a\u0430']\ndf_ruloni.head()\n\"\"\"\n<a id='f_eng'><\/a>\n#### Feature engineering\n [\u0412 \u043d\u0430\u0447\u0430\u043b\u043e](#start)\n\"\"\"\ndef to_dtime(s):\n    return datetime.datetime.strptime(s, \"%Y-%m-%d %H:%M:%S\")\ndef to_seconds(end, start):\n    return (to_dtime(end) - to_dtime(start)).seconds\n# \u0418\u043c\u0435\u043d\u0430 \u043f\u0440\u043e\u043a\u0430\u0442\u044b\u0432\u0430\u0435\u043c\u044b\u0445 \u043c\u0430\u0440\u043e\u043a \u0441\u0442\u0430\u043b\u0438\nmarki_names = df_ruloni.columns.tolist()[6:]\n\ndf_ruloni['\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430'] = df_ruloni['\u0422\u043e\u043b\u0449\u0438\u043d\u0430']*df_ruloni['\u0428\u0438\u0440\u0438\u043d\u0430']\n# \u0414\u0430\u043d\u043d\u044b\u0435 \u043f\u043e \u043f\u0440\u043e\u043a\u0430\u0442\u044b\u0432\u0430\u0435\u043c\u044b\u043c \u043c\u0430\u0440\u043a\u0430\u043c \u0441\u0442\u0430\u043b\u0438\nv1 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])[marki_names].sum())\nv1.reset_index(inplace=True)\n\n# \u0421\u043a\u043e\u043b\u044c\u043a\u043e \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u0430 \u043f\u0440\u043e\u0448\u043b\u043e\nv2 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430'].max())\nv2.reset_index(inplace=True)\nv2.rename({'\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430':'\u043f\u0440\u043e\u0448\u043b\u043e_\u0440\u0443\u043b\u043e\u043d\u043e\u0432'}, axis=1)\n\n# \u0421\u0443\u043c\u043c\u0430\u0440\u043d\u0430\u044f \u043f\u0440\u043e\u0439\u0434\u0435\u043d\u043d\u0430\u044f \u043c\u0430\u0441\u0441\u0430\nv3 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041c\u0430\u0441\u0441\u0430'].sum())\nv3.reset_index(inplace=True)\nv3.rename({'\u041c\u0430\u0441\u0441\u0430':'\u041c\u0430\u0441\u0441\u0430_\u0441\u0443\u043c\u043c\u0430'}, axis=1, inplace=True)\n\n# \u041c\u0438\u043d\u0438\u043c\u0443\u043c \u043c\u0430\u0441\u0441\u044b\nv4 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041c\u0430\u0441\u0441\u0430'].min())\nv4.reset_index(inplace=True)\nv4.rename({'\u041c\u0430\u0441\u0441\u0430':'\u041c\u0430\u0441\u0441\u0430_\u043c\u0438\u043d'}, axis=1, inplace=True)\n\n# \u041c\u0430\u043a\u0441\u0438\u043c\u0443\u043c \u043c\u0430\u0441\u0441\u044b\nv5 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041c\u0430\u0441\u0441\u0430'].max())\nv5.reset_index(inplace=True)\nv5.rename({'\u041c\u0430\u0441\u0441\u0430':'\u041c\u0430\u0441\u0441\u0430_\u043c\u0430\u043a\u0441'}, axis=1, inplace=True)\n\n# \u0421\u0438\u0433\u043c\u0430 \u043c\u0430\u0441\u0441\u0430\nv6 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041c\u0430\u0441\u0441\u0430'].std())\nv6.reset_index(inplace=True)\nv6.rename({'\u041c\u0430\u0441\u0441\u0430':'\u041c\u0430\u0441\u0441\u0430_\u0441\u0438\u0433\u043c\u0430'}, axis=1, inplace=True)\n\n# \u0421\u0440\u0435\u0434\u043d\u044f\u044f \u043c\u0430\u0441\u0441\u0430\nv7 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041c\u0430\u0441\u0441\u0430'].mean())\nv7.reset_index(inplace=True)\nv7.rename({'\u041c\u0430\u0441\u0441\u0430':'\u041c\u0430\u0441\u0441\u0430_\u0441\u0440'}, axis=1, inplace=True)\n# \u0421\u0440\u0435\u0434\u043d\u044f\u044f \u0442\u043e\u043b\u0449\u0438\u043d\u0430\nv8 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430'].mean())\nv8.reset_index(inplace=True)\nv8.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0441\u0440'}, axis=1, inplace=True)\n\n# \u0421\u0438\u0433\u043c\u0430 \u0442\u043e\u043b\u0449\u0438\u043d\u044b\nv9 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430'].std())\nv9.reset_index(inplace=True)\nv9.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0441\u0438\u0433\u043c\u0430'}, axis=1, inplace=True)\n\n# \u0421\u0440\u0435\u0434\u043d\u044f\u044f \u0448\u0438\u0440\u0438\u043d\u0430\nv10 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0428\u0438\u0440\u0438\u043d\u0430'].mean())\nv10.reset_index(inplace=True)\nv10.rename({'\u0428\u0438\u0440\u0438\u043d\u0430':'\u0428\u0438\u0440\u0438\u043d\u0430_\u0441\u0440'}, axis=1, inplace=True)\n\n# \u0421\u0438\u0433\u043c\u0430 \u0448\u0438\u0440\u0438\u043d\u044b\nv11 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0428\u0438\u0440\u0438\u043d\u0430'].std())\nv11.reset_index(inplace=True)\nv11.rename({'\u0428\u0438\u0440\u0438\u043d\u0430':'\u0428\u0438\u0440\u0438\u043d\u0430_\u0441\u0438\u0433\u043c\u0430'}, axis=1, inplace=True)\n\n# \u0421\u0440\u0435\u0434\u043d\u044f\u044f \u0422\u043e\u043b\u0449\u0438\u043d\u0430*\u0428\u0438\u0440\u0438\u043d\u0430\nv12 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430'].mean())\nv12.reset_index(inplace=True)\nv12.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430_\u0441\u0440'}, axis=1, inplace=True)\n\n# \u0421\u0438\u0433\u043c\u0430 \u0422\u043e\u043b\u0449\u0438\u043d\u0430*\u0428\u0438\u0440\u0438\u043d\u0430\nv13 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430'].std())\nv13.reset_index(inplace=True)\nv13.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430_\u0441\u0438\u0433\u043c\u0430'}, axis=1, inplace=True)\n# \u041c\u0438\u043d \u0442\u043e\u043b\u0449\u0438\u043d\u044b\nv14 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430'].min())\nv14.reset_index(inplace=True)\nv14.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u043c\u0438\u043d'}, axis=1, inplace=True)\n\n# \u041c\u0430\u043a\u0441 \u0442\u043e\u043b\u0449\u0438\u043d\u044b\nv15 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0422\u043e\u043b\u0449\u0438\u043d\u0430'].max())\nv15.reset_index(inplace=True)\nv15.rename({'\u0422\u043e\u043b\u0449\u0438\u043d\u0430':'\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u043c\u0430\u043a\u0441'}, axis=1, inplace=True)\n\n# \u041c\u0438\u043d \u0448\u0438\u0440\u0438\u043d\u044b\nv16 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0428\u0438\u0440\u0438\u043d\u0430'].min())\nv16.reset_index(inplace=True)\nv16.rename({'\u0428\u0438\u0440\u0438\u043d\u0430':'\u0428\u0438\u0440\u0438\u043d\u0430_\u043c\u0438\u043d'}, axis=1, inplace=True)\n\n# \u041c\u0430\u043a\u0441 \u0448\u0438\u0440\u0438\u043d\u044b\nv17 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u0428\u0438\u0440\u0438\u043d\u0430'].max())\nv17.reset_index(inplace=True)\nv17.rename({'\u0428\u0438\u0440\u0438\u043d\u0430':'\u0428\u0438\u0440\u0438\u043d\u0430_\u043c\u0430\u043a\u0441'}, axis=1, inplace=True)\n# \u0414\u043e\u0431\u0430\u0432\u0438\u043c \u0432\u0440\u0435\u043c\u044f \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0434\u043b\u044f \u043f\u043e\u043e\u043f\u0435\u0440\u0430\u0446\u0438\u043e\u043d\u043d\u043e\u0433\u043e \u043f\u043e\u0434\u0441\u0447\u0435\u0442\u0430\ndf_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438'] = df_ruloni_copy['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438']\ndf_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438_lag'] = df_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438'].shift(1)\ndf_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438_lag'].fillna(value=0, inplace=True)\nt = [116.81109473044754] # \u0421\u0440\u0435\u0434\u043d\u0435\u0435 \u043f\u043e \u0432\u0441\u0435\u043c \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u043c \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\nfor i in tqdm.tqdm_notebook(range(1,df_ruloni.shape[0])):\n    s = to_seconds(df_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438'].iloc[i],\n                   df_ruloni['\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438_lag'].iloc[i])\n    t.append(s)\ndf_ruloni['\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f'] = t\n# \u0421\u0440\u0435\u0434\u043d\u044f\u044f \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044f\nv18 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f'].mean())\nv18.reset_index(inplace=True)\nv18.rename({'\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f':'\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f_\u0441\u0440'}, axis=1, inplace=True)\n\n# \u0421\u0438\u0433\u043c\u0430 \u043e\u043f\u0435\u0440\u0430\u0446\u0438\u044f\nv19 = pd.DataFrame(df_ruloni.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])['\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f'].std())\nv19.reset_index(inplace=True)\nv19.rename({'\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f':'\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f_\u0441\u0438\u0433\u043c\u0430'}, axis=1, inplace=True)\n# \u0414\u043e\u0431\u0430\u0432\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0434\u043e\u043b\u0435\u0439 \u0432\u0440\u0435\u043c\u0435\u043d\u0438, \u0437\u0430\u0442\u0440\u0430\u0447\u0435\u043d\u043d\u044b\u0445 \u043d\u0430 \u043a\u0430\u0436\u0434\u0443\u044e \u043c\u0430\u0440\u043a\u0443 \u0441\u0442\u0430\u043b\u0438\ndf_ruloni_newf = df_ruloni.copy()\n\ncls = df_ruloni_newf.columns.tolist()\nfor i in ['\u041c\u0430\u0441\u0441\u0430', '\u0422\u043e\u043b\u0449\u0438\u043d\u0430', '\u0428\u0438\u0440\u0438\u043d\u0430', '\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438', 'party',\n          '\u043f\u043e\u0440\u044f\u0434\u043e\u043a_\u043f\u0440\u043e\u0445\u043e\u0434\u0430', '\u0422\u043e\u043b\u0449\u0438\u043d\u0430_\u0428\u0438\u0440\u0438\u043d\u0430','\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438',\n          '\u0412\u0440\u0435\u043c\u044f_\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438_lag']:\n    cls.remove(i)\ndf_ruloni_newf = df_ruloni_newf[cls].copy()\ncls.remove('\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f')\nfor i in cls:\n    df_ruloni_newf[f'{i}_time'] = df_ruloni_newf[i]*df_ruloni_newf['\u041e\u043f\u0435\u0440\u0430\u0446\u0438\u044f']\n    \nmarki_times = df_ruloni_newf.columns.tolist()[100:]\ndf_ruloni_newf['marki_time'] = 0\nfor m in marki_times:\n    df_ruloni_newf['marki_time'] = df_ruloni_newf[m]+df_ruloni_newf['marki_time']\ndf_ruloni['marki_time'] = df_ruloni_newf['marki_time']\ndf_ruloni_newf = df_ruloni_newf[marki_times].copy()\ndf_ruloni_newf['party'] = df_ruloni['party']\ntmp = pd.DataFrame(df_ruloni.groupby(['party'])['marki_time'].sum())\ntmp.reset_index(inplace=True, drop=False)\ntmp.rename({'marki_time':'marki_time_sum'}, axis=1, inplace=True)\n\ndf_ruloni_newf = df_ruloni_newf.merge(tmp, how='left', on = ['party'])\n\nfor m in marki_times:\n    df_ruloni_newf[m] = df_ruloni_newf[m]\/df_ruloni_newf['marki_time_sum']\n    \ntime_fractions = df_ruloni_newf[marki_times].copy()\ntime_fractions['party'] = df_ruloni['party']\ntime_fractions['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'] = df_ruloni['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438']\n\ntime_fr = time_fractions.groupby(['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])[marki_times].sum()\ntime_fr.reset_index(inplace=True, drop=False)\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u0441\u0443\u043c\u043c\u044b \u0434\u043e\u043b\u0435\u0439 \u043f\u043e \u043e\u0434\u043d\u043e\u043c\u0443 \u043f\u0440\u043e\u0433\u043e\u043d\u0443 \u043f\u0430\u0440\u0442\u0438\u0438. \n# 1+- machine eps\ntime_fr.iloc[0][marki_times].sum()\ntime_fr.head(1)\ndf_zavalki.head()\n# \u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435 df_ruloni\ndf_ruloni_exp = pd.merge(v1,v2, how='left', on = ['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])\nfor v in [v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,\n          v14,v15,v16,v17,v18,v19,time_fr]:\n    df_ruloni_exp = pd.merge(df_ruloni_exp, v, how='left', on = ['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])\ndf_ruloni_exp.head(1)\ndf_ruloni_exp.shape\n\"\"\"\n<a id='final_prep'><\/a>\n#### Final preprocess for modeling\n [\u0412 \u043d\u0430\u0447\u0430\u043b\u043e](#start)\n\"\"\"\ndef process_df_tocatb(df_test, df_valki, df_ruloni):\n\n    df_test['\u043d\u043e\u043c\u0435\u0440_\u043a\u043b\u0435\u0442\u043a\u0438'] = df_test['\u043d\u043e\u043c\u0435\u0440_\u043a\u043b\u0435\u0442\u043a\u0438'].astype(str)\n    \n    time_sec = []\n    for i in tqdm.tqdm(range(df_test.shape[0])):\n        s = to_seconds(df_test.iloc[i]['\u0434\u0430\u0442\u0430_\u0432\u044b\u0432\u0430\u043b\u043a\u0438'], df_test.iloc[i]['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])\n        time_sec.append(s)\n        \n    df_test['time_sec'] = time_sec\n    df_test = df_test.merge(df_valki, how='left', on = ['\u043d\u043e\u043c\u0435\u0440_\u0432\u0430\u043b\u043a\u0430'])\n    \n    df_test = df_test.merge(df_ruloni, how='left', on = ['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438'])\n\n    df_test.rename({'\u0438\u0437\u043d\u043e\u0441':'y'}, axis=1, inplace=True)\n    \n    return df_test\n# \u0418\u0442\u043e\u0433\u043e\u0432\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\nzavalki_to_catboost = process_df_tocatb(df_zavalki, df_valki, df_ruloni_exp)\n# \u0422\u0435\u0441\u0442\u043e\u0432\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\ntest_to_catboost = process_df_tocatb(df_test, df_valki, df_ruloni_exp)\nzavalki_to_catboost.head()\ndef y_hist(zavalki_to_catboost):\n    # \u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043e\u0442\u0432\u0435\u0442\u0430\n    plt.hist(zavalki_to_catboost['y'].values, bins=20)\n    y_mean = zavalki_to_catboost['y'].mean()\n    y_std = zavalki_to_catboost['y'].std()\n    plt.plot([y_mean+ 3*y_std for x in range(1000)], [x*2 for x in range(1000)], color='r')\n    plt.plot([y_mean- 3*y_std for x in range(1000)], [x*2 for x in range(1000)], color='r')\n    plt.plot()\n    plt.show()\ny_hist(zavalki_to_catboost)\n# \u0423\u0441\u0435\u0447\u0435\u043d\u0438\u0435 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nzavalki_to_catboost = zavalki_to_catboost[zavalki_to_catboost['y'] <=2]\nzavalki_to_catboost_ts= zavalki_to_catboost.copy()\nzavalki_to_catboost_ts.reset_index(inplace=True, drop=True)\nplt.hist(zavalki_to_catboost['y'].values, bins=20)\nplt.show()\n# \u0415\u0441\u0442\u044c \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u0434\u0430\u043d\u043d\u044b\u0445 \u043f\u043e 4 \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u0443\n# \u0418\u0445 \u0432\u043e\u0437\u044c\u043c\u0435\u043c \u0434\u043b\u044f \u0434\u0435\u0442\u0435\u043a\u0446\u0438\u0438 \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0438\u0442\u043e\u0433\u043e\u0432\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438\nprint(zavalki_to_catboost.iloc[17825:].shape)\nzavalki_to_catboost.iloc[17825:]\n# \u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043e\u043a \u0432\u0440\u0435\u043c\u0435\u043d\u0438\ndel zavalki_to_catboost['\u0434\u0430\u0442\u0430_\u0437\u0430\u0432\u0430\u043b\u043a\u0438']\ndel zavalki_to_catboost['\u0434\u0430\u0442\u0430_\u0432\u044b\u0432\u0430\u043b\u043a\u0438']\n# \u0420\u0430\u0437\u0431\u0438\u0442\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445 \u043f\u043e \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u043e\u043c.\n# \u0422\u0435\u0441\u0442\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432 \u0441 \u043f\u043e\u043a\u0432\u0430\u0440\u0442\u0430\u043b\u044c\u043d\u044b\u043c \u043e\u043a\u043d\u043e\u043c:\n# Train 1q, Test 2q; Train 2q, Test 3q\n# \u041d\u0435\u0431\u043e\u043b\u044c\u0448\u0430\u044f \u0447\u0430\u0441\u0442\u044c \u0434\u0430\u043d\u044b\u0445 \u043f\u043e 4 \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u0443 - \u0434\u043b\u044f \u0432\u044b\u0431\u043e\u0440\u0430 best_model \u0434\u043b\u044f \u0441\u0430\u0431\u043c\u0438\u0442\u0430.\n\n# \u041f\u043e\u043a\u0432\u0430\u0440\u0442\u0430\u043b\u044c\u043d\u044b\u0435 \u0430\u0434\u0440\u0435\u0441\u0430 \u044f\u0447\u0435\u0435\u043a \u0441 \u0443\u0441\u0435\u0447\u0435\u043d\u043d\u044b\u043c\u0438 \u043f\u043e y \u0434\u0430\u043d\u043d\u044b\u043c\u0438 \n# 1 reduced: 0:5869\n# 2 reduced: 5869:11806\n# 3 reduced: 11806:17825\n# 4 small:   17825:end\nX_q1nohe, y_q1 = zavalki_to_catboost.iloc[0:5869], zavalki_to_catboost['y'].iloc[0:5869]\nX_q2nohe, y_q2 = zavalki_to_catboost.iloc[5870:11806], zavalki_to_catboost['y'].iloc[5870:11806]\nX_q3nohe, y_q3 = zavalki_to_catboost.iloc[11807:17825], zavalki_to_catboost['y'].iloc[11807:17825]\nX_q4_small_val, y_q4_small_val = zavalki_to_catboost.iloc[17825:], zavalki_to_catboost['y'].iloc[17825:]\nzavalki_to_catboost.head(1)\nzavalki_to_catboost.shape\n# \u041f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0438 \u0438\u0445 \u0438\u043d\u0434\u0435\u043a\u0441\u044b\nfor i, f in enumerate(X_q1nohe.columns):\n    print(i, f)\n\"\"\"\n#### Experiments results\n<a id='exp_res'><\/a>\n [\u0412 \u043d\u0430\u0447\u0430\u043b\u043e](#start)\n\"\"\"\n#------------------------------\n#  \u0421\u0432\u043e\u0434\u043a\u0438 \u0438\u0437 \u0447\u0430\u0441\u0442\u0438 \u0438\u0434\u0435\u0439 \u043f\u043e \u0441\u043d\u0438\u0436\u0435\u043d\u0438\u044e RMSE \u0434\u043b\u044f Catboost\n#  \u041a\u0432\u0430\u0440\u0442\u0430\u043b\u044c\u043d\u0430\u044f \u0440\u0430\u0437\u0431\u0438\u0432\u043a\u0430 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0430 \u0441 \u0446\u0435\u043b\u044c\u044e \u043f\u0440\u0438\u0431\u043b\u0438\u0437\u0438\u0442\u044c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043a \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e \u043f\u0440\u0430\u0432\u0434\u043e\u043f\u043e\u0434\u043e\u0431\u043d\u043e\u043c\u0443 \u043f\u043e \u0441\u0430\u0431\u043c\u0438\u0442\u0443\n#------------------------------\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u0432\u0441\u0435\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \n#(0.2678169292)\/(0.2695692791) - \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\n\n# \u043c\u0438\u043d\/\u043c\u0430\u043a\u0441 \u043f\u043e \u0422\u043e\u043b\u0449\u0438\u043d\u0435 \u0438 \u0428\u0438\u0440\u0438\u043d\u0435\n# (0.2592309416)\/(0.2623674841)- \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\n\n# \u0438\u0433\u043d\u043e\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0441 \u043d\u0443\u043b\u0435\u0432\u044b\u043c \u0432\u0435\u0441\u043e\u043c \u043f\u043e \u0438\u0442\u043e\u0433\u0430\u043c\n# (0.2592309416)\/(0.2623674841)- \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\n\n# \u043c\u0438\u043d\/\u043c\u0430\u043a\u0441 \u043f\u043e \u0422\u043e\u043b\u0449\u0438\u043d\u0430*\u0428\u0438\u0440\u0438\u043d\u0430\n# (0.2592564188)\/(0.2630818086)- \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438. \u0423\u0431\u0440\u0430\u0442\u044c\n\n# \u0423\u0431\u0440\u0430\u043d\u043e \u043c\u0438\u043d\/\u043c\u0430\u043a\u0441 \u043f\u043e \u0422\u043e\u043b\u0449\u0438\u043d\u0430*\u0428\u0438\u0440\u0438\u043d\u0430\n# (0.2592791627)\/(0.2626429178)- \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n\n# \u0421\u0440\u0435\u0434\u043d\u0435\u0435 \u0438 \u0441\u0438\u0433\u043c\u0430 \u043f\u043e \u041e\u043f\u0435\u0440\u0430\u0446\u0438\u0438\n# (0.2581583367)\/(0.2625029269)- \u043d\u0430 2999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n\n# \u041c\u0430\u0441\u0441\u0430_\u0441\u0443\u043c\u043c\u0430\/time_sec:\n# (0.2603577499)\/(0.2630249549)\n\n# \u0414\u043e\u043b\u0438 \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u043c\u0430\u0440\u043e\u043a \u0441\u0442\n# (0.2567618605)\/(0.259612986)\n\n# \u0414\u043e\u043b\u0438 \u043c\u0430\u0441\u0441 \u043c\u0430\u0440\u043e\u043a \u0441\u0442\n# (0.2567835873)\/(0.260658636) \u0423\u0431\u0440\u0430\u0442\u044c\n\n# iterations 3000>3500 \n# (0.255353185)\/(0.2585162396)  - \u043d\u0430 3499 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n\n# iterations 3500>4000\n# (0.2545113556)\/(0.2576650744) - \u043d\u0430 3999 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n\n#  \u041f\u0440\u0438\u043c\u0435\u043d\u0435\u043d\u0438\u0435 hyperopt\n# 500 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0439, 10 eval-\u043e\u0432\n# {'l2_leaf_reg': 2.0, 'learning_rate': 0.03375590702146598}\n# [13:01<00:00, 77.64s\/it, best loss: 0.00924935909274656]\n# (0.2511933302)\/(0.2562225371)\n\n# \u041e\u0442\u0440\u0430\u0431\u043e\u0442\u043a\u0430 hyperopt \u043d\u0430 colaboratory:\n\n\"\"\"\ndef hyperopt_objective(params):\n    model = CatBoostRegressor(\n        l2_leaf_reg=int(params['l2_leaf_reg']),\n        learning_rate=params['learning_rate'],\n        iterations=3000,\n        eval_metric='RMSE',\n        random_seed=42,\n        task_type=\"GPU\",\n        logging_level='Silent'\n    )\n    \n    cv_data = cv(\n        Pool(zavalki_to_catboost, zavalki_to_catboost['y'],\n             cat_features=categorical_features_indices),\n        model.get_params()\n    )\n    best_rmse = np.min(cv_data['test-RMSE-mean'])\n    \n    return best_rmse # as hyperopt minimises\n    \nfrom numpy.random import RandomState\nparams_space = {\n    'l2_leaf_reg': hyperopt.hp.qloguniform('l2_leaf_reg', 0, 2, 1),\n    'learning_rate': hyperopt.hp.uniform('learning_rate', 1e-3, 1e-1),\n}\n\ntrials = hyperopt.Trials()\n\nbest = hyperopt.fmin(\n    hyperopt_objective,\n    space=params_space,\n    algo=hyperopt.tpe.suggest,\n    max_evals=10,\n    trials=trials,\n    rstate=RandomState(123)\n)\n\nprint(best)\n100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 10\/10 [51:31<00:00, 307.29s\/it, best loss: 0.009103421834351715]\n{'l2_leaf_reg': 2.0, 'learning_rate': 0.03375590702146598}\n\"\"\"\n\n# 3000 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0439, 10 eval-\u043e\u0432\n# {'l2_leaf_reg': 2.0, 'learning_rate': 0.03375590702146598}\n# [51:31<00:00, 307.29s\/it, best loss: 0.009103421834351715]\n# (0.2511933302)\/(0.2562225371)\n\n# y_lag\n# (0.2511000059)\/(0.2530664897)  \n# \u0414\u043b\u044f \u0442\u0435\u0441\u0442\u0430 - \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0431\u0435\u0437 y_lag,\n# \u041f\u043e\u0434\u0442\u044f\u0433\u0438\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0439 \u0438 \u043f\u043e\u0434\u0442\u044f\u0433\u0438\u0432\u0430\u043d\u0438\u0435 \u0438\u0445 \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043b\u0430\u0433\u043e\u0432\n# \u041d\u0435\u0437\u043d\u0430\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0439 \u0432\u043a\u043b\u0430\u0434, \u043c\u043e\u0436\u043d\u043e \u0438\u0441\u043a\u043b\u044e\u0447\u0438\u0442\u044c.\n\n# iterations 4000>6000\n# (0.2511883717)\/(0.2562225371) -\u043d\u0430 5916\/3277 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n\n# \u0423\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u0442\u0430 \u0442\u043e, \u043a\u0430\u043a\u0438\u0435 \u0435\u0449\u0435 \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u044b \u0432\u0430\u043b\u043a\u043e\u0432 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043b\u0438\u0441\u044c \u043f\u0440\u0438 \u044d\u0442\u043e\u043c \u0432\u0430\u043b\u043a\u0435\n# (0.2524229315)\/(0.2532975342)\n\n# \u041f\u0440\u0443\u043d\u0438\u043d\u0433 \u0444\u0430\u043a\u0442\u043e\u0440\u043e\u0432\n\"\"\"\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 10_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 104_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 106_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 107_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 15_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 28_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 29_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 31_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 37_time\n\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 40_time\n\"\"\"\n# (0.2508956729)\/(0.2545026402)\ncategorical_features_indices = [0, 1, 2, 5]\n# \u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u0431\u044b\u043b\u0438 \u043e\u0442\u043e\u0431\u0440\u0430\u043d\u044b \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e hyperopt\nparams = {\n    'iterations': 5000,\n    'learning_rate': 0.03375590702146598,\n    'l2_leaf_reg': 2.0,\n    'loss_function': 'RMSE',\n    'eval_metric': 'RMSE',\n    'ignored_features':['y',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 10_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 104_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 106_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 107_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 15_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 28_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 29_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 31_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 37_time',\n                        '\u041c\u0430\u0440\u043a\u0430 \u0441\u0442\u0430\u043b\u0438 40_time',]}\n\ncatb = CatBoostRegressor(**params)\ntrain_pool = Pool(X_q1nohe, y_q1, \n                  cat_features=categorical_features_indices)\nvalidate_pool = Pool(X_q2nohe, y_q2, \n                     cat_features=categorical_features_indices)\ncatb.fit(train_pool, eval_set=validate_pool)\nd1 = dict()\nfor n, imp in zip(catb.feature_names_, catb.feature_importances_):\n    d1.update({n:imp})\n    print(n, imp)\ndf_d1 = pd.DataFrame([d1]).T\ndf_d1 = df_d1.sort_values(ascending=False, by=0)\n# Top-30 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\nfig = plt.figure(figsize = (10, 8))\nxs = [i for i in range(30)]\nplt.bar(xs, df_d1[0].values.tolist()[:30])\nplt.xticks(xs, df_d1.index.tolist()[:30], rotation=90)\nplt.show()\ntrain_pool = Pool(X_q2nohe, y_q2, \n                  cat_features=categorical_features_indices)\nvalidate_pool = Pool(X_q3nohe, y_q3, \n                     cat_features=categorical_features_indices)\ncatb.fit(train_pool, eval_set=validate_pool)\nd2 = dict()\nfor n, imp in zip(catb.feature_names_, catb.feature_importances_):\n    d2.update({n:imp})\n    print(n, imp)\ndf_d2 = pd.DataFrame([d2]).T\ndf_d2 = df_d2.sort_values(ascending=False, by=0)\n# Top-30 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\nfig = plt.figure(figsize = (10, 8))\nxs = [i for i in range(30)]\nplt.bar(xs, df_d2[0].values.tolist()[:30])\nplt.xticks(xs, df_d2.index.tolist()[:30], rotation=90)\nplt.show()\n# \u0414\u043b\u044f \u0441\u0430\u0431\u043c\u0438\u0442\u0430 \u0438\u0449\u0435\u043c best_model \u0441 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0433\u043e \u043e\u0442\u0440\u0435\u0437\u043a\u0430 \u043f\u043e 4 \u043a\u0432\u0430\u0440\u0442\u0430\u043b\u0443\nbest_model_params = params.copy()\nbest_model_params.update({'use_best_model': True})\n\nbest_model = CatBoostRegressor(**best_model_params)\ntrain_to_kaggle_pool = Pool(zavalki_to_catboost, zavalki_to_catboost['y'],\n                            cat_features=categorical_features_indices)\n\nvalidate_pool_to_kaggle = Pool(X_q4_small_val, y_q4_small_val, \n                               cat_features=categorical_features_indices)\n\nbest_model.fit(train_to_kaggle_pool, eval_set=validate_pool_to_kaggle)\n# \u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u043d\u0435 \u0443\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u043c\u0443\u044e \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e y \u0432 \u0442\u0440\u0435\u0439\u043d\u0435\ntest_to_catboost['y'] = 0\ntest_to_catboost_for_pred = test_to_catboost[zavalki_to_catboost.columns.tolist()]\npreds_catb = best_model.predict(test_to_catboost_for_pred)\noutput = pd.DataFrame({'id':test_to_catboost['id'].values,\n                       'iznos':preds_catb})\noutput['iznos'].hist()\nplt.show()\n#output.to_csv('submit_output.csv', index=False)\noutput.head(10)","meta":"{'source': 'AI4Code', 'id': 'a83d3b11077a8e'}"}
{"id":"51603","text":"\"\"\"\n# Tabularize Data\n\nConvert from json to a flattened table.\n\nI wrote this before learning about:\n\n    from pandas.io.json import json_normalize\n    \nbut it works (though slow)\n\nPublished because results needed for next script to be published when I fix some bugs. If you're doing it yourself, you'll probably prefer json_normalize.\n\"\"\"\n\"\"\"\n## Imports\n\"\"\"\nimport pandas as pd\nx=pd;print(x.__name__, \"version:\", x.__version__)\nimport numpy as np\nx=np;print(x.__name__, \"version:\", x.__version__)\nimport matplotlib\nimport matplotlib.pyplot as plt\nx=matplotlib;print(x.__name__, \"version:\", x.__version__)\nimport seaborn as sns\nx=sns;print(x.__name__, \"version:\", x.__version__)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import linear_model, kernel_ridge, cluster, model_selection\nimport os, sys, math, datetime, shutil, pickle, itertools, json\nfrom IPython.core.interactiveshell import InteractiveShell\n\"\"\"\n## Settings\n\"\"\"\nInteractiveShell.ast_node_interactivity = \"all\" # this causes all lines of a notebook cell to show output, not just last line\n%matplotlib inline\npd.set_option('display.max_columns', 100) #default of 10 columns is just too small to see much\npd.set_option('display.max_rows', 10)\nplt.style.use('seaborn-poster') #makes the graphs bigger; important for my 4K monitor\nsns.set(palette='deep')\nsns.set(context='poster')\n\"\"\"\n## Load the data\n\"\"\"\ninput_prefix = '..\/input\/'\nval_prefix = '.\/val_'\noutput_prefix = '.\/'\n\nid = \"fullVisitorId\"\ndf_train = pd.read_csv(input_prefix + \"train.csv\", index_col=id, dtype={id:str})\ndf_test = pd.read_csv(input_prefix + \"test.csv\", index_col=id, dtype={id:str})\n\"\"\"\n## Remove trivial (constant) columns\n\"\"\"\njson_cols = ['device', 'geoNetwork', 'totals', 'trafficSource']#from inspection of data\n\nother_cols = list(set(df_train.columns).union(set(df_test.columns)) - set(json_cols))# all columns except json columns\nfor col in other_cols:\n    if len(set(df_train[col].unique()).union(set(df_test[col].unique()))) <= 1:# if all values are the same value, the column is not needed\n        val = df_train[col].iloc[0]\n        del df_train[col]\n        del df_test[col]\n        print(\"Removing trivial column: %r with unique value: %r\" % (col, val))\n\"\"\"\n## Split json columns into separate fields\n\nBy inspection, the columns 'device', 'geoNetwork', 'totals', 'trafficSource' of each row are json strings that we need to split into columns.\n\nIt appears not all json records of a column have the same keys, so some random sampling is done.  To do it right, use:\n    from pandas.io.json import json_normalize -- this \"seems\" to get them all (I had done multiple runs with larger samples and put keys found by them in by hand).\n\nRemove any trivial columns that were just added.\n\nAnd repeat till all json data is flattened recursively.\n\n\"\"\"\n#just for reproduceability\nnp.random.seed(2718281828)\n\ncolumns = json_cols #start processing with the json_columns known by inspection\nwhile len(columns) > 0: #while there are json columns left to process\n    additional_json_cols = []#if a newly-generated column is itself a json column (from nesting), we need to process it the same way\n    for col in columns:\n        print(\"Getting keys for column:\", col)\n        print(\"  Train column from string to dict:\", col)\n        d = df_train[col].apply(json.loads)#get the dicts of all entries (strings) of this column\n        print(\"  Test column from string to dict:\", col)\n        t = df_test[col].apply(json.loads)\n\n        print(\"  Union of %s train col keys:\" % len(d), col)\n        keys = {x for x in d[0]}# try to find all keys, considering that keys may be missing in some rows\n        if col == 'totals':\n            #make sure we don't miss this one!  It is the target.\n            keys.add('transactionRevenue')\n            #add keys found in previous run\n            keys = keys.union({'newVisits', 'bounces', 'transactionRevenue', 'pageviews', 'visits', 'hits'})\n        elif col == 'device':\n            #add keys found in previous run\n            keys = keys.union({'mobileInputSelector', 'mobileDeviceMarketingName', 'browserVersion', 'mobileDeviceModel', 'flashVersion', 'language', 'screenResolution', 'operatingSystem', 'mobileDeviceBranding', \n                               'browser', 'browserSize', 'isMobile', 'deviceCategory', 'operatingSystemVersion', 'mobileDeviceInfo', 'screenColors'})\n        elif col == 'geoNetwork':\n            #add keys found in previous run\n            keys = keys.union({'cityId', 'longitude', 'networkLocation', 'latitude', 'country', 'metro', 'networkDomain', 'region', 'city', 'continent', 'subContinent'})\n        elif col == 'trafficSource':\n            #add keys found in previous run\n            keys = keys.union({'isTrueDirect', 'medium', 'source', 'adwordsClickInfo', 'campaign', 'adContent', 'keyword', 'referralPath'})\n        elif col == 'trafficSource_adwordsClickInfo':\n            #add keys found in previous run\n            keys = keys.union({'slot', 'gclId', 'targetingCriteria', 'isVideoAd', 'criteriaParameters', 'page', 'adNetworkType'})\n\n        #random samples to make sure we got all the keys\n        samples = np.random.randint(1, len(d) - 1, 1000)#increase this to ensure getting all keys\n        if col == 'totals' or col == 'trafficSource' or col == 'trafficSource_adwordsClickInfo':\n            samples = np.random.randint(1, len(d) - 1, 5000)#increase this to ensure getting all keys\n        count = 0\n        for i in samples:\n            count += 1\n            if count % 20000 == 0:\n                print(\"    rows processed:\", i)\n            if len(keys) != len(d[i]):#may have missing keys to add\n                old_keys = keys\n                keys = keys.union({x for x in d[i]})\n                if len(keys - old_keys) > 0:\n                    print(\"%s new keys added\" % len(keys - old_keys))\n            else:\n                for x in d[i]:\n                    if x not in keys:#definitely have missing keys to add\n                        old_keys = keys\n                        keys = keys.union({x for x in d[i]})\n                        print(\"%s new keys added\" % len(keys - old_keys))\n                        break\n\n        print(\"  Union of %s test col keys:\" % len(t), col)\n        count = 0\n        for i in np.random.randint(1, len(t) - 1, 100):#increase this to ensure getting all keys\n            count += 1\n            if count % 20000 == 0:\n                print(\"    rows processed:\", i)\n            if len(keys) != len(t[i]):\n                old_keys = keys\n                keys = keys.union({x for x in t[i]})\n                if len(keys - old_keys) > 0:\n                    print(\"%s new keys added\" % len(keys - old_keys))\n            else:\n                for x in t[i]:\n                    if x not in keys:\n                        old_keys = keys\n                        keys = keys.union({x for x in t[i]})\n                        print(\"%s new keys added\" % len(keys - old_keys))\n                        break\n\n        print(\"Found %s keys for train\/test column %s; replacing with keyed columns; keys = %r\" % (len(keys), col, keys))\n        keylist = list(keys)\n        keylist.sort() #for reproduceability\n        \n        for key in keylist:#now, add new fields of type column_key and delete the original column.  For missing values, use 'XNA' string; this will be replaced with something better on a column-by-column basis in the next script\n            new_field = col + \"_\" + key\n            df_train[new_field] = d.apply(lambda x:x.get(key, 'XNA'))#use 'XNA' string for missing values\n            df_test[new_field] = t.apply(lambda x:x.get(key, 'XNA'))\n\n            #some json structures have extra recursive depth; make value into a string and re-process\n            try:\n                l = len(set(df_train[new_field].unique()).union(set(df_test[new_field].unique())))# l==1 means column is trivial\n            except TypeError: # most likely: found a dict as a value, which \"unique\" doesn't like, so need to recurse\n                def to_str(x):\n                    if isinstance(x, dict):\n                        return json.dumps(x)\n                    else:\n                        return json.dumps(dict())\n                print(\"Recursively processing new column:\", new_field)\n                df_train[new_field] = df_train[new_field].apply(to_str)#convert to string first\n                df_test[new_field] = df_test[new_field].apply(to_str)\n                additional_json_cols.append(new_field)#add to columns that need to be processed again\n                l = len(set(df_train[new_field].unique()).union(set(df_test[new_field].unique())))\n\n            #make sure the column isn't trivial (just one constant value)\n            if l <= 1:\n                val = df_train[new_field].iloc[0]\n                del df_train[new_field]\n                del df_test[new_field]\n                if new_field in additional_json_cols:\n                    additional_json_cols.remove(new_field)\n                print(\"Removing trivial column: %r with unique value: %r\" % (new_field, val))\n        del df_train[col]\n        del df_test[col]\n    columns = additional_json_cols\n\"\"\"\n## Check for columns that, looked at as categorical, have the same values with perhaps different labels.\nThis can find false positives, e.g. if you have a column \"value\" and a column \"log_value\" that is the logarithm of the first, they will be found to be equivalent.  So in real life, secondary testing is needed.\n\nBut for this data, it finds none so I skipped the secondary testing.\n\"\"\"\n#check for equivalent columns \n\nequivalent_columns = set()\nfor i in range(len(df_train.columns)):\n    for j in range(i):\n        col_i = df_train.columns[i]\n        col_j = df_train.columns[j]\n        if (df_train[col_i].factorize()[0] == df_train[col_j].factorize()[0]).all():\n            found = False\n            for x in equivalent_columns:\n                if col_i in x or col_j in x:\n                    x.add(col_i)\n                    x.add(col_j)\n                    found = True\n                    break\n            if not found:\n                equivalent_columns.add({col_i, col_j})\n\nequivalent_columns#possibly-equivalent columns\n\"\"\"\n## The cleaned and tabularized data saved here (zipped, makes it save\/load faster and use less disk space)\n'XNA' used for nulls, but that is handled in the next script, to be published when some bugs are zapped.\n\"\"\"\ndf_train.to_csv(output_prefix + \"train_clean.csv.zip\", compression='zip')\ndf_test.to_csv(output_prefix + \"test_clean.csv.zip\", compression='zip')\n\"\"\"\n## Create a validation set for local scoring by splitting by visitStartTime\n\"\"\"\nsplit = int(df_train[['visitStartTime']].describe().loc['75%', 'visitStartTime'])\ndf_valtrain = df_train[df_train['visitStartTime'] < split]\ndf_valtest = df_train[df_train['visitStartTime'] >= split]\ndf_valtrain.to_csv(val_prefix + \"train_clean.csv.zip\", compression='zip')\ndf_valtest.to_csv(val_prefix + \"test_clean.csv.zip\", compression='zip')","meta":"{'source': 'AI4Code', 'id': '5ef70db4f9cb1e'}"}
{"id":"81077","text":"\"\"\"\nAfter some discussions in this [thread](https:\/\/www.kaggle.com\/c\/rsna-miccai-brain-tumor-radiogenomic-classification\/discussion\/275233) whether OOF or CV is better, I want to clarify some points by looking at the results empirically:\n\n- CV AUC gives a better bias estimate than OOF AUC (in particular for high K)\n- the high std can be explained by the bias-variance tradeoff\n\n\n\"\"\"\n\"\"\"\n# Regular 5 and 200-fold CV\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import log_loss\nimport numpy as np\nimport pandas as pd\n\nX = pd.read_csv(\"..\/input\/leak-in-metadata\/X_train.csv\", usecols=['T2w_Percent Phase Field of View',\n                                        'FLAIR_Echo Train Length',\n                                        'T2w_shape',\n                                        'target'])\nX.fillna(0, inplace=True)\ny = X[\"target\"].values\nX.drop(\"target\", axis=1, inplace=True)\nX = X.values\n\no = []\no2 = []\nfor fold, (train_index, val_index) in enumerate(StratifiedKFold(n_splits=200).split(X, y)):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    regr = LogisticRegression()\n    regr.fit(X_train, y_train)\n    \n    y_pred = regr.predict_proba(X_val)[...,1]\n    \n    auc = roc_auc_score(y_val, y_pred)\n    val_loss = log_loss(y_val, y_pred)\n    \n    o.append(auc)\n    o2.append(val_loss)\n\nprint(\"Loss\", np.mean(o2), np.std(o2))\nprint(\"AUC\", np.mean(o), np.std(o))\n\"\"\"\nWe can see that the standard deviation is extremely high. However, this is not surprising by the [bias-variance-tradeoff](https:\/\/stats.stackexchange.com\/questions\/61783\/bias-and-variance-in-leave-one-out-vs-k-fold-cross-validation). Even the proper scoring rule log loss is affected by the high number of folds. Let us reduce the folds to 5.\n\"\"\"\no = []\no2 = []\nfor fold, (train_index, val_index) in enumerate(StratifiedKFold(n_splits=5).split(X, y)):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    regr = LogisticRegression()\n    regr.fit(X_train, y_train)\n    \n    y_pred = regr.predict_proba(X_val)[...,1]\n    \n    auc = roc_auc_score(y_val, y_pred)\n    val_loss = log_loss(y_val, y_pred)\n    \n    o.append(auc)\n    o2.append(val_loss)\n\nprint(\"Loss\", np.mean(o2), np.std(o2))\nprint(\"AUC\", np.mean(o), np.std(o))\n\"\"\"\nThe standard deviation is closer to the true standard deviation. However, we increased the bias. The AUC has decreased to 0.57.\n\"\"\"\n\"\"\"\n# OOF 5 and 200-fold CV\n\"\"\"\noof_score = np.zeros((X.shape[0],))\nfor fold, (train_index, val_index) in enumerate(StratifiedKFold(n_splits=200).split(X, y)):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    regr = LogisticRegression()\n    regr.fit(X_train, y_train)\n    \n    y_pred = regr.predict_proba(X_val)[...,1]\n    \n    oof_score[val_index] = y_pred\n\nprint(\"OOF Loss\", roc_auc_score(y, oof_score))\nprint(\"OOF AUC\", log_loss(y, oof_score))\n\"\"\"\nBy using OOF, we actually get a higher AUC! OOF AUC is **0.6806**, while regular CV AUC **0.6575**. Let us look at 5-fold CV again.\n\"\"\"\noof_score = np.zeros((X.shape[0],))\nfor fold, (train_index, val_index) in enumerate(StratifiedKFold(n_splits=5).split(X, y)):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    regr = LogisticRegression()\n    regr.fit(X_train, y_train)\n    \n    y_pred = regr.predict_proba(X_val)[...,1]\n    \n    oof_score[val_index] = y_pred\n\nprint(\"OOF Loss\", roc_auc_score(y, oof_score))\nprint(\"OOF AUC\", log_loss(y, oof_score))\n\"\"\"\nThe AUC has increased from 0.68 to 0.7. In contrast, the regular 5-fold CV AUC is 0.5768147135783306.\n\"\"\"\n\"\"\"\n# Train-test-split and CV\n\"\"\"\n\"\"\"\nFrom the last section, we found out that:\n- CV AUC < OOF AUC\n- By increasing the number of folds, we increase the variance\n\nNow, I want to look at the number of folds in relation to the bias of the estimator.\n\"\"\"\n\"\"\"\nThe train dataset is 78% of the total data and the test dataset is 22% of the total data. I am using 60 folds because the dataset is too small.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\nFOLDS = 60\n\nX = pd.read_csv(\"..\/input\/leak-in-metadata\/X_train.csv\", usecols=['T2w_Percent Phase Field of View',\n                                        'FLAIR_Echo Train Length',\n                                        'T2w_shape',\n                                        'target'])\nX.fillna(0, inplace=True)\ny = X[\"target\"].values\nX.drop(\"target\", axis=1, inplace=True)\nX = X.values\n\nX, X_test, y, y_test = train_test_split(X, y, test_size=0.78,\n                                        train_size=0.22, random_state=3,\n                                        shuffle=True, stratify=y)\nprint(\"train\", X.shape, \"test\", X_test.shape)\n\navg_auc_shape = []\nroc = []\nloss = []\nskf = StratifiedKFold(n_splits=FOLDS, random_state=None, shuffle=False)\noof = np.zeros((X.shape[0],), dtype=np.float64)\ny_pred_test = np.zeros((y_test.shape[0],), dtype=np.float64)\nfor train_index, val_index in tqdm(skf.split(X, y), total=FOLDS):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    model = LogisticRegression()\n    model.fit(X_train, y_train)\n\n    y_pred = model.predict_proba(X_val)[...,1]\n\n    y_pred_test += model.predict_proba(X_test)[...,1] \/ FOLDS\n\n    oof[val_index] = y_pred\n\n    roc.append(roc_auc_score(y_val, y_pred))\n    loss.append(log_loss(y_val, y_pred))\n    avg_auc_shape.append(y_val.shape[0])\n\nprint(\"Each AUC was computed on\", np.mean(avg_auc_shape), \"samples\")\nprint(\"CV AUC\", np.mean(roc), np.std(roc))\nprint(\"CV loss\", np.mean(loss), np.std(loss))\nprint()\nprint(\"OOF AUC\", roc_auc_score(y, oof))\nprint(\"OOF loss\", log_loss(y, oof))\nprint()\nprint(\"AUC test\", roc_auc_score(y_test, y_pred_test))\nprint(\"Loss test\", log_loss(y_test, y_pred_test))\n\"\"\"\nThis time we see that OOF AUC < AUC but the regular CV AUC is much closer to the test dataset. Again the estimation of the variance is wrong.\n\nLet us reduce the number of folds to 5.\n\"\"\"\nFOLDS = 5\n\navg_auc_shape = []\nroc = []\nloss = []\nskf = StratifiedKFold(n_splits=FOLDS, random_state=None, shuffle=False)\noof = np.zeros((X.shape[0],), dtype=np.float64)\ny_pred_test = np.zeros((y_test.shape[0],), dtype=np.float64)\nfor train_index, val_index in tqdm(skf.split(X, y), total=FOLDS):\n    X_train, X_val = X[train_index], X[val_index]\n    y_train, y_val = y[train_index], y[val_index]\n\n    model = LogisticRegression()\n    model.fit(X_train, y_train)\n\n    y_pred = model.predict_proba(X_val)[...,1]\n\n    y_pred_test += model.predict_proba(X_test)[...,1] \/ FOLDS\n\n    oof[val_index] = y_pred\n\n    roc.append(roc_auc_score(y_val, y_pred))\n    loss.append(log_loss(y_val, y_pred))\n    avg_auc_shape.append(y_val.shape[0])\n\nprint(\"Each AUC was computed on\", np.mean(avg_auc_shape), \"samples\")\nprint(\"CV AUC\", np.mean(roc), np.std(roc))\nprint(\"CV loss\", np.mean(loss), np.std(loss))\nprint()\nprint(\"OOF AUC\", roc_auc_score(y, oof))\nprint(\"OOF loss\", log_loss(y, oof))\nprint()\nprint(\"AUC test\", roc_auc_score(y_test, y_pred_test))\nprint(\"Loss test\", log_loss(y_test, y_pred_test))\n\"\"\"\nWe have a better estimation of the standard deviation by reducing the number of folds (bias-variance tradeoff). 0.522 + 0.0622 = 0.5842 which is quite close to 0.5756.\n\nHowever, the bias is again too high. Note that OOF AUC > CV AUC.\n\"\"\"\n\"\"\"\n# Distribution\n\"\"\"\n\"\"\"\nIn the last section, we only considered one dataset by using train_test_split with 1 seed. However, this is only one particular instance of the dataset. In the next experiment, we sample 300 datasets from the whole dataset distribution to get a better estimate of the CV.\n\nWe use 60 folds again.\n\"\"\"\nFOLDS = 60\n\navg_auc_shape = []\ncv_auc = []\ncv_loss = []\n\noof_auc = []\noof_loss = []\n\ntest_auc = []\ntest_loss = []\nfor i in tqdm(range(300)):\n    X = pd.read_csv(\"..\/input\/leak-in-metadata\/X_train.csv\", usecols=['T2w_Percent Phase Field of View',\n                                            'FLAIR_Echo Train Length',\n                                            'T2w_shape',\n                                            'target'])\n    X.fillna(0, inplace=True)\n    y = X[\"target\"].values\n    X.drop(\"target\", axis=1, inplace=True)\n    X = X.values\n\n    X, X_test, y, y_test = train_test_split(X, y, test_size=0.78,\n                                            train_size=0.22, random_state=i,\n                                            shuffle=True, stratify=y)\n    #print(\"train\", X.shape, \"test\", X_test.shape)\n\n    skf = StratifiedKFold(n_splits=FOLDS, random_state=None, shuffle=False)\n    oof = np.zeros((X.shape[0],), dtype=np.float64)\n    y_pred_test = np.zeros((y_test.shape[0],), dtype=np.float64)\n    for train_index, val_index in skf.split(X, y):\n        X_train, X_val = X[train_index], X[val_index]\n        y_train, y_val = y[train_index], y[val_index]\n\n        model = LogisticRegression()\n        model.fit(X_train, y_train)\n\n        y_pred = model.predict_proba(X_val)[...,1]\n\n        y_pred_test += model.predict_proba(X_test)[...,1] \/ FOLDS\n\n        oof[val_index] = y_pred\n\n        cv_auc.append(roc_auc_score(y_val, y_pred))\n        cv_loss.append(log_loss(y_val, y_pred))\n        avg_auc_shape.append(y_val.shape[0])\n    \n    oof_auc.append(roc_auc_score(y, oof))\n    oof_loss.append(log_loss(y, oof))\n    \n    test_auc.append(roc_auc_score(y_test, y_pred_test))\n    test_loss.append(log_loss(y_test, y_pred_test))\n\nprint(\"Each AUC was computed on\", np.mean(avg_auc_shape), \"samples\")\nprint(\"CV AUC\", np.mean(cv_auc), np.std(cv_auc))\nprint(\"CV loss\", np.mean(cv_loss), np.std(cv_loss))\nprint()\nprint(\"OOF AUC\", np.mean(oof_auc))\nprint(\"OOF loss\", np.mean(oof_loss))\nprint()\nprint(\"AUC test\", np.mean(test_auc))\nprint(\"Loss test\", np.mean(test_loss))\n\"\"\"\nAgain we see that CV AUC is closer to AUC test than OOF AUC. Next, we test the results with 5 folds.\n\"\"\"\nFOLDS = 5\n\navg_auc_shape = []\ncv_auc = []\ncv_loss = []\n\noof_auc = []\noof_loss = []\n\ntest_auc = []\ntest_loss = []\nfor i in tqdm(range(300)):\n    X = pd.read_csv(\"..\/input\/leak-in-metadata\/X_train.csv\", usecols=['T2w_Percent Phase Field of View',\n                                            'FLAIR_Echo Train Length',\n                                            'T2w_shape',\n                                            'target'])\n    X.fillna(0, inplace=True)\n    y = X[\"target\"].values\n    X.drop(\"target\", axis=1, inplace=True)\n    X = X.values\n\n    X, X_test, y, y_test = train_test_split(X, y, test_size=0.78,\n                                            train_size=0.22, random_state=i,\n                                            shuffle=True, stratify=y)\n    #print(\"train\", X.shape, \"test\", X_test.shape)\n\n    skf = StratifiedKFold(n_splits=FOLDS, random_state=None, shuffle=False)\n    oof = np.zeros((X.shape[0],), dtype=np.float64)\n    y_pred_test = np.zeros((y_test.shape[0],), dtype=np.float64)\n    for train_index, val_index in skf.split(X, y):\n        X_train, X_val = X[train_index], X[val_index]\n        y_train, y_val = y[train_index], y[val_index]\n\n        model = LogisticRegression()\n        model.fit(X_train, y_train)\n\n        y_pred = model.predict_proba(X_val)[...,1]\n\n        y_pred_test += model.predict_proba(X_test)[...,1] \/ FOLDS\n\n        oof[val_index] = y_pred\n\n        cv_auc.append(roc_auc_score(y_val, y_pred))\n        cv_loss.append(log_loss(y_val, y_pred))\n        avg_auc_shape.append(y_val.shape[0])\n    \n    oof_auc.append(roc_auc_score(y, oof))\n    oof_loss.append(log_loss(y, oof))\n    \n    test_auc.append(roc_auc_score(y_test, y_pred_test))\n    test_loss.append(log_loss(y_test, y_pred_test))\n\nprint(\"Each AUC was computed on\", np.mean(avg_auc_shape), \"samples\")\nprint(\"CV AUC\", np.mean(cv_auc), np.std(cv_auc))\nprint(\"CV loss\", np.mean(cv_loss), np.std(cv_loss))\nprint()\nprint(\"OOF AUC\", np.mean(oof_auc))\nprint(\"OOF loss\", np.mean(oof_loss))\nprint()\nprint(\"AUC test\", np.mean(test_auc))\nprint(\"Loss test\", np.mean(test_loss))\n\"\"\"\nBefore we saw a strong effect on the bias. This time the effect is not as strong. For 60-fold CV we had 0.575583, here we have 0.57384. AUC test is 0.57694. Then |0.575583 - 0.57694| = 0.001357 (60-fold) and |0.57384 - 0.57694| = 0.0031 (5-fold CV). Hence, 60-fold CV is closer to AUC test.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '94d5fea8614e69'}"}
{"id":"51506","text":"\"\"\"\nYes, linear stacking of GBDT and NN! A Promised Method:)\n\"\"\"\n\"\"\"\n# Libraries\n\"\"\"\n# 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)\nfrom sklearn import decomposition\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, QuantileTransformer\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import KFold\nfrom tqdm.auto import tqdm\nfrom sklearn import linear_model\nimport xgboost as xgb\nimport operator\nimport lightgbm as lgb\nfrom catboost import CatBoostRegressor, CatBoostClassifier\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\n# visualize\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport seaborn as sns\nfrom matplotlib import pyplot\nfrom matplotlib.ticker import ScalarFormatter\nsns.set_context(\"talk\")\nstyle.use('seaborn-colorblind')\n\nimport os\n# for dirname, _, filenames in os.walk('\/kaggle\/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\nimport warnings\nwarnings.filterwarnings('ignore')\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\n\"\"\"\n# Config\n\"\"\"\nSEED = 42\nNFOLD = 10\n\"\"\"\n# Load data\n\"\"\"\ntrain = pd.read_csv('..\/input\/tabular-playground-series-jan-2021\/train.csv')\ntest = pd.read_csv('..\/input\/tabular-playground-series-jan-2021\/test.csv')\n\nfeatures = [f'cont{i}' for i in range(1, 15)]\ntarget_col = 'target'\n\nX_train = train.drop(['id', 'target'], axis=1)\ny_train = train['target']\nX_test = test.drop('id', axis=1)\nprint(X_train.shape)\nX_train.head()\nprint(X_test.shape)\nX_test.head()\n\"\"\"\n# Target\nNormal?\n\"\"\"\ny_train.hist()\n\"\"\"\n# GBDT\n\"\"\"\nxgb_params = {\n    'colsample_bytree': 0.4,                 \n    'learning_rate': 0.01,\n    'max_depth': 7,\n    'subsample': 1,\n    'min_child_weight': 4,\n    'gamma': 0.24,\n    'alpha': 1,\n    'lambda': 1,\n    'seed': SEED,\n    'n_estimators': 800,\n    'objective': 'reg:squarederror',\n    'eval_metric': 'rmse',\n}\n\nlgb_params = {\n    'num_leaves': 512,\n    'objective': 'regression',\n    'boosting_type': 'gbdt',\n    'max_depth': 12,\n    'learning_rate': 0.01,\n    'subsample': 0.72,\n    'subsample_freq': 4,\n    'feature_fraction': 0.6,\n    'lambda_l1': 1,\n    'lambda_l2': 1,\n    'seed': SEED,\n    'early_stopping_rounds': 80,\n    'metric': 'rmse'\n    \n}\n\ncatb_params = { \n    'task_type': \"CPU\",\n    'learning_rate': 0.01, \n    'iterations': 1200,\n    'colsample_bylevel': 0.5,\n    'random_seed': SEED,\n    'use_best_model': True,\n    'early_stopping_rounds': 80,\n    'loss_function': 'RMSE',\n    'eval_metric': 'RMSE'\n}\n            \ndef fit_gbdt(params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='xgb'):\n    cv = KFold(n_splits=n_fold, shuffle=True, random_state=seed)\n\n    models = []\n    oof_train = np.zeros((len(X_train),))\n    y_preds = np.zeros((len(X_test),))\n    \n    # feature importance\n    fi_df = pd.DataFrame()\n    fi_df['features'] = features\n\n    for fold_id, (train_index, valid_index) in tqdm(enumerate(cv.split(X_train, y_train))):\n        # split\n        X_tr = X_train.loc[train_index, features]\n        X_val = X_train.loc[valid_index, features]\n        y_tr = y_train.loc[train_index].values\n        y_val = y_train.loc[valid_index].values\n        \n        # model\n        if modelname == 'xgb':\n            model = xgb.XGBRegressor(**params)\n            model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)],\n                        early_stopping_rounds=40, verbose=100)\n\n            # feature importance\n            importance = model.get_booster().get_score(importance_type='gain')\n            importance = sorted(importance.items(), key=operator.itemgetter(1))\n            importance = pd.DataFrame(importance, columns=['features', f'importance_cv{fold_id}'])\n            fi_df = fi_df.merge(importance, how='left', on='features')\n            \n        elif modelname == 'lgb':\n            model = lgb.LGBMRegressor(**params)\n            model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)],\n                verbose=-1, categorical_feature=[])\n            fi_df[f'importance_cv{fold_id}'] = model.booster_.feature_importance(importance_type=\"gain\")\n            \n        elif modelname == 'catb':\n            model = CatBoostRegressor(**params)\n            model.fit(X_tr, y_tr, eval_set=(X_val, y_val),\n                verbose=100, cat_features=[])     \n            fi_df[f'importance_cv{fold_id}'] = model.get_feature_importance()       \n\n        # predict\n        oof_train[valid_index] = model.predict(X_val)\n        y_pred = model.predict(X_test[features])\n        y_preds += y_pred \/ n_fold\n        models.append(model)\n        \n    return oof_train, y_preds, models, fi_df\n\"\"\"\n## XGB\n\"\"\"\noof_train_xgb, y_preds_xgb, xgb_models, fi_df = fit_gbdt(xgb_params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='xgb')\nfi_df['importance_mean'] = fi_df.values[:, 1:].mean(axis=1)\nsns.barplot(x='importance_mean', y='features', data=fi_df.sort_values(by='importance_mean', ascending=False))\n\"\"\"\n## LGB\n\"\"\"\noof_train_lgb, y_preds_lgb, lgb_models, fi_df = fit_gbdt(lgb_params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='lgb')\nfi_df['importance_mean'] = fi_df.values[:, 1:].mean(axis=1)\nsns.barplot(x='importance_mean', y='features', data=fi_df.sort_values(by='importance_mean', ascending=False))\n\"\"\"\n## CatB\n\"\"\"\noof_train_catb, y_preds_catb, catb_models, fi_df = fit_gbdt(catb_params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='catb')\nfi_df['importance_mean'] = fi_df.values[:, 1:].mean(axis=1)\nsns.barplot(x='importance_mean', y='features', data=fi_df.sort_values(by='importance_mean', ascending=False))\n\"\"\"\n# GBDT scores\n\"\"\"\nprint(f'CV (XGB): {mean_squared_error(y_train, oof_train_xgb, squared=False)}')\nprint(f'CV (LGB): {mean_squared_error(y_train, oof_train_lgb, squared=False)}')\nprint(f'CV (CATB): {mean_squared_error(y_train, oof_train_catb, squared=False)}')\n\"\"\"\n# NN\nWe use a simple MLP!\n\"\"\"\n\"\"\"\n## Scaling\nTo make sure similar range across features\n\"\"\"\nprep = StandardScaler()\ndf = pd.concat([X_train[features], X_test[features]])\ndf[features] = prep.fit_transform(df[features].values)\nX_test[features] = df[features].iloc[len(train):]\nX_train[features] = df[features].iloc[:len(train)]\nprint(X_train.shape)\nX_train.head()\nprint(X_test.shape)\nX_test.head()\n\"\"\"\n## MLP\n\"\"\"\nimport math\nimport random\nfrom typing import List, NoReturn, Union, Tuple, Optional, Text, Generic, Callable, Dict\n\n# tf keras\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\ndef seed_everything(seed : int):    \n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    tf.random.set_seed(seed)\n\nseed_everything(SEED)    \n\n# adapted from https:\/\/github.com\/ghmagazine\/kagglebook\/blob\/master\/ch06\/ch06-03-hopt_nn.py\nparams = {\n    'input_dropout': 0.0,\n    'hidden_layers': 3,\n    'hidden_units': 128,\n    'hidden_activation': 'relu',\n    'dropout': 0.2,\n    'lr': 1e-2,\n    'batch_size': 128,\n    'epochs': 196\n}\n    \ndef nn_model(params, L):\n    \"\"\"\n    NN hyperparameters and models\n    \n    :INPUT: \n    \n    :L: the number of features (int)\n    \"\"\"\n\n    # NN model architecture\n    n_neuron = params['hidden_units']\n\n    inputs = tf.keras.layers.Input(shape=(L, ))\n    \n    x = tf.keras.layers.Dense(n_neuron, activation=params['hidden_activation'])(inputs)\n    x = tf.keras.layers.Dropout(params['dropout'])(x)\n\n    # stack more layers\n    for i in np.arange(params['hidden_layers'] - 1):\n        x = tf.keras.layers.Dense(n_neuron \/\/ (2 * (i+1)), activation=params['hidden_activation'])(x)\n        x = tf.keras.layers.Dropout(params['dropout'])(x)\n        \n    # output\n    out1 = tf.keras.layers.Dense(1, activation='linear', name = 'out1')(x)\n    model = tf.keras.models.Model(inputs=inputs, outputs=out1)\n\n    # compile\n    loss = 'mse'\n    opt = tfa.optimizers.RectifiedAdam(lr=params['lr'])\n    model.compile(loss=loss, optimizer=opt, metrics=[tf.keras.metrics.RootMeanSquaredError()])\n    \n    return model\n\nmodel = nn_model(params, len(features))\nmodel.summary()\n\"\"\"\n## 1DCNN\nInspired from https:\/\/www.kaggle.com\/sishihara\/1dcnn-for-tabular-from-moa-2nd-place\n\nMake sure you upvote the kernel.\n\"\"\"\ndef cnn_model(params, L):\n    \"\"\"\n    NN hyperparameters and models\n    \n    :INPUT: \n    \n    :L: the number of features (int)\n    \"\"\"\n\n    # NN model architecture\n    n_neuron = params['hidden_units']\n\n    inputs = tf.keras.layers.Input(shape=(L, ))\n    \n    # 1dcnn\n    x = tf.keras.layers.Dense(4096, activation=params['hidden_activation'])(inputs)\n    x = tf.keras.layers.Reshape((256, 16))(x)\n    x = tf.keras.layers.Conv1D(filters=16,\n                      kernel_size=5,\n                      strides=1,\n                      activation=params['hidden_activation'])(x)\n    x = tf.keras.layers.MaxPooling1D(pool_size=2)(x)\n    x = tf.keras.layers.Flatten()(x)\n    \n    # ffn\n    x = tf.keras.layers.Dense(n_neuron, activation=params['hidden_activation'])(x)\n    x = tf.keras.layers.Dropout(params['dropout'])(x)\n\n    # stack more layers\n    for i in np.arange(params['hidden_layers'] - 1):\n        x = tf.keras.layers.Dense(n_neuron \/\/ (2 * (i+1)), activation=params['hidden_activation'])(x)\n        x = tf.keras.layers.Dropout(params['dropout'])(x)\n        \n    # output\n    out1 = tf.keras.layers.Dense(1, activation='linear', name = 'out1')(x)\n    model = tf.keras.models.Model(inputs=inputs, outputs=out1)\n\n    # compile\n    loss = 'mse'\n    opt = tfa.optimizers.RectifiedAdam(lr=params['lr'])\n    model.compile(loss=loss, optimizer=opt, metrics=[tf.keras.metrics.RootMeanSquaredError()])\n    \n    return model\n\nmodel = cnn_model(params, len(features))\nmodel.summary()\ndef fit_model(params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='mlp'):\n    cv = KFold(n_splits=n_fold, shuffle=True, random_state=seed)\n\n    models = []\n    oof_train = np.zeros((len(X_train),))\n    y_preds = np.zeros((len(X_test),))\n\n    for fold_id, (train_index, valid_index) in tqdm(enumerate(cv.split(X_train, y_train))):\n        # split\n        X_tr = X_train.loc[train_index, features].values\n        X_val = X_train.loc[valid_index, features].values\n        y_tr = y_train.loc[train_index].values\n        y_val = y_train.loc[valid_index].values\n        \n        # model\n        tf.keras.backend.clear_session()\n        if modelname == 'mlp':\n            model = nn_model(params, len(features))\n        elif modelname == 'cnn':\n            model = cnn_model(params, len(features))\n            \n        # callbacks\n        er = tf.keras.callbacks.EarlyStopping(patience=8, restore_best_weights=True, monitor='val_loss')\n        ReduceLR = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=8, verbose=1, mode='min')\n        model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(filepath=f'mybestweight{fold_id}_{modelname}.hdf5', \n                                                              save_weights_only=True, verbose=0, monitor='val_loss', save_best_only=True)\n\n        # fit\n        history = model.fit(X_tr, y_tr, callbacks=[er, ReduceLR, model_checkpoint_callback], \n                            verbose=2, epochs=params['epochs'], batch_size=params['batch_size'],\n                            validation_data=(X_val, y_val)) \n        \n        # predict\n        oof_train[valid_index] = model.predict(X_val).ravel()\n        y_pred = model.predict(X_test[features].values).ravel()\n        y_preds += y_pred \/ n_fold\n        models.append(model)\n        \n    return oof_train, y_preds, models\noof_train_mlp, y_preds_mlp, mlp_models = fit_model(params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='mlp')\noof_train_cnn, y_preds_cnn, cnn_models = fit_model(params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED, modelname='cnn')\n\"\"\"\n# MLP score\n\"\"\"\nprint(f'CV (MLP): {mean_squared_error(y_train, oof_train_mlp, squared=False)}')\nprint(f'CV (1DCNN): {mean_squared_error(y_train, oof_train_cnn, squared=False)}')\n\"\"\"\n# Linear model\n\"\"\"\nlin_params = {\n    'alpha': 80, \n    'fit_intercept': True,\n    'max_iter': 8000, \n    'tol': 1e-04,\n    'random_state': SEED,\n}\ndef fit_linear(params, X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED):\n    cv = KFold(n_splits=n_fold, shuffle=True, random_state=seed)\n\n    models = []\n    oof_train = np.zeros((len(X_train),))\n    y_preds = np.zeros((len(X_test),))\n    \n    # feature importance\n    fi_df = pd.DataFrame()\n    fi_df['features'] = features\n\n    for fold_id, (train_index, valid_index) in tqdm(enumerate(cv.split(X_train, y_train))):\n        # split\n        X_tr = X_train.loc[train_index, features]\n        X_val = X_train.loc[valid_index, features]\n        y_tr = y_train.loc[train_index].values\n        y_val = y_train.loc[valid_index].values\n        \n        # model\n        model = linear_model.Ridge(**params)\n        model.fit(X_tr, y_tr)\n\n        # feature importance\n        fi_df[f'importance_cv{fold_id}'] = model.coef_.ravel()\n            \n        # predict\n        oof_train[valid_index] = model.predict(X_val)\n        y_pred = model.predict(X_test[features])\n        y_preds += y_pred \/ n_fold\n        models.append(model)\n        \n    return oof_train, y_preds, models, fi_df\n\noof_train_lin, y_preds_lin, lin_models, fi_df = fit_linear(lin_params, \n    X_train, y_train, X_test, features=features, n_fold=NFOLD, seed=SEED)\nprint(f'CV (Linear): {mean_squared_error(y_train, oof_train_lin, squared=False)}')\n\"\"\"\n# Stacking\n\"\"\"\n# train\nstack_train_df = pd.DataFrame()\nstack_train_df['mlp'] = oof_train_mlp\nstack_train_df['1dcnn'] = oof_train_cnn\nstack_train_df['xgb'] = oof_train_xgb\nstack_train_df['lgb'] = oof_train_lgb\nstack_train_df['catb'] = oof_train_catb\nstack_train_df['lin'] = oof_train_lin\n\n# test\nstack_test_df = pd.DataFrame()\nstack_test_df['mlp'] = y_preds_mlp\nstack_test_df['1dcnn'] = y_preds_cnn\nstack_test_df['xgb'] = y_preds_xgb\nstack_test_df['lgb'] = y_preds_lgb\nstack_test_df['catb'] = y_preds_catb\nstack_test_df['lin'] = y_preds_lin\noof_train_lin, y_preds_lin, lin_models, fi_df = fit_linear(lin_params, \n    stack_train_df, y_train, stack_test_df, features=stack_test_df.columns.values.tolist(),\n    n_fold=NFOLD, seed=SEED)\nfi_df['importance_mean'] = fi_df.values[:, 1:].mean(axis=1)\nsns.barplot(x='importance_mean', y='features', data=fi_df.sort_values(by='importance_mean'))\n\"\"\"\n# Stacking score\n\"\"\"\nprint(f'CV (stacking): {mean_squared_error(y_train, oof_train_lin, squared=False)}')\nfi_df['importance_mean'] = fi_df.values[:, 1:].mean(axis=1)\nsns.barplot(x='importance_mean', y='features', data=fi_df.sort_values(by='importance_mean'))\n\"\"\"\n# Submit\n\"\"\"\nsub = pd.read_csv('..\/input\/tabular-playground-series-jan-2021\/sample_submission.csv')\nsub['target'] = y_preds_lin\nsub.to_csv('submission.csv', index=False)\nsub.head()","meta":"{'source': 'AI4Code', 'id': '5eca133e7c0d80'}"}
{"id":"135591","text":"\"\"\"\nAfter reviewing a few of the other onion-or-not kernels, I figured I'd try a character based approach. Instead of cleaning the text and tokenizing each word, I tried tokenizing each character, then fed the integer sequences to a CNN to see what results I got. I consistently achieved over 80% accuracy, which is not bad for such a simple approach.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\nfrom sklearn.model_selection import train_test_split\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# Any results you write to the current directory are saved as output.\ndf = pd.read_csv('..\/input\/onion-or-not\/OnionOrNot.csv')\ndf.head()\n# Here we tokenize each character (rather than each word).\ntokenize = Tokenizer(char_level=True)\ntokenize.fit_on_texts(df.text)\nX = pad_sequences(tokenize.texts_to_sequences(df.text), maxlen=250, padding=\"post\")\nY = df.label\n\nmodel = Sequential([\n                   Embedding(len(tokenize.word_index) + 1, 64),\n                   Conv1D(64, 5, activation=\"relu\"),\n                   Conv1D(64, 5, activation=\"relu\"),\n                   GlobalMaxPooling1D(),\n                   Dense(64, activation=\"relu\"),\n                   Dropout(.25),\n                   Dense(16, activation=\"relu\"),\n                   Dropout(.25),\n                   Dense(2, activation=\"softmax\"),\n])\nmodel.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"acc\"])\n# split data into training and test sets\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=.1, random_state=5)\nhistory = model.fit(x_train, y_train, validation_data=([x_test, y_test]), epochs=5, verbose=1)","meta":"{'source': 'AI4Code', 'id': 'f946bb6f60ee9c'}"}
{"id":"88952","text":"import numpy as np\nimport pandas as pd\nimport os\nimport folium\nfrom folium import plugins\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\ndata0=pd.read_csv('..\/input\/fast-food-restaurants-across-us\/Fast_Food_Restaurants_US.csv')\ndata0\nprint(data0.columns.tolist())\n\"\"\"\n### Fast Food Restaurant Ranknig\n\"\"\"\ndata2a=data0[['name']]\ndata2a['number']=1\ndata2a=data2a.groupby('name',as_index=False).sum()\ndata2a=data2a.sort_values('number',ascending=False)\ndata2a\nfig = px.bar(data2a[0:30], x='name', y='number',title=\"Fast Food Restaurant Ranknig\")\nfig.show()\n\"\"\"\n### Subway Ranknig by City\n\"\"\"\ndata2b=data0[data0['name']=='Subway'][['city']]\ndata2b['number']=1\ndata2b=data2b.groupby('city',as_index=False).sum()\ndata2b=data2b.sort_values('number',ascending=False)\ndata2b\nfig = px.bar(data2b[0:30], x='city', y='number',title=\"Subway Ranknig by City\")\nfig.show()\n\"\"\"\n### Location of Subway in Chicago \n\"\"\"\ndata3=data0[data0['name']=='Subway'][data0['city']=='Chicago'][['latitude','longitude']]\ndata3=data3.fillna('N')\ndata3\neq_map = folium.Map(location=[41.9,-87.7],tiles='Stamen Terrain',zoom_start=10.0,min_zoom=2.0)\neq_map.add_child(plugins.HeatMap(data3))\neq_map","meta":"{'source': 'AI4Code', 'id': 'a322f92e36f5b0'}"}
{"id":"56257","text":"\"\"\"\n# Google Play Store Analysis\n\"\"\"\n\"\"\"\n**Imports**\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nsns.set()\n%matplotlib inline\ndata = pd.read_csv('..\/input\/googleplaystore.csv')\ndf = data.copy()\ndf.head()\ndf.info()\n\"\"\"\n**From this we can see the null values**\n\"\"\"\ndf.isnull().sum()\ndf.describe(include='all')\ndf['Reviews'] = df['Reviews'].str.replace('3.0M', '3000000')\ndf['Reviews'] = df['Reviews'].astype(np.float)\ndf['Price'].unique()\ndf['Price In Dollors'] = df['Price']\ndf['Price In Dollors'] = df['Price In Dollors'].str.replace('Everyone', '$0')\ndf['Price In Dollors'] = df['Price In Dollors'].str.replace('$', '')\ndf['Price In Dollors'] = df['Price In Dollors'].astype(np.float)\n\"\"\"\n**Row number 10472 is shifted on the left size so i moved the row one step right**\n\"\"\"\ndf.loc[10472]\ndf.loc[10472] = df.loc[10472].shift(periods=1, axis=0)\ndf['Rating'] = df['Rating'].astype(np.float64)\ndf['Last Updated'] = pd.to_datetime(df['Last Updated'])\ndf['Installs'].unique()\ndf['Installs'] = df['Installs'].str.replace('+', '')\ndf['Installs'] = df['Installs'].str.replace(',', '')\ndf['Installs'] = df['Installs'].astype(np.int)\ndf['Type'].unique()\ndf['Type'].fillna(value='Free', inplace=True)\ndf['Content Rating'].unique()\ndf['Rating'].fillna(0, inplace=True)\ndf['Content Rating'].unique()\ndf['Content Rating'].fillna('Unrated', inplace=True, axis=0)\ndf['Current Ver'].fillna('Unknown', inplace=True, axis=0)\ndf['Android Ver'].fillna('Unknown', inplace=True, axis=0)\n\"\"\"\n# Visuallization\n\"\"\"\nsns.set(style=\"ticks\", color_codes=True, font_scale=1.5)\nplt.figure(figsize=(5, 4))\nsns.barplot(x='Type', y='Price In Dollors', ci=None, data=df);\nplt.figure(figsize=(25, 8))\nsns.barplot(x='Rating', y='Price In Dollors', data=df, ci=None);\ndf['Rating Size'] = ''\ndf.loc[(df['Rating']>=0.0) & (df['Rating']<=1.0), 'Rating Size'] = '0.0 - 1.0'\ndf.loc[(df['Rating']>=1.0) & (df['Rating']<=2.0), 'Rating Size'] = '1.0 - 2.0'\ndf.loc[(df['Rating']>=2.0) & (df['Rating']<=3.0), 'Rating Size'] = '2.0 - 3.0'\ndf.loc[(df['Rating']>=3.0) & (df['Rating']<=4.0), 'Rating Size'] = '3.0 - 4.0'\ndf.loc[(df['Rating']>=4.0) & (df['Rating']<=5.0), 'Rating Size'] = '4.0 - 5.0'\ndf.loc[(df['Rating']>=5.0) & (df['Rating']<=6.0), 'Rating Size'] = '5.0 - 6.0'\ndf.loc[(df['Rating']>=6.0) & (df['Rating']<=7.0), 'Rating Size'] = '6.0 - 7.0'\ndf.loc[(df['Rating']>=7.0) & (df['Rating']<=9.0), 'Rating Size'] = '7.0 - 8.0'\ndf.loc[df['Rating']>=9.0, 'Rating Size'] = '9.0+'\nplt.figure(figsize=(25, 8))\nsns.barplot(x='Rating Size', y='Price In Dollors', data=df, ci=None, order=['0.0 - 1.0','1.0 - 2.0','2.0 - 3.0','3.0 - 4.0','4.0 - 5.0','5.0 - 6.0','6.0 - 7.0','7.0 - 8.0','9.0+']);\nplt.figure(figsize=(20, 8))\nsns.lineplot(x='Rating Size', y='Price In Dollors', data=df);\nplt.figure(figsize=(20, 8))\nsns.relplot(x='Price In Dollors', y='Rating Size', hue='Type', data=df);\nplt.figure(figsize=(15, 8))\nsns.boxplot(x='Price In Dollors', y='Rating Size', hue='Type', order=['0.0 - 1.0','1.0 - 2.0','2.0 - 3.0','3.0 - 4.0','4.0 - 5.0','5.0 - 6.0','6.0 - 7.0','7.0 - 8.0','9.0+'], data=df);\nrating = df.groupby('Rating Size')['Price In Dollors'].sum().reset_index()\nplt.figure(figsize=(25, 8))\nsns.barplot(x='Rating Size', y='Price In Dollors', data=rating, ci=None, order=['0.0 - 1.0','1.0 - 2.0','2.0 - 3.0','3.0 - 4.0','4.0 - 5.0','5.0 - 6.0','6.0 - 7.0','7.0 - 8.0','9.0+']);\nplt.figure(figsize=(20, 8))\nsns.lineplot(x='Rating Size', y='Price In Dollors', data=rating);\nplt.figure(figsize=(20, 8))\nsns.barplot(x='Content Rating', y='Price In Dollors', data=df, ci=None);\ncontent_rating = df.groupby('Content Rating')['Price In Dollors'].sum().reset_index()\nplt.figure(figsize=(20, 8))\nsns.barplot(x='Content Rating', y='Price In Dollors', data=content_rating, ci=None);\nplt.figure(figsize=(35, 45))\nsns.barplot(x='Price In Dollors', y='Genres', data=df, ci=None);\ngenres = df.groupby('Genres')['Price In Dollors'].sum().reset_index()\nten_genres = genres.sort_values(by='Price In Dollors', ascending=False).reset_index(drop=True)\nten_genres.head()\nplt.figure(figsize=(20, 8))\nsns.barplot(x='Price In Dollors', y='Genres', data=ten_genres, ci=None, order=ten_genres.Genres.loc[:9]);\nplt.figure(figsize=(20, 8))\nsns.countplot(x='Rating Size', hue='Type', order=['0.0 - 1.0','1.0 - 2.0','2.0 - 3.0','3.0 - 4.0','4.0 - 5.0','5.0 - 6.0','6.0 - 7.0','7.0 - 8.0','9.0+'], data=df);\nsns.catplot(x='Type', y='Price In Dollors', col='Rating Size',col_order=['0.0 - 1.0','1.0 - 2.0','2.0 - 3.0','3.0 - 4.0','4.0 - 5.0','5.0 - 6.0','6.0 - 7.0','7.0 - 8.0','9.0+'], data=df);\n\"\"\"\n**Extracting year from last updated column**\n\"\"\"\ndf['Year'] = ''\ndf.loc[:,'Year'] = pd.DatetimeIndex(df['Last Updated']).year\n\"\"\"\n**Created a function which can show to all the important stats of the particular year**\n\"\"\"\ndef get_yearby_info(y, plot=False):\n    \n    if y > 2018 and y < 2010:\n        raise ValueError('Year starts from 2010 to 2018')\n    if y is None:\n        raise ValueError('Please enter year')\n    \n    year = df[df['Year'] == y]\n    installs = year.groupby(['App','Year','Type', 'Size', 'Genres', 'Content Rating','Price In Dollors'])['Installs'].sum().reset_index()\n    top_installs = installs.sort_values(by='Installs', ascending=False).reset_index(drop=True)\n    \n    if plot == False:\n        return top_installs.head(10)\n    else:\n        plt.figure(figsize=(20, 20))\n        plt.subplot(321)\n        plt.xscale('log')\n        sns.barplot(x='Installs', y=top_installs.App.loc[:9], data=top_installs);\n\n        plt.subplot(322)\n        plt.xscale('log')\n        sns.distplot(top_installs['Installs']);\n\n        plt.figure(figsize=(40, 10))\n        plt.subplot(323)\n        plt.xscale('log')\n        sns.boxplot(x='Installs', y='Type', data=top_installs);\nget_yearby_info(2018)\nget_yearby_info(2018, plot=True)","meta":"{'source': 'AI4Code', 'id': '67cca95ad74220'}"}
{"id":"128625","text":"\"\"\"\n![logo](https:\/\/optuna.org\/assets\/img\/bg.jpg)\n\"\"\"\n\"\"\"\nThere are many hyperparameter optimization frameworks available, and in this notebook we will give [Optuna](https:\/\/optuna.org\/) a spin.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport optuna\nfrom optuna.integration import TFKerasPruningCallback\nfrom optuna.trial import TrialState\nfrom optuna.visualization import plot_intermediate_values\nfrom optuna.visualization import plot_optimization_history\nfrom optuna.visualization import plot_param_importances\nfrom optuna.visualization import plot_contour\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras import *\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom tensorflow.keras.optimizers.schedules import ExponentialDecay\nfrom sklearn.preprocessing import RobustScaler, normalize\nfrom sklearn.model_selection import train_test_split\nfrom pickle import load\n!cp ..\/input\/ventilator-feature-engineering\/VFE.py .\n\"\"\"\n# Dataset creation\nTraining dataset is loaded from the [feature engineering notebook](https:\/\/www.kaggle.com\/mistag\/ventilator-feature-engineering).\nFeature engineering is based on [Ensemble Folds with MEDIAN](https:\/\/www.kaggle.com\/cdeotte\/ensemble-folds-with-median-0-153) by [Chris Deotte](https:\/\/www.kaggle.com\/cdeotte). The optimization is run on a smaller subset of the dataset.\n\"\"\"\nfrom VFE import add_features\n\ntrain = np.load('..\/input\/ventilator-feature-engineering\/x_train.npy')\ntargets = np.load('..\/input\/ventilator-feature-engineering\/y_train.npy')\n\nBATCH_SIZE = 1024\n\n# test set\ntest_ori = pd.read_csv('..\/input\/ventilator-pressure-prediction\/test.csv')\ntest = add_features(test_ori)\ntest.drop(['id', 'breath_id'], axis=1, inplace=True)\n\nRS = load(open('..\/input\/ventilator-feature-engineering\/RS.pkl', 'rb'))\ntest = RS.transform(test)\ntest = test.reshape(-1, 80, test.shape[-1])\n\"\"\"\nFinally we split the data into train and test sets. We keep a large holdout set for model evaluation.\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(train, targets, test_size=0.59284, random_state=21)\nX_test, X_valid, y_test, y_valid = train_test_split(X_test, y_test, test_size=0.79395, random_state=21)\nX_train.shape, X_test.shape, X_valid.shape\n\"\"\"\n# Model building\nThe model below is from  [Ensemble Folds with MEDIAN](https:\/\/www.kaggle.com\/cdeotte\/ensemble-folds-with-median-0-153) by [Chris Deotte](https:\/\/www.kaggle.com\/cdeotte).. Hopefully Optuna will be able to figure out the optimal parameters in the model. All parameters that we want to explore are created with a trial.suggest_() function. \n\"\"\"\n# model creation\ndef create_lstm_model(trial):\n\n    x0 = tf.keras.layers.Input(shape=(train.shape[-2], train.shape[-1]))  \n\n    lstm_layers = 4\n    lstm_units = np.zeros(lstm_layers, dtype=np.int)\n    lstm_units[0] = trial.suggest_int(\"lstm_units_L1\", 768, 1536)\n    lstm = Bidirectional(keras.layers.LSTM(lstm_units[0], return_sequences=True))(x0)\n    for i in range(lstm_layers-1):\n        lstm_units[i+1] = trial.suggest_int(\"lstm_units_L{}\".format(i+2), lstm_units[i]\/\/2, lstm_units[i])\n        lstm = Bidirectional(keras.layers.LSTM(lstm_units[i+1], return_sequences=True))(lstm)    \n    dropout_rate = trial.suggest_float(\"lstm_dropout\", 0.0, 0.3)\n    lstm = Dropout(dropout_rate)(lstm)\n    dense_units = lstm_units[-1]\n    # try different activations\n    activation = trial.suggest_categorical(\"activation\", [\"relu\", \"selu\", \"elu\", \"swish\"])\n    lstm = Dense(dense_units, activation=activation)(lstm)\n    lstm = Dense(1)(lstm)\n\n    model = keras.Model(inputs=x0, outputs=lstm)\n    metrics = [\"mae\"]\n    model.compile(optimizer=\"adam\", loss=\"mae\", metrics=metrics)\n    \n    return model\n\"\"\"\n## Objective function\nHere we define the Optuna objective function. The number of epochs per trial is a balance between execution time per trial and confidence in the result of each trial.\n\"\"\"\n# Function to get hardware strategy\ndef get_hardware_strategy():\n    try:\n        # TPU detection. No parameters necessary if TPU_NAME environment variable is\n        # set: this is always the case on Kaggle.\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        tpu = None\n\n    if tpu:\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        tf.config.optimizer.set_jit(True)\n    else:\n        # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n        strategy = tf.distribute.get_strategy()\n\n    return tpu, strategy\n\ntpu, strategy = get_hardware_strategy()\nEPOCHS = 30 # number of epocs per trial\n\ndef objective(trial):\n    \n    # Clear clutter from previous session graphs.\n    keras.backend.clear_session()\n    \n    with strategy.scope():\n        # Generate our trial model.\n        model = create_lstm_model(trial)\n\n        # learning rate scheduler\n        scheduler = ExponentialDecay(1e-3, 400*((len(train)*0.8)\/BATCH_SIZE), 1e-5)\n        lr = LearningRateScheduler(scheduler, verbose=0)\n    \n        # Fit the model on the training data.\n        # The TFKerasPruningCallback checks for pruning condition every epoch.\n        model.fit(\n            X_train,\n            y_train,\n            batch_size=BATCH_SIZE,\n            callbacks=[TFKerasPruningCallback(trial, \"val_loss\")],\n            epochs=EPOCHS,\n            validation_data=(X_test, y_test),\n            verbose=1,\n        )\n\n        # Evaluate the model accuracy on the validation set.\n        score = model.evaluate(X_valid, y_valid, verbose=0)\n        return score[1]\n\"\"\"\n# Run optimization\nThere are different samplers and pruners to choose from, here we go for TPESampler and HyperbandPruner.\n\"\"\"\nstudy = optuna.create_study(direction=\"minimize\", sampler=optuna.samplers.TPESampler(), pruner=optuna.pruners.HyperbandPruner())\nstudy.optimize(objective, n_trials=100)\npruned_trials = study.get_trials(deepcopy=False, states=[TrialState.PRUNED])\ncomplete_trials = study.get_trials(deepcopy=False, states=[TrialState.COMPLETE])\n\"\"\"\n# Result\nNow we can create a few interesting plots with the Optuna builtin visualization functions, starting with optimization history:\n\"\"\"\nplot_optimization_history(study)\n\"\"\"\nVisualize the loss curves of the trials:\n\"\"\"\nplot_intermediate_values(study)\n\"\"\"\nParameter contour plots - useful or confusing?\n\"\"\"\nplot_contour(study)\n\"\"\"\nThe parameter importance plot is really interesting:\n\"\"\"\nplot_param_importances(study)\n\"\"\"\nFinally list the optimized model parameters:\n\"\"\"\nprint(\"Study statistics: \")\nprint(\"  Number of finished trials: \", len(study.trials))\nprint(\"  Number of pruned trials: \", len(pruned_trials))\nprint(\"  Number of complete trials: \", len(complete_trials))\n\nprint(\"Best trial:\")\ntrial = study.best_trial\n\nprint(\"  Value: \", trial.value)\n\nprint(\"  Params: \")\nfor key, value in trial.params.items():\n    print(\"    {}: {}\".format(key, value))\n\"\"\"\n# Summary\nUsing Optuna we found a set of optimal model parameters. Next step is to [test the optimal model](https:\/\/www.kaggle.com\/mistag\/optuna-optimized-base-keras-model).\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ec96742754a2fd'}"}
{"id":"67691","text":"\"\"\"\n## 0-Import Library\n\"\"\"\n\"\"\"\nKfold & Catboost\nLB:5.94134\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\"\"\"\n## 1-Feature Engineering\n\nYou can start feature engineering quickly by The function 'feat_eng'(df)'\n\ndf is train.csv or test.csv\n\"\"\"\n\"\"\"\n### Data\n* country\n* store\n* product\n* (num_sold)\n* holiday (By Country)\n* year\n* dayofyear\n* quarter\n* month\n* day\n* week\n* GDP_value\n\n\n\"\"\"\ndf = pd.read_csv('..\/input\/tabular-playground-series-jan-2022\/train.csv')\ndf\nmean = df['num_sold'].mean()\nstd = df['num_sold'].std()\n\nmean,std\ndef feat_eng(df):\n    countries = {'Finland': 0, 'Norway': 1, 'Sweden': 2}\n    stores = {'KaggleMart': 0, 'KaggleRama': 1}\n    products = {'Kaggle Mug': 0,'Kaggle Hat': 1, 'Kaggle Sticker': 2}\n    \n    # load holiday info.\n    holiday = pd.read_csv('..\/input\/public-and-unofficial-holidays-nor-fin-swe-201519\/holidays.csv')\n    GDP = pd.read_csv('..\/input\/gdp-20152019-finland-norway-and-sweden\/GDP_data_2015_to_2019_Finland_Norway_Sweden.csv', index_col=\"year\")\n    population = pd.read_csv('..\/input\/population-20152019-finland-norway-sweden\/population_2015-2019_Finland_Norway_Sweden.csv',index_col = 'year')\n    fin_holiday = holiday.loc[holiday.country == 'Finland']\n    swe_holiday = holiday.loc[holiday.country == 'Sweden']\n    nor_holiday = holiday.loc[holiday.country == 'Norway']\n    df['fin holiday'] = df.date.isin(fin_holiday.date).astype(int)\n    df['swe holiday'] = df.date.isin(swe_holiday.date).astype(int)\n    df['nor holiday'] = df.date.isin(nor_holiday.date).astype(int)\n    df['holiday'] = np.zeros(df.shape[0]).astype(int)\n    df.loc[df.country == 'Finland', 'holiday'] = df.loc[df.country == 'Finland', 'fin holiday']\n    df.loc[df.country == 'Sweden', 'holiday'] = df.loc[df.country == 'Sweden', 'swe holiday']\n    df.loc[df.country == 'Norway', 'holiday'] = df.loc[df.country == 'Norway', 'nor holiday']\n    df.drop(['fin holiday', 'swe holiday', 'nor holiday'], axis=1, inplace=True)\n    \n    df['date'] = pd.to_datetime(df['date'])\n    df['year'] = df['date'].dt.year\n    df['dayofyear'] = df['date'].dt.dayofyear\n    df['quarter'] = df['date'].dt.quarter\n    df['month'] = df['date'].dt.month\n    df['dayofmonth'] = df['date'].dt.days_in_month\n    df['day'] = df['date'].dt.day\n    df['week']= df['date'].dt.weekday\n    df['country'] = df['country'].replace(countries)\n    df['store'] = df['store'].replace(stores)\n    df['product'] = df['product'].replace(products)\n    df = df.drop(columns = 'row_id')\n    df = df.drop(columns = 'date')\n    \n    # GDP columns\n    GDP.columns = [0,1,2]\n    GDP_dictionary = GDP.unstack().to_dict()\n    df[\"GDP_value\"] = df.set_index(['country','year']).index.map(GDP_dictionary.get)\n    df[\"GDP_value\"] = df[\"GDP_value\"]\n    \n    population.columns = [0,1,2]\n    population_dictionary = population.unstack().to_dict()\n    df[\"population\"] = df.set_index(['country','year']).index.map(population_dictionary.get)\n\n    \n    return df\n\ndf = pd.read_csv('..\/input\/tabular-playground-series-jan-2022\/train.csv')\ndf_train = feat_eng(df)\ndf_train['num_sold'] = np.log(df_train['num_sold'])\ndf_train['population'].describe()\n\"\"\"\n.descriv## 2-CrossValidation & CatBoost\n\"\"\"\ntrain_y = df_train['num_sold']\ntrain_x = df_train[['country',\n                   'store',\n                   'product',\n                   'holiday',\n                   'year',\n                   'dayofyear',\n                   'quarter',\n                   'month',\n                    'dayofmonth',\n                   'day',\n                   'week',\n                    'GDP_value',\n                   'population'\n                   ]\n                  ]\ntrain_x\ndef SMAPE(y_true, y_pred):\n    denominator = (y_true + np.abs(y_pred)) \/ 200.0\n    diff = np.abs(y_true - y_pred) \/ denominator\n    diff[denominator == 0] = 0.0\n    return np.mean(diff)\nfrom sklearn.metrics import log_loss, mean_squared_error\nfrom sklearn.model_selection import KFold,TimeSeriesSplit\nfrom sklearn.linear_model import LinearRegression\nimport xgboost as xgb\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nfrom catboost import CatBoostRegressor\n\n\n# fold5\nkf = KFold(n_splits = 5, shuffle = True, random_state = 70)\nx = 0.95\n# modeling and training\nfor fold, (tr_idx, va_idx) in enumerate(kf.split(train_x)):\n    print(f'--------fold:{fold}--------')\n    fold+=1\n    tr_x, va_x = train_x.iloc[tr_idx], train_x.iloc[va_idx]\n    tr_y, va_y = train_y.iloc[tr_idx], train_y.iloc[va_idx]\n    \n    params = {'depth': 5,\n                  'learning_rate': 0.001,\n                  'l2_leaf_reg': 5.0,\n                  'random_strength': 3.0,\n                  'min_data_in_leaf': 2}\n                  \n    model = CatBoostRegressor(**params,\n                              iterations=20000,\n                              bootstrap_type='Bayesian',\n                              boosting_type='Plain',\n                              loss_function='MAE',\n                              eval_metric='SMAPE',\n                              random_seed=5)\n    # Training the model\n    \n    va_pred = model.fit(tr_x,\n              tr_y,\n              eval_set=[(va_x, va_y)],\n              early_stopping_rounds = 200,\n              verbose = 1000)\n    val_pred = model.predict(va_x)\n    # Convert the target back to non-logaritmic.\n    print(f' SMAPE: {SMAPE(np.exp(va_y), np.exp(val_pred))}')\n\n\"\"\"\n## 3-Submission\n\"\"\"\ndf\ntest = pd.read_csv('..\/input\/tabular-playground-series-jan-2022\/test.csv')\ntest = feat_eng(test)\ny = model.predict(test)\ndf_submission = pd.read_csv('..\/input\/tabular-playground-series-jan-2022\/sample_submission.csv') \ndf_submission['num_sold'] = np.exp(y)\ndf_submission.to_csv('.\/submission.csv', index = False)","meta":"{'source': 'AI4Code', 'id': '7c98deb313cb70'}"}
{"id":"104243","text":"# 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 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\n\"\"\"\n# please upvote if you guys like the concept this will give me motivation to make more such kernels.\nThank you\n\"\"\"\n\"\"\"\n\n# what is NGBoost ? \n### ngboost stands for natural gradient boosting for probalistic prediction, NGBoost enables predictive uncertainty estimation with Gradient Boosting through probabilistic predictions (including real valued outputs). With the use of Natural Gradients, NGBoost overcomes technical challenges that make generic probabilistic prediction hard with gradient boosting.\n reference paper:- https:\/\/stanfordmlgroup.github.io\/projects\/ngboost\/, https:\/\/towardsdatascience.com\/ngboost-explained-comparison-to-lightgbm-and-xgboost-fda510903e53\nand thanks to Mr Y.Nakama i have used some of his code from this kernel :- https:\/\/www.kaggle.com\/yasufuminakama\/osic-ridge-baseline\n \n \n\"\"\"\n\"\"\"\n<img src = 'https:\/\/stanfordmlgroup.github.io\/projects\/ngboost\/img\/toy_single.png'>\n\"\"\"\n\"\"\"\n# Installing ngboost\n\"\"\"\n!pip install ngboost\n\"\"\"\n# Libararies used :-\n\"\"\"\nimport os\nfrom logging import getLogger, INFO, StreamHandler, FileHandler, Formatter\nfrom functools import partial\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport math\n\nfrom tqdm.notebook import tqdm\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import StratifiedKFold, GroupKFold, KFold\nfrom sklearn.metrics import mean_squared_error\nimport category_encoders as ce\n\nfrom PIL import Image\nimport cv2\nimport pydicom\n\nimport torch\n\nfrom ngboost import NGBRegressor\nfrom catboost import CatBoostRegressor\nfrom sklearn.svm import SVR\nimport lightgbm as lgb\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import BayesianRidge\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n# Utils\n\"\"\"\ndef get_logger(filename='log'):\n    logger = getLogger(__name__)\n    logger.setLevel(INFO)\n    handler1 = StreamHandler()\n    handler1.setFormatter(Formatter(\"%(message)s\"))\n    handler2 = FileHandler(filename=f\"{filename}.log\")\n    handler2.setFormatter(Formatter(\"%(message)s\"))\n    logger.addHandler(handler1)\n    logger.addHandler(handler2)\n    return logger\n\nlogger = get_logger()\n\n\ndef seed_everything(seed=2020):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\"\"\"\n# Config\n\"\"\"\nOUTPUT_DICT = '.\/'\n\nID = 'Patient_Week'\nTARGET = 'FVC'\nSEED = 42\nseed_everything(seed=SEED)\n\nN_FOLD = 4\n\"\"\"\n# Data Loading\n\"\"\"\ntrain = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/train.csv')\ntrain[ID] = train['Patient'].astype(str) + '_' + train['Weeks'].astype(str)\nprint(train.shape)\ntrain.head()\n# construct train input\n\noutput = pd.DataFrame()\ngb = train.groupby('Patient')\ntk0 = tqdm(gb, total=len(gb))\nfor _, usr_df in tk0:\n    usr_output = pd.DataFrame()\n    for week, tmp in usr_df.groupby('Weeks'):\n        rename_cols = {'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'}\n        tmp = tmp.drop(columns='Patient_Week').rename(columns=rename_cols)\n        drop_cols = ['Age', 'Sex', 'SmokingStatus', 'Percent']\n        _usr_output = usr_df.drop(columns=drop_cols).rename(columns={'Weeks': 'predict_Week'}).merge(tmp, on='Patient')\n        _usr_output['Week_passed'] = _usr_output['predict_Week'] - _usr_output['base_Week']\n        usr_output = pd.concat([usr_output, _usr_output])\n    output = pd.concat([output, usr_output])\n    \ntrain = output[output['Week_passed']!=0].reset_index(drop=True)\nprint(train.shape)\ntrain.head()\n# construct test input\n\ntest = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/test.csv')\\\n        .rename(columns={'Weeks': 'base_Week', 'FVC': 'base_FVC', 'Percent': 'base_Percent', 'Age': 'base_Age'})\nsubmission = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/sample_submission.csv')\nsubmission['Patient'] = submission['Patient_Week'].apply(lambda x: x.split('_')[0])\nsubmission['predict_Week'] = submission['Patient_Week'].apply(lambda x: x.split('_')[1]).astype(int)\ntest = submission.drop(columns=['FVC', 'Confidence']).merge(test, on='Patient')\ntest['Week_passed'] = test['predict_Week'] - test['base_Week']\nprint(test.shape)\ntest.head()\nsubmission = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/sample_submission.csv')\nprint(submission.shape)\nsubmission.head()\nfolds = train[[ID, 'Patient', TARGET]].copy()\n#Fold = KFold(n_splits=N_FOLD, shuffle=True, random_state=SEED)\nFold = GroupKFold(n_splits=N_FOLD)\ngroups = folds['Patient'].values\nfor n, (train_index, val_index) in enumerate(Fold.split(folds, folds[TARGET], groups)):\n    folds.loc[val_index, 'fold'] = int(n)\nfolds['fold'] = folds['fold'].astype(int)\nfolds.head()\n\"\"\"\n# MODEL building \n\"\"\"\n#===========================================================\n# model \n#===========================================================\ndef run_single_ngboost(param, train_df, test_df, folds, features, target, fold_num=0):\n    \n    trn_idx = folds[folds.fold!=fold_num].index\n    val_idx = folds[folds.fold==fold_num].index\n    \n    y_tr = target.iloc[trn_idx].values\n    X_tr = train_df.iloc[trn_idx][features].values\n    y_val = target.iloc[val_idx].values\n    X_val = train_df.iloc[val_idx][features].values\n    \n    oof = np.zeros(len(train_df))\n    predictions = np.zeros(len(test_df))\n    \n    clf = NGBRegressor(**param )\n    clf.fit(X_tr, y_tr)\n    \n    oof[val_idx] = clf.predict(X_val)\n    predictions += clf.predict(test_df[features])\n\n    logger.info(\"fold{} score: {:<8.5f}\"\n                .format(fold_num, np.sqrt(mean_squared_error(target[val_idx], oof[val_idx]))))\n    \n    return oof, predictions\n\n\ndef run_kfold_ngb(param, train, test, folds, features, target, n_fold=5):\n    \n    oof = np.zeros(len(train))\n    predictions = np.zeros(len(test))\n    feature_importance_df = pd.DataFrame()\n\n    for fold_ in range(n_fold):\n        \n        logger.info(\"Fold {}\".format(fold_))\n        _oof, _predictions = run_single_ngboost(param, \n                                                    train, \n                                                    test,\n                                                    folds,  \n                                                    features,\n                                                    target, \n                                                    fold_num=fold_)\n        oof += _oof\n        predictions += _predictions\/n_fold\n    \n    logger.info(\"CV score: {:<8.5f}\"\n                .format(np.sqrt(mean_squared_error(target, oof))))\n    \n    return oof, predictions\n\"\"\"\n## predict FVC\n\"\"\"\ntarget = train[TARGET]\ntest[TARGET] = np.nan\n\n# features\ncat_features = ['Sex', 'SmokingStatus']\nnum_features = [c for c in test.columns if (test.dtypes[c] != 'object') & (c not in cat_features)]\nfeatures = num_features + cat_features\ndrop_features = [ID, TARGET, 'predict_Week', 'base_Week']\nfeatures = [c for c in features if c not in drop_features]\n\nif cat_features:\n    ce_oe = ce.OrdinalEncoder(cols=cat_features, handle_unknown='impute')\n    ce_oe.fit(train)\n    train = ce_oe.transform(train)\n    test = ce_oe.transform(test)\n        \nngb_param = {\n                    'random_state': SEED,\n                    }\n\noof, predictions = run_kfold_ngb(ngb_param, train, test, folds, features, target, n_fold=N_FOLD)\ntrain['FVC_pred'] = oof\ntest['FVC_pred'] = predictions\n\"\"\"\n## make Confidence labels\n\"\"\"\n# baseline score\ntrain['Confidence'] = 100\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']\/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)\ntrain.head(10)\nimport scipy as sp\n\ndef loss_func(weight, row):\n    confidence = weight\n    sigma_clipped = max(confidence, 70)\n    diff = abs(row['FVC'] - row['FVC_pred'])\n    delta = min(diff, 1000)\n    score = -math.sqrt(2)*delta\/sigma_clipped - np.log(math.sqrt(2)*sigma_clipped)\n    return -score\n\nresults = []\ntk0 = tqdm(train.iterrows(), total=len(train))\nfor _, row in tk0:\n    loss_partial = partial(loss_func, row=row)\n    weight = [100]\n    #bounds = [(70, 100)]\n    #result = sp.optimize.minimize(loss_partial, weight, method='SLSQP', bounds=bounds)\n    result = sp.optimize.minimize(loss_partial, weight, method='SLSQP')\n    x = result['x']\n    results.append(x[0])\n# optimized score\ntrain['Confidence'] = results\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']\/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)\ntrain.head(10)\n\"\"\"\n## predict Confidence\n\"\"\"\nTARGET = 'Confidence'\n\ntarget = train[TARGET]\ntest[TARGET] = np.nan\n\n# features\ncat_features = ['Sex', 'SmokingStatus']\nnum_features = [c for c in test.columns if (test.dtypes[c] != 'object') & (c not in cat_features)]\nfeatures = num_features + cat_features\ndrop_features = [ID, TARGET, 'predict_Week', 'base_Week', 'FVC', 'FVC_pred']\nfeatures = [c for c in features if c not in drop_features]\n\nridge_param = {  'random_state': SEED,\n                    }\n\noof, predictions = run_kfold_ngb(ridge_param, train, test, folds, features, target, n_fold=N_FOLD)\ntrain['Confidence'] = oof\ntrain['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\ntrain['diff'] = abs(train['FVC'] - train['FVC_pred'])\ntrain['delta'] = train['diff'].apply(lambda x: min(x, 1000))\ntrain['score'] = -math.sqrt(2)*train['delta']\/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\nscore = train['score'].mean()\nprint(score)\ndef lb_metric(train):\n    train['sigma_clipped'] = train['Confidence'].apply(lambda x: max(x, 70))\n    train['diff'] = abs(train['FVC'] - train['FVC_pred'])\n    train['delta'] = train['diff'].apply(lambda x: min(x, 1000))\n    train['score'] = -math.sqrt(2)*train['delta']\/train['sigma_clipped'] - np.log(math.sqrt(2)*train['sigma_clipped'])\n    score = train['score'].mean()\n    return score\nscore = lb_metric(train)\nlogger.info(f'Local Score: {score}')\ntest['Confidence'] = predictions\n\"\"\"\n# Submission\n\"\"\"\nsubmission.head()\nsub1 = submission.drop(columns=['FVC', 'Confidence']).merge(test[['Patient_Week', 'FVC_pred', 'Confidence']], \n                                                           on='Patient_Week')\nsub1.columns = submission.columns\nsub1.to_csv('submission_ngb.csv', index=False)\nsub1.head()\nsub1.describe()\n\"\"\"\n# 1. Qunatile regression \n\"\"\"\n\"\"\"\n## libararies required for qunatile regression \n\"\"\"\nimport random\nfrom tqdm.notebook import tqdm \nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.metrics import mean_absolute_error\nfrom tensorflow_addons.optimizers import RectifiedAdam\nfrom tensorflow.keras import Model\nimport tensorflow.keras.backend as K\nimport tensorflow.keras.layers as L\nimport tensorflow.keras.models as M\nfrom tensorflow.keras.optimizers import Nadam\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom PIL import Image\nimport tensorflow as tf \nROOT = \"..\/input\/osic-pulmonary-fibrosis-progression\"\nBATCH_SIZE=128\n\ntr = pd.read_csv(f\"{ROOT}\/train.csv\")\ntr.drop_duplicates(keep=False, inplace=True, subset=['Patient','Weeks'])\nchunk = pd.read_csv(f\"{ROOT}\/test.csv\")\n\nprint(\"add infos\")\nsub = pd.read_csv(f\"{ROOT}\/sample_submission.csv\")\nsub['Patient'] = sub['Patient_Week'].apply(lambda x:x.split('_')[0])\nsub['Weeks'] = sub['Patient_Week'].apply(lambda x: int(x.split('_')[-1]))\nsub =  sub[['Patient','Weeks','Confidence','Patient_Week']]\nsub = sub.merge(chunk.drop('Weeks', axis=1), on=\"Patient\")\n\nimport math\ntr['WHERE'] = 'train'\nchunk['WHERE'] = 'val'\nsub['WHERE'] = 'test'\ndata = tr.append([chunk, sub])\nprint(tr.shape, chunk.shape, sub.shape, data.shape)\nprint(tr.Patient.nunique(), chunk.Patient.nunique(), sub.Patient.nunique(), \n      data.Patient.nunique())\ndata['min_week'] = data['Weeks']\ndata.loc[data.WHERE=='test','min_week'] = np.nan\ndata['min_week'] = data.groupby('Patient')['min_week'].transform('min')\nbase = data.loc[data.Weeks == data.min_week]\nbase = base[['Patient','FVC']].copy()\nbase.columns = ['Patient','min_FVC']\nbase['nb'] = 1\nbase['nb'] = base.groupby('Patient')['nb'].transform('cumsum')\nbase = base[base.nb==1]\nbase.drop('nb', axis=1, inplace=True)\ndata = data.merge(base, on='Patient', how='left')\ndata['base_week'] = data['Weeks'] - data['min_week']\ndel base\nCOLS = ['Sex','SmokingStatus'] #,'Age'\nFE = []\nfor col in COLS:\n    for mod in data[col].unique():\n        FE.append(mod)\n        data[mod] = (data[col] == mod).astype(int)\n#\ndata['age'] = (data['Age'] - data['Age'].min() ) \/ ( data['Age'].max() - data['Age'].min() )\ndata['BASE'] = (data['min_FVC'] - data['min_FVC'].min() ) \/ ( data['min_FVC'].max() - data['min_FVC'].min() )\ndata['week'] = (data['base_week'] - data['base_week'].min() ) \/ ( data['base_week'].max() - data['base_week'].min() )\ndata['percent'] = (data['Percent'] - data['Percent'].min() ) \/ ( data['Percent'].max() - data['Percent'].min() )\nFE += ['age','percent','week','BASE']\ntr = data.loc[data.WHERE=='train']\nchunk = data.loc[data.WHERE=='val']\nsub = data.loc[data.WHERE=='test']\ndel data\ntr.shape, chunk.shape, sub.shape\nimport keras\nC1, C2 = tf.constant(70, dtype='float32'), tf.constant(1000, dtype=\"float32\")\n\ndef score(y_true, y_pred):\n    tf.dtypes.cast(y_true, tf.float32)\n    tf.dtypes.cast(y_pred, tf.float32)\n    sigma = y_pred[:, 2] - y_pred[:, 0]\n    fvc_pred = y_pred[:, 1]\n    \n    #sigma_clip = sigma + C1\n    sigma_clip = tf.maximum(sigma, C1)\n    delta = tf.abs(y_true[:, 0] - fvc_pred)\n    delta = tf.minimum(delta, C2)\n    sq2 = tf.sqrt( tf.dtypes.cast(2, dtype=tf.float32) )\n    metric = (delta \/ sigma_clip)*sq2 + tf.math.log(sigma_clip* sq2)\n    return K.mean(metric)\n\n\n\ndef qloss(y_true, y_pred):\n    # Pinball loss for multiple quantiles\n    qs = [0.2, 0.50, 0.8]\n    q = tf.constant(np.array([qs]), dtype=tf.float32)\n    e = y_true - y_pred\n    v = tf.maximum(q*e, (q-1)*e)\n    return K.mean(v)\n\ndef mloss(_lambda):\n    def loss(y_true, y_pred):\n        return _lambda * qloss(y_true, y_pred) + (1 - _lambda)*score(y_true, y_pred)\n    return loss\n\ndef make_model(nh):\n    z = L.Input((nh,), name=\"Patient\")\n    x = L.Dense(300, activation=\"elu\", name=\"d1\")(z)\n    x = L.Dense(100, activation=\"relu\", name=\"d2\")(x)\n    x = L.Dense(100, activation=\"relu\", name=\"d3\")(x)\n    p1 = L.Dense(3, activation=\"linear\", name=\"p1\")(x)\n    p2 = L.Dense(3, activation=\"relu\", name=\"p2\")(x)\n    preds = L.Lambda(lambda x: x[0] + tf.cumsum(x[1], axis=1), \n                     name=\"preds\")([p1, p2])\n   # lr_schedule = keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=0.1,decay_steps=50000,decay_rate=0.9)\n    model = M.Model(z, preds, name=\"CNN\")\n    model.compile(loss=mloss(0.7), optimizer=tf.keras.optimizers.Adamax(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, name=\"Adamax\"), metrics=[score])\n    return model\ny = tr['FVC'].values\ny = y.astype(float)\nz = tr[FE].values\nze = sub[FE].values\nnh = z.shape[1]\npe = np.zeros((ze.shape[0], 3))\npred = np.zeros((z.shape[0], 3))\nnet = make_model(nh)\nprint(net.summary())\nprint(net.count_params())\nNFOLD = 5 # originally 5\nkf = KFold(n_splits=NFOLD)\n%%time\ncnt = 0\nEPOCHS = 950\nfor tr_idx, val_idx in kf.split(z):\n    cnt += 1\n    print(f\"FOLD {cnt}\")\n    net = make_model(nh)\n    net.fit(z[tr_idx], y[tr_idx], batch_size=BATCH_SIZE, epochs=EPOCHS, \n            validation_data=(z[val_idx], y[val_idx]), verbose=0) #\n    print(\"train\", net.evaluate(z[tr_idx], y[tr_idx], verbose=0, batch_size=BATCH_SIZE))\n    print(\"val\", net.evaluate(z[val_idx], y[val_idx], verbose=0, batch_size=BATCH_SIZE))\n    print(\"predict val...\")\n    pred[val_idx] = net.predict(z[val_idx], batch_size=BATCH_SIZE, verbose=0)\n    print(\"predict test...\")\n    pe += net.predict(ze, batch_size=BATCH_SIZE, verbose=0) \/ NFOLD\nsigma_opt = mean_absolute_error(y, pred[:, 1])\nunc = pred[:,2] - pred[:, 0]\nsigma_mean = np.mean(unc)\nprint(sigma_opt, sigma_mean)\nidxs = np.random.randint(0, y.shape[0], 100)\nplt.figure(figsize = (20,10))\nplt.plot(y[idxs], label=\"ground truth\")\nplt.plot(pred[idxs, 0], label=\"q25\")\nplt.plot(pred[idxs, 1], label=\"q50\")\nplt.plot(pred[idxs, 2], label=\"q75\")\nplt.legend(loc=\"best\")\nplt.show()\nprint(unc.min(), unc.mean(), unc.max(), (unc>=0).mean())\nplt.hist(unc)\nplt.title(\"uncertainty in prediction\")\nplt.show()\nsub.head()\n# PREDICTION\nsub['FVC1'] = 1.*pe[:, 1]\nsub['Confidence1'] = pe[:, 2] - pe[:, 0]\nsubm = sub[['Patient_Week','FVC','Confidence','FVC1','Confidence1']].copy()\nsubm.loc[~subm.FVC1.isnull()].head(10)\nsubm.loc[~subm.FVC1.isnull(),'FVC'] = subm.loc[~subm.FVC1.isnull(),'FVC1']\nif sigma_mean<70:\n    subm['Confidence'] = sigma_opt\nelse:\n    subm.loc[~subm.FVC1.isnull(),'Confidence'] = subm.loc[~subm.FVC1.isnull(),'Confidence1']\nsubm.head()\nsubm.describe().T\notest = pd.read_csv('..\/input\/osic-pulmonary-fibrosis-progression\/test.csv')\nfor i in range(len(otest)):\n    subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'FVC'] = otest.FVC[i]\n    subm.loc[subm['Patient_Week']==otest.Patient[i]+'_'+str(otest.Weeks[i]), 'Confidence'] = 0.1\nsubm[[\"Patient_Week\",\"FVC\",\"Confidence\"]].to_csv(\"submission_regression.csv\", index=False)\nreg_sub = subm[[\"Patient_Week\",\"FVC\",\"Confidence\"]].copy()\n\"\"\"\n# Ensemble\n\"\"\"\nFVC_weight = 0.35\nConfidence_weight = 0.35\ndf1 = sub1.sort_values(by=['Patient_Week'], ascending=True).reset_index(drop=True)\ndf2 = reg_sub.sort_values(by=['Patient_Week'], ascending=True).reset_index(drop=True)\ndf = df1[['Patient_Week']].copy()\ndf['FVC'] = FVC_weight*df1['FVC'] + (1-FVC_weight)*df2['FVC']\ndf['Confidence'] = Confidence_weight*df1['Confidence'] + (1-Confidence_weight)*df2['Confidence']\ndf.head()\ndf.to_csv('submission.csv', index=False)\ndf.describe()","meta":"{'source': 'AI4Code', 'id': 'bf7e772fce83e9'}"}
{"id":"110665","text":"\"\"\"\n# Stroke-Prediction (Classification Problem)\n\"\"\"\n# importing libraries\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import Normalizer\n# importing dataset\ndf = pd.read_csv(\"\/kaggle\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv\")\ndf.head(10)\n\"\"\"\n**Data Attributes**\n\n* id: unique identifier\n* gender: \"Male\", \"Female\" or \"Other\"\n* age: age of the patient\n* hypertension: 0 if the patient doesn't have hypertension, 1 if the patient has hypertension\n* heart_disease: 0 if the patient doesn't have any heart diseases, 1 if the patient has a heart disease\n* ever_married: \"No\" or \"Yes\"\n* work_type: \"children\", \"Govt_jov\", \"Never_worked\", \"Private\" or \"Self-employed\"\n* Residence_type: \"Rural\" or \"Urban\"\n* avg_glucose_level: average glucose level in blood\n* bmi: body mass index\n* smoking_status: \"formerly smoked\", \"never smoked\", \"smokes\" or \"Unknown\"*\n* stroke: 1 if the patient had a stroke or 0 if not\n\"\"\"\n# Datatypes of attributes\ndf.info()\n# Statistical data\ndf.describe()\n# Checking dor null values\ndf.isna().sum()\n# shape of our data\ndf.shape\n# dropping rows with null values\ndf = df.dropna(axis=0)\ndf = df.drop(columns=\"id\")\ndf.columns\n\"\"\"\n# Data Visualization\n\"\"\"\ndf.head()\nsns.pairplot(df, hue=\"stroke\",data=df)\nplt.show()\n# countplots\nsns.countplot(df[\"gender\"])\nplt.show()\nsns.countplot(df[\"heart_disease\"])\nplt.show()\nsns.countplot(df[\"Residence_type\"])\nplt.show()\nsns.countplot(df[\"smoking_status\"])\nplt.show()\nsns.countplot(df[\"work_type\"])\nplt.show()\nsns.histplot(df[\"age\"])\nplt.show()\nplt.figure(figsize=(14,7))\nsns.histplot(df[\"bmi\"],bins=30)\nplt.show()\n\"\"\"\n# Feature Engineering\n\"\"\"\ndf.head()\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ndf1 = df.apply(le.fit_transform)\ndf1.head()\nx = df1.drop(columns=\"stroke\")\ny = df1.stroke\nX_train, X_test, y_train, y_test = train_test_split(x,y, test_size=0.2, random_state=24)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\nX_train\n# Scaling of data\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\"\"\"\n# Model Selection\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\nmodel = RandomForestClassifier()\nmodel.fit(X_train,y_train)\ny_pred = model.predict(X_test)\nreport = classification_report(y_pred, y_test)\nprint(report)\nprint(\"Accuracy of Random Forest Classifier Model:\", accuracy_score(y_pred,y_test)*100,\"%\")\ncm = confusion_matrix(y_pred,y_test)\nsns.heatmap(data=cm, annot=True)\nplt.show()\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nmodel2 = SVC()\nmodel2.fit(X_train,y_train)\ny_pred2 = model2.predict(X_test)\nreport2 = classification_report(y_pred2, y_test)\nprint(report2)\nprint(\"Accuracy of SVM Model:\", accuracy_score(y_pred2,y_test)*100,\"%\")\nfrom sklearn.linear_model import LogisticRegression\nmodel3 = LogisticRegression()\nmodel3.fit(X_train,y_train)\ny_pred3 = model3.predict(X_test)\nreport3 = classification_report(y_pred3, y_test)\nprint(report3)\nprint(\"Accuracy of Logistic Regression Model:\", accuracy_score(y_pred3,y_test)*100,\"%\")\nimport xgboost\nxgb = xgboost.XGBClassifier(n_estimators=500)\nxgb.fit(X_train,y_train)\ny_pred4 = model3.predict(X_test)\nreport4 = classification_report(y_pred4, y_test)\nprint(report4)\nprint(\"Accuracy of XGBoost Model:\", accuracy_score(y_pred4,y_test)*100,\"%\")\n\"\"\"\n* Author: Purvit Vashishtha\n* Created on : 30.03.2021 at 11:55:40 pm\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'cb563c9779a44a'}"}
{"id":"67818","text":"# 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\n#for 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\n\"\"\"\n# Read data\n\"\"\"\n#import\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nimport missingno as msno\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nfrom PIL import Image\nbasepath = '\/kaggle\/input\/cassava-leaf-disease-classification'\npd.options.mode.chained_assignment = None\nTARGET_SZ=300 #Global variable for image size\ndata=pd.read_csv(\"\/kaggle\/input\/cassava-leaf-disease-classification\/train.csv\")\ndata.head()\n\"\"\"\n# How the image looks?\n\"\"\"\nimg = Image.open(\"..\/input\/cassava-leaf-disease-classification\/train_images\/1000723321.jpg\")\nplt.imshow(img)\nplt.show()\nprint(img.size)\n\"\"\"\n# Learn about data\n\"\"\"\n#How is the data distribution?\nprint(data.groupby('label').nunique())\nsn.countplot(x='label',data=data)\n\"\"\"\n# It is an Imbalanced training data set\n\nRemember the disease map\n\"root\": { 5 items\n\n\"0\":string\"Cassava Bacterial Blight (CBB)\"\n\n\"1\":string\"Cassava Brown Streak Disease (CBSD)\"\n\n\"2\":string\"Cassava Green Mottle (CGM)\"\n\n\"3\":string\"Cassava Mosaic Disease (CMD)\"\n\n\"4\":string\"Healthy\"\n}\n\nSo we have imbalanced data. \nCategory 3 - Mosaic Disease has large number of samples. Does this imbalance matters? Yes. We can try to fix it.\n\nBut wondering why Healthy is not as high as this - it seems  easy to get photos of healthy leaves.Shouldn't it?\n\"\"\"\n\"\"\"\n# Now to remove the imbalance\nThere are different techniques. We go for a simple method\n\"\"\"\n\n# To make the data set balanced, we select only 3000 samples of CMD (3) type.\n\n#balanced_data = data.loc[data['label'].isin([0,1,2,4])] \n#data=data.loc[data['label']==3]\n#data=data.sample(n=1000,random_state=1)\n#data=data.append(balanced_data)\n\ndata\n\"\"\"\n# Now let's see how the data looks\n\"\"\"\nprint(data.groupby('label').nunique())\nsn.countplot(x='label',data=data)\n\"\"\"\n# Check for null values\n\"\"\"\n#let's check the  data for missing values\n#msno.bar(data)\ndata.isnull().sum()\n\"\"\"\nGood. No null values.\n\"\"\"\n# For experimenting take only 9000 records in total\n\n#data=data.sample(n=300,random_state=1)\n# and again see the data distribution\n#sn.countplot(x='label',data=data)\n\"\"\"\n# Split data to training and validation\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ntrain, val = train_test_split(data, test_size=0.2)\n\"\"\"\n# Now define a CNN model\n\"\"\"\nclasses_to_prdict=train.label.unique()\n\nmodel = tf.keras.models.Sequential([\n    # input shape is the desired size of the image 300x300 with 3 bytes color\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(TARGET_SZ, TARGET_SZ, 3)),# convolution -1\n    tf.keras.layers.MaxPooling2D(2, 2), \n    tf.keras.layers.Conv2D(32, (3,3), activation='relu'), #Convolution-2\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Convolution-3\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Convolution-4\n    tf.keras.layers.MaxPooling2D(2,2), \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Convolution-5\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Convolution-6 sha\n    tf.keras.layers.MaxPooling2D(2,2),\n    #tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Convolution-7 sha - delete next also\n    #tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Flatten(), # Flatten before giving to NN\n    tf.keras.layers.Dense(512, activation='relu'),  # 512 neuron hidden layer\n    tf.keras.layers.Dense(256, activation='relu'),  # 256 neuron hidden layer - new\n    tf.keras.layers.Dense(128, activation='relu'),  # 128 neuron hidden layer - new\n    tf.keras.layers.Dense(64, activation='relu'),  # 64 neuron hidden layer - new\n    tf.keras.layers.Dense(32, activation='relu'),  # 32 neuron hidden layer - sha\n    #tf.keras.layers.Dense(16, activation='relu'),  # 16 neuron hidden layer - sha\n    tf.keras.layers.Dense(len(classes_to_prdict), activation='softmax') #Multi-class output\n])\nmodel.summary()\n#We use Adam optimizer\n\nfrom tensorflow.keras.optimizers import Adam\n\n#model.compile(loss='binary_crossentropy',\nmodel.compile(loss='categorical_crossentropy',\n#model.compile(loss='sparse_categorical_crossentropy',\n              #optimizer=Adam(lr=0.001),\n              optimizer=Adam(lr=0.001),\n              metrics=['accuracy'])\n#optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4)\n# All images will be rescaled by 1.\/255\ntrain_datagen = ImageDataGenerator(rescale=1.\/255)\nvalidation_datagen = ImageDataGenerator(rescale=1.\/255)\n#targetSz=300\ntargetSz=TARGET_SZ\n#batchSz=128\n#batchSz=100\nbatchSz=333\n\ntrain['label'] = train['label'].astype(str)\nval['label'] = val['label'].astype(str)\n\n# Flow training images in batches of 128 using train_datagen generator\ntrain_generator = train_datagen.flow_from_dataframe(train, \n                                                    directory = os.path.join(basepath, 'train_images'),\n                                                    x_col = 'image_id',\n                                                    y_col = 'label',\n                                                    target_size = (TARGET_SZ, TARGET_SZ),\n                                                    batch_size = batchSz,\n                                                    class_mode = 'categorical')\n\n# Flow training images in batches of 128 using train_datagen generator\nvalidation_generator = train_datagen.flow_from_dataframe(val, \n                                                    directory = os.path.join(basepath, 'train_images'),\n                                                    x_col = 'image_id',\n                                                    y_col = 'label',\n                                                    target_size = (TARGET_SZ, TARGET_SZ),\n                                                    batch_size = batchSz,\n                                                    class_mode = 'categorical')\n\"\"\"\n# Train the model\n\"\"\"\n#The parameters \"steps_per_epoch\" and \"validation_steps\" have to be equal to the\n#length of the dataset divided by the batch size. Otherwise within the first epoch itself it comes out. As\n#Then I found out from stack overflow the above rule. Not sure why?\n\ncallbacks = ReduceLROnPlateau(monitor='val_acc', \n                              #factor=0.5, \n                              factor=0.2,\n                              patience=5, \n                              verbose=1, \n                              #min_lr=0.0001)\n                              min_lr=0.001)\n\nhistory = model.fit_generator(\n            train_generator,\n            #steps_per_epoch = 3,\n            steps_per_epoch = 27,\n            #epochs = 3,\n            #epochs = 25,\n            epochs = 25,\n            verbose = 1,\n            validation_data = validation_generator,\n            #validation_steps = 3,\n            validation_steps = 27,\n            callbacks = [callbacks])\n\"\"\"\n# Plot loss progression \n\"\"\"\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Loss over epochs')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='best')\nplt.show()\n\"\"\"\n# Plot accuracy \n\"\"\"\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Accuracy over epochs')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='best')\nplt.show()\n\"\"\"\n# OK Model is ready. Now apply on test\n\"\"\"\n#Now use the model on test images\ntest_folder = os.path.join(basepath,  \"test_images\")\n\n#test_images = os.listdir(os.path.join(basepath,  \"test_images\"))\ntest_images = os.listdir(test_folder)\npredictions=[]\nfor i in test_images:\n    #image = Image.open(f'\/kaggle\/input\/cassava-leaf-disease-classification\/test_images\/{i}')\n    print(i) \n    tmp_image=os.path.join(test_folder,i)\n    print(tmp_image) \n    image = Image.open(tmp_image)\n    image = image.resize((targetSz, targetSz))\n       \n    \n    image = np.expand_dims(image, axis = 0)\n    image = image\/255.0\n    predictions.append(np.argmax(model.predict(image)))\n                       \nsubmission = pd.DataFrame({'image_id': test_images, 'label': predictions})\nsubmission\n\n\"\"\"\n# Finally submit\n\"\"\"\nsubmission.to_csv('\/kaggle\/working\/submission.csv', index = False)","meta":"{'source': 'AI4Code', 'id': '7cda88c65fa658'}"}
{"id":"136561","text":"\"\"\"\n# How to Create a Regular Expression to Extract Emoji in Python\n(Updated with version 13.1)\n\nA quick journey from the [raw emoji-test](\nhttps:\/\/unicode.org\/Public\/emoji\/13.1\/emoji-test.txt) text file, to a Python regular expression to extract all emoji. And yes, a CSV file that can be imported as a DataFrame for general use.\n\nThe dataset also provides additional functionality for emoji for the [advertools online marketing package](https:\/\/github.com\/eliasdabbas\/advertools): \n* As a DataFrame `emoji_df`\n* As a search option to search for emoji [`advertools.emoji_search`](https:\/\/advertools.readthedocs.io\/en\/master\/advertools.emoji.html)\n* One of the `extract_` functions that [extract emoji](https:\/\/advertools.readthedocs.io\/en\/master\/advertools.extract.html#advertools.extract.extract_emoji) from a text list, together with statistics about their occurences, categories, and sub-categories.\n\nHow they were extracted...\n\nI manually downloaded the file, and here we can open and inspect the first rows.\n\"\"\"\nimport re\nfrom collections import namedtuple, Counter\n\nwith open('..\/input\/emoji-data-descriptions-codepoints\/emoji-test.txt', 'rt') as file:\n    emoji_raw = file.read()\nprint(emoji_raw[:2800])\n\"\"\"\nThe first few lines explain some details about the file and how the data are represented. The remainder is like the last lines. Each line represents an emoji, and whenever there is a new group and\/or sub-group, those are listed (on a line starting with # and the name of the group\/sub-group), to show to group\/sub-group, the following emoji belong to. \n\nWe will go through the lines, one by one, and extract the information that we need and then put them in an easy-to-use format (`namedtuple`) so we can then use them to create the regex and the CSV file.  \n\nA few things about emoji that need to be understood in order to get what we want done. \n\n# Single and multi code point emoji\n\nSome emoji can simply be thought of as regular characters.\n\"\"\"\nprint('\\U00000063')  # the lower-cae letter \"c\" for example\nprint('\\U0001F44D')\n\"\"\"\nBut what about the similar emoji \ud83d\udc4d\ud83c\udfff?  \nLet's first compare the two.\n\"\"\"\nlen('\ud83d\udc4d'), len('\ud83d\udc4d\ud83c\udfff')\n\"\"\"\n# \ud83e\udd14\n\"\"\"\nprint('\ud83d\udc4d\ud83c\udfff'[0], '\ud83d\udc4d\ud83c\udfff'[1])\nimport unicodedata\nunicodedata.name('\ud83d\udc4d'), unicodedata.name('\ud83d\udc4d\ud83c\udfff'[0]), unicodedata.name('\ud83d\udc4d\ud83c\udfff'[1])\n\"\"\"\nThe generic yellow-colored emoji is basically one character. The others (with different skin tones), are two characters; the first is the same generic emoji, and the second is simply a coloring square. There are five skin tones available. \n\n# Long and short words in regular expressions \nAn important aspect of how regular expressions find their matches is that they are \"greedy\" (this mainly applies to regex-directed, and not text directed regex engines, which is what Python uses). One of the things that this means, is that when presented with several options, the regex is happy to find the first match and return it.  \nLet's say you want to find the words \"rest\", and \"restaurant\" in a document.  \nThe regex is striaghtforward. `rest|restaurant`. \nLet's see greediness in action:\n\"\"\"\ns = 'The rest of my friends are at the restaurant.'\nregex = re.compile('rest|restaurant')\nregex.findall(s)\n\"\"\"\nThe regex goes through the options from left to right, and returns the match if it finds one immediately. In this example, it found a match for \"rest\" in the second word of the sentence, and then found another match for \"rest\" in the last word. After finding the second match, the regex is now at the first \"a\" in \"restaurant\", because the regex has already 'consumed' the \"rest\" part of \"restaurant\".  \nIn a large text, you would get the false impression that there is no occurrence of the word \"restaurant\". The fix is easy. We simply put the long word(s) first, so the regex can check for their matches first. If it doesn't find a match (as it won't find in the first \"rest\"), then the regex will go on to try to match the second available option.\n\"\"\"\nregex2 = re.compile('restaurant|rest')\nregex2.findall(s)\nthumbs_sentence = 'This is thumbs up: \ud83d\udc4d, and this is thumbs up with dark skin tone: \ud83d\udc4d\ud83c\udfff'\nthumbs_regex = re.compile('\ud83d\udc4d|\ud83d\udc4d\ud83c\udfff')\n\nthumbs_regex.findall(thumbs_sentence)\nthumbs_regex2 = re.compile('\ud83d\udc4d\ud83c\udfff|\ud83d\udc4d')\nthumbs_regex2.findall(thumbs_sentence)\n\"\"\"\nSince the dark tone thumbs up emoji is made up of two code points, and since the first one is made of one, we are faced with the same case of \"rest\" and \"restaurant\". The regex finds the first word from left to right, and returns it. As in the previous example, putting the longer word first, made sure that we check for it first, and solves the issue. \n\n\nHere are the two emoji represented by code points. You can see that the first part of each of the 'words' is the same. \n\"\"\"\nprint('\\U0001F44D', '\\U0001F44D\\U0001F3FF')  # the U0001F44D code point exists in both\n\"\"\"\nThere are five skin tones, as well as four hair types. All of those fall under the group \"component\". Those emoji are not supposed to appear on their own, because they really don't mean anything. They function mainly as modifiers for the previous emoji, appearing right before them.  \nHere they are, and we will be skipping them when creating the final regex. \n\"\"\"\nfor i, line in enumerate(emoji_raw.splitlines()):\n    if '; component' in line:\n        print(i, line)\n\"\"\"\nNow we create the data structure that will hold our emoji entries. We will use the `namedtuple` because it has a nice representation, telling us exactly what each element means, as well as giving us the ability to extract those elements by name, using dot notation `entry.name` or `entry.group` for example. \n\"\"\"\nEmojiEntry = namedtuple('EmojiEntry', ['codepoint', 'status', 'emoji', 'name', 'group', 'sub_group'])\n\"\"\"\nThe following code goes through lines one by one, extracting the information that is needed, and appending each entry to `emoji_entries` which will be a list containing all of them.  \nI have annotated the code with some comments, and below elaborated a little more to clarify.\n\"\"\"\nE_regex = re.compile(r' ?E\\d+\\.\\d+ ') # remove the pattern E<digit(s)>.<digit(s)>\nemoji_entries = []\n\nfor line in emoji_raw.splitlines()[32:]:  # skip the explanation lines\n    if line == '# Status Counts':  # the last line in the document\n        break\n    if 'subtotal:' in line:  # these are lines showing statistics about each group, not needed\n        continue\n    if not line:  # if it's a blank line\n        continue\n    if line.startswith('#'):  # these lines contain group and\/or sub-group names\n        if '# group:' in line:\n            group = line.split(':')[-1].strip()\n        if '# subgroup:' in line:\n            subgroup = line.split(':')[-1].strip()\n    if group == 'Component':  # skin tones, and hair types, skip, as mentioned above\n        continue\n    if re.search('^[0-9A-F]{3,}', line):  # if the line starts with a hexadecimal number (an emoji code point)\n        # here we define all the elements that will go into emoji entries\n        codepoint = line.split(';')[0].strip()  # in some cases it is one and in others multiple code points\n        status = line.split(';')[-1].split()[0].strip() # status: fully-qualified, minimally-qualified, unqualified\n        if line[-1] == '#':\n            # The special case where the emoji is actually the hash sign \"#\". In this case manually assign the emoji\n            if 'fully-qualified' in line:\n                emoji = '#\ufe0f\u20e3'\n            else:\n                emoji = '#\u20e3'  # they look the same, but are actually different \n        else:  # the default case\n            emoji = line.split('#')[-1].split()[0].strip()  # the emoji character itself\n        if line[-1] == '#':  # (the special case)\n            name = '#'\n        else:  # extract the emoji name\n            split_hash = line.split('#')[1]\n            rm_capital_E = E_regex.split(split_hash)[1]\n            name = rm_capital_E\n        templine = EmojiEntry(codepoint=codepoint,\n                              status=status,\n                              emoji=emoji,\n                              name=name,\n                              group=group,\n                              sub_group=subgroup)\n        emoji_entries.append(templine)\n\nemoji_dict = {x.emoji: x for x in emoji_entries}\nemoji_dict['\ud83d\ude06'].emoji\nemoji_entries[0]\nemoji_entries[0].emoji\nemoji_entries[0].group, emoji_entries[0].sub_group\n\"\"\"\nHere is a quick summary of the counts of the groups, sub-groups, and all group\/sub-group combinations:\n\"\"\"\nCounter([x.group for x in emoji_entries])\nsorted(Counter([x.sub_group for x in emoji_entries]).items(), key=lambda x: x[1], reverse=True)[:30]\nCounter([' | '.join([x.group, x.sub_group]) for x in emoji_entries])\n\"\"\"\n## Emoji status\nIn case you are wondering about the status column, this is the explanation from the\n[Unicode official documentation:](http:\/\/unicode.org\/reports\/tr51\/#def_qualified_emoji_character) \n\n>ED-17a. qualified emoji character \u2014 An emoji character in a string that (a) has default emoji presentation or (b) is the first character in an emoji modifier sequence or (c) is not a default emoji presentation character, but is the first character in an emoji presentation sequence.  \n>ED-18. fully-qualified emoji \u2014 A qualified emoji character, or an emoji sequence in which each emoji character is qualified.  \n>ED-18a. minimally-qualified emoji \u2014 An emoji sequence in which the first character is qualified but the sequence is not fully qualified.  \n>ED-19. unqualified emoji \u2014 An emoji that is neither fully-qualified nor minimally qualified.\n\"\"\"\n\"\"\"\nAs mentioned above, we need to handle single and multiple code point emoji slightly differently.  \nWe start by extracting the multi code points.\n\"\"\"\nmulti_codepoint_emoji = []\n\nfor code in [c.codepoint.split() for c in emoji_entries]:\n    if len(code) > 1:\n        # turn to a hexadecimal number zfilled to 8 zeros e.g: '\\U0001F44D'\n        hexified_codes = [r'\\U' + x.zfill(8) for x in code]  \n        hexified_codes = ''.join(hexified_codes)  # join all hexadecimal components \n        multi_codepoint_emoji.append(hexified_codes)\n\n# sorting by length in decreasing order is extremely important as demonstrated above\nmulti_codepoint_emoji_sorted = sorted(multi_codepoint_emoji, key=len, reverse=True)\n\n# join with a \"|\" to function as an \"or\" in the regex\nmulti_codepoint_emoji_joined = '|'.join(multi_codepoint_emoji_sorted)  \nmulti_codepoint_emoji_joined[:400]  # sample\nsingle_codepoint_emoji = []\n\nfor code in [c.codepoint.split() for c in emoji_entries]:\n    if len(code) == 1:\n        single_codepoint_emoji.append(code[0])\n\"\"\"\n# Regex character ranges\n\nSince the single code point emoji are basically one character each, they can be treated as normal letters or numbers in the regex.  \nOne important feature of character classes is their ability to contain character ranges. \nIf I want to match a character that falls between A and F, there are two ways to define the character class: \n\n- `[ABCDEF]`\n- `[A-F]`\n\nThey effectively mean the same thing. The advantage of the second is that it is much more readable (imagine wanting to match the letters from A to T for example). It would be very difficult to read through and understand which letters are included. `[A-T]` is very easy to read.  \nI also believe there might be a slight performance boost with character ranges. Some regex engines do certain optimizations on their own, and I'm not aware of those details. But in general making two comparisons is way more efficient than making fifty.  \nFor example, you have the number 42, and want to check if it falls between 1 and 100. \nIn the character class case, you make to comparisons. You check if 42 >= 1 and 42 <=100.  \nIf you have all the numbers listed from 1 to 100, then you will have to make 42 comparisons to find out. On average, if you have a range of 100 numbers, you will be making fifty comparisons to find out. With larger ranges, this can obviously go very big.  \n\nBelow is the function `get_ranges`. It takes a list of integers, and returns a list of tuples, each representing the local minimum and maximum for any number of contiguous integers (numbers differing by 1).  \nFor example if I have the list `[1, 2, 3, 4, 6 7, 8, 10, 20]`, it will return `[(1, 4), (6, 8), (10, 10), (20, 20)]`\n\nThe numbers 1, 2, 3, and 4, can converted into a character range `[1-4]`, so do the numbers 6, 7, and 8. 10 and 20 are not part of a series of integers differing by one, so they are represented as single-number ranges. Later they will be used as single characters in the regex.\n\"\"\"\ndef get_ranges(nums):\n    \"\"\"Reduce a list of integers to tuples of local maximums and minimums.\n\n    :param nums: List of integers.\n    :return ranges: List of tuples showing local minimums and maximums\n    \"\"\"\n    nums = sorted(nums)\n    lows = [nums[0]]\n    highs = []\n    if nums[1] - nums[0] > 1:\n        highs.append(nums[0])\n    for i in range(1, len(nums)-1):\n        if (nums[i] - nums[i-1]) > 1:\n            lows.append(nums[i])\n        if (nums[i + 1] - nums[i]) > 1:\n            highs.append(nums[i])\n    highs.append(nums[-1])\n    if len(highs) > len(lows):\n        lows.append(highs[-1])\n    return [(l, h) for l, h in zip(lows, highs)]\n# We first convert single_codepoint_emoji to integers to make calculations easier\nsingle_codepoint_emoji_int = [int(x, base=16) for x in single_codepoint_emoji]\nsingle_codepoint_emoji_ranges = get_ranges(single_codepoint_emoji_int)\nsingle_codepoint_emoji_ranges[:10]\nsingle_codepoint_emoji_raw = r''  # start with an empty raw string\nfor code in single_codepoint_emoji_ranges:\n    if code[0] == code[1]:  # in this case make it a single hexadecimal character\n        temp_regex =  r'\\U' + hex(code[0])[2:].zfill(8)\n        single_codepoint_emoji_raw += temp_regex\n    else:\n        # otherwise create a character range, joined by '-'\n        temp_regex = '-'.join([r'\\U' + hex(code[0])[2:].zfill(8), r'\\U' + hex(code[1])[2:].zfill(8)])\n        single_codepoint_emoji_raw += temp_regex\n\nsingle_codepoint_emoji_raw[:100]  # sample\n\"\"\"\n# Final regex\nNow that we have created our sorted multi-code point characters, and generated the ranges for the single-code point emoji, we need to combine them together.  \nThe regex wil start with the longer 'words', which are emoji, represented by more than one character. These have already been sorted by length, in descending order. \nSingle-code point emoji have already been made into a character class, where some values are single characters, and some are character ranges. \n\nThe final regex will look something like this: \n\n`multi_code_point_emoji|[character_class_of_single_code_points]`\n\nIn more detail, this is how the first `multi_code_point_emoji` part will look like:\n\n`longest_multi_code_point|shorter_multiple_code_point|...|shortest_multiple_code_point`\n\nThis is how the character class part `[character_class_of_single_code_points]` will look like: \nFor simplicity I refer to `single_code_point` as `sp`. \n\n`[sp1sp2sp3sp4-sp20sp25sp500-sp600]` and so on. \n\nBelow we concatenate both regexes into one, and show the first and last 500 characters as a sample. \n\"\"\"\nall_emoji_regex = re.compile(multi_codepoint_emoji_joined + '|' +  r'[' + single_codepoint_emoji_raw + r']')\nall_emoji_regex.pattern[:500], all_emoji_regex.pattern[-500:]\n\"\"\"\n# Testing\nWe need to know that our work is correct. It is easy to get it wrong, especially when we are talking about 3k+ characters, and especially that many of them are combinations of the others. \n\nAs a quick sanity check, let see how many characters were actually in the initial text file. Each emoji entry contained a semicolon, so let's count those: \n\"\"\"\n\"\"\"\n![](https:\/\/drive.google.com\/uc?id=1cR0fsIlSFjT5yNz9QbJ-_BpcoqbSuWgE)\n\"\"\"\n\"\"\"\n* There are 4,591 semicolons in the file. One of them is part of the explanation on the first line, and remember that there were nine characters that we omitted, because they were basically modifiers. So the final number should be 4,591 - 1 - 9 = 4,581. \n\nNow we run `findall` by the combined final regex on a string that we create.  \nThis string is all the emoji characters in `emoji_entries` separated by spaces. Their number needs to be exactly 4,581. \n\"\"\"\nall_emoji_regex.findall(' '.join([x.emoji for x in emoji_entries])).__len__()\n\"\"\"\nSo far so good. Let's get some more assurance.\n\nThe code below goes through all the lines of the raw text file, as downloaded from the Unicode site.  \nFirst we define `count` as zero, and increment its value, every time we find a new match. This should add up to the same number 3,287.  \nWe also create a set `found_emoji` where we add every emoji we find to it. If we match a certain emoji more than once and add it to the set, it will be discarded, because sets only contain unique values. Again the length of this set, should be equal to our magic number. If not, it means we found duplicates. Or it means we are matching other things, if we get a higher number. \n\nLines 6-8 check if the length of the match is more than one, meaning the regex found more than one match in the line. We might be wrongly matching something more than once. It actually broke a few times, when I first ran it, until I fixed the issues.  \nOne final test is asserting that the name of the emoji (which we extract from `emoji_entries` is contained in the line in the raw text file, making sure that the names also correspond to the correct value, and extracted correctly. \n\"\"\"\ncount = 0\nfound_emoji = set()\nfor line in emoji_raw.splitlines()[30:]:\n    match = all_emoji_regex.findall(line)\n    if match:\n        if len(match) > 1:\n            break\n        count += 1\n        found_emoji.add(match[0])\n        temp_name = [x.name for x in emoji_entries if x.emoji == match[0]][0]\n        assert temp_name in line\n\ncount, found_emoji.__len__()\n\"\"\"\n## \ud83c\udf89 \ud83c\udf89 \ud83c\udf89 \ud83c\udf8a \ud83c\udf8a \ud83c\udf8a \ud83d\udc4d \ud83d\udc4f \ud83d\ude09\n\nTo save as a DataFrame, we can run the following code.  \nI made it semicolon-separated, as there were commas in the descriptions so this is easier. The I let `pandas` do the heavy lifting of converting back to comma-separated format. \n\"\"\"\nwith open('emoji_df.csv', 'wt') as file:\n    print('emoji;name;group;sub_group;codepoints', file=file)\n    for i, em in enumerate(emoji_entries):\n        print(f\"{em.emoji};{em.name};{em.group};{em.sub_group};{em.codepoint}\", file=file)\nimport pandas as pd\npd.options.display.max_columns = None\n\nemoji_df = pd.read_csv('emoji_df.csv', sep=';')\nemoji_df.to_csv('emoji_df.csv', index=False)\nemoji_df = pd.read_csv('emoji_df.csv')\nemoji_df[:35]\n\"\"\"\n# Emoji in Real-life Data\nLet's see how we can use this regex on a tweet dataset containing five thousand tweets that contain the hashtag #JustDoIt.\n\"\"\"\njustdoit = pd.read_csv('..\/input\/5000-justdoit-tweets-dataset\/justdoit_tweets_2018_09_07_2.csv')\njustdoit.head(3)\n\"\"\"\nThe `word_frequency` function in `advertools` extracts words and counts their occurrences on an absolute and weighted basis. The function takes an optional `regex` parameter, whereby the function counts occurrences of matches of the regex (and not all words).  \nWe can now use the regex created, to extract and count emoji in our dataset. \n\"\"\"\nimport advertools as adv\njustdoit_emoji_freq = (adv.word_frequency(justdoit['tweet_full_text'],\n                                          justdoit['user_followers_count'],\n                                          regex=all_emoji_regex.pattern))\njustdoit_emoji_freq.head(15)\n\"\"\"\nThe `abs_freq` column shows how many times each emoji was used (simply count). While `wtd_freq` counts the number of followers of the person who tweeted the tweet for each occurrence.  \nIn sample above you can see the monkey emoji being used only once, but since the user who tweeted has 2.9M followers, it has the highest `wtd_freq` of all emoji.  \n\nUsing the emoji_dict that we created we can show names, groups, and sub-groups of each emoji:\n\"\"\"\njustdoit_emoji_freq['name'] = [emoji_dict[word].name if word != '\ufe0f' else '' for word in justdoit_emoji_freq['word']]\njustdoit_emoji_freq['group'] = [emoji_dict[word].group if word != '\ufe0f' else '' for word in justdoit_emoji_freq['word']]\njustdoit_emoji_freq['sub_group'] = [emoji_dict[word].sub_group if word != '\ufe0f' else '' for word in justdoit_emoji_freq['word']]\njustdoit_emoji_freq[:40]\n\"\"\"\nThe previous table shows the frequencies per emoji.  \nWhat about the groups and sub-groups? \n\nWe do this next: \n\"\"\"\n(justdoit_emoji_freq\n .groupby('group')\n .agg({'abs_freq': 'sum', 'wtd_freq': 'sum'})\n .sort_values('wtd_freq', ascending=False)\n .style.format({'wtd_freq': '{:,.0f}'}))\n\"\"\"\nNote here that again, even though \"Smileys & Emotion\" emoji have been used 1,440 times and \"Animals & Nature\" only 38, the latter still ranks higher on a weighted basis.  \nThis is typical on social media. We often get a dataset that gets skewed by one tweet\/user. \n\"\"\"\n(justdoit_emoji_freq\n .groupby('sub_group')\n .agg({'abs_freq': 'sum', 'wtd_freq': 'sum'})\n .sort_values('wtd_freq', ascending=False)\n .head(20)\n .style.format({'wtd_freq': '{:,.0f}'}))","meta":"{'source': 'AI4Code', 'id': 'fb03454ff662a7'}"}
{"id":"52081","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import spearmanr\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.model_selection import KFold,cross_val_score\nfrom collections import Counter\nfrom sklearn.preprocessing import MinMaxScaler\ntrain=pd.read_csv(\"..\/input\/train.csv\")\ntest=pd.read_csv(\"..\/input\/test.csv\",usecols=['ID'])\ntest['ID'].unique()\nsample_submission=pd.read_csv(\"..\/input\/sample_submission.csv\")\n# separate array into input and output components\narray = train.values\nX = array[:,1:4992]\nY = array[:,4992]\nseed=7\n\"\"\"\n<h1> 2. Understand Data with Descriptive Stats<\/h1>\n<h4>In this dataset there are 3 different types of datatypes int64,float64 and object<\/h4>\n\"\"\"\n#Check the datatypes we have\nm=train.dtypes\nCount=Counter(m).most_common()\nprint(Count)\n# Load train dataset\nprint(train.head(10))\nprint('The Data in train is : {}'.format(train.shape))\n# Load test dataset\nprint(test.head(5))\nprint('The Data in test is : {}'.format(test.shape))\ntrain.dropna()\n\"\"\"\n<h1> 3.Visualization of Data <\/h1>\n\"\"\"\nplt.scatter(X[:,0], X[:,1], c='m')\nplt.show()\n\"\"\"\n<h1> 4. Prepare for  Modeling by Pre-Processing Data <\/h1>\n\"\"\"\nmin_max_scaler = MinMaxScaler()\nX_train_minmax = min_max_scaler.fit_transform(X)\nprint(X_train_minmax)\n\"\"\"\n<h4>It is possible to introspect the scaler attributes to find about the exact nature of the transformation learned on the training data:<\/h4>\n\"\"\"\nmin_max_scaler.scale_\nmin_max_scaler.min_  \n\"\"\"\n<h1>5. Spearman\u2019s Rank Correlation<\/h1>\nWe can demonstrate the Spearman\u2019s rank correlation on the test dataset. We know that there is a strong association between the variables in the dataset and we would expect the Spearman\u2019s test to find this association.\n\"\"\"\n# Calculate the spearman's correlation between two variables\n# prepare data\n# Select the random column from the train.csv\ndata1=train.iloc[:,[10]]\ndata2=train.iloc[:,[12]]\n# calculate spearman's correlation\ncoef,p=spearmanr(data1,data2)\nprint('Spearmans coefficient : %3f'%coef) \n# interpret the significance\nif(p>0.05):\n    print('Sample are uncorrelated (fail to reject Ho) p= %3f'%p) \nelse:\n    print('Sample are correlated (reject Ho) p=%3f'%p) \nkfold=KFold(n_splits=10,random_state=seed)\nmodel=KNeighborsRegressor()\nscoring='neg_mean_squared_error'\nresults=cross_val_score(model,X,Y,cv=kfold,scoring=scoring)","meta":"{'source': 'AI4Code', 'id': '5fdc2df9d76536'}"}
{"id":"113131","text":"\"\"\"\nThe Acea Group is one of the leading Italian multiutility operators. Listed on the Italian Stock Exchange since 1999, the company manages and develops water and electricity networks and environmental services. Acea is the foremost Italian operator in the water services sector supplying 9 million inhabitants in Lazio, Tuscany, Umbria, Molise, Campania.\n\nIn this competition Kagglers were asked to focus on the water sector to help Acea Group preserve precious waterbodies such as water springs, lakes, rivers, and aquifers. To help preserve the health of these waterbodies it is important to predict the water availability in terms of level and water flow for each day\/month of the year.\n\nIn the following sections, I would like to show my work on the prediction of water availabilities and its accuracies in terms of mean absolute error, mean squared error, and R^2 beween obervation and prediction values.\n\"\"\"\n\"\"\"\n# Content:\n\n1. Loading Data\n2. Visulization of Data\n3. Data imputation\n4. Exploratory Analysis and Feature Engineering\n5. Prediction\n\"\"\"\n# import libraries that will be used in the analysis\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n# 1. Loading Data\n\"\"\"\n# loading all data into a list structure\nfiles=os.listdir('..\/input\/acea-water-prediction')\nprint(files)\n# read cvs data files\nAquifer_Doganella=pd.read_csv('..\/input\/acea-water-prediction\/'+'Aquifer_Doganella.csv')\nAquifer_Auser=pd.read_csv('..\/input\/acea-water-prediction\/'+'Aquifer_Auser.csv')\nWater_Spring_Amiata=pd.read_csv('..\/input\/acea-water-prediction\/'+'Water_Spring_Amiata.csv')\nLake_Bilancino=pd.read_csv('..\/input\/acea-water-prediction\/'+'Lake_Bilancino.csv')\nWater_Spring_Madonna_di_Canneto=pd.read_csv('..\/input\/acea-water-prediction\/'+'Water_Spring_Madonna_di_Canneto.csv')\nAquifer_Luco=pd.read_csv('..\/input\/acea-water-prediction\/'+'Aquifer_Luco.csv')\nAquifer_Petrignano=pd.read_csv('..\/input\/acea-water-prediction\/'+'Aquifer_Petrignano.csv')\nWater_Spring_Lupa=pd.read_csv('..\/input\/acea-water-prediction\/'+'Water_Spring_Lupa.csv')\nRiver_Arno=pd.read_csv('..\/input\/acea-water-prediction\/'+'River_Arno.csv')\n# combine data into datasets\ndatasets = [Aquifer_Doganella,Aquifer_Auser,Water_Spring_Amiata,Lake_Bilancino,Water_Spring_Madonna_di_Canneto,\n           Aquifer_Luco,Aquifer_Petrignano,Water_Spring_Lupa,River_Arno]\ndatasets_names=['Aquifer_Doganella.csv', 'Aquifer_Auser.csv', 'Water_Spring_Amiata.csv', 'Lake_Bilancino.csv', 'Water_Spring_Madonna_di_Canneto.csv', 'Aquifer_Luco.csv', 'Aquifer_Petrignano.csv', 'Water_Spring_Lupa.csv', 'River_Arno.csv']\n\"\"\"\n# 2. Visulization of Data \n\n\"\"\"\n#boxplot of all variables in each file to examine data range and distribution\nfig,ax1 = plt.subplots(3,3,figsize=(15,15))\nfor i in range(len(datasets)):\n    ax1.flatten()[i].set_title(datasets_names[i][:-4])\n    datasets[i][datasets[i].columns[1:]].boxplot(ax=ax1.flatten()[i],rot=90)\nplt.tight_layout()\n    \n\"\"\"\n**Observation 1\uff1a**Data visulization using boxplot tells what variables are included in each data file and how responsive varibles and predictive variables are distributed. However, variable values are not at same scale (e.g. rainfall in mm, flow rate in cubic meter per sencond, and volume in cubic meter) which make it hard to fully view the distributions. Further data analysis including correlation, exploratory factor, and feature engineering are necessary. \n\"\"\"\n\"\"\"\n# 3.Data imputation and missing value treatment \nThere are a lot of missing values in the daily time series. for example the water use vollumes are mostly missing and they are hard to be replaced with meaningful values. In this analysis, monthly data were firstly grouped by from daily values and then monthly means were used to replace mising values\n\"\"\"\n# define a function to plot features vs. target variables\ndef plot1(inputdata,features,target_var,ylabel1,ylabel2):\n    fig, ax1= plt.subplots(figsize=(15,5))\n    #inputdata['Year-mon']=pd.to_datetime(inputdata['Year-mon'])\n    ax1.bar(inputdata['Year-mon'],inputdata[features])\n    ax1.spines['left'].set_color('blue')\n    ax1.spines['left'].set_linewidth(3)\n    ax1.legend([features],loc=2)\n    ax2 =ax1.twinx()\n    ax2.plot(inputdata['Year-mon'],inputdata[target_var],color='red')\n    ax2.spines['right'].set_color('red')\n    ax2.spines['right'].set_linewidth(3)\n    ax1.set_ylabel(ylabel1)\n    ax1.set_xticks(range(0,len(inputdata),10))\n    ax1.set_xticklabels(inputdata['Year-mon'][range(0,len(inputdata),10)],rotation=90)\n    ax2.set_ylabel(ylabel2)\n    ax2.set_xticks(range(0,len(inputdata),10))\n    ax2.set_xticklabels(inputdata['Year-mon'][range(0,len(inputdata),10)],rotation=90)\n    ax2.legend([target_var[0]],loc=1)\n\n# transform daily data into montly data using groupby\nfor i in range(len(datasets)): \n  datasets[i].drop(datasets[i][datasets[i].Date.isnull()].index,inplace = True,axis=0)\n  datasets[i]['Year-mon']=pd.to_datetime(datasets[i].Date).apply(lambda x: x.strftime('%Y-%m'))\ndatasets_monthly = [datasets[i].groupby('Year-mon').mean().reset_index() for i in range(len(datasets))]\n\ntarget_var=['Depth_to_Groundwater_Pozzo_1', 'Depth_to_Groundwater_Pozzo_2',\n       'Depth_to_Groundwater_Pozzo_3', 'Depth_to_Groundwater_Pozzo_4',\n       'Depth_to_Groundwater_Pozzo_5', 'Depth_to_Groundwater_Pozzo_6',\n       'Depth_to_Groundwater_Pozzo_7', 'Depth_to_Groundwater_Pozzo_8',\n       'Depth_to_Groundwater_Pozzo_9', ]\nplot1(datasets_monthly[0],'Rainfall_Monteporzio',target_var,'Rainfall, mm','Groundwater Level, m')\nplot1(datasets_monthly[0],'Volume_Pozzo_9',['Depth_to_Groundwater_Pozzo_9'],'Volume cm','Groundwater Level, m')\n\"\"\"\n**Observation 2:** Relative dry years (less rainfall) appeared in 2015-2017, which seems to cause well water depth droped, especially at wells Pozzo_1 and Pozzo_9. While water usage seems not to be very important in water depth drops as there is some cooccurence between less water usage and greater water depth drop at the well Pozzo_9. Of course, these are just observation for occasion wells at their occasion times. More important info about important features can be seen later in prediction and feature importance analysis.\n\"\"\"\n\"\"\"\n# 4. Exploratory Analysis and Feature Engineering\n\"\"\"\n# create a season variable to see if it can help improve prediction\nfor i in range(len(datasets_monthly)):\n    datasets_monthly[i].loc[datasets_monthly[i]['Year-mon'].str.split('-').str[1].str.contains('12|01|02'),'season']=1\n    datasets_monthly[i].loc[datasets_monthly[i]['Year-mon'].str.split('-').str[1].str.contains('03|04|05'),'season']=2\n    datasets_monthly[i].loc[datasets_monthly[i]['Year-mon'].str.split('-').str[1].str.contains('06|07|08'),'season']=3\n    datasets_monthly[i].loc[datasets_monthly[i]['Year-mon'].str.split('-').str[1].str.contains('09|10|11'),'season']=4\n# create a dryness variable based on rainfall amount\nfor i in range(len(datasets_monthly)):\n    datasets_monthly[i].loc[datasets_monthly[i].iloc[:,1]>(datasets_monthly[i].iloc[:,1].mean()+datasets_monthly[i].iloc[:,1].std()),'dryness']=4\n    datasets_monthly[i].loc[(datasets_monthly[i].iloc[:,1]<=(datasets_monthly[i].iloc[:,1].mean()+datasets_monthly[i].iloc[:,1].std())) & (datasets_monthly[i].iloc[:,1]>datasets_monthly[i].iloc[:,1].mean()),'dryness']=3\n    datasets_monthly[i].loc[(datasets_monthly[i].iloc[:,1]>=(datasets_monthly[i].iloc[:,1].mean()-datasets_monthly[i].iloc[:,1].std())) & (datasets_monthly[i].iloc[:,1]<=datasets_monthly[i].iloc[:,1].mean()),'dryness']=2\n    datasets_monthly[i].loc[datasets_monthly[i].iloc[:,1]<(datasets_monthly[i].iloc[:,1].mean()-datasets_monthly[i].iloc[:,1].std()),'dryness']=1\n\"\"\"\n# 5. Predictive Accuracy and Feature Importance**\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score\nf,ax3 = plt.subplots(9,2,figsize=(10,50))\n# setup target variabe list\ntarget_var = [[col for col in datasets_monthly[0].columns if 'Depth' in col]]\ntarget_var.append([col for col in datasets_monthly[1].columns if 'Depth' in col])\ntarget_var.append([col for col in datasets_monthly[2].columns if 'Flow_Rate' in col])\ntarget_var.append([col for col in datasets_monthly[3].columns if 'Lake' in col])\ntarget_var.append([col for col in datasets_monthly[4].columns if 'Flow_Rate' in col])\ntarget_var.append([col for col in datasets_monthly[5].columns if 'Depth' in col])\ntarget_var.append([col for col in datasets_monthly[6].columns if 'Depth' in col])\ntarget_var.append([col for col in datasets_monthly[7].columns if 'Flow_Rate' in col])\ntarget_var.append([col for col in datasets_monthly[8].columns if 'Hydrometry' in col])\n# create a dataframe to store prediction results\nstats_index=[datasets_names[j][:-4]+': '+item for j, sublist in enumerate(target_var) for item in sublist]\nstats = pd.DataFrame(columns=['MSE','MAE','R-Squared','Top 3 important features'],index=stats_index)\nfor j in range(len(target_var)):\n    for i,target in enumerate(target_var[j]):\n        #select non-null values of responsive variable and imputing nan values of predictive variables by mean\n        idx1 = datasets_monthly[j][target].notnull()\n        data = datasets_monthly[j][idx1].fillna(datasets_monthly[j][idx1].mean())\n        x = data.drop(target_var[j],axis=1)\n        x = x.drop('Year-mon',axis=1)\n        y = data[target]\n        x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3)\n        np.random.seed(1234)\n        RFG = RandomForestRegressor(n_estimators=20,random_state=0)\n        RFG.fit(x_train,y_train)\n        importance = RFG.feature_importances_\n        # output statistics of prediction\n        stats.loc[f'{datasets_names[j][:-4]}: {target}','MSE']=f'{mean_squared_error(y_test,RFG.predict(x_test)):.3f}'\n        stats.loc[f'{datasets_names[j][:-4]}: {target}','MAE']=f'{mean_absolute_error(y_test,RFG.predict(x_test)):.3f}' \n        stats.loc[f'{datasets_names[j][:-4]}: {target}','R-Squared']=f'{r2_score(y_test,RFG.predict(x_test)):.3f}'\n        stats.loc[f'{datasets_names[j][:-4]}: {target}','Top 3 important features']= [list(x.columns[np.argsort(importance)[::-1][:3]])]\n        # give an example of prediction in visulization\n        if j == 0:\n            ax3[i,0].plot(y_test,RFG.predict(x_test),'.')\n            ax3[i,0].plot(np.linspace(np.amin(y_test),np.amax(y_test),100),np.linspace(np.amin(y_test),np.amax(y_test),100),'k')\n            ax3[i,0].set_ylabel('Predicted')\n            ax3[i,0].set_xlabel('Observed')\n            ax3[i,0].text(np.min(y_test),np.max(y_test)-1,f'MSE: {mean_squared_error(y_test,RFG.predict(x_test)):.3f}')\n            ax3[i,0].text(np.min(y_test),np.max(y_test)-2,f'MAE: {mean_absolute_error(y_test,RFG.predict(x_test)):.3f}')\n            ax3[i,0].text(np.min(y_test),np.max(y_test)-3,f'R-Squared: {r2_score(y_test,RFG.predict(x_test)):.3f}' )\n            ax3[i,0].set_title(f'{target}, meter')   \n            ax3[i,1].bar(range(len(importance)),importance)\n            ax3[i,1].set_xticks(range(len(importance)))\n            ax3[i,1].set_xticklabels(x.columns,rotation=90)\n            ax3[i,1].set_ylabel('Importance')\n    plt.tight_layout()\n\"\"\"\n# 6. Statistics of prediction\n\"\"\"\nstats\n\nstats.to_csv('final_stats.csv')","meta":"{'source': 'AI4Code', 'id': 'cfdaadbfd602e7'}"}
{"id":"121864","text":"import numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nimport seaborn as sns\nsns.set()\n\"\"\"\n## Step 1: Data Cleaning\n\n### Loading the raw data\n\"\"\"\nraw_data = pd.read_csv('..\/input\/used-cars-price\/Used Car Price.csv')\nraw_data.head()\nraw_data.describe(include='all')\n\"\"\"\n### Determining the variables of interest\n\"\"\"\ndata = raw_data.drop(['Model'],axis=1)\ndata.describe(include='all')\n\"\"\"\n### Dealing with missing values\n\"\"\"\ndata.isnull().sum()\ndata_no_mv = data.dropna(axis=0)\ndata_no_mv.describe(include='all')\n\"\"\"\n### Exploring the PDFs\n\"\"\"\nsns.kdeplot(data_no_mv['Price'], shade = True)\n\"\"\"\n### Dealing with outliers\n\"\"\"\nq = data_no_mv['Price'].quantile(0.99)\ndata_1 = data_no_mv[data_no_mv['Price']<q]\ndata_1.describe(include='all')\nsns.kdeplot(data_1['Price'], shade = True)\nsns.kdeplot(data_no_mv['Mileage'], shade = True)\nq = data_1['Mileage'].quantile(0.99)\ndata_2 = data_1[data_1['Mileage']<q]\nsns.kdeplot(data_2['Mileage'], shade = True)\nsns.kdeplot(data_no_mv['EngineV'], shade = True)\ndata_3 = data_2[data_2['EngineV']<6.5]\nsns.kdeplot(data_3['EngineV'], shade = True)\nsns.kdeplot(data_no_mv['Year'], shade = True)\nq = data_3['Year'].quantile(0.01)\ndata_4 = data_3[data_3['Year']>q]\nsns.kdeplot(data_4['Year'], shade = True)\ndata_cleaned = data_4.reset_index(drop=True)\ndata_cleaned.describe(include='all')\n\"\"\"\n## Step 2: Checking the Regression Assumptions\n![download.png](attachment:087237df-65d2-4c82-b3b5-9e797fa05038.png)\n\"\"\"\n\"\"\"\n### 1- Linearity\n\"\"\"\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize =(15,3))\n\nax1.scatter(data_cleaned['Year'],data_cleaned['Price'])\nax1.set_title('Price and Year')\n\nax2.scatter(data_cleaned['EngineV'],data_cleaned['Price'])\nax2.set_title('Price and EngineV')\n\nax3.scatter(data_cleaned['Mileage'],data_cleaned['Price'])\nax3.set_title('Price and Mileage')\n\nplt.show()\nlog_price = np.log(data_cleaned['Price'])\ndata_cleaned['log_price'] = log_price\ndata_cleaned\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=False, figsize =(15,3))\n\nax1.scatter(data_cleaned['Year'],data_cleaned['log_price'])\nax1.set_title('Log Price and Year')\n\nax2.scatter(data_cleaned['EngineV'],data_cleaned['log_price'])\nax2.set_title('Log Price and EngineV')\n\nax3.scatter(data_cleaned['Mileage'],data_cleaned['log_price'])\nax3.set_title('Log Price and Mileage')\n\n\nplt.show()\ndata_cleaned_2 = data_cleaned.drop(['Price'],axis=1)\n\"\"\"\n### 2- No Endogeneity\nWe will talk about this issue later.\n\nKeyWords: Hausman test, IV, 2SLS, GMM, ...\n\nSee the following link:\n\nA good example: https:\/\/python.quantecon.org\/ols.html#Endogeneity\n\nHow we can intrpret our results: https:\/\/stats.stackexchange.com\/questions\/210696\/how-to-interpret-hausman-test-results\n\nDocumentations of linearmodels library: https:\/\/bashtage.github.io\/linearmodels\/doc\/iv\/introduction.html\n\n### 3- Normality and Homoscedasticity\nJust check the above graphs. Since intercept has been included in our model, so the mean of error is ZERO.\n\n### 4- No Autocorrelation\nWe should not be worry, because our data is not a time series data or a panel data.\n\n### 5- No Multicollinearity\nVIF (Variance Inflation Factor) and its application in detecting Multicollinearity\nIf VIF > 10, then multicollinearity is high and we should remove that item.\n\"\"\"\ndata_cleaned_2.columns\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nvariables = data_cleaned_2[['Mileage','Year','EngineV']]\n\nvif = pd.DataFrame()\n\nvif[\"VIF\"] = [variance_inflation_factor(variables.values, i) for i in range(variables.shape[1])]\n\nvif[\"features\"] = variables.columns\ndata_no_multicollinearity = data_cleaned_2.drop(['Year'],axis=1)\n\"\"\"\n## Step 3: Create dummy Variables\u00b6\nIn session 14 we create a dummy variable by using map\n\ndata = raw_data.copy()\n\ndata['Attendance'] = data['Attendance'].map({'Yes': 1, 'No': 0})\n\n#### Now in what follows, we will create dummies by a simple code of Pandas\n\n#### Note that if we have N categories for a feature, we have to create N-1 dummies\n![download (1).png](attachment:2f4710af-82cc-49d0-8a26-0d4372fce46f.png)\n\"\"\"\ndata_with_dummies = pd.get_dummies(data_no_multicollinearity, drop_first = True)\n\ndata_with_dummies\ndata_with_dummies.columns.values\n# Now we create a list of our desired columns order as follows:\n\nnew_columns = ['log_price', 'Mileage', 'EngineV', 'Brand_BMW',\n       'Brand_Mercedes-Benz', 'Brand_Mitsubishi', 'Brand_Renault',\n       'Brand_Toyota', 'Brand_Volkswagen', 'Body_hatch', 'Body_other',\n       'Body_sedan', 'Body_vagon', 'Body_van', 'Engine Type_Gas',\n       'Engine Type_Other', 'Engine Type_Petrol', 'Registration_yes']\ndata_preprocessed = data_with_dummies[new_columns]\ndata_preprocessed\n\"\"\"\n## Step 4: Creating the Linear Regression Model\n\"\"\"\ntargets = data_preprocessed['log_price']\n\ninputs = data_preprocessed.drop(['log_price'],axis=1)\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\n\nscaler.fit(inputs)\n\ninputs_scaled = scaler.transform(inputs)\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(inputs_scaled, targets, test_size=0.2, random_state=42)\nreg = LinearRegression()\n\nreg.fit(x_train,y_train)\ny_hat = reg.predict(x_train)\nplt.scatter(y_train, y_hat)\n\nplt.xlabel('Targets (y_train)',size=15)\nplt.ylabel('Predictions (y_hat)',size=15)\n\nplt.xlim(6,13)\nplt.ylim(6,13)\n\nplt.show()\n\"\"\"\n**Pay Attention Please:**\n\nAn ERROR is the difference between the observed value and the true value (very often unobserved, generated by the data generating process (DGP)). Consider the example of Height and Weight.\n\nA RESIDUAL is the difference between the observed value and the predicted value (by the model).\n\"\"\"\nsns.kdeplot(y_train - y_hat, shade = True)\nplt.title(\"Residuals PDF\", size=15)\n\"\"\"\n![download (2).png](attachment:17729205-1b28-45cb-9658-4acb0a59bda6.png)\n\"\"\"\nreg.score(x_train,y_train)\n\"\"\"\n**Note:**\n\nThe most common interpretation of r-squared is how well the regression model fits the observed data. For example, an r-squared of 0.60 reveals that 60% of the data fit the regression model. Generally, a higher r-squared indicates a better fit for the model.\n\"\"\"\nreg.intercept_\nreg.coef_\nreg_summary = pd.DataFrame(inputs.columns.values, columns=['Features'])\n\nreg_summary['Weights'] = reg.coef_\n\nreg_summary\n\"\"\"\n![download (3).png](attachment:f355bb4d-37bf-48ee-a1d3-2064cec2da34.png)\n\n## Step 5: Testing our Model\n\"\"\"\ny_hat_test = reg.predict(x_test)\nplt.scatter(y_test, y_hat_test)\n\nplt.xlabel('Targets (y_test)',size=15)\nplt.ylabel('Predictions (y_hat_test)',size=15)\n\nplt.xlim(6,13)\nplt.ylim(6,13)\n\nplt.show()\n\"\"\"\nRecall that we have:\n1: $ln (e^x) =x$\n\n2: $e^{ln(x)} = x$\n\nSo,\n\n$e^{ln (Price)}= Price$\n\"\"\"\ndf_performance = pd.DataFrame(np.exp(y_hat_test), columns=['Prediction'])\n\ndf_performance.head()\ndf_performance['Target'] = np.exp(y_test)\n\ndf_performance.head()\ny_test.head()\ny_test = y_test.reset_index(drop=True)\ny_test.head()\ndf_performance['Target'] = np.exp(y_test)\ndf_performance\n\"\"\"\nPercent Error = $\\Big|(Target-Prediction)\\times \\frac{100}{Target}\\Big| = \\frac{Residual}{Target}\\times 100$\n\nSee the following link for more details:\n\nhttps:\/\/www.mathsisfun.com\/data\/percentage-difference-vs-error.html\n\"\"\"\ndf_performance['Residual'] = df_performance['Target'] - df_performance['Prediction']\n\ndf_performance['Percent Error'] = np.absolute(df_performance['Residual']\/df_performance['Target']*100)\n\ndf_performance\ndf_performance.describe()\npd.options.display.max_rows = 999\n\ndf_performance.sort_values(by=['Percent Error'], inplace=True)\n\nnp.round(df_performance, 3)\n\"\"\"\n\nYou can change the values of Target to int:\n\ndf_performance['Target'] = df_performance['Target'].astype(int)\n\nYou can also use of this code to get a rounded two decimal float number:\n\npd.set_option('display.float_format', lambda x: '%.2f' % x)\n\"\"\"\nnp.round(reg_summary, 2)\n\"\"\"\nOur Model\n\n$\\hat{y} = -0.47\\times Mileage + 0.22\\times EngineV + 0.01\\times Brand\\_BMW + \\ldots + 0.31\\times Registration\\_yes$\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e01e0f83d3e554'}"}
{"id":"64563","text":"\"\"\"\nKaggleDaysSF Hackathon 17th Place Solution\n\nLGBMClassifier with SimpleImputer, StandardScaler, OneHotEncoder, and 42 hand-picked features.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler \nfrom sklearn.compose import ColumnTransformer,make_column_transformer\nfrom sklearn.pipeline import make_pipeline\nfrom lightgbm import LGBMClassifier\nfrom category_encoders import OneHotEncoder\nfrom sklearn.model_selection import cross_val_predict\nfrom warnings import filterwarnings\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfilterwarnings('ignore')\ntrain = pd.read_csv(\"..\/input\/train_2.csv\") \ntest = pd.read_csv(\"..\/input\/test_2.csv\") \ntrain_input = train.drop(['id','target','B_15'],axis = 1)\ntrain_labels = train['target']\napp_train = pd.get_dummies(train_input)\nimp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')\nimp_mean.fit(app_train)\ntrain_imputed = imp_mean.transform(app_train)\nscaler = StandardScaler()\nscaler.fit(train_imputed)\ntrain_imputed = scaler.transform(train_imputed)\nfeatures = list(app_train.columns)\nrandom_forest = RandomForestClassifier(n_estimators = 100, random_state = 50, verbose = 1, n_jobs = -1)\nrandom_forest.fit(train_imputed,train_labels)\nfeature_importance_values = random_forest.feature_importances_\nfeature_importances = pd.DataFrame({'feature': features, 'importance':feature_importance_values})\ndef plot_feature_importances(df):\n    #Sort features according to importance\n    df = df.sort_values('importance', ascending = False).reset_index()\n    \n    #Normalise the feature importances to add up to one\n    df['importance_normalized'] = df['importance'] \/ df['importance'].sum()\n    \n    #Make a horizontal bar chart of feature importances\n    plt.figure(figsize = (10,6))\n    ax = plt.subplot()\n    \n    #Need to reverse the index to plot most important on top\n    ax.barh(list(reversed(list(df.index[:15]))),\n           df['importance_normalized'].head(15),\n           align = 'center', edgecolor = 'k')\n    #Set the yticks and labels\n    ax.set_yticks(list(reversed(list(df.index[:15]))))\n    ax.set_yticklabels(df['feature'].head(15))\n    \n    #Plot labeling\n    plt.xlabel('Normalized Importance'); plt.title('Feature Importance')\n    plt.show()\n    \n    return df\nfeature_importances_sorted = plot_feature_importances(feature_importances)\ntrain = pd.read_csv(\"..\/input\/train_2.csv\")\ntrain=train[['target','B_15','B_10','B_3','B_12','B_8','B_7','B_4','D_121','D_26','D_17','B_11','D_56','D_138','D_1','D_40','D_166',\n            'C_10','D_102','D_132','D_99','C_14','C_3','C_2','D_13','D_34','D_66','D_2','D_142','D_143','D_21','D_156','D_158','D_37','B_9',\n            'D_14','C_12','D_28','D_6','D_29','D_54','D_117','C_5','D_86','D_107','D_30']]\ntest = pd.read_csv(\"..\/input\/test_2.csv\")\ntest=test[['B_15','B_10','B_3','B_12','B_8','B_7','B_4','D_121','D_26','D_17','B_11','D_56','D_138','D_1','D_40','D_166',\n            'C_10','D_102','D_132','D_99','C_14','C_3','C_2','D_13','D_34','D_66','D_2','D_142','D_143','D_21','D_156','D_158','D_37','B_9',\n            'D_14','C_12','D_28','D_6','D_29','D_54','D_117','C_5','D_86','D_107','D_30']]\ntarget_column = \"target\"\nid_column = \"id\"\ncategorical_cols = [c for c in test.columns if test[c].dtype in [np.object]]\nnumerical_cols = [c for c in test.columns if test[c].dtype in [np.float, np.int] and c not in [target_column, id_column]]\npreprocess = make_column_transformer(\n    (numerical_cols, make_pipeline(SimpleImputer(), StandardScaler())),\n    (categorical_cols, OneHotEncoder()))\nclassifier = make_pipeline(preprocess,LGBMClassifier(n_jobs=-1,eta=0.01,max_depth=4))\n\noof_pred = cross_val_predict(classifier, \n                             train, \n                             train[target_column], \n                             cv=5,\n                             method=\"predict_proba\")\n                  \nprint(\"LGBMClassifier Cross validation AUC {:.4f}\".format(roc_auc_score(train[target_column], oof_pred[:,1])))\nsub = pd.read_csv(\"..\/input\/sample_submission.csv\")\nclassifier.fit(train, train[target_column])\ntest_preds = classifier.predict_proba(test)[:,1]\nsub[target_column] = test_preds\nsub.to_csv(\"submissionWith42Predictors.csv\", index=False)\n\"\"\"\n**Credit**: Many functions were adapted from https:\/\/www.kaggle.com\/paweljankiewicz\/lightgbm-with-sklearn-pipelines.\n\nMade by https:\/\/www.kaggle.com\/hassamraja, https:\/\/www.kaggle.com\/therealrainier, and https:\/\/www.kaggle.com\/paultimothymooney during the 4\/11\/2019 KaggleDaysSF Hackathon.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '771ccadf74198e'}"}
{"id":"96234","text":"pip install pandas dash\n\"\"\"\n# Loading all the libraries\n\"\"\"\nimport pandas as pd\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom dash import no_update\n\"\"\"\n# Bringing Data\n\"\"\"\nairline_data =  pd.read_csv(\"..\/input\/us-airline-data\/airline_data.csv\", \n                            encoding = \"ISO-8859-1\",\n                            dtype={'Div1Airport': str, 'Div1TailNum': str, \n                                   'Div2Airport': str, 'Div2TailNum': str})\n\"\"\"\n### Reviewing Dataframe\n\"\"\"\nairline_data.head()\n\"\"\"\n### Checking statistical overview of data ,with columns including descriptive data also, will be evaluated by [ include='all' ] parameter\n\"\"\"\nairline_data.describe(include='all')\n\"\"\"\n# Creating an Instance of web application we are going to create.\n\"\"\"\napp = dash.Dash(__name__)\n\"\"\"\n### Let's begin.  \n**I am going to code all the program in one cell, because if I tried to execute in seprate cell, it will throw an error saying function is incomplete**\n\"\"\"\n# List of years \nyear_list = [i for i in range(2005, 2021, 1)]\n\n\"\"\"Compute graph data for creating yearly airline performance report \n\nFunction that takes airline data as input and create 5 dataframes based on the grouping condition to be used for plottling charts and grphs.\n\nArgument:\n     \n    df: Filtered dataframe\n    \nReturns:\n   Dataframes to create graph. \n\"\"\"\n\ndef compute_data_choice_1(df):\n    # Cancellation Category Count\n    bar_data = df.groupby(['Month','CancellationCode'])['Flights'].sum().reset_index()\n    # Average flight time by reporting airline\n    line_data = df.groupby(['Month','Reporting_Airline'])['AirTime'].mean().reset_index()\n    # Diverted Airport Landings\n    div_data = df[df['DivAirportLandings'] != 0.0]\n    # Source state count\n    map_data = df.groupby(['OriginState'])['Flights'].sum().reset_index()\n    # Destination state count\n    tree_data = df.groupby(['DestState', 'Reporting_Airline'])['Flights'].sum().reset_index()\n    return bar_data, line_data, div_data, map_data, tree_data\n\n\"\"\"Compute graph data for creating yearly airline delay report\n\nThis function takes in airline data and selected year as an input and performs computation for creating charts and plots.\n\nArguments:\n    df: Input airline data.\n    \nReturns:\n    Computed average dataframes for carrier delay, weather delay, NAS delay, security delay, and late aircraft delay.\n\"\"\"\n\ndef compute_data_choice_2(df):\n    # Compute delay averages\n    avg_car = df.groupby(['Month','Reporting_Airline'])['CarrierDelay'].mean().reset_index()\n    avg_weather = df.groupby(['Month','Reporting_Airline'])['WeatherDelay'].mean().reset_index()\n    avg_NAS = df.groupby(['Month','Reporting_Airline'])['NASDelay'].mean().reset_index()\n    avg_sec = df.groupby(['Month','Reporting_Airline'])['SecurityDelay'].mean().reset_index()\n    avg_late = df.groupby(['Month','Reporting_Airline'])['LateAircraftDelay'].mean().reset_index()\n    return avg_car, avg_weather, avg_NAS, avg_sec, avg_late\n\n# Application layout\n# This layout is created by dash\/dash_components_html\/dash_core_components and we don't need to understand html or xml to build layout\n# just try to visualize the layout in tree like structure and it will be easy for use to create any layout.\napp.layout = html.Div(children=[ \n                               html.H1('US Domestic Airline Flights Performance', style={'color':'#503D36','textAlign':'center','font-size':24}),\n                                # Dropdown creation\n                                # Create an outer division \n                                html.Div([\n                                    # Add an division\n                                    html.Div([\n                                        # Create an division for adding dropdown helper text for report type\n                                        html.Div(\n                                            [\n                                            html.H2('Report Type:', style={'margin-right': '2em'}),\n                                            ]\n                                        ),\n                                        # Add a dropdown\n                                        dcc.Dropdown(id='input-type',\n                                        options=[\n                                            {'label':'early Airline Performance Report','value':'OPT1'},\n                                            {'label':'Yearly Airline Delay Report', 'value':'OPT2'}\n                                        ],\n                                        placeholder='Select a report type',\n                                        style={'width':'80%','padding':'3px','font-size':'20px','text-align-last':'center'})\n                                    # Place them next to each other using the division style\n                                    ], style={'display':'flex'}),\n                                    \n                                   # Add next division \n                                   html.Div([\n                                       # Create an division for adding dropdown helper text for choosing year\n                                        html.Div(\n                                            [\n                                            html.H2('Choose Year:', style={'margin-right': '2em'})\n                                            ]\n                                        ),\n                                        dcc.Dropdown(id='input-year', \n                                                     # Update dropdown values using list comphrehension\n                                                     options=[{'label': i, 'value': i} for i in year_list],\n                                                     placeholder=\"Select a year\",\n                                                     style={'width':'80%', 'padding':'3px', 'font-size': '20px', 'text-align-last' : 'center'}),\n                                            # Place them next to each other using the division style\n                                            ], style={'display': 'flex'}),  \n                                          ]),\n                                \n                                # Add Computed graphs\n                                # Observe how we add an empty division and providing an id that will be updated during callback\n                                html.Div([ ], id='plot1'),\n    \n                                html.Div([\n                                        html.Div([ ], id='plot2'),\n                                        html.Div([ ], id='plot3')\n                                ], style={'display': 'flex'}),\n                                  html.Div([\n                                        html.Div([ ], id='plot4'),\n                                        html.Div([ ], id='plot5')\n                                ], style={'display': 'flex'})\n                                ])\n\n\n# Callback function definition\n@app.callback( [Output(component_id='plot1', component_property='children'),\n                Output(component_id='plot2', component_property='children'),\n                Output(component_id='plot3', component_property='children'),\n                Output(component_id='plot4', component_property='children'),\n                Output(component_id='plot5', component_property='children')],\n\n               [Input(component_id='input-type', component_property='value'),\n                Input(component_id='input-year', component_property='value')],\n               # Holding output state till user enters all the form information. In this case, it will be chart type and year\n               [State(\"plot1\", 'children'), State(\"plot2\", \"children\"),\n                State(\"plot3\", \"children\"), State(\"plot4\", \"children\"),\n                State(\"plot5\", \"children\")\n               ])\n\n# Add computation to callback function and return graph\ndef get_graph(chart, year, children1, children2, c3, c4, c5):\n      \n        # Select data\n        df =  airline_data[airline_data['Year']==int(year)]\n       \n        if chart == 'OPT1':\n            # Compute required information for creating graph from the data\n            bar_data, line_data, div_data, map_data, tree_data = compute_data_choice_1(df)\n            \n            # Number of flights under different cancellation categories\n            bar_fig = px.bar(bar_data, x='Month', y='Flights', color='CancellationCode', title='Monthly Flight Cancellation')\n            \n            line_fig = px.line(line_data,x='Month',y='AirTime',color='Reporting_Airline', title='Average monthly flight time (minutes) by airline')\n            \n            # Percentage of diverted airport landings per reporting airline\n            pie_fig = px.pie(div_data, values='Flights', names='Reporting_Airline', title='% of flights by reporting airline')\n            \n            # Number of flights flying from each state using choropleth\n            map_fig = px.choropleth(map_data,  # Input data\n                    locations='OriginState', \n                    color='Flights',  \n                    hover_data=['OriginState', 'Flights'], \n                    locationmode = 'USA-states', # Set to plot as US States\n                    color_continuous_scale='GnBu',\n                    range_color=[0, map_data['Flights'].max()]) \n            map_fig.update_layout(\n                    title_text = 'Number of flights from origin state', \n                    geo_scope='usa') # Plot only the USA instead of globe\n            \n            tree_fig = px.treemap(tree_data, path=['DestState', 'Reporting_Airline'], values='Flights', color='Flights', color_continuous_scale='RdBu', title='Flight count by airline to destination state')\n                 \n            # Return dcc.Graph component to the empty division\n            return [dcc.Graph(figure=tree_fig), \n                    dcc.Graph(figure=pie_fig),\n                    dcc.Graph(figure=map_fig),\n                    dcc.Graph(figure=bar_fig),\n                    dcc.Graph(figure=line_fig)\n                   ]\n        else:\n            # This covers chart type 2 and we have completed this exercise under Flight Delay Time Statistics Dashboard section\n            # Compute required information for creating graph from the data\n            avg_car, avg_weather, avg_NAS, avg_sec, avg_late = compute_data_choice_2(df)\n            \n            # Create graph\n            carrier_fig = px.line(avg_car, x='Month', y='CarrierDelay', color='Reporting_Airline', title='Average carrrier delay time (minutes) by airline')\n            weather_fig = px.line(avg_weather, x='Month', y='WeatherDelay', color='Reporting_Airline', title='Average weather delay time (minutes) by airline')\n            nas_fig = px.line(avg_NAS, x='Month', y='NASDelay', color='Reporting_Airline', title='Average NAS delay time (minutes) by airline')\n            sec_fig = px.line(avg_sec, x='Month', y='SecurityDelay', color='Reporting_Airline', title='Average security delay time (minutes) by airline')\n            late_fig = px.line(avg_late, x='Month', y='LateAircraftDelay', color='Reporting_Airline', title='Average late aircraft delay time (minutes) by airline')\n            \n            return[dcc.Graph(figure=carrier_fig), \n                   dcc.Graph(figure=weather_fig), \n                   dcc.Graph(figure=nas_fig), \n                   dcc.Graph(figure=sec_fig), \n                   dcc.Graph(figure=late_fig)]\n        \n\n\"\"\"\n# Running our application\n\"\"\"\n\"\"\"\n# *Important Note*  \n1. You can't run this file on kaggle or jupyter or any other online platform.\n1. To run this program you need to copy whole prorgam and run it on local IDE say VS-Code. \n1. You need to uncomment last cell of {Running  our application} and then run in local IDE. I have commented this beacuse if I didn't , it would not upload on kaggle\n\"\"\"\n# if __name__ == '__main__':\n#     app.run_server(host='0.0.0.0', port= 8050,debug = False)\n\"\"\"\n## All we have to do now  \n*Run the whole program and* **-->** *The last O\/P  probabily will be an IP adress* **-->** *go to that ip adress in browser* **-->** *Use interactive Dashboard*\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b0c4e516492ef6'}"}
{"id":"116793","text":"\"\"\"\n<table align=\"center\" width=100%>\n    <tr>\n        <td width=\"25%\">\n            <img src=\"https:\/\/monophy.com\/media\/3o7aD3LftJ423GBsVG\/monophy.gif\">\n        <\/td>\n        <td>\n            <div align=\"center\">\n                <font color=\"#0B2F02\" size=24px>\n                    <b>Carbon Dioxide Emissions\n                    <\/b>\n                <\/font>\n            <\/div>\n        <\/td>\n    <\/tr>\n<\/table>\n\"\"\"\n\"\"\"\n# Problem Statement  \ud83d\ude9a\ud83c\udfed\n\"\"\"\n\"\"\"\n**To predict the Carbon Dioxide emissions from a vehicle in Canada depending on the fuel consumption and other describing features of a vehicle.**\n\"\"\"\n\"\"\"\n<table>\n    <tr>\n        <td>\n            <img src=\"https:\/\/i.gifer.com\/6FR.gif\">\n        <\/td>\n    <\/tr>\n<\/table>\n\"\"\"\n\"\"\"\n# Data Dictionary\n\"\"\"\n\"\"\"\n1. **Make**  \u2192 Company of the vehicle\n2. **Model**  \u2192 Car model\n3. **Vehicle_Class**  \u2192 Class of vehicle depending on their utility, capacity and weight\n4. **Engine_Size**  \u2192 Size of engine in terms of Litre\n5. **Cylinders**  \u2192 Number of cylinders\n6. **Transmission**  \u2192 Transmission type with number of gears\n7. **Fuel_Type**  \u2192 Type of Fuel used\n8. **Fuel_Consumption_City**  \u2192 Fuel consumption in city roads (L\/100 km) \n9. **Fuel_Consumption_Hwy**  \u2192 Fuel consumption in Hwy roads (L\/100 km)\n10. **Fuel_Consumption_Comb**  \u2192 The combined fuel consumption (55% city, 45% highway) is shown in L\/100 km\n11. **Fuel_Consumption_Comb1**   \u2192 The combined fuel consumption in both city and highway is shown in mile per gallon(mpg)\n12. **CO2_Emissions**   \u2192 The tailpipe emissions of carbon dioxide (in grams per kilometre) for combined city and highway driving (Target\/dependent variable)\n\"\"\"\n\"\"\"\n## Table of Contents\n\n1. **[Import Libraries](#import_lib)**\n2. **[Set Options](#set_options)**\n3. **[Read Data](#Read_Data)**\n4. **[Exploratory Data Analysis](#data_preparation)**\n    - 4.1 - [Preparing the Dataset](#Data_Preparing)\n        - 4.1.1 - [Data Dimension](#Data_Shape)\n        - 4.1.2 - [Data Types](#Data_Types)\n        - 4.1.3 - [Missing Values](#Missing_Values)\n        - 4.1.4 - [Duplicate Data](#duplicate)\n        - 4.1.5 - [Indexing](#indexing)\n        - 4.1.6 - [Final Dataset](#final_dataset)\n    - 4.2 - [Understanding the Dataset](#Data_Understanding)\n        - 4.2.1 - [Summary Statistics](#Summary_Statistics)\n        - 4.2.2 - [Correlation](#correlation)\n        - 4.2.3 - [Analyze Categorical Variables](#analyze_cat_var)\n        - 4.2.4 - [Anaylze Target Variable](#analyze_tar_var)\n        - 4.2.5 - [Analyze Relationship Between Target and Independent Variables](#analyze_tar_ind_var)\n        - 4.2.6 - [Feature Engineering](#feature_eng)\n5. **[Data Pre-Processing](#data_pre)**\n    - 5.1 - [Outliers](#out)\n        - 5.1.1 - [Discovery of Outliers](#dis_out)\n        - 5.1.2 - [Removal of Outliers](#rem_out)\n        - 5.1.3 - [Rechecking of Correlation](#rec_cor)\n    - 5.2 - [Categorical Encoding](#cat_enc)\n6. **[Building Multiple Linear Regression Models](#bui_mlr_mod)**\n    - 6.1 - [Multiple Linear Regression - Basic Model](#bas_mod)\n    - 6.2 - [Feature Transformation](#fea_tra)\n    - 6.3 - [Feature Scaling](#fea_sca)\n    - 6.4 - [Multiple Linear Regression - Full Model - After Feature Scaling](#mod_aft_sca)\n    - 6.5 - [Assumptions Before Multiple Linear Regression Model](#ass_bef)\n        - 6.5.1 - [Assumption #1: If Target Variable is Numeric](#tgt_num)\n        - 6.5.2 - [Assumption #2: Presence of Multi-Collinearity](#pre_mul_col)\n    - 6.6 - [Multiple Linear Regression - Full Model - After PCA](#mod_pca)\n    - 6.7 - [Feature Selection](#fea_sel)\n        - 6.7.1 - [Forward Selection](#for_sel)\n        - 6.7.2 - [Backward Elimination](#bac_eli)\n    - 6.8 - [Multiple Linear Regression - Full Model - After Feature Selection](#mod_fea_sel)\n    - 6.9 - [Assumptions After Multiple Linear Regression Model](#ass_aft)\n        - 6.9.1 - [Assumption #1: Linear Relationship Between Dependent and Independent Variable](#lr_dep_ind)\n        - 6.9.2 - [Assumption #2: Checking for Autocorrelation](#che_aut_cor)\n        - 6.9.3 - [Assumption #3: Checking for Heterskedacity](#che_het)\n        - 6.9.4 - [Assumption #4: Test for Normality](#tes_nor)\n            - 6.9.4.1 - [Q-Q Plot](#qq_plt)\n            - 6.9.4.2 - [Shapiro Wilk Test](#sha_wil_tes)\n7. **[Model Evaluation](#mod_eva)**\n    - 7.1 - [Measures of Variation](#mea_var)\n    - 7.2 - [Inferences about Intercept and Slope](#inf_int_slo)\n    - 7.3 - [Confidence Interval for Intercept and Slope](#con_int_slo)\n    - 7.4 - [Compare Regression Results](#com_reg_res)\n8. **[Model Performance](#mod_per)**\n    - 8.1 - [Mean Square Error(MSE)](#mse)\n    - 8.2 - [Root Mean Squared Error(RMSE)](#rmse)\n    - 8.3 - [Mean Absolute Error(MAE)](#mae)\n    - 8.4 - [Mean Absolute Percentage Error(MAPE)](#mape)\n    - 8.5 - [Resultant Table](#res_tab)\n9. **[Model Optimization](#mod_opt)**\n    - 9.1 - [Bias](#bias)\n    - 9.2 - [Variance](#var)\n    - 9.3 - [Model Validation](#mod_val)\n      - 9.3.1 - [Cross Validation](#cro_val)\n      - 9.3.2 - [Leave One Out Cross Validation(LOOCV)](#loocv)\n    - 9.4 - [Gradient Descent](#gra_des)\n    - 9.5 - [Regularization](#reg)\n      - 9.5.1 - [Ridge Regression Model](#ridge)\n      - 9.5.2 - [Lasso Regression Model](#lasso)\n      - 9.5.3 - [Elastic Net Regression Model](#ela_net)\n      - 9.5.4 - [Grid Search CV](#gri_sea)\n10. **[Displaying Score Summary](#dis_sco_sum)**\n11. **[Conclusion](#conclu)**\n12. **[Deployment](#deploy)**\n13. **[References](#Refer)**\n\"\"\"\n\"\"\"\n# 1. Import Libraries <a id='import_lib'><\/a>\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nimport seaborn as sns\n\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n%matplotlib inline\n\n# display all columns of the dataframe\npd.options.display.max_columns = None\n\n# display all rows of the dataframe\npd.options.display.max_rows = None\nfrom sklearn.preprocessing import MinMaxScaler\nimport statsmodels\nimport statsmodels.api as sm\nimport statsmodels.stats.api as sms\nfrom statsmodels.compat import lzip\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom statsmodels.graphics.gofplots import qqplot\nfrom statsmodels.stats.anova import anova_lm\nfrom statsmodels.formula.api import ols\nfrom statsmodels.tools.eval_measures import rmse\n\n# import various functions from scipy\nfrom scipy import stats\nfrom scipy.stats import shapiro\n\n# 'metrics' from sklearn is used for evaluating the model performance\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\n\nfrom statsmodels.graphics.gofplots import qqplot\n\n# import 'stats'\nfrom scipy import stats\n\n# 'metrics' from sklearn is used for evaluating the model performance\nfrom sklearn.metrics import mean_squared_error\n\n# import functions to perform feature selection\nfrom mlxtend.feature_selection import SequentialFeatureSelector as sfs\nfrom sklearn.feature_selection import RFE\n\n# import function to perform linear regression\nfrom sklearn.linear_model import LinearRegression\n\n# import functions to perform cross validation\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\n\n\n# import function to perform linear regression\nfrom sklearn.linear_model import LinearRegression\n\n# import StandardScaler to perform scaling\nfrom sklearn.preprocessing import StandardScaler \n\n# import SGDRegressor from sklearn to perform linear regression with stochastic gradient descent\nfrom sklearn.linear_model import SGDRegressor\n\n# import function for ridge regression\nfrom sklearn.linear_model import Ridge\n\n# import function for lasso regression\nfrom sklearn.linear_model import Lasso\n\n# import function for elastic net regression\nfrom sklearn.linear_model import ElasticNet\n\n# import function to perform GridSearchCV\nfrom sklearn.model_selection import GridSearchCV\n\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom sklearn import linear_model\nfrom sklearn.decomposition import PCA\nfrom sklearn import preprocessing\n\"\"\"\n# 2. Set Options <a id='set_options'><\/a>\n\"\"\"\n# display all columns of the dataframe\npd.options.display.max_columns = None\n# display all rows of the dataframe\npd.options.display.max_rows = None\n# return an output value upto 6 decimals\npd.options.display.float_format = '{:.6f}'.format\n\"\"\"\n# 3. Read Data <a id='Read_Data'><\/a>\n\"\"\"\n# read csv file using pandas\ndata = pd.read_csv('..\/input\/co2-emissions-cannada\/CO2 Emissions_Canada.csv')\n\n# display the top 5 rows of the dataframe\ndata.head()\ndata.info()\n\"\"\"\n# 4. Exploratory Data Analysis <a id='data_preparation'><\/a>\n\"\"\"\n\"\"\"\n## 4.1 Preparing the Dataset <a id='Data_Preparing'><\/a>\n\"\"\"\n\"\"\"\n### 4.1.1 Data Dimensions <a id='Data_Shape'><\/a>\n\"\"\"\n# shape returns the dimension of the data\ndata.shape\n\"\"\"\nIn this dataset I have 7384 records across 12 features\n\"\"\"\n\"\"\"\n### 4.1.2 Data Types <a id='Data_Types'><\/a>\n\"\"\"\ndata.dtypes\n\"\"\"\nThe dataset contains **5 object columns, 3 int column and 4 float columns**\n\"\"\"\n\"\"\"\n### 4.1.3 Missing Values <a id='Missing_Values'><\/a>\n\"\"\"\nmissing_value = pd.DataFrame({\n    'Missing Value': data.isnull().sum(),\n    'Percentage': (data.isnull().sum() \/ len(data))*100\n})\nmissing_value.sort_values(by='Percentage', ascending=False)\n\"\"\"\nThere are **no missing values** present in this dataset\n\"\"\"\n\"\"\"\n**Visualising missing values using Heatmap**\n\"\"\"\n# set the figure size\nplt.figure(figsize=(15, 8))\n\n# plot heatmap to check null values\n# isnull(): returns 'True' for a missing value\n# cbar: specifies whether to draw a colorbar; draws the colorbar for 'True' \nsns.heatmap(data.isnull(), cbar=False)\n\n# display the plot\nplt.show()\n\"\"\"\n**Visual proof that there are no missing values**\n\"\"\"\n\"\"\"\n### 4.1.4 Duplicate Data <a id='duplicate'><\/a>\n\"\"\"\nduplicate = data.duplicated().sum()\nprint('There are {} duplicated rows in the data'.format(duplicate))\n\"\"\"\n**Getting rid of duplicate data**\n\"\"\"\ndata.drop_duplicates(inplace=True)\n\"\"\"\n**Checking for duplicate data after removal of duplicates**\n\"\"\"\nduplicate = data.duplicated().sum()\nprint('There are {} duplicated rows in the data'.format(duplicate))\n\"\"\"\n### 4.1.5 Indexing <a id='indexing'><\/a>\n\"\"\"\ndata.shape\n\"\"\"\nThere are **6281 records** after dropping duplicates\n\"\"\"\ndata.tail()\n\"\"\"\n**The last 5 index values range from 7379-7383 but I have only 6281 records thus the indexes need to be reset**\n\"\"\"\ndata.reset_index(inplace=True)\ndata.tail()\n\"\"\"\n**The indexes have been reset but a new column 'index' is created which needs to be dropped**\n\"\"\"\ndata.drop(['index'],inplace=True,axis=1)\n\"\"\"\n### 4.1.6 Final Dataset <a id='final_dataset'><\/a>\n\"\"\"\ndata.head()\ndata.shape\n\"\"\"\nThe final dataset has **6281 records and 12 features with no missing and duplicate values**\n\"\"\"\n\"\"\"\n## 4.2 Understanding the Dataset <a id='Data_Understanding'><\/a>\n\"\"\"\n\"\"\"\n### 4.2.1 Summary Statistics <a id='Summary_Statistics'><\/a>\n\"\"\"\n\"\"\"\n**Numeric Variables**\n\"\"\"\ndata.describe(include=np.number)\n\"\"\"\n<br>Inferences:<\/br>\n<br>1. The average amount of CO2 emitted from cars is 251 g\/km<\/br>\n<br>2. Atleast 4 Litres of fuel is consumed be it the car is on city roads or highway<\/br>\n<br>3. About 75% of the cars have 6 or less cylinders<\/br>\n<br>4. The amount of fuel consumed by cars on city roads is comparitvely greater than that of highway<\/br>\n\"\"\"\n\"\"\"\n**Categorical Variables**\n\"\"\"\ndata.describe(include = object)\n\"\"\"\n<br>Inferences:<\/br>\n<br>    1. There are a total of 42 different car companies with 2053 different car models<\/br>\n<br>    2. Vehicles are divided into 16 different classes with SUV-Small vehicles frequenting the most<\/br>\n<br>    3. 4 different types of fuels used by cars have been identified and fuel X seems to be the most famous<\/br>\n<br>    4. Most of the cars have AS6 transmission<\/br>\n\"\"\"\n\"\"\"\n### 4.2.2 Correlation <a id='correlation'><\/a>\n\"\"\"\n# select the numerical features in the dataset using 'select_dtypes()'\n# select_dtypes(include=np.number): considers the numeric variables\ndata_num_features = data.select_dtypes(include=np.number)\n\n# print the names of the numeric variables \nprint('The numerical columns in the dataset are: ',data_num_features.columns)\n# generate the correlation matrix\ncorr =  data_num_features.corr()\n\n# print the correlation matrix\ncorr\nplt.figure(figsize=(20,10))\ncorr =data_num_features.corr(method='pearson')\nsns.heatmap(corr, annot=True,cmap='tab20c')\nplt.show()\n\"\"\"\n<br>Inferences:<\/br>\n<br>    1. Fuel_Consumption_Comb1 has a high negative correaltion(<-0.9) with CO2_Emissions, Fuel_Consumption_Comb and Fuel_Consumption_City<\/br>\n<br>    2. CO2_Emissions has high positive correlation(>0.9) with Fuel_Consumption_Comb and Fuel_Consumption_City<\/br>\n\"\"\"\n\"\"\"\n### 4.2.3 Analyse Categorical Variables <a id='analyze_cat_var'><\/a>\n\"\"\"\n# create a list of all categorical variables\n# include=object: selects the categoric features\n# drop(['city'],axis=1): drops the city column from the dataframe\ndata_cat_features = data.select_dtypes(include='object')\n\n# plot the count distribution for each categorical variable \n# 'figsize' sets the figure size\n# plot a count plot for all the categorical variables\nfor variable in data_cat_features:\n    \n    cat_count  = data[variable].value_counts()\n    cat_count10 = cat_count[:10,]\n    plt.figure(figsize=(10,5))\n    sns.barplot(cat_count10.values,cat_count10.index, alpha=0.8)\n    if cat_count.size > 10:\n        plt.title('Top 10 {}'.format(variable))\n    else:\n        plt.title(variable)\n    plt.ylabel('{}'.format(variable), fontsize=12)\n    plt.xlabel('Number of Cars', fontsize=12)\n    plt.show()\n\n# avoid overlapping of the plots using tight_layout()    \nplt.tight_layout()   \n\n# display the plot\nplt.show()\n\"\"\"\n<br>Inferences from each Plot:<\/br>\n<br>    1. Top 10 Make: Most of the cars on Canadian roads are made by Ford<\/br>\n<br>    2. Top 10 Model: The F-150 FFV is amongst the most famous models driven in Canada<\/br>\n<br>    3. Top 10 Vehicle_Class: SUV-Small is the preferred class of vehicle amongst the Canadians<\/br>\n<br>    4. Top 10 Transmission: More than 1000 cars have AS6 and AS8 transmission types<\/br>\n<br>    5. Fuel Type: Majority of the cars in Canada use Fuel type X and Z<\/br>\n\"\"\"\n\"\"\"\n### 4.2.4 Analyse Target Variable <a id='analyze_tar_var'><\/a>\n\"\"\"\nsns.distplot(data['CO2_Emissions'], bins=30, kde=True, axlabel='Carbon Dioxide Emission (30 bins)')\n\"\"\"\nFrom the above histogram, I can see that CO2_Emissions is moderately positive skewed\n\"\"\"\nmean = data['CO2_Emissions'].mean()\n\n# calculate the mode\nmode = data['CO2_Emissions'].mode()\n\n# calculate the median\nmedian = data['CO2_Emissions'].median()\n\nprint('Mean for CO2 Emission is ',mean)\nprint('Median for CO2 Emission is ',median)\nprint('Mode for CO2 Emission is ',mode)\n\"\"\"\nCO2_Emissions is bi-modal in nature\n\"\"\"\n# create two plots in single figure\n# I define two axes by passing the value 3 to the subplot function\n# sharey returns the y axis label\nfig, axes = plt.subplots(1,3, sharey=True, figsize=(15,8))\n\n# create a boxplot\n# orient=\"v\": create a vertical plot\n# ax = axes: axes object to draw plot\n# I use axes[0] to use the first axes for plotting\nsns.boxplot(y=data['CO2_Emissions'], orient=\"v\", ax = axes[0])\n\n# create a violinplot\n# orient=\"v\": create a vertical plot\n# ax = axes: axes object to draw plot\n# I use axes[1] to use the second axes for plotting\nsns.violinplot(y=data['CO2_Emissions'], orient=\"v\", ax = axes[1]);\n\n# add a value of mode in the empty subplot\n# fontsize: font size of the text\nplt.text(0.1, 200, \"Mode = 221\/246\", fontsize=12)\n\n# add a value of median in the empty subplot\n# fontsize: font size of the text\nplt.text(0.1, 300, \"Median = 246\", fontsize=12)\n\n# add a value of mean in the empty subplot\n# fontsize: font size of the text\nplt.text(0.1, 400, \"Mean = 251.16\", fontsize=12)\n\n# add the result in the empty subplot\n# fontsize: font size of the text\nplt.text(0.1, 100, \"Mode < Median < Mean\", fontsize=12)\n\n# remove the axis for the third subplot\nplt.axis(\"off\")\n\n# show the plot\nplt.show()\n\"\"\"\nOf all the three statistics, the mean is the largest, while the mode is the smallest thus CO2_Emissions is positively skewed which implies that most of the CO2 Emissions are less than the average CO2 Emissions.\n\"\"\"\n\"\"\"\n### 4.2.5 Analyse Relationship between Target and Independent Variables <a id='analyze_tar_ind_var'><\/a>\n\"\"\"\nmake_co2 = data.groupby('Make')['CO2_Emissions'].mean().sort_values(ascending=False).head(10)\nmodel_co2 = data.groupby('Model')['CO2_Emissions'].mean().sort_values(ascending=False).head(10)\nvehicle_class_co2 = data.groupby('Vehicle_Class')['CO2_Emissions'].mean().sort_values(ascending=False).head(10)\ntransmission_co2 = data.groupby('Transmission')['CO2_Emissions'].mean().sort_values(ascending=False).head(10)\nfuel_type_co2 = data.groupby('Fuel_Type')['CO2_Emissions'].mean().sort_values(ascending=False).head()\nfig, axes = plt.subplots(5,1, figsize=(15,20))\nfig.suptitle('Average of Categorical Variables vs CO2 Emissions')\n\nsns.barplot(ax=axes[0],x = make_co2.values,y = make_co2.index)\naxes[0].set_title('CO2 Emissions v\/s Make')\n\nsns.barplot(ax=axes[1],x = model_co2.values,y = model_co2.index)\naxes[1].set_title('CO2 Emissions v\/s Model')\n\nsns.barplot(ax=axes[2],x = vehicle_class_co2.values,y = vehicle_class_co2.index)\naxes[2].set_title('CO2 Emissions v\/s Vehicle_Class')\n\nsns.barplot(ax=axes[3],x = transmission_co2.values,y = transmission_co2.index)\naxes[3].set_title('CO2 Emissions v\/s Transmission')\n\nsns.barplot(ax=axes[4], x=fuel_type_co2.values,y=fuel_type_co2.index)\naxes[4].set_title('CO2 Emissions v\/s Fuel Type')\n\"\"\"\n<br>Inferences from each Plot:<\/br>\n<br>    1. CO2 Emissions v\/s Make: While Ford cars are mainly found on the roads of Canada , its Bugatti that emit the most CO2 per car<\/br>\n<br>    2. CO2 Emissions v\/s Model: Bugatti Chiron is amongst the most CO2 emitting car model<\/br>\n<br>    3. CO2 Emissions v\/s Vehicle_Class: Most of the heavy vehicles like Vans , SUV and Pick-up truck are amongst the top few emitters of CO2<\/br>\n<br>    4. CO2 Emissions v\/s Transmission: Most of the cars with automatic transmission emit CO2<\/br>\n<br>    5. CO2 Emissions v\/s Fuel_Type: Cars using Fuel Type E are emitting the most CO2<\/br>\n\"\"\"\n\"\"\"\n**Let's check the relationship between Cylinders and CO2 Emissions**\n\"\"\"\n# plot the scatter plot\n# use 'hue' to add 3rd variable in the scatter plot\nplt.rcParams[\"figure.figsize\"] = (15,10)\nsns.scatterplot('CO2_Emissions','Cylinders',data = data,hue='Fuel_Type')\n\n# set label for x-axis\nplt.xlabel(\"CO2 Emissions\", fontsize=20)\n\n# set label for y-axis\nplt.ylabel(\"Cylinders\", fontsize=20)\n\n# set title\nplt.title(\"Scatter Plot\", fontsize=20)\n\n# display the plot\nplt.show()\n\"\"\"\n<br>From the above scatter plot i can see that:<\/br>\n<br>    1. As the number of cylinders increase, the CO2 emissions increase<\/br>\n<br>    2. Cars with 8 and less than 8 cylinders prefer using Fuel Type X which result in less emissions of CO2<\/br>\n<br>    3. Fuel Type Z results in more CO2 emissions than the other<\/br>\n\"\"\"\nplt.figure(figsize=(10,5))\nsns.pairplot(data,kind=\"reg\")\nplt.show()\n\"\"\"\nInferences:\n    1. Fuel_Consumption_Comb1 shows a negative relation with all the other numerical variables\n    2. Fuel_Consumption_City and Fuel_Consumption_Hwy are strongly postively related\n\"\"\"\n\"\"\"\n### 4.2.6 Feature Engineering <a id='feature_eng'><\/a>\n\"\"\"\n\"\"\"\n**Create a new feature Make_Type by combining various car companies(Make) on the basis of their functionality**\n\"\"\"\n\"\"\"\n**There are 42 unique Car Companies. I will divide these companies into Luxury, Sports, Premium and General cars**\n\"\"\"\ndata['Make_Type'] = data['Make'].replace(['BUGATTI', 'PORSCHE', 'MASERATI', 'ASTON MARTIN', 'LAMBORGHINI',\n                                                       'JAGUAR','SRT'],\n                                                      'Sports')\ndata['Make_Type'] = data['Make_Type'].replace(['ALFA ROMEO', 'AUDI', 'BMW', 'BUICK',\n                                                         'CADILLAC', 'CHRYSLER', 'DODGE', 'GMC',\n                                                         'INFINITI', 'JEEP', 'LAND ROVER', 'LEXUS', 'MERCEDES-BENZ',\n                                                         'MINI', 'SMART', 'VOLVO'],\n                                                         'Premium')\ndata['Make_Type'] = data['Make_Type'].replace(['ACURA', 'BENTLEY', 'LINCOLN', 'ROLLS-ROYCE',\n                                                         'GENESIS'],\n                                                         'Luxury')\ndata['Make_Type'] = data['Make_Type'].replace(['CHEVROLET', 'FIAT', 'FORD', 'KIA',\n                                                         'HONDA', 'HYUNDAI', 'MAZDA', 'MITSUBISHI',\n                                                         'NISSAN', 'RAM', 'SCION', 'SUBARU', 'TOYOTA',\n                                                         'VOLKSWAGEN'],\n                                                         'General')\ndata['Make_Type'].unique()\ndata['Make_Type'].value_counts()\n#Drop Make column\ndata = data.drop(['Make'], axis=1)\ndata.head()\n# set figure size\nplt.figure(figsize=(15,8))\n\n# boxplot of claim against region\n# x: specifies the data on x axis\n# y: specifies the data on y axis\n# data: specifies the dataframe to be used\nax = sns.boxplot(x=\"Make_Type\", y=\"CO2_Emissions\", data=data)\n\n# rotate labels using set_ticklabels\n# labels: specify the tick labels to be used\n# rotation: the angle by which tick labels should be rotated\nax.set_xticklabels(labels=ax.get_xticklabels(), rotation=90)\n\n# show the plot\nplt.show()\n\"\"\"\nThe plot shows that Sports cars and Luxury cars emit more CO2 compared to Premium and General use cars\n\"\"\"\n\"\"\"\n**Create a new feature Vehicle_Class_Type by combining various Vehicle_Class on the basis of their size**\n\"\"\"\n\"\"\"\n**There are 16 unique Vehicle Classes. I will divide them into Hatchback, Sedan, SUV and Truck**\n\"\"\"\ndata['Vehicle_Class_Type'] = data['Vehicle_Class'].replace(['COMPACT', 'MINICOMPACT', 'SUBCOMPACT'],\n                                                      'Hatchback')\ndata['Vehicle_Class_Type'] = data['Vehicle_Class_Type'].replace(['MID-SIZE', 'TWO-SEATER', 'FULL-SIZE', 'STATION WAGON - SMALL',\n                                                         'STATION WAGON - MID-SIZE'],\n                                                         'Sedan')\ndata['Vehicle_Class_Type'] = data['Vehicle_Class_Type'].replace(['SUV - SMALL', 'SUV - STANDARD', 'MINIVAN'],\n                                                         'SUV')\ndata['Vehicle_Class_Type'] = data['Vehicle_Class_Type'].replace(['VAN - CARGO', 'VAN - PASSENGER', 'PICKUP TRUCK - STANDARD', 'SPECIAL PURPOSE VEHICLE',\n                                                         'PICKUP TRUCK - SMALL'],\n                                                         'Truck')\n# check the unique values of the Make_Type column\ndata['Vehicle_Class_Type'].unique()\ndata['Vehicle_Class_Type'].value_counts()\n#Drop Vehicle_Class column\ndata = data.drop(['Vehicle_Class'], axis=1)\ndata.head()\n# set figure size\nplt.figure(figsize=(15,8))\n\n# boxplot of claim against region\n# x: specifies the data on x axis\n# y: specifies the data on y axis\n# data: specifies the dataframe to be used\nax = sns.boxplot(x=\"Vehicle_Class_Type\", y=\"CO2_Emissions\", data=data)\n\n# rotate labels using set_ticklabels\n# labels: specify the tick labels to be used\n# rotation: the angle by which tick labels should be rotated\nax.set_xticklabels(labels=ax.get_xticklabels(), rotation=90)\n\n# show the plot\nplt.show()\n\"\"\"\nThe plot shows that the bigger the cars are the more CO2 they emit\n\"\"\"\n\"\"\"\n# 5. Data Preprocessing <a id='data_pre'><\/a>\n\"\"\"\ndata.drop(['Model'],axis=1,inplace=True)\n\"\"\"\nSince Model has 2053 unique values and has no significance with respect to CO2 Emissions , I have dropped this column\n\"\"\"\ndata.head()\n\"\"\"\n## 5.1 Outliers <a id='out'><\/a>\n\"\"\"\n\"\"\"\n### 5.1.1 Discovery of Outliers<a id='dis_out'><\/a>\n\"\"\"\ndf_num_features=data.select_dtypes(include=np.number)\n\"\"\"\n**Identifying outliers using IQR**\n\"\"\"\nQ1 = df_num_features.quantile(0.25)\nQ3 = df_num_features.quantile(0.75)\nIQR = Q3 - Q1\nprint(IQR)\noutlier = pd.DataFrame((df_num_features < (Q1 - 1.5 * IQR)) | (df_num_features > (Q3 + 1.5 * IQR)))\nfor i in outlier.columns:\n    print('Total number of Outliers in column {} are {}'.format(i, (len(outlier[outlier[i] == True][i]))))\n\"\"\"\n**Visualizing outliers using Boxplots**\n\"\"\"\nfor column in enumerate(df_num_features):\n    plt.figure(figsize=(30,5))\n    sns.set_theme(style=\"darkgrid\")\n    sns.boxplot(x=column[1], data=  df_num_features)\n    plt.xlabel(column[1],fontsize=18)\n    plt.show()\n\"\"\"\n### 5.1.2 Removal of Outliers<a id='rem_out'><\/a>\n\"\"\"\n\"\"\"\n**Checking the normality of numeric features**\n\"\"\"\nstat, p_value = shapiro(df_num_features)\n\n# print the test statistic and corresponding p-value \nprint('Test statistic:', stat)\nprint('P-Value:', p_value)\n\"\"\"\nSince the numeric features are not normal I am removing the outliers using IQR method\n\"\"\"\ndata = data[~((data < (Q1 - 1.5 * IQR)) |(data > (Q3 + 1.5 * IQR))).any(axis=1)]\ndata.shape\ndata.reset_index(inplace=True)\ndata.drop(['index'],inplace=True,axis=1)\ndata.head()\n\"\"\"\n### 5.1.3 Re-checking Correlation<a id='rec_cor'><\/a>\n\"\"\"\n# select the numerical features in the dataset using 'select_dtypes()'\n# select_dtypes(include=np.number): considers the numeric variables\ndata_num_features = data.select_dtypes(include=np.number)\n\n# print the names of the numeric variables \nprint('The numerical columns in the dataset are: ',data_num_features.columns)\n# generate the correlation matrix\ncorr =  data_num_features.corr()\n\n# print the correlation matrix\ncorr\nplt.figure(figsize=(20,10))\ncorr =data_num_features.corr(method='pearson')\nsns.heatmap(corr, annot=True,cmap='tab20b')\nplt.show()\n\"\"\"\nRecheck of correlation after treating outliers. There has been a slight change with respect to the correlation between numeric values\n\"\"\"\n\"\"\"\n## 5.2 Categorical Encoding<a id='cat_enc'><\/a>\n\"\"\"\n\"\"\"\n**Filter the numeric and categorical features**\n\"\"\"\ndf_dummies = pd.get_dummies(data = data[[\"Fuel_Type\",\"Transmission\",\"Make_Type\",\"Vehicle_Class_Type\"]], drop_first = True)\ndf_dummies.head()\ndf_num_features=data.select_dtypes(include=np.number)\ndf_num_features.head()\n\"\"\"\n**Concatenate numerical and dummy encoded categorical variables**\n\"\"\"\ndf_comb = pd.concat([df_num_features, df_dummies], axis = 1)\ndf_comb.head()\n\"\"\"\n# 6. Building Multiple Linear Regression Models<a id='bui_mlr_mod'><\/a>\n\"\"\"\ndf_comb.drop(['CO2_Emissions'],inplace=True,axis=1)\ndf_comb.head()\ndf_comb.isna().sum()\n\"\"\"\n## 6.1 Multiple Linear Regression - Basic Model<a id='bas_mod'><\/a>\n\"\"\"\nX = df_comb.copy()\nX = sm.add_constant(X)\ny = data.CO2_Emissions\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)\n\nMLR_model1 = sm.OLS(y_train, X_train).fit()\nprint(MLR_model1.summary())\n\"\"\"\nInterpretations:\n    1. 99.5% of the variation in CO2 emissions is explained by the model.\n    2. The Durbin-Watson test statistic is 2.006 and indicates that there is no auto-correlation\n    3. The Condition Number is 1.00e+16 which suggests that there is severe mutli-collinearity\n    4. The features taken into consideration are of different scales\n\"\"\"\n\"\"\"\n## 6.2 Feature Transformation<a id='fea_tra'><\/a>\n\"\"\"\ndf_num_features.skew()\n\"\"\"\nSince the skewness is relatively low, there is no need to perform any further transformations to reduce skewness\n\"\"\"\n\"\"\"\n## 6.3 Feature Scaling<a id='fea_sca'><\/a>\n\"\"\"\nfor col in df_num_features.columns:\n    print(\"Column \", col, \" :\", stats.shapiro(df_num_features[col]))\n\"\"\"\nSince none of the numerical features are normally distributed (p-value<0.05) , I will perform Min-Max normalisation to scale the data\n\"\"\"\ndf_num_features.drop('CO2_Emissions',axis=1,inplace=True)\nmms = preprocessing.MinMaxScaler()\nmmsfit = mms.fit(df_num_features)\ndfxz = pd.DataFrame(mms.fit_transform(df_num_features), columns = ['Engine_Size','Cylinders','Fuel_Consumption_City','Fuel_Consumption_Hwy','Fuel_Consumption_Comb','Fuel_Consumption_Comb1'])\ndfxz.head()\ndfxz = pd.concat([dfxz, df_dummies], axis = 1)\ndfxz.head()\n\"\"\"\n## 6.4 Multiple Linear Regression - Full Model - After Feature Scaling<a id='mod_aft_sca'><\/a>\n\"\"\"\nX=dfxz\nX = sm.add_constant(X)\ny = data.CO2_Emissions\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)\n\nMLR_model2 = sm.OLS(y_train, X_train).fit()\nprint(MLR_model2.summary())\n\"\"\"\nInterpretations:\n    1. 99.5% of the variation in CO2 emissions is explained by the model .\n    2. The Durbin-Watson test statistic is 2.006 and indicates that there is no auto-correlation\n    3. The Condition Number is 1.24e+16 which suggests that there is severe mutli-collinearity\n\"\"\"\n\"\"\"\n## 6.5 Assumptions Before Multiple Linear Regression Model<a id=\"ass_bef\"><\/a>\n\"\"\"\n\"\"\"\n### 6.5.1 Assumption #1: If Target Variable is Numeric<a id=\"tgt_num\"><\/a>\n\"\"\"\ntarget = data['CO2_Emissions']\n\ntarget.dtype\n\"\"\"\n### 6.5.2 Assumption #2: Presence of Multi-Collinearity<a id=\"pre_mul_col\"><\/a>\n\"\"\"\n# create an empty dataframe to store the VIF for each variable\nvif = pd.DataFrame()\n\n# calculate VIF using list comprehension \n# use for loop to access each variable \n# calculate VIF for each variable and create a column 'VIF_Factor' to store the values \nvif[\"VIF_Factor\"] = [variance_inflation_factor(df_num_features.values, i) for i in range(df_num_features.shape[1])]\n\n# create a column of variable names\nvif[\"Features\"] = df_num_features.columns\n\n# sort the dataframe based on the values of VIF_Factor in descending order\n# 'ascending = False' sorts the data in descending order\n# 'reset_index' resets the index of the dataframe\n# 'drop = True' drops the previous index\nvif.sort_values('VIF_Factor', ascending = False).reset_index(drop = True)\n\"\"\"\nSince all the features except Fuel_Consumption_Comb1 have a VIF value greater than 10 I cannot proceed with VIF method else I will lose all our features. Hence , I will proceed with PCA\n\"\"\"\nsklearn_pca = PCA()\npcafit = sklearn_pca.fit(dfxz)\npcafit.explained_variance_\npcafit.components_\nplt.plot(np.cumsum(pcafit.explained_variance_ratio_))\nplt.locator_params(axis=\"x\", nbins=len(pcafit.explained_variance_))\nplt.xlabel('number of components')\nplt.ylabel('cumulative explained variance');\n\"\"\"\nAs you can see from the above graph, 28 components describe almost 98% of variance in features\n\"\"\"\nnp.round(pcafit.explained_variance_ratio_.reshape(-1,1) * 100,1)\n\"\"\"\nThe above output indicates how much variance each component holds and the last 6 components hold no variance\n\"\"\"\ndfx_pca = sklearn_pca.fit_transform(dfxz)\ndfx_pca.shape\ndfx_pca = pd.DataFrame(dfx_pca, columns=['pca0','pca1','pca2','pca3','pca4','pca5',\n                                         'pca6','pca7','pca8','pca9','pca10','pca11',\n                                         'pca12','pca13','pca14','pca15','pca16',\n                                         'pca17','pca18','pca19','pca20','pca21','pca22',\n                                         'pca23','pca24','pca25','pca26','pca27','pca28',\n                                         'pca29','pca30','pca31','pca32','pca33',\n                                         'pca34','pca35','pca36','pca37','pca38','pca39',\n                                         'pca40'])\ndfx_pca.head()\n\"\"\"\n## 6.6 Multiple Linear Regression - Full Model - After PCA<a id=\"mod_pca\"><\/a>\n\"\"\"\ndfx_pca = sm.add_constant(dfx_pca)\nX = dfx_pca[['const','pca0','pca1','pca2','pca3','pca4','pca5','pca6','pca7','pca8','pca9','pca10','pca11','pca12','pca13','pca14','pca15','pca16','pca17','pca18','pca19','pca20','pca21','pca22','pca23','pca24','pca25','pca26','pca27','pca28','pca29','pca30','pca31','pca32','pca33']]\nX.head()\ny = data.CO2_Emissions\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)\n\nMLR_model_pca = sm.OLS(y_train, X_train).fit()\nprint(MLR_model_pca.summary())\n\"\"\"\nInterpretations:\n    1. 99.3% of the variation in CO2 emissions is explained by the model .\n    2. The Durbin-Watson test statistic is 2.053 and indicates that there is no auto-correlation\n    3. The Condition Number is 23.4 which suggests that there is no mutli-collinearity\n\"\"\"\n\"\"\"\n## 6.7 Feature Selection<a id=\"fea_sel\"><\/a>\n\"\"\"\n\"\"\"\n### 6.7.1 Forward Selection<a id=\"for_sel\"><\/a>\n\"\"\"\n# initiate linear regression model to use in feature selection\nlinreg = LinearRegression()\nlinreg_forward = sfs(estimator=linreg, k_features ='best', forward=True,\n                     verbose=2, scoring='r2')\n\n# fit the forward selection on training data using fit()\nsfs_forward = linreg_forward.fit(X_train, y_train)\n# print the selected feature names when k_features = 12\nprint('Features selected using forward selection are: ')\nprint(sfs_forward.k_feature_names_)\n\n# print the R-squared value\nprint('\\nR-Squared: ', sfs_forward.k_score_)\n\"\"\"\nAll features except pca_14 and pca_22 have been retained for the betterment of the model\n\"\"\"\n\"\"\"\n### 6.7.2 Backward Elimination<a id=\"bac_eli\"><\/a>\n\"\"\"\n# initiate linear regression model to use in feature selection\nlinreg = LinearRegression()\nlinreg_backward = sfs(estimator = linreg, k_features ='best', forward = False,\n                     verbose = 2, scoring = 'r2')\n\n# fit the backward elimination on training data using fit()\nsfs_backward = linreg_backward.fit(X_train, y_train)\n# print the selected feature names when k_features = 12\nprint('Features selected using backward elimination are: ')\nprint(sfs_backward.k_feature_names_)\n\n# print the R-squared value\nprint('\\nR-Squared: ', sfs_backward.k_score_)\n\"\"\"\nObtained similar results as that of Forward Selection where all features except pca_14 and pca_22 have been retained for the betterment of the model\n\"\"\"\n\"\"\"\n## 6.8 Multiple Linear Regression - Full Model - After Feature Selection<a id=\"mod_fea_sel\"><\/a>\n\"\"\"\nX = dfx_pca[['const','pca0', 'pca1', 'pca2', 'pca3', 'pca4', 'pca5', 'pca6', 'pca7', 'pca8', 'pca9', 'pca10', 'pca11', 'pca12', 'pca13', 'pca15', 'pca16', 'pca17', 'pca18', 'pca19', 'pca20', 'pca21', 'pca23', 'pca24', 'pca25', 'pca26', 'pca27', 'pca28', 'pca29', 'pca30', 'pca31', 'pca32', 'pca33']]\nX.head()\ny = data.CO2_Emissions\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)\n\nMLR_full_model = sm.OLS(y_train, X_train).fit()\nprint(MLR_full_model.summary())\n\"\"\"\nInterpretations:\n    1. 99.3% of the variation in CO2 emissions is explained by the model .\n    2. The Durbin-Watson test statistic is 2.051 and indicates that there is no auto-correlation\n    3. The Condition Number is 23.4 which suggests that there is no mutli-collinearity\n\"\"\"\n\"\"\"\n## 6.9 Assumptions After Multiple Linear Regression Model<a id=\"ass_aft\"><\/a>\n\"\"\"\n\"\"\"\n### 6.9.1 Assumption #1: Linear Relationship Between Dependent and Independent Variable<a id=\"lr_dep_ind\"><\/a>\n\"\"\"\nimport seaborn as sns \nfig, ax = plt.subplots(nrows = 2, ncols= 2, figsize=(20, 15))\n\n# use for loop to create scatter plot for residuals and each independent variable (do not consider the intercept)\n# 'ax' assigns axes object to draw the plot onto \nfor variable, subplot in zip(X_train.columns[1:5], ax.flatten()):\n    sns.scatterplot(X_train[variable], MLR_full_model.resid , ax=subplot)\n\n# display the plot\nplt.show()\n\"\"\"\n**Interpretation:** The above plots show no specific pattern, implies that there is a linearity present in the data.\n\"\"\"\n\"\"\"\n### 6.9.2 Assumption #2: Checking for Autocorrelation<a id=\"che_aut_cor\"><\/a>\n\"\"\"\n# print the model summary\nprint(MLR_full_model.summary())\n\"\"\"\n**Interpretation:** From the above summary, I can observe that the value obtained from the `Durbin-Watson` test statistic is close to 2 (= 2.051). Thus, I conclude that there is no autocorrelation.\n\"\"\"\n\"\"\"\n### 6.9.3 Assumption #3: Checking for Heteroskedasticity<a id=\"che_het\"><\/a>\n\"\"\"\n\"\"\"\nBreusch-Pagan is one of the tests for detecting heteroskedasticity in the residuals.<br>\nThe test hypothesis for the Breusch-Pagan test is given as:\n<p style='text-indent:25em'> <strong> H<sub>o<\/sub>:  There is homoscedasticity present in the data <\/strong> <\/p>\n<p style='text-indent:25em'> <strong> H<sub>1<\/sub>:  There is a heteroscedasticity present in the data <\/strong> <\/p>\n\"\"\"\n# create vector of result parmeters\nname = ['f-value','p-value']\ntest = sms.het_breuschpagan(MLR_full_model.resid, MLR_full_model.model.exog)\nlzip(name, test[2:])\n\"\"\"\n**Interpretation:** I observe that the p-value is less than 0.05; thus, I conclude that there is heteroskedasticity present in the data.\n\"\"\"\n\"\"\"\n### 6.9.4 Assumption #4: Tests for Normality<a id=\"tes_nor\"><\/a>\n\"\"\"\n\"\"\"\n#### 6.9.4.1 Q-Q Plot<a id=\"qq_plt\"><\/a>\n\"\"\"\n# set the plot size using 'rcParams'\n# once the plot size is set using 'rcParams', it sets the size of all the forthcoming plots in the file\n# pass width and height in inches to 'figure.figsize' \nplt.rcParams['figure.figsize'] = [15,8]\n\n# plot the Q-Q plot\n# 'r' represents the regression line\nqqplot(MLR_full_model.resid, line = 'r')\n\n# set plot and axes labels\n# set text size using 'fontsize'\nplt.title('Q-Q Plot', fontsize = 15)\nplt.xlabel('Theoretical Quantiles', fontsize = 15)\nplt.ylabel('Sample Quantiles', fontsize = 15)\n\n# display the plot\nplt.show()\n\"\"\"\n**Interpretation:** The diagonal line (red line) is the regression line and the blue points are the cumulative distribution of the residuals. As some of the points are not close to the diagonal line, I conclude that the residuals do not follow a `normal distribution`.\n\"\"\"\n\"\"\"\n#### 6.9.4.2 Shapiro Wilk Test<a id=\"sha_wil_tes\"><\/a>\n\"\"\"\n\"\"\"\nThe Shapiro Wilk test is used to check the normality of the residuals. The test hypothesis is given as:<br>\n\n<p style='text-indent:25em'> <strong> H<sub>o<\/sub>:  Residuals are normally distributed <\/strong> <\/p>\n<p style='text-indent:25em'> <strong> H<sub>1<\/sub>:  Residuals are not normally distributed <\/strong> <\/p>\n\"\"\"\nstat, p_value = shapiro(MLR_full_model.resid)\nprint('Test statistic:', stat)\nprint('P-Value:', p_value)\n\"\"\"\n**Interpretation:** From the above test I can see that the p-value is 2.153e-37 (less than 0.05), thus I can say that the residuals are not normally distributed.\n\"\"\"\n\"\"\"\n# 7. Model Evaluation<a id=\"mod_eva\"><\/a>\n\"\"\"\n\"\"\"\n## 7.1 Measures of Variation<a id=\"mea_var\"><\/a>\n\"\"\"\ny_train_pred = MLR_full_model.predict(X_train) \ny_train_pred.head()\n# calculate the SSR on train dataset\nssr = np.sum((y_train_pred - y_train.mean())**2)\nprint('Sum of Squared Regression:',ssr)\n# calculate the SSE on train dataset\nsse = np.sum((y_train - y_train_pred)**2)\nprint('Sum of Squared Error:',sse)\n# calculate the SST on train dataset\nsst = np.sum((y_train - y_train.mean())**2)\nprint('Sum of Sqaured Total:',sst)\nprint('Sum of SSR and SSE is:',ssr+sse)\n\"\"\"\n**Interpretation:** From the above output, I can verify that SST (Total variation) is the sum of SSR and SSE.\n\"\"\"\nr_sq =MLR_full_model.rsquared\n\n# print the R-squared value\nprint('R Squared is:',r_sq)\nsee = np.sqrt(sse\/(len(X_train) - 2))    \nprint(\"The standard error of estimate:\",see)\n\"\"\"\n## 7.2 Inferences about Intercept and Slope<a id=\"inf_int_slo\"><\/a>\n\"\"\"\nMLR_full_model.summary()\nt_intercept =MLR_full_model.params[0] \/ MLR_full_model.bse[0]\nprint('t intercept:',t_intercept)\nt_coeff1 =MLR_full_model.params[1] \/ MLR_full_model.bse[1]\nprint('t coeff:',t_coeff1)\n# calculate p-value for intercept\n# use 'sf' (Survival function) from t-distribution to calculate the corresponding p-value\n\n# pass degrees of freedom and t-statistic value for intercept\n# degrees of freedom = n - 1 = 4070 - 1 = 4069\npval = stats.t.sf(np.abs(t_intercept), 4069)*2 \nprint('p val for intercept:',pval)\n# calculate p-value for slope\n# use 'sf' (Survival function) from t-distribution to calculate the corresponding p-value\n\n# pass degrees of freedom and t-statistic value for slope\n# degrees of freedom = n - 1 = 4070 - 1 = 4069\npval = stats.t.sf(np.abs(t_coeff1),4069)*2 \nprint('p val for slope:',pval)\n\"\"\"\n## 7.3 Confidence Interval for Intercept and Slope<a id=\"con_int_slo\"><\/a>\n\"\"\"\n# CI for intercept\n# create a tuple using the above formula\n# here, t_table_value = 1.9622\nCI_inter_min, CI_inter_max = MLR_full_model.params[0] - (1.9622*MLR_full_model.bse[0]), MLR_full_model.params[0] + (1.9622*MLR_full_model.bse[0])\n\n# print the confidence interval for intercept \nprint('CI for intercept:', [CI_inter_min , CI_inter_max])\n# CI for slope\n# create a tuple using the above formula\n# here, t_table_value = 1.9622\nCI_coeff1_min, CI_coeff1_max = MLR_full_model.params[1] - (1.9622*MLR_full_model.bse[1]), MLR_full_model.params[1] + (1.9622*MLR_full_model.bse[1])\n\n# print the confidence interval for slope\nprint('CI for coeff1:', [CI_coeff1_min, CI_coeff1_max])\n\"\"\"\n## 7.4 Compare Regression Results<a id=\"com_reg_res\"><\/a>\n\"\"\"\nprint(MLR_full_model.summary())\nr_sq_mlr = MLR_full_model.rsquared\n\n# print the value\nprint('r square in regression model:',r_sq_mlr)\n\"\"\"\n**Interpretation:** The value of R-squared is 0.993. Thus, I conclude that the 99.3% variation in the CO2_Emissions is explained by the model. I can also obtain this value from the summary of the model.\n\"\"\"\n# calculate adjusted R-Squared on train dataset\n# use 'rsquared_adj' from statsmodel\nadj_r_sq = MLR_full_model.rsquared_adj\n\n# print the value\nprint('Adjusted r square for regression model:',adj_r_sq)\n\"\"\"\n**Interpretation:** I can see that the value of adjusted R-squared calculated using the formula and the one obtained from the model are nearly same. I can also obtain this value from the summary of the model.\n\"\"\"\n\"\"\"\nOverall F-Test & p-value of the Model\n\"\"\"\n# compute f_value using the below formula \n# f_value = (r_sq \/ k-1)\/((1- r_sq)\/n-k)\n\n# k = number of beta coefficients\nk = len(X_train.columns)\n\n# n = number of observations\nn = len(X_train)\n\n# calculate value of F-statistic\n# 'r_sq_mlr' represents the R-Squared value\nf_value = (r_sq_mlr \/ (k - 1))\/((1-r_sq_mlr)\/(n - k))\n\n# print the value\nprint('f value for regression model:',f_value)\n# degrees of freedom \n# dfn = k-1 = 32-1 = 31\n# dfd = n-k = 4396-32 = 4364\np_val = stats.f.sf(f_value, dfn = 31, dfd = 4364)\n\n# print the value\nprint('p value for regression model:',p_val)\n\"\"\"\n**Interpretation:** As, the p-value is less than 0.05, I accept the alternate hypothesis; i.e. the model is significant.\n\"\"\"\n\"\"\"\n# 8. Model Performance<a id=\"mod_per\"><\/a>\n\"\"\"\ntrain_pred = MLR_full_model.predict(X_train)\ntest_pred = MLR_full_model.predict(X_test)\ntrain_pred.head()\ntest_pred.head()\n\"\"\"\n## 8.1 Mean Squared Error (MSE)<a id=\"mse\"><\/a>\n\"\"\"\nmse_train = round(mean_squared_error(y_train, train_pred),4)\n\n# print the MSE for the training set\nprint(\"Mean Squared Error (MSE) on training set: \", mse_train)\n\n# calculate the MSE for the test data\n# round the value upto 4 digits using 'round()'\nmse_test = round(mean_squared_error(y_test, test_pred),4)\n\n# print the MSE for the test set\nprint(\"Mean Squared Error (MSE) on test set: \", mse_test)\n\"\"\"\n## 8.2 Root Mean Squared Error (RMSE)<a id=\"rmse\"><\/a>\n\"\"\"\n# calculate the MSE using the \"mean_squared_error\" function\n\n# MSE for the train data\nmse_train = mean_squared_error(y_train, train_pred)\nrmse_train = round(np.sqrt(mse_train), 4)\n\n# print the RMSE for the train set\nprint(\"Root Mean Squared Error (RMSE) on training set: \", rmse_train)\n\n# MSE for the test data\nmse_test = mean_squared_error(y_test, test_pred)\n\n# take the square root of the MSE to calculate the RMSE\n# round the value upto 4 digits using 'round()'\nrmse_test = round(np.sqrt(mse_test), 4)\n\n# print the RMSE for the test set\nprint(\"Root Mean Squared Error (RMSE) on test set: \", rmse_test)\n\"\"\"\n## 8.3 Mean Absolute Error (MAE)<a id=\"mae\"><\/a>\n\"\"\"\n# calculate the MAE using the \"mean_absolute_error\" function\n\n# calculate the MAE for the train data\n# round the value upto 4 digits using 'round()'\nmae_train = round(mean_absolute_error(y_train, train_pred),4)\n\n# print the MAE for the training set\nprint(\"Mean Absolute Error (MAE) on training set: \", mae_train)\n\n# calculate the MAE for the test data\n# round the value upto 4 digits using 'round()'\nmae_test = round(mean_absolute_error(y_test, test_pred),4)\n\n# print the MAE for the test set\nprint(\"Mean Absolute Error (MAE) on test set: \", mae_test)\n\"\"\"\n## 8.4 Mean Absolute Percentage Error (MAPE)<a id=\"mape\"><\/a>\n\"\"\"\ndef mape(actual, predicted):\n    return (np.mean(np.abs((actual - predicted) \/ actual)) * 100)\nmape_train = round(mape(y_train, train_pred),4)\n\n# print the MAPE for the training set\nprint(\"Mean Absolute Percentage Error (MAPE) on training set: \", mape_train)\n\n# calculate the MAPE for the test data\n# round the value upto 4 digits using 'round()'\nmape_test = round(mape(y_test, test_pred),4)\n\n# print the MAPE for the test set\nprint(\"Mean Absolute Percentage Error (MAPE) on test set: \", mape_test)\n\"\"\"\n## 8.5 Resultant Table<a id=\"res_tab\"><\/a>\n\"\"\"\ncols = ['Model_Name', 'R-squared', 'Adj. R-squared', 'MSE', 'RMSE', 'MAE', 'MAPE']\n\nresult_table = pd.DataFrame(columns = cols)\nfrom statsmodels.tools.eval_measures import rmse\n\nMLR_full_model_metrics = pd.Series({'Model_Name': \"MLR Full Model\",\n                     'R-squared': MLR_full_model.rsquared,\n                     'Adj. R-squared': MLR_full_model.rsquared_adj,\n                     'MSE': mean_squared_error(y_test, test_pred),\n                     'RMSE': rmse(y_test, test_pred),\n                     'MAE': mean_absolute_error(y_test, test_pred),\n                     'MAPE': mape(y_test, test_pred)\n                   })\n\nresult_table = result_table.append(MLR_full_model_metrics, ignore_index = True)\n\nresult_table\n\"\"\"\n# 9. Model Optimization<a id=\"mod_opt\"><\/a>\n\"\"\"\n\"\"\"\n## 9.1 BIAS <a id=\"bias\"><\/a>\n\"\"\"\nsns.regplot(y = y_train,x = train_pred,color='red',line_kws={'color':'blue'},marker='x')\n\"\"\"\n## 9.2 VARIANCE<a id=\"var\"><\/a>\n\"\"\"\na = np.random.randint(1,4070,1745)\ntrain_pred1 = list(train_pred)\nTrainPred2 = []\nfor i in a:\n    TrainPred2.append(train_pred1[i])\nsns.regplot(y = test_pred,x = TrainPred2)\n\"\"\"\n<b> INTERPRETATION<\/b>: The bias is low and variance is high, hence I assume that the model is a complex one. I will have to employ optimization techniques to reduce the complexity and RMSE.\n\"\"\"\n\"\"\"\n# 9.3. MODEL VALIDATION<a id=\"mod_val\"><\/a>\n\"\"\"\n\"\"\"\n## 9.3.1 Cross Validation<a id=\"cro_val\"><\/a>\n\"\"\"\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\n\nkf = KFold(n_splits = 10)\ndef Get_score(model, X_train_k, X_test_k, y_train_k, y_test_k):\n    model.fit(X_train_k, y_train_k)\n    return model.score(X_test_k, y_test_k)  \nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 10, test_size = 0.3)\nfrom sklearn.linear_model import LinearRegression\n\nscores = []\n \nfor train_index, test_index in kf.split(X_train):\n    X_train_k, X_test_k, y_train_k, y_test_k = X_train.iloc[train_index], X_train.iloc[test_index], \\\n                                               y_train.iloc[train_index], y_train.iloc[test_index]\n \n    scores.append(Get_score(LinearRegression(), X_train_k, X_test_k, y_train_k, y_test_k)) \n    \nprint('All scores: ', scores)\n\nprint(\"\\nMinimum score obtained: \", round(min(scores), 4))\n\nprint(\"Maximum score obtained: \", round(max(scores), 4))\n\nprint(\"Average score obtained: \", round(np.mean(scores), 4))\nscores = cross_val_score(estimator = LinearRegression(), \n                         X = X_train, \n                         y = y_train, \n                         cv = 10, \n                         scoring = 'r2')\nprint('All scores: ', scores)\n\nprint(\"\\nMinimum score obtained: \", round(min(scores), 4))\n\nprint(\"Maximum score obtained: \", round(max(scores), 4))\n\nprint(\"Average score obtained: \", round(np.mean(scores), 4))\n\"\"\"\n**The R2 value is similar to the one obtained in the MLR model. There are no significant changes.**\n\"\"\"\n\"\"\"\n## 9.3.2 Leave Out One Cross Validation(LOOCV)<a id=\"loocv\"><\/a>\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 10, test_size = 0.2)\ndef Get_score(model, X_train_k, X_test_k, y_train_k, y_test_k):\n    model.fit(X_train_k, y_train_k)                              \n    return model.score(X_test_k, y_test_k)\nloocv_rmse = []\nloocv = LeaveOneOut()\n\nfor train_index, test_index in loocv.split(X_train):\n\n    X_train_l, X_test_l, y_train_l, y_test_l = X_train.iloc[train_index], X_train.iloc[test_index], \\\n                                               y_train.iloc[train_index], y_train.iloc[test_index]\n    \n    linreg = LinearRegression()\n    linreg.fit(X_train_l, y_train_l)\n \n    mse = mean_squared_error(y_test_l, linreg.predict(X_test_l))\n    \n    rmse = np.sqrt(mse)\n    \n    loocv_rmse.append(rmse)\nprint(\"\\nMinimum rmse obtained: \", round(min(loocv_rmse), 4))\n\nprint(\"Maximum rmse obtained: \", round(max(loocv_rmse), 4))\n \nprint(\"Average rmse obtained: \", round(np.mean(loocv_rmse), 4))\n\"\"\"\n# 9.4 GRADIENT DESCENT<a id=\"gra_des\"><\/a>\n\"\"\"\ndef get_train_rmse(model):\n\n    train_pred = model.predict(X_train)\n\n    mse_train = mean_squared_error(y_train, train_pred)\n\n    rmse_train = round(np.sqrt(mse_train), 4)\n\n    return(rmse_train)\ndef get_test_rmse(model):\n\n    test_pred = model.predict(X_test)\n\n    mse_test = mean_squared_error(y_test, test_pred)\n\n    rmse_test = round(np.sqrt(mse_test), 4)\n\n    return(rmse_test)\nfrom sklearn.linear_model import SGDRegressor\n\nsgd = SGDRegressor(random_state = 10)\n\nlinreg_with_SGD = sgd.fit(X_train, y_train)\n\nprint('RMSE on train set:', get_train_rmse(linreg_with_SGD))\n\nprint('RMSE on test set:', get_test_rmse(linreg_with_SGD))\ndef plot_coefficients(model, algorithm_name):\n\n    df_coeff = pd.DataFrame({'Variable': X.columns, 'Coefficient': model.coef_})\n\n    sorted_coeff = df_coeff.sort_values('Coefficient', ascending = False)\n\n    sns.barplot(x = \"Coefficient\", y = \"Variable\", data = sorted_coeff)\n\n    plt.xlabel(\"Coefficients from {}\".format(algorithm_name), fontsize = 15)\n\n    plt.ylabel('Features', fontsize = 15)\nMLR_model = linreg.fit(X_train, y_train)\nplt.subplot(1,2,1)\nplot_coefficients(MLR_model, 'Linear Regression (OLS)')\n\nplt.subplot(1,2,2)\nplot_coefficients(linreg_with_SGD, 'Linear Regression (SGD)')\n\nplt.tight_layout()\nscore_card = pd.DataFrame(columns=['Model_Name', 'Alpha (Wherever Required)', 'l1-ratio', 'R-Squared',\n                                       'Adj. R-Squared', 'Train_RMSE','Test_RMSE', 'Test_MAPE'])\ndef get_test_mape(model):\n\n    test_pred = model.predict(X_test)\n\n    mape_test = mape(y_test, test_pred)\n\n    return(mape_test)\ndef get_score(model):\n    \n    r_sq = model.score(X_train, y_train)\n\n    n = X_train.shape[0]\n\n    k = X_train.shape[1]\n\n    r_sq_adj = 1 - ((1-r_sq)*(n-1)\/(n-k-1))\n    \n    return ([r_sq, r_sq_adj])\ndef update_score_card(algorithm_name, model, alpha = '-', l1_ratio = '-'):\n    \n    global score_card\n    score_card = score_card.append({'Model_Name': algorithm_name,\n                       'Alpha (Wherever Required)': alpha, \n                       'l1-ratio': l1_ratio, \n                       'Test_MAPE': get_test_mape(model),\n                       'Train_RMSE': get_train_rmse(model),\n                       'Test_RMSE': get_test_rmse(model), \n                       'R-Squared': get_score(model)[0], \n                       'Adj. R-Squared': get_score(model)[1]}, ignore_index = True)\nupdate_score_card(algorithm_name = 'Linear Regression (using SGD)', model = linreg_with_SGD)\n\nscore_card\n\"\"\"\n# 9.5  Regularization<a id=\"reg\"><\/a>\n\"\"\"\n\"\"\"\n## 9.5.1 Ridge Regression Model<a id=\"ridge\"><\/a>\n\"\"\"\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.model_selection import GridSearchCV\nridge = Ridge(alpha = 0.1, max_iter = 500)\n\nridge.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(ridge))\nupdate_score_card(algorithm_name='Ridge Regression (with alpha = 0.1)', model = ridge, alpha = 0.1)\n\nscore_card\nridge = Ridge(alpha = 1, max_iter = 500)\n\nridge.fit(X_train, y_train)\n\nprint('RMSE on test set:', np.round(get_test_rmse(ridge),2))\nupdate_score_card(algorithm_name='Ridge Regression (with alpha = 1)', model = ridge, alpha = 1)\n\nscore_card\nridge = Ridge(alpha = 2, max_iter = 500)\n\nridge.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(ridge))\nupdate_score_card(algorithm_name='Ridge Regression (with alpha = 2)', model = ridge, alpha = 2)\n\nscore_card\nridge = Ridge(alpha = 0.5, max_iter = 500)\n\nridge.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(ridge))\nplt.subplot(1,2,1)\nplot_coefficients(MLR_model, 'Linear Regression (OLS)')\n\nplt.subplot(1,2,2)\nplot_coefficients(ridge, 'Ridge Regression (alpha = 0.5)')\n\nplt.tight_layout()\n\"\"\"\n<b>Interpretation:<\/b> The coefficients obtained from ridge regression have similar values as compared to the coefficients obtained from linear regression using OLS.\n\"\"\"\n\"\"\"\n## 9.5.2 Lasso Regression Model<a id=\"lasso\"><\/a>\n\"\"\"\nlasso = Lasso(alpha = 0.01, max_iter = 500)\n\nlasso.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(lasso))\nplt.subplot(1,2,1)\nplot_coefficients(MLR_model, 'Linear Regression (OLS)')\n\nplt.subplot(1,2,2)\nplot_coefficients(lasso, 'Lasso Regression (alpha = 0.01)')\n\nplt.tight_layout()\nlasso = Lasso(alpha = 0.05, max_iter = 500)\n\nlasso.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(lasso))\nplt.subplot(1,2,1)\nplot_coefficients(MLR_model, 'Linear Regression (OLS)')\n\nplt.subplot(1,2,2)\nplot_coefficients(lasso, 'Lasso Regression (alpha = 0.05)')\n\nplt.tight_layout()\n\"\"\"\n<b>Interpretation<\/b>: The second subplot (on the right) shows that the lasso regression have reduced the coefficients of some variables to zero.\n\"\"\"\ndf_lasso_coeff = pd.DataFrame({'Variable': X.columns, 'Coefficient': lasso.coef_})\n\nprint('Insignificant variables obtained from Lasso Regression when alpha is 0.05')\ndf_lasso_coeff.Variable[df_lasso_coeff.Coefficient == 0].to_list()\nupdate_score_card(algorithm_name = 'Lasso Regression', model = lasso, alpha = '0.05')\n\nscore_card\n\"\"\"\n## 9.5.3 Elastic-Net Regression Model<a id=\"ela_net\"><\/a>\n\"\"\"\nenet = ElasticNet(alpha = 0.1, l1_ratio = 0.55, max_iter = 500)\n\nenet.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(enet))\nupdate_score_card(algorithm_name = 'Elastic Net Regression', model = enet, alpha = '0.1', l1_ratio = '0.55')\n\nscore_card\nenet = ElasticNet(alpha = 0.1, l1_ratio = 0.1, max_iter = 500)\n\nenet.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(enet))\nupdate_score_card(algorithm_name = 'Elastic Net Regression', model = enet, alpha = '0.1', l1_ratio = '0.1')\n\nscore_card\nenet = ElasticNet(alpha = 0.1, l1_ratio = 0.01, max_iter = 500)\n\nenet.fit(X_train, y_train)\n\nprint('RMSE on test set:', get_test_rmse(enet))\nplt.subplot(1,2,1)\nplot_coefficients(MLR_model, 'Linear Regression (OLS)')\n\nplt.subplot(1,2,2)\nplot_coefficients(enet, 'Elastic Net Regression')\n\nplt.tight_layout()\n\"\"\"\n<b>Interpretation<\/b>: The second subplot (on the right) shows that the elastic-net regression has reduced the coefficients of some variables to zero.\n\"\"\"\nupdate_score_card(algorithm_name = 'Elastic Net Regression', model = enet, alpha = '0.1', l1_ratio = '0.01')\n\nscore_card\n\"\"\"\n## 9.5.4 Grid Search CV<a id=\"gri_sea\"><\/a>\n\"\"\"\ntuned_paramaters = [{'alpha':[1e-15, 1e-10, 1e-8, 1e-4,1e-3, 1e-2, 0.1, 1, 5, 10, 20, 40, 60, 80, 100]}]\n \nridge = Ridge()\n\nridge_grid = GridSearchCV(estimator = ridge, \n                          param_grid = tuned_paramaters, \n                          cv = 10)\n\nridge_grid.fit(X_train, y_train)\n\nprint('Best parameters for Ridge Regression: ', ridge_grid.best_params_, '\\n')\n\nprint('RMSE on test set:', get_test_rmse(ridge_grid))\nupdate_score_card(algorithm_name = 'Ridge Regression (using GridSearchCV)', \n                  model = ridge_grid, \n                  alpha = ridge_grid.best_params_.get('alpha'))\n\nscore_card\ntuned_paramaters = [{'alpha':[1e-15, 1e-10, 1e-8, 0.0001, 0.001, 0.01, 0.1, 1, 5, 10, 20]}]\n \nlasso = Lasso()\n\nlasso_grid = GridSearchCV(estimator = lasso, \n                          param_grid = tuned_paramaters, \n                          cv = 10)\n\nlasso_grid.fit(X_train, y_train)\n\nprint('Best parameters for Lasso Regression: ', lasso_grid.best_params_, '\\n')\n\nprint('RMSE on test set:', get_test_rmse(lasso_grid))\nupdate_score_card(algorithm_name = 'Lasso Regression (using GridSearchCV)', \n                  model = lasso_grid, \n                  alpha = lasso_grid.best_params_.get('alpha'))\n\nscore_card\ntuned_paramaters = [{'alpha':[0.0001, 0.001, 0.01, 0.1, 1, 5, 10, 20, 40, 60],\n                      'l1_ratio':[0.0001, 0.0002, 0.001, 0.01, 0.1, 0.2, 0.4, 0.55]}]\n\nenet = ElasticNet()\n\nenet_grid = GridSearchCV(estimator = enet, \n                          param_grid = tuned_paramaters, \n                          cv = 10)\n\nenet_grid.fit(X_train, y_train)\n\nprint('Best parameters for Elastic Net Regression: ', enet_grid.best_params_, '\\n')\n\nprint('RMSE on test set:', get_test_rmse(enet_grid))\nupdate_score_card(algorithm_name = 'Elastic Net Regression (using GridSearchCV)', \n                  model = enet_grid, \n                  alpha = enet_grid.best_params_.get('alpha'), \n                  l1_ratio = enet_grid.best_params_.get('l1_ratio'))\n\nscore_card\n\"\"\"\n# 10. Displaying score summary<a id=\"dis_sco_sum\"><\/a>\n\"\"\"\nscore_card = score_card.sort_values('Test_RMSE').reset_index(drop = True)\n\nscore_card.style.highlight_min(color = 'lightblue', subset = 'Test_RMSE')\n\"\"\"\nInterpretation: I can see that Lasso Regression (using GridSearchCV) has the lowest test RMSE.\n\"\"\"\n# plot the accuracy measure for all models\n# secondary_y: specify the data on the secondary axis\nscore_card.plot(secondary_y=['R-Squared','Adj. R-Squared'])\n\n# display just the plot\nplt.show()\n\"\"\"\nThe graph shows the performance metrics root mean squared error, R-squared and Adjusted R-squared of the models implemented: the X-axis has the model number as given in the table. \nThe plot gives a clear picture of the inverse relation of R squared values and the RMSE value, the better the R-squared value naturally the lesser is the RMSE value.\nFindings suggest that the Lasso Regression (using GridSearchCV) has the highest accuracy with lowest RMSE. Finally, it can be concluded that the Lasso Regression (using GridSearchCV) can be used to predict the amount of carbon dioxide emissions.\n\"\"\"\n\"\"\"\n# 11. Conclusion<a id=\"conclu\"><\/a>\n\"\"\"\n\"\"\"\n**Of all the optimization techniques used, I see that Lasso Regression using Grid search CV has been the most effective in reducing RMSE . the exact combination of features responsible for high CO2 emissions cannot be predicted  Since all the features are highly correlated . I can hereby conclude that I have successfully built a model that can predict amount of CO2 Emissions across different vehicle types at a high accuracy rate.**\n\"\"\"\n\"\"\"\n# 12.Deployment<a id=\"deploy\"><\/a>\n\"\"\"\n\"\"\"\nhttps:\/\/coemission.herokuapp.com\/\n\"\"\"\n\"\"\"\n# 13. References<a id=\"Refer\"><\/a>\n\"\"\"\n\"\"\"\nhttps:\/\/reader.elsevier.com\/reader\/sd\/pii\/S2352484719301088?token=807922D7C5CF2E7E78C846212A5D7F97FFCC0B513EDBEAAC2626D7FB0DBE7EFE67FEBE723E7610FC62CA1FA0F5B5110A&originRegion=eu-west-1&originCreation=20210510125616\n\"\"\"\n\"\"\"\nhttps:\/\/sci-hub.se\/https:\/\/ieeexplore.ieee.org\/abstract\/document\/7984819\n\"\"\"\n\"\"\"\nhttps:\/\/scihub.se\/https:\/\/www.sciencedirect.com\/science\/article\/abs\/pii\/S0959652620329875\n\"\"\"\n\"\"\"\n<table align=\"center\" width=100%>\n    <tr>\n        <td width=\"30%\">\n            <img src=\"https:\/\/i.pinimg.com\/originals\/60\/00\/50\/600050674a955d69dc5930c45321be30.gif\">\n        <\/td>\n        <td>\n            <div align=\"center\">\n                <font color=\"#208807 \" size=24px>\n                    <b>Thank You.\n                    <\/b>\n                <\/font>\n            <\/div>\n        <\/td>\n    <\/tr>\n<\/table>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd6df9ab76d11bb'}"}
{"id":"118275","text":"\"\"\"\n# COVID-19: BERT-based STS Method to Effectively Identify Articles related to Therapeutics and Vaccines\n\n* #### Team: MD-Lab, ASU\n* #### Author: Mihir Parmar\n* #### Team Members: Rishab Banerjee, Hong Guan, Jitesh Pabla, Ashwin Karthik Ambalavanan, Murthy Devarakonda\n* #### Email ID: loccapollo@gmail.com, hguan6@asu.edu, jpabla1@asu.edu, aambalav@asu.edu, Murthy.Devarakonda@asu.edu\n* #### Kaggle ID: loccapollo, hongguan, jiteshpabla, aambalav, murthydevarakonda\n* #### This is a Team Submission\n\"\"\"\n\"\"\"\n### On March 19, 2020, the White House Office of Science and Technology Policy (WH-OSTP) issued a statement announcing the release of an extensive machine-readable collection of scientific articles about COVID-19, SARS-CoV-2, and the coronavirus group, jointly by several institutions including National Library of Medicine and Allen Institute for AI, and WH-OSTP: \n> the institutions in issuing a call to action to the Nation\u2019s artificial intelligence experts to develop new text and data mining techniques that can help the science community answer high-priority scientific questions related to COVID-19\n### The dataset called COVID-19 Open Research Dataset (CORD-19) presently has nearly 59,000 articles (extracted from various archives), with more than 35,000 of which have full text. The institutions further compiled a series of questions to be answered. For example, some questions related to COVID-19 vaccines and therapeutics are:\n* Effectiveness of drugs being developed and tried to treat COVID-19 patients.\n* Exploration of use of best animal models and their predictive value for a human vaccine.\n* Efforts targeted at a universal coronavirus vaccine.\n* Efforts to develop prophylaxis clinical studies and prioritize in healthcare workers\n\"\"\"\n\"\"\"\n![corona.jpeg](attachment:corona.jpeg)\n\"\"\"\n\"\"\"\n# Project Description\n\nThe objective of this project is to use the state-of-the-art Clinical Semantic Textual Similarity (STS) technique to create a method to search an answer for the given query through the dataset of research papers provided as a part of [Kaggle's competition CORD-19-research-challenge](https:\/\/www.kaggle.com\/allen-institute-for-ai\/CORD-19-research-challenge). Currently, we are considering a limited amount of given text (Titles + Abstracts + Journals) for each paper to show the effectiveness of the proposed approach. Gradually, this project could be extended into a scientific search system where you can extract machine-readable scientific data for a given query for further analysis.\n\"\"\"\n\"\"\"\n# Proposed Methodology\n\nNeural Networks have become more popular in the domain of information retrieval. As we know, BERT-based scoring systems outperform previous approaches to the document retrieval as shown in [Yang et al. 2019](https:\/\/www.aclweb.org\/anthology\/D19-3004.pdf). Here, we are using Clinical Semantic Textual Similarity (STS)-based novel approach for document scoring. The primary aim of this method is to find documents that are most relevant to the given query. Here, we have used the Clinical STS dataset from [n2c2 Challange 2019](https:\/\/n2c2.dbmi.hms.harvard.edu\/) to fine-tune the BERT model. As illustrated in below figure (a), we have used BERT model for Next Sentence Prediction, and feed pair of sentences together ([CLS]Sentence 1[SEP]Sentence 2) to the BERT at training time, and used CLS token embedding for predicting similarity score between two sentences. The core idea behind using this model is that we want to generate embedding which contains the relevance between sentence 1 and sentence 2. Here, we have used Linear Regression (LR) as a regression model. The dataset consists of two sentences and their clinical semantic similarity score ranging from 0 to 5.0. The following is an example of a data item from the dataset. As can be seen from the example, the two sentences are to be scored on their semantic similarity.\n\nSentence 1: Neuro:  Proximal and distal strength in the upper and lower extremities is grossly intact.\t\nSentence 2: The distal circulation, sensation, and motor function is intact.\t\nSimilarity score: 2.5\/5.0\n\nBERT with linear regression on the top of the output CLS token is trained with the ClinicalSTS dataset. As a model input shown in figure (b), the query Q and the document text A are concatenated as a text sequence [[CLS] Q [SEP] A [SEP]], where document A = [title + abstract + journal], and passed through the trained BERT + linear regression to obtain a similarity score between Q and A. \n\"\"\"\n\"\"\"\n![(a) Fine-tuning, (b) Fine-tuned model](attachment:bertmodel.jpeg)\n\"\"\"\n\"\"\"\nIn this simple approach, long text poses a problem since base-BERT can handle only the 512 length of sentence at a time. In this case, we have research papers with full body text. Based on Yang et al. 2019, we presented sentence level inference as a solution to this problem. Hence, we generated the score for each sentence in the given document and aggregate that score to produce the document score. To get the score for the whole document, we simply devise function inspired by [Kotzias et al. 2015](https:\/\/dl.acm.org\/doi\/10.1145\/2783258.2783380) that assumes that the score of a document is obtained by averaging the score of its top n sentences. Assume candidate document d and corresponding set of sentences $\\mathcal{S}$ from d. Hence, document score ($S_d$) is given by below averaging formula:\n\n$S_d = \\frac{1}{|\\mathcal{S}|} \\sum_{i=0}^{n} \\text{score}(s_i)$,\n\nwhere $\\text{score}(s_i)$ denoted the function which gererates similarity score corresponding to the given input. In this formula, we are only considering the top n sentences from given text with high scores because they are more responsible for identifying the text. At the end, we normalized the obtained score between [0,1].\n\"\"\"\n\"\"\"\n## Scalability of Proposed Model\n\nIn this work, a limited amount of data (i.e., [title + abstract + journal]) is used to show the effectiveness of this given methodology. However, this model is easily scalable on the full-text of the given research article since it is using a sentence level inference for calculating the similarity score between the query and given article. You can see our interactive implementation of the proposed model and scale it as per your requirements.  \n\"\"\"\n\"\"\"\n# Implementation\n\nWe present a notebook that makes it possible for anyone to reproduce our system or modify it according to their requirements. We made our fine-tuned BERT models available and code to use it. Our notebook is set up to allow similarity score to be calculated for given test set collection (i.e., set of research articles in this competition). Here, we fine-tuned the BERT base model with a learning rate $2 x 10^{-4}$ for 10 epochs.\n\nFor the implementation of the above approach, we have used [Pytorch](https:\/\/pytorch.org\/) implementation of the BERT model by [huggingface](https:\/\/huggingface.co\/transformers\/index.html). All Code, Models, Data and Results mentioned in this Kernel are well documented and available in this [GitHub Link](https:\/\/github.com\/md-labs\/covid19-kaggle\/tree\/Mihir_3009\/scripts).\n\"\"\"\n# importing important libraries for code\n\nimport csv\nimport os\nimport random\nimport sys\n\nimport numpy as np\nimport pandas as pd\nfrom os import listdir\nfrom os.path import isfile, join\nimport unidecode\nimport re\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,TensorDataset)\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.autograd import Variable\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tqdm import tqdm, trange\nfrom scipy.stats.stats import pearsonr\n\nfrom transformers import BertTokenizer, BertConfig\nfrom transformers import AdamW, BertModel\n# Checking for GPU availability\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\nn_gpu = torch.cuda.device_count()\nprint(\"device: {} n_gpu: {}\".format(device, n_gpu))\n\"\"\"\nFor the fine-tuning of the BERT, we used the Clinical STS dataset from [n2c2 Challange 2019](https:\/\/n2c2.dbmi.hms.harvard.edu\/). This dataset is not publicly available. Hence, we haven't provided a code here for fine-tuning of the BERT, however, you can visit our [GitHub link](https:\/\/github.com\/md-labs\/covid19-kaggle\/tree\/Mihir_3009\/scripts) for this script for fine-tuning and tried out some other scientific or clinical STS datasets. Here, the fine-tuned model of the BERT on the Clinical STS dataset is uploaded for further use. You can use the below code to use this fine-tuned model.\n\"\"\"\n# Use this class for linear regression model\n\nclass linearRegression(nn.Module):\n    def __init__(self):\n        super(linearRegression, self).__init__()\n        self.linear = nn.Linear(768, 1)  # input and output is 1 dimension\n\n    def forward(self, x):\n        out = self.linear(x)\n        return out\n# Initializing the fine-tuned model\n\nmodel_class= BertModel\nmodel_dir= '..\/input\/models\/'\n\n# Load a trained model and config that you have fine-tuned\ntokenizer = BertTokenizer.from_pretrained('..\/input\/tokenizer\/bert-base-uncased-vocab.txt')\nmodel = model_class.from_pretrained(model_dir)\nregression = torch.load(join(model_dir,\"regression_model.pth\"), map_location=torch.device(device))\nmodel.to(device)\nregression.to(device)\n\n# Initializing the parameters\nmax_seq_length= 128\nbatch_size=1\n\"\"\"\nThe main aim of this work is to provide a system that can give you documents that are relevant to the given query. Here, you can provide your custom query to get the desired output. This model uses several queries that are likely to be useful in searching for a vaccine and therapeutics related articles. The COVID-19 dataset challenge questions are leveraged for this purpose. Examples are:\n\n* Q1: Vaccine vaccination dose antitoxin serum immunization inoculation for COVID-19 or coronavirus related research work\n* Q2: Therapeutics treatment therapy drug antidotes cures remedies medication prophylactic restorative panacea for COVID-19 or coronavirus\n\nWe provided the model output in the result section.\n\"\"\"\n# You can update this query list for your desire output\n\nquery_list = ['vaccine vaccination dose antitoxin serum immunization inoculation for covid 19 or coronavirus related research work', \n              'therapeutics treatment therapy drug antidotes cures remedies medication prophylactic restorative panacea for covid 19 or coronavirus']\n\"\"\"\nBelow is the code for computing similarity score between the query and given scientific article. You can modify this code according to your requirements.\n\"\"\"\n#Initialize evaluation mode\nmodel.eval()\nregression.eval()\n\n#Loading the test set given by this challange\ntest_path= '..\/input\/CORD-19-research-challenge\/metadata.csv'\ndf_test= pd.read_csv(test_path)\n\n#Empty List for saving the final computated score\nfinal_score= list()\nquery_number=1\n\n# Loop that calculate score corresponding to each query given in above list\nfor query in query_list:\n    for i in range(len(df_test)):\n        \n        # Aggregating the [title + abstract + journal]. You can modify it according to your input\n        document= str(df_test.iloc[i].title) + str(df_test.iloc[i].abstract) + str(df_test.iloc[i].journal)\n    \n        iteration = int(len(document)\/max_seq_length)\n    \n        if iteration==0:\n            final_score.append(0)\n            continue\n    \n        result= list()\n        sentence= list()\n        \n        # Loop for create sentence inputs\n        for i in range(0,iteration):\n            sent= document[(i*max_seq_length):(i+1)*max_seq_length]\n            sentence.append(sent)\n        \n        df_temp= pd.DataFrame(sentence, columns=['d_sent'])\n        df_temp['q']= query\n    \n        # Create text sequence\n        sentences_1 = df_temp.q\n        sentences_2 = df_temp.d_sent\n    \n        # We need to add special tokens at the beginning and end of each sentence for BERT to work properly\n        special_sentences_tempe_1 = [\"[CLS] \" + sentence for sentence in sentences_1]\n        special_sentences_tempe_2 = [\" [SEP] \" + sentence for sentence in sentences_2]\n        special_sentences = [i + j for i, j in zip(special_sentences_tempe_1, special_sentences_tempe_2)]\n        \n        tokenized_texts = [tokenizer.tokenize(sentence) for sentence in special_sentences]\n        \n        # Max sentence input \n        MAX_LEN = max_seq_length\n        \n        # Use the BERT tokenizer to convert the tokens to their index numbers in the BERT vocabulary\n        input_sentences = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]\n        \n        # Pad our input tokens\n        input_sentences = pad_sequences(input_sentences, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n        \n        # Create attention Masks\n        attention_masks = []\n        \n        # Create a mask of 1s for each token followed by 0s for padding\n        \n        for seq in input_sentences:\n            seq_mask = [float(i>0) for i in seq]\n            attention_masks.append(seq_mask)\n        \n        # Convert all of our data into torch tensors, the required datatype for our model\n        test_inputs = torch.tensor(input_sentences)\n        test_masks = torch.tensor(attention_masks)\n        \n        # Select a batch size for training. For fine-tuning BERT on a specific task, the authors recommend a batch size of 16 or 32\n        batch_size = batch_size\n        \n        # Create an iterator of our data with torch DataLoader. This helps save on memory during training because, unlike a for loop,\n        # with an iterator the entire dataset does not need to be loaded into memory\n        test_data = TensorDataset(test_inputs, test_masks)\n        test_sampler = RandomSampler(test_data)\n        test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=batch_size)\n        \n        # Loop for calculating the similarity score corresponding to each sentence\n        for step, batch in enumerate(test_dataloader):\n            input_ids, input_mask= batch\n            input_ids=input_ids.to(device)\n            input_mask=input_mask.to(device)\n            \n            outputs = model(input_ids, attention_mask=input_mask)\n            last_hidden_states = outputs[1]\n            pred_score= regression(last_hidden_states)\n            pred_score= np.squeeze(pred_score, axis=1)\n            pred_score = pred_score.detach().cpu().numpy()\n            result.extend(pred_score)\n            \n        result.sort(reverse=True)\n        \n        # This is to calculate final score. Here, we are using max sentence score only. You can change it according to your requirement.\n        \n        final_score.append(max(result)\/5)\n    \n    result_query= 'q'+str(query_number)+'_score'\n    query_number+=1\n    df_test[result_query]= final_score\n\n# Saving the final results as output.csv file\ndf_test.to_csv('..\/input\/output\/output.csv')\n\"\"\"\n# Results\n\nHere, I have provided results for two queries:\n\n* Q1: Vaccine vaccination dose antitoxin serum immunization inoculation for COVID-19 or coronavirus related research work\n* Q2: Therapeutics treatment therapy drug antidotes cures remedies medication prophylactic restorative panacea for COVID-19 or coronavirus\n\nUsing these two queries, I have predicted the labels corresponding to each paper. For that, you can refer below code:\n\"\"\"\npath= '..\/input\/output\/output.csv'\ndf= pd.read_csv(path)\n\nlabel= list()\n\nfor i in range(len(df)):\n    other_prob= 1 - df.iloc[i].q1_score - df.iloc[i].q2_score\n    \n    if other_prob<0:\n        other.append(0)\n    else:\n        other.append(other_prob)\n    \n    max_val= max(df.iloc[i].q1_score, df.iloc[i].q2_score, other_prob)\n    \n    if max_val==df.iloc[i].vaccine:\n        l='vaccine'\n    elif max_val==df.iloc[i].therapeutics:\n        l='therapeutics'\n    elif max_val==other_prob:\n        l='other'\n    \n    label.append(l)\n\ndf['label']= label\n\"\"\"\nTo calculate the label, we are calculating maximum score for each query and give label accoding to it. Below you can see the results of the above method.\n\"\"\"\ndf = pd.read_csv(\"..\/input\/output\/final_data.csv\")\ndf.head(40) # prints the first 40 rows of the table.\n\"\"\"\n# Future Plans and Remarks\n\nThis work describes the novel methodology based on STS for a straightforward application of BERT to compute similarity score and classify in particular tasks via sentence-level inference and aggregate scoring. In the future, we are planning to extend this approach for full-text. Moreover, we are planning to use more scientific and Clinical STS datasets for fine-tuning BERT to improve the results on this dataset.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd99a10a7c7ab98'}"}
{"id":"124254","text":"\"\"\"\n# Data Proccessing\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ngame = pd.read_csv(\"..\/input\/videogamesales\/vgsales.csv\")\ngame\n\"\"\"\n# Plot Top 10 games Global\n\"\"\"\ntop_10 = game[0:10]\ntop_10\nplt.figure(figsize = (18,8))\nplt.barh(top_10[\"Name\"],top_10[\"Global_Sales\"])\nplt.title(\"Top 10 games Global Sales\",fontdict = {\"fontsize\":20})\nplt.savefig(\"Top 10 games Global Sales.jpg\",dpi = 300)\nplt.show()\n\"\"\"\n# Top 5 Publisher\n\"\"\"\nPublisher = list(game.Publisher.unique())\nglobal_sale_of_every_Publisher = pd.Series(dtype = float)\nfor pub in Publisher :\n    data = game.loc[game.Publisher == pub]\n    global_sale = sum(data.Global_Sales)\n    global_sale_of_every_Publisher[pub] = global_sale\ntop_5 = global_sale_of_every_Publisher[:5]\nplt.figure(figsize = (10.5,9))\nplt.pie(top_5,labels = top_5.index,autopct = \"%.2f%%\",textprops = {\"fontsize\":13},labeldistance = 1.05)\nplt.legend(loc = 4,fontsize  = 12)\nplt.title(\"Top 5 Publisher of Games\",fontdict = {\"fontsize\":25,\"fontweight\":100})\nplt.savefig(\"Top 5 Publisher of Games\",dpi = 300)\nplt.show()\n\"\"\"\n# Groth of the 1st Publisher of games over years\n\"\"\"\nNintendo = game.loc[game.Publisher == \"Nintendo\"]\nNintendo_1 = Nintendo.sort_values(by = \"Year\")\nNintendo_1 = Nintendo_1.dropna()\nNintendo_years = Nintendo.Year.unique()\nNintendo_profit_year = pd.Series(dtype = float)\nfor yea in Nintendo_years:\n    data_of_year = Nintendo_1.loc[Nintendo_1.Year == yea]\n    total_of_year = data_of_year.Global_Sales.sum(axis = 0)\n    Nintendo_profit_year[yea] = total_of_year\nNintendo_profit_year = Nintendo_profit_year.sort_index()\nNintendo_profit_year = Nintendo_profit_year\nplt.plot(Nintendo_profit_year)\nplt.xlabel(\"Years\",size = 14)\nplt.ylabel(\"Unit Sales\",size = 14)\nplt.title(\"Nintendo Gloal Sales from 1983 to 2016\",fontdict = {\"fontsize\":15})\nplt.xticks([i for i in range(1983,2017,3)])\nplt.savefig(\"Nintendo Gloal Sales from 1983 to 2016\",dpi = 300)\nplt.show()\n\"\"\"\n# Plot Genre of Games\n\"\"\"\nGenre = game.Genre\nGenre = Genre.value_counts()\nplt.figure(figsize = (8,8))\nlabels = Genre.index\ncolors = [\"#0033ff\",\"#ff0800\",\"#f700ff\",\"#eeff00\",\"#51ff00\",\"#00ffdd\",\"#ff9d00\",\"#850012\",\"#c7714a\",\"#04615b\",\"#ab8d5e\",\"#00004a\"]\nplt.pie(Genre,labels = labels,colors = colors,autopct = \"%.2f%%\") \nplt.title(\"Games Top Genres\",fontdict = {\"fontsize\":20})\nplt.savefig(\"Games Top Genres\",dpi = 300)\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'e47fb2122cddc2'}"}
{"id":"40382","text":"\"\"\"\n# Tabular Playground Series - Jan 2021\n\n## If you have any suggestions feel free to leave a comment !\n\"\"\"\n\"\"\"\n# Setup\n\"\"\"\n# Data Manipulation\nimport pandas as pd\nimport numpy as np\n\n# Data Visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Models\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n# Read data\ntrain = pd.read_csv('..\/input\/tabular-playground-series-jan-2021\/train.csv', index_col='id')\ntest = pd.read_csv('..\/input\/tabular-playground-series-jan-2021\/test.csv', index_col='id')\n# Predictors & Target\npredictors = train.columns[:-1]\ntarget = train.columns[-1]\n# Styling\nplt.style.use('ggplot')\nplt.rcParams['axes.titlesize'] = 16\nplt.rcParams['axes.labelsize'] = 12\nplt.rcParams['xtick.labelsize'] = 'large'\n\"\"\"\n# Exploration\n\"\"\"\n# Size\nprint('Train set shape:', train.shape)\nprint('Test set shape:', test.shape)\n# Missing data\nprint('Missing values on the train data:', train.isnull().sum().sum())\nprint('Missing values on the test data:', test.isnull().sum().sum())\n# Duplicated data\nprint('Duplicated rows on the train data:', train.duplicated().sum())\nprint('Duplicated rows on the test data:', test.duplicated().sum())\n\"\"\"\n## Univariate Analysis\n\n### Target\n\"\"\"\n# Target\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)\nax1.title.set_text('Target Distribution')\nsns.distplot(train[target], ax=ax1)\nsns.boxplot(train[target], orient='h', ax=ax2);\n\"\"\"\n### Predictors\n\"\"\"\n# Distribution in test set\nplt.figure(figsize=(10, 5))\nplt.title('Distribution of predictors')\nsns.boxplot(data=pd.melt(train[predictors]), x='variable', y='value');\n# Distribution curve\nfig, axs = plt.subplots(7, 2, figsize=(12, 12))\nfor ax, pred in zip(axs.flatten(), predictors):\n    sns.distplot(train.loc[:, pred], ax=ax)\nplt.tight_layout()\n\"\"\"\n## Bivariate Analysis\n\n### Correlation\n\"\"\"\n# Correlation\ncorr = train.corr()\nplt.figure(figsize=(10, 10))\nplt.title('High Correlation - greater\/lower than +\/- 60%')\nsns.heatmap(corr[abs(corr) > 0.6], annot=True, cmap=\"YlGnBu\", square=True, linewidths =.5);\n\"\"\"\n### Link between predictor and target\n\"\"\"\n# Scatter plot\nfig, axs = plt.subplots(7, 2, figsize=(14, 16))\nfor ax, pred in zip(axs.flatten(), predictors):\n    train.plot.hexbin(x=pred, y=target, gridsize=(80, 20), ax=ax)\nplt.tight_layout()\n\"\"\"\n# Data Cleaning\n\n## Remove outliers\n\"\"\"\n# Remove observations with +\/- 1.5 IQR\n# Quantiles & IQR\nq1 = train.quantile(0.25)\nq3 = train.quantile(0.75)\niqr = q3 - q1\n\n# Selection\nmask = (train >= (q1 - 1.5*iqr)) & (train <= q3 + 1.5*iqr)\ntrain = train[mask.apply(all, axis=1)]\n\nprint('Train set without outliers shape:', train.shape)\n\"\"\"\n# Model XGBoost\n\n## Split data\n\"\"\"\n# Split ratio 0.2\nX_train, X_val, y_train, y_val = train_test_split(train[predictors], \n                                                  train[target], \n                                                  test_size = 0.2, \n                                                  random_state=2021)\n\"\"\"\n## Define, train and test XGB model\n\"\"\"\n# XGB\nmodel = XGBRegressor(objective='reg:squarederror',\n                     booster = \"gbtree\",\n                     eval_metric = \"rmse\",\n                     tree_method = \"gpu_hist\",\n                     n_estimators = 1000,\n                     learning_rate = 0.04,\n                     eta = 0.1,\n                     max_depth = 7,\n                     subsample=0.85,\n                     colsample_bytree = 0.85,\n                     colsample_bylevel = 0.8,\n                     alpha = 0,\n                     random_state = 2021)\n# Fit mode\n%time model.fit(X_train, y_train)\n# Test\ny_val_pred = model.predict(X_val)\nprint('Validation Set RMSE:', np.sqrt(mean_squared_error(y_val, y_val_pred)))\n\"\"\"\n# Submission\n\"\"\"\n# Make predictions\ntest['target'] = model.predict(test[predictors])\n\n# Save\ntest['target'].to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': '4a64eb6816b329'}"}
{"id":"22531","text":"\"\"\"\n# Introduction\n\nSo we all have heard of matrices and vectors, and we use numpy all the time. But what is the importance of it. Why can't we just use a for-loop instead of using the numpy syntax, np.(function_name here). The difference is in performance.\n\nIn this notebook, I will be running only dot products and element wise multiplication. Feel free to fork the notebook and try different input sizes, or different commonly used operations.\n\nVectorized implementations (numpy) are much faster and more efficient as compared to for-loops. To really see HOW large the difference is, let's try some simple operations used in most machine learnign algorithms (especially deep learning).\n\"\"\"\n# 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)\nimport time\nimport matplotlib.pyplot as plt\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        pass\n        \nprint(\"Finished Importing Libraries\")\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\n\"\"\"\nSo, first let's create 2 new vectors each with 1 million rows, all with random numbers.\n\"\"\"\nv1 = np.random.rand(1000000, 1)\nv2 = np.random.rand(1000000, 1)\n\"\"\"\n# Multiplication by a Scalar\n\"\"\"\n\"\"\"\nScaling a vector by a constant is important in processes like normalization. Quite often, there are for-loop implementations used, which take unnecessary amounts of time.\n\nLet's look at the difference.\n\"\"\"\n# Scaling Vector - For loop\nstart = time.process_time()\nv1_scaled = np.zeros((1000000, 1))\n\nfor i in range(len(v1)):\n    v1_scaled[i] = 2 * v1[i]\n\nend = time.process_time()\n    \nprint(\"Scaling vector Answer = \" + str(v1_scaled))\nprint(\"Time taken = \" + str(1000*(end - start)) + \" ms\")  \n#Scaling Vector - Vectorized\nstart = time.process_time()\nv1_scaled = np.zeros((1000000, 1))\n\nv1_scaled = 2 * v1\n\nend = time.process_time()\n    \nprint(\"Scaling vector Answer = \" + str(v1_scaled))\nprint(\"Time taken = \" + str(1000*(end - start)) + \" ms\")  \n\"\"\"\nWow, vectorization is almost 300 times faster than for-loops. That is impressive.\n\"\"\"\n\"\"\"\n# Dot Products\n\"\"\"\n\"\"\"\nNow we are going to perform the dot product of the two vectors. This is the formula used to multiply the different values of the features of a training example and the weights that the model has learned. In deep learning, this process is repeated lots and lots of times. Even simple algorithms like Linear Regression make use of this a lot.\n\nIf you are not familiar with the formula, it is basically multiplying the two vectors element wise and then summing all of the elements. Here is the for loop implementation.\n\"\"\"\n# Dot product For loop\nstart = time.process_time()\nproduct = 0\n\nfor i in range(len(v1)):\n    product += v1[i] * v2[i]\n\nend = time.process_time()\n\nprint(\"Dot product Answer = \" + str(product))\nprint(\"Time taken = \" + str(1000*(end - start)) + \" ms\")\n\"\"\"\nNow the vectorized implementation.\n\"\"\"\n#Dot product Vectorized\nstart = time.process_time()\nproduct = 0\n\nproduct = np.dot(v1.T, v2)\n\nend = time.process_time()\n\nprint(\"Dot product Answer = \" + str(product))\nprint(\"Time taken = \" + str(1000*(end - start)) + \" ms\")\n\"\"\"\nWow, vectorized implementation is roughtly 600 times faster! (It may change slightly, but overall it should roughly be the same).\n\"\"\"\n\"\"\"\n# Element Wise multiplication\n\"\"\"\n\"\"\"\nAnother important operation is just multiplying the two vectors element wise. Let's see the difference between the for-loop and vectorized version for this.\n\"\"\"\n#Element wise mutliplication For loop\nstart = time.process_time()\n\nanswer = np.zeros((1000000, 1))\n\nfor i in range(len(v1)):\n    answer[i] = v1[i] * v2[i]\n    \nend = time.process_time()\n\nprint(\"Element Wise answer = \" + str(answer))\nprint(\"Time Taken = \" + str(1000*(end - start)) + \" ms\")\n#Element wise multiplication Vectorized\nstart = time.process_time()\n\nanswer = np.zeros((1000000, 1))\n\nanswer = v1 * v2\n\nend = time.process_time()\n\nprint(\"Element Wise answer = \" + str(answer))\nprint(\"Time Taken = \" + str(1000*(end - start)) + \" ms\")\n\"\"\"\nWow, vectorized implementation is almost 500 times faster! \nHuge boost in performance.\n\n\"\"\"\n\"\"\"\n# Element Wise Matrix Multiplication\n\nNow let's investigate element wise matrix multiplication. Since this will have a complexity of O(n2), I will use smaller matrix sizes (just enough to see a good difference, but not too large).\n\"\"\"\n#Element wise matrix multiplication For loop\n\nm1 = np.random.rand(1000, 1000)\nm2 = np.random.rand(1000, 1000)\nanswer = np.zeros((1000, 1000))\n\nstart = time.process_time()\n\nfor i in range(m1.shape[0]):\n    for j in range(m1.shape[1]):\n        answer[i, j] = m1[i, j] * m2[i, j]\n    \nend = time.process_time()\n\nprint(\"Element Wise Matrix answer = \" + str(answer))\nprint(\"Time Taken = \" + str(1000*(end - start)) + \" ms\")\n#Element wise matrix multiplication Vectorized\nanswer = np.zeros((1000, 1000))\n\nstart = time.process_time()\n\nanswer = np.multiply(m1, m2)\n\nend = time.process_time()\n\nprint(\"Element Wise Matrix answer = \" + str(answer))\nprint(\"Time Taken = \" + str(1000*(end - start)) + \" ms\")\n\"\"\"\nWow, Numpy is almost 370 times faster than for-loops. This is going to save lots of time. Imagine having hundreds of features and millions of rows. Using a for-loop would unnecessariy kill your computer.\n\"\"\"\n\"\"\"\n# Time-complexity Plot\n\nNow let's try and plot the performance over different sizes of input. This way, we can actually compare how each method's time complexity grows.\n\"\"\"\nsizes = [10, 100, 1000, 10000, 100000, 1000000, 10000000]\ncomplexity = pd.DataFrame(columns=['sizes', 'for_loop', 'numpy'])\ncomplexity['sizes'] = sizes\n\"\"\"\nI will be using a for-loop to iterate through all of the input sizes (excuse me).\n\"\"\"\nfor_loops = []\nnumpy = []\n\nfor size in sizes:\n    v1 = np.random.rand(size, 1)\n    v2 = np.random.rand(size, 1)\n    \n    #For loop implementation\n    start = time.process_time()\n    product = 0\n\n    for i in range(len(v1)):\n        product += v1[i] * v2[i]\n\n    end = time.process_time()\n    \n    for_loops.append(1000*(end-start))\n    \n    #Vectorized implementation\n    \n    start = time.process_time()\n    product = 0\n\n    product = np.dot(v1.T, v2)\n\n    end = time.process_time()\n    numpy.append(1000*(end - start))\n    \ncomplexity['for_loops'] = for_loops\ncomplexity['numpy'] = numpy\nplt.plot(complexity['sizes'], complexity['for_loops'])\nplt.plot(complexity['sizes'], complexity['numpy'])\n\nplt.xscale(value='log')\nplt.xlabel(\"Size of input\")\nplt.ylabel(\"Time taken in ms\")\nplt.legend(['for loop', 'numpy'])\nplt.show()\n\"\"\"\nMy God!! Look at the way the for-loop implementation grows and compare that with numpy. Numpy is almost flat, but for loop grows drastically (by the way, the graph actually grows linearly, I have just made the x-axis logarithmic as it makes reading the plot a lot easier.\n\n\n# Summary\n\nIf you are curious, for-loop looks like it is following the time-complexity of O(N). Numpy however, is basically following a complexity of O(1). \n\nMost real-world datasets used for ML\/AI use millions or billions of rows. As you can see from the plot, using vectorized implementations can save a lot of time.\n\n\n\nSo I just have 1 final request: Please use vectorized implementations using numpy or pandas whenever you can. Try to avoid using for-loops, it will save you a lot of time (and money if you use servers).\n\n\nI hoped you like this simple analysis of why you should try using numpy (make friends with the library. It will reward you).\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '297388536b702a'}"}
{"id":"33546","text":"\"\"\"\nIn this kernel, we will try to predict the 'Aggregate rating' based on the other features.\n\"\"\"\n\"\"\"\n**First we will import some important libraries which we will use in the pre-processing and EDA**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\"\"\"\nThen we will upload our data to a DataFrame.\n\"\"\"\ndf = pd.read_csv('..\/input\/zomato.csv', encoding='iso-8859-1')\n\"\"\"\nLet's take a look at the 2 first rows of our dataset:\n\"\"\"\ndf.head(2)\n\"\"\"\nWe can see that there are text columns, categorical columns, and numerical columns.\nLet's take a deeper look at our columns properties.\n\"\"\"\ndf.columns\ndf.shape\ndf.info()\ndf.describe()\n\"\"\"\nWe can see that there are 21 columns in our dataset. In addition, in this kernel we are not going to use the text columns, so we won't consider them at our machine learning model. \n\"\"\"\n\"\"\"\nWe can also see some information about our target: the mean of 'Aggragate rating' is 2.66 and the standart diviation is 1.51. The min score is 0 and the max score is 4.9.\n\"\"\"\n\"\"\"\n***\n\"\"\"\n\"\"\"\nNow we will make some visualizations to get a better understanding of our data.\n\"\"\"\nsns.set(rc={'figure.figsize':(9,7)})\nsns.countplot(x='Has Table booking',data=df,palette='viridis')\n\"\"\"\nWe can see that most of the tables havn't been booked.\n\"\"\"\nsns.countplot(x='Has Online delivery',data=df,palette='viridis',order=['Yes','No'])\nsns.countplot(x='Is delivering now',data=df,palette='viridis',order=['Yes','No'])\n\"\"\"\nWith this plot, it seems that there are no deliveries. Let's take a look at the numbers.\n\"\"\"\ndf['Is delivering now'].value_counts()\n\"\"\"\nWe can see that there are only 34 restaurants who make deliveries. Because of this imbalance in the data, we will not use this feature.\n\"\"\"\ndf['Switch to order menu'].value_counts()\n\"\"\"\nIn this column there is only one option, so we will not use this column also.\n\"\"\"\nsns.countplot(x='Price range',data=df,palette='viridis')\n\"\"\"\nWe can see that from all the price category, the low price category has most of the restaurants.\n\"\"\"\nsns.countplot(x='Rating text',data=df,palette='viridis')\n\"\"\"\nWe can see that in this column the data is in a normal distribution.\n\"\"\"\nsns.countplot(x='Rating color',data=df,palette='viridis')\n\"\"\"\nIt looks like this data here is just the same as the 'Rating text', so we will use the Rating text column.\n\"\"\"\nsns.distplot(df['Aggregate rating'], hist=True,kde=False,bins=20,color = 'blue',hist_kws={'edgecolor':'black'})\n\"\"\"\nWe can see that most of the data is distributed in a normal distribution, but there are also restaurants who got a rating of 0.\n\"\"\"\n\"\"\"\n***\n\"\"\"\n\"\"\"\nNow, we will do some **feature engineering** and try to get more from our dataset.\n\"\"\"\n\"\"\"\nFirst, we have to change the cost column. Let's look at how many currencies we have.\n\"\"\"\ndf['Currency'].unique()\n\"\"\"\nSo we have 12 different currencies. We have to treat each currency different. The currency rate was taken from www.XE.com.\nWe will convert each cost to dollars.\n\"\"\"\ndf['new cost'] = 0\ndf['Currency'].unique()\nd = {'Botswana Pula(P)':0.095, 'Brazilian Real(R$)':0.266,'Dollar($)':1,'Emirati Diram(AED)':0.272,\n    'Indian Rupees(Rs.)':0.014,'Indonesian Rupiah(IDR)':0.00007,'NewZealand($)':0.688,'Pounds(\\x8c\u00a3)':1.314,\n    'Qatari Rial(QR)':0.274,'Rand(R)':0.072,'Sri Lankan Rupee(LKR)':0.0055,'Turkish Lira(TL)':0.188}\n\ndf['new cost'] = df['Average Cost for two'] * df['Currency'].map(d) \ndf.head(2)\nsns.heatmap(data=df.corr(),cmap='coolwarm',annot=True)\n\"\"\"\nWe can see that the 'price range', 'votes' and the 'new cost' correlated with our target, so we will use them in our model. \n\"\"\"\n\"\"\"\nNow we will try to do some **Exploratory data analysis** in order to get a better understanding of the connection between our features, and between the features and the target.\n\"\"\"\n\"\"\"\nWe will first add new feature from our target to understand it better.\n\"\"\"\ndf['new Rating'] = 0\nmask1 = (df['Aggregate rating'] < 1)\nmask2 = (df['Aggregate rating'] >= 1) & (df['Aggregate rating'] < 2)\nmask3 = (df['Aggregate rating'] >= 2) &(df['Aggregate rating'] < 3)\nmask4 = (df['Aggregate rating'] >= 3) & (df['Aggregate rating'] < 4)\nmask5 = (df['Aggregate rating'] >= 4)\n\ndf['new Rating'] = df['new Rating'].mask(mask1, 'Low')\ndf['new Rating'] = df['new Rating'].mask(mask2, 'Medium -')\ndf['new Rating'] = df['new Rating'].mask(mask3, 'Medium')\ndf['new Rating'] = df['new Rating'].mask(mask4, 'Medium +')\ndf['new Rating'] = df['new Rating'].mask(mask5, 'High')\nsns.set(rc={'figure.figsize':(18,6)})\nsns.countplot(data=df,x='new Rating',order=['Low','Medium -','Medium','Medium +','High'])\n\"\"\"\nWe can see that most of the restaurants have aggregate rating between 3 to 4.\n\"\"\"\nsns.set(rc={'figure.figsize':(18,6)})\nsns.scatterplot(data=df,x='Aggregate rating',y='Votes')\nplt.ylim(0,1000)\nplt.xlim(1,5)\n\"\"\"\nWe can see correlation between the number of votes and the aggregate rating, but we can see that it isn't strong.\n\"\"\"\nsns.countplot(data=df,x='Aggregate rating',hue='Has Table booking',palette='viridis')\nsns.countplot(data=df,x='Aggregate rating',hue='Has Online delivery',palette='viridis')\n\"\"\"\nWe can see that there is a bigger correlation between the delivery feature than the table booking feature. But, we can see that both of them can help the model, so we will use them both.\n\"\"\"\ndf.head(2)\n\"\"\"\nNow, after we deecided which columns we will use, we have to create subset from our dataset.\n\"\"\"\nnew_df = df[['Has Table booking','Has Online delivery','Price range','Rating text','Votes','new cost','Aggregate rating']]\nnew_df.head()\n\"\"\"\nWe can see that we have some features that have to be encoded in order to fit the machine learning algorithms (the scikit-learn library can't get any text).\n\"\"\"\nnew_df = pd.get_dummies(new_df, columns=['Has Table booking','Has Online delivery','Price range','Rating text'])\nnew_df.head()\n\"\"\"\nNow our data is ready for prediction models. Let's start.\n\"\"\"\n\"\"\"\n***\n\"\"\"\n\"\"\"\n# Linear Regression\n\"\"\"\nX = new_df.drop(['Aggregate rating'], axis=1)\ny = new_df['Aggregate rating']\nfrom sklearn import model_selection\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n# implementation of Linear Regression model using scikit-learn and K-fold for stable model\nfrom sklearn.linear_model import LinearRegression\nkfold = model_selection.KFold(n_splits=10)\nlr = LinearRegression()\nscoring = 'r2'\nresults = model_selection.cross_val_score(lr, X, y, cv=kfold, scoring=scoring)\nlr.fit(X_train,y_train)\nlr_predictions = lr.predict(X_test)\nprint('Coefficients: \\n', lr.coef_,'\\n')\nprint(results)\nprint(results.sum()\/10)\nfrom sklearn import metrics\n\nprint('MAE:', metrics.mean_absolute_error(y_test, lr_predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, lr_predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, lr_predictions)))\nfrom sklearn.metrics import r2_score\nprint(\"R_square score: \", r2_score(y_test,lr_predictions))\n\"\"\"\n***\n\"\"\"\n\"\"\"\n# Desicion Trees\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\ndtr = DecisionTreeRegressor(random_state = 42)\ndtr.fit(X_train,y_train)\ndtr_predictions = dtr.predict(X_test) \nresults = model_selection.cross_val_score(dtr, X, y, cv=kfold, scoring='r2')\nprint(results)\nprint(results.sum()\/10)\n\n# R^2 Score\nprint(\"R_square score: \", r2_score(y_test,dtr_predictions))\n\"\"\"\n***\n\"\"\"\n\"\"\"\n# Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nrfr = RandomForestRegressor(n_estimators = 100)\nrfr.fit(X_train,y_train)\nrfr_predicitions = rfr.predict(X_test) \nresults = model_selection.cross_val_score(dtr, X, y, cv=kfold, scoring='r2')\nprint(results)\nprint(results.sum()\/10)\n\n# R^2 Score\nprint(\"R_square score: \", r2_score(y_test,rfr_predicitions))\n\"\"\"\n***\n\"\"\"\n\"\"\"\n# Gardient Boost\n\"\"\"\nfrom sklearn import ensemble\nclf = ensemble.GradientBoostingRegressor(n_estimators = 400, max_depth = 5, min_samples_split = 2,\n          learning_rate = 0.1, loss = 'ls')\nclf.fit(X_train, y_train)\nclf_predicitions = clf.predict(X_test) \nresults = model_selection.cross_val_score(dtr, X, y, cv=kfold, scoring='r2')\nprint(results)\nprint(results.sum()\/10)\nprint(\"R_square score: \", r2_score(y_test,clf_predicitions))\n\"\"\"\n***\n\"\"\"\ny = np.array([r2_score(y_test,lr_predictions),r2_score(y_test,dtr_predictions),r2_score(y_test,rfr_predicitions),\n           r2_score(y_test,clf_predicitions)])\nx = [\"LinearRegression\",\"RandomForest\",\"DecisionTree\",\"Grdient Boost\"]\nplt.bar(x,y)\nplt.title(\"Comparison of Regression Algorithms\")\nplt.ylabel(\"r2_score\")\nplt.show()","meta":"{'source': 'AI4Code', 'id': '3dd4294f903768'}"}
{"id":"80862","text":"\"\"\"\n# India's COVID-19 Exploratory analysis\n---\n\"\"\"\n\"\"\"\n![](https:\/\/e3.365dm.com\/21\/03\/1600x900\/skynews-india-vaccine-graphic_5325213.jpg?bypass-service-worker&20210331165132)\n\"\"\"\n\"\"\"\n### **About**\n\"\"\"\n\"\"\"\nThis document contains basic exploaratory data analysis of COVID-19 Disease in India. This notebook serves to analyze and visualize the progress of the pandemic from various perspectives.\n\nData used in this notebook is complied from https:\/\/api.covid19india.org\/\n\n**Feel free to point out mistakes and give feedback since I am novice.\nAny suggestions are welcome.\nIf you like work Please upvote and share.**\n\"\"\"\n\"\"\"\n### **Introduction**\n\"\"\"\n\"\"\"\nThe first signs of **COVID-19 in India** was reported in some towns of Kerala, among three Indian medical students who had returned from Wuhan. After that, the Government of India had announced lockdown on **25 March 2020**. India faced its **first wave** from May 2020 to January 2020 with an Amplitude of around **90,000** new infections a day. As of now India is going under second wave which has proved to be more deadlier than previous one.\n\"\"\"\n\"\"\"\n## 1. Cases, Deaths and Recovery\n\"\"\"\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib import dates as mpl_dates\nind_covid_df = pd.read_csv('..\/input\/indias-covid19-cases\/case_time_series.csv')\nind_covid_df\nind_covid_df.info()\nind_covid_df.isnull().sum()\n\"\"\"\nWe can see that it doesn't contain any null or missing values.Hence it reduces our work\n\"\"\"\nind_covid_df['Date_YMD'] = pd.to_datetime(ind_covid_df['Date_YMD'])\nind_covid_df.tail(1)\ntotal_cases = ind_covid_df['Total Confirmed']\ndates = ind_covid_df['Date_YMD']\ncurr_date = dates.max()\ncurr_total_cases = int(total_cases.tail(1))\ndates.max()\nfilt = ind_covid_df.Date_YMD==dates.max()\ntoday_cases = int(ind_covid_df.loc[filt, 'Daily Confirmed'])\n\ntoday_deaths = int(ind_covid_df.loc[filt, 'Daily Deceased'])\n\ntoday_recovered = int(ind_covid_df.loc[filt, 'Daily Recovered'])\n\ncurr_total_deaths = int(ind_covid_df.loc[filt, 'Total Deceased'])\n\ncurr_total_recovered = int(ind_covid_df.loc[filt, 'Total Recovered'])\nplt.style.use('fivethirtyeight')\n# total_cases.plot(figsize=(10,6))\nplt.figure(figsize=(10,6))\nplt.plot(dates, total_cases.values\/10**6, color='#0000a0')\n# plt.plot(total_deaths.index, total_deaths.values, linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.xlabel('')\nplt.ylabel('Count (in Millions)',fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=13)\nplt.suptitle('Total Cases by Time', fontsize=20)\n\nplt.annotate(text=str(curr_total_cases), xy=(curr_date,curr_total_cases\/10**6),\n             xycoords='data', xytext=(-80,1), textcoords='offset points', fontsize=14)\n\"\"\"\nThe logarithmic rise of total cases was observed from July end 2020 till December 2020 which seemed to saturate in january 2020. But April 2020 onwards, cases started to increase at much higher rate than before\n\"\"\"\ndaily_cases = ind_covid_df['Daily Confirmed']\nplt.figure(figsize=(10,6))\nplt.plot(dates, daily_cases,'-', linewidth=2)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count')\nplt.suptitle('Daily New Cases by time',fontsize=22)\n\nplt.annotate(text=str(today_cases), xy=(curr_date, today_cases),\n             xycoords='data', xytext=(-56,1), textcoords='offset points', fontsize=14)\n\n\n\"\"\"\nFrom July 2020 Onwards infection rate started to increase and reached its first peak at September 2020 with over 90,000 cases reported per-day.\\\nCases began to decline from October 2020 and were reported below 15,000 in January 2021 which was a good sign.\n\nA second wave beginning in March 2021 was much larger than first, with shortages of vaccines, hospital beds, oxygen cylinders and other medicines such as remdesivir in parts of the country. By April end daily infection count reached over 400,000 which was new record\n\"\"\"\ntotal_deaths = ind_covid_df['Total Deceased']\nplt.figure(figsize=(10,6))\nplt.plot(dates, total_deaths, color='red')\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count')\nplt.suptitle('Total Deaths by Time', fontsize=22)\n\nplt.annotate(text=str(curr_total_deaths), xy=(curr_date, curr_total_deaths),\n             xycoords='data', xytext=(-56,1), textcoords='offset points', fontsize=14)\ndaily_deaths = ind_covid_df['Daily Deceased']\nplt.figure(figsize=(10,6))\nplt.plot(dates, daily_deaths,'-r', linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count')\nplt.suptitle('Daily New Deaths by time',fontsize=22)\n\nplt.annotate(text=str(today_deaths), xy=(curr_date, today_deaths),\n             xycoords='data', xytext=(-40,1), textcoords='offset points', fontsize=14)\n\"\"\"\nAbove plot depicts that their were large no. of deaths in August, September and October months of year 2020.\nSudden spike of deaths was seen in mid-June month. \nIn Second wave the deaths are 4 to 5 times more than the previous wave\n\"\"\"\n\"\"\"\n### Let us see if their is any correlation between new cases and new deaths on daily basis\n\"\"\"\nplt.figure(figsize=(8,5))\nplt.scatter(daily_cases, daily_deaths, edgecolor='black', alpha=.3)\nplt.xlabel('New Cases')\nplt.ylabel('New Deaths')\n\"\"\"\nThe Scatterplot shows that Daily New deaths are linearly correlated with new cases on daily basis.\nTheir is positive, strong relation between the two, as more points overlapp to form a line \n\ni.e. Deaths occuring each day depends on the fresh Covid cases on that day. More the no. of cases are found more deaths will occur.\n\nFrom above plots we can conclude, that if we could stop or supress the fresh Covid cases, then their would be less deaths.\n\"\"\"\n\"\"\"\n`if we could prevent new cases from happening, deaths would reduce`\n\"\"\"\ntotal_recovered = ind_covid_df['Total Recovered']\nplt.figure(figsize=(10,6))\nplt.plot(dates, total_recovered\/10**6, color='green')\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count (in Million)')\nplt.suptitle('Total Recovery by Time', fontsize=22)\n\nplt.annotate(text=str(curr_total_recovered), xy=(curr_date, curr_total_recovered\/10**6),\n             xycoords='data', xytext=(-70,1), textcoords='offset points', fontsize=14)\n\n\ndaily_recovered = ind_covid_df['Daily Recovered']\nplt.figure(figsize=(10,6))\nplt.plot(dates, daily_recovered,'-g', linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count')\nplt.suptitle('Daily Recovered by time',fontsize=22)\n\nplt.annotate(text=str(today_recovered), xy=(curr_date, today_recovered),\n             xycoords='data', xytext=(-60,1), textcoords='offset points', fontsize=14)\nactive_cases = total_cases-total_deaths-total_recovered\ncurr_active_cases = curr_total_cases - curr_total_deaths - curr_total_recovered\nplt.figure(figsize=(10,6))\nplt.plot(dates, active_cases\/10**6, color='#483096', linewidth=2)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Count (in Millions)')\nplt.suptitle('Active Cases over Time',fontsize=22)\n\nplt.annotate(text=str(curr_active_cases), xy=(curr_date, curr_active_cases\/10**6),\n             xycoords='data', xytext=(-66,1), textcoords='offset points', fontsize=14)\n\"\"\"\n## Summary\n\"\"\"\n\"\"\"\n### 1. Case Fatality Ratio (CFR)\n\"\"\"\n\"\"\"\nCase fatality ratio(CFR) is ratio to measure risk of death when person is infected with a disease. The actual probability of death of person diagonsed with a disease is generally less since everybody is not tested to have a disease or not. Hence their would be a scenario where their are people who have the disease but are not diagonsed.\nCFR can increase or decrease, or could vary by location and characteristics of the infected person.\n\nCFR gives rough chances of death if person is infected with COVID-19\n\"\"\"\n\"\"\"\n$$CFR=\\frac{Number\\ of\\ deaths\\ from\\ disease}{Number\\ of\\ diagonsed\\ case\\ of\\ disease}X\\ 100$$\n\"\"\"\ninf_fatality_ratio = (total_deaths\/total_cases)*100\ncurr_fat_ratio = (curr_total_deaths\/curr_total_cases)*100\nplt.figure(figsize=(10,6))\nplt.plot(dates, inf_fatality_ratio,'-m', linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Percent')\nplt.suptitle('Infection Fatality Ratio over Time',fontsize=22)\n# plt.title('(Chances of Death)')\n\nplt.annotate(text=str(round(curr_fat_ratio, 3)), xy=(curr_date, curr_fat_ratio),\n             xycoords='data', xytext=(-48,-10), textcoords='offset points', fontsize=14)\n\"\"\"\n### 2. Rate of Recovery\n\"\"\"\n\"\"\"\n$$Recovery\\ Rate = \\frac{Number\\ of\\ recovries\\ from\\ disease}{Number\\ of\\ diagonsed\\ case\\ of\\ disease}X\\ 100$$\n\"\"\"\n\"\"\"\nDuring the rise of second wave, recovery rate started falling from March 2021 and settled at 80% after which has started to grow again\n\"\"\"\nrecovery_rate = (total_recovered\/total_cases)*100\ncurr_rec_ratio = (curr_total_recovered\/curr_total_cases)*100\nplt.figure(figsize=(10,6))\nplt.plot(dates, recovery_rate, color='#3b7d24', linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Percent')\nplt.suptitle('Recovery rate over Time',fontsize=22)\n\nplt.annotate(text=str(round(curr_rec_ratio, 2)), xy=(curr_date, curr_rec_ratio),\n             xycoords='data', xytext=(-50,-5), textcoords='offset points', fontsize=14)\nper_act_cases = (active_cases\/total_cases)*100\ncurr_per_act_cases = (curr_active_cases\/curr_total_cases)*100\nplt.figure(figsize=(10,6))\nplt.plot(dates, per_act_cases, color='#8c2730', linewidth=1)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\nplt.ylabel('Percent')\nplt.suptitle('Percent of Active Cases over Time',fontsize=22)\n\nplt.annotate(text=str(round(curr_per_act_cases, 2)), xy=(curr_date, curr_per_act_cases),\n             xycoords='data', xytext=(-40,1), textcoords='offset points', fontsize=14)\nfig, ax = plt.subplots()\nfig.set_figheight(8)\nfig.set_figwidth(10)\n\nlabels = ['Deaths','Recovered','Active']\nax.stackplot(dates, total_deaths\/10**6,total_recovered\/10**6,active_cases\/10**6, alpha=.8, labels=labels)\nax.set_ylabel('Count (in Million)')\nax.legend(loc='upper left')\n\nfig.autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\n\nax.xaxis.set_major_locator(plt.MaxNLocator(18))\nax.xaxis.set_major_formatter(date_format)\n\nplt.annotate(text=str(curr_total_deaths), xy=(curr_date, curr_total_deaths\/10**6),\n             xycoords='data', xytext=(-55,5), textcoords='offset points', fontsize=14)\n\nplt.annotate(text=str(curr_total_recovered), xy=(curr_date, curr_total_recovered\/10**6),\n             xycoords='data', xytext=(-70,1), textcoords='offset points', fontsize=14)\n\nplt.annotate(text=str(curr_active_cases), xy=(curr_date, curr_active_cases\/10**6 + curr_total_recovered\/10**6),\n             xycoords='data', xytext=(-60,-10), textcoords='offset points', fontsize=14)\ntotal_deaths.max()\nfig, ax = plt.subplots(figsize=(10,6))\n\nlabels = ['Deceased', 'Active', 'Recovered', 'Confirmed']\nvalues = [total_deaths.max(), active_cases.max(), total_recovered.max(), total_cases.max()]\n\nax.bar(labels, values, color=['#a83232','#3267a8','#67a832','#5d32a8'])\nax.set_ylabel('Count')\n\n# create a list to collect the plt.patches data\ntotals = []\n\n# find the values and append to list\nfor i in ax.patches:\n    totals.append(i.get_height())\n\n# set individual bar lables using above list\nfor i in ax.patches:\n    # get_x pulls left or right; get_height pushes up or down\n    ax.text(i.get_x()+.18, i.get_height()+500000, \\\n            str(round(i.get_height())), fontsize=15,\n                color='dimgrey')\n\n\n\"\"\"\n\n## **2. Vaccination**\n\"\"\"\n\"\"\"\nIndia began its **vaccination program** on **16 January 2021**. India has approved two vaccines for emergency use, including Oxford-AstraZeneca vaccine also known as **Covisheld** manufactured by the Serum Institue of India, and **Covaxin** developed by Biotech. In April 2021 ,Sputnik V was approved as a third vaccine.\n\nIndia first started with vaccinating Health care workers being first to receive the vaccine. On **April 1 2021** vaccination of people above **age 45** was started. Followed by vaccination of age **group 18-44** from **1 May** onwards.\n\"\"\"\nvac_df = pd.read_csv('..\/input\/indias-vaccine-progress\/cowin_vaccine_data_statewise.csv')\npd.set_option('display.max_rows', 10)\nfilt = vac_df.State=='India'\nind_vac_df = vac_df.loc[filt].copy()\nind_vac_df\ntotal_population = 1380004385\nind_vac_df.columns\nind_vac_df.drop(['State','Total Sessions Conducted','Total Sites ','Male(Individuals Vaccinated)','Female(Individuals Vaccinated)','Transgender(Individuals Vaccinated)','AEFI'], axis=1, inplace=True)\nind_vac_df\nind_vac_df['Total Doses Administered']=ind_vac_df['First Dose Administered']+ind_vac_df['Second Dose Administered']\nind_vac_df.info()\nind_vac_df.rename(columns={'Updated On':'Date'}, inplace=True)\nind_vac_df.dropna(thresh=5,inplace=True)\nind_vac_df.loc[:,['First Dose Administered','Second Dose Administered',\n                  'Total Covaxin Administered','Total CoviShield Administered',\n                  'Total Individuals Vaccinated',\n                  'Total Doses Administered']]=ind_vac_df.loc[:,['First Dose Administered',\n                                                                 'Second Dose Administered',\n                                                                 'Total Covaxin Administered','Total CoviShield Administered','Total Individuals Vaccinated','Total Doses Administered']].astype('int64')\nind_vac_df['Date'] = pd.to_datetime(ind_vac_df['Date'],format='%d\/%m\/%Y')\nind_vac_df\n\"\"\"\n###  Percentage share of population vaccinated\n\"\"\"\n\"\"\"\nAfter the first quarter of the vaccination drive, India has vaccinated **10.13%** of its total population which is about **139 Million** Individuals vaccinated out of which **2.9%** are fully vaccinated. At the end of the quarter one, average Individuals immunized are **0.93 Million**.\n\"\"\"\nind_vac_df.set_index('Date',inplace=True)\nind_vac_df['Percentage Population Vaccinated'] = (ind_vac_df['Total Individuals Vaccinated']\/total_population)*100\nind_vac_df['Percentage Population Completely Vaccinated'] = (ind_vac_df['Second Dose Administered']\/total_population)*100\nind_vac_df\ncurr_date = ind_vac_df.index.max()\ncurr_fst_dose = ind_vac_df.loc[curr_date, 'First Dose Administered']\ncurr_snd_dose = ind_vac_df.loc[curr_date, 'Second Dose Administered']\nper_pop_vac = ind_vac_df['Percentage Population Vaccinated'].max()\nper_pop_com_vac = ind_vac_df['Percentage Population Completely Vaccinated'].max()\nfig, (ax1, ax2) = plt.subplots(1,2)\nfig.set_figheight(4)\nfig.set_figwidth(10)\n\nslices = [per_pop_vac, 100-per_pop_vac]\ncolors = ['#00aaff', '#f0b73c']\nlabels = ['Vaccinated','Unvaccinated']\nax1.pie(slices, labels=labels,colors=colors, wedgeprops={'edgecolor':'black'}, shadow=True, explode=(0.2,0),  autopct='%.2f%%')\n\nslices = [per_pop_com_vac, per_pop_vac-per_pop_com_vac, 100-per_pop_vac]\nlabels = ['Both dose','Only One dose','Unvaccinated']\nax2.pie(slices, labels=labels,startangle=30,\n        wedgeprops={'edgecolor':'black'}, shadow=True, explode=(0.2,0.2,0),  autopct='%.2f%%')\n\n\nplt.show()\n\"\"\"\n### Cumulative doses administered across the country\n\"\"\"\nfig, (ax,ax2) = plt.subplots(2,1)\nfig.set_figheight(14)\nfig.set_figwidth(10)\n\nax1 = ax.twiny()\nax.stackplot(ind_vac_df.index, ind_vac_df['Percentage Population Completely Vaccinated'],\n             ind_vac_df['Percentage Population Vaccinated']-ind_vac_df['Percentage Population Completely Vaccinated'],\n             labels=['Two dose','One dose'],colors=['#31a354','#addd8e'], alpha=.6)\nax.set_ylabel('Percent (%) of Population')\nax.legend(loc='upper left')\n\nax.set_xticks(ind_vac_df.index)\nax.xaxis.set_major_locator(plt.MaxNLocator(18))\nfor tick in ax.get_xticklabels():\n    tick.set_rotation(90)\n    \n\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nax.xaxis.set_major_formatter(date_format)\n\nax1.plot(ind_vac_df.index, ind_vac_df['Percentage Population Vaccinated'],\n         label='Total Percent of Population Vaccinated', color='#007580')\nax1.xaxis.set_visible(False)\nax1.yaxis.set_visible(False)\nax1.legend(loc='center left')\n\nax1.set_title('Vaccination over Time', fontsize=23)\n\n\nax2.plot(ind_vac_df.index, ind_vac_df['First Dose Administered']\/10**6, color='#28abb9', label='First dose')\nax2.plot(ind_vac_df.index, ind_vac_df['Second Dose Administered']\/10**6, color='#2d6187', label='Second dose')\nax2.plot(ind_vac_df.index, ind_vac_df['First Dose Administered']\/10**6+ind_vac_df['Second Dose Administered']\/10**6, color='#ab4b9c', label='Total doses')\nax2.legend()\nax2.set_ylabel('Count (in Millions)')\nax2.set_xticks(ind_vac_df.index)\nax2.xaxis.set_major_locator(plt.MaxNLocator(18))\nfor tick in ax2.get_xticklabels():\n    tick.set_rotation(90)\nax2.xaxis.set_major_formatter(date_format)\nax2.annotate(text=str(curr_fst_dose), xy=(curr_date,curr_fst_dose\/10**6), xycoords='data',\n            xytext=(-98, -20),\n            textcoords='offset points')\nax2.annotate(text=str(curr_snd_dose), xy=(curr_date,curr_snd_dose\/10**6), xycoords='data',\n            xytext=(-80, 0),\n            textcoords='offset points')\n\nplt.annotate(text=str(round(per_pop_com_vac,2)), xy=(curr_date, per_pop_com_vac),\n             xycoords='data', xytext=(-38,-35), textcoords='offset points', fontsize=14)\n\nplt.annotate(text=str(round(per_pop_vac-per_pop_com_vac, 2)), xy=(curr_date, per_pop_vac-per_pop_com_vac),\n             xycoords='data', xytext=(-35,-85), textcoords='offset points', fontsize=14)\n\nplt.annotate(text=str(round(per_pop_vac, 2)), xy=(curr_date, per_pop_vac),\n             xycoords='data', xytext=(-35,0), textcoords='offset points', fontsize=14)\n\"\"\"\n### Individuals immunized on daily basis\n\"\"\"\nhelp(ax.annotate)\nind_vac_df\ndaily_vac = []\n\nprev_vac=0;\ncurr_vac=0;\n\nfor i in range(ind_vac_df.shape[0]):\n    curr_vac=ind_vac_df['Total Individuals Vaccinated'][i]\n    daily_vac.append(curr_vac - prev_vac)\n    prev_vac=curr_vac\n    \nind_vac_df['Daily Individuals Vaccinated'] = daily_vac\nind_vac_df\ndaily_vac = ind_vac_df['Daily Individuals Vaccinated']\ndaily_vac\ntodays_vac = daily_vac.get(curr_date)\navg_daily_vac = daily_vac.median()\navg_daily_vac\nplt.figure(figsize=(10,6))\nplt.bar(daily_vac.index, daily_vac.values\/10**6,color='#de9d23', alpha=.6)\nplt.plot(daily_vac\/10**6, color='#6a2c70', linewidth=2)\nplt.axhline(y=avg_daily_vac\/10**6, linewidth=1, alpha=.9)\n\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b, %Y')\nplt.gca().xaxis.set_major_formatter(date_format)\n\n# plt.gca().xaxis.set_major_locator(plt.MaxNLocator(len(daily_vac)\/15))\n\nplt.ylabel('Count (in Millions)')\nplt.suptitle('Daily Individuals Vaccinated over time', fontsize=22)\n\nplt.annotate(text=str(todays_vac), xy=(curr_date, todays_vac\/10**6),\n             xycoords='data', xytext=(-5,10), textcoords='offset points', fontsize=14)\n\n","meta":"{'source': 'AI4Code', 'id': '947dcda252952e'}"}
{"id":"131807","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\nBu datasetlerde Ulkelerin 2015, 2016, 2017, 2018 ve 2019 yillarina ait \" Mutluluk skoru, ekonomik durumu, hukumetlerin yolsuzluk durumu, saglik durumu, comertlik durumu, aile, ozgurluk gibi cesitli degiskenler hakkinda bilgiler bulacaksiniz. Bu degiskenlerden yola cikarak asagidaki islemleri yapiniz.\n* Bu 5 dataseti ulkeleri baz alarak \" Country, Region, (happiness.score = score), Health, Freedom, Corruption, Generosity\" sutunlari olacak sekilde tekbir df'te birlestiriniz. Diger degiskenleri atabilirsiniz.  (Not: Birlestirme islemleri yaparken, gerekirse ek sutunlar olusturabilirsiniz.)\n* Bazi data setlerde ulkelerin region bilgileri yok, bu ulkeleri arastirarak, region sutununda eksik yerlere ekleyiniz.\n* NaN degerleri saydiriniz.\n* NaN degerleri o degiskenin ortalamasi ile doldurunuz.\n* Data uzerinde info ve describe bilgilerini aliniz.\n* Kac cesit bolge var hesaplayiniz.\n* Mutlulugu en fazla etkileyen degisken hangisidir. Yillara gore farklilik olup olmadigina bakiniz.\n* Hangi bolgede(Region) kac ulke var bulunuz.\n* 5 yilin MUTLULUK ortalamasini alarak en mutlu ve en mutsuz 3 ulkeyi bulunuz.\n* 5 yilin YOLSUZLUK ortalamasini alarak en iyi ve en kotu ulkeleri bulunuz.\n* 5 yila bakarak, ozgurluk ortalamasi en yuksek ve en dusuk BOLGEYI\/REGION bulunuz.\n* En sagliksiz bolge hangisidir bulunuz.\n* Ulkeleri bolgelerine gore gruplayarak, Mutluluk, Ozgurluk ve Yolsuzluk degiskenlerinin ortalamalini aliniz.\n\n\" Country, Region, (happiness.score = score), Health, Freedom, Corruption, Generosity\"\n\"\"\"\nwh_2015 = pd.read_csv(\"\/kaggle\/input\/world-happiness\/2015.csv\")\nwh_2016 = pd.read_csv(\"\/kaggle\/input\/world-happiness\/2016.csv\")\nwh_2017 = pd.read_csv(\"\/kaggle\/input\/world-happiness\/2017.csv\")\nwh_2018 = pd.read_csv(\"\/kaggle\/input\/world-happiness\/2018.csv\")\nwh_2019 = pd.read_csv(\"\/kaggle\/input\/world-happiness\/2019.csv\")\nwh_2015.columns\n\n\"\"\"\n**Firs we are trying to make all the columns and tables equal(by:name, index etc)**\n\"\"\"\nwh_2015.drop([\"Standard Error\",\"Economy (GDP per Capita)\",\"Family\",'Dystopia Residual'],axis = 1,inplace = True)\n\nwh_2015.columns\nwh_2016.drop([\"Economy (GDP per Capita)\",\"Lower Confidence Interval\",\"Family\",'Upper Confidence Interval','Dystopia Residual'],axis = 1,inplace = True)\nwh_2016.columns\nwh_2015.head(10)\nco_reg = pd.DataFrame([wh_2015['Country'],wh_2015['Region']])\ncountry_region = co_reg.T\n\nwh_2015.drop(['Happiness Rank','Region'],axis = 1,inplace = True)\nwh_2016.drop(['Happiness Rank','Region'],axis = 1,inplace = True)\nwh_2016.columns\nwh_2015.columns\n\nwh_1 = wh_2015.rename(columns = {'Country':'Country', 'Happiness Score':'2015_Happiness Score', 'Health (Life Expectancy)':'2015_Health (Life Expectancy)',\n       'Freedom':'2015_Freedom', 'Trust (Government Corruption)':'2015_Trust (Government Corruption)', 'Generosity':'2015_Generosity'})\nwh_2 = wh_2016.rename(columns = {'Country':'Country','Happiness Score':'2016_Happiness Score', 'Health (Life Expectancy)':'2016_Health (Life Expectancy)',\n       'Freedom':'2016_Freedom', 'Trust (Government Corruption)':'2016_Trust (Government Corruption)', 'Generosity':'2016_Generosity'})\nwh_2.head()\nwh_1.head()\nwh_2017.drop(['Happiness.Rank',\"Whisker.high\",\"Whisker.low\",\"Economy..GDP.per.Capita.\",\"Family\",\"Dystopia.Residual\"],axis =1,inplace = True)\nwh_2017.columns = ['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom', 'Trust (Government Corruption)','Generosity']\nwh_2017.head()\n# new_wh_2017 = wh_2017[['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom','Generosity','Trust (Government Corruption)']]\n\nwh_3 = wh_2017.rename(columns = {'Country':'Country', 'Happiness Score':'2017_Happiness Score', 'Health (Life Expectancy)':'2017_Health (Life Expectancy)',\n       'Freedom':'2017_Freedom', 'Trust (Government Corruption)':'2017_Trust (Government Corruption)', 'Generosity':'2017_Generosity'})\nwh_3.head()\nwh_2018.drop(['Overall rank',\"GDP per capita\",'Social support'],axis = 1,inplace=True)\n\nwh_2018.columns = ['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom','Generosity','Trust (Government Corruption)']\nwh_2018 = wh_2018[['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom','Trust (Government Corruption)','Generosity']]\nwh_4 = wh_2018.rename(columns = {'Country':'Country', 'Happiness Score':'2018_Happiness Score', 'Health (Life Expectancy)':'2018_Health (Life Expectancy)',\n       'Freedom':'2018_Freedom', 'Trust (Government Corruption)':'2018_Trust (Government Corruption)', 'Generosity':'2018_Generosity'})\nwh_2019.drop(['Overall rank','GDP per capita','Social support'],axis = 1, inplace = True)\nwh_2019.columns = ['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom','Generosity','Trust (Government Corruption)']\nwh_2019 = wh_2019[['Country','Happiness Score', 'Health (Life Expectancy)', 'Freedom','Trust (Government Corruption)','Generosity']]\nwh_5 = wh_2019.rename(columns = {'Country':'Country','Happiness Score':'2019_Happiness Score', 'Health (Life Expectancy)':'2019_Health (Life Expectancy)',\n       'Freedom':'2019_Freedom', 'Trust (Government Corruption)':'2019_Trust (Government Corruption)', 'Generosity':'2019_Generosity'})\n\nwh_1.info()\nwh_2.info()\nwh_3.info()\nwh_4.info()\nwh_5.info()\n\"\"\"\n**Now we are ready to merge all 5 tables and our ragion table in one table**\n\"\"\"\nall = wh_1.merge(wh_2,on='Country',how = \"left\")\nall = all.merge(wh_3,on='Country',how = \"left\")\nall = all.merge(wh_4,on='Country',how = \"left\")\nall = all.merge(wh_5,on='Country',how = \"left\")\nall = all.merge(country_region,on='Country',how = \"left\")\n\n\nall = all[['Country','Region', '2015_Happiness Score','2016_Happiness Score','2017_Happiness Score','2018_Happiness Score','2019_Happiness Score',\n           '2015_Health (Life Expectancy)','2016_Health (Life Expectancy)', '2017_Health (Life Expectancy)','2018_Health (Life Expectancy)','2019_Health (Life Expectancy)', \n       '2015_Freedom','2016_Freedom','2017_Freedom','2018_Freedom','2019_Freedom',\n           '2015_Trust (Government Corruption)','2016_Trust (Government Corruption)', '2017_Trust (Government Corruption)','2018_Trust (Government Corruption)','2019_Trust (Government Corruption)',\n           '2015_Generosity','2016_Generosity','2017_Generosity','2018_Generosity','2019_Generosity']]\n\nall.head()\n\"\"\"\n* NaN degerleri saydiriniz.\n* NaN degerleri o degiskenin ortalamasi ile doldurunuz.\n* Data uzerinde info ve describe bilgilerini aliniz.\n* Kac cesit bolge var hesaplayiniz.\n* Mutlulugu en fazla etkileyen degisken hangisidir. Yillara gore farklilik olup olmadigina bakiniz.\n* Hangi bolgede(Region) kac ulke var bulunuz.\n* 5 yilin MUTLULUK ortalamasini alarak en mutlu ve en mutsuz 3 ulkeyi bulunuz.\n* 5 yilin YOLSUZLUK ortalamasini alarak en iyi ve en kotu ulkeleri bulunuz.\n* 5 yila bakarak, ozgurluk ortalamasi en yuksek ve en dusuk BOLGEYI\/REGION bulunuz.\n* En sagliksiz bolge hangisidir bulunuz.\n* Ulkeleri bolgelerine gore gruplayarak, Mutluluk, Ozgurluk ve Yolsuzluk degiskenlerinin ortalamalini aliniz.\n\"\"\"\n\"\"\"\nFinding the NaN values:\n\"\"\"\nall.isna().sum()\n\"\"\"\nFilling the NaN values the mean of the same column.\n\"\"\"\nfor i in all.columns[2:]:\n    all[i].fillna(all[i].mean(),inplace = True)        \nall.isna().sum()  \nall.info\nall.T\n\"\"\"\nFinding the number of regions.\n\"\"\"\nlen(all.Region.groupby(all['Region']).count())\n\"\"\"\nThe value that (effects)most realted with the happiness is: Health(life expectancy)\n\"\"\"\nall.corr()\n\"\"\"\nThat's obvious in the correlation table: happiness is more than 75 percent in relation with Health(life expectancy), 50 percent Freedom, around 40 percent Trust and 15 percent with generosity. \n\"\"\"\n\"\"\"\nHangi bolgede(Region) kac ulke var bulunuz.{find the number of Country in each region?}\n\"\"\"\nall.groupby('Region')['Country'].nunique()\n\"\"\"\n5 yilin MUTLULUK ortalamasini alarak en mutlu ve en mutsuz 3 ulkeyi bulunuz.\n{finding the five year avarage of the happines score and happiest 3 country and worst happiest 3 country.}\n\n\"\"\"\nall[\"5year_Happines\"] = (all['2015_Happiness Score']+all['2016_Happiness Score']+all['2017_Happiness Score']+\n                         all['2018_Happiness Score']+all['2019_Happiness Score'])\/5\n# print(all[\"5year_Happines\"])\n\nhappiest = all.sort_values(by = \"5year_Happines\",ascending = False)\nhappiest.head(3)\nhappiest.tail(3)\n\"\"\"\n* 5 yilin YOLSUZLUK ortalamasini alarak en iyi ve en kotu ulkeleri bulunuz.\n{finding the five year avarage of the corruption and most corrupted country and least corrupted country.}\n\"\"\"\nall[\"5year_Corruption\"] = (all['2015_Trust (Government Corruption)']+all['2016_Trust (Government Corruption)']+all['2017_Trust (Government Corruption)']+\n                         all['2018_Trust (Government Corruption)']+all['2019_Trust (Government Corruption)'])\/5\ncorruption = all.sort_values(by = '5year_Corruption',ascending = False)\ncorruption.head(1) #Singapore\ncorruption.tail(1) #Lithuania\n\"\"\"\n* 5 yila bakarak, ozgurluk ortalamasi en yuksek ve en dusuk BOLGEYI\/REGION bulunuz.\n{Find the regions which has the best and lowest freedom avarage?}\n\n\"\"\"\nall['Mean_Freedom'] = (all['2015_Freedom']+ all['2016_Freedom']+all ['2017_Freedom']+all['2018_Freedom']+all['2019_Freedom'])\/5\nfreedom_region = all.groupby(\"Region\")['Mean_Freedom'].mean()\nfreedom_region\nfor i in (freedom_region):\n    if i == freedom_region.min():\n        print(freedom_region[freedom_region == i])\n    elif i == freedom_region.max():\n        print(freedom_region[freedom_region == i])\n\"\"\"\n* En sagliksiz bolge hangisidir bulunuz.\n{The least healthy region} \n\n\"\"\"\nall['Health'] = (all['2015_Health (Life Expectancy)']+ all['2016_Health (Life Expectancy)']+all ['2017_Health (Life Expectancy)']+all['2018_Health (Life Expectancy)']+all['2019_Health (Life Expectancy)'])\/5\nhealth_region = all.groupby(\"Region\")['Health'].mean()\nfor i in (health_region):\n    if i == health_region.min():\n        print(health_region[health_region == i])\n\"\"\"\n* Ulkeleri bolgelerine gore gruplayarak, Mutluluk, Ozgurluk ve Yolsuzluk degiskenlerinin ortalamalini aliniz.\n{Group the countries by Regions and find Happiness, Freedom and Corruption avarage of them.}\n\"\"\"\nall.head(1)\nall.groupby('Region')[\"5year_Happines\"].mean()\nall.groupby('Region')[\"Mean_Freedom\"].mean()\nall.groupby('Region')[\"5year_Corruption\"].mean()\nall.groupby('Region')[\"Health\"].mean()","meta":"{'source': 'AI4Code', 'id': 'f2788aaa4799a1'}"}
{"id":"124143","text":"\"\"\"\n# An\u00e1lisis de sentimientos - Clasificaci\u00f3n de cr\u00edticas de pel\u00edculas filmaffinity\n\n* Notebook introductorio sobre clasificaci\u00f3n de textos, aplicando algoritmos de aprendizaje sencillos.\n\n\n* Este notebook tiene como objetivo mostrar todo el proceso de clasificaci\u00f3n de textos (an\u00e1lisis de sentimientos) sobre cr\u00edticas de pel\u00edculas.\n\n\n* El proceso realizado es el siguiente:\n\n1. Carga de datos\n2. Definici\u00f3n del target en funci\u00f3n de la nota de la cr\u00edtica {Negativo, Neutro, Positivo}\n3. Normalizaci\u00f3n de textos\n4. Particionado de datos en entrenamiento y test\n5. Creacci\u00f3n del modelos de bolsa de palabras y su apliaci\u00f3n a los textos\n6. Creacci\u00f3n de modelos de clasificaci\u00f3n con algoritmos de aprendizaje sencillos de clasificaci\u00f3n\n7. Evaluaci\u00f3n de los modelos\n\n\"\"\"\n\"\"\"\n## 1.- Carga de datos\n\"\"\"\nimport pandas as pd\n\ndf = pd.read_table('..\/input\/criticas-peliculas-filmaffinity-en-espaniol\/reviews_filmaffinity.csv', sep='\\|\\|', header=0, engine='python')\ndf.sample(5)\n\"\"\"\n## 2.- Distribuci\u00f3n de votos (Positivo {>6} - Neutro {4-6} - Negativo {4>})\n\n1.- Creamos una nueva columna con la polaridad del voto: Positivo \\[10, 6), Neutro [6, 4], Negativo (4, 0\\].\n\n2.- Distribuci\u00f3n num\u00e9rica de los votos de las cr\u00edticas.\n\n3.- Distribuci\u00f3n categ\u00f3rica de la polaridad de los votos.\n\n4.- Distribuci\u00f3n de los votos por pel\u00edcula.\n\"\"\"\n# 1.- Nueva columna con la polaridad de los votos\ndf['polaridad'] = df['review_rate'].apply(lambda  x: 'positivo' if x > 6\n                                          else ('negativo' if x < 4\n                                                else 'neutro'))\ndf.sample(5)\n# 2.-  Distribuci\u00f3n num\u00e9rica de los votos de las cr\u00edticas.\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nsns.catplot(x='review_rate', kind='count', color='b', data=df)\nplt.title('Distribuci\u00f3n Votos')\nplt.xlabel('Notas')\nplt.ylabel('N\u00ba Votos')\n# 3.-  Distribuci\u00f3n de votos por polaridad\n\nsns.catplot(x='polaridad', kind='count', data=df,  order=['negativo', 'neutro', 'positivo'])\nplt.title('Distribuci\u00f3n Polaridad')\nplt.xlabel('Polaridad')\nplt.ylabel('N\u00ba Votos')\n# 4.- Distribuci\u00f3n de los votos por pel\u00edcula.\n\nsns.catplot(x=\"review_rate\", col=\"film_name\", data=df, kind='count', col_wrap=3)\n\"\"\"\n## 3.- Normalizaci\u00f3n de textos \n\n* Vamos a definir como texto a clasificar t\u00edtulo y la cr\u00edtica, ya que el t\u00edtulo aporta significado al texto.\n\n\n* En este punto realizaremos los siguientes pasos:\n\n1. Concatenaci\u00f3n de t\u00edtulo y cr\u00edtica\n1. Pasamos a array de numpy el texto y el target (polaridad)\n1. Importamos el modelo de spacy en espa\u00f1ol\n1. Normalizaci\u00f3n de los textos: La normalizaci\u00f3n es una tarea que tiene como objetivo poner todo el texto en igualdad de condiciones; como por ejemplo:\n        \n    * Pasar todo el texto a min\u00fasculas (o may\u00fasculas)\n    * Eliminar signos de puntuaci\u00f3n (puntos, comas, comillas, etc)\n    * Quitar las stop-words: pal\u00e1bras que no aportan significado a los textos\n    * Convertir n\u00fameros a su equivalente a palabras\n    * Transformar la palabra a su lema\n    * Pasar emoticonos a textos\n    * etc.\n\"\"\"\n# 1.- Concatenaci\u00f3n de t\u00edtulo y cr\u00edtica\n\ndf['texto'] = df['review_title'] + ' ' + df['review_text']\ndf.head(5)\n# 2.- Pasamos a array de numpy el texto (X) y el target-polaridad (y)\n\nX = df['texto'].values\ny =  df['polaridad'].values\n\n# 3.- Importamos el modelo de spacy en espa\u00f1ol\n\nimport spacy\n\n# Este comando se ejecuta en consola\n!python -m spacy download es\n\"\"\"\n**NOTA:** *Si ejecutais este notebook en local, es posible que os de un error a la hora de importar el modelo de NLP en espa\u00f1ol. Si da ese error deb\u00e9is de cambiar el nombre del modelo de 'es' a 'es_core_news_sm' o como se indique en el proceso de importaci\u00f3n del modelo de Spacy.*\n\"\"\"\nimport re\n\nfrom tqdm import tqdm\n\n# Importamos el modelo en espa\u00f1ol de spacy\nnlp = spacy.load('es')\n\n\ndef normalize(corpus):\n    \"\"\"Funci\u00f3n que dada una lista de textos, devuelve esa misma lista de textos\n       con los textos normalizados, realizando las siguientes tareas:\n       1.- Pasamos la palabra a min\u00fasculas\n       2.- Elimina signos de puntuaci\u00f3n\n       3.- Elimina las palabras con menos de 3 caracteres (palabras que seguramente no aporten significado)\n       4.- Elimina las palabras con m\u00e1s de 11 caracteres (palabras \"raras\" que seguramente no aporten significado)\n       5.- Elimina las stop words (palabras que no aportan significado como preposiciones, determinantes, etc.)\n       6.- Elimina los saltos de l\u00ednea (en caso de haberlos)\n       7.- Eliminamos todas las palabras que no sean Nombres, adjetivos, verbos o advervios\n    \"\"\"\n    for index, doc in enumerate(tqdm(corpus)):\n        doc = nlp(doc.lower())\n        corpus[index] = \" \".join([word.lemma_ for word in doc if (not word.is_punct)\n                                  and (len(word.text) > 3) \n                                  and (len(word.text) < 11) \n                                  and (not word.is_stop)\n                                  and re.sub('\\s+', ' ', word.text)\n                                  and (word.pos_ in ['NOUN', 'ADJ', 'VERB', 'ADV'])])\n        \n        \n    return corpus\n\n# Normalizaci\u00f3n\nX_norm = normalize(X)\n\"\"\"\n## 4.- Bolsa de Palabras (BoW) - Particionado de datos\n\"\"\"\n# 1.- Particionamos los textos en entrenamiento y test (80% entrenamiento, 20% test)\n\nfrom sklearn.model_selection import train_test_split  \n\nX_train, X_test, y_train, y_test = train_test_split(X_norm, y, test_size=0.2, random_state=0)\n\nprint('Textos de entrenamiento: {}'.format(len(X_train)))\nprint('Textos de test: {}'.format(len(X_test)))\n\"\"\"\n* Mostramos la distribuci\u00f3n del target de los datos de entrenamiento y test para ver si siguen una distribuci\u00f3n similar.\n\"\"\"\nimport numpy as np\n\nkeys_train, counts_train = np.unique(y_train, return_counts=True)\nkeys_test, counts_test = np.unique(y_test, return_counts=True)\nperct_train = counts_train \/ np.sum(counts_train)\nperct_test = counts_test \/ np.sum(counts_test)\n\nplt.figure(figsize=(15, 15))\nplt.subplot(1, 2, 1)\nplt.pie(perct_train, labels=keys_train, autopct='%1.1f%%')\nplt.title('Distribuci\u00f3n Target Train')\nplt.subplot(1, 2, 2)\nplt.pie(perct_test, labels=keys_test, autopct='%1.1f%%')\nplt.title('Distribuci\u00f3n Target Test')\nplt.plot()\n\n\"\"\"\n### Creamos una bolsa de palabras de frecuencias con los textos de entrenamiento.\n\n* Creamos un modelo de bolsa de palabras con las 2000 palabras m\u00e1s frecuentes de los textos de entrenamiento que aparezcan por lo menos en 3 documentos distintos.\n\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nbow = CountVectorizer(max_features=2000, min_df=3)\n\n# Creamos el modelo de bolsa de palabras con los textos de entrenamiento y aplicamos el modelo\nX_bow_train = bow.fit_transform(X_train)\n\n# A modo de ejemplo mostramos las 20 primeras palabras de la bolsa de palabras\nbow.get_feature_names()[0:21]\n\"\"\"\n* Con el modelo de bolsa de palabras creado con los textos de entrenamiento, aplicamos el modelo a los textos de test.\n\"\"\"\nX_bow_test = bow.transform(X_test)\n\"\"\"\n## 5.- Creacci\u00f3n de modelos (clasificaci\u00f3n)\n\nUtilizamos los siguientes algoritmos (o metaalgoritmos) de aprendizaje de clasificaci\u00f3n para crear modelos predictivos capaces de clasificar una cr\u00edtica de pelicula en alguna de las siguientes clases: {Negativa, Neutra, Positiva}\n\n* Multinomial Naive Bayes\n* Bernoulli Naive Bayes\n* Regresion Logistica\n* Support Vector Machine\n* Random Forest (ensemble)\n\"\"\"\n\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\n\nmnb = MultinomialNB()\nbnb = BernoulliNB()\nlr = LogisticRegression(solver='lbfgs', multi_class='multinomial', max_iter=1000)\nsvm_lin = SVC(kernel='linear')\nsvm_rbf = SVC(kernel='rbf')\nrf_20 = RandomForestClassifier(n_estimators=500, bootstrap=True, criterion='gini', max_depth=20, random_state=0)\nrf_50 = RandomForestClassifier(n_estimators=500, bootstrap=True, criterion='gini', max_depth=50, random_state=0)\n\nclasificadores = {'Multinomial NB': mnb,\n                  'Bernoulli NB': bnb,\n                  'Regresion Logistica': lr,\n                  'SVM lineal': svm_lin,\n                  'SVM Kernel rbf': svm_rbf,\n                  'Random Forest d_20': rf_20,\n                  'Random Forest d_50': rf_50}\n\n\n# Ajustamos los modelos y calculamos el accuracy para los datos de entrenamiento\nfor k, v in clasificadores.items():\n    print ('CREANDO MODELO: {clas}'.format(clas=k))\n    v.fit(X_bow_train, y_train)\n\"\"\"\n## 6.- Evaluaci\u00f3n de los modelos\n\n* Para cada uno de los modelos vamos a calcular las siguientes m\u00e9tricas de evaluaci\u00f3n:\n\n1. Accuracy\n1. Precision\n1. Recall\n1. F1\n\"\"\"\n\nfrom sklearn.metrics import accuracy_score,precision_score, recall_score, f1_score\n\ndef evaluation(model, name, X_train, y_train, X_test, y_test):\n    \"\"\"\n    Funci\u00f3n de devuelve en un diccionario las m\u00e9tricas de evaluaci\u00f3n de \n    Accuracy, Precision, Recall y F1 para los conjuntos de datos de entrenamiento y test\n        model: modelo a evaluar\n        name: nombre del modelo\n        X_train: Variables de entrada del conjunto de datos de entrenamiento\n        y_train: Variable de salida del conjunto de datos de entrenamiento\n        X_test: Variables de entrada del conjunto de datos de test\n        y_test: Variable de salida del conjunto de datos de test\n        return: diccionario con el nombre del modelo y el valor de las m\u00e9tricas\n    \"\"\"\n    model_dict = {}\n    model_dict['name'] = name\n    y_pred_train = model.predict(X_train)\n    y_pred_test = model.predict(X_test)\n    model_dict['accuracy_train'] = accuracy_score(y_true=y_train, y_pred=y_pred_train)\n    model_dict['accuracy_tests'] = accuracy_score(y_true=y_test, y_pred=y_pred_test)\n    model_dict['precision_train'] = precision_score(y_true=y_train, y_pred=y_pred_train, average='weighted')\n    model_dict['precision_tests'] = precision_score(y_true=y_test, y_pred=y_pred_test, average='weighted')\n    model_dict['recall_train'] = recall_score(y_true=y_train, y_pred=y_pred_train, average='weighted')\n    model_dict['recall_tests'] = recall_score(y_true=y_test, y_pred=y_pred_test, average='weighted')\n    model_dict['f1_train'] = f1_score(y_true=y_train, y_pred=y_pred_train, average='weighted')\n    model_dict['f1_tests'] = f1_score(y_true=y_test, y_pred=y_pred_test, average='weighted')\n    \n    return model_dict\n\n\n# Calculamos las m\u00e9tricas de los modelos por separado\nevaluacion = list()\nfor key, model in clasificadores.items():\n    evaluacion.append(evaluation(model=model, name=key, \n                                 X_train=X_bow_train, y_train=y_train,\n                                 X_test=X_bow_test, y_test=y_test))\n\n# Pasamos los resultados a un DataFrame para visualizarlos mejor\ndf = pd.DataFrame.from_dict(evaluacion)\ndf.set_index(\"name\", inplace=True)\ndf\n\"\"\"\n* Representamos las m\u00e9tricas para los diferentes modelos en un gr\u00e1fico de barras:\n\"\"\"\n# M\u00e9tricas a pintar\nMETRICS = [\"accuracy\", \"precision\", \"recall\", \"f1\"]\n\n# Transformamos el dataframe para pintar las gr\u00e1ficas con seaborn\ndf_plot = df.reset_index().melt(id_vars='name').rename(columns=str.title)\n\nplt.figure(figsize=(25, 12))\npos = 1\nfor metric in METRICS:\n    # Filtramos la m\u00e9trica a pintar\n    df_aux = df_plot[df_plot['Variable'].str.contains(metric)]\n    \n    # Pintamos la gr\u00e1fica en su posici\u00f3n 2x2\n    plt.subplot(2, 2, pos)\n    sns.barplot(x='Name', y='Value', hue='Variable', data=df_aux)\n    plt.title(metric.upper())\n    plt.grid()\n    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)\n    plt.xticks(rotation=20)\n    pos += 1\nplt.show()\n\"\"\"\n* Dibujamos las matrices de confusi\u00f3n de cada uno de los modelos creados para los textos de entrenamiento y test\n\"\"\"\nimport itertools\n\nfrom sklearn.metrics import confusion_matrix\n\npolaridad = ['positivo', 'neutro', 'negativo']\n\n# Obtenemos las Matrices de confusi\u00f3n\nmsc = list()\nfor k, v in clasificadores.items():\n    print ('Obteniendo Matriz de Confusi\u00f3n de: {model}'.format(model=k))\n    model = {}\n    model['name'] = k\n    y_pred_train = v.predict(X_bow_train)\n    y_pred_test = v.predict(X_bow_test)\n    model['confusion_matrix_train'] = confusion_matrix(y_true=y_train, y_pred=y_pred_train, labels=polaridad)\n    model['confusion_matrix_test'] = confusion_matrix(y_true=y_test, y_pred=y_pred_test, labels=polaridad)\n    msc.append(model)\n\n    \n# Definimos el heatmap de la matriz de confusi\u00f3n\ndef plot_confusion_matrix(cm, classes, title, cmap=plt.cm.Greens):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    \"\"\"\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], 'd'), horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    \n\n# Pintamos las matrices de confusi\u00f3n\nplt.figure(figsize=(20, 35))\npos = 0\nfor mc in msc:\n    pos += 1\n    plt.subplot(len(msc), 2, pos)\n    plot_confusion_matrix(mc['confusion_matrix_train'], classes=polaridad, \n                          title='{}\\nMatriz de Confusi\u00f3n Textos Entrenamiento'.format(mc['name']))\n    pos += 1\n    plt.subplot(len(msc), 2, pos)\n    plot_confusion_matrix(mc['confusion_matrix_test'], classes=polaridad, \n                          title='{}\\nMatriz de Confusi\u00f3n Textos Tests'.format(mc['name'] ))\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'e44be2f7dc9d51'}"}
{"id":"18859","text":"\"\"\"\nI tried to visualize and analyze data.\n\nAccording to the result; while the team with the most transfer was [Inter](#7), the team that spent the most money on transfer was [Chelsea](#6)...\n\n[Ronaldo](#3) was determined as the most efficient striker.\n\n<font color = 'black'>\n\n* [Load and Visualizing the Dataset](#1)\n* [Amateur Football Players](#2)\n* [Most Effective and Valuable Striker](#3)\n* [Highest Market Value and Transfer Fee](#4)\n* [The club that spends the most money according to the transfers](#5)\n* [Result](#6)\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns  \nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n<a id = \"1\"><\/a><br>\n# Load and Visualizing the Dataset\n\"\"\"\nData = pd.read_csv('..\/input\/top-250-football-transfers-from-2000-to-2018\/top250-00-19.csv')\nData.head()\n\nData.info()\nData.corr()\n# Name of columns\n\nData.columns\nData.Age.plot(kind = 'line', color = 'b',label = 'Age',linewidth = 1.5,alpha = 0.8, grid = True, linestyle = ':')\nData.Market_value.plot(color = 'r',label = 'Market_value',linewidth = 1.5, alpha = 0.5, grid = True, linestyle = '-.')\nData.Transfer_fee.plot(kind = 'line', color = 'k', label = 'Transfer_fee', linewidth = 1.5, alpha = 0.5, grid = True, linestyle = '--')\nplt.legend(loc='best')    \nplt.xlabel('x axis')              \nplt.ylabel('y axis')\nplt.title('Line Plot')\nplt.show()\nData.plot(kind='scatter', x='Age', y='Market_value',alpha = 0.5,color = 'green')\nplt.xlabel('Age')              \nplt.ylabel('Market Value')\nplt.title('Age and Market Value Scatter Plot')  \nsns.jointplot(data=Data, x=\"Age\", y=\"Transfer_fee\", marker=\"+\", s=100, marginal_kws=dict(bins=25, fill=False))\nComp = sns.cubehelix_palette(3, rot=-.5, dark=.2)\nsns.violinplot(data=Data, palette=Comp, inner=\"points\")\nplt.show()\nsns.swarmplot(x=\"Age\", y=\"Market_value\", data=Data)\nplt.show()\nsns.set(style = \"white\")\ndf = Data.loc[:,[\"Age\",\"Market_value\",\"Transfer_fee\"]]\ng = sns.PairGrid(df,diag_sharey = False,)\ng.map_lower(sns.kdeplot,cmap=\"Blues_d\")\ng.map_upper(plt.scatter)\ng.map_diag(sns.kdeplot,lw =3)\nplt.show()\n\"\"\"\n<a id = \"2\"><\/a><br>\n# Amateur Football Players\n\"\"\"\nx = Data['Age']<18\nData[x]\n\"\"\"\n<a id = \"3\"><\/a><br>\n# **Most Effective and Valuable Striker**\n\"\"\"\n\"\"\"\n* According to the [article](https:\/\/www.tandfonline.com\/doi\/full\/10.1080\/24748668.2020.1833625), a striker's most effective age is between the ages of **21 and 25**. For this, we will consider the strikers in this age range.\n\"\"\"\nPlayerAge = Data[np.logical_and(Data['Age']>21, Data['Age']<25)]\nPlayerAge\nPlayerPosition = PlayerAge[['Name', 'Position', 'Age', 'Market_value', 'Transfer_fee']]\nPlayerPosition\nEfficientStriker = PlayerPosition.loc[PlayerPosition['Position'] == 'Centre-Forward']\nEfficientStriker\nNameofStriker = EfficientStriker[['Name', 'Market_value', 'Transfer_fee']]\nNameofStriker\nPlayerWorth = NameofStriker.loc[NameofStriker['Market_value'].idxmax()]\nPlayerWorth\nPlayerFee = NameofStriker.loc[NameofStriker['Transfer_fee'].idxmax()]\nPlayerFee\n\"\"\"\n**Teams Cristiano Ronaldo Played with During This Time**\n\"\"\"\nData.loc[Data['Name'] == 'Cristiano Ronaldo']\n\"\"\"\n<a id = \"4\"><\/a><br>\n# **Highest Market Value and Transfer Fee**\n\"\"\"\nData.loc[Data['Market_value'].idxmax()]\n\nData.loc[Data['Transfer_fee'].idxmax()]\n\"\"\"\n<a id = \"5\"><\/a><br>\n# **The club that spends the most money according to the transfers**\n\"\"\"\nRichClubs = Data[['Team_to', 'Transfer_fee']]\nRichClubs\nTop = RichClubs.groupby(['Team_to', 'Transfer_fee']).size()\nTop.head(40)\n\"\"\"\n<a id = \"7\"><\/a><br>\n* **Team with the most transfers**\n\"\"\"\nf, ax = plt.subplots(figsize=(10,10))\nRichClubGraph = RichClubs['Team_to'].value_counts()[:30].sort_values(ascending=True).plot(kind='barh', ax=ax, legend = False, color = 'y', edgecolor='r', width=0.7)\nplt.tight_layout()\nRichClubs['Team_to'].value_counts()\ndff = RichClubs.groupby([\"Team_to\"]).Transfer_fee.sum().reset_index()\ndff = dff.sort_values(by = 'Transfer_fee', ascending=False, na_position='first')\n\nprint(dff.head(10))\n\"\"\"\n<a id = \"6\"><\/a><br>\n**The team that spent the most during this time**\n\"\"\"\ndff.loc[dff['Transfer_fee'].idxmax()]\n\"\"\"\n**[Thank you :)](http:\/\/www.galatasaray.org\/en\/Homepage)** \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '227a898e9558bf'}"}
{"id":"75540","text":"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport nltk\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import RegexpTokenizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import classification_report,confusion_matrix\n\"\"\"\n# Carregando os dados\n\"\"\"\ndf = pd.read_csv(\"..\/input\/olist_classified_public_dataset.csv\")\ndf.head(6)\n\"\"\"\n# Analise Explorat\u00f3ria dos dados\n\"\"\"\n#Quantidade de linhas e colunas do DataFrame\ndf.shape\n# 3584 linhas e 34 colunas\n\"\"\"\nPrimeiro vamos analisar as categorias dos produtos e retirar algumas estatisticas\n\"\"\"\ndf[\"product_category_name\"].describe()\n#Todas as categorias de produtos\nvalueCategoria = df[\"product_category_name\"].value_counts()\nvalueCategoria\nprint(valueCategoria[0:6])\nprint(\"Somatorio: %s\" % valueCategoria[0:6].sum())\nvalueCategoria[0:6].sum()\/valueCategoria.sum()\n\"\"\"\nPodemos notar que 10% das categorias s\u00e3o responsaveis por 46.24% da nossa base. Sendo elas:\n\n* cama_mesa_banho\n* moveis_decoracao\n* beleza_saude\n* esporte_lazer\n* informatica_acessorios\n* utilidades_domesticas\n\"\"\"\nMEAN = df[\"review_score\"].mean()\nprint(\"M\u00e9dia da popula\u00e7\u00e3o %s\" % MEAN)\nstd = df[\"review_score\"].std()\nprint(\"Desvio Padr\u00e3o da popula\u00e7\u00e3o: %s\" % std)\n\"\"\"\nA m\u00e9dia de score \u00e9 3.5228 e o desvio padr\u00e3o \u00e9 igual a 1.65, com isso em mente vamos analisar as principais categorias de produtos.\n\"\"\"\ndf.groupby(['product_category_name'])[\"review_score\"].describe().sort_values(['count'], ascending=False)\n\"\"\"\nSe analisarmos as seis primeiras categoria, podemos notar que a media de todos os dados (3.5228) n\u00e3o difere tanto da media por categoria, mas o desvio padr\u00e3o esta um valor alto. Como essas categorias representam 46.24% da nossa base. Poderia ser feito um estudo mais aprofundado para tentar elevar a media dos scores e diminuir a vari\u00e2ncia (quadrado do desvio padr\u00e3o). Diminuir essa vari\u00e2ncia seria importante, pois se o cliente n\u00e3o teve uma boa experiencia com compras online, ele pode n\u00e3o voltar a comprar na mesma.\n\"\"\"\ndfFiltrado = df[(df.product_category_name == \"cama_mesa_banho\") | \n                (df.product_category_name == \"moveis_decoracao\")|\n                (df.product_category_name == \"beleza_saude\")|\n                (df.product_category_name == \"esporte_lazer\")|\n                (df.product_category_name == \"informatica_acessorios\")|\n                (df.product_category_name == \"utilidades_domesticas\")]\n\n\ndfFiltrado.groupby(['product_category_name'])[\"most_voted_class\"].value_counts(normalize=True)\n\"\"\"\nNormalizando os nosso dados, podemos notar que proporcionalmente a categoria com o maior numero de clientes satisfeitos \u00e9 beleza_saude, enquanto a categoria com maior propor\u00e7\u00e3o de clientes com problemas na entrega foi informatica_acessorios e a categoria com maior propor\u00e7\u00e3o de problemas de qualidade tambem foi informatica acessorios. Como informatica_acessorios \u00e9 a categoria proporcionalmente com o maior numero de reclama\u00e7\u00e3o, caberia uma medida especifica para a mesma. Principalmente levando em conta que o mercado de inform\u00e1tica tem uma grande volatilidade, ent\u00e3o uma boa experiencia do cliente poderia ocasionar novas compras em um futuro pr\u00f3ximo.\n\"\"\"\n\"\"\"\n## Categoria: informatica_acessorios\n\"\"\"\ndfInformatica = df[df[\"product_category_name\"] == \"informatica_acessorios\"]\ndfInformatica.head(2)\n## Pegando as categorias problemas_de_entrega e problemas_de_qualidade\n\ndfInformatica[(dfInformatica[\"most_voted_class\"] == \"problemas_de_entrega\") |\n              (dfInformatica[\"most_voted_class\"] == \"problemas_de_qualidade\")][\"most_voted_subclass\"].value_counts()\n\"\"\"\nO maior problema para a categoria de inform\u00e1tica \u00e9 o atrasado, uma solu\u00e7\u00e3o seria uma melhoria do algoritmo de calculo do prazo de entrega ou a cria\u00e7\u00e3o de alguns indicadores e medidas de preven\u00e7\u00e3o, um exemplo seria um indicador que acompanha o rastreamento do pedido, quando o indicador notar que vai ocorrer um atraso, poderia levantar uma flag para que o operacional possa entrar em contato com o cliente, para explicar os motivos do atraso e contornar o problema da melhor maneira poss\u00edvel. \n\"\"\"\nprint(df[df[\"most_voted_class\"]== \"satisfeito_com_pedido\"][\"product_photos_qty\"].describe())\nprint(dfInformatica[(dfInformatica[\"most_voted_class\"] == \"problemas_de_qualidade\") | (dfInformatica[\"most_voted_class\"] == \"diferente_do_anunciado\")][\"product_photos_qty\"].describe())\n\"\"\"\nAnalisando o problema de qualidade e diferente do anunciado, podemos notar que esses produtos tem uma m\u00e9dia de fotos (1.976744) no anunciante abaixo da m\u00e9dia da classe \"satisfeito_com_pedido\"(2.217347), o que poderia ter alguma correla\u00e7\u00e3o, dado que com mais fotos, o cliente tem mais informa\u00e7\u00e3o sobre o produto.\n\"\"\"\n\"\"\"\n## Matriz de correla\u00e7\u00e3o\n\"\"\"\ndf.corr()\ndf[[\"review_score\", \"product_photos_qty\", \"product_description_lenght\", \"order_products_value\", \"order_freight_value\", \"order_items_qty\"]].corr()\n\"\"\"\nFazendo algum testes de correla\u00e7\u00e3o, n\u00e3o obtivemos nenhuma correla\u00e7\u00e3o significativa.\n\"\"\"\n\"\"\"\n# Most_voted_class\n\nAnalisaremos agora a categoria Most_voted_class, utilizando toda a nossa base de dados.\n\"\"\"\n# Classifica\u00e7\u00f5es e suas frequencias\nfreqClass = df[\"most_voted_class\"].value_counts()\nfreqClass\nprint(\"%s\" % ((1983 \/ freqClass.sum())* 100))\nprint(\"%s\" % ((950 \/ freqClass.sum())* 100))\nprint(\"%s\" % ((480 \/ freqClass.sum())* 100))\n\"\"\"\nPodemos notar que na nossa base, a classe dominante \u00e9 satisfeito_com_pedido, com 58.10%, seguido de problemas na entrega com 27.83% e por ultimo problemas de qualidade com 14.06%.\n\"\"\"\n## Plotando as frequencias\nsns.barplot(freqClass.index, freqClass.values)\nplt.show()\n\"\"\"\n## Subclass: problemas_de_qualidade\n\"\"\"\n# Criando um novo data frame apenas com os problemas de qualidade\ndfQuali = df[df[\"most_voted_class\"] == \"problemas_de_qualidade\"]\nfreqSubClassQual = dfQuali[\"most_voted_subclass\"].value_counts()\nfreqSubClassQual\n\"\"\"\nPodemos notar um volume muito grande de problemas com o produto diferente do anunciado, algumas medidas podem ser tomadas, como uma melhor descri\u00e7\u00e3o do produto, utiliza\u00e7\u00e3o de videos para demonstrar o produto, entre outras.\n\"\"\"\n\"\"\"\n### NLP da categoria Problemas_de_qualidade\n\"\"\"\n\"\"\"\nTemos 480 reviews, vamos criar Bigramas para cada subcategoria\n\"\"\"\nplt.figure()\nsubcategorias = [\"diferente_do_anunciado\", \"baixa_qualidade\", \"devolucao\", \"outro_pedido\"]\nfor subcategoria in subcategorias:\n    dfGenerico = dfQuali[dfQuali[\"most_voted_subclass\"] == subcategoria]\n    review = (\" \".join(dfGenerico[\"review_comment_message\"])).lower().replace(\"produtoq\", \"produto\")\n    review\n    # Removendo a pontua\u00e7\u00e3o e Tokenizando o texto\n    tokenizer = RegexpTokenizer(r'\\w+')\n    cleanText = tokenizer.tokenize(review)\n\n    # Removendo as StopWords\n    stopWords = stopwords.words('portuguese')\n    stopWords.remove(\"n\u00e3o\")\n    filtered_words = [word for word in cleanText if word not in stopWords]\n\n    # Criando Bigramas\n    filtered_words = nltk.ngrams(filtered_words, 2)\n\n    filtered_words\n\n    freq = nltk.FreqDist(filtered_words)\n    plt.figure(figsize=(10, 5))\n    plt.title(subcategoria)\n    freq.plot(30)\n\"\"\"\nAnalisando o gr\u00e1fico de bigramas, podemos notar que na categoria diferente_do_anunciado teve uma grande reclama\u00e7\u00e3o sobre a cor do produto que veio errado. Enquanto na categoria baixa_qualidade temos reclama\u00e7\u00e3o por causa da qualidade, ou afirma\u00e7\u00f5es como \"o produto n\u00e3o \u00e9 oque eu esperava\" ou que \"n\u00e3o vale o pre\u00e7o\". A classe de devolu\u00e7\u00e3o parece ter uma grande reclama\u00e7\u00e3o com a categoria roupas, como por exemplo o tamanho da camisa foi errada.\n\"\"\"\n\"\"\"\n## Subclass: problemas_de_entrega\n\"\"\"\n# Criando um novo data frame apenas com os problemas de entrega\ndfEntrega = df[df[\"most_voted_class\"] == \"problemas_de_entrega\"]\nfreqSubClassEntre = dfEntrega[\"most_voted_subclass\"].value_counts()\nfreqSubClassEntre\n\"\"\"\nPodemos notar que atraso foi a subcategoria que mais causou transtornos. Vamos analisar os estados que mais tiveram problemas com essa subcategoria.\n\"\"\"\n# Frequencia dos estados que mais tiveram problemas com a entrega\nfreqAtraso = dfEntrega[dfEntrega[\"most_voted_subclass\"] == \"atrasado\"][\"customer_state\"].value_counts()\nfreqAtraso\nprint((134\/freqAtraso.sum()) * 100)\nprint((108\/freqAtraso.sum()) * 100)\nprint(((134\/freqAtraso.sum()) * 100) + ((108\/freqAtraso.sum()) * 100))\n\"\"\"\nO estado de S\u00e3o Paulo e Rio de Janeiro somam juntas 55% dos problemas atrasos, 30.87% e 23.88% respectativamente.\nComo demonstrado na tabela abaixo, a cidade de S\u00e3o Paulo possui a maioria dos atrasos. Por se tratar de uma grande cidade, algumas outras medidas podem ser tomadas, alem das j\u00e1 debatidas nesta analise. Como por exemplo, uma parceria com outras empresas de transportes.\n\"\"\"\n# Cidades de S\u00e3o Paulo com o maior numero de atrasos\ndfEntrega[dfEntrega[\"customer_state\"] == \"SP\"][\"customer_city\"].value_counts()\n\"\"\"\n# Rede Neural\n\"\"\"\n\"\"\"\nVamos criar uma rede neural para tentar predizer o score do produto baseado no pre\u00e7o do produto e seu frete.\n\"\"\"\nX = df[[\"order_products_value\", \"order_freight_value\"]]\ny = df[\"review_score\"]\n# Separando a nossa base em valida\u00e7\u00e3o e treinamento\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nmlp = MLPClassifier(hidden_layer_sizes=(13),max_iter=5000)\nmlp.fit(X_train,y_train)\nMLPClassifier()\npredictions = mlp.predict(X_test)\n# Criando a matriz de confus\u00e3o\nprint(confusion_matrix(y_test,predictions))\nprint(classification_report(y_test,predictions))\n\"\"\"\nComo o esperado, a nossa precis\u00e3o foi de apenas, 0.35. Isso ocorreu pois n\u00e3o houve um tratamento das vari\u00e1veis, uma escolha dos melhores par\u00e2metros de teste e uma otimiza\u00e7\u00e3o dos par\u00e2metros da rede neural.\nO objetivo maior era demonstrar que podemos criar um modelo de predi\u00e7\u00e3o baseado na nossa base, que com um pouco de trabalho, pode dar \u00f3timos resultados.\n\"\"\"\n\"\"\"\n# Conclus\u00e3o\n\"\"\"\n\"\"\"\nO objetivo desta analise \u00e9 demonstrar algumas possibilidades de trabalhos mais estruturados que podem ser feitos com a utiliza\u00e7\u00e3o desta base, como a utiliza\u00e7\u00e3o de outras abordagens do NLP (Neuro-Linguistic Programming), testes estat\u00edsticos e cria\u00e7\u00e3o de modelos preditivos.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8ad29976a552ba'}"}
{"id":"125166","text":"\"\"\"\n## Table Content\n* 1. Importing Modules\n\n* 2. Loading Data\n\n* 3. Data PreProcessing And Visualizations\n\n* 4. Utility Functions\n\n* 5. Data Balancing\n\n* 6. Modelling And Optimizing The Models\n\n* 7. Results And Conclusion\n\"\"\"\n\"\"\"\n# Importing Modules\n\"\"\"\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_auc_score\nimport numpy as np\nimport pandas as pd \nimport os\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import plot_tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nimport seaborn as sns\nimport matplotlib.pyplot as plt \nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix,r2_score\nfrom sklearn import model_selection\nfrom sklearn.ensemble import BaggingClassifier\nimport warnings\nfrom imblearn.over_sampling import SMOTE\nwarnings.filterwarnings('ignore')\n\"\"\"\n# Loading Data\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/bank-marketing\/bank-additional-full.csv', sep = ';')\ndf.head()\ndf.info()\n\"\"\"\n# Checking Categorical Columns\n\"\"\"\nfor col in df.columns:\n    print()\n    if df[col].dtype == 'object':\n        print(f'Name of Column is: {col} and unique values are: {df[col].unique()}')\n\"\"\"\n## Utility Function\n\"\"\"\n#this function returns categorical variables\ndef return_categorical(df):\n\n  categorical_columns = [column_name for column_name in df if df[column_name].dtype == 'O']\n  return categorical_columns\n\n#this function returns numerical variables\ndef return_numerical(df):\n\n  return list(set(df.columns) - set(return_categorical(df)))\n\n\ndef check_normal(df):\n  fig, axes = plt.subplots(1,len(return_numerical(df)), figsize =(70, 10))\n\n  for i,numeric_column_name in enumerate(list(set(df.columns) -set(return_categorical(df)))):\n\n    sns.distplot(df[numeric_column_name], ax=axes[i]);\n    plt.title(f'Distribution of {numeric_column_name}');\n    \ndef classifier(clf, x_train,x_test,y_train,y_test):\n    y_test_pred = clf.predict(x_test)\n    y_train_pred = clf.predict(x_train)\n\n    accuracy_test = accuracy_score(y_test,y_test_pred)\n    accuracy_train =  accuracy_score(y_train,y_train_pred)\n    \n    roc_test = roc_auc_score(y_test, y_test_pred, multi_class='ovr')\n    roc_train = roc_auc_score(y_train, y_train_pred, multi_class='ovr')\n    \n    print('Train accuracy is:',accuracy_train )\n    print('Test accuracy is:',accuracy_test )\n    print()\n    print('Train ROC is:', roc_train)\n    print('Test ROC is:',roc_test )\n    \n    # Fscore, precision and recall on test data\n    f1 = f1_score(y_test, y_test_pred)\n    precision = precision_score(y_test, y_test_pred)\n    recall = recall_score(y_test, y_test_pred) \n    print()\n    print(\"F score is:\",f1 )\n    print(\"Precision is:\",precision)\n    print(\"Recall is:\", recall)\n  \n\ndef random_search(clf,params, x_train,x_test,y_train,y_test):\n    \n    random_search = RandomizedSearchCV(estimator= clf, param_distributions=params, scoring='roc_auc', cv=5)\n    random_search.fit(x_train, y_train)\n    optimal_model = random_search.best_estimator_\n\n    print(\"Best parameters are: \", random_search.best_params_)\n    print()\n    print(\"Best estimator is: \", random_search.best_estimator_)\n    print()\n    print('Scores and accuracies are:')\n    print()\n    classifier(optimal_model, x_train,x_test,y_train,y_test)\n\"\"\"\n# Data Preprocessing\n* Data Visualisation\n\"\"\"\ncheck_normal(df)\n\"\"\"\n* None of the feature are following a Normal Distribution\n\"\"\"\n\"\"\"\n# Visualising Categorical Variabels\n\"\"\"\n\n# plotting graphs for all categorical columns\nfor col in return_categorical(df):\n    counts = df[col].value_counts().sort_index()\n    if len(counts) > 10:\n      fig = plt.figure(figsize=(30, 10))\n    else:\n      fig = plt.figure(figsize=(9, 6))\n    ax = fig.gca()\n    counts.plot.bar(ax = ax, color='steelblue')\n    ax.set_title(col + ' counts')\n    ax.set_xlabel(col) \n    ax.set_ylabel(\"Frequency\")\nplt.show()\n\"\"\"\n* imbalanced categorical data observed\n\"\"\"\n\"\"\"\n# Checing highly co-related column\n\"\"\"\ncorr = df.corr()\ncorr_greater_than_75 = corr[corr>=.75]\ncorr_greater_than_75\n#Visualising by heatmap\nplt.figure(figsize=(12,8))\nsns.heatmap(corr_greater_than_75, cmap=\"Reds\", annot = True);\n\"\"\"\n* Some correlation can be seen here between emp. var rate and nr.employed.\n* Also, euribor3m and emp.var rate.\n* However, I would not be removing any. As I am gonna mostly be training on tree models which doesn't require much preprocessing.\n\"\"\"\n\"\"\"\n# Checking Unique values\n\"\"\"\ndf['pdays'].unique()\n\"\"\"\n* 999 represents no contact has been done, thus i'll be assigning it a very less weight.\n\"\"\"\n\"\"\"\n## Modefing the column on the basis of importance weighs\n\"\"\"\ndf['job'] = df['job'].apply(lambda x: -1 if x=='unknown' or x=='unemployed' else (15 if x=='entrepreneur' else (8 if x == 'blue-collar' else ( 6 if x=='technician' or x=='services' or  x=='admin.' or x=='management' else (4 if x== 'self-employed' or x=='student' else (2 if x=='housemaid' or x=='retired' else None) )))))\ndf['housing'] = df['housing'].apply(lambda x: 0 if x=='no' else (1 if x=='yes' else -1))\ndf['loan'] = df['loan'].apply(lambda x: 0 if x=='no' else (1 if x=='yes' else -1))\ndf['y'] = df['y'].apply(lambda x: 0 if x=='no' else (1 if x=='yes' else -1))\ndf['default'] = df['default'].apply(lambda x: 0 if x=='no' else (1 if x=='yes' else -1))\ndf['poutcome'] = df['poutcome'].apply(lambda x: 0 if x=='failure' else (2 if x=='failure' else -1))\ndf['pdays'] = df['pdays'].apply(lambda x: 0 if x==999 else(20 if x<=10 else(6 if x<=20 else 3)))\n\"\"\"\n# Droping columns\n\"\"\"\ndf.drop(['day_of_week', 'contact', 'month'], axis=1, inplace = True)\n\"\"\"\n# One hot encoding for categorical features \n\"\"\"\ndf  = pd.get_dummies(df, drop_first = True)\n\"\"\"\n# Train_Test_Split\n\"\"\"\nx = df.drop(\"y\", axis=1)\ny = df['y']\nx.sample()\n\nx_train,x_test,y_train,y_test = train_test_split(x,y, random_state=42)\n\"\"\"\n# Balancing data by using SMOTE\n\"\"\"\nsmote = SMOTE()\n\n# fit predictor and target variable\nx_smote, y_smote = smote.fit_resample(x_train, y_train)\n\nprint('Original dataset shape', len(x_train))\nprint('Resampled dataset shape', len(x_smote))\n\"\"\"\n# Scaling and Optimising\n\"\"\"\ns = StandardScaler()\n\"\"\"\n# Modeling with KNN\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors = 20)\nknn.fit( s.fit_transform(x_train), y_train)\n\nclassifier(knn, s.fit_transform(x_smote),s.transform(x_test), y_smote,y_test)\n\"\"\"\n# Tuning hyper perameters by using Knn \n\"\"\"\nerror_rate = []\nfor i in range(1,40):\n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit( s.fit_transform(x_train), y_train)\n pred_i = knn.predict(s.transform(x_test))\n error_rate.append(np.mean(pred_i != y_test))\n\nacc = []\nfor i in range(1,40):\n    neigh = KNeighborsClassifier(n_neighbors = i).fit(s.fit_transform(x_train), y_train)\n    yhat = neigh.predict(s.transform(x_test))\n    acc.append(metrics.accuracy_score(y_test, yhat))\n    \n# Visualising the tuning parameters\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', \n         marker='o',markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')\nprint(\"Minimum error:-\",min(error_rate),\"at K =\",error_rate.index(min(error_rate)))\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40),acc,color = 'blue',linestyle='dashed', \n         marker='o',markerfacecolor='red', markersize=10)\nplt.title('accuracy vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Accuracy')\nprint(\"Maximum accuracy:-\",max(acc),\"at K =\",acc.index(max(acc)))\n\"\"\"\n# Modeling value of K gives least error\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors = 10)\nknn.fit( s.fit_transform(x_smote), y_smote)\n\nclassifier(knn, s.fit_transform(x_smote),s.transform(x_test),y_smote,y_test)\n\"\"\"\n# Bagging Knn as base Model\n\"\"\"\n# bagging classifier\nmodel = BaggingClassifier(base_estimator = KNeighborsClassifier(n_neighbors = 10),\n                          n_estimators = 15)\nclassifier(model.fit( s.fit_transform(x_smote), y_smote), s.fit_transform(x_smote),s.transform(x_test),y_smote,y_test)\n\"\"\"\n# Modeling with Decession Tree\n\"\"\"\ndtree = DecisionTreeClassifier(random_state=0)\ndtree.fit(x_train, y_train)\nclassifier(dtree, x_train,x_test,y_train,y_test)\n\"\"\"\n* Not using balanced data with tree based models because they can handle imbalace pretty well so whynot.\n\"\"\"\n\"\"\"\n# Tuning hyper parameters for Decission tree\n\"\"\"\nparam_grid = {'max_depth':np.arange(3,20),\n              'min_samples_split': np.arange(3,20,1),\n             'min_samples_leaf':np.arange(3,30),\n              'min_samples_split' : np.arange(3,30),\n              'criterion': ('gini', 'entropy')}\n\n\n\nrandom_search(DecisionTreeClassifier(random_state=0),param_grid, x_train,x_test,y_train,y_test)\n\"\"\"\n# Decission Tree Base Bagging\n\"\"\"\n# I have chosen tuned hyperparameters here\n\n\nkfold = model_selection.KFold(n_splits = 3)\n\n# bagging classifier\nmodel = BaggingClassifier(base_estimator = DecisionTreeClassifier(min_samples_split=5, min_samples_leaf=25, max_depth=8, criterion='gini'),n_estimators = 500,)\n\nclassifier(model.fit(x_train, y_train), x_train,x_test,y_train,y_test)\n\"\"\"\n# Modeling with Random Forest\n\"\"\"\nrforest = RandomForestClassifier(random_state=0)\nclassifier(rforest.fit(x_train, y_train), x_train,x_test,y_train,y_test)\n\"\"\"\n# Tuning hyper parameters for Random Forest\n\"\"\"\nparams = {'n_estimators' : np.arange(100,1000, 100),\n              'max_depth' : np.arange(3,20,1),\n              'min_samples_split' : np.arange(3,20,1),\n              'min_samples_leaf' : np.arange(3,20,1),\n         'max_features': ('sqrt', 'log2'), 'criterion': ('gini', 'entropy')}\n\nrandom_search(RandomForestClassifier(random_state=0),params, x_train,x_test,y_train,y_test)\n\"\"\"\n* Bagging with Decision tree is performing the best according to recall and roc.\n* For a credit insurance problem, I would want to go with recall here.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e63dc9d497da9b'}"}
{"id":"471","text":"\"\"\"\n <b><p style=\"text-align:center;\"><font size =\"6\" color =\"Black\">\n    Quality Prediction in a Mining Process\n    <\/font><\/b>\n    \n \n <b><p style=\"text-align:center;\"><font size =\"3\" color =\"Black\">A Mineral Processing Engineer Approch<\/font><\/b> \n\n\"\"\"\n\"\"\"\n<h1>Table of Contents<\/h1>\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n    <ul>\n        <li>\n            1. Foreword    \n        <\/li>\n        <br>\n        <li>\n            2. CRISP-DM   \n        <\/li>\n        <br>\n        <li>\n            3. CRISP-DM STEP-1: Business Understanding   \n        <\/li>\n        <br>\n        <li>\n            4.CRISP-DM STEP-2: Data Understanding\n            <ul>\n                <li>4.1. Examine Data as Data Scientist<\/li>\n                <li>4.2. Examine Data as Mineral Processing Engineer<\/li>\n            <\/ul>\n        <\/li>\n        <br>\n        <li>\n            5. CRISP-DM STEP-3: DATA PREPARATION \n            <ul>\n                <li>5.1. Grouping Rows with Hourly Frequency<\/li>\n                <li>5.2. Divide Data<\/li>\n            <\/ul>\n        <\/li>\n        <br>\n        <li>\n            6. CRISP-DM STEP-4: MODELING\n             <ul>\n                <li>6.1. P-Value<\/li>\n                <li>6.2. Confidence Interval<\/li>\n            <\/ul>\n        <\/li>\n        <br>\n        <li>\n            7. CRISP-DM STEP-5: Evaluation\n            <ul>\n                <li>7.1. R-squared in Regression Analysis<\/li>\n                <li>7.2. Multi Linear Regression Analysis<\/li>\n                <li>7.3. Random Forest Regressor<\/li>\n            <\/ul>\n        <\/li>\n        <br>\n        <li>\n            8. CRISP-DM STEP-6: Deployment   \n            <ul>\n                <li>8.1. First Predictions<\/li>\n                <li>8.2. Second Predictions<\/li>\n            <\/ul>\n        <\/li>\n        <br>\n        <li>\n            9. Conclusion    \n        <\/li>\n    <\/ul>\n<\/div>\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n\n\n\n<h1><a id=\"Foreword\">1. FOREWORD<\/a><\/h1>\n\n<h4>I am a Mineral Processing Engineer and I train my-self about ML and AI. I prepared this notebook to gain experience. Thanks for EduardoMagalh\u00e3esOliveira for giving me this opportunity with this data. \n\n<h4> You will see a Mineral Processing approach in this report. I know, I am an amateur about machine learning. Please feel free to comment or reach me for anything. \n    \n\n<b><p style=\"text-align:right;\"><font size =\"3\" color =\"Black\">Aydin AKTAR<\/font><\/b>\n<b><p style=\"text-align:right;\"><font size =\"3\" color =\"Black\">aktaraydin@gmail.com<\/font><\/b>\n<b><p style=\"text-align:right;\"><a href=\"www.linkedin.com\/in\/aktaraydin\">Linkedin<\/a><\/font><\/b>\n\n\"\"\"\n\"\"\"\n<h4> You can reach the more detail from report below linked.\n\n<h3><p style=\"text-align:center;\"><a href=\"https:\/\/drive.google.com\/file\/d\/1kFGw01qVLsAaZ7kcKm27s0Hl3b4Mtze8\/view?usp=sharing\">Detailed Report Address<\/a><\/p><\/h3>\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"CRISP-DM\">2. CRISP-DM <\/a><\/h1>\n\n\"\"\"\n\"\"\"\n<h2><p style=\"text-align:center;\"><a href=\"https:\/\/en.wikipedia.org\/wiki\/Cross-industry_standard_process_for_data_mining\">Definition<\/a><\/p><\/h2>\n\n\n<img src=\"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/b\/b9\/CRISP-DM_Process_Diagram.png\" width=\"500\" height=\"500\">\n\n\n\n<h3><b><p style=\"text-align:center;\">I will do the project over the CRISP-DM cycle.<\/b><\/h3>\n\n\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"step1\">3. CRISP-DM STEP-1: BUSINESS UNDERSTANDING<\/a><\/h1>\n\"\"\"\n\"\"\"\n<h4>We cannot use the Mineral or Element in the ore extracted from the earth directly in industry. We\nhave to carry out an enrichment operation beforehand. The data we obtained was taken from a\nFlotation Plant, method is Reverse Cationic Flotation <\/h4>\n<br>\n<h3><p style=\"text-align:center;\"><a href=\" https:\/\/en.wikipedia.org\/wiki\/Froth_flotation\">Froth Flotation<\/a><\/p><\/h3>\n<h3><p style=\"text-align:center;\"><a href=\" https:\/\/iopscience.iop.org\/article\/10.1088\/1742-6596\/879\/1\/012016\/pdf\">Reverse Cationic Flotation<\/a><\/p><\/h3>\n\n\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"step2\">4.CRISP-DM STEP-2: DATA UNDERSTANDING<\/a><\/h1>\n\n\"\"\"\n\"\"\"\n\n<h3><a id=\"step21\">4.1. Examine Data as Data Scientist<\/a><\/h3>\n\"\"\"\n#Library Imports\n\nimport pandas as pd \nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor \nimport statsmodels.api as sm \nfrom sklearn.metrics import r2_score\nfrom pylab import *\n#Upload Data \nurl ='..\/input\/quality-prediction-in-a-mining-process\/MiningProcess_Flotation_Plant_Database.csv'\nmainData = pd.read_csv(url,decimal=',')\n\n \nprint('Shape of Main Data = ', mainData.shape)\nmainData = mainData.dropna()\nprint('Shape of Main Data after drop null values = ', mainData.shape)\n\n\"\"\"\n<h4>Data consists of 24 columns and 737453 rows, covers the dates between March 2017 and\nSeptember 2017 and some of the data were recorded at 10-second intervals and some at 1-hour\nintervals.<\/h4> \n\n\"\"\"\nmainData.head(10)\nmainData.columns\nmainData.dtypes\n\"\"\"\n<h4>In order to perform mathematical calculations on data, the data must be in \"int\" or \"float\"\nformat. The data type of columns containing numbers is \"float64\", sufficient for calculation.\nDate column is in \"object\" data type, we will need to change the unit before calculations. \n\nColumn Definitions: \n\n- Date: Date collection date and time.\n- % Iron Feed: Feed grade of iron-containing ore.\n- % Silica Feed: Feed grade of silica-containing ore..\n- Starch Flow: Depressant chemical for Iron(Fe) containing ore.\n- Amina Flow: Collector chemical for Silica containing ore.\n- Ore Pulp Flow: The amount of pulp flow fed to the Flotation Columns as the\nproduct of the previous process step.\n- Ore Pulp pH: pH.\n- Ore Pulp Density: The solid percent of ore fed to Flotation Columns.\n- Flotation Column 01,02,03,04,05,06,07 Air Flow: The amount of air fed to the\nFlotations Columns to frothing.\n- Flotation Column 01,02,03,04,05,06,07 Level: Showing float thickness of Flotation\nColumns.\n- % Iron Concentrate: Concentrate grade of iron-containing ore.\n- % Silica Concentrate: Concentrate grade of silica-containing ore\n\"\"\"\nmainData.describe()\n\"\"\"\n<h3><a id=\"step22\">4.2. Examine Data as Mineral Processing Engineer:\n<\/a><\/h3>\n\"\"\"\n\"\"\"\n<h3><p style=\"text-align:center;\">The plant flowsheet is probably (untold) like:<\/h3>\n\n<img src=\"https:\/\/i.ibb.co\/v48rqYr\/ak-m-semas.jpg\" width=\"400\" height=\"500\">\n\"\"\"\n\"\"\"\n<h4>Let\u2019s deep inside to Data:\n\n    \n- Data can be record at 10 second frequency.\n    \n- Flows can be measured.\n- pH can be measured.\n- Feed and Concentrate grade can be analyzed instantly.\n- Columns has level sensor.\n    \nIn order to obtain this data, plant must be operating with established automation system. It is not\npossible collect this data with this frequency by human hand.\nIn order to fully analyze a Flotation Plant, we need to obtain the minimum data below, which is\navailable in a plant operated with Scada.\n\n\nMissing data in the data that should be a minimum for analysis.\n\n1. Recovery \n2. Liberation Degree, Grinding Performance\n3. Pumps Amperes, Pressures, Flows\n4. Feed Tons\n5. Feed and Tail Grades for Every Columns \n6. Mineralogy\n\n\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n\n<h1><a id=\"step3\">5.CRISP-DM STEP-3: DATA PREPARATION<\/a><\/h1>\n\n\n\"\"\"\n\"\"\"\n<h4>There is no need for unit conversions in data. I just changed the \"date\" column from the \"object\"\ndata type to the \"datatime64\".\n\"\"\"\n#change date columns as datetime\nmainData['date'] = pd.to_datetime(mainData['date'])\n\"\"\"\n\n<h3><a id=\"step31\">5.1. Grouping Rows with Hourly Frequency<\/a><\/h3>\n\"\"\"\n\"\"\"\n<h4>I indicated about the need to consider the plant data as a totality. So how do we do this on\ndata? By doing loop-based analysis. My solution is to consider each row of data on a loop. We\nfeed 100 tons of ore to the plant, enrich it and complete the cycle. In this data I set each cycle as\n1 hour. That is, we take a photograph of the plant every hour and analyze it on this photograph.\nIf we had more regular data, we could do these cycles even for 1 minute, then we would have\nmore cycles for machine learning.\n\n\n\"\"\"\nmainData['date'] = pd.to_datetime(mainData['date'])\n#grouping the data according to the hours and get their average values. \ncycle_data = mainData.groupby(pd.Grouper(key='date',freq='H')).mean()\n# cycle_data.insert(0,'Date',cycle_data.index)\ncycle_data.reset_index(inplace = True)\n\n#some rows have 'null' values because of timing. We need to drop them \nprint('Shape of Cycle Data = ', cycle_data.shape)\ncycle_data = cycle_data.dropna()\nprint('Shape of Cycle Data after drop null values = ', cycle_data.shape)\nmainData.dtypes\n\"\"\"\n<h4>The grouping process has a number of advantages and disadvantages.\nAdvantages:\n    \n- Each analysis will be able to do each data cycle on an hourly frequency.\n- Date column can be dropped. The number of columns fell to 23.\n- The number of rows fell to 4097 from 737453. Every rows means calculations on\ncomputer.\n    \nDisadvantage:\n    \n- The number of rows fell to 4097 from 737453. The more rows we have for machine\nlearning, the better results we get. This large data loss will adversely affect our\nestimation results.\n\"\"\"\ndata = cycle_data.copy()\ndata.head()\n\"\"\"\n\n<h3><a id=\"step32\">5.2. Divide Data<\/a><\/h3>\n\"\"\"\n\"\"\"\n<h4>Flotation plant product (at least for this missing data) Iron and Silica concentrates namely the\nlast two columns. We will develop separate models for silica and iron in machine learning, so we\nwill separate the columns from the main data as two data types named \"iron_concentrate\" and\n\"silica_concentrate\".\nThe remaining columns are essentially Flotation conditions required to enrich the concentrate.\nWe also separate them as \"flotation_conditions\".\n\"\"\"\n#seperate data as flotation_conditions and concentrates\nflotation_conditions = data.iloc[:,1:22]\nconcentrates = data.iloc[:,22:]\nsilica_concentrate = concentrates.iloc[:,1].values\niron_concentrate = concentrates.iloc[:,0].values\n\nprint('Shape of flotation_conditions = ', flotation_conditions.shape)\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"step4\">6. CRISP-DM STEP-4: MODELING<\/a><\/h1>\n\"\"\"\n\"\"\"\n\n<h3><a id=\"step41\">6.1. P-Value:<\/a><\/h3>\n<h3><p style=\"text-align:center;\"><a href=\"https:\/\/medium.com\/@ODSC\/the-importance-of-p-values-in-data-science-6cb7c7380881\">p-Value Definition<\/a><\/p><\/h3>\n    \n\"\"\"\n'''P-value'''\n\nb_zero = np.append(arr = np.ones((len(data.iloc[:,1].values),1)).astype(int),\n                                                                     values = flotation_conditions,\n                                                                     axis = 1)\n\nsilica_concentrate = concentrates.iloc[:,1].values\niron_concentrate = concentrates.iloc[:,0].values\n\nmodel_iron = sm.OLS(endog = iron_concentrate,exog = b_zero).fit()\nprint(model_iron.summary())\n\nmodel_silica = sm.OLS(endog = silica_concentrate,exog = b_zero).fit()\nprint(model_silica.summary())\n#extract p-value from regression results\npValue_fe = model_iron.pvalues\npValue_si = model_silica.pvalues\npValue_fe_list = []\npValue_si_list = []\nfor i in range(len(pValue_fe)):\n    if i > 0:\n        pValue_fe_list.append(pValue_fe[i])\n        pValue_si_list.append(pValue_si[i])\nwidth_in_inches = 15\nheight_in_inches = 13\ndots_per_inch = 60\n\nplt.figure(\n    figsize=(width_in_inches, height_in_inches),\n    dpi=dots_per_inch)\n\nt = flotation_conditions.columns\nfe = pValue_fe_list\nsi = pValue_si_list\nplot(t, fe, label = 'Fe', color = 'blue',marker='o')\nplot(t, si, label = 'Si',color = 'red', marker='x')\nplt.xticks(rotation=90)\nplt.legend(loc=\"upper right\",prop={\"size\":25})\nylabel('P Value',fontsize = 20)\ntitle('P Value of Si adn Fe Cocentrates',fontsize = 25)\ngrid(True)\nplt.figure(figsize=(60,3))\nplt.savefig(\"p_values.png\")\nshow()\n\n\"\"\"\n<h4>When we examine the P values, we see that some values do not affect the concentrated grades.\nBut now we know that this is due to our lack of data. What would you think if you saw that the\ncocoa had no effect on the chocolate produced in the chocolate factory?\n\"\"\"\n\"\"\"\n\n<h3><a id=\"step42\">6.2. Confidence Interval:<\/a><\/h3>\n<h3><p style=\"text-align:center;\"><a href=\"http:\/\/mlwiki.org\/index.php\/Confidence_Intervals\">Confidence Interval Definition<\/a><\/p><\/h3>\n\"\"\"\n#Confidence Intervals\n\nm_fe = iron_concentrate.mean()\nse_fe = iron_concentrate.std()\/math.sqrt(len(iron_concentrate))\nci_fe = [m_fe - se_fe*1.96, m_fe + se_fe*1.96]\n\n\nm_si = silica_concentrate.mean()\nse_si = silica_concentrate.std()\/math.sqrt(len(silica_concentrate))\nci_si = [m_si - se_si*1.96, m_si + se_si*1.96]\n\nprint  ('Confidence interval of Fe Concentrate:' ,ci_fe)\nprint  ('Confidence interval of Silica Concentrate:' ,ci_si)\n\"\"\"\n<h4>Metallurgical engineers apply the pouring process to the concentrate we sell and obtain pure\niron. There is a grade range they demand from us for this operation:\n%67 \u2013 68 Fe Grade\n%1.6 \u2013 1.7 Si Grade\nIn the model we developed according to the confidence interval, the silica values are more than\ndemanded. In the first stage, we need to warn the engineers in the field. (Assuming our data is\nreliable.)<\/h4>\n\n\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"step5\">7. CRISP-DM STEP-5: EVALUATION<\/a><\/h1>\n\"\"\"\n\"\"\"\n\n<h3> <a id=\"step51\">7.1. R-squared in Regression Analysis<\/a><\/h3>\n<h3><p style=\"text-align:center;\"><a href=\"https:\/\/www.geeksforgeeks.org\/ml-r-squared-in-regression-analysis\/\">Confidence Interval Definition<\/a><\/p><\/h3>\n\n\"\"\"\n\"\"\"\n\n<h3><a id=\"step52\">7.2. Multi Linear Regression Analysis<\/a><\/h3>\n\"\"\"\nwidth_in_inches = 15\nheight_in_inches = 13\ndots_per_inch = 60\n\nplt.figure(\n    figsize=(width_in_inches, height_in_inches),\n    dpi=dots_per_inch)\n\nx_axis = data['% Iron Concentrate']\ny_axis = data['% Iron Feed']\nplot(x_axis, y_axis,marker='o')\nplt.xticks(rotation=90)\nplt.legend(loc=\"upper right\",prop={\"size\":25})\nxlabel('% Iron Concentrate',fontsize = 20)\nylabel('% Iron Feed',fontsize = 20)\ntitle('% Iron Concentrate vs % Iron Feed',fontsize = 25)\ngrid(True)\nplt.figure(figsize=(60,3))\nshow()\n\"\"\"\n<h4>As you can see in plot, there is no Linear Reletionship betweenn Iron Feed and Iron Concentration, this is just example. The other columns relation ships are same. I am waiting for a low result of R2-Score from Multi Linear Regression Analysis\n\"\"\"\n#train test split for regression training and testing \nx_train, x_test, y_train, y_test = train_test_split(flotation_conditions,\n                                                    concentrates,\n                                                    test_size = 0.15,\n                                                    random_state = 0)\n'''MLR'''\nregressor_mlr = LinearRegression()\nregressor_mlr.fit(x_train,y_train) #x trainden y traini \u00f6\u011fren \n\ny_pred_mlr = regressor_mlr.predict(x_test)\nprint('R2 Score of Multi Linear Regression',r2_score(y_test,y_pred_mlr))\n\"\"\"\n<h4>It has become clear that the Multi Linear Regression model cannot be used. I will focus on\nRandom Forest machine learning model development.\n\"\"\"\n\"\"\"\n\n<h3> <a id=\"step53\">7.3. Random Forest Regressor:<\/a><\/h3>\n<h3><p style=\"text-align:center;\"><a href=\"https:\/\/en.wikipedia.org\/wiki\/Random_forest\">Random Forest Regressor Definition<\/a><\/p><\/h3> \n\"\"\"\n\"\"\"\n<h4>The first time I divided the data as train test split at 0.33 degree and applied Random Forest\nmachine learning, but I got very low r-Square values. Finally, I used all the data for training and\ngot the following results. Despite the lack of data, the result is satisfactory.\n\"\"\"\n'''RANDOM FOREST with Train-Test Split'''\n\nregressor_randForest = RandomForestRegressor(random_state = 0, n_estimators = 100)  \nregressor_randForest.fit(x_train,y_train) \ny_pred_rf = regressor_randForest.predict(x_test)\n\nregressor_randForest2 = RandomForestRegressor(random_state = 0, n_estimators = 100)  \nregressor_randForest2.fit(flotation_conditions,concentrates)\ny_pred_rf2 = regressor_randForest.predict(flotation_conditions)\n \nprint('R2 Score of Random Forest Regression with Train-Test Split',r2_score(y_test,y_pred_rf))\nprint('R2 Score of Random Forest Regression with Whole Data',r2_score(concentrates,y_pred_rf2))\n\"\"\"\n<h4>As I mentioned before I divided concentrations and again applied Random Forest separately to Iron and Silica Concentration grades. R2-Score result is marvelous. \n\"\"\"\n'''Iron Random Forest Model'''\nregressor_Fe = RandomForestRegressor(random_state = 0, n_estimators = 100)  \nregressor_Fe.fit(flotation_conditions,iron_concentrate) \ny_pred_Fe = regressor_Fe.predict(flotation_conditions)\n\nprint('R2 Score of Random Forest Regression with Only Iron',r2_score(iron_concentrate,y_pred_Fe))\n'''Silica Random Forest Model'''\nregressor_Si = RandomForestRegressor(random_state = 0, n_estimators = 100)  \nregressor_Si.fit(flotation_conditions,silica_concentrate) \ny_pred_Si = regressor_Si.predict(flotation_conditions)\n\nprint('R2 Score of Random Forest Regression with Only Silica',r2_score(silica_concentrate,y_pred_Si))\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"step6\">8. CRISP-DM STEP-6: DEPLOYMENT<\/a><\/h1>\n\"\"\"\n\"\"\"\n<h3><a id=\"step61\">8.1. First Predictions:<\/a><h3>\n\n\"\"\"\n\"\"\"\n<h4>I will feed to ML random values as conditions and demand to predict concentrate\nvalues<\/h4>\n\"\"\"\n#feel free change values and see results\npredictions = {'% Iron Feed':50.5,\n          '% Silica Feed':13.3,\n          'Starch Flow':3500.0,\n          'Amina Flow':580.0,\n          'Ore Pulp Flow':400.0,\n          'Ore Pulp pH':10.11,\n          'Ore Pulp Density':1.69,\n          'Flotation Column 01 Air Flow':250.0,\n          'Flotation Column 02 Air Flow':150.0,\n          'Flotation Column 03 Air Flow':270.0,\n          'Flotation Column 04 Air Flow':190.0,\n          'Flotation Column 05 Air Flow':230.0,\n          'Flotation Column 06 Air Flow':200.0,\n          'Flotation Column 07 Air Flow':240.0,\n          'Flotation Column 01 Level':480,\n          'Flotation Column 02 Level':210.0,\n          'Flotation Column 03 Level':550.0,\n          'Flotation Column 04 Level':620.0,\n          'Flotation Column 05 Level':610.0,\n          'Flotation Column 06 Level':615.0,\n          'Flotation Column 07 Level':616.0,\n          }\n#to see predictions, run this code\npredict_values = []\nfor value in predictions.values(): \n    predict_values.append(value)\n\npredict_Fe = regressor_Fe.predict([predict_values])\npredict_Si = regressor_Si.predict([predict_values])\n\nprint('Predicted Fe Concentrate =',predict_Fe,'%')\nprint('Predicted Silica Concentrate =',predict_Si,'%')\n\"\"\"\n<h3><a id=\"step62\">8.2. Second Predictions:<\/a><\/h3>\n\n<h4>I will feed to ML mean values of the main data and demand to predict\nconcentrate values.<\/h4>\n\"\"\"\npredict_from_means = flotation_conditions.describe().mean()\npredict_Fe = regressor_Fe.predict([predict_from_means])\npredict_Si = regressor_Si.predict([predict_from_means])\n\nprint('Predicted Fe Concentrate from Conditions mean  =',predict_Fe,'%')\nprint('Predicted Silica Concentrate from Conditions mean =',predict_Si,'%')\n\"\"\"\n<h4>We obtained the values we determined in the Confidence Intervals. The results are also very close to\nthe average tenor values.\nAfter all, we have a working ML\napplication.\n\n\n\"\"\"\n\"\"\"\n<hr style=\"border: none; border-bottom: 2px solid lightblue;\">\n<h1><a id=\"conc\">9. CONCLUSION<\/a><h1>\n\"\"\"\n\"\"\"\n<h4>With the analysis made over the same data set, we can write thousands more questions and get\nresults.\n\nOur touchstone data on the road to IoT (internet of things) and how we store them. As long as we\ntake care of our data and enrich them, the future is not far away. The more data you get, the more\naccurate results are inevitable.\n\nArtificial intelligence, which analyzes the ore coming from the mine and gives us the facility\nparameters as ready and calculate equipment maintenance possibilities, is now very close.<\/h4>\n<br>\n\n<b><p style=\"text-align:right;\"><font size =\"3\" color =\"Black\">See you on the next project.<\/font><\/b> \n<b><p style=\"text-align:right;\"><font size =\"3\" color =\"Black\">Aydin AKTAR<\/font><\/b> \n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '00e6c60e3037ab'}"}
{"id":"120060","text":"\"\"\"\n# Analysis of Coronavirus Data, Arizona and USA\n\nStatus: Updating for friends and family upon request. Can update daily.\n\nA copy of the notebook \"Coronavirus 2019-20 Visualization\" by Holf Yuen, but adjusted to monitor the world vs. Arizona, USA.\n\n\n\n\"\"\"\n# Importing packages\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nplt.rcParams.update({'font.size': 14})\n\n# Load data\ndata = pd.read_csv('\/kaggle\/input\/novel-corona-virus-2019-dataset\/covid_19_data.csv', parse_dates = ['ObservationDate','Last Update'])\n\nprint (data.shape)\nprint ('Last update: ' + str(data.ObservationDate.max()))\n# To check every place has only one observation per day\ncheckdup = data.groupby(['Country\/Region','Province\/State','ObservationDate']).count().iloc[:,0]\ncheckdup[checkdup>1]\n# Checking where the duplicates come from\ndata[data['Province\/State'].isin(['Hebei','Gansu']) & (data['ObservationDate'].isin(['2020-03-11','2020-03-12']))]\n# Clean data\ndata = data.drop([4926,4927,5147, 5148]) # March 14 - remove duplicates\ndata.loc[data['Province\/State']=='Macau', 'Country\/Region'] = 'Macau' # March 14 - clean data for Macau and HK\ndata.loc[data['Province\/State']=='Hong Kong', 'Country\/Region'] = 'Hong Kong'\ndata = data.drop(['SNo', 'Last Update'], axis=1)\ndata = data.rename(columns={'Country\/Region': 'Country', 'ObservationDate':'Date'})\n# To check null values\ndata.isnull().sum()\ndaily = data.sort_values(['Date','Country','Province\/State'])\n\"\"\"\nAt first, we separate the cases into three regions, 'Arizona USA', 'Others USA' and 'World':\n\"\"\"\ndef get_place(row):\n    if row['Province\/State'] == 'Arizona':\n        return 'Arizona USA'\n    elif row['Country'] == 'US': \n        return 'Others USA'\n    else: return 'World'\n    \ndaily['segment'] = daily.apply(lambda row: get_place(row), axis=1)\n\"\"\"\n## Latest status update\n\"\"\"\nlatest = daily[daily.Date == daily.Date.max()]\nprint ('Total confirmed cases: %.d' %np.sum(latest['Confirmed']))\nprint ('Total death cases: %.d' %np.sum(latest['Deaths']))\nprint ('Total recovered cases: %.d' %np.sum(latest['Recovered']))\nsegment1 = latest.groupby('segment').sum()\nsegment1['Death Rate'] = segment1['Deaths'] \/ segment1['Confirmed'] * 100\nsegment1['Recovery Rate'] = segment1['Recovered'] \/ segment1['Confirmed'] * 100\nsegment1\n\"\"\"\nFindings:\n- 14 Mar: 12 cases in AZ, 2714 in other states\n- 15 Mar: 13 cases in AZ, 3486 in other states\n- 16 Mar: 18 cases in AZ, 4614 in other states\n- (didn't log in 17 Mar)\n- 18 Mar: 27 cases in AZ, 7759 in other states\n- 19 Mar: 45 cases in AZ, 13635 in other states\n- 20 Mar: 78 cases in AZ, 19023 in other states\n- 23 Mar: 235 cases in AZ, 43432 in other states\n- 30 Mar: 919 cases in AZ, 139967 in other states\n\"\"\"\n# Confirmed Cases USA\n_ = latest.loc[latest.segment=='Others USA',['Province\/State','Confirmed']].sort_values('Province\/State', ascending=True)\nplt.figure(figsize=(9,7))\nsns.barplot('Confirmed', 'Province\/State', data = _)\nplt.title('Top confirmed cases USA ex-Arizona')\nplt.yticks(fontsize=8)\nplt.grid(axis='x')\nplt.show()\n# Death Cases China USA\n_ = latest.loc[latest.segment=='Others USA',['Province\/State','Deaths']].sort_values('Deaths', ascending=False)\n_ = _[_.Deaths>0]\nplt.figure(figsize=(9,7))\nsns.barplot('Deaths', 'Province\/State', data = _)\nplt.title('Top Death cases USA')\nplt.yticks(fontsize=12)\nplt.grid(axis='x')\nplt.show()\n\"\"\"\n* [Insert findings here]\n\"\"\"\n# Confirmed Cases World ex-USA\nworldstat = latest[latest.segment=='World'].groupby('Country').sum()\n_ = worldstat.sort_values('Confirmed', ascending=False).head(15)\nplt.figure(figsize=(9,6))\nsns.barplot(_.Confirmed, _.index)\nplt.title('Top 15 Confirmed cases World ex-USA')\nplt.yticks(fontsize=12)\nplt.grid(axis='x')\nplt.show()\n# Death Cases World ex-USA\n_ = worldstat.sort_values('Deaths', ascending=False)\n_ = _[_.Deaths>=5]\nplt.figure(figsize=(9,6))\nsns.barplot(_.Deaths, _.index)\nplt.title('Top Deaths cases World ex-USA (5 or above)')\nplt.yticks(fontsize=12)\nplt.grid(axis='x')\nplt.show()\n# Compare death rate across countries\n_ = latest.groupby('Country')['Confirmed','Deaths'].sum().reset_index()\n_['Death rate'] = _['Deaths'] \/ _['Confirmed'] * 100\n_ = _.sort_values('Death rate', ascending=False)\ndeath_cty = _[_['Deaths']>=5]\nplt.figure(figsize=(9,6))\nsns.barplot(death_cty['Death rate'], death_cty['Country'])\nplt.title('Death Rate Comparison (>=5 Deaths)')\nplt.yticks(fontsize=12)\nplt.grid(axis='x')\nplt.show()\ndeath_cty\n\"\"\"\nFindings:\n- [Insert findings here]\n\"\"\"\n\"\"\"\n## Evolution of cases\n\"\"\"\nimport matplotlib.dates as mdates\nmonths = mdates.MonthLocator()\nmonths_fmt = mdates.DateFormatter('%b-%e')\n\nconfirm = pd.pivot_table(daily.dropna(subset=['Confirmed']), \n                         index='Date', columns='segment', values='Confirmed', aggfunc=np.sum).fillna(method = 'ffill')\nfig, ax = plt.subplots(figsize=(11,6))\nax.plot(confirm, marker='o')\nplt.title('Confirmed Cases')\nax.legend(confirm.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nax.grid(True)\nplt.show()\n\"\"\"\n[Insert findings here]\n\"\"\"\ndeath = pd.pivot_table(daily.dropna(subset=['Deaths']), \n                         index='Date', columns='segment', values='Deaths', aggfunc=np.sum).fillna(method = 'ffill')\nfig, ax = plt.subplots(figsize=(11,6))\nax.plot(death, marker='o')\nplt.title('Death Cases')\nax.legend(death.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nax.grid(True)\nplt.show()\n\"\"\"\n[Insert findings here]\n\"\"\"\ngood = pd.pivot_table(daily.dropna(subset=['Recovered']), \n                         index='Date', columns='segment', values='Recovered', aggfunc=np.sum).fillna(method = 'ffill')\nfig, ax = plt.subplots(figsize=(11,6))\nax.plot(good, marker='o')\nplt.title('Recovered Cases')\nax.legend(good.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nax.grid(True)\nplt.show()\n# Active case - confirmed minus deaths and recovered\ndaily['Active'] = daily['Confirmed'] - daily['Deaths'] - daily['Recovered']\nactive = pd.pivot_table(daily.dropna(subset=['Active']), \n                         index='Date', columns='segment', values='Active', aggfunc=np.sum).fillna(method = 'ffill')\nfig, ax = plt.subplots(figsize=(11,6))\nplt.plot(active, marker='o')\nplt.title('Active Cases')\nax.legend(active.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nax.grid(True)\nplt.show()\n\"\"\"\n[Insert findings here]\n\"\"\"\n# Global ex-China - Top 10 countries\nc10 = worldstat.sort_values('Confirmed', ascending=False).head(10).index.tolist()\n# Confirmed cases\nc10cases = daily[daily['Country'].isin(c10)]\nconfirm_w = pd.pivot_table(c10cases.dropna(subset=['Confirmed']), index='Date', \n                         columns='Country', values='Confirmed', aggfunc=np.sum).fillna(method='ffill')\nfig, ax = plt.subplots(figsize=(12,7))\nplt.plot(confirm_w[confirm_w.index>'2020-02-01'], marker='o')\nplt.title('Confirmed Cases - Top 10 Countries Outside China')\nax.legend(confirm_w.columns, loc=2)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nplt.grid(True)\nplt.show()\n\"\"\"\n[Insert findings here]\n\"\"\"\n# Death cases\ndeath_w = pd.pivot_table(c10cases.dropna(subset=['Deaths']), index='Date', \n                         columns='Country', values='Deaths', aggfunc=np.sum).fillna(method='ffill')\nfig, ax = plt.subplots(figsize=(12,7))\nplt.plot(death_w[death_w.index>'2020-02-01'], marker='o')\nplt.title('Death Cases - Top 10 Countries Outside China')\nplt.legend(death_w.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nplt.grid(True)\nplt.show()\n\"\"\"\n[Insert findings here]\n\"\"\"\n\"\"\"\n## Rate of Death and Recovery\n\"\"\"\n# Calculate death and recovery rate\n\ndf = confirm.join(death, lsuffix='_confirm', rsuffix='_death')\ndf = df.join(good.add_suffix('_recover'))\ndf['Arizona USA_death_rate'] = df['Arizona USA_death']\/df['Arizona USA_confirm']\ndf['Others USA_death_rate'] = df['Others USA_death']\/df['Others USA_confirm']\ndf['World_death_rate'] = df['World_death']\/df['World_confirm']\ndf['Arizona USA_recover_rate'] = df['Arizona USA_recover']\/df['Arizona USA_confirm']\ndf['Others USA_recover_rate'] = df['Others USA_recover']\/df['Others USA_confirm']\ndf['World_recover_rate'] = df['World_recover']\/df['World_confirm']\ndeath_rate = df[['Arizona USA_death_rate','Others USA_death_rate','World_death_rate']]*100\nfig, ax = plt.subplots(figsize=(11,6))\nplt.plot(death_rate, marker='o')\nplt.title('Death Rate %')\nplt.legend(death.columns)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nplt.grid(True)\nplt.show()\nrecover_rate = df[['Arizona USA_recover_rate','Others USA_recover_rate','World_recover_rate']]*100\nfig, ax = plt.subplots(figsize=(11,6))\nplt.plot(recover_rate, marker='o')\nplt.title('Recovery Rate %')\nplt.legend(good.columns, loc=2, fontsize=12)\nax.xaxis.set_major_locator(plt.MaxNLocator(7))\nax.xaxis.set_major_formatter(months_fmt)\nplt.xticks(rotation=45, fontsize=12)\nplt.grid(True)\nplt.show()\n\"\"\"\nFindings:\n- [Insert findings here]\n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dccca8800cc7ee'}"}
{"id":"7445","text":"\"\"\"\nCREDITABILITY (noun):\n\nAppearance of truth or authenticity:\nbelievability, color, credibility, credibleness, creditableness, plausibility, plausibleness, verisimilitude.\n\nCREDIBILITY\n\nCredibility comprises the objective and subjective components of the believability of a source or message. Credibility dates back to Aristotle theory of Rhetoric. Aristotle defines rhetoric as the ability to see what is possibly persuasive in every situation. \n\nHe divided the means of persuasion into three categories, namely Ethos (the source's credibility), Pathos (the emotional or motivational appeals), and Logos (the logic used to support a claim), which he believed have the capacity to influence the receiver of a message. According to Aristotle, the term \u201cEthos\u201d deals with the character of the speaker. The intent of the speaker is to appear credible.\n\nIn fact, the speaker's ethos is a rhetorical strategy employed by an orator whose purpose is to \"INSPIRE TRUST IN HIS AUDIENCE.\u201d Credibility has two key components: trustworthiness and expertise, which both have objective and subjective components. \n\nTrustworthiness is based more on subjective factors, but can include objective measurements such as established reliability. Expertise can be similarly subjectively perceived, but also includes relatively objective characteristics of the source or message (e.g., credentials, certification or information quality).\n\nSecondary components of credibility include source dynamism (charisma) and physical attractiveness.\n\nhttps:\/\/en.wikipedia.org\/wiki\/Credibility\n\"\"\"\n\"\"\"\n#Even Birds know the Meaning of Creditability\n\n![](https:\/\/thesaurus.plus\/img\/synonyms\/132\/creditability.png)thesaurusplus\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport warnings\nwarnings.filterwarnings(\"ignore\")\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\n\"\"\"\n<font color=\"#EC7063\">ETHOS. The source's credibility. <\/font>\n\n### <b><mark style=\"background-color: #9B59B6\"><font color=\"white\">* Has the applicant sources to pay the loan?   *<\/font><\/mark><\/b>\n\n<font color=\"#EC7063\">PATHOS. The emotional or motivational appeals. <\/font>\n\n### <b><mark style=\"background-color: #9B59B6\"><font color=\"white\">* Has the applicant good motivations to require the loan?   *<\/font><\/mark><\/b>\n\n<font color=\"#EC7063\">LOGOS. The logic used to support a claim. <\/font>\n\n### <b><mark style=\"background-color: #9B59B6\"><font color=\"white\">* Has the applicant convinced the bank that the loan will be paid?   *<\/font><\/mark><\/b>\n\"\"\"\nnRowsRead = 1000 # specify 'None' if want to read whole file\ndataset = pd.read_csv('..\/input\/cusersmarildownloadsgermancsv\/german.csv', delimiter=';', encoding = \"ISO-8859-2\", nrows = nRowsRead)\ndataset.dataframeName = 'german.csv'\nnRow, nCol = dataset.shape\nprint(f'There are {nRow} rows and {nCol} columns')\ndataset.head()\n\"\"\"\nThe predictors that may potentially have any influence on Creditability:\n\nAccount Balance: No account (1), None (No balance) (2), Some Balance (3)\n\nPayment Status: Some Problems (1), Paid Up (2), No Problems (in this bank) (3)\n\nSavings\/Stock Value: None, Below 100 DM, (100, 1000) DM, Above 1000 DM\n\nEmployment Length: Below 1 year (including unemployed), (1, 4), (4, 7), Above 7\n\nSex\/Marital Status: Male Divorced\/Single, Male Married\/Widowed, Female\n\nNo of Credits at this bank: 1, More than 1\n\nGuarantor: None, Yes\n\nConcurrent Credits: Other Banks or Dept Stores, None\n\nForeignWorker variable may be dropped from the study\n\nPurpose of Credit: New car, Used car, Home Related, Other\n\"\"\"\n\"\"\"\n#All script by Baris Cal https:\/\/www.kaggle.com\/bariscal\/portugal-wine-dataset-quality-prediction-w-ml \n\"\"\"\nfrom sklearn import tree\nimport graphviz \nimport os\nimport preprocessing \n\nfrom pandas_profiling import ProfileReport\n\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2, f_classif\nfrom sklearn.model_selection import KFold\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.svm import LinearSVC\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\n\nfrom sklearn.preprocessing import normalize\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.decomposition import PCA\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.naive_bayes import CategoricalNB\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.cluster import KMeans\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom xgboost import XGBClassifier\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV, cross_val_score\nfrom sklearn.model_selection import GridSearchCV\n\n\nfrom sklearn.linear_model import SGDClassifier, LogisticRegression\n\n\nfrom sklearn.neural_network import MLPClassifier\nfrom xgboost import XGBClassifier, XGBRFClassifier\nfrom xgboost import plot_tree, plot_importance\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score, roc_curve\nfrom sklearn import preprocessing\nfrom sklearn.feature_selection import RFE\n\n\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nlist(dataset.columns)\nfeatures = ['Account_Balance',\n 'Duration_of_Credit_monthly',\n 'Payment_Status_of_Previous_Credit',\n 'Purpose',\n 'Credit_Amount',\n 'Value_Savings_Stocks',\n 'Guarantors',\n 'Most_valuable_available_asset',\n 'Age_years',\n 'No_of_Credits_at_this_Bank',\n 'Occupation']\nsns.set_style('darkgrid')\n#sns.pairplot(dataset, hue = 'Creditability')\nmask = np.zeros_like(dataset[features].corr(), dtype=np.bool) \nmask[np.triu_indices_from(mask)] = True \n\nf, ax = plt.subplots(figsize=(16, 12))\nplt.title('Pearson Correlation Matrix',fontsize=25)\n\nsns.set_style('darkgrid')\nsns.heatmap(dataset[features].corr(),linewidths=0.25,vmax=0.7,square=True,cmap=\"BuGn\", #\"BuGn_r\" to reverse \n            linecolor='w',annot=True,annot_kws={\"size\":8},mask=mask,cbar_kws={\"shrink\": .9});\nplt.figure(figsize=(12,8)) \nsns.heatmap(dataset.corr(), annot=True, cmap='Dark2_r', linewidths = 2)\nplt.show()\nplt.figure(figsize=(30,30))\n\nplt.subplot(4,4,1)\nsns.distplot(dataset['Creditability']).set_title('Creditability Interval')\n\nplt.subplot(4,4,2)\nsns.distplot(dataset['Account_Balance']).set_title('Account Balance Interval')\n\nplt.subplot(4,4,3)\nsns.distplot(dataset['Purpose']).set_title('Purpose Interval')\n\nplt.subplot(4,4,4)\nsns.distplot(dataset['Guarantors']).set_title('Guarantors Interval')\n\nplt.subplot(4,4,5)\nsns.distplot(dataset['Most_valuable_available_asset']).set_title('Most valuable available asset Interval')\n\nplt.subplot(4,4,6)\nsns.distplot(dataset['Age_years']).set_title('Age Interval')\n\nplt.subplot(4,4,7)\nsns.distplot(dataset['Occupation']).set_title('Occupation Interval')\n\nplt.subplot(4,4,8)\nsns.distplot(dataset['Value_Savings_Stocks']).set_title('Value Savings & Stocks Interval')\nplt.figure(figsize=(20,15))\nplt.subplot(2,2,1)\nsns.violinplot(x = 'Creditability', y = 'Account_Balance', data = dataset)\nplt.subplot(2,2,2)\nsns.violinplot(x = 'Creditability', y = 'Credit_Amount', data = dataset)\nplt.subplot(2,2,3)\nsns.violinplot(x = 'Creditability', y = 'Occupation', data = dataset)\nplt.subplot(2,2,4)\nsns.violinplot(x = 'Creditability', y = 'Guarantors', data = dataset)\n\"\"\"\n#Apple co-founder says Apple Card algorithm gave wife LOWER CREDIT LIMIT\n\nApple Inc AAPL.O co-founder Steve Wozniak joined in the online debate over accusations of GENDER DISCRIMINATION by the ALGORITHM behind the iPhone maker's credit card, fueling scrutiny of the newly launched Apple Card.\n\nThe criticism started after entrepreneur David Heinemeier Hansson railed against the Apple Card in a series of Twitter posts, saying it gave him 20 times the credit limit his wife received.\n\nApple Card applicants were evaluated independently, according to income and creditworthiness, taking into account factors such as personal credit scores and personal debt.\n\nWozniak said he got 10 times more credit on the card, compared with his wife.\n\nhttps:\/\/www.reuters.com\/article\/us-goldman-sachs-apple\/apple-co-founder-says-apple-card-algorithm-gave-wife-lower-credit-limit-idUKKBN1XL038\n\"\"\"\ndataset[\"Sex_Marital_Status\"].value_counts()\nplt.figure(1, figsize=(10,10))\ndataset['Sex_Marital_Status'].value_counts().plot.pie(autopct=\"%1.1f%%\")\nplt.title ('Sex & Marital Status')\n\"\"\"\n#Sex\/Marital Status: Male Divorced\/Single, Male Married\/Widowed, Female.\n\n#They didn't mentioned which number corresponds to the status. What percent correspond to females if I don't know female number?\n\nhttps:\/\/online.stat.psu.edu\/stat508\/resources\/analysis\/gcd\/gcd.1\n\"\"\"\nfeatures = ['Account_Balance',\n 'Duration_of_Credit_monthly',\n 'Payment_Status_of_Previous_Credit',\n 'Purpose',\n 'Credit_Amount',\n 'Value_Savings_Stocks',\n 'Guarantors',\n 'Most_valuable_available_asset',\n 'Age_years',\n 'No_of_Credits_at_this_Bank',\n 'Occupation']\nlabel = ['Creditability']\n\nX = dataset[features]\ny = dataset[label]\n\"\"\"\n#Attention Below it's NOT 12 it's l2 (lower case L)\n\"\"\"\nX = normalize(X, norm = 'l2')\nprint(X[:3])\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=101) \nX_valid, X_test, y_valid, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)\n\nprint(f'Total # of sample in whole dataset: {len(X)}')\nprint(f'Total # of sample in train dataset: {len(X_train)}')\nprint(f'Total # of sample in validation dataset: {len(X_valid)}')\nprint(f'Total # of sample in test dataset: {len(X_test)}')\n\"\"\"\n#Score of Models\n\"\"\"\n#Scores of Models\nmodels = {\n    'GaussianNB': GaussianNB(),\n    'MultinomialNB': MultinomialNB(),\n    'BernoulliNB': BernoulliNB(),\n    'LogisticRegression': LogisticRegression(),\n    'RandomForestClassifier': RandomForestClassifier(),\n    'SupportVectorMachine': SVC(),\n    'DecisionTreeClassifier': DecisionTreeClassifier(),\n    'KNeighborsClassifier': KNeighborsClassifier(),\n    'GradientBoostingClassifier': GradientBoostingClassifier(),\n    'Stochastic Gradient Descent':  SGDClassifier(max_iter=5000, random_state=0),\n    'Neural Nets': MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5000, 10), random_state=1),\n    'XGBClassifier': XGBClassifier()\n}\n\nmodelNames = [\"GaussianNB\",\"MultinomialNB\",'BernoulliNB','LogisticRegression','RandomForestClassifier','SupportVectorMachine',\n             'DecisionTreeClassifier', 'KNeighborsClassifier','GradientBoostingClassifier',\n             'Stochastic Gradient Descent', 'Neural Nets', 'XGBClassifier']\n\ntrainScores = []\nvalidationScores = []\ntestScores = []\n\nfor m in models:\n  model = models[m]\n  model.fit(X_train, y_train)\n  score = model.score(X_valid, y_valid)\n  #print(f'{m} validation score => {score*100}')\n    \n  print(f'{m}') \n  train_score = model.score(X_train, y_train)\n  print(f'Train score of trained model: {train_score*100}')\n  trainScores.append(train_score*100)\n\n  validation_score = model.score(X_valid, y_valid)\n  print(f'Validation score of trained model: {validation_score*100}')\n  validationScores.append(validation_score*100)\n\n  test_score = model.score(X_test, y_test)\n  print(f'Test score of trained model: {test_score*100}')\n  testScores.append(test_score*100)\n  print(\" \")\n    \n  y_predictions = model.predict(X_test)\n  conf_matrix = confusion_matrix(y_predictions, y_test)\n\n  print(f'Confussion Matrix: \\n{conf_matrix}\\n')\n\n  predictions = model.predict(X_test)\n  cm = confusion_matrix(predictions, y_test)\n\n  tn = conf_matrix[0,0]\n  fp = conf_matrix[0,1]\n  tp = conf_matrix[1,1]\n  fn = conf_matrix[1,0]\n  accuracy  = (tp + tn) \/ (tp + fp + tn + fn)\n  precision = tp \/ (tp + fp)\n  recall    = tp \/ (tp + fn)\n  f1score  = 2 * precision * recall \/ (precision + recall)\n  specificity = tn \/ (tn + fp)\n  print(f'Accuracy : {accuracy}')\n  print(f'Precision: {precision}')\n  print(f'Recall   : {recall}')\n  print(f'F1 score : {f1score}')\n  print(f'Specificity : {specificity}')\n  print(\"\") \n  print(f'Classification Report: \\n{classification_report(predictions, y_test)}\\n')\n  print(\"\")\n   \n  for m in range (1):\n    current = modelNames[m]\n    modelNames.remove(modelNames[m])\n\n  preds = model.predict(X_test)\n  confusion_matr = confusion_matrix(y_test, preds) #normalize = 'true'\n  print(\"############################################################################\")\n  print(\"\")\n  print(\"\")\n  print(\"\")\nplt.figure(figsize=(20,10))\nplt.title('Train - Validation - Test Scores of Models', fontweight='bold', size = 24)\n\nbarWidth = 0.25\n \nbars1 = trainScores\nbars2 = validationScores\nbars3 = testScores\n \nr1 = np.arange(len(bars1))\nr2 = [x + barWidth for x in r1]\nr3 = [x + barWidth for x in r2]\n \nplt.bar(r1, bars1, color='blue', width=barWidth, edgecolor='white', label='train', yerr=0.5,ecolor=\"black\",capsize=10)\nplt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='validation', yerr=0.5,ecolor=\"black\",capsize=10, alpha = .50)\nplt.bar(r3, bars3, color='red', width=barWidth, edgecolor='white', label='test', yerr=0.5,ecolor=\"black\",capsize=10, hatch = '-')\n \nmodelNames = [\"GaussianNB\",\"MultinomialNB\",'BernoulliNB','LogisticRegression','RandomForestClassifier','SupportVectorMachine',\n             'DecisionTreeClassifier', 'KNeighborsClassifier','GradientBoostingClassifier',\n             'Stochastic Gradient Descent', 'Neural Nets', 'XGBClassifier']\n    \nplt.xlabel('Algorithms', fontweight='bold', size = 24)\nplt.ylabel('Scores', fontweight='bold', size = 24)\nplt.xticks([r + barWidth for r in range(len(bars1))], modelNames, rotation = 75)\n \nplt.legend()\nplt.show()\nfor i in range(12):\n    print(f'Accuracy of {modelNames[i]} -----> {testScores[i]}')\n\"\"\"\nThe best result was from XGBClassifier with 75.15 accuracy score.\n\nThat phrase below I simply didn't get. Maybe I'll ask Baris Cal.\n\n\"We had 7 labels to predict. Now, i will decrease this 7 labels to 3 and try to increase accuracy scores.\"\n\"\"\"\ndataset['Creditability'].value_counts()\n\"\"\"\nImproving Results\n\nDataset includes 'Creditability' attribute. This atribute values are between 0 and 1. So I think I don't even have to decrease the value interval.\n\n\n\nOn the original Dataset (Portugal Wines) the attribute \"quality\" values are between 0 and 9\n\n\"For increase the accuracy of results, I have done decrease the value interval. So I created an attribute. According to these attribute, if 'quality' value of sample is lower than 5, it will be classified as 'low', if 6 or 7 it will be in 'medium' range and the others will be 'high' quality wines. For use this new data in machine learning algorithms, I made this values integers. 'low' quality is 0, 'medium' quality is 1 and 'high' quality is 2. I not gonna use 'quality_value' attribute in my application. I did it to see how did I obtain that values.\"\nhttps:\/\/www.kaggle.com\/bariscal\/portugal-wine-dataset-quality-prediction-w-ml\n\"\"\"\n#Code by Olga Belitskaya https:\/\/www.kaggle.com\/olgabelitskaya\/sequential-data\/comments\nfrom IPython.display import display,HTML\nc1,c2,f1,f2,fs1,fs2=\\\n'#eb3434','#eb3446','Akronim','Smokum',30,15\ndef dhtml(string,fontcolor=c1,font=f1,fontsize=fs1):\n    display(HTML(\"\"\"<style>\n    @import 'https:\/\/fonts.googleapis.com\/css?family=\"\"\"\\\n    +font+\"\"\"&effect=3d-float';<\/style>\n    <h1 class='font-effect-3d-float' style='font-family:\"\"\"+\\\n    font+\"\"\"; color:\"\"\"+fontcolor+\"\"\"; font-size:\"\"\"+\\\n    str(fontsize)+\"\"\"px;'>%s<\/h1>\"\"\"%string))\n    \n    \ndhtml('Be patient. Mar\u00edlia Prata, @mpwolke was Here')","meta":"{'source': 'AI4Code', 'id': '0dd8ff1e3366dc'}"}
{"id":"51849","text":"import pandas as pd\nimport numpy as np\nimport plotly.express as px\nfrom sklearn.metrics import r2_score\nimport os\nimport glob\nfrom tqdm import tqdm\nimport lightgbm as lgbm\nfrom sklearn.model_selection import KFold\nfrom sklearn.linear_model import Ridge\n\nfrom joblib import Parallel, delayed\nclass CFG:\n    data_dir = '..\/input\/optiver-realized-volatility-prediction\/'\n    nfolds = 5\n\"\"\"\n# Functions\n\"\"\"\ndef log_return(list_stock_prices):\n    return np.log(list_stock_prices).diff() \n\ndef rv(series_log_return):\n    return np.sqrt(np.sum(series_log_return**2))\n\n\ndef rv2(series_log_return):\n    return np.sqrt(np.sum(series_log_return**2))\n\n\n# taken from https:\/\/www.kaggle.com\/yus002\/realized-volatility-prediction-lgbm-train\ndef my_metrics(y_true, y_pred):\n    return np.sqrt(np.mean(np.square((y_true - y_pred) \/ y_true)))\ndef rmspe(y_true, y_pred):  \n    output = my_metrics(y_true, y_pred)\n    return 'rmspe', output, False\n\n\"\"\"\nAdapted from https:\/\/www.kaggle.com\/konradb\/naive-optuna-tuned-stacked-ensemble-model\n\"\"\"\ndef get_stock_stat(stock_id : int, dataType = 'train'):\n    \n    df_book = pd.read_parquet(f'..\/input\/optiver-realized-volatility-prediction\/book_{dataType}.parquet\/stock_id={stock_id}\/')\n    df_book.sort_values(by=['time_id', 'seconds_in_bucket'])\n\n    # compute different vwap\n    df_book['wap1'] = (df_book['bid_price1'] * df_book['ask_size1'] + df_book['ask_price1'] * df_book['bid_size1']) \/ (\n                            df_book['bid_size1']+ df_book['ask_size1'])\n\n    # wap2\n    a = df_book['bid_price2'] * df_book['ask_size2'] + df_book['ask_price2'] * df_book['bid_size2']\n    b = df_book['bid_size2']+ df_book['ask_size2']\n    df_book['wap2'] = a\/b\n    \n    # wap3\n    a1 = df_book['bid_price1'] * df_book['ask_size1'] + df_book['ask_price1'] * df_book['bid_size1']\n    a2 = df_book['bid_price2'] * df_book['ask_size2'] + df_book['ask_price2'] * df_book['bid_size2']\n    b = df_book['bid_size1'] + df_book['ask_size1'] + df_book['bid_size2']+ df_book['ask_size2']    \n    df_book['wap3'] = (a1 + a2)\/ b\n    \n    # wap4 \n    a = (df_book['bid_price1'] * df_book['ask_size1'] + df_book['ask_price1'] * df_book['bid_size1']) \/ (\n                                       df_book['bid_size1']+ df_book['ask_size1'])\n    b = (df_book['bid_price2'] * df_book['ask_size2'] + df_book['ask_price2'] * df_book['bid_size2']) \/ (\n                                       df_book['bid_size2']+ df_book['ask_size2'])\n    df_book['wap4'] = (a + b) \/ 2\n                    \n    df_book['vol_wap1'] = (df_book.groupby(by = ['time_id'])['wap1'].apply(log_return).reset_index(drop = True).fillna(0))\n    df_book['vol_wap2'] = (df_book.groupby(by = ['time_id'])['wap2'].apply(log_return).reset_index(drop = True).fillna(0))\n    df_book['vol_wap3'] = (df_book.groupby(by = ['time_id'])['wap3'].apply(log_return).reset_index(drop = True).fillna(0))\n    df_book['vol_wap4'] = (df_book.groupby(by = ['time_id'])['wap4'].apply(log_return).reset_index(drop = True).fillna(0))\n                \n        \n    df_book['bas'] = (df_book[['ask_price1', 'ask_price2']].min(axis = 1)\n                                \/ df_book[['bid_price1', 'bid_price2']].max(axis = 1) - 1)                               \n\n    # different spreads\n    df_book['h_spread_l1'] = df_book['ask_price1'] - df_book['bid_price1']\n    df_book['h_spread_l2'] = df_book['ask_price2'] - df_book['bid_price2']\n    df_book['v_spread_b'] = df_book['bid_price1'] - df_book['bid_price2']\n    df_book['v_spread_a'] = df_book['ask_price1'] - df_book['bid_price2']\n    \n    # attach volatitilies based on different VWAPs\n    stock_stat = pd.merge(\n        df_book.groupby(by = ['time_id'])['vol_wap1'].agg(rv).reset_index(),\n        df_book.groupby(by = ['time_id'], as_index = False)['bas'].mean(),\n        on = ['time_id'], how = 'left'\n    )\n    \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['vol_wap2'].agg(rv).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )\n    \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['vol_wap3'].agg(rv).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )\n        \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['vol_wap4'].agg(rv).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )     \n    \n    # spread summaries\n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['h_spread_l1'].agg(max).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )     \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['h_spread_l2'].agg(max).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )     \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['v_spread_b'].agg(max).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )   \n    stock_stat = pd.merge( df_book.groupby(by = ['time_id'])['v_spread_a'].agg(max).reset_index(),\n        stock_stat, on = ['time_id'], how = 'left'\n    )   \n        \n    stock_stat['stock_id'] = stock_id\n    return stock_stat\n\n\ndef get_dataSet(stock_ids : list, dataType = 'train'):\n\n    stock_stat = Parallel(n_jobs=-1)(\n        delayed(get_stock_stat)(stock_id, dataType) \n        for stock_id in stock_ids\n    )    \n    stock_stat_df = pd.concat(stock_stat, ignore_index = True)\n    return stock_stat_df\n\"\"\"\n# Data\n\"\"\"\ntrain = pd.read_csv(CFG.data_dir + 'train.csv')\ntrain.loc[train.stock_id == 0].head(3)\n%%time\ntrain_stock_stat_df = get_dataSet(stock_ids = train['stock_id'].unique(), dataType = 'train')\ntrain_dataSet = pd.merge(train, train_stock_stat_df, on = ['stock_id', 'time_id'], how = 'left')\n%%time\n\ntest = pd.read_csv('..\/input\/optiver-realized-volatility-prediction\/test.csv')\n\ntest_stock_stat_df = get_dataSet(stock_ids = test['stock_id'].unique(), dataType = 'test')\ntest_dataSet = pd.merge(test, test_stock_stat_df, on = ['stock_id', 'time_id'], how = 'left')\n\n\"\"\"\n# Model\n\n\"\"\"\ncovariates = [f for f in train_dataSet.columns if f not in ['time_id', 'target']]\n# taken from https:\/\/www.kaggle.com\/yus002\/realized-volatility-prediction-lgbm-train\ndef my_metrics(y_true, y_pred):\n    return np.sqrt(np.mean(np.square((y_true - y_pred) \/ y_true)))\ndef rmspe(y_true, y_pred):  \n    output = my_metrics(y_true, y_pred)\n    return 'rmspe', output, False\nprval = np.zeros((train_dataSet.shape[0],1))\nprfull = np.zeros((test_dataSet.shape[0],1))\n\nxdat = train_dataSet[covariates].copy()\nydat = train_dataSet['target'].copy()\nxtest = test_dataSet[covariates].copy()\n\nparams = {'metric': 'rmse','reg_alpha': 0.9,  'reg_lambda': 5.61, \n          'num_leaves': 56, 'learning_rate': 0.08, \n          'max_depth': 5, 'n_estimators': 1000, 'min_child_weight': 0.11, \n          'subsample': 0.7, 'colsample_bytree': 0.8,  'min_child_samples': 28}\n\nkf = KFold(n_splits= CFG.nfolds, shuffle = True, random_state = 42)\nfor (ii, (id0, id1)) in enumerate(kf.split(train_dataSet)):\n    x0, x1 = xdat.loc[id0], xdat.loc[id1]\n    y0, y1 = ydat.loc[id0], ydat.loc[id1]\n    \n    model = lgbm.LGBMRegressor(**params)\n    model.fit(x0, y0, eval_set=[(x0, y0), (x1, y1)], eval_metric = rmspe,\n              early_stopping_rounds= 50,  verbose= 250)\n    prval[id1,0] = model.predict(x1)\n    prfull[:,0] += model.predict(xtest)\/CFG.nfolds\n    \ndel x0,x1,y0,y1,id0,id1\nlgbm.plot_importance(model, max_num_features= 25)\n\n# feeding prval and ydat directly into the metric crashes the script due to memory consumption,\n# and I don't have the energy to fix it atm. \n\n# del train_dataSet\nxref = pd.DataFrame()\nxref['ydat'] = ydat\nxref['prval'] = prval\ndel xdat, ydat\n\nR2 = round(r2_score(y_true = xref['ydat'], y_pred = xref['prval']),3)\na = (xref['ydat'] - xref['prval'])\/xref['ydat']\nRMSPE =  np.round((np.sqrt(np.mean(np.square(a )))) ,4)\nprint(f'Performance of the naive prediction: R2 score: {R2}, RMSPE: {RMSPE}')\n\"\"\"\n# Submission\n\"\"\"\ntest_dataSet['target'] = prfull\ntest_dataSet[['row_id', 'target']].to_csv('submission.csv', index = False)","meta":"{'source': 'AI4Code', 'id': '5f69516de1b80d'}"}
{"id":"22473","text":"\"\"\"\n![](https:\/\/bitcoinist.com\/wp-content\/uploads\/2018\/06\/shutterstock_1018654609.jpg)\n\"\"\"\n\"\"\"\n**Goal of this kernel is to compare NN and ARIMA modelling. We will be predicting Bitcoin prices with help of Bitcoin historical data.**\n\"\"\"\n\"\"\"\n**There are 4 csv files. CSV files for select bitcoin exchanges for the time period of Jan 2012 to July 2018, with minute to minute updates of OHLC (Open, High, Low, Close), Volume in BTC and indicated currency, and weighted bitcoin price. Timestamps are in Unix time. Timestamps without any trades or activity have their data fields forward filled from the last valid time period. If a timestamp is missing, or if there are jumps, this may be because the exchange (or its API) was down, the exchange (or its API) did not exist, or some other unforseen technical error in data reporting or gathering. **\n\ncoincheckJPY_1-min_data_2014-10-31_to_2018-06-27.csv\n\nbitflyerJPY_1-min_data_2017-07-04_to_2018-06-27.csv\n\ncoinbaseUSD_1-min_data_2014-12-01_to_2018-06-27.csv\n\nbitstampUSD_1-min_data_2012-01-01_to_2018-06-27.csv\n\n**All from different Bitcoin exchanges**\n\"\"\"\n\"\"\"\n**RNN** To predict bitcoin prices\n\"\"\"\n# First step, import libraries and then dataset\nimport numpy as np \nimport pandas as pd \nfrom matplotlib import pyplot as plt\n# Import the dataset and encode the date\ndf = pd.read_csv(\"..\/input\/coinbaseUSD_1-min_data_2014-12-01_to_2018-11-11.csv\")\ndf['date'] = pd.to_datetime(df['Timestamp'],unit='s').dt.date\ngroup = df.groupby('date')\nReal_Price = group['Weighted_Price'].mean()\n\"\"\"\nBitcoin predictions are going to be for a month, that is why we need to split the dataset accordingly\n\"\"\"\n# split data\nprediction_days = 30\ndf_train= Real_Price[len(Real_Price)-prediction_days:]\ndf_test= Real_Price[:len(Real_Price)-prediction_days]\n\"\"\"\nSome pre-processing is also necessary:\n\n\"\"\"\n# Data preprocess\ntraining_set = df_train.values\ntraining_set = np.reshape(training_set, (len(training_set), 1))\nfrom sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler()\ntraining_set = sc.fit_transform(training_set)\nX_train = training_set[0:len(training_set)-1]\ny_train = training_set[1:len(training_set)]\nX_train = np.reshape(X_train, (len(X_train), 1, 1))\n\"\"\"\nNow keras  to build the rNN, Long short-term memory!!! LSTM\n\"\"\"\n# Importing the Keras libraries and packages\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\n\n# Initialising the RNN\nregressor = Sequential()\n\n# Adding the input layer and the LSTM layer\nregressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1)))\n\n# Adding the output layer\nregressor.add(Dense(units = 1))\n\n# Compiling the RNN\nregressor.compile(optimizer = 'adam', loss = 'mean_squared_error')\n\n# Fitting the RNN to the Training set\nregressor.fit(X_train, y_train, batch_size = 5, epochs = 100)\n\"\"\"\n**NOTE!!!** Key thing is following and that is why NN COULD \"fail\". WE used values of today to predict the future values. That is not really failure of NN but jsut goes to show that we need to think about what are we \"feeding\" our NN with. Because it can happen that NN will only learn that price will be slightly higher than yesterdays price. Which is true, except when it is not. Than we fail big.\n\"\"\"\ntest_set = df_test.values[1:]\nsc = MinMaxScaler()\ninputs = np.reshape(df_test.values[0:len(df_test)-1], (len(test_set), 1))\ninputs = sc.transform(inputs)\ninputs = np.reshape(inputs, (len(inputs), 1, 1))\npredicted_BTC_price = regressor.predict(inputs)\npredicted_BTC_price = sc.inverse_transform(predicted_BTC_price)\n# Visualising the results\nplt.figure(figsize=(25,15), dpi=80, facecolor='w', edgecolor='k')\nax = plt.gca()  \nplt.plot(test_set, color = 'red', label = 'Real BTC Price')\nplt.plot(predicted_BTC_price, color = 'blue', label = 'Predicted BTC Price')\nplt.title('BTC Price Prediction', fontsize=40)\ndf_test = df_test.reset_index()\nx=df_test.index\nlabels = df_test['date']\nplt.xticks(x, labels, rotation = 'vertical')\nfor tick in ax.xaxis.get_major_ticks():\n    tick.label1.set_fontsize(18)\nfor tick in ax.yaxis.get_major_ticks():\n    tick.label1.set_fontsize(18)\nplt.xlabel('Time', fontsize=40)\nplt.ylabel('BTC Price(USD)', fontsize=40)\nplt.legend(loc=2, prop={'size': 25})\nplt.show()\n\n\"\"\"\n**ARIMA** Let us first go through theoretical part of ARIMA. (NN should be already familiar, if not visit my other kernels\n\"\"\"\n\"\"\"\nAn **ARIMA** model is a class of statistical models for analyzing and forecasting time series data. ARIMA model is one model for non-stationarity. It assumes that the data becomes stationary after differencing.\n\n**ARIMA** is an acronym that stands for AutoRegressive Integrated Moving Average. It is a generalization of the simpler AutoRegressive Moving Average and adds the notion of integration.\n\n\n\nThese acronyms describe it pretty well:\n1. **AR**: Autoregression. A model that uses the dependent relationship between an observation and some number of lagged observations.\n2.**I**: Integrated. The use of differencing of raw observations (e.g. subtracting an observation from an observation at the previous time step) in order to make the time series stationary.\n3. **MA**: Moving Average. A model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations.\n\n\n\nEach of these components are explicitly specified in the model as a parameter. A standard notation is used of ARIMA(p,d,q) where the parameters are substituted with integer values to quickly indicate the specific ARIMA model being used.\n\nParameters are defined as follows:\n\n1. **p**: The number of lag observations included in the model, also called the lag order.\n2. **d**: The number of times that the raw observations are differenced, also called the degree of differencing.\n3. **q**: The size of the moving average window, also called the order of moving average.\n\n\n\n\"\"\"\n\"\"\"\n**IMPORTANT**\n\nAdopting an ARIMA model for a time series assumes that the underlying process that generated the observations is an ARIMA process. This may seem obvious, but helps to motivate the need to confirm the assumptions of the model in the raw observations and in the residual errors of forecasts from the model.\n\"\"\"\n\"\"\"\nBut how do we check that? And how to de determine the parameters p,d,q in the model?\nFirst of all we need to make sure that the time-series is stationary, thats where differencing comes into place (degree corrects the level of non-stationarity if possible) And model parameters can be determined with the Box-Jenkins Method.\n\nBasicaly we have the following situation:\n1. Define the model by calling ARIMA() and passing in the p, d, and q parameters.\n2. The model is prepared on the training data by calling the fit() function.\n3. Predictions can be made by calling the predict() function and specifying the index of the time or times to be predicted.\n\"\"\"\n\"\"\"\nHow does **Box-Jenkins Method** work?\n[https:\/\/machinelearningmastery.com\/gentle-introduction-box-jenkins-method-time-series-forecasting\/](http:\/\/)\n\n\n\"\"\"\n\"\"\"\nLet us start coding\n\"\"\"\n# Import libraries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom scipy import stats\nimport statsmodels.api as sm\nimport warnings\nfrom itertools import product\nfrom datetime import datetime\nwarnings.filterwarnings('ignore')\nplt.style.use('seaborn-poster')\n# Load data\ndf = pd.read_csv(\"..\/input\/coinbaseUSD_1-min_data_2014-12-01_to_2018-11-11.csv\")\ndf.head()\n\"\"\"\nWe need to transform our index into time data and then split the time intervals\n\"\"\"\n# Unix-time to \ndf.Timestamp = pd.to_datetime(df.Timestamp, unit='s')\n\n# Resampling to daily frequency\ndf.index = df.Timestamp\ndf = df.resample('D').mean()\n\n# Resampling to monthly frequency\ndf_month = df.resample('M').mean()\n\n# Resampling to annual frequency\ndf_year = df.resample('A-DEC').mean()\n\n# Resampling to quarterly frequency\ndf_Q = df.resample('Q-DEC').mean()\n\"\"\"\nVisualize the trend\n\"\"\"\n# PLOTS\nfig = plt.figure(figsize=[15, 7])\nplt.suptitle('Bitcoin exchanges, mean USD', fontsize=22)\n\nplt.subplot(221)\nplt.plot(df.Weighted_Price, '-', label='By Days')\nplt.legend()\n\nplt.subplot(222)\nplt.plot(df_month.Weighted_Price, '-', label='By Months')\nplt.legend()\n\nplt.subplot(223)\nplt.plot(df_Q.Weighted_Price, '-', label='By Quarters')\nplt.legend()\n\nplt.subplot(224)\nplt.plot(df_year.Weighted_Price, '-', label='By Years')\nplt.legend()\n\n# plt.tight_layout()\nplt.show()\n\"\"\"\n**Stationarity check and STL-decomposition of the series*** Lower the p value the better. Stationarity is our models main assumption and dickey fuller is just hypothesis test of the unit root test\n\"\"\"\nplt.figure(figsize=[15,7])\nsm.tsa.seasonal_decompose(df_month.Weighted_Price).plot()\nprint(\"Dickey\u2013Fuller test: p=%f\" % sm.tsa.stattools.adfuller(df_month.Weighted_Price)[1])\nplt.show()\n\"\"\"\nObviously not stationary, hence we ought transform our data. First Box-cox transformation then check the test\n\"\"\"\n# Box-Cox Transformations\ndf_month['Weighted_Price_box'], lmbda = stats.boxcox(df_month.Weighted_Price)\nprint(\"Dickey\u2013Fuller test: p=%f\" % sm.tsa.stattools.adfuller(df_month.Weighted_Price)[1])\n\"\"\"\nWe need another transformation. Seasonal differentiation\n\"\"\"\n# Seasonal differentiation\ndf_month['prices_box_diff'] = df_month.Weighted_Price_box - df_month.Weighted_Price_box.shift(12)\nprint(\"Dickey\u2013Fuller test: p=%f\" % sm.tsa.stattools.adfuller(df_month.prices_box_diff[12:])[1])\n\"\"\"\nAgain series is not stationary, finally let us try regular differentiation\n\"\"\"\n# Regular differentiation\ndf_month['prices_box_diff2'] = df_month.prices_box_diff - df_month.prices_box_diff.shift(1)\nplt.figure(figsize=(15,7))\n\n# STL-decomposition\nsm.tsa.seasonal_decompose(df_month.prices_box_diff2[13:]).plot()   \nprint(\"Dickey\u2013Fuller test: p=%f\" % sm.tsa.stattools.adfuller(df_month.prices_box_diff2[13:])[1])\n\nplt.show()\n\"\"\"\nNow we need to make model selection, with help of :\n* Autocorrelation Function (ACF). The plot summarizes the correlation of an observation with lag values. The x-axis shows the lag and the y-axis shows the correlation coefficient between -1 and 1 for negative and positive correlation.\n* Partial Autocorrelation Function (PACF). The plot summarizes the correlations for an observation with lag values that is not accounted for by prior lagged observations.\nWe can get a basic picture of the parameter interval, and using this heuristic we can  with help of AIC- Akaike information criterion decide which are the best p,q,d for ARIMA\n\"\"\"\n# Initial approximation of parameters\nQs = range(0, 2)\nqs = range(0, 3)\nPs = range(0, 3)\nps = range(0, 3)\nD=1\nd=1\nparameters = product(ps, qs, Ps, Qs)\nparameters_list = list(parameters)\nlen(parameters_list)\n\n# Model Selection\nresults = []\nbest_aic = float(\"inf\")\nwarnings.filterwarnings('ignore')\nfor param in parameters_list:\n    try:\n        model=sm.tsa.statespace.SARIMAX(df_month.Weighted_Price_box, order=(param[0], d, param[1]), \n                                        seasonal_order=(param[2], D, param[3], 12)).fit(disp=-1)\n    except ValueError:\n        print('wrong parameters:', param)\n        continue\n    aic = model.aic\n    if aic < best_aic:\n        best_model = model\n        best_aic = aic\n        best_param = param\n    results.append([param, model.aic])\n# Best Models\nresult_table = pd.DataFrame(results)\nresult_table.columns = ['parameters', 'aic']\nprint(result_table.sort_values(by = 'aic', ascending=True).head())\nprint(best_model.summary())\n\"\"\"\nGood, now we can make predictions with our (ARIMA) model:\n\"\"\"\n# Inverse Box-Cox Transformation Function\ndef invboxcox(y,lmbda):\n   if lmbda == 0:\n      return(np.exp(y))\n   else:\n      return(np.exp(np.log(lmbda*y+1)\/lmbda))\n# Prediction\ndf_month2 = df_month[['Weighted_Price']]\ndate_list = [datetime(2017, 6, 30), datetime(2017, 7, 31), datetime(2017, 8, 31), datetime(2017, 9, 30), \n             datetime(2017, 10, 31), datetime(2017, 11, 30), datetime(2017, 12, 31), datetime(2018, 1, 31),\n             datetime(2018, 1, 28)]\nfuture = pd.DataFrame(index=date_list, columns= df_month.columns)\ndf_month2 = pd.concat([df_month2, future])\ndf_month2['forecast'] = invboxcox(best_model.predict(start=0, end=75), lmbda)\nplt.figure(figsize=(15,7))\ndf_month2.Weighted_Price.plot()\ndf_month2.forecast.plot(color='r', ls='--', label='Predicted Weighted_Price')\nplt.legend()\nplt.title('Bitcoin exchanges, by months')\nplt.ylabel('mean USD')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '295b2ba3ace1c9'}"}
{"id":"7958","text":"# 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\n\"\"\"\nPerform data preprocessing on movie_metadata.csv file. (You can download the dataset from the shared datasets folder on Google drive of your class.) Perform the following operations on this dataset:\ni. Importing the libraries required for preprocessing from sklearn.\n\nii. Importing the Dataset from the above link.\n\niii. Use the necessary function to handling the missing data.\n\niv. Perform data visualizations using matplotlib or seaborn libraries.\n\nv. Use the necessary function for handling of categorical data if any.\n\nvi. Splitting the dataset into training and testing datasets\n\nvii. Perform feature Scaling.\n\"\"\"\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom subprocess import check_output\ndata = pd.read_csv('..\/input\/imdb-5000-movie-dataset\/movie_metadata.csv')\nprint(data.shape)\ndata.count()\ndf =data.drop(['gross','budget'],axis=1).dropna(axis=0)\nimport seaborn as sns\nax = plt.subplots(figsize=(15,15)) \nsns.heatmap(data=data.corr(),annot=True)\ndata.loc[data.color == ' Black and White'].title_year.mean()\ndf = pd.concat([df,data.loc[df.index,['gross','budget']]],axis=1)\ndf.head(5)\ndf.reset_index(drop=True,inplace=True)\ndf.columns\nsns.boxplot(x=\"color\", y=\"title_year\", data=df, palette=\"PRGn\")\ncut = pd.cut(df.imdb_score, bins=list(np.arange(1,11)))\n\ncut2 = pd.cut(df.title_year, bins=list(5*(np.arange(380,405))))\n\ncut3 = pd.cut(df.imdb_score, bins=list([0,4,6,7,8,10]))\ndf['imdb_score_bin'] =cut\n\ndf['year_range'] =cut2\ndf['pc_imdb'] = cut3\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ndf['pc_imdb']= le.fit_transform(df['pc_imdb'])\nfig, ax = plt.subplots(figsize=(10,10))\nplt.xticks(rotation=45)\nsns.barplot(df['year_range'],df['budget'],ci=None)\nsns.barplot(df['year_range'],df['budget'],ci=None)\nfig, ax = plt.subplots(figsize=(10,10))\nplt.xticks(rotation=45)\nsns.barplot(df['year_range'],df['budget'],ci=None)\nsns.barplot(df['year_range'],df['gross'],ci=None)\nsns.barplot(df['imdb_score_bin'],df['gross'],ci=None)\nsns.boxplot(data=df,x='imdb_score_bin',y='gross')\nmean_chart = pd.DataFrame(df.groupby(by=['year_range'])['budget'].mean())\nmean_chart = pd.DataFrame(df.groupby(by=['year_range'])['budget'].mean())\n\ndf = pd.merge(df,mean_chart,left_on='year_range',right_index=True)\n\ndf.columns\n\ndf['budget_x'].fillna(df['budget_y'],inplace=True)\ndf['budget_x'].count()\ndf2=df\nfrom sklearn.preprocessing import LabelEncoder\nvar_mod=['imdb_score_bin','year_range']\nle = LabelEncoder()\nfor i in var_mod:\n    df2[i] = le.fit_transform(df2[i])\nfrom sklearn.tree import DecisionTreeRegressor\n\nclf= DecisionTreeRegressor()\n\n#df.budget.fillna(0,inplace =True)\n\nclf.fit(df[df['gross'].notnull()][['imdb_score_bin','year_range']],df['gross'].dropna(axis=0))\n\npred = clf.predict(df[df['gross'].isnull()][['imdb_score_bin','year_range']])\n\ndf[df['gross'].isnull()][['imdb_score_bin','year_range']].index\n\nj=0\nfor i in df[df['gross'].isnull()][['imdb_score_bin','year_range']].index :\n    df['gross'][i] = pred[j]\n    j=j+1\ndf_genre=df['genres'].str.split('|',expand=True).stack().str.get_dummies().sum(level=0)\n\nfig, ax = plt.subplots(figsize=(10,10))\nplt.xticks(rotation=45)\nk=pd.DataFrame(df_genre.sum(),columns=['sum'])\nsns.barplot(y='sum',x=k.index,data=k,orient='v')\ndf['age'] = 2017 - df.title_year\nk=df.groupby(by='director_name',sort=False).director_facebook_likes.mean()\nl=df.groupby(by='director_name',sort=False).imdb_score.sum()\nm=df.groupby(by='director_name',sort=False).age.max()\npd.DataFrame(df['director_name'].value_counts())\ndir_ran = pd.concat([k,l,m],axis=1)\ncol_5 =list(df['director_name'].value_counts().index[:5])\ncol_5\npp = df.loc[(df.director_name == col_5[0])|(df.director_name == col_5[1])|(df.director_name == col_5[2])|(df.director_name == col_5[3])|(df.director_name == col_5[4])]\n\nsns.boxplot(x='director_name',y='imdb_score',data=pp)\nstr_list = [] # empty list to contain columns with strings (words)\nfor colname, colvalue in df.iteritems():\n    if type(colvalue[1]) == str:\n         str_list.append(colname)          \nnum_list = df.columns.difference(str_list)  \nX=df[num_list]\nX.shape\nfrom sklearn.preprocessing import StandardScaler\nX_std = StandardScaler().fit_transform(X)\n\n\nfrom sklearn.decomposition import PCA as sklearnPCA\nsklearn_pca = sklearnPCA(n_components=20)\nY_sklearn = sklearn_pca.fit_transform(X_std)\n\ncum_sum = sklearn_pca.explained_variance_ratio_.cumsum()\n\nsklearn_pca.explained_variance_ratio_[:10].sum()\n\ncum_sum = cum_sum*100\n\nfig, ax = plt.subplots(figsize=(8,8))\nplt.bar(range(20), cum_sum, label='Cumulative _Sum_of_Explained _Varaince', color = 'b',alpha=0.5)\nfrom sklearn.decomposition import PCA as sklearnPCA\nsklearn_pca = sklearnPCA(n_components=3)\nX_reduced  = sklearn_pca.fit_transform(X_std)\nY=df['pc_imdb']\nfrom mpl_toolkits.mplot3d import Axes3D\nplt.clf()\nfig = plt.figure(1, figsize=(8, 6))\nax = Axes3D(fig, elev=-150, azim=110)\nax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=Y,cmap=plt.cm.Paired)\nax.set_title(\"First three PCA directions\")\nax.set_xlabel(\"1st eigenvector\")\nax.w_xaxis.set_ticklabels([])\nax.set_ylabel(\"2nd eigenvector\")\nax.w_yaxis.set_ticklabels([])\nax.set_zlabel(\"3rd eigenvector\")\nax.w_zaxis.set_ticklabels([])\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': '0ec429c513514e'}"}
{"id":"12567","text":"\"\"\"\n<h1>Case - Estat\u00edstica <\/h1>\n<h2> Case M\u00f3dulo 2 - VAI Academy <\/h2>\n\n\n\n\n\n\"\"\"\n\"\"\"\n# Dataset\n<p> Amazon Top 50 Bestselling Books 2009 - 2019 <br>\nhttps:\/\/www.kaggle.com\/sootersaalu\/amazon-top-50-bestselling-books-2009-2019\n<\/p>\n\n\"\"\"\n\"\"\"\nPara a an\u00e1lise dos dados e teste de hip\u00f3teses s\u00e3o utilizadas algumas bibliotecas indicadas abaixo:\n\"\"\"\nimport pandas as pd                                                             #Para se trabalhar com DataFrame\nimport numpy as np                                                              #Opera\u00e7\u00f5es matem\u00e1ticas com arrays\nimport matplotlib.pyplot as plt                                                 #Algumas ferramentas de plotagem de gr\u00e1ficos\nimport seaborn as srn                                                           #Plotagem de gr\u00e1ficos\n#Comando para que os gr\u00e1ficos sejam plotados dentro das c\u00e9lulas do notebook\n%matplotlib inline                                                              \nfrom numpy.random import seed, rand, normal, exponential, binomial, poisson     #Biblioteca para se lidar com algumas ferramentas estat\u00edsticas\nimport random                                                                   #Valor random\nimport scipy.stats as stats                                                     #Ferramentas estat\u00edsticas\nfrom scipy.stats import ttest_ind, normaltest, pearsonr                         #Ferramentas estat\u00edsticas\nsrn.set()\n\"\"\"\nAp\u00f3s a defini\u00e7\u00e3o das bilbiotecas que ser\u00e3o utilizadas na an\u00e1lise, \u00e9 feito o upload dos dados e leitura inicial das primeiras 5 linhas.\n\"\"\"\npath_dados = '..\/input\/amazon-top-50-bestselling-books-2009-2019\/bestsellers with categories.csv'\ndados = pd.read_csv(path_dados)                                           #Leitura do DataFrame\n\ndados.head()                                                                                  #Visualiza\u00e7\u00e3o dos dados\n\"\"\"\nSabe-se de antem\u00e3o que os dados s\u00e3o os 50 livros bestseller dos anos de 2009 a 2019, ou seja, 11 anos, tendo 550 linhas. Al\u00e9m disso, vemos que cada linhas apresenta dados em 7 colunas: \n\n*   'Name' (Nome do Livro)\n*   'Author' (Autor do Livro)\n*    'User Rating' (avalia\u00e7\u00e3o do usu\u00e1rio)\n* 'Reviews\" (n\u00famero de avalia\u00e7\u00f5es)\n* 'Price' (pre\u00e7o do livro)\n* 'Year' (ano em que este livro est\u00e1 como Bestseller), e \n*  'Genre' (o g\u00eanero liter\u00e1rio).\n\"\"\"\n\"\"\"\nUma primeira altera\u00e7\u00f5es que ser\u00e1 feita \u00e9 para que todas as colunas n\u00e3o tenham espa\u00e7os vazios no seu nome, apenas para se utilizar as bilbiotecas de maneira mais f\u00e1cil. Abaixo est\u00e3o os novos nomes das colunas (apenas 'User_Rating' foi alterada).\n\"\"\"\ndados.columns = dados.columns.str.replace(' ', \"_\")\ndados.columns\n\"\"\"\nAgora vamos analisar os dados para identificar quais tipos de vari\u00e1veis apresentam e como est\u00e3o distribu\u00eddos para poder conhecer um pouco mais sobre a an\u00e1lise a ser realizada.\n\"\"\"\n\"\"\"\n# An\u00e1lise Estat\u00edstica dos Dados\n\n\"\"\"\n\"\"\"\nPrimeiramente, havia sido feita uma considera\u00e7\u00e3o que os dados teriam 550 linhas, apresentando os 50 livros da lista de Bestseller durante 11 anos (2009 a 2019), tal pressuposto pode ser testado atrav\u00e9s da avalia\u00e7\u00e3o abaixo, onde tamb\u00e9m temos as 7 colunas citadas anteriormente.\n\"\"\"\ndados.shape\n\"\"\"\nVamos analisar agora cada coluna de dados separadamente e ver quais conclus\u00f5es podem ser retiradas.\n\"\"\"\n\"\"\"\nCome\u00e7ando pela coluna 'Name', podemos ver abaixo que das 550 linhas de livros apresentados nos dados, alguns livros aparecem mais de uma vez pois, agrupando os dados com rela\u00e7\u00e3o aos Nomes dos Livros vemos que tal agrupamento apresenta um 'Lenght' (tamanho) de 351 dados. Al\u00e9m disso, aplicando o m\u00e9todo 'size()' \u00e9 poss\u00edvel identificar a quantidadde de vezes em que tal livro aparece como Bestseller na Lista.\n\"\"\"\ndados.groupby('Name').size()\n\"\"\"\nPartindo para a coluna 'Author' vemos novamente que o n\u00famero de autores na lista de Bestseller ('Lenght': 248) \u00e9 menor do que o n\u00famero de linhas de dados (550), isso j\u00e1 era esperado considerando que h\u00e1 livros que aparecem mais de uma vez, por\u00e9m, a surpresa aqui \u00e9 que o n\u00famero de autores diferentes (248) \u00e9 inferior ao n\u00famero de Livros diferentes (351), ou seja, tais autores escreveram mais de um Bestseller. Tal dado pode ser provado aplicando a fun\u00e7\u00e3o 'size()' onde temos a informa\u00e7\u00f5es de quantas vezes o autor apareceu na lista.\n\"\"\"\ndados.groupby('Author').size()\n\"\"\"\nAs pr\u00f3ximas colunas s\u00e3o valores num\u00e9ricos que podem ser analisados atrav\u00e9s da fun\u00e7\u00e3o 'describe()', como mostrado abaixo. Podemos ver que as avalia\u00e7\u00f5es dos usu\u00e1rios variam de 3.3 a 4.9; que a vari\u00e1vel que tem maior varia\u00e7\u00e3o de valores \u00e9 a de 'Reviews', apresentando valores bem altos; a coluna 'Price' variando de 0 a 105 e o 'Year' que como esperado varia de 2009 a 2019.\n\"\"\"\ndados[['User_Rating','Reviews','Price','Year']].describe()\n\"\"\"\nQuanto aos reviews podemos realizar outra an\u00e1lise, pegando o livro 'Wonder' que, segundo a an\u00e1lise de nomes de livros, apareceu 5 vezes nos dados, vemos que o n\u00famero de Reviews permanece o mesmo para todas as vezes que ele aparece, isso pois os valores de 'Reviews' representa o n\u00famero de reviews escritas no site no dia da coleta de dados, assim \u00e9 um valor total para cada livro. Podemos ver tamb\u00e9m que o valor de User_Rating tamb\u00e9m apresenta a mesma an\u00e1lise, n\u00e3o mudando com os anos e o 'Price' tamb\u00e9m \u00e9 um valor constante.\n\"\"\"\ndados.query('Name == \"Wonder\"')\n\"\"\"\nPor \u00faltimo \u00e9 poss\u00edvel analisar a coluna 'Genre' que apresenta apenas dois valores poss\u00edveis: 'Fiction' e 'Non Fiction', o n\u00famero de vezes com que esses valores aparecem nos dados est\u00e1 mostrada abaixo e \u00e9 poss\u00edvel ver que todos os livros est\u00e3o classificados nessas categorias (240 + 310 = 550).\n\"\"\"\ndados.groupby('Genre').size()\n\"\"\"\n## Primeiras conclus\u00f5es \n\nDepois da an\u00e1lise inicial dos dados \u00e9 poss\u00edvel listar algumas caracter\u00edsticas de tal DataFrame.\n\n\n\n*   Os livros podem aparecer nos dados mais de uma vez em anos diferentes.\n*   Existem autores nessa lista que apresentam mais de um livro Bestseller\n*   Al\u00e9m disso, as reviews representam os valores totais para aquele livro, independente do ano, assim como os valores de Price e User_Rating tamb\u00e9m n\u00e3o muda para livros que se repetem.\n\n\n\"\"\"\n\"\"\"\n# Hip\u00f3teses\n\n\n\"\"\"\n\"\"\"\nAp\u00f3s a an\u00e1lise descritiva dos dados ser\u00e1 analisado, inicialmente, as hip\u00f3teses propostas pelo cliente que est\u00e3o listadas abaixo.\n\n1.   Desde o seu in\u00edcio, a VBooks teve como foco vender e estocar livros de fic\u00e7\u00e3o, assumindo como hip\u00f3tese que eram os preferidos pelos consumidores. Entretanto, nos \u00faltimos anos foi percebida uma poss\u00edvel mudan\u00e7a de comportamento: mais consumidores estariam buscando por livros de n\u00e3o-fic\u00e7\u00e3o, indicando uma poss\u00edvel mudan\u00e7a de prefer\u00eancias dos leitores em geral.\n\n2.   Outra hip\u00f3tese trazida pelos donos da empresa \u00e9 a diversifica\u00e7\u00e3o de livros na lista de bestsellers ao longo dos anos, de forma que os livros estariam ficando menos tempo na lista de bestsellers com o passar do tempo. \n\n3.   Por fim, a alta dire\u00e7\u00e3o acredita que as notas m\u00e9dias dos livros possuem maior influ\u00eancia na quantidade de vendas e tempo na lista de bestsellers do que os seus pre\u00e7os.\n\nPara a an\u00e1lise de cada um dos t\u00f3picos ser\u00e1 feito uma limpeza dos dados para a an\u00e1lise apenas das vari\u00e1veis necess\u00e1rias, a apresenta\u00e7\u00e3o gr\u00e1fica das vari\u00e1veis propostas e depois testes das hip\u00f3teses buscando alguma correla\u00e7\u00e3o que leva a hip\u00f3tese a ser descartada ou n\u00e3o.\n\"\"\"\n\"\"\"\n## Hip\u00f3tese 1\n\nDesde o seu in\u00edcio, a VBooks teve como foco vender e estocar livros de fic\u00e7\u00e3o, assumindo como hip\u00f3tese que eram os preferidos pelos consumidores. Entretanto, nos \u00faltimos anos foi percebida uma poss\u00edvel mudan\u00e7a de comportamento: mais consumidores estariam buscando por livros de n\u00e3o-fic\u00e7\u00e3o, indicando uma poss\u00edvel mudan\u00e7a de prefer\u00eancias dos leitores em geral.\n\n\"\"\"\n\"\"\"\nFazendo primeiramente uma an\u00e1lise do total de livros dentro das duas categorias temos os n\u00fameros abaixo. Onde vemos que ao longo dos 11 anos propostos pelos dados, h\u00e1 240 livros de Ficc\u00e7\u00e3o e 310 de N\u00e3o-Fic\u00e7\u00e3o. Mas ainda precisamos de mais informa\u00e7\u00f5es sobre isso para tirarmos conclus\u00f5es.\n\"\"\"\npd.crosstab(index=dados.Genre, columns='count')\n\"\"\"\nVamos analisar como o g\u00eanero dos livros s\u00e3o alterados ao longo do tempo. Para isso se levar\u00e1 em conta apenas as colunas 'Year' e 'Genre'. Atrav\u00e9s da tabela abaixo \u00e9 poss\u00edvel ver, numericamente, a quantidade de livros 'Fiction' e 'Non Fiction' de acordo com o ano, olhando apenas a tabela n\u00e3o \u00e9 poss\u00edvel tirar muitas conclus\u00f5es, apenas que em todos anos temos livros das duas categorias, vamos olhar graficamente.\n\"\"\"\nGenre_Year = pd.crosstab(index=dados.Genre, columns=dados.Year, margins=True)\nGenre_Year\n\"\"\"\nAtrav\u00e9s do tra\u00e7ado do gr\u00e1fico \u00e9 poss\u00edvel perceber que a hip\u00f3tese da VBooks de que os leitores tinham uma prefer\u00eancia por livros de fic\u00e7\u00e3o e de havia uma mudan\u00e7a ao longo do tempo tem um contraste importante com os dados. Aqui indica-se de que durante os anos de 2009 a 2019, com excess\u00e3o de 2014, os leitores preferiram sempre os livros de N\u00e3o Fic\u00e7\u00e3o. Pelo gr\u00e1fico pode perceber-se tamb\u00e9m que, com excess\u00e3o do ano de 2014, esses valores permaneceram em uma faixa de valores caracter\u00edstica. Vamos investigar.\n\"\"\"\nsrn.lineplot(y=Genre_Year.iloc[1,:11].values, x=Genre_Year.columns[:11].values, label='Non Fiction')\nsrn.lineplot(y=Genre_Year.iloc[0,:11].values, x=Genre_Year.columns[:11].values, label='Fiction', color='red')\n\"\"\"\nAqui, olhando a distribui\u00e7\u00e3o dos valores pela fun\u00e7\u00e3o 'describe()', vemos que, pela m\u00e9dia, o n\u00famero de livros de N\u00e3o-Fic\u00e7\u00e3o (28.2) foi superior aos de Fic\u00e7\u00e3o (21.8), sendo que os dois apresentam um valor de vari\u00e2ncia bem pr\u00f3xima. Mas ser\u00e1 que houve uma mudan\u00e7a nessa tend\u00eancia ao longo do tempo, como \u00e9 apresentado pela hip\u00f3tese?\n\"\"\"\nGenre_Year.iloc[:,:11].T.describe().T\n\"\"\"\nPara isso vamos utilzar a mesma tabela, por\u00e9m normalizada.\n\"\"\"\nGenre_Year_NORM = pd.crosstab(index=dados.Genre, columns=dados.Year, margins=True, normalize='columns')\nGenre_Year_NORM\n\"\"\"\nAqui \u00e9 realizado o teste de Hip\u00f3tese de Pearson entre a quantidade normalizada de livros de N\u00e3o-Fic\u00e7\u00e3o em cada ano em rela\u00e7\u00e3o ao ano. \n\"\"\"\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre a quantidade de livros de N\u00e3o Fic\u00e7\u00e3o por g\u00eanero e o ano\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = Genre_Year_NORM.iloc[1,:11].values\ndata2 = Genre_Year_NORM.columns[:11].values\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nif p < alpha:\n    print(\"Rejeitamos a hip\u00f3tese nula.\")\n    print(\"Conclu\u00edmos que existe uma rela\u00e7\u00e3o linear entre as popula\u00e7\u00f5es das amostras\")\nelse:\n    print(\"N\u00e3o podemos rejeitar a hip\u00f3tese nula.\")\n    print(\"Conclu\u00edmos que a correla\u00e7\u00e3o n\u00e3o \u00e9 estatisticamente significativa. Ou conclu\u00edmos que n\u00e3o existe uma correla\u00e7\u00e3o linear significativa.\")\n\nprint(\"valor-p: \", p)\nprint(\"alpha:   \", alpha)\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n\"\"\"\n### Conclus\u00e3o\n\"\"\"\n\"\"\"\nVemos que o coeficiente de correla\u00e7\u00e3o obtido (0.167) n\u00e3o \u00e9 suficiente para que afirme-se que h\u00e1 um aumento de livros de N\u00e3o-Fic\u00e7\u00e3o durante os 11 anos de an\u00e1lise dos dados. Por\u00e9m, como foi comprovado anteriormente, a quantidade m\u00e9dia de livros de N\u00e3o Fic\u00e7\u00e3o em rela\u00e7\u00e3o aos de Fic\u00e7\u00e3o ao longo do tempo \u00e9 sempre superior, ou seja, a Livraria VBooks deveria sim diversificar sua estante com a adi\u00e7\u00e3o de livros de N\u00e3o Ficc\u00e7\u00e3o, sendo essa uma \u00f3tima oportunidade de aumentar o Lucro da Livraria visto que esses livros tem uma aten\u00e7\u00e3o superior aos de Fic\u00e7\u00e3o segundo a an\u00e1lise da lista de Bestsellers.\n\"\"\"\n\"\"\"\n## Hip\u00f3tese 2\n\nOutra hip\u00f3tese trazida pelos donos da empresa \u00e9 a diversifica\u00e7\u00e3o de livros na lista de bestsellers ao longo dos anos, de forma que os livros estariam ficando menos tempo na lista de bestsellers com o passar do tempo. \n\"\"\"\n\"\"\"\nPara isso vamos analisar os livros que apareceram na lista de Bestsellers, vemos abaixo que temos 351 livros diferentes que aparecem entre os 50 livros Bestsellers entre os anos de 2009 e 2019.\n\"\"\"\ndados.Name.unique().shape\n\"\"\"\nEntre esse 351 livros \u00e9 poss\u00edvel saber quantas vezes eles aparecem na lista, ou seja, isso representa quantos anos eles permaneceram na lista dos 50 bestsellers. Aqui est\u00e3o os 5 livos que ficaram mais tempo durante os 11 anos de an\u00e1lise. Pode-se, tamb\u00e9m, consultar os anos em que cada ano permaneceu na lista.\n\"\"\"\ndados.Name.value_counts(ascending=False).head()\ndados.query('Name == \"Publication Manual of the American Psychological Association, 6th Edition\"').Year.unique()\ndados.query('Name == \"StrengthsFinder 2.0\"').Year.unique()\n\"\"\"\nPara analisar os livros e quanto tempo eles ficam dentro so bestsellers ao longo do tempo, montou-se um novo DataFrame que apresenta como colunas:\n\n*    Livro (nome do livro)\n*    Anos de Bestseller (quantidade de anos em que ficou como Bestseller\n*    1\u00ba ano de Bestseller\n\nAqui temos novamente os primeiros 5 livros com mais anos na lista dos Bestsellers.\n\"\"\"\nlivros_anos = pd.DataFrame({'Livro':dados.groupby(\"Name\").Year.count().index,\n                            'Anos de Bestseller':dados.groupby(\"Name\").Year.count().values[:],\n                            '1\u00ba ano de Bestseller':dados.groupby(\"Name\").Year.min().values[:]})\nlivros_anos = livros_anos.sort_values(by='Anos de Bestseller',ascending=False)\nlivros_anos.head()\n\"\"\"\nVamos analisar estat\u00edsticamente esse DataFrame, vemos que em m\u00e9dia os anos ficam 1.5 anos como Bestseller, tendo uma varia\u00e7\u00e3o muito pequena (std) indicando que at\u00e9 o 3\u00ba quartil o valor chega apenas at\u00e9 2, ou seja, os livros que ficam mais de 2 anos como Bestseller representam apenas 25% dos livros totais analisados durante os 11 anos. O que n\u00e3o se sabe \u00e9 se essa tend\u00eancia aumentou ou diminuiu ao longo do tempo, como pede a hip\u00f3tese.\n\"\"\"\nlivros_anos.describe()\n\"\"\"\nVamos agora ver graficamente como a quantidade de anos de Bestseller se altera conforme o primeiro ano do livro como Bestseller. Olhando erroneamente o gr\u00e1fico at\u00e9 pode-se parecer que livros lan\u00e7ados mais pr\u00f3ximo de 2019 tiveram uma queda quanto a anos de Bestseller, mas vale lembrar que os dados analisados apenas apresentam os livros que estiveram dentre os Bestsellers durante os 11 anos, ou seja, n\u00e3o se sabe se os livros que estavam na lista em 2019, por exemplo, permaneceram na lista em 2020 e assim suscetivamente, assim tal gr\u00e1fico n\u00e3o nos traz nenhuma informa\u00e7\u00e3o nova.\n\"\"\"\nsrn.lineplot(data=livros_anos, x='1\u00ba ano de Bestseller', y='Anos de Bestseller')\n\"\"\"\nPara que tal an\u00e1lise do n\u00famero de anos em Bestseller ao longo do tempo pode ser feita, pode-se utilizar v\u00e1rias ferramentas estat\u00edsticas, vamos investigar a mediana e a moda. Vemos que tanto utilizando a mediana quanto a moda o valor para todos os anos \u00e9 de 1, ou seja, pode-se dizer que o mais comum \u00e9 os livros permanecerem apenas 1 ano como Bestseller.\n\"\"\"\nlivros_anos.groupby('1\u00ba ano de Bestseller')['Anos de Bestseller'].agg(pd.Series.median)\nlivros_anos.groupby('1\u00ba ano de Bestseller')['Anos de Bestseller'].agg(pd.Series.mode)\n\"\"\"\nMas j\u00e1 vimos que para que isso pode mudar para o 3\u00ba quartil dos dados.\n\nUm m\u00e9todo para se investigar seria considerar qual a probabilidade de um livro que est\u00e1 na lista de Bestseller em um determinado ano estar ainda nessa lista no pr\u00f3ximo ano. Para isso \u00e9 preciso comparar a lista de livros entre os anos e ver quantos se mant\u00e9m.\n\"\"\"\nlista_anos = [2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]\nlista_rel = []\nfor ano in lista_anos[:-1]:\n  count=0\n  lista_a =[]\n  for i in range(50):\n    for j in range(50):\n      if (dados[dados['Year']==ano]['Name'].iloc[i] == dados[dados['Year']==ano+1]['Name'].iloc[j]):\n          count += 1\n  lista_a = [ano+1, count]\n  lista_rel.append(lista_a)\nprint(lista_rel)\n\"\"\"\nAqui obtemos uma lista que, por exemplo, no primeiro elemento fala que 10 livros que estavam no Bestseller em 2009 permaneceram nele em 2010 e assim suscetivamente. Dividindo tais n\u00fameros por 50 (total de livros em cada lista por ano) temos a probabilidade de um livro permanecer na lista de Bestseller.\n\"\"\"\nfor i in range(10):\n  lista_rel[i][1] = lista_rel[i][1]\/50\nprint(lista_rel)\nprob_permanecer = pd.DataFrame(columns=['Probabilidade de ficar Bestseller', 'Ano'])\nprob_permanecer['Ano'] = [2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]\nlista=[]\nfor i in range(10):\n  lista.append(lista_rel[i][1])\nprob_permanecer['Probabilidade de ficar Bestseller'] = lista\nprob_permanecer\n\"\"\"\nAssim obtemos um dataframe com o ano e o valor normalizado de livros que permaneceram do ano anterior, plotando isso obtemos o gr\u00e1fico abaixo em que vemos que o valor n\u00e3o se alterou muito ao longo do tempo, o que \u00e9 um indicativo de que a hip\u00f3tese 2 pode estar errada.\n\"\"\"\nsrn.lineplot(data=prob_permanecer, x='Ano', y='Probabilidade de ficar Bestseller')\n\"\"\"\nVamos ver se ao longo do tempo essa probabilidade subiu ou caiu.\n\"\"\"\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre permanecer como Bestseller e ano:\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = prob_permanecer['Ano']\ndata2 = prob_permanecer['Probabilidade de ficar Bestseller']\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nif p < alpha:\n    print(\"Rejeitamos a hip\u00f3tese nula.\")\n    print(\"Conclu\u00edmos que existe uma rela\u00e7\u00e3o linear entre as popula\u00e7\u00f5es das amostras\")\nelse:\n    print(\"N\u00e3o podemos rejeitar a hip\u00f3tese nula.\")\n    print(\"Conclu\u00edmos que a correla\u00e7\u00e3o n\u00e3o \u00e9 estatisticamente significativa. Ou conclu\u00edmos que n\u00e3o existe uma correla\u00e7\u00e3o linear significativa entre x e y na popula\u00e7\u00e3o\")\n\nprint(\"valor-p: \", p)\nprint(\"alpha:   \", alpha)\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n\"\"\"\n### Conclus\u00e3o\n\"\"\"\n\"\"\"\nN\u00e3o foi suficiente para que uma correla\u00e7\u00e3o entre os dois fatores fosse obtida, como j\u00e1 foi falado, a maioria dos livros (75%) fica apenas um ano como Bestseller.\n\"\"\"\n\"\"\"\n## Hip\u00f3tese 3:\n\nPor fim, a alta dire\u00e7\u00e3o acredita que as notas m\u00e9dias dos livros possuem maior influ\u00eancia na quantidade de vendas e tempo na lista de bestsellers do que os seus pre\u00e7os.\n\"\"\"\n\"\"\"\nVamos olhar para como o pre\u00e7o e as notas m\u00e9dias dos livros est\u00e3o distribu\u00eddos pelos dados, fazendo uma primeira an\u00e1lise.\n\nComo j\u00e1 falado anteriormente o 'User_Rating' apresenta valores entre 3.3 e 4.9, por\u00e9m vemos que sua m\u00e9dia \u00e9 alta, 4.6, assim como, pelos percentis, menos de 25% dos dados apresentam valores avaixo de 4.5, isso \u00e9 um grande potencial para investigar qual a distribui\u00e7\u00e3o de notas m\u00e9dias, pois a hip\u00f3tese proposta pela livraria VBooks pode estar correta.\n\nQuanto ao 'Price' vemos que os valores v\u00e3o de 0 a 105 com a m\u00e9dia em 13.1, sendo que 75% dos dados tem pre\u00e7o at\u00e9 16, ou seja, apenas 25% dos livros apresentam pre\u00e7os mais altos (acima de 16), esses dados, ent\u00e3o, n\u00e3o apresenta muita representatividade, uma vez que sua vari\u00e2ncia \u00e9 alta (10.8), mas tudo isso deve ser investigado melhor.\n\"\"\"\ndados[['User_Rating','Price']].describe()\nfig, ax =plt.subplots(1,2, figsize=(10,5))\nsrn.histplot(dados,x= \"User_Rating\",ax=ax[0])\nsrn.histplot(dados,x= \"Price\",ax=ax[1])\n\"\"\"\nPela apresenta\u00e7\u00e3o da hip\u00f3tese vemos que quer-se testar quais dos dois par\u00e2metros (pre\u00e7o ou nota de avalia\u00e7\u00e3o) tem mais influ\u00eancia sobre a quantidade de vendas e tempo na lista. Por\u00e9m, nos dados, n\u00e3o temos a informa\u00e7\u00e3o a respeito da quantidade de vendas, temos apenas a quantidade de reviews de cada livro, pensando na l\u00f3gica de que quanto maior a quantidade de vendas maior o n\u00famero de reviews, para a pr\u00f3xima an\u00e1lise ser\u00e1 considerado que o n\u00famero de reviews de um livro representa a quantidade de vendas.\n\"\"\"\n\"\"\"\nVamos utilizar um dos DataFrames criados para a an\u00e1lise e adicionar uma coluna referente aos reviews, ao pre\u00e7o e ao 'User_Rating' (valores m\u00e9dios).\n\"\"\"\nlista_livros = livros_anos.Livro.values\nlista_rev=[]\nlista_price =[]\nlista_urating =[]\nfor livro in lista_livros:\n  lista_rev.append(dados.query('Name == @livro').Reviews.mean())\n  lista_price.append(dados.query('Name == @livro').Price.mean())\n  lista_urating.append(dados.query('Name == @livro').User_Rating.mean())\nlivros_anos['Reviews'] = lista_rev\nlivros_anos['Price'] = lista_price\nlivros_anos['User_Rating'] = lista_urating\nlivros_anos.head()\n\"\"\"\nVamos ver graficamente a re\u00e7\u00e3o do 'Price' e do 'User_Rating' com 'Reviews' e 'Anos de Bestseller'.\n\"\"\"\nfig, ax =plt.subplots(2,2, figsize=(12,10))\nsrn.histplot(data=livros_anos, x='User_Rating',y='Anos de Bestseller',ax=ax[0][0])\nsrn.histplot(data=livros_anos, x='User_Rating',y='Reviews',ax=ax[0][1],label='User_Rating')\nsrn.histplot(data=livros_anos, x='Price',y='Anos de Bestseller',ax=ax[1][0], color='orange')\nsrn.histplot(data=livros_anos, x='Price',y='Reviews',ax=ax[1][1],label='Price', color='orange')\n\"\"\"\nAtrav\u00e9s desses gr\u00e1ficos podemos ver que, para os gr\u00e1ficos azuis ('User_Rating'), temos uma regi\u00e3o muito mais populosa para maiores notas m\u00e9dias, assim como, para os gr\u00e1ficos laranjas ('Price') temos regi\u00f5es mais populosas para menores pre\u00e7os. Assim, isso indica que pode existir alguma rela\u00e7\u00e3o desses fatores com os par\u00e2metros de 'Anos de Bestseller' e 'Reviews', mas essa correla\u00e7\u00e3o existe? Pre\u00e7o ou nota m\u00e9dia exerce maior influ\u00eancia?\n\nAtrav\u00e9s desses gr\u00e1ficos tamb\u00e9m pode-se tentar correlacionar essas quantidades com distribui\u00e7oes normais.\n\"\"\"\n\"\"\"\nVamos realizar um teste de hip\u00f3tese para investigar os dois cen\u00e1rios.\n\"\"\"\n\"\"\"\nPara o User_Rating\n\"\"\"\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre 'User_Rating' e 'Anos de Bestseller':\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = livros_anos['User_Rating']\ndata2 = livros_anos['Anos de Bestseller']\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre 'User_Rating' e 'Reviews'':\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = livros_anos['User_Rating']\ndata2 = livros_anos['Reviews']\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n\"\"\"\nTemos um coeficiente do User_Rating para os par\u00e2metros de:\n<li> Anos de Bestseller: 0.051 <\/li>\n<li> Reviews: -0.055 <\/li>\n\"\"\"\n\"\"\"\nPara o Price\n\"\"\"\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre 'Price' e 'Anos de Bestseller':\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = livros_anos['Price']\ndata2 = livros_anos['Anos de Bestseller']\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n# Vamos verificar se h\u00e1 correla\u00e7\u00e3o linear entre 'Price' e 'Reviews':\nalpha = 0.05 # signific\u00e2ncia desejada\n\ndata1 = livros_anos['Price']\ndata2 = livros_anos['Reviews']\n\n# Retorna o coeficiente de correla\u00e7\u00e3o de Pearson e o valor p to teste de pearson\ncorr, p = pearsonr(data1, data2)\n\nprint(\"Coeficiente de correla\u00e7\u00e3o:\", corr)\n\"\"\"\nTemos um coeficiente do Price para os par\u00e2metros de:\n<li> Anos de Bestseller: 0.0093 <\/li>\n<li> Reviews: -0.033 <\/li>\n\"\"\"\n\"\"\"\n### Conclus\u00e3o\n\"\"\"\n\"\"\"\nOu seja, temos que os coeficientes de correla\u00e7\u00e3o do User_Rating com rela\u00e7\u00e3o aos Anos de Bestseller e Reviews s\u00e3o maiores que aqueles do Price, ou seja, a Hip\u00f3tese \u00e9 valida.\n\"\"\"\n\"\"\"\n# Outras analises:\n\"\"\"\n\"\"\"\nVamos ver para os livros melhores avaliados ('User_Rating' == 4.9), como \u00e9 distribuido os Reviews, atrav\u00e9s de um gr\u00e1fico. Vemos que mesmo para os melhores avaliados, h\u00e1 muita diferen\u00e7a no n\u00famero de reviews realizadas.\n\"\"\"\nx=dados[dados[\"User_Rating\"]==4.9]\ny= x.groupby(\"Name\").Reviews.mean().sort_values(ascending= False)\nplt.figure(figsize= (10,10))\nsrn.set_style(\"whitegrid\")\nplot_xy = srn.barplot(x=y.values,y=y.index)\nplt.show()\n\"\"\"\nAs reviews est\u00e3o distribuidas como:\n\"\"\"\nsrn.distplot(dados.Reviews)\n\"\"\"\nVemos aqui o quanto o n\u00famero de Reviews altera com o tempo:\n\"\"\"\nplt.figure(figsize= (5,5))\nsrn.lineplot(x= \"Year\",y= \"Reviews\",data= dados,hue=\"Genre\")\n\"\"\"\nQuanto os pre\u00e7os caminham com o tempo:\n\"\"\"\nsrn.lineplot(x= \"Year\",y= \"Price\",data= dados,hue=\"Genre\")\n\"\"\"\nRela\u00e7\u00e3o entre Price e User_Rating:\n\"\"\"\nplt.figure(figsize=(8,6))\nplt.scatter('Price', 'User_Rating', data=dados, color='purple')\nplt.xlabel('Price')\nplt.ylabel('User_Rating')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '16faa100bd9e8c'}"}
{"id":"22354","text":"\"\"\"\n# INTRODUCTION\n1. Read datas\n1. Poverty rate of each state\n1. Most common 15 Name or Surname of killed people\n1. High school graduation rate of the population that is older than 25 in states\n1. Percentage of state's population according to races that are black,white,native american, asian and hispanic\n1. High school graduation rate vs Poverty rate of each state\n1. Kill properties\n    * Manner of death\n    * Kill weapon\n    * Age of killed people\n    * Race of killed people\n    * Most dangerous cities\n    * Most dangerous states\n    * Having mental ilness or not for killed people\n    * Threat types\n    * Flee types\n    * Having body cameras or not for police\n1. Race rates according to states in kill data \n1. Kill numbers from states in kill data\n1. Plotly Visualization Tutorial: https:\/\/www.kaggle.com\/kanncaa1\/plotly-tutorial-for-beginners\n<br>\n<br>\nPlot Contents:\n* [Bar Plot](#1)\n* [Point Plot](#2)\n* [Joint Plot](#3)\n* [Pie Chart](#4)\n* [Lm Plot](#5)\n* [Kde Plot](#6)\n* [Violin Plot](#7)\n* [Heatmap](#8)\n* [Box Plot](#9)\n* [Swarm Plot](#10)\n* [Pair Plot](#11)\n* [Count Plot](#12)\n    \n\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n%matplotlib inline\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"..\/input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\n#read data\nmedian_house_hold_in_come = pd.read_csv('..\/input\/MedianHouseholdIncome2015.csv', encoding=\"windows-1252\")\npercentage_people_below_poverty_level = pd.read_csv('..\/input\/PercentagePeopleBelowPovertyLevel.csv', encoding=\"windows-1252\")\npercent_over_25_completed_highSchool = pd.read_csv('..\/input\/PercentOver25CompletedHighSchool.csv',encoding= \"windows-1252\")\nshare_race_city =pd.read_csv('..\/input\/ShareRaceByCity.csv',encoding=\"windows-1252\")\n\n\n\n\"\"\"\n#  Poverty rate of each state\n\n\n\"\"\"\npercentage_people_below_poverty_level.head()\npercentage_people_below_poverty_level.info()\n#percentage_people_below_poverty_level.poverty_rate.value_counts()\npercentage_people_below_poverty_level.poverty_rate.replace(['-'], 0.0, inplace=True)\n#percentage_people_below_poverty_level.poverty_rate.value_counts()\n# Poverty rate of each state\npercentage_people_below_poverty_level.poverty_rate.replace(['-'], 0.0, inplace=True)\npercentage_people_below_poverty_level.poverty_rate = percentage_people_below_poverty_level.poverty_rate.astype(float)\narea_list = list(percentage_people_below_poverty_level['Geographic Area'].unique())\narea_poverty_ratio = []\nvarea_poverty_ratio = []\nfor i in area_list:\n    x = percentage_people_below_poverty_level[percentage_people_below_poverty_level['Geographic Area']==i]\n    area_poverty_rate = sum(x.poverty_rate)\/len(x)\n    area_poverty_ratio.append(area_poverty_rate)\ndata = pd.DataFrame({'area_list': area_list,'area_poverty_ratio':area_poverty_ratio})\nnew_index = (data['area_poverty_ratio'].sort_values(ascending=False)).index.values\nsorted_data = data.reindex(new_index)\n# visualization\n# barplot\nplt.figure(figsize=(15,16))\nsns.barplot(x=sorted_data['area_list'], y=sorted_data['area_poverty_ratio'])\nplt.xlabel(\"State\")\nplt.ylabel(\"Poverty rate\")\nplt.title(\"Poverty Rate Given States\")\nplt.xticks(rotation= 60)\n\n\n\n\narea_poverty_rate = sum(x.poverty_rate)\/len(x)\narea_poverty_rate\n#. High school graduation rate of the population that is older than 25 in states\n\npercent_over_25_completed_highSchool.head()\n\npercent_over_25_completed_highSchool.info()\n#percent_over_25_completed_highSchool.percent_completed_hs.value_counts()\npercent_over_25_completed_highSchool.percent_completed_hs.replace(['-'],0.0,inplace = True)\npercent_over_25_completed_highSchool.percent_completed_hs = percent_over_25_completed_highSchool.percent_completed_hs.astype(float)\narea_list = list(percent_over_25_completed_highSchool['Geographic Area'].unique())\narea_highschool = []\nfor i in area_list:\n    x = percent_over_25_completed_highSchool[percent_over_25_completed_highSchool['Geographic Area']==i]\n    area_highschool_rate = sum(x.percent_completed_hs)\/len(x)\n    area_highschool.append(area_highschool_rate)\n# sorting\ndata = pd.DataFrame({'area_list': area_list,'area_highschool_ratio':area_highschool})\nnew_index = (data['area_highschool_ratio'].sort_values(ascending=True)).index.values\nsorted_data2 = data.reindex(new_index)\n\n# visualization\nplt.figure(figsize =(15,10))\nsns.barplot(x = sorted_data2['area_list'], y = sorted_data2['area_highschool_ratio'])\nplt.xticks(rotation= 90)\nplt.xlabel(\"States\")\nplt.ylabel(\"High School Graduate Rate\")\nplt.title(\"Percentage of Given State's Population Above 25 that Has Graduated High School\")\n\nsorted_data.head()\n# high school graduation rate vs Poverty rate of each state\nsorted_data2[\"area_highschool_ratio\"] =sorted_data2[\"area_highschool_ratio\"]\/max(sorted_data2[\"area_highschool_ratio\"])\nsorted_data[\"area_poverty_ratio\"] =sorted_data[\"area_poverty_ratio\"]\/max(sorted_data[\"area_poverty_ratio\"])\n\ndata =pd.concat([sorted_data,sorted_data2[\"area_highschool_ratio\"]], axis = 1)\ndata.sort_values(\"area_poverty_ratio\", inplace= True)\n\nf,ax1 =plt.subplots(figsize = (20,10))\nsns.pointplot(x = \"area_list\" , y = \"area_poverty_ratio\", data = data, color = \"lime\",alpha= 0.8)\nsns.pointplot(x = \"area_list\" , y = \"area_highschool_ratio\", data = data, color = \"red\",alpha= 0.8)\nplt.text(40,0.6 ,\"high school graduate ratio\", fontsize=17,color = \"red\",style =\"italic\")\nplt.text(40,0.55,\"poverty ratio\",fontsize = 17, color =\"lime\",style=\"italic\")\n\nplt.xlabel(\"States\", fontsize =15,color =\"blue\")\nplt.ylabel(\"Value\", fontsize =15,color =\"blue\")\nplt.title(\"High School Graduate  VS  Poverty Rate\",fontsize =15,color =\"blue\")\nplt.grid()\n\n\n\"\"\"\n**jointplot**\n\"\"\"\n# jointplot \n#high school graduation rate vs Poverty rate of\ng = sns.jointplot(data.area_poverty_ratio, data.area_highschool_ratio, kind =\"kde\", size=7)\nplt.savefig(\"graph.png\")\nplt.show()\n\n\ng=sns.jointplot(x =\"area_poverty_ratio\", y=\"area_highschool_ratio\",data =data,ratio=3, size =6, color =\"r\")\n\"\"\"\n**Lm plot**\n\"\"\"\n sns.lmplot( x =\"area_poverty_ratio\", y =\"area_highschool_ratio\",data =data)\nplt.show()\n\"\"\"\n**Kde plot**\n\"\"\"\ndata.head()\nsns.kdeplot(data.area_poverty_ratio,data.area_highschool_ratio,shade=True,cut =6)\nplt.show()\n\"\"\"\n**violin plot**\n\"\"\"\npal = sns.cubehelix_palette(2, rot=-.5,dark=.6)\nsns.violinplot(data=data,palette=pal,inner=\"points\")\nplt.show()\n\"\"\"\n**heatmap**\n\"\"\"\nf, ax = plt.subplots(figsize =(5,5))\nsns.heatmap(data.corr(), annot =True, linewidths=0.5,linecolor=\"green\",fmt=\".2f\",ax=ax)\nplt.show()\ndata.head()\n\"\"\"\n**pair plot**\n\"\"\"\nsns.pairplot(data)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '29239dbc599071'}"}
{"id":"41485","text":"\"\"\"\n# About this notebook\n\nThis uses the implementation from @maunish as a basis and makes an inference using Electra-large model from google, scoring 0.504 on LB.\n\nIf you like it, please upvote maunish's notebooks mentioned below.\n\nThis uses a dataset that contains Electra pre-trained for 3 epochs, trained for 8 epochs, 3 folds\n\"\"\"\n\"\"\"\n# Original context from @maunish\n\nThis is inference notebooks that is trained using below notebooks.\n\nThis notebook uses the model created in pretrain any model notebook.\n\n1. Pretrain Roberta Model: https:\/\/www.kaggle.com\/maunish\/clrp-pytorch-roberta-pretrain\n2. Finetune Roberta Model: https:\/\/www.kaggle.com\/maunish\/clrp-pytorch-roberta-finetune <br\/>\n   Finetune Roberta Model TPU: https:\/\/www.kaggle.com\/maunish\/clrp-pytorch-roberta-finetune-tpu\n3. Inference Notebook: this notebook\n4. Roberta + SVM: https:\/\/www.kaggle.com\/maunish\/clrp-roberta-svm\n\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nimport os\nimport gc\nimport sys\nimport cv2\nimport math\nimport time\nimport tqdm\nimport random\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.model_selection import KFold,StratifiedKFold\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader,Sampler\n\nimport multiprocessing\nimport more_itertools\n\n\nfrom transformers import (AutoModel, AutoTokenizer, AutoModelForSequenceClassification)\n\nfrom colorama import Fore, Back, Style\ny_ = Fore.YELLOW\nr_ = Fore.RED\ng_ = Fore.GREEN\nb_ = Fore.BLUE\nm_ = Fore.MAGENTA\nc_ = Fore.CYAN\nsr_ = Style.RESET_ALL\n\"\"\"\n# Load data\n\"\"\"\ntrain_data = pd.read_csv('..\/input\/commonlitreadabilityprize\/train.csv')\ntest_data = pd.read_csv('..\/input\/commonlitreadabilityprize\/test.csv')\nsample = pd.read_csv('..\/input\/commonlitreadabilityprize\/sample_submission.csv')\n\"\"\"\n# Config\n\"\"\"\nconfig = {\n    'learning_rate':2e-5,\n    'batch_size':16,\n    'epochs':3,\n    'nfolds':5,\n    'seed':1, # 42\n    'max_len':256,\n}\n\ndef seed_everything(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONASSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n\nseed_everything(seed=config['seed'])\n\"\"\"\n# Dataset class\n\"\"\"\nclass CLRPDataset(Dataset):\n    def __init__(self,df,tokenizer):\n        self.excerpt = df['excerpt'].to_numpy()\n        self.tokenizer = tokenizer\n    \n    def __getitem__(self,idx):\n        encode = self.tokenizer(self.excerpt[idx],return_tensors='pt',\n                                max_length=config['max_len'],\n                                padding='max_length',truncation=True)\n        return encode\n    \n    def __len__(self):\n        return len(self.excerpt)\n\"\"\"\n# Electra Model\n\"\"\"\nclass AttentionHead(nn.Module):\n    def __init__(self, in_features, hidden_dim, num_targets):\n        super().__init__()\n        self.in_features = in_features\n        self.middle_features = hidden_dim\n\n        self.W = nn.Linear(in_features, hidden_dim)\n        self.V = nn.Linear(hidden_dim, 1)\n        self.out_features = hidden_dim\n\n    def forward(self, features):\n        att = torch.tanh(self.W(features))\n\n        score = self.V(att)\n\n        attention_weights = torch.softmax(score, dim=1)\n\n        context_vector = attention_weights * features\n        context_vector = torch.sum(context_vector, dim=1)\n\n        return context_vector\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model,self).__init__()\n        self.electra = AutoModel.from_pretrained('..\/input\/clrp-electra-large\/clrp_electra_large')\n        self.head = AttentionHead(256,256,1) \n        self.dropout = nn.Dropout(0.1)\n        self.linear = nn.Linear(256,1)\n\n    def forward(self,**xb):\n        x = self.electra(**xb)[0]\n        x = self.head(x)\n        x = self.dropout(x)\n        x = self.linear(x)\n        return x\n\"\"\"\n# Predict\n\"\"\"\ndef get_prediction(df,path,device='cuda'):        \n    model = Model()\n    model.load_state_dict(torch.load(path,map_location=device))\n    model.to(device)\n    model.eval()\n    \n    tokenizer = AutoTokenizer.from_pretrained('..\/input\/electra-tokenizer-files')\n    \n    test_ds = CLRPDataset(df,tokenizer)\n    test_dl = DataLoader(test_ds,\n                        batch_size = config[\"batch_size\"],\n                        shuffle=False,\n                        num_workers = 4,\n                        pin_memory=True)\n    \n    predictions = list()\n    for i, (inputs) in tqdm(enumerate(test_dl)):\n        inputs = {key:val.reshape(val.shape[0],-1).to(device) for key,val in inputs.items()}\n        outputs = model(**inputs)\n        outputs = outputs.cpu().detach().numpy().ravel().tolist()\n        predictions.extend(outputs)\n        \n    torch.cuda.empty_cache()\n    return np.array(predictions)\n\"\"\"\n# Prediction\n\"\"\"\npred1 = get_prediction(test_data,'..\/input\/electra-large-fit8\/model0\/model0.bin')\npred2 = get_prediction(test_data,'..\/input\/electra-large-fit8\/model1\/model1.bin')\npred3 = get_prediction(test_data,'..\/input\/electra-large-fit8\/model2\/model2.bin')\n\npredictions1 = (pred1 + pred2 + pred3)\/3\n\"\"\"\n# Submission\n\"\"\"\nsample['target'] = predictions1\nsample.to_csv('submission.csv',index=False)\nsample","meta":"{'source': 'AI4Code', 'id': '4c79a127702e22'}"}
{"id":"44099","text":"# 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\n\"\"\"\nStroke Prediction Model (Binary Classification)\n\n\"\"\"\n# packages\n\n# standard\nimport numpy as np\nimport pandas as pd\nimport time\n\n# plot\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# statistics tools\nfrom statsmodels.graphics.mosaicplot import mosaic\n\n# ML\nimport h2o\nfrom h2o.estimators import H2ORandomForestEstimator\nfrom h2o.estimators import H2OGradientBoostingEstimator\n\"\"\"\nImport and first glance\n\"\"\"\n# load data\ndf = pd.read_csv('..\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv')\n\n# dimensions of data\ndf.shape\n# column names\nprint(df.columns.tolist())\n\"\"\"\nData cleansing\n\"\"\"\n\ndf.info()\n# impute with -99\ndf.bmi = df.bmi.fillna(-99)\n# rename columns\ndf.rename(columns = {'Residence_type':'residence_type'}, inplace = True)\n# define target variable\ndf['target'] = df.stroke\ndf = df.drop(['stroke'], axis=1) # remove stroke column\n\"\"\"\nNumerical Features\n\"\"\"\n# select numerical features\nfeatures_num = ['age', 'avg_glucose_level','bmi']\n# basic stats\ndf[features_num].describe(percentiles=[0.1,0.25,0.5,0.75,0.9])\n# plot distribution of numerical features\nfor f in features_num:\n    df[f].plot(kind='hist', bins=50)\n    plt.title(f)\n    plt.grid()\n    plt.show()\n# pairwise scatter plot\nsns.pairplot(df[features_num], \n             kind='reg', \n             plot_kws={'line_kws':{'color':'magenta'}, 'scatter_kws': {'alpha': 0.1}})\nplt.show()\n# Spearman (Rank) correlation\ncorr_spearman = df[features_num].corr(method='spearman')\n\nfig = plt.figure(figsize = (6,5))\nsns.heatmap(corr_spearman, annot=True, cmap=\"RdYlGn\", vmin=-1, vmax=+1)\nplt.title('Spearman Correlation')\nplt.show()\nfeatures_cat = ['gender','hypertension','heart_disease','ever_married',\n                'work_type','residence_type','smoking_status']\nfor f in features_cat:\n    df[f].value_counts().plot(kind='bar')\n    plt.title(f)\n    plt.grid()\n    plt.show()\n# calc frequencies\ntarget_count = df.target.value_counts()\nprint(target_count)\nprint()\nprint('Percentage of strokes [1]:', np.round(100*target_count[1] \/ target_count.sum(),2), '%')\n# plot target distribution\ntarget_count.plot(kind='bar')\nplt.title('Target = Stroke')\nplt.grid()\nplt.show()\n\"\"\"\nTarget vs Numerical Features\n\"\"\"\n# add binned version of numerical features\n\n# quantile based:\ndf['age_bin'] = pd.qcut(df['age'], q=10, precision=1)\ndf['avg_glucose_level_bin'] = pd.qcut(df['avg_glucose_level'], q=10, precision=1)\n\n# explicitly defined bins:\ndf['bmi_bin'] = pd.cut(df['bmi'], [-100,10,20,25,30,35,40,50,100])\n# plot target vs features using mosaic plot\nplt_para_save = plt.rcParams['figure.figsize'] # remember plot settings\n\nfor f in features_num:\n    f_bin = f+'_bin'\n    plt.rcParams[\"figure.figsize\"] = (16,7) # increase plot size for mosaics\n    mosaic(df, [f_bin, 'target'], title='Target vs ' + f + ' [binned]')\n    plt.show()\n    \n# reset plot size again\nplt.rcParams['figure.figsize'] = plt_para_save\n\"\"\"\n\"Naive\" Interpretations based on those univariate plots:\nRisk increases with age and glucose level (diabetes).\nHigh BMI levels are also indicating higher risk.\nA missing value for BMI (the leftmost column) seems to indicate a massively increased risk!?\n\n\"\"\"\n# BMI - check cross table\nctab = pd.crosstab(df.bmi_bin, df.target)\nctab\n# normalize each row to get row-wise target percentages\n(ctab.transpose() \/ ctab.sum(axis=1)).transpose()\n\n\"\"\"\nAlmost 20% of the missing BMIs had a stroke! This is way higher than for the other bins.\n\"\"\"\n\"\"\"\nTarget vs Categorical Features\n\n\"\"\"\n# plot target vs features using mosaic plot\nplt_para_save = plt.rcParams['figure.figsize'] # remember plot settings\n\nfor f in features_cat:\n    plt.rcParams[\"figure.figsize\"] = (8,7) # increase plot size for mosaics\n    mosaic(df, [f, 'target'], title='Target vs ' + f)\n    plt.show()\n    \n# reset plot size again\nplt.rcParams['figure.figsize'] = plt_para_save\n\"\"\"\n\"Naive\" Interpretations based on those univariate plots:\nInfluence of gender seems surprisingly low\nHypertension and heart disease massively increase risk of stroke\n\"Ever married\" too!?\nWork type: Higher risk for self-employed (more stress?)\nResidence type: Slightly higher risk for urban vs rural\nSmoking: Highest risk for former smokers. Not much difference between \"smokes\" and \"never smoked\"?\n\"\"\"\n# \"ever married\" - check cross table\nctab = pd.crosstab(df.ever_married, df.target)\nctab\n# normalize each row\n(ctab.transpose() \/ ctab.sum(axis=1)).transpose()\n\"\"\"\nBuild Model\n\"\"\"\n# select predictors\npredictors = features_num + features_cat\nprint('Number of predictors: ', len(predictors))\nprint(predictors)\n# start H2O\nh2o.init(max_mem_size='12G', nthreads=4) # Use maximum of 12 GB RAM and 4 cores\n# upload data frame in H2O environment\ndf_hex = h2o.H2OFrame(df)\n\ndf_hex['target'] = df_hex['target'].asfactor()\n\n# train \/ test split (70\/30)\ntrain_hex, test_hex = df_hex.split_frame(ratios=[0.7], seed=999)\n\n# pandas versions of train\/test\ndf_train = train_hex.as_data_frame()\ndf_test = test_hex.as_data_frame()\n# export for potential external processing\ndf_train.to_csv('df_train.csv')\ndf_test.to_csv('df_test.csv')\n# define Gradient Boosting model\nfit_1 = H2OGradientBoostingEstimator(ntrees = 100,\n                                     max_depth=4,\n                                     min_rows=10,\n                                     learn_rate=0.01, # default: 0.1\n                                     sample_rate=1,\n                                     col_sample_rate=0.7,\n                                     nfolds=5,\n                                     score_each_iteration=True,\n                                     stopping_metric='auto',\n                                     stopping_rounds=10,\n                                     seed=999)\n# train model\nt1 = time.time()\nfit_1.train(x=predictors,\n            y='target',\n            training_frame=train_hex)\nt2 = time.time()\nprint('Elapsed time [s]: ', np.round(t2-t1,2))\n# show training scoring history\nplt.rcParams['figure.figsize']=(7,4)\nfit_1.plot()\n# show cross validation metrics\nfit_1.cross_validation_metrics_summary()\n# show scoring history - training vs cross validations\nfor i in range(5):\n    cv_model_temp = fit_1.cross_validation_models()[i]\n    df_cv_score_history = cv_model_temp.score_history()\n    my_title = 'CV ' + str(1+i) + ' - Scoring History [AUC]'\n    plt.scatter(df_cv_score_history.number_of_trees,\n                y=df_cv_score_history.training_auc, \n                c='blue', label='training')\n    plt.scatter(df_cv_score_history.number_of_trees,\n                y=df_cv_score_history.validation_auc, \n                c='darkorange', label='validation')\n    plt.title(my_title)\n    plt.xlabel('Number of Trees')\n    plt.ylabel('AUC')\n    plt.ylim(0.8,1)\n    plt.legend()\n    plt.grid()\n    plt.show()\n\"\"\"\nROC Curve - Training Data\n\"\"\"\n# training performance\nperf_train = fit_1.model_performance(train=True)\nperf_train.plot()\n\n\"\"\"\nROC Curve - Cross Validation\n\"\"\"\n# cross validation performance\nperf_cv = fit_1.model_performance(xval=True)\nperf_cv.plot()\n\"\"\"\nConfusion Matrix\n\"\"\"\n# on training data - automatic threshold (optimal F1 score)\nconf_train = fit_1.confusion_matrix(train=True)\nconf_train.show()\n# corresponding accuracy for this threshold:\nconf_list_temp = conf_train.to_list()\nn_matrix = sum(conf_list_temp[0]) + sum(conf_list_temp[1])\nacc_t0 = (conf_list_temp[0][0]+conf_list_temp[1][1]) \/ n_matrix\nprint('Accuracy:', np.round(acc_t0,6))\n# alternatively specify threshold manually - here we try to achieve a symmetric outcome\ntt = 0.148\nconf_train_man = fit_1.confusion_matrix(train=True, thresholds=tt)\nconf_train_man.show()\n# corresponding accuracy for manual threshold:\nconf_list_temp = conf_train_man.to_list()\nn_matrix = sum(conf_list_temp[0]) + sum(conf_list_temp[1]) \nacc_t1 = (conf_list_temp[0][0]+conf_list_temp[1][1]) \/ n_matrix\nprint('Accuracy:', np.round(acc_t1,6))\n\"\"\"\nMuch better: 184 actual positives vs. 185 predicted positives!\n\"\"\"\n# check on cross validation\nconf_cv_man = fit_1.confusion_matrix(xval=True, thresholds=tt)\nconf_cv_man.show()\n# corresponding accuracy for our manual threshold:\nconf_list_temp = conf_cv_man.to_list()\nn_matrix = sum(conf_list_temp[0]) + sum(conf_list_temp[1])\nacc_t1_CV = (conf_list_temp[0][0]+conf_list_temp[1][1]) \/ n_matrix\nprint('Accuracy:', np.round(acc_t1_CV,6))\n\"\"\"\nVariable Importance\n\"\"\"\n# basic version\nfit_1.varimp_plot()\n# variable importance using shap values => see direction as well as severity of feature impact\nt1 = time.time()\nfit_1.shap_summary_plot(train_hex);\nt2 = time.time()\nprint('Elapsed time [s]: ', np.round(t2-t1,2))\n\"\"\"\nPredictions on training data\n\n\"\"\"\n# predict on train set (extract probabilities only)\npred_train = fit_1.predict(train_hex)['p1']\npred_train = pred_train.as_data_frame().p1\n\n# and plot\nplt.hist(pred_train, bins=50)\nplt.title('Predictions on Train Set')\nplt.grid()\nplt.show()\n# check calibration\nfrequency_pred = sum(pred_train)\nfrequency_act = df_train.target.sum()\nprint('Predicted Frequency:', frequency_pred)\nprint('Actual Frequency   :', frequency_act)\n\"\"\"\nEvaluate on Test Set\n\"\"\"\n# calc performance on test test\nperf_test = fit_1.model_performance(test_hex)\n\n# ROC Curve - Test Set\nperf_test.plot()\n# confusion matrix using our manual threshold\nconf_test_man = perf_test.confusion_matrix(thresholds=tt)\nconf_test_man.show()\n\"\"\"\nQuite good: 65 actual positives vs 69 predicted positives.\n\"\"\"\n# calc accuracy for manual threshold:\nconf_list_temp = conf_test_man.to_list()\nn_matrix = sum(conf_list_temp[0]) + sum(conf_list_temp[1]) \nacc_t1_test = (conf_list_temp[0][0]+conf_list_temp[1][1]) \/ n_matrix\nprint('Accuracy:', np.round(acc_t1_test,6))\n# predict on test set (extract probabilities only)\npred_test = fit_1.predict(test_hex)['p1']\npred_test = pred_test.as_data_frame().p1\n\n# and plot\nplt.hist(pred_test, bins=50)\nplt.title('Predictions on Test Set')\nplt.grid()\nplt.show()\n# connect prediction with data frame\ndf_test['prediction'] = pred_test\n\"\"\"\nShow examples\n\"\"\"\n# show most endangered patients (according to our model) in test set\ndf_high_20 = df_test.nlargest(20, columns='prediction')\ndf_high_20\nprint('Actual cases in highest 20    :', df_high_20.target.sum())\nprint('Predicted cases in highest 20 :', np.round(df_high_20.prediction.sum(),2))\n# show least endangered patients (according to our model) in test set\ndf_low_20 = df_test.nsmallest(20, columns='prediction')\ndf_low_20\nprint('Actual cases in lowest 20    :', df_low_20.target.sum())\nprint('Predicted cases in lowest 20 :', np.round(df_low_20.prediction.sum(),2))","meta":"{'source': 'AI4Code', 'id': '514f4649a6c97b'}"}
{"id":"72233","text":"\"\"\"\nKaggle link : https:\/\/www.kaggle.com\/ronitf\/heart-disease-uci\n\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n! ls ..\/input\/heart-disease-uci\/heart.csv\n\"\"\"\n**Importing the librabries**\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\ndata = pd.read_csv('..\/input\/heart-disease-uci\/heart.csv')\ndata.head()\ndata.shape\ndata.info()\ndata.describe()\n#checking if threre is any null values present in dataset or not \ndata.isnull().sum()\n\"\"\"\n**Feature Selection **\n\"\"\"\ncorr = data.corr()\nplt.plot(figsize= (20,20))\nsns.heatmap(corr, annot=True)\nsns.countplot(x='target',data=data ,palette='winter_r')\nplt.xlabel('heart disease outcome')\nplt.ylabel('count of patient')\n# checking counts of true and false heartprediction ,we have balance dataset so no need to upsamping and down sampling. \ntarget_true= len(data.loc[data['target']==1])\ntarget_false= len(data.loc[data['target']==0])\nprint(target_true,target_false)\n\nfrom sklearn.model_selection import  train_test_split\nfrom sklearn.preprocessing import StandardScaler\nsc_x= StandardScaler()\ncolumns_to_scale = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']\ndata[columns_to_scale] = sc_x.fit_transform(data[columns_to_scale])\ndata.head()\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\ny = data['target']\nX = data.drop(['target'], axis = 1)\n#y is series hence convering into 2d array using reshape \ny1 =y.ravel().reshape(-1,1)\ny1.shape\n# checking best nearest naighbours values\nfrom sklearn.model_selection import cross_val_score\nknn_score= []\nfor i in range(1,20):\n    knn_classifier = KNeighborsClassifier(n_neighbors=i)\n    score = cross_val_score(knn_classifier,X,y1,cv=10)\n    knn_score.append(score.mean())\n    \nplt.plot([i for i in range(1,20)],knn_score,'b*--')\nplt.xticks([i for i in range(1, 20)])\nplt.xlabel('Number of Neighbors (K)')\nplt.ylabel('Scores')\nplt.title('K Neighbors Classifier scores for different K values')\n\"\"\"\nwe can take nearest neighbours value from 4 or 5 . \nbecause it is giving more score \n\"\"\"\n\nknn_classifier = KNeighborsClassifier(n_neighbors = 5)\nscore=cross_val_score(knn_classifier,X,y1,cv=10)\n\nscore.mean()\n##random forest\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nrandomforest_classifier= RandomForestClassifier(n_estimators=10)\nscore=cross_val_score(randomforest_classifier,X,y,cv=10)\nscore.mean() ","meta":"{'source': 'AI4Code', 'id': '84e3dd48bd5397'}"}
{"id":"100096","text":"# 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 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\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \ntrain = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/test.csv')\ntrain.head()\ndef getNullsCols(data):\n    drop_cols = []\n    for col in data.columns :\n        nans = data[col].isna().sum()\n        if nans > len(data)*0.30:\n            drop_cols.append(col)\n    return drop_cols\ntrain_dr_cols = getNullsCols(train)\ntest_dr_cols = getNullsCols(test)\ntrain_dr_cols, test_dr_cols\n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature'], inplace = True, axis = 1)\ntest.drop(['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature'], inplace = True, axis = 1)\ntrain.head()\n##Filling Na \nnumerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\ndigitcols_data_train = train.select_dtypes(numerics).columns\nnumerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\ndigitcols_data_test = test.select_dtypes(numerics).columns\ndigitcols_data_train, digitcols_data_test\n\nlen(digitcols_data_train),len(digitcols_data_test)\ndef fillNaForNumerCols(data, cols):\n    for col in cols :\n        if data[col].isna().sum() > 0.0 :\n            print(data[col].mean())\n            data[col].fillna(data[col].mean(), inplace = True)\n    return data\ntrian = fillNaForNumerCols(train, digitcols_data_test)\ntrain[digitcols_data_test].isna().sum()\ntest = fillNaForNumerCols(test, digitcols_data_test)\ntest[digitcols_data_test].isna().sum()\ndef fillNaForObjCols(data):\n    obj_cols = data.select_dtypes(['object','category'])\n    for col in obj_cols:\n        if data[col].isna().sum() > 0:\n            data[col].fillna(data[col].mode()[0], inplace = True)\n    return data\ntrain_t\ntrain_t = fillNaForObjCols(train)\ntest_t = fillNaForObjCols(train)\nfor i in train_t.isna().sum() > 0:\n    if i == True : \n        print(i)\nfor i in test_t.isna().sum() > 0:\n    if i == True : \n        print(i)\ntest_t = fillNaForObjCols(test)\ntrain = train_t\ntest = test_t\ntrain.head()\ntest.head()\ndef getNonUnqCols(data, thresh):\n    obj_cols = data.select_dtypes(['object', 'category'])\n    unq = []\n    for i in obj_cols:\n        unq_no = len(data[i].unique())\n        if unq_no > thresh:\n            unq.append(i)\n        \n    return unq\n\nnonUnq_train = getNonUnqCols(train, 6)\nnonUnq_test = getNonUnqCols(test, 6)\nnonUnq_train, nonUnq_test\nnonUnq_train = getNonUnqCols(train, 9)\nnonUnq_test = getNonUnqCols(test, 9)\nnonUnq_train, nonUnq_test\nnonUnq_train = getNonUnqCols(train, 5)\nnonUnq_test = getNonUnqCols(test, 5)\nnonUnq_train, nonUnq_test\n#The condition2 doesnt even have the same uniq values in the test data , i dont think its usefull therefore drop it \n#Drop = ['Condition2']\n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['Condition2'], inplace = True, axis = 1)\ntest.drop(['Condition2'], inplace = True, axis = 1)\nnonUnq_train = getNonUnqCols(train, 7)\nnonUnq_test = getNonUnqCols(test, 7)\nnonUnq_train, nonUnq_test\n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['HouseStyle'], inplace = True, axis = 1)\ntest.drop(['HouseStyle'], inplace = True, axis = 1)\n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['RoofMatl'], inplace = True, axis = 1)\ntest.drop(['RoofMatl'], inplace = True, axis = 1)\nnonUnq_train = getNonUnqCols(train, 7)\nnonUnq_test = getNonUnqCols(test, 7)\nnonUnq_train, nonUnq_test\nnonUnq_train = getNonUnqCols(train, 10)\nnonUnq_test = getNonUnqCols(test, 10)\nnonUnq_train, nonUnq_test\n#how  the cols 'Condition1', 'SaleType' are affecting the SalePrice\n#drop the cols more than 10 distinct values \n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['Neighborhood', 'Exterior1st', 'Exterior2nd'], inplace = True, axis = 1)\ntest.drop(['Neighborhood', 'Exterior1st', 'Exterior2nd'], inplace = True, axis = 1)\nimport seaborn as sns\nsns.catplot(x = 'Condition1', y = 'SalePrice', data = train)\ntrain['Condition1'].unique()\nsum(train['Condition1'] == 'RRNe'), sum(train['Condition1'] == 'PosA'), \nsum(train['Condition1'] == 'RRNn'), sum(train['Condition1'] == 'RRAe')\ntrain.replace({'Condition1': {'RRNe': 'condLow', 'PosA': 'condLow'}}, inplace= True)\ntrain.replace({'Condition1': {'RRAe': 'condLow'}}, inplace= True)\ntest.replace({'Condition1': {'RRNe': 'condLow', 'PosA': 'condLow','RRAe': 'condLow'}}, inplace= True)\ntrain['Condition1'].unique()\ntest['Condition1'].unique()\nsns.catplot(x = 'SaleType', y = 'SalePrice', data = train)\ntrain['SaleType'].unique()\n#make the cols :- Con, CWD  as SaleType_1\n               # 'Oth', 'ConLw','ConLI','ConLD'   as SaleType_2 \ntrain.replace({'SaleType': {'Con': 'SaleType_1', 'CWD': 'SaleType_1'}}, inplace= True)\ntest.replace({'SaleType': {'Con': 'SaleType_1', 'CWD': 'SaleType_1'}}, inplace= True)\ntrain.replace({'SaleType': {'Oth': 'SaleType_2', 'ConLw': 'SaleType_2',\n                            'ConLI': 'SaleType_2','ConLD': 'SaleType_2'}}, inplace= True)\ntest.replace({'SaleType': {'Oth': 'SaleType_2', 'ConLw': 'SaleType_2',\n                            'ConLI': 'SaleType_2','ConLD': 'SaleType_2'}}, inplace= True)\ntrain['SaleType'].unique()\ntest['SaleType'].unique()\n#dropping the high correlated values \ntrain.corr()['SalePrice']\n#dropping the OverallQual as it has close 80 % correlated to the SalePrice \n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['OverallQual'], inplace = True, axis = 1)\ntest.drop(['OverallQual'], inplace = True, axis = 1)\ntrain.head()\ntest.head()\n#Seems like the data has lot of zeros in it \nsum(train['EnclosedPorch'] == 0)\nsum(test['EnclosedPorch'] == 0)\nlen(train)*0.30\nnumerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\ncheck_zero_cols = test.select_dtypes(numerics).columns\nfor col in check_zero_cols:\n    l = len(train)\n    if sum(train[col] == 0) > (l*0.40):\n        print(col)\nfor col in check_zero_cols:\n    l = len(test)\n    if sum(test[col] == 0) > (l*0.40):\n        print('\\''+col+'\\',')\n#dropping the columns as the have the null values more than 30 %\n\ntrain.drop(['MasVnrArea',\n'BsmtFinSF2',\n'2ndFlrSF',\n'LowQualFinSF',\n'BsmtFullBath',\n'BsmtHalfBath',\n'HalfBath',\n'Fireplaces',\n'WoodDeckSF',\n'OpenPorchSF',\n'EnclosedPorch',\n'3SsnPorch',\n'ScreenPorch',\n'PoolArea',\n'MiscVal'], inplace = True, axis = 1)\ntest.drop(['MasVnrArea',\n'BsmtFinSF2',\n'2ndFlrSF',\n'LowQualFinSF',\n'BsmtFullBath',\n'BsmtHalfBath',\n'HalfBath',\n'Fireplaces',\n'WoodDeckSF',\n'OpenPorchSF',\n'EnclosedPorch',\n'3SsnPorch',\n'ScreenPorch',\n'PoolArea',\n'MiscVal'], inplace = True, axis = 1)\ntrain.head()\ntest.head()\nnumerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\ncheck_zero_cols = test.select_dtypes(numerics).columns\nfor col in check_zero_cols:\n    l = len(train)\n    if sum(train[col] == 0) < (l*0.40) and sum(train[col] == 0) > (l*0.10):\n        print('\\''+col+'\\',')\nmean_train_BSMT  = train['BsmtFinSF1'].mean()\nmean_test_BSMT  = test['BsmtFinSF1'].mean()\ntrain.replace({'BsmtFinSF1': {0: mean_train_BSMT}}, inplace= True)\ntest.replace({'BsmtFinSF1': {0: mean_test_BSMT}}, inplace= True)\ntrain.head()\ntest.head()\nfor col in check_zero_cols:\n    l = len(train)\n    if sum(train[col] == 0) < (l*0.40) and sum(train[col] == 0) > 0:\n        print('\\''+col+'\\',')\nsum(train['TotalBsmtSF'] ==0)\nplt.scatter(train['TotalBsmtSF'] , train['SalePrice'] )\nplt.scatter(train['FullBath'] , train['SalePrice'] )\nplt.scatter(train['BsmtUnfSF'] , train['SalePrice'] )\nplt.scatter(train['BedroomAbvGr'] , train['SalePrice'] )\nplt.scatter(train['KitchenAbvGr'] , train['SalePrice'] )\nplt.scatter(train['GarageCars'] , train['SalePrice'] )\nplt.scatter(train['GarageArea'] , train['SalePrice'] )\n#Change the Dtypes of the Classifies columns such as \n# FullBath, GarageCars, KitchenAbvGr, BedroomAbvGr \ntrain['FullBath'] = train['FullBath'].astype('object')\ntrain['GarageCars'] = train['GarageCars'].astype('object')\ntrain['KitchenAbvGr'] = train['KitchenAbvGr'].astype('object')\ntrain['BedroomAbvGr'] = train['BedroomAbvGr'].astype('object')\ntest['FullBath'] = test['FullBath'].astype('object')\ntest['GarageCars'] = test['GarageCars'].astype('object')\ntest['KitchenAbvGr'] = test['KitchenAbvGr'].astype('object')\ntest['BedroomAbvGr'] = test['BedroomAbvGr'].astype('object')\n#Ajust some mean value in the 'GarageArea' as it is separated from the other values \n#adjust to the rangeof 200 to 400 like 260 which gives the same result as for the 0 Garbase area \ntrain.replace({'GarageArea': {0: 260}}, inplace= True)\ntest.replace({'GarageArea': {0: 260}}, inplace= True)\nX  = train.iloc[:, :-1]\nX.head()\nY = pd.DataFrame(train.iloc[:, -1], columns={'SalePrice'})\nY\nX.drop(['Id'], inplace=True, axis = 1)\ntest_ids = pd.DataFrame(test['Id'], columns={'Id'})\ntest.drop(['Id'], inplace=True, axis = 1)\nX_dumm = pd.get_dummies(X, drop_first=True)\nX_dumm\nX_dumm.columns.values\ntest_dumm = pd.get_dummies(test, drop_first=True)\ntest_dumm\ntest_dumm.columns.values\nfor cols in X_dumm.columns.values:\n    if cols not in test_dumm.columns.values:\n        print(cols)\nfor cols in test_dumm.columns.values:\n    if cols not in X_dumm.columns.values:\n        print(cols)\n#drop column in the test data are \n#'FullBath_4', 'GarageCars_1.7661179698216736', 'GarageCars_5.0'\ntest_dumm.drop(['FullBath_4', 'GarageCars_1.7661179698216736', 'GarageCars_5.0'], inplace = True, axis = 1)\nfor cols in test_dumm.columns.values:\n    if cols not in X_dumm.columns.values:\n        print(cols)\ntest_dumm.rename(columns={\"GarageCars_1.0\": \"GarageCars_1\", \"GarageCars_2.0\": \"GarageCars_2\",\n                         \"GarageCars_3.0\": \"GarageCars_3\",\"GarageCars_4.0\": \"GarageCars_4\"}, inplace=True)\nfor cols in test_dumm.columns.values:\n    if cols not in X_dumm.columns.values:\n        print(cols)\nfor cols in X_dumm.columns.values:\n    if cols not in test_dumm.columns.values:\n        print('\\''+cols+'\\',')\n#dropping these are they are not in the test \n#'Utilities_NoSeWa',\n'Heating_GasA',\n'Heating_OthW',\n'Electrical_Mix',\n'BedroomAbvGr_8',\n'KitchenAbvGr_3',\n'GarageQual_Fa',\nX_dumm.drop(['Utilities_NoSeWa',\n'Heating_GasA',\n'Heating_OthW',\n'Electrical_Mix',\n'BedroomAbvGr_8',\n'KitchenAbvGr_3',\n'GarageQual_Fa'], inplace = True, axis = 1)\nX_dumm.head()\ntest_dumm.head()\nfor cols in X_dumm.columns.values:\n    if cols not in test_dumm.columns.values:\n        print('\\''+cols+'\\',')\n#All the coolumns have become equal and ready to model \nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.ensemble import GradientBoostingRegressor\nboosting = GradientBoostingRegressor()\nparams = {\n    'criterion':['mse'],\n    \"n_estimators\" : [50,100,200,400,350 ],\n    \"max_depth\" : [ 4,6]\n}\ncv = GridSearchCV(boosting, params, cv = 10)\ncv.fit(X_dumm, Y)\nboost_res = cv.predict(test_dumm)\nfinal_deep = pd.concat([test_ids, pd.DataFrame(boost_res, columns={'SalePrice'})], axis=1)\nfinal_deep.to_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/submission.csv', index=False)\n\"\"\"\nThe RMSE is almost 1.4* which is not that perfect, the model should be trained in even better way....\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b7f94741ac67d7'}"}
{"id":"24843","text":"\"\"\"\n# Overview\nMy Idea: 2D attention\n\n\nProvide attention to hidden states for multiple layers and create a context vector based on attention weights.\nthen provide attention to context vectors of multiple layers\n\nand \n\n\nAcknowledgments: some ideas were taken from kernels by [Torch](https:\/\/www.kaggle.com\/rhtsingh) and [Maunish](https:\/\/www.kaggle.com\/maunish) and [Andrey Tuganov](https:\/\/www.kaggle.com\/andretugan).\n\"\"\"\nimport os\nimport math\nimport random\nimport time\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nfrom transformers import AdamW\nfrom transformers import AutoTokenizer\nfrom transformers import AutoModel\nfrom transformers import AutoConfig\nfrom transformers import get_cosine_schedule_with_warmup\n\nfrom sklearn.model_selection import KFold\n\nimport gc\ngc.enable()\nNUM_FOLDS = 5\nNUM_EPOCHS = 3\nBATCH_SIZE = 10\nMAX_LEN = 248\nEVAL_SCHEDULE = [(0.50, 16), (0.49, 8), (0.48, 4), (0.47, 2), (-1., 1)]\nROBERTA_PATH = \"roberta-large\"\nTOKENIZER_PATH = \"roberta-large\"\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\ndef set_random_seed(random_seed):\n    random.seed(random_seed)\n    np.random.seed(random_seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(random_seed)\n\n    torch.manual_seed(random_seed)\n    torch.cuda.manual_seed(random_seed)\n    torch.cuda.manual_seed_all(random_seed)\n\n    torch.backends.cudnn.deterministic = True\ntrain_df = pd.read_csv(\"\/kaggle\/input\/commonlitreadabilityprize\/train.csv\")\n\n# Remove incomplete entries if any.\ntrain_df.drop(train_df[(train_df.target == 0) & (train_df.standard_error == 0)].index,\n              inplace=True)\ntrain_df.reset_index(drop=True, inplace=True)\n\ntest_df = pd.read_csv(\"\/kaggle\/input\/commonlitreadabilityprize\/test.csv\")\nsubmission_df = pd.read_csv(\"\/kaggle\/input\/commonlitreadabilityprize\/sample_submission.csv\")\ntokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)\n\"\"\"\n# Dataset\n\"\"\"\nclass LitDataset(Dataset):\n    def __init__(self, df, inference_only=False):\n        super().__init__()\n\n        self.df = df        \n        self.inference_only = inference_only\n        self.text = df.excerpt.tolist()\n        #self.text = [text.replace(\"\\n\", \" \") for text in self.text]\n        \n        if not self.inference_only:\n            self.target = torch.tensor(df.target.values, dtype=torch.float32)        \n    \n        self.encoded = tokenizer.batch_encode_plus(\n            self.text,\n            padding = 'max_length',            \n            max_length = MAX_LEN,\n            truncation = True,\n            return_attention_mask=True\n        )        \n \n\n    def __len__(self):\n        return len(self.df)\n\n    \n    def __getitem__(self, index):        \n        input_ids = torch.tensor(self.encoded['input_ids'][index])\n        attention_mask = torch.tensor(self.encoded['attention_mask'][index])\n        \n        if self.inference_only:\n            return (input_ids, attention_mask)            \n        else:\n            target = self.target[index]\n            return (input_ids, attention_mask, target)\n\"\"\"\n# Model\nThe model is inspired by the one from [Maunish](https:\/\/www.kaggle.com\/maunish\/clrp-roberta-svm).\n\"\"\"\nclass LitModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n\n        config = AutoConfig.from_pretrained(ROBERTA_PATH)\n        config.update({\"output_hidden_states\":True, \n                       \"hidden_dropout_prob\": 0.0,\n                       \"layer_norm_eps\": 1e-7})                       \n        \n        self.roberta = AutoModel.from_pretrained(ROBERTA_PATH, config=config)  \n            \n        self.attention1 = nn.Sequential(            \n            nn.Linear(1024, 256),            \n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        self.attention2 = nn.Sequential(            \n            nn.Linear(1024, 256),            \n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        self.attention4 = nn.Sequential(            \n            nn.Linear(1024, 256),            \n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        self.attention8 = nn.Sequential(            \n            nn.Linear(1024, 256),            \n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        \n        self.attention16 = nn.Sequential(            \n            nn.Linear(1024,256),\n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        self.attention20 = nn.Sequential(            \n            nn.Linear(1024,256),\n            nn.Tanh(),                       \n            nn.Linear(256, 1),\n            nn.Softmax(dim=1)\n        )\n        \n        self.attention_sm = nn.Sequential(            \n            nn.Linear(1024, 6),\n            nn.Tanh(),                       \n            nn.Linear(6, 1),\n            nn.Softmax(dim=1)\n        )\n\n        self.regressor = nn.Sequential(                        \n            nn.Linear(1024, 1)                        \n        )\n        \n\n    def forward(self, input_ids, attention_mask):\n        roberta_output = self.roberta(input_ids=input_ids,\n                                      attention_mask=attention_mask)        \n        \n        # There are a total of 13 layers of hidden states.\n        # 1 for the embedding layer, and 12 for the 12 Roberta layers.\n        # We take the hidden states from the last Roberta layer.\n        last_layer_hidden_states = roberta_output.hidden_states[-1]\n        weights_1 = self.attention1(last_layer_hidden_states)\n        context_vector_1 = torch.sum(weights_1 * last_layer_hidden_states, dim=1)\n        \n        last2_layer_hidden_states = roberta_output.hidden_states[-2]\n        weights_2 = self.attention2(last2_layer_hidden_states)\n        context_vector_2 = torch.sum(weights_2 * last2_layer_hidden_states, dim=1)\n        \n        last4_layer_hidden_states = roberta_output.hidden_states[-3]\n        weights_4 = self.attention4(last4_layer_hidden_states)\n        context_vector_4 = torch.sum(weights_4 * last4_layer_hidden_states, dim=1)\n        \n        last8_layer_hidden_states = roberta_output.hidden_states[-4]\n        weights_8 = self.attention8(last8_layer_hidden_states)\n        context_vector_8 = torch.sum(weights_8 * last8_layer_hidden_states, dim=1)\n        \n        last16_layer_hidden_states = roberta_output.hidden_states[-16]\n        weights_16 = self.attention16(last16_layer_hidden_states)\n        context_vector_16 = torch.sum(weights_16 * last16_layer_hidden_states, dim=1)\n        \n        last20_layer_hidden_states = roberta_output.hidden_states[-20]\n        weights_20 = self.attention20(last20_layer_hidden_states)\n        context_vector_20 = torch.sum(weights_20 * last20_layer_hidden_states, dim=1)\n        \n#         print(context_vector_1.shape)\n        con_context_vectors = torch.stack([context_vector_1, context_vector_2, context_vector_4, context_vector_8, context_vector_16, context_vector_20], dim=1)\n#         print(con_context_vectors.shape)\n        layer_weights = self.attention_sm(con_context_vectors)\n#         print(layer_weights.shape)\n        final_context_vector = torch.sum(layer_weights * con_context_vectors, dim=1)\n        \n#         print(final_context_vector.shape)\n        ans = self.regressor(final_context_vector)\n#         print(ans.shape)\n        \n        # Now we reduce the context vector to the prediction score.\n        return ans\ndef eval_mse(model, data_loader):\n    \"\"\"Evaluates the mean squared error of the |model| on |data_loader|\"\"\"\n    model.eval()            \n    mse_sum = 0\n\n    with torch.no_grad():\n        for batch_num, (input_ids, attention_mask, target) in enumerate(data_loader):\n            input_ids = input_ids.to(DEVICE)\n            attention_mask = attention_mask.to(DEVICE)                        \n            target = target.to(DEVICE)           \n            \n            pred = model(input_ids, attention_mask)                       \n\n            mse_sum += nn.MSELoss(reduction=\"sum\")(pred.flatten(), target).item()\n                \n\n    return mse_sum \/ len(data_loader.dataset)\ndef predict(model, data_loader):\n    \"\"\"Returns an np.array with predictions of the |model| on |data_loader|\"\"\"\n    model.eval()\n    result = np.zeros(len(data_loader.dataset))    \n    index = 0\n    with torch.no_grad():\n        for batch_num, (input_ids, attention_mask) in enumerate(data_loader):\n            input_ids = input_ids.to(DEVICE)\n            attention_mask = attention_mask.to(DEVICE)\n            pred = model(input_ids, attention_mask)                        \n            result[index : index + pred.shape[0]] = pred.flatten().to(\"cpu\")\n            index += pred.shape[0]\n    return result\ndef train(model, model_path, train_loader, val_loader,\n          optimizer, scheduler=None, num_epochs=NUM_EPOCHS):    \n    best_val_rmse = None\n    best_epoch = 0\n    step = 0\n    last_eval_step = 0\n    eval_period = EVAL_SCHEDULE[0][1]    \n    start = time.time()\n    for epoch in range(num_epochs):                           \n        val_rmse = None         \n        for batch_num, (input_ids, attention_mask, target) in enumerate(train_loader):\n            input_ids = input_ids.to(DEVICE)\n            attention_mask = attention_mask.to(DEVICE)            \n            target = target.to(DEVICE)                        \n            optimizer.zero_grad()\n            model.train()\n            pred = model(input_ids, attention_mask)\n            mse = nn.MSELoss(reduction=\"mean\")(pred.flatten(), target)\n            mse.backward()\n            optimizer.step()\n            if scheduler:\n                scheduler.step()\n            if step >= last_eval_step + eval_period:\n                elapsed_seconds = time.time() - start\n                num_steps = step - last_eval_step\n                last_eval_step = step\n                val_rmse = math.sqrt(eval_mse(model, val_loader))                            \n                for rmse, period in EVAL_SCHEDULE:\n                    if val_rmse >= rmse:\n                        eval_period = period\n                        break                               \n                if not best_val_rmse or val_rmse < best_val_rmse:                    \n                    best_val_rmse = val_rmse\n                    best_epoch = epoch\n                    torch.save(model.state_dict(), model_path)\n                    print(f\"New best_val_rmse: {best_val_rmse:0.4}\")\n                start = time.time()                       \n            step += 1\n    return best_val_rmse\ndef create_optimizer(model):\n    named_parameters = list(model.named_parameters())    \n    \n    roberta_parameters = named_parameters[:389]    \n    attention_parameters = named_parameters[391:395]\n    regressor_parameters = named_parameters[395:]\n        \n    attention_group = [params for (name, params) in attention_parameters]\n    regressor_group = [params for (name, params) in regressor_parameters]\n\n    parameters = []\n    parameters.append({\"params\": attention_group})\n    parameters.append({\"params\": regressor_group})\n\n    for layer_num, (name, params) in enumerate(roberta_parameters):\n        weight_decay = 0.0 if \"bias\" in name else 0.01\n\n        lr = 1.2e-5\n\n        if layer_num >= 133:        \n            lr = 3e-5\n\n        if layer_num >= 261:\n            lr = 7.5e-5\n\n        parameters.append({\"params\": params,\n                           \"weight_decay\": weight_decay,\n                           \"lr\": lr})\n\n    return AdamW(parameters)\n# del model\ngc.collect()\ntorch.cuda.empty_cache()\ngc.collect()\n\nSEED = 1000\nlist_val_rmse = []\n\nkfold = KFold(n_splits=NUM_FOLDS, random_state=SEED, shuffle=True)\n\nfor fold, (train_indices, val_indices) in enumerate(kfold.split(train_df)):    \n    print(f\"\\nFold {fold + 1}\/{NUM_FOLDS}\")\n    model_path = f\"model_{fold + 1}.pth\"\n        \n    set_random_seed(SEED + fold)\n    \n    train_dataset = LitDataset(train_df.loc[train_indices])    \n    val_dataset = LitDataset(train_df.loc[val_indices])    \n        \n    train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE,\n                              drop_last=True, shuffle=True, num_workers=2)    \n    val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE,\n                            drop_last=False, shuffle=False, num_workers=2)    \n        \n    set_random_seed(SEED + fold)    \n    \n    model = LitModel().to(DEVICE)\n    \n    optimizer = create_optimizer(model)                        \n    scheduler = get_cosine_schedule_with_warmup(\n        optimizer,\n        num_training_steps=NUM_EPOCHS * len(train_loader),\n        num_warmup_steps=50)    \n    \n    list_val_rmse.append(train(model, model_path, train_loader,\n                               val_loader, optimizer, scheduler=scheduler))\n\n    del model\n    gc.collect()\n    torch.cuda.empty_cache()\n\n    \nprint(\"\\nPerformance estimates:\")\nprint(list_val_rmse)\nprint(\"Mean:\", np.array(list_val_rmse).mean())\n# 0.474","meta":"{'source': 'AI4Code', 'id': '2da938d49fac40'}"}
{"id":"134167","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\"\"\"\n# Let's read data!\n\"\"\"\n\"\"\"\n**There are 110527 rows & 14 features.**\n\"\"\"\ndf = pd.read_csv('..\/input\/noshowappointments\/KaggleV2-May-2016.csv')\nprint('Count of rows', str(df.shape[0]))\nprint('Count of Columns', str(df.shape[1]))\ndf.head()\ndf.describe()\n\"\"\"\n**There is no null(NAN) values in dataset which is good! :)**\n\"\"\"\ndf.isnull().any().any()\n\"\"\"\n**Checking how pandas read datatypes in that dataframe**\n\"\"\"\ndf.info()\n\"\"\"\n**Check unique values in features. So, we can choose right methods to encode features.**\n\"\"\"\nfor i in df.columns:\n    print(i+\":\",len(df[i].unique()))\n\"\"\"\n**There are 110527 rows & all values in \"AppointmentID\" feature is unique. So, we do not need that feature because in every appointment there is an unique appointment ID even it's same person who looks for.**\n\"\"\"\ndf.drop('AppointmentID', axis=1,inplace = True)\n\"\"\"\n# Preprocess\n## PatientID: Float -> String (we are going to assume that feature like it's categorical)\n## No-show: String -> Integer (categorical feature)\n## Gender: String -> Integer (categorical feature)\n\"\"\"\ndf\ndf['PatientId'] = df['PatientId'].apply(int).apply(str)\ndf['Handcap'] = df['Handcap'].apply(lambda x: 0 if x == 0 else 1)\ndf['No-show'] = df['No-show'].map({'No':0, 'Yes':1})\ndf['Gender'] = df['Gender'].map({'F':0, 'M':1})\n\"\"\"\n## We also have to parse dates to correctly classify the data.\n## Let's convert it to datetime object for both \"ScheduledDay\" & \"AppointmentDay\"\n\"\"\"\ndf['ScheduledDay'] = pd.to_datetime(df['ScheduledDay']).dt.strftime('%Y-%m-%d')\ndf['ScheduledDay'] = pd.to_datetime(df['ScheduledDay'])\ndf['ScheduledDay']\ndf['AppointmentDay'] = pd.to_datetime(df['AppointmentDay']).dt.strftime('%Y-%m-%d')\ndf['AppointmentDay'] = pd.to_datetime(df['AppointmentDay'])\ndf['AppointmentDay']\n\"\"\"\n## There can be a time between Appointment Day and Scheduled Day which can be a good feature to classify. \n## So, let's create that feature\n\"\"\"\ndf['Day_diff'] = (df['AppointmentDay'] - df['ScheduledDay']).dt.days\ndf['Day_diff'].unique()\n\"\"\"\n## To give the data a classifier we have to digitilaze that features. \n## Let's seperate the date columns into year, month, day. (Also, weekday and season column can be added but I did not used it here)\n\"\"\"\ndf['ScheduledDay_Y'] = df['ScheduledDay'].dt.year\ndf['ScheduledDay_M'] = df['ScheduledDay'].dt.month\ndf['ScheduledDay_D'] = df['ScheduledDay'].dt.day\ndf.drop(['ScheduledDay'], axis=1, inplace=True)\n\ndf['AppointmentDay_Y'] = df['AppointmentDay'].dt.year\ndf['AppointmentDay_M'] = df['AppointmentDay'].dt.month\ndf['AppointmentDay_D'] = df['AppointmentDay'].dt.day\ndf.drop(['AppointmentDay'], axis=1, inplace=True)\n\"\"\"\n## There are negative integers in Age column which is not possible, so easyly drop them.\n\"\"\"\ndf.drop(df[df['Age'] < 0].index, inplace = True)\n\"\"\"\n## Neighbourhood: str -> integer (Categorical)\n## PatientId: integer -> Categorical Integer (Categorical)\n\"\"\"\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\ndf['Neighbourhood'] = le.fit_transform(df['Neighbourhood'])\nle = preprocessing.LabelEncoder()\ndf['PatientId'] = le.fit_transform(df['PatientId'])\n\"\"\"\n# Now, our dataframe is ready to split & classify. It's all digitized.\n\"\"\"\ndf\n\"\"\"\n## Last Check\n\"\"\"\ndf.info()\n\"\"\"\n## Split dataframe into train and test\n\"\"\"\nX = df.drop(['No-show'], axis=1)\ny = df['No-show']\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)\n\"\"\"\n## Let's classify the dataset into a few classifiers.\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import classification_report\nlr = LogisticRegression(solver='liblinear')\nlr.fit(X_train, y_train)\n\ny_pred_lr = lr.predict(X_test)\nclf_report = classification_report(y_test, y_pred_lr)\nprint(f\"Classification Report : \\n{clf_report}\")\nknn = KNeighborsClassifier()\nknn.fit(X_train, y_train)\n\ny_pred_knn = knn.predict(X_test)\n\nclf_report = classification_report(y_test, y_pred_knn)\nprint(f\"Classification Report : \\n{clf_report}\")\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train, y_train)\n\ny_pred_dtc = dtc.predict(X_test)\nclf_report = classification_report(y_test, y_pred_dtc)\n\nprint(f\"Classification Report : \\n{clf_report}\")\nrd_clf = RandomForestClassifier()\nrd_clf.fit(X_train, y_train)\n\ny_pred_rd_clf = rd_clf.predict(X_test)\nclf_report = classification_report(y_test, y_pred_rd_clf)\n\nprint(f\"Classification Report : \\n{clf_report}\")\nada = AdaBoostClassifier(base_estimator = dtc)\nada.fit(X_train, y_train)\n\ny_pred_ada = ada.predict(X_test)\nclf_report = classification_report(y_test, y_pred_ada)\n\nprint(f\"Classification Report : \\n{clf_report}\")\ngb = GradientBoostingClassifier()\ngb.fit(X_train, y_train)\n\ny_pred_gb = gb.predict(X_test)\nclf_report = classification_report(y_test, y_pred_gb)\n\nprint(f\"Classification Report : \\n{clf_report}\")\n\"\"\"\n## Average test set accuracy in these models is %80.\n## We did not scaled whole data. What changes if we scale whole data?\n## Let's try it!\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)\n\"\"\"\n## Even we scale the data into 0,1 the accuracy is not changed as expected!\n\"\"\"\nlr = LogisticRegression(solver='liblinear')\nlr.fit(X_train, y_train)\n\ny_pred_lr = lr.predict(X_test)\nclf_report = classification_report(y_test, y_pred_lr)\nprint(f\"Classification Report : \\n{clf_report}\")\n\"\"\"\n## Let's try a cross validation to validate our results.\n\"\"\"\nfrom sklearn.model_selection import cross_val_score\n\naccuracy = cross_val_score(estimator = lr, X = X, y =y, cv = 10)\nprint(\"avg acc: \",np.mean(accuracy))\nprint(\"acg std: \",np.std(accuracy))\n\"\"\"\n## As seen above, average test accuracy is 80% & average standard deviation is very low which is ok for now.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f6b7d8b2d35f16'}"}
{"id":"108368","text":"\"\"\"\n# <center>Ditching Excel for Python<\/center>\n\"\"\"\n\"\"\"\nAfter spending almost a decade with my first love Excel, its time to move on and search for a better half who in thick and thin of my daily tasks is with me and is much better and faster and who can give me a cutting edge in the challenging technological times where new technology is getting ditched by something new at a very rapid pace.\nThe idea is to replicate almost all excel functionalities in Python, be it using a simple filter or a complex task of creating an array of data from the rows and crunching them to get fancy results\n\"\"\"\n\"\"\"\nThe approach followed here is to start from simple tasks and move to complex computational tasks.\nI've tried and designed it such a way that this can be used a universal notebook and you just just have to change the input file and you can get the same result.\nHowever I will encourage you to please replicate the steps yourself for your better understanding.\n\"\"\"\n\"\"\"\nThe inspiration to create something like this came from the non-availablity of a free tutorial which literally gives all. I heavily read and follow Python documentation and you will find a lot of inspiration from that site.\n\"\"\"\n\"\"\"\n_Our Input and Ouput is both an Excel file :)_\n\"\"\"\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n## Importing Excel Files into a Pandas DataFrame\n\"\"\"\n\"\"\"\nInitial step is to import excel files into dtaframe so we can perform all our tasks on it.\n<br>I will be demonstrating the __read_excel__ method of Pandas which supports __xls__ and __xlsx__ file extensions.\n<br>__read_csv__ is same as using read_excel, we wont go in depth but I will share an example.\n\"\"\"\n\"\"\"\nThough __read_excel__ method includes million arguments but I will make you familiarise with the most common ones that will come very handy in day to day operations\n\"\"\"\n\"\"\"\nI'll be using the Iris sample dataset which is freely available online for educational purpose.\n<br>Please follow the below link to download the dataset and ensure to save it in the same folder where you are saving your python file\n\"\"\"\n\"\"\"\nhttps:\/\/archive.ics.uci.edu\/ml\/datasets\/iris\n\"\"\"\n\"\"\"\n## The first step is to import necessary libraries in Python\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\"\"\"\nWe can import the spreadsheet data into Python using the following code:\n\"\"\"\n\"\"\"\npandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, parse_cols=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skip_footer=0, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds)\n\"\"\"\n\"\"\"\nSince there's a plethora of arguments available, lets look at the most used one's.\n\"\"\"\n\"\"\"\n### Important Pandas read_excel Options\n\"\"\"\n\"\"\"\n|\tArgument\t|\tDescription\t|\n|\t\t-|\t\t|\n|\tio\t|\tA string containing the pathname of the given Excel file.\t|\n|\tsheet_name\t|\tThe Excel sheet name, or sheet number, of the data you want to import. The sheet number can be an integer where 0 is the first sheet, 1 is the second, etc. If a list of sheet names\/numbers are given, then the output will be a\u00a0dictionary of DataFrames. The default is to read all the sheets and output a dictionary of DataFrames.\t|\n|\theader\t|\tRow number to use for the list of column labels. The default is 0, indicating that the first row is assumed to contain the column labels. If the data does not have a row of column labels,\u00a0None\u00a0should be used.\t|\n|\tnames\t|\tA separate\u00a0Python list\u00a0input of column names. This option is\u00a0None\u00a0by default. This option is the equivalent of assigning a list of column names to the\u00a0columns attribute of the output DataFrame.\t|\n|\tindex_col\t|\tSpecifies which column should be used for row indices. The default option is\u00a0None, meaning that all columns are included in the data, and a range of numbers is used as the row indices.\t|\n|\tusecols\t|\tAn integer, list of integers, or string that specifies the columns to be imported into the DataFrame. The default is to import all columns. If a string is given, then Pandas uses the standard Excel format to select columns (e.g. \"A:C,F,G\" will import columns A, B, C, F, and G).\t|\n|\tskiprows\t|\tThe number of rows to skip at the top of the Excel sheet. Default is 0. This option is useful for skipping rows in Excel that contain explanatory information about the data below it.\t|\n\n\"\"\"\n\"\"\"\nIf we are using the path for our local file by default its separated by \"\\\" however python accepts \"\/\", \nso make to change the slashes or simply add the file in the same folder where your python file is.\nShould you require detailed explanation on the above, refer to the below medium article.\nhttps:\/\/medium.com\/@ageitgey\/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f\n\"\"\"\n\"\"\"\nWe can use Python to scan files in a directory and pick out the ones we want.\n\"\"\"\nwkbks = glob(os.path.join(os.pardir, 'input', 'xlsx_files_all', 'Ir*.xls'))\nsorted(wkbks)\nfilename = 'Iris.xlsx'\ndf = pd.read_excel(filename)\nprint(df)\n\"\"\"\n## Import a specifc sheet\n\"\"\"\n\"\"\"\nBy default, the first sheet in the file is imported to the dataframe as it is.\n<br>Using the sheet_name argument we can explicitly mention the sheet that we want to import. Defuat value is 0 i.e. teh first sheet in the file.\n    <br>We can either mention the name of the sheet(s) or pass an integer value to refer to the index of the sheet\n\"\"\"\ndf1 = pd.read_excel(filename,sheet_name='Sheet2')\nprint(df1)\n\"\"\"\n## Using a column from the sheet as an Index\n\"\"\"\n\"\"\"\nUnless explicitly mentioned, an index column is added to the dataframe which by default starts from a 0.\n<br>Using the index_col argumement we can manipulate the index column in our dataframe, if we set the value 0 from none, it will use the first column as our index.\n\"\"\"\ndf = pd.read_excel(filename,sheet_name='Sheet1', index_col=0)\nprint(df)\n\"\"\"\n## Skip rows and columns\n\"\"\"\n\"\"\"\nThe default read_excel parameters assumes that the first row is a list of column names, which is incorporated automatically as column labels within the DataFrame.\n<br>Using the arguments like skiprows and header we can manipulate the behaviour of the imported dataframe\n\"\"\"\ndf = pd.read_excel(filename, sheet_name='Sheet1', header=None, skiprows=1, index_col=0)\nprint(df)\n\"\"\"\n## Import a specifc column(s)\n\"\"\"\n\"\"\"\nUsing the usecols argument we can specify if we have import a specific column in our dataframe\n\"\"\"\ndf = pd.read_excel(filename, sheet_name='Sheet1', header=None, skiprows=1, usecols='B,D')\nprint(df)\ndf = pd.read_excel(filename)\n#Importing the file again to the dataframe in the original shape to use it for further analysis\n\"\"\"\n_Its not the end of the features available however its a start and you can play around with them as per your requirements_\n\"\"\"\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n## Lets have a look at the data from 10,000 feet\n\"\"\"\n\"\"\"\nAs now we have our dataframe, lets look at the data from multiple angles just to get a hang of it\/\n<br>Pandas have plenty of functions available that we can use. We'll use some of them to have a glimpse of our dataset.\n\"\"\"\n\"\"\"\n## \"Head\" to \"Tail\": \nTo view the first or last __five__ rows.\n<br>_Default is five, however the argument allows us to use a specific number_\n\"\"\"\ndf.head(10)\ndf.tail()\n\"\"\"\n## View specific column's data\n\"\"\"\ndf['SepalLength'].head()\n\"\"\"\n## Getting the name of all columns\n\"\"\"\ndf.columns\n\"\"\"\n## Info Method\nGives a summary of Dataframe\n\"\"\"\ndf.info()\n\"\"\"\n## Shape Method\nReturns the dimensions of Dataframe\n\"\"\"\ndf.shape[0]\nprint('Total rows in Dataframe is: ',  df.shape[0])\nprint('Total columns in Dataframe is: ',  df.shape[0])\n\"\"\"\n## Look at the datatypes in Dataframe\n\"\"\"\ndf.dtypes\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n# Slice and Dice i.e. Excel filters\n\"\"\"\n\"\"\"\nDescriptive reporting is all about data subsets and aggregations, the moment we are to understand our data a little bit we start using filters to look at the smaller sets of data or view a particular column maybe to have a better understanding.\n<br>Python offers a lot of different methods to slice and dice the dataframes, we'll play around with a couple of them to have an understanding of how it works\n\"\"\"\n\"\"\"\n## View a specific column\n\"\"\"\n\"\"\"\nThere exists three main methods to select columns:\n\n* Use dot notation: e.g. data.column_name\n* Use square braces and the name of the column:, e.g. data['column_name']\n* Use numeric indexing and the iloc selector data.loc[:, 'column_number']\n\"\"\"\ndf['Name'].head()\ndf.iloc[:,[4]].head()\ndf.loc[:,['Name']].head()\n\"\"\"\n## View multiple columns\n\"\"\"\ndf[['Name', 'PetalLength']].head()\n#Pass a variable as a list\nSpecificColumnList = ['Name', 'PetalLength']\ndf[SpecificColumnList].head()\n\"\"\"\n## View specific row's data\nThe method used here is slicing using the loc function, where we can specify the start and end row separated by colon\n<br>Remember, __index starts from a 0 and not 1__\n\"\"\"\ndf.loc[20:30] \n\"\"\"\n## Slice rows and columns together\n\"\"\"\ndf.loc[20:30, ['Name']]\n\"\"\"\n## Filter data in a column\n\"\"\"\ndf[df['Name'] == 'Iris-versicolor'].head()\n\"\"\"\n## Filter multiple values\n\"\"\"\ndf[df['Name'].isin(['Iris-versicolor', 'Iris-virginica'])]\n\"\"\"\n## Filter multiple values using a list\n\"\"\"\nFilter_Value = ['Iris-versicolor', 'Iris-virginica']\ndf[df['Name'].isin(Filter_Value)]\n\"\"\"\n## Filter values NOT in list or not equal to in Excel\n\"\"\"\ndf[~df['Name'].isin(Filter_Value)]\n\"\"\"\n## Filter usinng using multiple conditions in multiple columns\n__The input should always be a list__\n<br>We can use this method to replicate advanced filter function in excel\n\"\"\"\nwidth = [2]\nFlower_Name = ['Iris-setosa']\ndf[~df['Name'].isin(Flower_Name) & df['PetalWidth'].isin(width)]\n\"\"\"\n## Filter using numeric conditions\n\"\"\"\ndf[df['SepalLength'] == 5.1].head()\ndf[df['SepalLength'] > 5.1].head()\n\"\"\"\n## Replicate the custom filter in Excel\n\"\"\"\ndf[df['Name'].map(lambda x: x.endswith('sa'))]\n\"\"\"\n## Combine two filters to get the result\n\"\"\"\ndf[df['Name'].map(lambda x: x.endswith('sa')) & (df['SepalLength'] > 5.1)]\n\"\"\"\n## Contains function in Excel\n\"\"\"\ndf[df['Name'].str.contains('set')]\n\"\"\"\n## Get the unique values from dataframe\n\"\"\"\ndf['SepalLength'].unique()\n\"\"\"\nIf we want to view the entire dataframe with the unique values, we can use the drop_duplicates method\n\"\"\"\ndf.drop_duplicates(subset=['Name'])\ndf.drop_duplicates(subset=['Name']).iloc[:,[3,4]]\n\"\"\"\n## Sort Values\n\"\"\"\n\"\"\"\nSort data by a certain column, by default the sorting is ascending\n\"\"\"\ndf.sort_values(by = ['SepalLength'])\ndf.sort_values(by = ['SepalLength'], ascending = False)\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n# Statistical summary of data\n\"\"\"\n\"\"\"\n## __DataFrame Describe method:__ \n_Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset\u2019s distribution, excluding NaN values._\n\"\"\"\ndf.describe()\n\"\"\"\nSummary stats of character columns\n\"\"\"\ndf.describe(include = ['object'])\ndf.describe(include = 'all')\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n# <centre>Data Aggregation<\/centre>\n\"\"\"\n\"\"\"\n## Counting the unique values of a particular column. \n_Resulting output is a Series. You can refer it as a Single column Pivot Table_\n\"\"\"\npd.value_counts(df['Name'])\n\"\"\"\n## Count cells\nCount non-NA cells for each column or row.\n\"\"\"\ndf.count(axis=0)\n\"\"\"\n## Sum\nSummarising the data to get a snapshot of either by rows or columns\n\"\"\"\ndf.sum(axis = 0) # 0 for column wise total\n\"\"\"\nIts replicates the method of adding a total column against each row\n\"\"\"\ndf.sum(axis =1) # row wise sum\n\"\"\"\n## Add a total column to the existing dataset\n\"\"\"\ndf['Total'] = df.sum(axis =1)\ndf.head()\n\"\"\"\n## Sum of specific columns, use the loc methos and pass the column names\n\"\"\"\ndf['Total_loc']=df.loc[:,['SepalLength', 'SepalWidth']].sum(axis=1)\ndf.head()\n\"\"\"\n## Or, we can use the below method\n\"\"\"\ndf['Total_DFSum']= df['SepalLength'] + df['SepalWidth']\ndf.head()\n\"\"\"\n### Don't like the new column, delete it using drop method\n\"\"\"\ndf.drop(['Total_DFSum'], axis = 1)\n\"\"\"\n## Adding sum-total beneath each column\n\"\"\"\nSum_Total = df[['SepalLength', 'SepalWidth', 'Total']].sum()\nSum_Total\nT_Sum = pd.DataFrame(data=Sum_Total).T\nT_Sum\nT_Sum = T_Sum.reindex(columns=df.columns)\nT_Sum\nRow_Total = df.append(T_Sum,ignore_index=True)\nRow_Total\n\"\"\"\nA lot has been done above, the approach that we are using is:\n* Sum_Total: Do the sum of columns\n* T_Sum: Convert the series output to dataframe and transpose\n* Re-index to add missing columns\n* Row_Total: append T_Sum to existing dataframe\n\"\"\"\n\"\"\"\n## Sum based on criteria i.e. Sumif in Excel\n\"\"\"\ndf[df['Name'] == 'Iris-versicolor'].sum()\n\"\"\"\n## Sumifs\n\"\"\"\ndf[df['Name'].map(lambda x: x.endswith('sa')) & (df['SepalLength'] > 5.1)].sum()\n\"\"\"\n## Averageif\n\"\"\"\ndf[df['Name'] == 'Iris-versicolor'].mean()\n\"\"\"\n## Averageifs\n\"\"\"\ndf[df['Name'].map(lambda x: x.endswith('sa')) & (df['SepalLength'] > 5.1)].mean()\n\"\"\"\n## Max\n\"\"\"\ndf[df['Name'] == 'Iris-versicolor'].max()\n\"\"\"\n## Min\n\"\"\"\ndf[df['Name'] == 'Iris-versicolor'].min()\n\"\"\"\n# Groupby i.e. Subtotals in Excel\n\"\"\"\ndf[['Name','SepalLength']].groupby('Name').sum()\nGroupBy = df.groupby('Name').sum()\nGroup_By.append(pd.DataFrame(df[['SepalLength','SepalWidth','PetalLength','PetalWidth']].sum()).T)\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n# Pivot Tables in Dataframes i.e. Pivot Tables in Excel\n\"\"\"\n\"\"\"\nWho doesn'l love a Pivot Table in Excel, its one the best ways to analyse your data, have a quick overview of the information, helps you slice and dice the data with a super easy interface, helps you plots graphs basis on the data, add calculative columns etc.\n<br>No, we wont have an interface to work, we'll have to explicitly write the code to get the output, No, it wont generate charts for you, but I don't think we can complete a tutorial without learning about the Pivot tables.\n\"\"\"\npd.pivot_table(df, index= 'Name')#Same as Groupby\npd.pivot_table(df, values='SepalWidth', index= 'SepalLength',columns='Name', aggfunc = np.sum)\n\"\"\"\nA simple Pivot table showing us the sum of SepalWidth in values, SepalLength in Row Column and Name in Column Labels\n\"\"\"\n\"\"\"\nLets see if we can complicate it a bit.\n\"\"\"\npd.pivot_table(df, values='SepalWidth', index= 'SepalLength',columns='Name', aggfunc = np.sum, fill_value=0)\n\"\"\"\nBlanks are now replaced with 0's by using the fill_value argument\n\"\"\"\npd.pivot_table(df, values=['SepalWidth', 'PetalWidth'], index= 'SepalLength',columns='Name', aggfunc = np.sum, fill_value=0)\npd.pivot_table(df, values=['SepalWidth', 'PetalWidth'], index= ['SepalLength', 'PetalLength'],columns='Name', aggfunc = np.sum, fill_value=0)\npd.pivot_table(df, values=['SepalWidth', 'PetalWidth'], index= 'SepalLength',columns='Name', \n               aggfunc = {'SepalWidth': np.sum, 'PetalWidth': np.mean}, fill_value=0)\n\"\"\"\nWe can have individual calculations on values using dictionary method and can also have multiple calculations on values\n\"\"\"\npd.pivot_table(df, values=['SepalWidth', 'PetalWidth'], index= 'SepalLength',columns='Name', \n               aggfunc = {'SepalWidth': np.sum, 'PetalWidth': np.mean}, fill_value=0, margins=True)\n\"\"\"\nIf we use margins argument, we can have total row added\n\"\"\"\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\n# Vlookup\n\"\"\"\n\"\"\"\nWhat a magical formula is vlookup in Excel, I think its the first thing that everyone wants to learn before learning how to even add. Looks fascinating when someone is applying vlookup, looks like magic when we get the output. Makes life easy. I can with very much confidence can say its the backbone of every data wrangling action performed on the spreadsheet.\n<br>\n<br>__Unfortunately__ we dont have a vlookup function in Pandas!\n<br>\n<br>Since we dont have a \"Vlookup\" function in Pandas, Merge is used as an alternate which is same as SQL. There are a total of four merge options available:\n* \u2018left\u2019\u200a\u2014\u200aUse the shared column from the left dataframe and match to right dataframe. Fill in any N\/A as NaN\n\n* \u2018right\u2019\u200a\u2014\u200aUse the shared column from the right dataframe and match to left dataframe. Fill in any N\/A as NaN\n\n* \u2018inner\u2019\u200a\u2014\u200aOnly show data where the two shared columns overlap. Default method.\n\n* \u2018outer\u2019\u200a\u2014\u200aReturn all records when there is a match in either left or right dataframe.\n<br>\n\"\"\"\ndf1 = pd.read_excel(filename)\nlookup = df.merge(df,on='Name')\nlookup\n\"\"\"\nThe above might not be the best example to suppport the concept, however the working is the same.\n\"\"\"\n\"\"\"\n<pre>------------------------------------------------------------------------------------------<\/pre>\n\"\"\"\n\"\"\"\nI am hoping this tutorial made some sense, though I agree this could have been more elaborative which I will be pursuing soon.\n<br>__Watch out the space for more of it.__\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c734625cd04089'}"}
{"id":"7434","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom datetime import datetime\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn import linear_model\nfrom sklearn.linear_model import LogisticRegression\nimport lightgbm as lgb\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\npaths = []\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        paths.append(os.path.join(dirname, filename))\n        #print(os.path.join(dirname, filename))\n        \nsorted(paths)\n\"\"\"\n# Load Data\n\"\"\"\ntrain_df = pd.read_csv(sorted(paths)[10])\ntest_df = pd.read_csv(sorted(paths)[9])\nsubmission = pd.read_csv(sorted(paths)[8])\npopulation = pd.read_csv(sorted(paths)[11])\ncountry_stats = pd.read_csv(sorted(paths)[7])\nage_by_countries = pd.read_csv(sorted(paths)[1])\nhealth_index = pd.read_csv(sorted(paths)[3])\ntrain_df.head()\ntest_df.head()\nsubmission.head()\npopulation.head()\ncountry_stats.head()\nage_by_countries.head()\nhealth_index.head()\n\"\"\"\n# Feature engineering\n\"\"\"\npopulation_countries = population['Country (or dependency)'].unique()\n\ncountry_stats['Country'] = country_stats['Country'].apply(lambda x: x.replace(x[-1],''))\nstats_countries = country_stats['Country'].unique()\n\nage_countries = age_by_countries['Country'].unique()\nhealth_countries = health_index['Country'].unique()\nt_cols = train_df.columns\nt_cols\ncountries = train_df[t_cols[2]].unique()\ntest_countries = test_df[t_cols[2]].unique()\nnot_in_countries = []\nfor country in countries:\n    if country not in population_countries:\n        not_in_countries.append(country)\n        \nnot_in_countries_stats = []\nfor country in countries:\n    if country not in stats_countries:\n        not_in_countries_stats.append(country)\n        \nnot_in_countries_age = []\nfor country in countries:\n    if country not in age_countries:\n        not_in_countries_age.append(country)\n        \nnot_in_countries_health = []\nfor country in countries:\n    if country not in health_countries:\n        not_in_countries_health.append(country)\n#for item in health_countries:\n#    if 'Ad' in item:\n#        print(item)\n#for i in range(len(not_in_countries_health)):\n#    for item in health_countries:\n#        if not_in_countries_health[i][:4] in item:\n#            print(item)\nstats_countries_map = {'Antigua&Barbuda': 'Antigua and Barbuda',\n                       'Bahamas,The': 'Bahamas',\n                       'Bosnia&Herzegovina': 'Bosnia and Herzegovina',\n                       'BurkinaFaso': 'Burkina Faso',\n                       'CapeVerde': 'Cabo Verde',\n                       'CentralAfricanRep.': 'Central African Republic',\n                       'Congo,Dem.Rep.': 'Congo (Kinshasa)',\n                       'Congo,Repub.ofthe': 'Congo (Brazzaville)',\n                       'CostaRica': 'Costa Rica',\n                       \"Coted'Ivoire\": \"Cote d'Ivoire\",\n                       'CzechRepublic': 'Czechia',\n                       'DominicanRepublic': 'Dominican Republic',\n                       'ElSalvador': 'El Salvador',\n                       'EquatorialGuinea': 'Equatorial Guinea',\n                       'Swaziland': 'Eswatini',\n                       'Gambia,The': 'Gambia',\n                       'Korea,South': 'Korea, South',\n                       'NewZealand': 'New Zealand',\n                       'Macedonia': 'North Macedonia',\n                       'PapuaNewGuinea': 'Papua New Guinea',\n                       'SaintKitts&Nevis': 'Saint Kitts and Nevis',\n                       'SaintLucia': 'Saint Lucia',\n                       'SaintVincentandtheGrenadines': 'Saint Vincent and the Grenadines',\n                       'SanMarino': 'San Marino',\n                       'SaudiArabia': 'Saudi Arabia',\n                       'SouthAfrica': 'South Africa',\n                       'SriLanka': 'Sri Lanka',\n                       'Taiwan': 'Taiwan*',\n                       'EastTimor': 'Timor-Leste',\n                       'Trinidad&Tobago': 'Trinidad and Tobago',\n                       'UnitedStates': 'US',\n                       'UnitedArabEmirates': 'United Arab Emirates',\n                       'UnitedKingdom': 'United Kingdom'}\n\nmap_state_rev_stat = {k: v for k, v in stats_countries_map.items()}\ncountry_map = {'United States': 'US',\n               'Czech Republic (Czechia)': 'Czechia',\n               'Congo': 'Congo (Brazzaville)',\n               'DR Congo': 'Congo (Kinshasa)',\n               'South Korea': 'Korea, South',\n               'Taiwan': 'Taiwan*',\n               \"C\u00f4te d'Ivoire\": \"Cote d'Ivoire\",\n               'Saint Kitts & Nevis': 'Saint Kitts and Nevis',\n               'St. Vincent & Grenadines': 'Saint Vincent and the Grenadines'}\n\nmap_state_rev = {k: v for k, v in country_map.items()}\ncountry_age_map = {'Cape Verde': 'Cabo Verde',\n                   'Democratic Republic of the Congo': 'Congo (Kinshasa)',\n                   'Republic of the Congo': 'Congo (Brazzaville)',\n                   'Czech Republic': 'Czechia',\n                   'Eswatini (Swaziland)': 'Eswatini',\n                   'South Korea': 'Korea, South',\n                   'Taiwan': 'Taiwan*',\n                   'United States': 'US'}\n\nmap_state_rev_age = {k: v for k, v in country_age_map.items()}\nhealth_countries_map = {'Bosnia And Herzegovina': 'Bosnia and Herzegovina',\n                        'Czech Republic': 'Czechia',\n                        'South Korea': 'Korea, South',\n                        'Taiwan': 'Taiwan*',\n                        'Trinidad And Tobago': 'Trinidad and Tobago'}\n\nmap_state_rev_health = {k: v for k, v in health_countries_map.items()}\npopulation['New_country_name'] = population['Country (or dependency)'].apply(lambda x: country_map[x] if x in\n                                                                             map_state_rev else x)\n\ncountry_stats['New_country_name'] = country_stats['Country'].apply(lambda x: stats_countries_map[x] if x in\n                                                                  map_state_rev_stat else x)\n\nage_by_countries['New_country_name'] = age_by_countries['Country'].apply(lambda x: country_age_map[x] if x in\n                                                                  map_state_rev_age else x)\n\nhealth_index['New_country_name'] = health_index['Country'].apply(lambda x: health_countries_map[x] if x in\n                                                                  map_state_rev_health else x)\nhealth_care_idx = {}\nhealth_care_exp_idx = {}\n\nfor item in set(health_index['New_country_name']):\n    health_care_idx[item] = health_index.loc[health_index['New_country_name'] == item, 'Health Care Index'].values[0]\n    health_care_exp_idx[item] = health_index.loc[health_index['New_country_name'] == item, 'Health Care Exp. Index'].values[0]\npop = {}\ndens = {}\nl_area = {}\nage = {}\nurban_pop = {}\n\nfor item in set(population['New_country_name']):\n    pop[item] = population.loc[population['New_country_name'] == item, 'Population (2020)'].values[0]\n    dens[item] = population.loc[population['New_country_name'] == item, 'Density (P\/Km\u00b2)'].values[0]\n    l_area[item] = population.loc[population['New_country_name'] == item, 'Land Area (Km\u00b2)'].values[0]\n    age[item] = population.loc[population['New_country_name'] == item, 'Med. Age'].values[0]\n    urban_pop[item] = population.loc[population['New_country_name'] == item, 'Urban Pop %'].values[0]\nfor key, val in urban_pop.items():\n    if val != 'N.A.':\n        urban_pop[key] = int(val.replace('%', '')) \/ 100\n    else:\n        urban_pop[key] = -1\ncoastline = {}\ninf_mort = {}\ngdp = {}\nliteracy = {}\nphones = {}\narable = {}\ncrops = {}\nother = {}\nclimate = {}\nbirhrate = {}\ndeathrate = {}\nagri = {}\nindustry = {}\nservice = {}\n\nfor item in set(country_stats['New_country_name']):\n    coastline[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Coastline (coast\/area ratio)'].values[0]\n    inf_mort[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Infant mortality (per 1000 births)'].values[0]\n    gdp[item] = country_stats.loc[country_stats['New_country_name'] == item, 'GDP ($ per capita)'].values[0]\n    literacy[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Literacy (%)'].values[0]\n    phones[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Phones (per 1000)'].values[0]\n    arable[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Arable (%)'].values[0]\n    crops[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Crops (%)'].values[0]\n    other[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Other (%)'].values[0]\n    climate[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Climate'].values[0]\n    birhrate[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Birthrate'].values[0]\n    deathrate[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Deathrate'].values[0]\n    agri[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Agriculture'].values[0]\n    industry[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Industry'].values[0]\n    service[item] = country_stats.loc[country_stats['New_country_name'] == item, 'Service'].values[0]\ntrain_df['Population'] = train_df['Country_Region'].map(pop)\ntrain_df['Density'] = train_df['Country_Region'].map(dens)\ntrain_df['Land_Area'] = train_df['Country_Region'].map(l_area)\ntrain_df['Med_Age'] = train_df['Country_Region'].map(age)\ntrain_df['Urban_Pop'] = train_df['Country_Region'].map(urban_pop)\ntrain_df['Coastline'] = train_df['Country_Region'].map(coastline)\ntrain_df['Infant_mortality'] = train_df['Country_Region'].map(inf_mort)\ntrain_df['GDP'] = train_df['Country_Region'].map(gdp)\ntrain_df['Literacy'] = train_df['Country_Region'].map(literacy)\ntrain_df['Phones'] = train_df['Country_Region'].map(phones)\ntrain_df['Arable'] = train_df['Country_Region'].map(arable)\ntrain_df['Crops'] = train_df['Country_Region'].map(crops)\ntrain_df['Other'] = train_df['Country_Region'].map(other)\ntrain_df['Climate'] = train_df['Country_Region'].map(climate)\ntrain_df['Birthrate'] = train_df['Country_Region'].map(birhrate)\ntrain_df['Deathrate'] = train_df['Country_Region'].map(deathrate)\ntrain_df['Agriculture'] = train_df['Country_Region'].map(agri)\ntrain_df['Industry'] = train_df['Country_Region'].map(industry)\ntrain_df['Service'] = train_df['Country_Region'].map(service)\ntrain_df['Health_Care_Index'] = train_df['Country_Region'].map(health_care_idx)\ntrain_df['Health_Care_Exp_Index'] = train_df['Country_Region'].map(health_care_exp_idx)\n\ntest_df['Population'] = test_df['Country_Region'].map(pop)\ntest_df['Density'] = test_df['Country_Region'].map(dens)\ntest_df['Land_Area'] = test_df['Country_Region'].map(l_area)\ntest_df['Med_Age'] = test_df['Country_Region'].map(age)\ntest_df['Urban_Pop'] = test_df['Country_Region'].map(urban_pop)\ntest_df['Coastline'] = test_df['Country_Region'].map(coastline)\ntest_df['Infant_mortality'] = test_df['Country_Region'].map(inf_mort)\ntest_df['GDP'] = test_df['Country_Region'].map(gdp)\ntest_df['Literacy'] = test_df['Country_Region'].map(literacy)\ntest_df['Phones'] = test_df['Country_Region'].map(phones)\ntest_df['Arable'] = test_df['Country_Region'].map(arable)\ntest_df['Crops'] = test_df['Country_Region'].map(crops)\ntest_df['Other'] = test_df['Country_Region'].map(other)\ntest_df['Climate'] = test_df['Country_Region'].map(climate)\ntest_df['Birthrate'] = test_df['Country_Region'].map(birhrate)\ntest_df['Deathrate'] = test_df['Country_Region'].map(deathrate)\ntest_df['Agriculture'] = test_df['Country_Region'].map(agri)\ntest_df['Industry'] = test_df['Country_Region'].map(industry)\ntest_df['Service'] = test_df['Country_Region'].map(service)\ntest_df['Health_Care_Index'] = test_df['Country_Region'].map(health_care_idx)\ntest_df['Health_Care_Exp_Index'] = test_df['Country_Region'].map(health_care_exp_idx)\ntrain_df['Urban_pop_num'] = train_df[['Population', 'Urban_Pop']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['Urban_pop_num'] = test_df[['Population', 'Urban_Pop']].apply(lambda x: x[0]*x[1], axis=1)\nage_cols = ['Age 0 to 14 Years', 'Age 15 to 64 Years', 'Age above 65 Years']\nfor item in age_cols:\n    for i in range(len(age_by_countries)):\n        if type(age_by_countries[item][i]) == str:\n            age_by_countries[item][i] = age_by_countries[item][i].replace('%','')\n            age_by_countries[item][i] = float(age_by_countries[item][i]) \/ 100\nage_014 = {}\nage_1564 = {}\nage_65plus = {}\n\nfor item in set(age_by_countries['New_country_name']):\n    age_014[item] = age_by_countries.loc[age_by_countries['New_country_name'] == item, 'Age 0 to 14 Years'].values[0]\n    age_1564[item] = age_by_countries.loc[age_by_countries['New_country_name'] == item, 'Age 15 to 64 Years'].values[0]\n    age_65plus[item] = age_by_countries.loc[age_by_countries['New_country_name'] == item, 'Age above 65 Years'].values[0]\ntrain_df['age_0-14'] = train_df['Country_Region'].map(age_014)\ntrain_df['age_15-64'] = train_df['Country_Region'].map(age_1564)\ntrain_df['age_65plus'] = train_df['Country_Region'].map(age_65plus)\n\ntest_df['age_0-14'] = test_df['Country_Region'].map(age_014)\ntest_df['age_15-64'] = test_df['Country_Region'].map(age_1564)\ntest_df['age_65plus'] = test_df['Country_Region'].map(age_65plus)\ntrain_df = train_df.fillna(-1)\ntest_df = test_df.fillna(-1)\ndef time_feat(df, start_day):\n    start_day = datetime.strptime(start_day, '%Y-%m-%d').date()\n    df['Date_time'] = df['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d').date())\n    df['Time_delta'] = df['Date_time'].apply(lambda x: (x - start_day).days)\n    #df['Weekday'] = df['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d').weekday())\n    #df['Day_of_month'] = df['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d').day)\n    df['Month'] = df['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d').month)\n    \n    return df\ntrain_df = time_feat(train_df, '2020-01-22')\ntest_df = time_feat(test_df, '2020-01-22')\ncols = train_df.columns\ncols\ndef to_str(x):\n    if x == -1:\n        return str(x)\n    return x\ntrain_df['Province_State'] = train_df['Province_State'].apply(lambda x: to_str(x))\ntest_df['Province_State'] = test_df['Province_State'].apply(lambda x: to_str(x))\nfeatures=['Province_State', 'Country_Region', 'Population', 'Density', 'Land_Area', 'Med_Age',\n          'Urban_Pop', 'Coastline', 'Infant_mortality', 'GDP', 'Literacy',\n          'Phones', 'Arable', 'Crops', 'Other', 'Climate', 'Birthrate', 'Health_Care_Index', \n          'Health_Care_Exp_Index','Deathrate', 'Agriculture', 'Industry', 'Service', 'Urban_pop_num',\n          'Time_delta', 'Month', 'age_0-14', 'age_15-64', 'age_65plus']\n\ntrain_X = train_df[features + ['ConfirmedCases', 'Fatalities']].copy()\ntrain_yc = train_df['ConfirmedCases'].copy()\ntrain_yf = train_df['Fatalities'].copy()\nfor i in range(len(train_X)):\n    if train_X['Med_Age'][i] == 'N.A.':\n            train_X['Med_Age'][i] = -1\n            \nfor feature in features:\n    for i in range(len(test_df)):\n        if test_df[feature][i] == 'N.A.':\n            test_df[feature][i] = -1\nfor item in test_df[cols[2]].unique():\n    if item not in train_df[cols[2]].unique():\n        print(item)\nenc1 = OrdinalEncoder()\nenc2 = OrdinalEncoder()\nenc1.fit(train_X[cols[1]].to_numpy().reshape(-1, 1))\nenc2.fit(train_X[cols[2]].to_numpy().reshape(-1, 1))\ntrain_X[cols[1]] = enc1.transform(train_X[cols[1]].to_numpy().reshape(-1, 1))\ntrain_X[cols[2]] = enc2.transform(train_X[cols[2]].to_numpy().reshape(-1, 1))\ntest_df[cols[1]] = enc1.transform(test_df[cols[1]].to_numpy().reshape(-1, 1))\ntest_df[cols[2]] = enc2.transform(test_df[cols[2]].to_numpy().reshape(-1, 1))\ncheck_list = ['Coastline', 'Infant_mortality', 'GDP', 'Literacy','Phones', 'Arable', 'Crops', 'Other', \n              'Climate', 'Birthrate', 'Deathrate', 'Agriculture', 'Industry', 'Service']\n\nfor item in check_list:\n    for i in range(len(train_X)):\n        if type(train_X[item][i]) == str:\n            train_X[item][i] = train_X[item][i].replace(',','.')\n            train_X[item][i] = float(train_X[item][i])\n            \nfor item in check_list:\n    for i in range(len(test_df)):\n        if type(test_df[item][i]) == str:\n            test_df[item][i] = test_df[item][i].replace(',','.')\n            test_df[item][i] = float(test_df[item][i])\ntrain_X['Agri_pop_num'] = train_X[['Population', 'Agriculture']].apply(lambda x: x[0]*x[1], axis=1)\ntrain_X['Industry_pop_num'] = train_X[['Population', 'Industry']].apply(lambda x: x[0]*x[1], axis=1)\ntrain_X['Service_pop_num'] = train_X[['Population', 'Service']].apply(lambda x: x[0]*x[1], axis=1)\ntrain_X['age_0-14_num'] = train_X[['Population', 'age_0-14']].apply(lambda x: x[0]*x[1], axis=1)\ntrain_X['age_15-64_num'] = train_X[['Population', 'age_15-64']].apply(lambda x: x[0]*x[1], axis=1)\ntrain_X['age_65plus_num'] = train_X[['Population', 'age_65plus']].apply(lambda x: x[0]*x[1], axis=1)\n\ntest_df['Agri_pop_num'] = test_df[['Population', 'Agriculture']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['Industry_pop_num'] = test_df[['Population', 'Industry']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['Service_pop_num'] = test_df[['Population', 'Service']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['age_0-14_num'] = test_df[['Population', 'age_0-14']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['age_15-64_num'] = test_df[['Population', 'age_15-64']].apply(lambda x: x[0]*x[1], axis=1)\ntest_df['age_65plus_num'] = test_df[['Population', 'age_65plus']].apply(lambda x: x[0]*x[1], axis=1)\nfeatures = features + ['Agri_pop_num', 'Industry_pop_num', 'Service_pop_num', \n                       'age_0-14_num', 'age_15-64_num', 'age_65plus_num']\nfeatures.remove('Agriculture')\nfeatures.remove('Industry')\nfeatures.remove('Service')\nfeatures.remove('Urban_Pop')\nfeatures.remove('age_0-14')\nfeatures.remove('age_15-64')\nfeatures.remove('age_65plus')\n#features.remove('Weekday')\n#features.remove('Day_of_month')\n\"\"\"\n# Corellation matrix (Spearman)\n\"\"\"\nmatrix = train_X.corr(method='spearman')\nmask = np.triu(np.ones_like(matrix, dtype=np.bool))\nwith sns.axes_style(\"white\"):\n    f, ax = plt.subplots(figsize=(15, 12))\n    ax = sns.heatmap(matrix, mask=mask, annot=True, cmap=\"YlGnBu\",vmax=.3, square=True, linewidths=.4)\nplt.show();\n\"\"\"\n# Data scaling\n\"\"\"\nscaler = StandardScaler()\ntrain_X = scaler.fit_transform(train_X[features])\ntrain_X = pd.DataFrame(data=train_X, columns=features)\ntest = test_df[features].copy()\ntest = scaler.transform(test)\ntest = pd.DataFrame(data=test, columns=features)\n\"\"\"\n# Creation dataset for training SARIMAX model\n\"\"\"\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\ncount_len = len(train_df[train_df['Country_Region'] == 'Russia'])\n\ntrain_cc = []\ntrain_f = []\ncount = 0\nfor i in range(int(len(train_df) \/ count_len)):\n    train_cc.append(train_df.ConfirmedCases[count:count+count_len].values.tolist())\n    train_f.append(train_df.Fatalities[count:count+count_len].values.tolist())\n    count += count_len\nfrom datetime import date\ndelta = (datetime.today().date() - date(2020, 3, 26)).days\n#comp_start_delta = (datetime.today().date() - date(2020, 4, 2)).days - 1\n\"\"\"\n# SARIMAX models and preliminary predictions\nmodified concept from https:\/\/www.kaggle.com\/skeller\/arima-influenza-baselines\n\"\"\"\ntest_count = len(test_df[test_df['Country_Region'] == 0.0]) - delta - 1\npredicted_cc = []\n\nfor i in range(len(train_cc)):\n    data1 = train_cc[i]\n    model1 =  SARIMAX(data1, order=(1,1,0), seasonal_order=(1,1,0,12), measurement_error=True)\n    model1_fit = model1.fit(disp=False)\n    predicted1 = model1_fit.predict(len(data1), len(data1)+test_count)\n    predicted_cc.append(predicted1.tolist())\npredicted_f = []\nfor i in range(len(train_f)):\n    try:\n        data2 = train_f[i]\n        model2 =  SARIMAX(data2, order=(1,0,0), seasonal_order=(0,1,1,12), measurement_error=True)\n        model2_fit = model2.fit(disp=False)\n        predicted2 = model2_fit.predict(len(data2), len(data2)+test_count)\n        predicted_f.append(predicted2.tolist())\n    except:\n        print(i)\n        predicted2 = []\n        for j in range(test_count):\n            predicted2.append(train_f[i][-1]*1.5)\n        predicted_f.append(predicted2)\ncheck_lenght = len(train_cc[0][-delta:]) + len(predicted_cc[0])\nif check_lenght == 43:\n    print('Check OK')\nelse:\n    print('Check failed')\nimport itertools\n\npredicted_ConfirmedCases = []\npredicted_Fatalities = []\nfor i in range(int(len(train_df) \/ count_len)):\n    predicted_ConfirmedCases.append(train_cc[i][-delta:])\n    predicted_ConfirmedCases.append(predicted_cc[i])\n    predicted_Fatalities.append(train_f[i][-delta:])\n    predicted_Fatalities.append(predicted_f[i])\n    \npredicted_ConfirmedCases = list(itertools.chain.from_iterable(predicted_ConfirmedCases))\npredicted_Fatalities = list(itertools.chain.from_iterable(predicted_Fatalities))\n\"\"\"\n# Final FE\nAdd preliminary predictions of SARIMAX model to the test dataset\n\"\"\"\ntest['ConfirmedCases'] = predicted_ConfirmedCases\ntest['Fatalities'] = [int(x) for x in predicted_Fatalities]\ntrain_X['ConfirmedCases'] = train_df['ConfirmedCases']\ntrain_X['Fatalities'] = train_df['Fatalities']\ncc_feats = train_X.columns.to_list()\nfatal_feats = train_X.columns.to_list()\ncc_feats.remove('Fatalities')\nfatal_feats.remove('ConfirmedCases')\n\"\"\"\n# Predictions\n\"\"\"\ndef prediction(train_df, test_df, train_y, feats_list, n_splits, model_idx, disp=False):\n    models = [KNeighborsRegressor(n_neighbors=1, weights='distance', algorithm='auto', n_jobs=-1),\n             linear_model.LogisticRegression(random_state=17, max_iter=100, fit_intercept=False, n_jobs=-1),\n             linear_model.LinearRegression(fit_intercept=False, n_jobs=-1),\n             linear_model.Perceptron(),\n             linear_model.BayesianRidge(n_iter=1000, fit_intercept=False, lambda_init=0.0001),\n             linear_model.SGDRegressor(random_state=17)]\n    models_names = ['KNeighbors', 'LogRegression', 'LinRegression', 'Perceptron', 'Bayesian', 'SGDRegressor']\n    train = train_df[feats_list]\n    skf = StratifiedKFold(n_splits=n_splits, random_state=42)\n    score, preds = [], []\n    for i, (tdx, vdx) in enumerate(skf.split(train, train_y)):\n        if disp:\n            print(f'Fold : {i}')\n        X_train, X_val, y_train, y_val = train.iloc[tdx], train.iloc[vdx], train_y[tdx], train_y[vdx]\n        model = models[model_idx].fit(X_train, y_train)\n        val_preds = model.predict(X_val.to_numpy())\n        val_score = np.sqrt(mean_squared_log_error(y_val, abs(val_preds)))\n        if disp:\n            print(f'val_score_{models_names[model_idx]}: {val_score}')\n        score.append(val_score)\n        pred = model.predict(test_df[feats_list])\n        preds.append(abs(pred))\n    print(f'{models_names[model_idx]} {train_y.name} mean score: {np.mean(score)}')\n    print()\n    return np.vstack(preds), score\npred_c, score_c = prediction(train_X, test, train_yc, cc_feats, n_splits=306, model_idx=0, disp=False)\npred_f, score_f = prediction(train_X, test, train_yf, fatal_feats, n_splits=306, model_idx=0, disp=False)\n\"\"\"\n# KNeighbors mean train scoring\n\"\"\"\nc_mean = np.mean(score_c)\nf_mean = np.mean(score_f)\n(c_mean + f_mean) \/ 2\n\"\"\"\n# SARIMAX and KNeighbors averaging predictions\n\"\"\"\ncc_preds = np.mean((np.mean(pred_c, axis=0), predicted_ConfirmedCases), axis=0)\nf_preds = np.mean((np.mean(pred_f, axis=0), test.Fatalities), axis=0)\n\"\"\"\n# Submission\n\"\"\"\nsubmission['ConfirmedCases'] = cc_preds\nsubmission['Fatalities'] = f_preds\nsubmission.to_csv('submission.csv', index=False)\nsubmission.head()\n\"\"\"\n# Predictions example and some conclusions\n\"\"\"\nconcl_df = pd.read_csv(sorted(paths)[9])\nconcl_feats = ['ForecastId', 'Country_Region', 'Date']\nconclusion = pd.concat([concl_df[concl_feats], submission[['ConfirmedCases', 'Fatalities']]], axis=1)\n\"\"\"\n### Italy for example: \n\"\"\"\nregion = 'Italy'\nconclusion[conclusion['Country_Region'] == region]\nconclusion[conclusion['Country_Region'] == region]['ConfirmedCases'].plot(grid=True,\n                                                                          kind='density',\n                                                                          figsize=(14, 6),\n                                                                          title=region);\nconclusion[conclusion['Country_Region'] == region]['Fatalities'].plot(grid=True,\n                                                                      kind='density',\n                                                                      figsize=(14, 6),\n                                                                      title=region);\nconclusion[conclusion['Country_Region'] == region][['ConfirmedCases', \n                                                     'Fatalities', \n                                                     'Date']].plot(x='Date', grid=True, kind='line',\n                                                                    figsize=(14, 6), title=region);\nday_cc = conclusion[conclusion['Country_Region'] == region]['ConfirmedCases'].values\n\nperday_cc = []\nfor i in range(1, len(day_cc)):\n    perday_cc.append(day_cc[i] - day_cc[i-1])\n    \nperday_cc_df = pd.DataFrame(perday_cc, columns=['CC_per_day'])\nperday_cc_df['Date'] = conclusion[conclusion['Country_Region'] == region]['Date'].values[1:]\n\nperday_cc_df.plot(x='Date', y='CC_per_day', kind='bar', grid=True, figsize=(14, 6), title=region);\n\"\"\"\n# SARIMAX and KNeighbors predictions comparison\n\"\"\"\nmodel_preds_comparison = pd.DataFrame(data=conclusion[['Country_Region', 'Date', 'ConfirmedCases', 'Fatalities']].values, \n                                      columns=['Country_Region', 'Date', 'KN_ConfirmedCases', 'KN_Fatalities'])\nmodel_preds_comparison['SARIMAX_ConfirmedCases'] = test['ConfirmedCases']\nmodel_preds_comparison['SARIMAX_Fatalities'] = test['Fatalities']\nmodel_preds_comparison['CC_Diff'] = abs(model_preds_comparison['KN_ConfirmedCases'] - \n                                        model_preds_comparison['SARIMAX_ConfirmedCases'])\nmodel_preds_comparison['Fatal_Diff'] = abs(model_preds_comparison['KN_Fatalities'] - \n                                        model_preds_comparison['SARIMAX_Fatalities'])\nmodel_preds_comparison[model_preds_comparison['Country_Region'] == region][['KN_ConfirmedCases', \n                                                                            'KN_Fatalities',\n                                                                            'SARIMAX_ConfirmedCases',\n                                                                            'SARIMAX_Fatalities',\n                                                                            'Date']].plot(x='Date', \n                                                                                          grid=True, \n                                                                                          figsize=(14, 6), \n                                                                                          title=region);","meta":"{'source': 'AI4Code', 'id': '0dd359a7df0c38'}"}
{"id":"93774","text":"\"\"\"\nTable of content\n1. Import Required Libraries\n2. Load Data\n3. Data Information\n4. Check for null values\n5. EDA\n    1. Check Outliers\n    2. Univariant Analysis\n    3. Bivariant Analysis\n    4. Multivariant Analysis\n    5. Correlation\n6. Encode Categorical Variables\n7. Spliting Data\n8. Base Line Models\n    1. Logistic Regression\n    2. XGBoost Classifier\n    3. Random Forest Classifier\n    4. Gradient Boosting Classifier\n    5. Stacking Classifier\n9. Balancing target variable\n10. Feature Selection\n11. Dimentionality Reduction\n12. Hyper Parameter Tuning\n13. Best Model\n\"\"\"\n\"\"\"\n# Import Required Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, StackingClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom imblearn.combine import SMOTETomek\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.decomposition import PCA\n\n# display all columns of the dataframe\npd.options.display.max_columns = None\n\n# display all rows of the dataframe\npd.options.display.max_rows = None\n\n# use below code to convert the 'exponential' values to float\nnp.set_printoptions(suppress=True)\n\"\"\"\n# Load Data\n\"\"\"\ndf = pd.read_csv('..\/input\/arketing-campaign\/marketing_campaign.csv', sep=';')\ndf.head()\n# Dropping ID Column beacause we dont id column for predictions\ndf.drop('ID', axis=1, inplace = True)\n\"\"\"\n# Data Information\n\"\"\"\n# Shape of Dataset\nprint('Data contains', df.shape[0], 'rows and', df.shape[1], 'columns')\n# Dataset information about value count and variable data type\ndf.info()\n# Numerical Data Description\ndf.describe().T\n# Categorical Data Description\ndf.describe(include='O').T\n\"\"\"\n# Check for null values\n\"\"\"\n# Check for null values in the dataset\ndf.isnull().sum()\n\"\"\"\nOnly income column contains null values\n\"\"\"\n\"\"\"\n# Filling Null Values\n\"\"\"\ndef fill_na(frame):\n    for i in frame.columns:\n        if(((frame[i].isnull().sum() \/ len(frame))*100) <= 30) & (frame[i].dtype == 'int64'):\n            frame[i] = frame[i].fillna(frame[i].median())\n            \n        elif(((frame[i].isnull().sum() \/ len(frame))*100) <= 30) & (frame[i].dtype == 'O'):\n            frame[i] = frame[i].fillna(frame[i].mode()[0])\n            \n        elif(((frame[i].isnull().sum() \/ len(frame))*100) <= 30) & (frame[i].dtype == 'float64'):\n            frame[i] = frame[i].fillna(frame[i].median())\n            \nfill_na(df)\n\"\"\"\n# EDA\n\"\"\"\n\"\"\"\n# 1. Check Outliers\n\"\"\"\ndef detect_outliers(frame):\n    for i in frame.columns:\n        if(frame[i].dtype == 'int64'):\n            sns.boxplot(frame[i])\n            plt.show()\n            \n        elif(frame[i].dtype == 'float64'):\n            sns.boxplot(frame[i])\n            plt.show()\n            \ndetect_outliers(df)\n\"\"\"\n# 2. Univariant Analysis\n\"\"\"\ndef univariant(frame):\n    for i in frame.columns:\n        if(frame[i].dtype == 'int64'):\n            print(i)\n            sns.distplot(x=frame[i])\n            plt.show()\n                \n        elif(frame[i].dtype == 'float64'):\n            print(i)\n            sns.distplot(x=frame[i])\n            plt.show()\n            \nunivariant(df)\n# Plot Response variable seperately because our target variable(Class) is int and we have to treat it like object this time\nsns.countplot(df['Response'])\nplt.show()\n\"\"\"\nOur target variable(Response) is not balanced \n\"\"\"\n\"\"\"\n# 3. Multivariant Analysis\n\"\"\"\nsns.pairplot(df)\n\"\"\"\n# 4. Correlation\n\"\"\"\n# Check correlation between variables\nplt.figure(figsize=(30,25))\nsns.heatmap(df.corr(), annot=True)\n# Converting dt_Customer into datetime64 data type\ndf['Dt_Customer'] = df['Dt_Customer'].astype('datetime64')\n# Creating two new columns Date_customer and Month_customer from Dt_Customer column\ndf['Date_Customer'] = df['Dt_Customer'].dt.day\ndf['Month_Customer'] = df['Dt_Customer'].dt.month\ndf['Year_Customer'] = df['Dt_Customer'].dt.year\n# Now we can drop Dt_Customer column\ndf.drop('Dt_Customer', axis=1, inplace=True)\n\"\"\"\n# Encode Categorical Variables\n\"\"\"\ndef encode(dataframe):\n    lec = LabelEncoder()\n    for j in dataframe.columns:\n        if(dataframe[j].dtype == 'object'):\n            dataframe[j] = lec.fit_transform(dataframe[j])\n            \nencode(df)\n\"\"\"\n# Split data into train and test\n\"\"\"\nx = df.drop('Response', axis=1)\ny = df['Response']\n\nX_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.3, random_state=1)\n\"\"\"\n# Lets Build Models\n\"\"\"\n\"\"\"\n# Base Line Models\n\"\"\"\n\"\"\"\n# 1. Logistic Regression\n\"\"\"\nlr = LogisticRegression(max_iter=10000)\nlr.fit(X_train, Y_train)\nlr_pred = lr.predict(X_test)\nprint(classification_report(Y_test, lr_pred))\n\"\"\"\n# 2. XGBoost Classifier\n\"\"\"\nxgb = XGBClassifier()\nxgb.fit(X_train, Y_train)\nxgb_pred = xgb.predict(X_test)\nprint(classification_report(Y_test, xgb_pred))\n\"\"\"\n# 3. Random Forest Classifier\n\"\"\"\nrf = RandomForestClassifier()\nrf.fit(X_train, Y_train)\nrf_pred = rf.predict(X_test)\nprint(classification_report(Y_test, rf_pred))\n\"\"\"\n# 4. Gradient Boosting Classifier\n\"\"\"\ngb = GradientBoostingClassifier()\ngb.fit(X_train, Y_train)\ngb_pred = gb.predict(X_test)\nprint(classification_report(Y_test, gb_pred))\naccuracy_score(Y_test, gb_pred)\n\"\"\"\n# 5. Stacking Classifier\n\"\"\"\nestimators = [('xgb', XGBClassifier()),\n             ('rf', RandomForestClassifier()),\n             ('gb', GradientBoostingClassifier())]\nstack = StackingClassifier(estimators=estimators)\nstack.fit(X_train, Y_train)\nstack_pred = stack.predict(X_test)\nprint(classification_report(Y_test, stack_pred))\n\"\"\"\nFrom all my base line models Gradient Boosting Classifier gives best results\n\"\"\"\n\"\"\"\n# Balancing the target variable\n\"\"\"\nsmote = SMOTETomek()\nx_train, y_train = smote.fit_resample(X_train, Y_train)\n\"\"\"\nBuilding models again using new training sets \n\"\"\"\n\"\"\"\n# 1. Logistic Regression\n\"\"\"\nslr = LogisticRegression(max_iter=10000)\nslr.fit(x_train, y_train)\nslr_pred = slr.predict(X_test)\nprint(classification_report(Y_test, slr_pred))\n\"\"\"\n# 2. XGBoost Classifier\n\"\"\"\nsxgb = XGBClassifier()\nsxgb.fit(x_train, y_train)\nsxgb_pred = sxgb.predict(X_test)\nprint(classification_report(Y_test, sxgb_pred))\n\"\"\"\n# 3. Random Forest Classifier\n\"\"\"\nsrf = RandomForestClassifier()\nsrf.fit(x_train, y_train)\nsrf_pred = srf.predict(X_test)\nprint(classification_report(Y_test, srf_pred))\n\"\"\"\n# 4. Gradient Boosting Classifier\n\"\"\"\nsgb = GradientBoostingClassifier()\nsgb.fit(x_train, y_train)\nsgb_pred = sgb.predict(X_test)\nprint(classification_report(Y_test, sgb_pred))\nsstack = StackingClassifier(estimators=estimators)\nsstack.fit(x_train, y_train)\nsstack_pred = sstack.predict(X_test)\nprint(classification_report(Y_test, sstack_pred))\n\"\"\"\nModels after balancing the target variable gives good results. But if i them compare with base line models then base line model of Gradient Boosting Classifier give highest accuracy. So i further build my model with Gradient Boosting Classifier base line.\n\"\"\"\n\"\"\"\n# Feature Selection\n\"\"\"\nth = np.sort(gb.feature_importances_)\nl = []\nfor g in th:\n    select = SelectFromModel(gb, threshold = g, prefit = True)\n    x_Train = select.transform(X_train)\n    model = GradientBoostingClassifier()\n    model.fit(x_Train, Y_train)\n    x_Test = select.transform(X_test)\n    y_pred = model.predict(x_Test)\n    accuracy = accuracy_score(Y_test, y_pred)\n    print('Threshold:', g, 'Model Score:', accuracy)\nimp = pd.DataFrame(rf.feature_importances_)\nimp.index = X_train.columns\nimp[imp[0] < 0.017037885998921535]\nX_train = X_train.drop(['Z_CostContact', 'Z_Revenue'], axis=1)\nX_test = X_test.drop(['Z_CostContact', 'Z_Revenue'], axis=1)\n\"\"\"\n# Building model after feature selection\n\"\"\"\nfgb = GradientBoostingClassifier()\nfgb.fit(X_train, Y_train)\nfgb_pred = fgb.predict(X_test)\nprint(classification_report(Y_test, fgb_pred))\naccuracy_score(Y_test, fgb_pred)\n\"\"\"\nAfter feature selection i am getting same accuracy. So i further build model using base line\n\"\"\"\n\"\"\"\n# Dimentionality Reduction\n\"\"\"\n# First i check how many components we want\n# For this first i am initializing the pca\npca = PCA()\n# Fitting the training set in pca\npca.fit(X_train)\n# Now check number of components\npca.explained_variance_ratio_\n\"\"\"\nAs shown above our 99.97% data covers in 1 principal component\n\"\"\"\n# Creating pca with n_components = 15\nPca = PCA(n_components=15)\n# Fitting the training data\nX_Train = Pca.fit_transform(X_train)\nX_Test = Pca.fit_transform(X_test)\n# Building models after applying pca\npgb = GradientBoostingClassifier()\npgb.fit(X_Train, Y_train)\npgb_pred = pgb.predict(X_Test)\nprint(classification_report(Y_test, pgb_pred))\n\"\"\"\n# Hyper Parameter Tuning\n\"\"\"\ngrid = {\n    'learning_rate' : [0.2, 0.3, 0.4, 0.5],\n    'n_estimators' : [300, 500, 700, 900],\n    'min_samples_split' : [3, 4, 5, 6],\n    'max_depth' : [2, 3, 4, 5],\n    'loss' : ['deviance', 'exponential']\n}\nrandom_cv = RandomizedSearchCV(estimator=gb,\n                              param_distributions=grid,\n                              n_iter=20,\n                              n_jobs=-1,\n                              cv=5,\n                              verbose=7,\n                              random_state=10,\n                              scoring='accuracy')\nrandom_cv.fit(X_train, Y_train)\nrandom_cv.best_estimator_\nhgb = GradientBoostingClassifier(learning_rate=0.5, loss='exponential', max_depth=2,\n                           min_samples_split=4, n_estimators=300)\nhgb.fit(X_train, Y_train)\nhgb_pred = hgb.predict(X_test)\nprint(classification_report(Y_test, hgb_pred))\n\"\"\"\n# My Best Model\nMy Best model is Gradient Boosting Classifier after Hyper Parameter tuning\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ac1bf0eaac6803'}"}
{"id":"103378","text":"\"\"\"\n**Densenet** \n* max_lr = 0.0631\n* momentum = 0.9\n<br\/>\n\n**CNBM**\n* max_lr = 0.0316\n* momentum = 0.99\n<br\/>\n\n**seresnet**\n* max_lr = 0.02\n* momentum = 0.95\n\n\"\"\"\n\"\"\"\n### One Cycle Policy with Keras\nHighly inspired by following paper:\n- [A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay](http:\/\/arxiv.org\/abs\/1803.09820) (Leslie N. Smith)\n\nI have implemented the One Cycle Policy algorithm developed by Leslie N. Smith into the Keras Callback class. Leslie Smith suggests in this paper a slight modification of cyclical learning rate policy for super convergence using one cycle that is smaller than the total number of iterations\/epochs and allow the learning rate todecrease several orders of magnitude less than the initial learning rate for the remaining miterations. In his experiments this policy allows the accuracy to plateau before the training ends. This approach (among others) helped me to improve my score.\n\"\"\"\nfrom sklearn.utils import shuffle\nimport pandas as pd\nimport os\n# Save train labels to dataframe\ndf = pd.read_csv(\"..\/input\/train_labels.csv\")\n\n# Save test labels to dataframe\n\n\ndf = shuffle(df)\n# For demonstration only\n#df = df[:10000]\n# Split data set  to train and validation sets\nfrom sklearn.model_selection import train_test_split\n\n# Use stratify= df['label'] to get balance ratio 1\/1 in train and validation sets\ndf_train, df_val = train_test_split(df, test_size=0.1, stratify= df['label'])\n\n# Check balancing\nprint(\"Train data: \" + str(len(df_train[df_train[\"label\"] == 1]) + len(df_train[df_train[\"label\"] == 0])))\nprint(\"True positive in train data: \" +  str(len(df_train[df_train[\"label\"] == 1])))\nprint(\"True negative in train data: \" +  str(len(df_train[df_train[\"label\"] == 0])))\nprint(\"Valid data: \" + str(len(df_val[df_val[\"label\"] == 1]) + len(df_val[df_val[\"label\"] == 0])))\nprint(\"True positive in validation data: \" +  str(len(df_val[df_val[\"label\"] == 1])))\nprint(\"True negative in validation data: \" +  str(len(df_val[df_val[\"label\"] == 0])))\n# Train List\ntrain_list = df_train['id'].tolist()\ntrain_list = ['..\/input\/train\/'+ name + \".tif\" for name in train_list]\n\n# Validation List\nval_list = df_val['id'].tolist()\nval_list = ['..\/input\/train\/'+ name + \".tif\" for name in val_list]\n\n\n# Names library\nid_label_map = {k:v for k,v in zip(df.id.values, df.label.values)}\n# Functions for generators\ndef get_id_from_path(file_path):\n    return file_path.split(os.path.sep)[-1].replace('.tif', '')\n\ndef chunker(seq, size):\n    return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n!pip install albumentations\nimport albumentations\n# train_list = df['id'].tolist()\n# train_list = ['..\/input\/train\/'+ name + \".tif\" for name in train_list]\n# id_label_map = {k:v for k,v in zip(df.id.values, df.label.values)}\n# Import Pretrained Models\nimport keras\nfrom keras.applications.densenet import DenseNet201, preprocess_input\nfrom keras.layers import Dense, Input, Dropout, MaxPooling2D, Concatenate, GlobalAveragePooling2D, GlobalMaxPooling2D, Flatten, Concatenate\nfrom keras.models import Model\nimport pandas as pd\nfrom random import shuffle\nimport numpy as np\nimport cv2\nimport glob\nimport gc\nimport os\nimport tensorflow as tf\nfrom keras.regularizers import l2\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Dense, Dropout, Flatten, Activation, Input, BatchNormalization, Add, GlobalAveragePooling2D,AveragePooling2D,GlobalMaxPooling2D,concatenate\nfrom keras.layers import Lambda, Reshape, DepthwiseConv2D, ZeroPadding2D, Add, MaxPooling2D,Activation, Flatten, Conv2D, Dense, Input, Dropout, Concatenate, GlobalMaxPooling2D, GlobalAveragePooling2D, BatchNormalization\n\nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint,TensorBoard,TerminateOnNaN\nfrom keras.optimizers import Adam,RMSprop\nfrom keras.models import Model,load_model\nfrom keras.applications import NASNetMobile,MobileNetV2,densenet,resnet50,xception\n\nfrom keras_applications.resnext import ResNeXt50\nfrom albumentations import Resize,Compose, RandomRotate90, Transpose, Flip, OneOf, CLAHE, IAASharpen, IAAEmboss, RandomBrightnessContrast, JpegCompression, Blur, GaussNoise, HueSaturationValue, ShiftScaleRotate, Normalize\n\n\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split,StratifiedKFold\nfrom skimage import data, exposure\nimport itertools\nimport shutil\nimport matplotlib.pyplot as plt\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n%matplotlib inline\nfrom keras.callbacks import Callback\nfrom keras import backend as K\nclass LRFinder(Callback):\n    def __init__(self,\n                 num_samples,\n                 batch_size,\n                 minimum_lr=1e-5,\n                 maximum_lr=10.,\n                 lr_scale='exp',\n                 validation_data=None,\n                 validation_sample_rate=5,\n                 stopping_criterion_factor=4.,\n                 loss_smoothing_beta=0.98,\n                 save_dir=None,\n                 verbose=True):\n        \n        super(LRFinder, self).__init__()\n\n        if lr_scale not in ['exp', 'linear']:\n            raise ValueError(\"`lr_scale` must be one of ['exp', 'linear']\")\n\n        if validation_data is not None:\n            self.validation_data = validation_data\n            self.use_validation_set = True\n\n            if validation_sample_rate > 0 or validation_sample_rate < 0:\n                self.validation_sample_rate = validation_sample_rate\n            else:\n                raise ValueError(\"`validation_sample_rate` must be a positive or negative integer other than o\")\n        else:\n            self.use_validation_set = False\n            self.validation_sample_rate = 0\n\n        self.num_samples = num_samples\n        self.batch_size = batch_size\n        self.initial_lr = minimum_lr\n        self.final_lr = maximum_lr\n        self.lr_scale = lr_scale\n        self.stopping_criterion_factor = stopping_criterion_factor\n        self.loss_smoothing_beta = loss_smoothing_beta\n        self.save_dir = save_dir\n        self.verbose = verbose\n\n        self.num_batches_ = num_samples \/\/ batch_size\n        self.current_lr_ = minimum_lr\n\n        if lr_scale == 'exp':\n            self.lr_multiplier_ = (maximum_lr \/ float(minimum_lr)) ** (\n                1. \/ float(self.num_batches_))\n        else:\n            extra_batch = int((num_samples % batch_size) != 0)\n            self.lr_multiplier_ = np.linspace(\n                minimum_lr, maximum_lr, num=self.num_batches_ + extra_batch)\n\n        # If negative, use entire validation set\n        if self.validation_sample_rate < 0:\n            self.validation_sample_rate = self.validation_data[0].shape[0] \/\/ batch_size\n\n        self.current_batch_ = 0\n        self.current_epoch_ = 0\n        self.best_loss_ = 1e6\n        self.running_loss_ = 0.\n\n        self.history = {}\n\n    def on_train_begin(self, logs=None):\n\n        self.current_epoch_ = 1\n        K.set_value(self.model.optimizer.lr, self.initial_lr)\n\n        warnings.simplefilter(\"ignore\")\n\n    def on_epoch_begin(self, epoch, logs=None):\n        self.current_batch_ = 0\n\n        if self.current_epoch_ > 1:\n            warnings.warn(\n                \"\\n\\nLearning rate finder should be used only with a single epoch. \"\n                \"Hereafter, the callback will not measure the losses.\\n\\n\")\n\n    def on_batch_begin(self, batch, logs=None):\n        self.current_batch_ += 1\n\n    def on_batch_end(self, batch, logs=None):\n        if self.current_epoch_ > 1:\n            return\n\n        if self.use_validation_set:\n            X, Y = self.validation_data[0], self.validation_data[1]\n\n            # use 5 random batches from test set for fast approximate of loss\n            num_samples = self.batch_size * self.validation_sample_rate\n\n            if num_samples > X.shape[0]:\n                num_samples = X.shape[0]\n\n            idx = np.random.choice(X.shape[0], num_samples, replace=False)\n            x = X[idx]\n            y = Y[idx]\n\n            values = self.model.evaluate(x, y, batch_size=self.batch_size, verbose=False)\n            loss = values[0]\n        else:\n            loss = logs['loss']\n\n        # smooth the loss value and bias correct\n        running_loss = self.loss_smoothing_beta * loss + (\n            1. - self.loss_smoothing_beta) * loss\n        running_loss = running_loss \/ (\n            1. - self.loss_smoothing_beta**self.current_batch_)\n\n        # stop logging if loss is too large\n        if self.current_batch_ > 1 and self.stopping_criterion_factor is not None and (\n                running_loss >\n                self.stopping_criterion_factor * self.best_loss_):\n\n            if self.verbose:\n                print(\" - LRFinder: Skipping iteration since loss is %d times as large as best loss (%0.4f)\"\n                      % (self.stopping_criterion_factor, self.best_loss_))\n            return\n\n        if running_loss < self.best_loss_ or self.current_batch_ == 1:\n            self.best_loss_ = running_loss\n\n        current_lr = K.get_value(self.model.optimizer.lr)\n\n        self.history.setdefault('running_loss_', []).append(running_loss)\n        if self.lr_scale == 'exp':\n            self.history.setdefault('log_lrs', []).append(np.log10(current_lr))\n        else:\n            self.history.setdefault('log_lrs', []).append(current_lr)\n\n        # compute the lr for the next batch and update the optimizer lr\n        if self.lr_scale == 'exp':\n            current_lr *= self.lr_multiplier_\n        else:\n            current_lr = self.lr_multiplier_[self.current_batch_ - 1]\n\n        K.set_value(self.model.optimizer.lr, current_lr)\n\n        # save the other metrics as well\n        for k, v in logs.items():\n            self.history.setdefault(k, []).append(v)\n\n        if self.verbose:\n            if self.use_validation_set:\n                print(\" - LRFinder: val_loss: %1.4f - lr = %1.8f \" %\n                      (values[0], current_lr))\n            else:\n                print(\" - LRFinder: lr = %1.8f \" % current_lr)\n\n    def on_epoch_end(self, epoch, logs=None):\n        if self.save_dir is not None and self.current_epoch_ <= 1:\n            if not os.path.exists(self.save_dir):\n                os.makedirs(self.save_dir)\n\n            losses_path = os.path.join(self.save_dir, 'losses.npy')\n            lrs_path = os.path.join(self.save_dir, 'lrs.npy')\n\n            np.save(losses_path, self.losses)\n            np.save(lrs_path, self.lrs)\n\n            if self.verbose:\n                print(\"\\tLR Finder : Saved the losses and learning rate values in path : {%s}\"\n                      % (self.save_dir))\n\n        self.current_epoch_ += 1\n\n        warnings.simplefilter(\"default\")\n\n    def plot_schedule(self, clip_beginning=None, clip_endding=None):\n        \"\"\"\n        Plots the schedule from the callback itself.\n        # Arguments:\n            clip_beginning: Integer or None. If positive integer, it will\n                remove the specified portion of the loss graph to remove the large\n                loss values in the beginning of the graph.\n            clip_endding: Integer or None. If negative integer, it will\n                remove the specified portion of the ending of the loss graph to\n                remove the sharp increase in the loss values at high learning rates.\n        \"\"\"\n        try:\n            import matplotlib.pyplot as plt\n            plt.style.use('seaborn-white')\n        except ImportError:\n            print(\n                \"Matplotlib not found. Please use `pip install matplotlib` first.\"\n            )\n            return\n\n        if clip_beginning is not None and clip_beginning < 0:\n            clip_beginning = -clip_beginning\n\n        if clip_endding is not None and clip_endding > 0:\n            clip_endding = -clip_endding\n\n        losses = self.losses\n        lrs = self.lrs\n\n        if clip_beginning:\n            losses = losses[clip_beginning:]\n            lrs = lrs[clip_beginning:]\n\n        if clip_endding:\n            losses = losses[:clip_endding]\n            lrs = lrs[:clip_endding]\n\n        plt.plot(lrs, losses)\n        plt.title('Learning rate vs Loss')\n        plt.xlabel('learning rate')\n        plt.ylabel('loss')\n        plt.show()\n\n    @classmethod\n    def restore_schedule_from_dir(cls,\n                                  directory,\n                                  clip_beginning=None,\n                                  clip_endding=None):\n        \"\"\"\n        Loads the training history from the saved numpy files in the given directory.\n        # Arguments:\n            directory: String. Path to the directory where the serialized numpy\n                arrays of the loss and learning rates are saved.\n            clip_beginning: Integer or None. If positive integer, it will\n                remove the specified portion of the loss graph to remove the large\n                loss values in the beginning of the graph.\n            clip_endding: Integer or None. If negative integer, it will\n                remove the specified portion of the ending of the loss graph to\n                remove the sharp increase in the loss values at high learning rates.\n        Returns:\n            tuple of (losses, learning rates)\n        \"\"\"\n        if clip_beginning is not None and clip_beginning < 0:\n            clip_beginning = -clip_beginning\n\n        if clip_endding is not None and clip_endding > 0:\n            clip_endding = -clip_endding\n\n        losses_path = os.path.join(directory, 'losses.npy')\n        lrs_path = os.path.join(directory, 'lrs.npy')\n\n        if not os.path.exists(losses_path) or not os.path.exists(lrs_path):\n            print(\"%s and %s could not be found at directory : {%s}\" %\n                  (losses_path, lrs_path, directory))\n\n            losses = None\n            lrs = None\n\n        else:\n            losses = np.load(losses_path)\n            lrs = np.load(lrs_path)\n\n            if clip_beginning:\n                losses = losses[clip_beginning:]\n                lrs = lrs[clip_beginning:]\n\n            if clip_endding:\n                losses = losses[:clip_endding]\n                lrs = lrs[:clip_endding]\n\n        return losses, lrs\n\n    @classmethod\n    def plot_schedule_from_file(cls,\n                                directory,\n                                clip_beginning=None,\n                                clip_endding=None):\n        \"\"\"\n        Plots the schedule from the saved numpy arrays of the loss and learning\n        rate values in the specified directory.\n        # Arguments:\n            directory: String. Path to the directory where the serialized numpy\n                arrays of the loss and learning rates are saved.\n            clip_beginning: Integer or None. If positive integer, it will\n                remove the specified portion of the loss graph to remove the large\n                loss values in the beginning of the graph.\n            clip_endding: Integer or None. If negative integer, it will\n                remove the specified portion of the ending of the loss graph to\n                remove the sharp increase in the loss values at high learning rates.\n        \"\"\"\n        try:\n            import matplotlib.pyplot as plt\n            plt.style.use('seaborn-white')\n        except ImportError:\n            print(\"Matplotlib not found. Please use `pip install matplotlib` first.\")\n            return\n\n        losses, lrs = cls.restore_schedule_from_dir(\n            directory,\n            clip_beginning=clip_beginning,\n            clip_endding=clip_endding)\n\n        if losses is None or lrs is None:\n            return\n        else:\n            plt.plot(lrs, losses)\n            plt.title('Learning rate vs Loss')\n            plt.xlabel('learning rate')\n            plt.ylabel('loss')\n            plt.show()\n\n    @property\n    def lrs(self):\n        return np.array(self.history['log_lrs'])\n\n    @property\n    def losses(self):\n        return np.array(self.history['running_loss_'])\ndef do_train_augmentations():\n    return Compose([\n        #Resize(196,196),\n        RandomRotate90(p=0.5),\n        Transpose(p=0.5),\n        Flip(p=0.5),\n        OneOf([CLAHE(clip_limit=2),\n              IAASharpen(),\n              IAAEmboss(),\n              RandomBrightnessContrast(),\n              JpegCompression(),\n              Blur(),\n              GaussNoise()],\n              p=0.5),\n        HueSaturationValue(p=0.5),\n        ShiftScaleRotate(shift_limit=0.15, scale_limit=0.15, rotate_limit=45, p=0.5),\n        Normalize(p=1)])\n\n\ndef do_inference_aug():\n    return Compose([\n       # Resize(196,196),\n        RandomRotate90(p=0.5),\n        Transpose(p=0.5),\n        Flip(p=0.5),Normalize(p=1)])\n\n\ndef data_gen(list_files,id_label_map,batch_size,aug_func):\n    aug = aug_func()\n    while True:\n        shuffle(list_files)\n        for block in chunker(list_files,batch_size):\n            x = [aug(image = cv2.imread(addr))['image'] for addr in block]\n            y = [id_label_map[get_id_from_path(addr)] for addr in block]\n            yield np.array(x),np.array(y)\nfrom keras.layers import BatchNormalization\nfrom keras.layers import Conv2D\nfrom keras.layers import Dense\nfrom keras.layers import GlobalAveragePooling2D\nfrom keras.layers import GlobalMaxPooling2D\nfrom keras.layers import Input\nfrom keras.layers import MaxPool2D\nfrom keras.layers import ReLU\nfrom keras.layers import add\nfrom keras.models import Model\nfrom keras.utils import get_source_inputs\n\nfrom keras import backend as K\nfrom keras_applications.imagenet_utils import _obtain_input_shape\n\n\nfrom keras.layers import Conv2D, AveragePooling2D, UpSampling2D\nfrom keras.layers import add\n\n\ndef initial_octconv(ip, filters, kernel_size=(3, 3), strides=(1, 1),\n                    alpha=0.5, padding='same', dilation=None, bias=False):\n\n    if dilation is None:\n        dilation = (1, 1)\n\n    high_low_filters = int(alpha * filters)\n    high_high_filters = filters - high_low_filters\n\n    if strides[0] > 1:\n        ip = AveragePooling2D()(ip)\n\n    # High path\n    x_high = Conv2D(high_high_filters, kernel_size, padding=padding,\n                    dilation_rate=dilation, use_bias=bias,\n                    kernel_initializer='he_normal')(ip)\n\n    # Low path\n    x_high_low = AveragePooling2D()(ip)\n    x_low = Conv2D(high_low_filters, kernel_size, padding=padding,\n                   dilation_rate=dilation, use_bias=bias,\n                   kernel_initializer='he_normal')(x_high_low)\n\n    return x_high, x_low\n\n\ndef final_octconv(ip_high, ip_low, filters, kernel_size=(3, 3), strides=(1, 1),\n                  padding='same', dilation=None, bias=False):\n\n    if dilation is None:\n        dilation = (1, 1)\n\n    if strides[0] > 1:\n        avg_pool = AveragePooling2D()\n\n        ip_high = avg_pool(ip_high)\n        ip_low = avg_pool(ip_low)\n\n    # High path\n    x_high_high = Conv2D(filters, kernel_size, padding=padding,\n                         dilation_rate=dilation, use_bias=bias,\n                         kernel_initializer='he_normal')(ip_high)\n\n    # Low path\n    x_low_high = Conv2D(filters, kernel_size, padding=padding,\n                        dilation_rate=dilation, use_bias=bias,\n                        kernel_initializer='he_normal')(ip_low)\n\n    x_low_high = UpSampling2D(interpolation='nearest')(x_low_high)\n\n    # Merge paths\n    x = add([x_high_high, x_low_high])\n\n    return x\n\n\ndef octconv_block(ip_high, ip_low, filters, kernel_size=(3, 3), strides=(1, 1),\n                  alpha=0.5, padding='same', dilation=None, bias=False):\n\n    if dilation is None:\n        dilation = (1, 1)\n\n    low_low_filters = high_low_filters = int(alpha * filters)\n    high_high_filters = low_high_filters = filters - low_low_filters\n\n    avg_pool = AveragePooling2D()\n\n    if strides[0] > 1:\n        ip_high = avg_pool(ip_high)\n        ip_low = avg_pool(ip_low)\n\n    # High path\n    x_high_high = Conv2D(high_high_filters, kernel_size, padding=padding,\n                         dilation_rate=dilation, use_bias=bias,\n                         kernel_initializer='he_normal')(ip_high)\n\n    x_low_high = Conv2D(low_high_filters, kernel_size, padding=padding,\n                        dilation_rate=dilation, use_bias=bias,\n                        kernel_initializer='he_normal')(ip_low)\n    x_low_high = UpSampling2D(interpolation='nearest')(x_low_high)\n\n    # Low path\n    x_low_low = Conv2D(low_low_filters, kernel_size, padding=padding,\n                       dilation_rate=dilation, use_bias=bias,\n                       kernel_initializer='he_normal')(ip_low)\n\n    x_high_low = avg_pool(ip_high)\n    x_high_low = Conv2D(high_low_filters, kernel_size, padding=padding,\n                        dilation_rate=dilation, use_bias=bias,\n                        kernel_initializer='he_normal')(x_high_low)\n\n    # Merge paths\n    x_high = add([x_high_high, x_low_high])\n    x_low = add([x_low_low, x_high_low])\n\n    return x_high, x_low\n\n\ndef _conv_block(ip, filters, kernel_size=(3, 3), strides=(1, 1),\n                padding='same', bias=False):\n    x = Conv2D(filters, kernel_size, strides=strides, padding=padding, use_bias=bias,\n               kernel_initializer='he_normal')(ip)\n\n    return x\n\n\ndef _conv_bn_relu(ip, filters, kernel_size=(3, 3), strides=(1, 1),\n                  padding='same', bias=False, activation=True):\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x = _conv_block(ip, filters, kernel_size, strides, padding, bias)\n    x = BatchNormalization(axis=channel_axis)(x)\n    if activation:\n        x = ReLU()(x)\n\n    return x\n\n\ndef _initial_oct_conv_bn_relu(ip, filters, kernel_size=(3, 3), strides=(1, 1),\n                              alpha=0.5, padding='same', dilation=None, bias=False,\n                              activation=True):\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x_high, x_low = initial_octconv(ip, filters, kernel_size, strides, alpha,\n                                    padding, dilation, bias)\n\n    relu = ReLU()\n    x_high = BatchNormalization(axis=channel_axis)(x_high)\n    if activation:\n        x_high = relu(x_high)\n\n    x_low = BatchNormalization(axis=channel_axis)(x_low)\n    if activation:\n        x_low = relu(x_low)\n\n    return x_high, x_low\n\n\ndef _final_oct_conv_bn_relu(ip_high, ip_low, filters, kernel_size=(3, 3), strides=(1, 1),\n                            padding='same', dilation=None, bias=False, activation=True):\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x = final_octconv(ip_high, ip_low, filters, kernel_size, strides,\n                      padding, dilation, bias)\n\n    x = BatchNormalization(axis=channel_axis)(x)\n    if activation:\n        x = ReLU()(x)\n\n    return x\n\n\ndef _oct_conv_bn_relu(ip_high, ip_low, filters, kernel_size=(3, 3), strides=(1, 1),\n                      alpha=0.5, padding='same', dilation=None, bias=False, activation=True):\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x_high, x_low = octconv_block(ip_high, ip_low, filters, kernel_size, strides, alpha,\n                                  padding, dilation, bias)\n\n    relu = ReLU()\n    x_high = BatchNormalization(axis=channel_axis)(x_high)\n    if activation:\n        x_high = relu(x_high)\n\n    x_low = BatchNormalization(axis=channel_axis)(x_low)\n    if activation:\n        x_low = relu(x_low)\n\n    return x_high, x_low\n\n\ndef _octresnet_bottleneck_block(ip, filters, alpha=0.5, strides=(1, 1),\n                                downsample_shortcut=False, first_block=False,\n                                expansion=4):\n\n    if first_block:\n        x_high_res, x_low_res = _initial_oct_conv_bn_relu(ip, filters, kernel_size=(1, 1),\n                                                          alpha=alpha)\n\n        x_high, x_low = _oct_conv_bn_relu(x_high_res, x_low_res, filters, kernel_size=(3, 3),\n                                          strides=strides, alpha=alpha)\n\n    else:\n        x_high_res, x_low_res = ip\n        x_high, x_low = _oct_conv_bn_relu(x_high_res, x_low_res, filters, kernel_size=(1, 1),\n                                          alpha=alpha)\n\n        x_high, x_low = _oct_conv_bn_relu(x_high, x_low, filters, kernel_size=(3, 3),\n                                          strides=strides, alpha=alpha)\n\n    final_out_filters = int(filters * expansion)\n    x_high, x_low = _oct_conv_bn_relu(x_high, x_low, filters=final_out_filters,\n                                      kernel_size=(1, 1), alpha=alpha, activation=False)\n\n    if downsample_shortcut:\n        x_high_res, x_low_res = _oct_conv_bn_relu(x_high_res, x_low_res,\n                                                  final_out_filters, kernel_size=(1, 1),\n                                                  strides=strides, activation=False)\n\n    x_high = add([x_high, x_high_res])\n    x_low = add([x_low, x_low_res])\n\n    x_high = ReLU()(x_high)\n    x_low = ReLU()(x_low)\n\n    return x_high, x_low\n\n\ndef _octresnet_final_bottleneck_block(ip, filters, alpha=0.5, strides=(1, 1),\n                                      downsample_shortcut=False,\n                                      expansion=4):\n\n    x_high_res, x_low_res = ip\n\n    x_high, x_low = _oct_conv_bn_relu(x_high_res, x_low_res, filters, kernel_size=(1, 1),\n                                      alpha=alpha)\n\n    x_high, x_low = _oct_conv_bn_relu(x_high, x_low, filters, kernel_size=(3, 3),\n                                      strides=strides, alpha=alpha)\n\n    final_filters = int(filters * expansion)\n    x_high = _final_oct_conv_bn_relu(x_high, x_low, final_filters, kernel_size=(1, 1),\n                                     activation=False)\n\n    if downsample_shortcut:\n        x_high_res = _final_oct_conv_bn_relu(x_high_res, x_low_res, final_filters, kernel_size=(1, 1),\n                                             strides=strides, activation=False)\n\n    x = add([x_high, x_high_res])\n    x = ReLU()(x)\n\n    return x\n\n\ndef _bottleneck_original(ip, filters, strides=(1, 1), downsample_shortcut=False,\n                         expansion=4):\n\n    final_filters = int(filters * expansion)\n\n    shortcut = ip\n\n    x = _conv_bn_relu(ip, filters, kernel_size=(1, 1))\n    x = _conv_bn_relu(x, filters, kernel_size=(3, 3), strides=strides)\n    x = _conv_bn_relu(x, final_filters, kernel_size=(1, 1), activation=False)\n\n    if downsample_shortcut:\n        shortcut = _conv_block(shortcut, final_filters, kernel_size=(1, 1),\n                               strides=strides)\n\n    x = add([x, shortcut])\n    x = ReLU()(x)\n\n    return x\n\n\ndef OctaveResNet(block,\n                 layers,\n                 include_top=True,\n                 weights=None,\n                 input_tensor=None,\n                 input_shape=None,\n                 pooling=None,\n                 classes=1000,\n                 alpha=0.5,\n                 expansion=1,\n                 initial_filters=64,\n                 initial_strides=False,\n                 **kwargs):\n\n    if not (weights in {'imagenet', None} or os.path.exists(weights)):\n        raise ValueError('The `weights` argument should be either '\n                         '`None` (random initialization), `imagenet` '\n                         '(pre-training on ImageNet), '\n                         'or the path to the weights file to be loaded.')\n\n    if weights == 'imagenet' and include_top and classes != 1000:\n        raise ValueError('If using `weights` as `\"imagenet\"` with `include_top`'\n                         ' as true, `classes` should be 1000')\n\n    assert alpha >= 0. and alpha <= 1., \"`alpha` must be between 0 and 1\"\n\n    assert type(layers) in [list, tuple], \"`layers` must be a list\/tuple of integers\"\n\n    # Determine proper input shape\n    input_shape = _obtain_input_shape(input_shape,\n                                      default_size=224,\n                                      min_size=32,\n                                      data_format=K.image_data_format(),\n                                      require_flatten=include_top,\n                                      weights=weights)\n\n    if input_tensor is None:\n        img_input = Input(shape=input_shape)\n    else:\n        if not K.is_keras_tensor(input_tensor):\n            img_input = Input(tensor=input_tensor, shape=input_shape)\n        else:\n            img_input = input_tensor\n\n    if initial_strides:\n        initial_strides = (2, 2)\n\n    else:\n        initial_strides = (1, 1)\n\n    x = _conv_bn_relu(img_input, filters=64, kernel_size=(7, 7), strides=initial_strides)\n\n    if initial_strides:\n        x = MaxPool2D((3, 3), strides=(2, 2), padding='same')(x)\n\n    num_filters = initial_filters\n    num_blocks = len(layers)\n\n    for i in range(num_blocks - 1):\n        for j in range(layers[i]):\n            if j == 0:\n                strides = (2, 2)\n                downsample_shortcut = True\n\n            else:\n                strides = (1, 1)\n                downsample_shortcut = False\n\n            # first block has no downsample, no shortcut\n            if i == 0 and j == 0:\n                first_block = True\n                strides = (1, 1)\n                downsample_shortcut = True\n\n            else:\n                first_block = False\n\n            x = block(x, num_filters, alpha, strides, downsample_shortcut, first_block, expansion)\n\n        # double number of filters per block\n        num_filters *= 2\n\n    # final block\n    for j in range(layers[-1]):\n        if j == 0:\n            strides = (2, 2)\n            x = _octresnet_final_bottleneck_block(x, num_filters, alpha, strides,\n                                                  downsample_shortcut=True, expansion=expansion)\n\n        else:\n            strides = (1, 1)\n            x = _bottleneck_original(x, num_filters, strides, expansion=expansion)\n\n    if include_top:\n        x = GlobalAveragePooling2D(name='avg_pool')(x)\n        x = Dense(classes, activation='softmax', name='fc')(x)\n    else:\n        if pooling == 'avg':\n            x = GlobalAveragePooling2D(name='avg_pool')(x)\n        elif pooling == 'max':\n            x = GlobalMaxPooling2D(name='max_pool')(x)\n\n    # Ensure that the model takes into account\n    # any potential predecessors of `input_tensor`.\n    if input_tensor is not None:\n        inputs = get_source_inputs(input_tensor)\n    else:\n        inputs = img_input\n\n    model = Model(inputs, x, name='OctaveResNet')\n\n    return model\n\n\ndef OctaveResNet50(include_top=True,\n                   weights=None,\n                   input_tensor=None,\n                   input_shape=None,\n                   pooling=None,\n                   classes=1000,\n                   alpha=0.5,\n                   expansion=4,\n                   initial_filters=64,\n                   initial_strides=True,\n                   **kwargs):\n\n    return OctaveResNet(_octresnet_bottleneck_block,\n                        [3, 4, 6, 3],\n                        include_top,\n                        weights,\n                        input_tensor,\n                        input_shape,\n                        pooling,\n                        classes,\n                        alpha,\n                        expansion,\n                        initial_filters,\n                        initial_strides,\n                        **kwargs)\n\n\ndef OctaveResNet101(include_top=True,\n                    weights=None,\n                    input_tensor=None,\n                    input_shape=None,\n                    pooling=None,\n                    classes=1000,\n                    alpha=0.5,\n                    expansion=4,\n                    initial_filters=64,\n                    initial_strides=True,\n                    **kwargs):\n\n    return OctaveResNet(_octresnet_bottleneck_block,\n                        [3, 4, 23, 3],\n                        include_top,\n                        weights,\n                        input_tensor,\n                        input_shape,\n                        pooling,\n                        classes,\n                        alpha,\n                        expansion,\n                        initial_filters,\n                        initial_strides,\n                        **kwargs)\n\n\ndef OctaveResNet152(include_top=True,\n                    weights=None,\n                    input_tensor=None,\n                    input_shape=None,\n                    pooling=None,\n                    classes=1000,\n                    alpha=0.5,\n                    expansion=4,\n                    initial_filters=64,\n                    initial_strides=True,\n                    **kwargs):\n\n    return OctaveResNet(_octresnet_bottleneck_block,\n                        [3, 8, 36, 3],\n                        include_top,\n                        weights,\n                        input_tensor,\n                        input_shape,\n                        pooling,\n                        classes,\n                        alpha,\n                        expansion,\n                        initial_filters,\n                        initial_strides,\n                        **kwargs)\n\n\n\ndef densenet_model(input_shape,batch_size = 1024):\n    base_model = OctaveResNet50(input_shape=input_shape, include_top=False,\n                           alpha=0.5, expansion=4,\n                           initial_filters=64,\n                           initial_strides=False)\n    x = base_model.output\n\n    out1 = GlobalMaxPooling2D()(x)\n    out2 = GlobalAveragePooling2D()(x)\n    #out3 = Flatten()(x)\n    out = concatenate([out1,out2])\n    out = BatchNormalization(epsilon = 1e-5)(out)\n    out = Dropout(0.4)(out)\n    fc = Dense(512,activation = 'relu')(out)\n    fc = BatchNormalization(epsilon = 1e-5)(fc)\n    fc = Dropout(0.3)(fc)\n    fc = Dense(256,activation = 'relu')(fc)\n    fc = BatchNormalization(epsilon = 1e-5)(fc)\n    fc = Dropout(0.3)(fc)\n    X = Dense(1, activation='sigmoid', kernel_initializer='glorot_uniform', bias_initializer='zeros')(fc)\n    model =  Model(inputs=base_model.input, outputs=X)\n    #model.compile(optimizer=tf.keras.optimizers.Adam(lr = 0.0001), loss=tf.keras.losses.binary_crossentropy, metrics=['acc'])\n    return model\nres_model = densenet_model((96,96,3))\nprint(res_model.summary())\n\"\"\"\n* #### Here is the implementation of One Cycle Policy in the Keras Callback Class\n\"\"\"\nimport os\nimport numpy as np\nimport warnings\n\nfrom keras.callbacks import Callback\nfrom keras import backend as K\n\n\n# Code is ported from https:\/\/github.com\/fastai\/fastai\nclass OneCycleLR(Callback):\n    def __init__(self,\n                 max_lr,\n                 end_percentage=0.1,\n                 scale_percentage=None,\n                 maximum_momentum=0.95,\n                 minimum_momentum=0.85,\n                 verbose=True):\n        \"\"\" This callback implements a cyclical learning rate policy (CLR).\n        This is a special case of Cyclic Learning Rates, where we have only 1 cycle.\n        After the completion of 1 cycle, the learning rate will decrease rapidly to\n        100th its initial lowest value.\n        # Arguments:\n            max_lr: Float. Initial learning rate. This also sets the\n                starting learning rate (which will be 10x smaller than\n                this), and will increase to this value during the first cycle.\n            end_percentage: Float. The percentage of all the epochs of training\n                that will be dedicated to sharply decreasing the learning\n                rate after the completion of 1 cycle. Must be between 0 and 1.\n            scale_percentage: Float or None. If float, must be between 0 and 1.\n                If None, it will compute the scale_percentage automatically\n                based on the `end_percentage`.\n            maximum_momentum: Optional. Sets the maximum momentum (initial)\n                value, which gradually drops to its lowest value in half-cycle,\n                then gradually increases again to stay constant at this max value.\n                Can only be used with SGD Optimizer.\n            minimum_momentum: Optional. Sets the minimum momentum at the end of\n                the half-cycle. Can only be used with SGD Optimizer.\n            verbose: Bool. Whether to print the current learning rate after every\n                epoch.\n        # Reference\n            - [A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, weight_decay, and weight decay](https:\/\/arxiv.org\/abs\/1803.09820)\n            - [Super-Convergence: Very Fast Training of Residual Networks Using Large Learning Rates](https:\/\/arxiv.org\/abs\/1708.07120)\n        \"\"\"\n        super(OneCycleLR, self).__init__()\n\n        if end_percentage < 0. or end_percentage > 1.:\n            raise ValueError(\"`end_percentage` must be between 0 and 1\")\n\n        if scale_percentage is not None and (scale_percentage < 0. or scale_percentage > 1.):\n            raise ValueError(\"`scale_percentage` must be between 0 and 1\")\n\n        self.initial_lr = max_lr\n        self.end_percentage = end_percentage\n        self.scale = float(scale_percentage) if scale_percentage is not None else float(end_percentage)\n        self.max_momentum = maximum_momentum\n        self.min_momentum = minimum_momentum\n        self.verbose = verbose\n\n        if self.max_momentum is not None and self.min_momentum is not None:\n            self._update_momentum = True\n        else:\n            self._update_momentum = False\n\n        self.clr_iterations = 0.\n        self.history = {}\n\n        self.epochs = None\n        self.batch_size = None\n        self.samples = None\n        self.steps = None\n        self.num_iterations = None\n        self.mid_cycle_id = None\n\n    def _reset(self):\n        \"\"\"\n        Reset the callback.\n        \"\"\"\n        self.clr_iterations = 0.\n        self.history = {}\n\n    def compute_lr(self):\n        \"\"\"\n        Compute the learning rate based on which phase of the cycle it is in.\n        - If in the first half of training, the learning rate gradually increases.\n        - If in the second half of training, the learning rate gradually decreases.\n        - If in the final `end_percentage` portion of training, the learning rate\n            is quickly reduced to near 100th of the original min learning rate.\n        # Returns:\n            the new learning rate\n        \"\"\"\n        if self.clr_iterations > 2 * self.mid_cycle_id:\n            current_percentage = (self.clr_iterations - 2 * self.mid_cycle_id)\n            current_percentage \/= float((self.num_iterations - 2 * self.mid_cycle_id))\n            new_lr = self.initial_lr * (1. + (current_percentage *\n                                              (1. - 100.) \/ 100.)) * self.scale\n\n        elif self.clr_iterations > self.mid_cycle_id:\n            current_percentage = 1. - (\n                self.clr_iterations - self.mid_cycle_id) \/ self.mid_cycle_id\n            new_lr = self.initial_lr * (1. + current_percentage *\n                                        (self.scale * 100 - 1.)) * self.scale\n\n        else:\n            current_percentage = self.clr_iterations \/ self.mid_cycle_id\n            new_lr = self.initial_lr * (1. + current_percentage *\n                                        (self.scale * 100 - 1.)) * self.scale\n\n        if self.clr_iterations == self.num_iterations:\n            self.clr_iterations = 0\n\n        return new_lr\n\n    def compute_momentum(self):\n        \"\"\"\n         Compute the momentum based on which phase of the cycle it is in.\n        - If in the first half of training, the momentum gradually decreases.\n        - If in the second half of training, the momentum gradually increases.\n        - If in the final `end_percentage` portion of training, the momentum value\n            is kept constant at the maximum initial value.\n        # Returns:\n            the new momentum value\n        \"\"\"\n        if self.clr_iterations > 2 * self.mid_cycle_id:\n            new_momentum = self.max_momentum\n\n        elif self.clr_iterations > self.mid_cycle_id:\n            current_percentage = 1. - ((self.clr_iterations - self.mid_cycle_id) \/ float(\n                                        self.mid_cycle_id))\n            new_momentum = self.max_momentum - current_percentage * (\n                self.max_momentum - self.min_momentum)\n\n        else:\n            current_percentage = self.clr_iterations \/ float(self.mid_cycle_id)\n            new_momentum = self.max_momentum - current_percentage * (\n                self.max_momentum - self.min_momentum)\n\n        return new_momentum\n\n    def on_train_begin(self, logs={}):\n        logs = logs or {}\n\n        self.epochs = self.params['epochs']\n        self.batch_size = 192\n        self.samples = len(train_list)\n        self.steps = self.params['steps']\n\n        if self.steps is not None:\n            self.num_iterations = self.epochs * self.steps\n        else:\n            if (self.samples % self.batch_size) == 0:\n                remainder = 0\n            else:\n                remainder = 1\n            self.num_iterations = (self.epochs + remainder) * self.samples \/\/ self.batch_size\n\n        self.mid_cycle_id = int(self.num_iterations * ((1. - self.end_percentage)) \/ float(2))\n\n        self._reset()\n        K.set_value(self.model.optimizer.lr, self.compute_lr())\n\n        if self._update_momentum:\n            if not hasattr(self.model.optimizer, 'momentum'):\n                raise ValueError(\"Momentum can be updated only on SGD optimizer !\")\n\n            new_momentum = self.compute_momentum()\n            K.set_value(self.model.optimizer.momentum, new_momentum)\n\n    def on_batch_end(self, epoch, logs=None):\n        logs = logs or {}\n\n        self.clr_iterations += 1\n        new_lr = self.compute_lr()\n\n        self.history.setdefault('lr', []).append(\n            K.get_value(self.model.optimizer.lr))\n        K.set_value(self.model.optimizer.lr, new_lr)\n\n        if self._update_momentum:\n            if not hasattr(self.model.optimizer, 'momentum'):\n                raise ValueError(\"Momentum can be updated only on SGD optimizer !\")\n\n            new_momentum = self.compute_momentum()\n\n            self.history.setdefault('momentum', []).append(\n                K.get_value(self.model.optimizer.momentum))\n            K.set_value(self.model.optimizer.momentum, new_momentum)\n\n        for k, v in logs.items():\n            self.history.setdefault(k, []).append(v)\n\n    def on_epoch_end(self, epoch, logs=None):\n        if self.verbose:\n            if self._update_momentum:\n                print(\" - lr: %0.5f - momentum: %0.2f \" %\n                      (self.history['lr'][-1], self.history['momentum'][-1]))\n\n            else:\n                print(\" - lr: %0.5f \" % (self.history['lr'][-1]))\n\n\n\n# Define Ony Cycle Policy parameters and train model\n########################################################################################\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\n#from clr import OneCycleLR\n# CLR parameters\n\nbatch_size = 192\nepochs = 38\n# lr_callback = LRFinder(len(train_list), batch_size,\n#                        1e-5, 1.,\n#                        # validation_data=(X_val, Y_val),\n#                        lr_scale='exp', save_dir='weights\/')\nlr_manager = OneCycleLR(max_lr=0.02, end_percentage=0.1, scale_percentage=None,\n                        maximum_momentum=0.9,minimum_momentum=0.8)\n\nres_model.compile(loss='binary_crossentropy', optimizer=SGD(0.002, momentum=0.9, nesterov=True), metrics=['accuracy'])\n    \ncallbacks = [lr_manager,\n           ModelCheckpoint(filepath='octresnet_one_cycle_model.h5', monitor='val_loss',mode='min',verbose=1,save_best_only=True)]\n\nhistory = res_model.fit_generator(data_gen(train_list, id_label_map, batch_size,do_train_augmentations),\n                              validation_data=data_gen(val_list, id_label_map, batch_size,do_inference_aug),\n                              epochs = epochs,\n                              steps_per_epoch = (len(train_list) \/\/ batch_size) + 1,\n                              validation_steps = (len(val_list) \/\/ batch_size) + 1,\n                              callbacks=callbacks,\n                              verbose = 1)\nplt.plot(history.history['loss'], label='train')\nplt.plot(history.history['val_loss'], label='valid')\nplt.title(\"model loss\")\nplt.ylabel(\"loss\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"valid\"], loc=\"upper left\")\nplt.savefig('loss_performance.png')\nplt.clf()\nplt.plot(history.history['acc'], label='train')\nplt.plot(history.history['val_acc'], label='valid')\nplt.title(\"model acc\")\nplt.ylabel(\"acc\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"valid\"], loc=\"upper left\")\nplt.savefig('acc_performance.png')\n\n\ndef do_inference_aug():\n    return Compose([\n       # Resize(196,196),\n        RandomRotate90(p=0.5),\n        Transpose(p=0.5),\n        Flip(p=0.5),Normalize(p=1)])\n\n\ndef data_gen(list_files,batch_size,aug_func):\n    aug = aug_func()\n    while True:\n        #shuffle(list_files)\n        for block in chunker(list_files,batch_size):\n            x = [aug(image = cv2.imread(addr))['image'] for addr in block]\n            y = [id_label_map[get_id_from_path(addr)] for addr in block]\n            yield np.array(x),np.array(y)\n\n\npreds = res_model.predict_generator(data_gen(val_list,1,do_inference_aug),steps = len(val_list))\ny_preds = np.array(preds)\ny_preds[preds >= 0.5] = 1\ny_preds[preds < 0.5] = 0\ntrue = df_val['label'].values\nfrom sklearn.metrics import roc_auc_score,confusion_matrix,classification_report\nroc_auc_score(true,preds)\nimport sklearn.metrics as metrics\n# calculate the fpr and tpr for all thresholds of the classification\n\nfpr, tpr, threshold = metrics.roc_curve(true, preds)\nroc_auc = metrics.auc(fpr, tpr)\n\n# method I: plt\nimport matplotlib.pyplot as plt\nplt.title('Receiver Operating Characteristic')\nplt.plot(fpr, tpr, 'g', label = 'AUC = %0.2f' % roc_auc)\nplt.legend(loc = 'lower right')\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\nplt.savefig('octresnet_auc_roc.png')\ncm = confusion_matrix(true,y_preds)\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    print(cm)\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.tight_layout()\n    plt.savefig('octresnet_cm.png')\nplot_confusion_matrix(cm,['no_tumor_tissue', 'has_tumor_tissue'])\nreport = classification_report(true,y_preds,target_names=['no_tumor_tissue', 'has_tumor_tissue'])\nprint(report)\n# lr_callback.plot_schedule(clip_beginning=200, clip_endding=50)\n# # Define Ony Cycle Policy parameters and train model\n# ########################################################################################\n# import gc\n# from keras.optimizers import Adam, SGD\n# from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\n# import keras.backend as K\n# # CLR parameters\n\n# batch_size = 256\n# epochs = 1\n# for momentum in [0.9,0.95,0.99]:\n#     #K.clear_session()\n#     lr_finder = LRFinder(len(train_list), batch_size, minimum_lr=.0001, maximum_lr=.001,\n#                          lr_scale='linear',\n#                          #validation_data=data_gen(val_list, id_label_map, batch_size, do_inference_aug),  # use the validation data for losses\n#                          #validation_sample_rate=5,\n#                          save_dir='weights\/momentum\/momentum-%s' % str(momentum), verbose=True)\n#     res_model = densenet_model((96,96,3))\n#     res_model.compile(loss='binary_crossentropy', optimizer=SGD(0.0001, momentum=momentum, nesterov=True), metrics=['accuracy'])\n\n#     # clr =  CyclicLR(base_lr=base_lr,\n#     #                 max_lr=max_lr,\n#     #                 step_size=step_size,\n#     #                 max_m=max_m,\n#     #                 base_m=base_m,\n#     #                 cyclical_momentum=cyclical_momentum)\n\n#     callbacks = [lr_finder]\n#                 #ModelCheckpoint(filepath='best_model.h5', monitor='val_loss',mode='min',verbose=1,save_best_only=True)]\n\n#     history = res_model.fit_generator(data_gen(train_list, id_label_map, batch_size,do_train_augmentations),\n#                                   #validation_data=data_gen(val_list, id_label_map, batch_size, do_inference_aug),\n#                                   epochs = epochs,\n#                                   steps_per_epoch = (len(train_list) \/\/ batch_size) + 1,\n#                                  #validation_steps = (len(val_list) \/\/ batch_size) + 1,\n#                                   callbacks=callbacks,\n#                                   verbose = 1)\n#     del history\n#     del res_model\n#     gc.collect()\n    ","meta":"{'source': 'AI4Code', 'id': 'bdf42298e7b70c'}"}
{"id":"22457","text":"\"\"\"\n<h1>Table of Contents<span class=\"tocSkip\"><\/span><\/h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Loading-Libraries\" data-toc-modified-id=\"Loading-Libraries-0.1\"><span class=\"toc-item-num\">0.1&nbsp;&nbsp;<\/span>Loading Libraries<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#Descriptive-Analysis\" data-toc-modified-id=\"Descriptive-Analysis-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;<\/span>Descriptive Analysis<\/a><\/span><ul class=\"toc-item\"><li><span><a href=\"#Trailer-of-data\" data-toc-modified-id=\"Trailer-of-data-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;<\/span>Trailer of data<\/a><\/span><ul class=\"toc-item\"><li><span><a href=\"#Shape\" data-toc-modified-id=\"Shape-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;<\/span>Shape<\/a><\/span><\/li><li><span><a href=\"#Column-Names\" data-toc-modified-id=\"Column-Names-1.1.2\"><span class=\"toc-item-num\">1.1.2&nbsp;&nbsp;<\/span>Column Names<\/a><\/span><\/li><li><span><a href=\"#Converting-haves-and-haves_not\" data-toc-modified-id=\"Converting-haves-and-haves_not-1.1.3\"><span class=\"toc-item-num\">1.1.3&nbsp;&nbsp;<\/span>Converting haves and haves_not<\/a><\/span><\/li><li><span><a href=\"#General-Stats\" data-toc-modified-id=\"General-Stats-1.1.4\"><span class=\"toc-item-num\">1.1.4&nbsp;&nbsp;<\/span>General Stats<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#KDE---Normal\" data-toc-modified-id=\"KDE---Normal-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;<\/span>KDE - Normal<\/a><\/span><\/li><li><span><a href=\"#Histogram\" data-toc-modified-id=\"Histogram-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;<\/span>Histogram<\/a><\/span><\/li><li><span><a href=\"#Box-PLot\" data-toc-modified-id=\"Box-PLot-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;<\/span>Box PLot<\/a><\/span><\/li><li><span><a href=\"#Scatter-Plot\" data-toc-modified-id=\"Scatter-Plot-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;<\/span>Scatter Plot<\/a><\/span><\/li><li><span><a href=\"#Heat-Map\" data-toc-modified-id=\"Heat-Map-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;<\/span>Heat Map<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#Predcitive\" data-toc-modified-id=\"Predcitive-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;<\/span>Predcitive<\/a><\/span><ul class=\"toc-item\"><li><span><a href=\"#OLS-v1-adding-only-nominal-variables\" data-toc-modified-id=\"OLS-v1-adding-only-nominal-variables-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;<\/span>OLS v1 adding only nominal variables<\/a><\/span><\/li><li><span><a href=\"#OLS-v2-adding-all-variables\" data-toc-modified-id=\"OLS-v2-adding-all-variables-2.2\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;<\/span>OLS v2 adding all variables<\/a><\/span><\/li><li><span><a href=\"#Stepwise-OLS\" data-toc-modified-id=\"Stepwise-OLS-2.3\"><span class=\"toc-item-num\">2.3&nbsp;&nbsp;<\/span>Stepwise OLS<\/a><\/span><\/li><li><span><a href=\"#PCA\" data-toc-modified-id=\"PCA-2.4\"><span class=\"toc-item-num\">2.4&nbsp;&nbsp;<\/span>PCA<\/a><\/span><\/li><li><span><a href=\"#Clustering\" data-toc-modified-id=\"Clustering-2.5\"><span class=\"toc-item-num\">2.5&nbsp;&nbsp;<\/span>Clustering<\/a><\/span><\/li><li><span><a href=\"#Verifying-clusters\" data-toc-modified-id=\"Verifying-clusters-2.6\"><span class=\"toc-item-num\">2.6&nbsp;&nbsp;<\/span>Verifying clusters<\/a><\/span><\/li><li><span><a href=\"#Wordcloud\" data-toc-modified-id=\"Wordcloud-2.7\"><span class=\"toc-item-num\">2.7&nbsp;&nbsp;<\/span>Wordcloud<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#Prescriptive\" data-toc-modified-id=\"Prescriptive-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;<\/span>Prescriptive<\/a><\/span><ul class=\"toc-item\"><li><span><a href=\"#Q:-Does-Rating-change-evry-year-?\" data-toc-modified-id=\"Q:-Does-Rating-change-evry-year-?-3.1\"><span class=\"toc-item-num\">3.1&nbsp;&nbsp;<\/span>Q: Does Rating change evry year ?<\/a><\/span><ul class=\"toc-item\"><li><span><a href=\"#Normal-Distribution\" data-toc-modified-id=\"Normal-Distribution-3.1.1\"><span class=\"toc-item-num\">3.1.1&nbsp;&nbsp;<\/span>Normal Distribution<\/a><\/span><\/li><li><span><a href=\"#Boxplot\" data-toc-modified-id=\"Boxplot-3.1.2\"><span class=\"toc-item-num\">3.1.2&nbsp;&nbsp;<\/span>Boxplot<\/a><\/span><\/li><li><span><a href=\"#Standard-Deviation\" data-toc-modified-id=\"Standard-Deviation-3.1.3\"><span class=\"toc-item-num\">3.1.3&nbsp;&nbsp;<\/span>Standard Deviation<\/a><\/span><\/li><li><span><a href=\"#Mean-Rating-over-time\" data-toc-modified-id=\"Mean-Rating-over-time-3.1.4\"><span class=\"toc-item-num\">3.1.4&nbsp;&nbsp;<\/span>Mean Rating over time<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#Q:-Which-country-and-country-makes-the-best-chcolate?\" data-toc-modified-id=\"Q:-Which-country-and-country-makes-the-best-chcolate?-3.2\"><span class=\"toc-item-num\">3.2&nbsp;&nbsp;<\/span>Q: Which country and country makes the best chcolate?<\/a><\/span><\/li><li><span><a href=\"#Q:-Which-company-makes-the-best-choclate-?\" data-toc-modified-id=\"Q:-Which-company-makes-the-best-choclate-?-3.3\"><span class=\"toc-item-num\">3.3&nbsp;&nbsp;<\/span>Q: Which company makes the best choclate ?<\/a><\/span><\/li><li><span><a href=\"#Q:-Does-origin-of-bean-affects-rating?\" data-toc-modified-id=\"Q:-Does-origin-of-bean-affects-rating?-3.4\"><span class=\"toc-item-num\">3.4&nbsp;&nbsp;<\/span>Q: Does origin of bean affects rating?<\/a><\/span><\/li><li><span><a href=\"#Q:-Recipie-of-which-company-should-we-follow-?\" data-toc-modified-id=\"Q:-Recipie-of-which-company-should-we-follow-?-3.5\"><span class=\"toc-item-num\">3.5&nbsp;&nbsp;<\/span>Q: Recipie of which company should we follow ?<\/a><\/span><\/li><li><span><a href=\"#Master-Choclatier?\" data-toc-modified-id=\"Master-Choclatier?-3.6\"><span class=\"toc-item-num\">3.6&nbsp;&nbsp;<\/span>Master Choclatier?<\/a><\/span><\/li><\/ul><\/li><li><span><a href=\"#4.-Final-Dashboard\" data-toc-modified-id=\"4.-Final-Dashboard-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;<\/span>4. Final Dashboard<\/a><\/span><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Three-Componenets-Of-DASH\" data-toc-modified-id=\"Three-Componenets-Of-DASH-4.0.1\"><span class=\"toc-item-num\">4.0.1&nbsp;&nbsp;<\/span>Three Componenets Of DASH<\/a><\/span><\/li><\/ul><\/li><\/ul><\/li><li><span><a href=\"#Summary:\" data-toc-modified-id=\"Summary:-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;<\/span>Summary:<\/a><\/span><\/li><\/ul><\/div>\n\"\"\"\n\"\"\"\n1. So much data, do not know what to do 90%\n2. Knows about data, but not good questions 9%  \n3. Knows exact question and exact answers 1%   (Social Media platforms, Shopping platform, Advance Daignostic Transport Platform)\n\nData: http:\/\/flavorsofcacao.com\/index.html\n\"\"\"\n\"\"\"\n## Loading Libraries\n\"\"\"\n!pip install chart_studio\nimport pandas as pd\nimport numpy as np\n\n\nfrom chart_studio.plotly import plot, iplot as py\n\nimport plotly.graph_objects as go\nfrom plotly.offline import iplot, init_notebook_mode\n\nimport cufflinks\ncufflinks.go_offline(connected=True)\ninit_notebook_mode(connected=True)\n\nfrom plotly.subplots import make_subplots\nimport plotly.express as px\n\nimport plotly.io as pio\npio.templates\n!ls ..\/input\/cocolate\/chocolate.csv\n\n\"\"\"\n# Descriptive Analysis\n\"\"\"\n\"\"\"\n## Trailer of data\n\"\"\"\ndf=pd.read_csv(\"..\/input\/cocolate\/chocolate.csv\", index_col=\"serial\")\ndf.head()\n\"\"\"\n### Shape\n\"\"\"\ndf.shape\n\"\"\"\n### Column Names\n\"\"\"\nfor col in df.columns:\n    print(col)\n\"\"\"\n### Converting haves and haves_not\n\"\"\"\ncol_to_boolean= [\"beans\",\"cocoa_butter\",\"vanilla\",\"lecithin\",\"salt\",\"sugar\",\"sweetener_without_sugar\"]\n\ndef have_not_have_to_bool(x):\n    if \"have_not\" in x:\n        y=0\n    else:\n        y=1\n    return y\n\nfor col in col_to_boolean:\n    df[col]=df[col].apply(have_not_have_to_bool)\ndf.head()\n\"\"\"\n### General Stats\n\"\"\"\ndf.describe()\n\"\"\"\n## KDE - Normal \n## Histogram\n\n\"\"\"\ncol_for_normal=[\"cocoa_percent\",\"rating\",\"counts_of_ingredients\"]\n\nfig = make_subplots(rows=1, cols=3)\n\nfor col in col_for_normal:\n    \n    i=col_for_normal.index(col)\n    \n    \n    fig.add_trace(\n        go.Histogram(x=df[col],\n                     histnorm='probability',\n                     name=col,),\n        \n        row=1,\n        col=col_for_normal.index(col)+1\n    )\n\n\nfig.update_layout(height=500, width=1000, title_text=\"Histogram\")\nfig.show()\n\"\"\"\n## Box PLot\n\"\"\"\ncol_for_normal=[\"cocoa_percent\",\"rating\",\"counts_of_ingredients\"]\n\nfig = make_subplots(rows=1, cols=3)\n\nfor col in col_for_normal:\n    \n    i=col_for_normal.index(col)\n    \n    \n    fig.add_trace(\n        go.Box(y=df[col], name=col),\n    \n        row=1,\n        col=col_for_normal.index(col)+1\n    )\n\n\nfig.update_layout(height=500, width=1000, title_text=\"Histogram\")\nfig.show()\n\"\"\"\n## Scatter Plot\n\"\"\"\ncol_for_normal=[\"cocoa_percent\",\"rating\",\"counts_of_ingredients\"]\n\ncorr_dict=[]\nfor col in col_for_normal:\n    corr_dict.append(\n        dict(label=col,values=df[col]),\n    )\n    \n\n\nfig = go.Figure(data=go.Splom(\n                dimensions=corr_dict,\n#                 diagonal_visible=False, # remove plots on diagonal\n                ))\n\n\nfig.update_layout(\n    title=\"Scatter Plot\",\n    width=1000,\n    height=1000,\n)\n\nfig.show()\n\"\"\"\n## Heat Map\n\n\"\"\"\ncol_for_normal=[\"cocoa_percent\",\"rating\",\"counts_of_ingredients\"]\n\ndf_cor=df[col_for_normal].corr()\n\nprint(df_cor)\nimport plotly.express as px\n\nfig = px.imshow(df_cor)\n\nfig.update_layout(\n    title='Heat Map',\n    width=500,\n    height=500,\n)\n\nfig.show()\n\"\"\"\n# Predcitive\n\n\n\"\"\"\n\"\"\"\n## OLS v1 adding only nominal variables\n\"\"\"\nimport statsmodels.api as sm\n\ncol_for_normal=[\"cocoa_percent\",\"rating\"]\nX=df[[\"cocoa_percent\",\"counts_of_ingredients\"]]\ny=df[[\"rating\"]]\nX = sm.add_constant(X)\n\nmodel = sm.OLS(y,X)\n\nresults = model.fit()\nresults.summary()\ndf.head()\n\"\"\"\n* Numerical regression= OLS\n* Nominal regression = probit \n* Ordinal regression = logit\n\"\"\"\n\"\"\"\n## OLS v2 adding all variables\n\"\"\"\nX=df[[\"cocoa_percent\",\"counts_of_ingredients\",\"beans\",\"cocoa_butter\",\"lecithin\",\"salt\",\"vanilla\",\"sugar\",\"sweetener_without_sugar\"]]\ny=df[[\"rating\"]]\n\nmodel = sm.OLS(y, X)\n\nresults = model.fit()\n\nresults.summary()\n\"\"\"\n* If the p-value is less than 0.05, \n\n    - we reject the null hypothesis that there's no difference between the means and conclude that a significant difference does exist. If the p-value is larger than 0.05, we cannot conclude that a significant difference exists.03-Dec-2015\n\n* H0:that there's no difference between the means\n* H1:difference exist\n\"\"\"\n\"\"\"\n## Stepwise OLS\n\"\"\"\nX=df[[\"cocoa_butter\",\"sugar\",\"vanilla\",\"sweetener_without_sugar\"]]\n     \ny=df[[\"rating\"]]\n\nmodel = sm.OLS(y, X)\nresults = model.fit()\n\nresults.summary()\nresults.params\n\"\"\"\n## PCA\n\"\"\"\nfrom sklearn.decomposition import PCA\n\nX=df[[\"cocoa_butter\",\"sugar\",\"vanilla\",\"sweetener_without_sugar\"]]\n# X=df[[\"cocoa_percent\",\"counts_of_ingredients\",\"beans\",\"cocoa_butter\",\"lecithin\",\"salt\",\"vanilla\",\"sugar\",\"sweetener_without_sugar\"]]\n\n\npca = PCA(n_components=2)\nprincipalComponents = pca.fit_transform(X)\n\npca_df= pd.DataFrame(data = principalComponents\n             , columns = ['pca1', 'pca2',], index=df.index)\n\npca_df[\"rating\"]=df[\"rating\"].round(1).astype(float)\npca_df[\"rating\"]*=10\npca_df[\"rating\"]=pca_df[\"rating\"].astype(int)\ndisplay(pca_df.head())\n\n\nfig = go.Figure(data=go.Scatter(\n                x=pca_df[\"pca1\"], y=pca_df[\"pca2\"],\n                mode='markers',\n                hovertext=pca_df[\"rating\"],\n                marker=dict(\n                    size=16,\n                    color=pca_df[\"rating\"],\n                    colorscale='aggrnyl',\n#                     colorscale=\"blues\",\n                    showscale=True)\n                ))\n\n\nfig.update_layout(title='Using PCA to reduce dimension',width=600,height=600)\n\nfig.show()\n\"\"\"\n## Clustering\n\"\"\"\nfrom sklearn.cluster import KMeans\n\nkmeans = KMeans(n_clusters=6, random_state=0).fit(pca_df)\nkmeans.labels_\n\npca_df[\"label\"]=kmeans.labels_\ndisplay(pca_df.head())\n\n\n\nfig = px.scatter(pca_df, x=\"pca1\", y=\"pca2\", color=\"rating\",  size=\"rating\",hover_data=[\"rating\"], )\nfig.update_layout( title=\"Rating\", width=500, height=400 ,)\nfig.show()\n\n\nfig = px.scatter(pca_df, x=\"pca1\", y=\"pca2\", color=\"label\",size=\"rating\", hover_data=[\"rating\",\"label\"])\nfig.update_layout( title=\"Cluster\", width=500, height=400 )\nfig.show()\n\"\"\"\n## Verifying clusters\n\"\"\"\nkmean_df=pca_df[[\"rating\",\"label\"]].groupby(\"label\").mean()\nkmean_df[\"std\"]=pca_df[[\"rating\",\"label\"]].groupby(\"label\").std()[\"rating\"]\ndisplay(kmean_df)\ngood_df=df[pca_df[\"label\"]==3]\n\nmy_order = good_df.groupby(by=[\"company\"])[\"rating\"].mean().iloc[::-1].index\nmy_order=my_order[:20]\nmy_order\n\ngood_df=good_df[good_df[\"company\"].isin(my_order)]\ndisplay(good_df.head())\n\ngood_df.groupby([\"company\",\"review_date\"])[\"rating\"].mean()\n\"\"\"\n## Wordcloud\n\"\"\"\nfrom wordcloud import WordCloud\nfrom matplotlib import pyplot as plt\n\n\ncol_to_combi=[\"first_taste\",\"second_taste\",\"third_taste\",\"fourth_taste\"]\n\ntext=[]\nfor col in col_to_combi:\n    t=good_df[col].tolist()\n    text.extend(t)\nclean_text=\"\"\nfor t in text:\n    if not pd.isna(t):\n        clean_text+= (str(t) +\",\")\n    else:\n        pass\n\nword_cloud = WordCloud(collocations = False, background_color = 'white').generate(clean_text)\nplt.imshow(word_cloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n# Prescriptive\n\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n## Q: Does Rating change evry year ?\n### Normal Distribution\n\"\"\"\nyear_list=sorted(set(df[\"review_date\"]))\n\nfig = plt.figure(figsize=(20,20))\n\na=3\nb=5\nc=1\n\np=sns.color_palette(\"Paired\")\np.extend(p)\n\n\nfor year in year_list:\n    plt.subplot(a,b,c)\n    plt.title(year)\n    sns.kdeplot(data=df[df[\"review_date\"]==year], x=\"rating\", fill=True,color=p[c-1])\n    c+=1\n    \nplt.show()\n\"\"\"\n### Boxplot\n\"\"\"\nfig = plt.figure(figsize=(20,20))\nsns.boxplot(data=df,x=\"review_date\",y=\"rating\").set_title(\"Rating vs Years Box Plot\")\n\"\"\"\n### Standard Deviation\n\n\"\"\"\nfig = plt.figure(figsize=(5,5))\n\nstd_df=df[[\"review_date\",\"rating\"]].groupby([\"review_date\"]).std().reset_index()\nsns.lineplot(x=std_df[\"review_date\"],y=std_df[\"rating\"]).set_title(\"Standard Deviation vs Time\")\n\"\"\"\n### Mean Rating over time \n\"\"\"\nfig = plt.figure(figsize=(5,5))\n\nmean_df=df[[\"review_date\",\"rating\"]].groupby([\"review_date\"]).mean().reset_index()\nsns.lineplot(x=mean_df[\"review_date\"],y=mean_df[\"rating\"]).set_title(\"Rating vs Time\")\n\"\"\"\n## Q: Which country and country makes the best chcolate?\n\"\"\"\nfig = plt.figure(figsize=(10,20))\nmy_order = df.groupby(by=[\"company_location\"])[\"rating\"].mean().iloc[::-1].index\nsns.boxplot(data=df,x=\"rating\",y=\"company_location\", orient=\"h\", order=my_order)\nplt.show()\n\"\"\"\n## Q: Which company makes the best choclate ?\n\"\"\"\nfig = plt.figure(figsize=(20,10))\n\nmy_order = df.groupby(by=[\"company\"])[\"rating\"].median().iloc[::-1].index\nmy_order_20=my_order[:20]\n\ncomp_df=df[df[\"company\"].isin(my_order_20)]\n\nsns.boxplot(data=comp_df,x=\"company\",y=\"rating\", orient=\"v\", order=my_order_20)\nplt.xticks(rotation=80, fontsize=15)\n\n\nplt.show()\n\"\"\"\n## Q: Does origin of bean affects rating?\n\"\"\"\nfig = plt.figure(figsize=(20,10))\n\nmy_order = df.groupby(by=[\"country_of_bean_origin\"])[\"rating\"].mean().iloc[::-1].index\nmy_order_20=my_order[:20]\n\ncomp_df=df[df[\"country_of_bean_origin\"].isin(my_order_20)]\n\nsns.boxplot(data=comp_df,x=\"country_of_bean_origin\",y=\"rating\", orient=\"v\", order=my_order_20)\nplt.xticks(rotation=60, fontsize=15)\n\nplt.show()\n\"\"\"\n## Q: Recipie of which company should we follow ?  \n\n\"\"\"\nfig = plt.figure(figsize=(20,30))\n\na=4\nb=5\nc=1\n\n\nmy_order = df.groupby(by=[\"company\"])[\"rating\"].median().iloc[::-1].index\nmy_order_20=my_order[:20]\n\ncomp_df=df[df[\"company\"].isin(my_order_20)]\n\n\nfor company in my_order_20:\n    plt.subplot(a,b,c)\n    plt.title(company)\n    sns.lineplot(data=comp_df[comp_df[\"company\"]==company], x=\"review_date\",y=\"rating\")\n    c+=1\n    \nplt.show()\n\"\"\"\n## Master Choclatier?\n\"\"\"\n# twenty-four-blackbirds, Zokoko\n\nmaster_df=df[df[\"company\"]==\"twenty-four blackbirds\"]\n\ndisplay(master_df.head())\n\nmaster_df.groupby([\"rating\",\"country_of_bean_origin\",\"first_taste\",\"second_taste\"]).sum()\n\"\"\"\n# 4. Final Dashboard\n\"\"\"\n\"\"\"\n### Three Componenets Of DASH\n\n1. Components ->Slider, Checkbox\n2. Graph -> Line char, Scatter plot\n3. Callback -> Function\n\"\"\"\n!pip install jupyter_dash dash_bootstrap_components\nimport plotly.express as px\nfrom jupyter_dash import JupyterDash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport dash_bootstrap_components as dbc\ndf.head()\nexternal_stylesheets = ['https:\/\/codepen.io\/chriddyp\/pen\/bWLwgP.css']\n\n\napp = JupyterDash(__name__, external_stylesheets=external_stylesheets)\n\n\napp.layout = html.Div([\n\n    html.H1(\"Web Application Dashboards with Dash\", style={'text-align': 'center'}),\n        \n    \n    \n    dcc.Slider(\n        id='year-slider',\n        min=df['review_date'].min(),\n        max=df['review_date'].max(),\n        value=df['review_date'].min(),\n        marks={str(year): str(year) for year in df['review_date'].unique()},\n        step=None\n    ),\n   \n    dcc.Dropdown(\n        id='graph-dropdown',\n        \n        options=[\n            {'label': 'Scatter', 'value': 'scatter'},\n            {'label': 'Box Plot', 'value': 'boxplot'},\n            {'label': 'Bar Plot', 'value': 'barplot'},\n            \n        ],\n        value='scatter'\n    ),\n            \n    dcc.Graph(id='graph-with-slider'),\n    \n    \n#     html.Label('Dropdown'),\n#     dcc.Dropdown(\n#         options=[\n#             {'label': 'New York City', 'value': 'NYC'},\n#             {'label': u'Montr\u00e9al', 'value': 'MTL'},\n#             {'label': 'San Francisco', 'value': 'SF'}\n#         ],\n#         value='MTL'\n#     ),\n\n#     html.Label('Multi-Select Dropdown'),\n#     dcc.Dropdown(\n#         options=[\n#             {'label': 'New York City', 'value': 'NYC'},\n#             {'label': u'Montr\u00e9al', 'value': 'MTL'},\n#             {'label': 'San Francisco', 'value': 'SF'}\n#         ],\n#         value=['MTL', 'SF'],\n#         multi=True\n#     ),\n\n#     html.Label('Radio Items'),\n#     dcc.RadioItems(\n#         options=[\n#             {'label': 'New York City', 'value': 'NYC'},\n#             {'label': u'Montr\u00e9al', 'value': 'MTL'},\n#             {'label': 'San Francisco', 'value': 'SF'}\n#         ],\n#         value='MTL'\n#     ),\n\n#     html.Label('Checkboxes'),\n#     dcc.Checklist(\n#         options=[\n#             {'label': 'New York City', 'value': 'NYC'},\n#             {'label': u'Montr\u00e9al', 'value': 'MTL'},\n#             {'label': 'San Francisco', 'value': 'SF'}\n#         ],\n#         value=['MTL', 'SF']\n#     ),\n\n#     html.Label('Text Input'),\n#     dcc.Input(id='my-input', value='initial value', type='text'),\n\n#     html.Label('Text Output'),\n#     html.Div(id='my-output'),\n    \n    \n    \n#     html.Label('Slider'),\n#     dcc.Slider(\n#         min=0,\n#         max=9,\n#         marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n#         value=5,\n#     ),\n\n    \n    \n])\n\n@app.callback(\n    Output('graph-with-slider', 'figure'),\n    Input('year-slider', 'value'),\n    Input('graph-dropdown', 'value')\n)\n\n\n\n\ndef update_figure(selected_year,graph_type):\n    filtered_df = df[df.review_date == selected_year]\n\n    \n    if graph_type==\"boxplot\":\n        \n        fig = px.box(filtered_df, x='company_location', y='rating',\n                    hover_name=\"company\",\n                    color=\"company_location\")\n \n        fig.update_layout(transition_duration=500)\n\n    elif graph_type==\"barplot\":\n        \n        fig = px.bar(filtered_df, x='company_location', y='rating',\n                    color=\"rating\", hover_name=\"company\",)\n \n        fig.update_layout(transition_duration=500)\n\n    elif graph_type==\"scatter\":\n        fig = px.scatter(filtered_df, x=\"company_location\", y=\"rating\",\n                         color=\"rating\", hover_name=\"company\",\n                         size=\"counts_of_ingredients\",\n    #                      log_x=True, \n                         size_max=55\n                        )\n\n        fig.update_layout(transition_duration=500)\n\n    return fig\n\n# ------------------------------------------------------------------------------\nif __name__ == '__main__':\n    app.run_server(mode='inline',debug=True)\n\"\"\"\n# Summary:\n1. Methods are always more important than tools\n2. Do not memorize code (Google question or find in Docs\n3. Prepare questions for data\n4. Simple Roadmap \n    1. Describe\n    2. Predict: Ols->StepOls ->Clustering\n    2. Prescribe: Questions ->more Question->Answer->Dashbaord\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2953325e122e6e'}"}
{"id":"58281","text":"\"\"\"\n# Starting Off...\nImporting the data, and necessary libraries. Welcome to my notebook!\n\"\"\"\nimport numpy as np \nimport pandas as pd\n\nfull_train_data = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\nfull_test_data = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n\ntrain_data = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntest_data = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n\"\"\"\n# Introduction:\n\nAs said before, welcome to my notebook! Today we'll be analyzing one's likelihood for survival on the Titanic, based on features of one's travel plan. Despite the grim nature of this project, considering the tragedy it is based around, this will be an attempt at a thorough and professional look at the subject at hand.\n\nSo, let's start with the basics. What's our *question*?\n\n**Question: Based on the features in the provided dataset, can we accurately predict one's survival on the Titanic? If so, how accurately?**\n**MOREOVER: How can we do this?**\n\nSo... it's clear then that we will be using a *machine learning* approach in answering this question, as we will be attempting to build an algorithm to learn from data for this particular example. Yet we must first understand the data we are using! \n\nSo! Let's move on to some interactive data analysis, shall we?\n\"\"\"\n\"\"\"\n# Interactive Data Analysis:\n\nThis is going to be a large and broad section, so let's start by laying out a *table of contents*:\n\n**1. Features of the datasets**\n\n**2. Missing Value Analysis**\n\n**3. Categorical Variable Handling**\n\n\"\"\"\n\"\"\"\n**Features of the Dataset:**\n\nSo let's start by training to view and understand the features of the dataset. We have the following features. \n\"\"\"\ntrain_data.info()\nprint(\"\\n\\n --- \\n\\n\")\ntest_data.info()\ntrain_data.head()\ntest_data.head()\n\"\"\"\n**Passenger-Id:** A simple number to keep track of each passenger, starting at 1. It seems the split from training to testing data occurs between passenger 891-892. \n\n**Pclass:** What class the passenger was a part of, ranging from 1st to 3rd (according to research on the Titanic's classes). It should be noted that 3rd class enjoyed the least preferable locations on the ship... towards the bottom and front\/back of the ship. As such, it would be unsurprising if the third class had the highest moratlity rate, though that trend will be looked for later.\n\n**Name:** Fairly self-describing... Last name, first name. Sometimes, for women, the women's full name (and maiden name) is given in parantheses after the married name. Ex: Mrs. Alexander (Helga E Lindqvist). \n\n**Sex:** Again, self-describing... 'male' or 'female', specified as such. \n\n**Age:** Number denoting the person's age. *Surprisingly*, this number is a float, and seems to denote fractions of ages as well.\n\n**SibSp:** Detailed in the dictionary, number of siblings + spouses aboard.\n\n**Parch:** Also detailed in the dictionary, number of parents + children aboard.\n\n**Ticket:** These seem to be most likely ticket numbers for each passenger. Essentially another way of keeping track of each passenger individually.\n\n**Fare:** Amount of money payed to embark. These numbers likley directly correspond to class, and other factors (perhaps number of parents, children, siblings, spouses... where he\/she embarked from... etc.). \n\n**Cabin:** Most of these values seem to be null... As an example, in the training data, there are 891 total values (as evidenced by the passenger IDs), and only 204 cabin values. These values, where they exist, seem to consist of the form \\[Letter\\]\\[Set of three numbers\\]. There are some passengers with multiple cabins listed. \n\n**Embarked:** Single letters listing the locations in which the passenger embarked the ship from. The ship, according to research, departed from Southhampton, stopped at Cherbourg, and Queenstown (now Cobh), and then departed for New York. Q likely corresponds to Queenstown, S=Southhampton, C=Cherbourg. \n\"\"\"\n\"\"\"\n**Missing Value Analysis:**\n\nLet's move on to checking for missing values, and understanding how we might deal with these issues. \n\"\"\"\ntrain_data.isnull().sum()\ntest_data.isnull().sum()\n\"\"\"\nLet's remember a few major pieces of information:\n\nSize of the training set: 891 passengers\n\nSize of the test set: 418 passengers\n\nThus the missing values can be broken down as follows...\n\"\"\"\n\"\"\"\n**Training:**\n\nAge: 177\/891 = approx 20%\n\nCabin: 687\/891 = approx 77.1%\n\nEmbarked: 2\/891 = approx 0.22%\n\"\"\"\n\"\"\"\n**Test:**\n\nAge: 86\/418 = approx 20.6%\n\nFare: 1\/418 = approx 0.24%\n\nCabin: 327\/418 = approx 78.2%\n\"\"\"\n\"\"\"\nThere's an issue here. The cabin value is obviously missing almost all of the time (upwards of 80% of the values are missing). **Yet!** ... the cabin value is ***extremely important***! The number itself, without an extremely in-depth knowledge of the Titanic's layout, is fairly useless for us to analyze... but the first letter indicates the *deck* that the cabin was located on, as presented by the image below.\n\n![Titanic_cutaway.png](attachment:Titanic_cutaway.png)\n\nIt is a shame then, that the cabin value seems to be extremely useful, but not really accessible en masse. Yet! *PClass* will serve our purposes here, as the class one traveled in directly corresponds to the deck one would be assigned to. To increase the accuracy of this model, using cabin values may be added as an option, but seeing as so many values are missing, we will drop the cabin column. \n\"\"\"\ndel train_data[\"Cabin\"]\ndel test_data[\"Cabin\"]\n\nprint(\"Cabin columns deleted\")\n\"\"\"\nLet's also try and figure out how to handle the *age*, *embarked*, and *fare* missing values in both the training and testing data. Age is a little difficult as, by the cacluations done above, approximately 20% of the training data's rows are missing the age values. Yet, if we think about the time, it's likely that the elderly would be evacuated first (and, though grim, it's likely that the elderly in, say, 3rd class, would've had a hard time reaching the lifeboats). Thus, it's clear that age is an important feature... or at least one that should be included in an inital model for testing purposes. So! We must figure out how to deal with the missing values.\n\nIn this case... for an inital model, and seeing as the age category is numeric, it's likely most fair to say that we can probably get by with assigning the average age... so let's calculate and assign that.\n\"\"\"\n# Calculate the average age\nprint(\" - Calculating average ages - \\n\\n\")\naverage_train_age = 0\naverage_test_age = 0\ncount = 0\nfor age in train_data[\"Age\"]:\n    if not pd.isnull(age):\n        count += age\naverage_train_age = count\/train_data[\"Age\"].count()\n\ncount = 0\n\nfor age in test_data[\"Age\"]:\n    if not pd.isnull(age):\n        count += age\naverage_test_age = count\/test_data[\"Age\"].count()\nprint(\"Average training-set age: %s\" % average_train_age)\nprint(\"Average test-set age: %s\" % average_test_age)\n\nprint(\"\\n\\n - Rounding up - \\n\\n\")\n\n# Rounding up (to fit the format of the data, one decimal)...\naverage_train_age = round(average_train_age, 1)\naverage_test_age = round(average_test_age, 1)\n\nprint(\"Average training-set age: %s\" % average_train_age)\nprint(\"Average test-set age: %s\" % average_test_age)\n\n# Assign it to the missing values\n\nprint(\"\\n\\n - Assigning average values - \\n\\n\")\nfor i in range(0, train_data[\"PassengerId\"].count()):\n    if pd.isnull(train_data.iloc[i][\"Age\"]):\n        train_data.at[i, \"Age\"] = average_train_age\nfor i in range(0, test_data[\"PassengerId\"].count()):\n    if pd.isnull(test_data.iloc[i][\"Age\"]):\n        test_data.at[i, \"Age\"] = average_test_age\nprint(\"Done\")\n\"\"\"\nNext up is **embarked**, which is only missing in a few of the values. \n\n... Hmm. This one is a little difficult. It's a categorical variable, which we're gonna have to deal with later, but for now we have to deal with the fact that it's got a few missing values. Any sort of logical guessing is definitely not going to work... based on the information we have there's no way to logically deduce where a person embarked from. It's *very* unlikely that this feature matters at all... it's just the location someone boarded after all. But certain factors, such as more familiarity with the ship's layouts, or common sounds, might've helped a passenger survive in an odd incident. \n\nLet's d a little digging on the *embarked* feature, see if we can understand it a little better.\n\nFirst off, number of unique values.\n\n(We'll only concern ourselves with the training data, as no values are missing for embarked from the testing data). \n\"\"\"\nprint(\"Embarked unique values count: %s\" % train_data[\"Embarked\"].nunique())\n\n# Next, let's try list those values...\nembarked_unique_vals = []\n\nfor loc in train_data[\"Embarked\"]:\n    if not loc in embarked_unique_vals:\n       embarked_unique_vals.append(loc) \nprint(\"Embarked unique values: %s\" % embarked_unique_vals)\n\n# This fits exactly the prediction we had earlier!\n\"\"\"\nGreat! So it's exactly as we predicted earlier, in the feature description. Let's see if we can get an \"average\" value... or which value, of S, C, Q, occurs the most.\n\"\"\"\nprint(\"Training data: \\n%s\\n\\n\" % train_data[\"Embarked\"].value_counts())\n\"\"\"\nGreat, so we see it's the same result for both. S (Southampton) is the most common embarked location. Little issue here, it seems that the data is almost completely Southampton in the training set, and only just over half Southampton for the testing. We'll talk about such things in the skewness chapter though, for now let's focus on the \"average\" value.\n\nIt's quite clear that we'll be selecting S, or Southampton, for our \"average\" value in this case. Let's going ahead and replace all NaN values for embarked with S. \n\"\"\"\nprint(\"Before fix, number of null values: %s\" % train_data[\"Embarked\"].isnull().sum())\ntrain_data[\"Embarked\"].fillna(\"S\", inplace=True)  \nprint(\"After fix, number of null values: %s\" % train_data[\"Embarked\"].isnull().sum())\n\"\"\"\nIt's only a small fix, in this case, but it's all that's needed. \n\nAlright, final issue! Let's fix the missing value for fare in the test data! Let's just average the fares, and assign that. It's a simple fix, but it's only a single missing value.\n\nBut! Let's try and do it with a little intelligence. Not only the machines should do the learning, huh? Let's figure out the person's assigned class first.\n\"\"\"\nfare_missing_value_row = 99999\nfor i in range(0, test_data[\"PassengerId\"].count()):\n    if pd.isnull(test_data.at[i, \"Fare\"]):\n        fare_missing_value_row = i\nprint(\"Person: \\n%s\" % test_data.loc[fare_missing_value_row])\nprint(\"\\n\\n - Determining class - \\n\\n\")\nprint(\"Class: %s\" % test_data.at[fare_missing_value_row, \"Pclass\"])\n\"\"\"\nWe did it! We got his class, 3. So let's average the fares (from the test data) from his *class* only. \n\"\"\"\ntest_fare_average = 0 \nfor i in range(0, test_data[\"PassengerId\"].count()):\n    if not pd.isnull(test_data.at[i, \"Fare\"]) and test_data.at[i, \"Pclass\"] == 3:\n        test_fare_average += test_data.at[i, \"Fare\"]\ntest_fare_average \/= test_data[\"PassengerId\"].count()\nprint(\"Unrounded fare average: %s\" % test_fare_average)\n# Round to 4 decimals to fit the data's format\ntest_fare_average = round(test_fare_average, 4)\nprint(\"Rounded fare average: %s\" % test_fare_average)\n# Let's assign it now...\ntest_data.at[fare_missing_value_row, \"Fare\"] = test_fare_average\nprint(\"After fix, number of missing values in Fare (test data): %s\" % test_data[\"Fare\"].isnull().sum())\n\n\"\"\"\nGreat! We've fixed all the missing values! Observe...\n\"\"\"\ntrain_data.isnull().sum()\ntest_data.isnull().sum()\n\"\"\"\n**Handling Categorical Variables:**\n\"\"\"\n\"\"\"\nAnother large challenge in a machine learning approach is figuring out how to deal with the issue of *categorical* variables, or non-numerical variables. As an example, we can't provide someone's name just as a string of characters to the machine learning algortitms we're going to apply today, but we can provide numbers. So! Let's lay out our data again, determine which variables are categorical, and how we'll deal with this.\n\"\"\"\ntrain_data.info()\ntest_data.info()\n\"\"\"\nGreat, so we can see right away that Name, Sex, Ticket, and Embarked, are categorical variables. Cabin is as well, but we've already removed it from consideration.\nLet's start off easy. For an inital model, patterns in name, and survival, aren't likely to exist... so to save time and effort, we're just going to remove Name as a column.\n\nSex is definitely going to be a different story though, as it can be shown to play a much larger role in who survived, and who didn't (as women and children would be evacuated first). As just an example of that...\n\"\"\"\n# Before the example, remove name as a column.\ndel train_data[\"Name\"]\ndel test_data[\"Name\"]\n\n# So, how important is the gender feature? How many people from each gender survived (at least in the training data)? Let's see.\nfemale_passengers = [train_data.iloc[i] for i in range(0, len(train_data.index)) if train_data.iloc[i][3] == \"female\"]\nmale_passengers = [train_data.iloc[i] for i in range(0, len(train_data.index)) if train_data.iloc[i][3] == \"male\"]\n\nfemale_survivors = [female_passengers[i] for i in range(0, len(female_passengers)) if female_passengers[i][1]==1]\nmale_survivors = [male_passengers[i] for i in range(0, len(male_passengers)) if male_passengers[i][1]==1]\n\nprint(\"Number of male survivors (from training data): %s\" % len(male_survivors))\nprint(\"Number of female survivors (from training data): %s\" % len(female_survivors))\n\n# Let's remember the total number of people in the training set.\n\nprint(\"Total number of passengers on the Titanic (from the training data): %s\" % len(train_data.index))\nprint(\"Total number of female passengers on the Titanic (from the training data): %s\" % len(female_passengers))\nprint(\"Total number of male passengers on the Titanic (from the training data): %s\" % len(male_passengers))\n\n# Thus... survival rate. (Rounded to 1 decimal)\nprint(\"Rounded female survival rate: %s%%\" % (100 * round(len(female_survivors) \/ len(female_passengers), 3)))\nprint(\"Rounded male survival rate: %s%%\" % (100 * round(len(male_survivors) \/ len(male_passengers), 3)))\n\"\"\"\nOkay, so gender is needed. We won't one-hot encode that, as it seems to be a little too much trouble for a variable that can simply be encoded as binary, so we'll assign 1=male, 0=female. \n\nTicket has too many possible values, and many aren't very understandable. Perhaps this could be revisisted to improve model performance, but for now we're just going to drop Ticket.\n\nEmbarked might be important. It will be one-hot encoded, but, for now, let's just handle the above statements, and then .info() the data, and then in the following box we'll take a look at how much \"embarked\" had an effect.\n\"\"\"\n# Let's drop Ticket first\ndel train_data[\"Ticket\"]\ndel test_data[\"Ticket\"]\n\n# Now let's label encode sex\nfrom sklearn.preprocessing import LabelEncoder\nlabel_encoder = LabelEncoder()\n\ntrain_data[\"Sex\"] = label_encoder.fit_transform(train_data[\"Sex\"])\ntest_data[\"Sex\"] = label_encoder.transform(test_data[\"Sex\"])\n\n# Let's take a look at how important \"embarked\" is\nS_passengers = [train_data.iloc[i] for i in range(0, len(train_data.index)) if train_data.iloc[i][8] == \"S\"]\nC_passengers = [train_data.iloc[i] for i in range(0, len(train_data.index)) if train_data.iloc[i][8] == \"C\"]\nQ_passengers = [train_data.iloc[i] for i in range(0, len(train_data.index)) if train_data.iloc[i][8] == \"Q\"]\n\nS_survivors = [S_passengers[i] for i in range(0, len(S_passengers)) if S_passengers[i][1]==1]\nC_survivors = [C_passengers[i] for i in range(0, len(C_passengers)) if C_passengers[i][1]==1]\nQ_survivors = [Q_passengers[i] for i in range(0, len(Q_passengers)) if Q_passengers[i][1]==1]\n\nprint(\"Number of Southampton survivors (from training data): %s\" % len(S_survivors))\nprint(\"Number of Cherbourg survivors (from training data): %s\" % len(C_survivors))\nprint(\"Number of Queenstown survivors (from training data): %s\" % len(Q_survivors))\n\n# Let's remember the total number of people in the training set.\n\nprint(\"Total number of passengers on the Titanic (from the training data): %s\" % len(train_data.index))\nprint(\"Total number of Southampton passengers on the Titanic (from the training data): %s\" % len(S_passengers))\nprint(\"Total number of Cherbourg passengers on the Titanic (from the training data): %s\" % len(C_passengers))\nprint(\"Total number of Queenstown passengers on the Titanic (from the training data): %s\" % len(Q_passengers))\n\n# Thus... survival rate. (Rounded to 1 decimal)\nprint(\"Rounded Southampton survival rate: %s%%\" % (100 * round(len(S_survivors) \/ len(S_passengers), 3)))\nprint(\"Rounded Cherbourg survival rate: %s%%\" % (100 * round(len(C_survivors) \/ len(C_passengers), 3)))\nprint(\"Rounded Queenstown survival rate: %s%%\" % (100 * round(len(Q_survivors) \/ len(Q_passengers), 3)))\n\"\"\"\nHmm. Embarked didn't seem to have that much of a noticeable effect. It is true though, that there is far more data for Southampton's survival chances (as there are a far more Southamtpon passengers than any other city) than there are for the other cities.\n\nEither way though, it definitely seems like a useful variable. At any rate, there's nothing stopping us from including it, and our machine learning approach may find something with it we miss.\n\nSo, to make it useable, let's one-hot encode it. \n\"\"\"\n# One-hot encode the \"Embarked\" value\nfrom sklearn.preprocessing import OneHotEncoder\n\none_hot_enc = OneHotEncoder(categories='auto', handle_unknown='ignore', sparse=False) # ignore values that aren't present in the training data, and return values as a numpy array. Though the first parameter is unlikely to be needed.\n\nOH_cols_train = pd.DataFrame(one_hot_enc.fit_transform(train_data.Embarked.values.reshape(-1, 1))) \nOH_cols_test = pd.DataFrame(one_hot_enc.transform(test_data.Embarked.values.reshape(-1, 1)))\n\nOH_cols_train.index = train_data.index\nOH_cols_test.index = test_data.index\n\ndel train_data[\"Embarked\"]\ndel test_data[\"Embarked\"]\n\ntrain_data = pd.concat([train_data, OH_cols_train], axis=1)\ntest_data = pd.concat([test_data, OH_cols_test], axis=1)\n\n\"\"\"\nGreat! Column 0 = C, 1 = Q, 2 = S. \n\nOneeeee final change, PassengerID won't be useful in learning, as it's just a counter for each passenger, and not actual data. This isn't technically a categorical variable, but seeing as this is our final bit of preprocessing, I've included it here. \n\"\"\"\ndel train_data[\"PassengerId\"]\ndel test_data[\"PassengerId\"]\ntrain_data.head()\ntest_data.head()\n\"\"\"\n# Machine Learning (XGBoost):\n\nWe're here! Finally, time to start making predictions. We've analyzed (a little) our data, and set up our dataset for usage. The only step in between us and predictions now is the fact that we haven't seperated the target, survived, from our training data. We'll do that, and start training!\n\"\"\"\n# Seperate the target, survived, from our training data.\n\ny = train_data[\"Survived\"]\ntrain_data = train_data.drop(['Survived'], axis=1)\n\n# Import XGRegressor\nfrom xgboost import XGBRegressor\n\n# Create model and fit\nmodel = XGBRegressor()\nmodel.fit(pd.get_dummies(train_data), y)\n\n# Get predictions\npredictions = model.predict(pd.get_dummies(test_data))\n\n# Round each prediction up or down to get a whole 0, or 1.\npredictions = [round(x) for x in predictions]\nint_predictions = [int(x) for x in predictions]\n\n# Save and submit\noutput = pd.DataFrame({'PassengerId': full_test_data.PassengerId, 'Survived': int_predictions})\noutput.to_csv('my_submission.csv', index=False)\noutput.head() #  Output first few predictions\n\"\"\"\n# Thank you!\n\nI hope this notebook is useful in some way! This is my first published notebook, so if you have any comments at all, please feel free to leave them down in the comments section.\nThank you again!\n\nSources:\nhttps:\/\/en.wikipedia.org\/wiki\/RMS_Titanic#:~:text=After%20leaving%20Southampton%20on%2010,11%3A40%20p.m.%20ship's%20time.\nhttps:\/\/www.kaggle.com\/c\/titanic\/discussion\/4693\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6ba1a21de9b704'}"}
{"id":"14185","text":"\"\"\"\n<h1><center><font size=\"6\">fastai-v2\/GPU for Chinese MNIST Prediction<\/font><\/center><\/h1>\n\n# <a id='0'>Table of Contents<\/a>\n\n- <a href='#1'>Introduction<\/a>  \n- <a href='#2'>Preparing our Data<\/a>   \n- <a href='#3'>Preparing our DataBlock<\/a>   \n- <a href='#4'>Preparing our Learner<\/a> \n- <a href='#5'>Baseline Model<\/a> \n- <a href='#6'>Improving our Model<\/a> \n- <a href='#7'>Conclusions<\/a> \n\"\"\"\n\"\"\"\n# <a id='1'>Introduction<\/a> \n\"\"\"\n\"\"\"\nThe Chinese MNIST dataset provides us with 15,000 images of Chinese numbers handwritten by 100 volunteers. Each participant provided 10 samples of the 15 Chinese characters for numbers. \n\nThe objective of this notebook is to demonstrate how to solve the Chinese MNIST classification task with 0.999 accuracy using: \n1. `fastai` version 2\n2. GPU acceleration\n3. Multilabel classification\n\"\"\"\n\"\"\"\n# <a id='2'>Preparing our Data<\/a>   \n\"\"\"\n\"\"\"\n### Install Dependencies\n\"\"\"\nimport fastai\nfrom fastai.vision.all import *\nfrom fastai.vision.widgets import *\nimport pandas as pd\nimport os\n\"\"\"\n### Import Files\n\"\"\"\n#imports files from kaggle\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\nAfter importing your files, you can create a `path` to the folder that contains your images. The `path` object contains a `.ls()` method that behaves similar to a Python `list` but has additional functionality. \n\"\"\"\n#creates a path to the folder containing image files\npath = Path(\"..\/input\/chinese-mnist\/data\/data\")\n\n#makes .ls() format easier to read  \nPath.BASE_PATH = path\n\n#checks image files using .ls() method\npath.ls()\n\"\"\"\n### Create a DataFrame\n\"\"\"\n\"\"\"\nThe Chinese MNIST dataset also contains a CSV file that we can use to label our variables.\n\"\"\"\ndf = pd.read_csv(\"..\/input\/chinese-mnist\/chinese_mnist.csv\")\ndf.head()\n\"\"\"\nWe currently don't have a column that we can use to reference our x variables\/images. \n\nNotice that our image files have a similar structure. For example, `\"input_47_6_7.jpg\"` and `\"input_12_8_2.jpg\"` share various components. All of our image files begin and end similarly, and they all contain, in the same order, the number of the participant, the number of the sample, and the code of the Chinese character.\n\nWe can create a new column in Pandas and use our existing columns to concatenate our file names.\n\"\"\"\ndf['fname'] = (\"input_\" + df['suite_id'].astype(str) \n               + \"_\" \n               + df['sample_id'].astype(str) \n               + \"_\" \n               + df['code'].astype(str) \n               + \".jpg\")\ndf.head()\n\"\"\"\n# <a id='3'>Preparing our DataBlock<\/a>  \n\"\"\"\n\"\"\"\n### Define Variables\n\"\"\"\n\"\"\"\nNow that we have our DataFrame, we can define our variables. We can use our new `fname` column for our x variables, but we will need to attach a path to each variable. We can also use our `value` column to label our y variables.\n\"\"\"\ndef get_x(r): return path\/r['fname']\n\n#.astype() and .split() method were added to contain each label\ndef get_y(r): return r['value'].astype(str).split(\" \")\n\"\"\"\n### From DataFrames to DataLoaders\n\"\"\"\n\"\"\"\nBefore we jump into creating a `DataLoaders` object, lets review some terminology. Note that the last two classes are specific to fastai and build ontop of PyTorch's `Dataset` and `DataLoader` classes.\n\n* `Dataset`: A collection that returns a tuple of your independent and dependent variable for a single item.\n* `DataLoader`: An iterator that provides a stream of mini-batches, where each mini-batch is a tuple of a batch of independent variables and a batch of dependent variables.\n* `Datasets`: An object that contains a training `Dataset` and a validation `Dataset`.\n* `DataLoaders`: An object that contains a training `DataLoader` and a validation `DataLoader`.\n<p><font size=\"1\">*From \"Deep Learning for Coders with Fastai and PyTorch\" - credit to fastai\/Jeremy Howard\/Sylvain Gugger<\/font><\/p>\n\nWe will need to compile a `DataBlock` to create our `DataLoaders` object:\n\"\"\"\n#creates a Datablock object\ndblock = DataBlock(blocks=(ImageBlock, MultiCategoryBlock),\n                  splitter=RandomSplitter(seed=42),\n                  get_x=get_x,\n                  get_y=get_y,\n                  item_tfms = RandomResizedCrop(128, min_scale=0.35))\n\n# passes our dataframe into the dataloaders method of our DataBlock object\ndls = dblock.dataloaders(df)\n\"\"\"\nLets break this down: \n* `blocks` let us to pass `ImageBlock` and `MultiCategoryBlock.` Even though we converted our x variables into image paths, we still need a method to open our images and to transform them into tensors. `ImageBlock` does this. \n* `MultiCategoryBlock` allows us to have multiple labels for each item. More on one-hot-encoding later.\n* `splitter` splits our `DataFrame` into a training and validation set. Default split is 80\/20.\n* `get_x` calls our `get_x` function to retreive our image paths. \n* `get_y` calls our `get_y` function to retreive our image labels.\n* `item_tfms` makes sure all of our images are the same scale and GPU compatible.\n* `dblock.dataloaders(df)` creates a `DataLoaders` object and passes in our `DataFrame`.\n\nLet's analyze our new `DataLoaders` object: \n\"\"\"\n#displays number of batches for our training and validation sets\nlen(dls.train), len(dls.valid)\n#displays a batch with images and labels\ndls.show_batch(nrows=1, ncols=5)\n#displays training Dataset\ndls.train_ds\n#displays validation Dataset\ndls.valid_ds\n\"\"\"\nNotice that our `DataLoaders` object has split our `DataFrame` into a training `Dataset` of 12,000 and a validation `Dataset` of 3,000. Furthermore, our `DataLoaders` object transforms our `Dataset` objects into batches. \n\nAlso notice the structure of our `Dataset` objects:\n* Our x variables are images with a size of 64x64 pixels. \n* The lists of 0s and 1s contains our category labels and refers to ***one-hot-encoding***. Each category is considered independently and a 1 is granted if the category is present. Therefore, we can expect to see 15 digits for our 15 possible categories. \n* Although we don't expect to find multiple labels in our data, our multilabel classification approach allows our model to choose no label in the abscence of a prediction above our treshold. This is in contrast to a multicategory classification model with a softmax loss function which always predicts a category label even when there are no valid matches.\n\"\"\"\n\"\"\"\n# <a id='4'>Preparing our Learner<\/a>   \n\"\"\"\n\"\"\"\n### Batch Testing the Model\n\"\"\"\n\"\"\"\nBefore we test our `DalaLearner` object, lets generate predictions from a single batch.\n\"\"\"\n#uses fastai's resnet18 model\nlearn = cnn_learner(dls, resnet18)\n\n#creates a batch from our train dataset\nx,y = to_cpu(dls.train.one_batch())\n\n#generates predictions from our batch\nbatch = learn.model(x)\n#analyzes batch\nbatch.shape\n\"\"\"\nOur batch size is 64 images, which is the default for fastai, and each image is generating predictions for 15 seperate categories. Lets analyze a single image:\n\"\"\"\n#we can index into our batch to return predictions for a single image\nbatch[0]\n\"\"\"\nAs we expected, our image is receiving predictions for each of our 15 categories. We will compare our predictions with our targets\/labels to calculate a loss.\n\"\"\"\n\"\"\"\n### Loss Function\n\"\"\"\n\"\"\"\nBy default, fastai will apply a Binary Cross-Entropy loss function to multilabel classification problems. We can call `loss_func` on our learner object to see our loss function. \n\"\"\"\nlearn.loss_func\n\"\"\"\n* Because we have a one-hot-encoded dependent variable, we cannot use a cross entropy loss function. The softmax function that's used to transform predictions into comparative activations makes it impossible to do multilabel classification. Softmax tends to push one activation over the others and cannot identify multiple labels in one image.\n* Instead, a Binary Cross-Entropy loss function uses a sigmoid function to transform our predictions into activations between 0 and 1. Each prediction is then compared with our targets using a similar function to `mnist_loss`.\n* `BCEWithLogitsLoss` refers to both sigmoid and binary cross-entropy loss in a single function\n\"\"\"\n#defining our own sigmoid function\ndef sigmoid(x): return 1\/(1+torch.exp(-x))\n\n#defining our own BCELoss function  \ndef binary_cross_entropy(inputs, targets):\n    inputs = inputs.sigmoid()\n    return -torch.where(targets==1, inputs, 1-inputs).log().mean()\n\"\"\"\nNow that we understand `BCEWithLogitsLoss`, lets compare our batch predictions with our targets.\n\"\"\"\n#creates a loss function\nloss_func = nn.BCEWithLogitsLoss()\n\n#passes our predictions and our labels into our loss function\nloss = loss_func(batch, y)\n\n#prints out or loss\nloss\n\"\"\"\nNotice the `grad_fn` attribute. This tells us fastai is automatically keeping track of our gradients for us! Our gradients will be calculated from our loss and they will be used to update our parameters.\n\"\"\"\n\"\"\"\n### Metrics for Accuracy\n\"\"\"\n\"\"\"\nWe will also need to make sure our metric is compatible with our multilabel classification task. Because we could have more than one prediction on a single image, we need to pick a treshold to evaluate the accuracy of each prediction. The default treshold in fastai is 0.5, but Jeremy Howard suggests using 0.2.\n\"\"\"\ndef accuracy_multi(inp, targ, thresh=0.5, sigmoid=True):\n    if sigmoid: inp = inp.sigmoid()\n    return ((inp>thresh)==targ.bool()).float().mean()\n\"\"\"\n# <a id='5'>Baseline Model<\/a>\n\"\"\"\n\"\"\"\n### Results\n\"\"\"\n\"\"\"\nNow that we have our `DataLoaders` object, lets create a `learner`. \n\"\"\"\nlearn = cnn_learner(dls, resnet18, metrics=partial(accuracy_multi, thresh=0.2))\nlearn.fine_tune(6)\n\"\"\"\nOur baseline model was able to achieve 0.999 accuracy on our first attempt. Lets break down the `learner` object to see how we got our results:  \n* `cnn_learner` is a fastai class that allows us to build our model with a pretrained convolutional neural network. \n* `dls` is our `DataLoaders` object that contains our images in batches of training and validation sets.\n* `resnet18` tells fastai we want to use a pretrained `cnn` with 18 layers.\n* `metrics` calls our `accuracy_multi()` function which is needed for multilabel classification.\n* `fine_tune` is a fastai method that allows us to train our model and pass in the total number of epochs\n* `base_lr` is our learning rate which will be multiplied by our gradients to inform new activations. The default learning rate in fastai is 1e-3 and does not need to be specified inside of `fine_tune`. \n\"\"\"\n\"\"\"\n### Model Analysis\n\"\"\"\n\"\"\"\nNow that we have our results, we can plot our top losses with fastai's `ClassificationInterpretation` class. Notice that our `probabilities` category is a tensor of 15 predictions for each image. \n\"\"\"\ninterp = ClassificationInterpretation.from_learner(learn)\ninterp.plot_top_losses(5, nrows=1)\n\"\"\"\nOut of our 3000 images in our validation set, our model only mislabeled a few. Because we are using one-hot-encoding our results are saying actual 1s were predicted as 0s x times, and actual 0s were predicted as 1s y times. In any case, we can use the sum of x and y to determine the total number of mislabelled images.\n\"\"\"\ninterp.most_confused(5)\n\"\"\"\n# <a id='6'>Improving our Model<\/a>\n\"\"\"\n\"\"\"\n### Learning Rate Finder\n\"\"\"\n\"\"\"\nWe can improve our model by finding our ideal learning rate. Fastai lets us do this with the `.lr_find()` method on our `learner` object:\n\"\"\"\nlearn = cnn_learner(dls, resnet18, metrics=partial(accuracy_multi, thresh=0.2))\nlearn.lr_find()\n\"\"\"\nWe can see that there's not much activity between 1e-7 and 1e-3 (fastai's default learning rate), so lets test a learning rate of 1e-2:\n\"\"\"\nlearn = cnn_learner(dls, resnet18, metrics=partial(accuracy_multi, thresh=0.2))\nlearn.fine_tune(6, base_lr=1e-2)\n\"\"\"\nOur results improved! But there's still more we can do. \n\"\"\"\n\"\"\"\n### Unfreezing and Transfer Learning\n\"\"\"\n\"\"\"\nBecause we are using transfer learning, we are replacing the final linear layer of our `cnn` with a new layer of random weights. We want to train a model in such a way that it is able to remember the useful ideas from the pretrained model so that it can adjust these weights as required for our specific task. We can do this by freezing pretrained layers and only updating the weights for our new linear layer. \n\n`fastai` lets us do this with the `fit_one_cycle` method:\n\"\"\"\nlearn = cnn_learner(dls, resnet18, metrics=partial(accuracy_multi, thresh=0.2))\nlearn.fit_one_cycle(3, base_lr=1e-2)\n\"\"\"\nNow that we've gone through 3 epochs, we can unfreeze our pretrained layers using the fastai `.unfreeze()` method:\n\"\"\"\nlearn.unfreeze()\n\"\"\"\nAfter unfreezing our layers, we call the `.lr_find` method again since adding new layers results in a new learning rate:\n\"\"\"\nlearn.lr_find()\n\"\"\"\nWe don't have a steep decending slope like our previous plot because the model has already been trained. The goal is to pick a point before the sharp increase, not the maximum gradient. Given the flattened slope, we will train our model with our transfered weights for 6 more epochs.\n\"\"\"\nlearn.fit_one_cycle(6, 1e-4)\n\"\"\"\nOur accuracy has increased once more!\n\"\"\"\n\"\"\"\n# <a id='7'>Conclusions<\/a>\n\"\"\"\n\"\"\"\nWe were able to create a baseline model with .999+ accuracy using fastai's library, gpu acceleration, and multilabel classification. We were further able to improve our model by freezing our pretrained weights and by finding the ideal learning rates for multiple steps in our model. There is still some fine-tuning we can do, but this should be enough to get others started with fastai and multilabel classification!\n\nThank you to Jeremy Howard.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '19eeb6accc2906'}"}
{"id":"105383","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\ngenome_desc = pd.read_csv('..\/input\/genome_file_description.csv')\ngenome = pd.read_csv('..\/input\/genome_zeeshan_usmani.csv')\ngenome.head()\ngenome[\"chromosome\"].value_counts()\nchromosomes = {k: v for k, v in genome.groupby('chromosome')}\nchromosomes.keys()\nfor i in chromosomes:\n    chromosomes[i].sort_values(by='position')\nprint(chromosomes[1][0:10])\nprint(chromosomes['X'][0:10])\n\"\"\"\nFor more info on the dataset and how it is obtained I read here: https:\/\/customercare.23andme.com\/hc\/en-us\/articles\/115004459928-Raw-Genotype-Data-Technical-Details\n\"\"\"\n\"\"\"\n**Sex**\n\n\n\"\"\"\nchromosomes.keys()\ngenome.loc[genome['chromosome'] == 'Y'].head()\n\"\"\"\nThere is a Y chromosome with SNP data present so the patient is a male.\n\"\"\"\n\"\"\"\n**Eye color**\n\n\"\"\"\ngenome.loc[genome['# rsid'].isin(['rs4778241','rs12913832','rs7495174', 'rs8028689', 'rs7183877', 'rs1800401'])] #genoset 237 for eye color - SNPedia. \n\n\"\"\"\nThe subject is heterozygous in rs4778241 and rs7495174, which if homozygous C and A respectively, form a hapotype for blue-eyes association. Thus the subject likely does not have blue- eyes.\n\"\"\"\n\"\"\"\nThe rs1799971(G) allele in exon 1 of the mu opioid receptor OPRM1 gene causes the normal amino acid at residue 40, asparagine (Asn), to be replaced by aspartic acid (Asp). In the literature this SNP is also known as A118G, N40D, or Asn40Asp.\n\nCarriers of at least one rs1799971(G) allele appear to have **stronger cravings for alcohol** than carriers of two rs1799971(A) alleles, and are thus hypothesized to be more at higher risk for alcoholism. [PMID 17207095]\n\"\"\"\ngenome.loc[genome['# rsid'] == 'rs1799971']\n\"\"\"\nSample appears to be heterozygous - having one A allele and one G allele.\n![image.png](attachment:image.png)\n\n\"\"\"\n\"\"\"\nrs1333049 has been reported in a large study to be **associated with heart disease, in particular, coronary artery disease**.\n\nThe risk allele (oriented to the dbSNP entry) is most likely (C); the odds ratio associated with heterozygotes is 1.47 (CI 1.27-1.70), and for homozygotes, 1.9 (CI 1.61-2.24). [PMID 17554300OA-icon.png]\n\"\"\"\ngenome.loc[genome['# rsid'] == 'rs1333049']\n\"\"\"\n1. CG shown to have increased risk of coronary artery disease...\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n**Alzheimers:** ![image.png](attachment:image.png)\n\"\"\"\ngenome.loc[genome['# rsid'] == 'rs7412']\n\ngenome.loc[genome['# rsid'] == 'rs429358']\n\"\"\"\nSo this patient seems to have the ApoE-\u03b53 allele. ![image.png](attachment:image.png)\nwhich does not seem to indicate elevated Alzheimer's risk from just looking at these 2 SNPs.\n\"\"\"\n\"\"\"\nFor further reference about Apo-e4 genotypes: \n\nAPOE-\u03b54 carriers may have their risk of developing Alzheimer's disease modified by SNPs elsewhere in their genomes. For example:\n\nrs2373115, a SNP in the GAB2 gene\nInheritance of the rs1799724(T) allele appears to synergistically increase the risk of Alzheimer's in ApoE-\u03b54 carriers and is associated with altered CSF Abeta42 levels [PMID 15895461]\nA haplotype of 3 SNPs in the POLD1 gene; the combined presence of this POLD1 I-G-T haplotype and the ApoE-\u03b54 allele almost doubles the risk of AD (odds ratio: 10.09, CI: 3.88-26.25, =<0.0001) compared to ApoE-\u03b54 carriers alone.[PMID 17498878]\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c1984e64b35234'}"}
{"id":"72120","text":"import numpy as np\nimport pandas as pd \nimport glob\nimport json\nimport math\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\"\"\"\n### Loading Meta Data\n\"\"\"\nmeta_df = pd.read_csv('..\/input\/CORD-19-research-challenge\/metadata.csv')\nmeta_df.head()\n\"\"\"\n#### Get papers having covid content\n\"\"\"\nmeta_df = meta_df[(meta_df.abstract.str.contains('covid') | meta_df.abstract.str.contains('coronavirus') | meta_df.abstract.str.contains('cov') | meta_df.abstract.str.contains('coronaviruses'))] \nmeta_df.drop_duplicates(['sha'], inplace = True)\nlen(meta_df)\nmeta_df.info()\n\"\"\"\n### Loading All Json data\n\"\"\"\nall_json = meta_df.pdf_json_files.tolist()\nall_json = ['..\/input\/CORD-19-research-challenge\/' + str(x) for x in all_json]\n_json = glob.glob('..\/input\/CORD-19-research-challenge\/document_parses\/pdf_json\/*.json', recursive=True)\nlen(all_json)\nclass FileReader:\n    def __init__(self, file_path):\n        with open(file_path) as file:\n            content = json.load(file)\n            self.paper_id = content['paper_id']\n            self.abstract = []\n            self.body_text = []\n            # Abstract\n            for entry in content['abstract']:\n                self.abstract.append(entry['text'])\n            # Body text\n            for entry in content['body_text']:\n                self.body_text.append(entry['text'])\n            self.abstract = '\\n'.join(self.abstract)\n            self.body_text = '\\n'.join(self.body_text)\n    def __repr__(self):\n        return f'{self.paper_id}: {self.abstract[:200]}... {self.body_text[:200]}...'\n\nfirst_row = FileReader(all_json[0])\nprint(first_row)\n\ndict_ = {'paper_id': [], 'abstract': [], 'body_text': []}\nfor idx, entry in enumerate(all_json):\n    try:\n        content = FileReader(entry)\n        if (idx % 1000 == 0):\n            print(f\"processing {idx} of {len(all_json)} \")\n        dict_['paper_id'].append(content.paper_id)\n        dict_['abstract'].append(content.abstract)\n        dict_['body_text'].append(content.body_text)\n    except:\n        pass\ndf_covid = pd.DataFrame(dict_, columns=['paper_id', 'abstract', 'body_text'])\ndf_covid.head()\nfinal_df = pd.merge(meta_df, df_covid, how = 'inner', left_on = 'sha', right_on = 'paper_id')\nfinal_df.head()\nselected_columns = ['paper_id','title', 'doi', 'abstract_x', 'body_text', 'authors', 'journal', 'publish_time']\nfinal_df = final_df[selected_columns]\nfinal_df.info()\nfinal_df.sample(1).abstract_x.values\nfinal_df.to_csv('selected_data.csv', index = False)\nfinal_df.head()","meta":"{'source': 'AI4Code', 'id': '84ac82b8675983'}"}
{"id":"68591","text":"\"\"\"\n# Fashion MNIST - 3D CNN using Tensorflow,Keras\n\n*  The objective of this kernel is to define,compile & evaluate a 3 layer convolutional neural network(CNN) model \n\n*  Visualise the validation accuracy and validation loss\n\n\"\"\"\n# Import Libraries\n\nimport pandas as pd\n\nimport numpy as np\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nimport keras\n\nfrom keras.models import Sequential\n\nfrom keras.layers import Conv2D,MaxPooling2D,Dense,Flatten,Dropout\n\nfrom keras.optimizers import Adam\n\nfrom keras.callbacks import TensorBoard\n\nimport os\n\nprint(os.listdir(\"..\/input\"))\n\n\"\"\"\n**Create dataframes for train and test datasets**\n\"\"\"\ntrain_df = pd.read_csv('\/kaggle\/input\/fashion-mnist_train.csv',sep=',')\ntest_df = pd.read_csv('\/kaggle\/input\/fashion-mnist_test.csv', sep = ',')\n\"\"\"\nNow it is observed that the first column is the label data and because it has 10 classes so it is going to have from 0 to 9.The remaining columns are the actual pixel data.Here as you can see there are about 784 columns that contain pixel data.\nHere each row is a different image representation in the form pixel data.\n\nNow let us split the train data into x and y arrays where x represents the image data and y represents the labels.\nTo do that we need to convert the dataframes into numpy arrays of float32 type which is the acceptable form for tensorflow and keras.\n\"\"\"\ntrain_data = np.array(train_df, dtype = 'float32')\ntest_data = np.array(test_df, dtype='float32')\n\"\"\"\nNow let us slice the train arrays into x and y arrays namely x_train,y_train to store all image data and label data respectively.\ni.e \n\n- x_train contains all the rows and all columns except the label column and excluding header info .\n- y_train contains all the rows and first column and excluding header info .\n\nSimilarly slice the test arrays into x and y arrays namely x_train,y_train to store all image data and label data respectively.\ni.e \n- x_test contains all the rows and all columns except the label column and excluding header info .\n- y_test contains all the rows and first column and excluding header info .\n####  Important Note : Since the image data in x_train and x_test is from 0 to 255 ,  we need to rescale this from 0 to 1.To do this we need to divide the x_train and x_test by 255 \n\"\"\"\nx_train = train_data[:,1:]\/255\ny_train = train_data[:,0]\nx_test= test_data[:,1:]\/255\ny_test=test_data[:,0]\n\"\"\"\nNow we are gonna split the training data into validation and actual training data for training the model and testing it using the validation set. This is achieved using the train_test_split method of scikit learn library.\n\"\"\"\nx_train,x_validate,y_train,y_validate = train_test_split(x_train,y_train,test_size = 0.2,random_state = 12345)\n\"\"\"\n\nNow let us visualise the sample image how it looks like in 28 * 28 pixel size\n\"\"\"\nimage = x_train[13,:].reshape((28,28))\nplt.imshow(image)\nplt.show()\n\"\"\"\nAs you can observe above the shape of shoe from the sample image\n\n### Create the 3D Convolutional Neural Networks (CNN)\n\n- #### Define the model\n- #### Compile the model\n- #### Fit the model\n\nFirst of all let us define the shape of the image before we define the model\n\"\"\"\nimage_rows = 28\nimage_cols = 28\nbatch_size = 512\nimage_shape = (image_rows,image_cols,1) # Defined the shape of the image as 3d with rows and columns and 1 for the 3d visualisation\n\"\"\"\nNow we need to do more formating on the x_train,x_test and x_validate sets.\n\"\"\"\nx_train = x_train.reshape(x_train.shape[0],*image_shape)\nx_test = x_test.reshape(x_test.shape[0],*image_shape)\nx_validate = x_validate.reshape(x_validate.shape[0],*image_shape)\nprint(\"x_train shape = {}\".format(x_train.shape))\nprint(\"x_test shape = {}\".format(x_test.shape))\nprint(\"x_validate shape = {}\".format(x_validate.shape))\n\"\"\"\n- #### Define the model \n\"\"\"\nname = '1_Layer'\ncnn_model_1 = Sequential([\n    Conv2D(32, kernel_size=3, activation='relu', input_shape=image_shape, name='Conv2D-1'),\n    MaxPooling2D(pool_size=2, name='MaxPool'),\n    Dropout(0.2, name='Dropout'),\n    Flatten(name='flatten'),\n    Dense(32, activation='relu', name='Dense'),\n    Dense(10, activation='softmax', name='Output')\n], name=name)\n\nname = '2_Layer'\ncnn_model_2 = Sequential([\n    Conv2D(32, kernel_size=3, activation='relu', input_shape=image_shape, name='Conv2D-1'),\n    MaxPooling2D(pool_size=2, name='MaxPool'),\n    Dropout(0.2, name='Dropout-1'),\n    Conv2D(64, kernel_size=3, activation='relu', name='Conv2D-2'),\n    Dropout(0.25, name='Dropout-2'),\n    Flatten(name='flatten'),\n    Dense(64, activation='relu', name='Dense'),\n    Dense(10, activation='softmax', name='Output')\n], name=name)\n\nname='3_layer'\ncnn_model_3 = Sequential([\n    Conv2D(32, kernel_size=3, activation='relu', \n           input_shape=image_shape, kernel_initializer='he_normal', name='Conv2D-1'),\n    MaxPooling2D(pool_size=2, name='MaxPool'),\n    Dropout(0.25, name='Dropout-1'),\n    Conv2D(64, kernel_size=3, activation='relu', name='Conv2D-2'),\n    Dropout(0.25, name='Dropout-2'),\n    Conv2D(128, kernel_size=3, activation='relu', name='Conv2D-3'),\n    Dropout(0.4, name='Dropout-3'),\n    Flatten(name='flatten'),\n    Dense(128, activation='relu', name='Dense'),\n    Dropout(0.4, name='Dropout'),\n    Dense(10, activation='softmax', name='Output')\n], name=name)\n\ncnn_models = [cnn_model_1, cnn_model_2, cnn_model_3]\n\"\"\"\n**the model summaries**\n\"\"\"\nfor model in cnn_models:\n    model.summary()\n\"\"\"\n **train the models and save results to a dict**\n\"\"\"\nhistory_dict = {}\nfor model in cnn_models:\n    model.compile(\n        loss='sparse_categorical_crossentropy',\n        optimizer=Adam(),\n        metrics=['accuracy']\n    )\n    \n    history = model.fit(\n        x_train, y_train,\n        batch_size=batch_size,\n        epochs=50, verbose=1,\n        validation_data=(x_validate, y_validate)\n    )\n    \n    history_dict[model.name] = history\n\"\"\"\n### Plot the Accuracy and Loss\n\"\"\"\nfig,(ax1,ax2)=plt.subplots(2,figsize=(8,6))\nfor history in history_dict:\n    val_acc = history_dict[history].history['val_acc']\n    val_loss = history_dict[history].history['val_loss']\n    ax1.plot(val_acc, label=history)\n    ax2.plot(val_loss, label=history)\nax1.set_ylabel('Validation Accuracy')\nax2.set_ylabel('Validation Loss')\nax1.set_xlabel('Epochs')\nax1.legend()\nax2.legend()\nplt.show()  \n\"\"\"\nAs you can see in the above graph as the no of convolution layers increases the accuracy is increasing and loss keep decreasing\n\n## If you like this kernel greatly appreciate an Upvote.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7e3dd114cfd4e6'}"}
{"id":"49222","text":"\"\"\"\n# Decision Tree example\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\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\n\n\"\"\"\n# Data Preprocessing\n\"\"\"\n\"\"\"\n\n*Assigning column names*\n\"\"\"\necoli_df =  pd.read_csv(\"..\/input\/ecoli-data-set\/ecoli.csv\",header=None,sep=\"\\s+\")\ncol_names = [\"squence_name\",\"mcg\",\"gvh\",\"lip\",\"chg\",\"aac\",\"alm1\",\"alm2\",\"site\"]\necoli_df.columns = col_names\necoli_df.head()\n\"\"\"\nInspect the data.\nCheck whether there is any obvious missing values.\n\"\"\"\necoli_df.isnull().sum()\n\"\"\"\n# Clean the data\n\"\"\"\n\"\"\"\nShow the two non-numerical columns.\n\"\"\"\necoli_df.loc[:,ecoli_df.dtypes == \"object\"].columns.tolist()\n\"\"\"\nNumber of unique value in squence name is equal to the number of rows of the data frame. \n\nEach of the squence_name appear only once, it is similar to a unique identifier of each row. \n\nTherefore, we *can drop* this column without affecting our further analysis and model building.\n\n\n\"\"\"\nprint(len(ecoli_df[\"squence_name\"].unique()) == ecoli_df.shape[0])\nprint(ecoli_df['lip'].value_counts())\nprint(ecoli_df['chg'].value_counts())\n\"\"\"\nThe results above show that almost all values in chg are 335.\n\nAnd there are only 10 rows with 1. \n\nDropping classes having less than 10 instances, there is only 3 instances in lip is 1, so I drop lip and chg.\n\"\"\"\n\"\"\"\nA function to clean the data, the first thing is to drop the squence_name column. The second is to drop the classes that have less than 10 instances.\n\"\"\"\ndef cleaning_object(ecoli_df,cols_to_drop,class_col):\n    #ob1 suppose to be squence_name\n    ecoli_df = ecoli_df.drop(cols_to_drop,axis=1)\n        \n    #drop classes with less than 10 instances\n    uni_class = ecoli_df[class_col].unique().tolist()\n    for class_label in uni_class:\n        num_rows = sum(ecoli_df[class_col] == class_label)\n        if num_rows < 10:\n            class_todrop = ecoli_df[ecoli_df[class_col] == class_label].index\n            ecoli_df.drop(class_todrop,inplace = True)\n    return ecoli_df\ncleaned_ecoli_df = cleaning_object(ecoli_df,[\"squence_name\",'lip','chg'],\"site\")\ncleaned_ecoli_df.head()\n\"\"\"\nWe can see the squence_name column is dropped.\nAnd below table shows that there is no more classes having less than 10 instances.\n\"\"\"\ncleaned_ecoli_df[\"site\"].value_counts()\n\"\"\"\n# Data Visualization\n\"\"\"\n\"\"\"\nlip and chg are the binary columns, we will drop them from the visualization. Meanwhile, lip has only either 0.48 or 1.\n\"\"\"\nsns.pairplot(cleaned_ecoli_df[['mcg','gvh','aac','alm1','alm2','site']],hue='site')\n\"\"\"\nA linear trend between alm1 and alm2. As the graph shown, for alm1 and alm2 with values lowers than 0.5, the class is mainly cp, for the values higher than 0.5, the class is mainly imU (green). And there are some class pp below the straight line. And the other classes are scatter around. \n\nFor mch with others variabels, we can see there are some clusters. \n\"\"\"\n\"\"\"\n# Model building\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import f1_score, make_scorer\n\"\"\"\nGrid search for the best combination of parameters.\n\"\"\"\nparam_grid = {'max_depth': np.arange(4, 7),\"criterion\":['gini','entropy'],\n              \"max_features\":np.arange(2,5),\"min_samples_split\": np.arange(3,6)}\n#f1 = make_scorer(f1_score , average='samples')\nclf = GridSearchCV(DecisionTreeClassifier(random_state=22), param_grid, cv=3,scoring =\"f1_weighted\",\n                  return_train_score=True)\nclf_scaled = GridSearchCV(DecisionTreeClassifier(random_state=22), param_grid, cv=3,scoring =\"f1_weighted\",\n                  return_train_score=True)\n\"\"\"\nScale the data by standarize them. (PS Scaling doesn't affect the performace of decision tree)\nTo show you scaling doesn't affect the structure of decision tree, I built two decision trees, one with scaled data, another withou.\n\"\"\"\nscaler = StandardScaler()\n#Scale the cleaned data\nscaled_ecoli_df = scaler.fit_transform(cleaned_ecoli_df[['mcg','gvh','aac','alm1','alm2']])\n#put the scaled data back into data frame with column names\nscaled_ecoli_df = pd.DataFrame(scaled_ecoli_df,columns = ['mcg','gvh','aac','alm1','alm2'])\n#Merge that with the class column.\nscaled_ecoli_df = scaled_ecoli_df.merge(cleaned_ecoli_df[\"site\"].to_frame(),left_index=True, right_index=True)\n\"\"\"\nBuild the model with raw features:\n\"\"\"\nclf.fit(cleaned_ecoli_df[['mcg','gvh','aac','alm1','alm2']],cleaned_ecoli_df[\"site\"])\nclf_scaled.fit(scaled_ecoli_df[['mcg','gvh','aac','alm1','alm2']],scaled_ecoli_df[\"site\"])\n\"\"\"\n# Models comparison\n\"\"\"\n\"\"\"\nAlthough model without scaling perform better in term of average cross-valdiation f1 scores, it is not necessary always the case. The training results depend on the way the train data is splitted in cross validation. Each time the code run, the data is splitted randomly. \n\nIn fact, decision tree do not require feature scaling to be performed as they are not sensitive to the the variance in the data.\n\nTo sum up, the difference between the raw model and scaled model is due to the split of the folds in the cross validartion.\n\"\"\"\nprint('The best score for raw data decision tree: ', clf.best_score_)\nprint('The best score for scaled data decision tree: ',clf_scaled.best_score_)\n\"\"\"\nThe best parameters are differnt as shown below.Max features is the only parameter that has the same value across this tow model.\n\"\"\"\nprint('The best combination of raw data decision tree: ',clf.best_params_)\nprint('The best combination of scaled data decision tree: ',clf_scaled.best_params_)\n\"\"\"\nBelow will display the confustion matrices\n\"\"\"\nfrom sklearn.metrics import plot_confusion_matrix\n#Confusion matrix for the raw features model\nplot_confusion_matrix(clf,cleaned_ecoli_df[['mcg','gvh','aac','alm1','alm2']],\n                      cleaned_ecoli_df[\"site\"])\n\"\"\"\nAbove confusion matrix shows that most of the predictions are correct. However, the model does not perform well when predicting imU. There are 13 instances of imU were predicted as im in the model without scale the data.\n\"\"\"\n#Confusion matrix for the scaled features model\nplot_confusion_matrix(clf_scaled,scaled_ecoli_df[['mcg','gvh','aac','alm1','alm2']],\n                      scaled_ecoli_df[\"site\"])\n\"\"\"\nAbove confusion matrix shows that most of the predictions are correct. However, the model does not perform well when predicting imU. There are 13 instances of imU were predicted as im in the model without scale the data. And 2 instances and 1 instance are predicted as om and cp respectively while they are imU in fact. \n\"\"\"\n\"\"\"\n# Train-test split affects how the decision tree constructed\n\nBoth models did not perform well when predicting imU. In fact, their predictions or model itself are quite similar, since scaling would not affect the performance of decision tree. The split of the tree are based on gini index or information gain(entropy), scaling does not affect the those values. As we perfore cross-validation, the data used to build the models are different, therefore, the information gain or gini index from the data are different each time. \n\nThe 'random' split of the data is affecting how the tree split, since a subset of the data might have differnet distribution, information gain or gini index then other subset. \n\nIf the sclaed data and the raw data use the same data to build the model, they should obtain the same split.\n\"\"\"\n\"\"\"\nThe above plots show the actual values of compressive Strength against the predicted values. The closer the data points to the straight line, the more accuracy the prediction is. \n\nSupport vector regressor performs better than the other estimators. \n\nThe predictions of decision tree regression are given by the average of the value of the dependent variables(features) in that leaf node. So we can see the predictions of the regression tree are lying horizontally, which means they made the same predicted values. The instances in the same leaf node will make the same prediction. In other words, the data points with the same predicted value are in the same left node.\n\nSVM Regression tries to fit as many instances as possible on the *street* while limiting margin violations. It can be fitted to non-linear data. As a result, the data points of SVR are much more closer to the actual values. The hyperplane is more likely to wiggle aroudn the data points.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5a9d0cb2048c6f'}"}
{"id":"47031","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n*Importing necessary libraries *\n\"\"\"\nimport numpy as np    #numpy is a library for making computations\nimport matplotlib.pyplot as plt    #it is a 2D plotting library\nimport pandas as pd    # pandas is mainly used for data analysis\nimport seaborn as sns    # data visualization library\n%matplotlib inline \n#magic function to embed all the graphs in the python notebook\n#Import the salary dataset\n#Reading the csv file using the read_csv function of the pandas module\ndf=pd.read_csv(\"..\/input\/Salary_Data.csv\")\n#The read_csv function converts the data into dataframe\n#Look how the data looks like\n#Lets print the first 5 rows of the dataframe\ndf.head()\nX=df.iloc[:,:-1].values\n#Storing the column 1 in X and column 2 in y\ny=df.iloc[:,:1].values\n\"\"\"\n**Visualization of the Dataset to understand the data in a better way**\n\"\"\"\nsns.distplot(df['YearsExperience'],kde=False,bins=10)\n#This plot is used to represent univariate distribution of observations\n#Show the counts of observations in each categorical bin using bars\nsns.countplot(y='YearsExperience',data=df)\n#Plotting a barplot\nsns.barplot(x='YearsExperience',y='Salary',data=df)\n#Representing the correlation among the columns using a heatmap\nsns.heatmap(df.corr())\nsns.distplot(df.Salary)\n\"\"\"\n***Now we will use the scikit learn package to create the Linear Regression model***\n\"\"\"\n\"\"\"\nSplit the data into training and testing set\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n#splitting the data using this module and setting the test size as 1\/3 . Rest 2\/3 is used for training the data\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1\/3,random_state=0)\n\n\"\"\"\n**Creating the Linear Regression Model and Fitting the training data**\n\"\"\"\n#importing the linear regression model\nfrom sklearn.linear_model import LinearRegression\n#creating the model\nlr=LinearRegression()\n\nlr.fit(X_train,y_train)\n#fitting the training data\n\nX_train.shape \n#Counting the number of observations in the training data\ny_train.shape\n\n\"\"\"\n**Predicting the Test Results**\n\"\"\"\ny_pred=lr.predict(X_test)\ny_pred\n#Predicted data\n\"\"\"\n**Visualizing the training data**\n\"\"\"\n\"\"\"\nPlotting the actual y training values VS the y values predicted by the model using training data\n\"\"\"\nplt.scatter(X_train,y_train,color='blue')\nplt.plot(X_train,lr.predict(X_train),color='red')\nplt.title('Salary vs Years of Experience (Training Data)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary of an employee')\nplt.show()\n\"\"\"\nWe see that the data is fitted so well and the predicted and actual data is almost the same\n\"\"\"\n\"\"\"\n**Visualizing the Test Data**\n\"\"\"\n\"\"\"\nPlotting the y test data vs y predicted data\n\"\"\"\nplt.scatter(X_test,y_test,color='blue')\nplt.plot(X_test,lr.predict(X_test),color='red')\nplt.title('Salary vs Years of Experience (Test Data)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary of an employee')\nplt.show()\n\"\"\"\nWe see that the predicted data fits the regression line so well\n\"\"\"\n\"\"\"\n**Calculating the errors so as to check the difference between the actual value and predicted model value... There are certain metrics to find these error such as Mean Squared Error, Root Mean Squared Error and Mean Absolute Error****\n\"\"\"\nfrom sklearn import metrics\nprint('Mean Absolute Error of the Model:',metrics.mean_absolute_error(y_test,y_pred))\nprint('Mean Squared Error of the Model: ',metrics.mean_squared_error(y_test,y_pred))\nprint('Root Mean Squared Error of the Model: ',np.sqrt(metrics.mean_absolute_error(y_test,y_pred)))\n\"\"\"\nLooking at the values we see  that the error is very minute and hence we can see our model gives very accurate values\n\"\"\"\nfrom sklearn.metrics import r2_score\nr2_score(y_test,y_pred)\n#This shows that our model is completely accurate\n#R value lies between 0 to 1. Value of 1 represents it is completely accurate","meta":"{'source': 'AI4Code', 'id': '56a63e9dd5b7e5'}"}
{"id":"126649","text":"\"\"\"\n# Reduce training time by using npy files\n\"\"\"\n\"\"\"\nThis notebook is an attempt at reducing training times by using npy image files instead of raw jpg images. The notebook itself is mostly adapted from \npestipeti wonderful [starter notebook](https:\/\/www.kaggle.com\/pestipeti\/cassava-pytorch-starter-train).\n\n\n## Training time comparison\n\n### cv2 2-fold training \n- fold0 - train_set(4:03 mins), val_set(2:01 mins)\n- fold1 - train_set(3:47 mins), val_set(1:51 mins)\n\n### npy 2-fold training\n- fold0 - train_set(1:28 mins), val_set(1:55 mins)\n- fold1 - train_set(1:05 mins), val_set(1:09 mins)\n\n\nAny feedback on the method and dataset would be most welcome.`\n\"\"\"\n\"\"\"\n## References\n\n1. [plot_confusion_matrix](https:\/\/deeplizard.com\/learn\/video\/0LhiS6yu2qQ)\n2. [sklearn metrics example](https:\/\/towardsdatascience.com\/confusion-matrix-for-your-multi-class-machine-learning-model-ff9aa3bf7826)\n3. [multi_class_classification](https:\/\/towardsdatascience.com\/multi-class-classification-extracting-performance-metrics-from-the-confusion-matrix-b379b427a872)\n\"\"\"\n\"\"\"\n## Library imports\n\"\"\"\n# basic imports\nimport os\nimport numpy as np\nimport pandas as pd\nimport random\nimport itertools\nfrom tqdm.notebook import tqdm\nimport math\n\n# augumentations library\nfrom albumentations.pytorch import ToTensorV2\nimport albumentations as A\nimport cv2\n\n# DL library imports\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\n\n# metrics calculation\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.model_selection import KFold, StratifiedKFold\n\n# basic plotting library\nimport matplotlib.pyplot as plt\n\n# interactive plots\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nimport warnings  \nwarnings.filterwarnings('ignore')\n\"\"\"\ntemp = torch.Tensor([4.0, 30.0, 23.0])\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device('cpu')\ntemp = temp.to(device)\nnp.save('temp.npy', temp.cpu().data.numpy())\na = np.load('temp.npy')\n\"\"\"\n#!rm -rf \/output\/kaggle\/working\/*\n\"\"\"\n## Config files\n\"\"\"\npipeline = {'train' : True, 'lr_find' : False, 'test' : False}\nmodel_cfg = {'model_architecture': 'resnet50', 'model_name': 'cv2_npy_test_v1',\n             'init_lr': 3e-4, 'weight_path': '..\/input\/cassava-pytorch-r50-baseline'}\n\ntrain_cfg = {'batch_size': 16, 'shuffle': False, 'num_workers': 4, 'checkpt_every' : 1 }\nvalid_cfg = {'batch_size': 16, 'shuffle': False, 'num_workers': 4, 'validate_every' : 1 }\ntest_cfg  = {'batch_size': 16, 'shuffle': False, 'num_workers': 4}\n\nDIR_INPUT = '..\/input\/cassava-leaf-disease-classification'\nNPY_FOLDER = '..\/input\/cassava-npy-train-images\/train_npy_images'\nSEED = 42\nN_FOLDS = 2 #if pipeline['DEBUG'] else 5\nN_EPOCHS = 1 #if pipeline['DEBUG'] else 10\nBATCH_SIZE = 32\nSIZE = 256\nindex_label_map = {\n                0: \"Cassava Bacterial Blight (CBB)\", \n                1: \"Cassava Brown Streak Disease (CBSD)\",\n                2: \"Cassava Green Mottle (CGM)\", \n                3: \"Cassava Mosaic Disease (CMD)\", \n                4: \"Healthy\"\n                }\n\nclass_names = [value for key,value in index_label_map.items()]\n\"\"\"\n## Helper functions\n\"\"\"\ndef find_no_of_trainable_params(model):\n    total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    #print(total_trainable_params)\n    return total_trainable_params\ndef set_seed(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    \n#RANDOM_STATE = 42\nset_seed(SEED)\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    #print(cm)\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    #plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\"\"\"\n## Dataset \n\"\"\"\ntrain_df = pd.read_csv(f'{DIR_INPUT}\/train.csv')\ntrain_df[['cls0', 'cls1', 'cls2', 'cls3', 'cls4']] = train_labels = pd.get_dummies(train_df.iloc[:, 1])\ntrain_df['npy_image_id'] = train_df['image_id'].str.replace('jpg', 'npy')\ntrain_labels = train_df.iloc[:, 1].values\nprint(train_df.shape)\ntrain_df.head()\nclass CassavaDataset(Dataset):\n    \n    def __init__(self, df, dataset='train', transforms=None):\n        self.df = df\n        self.transforms=transforms\n        self.dataset=dataset\n        \n    def __len__(self):\n        return self.df.shape[0]\n    \n    def __getitem__(self, idx):        \n        #image_src = f'{DIR_INPUT}\/{self.dataset}_images\/{self.df.loc[idx, \"image_id\"]}'\n        #image = cv2.imread(image_src, cv2.IMREAD_COLOR)\n        #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        image = np.load(f'{NPY_FOLDER}\/{self.df.loc[idx, \"npy_image_id\"]}')\n\n        if self.dataset == 'train':\n            labels = self.df.loc[idx, ['cls0', 'cls1', 'cls2', 'cls3', 'cls4']].values\n            labels = torch.from_numpy(labels.astype(np.int8))\n            labels = labels.unsqueeze(-1)\n        \n        else:\n            labels = torch.Tensor(1)\n        \n        if self.transforms:\n            transformed = self.transforms(image=image)\n            image = transformed['image']\n\n        return image, labels\n\"\"\"\n## Transforms for Augumentations\n\"\"\"\ntransforms_train = A.Compose([\n    A.RandomResizedCrop(height=SIZE, width=SIZE, p=1.0),\n    #A.Flip(),\n    #A.ShiftScaleRotate(rotate_limit=1.0, p=0.8),\n    A.Normalize([0.4303133, 0.49675637, 0.3135656], \n                         [0.2379062, 0.24065569, 0.22874062], p=1.0),\n    ToTensorV2(p=1.0),\n])\n\ntransforms_valid = A.Compose([\n    A.Resize(height=SIZE, width=SIZE, p=1.0),\n    A.Normalize([0.4303133, 0.49675637, 0.3135656], \n                         [0.2379062, 0.24065569, 0.22874062], p=1.0),\n    ToTensorV2(p=1.0),\n])\n\ntransforms_test = A.Compose([\n    A.Resize(height=SIZE, width=SIZE, p=1.0),\n    A.Normalize([0.4303133, 0.49675637, 0.3135656], \n                         [0.2379062, 0.24065569, 0.22874062], p=1.0),\n    ToTensorV2(p=1.0),\n])\n\"\"\"\n## CV strategy\n\"\"\"\nfolds = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\noof_preds = np.zeros((train_df.shape[0],))\n\"\"\"\n## Model class\n\"\"\"\nclass CassavaModel(nn.Module):\n    \n    def __init__(self, num_classes=5, use_pretrained_weights=False):\n        super().__init__()\n        self.backbone = torchvision.models.resnet18(pretrained=use_pretrained_weights)\n        in_features = self.backbone.fc.in_features\n        self.logit = nn.Linear(in_features, num_classes)\n        \n    def forward(self, x):\n        batch_size, C, H, W = x.shape\n        \n        x = self.backbone.conv1(x)\n        x = self.backbone.bn1(x)\n        x = self.backbone.relu(x)\n        x = self.backbone.maxpool(x)\n\n        x = self.backbone.layer1(x)\n        x = self.backbone.layer2(x)\n        x = self.backbone.layer3(x)\n        x = self.backbone.layer4(x)\n        \n        x = F.adaptive_avg_pool2d(x,1).reshape(batch_size,-1)\n        x = F.dropout(x, 0.25, self.training)\n\n        x = self.logit(x)\n\n        return x\n\"\"\"\n## Loss function\n\"\"\"\nclass DenseCrossEntropy(nn.Module):\n\n    def __init__(self):\n        super(DenseCrossEntropy, self).__init__()\n        \n        \n    def forward(self, logits, labels):\n        logits = logits.float()\n        labels = labels.float()\n        \n        logprobs = F.log_softmax(logits, dim=-1)\n        \n        loss = -labels * logprobs\n        loss = loss.sum(-1)\n\n        return loss.mean()\n\n# creating loss function instance\ncriterion = DenseCrossEntropy()\n#criterion = nn.CrossEntropyLoss()\n## Device as cpu or tpu\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device('cpu')\nprint(device)\n\"\"\"\n## Lr_find\n\"\"\"\ndef plot_lr_finder_results(lr_finder): \n    # Create subplot grid\n    fig = make_subplots(rows=1, cols=2)\n    # layout ={'title': 'Lr_finder_result'}\n    \n    # Create a line (trace) for the lr vs loss, gradient of loss\n    trace0 = go.Scatter(x=lr_finder['log_lr'], y=lr_finder['smooth_loss'],name='log_lr vs smooth_loss')\n    trace1 = go.Scatter(x=lr_finder['log_lr'], y=lr_finder['grad_loss'],name='log_lr vs loss gradient')\n\n    # Add subplot trace & assign to each grid\n    fig.add_trace(trace0, row=1, col=1);\n    fig.add_trace(trace1, row=1, col=2);\n    #iplot(fig, show_link=False)\n    fig.write_html(model_cfg['model_name'] + '_lr_find.html');\ndef find_lr(model, data_loader, optimizer, init_value = 1e-8, final_value=100.0, beta = 0.98, num_batches = 200):\n    assert(num_batches > 0)\n    mult = (final_value \/ init_value) ** (1\/num_batches)\n    lr = init_value\n    optimizer.param_groups[0]['lr'] = lr\n    batch_num = 0\n    avg_loss = 0.0\n    best_loss = 0.0\n    smooth_losses = []\n    raw_losses = []\n    log_lrs = []\n    dataloader_it = iter(data_loader)\n    progress_bar = tqdm(range(num_batches))\n        \n    for idx in progress_bar:\n        batch_num += 1\n        try:\n            images, labels = next(dataloader_it)\n            #print(images.shape)\n        except:\n            dataloader_it = iter(data_loader)\n            images, labels = next(dataloader_it)\n\n        # Move input and label tensors to the default device\n        images = images.to(device, dtype=torch.float)\n        labels = labels.to(device, dtype=torch.float)\n        \n        # handle exception in criterion\n        try:\n            # Forward pass\n            log_ps = model(images)\n            loss = criterion(log_ps, labels.squeeze(-1))\n        except:\n            if len(smooth_losses) > 1:\n                grad_loss = np.gradient(smooth_losses)\n            else:\n                grad_loss = 0.0\n            lr_finder_results = {'log_lr':log_lrs, 'raw_loss':raw_losses, \n                                 'smooth_loss':smooth_losses, 'grad_loss': grad_loss}\n            return lr_finder_results \n                    \n        #Compute the smoothed loss\n        avg_loss = beta * avg_loss + (1-beta) *loss.item()\n        smoothed_loss = avg_loss \/ (1 - beta**batch_num)\n        \n        #Stop if the loss is exploding\n        if batch_num > 1 and smoothed_loss > 50 * best_loss:\n            if len(smooth_losses) > 1:\n                grad_loss = np.gradient(smooth_losses)\n            else:\n                grad_loss = 0.0\n            lr_finder_results = {'log_lr':log_lrs, 'raw_loss':raw_losses, \n                                 'smooth_loss':smooth_losses, 'grad_loss': grad_loss}\n            return lr_finder_results\n        \n        #Record the best loss\n        if smoothed_loss < best_loss or batch_num==1:\n            best_loss = smoothed_loss\n        \n        #Store the values\n        raw_losses.append(loss.item())\n        smooth_losses.append(smoothed_loss)\n        log_lrs.append(math.log10(lr))\n        \n        # Backward pass\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        \n        # print info\n        progress_bar.set_description(f\"loss: {loss.item()},smoothed_loss: {smoothed_loss},lr : {lr}\")\n\n        #Update the lr for the next step\n        lr *= mult\n        optimizer.param_groups[0]['lr'] = lr\n    \n    grad_loss = np.gradient(smooth_losses)\n    lr_finder_results = {'log_lr':log_lrs, 'raw_loss':raw_losses, \n                         'smooth_loss':smooth_losses, 'grad_loss': grad_loss}\n    return lr_finder_results\nif pipeline['lr_find'] == True:\n    # create Dataset\n    temp_train_dataset = CassavaDataset(df=train_df, dataset='train', transforms=transforms_train)\n    temp_train_dataloader = DataLoader(temp_train_dataset, batch_size=BATCH_SIZE, num_workers=4, shuffle=True)\n    \n    # create model instance\n    model = CassavaModel(num_classes=5, use_pretrained_weights=True)\n    model.to(device)\n    optimizer = optim.Adam(model.parameters(), lr=model_cfg['init_lr'])\n    \n    lr_finder_results = find_lr(model, temp_train_dataloader, optimizer)\n    plot_lr_finder_results(lr_finder_results)\n\"\"\"\n## One fold train and validation function\n\"\"\"\ndef train_one_fold(i_fold, model, optimizer, dataloader_train, dataloader_valid):\n    \n    train_fold_results = []\n\n    for epoch in range(N_EPOCHS):\n        print('  Epoch {}\/{}'.format(epoch + 1, N_EPOCHS))\n        model.train()\n        tr_loss = 0\n        lr_list = []\n        \n        # training iterator\n        tr_iterator = iter(dataloader_train)\n        train_progress_bar = tqdm(range(len(dataloader_train)))\n    \n        for idx in train_progress_bar:\n            try:\n                images, labels = next(tr_iterator)\n                #print(images.shape)\n            except StopIteration:\n                tr_iterator = iter(dataloader_train)\n                images, labels = next(tr_iterator)\n\n            images = images.to(device, dtype=torch.float)\n            labels = labels.to(device, dtype=torch.float)\n            \n            # Forward pass\n            outputs = model(images)\n\n            # Backward pass\n            loss = criterion(outputs, labels.squeeze(-1))                \n            tr_loss += loss.item()\n            loss.backward()\n            optimizer.step()\n            optimizer.zero_grad()\n            \n            lr_list.append(optimizer.state_dict()[\"param_groups\"][0]['lr'])\n\n            # print to console\n            train_progress_bar.set_description(f\"Train_loss: {tr_loss} loss(avg): {tr_loss\/(idx+1)}\")\n        \n        lr_list = np.array(lr_list)\n        np.save(model_cfg['model_name'] + '_' + str(i_fold) + 'fold_lr_list.npy', lr_list)\n\n        # Validate\n        model.eval()\n        val_loss = 0.0\n        val_preds = None\n        val_labels = None\n        \n        valid_iterator = iter(dataloader_valid)\n        valid_progress_bar = tqdm(range(len(dataloader_valid)))\n\n        for idx in valid_progress_bar:\n            try:\n                images, labels = next(valid_iterator)\n            except StopIteration:\n                tr_iterator = iter(dataloader_valid)\n                images, labels = next(valid_iterator)\n\n            if val_labels is None:\n                val_labels = labels.clone().squeeze(-1)\n            else:\n                val_labels = torch.cat((val_labels, labels.squeeze(-1)), dim=0)\n\n            images = images.to(device, dtype=torch.float)\n            labels = labels.to(device, dtype=torch.float)\n\n            with torch.no_grad():\n                outputs = model(images)\n\n                loss = criterion(outputs, labels.squeeze(-1))\n                val_loss += loss.item()\n\n                preds = torch.softmax(outputs, dim=1).data.cpu()\n\n                if val_preds is None:\n                    val_preds = preds\n                else:\n                    val_preds = torch.cat((val_preds, preds), dim=0)\n            \n            # print to console\n            valid_progress_bar.set_description(f\"val_loss: {val_loss} loss(avg): {val_loss\/(idx+1)}\")\n\n        \n        val_preds = torch.argmax(val_preds, dim=1)\n        val_labels = torch.argmax(val_labels, dim=1)\n        \n        np.save(model_cfg['model_name'] + '_val_preds_' + str(i_fold) + '.npy', val_preds.cpu().data.numpy())\n        np.save(model_cfg['model_name'] + '_val_labels_' + str(i_fold) + '.npy', val_labels.cpu().data.numpy())\n\n        train_fold_results.append({\n            'fold': i_fold,\n            'epoch': epoch,\n            'train_loss': tr_loss \/ len(dataloader_train),\n            'valid_loss': val_loss \/ len(dataloader_valid),\n            'valid_score': accuracy_score(val_labels, val_preds)\n        })\n\n    return val_preds, train_fold_results\n\"\"\"\n## Training and validation function calls\n\"\"\"\nif pipeline['train'] == True:\n    submissions = None\n    train_results = []\n\n    for i_fold, (train_idx, valid_idx) in enumerate(folds.split(train_df, train_labels)):\n        print(\"Fold {}\/{}\".format(i_fold + 1, N_FOLDS))\n\n        valid = train_df.iloc[valid_idx]\n        valid.reset_index(drop=True, inplace=True)\n\n        train = train_df.iloc[train_idx]\n        train.reset_index(drop=True, inplace=True)    \n\n        dataset_train = CassavaDataset(df=train, dataset='train', transforms=transforms_train)\n        dataset_valid = CassavaDataset(df=valid, dataset='train', transforms=transforms_valid)\n\n        dataloader_train = DataLoader(dataset_train, batch_size=BATCH_SIZE, num_workers=4, shuffle=True)\n        dataloader_valid = DataLoader(dataset_valid, batch_size=BATCH_SIZE, num_workers=4, shuffle=False)\n\n        model = CassavaModel(num_classes=5, use_pretrained_weights=True)\n        model.to(device)\n\n        plist = [{'params': model.parameters(), 'lr': 1e-4}]\n        optimizer = optim.Adam(plist, lr=model_cfg['init_lr'])\n\n        val_preds, train_fold_results = train_one_fold(i_fold, model, optimizer, \n                                                       dataloader_train, dataloader_valid)\n        oof_preds[valid_idx] = val_preds.numpy()\n        train_results = train_results + train_fold_results\n\n        torch.save({\n            'fold': i_fold,\n            'lr': optimizer.state_dict()[\"param_groups\"][0]['lr'],\n            'model_state_dict': model.cpu().state_dict(),\n            'optimizer_state_dict': optimizer.state_dict(),\n            # 'scheduler_state_dict'\n            # 'scaler_state_dict'\n        }, f\"{model_cfg['model_name']}_fold_{i_fold}.pth\")\n\n    print(\"{}-Folds CV score: {:.4f}\".format(N_FOLDS, accuracy_score(train_labels, oof_preds)))\n\"\"\"\n## Plot training results\n\"\"\"\ndef plot_training_results():\n    fig = make_subplots(rows=2, cols=1)\n\n    colors = [\n        ('#d32f2f', '#ef5350'),\n        ('#303f9f', '#5c6bc0'),\n        ('#00796b', '#26a69a'),\n        ('#fbc02d', '#ffeb3b'),\n        ('#5d4037', '#8d6e63'),\n    ]\n\n    for i in range(N_FOLDS):\n        data = train_results[train_results['fold'] == i]\n\n        fig.add_trace(go.Scatter(x=data['epoch'].values,\n                                 y=data['train_loss'].values,\n                                 mode='lines',\n                                 visible='legendonly' if i > 0 else True,\n                                 line=dict(color=colors[i][0], width=2),\n                                 name='Train loss - Fold #{}'.format(i)),\n                     row=1, col=1)\n\n        fig.add_trace(go.Scatter(x=data['epoch'],\n                                 y=data['valid_loss'].values,\n                                 mode='lines+markers',\n                                 visible='legendonly' if i > 0 else True,\n                                 line=dict(color=colors[i][1], width=2),\n                                 name='Valid loss - Fold #{}'.format(i)),\n                     row=1, col=1)\n\n        fig.add_trace(go.Scatter(x=data['epoch'].values,\n                                 y=data['valid_score'].values,\n                                 mode='lines+markers',\n                                 line=dict(color=colors[i][0], width=2),\n                                 name='Valid score - Fold #{}'.format(i),\n                                 showlegend=False),\n                     row=2, col=1)\n\n    fig.update_layout({\n      \"annotations\": [\n        {\n          \"x\": 0.225, \n          \"y\": 1.0, \n          \"font\": {\"size\": 16}, \n          \"text\": \"Train \/ valid losses\", \n          \"xref\": \"paper\", \n          \"yref\": \"paper\", \n          \"xanchor\": \"center\", \n          \"yanchor\": \"bottom\", \n          \"showarrow\": False\n        }, \n        {\n          \"x\": 0.775, \n          \"y\": 1.0, \n          \"font\": {\"size\": 16}, \n          \"text\": \"Validation scores\", \n          \"xref\": \"paper\", \n          \"yref\": \"paper\", \n          \"xanchor\": \"center\", \n          \"yanchor\": \"bottom\", \n          \"showarrow\": False\n        }, \n      ]\n    })\n\n    fig.show()\n\"\"\"\nval_preds_0 = np.load('.\/R18_imagenet_v2_val_preds_0.npy')\nval_labels_0 = np.load('.\/R18_imagenet_v2_val_labels_0.npy')\n\ncm = confusion_matrix(val_labels_0, val_preds_0)\nprint(cm)\nplt.figure(figsize=(8,8))\nplot_confusion_matrix(cm, classes=class_names, normalize=True)\n\"\"\"\nif pipeline['train'] == True:\n    train_results = pd.DataFrame(train_results)\n    print(train_results.head(10))\n    \n    final_results = train_results[train_results['epoch']==train_results['epoch'].max()]\n    print(final_results)\n    print(final_results['valid_score'].mean(), final_results['valid_score'].std())\n    plot_training_results()\n\"\"\"\n## Testing function\n\"\"\"\nif pipeline[\"test\"] == True:\n    # read submission file\n    submission_df = pd.read_csv(DIR_INPUT + '\/sample_submission.csv')\n    submission_df.iloc[:, 1] = 4\n    #print(submission_df.head())\n    submission_df.to_csv('submission.csv', index=False)\n\"\"\"\nif pipeline[\"test\"] == True:\n    # read submission file\n    submission_df = pd.read_csv(DIR_INPUT + '\/sample_submission.csv')\n    submission_df.iloc[:, 1] = 0\n    #print(submission_df.head())\n\n\n    # just for debugging purporse, adding 1 more row\n    if submission_df.shape[0] == 1:\n        submission_df = pd.DataFrame([{'image_id': '2216849948.jpg', 'label': 0},{'image_id': '2216849948.jpg', 'label': 0}])\n        submission_df.reset_index(drop=True, inplace=True)\n    #print(submission_df.head())\n\n\n    # Creating test dataset and dataloaders\n    dataset_test = CassavaDataset(df=submission_df, dataset='test', transforms=transforms_test)\n    dataloader_test = DataLoader(dataset_test, batch_size=BATCH_SIZE, num_workers=4, shuffle=False)\n    \n    \n    # placeholder for final submission csv\n    submissions = None\n\n    \"\"\"\n    1. Iterate and store predictions (one-hot encoded format) of N-folds of model \n    2. Average the predictions of all folds\n    3. argmax of mean one-hot encoded prediction is output\n    \"\"\"\n    for i_fold in range(N_FOLDS):\n        print(f'Inference for {i_fold}th fold')\n        model = CassavaModel(num_classes=5, use_pretrained_weights=False)\n        model.to(device)\n\n        checkpoint = torch.load(f\"{model_cfg['weight_path']}\/{model_cfg['model_name']}_fold_{i_fold}.pth\", map_location=device)\n        model.load_state_dict(checkpoint['model_state_dict'], strict=True)\n        model.eval()\n        test_preds = None\n\n        for step, (images, _) in enumerate(dataloader_test):\n            images = images.to(device, dtype=torch.float)\n            with torch.no_grad():\n                outputs = model(images)\n                preds = torch.softmax(outputs, dim=1).data.cpu()\n                if test_preds is None:\n                    test_preds = preds\n                else:\n                    test_preds = torch.cat((test_preds, preds), dim=0)\n\n        # submission_df[['label']] = test_preds.argmax(test_preds, dim=1)\n        # submission_df.to_csv('submission_fold_{}.csv'.format(i_fold), index=False)\n\n        # logits avg\n        if submissions is None:\n            submissions = test_preds \/ N_FOLDS\n        else:\n            submissions += test_preds \/ N_FOLDS\n            \n        \n    #print(submissions[:10])\n    # argmax of predictions and write to csv\n    submission_df['label'] = torch.argmax(submissions, dim=1)\n    submission_df.to_csv('submission.csv', index=False)\n    #print(submission_df.head())\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e8ebc3c4dc7339'}"}
{"id":"38434","text":"\"\"\"\n# Application of computer Vision: Understand Unsupervised learning auto-encoders with MNIST digit dataset.\n### Table of interest:\n1. Introduction\n2. Import all required Library\n3. Data Exploration and visualization.\n4. Data preprocessing.\n5. Building of our Auto-encoder.\n6. Model trainning and predict.\n7. Model evaluation.\n\n\"\"\"\n\"\"\"\n## Introduction.\nLet's start by understanding the operation of an auto-encoder.\n\n* Autoencoders are a class of neural network that attempt to recreate the input as its target using backpropagation. An autoencoder consists of two parts, an encoder and a decoder. The encoder will read the input and compress it to a compact representation, and the decoder will read the compact representation and recreate the input from it. In other words, the autoencoder tries to learn the identity function by minimizing the reconstruction error.\n\n* The number of hidden units in the autoencoder is typically less than the number of input (and output) units. This forces the encoder to learn a compressed representation of the input which the decoder reconstructs. If there is structure in the input data in the form of correlations between input features, then the autoencoder will discover some of these correlations, and end up learning a low dimensional representation of the data similar to that learned using principal component analysis (**PCA**).\n\n* The encoder and decoder components of an autoencoder can be implemented using either dense, convolutional, or recurrent networks, depending on the kind of data that is being modeled.\n\n* Autoencoders can also be stacked by successively stacking encoders that compress their input to smaller and smaller representations, and stacking decoders in the opposite sequence. Stacked autoencoders have greater expressive power and the successive layers of representations capture a hierarchical grouping of the input, similar to the convolution and pooling operations in convolutional neural networks.\n\n![auto-encoder.PNG](attachment:auto-encoder.PNG)\n\n* For example in the network shown above, we would first train layer **X** to reconstruct layer **X'** using the hidden layer **H1** (**ignoring H2**). We would then train the layer **H1** to reconstruct layer **H1'** using the hidden layer **H2**. Finally, we would stack all the layers together in the configuration shown and fine tune it to reconstruct **X'** from **X**. With better activation and regularization functions nowadays, however, it is quite common to train these networks in totality.\n\"\"\"\n\"\"\"\nNow let's apply this principe of operation to our famous MNIST digit dataset.\n\"\"\"\n\"\"\"\n## 2. Import all required Library\n\"\"\"\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.datasets import mnist\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\n## 3. Data Exploration and visualization.\n\"\"\"\n#Load our MNIST dataset.\n(XTrain, YTrain), (XTest, YTest) = mnist.load_data()\n\nprint('XTrain class = ',type(XTrain))\nprint('YTrain class = ',type(YTrain))\n\n# shape of our dataset.\nprint('XTrain shape = ',XTrain.shape)\nprint('XTest shape = ',XTest.shape)\nprint('YTrain shape = ',YTrain.shape)\nprint('YTest shape = ',YTest.shape)\n# Number of distinct values of our MNIST target\nprint('YTrain values = ',np.unique(YTrain))\nprint('YTest values = ',np.unique(YTest))\n# Distribution of classes in our dataset.\nunique, counts = np.unique(YTrain, return_counts=True)\nprint('YTrain distribution = ',dict(zip(unique, counts)))\nunique, counts = np.unique(YTest, return_counts=True)\nprint('YTest distribution = ',dict(zip(unique, counts)))\n\n\"\"\"\nNow let's visualize the distribution of our data by classes.\n\"\"\"\n# we plot an histogram distribution of our test and train data.\nfig, axs = plt.subplots(1,2,figsize=(15,5)) \naxs[0].hist(YTrain, ec='black')\naxs[0].set_title('YTrain data')\naxs[0].set_xlabel('Classes') \naxs[0].set_ylabel('Number of occurrences')\naxs[1].hist(YTest, ec='black')\naxs[1].set_title('YTest data')\naxs[1].set_xlabel('Classes') \naxs[1].set_ylabel('Number of occurrences')\n# We want to show all ticks...\naxs[0].set_xticks(np.arange(10))\naxs[1].set_xticks(np.arange(10))\n\nplt.show()\n\n\"\"\"\n## 4. Data preprocessing.\nWe don't need more preprocessing here because we are in unsupervised learning. Just normalise and reshapping our data. We don't need the target data.\n\"\"\"\n# Data normalization.\nXTrain = XTrain.astype('float32') \/ 255\nXTest = XTest.astype('float32') \/ 255\n# data reshapping.\nXTrain = XTrain.reshape((len(XTrain), np.prod(XTrain.shape[1:])))\nXTest = XTest.reshape((len(XTest), np.prod(XTest.shape[1:])))\n\nprint (XTrain.shape)\nprint (XTest.shape)\n\n\"\"\"\n## 5. Building of our Auto-encoder.\nOur model has only one hidden(**encoded layer**) layer with 32 units neurons. The input and output layer(**decoded layer**) have each 784 units neurons.\n\"\"\"\nInputModel = Input(shape=(784,))\nEncodedLayer = Dense(32, activation='relu')(InputModel)\nDecodedLayer = Dense(784, activation='sigmoid')(EncodedLayer)\n\nAutoencoderModel = Model(InputModel, DecodedLayer)\n# we can summarize our model.\nAutoencoderModel.summary()\n\n\"\"\"\n## 6. Model trainning and predict.\n\"\"\"\n# Let's train the model using adadelta optimizer\nAutoencoderModel.compile(optimizer='adadelta', loss='binary_crossentropy')\n\nhistory = AutoencoderModel.fit(XTrain, XTrain,\n                    batch_size=256,\n                    epochs=100,\n                    shuffle=True,\n                    validation_data=(XTest, XTest))\n# Make prediction to decode the digits\nDecodedDigits = AutoencoderModel.predict(XTest)\n\"\"\"\n## 7. Model evaluation.\nThe `fit()` method on a Keras Model returns a `History` object. The `History.history` attribute is a dictionary recording training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable).\nFor our model we don't have metrics values because we didn't specify metrics when we compiled the model.\n\"\"\"\ndef plotmodelhistory(history): \n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Autoencoder Model loss')\n    plt.ylabel('Loss')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()\n\n# list all data in history\nprint(history.history.keys())\n# visualization of the loss minimization during the training process\nplotmodelhistory(history)\n\"\"\"\n### Visualization of the results.\nNow let's visualize for 5 images decoded by our model.\n\"\"\"\nn=5\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n    ax = plt.subplot(2, n, i + 1)\n    # input image\n    plt.imshow(XTest[i+10].reshape(28, 28))\n    plt.gray()\n    ax.get_xaxis().set_visible(False)\n    ax.get_yaxis().set_visible(False)\n    ax = plt.subplot(2, n, i + 1 + n)\n    # Image decoded by our Auto-encoder\n    plt.imshow(DecodedDigits[i+10].reshape(28, 28))\n    plt.gray()\n    ax.get_xaxis().set_visible(False)\n    ax.get_yaxis().set_visible(False)\nplt.show()\n\"\"\"\n***Please give an up-vote if you have found this kernel helpful. It will ke me motivate to do more.***\n\nThanks\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '46c59ea25f92b4'}"}
{"id":"69935","text":"import numpy as np\nimport pandas as pd \nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords\nimport string, re\nfrom bs4 import BeautifulSoup\nfrom wordcloud import WordCloud\nfrom keras.preprocessing import text, sequence\nfrom nltk.tokenize.toktok import ToktokTokenizer\nfrom sklearn.model_selection import train_test_split\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Embedding,LSTM,Dropout, Bidirectional\nfrom keras.callbacks import ReduceLROnPlateau\nimport tensorflow as tf\nnp.random.seed(1)\ntf.random.set_seed(1)\n\"\"\"\n# Loading Data\n\"\"\"\ntrain_df = pd.read_csv('..\/input\/nlp-getting-started\/train.csv', index_col='id')\ntest_df = pd.read_csv('..\/input\/nlp-getting-started\/test.csv', index_col='id')\ntrain_df.head()\ntrain_df.info()\n\"\"\"\n# Initial EDA\n\"\"\"\n\"\"\"\nLet's first check the distributions of fake and real disaster tweets. \n\"\"\"\nax = sns.barplot(x=\"target\", y=\"target\", data=train_df, estimator=lambda x: len(x) \/ len(train_df.index) * 100)\nax.set(ylabel=\"Percent\")\nplt.show()\n\"\"\"\nWe see that the distributions are pretty even, so the minimum performance should be approx 53% accuracy.\n\"\"\"\ntrain_df.keyword.unique()\n\"\"\"\nNote that we see that some of the keywords have '%20' in place of spaces, so we replace these later by spaces.\n\"\"\"\n\"\"\"\n# Text Preprocessing\n\"\"\"\n\"\"\"\nFirst we import a set of stopwords such as 'the' and 'a' which can be removed from tweets, as well as punctuation.\n\"\"\"\nstop = set(stopwords.words('english'))\n# add punctuation to the list of stopwords\npunctuation = list(string.punctuation)\nstop.update(punctuation)\n\"\"\"\nWe wish to remove html links, any words between square brackets, urls, %20's, and stopwords from the text.\n\"\"\"\ndef strip_html(text):\n    soup = BeautifulSoup(text, \"html.parser\")\n    return soup.get_text()\n\n#Removing the square brackets\ndef remove_between_square_brackets(text):\n    return re.sub('\\[[^]]*\\]', '', text)\n\n# Removing URL's\ndef remove_url(text):\n    return re.sub(r'http\\S+', '', text)\n\ndef add_space(text):\n    return re.sub('%20', ' ', text)\n\n#Removing the stopwords from text\ndef remove_stopwords(text):\n    final_text = []\n    for i in text.split():\n        if i.strip().lower() not in stop:\n            final_text.append(i.strip())\n    return \" \".join(final_text)\n\n#Removing the noisy text\ndef denoise_text(text):\n    text = strip_html(text)\n    text = remove_between_square_brackets(text)\n    text = add_space(text)\n    text = remove_url(text)\n    text = remove_stopwords(text)\n    return text\n\n\"\"\"\n![](http:\/\/)As part of preprocessing, we add the location column and combine the keywords with the text into one big text column. Then we apply the denoise function to the text.\n\"\"\"\ndef preprocess_df(df):\n    df = df.fillna(\"\")\n    df['text'] = df['location'] + \" \" + df['keyword'] + \" \" + df['text']\n    del df['keyword']\n    del df['location']\n    df['text'] = df['text'].apply(denoise_text)\n    return df\ntrain_df = preprocess_df(train_df)\ntest_df = preprocess_df(test_df)\n\"\"\"\n# Model Training\n\"\"\"\n\"\"\"\nIn order to choose a model architecture, we split the training data into train and dev sets.\n\"\"\"\nX_train, X_dev, y_train, y_dev = train_test_split(train_df.text.values, train_df.target.values)\n# Set max words and max length hyperparameters\nmax_features = 10000\nmax_len = 300\n\"\"\"\nFirst, we tokenise the text into arrays.\n\"\"\"\n# Fit the tokenizer on the training data\ntokenizer = text.Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(X_train)\n# Tokenize and pad each set of texts\ntokenized_train = tokenizer.texts_to_sequences(X_train)\nX_train = sequence.pad_sequences(tokenized_train, maxlen=max_len)\n\ntokenized_dev = tokenizer.texts_to_sequences(X_dev)\nX_dev = sequence.pad_sequences(tokenized_dev, maxlen=max_len)\n\"\"\"\nNow, we create the glove embedding matrix to add to the model.\n\"\"\"\nEMBEDDING_FILE = '..\/input\/glove-twitter\/glove.twitter.27B.100d.txt'\n# Create a dictionary of words and their feature vectors from the embedding file\ndef get_coefs(word, *arr): \n    return word, np.asarray(arr, dtype='float32')\n\nembeddings_index = dict(get_coefs(*o.rstrip().rsplit(' ')) for o in open(EMBEDDING_FILE))\nall_embs = np.stack(list(embeddings_index.values()))\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\n\n# Find dims of embedding matrix\nembed_size = all_embs.shape[1]\n\nword_index = tokenizer.word_index\nnb_words = min(max_features, len(word_index))\n\n# Randomly initialize the embedding matrix\nembedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n\n# Add each vector to the embedding matrix, corresponding to each token that we set earlier\nfor word, i in word_index.items():\n    if i >= max_features: continue\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None: embedding_matrix[i] = embedding_vector\n\"\"\"\nNow, set the key hyperparameters.\n\"\"\"\nbatch_size = 1024\nepochs = 15\nembed_size = 100\n\"\"\"\nWe add learning rate reduction to the model to achieve good model fitting.\n\"\"\"\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.5, min_lr=0.00001)\n\"\"\"\nThe model architecture consists of two LSTM layers, followed by a Dense layer and a sigmoid activation function.\n\"\"\"\n#Defining Neural Network\nmodel = Sequential()\n#Non-trainable embeddidng layer\nmodel.add(Embedding(max_features, output_dim=embed_size, weights=[embedding_matrix], input_length=max_len, trainable=False))\n#LSTM \nmodel.add(LSTM(units=128 , return_sequences = False , recurrent_dropout = 0.3 , dropout = 0.3))\nmodel.add(Dense(units=64 , activation = 'relu', kernel_regularizer='l2'))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer=keras.optimizers.Adam(lr = 0.01), loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\"\"\"\nFinally, we fit the model.\n\"\"\"\nhistory = model.fit(X_train, y_train, batch_size = batch_size , \n                    validation_data = (X_dev,y_dev) , \n                    epochs = epochs , callbacks = [learning_rate_reduction])\n\"\"\"\n# Model Evaluation\n\"\"\"\n\"\"\"\nLet's see how the model does on the training and development data.\n\"\"\"\nprint(\"Accuracy of the model on Training Data is - \" , model.evaluate(X_train,y_train)[1]*100)\nprint(\"Accuracy of the model on Dev Data is - \" , model.evaluate(X_dev,y_dev)[1]*100)\n\"\"\"\nWe also track the progress of the loss and accuracy on the train and dev sets over each epoch.\n\"\"\"\nplt.figure(figsize=(10, 10))\n\nepochs = np.arange(epochs)\nplt.subplot(2, 2, 1)\nplt.xlabel('epochs')\nplt.ylabel('loss')\nplt.plot(epochs, history.history['loss'])\n\nplt.subplot(2, 2, 2)\nplt.xlabel('epochs')\nplt.ylabel('accuracy')\nplt.plot(epochs, history.history['accuracy'])\n\nplt.subplot(2, 2, 3)\nplt.xlabel('epochs')\nplt.ylabel('val_loss')\nplt.plot(epochs, history.history['val_loss'])\n\nplt.subplot(2, 2, 4)\nplt.xlabel('epochs')\nplt.ylabel('val_accuracy')\nplt.plot(epochs, history.history['val_accuracy'])\n\nplt.show()\n\"\"\"\n# Predicting Test Data\n\"\"\"\nX_test = test_df.text.values\ntokenized_dev = tokenizer.texts_to_sequences(X_test)\nX_test = sequence.pad_sequences(tokenized_dev, maxlen=max_len)\nclasses = model.predict_classes(X_test)[:, 0]\nsubmission = pd.DataFrame(\n    {'id': list(test_df.index.values),\n     'target': list(classes),\n    }).set_index('id')\nsubmission.to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': '809e4f5b2c6bef'}"}
{"id":"32777","text":"\"\"\"\n# Titanic: Machine Learning from Disaster\n\n## The Challenge\nThe sinking of the Titanic is one of the most infamous shipwrecks in history.\n\nOn April 15, 1912, during her maiden voyage, the widely considered \u201cunsinkable\u201d RMS Titanic sank after colliding with an iceberg. Unfortunately, there weren\u2019t enough lifeboats for everyone onboard, resulting in the death of 1502 out of 2224 passengers and crew.\n\nWhile there was some element of luck involved in surviving, it seems some groups of people were more likely to survive than others.\n\nIn this challenge, we ask you to build a predictive model that answers the question: \u201cwhat sorts of people were more likely to survive?\u201d using passenger data (ie name, age, gender, socio-economic class, etc).\n\"\"\"\n\"\"\"\n### 1. Import libraries and read all files\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression \n# Read files\ngender_submission = pd.read_csv(\"..\/input\/titanic\/gender_submission.csv\")\n# Train.csv will contain the details of a subset of the passengers on board (891 to be exact) and importantly, the \u201cground truth\u201d.\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\n# The test.csv dataset contains similar information but does not disclose the \u201cground truth\u201d for each passenger. It\u2019s your job to predict these outcomes.\ntest = pd.read_csv(\"..\/input\/titanic\/test.csv\")\ntrain.head()\ntrain.info()\n\"\"\"\n## Features and Transformations\n| categorical        \t| numerical         \t|\n|--------------------\t|-------------------\t|\n| Survived - boolean \t| Age - continuous  \t|\n| Pclass - ordinal   \t| SibSp - discrete  \t|\n| Name - nominal       \t| Parch  - discrete \t|\n| Sex - boolean        \t| Fare - continuous \t|\n| Ticket - nominal     \t|                   \t|\n| Cabin - nominal     \t|                   \t|\n| Embarked - nominal  \t|                   \t|\n\n\"\"\"\nfig, ax = plt.subplots(1,4, figsize=(15,3))\n\ntrain.Sex.value_counts().plot(kind='bar', ax=ax[0])\ntrain.Embarked.value_counts().plot(kind='bar', ax=ax[1])\ntrain.Pclass.value_counts().plot(kind='bar', ax=ax[2])\n\ndf_plot = train.groupby(['Pclass', 'Embarked']).size().reset_index().pivot(columns='Pclass', index='Embarked', values=0)\ndf_plot.apply(lambda x: x\/x.sum(), axis=1).plot(kind='bar', stacked=True, ax=ax[3])\ntrain.drop(['PassengerId'], axis=1).hist(figsize=(20,10))\n\"\"\"\n## features Transformation\nSurvived - True and False\n\nPcclass - boolean \n* Pcclass_1\n* Pcclass_2\n* Pcclass_3\n\nName - removed for now\n\nTicket - removed for now\n\nCabin - removed for now\n\nEmbarked - boolean\n* Embarked_C\n* Embarked_Q\n* Embarked_S\n\n\"\"\"\npclass_dummies = pd.get_dummies(train.Pclass, prefix = 'Pcclass')\nembarked_dummies = pd.get_dummies(train.Embarked, prefix = 'Embarked')\nsex_dummies = pd.get_dummies(train.Sex, prefix = 'Sex')\n\ntrain_y = train['Survived']\n\ntitanic_train = train.drop(['PassengerId','Name','Ticket','Cabin','Pclass','Embarked','Sex','Survived'], axis=1)\ntitanic_train[\"Age\"].fillna(train[\"Age\"].mean(), inplace = True)\ntitanic_train[\"Fare\"].fillna(train[\"Fare\"].mean(), inplace = True)\n\ntitanic_train = pd.concat([titanic_train,pclass_dummies,embarked_dummies,sex_dummies], axis=1)\ntitanic_train.head()\ntitanic_train[titanic_train.isna().any(axis=1)]\nreg = LogisticRegression().fit(titanic_train, train_y)\nreg.score(titanic_train, train_y)\npclass_dummies = pd.get_dummies(test.Pclass, prefix = 'Pcclass')\nembarked_dummies = pd.get_dummies(test.Embarked, prefix = 'Embarked')\nsex_dummies = pd.get_dummies(test.Sex, prefix = 'Sex')\n\ntitanic_test = test.drop(['PassengerId','Name','Ticket','Cabin','Pclass','Embarked','Sex'], axis=1)\ntitanic_test[\"Age\"].fillna(train[\"Age\"].mean(), inplace = True)\ntitanic_test[\"Fare\"].fillna(train[\"Fare\"].mean(), inplace = True)\n\ntitanic_test = pd.concat([titanic_test,pclass_dummies,embarked_dummies,sex_dummies], axis=1)\ntitanic_test\ntitanic_test[titanic_test.isna().any(axis=1)]\npred = reg.predict(titanic_test)\n\nmy_submission = test[['PassengerId']]\nmy_submission['Survived'] = pred\nmy_submission.head()\nmy_submission.to_csv('my_submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '3c6431b9892802'}"}
{"id":"38247","text":"\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\nFacebook is an American online social media and social networking service owned by Meta Platforms. Founded in 2004 by Mark Zuckerberg with fellow Harvard College students and roommates Eduardo Saverin, Andrew McCollum, Dustin Moskovitz, and Chris Hughes, its name comes from the face book directories often given to American university students. Membership was initially limited to Harvard students, gradually expanding to other North American universities and, since 2006, anyone over 13 years old. As of 2020, Facebook claimed 2.8 billion monthly active users, and ranked seventh in global internet usage.\n\n\n\"\"\"\n\"\"\"\n# Importing Packages for Analysis\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\"\"\"\n# Import of the data file in CSV format\n\"\"\"\ndf = pd.read_csv('..\/input\/facebook-ad-campaign\/data.csv')\n\"\"\"\n# Exploratory Data Analysis (EDA)\n\"\"\"\n\"\"\"\n**Top Five values in the Datset**\n\"\"\"\ndf.head()\n\"\"\"\n**Finding out the number of null values in each column**\n\"\"\"\ndf.isnull().sum()\n\"\"\"\n**Removing all empty rows**\n\"\"\"\ndf.dropna(inplace=True)\ndf.info()\n\"\"\"\n**Descriptive Statistics of the Dataset**\n\"\"\"\ndf.describe()\n\"\"\"\n**Setting Index of the dataset**\n\"\"\"\nIndex=np.arange(1,762)\ndf.set_index(Index,inplace=True)\n\"\"\"\n**Pairplot of the Dataset**\n\"\"\"\nsb.pairplot(df,hue='gender')\n\"\"\"\n**The targetted Age in the Ad Campaign**\n\"\"\"\ndf.age.value_counts().plot(kind='bar')\nplt.xticks(rotation=45)\nplt.xlabel('Age')\nplt.title('Targetted Age in the Ad Campaign')\n\"\"\"\n* The Ad Campaigns are mostly made for the age of 30 to 34 \n* The campaign is least targetted for the middle aged people between 45 to 49\n\"\"\"\n\"\"\"\n**Correlation throught Heatmap**\n\"\"\"\nax=plt.figure(figsize=(10,6))\ncorr=df.corr()\nsb.heatmap(corr,linewidths=1,linecolor='black',annot=True)\nplt.xticks(rotation=45)\n\"\"\"\nThe correlated valued lies between 0.7 and 1 \n\"\"\"\n\"\"\"\n**Genders targetted for the Ad Campaign**\n\"\"\"\ndf.gender.value_counts()\n\"\"\"\n* The Ads are targetted mainly for the Men as it is around 2x that of Female\n\"\"\"\n\"\"\"\n**Finding out who spent the maximum on Ad Campaign**\n\"\"\"\ndf[df['spent'] ==df['spent'].max()]\n\"\"\"\n* The maximum amount spend on Ads is around 640 \n\n\"\"\"\n\"\"\"\n**Maximum number of clicks received by an ID**\n\"\"\"\ndf[df['clicks'] ==df['clicks'].max()]\n\"\"\"\nId 1178 has received the maximum number of clicks of 340 by spending around 640 \n\"\"\"\n\"\"\"\n**Total conversions by each Id**\n\"\"\"\ntc=(df.groupby(['campaign_id'])).total_conversion.sum()\ntc\n\"\"\"\nId 1178 has received the maximum number of conversions of 1050\n\"\"\"\n\"\"\"\n**Total Approved conversions by each Id**\n\"\"\"\nac=(df.groupby(['campaign_id'])).approved_conversion.sum()\nac\n\"\"\"\nId 1178 has received the maximum number of approved conversions of 378\n\"\"\"\n\"\"\"\n**Percentage of Ads approved**\n\"\"\"\npercent_approved = (ac\/tc)*100\npercent_approved\n\"\"\"\nId 916 has received the highest percentage number of approved conversions of 41.38%\n\"\"\"\n\"\"\"\n**Finding out total amount spent of Ads**\n\"\"\"\n(df.groupby(['campaign_id'])).spent.sum()\n\"\"\"\nId 936 has spent the highest with 296936.80\n\"\"\"\n\"\"\"\n**Total Number of impressions received**\n\"\"\"\n(df.groupby(['campaign_id'])).impressions.sum()\n\"\"\"\nId 1178 has received the highest number of impressions of 69902476\n\"\"\"\n\"\"\"\n**Total Number of clicks received**\n\"\"\"\n(df.groupby(['campaign_id'])).clicks.sum()\n\"\"\"\nId 1178 has received the highest number of impressions of 9577\n\"\"\"\n\"\"\"\n# Regression Analysis\n\"\"\"\n\"\"\"\n**Assigning independant variables(X) and dependant variable(y)**\n\"\"\"\nX=df[['total_conversion','approved_conversion']]\ny=df[['spent']]\n\"\"\"\n**Importing train test split**\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n**Setting test size to 20%**\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\"\"\"\n**Importing linear regression**\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nlr= LinearRegression()\n\"\"\"\n**Fitting of the data and predicting the values**\n\"\"\"\nlr.fit(X_train, y_train)\npred = lr.predict(X_test)\n\"\"\"\n**Finding out the R-squared value**\n\"\"\"\nfrom sklearn.metrics import r2_score\nr2=r2_score(y_test,pred)\nr2\n\"\"\"\nThe R-squared value is 0.87\n\"\"\"\n\"\"\"\n**Conclusion :** The amount spent is related to the conversions, the more you spent, the more you get reach\n\"\"\"\n\"\"\"\n# Thank You\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '467416c8978b9c'}"}
{"id":"34171","text":"\"\"\"\n<p style=\"color:purple; font-size:50px; font-weight:bold; text-align:center;\">Clustering using Agglomerative Hierarchical Clustering Algorithm<\/p>\n\"\"\"\n\"\"\"\nI will start coding directly. I hope you have some basic knowledge of Hierarchical clustering algorithm. If you want to learn, then check it out [here.](https:\/\/www.javatpoint.com\/hierarchical-clustering-in-machine-learning)\n\"\"\"\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Importing libraries<\/span>\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Loading dataset<\/span>\n\"\"\"\ndf = pd.read_csv('..\/input\/mall-customer\/Mall_Customers.csv')\ndf.head()\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Storing input data in a variable<\/span>\n\"\"\"\nx = df.iloc[:, [3,4]].values\nx\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Draw a Dendrogram<\/span>\n\"\"\"\nimport scipy.cluster.hierarchy as shc  \ndendro = shc.dendrogram(shc.linkage(x, method=\"ward\"))  \nplt.title(\"Dendrogrma Plot\")  \nplt.ylabel(\"Euclidean Distances\")  \nplt.xlabel(\"Customers\")  \nplt.show()\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Train the model using sklearn library<\/span>\n\"\"\"\nfrom sklearn.cluster import AgglomerativeClustering\nmodel = AgglomerativeClustering(n_clusters = 5)\nmodel.fit(x)\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Predict the clustering<\/span>\n\"\"\"\ny_pred = model.fit_predict(x)\ny_pred\n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Visualize the clustering<\/span>\n\"\"\"\nplt.scatter(x[y_pred == 0, 0], x[y_pred == 0, 1], s = 100, c = 'blue', label = 'Cluster 1')  \nplt.scatter(x[y_pred == 1, 0], x[y_pred == 1, 1], s = 100, c = 'green', label = 'Cluster 2')  \nplt.scatter(x[y_pred== 2, 0], x[y_pred == 2, 1], s = 100, c = 'red', label = 'Cluster 3')  \nplt.scatter(x[y_pred == 3, 0], x[y_pred == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')  \nplt.scatter(x[y_pred == 4, 0], x[y_pred == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')\nplt.title('Clusters of customers')  \nplt.xlabel('Annual Income (k$)')  \nplt.ylabel('Spending Score (1-100)')  \nplt.legend()  \nplt.show()  \n\"\"\"\n<span style = \"color:green; font-size:25px; font-weight:bold;\">Conclusion : <\/span>I have successfully built a model of clustering.\n<br><br><br><br>\n<center>Thank you<\/center>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3ef1cc6118ffd3'}"}
{"id":"21592","text":"# 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 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\n# read data\ndf = pd.read_csv('..\/input\/515k-hotel-reviews-data-in-europe\/Hotel_Reviews.csv')\ndf\ndf.iloc[0].Hotel_Address\ncity = df.iloc[0].Hotel_Address.split()[-2]\ncountry = df.iloc[0].Hotel_Address.split()[-1]\ncity, country\ncity = df.iloc[1].Hotel_Address.split()[-2]\ncountry = df.iloc[1].Hotel_Address.split()[-1]\ncity, country\ncity = df.iloc[1034].Hotel_Address.split()[-2]\ncountry = df.iloc[1034].Hotel_Address.split()[-1]\ncity, country\ncity = df.iloc[134].Hotel_Address.split()[-2]\ncountry = df.iloc[134].Hotel_Address.split()[-1]\ncity, country\ndf.columns\ndf.dtypes\ndf.Reviewer_Score.value_counts()\ndf['neg_flag'] = df.Review_Total_Negative_Word_Counts <= df.Review_Total_Positive_Word_Counts\ndf\nimport seaborn as sns\nsns.scatterplot(x=df.lat, y=df.lng, hue=df['neg_flag'])\ncmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True)\nsns.scatterplot(x=df.lat, y=df.lng, size=df['neg_flag'],\n                sizes=(20, 200), palette=cmap)\ndf.shape\ndf.lat.value_counts()\n# visualization library\nimport seaborn as sns\n#  pair plot\nsns.pairplot(df)\n\"\"\"\n **Output description:  Most of the pairplot has linear (vertical or horizental) swarmp, means that many of the attributes do not affect the Reviewers_Score**.     Check Later...\n\"\"\"\n\"\"\"\n# **General overview of not-important attributes**\n\"\"\"\nsns.regplot(x=df['lat'], y=df['Reviewer_Score'])\n\"\"\"\nOutput description: The line is slightly changes (inversely), means there is no coefficient between the lables.\n\"\"\"\nsns.regplot(x=df['lng'], y=df['Reviewer_Score'])\n\"\"\"\nOutput description: The line is slightly changes (positively), means there is no coefficient between the lables.\n\"\"\"\n\"\"\"\n# Reviewer_Score based on nationality\n\"\"\"\n# Reviewe_Score counts\nsns.distplot(df[\"Reviewer_Score\"],kde=False,bins=15)\ndf.shape\n\"\"\"\nVast majority of the Reviewer_Score (33%) and the others are also considered high, which is an obvius indicator that most of Reviews are pretty positive.\nI will check the positivity\/negativity in the end of the notebook (text-cleaning, NLP)\n\"\"\"\n\"\"\"\n# Highest and Lowest Scoring Countries\n\"\"\"\ndf['Reviewer_Score'].min() , df['Reviewer_Score'].max(), df['Reviewer_Score'].mean()\n\"\"\"\n>*Top_Reviewers Nationality\n\"\"\"\ncountries = df[\"Reviewer_Nationality\"].value_counts()[df[\"Reviewer_Nationality\"].value_counts() > 100]\ng = df.groupby(\"Reviewer_Nationality\").mean()\ng.loc[countries.index.tolist()][\"Reviewer_Score\"].sort_values(ascending=False)[:10].plot(kind=\"bar\",ylim=(8.395076569886239,9),title=\"Top Reviewing Countries\")\n\"\"\"\nLeast_Reviewers Nationality\n\"\"\"\ng.loc[countries.index.tolist()][\"Reviewer_Score\"].sort_values()[:10].plot(kind=\"bar\",ylim=(2.5,8.395076569886239),title=\"least Reviewing Countries\")\n\"\"\"\nThe question now is:   It seems that most of the least reveiews basicully from \"Middle East\"\n\"\"\"\n\"\"\"\n# Best Hotels\n\"\"\"\n\"\"\"\nbased on Region\n\"\"\"\ndef country_ident(st):\n    last = st.split()[-1]\n    if last == \"Kingdom\": return \"United Kingdom\"\n    else: return last\n    \ndf[\"Hotel_Country\"] = df[\"Hotel_Address\"].apply(country_ident)\ndf.groupby(\"Hotel_Country\").mean()[\"Reviewer_Score\"].sort_values(ascending=False)\nsns.swarmplot(x=df.Hotel_Country, y=df.Reviewer_Score)\n\"\"\"\nBest Hotels\n\"\"\"\nbest_hotels = df.groupby('Hotel_Name')['Reviewer_Score'].mean().sort_values(ascending=False).head(10)\nbest_hotels.plot(kind=\"bar\",color = \"Green\")\n\"\"\"\nThe mean are slightly different. which draw the same conclusion that is until now there is no a descrimantal attribute (Hotel-coutry and the previous checked ones)\n\"\"\"\n\"\"\"\n# Review Date (searching about a trend, pattern,...)\n\"\"\"\nfrom datetime import datetime\ndf[\"Review_Date_Month\"] = df[\"Review_Date\"].apply(lambda x: x[5:7])\ndf[[\"Review_Date\",\"Reviewer_Score\"]].groupby(\"Review_Date\").mean().plot(figsize=(15,5))\n\"\"\"\nThere is no specific pattern, means there are other different features that affect the Reviewers_Score\n\"\"\"\n\"\"\"\n# Word Cloud\n\"\"\"\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\ndef show_wordcloud(data, title = None):\n    wordcloud = WordCloud(\n        background_color = 'white',\n        max_words = 200,\n        max_font_size = 40, \n        scale = 3,\n        random_state = 42\n    ).generate(str(data))\n\n    fig = plt.figure(1, figsize = (20, 20))\n    plt.axis('off')\n    if title: \n        fig.suptitle(title, fontsize = 20)\n        fig.subplots_adjust(top = 2.3)\n\n    plt.imshow(wordcloud)\n    plt.show()\n    \n# print wordcloud\nshow_wordcloud(df['Positive_Review'])\n# most positive\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(analyzer = \"word\",stop_words = 'english',max_features = 20,ngram_range=(2,2))\nmost_positive_words = cv.fit_transform(df['Positive_Review'])\ntemp1_counts = most_positive_words.sum(axis=0)\ntemp1_words = cv.vocabulary_\ntemp1_words\nshow_wordcloud(df['Negative_Review'])\ncv = CountVectorizer(analyzer = \"word\",stop_words = 'english',max_features = 20,ngram_range=(2,2))\nmost_negative_words = cv.fit_transform(df['Negative_Review'])\ntemp1_counts = most_negative_words.sum(axis=0)\ntemp1_words = cv.vocabulary_\ntemp1_words\n\"\"\"\nConclusion: until now, the only features affect the scores are the hotels themesleves (positive review) due to many aspects such as location,....\n\nNeed to extract all the hotel_positive_modes and then find the weight\n\nAlso, there are other suggestions that are related to the reviewers:\n\nExtracting data 'from Tags' such as (trip type, social status, room, stayed nights)\nNoticing the reviewers' nationalities: The less satisifed ones are somehow come from Asia, specifically Westren Union countris; which needs modeling if it is not by chance\n\"\"\"\n\"\"\"\n# Extracting from Tags, and positive\/negative most words\n\"\"\"\n# extrating nights from tag\ndef splitString(string):\n    array = string.split(\" ', ' \")\n    array[0] = array[0][3:]\n    array[-1] = array[-1][:-3]\n    if not 'trip' in array[0]:\n        array.insert(0,None)\n    try:\n        return float(array[3].split()[1])\n    except:\n        return None\n\ndf[\"Nights\"] = df[\"Tags\"].apply(splitString)\nsns.jointplot(data=df,y=\"Reviewer_Score\",x=\"Nights\",kind=\"reg\")\n\"\"\"\nThe more the reviewer stay at hotel the lower the score is (but also slightly)\n\"\"\"\n\"\"\"\nExtracting Trip_type\n\"\"\"\ndf['Leisure'] = df['Tags'].map(lambda x: 1 if ' Leisure trip ' in x else 0)\ndf['Business'] = df['Tags'].map(lambda x: 2 if ' Business trip ' in x else 0)\ndf['Trip_type'] = df['Leisure'] + df['Business']\n\"\"\"\n....  will checked in building model\nconclusion\nx = Reviewer_Score\ny = positive and negative reviews word vector or\/and some features from tag\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '27a1d950225d16'}"}
{"id":"125998","text":"\"\"\"\n# Exploring Views\n\"\"\"\n\"\"\"\n- What does it mean exploring views???? The notion of view was shown in the example code but had nothing to do with the wrap up exercice.\n- Name of the group participants missing\n- THE LAST \"FIGURE WITH THE \"ARCHITECTURE\" THAT IS NOT AN ARCHITECTURE IT IS THE PIPELINE IMPLEMENTED TO RUN THE EXPERIMENT\n- You had to clean the pieces of code that had nothing to do with the experiment\n\n\"\"\"\npip install dnspython\nimport pandas as pd\nimport json\nimport pymongo\nfrom pymongo import MongoClient\n\nimport pprint\nimport urllib.parse\n\nimport timeit \nimport ipywidgets as widgets\nimport threading \n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nclient = MongoClient(\"mongodb+srv:\/\/geuser:melq.5491@bdegi.3pkrh.gcp.mongodb.net\/gre_EMD?retryWrites=true&w=majority\")\ndb = client.test\ndb = client['gre_EMD'] \ncollection = db['gre10_depl']\ncollection1=db['gre10_mng']\ncollection2=db['gre10_pers']\ncollection3=db['gre10_traj']\ndb.list_collection_names()\ncollection.count_documents({})\ncollection.find_one()\n\"\"\"\nWe can convert our entire collection of data into a pandas DataFrame with the comand below\n\"\"\"\ndepl = pd.DataFrame(list(db.gre10_depl.find()))\n\"\"\"\nWe can use command shape to the number of data samples in rows and in columns:\n\"\"\"\ndepl.shape\n\"\"\"\nWe use print(depl) to see our data\n\"\"\"\nprint(depl)\n\"\"\"\nIn our database the duree has format string so we change it into integer\n\n\"\"\"\ndepl['duree'] = depl['duree'].astype(int)\n\n\"\"\"\nWe do the same thing with \"NO_PERS\"\n\"\"\"\ndepl['NO_PERS'] = depl['NO_PERS'].astype(int)\n\"\"\"\nWe do the same thing with \"NO_DEPL\"\n\"\"\"\ndepl['NO_DEPL'] = depl['NO_DEPL'].astype(int)\n\"\"\"\n# Introduction \nIn this hands on, we used the collection **gre10_depl** of database gre_EMD. We focused on issues relating to the number of travellers, the number of deplacements, the trip duration and the areas travalled through (the resident zones). \n\nIn this study, we used the following attributes : \n- NO_PERS : number of travellers in a trip \n- NO_DEPL: number of shifting in a trip \n- zoneorig : the zone where the trip began from  \n- zoneres : the zone where the trip passed through\n- zonedest : the destination of the trip \n- duree : trip duration  \n\n\"\"\"\n\"\"\"\n# Lonely trip or group trip ?\n\n\"\"\"\n\"\"\"\nWe will examine the number of travallers in the trip in the follwong part. We call \"group tours\" if there are more than 5 (including 5) individuals on a journey.\n\"\"\"\n# View the number of traveller for the less crowed trip and the most crowded trip\nprint('There are',min(depl['NO_PERS']), 'travellers in the less crowded trip.')\nprint('There are',max(depl['NO_PERS']), 'traveller in the most crowded trip.')\nprint ('The average number of travaller is: ', depl['NO_PERS'].mean(), '.' )\nprint ('The median number of travaller is: ', depl['NO_PERS'].median(), '.' )\n\"\"\"\nOn average, people traveled in pairs. The median here means that half of the people traveled alone or in pairs and more than 3 people traveled in the other half.\n\"\"\"\n# Groupe by number of travallers in a trip\nnbPers=depl.groupby('NO_PERS').size()\nprint (nbPers)\n# Delivery the data nbPers in table form\ndfPers=pd.DataFrame(nbPers,columns=['counts'])\n\n# Set the width and height of the figure \nplt.figure(figsize=(8,6))\n\n# Bar chart showing number of residents having stayed in each zone\nsns.barplot(x=dfPers.index, y=dfPers['counts'])\n\n# Add title\nplt.title(\"Number of trips taken by various numbers of individuals\")\n\n# Add label for vertical axis\nplt.xlabel(\"Number of individuqls on a trip\")\n\n# Add label for vertical axis\nplt.ylabel(\"Number of trips \")\n# Compute the rates\nlonelyTrip =depl[(depl.NO_PERS >= 1)&(depl.NO_PERS <= 2)]\ngroupTrip =depl[(depl.NO_PERS >= 5)]\nprint ('The rate of individuals traveling alone or in pairs ', int(len(lonelyTrip)\/float(len(depl))*100), '%.' )\nprint ('The rate of group trip: ', int(len(groupTrip)\/float(len(depl))*100), '%.' )\n\"\"\"\n# Number of deplacement\n\"\"\"\nprint('The minimum number of deplacement in our database is', min(depl['NO_DEPL']), '.')\nprint('The maximum number of deplacement in our database is', max(depl['NO_DEPL']), '.')\nprint ('The average of the number of deplacement is: ', depl['NO_DEPL'].mean(), '.' )\nprint ('The median of the number of deplacement is: ', depl['NO_DEPL'].median(), '.' )\n\"\"\"\nWe can notice that on average, the trips in the database are composed of 3.2 deplacements.\n\"\"\"\n# Group by each number of deplacement\nnbDepl=depl.groupby('NO_DEPL').size()\nprint (nbDepl)\n\"\"\"\nWe can notice that the more the number of deplacement increases, the less the number of trips composed of these deplacements decreases. For example, only 2 trips have 22 deplacements whereas 14831 trips have one deplacement\n\"\"\"\n# Show nbDepl in table form\ndfNoDepl=pd.DataFrame(nbDepl,columns=['counts'])\n\n# Sort by 'counts' in descending order \nprint(dfNoDepl.sort_values(by = 'counts',ascending = False, inplace = False))\nnoDpl1 =depl[(depl.NO_DEPL == 1)]\nnoDpl1.shape # return a tuple showing the dimensionality of the dataframe NoDpl1\nnoDpl2 =depl[(depl.NO_DEPL == 2)]\nnoDpl2.shape # return a tuple showing the dimensionality of the dataframe NoDpl2\nnoDpl3 =depl[(depl.NO_DEPL == 3)]\nnoDpl3.shape # return a tuple showing the dimensionality of the dataframe NoDpl3\nnoDpl7 =depl[(depl.NO_DEPL == 7)]\nnoDpl7.shape # return a tuple showing the dimensionality of the dataframe NoDpl7\nnoDpl10 =depl[(depl.NO_DEPL == 10)]\nnoDpl10.shape # return a tuple showing the dimensionality of the dataframe NoDpl10\nprint ('The rate of trips having 1 deplacement: ', int(len(noDpl1)\/float(len(depl))*100), '%.' )\nprint ('The rate of people having 2 deplacements: ', int(len(noDpl2)\/float(len(depl))*100), '%.' )\nprint ('The rate of people having 3 deplacements: ', int(len(noDpl3)\/float(len(depl))*100), '%.' )\nprint ('The rate of people having 7 deplacements: ', int(len(noDpl7)\/float(len(depl))*100), '%.' )\nprint ('The rate of people having 10 deplacements: ', int(len(noDpl10)\/float(len(depl))*100), '%.' )\n\n\"\"\"\nAs noticed before, the rates of trips which have done one or two deplacements are the highest, 23%. From 10 deplacements, the rate is only 0%.\n\"\"\"\n# Set the width and height of the figure \nplt.figure(figsize=(14,6))\n\n# Bar chart showing the number of trips according to the number of deplacement \nsns.barplot(x=dfNoDepl.index, y=dfNoDepl['counts'])\n\n# Add title\nplt.title(\"Numbers of trips having x deplacements\")\n\n# Add label for vertical axis\nplt.xlabel(\"Number of deplacements\")\n\n# Add label for vertical axis\nplt.ylabel(\"Number of trips\")\n\n\"\"\"\nOn this graph, we can see indeed that the number of deplacement 1 has the highest number of trips. And step by step, it decreases.\n\"\"\"\ngroupZoneOrig = depl[[\"zoneorig\", \"NO_DEPL\"]].groupby('zoneorig').mean()\ngroupZoneOrig\nprint('The maximum mean of number of deplacement in trips from origine zone is', groupZoneOrig.max(), '.')\nprint('The minimum mean of number of deplacement in trips from origine zones is', groupZoneOrig.min(), '.')\n\"\"\"\nWith this table, we can see what is for each origine zone, the mean of the number of deplacement of trips. To see which origine zones have the maximum or the minimum mean, we filter data by the values found before.\n\"\"\"\ngroupZoneOrig[groupZoneOrig['NO_DEPL'] == 13.0]\ngroupZoneOrig[groupZoneOrig['NO_DEPL'] == 1.0]\n\"\"\"\nHere we can notice that it is the trips from the zone 128051 which have the most deplacements, in average 13 deplacements. Maybe, this zone is far enough from destination zones, that\u2019s why the trips from there have more deplacements. On the contrary, trips from the zones 601005, 601016, 603006, 801002, 804051 and 806003 make only on average 1 deplacement. We can assume that these zones are near destination zones.\n\"\"\"\ngroupZoneDest = depl[[\"zonedest\", \"NO_DEPL\"]].groupby('zonedest').mean()\ngroupZoneDest\nprint('The maximum mean of number of deplacement in trips to destination zones is', groupZoneDest.max(), '.')\nprint('The minimum mean of number of deplacement in trips to destination zones is', groupZoneDest.min(), '.')\ngroupZoneDest[groupZoneDest['NO_DEPL'] == 12.0]\n\"\"\"\nSo there is in average 12 deplacements to the destination zone 128051\n\"\"\"\ngroupZoneDest[groupZoneDest['NO_DEPL'] == 1.0]\n\"\"\"\nSo there are on average 12 deplacements in the trips to the destination zone 128051. We can notice that it is the same zone which has the maximum mean of number of deplacements of trips from origine zones. We can conclude that this zone is far away from the other zones, that\u2019s why there are many deplacements to do in trips from this zone or to this zone.\n\"\"\"\n\"\"\"\n# Duration\n\"\"\"\n# Statistics of trip duration\ndur_mean = depl['duree'].mean()\ndur_median = depl['duree'].median()\ndur_var = dur_mean = depl['duree'].var()\ndur_std = dur_mean = depl['duree'].std()\n\nprint ('Statistics of trip duration: mu:',dur_mean,', median:',dur_median,', var:',dur_var,', std:',dur_std)\n# Duration distinction between lonely trips and group trips\ndur_lonelyTrip_mean = lonelyTrip['duree'].mean()\ndur_groupTrip_mean = groupTrip['duree'].mean()\n\nprint ('The average duration of lonely trip is: ', dur_lonelyTrip_mean, '.' )\nprint ('The average duration of group trip is: ', dur_groupTrip_mean, '.' )\n\"\"\"\n**Longest trip and shortest trip**\n\"\"\"\n# The longest road\n\ns = depl[[\"duree\",\"zoneorig\",\"zonedest\"]]\nindexmax = depl[\"duree\"].idxmax()\nprint(s.loc[[indexmax]])\n# The shortest road\n\nindexmin = depl[\"duree\"].idxmin()\nprint(s.loc[[indexmin]])\n\"\"\"\n# Resident zone\n\n\"\"\"\n# Groupe by resident zone \nnbZoneRes=depl.groupby('zoneres').size()\nprint (nbZoneRes)\n# show total nomber of resident zone \nprint('Totally, there are', nbZoneRes.size, 'resident zones where the trips passed through.')\n# View nbZoneRes in table form\ndfZoneRes=pd.DataFrame(nbZoneRes,columns=['counts'])\n\n# Sorting in descending order by 'counts' \nprint(dfZoneRes.sort_values(by = 'counts',ascending = False, inplace = False))\n\"\"\"\nMuch of trips traveled through these 3 zones : zone 1, zone2 and zone 3. From the calculation above, we found that there are 20735 items for zone 1, 17799 items for zone 2 and 10845 items for zone3. The fewest trips passing through the zone 54 (only 2 trips).\n\"\"\"\nzoneRes1 =depl[(depl.zoneres == '1')]\nzoneRes1.shape # return a tuple showing the dimensionality of the dataframe zoneRes1\nzoneRes2 =depl[(depl.zoneres == '2')]\nzoneRes2.shape # return a tuple showing the dimensionality of the dataframe zoneRes2\nzoneRes3 =depl[(depl.zoneres == '3')]\nzoneRes3.shape # return a tuple showing the dimensionality of the dataframe zoneRes3\nprint ('The rate of trips passing through the zone 1: ', int(len(zoneRes1)\/float(len(depl))*100), '%.' )\nprint ('The rate of trips  passing through the zone 2: ', int(len(zoneRes2)\/float(len(depl))*100), '%.' )\nprint ('The rate of trips  passing through the zone 3: ', int(len(zoneRes3)\/float(len(depl))*100), '%.' )\n# Set the width and height of the figure \nplt.figure(figsize=(14,6))\n\n# Bar chart showing number of trips passing through the x zone\nsns.barplot(x=dfZoneRes.index, y=dfZoneRes['counts'])\n\n# Add title\nplt.title(\"Numbers of trips passing through the x zone\")\n\n# Add label for vertical axis\nplt.xlabel(\"Resident Zone\")\n\n# Add label for vertical axis\nplt.ylabel(\"Number of trips\")\n\"\"\"\n# Destination\n\"\"\"\n\"\"\"\nwe will study in the following section the destination zone for people having stayed in zone 1. Have people staying in zone 1 gone to the same destination or not? Is it possible that the resident zone 1 is a must-see location for certain given destination?\n\"\"\"\n# Groupe by destination zone\nnbZoneDest=zoneRes1.groupby('zonedest').size()\n\n# View nbZoneDest data in table form\ndfZoneDest=pd.DataFrame(nbZoneDest,columns=['counts'])\n\n# Sorting in descending order by 'counts'\nprint(dfZoneDest.sort_values(by = 'counts',ascending = False, inplace = False).head())\n\"\"\"\nFrom the above data, the top 5 zones where people having stayed in zone 1 are : 101001, 131001, 137001, 128001, 140001.\n\"\"\"\n\"\"\"\nIn next part we want to know how many people will go to the same destination, so we group by zone destination and calcul the sum of the people in each zone destination\n\"\"\"\ngroup = depl[[\"zonedest\",\"NO_PERS\"]].groupby('zonedest')['NO_PERS'].sum()\ngroup\n\"\"\"\nHere, for each zone origin we can know all the reachable zone destinations and the duration between 2 zones\n\"\"\"\ngroup2 = depl[[\"zoneorig\",\"zonedest\",\"duree\"]].groupby(['zoneorig', 'zonedest'])['duree'].min()\ngroup2.head()\n\"\"\"\n![Wrap-up.png](attachment:Wrap-up.png)\n\"\"\"\n\"\"\"\nt\n\"\"\"\n\"\"\"\n## Releases\n\"\"\"\nstart_time = timeit.default_timer()\n# Creates a client for the primary sandbox from cluster host cluster0-nlbcx.mongodb.net\nclient = MongoClient(\"mongodb:\/\/adminUser:xpass@cluster0-shard-00-00-nlbcx.mongodb.net:27017\/?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin\")\n\ndb = client.test \ndb = client['stackoverflow-dump-view']\ncollection = db['viewModel-view']\n\nview = collection.find_one() # json file, can be browsed as a dictionary\n\n#print (view['releaseViewList'][0].keys())\nviewRel0=view['releaseViewList'][0]\nviewRel1=view['releaseViewList'][1]\nviewRel2=view['releaseViewList'][2]\n\"\"\"\n### First Release View\n\"\"\"\nviewRel0\n\"\"\"\n### Second Release View\n\"\"\"\nviewRel1\n\"\"\"\n### Third Release View\n\"\"\"\nviewRel2\nminValue0=viewRel0['attributeDescList'][0]['minValue'];print(minValue0)\nmaxValue0=viewRel0['attributeDescList'][0]['maxValue'];print(maxValue0)\nmean0=viewRel0['attributeDescList'][0]['mean'];print(mean0)\nmedian0=viewRel0['attributeDescList'][0]['median'];print(median0)\nnullValue0=viewRel0['attributeDescList'][0]['nullValue'];print(nullValue0)\nname0=viewRel0['attributeDescList'][0]['name'];print(name0)\ncount0=viewRel0['attributeDescList'][0]['count'];print(count0)\n\"\"\"\n### Number of Null Values per release\n\"\"\"\nnullsRel0=[]\nfor i in viewRel0['attributeDescList']:\n    nullsRel0.append(sum(i['nullValue']))\n\nnullsRel1=[]\nfor i in viewRel1['attributeDescList']:\n    nullsRel1.append(sum(i['nullValue']))\n\nnullsRel2=[]\nfor i in viewRel2['attributeDescList']:\n    nullsRel2.append(sum(i['nullValue']))\nimport matplotlib.pyplot as plt \n\n# line 1 points \nx = ['Votes','Posts','Comments','Badges','Users']\ny1 = nullsRel0\n# plotting the line 1 points \nplt.plot(x, y1, label = \"Jan01-18\")\n\n# line 2 points \ny2 = nullsRel1\n# plotting the line 1 points \nplt.plot(x, y2, label = \"Jan02-18\")\n\n# line 3 points \ny3 = nullsRel2\n# plotting the line 1 points \nplt.plot(x, y3, label = \"Jan03-18\")\n\n# naming the x axis \nplt.xlabel('dataset') \n# naming the y axis \nplt.ylabel('null values') \n# giving a title to my graph \nplt.title('Number of null values per release') \n\n# show a legend on the plot \nplt.legend() \n\n# function to show the plot \nplt.show() \n\"\"\"\n### Number of Items per release\n\"\"\"\ncountRel0=[]\nfor i in viewRel0['attributeDescList']:\n    countRel0.append(i['count'])\n\ncountRel1=[]\nfor i in viewRel1['attributeDescList']:\n    countRel1.append(i['count'])\n\ncountRel2=[]\nfor i in viewRel2['attributeDescList']:\n    countRel2.append(i['count'])\nimport matplotlib.pyplot as plt \n\n# line 1 points \nx = ['Votes','Posts','Comments','Badges','Users']\ny1 = countRel0\n# plotting the line 1 points \nplt.plot(x, y1, label = \"Jan01-18\")\n\n# line 2 points \ny2 = countRel1\n# plotting the line 1 points \nplt.plot(x, y2, label = \"Jan02-18\")\n\n# line 3 points \ny3 = countRel2\n# plotting the line 1 points \nplt.plot(x, y3, label = \"Jan03-18\")\n\n# naming the x axis \nplt.xlabel('dataset') \n# naming the y axis \nplt.ylabel('count') \n# giving a title to my graph \nplt.title('Count of items per release') \n\n# show a legend on the plot \nplt.legend() \n\n# function to show the plot \nplt.show() \nelapsed = timeit.default_timer() - start_time\n\"\"\"\n### Execution time\n\"\"\"\nprint (\"execution time: \" + str(elapsed) + \" s\")\n#------------------------------------------------------------------ Q1 --------------------------------------------------------------------#\nbtn1=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl1=widgets.Text(value='0',description='',disabled=True)\nq1 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q2 --------------------------------------------------------------------#\nbtn2=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl2=widgets.Text(value='0',description='',disabled=True)\nq2 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q3 --------------------------------------------------------------------#\nbtn3=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl3=widgets.Text(value='0',description='',disabled=True)\nq3 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q4 --------------------------------------------------------------------#\nbtn4=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl4=widgets.Text(value='0',description='',disabled=True)\nq4 = widgets.Dropdown(options=['Id','PostTypeId','AcceptedAnswerId','ParentId','CreationDate','DeletionDate','Score','ViewCount','Body','OwnerUserId','OwnerDisplayName','LastEditorUserId','LastEditorDisplayName','LastEditDate','LastActivityDate','Title','Tags','AnswerCount','CommentCount','FavoriteCount','ClosedDate','CommunityOwnedDate'],\n    value=None,description='Attribute:',disabled=True,)\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q5 --------------------------------------------------------------------#\nbtn5=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl5=widgets.Text(value='0',description='',disabled=True)\ndrop_options = [['--','Id','UserId','Name','Date','Class','TagBased'],\n                ['--','Id','PostId','Score','Text','CreationDate','UserDisplayName','UserId'],\n               ['--','Id','PostTypeId','AcceptedAnswerId','ParentId','CreationDate','DeletionDate','Score','ViewCount','Body','OwnerUserId','OwnerDisplayName','LastEditorUserId','LastEditorDisplayName','LastEditDate','LastActivityDate','Title','Tags','AnswerCount','CommentCount','FavoriteCount','ClosedDate','CommunityOwnedDate'],\n               ['--','Id','Reputation','CreationDate','DisplayName','LastAccessDate','WebsiteUrl','Location','AboutMe','Views','UpVotes','DownVotes','ProfileImageUrl','EmailHash','AccountId'],\n               ['--','Id','PostId','VoteTypeId','UserId','CreationDate','BountyAmount']]\nchildren = [widgets.Dropdown(options=name,description='',value=None) for name in drop_options]\ntab = widgets.Tab()\ntab.children = children\nitems=['Badges', 'Comments', 'Posts', 'Users', 'Votes']\nfor i in range(len(items)):\n    tab.set_title(i, items[i])\nq5=tab\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q6 --------------------------------------------------------------------#\nbtn6=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl6=widgets.Text(value='0',description='',disabled=True)\nq6= widgets.RadioButtons(options=['Yes', 'No'],value=None,description='',disabled=False)\n#------------------------------------------------------------------------------------------------------------------------------------------#\n#------------------------------------------------------------------ Q7 --------------------------------------------------------------------#\nbtn7=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')\n#timeLbl7=widgets.Text(value='0',description='',disabled=True)\nchildren2 = [widgets.Dropdown(options=name,value=None) for name in drop_options]\ntab2 = widgets.Tab()\ntab2.children = children2\nfor i in range(len(items)):\n    tab2.set_title(i, items[i])\nq7=tab2\n#------------------------------------------------------------------------------------------------------------------------------------------#\n\n#------------------------------------------------------- Effort questions -----------------------------------------------------------------#\neffortW = []\nfor e in range(7):\n    effortW.append(widgets.ToggleButtons(options=['Low', 'Regular', 'High'],description='Select Effort:',disabled=False,value=None))  \n\ntimeLblW = []\nfor t in range(7):\n    timeLblW.append(widgets.Text(value='0',description='',disabled=True))  \n    \n# Timer function    \n# btn - receive a button object\n# lbl - receive a label object\n#    we use lbl.value to get timer value\n# q - receive a multiple option object\n#    we use q.value to get answered value\ndef timer(btn,lbl,q):        \n\n    cnt =int(lbl.value)   \n    on=btn.value \n    desc=q.description\n\n    if desc!='Submitted':\n        if on==True:      \n            threading.Timer(1, timer, [btn,lbl,q]).start()\n            cnt = cnt+1                        \n            lbl.value = str(cnt)\n            btn.description='Submit answer'\n            q.disabled=False\n\n        elif on==False:\n            threading.Timer(1, timer, [btn,lbl,q]).start()\n            btn.description='Activate'\n            q.disabled=True\n\n        else:\n            None\n\n    if cnt!=0 and btn.description=='Activate':\n        threading.Timer(1, timer, [btn,lbl,q]).start()\n        q.description='Submitted'\n        btn.visibility='hidden'\n        btn.description='--'\n        btn.disbled=True  \n\ndef timerTab(btn,lbl,q):        \n\n    cnt=int(lbl.value)   \n    on=btn.value \n    desc=q.children[0].description\n\n    if desc!='Submitted':\n        if on==True:      \n            threading.Timer(1, timerTab, [btn,lbl,q]).start()\n            cnt = cnt+1                        \n            lbl.value = str(cnt)\n            btn.description='Submit answer'\n            for i in range(len(q.children)):\n                q.children[i].disabled=False\n\n        elif on==False:\n            threading.Timer(1, timerTab, [btn,lbl,q]).start()\n            btn.description='Activate'\n            for i in range(len(q.children)):\n                q.children[i].disabled=True\n\n        else:\n            None\n\n    if cnt!=0 and btn.description=='Activate':\n        threading.Timer(1, timerTab, [btn,lbl,q]).start()\n        for i in range(len(q.children)):\n            q.children[i].description='Submitted'\n        btn.visibility='hidden'\n        btn.description='--'\n        btn.disbled=True                        \n\"\"\"\n# Tasks\n\"\"\"\n\"\"\"\n## Q1. Which is the release with best quality? (less missing, nulls and default values)\n\"\"\"\ntimeLblW[0]\nbtn1\nq1\n\"\"\"\nJanuary 2nd 2018\n\"\"\"\ntimer(btn1,timeLblW[0],q1)\n\"\"\"\n### Q1.1 Effort to answer the question\n\"\"\"\neffortW[0]\n\"\"\"\nEffort : regular\n\n\"\"\"\n\"\"\"\n## Q2. Which release has the most number of records?\n\"\"\"\ntimeLblW[1]\nbtn2\nq2\n\"\"\"\nJanuary 3rd 2018 \n\"\"\"\ntimer(btn2,timeLblW[1],q2)\n\"\"\"\n### Q2.1 Effort to answer the question\n\"\"\"\neffortW[1]\n\"\"\"\nEffort : low\n\"\"\"\n\"\"\"\n## Q3. Which is the release where _UpVote_ attribute from _Users_ item is more spread?\n\"\"\"\ntimeLblW[2]\nbtn3\nq3\n\"\"\"\nJanuary 3rd 2018 \n\n\"\"\"\ntimer(btn3,timeLblW[2],q3)\n\"\"\"\n### Q3.1 Effort to answer the question\n\"\"\"\neffortW[2]\n\"\"\"\nEffort : high\n\"\"\"\n\"\"\"\n## Q4. Which attribute from _Posts_ item can be used to compute answers' popularity and author's reputation (started answered and authors)\n\"\"\"\ntimeLblW[3]\nbtn4\nq4\n\"\"\"\nViewCount \n\n\"\"\"\ntimer(btn4,timeLblW[3],q4)\n\"\"\"\n### Q4.1 Effort to answer the question\n\"\"\"\neffortW[3]\n\"\"\"\nEffort : low\n\n\"\"\"\n\"\"\"\n## Q5. Which is\/are the attribute(s) that can be used to identify the most trendy topic addressed in the release?\n\"\"\"\ntimeLblW[4]\nbtn5\nq5\n\"\"\"\n* Badges : TagBased \n* Comments : Score \n* Posts : ViewCount \n* Users : Views \n* Votes : BountyAmount\n\n\"\"\"\ntimerTab(btn5,timeLblW[4],q5)\n\"\"\"\n### Q5.1 Effort to answer the question\n\"\"\"\neffortW[4]\n\"\"\"\nEffort : low\n\"\"\"\n\"\"\"\n## Q6 Will missing, null, and default values bias observation of trends?\n\"\"\"\ntimeLblW[5]\nbtn6\nq6\n\"\"\"\nYes\n\n\"\"\"\ntimer(btn6,timeLblW[5],q6)\n\"\"\"\n### Q6.1 Effort to answer the question\n\"\"\"\neffortW[5]\n\"\"\"\nEffort : low\n\"\"\"\n\"\"\"\n## Q7. Choose the attributes that can be used as sharging keys to fragment the release using a hash based and an interval based strategy\n\"\"\"\ntimeLblW[6]\nbtn7\ntimerTab(btn7,timeLblW[6],q7)\nq7\n\"\"\"\n* Badges : TagBased\n* Comments : Score \n* Posts : View count \n* Users : Views\n* Votes : BountyAmount\n\n\"\"\"\n\"\"\"\n### Q7.1 Effort to answer the question\n\"\"\"\neffortW[6]\n\"\"\"\nEffort : regular\n\"\"\"\n\"\"\"\n## Get Match Results\n\"\"\"\n# collect user effort \nuserEffortL = []\nfor e in effortW:\n    userEffortL.append(e.value) \n        \n# collect time from answers\nqtimeL=[]\nfor t in timeLblW:\n    qtimeL.append(int(t.value))\n\n# tuple for answers\nqans1=q1.options[2]\nqans2=q2.options[0]\nqans3=q3.options[1]\nqans4=q4.options[3]\nqans5=[q5.children[0].options[3],q5.children[1].options[0],q5.children[2].options[5],q5.children[3].options[5],q5.children[4].options[0]]\nqans6=q6.options[0]\nqans7=[q7.children[0].options[3],q7.children[1].options[0],q7.children[2].options[5],q7.children[3].options[5],q7.children[4].options[0]]\nqans = [qans1,qans2,qans3,qans4,qans5,qans6,qans7]\n\nscoreL = [0.0]*7\n\nif q1.value == qans1: scoreL[0]=1 \nif q2.value == qans2: scoreL[1]=1 \nif q3.value == qans3: scoreL[2]=1 \nif q4.value == qans4: scoreL[3]=1 \n\nif qans5[0] == q5.children[0].value: scoreL[4]=scoreL[4] + 0.2\nif qans5[1] == q5.children[1].value: scoreL[4]=scoreL[4] + 0.2\nif qans5[2] == q5.children[2].value: scoreL[4]=scoreL[4] + 0.2\nif qans5[3] == q5.children[3].value: scoreL[4]=scoreL[4] + 0.2\nif qans5[4] == q5.children[4].value: scoreL[4]=scoreL[4] + 0.2\n\nif q6.value ==qans6: scoreL[5]=1\n\nif qans7[0] == q7.children[0].value: scoreL[6]=scoreL[6] + 0.2\nif qans7[1] == q7.children[1].value: scoreL[6]=scoreL[6] + 0.2\nif qans7[2] == q7.children[2].value: scoreL[6]=scoreL[6] + 0.2\nif qans7[3] == q7.children[3].value: scoreL[6]=scoreL[6] + 0.2\nif qans7[4] == q7.children[4].value: scoreL[6]=scoreL[6] + 0.2\n        \n# calculated effort\ncalcEffortL = []\nmaxcEffort = 100\nfor i in range(0,len(scoreL)):\n    if scoreL[i] == 0: \n        calcEffortL.append(maxcEffort)\n    else:\n        if int(qtimeL[i]) > 300: qtimeL[i] = 300 # 5 min limit\n        tmp=int(qtimeL[i])\/scoreL[i]\n        calcEffortL.append((tmp*100)\/1800)            \nimport csv\n# qid | time | score | user_effort | calculated_effort | execution_time (cpu)\nheader=['qid', 'score', 'time', 'user_effort', 'calculated_effort', 'execution_time'] \nqid=list(range(1,8))\nelapsedL = [elapsed]*7\n\nrows = zip(qid,scoreL,qtimeL,userEffortL,calcEffortL,elapsedL)\n\nwith open(\"..\/results\/match2.csv\", mode=\"w\") as f:\n    #writer = csv.writer(f, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n    writer = csv.writer(f, delimiter=',')\n    writer.writerow(header)\n    for row in rows:\n        writer.writerow(row)","meta":"{'source': 'AI4Code', 'id': 'e7b96751699c10'}"}
{"id":"77280","text":"# 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 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\n\"\"\"\n<a id = 'sec-one'> <\/a>\n## Reading the Datasets\n\"\"\"\npath = '\/kaggle\/input\/wine-reviews\/winemag-data-'\nwine_data = pd.read_csv(path+'130k-v2.csv')\nprint(wine_data.info())\nprint(\"Wine DataFrame shape: {}\".format(wine_data.shape))\nprint(\"Wine DataFrame Columns: {}\".format(wine_data.columns))\nwine_data.head()\n\"\"\"\n<a id = 'sec-2'> <\/a>\n## Exploratory Data Analysis\n1. [Price Distribution against Points](#sec-2a)\n2. [Which Wine variety is most expensive?](#sec-2b)\n3. [Which Country produces most expensive Wines?](#sec-2c)\n4. [Which Wine variety has most points?](#sec-2d)\n\"\"\"\n\"\"\"\n<a id = 'sec-2a'> <\/a>\n### Price Distribution against Points\n\"\"\"\n'''\nFor the initial analysis of the dataset, the Null values have been ignored. All the Null values have been dropped!!\nFind the average price for each point score to analyze if price increases with an increase in points.\n'''\nwd_price = wine_data.groupby('points')['price'].mean().reset_index()\nwd_price.head()\nimport plotly.express as px\n\nfig = px.scatter(x=wd_price['points'], y=wd_price['price'], title = 'Price Distribution against Points')\nfig.show()\n\"\"\"\n<a id = 'sec-2b'> <\/a>\n### Which Wine variety is most expensive? ---------> Ramisco\n\"\"\"\nwd_variety = wine_data.groupby('variety')['price'].mean().reset_index()\nprint(\"The average price of Wine per variety\")\nwd_variety.head()\nwd_variety = wd_variety.sort_values('price', ascending=False)[0:10]\n\nfig = px.pie(names=wd_variety['variety'], values=wd_variety['price'], title='Most expensive Wine varieties')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n<a id = 'sec-2c'> <\/a>\n### Which Country produces most expensive Wines? ----------> Switzerland\n\"\"\"\nwd_country = wine_data.groupby('country')['price'].mean().reset_index()\nprint(\"The average price of Wine per country\")\nwd_country.head()\nwd_country = wd_country.sort_values('price', ascending=False)[0:10]\n\nfig = px.pie(names=wd_country['country'], values=wd_country['price'], title='Countries thar produce expensive Wines')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\n\"\"\"\n<a id = 'sec-2d'> <\/a>\n### Which Wine variety has most points? ----------> Terrantez\n\"\"\"\nwd_variety = wine_data.groupby('variety')['points'].mean().reset_index()\nwd_variety.head()\nwd_variety = wd_variety.sort_values('points', ascending = False)[0:7]\n\nfig = px.pie(values=wd_variety['points'], names=wd_variety['variety'], title='Wine varieties with most points')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()","meta":"{'source': 'AI4Code', 'id': '8ded2ba00d22bb'}"}
{"id":"106816","text":"import numpy as np \nimport pandas as pd \nimport os\nimport matplotlib.pyplot as plt\nfrom itertools import chain\nfrom kaggle.competitions import twosigmanews\n\nenv = twosigmanews.make_env()\nprint('Done!')\n(market_train_df, news_train_df) = env.get_training_data()\nprint(f'market train df shape: {market_train_df.shape}')\nprint(f'news train df shape: {news_train_df.shape}')\n\"\"\"\n## Let's take a look at market data\n\"\"\"\nmarket_train_df.head()\nmarket_train_df.info()\n\"\"\"\n### missing values:\n- There are missing values in 4 returns columns spreadding out over lots of trading days. The reason is pointed out in the data description: \"The set of included instruments changes daily and is determined based on the amount traded and the availability of information. This means that there may be instruments that enter and leave this subset of data. There may therefore be gaps in the data provided, and this does not necessarily imply that that data does not exist.\"\n\"\"\"\nmissing_count = market_train_df.isna().sum()\nmissing_count\nplt.figure(figsize=(12,8))\nplt.bar(missing_count.index, missing_count.values)\nplt.xticks(rotation=45)\nplt.show()\n# show number of missing values over time\n\nmissing_col = ['returnsClosePrevMktres1', 'returnsOpenPrevMktres1', \n               'returnsClosePrevMktres10', 'returnsOpenPrevMktres10']\ndf_na = market_train_df[market_train_df.isnull().any(axis=1)]\nmissing_day = df_na.loc[:, missing_col].isnull().groupby(df_na.time).sum()\n\nf, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True, figsize=(12,8))\nax1.plot(missing_day.index, missing_day.returnsOpenPrevMktres1)\nax1.set_ylim(0,100)\nax1.set_title('returnsClosePrevMktres1')\nax2.plot(missing_day.index, missing_day.returnsOpenPrevMktres1)\nax2.set_ylim(0,100)\nax2.set_title('returnsOpenPrevMktres1')\nax3.plot(missing_day.index, missing_day.returnsClosePrevMktres10)\nax3.set_ylim(0,200)\nax3.set_title('returnsClosePrevMktres10')\nax4.plot(missing_day.index, missing_day.returnsOpenPrevMktres10)\nax4.set_ylim(0,200)\nax4.set_title('returnsOpenPrevMktres10')\nplt.show()\n\"\"\"\nThere are little more unique asset codes than names. It means there are cases that multiple asset codes correspond to the same asset name(there is an \"unknown\" asset name). Also note that the predictions are based on asset codes. \n\"\"\"\nprint(f'number of unique asset Codes: {market_train_df.assetCode.unique().shape[0]}')\nprint(f'number of unique asset Names: {market_train_df.assetName.unique().shape[0]}')\n\"\"\"\n### continuous variables\n\"\"\"\nmarket_train_df.describe()\n# histograme for log10(volume)\n\nplt.hist(market_train_df.volume.apply(lambda x: np.log10(x) if x!=0 else 0), bins=50)\nplt.title('volume')\nplt.show()\n# there are some very high open(10k) and close value(1.5k) \nf, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,4))\nax1.hist(market_train_df.open, bins=50, range=(0,500))\nax1.set_title('open')\nax2.hist(market_train_df.close, bins=50, range=(0,500))\nax2.set_title('close')\nplt.show()\n\"\"\"\n- Most of the returns values are close to 0, although in extreme cases the number can be quite large. Also, the distributions of 10 day return are wider than 1day return, since it's over longer period.\n- Given the range of next 10 day return and the range of y (-1,1) the submission wants, consider using tanh(next 10 day return) as target for prediction. \n\"\"\"\nf, axes = plt.subplots(3, 3, sharey=True, figsize=(15,15))\nfor i in range(3):\n    for j in range(3):\n        axes[i,j].hist(market_train_df.iloc[:, 6+i*3+j], range=(-0.5,0.5), bins=50)\n        axes[i,j].set_title(market_train_df.columns[6+i*3+j])\nplt.show()\n\"\"\"\n## Next,  news data\n\"\"\"\nnews_train_df.head()\nnews_train_df.info()\n# no missing value here\nnews_train_df.isna().sum().sum()\nnews_train_df.describe()\n# plot histogram of all the numeric columns\nnews_train_df.select_dtypes(include=[np.number]).hist(figsize=(15,15))\nplt.show()\n\"\"\"\nIt appears that there are much more asset codes and names in the news dataframe than the market dataframe. So there are assets in the news that are not included in market set. \n\"\"\"\nn_codes = len(set(chain(*news_train_df['assetCodes'].str.findall(f\"'([\\w\\.\/]+)'\"))))\nprint(f'number of unique asset Codes in news set: {n_codes}')\nprint(f'number of unique asset Names in news set: {news_train_df.assetName.unique().shape[0]}')\nprint('*'*50)\nprint(f'number of unique asset Codes in market set: {market_train_df.assetCode.unique().shape[0]}')\nprint(f'number of unique asset Names in market set: {market_train_df.assetName.unique().shape[0]}')\n\"\"\"\n## I haven't seen anyone doing EDA on test set yet, but there is something that may have been overlooked.\n\nEach time we call env.get_prediction_days(),  the Two Sigma method will spit out a set of market data in which each row is the data for a asset that we will need to make prediction. It also spit out the news **since the last trading day**. So as you can see, for 2017-1-3, the news set acutally contains news from 2016-12-30 to 2017-1-3(weekends and holidays). Also note that Two Sigma split days at 22:00, time after 22:00 and before 0:00 is considered the next day. So it looks like attention need to be paid when joining market and news set. Simply joining by date and assetCode may throw away useful information, or put 'future'(arguably) information in training data. \n\"\"\"\ndays = env.get_prediction_days()\n(market_obs_df, news_obs_df, predictions_template_df) = next(days)\nprint(f'market_obs_df shape: {market_obs_df.shape}')\nprint(f'news_obs_df shape: {news_obs_df.shape}')\nprint(f'predictions_template_df shape: {predictions_template_df.shape}')\nmarket_obs_df.head()\nnews_obs_df.head()\nprint(f'date in market set: {market_obs_df.time.dt.date.unique().tolist()}')\nprint(f'date in news set: {news_obs_df.time.dt.date.unique().tolist()}')\n\"\"\"\nThanks!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c43df84340b791'}"}
{"id":"125298","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import model_selection\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import LabelEncoder\ndf = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ndf.head()\n# Let's check the distribution of Survived\ndf[\"Survived\"].value_counts()\n\"\"\"\n## We'll use Stratified KFold as cross validation\n\"\"\"\n# adding a kfold column\ndf = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ndf[\"kfold\"] = -1\ndf = df.sample(frac=1).reset_index(drop=True)\ny = df[\"Survived\"].values\nkf = model_selection.StratifiedKFold(n_splits=5)\n\nfor fold, (t, v) in enumerate(kf.split(X=df, y=y)):\n    df.loc[v, \"kfold\"] = fold\n\n# save the csv\ndf.to_csv(f\"titanic_folds.csv\", index=False)\ndf = pd.read_csv(\".\/titanic_folds.csv\")\ndf.head()\ndf.info()\n\"\"\"\n# Analysing features\n\n\"\"\"\n\"\"\"\n## 1. Passenger ID\n- is unique for every passenger\n- therefore, of no use\n\"\"\"\n\"\"\"\n## 2. Survived\n- target variable\n\"\"\"\ny = df[\"Survived\"].values\nprint(y.shape)\n\"\"\"\n## 3. Pclass\n\"\"\"\n# 216 + 184 + 491 = 891\n# Hence no null values\n# This feature will be considered\nprint(np.unique(df[\"Pclass\"], return_counts=True))\n\"\"\"\n## 4. Name\n- may be not as important\n- will not consider for now\n\"\"\"\n\"\"\"\n## 5. Sex\n\"\"\"\n# This feature will be considered\nprint(np.unique(df[\"Sex\"], return_counts = True))\nlbl = LabelEncoder()\ndf[\"Sex\"] = lbl.fit_transform(df[\"Sex\"])\ndf[(df[\"Survived\"] == 1)][\"Sex\"].hist(bins=10, edgecolor='white')\n\"\"\"\n## More Females survived than Males\n\"\"\"\n\"\"\"\n## 6. Age\n\"\"\"\ndf[(df[\"Survived\"] == 1)][\"Age\"].hist(bins=10, edgecolor='white')\nplt.show()\n\"\"\"\n### More Children survived\n\"\"\"\ndf[df[\"Survived\"] == 0][\"Age\"].hist(bins=10, edgecolor='white')\nplt.show()\n\"\"\"\n## 7. Sibsp\n\"\"\"\n# This feature will be considered\nprint(np.unique(df[\"SibSp\"], return_counts = True))\n\"\"\"\n## 8. Parch\n\"\"\"\n# This feature will be considered\nprint(np.unique(df[\"Parch\"], return_counts = True))\n\"\"\"\n## 9. Ticket\n- is (almost) unique for every passenger\n- ignored\n\"\"\"\n\"\"\"\n## 10. Fare\n\"\"\"\nplt.style.use('seaborn')\nplt.hist(df[\"Fare\"], bins=40, edgecolor='white')\nplt.show()\n\"\"\"\n## 11. Cabin\n\"\"\"\ncabin_dict = {}\n\nfor cbn in df[\"Cabin\"]:\n    \n    if cbn in cabin_dict:\n        cabin_dict[cbn] += 1\n        \n    else:\n        cabin_dict[cbn] = 1\n        \nprint(cabin_dict)\ncabin_df = pd.DataFrame(columns=[\"Cabin_name\", \"Count\"])\ncabin_df[\"Cabin_name\"] = cabin_dict.keys()\ncabin_df[\"Count\"] = cabin_dict.values()\n\ncabin_df.head()\ncabin_df.sort_values(by=\"Count\").reset_index(drop=True)\n\"\"\"\n### out of 891 passengers, 687 cabin names are unknown\/missing\n\"\"\"\ndf[df[\"Cabin\"].isnull()][\"Survived\"].value_counts()\ndf[df[\"Cabin\"].isnull() == False][\"Survived\"].value_counts()\ndf = pd.read_csv(\"..\/input\/titanic\/train.csv\").copy()\n# df.Cabin.fillna(\"NONE\")\ndf[\"Cabin\"] = df[\"Cabin\"].astype(str)\nfor i, cbn in enumerate(df[\"Cabin\"]):\n  \n    # if the passenger has a cabin assign A\n    if cbn != \"nan\":\n        df.loc[i, \"Cabin\"] = \"A\"\n        \n    else:\n        df.loc[i, \"Cabin\"] = \"NONE\"\ndf[\"Cabin\"]\ntemp = df.groupby(\n    [\n        \"Sex\",\n        \"Cabin\",\n        \"Survived\"\n    ]\n)[\"Survived\"].count().reset_index(name=\"Survived_count\")\ntemp.head(n=8)\n\"\"\"\n## Some Conclusions\n- Males without a Cabin didn't survive (mostly)\n- Females with a cabin have survived (mostly)\n\"\"\"\n\"\"\"\n## 12. Embarked\n\"\"\"\ndf.Embarked.fillna(\"NONE\")\nprint(df[df[\"Embarked\"].isnull()])\n\ndf[\"Embarked\"] = df[\"Embarked\"].astype(str)\n# Embarked is not a very informative feature I see\n# Gonna ignore it in the model initially\ndf.info()","meta":"{'source': 'AI4Code', 'id': 'e673978d0fd4ac'}"}
{"id":"120637","text":"# 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 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\n\"\"\"\nIn recent years, Deep Learning models and architectures have gained a lot of traction while dealing with image data, as well as, for providing solutions to NLP based problems. This has been a result of some excellent and ground breaking research work that we have seen over the years in the field of Deep Learning. On the other hand, traditional tree-based models like RandomForrest and XGBoost have maintained their stronghold and have proved to be really successful and efficient when dealing with Tabular (Structured) data, especially in regression problems.\nToday, we will be looking at an approach to apply Deep Learning on Tabular data in order to solve a regression problem using FastAi.\n\"\"\"\n!pip install fastai==1.0.61 --no-deps\n# fastai depends also on an older version of torch\n!pip install torch==1.6.0 torchvision==0.7.0\n\"\"\"\n### Problem Statement:\n\"\"\"\n\"\"\"\nFootball (Soccer) in the modern times has become much complicated, than it ever was. For clubs all around the world, it\u2019s not just about playing your heart out in the field, but also perform well in the transfer markets, to snap up the right talent and players for their sides, at the right price. Over the past few years we have observed a serious inflation in player values and some exuberant release clauses (price inserted in a player\u2019s contract with his\/her current club for which he\/she can be bought by another club).\nAs a result of this, a many clubs end up paying a lot more for a player whose talent and performances on the field fail to justify his\/her price tag. A similar problem is faced by the club selling a player, where they fail to realise his\/her potential, and let him\/her go for a price which was way less than the actual price they should have asked for.\nWe shall try to solve this as a regression problem using Deep Learning. We will be making use of the fast.ai\u2019s tabular module to predict a player\u2019s value based on his\/her skill and personality attributes.\n\n\"\"\"\n\"\"\"\n### Assumption\n\"\"\"\n\"\"\"\nThe target value (Price) for which we will train our model, could already consist of the bias of over\/under valuing the players. We will build our solution based on the assumption that these prices for the players are highly curated and based on the research and analysis of experts of this domain.\n\"\"\"\n\"\"\"\n### Solution:\n\"\"\"\nimport pandas as pd\nimport math\nimport datetime\nimport fastai\nfrom fastai.tabular import *\nfrom fastai.tabular.all import *\nfrom fastai.imports import *\nfrom fastai.metrics import error_rate\n# from fastai.callbacks import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import Normalizer, MinMaxScaler\nfastai.__version__\n??fastai.tabular.all\n\"\"\"\n#### Data\n\"\"\"\nplayers_df = pd.read_csv('\/kaggle\/input\/fifa-20-complete-player-dataset\/players_20.csv')\nplayers_df\n\"\"\"\n#### Data Pre-Processing\n\"\"\"\n\"\"\"\nFirstly, we will apply it to the value_eur column. We will change all the values with 0 to 1, so that we do not run into the \u201cDivision by 0\u201d problem later on.\nThe next one would be the loaned_from column, which we will use to create another one, loaned_status. Instead of blank values and the club names the player is loaned to, we will use Boolean values telling us whether the player is on loan to another club or not.\nLastly, we will use the column contract_valid_until to generate contract_expiry_in, so that we use can use the number of years left on a player\u2019s to assess his value.\n\"\"\"\nplayers_df['value_eur'] = players_df['value_eur'].apply(lambda x : 1 if x == 0 else x)\nlen(players_df['value_eur'])\nplayers_val = np.array(players_df[['value_eur']])\n# players_val = players_val.reshape(-1,1)\nval_eur_normalised = MinMaxScaler().fit_transform(players_val)\nval_eur_normalised[9989]\n\nplayers_df['value_eur'] = val_eur_normalised\nlen(players_df['value_eur'])\nplayers_df['loaned_status'] = players_df['loaned_from'].fillna('').apply(lambda x:'no' if x == '' else 'yes')\ncurr_year = 2019\nplayers_df['contart_expiry_in'] = players_df['contract_valid_until'].apply(lambda x : x-curr_year)\nplayers_df\n\"\"\"\nNext, we ought to perform some data pre-processing steps like filling missing data, categorizing and normalizing the columns. With the fast.ai library, this is rather easy, we specify the pre-processing methods in a list, and use it later at the time of creating our fast.ai DataBunch for training.\n\"\"\"\nprocs = [FillMissing, Categorify, Normalize]\n\"\"\"\n#### Building the DataBunch\n\n\"\"\"\n\"\"\"\nFirst, we\u2019ll put all categorical fields in a list cat_var, and all continuous fields in another list cont_var . These two variables will be used to construct the fast.ai DataBunch.\n\"\"\"\ncont_var = ['age','height_cm','weight_kg','overall','potential','wage_eur','international_reputation','weak_foot','skill_moves','release_clause_eur',\n            'pace','shooting','passing','dribbling','defending','physic','gk_diving','gk_handling','gk_kicking','gk_reflexes','gk_speed','gk_positioning',\n            'attacking_crossing','attacking_finishing','attacking_heading_accuracy','attacking_short_passing','attacking_volleys',\n            'skill_dribbling','skill_curve','skill_fk_accuracy','skill_long_passing','skill_ball_control','movement_acceleration','movement_sprint_speed',\n            'movement_agility','movement_reactions','movement_balance','power_shot_power','power_jumping','power_stamina','power_strength','power_long_shots',\n            'mentality_aggression','mentality_interceptions','mentality_positioning','mentality_vision','mentality_penalties','mentality_composure', \n            'defending_marking','defending_standing_tackle','defending_sliding_tackle','goalkeeping_diving','goalkeeping_handling','goalkeeping_kicking',\n            'goalkeeping_positioning','goalkeeping_reflexes','contart_expiry_in']\ncat_var = ['preferred_foot','work_rate','body_type','team_position','nation_position','loaned_status','player_traits']\n\"\"\"\nNext up, we specify the dependent variable and keep only the specified continuous and categorical variables.\n\"\"\"\ndep_var = 'value_eur'\nplayers_df = players_df[cat_var + cont_var + [dep_var]].copy()\nplayers_df\n\"\"\"\nAfter this, we will spit the data into training and test so that we have a test dataset for our trained model to assess its performance later on a data that it has never seen before. We split the data 80-20 here, and create a TabularList from it.\n\"\"\"\nplayers_df_train, players_df_test = train_test_split(players_df, test_size = 0.2, random_state = 0)\nplayers_df_train.shape,players_df_test.shape\n# Test tabularlist\ntest = TabularPandas(players_df_test, cat_names=cat_var, cont_names=cont_var, procs=procs)\nsplits = RandomSplitter(valid_pct=0.2)(range_of(players_df_train))\ndep_var\n# Train data bunch\nto = TabularPandas(players_df_train, procs=procs, cat_names=cat_var, cont_names=cont_var, y_names = dep_var, splits=splits)\n                                                \ndls = to.dataloaders(bs=64)\ndls.show_batch()\nlearn = tabular_learner(dls, layers=[200,100], metrics=rmse, ps=[0.001,0.01], emb_drop=0.01)\nlearn.model\n# select the appropriate learning rate\nlearn.lr_find()\n\n# we typically find the point where the slope is steepest\n# learn.recorder.before_fit()\n# Fit the model based on selected learning rate\nlearn.fit_one_cycle(10, 5e-2)","meta":"{'source': 'AI4Code', 'id': 'dde99c0c9557ca'}"}
{"id":"133802","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns # gera\u00e7\u00e3o de gr\u00e1ficos\n\n# Ignorar warnings\nimport warnings\nwarnings.filterwarnings('ignore')\ndf1 = pd.read_csv('..\/input\/breast-cancer-wisconsin-data\/data.csv')\ndf1.sample(10)\nfrom sklearn.preprocessing import LabelEncoder\ndiagnosis = LabelEncoder()\ndf1['diagnosis'] = diagnosis.fit_transform(df1['diagnosis']) \ndf1.head() # 0 = B; 1 = M \n\"\"\"\n**Split Train & Test**\n\"\"\"\ndf1.drop(columns =['id','Unnamed: 32'], axis=1, inplace=True)\ndf1.head()\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(df1.loc[:,df1.columns != 'diagnosis'],\n                                                    df1['diagnosis'],\n                                                    test_size=0.3)\n\"\"\"\n**Exploratory Data Analysis**\n\"\"\"\nx_train.head()\nprint(x_train.shape)\nprint(x_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\ndf_pivot = pd.DataFrame({'types': x_train.dtypes,\n                         'nulls': x_train.isna().sum(),\n                          '% nulls': x_train.isna().sum() \/ x_train.shape[0],\n                          'size': x_train.shape[0],\n                          'uniques': x_train.nunique()})\ndf_pivot\nfig, ax = plt.subplots(figsize=(12,7))\nsns.heatmap(x_train.corr(), vmin=-1, vmax=1,\n            cmap=sns.diverging_palette(20, 220, as_cmap=True), \n            yticklabels=True) # show all y values\n\nplt.show()\ndf1.corr()['diagnosis'].sort_values(ascending=False).head()\nplt.scatter(x_train['concave points_worst'], x_train['perimeter_worst'], c=y_train, cmap=plt.cm.Spectral)\nplt.colorbar()\nplt.xlabel('concave points_worst')\nplt.ylabel('perimeter_worst')\nplt.title('concave points_worst x perimeter_worst')\nplt.show()\n\nsns.boxplot(y=x_train['concave points_worst'], x=y_train)\nplt.show()\nsns.boxplot(y=x_train['perimeter_worst'], x=y_train)\nplt.show()\n# Positive Correlated\nplt.xlabel('area_se')\nplt.ylabel('radius_se')\nplt.scatter(x_train['area_se'], x_train['radius_se'])\nplt.show()\n\"\"\"\n**Normalize Data**\n\"\"\"\nfrom sklearn import preprocessing\npreprocessParams = preprocessing.StandardScaler().fit(x_train)\nx_train_normalized = preprocessParams.transform(x_train)\nx_test_normalized = preprocessParams.transform(x_test)\n\nx_train_normalized[:1] \n\"\"\"\n**Neural Networks Structure**\n\"\"\"\nfrom keras import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\nNumerOfClasses = len(y_train.unique())\nNumerOfClasses\nRN = Sequential() # create network structure\nRN.add(Dense(10, input_shape = x_train_normalized.shape[1:], activation ='sigmoid'))\nRN.add(Dense(NumerOfClasses, activation ='sigmoid'))\nRN.summary()\n# training\nfrom keras.utils import to_categorical\nsgd = SGD(lr=0.1, decay=1e-6, momentum=0.9)\nRN.compile(optimizer=sgd, loss='mean_squared_error', metrics=['accuracy'])\ntrainedRN = RN.fit(x_train_normalized, to_categorical(y_train), epochs=100, verbose=1)\nscore = RN.evaluate(x_test_normalized, to_categorical(y_test),verbose=0)\nprint('Test Score:', score[0])\nprint('Test Accuracy:', score[1])\n#Predict\nfrom sklearn.metrics import confusion_matrix\ny_test_predicted = RN.predict(x_test_normalized)\ny_test_predicted_index = np.argmax(y_test_predicted, axis=1)\ny_test_index = y_test.values\n#Confusion Matrix\nconfMatrix = pd.DataFrame(confusion_matrix(y_test_predicted_index, y_test_index),\n                           index=['0 - Benigno','1 - Maligno'],columns=['0 - Benigno','1 - Maligno'])\n\nconfMatrix.index.name = 'Actual'\nconfMatrix.columns.name= 'Predicted'\nprint(confMatrix)","meta":"{'source': 'AI4Code', 'id': 'f609cb07f1d570'}"}
{"id":"123363","text":"# linear algebra\nimport numpy as np \n\n# data processing\nimport pandas as pd \n\n# data visualization\nimport seaborn as sns\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\n# Algorithms\nfrom sklearn import linear_model\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom sklearn.metrics import accuracy_score\n!ls\n# getting the data\ntrain_df = pd.read_csv('..\/input\/train.csv')\ntest_df = pd.read_csv('..\/input\/test.csv')\ntrain_df.head()\n\"\"\"\n### EDA\n\"\"\"\ntrain_df.info()\ntrain_df.describe()\n\"\"\"\n* There are 891 passengers in the training set\n* The survival rate was 38%\n* Most of the passengers belonged to class 3\n* The maximum Fare paid for a ticket was 512 however the fare prices varied a lot as we can see from the standard deviation of 49\n\"\"\"\n# missing values in Age`\nsns.heatmap(train_df.isnull(),yticklabels=False,cbar=False,cmap='viridis')\n\"\"\"\nIf we look at the above heat map, every yellow dash is a true point, TRUE equals NULL.We are missing\n\n* Age Info\n* Lot of Cabin info\n\nWe need to fill with some reasonable imputation of values\n\n\"\"\"\nmissing = train_df.isnull().sum().sort_values(ascending=False)\ntotal = train_df.isnull().sum() \/ train_df.isnull().count() * 100\nfinal = round(total,1).sort_values(ascending=False)\nmissing_data = pd.concat([missing, final], axis=1, keys=['Total', '%'],sort=True).head(5)\nmissing_data\n\"\"\"\nThe Embarked feature has only 2 missing values, which can easily be filled. It will be much more tricky, to deal with the \u2018Age\u2019 feature, which has 177 missing values. The \u2018Cabin\u2019 feature needs further investigation, but it looks like that we might want to drop it from the dataset, since 77 % of it are missing\n\"\"\"\ntrain_df.columns.values\n\"\"\"\n## EDA - Visual Data Analysis\n\"\"\"\nsns.set_style('whitegrid')\nsns.countplot('Survived',data=train_df,hue='Sex',palette='RdBu_r')\nsns.countplot('Sex',data=train_df)\n\"\"\"\nThe number of males on board were clearly more than the female.\n\"\"\"\ntrain_df.groupby(by='Sex',as_index=False)['Survived'].mean()\nsns.barplot(x='Pclass',y='Survived',data=train_df)\nsns.countplot(x='Survived',hue='Pclass',data=train_df)\n\"\"\"\nLooks like people who did not survive is mostly from the **third** class and people did survive mainly from the higher class\n\"\"\"\ntrain_df.groupby('Pclass',as_index=False)['Survived'].mean().sort_values(by='Survived',ascending=False)\n\"\"\"\nPassenger in `Pclass` 3 have lower chances of survival.Clearly Class had an effect on survival of each passenger with the percentages of survival being 62.96%, 47.28%, 24.23% for Pclass 1, 2 and 3 respectively. Thus, belonging to Pclass = 1 had a huge advantage.\n\"\"\"\n#Comparing the Embarked feature against Survived\nsns.barplot(x='Embarked',y='Survived',data=train_df)\ntrain_df[['Embarked','Survived']].groupby('Embarked',as_index=False).mean().sort_values(by='Survived'\n                                                                                        ,ascending=False)\nFacetGrid = sns.FacetGrid(train_df, row='Embarked', size=4.5, aspect=1.6)\nFacetGrid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette=None,  order=None, hue_order=None )\nFacetGrid.add_legend()\n\"\"\"\nEmbarked seems to be correlated with survival, depending on the gender.\n\nWomen on port Q and on port S have a higher chance of survival. The inverse is true, if they are at port C. Men have a high survival probability if they are on port C, but a low probability if they are on port Q or S\n\"\"\"\n\"\"\"\nIt seems that the passengers that embarked from port Cherbourg had a higher rate of Survival at 55%. This could be either due to their Sex or socio-economic class.\n\"\"\"\nsns.barplot(x='Parch',y='Survived',data=train_df)\n\"\"\"\nLooks like passengers who had either 1, 2 or 3 had a higher possibility of surviving than the ones had none. However having more than 3 made the possibility even lesser.\n\"\"\"\nsns.barplot(x='SibSp',y='Survived',data=train_df)\n\"\"\"\nIt seems that having a spouse or 1 sibling had a positive effect on Survival as compared to being alone. Though the chances of survival go down with the number of siblings after 1.\n\"\"\"\ntrain_df.Age.hist(bins=20)\nplt.xlabel('Age')\nplt.ylabel('Count')\n\"\"\"\nIt is obvious to assume that younger individuals were more likely to survive, however we should test our assumption before we proceed.\n\"\"\"\nsns.lmplot(x='Age',y='Survived',data=train_df,palette='Set1')\nsns.lmplot(x='Age',y='Survived',data=train_df,palette='Set1',hue='Sex')\n\"\"\"\nInterestingly, age has an opposite effect on the survival in men and women. The chances of survival increase as the age of women increases.\n\nTakeaway: Age feature can have a different effect on the outcome depending on the sex of the passenger. Perhaps we can use this information in feature engineering\n\"\"\"\nsns.distplot(train_df['Age'].dropna())\n#Checking for outliers in Age data\nsns.boxplot(x='Sex',y='Age',data=train_df)\n\n#getting the median age according to Sex\ntrain_df.groupby('Sex',as_index=False)['Age'].median()\nsns.countplot(x='Sex',data=train_df)\nsns.countplot(x='Survived',hue='Sex',data=train_df)\ntrain_df.describe(include='O')\n\nwomen = train_df[train_df['Sex']=='female']\nmen = train_df[train_df['Sex']=='male']\nfig,axes = plt.subplots(nrows=1,ncols=2,figsize=(10,4))\nax = sns.distplot(women[women['Survived'] == 1].Age.dropna(),label='Survived',bins=20,ax=axes[0],kde=False)\nax = sns.distplot(women[women['Survived'] == 0].Age.dropna(),label='Not Survived',bins=40,ax=axes[0],kde=False)\nax.set_title('Female')\nax.legend()\nax = sns.distplot(men[men['Survived'] == 1].Age.dropna(),label='Survived',bins=20,ax=axes[1],kde=False)\nax = sns.distplot(men[men['Survived'] == 0].Age.dropna(),label='Not Survived',bins=40,ax=axes[1],kde=False)\nax.set_title('Male')\nax.legend()\n\"\"\"\nFemales between `Age` of 15 and 40 had high chances of survival. Also we can notice that females infants\/toddlers also had a higher chance of survival. This may be because females have given preference while embarking. \n\nWhile Males between `Age` of 20 and 35 had higher chances of survival. This is almost same as women\n\"\"\"\n\"\"\"\nPeople who travelled in first class had higher chances of survival ( they were housed in upper decks of the ship ). \n\"\"\"\ng = sns.FacetGrid(data=train_df,col='Survived',row='Pclass')\ng.map(plt.hist,'Age',alpha=.5, bins=20)\ng.add_legend()\ntrain_df.Embarked.value_counts()\nsns.barplot(x='Embarked',y='Survived',data=train_df)\nsns.countplot('SibSp',data=train_df)\n\"\"\"\nThe above graph tells, most of the people were single\n\"\"\"\ntrain_df['Fare'].hist(bins=40,figsize=(10,4))\n\"\"\"\nMost of the purchase price are between 0 and 50. It makes sense on the cheaper fares when comparing to the third class passengers\n\"\"\"\nimport cufflinks as cf\ncf.go_offline()\ntrain_df['Fare'].iplot(kind='hist',bins=40)\nplt.figure(figsize=(10,4))\nsns.boxplot(x='Pclass',y='Age',data=train_df)\n\"\"\"\nFrom the above graph , when we seperate by class, the wealthier passengers in the first class and second tend to be more older than the third class. This makes sense, becuase it takes time to save your money and create wealth\n\"\"\"\ntrain_df.Embarked.describe()\n\"\"\"\n### Data Pre-processing\n\"\"\"\ntrain_df = train_df.drop(['PassengerId'],axis=1)\ntrain_df.columns\ntest_passenger_id = pd.DataFrame(test_df.PassengerId)\ntest_passenger_id.head()\ntest_df=test_df.drop(['PassengerId'],axis=1)\n\"\"\"\n## Missing data - Cabin\n\"\"\"\n\"\"\"\nWe have 687 records missing in `Cabin` category, which is almost 77% of the data. Looks like we can drop those\n\"\"\"\ntrain_df = train_df.drop(['Cabin'], axis=1)\ntest_df = test_df.drop(['Cabin'], axis=1)\n\"\"\"\n#### Age\n\"\"\"\ntrain_df.Age.median()\ntrain_df.Age.fillna(train_df.Age.median(),inplace=True)\ntrain_df.Age.isnull().sum()\ntest_df.Age.fillna(test_df.Age.median(),inplace=True)\ndata = [train_df, test_df] # turning into list and adding 'relatives' column to dataframe\nfor dataset in data:\n    dataset['relatives'] = dataset['SibSp'] + dataset['Parch']\n    dataset[\"IsAlone\"] = np.where(dataset[\"relatives\"] > 0, 0,1)\ntrain_df['IsAlone'].value_counts()    \n#dropping the Name,SibSP and Parch columns\nfor dataset in data:\n    dataset.drop(['SibSp','Parch'],axis=1,inplace=True)\ntrain_df.info()\n\"\"\"\nLet's check the heat map again\n\"\"\"\nsns.heatmap(train_df.isnull(),yticklabels=False,cbar=False,cmap='viridis')\n\"\"\"\nNo missing values, we have treated all\n\"\"\"\n\"\"\"\n### Embark data\n\"\"\"\ntop_value = 'S'\ndata = [train_df,test_df]\nfor dataset in data:\n    dataset['Embarked'] = dataset['Embarked'].fillna(top_value)\n\"\"\"\n### Converting Features:\n\"\"\"\ntrain_df.info()\n\"\"\"\n`Fare` is a float and we have to deal with 4 categorical features: `Name, Sex, Ticket` and `Embarked`\n\"\"\"\n### Fare\ndata = [train_df, test_df]\n\nfor dataset in data:\n    dataset['Fare'] = dataset['Fare'].fillna(0)\n    dataset['Fare'] = dataset['Fare'].astype(int)\ndata = [train_df,test_df]\ntitles = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}\nfor dataset in data:\n    # extract titles\n    dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\\.',expand=False)\n    # replace titles with a more common title or as Rare\n    dataset['Title'] = dataset['Title'].replace(['Lady','Countess','Capt', 'Col','Don', 'Dr','Major', 'Rev', 'Sir',\n                                                 'Jonkheer', 'Dona'], 'Rare')\n    dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')\n    dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')\n    dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')\n    # convert titles into numbers\n    dataset['Title'] = dataset['Title'].map(titles)\n    # filling NaN with 0, to get safe\n    dataset['Title'] = dataset['Title'].fillna(0)\ntrain_df = train_df.drop(['Name'], axis=1)\ntest_df = test_df.drop(['Name'], axis=1)\nsns.barplot(x='Title',y='Survived',data=train_df,)\n\"\"\"\nThe above plot shows the survival chance of women is higher, followed by infants\/kids\n\"\"\"\n\"\"\"\n### Sex:\n\"\"\"\ngender = {'male':0,'female':1}\ndata = [train_df, test_df]\nfor dataset in data:\n    dataset['Sex'] = dataset['Sex'].map(gender)\n\"\"\"\n### Dropping ticket \n\"\"\"\ntrain_df = train_df.drop(['Ticket'], axis=1)\ntest_df = test_df.drop(['Ticket'], axis=1)\n\"\"\"\n### Embarked:\n\"\"\"\ntrain_df['Embarked'].value_counts()\nports = {'S':0,'C':1,'Q':77}\ndata = [train_df, test_df]\nfor dataset in data:\n    dataset['Embarked'] = dataset['Embarked'].map(ports)\n\"\"\"\n#### Dropping Cabin:\n\"\"\"\n## Converting Age from float to integer\ntrain_df['Age'] = train_df['Age'].astype(int)\n\"\"\"\nAge and Fare columns have continuous data and there might be fluctuations that do not reflect patterns in the data, which might be noise. Categorizing every age into a group. \n\"\"\"\ntrain_df['AgeGroup'] = pd.qcut(train_df.Age,6,labels=False)\ntest_df['AgeGroup'] = pd.qcut(test_df.Age,6,labels=False)\ntrain_df['Fare'] = pd.qcut(train_df.Fare,5,labels=False)\ntest_df['Fare'] = pd.qcut(test_df.Fare,5,labels=False)\ntrain_df.head(5)\n\"\"\"\n### Building Models\n\n#### 1. Logistic Regression\n\"\"\"\n#Splitting out training data into X: features and y: target\nX = train_df.drop(\"Survived\", axis=1)\ny = train_df[\"Survived\"]\n#splitting our training data again in train and test data\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,random_state=123)\nlogreg = LogisticRegression()\nlogreg.fit(X_train,y_train)\ny_pred = logreg.predict(X_test)\nacc_logreg = round(accuracy_score(y_pred,y_test)*100,2)\ncv_scores = cross_val_score(logreg,X,y,cv=5)\nnp.mean(cv_scores)*100\n\"\"\"\nAge plays has importance in Randomn Forest algorithm. **Is Alone** can be dropped it seems\n\"\"\"\n\"\"\"\n#### 2. Random Forest\n    \n\"\"\"\nrf = RandomForestClassifier(n_estimators=100)\nrf.fit(X_train,y_train)\naccu_rf = rf.score(X_train,y_train)\naccu_rf = round(accu_rf*100,2)\naccu_rf\n# Displaying the important features\nimp_features = pd.DataFrame({'feature':X_train.columns,'importance':np.round(rf.feature_importances_,3)})\nimp_features = imp_features.sort_values('importance',ascending=False).set_index('feature')\nimp_features.head(10)\nimp_features.plot.bar()\n\"\"\"\n### 3. Decision Tree\n\"\"\"\ndt = DecisionTreeClassifier()\ndt.fit(X_train,y_train)\naccu_dt = dt.score(X_train,y_train)\naccu_dt = round(accu_dt*100,2)\naccu_dt\n\"\"\"\n#### 4. KNN\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors=3)\nknn.fit(X_train,y_train)\naccu_knn = knn.score(X_train,y_train)\naccu_knn = round(accu_knn*100,2)\naccu_knn\n\"\"\"\n#### 5. Gaussian NB\n\"\"\"\nnb = GaussianNB()\nnb.fit(X_train,y_train)\naccu_nb = nb.score(X_train,y_train)\naccu_nb = round(accu_nb*100,2)\naccu_nb\nresults = pd.DataFrame({\n    'Model':['Linear Reg.','Random Forest','Decision Trees','K-Nearest Neighbours','Naive Bayes'],\n    'Accuracy':[acc_logreg,accu_rf,accu_dt,accu_knn,accu_nb]\n})\nresults.sort_values(by='Accuracy',ascending=False)\ny_final = rf.predict(test_df)\nsubmission = pd.DataFrame({\n    'PassengerId': test_passenger_id['PassengerId'],\n    'Survived': y_final\n})\nsubmission.head()\nsubmission.to_csv('titanic_rf.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'e2d18a3f4aafaa'}"}
{"id":"130445","text":"\"\"\"\n# \ud0c0\uc288 \ub370\uc774\ud130 \ubd84\uc11d\n\"\"\"\n%matplotlib inline\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport matplotlib.image\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\npd.__version__\n\"\"\"\n## Open data with  csv file\n\"\"\"\nrent = pd.read_csv('..\/input\/tashu-taejon-shared-bike-data\/2013_01.csv', parse_dates=[2,4])\nrent.dtypes\nrent.describe()\nrent.head()\n# NaN \uc140\uc744 0\uc73c\ub85c \ubc14\uafb8\uae30\nrent['rent_station'] = rent.rent_station.fillna(0)\nrent['return_station'] = rent.return_station.fillna(0)\nrent.head()\n# float \ub97c int\ub85c \ubc14\uafb8\uae30\nrent['rent_station']=rent.rent_station.astype(int)\nrent.head()\nrent['return_station']=rent.return_station.astype(int)\nrent.head()\nrent.dtypes\n\"\"\"\n### \ub300\uc5ec \uc2dc\uac04 \uacc4\uc0b0\ud558\uae30\n\"\"\"\nrent['sub'] = rent.return_date - rent.rent_date\nrent['sub'].astype('timedelta64[s]')\nrent[:10]\nts = pd.Series(1, rent['rent_date'])\nts[:10]\n#hourly_ts = ts.resample('H').count()\nhourly_ts = ts.groupby(ts.index.hour).sum()\nhourly_ts.head()\nplt.title('Hourly Usage')\nhourly_ts.plot()\nplt.show()\ndaily_ts = ts.resample('D').count()\ndaily_ts[:10]\nmonthly_ts = ts.resample('M').count()\nmonthly_ts[:10]\nplt.title('Daily Usage')\ndaily_ts.plot()\nplt.show()\nplt.title('Monthly Usage')\nmonthly_ts.plot()\n\"\"\"\n## weekly stat\n\"\"\"\nrent['weekday'] = pd.DatetimeIndex(rent['rent_date']).weekday\nrent[:10]\nrent_weekday = rent.groupby('weekday').rent_station.count()\nrent_weekday\ndate_number = [0,1,2,3,4,5,6]\ndate_labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\nplt.title('Day of  Week Rentals')\n#rent_weekday.plot()\nrent_weekday.plot(kind='bar', \n                  color=['r', 'g', 'b', 'k', 'y', 'm', 'c']); \n                  \n#plt.axhline(y=0, color='k')\nplt.xticks(date_number, date_labels, rotation=45)\n#plt.hist(rent_weekday)\nplt.show()\nfrom numpy import *\nrent[:10]\nrent['hour'] = rent['rent_date'].dt.hour\nrent.head()\nrent['count'] = 1\nweekly_hourly = rent.groupby(['weekday', 'hour']).size().unstack()\nweekly_hourly\nweekly_hourly.fillna(0, inplace=True)\nweekly_hourly\nweekly_hourly = weekly_hourly.astype(int)\nweekly_hourly\nheatmap_hr = np.zeros([7,24])\nimport seaborn as sns\nhm = sns.heatmap(weekly_hourly, cmap=\"YlGnBu\")\n\"\"\"\n## Top 10 stations ?\n\"\"\"\nrent_station_cnt = rent.groupby('rent_station').rent_station.count()\nrent_station_cnt[:10]\nrent_station_cnt.sort_values(inplace=True, ascending=False)\ntop10 = rent_station_cnt[:10]\ntop10\nimport pandas as pd\nstation_df = pd.read_csv(r'..\/input\/tashu-taejon-shared-bike-data\/station_utf8.csv')\nstation_df.head(5)\ntop10\ntop10.index\ntop10.dtypes\ntop10_df = top10.to_frame()\ntop10_df\ntop10_df.rename(columns={\"rent_station\":\"count\"}, inplace=True)\ntop10_df\ntop10_df[\"no\"] = top10_df.index\ntop10_df\ntop10_df.rename(columns={\"station_no\":\"no\"}, inplace=True)\ntop10_df\nstation_df.head()\ntop10_merge_df = pd.merge(left=top10_df, right=station_df, how=\"inner\", on=\"no\")\ntop10_merge_df\nimport folium\n \nm = folium.Map(location=[36.369855, 127.388749],\n               zoom_start=12)\nm\n#import folium\n%matplotlib inline\nlocationlist = list(zip(top10_merge_df[\"lat\"], top10_merge_df[\"lon\"]))\nlocationlist\nm = folium.Map(location=locationlist[0],\n               zoom_start=13)\nfor i in range(10):\n    folium.Marker(locationlist[i], popup=locationlist[i]).add_to(m)\nm","meta":"{'source': 'AI4Code', 'id': 'efdfe990344aba'}"}
{"id":"41527","text":"# 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)\nimport nltk\nimport matplotlib.pyplot as plt\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\ntrain=pd.read_csv('\/kaggle\/input\/twitter-sentiment-analysis-hatred-speech\/train.csv')\ntest=pd.read_csv('\/kaggle\/input\/twitter-sentiment-analysis-hatred-speech\/test.csv')\ntrain.head()\nlabels=train['label']\ntrain=train.drop('label',axis=1)\nlabels\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\"\"\"\n# USING SENTIMENT INTENSITY ANALYZER FROM NLTK\n SentimentIntensityAnalyzer is a pretrained model which will be used to analyze the sentiment of a sentence.\n\"\"\"\nmodel=SentimentIntensityAnalyzer()\nsentiment=[]\nfor i in range(len(test)):\n    prob=model.polarity_scores(train['tweet'][i])\n    if(prob['pos']>prob['neu'] and prob['pos']>prob['neg']):\n        sentiment.append('Positive')\n    elif(prob['neg']>prob['pos'] and prob['neg']>prob['neu']):\n        sentiment.append('Negative')\n    else:\n        sentiment.append('Neutral')\nprint(sentiment)","meta":"{'source': 'AI4Code', 'id': '4c8c2aafd45488'}"}
{"id":"57056","text":"# 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\n\"\"\"\n# **Indian Premier League (2008-2019) Exploratory Data Analysis**\n\"\"\"\nfrom IPython.display import Image\nimport os\n!ls ..\/input\/\nImage(\"..\/input\/ipljpg\/ipl.jpg\")\n\"\"\"\n****Importing required libraries****\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport seaborn as sns\n%matplotlib inline\n\"\"\"\n**Datasets Description**\n\"\"\"\n\"\"\"\nThe dataset d_matches consists of data from the Season 2008 to 2019 that gives information regarding the location,matches played between various teams and the winners in each match and much more.The dataset d_deliveries further talks about which team will be batting and bowling, along with which player was batting or bowling in each inning.The dataset d_teams tells us the names of different teams that play in IPL.And finally the dataset d_team_hna talks about the matches held in home city and away and gives an eloborate detail of the same.\n\"\"\"\n\"\"\"\n**Loading Datasets**\n\"\"\"\nd_matches=pd.read_csv('..\/input\/ipl-dataset\/matches.csv')\nd_deliveries=pd.read_csv('..\/input\/ipl-dataset\/deliveries.csv')\nd_teams=pd.read_csv('..\/input\/ipl-dataset\/teams.csv')\nd_team_hna=pd.read_csv('..\/input\/ipl-dataset\/teamwise_home_and_away.csv')\nd_matches.head()\nd_deliveries.head()\nd_teams\nd_team_hna\n\"\"\"\n**Data Cleaning**\n\"\"\"\n\"\"\"\n> Checking For Nan values in each dataset\n\"\"\"\n(d_matches.isna().sum()\/len(d_matches))*100\nd_matches.drop(labels='umpire3',axis=1,inplace=True)\nd_matches[d_matches.city.isnull()]\n\"\"\"\n> Replacing Nan values from city column after comparison with venue column\n\"\"\"\nd_matches.loc[d_matches.venue=='Dubai International Cricket Stadium']\nd_matches.city.fillna('Dubai',inplace=True) \nd_matches.dropna(axis=0,subset=['winner','player_of_match'],inplace=True)\nd_matches.dropna(axis=0,subset=['umpire1','umpire2'],inplace=True)\n(d_deliveries.isna().sum()\/len(d_deliveries))*100\nd_deliveries.drop(axis=1,columns=['player_dismissed','dismissal_kind','fielder'])\n(d_teams.isnull().sum()\/len(d_teams))*100\n(d_team_hna.isnull().sum()\/len(d_team_hna))*100\n\"\"\"\n**Data Analysis**\n\"\"\"\n\"\"\"\n> 1. Number of matches in respective locations\n\"\"\"\npx.bar(d_matches.groupby(by='city')[['date']].count(),text='value',color_discrete_sequence= ['cornflowerblue'],labels={'value':'No.of days'},title='No.of matches played in each city')\n\"\"\"\n> 2. Wins by Respective Teams after winning the toss\n\"\"\"\nd_matches.toss_winner==d_matches.winner\ndf=d_matches[(d_matches.toss_winner==d_matches.winner)].groupby('winner')[['toss_winner']].count().sort_values('toss_winner')\npx.line(df,x=df.index,y=df.toss_winner.values,color_discrete_sequence=['blue'],labels={'winner':'teams','y':'Matches won'},title='Matches won by teams after winning the toss')\n\"\"\"\n> 3. Wins procured by teams in their home city\n\"\"\"\npx.pie(d_team_hna,names='team',values='home_wins',color_discrete_sequence=px.colors.sequential.Plasma_r,title='Percentage of home wins')\n\"\"\"\n> 4. Comparison between home wins and away wins by each team\n\"\"\"\npx.line(d_team_hna.groupby('team')[['home_wins','away_wins']].sum(),color_discrete_sequence=['green','red'],labels={'value':'No. of wins'},title='Comparison of wins')\n\"\"\"\n> 5. Number of wins by each team in the 2019 season\n\"\"\"\nd=d_matches.loc[d_matches.season==2019].groupby('winner')[['winner']].count()\nx=d.index\ny=d.winner.values\nf1=px.bar(data_frame=d,x=d.index,y=d.winner.values,color_discrete_sequence=['maroon'],labels={'index':'teams','y':'No.of wins'},title='Wins by each team in 2019')\nf1.show()\n\"\"\"\n> 6. Comparing the distribution of wins by runs and wins by wickets\n\"\"\"\nd=d_matches.pivot_table(index=['winner'],values=['win_by_runs','win_by_wickets'],aggfunc=sum)\nd.plot(kind='box',figsize=(30,10))\nplt.title('Comaprison of wins by runs and wins by wickets')\nplt.show()\n\"\"\"\n> 7. Comaparing the number of matches held in home city and away\n\"\"\"\ndf=pd.pivot_table(data=d_team_hna,values=['home_matches','away_matches'],index='team',aggfunc='sum').sort_values(by=['home_matches','away_matches'])\nfig = make_subplots(rows=1, cols=2)\n\nfig.add_trace(go.Scatter(x=df.index, y=df.home_matches.values,name='Home Matches'),\n    row=1, col=1)\n\nfig.add_trace(\n    go.Scatter(x=df.index, y=df.away_matches.values,name='Away Matches'),\n    row=1, col=2)\n\nfig.update_layout(height=600, width=800, title_text=\"Comparison of matches played in home city and away\")\nfig.show()\n\"\"\"\n# Observations\n\"\"\"\n\"\"\"\n1.The number of matches held in Mumbai city is the highest followed by Kolkata and Delhi.The number of matches held in each city between 2008 to 2019 can be observed.\n\n2.The number of matches won by each team after winning the toss can be found.In the dataset Chennai Super Kings has won the highest number of matches after winning the toss.\n\n3.Mumbai Indians has had the most number of wins in their home city.Similarly this information the number of matches won by each team in their home city can be observed.\n\n4.Also it is possible to compare the number of wins at home city and away for each team.\n\n5.In the Season IPL-2019 Mumbai Indians procured the most number of wins in matches held followed by Chennai Super Kings.\n\n6.We can find the distribution of wins by runs and wins by wickets throughout the Seasons 2008 to 2019.\n\n7.Comparing the number of matches played by each team in their home city and away using subplots.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6946c24f7903bd'}"}
{"id":"45708","text":"\"\"\"\n## Introduction\n* Predict orthopedic disease with KNN algorithm (3 class labels) :\n  * Normal , Hernia , Spondylolisthesis\n* Calculate reliability -- Accuracy\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\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\n# read dataset\ndata = pd.read_csv('\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_3C_weka.csv')\ndata.tail()\ndata.info()\ndata.describe()\n# green: Normal , red: Hernia , purple: Spondylolisthesis\n\ncolor_list = ['red' if i=='Hernia' else ('purple' if i=='Spondylolisthesis' else 'green' ) for i in data.loc[:,'class']]\npd.plotting.scatter_matrix(data.loc[:, data.columns != 'class'],\n                                       c=color_list,# c - color\n                                       figsize= [15,15],# figure size\n                                       diagonal='hist',# histohram of each features\n                                       alpha=0.5,# opacity\n                                       s = 150, # size of marker\n                                       marker = 'o',# marker type\n                                       edgecolor= \"black\")\nplt.show()\ndata['class'].value_counts()\n# split dataset\nx,y= data.iloc[:,: -1], data.iloc[:,-1]\n# train test split\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test= train_test_split(x,y,test_size=0.2,random_state=1)\n# import KNN algorithm\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors = 3)\n# fit and predict dataset\nknn.fit(x_train,y_train)\npred = knn.predict(x_test)\n# print accuracy\nprint('With KNN (K=3) accuracy is: ',knn.score(x_test,y_test))\n# find best parameter\nneighbor = np.arange(1,25)\ntrain_accuracy = []\ntest_accuracy = []\n\nfor i,k in enumerate(neighbor):\n    knn = KNeighborsClassifier(n_neighbors=k)\n    knn.fit(x_train,y_train)\n    train_accuracy.append(knn.score(x_train, y_train))\n    test_accuracy.append(knn.score(x_test, y_test))\n\n# Plot\nplt.figure(figsize=[13,8])\nplt.plot(neighbor, test_accuracy, label = 'Testing Accuracy')\nplt.plot(neighbor, train_accuracy, label = 'Training Accuracy')\nplt.legend()\nplt.xlabel('Number of Neighbors')\nplt.ylabel('Accuracy')\nplt.xticks(neighbor)\nplt.savefig('graph.png')\nplt.show()\n\nprint(\"Best accuracy is {} with K = {}\".format(np.max(test_accuracy),1+test_accuracy.index(np.max(test_accuracy))))\n\"\"\"\n## Conclusion\n* Accuracy : 0.8387096774193549\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5433c2b4ec423a'}"}
{"id":"48467","text":"\"\"\"\n# TMDB Movies Recommendation System \n\nHere [The Movies Dataset](https:\/\/www.kaggle.com\/rounakbanik\/the-movies-dataset) by [Rounak Banik](https:\/\/www.kaggle.com\/rounakbanik) and [TMDB 5000 Movie Dataset](https:\/\/www.kaggle.com\/tmdb\/tmdb-movie-metadata) datasets are used to build `demographic based`, `content based` and `collaborative filtering based` recommendation systems.\n\n> **Understanding theses recommendation systems**\n>\n> - **`Demographic Filtering`** - They offer `generalized recommendations` to every user, based on movie popularity and\/or genre. The System recommends the same movies to users with `similar demographic features`. Since each user is different, this approach is considered to be too simple. The basic idea behind this system is that movies that are more popular and critically acclaimed will have a higher probability of being liked by the average audience.\n>\n> - **`Content Based Filtering`** - They suggest similar items based on a particular item. This system uses item metadata, such as genre, director, description, actors, etc. for movies, to make these recommendations. The general idea behind these recommender systems is that if a person liked a particular item, he or she will also like an item that is similar to it.\n>\n> - **`Collaborative Filtering`** - This system matches persons with similar interests and provides recommendations based on this matching. Collaborative filters do not require item metadata like its content-based counterparts.\n\n![](https:\/\/media.giphy.com\/media\/SJkvVMzUIjNngDL4gY\/giphy.gif)\n\"\"\"\nfrom ast import literal_eval\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\nfrom surprise import SVD, Dataset, Reader\nfrom surprise.model_selection import cross_validate\n# Pandas config\ndef pandas_config():\n    # display 10 rows and all the columns\n    pd.set_option('display.max_rows', 10)\n    pd.set_option('display.max_columns', None)\n\n    \npandas_config()\n# Loading the dataset\ncredits_df = pd.read_csv('..\/input\/tmdb-movie-metadata\/tmdb_5000_credits.csv')\nmovies_df = pd.read_csv('..\/input\/tmdb-movie-metadata\/tmdb_5000_movies.csv')\ncredits_df.head()\nmovies_df.head()\n\"\"\"\nThe `credits_df` contains the following features:-\n\n* movie_id - A unique identifier for each movie.\n* cast - The name of lead and supporting actors.\n* crew - The name of Director, Editor, Composer, Writer etc.\n\nThe `movies_df` has the following features:- \n\n* budget - The budget in which the movie was made.\n* genre - The genre of the movie, Action, Comedy ,Thriller etc.\n* homepage - A link to the homepage of the movie.\n* id - This is infact the movie_id as in the first dataset.\n* keywords - The keywords or tags related to the movie.\n* original_language - The language in which the movie was made.\n* original_title - The title of the movie before translation or adaptation.\n* overview - A brief description of the movie.\n* popularity - A numeric quantity specifying the movie popularity.\n* production_companies - The production house of the movie.\n* production_countries - The country in which it was produced.\n* release_date - The date on which it was released.\n* revenue - The worldwide revenue generated by the movie.\n* runtime - The running time of the movie in minutes.\n* status - \"Released\" or \"Rumored\".\n* tagline - Movie's tagline.\n* title - Title of the movie.\n* vote_average -  average ratings the movie recieved.\n* vote_count - the count of votes recieved.\n\"\"\"\n# Chaning column name from movie_id to id\n\nprint(f'Previous column names {credits_df.columns.tolist()}')\ncredits_df.columns = ['id', 'title', 'cast', 'crew']\nprint(f'Current column names {credits_df.columns.tolist()}')\n# Merging credits_df with movies_df on id\ndf = movies_df.merge(credits_df, on='id')\ndf.head()\n# Here we will have `title_x` & `title_y` which will be identical since movies \n# are same, so dropping any one of them & chaning the name of the other to `title`\n\ndf.drop(['title_x'], axis='columns', inplace=True)\ncolumns = df.columns.tolist()\ncolumns[columns.index('title_y')] = 'title'\ndf.columns = columns\ndf.head()\n\"\"\"\n## Demographic Filtering\n\n![](https:\/\/media.giphy.com\/media\/fzZzoftMBR8is\/giphy.gif)\n\nBefore getting started with this \n* We need a `metric` to score or rate movie \n* Calculate the score for every movie \n* Sort the scores and recommend the best rated movie to the users.\n\nWe can use the average ratings of the movie as the score but using this won't be fair enough since a movie with 8.9 average rating and only 3 votes cannot be considered better than the movie with 7.8 as as average rating but 40 votes. \n\nSo, I'll be using `IMDB's weighted rating (wr)` which is given as :-\n![](https:\/\/image.ibb.co\/jYWZp9\/wr.png)\n\nwhere,\n* v is the number of `votes for the movie`\n* m is the `minimum votes` required to be listed in the chart\n* R is the `average rating` of the movie\n* C is the `mean vote` across the whole report\n\nWe already have `v (vote_count)` and `R (vote_average)` and C can be calculated as \n\"\"\"\n# Mean vote(rating) across the report\nC = df.vote_average.mean()\nC\n\"\"\"\nSo, the mean rating for all the movies is approx 6 on a scale of 10.\n\nThe next step is to determine an appropriate value for m, the minimum votes required to be listed in the chart. We will use `90th percentile` as our cutoff. In other words, for a movie to feature in the charts, it must have more votes than at least 90% of the movies in the list.\n\nA `quantile` defines a particular part of a data set, i.e. a quantile determines how many values in a distribution are above or below a certain limit. Special quantiles are the `quartile (quarter)`, the `quintile (fifth)` and `percentiles (hundredth)`.\n\"\"\"\n# Minimum votes required to be listed in the chart\nm = df.vote_count.quantile(0.9)\nm\n# Filtering out the movies that qualify for the chart\nqualified_movies = df.copy().loc[df.vote_count >= m]\n\nprint(qualified_movies.shape)\nqualified_movies.sample(5)\n\"\"\"\nWe see that there are 481 movies which qualify to be in this list. Now, we need to calculate our metric for each qualified movie. To do this, we will define a function, **`weighted_rating()`** and define a new feature **`score`**, of which we'll calculate the value by applying this function to our DataFrame of qualified movies\n\"\"\"\ndef weighted_rating(df_row, m=m, C=C):\n    v = df_row.vote_count\n    R = df_row.vote_average\n\n    # Calculation based on the IMDB formula\n    return (v \/ (v + m) * R) + (m \/ (m + v) * C)\n# Define a new feature 'score' and calculate its value with `weighted_rating()`\nqualified_movies['score'] = qualified_movies.apply(weighted_rating, axis='columns')\nqualified_movies.score[:10]\n# Sort movies based on score calculated above\nqualified_movies = qualified_movies.sort_values('score', ascending=False)\n# Get top 15 movies\nqualified_movies[['title', 'vote_count', 'vote_average', 'score']].head(15)\n\"\"\"\n## Content Based Filtering\n\nIn this recommender system the `content` of the movie (overview, cast, crew, keyword, tagline etc) `is used to find its similarity` with other movies. Then the movies that are most likely to be similar are recommended.\n\n![](https:\/\/image.ibb.co\/f6mDXU\/conten.png)\n\"\"\"\n\"\"\"\n### Plot description based Recommender\n\nWe will compute pairwise similarity scores for all movies based on their plot descriptions and recommend movies based on that `similarity score`. The plot description is given in the `overview` feature of our dataset.\n\"\"\"\ndf.overview[:5]\n\"\"\"\nFor any of you who has done even a  bit of text processing before knows we need to convert the `word vector of each overview`. Now we'll compute `Term Frequency-Inverse Document Frequency (TF-IDF)` vectors for each overview.\n\nNow if you are wondering what is term frequency, it is the `relative frequency of a word in a document and is given as (term instances \/ total instances)`. `Inverse Document Frequency` is the relative count of documents containing the term is given as `log(number of documents\/documents with term)`. The overall importance of each word to the documents in which they appear is equal to **`TF * IDF`**.\n\nThis will give you a matrix where each column represents a word in the overview vocabulary (all the words that appear in at least one document) and each row represents a movie, as before.This is done to reduce the importance of words that occur frequently in plot overviews and therefore, their significance in computing the final `similarity score`.\n\nFortunately, `scikit-learn` gives you a built-in `TfIdfVectorizer` class that produces the TF-IDF matrix.\n\"\"\"\n# This function can be used to understand TfidfVectorizer & CountVectorizer\ndef vectorizer_example(vectorizer):\n    # Documents\n    docs = [\n        'I\\'m cool but powered by python I\\'m awesome', \n        'Bond, James Bond'\n    ]\n    \n    doc_matrix = vectorizer.fit_transform(docs)\n    return pd.DataFrame(\n        doc_matrix.toarray(), columns=vectorizer.get_feature_names()\n    )\n\n\nvectorizer_example(TfidfVectorizer(stop_words='english'))\ndef get_tfidf(df: pd.DataFrame):\n    tfidf = TfidfVectorizer(stop_words='english')\n    df.overview = df.overview.fillna('')\n    tfidf_matrix = tfidf.fit_transform(df.overview)\n    return tfidf_matrix\n\n\ntfidf_matrix = get_tfidf(df)\ntfidf_matrix.shape\n\"\"\"\nWe see that over 20,000 different words were used to describe the 4800 movies in our dataset.\n\nWith this matrix in hand, we can now compute a similarity score. There are several candidates for this; such as the euclidean, the Pearson and the [cosine similarity scores](https:\/\/en.wikipedia.org\/wiki\/Cosine_similarity). There is no right answer to which score is the best. Different scores work well in different scenarios and it is often a good idea to experiment with different metrics.\n\nWe will be using the cosine similarity to calculate a numeric quantity that denotes the similarity between two movies. We use the cosine similarity score since it is independent of magnitude and is relatively easy and fast to calculate. Mathematically, it is defined as follows:\n![](data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAa0AAAB1CAMAAADKkk7zAAAAh1BMVEX\/\/\/8AAAD5+fnFxcWtra3z8\/P8\/Pzw8PBycnL09PTo6Oj39\/e9vb3g4ODBwcGXl5ednZ3Pz8\/c3NyIiIiOjo5FRUXS0tJ+fn64uLimpqZPT0\/d3d1tbW1jY2NXV1c9PT02NjZ3d3cvLy9TU1NdXV0YGBggICBISEg5OTkqKioLCwsTExMdHR2pbwthAAARwklEQVR4nO1d2YKiOhBNARJAIIGETVkVtbX7\/7\/vJiCILTPdLr3ckfPQ4xoYDlU5VamUCE2YMGHChAkTng2+YS1Z8tNnMeFzyMhBm716P30aEz4DnGQ1UjbxT5\/HhM8BYmSBqf\/0aUz4DDDMEQusyRX+L5CskF5HxPrp85jwGcRiyvIi\/6dPY8KECRN+BKZ1DvzTJzThL\/DyrGIsapFmteG8+wA+f0GZmeZMQPm+U5zQA2\/BCI9wSfoC7Pz9GVmbg6d6SAWShGr+\/FvPc0IDF2CgBdX1y\/nb3ls+NC7FS2EfUR4FhT3F0j8ABuVgsnJ29vBNzGARnn1c3XPpBeNNNgn+n8AaqpOZ6PYwFa+7xSJQzz6tQfMBe7WYMh8\/AecNtD+9VSXG6izZa5KtfG7yzZT5+BloZ1PXAHON42h7tu7l1zsXW0uaTWT9FAxYjMZZoeHM+IHKh\/pRArr7BUlouqJy8tKVSWl8P3AAbOS6Y5IgJQEuH\/taK+Q1qGJN04zME1\/w4snAfgDeAS6vu26XNI6jNgLzeGN9x2kLxQdDfMEm72PpCd+BVXbpCp2UUEIjiMRj5ZiS8uu6EfT2Pg+RaZkXX5rw9bDT5cVrcyppQiFUwifGSRt1qRsmGZoTiDBWkynk+gGo+eVlN+M2LA4hnSMvSknzahtt4aTcqchO6j8p\/wlfhzAfBLp64\/IUjwcrTRdGxSEgqqVltrAoj2aQCo3Bc8NThPBI3Z865ecFzgfxr642TxQ10RJNQVj81aiKNAMraK6SNqer2Y0moZE\/Kfhvhl7RwTO\/HrMXp+L+hfyzKs17Vk2oO+NLRthp8WXrhHywRqK4xsuYufhpGl8c30mrp4234nR0ytZplhpGmmVplKhfsQRID5rqNoiThAdSAV5i5tmXVjR\/4uB4B\/uxu1pXkxyaqZ1B8AWV6j7sF7sW5dsGDiv14+9MUN8AwvG3GDSJVSeA8vGX0rGHcG11WhL+BDIAMEbfUY5szSp44997UhPGYW3TA8Bs7K2erQy2UzT6K0DAWQCMzkuCrTfu+CF9W9Ev0IVsuLKvhyp5\/CH+OQQB0l5hNfaWYOsQpFm9h+wPE9tdSIcL9grl+y84xj8GF8QdvhrqDMw6ryfY2rDQ8+JildrjX78H1jAs0J1k9I6ZMEQGVIsLodT7V1TYHh918xayAbJHR1whfVc\/GE9sfQRr9VoUhbCtk87AaZe869myAILLhY37UKkgAmSaJIlMAOpIn9j6EOTg+b7v7ABOc3zvoXq2fIDdg5MHikdeRMzVAT0HW8ogLzO7XrgF6+Yf7QBvI2lS3ip3R4Rko2mhuwAi4O4qq8NfwJbuf3k2C\/NWEihujJFDriuLxKnQ7oWJkPEiXGERnCcTdL7YAOzz9bqA8vEKXjhCguIjpIaxv4MtnbPLF+cxWyJvV4yFEBZJHvZfn1GjKVBw0rRiWLev22SoLIUXlAtFS797dHaifo8vKIPQDiREsw5IITnwr19inMPm0oc4iw0VlL1GI1+I9ztpAvEjQphw0dBjZQZWdxqa07Fyr98JUzt3BNYXLs2coEfR5RUyNXmX++UYWw5v3Ap7wI2Eq0Z4m3QXIj\/gsszh\/7MCPv+RG2s+ljtuCkz9lzG20FxqrvGV0ivhrJpZy38Txwn3wiM7xpR9\/QM0TjwPhZ46Q47n+cjVhKgINalvLPn8yJZDiI2b11TLTxzF9zyMMDtQz5Gfk39Dz\/9r8BkTu7klQkob\/6knPPGWSIkDKWNm5E2Q5slaST3JnnaZ7u8Ispi+ErTYlo7O9mW0plVAI0a2DGGyLZIjW95LGkdBLATBvlznK2Yb2zy0og2sXhhOiv2eYb46\/O0iWy+LJFoJLx\/tE20nhrSCSGNljHCUy\/eXgdyWZjd1yHYwremNwQVZBhKJuQMcZHpQWIoDpaZbmQgkFRXokS0bIrQ0ah\/p2iGNs8rCUeEhhUNsmiJaqgthLbWGWyfu5kGPstN3Jei6IbigYCm6syGIFIKxNEFWncn3Q9gEu2C\/l17RLbskn704DZV\/RVK2ga4Vp8NUv7ckM4ZFgrEvF1gdmZtJ5U7anfgTyesfNmwVgi3sCbOhhbjl7QNtJjki2BKXvjUCBsKZGl1aRzFnJ+jdgZiULQoCudVTWZSYQxZjyxI2JlcRdRuYYnpBU0eplt3ahzIYqW+jNPPUx6DnZfQw1qMOcyfck1oXAf6brOE+siWJ2a\/P2WrmLb8qV2+B0BTxa3slectWqzLUIprx+G+zVtXsSNMRhoW8OtnGwzsRtTLlyJaZbJtpq1E0akn\/MhRSA3gMRuVTj2T\/oMPci0EGxqv2UPdssRG2hG3pMWS+SWRdQ7x5x5YjlXy1CaveUeHBTekqHVttlhVDINmqNyrS3fT1wJC1lgIeS1udNdYr6Fh1tmUN7jGvS9nqyoPQq2\/LPR2m32z\/sMPci\/40E8lbejiy5YyyJeItf7HwRNRa8Bjbb+\/Y4mpzH+aslxheZPRIj95GPW5jQiCX65Ria3ExNl7UIiiW85ai7Xxhxm1G5TRvqdVpqK\/ro6Tb6ekwv3SXjrSFRKgMxMVUwg\/W0bbMfS4T14UU73Lt3CmZYEvMJ05WVAS7m\/ZKkiBs5i2dy2h+lsEH2b1SHokwMYGp7W0RiZtCMSoRBjSa0Cs9ROs2N2QXkyZ8ByZrhCgsqgyW6BVgQyLhI4tY\/qFbgEMqn0eq+LNQbShTI90AI+JpaSN1If61kZ\/DSmt8HQ8+uvNXUGVCBopDrnNhaPMKcmNRWDI6kHezla2yqPV1SlL\/zvv7B1GBuNstjNTPXRlHxcgP3+dZdC9s3TzXPiykw3YrGvVQmqFuzRW1cZ5Oo9pF\/NC5UisdSTG\/gytmS3W0xskSduk2NqrJ1cGRT+hOiHA4+uVfDHjQOCp3UHV7MIRZev6Cuv7YEVaejrLTfcbd\/j6KxWhZM0AgQsZS3lHuEV77oZlG0ZLf1K7C0a6DfZniteLrhkja\/+WyuOV8R8BAJfcsHS2LMy+K+SfShNEZW+4r9OGDLRx82rAlA\/xCytATUnmaki3nNrbqK8V3cHkU7VoB36q610flBvx0m96T2NPt3ZDr2PgE85E6ZEtcRK0zroatJgyUbDVtl\/QSmkVKcaGk\/ryDrd39hdPaTSWofvrxZ74JijYoiv5cx9MztiwRx64644ov2cIrKHD7Oalk72Arv3vxyqJfUCb323HGFhMStm8Hc8bWvJQPera2IGOD2+etsLpbm4Tky9KdvxdnbJXR+gBZl5FMh7ZVygeSLUvXFRUO0ohvZ4vSuz2hS56wPeiQLQ18ddvXEjaa8MK2Nqlh5PAayat9O1uGd\/dScfzXFOg\/iiFbeTlHAcDxMoyztY0Yi4rXppHq7Ww9oB5Re3K2nC3FOn+FfaszztjqPWEgLQ\/vYHXXvNU339JnM3OGb6jTxrSThLppiiGeY3PegC12EF4ue+32LPxh3pLXWdGaUvmb2fLTjq04K6JqfAfSB0OQLvL30jytSv4Us9iAraLmhJP60MRSR03YqOSerdklWzcpeI13FYmVB0tk1NcPofZ9CW1eaygZaTn0D6JjS9G1Q3PdwzcALJeC7J6thWBLls4qltSEiqIsM9jwO9iK+s7FilxB2NwwBfUiQxdMhYg9l23ZSQDE11GoCVdoUP89W6W0KLKBLUkSksNeNpq7ma1B++mCIgz4+tBpIDIImy2z2Pq\/ZZdvQcdWtMjznaagZJ3n+Vr2WLiwLXMtPpMvBPIqvitPuD5JQrCQ9ur9vVRgBErSz3W40lBcM+0ZivHOs7pDuEO25mObCMwb2cKnJoSOmLLUNL26sN4hfbnsknjIY8ZTZDbOs7pDXHjCC9xqWza722t5\/PfWv30h\/mxbH7N1q21x7YoAaz66e8EmV5ijbv0rXpIJti5+4aWBGskNpvJRjZGyG\/mEGSfCJV3vgtqeADN8jvFcFLYJHelnF8vdVfr83RDjN4HiUa7+G71cXXHbXbYlk3DEzND2\/xOmoI8tJim+15azXomF\/IpJidxmnCSUCIhI78JG5R7aGUlD9nJxQ+ha0\/oz5schmjEIH2835C487bRsN+E6zGrJFt7BtrnWhDEWGWVTzTrEUpZmW4sKOZuLNXCLyDoRK4It0\/ohAsj7EHnmqW0xpodRtDJREEw\/\/XQb1KixZXUPg9IcN33Xr2heHTTpbGPkby82lYa87bWbAzmZUxjt+zoUh+1ldZmRAcNqoqBgPbF1G0jSXmF6GP4Qhrk4tyBPmF7zYJ6sLzyhe0xduMV24OJwNFjzYk0JupJBItv7r+LJE96GtFvciiAbTP7Ls9ZtuF4fGvp01bis3IqP1qYkr\/WAcZ+e9JIBzWMGhoks4ws6Kj4J+kwGXp9l34fKVNdSrdkMoYfURxexVZ93ElMXG2ik08KJuS6bw2TCxDC10f3Ln88Jpe5VpLr9U+dKZ+24Ms2vhwZRtfcqw+oXt1BYv47KPbWMTFm2WEQmZpGr1tO8dRO86mQMFNaj0YPCKQrllp0ZeVns6vfVTf5A7tvleiw+J6+VFsfZns6RvVvsCjLZ1k1IyEn8KSmwsZvez3VkSU0\/l52R1feMqvwU5JkExqL7FDillO2oiUIxxEjz5AmfQaUObnOngJGyQCWt7TiBsfxJg3joGq0KLiuo8Hp1nLYmMXgXzn5bFREY6T3hFlFVGW0NyBi0swAsLulFXsletYXKEUT\/Rs7pm+Ed3ZmeD1NVijGybmzlnuVY4eZFpiaw1itC6yhJMB1KyRnhl8kvDu1+YCEJxb+xOhnYVbC6zZ3+Wak\/H5m25u1ui\/mL7DMhvtiJCEyPJuXzQQSma2xk8SSFZfPeprk3qmRi6yrQbs+nNqygSNILSTijDCJLSHfyBoaYdPS+1Yu3P25H89jAmbrsQhLOYloCT5KE7atmp5z\/FEUbj4NVwzHfFA1aFsTZoFJJaWMoXFWRYENXIwGqO3ZnR5h1v4ds85OpeGzg5WbttkNMxVdlopc2P5mB1SkBfx1o9la1HnCQKVLrYWxM2jo1xRIQV3cm\/8WY0uz4fhisjhtzB5LQZ8N+FVrk9EMchxFI7O0zVNg8DpjTYNFe6pPICPNhAlAbk\/JCY\/Bj+hDHLGsbIZmnCpolG278dYtkbIHL1l4mXXgNTMepN41ROX0Pq2XNl85y6cv9y37C3mDUXS2D47LK3PFZ29fX4R2vFos8McTSRLrlxzzYjFcd5HzyhFcibZdH4ug445sZyGK4fF1FRr4GgGzsW7q9sLqATNHa5sxeJwIxgbKWY6SRUa+3YojRjIW1da4pBJmAZJzayAGeHL2SorquLbecN78JJDBaxGTSIO4NRm1\/8thlR383D9tN63Y\/xCgp6opOCY0rQYDKuT67rkRK95PTWocHhuTJvrJHJk7iad66Etq+CYvza9Ors5NZhKXsDDe\/eufWbPKD18ILCtmv7NQo03HP3dPHPyfoZC9xV0HTwHpXcPXJBjMTPoRZS5nhRv31pWdJp5huP\/SRmMkugSHrozSXD\/cBeWT3hNv8vwiNKCT09AspZ3ZhWfBh4xw9lg3k1FNdtmkN4yvsLSY18ShEMi3eV9Ag7f1q7sdsCVEom932zas8er7FDmcTW48COXCM6u76JuEqRDZpweV881GrPyRFYYr1fnHL03iCQnocQtwGgq2vOvmnQ7yqLbOPXzVrYwlneIR0aJ+wLb9YhJh0FTRhHCXCGR5hoomtByLcrSyv6iYrhb6vnv0EW066ipes\/1ycnpvj5AkfB6UGJzkV0xZugmLegn3SE2J+SMJeVeqEeH7YDRFOtvVQpOBEdmdQ1ptKFPO0lcf34OO9RUIUErUXGU4VxY5yGsKKC+ZNWYsHQYjC9SkZSM534Wtxwj\/efSxE4SnvpNv8jF9V0zif4uMHgW5YcLqYyrkVzBVl\/vGaofe2YKcKGuX8h4UUMYQ5TVwPgv2yz+\/cUuovDvXUhvtb4CzOdhjcAquCu7qjTvg8Mvjrj358AjMKH7fhnvAQGHB32wQXph+A+yaw7d2KTd1P++a+Ccm9IkOIwkf8ZOOEz8C\/P3a1LnYHTfjH8R9wYiZCyjFLIwAAAABJRU5ErkJggg==)\n\"\"\"\n\"\"\"\nSince we have used the TF-IDF vectorizer, calculating the dot product will directly give us the cosine similarity score. Therefore, we will use sklearn's **`linear_kernel()`** instead of `cosine_similarities()` since it is faster.\n\"\"\"\ndef compute_cosine_similarity(matrix):\n    cosine_simi = linear_kernel(matrix, matrix)\n    return cosine_simi\n\n\ncosine_sim = compute_cosine_similarity(tfidf_matrix)\nprint(cosine_sim)\n\"\"\"\nDiagonal elements are 1 since those are same movies so they have same plot & other values are how much one movie has similar plot to the other.\n\"\"\"\nlinear_kernel([[1, 2, 3]], [[1, 2, 3]])\n# Construct a reverse map of indices and movie titles & drop duplicate indexes\nindices = pd.Series(df.index, index=df.title).drop_duplicates()\n\n\nprint(len(cosine_sim))\nprint(len(indices))\n\"\"\"\nWe are now in a good position to define our recommendation function. These are the following steps we'll follow :-\n* Get the index of the movie given its title.\n* Get the list of cosine similarity scores for that particular movie with all movies. Convert it into a list of tuples where the first element is its position and the second is the similarity score.\n* Sort the aforementioned list of tuples based on the similarity scores; that is, the second element.\n* Get the top 10 elements of this list. Ignore the first element as it refers to self (the movie most similar to a particular movie is the movie itself).\n* Return the titles corresponding to the indices of the top elements.\n\"\"\"\n# Function that takes in movie title as input and outputs most similar movies\ndef get_recommendations(df, title, cosine_sim=cosine_sim, top=10):\n    # Get the index of the movie that matches the title\n    idx = indices[title]\n\n    # Get the pairwsie similarity scores of all movies with that movie\n    sim_scores = list(enumerate(cosine_sim[idx]))\n\n    # Sort the movies based on the similarity scores\n    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n\n    # Get the scores of the `top` most similar movies\n    sim_scores = sim_scores[1:top + 1]\n\n    # Get the movie indices (only if the indexes are well sorted in continuous manner\n    # eg. 1, 2, 3, 4 and not like 1, 3, 4 since the index given by enumerate is used\n    # to get movie index)\n    movie_indices = [i[0] for i in sim_scores]\n\n    # Return the top 10 most similar movies\n    return df['title'].iloc[movie_indices]\n\n\nget_recommendations(df, 'The Dark Knight Rises')\nget_recommendations(df, 'The Avengers')\n\"\"\"\nWhile our system has done a decent job of finding movies with similar plot descriptions, the quality of recommendations is not that great. \"The Dark Knight Rises\" returns all Batman movies while it is more likely that the people who liked that movie are more inclined to enjoy other Christopher Nolan movies. This is something that cannot be captured by the present system.\n\"\"\"\n\"\"\"\n### Credits, Genres and Keywords Based Recommender\n\nIt goes without saying that the quality of our recommender would be increased with the usage of better metadata. That is exactly what we are going to do in this section. We are going to build a recommender based on the following metadata: the 3 top actors, the director, related genres and the movie plot keywords.\n\nFrom the cast, crew and keywords features, we need to extract the three most important actors, the director and the keywords associated with that movie. Right now, our data is present in the form of `stringified` lists , we need to convert it into a safe and usable structure\n\"\"\"\n# Parse the stringified features into their corresponding python objects\ndef eval_features(df, features):\n    for feature in features:\n        df[feature] = df[feature].apply(literal_eval)\n\n\nfeatures = ['cast', 'crew', 'keywords', 'genres']\neval_features(df, features)\n# Get the director's name from the crew feature. If director is not listed, return NaN\ndef get_director(crew_dict):\n    for crew_info in crew_dict:\n        if crew_info['job'] == 'Director':\n            return crew_info['name']\n    return np.nan\n\n\nprint(df.loc[1, 'crew'])\ndf['director'] = df['crew'].apply(get_director)\n# Returns the list top 3 elements or entire list, whichever is more.\ndef get_list(x):\n    if isinstance(x, list):\n        names = [_dict['name'] for _dict in x]\n        return names[:3]  # top 3\n    # Return empty list in case of missing\/malformed data\n    return []\n\n\n# These features are of dict type and have 'name' key in them\nfeatures = ['cast', 'keywords', 'genres']\nfor feature in features:\n    df[feature] = df[feature].apply(get_list)\n\n    \n# Print the new features of the first 3 films\ndf[['title', 'cast', 'director', 'keywords', 'genres']].head(3)\n\"\"\"\nThe next step would be to convert the names and keyword instances into lowercase and strip all the spaces between them. This is done so that our vectorizer doesn't count the Johnny of `Johnny Depp` and `Johnny Galecki` as the same.\n\"\"\"\n# Function to convert all strings to lower case and strip names of spaces\ndef clean_data(x):\n    if isinstance(x, list):\n        return [str.lower(i.replace(' ', '')) for i in x]\n    else:\n        # Check if director exists. If not, return empty string\n        if isinstance(x, str):\n            return str.lower(x.replace(' ', ''))\n        else:\n            return ''\n\n\n# Apply clean_data function to your features.\nfeatures = ['cast', 'keywords', 'director', 'genres']\nfor feature in features:\n    df[feature] = df[feature].apply(clean_data)\n\n    \ndf.head()\n\"\"\"\nWe are now in a position to create our `metadata soup`, which is a string that contains all the metadata that we want to feed to our vectorizer (namely actors, director and keywords).\n\"\"\"\ndef create_soup(x):\n    keywords_str = ' '.join(x.keywords)\n    cast_str = ' '.join(x.cast)\n    director_str = x.director\n    genres_str = ' '.join(x.genres)\n    return f'{keywords_str} {cast_str} {director_str} {genres_str}'\n\n\ndf['soup'] = df.apply(create_soup, axis='columns')\ndf.soup[:5]\n\"\"\"\nThe next steps are the same as what we did with our plot description based recommender. One important difference is that we use the **`CountVectorizer()`** instead of TF-IDF. This is because we do not want to down-weight the presence of an actor\/director if he or she has acted or directed in relatively more movies. It doesn't make much intuitive sense.\n\"\"\"\nvectorizer_example(CountVectorizer(stop_words='english'))\ndef get_count_matrix(df: pd.DataFrame):\n    count = CountVectorizer(stop_words='english')\n    count_matrix = count.fit_transform(df.soup)\n    return count_matrix\n\n\ncount_matrix = get_count_matrix(df)\ncosine_sim_2 = compute_cosine_similarity(count_matrix)\n# Reset index of our main DataFrame and construct reverse mapping as before\ndf = df.reset_index()\nindices = pd.Series(df.index, index=df.title)\nget_recommendations(df, 'The Dark Knight Rises', cosine_sim_2)\nget_recommendations(df, 'The Godfather', cosine_sim_2)\n\"\"\"\nWe see that our recommender has been successful in capturing more information due to more metadata and has given us (arguably) better recommendations. It is more likely that Marvels or DC comics fans will like the movies of the same production house. Therefore, to our features above we can add `production_company` . We can also increase the weight of the director, by adding the feature multiple times in the soup.\n\"\"\"\n\"\"\"\n## Collaborative Filtering\n\n![](https:\/\/media.giphy.com\/media\/QWPIBMUCSXRL2\/giphy.gif)\n\nOur content based engine suffers from some severe limitations. It is only capable of suggesting movies which are close to a certain movie. That is, it is not capable of capturing tastes and providing recommendations across genres.\n\nAlso, the engine that we built is not really personal in that it doesn't capture the personal tastes and biases of a user. Anyone querying our engine for recommendations based on a movie will receive the same recommendations for that movie, regardless of who she\/he is.\n\nTherefore, in this section, we will use a technique called Collaborative Filtering to make recommendations to Movie Watchers.\nIt is basically of two types:-\n\n*  **`User based filtering`**-  These systems recommend products to a user that similar users have liked. For measuring the similarity between two users we can either use pearson correlation or cosine similarity.\nThis filtering technique can be illustrated with an example. In the following matrixes, each row represents a user, while the columns correspond to different movies except the last one which records the similarity between that user and the target user. Each cell represents the rating that the user gives to that movie. Assume user E is the target.\n![](https:\/\/cdn-images-1.medium.com\/max\/1000\/1*9NBFo4AUQABKfoUOpE3F8Q.png)\n\nSince user A and F do not share any movie ratings in common with user E, their similarities with user E are not defined in Pearson Correlation. Therefore, we only need to consider user B, C, and D. Based on Pearson Correlation, we can compute the following similarity.\n![](https:\/\/cdn-images-1.medium.com\/max\/1000\/1*jZIMJzKM1hKTFftHfcSxRw.png)\n\nFrom the above table we can see that user D is very different from user E as the Pearson Correlation between them is negative. He rated Me Before You higher than his rating average, while user E did the opposite. Now, we can start to fill in the blank for the movies that user E has not rated based on other users.\n![](https:\/\/cdn-images-1.medium.com\/max\/1000\/1*9TC6BrfxYttJwiATFAIFBg.png)\n\nAlthough computing user-based CF is very simple, it suffers from several problems. One main issue is that users\u2019 preference can change over time. It indicates that precomputing the matrix based on their neighboring users may lead to bad performance. To tackle this problem, we can apply item-based CF.\n\n* **`Item Based Collaborative Filtering`** - Instead of measuring the similarity between users, the item-based CF recommends items based on their similarity with the items that the target user rated. Likewise, the similarity can be computed with Pearson Correlation or Cosine Similarity. The major difference is that, with item-based collaborative filtering, we fill in the blank vertically, as oppose to the horizontal manner that user-based CF does. The following table shows how to do so for the movie Me Before You.\n![](https:\/\/cdn-images-1.medium.com\/max\/1000\/1*LqFnWb-cm92HoMYBL840Ew.png)\n\nIt successfully avoids the problem posed by dynamic user preference as item-based CF is more static. However, several problems remain for this method. First, the main issue is **`scalability`**. The computation grows with both the customer and the product. The `worst case complexity is O(mn)` with m users and n items. In addition, **`sparsity`** is another concern. Take a look at the above table again. Although there is only one user that rated both Matrix and Titanic rated, the similarity between them is 1. In extreme cases, we can have millions of users and the similarity between two fairly different movies could be very high simply because they have similar rank for the only user who ranked them both.\n\"\"\"\n\"\"\"\n### Single Value Decomposition\n\nOne way to handle the `scalability` and `sparsity` issue created by content filtering recommender is to leverage a **`latent factor model`** to capture the similarity between users and items. Essentially, we want to `turn the recommendation problem into an optimization problem`. We can view it as how good we are in predicting the rating for items given a user. One common metric is Root Mean Square Error (RMSE). **`The lower the RMSE, the better the performance`**.\n\nNow talking about latent factor you might be wondering what is it? It is a broad idea which describes a property or concept that a user or an item have. For instance, for music, latent factor can refer to the genre that the music belongs to. `SVD` decreases the dimension of the utility matrix by extracting its latent factors. Essentially, we map each user and each item into a latent space with dimension r. Therefore, it helps us better understand the relationship between users and items as they become directly comparable. The below figure illustrates this idea.\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*GUw90kG2ltTd2k_iv3Vo0Q.png)\n\"\"\"\n\"\"\"\nNow enough said , let's see how to implement this.\nSince the dataset we used before did not have userId(which is necessary for collaborative filtering) let's load another dataset. We'll be using the [**Surprise** ](https:\/\/surprise.readthedocs.io\/en\/stable\/index.html) library to implement SVD.\n\"\"\"\nreader = Reader()\nratings = pd.read_csv('..\/input\/the-movies-dataset\/ratings_small.csv')\nratings.sample(5)\ndata = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)\nsvd = SVD()\ncross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5)\n\"\"\"\nWe get a `mean Root Mean Sqaure Error` of 0.89 approx which is more than good enough for our case. Let us now train on our dataset and arrive at predictions.\n\"\"\"\ntrainset = data.build_full_trainset()\nsvd.fit(trainset)\n# Let us pick user with user Id 1 and check the ratings she\/he has given.\nratings[ratings['userId'] == 1]\nsvd.predict(1, 302, 3)\n\"\"\"\nFor movie with ID 302, we get an estimated prediction of **2.669**. One startling feature of this recommender system is that it doesn't care what the movie is (or what it contains). It works purely on the basis of an assigned movie ID and tries to predict ratings based on how the other users have predicted the movie.\n\"\"\"\n\"\"\"\n---\n\nI'll wrap things up there. If you want to find some other answers then go ahead `edit` this kernel. If you have any `questions` then do let me know.\n\nIf this kernel helped you then don't forget to \ud83d\udd3c `upvote` and share your \ud83c\udf99 `feedback` on improvements of the kernel.\n\n![](https:\/\/media.giphy.com\/media\/N2fDcOGHsEEA8\/giphy.gif)\n\n---\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5937b71d07f2d7'}"}
{"id":"9822","text":"\"\"\"\n## You're here! \nWelcome to your first competition in the [ITI's AI Pro training program](https:\/\/ai.iti.gov.eg\/epita\/ai-engineer\/)! We hope you enjoy and learn as much as we did prepairing this competition.\n\n\n## Introduction\n\nIn the competition, it's required to predict the `Severity` of a car crash given info about the crash, e.g., location.\n\nThis is the getting started notebook. Things are kept simple so that it's easier to understand the steps and modify it.\n\nFeel free to `Fork` this notebook and share it with your modifications **OR** use it to create your submissions.\n\n### Prerequisites\nYou should know how to use python and a little bit of Machine Learning. You can apply the techniques you learned in the training program and submit the new solutions! \n\n### Checklist\nYou can participate in this competition the way you perefer. However, I recommend following these steps if this is your first time joining a competition on Kaggle.\n\n* Fork this notebook and run the cells in order.\n* Submit this solution.\n* Make changes to the data processing step as you see fit.\n* Submit the new solutions.\n\n*You can submit up to 5 submissions per day. You can select only one of the submission you make to be considered in the final ranking.*\n\n\nDon't hesitate to leave a comment or contact me if you have any question!\n\"\"\"\n\"\"\"\n## Import the libraries\n\nWe'll use `pandas` to load and manipulate the data. Other libraries will be imported in the relevant sections.\n\"\"\"\nimport pandas as pd\nimport os\n##########################################\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.ticker import NullFormatter\nimport pandas as pd\nimport numpy as np\nimport matplotlib.ticker as ticker\nfrom sklearn import preprocessing\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split  #>>>>\nfrom sklearn.linear_model import LinearRegression     #>>>>\n##########################################\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nimport xml.etree.ElementTree as Xet\n\"\"\"\n## Exploratory Data Analysis\nIn this step, one should load the data and analyze it. However, I'll load the data and do minimal analysis. You are encouraged to do thorough analysis!\n\nLet's load the data using `pandas` and have a look at the generated `DataFrame`.\n\"\"\"\n\"\"\"\n### 1 - Data understanding\n\"\"\"\nprint('---------------File: train.csv-------------------')\ndataset_path = '\/kaggle\/input\/car-crashes-severity-prediction\/'\ndf = pd.read_csv(os.path.join(dataset_path, 'train.csv'))\nprint(\"#################################################\")\nprint(\"The shape of the dataset is {}.\".format(df.shape))\nprint(\"#################################################\")\nprint(\"Sample of the dataset:\\n\")\nprint(df.head())\nprint(\"#################################################\")\nprint(\"Sample of the dataset:\\n\")\nprint(df.describe())\nprint(\"#################################################\")\nprint(\"check the null values\")\nprint(df.isnull().sum())\nprint(\"#################################################\")\nprint(\"check the data types and duplicates\")\nprint(df.info())\nprint(\"#################################################\")\nprint(\"check the unique of each coloum\")\nprint(\"ID=\",df.ID.unique())\nprint(\"Lat=\",df.Lat.unique())\nprint(\"Lng=\",df.Lng.unique())\nprint(\"Bump=\",df.Bump.unique())\n#print(\"Distance(mi)=\",df[Distance(mi)].unique())\nprint(\"Crossing=\",df.Crossing.unique())\nprint(\"Give_Way=\",df.Give_Way.unique())\nprint(\"Junction=\",df.Junction.unique())\nprint(\"No_Exit=\",df.No_Exit.unique())\nprint(\"Railway=\",df.Railway.unique())\nprint(\"Roundabout=\",df.Roundabout.unique())\nprint(\"Stop=\",df.Stop.unique())\nprint(\"Amenity=\",df.Amenity.unique())\nprint(\"Side=\",df.Side.unique())\nprint(\"Severity=\",df.Severity.unique())\nprint(\"timestamp=\",df.timestamp.unique())\nprint(\"#################################################\")\nprint('---------------File: weather-sfcsv.csv-------------------')\ndf_weather = pd.read_csv(os.path.join(dataset_path, 'weather-sfcsv.csv'))\nprint(\"#################################################\")\nprint(\"The shape of the dataset is {}.\".format(df_weather.shape))\nprint(\"#################################################\")\nprint(\"Sample of the dataset:\\n\")\nprint(df_weather.head())\nprint(\"#################################################\")\nprint(\"Sample of the dataset:\\n\")\nprint(df_weather.describe())\nprint(\"#################################################\")\nprint(\"check the null values\")\nprint(df_weather.isnull().sum())\nprint(\"#################################################\")\nprint(\"check the data types and duplicates\")\nprint(df_weather.info())\nprint(\"#################################################\")\nprint(\"check the unique of each coloum\")\nprint(\"Year=\",df_weather.Year.unique())\nprint(\"Day=\",df_weather.Day.unique())\nprint(\"Month=\",df_weather.Month.unique())\nprint(\"Hour=\",df_weather.Hour.unique())\nprint(\"Weather_Condition=\",df_weather.Weather_Condition.unique())\nprint(\"Selected=\",df_weather.Selected.unique())\nprint(\"#################################################\")\nprint('---------------File: holidays.xml-------------------')\ncols = [\"date\", \"description\"]\nrows = []\n# Parsing the XML file\nprint(\"#################################################\")\nxmlparse = Xet.parse('\/kaggle\/input\/car-crashes-severity-prediction\/holidays.xml')\nroot = xmlparse.getroot()\nprint(\"#################################################\")\nfor i in root:\n    date = i.find(\"date\").text\n    description = i.find(\"description\").text \n    rows.append({\"date\": date,\"description\": description})\ndf_holidays = pd.DataFrame(rows, columns=cols)\nprint(df_holidays)\nprint(\"#################################################\")\n\"\"\"\nWe've got 6407 examples in the dataset with 14 featues, 1 ID, and the `Severity` of the crash.\n\nBy looking at the features and a sample from the data, the features look of numerical and catogerical types. What about some descriptive statistics?\n\"\"\"\n\"\"\"\n### 2 - Data Preparation\n\"\"\"\n\"\"\"\n#### 2-1 Statistics and correlations\n\"\"\"\nprint('---------------File: train.csv-------------------')\nprint(\"#################################################\")\nprint(\"Statistics describtion:\")\nprint(df.drop(columns='ID').describe())\nprint(\"#################################################\")\nprint(\"correlation matrix=\")\nprint(df.corr())\nprint(\"#################################################\")\nprint('---------------File: train.csv-------------------')\n\n# using Kmeans Clustering for Lat and Lng:\nX = df[['Lat','Lng']].to_numpy()\n\n\n#Finding the optimum number of clusters for k-means classification\nfrom sklearn.cluster import KMeans\ncss = []\n\nfor i in range(1, 11):\n    kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)\n    kmeans.fit(X)\n    css.append(kmeans.inertia_)\n    \n#Plotting the results onto a line graph, allowing us to observe 'The elbow'\nplt.plot(range(1, 11), css)\nplt.title('The elbow method')\nplt.xlabel('Number of clusters')\nplt.ylabel('CSS') #within cluster sum of squares\nplt.show()\n\n\n#Applying kmeans to the dataset \/ Creating the kmeans classifier\nkmeans = KMeans(n_clusters = 10, init = 'k-means++', max_iter = 500, n_init = 11, random_state = 0)\ny_kmeans = kmeans.fit_predict(X)\n\n\n\n\n#Visualising the clusters\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 50, c = 'red', label = 'City-1')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 50, c = 'blue', label = 'City-2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 50, c = 'green', label = 'City-3')\nplt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 50, c = 'purple', label = 'City-4')\nplt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 50, c = 'yellow', label = 'City-5')\n\n#Plotting the centroids of the clusters\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], s = 250, c = 'Black', label = 'Centroids', marker='*')\n\nplt.legend()\nplt.xlabel(\"Lat\")\nplt.ylabel(\"Lng\")\n\n\n\ndf[\"City No.\"]=kmeans.fit_predict(X)\ndf.head()\nprint('---------------File: weather-sfcsv.csv-------------------')\nprint(\"#################################################\")\nprint(\"Statistics describtion:\")\nprint(df_weather.describe())\nprint(\"#################################################\")\nprint(\"correlation matrix=\")\nprint(df_weather.corr())\nprint(\"#################################################\")\nprint(\"removing NaN from Weather_Condition\")\ndf_weather.dropna(subset=['Weather_Condition'], inplace=True)\nprint(\"#################################################\")\nprint(\"split Weather_Condition to Weather and Is_Windy\")\ndf_weather[['Weather','Is_Windy']]=df_weather.Weather_Condition.str.split(\" \/ \",expand=True)\ndf_weather[\"Is_Windy\"] = df_weather[\"Is_Windy\"].notnull().astype('int')\nprint(\"#################################################\")\nprint(\"Encoding Weather_Condition:\")\nWeather_Condition_coding={\"Weather\":{'Clear':1,'Fair':2,'Partly Cloudy':3,'Mostly Cloudy':4,'Cloudy':5,'Overcast':6,\n                                               'Smoke':7,'Scattered Clouds':8,'Light Drizzle':9,'Light Rain':10,'Rain':11,\n                                               'Heavy Rain':12,'Haze':13,'Mist':14,'Patches of Fog':15,'Fog':16,'Shallow Fog':17,\n                                               'Squalls':18,'Light Thunderstorms and Rain':19}}\ndf_weather = df_weather.replace(Weather_Condition_coding)\ndf_weather.info()\n#print(\"#################################################\")\n\"\"\"\n#### 2-2 Drop Unnecessary Columns & Convert & Encoding & merge\n\"\"\"\nprint('---------------File: train.csv-------------------')\nprint(\"Convert bool Type to int Type:\")\nprint(\"'Crossing','Give_Way','Junction','No_Exit','Railway','Stop','Amenity'\")\ndf['Crossing'] = df['Crossing'].astype('int')\ndf['Give_Way'] = df['Give_Way'].astype('int')\ndf['Junction'] = df['Junction'].astype('int')\ndf['No_Exit'] = df['No_Exit'].astype('int')\ndf['Railway'] = df['Railway'].astype('int')\ndf['Stop'] = df['Stop'].astype('int')\ndf['Amenity'] = df['Amenity'].astype('int')\nprint(\"#################################################\")\nprint(\"Convert 'timestamp' to datetime:\")\ndf.timestamp = pd.to_datetime(df.timestamp)\nprint(\"#################################################\")\nprint(\"Encoding 'Side' to bool Type:\")\nside_encod={\"Side\":{\"R\":0, \"L\":1}}\ndf = df.replace(side_encod)\nprint(\"#################################################\")\nprint(\"Drop Unnecessary Columns\")\ndf= df.drop(['Bump','Roundabout'],axis=1)\nprint(\"#################################################\")\nprint('---------------File: weather-sfcsv.csv-------------------')\nprint(\"#################################################\")\nprint('Removing Null values from preceptation and Build Model to free Nulls')\nclean_weather = df_weather.dropna()\ntrain_df_weather, val_df_weather = train_test_split(clean_weather, test_size=0.2, random_state=42) \nX_train = train_df_weather.drop(columns=['Weather_Condition','Precipitation(in)','Year', 'Day', 'Month', 'Hour', 'Wind_Chill(F)','Selected'])\ny_train = train_df_weather['Precipitation(in)']\nX_val = val_df_weather.drop(columns=['Weather_Condition','Precipitation(in)', 'Year', 'Day', 'Month', 'Hour', 'Wind_Chill(F)', 'Selected'])\ny_val = np.array(val_df_weather['Precipitation(in)'])\nprint(\"#################################################\")\nprint('LinearRegression Model')\nWeather_model = LinearRegression()\nWeather_model.fit(X_train,y_train)\nWeather_model.score(X_train,y_train)\nprint(\"#################################################\")\nprint('dataset null')\ndataset = df_weather[df_weather['Precipitation(in)'].isnull()]\nx = dataset.drop(columns=['Weather_Condition','Precipitation(in)','Year', 'Day', 'Month', 'Hour', 'Wind_Chill(F)','Selected'])\ny = dataset['Precipitation(in)']\nx.fillna(x.mean(), inplace=True)\ndf_weather.loc[df_weather[\"Precipitation(in)\"].isnull(), \"Precipitation(in)\"] = Weather_model.predict(x)\nprint(\"#################################################\")\nprint('free NAN from Wind_Speed(mph)')\ndf_weather.loc[df_weather[\"Wind_Speed(mph)\"].isnull(),\"Wind_Speed(mph)\"] = df_weather[\"Wind_Speed(mph)\"].mean()\nprint(\"#################################################\")\nprint('---------------File: train.csv-------------------')\nprint(\"#################################################\")\nprint(\"Drop Unnecessary Columns\")\ndf_weather=df_weather.drop(['Wind_Chill(F)','Selected'],axis=1)\nprint(\"#################################################\")\n#print(\"Drop Null Rows\")\n#df_weather=df_weather.dropna()\nprint(\"#################################################\")\nprint(\"Extract year, month, day, hour from timestamp\")\ndef get_my_date(row):\n    return pd.Timestamp(year=row.Year, month=row.Month, day=row.Day, hour=row.Hour)\ndf_weather[\"timestamp\"] = df_weather.apply(get_my_date, axis=1)\nprint(\"#################################################\")\nprint(\"Remove duplication from timestamp\")\ndf_weather.drop_duplicates(subset=\"timestamp\", inplace=True)\ndf_weather.reset_index(inplace=True, drop=True)\ndf_weather.info()\nprint(\"#################################################\")\nprint(\"round Hours in timestamp\")\n\ndef reset(row):\n    return row.round(freq=\"min\")\ndf_weather.timestamp = df_weather.timestamp.apply(reset)\ndf.timestamp = df.timestamp.apply(reset)\nprint(\"#################################################\")\nprint(\"merge year, month, day, hour to timestamp\")\nmerged = pd.merge(df, df_weather, how=\"left\", on=\"timestamp\")\nprint(\"#################################################\")\nmerged.info()\nprint('---------------File: weather-sfcsv.csv-------------------')\nprint(\"1#################################################\")\ndf_holidays['date'] = pd.to_datetime(df_holidays['date']).dt.date\nmerged['date'] = pd.to_datetime(merged['timestamp']).dt.date\nfinal_merged = pd.merge(merged, df_holidays, how=\"left\", on=\"date\")\nprint(df_weather.info())\nprint(\"2#################################################\")\nfinal_merged.loc[:,\"is_holiday\"] = final_merged[\"description\"].notnull()\nfinal_merged.head()\nprint(final_merged.info())\nprint(\"3#################################################\")\nfinal_merged['is_holiday'] = final_merged['is_holiday'].astype('int')\nprint(\"#################################################\")\nfinal_merged= final_merged.drop([\"description\",'date','Precipitation(in)'],axis=1)\nprint(\"#################################################\")\nfinal_merged_free=final_merged.dropna()  \n#final_merged.fillna(final_merged.mean(), inplace=True)\nprint(\"#################################################\")\nprint(final_merged_free.info())\n#Normalization\nscaler = preprocessing.MinMaxScaler()\ncolumns = [\"Temperature(F)\",\"Humidity(%)\",\"Wind_Speed(mph)\",\"Visibility(mi)\"]\nfor col in columns:\n        final_merged_free[col] = scaler.fit_transform(final_merged_free[col].values.reshape(-1, 1))\nint_cols = [\"Is_Windy\",\"Weather\",\"Year\",\"Day\",\"Month\",\"Hour\"]\nfor c in int_cols:\n    final_merged_free[c] = final_merged_free[c].astype(int)\n\nprint(final_merged.info())\nprint(final_merged_free['Lng'])\n\"\"\"\n#### 2-3 Data Visualization\n\"\"\"\nprint('---------------File: train.csv-------------------')\nprint(\"scatter_matrix for Lat, Lng, Distance(mi),Severity: \")\nscatter_matrix(df[['Lat', 'Lng', 'Distance(mi)','Severity']], figsize=(10,10));\nplt.show()\nprint(\"#################################################\")\nprint(\"Histogram:\")\ndf.Lat.hist();plt.title('Lat Histogram');plt.xlabel('Lat');plt.ylabel('Values');plt.show()\ndf.Lng.hist();plt.title('Lng Histogram');plt.xlabel('Lng');plt.ylabel('Values');plt.show()\ndf.Severity.hist();plt.title('Severity Histogram');plt.xlabel('Severity');plt.ylabel('Values');plt.show()\ndf.timestamp.hist();plt.title('timestamp Histogram');plt.xlabel('timestamp');plt.ylabel('Values');plt.show()\nprint(\"#################################################\")\nprint('---------------File: weather-sfcsv.csv-------------------')\nprint(\"#################################################\")\nprint(\"scatter_matrix for 'Year', 'Day', 'Month','Hour','Temperature(F)','Humidity(%)','Wind_Speed(mph)','Visibility(mi)': \")\nscatter_matrix(df_weather[['Year', 'Day', 'Month','Hour','Temperature(F)','Humidity(%)','Wind_Speed(mph)','Visibility(mi)']], figsize=(10,10));\nplt.show()\nprint(\"#################################################\")\nprint(\"Histogram:\")\ndf_weather.Year.hist();plt.title('Year Histogram');plt.xlabel('Year');plt.ylabel('Values');plt.show()\ndf_weather.Day.hist();plt.title('Day Histogram');plt.xlabel('Day');plt.ylabel('Values');plt.show()\ndf_weather.Month.hist();plt.title('Month Histogram');plt.xlabel('Month');plt.ylabel('Values');plt.show()\n#df.Temperature(F).hist();plt.title('Temperature(F) Histogram');plt.xlabel('Temperature(F)');plt.ylabel('Values');plt.show()\n#df.Humidity(%).hist();plt.title('Humidity(%) Histogram');plt.xlabel('Humidity(%)');plt.ylabel('Values');plt.show()\n#df.Wind_Speed(mph).hist();plt.title('Wind_Speed(mph) Histogram');plt.xlabel('Wind_Speed(mph)');plt.ylabel('Values');plt.show()\n#df.Visibility(mi).hist();plt.title('Visibility(mi) Histogram');plt.xlabel('Visibility(mi)');plt.ylabel('Values');plt.show()\nprint(\"#################################################\")\n\"\"\"\nThe output shows desciptive statistics for the numerical features, `Lat`, `Lng`, `Distance(mi)`, and `Severity`. I'll use the numerical features to demonstrate how to train the model and make submissions. **However you shouldn't use the numerical features only to make the final submission if you want to make it to the top of the leaderboard.**\n\"\"\"\n\"\"\"\n## Data Splitting\n\nNow it's time to split the dataset for the training step. Typically the dataset is split into 3 subsets, namely, the training, validation and test sets. In our case, the test set is already predefined. So we'll split the \"training\" set into training and validation sets with 0.8:0.2 ratio. \n\n*Note: a good way to generate reproducible results is to set the seed to the algorithms that depends on randomization. This is done with the argument `random_state` in the following command* \n\"\"\"\nfrom sklearn.model_selection import train_test_split\ntrain_df, val_df = train_test_split(final_merged_free, test_size=0.2, random_state=42) # Try adding `stratify` here  , shuffle=True, stratify=final_merged_free[['Severity']]\nX_train = train_df.drop(columns=['ID', 'Severity','Weather_Condition','timestamp','Year','Day','Weather','Temperature(F)','Give_Way','Railway','City No.'])\ny_train = train_df['Severity']\nX_val = val_df.drop(columns=['ID', 'Severity','Weather_Condition','timestamp','Year','Day','Weather','Temperature(F)','Give_Way','Railway','City No.'])\ny_val = val_df['Severity']\n\n#is_holiday  ,'Year','Day','Weather','Temperature(F)','Give_Way','Railway'\n\"\"\"\nAs pointed out eariler, I'll use the numerical features to train the classifier. **However, you shouldn't use the numerical features only to make the final submission if you want to make it to the top of the leaderboard.** \n\"\"\"\n## This cell is used to select the numerical features. IT SHOULD BE REMOVED AS YOU DO YOUR WORK.\n#X_train = X_train[['Lat', 'Lng', 'Distance(mi)']]\n#X_val = X_val[['Lat', 'Lng', 'Distance(mi)']]\n\"\"\"\n## Model Training\n\nLet's train a model with the data! We'll train a Random Forest Classifier to demonstrate the process of making submissions. \n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Create an instance of the classifier\nclassifier = RandomForestClassifier(max_depth=2, random_state=0)\n\n# Train the classifier\nclassifier = classifier.fit(X_train, y_train)\n\"\"\"\nNow let's test our classifier on the validation dataset and see the accuracy.\n\"\"\"\nprint(\"The accuracy of the classifier on the validation set is \", (classifier.score(X_val, y_val)))\n#0.8823529411764706\n\"\"\"\nWell. That's a good start, right? A classifier that predicts all examples' `Severity` as 2 will get around 0.63. You should get better score as you add more features and do better data preprocessing.\n\"\"\"\n\"\"\"\n## Submission File Generation\n\nWe have built a model and we'd like to submit our predictions on the test set! In order to do that, we'll load the test set, predict the class and save the submission file. \n\nFirst, we'll load the data.\n\"\"\"\ntest_df = pd.read_csv(os.path.join(dataset_path, 'test.csv'))\ntest_df.head()\n\"\"\"\nNote that the test set has the same features and doesn't have the `Severity` column.\nAt this stage one must **NOT** forget to apply the same processing done on the training set on the features of the test set.\n\nNow we'll add `Severity` column to the test `DataFrame` and add the values of the predicted class to it.\n\n**I'll select the numerical features here as I did in the training set. DO NOT forget to change this step as you change the preprocessing of the training data.**\n\"\"\"\nX = test_df[['Lat','Lng']].to_numpy()\nkmeans = KMeans(n_clusters = 10, init = 'k-means++', max_iter = 500, n_init = 11, random_state = 0)\ntest_df[\"City No.\"]=kmeans.fit_predict(X)\ntest_df.timestamp = pd.to_datetime(test_df.timestamp)\nside_encod={\"Side\":{\"R\":0, \"L\":1}}\ntest_df = test_df.replace(side_encod)\n\n\ntest_df['Crossing'] = test_df['Crossing'].astype('int')\ntest_df['Give_Way'] = test_df['Give_Way'].astype('int')\ntest_df['Junction'] = test_df['Junction'].astype('int')\ntest_df['No_Exit'] = test_df['No_Exit'].astype('int')\ntest_df['Railway'] = test_df['Railway'].astype('int')\ntest_df['Stop'] = test_df['Stop'].astype('int')\ntest_df['Amenity'] = test_df['Amenity'].astype('int')\ntest_df.timestamp = pd.to_datetime(test_df.timestamp)\n\ntest_df= test_df.drop(['Bump','Roundabout'],axis=1)\n\ntest_merged = pd.merge(test_df, df_weather, how=\"left\", on=\"timestamp\")\ndf_holidays['date'] = pd.to_datetime(df_holidays['date']).dt.date\ntest_merged['date'] = pd.to_datetime(test_merged['timestamp']).dt.date\n\nfinal_test_merged = pd.merge(test_merged, df_holidays, how=\"left\", on=\"date\")\nfinal_test_merged.loc[:,\"is_holiday\"] = final_test_merged[\"description\"].notnull()\nfinal_test_merged['is_holiday'] = final_test_merged['is_holiday'].astype('int')\nfinal_test_merged= final_test_merged.drop([\"description\",'date','Precipitation(in)'],axis=1)\nfinal_test_merged.fillna(final_test_merged.mean(), inplace=True)\n#final_test_merged_free=final_test_merged.fillna(final_test_merged.mean())\n#Normalization\nscaler = preprocessing.MinMaxScaler()\ncolumns = [\"Temperature(F)\",\"Humidity(%)\",\"Wind_Speed(mph)\",\"Visibility(mi)\"]\nfor col in columns:\n        final_test_merged[col] = scaler.fit_transform(final_test_merged[col].values.reshape(-1, 1))\nint_cols = [\"Is_Windy\",\"Weather\",\"Year\",\"Day\",\"Month\",\"Hour\"]\nfor c in int_cols:\n    final_test_merged[c] = final_test_merged[c].astype(int)\n\nprint(final_test_merged.info())\nX_test = final_test_merged.drop(columns=['ID','Weather_Condition','timestamp', 'Distance(mi)','Year','Day','Weather','Temperature(F)','Give_Way','Railway'])\n# You should update\/remove the next line once you change the features used for training\n#X_test = X_test[['Lat', 'Lng', 'Distance(mi)']]\ny_test_predicted = classifier.predict(X_test)\ntest_df['Severity'] = y_test_predicted\ntest_df.head()\n#X_test = test_df.drop(columns=['ID'])\n\n## You should update\/remove the next line once you change the features used for training\n#X_test = X_test[['Lat', 'Lng', 'Distance(mi)']]\n\n#y_test_predicted = classifier.predict(X_test)\n\n#test_df['Severity'] = y_test_predicted\n\n#test_df.head()\n\"\"\"\nNow we're ready to generate the submission file. The submission file needs the columns `ID` and `Severity` only.\n\"\"\"\ntest_df[['ID', 'Severity']].to_csv('\/kaggle\/working\/submission.csv', index=False)\n\"\"\"\nThe remaining steps is to submit the generated file and are as follows. \n\n1. Press `Save Version` on the upper right corner of this notebook.\n2. Write a `Version Name` of your choice and choose `Save & Run All (Commit)` then click `Save`.\n3. Wait for the saved notebook to finish running the go to the saved notebook.\n4. Scroll down until you see the output files then select the `submission.csv` file and click `Submit`.\n\nNow your submission will be evaluated and your score will be updated on the leaderboard! CONGRATULATIONS!!\n\"\"\"\n\"\"\"\n## Conclusion\n\nIn this notebook, we have demonstrated the essential steps that one should do in order to get \"slightly\" familiar with the data and the submission process. We chose not to go into details in each step to keep the welcoming notebook simple and make a room for improvement.\n\nYou're encourged to `Fork` the notebook, edit it, add your insights and use it to create your submission.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '121053889c81ef'}"}
{"id":"75811","text":"\"\"\"\n# EDA in Album review ratings dataset\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\npd.options.display.max_columns=90\ndata = pd.read_csv('..\/input\/30000-albums-aggregated-review-ratings\/album_ratings.csv')\ndata.head()\n\"\"\"\n## Selecting Data from 2000\n\"\"\"\ndata['Release Year'].unique()\ndata_2000 = data[data['Release Year'] >= 2000].copy()\ndata_2000['Release Year'].unique()\n\"\"\"\n## Checking if there's outliers\n\"\"\"\ncols = ['Metacritic Critic Score', 'Metacritic Reviews', 'Metacritic User Score', \n        'Metacritic User Reviews', 'AOTY Critic Score', 'AOTY Critic Reviews',\n       'AOTY User Score', 'AOTY User Reviews']\nfor col in cols:\n    print(data_2000[col].describe())\n    print('-'*50)\n\"\"\"\nThere's an outlier in the Metacritic User Score, the values goes from 0 to 10 and the max value is 80, so we before making any assumption let's find which record has that outlier\n\"\"\"\ndata_2000[data_2000['Metacritic User Score'] == 80.0]\n\"\"\"\nAccording to Metacritic the User Score for this album is 8.0\n![imagen.png](attachment:imagen.png)\nSo i'm going to transform that value to the actual scale\n\"\"\"\ndata_2000['Metacritic User Score'] = data_2000['Metacritic User Score'].replace(80.0, 8.0)\ndata_2000['Metacritic User Score'].describe()\n\"\"\"\n## Finding and filling NaN data\n\"\"\"\ndisplay(data_2000.isnull().sum())\ndisplay(data_2000.size)\n\"\"\"\nFirst, i'm going to multiply the Metacritic User Score by 10, so in that way it has the same scale as the other columns. In the case of missing data, i'm going to fill the missing values in the Title, Release Month, Release Day, Label and Genre with \"Unknown\". In the case of Metacritic scores i'm going to fill them using the average user score\/review and the average critic score\/review according to the genre\n\"\"\"\ndata_2000['Metacritic User Score'] = data_2000['Metacritic User Score'] * 10\ncols = ['Title', 'Release Month', 'Release Day', 'Label', 'Genre']\nfor col in cols:\n    data_2000[col].fillna('Unknown', inplace=True)\n    \ndata_2000.isnull().sum()\ncolumns = ['Metacritic Critic Score', 'Metacritic Reviews', 'Metacritic User Score', 'Metacritic User Reviews']\nfor genre in data_2000['Genre'].unique():\n    for col in columns:\n        value = round(data_2000.loc[data_2000['Genre'] == genre,  col].mean(), 0)\n        data_2000.loc[(data_2000['Genre'] == genre) &  (data_2000[col].isna()), col] = value\n\ndata_2000.isnull().sum()\n\"\"\"\nThere are still some NaN, let's explore them to see why weren't filled. But it looks like there might be albums that did not have any review\n\"\"\"\nmissing = data_2000[data_2000['Metacritic User Score'].isnull()]\nmissing.Genre.value_counts()\nmissing[missing['Genre'] == 'Folk Metal']\n\"\"\"\nFirst i created a genre count to find how many rows have NaN data. Some of the genres are not that popular, like Folk Metal. But at the same time they have reviews in the AOTY columns. So i'm going to run the for loop that i wrote to fill the NaN values with the mean value for each genre using the mean value of the AOTY column.\n\"\"\"\ncols = [['Metacritic Critic Score', 'AOTY Critic Score'],\n        ['Metacritic Reviews', 'AOTY Critic Reviews'],\n        ['Metacritic User Score', 'AOTY User Score'],\n        ['Metacritic User Reviews', 'AOTY User Reviews']]\n\nfor genre in data_2000['Genre'].unique():\n    for col, x in cols:               \n        value = round(data_2000.loc[data_2000['Genre'] == genre,  x].mean(), 0)\n        data_2000.loc[(data_2000['Genre'] == genre) &  (data_2000[col].isna()), col] = value\n\ndata_2000.isnull().sum()\ndata_2000[data_2000['Genre'] == 'Folk Metal']\n\"\"\"\nTo do the EDA i'm going to use the mean value for critics and users scores and the sum of the number of reviews\n\"\"\"\ndata_2000['Critic Score'] = round(data_2000[['Metacritic Critic Score', 'AOTY Critic Score']].mean(axis=1), 0)\ndata_2000['Critic Reviews'] = round(data_2000[['Metacritic Reviews', 'AOTY Critic Reviews']].sum(axis=1), 0)\ndata_2000['User Score'] = round(data_2000[['Metacritic User Score', 'AOTY User Score']].mean(axis=1), 0)\ndata_2000['User Reviews'] = round(data_2000[['Metacritic User Reviews', 'AOTY User Reviews']].sum(axis=1), 0)\n\ndata_clean = data_2000[['Artist', 'Title', 'Release Month', 'Release Day', 'Release Year', 'Format',\n              'Label', 'Genre', 'Critic Score', 'Critic Reviews', 'User Score', 'User Reviews']].copy()\n\ndata_clean.head()\n\"\"\"\n## Analysis\n\n### Best Albums for each year according to User Scores\n\"\"\"\nyears = [i for i in range(2000, 2021)]\nfor year in years:\n    data_year = data_clean[data_clean['Release Year'] == year]\n    score = data_year['User Score'].max()\n    secondary_df = data_year[data_year['User Score'] == score]\n    artist = secondary_df['Artist'].tolist()\n    album = secondary_df['Title'].tolist()\n    genre = secondary_df['Genre'].tolist()\n    album_format = secondary_df['Format'].tolist()\n    for i in range(0, len(artist)):\n        print('{}'.format(year))\n        print('\"{}\" by {} with a score of {}. Genre: {}. Format: {}'.format(album[i], artist[i].upper(), score, genre[i], album_format[i]))\n        print('-'*20)\n\"\"\"\nThere are 45 records on the list some years have at least two records considered as the best album of the year by the users. 2000 has two entries with \"Kid A\" by Radiohead and \"Lift your Skinny Fist Like Antennas to Heaven\" by Godspeed you! Black Emperor with a score of 90.\n\nThe year 2002 contains five entries with \"Yankee Hotel Foxtrot\" by Wilco, \"Songs for the Deaf\" by Queens of the Stone Age, \"You Forgot It In People\" by Broken Social Scene, \"Turn On The Bright Lights\" by Interpol, and \"October Road\" by James Taylor with a score of 88.\n\n2003 contains 15 entries with notable mentions to \"Ghosts of the Great Highway\" by Sun Kil Moon, \"The Black Album\" by Jay-Z, \"The Meadowlands\" by The Wrens with a score of 86. This is also the year with the fewest score.\n\n2016 contains five entries with notable mentions to \"Blackstar\" by David Bowie, which was his final studio album (he died two days after the album was released.) , \"A Moon Shaped Pool\" by Radiohead, and \"Atrocity Exhibition\" by Danny Brown with a score of 88.\n\n2017 has two entries, \"Melodrama\" by Lorde and \"Flower Boy\" by Tyler, The Creator. In 2020 the best album so far was \"Song Machine, Season One: Strange Timez\" by Gorillaz.\n\nThe most significant score was 94 in 2005's \"10th Avenue Freakout\" by FOG, 2006's \"Half The Perfect World\" by Madeleine Peyroux, and 2020s \"Song Machine, Season One: Strange Timez\" by Gorillaz.\n\nIt's also important to mention that Radiohead had three records on the list and Kendrick Lamar had two. It also looks like rock albums were really popular in the first years of the 2000s with at least 17 entries between 2000 and 2010 after 2010 rock albums only have three entries. After 2010 the established genres are pop, hip hop, and country.\n\"\"\"\n\"\"\"\n### Most hyped records by year according user reviews\n\"\"\"\nyears = [i for i in range(2000, 2021)]\nfor year in years:\n    data_year = data_clean[data_clean['Release Year'] == year]\n    score = data_year['User Reviews'].max()\n    secondary_df = data_year[data_year['User Reviews'] == score]\n    artist = secondary_df['Artist'].tolist()\n    album = secondary_df['Title'].tolist()\n    for i in range(0, len(artist)):\n        print('Most hyped record in {} was \"{}\" by {} with {} user reviews'.format(year, album[i], artist[i].upper(), score))\n        print('-'*20)\n\"\"\"\nHype doesn't always translate into quality is one of the conclusions that we can make with this list. Most of the albums in this list aren't in the best albums list with some exceptions like Radiohead's \"Kid A\" (2000) and Kendrick Lamar's \"good kid, m.A.A.d. city\" (2007). The most hyped artist in the list is Kanye West with five entries, Radiohead has three, Lady Gaga, Kendrick Lamar, and Taylor Swift has two entries. The album with more reviews was Taylor Swift's \"Folklore\" in 2020 with 16,556 user reviews. The album with the fewest reviews was \"Hail to the Thief\" by Radiohead in 2003 with 2,123 user reviews.\n\"\"\"\n\"\"\"\n### Artist that generate most hype\n\"\"\"\nfig, ax = plt.subplots(3, 1, figsize=(10,8))\n\ndata_artist = data_clean[['Artist', 'Critic Reviews', 'User Reviews']].copy()\n\ncritics = data_artist[['Artist', 'Critic Reviews']]\ncritics_group = critics.groupby('Artist').sum()\ncritics_group.sort_values(by=['Critic Reviews'], ascending=False, inplace=True)\nsns.barplot(ax=ax[0], x='Critic Reviews', y=critics_group.index[0:10], data=critics_group[0:10])\nax[0].set_title('Critics Hype')\nax[0].set_xlabel('')\nax[0].set_ylabel('')\n\nusers = data_artist[['Artist', 'User Reviews']]\nusers_group = users.groupby('Artist').sum()\nusers_group.sort_values(by=['User Reviews'], ascending=False, inplace=True)\nsns.barplot(ax=ax[1], x='User Reviews', y=users_group.index[0:10], data=users_group[0:10])\nax[1].set_title('Users Hype')\nax[1].set_xlabel('')\nax[1].set_ylabel('')\n\ndata_artist['total_hype'] = data_artist['Critic Reviews'] + data_artist['User Reviews']\ndata_artist = data_artist[['Artist', 'total_hype']]\ndata_artist_group = data_artist.groupby('Artist').sum()\ndata_artist_group.sort_values(by=['total_hype'], ascending=False, inplace=True)\nsns.barplot(ax=ax[2], x='total_hype', y=data_artist_group.index[0:10], data=data_artist_group[0:10])\nax[2].set_title('Total Hype')\nax[2].set_xlabel('')\nax[2].set_ylabel('') \n\nplt.suptitle('Top 10 artist that generates most hype')\nplt.subplots_adjust(hspace=0.3)\nsns.despine(left=False, bottom=False)\n\"\"\"\nFor critics, Animal Collective generates the most hype followed by Kanye West and Of Montreal. For fans Taylor Swift, Kanye West and Lady Gaga head the list. In total the most hyped artist are Taylor Swift, Kanye West and Lady Gaga. Huge notable mention to BTS in the fans hype figure with almost 20,000 reviews.\n\nThe differences happen because users tend to hype those popular artists while critics like to give their hype to not so popular or alternative artists.\n\nIt's equally interesting to see that in the total hype the user's reviews have more weight than the critic's reviews, again this is because popular artists tend to have more reviews from their fans.\n\"\"\"\n\"\"\"\n### Most critically acclaimed artists of the millenium according to Metacritic\n\"\"\"\nfig, ax = plt.subplots(2, 1, figsize=(10,8))\ndata_artist = data_clean[['Artist', 'Critic Score']]\ndata_artist_group = data_artist.groupby('Artist').sum()\ndata_artist_group.sort_values(by=['Critic Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[0], x='Critic Score', y=data_artist_group.index[0:10], data=data_artist_group[0:10])\nax[0].set_title('Total Critic Score')\nax[0].set_xlabel('')\nax[0].set_ylabel('')\n\n\ndata_artist = data_2000[['Artist', 'Critic Score']]\ndata_artist_group = data_artist.groupby('Artist').mean()\ndata_artist_group.sort_values(by=['Critic Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[1], x='Critic Score', y=data_artist_group.index[0:10], data=data_artist_group[0:10])\nax[1].set_title('Average Critic Score')\nax[1].set_xlabel('')\nax[1].set_ylabel('')\n\nplt.suptitle('Top 10 most critically artists from 2000-2020 according to critics')\nplt.subplots_adjust(hspace=0.2)\nsns.despine(left=False, bottom=False)\n\"\"\"\nTo find the most critically artists from 2000 to 2020 according to critics, I added the critic scores for each album, so obviously, artists that release an album each year might have a better score than artists that take more time to release an album. If I use the mean critic score the list change completely and will favor those artists that released one or two albums in the period. It's also interesting to see that none of the most hyped artists appear in neither of the two lists.\n\nAs I said before the first plot shows the 10 most critically artists from 2000 to 2020 according to the total score given by critics. This list is headed by Guided By Voices (19 records from 2000 to 2020) with a total score of 1400, then it's followed by Animal Collective (11 albums and 7 EPs from 2000 to 2020). In the next table, I show the number of records and total score for the top 5 artist that generates more hype.\n\n|Artist|Number of records in the period|Total Score|\n|:----:|:-----------------------------:|:---------:|\n|Taylor Swift|8 LP|602|\n|Kanye West|9 LP|689|\n|Lady Gaga|5 LP, 3 EP|551|\n|Lana Del Rey| 5 LP, 2EP|519|\n|Eminem| 9 LP|588|\n\nUsing the average score puts D'Angelo and The Vanguard in the first place but this artist only has one LP in the DataFrame, Ali Farka Tour\u00e9 in the second place also has one LP in the DataFrame although it has 3 LPs in the period 2000-2020. Using the average score the top 5 most hyped artist got the next scores\n\n|Artist|Number of records in the period|Average Score|\n|:----:|:-----------------------------:|:---------:|\n|Taylor Swift|8 LP|75|\n|Kanye West|9 LP|77|\n|Lady Gaga|5 LP, 3 EP|69|\n|Lana Del Rey| 5 LP, 2EP|74|\n|Eminem| 9 LP|65|\n\"\"\"\n\"\"\"\n### Genres that generates the most feedback from critics and users\n\nIn this item, I'll show the top 10 genres that generate the most feedback from critics, users and combined as I did in the most hyped section.\n\"\"\"\nfeedback = data_clean[['Genre', 'Critic Reviews', 'User Reviews']].copy()\nfeedback = feedback[feedback['Genre'] != 'Unknown']\nfeedback['Total'] = feedback['Critic Reviews'] + feedback['User Reviews']\n\nfig, ax = plt.subplots(3, 1, figsize=(10,8))\n\ncritics = feedback[['Genre', 'Critic Reviews']]\ncritics_group = critics.groupby('Genre').sum()\ncritics_group.sort_values(by=['Critic Reviews'], ascending=False, inplace=True)\nsns.barplot(ax=ax[0], x='Critic Reviews', y=critics_group.index[0:10], data=critics_group[0:10])\nax[0].set_title('From Critics')\nax[0].set_xlabel('')\nax[0].set_ylabel('')\n\nusers = feedback[['Genre', 'User Reviews']]\nusers_group = users.groupby('Genre').sum()\nusers_group.sort_values(by=['User Reviews'], ascending=False, inplace=True)\nsns.barplot(ax=ax[1], x='User Reviews', y=users_group.index[0:10], data=users_group[0:10])\nax[1].set_title('From Users')\nax[1].set_xlabel('')\nax[1].set_ylabel('')\n\ntotal = feedback[['Genre', 'Total']]\ntotal_group = total.groupby('Genre').sum()\ntotal_group.sort_values(by=['Total'], ascending = False, inplace=True)\nsns.barplot(ax=ax[2], x='Total', y=total_group.index[0:10], data=total_group[0:10])\nax[2].set_title('In Total')\nax[2].set_xlabel('')\nax[2].set_ylabel('')\n\nplt.suptitle('Genres that generate most feedback from 2000-2020')\nplt.subplots_adjust(hspace=0.3)\nsns.despine(left=False, bottom=False)\n\"\"\"\nThe similar phenomena that happen with the most hyped artists happen with the most hyped genres, in the total users reviews have more weight than the critic's reviews. Critics tend to review not so established genres, with the exception of Hip Hop. It's fascinating to see that Folk is still reviewed by critics and one can affirm that classic artists like Bob Dylan or Joan Baez or modern folk artists like First Aid Kit, still have an impact and that social and political protest themes still have a place in music. The same can be said for Hip Hop, although some modern hip hop artists now sing about cars, drugs and girls.\n\nFor fans hip hop, pop (and its variants) and alternative rock are the most popular and most of the reviews happen thanks to fandoms. It's delightful to see K-pop in 6th place, this genre has become really popular in the last 10 years and it's taking a good portion of the music market. It's also important to add that if we join all the variants of pop and rock they will occupy the top two spots.\n\"\"\"\n\"\"\"\n### Albums with the most negative reception from critics\n\"\"\"\nbad = data_clean[['Artist', 'Title', 'Critic Score']].copy()\nbad.sort_values(by=['Critic Score'], ascending= True, inplace=True)\nbad[0:10]\n\"\"\"\nThe worst album according to critics is \"Playing with Fire\" by Kevin Federline which is described as \"*Disposable and dumb*\" and \"*generic and instantly forgettable*.\" This is Federline's only album and was produced by Britney Spears. For most of the critics, this might be one of the worst albums ever made. At Metacritic, for example, it's the lowest-rated album on site. People Magazine gave it a half star, and Rolling Stone gave it one star over five.\n\n\"The Female Boss\" by Tulisa, which was her first solo album, received mostly negative critics. The Independent on Sunday from the UK says \"*Like most pop albums, it's front-loaded. The banging club tunes, like the chart-topping \"Young\" are at the start, then it slumps into a series of obligatory ballads on which her unremarkable voice is somewhat stretched*\", The site musicOHM.com says \"*For the most part, however, The Female Boss is a cynical and dire product which invites the riposte: Tulisa, you're fired*.\"\n\n\"Human\" by Three Days Grace was described by William Hughes at Kerrang Magazine as \"*Insipid... Listening to Human is like eating wallpaper paste.*\" The rest of the critics also gives this record mediocre scores, for example, Toronto Sun gave it a score of two over five. Revolver Magazine gave it 3 stars, and Ultimate Guitar gave it 6,7\/10\n\nA constant for most of the artists in the list is that the lyrics aren't good or that the album sounds exactly like any other album from the same artist, also some of the albums in the list are albums were the artist tried to do something new (\"Rebirth\" was an album where Lil Wayne tried to fuse Rock and Rap.) , others like \"Human\" by Three Days Grace were albums where the lead singer was new.\n\n\n### Albums with the most negative reception from users\n\"\"\"\nbad = data_clean[['Artist', 'Title', 'User Score']].copy()\nbad.sort_values(by=['User Score'], ascending= True, inplace=True)\nbad[0:10]\n\"\"\"\nFor fans, Kevin Federline's \"Playing with Fire\" is the worst album on the list. ACreativeName in AOTY website says \"*absolute legend. This guy sounds like a dad who just heard a rap song for the first time. Like it really sounds like he doesn't fully understand any of what he's saying.*\", Benny says \"*No wonder this was released on Halloween cuz it scary to think that hip hop has hit it lowest point in 2006*\", bl0nded says \"*His lyrics are generic, his flows are average, his beats are bad, and his rhymes are horrible*.\" On Metacritic the user reviews are similar, davim says \"*...It's effectively saying, it wasn't even worth the time, money, and effort in the studio to create. On this occasion, however, this album really is a zero if there ever was one. Never has a rap album flowed so badly. Lyrically, it is easily one of the worst albums I have ever come across...*.\" JohnC says \"*Putting all of the news headlines aside, and really listening to this material, all I can say is, you have to be kidding me. An absolute joke...*\"\n\nLil Xan's \"TOTAL XANARCHY\" it's not a well-received album, for critics, it has a score of 49 at Metacritic and 50 at AOTY. Users like TheRealEminem says \"*Honestly, this album is the worst album of all time.*\" MinatoArisato says \"*Not many albums are actually able to cause me physical pain as this one does.*\" Wallnnut says \"*This was easily among the worst rap albums I've listened to in quite some time. Tracks consist of uninteresting beats, paired with generic and repetitive lyrics...*\".\n\nRobin Thicke's \"Paula\" has a Metascore of 49, and most of the critics say that it's an odd, disjointed album and that the lyrics reach the creepy territory. Thicke dedicated that album to her ex-wife Paula Patton. The fans have harsher opinions, \"*\"Paula\", in the end, doesn't only sound desperate to win\/get Paula Patton back, but, instead, a plea to fans not to forget him*\", \"*He spends most of the time portraying himself as the hurt one in the relationship, despite the reality of the situation, and when he doesn't he's either a slimy sex-crazed douchebag or seems to think using a bunch of dime a dozen \"wasn't there for you\" cliches alone will make him not come off like the bad guy.*\"\n\nThe constant with user's critics is how disappointed they feel with the result of the album. In some cases, they agree that the album is bad.\n\n### Most Hyped EP according to Critics\n\"\"\"\nep = data_clean[data_clean['Format'] == 'EP'].copy()\nep = ep[['Artist', 'Title', 'Critic Reviews']]\nep.sort_values(by=['Critic Reviews'], ascending=False, inplace=True)\nep[0:10]\n\"\"\"\nThe critic hype list is led by Mac DeMarco's \"Another One\", this LP has a Metascore of 75 and a Critic Score of 74 at AOTY, for fans, it has a score of 8.4 at Metacritic and 75 at AOTY and both critic and fans describe it as \"*...The most technically refined album DeMarco has produced.*\"\n\n\"Do It Again\" by R\u00f6yskopp & Robin also has really good scores in both Metacritic and AOTY, reading the critics this LP was really expected by both critics and users because R\u00f6yskopp and Robin had collaborated a couple of times before and the result was pretty good.\n\nB\u00f6lzer's \"Lese Majesty\" which according to both critics and users is a universally acclaimed record. A similar situation happens with Beirut's \"March of the Zapotec\/Holland EP.\" The constant with this list is that the hype, measured in the number of reviews, translates in scores over 75, and most of the time users agree with the good reception of the album. \n\n### Most Hyped EP according to Users\n\"\"\"\nep = data_clean[data_clean['Format'] == 'EP'].copy()\nep = ep[['Artist', 'Title', 'User Reviews']]\nep.sort_values(by=['User Reviews'], ascending=False, inplace=True)\nep[0:10]\n\"\"\"\nIn the fans hype list, we see the power of K-pop fans the only artist that isn't from Korea is Lady Gaga, and I need to mention that \"The Fame Monster\" was released in 2008. Most of the albums in this list were released between 2017 and 2020.\n\nBlackPink's \"Square Up\" was released on June 15, 2018. The EP has a Critic Score of 80 and a user score of 68. For fans, the EP isn't that good and it looks like they were expecting something similar to their previous release. However one of the cool things about K-pop is that the artists use a different concept in each release not only in the visual aspect but also in the music. So in this release, they might use a lot of EDM tracks and the next one might be a strong pop ballad.\n\nTwice, which was Korea's most popular girl group before BlackPink's debut occupies the second and sixth spot with \"Fancy You\" (Critic Score: 80, User Score: 76) and \"More & More\" (Critic Score: 60, User Score: 67). Fancy You is described as \"*a retro-electro pop album with surprisingly tastefully implemented elements of rock and soul.*\" Meanwhile \"More & More\" is described as \"*a solid slice of not just K-pop but modern pop as a whole, nothing too experimental but still nothing to scoff at.*\", this EP was released through Universal Music's Republic Records Company and it looks like they were targeting the western market.\n\nA constant here is that most of the albums in this list has critic score around 75-80 and lower user scores in some cases. That's because most western fans keep thinking about K-pop as a linear concept instead of what it really is a genre (and a market) where they use a different concept in each release until the popularity of the group is over.\n\"\"\"\n\"\"\"\n\n\n### Months well recieved by critics and users\n\"\"\"\nfig, ax = plt.subplots(4, 1, figsize=(10,12))\ncritics = data_clean[['Release Month', 'Critic Score']].copy()\ncritics_group = critics.groupby('Release Month').sum()\ncritics_group.sort_values(by=['Critic Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[0], x='Critic Score', y=critics_group.index, data=critics_group)\nax[0].set_title('By Critics')\nax[0].set_xlabel('Total Score')\nax[0].set_ylabel('')\n\nusers = data_clean[['Release Month', 'User Score']].copy()\nusers_group = users.groupby('Release Month').sum()\nusers_group.sort_values(by=['User Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[1], x='User Score', y=users_group.index, data=users_group)\nax[1].set_title('By Users')\nax[1].set_xlabel('Total Score')\nax[1].set_ylabel('')\n\ncritics = data_clean[['Release Month', 'Critic Score']].copy()\ncritics_group = critics.groupby('Release Month').mean()\ncritics_group.sort_values(by=['Critic Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[2], x='Critic Score', y=critics_group.index, data=critics_group)\nax[2].set_title('By Critics')\nax[2].set_xlabel('Mean Score')\nax[2].set_ylabel('')\n\n\nusers = data_clean[['Release Month', 'User Score']].copy()\nusers_group = users.groupby('Release Month').mean()\nusers_group.sort_values(by=['User Score'], ascending=False, inplace=True)\nsns.barplot(ax=ax[3], x='User Score', y=users_group.index, data=users_group)\nax[3].set_title('By Users')\nax[3].set_xlabel('Mean Score')\nax[3].set_ylabel('')\n\nplt.suptitle('Months Well Recieved')\nplt.subplots_adjust(hspace=0.4)\nsns.despine(left=False, bottom=False)\n\n\"\"\"\nIf I sum the score of each album released on each month its found that both critics and fans the best received months are September, October, March, May, and June, it's difficult to say if in these months the albums with the best scores are released if we look at the mean score, which I think it's a better metric to use, we see there isn't a big difference in the scores and looks like music and the quality of the music doesn't depend on the month of the year.\n\n### Records not well recieved by users but are the most acclaimed by the critic\n\"\"\"\nrecords = data_clean[['Artist', 'Title', 'Critic Score', 'User Score']].copy()\nrecords.sort_values(by=['Critic Score'], inplace=True, ascending=False)\nrecords = records[(records['Critic Score'] >= 81) & (records['User Score'] <= 39)]\nrecords\n\"\"\"\nAccording to Metacritic, the \"universal acclaim\" indicator starts at 81 and the \"Generally unfavorable reviews\" starts at 39. Using these scores I only found one album which is universally acclaimed by critics but disliked by fans. For critics, Claro Intelecto's \"Reform Club\" is \"*Rich and intelligent, it's a welcome blow of muted midnight compulsions, swimming in its own tides against the sea of bombast and extravagance that's taken root in recent years.*\", \"*Reform Club is full of conventional beauty; protracted strings and pads which soar, pulse, float or shimmer on a dub-tinged substrate.*\", \"*A little older and a little more experienced, the sound of Claro here is slower in BPM but more graceful as a result.*\". However fans didn't wrote anything, in Metacritic the only User Review actually says that \"*This is a great album. I am listening to this album over and over again since more than a year.*\"\n\nSo I decided to decrease the Critic Score to 75 and see if there's another record that meets these conditions\n\"\"\"\nrecords = data_clean[['Artist', 'Title', 'Critic Score', 'User Score']].copy()\nrecords.sort_values(by=['Critic Score'], inplace=True, ascending=False)\nrecords = records[(records['Critic Score'] >= 75) & (records['User Score'] <= 39)]\nrecords\n\"\"\"\nIt's the same situation, there's good reviews made by the critics and zero reviews made by fans and most of them are spam like \"*I don't like his beard*\" read at Toby Keith's \"Bullets in the Gun\" page at AOTY\n\"\"\"\n\"\"\"\n### Records not well recieved by the critics but acclaimed by the fans\n\"\"\"\nbad = data_2000[['Artist', 'Title', 'User Score', 'Critic Score']].copy()\nbad.sort_values(by=['User Score'], inplace=True, ascending=False)\nbad = bad[(bad['User Score'] >= 81) & (bad['Critic Score'] <= 39)]\nbad\n\"\"\"\nI used the same criteria to find the records that fans like and critics don't but there was no result. I had to change the criteria to a score over 75 for User Score and 45 for Critic Score to find at least one record\n\"\"\"\nbad = data_2000[['Artist', 'Title', 'User Score', 'Critic Score']].copy()\nbad.sort_values(by=['User Score'], inplace=True, ascending=False)\nbad = bad[(bad['User Score'] >= 75) & (bad['Critic Score'] <= 45)]\nbad\n\"\"\"\nEnya isn't popular with the critics, her average career score at Metacritic is 48, at AOTY is 64. This particular album is praised by fans as \"*One of the best albums of Enya.*\", \"*One of enya's better album. I'm not sure what the critics are smoking but it must be affecting their judgment skills.*\", \"*This isn't the best thing of course but i did enjoy my listen.*\", however for critics (and myself) \"*Unfortunately, A Day Without Rain, Enya's first new studio album in five years, lacks the edge that could pry it loose from the New Age niche.*\", \"*Essentially, it sounds exactly like each of her four previous albums.*\", \"*Unless you're bound in an herbal body wrap, there's simply no acceptable reason to listen to this New Age nonsense.*\". \n\nAnd my favourite, made by Rolling Stone Magazine \"*If Enya were a Pokemon, she'd be Jigglypuff, the little pink monster who renders her opponents powerless by singing them to sleep. This isn't a bad thing: We all need some rest. But after the course of several albums, each like the one before, the Irish multi-instrumentalist-singer-composer's skill at ephemeral sonic watercolors has grown wearisome, like a relative who tells the same stories every holiday. You'd think after taking stock of her career via '97's best-of collection, and hearing her Celtic-New Age hybrid diluted and overpopularized via Titanic, she'd try something different, like trip-hop or trance or chamber music. Instead, her first album of new material in five years retraces less than thirty-five minutes of familiar steps. Swaying, swirling songs such as \"Only Time\" could have appeared on any one of her albums, as the airy arrangements haven't changed a single plink or plunk. Even Pokemon: The First Movie and Pokemon: The Movie 2000 had slightly different plots.*\" Barry Walters you are wild!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8b53bbc5cefcc9'}"}
{"id":"39931","text":"# 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\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\npd.set_option('display.max_columns', None)\n\ndf = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/train.csv\", index_col=0)\n# Selecionei um subconjunto das vari\u00e1veis de entrada para fins de simplifica\u00e7\u00e3o\nFEATURES_ANALISAR = ['MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea',  'Street', 'Alley', 'Neighborhood', 'HouseStyle', 'OverallQual', 'OverallCond', 'YearBuilt', 'CentralAir', 'BsmtCond', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'KitchenQual', 'Fireplaces', 'SalePrice']\ndf = df.loc[:, FEATURES_ANALISAR]\ndf\n\"\"\"\nOlhando na tabela (e em alguma descri\u00e7\u00e3o do dataset, se dispon\u00edvel), decidimos o que \u00e9 categ\u00f3rico e num\u00e9rico\n\"\"\"\nNominalCategorical = ['MSSubClass', 'MSZoning', 'Street', 'Alley', 'Neighborhood', 'HouseStyle', 'CentralAir', 'BsmtCond', 'KitchenQual']\nOrdinalCategorical = ['OverallQual', 'OverallCond', 'YearBuilt']\nNumeric = ['LotFrontage', 'LotArea', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'Fireplaces', 'SalePrice']\n\n\"\"\"\nTamanho do dataset:\n\"\"\"\nprint(\"{} linhas\\n{} colunas\/features.\".format(df.shape[0], df.shape[1]))\n\"\"\"\n# Medi\u00e7\u00e3o, dele\u00e7\u00e3o e imputa\u00e7\u00e3o de dados ausentes\n\"\"\"\n# Funcao do Pandas usada para contar o numero de valores vazios de cada coluna\ndata = df.isna().sum(axis=0)\ny = list(range(df.shape[1]))\nx = data.values\n\n# Criamos uma figura\nfig, ax = plt.subplots(figsize=(8, 10))\n\n# Plota as barras\nax.barh(y=y, width=x)\n\n# Adiciona informa\u00e7\u00f5es no gr\u00e1fico\nax.set_yticks(y)\nax.set_yticklabels(df.columns.values)\nax.set_title(\"Quantidade de vari\u00e1veis ausentes por coluna\")\nplt.show()\n\"\"\"\nTemos 3 features que apresentam valores ausentes. Vamos analisar uma por uma come\u00e7ando por \n### Alley\n\"\"\"\ndf['Alley'].value_counts()\n\"\"\"\nComo a feature Alley tem a grande maioria dos dados ausentes, \u00e9 do tipo categ\u00f3rica e suas categorias est\u00e3o divididas em n\u00fameros muito similares (50 e 41), decidimos por excluir esta coluna da an\u00e1lise:\n\"\"\"\nFEATURES_ANALISAR.remove('Alley')\ndf = df.loc[:, FEATURES_ANALISAR]\ndf_original = df.loc[:, FEATURES_ANALISAR]\ndf\n\"\"\"\n### LotFrontage\n\nComo LotFrontage pode ser considerado como uma feature num\u00e9rica, podemos imputar os dados ausentes usando a t\u00e9cnica de Imputa\u00e7\u00e3o por Regress\u00e3o Linear.\n\nPor motivos de simplicidade, ser\u00e1 modelado uma regress\u00e3o para predizer os dados ausentes de LotFrontage levando em considera\u00e7\u00e3o apenas LotArea e SalePrice, ambas vari\u00e1veis num\u00e9ricas.\n\"\"\"\n# Criamos um dataframe com os dados de LotFrontage, Lot Area e SalePrice\ndf_imput_regress = pd.concat([df['LotFrontage'], df['LotArea'], df['SalePrice']], axis=1)\ndf_imput_regress.head()\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\n\n# Criamos um objeto que far\u00e1 a Imputa\u00e7\u00e3o por Regress\u00e3o\nimp_mean = IterativeImputer(random_state=0)\n# Treinamos a regress\u00e3o com os dados disponiveis\nimp_mean.fit(df_imput_regress.values)\n\n# Agora, faremos uma regress\u00e3o nos mesmos dados usados no treinamento, para\n# gerar valores num\u00e9ricos para substituir os valores ausentes de LotFrontage\nX = df_imput_regress.values\nregr_output = imp_mean.transform(X)\nregr_output\n# Agora substituimos a primeira coluna de X (output do regressor) no nosso dataframe df\ndf['LotFrontage'] = regr_output[:, 0]\n\"\"\"\nAgora, como podemos perceber, LotFrontage n\u00e3o tem mais dados nulos\n\"\"\"\ndf['LotFrontage'].isna().sum()\n\"\"\"\n### BsmtCond\n\n\u00c9 uma vari\u00e1vei categ\u00f3rica ordinal. Portanto, n\u00e3o faria sentido substituir por um n\u00famero decimal, como por exemplo uma m\u00e9dia ou uma regress\u00e3o.\n\nEnt\u00e3o, iremos substituir os dados ausentes pelos dados que aparecem com maior frequ\u00eancia nesta feature.\n\"\"\"\ndf['BsmtCond'].value_counts()\n\"\"\"\nPodemos perceber que 'TA' \u00e9 a categoria com maior presen\u00e7a. Iremos substitu\u00ed-la nos dados ausentes:\n\"\"\"\n#.fillna substitui o argumento nos dados ausentes\ndf['BsmtCond'] = df['BsmtCond'].fillna('TA')\n\"\"\"\n#### Todos os dados ausentes foram deletados ou substitu\u00eddos:\n\"\"\"\ndf.isna().sum(axis=0)\n\"\"\"\n# Outliers\n\"\"\"\n\"\"\"\nPara detectar outliers, vamos utilizar 2 t\u00e9cnicas:\n - An\u00e1lise visual (atrav\u00e9s de boxplot e histogramas)\n - Z-Test, SE tiver alguma vari\u00e1vel float com distribui\u00e7\u00e3o normal ou normal com leve assimetria\n \nAl\u00e9m disto, neste momento vamos apenas verificar outliers de vari\u00e1veis codificadas de forma num\u00e9rica\n\"\"\"\nselected_columns = Numeric + OrdinalCategorical\ndf[selected_columns].head()\n\n\"\"\"\n### Detec\u00e7\u00e3o visual\n\"\"\"\nfig, axes = plt.subplots(nrows=1, ncols=10, figsize=(15, 5))\n\nfor i,col in enumerate(selected_columns):\n    axes[i].boxplot(df[col])\n    axes[i].set_title(col)\n\nplt.tight_layout()\nfig, axes = plt.subplots(nrows=5, ncols=2, figsize=(15, 15))\n# Quando criamos graficos com multiplas dimensoes, axes vira um array 2D. Ent\u00e3o\n# vamos transformar ele numa lista para iterar durante a cria\u00e7\u00e3o do grafico\naxes = axes.flatten()\n\n# Iterando de grafico em grafico\nfor i,ax in enumerate(axes):\n    ax.hist(df[selected_columns[i]])\n    ax.set_title(selected_columns[i])\n\nplt.tight_layout()\n\"\"\"\nVamos fazer um gr\u00e1fico de dispers\u00e3o 2D das vari\u00e1veis LotArea e LotFrontage para verificar a rela\u00e7\u00e3o entre elas\n\"\"\"\nfig, ax = plt.subplots()\n\nax.scatter(x=df['LotArea'], y=df['LotFrontage'])\nplt.show()\n\"\"\"\nAnalisando os histogramas, diagrama de caixas e gr\u00e1fico de dispers\u00e3o, decidimos filtrar duas features:\n - Valores de LotArea maiores que 100000 ser\u00e3o exclu\u00eddos\n - Valores de LotFrontage maiores que 200 ser\u00e3o exclu\u00eddos\n\"\"\"\nprint(\"Tamanho do dataset antes dos filtros: {}\".format(df.shape))\n\nmask = df['LotFrontage'] < 200\ndf = df[mask]\nmask = df['LotArea'] < 100000\ndf = df[mask]\n\nprint(\"Tamanho do dataset depois dos filtros: {}\".format(df.shape))\n\"\"\"\n### Detec\u00e7\u00e3o usando Z-Test\n\"\"\"\n\"\"\"\nPara a vari\u00e1vel SalePrice, vamos usar o m\u00e9todo Z-Test para remover outliers:\n\"\"\"\nfrom scipy import stats\n\n# df[\"SalePrice\"]\nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))\n\ndata = df[\"SalePrice\"]\nz_data = np.abs(stats.zscore(df[\"SalePrice\"]))\nax[0].hist(data)\nax[0].set_xlabel(\"Valores reais de SalePrice\")\nax[1].hist(z_data)\nax[1].set_xlabel(\"Valores Z de SalePrice\")\nax[1].vlines(x=3, ymin=0, ymax=850, colors='red')\nplt.show()\n\"\"\"\nVamos remover todos os dados com Z >= 3\n\"\"\"\nprint(\"Tamanho do dataset antes dos filtros: {}\".format(df.shape))\n\nmask = np.abs(stats.zscore(df[\"SalePrice\"])) < 3\ndf = df[mask]\n\nprint(\"Tamanho do dataset depois dos filtros: {}\".format(df.shape))\n\"\"\"\n# Feature Engineering\n\"\"\"\n\"\"\"\nVamos criar uma nova feature de forma bem simples, dividindo a \u00c1rea do terreno pelo tamanho da frente do terreno, ou seja, LotArea\/LotFrontage\n\"\"\"\ndf['RatioAreaFrontage'] = df['LotArea'] \/ df['LotFrontage']\n\ndf[['RatioAreaFrontage', 'LotArea', 'LotFrontage']]\n\"\"\"\n# Feature Selection\n\"\"\"\n\"\"\"\nVamos continuar apenas com as vari\u00e1veis num\u00e9ricas e ordinais categ\u00f3rias codificadas em forma de n\u00fameros, por simplicidade.\n\nVamos descartar 1 feature usando o teste f-regression\n\"\"\"\nselected_columns = ['LotFrontage', 'LotArea', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'Fireplaces', 'OverallQual', 'OverallCond', 'YearBuilt', 'RatioAreaFrontage']\nx = df[selected_columns]\ny = df['SalePrice']\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import f_regression\n\n# k \u00e9 o numero de features que N\u00c3O ser\u00e3o jogadas foras. Vamos primeiro ver os resultados, depois eliminar alguma feature.\nk = x.shape[1]\n# Utilizamos um m\u00e9todo do sklearn para isso, usando a estrat\u00e9gia Chi Squared.\nselector = SelectKBest(f_regression, k=k)\nx_new = selector.fit_transform(x, y)\n\"\"\"\n#### Visualizando os resultados do f-regression\n\"\"\"\n# Utilizo o log10 pois os valores s\u00e3o ou muito grandes, ou muito pequenos\nscores = -np.log10(selector.pvalues_)\n\nx_plot = list(range(len(scores)))\n\nfig, ax = plt.subplots(figsize=(8, 4))\nplt.bar(x_plot, scores)\nax.set_title(\"Score do m\u00e9todo f-regression para Feature Selection\")\nax.set_xticks(x_plot)\nax.set_xticklabels(selected_columns, rotation=45)\nplt.show()\n\"\"\"\nPodemos perceber que a feature \"OverallCond\" apresenta os menores resultados, e portanto, vamos elimin\u00e1-la do nosso dataset.\n\"\"\"\nprint(\"Tamanho do dataset antes dos filtros: {}\".format(df.shape))\n\ndf = df.drop(['OverallCond'], axis=1)\n\nprint(\"Tamanho do dataset depois dos filtros: {}\".format(df.shape))\n\"\"\"\n# Feature Encoding\n\"\"\"\n\"\"\"\nOlhando para a tabela do dataset, podemos perceber que a feature \"CentralAir\" tem apenas 2 valores, correspondentes a verdadeiro e falso: 'Y' e 'N':\n\"\"\"\ndf['CentralAir'].value_counts()\n\"\"\"\nPortanto, levando em considera\u00e7\u00e3o que \u00e9 poss\u00edvel que a presen\u00e7a de ar condicionado central possa valorizar a casa, podemos codificar 'Y'=1 e 'N'=0:\n\"\"\"\ndf['CentralAir'].replace(to_replace='Y', value=1, inplace=True)\ndf['CentralAir'].replace(to_replace='N', value=0, inplace=True)\n\ndf['CentralAir'].value_counts()\n\"\"\"\n# Data Scaling\n\"\"\"\n\"\"\"\nVamos novamente apenas tratar de vari\u00e1veis codificadas como n\u00fameros\n\"\"\"\nselected_columns = ['LotFrontage', 'LotArea', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'Fireplaces', 'OverallQual', 'YearBuilt', 'RatioAreaFrontage', 'SalePrice']\ndf[selected_columns].describe()\n\"\"\"\nPodemos perceber na tabela acima que os existem valores m\u00ednimos que come\u00e7am em 21 (Lot Frontage), 1300 (Lot Area) e 26.9 (RatioAreaFrontage). Al\u00e9m disso, os valores m\u00e1ximos de muitas tabelas s\u00e3o valores altos, como 182 (LotFrontage), 70761 (LotArea), entre outros.\n\nIsso pode resultar em problemas para o treinamento de uma rede neural, ent\u00e3o, vamos normalizar esses dados usando o estalonador MinMax do sklearn:\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\ndata = df[selected_columns]\nscaler.fit(data)\n\"\"\"\nO escalonador MinMax est\u00e1 ajustado para os dados presentes em selected_columns.\nAgora iremos reescalonar estes dados e verificar se eles est\u00e3o dentro de um intervalo [0,1]:\n\"\"\"\n# Reescalonamos os dados\ndata_scaled = scaler.transform(data)\n\n# Criamos um dataframe para facilitar a visualiza\u00e7\u00e3o\ndata_scaled = pd.DataFrame(data_scaled)\n# \"Devolvemos\" os nomes das features e os \u00edndices para o dataframe\ndata_scaled.columns = selected_columns\ndata_scaled.index = df.index\n\ndata_scaled.describe()\n\"\"\"\nComo podemos ver, todos os valores m\u00ednimos est\u00e3o em 0 e todos os valores m\u00e1ximos est\u00e3o em 1. Os dados foram reescalonados com sucesso.\n\nAgora precisamos incorporar estes dados no nosso dataframe df:\n\"\"\"\ndf = df.drop(selected_columns, axis=1)\ndf = pd.concat([df, data_scaled], axis=1)\n\"\"\"\n## Dataset \"Inicial\"\n\"\"\"\ndf_original\n\"\"\"\n## Dataset \"Final\"\n\"\"\"\ndf\nimport pandas as pd\n\nprint(\"Trabalho 1 de IA\")\ndf = pd.read_csv(\"..\/input\/aula-2-ia-dataset\/CasasParaAlugar.csv\")\n\ndf\ndf.head()\ndf['city'].value_counts().head(10).plot.bar()\ndf['city'].value_counts().sort_index().plot.bar()\ndf['area'].value_counts().head(10).plot.bar()\ndf['bathroom'].value_counts().head(10).plot.bar()\ndf['animal'].value_counts().head(10).plot.bar()\ndf['hoa (R$)'].value_counts().sort_index().plot.area()\ndf.plot.scatter(x='area', y='hoa (R$)')\ndf.isnull().count()\nimport seaborn as sns\nsns.countplot(df['city'].head(20))\nax = sns.distplot(df['area'], bins = 20, kde = False)\nsns.boxplot(x='city',\n           y ='area',\n           hue = 'bathroom',\n           data = df)\nr = df.corr()\nsns.heatmap(r)\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\ndata_train = pd.read_csv('..\/input\/aula-2-ia-dataset\/CasasParaAlugar.csv')\n#data_test = pd.read_csv('...\/input\/aula-2-ia-dataset\/CasasParaAlugar.csv')\n\ndata_train.sample(3)\nsns.barplot(x=\"city\", y=\"area\", hue=\"bathroom\", data=data_train);\nsns.pointplot(x=\"city\", y=\"area\", hue=\"animal\", data=data_train,\n              palette={\"acept\": \"blue\", \"not acept\": \"pink\"},\n              markers=[\"*\", \"o\"], linestyles=[\"-\", \"--\"]);\n\"\"\"\n#### Existem muito mais an\u00e1lises que podem ser feitas, e neste dataset existem MUUITAS outras vari\u00e1veis que precisariam ser tratadas para o dataset ficar adequado para o treinamento de uma rede neural.\n\n#### Ainda assim, estes s\u00e3o exemplos de alguns dos passos envolvidos na an\u00e1lise e pr\u00e9 processamento de dados antes da etapa de modelagem.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4986b3dc2d5e41'}"}
{"id":"1845","text":"# 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\n!pip install rich\nimport re\nimport warnings\nimport string\nimport numpy as np \nimport random\nimport pandas as pd \nfrom scipy import stats\nimport missingno as msno\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nfrom plotly import graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\n\nfrom rich.console import Console\nfrom rich.theme import Theme\nfrom rich import pretty\n\nfrom PIL import Image\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LinearRegression\n\n\nfrom tqdm import tqdm\nimport os\nimport nltk\nimport spacy\nimport random\nfrom spacy.util import compounding\nfrom spacy.util import minibatch\n\nfrom collections import defaultdict\nfrom collections import Counter\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score, cross_validate\nfrom sklearn.metrics import (\n    mean_squared_error as mse, \n    make_scorer, \n    accuracy_score, \n    confusion_matrix\n)\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import backend\nfrom tensorflow.keras import optimizers, losses, metrics, Model\nfrom tensorflow.keras.metrics import RootMeanSquaredError\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.initializers import Constant\nfrom keras.layers import (LSTM, \n                          Embedding, \n                          BatchNormalization,\n                          Dense, \n                          TimeDistributed, \n                          Dropout, \n                          Bidirectional,\n                          Flatten, \n                          GlobalMaxPool1D)\n\nfrom transformers import TFAutoModelForSequenceClassification, TFAutoModel, AutoTokenizer\ndef seed_everything(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed = 2021\nseed_everything(seed)\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_colwidth', 150)\n# Defining all our palette colours.\nprimary_blue = \"#496595\"\nprimary_blue2 = \"#85a1c1\"\nprimary_blue3 = \"#3f4d63\"\nprimary_grey = \"#c6ccd8\"\nprimary_black = \"#202022\"\nprimary_bgcolor = \"#f4f0ea\"\n\nprimary_green = px.colors.qualitative.Plotly[2]\n\nplotly_discrete_sequence = px.colors.qualitative.G10\ncolors = [primary_blue, primary_blue2, primary_blue3, primary_grey, primary_black, primary_bgcolor, primary_green]\nsns.palplot(sns.color_palette(colors))\nsns.palplot(sns.color_palette(plotly_discrete_sequence))\nplt.rcParams['figure.dpi'] = 120\nplt.rcParams['axes.spines.top'] = False\nplt.rcParams['axes.spines.right'] = False\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['axes.facecolor'] = primary_bgcolor\ncustom_theme = Theme({\n    \"info\" : \"italic bold blue\",\n    \"succeed\": \"italic bold green\",\n    \"danger\": \"bold red\"\n})\n\nconsole = Console(theme=custom_theme)\n\npretty.install()\n\"\"\"\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:250%; text-align:center; border-radius: 15px 50px;\">CommonLit Readability \ud83d\udcdd A complete Analysis<\/p>\n\n![nlp-header.png](attachment:4a916c95-e05d-4636-98fa-3e82cb1066ce.png)\n\n**Natural Language Processing or NLP** is a branch of Artificial Intelligence which deal with bridging the machines understanding humans in their Natural Language. Natural Language can be in form of text or sound, which are used for humans to communicate each other. NLP can enable humans to communicate to machines in a natural way.\n\n**Text Classification** is a process involved in Sentiment Analysis. It is classification of peoples opinion or expressions into different sentiments. Sentiments include Positive, Neutral, and Negative, Review Ratings and Happy, Sad. Sentiment Analysis can be done on different consumer centered industries to analyse people's opinion on a particular product or subject.\n\nNatural language processing has its roots in the 1950s. Already in 1950, Alan Turing published an article titled \"Computing Machinery and Intelligence\" which proposed what is now called the Turing test as a criterion of intelligence, a task that involves the automated interpretation and generation of natural language, but at the time not articulated as a problem separate from artificial intelligence.\n\"\"\"\n\"\"\"\n<a id=\"table-of-content\"><\/a>\n\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:120%; text-align:center; border-radius: 15px 50px;\">Table of Content<\/p>\n\n* [1. Loading Data \ud83d\udc8e](#1)\n* [2. EDA \ud83d\udcca](#2)\n    * [2.1 Missing values](#2.1)\n    * [2.2 Target and Std_err Distributions \ud83d\udcf8](#2.2)\n    * [2.3 Excert overview \ud83d\udd0e](#2.3)\n* [3. Data Preprocessing \u2699\ufe0f](#3)\n    * [3.1 Cleaning the corpus \ud83d\udee0](#3.1)\n    * [3.2 Stemming \ud83d\udee0](#3.2)\n    * [3.3 All together \ud83d\udee0](#3.3)\n* [4. Tokens visualization \ud83d\udcca](#4)\n    * [4.1 Top Words \ud83d\udcdd](#4.1)\n    * [4.2 WordCloud \ud83c\udf1f](#4.2)\n* [5. Vectorization](#5)\n    * [5.1 Tunning CountVectorizer](#5.1)\n    * [5.2 TF-IDF](#5.2)\n    * [5.3 Word Embeddings: GloVe](#5.3)\n* [6. Modeling](#6)\n    * [6.1 XGBoost](#6.1)\n* [7. LSTM with Glove](#7)\n* [8. RoBERTa](#8)\n\nTo be continued..\n\"\"\"\n\"\"\"\n<a id='1'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">1. Loading Data \ud83d\udc8e<\/p>\n\nJust load the dataset and global variables for colors and so on.\n\"\"\"\ntrain_df = pd.read_csv('\/kaggle\/input\/commonlitreadabilityprize\/train.csv')\ntest_df = pd.read_csv('\/kaggle\/input\/commonlitreadabilityprize\/test.csv')\nsub_df = pd.read_csv('\/kaggle\/input\/commonlitreadabilityprize\/sample_submission.csv')\n\ntrain_df.shape\ntrain_df.head()\ntarget_column = 'target'\n\ntrain_df.head()\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='2'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">2. EDA \ud83d\udcca<\/p>\n\nNow we are going to take a look about the target distribution, missings, messages length and so on.\n\"\"\"\n\"\"\"\n<a id='2.1'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">2.1 Missing values<\/p>\n\nAs we can see, the only missing values are in: `url_legal` and `license`. For now, we are going to do an analysis based on the `excerpt` text so we can go ahead.\n\"\"\"\nmsno.bar(train_df, color=primary_blue, sort=\"ascending\", figsize=(10,5), fontsize=12)\nplt.show()\n\"\"\"\n<a id='2.2'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">2.2 Target and Std_err Distributions \ud83d\udcf8<\/p>\n\n\"\"\"\nfig2 = ff.create_distplot([train_df[target_column]], [target_column], colors=[primary_blue],\n                             bin_size=.05, show_rug=False)\nplot_title = f\"<span style='font-size:30px; font-family:Serif'><b>{target_column.capitalize()}<\/b> resume<\/span>\"\n\nfig = go.Figure()\n\nmean_value = train_df[target_column].mean()\n\nfig.add_vrect(\n    x0=train_df[target_column].quantile(0.25), \n    x1=train_df[target_column].quantile(0.75), \n    annotation_text=\"IQR\", \n    annotation_position=\"top left\",\n    fillcolor=primary_grey, \n    opacity=0.25, \n    line_width=2,\n)\n\nfig.add_trace(go.Scatter(\n    fig2['data'][1],\n    line=dict(\n        color=primary_blue, \n        width=1.5,\n    ),\n    fill='tozeroy'\n))\n\nfig.add_vline(\n    x=mean_value, \n    line_width=2, \n    line_dash=\"dash\", \n    line_color=primary_black\n)\nfig.add_annotation(\n    yref=\"y domain\",\n    x=mean_value,\n    # The arrow head will be 40% along the y axis, starting from the bottom\n    y=0.5,\n    axref=\"x\",\n    ayref=\"y domain\",\n    ax=mean_value + 0.2*mean_value,\n    ay=0.6,\n    text=f\"<span>{target_column.capitalize()} mean<\/span>\",\n    arrowhead=2,\n)\nfig.add_annotation(\n    xref=\"x domain\", yref=\"y domain\",\n    x=0.98, y=0.98,\n    text=f\"<span><b>Skew: %.2f<\/b><\/span>\"%(train_df[target_column].skew()),\n    bordercolor=primary_black,\n    borderwidth=1.5, borderpad=2.5,\n    showarrow=False,\n)\n\nfig.update_layout(\n    showlegend=True,\n    title_text=plot_title\n)\n\nfig.show()\n###### Helpers not used:\n\n#fig.add_annotation(\n#    yref=\"y3 domain\",\n#    xref=\"x3\",\n#    x=q1_value,\n#    # The arrow head will be 40% along the y axis, starting from the bottom\n#    y=0.95,\n#    axref=\"x3\",\n#    ayref=\"y3 domain\",\n#    ay=0.95,\n#    ax=q1_value + abs(0.2*q1_value),\n#    text=\"Interquartile range (IQR)\",\n#    arrowhead=3,\n#)\n\n\n#fig.add_annotation(\n#    yref=\"y3 domain\",\n#    xref=\"x3\",\n#    x=mean_value,\n#    y=0.5,\n#    axref=\"x3\",\n#    ayref=\"y3 domain\",\n#    ax=mean_value + 0.2*mean_value,\n#    ay=0.6,\n#    text=f\"<span>{feature.capitalize()} mean<\/span>\",\n#    arrowhead=3,\n#)\n\n\n#fig.add_shape(go.layout.Shape(\n#    type=\"line\",\n#    yref=\"y3 domain\",\n#    xref=\"x\",\n#    x0=mean_value,\n#    y0=0,\n#    x1=mean_value,\n#    y1=1,\n#    line=dict(\n#        color=primary_black, \n#        width=2, \n#        dash=\"dash\"\n#    ),\n#), row=3, col=1)\ndef generate_feature_resume(df, feature):\n    \n    plot_title = f\"<span style='font-size:30px; font-family:Serif'><b>{feature.capitalize()}<\/b> resume<\/span>\"\n    (osm, osr), (slope, intercept, r) = stats.probplot(df[feature], plot=None)\n    \n    q1_value = train_df[feature].quantile(0.25)\n    mean_value = train_df[feature].mean()\n    fig2 = ff.create_distplot([df[feature]], [feature], colors=[primary_blue],\n                             bin_size=.05, show_rug=False)\n\n    fig = make_subplots(\n        rows=3, cols=2,\n        specs=[\n            [{\"rowspan\": 2}, {\"rowspan\": 2}],\n            [None, None],\n            [{\"colspan\": 2}, None]\n        ],\n        subplot_titles=(\n            \"Quantile-Quantile Plot\",\n            \"Box Plot\",\n            \"Distribution Plot\"\n        )\n    )\n\n    fig.add_trace(go.Scatter(\n        x=osm,\n        y=slope*osm + intercept,\n        mode='lines',\n        line={\n            'color': '#c81515',\n            'width': 2.5\n        }\n\n    ), row=1, col=1)\n    \n    ## QQ-Plot\n    fig.add_trace(go.Scatter(\n        x=osm,\n        y=osr,\n        mode='markers',\n        marker={\n            'color': primary_blue\n        }\n    ), row=1, col=1)\n\n    ## Box Plot\n    fig.add_trace(go.Box(\n        y=df[feature], \n        name='',\n        marker_color = primary_blue\n    ), row=1, col=2)\n\n    ## Distribution plot\n    fig.add_trace(go.Scatter(\n        fig2['data'][1],\n        line=dict(\n            color=primary_blue, \n            width=1.5,\n        ),\n        fill='tozeroy'\n    ), row=3, col=1)\n    \n    ## InterQuartile Range (IQR)\n    fig.add_vrect(\n        x0=df[feature].quantile(0.25), \n        x1=df[feature].quantile(0.75), \n        annotation_text=\"IQR\", \n        annotation_position=\"top left\",\n        fillcolor=primary_grey, \n        opacity=0.25, \n        line_width=2,\n        row=3, col=1,\n    )\n    \n    ## Mean line\n    fig.add_vline(\n        x=mean_value,\n        line_width=2, \n        line_dash=\"dash\", \n        line_color=primary_black,\n        annotation_text=\"Mean\", \n        annotation_position=\"bottom right\",\n        row=3, col=1,\n    )\n    \n    fig.add_annotation(\n        xref=\"x domain\", yref=\"y domain\",\n        x=0.98, y=0.98,\n        text=f\"<span style='font-family:Serif>Skew: %.2f<\/span>\"%(df[feature].skew()),\n        showarrow=False,\n        bordercolor=primary_black,\n        borderwidth=1, borderpad=2,\n        row=3, col=1,\n    )\n    \n    fig.update_layout(\n        showlegend=False, \n        title_text=plot_title,\n        height=720,\n    )\n\n    fig.show()\ngenerate_feature_resume(train_df, target_column)\n# As there is a f*** 0 in the standard_error feature, we are going to change it with the value of the next lowest element\ntrain_df.loc[train_df['standard_error'] == 0, 'standard_error'] = train_df['standard_error'].sort_values(ascending=True).iloc[1]\ngenerate_feature_resume(train_df, \"standard_error\")\nsns.jointplot(\n    x=train_df['target'], \n    y=train_df['standard_error'], \n    kind='hex',\n    height=8,\n    edgecolor=primary_grey,\n    color=primary_blue\n)\nplt.suptitle(\"Target vs Standard error \",font=\"Serif\", size=20)\nplt.subplots_adjust(top=0.95)\nplt.show()\n\"\"\"\n<a id='2.3'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">2.3 Excert overview \ud83d\udd0e<\/p>\n\"\"\"\ntrain_df['excerpt_len'] = train_df['excerpt'].apply(\n    lambda x : len(x)\n)\ntrain_df['excerpt_word_count'] = train_df['excerpt'].apply(\n    lambda x : len(x.split(' '))\n)\nfig = ff.create_distplot(\n    [train_df['excerpt_len']], \n    ['excerpt_len'], \n    bin_size=12, \n    show_rug=False,\n    colors=[primary_blue],\n)\nfig.update_layout(\n    showlegend=False, \n    title_text=f\"<span style='font-size:30px; font-family:Serif'><b>Excerpt<\/b> length<\/span>\",\n)\nfig.show()\nfig = ff.create_distplot(\n    [train_df['excerpt_word_count']], \n    ['excerpt_word_count'], \n    bin_size=2, \n    show_rug=False,\n    colors=[primary_blue],\n)\nfig.update_layout(\n    showlegend=False, \n    title_text=f\"<span style='font-size:30px; font-family:Serif'><b>Excerpt<\/b> word count<\/span>\",\n)\nfig.show()\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='3'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">3. Data Preprocessing \u2699\ufe0f<\/p>\n\nNow we are going to engineering the data to make it easier for the model to clasiffy.\n\nThis section is very important to reduce the dimensions of the problem.\n\"\"\"\n\"\"\"\n<a id='3.1'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">3.1 Cleaning the corpus \ud83d\udee0<\/p>\n\"\"\"\n# Special thanks to https:\/\/www.kaggle.com\/tanulsingh077 for this function\ndef clean_text(text):\n    '''Make text lowercase, remove text in square brackets,remove links,remove punctuation\n    and remove words containing numbers.'''\n    text = str(text).lower()\n    text = re.sub('\\[.*?\\]', '', text)\n    text = re.sub('https?:\/\/\\S+|www\\.\\S+', '', text)\n    text = re.sub('<.*?>+', '', text)\n    text = re.sub('[%s]' % re.escape(string.punctuation), '', text)\n    text = re.sub('\\n', '', text)\n    text = re.sub('\\w*\\d\\w*', '', text)\n    return text\ntrain_df['excerpt_clean'] = train_df['excerpt'].apply(clean_text)\ntrain_df.head()\n\"\"\"\n### Stopwords\nStopwords are commonly used words in English which have no contextual meaning in an sentence. So therefore we remove them before classification. Some examples removing stopwords are:\n\n![stopwords.png](attachment:a023a8e1-af19-4555-875a-8fc533b0c580.png)\n\"\"\"\nstop_words = stopwords.words('english')\nmore_stopwords = ['u', 'im', 'c']\nstop_words = stop_words + more_stopwords\n\ndef remove_stopwords(text):\n    text = ' '.join(word for word in text.split(' ') if word not in stop_words)\n    return text\n    \ntrain_df['excerpt_clean'] = train_df['excerpt_clean'].apply(remove_stopwords)\ntrain_df.head()\n\"\"\"\n<a id='3.2'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">3.2 Stemming \ud83d\udee0<\/p>\n\n### Stemming\/ Lematization\nFor grammatical reasons, documents are going to use different forms of a word, such as *write, writing and writes*. Additionally, there are families of derivationally related words with similar meanings. The goal of both stemming and lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form.\n\n**Stemming** usually refers to a process that chops off the ends of words in the hope of achieving goal correctly most of the time and often includes the removal of derivational affixes.\n\n**Lemmatization** usually refers to doing things properly with the use of a vocabulary and morphological analysis of words, normally aiming to remove inflectional endings only and to return the base and dictionary form of a word\n\n![stemming-lematization.png](attachment:e2f093fa-6bec-42b3-963b-a9fbc60761f0.png)\n\nAs far as the meaning of the words is not important for this study, we will focus on stemming rather than lemmatization.\n\n### Stemming algorithms\n\nThere are several stemming algorithms implemented in NLTK Python library:\n1. **PorterStemmer** uses *Suffix Stripping* to produce stems. **PorterStemmer is known for its simplicity and speed**. Notice how the PorterStemmer is giving the root (stem) of the word \"cats\" by simply removing the 's' after cat. This is a suffix added to cat to make it plural. But if you look at 'trouble', 'troubling' and 'troubled' they are stemmed to 'trouble' because *PorterStemmer algorithm does not follow linguistics rather a set of 05 rules for different cases that are applied in phases (step by step) to generate stems*. This is the reason why PorterStemmer does not often generate stems that are actual English words. It does not keep a lookup table for actual stems of the word but applies algorithmic rules to generate stems. It uses the rules to decide whether it is wise to strip a suffix.\n2. One can generate its own set of rules for any language that is why Python nltk introduced **SnowballStemmers** that are used to create non-English Stemmers!\n3. **LancasterStemmer** (Paice-Husk stemmer) is an iterative algorithm with rules saved externally. One table containing about 120 rules indexed by the last letter of a suffix. On each iteration, it tries to find an applicable rule by the last character of the word. Each rule specifies either a deletion or replacement of an ending. If there is no such rule, it terminates. It also terminates if a word starts with a vowel and there are only two letters left or if a word starts with a consonant and there are only three characters left. Otherwise, the rule is applied, and the process repeats.\n\"\"\"\nstemmer = nltk.SnowballStemmer(\"english\")\n\ndef stemm_text(text):\n    text = ' '.join(stemmer.stem(word) for word in text.split(' '))\n    return text\ntrain_df['excerpt_clean'] = train_df['excerpt_clean'].apply(stemm_text)\ntrain_df.head()\n\"\"\"\n<a id='3.3'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">3.3 All together \ud83d\udee0<\/p>\n\"\"\"\ndef preprocess_data(text, strip=False):\n    # Clean puntuation, urls, and so on\n    text = clean_text(text)\n    # Remove stopwords\n    text = ' '.join(word for word in text.split(' ') if word not in stop_words)\n    # Stemm all the words in the sentence\n    text = ' '.join(stemmer.stem(word) for word in text.split(' '))\n    \n    if strip:\n        text = text.strip()\n    \n    return text\ntrain_df['excerpt_clean'] = train_df['excerpt_clean'].apply(preprocess_data)\ntrain_df.head()\nconsole.print('First, lets see the original text:')\nconsole.print(train_df['excerpt'][0], style='info')\n\nconsole.print('And now, lets see the clean text:')\nconsole.print(train_df['excerpt_clean'][0], style='succeed')\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='4'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">4. Tokens visualization \ud83d\udcca<\/p>\n\nLet's see which are the top tockens using count vectorizer and ranking based on the appearence. They idea is to have a first overview of the relevance of each word or tuple of words.\n\"\"\"\n\"\"\"\n<a id='4.1'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">4.1 Top Words \ud83d\udcdd<\/p>\n\"\"\"\ndef get_top_n_grams(vect, corpus, n):\n    # Use the CountVectorizer to create a document-term matrix\n    dtm = vect.fit_transform(corpus)\n\n    dtm_sum = dtm.sum(axis=0) \n    dtm_freq = [(word, dtm_sum[0, idx]) for word, idx in vect.vocabulary_.items()]\n    dtm_freq =sorted(dtm_freq, key = lambda w: w[1], reverse=True)\n    return dict(sorted(dtm_freq[:n], key = lambda w: w[1], reverse=False))\n\ndef plot_top_grams(grams, groups, title):\n    fig = go.Figure(go.Bar(\n        x=list(grams.values()), y=list(grams.keys()),\n        orientation='h',\n    ))\n    # Customize aspect\n    fig.update_traces(\n        marker_color=groups[2]*[primary_grey] + groups[1]*[primary_blue2] + groups[0]*[primary_blue], \n        marker_line_color=primary_blue3,\n        marker_line_width=1, \n        opacity=0.6\n    )\n    fig.update_layout(\n        title_text=f\"<span style='font-size:30px; font-family:Serif'>{title}<\/span>\"\n    )\n    fig.show()\nvect = CountVectorizer()\ntop_unigrams = get_top_n_grams(vect, train_df['excerpt_clean'], 15)\n\nplot_top_grams(top_unigrams, [1,5,9], \"Top 15 <b>Unigrams<\/b>\")\nvect = CountVectorizer(ngram_range=(2, 2))\ntop_bigrams = get_top_n_grams(vect, train_df['excerpt_clean'], 15)\n\nplot_top_grams(top_bigrams, [3,7,5], \"Top 15 <b>Bigrams<\/b>\")\nvect = CountVectorizer(ngram_range=(3, 3))\ntop_trigrams = get_top_n_grams(vect, train_df['excerpt_clean'], 15)\n\nplot_top_grams(top_trigrams, [3,4,8], \"Top 15 <b>Trigrams<\/b>\")\n\"\"\"\n<a id='4.2'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">4.2 WordCloud \ud83c\udf1f<\/p>\n\"\"\"\nbook_mask = np.array(Image.open('\/kaggle\/input\/masksforwordclouds\/book-logo-1.jpg'))\n\nwc = WordCloud(\n    background_color='white', \n    max_words=200, \n    mask=book_mask,\n)\nwc.generate(' '.join(text for text in train_df.loc[:, 'excerpt_clean']))\nplt.figure(figsize=(18,10))\nplt.title('Top words', \n          fontdict={'size': 22,  'verticalalignment': 'bottom'})\nplt.imshow(wc)\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='5'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">5. Baseline Model and Comparison<\/p>\n\nCurrently, we have the messages as lists of tokens (also known as lemmas) and now we need to convert each of those messages into a vector the SciKit Learn's algorithm models can work with.\n\nWe'll do that in three steps using the bag-of-words model:\n\n1. Count how many times does a word occur in each message (Known as term frequency)\n2. Weigh the counts, so that frequent tokens get lower weight (inverse document frequency)\n3. Normalize the vectors to unit length, to abstract from the original text length (L2 norm)\n\nLet's begin the first step:\n\nEach vector will have as many dimensions as there are unique words in the SMS corpus. We will first use SciKit Learn's **CountVectorizer**. This model will convert a collection of text documents to a matrix of token counts.\n\nWe can imagine this as a 2-Dimensional matrix. Where the 1-dimension is the entire vocabulary (1 row per word) and the other dimension are the actual documents, in this case a column per text message.\n\n![vectorizer.png](attachment:fe0ac5b9-f924-4a7c-b8e3-306485322784.png)\n\"\"\"\nrmse = lambda y_true, y_pred: np.sqrt(mse(y_true, y_pred))\nrmse_loss = lambda Estimator, X, y: rmse(y, Estimator.predict(X))\n# how to define X and y (from the SMS data) for use with COUNTVECTORIZER\nx = train_df['excerpt_clean']\ny = train_df['target']\n\nprint(len(x), len(y))\n# Split into train and test sets\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, random_state=42)\nprint(len(x_train), len(y_train))\nprint(len(x_test), len(y_test))\nmodel = make_pipeline(\n    CountVectorizer(ngram_range=(1,1)),\n    LinearRegression(),\n)\n\nval_score = cross_val_score(\n    model, \n    train_df['excerpt_clean'], \n    train_df['target'], \n    scoring=rmse_loss\n).mean()\n\nconsole.print(f'Train Score for CountVectorizer(1,1): {val_score}')\nmodel = make_pipeline(\n    CountVectorizer(ngram_range=(2,2)),\n    LinearRegression(),\n)\n\nval_score = cross_val_score(\n    model, \n    train_df['excerpt_clean'], \n    train_df['target'], \n    scoring=rmse_loss\n).mean()\n\nconsole.print(f'Train Score for CountVectorizer(1,1): {val_score}')\nmodel = make_pipeline(\n    CountVectorizer(ngram_range=(1,2)),\n    LinearRegression(),\n)\n\nval_score = cross_val_score(\n    model, \n    train_df['excerpt_clean'], \n    train_df['target'], \n    scoring=rmse_loss\n).mean()\n\nconsole.print(f'Train Score for CountVectorizer(1,1): {val_score}')\n\"\"\"\nAs we can see, it seems that the best result is achived using `ngram_range=(1,2)` which has much sense as we are going to see in the following section.>\n\"\"\"\n# Now create the train and test dtm\nvect = CountVectorizer()\nvect.fit(x_train)\n\n# Use the trained to create a document-term matrix from train and test sets\nx_train_dtm = vect.transform(x_train)\nx_test_dtm = vect.transform(x_test)\n\"\"\"\n<a id='5.1'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">5.1 Tunning CountVectorizer<\/p>\n\nCountVectorizer has a few parameters you should know.\n\n1. **stop_words**: Since CountVectorizer just counts the occurrences of each word in its vocabulary, extremely common words like \u2018the\u2019, \u2018and\u2019, etc. will become very important features while they add little meaning to the text. Your model can often be improved if you don\u2019t take those words into account. Stop words are just a list of words you don\u2019t want to use as features. You can set the parameter stop_words=\u2019english\u2019 to use a built-in list. Alternatively you can set stop_words equal to some custom list. This parameter defaults to None.\n\n2. **ngram_range**: An n-gram is just a string of n words in a row. E.g. the sentence \u2018I am Groot\u2019 contains the 2-grams \u2018I am\u2019 and \u2018am Groot\u2019. The sentence is itself a 3-gram. Set the parameter ngram_range=(a,b) where a is the minimum and b is the maximum size of ngrams you want to include in your features. The default ngram_range is (1,1). In a recent project where I modeled job postings online, I found that including 2-grams as features boosted my model\u2019s predictive power significantly. This makes intuitive sense; many job titles such as \u2018data scientist\u2019, \u2018data engineer\u2019, and \u2018data analyst\u2019 are 2 words long.\n\n3. **min_df, max_df**: These are the minimum and maximum document frequencies words\/n-grams must have to be used as features. If either of these parameters are set to integers, they will be used as bounds on the number of documents each feature must be in to be considered as a feature. If either is set to a float, that number will be interpreted as a frequency rather than a numerical limit. min_df defaults to 1 (int) and max_df defaults to 1.0 (float).\n\n4. **max_features**: This parameter is pretty self-explanatory. The CountVectorizer will choose the words\/features that occur most frequently to be in its\u2019 vocabulary and drop everything else. \n\nYou would set these parameters when initializing your CountVectorizer object as shown below.\n\"\"\"\nvect_tunned = CountVectorizer(stop_words='english', ngram_range=(1,2), min_df=0.1, max_df=0.7, max_features=100)\n\"\"\"\n<a id='5.2'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">5.2 TF-IDF<\/p>\n\nIn information retrieval, tf\u2013idf, **TF-IDF**, or TFIDF, **short for term frequency\u2013inverse document frequency**, is a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus It is often used as a weighting factor in searches of information retrieval, text mining, and user modeling. The tf\u2013idf value increases proportionally to the number of times a word appears in the document and is offset by the number of documents in the corpus that contain the word, which helps to adjust for the fact that some words appear more frequently in general. \n\n**tf\u2013idf** is one of the most popular term-weighting schemes today. A survey conducted in 2015 showed that 83% of text-based recommender systems in digital libraries use tf\u2013idf.\n\n![tf-idf.png](attachment:ed3d959e-bd1b-446f-af2f-775e4364b2b7.png)\n\"\"\"\nmodel = make_pipeline(\n    TfidfVectorizer(ngram_range=(1,1)),\n    LinearRegression()\n)\n\nval_score = cross_val_score(\n    model, \n    train_df['excerpt_clean'], \n    train_df['target'], \n    scoring=rmse_loss\n).mean()\n\nconsole.print(f'Train Score for TfidfVectorizer(1,1): {val_score}')\nmodel = make_pipeline(\n    TfidfVectorizer(ngram_range=(1,2)),\n    LinearRegression()\n)\n\nval_score = cross_val_score(\n    model, \n    train_df['excerpt_clean'], \n    train_df['target'], \n    scoring=rmse_loss\n).mean()\n\nconsole.print(f'Train Score for TfidfVectorizer(1,1): {val_score}')\n\"\"\"\nAgain, the best selection for `ngram` parameter is the tuple `(1,2)`.\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\ntfidf_transformer = TfidfTransformer()\n\ntfidf_transformer.fit(x_train_dtm)\nx_train_tfidf = tfidf_transformer.transform(x_train_dtm)\n\nx_train_tfidf\n\"\"\"\n<a id='5.3'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">5.3 Word Embeddings: GloVe<\/p>\n\"\"\"\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers.embeddings import Embedding\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom keras.optimizers import Adam\ntexts = train_df['excerpt_clean']\ntarget = train_df['target']\n\"\"\"\nWe need to perform **tokenization** - the processing of segmenting text into sentences of words. The benefit of tokenization is that it gets the text into a format that is easier to convert to raw numbers, which can actually be used for processing.\n\n![tokenization.jpeg](attachment:156686a1-ffd0-4f85-be0a-d1fd31ea8a64.jpeg)\n\"\"\"\n# Calculate the length of our vocabulary\nword_tokenizer = Tokenizer()\nword_tokenizer.fit_on_texts(texts)\n\nvocab_length = len(word_tokenizer.word_index) + 1\nvocab_length\n\"\"\"\n### Pad_sequences\n\nhttps:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/preprocessing\/sequence\/pad_sequences\n\n```python\ntf.keras.preprocessing.sequence.pad_sequences(\n    sequences, maxlen=None, dtype='int32', padding='pre',\n    truncating='pre', value=0.0\n)\n```\n\nThis function transforms a list (of length num_samples) of sequences (lists of integers) into a 2D Numpy array of shape (num_samples, num_timesteps). num_timesteps is either the maxlen argument if provided, or the length of the longest sequence in the list.\n\n```python\n>>> sequence = [[1], [2, 3], [4, 5, 6]]\n>>> tf.keras.preprocessing.sequence.pad_sequences(sequence, padding='post')\narray([[1, 0, 0],\n       [2, 3, 0],\n       [4, 5, 6]], dtype=int32)\n```\n\"\"\"\ndef embed(corpus): \n    return word_tokenizer.texts_to_sequences(corpus)\n\nlongest_train = max(texts, key=lambda sentence: len(word_tokenize(sentence)))\nlength_long_sentence = len(word_tokenize(longest_train))\n\ntrain_padded_sentences = pad_sequences(\n    embed(texts), \n    length_long_sentence, \n    padding='post'\n)\n\ntrain_padded_sentences\n\"\"\"\n### GloVe\n\nGloVe method is built on an important idea,\n\n> You can derive semantic relationships between words from the co-occurrence matrix.\n\nTo obtain a vector representation for words we can use an unsupervised learning algorithm called **GloVe (Global Vectors for Word Representation)**, which focuses on words co-occurrences over the whole corpus. Its embeddings relate to the probabilities that two words appear together.\n\nWord embeddings are basically a form of word representation that bridges the human understanding of language to that of a machine. They have learned representations of text in an n-dimensional space where words that have the same meaning have a similar representation. Meaning that two similar words are represented by almost similar vectors that are very closely placed in a vector space.\n\nThus when using word embeddings, all individual words are represented as real-valued vectors in a predefined vector space. Each word is mapped to one vector and the vector values are learned in a way that resembles a neural network.\n\"\"\"\nembeddings_dictionary = dict()\nembedding_dim = 100\n\n# Load GloVe 100D embeddings\nwith open('\/kaggle\/input\/glove6b100dtxt\/glove.6B.100d.txt') as fp:\n    for line in fp.readlines():\n        records = line.split()\n        word = records[0]\n        vector_dimensions = np.asarray(records[1:], dtype='float32')\n        embeddings_dictionary [word] = vector_dimensions\n# Now we will load embedding vectors of those words that appear in the\n# Glove dictionary. Others will be initialized to 0.\n\nembedding_matrix = np.zeros((vocab_length, embedding_dim))\n\nfor word, index in word_tokenizer.word_index.items():\n    embedding_vector = embeddings_dictionary.get(word)\n    if embedding_vector is not None:\n        embedding_matrix[index] = embedding_vector\n        \nembedding_matrix\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='6'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">6. Modeling<\/p>\n\"\"\"\n\"\"\"\n<a id='6.1'><\/a>\n## <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:140%; text-align:center; border-radius: 15px 50px;\">6.1 TF-IDF with XGBoost<\/p>\n\"\"\"\nfrom sklearn.pipeline import Pipeline\nimport xgboost as xgb\n\npipe = Pipeline([\n    ('tfid', TfidfVectorizer(ngram_range=(1,2))),  \n    ('model', xgb.XGBRegressor(\n        learning_rate=0.1,\n        max_depth=7,\n        n_estimators=80,\n        use_label_encoder=False,\n        eval_metric='rmse',\n    ))\n])\n\n# Fit the pipeline with the data\npipe.fit(x_train, y_train)\ny_pred = pipe.predict(x_test)\n\nconsole.print(f'Score for XGBoost with TfidfVectorizer(1,2): {rmse(y_test, y_pred)}')\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='7'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">7. LSTM<\/p>\n\"\"\"\n# Split data into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(\n    train_padded_sentences, \n    target, \n    test_size=0.25\n)\n# Model from https:\/\/www.kaggle.com\/mariapushkareva\/nlp-disaster-tweets-with-glove-and-lstm\/data\n\ndef glove_lstm():\n    model = Sequential()\n    \n    model.add(Embedding(\n        input_dim=embedding_matrix.shape[0], \n        output_dim=embedding_matrix.shape[1], \n        weights = [embedding_matrix], \n        input_length=length_long_sentence\n    ))\n    \n    model.add(Bidirectional(LSTM(\n        length_long_sentence, \n        return_sequences = True, \n        recurrent_dropout=0.2\n    )))\n    \n    model.add(GlobalMaxPool1D())\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n    model.add(Dense(length_long_sentence, activation = \"relu\"))\n    model.add(Dropout(0.5))\n    model.add(Dense(length_long_sentence, activation = \"relu\"))\n    model.add(Dropout(0.5))\n    model.add(Dense(1, activation = 'linear'))\n    \n    model.compile(Adam(lr=1e-5), loss='mean_squared_error', metrics=[RootMeanSquaredError()])\n    \n    return model\n\nmodel = glove_lstm()\nmodel.summary()\n# Load the model and train!!\n\nmodel = glove_lstm()\n\ncheckpoint = ModelCheckpoint(\n    'model.h5', \n    monitor = 'val_loss', \n    verbose = 1, \n    save_best_only = True\n)\nreduce_lr = ReduceLROnPlateau(\n    monitor = 'val_loss', \n    factor = 0.2, \n    verbose = 1, \n    patience = 5,                        \n    min_lr = 0.001\n)\nhistory = model.fit(\n    X_train, \n    y_train, \n    epochs = 10,\n    batch_size = 32,\n    validation_data = (X_test, y_test),\n    verbose = 1,\n    callbacks = [reduce_lr, checkpoint]\n)\ndef plot_learning_curves(history, arr):\n    fig, ax = plt.subplots(1, 2, figsize=(20, 5))\n    for idx in range(2):\n        ax[idx].plot(history.history[arr[idx][0]])\n        ax[idx].plot(history.history[arr[idx][1]])\n        ax[idx].legend([arr[idx][0], arr[idx][1]],fontsize=18)\n        ax[idx].set_xlabel('A ',fontsize=16)\n        ax[idx].set_ylabel('B',fontsize=16)\n        ax[idx].set_title(arr[idx][0] + ' X ' + arr[idx][1],fontsize=16)\nplot_learning_curves(history, [['loss', 'val_loss'],['root_mean_squared_error', 'val_root_mean_squared_error']])\n\"\"\"\n<a href=\"#table-of-content\">back to table of content<\/a>\n<a id='8'><\/a>\n# <p style=\"background-color:skyblue; font-family:newtimeroman; font-size:150%; text-align:center; border-radius: 15px 50px;\">8. ToBERTa TF \ud83d\udee0<\/p>\n\nSpecial thanks to @sauravmaheshkar and @dimitreoliveira for such amazing work and thanks for sharing your code. It was ery helpful.\n\"\"\"\n# Sampling Function\ndef sample_target(features, target):\n    mean, stddev = target\n    sampled_target = tf.random.normal([], mean=tf.cast(mean, dtype=tf.float32), \n                                      stddev=tf.cast(stddev, dtype=tf.float32), dtype=tf.float32)\n    \n    return (features, sampled_target)\n\n# Convert to tf.data.Dataset\ndef get_dataset(df, tokenizer, labeled=True, ordered=False, repeated=False, \n                is_sampled=False, batch_size=32, seq_len=256):\n    \n    texts = [preprocess_data(text, True) for text in df['excerpt']]\n    \n    # Tokenize inputs\n    tokenized_inputs = tokenizer(texts, max_length=seq_len, truncation=True, \n                                 padding='max_length', return_tensors='tf')\n    \n    if labeled:\n        dataset = tf.data.Dataset.from_tensor_slices(({'input_ids': tokenized_inputs['input_ids'], \n                                                      'attention_mask': tokenized_inputs['attention_mask']}, \n                                                      (df[target_column], df['standard_error'])))\n        if is_sampled:\n            dataset = dataset.map(sample_target, num_parallel_calls=tf.data.AUTOTUNE)\n    else:\n        dataset = tf.data.Dataset.from_tensor_slices({'input_ids': tokenized_inputs['input_ids'], \n                                                      'attention_mask': tokenized_inputs['attention_mask']})\n        \n    if repeated:\n        dataset = dataset.repeat()\n    if not ordered:\n        dataset = dataset.shuffle(1024)\n    dataset = dataset.batch(batch_size)\n    dataset = dataset.prefetch(tf.data.AUTOTUNE)\n    \n    return dataset\n# TPU or GPU detection\n# Detect hardware and create the ad-hoc strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(f'Running on TPU {tpu.master()}')\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    print('Using GPU strategy...')\n    strategy = tf.distribute.get_strategy()\n\nAUTO = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')\nBATCH_SIZE = 8\nLEARNING_RATE = 1e-3\nEPOCHS = 5\nSTEPS=50\nN_FOLDS = 5\nES_PATIENCE = 7\nSEQ_LEN = 256\nBASE_MODEL = '\/kaggle\/input\/huggingface-roberta\/roberta-base\/'\nproper_names = ['fayre', 'roger', 'blaney']\n\ndef model_fn(encoder, seq_len=256):\n    input_ids = layers.Input(shape=(seq_len,), dtype=tf.int32, name='input_ids')\n    input_attention_mask = layers.Input(shape=(seq_len,), dtype=tf.int32, name='attention_mask')\n    \n    outputs = encoder({'input_ids': input_ids, \n                       'attention_mask': input_attention_mask})\n    \n    model = Model(\n        inputs=[input_ids, input_attention_mask], \n        outputs=outputs\n    )\n\n    optimizer = optimizers.Adam(lr=LEARNING_RATE)\n    model.compile(\n        optimizer=optimizer, \n        loss=losses.MeanSquaredError(), \n        metrics=[metrics.RootMeanSquaredError()]\n    ) \n    return model\n\n\nwith strategy.scope():\n    encoder = TFAutoModelForSequenceClassification.from_pretrained(BASE_MODEL, num_labels=1)\n    model = model_fn(encoder, SEQ_LEN)\n    \nmodel.summary()\ntf.keras.utils.plot_model(\n    model,\n    show_shapes=True, show_dtype=False,\n    show_layer_names=False, rankdir='TB', \n    expand_nested=False\n)\n%%script false --no-raise-error\n\ntokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)\n\nskf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=seed)\n\noof_pred = []; oof_labels = []\nhistory_list = []; test_pred = []\n\nfor fold,(idxT, idxV) in enumerate(skf.split(train_df)):\n    if tpu: tf.tpu.experimental.initialize_tpu_system(tpu)\n    \n    print(f'\\nFOLD: {fold+1}')\n    print(f'TRAIN: {len(idxT)} VALID: {len(idxV)}')\n\n    # Model\n    backend.clear_session()\n    with strategy.scope():\n        encoder = TFAutoModelForSequenceClassification.from_pretrained(BASE_MODEL, num_labels=1)\n        model = model_fn(encoder, SEQ_LEN)\n        \n    model_path = f'model_{fold}.h5'\n    es = EarlyStopping(monitor='val_root_mean_squared_error', mode='min', \n                       patience=ES_PATIENCE, restore_best_weights=True, verbose=1)\n    checkpoint = ModelCheckpoint(model_path, monitor='val_root_mean_squared_error', mode='min', \n                                 save_best_only=True, save_weights_only=True)\n\n    # Train\n    history = model.fit(\n        x=get_dataset(\n            train_df.loc[idxT], \n            tokenizer, \n            repeated=True, \n            is_sampled=True, \n            batch_size=BATCH_SIZE, \n            seq_len=SEQ_LEN\n        ), \n        validation_data=get_dataset(\n            train_df.loc[idxV], \n            tokenizer, \n            ordered=True, \n            batch_size=BATCH_SIZE, seq_len=SEQ_LEN\n        ), \n        steps_per_epoch=STEPS, \n        callbacks=[es, checkpoint], \n        epochs=EPOCHS,  \n        verbose=2\n    ).history\n      \n    history_list.append(history)\n    # Save last model weights\n    model.load_weights(model_path)\n    \n    # Results\n    print(f\"#### FOLD {fold+1} OOF RMSE = {np.min(history['val_root_mean_squared_error']):.4f}\")\n\n    # OOF predictions\n    valid_ds = get_dataset(\n        train_df.loc[idxV], \n        tokenizer, \n        ordered=True, batch_size=BATCH_SIZE, seq_len=SEQ_LEN\n    )\n    oof_labels.append([target[0].numpy() for sample, target in iter(valid_ds.unbatch())])\n    x_oof = valid_ds.map(lambda sample, target: sample)\n    oof_pred.append(model.predict(x_oof)['logits'])\n\n    # Test predictions\n    test_ds = get_dataset(\n        test_df, \n        tokenizer, \n        labeled=False, ordered=True, batch_size=BATCH_SIZE, seq_len=SEQ_LEN\n    )\n    x_test = test_ds.map(lambda sample: sample)\n    test_pred.append(model.predict(x_test)['logits'])","meta":"{'source': 'AI4Code', 'id': '0380b1e2a394bc'}"}
{"id":"111313","text":"%%html\n<marquee style='width: 100%; color: red;'><H1>SKIN_CANCER<\/H1><\/marquee>\n\"\"\"\n![](https:\/\/nci-media.cancer.gov\/pdq\/media\/images\/578083-750.jpg)\n\"\"\"\n\"\"\"\nL'\u00e9chelle de Clark comporte 5 niveaux de m\u00e9lanome :\n\n   1. Les cellules se trouvent dans la couche externe de la peau (\u00e9piderme)\n\n   2. Les cellules se trouvent dans la couche situ\u00e9e directement sous l'\u00e9piderme (derme pupillaire)\n\n   3. Les cellules touchent la couche suivante appel\u00e9e derme profond\n\n   4. Les cellules se sont r\u00e9pandues dans le derme r\u00e9ticulaire\n\n   5. Les cellules se sont d\u00e9velopp\u00e9es dans la couche de graisse\n\n![](https:\/\/media.giphy.com\/media\/lSJElktZ5BKUvYSztq\/giphy.gif)\n\"\"\"\n\"\"\"\n## R\u00e9f\u00e9rences \n* [TensorFlow + Transfer Learning: Melanoma](https:\/\/www.kaggle.com\/amyjang\/tensorflow-transfer-learning-melanoma)\n* [GENERAL INFORMATION ABOUT MELANOMA](https:\/\/www.uhhospitals.org\/services\/cancer-services\/skin-cancer\/melanoma\/about-melanoma)\n\n\"\"\"\n\"\"\"\n# 1. Introduction \u25b6\n\n### 1.1Qu'est-ce que le m\u00e9lanome:\n* [Le m\u00e9lanome est le cancer de la peau le moins fr\u00e9quent mais le plus mortel, ne repr\u00e9sentant qu'environ 1 % de tous les cas, mais la grande majorit\u00e9 des d\u00e9c\u00e8s dus au cancer de la peau.](https:\/\/www.aimatmelanoma.org\/about-melanoma\/melanoma-stats-facts-and-figures\/)\n* Le m\u00e9lanome est le troisi\u00e8me cancer le plus fr\u00e9quent chez les hommes et les femmes \u00e2g\u00e9s de 20 \u00e0 39 ans.\n* Aux \u00c9tats-Unis, le m\u00e9lanome continue d'\u00eatre \n    * le cinqui\u00e8me cancer le plus fr\u00e9quent chez les hommes de tous les groupes d'\u00e2ge\n    * le sixi\u00e8me cancer le plus fr\u00e9quent chez les femmes de tous les groupes d'\u00e2ge\n* L'Australie et la Nouvelle-Z\u00e9lande pr\u00e9sentent la plus forte incidence de m\u00e9lanomes au monde (plus de deux fois plus qu'en Am\u00e9rique du Nord)\n\n\n# N\u00f4tre Data:\n### Train Dataset se compose de:\n\n   1. image name -> le nom de fichier de l'image sp\u00e9cifique pour train set\n   2. patient_id -> id unique du patient \n   3. sex -> genre du patient\n   4. age_approx -> \u00e2ge approximatif du patient \n   5. anatom_site_general_challenge -> l'emplacement du  scan site\n   6. diagnosis -> des informations sur le diagnostic\n   7. benign_malignant - indique le r\u00e9sultat du scan s'il est malin ou b\u00e9nin\n   8. target -> m\u00eame chose que ci-dessus mais en mieux pour la mod\u00e9lisation puisqu'elle est binaire\n\n### Test Dataset se compose de:\n\n   1. image name -> le nom de fichier de l'image sp\u00e9cifique pour test set\n   2. patient_id -> id unique du patient \n   3. sex -> genre du patient\n   4. age_approx -> \u00e2ge approximatif du patient \n   5. anatom_site_general_challenge -> l'emplacement du  scan site\n\n\n\n\n### 1.2 objectifs:\n> L'objectif est d'identifier correctement les cas ****b\u00e9nins**** et ****malins****. Une tumeur b\u00e9nigne est une tumeur qui n'envahit pas les tissus environnants ou ne se propage pas dans le corps. Une tumeur maligne est une tumeur qui peut envahir les tissus environnants ou se propager dans le corps. .\n<img src = 'https:\/\/www.verywellhealth.com\/thmb\/IFgBpbmhYCJdS4rvLACzX3Ukqsc=\/1500x0\/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)\/514240-article-img-malignant-vs-benign-tumor2111891f-54cc-47aa-8967-4cd5411fdb2f-5a2848f122fa3a0037c544be.png' width = 300>\n\n> Data: DICOM Files split in Train (33,126 observations) and Test (10,982 observations)\n<img src='https:\/\/i.imgur.com\/or0AoVs.png' width = 500>\n\n\"\"\"\n\"\"\"\n# 3.Pr\u00e9paration de la base de donn\u00e9es\n\"\"\"\n\"\"\"\n## Visualisation de donn\u00e9es\n\"\"\"\n# Regular Imports\nimport os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport matplotlib.image as mpimg\nfrom tabulate import tabulate\nimport missingno as msno \nfrom IPython.display import display_html\nfrom PIL import Image\nimport gc\nimport cv2\n\nimport pydicom # for DICOM images\nfrom skimage.transform import resize\n\n# SKLearn\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# Set Style\nsns.set(style=\"darkgrid\")\nsns.despine(left=True, bottom=True)\n\n\nlist(os.listdir('..\/input\/siim-isic-melanoma-classification'))\n# Directory\ndirectory = '..\/input\/siim-isic-melanoma-classification'\n\n# Import the 2 csv s\ntrain_df = pd.read_csv(directory + '\/train.csv')\ntest_df = pd.read_csv(directory + '\/test.csv')\n\nprint('Train has {:,} rows and Test has {:,} rows.'.format(len(train_df), len(test_df)))\n\n# Change columns names\nnew_names = ['dcm_name', 'ID', 'sex', 'age', 'anatomy', 'diagnosis', 'benign_malignant', 'target']\ntrain_df.columns = new_names\ntest_df.columns = new_names[:5]\nprint(train_df)\nprint(test_df)\ntrain_df.head()\ntest_df.head()\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,5))\nsns.countplot(ax=ax1, x=\"anatomy\", data=train_df)\nax1.set_title(\"distribution de anatomy  dans  training data\")\nsns.countplot(ax=ax2, x=\"anatomy\", data=test_df)\nax2.set_title(\"distribution de anatomy dans test data\")\nplt.show()\nplt.figure(figsize=(16, 6))\na = sns.countplot(data=train_df, x='benign_malignant', hue='anatomy')\n\nfor p in a.patches:\n    a.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n\nplt.title('distribution de Anatomy par Target', fontsize=16)\nsns.despine(left=True, bottom=True);\n\"\"\"\n1. Il y a plus d'hommes que de femmes dans l'ensemble de donn\u00e9es\n2. Cependant, les pourcentages sont presque les m\u00eames\n\"\"\"\nf, (ax1, ax2) = plt.subplots(1, 2, figsize = (16, 6))\n\na = sns.countplot(train_df['anatomy'], ax=ax1)\nb = sns.countplot(train_df['diagnosis'], ax=ax2)\n\na.set_xticklabels(a.get_xticklabels(), rotation=35, ha=\"right\")\nb.set_xticklabels(b.get_xticklabels(), rotation=35, ha=\"right\")\n\nfor p in a.patches:\n    a.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n    \nfor p in b.patches:\n    b.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n    \nax1.set_title('Les fr\u00e9quences de Anatomy', fontsize=16)\nax2.set_title('Les fr\u00e9quences de Diagnosis', fontsize=16)\nsns.despine(left=True, bottom=True);\nfig, (ax1) = plt.subplots(1,1, figsize=(20,5))\nsns.countplot(ax=ax1, x=\"benign_malignant\", data=train_df)\nax1.set_title(\"distribution de benign_malignant  dans  training data\")\nplt.show()\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,5))\nsns.countplot(ax=ax1, x=\"sex\", data=train_df)\nax1.set_title(\"distribution de sex  dans  training data\")\nsns.countplot(ax=ax2, x=\"sex\", data=test_df)\nax2.set_title(\"distribution de sex dans test data\")\nplt.show()\nplt.figure(figsize=(16, 6))\na = sns.countplot(data=train_df, x='benign_malignant', hue='sex')\n\nfor p in a.patches:\n    a.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n\nplt.title('distribution de sex par target', fontsize=16)\nsns.despine(left=True, bottom=True);\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,5))\nsns.countplot(ax=ax1, x=\"age\", data=train_df)\nax1.set_title(\"distribution d'age  dans  training data\")\nsns.countplot(ax=ax2, x=\"age\", data=test_df)\nax2.set_title(\"distribution d'age dans test data\")\nplt.show()\nfig, (ax1) = plt.subplots(1,1, figsize=(20,5))\nsns.countplot(ax=ax1, x=\"target\", data=train_df)\nax1.set_title(\"distribution d'age  dans  training data\")\nplt.show()\n\"\"\"\n* **0=b\u00e9nins**\n* **1=malins**\n\"\"\"\nf, (ax1, ax2) = plt.subplots(1, 2, figsize = (16, 6))\n\na = sns.countplot(train_df[train_df['target']==0]['diagnosis'], ax=ax1)\nb = sns.countplot(train_df[train_df['target']==1]['diagnosis'], ax=ax2)\n\na.set_xticklabels(a.get_xticklabels(), rotation=35, ha=\"right\")\nb.set_xticklabels(b.get_xticklabels(), rotation=35, ha=\"right\")\n\nfor p in a.patches:\n    a.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n    \nfor p in b.patches:\n    b.annotate(format(p.get_height(), ','), \n           (p.get_x() + p.get_width() \/ 2., \n            p.get_height()), ha = 'center', va = 'center', \n           xytext = (0, 4), textcoords = 'offset points')\n    \nax1.set_title('Cas b\u00e9nins: vue de diagnostic', fontsize=16)\nax2.set_title('Cas malins: vue de diagnostic', fontsize=16)\nsns.despine(left=True, bottom=True);\ncolors_nude = ['#e0798c','#65365a','#da8886','#cfc4c4','#dfd7ca']\npatients_count_train = train_df.groupby(by='ID')['dcm_name'].count().reset_index()\npatients_count_test = test_df.groupby(by='ID')['dcm_name'].count().reset_index()\n\n# Figure\nf, (ax1, ax2) = plt.subplots(1, 2, figsize = (16, 6))\n\na = sns.distplot(patients_count_train['dcm_name'], kde=False, bins=50, \n                 ax=ax1, color=colors_nude[0], hist_kws={'alpha': 1})\nb = sns.distplot(patients_count_test['dcm_name'], kde=False, bins=50, \n                 ax=ax2, color=colors_nude[1], hist_kws={'alpha': 1})\n    \nax1.set_title('Train: Images per Patient Distribution', fontsize=16)\nax2.set_title('Test: Images per Patient Distribution', fontsize=16)\nsns.despine(left=True, bottom=True);\n\n# Create the paths\npath_train = directory + '\/train\/' + train_df['dcm_name'] + '.dcm'\npath_test = directory + '\/test\/' + test_df['dcm_name'] + '.dcm'\n\n# Append to the original dataframes\ntrain_df['path_dicom'] = path_train\ntest_df['path_dicom'] = path_test\n\n# === JPEG ===\n# Create the paths\npath_train = directory + '\/jpeg\/train\/' + train_df['dcm_name'] + '.jpg'\npath_test = directory + '\/jpeg\/test\/' + test_df['dcm_name'] + '.jpg'\n\n# Append to the original dataframes\ntrain_df['path_jpeg'] = path_train\ntest_df['path_jpeg'] = path_test\nfig, ax = plt.subplots()\nax.imshow(image)\nax.axis('off')\n plt.subplots(nrows=1, ncols=1, figsize=(16,6))\ndata = pydicom.read_file(train_df['path_dicom'][0])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\nimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nimage = cv2.resize(image, (512,512))\n#image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndata = pydicom.read_file(train_df['path_dicom'][1])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\n#image = cv2.cvtColor(image)\nimage = cv2.resize(image, (512,512))\n#image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndata = pydicom.read_file(train_df['path_dicom'][2])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\nimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nimage = cv2.resize(image, (512,512))\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndata = pydicom.read_file(train_df['path_dicom'][3])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\nimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nimage = cv2.resize(image, (512,512))\n#image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndata = pydicom.read_file(train_df['path_dicom'][4])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\nimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nimage = cv2.resize(image, (512,512))\n#image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndata = pydicom.read_file(train_df['path_dicom'][5])\nimage = data.pixel_array\nfig, ax = plt.subplots(figsize=(16,16))\nimage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nimage = cv2.resize(image, (512,512))\n#image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\nax.imshow(image, cmap=plt.cm.bone,) \nax.axis('off')\ndef show_images(data, n = 5, rows=1, cols=6, title='Default'):\n    plt.figure(figsize=(16,4))\n\n    for k, path in enumerate(data['path_dicom'][:n]):\n        image = pydicom.read_file(path)\n        image = image.pixel_array\n        \n        # image = resize(image, (200, 200), anti_aliasing=True)\n\n        plt.suptitle(title, fontsize = 16)\n        plt.subplot(rows, cols, k+1)\n        plt.imshow(image)\n        plt.axis('off')\nshow_images(train_df[train_df['target'] == 0], n=10, rows=2, cols=5, title='Benign Sample')\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(16,6))\nplt.suptitle(\"B&W\", fontsize = 16)\n\nfor i in range(0, 1):\n    data = pydicom.read_file(train_df['path_dicom'][i])\n    image = data.pixel_array\n    \n    # Transform to B&W\n    # The function converts an input image from one color space to another.\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    image = cv2.resize(image, (200,200))\n    \n    x = i \n    y = i  \n    axes[x, y].imshow(image, cmap=plt.cm.bone) \n    axes[x, y].axis('off')\nfig, axes = plt.subplots(nrows=1, ncols=6, figsize=(16,6))\nplt.suptitle(\"Without Gaussian Blur\", fontsize = 16)\n\nfor i in range(0, 2*6):\n    data = pydicom.read_file(train_df['path_dicom'][i])\n    image = data.pixel_array\n    \n    # Transform to B&W\n    # The function converts an input image from one color space to another.\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n    image = cv2.resize(image, (200,200))\n    \n    x = i \/\/ 6\n    y = i % 6\n    axes[x, y].imshow(image, cmap=plt.cm.bone) \n    axes[x, y].axis('off')\nfig, axes = plt.subplots(nrows=1, ncols=6, figsize=(16,6))\nplt.suptitle(\"With Gaussian Blur\", fontsize = 16)\n\nfor i in range(0, 2*6):\n    data = pydicom.read_file(train_df['path_dicom'][i])\n    image = data.pixel_array\n    \n    # Transform to B&W\n    # The function converts an input image from one color space to another.\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n    image = cv2.resize(image, (200,200))\n    image=cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0,0) ,256\/10), -4, 128)\n    \n    x = i \/\/ 6\n    y = i % 6\n    axes[x, y].imshow(image, cmap=plt.cm.bone) \n    axes[x, y].axis('off')\nfig, axes = plt.subplots(nrows=1, ncols=6, figsize=(16,6))\nplt.suptitle(\"Hue, Saturation, Brightness\", fontsize = 16)\n\nfor i in range(0, 2*6):\n    data = pydicom.read_file(train_df['path_dicom'][i])\n    image = data.pixel_array\n    \n    # Transform to B&W\n    # The function converts an input image from one color space to another.\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n    image = cv2.resize(image, (200,200))\n    \n    x = i \/\/ 6\n    y = i % 6\n    axes[x, y].imshow(image, cmap=plt.cm.bone) \n    axes[x, y].axis('off')\nfig, axes = plt.subplots(nrows=1, ncols=6, figsize=(16,6))\nplt.suptitle(\"LUV Color Space\", fontsize = 16)\n\nfor i in range(0, 2*6):\n    data = pydicom.read_file(train_df['path_dicom'][i])\n    image = data.pixel_array\n    \n    # Transform to B&W\n    # The function converts an input image from one color space to another.\n    image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)\n    image = cv2.resize(image, (200,200))\n    \n    x = i \/\/ 6\n    y = i % 6\n    axes[x, y].imshow(image, cmap=plt.cm.bone) \n    axes[x, y].axis('off')\n\n\nimage_list\ntrain_df\nt0=train_df['path_jpeg'][0]\nt1=train_df['path_jpeg'][1]\nt2=train_df['path_jpeg'][2]\nt3=train_df['path_jpeg'][3]\nt4=train_df['path_jpeg'][4]\nt5=train_df['path_jpeg'][5]\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t0)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t1)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t2)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t3)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t4)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t5)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t6)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n#image_list = train_df.sample(20)['path_jpeg']\n#image_list = image_list.reset_index()['path_jpeg']\n\n# Show the sample\nplt.figure(figsize=(16,16))\n#plt.suptitle(\"Original View\", fontsize = 16)\n    \n\nimage = mpimg.imread(t0)\nimage = cv2.resize(image, (512,512))\n#plt.subplot(2, 6, k+1)\nplt.imshow(image)\nplt.axis('off')\n","meta":"{'source': 'AI4Code', 'id': 'cc88ac919bea79'}"}
{"id":"124499","text":"import numpy as np # linear algebra\nimport math\nimport h5py\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom pandas.plotting import scatter_matrix\nimport os\nprint(os.listdir(\"..\/input\"))\n#Load data\ntrain = pd.read_csv(\"..\/input\/train.csv\")\ntest = pd.read_csv(\"..\/input\/test.csv\")\n\n#Load sub data\nsub = pd.read_csv(\"..\/input\/sample_submission.csv\")\nstructures = pd.read_csv(\"..\/input\/structures.csv\")\nscalar_coupling_contributions = pd.read_csv(\"..\/input\/scalar_coupling_contributions.csv\")\nmagnetic_shielding_tesors = pd.read_csv(\"..\/input\/magnetic_shielding_tensors.csv\")\ndipole_moments = pd.read_csv(\"..\/input\/dipole_moments.csv\")\npotential_energy = pd.read_csv(\"..\/input\/potential_energy.csv\")\nmulliken_charges = pd.read_csv(\"..\/input\/mulliken_charges.csv\")\nprint(train.shape)\nprint(test.shape)\nprint(sub.shape)\nprint(structures.shape)\nprint(scalar_coupling_contributions.shape)\nprint(magnetic_shielding_tesors.shape)\nprint(dipole_moments.shape)\nprint(potential_energy.shape)\nprint(mulliken_charges.shape)\n\n#check number of unique data \nprint(train[\"molecule_name\"].nunique())\nprint(test[\"molecule_name\"].nunique())\nprint(structures[\"atom\"].nunique())\nprint(train[\"type\"].nunique())\ndef map_atom_info(df, atom_idx):\n    df = pd.merge(df, structures, how = 'left',\n                  left_on  = ['molecule_name', f'atom_index_{atom_idx}'],\n                  right_on = ['molecule_name',  'atom_index'])\n    \n    df = df.drop('atom_index', axis=1)\n    df = df.rename(columns={'atom': f'atom_{atom_idx}',\n                            'x': f'x_{atom_idx}',\n                            'y': f'y_{atom_idx}',\n                            'z': f'z_{atom_idx}'})\n    return df\n\"\"\"\n### Merge Datasets\n\"\"\"\ntrain_structure = map_atom_info(train, 0)\ntrain_structure = map_atom_info(train_structure, 1)\ntest_structure = map_atom_info(test, 0)\ntest_structure = map_atom_info(test_structure, 1)\n\"\"\"\n### Computer Distance of atoms\nThe distance of atoms is sqrt((x_0 - x_1)^2 + (y_0 - y_1)^2 + (z_0 - z_1)^2), so I use numpy.linalg.norm.\n\"\"\"\ntrain_p_0 = train_structure[['x_0', 'y_0', 'z_0']].values\ntrain_p_1 = train_structure[['x_1', 'y_1', 'z_1']].values\ntrain_structure['dist'] = np.linalg.norm(train_p_0 - train_p_1, axis=1)\ntest_p_0 = test_structure[['x_0', 'y_0', 'z_0']].values\ntest_p_1 = test_structure[['x_1', 'y_1', 'z_1']].values\ntest_structure['dist'] = np.linalg.norm(test_p_0 - test_p_1, axis=1)\n\"\"\"\nAcademically, atomic number become large, scalar coupling constant also become large.\nSo, I want to add atomic number information in dataset.\n\"\"\"\ntrain_structure[\"atomic_number_0\"]=train_structure[\"atom_0\"].replace(\"H\", 1).replace(\"C\", 6).replace(\"N\", 7).replace(\"O\", 8).replace(\"F\", 9)\ntrain_structure[\"atomic_number_1\"]=train_structure[\"atom_1\"].replace(\"H\", 1).replace(\"C\", 6).replace(\"N\", 7).replace(\"O\", 8).replace(\"F\", 9)\ntest_structure[\"atomic_number_0\"]=test_structure[\"atom_0\"].replace(\"H\", 1).replace(\"C\", 6).replace(\"N\", 7).replace(\"O\", 8).replace(\"F\", 9)\ntest_structure[\"atomic_number_1\"]=test_structure[\"atom_1\"].replace(\"H\", 1).replace(\"C\", 6).replace(\"N\", 7).replace(\"O\", 8).replace(\"F\", 9)\n\"\"\"\nIn addition, maybe coupling number have effect for scalar coupling constant, let's add that.\n\"\"\"\ntrain_structure[\"coupling_number_0\"]=train_structure[\"atom_0\"].replace(\"H\", 1).replace(\"C\", 4).replace(\"N\", 3).replace(\"O\", 2).replace(\"F\", 1)\ntrain_structure[\"coupling_number_1\"]=train_structure[\"atom_1\"].replace(\"H\", 1).replace(\"C\", 4).replace(\"N\", 3).replace(\"O\", 2).replace(\"F\", 1)\ntest_structure[\"coupling_number_0\"]=test_structure[\"atom_0\"].replace(\"H\", 1).replace(\"C\", 4).replace(\"N\", 3).replace(\"O\", 2).replace(\"F\", 1)\ntest_structure[\"coupling_number_1\"]=test_structure[\"atom_1\"].replace(\"H\", 1).replace(\"C\", 4).replace(\"N\", 3).replace(\"O\", 2).replace(\"F\", 1)\ntest_structure.head(10)\n\"\"\"\n## New features using RDKIT \n\"\"\"\n!pip install --quiet cupy-cuda100\n!pip install --quiet chainer-chemistry\n!pip install --quiet chaineripy\n!conda install -y --quiet -c rdkit rdkit\n# Check correctly installed, and modules can be imported.\nimport chainer\nimport chainer_chemistry\nimport chaineripy\nimport cupy\nimport rdkit\n\nprint('chainer version: ', chainer.__version__)\nprint('cupy version: ', cupy.__version__)\nprint('chainer-chemistry version: ', chainer_chemistry.__version__)\nprint('rdkit version:', rdkit.__version__)\n\nfrom contextlib import contextmanager\nimport gc\nfrom pathlib import Path\nfrom time import time, perf_counter\n\nimport seaborn as sns\nfrom rdkit import Chem\nfrom chainer_chemistry.datasets.numpy_tuple_dataset import NumpyTupleDataset\ndef timer(name):\n    t0 = perf_counter()\n    yield\n    t1 = perf_counter()\n    print('[{}] done in {:.3f} s'.format(name, t1-t0))\n\"\"\"\nCopied from\nhttps:\/\/github.com\/jensengroup\/xyz2mol\/blob\/master\/xyz2mol.py\n\nModified `chiral_stereo_check` method for this task's purpose.\n\"\"\"\n##\n# Written by Jan H. Jensen based on this paper Yeonjoon Kim and Woo Youn Kim\n# \"Universal Structure Conversion Method for Organic Molecules: From Atomic Connectivity\n# to Three-Dimensional Geometry\" Bull. Korean Chem. Soc. 2015, Vol. 36, 1769-1777 DOI: 10.1002\/bkcs.10334\n#\nfrom rdkit.Chem import AllChem\nimport itertools\nfrom rdkit.Chem import rdmolops\nfrom collections import defaultdict\nimport copy\nimport networkx as nx  # uncomment if you don't want to use \"quick\"\/install networkx\n\nglobal __ATOM_LIST__\n__ATOM_LIST__ = [x.strip() for x in ['h ', 'he', \\\n                                     'li', 'be', 'b ', 'c ', 'n ', 'o ', 'f ', 'ne', \\\n                                     'na', 'mg', 'al', 'si', 'p ', 's ', 'cl', 'ar', \\\n                                     'k ', 'ca', 'sc', 'ti', 'v ', 'cr', 'mn', 'fe', 'co', 'ni', 'cu', \\\n                                     'zn', 'ga', 'ge', 'as', 'se', 'br', 'kr', \\\n                                     'rb', 'sr', 'y ', 'zr', 'nb', 'mo', 'tc', 'ru', 'rh', 'pd', 'ag', \\\n                                     'cd', 'in', 'sn', 'sb', 'te', 'i ', 'xe', \\\n                                     'cs', 'ba', 'la', 'ce', 'pr', 'nd', 'pm', 'sm', 'eu', 'gd', 'tb', 'dy', \\\n                                     'ho', 'er', 'tm', 'yb', 'lu', 'hf', 'ta', 'w ', 're', 'os', 'ir', 'pt', \\\n                                     'au', 'hg', 'tl', 'pb', 'bi', 'po', 'at', 'rn', \\\n                                     'fr', 'ra', 'ac', 'th', 'pa', 'u ', 'np', 'pu']]\n\n\ndef get_atom(atom):\n    global __ATOM_LIST__\n    atom = atom.lower()\n    return __ATOM_LIST__.index(atom) + 1\n\n\ndef getUA(maxValence_list, valence_list):\n    UA = []\n    DU = []\n    for i, (maxValence, valence) in enumerate(zip(maxValence_list, valence_list)):\n        if maxValence - valence > 0:\n            UA.append(i)\n            DU.append(maxValence - valence)\n    return UA, DU\n\n\ndef get_BO(AC, UA, DU, valences, UA_pairs, quick):\n    BO = AC.copy()\n    DU_save = []\n\n    while DU_save != DU:\n        for i, j in UA_pairs:\n            BO[i, j] += 1\n            BO[j, i] += 1\n\n        BO_valence = list(BO.sum(axis=1))\n        DU_save = copy.copy(DU)\n        UA, DU = getUA(valences, BO_valence)\n        UA_pairs = get_UA_pairs(UA, AC, quick)[0]\n\n    return BO\n\n\ndef valences_not_too_large(BO, valences):\n    number_of_bonds_list = BO.sum(axis=1)\n    for valence, number_of_bonds in zip(valences, number_of_bonds_list):\n        if number_of_bonds > valence:\n            return False\n\n    return True\n\n\ndef BO_is_OK(BO, AC, charge, DU, atomic_valence_electrons, atomicNumList, charged_fragments):\n    Q = 0  # total charge\n    q_list = []\n    if charged_fragments:\n        BO_valences = list(BO.sum(axis=1))\n        for i, atom in enumerate(atomicNumList):\n            q = get_atomic_charge(atom, atomic_valence_electrons[atom], BO_valences[i])\n            Q += q\n            if atom == 6:\n                number_of_single_bonds_to_C = list(BO[i, :]).count(1)\n                if number_of_single_bonds_to_C == 2 and BO_valences[i] == 2:\n                    Q += 1\n                    q = 2\n                if number_of_single_bonds_to_C == 3 and Q + 1 < charge:\n                    Q += 2\n                    q = 1\n\n            if q != 0:\n                q_list.append(q)\n\n    if (BO - AC).sum() == sum(DU) and charge == Q and len(q_list) <= abs(charge):\n        return True\n    else:\n        return False\n\n\ndef get_atomic_charge(atom, atomic_valence_electrons, BO_valence):\n    if atom == 1:\n        charge = 1 - BO_valence\n    elif atom == 5:\n        charge = 3 - BO_valence\n    elif atom == 15 and BO_valence == 5:\n        charge = 0\n    elif atom == 16 and BO_valence == 6:\n        charge = 0\n    else:\n        charge = atomic_valence_electrons - 8 + BO_valence\n\n    return charge\n\n\ndef clean_charges(mol):\n    # this hack should not be needed any more but is kept just in case\n    #\n\n    rxn_smarts = ['[N+:1]=[*:2]-[C-:3]>>[N+0:1]-[*:2]=[C-0:3]',\n                  '[N+:1]=[*:2]-[O-:3]>>[N+0:1]-[*:2]=[O-0:3]',\n                  '[N+:1]=[*:2]-[*:3]=[*:4]-[O-:5]>>[N+0:1]-[*:2]=[*:3]-[*:4]=[O-0:5]',\n                  '[#8:1]=[#6:2]([!-:6])[*:3]=[*:4][#6-:5]>>[*-:1][*:2]([*:6])=[*:3][*:4]=[*+0:5]',\n                  '[O:1]=[c:2][c-:3]>>[*-:1][*:2][*+0:3]',\n                  '[O:1]=[C:2][C-:3]>>[*-:1][*:2]=[*+0:3]']\n\n    fragments = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)\n\n    for i, fragment in enumerate(fragments):\n        for smarts in rxn_smarts:\n            patt = Chem.MolFromSmarts(smarts.split(\">>\")[0])\n            while fragment.HasSubstructMatch(patt):\n                rxn = AllChem.ReactionFromSmarts(smarts)\n                ps = rxn.RunReactants((fragment,))\n                fragment = ps[0][0]\n        if i == 0:\n            mol = fragment\n        else:\n            mol = Chem.CombineMols(mol, fragment)\n\n    return mol\n\n\ndef BO2mol(mol, BO_matrix, atomicNumList, atomic_valence_electrons, mol_charge, charged_fragments):\n    # based on code written by Paolo Toscani\n\n    l = len(BO_matrix)\n    l2 = len(atomicNumList)\n    BO_valences = list(BO_matrix.sum(axis=1))\n\n    if (l != l2):\n        raise RuntimeError('sizes of adjMat ({0:d}) and atomicNumList '\n                           '{1:d} differ'.format(l, l2))\n\n    rwMol = Chem.RWMol(mol)\n\n    bondTypeDict = {\n        1: Chem.BondType.SINGLE,\n        2: Chem.BondType.DOUBLE,\n        3: Chem.BondType.TRIPLE\n    }\n\n    for i in range(l):\n        for j in range(i + 1, l):\n            bo = int(round(BO_matrix[i, j]))\n            if (bo == 0):\n                continue\n            bt = bondTypeDict.get(bo, Chem.BondType.SINGLE)\n            rwMol.AddBond(i, j, bt)\n    mol = rwMol.GetMol()\n\n    if charged_fragments:\n        mol = set_atomic_charges(mol, atomicNumList, atomic_valence_electrons, BO_valences, BO_matrix, mol_charge)\n    else:\n        mol = set_atomic_radicals(mol, atomicNumList, atomic_valence_electrons, BO_valences)\n\n    return mol\n\n\ndef set_atomic_charges(mol, atomicNumList, atomic_valence_electrons, BO_valences, BO_matrix, mol_charge):\n    q = 0\n    for i, atom in enumerate(atomicNumList):\n        a = mol.GetAtomWithIdx(i)\n        charge = get_atomic_charge(atom, atomic_valence_electrons[atom], BO_valences[i])\n        q += charge\n        if atom == 6:\n            number_of_single_bonds_to_C = list(BO_matrix[i, :]).count(1)\n            if number_of_single_bonds_to_C == 2 and BO_valences[i] == 2:\n                q += 1\n                charge = 0\n            if number_of_single_bonds_to_C == 3 and q + 1 < mol_charge:\n                q += 2\n                charge = 1\n\n        if (abs(charge) > 0):\n            a.SetFormalCharge(int(charge))\n\n    # shouldn't be needed anymore bit is kept just in case\n    # mol = clean_charges(mol)\n\n    return mol\n\n\ndef set_atomic_radicals(mol, atomicNumList, atomic_valence_electrons, BO_valences):\n    # The number of radical electrons = absolute atomic charge\n    for i, atom in enumerate(atomicNumList):\n        a = mol.GetAtomWithIdx(i)\n        charge = get_atomic_charge(atom, atomic_valence_electrons[atom], BO_valences[i])\n\n        if (abs(charge) > 0):\n            a.SetNumRadicalElectrons(abs(int(charge)))\n\n    return mol\n\n\ndef get_bonds(UA, AC):\n    bonds = []\n\n    for k, i in enumerate(UA):\n        for j in UA[k + 1:]:\n            if AC[i, j] == 1:\n                bonds.append(tuple(sorted([i, j])))\n\n    return bonds\n\n\ndef get_UA_pairs(UA, AC, quick):\n    bonds = get_bonds(UA, AC)\n    if len(bonds) == 0:\n        return [()]\n\n    if quick:\n        G = nx.Graph()\n        G.add_edges_from(bonds)\n        UA_pairs = [list(nx.max_weight_matching(G))]\n        return UA_pairs\n\n    max_atoms_in_combo = 0\n    UA_pairs = [()]\n    for combo in list(itertools.combinations(bonds, int(len(UA) \/ 2))):\n        flat_list = [item for sublist in combo for item in sublist]\n        atoms_in_combo = len(set(flat_list))\n        if atoms_in_combo > max_atoms_in_combo:\n            max_atoms_in_combo = atoms_in_combo\n            UA_pairs = [combo]\n        #           if quick and max_atoms_in_combo == 2*int(len(UA)\/2):\n        #               return UA_pairs\n        elif atoms_in_combo == max_atoms_in_combo:\n            UA_pairs.append(combo)\n\n    return UA_pairs\n\n\ndef AC2BO(AC, atomicNumList, charge, charged_fragments, quick):\n    # TODO\n    atomic_valence = defaultdict(list)\n    atomic_valence[1] = [1]\n    atomic_valence[6] = [4]\n    atomic_valence[7] = [4, 3]\n    atomic_valence[8] = [2, 1]\n    atomic_valence[9] = [1]\n    atomic_valence[14] = [4]\n    atomic_valence[15] = [5, 4, 3]\n    atomic_valence[16] = [6, 4, 2]\n    atomic_valence[17] = [1]\n    atomic_valence[32] = [4]\n    atomic_valence[35] = [1]\n    atomic_valence[53] = [1]\n\n    atomic_valence_electrons = {}\n    atomic_valence_electrons[1] = 1\n    atomic_valence_electrons[6] = 4\n    atomic_valence_electrons[7] = 5\n    atomic_valence_electrons[8] = 6\n    atomic_valence_electrons[9] = 7\n    atomic_valence_electrons[14] = 4\n    atomic_valence_electrons[15] = 5\n    atomic_valence_electrons[16] = 6\n    atomic_valence_electrons[17] = 7\n    atomic_valence_electrons[32] = 4\n    atomic_valence_electrons[35] = 7\n    atomic_valence_electrons[53] = 7\n\n    # make a list of valences, e.g. for CO: [[4],[2,1]]\n    valences_list_of_lists = []\n    for atomicNum in atomicNumList:\n        valences_list_of_lists.append(atomic_valence[atomicNum])\n\n    # convert [[4],[2,1]] to [[4,2],[4,1]]\n    valences_list = list(itertools.product(*valences_list_of_lists))\n\n    best_BO = AC.copy()\n\n    # implemenation of algorithm shown in Figure 2\n    # UA: unsaturated atoms\n    # DU: degree of unsaturation (u matrix in Figure)\n    # best_BO: Bcurr in Figure\n    #\n\n    for valences in valences_list:\n        AC_valence = list(AC.sum(axis=1))\n        UA, DU_from_AC = getUA(valences, AC_valence)\n\n        if len(UA) == 0 and BO_is_OK(AC, AC, charge, DU_from_AC, atomic_valence_electrons, atomicNumList,\n                                     charged_fragments):\n            return AC, atomic_valence_electrons\n\n        UA_pairs_list = get_UA_pairs(UA, AC, quick)\n        for UA_pairs in UA_pairs_list:\n            BO = get_BO(AC, UA, DU_from_AC, valences, UA_pairs, quick)\n            if BO_is_OK(BO, AC, charge, DU_from_AC, atomic_valence_electrons, atomicNumList, charged_fragments):\n                return BO, atomic_valence_electrons\n\n            elif BO.sum() >= best_BO.sum() and valences_not_too_large(BO, valences):\n                best_BO = BO.copy()\n\n    return best_BO, atomic_valence_electrons\n\n\ndef AC2mol(mol, AC, atomicNumList, charge, charged_fragments, quick):\n    # convert AC matrix to bond order (BO) matrix\n    BO, atomic_valence_electrons = AC2BO(AC, atomicNumList, charge, charged_fragments, quick)\n\n    # add BO connectivity and charge info to mol object\n    mol = BO2mol(mol, BO, atomicNumList, atomic_valence_electrons, charge, charged_fragments)\n\n    return mol\n\n\ndef get_proto_mol(atomicNumList):\n    mol = Chem.MolFromSmarts(\"[#\" + str(atomicNumList[0]) + \"]\")\n    rwMol = Chem.RWMol(mol)\n    for i in range(1, len(atomicNumList)):\n        a = Chem.Atom(atomicNumList[i])\n        rwMol.AddAtom(a)\n\n    mol = rwMol.GetMol()\n\n    return mol\n\n\ndef get_atomicNumList(atomic_symbols):\n    atomicNumList = []\n    for symbol in atomic_symbols:\n        atomicNumList.append(get_atom(symbol))\n    return atomicNumList\n\n\ndef read_xyz_file(filename):\n    atomic_symbols = []\n    xyz_coordinates = []\n\n    with open(filename, \"r\") as file:\n        for line_number, line in enumerate(file):\n            if line_number == 0:\n                num_atoms = int(line)\n            elif line_number == 1:\n                if \"charge=\" in line:\n                    charge = int(line.split(\"=\")[1])\n                else:\n                    charge = 0\n            else:\n                atomic_symbol, x, y, z = line.split()\n                atomic_symbols.append(atomic_symbol)\n                xyz_coordinates.append([float(x), float(y), float(z)])\n\n    atomicNumList = get_atomicNumList(atomic_symbols)\n\n    return atomicNumList, charge, xyz_coordinates\n\n\ndef xyz2AC(atomicNumList, xyz):\n    import numpy as np\n    mol = get_proto_mol(atomicNumList)\n\n    conf = Chem.Conformer(mol.GetNumAtoms())\n    for i in range(mol.GetNumAtoms()):\n        conf.SetAtomPosition(i, (xyz[i][0], xyz[i][1], xyz[i][2]))\n    mol.AddConformer(conf)\n\n    dMat = Chem.Get3DDistanceMatrix(mol)\n    pt = Chem.GetPeriodicTable()\n\n    num_atoms = len(atomicNumList)\n    AC = np.zeros((num_atoms, num_atoms)).astype(int)\n\n    for i in range(num_atoms):\n        a_i = mol.GetAtomWithIdx(i)\n        Rcov_i = pt.GetRcovalent(a_i.GetAtomicNum()) * 1.30\n        for j in range(i + 1, num_atoms):\n            a_j = mol.GetAtomWithIdx(j)\n            Rcov_j = pt.GetRcovalent(a_j.GetAtomicNum()) * 1.30\n            if dMat[i, j] <= Rcov_i + Rcov_j:\n                AC[i, j] = 1\n                AC[j, i] = 1\n\n    return AC, mol\n\n\ndef chiral_stereo_check(mol):\n    # Chem.SanitizeMol(mol)\n    num_error = Chem.SanitizeMol(mol, Chem.SANITIZE_ALL ^ Chem.SANITIZE_PROPERTIES, catchErrors=True)\n    if num_error != 0:\n        print('error id', num_error)\n\n    Chem.DetectBondStereochemistry(mol, -1)\n    Chem.AssignStereochemistry(mol, flagPossibleStereoCenters=True, force=True)\n    Chem.AssignAtomChiralTagsFromStructure(mol, -1)\n\n    return mol\n\n\ndef xyz2mol(atomicNumList, charge, xyz_coordinates, charged_fragments, quick):\n    # Get atom connectivity (AC) matrix, list of atomic numbers, molecular charge,\n    # and mol object with no connectivity information\n    AC, mol = xyz2AC(atomicNumList, xyz_coordinates)\n\n    # Convert AC to bond order matrix and add connectivity and charge info to mol object\n    new_mol = AC2mol(mol, AC, atomicNumList, charge, charged_fragments, quick)\n\n    # Check for stereocenters and chiral centers\n    new_mol = chiral_stereo_check(new_mol)\n\n    return new_mol\ndef mol_from_xyz(filepath, to_canonical=False):\n    charged_fragments = True  # alternatively radicals are made\n\n    # quick is faster for large systems but requires networkx\n    # if you don't want to install networkx set quick=False and\n    # uncomment 'import networkx as nx' at the top of the file\n    quick = True\n\n    atomicNumList, charge, xyz_coordinates = read_xyz_file(filepath)\n    # print('atomicNumList', atomicNumList, 'charge', charge)\n    mol = xyz2mol(atomicNumList, charge, xyz_coordinates, charged_fragments, quick)\n\n    # Canonical hack\n    if to_canonical:\n        smiles = Chem.MolToSmiles(mol, isomericSmiles=True)\n        mol = Chem.MolFromSmiles(smiles)\n    return mol\n# This script is referred from http:\/\/rdkit.blogspot.jp\/2015\/02\/new-drawing-code.html\n# and http:\/\/cheminformist.itmol.com\/TEST\/wp-content\/uploads\/2015\/07\/rdkit_moldraw2d_2.html\nfrom __future__ import print_function\nfrom rdkit import Chem\nfrom rdkit.Chem.Draw import IPythonConsole\nfrom IPython.display import SVG\n\nfrom rdkit.Chem import rdDepictor\nfrom rdkit.Chem.Draw import rdMolDraw2D\ndef moltosvg(mol,molSize=(450,150),kekulize=True):\n    mc = Chem.Mol(mol.ToBinary())\n    if kekulize:\n        try:\n            Chem.Kekulize(mc)\n        except:\n            mc = Chem.Mol(mol.ToBinary())\n    if not mc.GetNumConformers():\n        rdDepictor.Compute2DCoords(mc)\n    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])\n    drawer.DrawMolecule(mc)\n    drawer.FinishDrawing()\n    svg = drawer.GetDrawingText()\n    return svg\n\ndef render_svg(svg):\n    # It seems that the svg renderer used doesn't quite hit the spec.\n    # Here are some fixes to make it work in the notebook, although I think\n    # the underlying issue needs to be resolved at the generation step\n    return SVG(svg.replace('svg:',''))\ntrain_mol_names = train['molecule_name'].unique()\ntest_mol_names = test['molecule_name'].unique()\nmol_names = np.hstack((train_mol_names, test_mol_names))\nprint(mol_names)\n#This for loop need a few minutes calculation\ninput_dir = Path('..\/input')\nmol_data=[]\nfor mol_id in mol_names:\n    filepath = input_dir\/f'structures\/{mol_id}.xyz'\n    mol_data.append(mol_from_xyz(filepath, to_canonical=True))\nmol =pd.DataFrame({\"molecule_name\":mol_names, \"mol_data\":mol_data})\nsmiles=[]\nfor i in range(mol.shape[0]):\n    smiles.append(Chem.MolToSmiles(mol.mol_data[i], isomericSmiles=False))\nmol =pd.DataFrame({\"molecule_name\":mol_names, \"mol_data\":mol_data, \"smiles\":smiles})\n#It looks success to convert xyz files\nmol.head()\n\"\"\"\n## Figerprints\n\"\"\"\nfrom rdkit import rdBase, Chem, DataStructs\nprint(rdBase.rdkitVersion) # 2017.09.1\nfrom rdkit.Avalon import pyAvalonTools\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem.Fingerprints import FingerprintMols\nfrom rdkit.Chem.AtomPairs import Pairs, Torsions\nfrom rdkit.Chem import MACCSkeys\nfrom rdkit.Chem import Descriptors\nfrom rdkit.ML.Descriptors import MoleculeDescriptors\nfps1 = [ MACCSkeys.GenMACCSKeys(mol1).ToBitString() for mol1 in mol.mol_data]\nfps2 = [ list(map(int,list(fps))) for fps in fps1]\nfps3 = np.array(fps2)\nfps3.shape\n#change data type ndarray to dataframe\nfingerprints = pd.DataFrame(fps3)\nfingerprints.head()\n#merge dataset\nmol = mol.join(fingerprints)\nmol.head()\n\"\"\"\n## Compute descriptors\n\"\"\"\ndef calculate_descriptors(mols, names=None, ipc_avg=False):\n    if names is None:\n        names = [d[0] for d in Descriptors._descList]\n    calc = MoleculeDescriptors.MolecularDescriptorCalculator(names)\n    descs = [calc.CalcDescriptors(mol) for mol in mols]\n    descs = pd.DataFrame(descs, columns=names)\n    if 'Ipc' in names and ipc_avg:\n        descs['Ipc'] = [Descriptors.Ipc(mol, avg=True) for mol in mols]      \n    return descs\ndescriptors = calculate_descriptors(mol.mol_data)\n#Merge dataset\nmol = mol.join(descriptors)\nmol.head()\nmol.to_csv('mol_dataset.csv',index=False)\n\"\"\"\n## Evaluate 166 parameters - PCA\n\"\"\"\ndef main():\n    mols = mol.mol_data\n\n    fps = [MACCSkeys.GenMACCSKeys(mol1) for mol1 in mols]\n    fpMtx = np.array([fp2arr(fp) for fp in fps])\n\n    plotPCA(fpMtx)\n\n# convert rdkit fingerprint to numpy array\ndef fp2arr(fp):\n    arr = np.zeros((1,))\n    DataStructs.ConvertToNumpyArray(fp, arr)\n    return arr\n\n\n# plot each compound using PCA\ndef plotPCA(fpMtx):\n    from sklearn.decomposition import PCA\n\n    pca = PCA(n_components=2)\n    res = pca.fit_transform(fpMtx)\n    # extract each component\n    pc = res.T\n\n    cum_cr = sum(pca.explained_variance_ratio_)\n    print(\"cumulative contribution ratio=%.2f\" % cum_cr)\n\n    plt.figure()\n    plt.scatter(pc[0], pc[1], marker=\".\")\n    plt.xlabel(\"PC1\")\n    plt.ylabel(\"PC2\")\n    plt.legend()\n    plt.savefig(\"pca_plot.png\")\n\nif __name__ == \"__main__\":\n    main()","meta":"{'source': 'AI4Code', 'id': 'e4f864dd0dcf46'}"}
{"id":"117503","text":"\"\"\"\n# Attention! Warning! Use at your own risk!\n\nIf you are going to use pseudo labeling technique (which is used in this kernel) make sure you **understand what you are doing**. Otherwise you will **horribly overfit** to Public LB and will be shaken down on Private LB.\n\nThus you should not use this submission as is, but instead find a way to improve your model with this technique.\n\n![](https:\/\/cdn1.imggmi.com\/uploads\/2019\/6\/4\/52f979f0a731c7806f225c5b5cdc1b87-full.png)\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom tqdm import tqdm_notebook\nimport warnings\nimport multiprocessing\nwarnings.filterwarnings('ignore')\n\"\"\"\nLoading data with multiprocessing. Lets make those CPU cores work.\n\"\"\"\ndef load_data(data):\n    return pd.read_csv(data)\n\nwith multiprocessing.Pool() as pool:\n    train, test, sub = pool.map(load_data, ['..\/input\/train.csv', '..\/input\/test.csv', '..\/input\/sample_submission.csv'])\n\"\"\"\nTraining first model with QDA, since it performs best on this dataset. We need predictions to make pseudo labeles furter on.\n\"\"\"\ncols = [c for c in train.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']]\noof = np.zeros(len(train))\npreds = np.zeros(len(test))\n\nfor i in tqdm_notebook(range(512)):\n\n    train2 = train[train['wheezy-copper-turtle-magic']==i]\n    test2 = test[test['wheezy-copper-turtle-magic']==i]\n    idx1 = train2.index; idx2 = test2.index\n    train2.reset_index(drop=True,inplace=True)\n\n    data = pd.concat([pd.DataFrame(train2[cols]), pd.DataFrame(test2[cols])])\n    data2 = VarianceThreshold(threshold=2).fit_transform(data[cols])\n\n    train3 = data2[:train2.shape[0]]; test3 = data2[train2.shape[0]:]\n\n    skf = StratifiedKFold(n_splits=11, random_state=42)\n    for train_index, test_index in skf.split(train2, train2['target']):\n\n        clf = QuadraticDiscriminantAnalysis(0.6)\n        clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n        oof[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n        preds[idx2] += clf.predict_proba(test3)[:,1] \/ skf.n_splits\n\nauc = roc_auc_score(train['target'], oof)\nprint(f'AUC: {auc:.5}')\n\"\"\"\nAlright. By now we have predictions in *preds* variable. On some rows in test set model is pretty sure with its prediction, so some samples are predicted as 0.99999 and some as 0.00001. \n\nWe assume that this is a correct case and simply label those samples as 1's and 0's respectively.\n\"\"\"\ntest['target'] = preds\ntest.loc[test['target'] > 0.99999, 'target'] = 1\ntest.loc[test['target'] < 0.00001, 'target'] = 0\n\"\"\"\nNow we are adding this new marked samples to our training set. So next we will train on whole training set and a **part** of test set. This is where overfitting comes from.\n\"\"\"\nusefull_test = test[(test['target'] == 1) | (test['target'] == 0)]\nnew_train = pd.concat([train, usefull_test]).reset_index(drop=True)\n\"\"\"\nAnd the next model we are building is now training on this combined data.\n\"\"\"\noof = np.zeros(len(new_train))\npreds = np.zeros(len(test))\n\nfor i in tqdm_notebook(range(512)):\n\n    train2 = new_train[new_train['wheezy-copper-turtle-magic']==i]\n    test2 = test[test['wheezy-copper-turtle-magic']==i]\n    idx1 = train2.index; idx2 = test2.index\n    train2.reset_index(drop=True,inplace=True)\n\n    data = pd.concat([pd.DataFrame(train2[cols]), pd.DataFrame(test2[cols])])\n    data2 = VarianceThreshold(threshold=2).fit_transform(data[cols])\n\n    train3 = data2[:train2.shape[0]]; test3 = data2[train2.shape[0]:]\n\n    skf = StratifiedKFold(n_splits=15, random_state=42)\n    for train_index, test_index in skf.split(train2, train2['target']):\n\n        clf = QuadraticDiscriminantAnalysis(0.1)\n        clf.fit(train3[train_index,:],train2.loc[train_index]['target'])\n        oof[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]\n        preds[idx2] += clf.predict_proba(test3)[:,1] \/ skf.n_splits\n\nauc = roc_auc_score(new_train['target'], oof)\nprint(f'AUC: {auc:.5}')\n\"\"\"\nEdit: Fixed a problem with CV, which was incorrect because of pandas DataFrame indexes collisions.\n\"\"\"\nsub['target'] = preds\nsub.to_csv('submission.csv', index=False)\npd.Series(oof[-usefull_test.shape[0]:]).plot(kind='hist', bins=50)\nauc = roc_auc_score(train['target'], oof[:-usefull_test.shape[0]])\nprint(f'AUC: {auc:.5}')\nauc = roc_auc_score(new_train['target'].iloc[-usefull_test.shape[0]:], oof[-usefull_test.shape[0]:])\nprint(f'AUC: {auc:.5}')\n\"\"\"\nCV score of raw train data is 0.9695, CV score of the new_train data which is added in raw data is 1.0, PB score is 0.9681, the gap is acceptable, so i think there is no overfitting!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd83190f08322f8'}"}
{"id":"11379","text":"\"\"\"\n# Candy Cane - Multi-Armed Bandit\n\nThis notebook shows how to use multi-armed bandit.\n\nMulti-armed bandit is a widely used RL-algorithm because it is very balanced in terms of exploitation\/exploration.\n\nAlgorithm logic:\n\n- At each step for each bandit generate a random number from B(a+1, b+1). B - beta-distribution, a - decay adjusted total reward from this bandit, b - number of this bandits's historical losses.\n- Select the bandit with the largest generated number and use it to generate the next step\n- Unless we won last round, in which case repeat the last action\n\"\"\"\n!pip install kaggle-environments --upgrade -q\n%%writefile submission.py\n\nimport json\nimport numpy as np\nimport pandas as pd\n\nclass MultiArmedBandit:\n\n    def __init__(self, no_reward_step=0.95, retry_winrate=False):\n        self.no_reward_step = no_reward_step\n        self.retry_winrate  = retry_winrate\n\n        self.bandit_state   = None\n        self.total_reward   = 0\n        self.last_step      = 0\n        \n    def __call__(self, obs, conf):\n        return self.agent(obs, conf)\n        \n        \n    # observation   {'remainingOverageTime': 60, 'agentIndex': 1, 'reward': 0, 'step': 0, 'lastActions': []}\n    # configuration {'episodeSteps': 2000, 'actTimeout': 0.25, 'runTimeout': 1200, 'banditCount': 100, 'decayRate': 0.97, 'sampleResolution': 100}\n    def agent(self, obs, conf):\n        # print('observation',   obs)\n        # print('configuration', conf)\n        # print('self.bandit_state', self.bandit_state)\n        # global history, history_bandit\n        # global bandit_state,total_reward,last_step\n\n        # updating bandit_state using the result of the previous step\n        last_reward       = obs.reward - self.total_reward\n        self.total_reward = obs.reward\n        \n        if obs.step == 0:\n            # initial bandit state\n            self.bandit_state = [[1,1] for i in range(conf.banditCount)]\n        else:       \n            if last_reward > 0:\n                self.bandit_state[ obs.lastActions[obs.agentIndex] ][0] += last_reward\n            else:\n                self.bandit_state[ obs.lastActions[obs.agentIndex] ][1] += self.no_reward_step\n\n            self.bandit_state[ obs.lastActions[0] ][0] = (\n                (self.bandit_state[ obs.lastActions[0] ][0] - 1) * conf.decayRate + 1\n            )\n            self.bandit_state[ obs.lastActions[1] ][0] = (\n                (self.bandit_state[ obs.lastActions[1] ][0] - 1) * conf.decayRate + 1\n            )\n\n            \n        # Repeat last action if we got a reward\n        if self.retry_winrate and last_reward == 1:\n            best_agent = self.last_step\n\n        # generate random number from Beta distribution for each agent and select the most lucky one            \n        else:            \n            best_proba = -1\n            best_agent = self.last_step  # None\n            for k in range(conf.banditCount):\n                proba = np.random.beta( self.bandit_state[k][0], self.bandit_state[k][1] )\n                if proba > best_proba:\n                    best_proba = proba\n                    best_agent = k\n\n        self.last_step = best_agent\n        return best_agent\n    \n    \nMultiArmedBandit_instance = MultiArmedBandit()\ndef MultiArmedBandit_agent(obs, conf):\n    return MultiArmedBandit_instance(obs, conf)\n%%writefile random_agent.py\n\nimport random\nclass RandomAgent():\n    def __call__(observation, configuration):\n        return random.randrange(configuration.banditCount)\n    \ndef random_agent(observation, configuration):\n    return random.randrange(configuration.banditCount)\n%run submission.py\n%run random_agent.py\nfrom kaggle_environments import make, evaluate\n\nprint([\"submission.py\", \"random_agent.py\"], evaluate(\"mab\", [\"submission.py\", \"random_agent.py\"]) )\nprint([\"submission.py\", \"submission.py  \"], evaluate(\"mab\", [\"submission.py\", \"submission.py\"]) )\nprint([\"MultiArmedBandit(0.4)\", \"MultiArmedBandit(0.75)\"], evaluate(\"mab\", [MultiArmedBandit(no_reward_step=0.4), MultiArmedBandit(no_reward_step=0.75)]) )\nfrom kaggle_environments import make\n\nenv = make(\"mab\", debug=True)\n\nenv.reset()\nenv.run([\"submission.py\", \"random_agent.py\"])\nenv.render(mode=\"ipython\", width=500, height=500)\n\"\"\"\n# Hyperparameters\n\"\"\"\nimport glob\nimport re\nimport os\nimport itertools\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\nfrom collections import defaultdict\nfrom joblib import Parallel, delayed\nfrom kaggle_environments import evaluate, make, utils\n%%time\nagents = {\n    MultiArmedBandit(no_reward_step=n, retry_winrate=retry_winrate): f'no_reward_step={n:.2f} retry_winrate={retry_winrate}'\n    for n in np.arange(0.75, 1.0, 0.05)\n    for retry_winrate in [ True, False ]\n}\nagents[\"random_agent.py\"] = \"random_agent\" \nagents[\"..\/input\/rock-paper-candy-copy-opponent-move-unless-win\/submission.py\"] = \"copy_opponent_unless_win\" \nagents[\"..\/input\/candy-cane-optimized-ucb\/submission.py\"]                       = \"optimized-ucb\"\n# print(agents)\n\ndef evaluate_mab(i1, i2, agent1, agent2):\n    # print(i1, i2, agent1, agent2)\n    try:\n        result = evaluate(\"mab\", [ agent1, agent2 ])\n        result = np.array(result).flatten()\n    except:\n        result = np.array([0,0])\n    return (i1, i2, result)\n    \nresults = Parallel(-1)( \n    delayed(evaluate_mab)(i1, i2, agent1, agent2) \n    for i1, agent1 in enumerate(agents.keys())\n    for i2, agent2 in enumerate(agents.keys())\n    for n in range(10)\n    if i1 < i2\n)\n# results\ndef winrate_score(score1, score2):\n    try:\n        if score1 == score2: return  0\n        if score1 is None:   return -1\n        if score2 is None:   return  1\n        if score1 >  score2: return  1\n        if score1 <  score2: return -1\n    except: pass\n    return 0\n    \n\nscores_agent = defaultdict(list)\nscores_total = np.zeros(( len(agents), len(agents) ), dtype=np.int)\nscores_diff  = np.zeros(( len(agents), len(agents) ), dtype=np.float)\nwinrates     = np.zeros(( len(agents), len(agents) ), dtype=np.int)\n\nfor (i1, i2, result) in results:\n    scores_total[i1,i2] += (result[0] or 0)\n    scores_total[i2,i1] += (result[1] or 0)\n    scores_diff[i1,i2]  += (result[0] or 0) - (result[1] or 0) \n    scores_diff[i2,i1]  += (result[1] or 0) - (result[0] or 0)\n    winrates[i1,i2]     += winrate_score(result[0], result[1])\n    winrates[i2,i1]     += winrate_score(result[1], result[0])\n    scores_agent[ list(agents.values())[i1] ].append( result[0] )\n    scores_agent[ list(agents.values())[i2] ].append( result[1] )\n    \ndf_scores_total = pd.DataFrame(\n    scores_total, \n    index   = list(agents.values()), \n    columns = list(agents.values()),\n)\ndf_scores_diff = pd.DataFrame(\n    scores_diff, \n    index   = list(agents.values()), \n    columns = list(agents.values()),\n)\ndf_winrates = pd.DataFrame(\n    winrates, \n    index   = list(agents.values()), \n    columns = list(agents.values()),\n)\ndf_scores_agent = pd.DataFrame(scores_agent)\n\n# Sort by mean score\nfor axis in [0,1]:\n    df_scores_total = df_scores_total.reindex( df_scores_agent.mean().sort_values(ascending=False).index, axis=axis)\n    df_scores_diff  = df_scores_diff.reindex(  df_scores_agent.mean().sort_values(ascending=False).index, axis=axis)\n    df_winrates     = df_winrates.reindex(     df_scores_agent.mean().sort_values(ascending=False).index, axis=axis)\ndf_scores_agent = df_scores_agent.reindex( df_scores_agent.mean().sort_values(ascending=False).index, axis=1)\n\n\ndf_scores_agent.T\ndef batch(iterable, n=1):\n    l = len(iterable)\n    for ndx in range(0, l, n):\n        yield iterable[ndx:min(ndx + n, l)]\n\n        \ndef plot_df_heatmap(df, title, **kwargs):\n    plt.figure(figsize=(df.shape[0], df.shape[1]))\n    plt.title(title)\n    sns.heatmap(\n        df, annot=True, cbar=False, \n        cmap='coolwarm', linewidths=1, \n        linecolor='black', \n        fmt='.0f',\n        **kwargs\n    )\n    plt.tick_params(labeltop=True, labelright=True)\n    plt.xticks(rotation=90, fontsize=max(10,df.shape[0]))\n    plt.yticks(rotation=0,  fontsize=max(10,df.shape[0]))\n    print(title)\n    print(df.mean(axis=1).sort_values(ascending=False))\n    \n    \ndef plot_df_boxplot(df, title, columns=10, boxplot_args={}, stripplot_args={}):\n    df_orig = df\n    n_rows    = math.ceil( len(df.columns) \/ columns )\n    n_columns = math.ceil( len(df.columns) \/ n_rows  )\n    for cols in batch(df.columns, n_columns):\n        df = df_orig[cols]\n        plt.figure(figsize=(n_columns*2, n_rows*6))\n        plt.title(title, loc=\"center\")\n\n        stripplot_args = { \"facecolor\": 'white', **boxplot_args }\n        ax = sns.boxplot(data=df, **boxplot_args)\n        plt.setp(ax.artists, edgecolor='grey', facecolor='w')\n        plt.setp(ax.lines, color='grey')\n\n        stripplot_args = { \"jitter\": 0.33, \"size\": 5, **stripplot_args }\n        ax = sns.stripplot(data=df, **stripplot_args)\n\n        # ax = sns.swarmplot(data=df_scores_agent)\n        plt.xticks(rotation=90, fontsize=15)\n        plt.yticks(rotation=0,  fontsize=15)\n        pass\nplot_df_heatmap(df_scores_total, 'Total Scores')\nplot_df_heatmap(df_scores_diff, 'Relative Scores')\nplot_df_boxplot(df_scores_agent, \"All Matchmaking Scores\")\n\"\"\"\n# Further Reading\n\nThis notebook is part of a series exploring the Santa2020 Candy Cane competition\n- [Rock Paper Candy - Copy Opponent Move](https:\/\/www.kaggle.com\/jamesmcguigan\/rock-paper-candy-copy-opponent-move)\n- [Rock Paper Candy - Copy Opponent Move Unless Win](https:\/\/www.kaggle.com\/jamesmcguigan\/rock-paper-candy-copy-opponent-move-unless-win)\n- [Candy Cane - Multi-Armed Bandit](https:\/\/www.kaggle.com\/jamesmcguigan\/candy-cane-multi-armed-bandit)\n- [Candy Cane - Optimized UCB](https:\/\/www.kaggle.com\/jamesmcguigan\/candy-cane-optimized-ucb)\n- [Candy Cane - Random Agent](https:\/\/www.kaggle.com\/jamesmcguigan\/candy-cane-random-agent)\n\nI also created an agents comparison notebook to compare the relative strengths of public agents:\n- [Santa 2020 - Agents Comparison](https:\/\/www.kaggle.com\/jamesmcguigan\/santa-2020-agents-comparison\/)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '14dafb6fbfe124'}"}
{"id":"123961","text":"\"\"\"\nThis notebook was made from scratch by me.  \nThe idea is reducing the 800,000 long mesurements to some shorter vector that is more fitted to a LSTM.  \nThis code below transform the 800.000 mesurements of the 3 diferent phases in a unique (80, 39) matrix.  \nThe matthews ocrrelation and attention functions are not mine.  \n\"\"\"\nimport pandas as pd\nimport pyarrow.parquet as pq\nimport os\nimport numpy as np\nfrom keras.layers import *\nfrom keras.models import Model\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend as K\nprint(os.listdir(\"..\/input\"))\ndef matthews_correlation(y_true, y_pred):\n    '''Calculates the Matthews correlation coefficient measure for quality\n    of binary classification problems.\n    '''\n    y_pred_pos = K.round(K.clip(y_pred, 0, 1))\n    y_pred_neg = 1 - y_pred_pos\n\n    y_pos = K.round(K.clip(y_true, 0, 1))\n    y_neg = 1 - y_pos\n\n    tp = K.sum(y_pos * y_pred_pos)\n    tn = K.sum(y_neg * y_pred_neg)\n\n    fp = K.sum(y_neg * y_pred_pos)\n    fn = K.sum(y_pos * y_pred_neg)\n\n    numerator = (tp * tn - fp * fn)\n    denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))\n\n    return numerator \/ (denominator + K.epsilon())\n# https:\/\/www.kaggle.com\/suicaokhoailang\/lstm-attention-baseline-0-652-lb\n\nclass Attention(Layer):\n    def __init__(self, step_dim,\n                 W_regularizer=None, b_regularizer=None,\n                 W_constraint=None, b_constraint=None,\n                 bias=True, **kwargs):\n        self.supports_masking = True\n        self.init = initializers.get('glorot_uniform')\n\n        self.W_regularizer = regularizers.get(W_regularizer)\n        self.b_regularizer = regularizers.get(b_regularizer)\n\n        self.W_constraint = constraints.get(W_constraint)\n        self.b_constraint = constraints.get(b_constraint)\n\n        self.bias = bias\n        self.step_dim = step_dim\n        self.features_dim = 0\n        super(Attention, self).__init__(**kwargs)\n\n    def build(self, input_shape):\n        assert len(input_shape) == 3\n\n        self.W = self.add_weight((input_shape[-1],),\n                                 initializer=self.init,\n                                 name='{}_W'.format(self.name),\n                                 regularizer=self.W_regularizer,\n                                 constraint=self.W_constraint)\n        self.features_dim = input_shape[-1]\n\n        if self.bias:\n            self.b = self.add_weight((input_shape[1],),\n                                     initializer='zero',\n                                     name='{}_b'.format(self.name),\n                                     regularizer=self.b_regularizer,\n                                     constraint=self.b_constraint)\n        else:\n            self.b = None\n\n        self.built = True\n\n    def compute_mask(self, input, input_mask=None):\n        return None\n\n    def call(self, x, mask=None):\n        features_dim = self.features_dim\n        step_dim = self.step_dim\n\n        eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n                        K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n        if self.bias:\n            eij += self.b\n\n        eij = K.tanh(eij)\n\n        a = K.exp(eij)\n\n        if mask is not None:\n            a *= K.cast(mask, K.floatx())\n\n        a \/= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n        a = K.expand_dims(a)\n        weighted_input = x * a\n        return K.sum(weighted_input, axis=1)\n\n    def compute_output_shape(self, input_shape):\n        return input_shape[0],  self.features_dim\ndf_train = pd.read_csv('..\/input\/metadata_train.csv')\ndf_train = df_train.set_index(['id_measurement', 'phase'])\ndf_train.head()\nmax_num = 127\nmin_num = -128\ndef min_max_transf(ts, min_data, max_data, range_needed=(-1,1)):\n    if min_data < 0:\n        ts_std = (ts + abs(min_data)) \/ (max_data + abs(min_data))\n    else:\n        ts_std = (ts - min_data) \/ (max_data - min_data)\n    if range_needed[0] < 0:    \n        return ts_std * (range_needed[1] + abs(range_needed[0])) + range_needed[0]\n    else:\n        return ts_std * (range_needed[1] - range_needed[0]) + range_needed[0]\ndef transform_ts(ts, n_dim=160, min_max=(-1,1)):\n    ts_std = min_max_transf(ts, min_data=min_num, max_data=max_num)\n    sample_size = 800000\n    bucket_size = int(sample_size \/ n_dim)\n    new_ts = []\n    for i in range(0, sample_size, bucket_size):\n        ts_range = ts_std[i:i + bucket_size]\n        mean = ts_range.mean()\n        std = ts_range.std()\n        std_top = mean + std\n        std_bot = mean - std\n        percentil_calc = np.percentile(ts_range, [0, 1, 25, 50, 75, 99, 100])\n        max_range = percentil_calc[-1] - percentil_calc[0]\n        covar = std \/ mean\n        asymmetry = mean - percentil_calc[4]\n        new_ts.append(np.concatenate([np.asarray([mean, std_top, std_bot, max_range, covar, asymmetry]),percentil_calc]))\n    return np.asarray(new_ts)\ndef prep_data(start, end):\n    #praq_train = pq.read_pandas('..\/input\/train.parquet').to_pandas()\n    praq_train = pq.read_pandas('..\/input\/train.parquet', columns=[str(i) for i in range(start, end)]).to_pandas()\n    X = []\n    y = []\n    #for id_measurement in tqdm(df_train.index.levels[0].unique()):\n    for id_measurement in df_train.index.levels[0].unique()[int(start\/3):int(end\/3)]:\n        X_signal = []\n        for phase in [0,1,2]:\n            signal_id, target = df_train.loc[id_measurement].loc[phase]\n            if phase == 0:\n                y.append(target)\n            X_signal.append(transform_ts(praq_train[str(signal_id)]))\n        X_signal = np.concatenate(X_signal, axis=1)\n        X.append(X_signal)\n    X = np.asarray(X)\n    y = np.asarray(y)\n    return X, y\nX = []\ny = []\ndef load_all():\n    total_size = len(df_train)\n    for ini, end in [(0, int(total_size\/2)), (int(total_size\/2), total_size)]:\n        X_temp, y_temp = prep_data(ini, end)\n        X.append(X_temp)\n        y.append(y_temp)\nload_all()\nX = np.concatenate(X)\ny = np.concatenate(y)\nprint(X.shape, y.shape)\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2)\ndef model_lstm(input_shape):\n    inp = Input(shape=(input_shape[1], input_shape[2],))\n    x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(inp)\n    x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)\n    x = Attention(input_shape[1])(x)\n    x = Dense(64, activation=\"relu\")(x)\n    x = Dense(1, activation=\"sigmoid\")(x)\n    model = Model(inputs=inp, outputs=x)\n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[matthews_correlation])\n    \n    return model\nmodel = model_lstm(X_train.shape)\nprint(model.metrics_names)\nmodel.summary()\nckp = ModelCheckpoint('weights.h5', save_best_only=True, save_weights_only=True, verbose=1, monitor='val_matthews_correlation', mode='max')\nmodel.fit(X_train, y_train, batch_size=100, epochs=100, validation_data=[X_valid, y_valid], callbacks=[ckp])\n%%time\n# 25ms in Kernel\nmeta_test = pd.read_csv('..\/input\/metadata_test.csv')\nmeta_test = meta_test.set_index(['signal_id'])\nmeta_test.head()\n%%time\n# About 10min in Kernel\nfirst_sig = meta_test.index[0]\nn_parts = 10\nmax_line = len(meta_test)\npart_size = int(max_line \/ n_parts)\nlast_part = max_line % n_parts\nprint(first_sig, n_parts, max_line, part_size, last_part, n_parts * part_size + last_part)\nstart_end = [[x, x+part_size] for x in range(first_sig, max_line + first_sig, part_size)]\nstart_end = start_end[:-1] + [[start_end[-1][0], start_end[-1][0] + last_part]]\nprint(start_end)\nX_test = []\nfor start, end in start_end:\n    subset_test = pq.read_pandas('..\/input\/test.parquet', columns=[str(i) for i in range(start, end)]).to_pandas()\n    for i in tqdm(subset_test.columns):\n        id_measurement, phase = meta_test.loc[int(i)]\n        subset_test_col = subset_test[i]\n        subset_trans = transform_ts(subset_test_col)\n        X_test.append([i, id_measurement, phase, subset_trans])\nX_test_input = np.asarray([np.concatenate([X_test[i][3],X_test[i+1][3], X_test[i+2][3]], axis=1) for i in range(0,len(X_test), 3)])\nX_test_input.shape\nsubmission = pd.read_csv('..\/input\/sample_submission.csv')\nprint(len(submission))\nsubmission.head()\nmodel.load_weights('weights.h5')\npred = model.predict(X_test_input, batch_size=300)\npred_3 = []\nfor pred_scalar in pred:\n    for i in range(3):\n        pred_3.append(int(pred_scalar > 0.4))\nsubmission['target'] = pred_3\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'e3f6eb0f2fd5c8'}"}
{"id":"110285","text":"\"\"\"\nA neural network written in Numpy validated as a XOR gate, Pandas 8x8 MNIST Binary Digit classifier and 28x28 MNIST 10 Class Digit classifier.\n\n\nResources Used\n\nhttp:\/\/page.mi.fu-berlin.de\/rojas\/neural\/chapter\/K7.pdf\n(backward step)\n\nhttps:\/\/gist.github.com\/tsbertalan\/3288114\n(learning rate, splitting delta & update steps, xor)\n\"\"\"\nimport numpy as np\nfrom math import tanh\n\"\"\"\n## Datasets for Supervised Learning\n\nA dataset for supervised learning consists of many rows of information, each paired with an expected output for the predictor.\n\nThe predictor, neural network in this case, will iterate over each row of information and generate its own predicted value for each one. This value will then be compared with the expected value(given by the dataset) and the network will update accordinly in attempt to minimize wrong predictions.\n\nIn order to see how well the predictor does in the end, a set of data will be needed to evaluate it. It is important that the test set data does not contain samples that the network has already seen as theese may bias the results. Normally a dataset is split into 2 parts, 80% of the data as a training set & 20% for the test set.\n\nWhen training a neural network on images, ie the MNIST Digits dataset, images are commonly flattened before being given to the predictor.\n\"\"\"\nfrom sklearn.datasets import load_iris\nimport pandas as pd\n\n# Load dataset to dataframe\ndata = load_iris()\nX = pd.DataFrame(data.data, columns=data.feature_names)\nX['expected_label'] = data.target\n\n# Shuffle rows\nX = X.reindex(np.random.permutation(X.index))\n\nX.head(10)\n\"\"\"\n## Activation Functions\n\nThe output of each neuron is passed through an activation function before being pushed to the next layer or output.\n\nThese make the output of each layers of neurons have nonlinear properties. \nWithout activation functions, there would be little(no?) value in adding more layers to the network. Each layer would be a linear transform, so a network without activation functions would just be a series of linear transforms, and a series of linear transforms could be represented by a single one.\n\"\"\"\n@np.vectorize\ndef sigmoid(x):\n    return tanh(x)\n\n@np.vectorize\ndef sigmoid_prime(x):\n    return 1.0 - x**2\n\n\nLEAK = 0\n@np.vectorize\ndef relu(x):\n    return x if x > 0 else (LEAK * x)\n\n@np.vectorize\ndef relu_prime(x):\n    return 1 if x > 0 else LEAK\n\n\nactivation_map = {\n    'sigmoid': {\"f\": sigmoid, \"f '\": sigmoid_prime},\n    'relu': {\"f\": relu, \"f '\": relu_prime},\n    }\n## Visualize Activation Functions\nimport matplotlib.pyplot as plt\n\nfor activation_type in activation_map:\n    X = np.arange(-4, 4, .1)\n    \n    for key, value in activation_map[activation_type].items():\n        Y = [value(v) for v in X]\n        \n        plt.plot(X, Y, label=key)\n\n    plt.title(activation_type)\n    plt.legend()\n    plt.show()\n\"\"\"\n## Cost Functions\nA cost function is the way to measure how far the output of the predictor is away from the desired value.\n\"\"\"\nclass MeanSquaredError:\n    \"\"\"\n    Mean squared error -- for regression problems.\n    \"\"\"\n    def __call__(seself, real, target):\n        return (1 \/ len(real)) * np.sum((target - real)**2)\n\n    def derivative(self, real, target):\n        return 2 \/ len(real) * (real - target)\n\n\nclass CrossEntropyLoss:\n    \"\"\"\n    Cross Entropy loss -- for categorical problems.\n    \"\"\"\n    def __call__(self, real, target):\n        return -real[np.where(target)] + np.log(np.sum(np.exp(real)))\n\n    def derivative(self, real, target):\n        return (1 \/ len(real)) * (real - target)\n\"\"\"\n## Neural Networks\n\nThe goal of a neural network is to approximate an arbitrary function. For example, we can use a neural network to approximate the function that 28x28 grayscale images of handwritten numbers to a number 0-9 -- the MNIST digit recognition task.\n\"\"\"\nclass NN:\n    def __init__(self, layers, layer_activations, loss_prime, learning_rate=.5):\n        self.layers = layers\n        self.layer_activations = layer_activations\n        self.learning_rate = learning_rate\n        self.loss_prime = loss_prime\n\n        assert len(self.layer_activations) == len(self.layers) - 1, \"Number activations incorrect.\"\n\n        self.w = []\n        for i, layer in enumerate(self.layers[:-1]):\n            # w[in, out]\n            matrix = np.random.uniform(-.1, .1, size=(layer, self.layers[i+1]))\n\n            self.w.append(matrix)\n\"\"\"\n## Feedforward Network\n\nMost networks trained w\/ gradient descent have a feedforward structure. This means the network is organized as a series of layers, with the output of every neuron in layer i being passed into every neuron in layer i+1.\n\nThe leftmost layer of neurons are inputs, with their activation set to whatever the input values are. The information from the initial layer is pushed through the corresponding synapses into the next layer, and so on to the next layer until the final layer has been updated. \n\nFor categorical tasks, the output layer is usually interpreted by measuring which output neuron has the highest activation, ie argmax(output_fires). If a neural network's task was to say whether an image had a 0 or a 1 (a cat or a dog, an iris or a rose, ...) in it, the output layer would have 2 neurons, whichever had the highest activation for a given input would correspond to the networks guess.\n\"\"\"\ndef forward(self, x):\n    \"\"\"\n    Network estimate y given x.\n    \"\"\"\n    fires = [np.copy(x)]\n\n    for i in range(len(self.layers) - 1):\n        x = np.matmul(fires[-1], self.w[i])\n\n        fires.append(activation_map[self.layer_activations[i]]['f'](x))\n\n    return fires[-1], fires\n\nNN.forward = forward\n\"\"\"\n# Learning\n\nThe learning in a neural network is done by updating the weights of the synapses in an intelligent manner in attempt to increase the accuracy of the network.\n\nFor this, I have implemented the stochastic gradient descent algorithm to update weights.\n\nGradient descent is moving along a curve in a way to find a trough based on the curves derivatives in every direction(via directional derivative). In this scenario, the goal is to move along the curve of the cost function - f(weight_1, weight_2, .... target) -> error in order to minimize the wrong predictions of the network. This curve has as many dimensions as there are weights in the network.\n\nStochastic GD is an approximation of gradient descent when not all gradient info is known. In this network, every prediction and corresponding prediction error is used to evaluate the gradient at a certain point -- with the same network, different input states may generate different guesses of the gradient. Mini batch stochastic gradient descent is a good way to alleviate this issue but is not implemented here.\n\nBackpropogation pushes the error of the output layer backwards through the network in order to update the weights of each layer based on what synapses are thought to have contributed most to the incorrect prediction.\n\"\"\"\ndef backward(self, real, target, fires):\n    \"\"\"\n    Update weights according to directional derivative to minimize error.\n    \"\"\"\n    ## Error for output layer\n    error = self.loss_prime(fires[-1], target)\n    \n    delta = activation_map[self.layer_activations[-1]][\"f '\"](fires[-1]) * error\n\n    deltas = [delta]\n\n    ## Backpropogate error\n    for i in range(len(self.layers) - 3, -1, -1):\n        error = np.sum(deltas[0] * self.w[i+1], axis=1)\n\n        delta = activation_map[self.layer_activations[i]][\"f '\"](fires[i+1]) * error\n\n        deltas.insert(0, delta)\n\n    for i in range(len(self.layers) - 2, -1, -1):\n        self.w[i] -= self.learning_rate * deltas[i] * fires[i].reshape((-1, 1))\n\nNN.backward = backward\n\"\"\"\n### Onehot Encoding\n\nAssign one expected value to each output of the neural network.\n\nie w\/ 3 classes\n\n0 -> [1 0 0]\n\n1 -> [0 1 0]\n\n2 -> [0 0 1]\n\"\"\"\ndef onehot(value, n_class):\n    output = np.zeros(n_class)\n\n    output[value] = 1.\n\n    return output\n\"\"\"\n### XOR Gate\n\"\"\"\n## Setup Dataset\n# ([in1, in2], expected)\ndata = [([0, 0], [0]), ([0, 1], [1]), ([1, 0], [1]), ([1, 1], [0])]\ndata = np.array(data)\n\n# shuffle and split info and labels\nidx = np.random.randint(0, 4, size=4000)\nX, y = data[idx, 0], data[idx, 1]\n\n## Setup NN\ncost = MeanSquaredError()\nnetwork = NN([2, 2, 1], ['sigmoid', 'sigmoid'], cost.derivative)\n\n## Train\nerror = 0\nfor i, expected in enumerate(y):\n    real, fires = network.forward(X[i])\n\n    network.backward(real, expected, fires)\n\n    error += (1 \/ 2) * (expected - real)**2\n\n    if i % 400 == 399:\n        print(error)\n        error = 0\n\n## Evaluate\nX, y = data[:, 0], data[:, 1]\nfor i, expected in enumerate(y):\n    real, fires = network.forward(X[i])\n    print(X[i], '->', real)\n\"\"\"\n### Binary Digit classification\n\"\"\"\n## Read Dataset\nN_CLASS = 2\nEPOCH = 10\n\nimport sklearn.datasets\nX, y = sklearn.datasets.load_digits(n_class=N_CLASS, return_X_y=True)\n\n## Setup\ncost = CrossEntropyLoss()\nnetwork = NN([64, N_CLASS], ['sigmoid'], cost.derivative, 10**-3)\n\n## Train\nerror = 0\nfor e in range(EPOCH):\n    # shuffle dataset between epoch\n    idx = [i for i in range(len(y))]\n    np.random.shuffle(idx)\n    X = X[idx]\n    y = y[idx]\n    \n    for i, expected in enumerate(y):\n        real, fires = network.forward(X[i])\n\n        target = onehot(expected, N_CLASS)\n        network.backward(real, target, fires)\n\n        error += cost(real, target)\n\n    if not e % 1:\n        print(error)\n        error = 0\n\n## Evaluate\nconfusion = {}\naccuracy = 0\nfor i, expected in enumerate(y):\n    real, fires = network.forward(X[i])\n\n    guess = np.argmax(real)\n    if expected not in confusion:\n        confusion[expected] = {}\n    if guess not in confusion[expected]:\n        confusion[expected][guess] = 0\n    confusion[expected][guess] += 1\n\n    accuracy += int(guess == expected)\n\nprint(f\"Accuracy: {accuracy \/ len(y)}\")\nprint(confusion)\n\"\"\"\n### Full MNIST\n\"\"\"\n## Read Dataset\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport pandas as pd\ndataset = pd.read_csv(\"..\/input\/digit-recognizer\/train.csv\")\ndataset.columns\nX, y = dataset[dataset.columns[1:]].values, dataset['label'].values\n## Split dataset into train and test set\nsplit_idx = int(y.size * .8)\n\ntrain_X, train_y = X[:split_idx], y[:split_idx]\ntest_X, test_y = X[split_idx:], y[split_idx:]\n## Setup NN\nN_CLASS = 10\nEPOCH = 10\n\ncost = CrossEntropyLoss()\n\nnetwork = NN([784, 32, N_CLASS], ['sigmoid', 'sigmoid'], cost.derivative, 10**-4)\n\n## Train\nerror = 0\nfor e in range(EPOCH):\n    # shuffle dataset between epoch\n    idx = [i for i in range(len(train_y))]\n    np.random.shuffle(idx)\n    train_X = train_X[idx]\n    train_y = train_y[idx]\n\n    for i, expected in enumerate(train_y):\n        real, fires = network.forward(train_X[i])\n\n        target = onehot(expected, N_CLASS)\n        network.backward(real, target, fires)\n\n        error += cost(real, target)\n\n    if not e % 1:\n        print(error)\n        error = 0\n\n        \n## Evaluate\nn_correct = 0\nfor i, expected in enumerate(test_y):\n    real, fires = network.forward(test_X[i])\n\n    n_correct += np.argmax(real) == expected\n\nprint(f\"Correct: {n_correct \/ test_y.size:.2f}\")","meta":"{'source': 'AI4Code', 'id': 'caacec8fc626c9'}"}
{"id":"37108","text":"\"\"\"\n## <font size='5' color='red'>Introduction<\/font>\n\"\"\"\n\"\"\"\nNatural language processing (NLP) has grown increasingly elaborate over the past few years. Machine learning models tackle question answering, text extraction, sentence generation, and many other complex tasks. But, can machines determine the relationships between sentences, or is that still left to humans? If NLP can be applied between sentences, this could have profound implications for fact-checking, identifying fake news, analyzing text, and much more. \n\n![](https:\/\/media.giphy.com\/media\/ZkwSxuckDvf7q\/giphy.gif)\n\n\n- In this notebook,I show how to do KFold Cross validation on TPU with XLM Roberta.I will further evaluate and tune the model in the upcoming updates.\n\n\"\"\"\n\"\"\"\n## <font size='4' color='blue'>Import Important packages<\/font>\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport seaborn as sns\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input,Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport transformers\nfrom transformers import TFAutoModel, AutoTokenizer\nfrom sklearn.model_selection import StratifiedKFold,KFold\nplt.style.use('fivethirtyeight')\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\npath=\"..\/input\/contradictory-my-dear-watson\"\nos.listdir(path)\n\n\"\"\"\n## <font size='4' color='blue'>Getting Basic Idea<\/font>\n\"\"\"\ndf_train=pd.read_csv(os.path.join(path,\"train.csv\"))\ndf_test=pd.read_csv(os.path.join(path,\"test.csv\"))\nprint('there are {} rows and {} columns in the train'.format(df_train.shape[0],df_train.shape[1]))\nprint('there are {} rows and {} columns in the test'.format(df_test.shape[0],df_test.shape[1]))\ndf_train.head(3)\n\"\"\"\n### <font size='3' color='blue'>Language distribution<font>\n\"\"\"\n\n\nlangs = df_train.language.unique()\n\nfig = go.Figure()\nfig.add_trace(go.Bar(\n    x=langs,\n    y=df_train.language.value_counts().values,\n    name='train',\n    marker_color='indianred'\n))\nfig.add_trace(go.Bar(\n    x=langs,\n    y=df_test.language.value_counts().values,\n    name='test',\n    marker_color='lightsalmon'\n))\n\n# Here we modify the tickangle of the xaxis, resulting in rotated labels.\nfig.update_layout(barmode='group', xaxis_tickangle=-45,title=\"language distribution in dataset\")\nfig.show()\n\"\"\"\n- The majoity of both the train and test set is in English.\n- All other language samples are under 100 per language.\n\"\"\"\n\"\"\"\n### <font size='3' color='blue'>Class distribution<\/font>\n\n\"\"\"\n\n\nlangs = df_train.label.unique()\n\nfig = go.Figure()\n\nfig.add_trace(go.Bar(\n    x=langs,\n    y=df_train.label.value_counts().values,\n    name='test',\n    marker_color=[ 'steelblue', 'tan', 'teal']\n))\n\n# Here we modify the tickangle of the xaxis, resulting in rotated labels.\nfig.update_layout(xaxis_tickangle=-45,title=\"Target distribution in train dataset\")\nfig.show()\n\"\"\"\n- The distribution of targets seems to be almost equal.\n\"\"\"\n\"\"\"\n## <font size='4' color='blue'>TPU Config<\/font>\n\"\"\"\n# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\nMODEL = 'jplu\/tf-xlm-roberta-large'\nEPOCHS = 10\nMAX_LEN = 96\n\n# Our batch size will depend on number of replic\nBATCH_SIZE= 16 * strategy.num_replicas_in_sync\nAUTO = tf.data.experimental.AUTOTUNE\ntokenizer = AutoTokenizer.from_pretrained(MODEL)\n\"\"\"\n## <font size='4' color='blue'>Fast Encoder<\/font>\n\"\"\"\ndef quick_encode(df,maxlen=100):\n    \n    values = df[['premise','hypothesis']].values.tolist()\n    tokens=tokenizer.batch_encode_plus(values,max_length=maxlen,pad_to_max_length=True)\n    \n    return np.array(tokens['input_ids'])\n\nx_train = quick_encode(df_train)\nx_test = quick_encode(df_test)\ny_train = df_train.label.values\n    \n\"\"\"\n## <font size='4' color='blue'>Dataset <\/font>\n\"\"\"\n\n\ndef create_dist_dataset(X, y,val,batch_size= BATCH_SIZE):\n    \n    \n    dataset = tf.data.Dataset.from_tensor_slices((X,y)).shuffle(len(X))\n          \n    if not val:\n        dataset = dataset.repeat().batch(batch_size).prefetch(AUTO)\n    else:\n        dataset = dataset.batch(batch_size).prefetch(AUTO)\n\n    \n    \n    return dataset\n\n\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_test))\n    .batch(BATCH_SIZE)\n)\n\n\"\"\"\n## <font size='4' color='blue'>Model<\/font>\n\"\"\"\ndef build_model(transformer,max_len):\n    \n    input_ids = Input(shape=(max_len,), dtype=tf.int32, name=\"input_ids\")\n    sequence_output = transformer(input_ids)[0]\n    cls_token = sequence_output[:, 0, :]\n    cls_token = Dropout(0.2)(cls_token)\n    cls_token = Dense(32,activation='relu')(cls_token)\n    out = Dense(3, activation='softmax')(cls_token)\n\n    # It's time to build and compile the model\n    model = Model(inputs=input_ids, outputs=out)\n    model.compile(\n        Adam(lr=1e-5), \n        loss='sparse_categorical_crossentropy', \n        metrics=['accuracy']\n    )\n    \n    return model\n\n\"\"\"\n## <font size='4' color='blue'>LR Scheduler<\/font>\nsource :https:\/\/www.kaggle.com\/miklgr500\/jigsaw-tpu-bert-with-huggingface-and-keras\n\"\"\"\ndef build_lrfn(lr_start=0.00001, lr_max=0.00003, \n               lr_min=0.000001, lr_rampup_epochs=3, \n               lr_sustain_epochs=0, lr_exp_decay=.6):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) \/ lr_rampup_epochs * epoch + lr_start\n        elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_exp_decay**(epoch - lr_rampup_epochs - lr_sustain_epochs) + lr_min\n        return lr\n    \n    return lrfn\n\nplt.figure(figsize=(10, 7))\n\n_lrfn = build_lrfn()\nplt.plot([i for i in range(10)], [_lrfn(i) for i in range(10)]);\nlrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\n\"\"\"\n## <font size='4' color='blue'>Kfold CV<\/font>\n\"\"\"\nskf = StratifiedKFold(n_splits=5,shuffle=True,random_state=777)\nval_score=[]\nhistory=[]\n\n\nfor fold,(train_ind,valid_ind) in enumerate(skf.split(x_train,y_train)):\n    \n    if fold < 4:\n    \n        print(\"fold\",fold+1)\n        \n       \n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        \n        train_data = create_dist_dataset(x_train[train_ind],y_train[train_ind],val=False)\n        valid_data = create_dist_dataset(x_train[valid_ind],y_train[valid_ind],val=True)\n    \n        Checkpoint=tf.keras.callbacks.ModelCheckpoint(f\"roberta_base.h5\", monitor='val_loss', verbose=0, save_best_only=True,\n        save_weights_only=True, mode='min')\n        \n        with strategy.scope():\n            transformer_layer = TFAutoModel.from_pretrained(MODEL)\n            model = build_model(transformer_layer, max_len=MAX_LEN)\n            \n        \n\n        n_steps = len(train_ind)\/\/BATCH_SIZE\n        print(\"training model {} \".format(fold+1))\n\n        train_history = model.fit(\n        train_data,\n        steps_per_epoch=n_steps,\n        validation_data=valid_data,\n        epochs=EPOCHS,callbacks=[Checkpoint],verbose=1)\n        \n        print(\"Loading model...\")\n        model.load_weights(f\"roberta_base.h5\")\n        \n        \n\n        print(\"fold {} validation accuracy {}\".format(fold+1,np.mean(train_history.history['val_accuracy'])))\n        print(\"fold {} validation loss {}\".format(fold+1,np.mean(train_history.history['val_loss'])))\n        \n        val_score.append(train_history.history['val_accuracy'])\n        history.append(train_history)\n\n        val_score.append(np.mean(train_history.history['val_accuracy']))\n        \n        print('predict on test....')\n        preds=model.predict(test_dataset,verbose=1)\n        \n        pred_test+=preds\/4\n        \n\n        \nprint(\"Mean Validation accuracy : \",np.mean(val_score))\n\"\"\"\n## <font size='4' color='blue'>Evaluation<\/font>\n\"\"\"\n\nplt.figure(figsize=(15,10))\n\nfor i,hist in enumerate(history):\n\n    plt.subplot(2,2,i+1)\n    plt.plot(np.arange(EPOCHS),hist.history['accuracy'],label='train accu')\n    plt.plot(np.arange(EPOCHS),hist.history['val_accuracy'],label='validation acc')\n    plt.gca().title.set_text(f'Fold {i+1} accuracy curve')\n    plt.legend()\n\n\n    \n\nplt.figure(figsize=(15,10))\n\nfor i,hist in enumerate(history):\n\n    plt.subplot(2,2,i+1)\n    plt.plot(np.arange(EPOCHS),hist.history['loss'],label='train loss')\n    plt.plot(np.arange(EPOCHS),hist.history['val_loss'],label='validation loss')\n    plt.gca().title.set_text(f'Fold {i+1} loss curve')\n    plt.legend()\n\n\n\"\"\"\n## <font size='4' color='blue'>Submission<\/font>\n\"\"\"\nsubmission = pd.read_csv(os.path.join(path,'sample_submission.csv'))\nsubmission['prediction'] = np.argmax(pred_test,axis=1)\nsubmission.head()\nsubmission.to_csv('submission.csv',index=False)\n\"\"\"\n## <font size='4' color='red'>Work in Progress! Please upvote if you think this was helpful.<\/font>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4449ed268837d0'}"}
{"id":"58565","text":"# 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\ndf_train = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ndf_test = pd.read_csv(\"..\/input\/titanic\/test.csv\")\ndf_train.head()\ndf_train.shape\n\ndf_test.shape\ndf_test.head()\ndf_train.info()\ntrain_df = df_train[[\"PassengerId\",\"Survived\",\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Ticket\",\"Fare\",\"Cabin\",\"Embarked\"]]\ntest_df = df_test[[\"PassengerId\",\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Ticket\",\"Fare\",\"Cabin\",\"Embarked\"]]\ntrain_df.isnull().sum()\ntrain_df.drop(\"Cabin\", inplace = True, axis = 1)\ntest_df.drop(\"Cabin\", inplace = True, axis = 1)\ntrain_df\ntrain_df.drop(\"Ticket\", inplace = True, axis = 1)\ntest_df.drop(\"Ticket\", inplace = True, axis = 1)\ntrain_df\ntrain_df.groupby(\"Embarked\").size()\ndef function(x):\n    if (x[\"Embarked\"] == \"C\"):\n        return int(1)\n    elif(x[\"Embarked\"] == \"Q\"):\n        return int(2)\n    elif(x[\"Embarked\"] == \"S\"):\n        return int(3)\ntrain_df1 = train_df.apply(function, axis = 1)\ntest_df1 = test_df.apply(function,axis = 1)\ntrain_df[\"Embarked\"] = train_df1\ntest_df[\"Embarked\"] = test_df1\ntrain_df.head()\ntrain_df[\"Age\"] = train_df[\"Age\"].fillna(train_df[\"Age\"].mean())\ntest_df[\"Age\"] = test_df[\"Age\"].fillna(test_df[\"Age\"].mean())\ntrain_df[\"Age\"] = train_df[\"Age\"].astype(int)\ntrain_df.shape\ntest_df.head()\ntest_df.shape\ntest_df.isnull().sum()\ntrain_df[\"Embarked\"] = train_df[\"Embarked\"].fillna(train_df[\"Embarked\"].mean())\ntest_df[\"Fare\"] = test_df[\"Fare\"].fillna(test_df[\"Fare\"].mean())\ntrain_df.info()\ntest_df.info()\ntrain_df.describe()\ndef function(x):\n    if (x[\"Sex\"] == \"male\"):\n        return int(0)\n    elif(x[\"Sex\"] == \"female\"):\n        return int(1)\n   \ntrain_df2 = train_df.apply(function, axis = 1)\ntest_df2 = test_df.apply(function,axis = 1)\ntrain_df[\"Sex\"] = train_df2\ntest_df[\"Sex\"] = test_df2\ntrain_df.head()\ntest_df.head()\nx = train_df[[\"PassengerId\",\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Fare\",\"Embarked\"]]\ny = train_df[\"Survived\"]\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.20, random_state = 0)\nx_train.info()\ndef get_mae(max_leaf_nodes, x_train, x_test, y_train, y_test):\n    model = DecisionTreeRegressor(max_leaf_nodes= max_leaf_nodes , random_state=0)\n    model.fit(x_train, y_train,)\n    preds_val = model.predict(x_test)\n    mae = mean_absolute_error(y_test, preds_val)\n    r_square = (round(r2_score(y_test,preds_val)*100, 2))\n    return mae, r_square\n\nfor max_leaf_nodes in [5, 50, 500, 5000]:\n    my_mae, r_square = get_mae(max_leaf_nodes, x_train, x_test, y_train, y_test)\n    print(\"Max leaf nodes: %d  \\t\\t Mean Absolute Error:  %d \\t\\t R-squared:  %d\" %(max_leaf_nodes, my_mae, r_square))\nmodel = DecisionTreeRegressor(max_leaf_nodes= 5 , random_state=0)\nmodel.fit(x_train, y_train,)\npreds_val = model.predict(x_test)\nmae = mean_absolute_error(y_test, preds_val)\nprint(\"mae = \",mae, \"accuracy score = \" , model.score(x_test,y_test)*100)\nlinear = LinearRegression()\nlinear.fit(x_train,y_train)\npredict = linear.predict(x_test)\nmae = mean_absolute_error(y_test, predict)\nr_squared = (round(r2_score(y_test, predict)*100, 2))\nprint(\"mean squared error: \", mae, \"r_square: \", r_squared )\nprint(\"accuracy score = \", linear.score(x_test, y_test)*100)\nlogistic = LogisticRegression(max_iter = 10000)\nlogistic.fit(x_train,y_train)\npredicted = logistic.predict(x_test)\nmae = mean_absolute_error(y_test, predicted)\nr_squared = (round(r2_score(y_test, predicted)*100, 2))\nprint(\"mean squared error: \", mae, \"r_square: \", r_squared )\nprint(\"accuracy score = \", logistic.score(x_test, y_test)*100)\nforest_model = RandomForestRegressor(random_state=16)\nforest_model.fit(x_train, y_train)\npreds = forest_model.predict(x_test)\nmae = mean_absolute_error(y_test, preds)\nr_squared = (round(r2_score(y_test, preds)*100, 2))\nprint(\"mean squared error: \", mae, \"r_square: \", r_squared )\nprint(\"accuracy score = \", forest_model.score(x_test, y_test)*100)\n\nmodel2= GaussianNB(var_smoothing=1e-08)\nmodel2.fit(x_train, y_train)\nY_pred= model2.predict(x_test)\nmodel2.score(x_test, y_test)\n\"\"\"\nTraining the Model (Since logistic regression has the highest accuracy. thus we are going to fit logistic regression model)\n\"\"\"\nlogistic_model = LogisticRegression(max_iter = 10000)\nlogistic_model.fit(x,y)\npredicted_values = logistic_model.predict(test_df)\nfinal_data = {'PassengerId': test_df.PassengerId, 'Survived': predicted_values}\nfinal_submission = pd.DataFrame(data=final_data)\nfinal_submission.to_csv('submission_file.csv',index =False)\n","meta":"{'source': 'AI4Code', 'id': '6c2a0b47ae1144'}"}
{"id":"17758","text":"\"\"\"\n# Full Pipeline for classic & modern ML (sklearn API), SHAP-based variables interaction with GPU acceleration.\n\"\"\"\n\"\"\"\nSources:\n\nhttps:\/\/www.kaggle.com\/rumasinha\/featureselectionanddiffmodelexperiments\nhttps:\/\/www.kaggle.com\/tunguz\/tps-02-21-feature-importance-with-xgboost-and-shap\nhttps:\/\/www.kaggle.com\/hamzaghanmi\/make-it-simple\n\"\"\"\n\"\"\"\nContents:\n\n    - Simple basic EDA\n    \n    - Feature preprocessing\n    \n    - Classic ML baselines\n    \n    - Modern ML baselines\n    \n    - Best Baseline model\n    \n    - Add new features using XGBoost and SHAP\n    \n    - Baseline model with added features\n    \n    - Hyperparameters tuning (Optuna)\n    \n    - Cross-validation with optimized params\n    \n    - Submission prepare\n\"\"\"\n!pip install xgboost==1.5.0\n!pip install shap\n!pip install optuna\n!pip install seaborn\n!pip install pandas_profiling==3.1.0\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\nimport numpy as np \nimport pandas as pd \n\nfrom pandas_profiling import ProfileReport\n\nfrom lightgbm import LGBMClassifier, LGBMRegressor\nfrom xgboost import XGBClassifier, XGBRegressor\nimport xgboost as xgb\n\nfrom sklearn.linear_model import LogisticRegression, LinearRegression, Ridge, \\\n                                SGDClassifier, RidgeClassifier, PassiveAggressiveClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error, classification_report, f1_score, roc_auc_score, accuracy_score\nfrom sklearn.model_selection import train_test_split, KFold, StratifiedKFold\nfrom sklearn.preprocessing import LabelEncoder, RobustScaler, PowerTransformer\nfrom sklearn.utils import shuffle\nfrom sklearn import metrics\n\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nimport optuna\nfrom optuna.samplers import TPESampler\n\nfrom tqdm.notebook import tqdm\nimport gc\nimport shap\nimport pickle\n\n%matplotlib inline\n\n#plt.rcParams['figure.dpi'] = 100\n#plt.rcParams.update({'font.size': 16})\n\n# load JS visualization code to notebook\nshap.initjs()\npath_with_data = '\/kaggle\/input\/tabular-playground-series-nov-2021\/'\npath_to_data = '\/kaggle\/working\/'\nDEBUG = False\nTRAIN_MODEL = True\nINFER_TEST = True\nONE_FOLD_ONLY = False\nCOMPUTE_IMPORTANCE = True\nOOF = True\ntrain, test, sub = pd.read_csv(path_with_data + \"train.csv\", index_col=\"id\"), \\\n    pd.read_csv(path_with_data + \"test.csv\", index_col=\"id\"), \\\n    pd.read_csv(path_with_data + \"sample_submission.csv\")\n\nif DEBUG:\n    train = train[:50000]\n    test = test[:50000]\n\nprint(f'Train shape: {train.shape}')\nprint(f'Test shape: {test.shape}')\n\ntarget = 'target'\ntrain.head(5)\n\"\"\"\n### Memory reducing\n\"\"\"\ndef reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) \/ start_mem))\n    \n    return df\ntrain = reduce_mem_usage(train)\ntest = reduce_mem_usage(test)\n\"\"\"\n### Simple EDA\n\"\"\"\n\"\"\"\n#### Pandas profiler\n\"\"\"\nprofile = ProfileReport(train, title=\"Pandas Profiling Report\", explorative=False, minimal=True, dark_mode=True)\nprofile\n\"\"\"\n#### Seaborn plots\n\"\"\"\n#sns.relplot(data=train, x=train['f0'], y=train['f1'], kind='scatter', hue='target')\n#sns.displot(data=train, x='f1', kind='hist', hue='target')\n#sns.displot(data=train, x='f1', kind='kde', hue='target', fill=True)\n#sns.jointplot(data=train, x=train['f0'], y=train['f1'], kind='scatter', hue='target')\n#sns.pairplot(data=train[['f0', 'f1', 'f2', 'f3']], hue='target')  # very slow\n\"\"\"\n#### Correlation heatmap\n\"\"\"\npredictors_amount = 20 + 1  # should div by 4  + 1\n\ncolormap = plt.cm.RdBu\nplt.figure(figsize=(14,12))\nplt.title('Spearman Correlation of Features', y=1.05, size=15)\ncorrmat = train.corr(method='spearman').abs()\ncols = corrmat.nlargest(predictors_amount, target)[target].index\ncm = abs(np.corrcoef(train[cols].values.T))\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)\nmost_correlated = list(set(cols) - set([target]))\n# plot the first most correlated features \n\ni = 1\ncols_amount = 4\nrows_amount = int(len(most_correlated) \/ cols_amount) \nplt.figure()\nfig, ax = plt.subplots(rows_amount, cols_amount, figsize=(20, 22))\nfor feature in most_correlated:\n    plt.subplot(rows_amount, cols_amount, i)\n    sns.histplot(train[feature],color=\"blue\", kde=True, bins=100, label='train_'+feature)\n    sns.histplot(test[feature],color=\"olive\", kde=True, bins=100, label='test_'+feature)\n    plt.xlabel(feature, fontsize=9); plt.legend()\n    i += 1\nplt.show()\nsns.boxplot(data=train[most_correlated])\n\"\"\"\n### Feature preprocessing\n\"\"\"\ncolumns = train.columns\npreproc = dict()\npreproc['target'] = target\nto_drop = [target]\n\"\"\"\n#### Select features\n\"\"\"\nfeatures = [col for col in train.columns if col not in to_drop ]\npreproc['features'] = features\n\"\"\"\n#### Collinear (highly correlated) features\n\"\"\"\n# Threshold for removing correlated variables\nthreshold = 0.90\n# Absolute value correlation matrix\ncorr_matrix = train[features].corr(method='spearman').abs()\n# Upper triangle of correlations\nupper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))\n# Select columns with correlations above threshold\nhighly_correlated = [column for column in upper.columns if any(upper[column] > threshold)]\nfeatures = [col for col in features if col not in highly_correlated]\npreproc['features'] = features\n\"\"\"\n#### Zero standard deviation\n\"\"\"\nthreshold = 0\nzero_std = train[features].std().index[train[features].std() <= threshold]\nfeatures = [col for col in features if col not in zero_std]    \npreproc['features'] = features\n\"\"\"\n#### Zero coefficient of variantion\n\"\"\"\nthreshold = 1  # in %\nzero_cv = (100 * train[features].std() \/ train[features].mean()).index[(100 * train[features].std() \/ train[features].mean()) <= threshold]\nfeatures = [col for col in features if col not in zero_cv]\npreproc['features'] = features\n\"\"\"\n#### Scaler transform\n\"\"\"\nscaler = RobustScaler()\nscaler.fit(train[features])\ntrain[features] = scaler.transform(train[features])\ntest[features] = scaler.transform(test[features])\npreproc['scaler'] = scaler\n\"\"\"\n#### Power transform\n\"\"\"\nif 0:\n  pt = PowerTransformer()\n  pt.fit(train[features])\n  train[features] = pt.transform(train[features])\n  test[features] = pt.transform(test[features])\n  preproc['power_transformer'] = pt\n\"\"\"\n#### Distribution Plots with changes\n\"\"\"\n# plot the first most correlated features \n\ni = 1\ncols_amount = 4\nrows_amount = int(len(most_correlated) \/ cols_amount) \nplt.figure()\nfig, ax = plt.subplots(rows_amount, cols_amount, figsize=(20, 22))\nfor feature in most_correlated:\n    plt.subplot(rows_amount, cols_amount, i)\n    sns.histplot(train[feature],color=\"blue\", kde=True, bins=100, label='train_'+feature)\n    sns.histplot(test[feature],color=\"olive\", kde=True, bins=100, label='test_'+feature)\n    plt.xlabel(feature, fontsize=9); plt.legend()\n    i += 1\nplt.show()\n\"\"\"\n## Classic ML baselines\n\"\"\"\n\"\"\"\n#### Data split\n\"\"\"\nfeatures = preproc['features']\nX_train, X_test, y_train, y_test = train_test_split(train[features], \n                                                    train[target],\n                                                    stratify=train[target], \n                                                    test_size=0.25, \n                                                    random_state=42)\nclfs = {\n        'Logistic Regression': LogisticRegression(random_state=0), \n        'Naive Bayes': GaussianNB(),\n        #'SVM': SVC(gamma='auto'),\n        #'Random Forest': RandomForestClassifier(random_state=0),\n        'SGD Classifier': SGDClassifier(random_state=0),\n        'Ridge': RidgeClassifier(random_state=0),\n        'Passive Aggressive Classifier': PassiveAggressiveClassifier(random_state=0),\n        #'KNN': KNeighborsClassifier(),\n        #'MLP': MLPClassifier(),\n        'Decision Tree': DecisionTreeClassifier()\n       }\nfor clf_name in clfs:   \n    clf = clfs[clf_name].fit(X_train, y_train)\n    y_pred = clf.predict(X_test)   \n    print(f'{clf_name}: F1 = {f1_score(y_test, y_pred)}, AUC = {roc_auc_score(y_test, y_pred)}, Accuracy = {accuracy_score(y_test, y_pred)}')\n    \n\"\"\"\n## Modern ML baselines\n\"\"\"\nclfs = {\n        'XGBoost': XGBClassifier(tree_method='gpu_hist', predictor='gpu_predictor'),\n        'LGB': LGBMClassifier()\n       }\nfor clf_name in clfs:   \n    clf = clfs[clf_name].fit(X_train, y_train)\n    y_pred = clf.predict(X_test)\n    print(f'{clf_name}: F1 = {f1_score(y_test, y_pred)}, AUC = {roc_auc_score(y_test, y_pred)}, Accuracy = {accuracy_score(y_test, y_pred)}')\n\"\"\"\n## Best Baseline model\n\"\"\"\nbaseline_model = LogisticRegression(random_state=0)\nbaseline_model.fit(X_train, y_train)\npreds = baseline_model.predict(test[features])\ny_pred = baseline_model.predict(X_test) \nprint(f'LR: F1 = {f1_score(y_test, y_pred)}, AUC = {roc_auc_score(y_test, y_pred)}, Accuracy = {accuracy_score(y_test, y_pred)}')\nsub['target'] = preds\nsub.to_csv(path_to_data + 'submission_bl.csv', index=False)\n\"\"\"\n#### intermediate conclusion\nBaseline Logistic regression model gives us 0.734 on LB, which is within 95% of max LB result (0.75091)\n\"\"\"\n\"\"\"\n## Add new features using XGBoost and SHAP\n\"\"\"\ntrain_oof = np.zeros((train.shape[0],))\ntest_preds = 0\ntrain_oof.shape\nxgb_params= {\n        \"objective\": \"binary:logistic\",\n        \"eval_metric\": \"error\",  \n        \"seed\": 2001,\n        'tree_method': \"gpu_hist\",\n        'predictor': 'gpu_predictor'\n    }\ntest_xgb = xgb.DMatrix(test[features])\nNUM_FOLDS = 5\nkf = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=0)\n\nfor f, (train_ind, val_ind) in tqdm(enumerate(kf.split(train[features], train[target]))):\n        #print(f'Fold {f}')\n        train_df, val_df = train[features].iloc[train_ind], train[features].iloc[val_ind]\n        train_target, val_target = train[target].iloc[train_ind], train[target].iloc[val_ind]\n                      \n        train_df = xgb.DMatrix(train_df, label=train_target)\n        val_df = xgb.DMatrix(val_df, label=val_target)\n        \n        model =  xgb.train(xgb_params, train_df, 100)\n        temp_oof = model.predict(val_df)\n        temp_test = model.predict(test_xgb)\n\n        train_oof[val_ind] = temp_oof\n        test_preds += temp_test\/NUM_FOLDS\n        \n        print(accuracy_score(np.round(temp_oof), val_target))\n%%time\nshap_preds = model.predict(test_xgb, pred_contribs=True)\n# summarize the effects of all the features\nshap.summary_plot(shap_preds[:,:-1], test[features])\nshap.summary_plot(shap_preds[:,:-1], test[features], plot_type=\"bar\")\n%%time\nshap_interactions = model.predict(xgb.DMatrix(test[features][:50000]), pred_interactions=True)\ndef plot_top_k_interactions(feature_names, shap_interactions, k):\n    # Get the mean absolute contribution for each feature interaction\n    aggregate_interactions = np.mean(np.abs(shap_interactions[:, :-1, :-1]), axis=0)\n    interactions = []\n    for i in range(aggregate_interactions.shape[0]):\n        for j in range(aggregate_interactions.shape[1]):\n            if j < i:\n                interactions.append(\n                    (feature_names[i] + \"*\" + feature_names[j], aggregate_interactions[i][j] * 2))\n    # sort by magnitude\n    interactions.sort(key=lambda x: x[1], reverse=True)\n    interaction_features, interaction_values = map(tuple, zip(*interactions))\n    plt.bar(interaction_features[:k], interaction_values[:k])\n    plt.xticks(rotation=90)\n    plt.tight_layout()\n    plt.show()\n    return interaction_features\n\ninteractions_to_add = 10    \ninteraction_features = plot_top_k_interactions(features, shap_interactions, interactions_to_add)\ndef add_new_features(df, interaction_features, amount_of_features):\n    features_list = interaction_features[:amount_of_features]\n    for feat in features_list: \n      first_name, second_name = feat.split('*')\n      df[feat] = df[first_name]*df[second_name]\n    return df, features_list\ntrain, features_added = add_new_features(train, interaction_features, interactions_to_add)\ntest, _ = add_new_features(test, interaction_features, interactions_to_add)\nfeatures += list(features_added)\n\ndel test_xgb\ndel shap_interactions\ngc.collect()\nfeatures_added\n\"\"\"\n#### Scaler transform\n\"\"\"\nscaler = RobustScaler()\nscaler.fit(train[features])\ntrain[features] = scaler.transform(train[features])\ntest[features] = scaler.transform(test[features])\npreproc['scaler'] = scaler\n\"\"\"\n## Baseline model with added features\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(train[features], \n                                                    train[target],\n                                                    stratify=train[target], \n                                                    test_size=0.25, \n                                                    random_state=42)\nbaseline_model_af = LogisticRegression(random_state=0)\nbaseline_model_af.fit(X_train, y_train)\npreds = baseline_model_af.predict(test[features])\ny_pred = baseline_model_af.predict(X_test) \nprint(f'LR: F1 = {f1_score(y_test, y_pred)}, AUC = {roc_auc_score(y_test, y_pred)}, Accuracy = {accuracy_score(y_test, y_pred)}')\nsub['target'] = preds\nsub.to_csv(path_to_data + 'submission_blaf.csv', index=False)\n\"\"\"\n## Hyperparameters tuning (Optuna)\n\"\"\"\n# HPO using opuna\n\ndef lr_objective(trial):\n    params = {\n        'C': trial.suggest_loguniform('C', 1e-8, 1000.0),        \n        'solver': trial.suggest_categorical('solver', ['lbfgs', 'liblinear']), \n        'random_state': 42,\n        'penalty' : 'l2',         \n    }\n    \n    X_train, X_val, y_train, y_val = train_test_split(train[features], train[target], test_size = 0.25, random_state = 42)\n    \n    model = LogisticRegression(**params)    \n    model.fit(X_train, y_train)\n    pred_val = model.predict(X_val)\n    \n    return roc_auc_score(y_val, pred_val)\nsampler = TPESampler(seed = 42)\nstudy = optuna.create_study(study_name = 'LR optimization',\n                            direction = 'maximize',\n                            sampler = sampler)\nstudy.optimize(lr_objective, n_trials = 10)\n\nprint(\"Best AUC:\", study.best_value)\nprint(\"Best params:\", study.best_params)\nif 1:\n    params = study.best_params\nelse:\n    params = {'C': 0.00045858194103088424, 'solver': 'liblinear'}\n\"\"\"\n## Cross-validation with optimized params\n\"\"\"\n#EPOCH = 250\n#BATCH_SIZE = 512\nNUM_FOLDS = 5\nCOLS = features.copy()\n\nkf = StratifiedKFold(n_splits=NUM_FOLDS, shuffle=True, random_state=42)\ntest_preds = []\noof_preds = []\nfor fold, (train_idx, test_idx) in enumerate(kf.split(train[features], train[target])):\n        \n        print('-'*15, '>', f'Fold {fold+1}', '<', '-'*15)\n        X_train, X_valid = train[features].iloc[train_idx], train[features].iloc[test_idx]\n        y_train, y_valid = train[target].iloc[train_idx], train[target].iloc[test_idx]\n        \n        filename = f\"folds{fold}.pkl\"\n        \n        if TRAIN_MODEL:\n            #model = LogisticRegression(C = params['C'], solver = params['solver'])\n            model = LogisticRegression(**params)\n            model.fit(X_train, y_train)\n            pickle.dump(model, open(path_to_data + filename, 'wb'))                                    \n            \n        else:                  \n            model = pickle.load(open(path_to_data + filename, 'rb'))                  \n    \n        if OOF:\n            print(' Predicting OOF data...')                \n            oof = model.predict(X_valid)\n            baseline_accuracy = accuracy_score(y_valid, oof)            \n            oof_preds.append(baseline_accuracy)\n            print('OOF Accuracy = {0}'.format(baseline_accuracy))\n            print(' Done!')\n                       \n        if INFER_TEST:\n            print(' Predicting test data...')\n            preds = model.predict(test[features])\n            test_preds.append(np.array(preds))\n            print(' Done!')\n                    \n        if COMPUTE_IMPORTANCE:\n            # from  https:\/\/www.kaggle.com\/cdeotte\/lstm-feature-importance\n            results = []\n            print(' Computing feature importance...')\n            \n            # COMPUTE BASELINE (NO SHUFFLE)\n            oof = model.predict(X_valid)\n            baseline_accuracy = accuracy_score(y_valid, oof)\n            results.append({'feature':'BASELINE','accuracy':baseline_accuracy})\n                                    \n            for k in tqdm(range(len(COLS))):\n                \n                # SHUFFLE FEATURE K\n                save_col = X_valid.copy()\n                np.random.shuffle(X_valid[COLS[k]].values)\n                                \n                # COMPUTE OOF Accuracy WITH FEATURE K SHUFFLED\n                oof = model.predict(X_valid)\n                acc = accuracy_score(y_valid, oof)\n                results.append({'feature':COLS[k],'accuracy':acc})                               \n                \n                X_valid = save_col.copy()\n         \n            # DISPLAY FEATURE IMPORTANCE\n            print()\n            df = pd.DataFrame(results)\n            df = df.sort_values('accuracy')\n            plt.figure(figsize=(10,20))\n            plt.barh(np.arange(len(COLS)+1),df.accuracy)\n            plt.yticks(np.arange(len(COLS)+1),df.feature.values)\n            plt.title('Feature Importance',size=16)\n            plt.ylim((-1,len(COLS)+1))\n            plt.plot([baseline_accuracy,baseline_accuracy],[-1,len(COLS)+1], '--', color='orange',\n                     label=f'Baseline OOF\\naccuracy={baseline_accuracy:.3f}')\n            plt.xlabel(f'Fold {fold+1} OOF accuracy with feature permuted',size=14)\n            plt.ylabel('Feature',size=14)\n            plt.legend()\n            plt.show()\n                               \n            # SAVE LSTM FEATURE IMPORTANCE\n            df = df.sort_values('accuracy',ascending=False)\n            df.to_csv(f'feature_importance_fold_{fold+1}.csv',index=False)\n                               \n        # ONLY DO ONE FOLD\n        if ONE_FOLD_ONLY: break\n\"\"\"\n### Plot of roc curve for the last fold\n\"\"\"\ny_pred_proba = model.predict_proba(X_valid)[:, 1]\nfpr, tpr, _ = metrics.roc_curve(y_valid,  y_pred_proba)\nauc = metrics.roc_auc_score(y_valid, y_pred_proba)\nplt.plot(fpr,tpr,label=\"data, auc for last fold = \" + str(round(auc*100,2)))\nplt.legend(loc=4)\nplt.show()\n\"\"\"\n### Submission prepare\n\"\"\"\nsub['target'] = sum(test_preds) \/ NUM_FOLDS\nsub.to_csv(path_to_data + 'submission.csv', index=False)\n\"\"\"\nFinal conclusion: the best baseline mode is the best without feature engineering :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '206fefb79f09b0'}"}
{"id":"20754","text":"\"\"\"\nHellooooo, I \u2764\ufe0f VBO\n- I will explain my Association Rule Learning Recommender project in my weekly assignments in order to turn it into a contribution for you.\n\"\"\"\n\"\"\"\n![image.png](attachment:ee702f43-6a1e-4730-83b6-7240540e9c45.png)\n\"\"\"\n\"\"\"\n# **Association Rule Learning Recommender**\n\"\"\"\n\"\"\"\n# Association Rules\n\nAssociation rule mining is a methodology that is used to discover unknown relationships hidden in big data. Rules refer to a set of identified frequent itemsets that represent the uncovered relationships in the dataset. The underlying idea is to identify rules that will predict the occurence of one or more items based on the occurrences of other items in the dataset. It is an unsupervised machine learning method. This means that no direct guiding output data is given to find the patterns.\n\nIn many commercial environments large quantities of data is accumulated in databases from day-to-day operations. This lays the foundation for mining association rules. In retail, for example, customer purchase data are collected on a daily basis at the checkout counters of city stores or when shopping at online stores. The accumulated data items are often market basket transactions. Managers of stores are interested in analyzing the collected data in order to learn the purchasing behaviour of customers. This enables a large variety of business-related applications (see below) based on the identified rules in the data.\n\nBelow is one of the famous examples illustrating a rule based on a strong relationship between the sale of Diapers and the sale of Beer. In other words many customers who buy Diapers also buy Beer. Investigating the transactions below in order to find those frequent itemsets seems to be easy. But consider in real datasets millions or billions of transactions are searched across 100000 of different items that may identify 1000 of rules. This motivates the automation of the process using association rule mining algorithms. In retail these rules help to identify new opportunities and ways for cross-selling products to customers.\n\n![image.png](attachment:6ae1bfdc-4419-45d2-a498-b209ec260aef.png)\n\n\nThe example above illustrated the core idea of association rule mining based on frequent itemsets. It is a simple example since it essentially ignores other relevant attributes such as quantity of items sold, the Price, or even a specific brand of items. The mining process to discover unknown patterns in large transaction datasets is computationally expensive. A particular challenge is also the size of the millions or billions of the transaction dataset when performing mining within memory. In other words smart out-of-cpu strategies are needed to work on the big datasets as a whole in order to identify frequent itemsets. This is the case since sub-sampling of dataset items may increase the risk to overlook frequent itemset patterns.\n\nAnother challenge when performing association rule mining is that some uncovered patterns are simply not true since they have happen by chance. The latter therefore needs often manual post-processing or even application domain knowledge in order to find true rules out of the undiscovered patterns. Important is to find actionable insights from rules that can be used to change a product portfolio, store setup, or customer relations. Several configuration options are available for association rules (e.g. support, confidence) in order to provide a more clear set of rules.\n\"\"\"\n\"\"\"\n# Association Rules Applications\n\nUnderstanding the customer purchasing behaviour by using association rule mining enables different applications. As shown above rules help to identify new opportunities and ways for cross-selling products to customers. It is used for personalised marketing promotions, smarter inventory management, product placement strategies in stores, and a better customer relationship management.\n\"\"\"\n\"\"\"\n# Business Problem:\n\nSuggesting products to users at the basket stage.\n\"\"\"\n\"\"\"\n# Dataset Story\n\n* The dataset named Online Retail II shows the sales of a UK-based online store between 01\/12\/2009 - 09\/12\/2011.\ncontains.\n\n* The product catalog of this company includes souvenirs. promotion\ncan be considered as products.\n\n* There is also information that most of its customers are wholesalers.\n\"\"\"\n\"\"\"\n# Variables\n\n* InvoiceNo \u2013 Invoice Number\n\n> If this code starts with C, it means that the operation has been cancelled.\n\n* StockCode \u2013 Product code\n\n> Unique number for each product.\n\n* Description \u2013 Product name\n\n* Quantity \u2013 Number of products\n\n> It expresses how many of the products on the invoices have been sold.\n\n* InvoiceDate \u2013 Invoice date\n\n* UnitPrice \u2013 Invoice price (Sterling)\n\n* CustomerID \u2013 Unique customer number\n\n* Country \u2013 Country name\n\"\"\"\n\"\"\"\n# Project Steps\n\"\"\"\n\"\"\"\n# TASK 1: \n\nPerform Data Preprocessing\n\n**Important note!**\n*Select the 2010-2011 data and preprocess all the data.\nThe choice of Germany will be in the next step.*\n\"\"\"\nimport pandas as pd\npd.set_option(\"display.max_columns\", None)\npd.set_option(\"display.width\", 500)\npd.set_option(\"display.expand_frame_repr\", False)\nfrom mlxtend.frequent_patterns import apriori, association_rules\n!pip install xlrd\n!pip install openpyxl\ndf_ = pd.read_excel(\"..\/input\/uci-online-retail-ii-data-set\/online_retail_II.xlsx\", sheet_name= \"Year 2010-2011\")\ndf = df_.copy()\ndf.head()\n# To avoid the outliers\ndef outlier_thresholds(dataframe, variable):\n    quartile1 = dataframe[variable].quantile(0.01)\n    quartile3 = dataframe[variable].quantile(0.99)\n    interquantile_range = quartile3 - quartile1\n    up_limit = quartile3 + 1.5 * interquantile_range\n    low_limit = quartile1 - 1.5 * interquantile_range\n    return low_limit, up_limit\ndef replace_with_thresholds(dataframe, variable):\n    low_limit, up_limit = outlier_thresholds(dataframe, variable)\n    dataframe.loc[(dataframe[variable] < low_limit), variable] = low_limit\n    dataframe.loc[(dataframe[variable] > up_limit), variable] = up_limit\n# Preprocessing\ndef retail_data_prep(dataframe):\n    dataframe.dropna(inplace=True)\n    dataframe = dataframe[~dataframe[\"Invoice\"].str.contains(\"C\", na=False)]\n    dataframe = dataframe[dataframe[\"Quantity\"] > 0]\n    dataframe = dataframe[dataframe[\"Price\"] > 0]\n    replace_with_thresholds(dataframe, \"Quantity\")\n    replace_with_thresholds(dataframe, \"Price\")\n    return dataframe\ndf_germany = df[df[\"Country\"] == \"Germany\"]\ndf_germany.groupby([\"Invoice\",\"Description\"]).agg({\"Quantity\":\"sum\"}).head(20)\ndf_germany.groupby(['Invoice', 'Description']).agg({\"Quantity\": \"sum\"}).unstack().iloc[0:5, 0:5]\ndf_germany.groupby(['Invoice', 'Description']).agg({\"Quantity\": \"sum\"}).unstack().fillna(0).iloc[0:5, 0:5]\ndf_germany.groupby(['Invoice', 'Description']).agg({\"Quantity\": \"sum\"}).unstack().fillna(0).applymap(lambda x: 1 if x > 0 else 0).iloc[0:5, 0:5]\n\"\"\"\n# TASK 2: \n\nGenerate association rules through Germany customers.\n\"\"\"\ndef create_invoice_product_df(dataframe, id=False):\n    if id:\n        return dataframe.groupby([\"Invoice\", \"StockCode\"])[\"Quantity\"].sum().unstack().fillna(0). \\\n            applymap(lambda x: 1 if x > 0 else 0)\n    else:\n        return dataframe.groupby([\"Invoice\", \"Description\"])[\"Quantity\"].sum().unstack().fillna(0). \\\n            applymap(lambda x: 1 if x > 0 else 0)\nger_inv_pro_df = create_invoice_product_df(df_germany)\nger_inv_pro_df = create_invoice_product_df(df_germany, id=True)\n# For the find the names of id\ndef check_id(dataframe, stock_code):\n    product_name = dataframe[dataframe[\"StockCode\"] == stock_code][[\"Description\"]].values[0].tolist()\n    print(product_name)\n\"\"\"\n# TASK 3: \n\nWhat are the names of the products whose IDs are given?\n\"\"\"\ncheck_id(df_germany, 21987) # ['PACK OF 6 SKULL PAPER CUPS']\ncheck_id(df_germany, 23235) # ['STORAGE TIN VINTAGE LEAF']\ncheck_id(df_germany, 22747) # [\"POPPY'S PLAYHOUSE BATHROOM\"]\n\"\"\"\n# TASK 4: \n\nMake a product recommendation for the users in the cart.\n\"\"\"\nfrequent_itemsets = apriori(ger_inv_pro_df, min_support=0.01, use_colnames=True)\nfrequent_itemsets.sort_values(\"support\", ascending=False).head(20)\nrules = association_rules(frequent_itemsets, metric=\"support\", min_threshold=0.01)\nrules.sort_values(\"support\", ascending=False).head(100)\nrules.sort_values(\"lift\", ascending=False).head(100)\n# Product recommendation:\ndef arl_recommender(rules_df, product_id, rec_count=1):\n    sorted_rules = rules_df.sort_values(\"lift\", ascending=False)\n    recommendation_list = []\n    for i, product in enumerate(sorted_rules[\"antecedents\"]):\n        for j in list(product):\n            if j == product_id:\n                recommendation_list.append(list(sorted_rules.iloc[i][\"consequents\"])[0])\n\n    return recommendation_list[0:rec_count]\narl_recommender(rules, 21987,2) # [21086, 21989]\ncheck_id(df_germany, 21086) # ['SET\/6 RED SPOTTY PAPER CUPS']\narl_recommender(rules, 22747,1)# [22746]\ncheck_id(df_germany, 22746) # [\"POPPY'S PLAYHOUSE LIVINGROOM \"]\n\"\"\"\n# <span style=\"font-family:cursive;\"> Thank youu:)))) <\/span>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2610f747b4a89b'}"}
{"id":"2578","text":"\"\"\"\n# \ud83e\udda0 Cell Instance Segmentation: \ud83d\udd0d interative data view\n\nFor more or future development see https:\/\/borda.github.io\/kaggle_cell-inst-segm\n\"\"\"\n! ls -l \/kaggle\/input\/sartorius-cell-instance-segmentation\n# ! ls -l \/kaggle\/input\/sartorius-cell-instance-segmentation\/LIVECell_dataset_2021\n\"\"\"\nBrowsing the provided data\/images\/annotations...\n\"\"\"\nimport os\nimport pandas as pd\n\nPATH_DATASET = \"\/kaggle\/input\/sartorius-cell-instance-segmentation\"\nPATH_IMAGES = os.path.join(PATH_DATASET, \"train\")\nPATH_TRAIN_CSV = os.path.join(PATH_DATASET, \"train.csv\")\n\ndf_train = pd.read_csv(PATH_TRAIN_CSV)\ndisplay(df_train.head())\ndf_train.loc[0, \"annotation\"]\n\"\"\"\n## Histogram of annotation per image\n\"\"\"\ndf_counts = df_train.groupby(['id']).size()\ndisplay(df_counts.head())\nax = df_counts.hist(bins=50, grid=True)\nax.set_xlabel(\"Annotations per image\")\nax.set_ylabel(\"Images with particular annot. count\")\n\"\"\"\n## Decode single annotation\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef rle_decode(mask_rle: str, img: np.ndarray = None, img_shape: tuple = None, label: int = 1) -> np.ndarray:\n    seq = mask_rle.split()\n    starts = np.array(list(map(int, seq[0::2])))\n    lengths = np.array(list(map(int, seq[1::2])))\n    assert len(starts) == len(lengths)\n    ends = starts + lengths\n    \n    if img is None:\n        img = np.zeros((np.product(img_shape), ), dtype=np.uint16)\n    else:\n        img_shape = img.shape\n        img = img.flatten()\n    for begin, end in zip(starts, ends):\n        img[begin:end] = label\n    return img.reshape(img_shape)\n\nmask = rle_decode(df_train.loc[0, \"annotation\"], img_shape=(df_train.loc[0, \"height\"], df_train.loc[0, \"width\"]))\nmask = rle_decode(df_train.loc[1, \"annotation\"], img=mask, label=2)\n_= plt.imshow(mask)\n\"\"\"\n## Create complete mask\n\"\"\"\ndef create_mask(df_image: pd.DataFrame) -> np.ndarray:\n    assert len(df_image[\"id\"].unique()) == 1\n    sizes = list(set((row[\"height\"], row[\"width\"]) for _, row in df_image.iterrows()))\n    assert len(sizes) == 1\n    mask = np.zeros(sizes[0], dtype=np.uint16)\n    df_image.reset_index(inplace=True)\n    for idx, row in df_image.iterrows():\n        mask = rle_decode(row[\"annotation\"], img=mask, label=idx + 1)\n    return mask\n    \n\n# print(df_train[\"sample_id\"].unique())\nmask = create_mask(df_train[df_train[\"id\"] == \"0030fd0e6378\"])\n_= plt.imshow(mask, interpolation='antialiased')\n\"\"\"\n## Interactive view\n\nNote that for interative browsing you need to be in edit mode (it is not supported for saved version)\n\"\"\"\nfrom ipywidgets import interact, SelectionSlider\n\n\ndef show_image_annot(img_name: str, df_train: pd.DataFrame, img_folder: str):\n    print(img_name)\n    df_img = df_train[df_train[\"id\"] == img_name]\n    path_img = os.path.join(img_folder, f\"{img_name}.png\")\n    img = plt.imread(path_img)\n    mask = create_mask(df_img)\n    fig, axarr = plt.subplots(ncols=3, figsize=(18, 6))\n    axarr[0].imshow(img)\n    axarr[1].imshow(img)\n    axarr[1].contour(mask, levels=np.unique(mask).tolist(), cmap=\"inferno\", linewidths=0.5)\n    axarr[2].imshow(mask, cmap=\"inferno\", interpolation='antialiased')\n    return fig\n\n\ndef interactive_show(df_train: pd.DataFrame, img_folder: str):\n    uq_images = df_train[\"id\"].unique()\n    interact(\n        lambda im: plt.show(show_image_annot(im, df_train, img_folder)),\n        im=SelectionSlider(\n            options=uq_images,\n            value=\"cc40345857dd\",  # uq_images[np.random.randint(0, len(uq_images))],\n            description='Select image:',\n            disabled=False,\n            continuous_update=False,\n            orientation='horizontal',\n            readout=True\n        ),\n    )\n\ninteractive_show(df_train, PATH_IMAGES)","meta":"{'source': 'AI4Code', 'id': '04eac711c149f7'}"}
{"id":"96426","text":"\"\"\"\n# General information about this notebook\nThis notebook has empty output cells. It ran outside of Kaggle for computation reasons:\n- Kaggle has many libraries, so dependencies\n- long notebook runtime\n\nHowever you can find the full notebook with full output on Github:\nhttps:\/\/github.com\/ThomasMeissnerDS\/e2e_ml\/blob\/develop\/Example%20notebooks\/Auto%20exploration%20using%20Timewalk\/Kaggle%20credit%20card%20fraud%20with%20Timewalk.ipynb\n\"\"\"\n\"\"\"\nThis notebook did not run on Kaggle, but a local system.\nWe are running on e2eml version 2.10.1\n\"\"\"\n\"\"\"\n# Introduction\n\nHi,\n\nI am Thomas, creator of the automl library e2eml. In this notebook I give you a little walkthrough and example run using a feature called Timewalk.\n\nI created this library for personal development, but also to give something back to the data science community. You can install the library using !pip install e2eml.\n\n\n# What does e2eml offer?\ne2eeml has two major goals: You can either speed up your prototyping and exploration (with Timewalk) or create a full pipeline with just a few lines of code. e2eml will take care of:\n- data preprocessing\n- model training\n- model fine-tuning\n- model evaluation\n- logging file\n\nIt can handle datetime, categorical and numerical data and allows you to build classification & regression models. For NLP tasks you can even let it create a full BERT model for you.\n\n# Why e2eml and not any other automl framework?\nThis decision is fully up to you. They all have their ins & outs. Chose what suits your needs best. e2eml is just an option for you.\n\n\n# What is the spirit of e2eml?\nThis library tries to maximize the model performance. It shall help to see how far you can get given your data.\nAs a characteristic it creates huge notebooks, but we really wanted to print out a lot for. We want you to be able to actually see what is happening under the hood. That comes at a cost here. If you prefer very elegant and silent implementations, check out the fantastic Pycaret library.\nAdditionally being able to fine-tune BERT models for you can be a life saver. We also provide some GPU acceleration with RAPIDS. Currently this is implemented in a few spots only however.\n\"\"\"\n\"\"\"\n# Importing libraries\n\"\"\"\n# import libraries and custom Postgres connector\nfrom e2eml.full_processing import postprocessing\nfrom e2eml.classification import classification_blueprints as cb\nfrom e2eml.timetravel import timetravel\n\nimport pandas as pd\nfrom sklearn import model_selection\nfrom sklearn.metrics import matthews_corrcoef\nfrom sklearn.metrics import classification_report\nimport re\nimport numpy as np\npd.set_option('display.max_colwidth', None)\n\nimport pickle\nimport gc\n\"\"\"\n# Import needed data\n\"\"\"\ntarget = 'Class'\ncreditcard = pd.read_csv('creditcard.csv')\ncreditcard\ncreditcard[target].value_counts()\ncreditcard[target].isna().sum()\nlen(creditcard.index)\n\"\"\"\n# Test train split\n\"\"\"\n\"\"\"\nFirst we sort the dataset by timestamp and then hold back the newest data points as unseen holdout data for validation.\nThis has two reasons:\n- Without any unseen data we cannot see overfitting\n- Fraud does not consist of static behaviour. In real world applications fraudsters change their behaviour to adapt for anti-fraud mechanisms. For model prototyping (not final training!) it makes sense to keep newest data as holdout, so we can see, if our model can adapt to changing patterns (given they even change in our training data)\n\"\"\"\ncreditcard = creditcard.sort_values(by=[\"Time\"], ascending=[True])\ntrain_df = creditcard.head(230000)\n\"\"\"\nHere we go crazy actually. Timewalk should be used with smaller samples, but we want to illustrate what might happen, if the sample is very big.\n\"\"\"\ntrain_df = train_df.sample(100000, random_state=1000)\ntrain_df_target = train_df[target]\ntrain_df_target.value_counts()\n# actual holdout\nholdout_df = creditcard.tail(50000)\nhold_df_target = holdout_df[target]\ndel holdout_df[target]\nhold_df_target.value_counts()\ndel creditcard\n_ = gc.collect()\n\"\"\"\n# Automl using e2eml\n\nWe use e2eml. There are plenty of fantastic frameworks. Chose whatever you like.\n\"\"\"\n\"\"\"\nUsing e2eml we first instantiate a class, here a ClassificationBluePrint.\n\"\"\"\nautoml_pipeline = cb.ClassificationBluePrint(datasource=train_df,\n                                       target_variable=target,\n                                       preferred_training_mode='cpu',\n                                       tune_mode='accurate',\n                                       ml_task='binary',\n                                       rapids_acceleration=False\n                                        )\n\"\"\"\nFrom here we have two general options. We can:\n- run a certain blueprint straight away (this is great to create a ready-to-use pipeline for prediction)\n- run Timewalk to fully explore many algorithms and preprocessing combinations\n\nHere we assume that we don't know much about what works for this dataset. So we chose Timewalk. Timewalk takes a long time to run (this can be controlled by manually chosing algorithms and preprocessing steps to use). As we have plenty of data Timewalk will automatically switch off some algorithms. I.e. Xgboost will not run here (this has been designed due to problems of releasing the memory again and also due to high consumption of system resources).\n\nAs our data is imbalanced, we add this flag as a parameter. This will add an additional step for imbalanced data only.\n\"\"\"\nresults = timetravel.timewalk_auto_exploration(class_instance=automl_pipeline,\n                                   holdout_df=holdout_df,\n                                   holdout_target=hold_df_target,\n                                   is_imbalanced=True,\n                                   algs_to_test=None,\n                                   experiment_name=\"timewalk_creditcard_fraud.pkl\")\nresults = pd.read_pickle(\"timewalk_creditcard_fraud.pkl\")\nresults.sort_values(by=[\"Matthews\"], ascending=[False]).head(30).drop_duplicates(subset=['Trial number', 'Algorithm', 'Matthews'], keep='last')\n\"\"\"\n# Results overview\nTimewalk returns a result dataframe. Here we can sort the results by Matthews correlation to see our best results.\n\nDuring our trial we ran out of memory. As Timewalk is still in an early stage we still try to aim for optimization. Timewalk tries to clean memory, but sometimes it does not clean properly., However we had a different reason here. For some reason memory consumption exploded after transforming the data.\n\nHowever it is not a big problem here. We already saw very good results. If we would like to continue Timewalk we could pass the parameter \"preprocess_checkpoints\", which expects a list. On default this includes:\n- \"default\"\n- \"delete_low_variance_features\"\n- \"automated_feature_selection\"\n- \"autotuned_clustering\"\n- \"cardinality_remover\"\n- \"delete_high_null_cols\"\n- \"early_numeric_only_feature_selection\"\n- \"fill_infinite_values\"\n\nWe failed during checkpoint \"cardinality_remover\". So we could provide the list \n[\"default\", \n \"delete_high_null_cols\",\n \"early_numeric_only_feature_selection\",\n \"fill_infinite_values\"] instead. We exclude the failing step as well as we would trigger the same issue again.\n \n We can also chose to run less algorithms. SGD & Quadratic Discriminent Analysis did not look promising at all. TabNet has been very good, but extremely slow.\n\"\"\"\n\"\"\"\n# Continue the trial\nWe continue our trial, but change the parameters (for this step we restartet Jupyter Kernel and rerun the code until ClassificationBlueprint instantiation. This is for demonstation purposes only).. We explicitly call certain algorithms and also reduce checkpoints (\"default\" is mandatory here). We also provide the name of an existing experiment file, so Timewalk can append new to previous results. This is kind of a mini MLOps utility.\n\nWhat exactly happens here?\nTimetravel will run the \"default\" step. During this step it creates different save points of our preprocessed data and stores them locally. In it's current implementation it does this every time we run Timnetravel. Please be aware, that this might consume much disk space (depending on dataset size).\nThen Timewalk will load a previous preprocessing checkpoint from disk, adjust some preprocessing decisions (i.e. different feature selection) and run the models again. In our case this should run a lot faster than in the attempt above, because we do not make use of all steps and algorithms anymore. Especially TabNet has been very slow. \n\"\"\"\nresults = timetravel.timewalk_auto_exploration(class_instance=automl_pipeline,\n                                   holdout_df=holdout_df,\n                                   holdout_target=hold_df_target,\n                                   is_imbalanced=True,\n                                    preprocess_checkpoints=[\"default\", \n                                                            \"delete_high_null_cols\",\n                                                            \"early_numeric_only_feature_selection\",\n                                                            \"fill_infinite_values\"],\n                                   algs_to_test=[\"lgbm\", \"lgbm_focal\", \"ridge\", \"logistic_regression\", \"vowpal_wabbit\"],\n                                   name_of_exist_experiment=\"timewalk_creditcard_fraud.pkl\",\n                                   experiment_name=\"timewalk_creditcard_fraud.pkl\")\n\"\"\"\nAfter the delete_high_null_cols step we would run into the same issues as every following step would use feature transformation as well.\nHere we could cose to run this npart with a smaller sample size, but LGBM focal seems to be the winner anyway.\n\"\"\"\nresults = pd.read_pickle(\"timewalk_creditcard_fraud.pkl\")\nresults.sort_values(by=[\"Matthews\"], ascending=[False]).head(30).drop_duplicates(subset=['Trial number', 'Algorithm', 'Matthews'], keep='last')\nimport plotly.express as px\nfig = px.line(\n            results,\n            x=\"Total runtime\",\n            y=\"Matthews\",\n            color=\"Algorithm\",\n            text=\"Trial number\",\n            title='Performance vs runtime comparison of algorithms'\n        )\nfig.update_traces(textposition=\"bottom right\")\nfig.show()\n\"\"\"\nLGBM focal is has been fast and superior. This makes sense as focal loss is most suitable for imbalanced data (binary and multiclass).\n\"\"\"\n\"\"\"\n# Creating the final pipeline\nWe:\n- restart the notebook\n- reimport libraries\n- reload the data, but this time use 230k rows for training instead of 100k\n- load in the results from Timnewalk\n- instantiate a ClassificationBlueprint class\n- take the winning parameters from results and overwrite the class default preprocessing steps\n- run the lgbm_focal_loss pipeline\n- run the function agsin (from here it is in prediction mode and will predict on new data)\n- do a final evaluation\n\nLet's see, if more data can help improving the score. It could also hurt performance, if we sudeenly have more bad data points in the set. \n\"\"\"\ntarget = 'Class'\ncreditcard = pd.read_csv('creditcard.csv')\ncreditcard = creditcard.sort_values(by=[\"Time\"], ascending=[True])\ntrain_df = creditcard.head(230000)\ntrain_df = train_df.sample(230000, random_state=1000)\ntrain_df_target = train_df[target]\n# actual holdout\nholdout_df = creditcard.tail(50000)\nhold_df_target = holdout_df[target]\ndel holdout_df[target]\ndel creditcard\n_ = gc.collect()\nresults = pd.read_pickle(\"timewalk_creditcard_fraud.pkl\")\nresults.sort_values(by=[\"Matthews\"], ascending=[False]).head(30).drop_duplicates(subset=['Trial number', 'Algorithm', 'Matthews'], keep='last')\nwinner_set = results[(results[\"Accuracy\"].isna() == False)].sort_values(by=[\"Matthews\"], ascending=[False]).head(1)\nwinner_set\nautoml_pipeline = cb.ClassificationBluePrint(datasource=train_df,\n                                       target_variable=target,\n                                       preferred_training_mode='cpu',\n                                       tune_mode='accurate',\n                                       ml_task='binary',\n                                       rapids_acceleration=False\n                                        )\n# showing the preprocessing steps of our best iteration and model\nbest_params = winner_set[\"Preprocessing applied\"].values.tolist()[0]\n\n# use best prarams from timewalk\nfor key, value in best_params.items():\n    automl_pipeline.blueprint_step_selection_non_nlp[key] = value\nautoml_pipeline.ml_bp14_multiclass_full_processing_lgbm_focal()\nautoml_pipeline.ml_bp14_multiclass_full_processing_lgbm_focal(holdout_df)\nalgorithms = [\"lgbm_focal\"]\n\ndef get_matthews(algorithm):\n    # Assess prediction quality on holdout data\n    print(classification_report(hold_df_target, automl_pipeline.predicted_classes[algorithm]))\n    try:\n        matthews = matthews_corrcoef(hold_df_target, automl_pipeline.predicted_classes[algorithm])\n    except Exception:\n        print(\"Matthew failed.\")\n        matthews = 0\n    print(matthews)\n    \nfor i in algorithms:\n    print(f\"---------Start evaluating {i}----------\")\n    get_matthews(i)\n\"\"\"\nMore data did not improve our model.\n\"\"\"\n\"\"\"\n# Summary\n\nIt seems like we created a good model here. However some notes:\n- Accuracy is not a good metric for imbalanced data. Matthews correlation is a lot better as a general metric\n- Our model could still fail on production! The training data might be from a wrong season or just too old and would suffer a lot seeing new patterns in production. So monitoring ongoing performance of your model is extremely important.\n- Does automl replace data scientists? No, it empowers them. Instead of building stuff from scratch, data scientists can focus on finding better features. Also it needs expertise to properly evaluate a model. Automl cannot replace domain knowledge at all.\n\nI hope you enjoyed the notebook. Upvotes are very welcome :-) \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b11ed9451ca50f'}"}
{"id":"108221","text":"\"\"\"\n# **Heart Disease (EDA & ML)**\n\"\"\"\n\"\"\"\n## **Exploratory Data Analysis (EDA)**\n\"\"\"\n\"\"\"\n#### **Step 1: Loading and Displaying tabular data**\n\"\"\"\nimport pandas as pd\n\n# Not limiting the column number when displaying dataframe\npd.set_option(\"display.max_columns\", None)\ndf = pd.read_csv(\"..\/input\/heart-failure-prediction\/heart.csv\", sep = r',', skipinitialspace = True)\ndf.head()\ndf.tail()\ndf.shape\n\"\"\"\n#### **Step 2: Basic statistics about the dataframe and specific columns**\n\"\"\"\nprint(df.columns)\nrows = df.shape[0]\ncols = df.shape[1]\n\nprint(\"Before cleaning, there are \" + str(rows) + \" rows and \" + str(cols) + \" columns in this dataframe.\")\ndupRows = df.duplicated().sum()\nprint(\"There are \" + str(dupRows) + \" duplicated rows in the dataframe.\")\ndf.isnull().sum()\ndf.nunique()\ndf.info()\ndf.dtypes.value_counts()\ndf.describe()\ndf.memory_usage()\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize = (16, 16))\nplt.title(\"Age Distribution\", fontsize = 20)\nplt.xlabel(\"Age\", fontsize = 16)\nplt.ylabel(\"Number of occurences\", fontsize = 16)\nsns.histplot(df[\"Age\"], color = \"gold\")\nplt.show()\n\"\"\"\n#### **Step 3: Correlation, Interdependencies, Relations & more**\n\"\"\"\ndf.corr()\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ncorrelations = df.corr()\n\nplt.figure(figsize = (16, 16))\nplt.title(\"Heatmap displaying the correlations between all columns\", fontsize = 20)\nsns.heatmap(correlations, annot = True, cmap = \"YlOrBr\", cbar_kws={'label': 'Correlation Value', 'orientation': 'horizontal'})\n\"\"\"\nHow do the columns correlate with our target column \"HeartDisease\"?\n\"\"\"\nhd = df.corr()[\"HeartDisease\"]\nhd = pd.DataFrame(hd)\nhd\n%matplotlib inline\n\nplt.figure(figsize = (16, 12))\nplt.title(\"Correlations between input columns and target column 'HeartDisease'\", fontsize = 20)\nplt.xlabel(\"Columns\", fontsize = 16)\nplt.ylabel(\"Correlation factor\", fontsize = 16)\nplt.plot(hd, color = \"orange\", linestyle = \"\", marker = \"X\")\nplt.show()\nsns.pairplot(df)\n\"\"\"\nHow many people have heart disease and how many don't?\n\"\"\"\nno = df.value_counts([\"HeartDisease\"])[0]\nyes = df.value_counts([\"HeartDisease\"])[1]\n\nprint(str(no) + \" patients do not have heart disease, while \" + str(yes) + \" do.\")\n\"\"\"\nAre there more men or more women with heart disease and what is their percentage?\n\"\"\"\npd.crosstab(df[\"Sex\"], df[\"HeartDisease\"])\n\"\"\"\nThere are way more men with heart disease than women, both in % and in absolute numbers.\n\"\"\"\nct = pd.crosstab(df[\"Sex\"], df[\"HeartDisease\"]) \n\nplt.figure(figsize = (16, 12))\nplt.title(\"Crosstab showing how many patients of which sex were diagnosed with heart disease\", fontsize = 20)\nsns.heatmap(ct, cmap = \"PiYG\", annot = True, cbar = True, fmt = \"g\", cbar_kws={'label': 'Absolute number of occurences', 'orientation': 'horizontal'})\n\"\"\"\nHow many people of what age had to die?\n\"\"\"\npd.crosstab(df[\"Age\"], df[\"HeartDisease\"])\nct = pd.crosstab(df[\"Age\"], df[\"HeartDisease\"]) \n\nplt.figure(figsize = (16, 16))\nplt.title(\"Crosstab showing how many patients of what age were diagnosed with heart disease\", fontsize = 20)\nsns.heatmap(ct, cmap = \"BuPu\", annot = True, cbar = True, fmt = \"g\", cbar_kws={'label': 'Absolute number of occurences', 'orientation': 'horizontal'})\n\"\"\"\n#### **Step 4: Interactive Profiling**\n\"\"\"\npip install pandas-profiling[notebook]\nimport pandas_profiling\nfrom pandas_profiling import ProfileReport\n\nprofile = ProfileReport(df, title = \"Pandas Profiling Report\", explorative = True)\n\nprofile.to_widgets()\n\"\"\"\n#### ================================================================================================================\n\"\"\"\n\"\"\"\n## **Machine Learning (ML)**\n\"\"\"\n\"\"\"\n#### **Step 1: Pre-Cleaning & Pre-Processing data**\n\"\"\"\ndf.head()\ndf = df.dropna()\ndf = df.replace(\"M\", 1)\ndf = df.replace(\"F\", 2)\ndf[\"ChestPainType\"] = df[\"ChestPainType\"].astype(str)\ndf[\"RestingECG\"] = df[\"RestingECG\"].astype(str)\ndf[\"ExerciseAngina\"] = df[\"ExerciseAngina\"].astype(str)\ndf[\"ST_Slope\"] = df[\"ST_Slope\"].astype(str)\n\nfrom sklearn import preprocessing\n\nnumber = preprocessing.LabelEncoder()\n\ndf[\"ChestPainType\"] = number.fit_transform(df[\"ChestPainType\"])\ndf[\"RestingECG\"] = number.fit_transform(df[\"RestingECG\"])\ndf[\"ExerciseAngina\"] = number.fit_transform(df[\"ExerciseAngina\"])\ndf[\"ST_Slope\"] = number.fit_transform(df[\"ST_Slope\"])\n\ndf.head()\n\"\"\"\n#### **Step 2: Defining input\/output and Splitting dataframe**\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX = df.drop([\"HeartDisease\"], axis = 1)\ny = df[\"HeartDisease\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0, test_size = 0.1)\n\"\"\"\n#### **Step 3: Models**\n\"\"\"\n\"\"\"\n#### Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression(solver = \"saga\", max_iter = 10000)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\"\"\"\n#### Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier(criterion = \"entropy\")\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\"\"\"\n#### Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\n\nmodel = DecisionTreeClassifier(criterion = \"entropy\")\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\nfrom sklearn.model_selection import validation_curve\nfrom sklearn.tree import DecisionTreeClassifier\nimport numpy as np\n\nparam_range = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n\ntrain_scores, test_scores = validation_curve(DecisionTreeClassifier(), X_train, y_train, param_name = \"max_depth\", param_range = param_range)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize = (16, 12))\n\nplt.plot(param_range, np.mean(train_scores, axis = 1))\nplt.plot(param_range, np.mean(test_scores, axis = 1))\n\nplt.title(\"How does the tree depth influence the accuracy?\", fontsize = 20)\nplt.xlabel(\"depth levels of model\", fontsize = 15)\nplt.ylabel(\"model accuracy\", fontsize = 15)\n\n# Adding a legend\nplt.legend([\"train\", \"test\"], loc = \"upper left\", fontsize = 12)\n\nplt.show()\n\"\"\"\n#### SVM with RBF-Kernel\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaler.fit(X_train)\n\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\nfrom sklearn.svm import SVC\n\nmodel = SVC(kernel = \"rbf\", gamma = 0.01, C = 5)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\"\"\"\n#### Gaussian NB\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\n\nmodel = GaussianNB()\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\"\"\"\n#### KNN\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\n\nmodel = KNeighborsClassifier(n_neighbors = 18)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.utils import shuffle\n\nX_train, y_train = shuffle(X_train, y_train)\n\nimport numpy as np\n\ntrain_sizes_abs, train_scores, test_scores = learning_curve(KNeighborsClassifier(), X_train, y_train)\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize = (16, 12))\n\nplt.plot(train_sizes_abs, np.mean(train_scores, axis = 1))\nplt.plot(train_sizes_abs, np.mean(test_scores, axis = 1))\n\nplt.title(\"Learning Curve KNN\", fontsize = 20)\nplt.xlabel(\"Number of neighbors\", fontsize = 15)\nplt.ylabel(\"Model Accuracy\", fontsize = 15)\n\n# Adding a legend\nplt.legend([\"train\", \"test\"], loc = \"upper right\", fontsize = 12)\n\nplt.show()\n\"\"\"\n#### Logistic Regression with pre-scaled data\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaler.fit(X_train)\n\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression(solver = \"saga\", max_iter = 10000)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)","meta":"{'source': 'AI4Code', 'id': 'c6e9d48e8cf749'}"}
{"id":"50541","text":"# 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 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\n\"\"\"\n# importing the libararies \n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport random \nimport matplotlib.pyplot as plt \nimport tensorflow as tf \nimport math \nimport pandas_datareader as data_reader \n\nfrom tqdm import tqdm_notebook , tqdm \nfrom collections import deque \n\"\"\"\n# building the AI trader network\n\"\"\"\nclass AI_Trader():\n  \n  def __init__(self, state_size, action_space=3, model_name=\"AITrader\"): #Stay, Buy, Sell\n    \n    self.state_size = state_size\n    self.action_space = action_space\n    self.memory = deque(maxlen=2000)\n    self.inventory = []\n    self.model_name = model_name\n    \n    self.gamma = 0.95\n    self.epsilon = 1.0\n    self.epsilon_final = 0.01\n    self.epsilon_decay = 0.995\n    \n    self.model = self.model_builder()\n    \n  def model_builder(self):\n    \n    model = tf.keras.models.Sequential()\n    \n    model.add(tf.keras.layers.Dense(units=32, activation='relu', input_dim=self.state_size))\n    \n    model.add(tf.keras.layers.Dense(units=64, activation='relu'))\n    \n    model.add(tf.keras.layers.Dense(units=128, activation='relu'))\n    \n    model.add(tf.keras.layers.Dense(units=self.action_space, activation='linear'))\n    \n    model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(lr=0.001))\n    \n    return model\n  \n  def trade(self, state):\n    \n    if random.random() <= self.epsilon:\n      return random.randrange(self.action_space)\n    \n    actions = self.model.predict(state)\n    return np.argmax(actions[0])\n  \n  \n  def batch_train(self, batch_size):\n    \n    batch = []\n    for i in range(len(self.memory) - batch_size + 1, len(self.memory)):\n      batch.append(self.memory[i])\n      \n    for state, action, reward, next_state, done in batch:\n      reward = reward\n      if not done:\n        reward = reward + self.gamma * np.amax(self.model.predict(next_state)[0])\n        \n      target = self.model.predict(state)\n      target[0][action] = reward\n      \n      self.model.fit(state, target, epochs=1, verbose=0)\n      \n    if self.epsilon > self.epsilon_final:\n      self.epsilon *= self.epsilon_decay\n            \n        \n\"\"\"\n# data set preprocessing \n\"\"\"\n\"\"\"\n## sigmoid \n\"\"\"\ndef sigmoid(x):\n    return 1\/(1 + math.exp(-x))\n\"\"\"\n## price format function \n\"\"\"\ndef stock_price_format(n):\n    if n < 0 :\n        return '- $ {:2f}'.format(abs(n))\n    else :\n        return '$ {:2f}'.format(abs(n))\n\"\"\"\n# dataset loader \n\"\"\"\ndef dataset_loader(stock_name):\n    \n    dataset = data_reader.DataReader(stock_name , data_source = 'yahoo')\n    \n    start_date = str(dataset.index[0]).split()[0]\n    end_date = str(dataset.index[-1]).split()[0]\n    \n    close = dataset['Close']\n    return close  \n# this is for example purpose for apple stocks \n\n\ndataset_for_example = data_reader.DataReader('AAPL' , data_source = 'yahoo')\ndataset_for_example\n\n\"\"\"\n# state creator \n\"\"\"\ndef state_creator(data, timestep, window_size):\n  \n  starting_id = timestep - window_size + 1\n  \n  if starting_id >= 0:\n    windowed_data = data[starting_id:timestep+1]\n  else:\n    windowed_data = - starting_id * [data[0]] + list(data[0:timestep+1])\n    \n  state = []\n  for i in range(window_size - 1):\n    state.append(sigmoid(windowed_data[i+1] - windowed_data[i]))\n    \n  return np.array([state])\n\"\"\"\n# loading a dataset \n\"\"\"\nstock_name = 'AAPL'\ndata = dataset_loader(stock_name)\n\ndata \n\"\"\"\n# Training the AI trader\n\"\"\"\n\"\"\"\n## setting the hyper parameters \n\"\"\"\nwindow_size = 10 \nepisodes = 1000\n\nbatch_size = 32\ndata_samples = len(data) - 1 \n\n\"\"\"\n## defining the trader model \n\"\"\"\ntrader = AI_Trader(window_size)\ntrader.model.summary()\n\"\"\"\n# training loop ( # this training process will take time )\n\"\"\"\n \n for episode in range(1, episodes + 1):\n  \n  print(\"Episode: {}\/{}\".format(episode, episodes))\n  \n  state = state_creator(data, 0, window_size + 1)\n  \n  total_profit = 0\n  trader.inventory = []\n  \n  for t in tqdm(range(data_samples)):\n    \n    action = trader.trade(state)\n    \n    next_state = state_creator(data, t+1, window_size + 1)\n    reward = 0\n    \n    if action == 1: #Buying\n      trader.inventory.append(data[t])\n      print(\"AI Trader bought: \", stock_price_format(data[t]))\n      \n    elif action == 2 and len(trader.inventory) > 0: #Selling\n      buy_price = trader.inventory.pop(0)\n      \n      reward = max(data[t] - buy_price, 0)\n      total_profit += data[t] - buy_price\n      print(\"AI Trader sold: \", stock_price_format(data[t]), \" Profit: \" + stock_price_format(data[t] - buy_price) )\n      \n    if t == data_samples - 1:\n      done = True\n    else:\n      done = False\n      \n    trader.memory.append((state, action, reward, next_state, done))\n    \n    state = next_state\n    \n    if done:\n      print(\"########################\")\n      print(\"TOTAL PROFIT: {}\".format(total_profit))\n      print(\"########################\")\n    \n    if len(trader.memory) > batch_size:\n      trader.batch_train(batch_size)\n      \n  if episode % 10 == 0:\n    trader.model.save(\"ai_trader_{}.h5\".format(episode))","meta":"{'source': 'AI4Code', 'id': '5cfb2fa8b71c71'}"}
{"id":"69454","text":"\"\"\"\nDo hacker news users favor particular topics? Can you predict weather a story will be popular from the title alone? \n\nIn this notebook we will see that it there are definately some keywords in post titles that correlate with higher post scores. It is also possible to create a model that predicts whether a post will be popular given the title alone, albeit with only marginal accuracy improvements over random guessing.\n\"\"\"\n#We will work with the 'stories' table in the hacker news dataset\n#preview the first few lines of the table\nfrom google.cloud import bigquery\n\n# Create a \"Client\" object\nclient = bigquery.Client()\n# Construct a reference to the \"openaq\" dataset\ndataset_ref = client.dataset(\"hacker_news\", project=\"bigquery-public-data\")\n# API request - fetch the dataset\ndataset = client.get_dataset(dataset_ref)\n# Construct a reference to the \"stories\" table\ntable_ref = dataset_ref.table(\"stories\")\n# API request - fetch the table\ntable = client.get_table(table_ref)\n# # Preview the first five lines of the table\nclient.list_rows(table, max_results=5).to_dataframe()\n\"\"\"\nFirst we will try and find a set of words that tend to be associated with high scoring posts. To do that we will first get a big set of 'candidate' popular words (from the most highly scored posts), then we get the median score for posts with these words (over the entire dataset). \n\"\"\"\n#query the dataset for all titles that ended up with very high scores (over 250)\nquery = \"\"\"\n        SELECT score, title    \n        FROM `bigquery-public-data.hacker_news.stories`\n        WHERE score>250\n        \"\"\"\n\n# Create a QueryJobConfig object to estimate size of query without running it\ndry_run_config = bigquery.QueryJobConfig(dry_run=True)\n\n# API request - dry run query to estimate costs\ndry_run_query_job = client.query(query, job_config=dry_run_config)\n\nprint(\"This query will process {:,} bytes.\".format(dry_run_query_job.total_bytes_processed))\n#get the high scoring dataset and convert titles to a spacy object\nimport spacy\nhigh_scores = client.query(query).to_dataframe()\nnlp = spacy.load('en_core_web_lg')\n\ndocs = [nlp(doc) for doc in high_scores['title']]\nfrom collections import defaultdict\nimport pandas as pd\n\nword_lib = defaultdict(list)#this dictionary will hold a list of occurances for each word\nnum_words = {}\n\nfor doc in docs:\n    #get the lemmastized words in the title and ignore top words\n    doc_words = [token.lemma_ for token in doc if not token.is_stop and not token.is_punct]\n    for word in doc_words:\n        #Add an occurance to the list for each word in the title\n        word_lib[word].append(1)\n\nfor key, value in word_lib.items():\n    num_words[key] = sum(value)#add up the occurances for each word\n\n#these are the 100 most popular words in the highest scoring titles. These will be our candidate words.\ncandidate_words = list(pd.Series(num_words).sort_values(ascending=False)[:100].index)\ncandidate_words\n\"\"\"\nNext we will query the full stories dataset and get the median score for each candidate word based on the score of titles that contain it.\n\"\"\"\nfrom spacy.matcher import PhraseMatcher\n\nquery = \"\"\"\n        SELECT score, title    \n        FROM `bigquery-public-data.hacker_news.stories`\n        \"\"\"\n#get all of the titles and scores in the dataset\nstories = client.query(query).to_dataframe()\n\n#drop entries with missing values, then select a random fraction of the data (due to speed and memory limitations)\ndata = stories.dropna().sample(frac=0.05)\n\n#convert titles to spacy\ndocs = [nlp(doc) for doc in data['title']]\n\n# Create a PhraseMatcher object. The tokenizer is the first argument. Use attr = 'LOWER' to make consistent capitalization\nmatcher = PhraseMatcher(nlp.vocab, attr='LOWER')\n\n# Create a list of tokens for each candidate word\ntokens_list = [nlp(item) for item in candidate_words]\n\n# Add the candidate words to the matcher. \nmatcher.add(\"pop_words\",            # Just a name for the set of rules we're matching to\n           tokens_list)\n\nword_scores = defaultdict(list)#this will hold a list of scores for each word\navg_word_scores = {}\n\nfor idx, story in data.iterrows():\n    doc = nlp(story['title'])\n\n    matches = matcher(doc)\n    \n    # Create a set of the items found in the title\n    found_words = set([doc[match[1]:match[2]].lower_ for match in matches])\n    \n    # Update item_ratings with rating for each item in found_items\n    # Transform the item strings to lowercase to make it case insensitive\n    for word in found_words:\n        word_scores[word].append(story['score'])\n\nfrom statistics import median\ndef standard_dev(lst):#function to compute the standard deviation\n    mean = sum(lst)\/len(lst)\n    return (sum([(ele-mean)**2 for ele in lst])\/len(lst))**0.5\n\nfor key, value in word_scores.items():\n    avg_word_scores[key] = [median(value), standard_dev(value), len(value)]\n\npopular_words = pd.DataFrame.from_dict(avg_word_scores, orient='index', columns=['median_score', 'standard_dev', 'count'])\npopular_words.sort_values(by=['median_score', 'count'], ascending=False, inplace=True)\n#Take a look at the 20 most popular words by mdeian score and number of occurances\npopular_words[:20]\n\"\"\"\nIt does look like certain topics tend to be more popular than others. Can we make a model that predicts whether a post will be popular fromthe title alone? We will create a classfication model that tries to predict whether a post gets a score above 5.\n\"\"\"\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import mean_squared_error, accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom lightgbm import LGBMRegressor\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.pipeline import make_pipeline\nimport numpy as np\n\n#vectorize each title (ie. convert the title to a vector in 300 dimensional space)\nwith nlp.disable_pipes():\n    doc_vectors = np.array([nlp_doc.vector for nlp_doc in docs])\n    \n#our target variable will be whether the post got more than 5 score. \ndata['popular'] = data['score'].map(lambda x: 1 if x>5 else 0)\n\nX_train, X_test, y_train, y_test = train_test_split(doc_vectors, data['popular'],\n                                                    test_size=0.2, random_state=20)\n\n#we use a support vector classifier as it works well in high dimensional space\nsvc_model = LinearSVC(random_state=0, tol=1e-5, max_iter=1e3, dual=False, C=100)\n\n#scale the vectors going into the model with a pipeline\nsvc = make_pipeline(MinMaxScaler(), \n                     svc_model\n                    )\n\nsvc.fit(X_train, y_train)\n\"\"\"\nThe suppor vector machine classifier can produce a proabbaily prediction for each class as the diatnce from the support vector to the datapoint. We will use that to produce plots of precision, recall, and ROC\n\"\"\"\nfrom sklearn.metrics import precision_recall_curve, roc_curve, auc\n\nprobas_pred = svc.decision_function(X_test)\nprecision, recall, thresholds = precision_recall_curve(y_test, probas_pred)\nfpr, tpr, thresholds_roc = roc_curve(y_test, probas_pred)\n\npos_ratio = y_test.sum()\/len(y_test)\nAUC = auc(fpr, tpr)\n\nimport matplotlib.pyplot as plt\nfig, axs = plt.subplots(1,2, figsize=(16,6))\n#Plot precision and recall vs threshold\naxs[0].set_title('Model Performance vs Classification Threshold')\naxs[0].plot([thresholds[0],thresholds[-1]], [pos_ratio, pos_ratio], linestyle='--', color='k')\naxs[0].plot(thresholds, precision[1:])\naxs[0].plot(thresholds, recall[1:])\naxs[0].set_xlabel('Threshold')\naxs[0].set_ylabel('Score')\n# axs[0].set_ylim([0, 0.4])\naxs[0].legend(['Precision - Random Classifier', 'Trained Model Precision', 'Trained Model Recall'], loc='best')\naxs[0].grid()\n#Plot ROC\nprops = dict(boxstyle='square', facecolor='white')\naxs[1].set_title('ROC')\naxs[1].text(1.25, 0.95, 'AUC={:.3}'.format(AUC), transform=axs[0].transAxes, fontsize=14,\n        verticalalignment='top', bbox=props)\naxs[1].plot(fpr, tpr)\naxs[1].plot([0,1], [0,1], linestyle='--', color='k')\naxs[1].set_xlabel('False Positive Rate')\naxs[1].set_ylabel('True Positive Rate')\naxs[1].legend(['Trained Model', 'Random Classifier'], loc='lower right')\naxs[1].grid()\nplt.show()\n\"\"\"\n* The model AUC is about 0.6, so it is slightly better than random guessing (0.5) \n* The lower we set the threshold the more the model guesses that every title will be popular, so it finds all the popular titles, but also gets many false positives\n* The higher we set the threshold, the more the model guesses that every title will not be popular. It may reach a higher precision this way (more true positives), but it misses most of the popular titles\n* A good compormise if found around -0.5\n* Comparing to the dashed lines, this model is a bit better than random guessing\n\"\"\"\n#plot confusion matrix for chosen threshold. 1=popular, 0=not popular\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\nthresh = -0.48\ny_pred = [1 if ele>thresh else 0 for ele in probas_pred]\n\ncm = confusion_matrix(y_test, y_pred)\nax = sns.heatmap(cm, annot=True, fmt=\"d\")\nax.set(ylabel='True Label', xlabel='Predicted Label')\nplt.show()\n#function to predict whether a set of titles will be popular\ndef pred(model, thresh, titles, nlp):\n    docs = [nlp(doc) for doc in titles]\n    with nlp.disable_pipes():\n        doc_vectors = np.array([nlp_doc.vector for nlp_doc in docs])\n    probas_pred = model.decision_function(doc_vectors)\n    return [1 if ele>thresh else 0 for ele in probas_pred]\n\ntitles = ['steve jobs hacker python', \n         'hn', \n         'the meaning of life']\n\npred(svc, thresh, titles, nlp)\n#look at which titles the model predicted as popular and got right\n\n[doc for doc, pred in zip(docs,y_pred) if pred==1]","meta":"{'source': 'AI4Code', 'id': '7fd0553430d3da'}"}
{"id":"119171","text":"\"\"\"\n# Residual Attention Network\n\"\"\"\n\"\"\"\nHello everyone! I'm trying attention based mechanism on this dataset to concentrate only the necessary parts of the data, I will train it for only 1 epoch and basic augmentations so that you guys can do much more with that. \n\nPlease note, these parameters I'm using are not tested and can be improved further, Image size is 448 which is according to the model architecture also I'm using AUC ROC for Multiclass because I don't trust accuracy :-P.\n\n\n\nThanks\n\"\"\"\nfrom albumentations import (\n    Compose, OneOf, Normalize, Resize, RandomResizedCrop, RandomCrop, HorizontalFlip, VerticalFlip, \n    RandomBrightness, RandomContrast, RandomBrightnessContrast, Rotate, ShiftScaleRotate, Cutout, \n    IAAAdditiveGaussianNoise, Transpose, HueSaturationValue, CenterCrop, CoarseDropout\n)\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom torch.nn import init\nimport functools\nfrom torch.autograd import Variable\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom PIL import ImageFile \nfrom tqdm import tqdm\nfrom torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, CosineAnnealingLR, ReduceLROnPlateau\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import metrics\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\nclass ResidualBlock(nn.Module):\n    def __init__(self, input_channels, output_channels, stride=1):\n        super(ResidualBlock, self).__init__()\n        self.input_channels = input_channels\n        self.output_channels = output_channels\n        self.stride = stride\n        self.bn1 = nn.BatchNorm2d(input_channels)\n        self.relu = nn.ReLU(inplace=True)\n        self.conv1 = nn.Conv2d(input_channels, int(output_channels\/4), 1, 1, bias = False)\n        self.bn2 = nn.BatchNorm2d(int(output_channels\/4))\n        self.relu = nn.ReLU(inplace=True)\n        self.conv2 = nn.Conv2d(int(output_channels\/4), int(output_channels\/4), 3, stride, padding = 1, bias = False)\n        self.bn3 = nn.BatchNorm2d(int(output_channels\/4))\n        self.relu = nn.ReLU(inplace=True)\n        self.conv3 = nn.Conv2d(int(output_channels\/4), output_channels, 1, 1, bias = False)\n        self.conv4 = nn.Conv2d(input_channels, output_channels , 1, stride, bias = False)\n        \n    def forward(self, x):\n        residual = x\n        out = self.bn1(x)\n        out1 = self.relu(out)\n        out = self.conv1(out1)\n        out = self.bn2(out)\n        out = self.relu(out)\n        out = self.conv2(out)\n        out = self.bn3(out)\n        out = self.relu(out)\n        out = self.conv3(out)\n        if (self.input_channels != self.output_channels) or (self.stride !=1 ):\n            residual = self.conv4(out1)\n        out += residual\n        return out\nclass AttentionModule_pre(nn.Module):\n\n    def __init__(self, in_channels, out_channels, size1, size2, size3):\n        super(AttentionModule_pre, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax1_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax2_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip2_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax3_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation3 = nn.UpsamplingBilinear2d(size=size3)\n\n        self.softmax4_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation2 = nn.UpsamplingBilinear2d(size=size2)\n\n        self.softmax5_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)\n\n        self.softmax6_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_softmax1 = self.softmax1_blocks(out_mpool1)\n        out_skip1_connection = self.skip1_connection_residual_block(out_softmax1)\n        out_mpool2 = self.mpool2(out_softmax1)\n        out_softmax2 = self.softmax2_blocks(out_mpool2)\n        out_skip2_connection = self.skip2_connection_residual_block(out_softmax2)\n        out_mpool3 = self.mpool3(out_softmax2)\n        out_softmax3 = self.softmax3_blocks(out_mpool3)\n        #\n        out_interp3 = self.interpolation3(out_softmax3)\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out = out_interp3 + out_skip2_connection\n        out_softmax4 = self.softmax4_blocks(out)\n        out_interp2 = self.interpolation2(out_softmax4)\n        out = out_interp2 + out_skip1_connection\n        out_softmax5 = self.softmax5_blocks(out)\n        out_interp1 = self.interpolation1(out_softmax5)\n        out_softmax6 = self.softmax6_blocks(out_interp1)\n        out = (1 + out_softmax6) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage0(nn.Module):\n    # input size is 112*112\n    def __init__(self, in_channels, out_channels, size1=(112, 112), size2=(56, 56), size3=(28, 28), size4=(14, 14)):\n        super(AttentionModule_stage0, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        # 56*56\n        self.softmax1_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        # 28*28\n        self.softmax2_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip2_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        # 14*14\n        self.softmax3_blocks = ResidualBlock(in_channels, out_channels)\n        self.skip3_connection_residual_block = ResidualBlock(in_channels, out_channels)\n        self.mpool4 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        # 7*7\n        self.softmax4_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n        self.interpolation4 = nn.UpsamplingBilinear2d(size=size4)\n        self.softmax5_blocks = ResidualBlock(in_channels, out_channels)\n        self.interpolation3 = nn.UpsamplingBilinear2d(size=size3)\n        self.softmax6_blocks = ResidualBlock(in_channels, out_channels)\n        self.interpolation2 = nn.UpsamplingBilinear2d(size=size2)\n        self.softmax7_blocks = ResidualBlock(in_channels, out_channels)\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)\n\n        self.softmax8_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias = False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels , kernel_size=1, stride=1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        # 112*112\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        # 56*56\n        out_softmax1 = self.softmax1_blocks(out_mpool1)\n        out_skip1_connection = self.skip1_connection_residual_block(out_softmax1)\n        out_mpool2 = self.mpool2(out_softmax1)\n        # 28*28\n        out_softmax2 = self.softmax2_blocks(out_mpool2)\n        out_skip2_connection = self.skip2_connection_residual_block(out_softmax2)\n        out_mpool3 = self.mpool3(out_softmax2)\n        # 14*14\n        out_softmax3 = self.softmax3_blocks(out_mpool3)\n        out_skip3_connection = self.skip3_connection_residual_block(out_softmax3)\n        out_mpool4 = self.mpool4(out_softmax3)\n        # 7*7\n        out_softmax4 = self.softmax4_blocks(out_mpool4)\n        out_interp4 = self.interpolation4(out_softmax4) + out_softmax3\n        out = out_interp4 + out_skip3_connection\n        out_softmax5 = self.softmax5_blocks(out)\n        out_interp3 = self.interpolation3(out_softmax5) + out_softmax2\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out = out_interp3 + out_skip2_connection\n        out_softmax6 = self.softmax6_blocks(out)\n        out_interp2 = self.interpolation2(out_softmax6) + out_softmax1\n        out = out_interp2 + out_skip1_connection\n        out_softmax7 = self.softmax7_blocks(out)\n        out_interp1 = self.interpolation1(out_softmax7) + out_trunk\n        out_softmax8 = self.softmax8_blocks(out_interp1)\n        out = (1 + out_softmax8) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage1(nn.Module):\n    # input size is 56*56\n    def __init__(self, in_channels, out_channels, size1=(56, 56), size2=(28, 28), size3=(14, 14)):\n        super(AttentionModule_stage1, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax1_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax2_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip2_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax3_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation3 = nn.UpsamplingBilinear2d(size=size3)\n\n        self.softmax4_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation2 = nn.UpsamplingBilinear2d(size=size2)\n\n        self.softmax5_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)\n\n        self.softmax6_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels , kernel_size = 1, stride = 1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_softmax1 = self.softmax1_blocks(out_mpool1)\n        out_skip1_connection = self.skip1_connection_residual_block(out_softmax1)\n        out_mpool2 = self.mpool2(out_softmax1)\n        out_softmax2 = self.softmax2_blocks(out_mpool2)\n        out_skip2_connection = self.skip2_connection_residual_block(out_softmax2)\n        out_mpool3 = self.mpool3(out_softmax2)\n        out_softmax3 = self.softmax3_blocks(out_mpool3)\n        #\n        out_interp3 = self.interpolation3(out_softmax3) + out_softmax2\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out = out_interp3 + out_skip2_connection\n        out_softmax4 = self.softmax4_blocks(out)\n        out_interp2 = self.interpolation2(out_softmax4) + out_softmax1\n        out = out_interp2 + out_skip1_connection\n        out_softmax5 = self.softmax5_blocks(out)\n        out_interp1 = self.interpolation1(out_softmax5) + out_trunk\n        out_softmax6 = self.softmax6_blocks(out_interp1)\n        out = (1 + out_softmax6) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage2(nn.Module):\n    # input image size is 28*28\n    def __init__(self, in_channels, out_channels, size1=(28, 28), size2=(14, 14)):\n        super(AttentionModule_stage2, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax1_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n        self.softmax2_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation2 = nn.UpsamplingBilinear2d(size=size2)\n\n        self.softmax3_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)\n\n        self.softmax4_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_softmax1 = self.softmax1_blocks(out_mpool1)\n        out_skip1_connection = self.skip1_connection_residual_block(out_softmax1)\n        out_mpool2 = self.mpool2(out_softmax1)\n        out_softmax2 = self.softmax2_blocks(out_mpool2)\n\n        out_interp2 = self.interpolation2(out_softmax2) + out_softmax1\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out = out_interp2 + out_skip1_connection\n        out_softmax3 = self.softmax3_blocks(out)\n        out_interp1 = self.interpolation1(out_softmax3) + out_trunk\n        out_softmax4 = self.softmax4_blocks(out_interp1)\n        out = (1 + out_softmax4) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage3(nn.Module):\n    # input image size is 14*14\n    def __init__(self, in_channels, out_channels, size1=(14, 14)):\n        super(AttentionModule_stage3, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        self.softmax1_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size1)\n\n        self.softmax2_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_softmax1 = self.softmax1_blocks(out_mpool1)\n\n        out_interp1 = self.interpolation1(out_softmax1) + out_trunk\n        out_softmax2 = self.softmax2_blocks(out_interp1)\n        out = (1 + out_softmax2) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage1_cifar(nn.Module):\n    # input size is 16*16\n    def __init__(self, in_channels, out_channels, size1=(16, 16), size2=(8, 8)):\n        super(AttentionModule_stage1_cifar, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)  # 8*8\n\n        self.down_residual_blocks1 = ResidualBlock(in_channels, out_channels)\n\n        self.skip1_connection_residual_block = ResidualBlock(in_channels, out_channels)\n\n        self.mpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)  # 4*4\n\n        self.middle_2r_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size2)  # 8*8\n\n        self.up_residual_blocks1 = ResidualBlock(in_channels, out_channels)\n\n        self.interpolation2 = nn.UpsamplingBilinear2d(size=size1)  # 16*16\n\n        self.conv1_1_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_down_residual_blocks1 = self.down_residual_blocks1(out_mpool1)\n        out_skip1_connection = self.skip1_connection_residual_block(out_down_residual_blocks1)\n        out_mpool2 = self.mpool2(out_down_residual_blocks1)\n        out_middle_2r_blocks = self.middle_2r_blocks(out_mpool2)\n        #\n        out_interp = self.interpolation1(out_middle_2r_blocks) + out_down_residual_blocks1\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out = out_interp + out_skip1_connection\n        out_up_residual_blocks1 = self.up_residual_blocks1(out)\n        out_interp2 = self.interpolation2(out_up_residual_blocks1) + out_trunk\n        out_conv1_1_blocks = self.conv1_1_blocks(out_interp2)\n        out = (1 + out_conv1_1_blocks) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage2_cifar(nn.Module):\n    # input size is 8*8\n    def __init__(self, in_channels, out_channels, size=(8, 8)):\n        super(AttentionModule_stage2_cifar, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)  # 4*4\n\n        self.middle_2r_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.interpolation1 = nn.UpsamplingBilinear2d(size=size)  # 8*8\n\n        self.conv1_1_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_mpool1 = self.mpool1(x)\n        out_middle_2r_blocks = self.middle_2r_blocks(out_mpool1)\n        #\n        out_interp = self.interpolation1(out_middle_2r_blocks) + out_trunk\n        # print(out_skip2_connection.data)\n        # print(out_interp3.data)\n        out_conv1_1_blocks = self.conv1_1_blocks(out_interp)\n        out = (1 + out_conv1_1_blocks) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\n\n\nclass AttentionModule_stage3_cifar(nn.Module):\n    # input size is 4*4\n    def __init__(self, in_channels, out_channels, size=(8, 8)):\n        super(AttentionModule_stage3_cifar, self).__init__()\n        self.first_residual_blocks = ResidualBlock(in_channels, out_channels)\n\n        self.trunk_branches = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n         )\n\n        self.middle_2r_blocks = nn.Sequential(\n            ResidualBlock(in_channels, out_channels),\n            ResidualBlock(in_channels, out_channels)\n        )\n\n        self.conv1_1_blocks = nn.Sequential(\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, bias = False),\n            nn.Sigmoid()\n        )\n\n        self.last_blocks = ResidualBlock(in_channels, out_channels)\n\n    def forward(self, x):\n        x = self.first_residual_blocks(x)\n        out_trunk = self.trunk_branches(x)\n        out_middle_2r_blocks = self.middle_2r_blocks(x)\n        #\n        out_conv1_1_blocks = self.conv1_1_blocks(out_middle_2r_blocks)\n        out = (1 + out_conv1_1_blocks) * out_trunk\n        out_last = self.last_blocks(out)\n\n        return out_last\nclass ResidualAttentionModel_448input(nn.Module):\n    # for input size 448\n    def __init__(self):\n        super(ResidualAttentionModel_448input, self).__init__()\n        self.conv1 = nn.Sequential(\n            nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias = False),\n            nn.BatchNorm2d(64),\n            nn.ReLU(inplace=True)\n        )\n        self.mpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        # tbq add\n        # 112*112\n        self.residual_block0 = ResidualBlock(64, 128)\n        self.attention_module0 = AttentionModule_stage0(128, 128)\n        # tbq add end\n        self.residual_block1 = ResidualBlock(128, 256, 2)\n        # 56*56\n        self.attention_module1 = AttentionModule_stage1(256, 256)\n        self.residual_block2 = ResidualBlock(256, 512, 2)\n        self.attention_module2 = AttentionModule_stage2(512, 512)\n        self.attention_module2_2 = AttentionModule_stage2(512, 512)  # tbq add\n        self.residual_block3 = ResidualBlock(512, 1024, 2)\n        self.attention_module3 = AttentionModule_stage3(1024, 1024)\n        self.attention_module3_2 = AttentionModule_stage3(1024, 1024)  # tbq add\n        self.attention_module3_3 = AttentionModule_stage3(1024, 1024)  # tbq add\n        self.residual_block4 = ResidualBlock(1024, 2048, 2)\n        self.residual_block5 = ResidualBlock(2048, 2048)\n        self.residual_block6 = ResidualBlock(2048, 2048)\n        self.mpool2 = nn.Sequential(\n            nn.BatchNorm2d(2048),\n            nn.ReLU(inplace=True),\n            nn.AvgPool2d(kernel_size=7, stride=1)\n        )\n        self.fc = nn.Linear(2048,10)\n\n    def forward(self, x):\n        out = self.conv1(x)\n        out = self.mpool1(out)\n        out = self.residual_block0(out)\n        out = self.attention_module0(out)\n        # print(out.data)\n        out = self.residual_block1(out)\n        out = self.attention_module1(out)\n        out = self.residual_block2(out)\n        out = self.attention_module2(out)\n        out = self.attention_module2_2(out)\n        out = self.residual_block3(out)\n        # print(out.data)\n        out = self.attention_module3(out)\n        out = self.attention_module3_2(out)\n        out = self.attention_module3_3(out)\n        out = self.residual_block4(out)\n        out = self.residual_block5(out)\n        out = self.residual_block6(out)\n        out = self.mpool2(out)\n        out = out.view(out.size(0), -1)\n        out = self.fc(out)\n\n        return out\nclass ResAttention(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model = ResidualAttentionModel_448input()\n        # self.model.fc.classifier = nn.Linear(n_features, 5)\n        self.model.fc = nn.Linear(2048, 5)\n\n    def forward(self, x):\n        x = self.model(x)\n        return x\nclass ClassificationDataset:\n  def __init__(\n    self, \n    image_paths, \n    targets, \n    resize=None, \n    augmentations=None\n  ):\n    \"\"\"\n    :param image_paths: list of path to images\n    :param targets: numpy array\n    :param resize: tuple, e.g. (256, 256), resizes image if not None\n    :param augmentations: albumentation augmentations\n    \"\"\"\n    self.image_paths = image_paths\n    self.targets = targets\n    self.resize = resize\n    self.augmentations = augmentations\n    \n    self.fmix_params = {\n     'alpha': 1., \n     'decay_power': 3., \n     'shape': (512, 512),\n     'max_soft': True, \n     'reformulate': False\n    },\n\n    self.cutmix_params = {\n     'alpha': 1,\n    }\n    \n  def __len__(self):\n    \"\"\"\n    Return the total number of samples in the dataset\n    \"\"\"\n    return len(self.image_paths)\n  \n  def __getitem__(self,item):\n    \"\"\"\n    For a given \"item\" index, return everything we needto train a given model\n    \"\"\"\n    # use PIL to open the image\n    image = Image.open(self.image_paths[item]) \n    # convert image to RGB, we have single channel images\n    image = image.convert(\"RGB\")\n    # grab correct targets\n    targets = self.targets[item]\n    \n    # resize if needed\n    if self.resize is not None:\n      image = image.resize(\n        (self.resize[1], self.resize[0]), \n        resample=Image.BILINEAR\n      )\n    # convert image to numpy array\n    image = np.array(image)\n    \n    # if we have albumentation augmentations\n    # add them to the image\n    if self.augmentations is not None:\n      augmented = self.augmentations(image=image)\n      image = augmented[\"image\"]\n      \n#       if np.random.uniform(0., 1., size=1)[0] > 0.5:\n#         #print(img.sum(), img.shape)\n#         with torch.no_grad():\n#             cmix_ix = np.random.choice(self.image_paths.shape[0], size=1)[0]\n#             cmix_img  = get_img(self.image_paths[cmix_ix])\n#             cmix_img = self.augmentations(image=cmix_img)['image']\n\n#             lam = np.clip(np.random.beta(1, 1),0.3,0.4)\n#             bbx1, bby1, bbx2, bby2 = rand_bbox((512, 512), lam)\n\n#             image[:, bbx1:bbx2, bby1:bby2] = cmix_img[:, bbx1:bbx2, bby1:bby2]\n\n#             rate = 1 - ((bbx2 - bbx1) * (bby2 - bby1) \/ 512 * 512)\n#             targets = rate*targets + (1.-rate)*self.targets[cmix_ix]\n    \n    # pytorch expects CHW instead of HWC\n    image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n    \n    # return tensors of image and targets\n    # take a look at the types!\n    # for regression tasks, \n    # dtype of targets will change to torch.float\n    return {\n      \"image\": torch.tensor(image, dtype=torch.float),\n      \"targets\": torch.tensor(targets, dtype=torch.long),\n    }\n\ndef get_scheduler(optimizer, scheduler):\n    if scheduler=='ReduceLROnPlateau':\n        scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=4, verbose=True, eps=1e-6)\n    elif scheduler=='CosineAnnealingLR':\n        scheduler = CosineAnnealingLR(optimizer, T_max=10, eta_min=1e-6, last_epoch=-1)\n    elif scheduler=='CosineAnnealingWarmRestarts':\n        scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=1, eta_min=1e-6, last_epoch=-1)\n    return scheduler\n\ndef train_model(data_loader, model, optimizer, scheduler, device):\n  \"\"\"\n  This function does training for one epoch\n  :param data_loader: this is the pytorch dataloader\n  :param model: pytorch model\n  :param optimizer: optimizer, for e.g. adam, sgd, etc\n  :param device: cuda\/cpu\n  \"\"\"\n  # put the model in train mode\n  model.train()\n  # go over every batch of data in data loader\n  for data in data_loader:\n    # remember, we have image and targets\n    # in our dataset class\n    inputs = data[\"image\"]\n    targets = data[\"targets\"]\n    \n    # move inputs\/targets to cuda\/cpu device\n    inputs = inputs.to(device, dtype=torch.float)\n    targets = targets.to(device, dtype=torch.long)\n    \n    # zero grad the optimizer\n    optimizer.zero_grad()\n    #do the forward step of model\n    outputs = model(inputs)\n    \n    criterion = nn.CrossEntropyLoss().to(device)\n    outputs = model(inputs)\n    loss = criterion(outputs, targets)\n\n    # backward step the loss\n    loss.backward()\n    # step optimizer\n    optimizer.step()\n    # if you have a scheduler, you either need to\n    # step it here or you have to step it after\n    # the epoch. here, we are not using any learning\n    # rate scheduler\n  scheduler.step()\n    \ndef evaluate_model(data_loader, model, device):\n  \"\"\"\n  This function does evaluation for one epoch\n  :param data_loader: this is the pytorch dataloader\n  :param model: pytorch model\n  :param device: cuda\/cpu\n  \"\"\"\n  # put model in evaluation mode\n  model.eval()\n  \n  # init lists to store targets and outputs\n  final_targets = []\n  final_outputs = []\n  \n  # we use no_grad context\n  with torch.no_grad():\n    for data in data_loader:\n      inputs = data[\"image\"]\n      targets = data[\"targets\"]\n      inputs = inputs.to(device, dtype=torch.float)\n      targets = targets.to(device, dtype=torch.float)\n      \n      # do the forward step to generate prediction\n      output = model(inputs)\n    \n      # convert targets and outputs to lists\n      targets = targets.detach().cpu().numpy().tolist()\n      output = output.detach().cpu().numpy().tolist()\n      \n      # extend the original list\n      final_targets.extend(targets)\n      final_outputs.extend(output)\n      \n  # return final output and final targets\n  return final_outputs, final_targets\n\ndef get_model(pretrained = True):\n    model = ResAttention()\n    \n#     model.last_linear = nn.Sequential(\n#         nn.BatchNorm1d(2048),\n#         nn.Dropout(p=0.25),\n#         nn.Linear(in_features=204800, out_features=2048),\n#         nn.ReLU(),\n#         nn.BatchNorm1d(2048, eps=1e-05, momentum=0.1),\n#         nn.Dropout(p=0.5),\n#         nn.Linear(in_features=2048, out_features=5), # out features \n#     )\n    return model\n\ndef save_checkpoint(model, optimizer, path):\n    if not os.path.exists(os.path.dirname(path)):\n        print(\"Creating directories on path: `{}`\".format(path))\n        os.makedirs(os.path.dirname(path))\n\n    torch.save({\n        \"model_state_dict\": model.state_dict(),\n        \"optimizer_state_dict\": optimizer.state_dict(),\n    }, path)\n\n\ndef load_checkpoint(model, path):\n    checkpoint = torch.load(path)\n\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n\n    optimizer = torch.optim.Adam(model.parameters())\n    optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n\n    return model, optimizer\n\n\ndef save_model(model, path):\n  if not os.path.exists(os.path.dirname(path)):\n      print(\"Creating directories on path: `{}`\".format(path))\n      os.makedirs(os.path.dirname(path))\n\n  torch.save({\n      \"model_state_dict\": model.state_dict(),\n  }, path)\n\n\ndef load_model(moodel, path):\n  restore_dict = torch.load(path)\n\n  model.load_state_dict(restore_dict[\"model_state_dict\"])\n  model.eval()\n\n  return model\nimg = cv2.imread('..\/input\/cassavapreprocessed\/train_images\/train_images\/1001320321.jpg')\nplt.imshow(img)\ntrain = pd.read_csv('..\/input\/cassavapreprocessed\/merged_data.csv')\ntrain.head()\ntrain['label'].value_counts()\nfor i, (tr_in, val_in) in enumerate(StratifiedKFold(random_state=42, shuffle = True).split(train['image_id'],train['label'])):\n    train[f'fold_{i}'] = 0\n    train.at[tr_in,f'fold_{i}'] = 1\ntrain\ntrain.to_csv('folds_training.csv', index = False)\ntrain = pd.read_csv('.\/folds_training.csv')\nfold = 0\nX_train, y_train, X_test, y_test = (train[train[f'fold_{fold}']==1].loc[:,'image_id'], \n                                    train[train[f'fold_{fold}']==1].loc[:,'label'],\n                                    train[train[f'fold_{fold}']==0].loc[:,'image_id'],\n                                    train[train[f'fold_{fold}']==0].loc[:,'label'])\nX_train = X_train.apply(lambda x: '..\/input\/cassavapreprocessed\/train_images\/train_images\/'+x)\nX_test = X_test.apply(lambda x: '..\/input\/cassavapreprocessed\/train_images\/train_images\/'+x)\naug = Compose(\n    [\n        RandomResizedCrop(448, 448),\n        Transpose(p=0.5),\n        HorizontalFlip(p=0.5),\n        VerticalFlip(p=0.5),\n        HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n        RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),\n        #CenterCrop(512, 512, p=1.0),\n        CoarseDropout(p=0.5),\n        Cutout(p=0.5),\n        Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n    ]\n)\nTrain_dataset = ClassificationDataset(X_train.values, y_train.values, resize = (448,448), \n                                      augmentations=aug)\naug = Compose(\n    [\n        Normalize(\n            mean=[0.485, 0.456, 0.406],\n            std=[0.229, 0.224, 0.225],\n        ),\n    ]\n)\n\n# aug = Compose(\n#     [\n#         RandomResizedCrop(448, 448),\n#         Transpose(p=0.5),\n#         HorizontalFlip(p=0.5),\n#         VerticalFlip(p=0.5),\n#         HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n#         RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),\n#         CenterCrop(448, 448, p=1.0),\n#         CoarseDropout(p=0.5),\n#         Cutout(p=0.5),\n#         Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n#     ]\n# )\nVal_dataset = ClassificationDataset(X_test.values, y_test.values, resize = (448,448),\n                                   augmentations=aug)\ndevice = 'cuda'\nclass CustomResNext(nn.Module):\n    def __init__(self, model_name='resnext50_32x4d', pretrained=False):\n        super().__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained)\n        n_features = self.model.fc.in_features\n        self.model.fc = nn.Linear(n_features, 5)\n\n    def forward(self, x):\n        x = self.model(x)\n        return x\nmodel = get_model(pretrained=False)\nmodel.to(device)\ntrain_loader = torch.utils.data.DataLoader(\n    Train_dataset, batch_size=8, shuffle=True, num_workers=4,pin_memory=True\n)\n\nvalid_loader = torch.utils.data.DataLoader(\n    Val_dataset, batch_size=8, shuffle=False, num_workers=4,pin_memory=True\n)\noptimizer = torch.optim.Adam(model.parameters(), lr=5e-4)\nepochs = 1\ndef multi_class_roc_auc(true, pred_probs_arr, labels):\n    auc_all = []\n    for label_number in labels:\n        true_labels = true.loc[:,label_number].copy()\n        pred_probs = pred_probs_arr.loc[:, label_number].copy()\n        \n       #AUROC and AP (sliding across multiple decision thresholds)\n        fpr, tpr, thresholds = metrics.roc_curve(y_true = true_labels,\n                                         y_score = pred_probs,\n                                         pos_label = 1)\n        auc = metrics.auc(fpr, tpr)\n        auc_all.append(auc)\n    print(f'AUC of each class: {auc_all}')\n    return np.mean(auc_all)\nlabels = [0.0, 1.0, 2.0, 3.0, 4.0]\nscheduler = get_scheduler(optimizer, 'CosineAnnealingWarmRestarts')\nfor epoch in range(epochs):\n    train_model(train_loader, model, optimizer, scheduler, device=device)\n    \n    predictions, valid_targets = evaluate_model(\n      valid_loader, model, device=device\n    )\n    \n    preds = pd.DataFrame(predictions, columns = labels)\n    targets = pd.get_dummies(valid_targets, columns = labels)\n    \n    # roc_auc = metrics.roc_auc_score(valid_targets, predictions.argmax(axis=1))\n    roc_auc = multi_class_roc_auc(targets.copy(), preds.copy(), labels)\n    \n    print(\n      f\"Epoch={epoch}, Valid ROC AUC={roc_auc}\"\n    )\n    save_model(model, '.\/model.h5')\n    save_checkpoint(model, optimizer, f'.\/model_{fold}_{epoch}.pth')","meta":"{'source': 'AI4Code', 'id': 'db3c23a716232b'}"}
{"id":"39214","text":"# 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\n\"\"\"\n<h1>Classification<\/h1>\n\"\"\"\nimport os\nimport pandas as pd\nimport math\nimport matplotlib.pyplot as plt\nimport seaborn as sns #Visualization\nfrom sklearn.linear_model import LinearRegression\ndf_class = pd.read_csv('\/kaggle\/input\/iris\/Iris.csv')\nprint('\\nNumber of rows and columns in the data set: ',df_class.shape)\nprint('')\nprint(df_class.head())\n\"\"\"\nCheck the features will null using heat map\n\"\"\"\nplt.figure(figsize=(12,4))\nsns.heatmap(df_class.isnull(),cbar=False,cmap='coolwarm',yticklabels=False)\nplt.title('Missing value in the dataset')\n\"\"\"\nFind the sum of null values in each feature\/column\n\"\"\"\ndf_class.isnull().sum()\nprint(df_class.info())\ndf_class.nunique()\ndf_class.info()\n# Scaling for Numerical data set\n#from sklearn.preprocessing import StandardScaler\n#sc=StandardScaler()\n#data_numerical.iloc[:,1:] =sc.fit_transform(data_numerical.iloc[:,1:])  \n# Lets verify the dummay variable process\nprint('Columns in original data frame:\\n',df_class.columns.values) #original dataframe column names\nprint('\\nNumber of rows and columns in the dataset:',df_class.shape) #previous dataframe shape\n#print('\\nColumns in data frame after encoding dummy variable:\\n',df_Loan.columns.values) #original dataframe column names\n#print('\\nNumber of rows and columns in the dataset:',df_Loan.shape) #updated data frame shape\n\"\"\"\nDistributing data in **training and testing**\n\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test =train_test_split(df_class.drop(['Species'],axis=1),df_class.Species,test_size=0.30,random_state=0)# chane zero to 20,10\n\"\"\"\nImporting SVM and creating the model\n\"\"\"\nfrom sklearn.svm import SVC\nsvc_model=SVC()\n\"\"\"\n<h1>SUPPORT VECTOR CLASSIFIER<\/h1>\nCreating the **SVM model** and run prediction on testing data\n\"\"\"\nsvc_model.fit(X_train,y_train)\nsvm_pred=svc_model.predict(X_test)\n\n\"\"\"\nImporting **evaluation** libraries\n\"\"\"\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n\"\"\"\n**Confusion matrix** and **Accuracy** score\n\"\"\"\n\ncm=confusion_matrix(y_test,svm_pred)\nprint(cm)\n\nfrom sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test,svm_pred))\nprint(\"SVM  -> \",accuracy_score(y_test,svm_pred)*100)\n\"\"\"\n**Classification Report**\n\"\"\"\nprint(confusion_matrix(y_test,svm_pred))\nprint(classification_report(y_test,svm_pred))\nprint(accuracy_score(y_test, svm_pred))\n\"\"\"\n<h1>Naive Bayes<\/h1>\n\"\"\"\nfrom sklearn import naive_bayes\nNaive = naive_bayes.GaussianNB()\n# fit the training dataset on the NB classifier\nNaive.fit(X_train,y_train)# predict the labels on validation dataset\npredictions_NB= Naive.predict(X_test)# Use accuracy_score function to get the accuracy\nprint(\"Naive Bayes Accuracy Score -> \",accuracy_score(predictions_NB, y_test)*100)\nprint(confusion_matrix(y_test,predictions_NB))\nprint(classification_report(y_test,predictions_NB))\nprint(accuracy_score(y_test,predictions_NB))\n\"\"\"\n<h1>K-nearest Neighbour<h1>\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=3)\nknn.fit(X_train, y_train)\nknn_pred = knn.predict(X_test)\nprint(\"Accuracy:\",accuracy_score(y_test, knn_pred))\nprint(confusion_matrix(y_test,knn_pred))\nprint(classification_report(y_test,knn_pred))\nprint(accuracy_score(y_test,knn_pred))\nprint('erroe')\n\nprint(1-accuracy_score(y_test,knn_pred))\n\"\"\"\nTry KNN model with different number of K and perform evaluation.\n\"\"\"\n\"\"\"\n<h1> Decision Tree <h1>\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\ndtc = DecisionTreeClassifier()\n# Train Decision Tree Classifer\ndtc.fit(X_train,y_train)\n\n#Predict the response for test dataset\ndtc_pred = dtc.predict(X_test)\nprint(confusion_matrix(y_test,dtc_pred))\nprint(classification_report(y_test,dtc_pred))\nprint(accuracy_score(y_test,dtc_pred))\n\"\"\"\n<H1> ENSEMBLE <H1>\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier, VotingClassifier\n\"\"\"\n<h3>Stacking<\/h3>\n\"\"\"\n\"\"\"\n<h2>Voting Classifier<\/h2>\n\"\"\"\nvoting_clf = VotingClassifier(estimators=[('SVC', SVC()), ('DTree', dtc), ('NaiveBayes', Naive),('KNN',knn)], voting='hard')\nvoting_clf.fit(X_train, y_train)\n\n\npreds = voting_clf.predict(X_test)\nprint(confusion_matrix(y_test,preds))\nprint(classification_report(y_test,preds))\nprint(accuracy_score(y_test,preds))\nprint('error')\nprint(1-accuracy_score(y_test,preds))\n\"\"\"\n<h3>Bagging<\/h3>\n\"\"\"\n\"\"\"\n<h2> Random Forest Classifier<\/h2>\n\"\"\"\nrandom_forest = RandomForestClassifier(n_estimators=10, random_state=12)\nrandom_forest.fit(X_train,y_train)\nrf=random_forest.predict(X_test)\nprint(confusion_matrix(y_test,rf))\nprint(classification_report(y_test,rf))\nprint(accuracy_score(y_test,rf))\nprint('error')\nprint(1-accuracy_score(y_test,rf))\nfrom sklearn.model_selection import KFold\n#kf=KFold(n_splits=5,shuffle=True)\nkf=KFold(n_splits=10,shuffle=True)\ndata=df_class.drop(['Species'],axis=1)\nprint(data.head)\nplt.figure(figsize=(12,4))\nsns.heatmap(data.isnull(),cbar=False,cmap='coolwarm',yticklabels=False)\nplt.title('Missing value in the dataset')\nrf_k=RandomForestClassifier(n_estimators=10)\nfrom sklearn.model_selection import cross_val_score\nacc_rf=cross_val_score(rf_k,data,df_class.Species,scoring='accuracy',cv=10)\nprint(acc_rf.mean())\nprint('error')\nprint(1-(acc_rf.mean()))\n\n\narray=[10,20,40,60,80,100]\nfor i in range(0,6):\n  random_forest = RandomForestClassifier(n_estimators=array[i])\n  random_forest.fit(X_train,y_train)\n  rf_predict=random_forest.predict(X_test)\n  print('Accuracy of Rain Forest when estimate is ',array[i], ' : ',accuracy_score(y_test,rf_predict))\n\"\"\"\n<h3> Boosting<\/h3>\n\"\"\"\nk_folds = KFold(n_splits=20,shuffle=True)\nfrom sklearn.ensemble import AdaBoostClassifier\nada_boost = AdaBoostClassifier(n_estimators=10, random_state=12)\nresults = cross_val_score(ada_boost, X_train, y_train, cv=k_folds)\nprint(results.mean()*100)\nada_boost.fit(X_train,y_train)\nada_predict=ada_boost.predict(X_test)\nprint(confusion_matrix(y_test,ada_predict))\nprint(classification_report(y_test,ada_predict))\nprint(accuracy_score(y_test,ada_predict))\nprint('error')\nprint(1-accuracy_score(y_test,ada_predict))\narray=[10,20,40,60,80,100]\nfor i in range(0,6):\n  ada_boost = AdaBoostClassifier(n_estimators=array[i], random_state=12)\n  ada_boost.fit(X_train,y_train)\n  ada_predict=ada_boost.predict(X_test)\n  print('Accuracy when estimate is ',array[i], ' : ',accuracy_score(y_test,ada_predict))","meta":"{'source': 'AI4Code', 'id': '483b58a4b1bb28'}"}
{"id":"1194","text":"\"\"\"\n# 1. Introduction\n\"\"\"\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nstore = pd.read_csv('\/kaggle\/input\/google-play-store-apps\/googleplaystore.csv')\nstore.head()\nstore.info()\n\"\"\"\n## 2. Data Cleaning\n\"\"\"\n\"\"\"\n### 2.1. Drop Unwanted Columns\n\"\"\"\nstore.drop(['Genres', 'Last Updated', 'Current Ver', 'Android Ver'], inplace=True, axis=1)\nstore.head()\n\"\"\"\n### 2.2. Drop Duplicates\n\"\"\"\nstore[store.duplicated(keep=False)].sort_values('App')\nstore.drop_duplicates(inplace=True)\n\"\"\"\n### 2.2. Drop Missing Rows\n\"\"\"\nstore.isna().sum()\nstore[store.Type.isna()]\nprint(store.shape)\nstore.dropna(inplace=True)\nprint(store.shape)\n# The amount of loss after cleaning.\n(1 - 8890 \/ 10841) * 100\n\"\"\"\n## 3. Data Tidying\n\"\"\"\n\"\"\"\n### 3.1. Determine Categorical Columns\n\"\"\"\nstore.Category.value_counts()\n\"\"\"\nLet's clean up \"Content Rating\" column.\n\"\"\"\nstore['Content Rating'].value_counts()\nstore.drop(store.loc[store['Content Rating'] == 'Unrated'].index, inplace=True)\nstore.loc[store['Content Rating'] == 'Adults only 18+', 'Content Rating'] = 'Mature 17+'\nstore['Content Rating'].value_counts()\nstore['Type'].value_counts()\nstore['Category'] = store['Category'].astype('category')\nstore['Content Rating'] = store['Content Rating'].astype('category')\nstore['Type'] = store['Type'].astype('category')\n\"\"\"\n### 3.2. Determine and Create Numerical Columns\n\"\"\"\nstore.sort_values('Reviews', ascending=False).head()\n\"\"\"\nLets consider the Installs column\n\"\"\"\nstore['Installs'].unique()\nstore['Installs'] = store['Installs'].str.replace('+','',regex=True).replace(',','',regex=True)\nstore['Installs'].unique()\nstore['Installs'] = store.Installs.astype(int)\n\"\"\"\nLet's evaluate Reviews column\n\"\"\"\nstore['Reviews'].unique()\nstore['Reviews'].str.isnumeric().sum() == store['Reviews'].count()\nstore['Rating'].unique()\n\"\"\"\nPrice column needs manipulation.\n\"\"\"\nstore['Price'].unique()\nstore['Price'].str.replace('$','', regex=True).unique()\nstore['Price'] = store['Price'].str.replace('$','', regex=True)\nstore['Size'].unique()\nsize_replace= {\n    '.':'',\n    'k':'000',\n    'M':'000000'\n              }\n\nfor key, value in size_replace.items():\n    store['Size'] = store['Size'].str.replace(key,value, regex=True)\n    \nstore['Size'].head()\nstore[store['Size'] == 'Varies with device'].shape\n\"\"\"\nIf the rows which has 'Size' column with \"varies with device\" value have dropped, we will lose %16.51 of our data.\n\"\"\"\nstore[store['Size'] == 'Varies with device'].shape[0] \/ store.shape[0] * 100\nstore[['Rating', 'Reviews', 'Installs', 'Price']] = store[['Rating', 'Reviews', 'Installs', 'Price']].apply(pd.to_numeric)\nstore.info()\n\"\"\"\n## 4. Exploratory Data Analysis \n\"\"\"\nstore.head()\nstore.describe(include=[np.number]).T\nstore.describe(include=[np.object, pd.Categorical]).T\n\"\"\"\n### 4.1. Categorical Analysis\n\"\"\"\nplt.figure(figsize=(16,6))\nsns.countplot(data=store, x='Category', order = store['Category'].value_counts().index)\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(16,6))\nsns.barplot(data=store, x='Category', y='Rating', estimator=np.median)\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(16,6))\nsns.barplot(data=store, x='Category', y='Price')\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(16,6))\nsns.barplot(data=store, x='Category', y='Installs')\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(12,6))\nsns.countplot(data=store, x='Type')\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(12,6))\nsns.countplot(data=store, x='Content Rating')\nplt.xticks(rotation=90)\nplt.show()\n\"\"\"\n### 4.2. Numerical Analysis\n\"\"\"\nfig, axes = plt.subplots(1, 3, figsize=(15,6))\nsns.histplot(data=store, x='Rating', ax=axes[0])\nsns.boxplot(data=store, x='Rating', ax=axes[1])\nsns.violinplot(data=store, x='Rating', ax=axes[2])\nplt.show()\nfig, axes = plt.subplots(1, 3, figsize=(15,6))\nsns.histplot(data=store, x='Reviews', ax=axes[0])\nsns.boxplot(data=store, x='Reviews', ax=axes[1])\nsns.violinplot(data=store, x='Reviews', ax=axes[2]);\n\"\"\"\nWe couldn't see anything  at histplot? This must be caused by outliers.\n\"\"\"\nreviews_filtered = store[store['Reviews'] < 200000]\nfig, axes = plt.subplots(1, 3, figsize=(15,6))\nsns.histplot(data=reviews_filtered, x='Reviews', ax=axes[0])\nsns.boxplot(data=reviews_filtered, x='Reviews', ax=axes[1])\nsns.violinplot(data=reviews_filtered, x='Reviews', ax=axes[2]);\nfig, axes = plt.subplots(1, 3, figsize=(15,6))\nsns.histplot(data=store, x='Price', ax=axes[0])\nsns.boxplot(data=store, x='Price', ax=axes[1])\nsns.violinplot(data=store, x='Price', ax=axes[2]);\nstore.Price.nlargest(50)\nprice_filtered = store[store['Price'] < 50]\nfig, axes = plt.subplots(1, 3, figsize=(15,6))\nsns.histplot(data=price_filtered, x='Price', ax=axes[0])\nsns.boxplot(data=price_filtered, x='Price', ax=axes[1])\nsns.violinplot(data=price_filtered, x='Price', ax=axes[2]);","meta":"{'source': 'AI4Code', 'id': '02424dfb4579c5'}"}
{"id":"133287","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom keras.models import Sequential \nfrom keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense ,LeakyReLU\nfrom keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom keras.applications import InceptionV3\n\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n\"\"\"\n\n\n\n**Firt of all  define test path and train path **\n\"\"\"\ntrain_path = \"\/kaggle\/input\/skin-cancer9-classesisic\/skin cancer isic the international skin imaging collaboration\/Skin cancer ISIC The International Skin Imaging Collaboration\/Train\/\"\ntest_path = \"\/kaggle\/input\/skin-cancer9-classesisic\/skin cancer isic the international skin imaging collaboration\/Skin cancer ISIC The International Skin Imaging Collaboration\/Test\/\"\n\"\"\"\n**Testing paths and images **\n\n\n\"\"\"\nimg = load_img(train_path + \"nevus\/ISIC_0000041.jpg\")\nplt.imshow(img)\nplt.axis(\"off\")\nplt.show()\n\n\"\"\"\n**convert images to array** \n\n\n**show to shape** \n\"\"\"\nx = img_to_array(img)\nprint(x.shape)\n\"\"\"\n\n**Using the glob function, we learn how many different folders there are in the dataset.**\n\"\"\"\n\nclassName = glob(train_path + '\/*' )\nnumberOfClass = len(className)\nprint(\"NumberOfClass: \",numberOfClass)\n\"\"\"\n**we are building the cnn structure**\n\"\"\"\n\n\nmodel = Sequential()\nmodel.add(InceptionV3(include_top=False, input_shape=(299,299,3)))\nmodel.add(Flatten())\nmodel.add(Dense(32))\nmodel.add(LeakyReLU(0.001))\nmodel.add(Dense(16))\nmodel.add(LeakyReLU(0.001))\nmodel.add(Dense(numberOfClass, activation='softmax'))\nmodel.layers[0].trainable = False\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])\nmodel.summary()\n\"\"\"\n**define loss and optimizer method ...**\n\"\"\"\nmodel.compile(loss = \"categorical_crossentropy\",\n              optimizer = \"rmsprop\",\n              metrics = [\"accuracy\"])\nbatch_size = 250\n\"\"\"\n**We get various images by zooming and rotating and flipping **\n\"\"\"\ntrain_datagen = ImageDataGenerator(rescale= 1.\/255,\n                   shear_range = 0.3,\n                   horizontal_flip=True,\n                   zoom_range = 0.3)\n\ntest_datagen = ImageDataGenerator(rescale= 1.\/255)\n\ntrain_generator = train_datagen.flow_from_directory(\n        train_path, \n        target_size=(299,299),\n        batch_size = batch_size,\n        color_mode= \"rgb\",\n        class_mode= 'categorical')\n\ntest_generator = test_datagen.flow_from_directory(\n        test_path, \n        target_size=(299,299),\n        batch_size = batch_size,\n        color_mode= \"rgb\",\n        class_mode= 'categorical')\n\nhist = model.fit_generator(\n        generator = train_generator,\n        steps_per_epoch = 5000,\n        epochs=1,\n        validation_data = test_generator,\n        validation_steps = 250)\n\"\"\"\n**if you want to save the train weights like me, you must push to internet button in setting on right vertical menu ** \n\"\"\"\nmodel.save_weights(\"weights.h5\")\n\"\"\"\naccuracy= 0,20 this is mean that dataset is not corrrect separetaly pehh ;)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f526a665f2e9b3'}"}
{"id":"93933","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nimport spacy\nimport gensim\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nimport math\nimport time\nimport plotly.express as px\nimport sys\nfrom pandasql import sqldf\npysqldf = lambda q: sqldf(q, globals())\nimport os\nRS = 123\ndata = pd.read_csv(\"..\/input\/bible\/t_asv.csv\")\n\"\"\"\n## To-do\n1. Cluster the bible according to the book\n2. Cluster the bible using K-Means (Doc2Vec of verses)\n3. Sentiment of each bible chapter\n4. Text completion using Transformers package\n\"\"\"\ndocuments = [TaggedDocument(doc, [i]) for i, doc in enumerate(data['t'])]\nmodel = Doc2Vec(documents, vector_size=10, workers=4)\nvector = [model.infer_vector([i]) for i in list(data['t'])]\nvector = np.array(vector)\n\"\"\"\n### Cluster the Bible according to the book\n\"\"\"\nperplex = math.sqrt(vector.shape[0])\nRS = 123\ntime_start = time.time()\ntsne = TSNE(perplexity = perplex, learning_rate = 100, n_iter = 700, random_state=RS).fit_transform(vector)\nprint('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start))\ncolumns = list(data.columns)\ncolumns.extend(['comp1', 'comp2'])\ndata_filter = np.concatenate((data.to_numpy(),tsne), axis = 1)\ndata_filter = pd.DataFrame(data_filter, columns = columns)\ndata_filter.head(2)\nfig = px.scatter(data_filter, x=\"comp1\", y=\"comp2\", hover_data=[\"t\"], color=\"b\")\nfig.show()\n\"\"\"\nAccording to this, bible apparently has only one theme\n\"\"\"\n\"\"\"\n### Cluster the bible using ML algorithms\n\"\"\"\nsse = {}\nfor k in range(1, 21):\n    kmeans = KMeans(n_clusters=k, max_iter=1000).fit(vector)\n    clusters = kmeans.labels_\n    #print(data[\"clusters\"])\n    sse[k] = kmeans.inertia_ # Inertia: Sum of distances of samples to their closest cluster center\nplt.figure()\nplt.plot(list(sse.keys()), list(sse.values()))\nplt.xlabel(\"Number of cluster\")\nplt.ylabel(\"SSE\")\nplt.show()\n\n\"\"\"\nCannot form any significant cluster because no elbow arises. Hence we go for GaussianMixture model\n\"\"\"\nn_components = np.arange(1, 51)\nmodels = [GaussianMixture(n, covariance_type='full', random_state=0).fit(vector) for n in n_components]\nplt.plot(n_components, [m.bic(vector) for m in models], label='BIC')\nplt.plot(n_components, [m.aic(vector) for m in models], label='AIC')\nplt.legend(loc='best')\nplt.xlabel('n_components');\n\"\"\"\nWe see a minima at cluster = 20 and hence we divide the data in 20 clusters\n\"\"\"\ngmm = GaussianMixture(n_components=20)\ngmm.fit(vector)\nlabels = gmm.predict(vector)\nperplex = math.sqrt(vector.shape[0])\nRS = 123\ntime_start = time.time()\ntsne = TSNE(perplexity = perplex, learning_rate = 100, n_iter = 700, random_state=RS).fit_transform(vector)\nprint('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start))\ncolumns = list(data.columns)\ncolumns.extend(['comp1', 'comp2', 'labels'])\ndata_filter = np.concatenate((data.to_numpy(),tsne, labels.reshape(31103,1)), axis = 1)\ndata_filter = pd.DataFrame(data_filter, columns = columns)\ndata_filter.head(2)\nfig = px.scatter(data_filter, x=\"comp1\", y=\"comp2\", hover_data=[\"t\"], color=\"labels\")\nfig.show()\n\"\"\"\nThere are small, overlapping clusters of themes in bible\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ac672f11a96750'}"}
{"id":"84105","text":"\"\"\"\nStroke \u2014 an acute violation of the blood supply to the brain, characterized by a sudden (within a few minutes, hours) the appearance of focal and \/ or general cerebral neurological symptoms that persist for more than 24 hours or lead to the death of the patient in a shorter period of time due to cerebrovascular pathology.\n\"\"\"\n\"\"\"\n![%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5.png](attachment:%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5.png)\n\"\"\"\n\"\"\"\nLet's import the main libraries and see what kind of data we have.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline \ndf=pd.read_csv('..\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv')\ndf.head(5)\ndf.info()\ndf.isna().sum()\ndf.describe()\n\"\"\"\nIn total, we have 9 variables and 1 target. The fact of a stroke is affected by the following parameters:\n1) Gender\n2) Average glucose level\n3) BMI\n4) Smoking\n5) Type of work\n6) Was the person married (amazing, isn't it?)\n7) Where does the person live\n8) Does a person suffer from hypertension\n9) Does the patient have a history of heart disease.\nLet's do a simple visual analysis of our data.\n\"\"\"\nsns.histplot(df['Residence_type'])\nsns.histplot(df['work_type'])\nsns.histplot(df['ever_married'])\nsns.histplot(df['gender'])\nsns.histplot(df['stroke'])\nprint(df['stroke'].value_counts())\nsns.distplot(df['age'], color='b', kde=True,bins=70)\nsns.histplot(df, x=\"heart_disease\", bins=6)\nprint(print(df['heart_disease'].value_counts()))\nsns.histplot(df, x=\"bmi\", color=\"b\",kde=True)\n\nsns.histplot(df, x=\"avg_glucose_level\", color=\"b\",kde=True)\n\nsns.histplot(df, x=\"hypertension\", color=\"b\")\nsns.countplot(df['work_type'],hue=df['stroke'])\nsns.countplot(df['Residence_type'],hue=df['stroke'])\nlabels=['no stroke','stroke']\ncolors = [\"cyan\",\"red\"]\nplt.pie(df['stroke'].value_counts(),labels=labels,colors=colors,\n        autopct='%1.2f%%', shadow=True, startangle=140) \nplt.show()\n\nplt.figure(figsize=(15,15))\nsns.heatmap(df.corr(),annot=True);\nsns.scatterplot(data=df, x=\"bmi\", y=\"avg_glucose_level\")\nplt.show()\nsns.scatterplot(data=df, x=\"age\", y=\"avg_glucose_level\")\nplt.show()\nsns.scatterplot(data=df, x=\"age\", y=\"bmi\")\nplt.show()\n\"\"\"\nWe were able to understand the distribution of our data. We also have an imbalance in observations: very few people have heart problems, hypertension, and in principle, few people with a stroke in our data. We also found that there is a relationship between age and average glucose levels. And also between age and bmi. Let's also take a closer look at who is more susceptible to stroke.\n\"\"\"\nsummary_df = df[['work_type','gender','Residence_type','smoking_status','stroke']]\nsummary = pd.concat([pd.crosstab(cat_df[x], cat_df.stroke) for x in cat_df.columns[:-1]], keys=cat_df.columns[:-1])\nsummary\nfor i in df:\n    if df[i].dtype == 'object':\n        print(i,df[i].unique())\n\"\"\"\nI decided to easily and simply fill in the missing values on mean. And also convert categorical data using Label Encoder. And also get rid of the imbalance with ADASYN. The following classification algorithms were selected: XGBClassifier, LGBMClassifier, and RandomForestClassifier\n\"\"\"\nfrom sklearn.impute import SimpleImputer\nimport numpy as np\nfor i in df:\n    if df[i].isna().sum()>0:\n        imr=SimpleImputer(missing_values=np.nan,strategy='mean')\n        imr=imr.fit(df[[i]])\n        imputed_data=imr.transform(df[[i]])\n        df[i]=imputed_data\nfrom sklearn.preprocessing import LabelEncoder\nfor c in df.columns:\n    le = LabelEncoder()\n    if df.dtypes[c] == object:\n        le.fit(df[c].astype(str))\n        df[c] = le.transform(df[c].astype(str))\ny=df['stroke']\nX=df.drop(['stroke','id'],axis=1)\nprint(y.value_counts())\nfrom sklearn import preprocessing\nnorm = preprocessing.StandardScaler()\nndf=norm.fit_transform(X)\nX = pd.DataFrame(ndf, index=X.index, columns=X.columns)\nX.head(10)\nfrom imblearn.over_sampling import ADASYN \nX_resampled, y_resampled = ADASYN().fit_resample(X, y)\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test =train_test_split(X_resampled,y_resampled,train_size=0.7, random_state=42)\nfrom sklearn.model_selection import RandomizedSearchCV\nimport lightgbm as lgb\nparams = {\n    'learning_rate': [0.05,0.01,0.0001],\n    'num_leaves': [90,140,200],\n    'boosting_type' : ['gbdt'],\n    'objective' : ['binary'],\n    'max_depth' : [3,4,5,6,7,8],\n    'random_state' : [42], \n    'colsample_bytree' : [0.5,0.6,0.7,0.8,1.0],\n    'subsample' : [0.5,0.6,0.7,0.8,1.0],\n    'min_split_gain' : [0.01],\n    'min_data_in_leaf':[10],\n    'metric':['auc']\n    }\nclf = lgb.LGBMClassifier()\nRSCV = RandomizedSearchCV(clf,params,verbose=3,cv=10,n_jobs = -1,n_iter=10)\nRSCV.fit(X_train,y_train)\ny_pred=RSCV.predict(X_test)\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, y_pred))\nfrom sklearn.metrics import roc_auc_score\nroc_auc_score(y_test,y_pred)\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nplot_confusion_matrix(RSCV,X_test,y_test)\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\nparam_grid = { \n    'n_estimators': [100, 200, 500],\n    'max_features': ['auto', 'sqrt', 'log2'],\n    'max_depth' : [4,5,6,7,8],\n    'criterion' :['gini', 'entropy']\n}\nrfc=RandomForestClassifier()\nCV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv=3,n_jobs=-1,verbose=True)\nCV_rfc.fit(X_train, y_train)\ny_predict = CV_rfc.predict(X_test)\n\nprint(classification_report(y_test, y_predict))\n\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nplot_confusion_matrix(CV_rfc,X_test,y_test)\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import StratifiedKFold\nxgb = XGBClassifier(learning_rate=0.05,n_estimators=10000,seed=2019,reg_alpha=5,eval_metric='auc',tree_method='hist',\n                    objective='binary:logistic',\n                    silent=True, nthread=1)\nparams = {\n        'min_child_weight': [1, 5, 10],\n        'gamma': [0.5, 1, 1.5, 2, 5],\n        'subsample': [0.6, 0.8, 1.0],\n        'colsample_bytree': [0.6, 0.8, 1.0],\n        'max_depth': [3, 4, 5]\n        }\nfolds = 3\nparam_comb = 5\n\nskf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001)\n\nrandom_search = RandomizedSearchCV(xgb, param_distributions=params, n_iter=param_comb, scoring='roc_auc', n_jobs=4, cv=skf.split(X_train,y_train), verbose=3, random_state=1001 )\nrandom_search.fit(X_train, y_train)\n\nfrom sklearn.ensemble import RandomForestClassifier\n\ny_predict = random_search.predict(X_test)\n\nprint(classification_report(y_test, y_predict))\n\nplot_confusion_matrix(random_search,X_test,y_test)\n\"\"\"\nFrom the work done, we can conclude that the Random Forest Classifier algorithm did the worst. XGBClassifier and LGBMClassifier are approximately equal. I would prefer LGBMClassifier, because it is worse at detecting sick people.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9a51a755f752d6'}"}
{"id":"11131","text":"\"\"\"\n### Summary\nThe app allows you to upload a submission and analyze how well you would have done in previous years\u2019 competitions. \n* The Public leaderboard is usually full of leaky submissions making it hard to determine the quality of a submission. The Public leaderboard is included here for comparison. It is updated everytime the app is run.\n* The Average leaderboard shows the average score of the nth place teams. For example, if your submission places 10th on the Average leaderboard then your score is slightly better the average of the 10th place teams in the previous competitions and slightly worse than the average of the 9th place teams in the previous competitions.\n* The 2018 - 2019 leaderboards are exact copys from previous competitions.You can use them to view where your submission would have placed in those competitions.\n\n\n### Run on the App on Kaggle\nFork and edit this notebook. Run all cells of the notebook and view the app in a separate tab using the url generated by [ngrok](https:\/\/ngrok.com\/). \n\n**Important: The app needs a backend to run. You must fork and edit the notebook. You won't be able to view the app from a static Kaggle notebook.**\n\n### Local Installation\nIf you prefer to run locally (it should be faster) follow the following instructions: \n1. **Run the Wave Server:** Follow the instructions [here](https:\/\/h2oai.github.io\/wave\/docs\/installation) to download and run the latest Wave Server, a requirement for apps. Note: If you have a version of Wave older than or equal to 0.12.0, you will need to reinstall Wave with a newer version. \n\n2. **Download the App:** Download the [app code](https:\/\/www.kaggle.com\/mmotoki\/womens-leaderboard-analyzer-app-2021) from kaggle. Open a terminal in the `womens_leaderboard` directory and create a `tmp` folder for uploded files.\n```bash\n$ mkdir tmp\n```\n\n3. **Setup Your Python Environment**:\n```bash\n$ make setup\n$ source venv\/bin\/activate\n```\n4. **Run the App:**\n```bash\n$ wave run leaderboard.app\n```\n5. **View the App:** Point your favorite web browser to [localhost:10101](http:\/\/localhost:10101)\n\n\n### Acknowledgements \n* Thank you to [nagiss](https:\/\/www.kaggle.com\/nagiss). This app was heavily influenced by nagiss's notebook: [Santa2020 Stable Rating Estimation & LeaderBoards](https:\/\/www.kaggle.com\/nagiss\/santa2020-stable-rating-estimation-leaderboards). Much of the code for formatting tables comes from that notebook. \n* Thank you to [KS](https:\/\/www.kaggle.com\/ks2019) who also influenced this app with his [discussion](https:\/\/www.kaggle.com\/c\/ncaam-march-mania-2021\/discussion\/222390) on making sense of the public leaderboard. \n* Thank you to [beluga](https:\/\/www.kaggle.com\/gaborfodor) who provided feedback and reviewed the app--you can thank him for the competition points idea.\n\n\"\"\"\n# Downloading and installing wave. We'll run it in following cell.\n!wget https:\/\/github.com\/h2oai\/wave\/releases\/download\/v0.12.1\/wave-0.12.1-linux-amd64.tar.gz\n!tar -zxvf wave-0.12.1-linux-amd64.tar.gz\n!chmod +x .\/wave-0.12.1-linux-amd64\/waved\n!pip install pyngrok -q #ngrok will be needed for adress tunneling.\nfrom pyngrok import ngrok\nfrom subprocess import Popen, run\nimport sys\nimport os\nimport time\nfrom IPython.core.display import display, HTML\n\nos.chdir('wave-0.12.1-linux-amd64')\nwaved_process = Popen(\".\/waved\", shell=True) # We run .\/waved at backend so that our app will be able to run on the browser.\nos.chdir('..')\n# Setting up the working directory so that the app will be run based on them.\n!mkdir -p tmp\n!mkdir -p data\n!mkdir -p leaderboard\n!cp -R ..\/input\/womens-leaderboard-analyzer-app-2021\/womens_leaderboard\/data\/. data\n!cp -R ..\/input\/womens-leaderboard-analyzer-app-2021\/womens_leaderboard\/leaderboard\/. leaderboard\n!pip install h2o-wave==0.12.1\ntry:\n    app_process.kill()\nexcept:\n    pass\napp_process = Popen([\"wave\", \"run\", \"leaderboard.app\"])\nurl = ngrok.connect(addr=10101).public_url\nprint(f\"Successfully established ngrok tunnel, visit the app at {url}\")\nprint(\"The app needs a backend to run. If you aren't already doing so, you must fork and edit the notebook. You won't be able to view the app from a static Kaggle notebook.\")","meta":"{'source': 'AI4Code', 'id': '14728b5a1189bc'}"}
{"id":"29812","text":"\"\"\"\nIn my [previous notebook](https:\/\/www.kaggle.com\/arunima24\/exploratory-data-analysis-on-titanic-dataset), I've done an EDA and Feature Engineering on the titanic dataset to understand the data pattern and relationship. Here, I would be continuing on the same pattern to use the different ensemble techniques to predict the accuracy.\n\"\"\"\n\"\"\"\n# Importing Libraries\n\"\"\"\nimport numpy as np \nfrom numpy import hstack\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport re\n\nfrom sklearn.model_selection import train_test_split,RandomizedSearchCV\nfrom sklearn.metrics import classification_report, accuracy_score\n\nfrom sklearn.impute import KNNImputer\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,VotingClassifier,AdaBoostClassifier\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\n\nplt.style.use('fivethirtyeight')\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\n\"\"\"\n# Reading Dataset\n\"\"\"\ntrain_data = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntest_data = pd.read_csv(\"..\/input\/titanic\/test.csv\")\ntrain_data.head(20)\n\"\"\"\n> **Get information about the data like count, mean, standard deviation etc.**\n\"\"\"\ntrain_data.describe()\ntrain_data.info()\n\"\"\"\n> **Creating an array using the columns which would be used for the various graphs for EDA**\n\"\"\"\nfeatures = []\nfor i in train_data.columns:\n    if i !='Survived':\n        features.append(i)\n\nfeatures\n\"\"\"\n> **Getting the information of the number of records per columns with null\/NaN value**\n\"\"\"\ntrain_data.isnull().sum()\n\"\"\"\n> **Checking the impact of each feature on target variable**\n\"\"\"\nfor i in features:\n    print(\"\\n\\n\"+i)\n    print (train_data[[i, \"Survived\"]].groupby([i], as_index=False).mean())\n\"\"\"\n# FEATURE ENGINEERING\nWe see from the above table that some columns have a large amount of similar data or contain NaN values which would be difficult to be used in a model if no changes are made to them. For example, \n\n**PassengerID**: The ID has no impact on survival, so we might ignore the column altogether.\n\n**Cabin**: The Cabin can be grouped according to the classes, and we can try to derive a pattern from it.\n\n**Fare**: There are 200+ different fares that the passengers have paid. Instead of analysing them individually for a prediction, we can use them as a range.\n\n**Ticket**: The Ticket has no impact on survival, so we might ignore the column altogether.\n\n**Age**: Again, like Fare, we need to treat them as age group instead of considering individual ages \n\n**Name**: The names are not important, but the salutation is. We can use that in addition to the Sex and Age feature for prediction.\n\"\"\"\ntrain_data.drop(['PassengerId','Ticket'],axis=1,inplace=True)\n\"\"\"\n**NAME**\n\nLet's look at Name feature. My idea is to get the salutation from each name and store it as a new column 'Title' in the dataframe.\n\"\"\"\n\ndef get_title(name):\n    title_search = re.search(' ([A-Za-z]+)\\.', name)\n\n    if title_search:\n        return title_search.group(1)\n    return \"\"\n\n\ntrain_data['Title'] = train_data['Name'].apply(get_title)\ntrain_data.drop('Name',axis=1,inplace=True)\ntrain_data['Title'].unique()\n\"\"\"\nLet's check the number of records for each of these titles.\n\"\"\"\ntrain_data.groupby(['Title']).size()\n\"\"\"\nWe can replace some of the titles (such as Ms -> Miss) and the group the ones which appear lesser compared to others in a new group. We'll then check the mean number of records of each title's relation to the output.\n\"\"\"\ntrain_data['Title'] = train_data['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Others')\n\ntrain_data['Title'] = train_data['Title'].replace('Mlle', 'Miss')\ntrain_data['Title'] = train_data['Title'].replace('Ms', 'Miss')\ntrain_data['Title'] = train_data['Title'].replace('Mme', 'Mrs')\n\ntrain_data[['Title', 'Survived']].groupby(['Title'], as_index=False).mean()\n\"\"\"\n**CABIN**\n\nNext, I'm starting with the Cabin feature. For this, I'll assign -1 to NaN\/null vales (and deal with them later) and group the others using the first letter of the values and create a new column 'Cabin_Group'.\n\"\"\"\ndef cabin_group(cabin):\n    if type(cabin) == str:\n        letter =  cabin[0]\n    else:\n        letter = -1\n    \n    if type(letter) == str and ord(letter) <= 70:\n        return letter\n    elif letter == -1:\n        return '-1'\n    else:\n        return 'OtherCabin'\n    \n    \ntrain_data['Cabin_Group'] = train_data['Cabin'].apply(cabin_group)\ntrain_data.drop('Cabin',axis=1,inplace=True)\ntrain_data.groupby(['Cabin_Group']).size()\n\"\"\"\nChecking the relation between this new feature with target.\n\"\"\"\ntrain_data[['Cabin_Group', 'Survived']].groupby(['Cabin_Group'], as_index=False).mean()\n\"\"\"\n**FARE**\n\nI'm dividing the fare to 5 buckets or ranges, which I'd be using later for my model.\n\"\"\"\nbucket = pd.qcut(train_data['Fare'], 5)\nbucket.unique()\ndef FareGroup(fare):\n    if float(fare):\n        if fare > 0.0 and fare <= 7.854:\n            return 1\n        elif fare > 7.854 and fare <= 10.5:\n            return 2\n        elif fare > 10.5 and fare <= 21.679:\n            return 3\n        elif fare > 21.679 and fare <= 39.688:\n            return 4\n        elif fare > 39.688 and fare <= 512.329:\n            return 5\n        else:\n            return -1\n    else:\n        return -1\n    \n    \ntrain_data['FareRange'] = train_data['Fare'].apply(FareGroup)\ntrain_data.drop('Fare',axis=1,inplace=True)\nprint(train_data.groupby(['FareRange']).size())\nprint (train_data[['FareRange', 'Survived']].groupby(['FareRange'], as_index=False).mean())\n\"\"\"\n**Age**\n\nCreating a similar range for age as well, like Fare and assigning -1 to Null values to be handled later.\n\"\"\"\nbucket = pd.qcut(train_data['Age'], 5).unique()\nbucket\ndef AgeGroup(age):\n    if float(age):\n        if age > 19.0 and age <= 25.0:\n            return 19\n        elif age > 25.0 and age <= 31.8:\n            return 25\n        elif age > 31.8 and age <= 41.0:\n            return 31\n        elif age > 41.0 and age <= 80.0:\n            return 41\n        elif age < 19.0:\n            return 0\n        else:\n            return -1\n    else:\n        return -1\n    \n    \ntrain_data['AgeGroup'] = train_data['Age'].apply(AgeGroup)\ntrain_data.drop('Age',axis=1,inplace=True)\nprint (train_data[['AgeGroup', 'Survived']].groupby(['AgeGroup'], as_index=False).mean())\n\"\"\"\nI'll update my features array with these new features and dropping the old ones.\n\"\"\"\nfeatures = []\nfor i in train_data.columns:\n    if i !='Survived':\n        features.append(i)\n\nfeatures\n\"\"\"\n# Handling Null Values\n\nWe have null values in Age, Cabin and Embarked features. I'll try different methods o handling null values for these features.\n\"\"\"\n\"\"\"\n**Embarked**\n\nSince we have only 2 null records for Embarked feature, I'm going to save some time and just drop them.\n\"\"\"\ntrain_data.dropna(subset=['Embarked'],inplace=True)\ntrain_data.groupby(['Embarked']).size()\n\"\"\"\n**Age and Fare**\n\nHere, I'd be using KNN to predict te missing values (which I've classified as -1 in previous function). For this task, I'd be using KNNImputer.\n\"\"\"\ntrain_data['AgeGroup'] = train_data['AgeGroup'].apply(lambda x: np.nan if x == -1 else x)\ntrain_data['FareRange'] = train_data['FareRange'].apply(lambda x: np.nan if x == -1 else x)\n\n\nimputer = KNNImputer(n_neighbors= 5)\nAgeGroupImputed = imputer.fit_transform([train_data['AgeGroup']])\nFareRangeImputed = imputer.fit_transform([train_data['FareRange']])\nFareRangeImputed = pd.Series(FareRangeImputed[0])\nAgeGroupImputed = pd.Series(AgeGroupImputed[0])\ntrain_data['FareRange'] = FareRangeImputed\ntrain_data['AgeGroup'] = AgeGroupImputed\n\ntrain_data.head(20)\n\"\"\"\nI'll replace the new columns with the one hot encoded values and append them to my dataframe.\n\"\"\"\nsex = pd.get_dummies(train_data['Sex'],drop_first=True)\nembark = pd.get_dummies(train_data['Embarked'],drop_first=True)\ntitle = pd.get_dummies(train_data['Title'],drop_first=True)\nfare = pd.get_dummies(train_data['FareRange'],drop_first=True)\ncabin = pd.get_dummies(train_data['Cabin_Group'],drop_first=True)\nage = pd.get_dummies(train_data['AgeGroup'],drop_first=True)\n\ntrain_data.drop(['AgeGroup','Sex',\"Embarked\",'Title','Cabin_Group','FareRange'],axis=1,inplace=True)\n\ntrain_data = pd.concat([train_data,sex,embark,title,cabin,fare,age],axis=1)\ntrain_data.head(20)\n\"\"\"\n# Splitting data to train and test dataset\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(train_data.drop('Survived',axis=1), \n                                                    train_data['Survived'], test_size=0.30, \n                                                    random_state=101)\n\"\"\"\n# Model Building\n\"\"\"\nRandomForestModel = RandomForestClassifier(random_state=3)\nRandomForestModel.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,RandomForestModel.predict(X_test))\nclassificationRep=classification_report(y_test,RandomForestModel.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\nLGBMModel = LGBMClassifier()\nLGBMModel.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,LGBMModel.predict(X_test))\nclassificationRep=classification_report(y_test,LGBMModel.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\nXGBModel = XGBClassifier()\nXGBModel.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,XGBModel.predict(X_test))\nclassificationRep=classification_report(y_test,XGBModel.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\nAdaBoostModel = AdaBoostClassifier()\nAdaBoostModel.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,AdaBoostModel.predict(X_test))\nclassificationRep=classification_report(y_test,AdaBoostModel.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n# Fine Tuning\n\nOnce I've tested with the common ensemble techniques, I'd now fine tune the hyperparamters and test what impact the fine tuning will have on the final prediction.\n\"\"\"\n\"\"\"\n**Fine tuning Random Forest**\n\"\"\"\n\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4]\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n\ncriterion = ['gini', 'entropy']\n# Create the random grid\nrandom_grid = {'n_estimators': n_estimators,\n               'max_features': max_features,\n               'max_depth': max_depth,\n               'min_samples_split': min_samples_split,\n               'min_samples_leaf': min_samples_leaf,\n               'bootstrap': bootstrap}\nprint(random_grid)\nRandomForestModel2 = RandomForestClassifier()\n# Random search of parameters, using 3 fold cross validation, \n# search across 100 different combinations, and use all available cores\nrf_random = RandomizedSearchCV(estimator = RandomForestModel2, param_distributions = random_grid, n_iter = 50, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n# Fit the random search model\nrf_random.fit(X_train, y_train)\nparams = rf_random.best_params_\nparams\nRandomForestModel2 = RandomForestClassifier(n_estimators=params['n_estimators'],min_samples_split=params['min_samples_split'],min_samples_leaf = params['min_samples_leaf'],max_features = params['max_features'],max_depth = params['max_depth'],bootstrap=params['bootstrap'])\nRandomForestModel2.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,RandomForestModel2.predict(X_test))\nclassificationRep=classification_report(y_test,RandomForestModel2.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n**Fine tuning LGBM Classifier**\n\"\"\"\nrandom_grid_lgbm = { \n                   'num_leaves':[int(x) for x in np.linspace(start = 1, stop = 200, num = 10)],\n                   'max_depth':[int(x) for x in np.linspace(start = 10, stop = 100, num = 10)], \n                   'learning_rate':[0.1,0.001], \n                   'n_estimators':[int(x) for x in np.linspace(start = 1, stop = 100, num = 10)]}\n\nLGBMModel2 = LGBMClassifier()\nrf_random = RandomizedSearchCV(estimator = LGBMModel2, param_distributions = random_grid_lgbm, n_iter = 50, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n\nrf_random.fit(X_train, y_train)\nrandom_grid_lgbm = rf_random.best_params_\nrandom_grid_lgbm\nLGBMModel2 = LGBMClassifier(n_estimators=random_grid_lgbm['n_estimators'],num_leaves=random_grid_lgbm['num_leaves'],max_depth = random_grid_lgbm['max_depth'],learning_rate=random_grid_lgbm['learning_rate'])\nLGBMModel2.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,LGBMModel2.predict(X_test))\nclassificationRep=classification_report(y_test,LGBMModel2.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n**Fine tuning XGBoost**\n\"\"\"\nxgparam = {'eta': [0.01,0.1,0.2],\n'min_child_weight': [int(x) for x in np.linspace(start = 1, stop = 10, num = 10)],\n'max_depth': [int(x) for x in np.linspace(start = 10, stop = 100, num = 10)],\n'gamma':np.linspace(start = 0.0, stop = 0.2, num = 20)}\n\nXGBModel2 = XGBClassifier()\nrf_random = RandomizedSearchCV(estimator = XGBModel2, param_distributions = xgparam, n_iter = 50, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n\nrf_random.fit(X_train, y_train)\nxgparam = rf_random.best_params_\nxgparam\nXGBModel2 = XGBClassifier(eta=xgparam['eta'],min_child_weight=xgparam['min_child_weight'],max_depth = xgparam['max_depth'],gamma=xgparam['gamma'])\nXGBModel2.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,XGBModel2.predict(X_test))\nclassificationRep=classification_report(y_test,XGBModel2.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n**Fine Tuning AdaBoost**\n\"\"\"\nadaparam = {\n    'n_estimators' : [int(x) for x in np.linspace(start = 10, stop = 100, num = 20)],\n    'learning_rate' : np.linspace(start = 0.01, stop = 1, num = 20)\n}\n\nAdaBoostModel2 = AdaBoostClassifier()\nrf_random = RandomizedSearchCV(estimator = AdaBoostModel2, param_distributions = adaparam, n_iter = 50, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n\nrf_random.fit(X_train, y_train)\nadaparam = rf_random.best_params_\nadaparam\nAdaBoostModel2 = AdaBoostClassifier(n_estimators=adaparam['n_estimators'],learning_rate=adaparam['learning_rate'])\nAdaBoostModel2.fit(X_train,y_train)\naccuracy = accuracy_score(y_test,AdaBoostModel2.predict(X_test))\nclassificationRep=classification_report(y_test,AdaBoostModel2.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n# Stacking (Voting) ensemble\n\"\"\"\n\nvotingModel = VotingClassifier(estimators=[('RF', RandomForestModel2), ('LGBM', LGBMModel2),\n('XGB', XGBModel2),('ADA',AdaBoostModel2)], voting='hard')\n\nvotingModel = votingModel.fit(X_train, y_train)\n\naccuracy = accuracy_score(y_test,votingModel.predict(X_test))\nclassificationRep=classification_report(y_test,votingModel.predict(X_test))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n# Blending Ensemble Method\n\"\"\"\n#blender\nBlend_X = list()\ny1 = RandomForestModel2.predict(X_test)\ny1 = y1.reshape(len(y1), 1)\nBlend_X.append(y1)\n\ny2 = LGBMModel2.predict(X_test)\ny2 = y2.reshape(len(y2), 1)\nBlend_X.append(y2)\n\ny3 = XGBModel2.predict(X_test)\ny3 = y3.reshape(len(y3), 1)\nBlend_X.append(y3)\n\ny4 = AdaBoostModel2.predict(X_test)\ny4 = y4.reshape(len(y4), 1)\nBlend_X.append(y4)\n\nBlend_X = hstack(Blend_X)\nfrom sklearn.linear_model import LogisticRegression\nBlenderModel = LogisticRegression()\nBlenderModel.fit(Blend_X, y_test)\n\naccuracy = accuracy_score(y_test,BlenderModel.predict(Blend_X))\nclassificationRep=classification_report(y_test,BlenderModel.predict(Blend_X))\nprint(\"Classification Report: \\n\"+classificationRep)\nprint(\"Accuracy: \"+str(accuracy))\n\"\"\"\n# WORKING WITH TEST DATA\n\"\"\"\ntest_data.describe()\ntest_data.info()\ntest_data_original = test_data.copy()\nfeatures = []\nfor i in test_data.columns:\n    if i !='Survived':\n        features.append(i)\n\nfeatures\ntest_data.isnull().sum()\ntest_data.drop(['PassengerId','Ticket'],axis=1,inplace=True)\n\ntest_data['Title'] = test_data['Name'].apply(get_title)\ntest_data.drop('Name',axis=1,inplace=True)\ntest_data['Title'] = test_data['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Others')\n\ntest_data['Title'] = test_data['Title'].replace('Mlle', 'Miss')\ntest_data['Title'] = test_data['Title'].replace('Ms', 'Miss')\ntest_data['Title'] = test_data['Title'].replace('Mme', 'Mrs')\n\n\ntest_data.groupby(['Title']).size()\ntest_data['Cabin_Group'] = test_data['Cabin'].apply(cabin_group)\nprint(test_data.groupby(['Cabin_Group']).size())\ntest_data.drop('Cabin',axis=1,inplace=True)\n\ntest_data['FareRange'] = test_data['Fare'].apply(FareGroup)\ntest_data.drop('Fare',axis=1,inplace=True)\nprint(test_data.groupby(['FareRange']).size())\n\ntest_data['AgeGroup'] = test_data['Age'].apply(AgeGroup)\nprint(test_data.groupby(['AgeGroup']).size())\ntest_data.drop('Age',axis=1,inplace=True)\nfeatures = []\nfor i in test_data.columns:\n    features.append(i)\n\nfeatures\n\ntest_data.dropna(subset=['Embarked'],inplace=True)\ntest_data.groupby(['Embarked']).size()\n\ntest_data['AgeGroup'] = test_data['AgeGroup'].apply(lambda x: np.nan if x == -1 else x)\ntest_data['FareRange'] = test_data['FareRange'].apply(lambda x: np.nan if x == -1 else x)\n\n\nimputer = KNNImputer(n_neighbors= 5)\nAgeGroupImputed = imputer.fit_transform([test_data['AgeGroup']])\nFareRangeImputed = imputer.fit_transform([test_data['FareRange']])\nFareRangeImputed = pd.Series(FareRangeImputed[0])\nAgeGroupImputed = pd.Series(AgeGroupImputed[0])\ntest_data['FareRange'] = FareRangeImputed\ntest_data['AgeGroup'] = AgeGroupImputed\n\ntest_data.head(20)\n\nsex = pd.get_dummies(test_data['Sex'],drop_first=True)\nembark = pd.get_dummies(test_data['Embarked'],drop_first=True)\ntitle = pd.get_dummies(test_data['Title'],drop_first=True)\nfare = pd.get_dummies(test_data['FareRange'],drop_first=True)\ncabin = pd.get_dummies(test_data['Cabin_Group'],drop_first=True)\nage = pd.get_dummies(test_data['AgeGroup'],drop_first=True)\n\ntest_data.drop(['AgeGroup','Sex',\"Embarked\",'Title','Cabin_Group','FareRange'],axis=1,inplace=True)\n\ntest_data = pd.concat([test_data,sex,embark,title,cabin,fare,age],axis=1)\ntest_data.head(5)\n\n\n\n\"\"\"\n**Predict**\n\nUsing the model with best  accuracy for prediction\n\"\"\"\n#blender\nBlend_Y = list()\ny1 = RandomForestModel2.predict(test_data)\ny1 = y1.reshape(len(y1), 1)\nBlend_Y.append(y1)\n\ny2 = LGBMModel2.predict(test_data)\ny2 = y2.reshape(len(y2), 1)\nBlend_Y.append(y2)\n\ny3 = XGBModel2.predict(test_data)\ny3 = y3.reshape(len(y3), 1)\nBlend_Y.append(y3)\n\ny4 = AdaBoostModel2.predict(test_data)\ny4 = y4.reshape(len(y4), 1)\nBlend_Y.append(y4)\n\n\nBlend_Y = hstack(Blend_Y)\n\ny_pred = BlenderModel.predict(Blend_Y)\npassengerId = test_data_original.iloc[:,0]\npassengerId\nsubmission = pd.DataFrame({'PassengerId':passengerId,'Survived':y_pred})\nsubmission.to_csv('submission.csv',index=False)\n\"\"\"\nIf you like it, please upvote. Also let me know in the comments, if my strategy is incorrect somewhere or you have a better solution for any part or any suggestions on how I should improve the accuracy of my models.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '36c845da7dbc73'}"}
{"id":"96439","text":"\"\"\"\n# COVID-19 Prediction using Different models\n\nIn this project, I will use data from the last three months to predict confirmed cases and deaths for the month of April. The work has just begun, good results have been obtained. Much work remains to be done, for exampl: \n\n* to explore new functions\n* try other models\n* adjust their parameters\n\nI will post all updates here. I ask you to support the project like if it seemed useful to you.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom itertools import cycle, islice\nimport seaborn as sb\nimport matplotlib.dates as dates\nimport datetime as dt\nfrom sklearn import preprocessing\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import StandardScaler\nimport plotly.graph_objects as go\nimport plotly_express as px\nfrom sklearn.preprocessing import OrdinalEncoder\ntrain = pd.read_csv(\"\/kaggle\/input\/covid19-global-forecasting-week-3\/train.csv\")\ntest = pd.read_csv(\"\/kaggle\/input\/covid19-global-forecasting-week-3\/test.csv\")\ntrain.head()\ntrain.info()\n\"\"\"\nCurrenty, the date is coming as a string. Lets convert it into datetime format so that EDA on the data becomes easier.\n\"\"\"\ntrain['Date'] = pd.to_datetime(train['Date'], format = '%Y-%m-%d')\ntest['Date'] = pd.to_datetime(test['Date'], format = '%Y-%m-%d')\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ncurr_date = train['Date'].max()\nworld_cum_confirmed = sum(train[train['Date'] == curr_date].ConfirmedCases)\nworld_cum_fatal = sum(train[train['Date'] == curr_date].Fatalities)\nprint('Number of Countires: ', len(train['Country_Region'].unique()))\nprint('End date in train dset: ', curr_date)\nprint('Number of confirmed cases: ', world_cum_confirmed)\nprint('Number of fatal cases: ', world_cum_fatal)\ntrain[['ConfirmedCases', 'Fatalities']].describe()\ntop_country_c = train[train['Date'] == curr_date].groupby(['Date','Country_Region']).sum().sort_values(['ConfirmedCases'], ascending=False)\ntop_country_c.head(10)\n\"\"\"\n*If you want to escape from panic and just take up the competition, you can safely go to these countries))*\n\"\"\"\ntop_country_c.tail()\ntop_country_f = train[train['Date'] == curr_date].groupby(['Date','Country_Region']).sum().sort_values(['Fatalities'], ascending=False)\ntop_country_f.head(10)\n\"\"\"\nConfirmed Cases and Fatalities are cummulative sums of all the previous days. \n\nI added new features but haven\u2019t used them yet. They look quite logical and useful (show the dynamics of the spread of the disease every day), I hope that come in handy later.\n\"\"\"\npr_confirm = train['ConfirmedCases'].value_counts(normalize=True)\npr_fatal = train['Fatalities'].value_counts(normalize=True)\n\nprint(f'Percs of confirmed case = {pr_confirm[1:].sum()*100}%')\nprint(f'Percs of fatality = {pr_fatal[1:].sum()*100}%')\ndef Country_cases(df, ConfirmedCases,*argv):\n    f, ax=plt.subplots(figsize=(16,5))\n    labels=argv\n    for a in argv: \n        country=df.loc[(df['Country_Region']==a)]\n        plt.plot(country['Date'],country['ConfirmedCases'],linewidth=3)\n        plt.xticks(rotation=40)\n        plt.legend(labels)\n        ax.set(title='Evolution of the number of cases' )\n        \ndef Country_fatalities(df, Fatalities,*argv):\n    f, ax=plt.subplots(figsize=(16,5))\n    labels=argv\n    for a in argv: \n        country=df.loc[(df['Country_Region']==a)]\n        plt.plot(country['Date'],country['Fatalities'],linewidth=3)\n        plt.xticks(rotation=40)\n        plt.legend(labels)\n        ax.set(title='Evolution of the number of fatalities' )\ntrain_sum=train.groupby(['Date','Country_Region']).agg('sum').reset_index()\n\nCountry_cases(train_sum,'ConfirmedCases','US')\nCountry_fatalities(train_sum,'Fatalities','US')\nCountry_cases(train_sum,'ConfirmedCases','Ukraine')\nCountry_fatalities(train_sum,'Fatalities','Ukraine')\ncase='ConfirmedCases'\ndef timeCompare(df, time,*argv):\n    Coun1=argv[0]\n    Coun2=argv[1]\n    f,ax=plt.subplots(figsize=(16,5))\n    labels=argv  \n    country=df.loc[(df['Country_Region']==Coun1)]\n    plt.plot(country['Date'],country[case],linewidth=2)\n    plt.xticks([])\n    plt.legend(labels)\n    ax.set(title=' Evolution of actual cases',ylabel='Number of cases' )\n\n    country2=df.loc[df['Country_Region']==Coun2]\n    #country2['Date']=country2['Date']-datetime.timedelta(days=time)\n    plt.plot(country2['Date'],country2[case],linewidth=2)\n    #plt.xticks([])\n    plt.legend(labels)\n    ax.set(title=' Evolution of cases in %d days difference '%time ,ylabel='Number of %s cases'%case )\ntimeCompare(train_sum, 7,'Italy','Germany')\ntimeCompare(train_sum, 7,'Italy','US')\ncase='Fatalities'\ndef timeCompare_f(df, time,*argv):\n    Coun1=argv[0]\n    Coun2=argv[1]\n    f,ax=plt.subplots(figsize=(16,5))\n    labels=argv  \n    country=df.loc[(df['Country_Region']==Coun1)]\n    plt.plot(country['Date'],country[case],linewidth=2)\n    plt.xticks([])\n    plt.legend(labels)\n    ax.set(title=' Evolution of actual cases',ylabel='Number of cases' )\n\n    country2=df.loc[df['Country_Region']==Coun2]\n    #country2['Date']=country2['Date']-datetime.timedelta(days=time)\n    plt.plot(country2['Date'],country2[case],linewidth=2)\n    #plt.xticks([])\n    plt.legend(labels)\n    ax.set(title=' Evolution of Fatalities in %d days difference '%time ,ylabel='Number of %s cases'%case )\ntimeCompare_f(train_sum, 7,'Italy','Germany')\ntimeCompare_f(train_sum, 7,'Italy','US')\ntrain_data_by_country = train.groupby(['Country_Region'],as_index=True).agg({'ConfirmedCases': 'max', 'Fatalities': 'max'})\ntrain_data_by_country_confirm = train_data_by_country.sort_values(by=[\"ConfirmedCases\"], ascending=False)\n\nfrom itertools import cycle, islice\n\ndiscrete_col = list(islice(cycle(['orange', 'r', 'g', 'k', 'b', 'c', 'm']), None, len(train_data_by_country_confirm.head(10))))\nplt.rcParams.update({'font.size': 22})\ntrain_data_by_country_confirm.head(10).plot(figsize=(15,10), kind='barh', color=discrete_col)\nplt.legend([\"Confirmed Cases\", \"Fatalities\"]);\nplt.xlabel(\"Number of Covid-19 Cases\")\nplt.title(\"TOP 10 Countries with Confirmed Cases\")\nylocs, ylabs = plt.yticks()\nfor i, v in enumerate(train_data_by_country_confirm.head(10)[\"ConfirmedCases\"][:]):\n    plt.text(v+0.01, ylocs[i]-0.25, str(int(v)), fontsize=12)\nfor i, v in enumerate(train_data_by_country_confirm.head(10)[\"Fatalities\"][:]):\n    if v > 200: #disply for only >200 fatalities\n        plt.text(v+0.01,ylocs[i]+0.1,str(int(v)),fontsize=12) \n\"\"\"\nFrom the interesting on this graph, we can distinguish a strangely high mortality rate in France compared with other countries with a similar incidence rate.\n*Perhaps this is due to the level of medicine or some other factors.*\n\nAs well as a lower mortality rate in the USA than in the TOP 2 countries. I think this is due to the fact that they began to do mass testing of people there and to identify patients in the early stages.\n\"\"\"\ntrain['MortalityRate'] = train['Fatalities'] \/ train['ConfirmedCases']\ntrain['MortalityRate'] = train['MortalityRate'].fillna(0.0)\n\"\"\"\nConfirmed Cases and Fatalities are cummulative sums of all the previous days. In order to understand the daily trend, I'll create a column for daily cases and deaths that will be the difference between the current value and the previous day's value\n\"\"\"\ndef add_daily_measures(df):\n    df.loc[0,'Daily Cases'] = df.loc[0,'ConfirmedCases']\n    df.loc[0,'Daily Deaths'] = df.loc[0,'Fatalities']\n    for i in range(1,len(df)):\n        df.loc[i,'Daily Cases'] = df.loc[i,'ConfirmedCases'] - df.loc[i-1,'ConfirmedCases']\n        df.loc[i,'Daily Deaths'] = df.loc[i,'Fatalities'] - df.loc[i-1,'Fatalities']\n    #Make the first row as 0 because we don't know the previous value\n    df.loc[0,'Daily Cases'] = 0\n    df.loc[0,'Daily Deaths'] = 0\n    return df\n\ndf_world = train.copy()\ndf_world = df_world.groupby('Date',as_index=False)['ConfirmedCases','Fatalities'].sum()\ndf_world = add_daily_measures(df_world)\nfig = go.Figure(data=[\n    go.Bar(name='Cases', x=df_world['Date'], y=df_world['Daily Cases']),\n    go.Bar(name='Deaths', x=df_world['Date'], y=df_world['Daily Deaths'])\n])\n# Change the bar mode\nfig.update_layout(barmode='overlay', title='Worldwide daily Case and Death count')\nfig.show()\nmort = train.copy()\nmort['Date'] = pd.to_datetime(mort['Date'])\ntrain_data_by_date = mort.groupby(['Date'],as_index=True).agg({'ConfirmedCases': 'sum','Fatalities': 'sum', 'MortalityRate':'mean'})\n\ntrain_data_by_date.MortalityRate.plot(figsize=(15,10),x_compat=True, legend='Mortality Rate',color='r')\ntop_country_m = train[train['Date'] == curr_date].groupby(['Country_Region']).sum().sort_values(['MortalityRate'], ascending=False)\ntop_country_m.head(10)\ntop_country_m.MortalityRate.head(10).plot(figsize=(15,10),kind='barh')\nplt.xlabel(\"Mortality Rate\")\nplt.title(\"First 10 Countries with Highest Mortality Rate\")\n\n\"\"\"\n# Preprocessing\n\"\"\"\ndef create_features(df):\n    df['day'] = df['Date'].dt.day\n    df['month'] = df['Date'].dt.month\n    df['dayofweek'] = df['Date'].dt.dayofweek\n    df['dayofyear'] = df['Date'].dt.dayofyear\n    df['quarter'] = df['Date'].dt.quarter\n    df['weekofyear'] = df['Date'].dt.weekofyear\n    return df\ndef train_dev_split(df, days):\n    #Last days data as dev set\n    date = df['Date'].max() - dt.timedelta(days=days)\n    return df[df['Date'] <= date], df[df['Date'] > date]\n\"\"\"\nProvince_State contains null values. I will convert the null values to the string \"NaN\". And just below I replace the missing values with the name of the country. I think that the analysis and prediction of growth dynamics, provinces are not particularly important. They are needed already for a more detailed study of each country.\n\"\"\"\ndef categoricalToInteger(df):\n    #convert NaN Province State values to a string\n    df.Province_State.fillna('NaN', inplace=True)\n    #Define Ordinal Encoder Model\n    oe = OrdinalEncoder()\n    df[['Province_State','Country_Region']] = oe.fit_transform(df.loc[:,['Province_State','Country_Region']])\n    return df\ndf_train = categoricalToInteger(train)\ndf_train.info()\ndf_train = create_features(df_train)\ndf_train, df_dev = train_dev_split(df_train,0)\n\ncolumns = ['day','month','dayofweek','dayofyear','quarter','weekofyear','Province_State', 'Country_Region','ConfirmedCases','Fatalities']\ndf_train = df_train[columns]\ndf_dev = df_dev[columns]\ndf_test = categoricalToInteger(test)\ndf_test = create_features(test)\n#Columns to select\ncolumns = ['day','month','dayofweek','dayofyear','quarter','weekofyear','Province_State', 'Country_Region']\n\"\"\"\n*Next new features are wrong. I will try to use this idea in the next version*\n\"\"\"\n#train['NewConfirmedCases'] = train['ConfirmedCases'] - train['ConfirmedCases'].shift(1)\n#train['NewConfirmedCases'] = train['NewConfirmedCases'].fillna(0.0)\n#train['NewFatalities'] = train['Fatalities'] - train['Fatalities'].shift(1)\n#train['NewFatalities'] = train['NewFatalities'].fillna(0.0)\n\n#train\n#df_train.loc[:,'Confirmed_log']  = np.log10(df_train.loc[:,'ConfirmedCases'] + 1)\n#df_train.loc[:,'Fatalities_log'] = np.log10(df_train.loc[:,'Fatalities'] + 1)\n\"\"\"\n# Modeling\n\nI prepared several initial models. So far I used only Random Forest and XGB.\n\"\"\"\ndef RF():\n    model = RandomForestRegressor(n_estimators = 100) \n    return model\n\ndef XGB():\n    model = XGBRegressor(n_estimators=1300)\n    return model\n\ndef LGBM():\n    model = LGBMRegressor(iterations=2)\n    return model\n\"\"\"\nSince we need to predict the number of diseases and the number of deaths, we will use the model separately for each predictor.\n\n*Perhaps for each there will be your parameters, I will study this question later.*\n\"\"\"\n\"\"\"\n**UPD:** LGBM not good\n\"\"\"\nsubmission = []\n#Loop through all the unique countries\nfor country in df_train.Country_Region.unique():\n    #Filter on the basis of country\n    df_train1 = df_train[df_train[\"Country_Region\"]==country]\n    #Loop through all the States of the selected country\n    for state in df_train1.Province_State.unique():\n        #Filter on the basis of state\n        df_train2 = df_train1[df_train1[\"Province_State\"]==state]\n        #Convert to numpy array for training\n        train = df_train2.values\n        #Separate the features and labels\n        X_train, y_train = train[:,:-2], train[:,-2:]\n        #model1 for predicting Confirmed Cases\n        model1 = XGBRegressor(n_estimators=1100)\n        model1.fit(X_train, y_train[:,0])\n        #model2 for predicting Fatalities\n        model2 = XGBRegressor(n_estimators=1100)\n        model2.fit(X_train, y_train[:,1])\n        #Get the test data for that particular country and state\n        df_test1 = df_test[(df_test[\"Country_Region\"]==country) & (df_test[\"Province_State\"] == state)]\n        #Store the ForecastId separately\n        ForecastId = df_test1.ForecastId.values\n        #Remove the unwanted columns\n        df_test2 = df_test1[columns]\n        #Get the predictions\n        y_pred1 = np.round(model1.predict(df_test2.values),5)\n        y_pred2 = np.round(model2.predict(df_test2.values),5)\n        #Append the predicted values to submission list\n        for i in range(len(y_pred1)):\n            d = {'ForecastId':ForecastId[i], 'ConfirmedCases':y_pred1[i], 'Fatalities':y_pred2[i]}\n            submission.append(d)\n\"\"\"\nConvert the submission list to DataFrame and save it as csv for submission\n\"\"\"\ndf_submit = pd.DataFrame(submission)\n\ndf_submit.to_csv(r'submission.csv', index=False)\n\"\"\"\n# Do leave an upvote if you like the work:) Constructive feedbacks are welcome!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b1257e622d944e'}"}
{"id":"101821","text":"\"\"\"\n<img src=\"https:\/\/media.giphy.com\/media\/9ABgKHIu3acWA\/giphy.gif\"\/>\n\"\"\"\n\"\"\"\n# Titantic: Machine Learning from Disaster  \n \n\"\"\"\n\"\"\"\n\nThe sinking of the RMS Titanic is one of the most infamous shipwrecks in history.  Titanic was a passenger liner that sank in the North Atlantic Ocean on 15 April 1912 after colliding with an iceberg during her first voyage from Southampton, UK to New York City, US. The sinking of Titanic caused the deaths of 1,502 people in one of the deadliest peacetime maritime disasters in history. Titanic was the largest ship at the time and was called 'the unsinkable'. This sensational tragedy shocked the international community and led to better safety regulations for ships.\n\nAfter leaving Southampton on 10 April 1912, Titanic called at Cherbourg in France and Queenstown (now Cobh) in Ireland before heading westwards towards New York. On 14 April 1912, four days into the crossing and about 375 miles (600 km) south of Newfoundland, she hit an iceberg at 11:40 pm (ship's time; GMT\u22123). The glancing collision caused Titanic's hull plates to buckle inwards in a number of locations on her starboard side and opened five of her sixteen watertight compartments to the sea. Over the next two and a half hours, the ship gradually filled with water and sank. Passengers and some crew members were evacuated in lifeboats, many of which were launched only partly filled. A disproportionate number of men -- over 90% of those in Second Class -- were left aboard due to a \"women and children first\" protocol followed by the officers loading the lifeboats. Just before 2:20 am Titanic broke up and sank bow-first with over a thousand people still on board. Those in the water died within minutes from hypothermia caused by immersion in the freezing ocean. The 710 survivors were taken aboard from the lifeboats by RMS Carpathia a few hours later.\n\nOne of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.\n\"\"\"\n\"\"\"\n**\u201cFifteen-hundred people went into the sea, when Titanic sank from under us. There were twenty boats floating nearby\u2026 and only one came back. One. Six were saved from the water, myself included. Six\u2026 out of fifteen-hundred. Afterward, the seven-hundred people in the boats had nothing to do but wait\u2026 wait to die\u2026 wait to live\u2026 wait for an absolution\u2026 that would never come.\u201d \u2014Rose**\n***\n\n<img src=\"https:\/\/media.giphy.com\/media\/YE9A1qSEn0gV2\/giphy.gif\"\/>\n\n\n\n\"\"\"\n\"\"\"\n## About This Dataset\n***\nSource: https:\/\/www.kaggle.com\/c\/titanic\n\n**Overview: The data has been split into two groups:**\n\ntraining set (train.csv) test set (test.csv) The training set should be used to build machine learning models. For the training set, the outcome is included (also known as the \u201cground truth\u201d) for each passenger. My model will be based on \u201cfeatures\u201d like passengers\u2019 gender and class.\n\nThe test set should be used to see how well my model performs on unseen data. For the test set, we do not provide the ground truth for each passenger. For each passenger in the test set, use the model to predict whether or not they survived the sinking of the Titanic.\n\ngender_submission.csv, a set of predictions that assume all and only female passengers survive, as an example of what a submission file should look like.\n\nData Dictionary Variable\tDefinition\tKey survival\tSurvival\t0 = No, 1 = Yes pclass\tTicket class\t1 = 1st, 2 = 2nd, 3 = 3rd sex\tSex Age Age in years sibsp\t# of siblings \/ spouses aboard the Titanic parch\t# of parents \/ children aboard the Titanic ticket\tTicket number fare\tPassenger fare cabin\tCabin number embarked\tPort of Embarkation\tC = Cherbourg, Q = Queenstown, S = Southampton Variable Notes pclass: A proxy for socio-economic status (SES) 1st = Upper 2nd = Middle 3rd = Lower\n\nage: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5\n\nsibsp: The dataset defines family relations in this way... Sibling = brother, sister, stepbrother, stepsister Spouse = husband, wife (mistresses and fianc\u00e9s were ignored)\n\nparch: The dataset defines family relations in this way... Parent = mother, father Child = daughter, son, stepdaughter, stepson Some children travelled only with a nanny, therefore parch=0 for them.\n\n\"\"\"\n\"\"\"\n## Problem\n***\n*The Titanic is about to sink and we want to predict who survives and who dies*\n\"\"\"\n\"\"\"\n## Objective \n***\n\n*We would like to see the likelyhood of a passenger surviving this fatal crash, many factors come into play in predicting whether or not a passenger survives.  The goal is to find out what those factors are and how much of an impact they make in this situation.*\n\"\"\"\n\"\"\"\n## OSEMN Pipeline\n****\n\n*I\u2019ll be following a typical data science pipeline, which is call \u201cOSEMN\u201d (pronounced awesome).*\n\n1. **O**btaining the data is the first approach in solving the problem.\n\n2. **S**crubbing or cleaning the data is the next step. This includes data imputation of missing or invalid data and fixing column names.\n\n3. **E**xploring the data will follow right after and allow further insight of what our dataset contains. Looking for any outliers or weird data. Understanding the relationship each explanatory variable has with the response variable resides here and we can do this with a correlation matrix. \n\n4. **M**odeling the data will give us our predictive power on whether a passenger will survive or not. \n\n5. I**N**terpreting the data is last. With all the results and analysis of the data, what conclusion is made? What factors contributed most to survival? What relationship of variables were found? \n\"\"\"\n\"\"\"\n# Part 1: Obtain the Data  \n***\n\"\"\"\n# Import libraries for data manipulation and data visulization\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n# Read the csv file and store the data into a dataframe \"titanic_df\"\ntitanic_df = pd.read_csv('..\/input\/train.csv', index_col=None)\n\"\"\"\n# Part 2: Scrubbing the Data\n***\n\"\"\"\n\"\"\"\nUsually cleaning and scrubbing the data would be tedious and can take many steps to prepare the data,  but thankfully, this particular data set is fairly clean and only has a few flaws.  I have to make sure that the dataset is not missing any values. \n\nBefore scrubbing the data, I am going to do a exploratory data analysis (EDA), which is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. A statistical model can be used or not, but primarily EDA is for seeing what the data can tell us beyond the formal modeling or hypothesis testing task.\n\n\n\"\"\"\n\"\"\"\n## Part 2a: Exploratory Data Analysis\nLet's get a first overview of the train and test dataset\nHow many rows and columns are there?\nWhat are the names of the features (columns)?\nWhich features are numerical, which are categorical?\nHow many values are missing?\nThe **shape** and **info** methods answer these questions\n**head** displays some rows of the dataset\n**describe** gives a summary of the statistics (only for numerical columns)\n\"\"\"\ntitanic_df.shape\ntitanic_df.info()\n# Check to see if there is any missing values in our dataset\ntitanic_df.isnull().any()\ntitanic_df.head()\ntitanic_df.describe()\n\"\"\"\n## Part 2a:  The Scrubbing\nSince it looks like the column \"Cabin\" is missing many values, so we are going to drop the nulls and I am going to call it \"deck\"\nI am going to ignore other columns with missing values, because it should not have much impact on the accuracy of my analysis.\n\"\"\"\ndeck = titanic_df['Cabin'].dropna()\n\"\"\"\nTaking a look at the cabin column, you can see that the values contain a Letter followed by numbers.  Since we only need the letter to determine their cabin location.\n\"\"\"\ndeck.head\nlevels = []\nfor level in deck:\n    levels.append(deck[0])\n    \n# plotting the new data\ncabin_df = DataFrame(levels)\n\ncabin_df.columns = ['Cabin']\nsns.factorplot('Cabin', data=cabin_df,palette='winter_d', kind=\"count\", order =['A','B','C','D','E','F','G','T'])\n\n\"\"\"\n# Part 3: Exploratory Analysis - Exploring the Data\n*** \n <img  src=\"https:\/\/s-media-cache-ak0.pinimg.com\/originals\/32\/ef\/23\/32ef2383a36df04a065b909ee0ac8688.gif\"\/>\n\"\"\"\n\"\"\"\n## Part 3a: Demographic of the people onboard the Titanic\n***\n\"\"\"\n# Count of sex onboard\nsns.catplot('Sex', data=titanic_df,kind='count')\n# Count of each sex on which \"Class\" \nsns.catplot('Pclass', data=titanic_df,kind='count',hue='Sex')\n# Making a function for whether or not the passenger is a \"child\" or not\n# Under the age of 16 = Child, over the age of 16 = \"Sex\"\ndef male_female_child(passenger):\n    age, sex = passenger\n    \n    if age < 16:\n        return 'child'\n    else:\n        return sex\n# Creating a row named 'person' that will display if the passenger is a child, if not child, then display sex\ntitanic_df['person'] = titanic_df[['Age','Sex']].apply(male_female_child,axis=1)\n# Let's take a look at the dataset to see if our column worked out \ntitanic_df[0:10]\n# List out the number of male, female, and children on each class\nsns.catplot('Pclass',data=titanic_df,kind='count',hue='person')\n# Histogram of the distribution of ages\ntitanic_df['Age'].hist(bins=70)\n# Average age of passengers onboard\ntitanic_df['Age'].mean()\n# The number of female\/male\/child\ntitanic_df['person'].value_counts()\n# FacetGrid allows me to make multiple plots\n# aspect changes is necessary to change the aspect ratio so the graph fits nicely\nfig = sns.FacetGrid(titanic_df, hue='Sex',aspect=4)\nfig.map(sns.kdeplot,'Age',shade=True)\n\n# Set a variable to equal the highest age in the data\noldest = titanic_df['Age'].max()\n\n# Set a limit from yongest to oldest\nfig.set(xlim=(0,oldest))\n\n# Add a legend to the graph\nfig.add_legend()\n# Let's do the same plot, but now adding the children\n# FacetGrid allows me to make multiple plots\n# aspect changes is necessary to change the aspect ratio so the graph fits nicely\nfig = sns.FacetGrid(titanic_df, hue='person',aspect=4)\nfig.map(sns.kdeplot,'Age',shade=True)\n\n# Set a variable to equal the highest age in the data\noldest = titanic_df['Age'].max()\n\n# Set a limit from yongest to oldest\nfig.set(xlim=(0,oldest))\n\n# Add a legend to the graph\nfig.add_legend()","meta":"{'source': 'AI4Code', 'id': 'bb1ca2510af927'}"}
{"id":"68156","text":"# 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\n# read the matches dataset\nmatches=pd.read_csv('\/kaggle\/input\/ipl-dataset-2017\/IPL data\/matches.csv')\nmatches.head()\n# lets explore the data a bit\nmatches.describe()\n# we can see NaN values in data \nmatches.isnull().sum()\nmatches.shape\n# third umpire value is null so remove them\nmatches=matches.drop('umpire3',axis=1)\nmatches.columns\n# drop null values\nmatches=matches.dropna()\nmatches.shape\n# final check for null values\nmatches.info()\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport warnings\nwarnings.simplefilter(\"ignore\")\n# Matches played per season\nfig = px.bar(matches, x=matches['season'].value_counts().keys(), y=matches['season'].value_counts(), color=matches['season'].value_counts().keys(),\n             labels={\n                     'x': \"Year\",\n                     'y': \"Number of matches\"\n                     \n                 })\nfig.update_layout(title = 'Total matches per season')\nfig.show()\n#Show IPL teams\nprint(\"Teams before preprocessing:\",matches.team1.unique())\nmatches=matches.replace('Rising Pune Supergiant','Rising Pune Supergiants')\nmatches=matches.replace('Delhi Daredevils','Delhi Capitals')\nprint()\nprint(\"Teams before preprocessing:\",matches.team1.unique())\nmatches_per_team1=matches.groupby('team2')['team2'].count()\nmatches_per_team2=matches.groupby('team1')['team1'].count()\n\nmatches_per_team=matches_per_team1+matches_per_team2\nmatches_per_team\n# Number of matches played per venue\nfig = px.bar(matches, x=matches['venue'].value_counts().keys()[:5],\n             y=matches['venue'].value_counts()[:5],\n             color=matches['venue'].value_counts().keys()[:5],\n             labels={\n                     'x': \"Venue\",\n                     'y': \"Total number of matches\"\n                     \n                 })\nfig.update_layout(title='Total number of matches played')\nfig.show()\n# Find out valueable player throughout IPL seasons\nfig = px.bar(matches, x=matches['player_of_match'].value_counts().keys()[:10],\n             y=matches['player_of_match'].value_counts()[:10],\n             color=matches['player_of_match'].value_counts().keys()[:10],\n             labels={\n                     'x': \"Player Name\",\n                     'y': \"Total number of player of the match award\"\n                     \n                 })\nfig.update_layout(title='Top ten most valuable players throught the IPL Seasons')\nfig.show()\n\"\"\"\nFrom the data we could see CH Gayle is the most valueable player\n\"\"\"\n# find relation with toss\nwin=matches[matches['toss_winner']==matches['winner']].count()\nloose=matches[matches['toss_winner']!=matches['winner']].count()\n\n# matches won when won the toss\nfig = px.bar(matches, x=[win[1],loose[1]],\n             y=['win','loose'],\n             color=['win','loose'],\n             labels={\n                     'x': \"Number of matches won\",\n                     'y': \"Match Result\"\n                     \n                 })\nfig.update_layout(title='Influence of toss on match result')\nfig.show()\n# Toss influence in each venue\n\nchinnaswamy_win=matches[(matches['toss_winner']==matches['winner'])&(matches['venue']=='M Chinnaswamy Stadium')].count()[0]\nchinnaswamy_loose=matches[(matches['toss_winner']!=matches['winner'])&(matches['venue']=='M Chinnaswamy Stadium')].count()[0]\n\nEden_win=matches[(matches['toss_winner']==matches['winner'])&(matches['venue']=='Eden Gardens')].count()[0]\nEden_loose=matches[(matches['toss_winner']!=matches['winner'])&(matches['venue']=='Eden Gardens')].count()[0]\n\n\nFeroz_win=matches[(matches['toss_winner']==matches['winner'])&(matches['venue']=='Feroz Shah Kotla')].count()[0]\nFeroz_loose=matches[(matches['toss_winner']!=matches['winner'])&(matches['venue']=='Feroz Shah Kotla')].count()[0]\n\nWankhede_win=matches[(matches['toss_winner']==matches['winner'])&(matches['venue']=='Wankhede Stadium')].count()[0]\nWankhede_loose=matches[(matches['toss_winner']!=matches['winner'])&(matches['venue']=='Wankhede Stadium')].count()[0]\n\nRG_win=matches[(matches['toss_winner']==matches['winner'])&(matches['venue']=='Rajiv Gandhi International Stadium, Uppal')].count()[0]\nRG_loose=matches[(matches['toss_winner']!=matches['winner'])&(matches['venue']=='Rajiv Gandhi International Stadium, Uppal')].count()[0]\n\nfig = go.Figure(data=[\n    go.Bar(name='Rajiv Gandhi International Stadium, Uppal', \n           x=['win','loose'],\n           y=[RG_win,RG_loose]),\n    go.Bar(name='Wankhede Stadium',\n           x=['win','loose'], \n           y=[Wankhede_win,Wankhede_loose]),\n    go.Bar(name='Feroz Shah Kotla', \n           x=['win','loose'],\n           y=[Feroz_win,Feroz_loose]),\n    go.Bar(name='Eden Gardens',\n           x=['win','loose'], \n           y=[Eden_win,Eden_loose]),\n    go.Bar(name='M Chinnaswamy Stadium', \n           x=['win','loose'],\n           y=[chinnaswamy_win,chinnaswamy_loose]),\n])\n\n# Change the bar mode\nfig.update_layout(title='Match results comparison with toss results in various venues')\nfig.update_layout(\n    xaxis_title=\"Win \/ loose\",\n    yaxis_title=\"Count\",\n    legend_title=\"Venue Name\",\n)\nfig.show()\n# decision influence of toss on result\nwinner_field=matches[(matches['toss_winner']==matches['winner'])& (matches['toss_decision']=='field')].count()[0]\nwinner_bat=matches[(matches['toss_winner']==matches['winner'])& (matches['toss_decision']!='field')].count()[0]\n# matches won when won the toss\nfig = px.bar(matches, x=[winner_field,winner_bat],\n             y=['Field','Bat'],\n             color=['Field','Bat'],\n             labels={\n                     'x': \"Decision\",\n                     'y': \"Count\"\n                     \n                 })\nfig.update_layout(title='Influence of toss Decision on match result')\nfig.show()\n#Wins toss,bats first & wins match by team\nseasons = matches['season'].unique()\nteams = matches['team1'].unique()\ndf_toss_match_winner=matches[matches['toss_winner']==matches['winner']]\ndf_toss_match_winner_season=df_toss_match_winner.groupby('season')['season'].count()\ndf_toss_match_winner_team=df_toss_match_winner.groupby('winner')['winner'].count()\ntoss_batting_first=matches[(matches['toss_winner']==matches['winner']) & (matches['toss_decision']=='bat')]\ntoss_batting_first_team=toss_batting_first.groupby('toss_winner')['toss_winner'].count()\nwin_perc=[]\nfor i in teams:\n    if i in toss_batting_first_team.keys() and i in df_toss_match_winner_team.keys():\n        win_perc.append((toss_batting_first_team[i]\/df_toss_match_winner_team[i])*100)\n    else:\n        win_perc.append(0)\n\nfig, ax = plt.subplots(figsize=(10,5))\nplt.xlim(0,110)\nrects=plt.barh(teams,win_perc)\n\nfor i, v in enumerate(win_perc):\n    ax.text(v+0.5 , i + .25, str(v)[:5]+\"%\", color='black', fontweight='bold',va='top')\n\nfig.suptitle('Percentage of batting first while winning both toss and match',fontsize=20)\nplt.xlabel('Percentage', fontsize=18)\nplt.ylabel('Team', fontsize=18,rotation=0,labelpad=40)\n\nfor i in range(13):\n    teams[i]\n\nplt.show()\n#Wins toss,fields first & wins match by team\ntoss_field_first=matches[(matches['toss_winner']==matches['winner']) & (matches['toss_decision']=='field')]\ntoss_field_first_season=toss_field_first.groupby('toss_winner')['toss_winner'].count()\nwin_perc=[]\n\nfor i in teams:\n    if i in toss_field_first_season.keys() and i in df_toss_match_winner_team.keys():\n        win_perc.append((toss_field_first_season[i]\/df_toss_match_winner_team[i])*100)\n    else:\n        win_perc.append(0)\n\nfig, ax = plt.subplots(figsize=(10,5))\nplt.xlim(0,110)\nrects=plt.barh(teams,win_perc)\n\nfor i, v in enumerate(win_perc):\n    ax.text(v+0.5 , i + .25, str(v)[:5]+\"%\", color='black', fontweight='bold',va='top')\n\nfig.suptitle('Percentage of fielding first while winning both toss and match',fontsize=20)\nplt.xlabel('Percentage', fontsize=18)\nplt.ylabel('Team', fontsize=18,rotation=0,labelpad=40)\n\nfor i in range(13):\n    teams[i]\n\n\nplt.show()\n#Average runs per over\ndeliveries= pd.read_csv('\/kaggle\/input\/ipl-dataset-2017\/IPL data\/deliveries.csv')\n\ndf_deliveries = deliveries\n\ntotal_matches=len(df_deliveries['match_id'].unique())\novers=df_deliveries['over'].unique()\nover_bowled=df_deliveries.groupby('over')['over'].count()\/6\nover_runs=df_deliveries.groupby('over').agg({'total_runs': 'sum'}).total_runs\nrpo=over_runs\/over_bowled\n\nfig=plt.figure(figsize=(10,5))\nplt.ylim(0,12)\nrects=plt.bar(rpo.keys(),rpo.values,width=0)\nplt.xticks(rpo.keys())\n\nfor rect in rects:\n    height = rect.get_height()\n    plt.text(rect.get_x() + rect.get_width()\/2., 1.05*height, str(height)[:4],ha='center', va='bottom',color='black')\n\nover_colors = [\"red\",\"red\",\"red\",\"red\",\"red\",\"red\",\"orange\",\"orange\",\"orange\",\"orange\",\"orange\",\"orange\",\"orange\",\"orange\",\"orange\",\"green\",\"green\",\"green\",\"green\",\"green\"]\nplt.vlines(rpo.keys(),0,rpo.values,color=over_colors,linestyles='solid')\nplt.scatter(rpo.keys()[:6],rpo.values[:6], marker=\"o\",s=100,color=\"red\")\nplt.scatter(rpo.keys()[6:15],rpo.values[6:15], marker=\"o\",s=100,color=\"orange\")\nplt.scatter(rpo.keys()[15:],rpo.values[15:], marker=\"o\",s=100,color=\"green\")\n    \n    \nfig.suptitle('Average runs per over',fontsize=20)\nplt.xlabel('Over', fontsize=18)\nplt.ylabel('Runs', fontsize=18,rotation=0,labelpad=60)\n\nplt.legend([\"\", \"Powerplay\",\"Middle overs\",\"Death overs\"])\nplt.show()\n# Let us look the same for our venues\n\nchinnaswamy_field=matches[(matches['toss_winner']==matches['winner'])&\n                        (matches['venue']=='M Chinnaswamy Stadium')&\n                        (matches['toss_decision']=='field')].count()[0]\nchinnaswamy_bat=matches[(matches['toss_winner']!=matches['winner'])&\n                          (matches['venue']=='M Chinnaswamy Stadium')&\n                          (matches['toss_decision']!='field')].count()[0]\n\nEden_field=matches[(matches['toss_winner']==matches['winner'])&\n                 (matches['venue']=='Eden Gardens')&\n                 (matches['toss_decision']=='field')].count()[0]\nEden_bat=matches[(matches['toss_winner']!=matches['winner'])&\n                   (matches['venue']=='Eden Gardens')&\n                   (matches['toss_decision']!='field')].count()[0]\n\n\nFeroz_field=matches[(matches['toss_winner']==matches['winner'])&\n                  (matches['venue']=='Feroz Shah Kotla')&\n                  (matches['toss_decision']=='field')].count()[0]\nFeroz_bat=matches[(matches['toss_winner']!=matches['winner'])&\n                    (matches['venue']=='Feroz Shah Kotla')&\n                    (matches['toss_decision']!='field')].count()[0]\n\nWankhede_field=matches[(matches['toss_winner']==matches['winner'])&\n                     (matches['venue']=='Wankhede Stadium')& \n                     (matches['toss_decision']=='field')].count()[0]\nWankhede_bat=matches[(matches['toss_winner']!=matches['winner'])\n                       &(matches['venue']=='Wankhede Stadium')\n                       & (matches['toss_decision']!='field')].count()[0]\n\nRG_field=matches[(matches['toss_winner']==matches['winner'])\n               &(matches['venue']=='Rajiv Gandhi International Stadium, Uppal')& \n               (matches['toss_decision']=='field')].count()[0]\nRG_bat=matches[(matches['toss_winner']!=matches['winner'])&\n                 (matches['venue']=='Rajiv Gandhi International Stadium, Uppal')\n                 & (matches['toss_decision']!='field')].count()[0]\n\nfig = go.Figure(data=[\n    go.Bar(name='Rajiv Gandhi International Stadium, Uppal', \n           x=['Field','Bat'],\n           y=[RG_field,RG_bat]),\n    go.Bar(name='Wankhede Stadium',\n           x=['Field','Bat'], \n           y=[Wankhede_field,Wankhede_bat]),\n    go.Bar(name='Feroz Shah Kotla', \n           x=['Field','Bat'],\n           y=[Feroz_field,Feroz_bat]),\n    go.Bar(name='Eden Gardens',\n           x=['Field','Bat'], \n           y=[Eden_field,Eden_bat]),\n    go.Bar(name='M Chinnaswamy Stadium', \n           x=['Field','Bat'],\n           y=[chinnaswamy_field,chinnaswamy_bat]),\n])\n# Change the bar mode\nfig.update_layout(title='Match results comparison with toss Decision results in various venues')\nfig.update_layout(\n    xaxis_title=\"Field \/ Bat\",\n    yaxis_title=\"Count\",\n    legend_title=\"Venue Name\",\n)\nfig.show()\n# teams with most wins\nmatches['winner'].value_counts()[:5]\n\n# Number of matches played per venue\nfig = px.bar(matches, x=matches['winner'].value_counts().keys()[:5],\n             y=matches['winner'].value_counts()[:5],\n             color=matches['winner'].value_counts().keys()[:5],\n             labels={\n                     'x': \"Team name\",\n                     'y': \"Total number of Matches Won\"\n                     \n                 })\nfig.update_layout(title='Top five most consistant teams throught the IPL Seasons')\nfig.show()\nMumbai_field=matches[(matches['winner']=='Mumbai Indians')& \n        (matches['toss_winner']=='Mumbai Indians')&\n       (matches['toss_decision']=='field')].count()[0]\nMumbai_bat=matches[(matches['winner']=='Mumbai Indians')& \n        (matches['toss_winner']=='Mumbai Indians')&\n       (matches['toss_decision']!='field')].count()[0]\n\nKolkata_field=matches[(matches['winner']=='Kolkata Knight Riders')& \n        (matches['toss_winner']=='Kolkata Knight Riders')&\n       (matches['toss_decision']=='field')].count()[0]\nKolkata_bat=matches[(matches['winner']=='Kolkata Knight Riders')& \n        (matches['toss_winner']=='Kolkata Knight Riders')&\n       (matches['toss_decision']!='field')].count()[0]\n\nChennai_field=matches[(matches['winner']=='Chennai Super Kings')& \n        (matches['toss_winner']=='Chennai Super Kings')&\n       (matches['toss_decision']=='field')].count()[0]\nChennai_bat=matches[(matches['winner']=='Chennai Super Kings')& \n        (matches['toss_winner']=='Chennai Super Kings')&\n       (matches['toss_decision']!='field')].count()[0]\n\nBangalore_field=matches[(matches['winner']=='Royal Challengers Bangalore')& \n        (matches['toss_winner']=='Royal Challengers Bangalore')&\n       (matches['toss_decision']=='field')].count()[0]\nBangalore_bat=matches[(matches['winner']=='Royal Challengers Bangalore')& \n        (matches['toss_winner']=='Royal Challengers Bangalore')&\n       (matches['toss_decision']!='field')].count()[0]\n\nPunjab_field=matches[(matches['winner']=='Kings XI Punjab')& \n        (matches['toss_winner']=='Kings XI Punjab')&\n       (matches['toss_decision']=='field')].count()[0]\nPunjab_bat=matches[(matches['winner']=='Kings XI Punjab')& \n        (matches['toss_winner']=='Kings XI Punjab')&\n       (matches['toss_decision']!='field')].count()[0]\n\nfig = go.Figure(data=[\n    go.Bar(name='Mumbai Indians', \n           x=['Field','Bat'],\n           y=[Mumbai_field,Mumbai_bat]),\n    go.Bar(name='Kolkata Knight Riders',\n           x=['Field','Bat'], \n           y=[Kolkata_field,Kolkata_bat]),\n    go.Bar(name='Chennai Super Kings', \n           x=['Field','Bat'],\n           y=[Chennai_field,Feroz_bat]),\n    go.Bar(name='Royal Challengers Bangalore',\n           x=['Field','Bat'], \n           y=[Bangalore_field,Bangalore_bat]),\n    go.Bar(name='Kings XI Punjab', \n           x=['Field','Bat'],\n           y=[Punjab_field,Punjab_bat]),\n])\n\n\n# Change the bar mode\nfig.update_layout(title='Match results comparison with toss Decision results in various Teams')\nfig.update_layout(\n    xaxis_title=\"Field \/ Bat\",\n    yaxis_title=\"Count\",\n    legend_title=\"Team Name\",\n)\nfig.show()\n# Number of times 10 wicket victory\nmatches[matches['win_by_wickets']==10]['winner'].value_counts()\n#teams with 10 wicket victory\nfig = px.pie(matches,\n             values=matches[matches['win_by_wickets']==10]['winner'].value_counts(), \n             names=matches[matches['win_by_wickets']==10]['winner'].value_counts().keys(),\n            color_discrete_sequence=px.colors.sequential.RdBu)\nfig.update_layout(\n    title='Teams with 10 wicket victory',\n    legend_title=\"Team Name \"\n)\nfig.show()\nmatches[matches['win_by_runs']>50]['winner'].value_counts()\n# sub plot piecharts\nfrom plotly.subplots import make_subplots\n\n\nfig = make_subplots(1, 2, specs=[[{'type':'domain'}, {'type':'domain'}]],\n                    subplot_titles=['Win By Runs >50', 'Win by 10 wickets'])\n\nfig.add_trace(go.Pie(labels=matches[matches['win_by_runs']>50]['winner'].value_counts().keys(),\n                     values=matches[matches['win_by_runs']>50]['winner'].value_counts(),\n                     scalegroup='one',\n                    ),\n                      1, 1)\n\nfig.add_trace(go.Pie(labels=matches[matches['win_by_wickets']==10]['winner'].value_counts().keys(), \n                     values=matches[matches['win_by_wickets']==10]['winner'].value_counts(), \n                     scalegroup='one'), 1, 2)\n\nfig.update_layout(\n    title='Brilliant performance by various teams',\n    legend_title=\"Team Name\",\n)\nfig.show()\numpire1=matches['umpire1'].value_counts()\numpire2=matches['umpire2'].value_counts()\nnew_umpire={}\nfor i in umpire1.keys():\n    if i in umpire2:\n        new_umpire[i]=umpire1[i]+umpire2[i]\n    else:\n        new_umpire[i]=umpire1[i]\n\n\nfig = px.bar(matches, x=list(new_umpire.keys())[:5],\n             y=list(new_umpire.values())[:5],\n             color=list(new_umpire.keys())[:5],\n             labels={\n                     'x': \"Umpire Name\",\n                     'y': \"Total number of Matches\"\n                     \n                 })\nfig.update_layout(title='Top five most consistant Umpires throught the IPL Seasons')\nfig.show()\n#load deliveries dataset\ndeliveries= pd.read_csv('\/kaggle\/input\/ipl-dataset-2017\/IPL data\/deliveries.csv')\ndeliveries.head()\ndeliveries.info()\ndeliveries.describe()\n\"\"\"\n# Data Analysis\n\"\"\"\nfig = px.bar(matches, x=deliveries['dismissal_kind'].value_counts().keys(),\n             y=deliveries['dismissal_kind'].value_counts(),\n             color=deliveries['dismissal_kind'].value_counts().keys(),\n             labels={\n                     'x': \"Medium of Dismissal\",\n                     'y': \"Total number of Dismissals\"\n                     \n                 })\nfig.update_layout(title='Number of Dismissials')\nfig.show()\nprint(\"Number of super overs {}\".format(len(deliveries[deliveries['is_super_over']==1]['match_id'].unique())))\nbowlers=dict.fromkeys(list(deliveries['bowler'].unique()),0)\nwicket_bowls=deliveries[deliveries.player_dismissed.isnull()==False]\nfor i in range(wicket_bowls.shape[0]):\n    bowlers[wicket_bowls.iloc[i]['bowler']]+=1\nbowlers=dict(sorted(bowlers.items(), key=lambda item: item[1],reverse=True))\ny=list(bowlers.values())[:20]\nx=list(bowlers.keys())[:20]\nbw=x\nfig = px.scatter(x=x, y=y ,color=x, size=y , labels={\n                     'x': \"Bowler Name\",\n                     'y': \"Number of wickets\",\n                     'color':'Player Name'\n                     \n                 })\nfig.update_layout(title='Number of dismissal by each bowler (Top 20)')\nfig.show()\ndeliveries['batsman_runs'].value_counts()\n\nfig = px.bar(matches, x=deliveries['batsman_runs'].value_counts().keys(),\n             y=deliveries['batsman_runs'].value_counts(),\n             color=deliveries['batsman_runs'].value_counts().keys(),\n             labels={\n                     'x': \"Run value\",\n                     'y': \"Total number\"\n                     \n                 })\nfig.update_layout(title='Count for each Run types')\nfig.show()\ncre_runs=deliveries['batsman_runs'].value_counts()\nprint(cre_runs)\nwides=deliveries['wide_runs'].sum()\nbye=deliveries['bye_runs'].sum()\nlegbye=deliveries['legbye_runs'].sum()\nnoball=deliveries['noball_runs'].sum()\npenalty=deliveries['penalty_runs'].sum()\n\ny=[wides,bye,legbye,noball,penalty]\nx=['wide_runs','bye_runs','legbye_runs','noball_runs', 'penalty_runs']\nfig = px.pie(deliveries,\n             values=y, \n             names=x)\nfig.update_layout(\n    title='Extra Runs',\n    legend_title=\"Extra Runs medium \"\n)\nfig.show()\nbowlers=dict.fromkeys(deliveries['bowler'].unique(),0)\nfor i in range(deliveries.shape[0]):\n    if deliveries.iloc[i]['wide_runs']>0:\n        bowlers[deliveries.iloc[i]['bowler']]+=1\nbowlers=dict(sorted(bowlers.items(), key=lambda item: item[1],reverse=True))\ny=list(bowlers.values())[:5]\nx=list(bowlers.keys())[:5]\n\nfig = px.scatter(x=x, y=y ,color=x, size=y , labels={\n                     'x': \"Bowler Name\",\n                     'y': \"Number of wide balls\",\n                     'color':'Player Name'\n                     \n                 })\nfig.update_layout(title='Number of wides by each bowler (Top 5)')\nfig.show()\nbowlers=dict.fromkeys(deliveries['bowler'].unique(),0)\nfor i in range(deliveries.shape[0]):\n    if deliveries.iloc[i]['bye_runs']>0:\n        bowlers[deliveries.iloc[i]['bowler']]+=1\nbowlers=dict(sorted(bowlers.items(), key=lambda item: item[1],reverse=True))\ny=list(bowlers.values())[:5]\nx=list(bowlers.keys())[:5]\n\nfig = px.scatter(x=x, y=y ,color=x, size=y , labels={\n                     'x': \"Bowler Name\",\n                     'y': \"Number of byes balls\",\n                     'color':'Player Name'\n                     \n                 })\nfig.update_layout(title='Number of byes by each bowler (Top 5)')\nfig.show()\nbowlers=dict.fromkeys(deliveries['bowler'].unique(),0)\nfor i in range(deliveries.shape[0]):\n    if deliveries.iloc[i]['noball_runs']>0:\n        bowlers[deliveries.iloc[i]['bowler']]+=1\nbowlers=dict(sorted(bowlers.items(), key=lambda item: item[1],reverse=True))\ny=list(bowlers.values())[:5]\nx=list(bowlers.keys())[:5]\n\nfig = px.scatter(x=x, y=y ,color=x, size=y , labels={\n                     'x': \"Bowler Name\",\n                     'y': \"Number of noball balls\",\n                     'color':'Player Name'\n                     \n                 })\nfig.update_layout(title='Number of noball by each bowler (Top 5)')\nfig.show()","meta":"{'source': 'AI4Code', 'id': '7d66815b2cbac6'}"}
{"id":"13234","text":"\"\"\"\n## This notebook is a fork from below the excellent notebook with a little tweak\n\nhttps:\/\/www.kaggle.com\/rakibilly\/extract-audio-starter\n\n\n## Therefore please upvote the original one .\n\"\"\"\n\"\"\"\n### Here we are trying to convert videos into wav file from a folder and then trying to find out if there are any audio fakes . We can replace the train_video_sample folder to any folder . Next version , will save the generated images and create dataset for CNN.\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport subprocess\nimport glob\nimport os\nfrom pathlib import Path\nimport shutil\nfrom zipfile import ZipFile\nfrom scipy import signal\nfrom scipy.io import wavfile\nfrom skopt import gp_minimize\nfrom skopt.space import Real\nfrom functools import partial\nimport librosa.display\nimport librosa.filters\nimport matplotlib.pyplot as plt\nimport skimage\n\"\"\"\nUsing the Static Build of ffmpeg from https:\/\/johnvansickle.com\/ffmpeg\/ because internet is not available. <br>\nThe public data set can be found here:\nhttps:\/\/www.kaggle.com\/rakibilly\/ffmpeg-static-build\n\n\"\"\"\n! tar xvf ..\/input\/ffmpeg-static-build\/ffmpeg-git-amd64-static.tar.xz\n\"\"\"\n### Specify output format and create a directory for the output Audio files\nFor 400 mp3 files, the directory is approx 94 MB.<br>\nFor 400 wav files, the directory is approx 673 MB.\n\"\"\"\nDATA_FOLDER = '..\/input\/deepfake-detection-challenge\/'\nTRAIN_SAMPLE_FOLDER = 'train_sample_videos\/'\nTEST_FOLDER = 'test_videos\/'\nDATA_PATH = os.path.join(DATA_FOLDER,TRAIN_SAMPLE_FOLDER)\nos.makedirs('\/kaggle\/working\/output', exist_ok=True)\nos.makedirs('\/kaggle\/working\/test_output', exist_ok=True)\nOUTPUT_PATH = '\/kaggle\/working\/output'\nTEST_OUTPUT_PATH = '\/kaggle\/working\/test_output\/'\nprint(f\"Train samples: {len(os.listdir(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER)))}\")\nprint(f\"Test samples: {len(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER)))}\")\nSPLIT='00'\ntrain_list = list(os.listdir(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER)))\next_dict = []\nfor file in train_list:\n    file_ext = file.split('.')[1]\n    if (file_ext not in ext_dict):\n        ext_dict.append(file_ext)\nprint(f\"Extensions: {ext_dict}\")      \njson_file = [file for file in train_list if  file.endswith('json')][0]\nprint(f\"JSON file: {json_file}\")\ndef get_meta_from_json(path):\n    df = pd.read_json(os.path.join(DATA_FOLDER, path, json_file))\n    df = df.T\n    return df\n\nmeta_train_df = get_meta_from_json(TRAIN_SAMPLE_FOLDER)\nmeta_train_df.head(20)\noutput_format = 'wav'  # can also use aac, wav, etc\n\noutput_dir = Path(f\"{output_format}s\")\nPath(output_dir).mkdir(exist_ok=True, parents=True)\nfake_name ='aaeflzzhvy'\nreal_name = 'flqgmnetsg'\nmeta = (list(meta_train_df.index))\n\"\"\"\n### Get the list of videos to extract audio from\n\"\"\"\nINPUT_PATH = '..\/input\/realfake045\/assorted\/'\nWAV_PATH = '.\/wavs\/'\nlist_of_files = []\nfor file in os.listdir(os.path.join(DATA_FOLDER,TRAIN_SAMPLE_FOLDER)):\n    filename = os.path.join(DATA_FOLDER,TRAIN_SAMPLE_FOLDER)+file\n    list_of_files.append(filename)\n\"\"\"\n### Extract the audio from files\n\"\"\"\ndef create_wav(list_of_files):\n    for file in list_of_files:\n        command = f\"..\/working\/ffmpeg-git-20191209-amd64-static\/ffmpeg -i {file} -ab 192000 -ac 2 -ar 44100 -vn {output_dir\/file[-14:-4]}.{output_format}\"\n        subprocess.call(command, shell=True)\n%%time\ncreate_wav(list_of_files)\ndef create_spectogram(name,sr):\n    audio_array, sample_rate = librosa.load(WAV_PATH+f'{name}', sr=sr)\n    trim_audio_array, index = librosa.effects.trim(audio_array)\n    S = librosa.feature.melspectrogram(y=trim_audio_array, sr=sr, n_mels=128, fmax=8000)\n    S_dB = np.log(S + 1e-9)\n    # min-max scale to fit inside 8-bit range\n    img = scale_minmax(S_dB, 0, 255).astype(np.uint8)\n    img = np.flip(img, axis=0) # put low frequencies at the bottom in image\n    img = 255-img # invert. make black==more energy\n    #S_dB = librosa.power_to_db(S, ref=np.max)\n    return S_dB ,img\n\ndef scale_minmax(X, min=0.0, max=1.0):\n    X_std = (X - X.min()) \/ (X.max() - X.min())\n    X_scaled = X_std * (max - min) + min\n    return X_scaled\n%%time\ni=0\nsr=20000\nfor index,row in meta_train_df.iterrows():\n    if row.label == 'FAKE':\n        if os.path.exists(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER,row.original)):\n              if os.path.exists(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER,index)):\n                    fake_name = index.split('.')[0]+'.wav'\n                    real_name =row.original.split('.')[0]+'.wav'\n                    S_fake,img_fake =create_spectogram(fake_name,sr)\n                    S_real,img_real =create_spectogram(real_name,sr)\n                    if not(np.array_equal(S_fake,S_real)):\n                        diff = np.sum(np.abs(S_real - S_fake))\n                        print(f\"There is a difference in Audio : {diff}\")\n                        plt.figure(figsize=(10, 4))\n                        plt.axis('off')\n                        #librosa.display.specshow(S_fake, x_axis='time',\n                        #          y_axis='mel', sr=sr,\n                        #          fmax=8000)\n                        plt.imshow(img_fake,cmap='gray')\n                        plt.colorbar(format='%+2.0f dB')\n                        plt.title(f'Mel-frequency spectrogram Fake name {fake_name}')\n                        plt.tight_layout()\n                        plt.show()\n                        plt.figure(figsize=(10, 4))\n                        plt.axis('off')\n                        #librosa.display.specshow(S_real, x_axis='time',\n                        #          y_axis='mel', sr=sr,\n                        #          fmax=8000)\n                        plt.imshow(img_real,cmap='gray')\n                        plt.colorbar(format='%+2.0f dB')\n                        plt.title(f'Mel-frequency spectrogram Real name {real_name}')\n                        plt.tight_layout()\n                        plt.show()\n            \n    i=i+1 \n\"\"\"\n### Create ZIP file\n\"\"\"\nwith ZipFile(f'all_{output_format}s.zip', 'w') as zipObj:\n   # Iterate over all the files in directory\n   for folderName, subfolders, filenames in os.walk(f'.\/{output_format}s\/'):\n       for filename in filenames:\n           #create complete filepath of file in directory\n           filePath = os.path.join(folderName, filename)\n           # Add file to zip\n           zipObj.write(filePath)\n\"\"\"\n#### Cleanup\n\"\"\"\n#Remove FFMPEG directory from output\nshutil.rmtree(\"..\/working\/ffmpeg-git-20191209-amd64-static\")\n#Remove directory of output files\nshutil.rmtree(f'.\/{output_format}s\/')","meta":"{'source': 'AI4Code', 'id': '18236434183ea8'}"}
{"id":"71839","text":"# 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\n\"\"\"\n# \u0421\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435\n\"\"\"\n\"\"\"\n1. [\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445](#load_data)\n2. [\u041f\u0440\u0438\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0442\u0438\u043f\u043e\u0432](#cast_data)\n3. [EDA \u0438 \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445](#eda)\n    *  [\u0410\u043d\u0430\u043b\u0438\u0437 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439   ](#target_analysis)\n    *  [\u0410\u043d\u0430\u043b\u0438\u0437 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#features_analysis) \n        *  [\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438](#num_features)\n            *  [Rooms](#rooms)\n            *  [KitchenSquare](#kitchen_square)    \n            *  [Square](#square)   \n            *  [LifeSquare](#life_square)\n            *  [HouseFloor](#house_floor)\n            *  [Floor](#floor)\n            *  [HouseYear](#house_year)\n            *  [Healthcare_1](#healthcare_1)\n        *  [\u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438](#cat_features) \n            *  [DistrictId](#district_id)\n            *  [Ecology_2](#ecology_2)\n            *  [Ecology_3](#ecology_3)\n            *  [Shops_2](#shops_2)\n        *  [\u041c\u0430\u0442\u0440\u0438\u0446\u0430 \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0439](#correlation_matrix)\n    *  [\u0410\u043d\u0430\u043b\u0438\u0437 \u0432\u043b\u0438\u044f\u043d\u0438\u044f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u043d\u0430 \u0442\u0430\u0440\u0433\u0435\u0442](#feature_target_analysis)\n4. [\u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 DataPreprocessing](#data_preprocessing_class)\n5. [\u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#feature_generation)\n    *  [Dummies](#dummies)\n    *  [DistrictSize, IsDistrictLarge](#district_size)\n    *  [MedPriceByDistrict](#med_price_by_district)\n    *  [MedPriceByFloorYear](#med_price_by_floor_year)\n6. [\u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 FeatureGenerator](#feature_generator)\n7. [\u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f Healthcare_1](#healthcare_1_model)\n8. [\u041e\u0442\u0431\u043e\u0440 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#features_select)\n9. [\u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043d\u0430 train \u0438 test](#train_test_split)\n10. [\u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438](#model)\n    * [\u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435](#fit_model)\n    * [\u041e\u0446\u0435\u043d\u043a\u0430 \u043c\u043e\u0434\u0435\u043b\u0438](#evaluate_model)\n    * [\u0412\u0430\u0436\u043d\u043e\u0441\u0442\u044c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](#feature_importance)\n    * [\u041a\u0440\u043e\u0441\u0441-\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044f](#cv_model)\n    * [\u041f\u043e\u0438\u0441\u043a \u043f\u043e \u0441\u0435\u0442\u043a\u0435](#grid_search)\n11. [\u041f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435](#test_preds)\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport random\nimport xgboost as xgb\n\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.metrics import r2_score as r2\nfrom sklearn.model_selection import KFold, GridSearchCV\nfrom catboost import CatBoostRegressor\n\nfrom datetime import datetime\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n# \u041e\u0442\u043a\u043b\u044e\u0447\u0430\u0435\u0442 \u0432\u044b\u0432\u043e\u0434 \u043f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436\u0434\u0435\u043d\u0438\u0439\nimport warnings\nwarnings.filterwarnings('ignore')\n# \u0417\u0430\u0434\u0430\u0435\u0442 \u0440\u0430\u0437\u043c\u0435\u0440 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432\nmatplotlib.rcParams.update({'font.size': 14})\ndef evaluate_preds(train_true_values, train_pred_values, test_true_values, test_pred_values):\n    \"\"\"\u0412\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u0442 \u043c\u0435\u0442\u0440\u0438\u043a\u0443 r2 \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438, \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0430\u0435\u0442 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0438 \u0438\u0441\u0442\u0438\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043d\u0430 \u0433\u0440\u0430\u0444\u0438\u043a\u0430\u0445\"\"\"\n    \n    print(\"Train R2:\\t\" + str(round(r2(train_true_values, train_pred_values), 3)))\n    print(\"Test R2:\\t\" + str(round(r2(test_true_values, test_pred_values), 3)))\n    \n    plt.figure(figsize=(18,10))\n    \n    plt.subplot(121)\n    sns.scatterplot(x=train_pred_values, y=train_true_values)\n    plt.xlabel('Predicted values')\n    plt.ylabel('True values')\n    plt.title('Train sample prediction')\n    \n    plt.subplot(122)\n    sns.scatterplot(x=test_pred_values, y=test_true_values)\n    plt.xlabel('Predicted values')\n    plt.ylabel('True values')\n    plt.title('Test sample prediction')\n\n    plt.show()\n# \u041f\u0443\u0442\u0438 \u0434\u043e \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438\nTRAIN_DATASET_PATH = '..\/input\/real-estate-price-prediction-moscow\/train.csv'\nTEST_DATASET_PATH = '..\/input\/real-estate-price-prediction-moscow\/test.csv'\n\"\"\"\n# \u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445<a class='anchor' id='load_data'>\n\"\"\"\n\"\"\"\n**\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430**\n\n* **Id** - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b\n* **DistrictId** - \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \u0440\u0430\u0439\u043e\u043d\u0430\n* **Rooms** - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043a\u043e\u043c\u043d\u0430\u0442\n* **Square** - \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n* **LifeSquare** - \u0436\u0438\u043b\u0430\u044f \u043f\u043b\u043e\u0449\u0430\u0434\u044c\n* **KitchenSquare** - \u043f\u043b\u043e\u0449\u0430\u0434\u044c \u043a\u0443\u0445\u043d\u0438\n* **Floor** - \u044d\u0442\u0430\u0436\n* **HouseFloor** - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0432 \u0434\u043e\u043c\u0435\n* **HouseYear** - \u0433\u043e\u0434 \u043f\u043e\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u0434\u043e\u043c\u0430\n* **Ecology_1, Ecology_2, Ecology_3** - \u044d\u043a\u043e\u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438\n* **Social_1, Social_2, Social_3** - \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438\n* **Healthcare_1, Helthcare_2** - \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u043c\u0435\u0441\u0442\u043d\u043e\u0441\u0442\u0438, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u0441 \u043e\u0445\u0440\u0430\u043d\u043e\u0439 \u0437\u0434\u043e\u0440\u043e\u0432\u044c\u044f\n* **Shops_1, Shops_2** - \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u0441 \u043d\u0430\u043b\u0438\u0447\u0438\u0435\u043c \u043c\u0430\u0433\u0430\u0437\u0438\u043d\u043e\u0432, \u0442\u043e\u0440\u0433\u043e\u0432\u044b\u0445 \u0446\u0435\u043d\u0442\u0440\u043e\u0432\n* **Price** - \u0446\u0435\u043d\u0430 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b\n\"\"\"\n# \u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438\ntrain_df = pd.read_csv(TRAIN_DATASET_PATH)\ntrain_df.head()\ntrain_df.dtypes\n# \u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438\ntest_df = pd.read_csv(TEST_DATASET_PATH)\ntest_df.head()\ntest_df.dtypes\nprint('\u0427\u0438\u0441\u043b\u043e \u0441\u0442\u0440\u043e\u043a \u0432 \u0442\u0440\u0435\u0439\u043d\u0435: ', train_df.shape[0])\nprint('\u0427\u0438\u0441\u043b\u043e \u0441\u0442\u0440\u043e\u043a \u0432 \u0442\u0435\u0441\u0442\u0435: ', test_df.shape[0])\nprint('\u0427\u0438\u0441\u043b\u043e \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432 \u0432 \u0442\u0440\u0435\u0439\u043d\u0435: ', train_df.shape[1])\nprint('\u0427\u0438\u0441\u043b\u043e \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432 \u0432 \u0442\u0435\u0441\u0442\u0435: ', test_df.shape[1])\n\"\"\"\n# \u041f\u0440\u0438\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0442\u0438\u043f\u043e\u0432<a class='anchor' id='cast_data'>\n\"\"\"\ntrain_df.dtypes\n\"\"\"\n\u041d\u0435\u0441\u043c\u043e\u0442\u0440\u044f \u043d\u0430 \u0442\u043e, \u0447\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a DistrictId \u0438\u043c\u0435\u0435\u0442 \u0442\u0438\u043f int64, \u043e\u043d \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c. \u0422\u0430\u043a\u0436\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a Id - \u044d\u0442\u043e \u043f\u0440\u043e\u0441\u0442\u043e \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438. \u0427\u0442\u043e\u0431\u044b \u043e\u043d\u0438 \u043d\u0435 \u043c\u0435\u0448\u0430\u043b\u0438 \u043f\u0440\u0438 \u0430\u043d\u0430\u043b\u0438\u0437\u0435 \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0438\u0437\u043c\u0435\u043d\u0438\u043c \u0438\u0445 \u0442\u0438\u043f \u043d\u0430 str.\n\"\"\"\ntrain_df['Id'] = train_df['Id'].astype(str)\ntrain_df['DistrictId'] = train_df['DistrictId'].astype(str)\ntrain_df.dtypes\n\"\"\"\n# EDA \u0438 \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0434\u0430\u043d\u043d\u044b\u0445<a class='anchor' id='eda'>\n\"\"\"\n\"\"\"\n## \u0410\u043d\u0430\u043b\u0438\u0437 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 <a class='anchor' id='target_analysis'>\n\"\"\"\ntarget_name = 'Price'\n\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439\ntrain_df[target_name].describe()\n\"\"\"\n\u042d\u0442\u043e \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043c\u043e\u0434\u0430 \u043d\u0435 \u0438\u043c\u0435\u0435\u0442 \u0441\u043c\u044b\u0441\u043b\u0430. \u0412 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u043e\u043d\u0430 \u0431\u0443\u0434\u0435\u0442 \u0440\u0430\u0432\u043d\u0430 \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u043e \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u043e\u043c\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439. \u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u0434\u043b\u044f \u0441\u0440\u0435\u0434\u043d\u0435\u0439 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u043c\u0435\u0434\u0438\u0430\u043d\u044b \u0434\u043b\u044f \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f \u043d\u0430 \u0433\u0440\u0430\u0444\u0438\u043a\u0435 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f.\n\"\"\"\ntarget_mean = round(train_df[target_name].mean(), 2)\ntarget_median = train_df[target_name].median()\n\nprint(f'\u0421\u0440\u0435\u0434\u043d\u0435\u0435: {target_mean}\\n\u041c\u0435\u0434\u0438\u0430\u043d\u0430: {target_median}')\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0438\u043a\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439\nplt.figure(figsize = (16, 8))\n\nsns.distplot(train_df[target_name], bins=50)\n\ny = np.linspace(0, 7e-6, 10)\nplt.plot([target_mean] * 10, y, label='mean', linewidth=3)\nplt.plot([target_median] * 10, y, label='median', linewidth=3)\n\nplt.title('Distribution of target')\nplt.legend()\nplt.show()\n\"\"\"\n\u0418\u0437 \u0433\u0440\u0430\u0444\u0438\u043a\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0432\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442, \u0438 \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0442\u044c \u0446\u0435\u043b\u0435\u0432\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043d\u0435 \u043d\u0443\u0436\u043d\u043e.\n\"\"\"\n\"\"\"\n## \u0410\u043d\u0430\u043b\u0438\u0437 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432<a class='anchor' id='features_analysis'>\n\"\"\"\n\"\"\"\n### \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438<a class='anchor' id='num_features'>\n\"\"\"\n\"\"\"\n\u0412\u044b\u0431\u0435\u0440\u0435\u043c \u0432\u0441\u0435 \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438, \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u0434\u043b\u044f \u043d\u0438\u0445 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438 \u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0434\u043b\u044f \u043d\u0438\u0445 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b.\n\"\"\"\ntrain_df.dtypes\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ntrain_df.describe()\n\"\"\"\n\u0412\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 **LifeSquare** \u0438 **Healthcare_1** \u0438\u043c\u0435\u044e\u0442 \u043c\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0442\u0430\u043a\u0436\u0435 \u043d\u0443\u0436\u043d\u043e \u0431\u0443\u0434\u0435\u0442 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c \u0434\u043b\u044f \u0432\u0435\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ntrain_df.select_dtypes(include=['float64', 'int64']).drop(target_name, axis=1).hist(figsize=(16, 16), bins=20, grid=False)\nplt.show()\n\"\"\"\n\u0418\u0437 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c \u0432\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 **Rooms**, **Square**, **LifeSquare**, **KitchenSquare**, **Floor**, **HouseFloor**, **HouseYear** \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0438\u043c\u0435\u044e\u0442 \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u044d\u0442\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e.\n\"\"\"\n\"\"\"\n\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0432\u0441\u043f\u043e\u043c\u043e\u0433\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u043c\u0435\u0442\u043e\u0434\u043e\u0432 \u0434\u043b\u044f \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0438 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432.\n\"\"\"\ndef plot_feature_hist(feature_name, bins_count=20, ylog=False):\n    \"\"\"\u0421\u0442\u0440\u043e\u0438\u0442 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0434\u043b\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\"\"\"\n    \n    train_df[feature_name].hist(figsize=(10, 10), bins=bins_count, grid=False)\n    \n    plt.xlabel(feature_name)\n    plt.ylabel('Count')\n    plt.title(f'Distribution of {feature_name}')\n    \n    if ylog:\n        plt.yscale('log')\n    \n    plt.show()\ndef add_outlier_label_feature(outlier_condition, outlier_label_feature_name):\n    \"\"\"\u0414\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u0442 \u043d\u043e\u0432\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0441 \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u043c \u0438\u043c\u0435\u043d\u0435\u043c - \u043c\u0435\u0442\u043a\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u0430 \u0432 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438 \u043e\u0442 \u043f\u0435\u0440\u0435\u0434\u0430\u043d\u043d\u043e\u0433\u043e \u0432 \u043c\u0435\u0442\u043e\u0434 \u0443\u0441\u043b\u043e\u0432\u0438\u044f\"\"\"\n    \n    train_df[outlier_label_feature_name] = 0\n    train_df.loc[condition, outlier_label_feature_name] = 1\ndef get_and_print_quantile(feature_name):\n    \"\"\"\u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 2.5, 97.5 \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044c \u0438 \u0432\u044b\u0432\u043e\u0434\u0438\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043d\u0430 \u044d\u043a\u0440\u0430\u043d\"\"\"\n    \n    quantile025 = train_df[feature_name].quantile(.025)\n    quantile975 = train_df[feature_name].quantile(.975)\n    print(f'2.5 \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044c: {quantile025}')\n    print(f'97.5 \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044c: {quantile975}')\n    return quantile025, quantile975\n\"\"\"\n#### Rooms <a class='anchor' id='rooms'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f Rooms\nplot_feature_hist('Rooms', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f Rooms\ntrain_df['Rooms'].describe()\ntrain_df['Rooms'].value_counts()\n\"\"\"\n\u0415\u0441\u0442\u044c \u043d\u0435\u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 - 0 \u043a\u043e\u043c\u043d\u0430\u0442.\n\n\u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f - 6, 10, 19 \u043a\u043e\u043c\u043d\u0430\u0442.\n\"\"\"\n\"\"\"\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0431\u043e\u043b\u044c\u0448\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c.\n\"\"\"\ntrain_df.loc[(train_df['Rooms'] == 10) | (train_df['Rooms'] == 19) | (train_df['Rooms'] == 6)]\n\"\"\"\n\u041f\u043b\u043e\u0449\u0430\u0434\u044c Square \u043f\u0440\u0438\u043c\u0435\u0440\u043d\u043e \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u0442 2 \u043a\u043e\u043c\u043d\u0430\u0442\u0430\u043c, \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f Rooms >= 6 \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439.\n\"\"\"\n\"\"\"\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e 0.\n\"\"\"\ntrain_df.loc[train_df['Rooms'] == 0]\n\"\"\"\n\u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0438\u043c\u0435\u0435\u0442\u0441\u044f \u0432 \u0432\u0438\u0434\u0443 \u043a\u0430\u0440\u0442\u0438\u0440\u0430-\u0441\u0442\u0443\u0434\u0438\u044f, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0431\u044b\u043b\u043e \u0443\u043a\u0430\u0437\u0430\u043d\u043e 0 \u043a\u043e\u043c\u043d\u0430\u0442. \u0422\u0430\u043a\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0437\u0430\u043c\u0435\u043d\u0438\u043c 1.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\ncondition = (train_df['Rooms'] == 0) | (train_df['Rooms'] >= 6)\nadd_outlier_label_feature(condition, 'Rooms_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[condition]\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[train_df['Rooms'] == 0, 'Rooms'] = 1\ntrain_df.loc[train_df['Rooms'] >= 6, 'Rooms'] = train_df['Rooms'].median()\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df.loc[train_df['Rooms_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('Rooms')\n\"\"\"\n\u0412\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['Rooms'].describe()\ntrain_df['Rooms'].value_counts()\n\"\"\"\n#### KitchenSquare <a class='anchor' id='kitchen_square'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f KitchenSquare\nplot_feature_hist('KitchenSquare', bins_count=100, ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f KitchenSquare\ntrain_df['KitchenSquare'].describe()\ntrain_df['KitchenSquare'].value_counts()\n\"\"\"\n\u0415\u0441\u0442\u044c \u043d\u0435\u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 - 0, 1, 2 \u0438 \u0442.\u0434.\n\n\u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f - 1970, 2014.\n\"\"\"\n\"\"\"\n\u041d\u0435\u043f\u043e\u043d\u044f\u0442\u043d\u043e, \u043a\u0430\u043a \u0437\u0430\u0434\u0430\u0442\u044c \u0432\u0435\u0440\u0445\u043d\u044e\u044e \u0438 \u043d\u0438\u0436\u043d\u044e\u044e \u0433\u0440\u0430\u043d\u0438\u0446\u0443 \u0434\u043b\u044f \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c 2.5 \u0438 97.5 \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044c.\n\"\"\"\nquantile025, quantile975 = get_and_print_quantile('KitchenSquare')\n\"\"\"\n\u0412 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043f\u0440\u0430\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c 97.5 \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044c. \u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u043e\u043b\u044c\u0448\u0435 \u043f\u0440\u0430\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439.\n\n\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u0435 0 \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043d\u0435 \u043f\u043e\u0434\u0445\u043e\u0434\u0438\u0442. \u0417\u0430\u0434\u0430\u0434\u0438\u043c \u0434\u043b\u044f \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043f\u0440\u0438\u043c\u0435\u0440\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0432\u043d\u043e\u0435 3. \u041c\u0435\u043d\u044c\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0442\u0430\u043a\u0436\u0435 \u0437\u0430\u043c\u0435\u043d\u0438\u043c 3.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\nKitchenSquare_min = 3\ncondition = (train_df['KitchenSquare'] < KitchenSquare_min) | (train_df['KitchenSquare'] > quantile975)\nadd_outlier_label_feature(condition, 'KitchenSquare_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df.head()\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[train_df['KitchenSquare'] < KitchenSquare_min, 'KitchenSquare'] = KitchenSquare_min\ntrain_df.loc[train_df['KitchenSquare'] > quantile975, 'KitchenSquare'] = train_df['KitchenSquare'].median()\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['KitchenSquare_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('KitchenSquare')\n\"\"\"\n\u0422\u0435\u043f\u0435\u0440\u044c \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['KitchenSquare'].describe()\ntrain_df['KitchenSquare'].value_counts()\n\"\"\"\n#### Square <a class='anchor' id='square'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f Square\nplot_feature_hist('Square', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f Square\ntrain_df['Square'].describe()\n\"\"\"\n\u0415\u0441\u0442\u044c \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, min = 1.136.\n\n\u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c \u043f\u043e\u0434\u043e\u0437\u0440\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0431\u043e\u043b\u044c\u0448\u0435 200.\n\"\"\"\n\"\"\"\n\u0412\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u0438 \u0434\u043b\u044f \u043e\u0446\u0435\u043d\u043a\u0438 \u0433\u0440\u0430\u043d\u0438\u0446 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432.\n\"\"\"\nquantile025, quantile975 = get_and_print_quantile('Square')\n\"\"\"\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0433\u0434\u0435 Square \u0431\u043e\u043b\u044c\u0448\u0435 \u043f\u0440\u0430\u0432\u043e\u0433\u043e \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044f.\n\"\"\"\ntrain_df[train_df['Square'] > quantile975]\n\"\"\"\n\u0421\u0440\u0435\u0434\u0438 \u0442\u0430\u043a\u0438\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u0435\u0441\u0442\u044c \u0438 \u0445\u043e\u0440\u043e\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u043d\u0435 \u043f\u043e\u0445\u043e\u0436\u0438\u0435 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u0422.\u0435. \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b \u0441 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u044c\u044e \u0438 \u043f\u043e \u0432\u044b\u0441\u043e\u043a\u043e\u0439 \u0446\u0435\u043d\u0435. \u041a\u0432\u0430\u043d\u0442\u0438\u043b\u044c \u0432 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043f\u0440\u0430\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u043d\u0435 \u043f\u043e\u0434\u043e\u0439\u0434\u0435\u0442. \n\"\"\"\n\"\"\"\n\u0418\u0441\u0445\u043e\u0434\u044f \u0438\u0437 \u0432\u0438\u0434\u0430 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b, \u0440\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 250. \n\"\"\"\ntrain_df[train_df['Square'] > 250]\n\"\"\"\n\u041f\u043e\u0445\u043e\u0436\u0435 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b - \u0431\u043e\u043b\u044c\u0448\u0430\u044f \u043f\u043b\u043e\u0449\u0430\u0434\u044c \u043f\u043e \u043d\u0438\u0437\u043a\u043e\u0439 \u0446\u0435\u043d\u0435. \u041f\u0443\u0441\u0442\u044c \u043f\u0440\u0430\u0432\u0430\u044f \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0440\u0430\u0432\u043d\u0430 250.\n\"\"\"\nSquare_max = 250\n\"\"\"\n\u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u043c \u043b\u0435\u0432\u0443\u044e \u0433\u0440\u0430\u043d\u0438\u0446\u0443. \u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0433\u0434\u0435 Square \u043c\u0435\u043d\u044c\u0448\u0435 \u043b\u0435\u0432\u043e\u0433\u043e \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044f.\n\"\"\"\ntrain_df[train_df['Square'] < quantile025]\n\"\"\"\n\u0415\u0441\u0442\u044c \u0438 \u0445\u043e\u0440\u043e\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u043d\u0435 \u043f\u043e\u0445\u043e\u0436\u0438\u0435 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b \u0441 \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u043e\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u044c\u044e \u0438 \u043f\u043e \u043d\u0435\u0432\u044b\u0441\u043e\u043a\u043e\u0439 \u0446\u0435\u043d\u0435. \u041f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u0443\u043c\u0435\u043d\u044c\u0448\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435.\n\"\"\"\ntrain_df[train_df['Square'] < 20]\n\"\"\"\n\u041d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432\u043f\u043e\u043b\u043d\u0435 \u0445\u043e\u0440\u043e\u0448\u0438\u0435. \u0421\u0434\u0432\u0438\u043d\u0435\u043c \u0433\u0440\u0430\u043d\u0438\u0446\u0443 \u0435\u0449\u0435 \u043b\u0435\u0432\u0435\u0435.\n\"\"\"\ntrain_df[train_df['Square'] < 15]\n\"\"\"\n\u041f\u043e\u0445\u043e\u0436\u0435 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u0414\u043b\u044f \u0442\u0430\u043a\u043e\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u0438 \u0446\u0435\u043d\u044b \u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e \u0432\u044b\u0441\u043e\u043a\u0438\u0435. \u041f\u0443\u0441\u0442\u044c \u043b\u0435\u0432\u0430\u044f \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0440\u0430\u0432\u043d\u0430 15.\n\"\"\"\nSquare_min = 15\n\"\"\"\n\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432\u043d\u0435 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0430 (Square_min, Square_max) \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\ncondition = (train_df['Square'] < Square_min) | (train_df['Square'] > Square_max)\nadd_outlier_label_feature(condition, 'Square_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[condition]\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[condition, 'Square'] = train_df['Square'].median()\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['Square_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('Square', ylog=True)\n\"\"\"\n\u0412\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['Square'].describe()\n\"\"\"\n#### LifeSquare <a class='anchor' id='life_square'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f LifeSquare\nplot_feature_hist('LifeSquare', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f LifeSquare\ntrain_df['LifeSquare'].describe()\n\"\"\"\n\u0415\u0441\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438, \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u0441\u043d\u0430\u0447\u0430\u043b\u0430 \u0438\u0445. \u0412\u044b\u0432\u0435\u0434\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\ntrain_df['LifeSquare'].isna().sum()\n\"\"\"\n\u0414\u043e\u0431\u0430\u0432\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0430.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0430\ntrain_df['LifeSquare_nan'] = train_df['LifeSquare'].isna() * 1\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df.head()\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u043f\u043e \u0444\u043e\u0440\u043c\u0443\u043b\u0435, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u0434\u0440\u0443\u0433\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438, \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c.\n\n\u0412\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043d\u0430\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u0440\u0438\u043c\u0435\u0440\u043d\u043e Square \u0431\u043e\u043b\u044c\u0448\u0435, \u0447\u0435\u043c LifeSquare + KitchenSquare. \u0414\u043b\u044f \u044d\u0442\u043e\u0433\u043e \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0441\u0435\u0440\u0438\u044e \u0441 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u044f\u043c\u0438 \u0438 \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u0443 add_square_median.\n\n\u041f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0434\u043b\u044f LifeSquare \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043a\u0430\u043a Square - KitchenSquare - add_square_median.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0441\u0435\u0440\u0438\u0438 \u0441 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u044f\u043c\u0438 \u043c\u0435\u0436\u0434\u0443 Square \u0438 LifeSquare + KitchenSquare\nadd_square_series = train_df['Square'] - train_df['LifeSquare'] - train_df['KitchenSquare']\n\n# \u0412\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0434\u0438\u0430\u043d\u044b \u044d\u0442\u0438\u0445 \u0440\u0430\u0437\u043d\u043e\u0441\u0442\u0435\u0439\nadd_square_median = add_square_series[(add_square_series > 0) & (~add_square_series.isna())].median()\n\n# \u0417\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0434\u043b\u044f LifeSquare \u043f\u043e \u0444\u043e\u0440\u043c\u0443\u043b\u0435\ncondition = (train_df['LifeSquare'].isna()) & (~train_df['Square'].isna()) & (~train_df['KitchenSquare'].isna())\ntrain_df.loc[condition, 'LifeSquare'] = train_df.loc[condition, 'Square'] - train_df.loc[condition, 'KitchenSquare'] - add_square_median\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['LifeSquare_nan'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\nplot_feature_hist('LifeSquare', ylog=True)\n\"\"\"\n\u0420\u0430\u0437\u043d\u0438\u0446\u044b \u0441 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u043c \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u043c \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\ntrain_df['LifeSquare'].describe()\n\"\"\"\n\u041f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n\"\"\"\n\u0422\u0435\u043f\u0435\u0440\u044c \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u041f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0431\u043e\u043b\u0435\u0435 \u0434\u0435\u0442\u0430\u043b\u044c\u043d\u0443\u044e \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443.\n\"\"\"\ntrain_df['LifeSquare'].hist(figsize=(10, 10), bins=100, grid=False)\nplt.xlim([0, 250])\n\"\"\"\n\u0415\u0441\u0442\u044c \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, min = 0.37.\n\n\u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c \u043f\u043e\u0434\u043e\u0437\u0440\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0431\u043e\u043b\u044c\u0448\u0435 250.\n\"\"\"\n\"\"\"\n\u0412\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u0438 \u0434\u043b\u044f \u043e\u0446\u0435\u043d\u043a\u0438 \u0433\u0440\u0430\u043d\u0438\u0446 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432.\n\"\"\"\nquantile025, quantile975 = get_and_print_quantile('LifeSquare')\n\"\"\"\n\u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u0430\u0432\u043e\u0433\u043e \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044f \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0443\u0434\u0430\u043b\u0438\u0442 \u0438 \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u044b\u0435 \u0434\u0430\u043d\u043d\u044b\u0435. \u0418\u0441\u0445\u043e\u0434\u044f \u0438\u0437 \u0432\u0438\u0434\u0430 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b, \u0438\u0441\u0441\u043b\u0435\u0434\u0443\u0435\u043c \u0441\u0440\u0430\u0437\u0443 \u043f\u0440\u0430\u0432\u0443\u044e \u0433\u0440\u0430\u043d\u0438\u0446\u0443, \u0440\u0430\u0432\u043d\u0443\u044e 150.\n\"\"\"\ntrain_df[train_df['LifeSquare'] > 150]\n\"\"\"\n\u0415\u0441\u0442\u044c \u0438 \u0445\u043e\u0440\u043e\u0448\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 - \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b \u0441 \u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u044c\u044e \u0438 \u043f\u043e \u0432\u044b\u0441\u043e\u043a\u043e\u0439 \u0446\u0435\u043d\u0435. \u0421\u0434\u0432\u0438\u043d\u0435\u043c \u0433\u0440\u0430\u043d\u0438\u0446\u0443 \u0435\u0449\u0435 \u043f\u0440\u0430\u0432\u0435\u0435.\n\"\"\"\ntrain_df[train_df['LifeSquare'] > 250]\n\"\"\"\n\u042d\u0442\u0438 \u0434\u0430\u043d\u043d\u044b\u0435 \u043f\u043e\u0445\u043e\u0436\u0438 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b - \u0431\u043e\u043b\u044c\u0448\u0438\u0435 LifeSquare \u043f\u0440\u0438 \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0445 Square \u0438 \u043f\u0440\u0438 \u043d\u0438\u0437\u043a\u043e\u0439 \u0446\u0435\u043d\u0435. \u041f\u0443\u0441\u0442\u044c \u043f\u0440\u0430\u0432\u0430\u044f \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0440\u0430\u0432\u043d\u0430 250.\n\"\"\"\nLifeSquare_max = 250\n\"\"\"\n\u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u043c \u043b\u0435\u0432\u0443\u044e \u0433\u0440\u0430\u043d\u0438\u0446\u0443. \u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0433\u0434\u0435 Square \u043c\u0435\u043d\u044c\u0448\u0435 \u043b\u0435\u0432\u043e\u0433\u043e \u043a\u0432\u0430\u043d\u0442\u0438\u043b\u044f.\n\"\"\"\ntrain_df[train_df['LifeSquare'] < quantile025]\n\"\"\"\n\u0412\u0440\u043e\u0434\u0435 \u0435\u0441\u0442\u044c \u0438 \u0445\u043e\u0440\u043e\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f - \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b \u0441 \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u043c LifeSquare. \u0421\u0434\u0438\u0432\u043d\u0435\u043c \u0433\u0440\u0430\u043d\u0438\u0446\u0443 \u0435\u0449\u0435 \u043b\u0435\u0432\u0435\u0435.\n\"\"\"\ntrain_df[train_df['LifeSquare'] < 10]\n\"\"\"\n\u0421\u043b\u0438\u0448\u043a\u043e\u043c \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f - \u043f\u043e\u0445\u043e\u0436\u0435 \u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u041f\u0443\u0441\u0442\u044c \u043b\u0435\u0432\u0430\u044f \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0440\u0430\u0432\u043d\u0430 10.\n\"\"\"\nLifeSquare_min = 10\n\"\"\"\n\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432\u043d\u0435 \u0438\u043d\u0442\u0435\u0440\u0432\u0430\u043b\u0430 (LifeSquare_min, LifeSquare_max) \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\ncondition = (train_df['LifeSquare'] < LifeSquare_min) | (train_df['LifeSquare'] > LifeSquare_max)\nadd_outlier_label_feature(condition, 'LifeSquare_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[condition]\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[condition, 'LifeSquare'] = train_df['LifeSquare'].median()\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['LifeSquare_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('LifeSquare', ylog=True)\n\"\"\"\n\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0431\u043e\u043b\u044c\u0448\u0435 200 - \u044d\u0442\u043e \u043d\u0435 \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['LifeSquare'].describe()\n\"\"\"\n#### HouseFloor <a class='anchor' id='house_floor'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f HouseFloor\nplot_feature_hist('HouseFloor', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f HouseFloor\ntrain_df['HouseFloor'].describe()\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0441\u043f\u0438\u0441\u043a\u0430 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439\ntrain_df['HouseFloor'].sort_values().unique()\n\"\"\"\n\u041c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0432 \u041c\u043e\u0441\u043a\u0432\u0435 \u0440\u0430\u0432\u043d\u043e 95, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f 0, 99, 117 - \u044d\u0442\u043e \u0432\u044b\u0431\u0440\u043e\u0441\u044b. \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043a\u0430\u043a\u0438\u0435 \u044d\u0442\u0430\u0436\u0438 \u0434\u043b\u044f \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u0438\u0445 \u0434\u0430\u043d\u043d\u044b\u0445.\n\"\"\"\ntrain_df[train_df['HouseFloor'] == 0]\n\"\"\"\n\u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0434\u043b\u044f \u0442\u0430\u043a\u0438\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u043f\u043e\u0434\u043e\u0439\u0434\u0435\u0442 \u043c\u0435\u0434\u0438\u0430\u043d\u0430.\n\"\"\"\ntrain_df[train_df['HouseFloor'] > 90]\n\"\"\"\n\u0422\u0443\u0442 \u0442\u0430\u043a\u0436\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u0443.\n\"\"\"\n\"\"\"\n\u0412 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u043f\u0440\u0430\u0432\u043e\u0439 \u0433\u0440\u0430\u043d\u0438\u0446\u044b \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u043c 95.\n\"\"\"\nHouseFloor_max = 95\n\"\"\"\n\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u044f HouseFloor = 0 \u0438 \u0431\u043e\u043b\u044c\u0448\u0435 HouseFloor_max \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\ncondition = (train_df['HouseFloor'] == 0) | (train_df['HouseFloor'] > HouseFloor_max)\nadd_outlier_label_feature(condition, 'HouseFloor_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[condition]\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[condition, 'HouseFloor'] = train_df['HouseFloor'].median()\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['HouseFloor_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('HouseFloor', ylog=True)\n\"\"\"\n\u0412\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['HouseFloor'].describe()\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0441\u043f\u0438\u0441\u043a\u0430 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439\ntrain_df['HouseFloor'].sort_values().unique()\ntrain_df['HouseFloor'].value_counts()\n\"\"\"\n#### Floor <a class='anchor' id='floor'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f Floor\nplot_feature_hist('Floor', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f Floor\ntrain_df['Floor'].describe()\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0441\u043f\u0438\u0441\u043a\u0430 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439\ntrain_df['Floor'].sort_values().unique()\ntrain_df['Floor'].value_counts()\n\"\"\"\n\u0414\u0430\u043d\u043d\u044b\u0435 \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u044b\u0435. \u041e\u0447\u0435\u0432\u0438\u0434\u043d\u044b\u0445 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442, \u043d\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0442\u0430\u043a, \u0447\u0442\u043e \u0432 \u0434\u0430\u043d\u043d\u044b\u0445 Floor > HouseFloor. \u0422.\u0435. \u044d\u0442\u0430\u0436, \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0430 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u0430, \u0432\u044b\u0448\u0435, \u0447\u0435\u043c \u0432\u0441\u0435\u0433\u043e \u044d\u0442\u0430\u0436\u0435\u0439 \u0432 \u0434\u043e\u043c\u0435. \n\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0442\u0430\u043a\u0438\u0445 \u0441\u0442\u0440\u043e\u043a.\n\"\"\"\n(train_df['Floor'] > train_df['HouseFloor']).sum()\n\"\"\"\n\u0417\u0430\u043f\u0438\u0448\u0435\u043c \u0438\u043d\u0434\u0435\u043a\u0441\u044b \u0442\u0430\u043a\u0438\u0445 \u0441\u0442\u0440\u043e\u043a.\n\"\"\"\n# \u0418\u043d\u0434\u0435\u043a\u0441\u044b \u0441\u0442\u0440\u043e\u043a, \u0433\u0434\u0435 Floor > HouseFloor\nfloor_outliers = train_df.loc[train_df['Floor'] > train_df['HouseFloor']].index\nfloor_outliers\n\"\"\"\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043f\u043e\u0434\u0440\u043e\u0431\u043d\u0435\u0435.\n\"\"\"\ntrain_df.loc[floor_outliers]\n\"\"\"\n\u041e\u0442\u043c\u0435\u0442\u0438\u043c \u0442\u0430\u043a\u0438\u0435 \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u0432 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0435 HouseFloor_outlier.\n\"\"\"\n# \u0414\u043e\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 HouseFloor_outlier \u043d\u043e\u0432\u044b\u043c\u0438 \u043c\u0435\u0442\u043a\u0430\u043c\u0438 \u043e \u0432\u044b\u0431\u0440\u043e\u0441\u0430\u0445\ntrain_df.loc[floor_outliers, 'HouseFloor_outlier'] = 1\n\"\"\"\n\u0422\u0430\u043a\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u043c \u0446\u0435\u043b\u044b\u043c \u0447\u0438\u0441\u043b\u043e\u043c \u043e\u0442 1 \u0434\u043e HouseFloor. \u0417\u0430\u0444\u0438\u043a\u0441\u0438\u0440\u0443\u0435\u043c random.seed \u0434\u043b\u044f \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438.\n\"\"\"\nrandom.seed(100)\n\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u044d\u0442\u0430\u0436 \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u044b \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u043c \u0446\u0435\u043b\u044b\u043c \u0447\u0438\u0441\u043b\u043e\u043c \u0432 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0435 [1, HouseFloor)\ntrain_df.loc[floor_outliers, 'Floor'] = train_df.loc[floor_outliers, 'HouseFloor'].apply(lambda x: random.randint(1, x))\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df.loc[floor_outliers]\n\"\"\"\n\u041f\u0440\u043e\u0432\u0435\u0440\u0438\u043c, \u0447\u0442\u043e \u043f\u043e\u0441\u043b\u0435 \u0437\u0430\u043c\u0435\u043d\u044b \u0442\u0430\u043a\u0438\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 \u043d\u0435\u0442.\n\"\"\"\n(train_df['Floor'] > train_df['HouseFloor']).sum()\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('Floor', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['Floor'].describe()\ntrain_df['Floor'].value_counts()\n\"\"\"\n#### HouseYear <a class='anchor' id='house_year'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f HouseYear\nplot_feature_hist('HouseYear', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f HouseYear\ntrain_df['HouseYear'].describe()\ntrain_df['HouseYear'].value_counts()\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0441\u043f\u0438\u0441\u043a\u0430 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439\ntrain_df['HouseYear'].sort_values().unique()\n\"\"\"\n\u0415\u0441\u0442\u044c \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u0441\u043f\u0440\u0430\u0432\u0430 - \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f.\n\n\u0412\u044b\u0431\u0440\u043e\u0441\u044b \u0441\u043f\u0440\u0430\u0432\u0430 \u0431\u0443\u0434\u0435\u043c \u043e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0442\u044c \u0442\u0430\u043a: \u0435\u0441\u043b\u0438 \u0433\u043e\u0434 \u0431\u043e\u043b\u044c\u0448\u0435 \u0442\u0435\u043a\u0443\u0449\u0435\u0433\u043e \u0433\u043e\u0434\u0430, \u0442\u043e \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u0435\u0433\u043e \u043d\u0435 \u0442\u0435\u043a\u0443\u0449\u0438\u0439 \u0433\u043e\u0434.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u0430\ncurrent_year = datetime.now().year\ncondition = train_df['HouseYear'] > datetime.now().year\nadd_outlier_label_feature(condition, 'HouseYear_outlier')\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[condition]\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u0438\u043c \u0432\u044b\u0431\u0440\u043e\u0441\u044b.\n\"\"\"\n# \u0417\u0430\u043c\u0435\u043d\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df.loc[condition, 'HouseYear'] = current_year\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[train_df['HouseYear_outlier'] == 1]\n\"\"\"\n\u0415\u0449\u0435 \u0440\u0430\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438 \u0432\u044b\u0432\u0435\u0434\u0435\u043c \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\u0438.\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\nplot_feature_hist('HouseYear', ylog=True)\n\"\"\"\n\u0412\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u043d\u0435\u0442.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u043f\u043e\u0441\u043b\u0435 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\ntrain_df['HouseYear'].describe()\n\"\"\"\n#### Healthcare_1 <a class='anchor' id='healthcare_1'>\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b \u0434\u043b\u044f Healthcare_1\nplot_feature_hist('Healthcare_1', ylog=True)\n# \u0412\u044b\u0432\u043e\u0434 \u043e\u0441\u043d\u043e\u0432\u043d\u044b\u0445 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a \u0434\u043b\u044f Healthcare_1\ntrain_df['Healthcare_1'].describe()\n\"\"\"\n\u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0441\u043a\u0430\u0437\u0430\u0442\u044c, \u0435\u0441\u0442\u044c \u043b\u0438 \u0432\u044b\u0431\u0440\u043e\u0441\u044b, \u043e\u0434\u043d\u0430\u043a\u043e \u0435\u0441\u0442\u044c \u043c\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432.\n\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\ntrain_df['Healthcare_1'].isna().sum()\n\"\"\"\n\u041f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u043e\u0447\u0435\u043d\u044c \u043c\u043d\u043e\u0433\u043e - \u043f\u043e\u0447\u0442\u0438 \u043f\u043e\u043b\u043e\u0432\u0438\u043d\u0430 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0432\u0447\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438. \u041d\u0435\u043f\u043e\u043d\u044f\u0442\u043d\u043e \u043a\u0430\u043a \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0442\u044c \u044d\u0442\u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438.\n\n\u0414\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u043e\u0431\u0443\u0447\u0438\u043c \u043c\u043e\u0434\u0435\u043b\u044c [\u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f Healthcare_1](#healthcare_1_model).\n\"\"\"\n\"\"\"\n\u0414\u043e\u0431\u0430\u0432\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0430. \u041f\u0440\u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u043c\u043e\u0434\u0435\u043b\u0438 \u043d\u0430 \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u044d\u0442\u043e\u0442 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0434\u043b\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0430.\n\"\"\"\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0442\u043a\u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0430\ntrain_df['Healthcare_1_nan'] = train_df['Healthcare_1'].isna() * 1\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df.head()\n\"\"\"\n### \u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438<a class='anchor' id='cat_features'>\n\"\"\"\n\"\"\"\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u0432\u0441\u0435 \u043d\u043e\u043c\u0438\u043d\u0430\u0442\u0438\u0432\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 - \u0442\u0438\u043f\u0430 object.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u0432\u0441\u0435\u0445 \u043d\u043e\u043c\u0438\u043d\u0430\u0442\u0438\u0432\u043d\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ntrain_df.select_dtypes(include='object').columns.tolist()\n\"\"\"\n\u0418\u0441\u0441\u043b\u0435\u0434\u0443\u0435\u043c \u044d\u0442\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438.\n\"\"\"\n\"\"\"\n#### DistrictId <a class='anchor' id='district_id'>\n\"\"\"\n\"\"\"\n\u041d\u0435\u0441\u043c\u043e\u0442\u0440\u044f \u043d\u0430 \u0442\u043e, \u0447\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a DistrictId \u0438\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u0438\u043c\u0435\u0435\u0442 \u0442\u0438\u043f int64, \u043e\u043d \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c. \u0415\u0433\u043e \u043d\u0443\u0436\u043d\u043e \u0437\u0430\u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u0442\u044c.\n\"\"\"\ntrain_df['DistrictId'].value_counts()\n\"\"\"\n\u042d\u0442\u043e\u0442 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0437\u0430\u043a\u043e\u0434\u0438\u0440\u0443\u0435\u043c \u0447\u0435\u0440\u0435\u0437 \u0441\u0435\u0431\u044f - \u0447\u0435\u0440\u0435\u0437 value_counts, \u0442.\u0435. \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0447\u0430\u0441\u0442\u043e\u0442\u043d\u043e\u0435 \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435. \u041f\u043e\u043b\u0443\u0447\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a DistrictSize - \u043f\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0443 \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u043e\u043c \u0440\u0430\u0439\u043e\u043d\u0435.\n\"\"\"\n\"\"\"\n#### Ecology_2 <a class='anchor' id='ecology_2'>\n\"\"\"\ntrain_df['Ecology_2'].value_counts()\n\"\"\"\n\u0417\u0434\u0435\u0441\u044c \u0438\u0437 \u0441\u0442\u0440\u043e\u043a\u043e\u0432\u043e\u0433\u043e \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 \u0441\u0434\u0435\u043b\u0430\u0435\u043c \u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a: \n\nA \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043d\u0430 0, \n\nB \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043d\u0430 1.\n\"\"\"\n\"\"\"\n#### Ecology_3 <a class='anchor' id='ecology_3'>\n\"\"\"\ntrain_df['Ecology_3'].value_counts()\n\"\"\"\n\u0417\u0434\u0435\u0441\u044c \u0437\u0430\u043a\u043e\u0434\u0438\u0440\u0443\u0435\u043c \u0442\u0430\u043a \u0436\u0435, \u043a\u0430\u043a \u0434\u043b\u044f Ecology_2\n\"\"\"\n\"\"\"\n#### Shops_2 <a class='anchor' id='shops_2'>\n\"\"\"\ntrain_df['Shops_2'].value_counts()\n\"\"\"\n\u0417\u0434\u0435\u0441\u044c \u0437\u0430\u043a\u043e\u0434\u0438\u0440\u0443\u0435\u043c \u0442\u0430\u043a \u0436\u0435, \u043a\u0430\u043a \u0434\u043b\u044f Ecology_2\n\"\"\"\n\"\"\"\n### \u041c\u0430\u0442\u0440\u0438\u0446\u0430 \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0439 <a class='anchor' id='correlation_matrix'>\n\"\"\"\n\"\"\"\n\u041f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u043c\u0430\u0442\u0440\u0438\u0446\u0443 \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0439 \u0438 \u0438\u0437\u043e\u0431\u0440\u0430\u0437\u0438\u043c \u0435\u0435 \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043a\u0438.\n\"\"\"\nplt.figure(figsize=(20, 15))\n\nsns.set(font_scale=1.4)\n\n# \u0412\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u0438 \u043e\u043a\u0440\u0443\u0433\u043b\u0435\u043d\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0438\ncorr_matrix = train_df.corr()\ncorr_matrix = np.round(corr_matrix, 2)\n\n# \u0417\u0430\u043d\u0443\u043b\u0435\u043d\u0438\u0435 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u0430 \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0438 \u043c\u0435\u043d\u044c\u0448\u0435 0.3, \u0447\u0442\u043e\u0431\u044b \u043e\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u0441\u0430\u043c\u044b\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0435\ncorr_matrix[np.abs(corr_matrix) < 0.3] = 0\n\nsns.heatmap(corr_matrix, annot=True, linewidths=.5, cmap='coolwarm')\n\nplt.title('Correlation matrix')\nplt.show()\n\"\"\"\n\u041d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0441\u0438\u043b\u044c\u043d\u044b\u0435 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438 \u043f\u043e\u043d\u044f\u0442\u043d\u044b \u0438 \u043e\u0447\u0435\u0432\u0438\u0434\u043d\u044b. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u044c \u043c\u0435\u0436\u0434\u0443 Rooms \u0438 Square \u0438\u043b\u0438 LifeSquare \u0438 Square, HouseFloor \u0438 Floor.\n\n\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u0430\u044f \u043f\u0440\u044f\u043c\u0430\u044f \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u044c \u043c\u0435\u0436\u0434\u0443 Shops1 \u0438 Social_3. \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u044d\u0442\u043e \u043a\u0430\u043a-\u0442\u043e \u0441\u0432\u044f\u0437\u0430\u043d\u043e \u0441 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e\u043c \u043c\u0430\u0433\u0430\u0437\u0438\u043d\u043e\u0432 - \u0447\u0435\u043c \u0432\u044b\u0448\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044c, \u0442\u0435\u043c \u0432\u044b\u0448\u0435 \u043d\u0435\u043a\u0438\u0439 \u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044c Social_3.\n\n\u0412\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u0446\u0435\u043b\u0435\u0432\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0430\u044f **Price** \u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e \u0441\u0438\u043b\u044c\u043d\u043e \u0437\u0430\u0432\u0438\u0441\u0438\u0442 \u043e\u0442 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 **Rooms** \u0438 **Square**. \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0431\u0443\u0434\u0443\u0442 \u043f\u043e\u043b\u0435\u0437\u043d\u044b \u043d\u043e\u0432\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043d\u0430 \u0438\u0445 \u043e\u0441\u043d\u043e\u0432\u0435.\n\"\"\"\n\"\"\"\n\u0422\u0430\u043a\u0436\u0435 \u0435\u0441\u0442\u044c \u043e\u0447\u0435\u043d\u044c \u0441\u0438\u043b\u044c\u043d\u0430\u044f \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u044c \u043c\u0435\u0436\u0434\u0443 \u0434\u0432\u0443\u043c\u044f \u043d\u0435\u043f\u043e\u043d\u044f\u0442\u043d\u044b\u043c\u0438 Social_1 \u0438 Social_2.\n\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0433\u0440\u0430\u0444\u0438\u043a \u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u0438 \u044d\u0442\u0438\u0445 \u0434\u0432\u0443\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432.\n\"\"\"\ngrid = sns.jointplot(train_df['Social_1'], train_df['Social_2'], kind='reg')\ngrid.fig.set_figwidth(8)\ngrid.fig.set_figheight(8)\n\nplt.show()\n\"\"\"\n## \u0410\u043d\u0430\u043b\u0438\u0437 \u0432\u043b\u0438\u044f\u043d\u0438\u044f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u043d\u0430 \u0442\u0430\u0440\u0433\u0435\u0442 <a class='anchor' id='feature_target_analysis'>\n\"\"\"\n\"\"\"\n\u0418\u0437\u043e\u0431\u0440\u0430\u0437\u0438\u043c \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438 \u0446\u0435\u043b\u0435\u0432\u043e\u0433\u043e \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043e\u0442 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 Rooms \u0438 Square, \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c\u0438 \u0435\u0441\u0442\u044c \u043d\u0430\u0438\u0431\u043e\u043b\u044c\u0448\u0430\u044f \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u044c. \n\"\"\"\ngrid = sns.jointplot(train_df['Rooms'], train_df['Price'], kind='reg')\ngrid.fig.set_figwidth(8)\ngrid.fig.set_figheight(8)\n\nplt.show()\ngrid = sns.jointplot(train_df['Square'], train_df['Price'], kind='reg')\ngrid.fig.set_figwidth(8)\ngrid.fig.set_figheight(8)\n\nplt.show()\n\"\"\"\n# \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 DataPreprocessing <a class='anchor' id='data_preprocessing_class'>\n\"\"\"\nclass DataPreprocessing:\n    \"\"\"\u041f\u043e\u0434\u0433\u043e\u0442\u043e\u0432\u043a\u0430 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445\"\"\"\n    \n    def __init__(self):\n        \"\"\"\u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u043a\u043b\u0430\u0441\u0441\u0430\"\"\"\n        self.medians = None\n        self.modas = None\n        self.kitchen_square_quantile975 = None\n        self.add_square_median = None\n    \n    def fit(self, X):\n        \"\"\"\u0421\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435 \u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043a\"\"\"\n        self.medians = X.median()\n        self.modas = X.mode().iloc[0]\n        self.kitchen_square_quantile975 = X['KitchenSquare'].quantile(.975)\n        \n        # \u0412\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u0434\u043e\u0431\u0430\u0432\u043e\u0447\u043d\u043e\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u0438 \u043e\u0442 \u043e\u0431\u0449\u0435\u0439 \u043f\u043b\u043e\u0449\u0430\u0434\u0438, \u043a\u0443\u0434\u0430 \u043d\u0435 \u0432\u0445\u043e\u0434\u0438\u0442 \u0436\u0438\u043b\u0430\u044f \u043f\u043b\u043e\u0449\u0430\u0434\u044c \u0438 \u043f\u043b\u043e\u0449\u0430\u0434\u044c \u043a\u0443\u0445\u043d\u0438\n        add_square_series = X['Square'] - X['LifeSquare'] - X['KitchenSquare']\n        self.add_square_median = add_square_series[(add_square_series > 0) & (~add_square_series.isna())].median()\n        \n        self.num_features = ['Rooms', 'KitchenSquare', 'Square', 'LifeSquare', 'HouseFloor', 'Floor', 'HouseYear', 'Healthcare_1']\n        self.cat_features = ['DistrictId', 'Ecology_2', 'Ecology_3', 'Shops_2']\n    \n    def transform(self, X):\n        \"\"\"\u0422\u0440\u0430\u043d\u0441\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\"\"\"\n        \n        def add_outlier_label_feature(outlier_condition, outlier_label_feature_name):\n            X[outlier_label_feature_name] = 0\n            X.loc[condition, outlier_label_feature_name] = 1\n        \n        # Rooms\n        Rooms_max = 6\n        condition = (X['Rooms'] == 0) | (X['Rooms'] >= Rooms_max)\n        add_outlier_label_feature(condition, 'Rooms_outlier')\n\n        X.loc[X['Rooms'] == 0, 'Rooms'] = 1\n        X.loc[X['Rooms'] >= Rooms_max, 'Rooms'] = self.medians['Rooms']\n        \n        # KitchenSquare\n        KitchenSquare_min = 3\n        condition = (X['KitchenSquare'] < KitchenSquare_min) | (X['KitchenSquare'] > self.kitchen_square_quantile975)\n        add_outlier_label_feature(condition, 'KitchenSquare_outlier')\n        \n        X.loc[X['KitchenSquare'] < KitchenSquare_min, 'KitchenSquare'] = KitchenSquare_min\n        X.loc[X['KitchenSquare'] > self.kitchen_square_quantile975, 'KitchenSquare'] = self.medians['KitchenSquare']\n        \n        # Square\n        Square_min = 15\n        Square_max = 250\n        condition = (X['Square'] < Square_min) | (X['Square'] > Square_max)\n        add_outlier_label_feature(condition, 'Square_outlier')\n        \n        X.loc[condition, 'Square'] = self.medians['Square']\n        \n        # LifeSquare\n        # \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\n        X['LifeSquare_nan'] = X['LifeSquare'].isna() * 1\n        \n        condition = (X['LifeSquare'].isna()) & (~X['Square'].isna()) & (~X['KitchenSquare'].isna())\n        X.loc[condition, 'LifeSquare'] = X.loc[condition, 'Square'] - X.loc[condition, 'KitchenSquare'] - self.add_square_median\n        \n        # \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432\n        LifeSquare_min = 10\n        LifeSquare_max = 250\n        condition = (X['LifeSquare'] < LifeSquare_min) | (X['LifeSquare'] > LifeSquare_max)\n        add_outlier_label_feature(condition, 'LifeSquare_outlier')\n        \n        X.loc[condition, 'LifeSquare'] = self.medians['LifeSquare']\n        \n        # HouseFloor\n        HouseFloor_max = 95\n        condition = (X['HouseFloor'] == 0) | (X['HouseFloor'] > HouseFloor_max)\n        add_outlier_label_feature(condition, 'HouseFloor_outlier')\n        \n        X.loc[condition, 'HouseFloor'] = self.medians['HouseFloor']\n        \n        # Floor\n        floor_outliers = X.loc[X['Floor'] > X['HouseFloor']].index\n        X.loc[floor_outliers, 'HouseFloor_outlier'] = 1\n        \n        random.seed(21)\n        X.loc[floor_outliers, 'Floor'] = X.loc[floor_outliers, 'HouseFloor'].apply(lambda x: random.randint(1, x))\n        \n        # HouseYear\n        current_year = datetime.now().year\n        condition = X['HouseYear'] > current_year\n        add_outlier_label_feature(condition, 'HouseYear_outlier')\n        \n        X.loc[condition, 'HouseYear'] = current_year\n        \n        # Healthcare_1\n        # \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\n        X['Healthcare_1_nan'] = X['Healthcare_1'].isna() * 1\n        \n        X[self.num_features] = X[self.num_features].fillna(self.medians[self.num_features])\n        X[self.cat_features] = X[self.cat_features].fillna(self.modas[self.cat_features])\n        \n        return X\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 <a class='anchor' id='feature_generation'>\n\"\"\"\n\"\"\"\n## Dummies <a class='anchor' id='dummies'>\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f Ecology_2, Ecology_3, Shops_2 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0431\u0438\u043d\u0430\u0440\u043d\u043e\u0435 \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435.\n\"\"\"\nbinary_to_numbers = {'A': 0, 'B': 1}\n\n# \u0411\u0438\u043d\u0430\u0440\u043d\u043e\u0435 \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435\ntrain_df['Ecology_2'] = train_df['Ecology_2'].replace(binary_to_numbers)\ntrain_df['Ecology_3'] = train_df['Ecology_3'].replace(binary_to_numbers)\ntrain_df['Shops_2'] = train_df['Shops_2'].replace(binary_to_numbers)\n\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430\ntrain_df[['Ecology_2', 'Ecology_3', 'Shops_2']]\n\"\"\"\n## DistrictSize, IsDistrictLarge <a class='anchor' id='district_size'>\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f DistrcitId \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u0447\u0430\u0441\u0442\u043e\u0442\u043d\u043e\u0435 \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435.\n\n\u0414\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0440\u0430\u0439\u043e\u043d\u0430 DistrictId \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u043e\u043c \u0440\u0430\u0439\u043e\u043d\u0435 \u0438 \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0442\u0430\u0431\u043b\u0438\u0446\u0443, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 DistrictId \u0438 DistrictSize - \u0447\u0438\u0441\u043b\u043e \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u043e\u043c \u0440\u0430\u0439\u043e\u043d\u0435.\n\"\"\"\n# \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0442\u0430\u0431\u043b\u0438\u0446\u044b DistrictId \u0438 DistrictSize - \u0447\u0438\u0441\u043b\u043e \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u043e\u043c \u0440\u0430\u0439\u043e\u043d\u0435\ndistrict_size = train_df['DistrictId'].value_counts().reset_index().rename(columns={'index':'DistrictId', 'DistrictId':'DistrictSize'})\ndistrict_size.head()\n\"\"\"\n\u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u0442\u0430\u0431\u043b\u0438\u0446\u0443 \u043a \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u043c\u0443 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c\u0443 \u043f\u043e DistrictId. \u041f\u0440\u0438 \u044d\u0442\u043e\u043c \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0442\u0430\u043a, \u0447\u0442\u043e \u043f\u0440\u0438 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043f\u043e\u044f\u0432\u044f\u0442\u0441\u044f DistrictId, \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0435\u0442 \u0432 \u0442\u0430\u0431\u043b\u0438\u0446\u0435 district_size. \u0412 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u043c\u043e\u0434\u043e\u0439 DistrictSize.\n\"\"\"\n# \u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u044b \u043a \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435\ntrain_df = train_df.merge(district_size, on='DistrictId', how='left')\ntrain_df.head()\n\"\"\"\n\u0414\u043e\u0431\u0430\u0432\u0438\u043c \u043d\u043e\u0432\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043f\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0443 \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0432 \u044d\u0442\u043e\u043c \u0440\u0430\u0439\u043e\u043d\u0435 IsDistrictLarge. \u0413\u0440\u0430\u043d\u0438\u0446\u0443 \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u043c \u0440\u0430\u0432\u043d\u043e\u0439 100, \u0442.\u043a. \u043e\u043d\u0430 \u0434\u0435\u043b\u0438\u0442 \u0432\u0441\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f DistrictSize \u043f\u0440\u0438\u043c\u0435\u0440\u043d\u043e \u043d\u0430 2 \u0447\u0430\u0441\u0442\u0438.\n\"\"\"\n(train_df['DistrictSize'] > 100).value_counts()\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 IsDistrictLarge\ntrain_df['IsDistrictLarge'] = (train_df['DistrictSize'] > 100).astype(int)\ntrain_df.head()\n\"\"\"\n## MedPriceByDistrict <a class='anchor' id='med_price_by_district'>\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f \u044d\u0442\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0447\u0435\u0440\u0435\u0437 \u0446\u0435\u043b\u0435\u0432\u0443\u044e \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e.\n\n\u0421\u0433\u0440\u0443\u043f\u043f\u0438\u0440\u0443\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043f\u043e DistrictId \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0443 \u043a\u043e\u043c\u043d\u0430\u0442 \u0438 \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u0443 \u0446\u0435\u043d \u043a\u0432\u0430\u0440\u0442\u0438\u0440. \u042d\u0442\u043e \u0431\u0443\u0434\u0435\u0442 \u043d\u043e\u0432\u044b\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u043c \u0434\u043b\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0445 DistrictId \u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043a\u043e\u043c\u043d\u0430\u0442.\n\"\"\"\n# \u0413\u0440\u0443\u043f\u043f\u0438\u0440\u043e\u0432\u043a\u0430 \u043f\u043e DistrictId \u0438 Rooms \u0438 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0434\u0438\u0430\u043d\u044b \u0446\u0435\u043d\u044b \u043f\u043e \u0433\u0440\u0443\u043f\u043f\u0435\nmed_price_by_district = train_df.groupby(['DistrictId', 'Rooms'], as_index=False).agg({'Price':'median'}).rename(columns={'Price':'MedPriceByDistrict'})\nmed_price_by_district.head()\n\"\"\"\n\u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u0442\u0430\u0431\u043b\u0438\u0446\u0443 \u043a \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u043c\u0443 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c\u0443 \u043f\u043e DistrictId \u0438 Rooms. \n\"\"\"\n# \u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u044b \u043a \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435\ntrain_df = train_df.merge(med_price_by_district, on=['DistrictId', 'Rooms'], how='left')\ntrain_df.head()\n\"\"\"\n\u041f\u0440\u0438 \u044d\u0442\u043e\u043c \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0442\u0430\u043a, \u0447\u0442\u043e \u043f\u0440\u0438 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043f\u043e\u044f\u0432\u044f\u0442\u0441\u044f DistrictId, \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0435\u0442 \u0432 \u0442\u0430\u0431\u043b\u0438\u0446\u0435 med_price_by_district. \u0412 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439 MedPriceByDistrict.\n\"\"\"\n\"\"\"\n## MedPriceByFloorYear <a class='anchor' id='med_price_by_floor_year'>\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f \u044d\u0442\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043a\u043e\u0434\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0447\u0435\u0440\u0435\u0437 \u0446\u0435\u043b\u0435\u0432\u0443\u044e \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e.\n\n\u0421\u0433\u0440\u0443\u043f\u043f\u0438\u0440\u0443\u0435\u043c \u043f\u043e Floor \u0438 HouseYear \u0438 \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u043c \u043c\u0435\u0434\u0438\u0430\u043d\u0443 \u0446\u0435\u043d \u043a\u0432\u0430\u0440\u0442\u0438\u0440. \u042d\u0442\u043e \u0431\u0443\u0434\u0435\u0442 \u043d\u043e\u0432\u044b\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u043c \u0434\u043b\u044f \u0437\u0430\u0434\u0430\u043d\u043d\u044b\u0445 Floor \u0438 HouseYear.\n\"\"\"\n# \u0413\u0440\u0443\u043f\u043f\u0438\u0440\u043e\u0432\u043a\u0430 \u043f\u043e Floor \u0438 HouseYear \u0438 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u043c\u0435\u0434\u0438\u0430\u043d\u044b \u0446\u0435\u043d\u044b \u043f\u043e \u0433\u0440\u0443\u043f\u043f\u0435\nmed_price_by_floor_year = train_df.groupby(['Floor', 'HouseYear'], as_index=False).agg({'Price':'median'}).rename(columns={'Price':'MedPriceByFloorYear'})\nmed_price_by_floor_year.head()\n\"\"\"\n\u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u0442\u0430\u0431\u043b\u0438\u0446\u0443 \u043a \u0438\u0441\u0445\u043e\u0434\u043d\u043e\u043c\u0443 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c\u0443 \u043f\u043e Floor \u0438 HouseYear.\n\"\"\"\n# \u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u043e\u0439 \u0442\u0430\u0431\u043b\u0438\u0446\u044b \u043a \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435\ntrain_df = train_df.merge(med_price_by_floor_year, on=['Floor', 'HouseYear'], how='left')\ntrain_df.head()\n\"\"\"\n\u041f\u0440\u0438 \u044d\u0442\u043e\u043c \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0442\u0430\u043a, \u0447\u0442\u043e \u043f\u0440\u0438 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043f\u043e\u044f\u0432\u044f\u0442\u0441\u044f DistrictId, \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0435\u0442 \u0432 \u0442\u0430\u0431\u043b\u0438\u0446\u0435 med_price_by_floor_year. \u0412 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u0431\u0443\u0434\u0435\u043c \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u043c\u0435\u0434\u0438\u0430\u043d\u043e\u0439 MedPriceByFloorYear.\n\"\"\"\n\"\"\"\n# \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 FeatureGenerator <a class='anchor' id='feature_generator'>\n\"\"\"\nclass FeatureGenerator():\n    \"\"\"\u0413\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044f \u043d\u043e\u0432\u044b\u0445 \u0444\u0438\u0447\"\"\"\n    \n    def __init__(self):\n        self.binary_to_numbers = None\n        self.district_size = None\n        self.med_price_by_district = None\n        self.med_price_by_floor_year = None\n        self.med_price_by_district_median = None\n        self.med_price_by_floor_year_median = None\n        self.district_size_mode = None\n    \n    def fit(self, X, y=None):\n        # Binary features\n        self.binary_to_numbers = {'A': 0, 'B': 1}\n        \n        # DistrictSize\n        self.district_size = X['DistrictId'].value_counts().reset_index().rename(columns={'index':'DistrictId', 'DistrictId':'DistrictSize'})\n        self.district_size_mode = self.district_size['DistrictSize'].mode()[0]\n        \n        # Target encoding\n        if y is not None:\n            X_copy = X.copy()\n            X_copy['Price'] = y.values\n\n            # MedPriceByDistrict\n            self.med_price_by_district = X_copy.groupby(['DistrictId', 'Rooms'], as_index=False).agg({'Price':'median'}).rename(columns={'Price':'MedPriceByDistrict'})\n            self.med_price_by_district_median = self.med_price_by_district['MedPriceByDistrict'].median()\n            \n            # MedPriceByFloorYear \n            self.med_price_by_floor_year = X_copy.groupby(['Floor', 'HouseYear'], as_index=False).agg({'Price':'median'}).rename(columns={'Price':'MedPriceByFloorYear'})\n            self.med_price_by_floor_year_median = self.med_price_by_floor_year['MedPriceByFloorYear'].median()\n    \n    def transform(self, X):\n        # Binary features\n        X['Ecology_2'] = X['Ecology_2'].map(self.binary_to_numbers)\n        X['Ecology_3'] = X['Ecology_3'].map(self.binary_to_numbers)\n        X['Shops_2'] = X['Shops_2'].map(self.binary_to_numbers)\n        \n        # DistrictSize\n        X = X.merge(self.district_size, on='DistrictId', how='left')\n        X['DistrictSize'].fillna(self.district_size_mode, inplace=True)\n        \n        X['IsDistrictLarge'] = (X['DistrictSize'] > 100).astype(int)\n        \n        # Target encoding\n        # MedPriceByDistrict\n        if self.med_price_by_district is not None:\n            X = X.merge(self.med_price_by_district, on=['DistrictId', 'Rooms'], how='left')\n            X['MedPriceByDistrict'].fillna(self.med_price_by_district_median, inplace=True)\n        \n        # MedPriceByFloorYear\n        if self.med_price_by_floor_year is not None:\n            X = X.merge(self.med_price_by_floor_year, on=['Floor', 'HouseYear'], how='left')\n            X['MedPriceByFloorYear'].fillna(self.med_price_by_floor_year_median, inplace=True)\n        \n        return X\n\"\"\"\n# \u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f Healthcare_1 <a class='anchor' id='healthcare_1_model'>\n\"\"\"\n\"\"\"\n\u041f\u0440\u0438\u0437\u043d\u0430\u043a Healthcare_1 \u0438\u043c\u0435\u0435\u0442 \u043c\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432, \u0438 \u043d\u0435\u043f\u043e\u043d\u044f\u0442\u043d\u043e \u043a\u0430\u043a \u0438\u0445 \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0442\u044c.\n\n\u0414\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043e\u0431\u0443\u0447\u0438\u043c \u043c\u043e\u0434\u0435\u043b\u044c.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u0441\u043f\u0438\u0441\u043a\u0430 \u0432\u0441\u0435\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ntrain_df.columns.tolist()\n\"\"\"\n\u0414\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0432\u0441\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438, \u043a\u0440\u043e\u043c\u0435 **Id**, **DistrictId**, **Healthcare_1**, **Price**.\n\n\u0422\u0430\u043a\u0436\u0435 \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435, \u0433\u0434\u0435 Healthcare_1 \u043d\u0435 \u0438\u043c\u0435\u0435\u0442 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432.\n\"\"\"\n# \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0432\u043a\u043b\u044e\u0447\u0430\u0435\u0442 \u0442\u0430\u043a\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0435, \u0433\u0434\u0435 Healthcare_1 \u043d\u0435 \u0438\u043c\u0435\u0435\u0442 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\nX = train_df[~train_df['Healthcare_1'].isna()].drop(columns=['Id', 'DistrictId', 'Healthcare_1', 'Price'])\nX.head()\n# \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0446\u0435\u043b\u0435\u0432\u043e\u0433\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 - \u043f\u0440\u0438\u0437\u043d\u0430\u043a Healthcare_1 \u0431\u0435\u0437 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\ny = train_df.loc[~train_df['Healthcare_1'].isna(), 'Healthcare_1']\ny.head()\n# \u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043d\u0430 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u044b\u0439 \u0438 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u044b\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33, shuffle=True, random_state=21)\nX_train.shape, X_valid.shape\n\"\"\"\n\u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u043e\u0434\u0431\u0435\u0440\u043c \u0432\u0440\u0443\u0447\u043d\u0443\u044e.\n\"\"\"\n# \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438\nmodel = RandomForestRegressor(criterion='mse',\n                              max_depth=10,\n                              min_samples_leaf=10,\n                              random_state=21, \n                              n_estimators=100)\n\nmodel.fit(X_train, y_train)\n# \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f\ny_train_preds = model.predict(X_train)\ny_valid_preds = model.predict(X_valid)\n\nevaluate_preds(y_train, y_train_preds, y_valid, y_valid_preds)\n\"\"\"\n\u041f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u0445\u043e\u0440\u043e\u0448\u0438\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442. \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c \u0438 \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0432 Healthcare_1.\n\"\"\"\nclass HealthcareFiller():\n    \"\"\"\u041a\u043b\u0430\u0441\u0441 \u0434\u043b\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 Healthcare_1\"\"\"\n    \n    def __init__(self):\n        self.model = RandomForestRegressor(criterion='mse',\n                                           max_depth=10,\n                                           min_samples_leaf=10,\n                                           random_state=21, \n                                           n_estimators=100)\n        self.feature_names = ['Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear', \n                              'Ecology_1', 'Ecology_2', 'Ecology_3', 'Social_1', 'Social_2', 'Social_3', 'Helthcare_2', \n                              'Shops_1', 'Shops_2', 'Rooms_outlier', 'KitchenSquare_outlier', 'Square_outlier', \n                              'LifeSquare_nan', 'LifeSquare_outlier', 'HouseFloor_outlier', 'HouseYear_outlier', 'Healthcare_1_nan', \n                              'DistrictSize', 'IsDistrictLarge', 'MedPriceByDistrict', 'MedPriceByFloorYear']\n\n        self.target_name = 'Healthcare_1'\n    \n    def fit(self, X):\n        X_train = X[self.feature_names]\n        \n        # \u0414\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0432\u044b\u0431\u0438\u0440\u0430\u044e\u0442\u0441\u044f \u0441\u0442\u0440\u043e\u043a\u0438, \u0433\u0434\u0435 Healthcare_1 \u043d\u0435 \u0440\u0430\u0432\u0435\u043d NaN\n        X_train = X_train[X_train['Healthcare_1_nan'] == 0]\n        y_train = X.loc[X['Healthcare_1_nan'] == 0, self.target_name]\n        self.model.fit(X_train, y_train)\n    \n    def transform(self, X):\n        X_preds = X[self.feature_names]\n        \n        # \u0414\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u0432\u044b\u0431\u0438\u0440\u0430\u044e\u0442\u0441\u044f \u0441\u0442\u0440\u043e\u043a\u0438, \u0433\u0434\u0435 Healthcare_1 = NaN\n        X_preds = X_preds[X_preds['Healthcare_1_nan'] == 1]\n        \n        y_preds = self.model.predict(X_preds)\n        \n        # \u0417\u0430\u043c\u0435\u043d\u0430 NaN-\u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0434\u043b\u044f Healthcare_1\n        X.loc[X['Healthcare_1_nan'] == 1, self.target_name] = y_preds\n        \n        return X\n\"\"\"\n# \u041e\u0442\u0431\u043e\u0440 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 <a class='anchor' id='features_select'>\n\"\"\"\n\"\"\"\n\u0412\u044b\u0432\u0435\u0434\u0435\u043c \u0441\u043f\u0438\u0441\u043e\u043a \u0432\u0441\u0435\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432.\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u0441\u043f\u0438\u0441\u043a\u0430 \u0432\u0441\u0435\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ntrain_df.columns.tolist()\n\"\"\"\n\u0414\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438. \n\n\u041f\u0440\u0438 \u044d\u0442\u043e\u043c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043d\u0435 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0442\u0441\u044f, \u0442.\u043a. \u0434\u0430\u043b\u0435\u0435 \u043f\u0440\u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u043c\u043e\u0434\u0435\u043b\u0438 \u0432\u044b\u044f\u0441\u043d\u0438\u043b\u043e\u0441\u044c, \u0447\u0442\u043e \u043e\u043d\u0438 \u043b\u0438\u0431\u043e \u0431\u0435\u0441\u043f\u043e\u043b\u0435\u0437\u043d\u044b\u0435, \u043b\u0438\u0431\u043e \u0432\u0435\u0434\u0443\u0442 \u043a \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044e. \u042d\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 **Rooms_outlier**, **HouseYear_outlier**, **MedPriceByDistrict**.\n\"\"\"\nfeature_names = ['Rooms', 'Square', 'LifeSquare', 'KitchenSquare', 'Floor', 'HouseFloor', 'HouseYear',\n                 'Ecology_1', 'Ecology_2', 'Ecology_3', 'Social_1', 'Social_2', 'Social_3',\n                 'Healthcare_1', 'Helthcare_2', 'Shops_1', 'Shops_2']\n\nnew_feature_names = ['KitchenSquare_outlier', 'Square_outlier', 'LifeSquare_nan', 'LifeSquare_outlier',\n                     'HouseFloor_outlier', 'Healthcare_1_nan', 'DistrictSize',\n                     'IsDistrictLarge', 'MedPriceByFloorYear']\n\ntarget_name = 'Price'\n\"\"\"\n# \u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043d\u0430 train \u0438 test <a class='anchor' id='train_test_split'>\n\"\"\"\n# \u0421\u0447\u0438\u0442\u044b\u0432\u0430\u043d\u0438\u0435 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0433\u043e \u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0433\u043e \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u043e\u0432\ntrain_df = pd.read_csv(TRAIN_DATASET_PATH)\ntest_df = pd.read_csv(TEST_DATASET_PATH)\n\n# \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u0438 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439\nX = train_df.drop(columns=target_name)\ny = train_df[target_name]\n# \u0420\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u0435 \u043e\u0431\u0443\u0447\u0430\u044e\u0449\u0435\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0438 \u043d\u0430 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u044b\u0439 \u0438 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u044b\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33, shuffle=True, random_state=21)\n# \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432 \u0438 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0432\u044b\u0431\u043e\u0440\u043e\u043a\npreprocessor = DataPreprocessing()\npreprocessor.fit(X_train)\n\nX_train = preprocessor.transform(X_train)\nX_valid = preprocessor.transform(X_valid)\ntest_df = preprocessor.transform(test_df)\n\nX_train.shape, X_valid.shape, test_df.shape\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0432\u043e \u0432\u0441\u0435 \u0432\u044b\u0431\u043e\u0440\u043a\u0438\nfeatures_gen = FeatureGenerator()\nfeatures_gen.fit(X_train, y_train)\n\nX_train = features_gen.transform(X_train)\nX_valid = features_gen.transform(X_valid)\ntest_df = features_gen.transform(test_df)\n\nX_train.shape, X_valid.shape, test_df.shape\n# \u0417\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0432 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0435 Healthcare_1 \u0432\u043e \u0432\u0441\u0435\u0445 \u0432\u044b\u0431\u043e\u0440\u043a\u0430\u0445\nfiller = HealthcareFiller()\nfiller.fit(X_train)\n\nX_train = filler.transform(X_train)\nX_valid = filler.transform(X_valid)\ntest_df = filler.transform(test_df)\n\nX_train.shape, X_valid.shape, test_df.shape\n# \u041e\u0442\u0431\u043e\u0440 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0434\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0438 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f\nX_train = X_train[feature_names + new_feature_names]\nX_valid = X_valid[feature_names + new_feature_names]\ntest_df = test_df[feature_names + new_feature_names]\n\nX_train.shape, X_valid.shape, test_df.shape\n# \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430, \u0447\u0442\u043e \u043d\u0435\u0442 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0432\u043e \u0432\u0441\u0435\u0445 \u0432\u044b\u0431\u043e\u0440\u043a\u0430\u0445\nX_train.isna().sum().sum(), X_valid.isna().sum().sum(), test_df.isna().sum().sum()\n\"\"\"\n# \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438 <a class='anchor' id='model'>\n\"\"\"\n\"\"\"\n## \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 <a class='anchor' id='fit_model'>\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u0431\u044b\u043b\u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u044b \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438: **RandomForestRegressor**, **GradientBoostingRegressor**, **StackingRegressor** \u0438 **CatBoostRegressor**.\n\n\u0425\u0443\u0434\u0448\u0438\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e \u043c\u0435\u0442\u0440\u0438\u043a\u0435 \u0438 \u043f\u043e \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044e \u043f\u043e\u043a\u0430\u0437\u0430\u043b\u0430 \u043c\u043e\u0434\u0435\u043b\u044c RandomForestRegressor.\n\n\u0414\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0435\u0439 GradientBoostingRegressor, StackingRegressor \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u043f\u0440\u0438\u043c\u0435\u0440\u043d\u043e \u043e\u0434\u0438\u043d\u0430\u043a\u043e\u0432\u044b\u0439. \u0414\u043b\u044f GradientBoostingRegressor \u0431\u044b\u043b \u043f\u0440\u043e\u0432\u0435\u0434\u0435\u043d \u043f\u043e\u0438\u0441\u043a \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432 \u043f\u043e \u0441\u0435\u0442\u043a\u0435.\n\n\u0421\u0430\u043c\u044b\u0439 \u043b\u0443\u0447\u0448\u0438\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u043f\u043e\u043a\u0430\u0437\u0430\u043b\u0430 \u043c\u043e\u0434\u0435\u043b\u044c **CatBoostRegressor** \u043f\u0440\u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0438 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e. \u0414\u043b\u044f \u044d\u0442\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 \u0442\u0430\u043a\u0436\u0435 \u0431\u044b\u043b \u043f\u0440\u043e\u0432\u0435\u0434\u0435\u043d \u043f\u043e\u0438\u0441\u043a \u043f\u043e \u0441\u0435\u0442\u043a\u0435, \u043e\u0434\u043d\u0430\u043a\u043e \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0435 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u043d\u0435 \u0443\u043b\u0443\u0447\u0448\u0438\u043b\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442.\n\"\"\"\n# \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u043c\u043e\u0434\u0435\u043b\u0438 \u0441 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e\ncb_model = CatBoostRegressor(logging_level='Silent')\n\n# \u041e\u0431\u0443\u0447\u0435\u043d\u0438\u0435\ncb_model.fit(X_train, y_train, verbose=False)\n\"\"\"\n## \u041e\u0446\u0435\u043d\u043a\u0430 \u043c\u043e\u0434\u0435\u043b\u0438 <a class='anchor' id='evaluate_model'>\n\"\"\"\n# \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0438 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u043e\u043d\u043d\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0430\u0445\ny_train_preds = cb_model.predict(X_train)\ny_valid_preds = cb_model.predict(X_valid)\n\n# \u0412\u044b\u0432\u043e\u0434 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432\nevaluate_preds(y_train, y_train_preds, y_valid, y_valid_preds)\n\"\"\"\n\u0420\u0430\u0437\u043d\u043e\u0441\u0442\u044c \u043c\u0435\u0442\u0440\u0438\u043a \u043e\u043a\u043e\u043b\u043e 16%. \u0417\u043d\u0430\u0447\u0438\u0442 \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u043f\u0435\u0440\u0435\u043e\u0431\u0443\u0447\u0435\u043d\u0430.\n\n\u0418\u0437 \u0433\u0440\u0430\u0444\u0438\u043a\u0430 \u043c\u043e\u0436\u043d\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u0432\u044b\u0432\u043e\u0434, \u0447\u0442\u043e \u043c\u043e\u0434\u0435\u043b\u044c \u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e \u043f\u043b\u043e\u0445\u043e \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0446\u0435\u043d\u0443 \u0434\u043b\u044f \u043a\u0432\u0430\u0440\u0442\u0438\u0440 \u0441 \u043d\u0435\u0432\u044b\u0441\u043e\u043a\u043e\u0439 \u0441\u0442\u043e\u0438\u043c\u043e\u0441\u0442\u044c\u044e - \u0446\u0435\u043d\u0430 \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442\u0441\u044f \u0437\u0430\u0432\u044b\u0448\u0435\u043d\u043d\u043e\u0439.\n\"\"\"\n\"\"\"\n## \u0412\u0430\u0436\u043d\u043e\u0441\u0442\u044c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 <a class='anchor' id='feature_importance'>\n\"\"\"\n# \u0412\u044b\u0432\u043e\u0434 \u0441\u043f\u0438\u0441\u043a\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432, \u043e\u0442\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u043f\u043e \u0432\u0430\u0436\u043d\u043e\u0441\u0442\u0438\nfeature_importances = pd.DataFrame(zip(X_train.columns, cb_model.feature_importances_), \n                                   columns=['feature_name', 'importance'])\n\nfeature_importances.sort_values(by='importance', ascending=False)\n\"\"\"\n\u0412\u0438\u0434\u043d\u043e, \u0447\u0442\u043e \u043d\u043e\u0432\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a MedPriceByFloorYear \u043e\u043a\u0430\u0437\u0430\u043b\u0441\u044f \u043f\u043e\u043b\u0435\u0437\u043d\u044b\u043c.\n\"\"\"\n\"\"\"\n## \u041a\u0440\u043e\u0441\u0441-\u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044f <a class='anchor' id='cv_model'>\n\"\"\"\ncv_score = cross_val_score(cb_model, X_train, y_train, scoring='r2', cv=KFold(n_splits=3, shuffle=True, random_state=21))\ncv_score\ncv_score.mean()\n\"\"\"\n\u041c\u0435\u0442\u0440\u0438\u043a\u0438 \u043e\u0442\u043b\u0438\u0447\u0430\u044e\u0442\u0441\u044f \u0434\u0440\u0443\u0433 \u043e\u0442 \u0434\u0440\u0443\u0433\u0430 \u043d\u0435 \u0441\u0438\u043b\u044c\u043d\u043e, \u0437\u043d\u0430\u0447\u0438\u0442 \u043c\u043e\u0434\u0435\u043b\u044c \u0441\u043a\u043e\u0440\u0435\u0435 \u0432\u0441\u0435\u0433\u043e \u0443\u0441\u0442\u043e\u0439\u0447\u0438\u0432\u0430.\n\"\"\"\n\"\"\"\n## \u041f\u043e\u0438\u0441\u043a \u043f\u043e \u0441\u0435\u0442\u043a\u0435 <a class='anchor' id='grid_search'>\n\"\"\"\n\"\"\"\n\u0411\u044b\u043b \u043f\u0440\u043e\u0432\u0435\u0434\u0435\u043d \u043f\u043e\u0438\u0441\u043a \u043f\u043e \u0441\u0435\u0442\u043a\u0435 \u0441\u043e \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c\u0438 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438. \u0421\u0435\u0439\u0447\u0430\u0441 \u0432 \u0432\u0438\u0434\u0435 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u044f, \u0442.\u043a. \u0440\u0430\u0441\u0447\u0435\u0442 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u043e\u0447\u0435\u043d\u044c \u0434\u043e\u043b\u0433\u043e.\n\n\n\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0435 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b:\n\ndepth=6, l2_leaf_reg=3, learning_rate=0.03.\n\n\u0422.\u0435. \u0442\u043e\u043b\u044c\u043a\u043e depth \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u043d\u0435 \u0440\u0430\u0432\u043d\u044b\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044e \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e.\n\"\"\"\n# search_model = CatBoostRegressor()\n# grid = {'learning_rate': [0.03, 0.1],\n#         'depth': [4, 6, 10],\n#         'l2_leaf_reg': [1, 3, 5, 7, 9],\n#         'logging_level':['Silent'],\n#         'random_seed': [42]\n#        }\n\n# gs = GridSearchCV(search_model, grid, \n#                   scoring='r2',\n#                   cv=KFold(n_splits=5,\n#                            random_state=21, \n#                            shuffle=True),\n#                   n_jobs=-1\n#                   )\n\n# gs.fit(X_train, y_train)\n# gs.best_params_\n\"\"\"\n# \u041f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 <a class='anchor' id='test_preds'>\n\"\"\"\ntest_df.shape\ntest_df\n# \u0421\u0447\u0438\u0442\u044b\u0432\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0432\u0435\u0440\u043e\u0447\u043d\u043e\u0433\u043e \u0444\u0430\u0439\u043b\u0430\nsubmit = pd.read_csv('\/kaggle\/input\/real-estate-price-prediction-moscow\/sample_submission.csv')\nsubmit.head()\n# \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435\npredictions = cb_model.predict(test_df)\npredictions\n# \u0417\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0432\u0435\u0440\u043e\u0447\u043d\u043e\u0433\u043e \u0444\u0430\u0439\u043b\u0430 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u043c\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438 \u0446\u0435\u043d\u044b\nsubmit['Price'] = predictions\nsubmit.head()\n# \u0421\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0430 \u0432 \u0444\u0430\u0439\u043b\nsubmit.to_csv('catboost_submit.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '8428aa0ab90293'}"}
{"id":"103797","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\n%matplotlib inline\nseed = 42\nrandom.seed(seed)\n\"\"\"\n# Corona Virus\n\"\"\"\n\"\"\"\n![](http:\/\/..\/input\/images\/img1.jpg)\n\"\"\"\n\"\"\"\nCoronaviruses (CoV) are a large family of viruses that cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS-CoV) and Severe Acute Respiratory Syndrome (SARS-CoV). A novel coronavirus (nCoV) is a new strain that has not been previously identified in humans.  \n\nCoronaviruses are zoonotic, meaning they are transmitted between animals and people.  Detailed investigations found that SARS-CoV was transmitted from civet cats to humans and MERS-CoV from dromedary camels to humans. Several known coronaviruses are circulating in animals that have not yet infected humans. \n\nCommon signs of infection include respiratory symptoms, fever, cough, shortness of breath and breathing difficulties. In more severe cases, infection can cause pneumonia, severe acute respiratory syndrome, kidney failure and even death. \n\nStandard recommendations to prevent infection spread include regular hand washing, covering mouth and nose when coughing and sneezing, thoroughly cooking meat and eggs. Avoid close contact with anyone showing symptoms of respiratory illness such as coughing and sneezing.\n\"\"\"\n\"\"\"\nIn this analysis and prediction we will analiys data provided by Johns Hopkins university. We will also build a predictive model to predict spread of this deadly virus\n\"\"\"\n\"\"\"\n# Importing Dataset\n\"\"\"\ndata = pd.read_csv('..\/input\/novel-corona-virus-2019-dataset\/2019_nCoV_data.csv')\n\"\"\"\n# EDA\n\"\"\"\n\"\"\"\n<h3> Data Familiarization <\/h3>\n\"\"\"\ndata.head()\ndata.tail()\n\"\"\"\nDataset is a time series data from 22 January 2020 to 22 February, It have 7 columns with a mix of categorical and numerical data\n\"\"\"\n\"\"\"\nObservationDate - Date of the observation in MM\/DD\/YYYY<br>\nProvince\/State - Province or state of the observation (Could be empty when missing)<br>\nCountry\/Region - Country of observation<br>\nLast Update - Time in UTC at which the row is updated for the given province or country. (Not standardised and so please clean before using it)<br>\nConfirmed - Cumulative number of confirmed cases till that date<br>\nDeaths - Cumulative number of of deaths till that date<br>\nRecovered - Cumulative number of recovered cases till that date<br>\n\"\"\"\ndata.info()\ndata['Province\/State'] = data['Province\/State'].fillna('Unknown')\n\"\"\"\n<h3>Converting to datetime  <h3>\n\"\"\"\ndata['Date'] = pd.to_datetime(data['Date'])\ndata['Date'] = data['Date'].dt.strftime('%d\/%m\/%Y')\ndata['Last Update'] = pd.to_datetime(data['Last Update'])\ndata['Last Update'] = data['Last Update'].dt.strftime('%d\/%m\/%Y')\ndata.info()\n# missing data\ntotal = data.isnull().sum().sort_values(ascending=False)\npercent = (data.isnull().sum() \/ data.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nprint(missing_data.head(10))\n\"\"\"\nProvince\/state column have lots of missing values, We can totally remove this column to analyis only country wise data or we can impute this value to preserve state feature for deeper analysis.\n\"\"\"\nprint([pd.value_counts(data[cols]) for cols in data.columns])\n\"\"\"\nData was not recorded evenly on each date<br>\nMost cases of corona virus is in China followed by USA and Australia. Least cases are in Brazil, Ivory Coast and Mexico<br>\n\"\"\"\ndata.describe()\n\"\"\"\nMax confirmed cases are : 59989<br>\nMax Deaths are : 1789<br>\nMax recovered : 7862<br>\n<br>\n\n\"\"\"\ndata[data.Confirmed > 500]\n\"\"\"\n<br>\nData shows that China's Hubei region have huge amount of cases confirmed.\n<br>\nOn some research over internet it was confirmed that Hubei region cases are not outliers rather true value. Here Hubei region data is not good for the model we might remove it later in model building phase because it will definetly interfere with our predictions.\n\"\"\"\n\"\"\"\n<h3>Data Visualization<\/h3>\n\"\"\"\n\"\"\"\nData in number form is not very intuitive. It provides numerical insights like central tendency of data its variance and standard deviation but to fully understand data we need to visualize it on graph.<br>\nVisualizing data shows hidden patterns in data. These hidden patterns might provide us useful insight which can be helpfull to tackle this deadly virus.\n<br>\n<br>\n\"\"\"\ndata['Country'].value_counts().head(30).plot(kind='barh', figsize=(20, 6))\n\"\"\"\n<br>\n<br>Graph shows that most number of cases are in Mainland China<br>\nData also shows that Top 5 countries have majority of cases of Corona virus\n<br>\n<br>\n\"\"\"\nconfirmed_plt = sns.relplot(x='Date', y='Confirmed',  data=data, kind='line',aspect=2, height=10, sort=False)\nconfirmed_plt.set_xticklabels(rotation=-45)\n\"\"\"\n<br>\n<br>\nCases of Corona virus increased as we observed more data, it is clearly visble by slope of the line. Also notice as observation increases deveation in number of cases also increases, this huge deviation is due to Hubei region of china.\nThere is sudden rise in number of cases 11 Feb and 13 Feb 2020. (I wonder what it would be?)\n<br>\n<br>\n\"\"\"\n\"\"\"\n<h3> Binning Data <h3>\n\"\"\"\n\"\"\"\nBinning data provides us an insight on overall patterns in data. Here we will bin confirmed, deaths, Recovery, Date and Last Update\n\"\"\"\n\"\"\"\n<h5> Binning Confirmed<\/h5>\n<br>\nConfirmed has an interesting take most of the cases in confirmed are below 12 in a day therefore we can bin cases of below 2 as low_cases, cases between 2 and 6 as medium_cases and cases above 12 as high_cases. This binning can be done according to any other criteria. As this virus is well contaminated anything above 2 cases per day should be more than controlled.\n\"\"\"\ndata['Confirmed_cases'] = data['Confirmed'].apply(lambda x: 'Low' if x < 3 else('Medium' if 3 <= x >=6 else 'High'))\ndata['Confirmed_cases'].value_counts()\n\"\"\"\nHere most of the cases detected in a day are between 3 and 6 which is good for this deadly virus.<br>\nLow cases are also quite high, but we need to increase ratio low cases to sucessfully contain the spread of virus.<br>\nHigh cases are not that prevalant which is a good news but it can be decreased.\nNote: Here increase in cases are considered as bad because as more confirmed cases are observed higher the risk of virus to the masses.<br>\n\"\"\"\n\"\"\"\n<h5> Binning deaths<\/h5>\nAccording to numerical analysis of deaths we can see 75% data have zero deaths with this much high deaths we will bin deaths in binary category of yes or no.\n\"\"\"\ndata['Deaths_Status'] = data['Deaths'].apply(lambda x: 'No' if x < 1 else 'Yes')\ndata['Deaths_Status'].value_counts()\n\"\"\"\nHere 1351 cases shows no deaths but in 368 days there are deaths this maybe due to accumlation of data and releasing it in one go.\n\"\"\"\n\"\"\"\n<h5> Binning Recovered<\/h5>\nAccording to numerical analysis of recovered we can see 50% data have zero recovery but 25% data have recovery of upto 7 persons in a day and 75% to 100% have recovery greater than 7, Hence we will bin data in 3 category. No_recovery for zero recovery datapoint, medium_recovery for 1 to 7 and high recovery for more than 7.<br>\nAgain this categorization is used by me based on heuristics, better binning may increase information gain.\n\"\"\"\ndata['Recovered_Status'] = data['Recovered'].apply(lambda x: 'No' if x < 1 else('Medium' if 1 <= x >=7 else 'High'))\ndata['Recovered_Status'].value_counts()\n\"\"\"\nNo recovery is pre-dominant in dataset which needs critical attention of medical professionals as well as researchers to find a cure and speedy recovery guides.<br>\nAlthough Medium and High recovery are there but in dataset maximum recovery is 7862 which is way lower than maximum cases confimed 59989\n\"\"\"\nconfirmed_death_reco_plt = sns.relplot(x='Date', y='Confirmed', hue='Deaths_Status', size='Recovered_Status', sizes=(50, 200),\n                                       data=data, legend='brief', aspect=2)\nconfirmed_death_reco_plt.set_xticklabels(rotation=-45)\n\"\"\"\nAs time passes confirmed cases, deaths and recovery of patients increasing. This shows as linear relationship between time and cases.\n<br>\n<br>\n\"\"\"\n\"\"\"\nDue to high voloume of people infected by virus in Hubei, China we are not able to analyis majority of trend. <br>\nWe might consider removing data of Hubei or limiting number of confirmed cases.\n\"\"\"\ndata_no_hubei = data.drop(data[data['Province\/State'] == 'Hubei'].index)\nconfirmed_death_no_hubei_plt = sns.relplot(x='Date', y='Confirmed', hue='Recovered_Status', size='Deaths_Status', sizes=(50, 200),\n                                       data=data_no_hubei, legend='brief', aspect=2)\nconfirmed_death_no_hubei_plt.set_xticklabels(rotation=-45)\n\"\"\"\nAbove plot shows there are diffrent trends in data. We will see most of them closely<br>\n\"\"\"\ndata_conf_1000 = data.iloc[data[data.Confirmed.between(1000, 2000)].index, :]\nconfirmed_death_no_hubei_1000_plt = sns.relplot(x='Date', y='Confirmed', hue='Deaths_Status', size='Recovered_Status', row='Country',\n                                             data=data_conf_1000, legend='brief', aspect=2, kind='line', sort=False)\nconfirmed_death_no_hubei_1000_plt.set_xticklabels(rotation=-45)\n\"\"\"\nThere is sharp increase and decrease in deaths due to virus between 25 Jan 2020 to 7 Feb 2020, this maybe due to release of holded data about number of deaths in China. (Thanks to China's Censorship). There is high deviation in number of deaths recorded after 8 Feb 2020 and significant deviation after 15 Feb 2020.<br>\nNo death is increasing gradually with a gentle slope after 15 Feb 2020, This needs to increased exponentially.<br>\nRecovered status is almost negligible which indicates dire need of a CURE!!!!\n\"\"\"\ndata_conf_800 = data.iloc[data[data.Confirmed.between(100, 500)].index, :]\nconfirmed_800_plt = sns.relplot(x='Date', y='Confirmed', hue='Recovered_Status', size='Country', sizes= (20, 200), row='Deaths_Status',\n                                             data=data_conf_800, legend='brief', aspect=2)\nconfirmed_800_plt.set_xticklabels(rotation=-45)\n\"\"\"\nData shows that Majority of cases are from Mainland China, which is not a surprise as its origin is China.<br>\nOther countries have exponential amount of increase in confirmed cases after 13 Feb 2020.<br>\nThere is moderate of recovery which is between 1 and 7. This is nothing compared to number of cases confirmed.\n\"\"\"\nsns.countplot(x='Confirmed_cases', hue='Recovered_Status', data=data)\nsns.countplot(x='Confirmed_cases', hue='Deaths_Status', data=data)\nsns.countplot(x='Deaths_Status', hue='Recovered_Status', data=data)\n\"\"\"\n<h2> Country Wise Analysis <\/h2>\n\"\"\"\n\"\"\"\ninsights provided overall analysis is not very clear as data from diffrent countries and states are making dataset very confusing. Here in this section we will analyis data on the basis of per country.\n\"\"\"\n\"\"\"\n<h4>Mainland China<\/h4>\n\"\"\"\n\"\"\"\nChina has most number of cases of corona virus hence it is only natural to analyis china's situation in depth.\n\"\"\"\ndata_china = data.iloc[data[data.Country == 'Mainland China'].index, :]\ndata_china\nprint('There are ', len(data_china['Province\/State'].value_counts()), 'Districts in China where virus is observed')\ndata_china['Province\/State'].value_counts()\n\"\"\"\nData observed in each district is 26 except for Tibet where it is 21.\n\"\"\"\n\"\"\"\n<h6>Visualizing China<\/h6>\n\"\"\"\n\"\"\"\n![title](img\/img2.png)\n\"\"\"\n\"\"\"\n<h6> Hubei District <\/h6>\n\"\"\"\nchina_date_plt = sns.relplot(x='Date', y='Confirmed', data=data_china, aspect=2.5, kind='line', sort=False)\nchina_date_plt.set_xticklabels(rotation=-45)\n\"\"\"\nData of China is most similar to the overall data this shows that China's confirmed cases have heavy influence on dataset. It will not be intutive to analyse this data as same as overall because it will not reveal anything interesting but visualizing data as per district might reveal something interesting.<br>\nWe will divide data in 2 parts on basis of district of Hubei as Hubei's record distorts the whole data due to its large number of cases.\n\"\"\"\ndata_china_hubei = data.iloc[data[data['Province\/State'] == 'Hubei'].index, :]\nchina_hubei_plt = sns.relplot(x='Date', y='Confirmed', data=data_china_hubei, aspect=2.5,\n                                 kind='line', sort=False)\nchina_hubei_plt.set_xticklabels(rotation=-45)\n\"\"\"\nThis line shows gradual increase in number off reported cases in Hubei district with exponential growth during 11 abd 13 Feb 2020.<br>\nHubei is the most hit region in the world by corona virus and this data tells us no diffrent. We need to analyis further.\n\"\"\"\nchina_hubei_plt1 = sns.relplot(x='Date', y='Confirmed', hue='Recovered_Status', size='Deaths_Status', sizes=(100, 20),\n                               data=data_china_hubei, aspect=2.5)\nchina_hubei_plt1.set_xticklabels(rotation=-45)\n\"\"\"\nThis zoomed in plot shows recovery is increasing as observation is increasing but number of death is also way to high daya by day. This is a matter of concern\n\"\"\"\n\"\"\"\n<h6> Other Districts <\/h6>\n\"\"\"\ndata_china_no_hubei = data_china.drop(data_china[data_china['Province\/State'] == 'Hubei'].index)\nchina_no_hubei_plt = sns.relplot(x='Date', y='Confirmed', hue='Recovered_Status', size='Deaths_Status',\n                               row='Province\/State', data=data_china_no_hubei, aspect=2)\nchina_no_hubei_plt.set_xticklabels(rotation=-45)\n\"\"\"\nMost of the districts have cases less than 400 but a few districts have upward of 1200 cases.<br>\nThere was no recovery in starting of the observation but once as more cases are observed recovery increased.<br>\nDeath rates are still increasing in some districts and there are no death observed but overall death ratio is quite high\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'beb3dc9cd7b255'}"}
{"id":"33723","text":"\"\"\"\n### 1. Exploratory Data Analysis\n\"\"\"\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pylab as plot\ndata=pd.read_csv(\"..\/input\/titanic\/train.csv\")\ndata.shape\ndata.head(10)\n\"\"\"\n#### Checking missing values in each variable\n\"\"\"\nplt.figure(figsize=(10,10))\nsns.heatmap(data.isnull(), yticklabels=False, cbar=False)\n\"\"\"\n###### Some observations\n1. There are total of 891 passengers in our training set.<br>\n2. The age feature is missing approximately 20% of its values.<br> \n3. Cabin feature has most of its value missing.<br>\n4. Embarkes feature is missing small amount of its values.<br>\n\"\"\"\n# Check for any other unusable values\npd.isnull(data).sum()\ndata['Age']=data['Age'].fillna(data['Age'].median())\ndata.describe()\n\"\"\"\n### Data Visualization\n\"\"\"\n\"\"\"\n##### Gender - Survival\n\"\"\"\ndata['Died'] = 1-data['Survived']\ndata.groupby('Sex').agg('sum')[['Survived','Died']].plot(kind='bar',figsize=(25, 7), stacked = True);\n\"\"\"\nFrom the above plot we can see female passengers a more likely to survive\n\"\"\"\ndata.groupby('Sex').agg('mean')[['Survived','Died']].plot(kind='bar', figsize=(25, 7), stacked=True);\n\"\"\"\n##### Age - Survival\n\"\"\"\nfigure = plt.figure(figsize=(25,7))\nsns.violinplot(x='Sex', y='Age', hue='Survived', \n               data=data, \n               split=True, palette={0: 'r', 1:'g'});\n\"\"\"\nYounger male tend to survive<br>\nThe age doesn't seems to have a direct impact on the female survival\n\"\"\"\n\"\"\"\n##### Fare - Survival\n\"\"\"\nfigure = plt.figure(figsize=(25,7))\nplt.hist([data[data['Survived']==1]['Fare'],\n          data[data['Survived']==0]['Fare']],\n            stacked=True,\n            bins=50, label=['Survived','Dead'])\nplt.xlabel('Fare')\nplt.ylabel('Number of passengers')\nplt.legend();\n\"\"\"\nPassenger with more expensive ticket are more likely to survive\n\"\"\"\n\"\"\"\n##### Age - Fare - Survival\n\"\"\"\nplt.figure(figsize=(25,7))\nax=plt.subplot()\n\nax.scatter(data[data['Survived']==1]['Age'],\n          data[data['Survived']==1]['Fare'],\n          c='green', s=data[data['Survived']==1]['Fare']);\n\nax.scatter(data[data['Survived']==0]['Age'],\n          data[data['Survived']==0]['Fare'],\n          c='red', s=data[data['Survived']==0]['Fare']);\n\"\"\"\nThe size of the circles is proportional to the ticket fare.\n\nOn the x-axis, we have the ages and the y-axis, we consider the ticket fare.\n\nWe can observe different clusters:<br>\n\n1. Large green dots between x=20 and x=45: adults with the largest ticket fares<br>\n2. Small red dots between x=10 and x=45, adults from lower classes on the boat<br>\n3. Small greed dots between x=0 and x=7: these are the children that were saved<br>\n\nAs a matter of fact, the ticket fare correlates with the class as we see it in the chart below.\n\"\"\"\nax = plt.subplot()\nax.set_ylabel('Average fare')\ndata.groupby('Pclass').mean()['Fare'].plot(kind='bar',figsize=(25,7),ax=ax);\n\"\"\"\n##### Embarkation - Survival\n\"\"\"\nplt.figure(figsize=(25,7))\nsns.violinplot(x='Embarked', y='Fare', hue='Survived', data=data, split=True, palette={0:'r', 1:'g'});\n\"\"\"\n### 2. Feature Engineering\n\"\"\"\ndef status(feature):\n    print('Processing', feature, ': Ok')\ntrain = pd.read_csv('..\/input\/titanic\/train.csv')\ntest  = pd.read_csv('..\/input\/titanic\/test.csv' )\ntarget = train.Survived\ntrain.drop(['Survived'], 1, inplace=True)\ndef get_combined_data():\n    combined = train.append(test)\n    combined.reset_index(inplace=True)\n    \n    return combined\ncombined = get_combined_data()\ncombined.drop(['index','PassengerId'],inplace=True,axis=1)\ncombined.shape\ncombined.head()\n\"\"\"\n##### Extracting the passengers title\n\"\"\"\ntitles = set()\nfor name in data['Name']:\n    titles.add(name.split(',')[1].split('.')[0].strip())\ntitles\nTitle_Dictionary = {\n    'Capt':'Officer',\n    'Col' :'Officer',\n    'Don' :'Royalty',\n    'Dr':'Officer',\n    'Jonkheer':'Royalty',\n    'Lady':'Royalty',\n    'Major':'Officer',\n    'Master':'Master',\n    'Miss':'Miss',\n    'Mlle':'Miss',\n    'Mme':'Mrs',\n    'Mr':'Mr',\n    'Mrs':'Mrs',\n    'Ms':'Mrs',\n    'Rev':'Officer',\n    'Sir':'Royalty',\n    'the Countess':'Royalty'\n}\n\ndef get_titles():\n    combined['Title'] = combined['Name'].map(lambda name:name.split(',')[1].split('.')[0].strip())\n    \n    combined['Title'] = combined.Title.map(Title_Dictionary)\n    status('Title')\n    return combined\ncombined=get_titles()\ncombined.head()\n\"\"\"\n##### Processing age\n\"\"\"\ngrouped_train=combined.iloc[:891].groupby(['Sex','Pclass','Title'])\ngrouped_median_train=grouped_train.median()\ngrouped_median_train=grouped_median_train.reset_index()[['Sex','Pclass','Title','Age']]\ngrouped_median_train.head()\ndef fill_age(row):\n    condition = (\n    (grouped_median_train['Sex']==row['Sex']) & \n    (grouped_median_train['Title']==row['Title']) & \n    (grouped_median_train['Pclass']==row['Pclass']))\n    return grouped_median_train[condition]['Age'].values[0]\n\ndef process_age():\n    global combined\n    \n    combined['Age']=combined.apply(lambda row: fill_age(row) if np.isnan(row['Age']) else row['Age'], axis=1)\n    status('age')\n    return combined\ncombined = process_age()\n\"\"\"\n##### Processing Names\n\"\"\"\ndef process_names():\n    global combined\n    combined.drop('Name', axis=1, inplace=True)\n    \n    titles_dummies=pd.get_dummies(combined['Title'],prefix='Title')\n    combined=pd.concat([combined, titles_dummies], axis=1)\n    \n    combined.drop('Title', axis=1, inplace= True)\n    \n    status('names')\n    return combined\ncombined = process_names()\ncombined.head()\n\"\"\"\n##### Processing Fares\n\"\"\"\ndef process_fares():\n    global combined\n    combined.Fare.fillna(combined.iloc[:891].Fare.mean(), inplace=True)\n    status('Fare')\n    return combined\ncombined=process_fares()\n\"\"\"\n##### Processing Embarked\n\"\"\"\ndef process_embarked():\n    global combined\n    \n    combined.Embarked.fillna('S', inplace=True)\n    embarked_dummies = pd.get_dummies(combined['Embarked'],prefix='Embarked')\n    combined=pd.concat([combined, embarked_dummies], axis=1)\n    combined.drop('Embarked', axis=1, inplace=True)\n    status('embarked')\n    return combined\ncombined = process_embarked()\ncombined.head()\n\"\"\"\n##### Processing Cabin\n\"\"\"\ntrain_cabin=set()\ntest_cabin=set()\n\nfor c in combined.iloc[:891]['Cabin']:\n    try:\n        train_cabin.add(c[0])\n    except:\n        train_cabin.add('U')\n\nfor c in combined.iloc[891:]['Cabin']:\n    try:\n        test_cabin.add(c[0])\n    except:\n        test_cabin.add('U')\ntrain_cabin\ntest_cabin\ndef process_cabin():\n    global combined\n    \n    combined.Cabin.fillna('U',inplace=True)\n    combined['Cabin']=combined['Cabin'].map(lambda c: c[0])\n    \n    cabin_dummies = pd.get_dummies(combined['Cabin'],prefix='Cabin')\n    combined = pd.concat([combined, cabin_dummies], axis=1)\n    \n    combined.drop('Cabin', axis=1, inplace=True)\n    status('cabin')\n    return combined\ncombined = process_cabin()\ncombined.head()\n\"\"\"\n##### Processing Sex\n\"\"\"\ndef process_sex():\n    global combined\n    \n    combined['Sex']=combined['Sex'].map({'male':1, 'female':0})\n    status('Sex')\n    \n    return combined\ncombined = process_sex()\n\"\"\"\n##### Processing Pclass\n\"\"\"\ndef process_pclass():\n    global combined\n    \n    pclass_dummies = pd.get_dummies(combined['Pclass'], prefix='Pclass')\n    combined = pd.concat([combined, pclass_dummies], axis=1)\n    combined.drop('Pclass', axis=1, inplace=True)\n    \n    status('Pclass')\n    return combined\ncombined = process_pclass()\n\"\"\"\n##### Processing Ticket\n\"\"\"\ndef cleanTicket(ticket):\n    ticket = ticket.replace('.','')\n    ticket = ticket.replace('\/','')\n    ticket = ticket.split()\n    ticket = map(lambda t : t.strip(), ticket)\n    ticket = list(filter(lambda t : not t.isdigit(), ticket))\n    if len(ticket) > 0:\n        return ticket[0]\n    else:\n        return 'XXX'\ntickets = set()\nfor t in combined['Ticket']:\n    tickets.add(cleanTicket(t))\nprint(len(tickets))\ndef process_ticket():\n    global combined\n    \n    def cleanTicket(ticket):\n        ticket = ticket.replace('.','')\n        ticket = ticket.replace('\/','')\n        ticket = ticket.split()\n        ticket = map(lambda t : t.strip(), ticket)\n        ticket = list(filter(lambda t : not t.isdigit(), ticket))\n        if len(ticket) > 0:\n            return ticket[0]\n        else:\n            return 'XXX'\n    \n    combined['Ticket']=combined['Ticket'].map(cleanTicket)\n    tickets_dummies = pd.get_dummies(combined['Ticket'], prefix='Ticket')\n    combined = pd.concat([combined, tickets_dummies], axis=1)\n    combined.drop('Ticket', inplace=True, axis=1)\n    \n    status('Ticket')\n    return combined\n    \ncombined = process_ticket()\n\"\"\"\n##### Processing Family\n\"\"\"\ndef process_family():\n    global combined\n    \n    combined['FamilySize']=combined['Parch']+combined['SibSp'] + 1\n    \n    combined['Singleton'] = combined['FamilySize'].map(lambda s:1 if s == 1 else 0)\n    combined['SmallFamily'] = combined['FamilySize'].map(lambda s:1 if 2 <= s <= 4 else 0)\n    combined['LargeFamily'] = combined['FamilySize'].map(lambda s:1 if 5 <= s else 0)\n    status('Family')\n    return combined\ncombined = process_family()\ncombined.shape\ncombined.head()\n\"\"\"\n### 3. Modeling\n\"\"\"\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble.gradient_boosting import GradientBoostingClassifier\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\ndef compute_score(clf, X, y, scoring='accuracy'):\n    xval = cross_val_score(clf, X, y, cv = 5, scoring=scoring)\n    return np.mean(xval)\ndef recover_train_test_target():\n    global combined\n    \n    targets = pd.read_csv('..\/input\/titanic\/train.csv', usecols=['Survived'])['Survived'].values\n    train = combined.iloc[:891]\n    test = combined.iloc[891:]\n    \n    return train, test, targets\ntrain, test, targets = recover_train_test_target()\n\"\"\"\n### Feature Selection\n\"\"\"\nclf = RandomForestClassifier(n_estimators=50, max_features='sqrt')\nclf = clf.fit(train, targets)\nfeatures = pd.DataFrame()\nfeatures['feature'] = train.columns\nfeatures['importance'] = clf.feature_importances_\nfeatures.sort_values(by=['importance'], ascending=True, \n                     inplace=True)\nfeatures.set_index('feature', inplace=True)\nfeatures.plot(kind='barh', figsize=(20, 25));\nmodel = SelectFromModel(clf, prefit=True)\ntrain_reduced = model.transform(train)\ntrain_reduced.shape\ntest_reduced = model.transform(test)\ntest_reduced.shape\n\"\"\"\n##### Trying different base models\n\"\"\"\nlogreg = LogisticRegression()\nlogreg_cv = LogisticRegressionCV()\nrf = RandomForestClassifier()\ngboost = GradientBoostingClassifier()\n\nmodels = [logreg, logreg_cv, rf, gboost]\nfor model in models:\n    print ('Cross-validation of : {0}'.format(model.__class__))\n    score = compute_score(clf=model, X=train_reduced, y=targets, scoring='accuracy')\n    print ('CV score = {0}'.format(score))\n    print ('****')\n\"\"\"\n### Hyperparameters tuning\n\"\"\"\nrun_gs = False\n\nif run_gs:\n    parameter_grid = {\n                 'max_depth' : [4, 6, 8],\n                 'n_estimators': [50, 10],\n                 'max_features': ['sqrt', 'auto', 'log2'],\n                 'min_samples_split': [2, 3, 10],\n                 'min_samples_leaf': [1, 3, 10],\n                 'bootstrap': [True, False],\n                 }\n    forest = RandomForestClassifier()\n    cross_validation = StratifiedKFold(n_splits=5)\n\n    grid_search = GridSearchCV(forest,\n                               scoring='accuracy',\n                               param_grid=parameter_grid,\n                               cv=cross_validation,\n                               verbose=1\n                              )\n\n    grid_search.fit(train, targets)\n    model = grid_search\n    parameters = grid_search.best_params_\n\n    print('Best score: {}'.format(grid_search.best_score_))\n    print('Best parameters: {}'.format(grid_search.best_params_))\n    \nelse: \n    parameters = {'bootstrap': False, 'min_samples_leaf': 3, 'n_estimators': 50, \n                  'min_samples_split': 10, 'max_features': 'sqrt', 'max_depth': 6}\n    \n    model = RandomForestClassifier(**parameters)\n    model.fit(train, targets)","meta":"{'source': 'AI4Code', 'id': '3e21535ef29f57'}"}
{"id":"16190","text":"\"\"\"\n# Prediction of Total Energy Consumption\n\"\"\"\n\"\"\"\nIn this case study we need to predict the total load consumption depending upon different parameters, such as generation from different sources and the weather condition.\n\"\"\"\n\"\"\"\n## Understanding the data features:\n\n1)generation biomass-Power generated by biomass\n\n2)generation fossil brown coal\/lignite-Power generated by fossil brown coal\/lignite\n\n3)generation fossil gas-power generated by fossil gas\n\n4)generation fossil hard coal-power generated by fossil hard coal\n\n5)generation fossil oil-power generated by fossil oil\n\n6)generation hydro pumped storage consumption-power generated by pumped storage consumption(This is used as an emergency power                                               resource) \n\n7)generation hydro run-of-river and poundage-power generated by hydro run\n\n8)generation hydro water reservoir-power generated by water reservior\n\n9)generation nuclear-power generated by nuclear energy\n\n10)generation other-power generated by other sources\n\n11)generation other renewable-power generated by other renewable energies other than mentioned in the dataset\n\n12)generation solar-power generated by solar energy\n\n13)generation waste-power generated by waste\n\n14)generation wind onshore-power generated by wind onshore\n\n15)total load actual-__This is the dependent varibale.It tell us about the total load consumption.__\n\n16)temp- Temperature of the area when load consumption was recorded\n\n17)pressure-Pressure of the area when load consumption was recorded\n\n18)humidity-Humidity of the area when load consumption was recorded.\n\n19)wind_speed-Wind speed of the area when load consumption was recorded.\n\n20)wind_deg-Wind direction of the area when load consumption was recorded.\n\n21)rain_1h-It tells us about the intensity of rainfall.\n\n22)snow_3h-It is divided into 4 values and tells us about the intensity of snowfall.\n\n23)weather_id-It gives us 23 values of different weather condition. \n\n24)weather_main-Even this column tells us about the weather condition i.e whether it was clear or cloudy or it was raining when                 the load was recorded.\n\n25)weather_description-It tells us about the overcast,whether it was raining or sunny.\n\n26)time-It gives us the date and time when load was recorded\n\"\"\"\n\"\"\"\n\n# Importing Libraries\n\"\"\"\n# suppress warnings \nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n\n# 'Pandas' is used for data manipulation and analysis\nimport pandas as pd \n\n# 'Numpy' is used for mathematical operations on large, multi-dimensional arrays and matrices\nimport numpy as np\n\n# 'Matplotlib' is a data visualization library for 2D and 3D plots, built on numpy\nimport matplotlib.pyplot as plt\n\n# 'Seaborn' is based on matplotlib; used for plotting statistical graphics\nimport seaborn as sns\n\n# 'Scikit-learn' (sklearn) emphasizes various regression, classification and clustering algorithms\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestRegressor\n\n# 'Statsmodels' is used to build and analyze various statistical models\nimport statsmodels\nimport statsmodels.api as sm\nfrom statsmodels.tools.eval_measures import rmse\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\n# 'SciPy' is used to perform scientific computations\nfrom scipy.stats import shapiro\nfrom scipy import stats\n\n# import functions to perform feature selection\nfrom mlxtend.feature_selection import SequentialFeatureSelector as sfs\n\n#import functions for time series\nimport itertools\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.stattools import adfuller\n\"\"\"\n# Reading the dataframe\n\"\"\"\n#reading the data\ndf_energy=pd.read_csv(\"..\/input\/energy-dataset\/energy_dataset.csv\")\n#displaying the first five records\ndf_energy.head()\n\"\"\"\n# Understanding the dataset\n\"\"\"\n#\"df.shape\" gives the number of rows and columns in the dataset\ndf_energy.shape\n\"\"\"\nThere are 35064 rows and 37 columns\n\"\"\"\n#understanding the data types and null values in each column\ndf_energy.info()\n\"\"\"\n1)From the above display we can see that the datatype of time column is object whereas it should be in datetime format.\n\n2)The columns \"generation hydro pumped storage aggregated\" has null values.There are even missing values in other columns which needs to be handled. \n\"\"\"\n#We need to further understand that whether other columns are really of float type or other datatype\nfor i in df_energy.columns:\n    print(i,\"--->\",df_energy[i].nunique(),\"--->\",df_energy[i].dtypes)\n\"\"\"\nWe see that the columns \"generation fossil coal-derived gas\",\"generation fossil oil shale\",\"generation fossil peat\",\"generation geothermal\",\"generation marine\",\"generation wind offshore\" have just one value.So these should be of object type.Let us explore it further.\n\"\"\"\n#checking the values in the columns 'generation fossil coal-derived gas','generation fossil oil shale',\n#'generation fossil peat','generation geothermal','generation marine','generation wind offshore'\ncols=['generation fossil coal-derived gas','generation fossil oil shale','generation fossil peat',\n      'generation geothermal','generation marine','generation wind offshore']\nfor values in cols:\n    print(df_energy[values].unique())\n\"\"\"\nWe can see from the above output that these columns doesnot have any values other than 0.So we delete these columns.\n\"\"\"\n#deleting the columns above\ndf_energy=df_energy.drop(['generation fossil coal-derived gas','generation fossil oil shale','generation fossil peat','generation geothermal','generation marine','generation wind offshore'],axis=1)\n#dropping the column 'generation hydro pumped storage aggregated' as there are no values in it\ndf_energy=df_energy.drop(['generation hydro pumped storage aggregated'],axis=1)\n#conversion of datatypes of columns\ncols=['rain_1h','snow_3h','weather_description','weather_main']\ndf_energy[cols]=df_energy[cols].astype(object)\n#Changing the datatype of time column\ndf_energy[['Date','Time']]=df_energy['time'].str.split(\" \",n=1,expand=True)\ndf_energy['Date']=pd.to_datetime(df_energy['Date'])\ndf_energy[['Time','Spare']]=df_energy['Time'].str.split(\"+\",n=1,expand=True)\n\ndf_energy=df_energy.drop([\"Spare\",\"time\"],axis=1)\ndf_energy['Time']=pd.to_datetime(df_energy['Time'],format='%H:%M:%S')\ndf_energy['Time']=df_energy['Time'].dt.time\n#Finally checking the columns and the datatype of all the columns \ndf_energy.info()\n\"\"\"\nWe can see that the columns have been handled and the datatype of time column has been changed.\n\"\"\"\n\"\"\"\nNow our dataset is ready for doing EDA\n\"\"\"\n\"\"\"\n# Extrapolatory Data Analysis \n\"\"\"\n#sns.distplot(df_energy['generation biomass'])\nsns.set_color_codes()\nsns.distplot(df_energy['generation biomass'], color=\"b\")\nplt.show()\n#creating a new variable fossil and adding up all the power generated from fossil\nfossil=df_energy['generation fossil brown coal\/lignite']+df_energy['generation fossil gas']+df_energy['generation fossil hard coal']+df_energy['generation fossil oil']\nsns.distplot(fossil, color=\"b\")\nplt.show()\n#creating a variable renewable and storing adding up all the powers generated from renewable source of energy\nrenewable=df_energy['generation hydro run-of-river and poundage']+df_energy['generation hydro water reservoir']+df_energy['generation hydro pumped storage consumption']+df_energy['generation wind onshore']+df_energy['generation other renewable']+df_energy['generation solar']\nsns.distplot(renewable, color=\"b\")\nplt.show()\nsns.distplot(df_energy['generation other'])\nplt.show()\nsns.distplot(df_energy['total load actual'])\nplt.show()\ndf_energy['total load actual'].skew()\nsns.distplot(df_energy['temp'])\nplt.show()\nsns.distplot(df_energy['humidity'])\nplt.show()\n\"\"\"\nFrom the graphs plotted above we can see that maximum graphs are normally distributed.The new variable renewable is slightly right skewed and the feature humidity is slightly left skewed.\n\"\"\"\nsns.boxplot(df_energy['pressure'])\nplt.show()\nsns.boxplot(df_energy['temp'])\nsns.boxplot(df_energy['wind_speed'])\nsns.boxplot(df_energy['wind_deg'])\n\"\"\"\nWe can see that there are many outliers in the pressure and temperature column.We will handle these outliers.\n\"\"\"\nfrom scipy.stats.mstats import winsorize\ndf_energy['pressure']=winsorize(df_energy['pressure'],(0.1,0.1))\n\ndf_energy['wind_speed']=winsorize(df_energy['wind_speed'],(0.01,0.1))\n\"\"\"\nChecking the columns after handling the outliers\n\"\"\"\nsns.boxplot(df_energy['pressure'])\nplt.show()\nsns.boxplot(df_energy['wind_speed'])\nplt.show()\n\"\"\"\n# Checking for the missing values\n\"\"\"\nmissing=df_energy.isnull().sum()\nmissing_percent=(df_energy.isna().mean())*100\npd.concat([missing,missing_percent],axis=1,keys=[\"missing\",\"missing_percent\"])\n#making a dataframe of all missing values\ndf1=df_energy[df_energy.isnull().any(axis=1)]\n#plotting a swarmplot of all missing values with respect to date\nsns.swarmplot(x='Date', data=df1)\nplt.xticks(rotation=60)\nplt.title('Missing values with respect to time')\nplt.show()\n\"\"\"\nWe can see there are many missing values in the starting of the dataframe.\n\"\"\"\n#interpolating the missing values\ndf_energy.interpolate(method='linear', limit_direction='forward', inplace=True, axis=0)\n#Checking the dataframe after handling the missing values\ndf_energy.isnull().sum()\n#plotting to see if there is any other missing value in our dataset\nplt.figsize=(15,10)\nsns.heatmap(df_energy.isnull(),cbar=False)\nplt.show()\n\"\"\"\nSo we have handled the missing values.Now our dataset is ready to used for making model.\n\"\"\"\n#Findig the correlation between variables\ndf_energy.corr()\n\n#plotting the correlation between variables in which correlation is high\ndf5=df_energy.corr()\nplt.figure(figsize=(15, 10))\nsns.heatmap(df5[(df5>0.5)|(df5<-0.5)],annot=True,cbar=False,linewidth=0.5,linecolor='blue')\n\"\"\"\nThe temperature minumim column and the temperature maximum column are having high correlation.So we will drop these columns to avoid multicollinearity.\n\"\"\"\ndf_energy=df_energy.drop(['temp_min','temp_max'],axis=1)\n\"\"\"\nNow our dataset is ready for model building\n\"\"\"\n\"\"\"\n# Data Preparation for model building\n\"\"\"\n#segregating the categorical and numeric variables into two variables\ndf_cat=df_energy.select_dtypes(include=object)\ndf_num=df_energy.select_dtypes(include=np.number)\n#getting dummies for categorical variables\ndf_dummy=pd.get_dummies(df_cat,drop_first=True)\n#creating the final dataframe for model building\ndf_final=pd.concat([df_dummy,df_num],axis=1)\nX=df_final.drop('total load actual',axis=1)\ny=df_final['total load actual']\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\n\"\"\"\n# Model 1(Ordinary least square)\n\"\"\"\n# build a full model using OLS()\nlinreg_full_model = sm.OLS(y_train, X_train).fit()\n\n# print the summary output\nlinreg_full_model.summary()\n# predict the 'log_Property_Sale_Price' using predict()\npredicted = linreg_full_model.predict(X_test)\n# calculate rmse using rmse()\nlinreg_full_model_rmse = rmse(y_test, predicted)\n\n# calculate R-squared using rsquared\nlinreg_full_model_rsquared = linreg_full_model.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_rsquared_adj = linreg_full_model.rsquared_adj \n# create a list of column names\ncols = ['Model', 'RMSE', 'R-Squared', 'Adj. R-Squared']\n\n# create a empty dataframe of the colums\nresult_tabulation = pd.DataFrame(columns = cols)\n\n# compile the required information\nlinreg_full_model_with_metrics = pd.Series({'Model': \"Linreg full model\",\n                     'RMSE':linreg_full_model_rmse,\n                     'R-Squared': linreg_full_model_rsquared,\n                     'Adj. R-Squared': linreg_full_model_rsquared_adj     \n                   })\n\n# append our result table using append()\n# ignore_index=True: does not use the index labels\n# python can only append a Series if ignore_index=True or if the Series has a name\nresult_tabulation = result_tabulation.append(linreg_full_model_with_metrics, ignore_index = True)\n\n# print the result table\nresult_tabulation\n\"\"\"\n# Model 2(using feature engineering(Total generation from fossil))\n\"\"\"\n# create a new variable 'TotalFossil' using the variables 'generation fossil brown coal\/lignite', 'generation fossil gas', 'generation fossil hard coal', and 'generation fossil oil'\n# add the new variable to the dataframe 'df_house'\ndf_energy['TotalFossil'] = df_energy['generation fossil brown coal\/lignite'] + df_energy['generation fossil gas'] + df_energy['generation fossil hard coal'] + df_energy['generation fossil oil']\n\n\n#segregating the variables into categorical and continuous\ndf_num=df_energy.select_dtypes(include=np.number)\ndf_cat=df_energy.select_dtypes(include=object)\n#dropping the redundant variables\ndf_num=df_num.drop(['generation fossil brown coal\/lignite',\n       'generation fossil gas', 'generation fossil hard coal',\n       'generation fossil oil'], axis=1)\n#getting dummies for categorical variables\ndf_dummy=pd.get_dummies(df_cat,drop_first=True)\n\n#creating the final dataframe for model building\ndf_final=pd.concat([df_dummy,df_num],axis=1)\n\nX=df_final.drop('total load actual',axis=1)\n\ny=df_final['total load actual']\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\nlinreg_full_model_fossil = sm.OLS(y_train, X_train).fit()\n\npredicted = linreg_full_model_fossil.predict(X_test)\nlinreg_full_model_fossil_rmse = rmse(y_test, predicted)\n\n# calculate R-squared using rsquared\nlinreg_full_model_fossil_rsquared = linreg_full_model_fossil.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_fossil_rsquared_adj = linreg_full_model_fossil.rsquared_adj \n# create the result table for all accuracy scores\n# accuracy measures considered for model comparision are RMSE, R-squared value and Adjusted R-squared value\n# create a list of column names\ncols = ['Model', 'RMSE', 'R-Squared', 'Adj. R-Squared']\n\n# create a empty dataframe of the colums\n# columns: specifies the columns to be selected\n\n\n# compile the required information\nlinreg_full_model_fossil = pd.Series({'Model': \"Linreg full model with new feature(Total generation by Fossil) \",\n                     'RMSE':linreg_full_model_fossil_rmse,\n                     'R-Squared': linreg_full_model_fossil_rsquared,\n                     'Adj. R-Squared': linreg_full_model_fossil_rsquared_adj     \n                   })\n\n# append our result table using append()\n# ignore_index=True: does not use the index labels\n# python can only append a Series if ignore_index=True or if the Series has a name\nresult_tabulation = result_tabulation.append(linreg_full_model_fossil, ignore_index = True)\n\n# print the result table\nresult_tabulation\n\"\"\"\n# Model 3(Using feature engineering(Total generation from renewable energy))\n\"\"\"\n#dropping the feature added\ndf_energy=df_energy.drop('TotalFossil',axis=1)\n#creating a variable renewable in which total power generation by renewable energies are added\ndf_energy['renewable']=df_energy['generation other renewable']+df_energy['generation solar']+df_energy['generation wind onshore']+df_energy['generation hydro pumped storage consumption']+df_energy['generation hydro run-of-river and poundage']+df_energy['generation hydro water reservoir']\n#segregating the categorical and numerical variables\ndf_num=df_energy.select_dtypes(include=np.number)\ndf_cat=df_energy.select_dtypes(include=object)\n#dropping the redundant variables\ndf_num.drop(['generation hydro pumped storage consumption',\n       'generation hydro run-of-river and poundage',\n       'generation hydro water reservoir', 'generation other renewable', 'generation solar',\n       'generation wind onshore'],axis=1,inplace=True)\n#getting dummies for categorical variables\ndf_dummy=pd.get_dummies(df_cat,drop_first=True)\n\n#creating the final dataframe for model building\ndf_final=pd.concat([df_dummy,df_num],axis=1)\n\nX=df_final.drop('total load actual',axis=1)\n\ny=df_final['total load actual']\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\nlinreg_full_model_renewable = sm.OLS(y_train, X_train).fit()\n\npredicted = linreg_full_model_renewable.predict(X_test)\nlinreg_full_model_renewable_rmse = rmse(y_test, predicted)\n\n# calculate R-squared using rsquared\nlinreg_full_model_renewable_rsquared = linreg_full_model_renewable.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_renewable_rsquared_adj = linreg_full_model_renewable.rsquared_adj \n#create a list of column names\ncols = ['Model', 'RMSE', 'R-Squared', 'Adj. R-Squared']\n\n\n\n# compile the required information\nlinreg_full_model_renewable = pd.Series({'Model': \"Linreg full model with new feature(renewable) \",\n                     'RMSE':linreg_full_model_renewable_rmse,\n                     'R-Squared': linreg_full_model_renewable_rsquared,\n                     'Adj. R-Squared': linreg_full_model_renewable_rsquared_adj     \n                   })\n\n# append our result table using append()\nresult_tabulation = result_tabulation.append(linreg_full_model_renewable, ignore_index = True)\n\n# print the result table\nresult_tabulation\n#dropping the column added\ndf_energy=df_energy.drop(['renewable'],axis=1)\n\"\"\"\n# Model 4(Using VIF selecting the important features)\n\"\"\"\n#dropping the dependent variable\ndf_features = df_energy.drop(['total load actual'], axis = 1)\n\n# filter the numerical features in the dataset\ndf_numeric_features_vif = df_features.select_dtypes(include=[np.number])\n# for each numeric variable, calculate VIF and save it in a dataframe 'vif'\n\n# use for loop to iterate the VIF function \nfor ind in range(len(df_numeric_features_vif.columns)):\n    \n    # create an empty dataframe\n    vif = pd.DataFrame()\n\n    # calculate VIF using list comprehension\n    vif[\"VIF_Factor\"] = [variance_inflation_factor(df_numeric_features_vif.values, i) for i in range(df_numeric_features_vif.shape[1])]\n\n    # create a column of variable names\n    vif[\"Features\"] = df_numeric_features_vif.columns\n\n    # filter the variables with VIF greater than 10 and store it in a dataframe 'multi' \n    # one can choose the threshold other than 10 (it depends on the business requirements)\n    multi = vif[vif['VIF_Factor'] > 10]\n    \n    # if dataframe 'multi' is not empty, then sort the dataframe by VIF values\n    # if dataframe 'multi' is empty (i.e. all VIF <= 10), then print the dataframe 'vif' and break the for loop using 'break' \n    if(multi.empty == False):\n        df_sorted = multi.sort_values(by = 'VIF_Factor', ascending = False)\n    else:\n        print(vif)\n        break\n    \n    # use if-else to drop the variable with the highest VIF\n    #  else print the final dataframe 'vif' with all values after removal of variables with VIF less than 10  \n    if (df_sorted.empty == False):\n        df_numeric_features_vif = df_numeric_features_vif.drop(df_sorted.Features.iloc[0], axis=1)\n    else:\n        print(vif)\n#creating the final dataframe for model building\ndf_final = pd.concat([df_numeric_features_vif, df_dummy], axis=1)\nX=df_final\ny=df_energy[['total load actual']]\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\n# build a full model using OLS()\n# consider the log of sales price as the target variable\n# use fit() to fit the model on train data\nlinreg_full_model_vif = sm.OLS(y_train, X_train).fit()\n\n# print the summary output\nprint(linreg_full_model_vif.summary())\n# predict the 'log_Property_Sale_Price' using predict()\npredicted = linreg_full_model_vif.predict(X_test)\n# calculate rmse using rmse()\nlinreg_full_model_vif_rmse = rmse(y_test, predicted)\n\n# calculate R-squared using rsquared\nlinreg_full_model_vif_rsquared = linreg_full_model_vif.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_vif_rsquared_adj = linreg_full_model_vif.rsquared_adj \n# append the accuracy scores to the table\n# compile the required information\nlinreg_full_model_vif_metrics = pd.Series({'Model': \"Linreg with VIF\",\n                                                'RMSE': rmse(y_test,predicted)[0],\n                                                'R-Squared': linreg_full_model_vif_rsquared,\n                                                'Adj. R-Squared': linreg_full_model_vif_rsquared_adj})\n\n# append our result table using append()\n# ignore_index=True: does not use the index labels\n# python can only append a Series if ignore_index=True or if the Series has a name\nresult_tabulation = result_tabulation.append(linreg_full_model_vif_metrics, ignore_index = True)\n\n# print the result table\nresult_tabulation\n\"\"\"\n# Model 5(Using forward elimination)\n\"\"\"\n# filter the numerical features in the dataset using select_dtypes()\ndf_numeric_features = df_energy.select_dtypes(include=np.number)\n\n# filter the categorical features in the dataset using select_dtypes()\ndf_categoric_features = df_energy.select_dtypes(include = object)\n# use 'get_dummies()' from pandas to create dummy variables\ndf_dummy = pd.get_dummies(df_categoric_features, drop_first = True)\n# concatenate the numerical and dummy encoded categorical variables using concat()\ndf_final = pd.concat([df_numeric_features, df_dummy], axis=1)\nX = df_final.drop(['total load actual'], axis = 1)\ny = df_final[['total load actual']]\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\n# initiate linear regression model to use in feature selection\nlinreg = LinearRegression()\n\n# build step forward selection\nlinreg_forward = sfs(estimator = linreg, k_features = 'best', forward = True, verbose = 2, scoring = 'r2', n_jobs = -1)\n\nsfs_forward = linreg_forward.fit(X_train, y_train)\n# print the number of selected features\nprint('Number of features selected using forward selection method:', len(sfs_forward.k_feature_names_))\n\n# print a blank line\nprint('\\n')\n\n# print the selected feature names when k_features = 'best'\nprint('Features selected using forward selection method are: ')\nprint(sfs_forward.k_feature_names_)\n# consider numeric features\ndf_numeric_features = df_energy.loc[:, ['generation biomass', 'generation fossil brown coal\/lignite', 'generation fossil gas', \n                                        'generation fossil hard coal', 'generation fossil oil', 'generation hydro pumped storage consumption', 'generation hydro run-of-river and poundage', \n                                        'generation hydro water reservoir', 'generation nuclear', 'generation other', 'generation other renewable', 'generation solar', 'generation waste', \n                                        'generation wind onshore', 'temp', 'pressure', 'humidity', 'wind_speed', 'wind_deg', 'clouds_all']]\n\n# consider categoric features\ndf_categoric_features = df_energy.loc[:, [\"rain_1h\",\"snow_3h\",\"weather_main\",\"weather_description\"]]\ndummy_encoded_variables = pd.get_dummies(df_categoric_features, drop_first = True)\ndf_dummy = pd.concat([df_numeric_features, dummy_encoded_variables], axis=1)\nX=df_dummy\ny = df_energy[['total load actual']]\n\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\n# build a full model using OLS()\nlinreg_full_model_forward = sm.OLS(y_train, X_train).fit()\n\n# print the summary output\nprint(linreg_full_model_forward.summary())\nlinreg_full_model_forward_predictions = linreg_full_model_forward.predict(X_test)\n# calculate rmse using rmse()\nlinreg_full_model_forward_rmse = rmse(y_test, linreg_full_model_forward_predictions)\n\n# calculate R-squared using rsquared\nlinreg_full_model_forward_rsquared = linreg_full_model_forward.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_forward_rsquared_adj = linreg_full_model_forward.rsquared_adj \n# append the accuracy scores to the table\n# compile the required information\nlinreg_full_model_forward_metrics = pd.Series({'Model': \"Linreg with Forward Selection\",\n                                                'RMSE': linreg_full_model_forward_rmse[0],\n                                                'R-Squared': linreg_full_model_forward_rsquared,\n                                                'Adj. R-Squared': linreg_full_model_forward_rsquared_adj})\n\n# append our result table using append()\n# ignore_index=True: does not use the index labels\n# python can only append a Series if ignore_index=True or if the Series has a name\nresult_tabulation = result_tabulation.append(linreg_full_model_forward_metrics, ignore_index = True)\n\n# print the result table\nresult_tabulation\n\"\"\"\n# Model 6(Using Backward elimination) \n\"\"\"\n# filter the numerical features in the dataset using select_dtypes()\ndf_numeric_features = df_energy.select_dtypes(include=np.number)\n\n# filter the categorical features in the dataset using select_dtypes()\ndf_categoric_features = df_energy.select_dtypes(include = object)\n# use 'get_dummies()' from pandas to create dummy variables\ndummy_encoded_variables = pd.get_dummies(df_categoric_features, drop_first = True)\n# concatenate the numerical and dummy encoded categorical variables using concat()\ndf_dummy = pd.concat([df_numeric_features, dummy_encoded_variables], axis=1)\nX = df_dummy.drop(['total load actual'], axis = 1)\n\n# extract the target variable from the data set\ny = df_dummy[['total load actual']]\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\n# initiate linear regression model to use in feature selection\nlinreg = LinearRegression()\n\n# build step backward feature selection\nlinreg_backward = sfs(estimator = linreg, k_features = 'best', forward = False, verbose = 2, scoring = 'r2', n_jobs = -1)\n\n# fit the backward elimination on train data using fit()\nsfs_backward = linreg_backward.fit(X_train, y_train)\n# print the number of selected features\nprint('Number of features selected using backward elimination method:', len(sfs_backward.k_feature_names_))\n\n# print a blank line\nprint('\\n')\n\n# print the selected feature names when k_features = 'best'\nprint('Features selected using backward elimination method are: ')\nprint(sfs_backward.k_feature_names_)\n# consider numeric features\ndf_numeric_features = df_energy.loc[:, ['generation biomass', 'generation fossil brown coal\/lignite', 'generation fossil gas', 'generation fossil hard coal', \n                                        'generation fossil oil', 'generation hydro pumped storage consumption', 'generation hydro run-of-river and poundage', \n                                        'generation hydro water reservoir', 'generation nuclear', 'generation other', 'generation other renewable', 'generation solar', 'generation waste', 'generation wind onshore',\n                                        'temp', 'pressure', 'humidity', 'wind_speed', 'wind_deg', 'rain_3h', 'clouds_all', 'weather_id']]\n\n# consider categoric features\ndf_categoric_features = df_energy.loc[:, [\"rain_1h\",\"snow_3h\",\"weather_main\",\"weather_description\",\"Time\"]]\n# use 'get_dummies()' from pandas to create dummy variables\ndummy_encoded_variables = pd.get_dummies(df_categoric_features, drop_first = True)\n# concatenate the numerical and dummy encoded categorical variables using concat()\ndf_dummy = pd.concat([df_numeric_features, dummy_encoded_variables], axis=1)\nX=df_dummy\ny=df_energy[['total load actual']]\n# add the intercept column using 'add_constant()'\nX= sm.add_constant(X)\n\n\n\n# split data into train subset and test subset for predictor and target variables\n# 'test_size' returns the proportion of data to be included in the test set\n# set 'random_state' to generate the same dataset each time you run the code \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \n# print dimension of predictors train set\nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\nlinreg_full_model_backward = sm.OLS(y_train, X_train).fit()\n\n# print the summary output\nprint(linreg_full_model_backward.summary())\n# predict the 'log_Property_Sale_Price' using predict()\nlinreg_full_model_backward_predictions = linreg_full_model_backward.predict(X_test)\n# calculate rmse using rmse()\nlinreg_full_model_backward_rmse = rmse(y_test, linreg_full_model_backward_predictions)\n\n# calculate R-squared using rsquared\nlinreg_full_model_backward_rsquared = linreg_full_model_backward.rsquared\n\n# calculate Adjusted R-Squared using rsquared_adj\nlinreg_full_model_backward_rsquared_adj = linreg_full_model_backward.rsquared_adj \n# append the accuracy scores to the table\nlinreg_full_model_backward_metrics = pd.Series({'Model': \"Linreg with Backward Elimination\",\n                                                'RMSE': linreg_full_model_backward_rmse[0],\n                                                'R-Squared': linreg_full_model_backward_rsquared,\n                                                'Adj. R-Squared': linreg_full_model_backward_rsquared_adj})\n\n# append our result table using append()\nresult_tabulation = result_tabulation.append(linreg_full_model_backward_metrics, ignore_index = True)\n\n# print the result table\nresult_tabulation\n\"\"\"\n# Model 7(Linear Regression using SGD)\n\"\"\"\n#segregating the categorical and numerical variables\ndf_num=df_energy.select_dtypes(include=np.number)\ndf_cat=df_energy.select_dtypes(include=object)\n\n#getting dummies for categorical variables\ndf_dummy=pd.get_dummies(df_cat,drop_first=True)\n\n#creating the final dataframe for model building\ndf_final=pd.concat([df_dummy,df_num],axis=1)\n\nX=df_final.drop('total load actual',axis=1)\n\ny=df_final['total load actual']\n\n# split data into train subset and test subset for predictor and target variables\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)\n\n# check the dimensions of the train & test subset for \nprint(\"The shape of X_train is:\",X_train.shape)\n\n# print dimension of predictors test set\nprint(\"The shape of X_test is:\",X_test.shape)\n\n# print dimension of target train set\nprint(\"The shape of y_train is:\",y_train.shape)\n\n# print dimension of target test set\nprint(\"The shape of y_test is:\",y_test.shape)\nfrom sklearn.linear_model import LinearRegression\n# build the model\nOLS_model = LinearRegression()\n\n# fit the model\nOLS_model.fit(X_train, y_train)\n\n# predict the values\ny_pred_OLS = OLS_model.predict(X_test)\n# compute the R-Squared\nr_squared_OLS = OLS_model.score(X_train,y_train)\n\n# Number of observation or sample size\nn = 24544 \n\n# No of independent variables\np = 85\n\n#Compute Adj-R-Squared\nAdj_r_squared_OLS = 1 - (1-r_squared_OLS)*(n-1)\/(n-p-1)\n\n# Compute RMSE\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nrmse_OLS = sqrt(mean_squared_error(y_test, y_pred_OLS))\n\n\n# append the accuracy scores to the table\nlinreg_full_model_SGD = pd.Series({'Model': \"Linreg with SGD\",\n                                                'RMSE': rmse_OLS,\n                                                'R-Squared': r_squared_OLS,\n                                                'Adj. R-Squared':Adj_r_squared_OLS})\n\n# append our result table using append()\nresult_tabulation = result_tabulation.append(linreg_full_model_SGD, ignore_index = True)\n\n# print the result table\nresult_tabulation\nplt.rcParams['figure.figsize'] = [10,8]\nresult=pd.DataFrame({'Model':[1,2,3,4,5,6,7],\n                     'RMSE':[1238.66,1280.40,1696.45,6584.66,6000.29,6552.28,1238.61]}                                                                                                                             \n                   )\nresult.plot(kind='bar',x='Model',y='RMSE')\n\"\"\"\n# Conclusion:\n\"\"\"\n\"\"\"\nTotal 7 models have been built to predict the total load consumption depending upon various generation and weather factors.\nOut of all the models we select the 7th model that is linear regression using SGD to predict the total load consumption because \nit has got the best Adjusted R-squared value and least RMSE value.\n\nAs we know that Adjusted R-squared gives us information about the best features added and RMSE gives us information about \nthe least difference between actual and predicted value.Since RMSE value for linear regression with SGD is minimum so we select\nthis model to predict the power consumption.\n\nEven from the statistical summary if we see the AIC,BIC and log-likelihood values, then we can observe that the AIC and BIC values\nof linear regression with SGD is minimum.AIC and BIC is the penalty that is given to the model for losing information during model\nbuilding.So, as the values of AIC and BIC is minimum for the model we select this model.\n\"\"\"\n\"\"\"\n# Time Series Analysis\n\"\"\"\n#copying the dataframe in another dataframe\ndf=df_energy.copy(deep=True)\n#displaying the first five records\ndf.head()\n\"\"\"\n# Preparing the data\n\"\"\"\n#Dropping all the columns except total actual load and date\n#As in time series forecasting we reuire the column to be forecasted and the date\ncols = ['generation biomass', 'generation fossil brown coal\/lignite',\n       'generation fossil gas', 'generation fossil hard coal',\n       'generation fossil oil', 'generation hydro pumped storage consumption',\n       'generation hydro run-of-river and poundage',\n       'generation hydro water reservoir', 'generation nuclear',\n       'generation other', 'generation other renewable', 'generation solar',\n       'generation waste', 'generation wind onshore',\n       'temp', 'pressure', 'humidity', 'wind_speed', 'wind_deg', 'rain_1h',\n       'rain_3h', 'snow_3h', 'clouds_all', 'weather_id', 'weather_main',\n       'weather_description','Time']\ndf=df.drop(cols,axis=1)\ndf = df.sort_values('Date')\n\n#grouping the data by date and taking the sum of all the load on that date\ndf = df.groupby('Date')['total load actual'].sum().reset_index()\n#setting the index of the dataframe to date\ndf.set_index('Date', inplace=True)\n#displaying the final dataframe\ndf.head()\n#plotting the dataframe in time axis\ndf.plot(figsize=(15, 6))\nplt.show()\n\"\"\"\n# Decomposing\n\nDecomposing the time series into three distinct components: trend, seasonality, and noise.\n\"\"\"\n#resampling the data by month as working with the current data is difficult due to lots of data\ny = df['total load actual'].resample('MS').mean()\n\ndecomposition = seasonal_decompose(y)\n\nplt.plot(y, label = 'Original')\nplt.legend(loc = 'best')\n\ntrend = decomposition.trend\nplt.show()\nplt.plot(trend, label = 'Trend')\nplt.legend(loc = 'best')\n\nseasonal = decomposition.seasonal\nplt.show()\nplt.plot(seasonal, label = 'Seasonal')\nplt.legend(loc = 'upper right')\n\nresidual = decomposition.resid\nplt.show()\nplt.plot(residual, label = 'Residual')\nplt.legend(loc='best')\n\"\"\"\n# Checking Stationarity\n\"\"\"\nfrom pandas import Series\nfrom statsmodels.tsa.stattools import adfuller\n#series = Series.from_csv('daily-total-female-births.csv', header=0)\nresult = adfuller(y)\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n    print('\\t%s: %.3f' % (key, value))\n\"\"\"\nAs the p-value is greater than 0.05, it means the series is not stationary.Even the statistics value is greater than the 1% critical value so we can conclude that the series is not stationary. \n\"\"\"\n#Differencing to make the series stationary\ny = y - y.shift(1)\n#plotting the series after differencing\ny.dropna(inplace=True)\ny.plot()\nfrom statsmodels.tsa.seasonal import seasonal_decompose\ndecomposition = seasonal_decompose(y)\n\nplt.plot(y, label = 'Original')\nplt.legend(loc = 'best')\n\ntrend = decomposition.trend\nplt.show()\nplt.plot(trend, label = 'Trend')\nplt.legend(loc = 'best')\n\nseasonal = decomposition.seasonal\nplt.show()\nplt.plot(seasonal, label = 'Seasonal')\nplt.legend(loc = 'best')\n\nresidual = decomposition.resid\nplt.show()\nplt.plot(residual, label = 'Residual')\nplt.legend(loc='best')\n#dividing the data into test and train\nsize = int(len(y) * 0.95)\ntrain, test = y[0:size], y[size:len(y)]\n\"\"\"\n# Time Series Forcasting using ARIMA\n\"\"\"\np = d = q = range(0, 2)\npdq = list(itertools.product(p, d, q))\nseasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\nprint('Examples of parameter combinations for Seasonal ARIMA...')\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))\nprint('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))\nprint('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))\n\"\"\"\n# Parameter Selection \n\"\"\"\nfrom pylab import rcParams\nfor param in pdq:\n    for param_seasonal in seasonal_pdq:\n        try:\n            mod = sm.tsa.statespace.SARIMAX(y, order=param,\nseasonal_order=param_seasonal,\nenforce_stationarity=False, \nenforce_invertibility=False)\n            results = mod.fit()\n            print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n        except:\n            continue\n\"\"\"\n# Fitting the ARIMA model\n\"\"\"\nmod = sm.tsa.statespace.SARIMAX(y,\n                                order=(0, 1, 1),\n                                seasonal_order=(0, 1, 1, 12),\n                                enforce_invertibility=False)\nresults = mod.fit()\nprint(results.summary().tables[1])\n\"\"\"\n# Running Model Diagnostics\n\"\"\"\nresults.plot_diagnostics(figsize=(16, 8))\nplt.show()\n\"\"\"\n# Validating Forecasts\n\"\"\"\n#set forecasts to start at 2017\u201301\u201301 to the end of the data to forecast\npred = results.get_prediction(start=pd.to_datetime('2017-01-01'), dynamic=False)\npred_ci = pred.conf_int()\nax = y['2015':].plot(label='observed')\npred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 7))\nax.fill_between(pred_ci.index,\n                pred_ci.iloc[:, 0],\n                pred_ci.iloc[:, 1], color='k', alpha=.2)\nax.set_xlabel('Date')\nax.set_ylabel('Total Load Actual')\nplt.legend()\nplt.show()\ny_forecasted = pred.predicted_mean\ny_truth = train['2016-01-01':]\nmse = ((y_forecasted - y_truth) ** 2).mean()\nprint('The Mean Squared Error of our forecasts is {}'.format(round(mse, 2)))\n\nprint('The Root Mean Squared Error of our forecasts is {}'.format(round(np.sqrt(mse), 2)))","meta":"{'source': 'AI4Code', 'id': '1d85b3a32d2287'}"}
{"id":"64070","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n\"\"\"\n# Part 0\n**Data reading and cleaning**\n\"\"\"\nfolder = \"..\/input\/crypto-mining-data\/\"\ndataPackage = [ pd.read_csv(folder+file) for file in os.listdir(folder) ]\n\"\"\"\nLet's clean data from NaN values.\n\"\"\"\ndef del_cols_with_many_nans(data : pd.DataFrame) -> pd.DataFrame:\n    cols = list(data.columns)\n    new_cols = []\n    data_len = float(len(data))\n    for col in cols:\n        nans_count = float(data[col].isna().sum())\n        if(nans_count\/data_len <= 0.01):\n            new_cols.append(col)\n    return data[new_cols]\nfor i in range(len(dataPackage)):\n    dataPackage[i] = del_cols_with_many_nans(dataPackage[i]).dropna()\n    print( str(i+1) + \"st file\\ncols: \" + str(len(dataPackage[i].columns)) + \" number of object: \" + str(len(dataPackage[i])), end=\"\\n\\n\" )\n\"\"\"\n# Part 1\n**Primary preprocessing**\n\"\"\"\ndef select_month(data : pd.DataFrame) -> pd.DataFrame:\n    new_data = data.copy()\n    new_data[\"month\"] = list(range(len(new_data)))\n    for i in new_data.index:\n        new_data[\"month\"][i] = float( new_data[\"date\"][i].split(\"-\")[1])\n    cols = list(new_data.columns)[1:]\n    return new_data[cols].astype(\"float\")\n\ndef select_year(data : pd.DataFrame) -> pd.DataFrame:\n    new_data = data.copy()\n    new_data[\"year\"] = list(range(len(new_data)))\n    for i in new_data.index:\n        new_data[\"year\"][i] = float( new_data[\"date\"][i].split(\"-\")[0])\n    cols = list(new_data.columns)[1:]\n    return new_data[cols].astype(\"float\")\ndata_per_month = dataPackage.copy()\nfor i in range(len(data_per_month)):\n    data_per_month[i] = select_month(data_per_month[i])\n\ndata_per_year = dataPackage.copy()\nfor i in range(len(data_per_year)):\n    data_per_year[i] = select_year(data_per_year[i])\nfor i in range(len(data_per_month)):\n    data_per_month[i] = data_per_month[i].groupby(\"month\").mean()\nfor i in range(len(data_per_year)):\n    data_per_year[i] = data_per_year[i].groupby(\"year\").mean()\n\"\"\"\n# Part 2\n**Visualization**\n\"\"\"\ncryptocurrencies = [\n    \"binance coin\",\n    \"bitcoin\",\n    \"bitcoin gold\",\n    \"dash\",\n    \"dogecoin\",\n    \"ethereum\",\n    \"ethereum classic\",\n    \"litecoin\",\n    \"tether\"\n]\ndef visualize_for_month(data : pd.DataFrame, currency : str):\n    plt.figure(figsize=(13, 13))\n    for col in data.columns:\n        plt.plot(data.index, np.cbrt(np.cbrt(data[col])), label=col)\n    \n    plt.xlabel(\"month\")\n    plt.ylabel(\"root of the 9th degree of mean\")\n    plt.title(currency)\n    plt.legend()\n    plt.show()\ndef visualize_for_year(data : pd.DataFrame, currency : str):\n    global cryptocurrencies\n    \n    plt.figure(figsize=(13, 13))\n    for col in data.columns:\n        plt.plot(data.index, np.cbrt(np.cbrt(data[col])), label=col)\n    \n    plt.xlabel(\"year\")\n    plt.ylabel(\"root of the 9th degree of mean\")\n    plt.title(currency)\n    plt.legend()\n    plt.show()\n\"\"\"\nVisualization for month.\n\"\"\"\nfor i in range(9):\n    visualize_for_month(data_per_month[i], cryptocurrencies[i])\nfor i in range(9):\n    visualize_for_year(data_per_year[i], cryptocurrencies[i])","meta":"{'source': 'AI4Code', 'id': '76340a93f5933a'}"}
{"id":"19645","text":"\"\"\"\n### TPS Dec 2021 - Baseline Model\n\n- For modeling, i am using 5 Folds [data](https:\/\/www.kaggle.com\/nitishraj\/tps-dec21-5-folds) created by [Tps-dec-2021-5-folds](https:\/\/www.kaggle.com\/nitishraj\/tps-dec-2021-5-folds)\n\"\"\"\n# Import Required Libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import XGBClassifier\n\nfrom scipy.stats import mode\n# Read 5 Fold Train, Test and Sample Submission Files\ndf_train = pd.read_csv(\"..\/input\/tps-dec21-5-folds\/train_folds.csv\")\ndf_test = pd.read_csv(\"..\/input\/tabular-playground-series-dec-2021\/test.csv\")\ndf_submission = pd.read_csv(\"..\/input\/tabular-playground-series-dec-2021\/sample_submission.csv\")\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() \/ 1024**2\n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)\n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) \/ start_mem))\n\n    return df\ndf_train = reduce_mem_usage(df_train)\ndf_test = reduce_mem_usage(df_test)\nuseful_features = [c for c in df_train.columns if c not in (\"Id\", \"Cover_Type\", \"kfold\")]\n#cont_cols = [col for col in useful_features if 'Soil_Type' not in col]\n\ndf_train = df_train[df_train.Cover_Type!=5]\n\ndf_test = df_test[useful_features]\n\nfinal_test_predictions = []\nfinal_valid_predictions = {}\n\nscores = []\n\nfor fold in range(5):\n    xtrain =  df_train[df_train.kfold != fold].reset_index(drop=True)\n    xvalid = df_train[df_train.kfold == fold].reset_index(drop=True)\n    \n    xtest = df_test.copy()\n    \n    # Store IDs of validation Dataset\n    valid_ids = xvalid.Id.values.tolist()\n    \n    #Label encoding Y\n    le = preprocessing.LabelEncoder().fit(xtrain.Cover_Type)\n    \n    ytrain = le.transform(xtrain.Cover_Type)\n    yvalid = le.transform(xvalid.Cover_Type)\n    \n    #Save a copy of yvalid\n    true_valid = xvalid.Cover_Type\n    \n    n_class = len(xtrain.Cover_Type.unique())\n    \n    xtrain = xtrain[useful_features]\n    xvalid = xvalid[useful_features]\n    \n    params = {'learning_rate': 0.03811822061503613, \n              'reg_lambda': 17.136779266696237, \n              'reg_alpha': 1.196532346754796e-05, \n              'subsample': 0.16103284130404089, \n              'colsample_bytree': 0.9165052246716364, \n              'max_depth': 10,\n              'grow_policy': 'depthwise'}\n    \n    model = XGBClassifier(\n        \n        random_state = 42,\n        tree_method='gpu_hist',\n        objective = 'multi:softmax',\n        sampling_method = 'gradient_based',\n        n_estimators=10000,\n        n_jobs=-1,\n        num_class = n_class,\n        use_label_encoder=False,\n        eval_metric = 'mlogloss',\n        **params\n    )\n    model.fit(xtrain, ytrain,early_stopping_rounds=300, eval_set=[(xvalid, yvalid)], verbose=1000)\n    \n    preds_valid = le.inverse_transform(model.predict(xvalid))\n    \n    test_preds = le.inverse_transform(model.predict(xtest))\n    \n    final_test_predictions.append(test_preds)\n    \n    final_valid_predictions.update(dict(zip(valid_ids, preds_valid)))\n    \n    acc_scr = accuracy_score(true_valid, preds_valid)\n    \n    print(fold, acc_scr)\n    \n    scores.append(acc_scr)\n\n\n#final_valid_predictions = pd.DataFrame.from_dict(final_valid_predictions, orient=\"index\").reset_index()\n#final_valid_predictions.columns = [\"Id\", \"Cover_Type\"]    \n    \ndf_submission.Cover_Type = mode(np.column_stack(final_test_predictions), axis=1)[0]\ndf_submission.columns = [\"Id\", \"Cover_Type\"]\ndf_submission.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '23f0d57107f572'}"}
{"id":"119784","text":"# 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ndf = pd.read_csv('\/kaggle\/input\/all-space-missions-from-1957\/Space_Corrected.csv')\ndf.shape\n\"\"\"\n# **Quick look into the columns and datatypes**\n\"\"\"\ndf.info()\n\"\"\"\n# Look at 5 random rows from the dataset\n\"\"\"\ndf.sample(5)\n\"\"\"\n# **We observe from above result that unnamed columns are redundant, so we will remove them**\n\"\"\"\ndf = df.iloc[:,2:len(df.columns)]\n\npd.set_option('display.max_columns', None)\ndf.sample(5)\n#Find missing values\ndf.isnull().sum()\nimport missingno as mno\nprint(df.shape)\nmno.matrix(df)\nmissing=pd.DataFrame(df.isna().sum().reset_index())\nmissing.columns=['Variables','Missing']\nmissing['Percentage']=(missing['Missing']\/df.shape[0])*100\nmissing\n\"\"\"\n# Rocket column has many missing values, as the datatype is string, let's replace it with mode value\n\"\"\"\nprint(df[' Rocket'].mode())\n#The mode value is 450$M\ndf[' Rocket']=df[' Rocket'].fillna('450.0')\n\"\"\"\n# Statistics\n\"\"\"\nstats=pd.DataFrame(df.describe().T)\nstats\n\"\"\"\n# **Let us create country column from the location column **\n\"\"\"\ndf['Country'] = df.Location.apply(lambda x:x.split(',')[-1])\ndf.sample(5)\n#Top 10 countries\ncountry_df = df.Country.value_counts().head(10)\n\"\"\"\n# **Top 10 countries chart**\n\"\"\"\nsns.set_theme(style=\"darkgrid\")\nsns.barplot(x=country_df.values, y=country_df.index)\n\"\"\"\n1. Russia and USA launched almost same number of space vehicles\n\n\"\"\"\n\"\"\"\n# **Less number of Rockets are active**\n\"\"\"\nsns.countplot(x='Status Rocket', data=df)\ndf['Status Rocket'].value_counts()\ndf.nunique()\n\"\"\"\n# **Visualising the Success Rates**\n\"\"\"\nsns.countplot(x='Status Mission', data=df)\n\"\"\"\n# **Take-aways**\n1. Success Rate is more than 90%\n2. Negligible or None Prelaunch Failure\n \n\"\"\"\n\"\"\"\n# **Explore which company has high success rate**\n\"\"\"\n# Histogram \ndf['Company Name'].value_counts().head(10)\nussr=pd.DataFrame(df[df['Company Name']=='RVSN USSR'][['Status Rocket','Status Mission']].value_counts())\nussr.columns=['Count']\nussr['Percentage']=(ussr['Count']\/df[df['Company Name']=='RVSN USSR'].shape[0])*100\nussr\n\"\"\"\n# Interesting that 90.8% of RVSN USSR company were successful, but all are retired\n\"\"\"\n\"\"\"\n# other companies status\n\"\"\"\ndf_active = df[df['Status Rocket'] == \"StatusActive\"]\ndf_active = df_active.groupby('Company Name').count()['Detail'].sort_values(ascending=False).reset_index()\nlen(df_active)\n\ncompanies = df.groupby(['Company Name'])['Detail'].count().sort_values(ascending=False).reset_index()\nlen(companies)\n\ntop_20 = companies[1:40]\ncmp = df.groupby(['Company Name','Status Rocket']).count()['Detail'].reset_index()\ncmp = cmp[cmp['Company Name'].isin(top_20['Company Name'])]\nactive = cmp[cmp['Status Rocket']==\"StatusActive\"].sort_values('Detail')\nretired = cmp[cmp['Status Rocket']!=\"StatusActive\"]\nfig = go.Figure()\nfig.add_bar(y=active['Detail'],x=active['Company Name'],name='Status Active')\nfig.add_bar(y=retired['Detail'],x=retired['Company Name'],name='Status Retired')\nfig.update_layout(barmode=\"stack\",title=\"Companies and Mission Status\",yaxis_title=\"No of Missions\")\nfig.show()\n\"\"\"\n# **Time to convert date datatype from object to datetime and create more features out of it**\n\"\"\"\ndf['day'] = df['Datum'].apply(lambda x:x.split()[0])\ndf['Month']=df['Datum'].apply(lambda x:x.split()[1])\ndf['year'] = df['Datum'].apply(lambda x:x.split()[3])\ndf.head()\n\"\"\"\n# Monthwise Space Launches\n\"\"\"\nfig, ax = plt.subplots(figsize=(16,6))\nax.set_title('No. of Launches by Month', fontsize=20)\norder = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nsns.countplot(x='Month', data=df, order=order)\nax.set_xlabel('Month', fontsize=10)\nax.set_ylabel('No. of Launches', fontsize=10)\nplt.show()\n\"\"\"\n# Daywise Space Launches\n\"\"\"\ndays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\ndf_days = df.groupby('day').count()['Detail'].reset_index()\n\ndf_days['day'] = pd.Categorical(df_days['day'], categories=days, ordered=True)\ndf_days = df_days.sort_values('day')\nplt.figure(figsize=(11,4))\nsns.barplot(x='day', y='Detail', data=df_days)\nplt.ylabel('No of launches')\nb=plt.title(' Day vs No of launches')\n\"\"\"\n# Yearwise Space Launches\n\"\"\"\ndate= df.groupby('year').count()['Detail'].reset_index()\nplt.figure(figsize=(16,6))\nb=sns.barplot(x='year', y='Detail', data=date)\nplt.ylabel('no of launches')\nplt.title(' No of launches per year')\n_=b.set_xticklabels(b.get_xticklabels(), rotation=90, horizontalalignment='right')","meta":"{'source': 'AI4Code', 'id': 'dc592075b03ec3'}"}
{"id":"25765","text":"import sys\npackage_dir = \"..\/input\/pretrained-models\/pretrained-models\/pretrained-models.pytorch-master\/\"\nsys.path.insert(0, package_dir)\nimport numpy as np\nimport pandas as pd\nimport torchvision\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom PIL import Image, ImageFile\nfrom torch.utils.data import Dataset\nimport torch\nfrom torchvision import transforms\nimport os\nimport pretrainedmodels\n\ndevice = torch.device(\"cuda:0\")\nImageFile.LOAD_TRUNCATED_IMAGES = True\nclass RetinopathyDatasetTest(Dataset):\n    def __init__(self, csv_file, transform):\n        self.data = pd.read_csv(csv_file)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        img_name = os.path.join('..\/input\/aptos2019-blindness-detection\/test_images', self.data.loc[idx, 'id_code'] + '.png')\n        image = Image.open(img_name)\n        image = self.transform(image)\n        return {'image': image}\nmodel = pretrainedmodels.__dict__['resnet101'](pretrained=None)\n\nmodel.avg_pool = nn.AdaptiveAvgPool2d(1)\nmodel.last_linear = nn.Sequential(\n                          nn.BatchNorm1d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n                          nn.Dropout(p=0.25),\n                          nn.Linear(in_features=2048, out_features=2048, bias=True),\n                          nn.ReLU(),\n                          nn.BatchNorm1d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n                          nn.Dropout(p=0.5),\n                          nn.Linear(in_features=2048, out_features=1, bias=True),\n                         )\nmodel.load_state_dict(torch.load(\"..\/input\/mmmodel\/model.bin\"))\nmodel = model.to(device)\nfor param in model.parameters():\n    param.requires_grad = False\n\nmodel.eval()\ntest_transform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.RandomHorizontalFlip(),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\ntest_dataset = RetinopathyDatasetTest(csv_file='..\/input\/aptos2019-blindness-detection\/sample_submission.csv',\n                                      transform=test_transform)\n\"\"\"\n#### TTA for the lazy, like me\n\"\"\"\ntest_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)\ntest_preds1 = np.zeros((len(test_dataset), 1))\ntk0 = tqdm(test_data_loader)\nfor i, x_batch in enumerate(tk0):\n    x_batch = x_batch[\"image\"]\n    pred = model(x_batch.to(device))\n    test_preds1[i * 32:(i + 1) * 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1)\ntest_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)\ntest_preds2 = np.zeros((len(test_dataset), 1))\ntk0 = tqdm(test_data_loader)\nfor i, x_batch in enumerate(tk0):\n    x_batch = x_batch[\"image\"]\n    pred = model(x_batch.to(device))\n    test_preds2[i * 32:(i + 1) * 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1)\ntest_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)\ntest_preds3 = np.zeros((len(test_dataset), 1))\ntk0 = tqdm(test_data_loader)\nfor i, x_batch in enumerate(tk0):\n    x_batch = x_batch[\"image\"]\n    pred = model(x_batch.to(device))\n    test_preds3[i * 32:(i + 1) * 32] = pred.detach().cpu().squeeze().numpy().ravel().reshape(-1, 1)\ntest_preds = (test_preds1 + test_preds2 + test_preds3) \/ 3.0\ncoef = [0.5, 1.5, 2.5, 3.5]\n\nfor i, pred in enumerate(test_preds):\n    if pred < coef[0]:\n        test_preds[i] = 0\n    elif pred >= coef[0] and pred < coef[1]:\n        test_preds[i] = 1\n    elif pred >= coef[1] and pred < coef[2]:\n        test_preds[i] = 2\n    elif pred >= coef[2] and pred < coef[3]:\n        test_preds[i] = 3\n    else:\n        test_preds[i] = 4\n\n\nsample = pd.read_csv(\"..\/input\/aptos2019-blindness-detection\/sample_submission.csv\")\nsample.diagnosis = test_preds.astype(int)\nsample.to_csv(\"submission.csv\", index=False)\nsample","meta":"{'source': 'AI4Code', 'id': '2f7391acc104d5'}"}
{"id":"96601","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom itertools import chain\nfrom tensorflow.keras import layers\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score, accuracy_score, average_precision_score\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimport tensorflow as tf\n!pip install gdown\n!gdown --id 1qRIdvUWiNxdAXXeEoyOMya-NuES6D-Px\nDATA_DIR = '..\/input\/data'\nimage_size = 256\nbatch_size = 32\ndf = pd.read_csv('..\/input\/data\/Data_Entry_2017.csv')\ndf\ndata_image_paths = {os.path.basename(x): x for x in glob(os.path.join(DATA_DIR, 'images*', '*', '*.png'))}\ndf['path'] = df['Image Index'].map(data_image_paths.get)\ndf['path']\ndf['Finding Labels'] = df['Finding Labels'].map(lambda x: x.replace('No Finding', ''))\nlabels = np.unique(list(chain(*df['Finding Labels'].map(lambda x: x.split('|')).tolist())))\nlabels = [x for x in labels if len(x) > 0]\nlabels\nfor label in labels:\n    if len(label) > 1:\n        df[label] = df['Finding Labels'].map(lambda finding: 1.0 if label in finding else 0.0)\nlabels = [label for label in labels if df[label].sum() > 1000]\nlabels\ntrain_df, valid_df = train_test_split(df, test_size=0.20, random_state=2018, stratify=df['Finding Labels'].map(lambda x: x[:4]))\ntrain_df['labels'] = train_df.apply(lambda x: x['Finding Labels'].split('|'), axis=1)\nvalid_df['labels'] = valid_df.apply(lambda x: x['Finding Labels'].split('|'), axis=1)\ncore_idg = ImageDataGenerator(rescale=1 \/ 255,\n                                  samplewise_center=True,\n                                  samplewise_std_normalization=True,\n                                  horizontal_flip=True,\n                                  vertical_flip=False,\n                                  height_shift_range=0.05,\n                                  width_shift_range=0.1,\n                                  rotation_range=5,\n                                  shear_range=0.1,\n                                  fill_mode='reflect',\n                                  zoom_range=0.15)\n\ntrain_gen = core_idg.flow_from_dataframe(dataframe=train_df,\n                                             directory=None,\n                                             x_col='path',\n                                             y_col='labels',\n                                             class_mode='categorical',\n                                             batch_size=batch_size,\n                                             classes=labels,\n                                             target_size=(image_size, image_size))\n\nvalid_gen = core_idg.flow_from_dataframe(dataframe=valid_df,\n                                             directory=None,\n                                             x_col='path',\n                                             y_col='labels',\n                                             class_mode='categorical',\n                                             batch_size=batch_size,\n                                             classes=labels,\n                                             target_size=(image_size, image_size))\n\ntest_X, test_Y = next(core_idg.flow_from_dataframe(dataframe=valid_df,\n                                                       directory=None,\n                                                       x_col='path',\n                                                       y_col='labels',\n                                                       class_mode='categorical',\n                                                       batch_size=1024,\n                                                       classes=labels,\n                                                       target_size=(image_size, image_size)))\nfrom tensorflow.keras.applications.densenet import DenseNet121\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.applications.xception import Xception\nfrom tensorflow.keras.applications.nasnet import NASNetMobile\nfrom tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2\n\nbase_model = InceptionResNetV2(include_top=False, weights='imagenet', input_shape=(256, 256, 3))\nx = base_model.output\nx = tf.keras.layers.GlobalAveragePooling2D()(x)\noutput = tf.keras.layers.Dense(len(labels), activation=\"sigmoid\")(x)\nmodel = tf.keras.Model(base_model.input, output)\nmodel.compile(optimizer=tf.keras.optimizers.Adam(), loss='binary_crossentropy', metrics=['accuracy'])\ndef get_callbacks(model_name):\n    callbacks = []\n    tensor_board = tf.keras.callbacks.TensorBoard(log_dir='.\/logs', histogram_freq=0)\n    callbacks.append(tensor_board)\n    checkpoint = tf.keras.callbacks.ModelCheckpoint(\n        filepath=f'model.{model_name}.h5',\n        verbose=1,\n        save_best_only=True)\n    # erly = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)\n    callbacks.append(checkpoint)\n    # callbacks.append(erly)\n    return callbacks\nwith tf.device(\"gpu:0\"):\n    from tensorflow.keras.applications.densenet import DenseNet121\n    from tensorflow.keras.applications.inception_v3 import InceptionV3\n    from tensorflow.keras.applications.xception import Xception\n    from tensorflow.keras.applications.nasnet import NASNetMobile\n    from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2\n\n    base_model = InceptionResNetV2(include_top=False, weights='imagenet', input_shape=(256, 256, 3))\n    x = base_model.output\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    output = tf.keras.layers.Dense(len(labels), activation=\"sigmoid\")(x)\n    model = tf.keras.Model(base_model.input, output)\n    model.compile(optimizer=tf.keras.optimizers.Adam(), loss='binary_crossentropy', metrics=['accuracy'])\ncallbacks = get_callbacks('inceptionresnetv2')\nmodel.fit(train_gen,\n              steps_per_epoch=100,\n              validation_data=(test_X, test_Y),\n              epochs=50,\n              callbacks=callbacks)\n\"\"\"\n**Fine Tune on chexpert**\n\"\"\"\npath = \"..\/input\/chexpert-dataset\/\"\n\ntrain_df = pd.read_csv('..\/input\/chexpert-modified\/modifiedv2_train.csv')\nvalid_df = pd.read_csv('..\/input\/chexpert-modified\/modifiedv2_valid.csv')\ntrain_df[\"path\"] = path + train_df[\"Path\"]\nvalid_df[\"path\"] = path + valid_df[\"Path\"]\n\ndfs = [train_df, valid_df]\nall_xray_df = pd.concat(dfs)\nall_xray_df.sample(3)\n# all_xray_df.drop(\"No Finding\", axis=1, inplace=True)\nall_xray_df.columns\nall_xray_df['Finding Labels'] = all_xray_df['Finding Labels'].fillna('')\nall_xray_df['Finding Labels'] = all_xray_df['Finding Labels'].map(lambda x: x.replace('No Finding', ''))\nall_labels = ['Atelectasis'\n, 'Consolidation'\n, 'Infiltration'\n, 'Pneumothorax'\n, 'Edema'\n, 'Emphysema'\n, 'Fibrosis'\n, 'Pleural Effusion'\n, 'Mass'\n, 'Pneumonia'\n, 'Pleural_thickening'\n, 'Cardiomegaly'\n, 'Nodule Mass'\n, 'Hernia'\n, 'Enlarged Cardiom'\n, 'Lung Lesion'\n, 'Lung Opacity'\n, 'Pleural Other'\n,'Fracture']\n\nprint('All Labels ({}): {}'.format(len(all_labels), all_labels))\nfor c_label in all_labels:\n    if len(c_label)>1: # leave out empty labels\n        all_xray_df[c_label] = all_xray_df['Finding Labels'].map(lambda finding: 1.0 if c_label in finding else 0)\nall_xray_df.sample(3)\nall_xray_df.head()\ntrain_df, valid_df = train_test_split(all_xray_df, test_size=0.20, random_state=2018, stratify=all_xray_df['Finding Labels'].map(lambda x: x[:4]))\ntrain_df['labels'] = train_df.apply(lambda x: x['Finding Labels'].split('|'), axis=1)\nvalid_df['labels'] = valid_df.apply(lambda x: x['Finding Labels'].split('|'), axis=1)\nDATA_DIR = '..\/input\/chexpert-dataset\/CheXpert-v1.0-small\/train'\nimage_size = 256\nbatch_size = 32\ncore_idg = ImageDataGenerator(rescale=1 \/ 255,\n                                  samplewise_center=True,\n                                  samplewise_std_normalization=True,\n                                  horizontal_flip=True,\n                                  vertical_flip=False,\n                                  height_shift_range=0.05,\n                                  width_shift_range=0.1,\n                                  rotation_range=5,\n                                  shear_range=0.1,\n                                  fill_mode='reflect',\n                                  zoom_range=0.15)\n\ntrain_gen = core_idg.flow_from_dataframe(dataframe=train_df,\n                                             directory=None,\n                                             x_col='path',\n                                             y_col='labels',\n                                             class_mode='categorical',\n                                             batch_size=batch_size,\n                                             classes=all_labels,\n                                             target_size=(image_size, image_size))\n\nvalid_gen = core_idg.flow_from_dataframe(dataframe=valid_df,\n                                             directory=None,\n                                             x_col='path',\n                                             y_col='labels',\n                                             class_mode='categorical',\n                                             batch_size=batch_size,\n                                             classes=all_labels,\n                                             target_size=(image_size, image_size))\n\ntest_X, test_Y = next(core_idg.flow_from_dataframe(dataframe=valid_df,\n                                                       directory=None,\n                                                       x_col='path',\n                                                       y_col='labels',\n                                                       class_mode='categorical',\n                                                       batch_size=1024,\n                                                       classes=all_labels,\n                                                       target_size=(image_size, image_size)))\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau\nweight_path=\"{}sigmoid_activation_inceptionresnetv2.hdf5\".format('xray_class')\n\ncheckpoint = ModelCheckpoint(weight_path, monitor='val_loss', verbose=1, \n                             save_best_only=True, mode='min')\n\nearly = EarlyStopping(monitor=\"val_loss\", \n                      mode=\"min\", \n                      patience=3)\ncallbacks_list = [checkpoint, early]\nfor x, y in train_gen:\n    print(x.shape)\n    break\nnihmodel = tf.keras.models.load_model('.\/sigmoid_activation_inceptionresnetv2.h5')\nnihmodel.trainable = False\nbase_inputs = nihmodel.layers[0].input\nbase_outputs = nihmodel.layers[-2].output\ndense_1 = layers.Dense(500, activation=\"relu\")(base_outputs)\noutput_layer = layers.Dense(19, activation=\"softmax\")(dense_1)\n\nnewnihmodel = tf.keras.Model(inputs = base_inputs, outputs = output_layer)\nnewnihmodel.compile(optimizer=tf.keras.optimizers.Adam(),\n                 loss=tf.keras.losses.BinaryCrossentropy(),\n                 metrics=[\"binary_accuracy\", \"mae\"])\nnewnihmodel.summary()\nnewnihmodel.fit(train_gen, \n                            steps_per_epoch=100,\n                            validation_data = (test_X, test_Y), \n                            epochs = 10, \n                            callbacks = callbacks_list)","meta":"{'source': 'AI4Code', 'id': 'b1749c42c59ce2'}"}
{"id":"135305","text":"\"\"\"\n## Changes\n- Classification\n- Custom loss (ArcFace + BCEWithLogits)\n- Custom Architecture\n- Backbone: swin_large_patch4_window12_384_in22k\n\n**I hope you find it helpful :) !**\n\"\"\"\nimport sys\nsys.path.append(\"..\/input\/tez-lib\/\")\nsys.path.append(\"..\/input\/timmmaster\/\")\nimport os\nimport random\nimport tez\nimport albumentations\nimport pandas as pd\nimport cv2\nimport numpy as np\nimport timm\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as T\nfrom torchvision.io import read_image\nfrom sklearn import metrics\nimport torch\nfrom tez.callbacks import EarlyStopping\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom sklearn.preprocessing import StandardScaler\nimport math\ndef seed_everything(seed=2021):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    \nseed_everything()\nclass args:\n    batch_size = 8\n    image_size = 384\n    coeff = 0.2\n    epochs = 20\n    learning_rate = 1e-4\n    fold = 0\nclass PawpularDataset:\n    def __init__(self, image_paths, dense_features, targets, augmentations):\n        self.image_paths = image_paths\n        self.dense_features = dense_features\n        self.targets = targets\n        self.augmentations = augmentations\n        \n    def __len__(self):\n        return len(self.image_paths)\n    \n    def __getitem__(self, item):\n        image = cv2.imread(self.image_paths[item])\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        if self.augmentations is not None:\n            augmented = self.augmentations(image=image)\n            image = augmented[\"image\"]\n            \n        image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n        \n        features = self.dense_features[item, :]\n        targets = self.targets[item] \/ 100.\n        \n        return {\n            \"image\": torch.tensor(image, dtype=torch.float),\n            \"features\": torch.tensor(features, dtype=torch.float),\n            \"targets\": torch.tensor(targets, dtype=torch.float),\n        }\nclass ArcFaceLoss(nn.modules.Module):\n    def __init__(self, s=30.0, m=0.5):\n        super().__init__()\n        self.crit = nn.BCEWithLogitsLoss()\n        self.s = s\n        self.cos_m = math.cos(m)\n        self.sin_m = math.sin(m)\n        self.th = math.cos(math.pi - m)\n        self.mm = math.sin(math.pi - m) * m\n\n    def forward(self, logits, labels):\n        logits = logits.float()\n        cosine = logits\n        sine = torch.sqrt(1.0 - torch.pow(cosine, 2))\n        phi = cosine * self.cos_m - sine * self.sin_m\n        phi = torch.where(cosine > self.th, phi, cosine - self.mm)\n\n        output = (labels * phi) + ((1.0 - labels) * cosine)\n        output *= self.s\n        loss = self.crit(output, labels)\n        return loss \/ 2\n    \nclass ArcMarginProduct(nn.Module):\n    def __init__(self, in_features, out_features):\n        super().__init__()\n        self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        stdv = 1. \/ math.sqrt(self.weight.size(1))\n        self.weight.data.uniform_(-stdv, stdv)\n\n    def forward(self, features):\n        cosine = F.linear(F.normalize(features), F.normalize(self.weight))\n        return cosine\nclass PawpularModel(tez.Model):\n    def __init__(self):\n        super().__init__()\n\n        self.model = timm.create_model(\"swin_large_patch4_window12_384_in22k\", pretrained=True, in_chans=3)\n        in_features = self.model.head.in_features\n        self.model.head = nn.Identity()\n        self.neck = nn.Sequential(\n            nn.BatchNorm1d(in_features),\n            nn.Linear(in_features, 512, bias=False),\n            nn.ReLU(inplace=True),\n            nn.BatchNorm1d(512),\n            nn.Linear(512, 512, bias=False),\n            nn.BatchNorm1d(512)\n        )\n        self.dropout = nn.Dropout(0.1)\n        self.out = nn.Sequential(\n            nn.Linear(in_features, 512, bias=False),\n            nn.BatchNorm1d(512),\n            nn.ReLU(inplace=True),\n            nn.Linear(512, 1)\n        )\n        self.arc_margin_product = ArcMarginProduct(512, 1)\n        \n        self.step_scheduler_after = \"epoch\"\n\n    def monitor_metrics(self, outputs, targets):\n        outputs = outputs.cpu().detach().numpy()\n        targets = targets.cpu().detach().numpy()\n        rmse = metrics.mean_squared_error(targets, outputs, squared=False)\n        return {\"rmse\": rmse}\n\n    def fetch_scheduler(self):\n        sch = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n            self.optimizer, T_0=10, T_mult=1, eta_min=1e-6, last_epoch=-1\n        )\n        return sch\n\n    def fetch_optimizer(self):\n        opt = torch.optim.Adam(self.parameters(), lr=args.learning_rate)\n        return opt\n\n    def forward(self, image, features, targets=None):\n\n        x = self.model(image)\n        x = self.dropout(x)\n        x_ = self.neck(x)\n        x_ = self.arc_margin_product(x_)\n        x = self.out(x)\n        \n        if targets is not None:\n            loss_classification = nn.BCEWithLogitsLoss()(x, targets.view(-1, 1))\n            loss_metric = ArcFaceLoss()(x_, targets.view(-1, 1))\n            coeff = args.coeff\n            loss =  loss_classification * (1 - coeff) + loss_metric * coeff\n            \n            metrics = self.monitor_metrics(torch.sigmoid(x) * 100, targets * 100)\n            return x, loss, metrics\n        return x, 0, {}\ntrain_aug = albumentations.Compose(\n    [\n        albumentations.Resize(args.image_size, args.image_size, p=1),\n        albumentations.RandomResizedCrop(args.image_size, args.image_size, p=0.5),\n        albumentations.HorizontalFlip(p=0.5),\n        albumentations.VerticalFlip(p=0.5),\n        albumentations.Normalize(\n            mean=[0.485, 0.456, 0.406],\n            std=[0.229, 0.224, 0.225],\n            max_pixel_value=255.0,\n            p=1.0,\n        ),\n    ],\n    p=1.0,\n)\n\nvalid_aug = albumentations.Compose(\n    [\n        albumentations.Resize(args.image_size, args.image_size, p=1),\n        albumentations.Normalize(\n            mean=[0.485, 0.456, 0.406],\n            std=[0.229, 0.224, 0.225],\n            max_pixel_value=255.0,\n            p=1.0,\n        ),\n    ],\n    p=1.0,\n)\ndf = pd.read_csv(\"..\/input\/same-old-creating-folds\/train_10folds.csv\")\ndense_features = [\n    'Subject Focus', 'Eyes', 'Face', 'Near', 'Action', 'Accessory',\n    'Group', 'Collage', 'Human', 'Occlusion', 'Info', 'Blur'\n]\ndf_train = df[df.kfold != args.fold].reset_index(drop=True)\ndf_valid = df[df.kfold == args.fold].reset_index(drop=True)\ntrain_img_paths = [f\"..\/input\/petfinder-pawpularity-score\/train\/{x}.jpg\" for x in df_train[\"Id\"].values]\nvalid_img_paths = [f\"..\/input\/petfinder-pawpularity-score\/train\/{x}.jpg\" for x in df_valid[\"Id\"].values]\ntrain_dataset = PawpularDataset(\n    image_paths=train_img_paths,\n    dense_features=df_train[dense_features].values,\n    targets=df_train.Pawpularity.values,\n    augmentations=train_aug,\n)\n\nvalid_dataset = PawpularDataset(\n    image_paths=valid_img_paths,\n    dense_features=df_valid[dense_features].values,\n    targets=df_valid.Pawpularity.values,\n    augmentations=valid_aug,\n)\n\nmodel = PawpularModel()\n\nes = EarlyStopping(\n    monitor=\"valid_rmse\",\n    model_path=f\"model_f{args.fold}.bin\",\n    patience=3,\n    mode=\"min\",\n    save_weights_only=True,\n)\n\nmodel.fit(\n    train_dataset,\n    valid_dataset=valid_dataset,\n    train_bs=args.batch_size,\n    valid_bs=2*args.batch_size,\n    device=\"cuda\",\n    epochs=args.epochs,\n    callbacks=[es],\n    fp16=True\n)","meta":"{'source': 'AI4Code', 'id': 'f8be9afa254637'}"}
{"id":"14358","text":"\"\"\"\nJust a Simple Attempt to the unsupervised learning and finding the solution for the problem statement \n\n\nDo upvote if this notebook was helpful!!!!\n\"\"\"\n# 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 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\n# importing the necessary library\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cluster import KMeans\n# reading the data\ndata = pd.read_csv('..\/input\/unsupervised-learning-on-country-data\/Country-data.csv')\ndf = pd.read_csv('..\/input\/unsupervised-learning-on-country-data\/Country-data.csv')\n# df = \n# dropping the column\ndf.drop(columns = 'health',inplace= True)\n# first 5 rows of the dataset\ndata.head()\n# check for the null values\nsns.heatmap(data.isnull())\n# looking for the realtions of columns with each other\nsns.heatmap(data.corr(),annot = True)\n# dropping the column\ndata.drop(columns = 'health',inplace=True)\ndata.drop(columns = 'country',inplace=True)\n\n# seeing the income and gdp distribution\n\nsns.scatterplot(x = 'income',y = 'gdpp',data=data)\n\n\n#  seeing how import and exports are related to gdp\nsns.scatterplot(x = 'imports',y = 'exports',hue = 'gdpp',data=data)\n# histrogram based on the child mortalitry rate per 1000 capita\nsns.distplot(data['child_mort'],bins = 10,kde= False)\ndata.describe()\nfrom sklearn.preprocessing import MinMaxScaler\n\n# to scale the data\nscalar = MinMaxScaler()\ndata = scalar.fit_transform(data)\ndf = pd.DataFrame(data = data,columns=df.columns[1:])\n\ndf.head()\n\ndf.describe()\n\n# to get the sum of distance\nclf = KMeans()\nssd = []\nK = range(1,9)\nfor k in K:\n    km = KMeans(n_clusters=k)\n    km = km.fit(data)\n    ssd.append(km.inertia_) \nplt.figure(figsize=(10,6))\nplt.plot(K, ssd, 'bx-')\nplt.xlabel('Clusters')\nplt.ylabel('Distance')\nplt.title('Elbow Method For Optimization')\nplt.show()\n# dividing the the dataset into clusters of 5\nkmean = KMeans(n_clusters=5)\nkmean.fit(data)\n# distributed labels\npred = kmean.labels_\nprint(pred)\ndf1 = pd.read_csv('..\/input\/unsupervised-learning-on-country-data\/Country-data.csv')\n\n# gdp and income based on the clusters\nsns.scatterplot(data= df1,x = 'gdpp',y = 'income',hue=kmean.labels_)\n''' list of countries which require utmost need for the money based on \nthe income less than 1000 noticed from the above diagram'''\ndf1['country'][df1['income']<1000]","meta":"{'source': 'AI4Code', 'id': '1a37e1ea2ea3c7'}"}
{"id":"4918","text":"\"\"\"\n**This notebook is an exercise in the [Introduction to Machine Learning](https:\/\/www.kaggle.com\/learn\/intro-to-machine-learning) course.  You can reference the tutorial at [this link](https:\/\/www.kaggle.com\/alexisbcook\/machine-learning-competitions).**\n\n---\n\n\"\"\"\n\"\"\"\n# Introduction\n\nIn this exercise, you will create and submit predictions for a Kaggle competition. You can then improve your model (e.g. by adding features) to apply what you've learned and move up the leaderboard.\n\nBegin by running the code cell below to set up code checking and the filepaths for the dataset.\n\"\"\"\n# Set up code checking\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.machine_learning.ex7 import *\n\n# Set up filepaths\nimport os\nif not os.path.exists(\"..\/input\/train.csv\"):\n    os.symlink(\"..\/input\/home-data-for-ml-course\/train.csv\", \"..\/input\/train.csv\")  \n    os.symlink(\"..\/input\/home-data-for-ml-course\/test.csv\", \"..\/input\/test.csv\") \n\"\"\"\nHere's some of the code you've written so far. Start by running it again.\n\"\"\"\n# Import helpful libraries\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\n\n# Load the data, and separate the target\niowa_file_path = '..\/input\/train.csv'\nhome_data = pd.read_csv(iowa_file_path)\ny = home_data.SalePrice\n\n# Create X (After completing the exercise, you can return to modify this line!)\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\n\n# Select columns corresponding to features, and preview the data\nX = home_data[features]\nX.head()\n\n# Split into validation and training data\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)\n\n# Define a random forest model\nrf_model = RandomForestRegressor(random_state=1)\nrf_model.fit(train_X, train_y)\nrf_val_predictions = rf_model.predict(val_X)\nrf_val_mae = mean_absolute_error(rf_val_predictions, val_y)\n\nprint(\"Validation MAE for Random Forest Model: {:,.0f}\".format(rf_val_mae))\n\"\"\"\n# Train a model for the competition\n\nThe code cell above trains a Random Forest model on **`train_X`** and **`train_y`**.  \n\nUse the code cell below to build a Random Forest model and train it on all of **`X`** and **`y`**.\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\n\n# To improve accuracy, create a new Random Forest model which you will train on all training data\nrf_model_on_full_data = RandomForestRegressor(random_state = 42)\n\n# fit rf_model_on_full_data on all data from the training data\nrf_model_on_full_data.fit(train_X, train_y)\n\"\"\"\nNow, read the file of \"test\" data, and apply your model to make predictions.\n\"\"\"\n# path to file you will use for predictions\ntest_data_path = '..\/input\/test.csv'\n\n# read test data file using pandas\ntest_data = pd.read_csv(test_data_path)\n\n# test_data.columns\ntest_data.dropna(axis = 0)\n\n# create test_X which comes from test_data but includes only the columns you used for prediction.\n# The list of columns is stored in a variable called features\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\n\ntest_X = test_data[features]\n# # make predictions which we will submit. \n\ntest_preds = rf_model_on_full_data.predict(test_X)\n\"\"\"\nBefore submitting, run a check to make sure your `test_preds` have the right format.\n\"\"\"\n# Check your answer (To get credit for completing the exercise, you must get a \"Correct\" result!)\nstep_1.check()\n# step_1.solution()\n\"\"\"\n# Generate a submission\n\nRun the code cell below to generate a CSV file with your predictions that you can use to submit to the competition.\n\"\"\"\n# Run the code to save predictions in the format used for competition scoring\n\noutput = pd.DataFrame({'Id': test_data.Id,\n                       'SalePrice': test_preds})\noutput.to_csv('submission2.csv', index=False)\n\"\"\"\n# Submit to the competition\n\nTo test your results, you'll need to join the competition (if you haven't already).  So open a new window by clicking on **[this link](https:\/\/www.kaggle.com\/c\/home-data-for-ml-course)**.  Then click on the **Join Competition** button.\n\n![join competition image](https:\/\/i.imgur.com\/axBzctl.png)\n\nNext, follow the instructions below:\n1. Begin by clicking on the **Save Version** button in the top right corner of the window.  This will generate a pop-up window.  \n2. Ensure that the **Save and Run All** option is selected, and then click on the **Save** button.\n3. This generates a window in the bottom left corner of the notebook.  After it has finished running, click on the number to the right of the **Save Version** button.  This pulls up a list of versions on the right of the screen.  Click on the ellipsis **(...)** to the right of the most recent version, and select **Open in Viewer**.  This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n4. Click on the **Output** tab on the right of the screen.  Then, click on the file you would like to submit, and click on the **Submit** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\nIf you want to keep working to improve your performance, select the **Edit** button in the top right of the screen. Then you can change your code and repeat the process. There's a lot of room to improve, and you will climb up the leaderboard as you work.\n\n\n# Continue Your Progress\nThere are many ways to improve your model, and **experimenting is a great way to learn at this point.**\n\nThe best way to improve your model is to add features.  To add more features to the data, revisit the first code cell, and change this line of code to include more column names:\n```python\nfeatures = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']\n```\n\nSome features will cause errors because of issues like missing values or non-numeric data types.  Here is a complete list of potential columns that you might like to use, and that won't throw errors:\n- 'MSSubClass'\n- 'LotArea'\n- 'OverallQual' \n- 'OverallCond' \n- 'YearBuilt'\n- 'YearRemodAdd' \n- '1stFlrSF'\n- '2ndFlrSF' \n- 'LowQualFinSF' \n- 'GrLivArea'\n- 'FullBath'\n- 'HalfBath'\n- 'BedroomAbvGr' \n- 'KitchenAbvGr' \n- 'TotRmsAbvGrd' \n- 'Fireplaces' \n- 'WoodDeckSF' \n- 'OpenPorchSF'\n- 'EnclosedPorch' \n- '3SsnPorch' \n- 'ScreenPorch' \n- 'PoolArea' \n- 'MiscVal' \n- 'MoSold' \n- 'YrSold'\n\nLook at the list of columns and think about what might affect home prices.  To learn more about each of these features, take a look at the data description on the **[competition page](https:\/\/www.kaggle.com\/c\/home-data-for-ml-course\/data)**.\n\nAfter updating the code cell above that defines the features, re-run all of the code cells to evaluate the model and generate a new submission file.  \n\n\n# What's next?\n\nAs mentioned above, some of the features will throw an error if you try to use them to train your model.  The **[Intermediate Machine Learning](https:\/\/www.kaggle.com\/learn\/intermediate-machine-learning)** course will teach you how to handle these types of features. You will also learn to use **xgboost**, a technique giving even better accuracy than Random Forest.\n\nThe **[Pandas](https:\/\/kaggle.com\/Learn\/Pandas)** course will give you the data manipulation skills to quickly go from conceptual idea to implementation in your data science projects. \n\nYou are also ready for the **[Deep Learning](https:\/\/kaggle.com\/Learn\/intro-to-Deep-Learning)** course, where you will build models with better-than-human level performance at computer vision tasks.\n\"\"\"\n\"\"\"\n---\n\n\n\n\n*Have questions or comments? Visit the [course discussion forum](https:\/\/www.kaggle.com\/learn\/intro-to-machine-learning\/discussion) to chat with other learners.*\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0920005584e83d'}"}
{"id":"60010","text":"\"\"\"\n\n# Voting Baseline - Solving the Synthanic using Democracy\nThis notebook provides a simple baseline to ensemble submissions using voting.\n\n\n### Credits\nI used a random selection of public notebooks. All credit goes to the creators:\n\n@andreshg: https:\/\/www.kaggle.com\/andreshg\/tps-apr-data-visualization-and-engineering\n\n@Alexander Ryzhkov: https:\/\/www.kaggle.com\/alexryzhkov\/n3-tps-april-21-lightautoml-starter\n\n@tomwarrens: https:\/\/www.kaggle.com\/tomwarrens\/tps-april-2021-lgbm-optuna\n\n@springmanndaniel: https:\/\/www.kaggle.com\/springmanndaniel\/bagged-lgbms\n\"\"\"\n\"\"\"\n## What is voting ensembling?\nThe answer is fairly simple. \n\nWe just look at each row of our submission and retrive the prediction of each model (the votes). Then we count the votes for \"Survived\" (1) or \"Not Survived\" (0) and the prediction with the most votes wins.\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# all our submissions paths\nvoters = [\n    \"..\/input\/tps-apr-data-visualization-and-engineering\/lightautoml_utilized_300s_f1_metric.csv\",\n    \"..\/input\/n3-tps-april-21-lightautoml-starter\/submission_N3.csv\",\n    \"..\/input\/tps-april-2021-lgbm-optuna\/submission.csv\",\n    \"..\/input\/bagged-lgbms\/submission_prob.csv\"\n]\n\n# Our voters\nvoter_tags = [\"AndresHG\", \"alexryzhkov\", \"Tommaso Guerrini\", \"danzel\"]\ncombined_votes = pd.DataFrame()\n\nfor voter in voters:\n    d = pd.read_csv(voter)\n    combined_votes = pd.concat([combined_votes, d[['Survived']]], \n                             axis=1)\n    \ncombined_votes.columns=voter_tags    \n\ncombined_votes_corr = combined_votes.corr()\n\nsns.set(font_scale=1.3)\n\nfig,axes=plt.subplots(figsize=(12,12))\n\nsns.heatmap(combined_votes_corr,\n           annot=True,\n           vmin=0.7,\n           vmax=1,\n           fmt='.3f',\n           linewidth=1,\n         annot_kws={\"fontsize\":8})\n\nplt.title('Vote Correlations')\nplt.tight_layout()\ncombined_votes[\"Results\"] = combined_votes.sum(axis=1)\n# predict 1 if the majority of our voters say so\ncombined_votes[\"Survived\"] = combined_votes[\"Results\"].apply(lambda x: 1 if x > len(voters)\/2 else 0)\n# create our submission\nsub_df = pd.read_csv(\"..\/input\/tabular-playground-series-apr-2021\/sample_submission.csv\")\nsub_df[\"Survived\"] = combined_votes[\"Survived\"]\nsub_df.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '6eb2fbb4aa8482'}"}
{"id":"42947","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n* **1. Introduction**\n* **2. Feature Engineering\/Data Preprocessing**\n*       2(i). Importing Dataset\n*       2(ii). Descriptive Statistics\n*       2(iii). Handle Null or Empty Values (Data Cleaning)\n*       2(iv). Visualising Descriptive Statistics\n*       2(v). HeatMap Visualisation\n*       2(vi). Correlation Coefficient Values Each Attribute.\n*       2(vii). Label Encoder\/One Hot Encoder\n*       2(viii). Feature Split\n*       2(ix). Feature scale\n*       2(x). Resample Module Evaluate Performance\n* **3. Modeling**\n\"\"\"\n\"\"\"\n# **1. Introduction**\n\nwe will use various predictive models to see how accurate they are in detecting whether a transaction is a normal payment or a fraud. As described in the dataset.\n\nIn this dataset we have imbalanced dataset we have more transaction list of non-fraud and very less number of fraud transaction.\n\nWhich is highly imbalanced dataset..With this imabalanced dataset we won't get accuracte predictions now we need to balance both fraud and non-fraud transcation to balanced like 50:50...\n\nLet have a look how i will extract features and convert imbalanced dataset into balanced dataset\n\nWe have Non-Fraud (99.83%) of the time, while Fraud transactions occurs (0.17%) in our dataset\n\"\"\"\n\"\"\"\n# **2. Feature Engineering\/Data Preprocessing**\n\n **2(i). Importing Dataset**\n\"\"\"\n# Importing the dataset\nimport pandas as pd\ndataset = pd.read_csv(\"..\/input\/creditcardfraud\/creditcard.csv\")\n\"\"\"\n**2(ii). Descriptive Statistics**\n\"\"\"\n# Displaying the head and tail of the dataset\ndataset.head()\ndataset.tail()\n# Column key for each attributes\ndataset.columns\n# Displaying the shape and data type for each attribute.\n\nprint(dataset.shape)\ndataset.dtypes\n\"\"\"\nAs per above visuval we have 284807 rows and 31 columns.\n\nAll Attribute Having Float and Integer values only we dont have any categorical values.\n\"\"\"\n# Displaying the describe statistics in each column\n\ndataset.describe()\n\"\"\"\n# **2(iii). Handle Null or Empty Values (Data Cleaning)**\n\nCleaning any null or empty values available in our dataset\n\"\"\"\n# Displaying the only non empty count\ndataset.info()\n# Displaying the Empty cell and total cell count in each attribute.\n\ndataset.isna().sum()\n\"\"\"\nWe dont have any missing values in our dataset. So no need to clean our dataset.\n\nNow we can safely go ahead with other preprocessings.\n\"\"\"\n\"\"\"\n# Checking Balanced or Imbalanced Dataset\n\"\"\"\n# Checking percentage of each class rows.\nnon_fraud=round(dataset['Class'].value_counts()[0])\/len(dataset)*100.0\nfraud=round(dataset['Class'].value_counts()[1])\/len(dataset)*100.0\n\nprint(\"Non-Fraud Transaction data percentage %f\"%(non_fraud))\nprint(\"Fraud Trabsaction data percentage %f\"%(fraud))\n\"\"\"\n# It's ImBalance Dataset\nAs per above class percentage its clear that our dataset is imbalanced dataset.We can seed Non-fraud transaction having 99.8% data and fraud transaction only 0.17%.\n\nBy using this imabalance dataset we never get accurate perfromance.\n\nThe base for our predictive models and analysis we might get a lot of errors and our algorithms will probably overfit since it will \"assume\" that most transactions are not fraud. But we don't want our model to assume, we want our model to detect patterns that give signs of fraud!\n\"\"\"\n# Dispalying our class row count in bar plot manner.\n\ncolors=['red','blue']\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nsb.countplot('Class',data=dataset,palette=colors)\nplt.title(\"Class Distribution 0-Not Fraud and 1- Fraud\")\n\"\"\"\n# Converting all imbalanced to balanced dataset\n\"\"\"\n\"\"\"\nwe will first scale the columns comprise of Time and Amount . Time and amount should be scaled as the other columns. On the other hand, we need to also create a sub sample of the dataframe in order to have an equal amount of Fraud and Non-Fraud cases.\n\nIn this scenario, our subsample will be a dataframe with a 50\/50 ratio of fraud and non-fraud transactions. Meaning our sub-sample will have the same amount of fraud and non fraud transactions.\n\nScaled amount and scaled time are the columns with scaled values.\nThere are 492 cases of fraud in our dataset so we can randomly get 492 cases of non-fraud to create our new sub dataframe.\nWe concat the 492 cases of fraud and non fraud, creating a new sub-sample.\n\n\"\"\"\n# Since our classes are highly skewed we should make them equivalent in order to have a normal distribution of the classes.\n\n# Lets shuffle the data before creating the subsamples\n\ndataset = dataset.sample(frac=1)\n\n# amount of fraud classes 492 rows.\nfraud_dataset = dataset.loc[dataset['Class'] == 1]\nnon_fraud_dataset = dataset.loc[dataset['Class'] == 0][:492]\n\nnormal_distributed_dataset = pd.concat([fraud_dataset, non_fraud_dataset])\n\n# Shuffle dataframe rows\nnew_dataset = normal_distributed_dataset.sample(frac=1, random_state=42)\n\nnew_dataset.head()\nprint('Distribution of the Classes in the subsample dataset')\nprint(new_dataset['Class'].value_counts()\/len(new_dataset))\n\n\n\nsb.countplot('Class', data=new_dataset, palette=colors)\nplt.title('Equally Distributed Classes')\nplt.show()\n\"\"\"\n# 2(viii). Feature Split\n\"\"\"\ny=new_dataset['Class']\nx=new_dataset.drop(['Class'],axis=1)\nx=x.values\ny=y.values\nx[:1,:]\n\"\"\"\n# 2(x). Resample Module Evaluate Performance\n\"\"\"\n# Splitting the dataset into training and test set\ntrain_size=0.80\ntest_size=0.20\nseed=5\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=train_size,\n                                               test_size=test_size,random_state=seed)\n\"\"\"\n# 3. Modeling\n\n# Classification.\n\"\"\"\n# Spotcheck and compare algorithms with out applying feature scale.......\n\nn_neighbors=5\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\n\n# keeping all models in one list\nmodels=[]\nmodels.append(('LogisticRegression',LogisticRegression()))\nmodels.append(('knn',KNeighborsClassifier(n_neighbors=n_neighbors)))\nmodels.append(('SVC',SVC()))\nmodels.append((\"decision_tree\",DecisionTreeClassifier()))\nmodels.append(('Naive Bayes',GaussianNB()))\n\n# Evaluating Each model\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nnames=[]\npredictions=[]\nerror='accuracy'\nfor name,model in models:\n    fold=KFold(n_splits=10,random_state=0)\n    result=cross_val_score(model,x_train,y_train,cv=fold,scoring=error)\n    predictions.append(result)\n    names.append(name)\n    msg=\"%s : %f (%f)\"%(name,result.mean(),result.std())\n    print(msg)\n    \n\n# Visualizing the Model accuracy\nfig=plt.figure()\nfig.suptitle(\"Comparing Algorithms\")\nplt.boxplot(predictions)\nplt.show()\n\"\"\"\nClassification Algorithm accuracy without feature scale.\n\n1. LogisticRegression : 0.921243 (0.021070)\n2. knn : 0.664589 (0.038532)\n3. SVC : 0.575576 (0.048506)\n4. decision_tree : 0.923856 (0.032898)\n5. Naive Bayes : 0.871633 (0.025133)\n\"\"\"\n# Spot Checking and Comparing Algorithms With StandardScaler Scaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn. preprocessing import StandardScaler\npipelines=[]\npipelines.append(('scaled Logisitic Regression',Pipeline([('scaler',StandardScaler()),('LogisticRegression',LogisticRegression())])))\npipelines.append(('scaled KNN',Pipeline([('scaler',StandardScaler()),('KNN',KNeighborsClassifier(n_neighbors=n_neighbors))])))\npipelines.append(('scaled SVC',Pipeline([('scaler',StandardScaler()),('SVC',SVC())])))\npipelines.append(('scaled DecisionTree',Pipeline([('scaler',StandardScaler()),('decision',DecisionTreeClassifier())])))\npipelines.append(('scaled naive bayes',Pipeline([('scaler',StandardScaler()),('scaled Naive Bayes',GaussianNB())])))\n\n# Evaluating Each model\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nnames=[]\npredictions=[]\nfor name,model in models:\n    fold=KFold(n_splits=10,random_state=0)\n    result=cross_val_score(model,x_train,y_train,cv=fold,scoring=error)\n    predictions.append(result)\n    names.append(name)\n    msg=\"%s : %f (%f)\"%(name,result.mean(),result.std())\n    print(msg)\n    \n\n# Visualizing the Model accuracy\nfig=plt.figure()\nfig.suptitle(\"Comparing Algorithms\")\nplt.boxplot(predictions)\nplt.show()\n\"\"\"\nWe got an accuracy likes..\n\n1. LogisticRegression : 0.927459 (0.028305)\n2. knn : 0.637861 (0.054821)\n3. SVC : 0.515807 (0.060123)\n4. decision_tree : 0.908439 (0.031689)\n5. Naive Bayes : 0.880542 (0.028052)\n\"\"\"\n\"\"\"\nNow we are going to apply tuning to Logistic Regression and Decision Tree...\n\"\"\"\n# tuning to Logistic Regression\nimport numpy as np\nfrom sklearn.model_selection import GridSearchCV\nscaler=StandardScaler().fit(x_train)\nrescaledx=scaler.transform(x_train)\nc=[0.01,0.1,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\nparam_grid=dict(C=c)\nmodel=LogisticRegression()\nfold=KFold(n_splits=10,random_state=5)\ngrid=GridSearchCV(estimator=model,param_grid=param_grid,scoring=error,cv=fold)\ngrid_result=grid.fit(rescaledx,y_train)\n\nprint(\"Best: %f using %s \"%(grid_result.best_score_,grid_result.best_params_))\n# tuning to Decision Tree Classification Algorithm\nimport numpy as np\nfrom sklearn.model_selection import GridSearchCV\nscaler=StandardScaler().fit(x_train)\nrescaledx=scaler.transform(x_train)\nparam_grid=dict()\nmodel=DecisionTreeClassifier()\nfold=KFold(n_splits=10,random_state=5)\ngrid=GridSearchCV(estimator=model,param_grid=param_grid,scoring=error,cv=fold)\ngrid_result=grid.fit(rescaledx,y_train)\n\nprint(\"Best: %f using %s \"%(grid_result.best_score_,grid_result.best_params_))\n\"\"\"\nAfter Applying tuning to those top 2 algorithms we got accuray and with best hyper parameter and its values.\n\n1. Logistic Regression 0.943995 using {'C': 0.9} \n2. Decision Tree Classifier Best: 0.905972 using {} \n\"\"\"\n# Ensemble and Boosting algorithm to improve performance\n\n#Ensemble\n# Boosting methods\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n# Bagging methods\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nensembles=[]\nensembles.append(('scaledAB',Pipeline([('scale',StandardScaler()),('AB',AdaBoostClassifier())])))\nensembles.append(('scaledGBC',Pipeline([('scale',StandardScaler()),('GBc',GradientBoostingClassifier())])))\nensembles.append(('scaledRFC',Pipeline([('scale',StandardScaler()),('rf',RandomForestClassifier(n_estimators=10))])))\nensembles.append(('scaledETC',Pipeline([('scale',StandardScaler()),('ETC',ExtraTreesClassifier(n_estimators=10))])))\n\n# Evaluate each Ensemble Techinique\nresults=[]\nnames=[]\nfor name,model in ensembles:\n    fold=KFold(n_splits=10,random_state=5)\n    result=cross_val_score(model,x_train,y_train,cv=fold,scoring=error)\n    results.append(result)\n    names.append(name)\n    msg=\"%s : %f (%f)\"%(name,result.mean(),result.std())\n    print(msg)\n    \n# Visualizing the compared Ensemble Algorithms\nfig=plt.figure()\nfig.suptitle('Ensemble Compared Algorithms')\nplt.boxplot(results)\nplt.show()\n\"\"\"\nWe got good accuracy for this ensemble models.\n\n1. Ada Boost Classifier Algorithm 0.931289 (0.028229)\n2. GradientBoosting Classifier Algorithm 0.949059 (0.032391)\n3. Random Forest Classifier Algorithm 0.938916 (0.035196)\n4. Extra Tree Classifier Algorithm 0.932554 (0.037078)\n\nNow we are going to tuning the Random Forest and Gradient Boosting CLassification algorithms.....\n\"\"\"\n\"\"\"\nNow we are going to apply tuning Random Forest and Gradient Boosting classification algorithms.\n\"\"\"\n# Random forest Classifier Tuning\nimport numpy as np\nfrom sklearn.model_selection import GridSearchCV\nscaler=StandardScaler().fit(x_train)\nrescaledx=scaler.transform(x_train)\nn_estimators=[10,20,30,40,50,100,150,200]\nparam_grid=dict(n_estimators=n_estimators)\nmodel=RandomForestClassifier()\nfold=KFold(n_splits=10,random_state=5)\ngrid=GridSearchCV(estimator=model,param_grid=param_grid,scoring=error,cv=fold)\ngrid_result=grid.fit(rescaledx,y_train)\n\nprint(\"Best: %f using %s \"%(grid_result.best_score_,grid_result.best_params_))\n# Gradient Boosting Classifier Tuning\nimport numpy as np\nfrom sklearn.model_selection import GridSearchCV\nscaler=StandardScaler().fit(x_train)\nrescaledx=scaler.transform(x_train)\nlearning_rate=[0.01,0.05,0.1,0.2,0.3,0.4]\nn_estimators=[10,20,30,40,50,100,150,200]\nparam_grid=dict(n_estimators=n_estimators,learning_rate=learning_rate)\nmodel=GradientBoostingClassifier()\nfold=KFold(n_splits=10,random_state=5)\ngrid=GridSearchCV(estimator=model,param_grid=param_grid,scoring=error,cv=fold)\ngrid_result=grid.fit(rescaledx,y_train)\n\nprint(\"Best: %f using %s \"%(grid_result.best_score_,grid_result.best_params_))\n\"\"\"\nAfter Applying tuning to classification algorithm and ensemble algorithm we got top 4 accuracy algorithm\n\n1. Random Forest classification algorithm 0.942746 using {'n_estimators': 30} \n2. Gradient Boosting Classification algorithm 0.950357 using {'learning_rate': 0.2, 'n_estimators': 50} \n3. Logistic Regression 0.943995 using {'C': 0.9} \n4. Decision Tree Classifier Best: 0.905972 using {} \n\"\"\"\n\"\"\"\nAs per above algorithm Ada Boosting Algorithm Giving the best Accuracy So now we are going to use Ada boost algorithm to fit and predict our model.\n\"\"\"\n# Finalize Model\n# we finalized the Gradient Boosting Algorithm and evaluate the model for Hotel Booking Demand Dataset\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nscaler=StandardScaler().fit(x_train)\nscaler_x=scaler.transform(x_train)\nmodel=GradientBoostingClassifier(learning_rate=0.2,n_estimators=50)\nmodel.fit(scaler_x,y_train)\n\n#Transform the validation test set data\nscaledx_test=scaler.transform(x_test)\ny_pred=model.predict(scaledx_test)\ny_trainpred=model.predict(scaler_x)\naccuracy_mean=accuracy_score(y_train,y_trainpred)\naccuracy_matric=confusion_matrix(y_train,y_trainpred)\nprint(\"train set %f\"%accuracy_mean)\nprint(\"train set \",accuracy_matric)\n\n\n\naccuracy_mean=accuracy_score(y_test,y_pred)\naccuracy_matric=confusion_matrix(y_test,y_pred)\nprint(\"test set %f\"%accuracy_mean)\nprint(\"test set \",accuracy_matric)\n\"\"\"\nWell Done we got accuracy for training set is 100% and 92.89% for test set...\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4f26955dc9c875'}"}
{"id":"111548","text":"import pandas as pd\nimport numpy as np\nfrom pprint import pprint\nfrom time import time\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_context('talk')\ntrain = pd.read_json('..\/input\/train.json', orient='columns')\ntest = pd.read_json('..\/input\/test.json', orient='columns')\n\"\"\"\n## Distribution of cuisines in the data set\n\"\"\"\nf, ax = plt.subplots(figsize=(5,6))\nsns.countplot(y = 'cuisine', \n                   data = train,\n                  order = train.cuisine.value_counts(ascending=False).index)\n\"\"\"\n## Analysis of ingredients\n\"\"\"\ningredients_individual = Counter([ingredient for ingredient_list in train.ingredients for ingredient in ingredient_list])\ningredients_individual = pd.DataFrame.from_dict(ingredients_individual,orient='index').reset_index()\ningredients_individual = ingredients_individual.rename(columns={'index':'Ingredient', 0:'Count'})\n\"\"\"\n### Frequency of Ingredients \n\"\"\"\n\"\"\"\n### Frequency of each ingredient\n\"\"\"\ningredients_individual.sort_values('Count', ascending = False)['Count'].describe()\n\"\"\"\n### Most Common Ingredients\n\"\"\"\nf, ax = plt.subplots(figsize=(15,10))\nsns.barplot(x = 'Count', \n            y = 'Ingredient',\n            data = ingredients_individual.sort_values('Count', ascending=False).head(20))\n\"\"\"\n### Least Common Ingredients\n\"\"\"\ningredients_individual.sort_values('Count', ascending=True).head(20)\n\"\"\"\n### Distribution of number of ingredients in meals\n\"\"\"\nf, ax = plt.subplots(figsize=(15,10))\nsns.barplot(x='number_ingredients_meal',\n            y='number_meals',\n            data= (train.ingredients.map(lambda l: len(l))\n                    .value_counts()\n                    .sort_index()\n                    .reset_index()\n                    .rename(columns={'index':'number_ingredients_meal', 'ingredients':'number_meals'}))\n            )\n\"\"\"\n### Boxplots for numer of ingredients per cuisine\nThere seems to be no cuisines that use far less or more ingredients per meal.\n\"\"\"\nf, ax = plt.subplots(figsize=(32,15))\nsns.boxplot(x='cuisine',\n            y='number_ingredients',\n            data= (pd.concat([train.cuisine,train.ingredients.map(lambda l: len(l))], axis=1)\n                    .rename(columns={'ingredients':'number_ingredients'}))\n            )","meta":"{'source': 'AI4Code', 'id': 'ccf3575dc76b58'}"}
{"id":"30081","text":"# 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\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.simplefilter(\"ignore\")\nfrom sklearn.model_selection import train_test_split\nplt.rcParams.update({'font.size': 12})\nplt.rcParams[\"figure.figsize\"] = (10,5)\n\"\"\"\n# Inputting and Understanding Data\n\"\"\"\ndf=pd.read_csv('\/kaggle\/input\/room-occupancy\/file.csv')\ndf.head()\ndf.count()\ndf.describe()\n\"\"\"\n# EDA + Preprocessing\n\"\"\"\ndf.hist()\nsns.heatmap(df.corr(), annot=True, fmt='.1g', cmap=\"viridis\",);\nraw_df=df.drop('Humidity',axis=1)\nraw_df.head()\nsns.heatmap(raw_df.corr(), annot=True, fmt='.1g', cmap=\"viridis\",);\n\"\"\"\n# Model Building\n\"\"\"\nX = raw_df.drop('Occupancy', axis=1)\nY = raw_df['Occupancy']\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2)\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.svm import SVC\nmodel = LogisticRegression()\nmodel.fit(X_train,Y_train)\nY_pred=model.predict(X_test)\nLRScore = model.score(X_test,Y_test)\nprint(\"Accuracy for Method 1 - Logistic Regression:\",LRScore*100)\nmodel1 = RandomForestClassifier()\nmodel1.fit(X_train,Y_train)\nY_pred_rf=model1.predict(X_test)\nRandomForestClassifierScore = model.score(X_test,Y_test)\nprint(\"Accuracy obtained for Method 2 - Random Forest Classifier :\",RandomForestClassifierScore*100)\ntree = DecisionTreeClassifier()\ntree.fit(X_train,Y_train)\nDecisionTreeClassifierScore = tree.score(X_test,Y_test)\nprint(\"Accuracy obtained by Decision Tree Classifier model:\",DecisionTreeClassifierScore*100)\nmodelXGB = XGBClassifier(n_estimators=100, subsample=0.9, colsample_bynode=0.2)\nmodelXGB.fit(X_train,Y_train)\npreds=modelXGB.predict(X_test)\nXGBScore=modelXGB.score(X_test,Y_test)\nprint(\"Accuracy obtained by XGB model:\",XGBScore*100)\nKNN_model = KNeighborsClassifier(n_neighbors=7, metric='manhattan', weights='distance')\nKNN_model.fit(X_train, Y_train)\nKNN_model.score(X_test, Y_test)*100\nSVC_model = SVC()\nSVC_model.fit(X_train,Y_train)\nSVC_model.score(X_test, Y_test)*100\n\"\"\"\n# Predicting on overall Dataset with XGBoost\n\"\"\"\nfinal_df=pd.DataFrame(columns = ['Actual', 'Predicted'])\nfinalPreds=modelXGB.predict(X)\nfinal_df['Actual']=Y\nfinal_df['Predicted']=finalPreds\nfinal_df.head()\nXGBScore=modelXGB.score(X,Y)\nprint(\"Accuracy obtained by XGB model:\",XGBScore*100)","meta":"{'source': 'AI4Code', 'id': '37516d4d41a90e'}"}
{"id":"92674","text":"\"\"\"\n# Object Detection\n\"\"\"\n\"\"\"\n![](data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wCEAAkGBxMTEhUTExMWFRUXFxcbGRgYFx0dIBoXHSAXFx0aGhodHighIB4lGxkbITEhJSorLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGi0lHyUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf\/AABEIALYBFQMBEQACEQEDEQH\/xAAbAAACAwEBAQAAAAAAAAAAAAAEBQIDBgEAB\/\/EAFMQAAIBAgMEBgQHCwkHBAMBAAECEQADBBIhBTFBUQYTImFxgTKRobEUQlJywdHSFSMzYoKSorLh8PEHFiQ0U3ODk9MlNUNUY8LDREV0s1Xi4xf\/xAAbAQADAQEBAQEAAAAAAAAAAAAAAQIDBAUGB\/\/EAEURAAIBAgMDBQwJBAEDBQAAAAABAgMRBBIhMUFRBRMUYZIiMlJTcXKRobHC0dIGFTNCYoGCssEkk+HwojRD0yNEg+Lx\/9oADAMBAAIRAxEAPwBsm2516l\/Wn2qYgn7vKIBs3O70PtUhkrfSK2f+Hd4cF4\/lUwCF25b39XdH5I+hqQHj0itDetwbvijj50AXfd21yuD8g0AeTbVlmCjNLEAdgjU95oAYGgCu5cA5kncBQBDMx3KB84\/QJ99AHsjcXj5qgfrZqAJKpHxmPjH0AUATWgBXs3+qT+LdPtc0CRDouP6Ovzm99NghrSGcc6HwNACLYn9Yu91q0P0Epkoe0ij1AAuDKi2mkdhTop5DkKALlvrzA8dPYaAEuN\/3ha\/u\/wDVoEPLjgakgDvMUDIi8p3GfAGgCVAHqAPUAeoA6KAMl0i1xtr\/AAv1zTQjWtSAhFAESKBkCKQGe+AEAQy790D2RcNUAIzqzKguANmywUfeTEbudZ543sdLwtXLmtoVYa82qlVkNwaPo7q0OUKTFFvijeNC\/L8mkM5irjNAyAej8blJ5UCJ4i+SUhOJ1zjke7dQBPBg9dbJkAOCdRGkmkkNvQ19u4rKGUgqRII4imAHi8Wlt1zmM0KPEn9lCQm7BJcTlkSBMTrHOKBkqAPUARW4M0TqBJ8KAFWA0wM\/9K4f1jQxI70b0wyk6CW95psSGtIoqxJhGPJW9xoATbF\/rF\/5tsforTYkPKkZw0AU4P8ABp8xfcKYF1AGbxaAY9ABAyjRdOD7oigQ8tsg1y5TzKketiPpoGXK06jUc6BHnYASTA76BkBeU\/GHr+qgCYoA7NAjooGZHbeuOt+Nn9aaYjXGkBGgDhoGQNAECoI3VbJRkrKqb6jqWDG+O3mMemDuI5Tx41z5VfYes6jyvu1a2z8joskyY0zH6a0Z5gbZsLAGUb+VCEexVhZ0UcOHc31UwOXMMspKjU8u40IGEfB7aFWKjLJzQNcsNIoENsBtPDwLdsFQNyxEA9rie+abixKSI4u7ZZj1ihoUZZEwZbUb44UJMehDAdWW61jN0grOvok6CPACizC6DDjEmJMxPondz3bqQzoxlvUZxpv36eNFmFxftFrTaLcUZwQ5zaxoQACdCSANO+lcpQk1exGxiUGCy51zdUwjMJmDpHOncSi7XsV7Ps27mEFp7mWZmGAOjE8ZobsSotoJ2KHVPvlwGcsCfRgQR7AfM0N3Gk0FY5h1Vwg\/Efd800ALNiD+kYj8gfR9FNiQ6NSMrvHst4H3UARw\/oL81fcKYFopAZ69rtBe5R+qxpiNATSGUYhBExBldRodSBvGtMDsKpkKfHLr7JNAElug6A68uPq30AddgN5A8TFAHFuqdxFAFgoAyO1DOPX59n\/tpiNcaQzlAHDQBE0Aetwfzo\/SIqmJGJ2Sma\/aaDrdX9YUFMswz6E9odo6FfHuqRPaX9bp6Tb9Ox\/+tAHVeYliD83uPdQgIYjE6oMx0JMx3RER++tNITYUl+SO1O\/eG5HXTX1Uio7UdtXy7ht5zwBm+KoggcgZ9dWtCq8VFpFF6Y0Bf0dTMxrrp9NJmSLMC\/p57bQltmgEicvjxPjFedypXq0aKlSdm5JX27TOvLLFZXvCmxGGjM6uujHUmYXPmIAYzGRt3dzr576y5TbtGaezct9rbV1o5Ocq7mRU2XW8FQhrQG9p3gMDvIO8jSRpv5b4flHG8\/SVSacZPglv8nwfUaRnUcoxb2iRt4BmdN3nX0rTcmz2ozjGnFa7Dykd9GV5iVViqVtdhLL47voqamjNMJrHaysEcz+8\/VUuLtsNozi3tZrLIjBt\/dn2qK2hsR51fv5FWxf6xifnD2FhVMyQ5NIZRijCOeSt7jQB2z6K+A91AFgoAzv\/ALifAf8A1\/tp7hGhNIZTiNw+cn6y0wLaAI3ACDIB8aQELFsACAAYGsUwLaAOigDI43XaA\/vLPuSmI1xpDOUAcoA9QBkLP8o9lVdRhMVDOWbNl0bTSQ+m4aVDcZby0px1ysj\/AP6RZ4Ya75sPt0c2iecO4v8AlBt3subBO+QQDnOgPOG99N2jvGry2IG\/nlYj+oNA\/wCo2nj2qWZbLjyStezCj\/KLbIj4DbiIgZRv8Bv76vKZ5gFumWG0BwbaTB6zn3zr50ZWGZHsH0vtNftqcORbZlX0jmBbsSWz7pPLdRZgpJGl2hhMKttLlpmIFw2yJmHGeQCBMhgRBnd3URk72Kqd1qwWztDJA0JYADMO9vtCraM00X4Xay78onJJGnEr3Tx9lefylhliKcaUnZOS2eRv+DKqlNJdYdaxF9hmGHIAMAt2d+k9qN5ivIf0coL\/ALkvUQsEnvKjiGYm1ltjQhvvi6buR5Eeuro8iQpVFUjN3TvrY0WDUXmUiN7YlmdLqHd8cjjrxndNerkr+H\/xR0tSaSzepHvuNZ39banhLnx99PJWv3\/\/ABQrSy2zeoo+5S87HD\/jH7NTOlWl9\/1I1oN0133qXxIDYo0g2T\/jH6qHTr2tn9SBaNPO\/QviORZHUFAUJyxl6wcgIk1pGFVLv\/UjCam23m9RDZ+FZbl1igAdtCLimRLGYnTf7aMlXw\/+KJUJ8fUG3nVRLMqjvZRr66MlTxnqQ8k3v9RRjGHUu4GZerYyDIIIMQw0g86eSp4z1ITjPj6iaxAjupLnI1EnK6d91tglmTSbOiug0M7Z\/wB4v+\/\/AAxTEaI0hlGJ3D56e8UAW0AV4k9hvmt7jQBZFAHqYEgKAMje\/wB4f4tv3LQI1xFIZGgD1MD1AHyS3s+7fRhaQuBuIbe0WwVkgK27fPOuKF1JO3qPRqNOLV\/WG4ToJjWUHqXEka5rcRGu4n41dDnO+w5FClbVjTDdBsQunwa+Zgz19gCRPCCffTlHNtFCeTYM36D3iI6iZmf6SBy3wg9nKoVKzuaSrtqxRc6BupRTZthnkAfCWJkDNpKxoK17ow7k9d\/k7vEaWbY0\/wCYMz5rHto7oVoihv5N9ogSqW8w1H30bxqPbV3M8ps9o7DvqLQt2vvYuYi5c7QJDXCzgwDJ1d90xpUxVtpo3poZ2\/jrCnQPdO+PQXh4sRr3U84Km2HbEv8AWK5zLh0Xsnq1AaJEnrWk92vOuXENuVO3he7IVSGXL\/u5ntjs1ywVckdRilYEuGL2cwIJIPGW0PLdW0tClrdI+Yqc5LsBLEsdOLHMfaa2WiMZO7LksjkPVQItFochQM8ba8h6qAI9WOQ9VAETZX5I9VAjnUr8keqgCSsQIBjwNAXZuui2NuLgnuFyUS3fVlOsuWlJnXQHLviG8Iyku6NovuTXWbgg6HhwqKn2sP1fwZN90vzJLfFbGhn8O\/8ATbjAE7\/1QKBDZ79yTCiOGh3U7IV2cu4hoTMhnONw5a0WC4RbvSfRYeIpWHc9jPwb6H0TwPKgYRl7jSAU4rC9snXWTurVPQza1ILhOR3n2fxp3Jymej+kn+8FRvLWw0z32G5jTsJssGKPPypWKTuWfCu79\/XU2KLbNwN5UWC5jdl4U27Vu0GGgAPDU6k6cyTQ0rgm7H1LBJltqvICgAiaAPTQBwjcYGm7uoA7NAHpoA8GoAwPSjA2rd95DZrnaEEDKDAMSN2YSeQ3RU2NM+iM7i7wGaZINpzqeT2Rp+USe+sa\/fU\/O92Rz1Xs8vxFewMY8bSy8LNsL3EswB8jrW89bFw01ElrCsAB2fzj9mtDMu6h+SfnH7NIDnwV+S\/nn7NMDvwV\/kr+efs0ASXDv8kfnfsoC502G+SPz\/2UBcraw\/yR+d+ygRE2G+T+kPqoAebKusuzMchBkXbDeTsgj12zUNd0jSL7ln09segJMnQ8jWFT7WH5\/wACb7pfmVHbCcAT+\/fW9i7mc2fjv6XcugTOaNY5UWFc0A2mTuA9c08oswNitoOSg7Ppg7u5u+iwsxFtqv8AKHqH1U7ILsQ3dqXS7g3miW0kxHKOVVZWIu77Sn7ovE9cxPzv207IWZh2DxRyglpnu+kb6MrHmXEKON5H2GlZhmXER2Lg+Elp06xj7TU7y9w6v3xIIZY41RB1byxOYeEihjRDGYsqhZcpOmm\/lSsNyYPZ2xc5IPJvoNPKTnYNsu4r3FyXM2o0Mka6azr7ag1NuelOEEffgfmqzD1qppWYzn87sJ\/aN\/lXPsUWYED0ywny3\/ybn2aLMCH89sJ8t\/8AKf7NFmB49NcJ8pz4Wm+kUWYaEV6b4Y8Lv+WfroswLh0xwvO5\/ltRYRmenu0bGKsqyHMLVy2HlCCEuZgd41EqNBxotqPcZXalyLl4ERGGf19ahPvrnxHfU\/P92RlU3eUA6LOCu0jMjq7XsY10SWwuL2hmz7n3sefvrSxjchjXEjwpNFJhuz+j2Jvp1lq3mUkicyjUb9CQa83E8rYTDVObqzs\/I37EUoNksV0YxdpGuPahFBJOdDAHcGmoo8t4KtUVOnO7ei0l8B5GhJ1leqSTzc6BHAwoAizj2UAH4C5\/s\/aHOMJ\/9j1L2ouOxh3Qva14jtXXYTbHaYnfn5nuHqrCp9vT\/V\/Bm33S\/M2b4hvlH110WRd2I8Bc+\/3CPlPwHOhbRtuwxF9p3+wfVTshZmSwWAe65uLlJBAObwOgFebjuVMPgnGNW+uyyvsKSbGD7Ku6nJZ9X7K4Y\/STAt2Tl6P8jyyM42EQy+oJO4btf419C9NDJK5H7mJIEkAkzMd\/dRmDKFthxbESCogd\/npUupI2jSpW1WoQyWwMxYARqSdKtVXvMJUNdDO4O4pvFgQVzuQQd4kxB79KlPurltdxYeZFgTv5AzHnWrqWMVSuXWmRdMoJJ3kD6aynK+pvThlVmDbStC4hCgCSPZPKmtLEy1bsLBst\/lD8407k5RV0MzDF4ZQYD3SCOa27TaH8pgfEVDNEP+jGEtOjG6WVVFuMu8sxygQASSWIAA514\/LOOr4SMOYSbbe3glfiikk2x5Y2XhHfq1e8W7RiCNFOUmSkROk868CfL\/KMIZ5Rhb4\/qKyRM9eUBmAJ0YjyBr7WlJyhGT3pMyKGtoTr9NWBYthBqB5T9NAF6BRuT20DLezGqe39lAAL2g1rEpGhsM48bT2rg9mYUmOILsIdu6zJ1n3lAZE6ZrQYxBkgDNHGK8PlttU4Wlbutuz7srfA6cJZ1Y3V9V\/P\/wChhuOqPkwirmQyAN5ClgGUJr2gB5+VeLGXdWdd7ePXxzcNT35RWX7Jf6vIW9cQhb4IPSAAA3iJzRkkDcN066xBpKc8yjz72X2+rvtv+q4c3C1+aXo\/wRwzMWVXw41PpZIgZZ+SRv01I3iJg06tSWVyjWem7M+Pl9ifXYVOnG6UqS9H+BzsVFOGUfCFsdq\/AzZZkwGEOuqndMjU6TBE8qwqPFuUaTn3MNivsWzY9vp\/K9\/nbpN+V+0JvrbGGxCHFJee4Gyg3dACNEAe43GdSZM67q5sJCqsZRqOhKMYtX7h+l2ivYKTTT1MbY2FdbRLaMY3K9sn1Bq+46dRt97sT+U5srLx0Xvt6FoNvkApK6kQwDGN3Ol0+j+LsT+UeSRE9E8V\/wAufMoPeaOnUfxdifyhkkRPRXE\/8v7U+1R06j+LsT+UMki610axK4TGWuo7dxbGRQydopcLHXNGgPGpljaV133Yn8ppGLs7lXR7o5jLKnNh2JDIQMyagF53N3isKmMpOtTazfe+5Pq\/CQ4PMh9tBLhtOCgtvl3M6KRu1nPFb9Npfi7E\/lNLCzYWDuj0su7+1tnXTkxprG0vxdifyg1oOPgrc1\/zF+uq6ZS\/F2J\/KRlDNn2VVGFxwnbRhqCG0Oh4EcfEA8K+c5aVTE1IPDwcrKSejTWq42a+BrHTaX7Mt4eyWPwjOSABmYaQAs+JiSeJJNeTVwePquN6DSTvp5b+rdwRV0JGwx3Z7fD44r7l4pN95LssytYZbJ2fbdiLhkRpkceEERPHeDUvFLwZdllKIVtAYUTba8bDDSResg67jFyfEaULELwZdljAsNhcIVdLuN6xWkS1+xJUj8RVj2+NHSPwy7LApXonhlTrMNezKgOhdGUwNe0BoRv1n20dJ4xl2WDWhS2DH9ooPzx9dPpK8GXZZBA22UwWHA6QQQda2p1Y1Y3jfetdNmgLQ4EiYOkj3VoDLF3UyTO9CUHwrBHibl9vJkb6Uo3ANejWNW1auM1sXARbUqToZzb5B5cq8blfBPGTpU4zytZne19iXWuJd7NjbD9JbasSmFRSeKsATPgnGvKn9F5yVpYhtdcf\/sPP1CaxjLV649s2byXM3ZBdO3mLfiSN24j9vvxjiIwSVSFkvAe7\/wCQWXW1hkuxH\/sLnnft\/YrF4qov+5D+3L\/yGioS4BA2M0LNptN\/35N0\/Mg6eFZVcXWcWo1I38yXzs1p4ezvL\/fYSs7HO42rg369Zb37xPZHd5VhDFYlSu6kbeY\/nQ6lF5e5RC7sxxJ6i4YHC7bM90Za61iavjIdiX\/kMuYlwFFy4tvN1lm\/bYpcRczKytmRhrCgxp3axvr0OTqlWpiqac4NXWii7\/vfsOnA0rYukmvvL2iTZGNuZLrC2Z6hiNTvm0QN3edfxe+vo8Y8\/R5cytZ+5J22eX0dZ9JXqOSoTjRSvK\/l7hu2zrfo6yt8fdBI7R3a5jr+58u+vQnQpxbSoRezcvh\/jiz1KkpRk0qSdrfnp5P8cWE4PaVxRLEzu3z38a8jlvA4erhoqpSS7rdpue9WZ5fLFepSw0ZxWV5rbtmVvev9saHo\/tBWF1rwLKgSIgGWbLzA3kakgDeSBX5zy3gadFU1h1Ztu+16JX6\/Urs+cjyjiX971L4DjD2MHdZLYsT+EInLChWysTDcX8TrXiyxWPoxc+ea2b3rdabuBjzl3dpdmPwMPjwB1ohQFbswqjTMRvAndX3dGNnTd3qtbyb3J7GzKTzU53S0tsSW\/qRXhcVdtXLaWiA7BWaY1n0QSdwjX191drdzCKsfQb\/SC1avX1awzk9WrFQILBRmk9xaPKhR0Lckgf8AnJhxuwDHxb9hp5Sc6OHpRaH\/ALePz\/8A+dGUM5EdK7X\/AOPX88f6dGUecV9I9vh7Oa3hzYIZRo05pk8FG7KefpVvhMixMM8c18yt+V+vgelyW6brLPBS26PXc3wfAzR2tebsHPlGYgHdy0Hf7q+mVGi5NcwtL7lu\/Lf7NT6yNDDym49HWl9y1t+W17urXqB7eNZfRRhpwBGkTy8h9FTko7qC9HVfh6OPUQ6WG3YZdnqvw\/Jcd9jY7DwYu2i9y6EC7y3eSBJJEcq+L+kvKX1fi1Tp0s19ydrWS3JPifMcr0IQxk4wSS00Wi71Du7sdXRUF5dCNwBkqCCIzd9fIQ+kMqdWVR0Xrf73Fr8PUedkEGDwhutAMADtH3acz9dfbEjvB7DsMwUu5JExIgx4CfbQMY3+jCGOruXLXPLlM+OdW9kUmguCP0OQ6tdZzp2mVJPDWFA9QFZVqsKFN1KjtFbdv8DvcivRS2DpcP5o+iK8z6+5P8b\/AMZfAdmXbP6LlFKtibjqZ3qg3+Ar0cPXpYiCqUndcdV7RXKsV0VYAlHDHkRHtraSYKyE2NSDBEEIgIPCANKxwney86XtZMtpVZHY866mI5QAi6C2ycZgkAPYw\/WN81jeAPjLgR4HwHsElsDcDjrNrCX1dLjXUZFK5fRIYgAFiBPZafLnXNUt0in5Je6N7WD47pArNZ+D2TamFIfJmMsVBOUnUyTPEW2GmlRimpRcXsSub0VbU1vwLDuyX7jFrqEgZWOmQmMwDAGTru4159GniXTSTsmuBvOdNS1Dbm1E1g+Gm8980Lkyo94ulRKW2t+K0cYC7vNh31f1U\/CJ6WuBSm1oZiBc7R3HJGmgjtadnfv1qvqxtJNh0pcC+3tbXtBo4won9apfJcraS\/30AsWuBRtPE2b1sq6zxE8DzkDSunAYKrSxMJxlqmdOExS56NuIq6R4K3h7D3MKq3D1ZlGZgcoKs3GScqyI5NvkRdTlDlGU6aq1WrSunaO3K1w6zafKOIrxuqmsbSWi27OHBsT9Gbli\/hrt+6qoLT6kO0BYkkmSY37uVdb5Q5RVZQeIlsv3sOPmnKuWOUGvtn6I\/Ax+0OmdnrItYcdWPjM7Atv1y5jAjhv3+WlSvjqitKs2uuFN+6Zz5TxlVWqVLrrjB+2JsOj2PJsXL9pOyMmq3HAIOaZhgTBA9deXXjXrVYU6kk13T1p0nstxg+JM8VUirqUexT+UZt0quW7dtwBqHnM7sPSI4sZ3Dv4CuaXIlLEqrGo9kobIU4vWL8GC9C0e16kSqTqUJTbV047IxW1S4Lq\/MaL0QUibiT1sEhcwOpzHe8gDMSdBHAE6VpiKdWhBSjUfcxla6juj5DOEJOEu64blxEWybJfHlb9jq3z52kvIHaIMFojIGMRHaFdipVfGv0R+Bk4yvt9gbaxIdQ5QZnm4dTvc5zrP41aqjU8Y\/RH4GMk29pZ1i\/IHrP10c1U8Y\/RH4BlfEj1i\/IHrb66OZqeMfoj8As+J43F+SPW310KlV8Y\/RH4A4viUYhwwyZBB1Op4eJ7668KqtF88qjbTtqo21T4LqO\/B16uGi69OWqaWxb1L4AowKSOzpB4nhH116a5UxPNylm1TW5b7\/A9aHLmNdGU3JXTiti3qV\/YiYwNoOkjsM2RtT2S\/ZRvAPlB7mJ4Vm+VsV4S9CMF9IMde2ZehGi2DhkyOi2rxysmgkFWGbUGVI4zr3V8h9IcPiMfiISpyjmtK99lu5XBnDVxVSvUdSrtdvUhsr28OsZHQRMEE6KIgancqgQO6vlqnI2LqVMspRve217b+TizPOkItnYUBAfSzGRI4btx8PbX6HJakJ3RzBbWC425bVRlw+Ha4Txz5SxXwIZfMGiwrl7dK7\/ybX5rfbqspDqF+A6R3rlxUYWwpmSFYQACd5cjhXmctQbwNVRV3Ze1DhO8iK4BuxON0GTNDMC0NLa9bpmHdpw00r4lxqa2w0tb27nZpp93d69+upvdcQvGbavI+W0tp0gdotrPH44r6nkOao4OMKqald6ZZcfIZSlroct7fxH9lbPg4+0a9bpVHi+zL4CuwTa1lrpFzJlYhQy5geEgiTw1U+C865sPi6SUtX30t0uPkK2gabOuEcBrxYevf3+yujplLr7MvgFjtvZ9zgs+BB+msqnKWGp2zzt5U17UOwL0X2dZOItXVUq1uUDS05dQEGYnsa7t24jga7QFm0cERcxqEyfhA9Re6wJ8jXNWaVem+qXuha7sItgw+JV\/ipnufkWwVX9Ut\/imuTFzfNNb5NL07TrhHukuB9a6PJlwlpfg7OxScxFuCWlplmmNeVeqkkrI4m7u5nLlgoxVhDA6jvqiDpuCmSde4IAA1oGVZCTrvoA9iF7J8DWuH+1j5Tqwf28PKSvyV7J7XDx3j17vOuSrRhVjaauY0qsqbvF2Mhty7fs2bhR26u5ftugzbrZS4cn5LgjvyA15NGhSdfI4rSLv5VJa+g7Klep3yltMo22bs6XXA4ifrr0Oh0PARl0qt4TH+xcRi7mFv5Hd3z2soB3LLzu3DQ765amHorEU1lVrS90OerNXzMf7Ks3str4QzZra3HcSDKqzPlMadoAL4kbq6sNQpNYhWVs1P9svibxrVVQnd65o+yZo8JisRZZMtsXFzolxsygh2yhngjUak6Nw3VjjKVOFCo4qzyy9jOfnak1qwTZmJfGYu472Xw5fDtblsp7ZDJmBViDCndIPrrtMwluiOLAATEYeAAO1YuTAEcLvdVZyObPW+imM+NiMMfCxcH\/lozA4F69FL3G\/a8rbfbozhzZXd6JYn4uJsAd+Hc\/8AnFGcObRS3QzF7\/hlnjuwzd3\/AFzyrWFfLFxcU07bb7r8GuJ0UpxhBwcVJNp633X4NcWW4fojiAZbFW20jSyw5fjnlRKveOVRS1T0vuvxb4jlVTg4RhGKbT0zbr276T4vcdxHQ266sjYhAGEGLZPq7YrLMc2TW4btbFX8HLW7XXtcNsE5lSWh87EMdO0J4+lxg1yvXExX4Ze2JWzUoxOOuXLWe8FU5CYDZgCVadYHsrztek6+F7yB6lGM2nYsMq3biocqwDviAJgaxM17VrhdIzHRfEZ32hc3lk9j3AI8ACR5VRC3h0Sau5lYJwXpfk3P1Grkxn2X6ofviVFalNddySm7dCxJA5ngq69o+owOJ8zSbHGOupO+2RTcDMV1iTIIAMmNwk8ABu76hG1w7GBwV7YH3u3pl\/FH41YYVaS86XtZLkQ6i5oesH5v7a6rCzDfouHBu5yD6EQPnV8l9KtlH9XumtN3uI9g7QKYgWijAZc2eRGjKsRvmGB5V9REclvGe3Nr4nC3sS9jDrcDNYZSLiqXLKUaZGhBQeM+NcVavCOJpwb1tL+LFKnJq6EGzLd3EYnFPcw7WHuoNCVYDMuUlWXQjsid2pI4GuXH1IxqU7a2d2vIdVCLad+FjZYW5ilRVGJACgADqV3DQceVV9a3+56yFg+sEvbMZ2LteYkmSQiCT4Qah8q1N0UV0SPEtt7MA+M0+Q+il9aVOC\/38w6JAkdnjdmf9H7NL60q8F\/v5j6JAiNmDfnfw7EfqzTXKlXgv9\/MXRIHMZhFCNv3Hl9VdOD5SqSxEItLVm+GwsI1YvrOfcxRJzEcddwiudcq1PBRzdDjxPlXSbaeew7AsF+EgIOS5LjbuEkkxzPGu2P\/AFSbWrhr2kc89NEZUW2PartM9p9Q6HbNxOHwi37N5TdusjgOvYRCLh4asSGjzBA0Jrhqv+pp+SX8GuuVammw+Fv4m4pvtbVntEZ7QLKcl224kEIYgAHx7q6sO\/t\/Op\/tkbx\/6afnR9kykF7OIKZ80XVUmIBkqp0k+81y453w9XzZexnPGNhjsRVbDucsuksIO879\/lFdSA9svpRn5qMzCLgDQVOQjOMsaiNQ1XYkZHpFaW292995RMuZmzFe0YENlmSdIIBncCIJVgBG6c7PCC4cSoRiQrlLgUkbwGKQSOIG6nlFmJYrphgRCPiAjOBlBS4Cwb0SoKazwNFh3LF6WYMXOo66bw0Nvq7meYnVBbmY13UWFcpXpxs8hyMQCLYlyLd05BMS0WzAnSTxoyhmCLHSWzdtrcw5F5WfJmAcANEkGVBzRuWJMjcNaGrDTuL9o7UW5CXFzhmVIgLlLaBgGDaiflR3VjUoQqNOS2cG17GhizpCjWsthcRFzMqwwUz2XIkBRqQM0DlXl4bD0ulS26Xerb3q21+0Qn2v0cw+Ja2cTccXQioCjKMx7bwAVIO5zAjQGvZuFg\/oT0dOHa+s9dZuhU1EEr280xqN4jU7uFO4rD3HdDQ2trE3LfcVRx5aA+smi7FkRHA9EXtklsU1zRhraQRIK6EGeM1zYuT5r9UP3xGoK5DH9H0soXfEEDhFtSWbkBNdd2RlSMDt2+pu5DftKyBdC3GA2bKO8g6\/JFPaGwmm0y1pLJIOXsFl3NC6Ed2WPOaEI2GOsy0\/ir7hXNhnpLzpe1jaBjcbQE7t1dRA66OtOf8AJ\/7q+S+lWyj+r3TWlvM\/s1ldjbkZ8mYA8iSublvivp0aMWYLHtcwjMSS6uisSS3oFhqSZPZA499fO4mEvrBb7p\/x\/J202ubj1XGuxcfKB1bRhMnnuIrjxsqyrPO9UdeHVNx0WhqMDhr1xA6qGBnu3b9491ddLAVKlNTUtvUZTqwjJxYIuIcubYABBjUkT4Qp1nSKqPJlWWyfqFOtGKvYTt0qQbw48bVz\/Tq\/qet4xegz6VBfdYXsnbYxDlEaGC5u2lxREqu824mWGnjyo+p63jEHTKfgsK2ni2sW+sdlK5gsJmcyQTuVOQNH1PW8YvQHS6fgsTXOlCsCuW7qD\/wnA9ZSuvAck1YYmEnNOzNsPioSqxiovaUdKukLJg8wBXrpUZgwYLLKSVKiAcrAHv0rLDclypzjKc7nO8SpReWJ852ph3XBw4yk4m2wB+S1pyNO8EGu9O+LVvAf7kcUotLUVg5VPYDaDy8ONdhmfWtl4q62Et9jJIQqNNUAnsk8Cp0B1EEa6GvPq6YmC6pfwbLYrj\/ZeMyNhOrIPW9YktwJZdYHGViJ4114fva3nQ\/azojbmJ+dH2SElu4wxmIXNqMaRp3m2xXw7RFcmNd8NV82XsZlJZWrcEM+gmOF4MSAO1eQj5jlfaAD512JW0Mm7heL6OOr5rZDa5gJ7Q1zEmd+vfryqrtBoxT0yR7qXbt4RK9VdGSMlt8oS5rqwW6qnx8aM3AWVbTC2dkltmW7V+7bwxF+46G6W7QaUYhUDNlkbyADwNVcm2mo2xTYdns3PhuHzJhjaDMl6Q8iHSLYI0BXMCrDMYIIFIYYmNwpxlnE\/C8Oxts5JC3sxVgAFnIcwBBbUwMxAA1k1DQR7O2Yot45LWKsX7uKt5ERS6mc+fKDcRVk7gJ1pgbLoBZu2sPaCiDabVSsl7zgO4YcOrtsqE86TYJGjwexG6zrLhCksWIG8kknyHCJjhUlCzpKGGJX5LMpPgLd0frLXm4d\/wBVP8\/bELC\/rDmmOAHqza\/pV6Nxk7u0Fs285bLmYKCOE8xyAknw76aFbU0\/RQret5nJRpjKGGvHMDqCDOkEiKyjNN2ehrONkragm2ekiYe8bWtyFdpHDKrXIPCYXf37q5cTVWTL+KH74j5p5cxlOku3ruIGHe0mQujMoYicmZkkiOJXSINd0Z3bRlKFjLYzC4e839KssbgAl7bMCeUrorRzEnTWrIPbKwdsYi3atMWtKrFSwXlqDCCY5tz9dInea\/F4JAyk9Z+Dtjs3rgGij4uaPOubC7JedL2sbSPWrNvhJ8XY+811aish70ZQA3I\/E4n8avkvpTso\/q900gjK7Itq2LtPnZJs3VlQpzdq02oYR3+VfUIb3Gd6I3f6HibZPaUhvzluoD+hXlYxZcbRnxUl7DajqmgfYe2biWl7UDQxA468RW2JwVKq80lqaUK8o6I+hdHen5t2jbKht5WeHq3idamjJ0I82lpuNalKNR5rifbW2Wuhyq9tuMr6Wuo4r+yuinUSWu0yqQb0Wwx9+7tPMSMViYk7sVc92et1VjxMHRlwK7OP2qrK3wm+2UzlfEMynuZS8EVXOxI5mfAntnaOPvZVX7xbWexbvZZJMktBE92mkmjnY8QdKb3C\/AJjBcUteuFZMj4ROnKM+tdOEqxdeKvvOrA0pLEQut482FiLhtMmJZrpJ3tcDyCAIbMSSNN3fXJzkJJNnPCNWCaW890ow1y7auXGec+JRgSOHVuuXTlu8qwiv6pNeA\/3Iio3sYn2ZgSSFNwL3gTHjXeoXMHUsfSNkbRtX89i0TnsZVIYEcCog7jIUmRpAmvLrrLiIN8Je6dMO6skWbHtA2cOrKHgXzDKDEvMa7oDRNdlB3jW8tP9sjoirUJr8UffEHRhwuNvo2i\/DbmUcAQy7iTuEgR4c6wxq\/panmy9jOZO7LugmIYW74QdoYu6BrGrFN54ATqeGtdDdkgjq2bVdoYmxce1dKlky6qSVMjNxAMxwqVJ7ynFbUVbQ6VWHJsXWsXHIjqmKljImMp11FXdkGTbb+FtKXixfvhwi2+sWYkWgoXUgBRMZdJNVFXdiZSsrhNtmIb\/AGfhSHjMDfY+mTAH3g5ZJOgihpLQabauQe+VQKcDhQpIg\/CLk5j2oLCxmmO\/3UhksZtex2rWLt4bDuE7I6wGUYMpiUXUQRIGmkGjyCHGwel1i3YsG5cso91fS0HWODlZp4ywme8UAO2x166627RUMxOrzAgE8NeEVLb3FJLeYzp3euNbs8LvWWdxMdku2h5HKT4GvNwuuKm3wl7UEuCDOsV9UOvI16QGJ2pinL3w7HKLgyKfi9lA0eJjTnJ40xXIYHbTW\/RaKxnSzG8KuUOwOM6y7M69Xf0n\/pXfWK58TRUaWnhQ\/fEU6rkQ2VtQuTnmLai0rRwGRiNeIYt5MK7HG2wlTTd2M\/ulby5HCHU+kYpqL4kuUdgsx21EQulnW5CZjBlCRmhTxAHGOMVcb7zKVtiN7snZD4gWWNzKGtprl0kLwII17q5MPJ2kvxS\/cy8u8VbX2VctO46y2cs6zl3d8muuMrktBv8AJ\/iy4ulidyeAM3REzJMAE6D0hv4fK\/Sp6Uf1e6VTPm+wuk46ywX7ORwrHhDDJmnzkjumvq7EX0DOjXZt4g6amxPzSbzDyrzsZTc61K27N7ptSnlkxGr5VE8vaP2V3NXJUrMk2JIAJVgCJBIIkcxUOmjRVSltp5dRB8SfoIojTW8Uqr3FdrbnbGdOxxClpOh+UxG+OFbQUYu9jCpKUotXNmOnWCkmboBO7qwABJPOd2n7iHZCuyF7p5hNABdICkSLYEkkGScwMgCO\/XnSsh5gLbXS2xiWsW7NtgRcdmLLAghoUQZ007q3wqXPx8p2YCV8RBdZmMFtN7rBAqrJ4ZtOe94iudQT0SOPnJJas1uPvE4UZN630AG+ewwAI76zlG2KS\/A\/3IyUrq\/WLVdXAu293EDgfqrqjxREuDHF\/FJas3MVBEvhVulfSJUvDKCYnLEbtV361wYqP9TS61P3fgbUZaeQK2virBwqW7t17aOC2Yb+2VcAg7xIPZnzrTCf+4XCVP8AYzvVnh5v8UffEXR2yvwux1F+1AxIIB7PW22a1myKZ1XJESSYHKssc7Yap5svYzkirsv6HbatYa06XnVWN1zoYk+ieEEae2upq4k7D650yw0aXQTwgrp3xAH11OUecWY\/pja6o27QRdRr2CZmSS8TmJkkzxNVlFmBv5yAgDLZjxU7vyadhXuEL0juHcAd24z6+zQFyVzpJdG\/TxY++KVh3KG6UEf2e6JzDSPKnYWY7svpsLZcNkKMNQcpBJAHKIIXUd9DQKQyw3TXDAAZyI0AmdNIExrG7XlU5Ss4XtnaVu98HPaKubcNMEE277ZjpqBv1rysK\/6yovO9sRmV2Pt1XAl1tuODaAngQTpJHIjfXr2ITKtvu2mbKCzNqpmdFM8eEeukhtiYPy\/fymnYVw3Y909cOA6rE+vqL9cuM+y\/VD98Rp6l+zLCtYtKzZC998zAahcoAMcRmkeddDvuKVntGOJ6M4sW+stMuJt8khmHzrZ7Q8p8azVXirFujwdxLhHZUd2GUm6Ru5SpXnppp41smYtaD\/F9IHsvbNp2WcPYOhI3ovI1y4TvZ+fP9zB7dDl3ptfPpnMO8Kx9bKa6rIV2ab+SzaAuviiAQfvJOvFjeJ0A518p9KnZUbfj90unvPjttT1TNpEjzO71V9YyDcdH9pvh0uPaKK3VYBfvnonMtwmTwnnXHVf9TS8k\/dKWwzW1bpV8umiofWit9NdYmyjF7We4FDGcoCjQDTQcBruG\/lQK5VhVD3FDHsk6wQDl4xOk0BcffcfBbpxJ80P\/AI6RVuoi2xcHzxXkE+xQFuoimx8Hrrih4qv2RRcLdRdg9k4RbilWxOadJVInvgV0YV\/+tHynVgdMRDTeF2dnWcOCtvMc0SXImPk9nSAZ\/eKIRUVqeVKebYB39rxhC1rQDEqAdONp9dR+2uCcr4teY\/3I3hG0dQLo7eYkqsdlWaOYG\/2H2V1xlZkyjc0z3uswty0LSXSchCOzxKmd6MpnKTx5VnisPzmWak4uN9lt+3amRRlaVgPbTxhLGfCWZE9hmvgCGuCZ67NuHPie6OTDUpf1C5yXfU9bQv3svw29X8nqwX9NPzo+yYkfbK2WsOuDwwdIcHNiCFZWOWJvwdFU8eXMUVMLKpBwlVlZq2yGx\/oOO9twqv6W7WvxWP6RE+sGu0g7gsFcvsVtrLASfCQPeaQBjdGcSN9s\/v7KB2IDo3iv7JyO4TRcLETsLEDfaf1D66LoeVhOy+jVy85XMLZGozjfzjWJFFxZT3SHo62EVWNwOHJAgQdN50ZhxHHjQgaEyLOlMRJW5UAfTrOxrt3Z+FuWgWZUtnKAZ\/B3bfD51eHRqU6WLqSqSSvm2u29Gm1GJtdF8aD2sLiF8LTn3CvR6dhfGx7S+JGVh+09h4sJaQYfEORnJItOdSR3d1JY7C+Nj2l8RtPgSwPRHEOgZkuoZPZNm5OnGMtPp+F8bDtL4hlHGxuiV1LmbNdH3u+PwF0elauqPixvP1amubF43DunpUj30PvLw49Y0gTG7KxVqxbRMPeuutzNnFm4ZEOIIKzvYb+VdPTsLf7WPaXxCztoG4E3iO1gsUj8wlwL5jISfWPCoeMw3jYdqPxNFLigbamxMSbL5cNeM3p9Bie0CxMZZOsgnd7Kax2G8bHtL4kSQp23ZyvZS4MrLh8MGVuyfwagqZ3Hx76eClGcJyi7pznqtnfMiW0pxosGOqRl0M9omd0D0iP412CNx\/IwsNi\/m4f336+S+lfe0f1+6aU95gDgLTShZrbCJDCNfXofECvrCQpbOezibPWWsx+C5M11EDLbFwGGuMo0BGk8a4sQ8tenNptJSvZN7bW2Jj3WKNpbNuPcJzYfco\/rmG+KoXjd7q06XT4T\/t1PlFZnbPR5mWS1mQfi4vDHTx62jpdPhP8At1PlCwRs\/CXbJm1etITvK43DA+vraOlQ4T\/t1PlCwUcVjdP6d4\/7Qsf69PpUOE\/7dT5Qs\/8AWX272Nb\/ANc0d20bX+vS6XBbp\/26nyhl\/wBuWXExjIq\/DJhmJb4dbkyFABm8RAyyO9jS6XC97T\/t1PlK3WCtmWLyfhcVJYEKGxdpgVj5IuySeURoe6OrBYqnKtFWle\/gTXum+EhLn4NcRVt7CvkKJcsF29Iti8OIXfEG7x91ZSx1PYlP+3U+U4KVN2uxdtfAjD4NbZu2nZ7yXALd1H06t1J7LHQNpJia5qc+cxWZJpKNtYyjrmXhJHQ1ZBP8m6g4lidy2mk95KgeyfVXcyIrUdYq11V9lQwDqvgfq19VbU3dWMKqs7n0ToptCzdFv4QLKgW3LFgAA0pxO6TJjjNcVXA0nGpKV9XHZKSWyW5NI9XD1JSw8pR23js8kjF9ItmlrrdSLA3kL8EsPpO\/MUO\/xrlo4aGXWUu3P5jOsu60E17ZmNaMtqywUH0cFYMCSYE2twk1pKjSjtlLtz+YzjCUthzZN7EWi+e3ZVoj+q2E8tLQnWqWHpSV1KX9yfzEyjJaNBL7axHxRbnusWj\/ANlPolPjLtz+YjUhb29jf+nH\/wAe39CUdEp8ZdufzBqNtn9JsWvpWLNz\/DC+4VlPk+EvvT7cvmNo1bbi19tX2JJw9lQZ06tT70pxwcIrvpP9c\/mCUlJiLbF3FXIW3asKoMwcNZaTGphrZrRYWG9y7c\/mM31AeCt41C02bJVlZTlwuHB1H91umN8in0Wnxl25\/MLugFreMH\/BsT\/8LD\/6NLo1PjLtz+YaUnuPoFjEqbNsMkfe1Hoqm4a9lQFHHcIrSlShSVocb7W9X1ttj1BCiyMjMvcHAH5qgTWtxA17CJcMXUseLSx3\/iqvDjNF2tgyf8x84LJh7TqONu4T6wUgfnVi8RZ2uzbmd+hXs3ozcW7\/AFZlAS+u620ZrVxQOweMxHGufG1VzN29Lw2+fElwtuE+0ehOLa3bVbDELmgC2RGYzxrRcpYXx0e1H4mTixfh+jGJtyHwF5+M9Sx9ymq+scN46Hbj8ScskW47Y+JNhbaYPEgF5KdRc0K5gPicc7UvrDC3+2h24\/EbTsL7fR\/FccFio5CzcE+eQ0\/rDC+Oh2o\/EnK+AT9w7pEHZuMB07QW6SPI249dLp+E8dDtR+I8r4H0f+SnZotfCIsYu1mFmfhCRMdb6HYWYnXxFfL\/AElxNGqqXNzUrZtjTt3vBlwT4AO0Oj1u4plZaJGnHygmvsLhYx+1NgYhJudS3VAAZskjQAEkESBPE007icbCXFYYZj9HdpTuTY0HR7ZZuWyLcMRvEejM90HdvmpbsVGNw250Uu7ivnEn1aUZh5ABuj9udXbyH7aWYMqO4fYaL8YmfxP2ijMGVHsJsUsWUFgynXQkQdxnkapMVgm1sF1YEkmJ+mt8J9vHynXgdMRDygj9Fc+9MraSQx3RG7cPHurJUaq+6\/QzLo9RrvH6GQxnRqRbUlzlBA3HeSdIG7uk0+aq+C\/Qw6LV8F+hj\/oTstbDXVYE5gDqI3EjfPf76Tp1fBfoY1hqq+6\/Qy\/pph0CI9osLgYLukFDmPAbwQN\/Bj3VUYVd0X6GJ4SpLbB+hh\/RfYNsNba9eN6RnK5YAKxoZ1YaneBuGlKcJqhPMn30dvkkdlOnKnh5XTWsd1t0jQ7UtW2uM43kkzA9Y0rkppo5ajTsU7MxDWnBghflI3vED1bqKqurip22DnbVtVxAQuDmUEk3Mu88YIrOnG2iHN3imxBtbZNtW7QUCJBBdtP8wewV0J7jIRPsDTNZuZhroNB4GXq7k2RxcBdEBsKzRxF5frouLKWXbWUS2HYd8kkeqRGlK5VgP7oAE\/FPeY+qjMLKPuj2Kw91st2+bbcywI\/OnTzpPUew1eC2GC5QXC0iVPA+Yma5aqlKSijopyUY3E+JRUJXMdNOXvitaUm4k1UkwG4mugB9X01sYizF3BMPZJEn4yr\/ANtJsaRs+h+JPUnLZvquuqurge0Nu5A1yNO7sdErabBJi1w1xyBdJYk6MxUz3Awa1o5spNS1zmIwasMrDMPxiTW92Y3FydHsMoJGHQNwygCRx5RUuU7lLLYDxOCw6r28PEHSfPxqlJ8SWOei2x8FfJU4WdJ7JYiBz9H3VMnLiCZLanRvAMYsBF7iTPkGkkURlLiDYqbomnK35rPuIq8z4iHlrKu5Y\/fxpAWnFN8kn1D3TQAFjNk2MQCLuHgnQOoUMPBo94PhUSbWw0ir7Six0IFgdZhcTeRvk9hu+GEqGHcedYOvK9mjVUY7ga3tLaCMVu2bbAfGCOCe+VkeyuiMk0YzhJMuudSxk2DJ35lddd+krTsibskow3yLfk30GnYVyxDhQQ4KAgRObhyMHUeNAF3wiyfjrPl9VAJtFN3F2o0cH9\/Crzy4v0l85Pwn6xNjNpWhIa4g8TPvUU1OXF+kXOzW9+slgMZaLHI6TxiNw01ozy4v0hz0\/CfpYyG0rYP4S3I4HLRmnxfpFz0\/CfpY22fg3vCbag8dAPorKdR7HdmmsleUge8ioSGIUjfrEVMZJ7CZRttO4RQ7KEdWJMDtTr5U5OyuyVqxvgbQe4LZZBcEqJ1I5AEmamEU9UOTa0ZPpBi+rOS45aIHCNNdKu12TcTDGWzuYU7CuSJB5U7BclSAquXQN9ot+Sp+miwXYx2bslcSpHVWSImLiOCPCNx8DSyjuRwWyzbN1bDGycuuVpiJ9EXFbXxisKiWlzaDFjviNC13rOZZFB\/RP0VtFJGcnc8MSeMT3SPeDVEFiAkagkHgY+kAUpFR2mu2VYu27Ga1kRN5B1PInQEcOBrBOVm0bSyXszNY1AxJYAzxg\/SBV09hMwO3ZtposKOQMD1TFamRPrBzoA4MWo3miwrjjo7hQz5rK2c44lR56jXjU21HcF2rgEDENatq0\/EWPfQkFxW9gj0XIHI5dPCFrQksE8x6jUlHULfi+r9tAwiwx4x6v21nI0ihsl2xlk5Q35X2DWFma3Ab18Hcw8ga1gnvIm0A3EuGct0j8hT72rVGLArmGxWrLdBPI2k9+encVusGe7j1P4O2yzwUTHkx+mjQLMIt7QYxmt3UMa9gx5HLRYNQ\/DQSJf8Af2VnPYaQB9qYSHMZTpyH8adJ6BVWov8Ag7Zp7Pu9vGtTILsI3GD3QKTYI0mwMctsOryAykSDEd9YS0bN1qkI1W4DBIcc9x+o+yqpppaiqNN6F1i5B3Ea8N9W1oZJj3Y18dYDrqdTx47zP004oUmc26yuTCkkf2h3cdD2hxoYIzF+xfHo2bBHLX7Ip6BqDZ8Sv\/prZ+aQPpNF0KzI\/dS6vpYZvL+Ao0DUkOkCD07br45ftTRYLs1\/RG+jjOjxziOMwSBzoswGW2DbdhkysxkGAD66iolbUune+hmsRhwhyjQDy9lEXdBJWYM6Hx8\/2VRJRkPG2p8lPvNDKTNVsyzd6rRwEy+iBuHLdHqrnb22NtN5ncbaMwBp88j2AR7a0hsIntAVa4NMh8eyffrVkHGe9pC2zrrmUj3E60Da02leCxLt+Hw9tfm5jr4FKojU1HR1Gn+jhAYJ9FZjwOoEkCpGVbQBZj1irm49kb6EICFlBuA9VUBQDSGTVqBhWHfkYrKVjWNx1mcW4N0QQNCPp09dYtdRaauLL7d8+Z+utYomTBzBrQybOZBypiPEd59dAiDITuuMPAj6RQATsuwxcB7pZTwjX9HX+NZVL7jaFgbb7LbuEB0QSQM4PvzCnSbejFUSsmAJdJ1BtMOY\/ia2sY3LVJ5AeBpDDcDhi89swBPZP1kVnOVjSMbg9xDJ1J86qLuiZKzO2LM72IHdr9VNkjTZnR\/rG9Mpv1g6+399aauJ2BMbgSmi3MwE8CD7ooADKNzigCUPz99AHQz91AFiluU\/v4UDNJsnBLctsCEEjjkJ57jb+mmhC9NmpbF6FAYrAZQBzmdZ17orKau9TSL0EJsEH0lrTcZkCj\/KX2UwL8LaPMHypNjSNBs21dAJXOFiTlYjT1xXPKV9huopbQDaBBY6EeJmrp7CJgTLWpmQy0AcIoAYbOuXVkoTu1++BdO6TQADiJJlk15mCT50CKYHIjzI+mmB4NSGSDCgC+0QedQy1YZBBk3yCAfQHGeM91Zvaa3QI6+3uq0ZyIVZB6mIiTQBBnA4UAeGIAOkyKVh3I4t1uEllknfoPcKFGw3JsGt4dBuRB4LFMkuCjkP38qACsLfyBgBEjh\/EVEoplxlYHYT51SViW7hGFtihiRp9g2e1IMfVv8A35VSJYv2+jByDHkI3\/woYxGxikBBbk0AdD0AW2n140Aazo5cUqR2t07\/ABPjupoQsxrglonj7Kl7SkhS5piKmP7xQBPDgTuHqqZIqO00drH3FUrI0AHox7axzW0Nst9TP4lBmk1rDYZz2gj2hMy351WZkF8\/Mn66AOpaJO\/1T9dMDR9GkVHkyTHHX31N9QBtuENcJQsNdxP8aEAmayx+OfZ9VUB\/\/9k=)\n\"\"\"\n\"\"\"\nObject detection is a computer vision technique that allows us to identify and locate objects in an image or video. With this kind of identification and localization, object detection can be used to count objects in a scene and determine and track their precise locations, all while accurately labeling them.\n\"\"\"\n\"\"\"\n# Importing Packages\n\"\"\"\n\"\"\"\n![](https:\/\/media3.giphy.com\/media\/l0HlNOUe47hoQa3OE\/giphy.gif)\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\"\"\"\n# First Look at the image\n\"\"\"\n# Having a look at the image\nimage=cv2.imread('..\/input\/ducks-in-a-pond-pt-2\/maxresdefault.jpg')\nplt.imshow(image);\nplt.axis('off') ;\n\"\"\"\n# Converting Image From BGR to RGB (it's not a witchcraft lol)\n\"\"\"\n# Changing the image from BGR to RGB\nimage=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\nplt.imshow(image);\nplt.axis('off') ;\n# Reshaping the image to 2d \npixel_vals = image.reshape((image.shape[0]*image.shape[1],3))\npixel_vals = np.float32(pixel_vals)\n\"\"\"\n# Implementing the K Means clustering using cv2\n\"\"\"\n\"\"\"\ncriteria : It is the iteration termination criteria. When this criteria is satisfied, algorithm iteration stops. Actually, it should be a tuple of 3 parameters. They are `( type, max_iter, epsilon )`:\ntype of termination criteria. It has 3 flags as below:\n* cv.TERM_CRITERIA_EPS - stop the algorithm iteration if specified accuracy, epsilon, is reached.\n* cv.TERM_CRITERIA_MAX_ITER - stop the algorithm after the specified number of iterations, max_iter.\n* cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER - stop the iteration when any of the above condition is met.\n\"\"\"\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)\n\nk = 4\nretval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)\ncenters = np.uint8(centers)\nsegmented_data = centers[labels.flatten()]\n\nsegmented_image = segmented_data.reshape((image.shape))\nlabels_reshape = labels.reshape(image.shape[0], image.shape[1])\n\nplt.imshow(segmented_image);\n\"\"\"\n# Masking the image\n\"\"\"\n\"\"\"\n![](https:\/\/i.pinimg.com\/originals\/59\/cc\/ca\/59ccca31f3cda571dd3f64febd81c7ed.gif)\n\"\"\"\n\nBLUE = (0,0,255)\nRED = (255,0,0)\ncluster = 3\nmasked_image = np.copy(image)\nmasked_image[labels_reshape == cluster] = [BLUE]\ncv2.imwrite('images\/masked.jpg',masked_image)\n\nplt.imshow(masked_image);\n\"\"\"\n# Converting the image to HSV\n\"\"\"\n\nhsv_img = cv2.cvtColor(masked_image, cv2.COLOR_RGB2HSV)\nplt.imshow(hsv_img)\n\"\"\"\n# Find upper and lower color from BGR to HSV\n\"\"\"\nblue = np.uint8([[[255,0,0]]])\nhsv_blue = cv2.cvtColor(blue,cv2.COLOR_BGR2HSV)\nprint(hsv_blue)\n\"\"\"\n# Getting the maxed area of the cluster and representing it with a box around it :)\n\"\"\"\n\"\"\"\n![](https:\/\/i.pinimg.com\/originals\/e9\/d9\/d4\/e9d9d40eef4ab994670c08524e35bbdb.gif)\n\"\"\"\nlower_blue = (120,255,250)\nupper_blue = (120,255,255)\nCOLOR_MIN = np.array([lower_blue],np.uint8)\nCOLOR_MAX = np.array([upper_blue],np.uint8)\nframe_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX)\nimgray = frame_threshed\nret,thresh = cv2.threshold(frame_threshed,127,255,0)\ncontours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n# Find the index of the largest contour\nareas = [cv2.contourArea(c) for c in contours]\nmax_index = np.argmax(areas)\ncnt=contours[max_index]\n\nx,y,w,h = cv2.boundingRect(cnt)\n\npad_w = 3\npad_h = 4\npad_x = 3\npad_y = 4\n\ncv2.rectangle(image,(x-pad_x,y-pad_y),(x+w+pad_w,y+h+pad_h),(255,0,0),2)\n\nplt.imshow(image);\n\"\"\"\n# Finally we were able to detect the duck and form a box around it using K Means :)\n\"\"\"\n\"\"\"\n![](https:\/\/i.pinimg.com\/originals\/56\/a7\/b8\/56a7b8e4953907848148e15efa28ae81.gif)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'aa152a2cec525c'}"}
{"id":"124347","text":"\"\"\"\nDecision trees and neural nets have trouble classifying examples when trained on imbalanced data. This kernel will explore a wide range of resampling techniques, how they vary, and their effect on XGBoost.\n\n### Contents\n1. [Introduction](#introduction)\n2. [Table of techniques](#technique-table)\n    1. [Random Undersampling](#random-undersampling)\n    2. [Tomek Links](#tomek-links)\n    3. [AllKNN](#allknn)\n    4. [Edited Nearest Neighbor](#enn)\n    5. [Random Oversampling](#random-oversampling)\n    6. [ADASYN](#adasyn)\n    7. [SMOTE](#smote)\n    2. [SMOTETOMEK](#smotetomek)\n    2. [SMOTEENN](#smoteenn)\n3. [Training XGBoost](#training-xgboost)\n4. [Conclusion](#conclusion)\n\"\"\"\nimport time\nimport math\nimport logging \nimport random\n\nimport pandas as pd\nimport numpy as np\nimport scipy as sci\nfrom imblearn import under_sampling, over_sampling, combine\nfrom sklearn.decomposition import PCA\nimport plotly.offline as py\nimport plotly.graph_objs as go\npy.init_notebook_mode(connected=True)\n\nimport catboost as cb\nimport xgboost as xgb\nimport seaborn as sns\nfrom scipy.stats import spearmanr\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom hyperopt import hp, tpe, Trials, STATUS_OK\nfrom hyperopt import fmin\n\nfrom sklearn.metrics import precision_score, roc_auc_score, accuracy_score, confusion_matrix\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_validate, cross_val_score, StratifiedKFold\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom matplotlib import pyplot as plt\nplt.style.use('fivethirtyeight') \n%matplotlib inline\ndf = pd.read_csv('..\/input\/train.csv', low_memory=True)\ncount_yes = len(df[df.target == 1])\ncount_no = len(df[df.target== 0])\n\nplt.bar(['No', 'Yes'], [count_no, count_yes])\nplt.title('Santander Customer Transaction Prediction')\nplt.xlabel('Whether Successful Transaction')\nplt.ylabel('Count of Customers')\nplt.show()\n\"\"\"\n<a id='introduction'><\/a>\n# Target Class Imbalance\n---\nIn the Santander customer transaction prediction data we have a binary target variable where 1 is a successful future transaction and 0 is no future transaction. The problem is that we have an imbalance of about 7:1. If we train on this data we are likely to have a model that will missclassify the minority class, 'yes', because it has seen so few examples. \n\nTo deal with class imbalance we can resample. Resampling can mean that we oversample a minority class or undersample a majority class to introduce bias to select a more even distribution of classes. Class imbalance is something we will regularly see in tasks like network intrusion, rare disease diagnosing, and fraud detection. \n\"\"\"\ndescription = pd.DataFrame(index=['observations(rows)', 'percent missing', 'dtype', 'range'])\nnumerical = []\ncategorical = []\n# Construct a dataframe of Santander metadata\nfor col in df.columns:\n    obs = df[col].size\n    p_nan = round(df[col].isna().sum()\/obs, 2)\n    num_nan = f'{p_nan}% ({df[col].isna().sum()}\/{obs})'\n    dtype = 'categorical' if df[col].dtype == object else 'numerical'\n    numerical.append(col) if dtype == 'numerical' else categorical.append(col)\n    rng = f'{len(df[col].unique())} labels' if dtype == 'categorical' else f'{df[col].min()}-{df[col].max()}'\n    description[col] = [obs, num_nan, dtype, rng]\n\nfinal_results = pd.DataFrame(columns = ['parameters', 'training auc score',\n                                       'precision', 'training time', 'parameter tuning time'])\n\npd.set_option('display.max_columns', 150)\ndisplay(description)\ndisplay(df.head())\n\"\"\"\n<a id='technique-table'><\/a>\n# Resampling Techniques\n---\n### Undersampling Techniques \n1. Random Undersampling\n2. Tomek Links\n3. AllKNN\n4. ENN (Edited Nearest Neighbours)\n\n### Oversampling Techniques\n1. Random Oversampling\n2. ADASYN (Adaptive Synthetic Sampling)\n3. SMOTE (Synthetic Minority Over-Sampling Technique)\n\n### Combined Resampling\n1. SMOTETomek\n2. SMOTEENN\n\"\"\"\nsample = df.sample(n=100)\nsample = sample.drop(columns=['ID_code'])\nclass_1 = len(sample[sample.target == 1])\nclass_0 = len(sample[sample.target== 0])\n\nplt.bar(['Zero', 'One'], [class_0, class_1])\nplt.title('Size 100 Sample Distribution')\nplt.xlabel('Target Class Label')\nplt.ylabel('Count of Customers')\nplt.show()\nprint(f'Zero: {class_0} \\nOne: {class_1}')\n\"\"\"\n<a id='random-undersampling'><\/a>\n### Random Undersampling\nThe simplest form of undersampling is to remove random records from the majority class. With imblearn's implementation we can choose to remove samples with or without replacement. The biggest drawback to this form of undersampling is loss of information.\n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nrus = under_sampling.RandomUnderSampler(random_state=0)\nresamp_x, resamp_y= rus.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Undersampled Majority Class')\naxs[1].scatter(ono_x, ono_y, label='Original Class0')\naxs[1].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])\nplt.show()\n\"\"\"\n<a id='tomek-links'><\/a>\n### Tomek Links\nTomek links can be used as an under-sampling method or as a data cleaning method. A Tomek link is any place where two samples of different classes are nearest neighbors. When we find a Tomek link we can choose which observatin to delete- in undersampling we remove the majority class. \n\nThe difference between the data before and after Tomek links is subtle but clear- Tomek links is a great technique we can use to clear up our boundaries in classificatino problems. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\ntom = under_sampling.TomekLinks(random_state=0)\nresamp_x, resamp_y= tom.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Undersampled Majority Class')\naxs[1].scatter(ono_x, ono_y, label='Original Class0')\naxs[1].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])\nplt.show()\n\"\"\"\n<a id='allknn'><\/a>\n### AllKNN\nAllKNN is a method also created by the Ivan Tomek that deletes an object if a KNN classifier misclassifies it. In imblearn the default value of k is 3, but we can also pass a value. In the below cell its worth passing different values to `n_neighbors`. AllKNN tends to delete more datapoints than ENN, especially as the value of k increases. I think that it undersamples too haphazardly. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\naknn = under_sampling.AllKNN(random_state=0, n_neighbors=5)\nresamp_x, resamp_y= aknn.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Undersampled Majority Class')\naxs[1].scatter(ono_x, ono_y, label='Original Class0')\naxs[1].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])\nplt.show()\n\"\"\"\n<a id='enn'><\/a>\n### ENN (Edited Nearest Neighbours)\nENN removes examples whose class label differs from the class of at least half of its k nearest neighbors. The benefit of ENN is that we can remove examples of the majority class while retaining as much information as possible because we are only removing redundant observations. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nenn = under_sampling.EditedNearestNeighbours(random_state=0, n_neighbors=3)\nresamp_x, resamp_y= enn.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Undersampled Majority Class')\naxs[1].scatter(ono_x, ono_y, label='Original Class0')\naxs[1].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])\nplt.show()\n\"\"\"\n<a id='random-oversampling'><\/a>\n### Random Oversampling\nThe simplest implementation of oversampling is to duplicate random records from the minority class, this can cause overfitting. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nros = over_sampling.RandomOverSampler(random_state=0, ratio=0.5)\nresamp_x, resamp_y= ros.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Oversampled Minority Class')\naxs[1].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(ono_x, ono_y, label='Original Class0')\naxs[2].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])\nplt.show()\n\"\"\"\n<a id='adasyn'><\/a>\n### ADASYN (Adaptive Synthetic Sampling)\nADASYN adaptively generates samples next to original observations which are wrongly classified by a KNN classifier. Unlike SMOTE that generates new samples that lie inside the class boundary, ADASYN tends to generate new samples near existing outliers. \n\nYou can run these code cells with different data samples to see how  ADASYN tends to change the data distribution, but especially in contrast to SMOTE we can see how it tends to constuct points on the frontier of our existing data. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nada = over_sampling.ADASYN(random_state=0, ratio=0.5)\nresamp_x, resamp_y= ada.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Oversampled Minority Class')\naxs[1].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(ono_x, ono_y, label='Original Class0')\naxs[2].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])   \nplt.show()\n\"\"\"\n<a id='smote'><\/a>\n### SMOTE (Synthetic Minority Over-Sampling Technique)\nSMOTE synthesizes new examples by interpolating existing observations. SMOTE begins by iterating over every minority class instace and choosing its k nearest neighbors. The algorithm then constructs new instances halfway between the chosen obervations and its k neighbors. The greatest limitation of SMOTE is that it can only construct examples within the body of observations, never outside. If we compare the rebalanced data in the SMOTE plot against the plot for ADASYN we can see this exact effect. \n\nSMOTE has several variants like SVMSMOTE and BorderlineSMOTE.\n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nsmo = over_sampling.SMOTE(random_state=0, ratio=0.5)\nresamp_x, resamp_y= smo.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Oversampled Minority Class')\naxs[1].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(ono_x, ono_y, label='Original Class0')\naxs[2].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\nfig.delaxes(axs[3])   \nplt.show()\n\"\"\"\n<a id='smotetomek'><\/a>\n### SMOTETomek\nSMOTETomek is the combination of using Tomek links to undersample the majoirty class and the use of SMOTE to oversample the minority class. \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nsmotom = combine.SMOTETomek(random_state=0, ratio=0.5)\nresamp_x, resamp_y= smotom.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Oversampled Minority Class')\naxs[1].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[3].set_title('Undersampled Majority Class')\naxs[3].scatter(ono_x, ono_y, label='Original Class0')\naxs[3].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\naxs[3].legend()\n  \nplt.show()\n\"\"\"\n<a id='smoteenn'><\/a>\n### SMOTEENN\nSMOTEENN is the combination of SMOTE and Edited Nearest Neighbor. ENN removes any example whose class label differs from the class label of at least two of its three nearest neighbors. ENN tends to remove more examples then the Tomek links. \n\nThere's a really interesting difference here between SMOTETomek and SMOTEENN. There are so few minority class examples that Tomek Links are not nearly as effective at undersampling the majority class. If we we're using a built in method we could first perform SMOTE and then perform the Tomek Links step but \n\"\"\"\ny = sample.target\nx = sample.drop(columns=['target'])\nsmotenn = combine.SMOTEENN(random_state=0, ratio=0.5)\nresamp_x, resamp_y= smotenn.fit_resample(x, y)\n# Transform the resampled data into principal components\npca = PCA(n_components=2)\nresamp = pd.DataFrame(np.hstack((np.vstack(resamp_y), resamp_x)))\n\nresamp_0 = resamp[resamp[0] == 0.0]\nresamp_1 = resamp[resamp[0] == 1.0]\norig_0 = sample[sample.target == 0]\norig_1 = sample[sample.target == 1]\n\norig_no = pca.fit_transform(orig_0)\norig_yes = pca.fit_transform(orig_1)\nresamp_no = pca.fit_transform(resamp_0)\nresamp_yes = pca.fit_transform(resamp_1)\n\nono_x = orig_no[:, 0]\nono_y = orig_no[:, 1]\noyes_x = orig_yes[:, 0]\noyes_y = orig_yes[:, 1]\nrno_x = resamp_no[:, 0]\nrno_y = resamp_no[:, 1]\nryes_x = resamp_yes[:, 0]\nryes_y = resamp_yes[:, 1]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\naxs= axs.flatten()\naxs[0].set_title('Original Data')\naxs[0].scatter(ono_x, ono_y, label='Original Class0')\naxs[0].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].set_title('Oversampled Minority Class')\naxs[1].scatter(oyes_x, oyes_y, label='Original Class1')\naxs[1].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[3].set_title('Undersampled Majority Class')\naxs[3].scatter(ono_x, ono_y, label='Original Class0')\naxs[3].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].set_title('More Balanced Data')\naxs[2].scatter(rno_x, rno_y, label='Undersampled Class0')\naxs[2].scatter(ryes_x, ryes_y, label='Oversampled Class1')\naxs[0].legend()\naxs[1].legend()\naxs[2].legend()\naxs[3].legend()\n  \nplt.show()\n\"\"\"\n<a id='training-xgboost'><\/a>\n# XGBoost with Unbalanced Data\nNow that we know about strategies to deal with unbalanced data, here is the effect of unbalanced data on our gradient boosted random forests. \n\nWe will fit XGBoost models with Bayesian hyperparameter optimization to two datasets, first our unbalanced dataset- and second, a dataset that we have balanced with Smotetomek. The hyperparameter optimization library Hyperopt is great because it will do the optimization for us if we pass (1) a hyperparameter feature space, (2) an objective function that fits the model and returns a score to minimize, and (3) a `Trials` object that we can store arbitary data in from the model training. \n\"\"\"\n# Organizes XGB results and extracts metadata from Trials object\ndef org_results(trials, hyperparams, ratio, model_name):\n    fit_idx = -1\n    for idx, fit  in enumerate(trials):\n        hyp = fit['misc']['vals']\n        xgb_hyp = {key:[val] for key, val in hyperparams.items()}\n        if hyp == xgb_hyp:\n            fit_idx = idx\n            break\n            \n    train_time = str(trials[-1]['refresh_time'] - trials[0]['book_time'])\n    acc = round(trials[fit_idx]['result']['accuracy'], 3)\n    train_auc = round(trials[fit_idx]['result']['train auc'], 3)\n    test_auc = round(trials[fit_idx]['result']['test auc'], 3)\n    conf_matrix = trials[fit_idx]['result']['conf matrix']\n\n    results = {\n        'model': model_name,\n        'ratio': ratio,\n        'parameter search time': train_time,\n        'accuracy': acc,\n        'test auc score': test_auc,\n        'training auc score': train_auc,\n        'confusion matrix': conf_matrix,\n        'parameters': hyperparams\n    }\n    return results\n\ndef data_ratio(y):\n    unique, count = np.unique(y, return_counts=True)\n    ratio = round(count[0]\/count[1], 2)\n    return f'{ratio}:1 ({count[0]}\/{count[1]})'\nbatch_size = 10000\nxgb_df = df.sample(batch_size)\ny = xgb_df['target'].reset_index(drop=True)\nx = xgb_df.drop(columns=['target','ID_code'])\nsmotomek = combine.SMOTETomek(random_state=0, ratio=0.5)\nbal_x, bal_y= smotomek.fit_resample(x, y)\n\nsamp_len = len(bal_y)\nxgb_df2 = df.sample(samp_len - batch_size)\nxgb_df = pd.concat([xgb_df, xgb_df2])\nimb_y = xgb_df['target'].reset_index(drop=True)\nimb_x = xgb_df.drop(columns=['target','ID_code'])\ndef xgb_train(data_x, data_y, md_name):\n    ratio = data_ratio(data_y)\n    train_x, test_x, train_y, test_y = train_test_split(data_x, data_y, test_size=0.20)\n   \n    def xgb_objective(space, early_stopping_rounds=50):\n\n        model = XGBClassifier(\n            learning_rate = space['learning_rate'], \n            n_estimators = int(space['n_estimators']), \n            max_depth = int(space['max_depth']), \n            min_child_weight = space['m_child_weight'], \n            gamma = space['gamma'], \n            subsample = space['subsample'], \n            colsample_bytree = space['colsample_bytree'],\n            objective = 'binary:logistic'\n        )\n\n        model.fit(train_x, train_y, \n                  eval_set = [(train_x, train_y), (test_x, test_y)],\n                  eval_metric = 'auc',\n                  early_stopping_rounds = early_stopping_rounds,\n                  verbose = False)\n\n        predictions = model.predict(test_x)\n        test_preds = model.predict_proba(test_x)[:,1]\n        train_preds = model.predict_proba(train_x)[:,1]\n\n        xgb_booster = model.get_booster()\n        train_auc = roc_auc_score(train_y, train_preds)\n        test_auc = roc_auc_score(test_y, test_preds)\n        accuracy = accuracy_score(test_y, predictions) \n        conf_matrix = confusion_matrix(test_y, predictions)\n\n        return {'status': STATUS_OK, 'loss': 1-test_auc, 'accuracy': accuracy,\n                'test auc': test_auc, 'train auc': train_auc, 'conf matrix': conf_matrix\n               }\n\n    space = {\n        'n_estimators': hp.quniform('n_estimators', 50, 1000, 25),\n        'max_depth': hp.quniform('max_depth', 1, 12, 1),\n        'm_child_weight': hp.quniform('m_child_weight', 1, 6, 1),\n        'gamma': hp.quniform('gamma', 0.5, 1, 0.05),\n        'subsample': hp.quniform('subsample', 0.5, 1, 0.05),\n        'learning_rate': hp.loguniform('learning_rate', np.log(.001), np.log(.3)),\n        'colsample_bytree': hp.quniform('colsample_bytree', .5, 1, .1)\n    }\n\n    trials = Trials()\n    xgb_hyperparams = fmin(fn = xgb_objective, \n                     max_evals = 25, \n                     trials = trials,\n                     algo = tpe.suggest,\n                     space = space\n                     )\n    \n    results = org_results(trials.trials, xgb_hyperparams, ratio, md_name)\n    return results\n\nbal_results = xgb_train(bal_x, bal_y, 'Balanced Data')\nimb_results = xgb_train(imb_x, imb_y, 'Imbalanced Data')\nbal_confusion = bal_results.pop('confusion matrix')\nimb_confusion = imb_results.pop('confusion matrix')\nfig, ax = plt.subplots(1, 2, figsize=(10, 5))\nsns.heatmap(bal_confusion, annot=True, cmap= 'viridis_r', ax=ax[0])\nsns.heatmap(imb_confusion, annot=True, cmap= 'viridis_r', ax=ax[1])\nax[0].set_title('Balanced Dataset')\nax[1].set_title('Imbalanced Dataset')\nplt.show()\nfinal_results = pd.DataFrame([bal_results, imb_results])\ndisplay(final_results) \n\"\"\"\n<a id='conclusion'><\/a>\n# Imbalanced Dataset Conclusion\n---\nIn the confusion matrix we can see how much more often the imbalanced dataset correctly identifies class one observations as class one- the bottom right hand square. \n\nThe dropoff in accuracy between the two sets is a little over 5% depending on how the sample distribution shakes out, and the test auc scores tends to be about 10% different. This is the difference between a 2:1 target label imbalance and 9:1. \n\nImbalances in trees can have a significant effect on our classification power. While we focus on target label imbalance here, imbalances in the distributions of values and classes is an important topic in tree based models. If we go back and look at the charts of points that we use as examples we can see how tightly grouped points of two different classes can be- the job of XGBoost is to be able to disambiguate between these points and and that requires robust data. Imabalnce problems dont just have to be in the class of target label, we can face imbalances where there are two few examples of one category in a categorical variable, outliers in the distribution of a numerical variable, and imbalances between train and test sets. \n\nSomething you should try on your own is rerunning this kernel and seeing how a technique like ADASYN produces a different model than the SMOTE-based technique we used here. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e4abdb6f54d871'}"}
{"id":"18641","text":"\"\"\"\n# Importing libraries\ud83d\udcda\n\"\"\"\nimport torch\nimport torchvision\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.transforms import ToTensor\nfrom torchvision.utils import make_grid\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data import random_split\nimport pandas as pd\nimport seaborn as sns\nfrom colorama import Fore, Back, Style\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline\n\"\"\"\n# Getting data \ud83d\udcbd\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntest = pd.read_csv(\"..\/input\/titanic\/test.csv\")\nsubmission = pd.read_csv(\"..\/input\/titanic\/gender_submission.csv\")\ntrain.shape\ntest.shape\ntrain.head()\ntest.head()\ntrain.isnull().sum()\n\"\"\"\n# EDA \ud83d\udcca\n\"\"\"\nred = Fore.RED\ngrn = Fore.GREEN\nblu = Fore.BLUE\nylw = Fore.YELLOW\nwht = Fore.WHITE\ndef plot_distribution(feature,color):\n    plt.figure(dpi=125)\n    sns.distplot(train[feature],color=color);\n    print(\"{}Max value of {} is {}\\n{}Min value of {} is {}\\n{}Mean value of {} is {}\\n{}Std value of {} is {}\\n{}Median value of {} is {}\".format(red,feature,train[feature].max(),blu,feature,train[feature].min(),grn,feature,train[feature].mean(),ylw,feature,train[feature].std(),wht,feature,train[feature].median()));\nplot_distribution('Age','green')\n\"\"\"\nAs we know from the disaster.. women and children were the first to be evacuated.. mean age is 29.6, median age is 28.. both of which are >18 which suggests the people with missing ages are adults ... standard deviation is 14.5 which is <18 which suggests they are chilren..\n\"\"\"\nsns.set(style = 'darkgrid')\nplt.figure(dpi=125)\nsns.countplot(x=train.Sex, hue=train.Survived, data=train,edgecolor = sns.color_palette('dark',2));\n\"\"\"\nAs we can confirm females had a greater survival rate compared to males.\n\"\"\"\nplt.figure(dpi=125)\nsns.countplot(x = train.Sex, hue = train.Pclass,data = train,edgecolor = sns.color_palette('dark',3));\n\"\"\"\nThere were many people from both genders in 3rd class(as expected)... the second most filled class was 1st class ... this maybe suggests huge price difference between classes.. not sure though \ud83e\udd37\u200d\u2642\ufe0f\ud83e\udd37\u200d\u2642\ufe0f\n\"\"\"\nplt.figure(dpi=125)\nsns.countplot(x = train.Survived, hue = train.Pclass, data = train,edgecolor = sns.color_palette('dark',1));\n\"\"\"\nMost people survived were from 1st class.. so people in 1st class had a greater chance of survival\n\"\"\"\nplt.figure(dpi=125)\nsns.countplot(x = train.Pclass, hue = train.Survived, data = train,edgecolor = sns.color_palette('dark',5));\n\"\"\"\nOnly people from 1st class had a greater survival rate compared to classes 2 and 3... maybe there were fewer people in 1st class\n\"\"\"\ntrain.groupby('Pclass').Survived.value_counts()\n\"\"\"\nWell there weren't fewer people in 1st class.. so we can conclude that people in first class did indeed had a higher chance and rate of survival\n\"\"\"\nplt.figure(dpi=125)\nsns.countplot(x = train.Embarked, hue = train.Sex, data = train,edgecolor = sns.color_palette('dark',6));\nplt.figure(dpi=125)\nsns.countplot(x = train.Embarked, hue = train.Survived, data = train);\n\"\"\"\nMore people survived from Cherbourg compared to other two\n\"\"\"\n\"\"\"\n### Name\n\"\"\"\ntrain['Name'] = train.Name.str.extract('([A-Za-z]+)\\.',expand = False)\nplt.figure(dpi=200)\nplt.xticks(size=5)\nsns.countplot(x = train.Name, hue = train.Survived, data = train);\ntop6 = train['Name'].value_counts()[:6].index.to_list()\ntop6\ntrain['Name'] = train['Name'].apply(lambda x: x if x in top6 else 'Other')\ntrain.groupby('Name').Survived.value_counts()\n\"\"\"\n### Family\n\"\"\"\ntrain['family'] = train['SibSp'] + train['Parch'] + 1\nplt.figure(dpi=125)\nsns.countplot(x = train.family, hue = train.Survived, data = train);\ntrain.groupby('family').Survived.value_counts()\n\"\"\"\nThis seems kinda random .. only people with family member size of 2,3,4 survived greater than the rest \ud83e\udd14\ud83e\udd14.\n\"\"\"\nfor i in range(len(train)):\n    if(train['family'][i] > 1):\n        train['family'][i] = 1\n    else:\n        train['family'][i] = 0\nplt.figure(dpi=125)\nsns.countplot(x = train.family, hue = train.Survived, data = train);\n\"\"\"\npeople with family had greater rate of survival\n\"\"\"\n\"\"\"\n### Cabin\n\"\"\"\ntrain.groupby('Cabin').Survived.value_counts()\ntrain['Cabin'].fillna('S',inplace=True)\nfor i in range(len(train)):\n    train['Cabin'][i] = train['Cabin'][i][0]\ntrain.groupby('Cabin').Survived.value_counts()\nplt.figure(dpi = 125)\nsns.countplot(x = train.Cabin,hue = train.Survived, data = train);\n\"\"\"\npeople from cabins were more likely to survive\n\"\"\"\n\"\"\"\n### Fare\n\"\"\"\nplt.figure(dpi=125)\nplot_distribution('Fare','orange')\n\"\"\"\nThe minimum fare is 0.0 which means there was\/were someone\/some people with a free ride in titanic(probably in 1st class) \ud83d\ude05\ud83d\ude05\n\"\"\"\ntrain['fare_val'] = 0\nfor i in range(len(train)):\n    if(train['Fare'][i] > 32.0):\n        train['fare_val'][i] = 1\ntrain.groupby('fare_val').Survived.value_counts()\nplt.figure(dpi=125)\nsns.countplot(x = train.fare_val, hue = train.Survived, data = train);\n\"\"\"\nPeople with greater fare had a higher rate of survival\n\"\"\"\n\"\"\"\n#### Making same modifications to test dataset\n\"\"\"\n#family\ntest['family'] = test['SibSp'] + test['Parch'] + 1\nfor i in range(len(test)):\n    if(test['family'][i] > 1):\n        test['family'][i] = 1\n    else:\n        test['family'][i] = 0\n\n#Name\ntest['Name'] = test['Name'].apply(lambda x: x if x in top6 else 'Other')\n\n#Cabin\ntest['Cabin'].fillna('S',inplace=True)\n\nfor i in range(len(test)):\n    test['Cabin'][i] = test['Cabin'][i][0]\n\n\n#Fare\ntest['fare_val'] = 0\nfor i in range(len(test)):\n    if(test['Fare'][i] > 32.0):\n        test['fare_val'][i] = 1\n\"\"\"\n# Data Preprocessing \ud83d\uddc4\ufe0f\n\"\"\"\nfeatures = [##'PassengerId',\n            'Pclass',\n            #'Name',\n            'Sex',\n            'Age',\n            ##'SibSp',\n            ##'Parch',\n            'family',#derived from SibSp & Parch\n            #'Ticket',\n            ##'Fare',\n            'fare_val',#derived from Fare\n            #'Cabin',\n            'Embarked'\n           ]\n\ntarget = 'Survived'\ntrain[features].isnull().sum()\ntest[features].isnull().sum()\n'''Age_mean = train['Age'].mean()\ntrain['Age'] = train['Age'].fillna(value = Age_mean)\n\nAge_mean_t = test['Age'].mean()\ntest['Age'] = test['Age'].fillna(value = Age_mean_t)\nf\"'train',{Age_mean}, 'test',{Age_mean_t}\"''';\nAge_std = train['Age'].std()\ntrain['Age'] = train['Age'].fillna(value = Age_std)\n\nAge_std_t = test['Age'].std()\ntest['Age'] = test['Age'].fillna(value = Age_std_t)\nf\"'train',{Age_std}, 'test',{Age_std_t}\"\nfrom sklearn.preprocessing import LabelEncoder\n\nlbl = LabelEncoder()\n\ntrain['Sex'] = lbl.fit_transform(train[['Sex']].values.ravel())\ntest['Sex'] = lbl.fit_transform(test[['Sex']].values.ravel())\n#lbl2 = LabelEncoder()\n#train['Name'] = lbl2.fit_transform(train[['Name']].values.ravel())\n#test['Name'] = lbl2.fit_transform(test[['Name']].values.ravel())\ntrain['Embarked'] = train['Embarked'].fillna(value=train['Embarked'].mode()[0])\ntest['Embarked'] = test['Embarked'].fillna(value=test['Embarked'].mode()[0])\n\ntrain_ds = train[features]\ntest_ds = test[features]\ntrain_ds = pd.get_dummies(columns = ['Embarked','Pclass'],data=train_ds,drop_first = True)\ntest_ds = pd.get_dummies(columns = ['Embarked','Pclass'],data=test_ds,drop_first = True)\nprint(train_ds.head())\ntrain_ds.shape\nprint(test_ds.head())\ntest_ds.shape\n#train_ds.drop(columns = ['Cabin_T'],inplace = True)\n\"\"\"\n# Creating a XGBoost Model with Randomized Search \u2764\ufe0f\u200d\ud83d\udd25\n\"\"\"\ny_train = train[target]\nfrom sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(train_ds, y_train, test_size=0.30)\nX_train.columns\nfrom sklearn.model_selection import train_test_split,cross_val_score,RandomizedSearchCV,GridSearchCV\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\n'''rfc = RandomForestClassifier()\n\nparams = {'n_estimators': [200,500,800,1000,1200],\n          'max_depth': [3,5,7],\n          'criterion':['entropy', 'gini'],\n          'min_samples_leaf' : [1, 2, 3, 4, 5],\n          'max_features':['auto'],\n          'min_samples_split': [3, 5, 10],\n          'max_leaf_nodes':[2,3,5,7],\n          }\n\nrfc_cv = RandomizedSearchCV(rfc, params, cv = 250, n_jobs=-1, verbose=2).fit(X_train, y_train)''';\nrfc = XGBClassifier()\n\nparams = {'n_estimators': [200,500,800,1000,1200],\n          'max_depth': [3,5,7],\n          'objective' : ['binary:logistic'],\n          'min_samples_leaf' : [1, 2, 3, 4, 5],\n          'max_leaf_nodes':[2,3,5,7],\n          'min_child_weight': [1, 5, 10],\n          'gamma': [0.5, 1, 1.5, 2, 5],\n          }\n\nrfc_cv = RandomizedSearchCV(rfc, params, cv = 10, n_jobs=-1, verbose=2).fit(X_train, y_train)\nrfc_cv.best_params_\nbest_model = rfc_cv.best_estimator_\n\nprint(best_model)\nprint(rfc_cv.best_score_)\nrfc_pred = best_model.predict(X_valid)\n\nprint(\"Accuracy: \", accuracy_score(y_valid, rfc_pred))\n\nprint(\"\\nConfusion Matrix\\n\")\nprint(confusion_matrix(y_valid, rfc_pred))\n\"\"\"\n## Saving the Model \ud83d\udcbe\n\"\"\"\nimport pickle\n\nfilename = 'Titanic_model.sav'\npickle.dump(best_model, open(filename, 'wb'))\n\"\"\"\n## Loading the Model \ud83d\udd03\n\"\"\"\nloaded_model = pickle.load(open(filename, 'rb'))\nresult = loaded_model.score(X_valid, y_valid)\nprint(result)\nprint(rfc_pred)\npassId = test[['PassengerId']].values\ntest_ds.head()\nfinal_pred = best_model.predict(test_ds)\n\"\"\"\n# My Submission \ud83d\ude4b\u200d\u2642\ufe0f\n\"\"\"\nsub = {'PassengerId':passId.ravel(), 'Survived':final_pred}\nsubmission_csv = pd.DataFrame(sub)\nsubmission_csv.head()\nsubmission_csv.to_csv('final_sub_titanic_xgb_cv_10.csv',index = False)\nx = pd.read_csv(\".\/final_sub_titanic_xgb_cv_10.csv\")\nx.head()\n\"\"\"\n## Checkout my other [**Notebook**](https:\/\/www.kaggle.com\/mdhamani\/titanic-getting-better-eda-pytorch-gpu-top-14) with PyTorch Neural Network Classifier\n\"\"\"\n\"\"\"\n# To-Do\ud83d\udccb\n## Tuning parameters \ud83e\udd37\u200d\u2642\ufe0f\ud83e\udd37\u200d\u2642\ufe0f\n## Make the PyTorch Model more accurate\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '220b9fb513aeb3'}"}
{"id":"88181","text":"\"\"\"\nI am running it for one epoch only. Just due to time constraint.\n\"\"\"\nimport numpy as np  # Data manipulation\nimport pandas as pd # Dataframe manipulation \nimport matplotlib.pyplot as plt # Plotting the data and the results\nimport matplotlib.image as mpimg # For displaying imagees\n%matplotlib inline\nfrom keras import models\nfrom keras import layers\nimport keras.preprocessing  as kp\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import regularizers\nfrom keras import optimizers\ntrain_datagen = ImageDataGenerator( # Data Augumentation for test data\nrescale=1.\/255,\nrotation_range=30,\nshear_range=0.3,\nzoom_range=0.3\n)\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\ntrain_gen=train_datagen.flow_from_directory('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Train',\n                                            target_size=(250,250),\n                                            batch_size=48,\n                                            class_mode='binary')\nvalid_gen=test_datagen.flow_from_directory('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Validation',\n                                           target_size=(250,250),\n                                           batch_size=48,\n                                           class_mode='binary')\nfrom keras.applications import MobileNet\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras.layers import Dense, GlobalAveragePooling2D\n\n\nbase_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.\n\nx=base_model.output\nx=GlobalAveragePooling2D()(x)\nx=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.\nx=Dense(1024,activation='relu')(x) #dense layer 2\nx=Dense(512,activation='relu')(x) #dense layer 3\npreds=Dense(1,activation='softmax')(x)\n\n\n\n# train the model on the new data for a few epochs\n\nmodel=Model(inputs=base_model.input,outputs=preds)\nfor i,layer in enumerate(model.layers):\n  print(i,layer.name)\nfor layer in model.layers:\n    layer.trainable=False\n# or if we want to set the first 20 layers of the network to be non-trainable\nfor layer in model.layers[:20]:\n    layer.trainable=False\nfor layer in model.layers[20:]:\n    layer.trainable=True\n# compile the model (should be done *after* setting layers to non-trainable)\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy',metrics=['acc'])\nstep_size_train=train_gen.n\/\/train_gen.batch_size\nhistory=model.fit_generator(generator=train_gen,\n                   steps_per_epoch=step_size_train,\n                   epochs=1,validation_data=valid_gen,validation_steps=50)\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'ro', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'ro', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.figure()\ntest_datagen1 = ImageDataGenerator(rescale=1.\/255)\ntest_generator = test_datagen1.flow_from_directory(\n'..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Test',\ntarget_size=(150,150),\nbatch_size=64,\nclass_mode='binary')\nfig,ax=plt.subplots(ncols=2,nrows=4,figsize=(20,20))\nimg1 = mpimg.imread('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Test\/Female\/160003.jpg')\nax[0][0].imshow(img1)\nax[0][0].set_title(\"Dataset we trained and tested on.\")\nimg2 = mpimg.imread('..\/input\/gender-classification-dataset\/Training\/female\/131422.jpg.jpg')\nax[0][1].imshow(img2)\nax[0][1].set_title(\"The completely new dataset.\")\nimg3 =  mpimg.imread('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Validation\/Female\/180019.jpg')\nax[1][0].imshow(img3)\nimg4= mpimg.imread('..\/input\/gender-classification-dataset\/Validation\/female\/113010.jpg.jpg')\nax[1][1].imshow(img4)\nimg5 = mpimg.imread('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Validation\/Male\/180028.jpg')\nax[2][0].imshow(img5)\nimg6 = mpimg.imread('..\/input\/gender-classification-dataset\/Validation\/male\/063517.jpg.jpg')\nax[2][1].imshow(img6)\nax[3][0].imshow(mpimg.imread('..\/input\/gender-recognition-200k-images-celeba\/Dataset\/Validation\/Male\/180073.jpg'))\nax[3][1].imshow(mpimg.imread('..\/input\/gender-classification-dataset\/Validation\/male\/063531.jpg.jpg'))\nplt.tight_layout()\ntest_datagen2 = ImageDataGenerator(rescale=1.\/255)\ntest_generator = test_datagen2.flow_from_directory(\n'..\/input\/gender-classification-dataset\/Training',\ntarget_size=(150,150),\nbatch_size=64,\nclass_mode='binary')\ntest_datagen3 = ImageDataGenerator(rescale=1.\/255)\ntest_generator = test_datagen1.flow_from_directory(\n'..\/input\/gender-classification-dataset\/Validation',\ntarget_size=(150,150),\nbatch_size=64,\nclass_mode='binary')","meta":"{'source': 'AI4Code', 'id': 'a1c51769bd886e'}"}
{"id":"53545","text":"# 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\nimport matplotlib.pyplot as plt\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\nfrom tensorflow.keras.datasets import cifar10\n(X_train,y_train),(X_test,y_test)=cifar10.load_data()\nX_train.shape\nX_train[0].shape\nplt.imshow(X_train[0])\nplt.imshow(X_train[12])\nX_train[0].max()\nX_train=X_train\/255\nX_test=X_test\/255\nX_test.shape\ny_test\nfrom tensorflow.keras.utils import to_categorical\ny_cat_train=to_categorical(y_train,10)\ny_cat_test=to_categorical(y_test,10)\ny_train[0]\nplt.imshow(X_train[0])\n\"\"\"\n <br><br>This is the final output sheet representing values corresponding to respective images\n \n <font face = \"Verdana\" size =\"1\">\n    <img src='https:\/\/corochann.com\/wp-content\/uploads\/2017\/04\/cifar10_plot.png'>\n\n    \n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Conv2D,MaxPool2D,Flatten\n28*28\n32*32*3\nmodel=Sequential()\n\n#1st layer\n#Convolutional Layer\nmodel.add(Conv2D(filters=32,kernel_size=(4,4),input_shape=(32,32,3),activation=\"relu\"))\n\n#Pooling Layer\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\n#2nd Layer\n#Convolutional Layer\nmodel.add(Conv2D(filters=32,kernel_size=(4,4),input_shape=(32,32,3),activation=\"relu\"))\n\n#Pooling Layer\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(256,activation=\"relu\"))\n\nmodel.add(Dense(10,activation=\"softmax\"))\n\nmodel.compile(loss=\"categorical_crossentropy\",optimizer=\"adam\",metrics=[\"accuracy\"])\nmodel.summary()\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stop=EarlyStopping(monitor=\"val_loss\",patience=2)\nmodel.fit(X_train,y_cat_train,epochs=15,validation_data=(X_test,y_cat_test),callbacks=[early_stop])\nmetrics=pd.DataFrame(model.history.history)\nmetrics.columns\nmetrics[[\"accuracy\",\"val_accuracy\"]].plot()\nmetrics[[\"loss\",\"val_loss\"]].plot()\nmodel.evaluate(X_test,y_cat_test,verbose=0)\nfrom sklearn.metrics import classification_report,confusion_matrix\npredictions=model.predict_classes(X_test)\nprint(classification_report(y_test,predictions))\n import seaborn as sns\n    \nplt.figure(figsize=(20,20))\nsns.heatmap(confusion_matrix(y_test,predictions),annot=True)\nmy_image=X_test[0]\nplt.imshow(my_image)\ny_test[0]\nmodel.predict_classes(my_image.reshape(1,32,32,3))\n#As we can see its working well,so we are done here for now!","meta":"{'source': 'AI4Code', 'id': '628f0408a94737'}"}
{"id":"135129","text":"\"\"\"\nAuditeur : Didier GORGES\n\nkaggle notebook : https:\/\/www.kaggle.com\/dgcnam\/sec201-lab-session-predicting-attacks\/edit\/run\/61813075\n\n# Loading data\n\n## 1. Open a new Jupyter notebook and name it \u2018SEC201 - Lab session - predicting attacks\u2019\n\nDone\n\n## 2. In File > Add or Include Data, search for \u201cUNSW_NB15\u201d dataset and include it\n\nDone\n\n## 3. In \u2018Data > input > unsw-nb15\u2018, get the exact path of CSV file 'UNSW_NB15_training-set.csv' and load it as training_set using Pandas.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\ndf = pd.read_csv('\/kaggle\/input\/unsw-nb15\/UNSW_NB15_training-set.csv')\n\"\"\"\n## 4. List following information for the training set\n\n\n### 4.1. Column number\n\"\"\"\nprint(f'Column number: { df.columns.size }')\n\"\"\"\n### 4.2. Column names\n\"\"\"\nprint('Column names')\nprint(df.columns)\n\"\"\"\n### 4.3. Column types\n\"\"\"\nprint('Column types')\nprint(df.dtypes)\n\"\"\"\n### 4.4. Size of the data set\n\"\"\"\nprint(f'Size of the dataset : { len(df) }')\n\"\"\"\n## 5. Look at the file head using: df.head()\n\"\"\"\ndf.head()\n\"\"\"\n## 6. Which columns are categories? List them; extract existing values.\n\"\"\"\nprint(df.dtypes[df.dtypes == 'object'].index)\n\nfor category in df.dtypes[ df.dtypes == 'object' ].index:\n    print(category)\n    print(list(set(df[category])))\n\"\"\"\n## 7. Which columns are numeric? List them; extract min, max, mean, median and standard deviation values for \u2018rate\u2019.\n\"\"\"\nprint('Numeric columns :')\nnewdf = df._get_numeric_data()\nprint(newdf.columns)\nprint(\"Extract min, max, mean, median and standard deviation values for 'rate'\")\nfor f in [ 'min', 'max', 'mean', 'median', 'std']:\n    print(f'{ f } = { getattr(df.rate, f)() }')\nprint('Extract min, max, mean, median and standard deviation values for all numeric colums')\nfunction_list = [ 'min', 'max', 'mean', 'median', 'std']\nstats = pd.DataFrame(columns=[ 'name' ] + function_list)\nfor c in newdf:\n    line = { 'name': c }\n    for f in function_list:\n        line[f] = newdf[c].aggregate(f)\n    stats = stats.append(line, ignore_index = True)\nstats\n\"\"\"\n## 8. Based on this information\n### 8.1. Define the goal of the analysis.\n\nThe goal of the analysis is to check if the data are correctly labelled to reveal an attack.\n\n\"\"\"\n\"\"\"\n### 8.2. Identify the target properties you will want to analyse\nI will want to analyse the 'label' and 'attack_cat' properties versus the others properties.\n\"\"\"\n\"\"\"\n## 9. Check whether the positive label (1) match attack categories and whether attack categories match labelled data.\n\nThe following code shows that the positive label matchs the Normal attack category, and that the negative label matchs all the other attack categories.\n\"\"\"\nlabel_normal = df.loc[df.attack_cat == 'Normal'].label.unique()\nprint(f'There is { len(label_normal) } label where attack_cat == Normal, label = { label_normal }')\n\nlabel_attack = df.loc[df.attack_cat != 'Normal'].label.unique()\nprint(f'There is { len(label_attack) } label where attack_cat != Normal, label = { label_attack }')\n\n\"\"\"\n## 10. Which is the number of occurrences for each attack category?\n\"\"\"\nprint('Number of occurrences for each attack category :')\ndf.groupby(\"attack_cat\").count()[\"id\"]\n\"\"\"\n## 11. Which protocols and services appear in the positively labelled entries? In the negatively labelled ones?\n\"\"\"\nprint('protocols appearing in negatively labelled entries :')\nprint(df.loc[df.label == 0].groupby('proto').count()['id'].sort_values(ascending=False).index.tolist())\nprint('protocols appearing in positively labelled entries:')\nprint(df.loc[df.label == 1].groupby('proto').count()['id'].sort_values(ascending=False).index.tolist())\nprint('services appearing in negatively labelled entries :')\nprint(df.loc[df.label == 0].groupby('service').count()['id'].sort_values(ascending=False).index.tolist())\nprint('services appearing in positively labelled entries:')\nprint(df.loc[df.label == 1].groupby('service').count()['id'].sort_values(ascending=False).index.tolist())\n\"\"\"\n## 12. What do you conclude about the traffic being analysed?\n\nIn this data set, the 'label' and 'attack_cat' properties are coherents. If 'label' is 1, the 'attack_cat' is not 'Normal'. If 'label' is 0, the attack_cat is 'Normal'.\n\nThere are big differences between mean and median on some properties ('rate', 'sload', 'dload', 'sjiy', ...) which means we expect to see some outliers due to attacks.\n\nAttackers' traffic uses more various protocols and services than the legitimate one. Protocols and services that do not appear in legitimate traffic are suspicious.\n\"\"\"\n\"\"\"\n# Data visualisation\n\n## 13. Visualise the repartition of services, protocols, attack types, as histograms Use pyplot and seaborn libraries.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfig = plt.gcf()\nfig.set_size_inches(8, 5)\ncplot = sns.countplot(y='service', data=df)\ncplot.set_title('Repartition of services')\nplt.show()\nplt.figure(figsize=(30, 15))\nbarplot = sns.countplot(y='proto', data=df)\nbarplot.set_title('Repartition of protocols')\nplt.show()\ntable = df[['proto', 'id']].pivot_table(index=['proto'], aggfunc='count').sort_values(['id'],ascending=False,inplace=False).head(10)\ntable.plot(kind='bar', title='Repartition of top 10 protocols', legend=False)\ndf.groupby('proto').count().describe()\nbarplot = sns.countplot(y='attack_cat', data=df)\nbarplot.set_title('Repartition of attack types')\nplt.figure(figsize=(30,15))\nheatmap = sns.heatmap(df.corr(), vmin=-1, vmax=1, annot=True, cmap='BrBG')\nheatmap.set_title('Correlation heatmap', fontdict={'fontsize': 12}, pad=10)\nplt.show()\n\"\"\"\n## 14. Build the correlation matrix between parameters for labelled and unlabelled entries.\n\"\"\"\nprint('Correlation matrix for labelled entries')\nplt.figure(figsize=(30,15))\nheatmap = sns.heatmap(df[df.label == 1].corr(), vmin=-1, vmax=1, annot=True, cmap='BrBG')\nheatmap.set_title('Correlation heatmap', fontdict={'fontsize': 12}, pad=10)\nplt.show()\nprint('Correlation matrix for unlabelled entries')\nplt.figure(figsize=(30,15))\nheatmap = sns.heatmap(df[df.label == 0].corr(), vmin=-1, vmax=1, annot=True, cmap='BrBG')\nheatmap.set_title('Correlation heatmap', fontdict={'fontsize': 12}, pad=10)\nplt.show()\nprint('Correlation matrix for labelled - unlabelled entries')\nplt.figure(figsize=(30,15))\nheatmap = sns.heatmap(df[df.label == 1].corr() - df[df.label == 0].corr(), vmin=-1, vmax=1, annot=True, cmap='BrBG')\nheatmap.set_title('Correlation heatmap', fontdict={'fontsize': 12}, pad=10)\nplt.show()\nprint('Top 20 differences between matrix of labelled correlation - matric of unlabelled correlation')\nx = (df[df.label == 1].corr() - df[df.label == 0].corr()).stack().sort_values()\nt = pd.DataFrame(columns=['a', 'b', 'diff', 'abs'])\nfor a, b in x.index:\n    if (a != b):\n        t = t.append({ 'a': a, 'b': b, 'diff': x[(a, b)], 'abs': abs(x[(a,b)]) }, ignore_index=True)\nprint(t.sort_values('abs', ascending=False)[['a', 'b', 'diff']].head(20))\n\nprint('correlation of sttl and dttl, for labelled entries')\nprint(df.loc[df.label == 1][['sttl', 'dttl']].corr())\nprint('correlation of sttl and dttl, for unlabelled entries')\nprint(df.loc[df.label == 0][['sttl', 'dttl']].corr())\nprint('min, max, mean, median and standard deviation values for rate, sttl and dttl for unlabelled entries')\nfunction_list = [ 'min', 'max', 'mean', 'median', 'std']\nstats = pd.DataFrame(columns=[ 'name' ] + function_list)\nfor c in 'rate', 'sttl','dttl':\n    line = { 'name': c }\n    for f in function_list:\n        line[f] = df.loc[df.label == 0][c].aggregate(f)\n    stats = stats.append(line, ignore_index = True)\nstats\nprint('min, max, mean, median and standard deviation values for sttl and dttl for labelled entries')\nstats = pd.DataFrame(columns=[ 'name' ] + function_list)\nfor c in 'rate', 'sttl','dttl':\n    line = { 'name': c }\n    for f in function_list:\n        line[f] = df.loc[df.label == 1][c].aggregate(f)\n    stats = stats.append(line, ignore_index = True)\nstats\n\ndf.loc[df.label == 0][['sttl','dttl']].plot.hist(bins=256, alpha=0.5, title='unlabelled entries')\n\ndf.loc[df.label == 1][['sttl','dttl']].plot.hist(bins=256, alpha=0.5, title='labelled entries')\n\"\"\"\n## 15. Based on the Exploratory Data Analysis\n### 15.1. Describe what you learnt from the dataset\n\nI learnt that the label field is a flag that indicates if the entry is considered as an attack.\n\nThe kind of attack is written in the attack_cat field. The label values of the entries are coherents with their attack_cat values.\n\nThe protocols and services use in an attack are more various than for a legitimate traffic.\n\nCorrelation matrix show that, for labelled entries, sttl and dttl fields does not have the same distributions as for unlabelled entries. There is correlation differences for some other fields too.\n\nrate median is 118 for unlabelled entries and 100000 for labelled entries.\n\ndttl median is 29 for unlabelled entries and 0 for labelled entries.\n\nsttl median is 62 for unlabelled entries en 254 for labelled entries.\n\n### 15.2. Draw the first conclusions\n\nThe entries contain normal and attack traffic, and seem correctly classified without identified bias. When aggregated according the label field, data have a different metrics profile.\n\n### 15.3. Emit recommendations for enforcing the cybersecurity of the target system\n\nWe can use this data set to train machine learning classifiers, like XGBoost, in order to estimate a probability of attack on new entries.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f869f920ad03bd'}"}
{"id":"33479","text":"\"\"\"\n# Introduction\nThe U.S. has almost 500 students for every guidance counselor. Underserved youth lack the network to find their career role models, making CareerVillage.org the only option for millions of young people in America and around the globe with nowhere else to turn.\n\nOur goal is to develop a method to recommend relevant questions to the professionals who are most likely to answer them.\n\nOutline of kernel is as follows:\n\n* Exploring questions and answers (1)\n* Exploring questions and answers (2) and mind-blowing observation\n* Exploring students\n* Exploring professionals (added filtering active professionals)\n* Exploring professionals and answers\n* Exploring tags\n* Exploring questions bigram\n* Building tag_chart\n* Content Based Recommender (added get similar professionals)\n* t-SNE visualization\n\nPlease remember to upvote if you find the work useful! Thank you for visiting.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport warnings\nwarnings.simplefilter('ignore')\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel, cosine_similarity\n\nimport re\nimport string \nfrom collections import Counter\nfrom nltk.corpus import stopwords\nstop = stopwords.words('english')\n\nfrom plotly.offline import init_notebook_mode, iplot\nimport plotly.graph_objs as go\nimport plotly.plotly as py\nfrom plotly import tools\ninit_notebook_mode(connected=True)\n\"\"\"\nReading in all the csvs.\n\"\"\"\nemails = pd.read_csv('..\/input\/emails.csv')\nquestions = pd.read_csv('..\/input\/questions.csv')\nprofessionals = pd.read_csv('..\/input\/professionals.csv')\ncomments = pd.read_csv('..\/input\/comments.csv')\ntag_users = pd.read_csv('..\/input\/tag_users.csv')\ngroup_memberships = pd.read_csv('..\/input\/group_memberships.csv')\ntags = pd.read_csv('..\/input\/tags.csv')\nstudents = pd.read_csv('..\/input\/students.csv')\ngroups = pd.read_csv('..\/input\/groups.csv')\ntag_questions = pd.read_csv('..\/input\/tag_questions.csv')\nmatches = pd.read_csv('..\/input\/matches.csv')\nanswers = pd.read_csv('..\/input\/answers.csv')\nschool_memberships = pd.read_csv('..\/input\/school_memberships.csv')\n\"\"\"\nCreate a function for merging tables more easily.\n\"\"\"\ndef merging(df1, df2, left, right):\n    return df1.merge(df2, how=\"inner\", left_on=left, right_on=right)\n\"\"\"\nMerging questions with answers.\n\"\"\"\nqa = merging(questions, answers, \"questions_id\", \"answers_question_id\")\nqa.head(3).T\n\"\"\"\n# Exploring questions_answers (1)\nCan we find out how long does it take for a question to be answered?\n\"\"\"\nqa['questions_date_added'] = pd.to_datetime(qa['questions_date_added'])\nqa['answers_date_added'] = pd.to_datetime(qa['answers_date_added'])\nqa['qa_duration'] = (qa['answers_date_added'] - qa['questions_date_added']).dt.days\n\nqa.head().T\n# after groupby, head(1) returns the first occurrence\nfirst_qa = qa.groupby('questions_id').head(1)\n\n# let's explore data from last year\nfirst_qa = first_qa[first_qa['questions_date_added'] >= pd.datetime(2018, 1, 1)]\n\nfirst_qa.loc[(first_qa['qa_duration'] <= 7), 'week'] = 1\nfirst_qa.loc[(first_qa['qa_duration'] > 7) & (first_qa['qa_duration'] <= 14), 'week'] = 2\nfirst_qa.loc[(first_qa['qa_duration'] > 14) & (first_qa['qa_duration'] <= 21), 'week'] = 3\nfirst_qa.loc[(first_qa['qa_duration'] > 21) & (first_qa['qa_duration'] <= 28), 'week'] = 4\nfirst_qa.loc[(first_qa['qa_duration'] > 28), 'week'] = 5\nweek_val_cnt = first_qa['week'].value_counts().sort_index()\n\nplt.figure(figsize=(8,6))\nsns.barplot(week_val_cnt.index, \n            week_val_cnt.values)\n\nplt.xlabel('Week')\nplt.ylabel('Responses')\nplt.title('Responses vs Week')\nplt.show()\n\"\"\"\n3,252 questions have responses within the first week while 3,140 took more than a month.\n\"\"\"\n\"\"\"\n# Exploring questions and answers (2) and mind-blowing observation\n\"\"\"\n\"\"\"\nWe continue exploring the question body to understand why some questions have longer response time.\n\"\"\"\ndef process_text(df, col):\n    df[col] = df[col].str.replace('[^\\w\\s]','') # replacing punctuations\n    df[col] = df[col].str.replace('-',' ') # replacing dashes\n    df[col] = df[col].str.replace('\\d+','') # replacing digits\n    df[col] = df[col].str.lower().str.split() # convert all str to lowercase    \n    df[col] = df[col].apply(lambda x: [item for item in x if item not in stop]) # remove stopwords    \n    df[col] = df[col].apply(' '.join) # convert list to str\n    return df\nfirst_qa['questions_body'] = process_text(first_qa, 'questions_body')['questions_body']\n\nfast_resp = pd.Series(first_qa[first_qa['week'] == 1]['questions_body'].tolist()).astype(str)\nslow_resp = pd.Series(first_qa[first_qa['week'] == 5]['questions_body'].tolist()).astype(str)\n\ndist_fast = fast_resp.apply(lambda x: len(x.split(' ')))\ndist_slow = slow_resp.apply(lambda x: len(x.split(' ')))\npal = sns.color_palette()\n\nplt.figure(figsize=(18, 8))\nplt.hist(dist_fast, bins=40, range=[0, 80], color=pal[9], normed=True, label='fast')\nplt.hist(dist_slow, bins=40, range=[0, 80], color=pal[1], normed=True, alpha=0.5, label='slow')\nplt.title('Normalised histogram of word count in question_body', fontsize=15)\nplt.legend()\nplt.xlabel('Number of words', fontsize=15)\nplt.ylabel('Probability', fontsize=15)\n\"\"\"\nWow! Seems like longer questions tend to have longer response time.\n\"\"\"\nfrom wordcloud import WordCloud\n\nall_q = process_text(first_qa, 'questions_body')['questions_body']\ncloud = WordCloud(width=1440, height=1080).generate(\" \".join(all_q.astype(str)))\nplt.figure(figsize=(20, 15))\nplt.imshow(cloud)\nplt.axis('off')\n\"\"\"\nUnsurprisingly, we see big `college` and `career`.\n\nWhat else differentiates a fast response and slow response question?\n\"\"\"\ntf = TfidfVectorizer(analyzer='word',\n                     min_df=3,\n                     max_df=0.9,\n                     stop_words='english')\n\n# generate a matrix of sentences and a score for each word\nfast_tfidf_matrix = tf.fit_transform(fast_resp)\n\n# generate a list of words from the vectorizer\nfast_vocab = tf.get_feature_names()\n\n# repeat for slow response\nslow_tfidf_matrix = tf.fit_transform(slow_resp)\nslow_vocab = tf.get_feature_names()\n# sum of the scores of each word\n# each row represents a sentence\n# each column represents a word\n# we have to sum across all columns\n\ndef word_score_pair(matrix, vocab):\n    mat_to_arr = matrix.toarray() # convert the 2d matrix to a 2d array\n    word_score = list(map(sum,zip(*mat_to_arr))) # fastest way to sum across all columns\n    rank_words_idx = np.argsort(word_score)\n    idx_list = rank_words_idx[:10]\n    \n    for idx in idx_list:\n        print(\"word: {0}, score: {1:.3f}\".format(vocab[idx], word_score[idx]))\nprint('fast_vocab\\'s words and score:')\nword_score_pair(fast_tfidf_matrix, fast_vocab)\nprint('slow_vocab\\'s words and score:')\nword_score_pair(slow_tfidf_matrix, slow_vocab)\n\"\"\"\nWait a second kid, you are asking about machine learning, data analysis, and big data...?\n\n![](https:\/\/pics.me.me\/machine-learnin-machine-learning-everywhere-emegenerator-net-29035157.png)\n\n## IMPORTANT OBSERVATION:\n* Question body of slow responses are LONGER than that of fast response.\n* Question body of slow responses are DIFFICULT to answer! They require more expertise to answer! \n\"\"\"\n\"\"\"\n# Exploring students\nWhere do the students come from if they are from the US? \n\"\"\"\nstate_codes = {'District of Columbia' : 'DC','Mississippi': 'MS', 'Oklahoma': 'OK', \n               'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR', \n               'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA', \n               'Idaho': 'ID', 'Wyoming': 'WY', 'Tennessee': 'TN', 'Arizona': 'AZ', \n               'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT', \n               'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT', \n               'California': 'CA', 'Massachusetts': 'MA', 'West Virginia': 'WV', \n               'South Carolina': 'SC', 'New Hampshire': 'NH', 'Wisconsin': 'WI',\n               'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND', \n               'Pennsylvania': 'PA', 'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY', \n               'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO', 'Ohio': 'OH', \n               'Alabama': 'AL', 'Rhode Island': 'RI', 'South Dakota': 'SD', \n               'Colorado': 'CO', 'New Jersey': 'NJ', 'Washington': 'WA', \n               'North Carolina': 'NC', 'New York': 'NY', 'Texas': 'TX', \n               'Nevada': 'NV', 'Maine': 'ME'}\nstudents['students_location'] = students['students_location'].fillna('')\nstudents['students_location'] = students['students_location'].str.split(',').str[1]\nstudents['students_location'] = students['students_location'].str.lstrip() # remove first white space\n\ns_val_cnt = students['students_location'].value_counts()\ns_val_cnt[:10]\nus_states = []\n\n# only get the location if it's in US\nfor s in s_val_cnt.index.tolist():\n    if s in state_codes:\n        us_states.append(s)\ndf = pd.DataFrame({'states': s_val_cnt.index,\n                   'count': s_val_cnt.values})\n\ndf = df[df['states'].isin(us_states)]\ndf['states'] = df['states'].apply(lambda x: state_codes[x])\ndata = [ dict(\n        type='choropleth',\n        autocolorscale = True,\n        locations = df['states'], \n        z = df['count'].astype(float), \n        locationmode = 'USA-states', \n        text = df['states'], \n        marker = dict(\n            line = dict (\n                color = 'rgb(255,255,255)',\n                width = 2\n            ) ),\n        colorbar = dict(  \n            title = \"count\")  \n        ) ]\n\nlayout = dict(\n        title = 'Number of Students by State<br>(Hover for breakdown)',\n        geo = dict(\n            scope='usa',\n            projection=dict( type='albers usa' ),\n            showlakes = True,\n            lakecolor = 'rgb(255, 255, 255)'),\n             )\n\nfig = dict(data=data, layout=layout)\niplot(fig)\n\"\"\"\n# Exploring professionals\nMerging questions_answers with professionals.\n\"\"\"\nqap = merging(qa, professionals, \"answers_author_id\", \"professionals_id\")\nqap.head(3).T\n\"\"\"\nWhat industry do the professionals come from?\n\"\"\"\np_industry_cnt = professionals['professionals_industry'].value_counts()\n\nplt.figure(figsize=(10,8))\nsns.barplot(p_industry_cnt.index, \n            p_industry_cnt.values,\n            order=p_industry_cnt.iloc[:10].index)\n\nplt.xticks(rotation=90)\nplt.xlabel('professionals_industry', fontsize=16)\nplt.ylabel('counts', fontsize=16)\nplt.title('counts vs professionals_industry', fontsize=18)\nplt.show()\n\"\"\"\nWhat are the professionals' headline?\n\"\"\"\np_cnt = professionals['professionals_headline'].value_counts()\n\nplt.figure(figsize=(10,8))\nsns.barplot(p_cnt.index, \n            p_cnt.values,\n            order=p_cnt.iloc[1:11].index) # 1 to 11 because we remove NaNs\n\nplt.xticks(rotation=90)\nplt.xlabel('professionals_headline', fontsize=16)\nplt.ylabel('counts', fontsize=16)\nplt.title('counts vs professionals_headline', fontsize=18)\nplt.show()\n\"\"\"\nWho are our biggest heroes?\n\"\"\"\nqap_author_id = qap['answers_author_id'].value_counts()\n\nplt.figure(figsize=(10,8))\nsns.barplot(qap_author_id.index, \n            qap_author_id.values,\n            order=qap_author_id.iloc[:10].index)\n\nplt.xticks(rotation=90)\nplt.xlabel('answers_author_id', fontsize=16)\nplt.ylabel('counts', fontsize=16)\nplt.title('counts vs answers_author_id', fontsize=18)\nplt.show()\n\"\"\"\nWhere do the professionals come from? Let's remove the city to get a better context.\n\"\"\"\np = professionals.copy()\np['professionals_location'] = p['professionals_location'].str.split(',').str[1]\n\np_cnt = p['professionals_location'].value_counts()\n\nplt.figure(figsize=(10,8))\nsns.barplot(p_cnt.index, \n            p_cnt.values,\n            order=p_cnt.iloc[0:10].index) # 1 to 11 because we remove NaNs\n\nplt.xticks(rotation=90)\nplt.xlabel('professionals_location', fontsize=16)\nplt.ylabel('counts', fontsize=16)\nplt.title('counts vs professionals_location', fontsize=18)\nplt.show()\n\"\"\"\nLet's check for active professionals.\n\"\"\"\npa = merging(professionals, answers, \"professionals_id\", \"answers_author_id\")\n\n# get active authors\npa['ans_cnt'] = 1\np = pa.groupby('professionals_id')['ans_cnt'].sum()\nactive_p = (p[p > 5].index).tolist()\nactive_p\n\n# get an updated list of authors\npa['answers_date_added'] = pd.to_datetime(pa['answers_date_added'])\nrecent_p = (pa[pa['answers_date_added'] >= pd.datetime(2018, 1, 1)]['professionals_id']).tolist()\nrecent_p\n\n# get the intersection of both recent and active authors\nactive_recent_p = list(set(recent_p) & set(active_p))\n\nlen(recent_p), len(active_p), len(active_recent_p)\n\"\"\"\nWe have 17,225 authors who have answered more than 5 questions and 1,766 authors who at least answered a question in year 2018 since the data was collected up to January 31st of 2019.\n\"\"\"\n\"\"\"\n# Exploring professionals and answers\nLet's take a closer look at the professionals' answers.\n\"\"\"\npa = merging(professionals, answers, \"professionals_id\", \"answers_author_id\")\npa.head().T\nbefore = pa.iloc[0]['answers_body'][:496]\nbefore\n\"\"\"\nWhat a messy answers_body! Let's clean it up by stripping html, remove punctuations and stopwords. Credits to Matteo Tosi for his regex pattern. Let's go! \n\"\"\"\nuri_re = r'(?i)\\b((?:https?:\/\/|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\\'\".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019]))'\n\ndef strip_html(s):\n    return re.sub(uri_re, ' ', str(s))\n\"\"\"\nThe following block of code basically strips html, replace punctuations, convert all string to lowercase and remove stopwords!\n\"\"\"\npa['answers_body'] = pa['answers_body'].apply(strip_html)\npa['answers_body'] = pa['answers_body'].str.replace('[^\\w\\s\\n\\t]',' ') # replace punctuations\npa['answers_body'] = pa['answers_body'].str.lower().str.split() # convert all str to lowercase\npa['answers_body'] = pa['answers_body'].apply(lambda x: [item for item in x if item not in stop]) # remove stopwords\npa['answers_body'] = pa['answers_body'].apply(' '.join) # convert list to str\nafter = pa.iloc[0]['answers_body'][:496]\nafter\n\"\"\"\nComparing before and after, we did a grea job!\n\"\"\"\nall_a = pa['answers_body']\ncloud = WordCloud(width=1440, height=1080).generate(\" \".join(all_a.astype(str)))\nplt.figure(figsize=(20, 15))\nplt.imshow(cloud)\nplt.axis('off')\n\"\"\"\nOne, work, good luck. Awesome! \n\"\"\"\n\"\"\"\n# Exploring tags\nLet's explore the tags by first merging the tags with tag_questions and then merge the tag of each question to our questions_answers_professionals and remove some not so useful features.\n\"\"\"\nttq = merging(tags, tag_questions, \"tags_tag_id\", \"tag_questions_tag_id\")\nqttq = merging(questions, ttq, \"questions_id\", \"tag_questions_question_id\")\ntqq_list = ttq['tag_questions_question_id'].tolist()\nquestions.shape[0], questions[~questions['questions_id'].isin(tqq_list)].shape[0]\n\"\"\"\nOut of the 23,931 questions, 643 questions do not have tags.\n\"\"\"\n\"\"\"\nWhat are some common and rare tags?\n\"\"\"\nval_cnt = ttq['tags_tag_name'].value_counts()\nto_replace = val_cnt[val_cnt <= 5].index.tolist()\n\nprint(\"Top 10 most popular tags:\")\nprint(val_cnt[:10], '\\n')\nprint(\"Number of unique tags: \", ttq['tags_tag_name'].nunique())\nprint(\"Number of tags that occur 5 times and below: \", len(to_replace))\ntop_10_val_cnt = val_cnt[:10]\n\nfig = {\n    \"data\": [\n    {\n      \"values\": top_10_val_cnt.values,\n      \"labels\": top_10_val_cnt.index,\n      \"domain\": {\"x\": [0, .48]},\n      \"marker\" : dict(colors=[\"#f77b9c\" ,'#ab97db',  '#b0b1b2']),\n      \"name\": \"tag count\",\n      \"hoverinfo\":\"label+percent+name\",\n      \"hole\": .5,        \n      \"type\": \"pie\"\n    }],\n    \"layout\": {\n      \"title\":\"Tags and Count\",\n      \"annotations\": [\n            {\n                \"font\": {\n                    \"size\": 20\n                },\n                \"showarrow\": False,\n                \"text\": \"Tags\",\n                \"x\": 0.2,\n                \"y\": 0.5\n            }]\n    }\n}\n        \niplot(fig, filename='plot-0')\n\"\"\"\nWhat are some variations of #college?\n\"\"\"\ndef search_pat(pat, tags_list):\n    sim_pat = []\n    for s in tags_list:\n        if pat in s:\n            sim_pat.append(s)    \n    return sim_pat\ntags_list = val_cnt.index.tolist()\nc_idx = []\nc_val = []\n\nfor c in search_pat(\"college\", tags_list)[:10]:\n    c_idx.append(c)\n    c_val.append(val_cnt[c])\n\ndf = pd.DataFrame({'variation of #college': c_idx,\n                   'counts': c_val})\nfig = {\n    \"data\": [\n    {\n      \"values\": df['counts'],\n      \"labels\": df['variation of #college'],\n      \"domain\": {\"x\": [0, .48]},\n      \"marker\" : dict(colors=[\"#f77b9c\",\"#efbc56\", \"#81a7e8\", \"#e295d0\"]),\n      \"name\": \"count\",\n      \"hoverinfo\":\"label+percent+name\",\n      \"hole\": .5,        \n      \"type\": \"pie\"\n    }],\n    \"layout\": {\n      \"title\":\"#college and Count\",\n      \"annotations\": [\n            {\n                \"font\": {\n                    \"size\": 20\n                },\n                \"showarrow\": False,\n                \"text\": \"#college\",\n                \"x\": 0.16,\n                \"y\": 0.5\n            }]\n    }\n}\n        \niplot(fig, filename='plot-1')\n\"\"\"\n`college` is the most popular tag. That might just be an abuse of the tag which does not give a good indication of the nature of the question but its variation does! We should remove `college` tag from questions with multiple tags.\n\"\"\"\ndef multi_single_tags(df, tag):\n    without_tag = df[df['tags_tag_name'] != tag]['tag_questions_question_id'].tolist()\n    with_tag = df[df['tags_tag_name'] == tag]['tag_questions_question_id'].tolist()\n    \n    only_tag = df[~df['tag_questions_question_id'].isin(without_tag)]['tag_questions_question_id'].tolist()\n\n    multiple_tags = list(set(with_tag) - set(only_tag))\n    \n    return multiple_tags, only_tag\ndef remove_multiple(df, tag, ids_multiple, ids_single):\n    df = df[((df['questions_id'].isin(ids_multiple)) & (df['tags_tag_name'] != tag)) | \n             (df['tags_tag_name'] != tag) |\n             (df['questions_id'].isin(ids_single))]\n    return df\n\"\"\"\nAfter generating a list of questions with multiple tags that contain the tag `college` and a list of questions with only the tag `college`, we proceed to remove those entries that have multiple tags that contain `college`. \n\"\"\"\ncollege_ids_multiple, college_ids_single = multi_single_tags(ttq, \"college\")\n\nprint('Before removing multiple tags containing #college, we have {} questions.'.format(qttq.shape[0]))\n\nqttq = remove_multiple(qttq, \"college\", college_ids_multiple, college_ids_single)\n\nprint('After removing multiple tags containing #college, we are left with {} questions.'.format(qttq.shape[0]))\ndef combine_tags(df):\n    grouped = df.groupby('questions_id')['tags_tag_name'].apply(lambda x: \"%s\" % ', '.join(x))\n    df_c = merging(questions, pd.DataFrame(grouped), \"questions_id\", \"questions_id\")\n    return df_c\ncombine_qttq = combine_tags(qttq)\ncombine_qttq.head().T\n# qapttq = merging(qap, ttq, \"questions_id\", \"tag_questions_question_id\")\nqapttq = merging(answers, combine_qttq, \"answers_question_id\", \"questions_id\")\nqapttq.head().T\nqapttq.shape[0], combine_qttq.shape[0]\n\"\"\"\nWe are now left with 23,242 unique questions and 49,323 rows - indicating some questions receive multiple answers.\n\"\"\"\n\"\"\"\n# Questions\nLet's explore the questions body by looking at the most common bigrams. Here, I remove some \"noise\" that are common words, polite expressions, and others deem as unhelpful.\n\"\"\"\nnoise = ['school','would','like', 'want', 'dont', \n         'become','sure','go', 'get', 'college', \n         'career', 'wanted', 'im', 'ing', 'ive',\n         'know', 'high', 'becom', 'job', 'best',\n         'day', 'hi', 'name', 'help', 'people',\n         'year', 'years', 'next', 'interested', \n         'question', 'questions', 'take', 'even',\n         'though', 'please', 'tell']\ndef another_process_text(df, col):\n    df[col] = df[col].str.replace('[^\\w\\s]','') # replacing punctuations\n    df[col] = df[col].str.replace('-',' ') # replacing dashes\n    df[col] = df[col].str.replace('\\d+','') # replacing digits\n    df[col] = df[col].str.lower().str.split() # convert all str to lowercase    \n    df[col] = df[col].apply(lambda x: [item for item in x if item not in stop]) # remove stopwords\n    df[col] = df[col].apply(lambda x: [item for item in x if item not in noise])\n    df[col] = df[col].apply(' '.join) # convert list to str\n    return df\n\ndef generate_ngrams(text, N):\n    grams = [text[i:i+N] for i in range(len(text)-N+1)]\n    grams = [\" \".join(b) for b in grams]\n    return grams\ndf = another_process_text(questions, 'questions_body')\ndf['bigrams'] = df['questions_body'].apply(lambda x : generate_ngrams(x.split(), 2))\nall_bigrams = []\n\nfor each in df['bigrams']:\n    all_bigrams.extend(each)\n    \nt1 = Counter(all_bigrams).most_common(20)\nx1 = [a[0] for a in t1]\ny1 = [a[1] for a in t1]\nfig, axes = plt.subplots(figsize=(15,10))\n\nbar = sns.barplot(y=x1, x=y1)\nbar.set(ylabel='Most frequent bigrams', xlabel='Frequency')\n\"\"\"\n# Building tag_chart\nThe below function takes in a tag and returns the professionals who have answered the most questions in the tag category.\n\"\"\"\ndef tag_chart(df, what_tag, top):\n    \"\"\"\n    df: the DataFrame\n    what_tag: tags we are looking for\n    top: number of professionals in the chart after filtering\n    \"\"\"    \n    mod_df = df[['answers_author_id', 'tags_tag_name']].copy()\n    mod_df['tag_count'] = 1\n    grouped = mod_df.groupby(['tags_tag_name', 'answers_author_id']).sum()\n    grouped_df = (grouped.reset_index()\n                         .sort_values(['tags_tag_name', 'tag_count'], ascending=False)\n                         .set_index(['answers_author_id']))\n\n    grouped_filter = grouped_df[grouped_df['tags_tag_name'] == what_tag]['tag_count'].reset_index()\n    return grouped_filter.head(top)\n# remerge our qapttq since we modified the tags in the previous one\nqapttq = merging(qap, ttq, \"questions_id\", \"tag_questions_question_id\")\n\ntag_chart(qapttq, \"college\", 5), tag_chart(qapttq, \"engineering\", 5) \n\"\"\"\nHero \"36ff3b3666df400f956f8335cf53e09e\" has answered a total of 693 questions under the tag \"college\" while hero \"c3b4e11154f74a858779be7ba9b6f00c\" has answered a total of 194 questions under the tag \"engineering\".\n\"\"\"\n\"\"\"\n# Content Based Recommender\nIdeally, we would like to associate a question to professionals who have been actively answering similar questions.\n\"\"\"\ndef combine_authors(df):\n    c = df.groupby('questions_id')['answers_author_id'].apply(list)\n    df_c = merging(df, pd.DataFrame(c), 'questions_id', 'questions_id')\n    df_c.drop('answers_author_id_x', axis=1, inplace=True)\n    df_c['answers_author_id_y'] = df_c['answers_author_id_y'].apply(', '.join)\n    df_c.drop_duplicates(inplace=True)\n    return df_c\nqa_sub = qa[['questions_title', 'questions_body', 'answers_author_id', 'questions_id']].copy()\n\nqa_cbr = combine_authors(qa_sub)\n\nauthors_link = qa_cbr[['questions_id', 'answers_author_id_y']].copy()\n\nqa_cbr.drop('answers_author_id_y', axis=1, inplace=True)\n\nqa_cbr.head()\n# hacky way to remove authors who are not linked\nauthors_link = authors_link[authors_link['answers_author_id_y'].str.len() > 33] \n\nauthors_link_dic = authors_link.set_index('questions_id').T.to_dict()\nqa_cbr = process_text(qa_cbr, \"questions_title\") \nqa_cbr = process_text(qa_cbr, \"questions_body\") \n\nqa_cbr.head()\n\"\"\"\nThe following recommender system was the work of Rounak Banik. A huge thanks (and credits) to Rounak!\n\"\"\"\ntf = TfidfVectorizer(analyzer='word',\n                     ngram_range=(1,2),\n                     min_df=3,\n                     max_df=0.9,\n                     stop_words='english')\n\ntfidf_matrix = tf.fit_transform(qa_cbr['questions_body'])\ntfidf_matrix.shape\ncosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n# qa_cbr = qa_cbr.reset_index()\nq_titles = qa_cbr['questions_title']\nq_ids = qa_cbr['questions_id']\nindices = pd.Series(qa_cbr.index, index=qa_cbr['questions_title'])\n\nqa_cbr.head()\ndef get_recommendations_idx(title):\n    idx = indices[title]\n    sim_scores = list(enumerate(cosine_sim[idx]))\n    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n    sim_scores = sim_scores[1:31]\n    q_indices = [i[0] for i in sim_scores]\n    return q_indices\n\ndef get_recommendations(title):\n    return q_titles.iloc[get_recommendations_idx(title)]\n    \ndef get_questions_id(title):\n    return q_ids.iloc[get_recommendations_idx(title)]    \nget_recommendations('want become army officer become army officer').head(10)\n\"\"\"\nUndeniably, they are related to army!\n\"\"\"\nget_questions_id('want become army officer become army officer').head(10)\ndef get_sim_authors(qids):\n    sim_authors = []\n    for qid in qids:\n        if qid in authors_link_dic:\n            sim_authors.append(authors_link_dic[qid]['answers_author_id_y'])\n    return sim_authors\nqids = get_questions_id('want become army officer become army officer').tolist()\n\nqa[qa['questions_id'].isin(qids)].head()\nsim_ids = []\nfor all_ids in get_sim_authors(qids):\n    for each_id in all_ids.split(','):\n        sim_ids.append(each_id)\n\nsim_ids = set(sim_ids)\n\nsim_active_recent = set(active_recent_p) & set(sim_ids)\n\nsim_active_recent\n\nprofessionals[professionals['professionals_id'].isin(sim_active_recent)].T\n\"\"\"\nSo these are the professionals who have been answering questions related to \"army\"!\n\"\"\"\n\"\"\"\n# t-SNE visualization\nLet's explore some t-SNE visualization. Essentially, t-SNE learns a mapping from a set of high-dimensional vectors and output the outcome to a space with in 2 dimensions. Credits to DanB for sharing the t-SNE plot code.\n\"\"\"\nfrom sklearn.manifold import TSNE\n\ntsne = TSNE(random_state=0, n_iter=250, metric=\"cosine\")\n\"\"\"\nTo prevent running out of memory, we sample 40% of our data for visualization purposes. Since t-SNE takes in an embedding matrix, we feed it with our tf-idf matrix.\n\"\"\"\ng_q_sample = qa_cbr.sample(frac=.4, random_state=43)\n\ntf = TfidfVectorizer(analyzer='word',\n                     ngram_range=(1,2),\n                     min_df=0,\n                     stop_words='english')\n\ntfidf_matrix = tf.fit_transform(g_q_sample['questions_body'])\ntfidf_matrix.shape\n\ntm = tfidf_matrix.toarray()\n\ntsne_matrix = tsne.fit_transform(tm)\n\ntsne_matrix\n\"\"\"\nWe add the x- and y-coordinate calculated by t-SNE to our dataframe.\n\"\"\"\ndf = g_q_sample.copy()\n\ndf['x'] = tsne_matrix[:, 0]\ndf['y'] = tsne_matrix[:, 1]\nFS = (10, 8)\nfig, ax = plt.subplots(figsize=FS)\n# Make points translucent so we can visually identify regions with a high density of overlapping points\nax.scatter(df.x, df.y, alpha=.1)\n\"\"\"\nSeems like most points are clustered around the center region. Can we generate a better plot?\n\"\"\"\nFS = (18, 8)\ndef plot_region(x0, x1, y0, y1, text=True):\n    \"\"\"\n    Plot the region of the mapping space bounded by the given x and y limits.\n    \"\"\"    \n    pts = df[\n        (df.x >= x0) & (df.x <= x1)\n        & (df.y >= y0) & (df.y <= y1)\n    ]\n    fig, ax = plt.subplots(figsize=FS)\n    ax.scatter(pts.x, pts.y, alpha=.6)\n    ax.set_xlim(x0, x1)\n    ax.set_ylim(y0, y1)\n    if text:\n        texts = []\n        for label, x, y in zip(pts.questions_title.values, pts.x.values, pts.y.values):\n            t = ax.annotate(label, xy=(x, y))\n            texts.append(t)\n    return ax\n\ndef plot_region_around(title, margin=5, **kwargs):\n    \"\"\"\n    Plot the region of the mapping space in the neighbourhood of the the questions_title. \n    The margin parameter controls the size of the neighbourhood around the movie.\n    \"\"\"\n    xmargin = ymargin = margin\n    match = df[df.questions_title == title]\n    assert len(match) == 1\n    row = match.iloc[0]\n    return plot_region(row.x-xmargin, row.x+xmargin, row.y-ymargin, row.y+ymargin, **kwargs)\n# df\nplot_region_around('lifestyle pediatric surgeon', .00005)\n\"\"\"\nI would say points within the .00005 region of \"lifestyle pediatric surgeon\" are pretty much related.\n\"\"\"\n\"\"\"\n# How can we utilize this to pair future questions with authors?\n## To be continued...\n### Please upvote if you find the work useful. Thanks! :))\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3db544e7de3457'}"}
{"id":"36539","text":"\"\"\"\n**Imports**\n\"\"\"\nimport re\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nprint(tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE\nGCS_PATH=KaggleDatasets().get_gcs_path('512x512-melanoma-tfrecords-70k-images')\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is set.\n    # On Kaggle this is always the case.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\"\"\"\n**Hyper parameters**\n\"\"\"\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n            \nIMAGE_SIZE = [512 , 512]\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH+'\/train*')\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH+'\/test*')\n\"\"\"\n# Preparing the dataset\n\"\"\"\ndef decode_augument_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.bfloat16) \/ 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    return image\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.bfloat16) \/ 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),  \n        \"sex\": tf.io.FixedLenFeature([], tf.int64), \n        \"anatom_site_general_challenge\" : tf.io.FixedLenFeature([] , tf.int64),\n        \"target\": tf.io.FixedLenFeature([], tf.int64),  \n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_augument_image(example['image'])\n    age = tf.cast(example['age_approx'], tf.bfloat16)\n    sex = tf.cast(example['sex'], tf.bfloat16)\n    asg = tf.cast(example['anatom_site_general_challenge'] , tf.bfloat16)\n    target = tf.cast(example['target'], tf.int32)\n    return image,target\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),  \n        \"sex\": tf.io.FixedLenFeature([], tf.int64), \n        \"anatom_site_general_challenge\" : tf.io.FixedLenFeature([] , tf.int64),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    age = tf.cast(example['age_approx'], tf.bfloat16)\n    sex = tf.cast(example['sex'], tf.bfloat16)\n    asg = tf.cast(example['anatom_site_general_challenge'] , tf.bfloat16)\n    idnum = example['image_name']\n    return image,idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES,labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=True):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\n#VALIDATION_STEPS = NUM_VALID_IMAGES \/\/ BATCH_SIZE\nprint('Dataset: {} training images ,{} unlabeled test images'.format(NUM_TRAINING_IMAGES,NUM_TEST_IMAGES))\nprint(\"STEPS_PER_EPOCH are {}\".format(STEPS_PER_EPOCH))\n#print(\"validation Steps are {}\".format(VALIDATION_STEPS))\ntrain_ds=get_training_dataset()\n\"\"\"\n# Training \n\"\"\"\n!pip install -q efficientnet\nfrom tensorflow.keras import *\nfrom tensorflow.keras.layers import *\nfrom efficientnet.tfkeras import *\n\"\"\"\n**Model Architectures**\n\"\"\"\ndef create_model():\n    base_model=EfficientNetB7(include_top=False,input_shape=(*IMAGE_SIZE,3))\n    base_model.trainable=False\n    inp1=Input(shape=(*IMAGE_SIZE,3))\n    #inp2=Input(shape=(3,))\n    X=base_model(inp1,training=False)\n    X=GlobalAveragePooling2D()(X)\n    '''Z=Dense(256,activation='relu')(inp2)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    Z=Dense(256,activation='relu')(Z)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    X=Concatenate()([X,Z])'''\n    X=Dense(512,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.2)(X)\n    X=Dense(1024,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.4)(X)\n    Y=Dense(1,activation='sigmoid')(X)\n    return Model(inputs=inp1,outputs=Y)\ndef create_model2():\n    base_model=EfficientNetB7(include_top=False,input_shape=(*IMAGE_SIZE,3))\n    base_model.trainable=False\n    inp1=Input(shape=(*IMAGE_SIZE,3))\n    #inp2=Input(shape=(3,))\n    X=base_model(inp1,training=False)\n    X=GlobalAveragePooling2D()(X)\n    '''Z=Dense(256,activation='relu')(inp2)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    Z=Dense(256,activation='relu')(Z)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    X=Concatenate()([X,Z])'''\n    X=Dense(256,activation='relu')(X)\n    X=Dropout(0.4)(X)\n    X=BatchNormalization()(X)\n    X=Dense(1024,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.4)(X)\n    Y=Dense(1,activation='sigmoid')(X)\n    return Model(inputs=inp1,outputs=Y)\n\"\"\"\n# Model1\n\"\"\"\nwith strategy.scope():\n    model = create_model()\n    \n    model.compile(optimizer='rmsprop',\n                  loss='binary_crossentropy',\n                  metrics=[tf.keras.metrics.BinaryCrossentropy(),'accuracy'])\n    \n    model.summary()\ntf.keras.utils.plot_model(model,show_shapes=True)\n# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.000001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 4\nLR_SUSTAIN_EPOCHS = 4\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) \/ LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nes=tf.keras.callbacks.EarlyStopping(monitor='loss',mode='min',patience=4,verbose=1)\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.2,patience=4,mode='min', min_lr=0.001)\nmodel.fit(train_ds,\n          epochs=20,\n          steps_per_epoch=STEPS_PER_EPOCH,\n          callbacks=[es,lr_callback,reduce_lr]\n         )\n\"\"\"def display_training_curves(training, validation, title, subplot):\n    #Source: https:\/\/www.kaggle.com\/mgornergoogle\/getting-started-with-100-flowers-on-tpu\n    \n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\"\"\"\nimport h5py\n\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n\nmodel.save_weights(\"mo.h5\")\nprint(\"Saved model to disk\")\n\"\"\"\n# Predictions\n\"\"\"\ndef predictions():\n    test_ds=get_test_dataset(ordered=True)\n\n    test_ds_features=test_ds.map(lambda img,idnum: img) #Getting the features of the Test_ds\n\n    preds=model.predict(test_ds_features) #predicting with the model\n\n    test_ids_ds = test_ds.map(lambda img,imname: imname).unbatch()\n\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n    prediction_df=pd.DataFrame({'image_name':test_ids ,'target':np.concatenate(preds)}) #writing to Dataframs\n\n    prediction_df.to_csv(\"submission.csv\",index=False) #Generating CSV file\n    \npredictions()\n\"\"\"\n# Model2\n\"\"\"\n\"\"\"with strategy.scope():\n    model2=create_model2()\n    \n    model2.compile(optimizer='adam',\n                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n                  metrics=[tf.keras.metrics.BinaryCrossentropy(),'accuracy'])\n    model2.summary()\"\"\"\ntf.keras.utils.plot_model(model2,show_shapes=True)\nmodel2.fit(get_training_dataset(),\n           epochs=10,\n           steps_per_epoch=STEPS_PER_EPOCH\/\/2,\n           callbacks=[es,lr_callback,reduce_lr]\n          )\ndef predictions():\n    test_ds=get_test_dataset(ordered=True)\n\n    test_ds_features=test_ds.map(lambda img,idnum: img) #Getting the features of the Test_ds\n\n    preds=model2.predict(test_ds_features) #predicting with the model\n\n    test_ids_ds = test_ds.map(lambda img,imname: imname).unbatch()\n\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n    prediction_df=pd.DataFrame({'image_name':test_ids ,'target':np.concatenate(preds)}) #writing to Dataframs\n\n    prediction_df.to_csv(\"submission(1).csv\",index=False) #Generating CSV file\n    \npredictions()\n#not well","meta":"{'source': 'AI4Code', 'id': '434a00d155440a'}"}
{"id":"96004","text":"\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\nThis notebook is an effort to understand TPU and get better at computer vision tasks. This is my first effort in performing tasks in TPU. Following is how I approached this competition - \n\"\"\"\n\"\"\"\n* V1: Simple Resnet-50 with freezing of parameters. (F-score: **0.00025**)\n* V2: EfficientNet-B4 with non freezing of layers.(From now on layers are never freezed) Also added ramp up learning rate. (F-score: **0.87193**)\n* V3 & V4: Has errors\n* V5: EfficientNet-B7 with class weights for imbalance. (Model learns very slowly) F-score: **0.88873**\n* V6: Added the validation data into training data (F-score: **0.95352**)\n* V7: Used Denset201. It overfits a little bit (F-score: **0.94371**)\n* V8: Added random-blackout augmentation with EfficientNet-B7 (F-score: **0.95465**)\n* V9: Ensemble model of EfficientNet-B7 and DenseNet201. Added external dataset from Oxford (F-score: **0.96329**)\n* V10: Using K-fold cross validation. Did not run it because training takes long time.\n* V11: Same as version 9 but without external dataset and more epochs. (F-score: **0.96140**)\n* V12: Same as version 11 but including external dataset\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\n!pip install -q efficientnet\nimport math, re, os\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow.keras.layers as L\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\nfrom tensorflow import keras\nfrom functools import partial\nprint(\"Tensorflow version \" + tf.__version__)\n\nfrom collections import Counter\nimport gc\n\"\"\"\n# Distribution Strategy\n\"\"\"\n\"\"\"\nA TPU has eight different cores and each of these cores acts as its own accelerator. (A TPU is sort of like having eight GPUs in one machine.) We tell TensorFlow how to make use of all these cores at once through a distribution strategy. The following cell creates the distribution strategy that we'll later apply to our model.\n\nWe'll use the distribution strategy when we create our neural network model. Then, TensorFlow will distribute the training among the eight TPU cores by creating eight different replicas of the model, one for each core.\n\"\"\"\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)\nfrom numpy.random import seed\nseed(1)\n\"\"\"\n# Loading the Data\n\"\"\"\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nGCS_DS_PATH_EXT = KaggleDatasets().get_gcs_path('oxford-102')\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nHEIGHT = 512 \nWIDTH = 512\nCHANNELS = 3\nIMAGE_SIZE = [HEIGHT, WIDTH]\nEPOCHS = 20\n\"\"\"\n## GCS Path\nWhen used with TPUs, datasets need to be stored in a Google Cloud Storage bucket. You can use data from any public GCS bucket by giving its path just like you would data from '\/kaggle\/input'. The following will retrieve the GCS path for this competition's dataset.\n\"\"\"\nGCS_PATH = GCS_DS_PATH + '\/tfrecords-jpeg-512x512'\nGCS_PATH_EXT = GCS_DS_PATH_EXT + '\/tfrecords-jpeg-512x512'\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '\/train\/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '\/val\/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '\/test\/*.tfrec') \n\nOXFORD_FILES = tf.io.gfile.glob(GCS_PATH_EXT + '\/*.tfrec')\n\nTRAINING_FILENAMES = TRAINING_FILENAMES + OXFORD_FILES\n\nSKIP_VALIDATION = True\nif SKIP_VALIDATION:\n    TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES\n\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102\n\n\n\"\"\"\nWe convert the image from tfRecord to tensor so that we can- \n* Change the image size\n* Normalize the pixels between 0-1\n\"\"\"\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32) \/ 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\"\"\"\n# Understanding TFRecord\n\"\"\"\n\"\"\"\nOur data is structured data- (image, label). A single 'Example' represents a single instance in the dataset. Each Example has 'Features' described as a dictionary of feature names and values. A value can be either a BytesList, a FloatList, or an Int64List, each wrapped as a single Feature. Heres how we encode the data-\n\"\"\"\nfrom tensorflow.train import BytesList, FloatList, Int64List\nfrom tensorflow.train import Example, Features, Feature\n\n# The Data\nimage = tf.constant([ # this could also be a numpy array\n    [0, 1, 2],\n    [3, 4, 5],\n    [6, 7, 8],\n])\nlabel = 0\nclass_name = \"Class A\"\n\n\n# Wrap with Feature as a BytesList, FloatList, or Int64List\nimage_feature = Feature(\n    bytes_list=BytesList(value=[\n        tf.io.serialize_tensor(image).numpy(),\n    ])\n)\nlabel_feature = Feature(\n    int64_list=Int64List(value=[label]),\n)\nclass_name_feature = Feature(\n    bytes_list=BytesList(value=[\n        class_name.encode()\n    ])\n)\n\n\n# Create a Features dictionary\nfeatures = Features(feature={\n    'image': image_feature,\n    'label': label_feature,\n    'class_name': class_name_feature,\n})\n\n# Wrap with Example\nexample = Example(features=features)\n\nprint(example)\n\"\"\"\nAll the data is stored as attributes of Example instance. Once everything is encoded as an Example, you can serialize it with the SerializeToString method. \nSerialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.\n\"\"\"\nexample_bytes = example.SerializeToString()\nprint(example_bytes)\n\"\"\"\nNow we already have Serialized data. To decode it, we need to tell tf what kind of data it has to expect. Passing the info to 'tf.io.parse_single_example' gives us the 'Example' as mentioned above which has image in Bytes format. So we have to decode the image back to tensor. \n\"\"\"\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\n\"\"\"\nOne advantage of TPU is that we can run multiple files across TPU at once. Thus once the data gets in, we want to use it immediately and avoid creating any data streaming bottlenecks\n\"\"\"\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset\n\"\"\"\n# Augmentations\n\"\"\"\n# data augmentation @cdeotte kernel: https:\/\/www.kaggle.com\/cdeotte\/rotation-augmentation-gpu-tpu-0-96\ndef transform_rotation(image, height, rotation):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated\n    DIM = height\n    XDIM = DIM%2 #fix for size 331\n    \n    rotation = rotation * tf.random.uniform([1],dtype='float32')\n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation \/ 180.\n    \n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])\n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM\/\/2,-DIM\/\/2,-1), DIM )\n    y = tf.tile( tf.range(-DIM\/\/2,DIM\/\/2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(rotation_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM\/\/2+XDIM+1,DIM\/\/2)\n    \n    # FIND ORIGIN PIXEL VALUES \n    idx3 = tf.stack( [DIM\/\/2-idx2[0,], DIM\/\/2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3])\n\ndef transform_shear(image, height, shear):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly sheared\n    DIM = height\n    XDIM = DIM%2 #fix for size 331\n    \n    shear = shear * tf.random.uniform([1],dtype='float32')\n    shear = math.pi * shear \/ 180.\n        \n    # SHEAR MATRIX\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])    \n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM\/\/2,-DIM\/\/2,-1), DIM )\n    y = tf.tile( tf.range(-DIM\/\/2,DIM\/\/2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(shear_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM\/\/2+XDIM+1,DIM\/\/2)\n    \n    # FIND ORIGIN PIXEL VALUES \n    idx3 = tf.stack( [DIM\/\/2-idx2[0,], DIM\/\/2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3])\n\ndef transform_shift(image, height, h_shift, w_shift):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly shifted\n    DIM = height\n    XDIM = DIM%2 #fix for size 331\n    \n    height_shift = h_shift * tf.random.uniform([1],dtype='float32') \n    width_shift = w_shift * tf.random.uniform([1],dtype='float32') \n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n        \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])\n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM\/\/2,-DIM\/\/2,-1), DIM )\n    y = tf.tile( tf.range(-DIM\/\/2,DIM\/\/2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(shift_matrix,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM\/\/2+XDIM+1,DIM\/\/2)\n    \n    # FIND ORIGIN PIXEL VALUES \n    idx3 = tf.stack( [DIM\/\/2-idx2[0,], DIM\/\/2-1+idx2[1,]] )\n    d = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3])\ndef random_blockout(img, sl=0.1, sh=0.2, rl=0.4):\n\n    h, w, c = tf.shape(img)[0], tf.shape(img)[1], 3\n    origin_area = tf.cast(h*w, tf.float32)\n\n    e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)), tf.int32)\n    e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh \/ rl)), tf.int32)\n\n    e_height_h = tf.minimum(e_size_h, h)\n    e_width_h = tf.minimum(e_size_h, w)\n\n    erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)\n    erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)\n\n    erase_area = tf.zeros(shape=[erase_height, erase_width, c])\n    erase_area = tf.cast(erase_area, tf.uint8)\n\n    pad_h = h - erase_height\n    pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)\n    pad_bottom = pad_h - pad_top\n\n    pad_w = w - erase_width\n    pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)\n    pad_right = pad_w - pad_left\n\n    erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)\n    erase_mask = tf.squeeze(erase_mask, axis=0)\n    erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))\n\n    return tf.cast(erased_img, img.dtype)\ndef data_augment(image, label):\n    seed = (0,0)\n    p_rotation = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_pixel = tf.random.uniform([], 0, 1.0, dtype=tf.float32)    \n    p_shear = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_shift = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_blackout = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    \n    # Blackout\n    if p_blackout >=0.8:\n        image = random_blockout(image)\n    \n    # Flips\n    if p_spatial >= .2:\n        image = tf.image.stateless_random_flip_left_right(image, seed)\n        image = tf.image.stateless_random_flip_up_down(image, seed)\n        \n    # Rotates\n    if p_rotate > .75:\n        image = tf.image.rot90(image, k=3) # rotate 270\u00ba\n    elif p_rotate > .5:\n        image = tf.image.rot90(image, k=2) # rotate 180\u00ba\n    elif p_rotate > .25:\n        image = tf.image.rot90(image, k=1) # rotate 90\u00ba\n    \n    if p_rotation >= .3: # Rotation\n        image = transform_rotation(image, height=HEIGHT, rotation=45.)\n    if p_shift >= .3: # Shift\n        image = transform_shift(image, height=HEIGHT, h_shift=15., w_shift=15.)\n    if p_shear >= .3: # Shear\n        image = transform_shear(image, height=HEIGHT, shear=20.)\n        \n    # Crops\n    if p_crop > .3:\n        crop_size = tf.random.uniform([], int(HEIGHT*.7), HEIGHT, dtype=tf.int32)\n        image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n    elif p_crop > .7:\n        if p_crop > .9:\n            image = tf.image.central_crop(image, central_fraction=.7)\n        elif p_crop > .8:\n            image = tf.image.central_crop(image, central_fraction=.8)\n        else:\n            image = tf.image.central_crop(image, central_fraction=.9)\n            \n    image = tf.image.resize(image, size=[HEIGHT, WIDTH])\n        \n    # Pixel-level transforms\n    if p_pixel >= .2:\n        if p_pixel >= .7:\n            image = tf.image.stateless_random_saturation(image, lower=0.2, upper=0.8, seed=seed)\n        elif p_pixel >= .5:\n            image = tf.image.stateless_random_contrast(image, lower=.3, upper=0.7, seed=seed)\n        elif p_pixel >= .3:\n            image = tf.image.stateless_random_brightness(image, max_delta=.7, seed=seed)\n        else:\n            image = tf.image.adjust_gamma(image, gamma=.6)\n\n    return image, label\ndef get_training_dataset(): \n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True) \n    dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)  \n    dataset = dataset.repeat()          # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)   # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\ndef get_validation_dataset( ordered=False): \n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered) \n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = (1 - SKIP_VALIDATION) * count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} (unlabeled) test images'.format(\n    NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\"\"\"\n# Visualizing Dataset\n\"\"\"\nfrom matplotlib import pyplot as plt\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case,\n                                     # these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is\n    # the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize\/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize\/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square\n    # or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)\/\/rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE\/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE\/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING\/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\n\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\nds_iter = iter(get_training_dataset().unbatch().batch(20))\none_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)\n\"\"\"\n# Defining Model \n\"\"\"\n# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) \/ LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nrng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))\n#gc.enable()\n\n#def get_training_dataset_raw():\n#    dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)\n#    return dataset\n\n#raw_training_dataset = get_training_dataset_raw()\n\n#label_counter = Counter()\n#for images, labels in raw_training_dataset:\n#    label_counter.update([labels.numpy()])\n\n#del raw_training_dataset    \n\n#mean=0\n#for i in label_counter.values():\n#    mean = mean + i\n#mean = float(round(mean\/len(label_counter)))\n\n#def get_weight_for_class(class_id):\n#    counting = label_counter[class_id]\n#    weight = mean \/ counting\n#    return weight\n\n#weight_per_class = {class_id: get_weight_for_class(class_id) for class_id in range(104)}\n\"\"\"\n## Model-1\n\"\"\"\nwith strategy.scope():\n    pretrained_model = efn.EfficientNetB7(\n        weights='noisy-student',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = True\n    \n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        #tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()\ntrain_dataset = get_training_dataset()\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES \/\/ BATCH_SIZE\n\nhistory = model.fit(train_dataset, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=None if SKIP_VALIDATION else get_validation_dataset(),\n                    validation_steps=None if SKIP_VALIDATION else VALID_STEPS,\n                    callbacks=[lr_callback])\n                    #class_weight = weight_per_class)\nif not SKIP_VALIDATION:\n    history_frame = pd.DataFrame(history.history)\n    history_frame.loc[:, ['loss', 'val_loss']].plot()\n    history_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();\n    \nif SKIP_VALIDATION:\n    history_frame = pd.DataFrame(history.history)\n    history_frame.loc[:, ['loss']].plot()\n    history_frame.loc[:, ['sparse_categorical_accuracy']].plot();\n\"\"\"\n## Model-2\n\"\"\"\nwith strategy.scope():\n    pretrained_model_2 = tf.keras.applications.DenseNet201(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model_2.trainable = True\n    \n    model2 = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model_2,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\nmodel2.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel2.summary()\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES \/\/ BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES \/\/ BATCH_SIZE\n\nhistory = model2.fit(train_dataset, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=None if SKIP_VALIDATION else get_validation_dataset(),\n                    validation_steps=None if SKIP_VALIDATION else VALID_STEPS,\n                    callbacks=[lr_callback])\n                    #class_weight = weight_per_class)\nif not SKIP_VALIDATION:\n    history_frame = pd.DataFrame(history.history)\n    history_frame.loc[:, ['loss', 'val_loss']].plot()\n    history_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();\n    \nif SKIP_VALIDATION:\n    history_frame = pd.DataFrame(history.history)\n    history_frame.loc[:, ['loss']].plot()\n    history_frame.loc[:, ['sparse_categorical_accuracy']].plot();\n\"\"\"\n# Predictions\n\"\"\"\ndef to_float32(image, label):\n    return tf.cast(image, tf.float32), label\ntest_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities_1 = model.predict(test_images_ds)\nprobabilities_2 = model2.predict(test_images_ds)\nprobabilities = (probabilities_1 + probabilities_2)\/2\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\nprint('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","meta":"{'source': 'AI4Code', 'id': 'b0477df3a13045'}"}
{"id":"296","text":"# 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\n\"\"\"\n# Load the dataset and explore\n\"\"\"\ntrain=pd.read_csv('..\/input\/weather-dataset-rattle-package\/weatherAUS.csv',index_col=0)\nprint(train.dtypes)\nprint(train.shape)\nprint(train.describe(include='all'))\n#Check if there are missing values in the target variable if true then drop them\nprint(train['RainTomorrow'].isna().sum()\/len(train))\ntrain=train.dropna(axis=0,subset=['RainTomorrow'])\n\nprint(train.shape)\n\"\"\"\n# Divide the dataset into X and y\n\"\"\"\ny=train[['RainTomorrow']]\nX=train.drop(['RainTomorrow'],axis=1)\nprint(X.shape)\n\"\"\"\n# Let us perform EDA on the dataset\n\"\"\"\n#Let us define few functions for visualization\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef boxplot(df):\n    plt.figure(figsize=(10,6))\n    plt.title('Boxplot')\n    sns.boxplot(df)\n    plt.show()\n\ndef histogram(df):\n    plt.figure(figsize=(10,6))\n    sns.displot(df,kde=True)\n    plt.title('Histogram')\n    sns.despine()\n    plt.show\n\ndef countplot(df):\n    plt.figure(figsize=(10,6))\n    sns.countplot(df,palette='spring')\n    plt.title('Countplot')\n    plt.show()\n    \nprint(X.dtypes)\n#Visualize the numeric variables (Boxplot)\n\nnum_col=X.select_dtypes(include=[np.number]).columns\nnum_cols=[n for n in num_col]\n \nfor n in num_cols:\n    boxplot(X[n])\n\"\"\"\nFrom boxplot we can see the only 4 columns have no outliers. Sunshine,WindSpeed3pm , Cloud9am and Cloud3am. In the next step we will visualize the distribution of the variables.\n\"\"\"\n#Distribution of the numeric variables\n\nfor n in num_cols:\n    histogram(X[n])\nprint(num_cols)\n\"\"\"\nThe columns ['Evaporation', 'Sunshine', 'WindGustSpeed', 'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am','Cloud9am', 'Cloud3pm'] are not symmetric in nature. We'll apply preprocessing later. We'll not that much be oncerned about outlers as we'll implement Boosting learner.\n\"\"\"\n#Count plot of the categorical variables\ncat_col=X.select_dtypes(exclude=[np.number]).columns\ncat_cols=[ c for c in cat_col]\n\nfor c in cat_cols:\n    countplot(X[c])\n\n\"\"\"\nWe see thet the RainToday column is imbalanced.\n\"\"\"\n\"\"\"\n# Check for missing values\n\n\"\"\"\nprint(X.select_dtypes(include=[np.number]).isna().sum()\/len(X))\nprint('************************************************')\nprint(X.select_dtypes(exclude=[np.number]).isna().sum()\/len(X))\n\"\"\"\nEvaporation and Cloud3pm has 43 and 40 percent missing values. Sunshine also has 48 percent missing values and Cloud9am has 37 percent missing values. We'll impute these values later. What strategy to use for imputation depends on whether outliers exists ir not for that variable.\n\"\"\"\n\"\"\"\n# Check whether the dependent variable is balanced or not\n\"\"\"\nprint(y.value_counts())\ncountplot(y['RainTomorrow'])\n\"\"\"\nThe dataset is highly imbalaced. Thus we'll split the data in a stratified manner.\n\"\"\"\n\"\"\"\n# Perform Train Test split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train,X_valid,y_train,y_valid=train_test_split(X,y,test_size=.25,stratify=y,random_state=99)\nprint(X_train.shape, X_valid.shape)\nprint(y_train.value_counts())\n\"\"\"\nClearly the stratification is maintained here also.\n\"\"\"\n\"\"\"\n# Apply preprocessing \n\"\"\"\n#Apply preprocessing to the numeric variables\n\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import QuantileTransformer\n\nfor c in num_cols:\n    im_n=SimpleImputer(strategy='median')\n    X_train[c]=im_n.fit_transform(X_train[[c]])\n    X_valid[c]=im_n.transform(X_valid[[c]])\n\nfor n in num_cols:\n    qt=QuantileTransformer(output_distribution='normal',random_state=99)\n    X_train[n]=qt.fit_transform(X_train[[n]])\n    X_valid[n]=qt.transform(X_valid[[n]])\n    \nprint(X_train.isna().sum())       \n\"\"\"\nClearly the missing values are imputed with median strategy\n\"\"\"\n#Preprocessing for categorical variables\nfrom sklearn.preprocessing import OrdinalEncoder\n\nfor c in cat_cols:\n    im_c=SimpleImputer(strategy='most_frequent')\n    X_train[c]=im_c.fit_transform(X_train[[c]])\n    X_valid[c]=im_c.transform(X_valid[[c]])\n\nfor c in cat_cols:\n    oe=OrdinalEncoder(dtype=int)\n    X_train[c]=oe.fit_transform(X_train[[c]])\n    X_valid[c]=oe.transform(X_valid[[c]])\nprint(X_train.head(n=6))\n\"\"\"\nAll the preprocessing is completed without any data leakage\n\"\"\"\n\"\"\"\n> # Modeling using catBoostClassifier\n\"\"\"\nfrom catboost import CatBoostClassifier,Pool\n\ncat_features = [X_train.columns.get_loc(col) for col in cat_cols]\nprint(cat_features)\n\ntrain_x=Pool(data=X_train,label=y_train,cat_features=cat_features)\nvalid_x=Pool(data=X_valid,label=y_valid,cat_features=cat_features)\n\nparams = {'loss_function':'Logloss',\n          'learning_rate':0.03,\n          'depth':7,\n          'n_estimators':10000,\n          'eval_metric':'AUC',\n          'od_type': 'Iter',\n          'od_wait':1000,\n          'verbose':200,\n          'one_hot_max_size':0,\n          'class_weights':(1,3.4),\n          'random_state':99\n         }\n#Fit the random forest learner\ncb=CatBoostClassifier(**params)\ncb.fit(train_x,eval_set=valid_x,use_best_model=True,plot=True)\n\"\"\"\n# Simple Catboost model performs very well on the validation data. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '008eb6ef263803'}"}
{"id":"73023","text":"\"\"\"\nThis is my best private score kernel (0.99280),\nso I would like to share what I did.\nThe point is the method described in [Keras Learning Rate Finder](https:\/\/www.pyimagesearch.com\/2019\/08\/05\/keras-learning-rate-finder\/)\nto find effective leraning rate range for the model.\nI used the values in the found range to train the model.\n\n## Contents\n1. [Preparation](#Preparation)\n1. [Making Model](#MakingModel)\n1. [Data Augmentation](#DataAugmentation)\n1. [Finding Effective Learning Rate](#FindingEffectiveLearningRate)\n1. [Training](#Training)\n1. [Submit Prediction](#SubmitPrediction)\n1. [Reference](#Reference)\n\"\"\"\n\"\"\"\n<div id='Preparation'>\n## 1. Preparation\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n# https:\/\/keras.io\/getting-started\/faq\/#how-can-i-obtain-reproducible-results-using-keras-during-development\n# How can I obtain reproducible results using Keras during development?\nimport random as rn\nimport tensorflow as tf\n\nrand_seed = 53\n# maybe no effect, since this should be set before the program starts.\n%env PYTHONHASHSEED=0\nnp.random.seed(rand_seed)\nrn.seed(rand_seed)\n\ntf.config.threading.set_inter_op_parallelism_threads(1)\ntf.config.threading.set_intra_op_parallelism_threads(1)\ntf.random.set_seed(rand_seed)\ndef read_data(file_name):\n    file_path = '..\/input\/Kannada-MNIST\/' + file_name\n    data_df = pd.read_csv(file_path)\n    pixels_df = data_df.drop(columns='label')\n    pixels_array = pixels_df.to_numpy(dtype=np.uint8)\n    reshaped_pixels_array = pixels_array.reshape(-1, 28, 28, 1)\n    labels_array = data_df.label.values\n    return (reshaped_pixels_array, labels_array)\n\"\"\"\nFor [train_test_split](https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.model_selection.train_test_split.html),\nI specified the stratify option.\nThis ensures that the distribution of each splitted data becomes\nthe same as the one in the specified data.\nIn this case, train_test_split tries to split the whole data\ninto training and test with the same distribution of labels in the whole data.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX, y = read_data('train.csv')\nX_train, X_test, y_train, y_test = \\\n    train_test_split(X, y, test_size=0.1, random_state=rand_seed, stratify=y)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\ndef draw_image(im_array, subplot=(1, 1, 1)):\n    im = Image.fromarray(im_array.reshape(28, 28))\n    plt.subplot(*subplot)\n    plt.imshow(im, cmap='gray')\n    plt.axis(\"off\")\ndraw_image(X_train[0])\nplt.show()\nunique_y = np.unique(y_train)\nprint(unique_y)\nlabel_count = len(unique_y)\nprint(label_count)\n# TODO: Fix, xticks and bar positions are not aligned.\ndef draw_hist(x, title):\n    global label_count\n    plt.hist(x, bins=label_count, rwidth=0.8)\n    plt.title(title)\n    plt.xlabel('labels')\n    plt.ylabel('counts')\n    plt.xticks(np.arange(10))\n    plt.show()\ndraw_hist(y_train, \"Distributions of all train labels\")\ndraw_hist(y_test, \"Distributions of all test labels\")\n\"\"\"\n<div id='MakingModel'>\n## 2. Making Model\n\nFor a convolution block, I used \"Conv2D --> ReLU --> BatchNormalization\".\nI specified he_normal as the [kernel_initializer](https:\/\/keras.io\/initializers\/).\nWithout this, sometimes loss of the model became larger and larger and did not converged.\n\"\"\"\nfrom keras.layers import Conv2D, BatchNormalization\nfrom keras.initializers import he_normal\n\ndef make_conv_layer(filter_size, suffix, inputs):\n    x = Conv2D(\n        filter_size, kernel_size=(3, 3), padding='same', activation='relu',\n        kernel_initializer=he_normal(seed=rand_seed), name='conv_' + suffix)(inputs)\n    outputs = BatchNormalization(name='bn_' + suffix)(x)\n    return outputs\n\"\"\"\nThe model consists of the following blocks:\n1. Scaling by dividing 255.0.\n1. 3 Convolutions with filter size 64, then MaxPooling and SpatialDropout(0.25)\n1. 3 Convolutions with filter size 128, then MaxPooling and SpatialDropout(0.25)\n1. 3 Convolutions with filter size 256, then GlobalAveragePooling\n1. Dense with 256 units, then Dropout(0.25) and outputs with Dense(label_count).\n\nSome points are:\n* Scaling is done here, because:\n    * To do just once.\n    * To save memory.  Data type for image is unsigned integer (0..255) and its size is 1 byte. Dividing by floting point number 255.0 makes floating point result of 4 or 8 bytes. So dividing whole data comsumes a lot of memory.\n* [GlobalAveragePooling2D](https:\/\/keras.io\/layers\/pooling\/) is used\nto connect the last convolution block to the Dence.\nThis saves the number of parameters for the Dence and seems the performance is much the same.\n* sparse_categorical_crossentropy is used for the [loss function](https:\/\/keras.io\/losses\/).\nThis function accepts the label value directly, so one hot encoding is not necessary.\n\"\"\"\nfrom keras.layers import Input, Lambda, MaxPooling2D, SpatialDropout2D, Dense\nfrom keras.layers import GlobalAveragePooling2D, Dropout\nfrom keras.models import Model\n\ndef make_model():\n    inputs = Input(shape=(28, 28, 1), name=\"input\")\n    x = Lambda(lambda v: v \/ 255.0, name='scaling')(inputs)\n    \n    x = make_conv_layer(64, '1_1', x)\n    x = make_conv_layer(64, '1_2', x)\n    x = make_conv_layer(64, '1_3', x)\n    x = MaxPooling2D(pool_size=(2, 2), name=\"maxpool_1\")(x)\n    x = SpatialDropout2D(0.25, name='sp_dpout_1')(x)\n\n    x = make_conv_layer(128, '2_1', x)\n    x = make_conv_layer(128, '2_2', x)\n    x = make_conv_layer(128, '2_3', x)\n    x = MaxPooling2D(pool_size=(2, 2), name='maxpool_2')(x)\n    x = SpatialDropout2D(0.25, name='sp_dpout_2')(x)\n\n    x = make_conv_layer(256, '3_1', x)\n    x = make_conv_layer(256, '3_2', x)\n    x = make_conv_layer(256, '3_3', x)\n    x = GlobalAveragePooling2D(name='gblavgpool')(x)\n\n    x = Dense(256, activation='relu', name='dense')(x)\n    x = Dropout(0.25, name='dropout')(x)\n    outputs = Dense(label_count, activation='softmax', name='outputs')(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    model.compile(\n        optimizer='adam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'])\n    \n    return model\ntrain_model = make_model()\ntrain_model.summary()\n\"\"\"\n<div id='DataAugmentation'>\n## 3. Data Augmentation\n\nI used [ImageDataGenerator](https:\/\/keras.io\/preprocessing\/image\/)\nto make variations of the traing data.\nI drew heatmaps to check how the significant pixels are distributed\nin the original and generated images.\n\"\"\"\nimport seaborn as sns\n\ndef draw_sum_heatmap(X):\n    X_sum = np.sum(X, axis=0, dtype=np.float32) \/ 255.0\n    X_reshaped_sum = np.reshape(X_sum, (28, 28))\n    sns.heatmap(X_reshaped_sum)\n    plt.show()\ndraw_sum_heatmap(X)\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_image_generator = ImageDataGenerator(\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=10,\n    zoom_range=0.2,\n    fill_mode='constant',\n    cval=0,\n    data_format='channels_last')\ntest_image_generator = ImageDataGenerator()\n\"\"\"\nBy calling next(), batch_size number of images are generated.\nIn this case, it is 60,000. \n\"\"\"\nsample_image_flow = train_image_generator.flow(\n    X, y, batch_size=len(X), shuffle=False, seed=rand_seed)\nX_generated_sample, _ = next(sample_image_flow)\nprint(X_generated_sample.shape)\ndraw_sum_heatmap(X_generated_sample)\nbatch_size = 256\nsteps_per_epoch = (X_train.shape[0] + batch_size - 1) \/\/ batch_size\n\ntrain_image_flow = train_image_generator.flow(\n    X_train, y_train, batch_size=batch_size, shuffle=True, seed=rand_seed)\ntest_image_flow = test_image_generator.flow(\n    X_test, y_test, batch_size=batch_size, shuffle=True, seed=rand_seed)\n\nprint(\"batch_size: {0}\".format(batch_size))\nprint(\"steps_per_epoch: {0}\".format(steps_per_epoch))\n\"\"\"\n<div id='FindingEffectiveLearningRate'>\n## 4. Finding Effective Learning Rate\n\nI referred [Keras Learning Rate Finder](https:\/\/www.pyimagesearch.com\/2019\/08\/05\/keras-learning-rate-finder\/) to make this portion.\nThe idea is:\n* Sweep learning rate from far too small to far too large.\n* Monitor loss while sweeping.\n* The point where the loss becomes decreasing is the minimum available learning rate.\n* The point where the loss stops decreasing is the maximum available learning rate.\n\"\"\"\nfrom keras import backend as K\n\ndef get_lr(model):\n    return K.get_value(model.optimizer.lr)\n\ndef set_lr(model, lr):\n    K.set_value(model.optimizer.lr, lr)\ndef find_lr_on_batch_end(model, logs, lr_list, loss_list, lr_mult):\n    lr = get_lr(model)\n    lr_list.append(lr)\n    loss = logs['loss']\n    loss_list.append(loss)\n    \n    set_lr(model, lr * lr_mult)\nfind_lr_start_lr = 1e-10\nfind_lr_end_lr = 1.0\n\nfind_lr_epochs = 3\nfind_lr_total_batch_count = find_lr_epochs * steps_per_epoch\nfind_lr_lr_mult = (find_lr_end_lr \/ find_lr_start_lr) ** (1.0 \/ find_lr_total_batch_count)\n\nprint(\"find_lr_epochs: {0}\".format(find_lr_epochs))\nprint(\"find_lr_total_batch_count: {0}\".format(find_lr_total_batch_count))\nprint(\"find_lr_lr_mult: {0}\".format(find_lr_lr_mult))\nfrom keras.callbacks import LambdaCallback\n\nfind_lr_model = make_model()\nfind_lr_lr_list = []\nfind_lr_loss_list = []\n\nfind_lr_callback = LambdaCallback(\n    on_batch_end=lambda batch, logs: find_lr_on_batch_end(\n        find_lr_model, logs, find_lr_lr_list, find_lr_loss_list, find_lr_lr_mult))\nset_lr(find_lr_model, find_lr_start_lr)\nfind_lr_history = find_lr_model.fit_generator(\n    train_image_flow,\n    steps_per_epoch=steps_per_epoch,\n    epochs=find_lr_epochs,\n    validation_data=test_image_flow,\n    callbacks=[find_lr_callback],\n    verbose=2)\nplt.plot(find_lr_lr_list, find_lr_loss_list)\nplt.xscale('log')\nplt.ylim(0, 4)\nplt.title('Learning Rate vs Loss')\nplt.xlabel('Learning Rate (Log Scale)')\nplt.ylabel('Loss')\nplt.show()\n\"\"\"\n<div id='Training'>\n## 5. Training\n\n* I used 3 learning rates, maximum, medium, and minimum of the range\nfound in the previous step.\n* I specified the epoch explicitly for changing the learning rate.\nIt's simple.\nBy the loss and accuracy plots below,\nthey are improved at the point where the rate changed.\n* 150 epochs seems a bit too long, however sometimes might get a fantastic result,\nbecause the training step is not deterministic.\n* I chose the best model by using the validation accuracy.\n\"\"\"\nfrom keras.callbacks import LearningRateScheduler\n\ntrain_epochs = 150\n\ndef lr_schedule(epoch_index, current_lr):\n    if epoch_index == 0:\n        new_lr = 1e-3\n    elif epoch_index == 49:\n        new_lr = 3e-4\n    elif epoch_index == 99:\n        new_lr = 1e-4\n    else:\n        new_lr = current_lr\n\n    if new_lr != current_lr:\n        print(\n            \"Epoch {0}: Learning late changed from {1:.5f} to {2:.5f}\".format(\n            epoch_index + 1, current_lr, new_lr))\n    return new_lr\n\nlr_scheduler = LearningRateScheduler(lr_schedule, verbose=0)\nfrom keras.callbacks import ModelCheckpoint\n\nbest_model_file_name = \"best_model.hdf5\"\nmodel_check_point = ModelCheckpoint(\n    best_model_file_name, monitor='val_sparse_categorical_accuracy', mode='max',\n    verbose=0, save_best_only=True, save_weights_only=True, period=1)\ntrain_history = train_model.fit_generator(\n    train_image_flow,\n    steps_per_epoch=steps_per_epoch,\n    epochs=train_epochs,\n    validation_data=test_image_flow,\n    callbacks=[lr_scheduler, model_check_point],\n    verbose=2)\nbest_train_model = make_model()\nbest_train_model.load_weights(best_model_file_name)\ntrain_result = best_train_model.evaluate(X_test, y_test)\nprint(train_result)\ndef draw_loss(history, ylim):\n    plt.figure(figsize=(12, 4))\n    plt.plot(history.history['loss'], label='loss')\n    plt.plot(history.history['val_loss'], label='val_loss')\n    plt.title('Loss and Val Loss')\n    plt.xlabel('epochs')\n    plt.ylabel('loss')\n    plt.ylim(*ylim)\n    plt.legend()\n    plt.show()\ndraw_loss(train_history, (0.0, 0.05))\ndef draw_acc(history, ylim):\n    plt.figure(figsize=(12, 4))\n    plt.plot(history.history['sparse_categorical_accuracy'], label='acc')\n    plt.plot(history.history['val_sparse_categorical_accuracy'], label='val_acc')\n    plt.title('Acc and Val Acc')\n    plt.xlabel('epochs')\n    plt.ylabel('accuracy')\n    plt.ylim(*ylim)\n    plt.legend()\n    plt.show()\ndraw_acc(train_history, (0.99, 1.0))\n\"\"\"\n<div id='SubmitPrediction'>\n## 6. Submit Prediction\n\"\"\"\ntest_df = pd.read_csv('..\/input\/Kannada-MNIST\/test.csv')\ntest_df.head()\ntest_pixels_df = test_df.drop(columns='id')\ntest_pixels_array = test_pixels_df.to_numpy(dtype=np.uint8)\ntest_images = test_pixels_array.reshape(-1, 28, 28, 1)\nprint(test_images.shape)\ndraw_image(test_images[0])\nmodel_preds = best_train_model.predict(test_images)\nprint(model_preds.shape)\npred_labels = np.argmax(model_preds, axis=1)\ndraw_hist(pred_labels, \"Distributions of prediction labels\")\nsample_submission_df = pd.read_csv('..\/input\/Kannada-MNIST\/sample_submission.csv')\nsample_submission_df.head()\nsample_submission_df['label'] = pred_labels\nsample_submission_df.head()\nsample_submission_df.to_csv('submission.csv', index=False)\nprint('Done!')\n\"\"\"\n<div id='Reference'>\n## 7. Reference\n\nI referred the following documents and kernels.\nMany thanks to the authors of them.\n\n* [How to use pre-trained models in kernels on Kaggle](https:\/\/www.kaggle.com\/paultimothymooney\/how-to-use-pre-trained-models-in-kernels-on-kaggle) -- at first, I planed to use transfer learning.\n* [Indian way to learn CNN](https:\/\/www.kaggle.com\/shahules\/indian-way-to-learn-cnn) -- referred for reading and handling data.\n* [Keras Learning Rate Finder](https:\/\/www.pyimagesearch.com\/2019\/08\/05\/keras-learning-rate-finder\/) -- so I specified learning rate with confidence.\n* [Cyclical Learning Rates with Keras and Deep Learning](https:\/\/www.pyimagesearch.com\/2019\/07\/29\/cyclical-learning-rates-with-keras-and-deep-learning\/) -- I tried.\n* [An implementation of DropConnect Layer in Keras](https:\/\/github.com\/andry9454\/KerasDropconnect),\n[Fork of Keras CNN - DropConnect](https:\/\/www.kaggle.com\/naraque\/fork-of-keras-cnn-dropconnect) -- I tried too.\n* [Deep Dive in KannadaMnist with tfkeras](https:\/\/www.kaggle.com\/xiejialun\/deep-dive-in-kannadamnist-with-tfkeras) -- \"Symmetric Cross Entropy\" used in this kernel is interesting and I tried.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8669edb9b4d1d3'}"}
{"id":"112810","text":"%config IPCompleter.greedy=True\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndata = pd.read_csv(\"..\/input\/daily-inmates-in-custody.csv\")\ndata.head()\ndata.columns\n\"\"\"\n# Look at the distribution of ages\n\"\"\"\nplt.hist(\n    data.loc[~data['AGE'].isna(),'AGE']\n    , bins=list(range(16,96,5))\n)\nplt.xlabel(\"Age\")\nplt.ylabel(\"Count\")\nplt.show()\n\"\"\"\n# Look at distribution of gang affiliation\n\"\"\"\ngang_affiliated = data.SRG_FLG.map(dict(N=0,Y=1))\nplt.hist(gang_affiliated)\nplt.xlabel(\"Gang Affiliated\")\nplt.ylabel(\"Count\")\nplt.show()\n\"\"\"\n# Look at the ages of gangsters vs non-gangsters\n\"\"\"\nplt.hist(\n    [\n        data.loc[data.SRG_FLG == 'Y', 'AGE']\n        , data.loc[data.SRG_FLG == 'N', 'AGE']\n    ]\n    , bins=list(range(16,96,5))\n)\nplt.legend(['Ganster', 'Non-Gangster'])\nplt.xlabel(\"Age\")\nplt.ylabel(\"Count\")\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'cf41e640727e61'}"}
{"id":"11022","text":"\"\"\"\nForked from this nice kernel https:\/\/www.kaggle.com\/shahules\/indian-way-to-learn-cnn\n\"\"\"\nimport pandas as pd\nimport numpy as  np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization\nfrom keras.optimizers import RMSprop,Adam\nfrom keras.callbacks import ReduceLROnPlateau\n\"\"\"\n### Loading data\n\"\"\"\ntrain=pd.read_csv('..\/input\/Kannada-MNIST\/train.csv')\ntest=pd.read_csv('..\/input\/Kannada-MNIST\/test.csv')\nsample_sub=pd.read_csv('..\/input\/Kannada-MNIST\/sample_submission.csv')\n\"\"\"\nBefore jumping to all complex stuff about Convolutions and all,we will simply understand our data.We will learn and gain basic understanding about this data.\n\"\"\"\nprint('The Train  dataset has {} rows and {} columns'.format(train.shape[0],train.shape[1]))\nprint('The Test  dataset has {} rows and {} columns'.format(test.shape[0],test.shape[1]))\n\ntrain.head(3)\ntest.head(3)\ntest=test.drop('id',axis=1)\n\n\"\"\"\n### Checking Target class distribution..\n\n\"\"\"\ny=train.label.value_counts()\nsns.barplot(y.index,y)\n\"\"\"\nNow we can see that all of the classes has equal distribution.There are 6000 examples of each numbers in kannada in the the training dataset.Cool !\n\"\"\"\n\"\"\"\n## Data preparation <a id='2'><\/a>\n\"\"\"\nX_train=train.drop('label',axis=1)\nY_train=train.label\n\"\"\"\n### Normalize Pixel Values\n\nFor most image data, the pixel values are integers with values between 0 and 255.\n\nNeural networks process inputs using small weight values, and inputs with large integer values can disrupt or slow down the learning process. As such it is good practice to normalize the pixel values so that each pixel value has a value between 0 and 1.\n\nIt is valid for images to have pixel values in the range 0-1 and images can be viewed normally.\n\nThis can be achieved by dividing all pixels values by the largest pixel value; that is 255. This is performed across all channels, regardless of the actual range of pixel values that are present in the image.\n\"\"\"\nX_train=X_train\/255\ntest=test\/255\n\"\"\"\n### Reshape\n\"\"\"\nX_train=X_train.values.reshape(-1,28,28,1)\ntest=test.values.reshape(-1,28,28,1)\nprint('The shape of train set now is',X_train.shape)\nprint('The shape of test set now is',test.shape)\n\n\"\"\"\nAll Set,We have our data reshape into 60000 examples of height 28 and width 28 and 1 channel.\n\"\"\"\n\"\"\"\n### Splitting train and test\n\"\"\"\n\"\"\"\nNow we will split out training data into train and validation data.15percent of the training data will be used for validation purpose.\n\"\"\"\nX_train,X_test,y_train,y_test=train_test_split(X_train,Y_train,random_state=42,test_size=0.15)\nplt.imshow(X_train[0][:,:,0])\n\"\"\"\nIt's Nine in Kannada\n\n\"\"\"\n\"\"\"\n### More data !\n\"\"\"\n\"\"\"\nIn order to avoid overfitting problem, we need to expand artificially our handwritten digit dataset. We can make your existing dataset even larger. The idea is to alter the training data with small transformations to reproduce the variations occuring when someone is writing a digit.\n\nFor example, the number is not centered The scale is not the same (some who write with big\/small numbers) The image is rotated...\n\nApproaches that alter the training data in ways that change the array representation while keeping the label the same are known as data augmentation techniques. Some popular augmentations people use are grayscales, horizontal flips, vertical flips, random crops, color jitters, translations, rotations, and much more.\n\nBy applying just a couple of these transformations to our training data, we can easily double or triple the number of training examples and create a very robust model.\n\n\n\"\"\"\ndatagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)\n\n\"\"\"\nFor the data augmentation, i choosed to :\n\n   - Randomly rotate some training images by 10 degrees\n   - Randomly Zoom by 10% some training images\n   - Randomly shift images horizontally by 10% of the width\n   - Randomly shift images vertically by 10% of the height\n\nI did not apply a vertical_flip nor horizontal_flip since it could have lead to misclassify symetrical numbers such as 6 and 9.\n\"\"\"\n\"\"\"\n## Modelling <a id='4' ><\/a>\n\"\"\"\nmodel = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization(momentum=.15))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization(momentum=0.15))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(BatchNormalization(momentum=.15))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1))\nmodel.summary()\noptimizer=Adam(learning_rate=0.001,beta_1=0.9,beta_2=0.999)\nimport keras.backend as K\ndef Acc(y_true, y_pred, from_logits=False, label_smoothing=0):\n    y_pred=K.round(y_pred)\n    return K.mean(K.cast(K.equal(y_true,y_pred),y_pred.dtype))\n\nmodel.compile(optimizer=optimizer,loss='mae',metrics=['accuracy',Acc])\n\"\"\"\n### Learning rate reduction\n\"\"\"\n# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n\"\"\"\n### Fitting our model <a id='5'><\/a>\n\"\"\"\nepochs=40 \nbatch_size=64\n# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train,y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_test,y_test),\n                              verbose = 1, steps_per_epoch=X_train.shape[0] \/\/ batch_size\n                              , callbacks=[learning_rate_reduction])\n\"\"\"\n## Evaluating our approach <a id='6'><\/a>\n\"\"\"\nfig,ax=plt.subplots(2,1)\nfig.set\nx=range(1,1+epochs)\nax[0].plot(x,history.history['loss'],color='red')\nax[0].plot(x,history.history['val_loss'],color='blue')\n\nax[1].plot(x,history.history['accuracy'],color='red')\nax[1].plot(x,history.history['val_accuracy'],color='blue')\nax[0].legend(['trainng loss','validation loss'])\nax[1].legend(['trainng acc','validation acc'])\nplt.xlabel('Number of epochs')\nplt.ylabel('accuracy')\n\n\"\"\"\nWe have plotted the performance of our model.We can see the number of epochs in the X axis and change in model performance in Y axis.\n\"\"\"\ny_pre_test=model.predict(X_test)\ny_pre_test=np.round(y_pre_test)\ny_pre_test[y_pre_test>9]=9\ny_pre_test[y_pre_test<0]=0\ny_pre_test.shape\nprint(\"Correct predictions\",np.sum((y_pre_test.flat==y_test).astype(int)))\nprint(\"Incorrect predictions\",np.sum((y_pre_test.flat!=y_test).astype(int)))\n\"\"\"\n## Making a Submission <a id='7'><\/a>\n\n\"\"\"\ntest=pd.read_csv('..\/input\/Kannada-MNIST\/test.csv')\ntest_id=test.id\ntest=test.drop('id',axis=1)\ntest=test\/255\ntest=test.values.reshape(-1,28,28,1)\n\ntest.shape\n\"\"\"\nWe will make our prediction using our CNN model.\n\"\"\"\ny_pre=model.predict(test)     ##making prediction\ny_pre=np.round(y_pre).astype(int) ##changing the prediction intro labels\ny_pre[y_pre>9]=9\ny_pre[y_pre<0]=0\nsample_sub['label']=y_pre.flat\nsample_sub.to_csv('submission.csv',index=False)\n\nsample_sub.head()\n\"\"\"\nThings to try:\n1. Different Thresholds\n2. Other loss fuctions\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '143afc7c6152b7'}"}
{"id":"72994","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nsns.set_style('whitegrid')\nplt.figure(figsize=(6,5))\nx=range(1,8)\ny= [2,3,4,1,0,7,6]\nplt.plot(x,y)\nplt.title('Lineplot')\nplt.xlabel(\"Numbers\")\nplt.ylabel(\"Frequency\")\nplt.show()\ncars=pd.read_csv(\"..\/input\/praactice-data\/mt1cars.csv\")\ncars.head()\ncars.rename(columns={'Unnamed: 0': 'cars_name'}, inplace=True)\nmpg=cars['mpg']\nmpg.plot()\ndf= cars[['cyl','wt','mpg']]\ndf.plot()\nplt.bar(x,y)\nplt.figure(figsize=(8,7))\nmpg.plot(kind='bar', color = 'g')\nplt.figure(figsize=(8,7))\nmpg.plot(kind='barh', color = 'r')\nx=[1,2,3,4,5]\nplt.pie(x)\nplt.show()\nplt.savefig('pie_chart.jpeg')\nplt.show()\n%pwd\nx=range(1,10)\ny= [1,2,8,9,3,4,6,3,8]\nfig, ax = plt.subplots(figsize=(6,6))\nax.plot(x,y)\nfig, ax = plt.subplots(figsize=(6,6))\nax.set_xlim([1,9])\nax.set_ylim([0,5])\nax.set_xticks([0,1,2,3,4,5,6,7,8,9,10])\nax.set_yticks([0,2,4,6,8,10])\nax.plot(x,y)\nfig=plt.figure(figsize=(10,6))\nfig, (ax1, ax2) = plt.subplots(1,2)\nax1.plot(x)\nax2.plot(x,y)\nplt.bar(x,y)\nwide=[0.5, 0.5, 0.5, 0.7, 0.7, 0.5, 0.5, 0.7, 0.8]\ncolor=['salmon']\nplt.bar(x,y, width=wide, color=color, align = 'center')\ndf= cars[['cyl','wt','mpg']]\ncolor_t=['darkgray','lightsalmon', 'powderblue']\ndf.plot(color=color_t)\nz = [2,4,6,8,10]\ncolor_theme = ['#A9A9A9', '#FFA07A','#B0E0E6','#FFE4C4','#BDB76B']\nplt.pie(z, colors=color_theme)\nplt.show()\nx1=range(0,10)\ny1=[10,9,8,7,6,5,4,3,2,1]\nplt.plot(x,y, ls='steps', lw=10)\nplt.plot(x1,y1, ls='--', lw=5)\nplt.plot(x,y, marker='1', mew=20)\nplt.plot(x1,y1, marker='+', mew=15)\n\"\"\"\n# Label and annotate\n\"\"\"\nx2=range(1,10)\ny2=(1,2,3,4,5,7,8,9,10)\nplt.bar(x,y)\nplt.xlabel('x_axis')\nplt.ylabel('y_axis')\nplt.show()\nz2 = [2,3,4,5,6]\nfruit=['fig', 'mango','apple', 'coco', 'tamarind']\nplt.pie(z2, labels=fruit)\n\nfig, ax = plt.subplots(1,1, figsize=(15,10))\nax.set_xticks(range(32))\nmpg.plot()\nax.set_xticklabels(cars.cars_name , rotation = 60, fontsize= 'medium')\nax.set_title(\"mpg of cars\")\nax.set_xlabel('car names')\nax.set_ylabel('m-p-g')\nax.legend(loc='best')\nplt.show()\nplt.pie(z2)\nplt.legend(fruit, loc='best')\nplt.show()\n\"\"\"\n# Annotation\n\"\"\"\nmpg.max()\nfig, ax = plt.subplots(1,1, figsize=(15,10))\nmpg.plot()\nax.set_ylim([0,45])\nax.set_title(\"mpg of cars\")\nax.set_xlabel('car names')\nax.set_ylabel('m-p-g')\nax.annotate('Toyota Corolla', xy=(19,33.9), xytext=(21,35), arrowprops=dict(facecolor='black', shrink = 0.05))\nmpg.plot(kind='hist')\nplt.hist(mpg)\nplt.show()\nsns.distplot(mpg)\ncars.plot(kind='scatter', x= 'hp', y ='mpg', color ='g', s=150 )\nsns.regplot(x='hp', y = 'mpg', data=cars)\nsns.pairplot(cars)\ncars_df=cars[['mpg', 'disp', 'hp', 'wt']]\ncars_df.values\ncars_target= cars[['am']]\ncars_target.values\ntarget_names=[0,1]\nfrom pandas import Series\ncars_df['group']=pd.Series(cars_target, dtype='category')\nsns.pairplot(cars_df, hue='group', palette='hls')\ncars.boxplot(column='mpg', by='am')\ncars.boxplot(column='wt', by='am')\nsns.boxplot(x='am', y='mpg', data=cars)","meta":"{'source': 'AI4Code', 'id': '865ed617a2774b'}"}
{"id":"20215","text":"\"\"\"\n# Suicide Rates Overview 1985 to 2016\n> Compares socio-economic info with suicide rates by year and country\n\"\"\"\n\"\"\"\nThis is a simple EDA to explore the data and extract some relationship with them and the actual world that we know. I want to bring attention to a visual analyzing using different plot in order to find key points inside data.\n\"\"\"\n\"\"\"\n## Informations\n- Countries in the World: **195** ([source](https:\/\/www.worldometers.info\/geography\/how-many-countries-are-there-in-the-world\/))\n\n### Generations\n- Gen Z, iGen, or Centennials: Born 1996 \u2013 Today\n- Millennials or Gen Y: Born 1977 \u2013 1995\n- Generation X: Born 1965 \u2013 1976\n- Baby Boomers: Born 1946 \u2013 1964\n- Silent Generation \/ Traditionalists: Born 1945 - 1925\n- G.I. Generation: Born 1900 - 1924\n\n### Life indexes\n- **HDI per year**: is a statistic composite index of life expectancy, education, and per capita income indicators, which are used to rank countries into four tiers of human development. \n- **GDP**: is a monetary measure of the market value of all the final goods and services produced in a specific time period.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.gridspec as gridspec\nimport matplotlib.style as style\n\nstyle.use('ggplot')\n\nID = 'id'\nTARGET = 'target'\nNFOLDS = 7\nSEED = 18\nNROWS = None\nDATA_DIR = '..\/input\/suicide-rates-overview-1985-to-2016'\n\nDATA_FILE = f'{DATA_DIR}\/master.csv'\ndf = pd.read_csv(DATA_FILE)\ndf.sample(8)\ndef tableSummary(df):\n    from scipy import stats\n    print(f'Dataset Shape: {df.shape}')\n    summary = pd.DataFrame(df.dtypes,columns=['dtypes'])\n    summary = summary.reset_index()\n    summary['Name'] = summary['index']\n    summary = summary[['Name','dtypes']]\n    summary['Missing'] = df.isnull().sum().values    \n    summary['Uniques'] = df.nunique().values\n    summary['First Value'] = df.loc[0].values\n    summary['Second Value'] = df.loc[1].values\n    summary['Third Value'] = df.loc[2].values\n\n    for name in summary['Name'].value_counts().index:\n        summary.loc[summary['Name'] == name, 'Entropy'] = round(stats.entropy(df[name].value_counts(normalize=True), base=2),2) \n\n    return summary\n\"\"\"\n## Features and cleaning\n\"\"\"\n\"\"\"\nGenerations order by years.\n\"\"\"\ngenerations_order = ['G.I. Generation', 'Silent', 'Boomers', 'Generation X', 'Millenials', 'Generation Z']\ndf.rename(columns={\n    ' gdp_for_year ($) ': 'gdp_for_year',\n    'gdp_per_capita ($)': 'gdp_per_capita',\n    'suicides\/100k pop': 'suicides\/100k',\n}, inplace=True)\n# Drop country-year because is useless\n# Drop HDI because too many missing values\ndf = df.drop(['country-year', 'HDI for year'], axis=1)\n\ndf['country'] = df['country'].astype('category')\ndf['sex'] = df['sex'].astype('category')\ndf['age'] = df['age'].astype('category')\ndf['generation'] = df['generation'].astype('category')\n\n# Convert GDP to numerical value\ndf['gdp_for_year'] = df['gdp_for_year'].apply(lambda x: int(x.replace(',', ''))).astype('int64')\ntableSummary(df)\n# Data cleaning took from https:\/\/www.kaggle.com\/fredzanella\/should-we-care-about-money-an-eda-on-suicide\n# Thanks fredzanella for the amazing work!\n\nagg_dict = { 'country':'nunique', 'age':'nunique',\n             'population':'sum', 'suicides_no':'sum',\n             'suicides\/100k':'mean' }\n\nboth_ends = df.query('year < 1988 | year > 2013')\n\nboth_ends = both_ends[['year', 'country',\n                       'age', 'population',\n                       'suicides_no',\n                       'suicides\/100k']].groupby('year').agg(agg_dict)\nboth_ends\n# Remove 2016 for data inconsistency\ndf = df.query('year != 2016')\n\"\"\"\n## EDA\n\n### Sucides rate by year\n\"\"\"\naggr = { 'population':'sum', 'suicides_no':'sum' }\n\ndf_group_year = df.groupby(['year']).agg(aggr).reset_index()\ndf_group_year['suicides\/100k'] = 100000 * df_group_year['suicides_no'] \/ df_group_year['population']\ndf_group_year.head()\nfig = plt.figure(figsize = (16, 8))\nsns.barplot(x='year', y='suicides_no', data=df_group_year, palette='rocket')\nfig.suptitle('Suicides rate by Year', fontsize=18)\nplt.show()\nfig, ax = plt.subplots(figsize=(16,8))\ndf_group_year.plot(x='year', y='suicides\/100k', ax=ax)\nfig.suptitle('Suicides rate over 100k by Year', fontsize=18)\nplt.show()\n\"\"\"\n### Population vs number of suicides trough history\n\"\"\"\nfig, ax1 = plt.subplots(1, 1, figsize=(16, 8))\nsns.lineplot(data=df_group_year, y='population', x='year', ax=ax1, label='Population')\nax1.set_ylim(1e9, 2.6e9)\nax1.legend(bbox_to_anchor=(1.112, 0.1))\n\nax2 = plt.twinx()\nsns.lineplot(data=df_group_year, y='suicides_no', x='year', ax=ax2, color='C3', label='Suicides')\nax2.set_ylim(1e5, 2.6e5)\nax2.legend(bbox_to_anchor=(1.1, 0.21))\n\nplt.title('Population vs number of suicides by year', fontsize=18)\nplt.show()\n\"\"\"\n### Suicides division by sex\n\"\"\"\n\"\"\"\n> In other western countries, males are also much more likely to die by suicide than females (usually by a factor of 3\u20134:1). It was the 8th leading cause of death for males, and 19th leading cause of death for females. Excess male mortality from suicide is lower in non-Western where as of 2015 in China (about one fifth of world population) and seven more countries it is absent, with females more likely to die by suicide than males by a factor of 1.3\u20131.6.\n[Source Wikipedia](https:\/\/en.wikipedia.org\/wiki\/Epidemiology_of_suicide)\n\"\"\"\ndf_group_sex = df.groupby(['sex']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_sex.head()\nfig = plt.figure(figsize = (8, 6))\nsns.barplot(x='sex', y='suicides_no', data=df_group_sex, palette='rocket')\nfig.suptitle('Suicides rate by Sex', fontsize=18)\nplt.show()\ndf_group_year_sex = df.groupby(['year', 'sex']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_year_sex.head()\nfig = plt.figure(figsize = (16, 8))\nsns.barplot(x='year', y='suicides_no', data=df_group_year_sex, hue='sex', palette='rocket')\nfig.suptitle('Suicides rate by Year', fontsize=18)\nplt.show()\n\"\"\"\n**China is not available as Country :(**\n\"\"\"\ndf_jp = df[df['country'] == 'Japan']\ndf_fr = df[df['country'] == 'France']\ndf_mix1 = df_jp.groupby(['sex']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_mix1['country'] = 'Japan'\ndf_mix2 = df_fr.groupby(['sex']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_mix2['country'] = 'France'\n\ndf_mix = pd.concat([df_mix1, df_mix2])\ndf_mix\nfig = plt.figure(figsize = (8, 6))\nsns.barplot(x='country', y='suicides_no', data=df_mix, hue='sex', palette='rocket')\nfig.suptitle('Suicides rate by Sex - Japan vs France', fontsize=18)\nplt.show()\n\"\"\"\n### Suicides by country\n\"\"\"\ndf_group_country = df.groupby(['country']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_country.head()\ntop_countries = df_group_country.sort_values('suicides_no', ascending=False)[:20]\n\nfig = plt.figure(figsize = (16, 8))\ng = sns.barplot(x='country', y='suicides_no', data=top_countries, order=top_countries['country'], palette='rocket')\nfig.suptitle('Suicides rate by Country - top 20', fontsize=18)\ng.set_xticklabels(g.get_xticklabels(), rotation=45)\nplt.show()\n\"\"\"\n### Suicides by country with population\n\"\"\"\ndf_group_country_p = df.groupby(['country']).agg({ 'suicides\/100k': 'mean' }).reset_index()\ndf_group_country_p.head()\ntop_countries = df_group_country_p.sort_values('suicides\/100k', ascending=False)[:20]\n\nfig = plt.figure(figsize = (16, 8))\ng = sns.barplot(x='country', y='suicides\/100k', data=top_countries, order=top_countries['country'], palette='rocket')\nfig.suptitle('Suicides rate over 100k citizen - top 20', fontsize=18)\ng.set_xticklabels(g.get_xticklabels(), rotation=45)\nplt.show()\n\"\"\"\nWe could also analyze the top 20 countries with **lowest suicides ratio**, but we should pay attention to the quantity of data available for each of them. If a country have data for a single year only, should not be compared with the others.\n\"\"\"\nbottom_countries = df_group_country_p.sort_values('suicides\/100k', ascending=True)\nbottom_countries.head(10)\n\"\"\"\nWe can calculate the number of *year* occurrencies for each country.\n\"\"\"\ncountry_occ = []\n\nfor country in df_group_country_p['country']:\n    years = df[df['country'] == country]['year'].nunique()\n    country_occ.append({\n        'country': country,\n        'year_no': years\n    })\n\ndf_year_country = pd.DataFrame(country_occ)\ndf_year_country.sample(8)\nprint('Mean occurrences for each country:', df_year_country['year_no'].mean())\n\"\"\"\nCountries with occurrences less thant 15\n\"\"\"\ndf_year_country.sort_values('year_no', ascending=True).query('year_no < 15')\n\"\"\"\nNow we could filter countries eliminating irrelevant ones.\n\"\"\"\ndf_gcp = df_group_country_p\ndf_ycfiltered = df_year_country.query('year_no >= 15')\nbottom_countries = df_gcp[df_gcp['country'].isin(df_ycfiltered['country'])].sort_values('suicides\/100k', ascending=True)[:15]\n\nfig = plt.figure(figsize = (16, 8))\ng = sns.barplot(x='country', y='suicides\/100k', data=bottom_countries, order=bottom_countries['country'], palette='rocket')\nfig.suptitle('Suicides rate over 100k citizen - bottom 15 (filtered)', fontsize=18)\ng.set_xticklabels(g.get_xticklabels(), rotation=45)\nplt.show()\n\"\"\"\n### Suicides rate by year\/generation\n\"\"\"\ndf_group_year_gen = df.groupby(['year', 'generation']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_year_gen['suicides_no'].fillna(0, inplace=True)\ndf_group_year_gen['suicides_no'] = df_group_year_gen['suicides_no'].astype('int64')\ndf_group_year_gen.head(10)\ngrid = gridspec.GridSpec(30, 2)\nfig = plt.figure(figsize=(20, 150))\nfig.subplots_adjust(hspace=0.4, wspace=0.3)\n\nmin_year = min(df['year'])\nmax_year = max(df['year'])\n\nfor n, year in enumerate(range(min_year, max_year + 1)):\n    df_y = df_group_year_gen[df_group_year_gen['year'] == year]\n    ax = plt.subplot(grid[n])\n    sns.barplot(x='generation', y='suicides_no', data=df_y, palette='rocket', order=generations_order)\n    ax.set_title(f'Suicides rate by Generation - {year}', fontsize=16)\n\nplt.show()\n\"\"\"\n### Total suicides by generation\n\"\"\"\ndf_group_gen = df.groupby(['generation']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_gen\nrocketPalette = sns.color_palette('rocket', n_colors=8)\n\npatches, texts, autotexts = plt.pie(df_group_gen['suicides_no'],\n                                    colors=rocketPalette,\n                                    labels=df_group_gen['generation'],\n                                    autopct='%1.1f%%',\n                                    startangle=90)\nplt.title('Division of suicides by Generation', fontsize=20, y=1.05)\nfor text in texts:\n    text.set_fontsize(12)\nfor autotext in autotexts:\n    autotext.set_color('white')\n    autotext.set_fontsize(12)\nplt.axis('equal')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### Suicides by age\n\"\"\"\ndf_group_age = df.groupby(['age']).agg({ 'suicides_no': 'sum' }).reset_index()\ndf_group_age\nrocketPalette = sns.color_palette('rocket', n_colors=8)\n\npatches, texts, autotexts = plt.pie(df_group_age['suicides_no'],\n                                    colors=rocketPalette,\n                                    labels=df_group_age['age'],\n                                    autopct='%1.1f%%',\n                                    startangle=90)\nplt.title('Division of suicides by Age', fontsize=20, y=1.05)\nfor text in texts:\n    text.set_fontsize(12)\nfor autotext in autotexts:\n    autotext.set_color('white')\n    autotext.set_fontsize(12)\nplt.axis('equal')\nplt.tight_layout()\nplt.show()\n\"\"\"\n### GDP - suicides relationship\n\"\"\"\nsns.jointplot(x='suicides_no', y='gdp_per_capita', data=df)\nplt.suptitle('Relation GDP per capita with Suicides number', fontsize=18, y=1.05)\nplt.show()\n\"\"\"\n### Analysis Russian Federation - USA\n\"\"\"\ndf_ru = df[df['country'] == 'Russian Federation']\ndf_us = df[df['country'] == 'United States']\ndf_ru_gdp = df_ru.groupby(['year']).agg({ 'suicides_no': 'sum', 'gdp_for_year': 'mean' }).reset_index()\n\nsns.jointplot(x='suicides_no', y='gdp_for_year', data=df_ru_gdp, kind='reg')\nplt.suptitle('Relation GDP for year with Suicides number - Russian Federation', fontsize=18, y=1.05)\nplt.show()\ndf_us_gdp = df_us.groupby(['year']).agg({ 'suicides_no': 'sum', 'gdp_for_year': 'mean' }).reset_index()\n\nsns.jointplot(x='suicides_no', y='gdp_for_year', data=df_us_gdp, kind='reg')\nplt.suptitle('Relation GDP for year with Suicides number - USA', fontsize=18, y=1.05)\nplt.show()\n\"\"\"\n**Is this an evidence of the [Easterlin paradox](https:\/\/en.wikipedia.org\/wiki\/Easterlin_paradox)?** We could discuss the results in the comments.\n\"\"\"\n\"\"\"\n## Thanks for reading!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '24fc8062a120c9'}"}
{"id":"94003","text":"# 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 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\n\"\"\"\nLets assume we have continous value y form space (-inf, + inf) and we wannt to convert it to discrete  n states, we want to split ininite area to equal ranges  it means that probability od each state is the same.\n\n(-inf, + inf) ---> {x1,x2,x3,...,xn}\n\nWe can interprete continous value as number of rotation around point (0,0).\n\nExample:\n7.2 - means 7.2 rotation in clockwise direction\n-3.2 -means 3.2 rotation in counter-clockwise direction \n\nNow we san split circle to n - states, for example:\naction 0 - 'up' part 0\naction 1 - 'left' part 1\naction 2 - 'down' part 2\naction 3 - 'right' part 3\n\n\"\"\"\n#lets try to convert y value for n=4 equal states\ny=6.8\nn=4\ny_rest=y%1\nprint('y_rest=',y_rest)\npart_size=1\/n\npart_number=y_rest\/\/part_size\nprint('part_number=',part_number)\n\n#write as function\n\ndef continous2discrete(y_con,n):\n    y_rest=y_con%1\n    part_size=1\/n\n    part_number=y_rest\/\/part_size\n    return int(part_number)\naction=continous2discrete(-1.13,n=6)\nprint('action=',action)","meta":"{'source': 'AI4Code', 'id': 'ac87c06061fbba'}"}
{"id":"58879","text":"# 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\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\nimport pandas as pd \nimport numpy as np \nimport seaborn as sns \nimport matplotlib.pyplot as plt \n\ndf=pd.read_csv('\/kaggle\/input\/housesalesprediction\/kc_house_data.csv')\ndf\ndf.head(5)\ndf.info()\ndf.describe().transpose()\ndf.isnull().sum()\n\"\"\"\n\"\"\"\n As we can see that there are no null data entry \n \n\n## The Data(insight )\n\n\n#### Feature Columns\n \n* id - Unique ID for each home sold\n* date - Date of the home sale\n* price - Price of each home sold\n* bedrooms - Number of bedrooms\n* bathrooms - Number of bathrooms, where .5 accounts for a room with a toilet but no shower\n* sqft_living - Square footage of the apartments interior living space\n* sqft_lot - Square footage of the land space\n* floors - Number of floors\n* waterfront - A dummy variable for whether the apartment was overlooking the waterfront or not\n* view - An index from 0 to 4 of how good the view of the property was\n* condition - An index from 1 to 5 on the condition of the apartment,\n* grade - An index from 1 to 13, where 1-3 falls short of building construction and design, 7 has an average level of construction and design, and 11-13 have a high quality level of construction and design.\n* sqft_above - The square footage of the interior housing space that is above ground level\n* sqft_basement - The square footage of the interior housing space that is below ground level\n* yr_built - The year the house was initially built\n* yr_renovated - The year of the house\u2019s last renovation\n* zipcode - What zipcode area the house is in\n* lat - Lattitude\n* long - Longitude\n* sqft_living15 - The square footage of interior housing living space for the nearest 15 neighbors\n* sqft_lot15 - The square footage of the land lots of the nearest 15 neighbors\n\n\"\"\"\n\"\"\"\n\"\"\"\n**Exploratory data analysis **\n\"\"\"\nplt.figure(figsize=(12,12),edgecolor='yellow')\nsns.distplot(df['price'])\nsns.countplot(df['bedrooms'])\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='price',y='sqft_living',data=df)\nsns.boxplot(x='bedrooms',y='price',data=df)\n\"\"\"\n**Geographical Properties****\n\"\"\"\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='price',y='long',data=df)\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='price',y='lat',data=df)\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='long',y='lat',data=df,hue='price')\ndf.sort_values('price',ascending=False).head(20)\nlen(df)*(0.01)\nnon_top_1_perc = df.sort_values('price',ascending=False).iloc[216:]\nnon_top_1_perc\nplt.figure(figsize=(12,8))\nsns.scatterplot(x='long',y='lat',\n                data=non_top_1_perc,hue='price',\n                palette='RdYlGn',edgecolor=None,alpha=0.2)\n\"\"\"\n**OTHER FEATURES **\n\"\"\"\nsns.boxplot(x='waterfront',y='price',data=df)\n\"\"\"\n**WORKING WITH FEATURE DATA **\n\"\"\"\ndf.head()\ndf.info()\n\"\"\"\n**here we dont need the id col becuase we can use the predefined index as a way to act as the primary key of the data  **\n\"\"\"\ndf.drop(['id'],axis=1,inplace=True)\ndf.head(5)\n\"\"\"\n**Feature Engineering from date**\n\"\"\"\ndf['date'] = pd.to_datetime(df['date'])\ndf['month'] = df['date'].apply(lambda date:date.month)\ndf['year'] = df['date'].apply(lambda date:date.year)\nsns.boxplot(x='year',y='price',data=df)\nsns.boxplot(x='month',y='price',data=df)\ndf.groupby('month').mean()['price'].plot()\ndf.groupby('year').mean()['price'].plot()\n\"\"\"\n**NOW WE DONT NEED THE DATE **\n\"\"\"\ndf\ndf.columns\ndf['zipcode'].value_counts()\ndf = df.drop('zipcode',axis=1)\ndf.head()\ndf['yr_renovated'].value_counts()\ndf['sqft_basement'].value_counts()\n\"\"\"\n**SCALING AND TRAIN_TEST_SPLIT**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6cb4570aef3cdc'}"}
{"id":"12578","text":"\"\"\"\n# Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nfrom tqdm import tqdm\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Embedding, Dense, LSTM, GRU, Dropout\nfrom tensorflow.keras.initializers import Constant\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import metrics, losses, models\n\nfrom tensorflow import autograph\nautograph.set_verbosity(0)\nimport tensorflow_addons as tfa\n\"\"\"\n# Datasets\n\"\"\"\nX_train = pd.read_csv('..\/input\/lstm-gru-sentiment-analysis-data-prep\/X_train.csv').to_numpy()\ny_train = pd.read_csv('..\/input\/lstm-gru-sentiment-analysis-data-prep\/y_train.csv').to_numpy()\nX_test  = pd.read_csv('..\/input\/lstm-gru-sentiment-analysis-data-prep\/X_test.csv').to_numpy()\ny_test  = pd.read_csv('..\/input\/lstm-gru-sentiment-analysis-data-prep\/y_test.csv').to_numpy()\n\nprint(\"Shape of training examples : \"+str(X_train.shape)+\", and training labels : \"+str(y_train.shape))\n\nembedding_matrix  = pd.read_csv('..\/input\/lstm-gru-sentiment-analysis-data-prep\/embedding_matrix.csv').to_numpy()\nnum_words = np.shape(embedding_matrix)[0]\n\nprint(\"Number of words : \"+str(num_words))\nprint(\"Shape of the embedding matrix : \"+str(np.shape(embedding_matrix)))\n\"\"\"\n# Model\n\"\"\"\nINITIAL_DROPOUT = 0.1\nNUM_UNITS_LSTM  = 32\nLSTM_DROPOUT    = 0.2\nNUM_UNITS_GRU   = 32\nGRU_DROPOUT     = 0.2\n\nDENSE_ACT = 'sigmoid'\nLOSS_FCT  = 'mean_squared_error'\nOPTIMIZER = Adam(learning_rate=0.002)\nMETRICS   = [metrics.CategoricalAccuracy()]\nprint(\"Shape of the X_train matrix\" + str(X_train.shape) + \" -- (num_examples, length of examples)\")\nprint(\"Shape of the y_train vector\" + str(y_train.shape) + \" -- (num_examples,)\")\nprint(\"Number of words in the corpus\/embedding : \"+str(num_words))\n\nmodel = Sequential()\nmodel.add(Input(shape=(X_train.shape[1],)))\nmodel.add(Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix),trainable=False))\n\n#model.add(Dropout(INITIAL_DROPOUT))\n\nmodel.add(LSTM(NUM_UNITS_LSTM, return_sequences=True, dropout=LSTM_DROPOUT))\n\nmodel.add(GRU(NUM_UNITS_GRU, dropout=GRU_DROPOUT))         \n    \nmodel.add(Dense(3, activation = DENSE_ACT))\n\nmodel.compile(loss=LOSS_FCT,optimizer=OPTIMIZER,metrics=METRICS)\n\nmodel.summary()\n\"\"\"\n# Training - First pass\n\"\"\"\nBATCH_SIZE = 100\nNUM_EPOCHS = 10\n\nhistory = model.fit(X_train,y_train,batch_size=BATCH_SIZE,epochs=NUM_EPOCHS,validation_data=(X_test,y_test))\n\nmodel.save(\"lstm-gru_1.h5\")\n\"\"\"\n# Training - Second pass\n\"\"\"\n#from tensorflow.keras import models\n#NUM_EPOCHS_2 = 5\n#model1 = models.load_model('lstm-gru_1.h5')\n#history_2 = model1.fit(X_train,y_train,batch_size=BATCH_SIZE,epochs=NUM_EPOCHS_2,validation_data=(X_test,y_test))\n#model1.save(\"lstm-gru_1.h5\")\n\"\"\"\n# Metrics and analysis\n\"\"\"\nimport matplotlib.pyplot as plt\n\nepochs = range(1, NUM_EPOCHS+1)\n\nplt.plot(epochs, history.history['categorical_accuracy'])\nplt.plot(epochs, history.history['val_categorical_accuracy'])\nplt.title('model categorical accuracy')\nplt.ylabel('categorical accuracy')\nplt.xlabel('epochs')\nplt.legend(['train', 'test'], loc='upper left')\nplt.xticks(epochs, epochs)\nplt.show()\n\nplt.plot(epochs, history.history['loss'])\nplt.plot(epochs, history.history['val_loss'])\nplt.title('model loss')\nplt.xlabel('epochs')\nplt.legend(['train', 'test'], loc='upper left')\nplt.xticks(epochs, epochs)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '170422ae6ca9e7'}"}
{"id":"2285","text":"\"\"\"\n# Jane Street Market Prediction EDA\n## Action Threshold and Feature Communities\n\nSince the training set does not provide the label `action`, it is left up to us to determine how that label is applied to the data used to train our models. In this notebook, we set an arbitrary initial `action_threshold` value for `weight * resp` that will determine the positive `action` class. Then, we'll determine raw feature similarity by creating a graph (nodes and edges) using the feature and tags. Finally, we'll group the features according to the community structure exhibited in the graph and take a look at pairplots of the groups with our `action` label.\n\nTODO: determine methods that will optimize the `action_threshold` value for creating the positive class.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\ntrain = pd.read_csv('\/kaggle\/input\/jane-street-market-prediction\/train.csv')\n\ntrain = train.astype({col: np.float32 for col in train.select_dtypes('float64').columns})\ntrain = train.astype({col: np.int32 for col in train.select_dtypes('int64').columns})\nclass TrainData():\n    \n    def __init__(self, df, action_threshold=0.0):\n        self.train = df.copy()\n        self.action_threshold = action_threshold\n        \n    \n    def add_weight_resp(self):\n        \"\"\"Calculates weight * resp for new column weight_resp.\"\"\"\n        self.train['weight_resp'] = self.train['weight'] * self.train['resp']\n        self.train['weight_resp'] = self.train['weight_resp'].astype(np.float32)\n        \n    def add_action(self):\n        \"\"\"Adds action column if weight_resp > action_threshold.\"\"\"\n        self.train['action'] = np.where(\n            self.train['weight_resp'] > self.action_threshold, 1, 0)\n        self.train['action'] = self.train['action'].astype(np.int32)\n\"\"\"\n## Training Data\nFor initial analysis, we are going to arbitrarily set the `action_threshold` parameter in our `TrainData` object. \n\nThe `add_action` method will add the `action` column with a value of 1 if `weight * resp > action_threshold`, else 0.\n\"\"\"\nact_thresh = 0.1\n\ntd = TrainData(df=train, action_threshold=act_thresh)\ntd.add_weight_resp()\ntd.add_action()\n\"\"\"\n## Plots\nLet's take a look at a few distributions with the arbitrarily set `action_threshold`...\n\"\"\"\nsns.distplot(td.train['weight_resp'], rug=False, bins=100)\nplt.title('Distribution: weight * resp')\nplt.hist(td.train['action'])\nplt.title(f'Distribution: action\\nwith threshold = {act_thresh}')\n\"\"\"\nThe distribution of our dependent variable above shows a significant class imbalance. Oversampling may be a good idea here.\n\nThe following scatterplots show `weight` vs. `resp`. The first one is colored by `weight * resp`. The second one is colored by `action` and was used to come up with the `action_threshold` value. Note the outliers.\n\"\"\"\nfig = plt.figure(figsize=(24, 16))\nsns.scatterplot(x='weight', y='resp', hue='weight_resp', data=td.train, palette='icefire')\nplt.title('weight vs. resp', fontsize=20)\nfig = plt.figure(figsize=(24, 16))\nsns.scatterplot(x='weight', y='resp', hue='action', data=td.train, palette='icefire')\nplt.title('weight vs. resp', fontsize=20)\n\"\"\"\n## Comparing `feature_0` to `action`\nHere, I'm using Seaborn's pairplot to produce bivariate scatterplots for a handful of features. In particular, I was curious to see how `feature_0` - a feature with only two values - compared to the `action` variable derived from our `action_threshold`.\n\"\"\"\nsns.pairplot(td.train.iloc[:, 7:12], hue='feature_0')\nsns.pairplot(pd.concat([td.train.iloc[:, 8:12], td.train.loc[:, 'action']], axis=1), hue='action')\n\"\"\"\nI find it very interesting that the positive `action` class appears to be centered within each scatter plot, and that `feature_0` value of 1 corresponds with this with a bit of a skew. Makes me wonder whether the former is a subset of the latter...\n\"\"\"\nfor val in td.train['feature_0'].unique():\n    subdf = td.train.loc[td.train['feature_0'] == val]\n    print(f\"***\\nfeature_0 = {val}\\n{subdf['action'].value_counts()}\\n\")\n\"\"\"\nNope.\n\"\"\"\n\"\"\"\n## Tags\nEach of the features in our training set have a set of boolean tags associated with them. These are specified in `features.csv`. In order to find some similarities among the features, let's create a bipartite graph where the nodes are the features and tags, and where an edge exists between a feature and a tag if the tag value is `True`. Then, let's apply the `best_partition` method to better see the community structure.\n\"\"\"\nimport networkx as nx\nimport community\nimport matplotlib.cm as cm\nfrom matplotlib.colors import Normalize\nfeats = pd.read_csv(\n    '\/kaggle\/input\/jane-street-market-prediction\/features.csv')\nfeats = feats.astype({col: np.int32 for col in feats.select_dtypes('bool').columns})\nclass FeatureGraph():\n    \n    def __init__(self, df):\n        self.G = nx.Graph()\n        self.data = df.copy()\n        self.partition = None\n        \n        \n    def add_feature_nodes(self):\n        \"\"\"Adds nodes for features.\"\"\"\n        for feat in self.data['feature'].unique():\n            self.G.add_nodes_from([feat], color='green')\n            \n            \n    def add_tag_nodes(self):\n        \"\"\"Adds nodes for tags.\"\"\"\n        for col in self.data.columns:\n            if 'tag' in col:\n                self.G.add_nodes_from([col], color='red')\n                \n                \n    def add_edges(self):\n        \"\"\"Adds edges between features and tags if value == 1.\"\"\"\n        for row in range(self.data.shape[0]):\n            source_node = self.data.loc[row, 'feature']\n\n            for col in range(1, self.data.shape[1]):\n                target_node = self.data.columns[col]\n                if self.data.iloc[row, col] == 1:\n                    self.G.add_edge(source_node, target_node)\n\n    \n    def create_graph(self):\n        \"\"\"Creates graph object.\"\"\"\n        self.add_feature_nodes()\n        self.add_tag_nodes()\n        self.add_edges()\n        \n        \n    def create_partition(self):\n        \"\"\"Partition the graph and adds partition attribute to each node.\"\"\"\n        self.partition = community.best_partition(self.G)\n        nx.set_node_attributes(self.G, self.partition, 'partition')\nfg = FeatureGraph(df=feats)\nfg.create_graph()\n\"\"\"\nBelow, we have the features colored in green and the tags colored in red. We definitely see some community structure within the network.\n\"\"\"\nfig = plt.figure(figsize=(24, 16))\npos = nx.spring_layout(fg.G)\ncol = nx.get_node_attributes(fg.G, 'color').values()\nnx.draw(fg.G, pos=pos, font_size=8, with_labels=True, node_size=100, node_color=col)\n\"\"\"\nNote that node `feature_0` has no edges. \n\nNow, let's color the nodes according to the communities determined by the `best_partition` method. We will also create `partition_dict` to look at scatter plots for each partition.\n\"\"\"\nfg.create_partition()\n\ncmap = cm.viridis\nnorm = Normalize(vmin=min(fg.partition.values()), \n                 vmax=max(fg.partition.values()))\n\npart_list = []\nfor k in fg.partition.keys():\n    part_list.append(fg.partition[k])\n\npart_set = set(part_list)\n\npartition_dict = {}\nfor i in part_set:\n    partition_dict.update({i: []})\n\npartition_colors = []\n\nfor node in fg.G.nodes(data=True):\n    for k in partition_dict.keys():\n        if node[1]['partition'] == k:\n            partition_colors.append(cmap(norm(k)))\n            if 'feature' in node[0]:\n                partition_dict[k].append(node[0])\nfig = plt.figure(figsize=(24, 16))\npos = nx.spring_layout(fg.G)\nnx.draw(fg.G, pos=pos, font_size=8, with_labels=True, node_size=100, node_color=partition_colors)\npartition_dict\n\"\"\"\n## Pairplots by Partition\nNow, let's take a look at the pairplots for a few of the smaller partitions, colored by `action`.\n\"\"\"\nl_list = []\n\nfor k, v in partition_dict.items():\n    l_list.append(len(v))\nplot_list = partition_dict[np.argsort(l_list)[1]] + ['action']\nsns.pairplot(td.train.loc[:, plot_list], hue='action')\nplot_list = partition_dict[np.argsort(l_list)[2]] + ['action']\nsns.pairplot(td.train.loc[:, plot_list], hue='action')\n# plot_list = partition_dict[np.argsort(l_list)[3]] + ['action']\n# sns.pairplot(td.train.loc[:, plot_list], hue='action')\n# plot_list = partition_dict[np.argsort(l_list)[4]] + ['action']\n# sns.pairplot(td.train.loc[:, plot_list], hue='action')","meta":"{'source': 'AI4Code', 'id': '045b0241355a21'}"}
{"id":"2159","text":"\"\"\"\n# From EfficientNetB0 to B7 - Melanoma Classification with Tensorflow\/Keras\n\nThis kernel presents the results of training the EfficientNet models, from B0 to B7, using TPUs (yeah, it took a looooooong time to train it all).\n\nAnd the kernel I used to train all these models is [here](https:\/\/www.kaggle.com\/fredericods\/efficientnetbi-melanoma-classification-with-tf). \n\nThe main idea is to analyze the influence of the model size on its performance. And obviously, practice computer vision and deep learning skills. :)\n\nThe performance of the trained networks here is still far behind the top-score solutions, but there is a lot of room for improvement: tuning the learning rate, larger input size, larger networks, more complex augmentations, using metadata, ensembling etc.\n\nFeel free to criticize and suggest!\n\n**Training\/Modeling Highlights:**\n- Image input size: 256 x 256\n- Fine tuning EfficientNet with only a dense layer on the top\n- Stratified Group 4-Fold Validation: imbalanced target distribution + not have same patient on train and validation set\n- Augmentations: random flip left-right and random flip up-down\n- Learning Rate Scheduler: adopting a learning rate ramp-up because fine-tuning a pre-trained model\n- Adam optimizer\n- Loss function: Binary Cross-Entropy Loss with label_smoothing\n- Epochs: 10\n- Model checkpoint: saving when best validation loss is achieved\n\n**References:**\n- https:\/\/www.kaggle.com\/reighns\/groupkfold-efficientbnet-and-augmentations\n- https:\/\/www.kaggle.com\/jakubwasikowski\/stratified-group-k-fold-cross-validation\n- https:\/\/www.kaggle.com\/cdeotte\/rotation-augmentation-gpu-tpu-0-96\n- https:\/\/www.kaggle.com\/ajaykumar7778\/melanoma-tpu-efficientnet-b5-dense-head\n- https:\/\/www.kaggle.com\/khoongweihao\/siim-isic-multiple-model-training-stacking\n\"\"\"\n\"\"\"\n## 1) Importing libraries and dataset\n\"\"\"\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport numpy as np\nimport pandas as pd\n\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n        \nDATA_PATH = '\/kaggle\/input\/efficientbx-melanoma-classification-with-tf'\n\n# Importing Data\nhistory_files = [f for f in listdir(DATA_PATH) if isfile(join(DATA_PATH, f)) and f.split('_')[0] == 'history']\nsubmit_files = [f for f in listdir(DATA_PATH) if isfile(join(DATA_PATH, f)) and f.split('_')[0] == 'submit']\n# Preprocessing Data for visualization (Performance x Model)\nlist_results = []\nfor file_name_i in history_files:\n    model_name_i = file_name_i[8:22]\n    fold_name_i = file_name_i[23:29]\n    df_i = pd.read_csv(os.path.join(DATA_PATH, file_name_i), index_col=0)\n    auc_i = df_i[df_i.val_loss == df_i.val_loss.min()]['val_auc'].iloc[0]\n    loss_i = df_i.val_loss.min()\n    list_results.append([model_name_i, fold_name_i, auc_i, loss_i])\ndf_results = pd.DataFrame(list_results, columns = ['Model', 'Fold', 'AUC', 'Loss'])\n\nfor model_name_i in df_results.Model.unique():\n    mean_auc_i = df_results.AUC[df_results.Model == model_name_i].mean()\n    mean_loss_i = df_results.Loss[df_results.Model == model_name_i].mean()\n    df_i = pd.DataFrame([[model_name_i, 'mean_fold', mean_auc_i, mean_loss_i]], columns = ['Model', 'Fold', 'AUC', 'Loss'])\n    df_results = pd.concat([df_results, df_i])\n    \ndf_results = df_results.sort_values(by = ['Model', 'Fold'], ascending = True).reset_index().drop(columns = ['index'])\n# Preprocessing Data for visualization (Training History)\nmodel_names = ['EfficientNetB' + str(i) for i in range(8)]\nfold_names = ['fold_' + str(i) for i in range(4)]\ndict_df_history = {}\nfor model_i in model_names:\n    dict_df_history[model_i] = {}\n    for fold_i in fold_names:\n        file_name_i = 'history_' + model_i + '_' + fold_i + '.csv'\n        df_history_i = pd.read_csv(os.path.join(DATA_PATH, file_name_i))\n        df_history_i=df_history_i.rename(columns = {\n            'Unnamed: 0': 'Epoch',\n            'loss': 'Train Loss',\n            'auc': 'Train AUC',\n            'val_loss': 'Valid Loss',\n            'val_auc': 'Valid AUC',\n            'lr': 'Learning Rate'\n        }\n                           )\n        dict_df_history[model_i][fold_i] = df_history_i\n\"\"\"\n## 2) Visualizing Results\n\"\"\"\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n\ndf_results_mean_fold = df_results[df_results.Fold=='mean_fold']\n\nfig = make_subplots(rows=2, cols=1)\n\nfig.append_trace(\n    go.Scatter(x=df_results_mean_fold.Model, y=df_results_mean_fold.AUC, name='AUC'),\n    row=1, col=1\n)\n\nfig.append_trace(\n    go.Scatter(x=df_results_mean_fold.Model, y=df_results_mean_fold.Loss, name='Loss'),\n    row=2, col=1\n)\n\n\nfig.update_layout(height=800, width=600, title_text=\"Performance x Model\")\nfig.update_yaxes(title_text=\"AUC\", row=1, col=1)\nfig.update_yaxes(title_text=\"Loss\", row=2, col=1)\n\nfor trace in fig['data']: \n    trace['showlegend'] = False\n        \nfig.show()\n\"\"\"\n### Model Training History\n\"\"\"\nfig = make_subplots(rows=2, cols=2, subplot_titles=('Fold 0', 'Fold 1', 'Fold 2', 'Fold 3'))\n\n# Add Traces\nfor model_name_i in model_names:\n    for i, fold_i in enumerate(fold_names):\n        for set_i in ['Train', 'Valid']:\n            for metric_i in ['AUC', 'Loss']:\n                index_dict = {\n                    'fold_0': [1,1],\n                    'fold_1': [1,2],\n                    'fold_2': [2,1],\n                    'fold_3': [2,2]\n                }\n                color_dict = {\n                    'Train AUC': {'color': '#dba053'},\n                    'Valid AUC': {'color': '#6e53db'},\n                    'Train Loss': {'color': '#4cd489'},\n                    'Valid Loss': {'color': '#bf2e2e'}\n                }\n                fig.add_trace(\n                    go.Scatter(\n                        x=dict_df_history[model_name_i][fold_i]['Epoch'],\n                        y=dict_df_history[model_name_i][fold_i][set_i + ' ' + metric_i],\n                        name=set_i + ' ' + metric_i,\n                        #name=model_name_i + ' ' + fold_i + ' ' + set_i + ' ' + metric_i,\n                        #name=model_name_i[-2:] + fold_i[-1] + set_i + metric_i,\n                        line=color_dict[set_i + ' ' + metric_i],\n                        legendgroup=model_name_i[-2:] + ' ' + metric_i,\n                        showlegend=(i==0)\n                    ),\n                    row=index_dict[fold_i][0], col=index_dict[fold_i][1]\n                )\n\nlist_buttons = []\nfor i, model_name_i in enumerate(model_names):\n    visible_list_aux_i = [False]*128\n    visible_list_aux_i[i*16:i*16+16] = [True]*16\n    button_i = dict(\n        label=model_name_i[-2:],\n        method=\"update\",\n        args=[{\"visible\": visible_list_aux_i}])\n    list_buttons.append(button_i)                \n                \nfig.update_layout(\n    updatemenus=[\n        dict(\n            active=0,\n            buttons=list_buttons,\n            direction=\"right\",\n            pad={\"r\": 10, \"t\": 10},\n            showactive=True,\n            x=0.00,\n            xanchor=\"left\",\n            y=1.25,\n            yanchor=\"top\",\n            type = 'buttons'\n        )\n    ])\n\nfig.show()\n\"\"\"\n## 3) Submit Files\n\"\"\"\nsample_submit = pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/sample_submission.csv')\nfor model_name_i in model_names:\n    target_list = []\n    for fold_i in fold_names:\n        target_i = pd.read_csv(os.path.join(DATA_PATH, 'submit_' + model_name_i + '_' + fold_i + '.csv'))['target'].values\n        target_list.append(target_i)\n    df_submit_i = sample_submit.copy()\n    df_submit_i['target'] = np.mean(target_list, axis=0)\n    df_submit_i.to_csv('submit_' + model_name_i + '_mean_fold.csv', index=False)\n    print(model_name_i + ' - Mean Fold submit file saved')","meta":"{'source': 'AI4Code', 'id': '0418c68457fcb5'}"}
{"id":"30044","text":"\"\"\"\n**First we import necessary libraries.Lets collect the data. We are using URL to collect the data. This URL downloads the csv file**\n\"\"\"\nimport pandas as pd\nimport plotly as py\nimport plotly.express as px #For high level data visualization\nurl='https:\/\/covid.ourworldindata.org\/data\/owid-covid-data.csv'\ndata=pd.read_csv(url) #Reading data into dataframe\npd.options.display.float_format = '{:.2f}'.format #getting rid of 'e'form in data value\ndata.head()\ndata_countrydate = data[data['new_cases']>0] #Filtering data with new cases>0\ndata_countrydate=data_countrydate.groupby(['date','location']).sum().reset_index() #Grouping the data by date and location\nfig = px.choropleth(data_countrydate, \n                    locations=\"location\", \n                    locationmode = \"country names\",\n                    color=\"new_cases\", \n                    hover_name=\"location\", \n                    animation_frame=\"date\"\n                   )\nfig.update_layout(\n    title_text = 'Spread of Coronavirus',\n    title_x = 0.5,\n    geo=dict(\n        showframe = False,\n        showcoastlines = False,\n    ))\n\"\"\"\nThis is simple way of knowing how new cases of covid are changing.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '373c939884da33'}"}
{"id":"55533","text":"\"\"\"\n# General Overview\n\"\"\"\n\"\"\"\nDataset Resources: [UC Irvine's Machine Learning Repository](https:\/\/archive.ics.uci.edu\/ml\/datasets\/Diabetes+130-US+hospitals+for+years+1999-2008)\n\n[Kaggle Link](https:\/\/www.kaggle.com\/pavan2029\/diabetic-data)\n\n**Objective:**\nHospital readmission rates for certain conditions are now considered an indicator of hospital quality, and also affect the cost of care adversely. Hospital readmissions of diabetic patients are expensive as hospitals face penalties if their readmission rate is higher than expected and reflects the inadequacies in health care system. For these reasons, it is important for the hospitals to improve focus on reducing readmission rates. Identify the key factors that influence readmission for diabetes and to predict the probability of patient readmission. \n\nThe dataset represents 10 years (1999-2008) of clinical care at 130 US hospitals and integrated delivery networks. It includes over 50 features representing patient and hospital outcomes. The data contains such attributes as patient number, race, gender, age, admission type, time in hospital, medical specialty of admitting physician, number of lab test performed, HbA1c test result, diagnosis, number of medication, diabetic medications, number of outpatient, inpatient, and emergency visits in the year before the hospitalization, etc.*\n\"\"\"\n\"\"\"\n### Import Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nimport re\n\n# to avoid warnings\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.warn(\"this will not show\")\n\nsns.set(style='darkgrid')\n%matplotlib inline\n\"\"\"\n### Import Dataset\n\"\"\"\npd.read_csv('diabetic_data.zip').head()\n# csv contains \"?\" for missing values. We replace it with NaN\ndata = pd.read_csv('diabetic_data.zip', na_values=[\"?\"])\ndf= data.copy()\ndf.head()\n\"\"\"\n### Import Features Dataset\nDescriptions of the features:\nhttps:\/\/www.hindawi.com\/journals\/bmri\/2014\/781670\/tab1\/\n\"\"\"\nfeatures = pd.read_csv('features.csv',index_col='Unnamed: 0')\ninfo = lambda attribute:print(f\"{attribute.upper()} : {features[features['Feature']==attribute]['Description'].values[0]}\\n\")\nfeatures.head()\ninfo('encounter_id')\n\"\"\"\n### Check Duplicates\n\"\"\"\ndf.duplicated().value_counts()\n# df = df.drop_duplicates()\n\"\"\"\n> no duplicates detected!\n\"\"\"\n\"\"\"\n### Descriptive Analysis\n\"\"\"\ndef summary(df, pred=None):\n    obs = df.shape[0]\n    Types = df.dtypes\n    Counts = df.apply(lambda x: x.count())\n    Min = df.min()\n    Max = df.max()\n    Uniques = df.apply(lambda x: x.unique().shape[0])\n    Nulls = df.apply(lambda x: x.isnull().sum())\n    print('Data shape:', df.shape)\n\n    if pred is None:\n        cols = ['Types', 'Counts', 'Uniques', 'Nulls', 'Min', 'Max']\n        str = pd.concat([Types, Counts, Uniques, Nulls, Min, Max], axis = 1, sort=True)\n\n    str.columns = cols\n    print('___________________________\\nData Types:')\n    print(str.Types.value_counts())\n    print('___________________________')\n    return str\n\ndisplay(summary(df).sort_values(by='Nulls', ascending=False))\n\"\"\"\n* 'citoglipton' and 'examide' features that the number of uniques is 1 are droped.\n* all values of 'encounter_id' column are unique. It has to be droped.\n\"\"\"\ndf = df.drop(['citoglipton','examide','encounter_id'],axis=1)\n\"\"\"\n### FOCUS ON \"Gender\"\n\"\"\"\ndf.gender.value_counts(dropna=False)\n\"\"\"\n> We regard the observations of \"Unknown\/Invalid\" gender as null values and drop them.\n\"\"\"\ngender_index = df[df.gender == 'Unknown\/Invalid'].index\ndf = df.drop(gender_index, axis=0)\n# confirm removal\ndf.gender.value_counts(dropna=False)\n\"\"\"\n### FOCUS ON \"readmitted\"\n\"\"\"\ndf.readmitted.value_counts(dropna=False)\n\"\"\"\n> Patients readmitted to the hospital within and after 30 days will be combined into one column, because these patients ultimately returned.\n\"\"\"\ndf = df.replace(['<30', '>30'], 'YES')\n\"\"\"\n### FOCUS  ON \" patient_nbr \"\n\"\"\"\ninfo('patient_nbr')\ndf['patient_nbr'].duplicated().value_counts(dropna=False)\n\"\"\"\n* we can think of 'patient_nbr' as the id number of each patient.\n* It turned out that the dataset is the data of 71515 unique patients.\n* Some patients visited the hospital multiple times for treatment so to avoid over-representing any particular individual, only the first encounter with a patient will be used \/ kept in this dataset.\n\"\"\"\n# total unique patients\nlen(df.patient_nbr), df.patient_nbr.nunique()\n# locate number of patient visits using patient_id\ndf.patient_nbr.value_counts()\n# keep only one record for each patient, the first visit\ndf = df.drop_duplicates(['patient_nbr'], keep='first')\ndf.shape\ndf.patient_nbr.nunique()\n\"\"\"\n* Since patient_nbr is unique, it is no longer needed.\n\"\"\"\ndf = df.drop('patient_nbr', axis=1)\n\"\"\"\n### Dropping irrelevant columns\n\"\"\"\n def null_values(df):\n    \"\"\"a function to show null values with percentage\"\"\"\n    nv=pd.concat([df.isnull().sum(), 100 * df.isnull().sum()\/df.shape[0]],axis=1).rename(columns={0:'Missing_Records', 1:'Percentage (%)'})\n    return nv[nv.Missing_Records>0].sort_values('Missing_Records', ascending=False)\n# columns with missing values\nnull_values(df)\nfor i in ['weight','medical_specialty','payer_code']: info(i)\n\"\"\"\n* The majority of patients do not have a weight listed so this column can be dropped. \n* Medical specialty and payer code are also missing for about half of the patients. \n* We do not need to know how the patients paid for their treatments.\n* we do not have enough information to figure out which medical unit they went to.\n\"\"\"\ndf = df.drop(['weight','medical_specialty','payer_code'], axis=1)\nsummary(df).sort_values(by='Uniques', ascending=False)[:20]\nfor i in ['admission_type_id', 'discharge_disposition_id', 'admission_source_id']: info(i)\n\"\"\"\n* We dont need 'admission_type_id', 'discharge_disposition_id', 'admission_source_id' columns\n\"\"\"\n# drop columns\ndrop_cols = ['admission_type_id', 'discharge_disposition_id', 'admission_source_id']\ndf = df.drop(drop_cols, axis=1)\n\"\"\"\n### Handling Missing Values\n\"\"\"\nnull_values(df)\ndf.race.value_counts(dropna=False)\n\"\"\"\n* Since there is no way to know the race of the patient using existing information, the best option is to remove those rows.\n\"\"\"\ndf = df.dropna(axis=0, subset=['race'])\nnull_values(df)\nfor i in ['diag_1', 'diag_2', 'diag_3']: info(i)\n\"\"\"\n* You can reach the extensive diagnosis description on this website by querying with the ICD9 code:\nhttp:\/\/icd9.chrisendres.com\/\n\"\"\"\n\"\"\"\nNow, we are down to three columns with missing information: diagnosis 1, 2, and 3. \n* Diagnosis 1 is described as the primary diagnosis made during the patient's visit while diagnosis 2 is the second and 3 is an any additional diagnoses made after that. \n* Looking at the patients' rows that are missing a primary diagnosis, most of them have a second diagnosis or even a third. \n* Since it doesn't make sense to have a second (or third) but not a primary diagnosis, we will remove these columns from the dataset.\n\"\"\"\ninfo('number_diagnoses')\ndf[['diag_1', 'diag_2', 'diag_3','number_diagnoses']][df.diag_1.isnull() & df.diag_2.notnull() & df.diag_3.notnull() & df.number_diagnoses.notnull()]\n\"\"\"\nThe number of diagnoses column shows the total number of conditions a patient is diagnosed with. Only the first three are recorded, so those that are missing the first diagnosis but still a second or third are in error.\n\"\"\"\n# remove rows where diagnosis 1 is missing\ndf = df.dropna(axis=0, subset=['diag_1'])\n\"\"\"\nThere are two remaining diagnosis columns with missing values. Each number correlates to a specific condition so if there is a missing value, then it is likely that the patient only has one diagnosed condition. The number of diagnoses column lists the total number of diagnosed conditions. When looking at all three diagnosis columns, if the number is one, then diagnosis 2 and 3 can be filled in with a 0 to show that there is no additional diagnosis. If diagnosis 2 or 3 is missing a value and the number of diagnoses is greater than one, then some diagnoses were not recorded and the rows should be removed.\n\"\"\"\nnull_values(df)\ndf[['diag_1','diag_2', 'diag_3','number_diagnoses']][df.diag_2.isnull() & (df.diag_3.notnull()|(df.number_diagnoses > 1))]\n# remove rows where diagnosis 2 is missing and number of diagnoses is greater than 1\ndiag_2_indexes = df[df.diag_2.isnull() & (df.diag_3.notnull()|(df.number_diagnoses > 1))].index\ndf = df.drop(index = diag_2_indexes, axis=0)\nnull_values(df)\n\"\"\"\nDiagnosis 3 is the last column left with unaccounted missing values. Since some patients have 1 or 2 diagnosed conditions, the diagnosis 3 column is left intentionally blank. The goal here is to remove the rows that have a diagnoses number greater than two.\n\"\"\"\n# list of affected rows\ndf[['diag_1','diag_2', 'diag_3', 'number_diagnoses']][df.diag_3.isnull() & (df.number_diagnoses > 2)]\n# remove rows with missing diagnosis 3 and number of diagnoses is greater than 2\ndiag_3_indexes = df[(df.diag_3.isnull()) & (df.number_diagnoses > 2)].index\ndf = df.drop(index=diag_3_indexes, axis=0)\nnull_values(df)\nsns.heatmap(df[['diag_1','diag_2', 'diag_3','number_diagnoses']].isnull(),yticklabels=False,cbar=False,cmap='viridis');\n# replace NaN with None in diagnosis 2 and 3 to show there is no additional diagnosis\ndf.fillna('None', inplace=True)\n# confirm there are no more NaN values\nnull_values(df)\n\"\"\"\n### Grouping Diagnosis Codes\n\"\"\"\nsummary(df[['diag_1','diag_2', 'diag_3']])\n\"\"\"\n* 'diag_1','diag_2' and 'diag_3' columns contain codes for the types of conditions patients are diagnosed with. \n* There are too much unique codes throughout this dataset.\n* We can group the related icd9 diagnosis codes among themselves. In this way, we use categorical group names instead of numerical codes.\n* The grouping is based on the research paper table (https:\/\/www.hindawi.com\/journals\/bmri\/2014\/781670\/tab2\/)\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n**Group Names**\n\n    1-Circulatory\n    2-Respiratory\n    3-Digestive\n    4-Diabetes\n    5-Injury\n    6-Musculoskeletal\n    7-Genitourinary\n    8-Neoplasms\n    9-Other\n\"\"\"\n# Circulatory\ncodes =[str(i) for i in list(range(390,460)) + [785]]\ndf = df.replace(codes, 'Circulatory')\n# Respiratory\ncodes =[str(i) for i in list(range(460,520)) + [786]]\ndf = df.replace(codes, 'Respiratory')\n# Digestive\ncodes =[str(i) for i in list(range(520,580)) + [787]]\ndf = df.replace(codes, 'Digestive')\n# Diabetes\ndf = df.replace(regex=r'^250.*', value='Diabetes')\n# Injury\ncodes =[str(i) for i in range(800,1000)]\ndf = df.replace(codes, 'Injury')\n# Musculoskeletal\ncodes =[str(i) for i in range(710,740)]\ndf = df.replace(codes, 'Musculoskeletal')\n# Genitourinary\ncodes =[str(i) for i in list(range(580,630)) + [788]]\ndf = df.replace(codes, 'Genitourinary')\n# Neoplasms\ncodes =[str(i) for i in range(140,240)]\ndf = df.replace(codes, 'Neoplasms')\n# Other\ndf = df.replace(regex=r'^[E,V].*', value='Other')\n\ncodes =[str(i) for i in range(0,1000)]\ndf = df.replace(codes, 'Other')\ndf[['diag_1', 'diag_2', 'diag_3']].head()\n# Unique Values of Each Features:\nfor i in df[['diag_1', 'diag_2', 'diag_3']]:\n    print(f'{i}:\\n{sorted(df[i].unique())}\\n')\n# need to add 365.44 to Other\ndf = df.replace('365.44', 'Other') \n\"\"\"\n### Analysis of Diagnosis\n\"\"\"\nplt.figure(figsize=(20, 8))\nfor diag in ['diag_1','diag_2','diag_3']:\n    sns.lineplot(x=df[diag].value_counts().sort_index().index, y= df[diag].value_counts().sort_index().values, marker='o')\nplt.legend(['diag_1','diag_2','diag_3'])\nplt.show()\n\"\"\"\n* Looking at the graph above, we can say that there is a high correlation between the diagnoses. So we drop diag_2 and diag_3.\n* Also since the most common diagnoses are prevalent in all three diagnoses listed, We are only using the primary diagnosis variable to build the machine learning model\n\"\"\"\n# drop diagnoses 2 and 3\ndf = df.drop(columns=['diag_2', 'diag_3'])\n\"\"\"\n### FOCUS ON \"`number_diagnoses`\"\n\"\"\"\nplt.figure(figsize=(8,5))\nax = df.number_diagnoses.value_counts().sort_index().plot.bar()\ndef labels(ax, df=df):\n    for p in ax.patches:\n            ax.annotate('{:.0f}'.format(p.get_height()), \n                        (p.get_x(), p.get_height()+100),size=10)\nlabels(ax)\n\"\"\"\n* For a small number of observations with number of diagnoses greater than 9, let's change the number of diagnoses to 9.\n\"\"\"\ndf.number_diagnoses = df.number_diagnoses.replace([10,11,12,13,14,15,16],9)\n\"\"\"\n### Outlier Detection\n\"\"\"\n\"\"\"\nBased on the basic statistics describing the dataset, it looks there are outliers that influence skewness in the data. In order to represent the majority of samples and build clean models, we are going to remove outliers that have [z-scores](https:\/\/www.statisticshowto.datasciencecentral.com\/probability-and-statistics\/z-score\/) greater than 3.0 or less than -3.0. This means that we are removing samples that are more (or less) than 3 times the standard deviation from the mean.\n\"\"\"\ndf.describe().T\nfeatures = df.describe().columns\ndef col_plot(df,col_name):\n    plt.figure(figsize=(15,6))\n    \n    plt.subplot(141) # 1 satir x 4 sutun dan olusan ax in 1. sutununda calis\n    plt.hist(df[col_name], bins = 20)\n    f=lambda x:(np.sqrt(x) if x>=0 else -np.sqrt(-x))\n    \n    # \u00fc\u00e7 sigma aralikta(verinin %99.7 sini icine almasi beklenen bolum) iki kirmizi cizgi arasinda\n    plt.axvline(x=df[col_name].mean() + 3*df[col_name].std(),color='red')\n    plt.axvline(x=df[col_name].mean() - 3*df[col_name].std(),color='red')\n    plt.xlabel(col_name)\n    plt.tight_layout\n    plt.xlabel(\"Histogram \u00b13z\")\n    plt.ylabel(col_name)\n\n    plt.subplot(142)\n    plt.boxplot(df[col_name]) # IQR katsayisi, defaultu 1.5\n    plt.xlabel(\"IQR=1.5\")\n\n    plt.subplot(143)\n    plt.boxplot(df[col_name].apply(f), whis = 2.5)\n    plt.xlabel(\"ROOT SQUARE - IQR=2.5\")\n\n    plt.subplot(144)\n    plt.boxplot(np.log(df[col_name]+0.1), whis = 2.5)\n    plt.xlabel(\"LOGARITMIC - IQR=2.5\")\n    plt.show()\nfor i in features:\n    col_plot(df,i)\nfrom scipy.stats.mstats import winsorize\n\ndef plot_winsorize(df,col_name,up=0.1,down=0):\n    plt.figure(figsize = (15, 6))\n\n    winsor=winsorize(df[col_name], (down,up))\n    logr=np.log(df[col_name]+0.1)\n\n    plt.subplot(141)\n    plt.hist(winsor, bins = 22)\n    plt.axvline(x=winsor.mean()+3*winsor.std(),color='red')\n    plt.axvline(x=winsor.mean()-3*winsor.std(),color='red')\n    plt.xlabel('Winsorize_Histogram')\n    plt.ylabel(col_name)\n    plt.tight_layout\n\n    plt.subplot(142)\n    plt.boxplot(winsor, whis = 1.5)\n    plt.xlabel('Winsorize - IQR:1.5')\n    \n    plt.subplot(143)\n    plt.hist(logr, bins=22)\n    plt.axvline(x=logr.mean()+3*logr.std(),color='red')\n    plt.axvline(x=logr.mean()-3*logr.std(),color='red')\n    plt.xlabel('Logr_col_name')\n\n    plt.subplot(144)\n    plt.boxplot(logr, whis = 1.5)\n    plt.xlabel(\"Logaritmic - IQR=1.5\")\n    plt.show()    \n\nfor i in features:\n    plot_winsorize(df,i)\ndf_winsorised=df.copy()\nfor i in features:\n    df_winsorised[i]=winsorize(df_winsorised[i], (0,0.1))\ndf_log=df.copy()\nfor i in features:\n    df_log[i]=np.log(df_log[i])\ndf_root=df.copy()\nf=lambda x:(np.sqrt(x) if x>=0 else -np.sqrt(-x))\nfor i in features:\n    df_root[i]=df_root[i].apply(f)\nfrom numpy import percentile\nfrom scipy.stats import zscore\nfrom scipy import stats\n\ndef outlier_zscore(df, col, min_z=1, max_z = 5, step = 0.1, print_list = False):\n    z_scores = zscore(df[col].dropna())\n    threshold_list = []\n    for threshold in np.arange(min_z, max_z, step):\n        threshold_list.append((threshold, len(np.where(z_scores > threshold)[0])))\n        df_outlier = pd.DataFrame(threshold_list, columns = ['threshold', 'outlier_count'])\n        df_outlier['pct'] = (df_outlier.outlier_count - df_outlier.outlier_count.shift(-1))\/df_outlier.outlier_count*100\n    plt.plot(df_outlier.threshold, df_outlier.outlier_count)\n    best_treshold = round(df_outlier.iloc[df_outlier.pct.argmax(), 0],2)\n    outlier_limit = int(df[col].dropna().mean() + (df[col].dropna().std()) * df_outlier.iloc[df_outlier.pct.argmax(), 0])\n    percentile_threshold = stats.percentileofscore(df[col].dropna(), outlier_limit)\n    plt.vlines(best_treshold, 0, df_outlier.outlier_count.max(), \n               colors=\"r\", ls = \":\"\n              )\n    plt.annotate(\"Zscore : {}\\nValue : {}\\nPercentile : {}\".format(best_treshold, outlier_limit, \n                                                                   (np.round(percentile_threshold, 3), \n                                                                    np.round(100-percentile_threshold, 3))), \n                 (best_treshold, df_outlier.outlier_count.max()\/2))\n    #plt.show()\n    if print_list:\n        print(df_outlier)\n    return (plt, df_outlier, best_treshold, outlier_limit, percentile)\nfrom scipy.stats import zscore\nfrom scipy import stats\n\ndef outlier_inspect(df, col, min_z=1, max_z = 5, step = 0.5, max_hist = None, bins = 50):\n    fig = plt.figure(figsize=(20, 6))\n    fig.suptitle(col, fontsize=16)\n    plt.subplot(1,3,1)\n    if max_hist == None:\n        sns.distplot(df[col], kde=False, bins = 50)\n    else :\n        sns.distplot(df[df[col]<=max_hist][col], kde=False, bins = 50)\n   \n    plt.subplot(1,3,2)\n    sns.boxplot(df[col])\n    plt.subplot(1,3,3)\n    z_score_inspect = outlier_zscore(df, col, min_z=min_z, max_z = max_z, step = step)\n    \n    plt.subplot(1,3,1)\n    plt.axvline(x=df[col].mean() + z_score_inspect[2]*df[col].std(),color='red',linewidth=1,linestyle =\"--\")\n    plt.axvline(x=df[col].mean() - z_score_inspect[2]*df[col].std(),color='red',linewidth=1,linestyle =\"--\")\n    plt.show()\n    \n    return z_score_inspect\ndef detect_outliers(df:pd.DataFrame, col_name:str, p=1.5) ->int:\n    ''' \n    this function detects outliers based on 3 time IQR and\n    returns the number of lower and uper limit and number of outliers respectively\n    '''\n    first_quartile = np.percentile(np.array(df[col_name].tolist()), 25)\n    third_quartile = np.percentile(np.array(df[col_name].tolist()), 75)\n    IQR = third_quartile - first_quartile\n                      \n    upper_limit = third_quartile+(p*IQR)\n    lower_limit = first_quartile-(p*IQR)\n    outlier_count = 0\n                      \n    for value in df[col_name].tolist():\n        if (value < lower_limit) | (value > upper_limit):\n            outlier_count +=1\n    return lower_limit, upper_limit, outlier_count\nk=3\nprint(f\"Number of Outliers for {k}*IQR\\n\")\n\ntotal=0\nfor col in features:\n    if detect_outliers(df, col)[2] > 0:\n        outliers=detect_outliers(df, col, k)[2]\n        total+=outliers\n        print(\"{} outliers in '{}'\".format(outliers,col))\nprint(\"\\n{} OUTLIERS TOTALLY\".format(total))\nk=3\nprint(f\"Number of Outliers for {k}*IQR after Root Square\\n\")\n\ntotal=0\nfor col in features:\n    if detect_outliers(df_root, col)[2] > 0:\n        outliers=detect_outliers(df_root, col, k)[2]\n        total+=outliers\n        print(\"{} outliers in '{}'\".format(outliers,col))\nprint(\"\\n{} OUTLIERS TOTALLY\".format(total))\nk=3\nprint(f\"Number of Outliers for {k}*IQR after Winsorised\\n\")\n\ntotal=0\nfor col in features:\n    if detect_outliers(df_winsorised, col)[2] > 0:\n        outliers=detect_outliers(df_winsorised, col, k)[2]\n        total+=outliers\n        print(\"{} outliers in '{}'\".format(outliers,col))\nprint(\"\\n{} OUTLIERS TOTALLY\".format(total))\nk=3\nprint(f\"Number of Outliers for {k}*IQR after Logarithmed\\n\")\n\ntotal=0\nfor col in features:\n    if detect_outliers(df_log, col)[2] > 0:\n        outliers=detect_outliers(df_log, col, k)[2]\n        total+=outliers\n        print(\"{} outliers in '{}'\".format(outliers,col))\nprint(\"\\n{} OUTLIERS TOTALLY\".format(total))\nz_scores=[]\nfor i in features:\n    z_scores.append(outlier_inspect(df,i)[2])\nz_scores\nfeatures\n# create columns for z scores, new column with z score\ndf_3z=df.copy()\n\nfor x in features:\n    df_3z[x + '_z'] = stats.zscore(df_3z[x])\n\nfor x in df_3z.columns[-len(features):]:\n    df_3z = df_3z[(df_3z[x] < 3) & (df_3z[x] > -3)]\n    \n# drop _z columns\ndf_3z = df_3z.drop(columns=df_3z.columns[-8:])\n\nprint('Number of Outliers:',len(df)-len(df_3z))\ndf_3z.describe().T.round(2)\ndf.describe().T.round(2)\n\"\"\"\n### Check Unique Values\n\"\"\"\n\"\"\"\nInvestigate the unique values of each column and look for error entries.\n\"\"\"\nsummary(df_3z)\n\"\"\"\n> Drop the columns that the number of uniques is 1\n\"\"\"\ndf_3z = df_3z.drop(['acetohexamide','glimepiride-pioglitazone','metformin-rosiglitazone'],axis=1)\n\"\"\"\n### Export Cleaned Dataset\n\"\"\"\ndf_3z = df_3z.reset_index(drop=True)\ndf_3z.to_csv('diabetic_data_cleaned.csv')\n\"\"\"\n# Visualization\n\"\"\"\n\"\"\"\n* We are looking for correlations between the independent variables and the target variable, the likelihood of being readmitted to the hospital, using graphs and plots. \n* This is also a good time to get a better understanding of patient demographics, their experiences at the hospital, medications being used \/ not used, and any diagnosed conditions.\n\"\"\"\n\"\"\"\n### Import Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 12,6\n\n# to avoid warnings\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.warn(\"this will not show\")\n\nsns.set(style='darkgrid')\n%matplotlib inline\n\"\"\"\n### Import Dataset\n\"\"\"\ndata = pd.read_csv('diabetic_data_cleaned.csv', index_col=0)\ndf = data.copy()\ndf.head()\nfeatures = pd.read_csv('features.csv',index_col='Unnamed: 0')\ninfo = lambda attribute:print(f\"{attribute.upper()} : {features[features['Feature']==attribute]['Description'].values[0]}\\n\")\nfeatures.head()\ndef summary(df, pred=None):\n    obs = df.shape[0]\n    Types = df.dtypes\n    Counts = df.apply(lambda x: x.count())\n    Min = df.min()\n    Max = df.max()\n    Uniques = df.apply(lambda x: x.unique().shape[0])\n    Nulls = df.apply(lambda x: x.isnull().sum())\n    print('Data shape:', df.shape)\n\n    if pred is None:\n        cols = ['Types', 'Counts', 'Uniques', 'Nulls', 'Min', 'Max']\n        str = pd.concat([Types, Counts, Uniques, Nulls, Min, Max], axis = 1, sort=True)\n\n    str.columns = cols\n    print('___________________________\\nData Types:')\n    print(str.Types.value_counts())\n    print('___________________________')\n    return str\n\nsummary(df)\nround(df.describe(), 2)\ndf.shape\nsns.pairplot(df, hue='readmitted');\nplt.figure(figsize=(20,10))\nsns.heatmap(df.corr(), annot=True, cmap=\"coolwarm\");\n\"\"\"\n### FOCUS ON \"readmitted\" patients overall\n\"\"\"\ninfo('readmitted')\ndef labels(ax):\n    for p in ax.patches:\n            ax.annotate('%{:.1f}\\n{:.0f}'.format(100*p.get_height()\/len(df),p.get_height()), \n                        (p.get_x()+0.3, p.get_height()-1900),size=11)\n\nax = sns.countplot(x='readmitted', palette='husl', data=df)\nlabels(ax)\n\n# sns.catplot(x='readmitted', kind='count', palette='husl', data=df)  # alternative\nplt.title('Readmit Rates')\nplt.show()\n\"\"\"\n### FOCUS ON \"race\"\n\"\"\"\ndef labels(ax):\n    for bar in ax.patches: \n        ax.annotate('%{:.1f}\\n{:.0f}'.format(100*bar.get_height()\/len(df),bar.get_height()), (bar.get_x() + bar.get_width() \/ 2,  \n                        bar.get_height()), ha='center', va='center', \n                       size=10, xytext=(0, 8), \n                       textcoords='offset points') \n\nrcParams['figure.figsize'] = 12,6\nax = sns.countplot(x='race', hue='readmitted', palette='husl', data=df)\nlabels(ax)\n# sns.catplot(x='race', hue='readmitted', kind='count', palette='husl', data=df, aspect=2, legend_out=False)\nplt.title('Patient Demographic Readmissions')\nplt.show()\npd.crosstab(df.race, df.readmitted, margins=True, margins_name='Total')\n\"\"\"\n### FOCUS ON \"gender\"\n\"\"\"\nrcParams['figure.figsize'] = 12,6\nax = sns.countplot(x='gender', hue='readmitted', palette='husl', data=df)\nlabels(ax)\nplt.title('Readmissions by Gender')\nplt.show()\npd.crosstab(df.gender, df.readmitted, margins=True, margins_name='Total')\n\"\"\"\n### FOCUS ON \"age\" groups\n\"\"\"\nax = sns.countplot(x='age', palette='husl', data=df.sort_values('age'))\nlabels(ax)\nplt.title('Patient Demographics')\nplt.show()\n\"\"\"\n> It looks like most patients are older, 50+ years old, though there aren't many patients over 90.\n\"\"\"\nax = sns.countplot(x='age', hue='readmitted', palette='husl', data=df.sort_values('age'))\nlabels(ax)\nplt.title('Readmits By Age Group')\nplt.show()\npd.crosstab(df.age, df.readmitted, margins=True, margins_name='Total').T\n\"\"\"\n>In every age group, more patients are not readmitted. The 70-80 age group account has the highest number of readmitted and not readmitted patients.\n\"\"\"\n\"\"\"\n### FOCUS ON \"time_in_hospital\"\n\"\"\"\nsns.countplot(x='time_in_hospital', palette='muted', data=df)\nmean, median = np.mean(df.time_in_hospital), np.median(df.time_in_hospital)\nplt.axvline(mean-df.time_in_hospital.min(), color='blue', label=f'mean:{round(mean,2)}')\nplt.axvline(median-df.time_in_hospital.min(), color='red', label=f'median:{round(median,2)}')\nplt.title('Duration of Hospital Visit in Days')\nplt.legend()\nplt.show()\n\"\"\"\n> **Does the amount of time spent in the hospital impact a patient's chances of readmission?**\n\"\"\"\nsns.catplot(x='time_in_hospital', hue='readmitted', kind='count', palette='husl', aspect=3, data=df, legend_out=False)\nplt.title('Readmission Based on Time in Hospital')\nplt.show()\nsns.displot(x='time_in_hospital', hue='readmitted', data=df, height=7, aspect=3)\nplt.title('Readmission Based on Time in Hospital')\nplt.show()\n\"\"\"\n> Based on the graph, the longer a patient spends in the hospital, the likelier their chances are of being readmitted. Patients who spend more than a week in the hospital usually have a serious illness or complication that may reoccur depending on their ability to recover, which is why they may need to revisit the hospital.\n\"\"\"\n\"\"\"\n> **Which age group is spending the most time in hospitals during visits?**\n\"\"\"\ndef box_labels(ax, df,col1,col2):\n    medians = df.groupby([col1])[col2].median()\n    vertical_offset = df[col2].median() * 0.05 # offset from median for display\n\n    for xtick in ax.get_xticks():\n        ax.text(xtick,medians[xtick] + vertical_offset,medians[xtick], \n                horizontalalignment='center',size='x-small',color='w',weight='semibold')\n\nax = sns.boxplot(x='age', y='time_in_hospital', data=df.sort_values('age'))\nbox_labels(ax, df.sort_values('age'),'age','time_in_hospital')    \nplt.title('Length of Hospital Stay Based on Age')\nplt.show()\n\"\"\"\n> **What is the comparison of time in hospital for readmitted patients?**\n\"\"\"\nax = sns.boxplot(x='readmitted', y='time_in_hospital', data=df.sort_values('readmitted'))\nbox_labels(ax, df.sort_values('readmitted'),'readmitted','time_in_hospital') \nplt.title('Length of Hospital Stay for Readmitted Patients')\nplt.show()\n\"\"\"\n> Readmitted patients stay longer in the hospital on average compared to those who are not readmitted.\n\"\"\"\n\"\"\"\n### FOCUS ON \"number of lab procedures`\n\"\"\"\ninfo(\"num_lab_procedures\")\nrcParams['figure.figsize'] = 25,10\nsns.countplot(x='num_lab_procedures', data=df)\nmean, median = np.mean(df.num_lab_procedures), np.median(df.num_lab_procedures)\nplt.axvline(mean-df.num_lab_procedures.min(), color='blue', label=f'mean:{round(mean,2)}')\nplt.axvline(median-df.num_lab_procedures.min(), color='black', label=f'median:{round(median,2)}')\nplt.title('Number of Lab Procedures Performed During Visit')\nplt.legend()\nplt.show()\ndf.groupby('readmitted')['num_lab_procedures'].describe().round(2)\n\"\"\"\n> **Do the patients with longer hospital stays have more lab tests?**\n\"\"\"\ndef box_labels(ax, df,col1,col2):\n    medians = df.groupby([col1])[col2].median()\n    vertical_offset = df[col2].median() * 0.05 # offset from median for display\n\n    for xtick in ax.get_xticks():\n        ax.text(xtick,medians[xtick] + vertical_offset,medians[xtick], \n                horizontalalignment='center',size=12,color='w',weight='semibold')\n\nax = sns.boxplot(x='time_in_hospital', y='num_lab_procedures', data=df.sort_values('time_in_hospital'))\n# box_labels(ax, df.sort_values('time_in_hospital'),'time_in_hospital','num_lab_procedures') \nplt.title('Lab Procedures Based on Length of Hospital Visit')\nplt.show()\n\"\"\"\n* There is a positive correlation between time spent in the hospital and number of lab tests completed. \n* This makes sense since patients with longer stays had more tests completed to properly diagnose their conditions.\n\"\"\"\n\"\"\"\n> **Do readmitted patients have more lab tests?**\n\"\"\"\nplt.figure(figsize=(10, 8))\nax = sns.boxplot(x='readmitted', y='num_lab_procedures', data=df.sort_values('readmitted'))\nbox_labels(ax, df.sort_values('readmitted'),'readmitted','num_lab_procedures') \nplt.title('Lab Procedures for Readmitted Patients')\nplt.show()\n\"\"\"\n* The average number of lab procedures is about equal for readmitted and not readmitted patients. \n* Not readmitted patients have a slightly lower number of lab procedures done during their visit.\n\"\"\"\n\"\"\"\n### FOCUS ON \"`number of procedures`\" (other than lab)\n\"\"\"\ninfo('num_procedures')\nsns.catplot(x='num_procedures', kind='count', palette='muted', data=df)\nmean, median = np.mean(df.num_procedures), np.median(df.num_procedures)\nplt.axvline(mean, color='blue', label=f'mean:{round(mean,2)}')\nplt.axvline(median, color='black', label=f'median:{round(median,2)}')\nplt.title('Number of Procedures Performed (Except Lab)')\nplt.legend()\nplt.show()\n\"\"\"\n> **Do the number of tests performed indicate whether a patient will be readmitted?**\n\"\"\"\ndef labels(ax):\n    for bar in ax.patches: \n        ax.annotate('%{:.1f}\\n{:.0f}'.format(100*bar.get_height()\/len(df),bar.get_height()), (bar.get_x() + bar.get_width() \/ 2,  \n                        bar.get_height()-400), ha='center', va='center', \n                       size=14, xytext=(0, 8), \n                       textcoords='offset points') \n        \nax = sns.countplot(x='num_procedures', hue='readmitted', palette='husl', data=df)\nlabels(ax)\nplt.title('Readmits Based on Procedures (Sans Lab)')\nplt.show()\n\"\"\"\n### FOCUS ON \"number of medications\"\n\"\"\"\ninfo('num_medications')\nrcParams['figure.figsize'] = 25,10\nsns.countplot(x='num_medications', data=df)\nmean, median = np.mean(df.num_medications), np.median(df.num_medications)\nplt.axvline(mean-df.num_medications.min(), color='blue', label=f'mean:{round(mean,2)}')\nplt.axvline(median-df.num_medications.min(), color='black', label=f'median:{round(median,2)}')\nplt.title('Number of Distinct Generic Medications Administered During Visit')\nplt.legend()\nplt.show()\ndf.groupby('readmitted')['num_medications'].describe()\n\"\"\"\n> **How many medications are patients receiving during their visit?**\n\"\"\"\nax = sns.boxplot(x='time_in_hospital', y='num_medications', data=df)\n# box_labels(ax, df.sort_values('time_in_hospital'),'time_in_hospital','num_medications')\nplt.title('Medications Administered Based on Length of Hospital Visit')\nplt.show()\n\"\"\"\n> Patients who spend more time in the hospital receive more medications, but there are a few that receive over 60 different kinds of medications.\n\"\"\"\n\"\"\"\n> **How many medications are patients receiving during their visit?**\n\"\"\"\nax = sns.boxplot(x='readmitted', y='num_medications', data=df.sort_values('readmitted'))\nbox_labels(ax, df.sort_values('readmitted'),'readmitted','num_medications')\nplt.title('Medications Administered')\nplt.show()\n\"\"\"\n> The distribution is almost equal for readmitted and not readmitted patients, with readmits being slightly higher on average.\n\"\"\"\n\"\"\"\n### FOCUS ON \"`number of outpatient`\" visits\n\"\"\"\ninfo('number_outpatient')\ndef labels(ax):\n    for bar in ax.patches: \n        ax.annotate('%{:.1f}\\n{:.0f}'.format(100*bar.get_height()\/len(df),bar.get_height()), (bar.get_x() + bar.get_width() \/ 2,  \n                        bar.get_height()+750), ha='center', va='center', \n                       size=16, xytext=(0, 8), \n                       textcoords='offset points') \n        \nax = sns.countplot(x='number_outpatient',data=df)\nlabels(ax)\nplt.title('Number of Outpatient Visits Prior to Encounter')\nplt.show()\n# outpatient visit stats\ndf.groupby('readmitted')['number_outpatient'].describe()\n# outpatient vists and readmissions\nax = sns.countplot(x='number_outpatient',data=df, hue='readmitted')\nlabels(ax)\nplt.title('Outpatient Vists and Readmissions')\nplt.show()\npd.crosstab(df.readmitted, df.number_outpatient, margins=True, margins_name='Total')\n\"\"\"\n> Most patients did not have any outpatient visits prior to the recorded one.\n\"\"\"\n\"\"\"\n### FOCUS ON \"`number of emergency`\" visits\n\"\"\"\ninfo('number_emergency')\n# plt.figure(figsize=(20,5))\nax = sns.countplot(x='number_emergency', data=df)\nlabels(ax)\nplt.title('Number of Emergency Visits Prior to Encounter')\nplt.show()\n# emergency vists and readmissions\nax = sns.countplot(x='number_emergency', hue='readmitted', data=df)\nlabels(ax)\nplt.title('Emergency Vists and Readmissions')\nplt.show()\n\"\"\"\n> Most patients did not visit the emergency room prior to their recorded visit.\n\"\"\"\npd.crosstab(df.readmitted, df.number_emergency, margins=True, margins_name='Total')\n\"\"\"\n> **How many emergency visits did patients have prior to this visit?**\n\"\"\"\nplt.figure(figsize=(5, 5))\nsns.boxplot(x='readmitted', y='number_emergency', data=df)\nplt.title('Readmits for Emergency Vists')\nplt.show()\n\"\"\"\n### FOCUS ON \"`number of inpatient`\" visits\n\"\"\"\ninfo('number_inpatient') # onceki yildaki yatarak tedavi sayisi\nax = sns.countplot(x='number_inpatient',data=df)\nlabels(ax)\nplt.title('Number of Inpatient Visits Prior to Encounter')\nplt.show()\n# inpatient visits and readmissions\nax = sns.countplot(x='number_inpatient', hue='readmitted',data=df)\nlabels(ax)\nplt.title('Inpatient Visits and Readmissions')\nplt.show()\n\"\"\"\n> Inpatient visits are not common for most patients prior to this visit.\n\"\"\"\npd.crosstab(df.readmitted, df.number_inpatient, margins=True, margins_name='Total')\n\"\"\"\n### FOCUS ON \"`number of diagnoses`\"\n\"\"\"\ninfo('number_diagnoses')\nax = sns.countplot(x='number_diagnoses',data=df)\nmean, median = np.mean(df.number_diagnoses), np.median(df.number_diagnoses)\nplt.axvline(mean-df.number_diagnoses.min(), color='blue', label=f'mean:{round(mean,2)}')\nplt.axvline(median-df.number_diagnoses.min(), color='red', label=f'median:{round(median,2)}')\nplt.title('Number of Diagnoses')\nplt.legend()\nplt.show()\n# number of diagnoses and readmit rate\nax = sns.countplot(x='number_diagnoses', hue='readmitted', palette='Accent', data=df)\n# labels(ax)\nplt.title('Readmits By Number of Diagnoses')\nplt.show()\npd.DataFrame(df.number_diagnoses.describe()).T.round(2)\ndf.groupby('readmitted')['number_diagnoses'].describe().round(2)\n# number of diagnoses\npd.crosstab(df.readmitted, df.number_diagnoses, margins=True, margins_name='Total')\n\"\"\"\n* Most patients have up to nine diagnosed conditions during their visit, after that, only a handful have more than nine in one visit. \n* Readmitted patients tend to have more diagnosed conditions but their average is only slightly higher than those not readmitted.\n\"\"\"\n\"\"\"\n> **How many diagnoses do readmitted patients have?**\n\"\"\"\nplt.figure(figsize=(8, 6))\nax = sns.boxplot(x='readmitted', y='number_diagnoses', data=df.sort_values('readmitted'))\nbox_labels(ax, df.sort_values('readmitted'),'readmitted','number_diagnoses')\nplt.title('Number of Diagnoses for Re\/admitted Patients')\nplt.show()\n\"\"\"\n# FOCUS ON \"`glucose serum test results`\"\n\"\"\"\ninfo('max_glu_serum')\nax = sns.countplot(x='max_glu_serum', data=df)\nlabels(ax)\nplt.title('Glucose Serum Test Results')\nplt.show()\n\"\"\"\n> Since the majority of patients do not have a glucose reading, they will be excluded for the next graph in order to show the readmit rates for patients who do have a reading.\n\"\"\"\ndef labels(ax, df=df):\n    for p in ax.patches:\n            ax.annotate('%{:.1f}\\n{:.0f}'.format(100*p.get_height()\/len(df),p.get_height()), \n                        (p.get_x()+0.2, p.get_height()-27),size=16)\n\n# exclude patients without a glucose reading\nglucose_none = df[df.max_glu_serum != 'None']\n\n# glucose serum results and readmit impact\nax = sns.countplot(x='max_glu_serum', hue='readmitted', palette='Accent', data=glucose_none)\nlabels(ax,glucose_none)\nplt.title('Readmits By Glucose Serum Levels')\nplt.show()\n\"\"\"\nPatients with a glucose serum reading of over 300 have a 50-50 chance of being readmitted. High blood sugar levels are often dangerous for older patients due to the medical complications involved, so it's understandable that more patients return to the hospital for additional care.\n\"\"\"\n\npd.crosstab(df.readmitted, df.max_glu_serum, margins=True, margins_name='Total')\n\"\"\"\nGlikoz serum okumas\u0131 300'\u00fcn \u00fczerinde olan hastalar\u0131n readmit orani 50-50'dir. Y\u00fcksek kan \u015fekeri seviyeleri, t\u0131bbi komplikasyonlar nedeniyle genellikle ya\u015fl\u0131 hastalar i\u00e7in tehlikelidir, bu nedenle daha fazla hastan\u0131n ek bak\u0131m i\u00e7in hastaneye d\u00f6nmesi anla\u015f\u0131labilir bir durumdur.\n\"\"\"\n\"\"\"\n### FOCUS ON \"`A1C results`\"\n\"\"\"\ninfo('A1Cresult')\nax = sns.countplot(x='A1Cresult', palette='husl', data=df)\nlabels(ax)\nplt.title('A1c Test Results')\nplt.show()\n\"\"\"\n* Similar to the glucose reading, the majority of patients also do not have a HbA1c test reading. \n* In order to understand the impact of A1c tests on readmit rates, patients without a reading will be excluded in the graph below.\n\"\"\"\n# exclude patients without an A1C reading\nalc_none = df[df.A1Cresult != 'None']\n\n# A1C results and readmit impact\nax = sns.countplot(x='A1Cresult', hue='readmitted', palette='Accent', data=alc_none)\nlabels(ax, alc_none)\nplt.title('Readmits By A1C Test Results')\nplt.show()\npd.crosstab(df.readmitted, df.A1Cresult, margins=True, margins_name='Total')\n\"\"\"\n### FOCUS ON \"`change`\" column\n\"\"\"\ninfo('change')\n\"\"\"\n## change in medications, dosage or brand\n\"\"\"\n# change in medications\nax = sns.countplot(x='change', hue='readmitted', data=df)\nlabels(ax)\nplt.title('Change in Diabetic Medications')\nplt.show()\npd.crosstab(df.change, df.readmitted, margins=True, margins_name='Total')\n\"\"\"\n> **who is likely to have a change in medication?**\n\"\"\"\nax = sns.countplot(x='gender', hue='change', palette='Set2', data=df)\nlabels(ax)\nplt.title('Change in Medication Based on Gender')\nplt.show()\npd.crosstab(df.gender, df.change, margins=True, margins_name='Total')\n\"\"\"\n### FOCUS ON \"`diabetesMed`\"\n\"\"\"\ninfo('diabetesMed')\nax = sns.countplot(x='diabetesMed', hue='readmitted', data=df)\nlabels(ax)\nplt.title('Prescribed Diabetic Medications During Visit')\nplt.show()\npd.crosstab(df.diabetesMed, df.readmitted, margins=True, margins_name='Total')\n\"\"\"\n> **Who is likely or not likely to have a change in medication?**\n\"\"\"\nsns.catplot(x='diabetesMed', hue='readmitted', col='gender', palette='Accent', data=df, kind='count', height=4, aspect=1)\nplt.show()\n\"\"\"\n### medications used by patients\n\"\"\"\ncolumns=['metformin', 'repaglinide', 'nateglinide',\n       'chlorpropamide', 'glimepiride', 'glipizide', 'glyburide',\n       'tolbutamide', 'pioglitazone', 'rosiglitazone', 'acarbose', 'miglitol',\n       'troglitazone', 'tolazamide', 'insulin', 'glyburide-metformin',\n       'glipizide-metformin', 'metformin-pioglitazone']\n\nplt.figure(figsize=(26, 26))\nfor i,col in enumerate(columns):\n    plt.subplot(6,3,i+1)\n    sns.countplot(x=df[col])\n\"\"\"\n> Dosages for insulin shows the most activity out of all diabetic medications, most of which aren't prescribed to patients.\n\"\"\"\ninfo('insulin')\nsns.countplot(x='insulin', hue='readmitted', data=df)\nplt.title('Readmit Rates by Medication: Insulin')\nplt.show()\n\"\"\"\n# General Overview - Statistical Analysis\n\"\"\"\n\"\"\"\n* We want to analyze the variables in this dataset to understand any relationships between them and their overall effects.\n* To do this,\n        * `Chi-square test` for categorical variables relationship\n        * We have to analyze numerical variables using `analysis of variance` or `ANOVA test`.\n* The purpose of these tests is to determine whether there is a statistically significant relationship between the target variable, readmissions and independent variable. Our p-value is 0.01, if anything above that, we cannot reject the null hypothesis.\n* A machine learning model can interpret integers as well as process strings, so we must transform all categorical variables using dummy variables as numeric variables. This takes the string values \u200b\u200bin a variable and converts them to columns labeled 0 or 1 relative to the string. We will also standardize the original numerical variables with a mean of 0 and a standard deviation of 1.\n* Finally, we look at the correlation coefficients between the independent variables to make sure they do not have a strong influence on each other. The threshold we used is -0.7 <x <0.7.\n\n\n\"\"\"\n\"\"\"\n### Import Libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 12,6\n\n# to avoid warnings\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.warn(\"this will not show\")\n\nsns.set(style='darkgrid')\n%matplotlib inline\n\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nfrom scipy.stats import chi2_contingency\nfrom numpy.random import seed\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\ndata = pd.read_csv('diabetic_data_cleaned.csv', index_col=0) # import data\ndf = data.copy() # save a copy of data as diabetes\nfeatures = pd.read_csv('features.csv',index_col='Unnamed: 0')\ninfo = lambda attribute:print(f\"{attribute.upper()} : {features[features['Feature']==attribute]['Description'].values[0]}\\n\")\ndef summary(df, pred=None):\n    obs = df.shape[0]\n    Types = df.dtypes\n    Counts = df.apply(lambda x: x.count())\n    Min = df.min()\n    Max = df.max()\n    Uniques = df.apply(lambda x: x.unique().shape[0])\n    Nulls = df.apply(lambda x: x.isnull().sum())\n    print('Data shape:', df.shape)\n\n    if pred is None:\n        cols = ['Types', 'Counts', 'Uniques', 'Nulls', 'Min', 'Max']\n        str = pd.concat([Types, Counts, Uniques, Nulls, Min, Max], axis = 1, sort=True)\n\n    str.columns = cols\n    print('___________________________\\nData Types:')\n    print(str.Types.value_counts())\n    print('___________________________')\n    return str\n\nsummary(df)\ndf.describe().round(2).T\nplt.figure(figsize=(6,6))\n\nexplode = [0,0.1]\nplt.pie(df['readmitted'].value_counts(),explode=explode,autopct='%1.1f%%',shadow=True,startangle=60)\nplt.legend(labels=df.readmitted.value_counts().index)\nplt.title('Readmitted Patients')\nplt.axis('off')\nplt.show()\n\"\"\"\n## Feature Selection\n![How-to-Choose-Feature-Selection-Methods-For-Machine-Learning.png](attachment:How-to-Choose-Feature-Selection-Methods-For-Machine-Learning.png)\n\"\"\"\n\"\"\"\n### categorical variables\n\"\"\"\nprint('Unique Values of Each Features:\\n')\nfor i in df:\n    print(f'{i}:\\n{sorted(df[i].unique())}\\n')\ncategorical=df.select_dtypes(include='object').columns.tolist()\nprint(categorical)\n\"\"\"\n* The categorical variables are: \n<br>`['race', 'gender', 'age', 'diag_1', 'max_glu_serum', 'A1Cresult', 'metformin', 'repaglinide', 'nateglinide', 'chlorpropamide', 'glimepiride', 'glipizide', 'glyburide', 'tolbutamide', 'pioglitazone', 'rosiglitazone', 'acarbose', 'miglitol', 'troglitazone', 'tolazamide', 'insulin', 'glyburide-metformin', 'glipizide-metformin', 'metformin-pioglitazone', 'change', 'diabetesMed', 'readmitted']`\n\n\n* We are using the chi-square test for association with a p-value of 0.01 to reject the null hypothesis.\n\"\"\"\n\"\"\"\n## chi-square test for association\n\"\"\"\n# define a function that returns a table, a chi-square value, and a p value\ndef chisquare_test(df, var_list, target, null_list=[]):\n    for var in var_list:\n        print(var.upper())\n        chi_test = pd.crosstab(df[var], df[target])\n        display(chi_test)\n    \n        chisq_value, pvalue, dataframe, expected = chi2_contingency(chi_test)\n    \n        print(f\"\"\"Chi-square value: {chisq_value:.2f}\np-value\\t\\t: {pvalue:.3f}\\n\"\"\")\n        \n        if pvalue > 0.01: # adds variables that fail to reject the null hypothesis\n            null_list.append(var)\n            \n    print(f'Fail to reject null hypothesis: {null_list}')\ncols_cat = ['race','gender', 'age', 'diag_1', 'max_glu_serum', 'A1Cresult', 'change', 'diabetesMed']\nnull_list=[]\nchisquare_test(df, cols_cat,'readmitted',null_list)\n\"\"\"\n> Based on the chi-square value and p-value, we can safely say that there is no relation between the independent variables and the target variable.\n\"\"\"\n\"\"\"\n### medications\n\"\"\"\nmedications = ['metformin', 'repaglinide', 'nateglinide', 'chlorpropamide', 'glimepiride', \n            'glipizide', 'glyburide', 'tolbutamide', 'pioglitazone', \n               'rosiglitazone', 'acarbose', 'miglitol', 'troglitazone', 'tolazamide', \n               'insulin', 'glyburide-metformin', 'glipizide-metformin', 'metformin-pioglitazone']\nchisquare_test(df, medications,'readmitted', null_list)\n\"\"\"\n* The medications: nateglinide, chlorpropamide, glimepiride, acetohexamide, glyburide, tolbutamide, miglitol, troglitazone, tolazamide, glyburide-metformin, glipizide-metformin, and metformin-pioglitazone all failed to pass the test since they have p-values greater than 0.01.\n\n* Since these variables are not independent of the target variable, we are removing them from the dataset.\n\"\"\"\nprint(null_list)\n# drop columns that do not pass the p-value test\ndf = df.drop(columns=null_list)\n\"\"\"\n# numerical variables\n\"\"\"\n\"\"\"\n## statistical testing - analysis of variance (ANOVA)\n\"\"\"\n\"\"\"\n![one-way-ANOVA-formulas.png](attachment:one-way-ANOVA-formulas.png)\n\"\"\"\n# The numerical variables \nnumerical=df.select_dtypes(include=['int64','float']).columns.tolist()\nprint(numerical)\n\"\"\"\n* Using the analysis of variance (ANOVA) test, we want to determine if there is a statistically significant relationship between a numerical variable and the categorical target variable. Our p-value threshold is 0.01.\n\"\"\"\ndf.describe().T.round(2)\n# define a function that performs the ANOVA test and returns a table\ndef anova_table(var_list, null_list=[]):\n    for var in var_list:\n        print(var.upper())\n        \n        anova = ols('time_in_hospital ~ {}'.format(var), data=df).fit()\n        table = sm.stats.anova_lm(anova, typ=2)\n        pvalue=table['PR(>F)'][0]\n        if pvalue > 0.01: # adds variables that fail to reject the null hypothesis\n            null_list.append(var)\n        display(table)\n    print(f'Fail to reject null hypothesis: {null_list}')\nanova_vars = ['readmitted']+numerical\nanova_table(anova_vars)\n\"\"\"\n> Based on the ANOVA test, we can drop the number of emergency visits since we cannot reject the null hypothesis that the averages for each class are similar, the p-value is greater than our threshold of 0.01.\n\"\"\"\n# drop number_emergency column\ndf = df.drop(columns=['number_emergency'])\n\"\"\"\n# One Hot Encoding\n\"\"\"\n\"\"\"\nBinary columns will be replaced with 0 for No and 1 for Yes. In the gender column, Male and Female will be replaced with 0 and 1 respectively.\n\"\"\"\n# Unique Values of Each Features\nfor i in df:\n    print(f'{i}:\\n{sorted(df[i].unique())}\\n')\ndf_dummy = pd.get_dummies(df,drop_first=True)\ndf_dummy.head()\n\"\"\"\n# Are the features that affect readmissions correlated with each other?\n\"\"\"\n\"\"\"\nIf the correlation value is greater than 0.7 or less than -0.7, we have to drop one of the two columns.\n\nThe correlation map is quite large for this notebook. Instead, we are going to find each correlation coefficient individually and mark the ones that have a coefficient greater than 0.7 or less than -0.7.\n\"\"\"\nplt.figure(figsize=(20,5))\ndf_dummy.corr()[\"readmitted_YES\"].sort_values()[:-1].plot.bar();\nplt.figure(figsize=(20,20))\nsns.heatmap(df_dummy.corr(), cmap=\"coolwarm\");\ndef corrank(X, threshold=0):\n    import itertools\n    df = pd.DataFrame([[i,j,X.corr().abs().loc[i,j]] for i,j in list(itertools.combinations(X.corr().abs(), 2))],columns=['Feature1','Feature2','corr'])    \n    df = df.sort_values(by='corr',ascending=False).reset_index(drop=True)\n    return df[df['corr']>threshold]\n\n# prints a descending list of correlation pair (Max on top)\ncorrank(df_dummy, 0.7)\n# Remove the highly collinear features from data\ndef remove_collinear_features(x, threshold):\n    # Calculate the correlation matrix\n    corr_matrix = x.corr()\n    iters = range(len(corr_matrix.columns) - 1)\n    drop_cols = []\n\n    # Iterate through the correlation matrix and compare correlations\n    for i in iters:\n        for j in range(i+1):\n            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]\n            col = item.columns\n            row = item.index\n            val = abs(item.values)\n\n            # If correlation exceeds the threshold\n            if val >= threshold:\n                # Print the correlated features and the correlation value\n                print(col.values[0], \"|\", row.values[0], \"|\", round(val[0][0], 2))\n                drop_cols.append(col.values[0])\n\n    # Drop one of each pair of correlated columns\n    drops = set(drop_cols)\n    x = x.drop(columns=drops)\n\n    return x\n#Remove columns having more than 70% correlation\n#Both positive and negative correlations are considered here\ndf_dummy = remove_collinear_features(df_dummy,0.70)\ndf_dummy.shape\n\"\"\"\n# saving machine learning dataset\n\"\"\"\n# save dataset to new file for machine learning\ndf_dummy.to_csv('diabetic_data_cleaned_dummy.csv')\n\"\"\"\n# General Overview - Machine Learning\n\"\"\"\n\"\"\"\n### Import and Load\n\"\"\"\n# for basic operations\nimport numpy as np \nimport pandas as pd \n\n# for visualizations\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pylab import rcParams\n# rcParams['figure.figsize'] = 4,4\n# plt.style.use('fivethirtyeight')\n\nfrom collections import Counter\n\n# for modeling \nimport sklearn\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report, plot_precision_recall_curve, precision_recall_curve\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV, cross_val_score, train_test_split, KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import datasets, metrics\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\n\nimport imblearn\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import SMOTE\n\n# to avoid warnings\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.warn(\"this will not show\")\ndata = pd.read_csv('diabetic_data_cleaned_dummy.csv', index_col=0)\ndf = data.copy()\n\ndf.head()\n\"\"\"\n### Lazy Predict with 5000 samples\n\"\"\"\nfrom lazypredict.Supervised import LazyClassifier\n\ndf_5000 = df.sample(5000,random_state=42)\ny = df_5000['readmitted_YES']\nX = df_5000.drop('readmitted_YES', axis=1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state =42)\n\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\nclf = LazyClassifier(verbose=0,ignore_warnings=True, custom_metric=None)\nmodels,predictions = clf.fit(X_train, X_test, y_train, y_test)\nmodels\n\"\"\"\n### Split Data\n\"\"\"\nax = df['readmitted_YES'].value_counts(normalize=True).plot.bar()\ndef labels(ax):\n    for p in ax.patches:\n        ax.annotate(f\"%{p.get_height()*100:.2f}\", (p.get_x() + 0.15, p.get_height() * 1.005),size=11)\nlabels(ax)\n# separating the dependent and independent data\nX = df.drop('readmitted_YES', axis=1)\ny = df['readmitted_YES']\n\n# the function train_test_split creates random data samples (default: 75-25%)\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)\n\n# getting the shapes\nprint(f\"\"\"shape of X_train: {X_train.shape}\nshape of X_test\\t: {X_test.shape}\nshape of y_train: {y_train.shape}\nshape of y_test\\t: {y_test.shape}\"\"\")\n\"\"\"\n### Data Scaling\n\"\"\"\n# creating a standard scaler\nsc = StandardScaler()\n\n# fitting independent data to the model\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\"\"\"\n### Iteration 1: (Unbalanced data)\n![CM-1024x382.png](attachment:CM-1024x382.png)\n\"\"\"\ncv_acc_train = {}\ncv_acc_test = {}\ncv_TPR = {}\ncv_FPR = {}\ncv_AUC = {}\ndef plot_result(model, name:str):\n    model.fit(X_train, y_train)\n    y_pred = model.predict(X_test)\n\n    # Evaluation based on a 10-fold cross-validation\n    scoring = ['balanced_accuracy', 'recall_macro']\n    scores_train = cross_val_score(model, X_train, y_train, cv=10, scoring = 'balanced_accuracy')\n    scores_test = cross_val_score(model, X_test, y_test, cv=10, scoring = 'balanced_accuracy')  \n    cv_acc_train[name] = round(scores_train.mean(), 4)*100  # balanced accuracy\n    cv_acc_test[name] = round(scores_test.mean(), 4)*100  # balanced accuracy\n    cv_TPR[name] = (confusion_matrix(y_test, y_pred)[1][1]\/confusion_matrix(y_test, y_pred)[1].sum())*100  # recall (Max)\n    cv_FPR[name] = (confusion_matrix(y_test, y_pred)[0][1]\/confusion_matrix(y_test, y_pred)[0].sum())*100  # fallout (Min)\n    \n    # accuracy scores\n    print('Average Balanced Accuracy (CV=10), Test Set:', scores_test.mean())  \n    print('Average Balanced Accuracy (CV=10), Training Set: ', scores_train.mean())\n\n    # print classification report\n    print(classification_report(y_test, y_pred, zero_division=0))\n\n    # Plot Confusion Matrix\n    plot_confusion_matrix(model, X_test, y_test)\n    plt.show()\n\"\"\"\n### 1-Decision tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import plot_confusion_matrix, classification_report, confusion_matrix\ndtc = DecisionTreeClassifier()\nplot_result(dtc, \"dtc\")\n# plot tree\n# plt.figure(figsize=(16,6))\n# plot_tree(dtc, filled = True, class_names=[\"-1\", \"1\"], feature_names=X.columns, fontsize=11);\ncv_acc_train, cv_acc_test, cv_TPR, cv_FPR\n\"\"\"\n### 2-Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\nplot_result(lr, \"lr\")\n\"\"\"\n### 3-SVC\n\"\"\"\n# svc = SVC(probability=True)  # default values\n# plot_result(svc, \"svc\")\n\"\"\"\n### 4-NearestCentroid\n\"\"\"\nfrom sklearn.neighbors import NearestCentroid\nfrom sklearn.metrics import plot_confusion_matrix, classification_report, confusion_matrix\nnc = NearestCentroid()\nplot_result(nc, \"nc\")\n\"\"\"\n### 5-Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier()\nplot_result(rfc, \"rfc\")\ndef plot_feature_importances(model):\n    feature_imp = pd.Series(model.feature_importances_,index=X.columns).sort_values(ascending=False)[:10]\n\n    sns.barplot(x=feature_imp, y=feature_imp.index)\n    plt.title(\"Feature Importance\")\n    plt.show()\n\n    print(f\"Top 10 Feature Importance for {str(model).split('(')[0]}\\n\\n\",feature_imp[:10],sep='')\nplot_feature_importances(rfc)\n\"\"\"\n### 6-Gradient Boosting\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingClassifier\ngbc = GradientBoostingClassifier(random_state=42)\nplot_result(gbc, \"gbc\")\nplot_feature_importances(gbc)\n\"\"\"\n### 7-Naive Bayes\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nnb = GaussianNB()\nplot_result(nb, \"nb\")\n\"\"\"\n### 8-kNN\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\nplot_result(knn, \"knn\")\n\"\"\"\n### 9-XGBOOST\n\"\"\"\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV, cross_val_score\nxgb = XGBClassifier(eval_metric = \"logloss\")\nplot_result(xgb, \"xgb\")\nplot_feature_importances(xgb)\nfrom xgboost import plot_importance\nplot_importance(xgb,max_num_features=10)\nplt.xlabel('The F-Score for each features')\nplt.ylabel('Importances')\nplt.show()\n\"\"\"\n### Evaluation (iteration 1)\n\"\"\"\n\ndef AUC(cv_AUC, X_test=X_test):\n    dtc_auc= roc_auc_score(y_test,dtc.predict(X_test)) #Decision Tree Classifier\n    lr_auc= roc_auc_score(y_test, lr.decision_function(X_test))#logistic regression\n#     svc_auc= roc_auc_score(y_test, svc.decision_function(X_test))#Support Vector Classifier\n    nc_auc= roc_auc_score(y_test, nc.predict(X_test))#Nearest Centroid Classifier\n    rfc_auc= roc_auc_score(y_test, rfc.predict_proba(X_test)[:,1])#Randomforest Classifier\n    gbc_auc= roc_auc_score(y_test, gbc.predict_proba(X_test)[:,1])#GradientBoosting Classifier\n    nb_auc= roc_auc_score(y_test, nb.predict_proba(X_test)[:,1])#Naive Bayes Classifier\n    knn_auc= roc_auc_score(y_test, knn.predict(X_test))#KNeighbors Classifier\n    xgb_auc= roc_auc_score(y_test, xgb.predict_proba(X_test)[:,1])#XGBoost Classifier\n\n    cv_AUC={'dtc': dtc_auc,\n           'lr': lr_auc,\n#            'svc':svc_auc,\n           'nc':nc_auc,\n           'rfc':rfc_auc,\n           'gbc':gbc_auc,\n           'nb':nb_auc,\n           'knn':knn_auc,\n           'xgb':xgb_auc}\n    return cv_AUC\ncv_AUC = AUC(cv_AUC)\ndf_eval = pd.DataFrame(data={'model': list(cv_acc_test.keys()), \n                             'bal_acc_train':list(cv_acc_train.values()),\n                             'bal_acc_test': list(cv_acc_test.values()), \n                             'recall': list(cv_TPR.values()), \n                             'fallout':list(cv_FPR.values()),\n                              'AUC': list(cv_AUC.values())}).round(2)\ndf_eval\ndef plot_ROC(X_test=X_test, y_test=y_test):\n    fpr_dtc, tpr_dtc, thresholds = roc_curve(y_test,dtc.predict(X_test)) #Decision Tree Classifier\n    fpr_lr, tpr_lr, thresholds = roc_curve(y_test, lr.decision_function(X_test))#logistic regression\n#     fpr_svc, tpr_svc, thresholds = roc_curve(y_test, svc.decision_function(X_test))#Support Vector Classifier\n    fpr_nc, tpr_nc, thresholds = roc_curve(y_test, nc.predict(X_test))#Nearest Centroid Classifier\n    fpr_rfc, tpr_rfc, thresholds = roc_curve(y_test, rfc.predict_proba(X_test)[:,1])#Randomforest Classifier\n    fpr_gbc, tpr_gbc, thresholds = roc_curve(y_test, gbc.predict_proba(X_test)[:,1])#GradientBoosting Classifier\n    fpr_nb, tpr_nb, thresholds = roc_curve(y_test, nb.predict_proba(X_test)[:,1])#Naive Bayes Classifier\n    fpr_knn, tpr_knn, thresholds = roc_curve(y_test, knn.predict(X_test))#KNeighbors Classifier\n    fpr_xgb, tpr_xgb, thresholds = roc_curve(y_test, xgb.predict_proba(X_test)[:,1])#XGBoost Classifier\n\n    #compare the ROC curve between different models\n    plt.figure(figsize=(10,10))\n    plt.plot(fpr_dtc, tpr_dtc, label='Decision Tree Classifier')\n    plt.plot(fpr_lr, tpr_lr, label='Logistic Regression')\n#     plt.plot(fpr_svc, tpr_svc, label='Support Vector Classifier')\n    plt.plot(fpr_nc, tpr_nc, label='Nearest Centroid Classifier')\n    plt.plot(fpr_rfc, tpr_rfc, label='Randomforest Classifier')\n    plt.plot(fpr_gbc, tpr_gbc, label='GradientBoosting Classifier')\n    plt.plot(fpr_nb, tpr_nb, label='Naive Bayes Classifier')\n    plt.plot(fpr_knn, tpr_knn, label='KNeighbors Classifier')\n    plt.plot(fpr_xgb, tpr_xgb, label='XGBoost Classifier')\n\n    plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n             label='random', alpha=.8)\n    plt.xlim([0,1])\n    plt.ylim([0,1])\n    plt.xticks(np.arange(0,1.1,0.1))\n    plt.yticks(np.arange(0,1.1,0.1))\n    plt.grid()\n    plt.legend()\n    plt.axes().set_aspect('equal')\n    plt.xlabel('False Positive Rate')\n    plt.ylabel('True Positive Rate')\n\nplot_ROC()\nfig, ax = plt.subplots(1,4, figsize=(20, 4))\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0])\nax[0].set_title(\"Unbalanced Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[1])\nax[1].set_title(\"Unbalanced Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[2])\nax[2].set_title(\"Unbalanced Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[3])\nax[3].set_title(\"Unbalanced Test FPR\")\nplt.show()\n\"\"\"\n> NaiveBayes gave high BalanceAccuracy and TPR_Score (Recall), but it gave the poor FPR_Score (Fallout) in this unbalanced data set.\n\"\"\"\n\"\"\"\n### Iteration 2: (Oversampling with SMOTE)\n\"\"\"\n\"\"\"\n![resampling-techniques-in-machine-learning-15-638.jpg](attachment:resampling-techniques-in-machine-learning-15-638.jpg)\n\"\"\"\n\"\"\"\n### Balancing data\n\"\"\"\ny_test.value_counts(normalize=True)\ny_train.value_counts(normalize=True)\n# pip install imblearn\nfrom imblearn import under_sampling, over_sampling\nfrom imblearn.over_sampling import SMOTE\noversmote = SMOTE()\nX_train_os, y_train_os= oversmote.fit_resample(X_train, y_train)\nax = y_train_os.value_counts().plot.bar(color=[\"blue\", \"red\"])\ndef labels(ax):\n    for p in ax.patches:\n        ax.annotate(f\"{p.get_height()}\", (p.get_x() + 0.15, p.get_height()+200),size=8)\nlabels(ax)\nplt.show()\nX_train_os.shape\n\"\"\"\n### Use algorithms\n\"\"\"\ncv_acc_balance_train = {}\ncv_acc_balance_test = {}\ncv_TPR_balance = {}\ncv_FPR_balance = {}\ncv_AUC_balance = {}\ndef plot_result_smote(model, name:str):\n    model.fit(X_train_os, y_train_os)\n    y_pred = model.predict(X_test)\n\n    # Evaluation based on a 10-fold cross-validation\n    scoring = ['balanced_accuracy', 'recall_macro']\n    scores_train = cross_val_score(model, X_train, y_train, cv=10, scoring = 'balanced_accuracy')\n    scores_test = cross_val_score(model, X_test, y_test, cv=10, scoring = 'balanced_accuracy')\n    cv_acc_balance_train[name] = round(scores_train.mean(), 4)*100  # balanced accuracy\n    cv_acc_balance_test[name] = round(scores_test.mean(), 4)*100  # balanced accuracy\n    cv_TPR_balance[name] = (confusion_matrix(y_test, y_pred)[1][1]\/confusion_matrix(y_test, y_pred)[1].sum())*100  # recall (max)\n    cv_FPR_balance[name] = (confusion_matrix(y_test, y_pred)[0][1]\/confusion_matrix(y_test, y_pred)[0].sum())*100  # fallout (min)\n    \n    # accuracy scores\n    print('Average Balanced Accuracy (CV=10), Test Set:', scores_test.mean())  \n    print('Average Balanced Accuracy (CV=10), Training Set: ', scores_train.mean())\n\n    # print classification report\n    print(classification_report(y_test, y_pred, zero_division=0))\n\n    # Plot Confusion Matrix\n    plot_confusion_matrix(model, X_test, y_test)\n    plt.show()\n# Decision tree\ndtc = DecisionTreeClassifier()\n\nplot_result_smote(dtc, \"dtc\")\n# Logistic Regression\nlr = LogisticRegression()\nplot_result_smote(lr, \"lr\")\n# NearestCentroid\nnc = NearestCentroid()\nplot_result_smote(nc, \"nc\")\n# # SVC\n# svc = SVC()\n# plot_result_smote(svc, \"svc\")\n# Random Forest\nrfc = RandomForestClassifier()\nplot_result_smote(rfc, \"rfc\")\n# Gradient Boost\ngbc = GradientBoostingClassifier(random_state=42)\nplot_result_smote(gbc, \"gbc\")\n# Naive Bayes\nnb = GaussianNB()\nplot_result_smote(nb, \"nb\")\n# kNN\nknn = KNeighborsClassifier()\nplot_result_smote(knn, \"knn\")\n# XGBOOST\nxgb = XGBClassifier(eval_metric = \"logloss\", random_state=42)\nplot_result_smote(xgb, \"xgb\")\ncv_AUC_balance = AUC(cv_AUC_balance)\ndf_eval_smote = pd.DataFrame(data={'model': list(cv_acc_balance_test.keys()), \n                                   'bal_acc_train':list(cv_acc_balance_train.values()),\n                                   'bal_acc_test': list(cv_acc_balance_test.values()),\n                                   'recall': list(cv_TPR_balance.values()), \n                                   'fallout':list(cv_FPR_balance.values()),\n                                   'AUC': list(cv_AUC_balance.values())}).round(2)\ndf_eval_smote\nfig, ax = plt.subplots(2,4, figsize=(20, 8))\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,0])\nax[0,0].set_title(\"Unbalanced Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,1])\nax[0,1].set_title(\"Unbalanced Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,2])\nax[0,2].set_title(\"Unbalanced Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,3])\nax[0,3].set_title(\"Unbalanced Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,0])\nax[1,0].set_title(\"Smote Model Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,1])\nax[1,1].set_title(\"Smote Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,2])\nax[1,2].set_title(\"Smote Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,3])\nax[1,3].set_title(\"Smote Model Test FPR\")\n\nplt.tight_layout()\nplt.show()\nplot_ROC()\n\"\"\"\nGradientBoosting yielded the optimized result as better FPR and relative mean strong recall scores. The balance accuracy is also relatively good.\n\"\"\"\n\"\"\"\n## Iteration 3: (with RUS)\n\"\"\"\nimport imblearn\nfrom imblearn.under_sampling import RandomUnderSampler, EditedNearestNeighbours, NearMiss\nunder_sampler = RandomUnderSampler(random_state=42)\nX_train_rus, y_train_rus = under_sampler.fit_sample(X_train, y_train)\nax = y_train_rus.value_counts().plot.bar(color=[\"blue\", \"red\"])\nlabels(ax)\nplt.show()\n\"\"\"\n#### Use Algorithm\n\"\"\"\ncv_acc_rus_train = {}\ncv_acc_rus_test = {}\ncv_TPR_rus = {}\ncv_FPR_rus = {}\ncv_AUC_rus = {}\ndef plot_result_rus(model, name:str):\n    model.fit(X_train_rus, y_train_rus)\n    y_pred = model.predict(X_test)\n\n    # Evaluation based on a 10-fold cross-validation\n    scoring = ['balanced_accuracy', 'recall_macro']\n    scores_train = cross_val_score(model, X_train, y_train, cv=10, scoring = 'balanced_accuracy')\n    scores_test = cross_val_score(model, X_test, y_test, cv=10, scoring = 'balanced_accuracy')\n    cv_acc_rus_train[name] = round(scores_train.mean(), 4)*100  # balanced accuracy\n    cv_acc_rus_test[name] = round(scores_test.mean(), 4)*100  # balanced accuracy\n    cv_TPR_rus[name] = (confusion_matrix(y_test, y_pred)[1][1]\/confusion_matrix(y_test, y_pred)[1].sum())*100  # recall (max)\n    cv_FPR_rus[name] = (confusion_matrix(y_test, y_pred)[0][1]\/confusion_matrix(y_test, y_pred)[0].sum())*100  # fallout (min)\n    \n    # accuracy scores\n    print('Average Balanced Accuracy (CV=10), Test Set:', scores_test.mean())  \n    print('Average Balanced Accuracy (CV=10), Training Set: ', scores_train.mean())\n\n    # print classification report\n    print(classification_report(y_test, y_pred, zero_division=0))\n\n    # Plot Confusion Matrix\n    plot_confusion_matrix(model, X_test, y_test)\n    plt.show()\n# Decision tree\ndtc = DecisionTreeClassifier()\n\nplot_result_rus(dtc, \"dtc\")\n# Logistic Regression\nlr = LogisticRegression()\nplot_result_rus(lr, \"lr\")\n# NearestCentroid\nnc = NearestCentroid()\nplot_result_rus(nc, \"nc\")\n# # SVC\n# svc = SVC()\n# plot_result_rus(svc, \"svc\")\n# Random Forest\nrfc = RandomForestClassifier()\nplot_result_rus(rfc, \"rfc\")\n# Gradient Boost\ngbc = GradientBoostingClassifier(random_state=42)\nplot_result_rus(gbc, \"gbc\")\n# Naive Bayes\nnb = GaussianNB()\nplot_result_rus(nb, \"nb\")\n# kNN\nknn = KNeighborsClassifier()\nplot_result_rus(knn, \"knn\")\n# XGBOOST\nxgb = XGBClassifier(eval_metric = \"logloss\",random_state=42)\nplot_result_rus(xgb, \"xgb\");\ncv_AUC_rus = AUC(cv_AUC_rus)\ndf_eval_rus = pd.DataFrame(data={'model': list(cv_acc_rus_train.keys()), \n                             'bal_acc_train':list(cv_acc_rus_train.values()),\n                             'bal_acc_test': list(cv_acc_rus_test.values()), \n                             'recall': list(cv_TPR_rus.values()), \n                             'fallout':list(cv_FPR_rus.values()),\n                             'AUC': list(cv_AUC_rus.values())}).round(2)    \ndf_eval_rus\nfig, ax = plt.subplots(3,4, figsize=(20, 12))\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,0])\nax[0,0].set_title(\"Unbalanced Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,1])\nax[0,1].set_title(\"Unbalanced Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,2])\nax[0,2].set_title(\"Unbalanced Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,3])\nax[0,3].set_title(\"Unbalanced Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,0])\nax[1,0].set_title(\"Smote Model Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,1])\nax[1,1].set_title(\"Smote Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,2])\nax[1,2].set_title(\"Smote Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,3])\nax[1,3].set_title(\"Smote Model Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,0])\nax[2,0].set_title(\"RUS_Featured Model Test Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,1])\nax[2,1].set_title(\"RUS_Featured Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,2])\nax[2,2].set_title(\"RUS_Featured Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,3])\nax[2,3].set_title(\"RUS_Featured Model Test FPR\")\n\nplt.tight_layout()\nplt.show()\nplot_ROC()\n\"\"\"\n## Iteration 4: (with SMOTE and PCA)\n\"\"\"\nfrom sklearn.decomposition import PCA\npca = PCA().fit(X_train_os)\nfig, ax = plt.subplots(figsize=(20,8))\nxi = np.arange(0, 54, step=1)\ny = np.cumsum(pca.explained_variance_ratio_[0:160:1])\n\nplt.ylim(0.0,1.1)\nplt.plot(xi, y, marker='.', linestyle='--', color='b')\n\nplt.xlabel('Number of Components')\nplt.xticks(np.arange(0, 54, step=2), rotation=90) #change from 0-based array index to 1-based human-readable label\nplt.ylabel('Cumulative variance (%)')\nplt.title('The number of components needed to explain variance')\n\nplt.axhline(y=0.95, color='r', linestyle='-')\nplt.text(0.5, 0.85, '95% cut-off threshold', color = 'red', fontsize=16)\n\nax.grid(axis='x')\nplt.show()\n\"\"\"\nIt looks like n_components = 43 is suitable for% 95 total explained variance,\n\"\"\"\npca = PCA(n_components=43)\npca.fit(X_train_os)\nper_var = np.round(pca.explained_variance_ratio_ * 100, 1)\nlabels = ['PC' + str(x) for x in range(1,len(per_var)+1)]\n\nplt.figure(figsize=(20,6))\nplt.bar(x=range(len(per_var)), height=per_var, tick_label=labels)\nplt.title('Total explained variance {}'.format(np.round(sum(per_var),2)))\nplt.ylabel('Explained variance in percent')\nplt.xticks(rotation=90)\nplt.show()\nX_train_os_pca = pca.transform(X_train_os)\npd.DataFrame(X_train_os_pca)\n\"\"\"\nThe loads (loading scores) indicate \"how high a variable X loads on a factor Y\". \n\n(The i-th principal components can be selected via i in pca.components_ [0].)\n\"\"\"\n# Top 20 columns that have the greatest impact\nloading_scores = pd.Series(pca.components_[0], index=X.columns)\nloading_scores.abs().sort_values(ascending=False)[:20]\n\"\"\"\n#### Use Algorithm\n\"\"\"\nX_test_pca = pca.transform(X_test)\ncv_acc_balance_train_pca = {}\ncv_acc_balance_test_pca = {}\ncv_TPR_balance_pca = {}\ncv_FPR_balance_pca = {}\ncv_AUC_balance_pca = {}\ndef plot_result_smoted_pca(model, name:str):\n    model.fit(X_train_os_pca, y_train_os)\n    y_pred = model.predict(X_test_pca)\n\n    # Evaluation based on a 10-fold cross-validation\n    scoring = ['balanced_accuracy', 'recall_macro']\n    scores_train = cross_val_score(model, X_train_os_pca, y_train_os, cv=10, scoring = 'balanced_accuracy')\n    scores_test = cross_val_score(model, X_test_pca, y_test, cv=10, scoring = 'balanced_accuracy')\n    cv_acc_balance_train_pca[name] = round(scores_train.mean(), 4)*100  # balanced accuracy\n    cv_acc_balance_test_pca[name] = round(scores_test.mean(), 4)*100  # balanced accuracy\n    cv_TPR_balance_pca[name] = (confusion_matrix(y_test, y_pred)[1][1]\/confusion_matrix(y_test, y_pred)[1].sum())*100  # recall (max)\n    cv_FPR_balance_pca[name] = (confusion_matrix(y_test, y_pred)[0][1]\/confusion_matrix(y_test, y_pred)[0].sum())*100  # fallout (min)\n\n    # accuracy scores\n    print('Average Balanced Accuracy (CV=10), Test Set:', scores_test.mean())  \n    print('Average Balanced Accuracy (CV=10), Training Set: ', scores_train.mean())\n\n    # print classification report\n    print(classification_report(y_test, y_pred, zero_division=0))\n\n    # Plot confusion matrix\n    plt.figure(figsize=(3,3))\n    plot_confusion_matrix(model, X_test_pca, y_test)\n    plt.show()\n# Decision tree\ndtc = DecisionTreeClassifier()\nplot_result_smoted_pca(dtc, \"dtc\")\n# Logistic Regression\nlr = LogisticRegression()\nplot_result_smoted_pca(lr, \"lr\")\n# NearestCentroid\nnc = NearestCentroid()\nplot_result_smoted_pca(nc, \"nc\")\n# # SVC\n# svc = SVC()\n# plot_result_smoted_pca(svc, \"svc\")\n# Random Forest\nrfc = RandomForestClassifier()\nplot_result_smoted_pca(rfc, \"rfc\")\n# Gradient Boost\ngbc = GradientBoostingClassifier()\nplot_result_smoted_pca(gbc, \"gbc\")\n# Naive Bayes\nnb = GaussianNB()\nplot_result_smoted_pca(nb, \"nb\")\n# kNN\nknn = KNeighborsClassifier()\nplot_result_smoted_pca(knn, \"knn\")\n# XGBOOST\nxgb = XGBClassifier(eval_metric = \"logloss\")\nplot_result_smoted_pca(xgb, \"xgb\");\ncv_AUC_balance_pca = AUC(cv_AUC_balance_pca, X_test_pca)\ncv_AUC_balance_pca\ndf_eval_smote_pca = pd.DataFrame(data={'model': list(cv_acc_balance_train_pca.keys()), \n                                       'bal_acc_train':list(cv_acc_balance_train_pca.values()),\n                                       'bal_acc_test': list(cv_acc_balance_test_pca.values()),\n                                       'recall': list(cv_TPR_balance_pca.values()), \n                                       'fallout':list(cv_FPR_balance_pca.values()),\n                                       'AUC': list(cv_AUC_rus.values())}).round(2)\ndf_eval_smote_pca\nfig, ax = plt.subplots(4,4, figsize=(20, 16))\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,0])\nax[0,0].set_title(\"Unbalanced Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,1])\nax[0,1].set_title(\"Unbalanced Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,2])\nax[0,2].set_title(\"Unbalanced Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval.sort_values(by=\"recall\"), ax=ax[0,3])\nax[0,3].set_title(\"Unbalanced Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,0])\nax[1,0].set_title(\"Smote Model Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,1])\nax[1,1].set_title(\"Smote Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,2])\nax[1,2].set_title(\"Smote Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_smote.sort_values(by=\"recall\"), ax=ax[1,3])\nax[1,3].set_title(\"Smote Model Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,0])\nax[2,0].set_title(\"RUS_Featured Model Test Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,1])\nax[2,1].set_title(\"RUS_Featured Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,2])\nax[2,2].set_title(\"RUS_Featured Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_rus.sort_values(by=\"recall\"), ax=ax[2,3])\nax[2,3].set_title(\"RUS_Featured Model Test FPR\")\n\nsns.barplot(x=\"bal_acc_train\", y=\"model\", data=df_eval_smote_pca.sort_values(by=\"recall\"), ax=ax[3,0])\nax[3,0].set_title(\"Smoted_PCA Model Train Acc\")\nsns.barplot(x=\"bal_acc_test\", y=\"model\", data=df_eval_smote_pca.sort_values(by=\"recall\"), ax=ax[3,1])\nax[3,1].set_title(\"Smoted_PCA Model Test Acc\")\nsns.barplot(x=\"recall\", y=\"model\", data=df_eval_smote_pca.sort_values(by=\"recall\"), ax=ax[3,2])\nax[3,2].set_title(\"Smoted_PCA Model Test TPR\")\nsns.barplot(x=\"fallout\", y=\"model\", data=df_eval_smote_pca.sort_values(by=\"recall\"), ax=ax[3,3])\nax[3,3].set_title(\"Smoted_PCA Model Test FPR\")\n\nplt.tight_layout()\nplt.show()\nplot_ROC(X_test_pca)\n\"\"\"\nAccording to Smote and PCA, none of the models really gave relatively good results.\n\"\"\"\ndf_eval[\"type\"] = \"Unbalanced\"\ndf_eval_smote[\"type\"] = \"Smote\"\ndf_eval_rus[\"type\"] = \"RUS\"\ndf_eval_smote_pca[\"type\"] = \"Smote_PCA\"\nframes = [df_eval, df_eval_smote, df_eval_rus, df_eval_smote_pca]\ndf_result = pd.concat(frames, ignore_index=True)\ndf_result['model'] = df_result['model'].str.upper()\ndf_result[[\"recall\", \"fallout\", \"bal_acc_train\", \"bal_acc_test\",'AUC']] = df_result[[\"recall\", \"fallout\",  \"bal_acc_train\", \"bal_acc_test\",'AUC']].apply(lambda x: np.round(x, 2))\ndf_result\nsns.relplot(x=\"recall\", y=\"AUC\", hue=\"model\", size=\"bal_acc_test\", \n            sizes=(40, 400), col=\"type\", alpha=1, palette=\"bright\", height=4, legend='full', data=df_result)\n\"\"\"\n* In this plot it looks like GradientBoosting in Smote_PCA has the best scores. But There is a overfitting there, GradientBoosting in RUS(Random Under Sampling) is better. There is no overfitting. Recall:57.27, AUC:0.62, F1:58\n* In the last iteration we will make hyperparameter optimization with GradientBoosting in RUS. We try to reach a better scores.\n\"\"\"\n\"\"\"\n## Iteration 5: (with RUS and hyperparameter optimization)\n\"\"\"\n\"\"\"\nAt the end of 4 iteration, GradientBoost with only undersampled and scaled data set gave better results. In this iteration, we try to improve the GradientBoost Model with hyperparameter optimization.\n\"\"\"\n# Gradient Boosting Classifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nunder_sampler = RandomUnderSampler(random_state=42)\nX_train_rus, y_train_rus = under_sampler.fit_sample(X_train, y_train)\n\nparams={\"learning_rate\": [1],\n     \"min_samples_split\": [50, 10, 2],\n       \"min_samples_leaf\": [1, 5, 10],\n       \"max_depth\":[3,4,5],\n       \"subsample\":[0.5, 1.0],\n       \"n_estimators\":[10, 50, 100],\n       \"random_state\":[42]}\n\ngbc_tunned = GridSearchCV(GradientBoostingClassifier(), \n                                params, \n                                n_jobs=-1, \n                                verbose=2, \n                                ).fit(X_train_rus, y_train_rus)\nfrom sklearn.metrics import plot_confusion_matrix, classification_report, confusion_matrix\nprint(gbc_tunned.best_estimator_)\ny_pred = gbc_tunned.predict(X_test)\n\n# AUC Score\nprint('AUC:', roc_auc_score(y_test, gbc_tunned.predict_proba(X_test)[:,1]))\n\n# print classification report\nprint(classification_report(y_test, y_pred, zero_division=0))\n\n# Plot confusion matrix\nplt.figure(figsize=(3,3))\nplot_confusion_matrix(gbc_tunned, X_test, y_test)\nplt.show()\n\"\"\"\nThe tunned GradientBoost Model didnt give a better result.\n\"\"\"\n\"\"\"\n#  Summary: \n* In this project the diabetic_data.csv dataset was analyzed by machine learning methods with 5 iterations as a classification. For each iteration one tried little by little to achieve a better model result. \n* 8 different algorithms (DecisionTree, Logistic Regression, Random Forest, Gradient Boost, NaiveBayes, Nearest Centroid, XGBOOST and kNearestNeigbour) were used. \n* After the data cleaning and EDA process, the data set was scaled with StandartScaler because there were many large and small features. After that, something special (oversampling, FeatureSelection, FeatureExtraction, HyperParameter optimization) was applied in each iteration. \n* In the end, GradientBoost with only undersampled and scaled data set gave better results.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6659477095f838'}"}
{"id":"58108","text":"# 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 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\n\"\"\"\n# 60k Stack Overflow Questions with Quality Rating \n\"\"\"\n\"\"\"\n# ---------------------------------------------------------------------------------------------------------------\n\"\"\"\n\"\"\"\n## Data\n\nThis is an original dataset, made publicly available for researchers.\n\nWe collected 60,000 Stack Overflow questions from 2016-2020 and classified them into three categories:\n\nHQ: High-quality posts with 30+ score and without a single edit.\nLQ_EDIT: Low-quality posts with a negative score and with multiple community edits. However, they still remain open after the edits.\nLQ_CLOSE: Low-quality posts that were closed by the community without a single edit.\nNotes:\n\nQuestions are sorted according to Question Id.\nQuestion body is in HTML format.\nAll dates are in UTC format.\nPlease let me know of any additional information that you may require.\n\n## Task\n\n- Which Stack Overflow questions should be closed?\n- Predict tags according to text and title.\n\n\"\"\"\n\"\"\"\n## Summary\n\n   - [Vizualisation Libraries import](#a)\n   - [Data import](#b)\n   - [Cleaning of the data](#c)\n   - [Let's analyse the data](#d)\n     - [Number of questions](#e)\n     - [Languages used](#f)\n     - [To continue](#g)\n   - [Let's predict](#h)\n      - [Import Libraries](#i)\n      - [Preprocessing](#j)\n     - [Predict Y(ML tools)](#k)\n     - [Predict Tags(ML tools)](#l)\n     - [Predict Tags(DL tools)](#m)\n     \n\"\"\"\n\"\"\"\n# Vizualisation Libraries import<a id=\"a\"><\/a>\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nplt.rcParams[\"figure.figsize\"] = (20, 15)\nimport seaborn as sns\nfrom bs4 import BeautifulSoup\n\"\"\"\n# Data import<a id=\"b\"><\/a>\n\"\"\"\nstack_data = pd.read_csv(r'\/kaggle\/input\/60k-stack-overflow-questions-with-quality-rate\/data.csv')\nstack_data\n\"\"\"\n# Cleaning of the data<a id=\"c\"><\/a>\n\"\"\"\n\"\"\"\nWe delete bad data found in the table.\n\"\"\"\nprint(stack_data.info())\n\"\"\"\n200 NAN in Y to delete.\n\"\"\"\nstack_data_f = stack_data.dropna(subset=['Y'])\nstack_data_f.CreationDate = stack_data_f.CreationDate.astype('datetime64[ns]')\nstack_data_f['year'] = stack_data_f.CreationDate.dt.year\nstack_data_f['month'] = stack_data_f.CreationDate.dt.month\nstack_data_f['day'] = stack_data_f.CreationDate.dt.day\nstack_data_f.info()\n\"\"\"\n# Let's analyse the data<a id=\"d\"><\/a>\n\"\"\"\n\"\"\"\n#### Number of questions ? <a id=\"e\"><\/a>\n\nIt's interesting to know the number of question according to time. To do it:\n\n- Column date_month is created to analyse the number of questions less deeper.\n- Stack_data_gb_d: Groupby object created to calculate the number of questions per day.\n- Stack_data_gb_m: Other groupby object created to calculate the number of question per month.\n- Stack_data_gb_y: Other groupby object created to calculate the number of questions per year.\n- It would be a litle bit messy to show the number of questions per day, instead of that we showed the mean, min and max number of questions asked per days over months.\n- We plot the result thanks to matplotlib.\n- MajorLocator, majorFormatter, minorLocator are used to defined more precise yticks.\n- Fill_between is used to fill the area between the max and min plot.\n- Autolabel function is the same than the matplotlib doc on bar labels.\n\"\"\"\nstack_data_f['date_month'] = pd.to_datetime({'month':stack_data_f.CreationDate.dt.month,\n                                             'year':stack_data_f.CreationDate.dt.year,\n                                             'day':[1 for i in stack_data_f.CreationDate]})\n\nstack_data_gb_d = stack_data_f.groupby(by=stack_data_f.CreationDate.dt.date\n                                    ).agg({'CreationDate':lambda x:(~x.isna()).sum(),\n                                           'date_month': lambda x: x.iloc[0]})\n\nstack_data_gb_m = stack_data_gb_d.groupby(by=['date_month']).agg([np.mean, np.max, np.min, np.sum])\n\n\nstack_data_gb_y = stack_data_f.groupby(by=stack_data_f.CreationDate.dt.year\n                                    ).agg({'CreationDate':lambda x:(~x.isna()).sum(),\n                                           'date_month': lambda x: x.iloc[0]})\n\n\nfig = plt.figure(figsize = (20, 15))\nplt.gcf().subplots_adjust(left = 0.1, bottom = 0.1,\n                       right = 0.9, top = 0.9, wspace = 0, hspace = 0.3)\nwidth = 0.35\n\n# Plot day\nax_d = fig.add_subplot(311)\n\nmajorLocator = MultipleLocator(10)\nmajorFormatter = FormatStrFormatter('%d')\nminorLocator = MultipleLocator(2)\n\nl1, = ax_d.plot(stack_data_gb_m.index, stack_data_gb_m.iloc[:,1],\n            label='Questions per day', alpha=0.5, c='b')\nl2, = ax_d.plot(stack_data_gb_m.index, stack_data_gb_m.iloc[:,2],\n            label='Questions per day', alpha=0.5, c='b')\nl3, = ax_d.plot(stack_data_gb_m.index, stack_data_gb_m.iloc[:,0], c='orange')\n\nax_d.set_ylabel('Number of Questions per day')\nax_d.set_title('Number of questions asked per month')\nax_d.yaxis.set_major_locator(majorLocator)\nax_d.yaxis.set_major_formatter(majorFormatter)\nax_d.yaxis.set_minor_locator(minorLocator)\n\nplt.fill_between(stack_data_gb_m.index, \n                     stack_data_gb_m.iloc[:,1],\n                     stack_data_gb_m.iloc[:,2],\n                     alpha=0.2)\n    \nplt.grid(axis='both', color='0.95')\nplt.legend([l1,l3],['min and max number of questions per day', 'mean'])\n\n# Barplot month\nax_m = fig.add_subplot(3,1,2)\n\nsns.barplot(x=stack_data_gb_m.index.date, y=stack_data_gb_m.iloc[:,3], palette=\"Blues_d\", ax=ax_m)\nplt.setp(ax_m.get_xticklabels(), rotation=45, ha=\"right\",\n         rotation_mode=\"anchor\")\nax_m.set_ylabel('Number of Questions')\n\n# Barplot year\nax_y = fig.add_subplot(3,1,3)\n\nsns.barplot(x=stack_data_gb_y.index, y=stack_data_gb_y['CreationDate'], data=stack_data_gb_y, palette=\"Blues_d\")\n\nax_y.set_xlabel('time')\nax_y.set_ylabel('Number of Questions')\n\n#From matplotlib exemple\ndef autolabel(rects, ax, width=0.35, xpos='center'):\n    \"\"\"\n    Attach a text label above each bar in *rects*, displaying its height.\n\n    *xpos* indicates which side to place the text w.r.t. the center of\n    the bar. It can be one of the following {'center', 'right', 'left'}.\n    \"\"\"\n\n    ha = {'center': 'center', 'right': 'left', 'left': 'right'}\n    offset = {'center': 0, 'right': 1, 'left': -1}\n    i=0\n    for height in rects:\n        ax.annotate('{}'.format(height),\n                    xy=(i , height),\n                    xytext=(offset[xpos]*3, 3),  # use 3 points offset\n                    textcoords=\"offset points\",  # in both directions\n                    ha=ha[xpos], va='bottom', size=8)\n        i+=1\n\n\nautolabel(stack_data_gb_m.iloc[:,3], ax=ax_m)\nautolabel(stack_data_gb_y['CreationDate'], ax=ax_y)\nprint('graphs based on:')\nstack_data_gb_d\n\"\"\"\n#### Conclusion:\nWe have more questions from 2016 than 2020. The algorithme could be influenced by old questions, we need to be careful about the influence of the time on our predictions.\n\"\"\"\n\"\"\"\n#### Languages used. <a id=\"f\"><\/a>\n\nIt could be interesting to know which language have the more questions on it (Not the most famous or the more used). To do it, i used a list of arbitrary chosen languages: C, C++, C#, Java, SQL, Java, Script, Python, Ruby, PHP, HTML\/CSS, R, MATLAB.\n\nIn total there are 159871 tags (tag -> <...>) over 60k topics and 43746 are refering to a language in the list above.\n\nFrom discussion, we know that each sentence hasn't been taken randomly. they have been sorted from highest rated to lowest then selected. The following graphs can't give us reliable results on the most questioned language. It can just give us a quick view on the top 3: Python, JavaScript and Java.\n\nIt's also interesting to know the proportions of each languages over time on the 43746 references. We represented them by 5 KPI. The last graph gathered the 5 kpi in lineplot: It's easiest to see the evolution of a language.\n\n\n\nThis kind of study can be done on other subject like the different IDE used: Visual-studio etc... lang_list need to be modified.\n\"\"\"\n# Could be better defined\nlang_list = ['( |<)C( |>)','( |<)C[+]','( |<)C[#]','objective-c','Java( |>)','SQL','Javascript','Python','Ruby','PHP','HTML','( |<)R( |>)','MATLAB']\n\nTags = stack_data_f.Tags.str.split('><',expand=True)\nTags = Tags.apply(lambda x: x.str.replace('<|>',''))\n\nlist_tags=pd.Series()\nfor col in Tags:\n    list_tags = pd.concat([list_tags, Tags.loc[:, col]])\n    \nlist_tags = list_tags.dropna().reset_index(drop=True) # List of all the tags\nprint(\"Total number of tags over 60k topics:\", list_tags.shape[0])\n\n# Languages study\nstack_data_l = stack_data_f.copy()\nfor lang in lang_list:\n    stack_data_l[lang] = stack_data.Tags.str.contains(lang, regex=True, case=False)\n    \nstack_data_nb_l = stack_data_l.loc[:,lang_list].sum().sort_values(ascending=False) # Values for each languages\nprint('Total number of references to a language:', stack_data_nb_l.sum())\n\n# Graph\nlgs = stack_data_nb_l.values\nind = stack_data_nb_l.index\nwidth = 0.35  # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(ind, lgs, width)\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Scores')\nax.set_title('Number of tags by languages between 2016 and 2020 over 60k topics')\nax.set_xticks(ind)\nax.legend()\n\n\n#From matplotlib exemple\ndef autolabel(rects, xpos='center'):\n    \"\"\"\n    Attach a text label above each bar in *rects*, displaying its height.\n\n    *xpos* indicates which side to place the text w.r.t. the center of\n    the bar. It can be one of the following {'center', 'right', 'left'}.\n    \"\"\"\n\n    ha = {'center': 'center', 'right': 'left', 'left': 'right'}\n    offset = {'center': 0, 'right': 1, 'left': -1}\n\n    for rect in rects:\n        height = rect.get_height()\n        ax.annotate('{}'.format(height),\n                    xy=(rect.get_x() + rect.get_width() \/ 2, height),\n                    xytext=(offset[xpos]*3, 3),  # use 3 points offset\n                    textcoords=\"offset points\",  # in both directions\n                    ha=ha[xpos], va='bottom')\n\n\nautolabel(rects1)\n\n# Proportion of languages per year\n# Same code than the previous point\n\ndef pie_l(periodicity, date, lang_list, ax, data=stack_data_l.copy()):\n    \"\"\"Create a pie on languages proportions according to the periodicity chosen and the date\"\"\"\n    \n    fracs = data.loc[data[periodicity] == date,lang_list].sum().sort_values(ascending=False)\n    fracs = fracs.apply(lambda x: x*100\/fracs.sum())\n    labels = fracs.index\n    ax.pie(fracs, labels=labels, autopct='%1.1f%%', textprops={'fontsize':10},\n                  shadow=True, explode=tuple(0.2 if i==0 \n                                              else 0.1 if i==1\n                                              else 0.05 if i==2 \n                                              else 0 for i,v in enumerate(fracs)))\n    ax.set_title('Proportions of each languages in '+str(date))\n    return fracs\n\n# Make figure and axes\nfig, axs = plt.subplots(3, 2, figsize=(30,30))\nx1 = pie_l('year', 2016, lang_list, ax=axs[0,0])\nx2 = pie_l('year', 2017, lang_list, ax=axs[0,1])\nx3 = pie_l('year', 2018, lang_list, ax=axs[1,0])\nx4 = pie_l('year', 2019, lang_list, ax=axs[1,1])\nx5 = pie_l('year', 2020, lang_list, ax=axs[2,0])\n\npaper_rc = {'lines.linewidth': 1, 'lines.markersize': 8}                  \nsns.set_context(\"paper\", rc = paper_rc)\nsns.lineplot(data=pd.DataFrame([x1,x2,x3,x4,x5], index=pd.date_range('2016', periods=5, freq='Y')),\n             markers=['s', 'o', 'v', '<', '>','s', 'o', 'v', '<', '>','o', 'v', '<' ], dashes=False, ax=axs[2,1])\naxs[2,1].set_title('Languages proportions over time (Same meaning than the kpi)')\n\"\"\"\n#### Conclusion:\n\nPython, Javascript and java are the three most questioned languages. That would be a shortcut to conclude on the most famous or the more used language only with this study. Moreover, the data have not been taken randomly. However, it gives us an idea of the IT languages landscape. The last graph is very interesting and shows us the increasing of Python.\n\"\"\"\n\"\"\"\n### To continue <a id=\"g\"><\/a>\n\nIn order to go further on this languages study, we now get the proportions of each language on total HQ, LQ_EDIt and LQ_CLOSE topics over 2016 to 2020.\n- HQ: 20000 lines\n- LQ_EDIT: 19998 lines\n- LQ_CLOSE: 19999 lines\n\"\"\"\nfig, ax = plt.subplots(2,3, figsize=(30,20))\n\n# By Classes\nHQ = stack_data_l.loc[stack_data_l.Y=='HQ', lang_list].sum()\nHQ.loc['other'] = 20000 - HQ.sum()\nHQ.sort_values(ascending=False, inplace=True)\n\nLQ = stack_data_l.loc[stack_data_l.Y=='LQ_EDIT', lang_list].sum()\nLQ.loc['other'] = 19999 - LQ.sum()\nLQ.sort_values(ascending=False, inplace=True)\n\nLQC = stack_data_l.loc[stack_data_l.Y=='LQ_CLOSE', lang_list].sum()\nLQC.loc['other'] = 19998 - LQC.sum()\nLQC.sort_values(ascending=False, inplace=True)\n\n# By languages\npy = stack_data_l.loc[stack_data_l.Python==True, 'Y'].value_counts()\njs = stack_data_l.loc[stack_data_l['Java( |>)']==True, 'Y'].value_counts()\nj = stack_data_l.loc[stack_data_l.Javascript==True, 'Y'].value_counts()\n\npie_HQ = ax[0,0].pie(HQ, labels=HQ.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                  shadow=True, explode=tuple(0.2 if i==0 \n                                              else 0.1 if i==1\n                                              else 0.05 if i==2 \n                                              else 0 for i,v in enumerate(HQ)))\n\npie_LQ = ax[0,1].pie(LQ, labels=LQ.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                  shadow=True, explode=tuple(0.2 if i==0 \n                                              else 0.1 if i==1\n                                              else 0.05 if i==2 \n                                              else 0 for i,v in enumerate(LQ)))\n\npie_LQC = ax[0,2].pie(LQC, labels=LQC.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                  shadow=True, explode=tuple(0.2 if i==0 \n                                              else 0.1 if i==1\n                                              else 0.05 if i==2 \n                                              else 0 for i,v in enumerate(LQC)))\n\npie_py = ax[1,0].pie(py, labels=py.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                          shadow=True)\n\npie_js = ax[1,1].pie(js, labels=js.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                          shadow=True)\n\npie_j = ax[1,2].pie(j, labels=j.index, autopct='%1.1f%%', textprops={'fontsize':10},\n                          shadow=True)\n\nax[0,0].set_title('HQ topics')\nax[0,1].set_title('LQ_EDIT topics')\nax[0,2].set_title('LQ_CLOSE topics')\nax[1,0].set_title('Python')\nax[1,1].set_title('JavaScript')\nax[1,2].set_title('Java')\n\"\"\"\n#### Conclusion\n\"\"\"\n\"\"\"\nWe refind The three languages Python, JavaScript and Java. They are most composed by LQ_CLOSE.\n\"\"\"\n\"\"\"\n# ------------------------------------------------------------------------\n\"\"\"\n\"\"\"\n# Let's predict<a id=\"h\"><\/a>\n\"\"\"\n\"\"\"\nThe goal of this part is to make 2 kind of predictions: \n- Classification on Y thanks to title and body topics -> Single classification\n- Classification on Tags thanks to title and body topics -> Multiclass classification\n\nFor this two tasks, we will compare deep learning and other machine learning classificators.\nBefore that, Preprocessing need to be done on body topics to remove tags.\n\"\"\"\n\"\"\"\n### Import libraries<a id=\"i\"><\/a>\n\"\"\"\n\"\"\"\nLibraries related to scikit learning tools\n\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.multioutput import MultiOutputClassifier\nimport xgboost\nfrom sklearn.model_selection import ParameterGrid\nimport sklearn\nimport eli5\nfrom eli5.lime import TextExplainer\n\"\"\"\nLibr\u00e9aries related to TensorFlow (dl analysis coming soon)\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.preprocessing import text\nfrom sklearn.metrics import classification_report\nfrom tokenizers import Tokenizer, models, pre_tokenizers, decoders, processors\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nimport re\n\"\"\"\n### Preprocessing<a id=\"j\"><\/a>\n\"\"\"\nstack_data_f['text'] = stack_data_f.Title+': '+stack_data_f.Body\n\ndef clean_text(text):\n    text = text.lower()\n    text = re.sub(r'[^(a-zA-Z)\\s]','', text)\n    return text\nstack_data_f.text = stack_data_f.text.apply(clean_text)\n\n\"\"\"\n## Predict Y (Machine learning tools)<a id=\"k\"><\/a>\n\"\"\"\n# Best model\n#Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(stack_data_f.text.iloc[:50000]\n                                                    , stack_data_f.Y.iloc[:50000], test_size=0.3, random_state=0 )\n\n\n#Try different classifiers\nclassifiers = [\n    LogisticRegression(C=1),\n    MultinomialNB(),\n    DecisionTreeClassifier(),\n    RandomForestClassifier()]\n\nClassifiers_results = pd.Series(name='results')\n\nfor cls in classifiers:\n    text_clf = Pipeline([\n        ('vect', TfidfVectorizer(ngram_range=(1,1))),\n        ('clf', cls)])\n\n    text_clf.fit(X_train, y_train)\n    predicted = text_clf.predict(X_test)\n    print(str(cls) +': ' + str(text_clf.score(X_test, y_test)))\n\"\"\"\nBest parameters\n\"\"\"\ndef GridSearch(cls, parameters, X, y):\n    \"\"\"Try different parameters. Don't use CV because of huge train dataset\"\"\"\n    \n    results = pd.DataFrame()\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n    \n    for ind,par in enumerate(list(ParameterGrid(parameters))):\n        text_clf = Pipeline([\n                ('vect', TfidfVectorizer()),\n                ('clf', classifier(**par))])\n        text_clf.fit(X_train, y_train)\n        predicted = text_clf.predict(X_test)\n        results.loc[str(par),'results'] = text_clf.score(X_test, y_test)\n        results.loc[str(par),'parameters'] = ind\n        ind_best = results.sort_values(by=['results'], ascending=False).iloc[0,1]\n\n    return list(ParameterGrid(parameters))[int(ind_best)]\n\nclassifier = LogisticRegression\nparameters = {\n    'solver':['saga'],\n    'C': [1, 1.5, 2],\n    'penalty': ['l1', 'l2']\n }\n\nresults = GridSearch(classifier, parameters, stack_data_f.text.iloc[:5000], stack_data_f.Y.iloc[:5000])\nresults\n\"\"\"\nResults\n\"\"\"\nclassifier = LogisticRegression(**results)\n\ntext_clf = Pipeline([\n                ('vect', TfidfVectorizer()),\n                ('clf', classifier)])\ntext_clf.fit(X_train, y_train)\npredicted = text_clf.predict(X_test)\ntext_clf.score(X_test, y_test)\n\"\"\"\nExplanations: The following tab gives us some explan\n\"\"\"\nte = TextExplainer(random_state=0)\nte.fit(stack_data_f.text.iloc[:50000][0], text_clf.predict_proba)\nte.show_prediction(target_names= stack_data_f.Y.unique().tolist())\n\"\"\"\n## Predict Tags (Machine learning tools)<a id=\"l\"><\/a>\n\"\"\"\n\"\"\"\nTo do it, we can use classifiers which support multilabel output as :\n\n- sklearn.tree.DecisionTreeClassifier\n- sklearn.tree.ExtraTreeClassifier\n- sklearn.ensemble.ExtraTreesClassifier\n- sklearn.neighbors.KNeighborsClassifier\n- sklearn.neural_network.MLPClassifier\n- sklearn.neighbors.RadiusNeighborsClassifier\n- sklearn.ensemble.RandomForestClassifier\n- sklearn.linear_model.RidgeClassifierCV\n\nElse, we can use sklearn.multioutput.MultiOutputClassifier, if you want to use classifiers which do not natively support multi-target classification.\n\nSee https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.multioutput.MultiOutputClassifier.html#sklearn.multioutput.MultiOutputClassifier for more details\n\"\"\"\n\"\"\"\nWe will try to predict the first tags columns # 2 columns is to long\n\"\"\"\nTags = stack_data_f.Tags.str.split('><',expand=True)\nTags = Tags.apply(lambda x: x.str.replace('<|>',''))\n\nf_tags = Tags[0]\ns_tags = Tags[1].fillna(f_tags)\nt_tags = Tags[2].fillna(f_tags)\n\nf_stack_data_f = stack_data_f.text\ns_stack_data_f = stack_data_f.text\nt_stack_data_f = stack_data_f.text\n\n\"\"\"\n# If you want to do multiouput classifier, join the three previous columns\nf_s_tags = pd.DataFrame({'0':f_tags,'1':s_tags})\nbinarizer = MultiLabelBinarizer()\nf_s_tags = binarizer.fit_transform(f_s_tags.values)\"\"\"\n\"\"\"\n#### Best model\n\"\"\"\n#Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(f_stack_data_f.iloc[:10000]\n                                                    , f_tags[:10000], test_size=0.3, random_state=0 ) # f_s_tags[:10000,:]\n\n\n#Try different classifiers\nclassifiers = [\n    DecisionTreeClassifier(random_state=0),\n    RandomForestClassifier(random_state=0)]\n\nfor cls in classifiers:\n    text_clf = Pipeline([\n        ('vect', TfidfVectorizer()),\n        ('clf', cls)])\n\n    text_clf.fit(X_train, y_train)\n    predicted = text_clf.predict(X_test)\n    print(str(cls) +': ' + str(text_clf.score(X_test, y_test)))\n\"\"\"\nText explanations\n\"\"\"\n\"\"\"\n#### Best parameters\n\"\"\"\ndef GridSearch(cls, parameters, X, y):\n    \"\"\"Try different parameters. Don't use CV because of huge train dataset\"\"\"\n    \n    results = pd.DataFrame()\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n    \n    for ind,par in enumerate(list(ParameterGrid(parameters))):\n        text_clf = Pipeline([\n                ('vect', TfidfVectorizer()),\n                ('clf', classifier(**par))])\n        text_clf.fit(X_train, y_train)\n        predicted = text_clf.predict(X_test)\n        results.loc[str(par),'results'] = text_clf.score(X_test, y_test)\n        results.loc[str(par),'parameters'] = ind\n        ind_best = results.sort_values(by=['results'], ascending=False).iloc[0,1]\n        \n    return list(ParameterGrid(parameters))[int(ind_best)]\n    \n#Try different parameters\nclassifier = RandomForestClassifier\n\nparameters = {\n    'random_state': [0],\n    'max_features': [1000, 2000, 3000],\n    'n_estimators': [150, 200, 300],\n }\n\nresults = GridSearch(classifier, parameters, f_stack_data_f.iloc[:5000], f_tags[:5000])\nresults\n\"\"\"\n#### Results\n\"\"\"\n#Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(f_stack_data_f.iloc[:10000]\n                                                        , f_tags[:10000], test_size=0.3, random_state=0)\n\nclassifier = RandomForestClassifier(**results)\n\ntext_clf = Pipeline([\n            ('vect', TfidfVectorizer()),\n            ('clf', classifier)])\n\ntext_clf.fit(X_train, y_train)\npredicted = text_clf.predict(X_test)\nprint('score :' + str(text_clf.score(X_test, y_test)))\ntext_clf.predict([f_stack_data_f.iloc[32500]])\nf_tags[32500]\n\"\"\"\n#### Conclusion\n\nThe results of Y predictions are not good at all, that's why a deep learning model could be usefull here\n\"\"\"\n\"\"\"\n## Deep learning <a id=\"m\"><\/a>\n\"\"\"\n\"\"\"\nWe have to define some hyperparameters before start running our model\nFirst:\n\"\"\"\nMAX_FEATURES = 20000\nEPOCHS = 20\nBATCH_SIZE = 20\n\"\"\"\nwe have to clean our text and we add the title, it could have usefull data\n\"\"\"\nstack_data_f['text'] = stack_data_f.Title+': '+stack_data_f.Body\n\ndef clean_text(text):\n    text = text.lower()\n    text = BeautifulSoup(text,'html.parser').text\n    text = text.replace('\\n', '').replace('\\r\\n', '').replace('\\r', '').replace(\"\\'\", '')\n    return text\nstack_data_f.text = stack_data_f.text.apply(clean_text)\n\"\"\"\nTo compare with our previous random forest model, we will predict just the two first tags columns however.\n\"\"\"\nf_s_tags = pd.DataFrame({'0':f_tags,'1':s_tags})\ntest = f_s_tags.copy()\nencoder = LabelEncoder()\nencoder.fit(pd.concat([test.iloc[:,0],test.iloc[:,1]],ignore_index=True)) # Transform columns of tag into integers\ntest.iloc[:,0] = encoder.transform(test.iloc[:,0])\ntest.iloc[:,1] = encoder.transform(test.iloc[:,1])\n\ndf = sklearn.utils.shuffle(pd.DataFrame({'text':stack_data_f.text, 'Tags1':test.iloc[:,0], 'Tags2':test.iloc[:,1]}), random_state=0) # Shuffle \nY1 = df.Tags1\nY2 = df.Tags2\ntext_stack = df.text\nY1 =  np_utils.to_categorical(Y1) # Transform integers into binary output. exemple: Let's [1,2,3] be our output, this vector become [[1,0,0],[0,1,0],[0,0,1]]\nY2 =  np_utils.to_categorical(Y2)\n\nX_train = text_stack.values[:50000]\nX_test = text_stack.values[50000:55000]\ny_train1 = Y1[:50000]\ny_test1 = Y1[50000:55000]\ny_train2 = Y2[:50000]\ny_test2 = Y2[50000:55000]\n\"\"\"\nThe text need to be transform into sequences and then they are set at the same size with adding 0 for the sorter one and cut parts of text for the longer one.\n\"\"\"\ntokens = text.Tokenizer(num_words=MAX_FEATURES, lower=True)\ntokens.fit_on_texts(list(X_train))\nX_train_seq = tokens.texts_to_sequences(X_train)\nX_test_seq = tokens.texts_to_sequences(X_test)\n\nlength = [len(i) for i  in pd.Series(X_train_seq)]\nplt.hist(length)\nprint(np.quantile(length, 0.90))\n# 90% of the questions count more than 230 words \nMAX_LEN = 250\n\nX_train = tf.keras.preprocessing.sequence.pad_sequences(X_train_seq, maxlen=MAX_LEN, padding='pre')\nX_test = tf.keras.preprocessing.sequence.pad_sequences(X_test_seq, maxlen=MAX_LEN, padding='pre')\n\"\"\"\n### Model\n\"\"\"\n# detect and init the TPU\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\n\n# instantiate a distribution strategy\ntpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)\n\n# instantiating the model in the strategy scope creates the model on the TPU\nwith tpu_strategy.scope():\n    inputs = tf.keras.Input(shape=(None,), dtype=\"int32\")\n    x = layers.Embedding(MAX_FEATURES, 256)(inputs)\n    x = layers.Bidirectional(layers.LSTM(256, return_sequences=True))(x)\n    x = layers.Bidirectional(layers.LSTM(128, return_sequences=True))(x)\n    x = layers.Bidirectional(layers.LSTM(128, return_sequences=True))(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Conv1D(64, kernel_size = 3, padding = \"valid\", kernel_initializer = \"glorot_uniform\")(x)\n    x = layers.GlobalMaxPooling1D()(x)\n    outputs = layers.Dense(4970, activation='softmax')(x)\n    outputs2 = layers.Dense(4971, activation='softmax')(x)\n    model = tf.keras.Model(inputs, [outputs,outputs2])\n    model.summary()\n    \n    es_cb = EarlyStopping(monitor='val_loss', min_delta=0,  patience=10, verbose=0, mode='auto')\n    reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001)\n    # Momentum permit to our model to cross 'mountains and plateau'\n    SGD = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9) \n    model.compile(loss='categorical_crossentropy', optimizer=SGD ,metrics=[tf.keras.metrics.CategoricalAccuracy()])\n\"\"\"\n### Others functions Usefull\n\"\"\"\n\"\"\"\n### Learning rate\n\"\"\"\n#Learning Rate is one of the most important hyperparameter so the following piece of code is a way to find a good LR\nimport keras\nclass ExponentialLearningRate(keras.callbacks.Callback):\n    \n    def __init__(self, K, factor):\n        self.factor = factor\n        self.rates = []\n        self.losses = []\n        self.K = K\n        \n    def on_batch_end(self, batch, logs):\n        \n        self.rates.append(self.K.get_value(self.model.optimizer.lr))\n        self.losses.append(logs[\"loss\"])\n        self.K.set_value(self.model.optimizer.lr, self.model.optimizer.lr * self.factor)\n        \n        \ndef bestLearningRate():\n        \n        print(\"\\n\\n********************** Best learning rate calculation ******************\\n\\n\")\n        K = keras.backend\n        model.compile(loss='categorical_crossentropy', optimizer=SGD, metrics=[tf.keras.metrics.CategoricalAccuracy()])\n        expon_lr = ExponentialLearningRate(K,factor=1.0002)\n        model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs = 15, callbacks=[expon_lr])\n        print(\"*************************************************************************\\n\\n\")\n        \n        print(\"********************** Loss as function of learning rate plot displayed ********************\\n\\n\")\n        plt.plot(expon_lr.rates, expon_lr.losses)\n        plt.gca().set_xscale('log')\n        plt.hlines(min(expon_lr.losses), min(expon_lr.rates), max(expon_lr.rates))\n        plt.axis([min(expon_lr.rates), max(expon_lr.rates), 0, expon_lr.losses[0]])\n        plt.xlabel(\"Learning rate\")\n        plt.ylabel(\"Loss\")\n        \nbestLearningRate()\n\"\"\"\nThe lowest point give you the LR to choose.\n\"\"\"\n# detect and init the TPU\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\n\n# instantiate a distribution strategy\ntpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)\n\n# instantiating the model in the strategy scope creates the model on the TPU\nwith tpu_strategy.scope():\n    inputs = tf.keras.Input(shape=(None,), dtype=\"int32\")\n    x = layers.Embedding(MAX_FEATURES, 256)(inputs)\n    x = layers.Bidirectional(layers.LSTM(256, return_sequences=True))(x)\n    x = layers.Bidirectional(layers.LSTM(128, return_sequences=True))(x)\n    x = layers.Bidirectional(layers.LSTM(128, return_sequences=True))(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Conv1D(64, kernel_size = 3, padding = \"valid\", kernel_initializer = \"glorot_uniform\")(x)\n    x = layers.GlobalMaxPooling1D()(x)\n    outputs = layers.Dense(4970, activation='softmax')(x)\n    outputs2 = layers.Dense(4971, activation='softmax')(x)\n    model = tf.keras.Model(inputs, [outputs,outputs2])\n    model.summary()\n    \n    es_cb = EarlyStopping(monitor='val_loss', min_delta=0,  patience=10, verbose=0, mode='auto')\n    reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001)\n    # Momentum permit to our model to cross 'mountains and plateau'\n    SGD = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9) \n    model.compile(loss='categorical_crossentropy', optimizer=SGD ,metrics=[tf.keras.metrics.CategoricalAccuracy()])\n\n#training \nhistory = model.fit(X_train, [y_train1, y_train2], batch_size=BATCH_SIZE, epochs=EPOCHS, validation_data=(X_test, [y_test1,y_test2]),callbacks = [es_cb, reduce_lr], verbose=1)\n\"\"\"\n- val_loss = val_dense_loss + val_dense_1_loss\n- val_dense_1_categorical_accuracy --> val_dense_1_loss\n- val_dense_categorical_accuracy --> val_dense_loss\n\nAround 60% of accuracy for the first column and 30 for the second\n\"\"\"\n\"\"\"\nExemple of prediction\n\"\"\"\ndef tags_pred(test_question):\n    \n    print(test_question)\n    seq = tokens.texts_to_sequences([test_question])\n    padded = tf.keras.preprocessing.sequence.pad_sequences(seq, maxlen=MAX_LEN, padding='pre')\n    pred = model.predict(padded)\n\n    labels=list(encoder.classes_)\n    pred1 = pred[0][0]\n    pred2 = pred[1][0]\n    for i in range(3): # We get the three most probable tags\n        \n        print('Tags 1 : ' +str(labels[np.argmax(pred1)]) + ' ' + str(pred1[np.argmax(pred1)]))\n        pred1 = np.delete(pred1, np.argmax(pred1), axis=0)\n    for i in range(3):\n\n        print('Tags 2 : ' +str(labels[np.argmax(pred2)]) + ' ' + str(pred2[np.argmax(pred2)]))\n        pred2 = np.delete(pred2, np.argmax(pred2), axis=0)\n    \nlabels=list(encoder.classes_)\nprint('Tag 1 : ' + str(np.argmax(Y1[56311]))+ ' ' + str(labels[np.argmax(Y1[56311])]))\nprint('Tag 2 : ' + str(np.argmax(Y2[56311]))+ ' ' + str(labels[np.argmax(Y2[56311])]))\ntags_pred(text_stack.iloc[56311])\n\"\"\"\n# If you liked this notebook, please upvoted it!\n\"\"\"\n\"\"\"\nThanks\nGa\u00e9tan\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6b544832ec6b22'}"}
{"id":"91737","text":"\"\"\"\n**Loading the Libraries**\n\"\"\"\nimport os\nprint(os.listdir(\"..\/input\"))\nimport pandas as pd\nimport numpy as np\nimport re #Regular expression for deleting characters which are not letters\nimport nltk #natural language tool kit\nimport PIL\nfrom nltk import punkt\nfrom nltk.corpus import stopwords \nfrom os import path #creating word cloud\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\nWe will look to analyse both the datasets using python visualisation libraries. \n\"\"\"\nGPSA = pd.read_csv('..\/input\/googleplaystore.csv')\nGPSA.head()\n\"\"\"\n*The number of unique values within the category variable*\n\"\"\"\nGPSA['Category'].value_counts()\n\"\"\"\n*In the categories variable, '1.9' value seems like an anamoly within the dataset. We are going to find its index value and then remove it altogether*\n\"\"\"\nGPSA.index[GPSA['Category'] == \"1.9\"].tolist()\nGPSA = GPSA.drop(10472, axis = 0)\nGPSA.rename(columns={'Content Rating':'Content'},inplace=True)\nGPSA.head()\nprint(\"There are {} observations and {} dimensions in this dataset. \\n\".format(GPSA.shape[0],GPSA.shape[1]))\n\nprint(\"There are {} categories in this dataset such as {}... \\n\".format(len(GPSA.Category.unique()),\n                                                                           \", \".join(GPSA.Category.unique()[0:5])))\n\nprint(\"There are {} genres under different categories in this dataset such as {}... \\n\".format(len(GPSA.Genres.unique()),\n                                                                                      \", \".join(GPSA.Genres.unique()[0:5])))\n\"\"\"\n*Explore the grouped category variable using measures of central tendenceis such as mean, median, quartiles, SD etc.*\n\"\"\"\nCategory = GPSA.groupby(\"Category\")\nCategory.describe().head()\n\"\"\"\n*The average ratings per category*\n\"\"\"\nCategory.mean().sort_values(by=\"Rating\",ascending=False).head()\n\"\"\"\n**Number of Android Applications grouped by Category**\n\"\"\"\nplt.figure(figsize=(15,10))\nCategory.size().sort_values(ascending=False).plot.bar()\nplt.xticks(rotation=50)\nplt.xlabel(\"Application Category\")\nplt.ylabel(\"Number of Android Applications\")\nplt.show()\n\"\"\"\n**Average Ratings per Category**\n\"\"\"\nplt.figure(figsize=(15,10))\nCategory.max().sort_values(by=\"Rating\",ascending=False)[\"Rating\"].plot.bar()\nplt.xticks(rotation=50)\nplt.xlabel(\"Application Category\")\nplt.ylabel(\"Highest Rating\")\nplt.show()\n\"\"\"\n**Creating bokeh chart to plot category and content by mean ratings**\n\"\"\"\nfrom bokeh.io import show, output_file\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.palettes import RdPu6\nfrom bokeh.transform import factor_cmap\n\noutput_file(\"Google_Play.html\")\n\nGPSA.Content = GPSA.Content.astype(str)\nGPSA.Category = GPSA.Category.astype(str)\n\ngroup = GPSA.groupby(by=['Content', 'Category'])\n\nsource = ColumnDataSource(group)\n\nindex_cmap = factor_cmap('Content_Category', palette = RdPu6, factors = sorted(GPSA.Content.unique()), end = 1)\n\np = figure(plot_width=1200, plot_height=500, title= \"Mean Ratings by Category and Content\", x_range=group, toolbar_location=None, tooltips=[(\"Rating\", \"@Rating_mean\"), (\"Content, Category\", \"@Content_Category\")])\n\np.vbar(x='Content_Category', top = 'Rating_mean' , width=1, source=source, line_color=\"white\", fill_color=index_cmap, )\n\np.y_range.start = 0\np.x_range.range_padding = 0.025\np.xgrid.grid_line_color = None\np.xaxis.axis_label = \"Categories grouped by Content\"\np.xaxis.major_label_orientation = 1.0\np.outline_line_color = None\n\nshow(p)\n\"\"\"\n![Screen%20Shot%202019-05-28%20at%205.26.19%20PM%20%282%29.png](attachment:Screen%20Shot%202019-05-28%20at%205.26.19%20PM%20%282%29.png)\nThe file outputs as html and I have attached .png file so that you can view the output. Please provide any suggestions if you know how I can output it in the kaggle notebook. \n\n\"\"\"\n\"\"\"\n**Word Cloud using the Individual Reviews Dataset**\n\"\"\"\nGPSAr = pd.read_csv('..\/input\/googleplaystore_user_reviews.csv', encoding = \"latin1\")\nGPSAr.head()\n\"\"\"\n*Since we are not going to do any sentiment analysis, we are going to concatenate Translated_Review and Sentiment*\n\"\"\"\nGPSAr = pd.concat([GPSAr.Translated_Review,GPSAr.Sentiment],axis=1)\nGPSAr.dropna(axis=0,inplace=True) #drop NaN values\nGPSAr.head()\n\"\"\"\n*The counts of sentiments per group*\n\"\"\"\nGPSAr['Sentiment'].value_counts()\n\"\"\"\n*Cleaning the data set for characted values such as !,. etc.*\n\"\"\"\ntext_list = []\nfor i in GPSAr.Translated_Review:\n    text = re.sub(\"[^a-zA-Z]\",\" \",i)\n    text = text.lower()\n    text = nltk.word_tokenize(text)\n    lemma = nltk.WordNetLemmatizer()\n    text = [lemma.lemmatize(word) for word in text]\n    text = \" \".join(text)\n    text_list.append(text)\ntext_list[5:10]\ntext1 = \" \".join(review for review in GPSAr.Translated_Review)\nprint (\"There are {} words in the combination of all reviews.\".format(len(text1)))\n\"\"\"\n*Editing the wordcloud; changing font size, background colour and the interpolation*\n\"\"\"\nwordcloud = WordCloud(max_font_size=150, max_words=100, background_color=\"grey\").generate(text)\nplt.figure()\nplt.imshow(wordcloud, interpolation=\"sinc\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n*Create stopword list. Added stop words by multiple iterations of the code to remove selected words from each iteration of the word cloud*\n\"\"\"\nstopwords = set(STOPWORDS)\nstopwords.update([\"app\", \"game\", \"thank\", \"you\", \"think\", \"even\", \"make\", \"still\", \"really\", \"find\", \"much\",\n                  \"now\", \"go\", \"thing\", \"say\", \"got\", \"lot\", \"open\", \"day\", \"one\", \"back\", \"please\", \"sometime\",\n                 \"way\", \"first\", \"though\"]) \n\n# Generate a word cloud image\nwordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(text1)\n\n# Display the generated image:\n# the matplotlib way:\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\"\"\"\nI hope I did justice to the dataset. Do comment if you have any suggestion for this notebook. \nCheers!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a850afd70c312c'}"}
{"id":"45897","text":"\"\"\"\n# About Me\nHello all, I am Hasan and this is my first kernel. I'm still learning python and data science libraries. So your comments are extremely helpful to me. \n\n# Introduction\nTurkey stands between Europe and Asia. Geographically country is rather young hence it is more sismographically active. I found this dataset on Kaggle which originates from Kandilli Rasathanesi which is a reputable organisation affiliated with Bogazici University. I will try to analyse the data and create some visualisations. \n\"\"\"\n#Importing the necessary libraries\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nimport chardet\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\"\"\"\n# Data Cleaning\n\"\"\"\n\"\"\"\nThe dataset is in a txt file and whilst reading it, an encoding error has raised. I used *chardet* library to detect the encoding.\n\"\"\"\nwith open('..\/input\/datasetindex.txt', 'rb') as rawdata:\n    result = chardet.detect(rawdata.read(1000000))\n    \nprint(result)\n\"\"\"\nAs seen above encoding is *ISO-8859-1* on a confidence level of 73%. \n\"\"\"\n#reading the dataset\ndata = pd.read_table('..\/input\/datasetindex.txt', sep='\\t', encoding='ISO-8859-1', index_col=0)\ndata.info()\ndata.sample(5)\n\"\"\"\nAbove it is seen that the column names are in Turkish and the last column is partially in Turkish. I am translated them and replace the column names with their English equivalents. \n\"\"\"\ncol_names = ['earthquake_code', 'date', 'time', 'latitude', 'longitude',\n       'depth(km)', 'xM', 'MD', 'ML', 'Mw', 'Ms', 'Mb', 'type', 'location']\ndata.columns = col_names\ndata.head(3)\n\"\"\"\nDate and time are two different columns and they are not in *datetime* format. When I tried to convert them to datetime in one column, I recieved an error that there was a problem with seconds. One of the data point had higher than 59, which is impossible for a second. Below, you may see how I found that point and updated it. \n\"\"\"\n#There was a wrong data of seconds, updated that\nsec_err = data['time'].str.extract(r'\\:(\\d+)\\.')[0].apply(lambda x: int(x))\nprint(sec_err[sec_err>59])\ndata.loc[13080, 'time'] = '10:03:59.00'\nprint(sec_err[sec_err>59])\n\"\"\"\nSince I eradicated the error I can now create one column of datetime and drop the others. \n\"\"\"\ndata['date_time'] = pd.to_datetime(data['date'] + ' ' + data['time'])\ndata = data.drop(['date', 'time'], axis=1)\n\"\"\"\nWhilst checking the location column I realised there are other countries in the data. I cleared them out. \n\"\"\"\ncountries = ['YUNANISTAN', 'GURCISTAN', 'RUSYA', 'IRAN', 'AZERBAYCAN', 'MAKEDONYA', \n             'BULGARISTAN', 'SURIYE', 'IRAK', 'ROMANYA', 'ARNAVUTLUK', 'MISIR', \n             'KIBRIS RUM KESIMI', 'UKRAYNA', 'YUNANiSTAN', 'iRAN', 'BULGARiSTAN',\n             'G\u00dcRCiSTAN', 'MISIR', 'SURiYE', 'ISRAIL', 'ONiKi ADALAR YUNANiSTAN',\n             'KIBRIS RUM KESiMi']\nfor country in countries:\n    data = data[data.location != country]\n    \n#delete the points out of Turkey's geolocation\ndata = data[data.latitude >= 36]\ndata = data[data.longitude >= 26]\n\"\"\"\nThe location data is very detailed and not structured. It shows the provinces and cities. City names are included generally in paranthesis. I am creating a new column showing only the city names. \n\"\"\"\ndata['city'] = data['location'].str.extract(r'\\((.+)\\)')\ndata.city = data.city.fillna(data[data.city.isnull()].location)\n\"\"\"\nLet's explore the data. Here is the 10 worst earthquakes of Turkey. The heaviest earthquate was occured in the city of Erzincan in 1939. \n\"\"\"\ndata[['date_time', 'city', 'xM']].sort_values('xM', ascending=False).head(10)\n\"\"\"\n# Visualisations\n\"\"\"\ndata.xM.plot.hist(bins=10)\n\"\"\"\nThe frequency of earthquakes are shown above. The most frequent eathquakes have a magnitude between 3 and 4. The Richter magnitude scale categorises earthquakes below 5 as minor. I plotted some non-minor insights below. The month of May is a bit unlucky, the most of the earthqaukes more than 5 happening on May. Also Wednesday is the most shakey day of the week. \n\"\"\"\ndata['year'] = data.date_time.apply(lambda x: x.year)\ndata['month'] = data.date_time.apply(lambda x: x.month)\ndata['weekday'] = data.date_time.apply(lambda x: x.dayofweek)\ndataover5 = data[data.xM >= 5]\n\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\ndataover5.month.value_counts().sort_index().plot.bar()\nplt.xlabel('Months of the year')\nplt.subplot(1,2,2)\ndataover5.weekday.value_counts().sort_index().plot.bar()\nplt.xlabel('Days of the week')\n\"\"\"\nBy looking all data, May is still the worst month of all, however, the most shakey day is Sunday. This refutes a popular Turkish pun 'Tuesday shakes' (Sal\u0131 sallan\u0131r).  \n\"\"\"\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\ndata.month.value_counts().sort_index().plot.bar()\nplt.xlabel('Months of the year')\nplt.subplot(1,2,2)\ndata.weekday.value_counts().sort_index().plot.bar()\nplt.xlabel('Days of the week')\n\"\"\"\n\nBelow I plotted the frequency of the earthquakes by years. The graph on left shows the occurence of earthquakes are on an increasing trend. The occurences peak somewhere in 1970s, this probably means that there were new technologies to capture the data from then. The graph on the right shows the frequency of eathquakes with magnitude higher then 5. \n\"\"\"\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\nplt.plot(data.year.value_counts().sort_index())\nplt.subplot(1,2,2)\nplt.plot(data[data.xM >= 5].year.value_counts().sort_index())\n\"\"\"\nThe graphics above gives their trends differently by years. Below the total earthquakes and the ones more than 5 can be seen in the same graph. \n\"\"\"\ndata.year.value_counts().sort_index(ascending=False).plot.area()\ndata[data.xM >= 5].year.value_counts().sort_index(ascending=False).plot.area()\nplt.legend(['all earthquakes', '5 plus'])\n\"\"\"\nMaps are better to comprehend the geologic data. Below you may see the projection of earthquakes with magnitudes more than 5. Seismicly most active areas of Turkey are Aegean Region and Eastern Anatolia. \n\"\"\"\nsel = data[data.xM >= 5]\nlon = sel['longitude'].values\nlat = sel['latitude'].values\nxM = sel['xM'].values\n\nfig = plt.figure(figsize=(12, 6))\nm = Basemap(projection='lcc', resolution='l', lat_0=39, lon_0=35, width=1.7E6, height=1E6)\nm.bluemarble()\nm.drawcoastlines(color='gray')\nm.drawcountries(color='red')\n\nm.scatter(lon, lat, latlon=True, c=xM, s=xM*2, cmap='YlOrRd', alpha=0.7)\n\nplt.colorbar()\nplt.clim(5, 8)","meta":"{'source': 'AI4Code', 'id': '549577f0daf3c6'}"}
{"id":"69882","text":"\"\"\"\n## Basic Exploratory Data Analysis(EDA) \n\"\"\"\n\"\"\"\n## preparations\n\"\"\"\n#load packages\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\"\"\"\n**Load data**\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/tabular-playground-series-jan-2021\/train.csv\")\ntest = pd.read_csv(\"..\/input\/tabular-playground-series-jan-2021\/test.csv\")\n\"\"\"\n## **Basic information**\n\n\"\"\"\n# a quick look into the data\ntrain.head()\n#see if there are null values\ntrain.info()\n\"\"\"\ngreat! no null values in this dataset.\n\"\"\"\n#get some statistical information\ntrain.describe()\n\"\"\"\n### Distribution\n\"\"\"\n#visualize target distribution\n\nsns.distplot(a=train['target'], rug = True)\n\"\"\"\nnotice that there is a training sample whose target value is \u201dabnormally\u201c small.\n\"\"\"\ntrain[train['target']<4] # find the samples whose target value is smaller than 4\n#visulization of 14 features\nfig = plt.figure(figsize=(18,16))\ntrain_feature = train.drop(['id','target'],axis=1)\nfor index,col in enumerate(train_feature):\n    plt.subplot(5,3,index+1)\n    sns.distplot(train_feature.loc[:,col], kde = False)\nfig.tight_layout(pad=1.0)\n\"\"\"\n### Correlation\n\"\"\"\n# corralation heatmap\nmask = np.zeros_like(train_feature.corr())\nmask[np.tril_indices_from(mask)] = True\n\nfeature_corr = train_feature.corr()\nsns.heatmap(feature_corr,cmap= \"Blues\",mask = mask.T)\n\n\"\"\"\n## Baseline Regression\n\"\"\"\n\"\"\"\ntrain\/test set split\n\"\"\"\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\n\n\ntrain_X, val_X,  train_Y, val_Y = train_test_split(\n    train_feature, train['target'], test_size=0.2, shuffle=True)\n\n\"\"\"\n### CatBoosting Baseline\n\"\"\"\n\"\"\"\nLet's use CatBoostRegressor as our baseline model.\n\"\"\"\nfrom catboost import CatBoostRegressor\ncat = CatBoostRegressor(random_state = 7, loss_function='RMSE', verbose = False)\ncat.fit(train_X, train_Y)\n\nval_pred = cat.predict(val_X)\nscore = np.sqrt(mean_squared_error(val_Y, val_pred)) \n\nprint(\"CB model RMSE: \",end = \"\")\nprint(score)\n\"\"\"\nExport baseline model prediction.\n\"\"\"\n\ntest_pred = cat.predict(test.drop(\"id\",axis = 1))\n\nsubmission = pd.DataFrame({\n        \"id\": test[\"id\"],\n        \"target\":test_pred\n    })\nsubmission.to_csv('baseline_cat.csv', index=False)\n\"\"\"\n### Feature Importance\n\"\"\"\n\"\"\"\nMoreover, we can easily derive feature importance after training the CatRegressor model. For more information, you may refer to official doc on [Feature importance - Catboost](https:\/\/catboost.ai\/docs\/features\/feature-importances-calculation.html#feature-importances-calculation)\n\"\"\"\n\nplt.figure(figsize=(10, 10))\nplt.barh(cat.feature_names_, cat.feature_importances_,height =0.5)\n\n\"\"\"\n## model tuning\n\"\"\"\n\"\"\"\nWe may use LightGBM, XGBoosting and CatBoost as our base models for model stacking. Before applying [model stacking](https:\/\/machinelearningmastery.com\/stacking-ensemble-machine-learning-with-python\/), we shall fine-tune the base models. [Bayesian Optimization](https:\/\/towardsdatascience.com\/shallow-understanding-on-bayesian-optimization-324b6c1f7083) is a efficient optimizaion methods by practice.\n\"\"\"\n\"\"\"\n### LGBM tuning\n\"\"\"\nfrom bayes_opt import BayesianOptimization\nimport lightgbm\n\n#codes below are taken from https:\/\/www.kaggle.com\/yevonnaelandrew\/lgbm-cat-xgb-optimization-stacking\n\n\ndtrain = lightgbm.Dataset(data=train_feature, label=train['target'])\n\ndef hyp_lgbm(num_leaves, feature_fraction, bagging_fraction, max_depth, min_split_gain, min_child_weight, learning_rate):\n      \n        params = {'application':'regression','num_iterations': 5000,\n                  'early_stopping_round':100, 'metric':'rmse'}\n        params[\"num_leaves\"] = int(round(num_leaves))\n        params['feature_fraction'] = max(min(feature_fraction, 1), 0)\n        params['bagging_fraction'] = max(min(bagging_fraction, 1), 0)\n        params['max_depth'] = int(round(max_depth))\n        params['min_split_gain'] = min_split_gain\n        params['min_child_weight'] = min_child_weight\n        params['learning_rate'] = learning_rate\n        cv_result = lightgbm.cv(params, dtrain, nfold=3, \n                                seed=7, stratified=False, \n                                verbose_eval =None, metrics=['rmse'])\n        \n        return -np.min(cv_result['rmse-mean']) \n        #add a minus because Bayesian Optimization can only be performed to approximate maxima.\npds = {\n    'num_leaves': (5, 50),\n    'feature_fraction': (0.2, 1),\n    'bagging_fraction': (0.2, 1),\n    'max_depth': (2, 20),\n    'min_split_gain': (0.001, 0.1),\n    'min_child_weight': (10, 50),\n    'learning_rate': (0.01, 0.5),\n      }\n# codes below takes a long execution time, uncomment to see the process\n# optimizer = BayesianOptimization(hyp_lgbm,pds,random_state=7)\n# optimizer.maximize(init_points=10, n_iter=50)\n# optimizer.max['params']\n\"\"\"\n### CatBoost Tuning\n\"\"\"\nimport catboost as cgb\n\ndef cat_hyp(depth, bagging_temperature, l2_leaf_reg, learning_rate):\n  params = {\"iterations\": 100,\n            \"loss_function\": \"RMSE\",\n            \"verbose\": False} \n  params[\"depth\"] = int(round(depth)) \n  params[\"bagging_temperature\"] = bagging_temperature\n  params[\"learning_rate\"] = learning_rate\n  params[\"l2_leaf_reg\"] = l2_leaf_reg\n  \n  cat_feat = [] # Categorical features list, we have nothing in this dataset\n  cv_dataset = cgb.Pool(data=train_feature, label=train['target'], cat_features=cat_feat)\n\n  scores = cgb.cv(cv_dataset,\n              params,\n              fold_count=3)\n  return -np.min(scores['test-RMSE-mean']) \n# Search space\npds = {'depth': (3, 10),\n       'bagging_temperature': (0.1,10),\n       'l2_leaf_reg': (0.1, 10),\n       'learning_rate': (0.05, 0.3),\n        }\n# optimizer = BayesianOptimization(cat_hyp, pds, random_state=7)\n# optimizer.maximize(init_points=10, n_iter=80)\n# optimizer.max['params']\n\"\"\"\n### XGBoosting tuning\n\"\"\"\nimport xgboost as xgb\n\ndtrain = xgb.DMatrix(train_feature, train['target'], feature_names=train_feature.columns.values)\ndef hyp_xgb(max_depth, subsample, colsample_bytree,min_child_weight, gamma, learning_rate):\n    params = {\n    'objective': 'reg:squarederror',\n    'eval_metric':'rmse',\n    'nthread':-1\n     }\n    \n    params['max_depth'] = int(round(max_depth))\n    params['subsample'] = max(min(subsample, 1), 0)\n    params['colsample_bytree'] = max(min(colsample_bytree, 1), 0)\n    params['min_child_weight'] = int(min_child_weight)\n    params['gamma'] = max(gamma, 0)\n    params['learning_rate'] = learning_rate\n    scores = xgb.cv(params, dtrain, num_boost_round=500,verbose_eval=False, \n                    early_stopping_rounds=10, nfold=3)\n    return -scores['test-rmse-mean'].iloc[-1]\npds ={\n  'min_child_weight':(3, 20),\n  'gamma':(0, 5),\n  'subsample':(0.7, 1),\n  'colsample_bytree':(0.1, 1),\n  'max_depth': (3, 10),\n  'learning_rate': (0.01, 0.5)\n}\n# optimizer = BayesianOptimization(hyp_xgb, pds, random_state=7)\n# optimizer.maximize(init_points=4, n_iter=15)\n\"\"\"\n## model stacking\n\"\"\"\n## parameters derived from Bayesian Optimizaion fine-tuning\nparam_lgbm = {\n     'bagging_fraction': 0.973905385549851,\n     'feature_fraction': 0.2945585590881137,\n     'learning_rate': 0.03750332268701348,\n     'max_depth': int(7.66),\n     'min_child_weight': int(41.36),\n     'min_split_gain': 0.04033836353603582,\n     'num_leaves': int(46.42),\n     'application':'regression',\n     'num_iterations': 5000,\n     'metric': 'rmse'\n}\n\nparam_cat = {\n     'bagging_temperature': 0.31768713094131684,\n     'depth': int(8.03),\n     'l2_leaf_reg': 1.3525686450404295,\n     'learning_rate': 0.18,\n     'iterations': 150,\n     'loss_function': 'RMSE',\n     'verbose': False\n}\n\n\nparam_xgb = {\n     'colsample_bytree': 0.8119098377889549,\n     'gamma': 2.244423418642122,\n     'learning_rate': 0.015800631696721114,\n     'max_depth': int(9.846),\n     'min_child_weight': int(15.664),\n     'subsample': 0.82345,\n     'objective': 'reg:squarederror',\n     'eval_metric':'rmse',\n     'num_boost_roun' : 500\n}\nfrom sklearn.ensemble import StackingRegressor\nfrom xgboost import XGBRegressor\n\nestimators = [\n        ('lgbm', lightgbm.LGBMRegressor(**param_lgbm, random_state=7, n_jobs=-1)),\n        ('xgbr', XGBRegressor(**param_xgb, random_state=7, nthread=-1)),\n        ('cat', CatBoostRegressor(**param_cat))\n]\n\nreg = StackingRegressor(\n    estimators=estimators,\n    final_estimator=lightgbm.LGBMRegressor(),\n    n_jobs=-1,\n    cv=5\n)\n\ntrain_X, val_X,  train_Y, val_Y = train_test_split(\n    train_feature, train['target'], test_size=0.2, shuffle=True)\n\nreg.fit(train_X,train_Y)\n\nval_pred = reg.predict(val_X)\nscore = np.sqrt(mean_squared_error(val_Y, val_pred))\n\nprint(\"Final model RMSE: \",end = \"\")\nprint(score)\n\n\n\"\"\"\nfinally we can make prediction to the test set.\n\"\"\"\n#predict\nreg = StackingRegressor(\n    estimators=estimators,\n    final_estimator=lightgbm.LGBMRegressor(),\n    n_jobs=-1,\n    cv=5\n)\n\nreg.fit(train_feature, train['target'])\n\ntest_pred = reg.predict(test.drop(\"id\",axis = 1))\n\nsubmission = pd.DataFrame({\n        \"id\": test[\"id\"],\n        \"target\":test_pred\n    })\nsubmission.to_csv('stacking_sub.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '808d2fb12b3277'}"}
{"id":"81378","text":"# 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\nfrom tensorflow.keras.datasets import mnist\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.callbacks import EarlyStopping, LambdaCallback\nfrom tensorflow.keras.utils import to_categorical\nimport matplotlib.pyplot as plt\n\"\"\"\n## 1. Data Preprocessing\n\"\"\"\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = x_train.astype('float')\/255.\nx_test = x_test.astype('float')\/255.\nx_train = np.reshape(x_train, (60000, 784))\nx_test = np.reshape(x_test, (10000, 784))\nx_train.shape\n\n\n\"\"\"\n## 2. Adding Noise \n\"\"\"\nx_train_noisy = x_train + np.random.rand(60000, 784) * 0.9\nx_test_noisy = x_test + np.random.rand(10000, 784) * 0.9\nx_train_noisy = np.clip(x_train_noisy, 0., 1.)\nx_test_noisy = np.clip(x_test_noisy, 0., 1.)\ndef plot(x,predictions, labels=False):\n    plt.figure(figsize=(20,2))\n    for i in range(10):\n        plt.subplot(1,10,i+1)\n        plt.imshow(x[i].reshape(28,28),cmap=\"binary\")\n        plt.xticks([])\n        plt.yticks([])\n        if labels:\n            plt.xlabel(np.argmax(p[i]))\n    plt.show()\n\"\"\"\nWe see the original images as follows:\n\"\"\"\nplot(x_train,None)\n\"\"\"\nWe see the noisy images as follows:\n\"\"\"\nplot(x_train_noisy,None)\n\"\"\"\n## 3. Building the Autoencoder\n\"\"\"\nmodel = Sequential()\nmodel.add(Dense(units=256,activation=\"relu\", input_shape=(784,)))\nmodel.add(Dense(units=256,activation=\"relu\"))\nmodel.add(Dense(units=10,activation=\"softmax\"))\nmodel.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\",metrics=[\"accuracy\"])\nmodel.summary()\nmodel.fit(x=x_train, y=y_train,validation_data=(x_test,y_test), epochs=4)\nmodel.evaluate(x_test,y_test)\n\"\"\"\nAs seen our model's prediction is very low in the noisy images %97 versus %26\n\"\"\"\nmodel.evaluate(x_test_noisy,y_test)\n\"\"\"\n## 4. Building the Autoencoder\n\"\"\"\n\"\"\"\n<font color=\"green\">\nAn autoencoder is an unsupervised learning technique for neural networks that learns efficient data representations (encoding) by training the network to ignore signal \u201cnoise.\u201d Autoencoders can be used for image denoising, image compression, and, in some cases, even generation of image data.\n  \nAutoencoder gets the noisy images as input and the original images as output. This forces the model to learn the most important characteristics of the image like Principal Component Analysis.\n\"\"\"\ninput_image = Input(shape=(784,))\nencoded = Dense(units=64,activation=\"relu\")(input_image) # This will reduce the dimensionality of the image and get the most important parts\ndecoded = Dense(units=784,activation=\"sigmoid\")(encoded) # This will return 1 or 0 on the encoded pixels, so will reduce the noises.\n\nautoencoder = Model(input_image, decoded)\nautoencoder.compile(loss=\"binary_crossentropy\",optimizer=\"adam\",metrics=[\"accuracy\"])\n\"\"\"\n## 5. Training the Autoencoder\n\"\"\"\nautoencoder.fit(x=x_train_noisy,y=x_train, epochs =100, callbacks=[EarlyStopping(monitor='val_loss', patience=5)])\n\nprint(' ***********************************************************************************')\nprint('Training is complete!')\n\"\"\"\n## 6.Denoised Images and Evaluate Performance of the Model\n\"\"\"\npredictions = autoencoder.predict(x_test_noisy)\nplot(x_test_noisy, None)\nplot(predictions, None)\n\"\"\"\nLets see the performance of our classifier with the denoised images. As seen below, we have almost the same accuracy as we had with the original images.\n\"\"\"\nmodel.evaluate(predictions,y_test)\n\"\"\"\n## 7. Composite Model\n\"\"\"\nnoisy_image = Input(shape=(784,))\nx = autoencoder(noisy_image)\ny = model(x)\n\ndenoise_and_classify = Model(noisy_image, y)\np = denoise_and_classify.predict(x_test_noisy)\nplot(x_test_noisy, p, True)\nplot(x_test_noisy, to_categorical(y_test), True)","meta":"{'source': 'AI4Code', 'id': '955aa1d3e7086b'}"}
{"id":"5509","text":"\"\"\"\n**PLEASE UP VOTE ME!!!!**\n\nIn this Kernel, I will take up a use case for identifying anamoly in the data, and thereby being able to predict anamoly in data. I will take a use case of credit card fraud data.\n\nFirstly, we will have a look at our provided data, and glean insights by using data exploratory and visualization tools.\n\nThen we will explore different ways to look for anamolies, and compare & contrast between them. We will start with Unsupervised learning, in that we will develop KMeans Cluster & IsolationForest Model, and use them to predict anamolies. After that, we will use Supervised learning methods, in that we will use gradient boost & Logistic regression to predict anamolies.\n\nFinally, we will dive into deep learning methods. We will build a deep sequential model, and predict anamolies.\n\nThis Kernel is for a beginner to understand how to work through different steps in building a model, and selecting the right one.\n\n**Have Fun!!! - Lijesh Shetty..**\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\/\"))\n\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\nLets read data from the credit card csv file. \nYou can read more about this data, but essentially the dimension of the data has been reduced by applying PCA (Principal Component Analysis). \n\"\"\"\n# Lets read the data into a dataframe\ndf = pd.read_csv('..\/input\/creditcard.csv')\ndf.head()\n\"\"\"\nIts good to always do df.info() & df.describe()\nThese methods help you to find out whether there are any invalid\/empty data, and how the data is spread as well.\n\"\"\"\n# split into label and features\ntarget_label = df['Class']\ntarget_label.value_counts()\nX = df.iloc[:,:-1]\ndf.info() # there are 284806 rows with 31 columns including the target label 'Class' in the provided data.\n\"\"\"\nLets look at correlation of features. This will tell us how the features are correlated with each other. \nCorrelation gives us a intution on which variables are important, and have impact on the predicted class.\n\"\"\"\n# Now lets look at the correlationin the data. \n# Prior to that we will split out data into training and testing set.\nfrom sklearn.model_selection import train_test_split \ntrain_X, test_X, train_y, test_y = train_test_split(X,target_label,test_size=0.3,random_state=42)\n# find the correlation between the different variables.\ncorr_mtx = df.corr()\ncorr_mtx\nprint(corr_mtx['Class'].sort_values(ascending = False)) \n# V11 thru V27 are the features which have the most correlation impact on Class, and there are attributes which are negatively \n# correlated as well\n\n    \n\"\"\"\nHere I am plotting feature data, and seeing their spread. Histogram will help us to do that. :)\n\"\"\"\n# Here we will plot a hist of all features to see the spread of data.\n# doing a visual on data helps to further understand the data.\nimport matplotlib.pyplot as plt\nX.hist(figsize=(20,21))\nplt.show()\n\"\"\"\nLets try our first model, and see where it gets us..\n\n**KMEANS**\n\nWe will try with KMeans Clustering algorithm. We will seggregate the data in different clusters, and see whether the fraud gets segregated differently...Also, I will train the model using the non-fraud data (meaning, I will remove the fraud data out, and train the model with non fraud data only). Then we will feed in fraud data, and see how the prediction is..\n\nYou can feed in the entire data set, including Fraud, and see how the model behaves. \n\nIn the below step, I am separating fraud from non-fraud, and creating train and set set for non fraud data.\n\"\"\"\n# Separate out Fraud & Non-Fraud Data, and split to get train & test set.\nnon_fraud_data = df[df.Class == 0]\nfraud_data = df[df.Class == 1]\nnp.unique(non_fraud_data.Class)\n\n\nnon_fraud_label = non_fraud_data['Class']\nnon_fraud_X = non_fraud_data.iloc[:,:-1]\nnon_fraud_X.head()\n\nfraud_label = fraud_data['Class']\nfraud_X = fraud_data.iloc[:,:-1]\n\nnon_train_X, non_test_X, non_train_y, non_test_y = train_test_split(non_fraud_X,non_fraud_label,test_size=0.3,random_state=42)\n\n# Lets look at Kmeans...\n# Lets see whether we can segregate data in Clusters.\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\nks = range(1, 6)\ninertias = []\nfor k in ks:\n    # Create a KMeans instance with k clusters: model\n    model = KMeans(n_clusters=k)\n   # Fit model to samples\n    model.fit(non_train_X)\n   # Append the inertia to the list of inertias\n    inertias.append(model.inertia_)\n    \n# Plot ks vs inertias\nplt.plot(ks, inertias, '-o')\nplt.xlabel('number of clusters, k')\nplt.ylabel('inertia')\nplt.xticks(ks)\nplt.show()\n\"\"\"\nFrom the above plot of inertia with number of clusters, we can see that the inertial change is smaller post the 3 clusters. We will now build our model for three clusters, and use it for predictions.\n\"\"\"\n# lets use three clusters..\n\nfrom sklearn.cluster import KMeans\n\nmodel = KMeans(n_clusters=3, random_state=42)\nk_labels = model.fit_predict(non_fraud_X,non_fraud_label)\n\nprint('len of fraud', len(fraud_X))\nprint('len of non_fraud_X', len(non_fraud_X))\nprint('len of df', len(df))\n\n\"\"\"\nKMeans was not really helpful here. \nOfcourse, you can try including fraud data when you are training the model, and see how it works.\nThe predictions has classified them in one of the existing clusters. Not much helpful.\nSo lets move on to other predictor models.\n\"\"\"\nfraud_predict_labels = model.predict(fraud_X)\nnp.unique(fraud_predict_labels)\n\nlen(fraud_predict_labels[fraud_predict_labels < 0])\n\n\n\"\"\"\n**Lets do an Isolation Forest. Isolation Forest is used to find anamoly.******\n\"\"\"\n# compute outlier_fraction for the model here\noutlier_fraction = len(fraud_X)\/len(df)\nprint(outlier_fraction)\n\nfrom sklearn.ensemble import IsolationForest\nclf = IsolationForest(n_estimators=10, max_samples= len(train_X),contamination = outlier_fraction,n_jobs=5, random_state=42, behaviour ='new')\nclf.fit(train_X)\nscore = clf.decision_function(train_X)\n\ny_pred_train = clf.predict(train_X)\ny_pred_test = clf.predict(test_X)\n\n\"\"\"\nLets try to find accuracy and precision of our model for the test data.\n\nFirst we have to align both the prediction and the observation. To match with Observation categorical values, we change predictions values to '1', when it is fraud, and '0' when it is not a fraud.\nWe will build a confusion matrix, and then calculate our precision and accuracy values.\n\"\"\"\n# lets try to build confusion matrix and get precision and accuracy scores.\ny_pred_test[y_pred_test == 1] = 0\ny_pred_test[y_pred_test == -1] = 1\nnp.unique(y_pred_test)\n\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\n\ncnf_mtrx = confusion_matrix(test_y,y_pred_test)\ncnf_mtrx\n\"\"\"\nOnly 44 fraud's have been detected by our model, and 93 have been missed whereas 92 have been incorrectly classified as fraud by our model.\n\"\"\"\naccuracy_score(train_y,y_pred_train)\n############################################################################################################################\n# Calculate precison & recall. \n# Precision is actual positive prediction\/ total positive prediction\n# Recall is actual positive prediction\/ total actual positives\n############################################################################################################################\nprecision = cnf_mtrx[1,1]\/(cnf_mtrx[1,1]+cnf_mtrx[0,1])\nrecall = cnf_mtrx[1,1]\/(cnf_mtrx[1,1]+cnf_mtrx[1,0])\nprint(\"precision is {0}, and recall is {1}\".format(precision,recall))\n\"\"\"\nPrecision and recall both are around 32%. Although, this may seem low, but the results are fantastic! \nModel is now able to detect 32% of fraud cases.\n\"\"\"\n\"\"\"\nLets change our gear to using Supervised Learning. We will use ADABOOST & Logistic Regression, and see where it gets us...\n\n**ADABOOST**\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\n\nclf_ada = AdaBoostClassifier(n_estimators=100, random_state=42)\nclf_ada.fit(train_X,train_y) \ntest_y_ada_predict = clf_ada.predict(test_X)\n\n# lets build confusion matrix\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\n\nada_test_cnf_mtrx = confusion_matrix(test_y,test_y_ada_predict)\nada_test_cnf_mtrx\n##Find precision and recall for AdaBoost Model\nprecision = ada_test_cnf_mtrx[1,1]\/(ada_test_cnf_mtrx[1,1]+ada_test_cnf_mtrx[0,1])\nrecall = ada_test_cnf_mtrx[1,1]\/(ada_test_cnf_mtrx[1,1]+ada_test_cnf_mtrx[1,0])\nprint(\"precision is {0}, and recall is {1}\".format(precision,recall))\n\"\"\"\n**WOW!!** If you were excited about 32% accuracy with IsolationForest, AdaBoost has been able to give us 87% accuracy. We will able to predict 87 out of 100 Fraud cases, and can potentially stop them before happening :)\n\"\"\"\n\"\"\"\nLets use a simple Logistic Regression Model and check our precision.\n\n**Logistic Regression**\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\n\nlg_clf = LogisticRegression(penalty='l2',tol=0.0001,random_state=42)\nlg_clf.fit(train_X,train_y)\ntest_y_lg_predict = lg_clf.predict(test_X)\n\n# lets build confusion matrix\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\n\nlg_test_cnf_mtrx = confusion_matrix(test_y,test_y_lg_predict)\nlg_test_cnf_mtrx\n##Find precision and recall for Logistic Regression Model\nprecision = lg_test_cnf_mtrx[1,1]\/(lg_test_cnf_mtrx[1,1]+lg_test_cnf_mtrx[0,1])\nrecall = lg_test_cnf_mtrx[1,1]\/(lg_test_cnf_mtrx[1,1]+lg_test_cnf_mtrx[1,0])\nprint(\"precision is {0}, and recall is {1}\".format(precision,recall))\n\"\"\"\nA simple Log Regression model has given us a precision of 69% and recall of 60%.\nNow lets dive into Deep Learning Model, and see how further it can take us......\n\"\"\"\n\"\"\"\nNow..Lets do DeepLearning using Keras and TensorFlow as our backend.\nI have built a very simple model with no hidden layers.\nI have 128 neuron for the input layer, and output layer has 2 neurons (0 or 1) with softmax activation..\nI have used to_categorical method to change to binary output for train_y & test_y label array.\nI have used sgd optimizer, and then I run the model...\n\"\"\"\nfrom keras import  backend as K\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Activation, Flatten, Dropout\nfrom keras.optimizers import Adam,RMSprop, SGD\n\nfrom keras.utils import np_utils\nimport numpy as np\n\nn_cols = train_X.shape[1]\ny_train = np_utils.to_categorical(train_y,2)\ny_test = np_utils.to_categorical(test_y,2)\nprint('shape is',n_cols)\n\nmodel = Sequential()\nmodel.add(Dense(128,activation='relu',input_shape=(n_cols,)))\nmodel.add(Dense(2,activation='softmax'))\nmodel.summary()\nmodel.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])\nhistory = model.fit(train_X,y_train,batch_size=1000,epochs=200,verbose='VERBOSE',validation_split = 0.2)\n\n\n\"\"\"\n**WOW!!! Blown away....**\ntrain accuracy is 99.82% whereas test accuracy is 99.84%.\n\nI am satisfied with this outcome. Question is, **Are You?**\n\"\"\"\nscore1 = model.evaluate(train_X,y_train)\nprint('train score',score1[0])\nprint('train accuracy',score1[1])\n\nscore = model.evaluate(test_X,y_test)\nprint('test score',score[0])\nprint('test accuracy',score[1])","meta":"{'source': 'AI4Code', 'id': '0a364bdf7d0352'}"}
{"id":"135054","text":"\"\"\"\n# Load the train dataset\n\"\"\"\nimport pandas as pd\ntrain = pd.read_csv('\/kaggle\/input\/mobile-price-classification\/train.csv')\ntrain.head()\n\"\"\"\n# Install PyCaret\n\"\"\"\n!pip install pycaret\n\"\"\"\n# Initializing Setup\n\"\"\"\nfrom pycaret.classification import *\nclf1 = setup(data = train, target = 'price_range', session_id = 786, silent = True)\n\n#silent is True to perform unattended run when kernel is executed.\n\"\"\"\n# Compare Models\n\"\"\"\n%%time\ncompare_models()\n\"\"\"\n# Create Model\n\"\"\"\n# create knn model\nknn = create_model('knn')\n# create catboost model\ncatboost = create_model('catboost')\n\"\"\"\n# Tune Model\n\"\"\"\n# tune knn model\ntuned_knn = tune_model('knn', optimize = 'Accuracy', n_iter = 100)\n# parameters of tuned_knn\nprint(tuned_knn)\ntuned_catboost = tune_model('catboost', optimize = 'Accuracy', n_iter = 100)\ntuned_lightgbm = tune_model('lightgbm', optimize = 'Accuracy', n_iter = 100)\ntuned_ada = tune_model('ada', optimize = 'Accuracy', n_iter = 100)\ntuned_lr = tune_model('lr', optimize = 'Accuracy', n_iter = 100)\n\"\"\"\n# Ensemble Model\n\"\"\"\ndt = create_model('dt')\nbagged_dt = ensemble_model(dt, n_estimators = 100)\n\"\"\"\n# Plot Model\n\"\"\"\n# auc\nplot_model(bagged_dt)\n# confusion matrix\nplot_model(bagged_dt, plot = 'confusion_matrix')\n# boundary\nplot_model(bagged_dt, plot = 'boundary')\n# vc\nplot_model(bagged_dt, plot = 'dimension')\n\"\"\"\n# Predict on holdout set\n\"\"\"\npred_holdout = predict_model(bagged_dt)\n\"\"\"\n# Finalize Model \n\"\"\"\nfinal_dt = finalize_model(bagged_dt)\n\"\"\"\n# Predictions\n\"\"\"\ntest = pd.read_csv('\/kaggle\/input\/mobile-price-classification\/test.csv')\ntest.head()\npredictions = predict_model(final_dt, data=test)\npredictions.head()","meta":"{'source': 'AI4Code', 'id': 'f8498ba96b69bb'}"}
{"id":"85026","text":"\"\"\"\n# Predicting Credit Card Application Approvals\n\"\"\"\n\"\"\"\nBanks receive a lot of applications for credit cards. Many of them get rejected for many reasons, like high loan balances, low credit scores or low income levels and etc for example.\nThe task I wish to achieve from this notebook is to build an automatic credit card approval predictor using Data Analysis and Machine Learning. For this, I have: \n1) Load and read the data\n\n2) Perform data cleaning- deal with missing values, duplicate values\n\n3) Data Preprocessing- converting non-numeric values to numeric, scaling the dataset values to best fit a Machine Learning algorithm and finally split the dataset into train and test data\n\n4) Exploratory data analysis to build an intuition about model needed\n\n5) Build a Machine Learning model that is able to predict if an individual credit card application is approved or reject\n\nThe dataset that I have picked is the <a href=\"http:\/\/archive.ics.uci.edu\/ml\/datasets\/credit+approval\">Credit Card Approval dataset<\/a> from the UCI Machine Learning Repository.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\n# load dataset\ndf = pd.read_csv(\"\/kaggle\/input\/credit-card-applications-dataset\/cc_approvals.data\", header=None)\ndf.head(20)\n\"\"\"\nAs seen, the column names are anonymized by the contributor since this data is confidential.\n\n<a href=\"http:\/\/rstudio-pubs-static.s3.amazonaws.com\/73039_9946de135c0a49daa7a0a9eda4a67a72.html\"> This blog<\/a> gives us a pretty good overview of the probable features. The probable features in a typical credit card application are <i>Gender, Age, Debt, Married, BankCustomer, EducationLevel, Ethnicity, YearsEmployed, PriorDefault, Employed, CreditScore, DriversLicense, Citizen, ZipCode, Income and finally the ApprovalStatus.<\/i> This gives us a pretty good starting point, and we can map these features with respect to the columns in the output.\n\"\"\"\n# dataframe information\ndf.info()\ndf.describe()\n# summary statistics\ndf.describe(include = 'O') \n#notice the '?' there, these need to be removed\/replaced\ndf.tail(20) \n# notice the '?' there, these need to be removed\/replaced\ndf.isnull().sum()\n\"\"\"\n### Data Imputation\n\"\"\"\n# replace the '?'s with NaN\ndf.replace('?', np.nan, inplace=True)\n\n# inspect the missing values again\ndf.tail(20)\n# impute the missing values with mean imputation\ndf.fillna(df.mean(), inplace=True)\n# count the number of NaNs in the dataset and print the counts to verify\ndf.isnull().sum()\n# use backfill method to fill nan values in object columns\nfor cname in df:\n    if df[cname].dtypes == \"object\":\n        df[cname].fillna(method = 'backfill', inplace = True)\n# finally check for any duplicate rows\ndf.duplicated().sum()\n\"\"\"\n### Data Preprocessing\n\"\"\"\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\n\n# extract columns having data type as object (i.e non numeric)\nfor col in df:\n    if df[col].dtypes =='object':\n        df[col]=le.fit_transform(df[col])  # use LabelEncoder to transform values into numeric\ndf.head(20)\n# all values converted to numeric\ndf.nunique()\n# drop the features 11 and 13 because feature 11 corresponds to DriversLicencse and 13 to ZipCode which are both unimportant for us\ndf = df.drop([11, 13], axis=1)\n# view the df to verify\ndf.head()\n# segregate features and labels into separate variables\nX = df.drop([15], axis =1)\ny = df[15]\n# perform one hot encoding on columns that have less than 5 unique values so that all values are considered of equal weight\nX = pd.get_dummies(X, columns=[3,4,8,9,12]) \n# Split into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)\n# data scaling\n\nscaler = MinMaxScaler(feature_range=(0,1))\nrescaledX_train = scaler.fit_transform(X_train)\nrescaledX_test = scaler.fit_transform(X_test)\n\"\"\"\n### Model Building\n\nThis is a classifcation problem and the possible models I would consider for this are- Logistic Regression, Random Forrest Classifer and KNeighbors Classifer. Lets build these models and check accuraries\n\"\"\"\n# Logistic Regression Model\nfrom sklearn.linear_model import LogisticRegression\n\nlr_model = LogisticRegression(random_state = 15)\nlr_model.fit(rescaledX_train, y_train)\ny_pred = lr_model.predict(rescaledX_test)\n# model evaluation\nprint(\"Accuracy of logistic regression classifier: \", lr_model.score(rescaledX_test, y_test))\n# Random Forest Classifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nrfc_model = RandomForestClassifier(random_state = 36)\nrfc_model.fit(rescaledX_train, y_train)\ny_pred = rfc_model.predict(rescaledX_test)\n# model evaluation\nprint(\"Accuracy of random forest classifier: \", rfc_model.score(rescaledX_test, y_test))\n#KNeightboursClassifier Model\nfrom sklearn.neighbors import KNeighborsClassifier\n\nkn_model = KNeighborsClassifier()\nkn_model.fit(rescaledX_train, y_train)\ny_pred = kn_model.predict(rescaledX_test)\n# model evaluation\nprint(\"Accuracy of KNeighbors classifier: \", kn_model.score(rescaledX_test, y_test))\n\"\"\"\nThe Random Forest and KNeighbors Classifiers have the best accuracy. Lets hypertune parameters for these and check our best model for Credit Card Approval predictions!\n\"\"\"\n\"\"\"\n### Hypertuning the model\n\"\"\"\n# hyperparameter tuning for RandomForestClassifier\nmax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\nparameters = {'n_estimators': [20, 50, 60, 80, 90, 100, 120, 150, 200], 'max_features': [\"auto\", \"sqrt\", \"log2\"]}\ncls = GridSearchCV(estimator = rfc_model, param_grid = parameters)\ncls.fit(rescaledX_train, y_train)\n\n# displaying the best params \ncls.best_params_\nrfc_model2 = RandomForestClassifier(random_state = 36, n_estimators = 150, max_features = 'auto')\nrfc_model2.fit(rescaledX_train, y_train)\ny_pred = rfc_model2.predict(rescaledX_test)\nrfc_model2.score(rescaledX_test, y_test)\n# hyperparameter tuning for RandomForestClassifier\n\nn_neighbors = range(1, 21, 2)\nparameters = {'n_neighbors': n_neighbors, 'weights': ['uniform', 'distance'], 'metric': ['euclidean', 'manhattan', 'minkowski']}\ncls = GridSearchCV(estimator = kn_model, param_grid = parameters)\ncls.fit(rescaledX_train, y_train)\n\n# displaying the best params \ncls.best_params_\nkn_model2 = KNeighborsClassifier(n_neighbors=15, weights = 'distance', metric='euclidean')\nkn_model2.fit(rescaledX_train, y_train)\ny_pred = kn_model2.predict(rescaledX_test)\nkn_model2.score(rescaledX_test, y_test)\n\"\"\"\nThe best score is using the Random Forest Classifier model with parameters obtained from GridSearchCV(). Hence, our final model for Credit Card Aprovals is now ready!\n\"\"\"\nmodel = RandomForestClassifier(random_state = 36, n_estimators = 150, max_features = 'auto')\nmodel.fit(rescaledX_train, y_train)\ny_pred = model.predict(rescaledX_test)\nmodel.score(rescaledX_test, y_test)\n\"\"\"\n### <b>The Machine Learning Model is able to predict Credit Card Approvals with an enhanced accuracy of 90.36%<\/b>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9bfbcc08b553af'}"}
{"id":"55492","text":"\"\"\"\n# LightGBM GPU Build Installation\n\n* Poor accuracy\n\n* Didn't speedup at all(even after using recommended settings)\n\n[https:\/\/lightgbm.readthedocs.io\/en\/latest\/GPU-Performance.html#:~:text=In%20LightGBM%2C%20the%20main%20computation,ranking%2C%20regression%2C%20etc).]\n\"\"\"\n#%%bash\n#apt-get install --no-install-recommends git cmake build-essential libboost-dev libboost-system-dev libboost-filesystem-dev\n#git clone --recursive https:\/\/github.com\/microsoft\/LightGBM\n#cd LightGBM\n#mkdir build\n#cd build\n#cmake -DUSE_GPU=1 -DOpenCL_LIBRARY=\/usr\/local\/cuda\/lib64\/libOpenCL.so -DOpenCL_INCLUDE_DIR=\/usr\/local\/cuda\/include\/ ..\n#make -j$(nproc)\n#cd ..\n#cd LightGBM\/python-package\/;python3 setup.py install --precompile\n#mkdir -p \/etc\/OpenCL\/vendors && echo \"libnvidia-opencl.so.1\" > \/etc\/OpenCL\/vendors\/nvidia.icd\n#rm -r LightGBM\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.pylab import rcParams\nrcParams['figure.figsize'] = 15,15\nimport seaborn as sns\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom catboost import CatBoostClassifier\n\nfrom sklearn.model_selection import train_test_split,StratifiedShuffleSplit,StratifiedKFold\nfrom sklearn.preprocessing import LabelEncoder,RobustScaler\nfrom sklearn.metrics import roc_auc_score,accuracy_score ,confusion_matrix\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom imblearn.under_sampling import TomekLinks\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.combine import SMOTETomek\nfrom imblearn.under_sampling import ClusterCentroids , NearMiss\n\nfrom tqdm.notebook import tqdm ,tnrange\ntrain_data = pd.read_csv('..\/input\/healthcareanalyticsii\/train.csv')\ntest_data = pd.read_csv('..\/input\/healthcareanalyticsii\/test.csv')\nprint(train_data.shape)\ntrain_data.head()\nprint(test_data.shape)\ntest_data.head()\ndef nullColumns(train_data):\n    list_of_nullcolumns =[]\n    for column in train_data.columns:\n        total= train_data[column].isna().sum()\n        try:\n            if total !=0:\n                print('Total Na values is {0} for column {1}' .format(total, column))\n                list_of_nullcolumns.append(column)\n        except:\n            print(column,\"-----\",total)\n    print('\\n')\n    return list_of_nullcolumns\n\n\ndef percentMissingFeature(data):\n    data_na = (data.isnull().sum() \/ len(data)) * 100\n    data_na = data_na.drop(data_na[data_na == 0].index).sort_values(ascending=False)[:30]\n    missing_data = pd.DataFrame({'Missing Ratio' :data_na})\n    return data_na\n\n\ndef plotMissingFeature(data_na):\n    f, ax = plt.subplots(figsize=(15, 12))\n    plt.xticks(rotation='90')\n    if(data_na.empty ==False):\n        sns.barplot(x=data_na.index, y=data_na)\n        plt.xlabel('Features', fontsize=15)\n        plt.ylabel('Percent of missing values', fontsize=15)\n        plt.title('Percent missing data by feature', fontsize=15)\nprint('train data')\nprint(nullColumns(train_data))\nprint(percentMissingFeature(train_data))\nprint('\\n')\nprint('test_data')\nprint(nullColumns(test_data))\nprint(percentMissingFeature(test_data))\nstay = train_data.loc[:,\"Stay\"].value_counts().rename('Count')\nplt.xlabel(\"Stay\")\nplt.ylabel('Count')\nsns.barplot(stay.index , stay.values).set_title('Stay')\nsns.set(style=\"white\", palette=\"muted\", color_codes=True)\n\nf, axes = plt.subplots(3, 2, figsize=(15, 15))\n\nradiotherapy = train_data[train_data.Department =='radiotherapy'][\"Stay\"].value_counts().rename('Count')\n\nanesthesia = train_data[train_data.Department =='anesthesia'][\"Stay\"].value_counts().rename('Count')\n\ngynecology = train_data[train_data.Department =='gynecology'][\"Stay\"].value_counts().rename('Count')\n\nsurgery = train_data[train_data.Department =='surgery'][\"Stay\"].value_counts().rename('Count')\n\ntb = train_data[train_data.Department =='TB & Chest disease'][\"Stay\"].value_counts().rename('Count')\n\nsns.barplot(radiotherapy.index,radiotherapy,  color=\"b\", ax=axes[0, 0]).set_title('Department : radiotherapy')\n\nsns.barplot(anesthesia.index,anesthesia,   color=\"r\", ax=axes[0, 1]).set_title('Department : anesthesia')\n\nsns.barplot(gynecology.index,gynecology,  color=\"g\", ax=axes[1, 0]).set_title('Department : gynecology')\n\nsns.barplot(surgery.index,surgery, color=\"m\", ax=axes[1, 1]).set_title('Department : surgery')\n\nsns.barplot(tb.index,tb, color=\"m\", ax=axes[2, 0]).set_title('Department : TB & Chest disease')\n\nsns.barplot(stay.index,stay, color=\"m\", ax=axes[2, 1]).set_title('Department : ALL')\n\nplt.xlabel(\"Stay\")\n\nplt.setp(axes,yticks = np.arange(0,50000,5000))\n\nfor ax in f.axes:\n    \n    plt.sca(ax)\n    \n    plt.xticks(rotation=45)\n\nplt.tight_layout()\n\nsns.set(style=\"white\", palette=\"muted\", color_codes=True)\n\nf, axes = plt.subplots(6, 2, figsize=(15, 15))\n\nstay0 = train_data[train_data.Stay =='0-10'][\"Department\"].value_counts().rename('Count')\n\nstay1 = train_data[train_data.Stay =='11-20'][\"Department\"].value_counts().rename('Count')\n\nstay2 = train_data[train_data.Stay =='21-30'][\"Department\"].value_counts().rename('Count')\n\nstay3 = train_data[train_data.Stay =='31-40'][\"Department\"].value_counts().rename('Count')\n\nstay4 = train_data[train_data.Stay =='41-50'][\"Department\"].value_counts().rename('Count')\n\nstay5 = train_data[train_data.Stay =='51-60'][\"Department\"].value_counts().rename('Count')\n\nstay6 = train_data[train_data.Stay =='61-70'][\"Department\"].value_counts().rename('Count')\n\nstay7 = train_data[train_data.Stay =='71-80'][\"Department\"].value_counts().rename('Count')\n\nstay8 = train_data[train_data.Stay =='81-90'][\"Department\"].value_counts().rename('Count')\n\nstay9 = train_data[train_data.Stay =='91-100'][\"Department\"].value_counts().rename('Count')\n\nstay10 = train_data[train_data.Stay =='More than 100 Days'][\"Department\"].value_counts().rename('Count')\n\nsns.barplot(stay0.index,stay0,  color=\"b\", ax=axes[0, 0]).set_title('Stay : 0-10')\n                   \nsns.barplot(stay1.index,stay2,  color=\"r\", ax=axes[0, 1]).set_title('Stay : 11-20')\n\nsns.barplot(stay2.index,stay2,  color=\"b\", ax=axes[1, 0]).set_title('Stay : 21-30')\n\nsns.barplot(stay3.index,stay3,  color=\"g\", ax=axes[1, 1]).set_title('Stay : 31-40')\n\nsns.barplot(stay4.index,stay4,  color=\"b\", ax=axes[2, 0]).set_title('Stay : 41-50')\n\nsns.barplot(stay5.index,stay5,  color=\"b\", ax=axes[2, 1]).set_title('Stay : 51-60')\n\nsns.barplot(stay6.index,stay6,  color=\"m\", ax=axes[3, 0]).set_title('Stay : 61-70')\n\nsns.barplot(stay7.index,stay7, color=\"b\", ax=axes[3, 1]).set_title('Stay : 71-80')\n\nsns.barplot(stay8.index,stay8,  color=\"b\", ax=axes[4, 0]).set_title('Stay : 81-90')\n\nsns.barplot(stay9.index,stay9,  color=\"g\", ax=axes[4, 1]).set_title('Stay : 91-100')\n\nsns.barplot(stay10.index,stay10, color=\"r\", ax=axes[5, 0]).set_title('Stay : >100')\n\nplt.setp(axes, yticks = np.arange(0,20000,5000))\n\n\nfor ax in f.axes:\n    \n    plt.sca(ax)\n    \n    plt.xticks(rotation=45)\n\nplt.tight_layout()\nsns.set(style=\"white\", palette=\"muted\", color_codes=True)\n\nf, axes = plt.subplots(3, 1, figsize=(15, 15))\n\nemergency = train_data[train_data['Type of Admission'] =='Emergency'][\"Stay\"].value_counts().rename('Count')\n\ntrauma = train_data[train_data['Type of Admission'] =='Trauma'][\"Stay\"].value_counts().rename('Count')\n\nurgent = train_data[train_data['Type of Admission'] =='Urgent'][\"Stay\"].value_counts().rename('Count')\n\nsns.barplot(emergency.index,emergency,  color=\"b\", ax=axes[0]).set_title('Admn. Type : Emergency')\n\nsns.barplot(trauma.index,trauma,   color=\"r\", ax=axes[1]).set_title('Admn. Type : Trauma')\n\nsns.barplot(urgent.index,urgent,  color=\"g\", ax=axes[2]).set_title('Admn. Type : Urgent')\n\nplt.setp(axes, yticks = np.arange(0,50000,10000))\n\nfor ax in f.axes:\n    \n    plt.sca(ax)\n    \n    plt.xticks(rotation=45)\n\nplt.tight_layout()\ntrain_data['City_Code_Patient'] = train_data['City_Code_Patient'].fillna(-1)\ntrain_data['Bed Grade'] = train_data['Bed Grade'].fillna(-1)\ntest_data['City_Code_Patient'] = test_data['City_Code_Patient'].fillna(-1)\ntest_data['Bed Grade'] = test_data['Bed Grade'].fillna(-1)\ncat_cols = ['Hospital_code','Hospital_type_code','City_Code_Hospital','Hospital_region_code'\n            ,'Department','Ward_Type','Ward_Facility_Code','Bed Grade','City_Code_Patient',\n           # 'Type of Admission','Severity of Illness',\n            'Age']\nlabel = 'Stay'\ndef encode_cat_cols(train, test, cat_cols): #target\n\n    train_df = train_data.copy()\n    \n    test_df = test_data.copy()\n    \n    # Making a dictionary to store all the labelencoders for categroical columns to transform them later.\n    \n    le_dict = {}\n\n    for col in cat_cols:\n        \n        le = LabelEncoder()\n        \n        le.fit(train_df[col].unique().tolist() + test_df[col].unique().tolist())\n        \n        train_df[col] = le.transform(train_df[[col]])\n        \n        test_df[col] = le.transform(test_df[[col]])\n\n        le_dict[col] = le\n\n    le = LabelEncoder()\n    \n    train_df[label] = le.fit_transform(train_df[[label]])\n    \n    le_dict[label] = le\n    \n    train_df['Type of Admission'] = train_df['Type of Admission'].map({'Urgent':0,'Emergency':1,'Trauma':2})\n    \n    train_df['Severity of Illness'] = train_df['Severity of Illness'].map({'Minor':0,'Moderate':1,'Extreme':2})\n    \n    test_df['Type of Admission'] = test_df['Type of Admission'].map({'Urgent':0,'Emergency':1,'Trauma':2})\n    \n    test_df['Severity of Illness'] = test_df['Severity of Illness'].map({'Minor':0,'Moderate':1,'Extreme':2})\n    \n    return train_df, test_df, le_dict\ndef feature_importance(model, X_train):\n\n    fI = model.booster_.feature_importance(importance_type='gain')\n    \n    print(fI)\n    \n    names = X_train.columns.values\n    \n    ticks = [i for i in range(len(names))]\n    \n    plt.bar(ticks, fI)\n    \n    plt.xticks(ticks, names,rotation = 90)\n    \n    plt.show()\ntrain_df, test_df, le_dict = encode_cat_cols(train_data,test_data,cat_cols)\n#After Feature Engineering\n# https:\/\/www.kaggle.com\/gcspkmdr\/lets-get-rid-of-the-patients-feature-engineering\n\ncombined_data = pd.read_csv('..\/input\/lets-get-rid-of-the-patients-feature-engineering\/combined.csv')\ntrain_df = combined_data[combined_data['train']==1]\n\ntest_df = combined_data[combined_data['train']==0]\ntrain_df.drop(columns = ['case_id','train','patientid','Hospital_code',\n                         'Hospital_type_code','City_Code_Hospital','Ward_Facility_Code'],inplace = True)\n\ntarget = train_df.pop('Stay')\n\ntest_df.drop(columns = ['case_id','train','Stay','patientid','Hospital_code',\n                        'Hospital_type_code','City_Code_Hospital','Ward_Facility_Code'],inplace = True)\ncat_features = ['Hospital_region_code','Department','Ward_Type','Bed Grade','City_Code_Patient','Type of Admission','Severity of Illness','Age']\n\nfor f in cat_features:\n    \n    train_df[f] = train_df[f].astype('category')\n    \n    test_df[f] = test_df[f].astype('category')\n\"\"\"\n# Cross Validation\n![](https:\/\/4.bp.blogspot.com\/-wpr6O3EBAfU\/WbHyt6UCOVI\/AAAAAAAAjPw\/Y1DaO6qcV8oDYjJHzJ1PaPB2EXHmYtBBQCLcBGAs\/s1600\/%25E6%2593%25B7%25E5%258F%2596.JPG)\n\n* **The CV score generated using the methodology shown in the above figure is a better indicator of model performance than public LB**\n\"\"\"\n%%time\n\n##LightGBM\n\nscores = []\n\navg_loss = []\n\nX_train_cv,y_train_cv = train_df.copy(), target.copy()\n\nsssf = StratifiedShuffleSplit(n_splits=5, test_size = 0.45 ,random_state=1)\n\nfor i, (idxT, idxV) in enumerate(sssf.split(X_train_cv, y_train_cv)):\n    \n    print('Fold',i)\n    \n    print(' rows of train =',len(idxT),'rows of holdout =',len(idxV))\n    \n    clf = lgb.LGBMClassifier(n_estimators=10000,\n                             max_depth=8,\n                             learning_rate=0.1,\n                             subsample=0.85,\n                             colsample_bytree=0.5,\n                             #device ='gpu',\n                             #gpu_platform_id = 0,\n                             #gpu_device_id =  0,\n                             objective ='multiclass',\n                             #max_bin=63,\n                             #gpu_use_dp=False,\n                             random_state = 1,\n                             #categorical_columns = cat_features\n                            )        \n    \n    h = clf.fit(X_train_cv.iloc[idxT], y_train_cv.iloc[idxT], \n                eval_set=[(X_train_cv.iloc[idxV],y_train_cv.iloc[idxV])],\n                verbose=100,eval_metric=['multi_logloss'],\n                early_stopping_rounds=50)\n    \n    acc = accuracy_score(y_train_cv.iloc[idxV],np.argmax(clf.predict_proba(X_train_cv.iloc[idxV]),axis =1))*100\n    \n    scores.append(acc)\n\n    avg_loss.append(clf.best_score_['valid_0']['multi_logloss'])\n    \n    print ('LGB Val CV=',acc)\n    \n    print('#'*100)\n    \n    if i==0:\n        feature_importance(clf,X_train_cv)\n\nprint(\"Multi Log Loss Stats {0:.5f},{1:.5f}\".format(np.array(avg_loss).mean(), np.array(avg_loss).std()))\n\nprint('%.3f (%.3f)' % (np.array(scores).mean(), np.array(scores).std()))\n\"\"\"\n# Model Building\n\"\"\"\ntrees = 5\n\nseeds = [32,432,73]\n\nsubmission = pd.read_csv('..\/input\/healthcareanalyticsii\/sample_submission.csv')\n\nprobs = np.zeros(shape=(len(test_df),11))\n\nsubmission_probs = pd.DataFrame(columns = ['case_id'] + list(le_dict['Stay'].classes_))\n\nsubmission_probs.iloc[:,0] = submission.iloc[:,0]\n\nsubmission_probs.iloc[:,1:] = 0\n%%time\n\n##LightGBM\n\n#groups = train_df['patientid'].values\n\nscores = []\n\navg_loss = []\n\nsubmission_name = [] \n\nX_train_cv,y_train_cv = train_df.copy(), target.copy()\n\nfor seed in tnrange(len(seeds)):\n\n    sssf = StratifiedShuffleSplit(n_splits=5, test_size = 0.3 ,random_state=seeds[seed])\n\n    for j, (idxT, idxV) in tqdm(enumerate(sssf.split(X_train_cv, y_train_cv))):\n\n        print('Fold',j)\n\n        print(' rows of train =',len(idxT),'rows of holdout =',len(idxV))\n\n        model_lgb = [0] *trees\n\n        for i in tnrange(trees):\n\n            print('Tree',i)\n\n            model_lgb[i] = lgb.LGBMClassifier(n_estimators=1000,\n                                     max_depth=8,\n                                     learning_rate=0.1,\n                                     subsample=0.8,\n                                     colsample_bytree=0.5,\n                                     #device ='gpu',\n                                     #gpu_platform_id = 0,\n                                     #gpu_device_id =  0,\n                                     objective ='multiclass',\n                                     random_state = i*27\n                                    )        \n\n            model_lgb[i].fit(X_train_cv.iloc[idxT], y_train_cv.iloc[idxT], \n                        eval_set=[(X_train_cv.iloc[idxV],y_train_cv.iloc[idxV])],\n                        verbose=100,eval_metric=['multi_logloss'],\n                        early_stopping_rounds=50)\n\n            probs_file_name = 'probs_'+str(seeds[seed])+'_'+str(j)+'_'+str(i)+\".csv\"\n            \n            submisssion_file_name  = 'submission_'+str(seeds[seed])+'_'+str(j)+'_'+str(i)+\".csv\"\n            \n            model_lgb_probs = model_lgb[i].predict_proba(test_df)\n            \n            submission_probs.iloc[:,1:] = model_lgb_probs\n            \n            # probablity file per seed per split per tree\n            submission_probs.to_csv(probs_file_name,index = False)\n            \n            submission['Stay'] = le_dict['Stay'].inverse_transform(np.argmax(model_lgb_probs,axis =1))\n            \n            # submission file per seed per split per tree\n            submission.to_csv(submisssion_file_name,index =False)\n            \n            probs += model_lgb_probs\n            \n            acc = accuracy_score(y_train_cv.iloc[idxV],np.argmax(model_lgb[i].predict_proba(X_train_cv.iloc[idxV]),axis =1))*100\n            \n            scores.append(acc)\n            \n            submission_name.append(submisssion_file_name)\n            \n            avg_loss.append(model_lgb[i].best_score_['valid_0']['multi_logloss'])\n\n            #print ('LGB Accuracy Split =',acc)\n            \n            print('#'*100)\n    \n\nprint(\"Average Multi Log Loss Stats {0:.5f},{1:.5f}\".format(np.array(avg_loss).mean(), np.array(avg_loss).std()))\n\n#print('%.3f (%.3f)' % (np.array(scores).mean(), np.array(scores).std()))\nsubmission_probs.iloc[:,1:] = probs\n\n# probablity combined\nsubmission_probs.to_csv('probs.csv',index =False)\nsubmission['Stay'] = le_dict['Stay'].inverse_transform(np.argmax(probs,axis =1))\n\n# submission file combined            \nsubmission.to_csv('submission.csv',index =False)\n            \nmodel_stats = pd.DataFrame({'submission':submission_name,'accuracy':scores,'validation_loss':avg_loss})\nmodel_stats.head()\nmodel_stats.to_csv('model_stats.csv',index =False)\n# Ensembles\n# https:\/\/www.kaggle.com\/gcspkmdr\/lets-get-rid-of-the-patients-xgboost?select=probs.csv\n# https:\/\/www.kaggle.com\/gcspkmdr\/lets-get-rid-of-the-patients-catboost\/output    ","meta":"{'source': 'AI4Code', 'id': '66447ce964ecbd'}"}
{"id":"37898","text":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(\"..\/input\/gold-prices\/annual_csv.csv\")\ndf2= pd.read_csv(\"..\/input\/gold-prices\/monthly_csv.csv\")\n\ndf2.tail()\nplt.plot(df2[\"Price\"])\ndf.head()\n\"\"\"\n> I WANT TO SEE JUST YEARS WITHOUT MONTHS\n\"\"\"\nlist=np.arange(1950,2020)\ndf[\"Date\"]=list\ndf.head()\nplt.plot(df[\"Date\"],df[\"Price\"],\"ro\")\n\nplt.figure(figsize=(12,5))\nplt.subplot(121)\nplt.plot(df[\"Date\"],df[\"Price\"],\"ro\")\nplt.subplot(122)\nplt.plot(df2[\"Price\"])\n\ndf.describe()","meta":"{'source': 'AI4Code', 'id': '45cfde4fba2239'}"}
{"id":"72259","text":"!jt -t oceans16\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport math\nfrom collections import Counter\nipl = pd.read_csv('..\/input\/ipl-complete-dataset-20082020\/IPL Matches 2008-2020.csv', parse_dates = True, index_col = 2)\n\n## Cleaning The Data##\n\nipl = ipl.drop(columns = ['id','method'])\n\n## check for Columns with NaN Values\n\nsns.set_style('dark')\n\nplt.rcParams[\"figure.figsize\"] = (28,6)\n\nipl.isna().sum().plot(kind = 'bar',color = '#00afb9',label = \"Number of NaN's\")\n\nplt.xlabel('Columns', color = '#f07167', fontsize = 20)\n\nplt.ylabel(\"Number of Missing Values\", color = '#f07167', fontsize = 20)\n\nplt.title(\"MISSING VALUES\", color  = '#0081a7', fontsize = 20)\n\nplt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)\n\nplt.yticks(color = '#6d597a', fontsize = 20)\n\nplt.axhline(y = 4, label = \"Four columns with Similar number of NaN Values\", linestyle = '--')\n\nplt.legend(fontsize = 20)\n\nplt.annotate(xy =(10,16) ,xytext =(4,10) ,text ='\"result_margin\" column has largest number of NaN Values'\\\n             ,arrowprops = {'arrowstyle':'simple','color':'#00296b'}, fontsize = 20, color = \"#1f2041\")\nplt.show()\n\nplt.clf()\n\n\"\"\"\n# Filling up the NaN values\n***\n#### As we can see 'city' Column and 'result_margin' column Have most NaN values. I will fill city columns NaN values with 'Unknown Venue'. And Result Margin will be filled with value 0.\n***\n#### Alse note that columns = ['player_of_match','winner','result','eliminator'] have Similar amount of NaN. I have researched a bit and these tend to be No results. I will Fill these with 'No Result'. But I dont think 'eliminator' Column is that important. So I will leave it as it is.\n\"\"\"\n## Cleaning Data From NaN Values\n\nipl['city'] = ipl['city'].fillna('Unkown City')\n\nipl['winner'] = ipl['winner'].fillna('No Result')\n\nipl['result'] = ipl['result'].fillna('No Result')\n\nipl['player_of_match'] = ipl['player_of_match'].fillna('No Result')\n\nipl['result_margin'] = ipl['result_margin'].fillna(0)\n##Umpires in IPL History##\n\n## Extracting Umpire Data from the IPL Data##\n\numpire1 = ipl['umpire1'].to_list()\n\numpire2 = ipl['umpire2'].to_list()\n\numpire_df = pd.DataFrame()\n\numpire_df['Total_umpires'] = umpire1+umpire2\n\n## Plotting the extracted data to get insights##\n\numpire = sns.catplot(kind = 'count',x = 'Total_umpires', data = umpire_df, color  = '#00afb9')\n\n##Customising the PLOT##\n\nsns.set_style('dark')\n\numpire.fig.set_size_inches([28,6])\n\nplt.title(\"Number of Matches Umpired per Unique Umpire\", fontsize = 20, color  = '#0081a7')\n\nplt.xlabel(\"Umpires\", color = '#fb5607', fontsize = 20)\n\nplt.ylabel('Match Count',  color = '#fb5607', fontsize = 20)\n\nplt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)\n\nplt.yticks(color = '#6d597a', fontsize = 20)\n\nplt.annotate( xy = (20, 120), fontsize = 20,text = 'S Ravi Tops with 120 Matches',\\\n            arrowprops = {'arrowstyle':'simple', 'color':'#00296b'}, xytext = (21,115), color = \"#1f2041\")\nplt.show()\n\nplt.clf()\n\"\"\"\n# Umpiring facts that I observed from the data\n***\n\n\"\"\"\n\"\"\"\n#### 1) <span style = 'color:#0081a7'>S. Ravi<\/span> holds the distinction of Umpiring most number of matches in the IPL\n#### 2) In the entire History of IPL <span style = 'color:#0081a7'>56<\/span> Different Umpires have Supervised IPL Matches\n\"\"\"\n\"\"\"\n# Modes of wins in IPL\n\"\"\"\npop = 0\n\nsns.set_palette('YlGnBu')\n\nexplode1 = [ 0 if x != 'No Result' else 0.2 for x in ipl['result'].value_counts().index ]\n\nplt.pie(ipl['result'].value_counts(),explode = explode1, autopct = '%1.1f%%')\n\nplt.legend(labels = ipl['result'].value_counts().index , fontsize = 20, loc = 'upper right', bbox_to_anchor=(1.5,0.9))\n\nplt.show()\n\nplt.clf()\n## Corrcting the Error OF Chinnaswamy Stadium##\n\nipl = ipl.replace(['M Chinnaswamy Stadium'],'M.Chinnaswamy Stadium')\n\n## Creating a Count Plot withrespect to Venue at which mathces are held##\n\ng = sns.catplot(x = 'venue', data = ipl, kind = 'count', color = '#00afb9')\n\n##customising the Plot##\n\nsns.set_style('dark')\n\ng.fig.set_size_inches([28,6])\n\n# g.fig.suptitle(\"No of Cricket Matches in Different Venues\", color  = '#7209b7',y = 0.945)\n\nplt.title(\"Number of Cricket Matches in Different Venues\", fontsize = 20, color  = '#0081a7')\n\nplt.ylabel('Number of Matches Per Stadium',color = '#fb5607')\n\nplt.xlabel('Stadium', color = '#fb5607', fontsize = 20)\n\nplt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)\n\nplt.yticks(color = '#6d597a', fontsize = 20)\n\nplt.annotate(xy = (0,78), xytext = (10,70), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\\\n            text = \"M.Chinnaswamy Stadium Hosted Most IPL Matches\", color = \"#1f2041\")\n\nplt.show()\n\nplt.clf()\n\"\"\"\n# M.Chinnaswamy Stadium\n#### As we can see from the above countplot M.Chinnaswamy Stadium in Chennai Held Most IPL Matches.\n\"\"\"\n# Overall Teams\n\nprint(ipl['winner'].unique())\n\"\"\"\n# Errors in the IPL Team List\n#### We have Noticed a Entry error. Both Risisng Pune Supergiants and Rising Pune Supergiant are obivously same team. But due to wrong entry we have Rising Pune Supergaints which is not the name of franchise. We should Correct This Error.\n\"\"\"\n\"\"\"\n# Re-Branding of Delhi and HyderaBad\n#### Both The Delhi DareDevils and the Delhi Capitals are the same team. The Delhi daredevils in 2018 renamed to Delhi capitals. And also Deccan Charges were acquired by a new owner and was Renamed to Sunrisers hyderabad. So for the Sake of Better Coding Lets Rename Delhi Daredevils to Delhi capitals and Deccan Chargers to Sunrisers Hyderabad in 'ipl' DataFrame. Specifically in the column 'winner'\n\"\"\"\n#Correcting Errors and Rebranding Team names\n\nipl = ipl.replace(['Delhi Daredevils'],'Delhi Capitals')\n\nipl = ipl.replace(['Rising Pune Supergiants'],'Rising Pune Supergiant')\n\nipl = ipl.replace(['Deccan Chargers'],'Sunrisers Hyderabad')\n\nprint(ipl['winner'].unique())\n\nipl_teams = list(ipl['winner'].unique())\n\nipl_cities  = list(ipl['city'].unique())\n\"\"\"\n# Overall\n#### The Above list is the Cleaned Version of Teams that participated in Ipl History. From the list we can count 13 Unique teams that participated.\n\"\"\"\n## Lets See Who won the Most ##\n\nwinner = sns.catplot(kind = 'count', x = 'winner', data = ipl, color  = '#00afb9')\n\n## Customising the Plot ##\n\nsns.set_style('dark')\n\nwinner.fig.set_size_inches([28,6])\n\nplt.title(\"Number of Matches Won by Each Franchise\", fontsize = 20, color  = '#0081a7')\n\nplt.ylabel('Wins',color = '#fb5607', fontsize = 20)\n\nplt.xlabel('IPL Franchises', color = '#fb5607', fontsize = 20)\n\nplt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)\n\nplt.yticks(color = '#6d597a')\n\nplt.annotate(xy = (7,118), xytext = (8,120), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\\\n            text = \"Mumbai Indians Won most Matches\", color = \"#1f2041\")\nplt.show()\n\nplt.clf()\n##Plot For Cities Which Hosted Ipl##\n\nsns.set_style('dark')\n\ncity = sns.catplot(x = 'city', data = ipl, kind ='count', color  = '#00afb9')\n\n## customizing the Plot ##\n\ncity.fig.set_size_inches([28,6])\n\nplt.title('Number of Matches Per City', color  = '#0081a7',fontsize = 20)\n\nplt.ylabel('Number of Matches Per City',color = '#fb5607', fontsize = 20)\n\nplt.xlabel('City', color = '#fb5607', fontsize = 20)\n\nplt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)\n\nplt.yticks(color = '#6d597a', fontsize = 20)\n\n##Adding Annotations##\n\nplt.annotate(xy = (27,13), xytext = (24,40), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\\\n            text = \"Note That there are 13 Unknown Cities\", color = \"#1f2041\")\n\nplt.annotate(xy = (4,100), xytext = (7,65), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\\\n            text = \"Mumbai Hosted Most IPL Matches and \\nInterestigly Its the home town of Mumbai Indians the team with most wins in IPL\"\\\n             , color = \"#1f2041\")\n\nplt.show()\n\nplt.clf()\n\"\"\"\n# Observations From Above Two Plots\n#### Mumabai Indians are the Team with most Number of wins(with 120 wins) in IPL and Mumbai which is there home City also hosted most number of IPL Matches .\n\n#### This assumed correlation screams of \"HOME ADVANTAGE\". Lets see if such a term really holds value in the face of real data.\n\"\"\"\n## Filtering ipl Data Frame##\n\n\"\"\" Let's cretate a Data Frame from ipl Data Frame with condition that Mumbai indians won the match\"\"\"\n\nipl_mi_won = ipl[ipl['winner'] == 'Mumbai Indians']\n\nsns.set_palette('YlGnBu')\n\nfig, ax = plt.subplots()\n\nexplode = [0.1 if city == 'Mumbai' else 0 for city in ipl_mi_won['city'].value_counts().index ]\n\nax.pie(ipl_mi_won['city'].value_counts(), explode = explode, autopct='%1.1f%%', shadow = True)\n\n## customization ##\n\nax.legend(loc = 'upper right', bbox_to_anchor=(1.2,0.9), labels = ipl_mi_won['city'].value_counts().index )\n\nax.annotate(xy = (0.4,0.9), xytext = (1.5,1.5), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},color = \"#1f2041\", \\\n            text =\"Proving our Hypothesis True Mumbai Indians won 53 matches in Mumbai that is 44.2% of thier total 120 wins\")\n\nfig.set_size_inches([32,9])\n\nplt.plot()\n# lets remove rows with result == 'No Result' ##\n\nipl_without_no_result = ipl[ipl['winner'] != 'No Result']\n\n##Forming a Facet Grid##\n\ng = sns.catplot(kind = 'count', x= 'city', data = ipl_without_no_result, col ='winner', col_wrap = 3, color  = '#00afb9')\n\ng.set_xticklabels(rotation = 90,color = '#6d597a' )\n\ng.set_yticklabels(color = '#6d597a')\n\ng.set_xlabels('Cities' ,color = '#fb5607')\n\ng.set_ylabels('Wins in the city',color = '#fb5607')\n\ng.set_titles( color  = '#0081a7')\n\ng.add_legend()\n\nplt.show()\n\nplt.clf()\n\"\"\"\n### From the above Facet Grid it's pretty clear that Home Matches constitute a major chunk of Teams total match wins.\n### Lets further explore to seee if \"Home Advantage\" is Fictional or Real \n\"\"\"\n### Extracting data to Visualise Info ###\nteam_and_thier_best_city = []\n\npercentage_of_wins = []\n\nfor team in ipl_without_no_result['winner'].unique():\n    data = ipl_without_no_result[ipl_without_no_result['winner'] == team]['city'].value_counts(normalize =True)\n    team_and_thier_best_city.append(f'{team} at {list(data.index)[0]}')\n    percentage_of_wins.append(data.max()*100)\n    \n\n### Forming A bar plot using the Lists we created ###\n\nsns.barplot(x = team_and_thier_best_city, y = percentage_of_wins, color  = '#00afb9')\n\n### customization ###\n\nplt.xticks(rotation = 90, fontsize = 20,color = '#6d597a')\n\nplt.yticks( [0,10,20,30,40],['0%','10%','20%','30%','40%'],fontsize = 20,color = '#6d597a')\n\nplt.ylabel(\"Percentage of wins\", fontsize = 20, color = '#fb5607')\n\nplt.xlabel(\"Teams at cities where they won most\", fontsize = 20, color = '#fb5607')\n\nplt.title(\"Pecentage of wins at  Home \", color  = '#0081a7', fontsize = 20)\n\nplt.axhline(np.mean(percentage_of_wins), label = 'Mean', linestyle = '--', color = '#0077b6')\n\nplt.legend(fontsize = 20)\n\nplt.show()\n\"\"\"\n### Team have an average 35% of thier total wins at Home. From this we can conclude that \"Home Advantage\" is not A myth\n\n***\n\n\"\"\"\n\"\"\"\n# Importance of TOSS\n### While we proved Home Advantage is not fictious. There is one more Aspect of a cricket match which cricket community deem quite important and that is winning a toss. People feel that winning a toss can give a team massive advantage. Lets explore if it's True.\n\"\"\"\nprint(len(ipl_without_no_result[ipl_without_no_result['toss_winner'] == ipl_without_no_result['winner']].index))\nprint(len(ipl_without_no_result[ipl_without_no_result['toss_winner'] != ipl_without_no_result['winner']].index))\n\"\"\"\n### As we can see '418' times did teams win the toss and won the match and '394' times teams won the toss and still lost the match. with just 24 matches of difference we can say that winnig a TOSS doesnt help you in winning matches\n\"\"\"\n\"\"\"\n***\n\"\"\"\n\"\"\"\n# Conclusions and Some Finds\n* Of 56 umpires to have umpired in IPL ***S.Ravi*** Umpired Most number of IPL matches with 120 matches\n* ***M.Chinnaswamy*** Stadium in Banglore hosted most number of IPL matches. A whooping 80 matches were held at this Venue\n* ***Mumbai*** as a city hosted most number of IPL matches and The Mumbai's home team ***Mumbai Indians*** won most number of IPL matches\n* When we dug further we were able to see that Home Advantage is Real and playing at home does help teams\n* But winning a toss doesnt seems to have a deterministic effect on a match's outcome. \n\"\"\"\n\"\"\"\n# With this I wave you a Good Bye!! Take care and wear masks.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '84f16db9bd1303'}"}
{"id":"39367","text":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\nfrom fastai.vision import *\nfrom torchvision.models import *\nimport torch\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport seaborn as sns\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom joblib import load, dump\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.metrics import confusion_matrix\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks import *\nfrom torchvision import models as md\nfrom torch import nn\nfrom torch.nn import functional as F\nimport re\nimport math\nimport collections\nfrom functools import partial\nfrom torch.utils import model_zoo\nfrom sklearn import metrics\nfrom collections import Counter\nimport json\n\n\nfrom fastai import *\nfrom fastai.vision import *\nfrom torchvision.models import *\n#import pretrainedmodels\nimport torch\nimport torch.optim as optim\nfrom fastai.vision.models import *\nfrom fastai.vision.learner import model_meta\nfrom fastai.callbacks import *\nimport warnings\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plts\nfrom matplotlib import style\nimport seaborn as sns\n \n\n%matplotlib inline  \nstyle.use('fivethirtyeight')\nsns.set(style='whitegrid', color_codes=True)\n\nfrom sklearn.metrics import confusion_matrix\n\n\nimport cv2                  \n\nimport os, random\nfrom random import shuffle  \nfrom zipfile import ZipFile\nfrom PIL import Image\nfrom sklearn.utils import shuffle\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    \nseed_everything(42)\ntemp = vision.data.open_image\n\n!ls ..\/input\/new-model\/\n!mkdir models\n!cp '..\/input\/new-model\/modelk.pth' 'models\/'\n!ls .\/models\ndef get_df():\n    base_image_dir = os.path.join('..', 'input\/aptos2019-blindness-detection\/')\n    train_dir = os.path.join(base_image_dir,'train_images\/')\n    df = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))\n    df['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x)))\n    df = df.drop(columns=['id_code'])\n    df = df.sample(frac=1).reset_index(drop=True) #shuffle dataframe\n    test_df = pd.read_csv('..\/input\/aptos2019-blindness-detection\/sample_submission.csv')\n    return df, test_df\n\ndf, test_df = get_df()\nbs = 16\nsz = 380 \n\n\n# aptos19_stats = ([0.42, 0.22, 0.075], [0.27, 0.15, 0.081])\n# # tsfm1=[zoom_crop(scale=(0.5,2), do_rand=True),rotate(degrees=(-30,30))]\n# tsfm1 = get_transforms(do_flip=True, flip_vert=True, max_rotate=0.10, max_zoom=2.3, max_warp=0.0, max_lighting=0.3,p_affine=0.7)\n# data = ImageDataBunch.from_df(df=df_train,\n#                               path=PATH, folder='train_images', suffix='.png',\n#                               valid_pct=0.1,\n#                               ds_tfms=(tsfm1),\n#                               size=224,\n#                               bs=4,seed=42, \n#                               num_workers=4\n#                              ).normalize(imagenet_stats)\n# data1 = (ImageList.from_df(df=df,path='.\/',cols='path') \n#         .split_by_rand_pct(0.1) \n#         .label_from_df(cols='diagnosis',label_cls=FloatList) \n#         .transform(tsfm1,size=sz,resize_method=ResizeMethod.SQUISH,padding_mode='zeros') \n#         .databunch(bs=bs,num_workers=4) \n#         .normalize(aptos19_stats)  \n#        )\n# def crop_image1(img,tol=7):\n#     # img is image data\n#     # tol  is tolerance\n        \n#     mask = img>tol\n#     return img[np.ix_(mask.any(1),mask.any(0))]\n\n# def crop_image_from_gray(img,tol=7):\n#     if img.ndim ==2:\n#         mask = img>tol\n#         return img[np.ix_(mask.any(1),mask.any(0))]\n#     elif img.ndim==3:\n#         gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n#         mask = gray_img>tol\n        \n#         check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n#         if (check_shape == 0): # image is too dark so that we crop out everything,\n#             return img # return original image\n#         else:\n#             img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n#             img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n#             img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n#     #         print(img1.shape,img2.shape,img3.shape)\n#             img = np.stack([img1,img2,img3],axis=-1)\n#     #         print(img.shape)\n#         return img\n\n# def load_ben_color(path, sigmaX=10):\n#     image = cv2.imread(path)\n#     image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n#     image = crop_image_from_gray(image)\n#     image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n#     image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)\n        \n#     return image\n# IMG_SIZE = 512\n\n# def _load_format(path, convert_mode, after_open)->Image:\n#     image = cv2.imread(path)\n#     image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n#     image = crop_image_from_gray(image)\n#     image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n#     image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0), 10) ,-4 ,128)\n                    \n#     return Image(pil2tensor(image, np.float32).div_(255)) #return fastai Image format\n\n# vision.data.open_image = _load_format\nfrom fastai import *\nfrom fastai.vision import *\nfrom torchvision.models import *\n#import pretrainedmodels\nimport torch\nimport torch.optim as optim\nfrom fastai.vision.models import *\nfrom fastai.vision.learner import model_meta\nfrom fastai.callbacks import *\naptos19_stats = ([0.42, 0.22, 0.075], [0.27, 0.15, 0.081])\n# tsfm1=[zoom_crop(scale=(0.5,2), do_rand=True),rotate(degrees=(-30,30))]\ntsfm1 = get_transforms(do_flip=False, flip_vert=False, max_rotate=0., max_zoom=0., max_warp=0.0, max_lighting=0.,p_affine=0.)\n# data = ImageDataBunch.from_df(df=df_train,\n#                               path=PATH, folder='train_images', suffix='.png',\n#                               valid_pct=0.1,\n#                               ds_tfms=(tsfm1),\n#                               size=224,\n#                               bs=4,seed=42, \n#                               num_workers=4\n#                              ).normalize(imagenet_stats)\ndata = (ImageList.from_df(df=df,path='.\/',cols='path') \n        .split_by_rand_pct(0.1) \n        .label_from_df(cols='diagnosis',label_cls=FloatList) \n        .transform(tsfm1,size=380,) \n        .databunch(bs=bs,num_workers=4) \n        .normalize(imagenet_stats)  \n       )\ndata.show_batch(3,(5,5))\n\"\"\"\n# DAta\n\"\"\"\n\n\n# Parameters for the entire model (stem, all blocks, and head)\nGlobalParams = collections.namedtuple('GlobalParams', [\n    'batch_norm_momentum', 'batch_norm_epsilon', 'dropout_rate',\n    'num_classes', 'width_coefficient', 'depth_coefficient',\n    'depth_divisor', 'min_depth', 'drop_connect_rate', 'image_size'])\n\n\n# Parameters for an individual model block\nBlockArgs = collections.namedtuple('BlockArgs', [\n    'kernel_size', 'num_repeat', 'input_filters', 'output_filters',\n    'expand_ratio', 'id_skip', 'stride', 'se_ratio'])\n\n\n# Change namedtuple defaults\nGlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields)\nBlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields)\n\n\ndef relu_fn(x):\n    \"\"\" Swish activation function \"\"\"\n    return x * torch.sigmoid(x)\n\n\ndef round_filters(filters, global_params):\n    \"\"\" Calculate and round number of filters based on depth multiplier. \"\"\"\n    multiplier = global_params.width_coefficient\n    if not multiplier:\n        return filters\n    divisor = global_params.depth_divisor\n    min_depth = global_params.min_depth\n    filters *= multiplier\n    min_depth = min_depth or divisor\n    new_filters = max(min_depth, int(filters + divisor \/ 2) \/\/ divisor * divisor)\n    if new_filters < 0.9 * filters:  # prevent rounding by more than 10%\n        new_filters += divisor\n    return int(new_filters)\n\n\ndef round_repeats(repeats, global_params):\n    \"\"\" Round number of filters based on depth multiplier. \"\"\"\n    multiplier = global_params.depth_coefficient\n    if not multiplier:\n        return repeats\n    return int(math.ceil(multiplier * repeats))\n\n\ndef drop_connect(inputs, p, training):\n    \"\"\" Drop connect. \"\"\"\n    if not training: return inputs\n    batch_size = inputs.shape[0]\n    keep_prob = 1 - p\n    random_tensor = keep_prob\n    random_tensor += torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device)\n    binary_tensor = torch.floor(random_tensor)\n    output = inputs \/ keep_prob * binary_tensor\n    return output\n\n\ndef get_same_padding_conv2d(image_size=None):\n    \"\"\" Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n        Static padding is necessary for ONNX exporting of models. \"\"\"\n    if image_size is None:\n        return Conv2dDynamicSamePadding\n    else:\n        return partial(Conv2dStaticSamePadding, image_size=image_size)\n\nclass Conv2dDynamicSamePadding(nn.Conv2d):\n    \"\"\" 2D Convolutions like TensorFlow, for a dynamic image size \"\"\"\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True):\n        super().__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias)\n        self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]]*2\n\n    def forward(self, x):\n        ih, iw = x.size()[-2:]\n        kh, kw = self.weight.size()[-2:]\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih \/ sh), math.ceil(iw \/ sw)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            x = F.pad(x, [pad_w\/\/2, pad_w - pad_w\/\/2, pad_h\/\/2, pad_h - pad_h\/\/2])\n        return F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n\n\nclass Conv2dStaticSamePadding(nn.Conv2d):\n    \"\"\" 2D Convolutions like TensorFlow, for a fixed image size\"\"\"\n    def __init__(self, in_channels, out_channels, kernel_size, image_size=None, **kwargs):\n        super().__init__(in_channels, out_channels, kernel_size, **kwargs)\n        self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]] * 2\n\n        # Calculate padding based on image size and save it\n        assert image_size is not None\n        ih, iw = image_size if type(image_size) == list else [image_size, image_size]\n        kh, kw = self.weight.size()[-2:]\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih \/ sh), math.ceil(iw \/ sw)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            self.static_padding = nn.ZeroPad2d((pad_w \/\/ 2, pad_w - pad_w \/\/ 2, pad_h \/\/ 2, pad_h - pad_h \/\/ 2))\n        else:\n            self.static_padding = Identity()\n\n    def forward(self, x):\n        x = self.static_padding(x)\n        x = F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n        return x\n\n\nclass Identity(nn.Module):\n    def __init__(self,):\n        super(Identity, self).__init__()\n\n    def forward(self, input):\n        return input\n\n\n########################################################################\n############## HELPERS FUNCTIONS FOR LOADING MODEL PARAMS ##############\n########################################################################\n\n\ndef efficientnet_params(model_name):\n    \"\"\" Map EfficientNet model name to parameter coefficients. \"\"\"\n    params_dict = {\n        # Coefficients:   width,depth,res,dropout\n        'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n        'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n        'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n        'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n        'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n        'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n        'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n        'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n    }\n    return params_dict[model_name]\n\n\nclass BlockDecoder(object):\n    \"\"\" Block Decoder for readability, straight from the official TensorFlow repository \"\"\"\n\n    @staticmethod\n    def _decode_block_string(block_string):\n        \"\"\" Gets a block through a string notation of arguments. \"\"\"\n        assert isinstance(block_string, str)\n\n        ops = block_string.split('_')\n        options = {}\n        for op in ops:\n            splits = re.split(r'(\\d.*)', op)\n            if len(splits) >= 2:\n                key, value = splits[:2]\n                options[key] = value\n\n        # Check stride\n        assert (('s' in options and len(options['s']) == 1) or\n                (len(options['s']) == 2 and options['s'][0] == options['s'][1]))\n\n        return BlockArgs(\n            kernel_size=int(options['k']),\n            num_repeat=int(options['r']),\n            input_filters=int(options['i']),\n            output_filters=int(options['o']),\n            expand_ratio=int(options['e']),\n            id_skip=('noskip' not in block_string),\n            se_ratio=float(options['se']) if 'se' in options else None,\n            stride=[int(options['s'][0])])\n\n    @staticmethod\n    def _encode_block_string(block):\n        \"\"\"Encodes a block to a string.\"\"\"\n        args = [\n            'r%d' % block.num_repeat,\n            'k%d' % block.kernel_size,\n            's%d%d' % (block.strides[0], block.strides[1]),\n            'e%s' % block.expand_ratio,\n            'i%d' % block.input_filters,\n            'o%d' % block.output_filters\n        ]\n        if 0 < block.se_ratio <= 1:\n            args.append('se%s' % block.se_ratio)\n        if block.id_skip is False:\n            args.append('noskip')\n        return '_'.join(args)\n\n    @staticmethod\n    def decode(string_list):\n        \"\"\"\n        Decodes a list of string notations to specify blocks inside the network.\n\n        :param string_list: a list of strings, each string is a notation of block\n        :return: a list of BlockArgs namedtuples of block args\n        \"\"\"\n        assert isinstance(string_list, list)\n        blocks_args = []\n        for block_string in string_list:\n            blocks_args.append(BlockDecoder._decode_block_string(block_string))\n        return blocks_args\n\n    @staticmethod\n    def encode(blocks_args):\n        \"\"\"\n        Encodes a list of BlockArgs to a list of strings.\n\n        :param blocks_args: a list of BlockArgs namedtuples of block args\n        :return: a list of strings, each string is a notation of block\n        \"\"\"\n        block_strings = []\n        for block in blocks_args:\n            block_strings.append(BlockDecoder._encode_block_string(block))\n        return block_strings\n\n\ndef efficientnet(width_coefficient=None, depth_coefficient=None, dropout_rate=0.2,\n                 drop_connect_rate=0.2, image_size=None, num_classes=1000):\n    \"\"\" Creates a efficientnet model. \"\"\"\n\n    blocks_args = [\n        'r1_k3_s11_e1_i32_o16_se0.25', 'r2_k3_s22_e6_i16_o24_se0.25',\n        'r2_k5_s22_e6_i24_o40_se0.25', 'r3_k3_s22_e6_i40_o80_se0.25',\n        'r3_k5_s11_e6_i80_o112_se0.25', 'r4_k5_s22_e6_i112_o192_se0.25',\n        'r1_k3_s11_e6_i192_o320_se0.25',\n    ]\n    blocks_args = BlockDecoder.decode(blocks_args)\n\n    global_params = GlobalParams(\n        batch_norm_momentum=0.99,\n        batch_norm_epsilon=1e-3,\n        dropout_rate=dropout_rate,\n        drop_connect_rate=drop_connect_rate,\n        # data_format='channels_last',  # removed, this is always true in PyTorch\n        num_classes=num_classes,\n        width_coefficient=width_coefficient,\n        depth_coefficient=depth_coefficient,\n        depth_divisor=8,\n        min_depth=None,\n        image_size=image_size,\n    )\n\n    return blocks_args, global_params\n\n\ndef get_model_params(model_name, override_params):\n    \"\"\" Get the block args and global params for a given model \"\"\"\n    if model_name.startswith('efficientnet'):\n        w, d, s, p = efficientnet_params(model_name)\n        # note: all models have drop connect rate = 0.2\n        blocks_args, global_params = efficientnet(\n            width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s)\n    else:\n        raise NotImplementedError('model name is not pre-defined: %s' % model_name)\n    if override_params:\n        # ValueError will be raised here if override_params has fields not included in global_params.\n        global_params = global_params._replace(**override_params)\n    return blocks_args, global_params\n\n\nurl_map = {\n    \n    'efficientnet-b5': '\/kaggle\/input\/efficientnet-pytorch\/efficientnet-b5-586e6cc6.pth',\n}\n\ndef load_pretrained_weights(model, model_name, load_fc=True):\n    \"\"\" Loads pretrained weights, and downloads if loading for the first time. \"\"\"\n    state_dict = model_zoo.load_url(url_map[model_name])\n    if load_fc:\n        model.load_state_dict(state_dict)\n    else:\n        state_dict.pop('_fc.weight')\n        state_dict.pop('_fc.bias')\n        res = model.load_state_dict(state_dict, strict=False)\n        assert str(res.missing_keys) == str(['_fc.weight', '_fc.bias']), 'issue loading pretrained weights'\n    print('Loaded pretrained weights for {}'.format(model_name))\n    \n    \nclass MBConvBlock(nn.Module):\n    \"\"\"\n    Mobile Inverted Residual Bottleneck Block\n\n    Args:\n        block_args (namedtuple): BlockArgs, see above\n        global_params (namedtuple): GlobalParam, see above\n\n    Attributes:\n        has_se (bool): Whether the block contains a Squeeze and Excitation layer.\n    \"\"\"\n\n    def __init__(self, block_args, global_params):\n        super().__init__()\n        self._block_args = block_args\n        self._bn_mom = 1 - global_params.batch_norm_momentum\n        self._bn_eps = global_params.batch_norm_epsilon\n        self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1)\n        self.id_skip = block_args.id_skip  # skip connection and drop connect\n\n        # Get static or dynamic convolution depending on image size\n        Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)\n\n        # Expansion phase\n        inp = self._block_args.input_filters  # number of input channels\n        oup = self._block_args.input_filters * self._block_args.expand_ratio  # number of output channels\n        if self._block_args.expand_ratio != 1:\n            self._expand_conv = Conv2d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False)\n            self._bn0 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n        # Depthwise convolution phase\n        k = self._block_args.kernel_size\n        s = self._block_args.stride\n        self._depthwise_conv = Conv2d(\n            in_channels=oup, out_channels=oup, groups=oup,  # groups makes it depthwise\n            kernel_size=k, stride=s, bias=False)\n        self._bn1 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n        # Squeeze and Excitation layer, if desired\n        if self.has_se:\n            num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio))\n            self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1)\n            self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)\n\n        # Output phase\n        final_oup = self._block_args.output_filters\n        self._project_conv = Conv2d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False)\n        self._bn2 = nn.BatchNorm2d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n    def forward(self, inputs, drop_connect_rate=None):\n        \"\"\"\n        :param inputs: input tensor\n        :param drop_connect_rate: drop connect rate (float, between 0 and 1)\n        :return: output of block\n        \"\"\"\n\n        # Expansion and Depthwise Convolution\n        x = inputs\n        if self._block_args.expand_ratio != 1:\n            x = relu_fn(self._bn0(self._expand_conv(inputs)))\n        x = relu_fn(self._bn1(self._depthwise_conv(x)))\n\n        # Squeeze and Excitation\n        if self.has_se:\n            x_squeezed = F.adaptive_avg_pool2d(x, 1)\n            x_squeezed = self._se_expand(relu_fn(self._se_reduce(x_squeezed)))\n            x = torch.sigmoid(x_squeezed) * x\n\n        x = self._bn2(self._project_conv(x))\n\n        # Skip connection and drop connect\n        input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters\n        if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters:\n            if drop_connect_rate:\n                x = drop_connect(x, p=drop_connect_rate, training=self.training)\n            x = x + inputs  # skip connection\n        return x\n\n\nclass EfficientNet(nn.Module):\n    \"\"\"\n    An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods\n\n    Args:\n        blocks_args (list): A list of BlockArgs to construct blocks\n        global_params (namedtuple): A set of GlobalParams shared between blocks\n\n    Example:\n        model = EfficientNet.from_pretrained('efficientnet-b0')\n\n    \"\"\"\n\n    def __init__(self, blocks_args=None, global_params=None):\n        super().__init__()\n        assert isinstance(blocks_args, list), 'blocks_args should be a list'\n        assert len(blocks_args) > 0, 'block args must be greater than 0'\n        self._global_params = global_params\n        self._blocks_args = blocks_args\n\n        # Get static or dynamic convolution depending on image size\n        Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)\n\n        # Batch norm parameters\n        bn_mom = 1 - self._global_params.batch_norm_momentum\n        bn_eps = self._global_params.batch_norm_epsilon\n\n        # Stem\n        in_channels = 3  # rgb\n        out_channels = round_filters(32, self._global_params)  # number of output channels\n        self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)\n        self._bn0 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n        # Build blocks\n        self._blocks = nn.ModuleList([])\n        for block_args in self._blocks_args:\n\n            # Update block input and output filters based on depth multiplier.\n            block_args = block_args._replace(\n                input_filters=round_filters(block_args.input_filters, self._global_params),\n                output_filters=round_filters(block_args.output_filters, self._global_params),\n                num_repeat=round_repeats(block_args.num_repeat, self._global_params)\n            )\n\n            # The first block needs to take care of stride and filter size increase.\n            self._blocks.append(MBConvBlock(block_args, self._global_params))\n            if block_args.num_repeat > 1:\n                block_args = block_args._replace(input_filters=block_args.output_filters, stride=1)\n            for _ in range(block_args.num_repeat - 1):\n                self._blocks.append(MBConvBlock(block_args, self._global_params))\n\n        # Head\n        in_channels = block_args.output_filters  # output of final block\n        out_channels = round_filters(1280, self._global_params)\n        self._conv_head = Conv2d(in_channels, out_channels, kernel_size=1, bias=False)\n        self._bn1 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n        # Final linear layer\n        self._dropout = self._global_params.dropout_rate\n        self._fc = nn.Linear(out_channels, self._global_params.num_classes)\n\n    def extract_features(self, inputs):\n        \"\"\" Returns output of the final convolution layer \"\"\"\n\n        # Stem\n        x = relu_fn(self._bn0(self._conv_stem(inputs)))\n\n        # Blocks\n        for idx, block in enumerate(self._blocks):\n            drop_connect_rate = self._global_params.drop_connect_rate\n            if drop_connect_rate:\n                drop_connect_rate *= float(idx) \/ len(self._blocks)\n            x = block(x, drop_connect_rate=drop_connect_rate)\n\n        # Head\n        x = relu_fn(self._bn1(self._conv_head(x)))\n\n        return x\n\n    def forward(self, inputs):\n        \"\"\" Calls extract_features to extract features, applies final linear layer, and returns logits. \"\"\"\n\n        # Convolution layers\n        x = self.extract_features(inputs)\n\n        # Pooling and final linear layer\n        x = F.adaptive_avg_pool2d(x, 1).squeeze(-1).squeeze(-1)\n        if self._dropout:\n            x = F.dropout(x, p=self._dropout, training=self.training)\n        x = self._fc(x)\n        return x\n\n    @classmethod\n    def from_name(cls, model_name, override_params=None):\n        cls._check_model_name_is_valid(model_name)\n        blocks_args, global_params = get_model_params(model_name, override_params)\n        return EfficientNet(blocks_args, global_params)\n\n    @classmethod\n    def from_pretrained(cls, model_name, num_classes=1000):\n        model = EfficientNet.from_name(model_name, override_params={'num_classes': num_classes})\n        return model\n\n    @classmethod\n    def get_image_size(cls, model_name):\n        cls._check_model_name_is_valid(model_name)\n        _, _, res, _ = efficientnet_params(model_name)\n        return res\n\n    @classmethod\n    def _check_model_name_is_valid(cls, model_name, also_need_pretrained_weights=False):\n        \"\"\" Validates model name. None that pretrained weights are only available for\n        the first four models (efficientnet-b{i} for i in 0,1,2,3) at the moment. \"\"\"\n        num_models = 4 if also_need_pretrained_weights else 8\n        valid_models = ['efficientnet_b'+str(i) for i in range(num_models)]\n        if model_name.replace('-','_') not in valid_models:\n            raise ValueError('model_name should be one of: ' + ', '.join(valid_models))\n\"\"\"\n# Model training\n\"\"\"\nmd_ef = EfficientNet.from_pretrained('efficientnet-b5', num_classes=1)\n# def qk(y_pred, y):\n#     return torch.tensor(cohen_kappa_score(torch.round(y_pred), y, weights='quadratic'), device='cuda:0')\nfrom sklearn.metrics import cohen_kappa_score\ndef quadratic_kappa(y_hat, y):\n    return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0')\nlearn = Learner(data, \n                md_ef, \n                metrics = [quadratic_kappa] \n                ,callback_fns=[BnFreeze,partial(SaveModelCallback, monitor='quadratic_kappa', name='best_accuracy')]).to_fp16()\n\nlearn.data.add_test(ImageList.from_df(test_df,\n                                      '..\/input\/aptos2019-blindness-detection',\n                                      folder='test_images',\n                                      suffix='.png'))\n\n\nlearn.model_dir=\"\/kaggle\/working\/models\"\nlearn.load('modelk');\n# learn.validate()\nlearn.freeze_to(-1)\n# learn.lr_find()\n# learn.recorder.plot(suggestion=True)\nlearn.fit_one_cycle(5,3e-04)\nlearn.load('best_accuracy')\nlearn.save('stage1')\nlearn.unfreeze()\n# learn.lr_find()\n# learn.recorder.plot(suggestion=True)\nlearn.fit_one_cycle(10, 7.59E-07)\n# learn.save('stage2')\n\"\"\"\n# pred\n\"\"\"\nimport scipy as sp\nfrom sklearn import metrics\n\nclass OptimizedRounder(object):\n    def __init__(self):\n        self.coef_ = 0\n\n    def _kappa_loss(self, coef, X, y):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n\n        ll = metrics.cohen_kappa_score(y, X_p, weights='quadratic')\n        return -ll\n\n    def fit(self, X, y):\n        loss_partial = partial(self._kappa_loss, X=X, y=y)\n        initial_coef = [0.5, 1.5, 2.5, 3.5]\n        self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\n        print(-loss_partial(self.coef_['x']))\n\n    def predict(self, X, coef):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n        return X_p\n\n    def coefficients(self):\n        return self.coef_['x']\nlearn.load('best_accuracy');\nvalid_preds = learn.get_preds(ds_type=DatasetType.Valid)\noptR = OptimizedRounder()\noptR.fit(valid_preds[0],valid_preds[1])\ncoefficients = optR.coefficients()\ncoefficients=np.around((coefficients), decimals=2)\nprint(coefficients)\n# data.show_batch(DatasetType.Test)\npreds,y = learn.get_preds(DatasetType.Test)\ntst_pred = optR.predict(preds, coefficients)\ntest_df.diagnosis = tst_pred.astype(int)\ntest_df.to_csv('submission.csv',index=False)\ntest_df['diagnosis'].value_counts()\ndata.show_batch()\nfrom fastai.vision import *\ndata.show_batch(ds_type=DatasetType.Test)\nvision.data.open_image=temp","meta":"{'source': 'AI4Code', 'id': '4889655b516a52'}"}
{"id":"16456","text":"\"\"\"\n*Climate change includes both the global warming driven by human emissions of greenhouse gases, and the resulting large-scale shifts in weather patterns. Though there have been previous periods of climatic change, since the mid-20th century the rate of human impact on Earth's climate system and the global scale of that impact have been unprecedented.* [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/Climate_change)\n\n\nThe goal of this research is to analyze the rise of temperature over time in different parts of the world, using the dataset on the temperature of major cities of the world. The dataset was provided by University of Dayton ([licence](https:\/\/academic.udayton.edu\/kissock\/http\/Weather\/default.htm)).\n\n- How much is the temperature increase in different parts of the world over time?\n- Which countries are seeing a rapid increase in temperature over time?\n- What seasonality patterns do we have in different parts of the world? And how did those patterns change over time?\n\nThe notebook illustrates answers to these questions, using Bokeh graphs and interactive dashboards.\nActually, this notebook is a concise Bokeh interpretation of its [elder Plotly brother](https:\/\/www.kaggle.com\/dunklerwald\/what-s-going-on-in-ecuador-splash-of-plotly) that I published a while back. The Plotly version is a more elaborate work whereas here I just experiment with some special Bokeh features, such as tabs and shared data sources. So if you really want to know what's going on in Ecuador, you might want to check the Plotly version.\n\nWhat I disliked about Bokeh is its poor documentation. Limited search, missing crosslinks, unclear and confusing structure.<br>\nWhat I really liked about Bokeh:\n- **tabs**(!) and therefore more compact output\n- advanced pan tool when you can connect and pan several plots by left-dragging a mouse simultaneously (I guess Plotly also can provide such features but I didn't check it)\n- simple and fast ways to create different grids\n- easier ways to manage interactions based on user input (e.g. update all graphs in a grid according to the selected value in Select widget).\n\n\nPerformance and internals of both frameworks is still an unexplored territory for me. Especially when it comes to building powerful web apps. If you have some working experience or research articles, analyzing both Plotly and Bokeh, please, don't hesitate to share info here in comments. All in all, based on what I tested so far, Plotly is my tool of choice when it comes to EDA. No brainer.\n\nPart 1: [What's going on in Ecuador? - splash of Plotly](https:\/\/www.kaggle.com\/dunklerwald\/what-s-going-on-in-ecuador-splash-of-plotly)<br>\nPart 2: [What's going on in Ecuador? - breeze of Bokeh](https:\/\/www.kaggle.com\/dunklerwald\/what-s-going-on-in-ecuador-breeze-of-bokeh)\n\"\"\"\n\"\"\"\n# Table of contents\n1. [Loading necessary libraries](#1)\n1. [Loading city temperatures dataset](#2)\n1. [Basic stats](#3)\n1. [Data cleaning and feature engineering](#4)\n1. [Regional temperature dynamics: dashboard](#5)     \n1. [Country temperature dynamics: dashboard](#6)     \n1. [Summary](#7)    \n\"\"\"\n\"\"\"\n## Loading necessary libraries <a id=\"1\"><\/a>\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom math import pi\nimport gc\n\nfrom IPython.core.display import HTML\n\nfrom bokeh.plotting import figure, output_notebook, show\nfrom bokeh.models import ColumnDataSource, CDSView, GroupFilter, BooleanFilter, CustomJS, Slider, Select, Panel, Tabs, HoverTool, Legend, FactorRange\nfrom bokeh.layouts import row, column, grid, gridplot, layout\nfrom bokeh.io import curdoc\nfrom bokeh.themes import Theme\nfrom bokeh.palettes import Category10, Bokeh\nfrom bokeh.transform import factor_cmap\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\npd.set_option('display.max_columns', 300)\npd.set_option(\"display.max_rows\", 20)\noutput_notebook()\n# Let's define some common style settings for bokeh graphs\ntools = ['pan', 'box_select', 'lasso_select', 'box_zoom',  'reset']\n\ncurdoc().theme = Theme(json={'attrs': {\n\n    # Figure properties\n    'Figure': {\n        'min_border_left': 20,\n        'min_border_right': 20,\n        'background_fill_color': '#E6F1FC'\n    },\n    # Axis properties\n    'Axis': {\n        'minor_tick_out': None,\n        'minor_tick_in': None,\n        'major_tick_out': None,\n        'major_tick_in': None,\n        'axis_line_color':None\n    },\n    # Grid properties\n    'Grid': {\n        'grid_line_color': '#FFFFFF'       \n    },\n    # Title properties\n    'Title': {\n        'text_font_size' : '16px',\n        'text_font_style' : 'normal',\n        'align' : 'center'\n    },\n    # Legend properties\n    'Legend': {\n        'background_fill_alpha': 0.8,\n        'location': 'top_left',\n        'label_text_font_size' : '10px'\n    }\n}})\n\"\"\"\n## Loading city temperatures datasets <a id=\"2\"><\/a>\n\"\"\"\n\"\"\"\nLet's load the dataset on the temperature of major cities of the world, provided by University of Dayton.\n\"\"\"\ndf = pd.read_csv('..\/input\/daily-temperature-of-major-cities\/city_temperature.csv')\nprint(df.shape)\ndf.head()\n\"\"\"\n## Basic stats  <a id=\"3\"><\/a>\n\"\"\"\n\"\"\"\nNow we can get basic stats about columns and data demographics, such as uniqueness, missing values and zero values.\n\"\"\"\n#\u0421ommon functions for exploratory data analysis\ndef get_stats(df):\n    \"\"\"\n    Function returns a dataframe with the following stats for each column of df dataframe:\n    - Unique_values\n    - Percentage of missing values\n    - Percentage of zero values\n    - Percentage of values in the biggest category\n    - data type\n    \"\"\"\n    stats = []\n    for col in df.columns:\n        if df[col].dtype not in ['object', 'str', 'datetime64[ns]']:\n            zero_cnt = df[df[col] == 0][col].count() * 100 \/ df.shape[0]\n        else:\n            zero_cnt = 0\n\n        stats.append((col, df[col].nunique(),\n                      df[col].isnull().sum() * 100 \/ df.shape[0],\n                      zero_cnt,\n                      df[col].value_counts(normalize=True, dropna=False).values[0] * 100,\n                      df[col].dtype))\n\n    df_stats = pd.DataFrame(stats, columns=['Feature', 'Unique_values',\n                                            'Percentage of missing values',\n                                            'Percentage of zero values',\n                                            'Percentage of values in the biggest category',\n                                            'type'])\n\n    del stats\n    gc.collect()\n\n    return df_stats\nget_stats(df)\n\"\"\"\n## Data cleaning and feature engineering  <a id=\"4\"><\/a>\n\"\"\"\n\"\"\"\nIn this section we will clean our dataset and generate some new features.\n\"\"\"\n# First of all, we drop State column which is irrelevant for our analysis.\ndel df['State']\n\n# We also change data types of several columns to optimize memory storage.\ndf['Month'] = df['Month'].astype('int8')\ndf['Day'] = df['Day'].astype('int8')\ndf['Year'] = df['Year'].astype('int16')\ndf['AvgTemperature'] = df['AvgTemperature'].astype('float16')\n\n# There are several rows with Day=0. We are going to drop such rows.\nprint(f\"There are {df[df['Day']==0].Day.count()} rows with Day=0\")\ndf[df['Day']==0].head()\n\n# Looking at data distribution across years, there are several obvious outliers: years 200,201 and 2020.\n# Years 200 and 201 must be typos whereas year 2020 does not keep data for the whole year.\n# We will drop all rows, belonging to these years. Also we will drop more than 20 thousand duplicate rows.\ndf = df[df['Day']!=0]\ndf = df[~df['Year'].isin([200,201,2020])]\ndf = df.drop_duplicates()\n\n# 2.7% rows in the dataset have AvgTemperature value of -99. Let's look at distibution of AvgTemperature=-99 across regions.\n# Most likely, value of -99 was used used to fill missing temperature values. We are going to drop all such rows.\n# Also, for the sake of simplicity, we will drop all \"incomplete years\" - in case number of observations per country & year is less than 270 days, we eliminate this year as an incomplete yearly snapshot.\ndf = df[df['AvgTemperature']!=-99]\ndf['days_in_year']=df.groupby(['Country','Year'])['Day'].transform('size')\ndf=df[df['days_in_year']>270]\n\n# Here we create column Date and convert AvgTemperature to Celsius scale.\ndf['Date'] = pd.to_datetime(df[['Year','Month', 'Day']])\ndf['AvgTemperature'] = (df['AvgTemperature'] -32)*(5\/9)\n\n# Also we need to fix some discrepancies in country names\ncode_dict = {'Czech Republic':'Czechia','Equador':'Ecuador', 'Ivory Coast':\"C\u00f4te d'Ivoire\",'Myanmar (Burma)':'Myanmar','Serbia-Montenegro':'Serbia', 'The Netherlands':'Netherlands'}\ndf['Country'].replace(code_dict, inplace=True)\n\"\"\"\nNow we are ready to go with our final data set.\n\"\"\"\nprint(f\"Final data set shape: {df.shape}\")\n\"\"\"\n## Regional temperature dynamics: dashboard  <a id=\"5\"><\/a>\n\"\"\"\n\"\"\"\nLet's look at how temperature has been changing in different regions through all the years.<br><br>\n*Tab General*<br>\nThe left chart demostrates temperature rise for each region over the entire period. I calculate the rise as the exponentially smoothed temperatures difference of the first and the last year of observations for each region. The chart on the right shows regional dynamics over the years.\nYou can see it with the naked eye - temperature has been growing across all regions. What's more, in some regions temperature has been growing faster.<br><br>\n*Regional tabs* (Africa, Asia etc.)<br>\nThe chart on the left shows a monthly temperature profile for this region. The tabbed charts on the right illustrate how seasonal temperature has been changing in this region.\n\"\"\"\n# several mappings for seasonality charts\nmonth_dict = {1:\"January\", 2:\"February\", 3:\"March\", 4:\"April\", 5:\"May\", 6:\"June\" ,7:\"July\", 8:\"August\", 9:\"September\", 10:\"October\", 11:\"November\", 12:\"December\"}\nseason_dict = {1:\"Winter\", 2:\"Spring\", 3:\"Summer\", 4:\"Autumn\"}\nseason_month_map = {1:1, 2:1, 3:2, 4:2, 5:2, 6:3, 7:3, 8:3, 9:4, 10:4, 11:4, 12:1}\nseasons = [\"Winter\", \"Spring\", \"Summer\", \"Autumn\"]\n\n\n# temperature stats, grouped by region and year \ndfr = (\n       df.groupby(['Year','Region'])['AvgTemperature'].agg(['mean','min','idxmin','max','idxmax']).reset_index()\n      .merge(df[['Country','City','Date']], left_on='idxmin',right_index=True)\n      .merge(df[['Country','City','Date']], left_on='idxmax',right_index=True,suffixes=('_min','_max'))\n      )\n\n# average temperature, smoothed with exponential weighted average.\ndfr['mean_smoothed'] = dfr.groupby(['Region'])['mean'].transform(lambda x: x.ewm(span=3).mean()).fillna(dfr['mean'])\n\nregions = dfr['Region'].sort_values().unique().tolist()\nregions_reverse = dfr['Region'].sort_values(ascending=False).unique().tolist()\n\n# Temperature rise per region through the entire period, using exponentially smoothed average temperature\ndfrs = dfr.groupby('Region')['mean_smoothed'].agg(['first','last']).reset_index()\ndfrs['Temp_delta'] = dfrs['last'] - dfrs['first']\ndfrs.columns=['Region','Start year temp','End year temp', 'Delta_temp']\n\n\n# temperature stats, grouped by year, month, region and country \ndfmc = (\n       df.groupby(['Year','Month','Region','Country'])['AvgTemperature'].agg(['mean'])\n      .reset_index()\n      .rename(columns={'mean': 'AvgTemperature','Month': 'Month_num'})\n      .sort_values(by=['Year','Month_num','Region','Country'])\n      )\n\ndfmc['Season_num'] = dfmc['Month_num'].map(season_month_map)\ndfmc['Season'] = dfmc['Season_num'].map(season_dict)\ndfmc['Month'] = dfmc['Month_num'].map(month_dict)\n\n# temperature stats, grouped by year, season, month and region \ndfmr = (\n       dfmc.groupby(['Year','Season_num','Season','Month_num','Month','Region'])['AvgTemperature'].agg(['mean'])\n      .reset_index()\n      .rename(columns={'mean': 'AvgTemperature'})\n      .sort_values(by=['Year','Month_num','Region'])\n      )\n\n# temperature stats, grouped by month and region \ndfmr_g = (\n       dfmr.groupby(['Region','Month_num','Month'])['AvgTemperature'].agg(['mean'])\n      .reset_index()\n      .rename(columns={'mean': 'AvgTemperature'})\n      .sort_values(by=['Region','Month_num'])\n      )\n\nmonths = dfmr_g[['Month','Month_num']].sort_values(by='Month_num')['Month'].unique().tolist()\n\n# temperature stats, grouped by year, season and region \ndfsr = (\n       dfmc.groupby(['Year','Season_num','Season','Region'])['AvgTemperature'].agg(['mean'])\n      .reset_index()\n      .rename(columns={'mean': 'AvgTemperature'})\n      .sort_values(by=['Year','Season_num','Region'])\n      )\nplot_height = 420\nplot_width = 400\n\n#General tab\npalette = Bokeh[len(dfr['Region'].unique())]\n\nsource_dfrs = ColumnDataSource(data=dfrs)\n\n# Temperature rise per region\np_rise = figure(\n                 plot_width=plot_width\n                ,plot_height=plot_height\n                ,tools=tools\n                ,y_range=FactorRange(factors=regions_reverse)\n                ,title='Temperature rise per region, \u00b0C'\n                ,tooltips = [('Region','@Region'), ('Temperature rise', '@Delta_temp')])\np_rise.hbar(\n             y='Region'\n            ,height=0.5\n            ,left=0\n            ,right='Delta_temp'\n            ,line_color=None\n            ,fill_color=factor_cmap('Region', palette=Bokeh[len(regions)], factors=regions)\n            ,source=source_dfrs)\n\n# Temperature trend per region\np_trend = figure(\n                  plot_width=plot_width\n                 ,plot_height=plot_height\n                 ,tools=tools\n                 ,title='Temperature trend per region, \u00b0C')\np_trend.add_layout(Legend(), 'right')\n\nfor region, color in zip(regions,palette):\n    source_dfr_line = ColumnDataSource(data=dfr[dfr['Region']==region])\n    p_trend.line(\n                  x='Year'\n                 ,y='mean_smoothed'\n                 ,line_width=2\n                 ,line_color=color\n                 ,source=source_dfr_line)\n    \np_trend.legend.click_policy='hide'\nhover = HoverTool(tooltips = [('Region','@Region'), ('Year','@Year'), ('AvgTemperature', '@mean_smoothed')])\np_trend.add_tools(hover)\n\ntab_general = Panel(child=row(p_rise, p_trend), title='General')\n# Regional and seasonal tabs\nsource_dfmr = ColumnDataSource(data=dfmr_g)\nsource_dfsr = ColumnDataSource(data=dfsr)\n\ntabs = []\n\n# create a tab for each region\nfor region in regions:\n    \n    # Average temperature per month\n    region_view = CDSView(source=source_dfmr, filters=[GroupFilter(column_name='Region', group=region)])\n    p_region_month = figure(\n                             plot_width=plot_width\n                            ,plot_height=plot_height\n                            ,tools=tools\n                            ,x_range=FactorRange(factors=months)\n                            ,title='Average temperature per month, \u00b0C'\n                            ,tooltips = [('Region','@Region'), ('Month','@Month'), ('AvgTemperature', '@AvgTemperature')])\n    p_region_month.vbar(\n                         x='Month'\n                        ,bottom=0\n                        ,top='AvgTemperature'\n                        ,width = 0.8\n                        ,line_color=None\n                        ,fill_color=factor_cmap('Region', palette=Bokeh[len(regions)], factors=regions)\n                        ,source=source_dfmr\n                        ,view=region_view)\n    p_region_month.xaxis.major_label_orientation = -pi\/4\n    \n    # in each regional tab create 4 seasonal tabs (winter, spring, summer, autumn)\n    season_tabs = []\n    for season in seasons:\n            season_view = CDSView(source=source_dfsr, filters=[GroupFilter(column_name='Region', group=region), GroupFilter(column_name='Season', group=season)])\n            p_season = figure(\n                             plot_width=plot_width\n                            ,plot_height=plot_height-70\n                            ,y_range=p_region_month.y_range\n                            ,tools=tools\n                            ,title='Seasonal temperature dynamics, \u00b0C'\n                            ,tooltips = [('Region','@Region'), ('Season','@Season'), ('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\n            p_season.vbar(\n                                 x='Year'\n                                ,bottom=0\n                                ,top='AvgTemperature'\n                                ,width = 1.0\n                                ,line_color='#FFFFFF'\n                                ,fill_color=factor_cmap('Season', palette=['#40E0D0','#00FF7F','#FF6347','#FFA500'], factors=seasons)\n                                ,fill_alpha=0.6\n                                ,source=source_dfsr\n                                ,view=season_view)\n            season_tabs.append(Panel(child=p_season, title=season))\n\n    tabs.append(Panel(child=row(p_region_month, Tabs(tabs=season_tabs)), title=region))\n# Final dashboard that combines General and all regional tabs\ng = gridplot([[Tabs(tabs=[tab_general]+tabs)]])\nshow(g)\n\"\"\"\n## Country temperature dynamics: dashboard  <a id=\"6\"><\/a>\n\"\"\"\n\"\"\"\nJust select a country from the list to get 3 different visualisations the dashboard provides:\n\n- first charts shows average country temperature trend through all the years;\n- second chart illustrates how seasonal temperature has been changing over years;\n- third chart compares 2 distributions for this country: temperature distribution in 1995-2014 vs temperature distribution in 2015-2019.\n\nYou can check yourself that in many countries temperature distribution has shifted to the right (e.g. Australia) whereas some countries shifted back to the left (e.g. Canada).\n\"\"\"\n# add new \"period\" dimension: 1995-2014 (first 15 years) and 2015-2019 (last 5 years) \ndfmc['Period'] = '1995-2014'\ndfmc['Period'].loc[dfmc['Year']>2014] = '2015-2019'\n\ndfyc = dfmc.groupby(['Country','Year'])['AvgTemperature'].mean().reset_index()\ndfycs = dfmc.groupby(['Country','Year','Season_num','Season'])['AvgTemperature'].mean().reset_index()\ndef f(x, period):\n    array_hist, edges = np.histogram(x,density=True, bins=25)\n    return pd.DataFrame({'period':period, 'array_hist':array_hist,'left':edges[:-1], 'right':edges[1:]})\n\ndfyc_bk = dfyc.groupby('Country', sort = False)['Year', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\n\ndfyc_winter_bk = dfycs[dfycs['Season']=='Winter'].groupby('Country', sort = False)['Year', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\ndfyc_spring_bk = dfycs[dfycs['Season']=='Spring'].groupby('Country', sort = False)['Year', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\ndfyc_summer_bk = dfycs[dfycs['Season']=='Summer'].groupby('Country', sort = False)['Year', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\ndfyc_autumn_bk = dfycs[dfycs['Season']=='Autumn'].groupby('Country', sort = False)['Year', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\n\ndfmc_bk = dfmc.groupby('Country', sort = False)['Period', 'AvgTemperature'].apply(lambda x: x.to_dict(orient = 'list'))\n\ndfmc_period1_bk = dfmc[dfmc['Period']=='1995-2014'].groupby('Country', sort = False)['AvgTemperature'].apply(lambda x: f(x,'1995-2014')).groupby(level=0).apply(lambda x: x.to_dict(orient = 'list'))\ndfmc_period2_bk = dfmc[dfmc['Period']=='2015-2019'].groupby('Country', sort = False)['AvgTemperature'].apply(lambda x: f(x,'2015-2019')).groupby(level=0).apply(lambda x: x.to_dict(orient = 'list'))\n\ncountries = dfmc['Country'].sort_values().unique().tolist()  \nsource_gen = ColumnDataSource(data=dfyc_bk[countries[0]])\nsource_winter = ColumnDataSource(data=dfyc_winter_bk[countries[0]])\nsource_spring = ColumnDataSource(data=dfyc_spring_bk[countries[0]])\nsource_summer = ColumnDataSource(data=dfyc_summer_bk[countries[0]])\nsource_autumn = ColumnDataSource(data=dfyc_autumn_bk[countries[0]])\nsource_period1 = ColumnDataSource(data=dfmc_period1_bk[countries[0]])\nsource_period2 = ColumnDataSource(data=dfmc_period2_bk[countries[0]])\n\nselect = Select(value=countries[0], options=countries, width=200)\ncallback = CustomJS(\n             args=dict(source_gen=source_gen, s_gen=dfyc_bk.to_dict(),\n                              source_winter=source_winter, s_winter=dfyc_winter_bk.to_dict(),\n                              source_spring=source_spring, s_spring=dfyc_spring_bk.to_dict(),\n                              source_summer=source_summer, s_summer=dfyc_summer_bk.to_dict(),\n                              source_autumn=source_autumn, s_autumn=dfyc_autumn_bk.to_dict(),\n                              source_period1=source_period1, s_period1=dfmc_period1_bk.to_dict(),\n                              source_period2=source_period2, s_period2=dfmc_period2_bk.to_dict()),\n            code=\"\"\"\n                 source_gen.data = s_gen[cb_obj.value];\n                 source_winter.data = s_winter[cb_obj.value];\n                 source_spring.data = s_spring[cb_obj.value];\n                 source_summer.data = s_summer[cb_obj.value];\n                 source_autumn.data = s_autumn[cb_obj.value];\n                 source_period1.data = s_period1[cb_obj.value];\n                 source_period2.data = s_period2[cb_obj.value];\n                 source_gen.change.emit();\n                 source_winter.change.emit();\n                 source_spring.change.emit();\n                 source_summer.change.emit();\n                 source_autumn.change.emit();\n                 source_period1.change.emit();\n                 source_period2.change.emit();\n\"\"\")\n\nselect.js_on_change('value', callback)\n\nplot_width = 800\n\n# Average temperature dynamics on country level\np_gen = figure(plot_width=plot_width, plot_height=150, tools=tools, title='Average temperature dynamics on country level (1995-2019)')\np_gen.line(x='Year', y='AvgTemperature', line_width=4, source=source_gen, line_dash='dashdot', line_color='#00CC96')\nhover = HoverTool(tooltips = [('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\np_gen.add_tools(hover)\n\n# Seasonal tabs\np_winter = figure(tools=tools, plot_width=plot_width, plot_height=150, x_range=p_gen.x_range)\np_winter.line(x='Year', y='AvgTemperature', line_width=2, source=source_winter, line_color='blue')\nhover = HoverTool(tooltips = [('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\np_winter.add_tools(hover)\ntab_winter = Panel(child=p_winter, title='Winter')\n\np_spring = figure(tools=tools, plot_width=plot_width, plot_height=150, x_range=p_gen.x_range)\np_spring.line(x='Year', y='AvgTemperature', line_width=2, source=source_spring, line_color='green')\nhover = HoverTool(tooltips = [('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\np_spring.add_tools(hover)\ntab_spring = Panel(child=p_spring, title='Spring')\n\np_summer = figure(tools=tools, plot_width=plot_width, plot_height=150, x_range=p_gen.x_range)\np_summer.line(x='Year', y='AvgTemperature', line_width=2, source=source_summer, line_color='red')\nhover = HoverTool(tooltips = [('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\np_summer.add_tools(hover)\ntab_summer = Panel(child=p_summer, title='Summer')\n\np_autumn = figure(tools=tools, plot_width=plot_width, plot_height=150, x_range=p_gen.x_range)\np_autumn.line(x='Year', y='AvgTemperature', line_width=2, source=source_autumn, line_color='orange')\nhover = HoverTool(tooltips = [('Year','@Year'), ('AvgTemperature', '@AvgTemperature')])\np_autumn.add_tools(hover)\ntab_autumn = Panel(child=p_autumn, title='Autumn')\n\n# Temperature distribution dynamics\np_dist = figure(plot_width=plot_width, plot_height=200, tools=tools, title='Temperature distribution dynamics: (1995-2014) vs (2015-2019)')\np_dist.quad(bottom=0, top='array_hist', left='left', right='right', source=source_period1,\n            fill_color='blue', fill_alpha = 0.4, line_alpha=0, hover_fill_alpha = 1.0, hover_fill_color = 'blue', legend_label='1995-2014')\np_dist.quad(bottom=0, top='array_hist', left='left', right='right', source=source_period2,\n            fill_color='red', fill_alpha = 0.4, line_alpha=0, hover_fill_alpha = 1.0, hover_fill_color = 'red', legend_label='2015-2019')\nhover = HoverTool(tooltips = [('Period','@period'), ('AvgTemperature', '@left-@right'), ('count', '@array_hist{0.000}')])\np_dist.add_tools(hover)\n\ng = gridplot([[select],[p_gen],[Tabs(tabs=[tab_winter, tab_spring, tab_summer, tab_autumn])],[p_dist]])\nshow(g)\n\"\"\"\n# Summary  <a id=\"7\"><\/a>\n\"\"\"\n\"\"\"\nBased on all information above, now we know for certain that global world temperature has been growing. We also observe that average temperature has been changing differently in different regions. Having said that, missing values (AvgTemperature=-99), data gaps of various nature and smoothing effect of aggregation (Ecuador case is a good example) could affect analysis in the misleading way. So we should be careful of making wrong judgements and be attentive to data we have under the hood.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1dfea05e6182c3'}"}
{"id":"46061","text":"\"\"\"\n\n<h1><center>APTOS 2019 Blindness Detection<\/center><\/h1>\n<h2><center>Diabetic retinopathy - SHAP model explainability<\/center><\/h2>\n![](https:\/\/raw.githubusercontent.com\/dimitreOliveira\/MachineLearning\/master\/Kaggle\/APTOS%202019%20Blindness%20Detection\/aux_img.png)\n\nIn this work, I'll train a baseline ResNet50, evaluate the model, and use SHAP model explainability technique to help us better understand our model's predictions, and how we could further improve its performance.\n\n#### About [SHAP](https:\/\/github.com\/slundberg\/shap) from its source:\n\n<img src=\"https:\/\/raw.githubusercontent.com\/slundberg\/shap\/master\/docs\/artwork\/shap_diagram.png\" width=\"400\">\n\n##### SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of any machine learning model. SHAP connects game theory with local explanations, uniting several previous methods [1-7] and representing the only possible consistent and locally accurate additive feature attribution method based on expectations (see our [papers](https:\/\/github.com\/slundberg\/shap#citations) for details).\n\"\"\"\n\"\"\"\n## Dependencies\n\"\"\"\nimport os\nimport shap\nimport random\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import class_weight\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, cohen_kappa_score\nfrom keras.models import Model\nfrom keras import optimizers, applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input\n\n# Set seeds to make the experiment more reproducible.\nfrom tensorflow import set_random_seed\ndef seed_everything(seed=0):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    set_random_seed(seed)\n\nseed = 0\nseed_everything(seed)\n\n%matplotlib inline\nsns.set(style=\"whitegrid\")\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n## Load data\n\"\"\"\ntrain = pd.read_csv('..\/input\/aptos2019-blindness-detection\/train.csv')\ntest = pd.read_csv('..\/input\/aptos2019-blindness-detection\/test.csv')\nprint('Number of train samples: ', train.shape[0])\nprint('Number of test samples: ', test.shape[0])\n\n# Preprocecss data\ntrain[\"id_code\"] = train[\"id_code\"].apply(lambda x: x + \".png\")\ntest[\"id_code\"] = test[\"id_code\"].apply(lambda x: x + \".png\")\ntrain['diagnosis'] = train['diagnosis'].astype('str')\ndisplay(train.head())\n\"\"\"\n# Model parameters\n\"\"\"\n# Model parameters\nBATCH_SIZE = 8\nEPOCHS = 40\nWARMUP_EPOCHS = 2\nLEARNING_RATE = 1e-4\nWARMUP_LEARNING_RATE = 1e-3\nHEIGHT = 320\nWIDTH = 320\nCANAL = 3\nN_CLASSES = train['diagnosis'].nunique()\nES_PATIENCE = 5\nRLROP_PATIENCE = 3\nDECAY_DROP = 0.5\n\"\"\"\n## Train test split\n\"\"\"\nX_train, X_val = train_test_split(train, test_size=0.2, random_state=seed)\n\"\"\"\n# Data generator\n\"\"\"\ntrain_datagen=ImageDataGenerator(rescale=1.\/255, \n                                 rotation_range=360,\n                                 horizontal_flip=True,\n                                 vertical_flip=True)\n\ntrain_generator=train_datagen.flow_from_dataframe(\n    dataframe=X_train,\n    directory=\"..\/input\/aptos2019-blindness-detection\/train_images\/\",\n    x_col=\"id_code\",\n    y_col=\"diagnosis\",\n    class_mode=\"categorical\",\n    batch_size=BATCH_SIZE,\n    target_size=(HEIGHT, WIDTH),\n    seed=0)\n\nvalidation_datagen = ImageDataGenerator(rescale=1.\/255)\n\nvalid_generator=validation_datagen.flow_from_dataframe(\n    dataframe=X_val,\n    directory=\"..\/input\/aptos2019-blindness-detection\/train_images\/\",\n    x_col=\"id_code\",\n    y_col=\"diagnosis\",\n    class_mode=\"categorical\", \n    batch_size=BATCH_SIZE,   \n    target_size=(HEIGHT, WIDTH),\n    seed=0)\n\ntest_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntest_generator = test_datagen.flow_from_dataframe(  \n        dataframe=test,\n        directory = \"..\/input\/aptos2019-blindness-detection\/test_images\/\",\n        x_col=\"id_code\",\n        batch_size=1,\n        class_mode=None,\n        shuffle=False,\n        target_size=(HEIGHT, WIDTH),\n        seed=0)\n\"\"\"\n# Model\n\"\"\"\ndef create_model(input_shape, n_out):\n    input_tensor = Input(shape=input_shape)\n    base_model = applications.ResNet50(weights=None, \n                                       include_top=False,\n                                       input_tensor=input_tensor)\n    base_model.load_weights('..\/input\/resnet50\/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dropout(0.5)(x)\n    x = Dense(2048, activation='relu')(x)\n    x = Dropout(0.5)(x)\n    final_output = Dense(n_out, activation='softmax', name='final_output')(x)\n    model = Model(input_tensor, final_output)\n    \n    return model\n\"\"\"\n# Train top layers\n\"\"\"\nmodel = create_model(input_shape=(HEIGHT, WIDTH, CANAL), n_out=N_CLASSES)\n\nfor layer in model.layers:\n    layer.trainable = False\n\nfor i in range(-5, 0):\n    model.layers[i].trainable = True\n    \nclass_weights = class_weight.compute_class_weight('balanced', np.unique(train['diagnosis'].astype('int').values), train['diagnosis'].astype('int').values)\n\nmetric_list = [\"accuracy\"]\noptimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy',  metrics=metric_list)\nmodel.summary()\nSTEP_SIZE_TRAIN = train_generator.n\/\/train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n\/\/valid_generator.batch_size\n\nhistory_warmup = model.fit_generator(generator=train_generator,\n                                     steps_per_epoch=STEP_SIZE_TRAIN,\n                                     validation_data=valid_generator,\n                                     validation_steps=STEP_SIZE_VALID,\n                                     epochs=WARMUP_EPOCHS,\n                                     class_weight=class_weights,\n                                     verbose=1).history\n\"\"\"\n# Fine-tune the complete model\n\"\"\"\nfor layer in model.layers:\n    layer.trainable = True\n\nes = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)\nrlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience=RLROP_PATIENCE, factor=DECAY_DROP, min_lr=1e-6, verbose=1)\n\ncallback_list = [es, rlrop]\noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy',  metrics=metric_list)\nmodel.summary()\nhistory_finetunning = model.fit_generator(generator=train_generator,\n                                          steps_per_epoch=STEP_SIZE_TRAIN,\n                                          validation_data=valid_generator,\n                                          validation_steps=STEP_SIZE_VALID,\n                                          epochs=EPOCHS,\n                                          callbacks=callback_list,\n                                          class_weight=class_weights,\n                                          verbose=1).history\n\"\"\"\n# Model loss graph \n\"\"\"\nhistory = {'loss': history_warmup['loss'] + history_finetunning['loss'], \n           'val_loss': history_warmup['val_loss'] + history_finetunning['val_loss'], \n           'acc': history_warmup['acc'] + history_finetunning['acc'], \n           'val_acc': history_warmup['val_acc'] + history_finetunning['val_acc']}\n\nsns.set_style(\"whitegrid\")\nfig, (ax1, ax2) = plt.subplots(2, 1, sharex='col', figsize=(20, 14))\n\nax1.plot(history['loss'], label='Train loss')\nax1.plot(history['val_loss'], label='Validation loss')\nax1.legend(loc='best')\nax1.set_title('Loss')\n\nax2.plot(history['acc'], label='Train accuracy')\nax2.plot(history['val_acc'], label='Validation accuracy')\nax2.legend(loc='best')\nax2.set_title('Accuracy')\n\nplt.xlabel('Epochs')\nsns.despine()\nplt.show()\n\"\"\"\n# Model Evaluation\n\n## Confusion Matrix\n\"\"\"\n# Create empty arays to keep the predictions and labels\nlastFullTrainPred = np.empty((0, N_CLASSES))\nlastFullTrainLabels = np.empty((0, N_CLASSES))\nlastFullValPred = np.empty((0, N_CLASSES))\nlastFullValLabels = np.empty((0, N_CLASSES))\n\n# Add train predictions and labels\nfor i in range(STEP_SIZE_TRAIN+1):\n    im, lbl = next(train_generator)\n    scores = model.predict(im, batch_size=train_generator.batch_size)\n    lastFullTrainPred = np.append(lastFullTrainPred, scores, axis=0)\n    lastFullTrainLabels = np.append(lastFullTrainLabels, lbl, axis=0)\n\n# Add validation predictions and labels\nfor i in range(STEP_SIZE_VALID+1):\n    im, lbl = next(valid_generator)\n    scores = model.predict(im, batch_size=valid_generator.batch_size)\n    lastFullValPred = np.append(lastFullValPred, scores, axis=0)\n    lastFullValLabels = np.append(lastFullValLabels, lbl, axis=0)\n    \n    \nlastFullComPred = np.concatenate((lastFullTrainPred, lastFullValPred))\nlastFullComLabels = np.concatenate((lastFullTrainLabels, lastFullValLabels))\ncomplete_labels = [np.argmax(label) for label in lastFullComLabels]\n\ntrain_preds = [np.argmax(pred) for pred in lastFullTrainPred]\ntrain_labels = [np.argmax(label) for label in lastFullTrainLabels]\nvalidation_preds = [np.argmax(pred) for pred in lastFullValPred]\nvalidation_labels = [np.argmax(label) for label in lastFullValLabels]\nfig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 7))\nlabels = ['0 - No DR', '1 - Mild', '2 - Moderate', '3 - Severe', '4 - Proliferative DR']\ntrain_cnf_matrix = confusion_matrix(train_labels, train_preds)\nvalidation_cnf_matrix = confusion_matrix(validation_labels, validation_preds)\n\ntrain_cnf_matrix_norm = train_cnf_matrix.astype('float') \/ train_cnf_matrix.sum(axis=1)[:, np.newaxis]\nvalidation_cnf_matrix_norm = validation_cnf_matrix.astype('float') \/ validation_cnf_matrix.sum(axis=1)[:, np.newaxis]\n\ntrain_df_cm = pd.DataFrame(train_cnf_matrix_norm, index=labels, columns=labels)\nvalidation_df_cm = pd.DataFrame(validation_cnf_matrix_norm, index=labels, columns=labels)\n\nsns.heatmap(train_df_cm, annot=True, fmt='.2f', cmap=\"Blues\", ax=ax1).set_title('Train')\nsns.heatmap(validation_df_cm, annot=True, fmt='.2f', cmap=sns.cubehelix_palette(8), ax=ax2).set_title('Validation')\nplt.show()\n\"\"\"\n## Quadratic Weighted Kappa\n\"\"\"\nprint(\"Train Cohen Kappa score: %.3f\" % cohen_kappa_score(train_preds,train_labels, weights='quadratic'))\nprint(\"Validation Cohen Kappa score: %.3f\" % cohen_kappa_score(validation_preds, validation_labels, weights='quadratic'))\nprint(\"Complete set Cohen Kappa score: %.3f\" % cohen_kappa_score(train_preds+validation_preds, train_labels+validation_labels, weights='quadratic'))\n\"\"\"\n# SHAP Model explainability\n\n#### About SHAP's DeepExplainer from the [source repository](https:\/\/github.com\/slundberg\/shap#deep-learning-example-with-deepexplainer-tensorflowkeras-models): \n- Deep SHAP is a high-speed approximation algorithm for SHAP values in deep learning models that builds on a connection with [DeepLIFT](https:\/\/arxiv.org\/abs\/1704.02685) described in the SHAP NIPS paper. The implementation here differs from the original DeepLIFT by using a distribution of background samples instead of a single reference value, and using Shapley equations to linearize components such as max, softmax, products, divisions, etc.\n\n### First let's see the images that we will explain\n\"\"\"\nn_explain = 2\nvalid_generator.batch_size = 10 # background dataset\nbackground, lbls = next(valid_generator)\n\nsns.set_style(\"white\")\nplt.figure(figsize=[8, 8])\nfor index, image in enumerate(background[:n_explain]):\n    plt.subplot(n_explain, 1, index+1)\n    plt.imshow(image)\n    plt.title(\"Image %s, Label: %s\" % (index, np.argmax(lbls[index])))\n    \nplt.show()\n\"\"\"\n### Now the SHAP explanation\n\"\"\"\n# explain predictions of the model on \"n_explain\" images\ne = shap.DeepExplainer(model, background)\nshap_values = e.shap_values(background)\n\n# plot the feature attributions\nshap.image_plot(shap_values, -background[:n_explain], labels=lbls, hspace=0.1)\n\"\"\"\n- The plot above explains five outputs (our five levels of diabetic retinopathy 0-5) for three different images. Red pixels increase the model's output while blue pixels decrease the output. The input images are shown on the left (they are black because most of the pixels are greater than 0), and as nearly transparent grayscale backings behind each of the explanations. The sum of the SHAP values equals the difference between the expected model output (averaged over the background dataset, here I'm using 10 images) and the current model output. \n- Note that for the images that the label is \"1.0\" (the correct one), we a greater pink area.\n- Labels that have as much pink area as the correct one are labels that our model probably doesn't have a high confidence prediction.\n\"\"\"\n\"\"\"\n## Let's try on a few more images\n\"\"\"\nn_explain = 3\nbackground, lbls = next(valid_generator)\n\nsns.set_style(\"white\")\nplt.figure(figsize=[12, 12])\nfor index, image in enumerate(background[:n_explain]):\n    plt.subplot(n_explain, 1, index+1)\n    plt.imshow(image)\n    plt.title(\"Image %s, Label: %s\" % (index, np.argmax(lbls[index])))\n    \nplt.show()\n# explain predictions of the model on \"n_explain\" images\ne = shap.DeepExplainer(model, background)\nshap_values = e.shap_values(background)\n\n# plot the feature attributions\nshap.image_plot(shap_values, -background[:n_explain], labels=lbls, hspace=0.1)\n\"\"\"\n## Apply model to test set and output predictions\n\"\"\"\ntest_generator.reset()\nSTEP_SIZE_TEST = test_generator.n\/\/test_generator.batch_size\npreds = model.predict_generator(test_generator, steps=STEP_SIZE_TEST)\npredictions = [np.argmax(pred) for pred in preds]\n\nfilenames = test_generator.filenames\nresults = pd.DataFrame({'id_code':filenames, 'diagnosis':predictions})\nresults['id_code'] = results['id_code'].map(lambda x: str(x)[:-4])\n\"\"\"\n# Predictions class distribution\n\"\"\"\nfig = plt.subplots(1, 1, sharex='col', figsize=(24, 8.7))\nsns.countplot(x=\"diagnosis\", data=results, palette=\"GnBu_d\")\nsns.despine()\nplt.show()\nresults.to_csv('submission.csv', index=False)\nresults.head(10)","meta":"{'source': 'AI4Code', 'id': '54e5ff1d134be8'}"}
{"id":"100656","text":"\"\"\"\n# Creating a Baseline Tensorflow Model to Predict Pet Popularity\n\"\"\"\n\"\"\"\nV2 Updates:\n* made CNN deeper\n* tweaked parameters\n* added some image augmentation to the model\n* added some documentation\n\"\"\"\n\"\"\"\nSources:\n* https:\/\/www.kaggle.com\/ekaterinadranitsyna\/pretrained-feature-model-keras \n    * used it to load data and convert it to TF Datasets\n* removed the Transfer Learning part for simplicity\n* converted Sequential API -> Functional API\n\"\"\"\n# Imports\n\nimport os\nfrom tqdm.notebook import tqdm\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow import keras\n# Setting the path\n\nPATH = \"..\/input\/petfinder-pawpularity-score\/\"\n# Reading in data\n\ntrain = pd.read_csv(\"\".join([PATH,\"train.csv\"]))\ntest = pd.read_csv(\"\".join([PATH,\"test.csv\"]))\nsubmission = pd.read_csv(\"\".join([PATH,\"sample_submission.csv\"]))\n# Viewing the first few rows\n\ntrain.head()\n# Viewing the shape\n\ntrain.shape\n# Viewing the info of the data\n\ntrain.info()\n# Setting the file path of each image\n\ntrain[\"path\"] = train[\"Id\"].apply(lambda x: \"..\/input\/petfinder-pawpularity-score\/train\/\" + x + \".jpg\")\ntest[\"path\"] = test[\"Id\"].apply(lambda x: \"..\/input\/petfinder-pawpularity-score\/test\/\" + x + \".jpg\")\n# Functions reading and converting data into Tensorflow datasets\n# source: https:\/\/www.kaggle.com\/ekaterinadranitsyna\/pretrained-feature-model-kera\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 64\nIMG_SIZE = 224\ntarget = 'Pawpularity'\nseed = 0\n\ndef set_seed(seed=seed):\n    \"\"\"Utility function to use for reproducibility.\n    :param seed: Random seed\n    :return: None\n    \"\"\"\n    np.random.seed(seed)\n    random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\n\ndef set_display():\n    \"\"\"Function sets display options for charts and pd.DataFrames.\n    \"\"\"\n    # Plots display settings\n    plt.style.use('fivethirtyeight')\n    plt.rcParams['figure.figsize'] = 12, 8\n    plt.rcParams.update({'font.size': 14})\n    # DataFrame display settings\n    pd.set_option('display.max_columns', None)\n    pd.set_option('display.max_rows', None)\n    pd.options.display.float_format = '{:.4f}'.format\n\n\ndef id_to_path(img_id: str, dir: str):\n    \"\"\"Function returns a path to an image file.\n    :param img_id: Image Id\n    :param dir: Path to the directory with images\n    :return: Image file path\n    \"\"\"\n    return os.path.join(dir, f'{img_id}.jpg')\n\n\n@tf.function\ndef get_image(path: str) -> tf.Tensor:\n    \"\"\"Function loads image from a file and preprocesses it.\n    :param path: Path to image file\n    :return: Tensor with preprocessed image\n    \"\"\"\n    print(f\"IMAGE PROCESSING {str}\")\n    ## Decoding the image\n    image = tf.image.decode_jpeg(tf.io.read_file(path), channels=3)\n\n    ## Resizing image\n    image = tf.cast(tf.image.resize_with_pad(image, IMG_SIZE, IMG_SIZE), dtype=tf.int32)\n\n    return image\n\n\n@tf.function\ndef process_dataset(path: str, label: int) -> tuple:\n    \"\"\"Function returns preprocessed image and label.\n    :param path: Path to image file\n    :param label: Class label\n    :return: tf.Tensor with preprocessed image, numeric label\n    \"\"\"\n    return get_image(path), label\n\n\n@tf.function\ndef get_dataset(x, y=None) -> tf.data.Dataset:\n    \"\"\"Function creates batched optimized dataset for the model\n    out of an array of file paths and (optionally) class labels.\n    :param x: Input data for the model (array of file paths)\n    :param y: Target values for the model (array of class indexes)\n    :return TensorFlow Dataset object\n    \"\"\"\n    if y is not None:\n        ds = tf.data.Dataset.from_tensor_slices((x, y))\n        return ds.map(process_dataset, num_parallel_calls=AUTOTUNE) \\\n            .batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\n    else:\n        ds = tf.data.Dataset.from_tensor_slices(x)\n        return ds.map(get_image, num_parallel_calls=AUTOTUNE) \\\n            .batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\n\ndef plot_history(hist):\n    \"\"\"Function plots a chart with training and validation metrics.\n    :param hist: Tensorflow history object from model.fit()\n    \"\"\"\n    # Losses and metrics\n    loss = hist.history['loss']\n    val_loss = hist.history['val_loss']\n    rmse = hist.history['root_mean_squared_error']\n    val_rmse = hist.history['val_root_mean_squared_error']\n\n    # Epochs to plot along x axis\n    x_axis = range(1, len(loss) + 1)\n\n    fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True)\n\n    ax1.plot(x_axis, loss, 'bo', label='Training')\n    ax1.plot(x_axis, val_loss, 'ro', label='Validation', alpha=0.3)\n    ax1.set_title('MSE Loss')\n    ax1.legend()\n\n    ax2.plot(x_axis, rmse, 'bo', label='Training')\n    ax2.plot(x_axis, val_rmse, 'ro', label='Validation', alpha=0.3)\n    ax2.set_title('Root Mean Squared Error')\n    ax2.set_xlabel('Epochs')\n    ax2.legend()\n\n    plt.tight_layout()\n    plt.show()\n# Splitting train into train and validation sets\n\ntrain_subset, valid_subset = train_test_split(\n    train[['path', target]],\n    test_size=.2, shuffle=True, random_state=0\n)\n# Creating TensorFlow datasets\n\ntrain_ds = get_dataset(x=train_subset['path'], y=train_subset[target])\nvalid_ds = get_dataset(x=valid_subset['path'], y=valid_subset[target])\ntest_ds = get_dataset(x=test['path'])\n# Creating the model\n\ndef get_model():\n    \n    ## Setting the Inputs\n    inputs = keras.Input(shape=(224, 224, 3))\n    x = inputs\n    \n    ## Preprocessing Layers\n    \n    ### Rescaling\n    x = keras.layers.experimental.preprocessing.Rescaling(1.\/255)(x)\n    \n    ## Data Augmentation\n    x = keras.layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\")(x)\n    x = keras.layers.experimental.preprocessing.RandomRotation(0.2)(x)\n    x = keras.layers.experimental.preprocessing.RandomTranslation(0.2,0.2)(x)\n    \n    ## Convolutional Layers\n    \n    ### First CNN layer\n    x = keras.layers.Conv2D(filters=96, kernel_size=3, strides=2, padding='same', kernel_initializer=tf.keras.initializers.HeNormal())(x)\n    x = keras.layers.Activation('relu')(x)\n    x = keras.layers.MaxPool2D(2)(x)\n\n    ### Second CNN layer\n    x = keras.layers.Conv2D(filters=128, kernel_size=3, strides=2, padding='same', kernel_initializer=tf.keras.initializers.HeNormal())(x)\n    x = keras.layers.BatchNormalization()(x)\n    x = keras.layers.Activation('relu')(x)\n    x = keras.layers.MaxPool2D(2)(x)\n    \n    ### Third CNN layer\n    x = keras.layers.Conv2D(filters=256, kernel_size=3, strides=2, padding='same', kernel_initializer=tf.keras.initializers.HeNormal())(x)\n    x = keras.layers.BatchNormalization()(x)\n    x = keras.layers.Activation('relu')(x)\n    x = keras.layers.MaxPool2D(2)(x)\n\n    ## Flattening the layer\n    x = keras.layers.Flatten()(x)\n    \n    ## Fully Connected (Dense) Layers\n    \n    ### First Fully Connected layer w\/ Dropout\n    x = keras.layers.Dense(128, activation='relu', kernel_initializer=tf.keras.initializers.HeNormal())(x)\n    x = keras.layers.Dropout(0.2)(x)\n    \n    ## Output layer\n    output = keras.layers.Dense(1)(x)\n\n    ## Returning the model\n    return keras.Model(inputs=inputs, outputs=output)\n# Fitting the model\n\ndef compile_and_fit(model):\n    \n    # Creating an exponential decay for learning rate\n\n    LEARNING_RATE = 1e-2\n    DECAY_STEPS = 100\n    DECAY_RATE = 0.99\n\n    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n        initial_learning_rate=LEARNING_RATE,\n        decay_steps=DECAY_STEPS, decay_rate=DECAY_RATE,\n        staircase=True\n    )\n    \n    # Creating an early stopper\n\n    early_stop = tf.keras.callbacks.EarlyStopping(\n        monitor='val_loss', patience=5, restore_best_weights=True\n    )\n    \n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n        loss=tf.keras.losses.MeanSquaredError(),\n        metrics=[tf.keras.metrics.RootMeanSquaredError()]\n    )\n    \n    history = model.fit(\n        train_ds, \n        validation_data=valid_ds,\n        epochs=50,\n        use_multiprocessing=True, workers=-1,\n        callbacks=[early_stop]\n    )\n    \n    return model, history\n# # Applying K-Fold\n\n# from sklearn.model_selection import KFold\n# from sklearn.metrics import mean_squared_error\n\n# kf = KFold(5)\n\n# scores = []\n\n# for train_index, valid_index in kf.split(train_subset):\n#     print(\"TRAIN:\", train_index, \"TEST:\", valid_index)\n    \n#     X_train, X_valid = train_subset.iloc[train_index], train_subset.iloc[valid_index]\n    \n#     train_ds = get_dataset(x=X_train['path'], y=X_train[target])\n#     valid_ds = get_dataset(x=X_valid['path'], y=X_valid[target])\n    \n#     model = get_model()\n    \n#     model, history = compile_and_fit(model)\n    \n#     predictions = model.predict(valid_ds, use_multiprocessing=True, workers=os.cpu_count())\n    \n#     rmse = mean_squared_error(X_valid[target], predictions, squared=False)\n#     print(rmse)\n    \n#     scores.append(rmse)\n\n# # Printing the results of K-Fold\n\n# print(f\"Mean: {np.mean(scores)}, Std: {np.std(scores)}\")\n# Getting the model\n\nkeras.backend.clear_session()\n\nmodel = get_model()\nmodel.summary()\n# Fitting the model\n\nmodel, history = compile_and_fit(model)\n# predictions = model.predict(valid_ds, use_multiprocessing=True, workers=os.cpu_count())\n# Plotting accuracy and loss of model\n\nplot_history(history)\n\"\"\"\n## Inference\n\"\"\"\n# Using the model to predict on the test data\n\ntest[target] = model.predict(\n    test_ds, use_multiprocessing=True, workers=os.cpu_count()\n)\n# Saving the submission file\n\ntest[['Id', target]].to_csv('submission.csv', index=False)\ntest[['Id', target]].head()\n\"\"\"\nTo-Do's\n* save model\n* remove Duplicate images\n* augment the data more\n* add Transfer Learning\n* add meta data\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b8fbb741130965'}"}
{"id":"57397","text":"\"\"\"\nIn this notebook, I introduce a code that can easily improve the speed of **diff** and **rolling** feature extraction.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\ndf = pd.read_csv('..\/input\/ventilator-pressure-prediction\/train.csv')\n\"\"\"\n# diff\n\"\"\"\n%%time\n\n# Normal code\nlag = 1\ndf[f'normal_diff{lag}_u_in'] = df.groupby('breath_id')['u_in'].diff(lag)\n%%time\n\n# Speed up code\nlag = 1\nshift_u_in = df.groupby('breath_id')['u_in'].shift(lag)\ndf[f'speedup_diff{lag}_u_in'] = df['u_in'] - shift_u_in\n(df[f'normal_diff{lag}_u_in'] - df[f'speedup_diff{lag}_u_in']).max()\n\"\"\"\n# rolling\n\"\"\"\n%%time\n\n# Normal code\nlag = 5\ndf[f'normal_windowmean{lag}_u_in'] = df.groupby('breath_id')['u_in'] \\\n                                .rolling(window=lag, min_periods=1).mean() \\\n                                .reset_index(drop=True)\n%%time\n\n# Speed up code\nlag = 5\ntmp_df = pd.DataFrame()\nfor i in range(lag):\n    tmp_df[f'tmp_shif{i}'] = df.groupby('breath_id')['u_in'].shift(i)\n\ndf[f'speedup_windowmean{lag}_u_in'] = tmp_df.mean(axis=1)\n(df[f'normal_windowmean{lag}_u_in'] - df[f'speedup_windowmean{lag}_u_in']).max()\n\"\"\"\nThank you for taking a look at this notebook. If there is anything else that can be improved, please let us know in the comments.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '69fc02d4697a47'}"}
{"id":"100090","text":"\"\"\"\n# Cash Ratio Optimization \n\n\nPendahuluan\n\n    Cash ratio (CR) merupakan salah satu aspek likuiditas yang menyatakan tingkat kesehatan bank. CR menunjukkan kemampuan bank dalam memenuhi kewajiban jangka pendek menggunakan alat-alat pembayaran liquid yang dimiliki. Alat-alat liquid ini meliputi kas dan setara kas. CR adalah perbandingan antara kas total perusahaan dengan kewajiban lancarnya. Perhitungan CR dinyatakan oleh persamaan berikut:  \n    \n    cash_ratio = (kas + setara kas) : hutang lancar. \n\nKas pada bisnis perbankan terdiri atas dua komponen, yaitu kas kantor dan kas e-channel, seperti dideskripsikan pada Bagian Overview. Nilai kas kantor pada saat t atau kas_kantor(t) dan nilai kas e channel (t) dinyatakan oleh persamaan berikut: \n\n    kas_kantor(t)=kas_kantor(t\u22121) + cash_in_kantor(t)+ cash_out_kantor(t)\n\n    kas_echannel(t) = kas_echannel(t\u22121) + cash_in_echannel(t) + cash_out_echannel(t)\n\n\nDefinisi Permasalahan\n\n   Pekerjaan yang diberikan pada kompetisi ini, sebagaimana dinyatakan pada Bagian Overview --> Description, adalah melakukan prediksi nilai kas_kantor dan kas_echannel untuk 31 hari kedepan (1 Oktober 2020 - 31 Oktober 2020). Istilah yang lebih tepat digunakan adalah forecasting, karena data yang digunakan adalah data time series. \n\n\n\n\"\"\"\n\"\"\"\nExploratory Data Analysis (EDA)\n   \n   Pada tahap ini dilakukan proses EDA untuk memahami data. \n\"\"\"\n# 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\n# mengetahui deskripsi data\ndt_desc = pd.read_csv('..\/input\/bri-data-hackathon-cr-optimization\/data_description.csv')\npd.set_option('display.max_colwidth',1)\ndt_desc\n\"\"\"\nDeskripsi dari setiap kolom ditampilkan pada tampilan diatas, dimana kolom utama yang digunakan untuk melakukan forecasting adalah kolom kas_kantor dan kas_echannel. \n\nBeberapa hal yang perlu dilakukan adalah:\n1. melihat deskripsi data yang diberikan\n2. melihat ada atau tidaknya nilai null \n3. melakukan pengecekan kesesuaian antara rumus kas_kantor dan kas_echannel dengan data yang diberikan\n\"\"\"\n#melihat deskripsi data\ndt_train = pd.read_csv('..\/input\/bri-data-hackathon-cr-optimization\/train.csv')\ndt_train.head(10)\ndt_train.info()\n\"\"\"\ndari tampilan diatas diketahui sebagai berikut:\n1. nilai total kas keluar baik cash_out_echannel maupun cash_out_kantor adalah negatif\n2. data training sudah tidak mengandung nilai null. \n\"\"\"\n\"\"\"\nlangkah selanjutnya adalah mengecek kesesuaian antara rumus kas kantor dengan data\n\"\"\"\ndata_train = dt_train\ndata_train['kas_kantor_t']= data_train['kas_kantor']\ndata_train['kas_echannel_t']= data_train['kas_echannel']\nfor idx  in range(len(data_train)):\n    if(idx >0):\n        data_train['kas_kantor_t'].iloc[idx] = data_train['cash_in_kantor'].iloc[idx]+data_train['cash_out_kantor'].iloc[idx] + data_train['kas_kantor'].iloc[idx-1]\n        data_train['kas_echannel_t'].iloc[idx] = data_train['cash_in_echannel'].iloc[idx]+data_train['cash_out_echannel'].iloc[idx] + data_train['kas_echannel'].iloc[idx-1]\n\n#komparasi hasil hitungan dan data yang diberikan\nkolom_terpilih = ['kas_kantor','kas_kantor_t','kas_echannel','kas_echannel_t']\ndt_komparasi = data_train[kolom_terpilih]\ndt_komparasi\n\"\"\"\nHasil eksplorasi terhadap data menunjukkan bahwa dataset sudah valid untuk bisa digunakan pada proses selanjutnya\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b7f70b82124889'}"}
{"id":"44433","text":"\"\"\"\n# RAMEN RATINGS PROJECT\n\"\"\"\n\"\"\"\n### SOME QUESTIONS TO ANSWER WITH DATA VISUALIZATION:\n- What are the Top ten rated ramens?\n- What the country with the highest rating product?\n- What country produces the highest amount of ramen products?\n- Which brands are the most successful? \n- Which style has the best ratings?\n\n\"\"\"\n\"\"\"\n#### This data set is from following Kaggle link: \nhttps:\/\/www.kaggle.com\/residentmario\/ramen-ratings\n\"\"\"\n### Import libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ndata = pd.read_csv('..\/input\/ramen-ratings\/ramen-ratings.csv')\ndata.head(10)\ndata.info()\ndata.describe(include='all')\n\"\"\"\n## Top Ten Ramens\n\"\"\"\ndata_top_ten = data[data['Top Ten'].notnull()]\ndata_top_ten\ntop_tens = data_top_ten[data_top_ten[\"Top Ten\"] != '\\n']\ntop_tens\ntop_tens['Year'] = top_tens['Top Ten'].apply(lambda year:year.split('#')[0])\ntop_tens['Rank'] = top_tens['Top Ten'].apply(lambda year:int(year.split('#')[1]))\ntop_tens['Popularity'] = top_tens['Rank'].apply(lambda rank: abs(11-rank))\ntop_tens\ntop_tens =top_tens.drop('Top Ten',axis=1)\ntop_tens.head()\ntop_tens = top_tens.drop('Review #',axis=1)\ntop_tens.reset_index(drop=True)\n## 2016 top ten ramen\nplt.figure(figsize=(14,4)) \n\nsns.countplot(data=top_tens,x='Country',hue='Rank')\nplt.legend(loc=(1.05 ,0.1),title=\"Ranks\")\n## 2016 top ten ramen\ntops = sns.catplot(data=top_tens,x='Country',y='Popularity',hue='Year',kind='bar',height=6,aspect=2,ci=None)\n(tops.set_axis_labels('COUNTRIES', 'MOST RANKED',weight='bold')\n     .set(ylim=(0,10)))\ntops.fig.suptitle('MOST RANKED RAMEN BY COUNTRY AND YEAR',weight='bold')\n\"\"\"\n### Sorting Top Tens Dataframe based on rank for each year for easy reading\n\"\"\"\ntop_tens= top_tens.sort_values(by=['Year','Rank'],ascending=True,ignore_index=True)\ntop_tens\nplt.figure(figsize=(16,10))\nsns.countplot(data=top_tens,x='Country').set_title('Best Countries in Top Ten Ramen List',weight='bold')\n\nplt.figure(figsize=(10,6))\nsns.countplot(data=top_tens,x='Style').set_title('Best Styles in Top Ten Ramen List',weight='bold')\n\"\"\"\n### What country has the most ramen products\n\"\"\"\n## Check if any country used by different names\ndata['Country'].value_counts()\ndata_clean = data.replace({'Country': {'United States': \"USA\", 'Holland': 'Netherlands', \"Sarawak\": 'Malaysia'}})\ndata_clean['Country'].value_counts()\nplt.figure(figsize=(20,16),dpi=200)\nax = sns.countplot(data=data_clean, x='Country',order=data_clean['Country'].value_counts().index)\nplt.title('Countries based on Ramen Products',weight='bold',fontsize=16)    \nplt.xlabel('Countries',weight='bold')\nplt.xticks(rotation=90)\n\nfor p in ax.patches:\n    ax.annotate(f'\\n{p.get_height()}', (p.get_x()+0.2, p.get_height()), ha='center', va='top', color='black', size=10)\nplt.show()\n\"\"\"\n### Which brands are the most successful?\n\"\"\"\ndata_clean['Stars'].value_counts()\ndrop_unrated = data_clean[data_clean['Stars'] == 'Unrated'].index\ndata_clean = data_clean.drop(drop_unrated)\ndata_clean['Stars'] = data_clean['Stars'].apply(lambda star: float(star))\nsuccessful_brands = data_clean[ data_clean[\"Stars\"] >= 4.5]\nsuccessful_brands['Brand'].value_counts()\n## There are lots of brands (147) with 4.5 star and above, so I will display only the first 10 companies with most stars\nplt.figure(figsize=(20,10))\nax = sns.countplot(data=successful_brands, x='Brand', hue='Stars', order = successful_brands['Brand'].value_counts().iloc[:10].index)\nplt.title('Most Successful Ten Ramen Brands based on Stars',weight='bold',fontsize=16)\nplt.xlabel('Brand Name',weight='bold')\nplt.ylabel('Count',weight='bold')\nplt.xticks(rotation=90)\nfor p in ax.patches:\n    ax.annotate(f'\\n{p.get_height()}', (p.get_x()+0.2, p.get_height()), ha='center', va='top', color='black', size=10)\nplt.show()\n\"\"\"\n### Which style has most ratings?\n\"\"\"\n## I will use successful_brands df for styling, because I already distrubuted ramens by 4.5 stars and above\nsuccessful_brands['Style'].value_counts()\nplt.figure(figsize=(20,10))\nax = sns.countplot(data=successful_brands, x='Style', hue='Stars', order = successful_brands['Style'].value_counts().index)\nplt.title('Most Rated Styles',weight='bold',fontsize=16)\nplt.xlabel('Brand Name',weight='bold')\nplt.ylabel('Count',weight='bold')\nplt.xticks(rotation=90)\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': '51e6a326320f4a'}"}
{"id":"97544","text":"\"\"\"\n<h1 style=\"color:Orange;\"><center>Pima Indians Diabetes - EDA and Prediction<\/center><\/h1> \n\"\"\"\n\"\"\"\nTable of Contents:\n1. [Introduction](#1)\n    - 1.1 [Context](#2)\n    - 1.2 [Data Dictionary](#3)\n    - 1.3 [Task](#4)\n2. [Preparation](#5)\n    - 2.1 [Packages](#6)\n    - 2.2 [Data](#7)\n    - 2.3 [Understanding Data](#8)\n3. [Exploratory Data Analysis](#9)\n    - 3.1 [Univariate Analysis](#10)\n    - 3.2 [Bivariate Analysis](#11)\n4. [Data Preprocessing](#12)\n    - 4.1 [Conclusions from EDA](#13)\n    - 4.2 [Removing the outliers](#14)\n    - 4.3 [Removing the skewness](#15)\n    - 4.4 [Making features model ready](#16)\n5. [Modeling](#17)\n    - 5.1 [Packages](#18)\n    - 5.1 [Train\/test split](#19)\n    - 5.2 [Base Modeling](#20)\n    - 5.3 [Hyperparameter tuning using GridSearchCV](#21)\n    - 5.4 [Bayesian Optimization with gausian process](#22)\n\"\"\"\n\"\"\"\n### 1. Introduction <a id=1><\/a>\n\"\"\"\n\"\"\"\n#### 1.1 Context <a id=2><\/a>\nThis dataset is originally from the National Institute of Diabetes and Digestive and Kidney Diseases. The objective of the dataset is to diagnostically predict whether or not a patient has diabetes, based on certain diagnostic measurements included in the dataset. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here are females at least 21 years old of Pima Indian heritage.\n\"\"\"\n\"\"\"\n#### 1.2 Data Dictionary <a id=3><\/a>\n`Pregnancies` - Number of times pregnant\n\n`Glucose` - Plasma glucose concentration - 2 hours in an oral glucose tolerance test\n\n`BloodPressure` - Diastolic blood pressure (mm Hg)\n\n`SkinThickness` - Triceps skin fold thickness (mm)\n\n`Insulin` - 2-Hour serum insulin (mu U\/ml)\n\n`BMI` - Body mass index\n\n`DiabetesPedigreeFunction` - Diabetes pedigree function\n\n`Age` - Age (years)\n\n`Outcome` - Class variable (0 or 1)\n\"\"\"\n\"\"\"\n#### 1.3 Task <a id=4><\/a>\nTo predict the onset of diabetes based on diagnostic measures.\n\"\"\"\n\"\"\"\n### 2. Preparation <a id=5><\/a>\n\"\"\"\n\"\"\"\n#### 2.1 Packages <a id=6><\/a>\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport seaborn as sns\n\nimport warnings\nfrom termcolor import colored\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n#### 2.2 Data <a id=7><\/a>\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/pima-indians-diabetes-database\/diabetes.csv')\n\"\"\"\n#### 2.3 Understanding Data <a id=8><\/a>\n\"\"\"\n\"\"\"\n##### 2.3.1 The shape of the data\n\"\"\"\nprint(f\"Shape of dataset: {colored(df.shape, 'yellow')}\")\n\"\"\"\n##### 2.3.2 Preview of the first five rows of the data\n\"\"\"\ndf.head()\n\"\"\"\n##### 2.3.3 Renaming `DiabetesPedigreeFunction` to `DPF` for better consistency\n\"\"\"\ndf = df.rename(columns = {'DiabetesPedigreeFunction':'DPF'})\n\"\"\"\n##### 2.3.4 Checking the number of unique values in each column\n\"\"\"\ndict = {}\nfor i in list(df.columns):\n    dict[i] = df[i].value_counts().shape[0]\n\npd.DataFrame(dict,index=[\"unique count\"]).transpose()\n\"\"\"\n##### 2.3.5 Separating into features and targets\n\"\"\"\ncon_cols = list(df.drop('Outcome',axis=1).columns)\ntarget = ['Outcome']\nprint(f\"The columns are : {colored(con_cols, 'yellow')}\")\nprint(f\"The target is   : {colored(target,'yellow')}\")\n\"\"\"\n##### 2.3.6 Summary statistics\n\"\"\"\ndf[con_cols].describe().transpose()\n\"\"\"\n##### 2.3.6 Missing values\n\"\"\"\ndf.isnull().sum()\n\"\"\"\n### 3. Exploratory Data Analysis <a id=9><\/a>\n\"\"\"\n\"\"\"\n#### 3.1 Univariate Analysis <a id=10><\/a>\n\"\"\"\n\"\"\"\n##### 3.1.1 Count of target variable\n\"\"\"\nfig = plt.figure(figsize=(18,7))\ngs = fig.add_gridspec(1,2)\ngs.update(wspace=0.3, hspace=0.15)\nax0 = fig.add_subplot(gs[0,0])\nax1 = fig.add_subplot(gs[0,1])\n\nbackground_color = \"#c9c9ee\"\ncolor_palette = [\"#f56476\",\"#ff8811\",\"#001427\",\"#6369d1\",\"#f0f66e\"]\nfig.patch.set_facecolor(background_color) \nax0.set_facecolor(background_color) \nax1.set_facecolor(background_color)\n\n# Title of the plot\nax0.text(0.5,0.5,\"Count of the target\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\n\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\n\n# Target Count\nax1.text(0.45,510,\"Output\",fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.countplot(ax=ax1, data=df, x = 'Outcome',palette = color_palette)\nax1.set_xlabel(\"\")\nax1.set_ylabel(\"\")\nax1.set_xticklabels([\"Low chances of diabetes(0)\",\"High chances of diabetes(1)\"])\n\nax0.spines[\"top\"].set_visible(False)\nax0.spines[\"left\"].set_visible(False)\nax0.spines[\"bottom\"].set_visible(False)\nax0.spines[\"right\"].set_visible(False)\nax1.spines[\"top\"].set_visible(False)\nax1.spines[\"left\"].set_visible(False)\nax1.spines[\"right\"].set_visible(False)\n\"\"\"\n##### 3.1.2 Boxenplot of features\n\"\"\"\nfig = plt.figure(figsize=(18,15))\ngs = fig.add_gridspec(3,3)\ngs.update(wspace=0.5, hspace=0.25)\nax0 = fig.add_subplot(gs[0,0])\nax1 = fig.add_subplot(gs[0,1])\nax2 = fig.add_subplot(gs[0,2])\nax3 = fig.add_subplot(gs[1,0])\nax4 = fig.add_subplot(gs[1,1])\nax5 = fig.add_subplot(gs[1,2])\nax6 = fig.add_subplot(gs[2,0])\nax7 = fig.add_subplot(gs[2,1])\nax8 = fig.add_subplot(gs[2,2])\n\nbackground_color = \"#c9c9ee\"\n# c9c9ee\ncolor_palette = [\"#f56476\",\"#ff8811\",\"#ff0040\",\"#ff7f6c\",\"#f0f66e\",\"#990000\"]\nfig.patch.set_facecolor(background_color) \nax0.set_facecolor(background_color) \nax1.set_facecolor(background_color)\nax2.set_facecolor(background_color)\nax3.set_facecolor(background_color)\nax4.set_facecolor(background_color)\nax5.set_facecolor(background_color)\nax6.set_facecolor(background_color)\nax7.set_facecolor(background_color)\nax8.set_facecolor(background_color)\n\n# Title of the plot\nax0.spines[\"bottom\"].set_visible(False)\nax0.spines[\"left\"].set_visible(False)\nax0.spines[\"top\"].set_visible(False)\nax0.spines[\"right\"].set_visible(False)\nax0.tick_params(left=False, bottom=False)\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.text(0.5,0.5,\n         'Boxenplot plot for various\\n features\\n_________________',\n         horizontalalignment='center',\n         verticalalignment='center',\n         fontsize=18, fontweight='bold',\n         fontfamily='serif',\n         color=\"#000000\")\n\n# Pregnancies \nax1.text(-0.18, 19, 'Pregnancies', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax1,y=df['Pregnancies'],palette=[\"#f56476\"],width=0.6)\nax1.set_xlabel(\"\")\nax1.set_ylabel(\"\")\n\n# Glucose \nax2.text(-0.1, 217, 'Glucose', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax2,y=df['Glucose'],palette=[\"#ff8811\"],width=0.6)\nax2.set_xlabel(\"\")\nax2.set_ylabel(\"\")\n\n# BloodPressure \nax3.text(-0.20, 132, 'BloodPressure', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax3.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax3,y=df['BloodPressure'],palette=[\"#ff0040\"],width=0.6)\nax3.set_xlabel(\"\")\nax3.set_ylabel(\"\")\n\n# SkinThickness \nax4.text(-.2, 110, 'SkinThickness', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax4.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax4,y=df['SkinThickness'],palette=[\"#ff7f6c\"],width=0.6)\nax4.set_xlabel(\"\")\nax4.set_ylabel(\"\")\n\n# Insulin \nax5.text(-0.10, 900, 'Insulin', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax5.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax5,y=df['Insulin'],palette=[\"#f0f66e\"],width=0.6)\nax5.set_xlabel(\"\")\nax5.set_ylabel(\"\")\n\n# BMI \nax6.text(-0.08, 77, 'BMI', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax6.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax6,y=df['BMI'],palette=[\"#990000\"],width=0.6)\nax6.set_xlabel(\"\")\nax6.set_ylabel(\"\")\n\n# DPF \nax7.text(-0.065, 2.8, 'DPF', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax7.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax7,y=df['DPF'],palette=[\"#3339FF\"],width=0.6)\nax7.set_xlabel(\"\")\nax7.set_ylabel(\"\")\n\n# Age \nax8.text(-0.08, 86, 'Age', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax8.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.boxenplot(ax=ax8,y=df['Age'],palette=[\"#34495E\"],width=0.6)\nax8.set_xlabel(\"\")\nax8.set_ylabel(\"\")\n\n\n\nfor s in [\"top\",\"right\",\"left\"]:\n    ax1.spines[s].set_visible(False)\n    ax2.spines[s].set_visible(False)\n    ax3.spines[s].set_visible(False)\n    ax4.spines[s].set_visible(False)\n    ax5.spines[s].set_visible(False)\n    ax6.spines[s].set_visible(False)\n    ax7.spines[s].set_visible(False)\n    ax8.spines[s].set_visible(False)\n\"\"\"\n##### 3.1.3 Histogram of features\n\"\"\"\nfig = plt.figure(figsize=(18,15))\ngs = fig.add_gridspec(3,3)\ngs.update(wspace=0.5, hspace=0.25)\nax0 = fig.add_subplot(gs[0,0])\nax1 = fig.add_subplot(gs[0,1])\nax2 = fig.add_subplot(gs[0,2])\nax3 = fig.add_subplot(gs[1,0])\nax4 = fig.add_subplot(gs[1,1])\nax5 = fig.add_subplot(gs[1,2])\nax6 = fig.add_subplot(gs[2,0])\nax7 = fig.add_subplot(gs[2,1])\nax8 = fig.add_subplot(gs[2,2])\n\nbackground_color = \"#c9c9ee\"\n# c9c9ee\ncolor_palette = [\"#f56476\",\"#ff8811\",\"#ff0040\",\"#ff7f6c\",\"#f0f66e\",\"#990000\"]\nfig.patch.set_facecolor(background_color) \nax0.set_facecolor(background_color) \nax1.set_facecolor(background_color)\nax2.set_facecolor(background_color)\nax3.set_facecolor(background_color)\nax4.set_facecolor(background_color)\nax5.set_facecolor(background_color)\nax6.set_facecolor(background_color)\nax7.set_facecolor(background_color)\nax8.set_facecolor(background_color)\n\n# Title of the plot\nax0.spines[\"bottom\"].set_visible(False)\nax0.spines[\"left\"].set_visible(False)\nax0.spines[\"top\"].set_visible(False)\nax0.spines[\"right\"].set_visible(False)\nax0.tick_params(left=False, bottom=False)\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.text(0.5,0.5,\n         'Histogram for various\\n features\\n_________________',\n         horizontalalignment='center',\n         verticalalignment='center',\n         fontsize=18, fontweight='bold',\n         fontfamily='serif',\n         color=\"#000000\")\n\n# Pregnancies \nax1.text(4, 260, 'Pregnancies', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax1,x=df['Pregnancies'],color=\"#f56476\",kde=True)\nax1.set_xlabel(\"\")\nax1.set_ylabel(\"\")\n\n# Glucose \nax2.text(55, 105, 'Glucose', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax2,x=df['Glucose'],color=\"#ff8811\",kde=True)\nax2.set_xlabel(\"\")\nax2.set_ylabel(\"\")\n\n# BloodPressure \nax3.text(35, 115, 'BloodPressure', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax3.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax3,x=df['BloodPressure'],color=\"#ff0040\",kde=True)\nax3.set_xlabel(\"\")\nax3.set_ylabel(\"\")\n\n# SkinThickness \nax4.text(25, 250, 'SkinThickness', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax4.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax4,x=df['SkinThickness'],color=\"#ff7f6c\",kde=True)\nax4.set_xlabel(\"\")\nax4.set_ylabel(\"\")\n\n# Insulin \nax5.text(250, 430, 'Insulin', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax5.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax5,x=df['Insulin'],color=\"#f0f66e\",kde=True)\nax5.set_xlabel(\"\")\nax5.set_ylabel(\"\")\n\n# BMI \nax6.text(25, 100, 'BMI', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax6.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax6,x=df['BMI'],palette=[\"#990000\"],kde=True)\nax6.set_xlabel(\"\")\nax6.set_ylabel(\"\")\n\n# DPF \nax7.text(1, 150, 'DPF', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax7.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax7,x=df['DPF'],color=\"#3339FF\",kde=True)\nax7.set_xlabel(\"\")\nax7.set_ylabel(\"\")\n\n# Age \nax8.text(40, 230, 'Age', fontsize=14, fontweight='bold', fontfamily='serif', color=\"#000000\")\nax8.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.histplot(ax=ax8,x=df['Age'],color=\"#34495E\",kde=True)\nax8.set_xlabel(\"\")\nax8.set_ylabel(\"\")\n\n\nfor s in [\"top\",\"right\",\"left\"]:\n    ax1.spines[s].set_visible(False)\n    ax2.spines[s].set_visible(False)\n    ax3.spines[s].set_visible(False)\n    ax4.spines[s].set_visible(False)\n    ax5.spines[s].set_visible(False)\n    ax6.spines[s].set_visible(False)\n    ax7.spines[s].set_visible(False)\n    ax8.spines[s].set_visible(False)\n\"\"\"\n#### 3.2 Bivariate Analysis <a id=11><\/a>\n\"\"\"\n\"\"\"\n##### 3.2.1 Correlation matrix of features\n\"\"\"\ndf_corr = df.corr().transpose()\ndf_corr\nfig = plt.figure(figsize=(10,10))\ngs = fig.add_gridspec(1,1)\ngs.update(wspace=0.3, hspace=0.15)\nax0 = fig.add_subplot(gs[0,0])\nfig.patch.set_facecolor(background_color) \nax0.set_facecolor(background_color) \n\ndf_corr = df[con_cols].corr().transpose()\nmask = np.triu(np.ones_like(df_corr))\nax0.text(2,-0.1,\"Correlation Matrix\",fontsize=22, fontweight='bold', fontfamily='serif', color=\"#000000\")\nsns.heatmap(df_corr,mask=mask,fmt=\".1f\",annot=True)\nplt.show()\n\"\"\"\n##### 3.2.2 Distribution of features according to target variable\n\"\"\"\nfig = plt.figure(figsize=(18,25))\ngs = fig.add_gridspec(8,2)\ngs.update(wspace=0.5, hspace=0.5)\nax0 = fig.add_subplot(gs[0,0])\nax1 = fig.add_subplot(gs[0,1])\nax2 = fig.add_subplot(gs[1,0])\nax3 = fig.add_subplot(gs[1,1])\nax4 = fig.add_subplot(gs[2,0])\nax5 = fig.add_subplot(gs[2,1])\nax6 = fig.add_subplot(gs[3,0])\nax7 = fig.add_subplot(gs[3,1])\nax8 = fig.add_subplot(gs[4,0])\nax9 = fig.add_subplot(gs[4,1])\nax10 = fig.add_subplot(gs[5,0])\nax11 = fig.add_subplot(gs[5,1])\nax12 = fig.add_subplot(gs[6,0])\nax13 = fig.add_subplot(gs[6,1])\nax14 = fig.add_subplot(gs[7,0])\nax15 = fig.add_subplot(gs[7,1])\n\n\nbackground_color = \"#c9c9ee\"\ncolor_palette = [\"#f56476\",\"#ff8811\",\"#ff0040\",\"#ff7f6c\",\"#f0f66e\",\"#990000\"]\nfig.patch.set_facecolor(background_color) \nax0.set_facecolor(background_color) \nax1.set_facecolor(background_color) \nax2.set_facecolor(background_color)\nax3.set_facecolor(background_color)\nax4.set_facecolor(background_color)\nax5.set_facecolor(background_color) \nax6.set_facecolor(background_color) \nax7.set_facecolor(background_color)\nax8.set_facecolor(background_color)\nax9.set_facecolor(background_color)\nax10.set_facecolor(background_color)\nax11.set_facecolor(background_color)\nax12.set_facecolor(background_color)\nax13.set_facecolor(background_color)\nax14.set_facecolor(background_color)\nax15.set_facecolor(background_color)\n\n# Pregnancies title\nax0.text(0.5,0.5,\"Distribution of Pregnancies\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax0.spines[\"bottom\"].set_visible(False)\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\n\n# Pregnancies\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax1, data=df, x='Pregnancies',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax1.set_xlabel(\"\")\nax1.set_ylabel(\"\")\n\n# Glucose title\nax2.text(0.5,0.5,\"Distribution of Glucose\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax2.spines[\"bottom\"].set_visible(False)\nax2.set_xticklabels([])\nax2.set_yticklabels([])\nax2.tick_params(left=False, bottom=False)\n\n# Glucose\nax3.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax3, data=df, x='Glucose',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax3.set_xlabel(\"\")\nax3.set_ylabel(\"\")\n\n# BloodPressure title\nax4.text(0.5,0.5,\"Distribution of BloodPressure\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax4.spines[\"bottom\"].set_visible(False)\nax4.set_xticklabels([])\nax4.set_yticklabels([])\nax4.tick_params(left=False, bottom=False)\n\n# BloodPressure\nax5.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax5, data=df, x='BloodPressure',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax5.set_xlabel(\"\")\nax5.set_ylabel(\"\")\n\n# SkinThickness title\nax6.text(0.5,0.5,\"Distribution of SkinThickness\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax6.spines[\"bottom\"].set_visible(False)\nax6.set_xticklabels([])\nax6.set_yticklabels([])\nax6.tick_params(left=False, bottom=False)\n\n# SkinThickness\nax7.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax7, data=df, x='SkinThickness',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax7.set_xlabel(\"\")\nax7.set_ylabel(\"\")\n\n# Insulin title\nax8.text(0.5,0.5,\"Distribution of Insulin\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax8.spines[\"bottom\"].set_visible(False)\nax8.set_xticklabels([])\nax8.set_yticklabels([])\nax8.tick_params(left=False, bottom=False)\n\n# Insulin\nax9.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax9, data=df, x='Insulin',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax9.set_xlabel(\"\")\nax9.set_ylabel(\"\")\n\n# BMI title\nax10.text(0.5,0.5,\"Distribution of BMI\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax10.spines[\"bottom\"].set_visible(False)\nax10.set_xticklabels([])\nax10.set_yticklabels([])\nax10.tick_params(left=False, bottom=False)\n\n# BMI\nax11.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax11, data=df, x='BMI',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax11.set_xlabel(\"\")\nax11.set_ylabel(\"\")\n\n# DPF title\nax12.text(0.5,0.5,\"Distribution of DPF\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax12.spines[\"bottom\"].set_visible(False)\nax12.set_xticklabels([])\nax12.set_yticklabels([])\nax12.tick_params(left=False, bottom=False)\n\n# DPF\nax13.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax13, data=df, x='DPF',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax13.set_xlabel(\"\")\nax13.set_ylabel(\"\")\n\n# Age title\nax14.text(0.5,0.5,\"Distribution of Age\\naccording to\\n target variable\\n___________\",\n        horizontalalignment = 'center',\n        verticalalignment = 'center',\n        fontsize = 18,\n        fontweight='bold',\n        fontfamily='serif',\n        color='#000000')\nax14.spines[\"bottom\"].set_visible(False)\nax14.set_xticklabels([])\nax14.set_yticklabels([])\nax14.tick_params(left=False, bottom=False)\n\n# Age\nax15.grid(color='#000000', linestyle=':', axis='y', zorder=0,  dashes=(1,5))\nsns.kdeplot(ax=ax15, data=df, x='Age',hue=\"Outcome\", fill=True,palette=[\"#ff8811\",\"#3339FF\"], alpha=.5, linewidth=0)\nax15.set_xlabel(\"\")\nax15.set_ylabel(\"\")\n\n\n\nfor i in [\"top\",\"left\",\"right\"]:\n    ax0.spines[i].set_visible(False)\n    ax1.spines[i].set_visible(False)\n    ax2.spines[i].set_visible(False)\n    ax3.spines[i].set_visible(False)\n    ax4.spines[i].set_visible(False)\n    ax5.spines[i].set_visible(False)\n    ax6.spines[i].set_visible(False)\n    ax7.spines[i].set_visible(False)\n    ax8.spines[i].set_visible(False)\n    ax9.spines[i].set_visible(False)\n    ax10.spines[i].set_visible(False)\n    ax11.spines[i].set_visible(False)\n    ax12.spines[i].set_visible(False)\n    ax13.spines[i].set_visible(False)\n    ax14.spines[i].set_visible(False)\n    ax15.spines[i].set_visible(False)\n\n\"\"\"\n##### 3.2.3 Pair plot - one plot to rule them all\n\"\"\"\nsns.pairplot(df,hue='Outcome',palette = [\"#ff8811\",\"#3339FF\"])\nplt.show()\n\"\"\"\n##### 3.2.4 Scatter plot of BloodPressure vs Glucose vs Age wrt Outcome \n\"\"\"\nfig = px.scatter_3d(df, x='Age', y='Glucose', z='BloodPressure',\n              color='Outcome',size_max=18,color_continuous_scale=[\"#3339FF\", \"#ff8811\"])\nfig.update_layout({\"template\":\"plotly_dark\"})\nfig.show()\n\"\"\"\n##### 3.2.5 Scatter plot of Glucose vs Insulin vs DPF wrt Outcome \n\"\"\"\nfig = px.scatter_3d(df, x='Glucose', y='Insulin', z='DPF',\n              color='Outcome',size_max=18,color_continuous_scale=[\"#3339FF\", \"#ff8811\"])\nfig.update_layout({\"template\":\"plotly_dark\"})\nfig.show()\n\"\"\"\n### 4. Data Preprocessing <a id=12><\/a>\n\"\"\"\n\"\"\"\n#### 4.1 Conclusions from EDA <a id=13><\/a>\n1. There are no NaN values in the data.\n2. They are a very less number of outliers in all features.\n3. There is no apparent linear correlation between feature variable according to the heatmap.\n4. The distribution curve of `insulin` and `DPF` is right skewed.\n5. The distribution curve of `Glucose` wrt `Outcome` shows that there are less number of people with high Glucose level but they have higher chances of diabetes.\n6. The `BloodPressure` lies between 40 and 100, and there are less number of people with diabetes in this range.\n7. The plots `3.2.3` tells the following -\n    - Over the `Pregnancy` range, females with high glucose have Diabetes.\n    - As `Insulin` increase, and as `Glucose`, there are higher chances of Diabetes.\n    - As `BMI` increase, and as `Glucose`, there are higher chances of Diabetes.\n    - `Age` alone isn't really an indicator of Diabetes.\n8. Middle aged people with high `Glucose` level and high `BloodPressure` level have higher chances of Diabetes which is quite intuitive as well.\n\n\"\"\"\n\"\"\"\n#### 4.2 Removing the outliers <a id=14><\/a>\n\"\"\"\n\"\"\"\n##### 4.2.1 The shape of dataset before removing the outliers\n\"\"\"\nprint(f\"Shape of dataset: {colored(df.shape, 'yellow')}\")\n\"\"\"\n##### 4.2.2 Removing the outliers and checking the shape\n\"\"\"\ndf.drop(df[df[\"Pregnancies\"] > 14].index,inplace=True)\ndf.drop(df[df[\"Glucose\"] < 50].index,inplace=True)\ndf.drop(df[df[\"BloodPressure\"] > 120].index,inplace=True)\ndf.drop(df[df[\"SkinThickness\"] > 80].index,inplace=True)\ndf.drop(df[df[\"Insulin\"] > 600].index,inplace=True)\ndf.drop(df[df[\"BMI\"] > 55].index,inplace=True)\ndf.drop(df[df[\"DPF\"] > 2].index,inplace=True)\ndf.drop(df[df[\"Age\"] > 70].index,inplace=True)\n\nprint(f\"Shape of dataset: {colored(df.shape, 'yellow')}\")\n\"\"\"\n#### 4.3 Removing the skewness <a id=15><\/a>\n\"\"\"\n\"\"\"\n##### 4.3.1 Checking the distribution of `Insulin`\n\"\"\"\nsns.kdeplot(df['Insulin'],color='Orange',fill=True)\n\"\"\"\n##### 4.3.2 Removing the skewness using a log function and checking the distribution again\n\"\"\"\ndf['Insulin'] = df['Insulin'].map(lambda i : np.log(i) if i > 0 else 0)\nsns.kdeplot(df['Insulin'],color='Orange',fill=True)\n\"\"\"\n#### 4.4 Making features model ready <a id=16><\/a>\n\"\"\"\n# importing the scaler\nfrom sklearn.preprocessing import StandardScaler\n\n# creating a copy of dataframe\ndf1 = df\ncol_cols = list(df1.columns)\n\n# removing the target variable from the columns list\ncol_cols.pop() \n\n# separating the features and target \nX = df1.drop(['Outcome'],axis=1)\ny = df1[['Outcome']]\n\n# instantiating the scaler\nscaler = StandardScaler()\nX[col_cols] = scaler.fit_transform(X[col_cols])\nprint(\"The first 5 rows of X are\")\nX.head()\n\"\"\"\n### 5. Modeling <a id=17><\/a>\n\"\"\"\n\"\"\"\n#### 5.1 Packages <a id=18><\/a>\n\"\"\"\n# Train test split\nfrom sklearn.model_selection import train_test_split\n\n# Base Models\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\n\n# Ensembling and Boosting\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n\n# Metrics\nfrom sklearn.metrics import accuracy_score, classification_report, roc_curve\n\n# Cross Validation\nfrom sklearn.model_selection import cross_val_score\n\n# Hyper-parameter tuning\nfrom functools import partial\nfrom skopt import gp_minimize\nfrom skopt import space\nfrom sklearn import model_selection\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\"\"\"\n#### 5.2 Train\/test split <a id=19><\/a>\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y , test_size = 0.2, random_state = 42)\nprint(f\"The shape of X_train is      {colored(X_train.shape,'yellow')}\")\nprint(f\"The shape of X_test is       {colored(X_test.shape,'yellow')}\")\nprint(f\"The shape of y_train is      {colored(y_train.shape,'yellow')}\")\nprint(f\"The shape of y_test is       {colored(y_test.shape,'yellow')}\")\n\"\"\"\n#### 5.3 Base Modeling <a id=20><\/a>\n\"\"\"\n\"\"\"\n##### 5.3.1 Training the data with base models without any hyper-parameter tuning\n\"\"\"\nmodels = [\n    ('SVC', SVC()),\n    ('DecisionTreeClassifier',DecisionTreeClassifier()),\n    ('KNeighborsClassifier',KNeighborsClassifier()),\n    ('LogisticRegression',LogisticRegression()),\n    ('RandomForestClassifier',RandomForestClassifier()),\n    ('AdaBoostClassifier',AdaBoostClassifier()),\n    ('GradientBoostingClassifier',GradientBoostingClassifier())\n]\n\nprint(\"The accuracy scores of the models are :\")\nfor model_name, model in models:\n    model.fit(X_train, y_train)\n    y_pred = model.predict(X_test)\n    print(f\"{colored(model_name,'blue')}\")\n    print(f\"{colored(accuracy_score(y_test,y_pred), 'yellow')}\\n\")\n\"\"\"\n#### 5.4 Hyperparameter tuning using GridSearchCV <a id=21><\/a>\n\"\"\"\n\"\"\"\n##### 5.4.1 Decision Tree Classifier tuning\n\"\"\"\n# define the model\nclassifier = DecisionTreeClassifier()\n\n# define a grid of parameters\nparam_grid = {'criterion':['gini','entropy'],\n              'splitter':['best','random'],\n              'max_depth':[2,3,4,5,6,7,8],\n              'max_features':['auto','sqrt','log2'],\n             }\n\n# initialize grid search\nmodel = GridSearchCV(\nestimator=classifier, param_grid=param_grid, scoring=\"accuracy\", verbose=10,\nn_jobs=1,\ncv=5 )\n\n# fit the model and extract best score\nmodel.fit(X,y)\nprint(f\"{colored('Decision Tree Classifier', 'blue')}\")\nprint(f\"Best score : {colored(model.best_score_,'yellow')}\")\n\nprint(\"Best parameters set:\")\nbest_parameters = model.best_estimator_.get_params()\nfor param_name in sorted(param_grid.keys()):\n    print(f\"\\t{param_name}: {colored(best_parameters[param_name],'yellow')}\")\n\"\"\"\n##### 5.4.2 K Neighbors Classifier tuning\n\"\"\"\n# define the model\nclassifier = KNeighborsClassifier()\n\n# define a grid of parameters\nparam_grid = {'n_neighbors':[2,3,4,5,6,7,8],\n              'weights':['uniform','distance'],\n              'algorithm':['auto','ball_tree','kd_tree','brute'],\n              'leaf_size':[26,27,28,29,30,31]\n             }\n\n# initialize grid search\nmodel = GridSearchCV(\nestimator=classifier, param_grid=param_grid, scoring=\"accuracy\", verbose=10,\nn_jobs=1,\ncv=5 )\n\n# fit the model and extract best score\nmodel.fit(X,y)\nprint(f\"{colored('K Neighbors Classifier', 'blue')}\")\nprint(f\"Best score : {colored(model.best_score_,'yellow')}\")\n\nprint(\"Best parameters set:\")\nbest_parameters = model.best_estimator_.get_params()\nfor param_name in sorted(param_grid.keys()):\n    print(f\"\\t{param_name}: {colored(best_parameters[param_name],'yellow')}\")\n\"\"\"\n### If you like the notebook, consider giving an upvote.\nCheck out my other notebooks\n1. https:\/\/www.kaggle.com\/namanmanchanda\/star-wars-classifier\n2. https:\/\/www.kaggle.com\/namanmanchanda\/gradient-descent-101\n3. https:\/\/www.kaggle.com\/namanmanchanda\/cat-vs-dog-classifier-10-lines-of-code-fast-ai\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b3189374967441'}"}
{"id":"48272","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport math, re\nfrom collections import Counter\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\n\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport folium\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## Dataset description:\n\n    \n\"\"\"\nwf_input = pd.read_csv(\"\/kaggle\/input\/california-wildfire-incidents-20132020\/California_Fire_Incidents.csv\")\nwf_input['Started'] = pd.to_datetime(wf_input['Started'].astype(str))\n\"\"\"\nCalifornia is one of the places having the most deadliest and destructive wildfire seasons. The dataset contains the list of Wildfires that has occurred in California between 2013 and 2019. The dataset contains the location where wildfires have occurred including the County name, latitude and longitude values and also details on when the wildfire has started.\n\nThis data helps to generate insights on what locations in California are under fire threat, what time do Wildfires usually occur and how frequent and devastating they are!!\n\"\"\"\nwf_input.head()\nwf_input.columns\n\"\"\"\n## Data preprocessing\n\"\"\"\n# Some Records may be counted in diffrent counties multiple times\nwf = wf_input.drop_duplicates(subset=['Name', 'Started', 'AcresBurned','StructuresDamaged', 'StructuresDestroyed'], keep='first', inplace=False, ignore_index=False).reset_index().drop(columns=['index'])\n\"\"\"\n## 1. Trend of wildfire in California from 2013 to 2019\n\"\"\"\nwf['StartedMonth'] = [x.month for x in wf['Started']]\nmonthly_count = wf.groupby([\"ArchiveYear\",\"StartedMonth\"])['AcresBurned'].count().reset_index()\nmonthly_count.rename(columns={\"AcresBurned\": \"WildfireCount\"}, inplace=True)\nmonthly_count\nfig = px.line(monthly_count, x = \"StartedMonth\", y = \"WildfireCount\", color = \"ArchiveYear\", height=600, title='Widefire Count in Each Month, 2013-2019')\nfig.show()\n\"\"\"\n**Observation**:  \n\nThe line plot shows that California's wildfires usually occur in the summer (June to August). It might be caused by the dryness and high temperature in summer.  \nIn 2017, 111 wildfires occurred in July, and this is the highest monthly count from 2013 to 2019.\n\"\"\"\n\"\"\"\n## 2. Trend of wildfire damage in California from 2013 to 2019\n\"\"\"\nyearly_wf = wf.groupby(\"ArchiveYear\").sum()[['AcresBurned', 'MajorIncident', 'Injuries', 'StructuresDamaged', 'StructuresDestroyed', 'StructuresThreatened']]\nyearly_wf\n\"\"\"\n**Observation**:  \n\nThe wildfires archived in 2018 burned the most acres of land and destroyed the most number of structures. This means those fires are more closed to the town.  \nIn 2013 and 2014, there are more injuries than in other years. And 2017 has the highest count of the major incidents.\n\"\"\"\n\"\"\"\n## 3. Spatial distribution of wildfire in California from 2013 to 2019\n\"\"\"\nm = folium.Map(location=[37.160317,-120.621407], tiles=\"Stamen Terrain\", zoom_start=6)\nfor idx in range(len(wf)):\n    folium.Circle(\n        location=[wf.loc[idx,'Latitude'], wf.loc[idx,'Longitude']],\n        radius=math.sqrt(float(wf.loc[idx,'AcresBurned'])*4047\/3.14),\n        popup=str(wf.loc[idx,'Name'])+', '+str(wf.loc[idx,'ArchiveYear']),\n        color=\"crimson\",\n        fill=True,\n        fill_color=\"crimson\",\n    ).add_to(m)\n\ntitle_html = '''\n             <h3 align=\"center\" style=\"font-size:20px\"><b>Spatial distribution of All Recorded Wildfire<\/b><\/h3>\n             '''\nm.get_root().html.add_child(folium.Element(title_html))    \n    \nm\n\"\"\"\n**Observation**:   \nThe wildfires occur in the mountains or other areas covered by vegetation, and most of them are small fires.\n\"\"\"\n\"\"\"\n## 4. Wordcloud of wildfire statement from the fire department\n\"\"\"\ndef extract_words(text):\n    text = text.replace('nan', '').replace('\\r', '').replace('\\n', '').replace('<p>', '').replace('  ', '')\n    text = re.sub(r'<a.*<\/a>', \"\", text)\n    words = text.split(' ')\n\n    for i in range(len(words)):\n        if len(words[i]) > 0:\n            if words[i][-1] in ['.', ',', ':']:\n                words[i] = words[i][:-1]\n        words[i] = words[i].lower()\n        \n    return words\nwords = wf['ConditionStatement'].astype(str).apply(extract_words)\n\nword_list = []\nfor row in words:\n    word_list += row\n\nword_count = Counter(word_list)\n\n# Create stopword list:\nstopwords = set(STOPWORDS)\nstopwords.update([\"fire\", \"will\", \"continue\", \"area\", \"firefighters\"])\n\nfor key in stopwords:\n    word_count.pop(key, None)\nword_count.pop('', None)\n\n\nwc = WordCloud(background_color=\"white\",max_words=500,relative_scaling=0.5, normalize_plurals=False).generate_from_frequencies(word_count)\n# plt.title(tag_sentiment[i] + ' tags related to ' + idx)\nplt.figure(figsize=(16, 12))\nplt.imshow(wc)\nplt.axis('off')\nplt.show()\n\"\"\"\n**Observation**:  \n\nThe word cloud is generated using the condition statement of the wildfire report. The top 3 most mentioned words are: \"containment\", \"crews\", and \"lines\".\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '58de86a0498d31'}"}
{"id":"74423","text":"\"\"\"\n<h1><center>HuBMAP - Hacking the Kidney<\/h1>\n\"\"\"\n\"\"\"\n<h3><center>Let\u2019s understand the problem statement first<\/h3>\n\nThe aim of this competition is to develop a segmentation problem to identify \u2018Glomerulus\u2019 in the kidney. For this we have to train a segmentation model that takes PAS kidney image input and identify the segments of glomeruli FTU in the PAS-stained microscopy data.\nFor this task, we are given historical images of kidney and annotation information representing the glomerular segmentation.\nI believe I used some terminologies, that are confusing. So, lets understand these terms and get some Domain Knowledge.\n\n\"\"\"\n\"\"\"\n<h3><center>Domain Knowledge<\/h3>\n\"\"\"\n\"\"\"\n<h4>1. What is Glomerulus?<\/h4>\nFirst, we understand what \u2018Nephron\u2019 is. The nephron is the microscopic structural and functional unit of the kidney. It is composed of a renal corpuscle and a renal tubule. The renal corpuscle consists of a tuft of capillaries called a glomerulus and an encompassing Bowman's capsule. \nGlomerulus a cluster of nerve endings, spores, or small blood vessels, in particular a cluster of capillaries around the end of a kidney tubule, where waste products are filtered from the blood.\n\n\n\nIn short, each nephron in your kidneys has a microscopic filter, called a glomerulus that is constantly filtering your blood.\n\n\"\"\"\n\"\"\"\n<h4>2. PAS (Periodic acid-Schiff) Stain Microscopy<\/h4>\nPAS is a histology stain that detects complex sugars in tissue sections. Periodic acid is used to break specific bonds within these sugars. The resulting aldehydes react with the Schiff reagent to produce the purple-magenta color exhibited by these images. Glomeruli can be observed as the circular areas of dark stain.\n\"\"\"\n\"\"\"\n<h4>3.\tFTU (Functional Tissue Unit)<\/h4>\nFTU or functional tissue unit, is a three-dimensional, maximally connected, block of cells centered around a capillary, such that each cell in this block is within diffusion distance from any other cell in the same block.\n\"\"\"\n\"\"\"\n<h3><center>Let\u2019s understand the DATA now,<\/h3>\nThe Dataset is comprised of very large TIFF files (TIFF is described later in the notebook).\n\n\u2022\tThe training set has 8 files.\n\n\u2022\tThe public test set has 5 files.\n\n\u2022\tThe private test set is larger than the public test set. I suppose there will be 7 files.\n\nThe train set includes annotations in both RLE-encoded (RLE is explained later in the notebook) and unencoded (JSON) forms. The annotations denote segmentations of glomeruli.\nBoth training and public test sets include anatomical structure segmentations. I suppose this can be used for pretraining.\nJSON files are structured as follows\n\n\u2022\tA type (Feature) and object type id (PathAnnotationObject). Note that these fields are the same between all files and do not offer signal.\n\n\u2022\tA geometry containing a Polygon with coordinates for the feature's enclosing volume\n\n\u2022\tAdditional properties, including the name and color of the feature in the image.\n\n\u2022\tThe IsLocked field is the same across file types (locked in glomerulus, unlocked for anatomical structure) and is not signal bearing.\n\"\"\"\n\"\"\"\n<h4>TIFF File Format<\/h4>\nTag Image File Format, abbreviated TIFF or TIF, is a computer file format for storing raster graphics images, popular among graphic artists, the publishing industry, and photographers. TIFF is a flexible, adaptable file format for handling images and data within a single file, by including the header tags (size, definition, image-data arrangement, applied image compression) defining the image's geometry.\n\"\"\"\n\"\"\"\n<h4>RLE<\/h4>\nThe masks provided in the train.csv is in Running Length Encoding format. This encoding comes in pairs of pixel values as follows:\n\n1.\tThe starting pixel.\n2.\tNumber of pixels from the starting pixel.\n\nSo, to specify 10 pixels starting from pixel number 200 would be written as: 200 10\n\"\"\"\n\"\"\"\n<h3><center>Evaluation Metric<\/h3>\n\"\"\"\n\"\"\"\n<h4>Dice Coefficient<\/h4>\nDice coefficient is a statistical tool which measures the similarity between two sets of data. This index has become arguably the most broadly used tool in the validation of image segmentation algorithms created with AI, but it is a much more general concept which can be applied sets of data for a variety of applications including NLP.\nThe Dice coefficient can be used to compare the pixel-wise agreement between a predicted segmentation and its corresponding ground truth.\n\"\"\"\n\"\"\"\n<h4>Jaccard Score<\/h4>\nThe Jaccard similarity index (sometimes called the Jaccard similarity coefficient) compares members for two sets to see which members are shared and which are distinct. It\u2019s a measure of similarity for the two sets of data, with a range from 0% to 100%. The higher the percentage, the more similar the two populations. Although it\u2019s easy to interpret, it is extremely sensitive to small samples sizes and may give erroneous results, especially with very small samples or data sets with missing observations.\nThe formula to find the Index is:\nJaccard Index = (the number in both sets) \/ (the number in either set) * 100\n\"\"\"\n\"\"\"\n<h4>Relation between Dice Coefficient and Jaccard Score<\/h4>\n<h4><center>J=D\/2-D<\/h4>\n\n\"\"\"\n\"\"\"\n<h3><center>Let\u2019s do the EDA now,<\/h3>\n\"\"\"\n# Libraries\nimport cv2\nimport datetime\nimport gc\nimport glob\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport skimage.morphology\nimport sys\nimport tensorflow as tf\nimport tifffile\n#Parameters\nbase_path = '..\/input\/hubmap-kidney-segmentation'\n\nplot_full_image = True\n\n# Number of glomeruli to display for each image\nnum_glom_display = 5\n\n# Number of glomberuli to save as tiff files.\nnum_glom_save = 5\n\nglob_scale = 0.25\n# Utility Functions\ndef rle_to_image(rle_mask, image_shape):\n    \"\"\"\n    Converts an rle string to an image represented as a numpy array.\n    Reference: https:\/\/www.kaggle.com\/paulorzp\/rle-functions-run-lenght-encode-decode\n\n    :param rle_mask: string with rle mask.\n    :param image_shape: (width, height) of array to return\n    :return: Image as a numpy array. 1 = mask, 0 = background.\n    \"\"\"\n\n    # Processing\n    s = rle_mask.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    image = np.zeros(image_shape[0] * image_shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        image[lo:hi] = 1\n\n    return image.reshape(image_shape).T\n\"\"\"\n<h4>File Structure<\/h4>\nThe files in the root of the dataset are shown below. The dataset consists of 2 directories that contain training and test images and 3 csv-files with additional information about the images.\n\"\"\"\n#Directory Contents\nprint('\\n'.join(os.listdir(base_path)))\n# Training Images\ntrain_files = sorted(glob.glob(os.path.join(base_path, 'train\/*.tiff')))\nprint(f'Number of training images: {len(train_files)}')\nprint('\\n'.join(train_files))\n#Test Images\ntest_files = sorted(glob.glob(os.path.join(base_path, 'test\/*.tiff')))\nprint(f'Number of test images: {len(test_files)}')\nprint('\\n'.join(test_files))\n#Train CSV\n#The masks indicating a glomeruli FTUs are stored in rle format in the train.csv for each training image id.\ndf_train = pd.read_csv(os.path.join(base_path, 'train.csv'))\ndisplay(df_train)\n# Sample_Submission.csv\n#The sample_submission.csv files shows the format of the submissions files consisting of the test image id and an rle encoded masks.\ndf_submission = pd.read_csv(os.path.join(base_path,'sample_submission.csv'))\ndisplay(df_submission)\n# Paitient Data\n#HuBMAP-20-dataset_information.csv contains additional information about each image such as image size and anonymized patient data.\ndf_info = pd.read_csv(os.path.join(base_path,'HuBMAP-20-dataset_information.csv'))\ndisplay(df_info)\n\"\"\"\n<h3><center>Training Image Analysis<\/h3>\n<h4>Width and Height Distribution<\/h4>\n\nThe training images do not have consistent dimensions. This has to be corrected when loading the images. They have on of the following shapes:\n\n[height, width, channel]\n    \n[channel, height, width]\n\n[1, 1, channel, height, width]\n\"\"\"\nfor f in train_files + test_files:\n    image = tifffile.imread(f)\n    print(f'Image {f} shape: {image.shape}', flush=True)\n    del image\n    gc.collect()\n#The size of the images varies greatly as well.\nplt.scatter(df_info['width_pixels'], df_info['height_pixels'])\nplt.title('Image Height and Width')\nplt.xlabel('Width')\nplt.ylabel('Height')\nplt.xlim(0, df_info['width_pixels'].max() * 1.1)\nplt.ylim(0, df_info['height_pixels'].max() * 1.1)\nplt.grid()\n\"\"\"\n<h4>Image Utilitity Functions<\/h4>\n\"\"\"\ndef overlay_image_mask(image, mask, mask_color=(0,255,0), alpha=1.0):\n    im_f= image.astype(np.float32)\n#     if mask.ndim == 2:\n#         mask = np.expand_dims(mask,-1)        \n    mask_col = np.expand_dims(np.array(mask_color)\/255.0, axis=(0,1))\n    return (im_f + alpha * mask * (np.mean(0.8 * im_f + 0.2 * 255, axis=2, keepdims=True) * mask_col - im_f)).astype(np.uint8)\n\n\ndef overlay_image_mask_original(image, mask, mask_color=(0,255,0), alpha=1.0):\n    return  np.concatenate((image, overlay_image_mask(image, mask)), axis=1)\n\ndef get_image_id(image_file):\n    return os.path.splitext(os.path.split(image_file)[1])[0]\n\n\ndef read_image(image_file, scale=1.0):\n    image = tifffile.imread(image_file).squeeze()\n    if image.shape[0] == 3:\n        image = np.transpose(image, (1,2,0))\n    \n    orig_shape = image.shape\n    if scale != 1.0:\n        image = cv2.resize(image, (0,0), fx=scale, fy=scale)\n    return image, orig_shape\n\n\ndef read_mask(image_file, image_shape, scale=1.0):\n    image_id = get_image_id(image_file)\n    train_info = df_train.loc[df_train['id'] == image_id]\n    rle = train_info['encoding'].values[0] if len(train_info) > 0 else None\n    if rle is not None:\n        mask = rle_to_image(rle, (image_shape[1], image_shape[0]))\n        if scale != 1.0:\n            mask = cv2.resize(mask, (0,0), fx=scale, fy=scale)\n        return np.expand_dims(mask,-1)\n    else:\n        return None        \n\n    \ndef read_image_mask(image_file, scale=1.0):\n    image, image_shape = read_image(image_file, scale)\n    mask = read_mask(image_file, image_shape, scale)\n    return image, mask\n\n\ndef get_tile(image, mask, x, y, tile_size, scale=1.0):\n    x = round(x * scale)\n    y = round(y * scale)\n    size = int(round(tile_size \/ 2 * scale))\n    image_s = image[y-size:y+size, x-size:x+size, :] \n    mask_s = mask[y-size:y+size, x-size:x+size, :]\n    return image_s, mask_s\n\n\ndef get_particles(mask, scale=1.0):\n    num, labels, stats, centroids = cv2.connectedComponentsWithStats(mask)\n    df_particles = pd.DataFrame(dict(zip(['x','y','left','top','width','height','area'],\n                               [(centroids[1:,0]) \/ scale,\n                                (centroids[1:,1]) \/ scale,\n                                (stats[1:,cv2.CC_STAT_LEFT]) \/ scale,\n                                (stats[1:,cv2.CC_STAT_TOP]) \/ scale,\n                                (stats[1:,cv2.CC_STAT_WIDTH]) \/ scale,\n                                (stats[1:,cv2.CC_STAT_HEIGHT]) \/ scale,\n                                (stats[1:,cv2.CC_STAT_AREA]) \/ (scale * scale)])))\n    df_particles.sort_values(['x','y'], inplace=True, ignore_index=True)\n    df_particles['no'] = range(len(df_particles))\n    return df_particles\n\n\ndef analyze_image(image_file):\n    image_id = get_image_id(image_file)\n    image, image_shape = read_image(image_file, glob_scale)\n    mask = read_mask(image_file, image_shape, glob_scale)\n\n    mask_full = read_mask(image_file, image_shape, scale=1.0)\n    df_glom = get_particles(mask_full, scale=1.0)\n    df_glom['id'] = image_id\n    del mask_full\n    gc.collect()\n    \n    info = df_info[df_info['image_file'] == f'{image_id}.tiff']\n    print(f'Image ID:        {image_id:}')\n    print(f'Image Size:      {info[\"width_pixels\"].values[0]} x {info[\"height_pixels\"].values[0]}')\n    print(f'Patient No:      {info[\"patient_number\"].values[0]}')\n    print(f'Sex:             {info[\"sex\"].values[0]}')\n    print(f'Age:             {info[\"age\"].values[0]}')\n    print(f'Race:            {info[\"race\"].values[0]}')\n    print(f'Height:          {info[\"height_centimeters\"].values[0]} cm')\n    print(f'Weight:          {info[\"weight_kilograms\"].values[0]} kg')\n    print(f'BMI:             {info[\"bmi_kg\/m^2\"].values[0]} kg\/m^2')\n    print(f'Laterality:      {info[\"laterality\"].values[0]}')\n    print(f'Percent Cortex:  {info[\"percent_cortex\"].values[0]} %')\n    print(f'Percent Medulla: {info[\"percent_medulla\"].values[0]} %')\n    \n    # Plot full image\n    if plot_full_image:\n        scale = 0.1\n        image_small = cv2.resize(image, (0,0), fx=scale, fy=scale)\n        mask_small = cv2.resize(mask, (0,0), fx=scale, fy=scale)\n        mask_small = np.expand_dims(mask_small,-1) \n    \n        plt.figure(figsize=(16, 16))\n        plt.imshow(overlay_image_mask(image_small, mask_small))\n        plt.axis('off')\n\n    # Plot glomeruli images\n    fig_cols = 5\n    fig_rows = int(math.ceil(num_glom_display\/fig_cols))\n    plt.figure(figsize=(4 * fig_cols, 4 * fig_rows))\n    if num_glom_save > 0 and not os.path.exists(image_id):\n        os.mkdir(image_id)\n    for i in range(min(max(num_glom_display, num_glom_save), len(df_glom))):\n        image_s, mask_s = get_tile(image,mask, df_glom['x'][i], df_glom['y'][i], 1000, scale=glob_scale)\n        ovl = overlay_image_mask(image_s, mask_s)\n        if i < num_glom_display:\n            plt.subplot(fig_rows, fig_cols, i+1)\n            plt.imshow(ovl)\n            plt.axis('off')\n        if i < num_glom_save:\n            cv2.imwrite(f'{image_id}_{i:03}.png', cv2.cvtColor(ovl, cv2.COLOR_RGB2BGR))    \n    \n    del image, mask\n    gc.collect()\n    return df_glom\n\n\ndef plot_glom(df, image_id, glom_no):\n    image, mask = read_image_mask(os.path.join(base_path, f'train\/{image_id}.tiff'), scale=glob_scale)\n    glom = df.loc[(df['id'] == image_id) & (df['no'] == glom_no)]\n    im, ma = get_tile(image, mask, glom['x'].iloc[0], glom['y'].iloc[0], 1000, scale=glob_scale)\n    del image, mask\n    gc.collect()\n    plt.figure(figsize=(16,8))\n    plt.imshow(overlay_image_mask_original(im, ma))\n    plt.title(f'Image: {image_id}, Glomeruli No: {glom_no}, Area: {glom[\"area\"].iloc[0]}')\n\"\"\"\n<h3>Training Images With Glomerulis<\/h3>\n\"\"\"\ndf_glom = pd.DataFrame()\ndf_glom = df_glom.append(analyze_image(train_files[0]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[1]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[2]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[3]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[4]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[5]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[6]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[7]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[8]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[9]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[10]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[11]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[12]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[13]), ignore_index=True)\ndf_glom = df_glom.append(analyze_image(train_files[14]), ignore_index=True)\n\"\"\"\n<h3>Glomerulis<\/h3>\n\"\"\"\n\"\"\"\n<h4>Basic Statistics<\/h4>\n\"\"\"\ndf_glom.to_csv('glomeruli.csv')\ndisplay(df_glom)\ndf_glom.describe()\n\"\"\"\n<h4>Glomerulis Per Image<\/h4>\n\"\"\"\ng = df_glom.groupby('id')\nplt.bar(g.size().index, g.size().values)\nplt.title('Number of Glomerulis in Image')\nplt.xticks(rotation=90)\nplt.grid()\n\"\"\"\n<h4>Glomeruli Width, Height and Area Distribution<\/h4>\n\"\"\"\nplt.figure(figsize=(20,5))\nplt.subplot(1,3,1)\nplt.hist(df_glom['width'], bins=40, density=True)\nplt.title('Width Distribution')\nplt.grid()\nplt.subplot(1,3,2)\nplt.hist(df_glom['height'], bins=40, density=True)\nplt.title('Height Distribution')\nplt.grid()\nplt.subplot(1,3,3)\nplt.hist(df_glom['area'], bins=40, density=True)\nplt.title('Area Distribution')\nplt.grid()\n\"\"\"\n<h4>Glomerulis by Size<\/h4>\n\"\"\"\ndf_glom.sort_values('area', inplace=True)\ndf_glom\n\"\"\"\n<h4>Five Smallest Glomerulis<\/h4>\n\"\"\"\nfor i in range(5):\n    plot_glom(df_glom, df_glom['id'].iloc[i], df_glom['no'].iloc[i])\n\"\"\"\n<h4>Five Largest Glomerulis<\/h4>\n\"\"\"\nfor i in range(len(df_glom)-5, len(df_glom)):\n    plot_glom(df_glom, df_glom['id'].iloc[i], df_glom['no'].iloc[i])\n\"\"\"\n<h3><center>SUB EffUNet5 + TPU EfficientUNet 512x512<\/h3>\n\"\"\"\n\"\"\"\nIn the code below I will try to use TPU EfficientUNet 512x512 with freeze-pretrained SUB EffUNet5. This will help to improve the existing algorithms used to detect functional tissue units (FTUs) across different tissue preparation pipelines.\n\"\"\"\nmod_path = '\/kaggle\/input\/hubmap-tf-with-tpu-efficientunet-512x512-train\/'\nimport yaml\nimport pprint\nwith open(mod_path+'params.yaml') as file:\n    P = yaml.load(file, Loader=yaml.FullLoader)\n    pprint.pprint(P)\n    \nTHRESHOLD = 0.4\nWINDOW = 1024\nMIN_OVERLAP = 300\nNEW_SIZE = P['DIM']\n\nSUBMISSION_MODE = 'PUBLIC_TFREC' \n# 'PUBLIC_TFREC' = use created tfrecords for public test set with MIN_OVERLAP = 300 tiling 1024-512, ignore other (private test) data\n# 'FULL' do not use tfrecords, just full submission \n\nCHECKSUM = True # compute mask sum for each image\n# METRICS\n\nimport json\n\nwith open(mod_path + 'metrics.json') as json_file:\n    M = json.load(json_file)\nprint('Model run datetime: '+M['datetime'])\nprint('OOF val_dice_coe: ' + str(M['oof_dice_coe']))\n! pip install ..\/input\/kerasapplications\/keras-team-keras-applications-3b180cb -f .\/ --no-index -q\n! pip install ..\/input\/efficientnet\/efficientnet-1.1.0\/ -f .\/ --no-index -q\nimport numpy as np\nimport pandas as pd\nimport os\nimport glob\nimport gc\n\nimport rasterio\nfrom rasterio.windows import Window\n\nimport pathlib\nfrom tqdm.notebook import tqdm\nimport cv2\n\nimport tensorflow as tf\nimport efficientnet as efn\nimport efficientnet.tfkeras\n\nimport os, glob, gc\nimport json\n\nosj = os.path.join\ndef rle_encode_less_memory(img):\n    pixels = img.T.flatten()\n    pixels[0] = 0\n    pixels[-1] = 0\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\ndef make_grid(shape, window=256, min_overlap=32):\n    \"\"\"\n        Return Array of size (N,4), where N - number of tiles,\n        2nd axis represente slices: x1,x2,y1,y2 \n    \"\"\"\n    x, y = shape\n    nx = x \/\/ (window - min_overlap) + 1\n    x1 = np.linspace(0, x, num=nx, endpoint=False, dtype=np.int64)\n    x1[-1] = x - window\n    x2 = (x1 + window).clip(0, x)\n    ny = y \/\/ (window - min_overlap) + 1\n    y1 = np.linspace(0, y, num=ny, endpoint=False, dtype=np.int64)\n    y1[-1] = y - window\n    y2 = (y1 + window).clip(0, y)\n    slices = np.zeros((nx,ny, 4), dtype=np.int64)\n    \n    for i in range(nx):\n        for j in range(ny):\n            slices[i,j] = x1[i], x2[i], y1[j], y2[j]    \n    return slices.reshape(nx*ny,4)\n\ndef global_shift_mask(maskpred1, y_shift, x_shift):\n    \"\"\"\n    applies a global shift to a mask by \n    padding one side and cropping from the other\n    \"\"\"\n    if y_shift < 0 and x_shift >=0:\n        maskpred2 = np.pad(maskpred1, \n                           [(0,abs(y_shift)), (abs(x_shift), 0)], \n                           mode='constant', constant_values=0)\n        maskpred3 = maskpred2[abs(y_shift):, :maskpred1.shape[1]]\n    elif y_shift >=0 and x_shift <0:\n        maskpred2 = np.pad(maskpred1, \n                           [(abs(y_shift),0), (0, abs(x_shift))], \n                           mode='constant', constant_values=0)\n        maskpred3 = maskpred2[:maskpred1.shape[0], abs(x_shift):]\n    elif y_shift >=0 and x_shift >=0:\n        maskpred2 = np.pad(maskpred1,\n                           [(abs(y_shift),0), (abs(x_shift), 0)], \n                           mode='constant', constant_values=0)\n        maskpred3 = maskpred2[:maskpred1.shape[0], :maskpred1.shape[1]]\n    elif y_shift < 0 and x_shift < 0:\n        maskpred2 = np.pad(maskpred1, \n                           [(0, abs(y_shift)), (0, abs(x_shift))], \n                           mode='constant', constant_values=0)\n        maskpred3 = maskpred2[abs(y_shift):, abs(x_shift):]\n    return maskpred3\n##MODEL\nidentity = rasterio.Affine(1, 0, 0, 0, 1, 0)\nfold_models_1 = []\nfor fold_model_path in glob.glob(mod_path+'*.h5'):\n    fold_models_1.append(tf.keras.models.load_model(fold_model_path,compile = False))\nprint(len(fold_models_1))\nAUTO = tf.data.experimental.AUTOTUNE\nimage_feature = {\n    'image': tf.io.FixedLenFeature([], tf.string),\n    'x1': tf.io.FixedLenFeature([], tf.int64),\n    'y1': tf.io.FixedLenFeature([], tf.int64)\n}\ndef _parse_image(example_proto):\n    example = tf.io.parse_single_example(example_proto, image_feature)\n    image = tf.reshape( tf.io.decode_raw(example['image'],out_type=np.dtype('uint8')), (P['DIM'],P['DIM'], 3))\n    return image, example['x1'], example['y1']\n\ndef load_dataset(filenames, ordered=True):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(_parse_image)\n    return dataset\n\ndef get_dataset(FILENAME):\n    dataset = load_dataset(FILENAME)\n    dataset  = dataset.batch(64)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\ndebug = True # True False\nn_debug_images = 1 if debug else 1000000000\nn_debug_slices = 20 if debug else 1000000000\n\n# whether to run prediction when committing. WILL RUN predictions during submission in any case\ndo_predict = False  if not debug else True\n\nmodels_dir = '..\/input\/hubmap-models-cv-08848-pl-0847'\nmodel_filepaths = [ os.path.join(models_dir, f\"model-fold-{i}.h5\") for i in range(4)]\n\nassert len(model_filepaths)==len(np.unique(model_filepaths))\n#folds_to_predict = [i for (i, fn) in enumerate(model_filepaths) if os.path.isfile(fn)]\nmodel_dirnames = [os.path.dirname(filepath) for filepath in model_filepaths]\n\n#check_order = [fn.split('.')[-2].split('-')[-1] == i for (i,fn) in enumerate(model_filepaths) if fn.strip()!='']\n#assert np.sum(check_order)==0, 'models should be in folds order or empty string'\n\nimport yaml\nimport pprint\nwith open(osj(model_dirnames[0],'params.yaml')) as file:\n    P = yaml.load(file, Loader=yaml.FullLoader)\n    pprint.pprint(P)\n\nTHRESHOLD = 0.3\nWINDOW = 1024\nMIN_OVERLAP = 32\nNEW_SIZE = P['DIM']\n\nassert sum([not os.path.isfile(path_) for path_ in model_filepaths]) == 0\nprint(\"\\n Number of models:: {}\".format(len(model_filepaths)))\nave_score = 0\nfor i, m_path in enumerate(model_filepaths):\n    fold_ = int(m_path.split('.')[-2].split('-')[-1])\n    with open(osj(model_dirnames[i],'metrics.json')) as json_file:\n        M = json.load(json_file)\n    print(f\"\\n ----------- \\nModel {model_dirnames[i].split('\/')[-1]}\" +\n          '\\nval_dice_coe: '+ str(round(M['val_dice_coe'][fold_], 5)) +\n          '\\tval_loss: ' + str(round(M['val_loss'][fold_], 5)) +\n          '\\tval_accuracy: '+ str(round(M['val_accuracy'][fold_], 5))\n          )\n\n\n\nfor model_group in np.unique(model_dirnames):\n    with open(osj(model_group,'metrics.json')) as json_file:\n        M = json.load(json_file)\n        ave_dice = np.mean(M['val_dice_coe']) \n    ave_loss = np.mean(M['val_loss'])  # \/len(folds_to_predict)\n    ave_accuracy = np.mean(M['val_accuracy'])\n    print(f\"\\n ============ MODEL GROUP {model_group} ==============\")\n    print(\" ------------ \\nAVERAGE DICE SCORE = {}\".format(round(ave_dice, 5)))\n    print(\" ------------ \\nAVERAGE VALIDATION LOSS = {}\".format(round(ave_loss, 5)))\n    print(\" ------------ \\nAVERAGE VALIDATION ACCURACY = {}\".format(round(ave_accuracy, 5)))\n%%time\nif do_predict:\n    identity = rasterio.Affine(1, 0, 0, 0, 1, 0)\n    fold_models_2 = []\n    \n    for fold_model_path in model_filepaths:\n        fold_models_2.append(tf.keras.models.load_model(fold_model_path,compile = False))\n    print(len(fold_models_2))\n\"\"\"\n<h3>References<\/h3>\n\nhttps:\/\/www.kaggle.com\/kwk100\/hubmap-exploratory-data-analysis-eda\n\nhttps:\/\/www.kaggle.com\/roydatascience\/hubmap-sub-effunet5-tpu-efficientunet-512x512\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '88e04260f9977b'}"}
{"id":"46944","text":"import torch\nfrom torch.utils import data\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom keras.preprocessing import sequence\nimport numpy as np # linear algebra\n# truncated sentence by lens percentile of batch\nPERCENTILE = 80\n# truncated sentence by a constant\nMAX_LEN = 4\nBATCH_SIZE = 4\nclass MyDataset(data.Dataset):\n    \n    def __init__(self, text, lens, y=None):\n        self.text = text\n        self.y = y\n        self.lens = lens\n    \n    def __len__(self):\n        return len(self.lens)\n    \n    def __getitem__(self, index):\n        if self.y is None:\n            return self.text[index], self.lens[index]\n        else:\n            return self.text[index], self.lens[index], self.y[index]\n    \n\ndef collate_fn(batch):\n    \"\"\"\n    batch = [dataset[i] for i in N]\n    \"\"\"\n    size = len(batch[0])\n    if size == 3:\n        texts, lens, y = zip(*batch)\n    else:\n        texts, lens = zip(*batch)\n    lens = np.array(lens)\n    sort_idx = np.argsort(-1 * lens)\n    reverse_idx = np.argsort(sort_idx)\n    max_len = min(int(np.percentile(lens, PERCENTILE)), MAX_LEN)\n    \n    lens = np.clip(lens, 0, max_len)[sort_idx]\n    texts = torch.tensor(sequence.pad_sequences(texts, maxlen=max_len)[sort_idx], dtype=torch.long)\n    if size == 3:\n        return texts, lens, reverse_idx, torch.tensor(y, dtype=torch.float32)\n    else:\n        return texts, lens, reverse_idx\n\n\ndef build_data_loader(texts, lens, y=None, batch_size=BATCH_SIZE):\n    dset = MyDataset(texts, lens, y)\n    dloader = data.DataLoader(dset, batch_size=batch_size, shuffle=False, collate_fn=collate_fn)\n    return dloader\n\"\"\"\n## Test\n\"\"\"\nseqs = [[1,2,3,3,4,5,6,7], [1,2,3], [2,4,1,2,3], [1,2,4,1]]\nlens = [len(i) for i in seqs]\n\ndata_loader = build_data_loader(seqs, lens)\n\nfor batch in data_loader:\n    seq_batch, lens_batch, reverse_idx_batch = batch\n    break\nprint(f'original seqs:')\nprint(seqs)\nprint(f'batch seqs, already sort by lens, and padding dynamic in batch:')\nprint(seq_batch.numpy().tolist())\nprint(f'reverse batch seqs:')\nprint(seq_batch[reverse_idx_batch].numpy().tolist())\n\"\"\"\n## pack_padded_seq\n\"\"\"\npack_padded_sequence(seq_batch, lens_batch, batch_first=True)","meta":"{'source': 'AI4Code', 'id': '567ce41192156c'}"}
{"id":"117207","text":"\"\"\"\n# Here we import all the neccesary libraries\n\"\"\"\nimport os\nimport json\n\nimport numpy as np\nimport pandas as pd\nimport keras\nfrom keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom keras.utils.vis_utils import plot_model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score\n\"\"\"\n## Loading the 32x32 dataset\n\"\"\"\n# The data, split between train and test sets:\nx_train = np.load('..\/input\/reducing-image-sizes-to-32x32\/X_train.npy')\nx_test = np.load('..\/input\/reducing-image-sizes-to-32x32\/X_test.npy')\ny_train = np.load('..\/input\/reducing-image-sizes-to-32x32\/y_train.npy')\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train \/= 255.\nx_test \/= 255.\n\"\"\"\n## Create Callback for F1 score\n\"\"\"\nclass Metrics(Callback):\n    def on_train_begin(self, logs={}):\n        self.val_f1s = []\n        self.val_recalls = []\n        self.val_precisions = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_pred = self.model.predict(X_val)\n\n        y_pred_cat = keras.utils.to_categorical(\n            y_pred.argmax(axis=1),\n            num_classes=14\n        )\n\n        _val_f1 = f1_score(y_val, y_pred_cat, average='macro')\n        _val_recall = recall_score(y_val, y_pred_cat, average='macro')\n        _val_precision = precision_score(y_val, y_pred_cat, average='macro')\n\n        self.val_f1s.append(_val_f1)\n        self.val_recalls.append(_val_recall)\n        self.val_precisions.append(_val_precision)\n\n        print((f\"val_f1: {_val_f1:.4f}\"\n               f\" \u2014 val_precision: {_val_precision:.4f}\"\n               f\" \u2014 val_recall: {_val_recall:.4f}\"))\n\n        return\n\nf1_metrics = Metrics()\n\"\"\"\n## Create the Model\n\"\"\"\ndensenet = DenseNet121(\n    weights='..\/input\/densenet-keras\/DenseNet-BC-121-32-no-top.h5',\n    include_top=False,\n    input_shape=(32,32,3)\n)\n\nmodel = Sequential()\nmodel.add(densenet)\nmodel.add(layers.GlobalAveragePooling2D())\nmodel.add(Dropout(0.5))\nmodel.add(layers.Dense(14, activation='softmax'))\nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\nmodel.summary()\n\"\"\"\n# Callbacks\n\"\"\"\ncheckpoint = ModelCheckpoint(\n    'model.h5', \n    monitor='val_acc', \n    verbose=1, \n    save_best_only=True, \n    save_weights_only=False,\n    mode='auto'\n)\n\"\"\"\n# Compile The Model And Train\n\"\"\"\nmodel.compile(loss='categorical_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\nhistory = model.fit(\n    x=x_train,\n    y=y_train,\n    batch_size=256,\n    epochs=30,\n    callbacks=[checkpoint, f1_metrics],\n    validation_split=0.2\n)\n\"\"\"\n## Evaluation\n\"\"\"\nwith open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df['val_f1'] = f1_metrics.val_f1s\nhistory_df['val_precision'] = f1_metrics.val_precisions\nhistory_df['val_recall'] = f1_metrics.val_recalls\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['acc', 'val_acc']].plot()\nhistory_df[['val_f1', 'val_precision', 'val_recall']].plot()\n\"\"\"\n## Submission\n\"\"\"\nmodel.load_weights('model.h5')\ny_test = model.predict(x_test)\n\nsubmission_df = pd.read_csv('..\/input\/iwildcam-2019-fgvc6\/sample_submission.csv')\nsubmission_df['Predicted'] = y_test.argmax(axis=1)\n\nprint(submission_df.shape)\nsubmission_df.head()\n\nsubmission_df.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'd79e13d99f3829'}"}
{"id":"79793","text":"\"\"\"\n### Import the Necessary Libraries\n\"\"\"\n#import necessary libraries\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set_style('whitegrid')\n\nimport plotly.express as px\nimport statsmodels\n\nimport nltk\nfrom nltk.corpus import stopwords\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\n\nfrom nltk import sent_tokenize, word_tokenize\nfrom nltk.probability import FreqDist\n\nfrom bs4 import BeautifulSoup\n\nfrom wordcloud import WordCloud, STOPWORDS\n\nfrom tqdm import tqdm\n\nimport re\nimport os\nimport datetime\nfrom collections import Counter\n\nimport pickle\n\nimport warnings\nwarnings.filterwarnings(action = 'ignore')\n\"\"\"\n### Reading the Data from file\n\"\"\"\n#https:\/\/stackoverflow.com\/questions\/12468179\/unicodedecodeerror-utf8-codec-cant-decode-byte-0x9c\n\n#df = pd.read_csv('..\/input\/beer-data-analytics\/BeerProject.csv',encoding='latin-1') #this works too for Utf-8 encoding errors\ndf = pd.read_csv('..\/input\/beer-data-analytics\/BeerProject.csv',engine='python')\ndf.head(10)\n\"\"\"\n### Save a copy of the original data.\n\"\"\"\ndf_original = df.copy()\n\"\"\"\n### Exploratory Data Analysis (EDA)\n\"\"\"\n# Feature Names\n\ndf.columns\n#Shape of data\n\ndf.shape\n\"\"\"\n**Observations:**\n* Data set contains 528870 rows and 13 columns.\n\"\"\"\n\"\"\"\n### Check the data type and count of each feature\n\"\"\"\ndf.info()\n\"\"\"\n**Observations:**\n* Out of 13 features, we have 4 features ['beer_name', 'beer_style','review_profileName','review_text'] which are categorical \/text based features.\n* The remaining 9 features ['beer_ABV', 'beer_beerId', 'beer_brewerId', 'review_appearance', 'review_palette', 'review_overall', 'review_taste', 'review_aroma', 'review_time'] are numeric type.\n\n* From the given data we can briefly infer about the different features as follows:\n<ol>\n    <li>beer_ABV : Alcohol by volume content of a beer<\/li>\n    <li>beer_beerId : Unique ID for beer identification<\/li>\n    <li>beer_brewerId : Unique ID identifying the brewer<\/li>\n    <li>beer_name : Name of the beer<\/li>\n    <li>beer_style : Beer Category<\/li>\n    <li>review_appearance: Rating based on how the beer looks [Range : 1-5]<\/li>\n    <li>review_palatte : Rating based on how the beer interacts with the palate [Range : 1-5]<\/li>\n    <li>review_overall : Overall experience of the beer is combined in this rating [Range : 1-5]<\/li>\n    <li>review_taste : Rating based on how the beer actually tastes [Range : 1-5]<\/li>\n    <li>review_profileName: Reviewer\u2019s profile name \/ user ID<\/li>\n    <li>review_aroma : Rating based on how the beer smells [Range : 1-5]<\/li>\n    <li>review_text : Review comments\/observations in text format<\/li>\n    <li>review_time : Time in UNIX format when review was recorded<\/li>\n<\/ol>\n\"\"\"\n\"\"\"\n### Analyzing the Statistical significance of Numeric features\n\"\"\"\ndf.describe()\n\"\"\"\n**Observation :**\n* The IQR [Inter Quartile Range - that is between 25 % - 75 %] for the beer_ABV feature lies between the values 5.3 to 8.5 with a mean value of around 7.0. For beer_ABV data we can observe outliers values where the max value for the beer ABV contents is around 57.7 \n* Based on the count of the beer_ABV we can observe some Null values exists for these feature.\n* beer_brewerId - although it is a numeric value but it signifies a specific value of corresponding to each brewery name.\n* review_appearance, review_palette, review_taste, review_aroma and review_overall - are the key indicators of the various aspect related to the beer review. The IQR for these lies between 3.5 - 4.5. All these values are observed in the range of 1-5. All the values for these features are fairly spread across the mean value which is centered around 3.8.\n* review_time is a numeric feaure which records the UNIX time when the review was given.\n\"\"\"\n\"\"\"\n### Analyzing the Statistical significance of Non-Numeric(categorical)features\n\"\"\"\ndf.describe(exclude=np.number)\n\"\"\"\n**Observation :**\n* There are 18339 unique varieties of beers presented in this dataset. Most common beer observed is 'Sierra Nevada Celebration Ale'.\n* Most common beer_style is 'American IPA'.\n* We can see missing values exists for features - 'review_profileName' and 'review_text'.\n\"\"\"\n\"\"\"\n### Check for missig values across features\n\"\"\"\ndf.isna().sum()\n(df.isna().sum()\/len(df)) * 100\n\"\"\"\n**Observation :**\n* Missing values are present for 3 features - beer_ABV, review_profileName, review_text.\n* Around 3.8% of the values for the feature [beer_ABV] are missig, whereas the missing values for the  [review_profileName, review_text] features are minuscule and only around 0.02 % of the total.\n* Since missing data can reduce the statistical power and can produce biased estimates, leading to invalid conclusions, we will need to handle these missing values before building the model.\n\"\"\"\n\"\"\"\n### Handling the missing values for 'review_profileName' feature\n\"\"\"\n\n#since profile name (categorical feature) is merely a name of the person givng the review comments, \n#we will repace the missing values with the mode of the feature i.e. northyorksammy\n\ndf.loc[df['review_profileName'].isna(),'review_profileName'] = df['review_profileName'].fillna(df['review_profileName'].mode()[0])\n\ndf['review_profileName'].mode()[0]\ndf.review_profileName.isna().sum()\n\"\"\"\n### Handling the missing values for 'review_text' feature\n\"\"\"\n\n#since review text is the description of the user's specific comments about a particular beer, \n#we will repace the missing values for the reviw text with the most common review text i.e. '#NAME?'. \n\ndf.loc[df['review_text'].isna(),'review_text'] = df['review_text'].fillna(df['review_text'].mode()[0])\ndf['review_text'].mode()[0]\ndf.review_text.isna().sum()\n\"\"\"\n### Handling the missing values for 'beer_ABV' feature\n\n* 'beer_ABV' is a feature which describes about the volume of alcohol content in a beer. \n* Also we can observe that the beer_abv is related to beer name and we can identify it to be a unique value for a particular beer name. So we will identify the 'beer_ABV' by its 'beer_name' and replace the null values for the same.\n* After analyzing further we have observed that some 'beer_name' feature values have both null and non-null values for the correspoing the 'beer_ABV' feature. So we will need to handle the null replacement for 'beer_ABV' feature by considering the unique non-null value replacement here.\n\n\"\"\"\ndf.loc[:,['beer_name','beer_ABV']]\nprint('No. of unique values of beer names in the given data :',df.beer_name.nunique(dropna=False))\n\nprint('No. of unique values of beer abv in the given data :',df.beer_ABV.nunique(dropna=False))\n#create a dataframe for beer_ABV not null data\n\ndf_NNA = df.loc[df.beer_ABV.notna(),['beer_name','beer_ABV']].sort_values(by = 'beer_name', axis=0, ascending=True, \n                                                         inplace=False, kind='quicksort', na_position='last')\ndf_NNA\nprint('No. of unique values of beer names in the not_null data :',df_NNA.beer_name.nunique(dropna=False))\n\nprint('No. of unique values of beer abv in the not_null data :',df_NNA.beer_ABV.nunique(dropna=False))\n#get the mode of the 'beer_ABV' feature corresponding to the 'beer_name' feature\n\n# credits: https:\/\/stackoverflow.com\/questions\/15222754\/groupby-pandas-dataframe-and-select-most-common-value\nget_items = lambda vals : max(Counter(vals).items(), key = lambda x : x[1])[0] \nbeer_name_abv1 = df_NNA.groupby('beer_name')['beer_ABV'].agg(get_items).to_dict()\nbeer_name_abv1\n#replace the beer_ABV feture with the mode of the 'beer_ABV' feature corresponding to the beer_name\n\ndf.beer_ABV = df.beer_name.map(beer_name_abv1)\n#we can observe that around (20280-17920=)2360 the missing values in the beer_ABV feature got replaced by mode.\n\ndf.loc[df.beer_ABV.isna()].shape[0]\ndf.loc[df.beer_ABV.notna(),['beer_name','beer_ABV']]\n#now get the mode of the 'beer_ABV' feature corresponding to the 'beer_name' feature for the entire data\n\nget_items1 = lambda vals : max(Counter(vals).items(), key = lambda x :(x[0] != np.NaN) & x[1])[0] \nbeer_name_abv2 = df.groupby('beer_name')['beer_ABV'].agg(get_items1).to_dict()\nbeer_name_abv2\n#again replace the beer_ABV feture with the mode of the 'beer_ABV' feature corresponding to the beer_name\n\ndf.beer_ABV = df.beer_name.map(beer_name_abv2)\n#we can observe that there are still 17920 the missing values present in the beer_ABV feature\n#corresponding to the beer_name. \n\ndf.shape[0]\n\ndf_temp = df.loc[df.beer_ABV.isna(),['beer_name','beer_ABV']]\ndf_temp.groupby('beer_name')['beer_ABV'].count().to_dict()\n\"\"\"\n* **Since the beer_ABV values are not present at all for these  17920 records, we will drop these datapoints from our dataset for further analysis.**\n\"\"\"\ndf.dropna(inplace=True)\ndf\ndf.isna().sum()\n\"\"\"\n### Featurization - Adding new Feature for simplifying analysis\n\"\"\"\n#converting the 'review_time' from UNIX timestap to date_time format\n\ndf['review_time'] = df['review_time'].apply(lambda x :datetime.datetime.fromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S'))\ndf['year'] = df['review_time'].apply(lambda x : x[0:4]).astype(int)\n\"\"\"\n### Univariate and Bivariate analysis of different features\n\"\"\"\n#Beer Name\n\ndf['beer_name'].value_counts().head(50).plot.bar(figsize=(16,5),title= 'Most Poular Beers by Name')\n#Beer style\n\ndf['beer_style'].value_counts().head(50).plot.bar(figsize=(16,5),title= 'Most Poular Beers by Style')\n#Beer ABV\nplt.figure(figsize=(12,5))\nsns.distplot(df['beer_ABV'],bins = 50)\n##df['beer_ABV'].plot.density()  # this can be used alternatively but prefer sns.distplot\nplt.xlabel(\"Alcohol By Volume\")\nplt.show()\n\"\"\"\n**Observation :**\n* It can be infered that almost all of the majority data in the distribution of 'beer_ABV' is between 5-10 with long tail towards right.\n* Data is not perfectly normally distributed but good overall.\n\"\"\"\nplt.figure(figsize=(12,5))\ndf['beer_ABV'].plot.box(title= 'beer_ABV') \n##df.boxplot(column='beer_ABV') # this can be used alternatively \n#plt.tight_layout()\nplt.show()\n\"\"\"\n**Observation :**\n* We can see that the feature 'beer_ABV' has presence of outlier values. \n* Since the missing values are around than 3%, we will be replacing them with the unique value of the feature corrsponding to beer_name feature.\n\"\"\"\n#Review Overall\n\nplt.figure(figsize=(16,5))\n\nplt.subplot(121) \nsns.distplot(df.review_overall,bins=50)\n\nplt.subplot(122) \ndf['review_overall'].plot.box(title= 'review_overall') \n\nplt.tight_layout()\nplt.show()\n\"\"\"\n**Observation :**\n* It can be infered that the overall ratings are distributed in the range of 1 to 5 with most common rating is 4. \n* Data is not normally distributed, left-skewness is observed in the data.\n* Also the the IQR for the overall review feature is observed to be between 3.5-4.5.\n\"\"\"\n# Plotting Histograms to display the PDF of all the numeric type features in this dataset. \n\ndf.hist(bins = 15,figsize=(16,12))\nplt.show()\n# Number of Beers By Alcohol content\n\nd1 = df.groupby('beer_ABV')['beer_name'].count().sort_values(ascending=False).head(50)\n\nx = list(d1.index.values)\nfor i in range(len(x)):\n    x[i] = np.format_float_positional(np.float16(x[i]*1))\n\ny = d1.values\n\nplt.figure(figsize=(20,10))\n\nsns.barplot(x,y)\nplt.xlabel(\"Alcohol By Volume (%)\",color='blue')\nplt.ylabel(\"Number of Beers\",color='red')\nplt.title(\"Beer by Alcohol content\", color='green')\nplt.show()\nd2 = df.groupby('beer_style')[['beer_ABV','review_overall']].mean().sort_values('beer_style').reset_index()\n#d2\n#Beer style vs Beer ABV\nfig = px.scatter(d2,x=\"beer_style\",y=\"beer_ABV\")\nfig.show()\n\"\"\"\n**Observatin:**\n    \n* Almost all the Beer Styles have an average alcohol volume,  ABV > 4%.\n\n\"\"\"\n#Beer ABV vs Overall Review\n\nfig = px.scatter(d2,x=\"beer_ABV\",y=\"review_overall\",trendline ='ols')\nfig.show()\n\"\"\"\n**Observatin:**\n    \n* Beers with ABV >5%  tend to get higher Overall ratings, with almost all of them getting >3 overall rating\n* There is a positive correlation between ABV levels and the overall rating of the beer.\n\"\"\"\n# Pair Plot for all the user ratings\n\ndat = df.loc[:,['review_appearance', 'review_palette', 'review_overall', 'review_taste','review_aroma']]\ndat = dat.groupby('review_overall')['review_appearance', 'review_palette','review_taste','review_aroma'].mean().sort_values('review_overall').reset_index()\n#dat\nsns.pairplot(data=dat)\n\"\"\"\n## Let's explore some really interesting intuitive questions about the beer data :\n\"\"\"\n\"\"\"\n### Q1:\n\n1. **Rank top 3 Breweries which produce the strongest beers?**\n\"\"\"\n\"\"\"\n* Based on the alcohol volume of a beer (i.e. 'beer_ABV'), we can determine how strong it is. \n* In this dataset, we are given only 'beer_brewerId' and not the corresponding **'brewer_names'**, so we will use the 'beer_brewerId' for finding the breweries which produce the strongest beer.\n\"\"\"\ndf.beer_brewerId.value_counts()\ndf_abv = df.groupby('beer_brewerId')['beer_ABV'].mean()\ndf_abv = pd.DataFrame(data=df_abv).sort_values(by=['beer_ABV'],ascending=False).reset_index()\ndf_abv.head(3)\n\"\"\"\n* **The top 3 breweries which produce the strongest beer can recognized by below brewery ids.**\n<ul>\n    <li>6513<\/li> \t\n    <li>736<\/li>  \t\n    <li>24215<\/li> \n<\/ul>\n\"\"\"\nfig = px.scatter(df_abv,x=\"beer_brewerId\",y=\"beer_ABV\")\nfig.show()\n\"\"\"\n### Q2:\n\n2. **Which year did beers enjoy the highest ratings?**\n\"\"\"\n\"\"\"\n* For determining whether a beer is overall good or not, we will consider the overall rating that is  'review_overall'.\n\n\"\"\"\ndf.groupby('year')['year'].count()\ndf_dt = df.loc[:,['year','review_overall']]\ndf_dt = df_dt.groupby('year')[['review_overall']].mean().sort_values('review_overall',ascending = False).reset_index()\ndf_dt\n\"\"\"\n* **Thus Beers enjoyed the highest ratings in the year 2000.**\n\"\"\"\nfig = px.scatter(df_dt,x=\"year\",y=\"review_overall\")\nfig.show()\n\"\"\"\n### Q3:\n\n3. **Based on the user\u2019s ratings which factors are important among taste, aroma, appearance, and palette?**\n\"\"\"\n\"\"\"\n* For determining the important factors, we need to find the correlation amongst different factors.\n* Compare the different factors with the overall review and thus find the important factor.\n\"\"\"\ndf_taap = df.loc[:,['review_taste','review_aroma','review_appearance', 'review_palette', 'review_overall']]\ndf_taap\ncorr_mat = df_taap.corr()\ncorr_mat\nplt.figure(figsize=(10,6))\nsns.heatmap(data=corr_mat, annot=True,cmap=\"YlGnBu\")\n\"\"\"\n* **Standard Pearson Correlation coefficient is used here to calculate the correlation between different factors and overall beer quatlity.**\n* **It can be observed that the 'review_aroma' feature is most correlated with the 'review_overall' feature and thus we can conclude it to be an important feature based on user's review and different ratings.**\n\"\"\"\n#Review_aroma vs Overall Review\ndf_taap = df_taap.groupby('review_overall')['review_taste','review_aroma','review_appearance', 'review_palette'].mean().sort_values('review_overall').reset_index()\n#df_taap\nfig = px.scatter(df_taap,x=\"review_aroma\",y=\"review_overall\",trendline ='ols')\nfig.show()\n\"\"\"\n* **We can see a strong positive correlation exist between the Review_aroma and Overall Review.**\n\"\"\"\n\"\"\"\n### Q4:\n\n4. **If you were to recommend 3 beers to your friends based on this data which ones will you recommend?**\n\"\"\"\n\"\"\"\n* For determining whether a beer is overall good or not, we will consider 2 factors here - 'review_overall' and 'beer_ABV'.\n* Those beers witht the best overall values considering both the overall ratings and alcohol volume will be considered for recommendation.\n\"\"\"\ndf.groupby('beer_name')['beer_name'].count().sort_values(ascending=False)\n\"\"\"\n* **Observation** : 14028 different varieties of beers are available in the dataset.\n\"\"\"\ndf_br = df.loc[:,['beer_name','review_overall','beer_ABV']]\ndf_br\ndf_br = df_br.groupby('beer_name')['review_overall','beer_ABV'].mean().reset_index().sort_values(by = ['review_overall','beer_ABV'],ascending = False).head(10)\ndf_br\n\"\"\"\n* **The top 3 beers which can be considered for recommendation based on the overall ratings and the alcohol volume can recognized by below beer names.**\n<ul>\n    <li>AleSmith Speedway Stout - Oak Aged<\/li> \t\n    <li>Pilot Series Imperial Sweet Stout - Palm Ridge Reserve Barrel Aged<\/li>  \t\n    <li>Bees Knees Barleywine<\/li> \n<\/ul>\n\"\"\"\nfig = px.scatter(df_br,x=\"beer_name\",y=\"review_overall\")\nfig.show()\n\n\"\"\"\n### Q5:\n\n5. **Which Beer style seems to be the favorite based on reviews written by users?**\n\"\"\"\ndf['beer_style'].value_counts()\nplt.figure(figsize=(20,10))\n\ndf['beer_style'].value_counts().plot(kind = \"bar\", color = \"blue\")\n\nplt.title(\"Most Favorite Beer Styles by Count of written reviews\")\ndf_bsrt = df.loc[:,['beer_style','review_text']].sort_values(by='beer_style')\ndf_bsrt = df_bsrt.iloc[0:100000,:]\n#df_bsrt.to_dict()\ndf_tmp = df_bsrt.groupby('beer_style')['review_text'].count().nlargest(10)\ndf_tmp\n# Credits : https:\/\/stackoverflow.com\/a\/47091490\/4084039\n\ndef decontracted(phrase):\n    # specific\n    phrase = re.sub(r\"won\\'t\", \"will not\", phrase)\n    phrase = re.sub(r\"can\\'t\", \"can not\", phrase)\n    #phrase = re.sub(r\"I\\'d\", \"I had\", phrase)\n\n    # general\n    phrase = re.sub(r\"n\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'re\", \" are\", phrase)\n    phrase = re.sub(r\"\\'s\", \" is\", phrase)\n    phrase = re.sub(r\"\\'d\", \" would\", phrase)\n    phrase = re.sub(r\"\\'ll\", \" will\", phrase)\n    phrase = re.sub(r\"\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'ve\", \" have\", phrase)\n    phrase = re.sub(r\"\\'m\", \" am\", phrase)\n    return phrase\n\"\"\"\n## Natural Language Processing of Text Feature\n\"\"\"\nnltk.download('stopwords')\npreprocessed_reviews = []\n\nif os.path.isfile('.\/preprocessed_reviews.pkl'):\n    #retrieve the preprocessed_reviews list for usage.\n    with open('.\/preprocessed_reviews.pkl', 'rb') as f:\n        preprocessed_reviews = pickle.load(f)\nelse:\n    for rev in  tqdm(df_bsrt['review_text'].values):\n        rev = re.sub(r\"http\\S+\", \"\", rev)\n        rev = BeautifulSoup(rev, 'lxml').get_text()\n        rev = decontracted(rev)\n        rev = re.sub(\"\\S*\\d\\S*\", \"\", rev).strip()\n        rev = re.sub(\"[^A-Za-z]+\", ' ', rev)\n        rev = ' '.join(w.lower() for w in rev.split() if w.lower() not in stop_words)\n        preprocessed_reviews.append(rev)\n\n    #save the preprocessed_reviews list for later usage.\n    with open('preprocessed_reviews.pkl', 'wb') as f: \n        pickle.dump(preprocessed_reviews, f)\nreview_text_string = ' '.join(map(str, preprocessed_reviews)) \nreview_text_words = word_tokenize(review_text_string)\nlen(review_text_words)\nwordsToken = FreqDist(review_text_words)\nwordsToken.most_common(50)\nreview_text_words_clean = [w for w in review_text_words if w.isalpha()]\nprint(len(review_text_words_clean))\nwordstring = ' '.join(map(str,review_text_words_clean))\n# Word Cloud\n\nwc = WordCloud(background_color=\"white\",stopwords=STOPWORDS)\n# generate word cloud\nwc.generate(wordstring)\nprint (\"Word Cloud for input text:\")\nplt.figure(figsize=(20,20))\nplt.imshow(wc)\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n**Observations:**\n\n* word cloud here displays the most important words corresponding to the beer_style.\n\"\"\"\nd_0 = df.loc[:,['beer_style','review_text','review_overall']]\nd_0\nd_0 = d_0.groupby(['beer_style','review_text'])[['review_overall']].sum().sort_values('review_overall',ascending = False).reset_index()\nd_0\nd_0.loc[d_0.review_text != '#NAME?'].head(5)\n\"\"\"\n**Observations:**\n\n* THe most favorite 'beer_style ' based on reviews written by users are:\n<ul>\n    <li>American Adjunct Lager<\/li> \t\n    <li>M\u00e4rzen \/ Oktoberfes<\/li>  \t\n    <li>American Adjunct Lager<\/li> \n    <li>English Porter<\/li>\n    <li>Fruit \/ Vegetable Beer<\/li>\n<\/ul>\n\"\"\"\n\"\"\"\n### Q6:\n\n6. **How does written review compare to overall review score for the beer styles?**\n\"\"\"\ndf_rtro = df.loc[:,['beer_style','review_text']].sort_values('beer_style')\ndf_rtro\ndf_bsro = df.loc[:,['beer_style','review_overall']].sort_values('beer_style')\ndf_bsro\nq6 = df_bsro.loc[:,['beer_style','review_overall']]\nq6 = q6.groupby('beer_style')[['review_overall']].mean().sort_values('review_overall', ascending = False).reset_index()\nq6\nfig = px.scatter(q6,x=\"beer_style\",y=\"review_overall\",color='beer_style')\n\nfig.show()","meta":"{'source': 'AI4Code', 'id': '92851b4b331310'}"}
{"id":"13642","text":"\"\"\"\nCopyright 2019 Google LLC.\n\"\"\"\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport bq_helper\n\npatents_helper = bq_helper.BigQueryHelper(\n    active_project=\"patents-public-data\",\n    dataset_name=\"patents\"\n)\n\"\"\"\n# Plotting Similar Patents with Google Patents Public Data\n- In this notebook, we'll walk through how to use publicly available patent embeddings, similar patents and other data to visualize patents near some set of input patents.\n\n## Overview\n- We'll set an input list of patents and use these to a few additional sets of patents including 1) The 25 most similar patents to each of those in our input list. 2) A set of 100 patents with shared CPC's and 3) A set of 100 patents which have no CPC overlap. \n- Next we'll pull a patent embedding from the Google Patents Research Dataset\n- Finally, we'll run PCA to convert the 64 digit embedding in a 2D vector for plotting.\n\"\"\"\n# A list of patents we care about. In this case we're going to manually enter a set of patents related to codecs.\ninput_patents = [\n    'US-7292636-B2',\n    'US-6115503-A',\n    'US-6812873-B1',\n    'US-6825782-B2',\n    'US-6850175-B1',\n    'US-6934331-B2',\n    'US-6967601-B2',\n    'US-7068721-B2',\n    'US-7183951-B2',\n    'US-7190289-B2',\n    'US-7199836-B1',\n    'US-7298303-B2',\n    'US-7310372-B2',\n    'US-7339991-B2',\n    'US-7346216-B2',\n    'US-7474699-B2',\n]\n# Converts input list into a string for use in queries.\ninput_patents_str = '(' + str(input_patents)[1:-1] + ')'\ninput_patents_str\n\"\"\"\n## Dataset Construction\nHere we need to do some data wrangling. We could either write one big query, or do things step by step in python. Its easier to follow in python, so I'm going to do it iteratively as follows:\n1. First I'm going to pull the list of all CPC codes covered by our input list (including non-inventive). This will be used for getting a sample of other patents which are related but not exactly the same as our input set.\n2. Get the list of most similar patents for each of the patents in our input set. This comes from the table `patents-public-data.google_patents_research.publications`\n4. For all patents in our set, get the 64 digit patent embedding from the `patents-public-data.google_patents_research.publications` table.\n3. Run PCA to convert our 64 digit embedding into 2 dimensions and plot our similar patents against the larger random sample from shared CPC's. \n\"\"\"\nquery = '''\n#standardSQL\nSELECT DISTINCT cpc_code \nFROM (\n    SELECT\n    publication_number,\n    c.code as cpc_code\n\n    FROM `patents-public-data.patents.publications`\n    ,UNNEST(cpc) as c\n\n    where publication_number in {}\n)\n'''.format(input_patents_str)\n\nall_cpcs = patents_helper.query_to_pandas(query=query)\n# Convert into helper string for limiting CPCs\nall_cpcs_str = '(' + str(list(all_cpcs.cpc_code.values))[1:-1] + ')'\n# Get sample of patents not in our input set, but sharing at least 1 cpc.\nquery = '''\nSELECT DISTINCT publication_number\nFROM `patents-public-data.patents.publications`\n,UNNEST(cpc) as cpc\nwhere publication_number not in {}\nand cpc.code in {}\nand rand() < 0.2\nlimit 100\n'''.format(input_patents_str, all_cpcs_str)\nshared_cpc = patents_helper.query_to_pandas_safe(query, max_gb_scanned=5)\nshared_cpc.loc[:, 'source'] = 'shared_cpc'\nshared_cpc.head()\n# Get sample of 100 random patents not sharing any CPC's.\nquery = '''\nSELECT DISTINCT publication_number\nFROM `patents-public-data.patents.publications`\n,UNNEST(cpc) as cpc\nwhere publication_number not in {}\nand cpc.code not in {}\nand rand() < 0.2\nlimit 100\n'''.format(input_patents_str, all_cpcs_str)\nno_shared_cpc = patents_helper.query_to_pandas_safe(query, max_gb_scanned=5)\nno_shared_cpc.loc[:, 'source'] = 'no_shared_cpc'\nno_shared_cpc.head()\n# Pull all the \"similar patents\" from Patents Research dataset.\n# Each of our patents in the input list should have ~25 similar patents listed, so we get back 12*25 rows\nquery = '''\nSELECT distinct\ns.publication_number\n\nFROM `patents-public-data.patents.publications` p\nJOIN `patents-public-data:google_patents_research.publications` r\n  on p.publication_number = r.publication_number\n, UNNEST(similar) as s\nwhere p.publication_number in {}\n'''.format(input_patents_str)\nsimilar = patents_helper.query_to_pandas_safe(query, max_gb_scanned=36)\nsimilar.loc[:, 'source'] = 'similar_to_input'\nprint(len(similar))\n# Lets constuct our dataframe by concatenating our input list, the close negatives and \n# the list of \"similar patents\" according to the patents research table.\ndf = pd.DataFrame(input_patents, columns=['publication_number'])\ndf.loc[:, 'source'] = 'input'\ndf = pd.concat(\n    [df, similar, shared_cpc, no_shared_cpc]).drop_duplicates('publication_number', keep='first')\ndf.source.value_counts()\n\"\"\"\nNote on embeddings - the Patents research table has a repeated field which contains a patent embedding. To use this in python, we need to extract the repeated value as a joined string - hence the javascript UDF below.\n\"\"\"\nall_patents_str = '(' + str(list(df.publication_number.unique()))[1:-1] + ')'\nquery = r'''\nCREATE TEMPORARY FUNCTION convert_embedding_to_string(embedding ARRAY<FLOAT64>)\nRETURNS STRING\nLANGUAGE js AS \"\"\"\nlet embedding_str = ''\nfor (i = 0; i < embedding.length; i++) { \n  embedding_str += embedding[i].toFixed(6) + ',';\n} \nreturn embedding_str\n\"\"\"; \n\nSELECT \npublication_number,\nconvert_embedding_to_string(embedding_v1) embedding\nFROM `patents-public-data.google_patents_research.publications` \nwhere publication_number in %s\n''' % (all_patents_str)\n\nresults = patents_helper.query_to_pandas_safe(query, max_gb_scanned=50).drop_duplicates('publication_number')\n# Put the string embedding into 64 float cols.\nembeddings = pd.DataFrame(\n    data=[e for e in results.embedding.apply(lambda x: x.split(',')[:64]).values],\n    columns = ['x{}'.format(i) for i in range(64)],\n    index=results.publication_number\n)\nembeddings = embeddings.astype(float).reset_index()\nembeddings.head()\n# Merge the embeddings into the dataframe.\ndf = df.merge(embeddings, on='publication_number').drop_duplicates('publication_number')\ndf.head()\n\"\"\"\n## Next, we'll run PCA on the 64 dimensional embeddings - converting them into a 2-D vector for ease of plotting. \n\"\"\"\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\nprincipal_components = pca.fit_transform(df.iloc[:, 2:].values)\npca_df = pd.DataFrame(\n    data = principal_components\n    ,columns = ['principal component 1', 'principal component 2']\n)\n\nplot_df = pd.concat([pca_df, df[['source']]], axis = 1)\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = plot_df.source.unique()\ncolors = ['r', 'g', 'b', 'y']\nfor source, color in zip(targets,colors):\n    indicesToKeep = plot_df['source'] == source\n    ax.scatter(plot_df.loc[indicesToKeep, 'principal component 1']\n               , plot_df.loc[indicesToKeep, 'principal component 2']\n               , c = color\n               , s = 12)\nax.legend(targets)\nax.grid()","meta":"{'source': 'AI4Code', 'id': '18efbc038b329b'}"}
{"id":"86385","text":"\"\"\"\n# Store Item Demand Forecasting Challenge - Spark and deep learning\n### link for the github repository (spark part is on ipynb): https:\/\/github.com\/dimitreOliveira\/StoreItemDemand\n\"\"\"\n# this code get the resulting dataset that i uploaded from my databricks code and commits.\nimport pandas as pd\nimport os\n\n\nsubmission25 = pd.read_csv('..\/input\/test_data\/model25.csv')\nsubmission25.to_csv('submission25.csv', index=False)\nfrom pyspark.sql import Window\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql.types import *\nfrom pyspark.sql import types as T\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql import functions as F\nfrom pyspark.ml import Transformer\nfrom pyspark.ml.param.shared import HasInputCol, HasOutputCol\n\ndays = lambda i: i * 86400\nget_weekday = udf(lambda x: x.weekday())\nserie_has_null = F.udf(lambda x: reduce((lambda x, y: x and y), x))\nimport json\nimport numpy as np\nfrom keras.models import model_from_json\nunlist = lambda x: [float(i[0]) for i in x]\ndef prepare_data(data):\n    list_result = []\n    for i in range(len(data)):\n        list_result.append(np.asarray(data[i]))\n    return np.asarray(list_result)\n\ndef prepare_collected_data(data):\n    list_features = []\n    list_labels = []\n    for i in range(len(data)):\n        list_features.append(np.asarray(data[i][0]))\n        list_labels.append(data[i][1])\n    return np.asarray(list_features), np.asarray(list_labels)\n\ndef prepare_collected_data_test(data):\n    list_features = []\n    for i in range(len(data)):\n        list_features.append(np.asarray(data[i][0]))\n    return np.asarray(list_features)\n\n\ndef save_model(model_path, weights_path, model):\n    \"\"\"\n    Save model.\n    \"\"\"\n    np.save(weights_path, model.get_weights())\n    with open(model_path, 'w') as f:\n        json.dump(model.to_json(), f)\n    \ndef load_model(model_path, weights_path):\n    \"\"\"\n    Load model.\n    \"\"\"\n    with open(model_path, 'r') as f:\n        data = json.load(f)\n\n    model = model_from_json(data)\n    weights = np.load(weights_path)\n    model.set_weights(weights)\n\n    return model\nclass DateConverter(Transformer):\n    def __init__(self, inputCol, outputCol):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != TimestampType()):\n        raise Exception('Input type %s did not match input type TimestampType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, df.date.cast(self.inputCol))\n    \n    \nclass DayExtractor(Transformer):\n    def __init__(self, inputCol, outputCol='day'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != DateType()):\n            raise Exception('DayExtractor input type %s did not match input type DateType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.dayofmonth(df[self.inputCol]))\n    \n    \nclass MonthExtractor(Transformer):\n    def __init__(self, inputCol, outputCol='month'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != DateType()):\n            raise Exception('MonthExtractor input type %s did not match input type DateType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.month(df[self.inputCol]))\n    \n    \nclass YearExtractor(Transformer):\n    def __init__(self, inputCol, outputCol='year'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != DateType()):\n            raise Exception('YearExtractor input type %s did not match input type DateType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.year(df[self.inputCol]))\n    \n    \nclass WeekDayExtractor(Transformer):\n    def __init__(self, inputCol, outputCol='weekday'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != DateType()):\n            raise Exception('WeekDayExtractor input type %s did not match input type DateType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, get_weekday(df[self.inputCol]).cast('int'))\n    \n    \nclass WeekendExtractor(Transformer):\n    def __init__(self, inputCol='weekday', outputCol='weekend'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != IntegerType()):\n            raise Exception('WeekendExtractor input type %s did not match input type IntegerType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.when(((df[self.inputCol] == 5) | (df[self.inputCol] == 6)), 1).otherwise(0))\n    \n    \nclass SerieMaker(Transformer):\n    def __init__(self, inputCol='scaledFeatures', outputCol='serie', dateCol='date', idCol=['store', 'item'], serieSize=30):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n        self.dateCol = dateCol\n        self.serieSize = serieSize\n        self.idCol = idCol\n\n    def _transform(self, df):\n        window = Window.partitionBy(self.idCol).orderBy(self.dateCol)\n        series = []   \n        \n    df = df.withColumn('filled_serie', F.lit(0))\n    \n    for index in reversed(range(0, self.serieSize)):\n        window2 = Window.partitionBy(self.idCol).orderBy(self.dateCol).rowsBetween((30 - index), 30)\n        col_name = (self.outputCol + '%s' % index)\n        series.append(col_name)\n        df = df.withColumn(col_name, F.when(F.isnull(F.lag(F.col(self.inputCol), index).over(window)), F.first(F.col(self.inputCol), ignorenulls=True).over(window2)).otherwise(F.lag(F.col(self.inputCol), index).over(window)))\n        df = df.withColumn('filled_serie', F.when(F.isnull(F.lag(F.col(self.inputCol), index).over(window)), (F.col('filled_serie') + 1)).otherwise(F.col('filled_serie')))\n\n    df = df.withColumn('rank', F.rank().over(window))\n    df = df.withColumn(self.outputCol, F.array(*series))\n    \n    return df.drop(*series)\n\n\nclass MonthBeginExtractor(Transformer):\n    def __init__(self, inputCol='day', outputCol='monthbegin'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != IntegerType()):\n            raise Exception('MonthBeginExtractor input type %s did not match input type IntegerType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.when((df[self.inputCol] <= 7), 1).otherwise(0))\n    \n    \nclass MonthEndExtractor(Transformer):\n    def __init__(self, inputCol='day', outputCol='monthend'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != IntegerType()):\n            raise Exception('MonthEndExtractor input type %s did not match input type IntegerType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.when((df[self.inputCol] >= 24), 1).otherwise(0))\n    \n    \nclass YearQuarterExtractor(Transformer):\n    def __init__(self, inputCol='month', outputCol='yearquarter'):\n        self.inputCol = inputCol\n        self.outputCol = outputCol\n    \n    def check_input_type(self, schema):\n        field = schema[self.inputCol]\n        if (field.dataType != IntegerType()):\n            raise Exception('YearQuarterExtractor input type %s did not match input type IntegerType' % field.dataType)\n\n    def _transform(self, df):\n        self.check_input_type(df.schema)\n        return df.withColumn(self.outputCol, F.when((df[self.inputCol] <= 3), 0)\n                               .otherwise(F.when((df[self.inputCol] <= 6), 1)\n                                .otherwise(F.when((df[self.inputCol] <= 9), 2)\n                                 .otherwise(3))))\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.feature import MinMaxScaler\n\ntrain_data = spark.sql(\"select * from store_item_demand_train_csv\")\n\ntrain, validation = train_data.randomSplit([0.8,0.2], seed=1234)\n# Feature extraction\ndc = DateConverter(inputCol='date', outputCol='dateFormated')\ndex = DayExtractor(inputCol='dateFormated')\nmex = MonthExtractor(inputCol='dateFormated')\nyex = YearExtractor(inputCol='dateFormated')\nwdex = WeekDayExtractor(inputCol='dateFormated')\nwex = WeekendExtractor()\nmbex = MonthBeginExtractor()\nmeex = MonthEndExtractor()\nyqex = YearQuarterExtractor()\n\n# Data process\nva = VectorAssembler(inputCols=['store', 'item', 'day', 'month', 'year', 'weekday', 'weekend', 'monthbegin', 'monthend', 'yearquarter'], outputCol=\"features\")\nscaler = MinMaxScaler(inputCol=\"features\", outputCol=\"scaledFeatures\")\n\n# Serialize data\nsm = SerieMaker(inputCol='scaledFeatures', dateCol='date', idCol=['store', 'item'], serieSize=15)\n\npipeline = Pipeline(stages=[dc, dex, mex, yex, wdex, wex, mbex, meex, yqex, va, scaler, sm])\npipiline_model = pipeline.fit(train)\n\ntrain_transformed = pipiline_model.transform(train)\nvalidation_transformed = pipiline_model.transform(validation)\n\ntrain_transformed.write.saveAsTable('train_transformed_15', mode='overwrite')\nvalidation_transformed.write.saveAsTable('validation_transformed_15', mode='overwrite')\ntest_data = spark.sql(\"select * from store_item_demand_test_csv\")\ntest_transformed = pipiline_model.transform(test_data)\ntest_transformed.write.saveAsTable('test_transformed_15', mode='overwrite')\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Dropout, GRU\nfrom pyspark.ml.evaluation import RegressionEvaluator\n\ntrain_transformed = spark.sql(\"select * from train_transformed\")\nvalidation_transformed = spark.sql(\"select * from validation_transformed\")\n\ntrain_x, train_y = prepare_collected_data(train_transformed.select('serie', 'sales').collect())\nvalidation_x, validation_y = prepare_collected_data(validation_transformed.select('serie', 'sales').collect())\n\nn_label = 1\nserie_size = len(train_x[0])\nn_features = len(train_x[0][0])\n# hyperparameters\nepochs = 80\nbatch = 512\nlr = 0.001\n\n# design network\nmodel = Sequential()\nmodel.add(GRU(40, input_shape=(serie_size, n_features)))\nmodel.add(Dense(10, kernel_initializer='glorot_normal', activation='relu'))\nmodel.add(Dense(n_label))\nmodel.summary()\n\nadam = optimizers.Adam(lr)\nmodel.compile(loss='mae', optimizer=adam, metrics=['mse', 'msle'])\n\nhistory = model.fit(train_x, train_y, epochs=epochs, batch_size=batch, validation_data=(validation_x, validation_y), verbose=2, shuffle=False)\nmodel_path = '\/dbfs\/user\/model1.json'\nweights_path = '\/dbfs\/user\/weights1.npy'\nsave_model(model_path, weights_path, model)\n\npredictions = model.predict(validation_x)\n\nimport pandas as pd\nids = validation_y\ndf = pd.DataFrame(ids, columns=['label'])\ndf['sales'] = predictions\ndf_predictions = spark.createDataFrame(df)\n\nrmse_evaluator = RegressionEvaluator(labelCol=\"label\", predictionCol=\"sales\", metricName=\"rmse\")\nmse_evaluator = RegressionEvaluator(labelCol=\"label\", predictionCol=\"sales\", metricName=\"mse\")\nmae_evaluator = RegressionEvaluator(labelCol=\"label\", predictionCol=\"sales\", metricName=\"mae\")\n\nvalidation_rmse = rmse_evaluator.evaluate(df_predictions)\nvalidation_mse = mse_evaluator.evaluate(df_predictions)\nvalidation_mae = mae_evaluator.evaluate(df_predictions)\nprint(\"RMSE: %f, MSE: %f, MAE: %f\" % (validation_rmse, validation_mse, validation_mae))\nmodel_path = '\/dbfs\/user\/model1.json'\nweights_path = '\/dbfs\/user\/weights1.npy'\nmodel = load_model(model_path, weights_path)\n\ntest_transformed = spark.sql(\"select * from test_transformed_15\")\n\ntest = prepare_collected_data_test(test_transformed.select('serie').collect())\n\nids = test_transformed.select('id').collect()\n\npredictions = model.predict(test)\n\nimport pandas as pd\ndf = pd.DataFrame(ids, columns=['id'])\ndf['sales'] = predictions\ndf_predictions = spark.createDataFrame(df)\n\ndf_predictions = df_predictions.withColumn('sales', df_predictions['sales'].cast('int'))\ndisplay(df_predictions)","meta":"{'source': 'AI4Code', 'id': '9e6f005eabe84f'}"}
{"id":"85499","text":"\"\"\"\n#      Exploratory Data Analysis (EDA) of Forest Cover Type Data\n\"\"\"\n\"\"\"\nThe study area includes four wilderness areas located in the Roosevelt National Forest of Northern Colorado.\n\nThe wilderness areas are:\n\n1 - Rawah Wilderness Area\n2 - Neota Wilderness Area\n3 - Comanche Peak Wilderness Area\n4 - Cache la Poudre Wilderness Area.\n\n\nThe seven forest cover types are:\n\n1 - Spruce\/Fir\n2 - Lodgepole Pine\n3 - Ponderosa Pine\n4 - Cottonwood\/Willow\n5 - Aspen\n6 - Douglas-fir\n7 - Krummholz.\n\"\"\"\n\"\"\"\n# Preparing the data for analysis\n\"\"\"\n#Importing the required libraries.\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n#Reading the given csv file into a dataframe.\ndf=pd.read_csv(\"\/kaggle\/input\/forest_train.csv\")\n#Getting the initial five values of the dataframe.\ndf.head()\n#Getting the dimensionality of the dataframe.\ndf.shape\n#Getting the summary of the data types in the data frame\ndf.info()\n#Renaming the wilderness area columns for better clarity.\ndf.rename(columns = {'Wilderness_Area1':'Rawah', 'Wilderness_Area2':'Neota','Wilderness_Area3':'Comanche_Peak ','Wilderness_Area4':'Cache_la_Poudre'}, inplace = True) \n#Checking the column names\ndf.columns\n#Combining the four wilderness area columns and fourty soil type columns to Wild_area and Soil_type respectively, and removing already existing ones.\ndf['Wild_area'] = (df.iloc[:, 11:15] == 1).idxmax(1)\ndf['Soil_type'] = (df.iloc[:, 15:55] == 1).idxmax(1)\ndf_forest=df.drop(columns=['Id','Rawah', 'Neota',\n       'Comanche_Peak ', 'Cache_la_Poudre', 'Soil_Type1', 'Soil_Type2', 'Soil_Type3', 'Soil_Type4',\n       'Soil_Type5', 'Soil_Type6', 'Soil_Type7', 'Soil_Type8', 'Soil_Type9',\n       'Soil_Type10', 'Soil_Type11', 'Soil_Type12', 'Soil_Type13',\n       'Soil_Type14', 'Soil_Type15', 'Soil_Type16', 'Soil_Type17',\n       'Soil_Type18', 'Soil_Type19', 'Soil_Type20', 'Soil_Type21',\n       'Soil_Type22', 'Soil_Type23', 'Soil_Type24', 'Soil_Type25',\n       'Soil_Type26', 'Soil_Type27', 'Soil_Type28', 'Soil_Type29',\n       'Soil_Type30', 'Soil_Type31', 'Soil_Type32', 'Soil_Type33',\n       'Soil_Type34', 'Soil_Type35', 'Soil_Type36', 'Soil_Type37',\n       'Soil_Type38', 'Soil_Type39', 'Soil_Type40'])\ndf_forest\n#Checking the columns in the modified dataframe.\ndf_forest.columns\n\"\"\"\n\n# Preliminary analysis\n\"\"\"\n#Provide the general descriptive statistical values.\ndf_forest.describe()\n\"\"\"\n* The average elevation is around 2750m with values ranging from 1863m to 3849m.\n\n* The mean horizontal distance to surface water features is 227 units and mean vertical distance to surface water features is 51 units.\n\n* Mean horizontal distance to roadways is 1714 units. The values range from 0 units to 6890 units and hence the standard deviation is 1325 units.\n\n* Mean horizontal distance to firepoints is 1511 units. The values range from 0 to 6993 units.\n\"\"\"\n#Count of number of entries of each cover type.\nsns.countplot(df_forest['Cover_Type'],color=\"grey\");\n\"\"\"\nAll seven forest cover types occur with the same frequency in the data.\n\"\"\"\n#Count of the entries from different wilderness areas.\nsns.countplot(df_forest['Wild_area']);\n\"\"\"\n* The four wilderness areas, on the other hand, occur in varying frequencies in the data.\n* Entries from Comanche Peak wilderness area occur the most and entries from the Neota wilderness area, the least.\n* This points to the uneven sampling with respect to the wilderness areas, even though the number of samples for each cover type is equal.\n\"\"\"\n#Distribution of elevation values in the data.\nsns.distplot(df_forest['Elevation'],kde=False,color='red', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The elevation values range between 2000m to 4000m. Thus the data is collected from relatively high altitude areas, as indicated by the vegetation type observed in the data.\n* The distribution of elevation values follows a trimodal fashion, peaking in the middle of the intervals 2000m-2500m, 2500m-3000m,3000m-3500m, and tapering at both ends.\n\"\"\"\n#Distribution of aspect values in the data\nsns.distplot(df_forest['Aspect'],kde=False,color='red', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\nThe aspect values range from 0 to 350 with most of them lying between 0-100 and 275-350.\nIt follows a bimodal distribution.\n\"\"\"\n#Distribution of values of slope in the data.\nsns.distplot(df_forest['Slope'],kde=False,color='red', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\nA positively skewed (right skewed) distribution, peaked at around 10, is obtained with the slope values in the data.\n\"\"\"\n#Distribution of values of the horizontal distance to roadways.\nsns.distplot(df_forest['Horizontal_Distance_To_Roadways'],kde=False,color='blue', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* For horizontal distance from roadways, a positively skewed distribution is obtained, peaked at 1000. \n* It is thus clear from the graph that most of the samples are within 0-2000 distance to the roadways.\n* This indicates a considerable human impact and chances of commercial exploitation of the forests.\n\"\"\"\n#Distribution of values of the horizontal distance to fire points.\nsns.distplot(df_forest['Horizontal_Distance_To_Fire_Points'],kde=False,color='blue', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* Most of the samples are located within a distance of 0-2000 units to fire points in this positively skewed distribution.This indicates the horizontal distance to wildfire ignition point.\n* This data, thus indicates the noticeable influence of human activities including presence of roads and proximity to fire points.The type of vegetaion that would grow in these regions would depend on these factors.\n\"\"\"\n#Distribution of values of the horizontal distance to nearest surface water features.\nsns.distplot(df_forest['Horizontal_Distance_To_Hydrology'],kde=False,color='green', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The horizontal distances to the nearest surface water features also shows a positively skewed distribution,ranging from 0 to 1200, peaking near zero. This means that most of the samples are present very close to surface water sources.\n\"\"\"\n#Distribution of values of the vertical distances to nearest surface water features.\nsns.distplot(df_forest['Vertical_Distance_To_Hydrology'],kde=False,color='green', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The vertical distance to surface water features,even though a positively skewed distribution with a sharp peak at zero,ranges from -150 to around 500.\n\"\"\"\n#Distribution of values of the hillshade index at 9am during summer solstice on an index from 0-255.\nsns.distplot(df_forest['Hillshade_9am'],kde=False,color='black', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The values for hillshade index at 9am follows a negtively skewed distribution, peaking at around 225, ranging from 100 to 250.\n\"\"\"\n#Distribution of values of the hillshade index at noon during summer solstice on an index from 0-255.\nsns.distplot(df_forest['Hillshade_Noon'],kde=False,color='black', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The values for hillshade index at noon follows a negtively skewed distribution, peaking at around 225, ranging from 125 to 250.\n\"\"\"\n#Distribution of values of the hillshade index at 3pm during summer solstice on an index from 0-255.\nsns.distplot(df_forest['Hillshade_3pm'],kde=False,color='black', bins=100);\nplt.ylabel('Frequency',fontsize=10)\n\"\"\"\n* The values for hillshade index at 3pm follows a more or less symmetric normal distribution, peaking at around 150,ranging from 0 to 250.\n\n\"\"\"\n#Distribution of frequency of various soil types in the data.\ndf_forest['Soil_type'].value_counts().plot(kind='barh',figsize=(10,10));\nplt.xlabel('Frequency',fontsize=10)\nplt.ylabel('Soil_types',fontsize=10)\n\"\"\"\n* Of the forty soil types mentioned, two, namely soil-type 8 and soil-type 25 are not present in the data.\n\n* Soil type 28 is present in the smallest amount.\n\n* Soil-type 10 is present in the maximum samples. \n\n* This indicates the wide differences in the representaion of various soil types in the region of interest.\n\"\"\"\n\"\"\"\n**The above analysis of the distribution of various features gives a clear idea of the geography of the area of interest.The key take away at this point are as follows:**\n\"\"\"\n\"\"\"\n* This is a relatively high elavation area with a mean elavation around 2750m.\n\n* Located close to roadways and fire points,there are high chances of human intereference and significant impact like forest fires in this region.\n\n* Surface water features are present close to the sample areas.\n\n* Bullwark - Catamount families - Rock outcrop complex, rubbly type of soil is the most common soil type in the data.\n\"\"\"\n\"\"\"\n**Now let us explore the relationships between various forest cover types to other features to better understand their variation and relevance to or analysis.**\n\"\"\"\n\"\"\"\n# Detailed analysis\n\"\"\"\n\"\"\"\n**Analysis of features across various forest cover types.**\n\"\"\"\n#Forest cover types in each wilderness areas.\na1=sns.countplot(data=df_forest,x='Wild_area',hue=\"Cover_Type\");\na1.set_xticklabels(a1.get_xticklabels(),rotation=15);\n\"\"\"\n* Rawah wilderness area has only the forest cover types 1(Spruce\/Fir),2(Lodgepole Pine),5(Aspen) and 7(Krummholz).\n\n* Comanche peak wilderness area has all the forest cover types, except 4.Neota wilderness area has only 3 forest cover types-1(Spruce\/Fir),2(Lodgepole Pine) and 7(Krummholz).So, Neota and Comanche Peak are two extremes in forest cover type diversity, having the lowest and highest repsectively.\n\n* The forest cover type 4(Cottonwood\/Willow) is present only in the Cache la Poudre wilderness area and is the major forest cover in that area.It is the rarest in terms of distribution, but has the highest count than any other cover type in a single wilderness region.ache la Poudre wilderness is devoid of 3 forest cover types(Spruce\/Fir,Aspen,Krummholz).\n\n* Forest cover type 2(Lodgepole Pine) is present in all wilderness regions, maximum in Rawah and minimum in Cache la Poudre wilderness.\n\"\"\"\n#Elevation values across forest types.\nsns.boxplot(y=df_forest['Elevation'],x=df_forest['Cover_Type']);\n\"\"\"\n* The box plot of cover type versus elevation reveals the clear dispersion of various forest cover types based on elavation.Most of the tpes co exist at similar elavations, except for forest cover type 7(Krummholz).\n\n* The forest cover type 7(Krummholz) is present at the highest median elavation of around 3375m. It is followed by forest cover type 1(Spruce\/Fir) at nearly 3125m median elavation.\n\n* Forest cover type 2(Lodgepole Pine) and 5(Aspen) occur at similar elavations. Similarly,6(Douglas-fir) and 3 (Ponderosa Pine) occur at the same elavations.\n\n* The forest cover type 4 (Cottonwood\/Willow) shows the least median elavation at around 2250m.\n\"\"\"\n#Aspect values across forest types.\nsns.boxplot(y=df_forest['Aspect'],x=df_forest['Cover_Type']);\n\"\"\"\n* The aspect values do not vary very distinctly with forest cover types.The median aspect values for all the types occur between 100-200.\n\n* This parameter might not be very significant to come up with any conclusions regarding the area of interest.\n\"\"\"\n#Slope values across forest types.\nsns.boxplot(y=df_forest['Slope'],x=df_forest['Cover_Type']);\n\"\"\"\n* The values of slope do not vary very significantly between various forest cover types, as we can observe that the box plots overlap.Slight variations in median slope is observed.\n\"\"\"\n#Soil types across forest types.\na2=sns.catplot(y=\"Soil_type\",hue=\"Cover_Type\",kind=\"count\",palette=\"pastel\",height=15,data=df_forest);\n\n\"\"\"\nThis graph showcasses the soil types in which the seven forest cover types are present.\n\n* 1(Spruce\/Fir) is present in the highest frequency in soil type 29(Como - Legault families complex, extremely stony).\n\n* 2(Lodgepole Pine) is present in the highest frequency in soil type 29(Como - Legault families complex, extremely stony).\n\n* 3(Ponderosa Pine) is present in the highest frequency in soil type 10(Bullwark - Catamount families - Rock outcrop complex, rubbly).\n\n* 4(Cottonwood\/Willow) is present in the highest frequency in soil type 3( Haploborolis - Rock outcrop complex, rubbly).\n\n* 5(Aspen) is present in the highest frequency in soil type 30(Como family - Rock land - Legault family complex, extremely stony).\n\n* 6(Douglas-fir) is present in the highest frequency in soil type 10(Bullwark - Catamount families - Rock outcrop complex, rubbly).\n\n* 7(Krummholz) is present in the highest frequency in soil type 38(Leighcan - Moran families - Cryaquolls complex, extremely stony).\n\n\"\"\"\n#Horizontal distance to fire points across forest types.\nsns.boxplot(data=df_forest,x='Cover_Type',y=\"Horizontal_Distance_To_Fire_Points\");\n\"\"\"\n* The median horizontal distance to firepoints varies from 1000-2000 units across the various forest cover types.\n\n* It is the least for type 3,4 and 6.\n\n* This shows that on average, all types are vulnerable to the occurance of forest fire.\n\"\"\"\n#Horizontal distance to roadways across forest types.\nsns.boxplot(y=df_forest['Horizontal_Distance_To_Roadways'],x=df_forest['Cover_Type']);\n\"\"\"\n* The median horizontal distance to roadways varies from 1000-2000 units across all the forest cover types except 7.\n\n* This shows that on average, most types are equidistant from roadways. This would imply that they are prone to human interference and explotation.\n\n* Since the distance to firepoints are also in this range, one could assume that both distance to roadways and firepoints influence each other. \n\"\"\"\n#Horizontal distance to surface water features across forest types.\nsns.boxplot(y=df_forest['Horizontal_Distance_To_Hydrology'],x=df_forest['Cover_Type']);\n\"\"\"\n* The median of horizontal distances to surface water features vary from as low as 0 to nearly 200.\n\n* 4(Cottonwood\/Willow) is present close to water source based on this data.\n\n* 7(Krummholz) is present most distant to water sources.\n\"\"\"\n#Vertical distance to surface water features across forest types.\nsns.boxplot(y=df_forest['Vertical_Distance_To_Hydrology'],x=df_forest['Cover_Type']);\n\"\"\"\n* The vertical distance to water sources do not vary much among various forest cover types.\n\n* This might mean that the vertical distance to water source is not an important factor in performing further analysis on our data.\n\"\"\"\n#Hillshade at 9am values across forest types.\nsns.boxplot(y=df_forest['Hillshade_9am'],x=df_forest['Cover_Type']);\n\"\"\"\n* Hillshade at 9am values across forest types lie between 200 and 250.\n\"\"\"\n#Hillshade at noon values across forest types.\nsns.boxplot(y=df_forest['Hillshade_Noon'],x=df_forest['Cover_Type']);\n\"\"\"\n* Hillshade at noon values across forest types are similar, lying between 220 to 240.\n\"\"\"\n#Hillshade at 3pm values across forest types.\nsns.boxplot(y=df_forest['Hillshade_3pm'],x=df_forest['Cover_Type']);\n\"\"\"\n* Hillshade at 3pm values across forest types vary between 100 to 150.\n\"\"\"\n\"\"\"\n* This shows that hillshade values at 9 am and noon are in similar range of around 200 to 250, while hillshade values at 3pm are lower,in the range of 100 to 150 with rspect to various forest cover types.\n\"\"\"\n\"\"\"\n**Now we will explore the variation of various features and then combine it with forest cover types to get a wholesome final idea on the area of interest.**\n\"\"\"\n#Elevation values across wilderness areas.\na2=sns.boxplot(y=df_forest['Elevation'],x=df_forest['Wild_area']);\na2.set_xticklabels(a2.get_xticklabels(),rotation=15);\n\"\"\"\n* The area with the highest elevation is Neota wilderness area.\n\n* This is followed by Rawah and Comanche peak areas. The difference in the elevation of these regions are not very distinct.\n\n* Cache la Poudre area has the lowest elevation and is quite distinct from others.\n\n* This might influence the vegetation type in these regions. \n\"\"\"\n#Elevation values across wilderness areas and forest cover types.\na3=sns.catplot(data=df_forest,x='Wild_area',y=\"Elevation\",hue=\"Cover_Type\");\na3.set_xticklabels(rotation=65, horizontalalignment='right');\n\"\"\"\n* This plot shows that the forest cover type 7(Krummholz) which is a high elevataion forest cover,is absent in the low elevation Cache la Poudre area.\n\n* 4(Cottonwood\/willow) tree is present only in this low elevation region.\n\n* It is clear that the point of highest elevation is present in Comanche Peak region eventhough Neota area has the highest median elevation.\n\n* Krummholz forest type is the only forest cover type present from 3500m to 3750m elevation. \n\"\"\"\n#Horizontal distance to fire points across wilderness areas.\na4=sns.boxplot(data=df_forest,x='Wild_area',y=\"Horizontal_Distance_To_Fire_Points\");\na4.set_xticklabels(a4.get_xticklabels(),rotation=15);\n\"\"\"\n* Cache la Poudre area is closest to firepoints as seen from the plot.This means that the vegetation here is more prone to fire.\n\n* Rawah area is the farthest from firepoints.\n\"\"\"\n#Horizontal distance to fire points across wilderness areas and forest cover types.\na5=sns.catplot(data=df_forest,x='Wild_area',y=\"Horizontal_Distance_To_Fire_Points\",hue=\"Cover_Type\");\na5.set_xticklabels(rotation=65, horizontalalignment='right');\n\"\"\"\n* From this plot we can understand that in Rawah area, cover type 2(Lodgepole Pine) is present in large frequency farthest from firepoints.\n\n* In Comanche peak area 7(Krummholz) is farthest from firepoint while in Neota area, this forest cover type is closer to firepoints.\n\n* Vegetation in Cache la Poudre area are relatively closer to fire points.\n\"\"\"\n##Horizontal distance to roadways across wilderness areas.\na6=sns.boxplot(y=df_forest['Horizontal_Distance_To_Roadways'],x=df_forest['Wild_area']);\na6.set_xticklabels(a6.get_xticklabels(),rotation=15);\n\"\"\"\n* This plot shows that Rawah area is the farthest from roadways and Cache la Poudre area is the closest to roadways.\n\n* Neota area, even though is at a higher median elevation than other areas, is closer to roadways.\n\"\"\"\n#Relationship between wild areas and distance to roadways across forest cover types.\na7=sns.catplot(data=df_forest,x='Wild_area',y=\"Horizontal_Distance_To_Roadways\",hue=\"Cover_Type\");\na7.set_xticklabels(rotation=65, horizontalalignment='right');\n\"\"\"\n* This graph further clarifies our analysis on the relationship of these features.\n\n* 7(Krummholz) forest cover type is in general far from roadways.\n\n`Roadways are important areas of human interaction and movement. So, it would be logical to see the relationship between distance to roadways and firepoint.`\n\"\"\"\n#Elevation values across horizontal distance to fire points.\nsns.lmplot(data= df_forest,x='Elevation',y='Horizontal_Distance_To_Fire_Points',scatter=False);\n#Elevation values across horizontal distance to roadways and elevation.\nsns.lmplot(data=df_forest,x='Elevation',y='Horizontal_Distance_To_Roadways',scatter=False);\n#Relationship between horizontal distance to roadways and firepoint.\nsns.lmplot(data=df_forest,x='Horizontal_Distance_To_Fire_Points',y='Horizontal_Distance_To_Roadways',scatter=False);\n\"\"\"\n* The above three plots shows that with elevation, distance to firepoints and roadways on average, increases. \n\n* It also shows that, on average, horizontal distance to fire points and distance to roadways are directly proportional.\n\n* This means that these features, namely, Elevation, horizontal distance to roadways and horizontal distance to firepoints are closely related to each other and have a positive correlation.\n\n`Now, let us analyse this further so as to a better picture.`\n\"\"\"\n#Relationship between distance to firepoints and roadways across wilderness types.\nsns.lmplot(data=df_forest,x='Horizontal_Distance_To_Fire_Points',y='Horizontal_Distance_To_Roadways',scatter=False,hue=\"Wild_area\");\n\"\"\"\nFrom this plot, we can understand that the relationship between distance to firepoints and distance to roadways are directly proportional, except in Cache la Poudre area.\n\"\"\"\n#Relationship between distance to firepoints and roadways across forest cover types.\nsns.lmplot(data=df_forest,x='Horizontal_Distance_To_Fire_Points',y='Horizontal_Distance_To_Roadways',scatter=False,hue=\"Cover_Type\");\n\"\"\"\nThis graph explains the exception of Cache la Poudre area in the previous graph. \n\n* This is beacuse 4(Cottonwood\/Willow) is present only in this region and it shows neagtive correlation between firepoint and roadways distances.\n* This must be viewed in the background that Cache la Poudre area is closest to roadways and firepoints.\n\"\"\"\n\"\"\"\n* On average, we can say that horizontal distance to fire points and horizontal distance are directly proportional.This might be due to human influence on fire point.\n\n* 4(Cottonwood\/Willow) forest cover type and consequently Cache la Poudre area does not follow the normal trend even though this area is closest to roadways and firepoints.\n\n* This might be because this forest type might be innately highly inflammable and does not require human interference for starting a fire.\n\"\"\"\n##Horizontal distance to hydrology across wilderness areas.\na8=sns.boxplot(y=df_forest['Horizontal_Distance_To_Hydrology'],x=df_forest['Wild_area']);\na8.set_xticklabels(a8.get_xticklabels(),rotation=15);\n\"\"\"\n* All the forest areas considered are more or less equally distanced from water source.\n* Neota area is slightly far fom surface water source on average.\n\"\"\"\n#Relationship between wild areas and distance to hydrology across forest cover types.\na9=sns.catplot(data=df_forest,x='Wild_area',y=\"Horizontal_Distance_To_Hydrology\",hue=\"Cover_Type\");\na9.set_xticklabels(rotation=65, horizontalalignment='right');\n\"\"\"\n* We observe that the forest cover type 7(Kremmholz) is more spread out from 0 to 1000 distance units in each of the wilderness areas(except in Cache la Poudre).\n\"\"\"\n#Elevation values across horizontal distance to fire points.\nsns.lmplot(data= df_forest,x='Elevation',y='Horizontal_Distance_To_Hydrology',scatter=False);\n\"\"\"\n* The above plots shows that elevation and horizontal distance to hydrology are directly proportional. \n\n* This, coupled with the previous plots shows that elevation, horizontal distances to roadways, surface water features and firepoints are directly proprtional on average and has a strong influence on the forest cover type and distribution in four different wilderness areas.\n\"\"\"\n\"\"\"\nNow let us explore the features which were seen not to change much with forest cover type.\n\"\"\"\n##Vertical distance to hydrology across wilderness areas.\na10=sns.boxplot(y=df_forest['Vertical_Distance_To_Hydrology'],x=df_forest['Wild_area']);\na10.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\n* All the wilderness areas show similar vertical distance to surface water features at a mean of around 50 units.\n\"\"\"\n#Relationship between wild areas and vertical distance to hydrology across forest cover types.\na11=sns.catplot(data=df_forest,x='Wild_area',y=\"Vertical_Distance_To_Hydrology\",hue=\"Cover_Type\");\na11.set_xticklabels(rotation=65, horizontalalignment='right');\n\"\"\"\n* As in the previous graph, the difference between various wilderness areas is not very distinct.\n\"\"\"\n##Hillshade at 9am across wilderness areas.\na12=sns.boxplot(y=df_forest['Hillshade_9am'],x=df_forest['Wild_area']);\na12.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\n##This shows that the median values of hillshade at 9am occurs in the range 200-250 with very less variation among various wilderness areas.\n\"\"\"\n##Hillshade at noon across wilderness areas.\na13=sns.boxplot(y=df_forest['Hillshade_Noon'],x=df_forest['Wild_area']);\na13.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\n* This shows that the median values of hillshade at noon occurs in the range 200-240 with very less variation among various wilderness areas.\n\"\"\"\n##Hillshade at 3pm across wilderness areas.\na14=sns.boxplot(y=df_forest['Hillshade_3pm'],x=df_forest['Wild_area']);\na14.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\n* This shows that the median values of hillshade at 3pm occurs in the range 100-150 with very less variation among various wilderness areas.\n\"\"\"\n##Slope values across wilderness areas.\na15=sns.boxplot(y=df_forest['Slope'],x=df_forest['Wild_area']);\na15.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\n* This shows that the median values of slope occurs in the range 10-20 degrees with very less variation among various wilderness areas.\n\"\"\"\n##Aspect values across wilderness areas.\na16=sns.boxplot(y=df_forest['Aspect'],x=df_forest['Wild_area']);\na16.set_xticklabels(a10.get_xticklabels(),rotation=15);\n\"\"\"\nThis shows that the median values of aspect occurs in the range 50-150 degrees.\n\"\"\"\n\"\"\"\n* Since the above features: hillshade at 9am,hillshade at noon,hillshade at 3pm,slope and aspect are found to not vary with forest cover type and wilderness area,further analysis of these features might not be required.\n\"\"\"\n\"\"\"\n# Conclusion\n\"\"\"\n\"\"\"\n**We can infer the following conclusions about various forest cover types:**\n\"\"\"\n\"\"\"\n`1-Spruce\/Fir`\n\"\"\"\n\"\"\"\n* *Present in all wilderness areas except Cache la Pourde, it is present in the highest frequency in the Rawah wilderness area.*\n\n* *It occurs at a relatively high elevation of around 3125m, second only to Krummholz forest type.*\n\n* *It is present in the highest frequency in soil type 29(Como - Legault families complex, extremely stony), but is present in other soil types as well.*\n\n* *It is present relatively farther from fire points and roadways. This could mean that this is a high altitude tree that has less human interference.*\n\n* *It is not very far from surface water sources, but not as close to water as Cottonwood\/Willow.*\n\"\"\"\n\"\"\"\n`2-Lodgepole Pine`\n\"\"\"\n\"\"\"\n* *This is the only forest cover type that is present in all the wilderness areas, present in maximum frequency in Rawah wilderness area and minimum in Cache la Poudre.*\n\n* *It occurs at a relatively medium median elevation of 2875m.*\n\n* *It is present in the highest frequency in soil type 29(Como - Legault families complex, extremely stony).*\n\n* *It is present relatively farther from fire points and roadways like Spruce\/Fir.*\n\n* *It is present at similar distance to surface water features as Spruce\/Fir.*\n\"\"\"\n\"\"\"\n`3-Ponderosa Pine`\n\"\"\"\n\"\"\"\n* *This forest cover type is present only in Cache la Poudre and Comanche Peak areas, with highest frequency in Cache la Poudre area.*\n\n* *It is a relatively low elevation forest type.*\n\n* *It is present in the highest frequency in soil type 10(Bullwark - Catamount families - Rock outcrop complex, rubbly).*\n\n* *It is present close to firepoints and roadways. It along with Cottonwood\/Willow is present in maximum frequency is present in Cache la Poudre.*\n\n* *The horizontal distance to surface water features is low, indicating the existence of this vegetation close to rivers, lakes or other surface water features.*\n\"\"\"\n\"\"\"\n`4-Cottonwood\/Willow`\n\"\"\"\n\"\"\"\n* *This forest cover type is present only in Cache la Poudre.*\n\n* *It is a relatively low elevation forest type.*\n\n* *It is present in the highest frequency in soil type 3( Haploborolis - Rock outcrop complex, rubbly).*\n\n* *It is present close to firepoints and roadways but these values are negatively correlated in this cover type.This is unlike other forest types,where distance to firepoint and distance to roadways are directly proportional.This property could be due to the innate inflammability of Cottonwood tree parts.*\n\n* *The horizontal distance to surface water features is the lowest, indicating the existence of this vegetation close to rivers, lakes or other surface water features.*\n\"\"\"\n\"\"\"\n`5-Aspen`\n\"\"\"\n\"\"\"\n* *Comanche Peak area has the highest frequency of this forest cover. It is present in Rawah area, but absent in the other two areas.*\n\n* *It is a relatively medium elevation forest type.*\n\n* *It is present in the highest frequency in soil type 30(Como family - Rock land - Legault family complex, extremely stony).*\n\n* *It is present relatively close to firepoints and roadways.*\n\n* *The horizontal distance to surface water features is also relatively low.*\n\"\"\"\n\"\"\"\n`6-Douglas-fir`\n\"\"\"\n\"\"\"\n* *Cache la Poudre area has the highest frequency of this forest cover. It is present in Comanche Peak area.*\n\n* *It is a relatively low elevation forest type.*\n\n* *It is present in the highest frequency in soil type 10(Bullwark - Catamount families - Rock outcrop complex, rubbly).*\n\n* *It is present close to firepoints and roadways.*\n\n* *The horizontal distance to surface water features is also low.*\n\"\"\"\n\"\"\"\n`7-Krummholz`\n\"\"\"\n\"\"\"\n* *A relatively more widely distributed forest cover type, it is present in the highest frequency in Comanche Peak area*\n\n* *It is the forest type present in the highest elevations. The median elevation is 3375m.*\n\n* *It is present in the highest frequency in soil type 38(Leighcan - Moran families - Cryaquolls complex, extremely stony).*\n\n* *It is present farthest from firepoints and roadways.*\n\n* *The horizontal distance to surface water features is also the highest.*\n\"\"\"\n\"\"\"\n**This detailed analysis leaves us with a complete picture of the features of various forest types and wilderness areas.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9cd898c01ac2c4'}"}
{"id":"87191","text":"\"\"\"\n<h4> The goal of this kernal is basicly to scrutinize articles to asses similaries between sentences containing vaccines and\/therapeutics by following steps bellow:<\/h4>\n\n> Import required libraries\n\n> Import universal sentence encoder\n\n> Import the data\n\n> Data cleansing and preprocessing\n\n> Computing sentence similarity-matrix\n\n**Import required libraries and universal sentence encoder**\n\"\"\"\nimport numpy as np\nimport json\nimport os\nfrom tqdm import tqdm\ndata_dir = '\/kaggle\/input\/CORD-19-research-challenge'\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport nltk\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\nimport tensorflow_hub as hub\nimport matplotlib.pyplot as plt\nmodule_url = \"https:\/\/tfhub.dev\/google\/universal-sentence-encoder\/1?tf-hub-format=compressed\"\nembed = hub.Module(module_url)\n\n\"\"\"\n**Import the data**\n\"\"\"\ndef get_json_data(folder):\n    text  =  \"\"\n    #title = \"\"\n    data = []\n    for txt in os.listdir(folder):\n        if not txt.startswith('.') and txt in ['biorxiv_medrxiv','comm_use_subset','custom_license','noncomm_use_subset']:\n            for filename in tqdm(os.listdir(f\"{folder}\/{txt}\/{txt}\")):\n                if not filename.startswith('.'):\n                    json_data =  json.load(open(f\"{folder}\/{txt}\/{txt}\/{filename}\",'rb'))\n                    for t in json_data['body_text']:            \n                        text += t['text']+'\\n\\n'\n\n    return text\ntxt_data = get_json_data(data_dir)\n\"\"\"\n**Data cleansing and preprocessing**\n\nFor better understanding the data is crisual to make the data clean by removing stopwords and choosing sentences containing vaccines and\/ therapeutics\n\"\"\"\nprint('sentences containing vaccines or therapeutics ...')\ndoc = \"\"\nfor sentnece in txt_data.split('\\n'):\n    if('vaccines' in sentnece) or ('therapeutics' in sentnece):\n        #word_tokens = word_tokenize(sentnece)\n        doc +=sentnece \n\nprint('Removing stopwords ...')\n\nstop_words = set(stopwords.words('english'))\ntext = \"\"\nfor i in doc.split(' '):\n    if i not in stop_words:\n        text += ' ' + i.lower()\nCorpus = []\nprint('Focusing on short sentences for visualization  ...')\nfor i in text.split(','):\n    if ('vaccines' in i) or ('therapeutics' in i): \n        if len(i.split(' ')) < 15:\n            Corpus.append(i)\n\"\"\"\n**Computing sentence similarity-matrix**\n\nTo simplify and better visualize the result the first 10 sentences are choosen feel free to increase sentences.\n\"\"\"\nmessages2 = Corpus[:10]\nsimilarity_input_placeholder = tf.placeholder(tf.string, shape=(None))\nsimilarity_message_encodings = embed(similarity_input_placeholder)\nwith tf.compat.v1.Session()  as session:\n    session.run(tf.global_variables_initializer())\n    session.run(tf.tables_initializer())\n    message_embeddings_ = session.run(similarity_message_encodings, feed_dict={similarity_input_placeholder: messages2})\n\n    corr = np.inner(message_embeddings_, message_embeddings_)\n    print(corr)\n    def heatmap(x_labels, y_labels, values):\n        fig, ax = plt.subplots()\n        im = ax.imshow(values)\n        # We want to show all ticks...\n        ax.set_xticks(np.arange(len(x_labels)))\n        ax.set_yticks(np.arange(len(y_labels)))\n        # ... and label them with the respective list entries\n        ax.set_xticklabels(x_labels)\n        ax.set_yticklabels(y_labels)\n        # Rotate the tick labels and set their alignment.\n        plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", fontsize=10,\n             rotation_mode=\"anchor\")\n        # Loop over data dimensions and create text annotations.\n        for i in range(len(y_labels)):\n            for j in range(len(x_labels)):\n                text = ax.text(j, i, \"%.2f\"%values[i, j],\n                               ha=\"center\", va=\"center\", color=\"w\", fontsize=6)\n\n        fig.tight_layout()\n        plt.show()\n    heatmap(messages2, messages2, corr)\n","meta":"{'source': 'AI4Code', 'id': '9fe7b8a37a014b'}"}
{"id":"58244","text":"\"\"\"\nThis is a fine-tuning notebook which uses EfficientNet-b0 imagenet pretrained model as backbone. You can use any model from the `timm` library. Available models can be found via the `timm.list_models()` function.\n\nThe models can be used as a backbone in the ongoing [Shopee - Price Match Guarantee](https:\/\/www.kaggle.com\/c\/shopee-product-matching\/) Challange.\n\"\"\"\n!pip install timm\n\"\"\"\n# Imports\n\"\"\"\nimport os\nimport random\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport torch\n\nimport cv2\nimport albumentations\n\nimport timm\nBASE_DATA_DIR = Path(\"..\/input\/shopee-product-detection\/\")\n\ndf_train = pd.read_csv(BASE_DATA_DIR \/ \"train.csv\")\ndf_test = pd.read_csv(BASE_DATA_DIR \/ \"test.csv\")\n\ndf_train = df_train.loc[~df_train.filename.isin([\"64faf0b221af4767ba8c167b228fde00.jpg\", \n                                                 \"d946ee19ac1d2997bac5f18ce75656cb.jpg\"])].reset_index(drop=True)\ncounts = df_train.category.value_counts()\ndf_train.category.max(), df_train.category.min()\nplt.figure(figsize=(16, 10))\nplt.bar(counts.index, counts)\nplt.xticks(range(42));\n\nplt.show()\n\"\"\"\n# Utilities\n\"\"\"\nimport time\nfrom contextlib import contextmanager\n\nLOGS_PATH = Path(\"logs\")\nLOGS_PATH.mkdir(exist_ok=True)\n\n\ndef init_logger(log_file=LOGS_PATH \/ 'train.log'):\n    from logging import getLogger, INFO, FileHandler,  Formatter,  StreamHandler\n    logger = getLogger(__name__)\n    logger.setLevel(INFO)\n    handler1 = StreamHandler()\n    handler1.setFormatter(Formatter(\"%(message)s\"))\n    handler2 = FileHandler(filename=log_file)\n    handler2.setFormatter(Formatter(\"%(message)s\"))\n    logger.addHandler(handler1)\n    logger.addHandler(handler2)\n    return logger\n\n\nLOGGER = init_logger()\n\n\n@contextmanager\ndef timer(name):\n    t0 = time.time()\n    LOGGER.info(f'[{name}] start')\n    yield\n    LOGGER.info(f'[{name}] done in {time.time() - t0:.0f} s.')\n\"\"\"\n# Simple Visualization\n\"\"\"\nBASE_IMG_DIR = Path(\"..\/input\/shopee-product-detection\/train\/train\/\")\n\ndef read_img_and_cvt_format(img_path, clr_format=cv2.COLOR_BGR2RGB):\n    return cv2.cvtColor(cv2.imread(img_path), clr_format)\n\ndef visualize_batch(img_ids, labels):\n    \n    plt.figure(figsize=(16, 12))\n    \n    for idx, (img_id, label) in enumerate(zip(img_ids, labels)):\n        plt.subplot(3, 3, idx + 1)\n        img_fn = str(BASE_IMG_DIR \/ img_id)\n        img = read_img_and_cvt_format(img_fn)\n        plt.imshow(img)\n        plt.title(f\"Class: {label}\", fontsize=9)\n        plt.axis(\"off\")\n        \n    plt.show()\ndf_train.columns\nsampled_df = df_train.sample(9)\nimg_ids = sampled_df[\"filename\"].values\nlabels = sampled_df[\"category\"].values\n\nvisualize_batch(img_ids, labels)\n\"\"\"\n# Dataset\n\"\"\"\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\nclass ShopeeDataset(Dataset):\n    \n    def __init__(self, image_paths, labels=None, transform=None):\n        \n        self.image_paths = image_paths\n        self.labels = labels\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.image_paths)\n    \n    def __getitem__(self, idx):\n        \n        img_filepath = self.image_paths[idx]\n        img = read_img_and_cvt_format(img_filepath)\n        if self.transform:\n            img = self.transform(image=img)[\"image\"]\n        \n        label = 0\n        if self.labels is not None:\n            label = torch.tensor(self.labels[idx]).long()\n        return img, label\n\ntrain_img_paths = [f\"{BASE_IMG_DIR}\/{img_id}\" for img_id in df_train[\"filename\"].values]\ntrain_dataset = ShopeeDataset(image_paths=train_img_paths, \n                               labels=df_train[\"category\"].values,\n                               transform=None)\n\nfor i in range(1):\n    img, label = train_dataset[i]\n    \n    plt.title(f\"Label: {label}\")\n    plt.imshow(img)\n\nplt.show()\nlen(df_train.category.unique())\n\"\"\"\n# Config\n\"\"\"\nclass Config:\n    \n    model_name = \"efficientnet_b0\" # resnet34\n    n_epochs = 10\n    batch_size = 32\n    img_size = 512\n    n_classes = len(df_train.category.unique())\n    lr = 1e-3\n    weight_decay = 1e-6\n    gradient_accumulation_steps = 1\n    max_grad_norm = 1000\n    seed = 42\n    scheduler = \"\"\n    n_fold = 1\n    train_fold = [0, 1, 2, 3, 4]\n    train = True\n    print_every = 100\n    num_workers = 4\n    \n\ndef seed_torch(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\nseed_torch(seed=Config.seed)\n\"\"\"\n# Classifier\n\"\"\"\nimport torch.nn as nn\n\nclass Classifier(nn.Module):\n    \n    def __init__(self, model_name, pretrained=False):\n        super(Classifier, self).__init__()\n        \n        self.model = timm.create_model(model_name, pretrained=pretrained)\n        if model_name.startswith(\"eff\"):\n            n_features = self.model.classifier.in_features\n            self.model.classifier = nn.Linear(n_features, Config.n_classes)\n        else:    \n            n_features = self.model.fc.in_features\n            self.model.fc = nn.Linear(n_features, Config.n_classes)\n        \n    def forward(self, x):\n        return self.model(x)\n\"\"\"\n# Augmentations\n\"\"\"\nfrom albumentations.pytorch import ToTensorV2\nfrom torchvision import transforms as T\n\ndef get_train_transforms():\n    return albumentations.Compose([\n        albumentations.Resize(\n            Config.img_size, Config.img_size),\n        albumentations.Transpose(),\n        albumentations.HorizontalFlip(),\n        albumentations.VerticalFlip(),\n        albumentations.ShiftScaleRotate(),\n        albumentations.Normalize(\n            mean=[0.485, 0.456, 0.406], \n            std=[0.229, 0.224, 0.225]),\n        albumentations.Cutout(num_holes=8, max_h_size=32, max_w_size=32, fill_value=0, p=0.5),\n        ToTensorV2(),\n    ])\n\n\ndef get_test_transforms():\n    \n    return albumentations.Compose([\n        albumentations.Resize(Config.img_size, Config.img_size),\n        albumentations.Normalize(mean=[0.485, 0.456, 0.406], \n                  std=[0.229, 0.224, 0.225]),\n        ToTensorV2()\n    ])\n\n\"\"\"\n# Metric Tracking\n\"\"\"\nimport math\nimport time\n\n\nclass AverageMeter:\n    \n    def __init__(self):\n        self.reset()\n    \n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n    \n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum \/ self.count\n        \n        \ndef as_minutes(s):\n    m = math.floor(s \/ 60)\n    s -= m * 60\n    return f\"{m}m {s}s\"\n\n\ndef time_since(since, percent):\n    now = time.time()\n    s = now - since\n    es = s \/ percent\n    rs = es - s\n    return f\"{as_minutes(s)} (remain {as_minutes(rs)})\"\ndef train_step(model, data_loader, criterion, optimizer, epoch, scheduler, device):\n    \"\"\"\n    There is no scheduler update currently.\n    \"\"\"\n    batch_time = AverageMeter()\n    data_time = AverageMeter()\n    losses = AverageMeter()\n    # scores = AverageMeter()\n    \n    model.train()\n    start = end = time.time()\n    # global_step = 0\n    total_len = len(data_loader)\n    \n    for step, (images, labels) in enumerate(data_loader):\n        \n        data_time.update(time.time() - end)\n        images = images.to(device)\n        labels = labels.to(device)\n        batch_size = labels.size(0)\n        preds = model(images)\n        loss = criterion(preds, labels)\n        losses.update(loss.item(), batch_size)\n        \n        if Config.gradient_accumulation_steps > 1:\n            loss = loss \/ Config.gradient_accumulation_steps\n        \n        loss.backward()\n        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), \n                                                   Config.max_grad_norm)\n        if (step + 1) % Config.gradient_accumulation_steps == 0:\n            optimizer.step()\n            optimizer.zero_grad()\n            scheduler.step()\n            # global_step += 1\n        \n        batch_time.update(time.time() - end)\n        end = time.time()\n        if step % Config.print_every == 0 or step == (total_len - 1):\n            print(f\"Epoch: [{epoch+1}][{step}\/{total_len}] \"\n                  f\"Data: {data_time.val:.3f} ({data_time.avg:.3f}) \"\n                  f\"Batch: {batch_time.val:.3f} ({batch_time.avg:.3f}) \"\n                  f\"Elapsed: {time_since(start, float(step + 1) \/ (total_len))} \"\n                  f\"Loss: {losses.val:.5f}({losses.avg:.5f}) \"\n                  f\"Grad: {grad_norm:.4f}\" # LR: {lr:.6f}\n                 )\n        \n    return losses.avg\n            \n\ndef valid_step(model, data_loader, criterion, device):\n    \n    batch_time = AverageMeter()\n    data_time = AverageMeter()\n    losses = AverageMeter()\n    scores = AverageMeter()\n    \n    model.eval()\n    start = end = time.time()\n    total_len = len(data_loader)\n    predictions = []\n    \n    for step, (images, labels) in enumerate(data_loader):\n        data_time.update(time.time() - end)\n        images = images.to(device)\n        labels = labels.to(device)\n        batch_size = labels.size(0)\n        \n        with torch.no_grad():\n            preds = model(images)\n        \n        loss = criterion(preds, labels)\n        losses.update(loss.item(), batch_size)\n        predictions.append(preds.softmax(1).cpu().numpy())\n        \n        if Config.gradient_accumulation_steps > 1:\n            loss = loss \/ Config.gradient_accumulation_steps\n            \n        batch_time.update(time.time() - end)\n        end = time.time()\n        \n        if step % Config.print_every == 0 or step == (total_len - 1):\n            print(f\"Eval: [{step}\/{total_len}] \"\n                  f\"Data: {data_time.val:.3f} ({data_time.avg:.3f}) \"\n                  f\"Batch: {batch_time.val:.3f} ({batch_time.avg:.3f}) \"\n                  f\"Elapsed: {time_since(start, float(step + 1) \/ total_len)} \"\n                  f\"Loss: {losses.val:.5f} ({losses.avg:.5f})\"\n                 )\n    \n    predictions = np.concatenate(predictions)\n    return losses.avg, predictions\n# !rm -rf models\nimport torch.optim as optim\nfrom sklearn.metrics import accuracy_score, classification_report\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nMODELS_DIR = Path(\"models\")\nMODELS_DIR.mkdir(exist_ok=False)\n\"\"\"\n# Train Loop\n\"\"\"\ndef train_loop(df_tr, df_val):\n\n    train_img_paths = [f\"{BASE_IMG_DIR}\/{img_id}\" for img_id in df_tr[\"filename\"].values]\n    valid_img_paths = [f\"{BASE_IMG_DIR}\/{img_id}\" for img_id in df_val[\"filename\"].values]\n    \n    train_dataset = ShopeeDataset(\n        train_img_paths, \n        labels=df_tr[\"category\"].values, \n        transform=get_train_transforms()\n    )\n    \n    valid_dataset = ShopeeDataset(\n        valid_img_paths,\n        labels=df_val[\"category\"].values,\n        transform=get_test_transforms()\n    )\n    \n    train_data_loader = DataLoader(\n        train_dataset, batch_size=Config.batch_size, \n        shuffle=True, num_workers=Config.num_workers\n    )\n    valid_data_loader = DataLoader(\n        valid_dataset, batch_size=Config.batch_size, \n        shuffle=False, num_workers=Config.num_workers\n    )\n    \n    model = Classifier(Config.model_name, pretrained=True)\n    model.to(device)\n    # amsgrad = False\n    optimizer = optim.Adam(model.parameters(), \n                           lr=Config.lr, \n                           weight_decay=Config.weight_decay)\n    criterion = nn.CrossEntropyLoss()\n\n        \n    scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, \n                                                                     T_0=10, \n                                                                     T_mult=1, \n                                                                     eta_min=1e-6, \n                                                                     last_epoch=-1)\n    \n    best_score = 0.0\n    best_loss = np.inf\n\n    for epoch in range(Config.n_epochs):\n        \n        start_time = time.time()\n        avg_epoch_loss = train_step(model, \n                                    train_data_loader, \n                                    criterion, \n                                    optimizer, \n                                    epoch, \n                                    scheduler=scheduler, \n                                    device=device)\n\n        avg_valid_loss, valid_preds = valid_step(model, \n                                                 valid_data_loader, \n                                                 criterion, \n                                                 device)\n        valid_labels = df_val[\"category\"].values\n        accuracy = accuracy_score(valid_labels, valid_preds.argmax(1))\n        classification_result = classification_report(valid_labels, \n                                                      valid_preds.argmax(1))\n        elapsed = time.time() - start_time\n        LOGGER.info(f\"Epoch: {epoch+1} - avg_epoch_loss: {avg_epoch_loss:.5f} - avg_val_loss: {avg_valid_loss:.5f} - time: {elapsed:.0f}s\")\n        LOGGER.info(f\"Epoch: {epoch+1} - Accuracy: {accuracy}\")\n        print(classification_result)\n        \n        if accuracy > best_score:\n            best_score = accuracy\n            LOGGER.info(f\"Epoch: {epoch+1} - Save best score: {best_score:.4f} Model\")\n            torch.save({\n                \"model\": model.state_dict(),\n                \"preds\": valid_preds\n            }, str(MODELS_DIR \/ f\"{Config.model_name}_best.pth\"))\n            \n#     check_point = torch.load(str(MODELS_DIR \/ f\"{Config.model_name}_fold_{fold}_best.pth\"))\n#     valid_folds[[str(c) for c in range(5)]] = check_point[\"preds\"]\n#     valid_folds[\"preds\"] = check_point[\"preds\"].argmax(1)\n#     return valid_folds\n\nfrom sklearn.model_selection import train_test_split\ndf_train_, df_valid_ = train_test_split(df_train, test_size=0.2, random_state=42)\nlen(df_train_.category.unique()), len(df_valid_.category.unique())\ntrain_loop(df_train_, df_valid_)","meta":"{'source': 'AI4Code', 'id': '6b9454f48125c2'}"}
{"id":"85206","text":"# 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 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\ntrain = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-comment-classification-challenge\/train.csv.zip')\ntest = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-comment-classification-challenge\/test.csv.zip')\ntest_labels = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-comment-classification-challenge\/test_labels.csv.zip')\nword_to_vec_map = {}\nwords = set()\nwith open('..\/input\/glove-global-vectors-for-word-representation\/glove.6B.50d.txt') as file:\n    for line in file:\n        values = line.strip().split()\n        curr_word = values[0]\n        words.add(curr_word)\n        word_to_vec_map[curr_word] = np.array(values[1:], dtype = np.float64)\nlen(word_to_vec_map)\ntrain.shape, test.shape, test_labels.shape\ntrain.head(20)\n\"\"\"\nHere, the output variables are not exclusive. More than one can occur at same time. \n\"\"\"\ntest.head(20)\ntrain.info()\ntest.info()\n\"\"\"\nNo null values\n\"\"\"\ntrain_sentences = train['comment_text'].values\ntest_sentences = test['comment_text'].values\nfrom keras.preprocessing.text import Tokenizer\ntokenizer = Tokenizer(num_words = 10000)\nfrom keras.preprocessing.sequence import pad_sequences\nmax_seq_length = 1000\ntokenizer.fit_on_texts(train_sentences)\ntrain_sequences = tokenizer.texts_to_sequences(train_sentences)\ntest_sequences = tokenizer.texts_to_sequences(test_sentences)\npadded_seq_train = pad_sequences(train_sequences, maxlen = max_seq_length)\npadded_seq_test = pad_sequences(test_sequences, maxlen = max_seq_length)\nindex = tokenizer.word_index\nlen(index)\nembedding_matrix = np.zeros((len(index) + 1, 50))\nfor word, i in index.items():\n    temp = word_to_vec_map.get(word)\n    if temp is not None:\n        embedding_matrix[i] = temp\nclasses = ['toxic', 'severe_toxic', 'obscene', 'threat',\n       'insult', 'identity_hate']\ny = train[classes].values\nfrom sklearn.model_selection import train_test_split\nxTrain, xTest, yTrain, yTest = train_test_split(padded_seq_train, y, test_size = 0.3, random_state = 21)\nyTrain.shape\nfrom keras.models import Sequential\nfrom keras.layers import Embedding, Bidirectional, Dense, LSTM, GlobalMaxPooling1D, Dropout\nembed_layer = Embedding(len(index) + 1, 50, input_length = max_seq_length, weights = [embedding_matrix] )\nmodel = Sequential()\nmodel.add(embed_layer)\nmodel.add(Bidirectional(LSTM(50, return_sequences = True, dropout = 0.1, recurrent_dropout = 0.1)))\nmodel.add(GlobalMaxPooling1D())\nmodel.add(Dense(50, activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(6, activation = 'sigmoid'))\nmodel.summary()\nmodel.compile(loss='binary_crossentropy', optimizer = 'Adam', metrics = ['accuracy'])\nhistory = model.fit(xTrain, yTrain, epochs = 2, batch_size = 128, validation_split = 0.1)\nresult = model.evaluate(xTest,yTest)\npred = model.predict(padded_seq_test)\npred.shape\nsample = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-comment-classification-challenge\/sample_submission.csv.zip')\nsample.head()\ntest.head()\nsample[classes] = pred\nsample.head(20)\nsample.to_csv('submission.csv', index = False)","meta":"{'source': 'AI4Code', 'id': '9c590fbed711ec'}"}
{"id":"4148","text":"import numpy as np, pandas as pd\nimport matplotlib.pyplot as plt, seaborn as sns\nfrom tqdm import tqdm\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n### Data Loading\n\"\"\"\ndata = pd.read_csv(\"..\/input\/spotify-dataset-19212020-160k-tracks\/data.csv\")\n\"\"\"\nChecking if data loaded correctly.\n\"\"\"\ndata.head()\n\"\"\"\nChecking data's shape.\n\"\"\"\ndata.shape\n\"\"\"\n### Data Preprocessing\n\"\"\"\n\"\"\"\nLet's check if our data has any missing values.\n\"\"\"\ndata.isna().sum()\n\"\"\"\nThere is no missing data, which is fine for us!\n\"\"\"\n\"\"\"\n### Exploratory Data Analisys\n\"\"\"\n\"\"\"\nNow, we will vizualize our data, to understand, how music changed during the century.\n\"\"\"\nviz_data = data.drop(columns=['id', 'name', 'artists', 'release_date', 'year'])\n\nplt.figure(figsize=(50, 50))\nfor i in tqdm(np.arange(1, len(viz_data.columns))):\n    plt.subplot(7, 2, i)\n    sns.barplot(x=data.year,y=viz_data[viz_data.columns[i]])\n    plt.xticks(rotation=45);\nplt.show()\n\"\"\"\nAs can be seen from the plots, nowadays music became more energetic and popular. The loudness decreased and duration increased.\n\"\"\"\n\"\"\"\n#### Correlation\n\"\"\"\n\"\"\"\nLet's check if any features correlates with each other.\n\"\"\"\n\"\"\"\n#### Pearson Correlation\n\"\"\"\nplt.subplots(figsize=(12, 8))\nsns.heatmap(viz_data.corr(), annot=True, square=True)\nplt.show()\n\"\"\"\nAs we can see, loudness greatly correlates with energy\/accousticness and accousticness correlates with energy.\n\"\"\"\n\"\"\"\n### Feature Engineering\n\"\"\"\ndata.head(2)\n\"\"\"\nAs we will use our data to calculate the distances between the songs and our feature's data veries, we will create a function to normalize it.\n\"\"\"\ndef normalize_column(col):\n    max_d = data[col].max()\n    min_d = data[col].min()\n    data[col] = (data[col] - min_d)\/(max_d - min_d)\n\"\"\"\nNow, let's get all the numerical columns and normalize them.\n\"\"\"\nnum_types = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\nnum = data.select_dtypes(include=num_types)\n        \nfor col in num.columns:\n    normalize_column(col)\n\"\"\"\nLet's check if our data transformed correctly.\n\"\"\"\ndata.head(3)\n\"\"\"\nSeems like everything worked fine.\n\"\"\"\n\"\"\"\nThere is a probability, that songs from the different genres could have quite similar characteristics, and that's not fine. \n\"\"\"\n\"\"\"\nFor example, Nicki Minaj songs won't be an accurate recomendation for Slayer songs.\n\"\"\"\n\"\"\"\nThat's why we will create a new feature, which would differ the songs from different groups.\n\"\"\"\n\"\"\"\nWe will use KMeans clusterization with 10 clusters for this goal.\n\"\"\"\nfrom sklearn.cluster import KMeans\n\nkm = KMeans(n_clusters=10)\ncat = km.fit_predict(num)\ndata['cat'] = cat\nnormalize_column('cat')\n\"\"\"\nLet's check the result.\n\"\"\"\ndata.cat[:10]\n\"\"\"\nSeems like everything is fine, let's move on.\n\"\"\"\n\"\"\"\n### Recommendation System\n\"\"\"\n\"\"\"\nOur data has numeric features like acousticness, danceability, energy etc, we will use it to find the most similar songs for ours. \n\"\"\"\ncaya=data[data.name=='Come As You Are']\ncaya.head(3)\n\"\"\"\nAs there could be many versions of the same song (example above), we will always take the oldest version.\n\"\"\"\n\"\"\"\nNow, let's create a class which will make the recomendations for our songs.\n\"\"\"\n\"\"\"\nTo find the difference among the songs, we will calculate the manhattan distance between all of them. \n\"\"\"\n\"\"\"\nAnd, as the result, we will choose the songs with the smallest distances.\n\"\"\"\nclass SpotifyRecommender():\n    def __init__(self, rec_data):\n        #our class should understand which data to work with\n        self.rec_data_ = rec_data\n    \n    #if we need to change data\n    def change_data(self, rec_data):\n        self.rec_data_ = rec_data\n    \n    #function which returns recommendations, we can also choose the amount of songs to be recommended\n    def get_recommendations(self, song_name, amount=1):\n        distances = []\n        #choosing the data for our song\n        song = self.rec_data_[(self.rec_data_.name.str.lower() == song_name.lower())].head(1).values[0]\n        #dropping the data with our song\n        res_data = self.rec_data_[self.rec_data_.name.str.lower() != song_name.lower()]\n        for r_song in tqdm(res_data.values):\n            dist = 0\n            for col in np.arange(len(res_data.columns)):\n                #indeces of non-numerical columns\n                if not col in [1, 6, 12, 14, 18]:\n                    #calculating the manhettan distances for each numerical feature\n                    dist = dist + np.absolute(float(song[col]) - float(r_song[col]))\n            distances.append(dist)\n        res_data['distance'] = distances\n        #sorting our data to be ascending by 'distance' feature\n        res_data = res_data.sort_values('distance')\n        columns = ['artists', 'name']\n        return res_data[columns][:amount]\n\"\"\"\nLet's create the object of our SpotifyRecommender.\n\"\"\"\nrecommender = SpotifyRecommender(data)\n\"\"\"\n#### Nirvana - Come As You Are\n\"\"\"\nrecommender.get_recommendations('come as you are', 5)\n\"\"\"\nSeems like results are pretty logical, as all the songs have pretty similar genre and the sounding.\n\"\"\"\n\"\"\"\nLet's test our function on the other songs.\n\"\"\"\n\"\"\"\n#### Mot\u00f6rhead - Ace Of Spades \n\"\"\"\nrecommender.get_recommendations('ace of spades', 5)\n\"\"\"\n#### 50 Cent - In Da Club\n\"\"\"\nrecommender.get_recommendations('in da club', 5)\n\"\"\"\n#### Lil Skies - Red Roses (feat. Landon Cube)\n\"\"\"\nrecommender.get_recommendations('Red Roses (feat. Landon Cube)', 5)\n\"\"\"\nSeems like recommender works pretty fine and gives us really accurate recommendations.\n\"\"\"\n\"\"\"\n### That's all. Thank you for reading this notebook, you can upvote it, if you find it useful!\n\n\"\"\"\n\"\"\"\n### Good luck!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '07c59587f06b1e'}"}
{"id":"89967","text":"\"\"\"\n# Introduction\n\nThis is the third notebook in my series about machine learning. I previously wrote [ML Bootcamp: Intro to NumPy](https:\/\/www.kaggle.com\/rafidka\/ml-bootcamp-intro-to-numpy) and [Intro to Pandas](https:\/\/www.kaggle.com\/rafidka\/ml-bootcamp-intro-to-pandas). If you don't already know NumPy and pandas, you should still be able to follow this notebook and understand the basic ideas, though I still highly recommend that you read and experiment with the previous notebooks\n\nIn this notebook, I will take the reader through [matplotlib](https:\/\/matplotlib.org\/), which is the most famous package for visualization in Python. Machine learning deals with a huge amount of data and without proper insignt into the data, it is hard to come up with something useful. `matplotlib` supports a variety of [plot types](https:\/\/matplotlib.org\/gallery\/index.html) which can be exteremely useful within machine learning and outside it.\n\nFor good visualization we need good data. As such, I will mostly be using [Stack Overflow Developer Survey for 2019](https:\/\/www.kaggle.com\/mchirico\/stack-overflow-developer-survey-results-2019) throughout this notebook, except at the beginning where I will be using elementary mathematical functions.\n\"\"\"\n\"\"\"\n# Loading the Data\n\n\n\"\"\"\n\"\"\"\nLet's start by loading the Stack Overflow Developer Survey so we could employ it in the subsequent sections.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\ncomplete_survey = pd.read_csv(\"..\/input\/stack-overflow-developer-survey-results-2019\/survey_results_public.csv\")\ncomplete_survey_schema = pd.read_csv(\"..\/input\/stack-overflow-developer-survey-results-2019\/survey_results_schema.csv\")\n\"\"\"\nHaving load the complete survey, let's pick the some columns which are interesting to study:\n\"\"\"\nsurvey = complete_survey[[\n    'MainBranch',\n    'Hobbyist',\n    'OpenSourcer',\n    'Employment',\n    'Country',\n    'Student',\n    'EdLevel',\n    'UndergradMajor',\n    'DevType',\n    'YearsCode',\n    'Age1stCode',\n    'YearsCodePro',\n    'ConvertedComp',\n    'LanguageWorkedWith',\n    'Age',\n    'Gender'\n]]\n\"\"\"\n# Simple 2D Plots\n\nLet's start with a simple 2D plot. We use NumPy to generate 50 equally spaced X values between `-2*Pi` and `2*Pi`, and then calculate the sine of those points to draw the sine function.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n# Enable inline usage of matplotlib within the notebook. See for more information:\n# https:\/\/ipython.readthedocs.io\/en\/stable\/interactive\/magics.html#magic-matplotlib \n%matplotlib inline\n\nx1 = np.linspace(-2*np.pi, 2*np.pi, 50)\ny1 = np.sin(x1)\nplt.plot(x1, y1)\nplt.show()\n\"\"\"\n# Multilpe 2D Plots\n\nIn many cases, we need to plot multiple graphs on the same plot. We can do that easily with matplotlib.\n\"\"\"\nx2 = np.linspace(-2*np.pi, 2*np.pi, 50)\nplt.plot(x2, np.sin(x2))\nplt.plot(x2, np.cos(x2))\nplt.show()\n\"\"\"\nAs easy as that, just another call to the `plot` method and we have two graphs. However, we cannot easily tell which graph is for which function. We will see in the next section how we can enhance the graph by adding more features.\n\"\"\"\n\"\"\"\n# Enhancing Plots: Title, Labels, Legends, and Grid\n\nLet's first add legends to the graph so we can distinguish which curve belong to which function:\n\"\"\"\nx3 = np.linspace(-2*np.pi, 2*np.pi, 50)\nplt.plot(x3, np.sin(x3), label='sin(x)') # Notice the additional label argument.\nplt.plot(x3, np.cos(x3), label='cos(x)') # Notice the additional label argument.\nplt.legend() # You need this call for the legends to show.\nplt.show()\n\"\"\"\nThe plot above is nice, especially that it was generated by 5 lines of code. However, it misses multiple features that would be really helpful:\n\n1. The plot misses a title; we want to let the reader knows what the plot is about.\n2. The axes don't have labels. It is not clear what the horizontal and vertical axes represent.\n3. Lack of grid makes it harder to estimate values at certain points.\n\nWith a few additional calls, we can add those features.\n\n\"\"\"\nx4 = np.linspace(-2*np.pi, 2*np.pi, 50)\nplt.plot(x4, np.sin(x4), label='sin(x)')\nplt.plot(x4, np.cos(x4), label='cos(x)')\nplt.legend()\nplt.title(\"Comparison of sine and cosine\") # Add a title to the graph\nplt.xlabel(\"x\")                            # Add a label to the x-axis\nplt.ylabel(\"sin(x)\\ncos(x)\")               # Add a label to the y-axis\nplt.grid(True)                             # Enable grid\nplt.show()\n\"\"\"\n# Further Enhancements to Plots: Plot Style, Figure Size and Axes Limits\n\nWe might also want to change the format of the graphs just to add more clarity. This can be particularly useful with plots containing multiple curves. Let's try to do this. While at it, let's also add two more functions to make the plot more sophisticated.\n\"\"\"\nx5 = np.linspace(-2*np.pi, 2*np.pi, 50)\n\n# Notice the additional 'linestyle' and 'color' args.\nplt.plot(x5, np.sin(x5), linestyle='-', color='r', label='sin(x)')\nplt.plot(x5, np.cos(x5), linestyle='--', color='g', label='cos(x)')\nplt.plot(x5, x5**2, linestyle=':', color='b', label='x^2')          # Added the x-squared function.\nplt.plot(x5, np.exp(x5), linestyle='-.', color='y', label='cos(x)') # Added the exp(x) function.\n\nplt.legend()\nplt.title(\"Comparison of sine, cosine, x^2, and exp(x)\")\nplt.xlabel(\"x\")\nplt.ylabel(\"\"\"sin(x)\ncos(x)\nx^2\nexp(x)\"\"\")\nplt.grid(True)\nplt.show()\n\"\"\"\nAs you can see, by passing the `linestyle` and `color` optional arguments to the `plot()` method, we were able to format the curves differently. However, with the introduction of the exponetial function and `matplotlib` trying to guess the limits of the x- and y-axis, the sine and cosine functions are almost gone now. In such cases, we can manually specify those limits via the [xlim](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.xlim.html) and [ylim](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.ylim.html) functions. Let's also make the figure larger by employing the [figure](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure) method of [pyplot](https:\/\/matplotlib.org\/api\/pyplot_summary.html).\n\"\"\"\nplt.figure(figsize=(10, 8))              # Made the graph larger as we have more functions now.\n                                         # Notice that this call has to come before the calls to\n                                         # the plot() methods, as this call instructs matplotlib\n                                         # to start a new plot.\nplt.xlim(-2*np.pi, 2*np.pi)              # Manually specifying the limits of the x and y axes.\nplt.ylim(-5, 5)                          # This is necessary because the x^2 and the exp(x)\n                                         # functions grow large quickly, making the sine and\n                                         # cosine functions hard to notice.\n\n# Notice the additional 'linestyle' and 'color' args.\nplt.plot(x5, np.sin(x5), linestyle='-', color='r', label='sin(x)')\nplt.plot(x5, np.cos(x5), linestyle='--', color='g', label='cos(x)')\nplt.plot(x5, x5**2, linestyle=':', color='b', label='x^2')\nplt.plot(x5, np.exp(x5), linestyle='-.', color='y', label='cos(x)')\n\n\nplt.legend()\nplt.title(\"Comparison of sine, cosine, x^2, and exp(x)\")\nplt.xlabel(\"x\")\nplt.ylabel(\"\"\"sin(x)\ncos(x)\nx^2\nexp(x)\"\"\")\nplt.grid(True)\nplt.show()\n\"\"\"\n## Note About Formatting\n\nIf you find it too long to write the additional arguments for formatting, i.e. `color`, `linestyle`, etc., there is a third argument which you can pass (after the x and y arrays) which can combine multiple formatting styles in one value. For example, to specify a dotted green curve, you pass `'.g'` to the `plot()` method:\n\n\"\"\"\nx6 = np.linspace(-2*np.pi, 2*np.pi, 50)\nplt.figure(figsize=(10, 8))              # Made the graph larger as we have more functions now.\n                                         # Notice that this call has to come before the calls to\n                                         # the plot() methods, as this call instructs matplotlib\n                                         # to start a new plot.\n\n# Notice the additional 'linestyle' and 'color' args.\nplt.plot(x6, np.sin(x6), '.g', label='sin(x)')\n\nplt.legend()\nplt.title(\"Graph of sin(x)\")\nplt.xlabel(\"x\")\nplt.ylabel(\"sin(x)\")\nplt.grid(True)\nplt.show()\n\"\"\"\n# Bar Charts\n\nHaving generated some nice 2D plots, let's move on to a different plot type: [bar chart](https:\/\/en.wikipedia.org\/wiki\/Bar_chart). Bar charts are very useful to visualize categoral data. For this, let's use some real data from the Stack Overflow Developer Survey.\n\nTo plot a bar chart with matplotlib, we need to use the [bar](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar) method. To get a basic understanding of how this works, let's see the following example:\n\"\"\"\nplt.bar([1, 2, 3, 4], [10, 20, 30, 40])\n\"\"\"\nI am simply passing a list containing the numbers 1, 2, 3, and 4, which act as the categories of the plot, and then another sequence containing the height of each category, respectively.\n\nLet's now move to a more realistic example. Say we want to plot the number of respondants in each age group. We can use pandas's [groupby](https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/api\/pandas.DataFrame.groupby.html) method and find the [count](https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/api\/pandas.core.groupby.GroupBy.count.html#pandas.core.groupby.GroupBy.count) to find the count of each group.\n\"\"\"\nsurvey_with_age = survey.dropna(subset=['Age']) # First, drop rows which don't have a value in Age\nsurvey_by_age = survey_with_age.groupby(pd.cut(survey_with_age['Age'], np.arange(0, 101, 10)))['Age'].count()\nsurvey_by_age\ncats = list(map(lambda x: str(x), survey_by_age.index))\nvalues = survey_by_age.values\nplt.figure(figsize=(14, 8))\nplt.bar(cats, values)\n\n\"\"\"\n# Multiple Bar Charts\n\nIt is sometimes useful to have multiple bar charts for better comparison. For example, taking the respondants from the top 15 countries, what is the number of developers who are actively contributing to open source vs those who are not? Let's try to plot this. First, let's examine the `OpenSourcer` column to see the possibly values:\n\"\"\"\nsurvey['OpenSourcer'].unique()\n\n\"\"\"\nLet's use the value of `Once a month or more ofter` as a definition for actively contributing to open source, and the rest is an indicator of not actively contributing to open source.\n\nLet's first find the countries with top respondants to this servey:\n\"\"\"\ntop_countries = survey.groupby('Country')['Country'].count().sort_values(ascending=False).head(10)\ntop_countries\n\"\"\"\nNext, let's filter the data frame to those countries only:\n\"\"\"\n# Notice that we use .index to extract the country names, e.g. United States.\ntop_countries_names = top_countries.index\nsurvey_top_countries = survey[survey['Country'].isin(top_countries_names)]\n\n# verify that we indeed only has those countries.\nsurvey_top_countries['Country'].unique()\n\"\"\"\nNext, let's filter the data frame even further to respondans which are either actively or not actively contributing to open source:\n\"\"\"\nsurvey_top_countries_active_in_os = survey_top_countries[survey_top_countries['OpenSourcer'] == 'Once a month or more often']\nsurvey_top_countries_inactive_in_os = survey_top_countries[survey_top_countries['OpenSourcer'] != 'Once a month or more often']\n\n\n\"\"\"\nFinally, let's find the values of the bar charts and plot them.\n\"\"\"\nbar1_heights = survey_top_countries_active_in_os.groupby('Country')['Country'].count()[top_countries_names]\nbar2_heights = survey_top_countries_inactive_in_os.groupby('Country')['Country'].count()[top_countries_names]\n\nplt.figure(figsize=(14, 8))\nplt.bar(top_countries_names, bar1_heights, color='orange')\nplt.bar(top_countries_names, bar2_heights, color='blue')\n\n\"\"\"\nHmm, we only see one graph! The reason is that we plotted the taller bars before the shorter. Let's swap the order of plot:\n\"\"\"\nplt.figure(figsize=(14, 8))\nplt.bar(top_countries_names, bar2_heights, color='blue')\nplt.bar(top_countries_names, bar1_heights, color='orange')\n\n\"\"\"\nWhat if we want to the draw side adjacent to each others instead of overlapping? In this case, we need somoe manual processing here. Specifically:\n\n1. Instead of passing in categories, i.e. country names, as the first parameter to the `bar()` method, we pass x-coordinates. This way we can shift the bars to the left or right, depending on which set of bars we want to show.\n\n2. Now that we are passing in x-coordinates instead of the actual country names, we need to use the [set_xticks](https:\/\/matplotlib.org\/3.1.1\/api\/_as_gen\/matplotlib.axes.Axes.set_xticks.html) and [set_xticklabels](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.axes.Axes.set_xticklabels.html).\n\"\"\"\nplt.figure(figsize=(14, 8))\n\nwidth = 0.4 # A width of 1.0 spans the whole area between two consecutive\n            # tickts in the x-axis. Since we want to show two bars at each\n            # tick, the width should be less than 0.5 for each bar so bars\n            # from different tickts don't touch or overlap each other\nx = np.arange(len(top_countries_names))\nplt.bar(x - width\/2, bar2_heights, width=width, color='blue') # left-shifted\nplt.bar(x + width\/2, bar1_heights, width=width, color='orange') # right-shifted\n\n# Set the x-ticks and their labels.\nax = plt.axes()\nax.set_xticks(x)\nax.set_xticklabels(top_countries_names)\n\nplt.show()\n\"\"\"\nOne last thing we can do to improve the plot is to add legends:\n\"\"\"\nplt.figure(figsize=(14, 8))\n\nwidth = 0.4\nx = np.arange(len(top_countries_names))\nplt.bar(x - width\/2, bar2_heights, width=width, color='blue',\n        label=\"Not actively contributing to open source\") # Add label\nplt.bar(x + width\/2, bar1_heights, width=width, color='orange',\n        label=\"Actively contributing to open source\") # Add label\n\n# Set the x-ticks and their labels.\nax = plt.axes()\nax.set_xticks(x)\nax.set_xticklabels(top_countries_names)\nplt.legend() # Enable legends\n\nplt.show()\n\n\"\"\"\n# Pie Chart\n\"\"\"\nsurvey['EdLevel'].unique()\n\nsurvey_by_edlevel = survey.groupby('EdLevel')['EdLevel'].count().sort_values()\nsurvey_by_edlevel = survey_by_edlevel * 100 \/ survey_by_edlevel.sum() # convert to percentages\n\nlabels = list(map(lambda x: str(x), survey_by_edlevel.index))\nvalues = survey_by_edlevel.values\n\nplt.figure(figsize=(14, 8))\nplt.pie(values, labels=labels,\n        explode=[0.1] * len(labels), # if the values here are non-zero, the slices of\n                                     # the pie chart are moved away from the centre.\n        autopct='%1.1f%%')           # tell matplotlib to print the percentages on the slices.\n\n\"\"\"\n# Heatmaps\n\nIn this section, we will demonstrate how to plot a [heat map](https:\/\/en.wikipedia.org\/wiki\/Heat_map). The way [a heat map is plotted using matplotlib](https:\/\/matplotlib.org\/3.1.1\/gallery\/images_contours_and_fields\/image_annotated_heatmap.html) is with a little trick. matplotlib has a function called [imshow](https:\/\/matplotlib.org\/3.1.1\/api\/_as_gen\/matplotlib.pyplot.imshow.html) which is used to display an image. So, to display a heat map, we could treat the values of the heat map matrix as an image (think a low resolution image). \n\n\n\"\"\"\nheatmap = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],\n                    [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],\n                    [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],\n                    [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],\n                    [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],\n                    [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],\n                    [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])\n\n\nfig, ax = plt.subplots()\nfig.set_size_inches(6, 6)\nim = ax.imshow(heatmap)\n\"\"\"\nWhat if we want to annotate the blocks of the heat map with the values they represent? We can do that by calling the [text](https:\/\/matplotlib.org\/3.1.1\/api\/_as_gen\/matplotlib.axes.Axes.text.html) method of `ax`. What if we want to add a color bar so we get a sense of the value of each color? We could use [colorbar](https:\/\/matplotlib.org\/3.1.1\/api\/_as_gen\/matplotlib.pyplot.colorbar.html). As you can see, things are getting complicated quickly. Obviously, you could wrote your method for plotting a heat map with all required features and re-use it, but you don't have to since others have already done in other libraries that extend the functionality of matplotlib. One such library is [seaborn](https:\/\/seaborn.pydata.org\/). Let's use its [heat map plotting](https:\/\/seaborn.pydata.org\/generated\/seaborn.heatmap.html) functionality:\n\"\"\"\nimport seaborn as sns;\nplt.figure(figsize=(7, 6)) # increased the width to 7 compared to the\n                           # previous code to account for the color bar\nax = sns.heatmap(heatmap)\n\n\"\"\"\nNotice that we got the color bar automatically. If we want to get annotation, we simply pass `annot=True`. We could also easily add labels \n\"\"\"\nimport seaborn as sns;\nplt.figure(figsize=(7, 6))\nax = sns.heatmap(heatmap, annot=True)\n\n\"\"\"\nAs a practical application of heat maps on the Stack Overflow Developer Survey, let's plot the a heat map for open source contribution among the top countries with respect to the number of years coding. In other words, how likely are people to contribute based on their number of years coding?\n\nLet's first see the different values of the `OpenSourcer` fields to know what what to make of it:\n\"\"\"\nlist(survey_top_countries['OpenSourcer'].unique()) # Converting to list to make it easier to read\n\"\"\"\nWe need to convert this field to a numerical representation so we could plot a heat map. Let's map `Never` and `Less than once per year` to 0, map `Once a month or more ofter` to 12, i.e. at least 12 contributions a year, and `Less than once a month but more than once per year` to 6 (since it is more than once but less than 12 contributions a year, picking a value in the middle). Let's define this conversion function:\n\"\"\"\ndef map_os(value):\n    return {\n      'Never': 0,\n      'Less than once per year': 0,\n      'Less than once a month but more than once per year': 6,\n      'Once a month or more often': 12,\n    }[value]\n\n\"\"\"\nNext, let's inspect the value of the `YearsCode` field:\n\"\"\"\nlist(survey_top_countries['YearsCode'].unique()) # Converting to list to make it easier to read\n\"\"\"\nWe can notice two things about this:\n\n1. It is not always numeric, e.g. `Less than 1 year`.\n2. Even when it is numeric, it is still a string type.\n\nLet's define a function to make this numeric:\n\"\"\"\ndef to_int(value):\n    try:\n        return int(value)\n    except:\n        return None\n\"\"\"\nWith these, let's go ahead and create a pivot table for the \n\"\"\"\n\nsurvey_temp = survey_top_countries[['Country', 'YearsCode', 'OpenSourcer']].copy()\nsurvey_temp['OpenSourcer'] = survey_temp['OpenSourcer'].transform(lambda x: map_os(x))\nsurvey_temp['YearsCode'] = survey_temp['YearsCode'].transform(lambda x: to_int(x))\nsurvey_temp = survey_temp[(survey_temp['YearsCode'] >= 1) & (survey_temp['YearsCode'] <= 20)]\n\nptable = survey_temp.pivot_table(\n    index='Country',\n    columns='YearsCode',\n    values='OpenSourcer'\n)\n\nplt.figure(figsize=(14, 6))\nsns.heatmap(ptable, annot=True)\n\"\"\"\nNotice that seaborn automatically used the values of the `Country` and `YearsCode` to set the labels. Such a graph in matplotlib would have required much more code. This is why you should always check whether there are helper functionalities in seaborn or similar libraries before implementing graphs in plain matplotlib.\n\n\"\"\"\n\"\"\"\n# Multiple Plots\n\nBefore ending this notebook, I would like to talk about how to draw multiple plots within the same figure. The way this is done in matplotlib is via the [plt.subplot](https:\/\/matplotlib.org\/api\/_as_gen\/matplotlib.pyplot.subplot.html) method. This method instrurcts matplotlib that the upcoming plot-related instructions belong to particular subplot of the figure. The method accepts three parameters, one for the number of subplot rows in the figure, one for the number of subplot columns, and the last is for the index of the subplot currently being created starting from the top-left corner with index 1 and moving right. For example, the following call:\n```Python\nplt.subplot(3, 3, 4)\n```\ninstruct matplotlib that our figure should have 3 rows and 3 columns of subplots, and that we are currently created the plot number of 4.\n\nAs a demonstration, let's modify our code at the beginning for plotting the sine function to draw multiple plots of the sine function, each having different frequency:\n\"\"\"\nx1 = np.linspace(-2*np.pi, 2*np.pi, 200)\ny1 = np.sin(x1)\n\nplt.figure(figsize=(10, 6))\n\nfor i in range(1, 10):\n    plt.subplot(3, 3, i)\n    #plt.plot(x1, y1)\n    plt.plot(x1, np.sin(i*x1))\nplt.show()\n\"\"\"\n# Summary\n\nI hope this gave you a taste of how to work with matplotlib. The number of different [kinds](https:\/\/matplotlib.org\/gallery\/index.html) of graphs you can do with matplotlib is huge, so this notebook is no way a representation of the power of matplotlib. Instead, I hope I managed to take you through the basics of matplotlib that, with a little googling or Stack Overflow reading, you could easily generate the plot type you need to visualize your data.\n\nAnother thing worth mentioning is that I focused on 2D plots here. It is frequently necessary to deal with 3D plots. However, the notebook is already long, so I thought I would refer you to [matplotlib 3D plotting tutorials](https:\/\/matplotlib.org\/mpl_toolkits\/mplot3d\/tutorial.html) if you need such plots.\n\nIt is also worth pointing out that matplotlib is not the only visualization library in Python. In fact, there are [many more](https:\/\/www.anaconda.com\/python-data-visualization-2018-why-so-many-libraries\/) libraries and matplotlib is just one of them, though it is one of the oldest and most popular library and many other libraries build on top of it. One interesting library which extends matplotlib is [seaborn](seaborn.pydata.org) as mentioned in the section about heat maps. Another interesting library I came to know about recently is [altair](https:\/\/altair-viz.github.io\/getting_started\/installation.html).\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a500222579e9a1'}"}
{"id":"112931","text":"\"\"\"\n# Some statistics to choose the input resolution for your InChI predictor\n\nAnalysis of train and test images (random sample) in the [Bristol-Myers Squibb \u2013 Molecular Translation Competition](https:\/\/www.kaggle.com\/c\/bms-molecular-translation) to find a suitable input image ratio and resolution.\n\n**Credits: I adapted the crop function from https:\/\/www.kaggle.com\/markwijkhuizen\/advanced-image-cleaning-and-tfrecord-generation (great TFRecord kernel!)**\n\"\"\"\n\"\"\"\nHi everyone!\n\nI've seen different choices of the image resolution and w\/h ratio so far, some use squares, some rectangles. I did this analysis to learn more about the images we are given, especially after they are cropped. Note that image width and height are swapped if height > width, for orginal versions as well as cropped versions.\n\n**In the end you can find a summary with the fractions of images that need to be 'shrinked' after cropping for different input resolutions together with the mean 'shrink factor' and more statistics for each resolution.**\n\nIn this summary width \/ height ratios of around 2 seems to work best. What ratio and image resolution did you choose as input for your InChI prediction model? What were the reasons?\n\nFeel free to comment below and \/ or leave a vote if you find this kernel helpful :)\n\"\"\"\nDEBUG = False\nIMAGE_NUM = 1000 if DEBUG else 1_300_000\nEXAMPLE_NUM = 2 if DEBUG else 5\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\n\nimport cv2\nimport imageio\nimport os\nimport sys\nimport re\nimport seaborn as sns\nimport time\nimport random\nimport pickle\n       \nSEED = round(time.time())\nprint(f'SEED: {SEED}')\nos.environ['PYTHONHASHSEED'] = str(SEED)\nrandom.seed(SEED)\nnp.random.seed(SEED)\n# sorting again after sampling seems to make the file access slightly faster for large IMAGE_NUM\ntrain_ids = pd.read_csv('\/kaggle\/input\/bms-molecular-translation\/train_labels.csv', dtype={'image_id': 'string', 'InChI': 'string'}).sample(n=IMAGE_NUM).sort_values(by='image_id', ignore_index=True).image_id\ntest_ids = pd.read_csv('\/kaggle\/input\/bms-molecular-translation\/sample_submission.csv', usecols=['image_id'], dtype={'image_id': 'string'}).sample(n=IMAGE_NUM).sort_values(by='image_id', ignore_index=True).image_id\n\"\"\"\n# Adapted crop function\n\"\"\"\n\"\"\"\nThe crop function from the original source above was adapted to ignore noise pixels and thus crop the real molecule structure only without removing the noise first.\n\"\"\"\ndef crop(img, contour_min_size=2, small_stuff_size=2, small_stuff_dist=5, pad_pixels=1, debug=False, my_figsize=(12,6), horizontal=True):\n    \n    # idea: pad with contour_min_size pixels just in case we cut off\n    #       a small part of the structure that is separated by a missing pixel\n    \n    # rotate counter clockwise to get horizontal images\n    h, w = img.shape\n    if h > w:\n        img = np.rot90(img)\n    \n    if debug:\n        if horizontal:\n            fig, ax = plt.subplots(1,2, figsize=my_figsize)\n        else:\n            fig, ax = plt.subplots(2,1, figsize=my_figsize)\n        ax[0].imshow(img)\n        ax[0].set_title(f'original image, shape: {img.shape}', size=16)\n        \n    _, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n    contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]\n    \n    small_stuff = []\n    \n    x_min0, y_min0, x_max0, y_max0 = np.inf, np.inf, 0, 0\n    for cnt in contours:\n        if len(cnt) < contour_min_size:  # ignore contours under contour_min_size pixels\n            continue\n        x, y, w, h = cv2.boundingRect(cnt)\n        if w <= small_stuff_size and h <= small_stuff_size:  # collect position of small contours starting with contour_min_size pixels\n            small_stuff.append([x, y, x+w, y+h])\n            continue\n        x_min0 = min(x_min0, x)\n        y_min0 = min(y_min0, y)\n        x_max0 = max(x_max0, x + w)\n        y_max0 = max(y_max0, y + h)\n        \n    x_min, y_min, x_max, y_max = x_min0, y_min0, x_max0, y_max0\n    \n    # enlarge the found crop box if it cuts out small stuff that is very close by\n    for i in range(len(small_stuff)):\n        if small_stuff[i][0] < x_min0 and small_stuff[i][0] + small_stuff_dist >= x_min0:\n             x_min = small_stuff[i][0]\n        if small_stuff[i][1] < y_min0 and small_stuff[i][1] + small_stuff_dist >= y_min0:\n             y_min = small_stuff[i][1]\n        if small_stuff[i][2] > x_max0 and small_stuff[i][2] - small_stuff_dist <= x_max0:\n             x_max = small_stuff[i][2]\n        if small_stuff[i][3] > y_max0 and small_stuff[i][3] - small_stuff_dist <= y_max0:\n             y_max = small_stuff[i][3]\n                             \n    if pad_pixels > 0:  # make sure we get the crop within a valid range\n        y_min = max(0, y_min-pad_pixels)\n        y_max = min(img.shape[0], y_max+pad_pixels)\n        x_min = max(0, x_min-pad_pixels)\n        x_max = min(img.shape[1], x_max+pad_pixels)\n        \n    img_cropped = img[y_min:y_max, x_min:x_max]\n    \n    if debug:\n        ax[1].imshow(img_cropped)\n        ax[1].set_title(f'cropped image, shape: {img_cropped.shape}', size=16)\n        plt.show()\n    \n    return img_cropped\ndef check_cropping(image_id, folder='train', my_figsize=(12,6), horizontal=True):\n    print(f'{folder}\/{image_id}')\n    file_path =  f'\/kaggle\/input\/bms-molecular-translation\/{folder}\/{image_id[0]}\/{image_id[1]}\/{image_id[2]}\/{image_id}.png'\n    img = 255 - cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)\n    img = crop(img, debug=True, my_figsize=my_figsize, horizontal=horizontal)\n\"\"\"\n# Check cropped train images\n\"\"\"\ndummy = [check_cropping(image_id, folder='train') for image_id in train_ids[:EXAMPLE_NUM]]\n\"\"\"\n# Check cropped test images\n\"\"\"\ndummy = [check_cropping(image_id, folder='test') for image_id in test_ids[:EXAMPLE_NUM]]\n\"\"\"\n# Image analysis function\n\nImage width and height are swapped if height > width, for orginal versions as well as cropped versions.\n\"\"\"\npd.set_option('display.float_format', lambda x: '%.2f' % x)\n\ndef analyse_img_sizes(image_ids, folder='train', plots=False, w_large=500, h_large=250, very_large_factor=1.5):\n    ws = []\n    hs = []\n    ws_c = []\n    hs_c = []\n    fs = []\n    for image_id in tqdm(image_ids):\n        file_path =  f'\/kaggle\/input\/bms-molecular-translation\/{folder}\/{image_id[0]}\/{image_id[1]}\/{image_id[2]}\/{image_id}.png'\n        file_size = os.path.getsize(file_path) \n        fs.append(file_size)\n        img = 255 - cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)  # '255 -' need for cropping to work\n\n        h, w = img.shape\n        if h > w:\n            h, w = w, h\n        ws.append(w)\n        hs.append(h)\n\n        img_cropped = crop(img)\n        h_c, w_c = img_cropped.shape\n        if h_c > w_c:\n            h_c, w_c = w_c, h_c\n        ws_c.append(w_c)\n        hs_c.append(h_c)\n\n    img_info = pd.DataFrame({'image_id': image_ids, 'file_size': fs, 'width': ws, 'width_crop': ws_c, 'height': hs, 'height_crop': hs_c})\n    \n    img_info['area'] = img_info.width * img_info.height\n    img_info['area_crop'] = img_info.width_crop * img_info.height_crop\n    img_info['ratio'] = img_info.width \/ img_info.height\n    img_info['ratio_crop'] = img_info.width_crop \/ img_info.height_crop\n        \n    img_info_large = img_info.loc[np.logical_or(img_info.width_crop > w_large, img_info.height_crop > h_large),:]\n    \n    img_info_very_large = img_info.loc[np.logical_or(img_info.width_crop > very_large_factor*w_large, img_info.height_crop > very_large_factor*h_large),:]\n        \n    print(f'statistics for all images')\n    display(img_info.describe())\n    print()\n    print(f\"statistics for 'large' images with cropped width > {w_large} or height > {h_large} ({len(img_info_large)\/len(img_info)*100:.3}%):\")\n    display(img_info_large.describe())\n    print()\n    print(f\"statistics for 'very large' images with cropped width > {very_large_factor*w_large} or height > {very_large_factor*h_large} ({len(img_info_very_large)\/len(img_info)*100:.3}%):\")\n    display(img_info_very_large.describe())\n    \n    if plots:\n        print()\n        print(f\"plots for 'large' and 'very large' images only\")\n        plot_info =  img_info_large\n        sns.jointplot(data=plot_info, x='width', y='height', kind='hist')\n        sns.jointplot(data=plot_info, x='file_size', y='area', kind='hist')\n        sns.jointplot(data=plot_info, x='width', y='width_crop', kind='hist')\n        sns.jointplot(data=plot_info, x='height', y='height_crop', kind='hist')\n        sns.jointplot(data=plot_info, x='width_crop', y='height_crop', kind='hist')\n        sns.jointplot(data=plot_info, x='ratio', y='ratio_crop', kind='hist')\n        sns.jointplot(data=plot_info, x='area_crop', y='ratio_crop', kind='hist')\n\n    return img_info\n\"\"\"\n# Train image statistics \n\"\"\"\ntrain_img_info = analyse_img_sizes(train_ids, folder='train', plots=not DEBUG)\n\nwith open('train_img_info.pkl', 'wb') as handle:\n    pickle.dump(train_img_info, handle)\n\"\"\"\n# Test image statistics \n\"\"\"\ntest_img_info = analyse_img_sizes(test_ids, folder='test', plots=not DEBUG)\n\nwith open('test_img_info.pkl', 'wb') as handle:\n    pickle.dump(test_img_info, handle)\n\"\"\"\n# Images with extremly low width or height\n\nThere are some images with extremly low height after cropping. Checking if crop function made a mistake... Seems legit.\n\"\"\"\ndef plot_extreme_images(img_info, folder='train', my_figsize = (20, 10)):\n    img_info_width = img_info.sort_values(by='width_crop', ignore_index=True)[:EXAMPLE_NUM]\n    img_info_height = img_info.sort_values(by='height_crop', ignore_index=True)[:EXAMPLE_NUM]\n    \n    print('very low height images (after swapping if height > width)')\n    [check_cropping(image_id, folder=folder, my_figsize=my_figsize, horizontal=False) for image_id in img_info_height.image_id]\n    \n    print('very low width images (after swapping if height > width)')\n    [check_cropping(image_id, folder=folder, my_figsize=my_figsize) for image_id in img_info_width.image_id]\n\nplot_extreme_images(train_img_info)\nplot_extreme_images(test_img_info, folder='test')\n\"\"\"\n# Find best input resolution\n\"\"\"\ninput_ratios = [1, 1.25, 1.5, 1.75, 1.9, 2, 2.1, 2.25, 2.5]\n\ndef get_res(pixels, ratio):\n    pixels = pixels**0.5\n    ratio = ratio**0.5\n    return (round(pixels*ratio), round(pixels\/ratio))\n\nbase_pixels = 320*320\ninput_sizes = [get_res(base_pixels, r) for r in input_ratios]\n\nbase_pixels = 448*256\ninput_sizes += [get_res(base_pixels, r) for r in input_ratios]\n\nbase_pixels = 512*256\ninput_sizes += [get_res(base_pixels, r) for r in input_ratios]\n\nbase_pixels = 384*384\ninput_sizes += [get_res(base_pixels, r) for r in input_ratios]\n\npixels = [w*h for w, h in input_sizes]\ninput_ratios = [w\/h for w, h in input_sizes]\n\ndef calc_shrink_factors(current_width, current_height, input_size):\n    if current_width < input_size[0] and current_height < input_size[1]:\n        return 1\n    else:\n        return max(input_size[0]\/current_width, input_size[1]\/current_height)\n\ndef check_resolutions(img_info):\n\n    mean_shrink_factors = []  # mean shrink factor (largest of the two factors to decrease image width and\/or height to fit the image into the input size, 1 if image fits already)\n    rms_shrink_factors = []  # root mean square \n    mean_shrink_factors_over_1 = []\n    rms_shrink_factors_over_1 = []\n    fraction_shrinked = []\n\n    for input_size in input_sizes:\n        shrink_factors = np.array([calc_shrink_factors(train_img_info.width_crop[i], train_img_info.height_crop[i], input_size) for i in range(len(train_img_info))])\n        mean_shrink_factors.append(np.mean(shrink_factors))\n        rms_shrink_factors.append(np.mean(shrink_factors**2)**0.5)\n        temp = shrink_factors>1\n        fraction_shrinked.append(np.mean(temp))\n        mean_shrink_factors_over_1.append(np.mean(shrink_factors[temp]))\n        rms_shrink_factors_over_1.append(np.mean(shrink_factors[temp]**2)**0.5)\n        \n    return(pd.DataFrame({'resolution': input_sizes, 'pixels': pixels, 'input_ratio': input_ratios, 'frac_shrinked': fraction_shrinked, \n                        'mean_shr_factor': mean_shrink_factors, 'rms_shr_factor': rms_shrink_factors, 'mean_shr_fac_over_1': mean_shrink_factors_over_1, \n                        'rms_shr_fac_over_1': rms_shrink_factors_over_1}))\n\npd.set_option('display.float_format', lambda x: '%.3f' % x)\n\nprint('train images')\ndisplay(check_resolutions(train_img_info))\n\nprint('test images')\ndisplay(check_resolutions(test_img_info))","meta":"{'source': 'AI4Code', 'id': 'cf76c184fe2554'}"}
{"id":"138515","text":"\"\"\"\n# A Message to readers\n\nGiven the importance of Data Preprocessing in ML, I as a beginner used to be inconsiderate of its effect in model performance. Neglecting it always put me behind in competitions until I explored the methods comprehensively and learned what data science really is. I aim to cover the methods in my notebooks so that I can enlist the prevalent methods for my and your future reference.\n\nBelow is my take on how handle outliers in your data. My target is to make it comprehensive and include all the research done in the field. Yet the notebook is not extensive but will be will in the near future. Stay tuned for future versions. \n\n\nPlease provide your suggestions and compliments in comments! Feel to point out any mistakes I might have made. They help a lot in the learning process!!\n\nUpvote and follow the notebook for updates on future versions! Happy Learning :)\n\"\"\"\n\"\"\"\n# Problem Statement\nThe problem statement was posted on [Analytics Vidhya](https:\/\/datahack.analyticsvidhya.com\/contest\/all\/) as a competition - [JanataHack: Mobility Analytics](https:\/\/datahack.analyticsvidhya.com\/contest\/janatahack-mobility-analytics\/). \nYou can access the data there while I will post the gist of the problem statement which will make you ready to go!\n\nWelcome to Sigma Cab Private Limited - a cab aggregator service. Their customers can download their app on smartphones and book a cab from any where in the cities they operate in. They, in turn search for cabs from various service providers and provide the best option to their client across available options. They have been in operation for little less than a year now. During this period, they have captured surge_pricing_type from the service providers.\n\nYou have been hired by Sigma Cabs as a Data Scientist and have been asked to build a predictive model, which could help them in predicting the surge_pricing_type pro-actively. This would in turn help them in matching the right cabs with the right customers quickly and efficiently.\n\n![image.png](attachment:image.png)\n\nI had submitted my score and got a rank of roughly 170 (as far as I remember). I would share the approach in a future notebook and stick with outlier handling in this one!\n\n### It is a multi-class classification problem.\n\"\"\"\n\"\"\"\n# IMPORTS & necessary data preprocessing before getting into Outlier handling\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (8,6) # setting a default preferred size for plots\nplt.style.use('fivethirtyeight')\nsns.set(style='darkgrid')\nimport scipy\nfrom scipy import stats\ndf = pd.read_csv('..\/input\/mobility\/train.csv')\ndf\ndf.drop('Trip_ID', axis=1,inplace=True); target = 'Surge_Pricing_Type'\nnumfeat, catfeat = list(df.select_dtypes(include=np.number)), list(df.select_dtypes(exclude=np.number)); numfeat.remove(target)\ndf\ndf.info()\n\"\"\"\n### Dont like tabular ugly datas hence dont understand a thing?\n[This](https:\/\/www.kaggle.com\/twinkle0705\/a-comprehensive-guide-to-handle-missing-values) notebook tells you about beautiful insightful visualizations for missing values. Lets be done with it and move to the main methods of outlier handling.\n\"\"\"\nimport missingno as msno; msno.bar(df, figsize=(16,6)); plt.show()\n\"\"\"\nSo simple and pretty already.\n\nUnderstand what it tells? Well, obviously...\n\"\"\"\ndf[numfeat].skew()\n\"\"\"\nSee, the numeric features do not have much skew. We can safely assume mean ~= median and fill with median. \n\nYou get what I am saying? Well, obviously...\n\"\"\"\nfor col in catfeat:\n    df[col].fillna(df[col].mode()[0], inplace=True)\nfor col in numfeat:\n    df[col].fillna(df[col].median(), inplace=True)\n\"\"\"\n# Now, outliers - what are they?\nOutlier is defined as an observation point that is distant from the mainstream data. The presence of outliers can break a model\u2019s analysis ability. \nOne of the most efficient ways to identify outliers may be data visualization. But we'll go beyond that in this notebook.\n\n### Definition of Hawkins [Hawkins 1980]:\n\u201cAn outlier is an observation which deviates so much from the other observations as to arouse suspicions that it was generated by a different mechanism\u201d\n\n\nUsually, features are expected to follow some statistical process - a generating mechanism. A lot of times we observe the feature distributions deviating from this \"generating mechanism\". \n\nML models generally expect **Normal Distribution** of the data hence we proceed assuming our features should be Normally Distributed. \n\n*(Ever wonder \"WHY NORMAL DISTRIBUTION EVERYTIME!!!\"? Here's [C\u00e9dric Villani](https:\/\/www.springer.com\/birkhauser?SGWID=0-40290-6-986722-0) in his [TED Talk explaining why](https:\/\/www.youtube.com\/watch?v=Kc0Kthyo0hU)).*\n\nOutlier handling involves 2 steps:-\n 1. Detecting the outliers\n 2. Treating the detected outliers\n \nLets proceed with various methods of detection of the outliers. \n\"\"\"\n\"\"\"\n## Detecting outliers using Univariate Analysis\n\nThere are numerous ways one can go about detecting outliers. The one which we usually use - visualizations of univariate, bivariate, trivariate.....multivariate, and statistical calculations. \n\nUnivariate visualizations would be the case of checking the distribution of data. \n\n\n\"\"\"\n\"\"\"\n### Distribution plots\n\"\"\"\nf, a = plt.subplots(2,4, figsize=(24,12))\na = a.flatten().T\nfor i, col in enumerate(df[numfeat].columns):\n    sns.distplot(df[col],ax=a[i],kde=False).set_title('Skew: {:.4f}'.format(df[col].skew()))\nplt.show()\n\"\"\"\nDo you see any outliers for any feature? Well, with plots it can be a bit difficult more so when the data is huge. Plus there is an argument of artificial vs natural outliers. How do we go on about deciding which outlier is which? \n\nIt is hard to identify outliers if the data range is not specified.\n\"\"\"\n\"\"\"\n### Normal Probability Plot\n#### The normal probability plot is formed by:\n   *  Vertical axis: Ordered response values\n   *  Horizontal axis: Normal order statistic medians\nWell, what do they mean? Check it out [here](https:\/\/online.stat.psu.edu\/stat501\/lesson\/4\/4.6).\n   \nThe crux is - **The further the points vary from this line, the greater the indication of departures from normality.**\n\"\"\"\nf, a = plt.subplots(2,4, figsize=(24,12))\na = a.flatten().T\nfor i, col in enumerate(df[numfeat].columns):\n    stats.probplot(df[col], plot=a[i])\n    a[i].set_title(col)\nplt.show()\n\"\"\"\nNow, the assumption that out data should be Normally Distributed as the generating mechanism was so, we can clearly see from the probability plots that there exist values which are responsible for deviation from Normal Distribution. \n\nSo, one can nitpick values from the visualizations and classify them as \"Outliers\" and treat accordingly.\n\n#### Example:-\n*  Similarly, values beyond 160 can be treated as **Outliers** for feature 'Var1'.\n*  It can be clearly seen that values between 50 and 60, and values beyond 150 are responsible for the deviation and hence can be classified as **Outliers** for feature 'Var3'.\n*  Values beyond 4.0 are **Outliers** for feature 'Life_Style_Index' and so on for other features too..\n\n## Treatment of outliers\n*  Removing observations which involve these outliers \n*  Or transform the data \n*  Or treat them as we would treat missing values and impute accordingly\n\"\"\"\n## REMOVING OBSERVATIONS BASED ON CLASSIFICATION IN 'EXAMPLE OUTLIERS' FOR FEATURE 'Var1'\ndf.drop(df[df['Var1']>160].index).reset_index(drop=True)\n## TRANSFORMING THE FEATURE TO TREAT OUTLIERS USING BOXCOX TRANSFORMATION FOR FEATURE 'Var3'\ntemp = pd.Series(stats.boxcox(df['Var3'],lmbda=stats.boxcox_normmax(df['Var3'])))\nstats.probplot(temp, plot=plt); plt.show()\n## TREATING OUTLIERS AS MISSING VALUES FOR FEATURE 'Life_Style_Index'\ndf['Life_Style_Index'].where(df['Life_Style_Index']<4.0, df['Life_Style_Index'].median())\n\"\"\"\nSo, these was the most basic (and comprehensive) way of treating outliers based on univariate analysis of numeric features. Doing so might yield you better results already. But we aren't done yet, **are we?**\n\n## Detecting (more) outliers using Multivariate Analysis\nYour data might still have outliers so we are not done yet! How do we detect them in the first place?\n\nWell, we are still left with bivariate (involving two variables\/features) analysis of the data. These will the last kind of analysis we'll be able to plot (unless you delve into 3D plotting or 2D plots with hue).\n\nStarting off with bivariate visualizations we realize that we can now have \n* Numeric-Numeric analysis\n* and Numeric-Categorical analysis \n\nfor which we will use scatterplots and boxplots respectively.\n\n### Scatterplots\nA scatterplot is a graphic tool used to display the relationship between two quantitative variables. They are nice to the eye and easy to interpret and draw conclusions from. Lets see how!\n\n\"\"\"\nsns.pairplot(df[numfeat]); plt.show()\nsns.scatterplot('Var2', 'Var3', data=df, hue = target).set_title('Correlation: {:.4f}'.format(df['Trip_Distance'].corr(df['Life_Style_Index']))); plt.show()\nfrom scipy.spatial import ConvexHull\n\nextremes = df[['Var2', 'Var3']].to_numpy()\n\nhull = ConvexHull(extremes)\n\n# print(extremes[hull.vertices])\n\nplt.plot(df[\"Var2\"], df[\"Var3\"], 'ok')\nplt.plot(extremes[hull.vertices, 0], extremes[hull.vertices,1], 'r--', lw = 2)\nplt.plot(extremes[hull.vertices, 0], extremes[hull.vertices,1], 'ro', lw = 2)\nplt.show()\n\"\"\"\n## Now, what is this doing for us? Thats for you to answer. I will upload the answer in the next version of the notebook which will also include:\n* ###  Complete bi-variate and multivariate analysis\n* ###  Un-supervised learning for outlier-inlier clustering\n* ###  Outliers and Marginal Objects Detection\n* ###  Do categorical variables have any outliers?\n\n### I am sure we are gonna learn a lot from this notebook. I would learn from your experience and suggestions and you might learn a bit from my research and coverage of the topic so crucial to Data Preprocessing! See ya!\n\"\"\"\n\"\"\"\nReferences:-\n*  [Sets up the pipeline for you](https:\/\/www.analyticsvidhya.com\/blog\/2016\/01\/guide-data-exploration\/)\n*  [A great comprehensive resource](https:\/\/www.itl.nist.gov\/div898\/handbook\/eda\/section3\/eda35h.htm) to learn statistical methods\n*  [Pandas documentation](https:\/\/pandas.pydata.org\/pandas-docs\/stable\/reference\/frame.html) comes in very handy\n*  [Scipy Stats documentation](https:\/\/docs.scipy.org\/doc\/scipy\/reference\/generated\/scipy.stats.probplot.html) is worth a read after your stats lecture\n*  [Google Scholar search on published papers](https:\/\/scholar.google.co.in\/scholar?q=outlier+detection+papers&hl=en&as_sdt=0&as_vis=1&oi=scholart) \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fea3cc2d890e8b'}"}
{"id":"122329","text":"\"\"\"\n## Import Package\n\"\"\"\nimport numpy as np\n\"\"\"\n## Linear Equation\n\"\"\"\ndef F1(t):\n    noise = np.random.normal(loc=0, scale=1)\n    a1 = 0.063\n    a2 = 5.284\n    a3 = 4.887\n    a4 = 10.34\n    a5 = 105\n    return a1*(t**4) - a2*(t**3) + a3*(t**2) + a4*(t**1) + a5 + noise\n# number of simulation\nn = 1000\n\n# A (matrix) * x (vector with 5 dimensions) = b (vector with 5 dimensions)\nA = np.zeros((n, 5))\nb = np.zeros((n, 1))\n\nfor i in range(n):\n    # t wll be a number between 0 and 100\n    t = np.random.random()*100\n    \n    b[i] = F1(t)\n    A[i, 0] = t**4\n    A[i, 1] = t**3\n    A[i, 2] = t**2\n    A[i, 3] = t**1\n    A[i, 4] = t**0\n\n# Ax = b\nx = np.linalg.lstsq(A, b)[0]\nx\n\"\"\"\n## Non-Linear Equation\n\"\"\"\ndef F2(t, A, B, C, D):\n    return A*(t**B) + C*np.cos(D*t) + np.random.normal(0, 1, t.shape[0])\nn = 1000\nT = np.random.random((n, 1))*100\nb2 = F2(T, 0.6, 1.2, 100, 0.4)\n\"\"\"\n### Using genetic algorithm to estimate four parameter we have defined: 0.6, 1.2, 100, 0.4\n\"\"\"\n# genetic algo: first step => encoding\n# each row represents a person, gene or solution\npopulation = np.random.randint(0, 2, (10000, 40))\npopulation\n# a function to covert gene into parameter\ndef gene2para(gene):\n    A = (np.sum(2**np.arange(10)*gene[0:10]) - 511) \/ 100\n    B = (np.sum(2**np.arange(10)*gene[10:20]) - 511) \/ 100\n    C = (np.sum(2**np.arange(10)*gene[20:30]) - 511)\n    D = (np.sum(2**np.arange(10)*gene[30:40]) - 511) \/ 100\n    \n    '''\n    Because we have known the range of each parameter, and the solution should locate in this range\n    A: -5.11 ~ 5.12\n    \n    '''\n    return A, B, C, D\n# \"error\" matrix will store how good the gene is \nerror = np.zeros((10000, 1))\nfor generation in range(10):\n    print(\"#{} Gneartion\".format(generation+1))\n    for i in range(10000):\n        A, B, C, D = gene2para(population[i, :])\n        error[i] = np.mean(abs(F2(T, A, B, C, D) - b2))\n    \n    # sort index of person based on its error\n    sort_idx = np.argsort(error[:, 0])\n    population = population[sort_idx, :]\n    \n    # genetic algo: second & third step => Survival of the Fittest\n    for i in range(100, 10000):\n        father = np.random.randint(0, 100)\n        mother = np.random.randint(0, 100)\n        while father == mother:\n            mother = np.random.randint(0, 100)\n        \n        mask = np.random.randint(low=0, high=2, size=(1, 40))\n        son_gene = np.zeros((40))\n        \n        mother_gene = population[mother, :]\n        father_gene = population[father, :]\n        son_gene[mask[0, :] == 1] = father_gene[mask[0, :] == 1]\n        son_gene[mask[0, :] == 0] = mother_gene[mask[0, :] == 0]\n        population[i, :] = son_gene\n        \n    \n    # genetic algo: forth step => Mutation\n    for i in range(1000):\n        mutation_person = np.random.randint(0, 10000)\n        mutation_gene = np.random.randint(0, 40)\n        population[mutation_person, mutation_gene] = 1 - population[mutation_person, mutation_gene]\nfor i in range(10000):\n    A, B, C, D = gene2para(population[i, :])\n    error[i] = np.mean(abs(F2(T, A, B, C, D) - b2))\n    \n# sort index of person based on its error\nsort_idx = np.argsort(error[:, 0])\npopulation = population[sort_idx, :]\ngene2para(population[0])\n# possible improvement\n# we should choose better parent (maybe based on its error)\n# every person should have probability to live (person who has big error should have small probability instead of 0)\n# adaptive mutation rate (high at first, low at final)","meta":"{'source': 'AI4Code', 'id': 'e0f48443259c4e'}"}
{"id":"55137","text":"\"\"\"\n## \uc0c8\ub85c\uc6b4 CNN \ubaa8\ub378\uc758 \ud3c9\uac00\ubc29\ubc95\n* OpenNSFW\uc5d0\uc11c\uc758 \ud3c9\uac00 \uacb0\uacfc\uac00 \uc774\ubbf8 \ub098\uc640 \uc788\ub294 \uacf5\uac1c\ub41c \ub370\uc774\ud130\uc14b\uc744 \uc774\uc6a9\n> https:\/\/www.kaggle.com\/nmurray1234\/yahoo-nsfw-as-mobilenetv2-bottlenecks\n* \uc0c8\ub85c\uc6b4 CNN \ubaa8\ub378\uacfc OpenNSFW\uc758 \uacb0\uacfc\uac12\uc774 \uac19\uac8c \ub098\uc624\ub3c4\ub85d \ud559\uc2b5\n* 3000\uac1c\uc758 \uc601\uc0c1\ub370\uc774\ud130\ub85c \ud559\uc2b5\ud558\uace0, 300\uac1c\uc758 \ub370\uc774\ud130\ub85c \ud3c9\uac00\n* \ub3d9\uc77c\ud55c \uc785\ub825 \uc601\uc0c1\uc5d0 \ub300\ud55c \uacb0\uacfc\uac12\uc774 OpenNSFW\uc5d0\uc11c\uc758 \uacb0\uacfc\uc640\uc758 \ucc28\uc774\uac00 0.05\uc774\ud558\uc778 \uacbd\uc6b0 \uc815\ud655\ud558\uac8c \ucd9c\ub825 \uacb0\uacfc\ub85c \ud310\ub2e8\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import StandardScaler\nfrom tensorflow.python.keras.utils import Sequence\nfrom keras import backend as K\nfrom keras.applications.resnet import ResNet50\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport tensorflow as tf\nimport os\nimport glob\n\"\"\"\nnpz\uc73c\ub85c \uc555\ucd95\ub418\uc5b4 \uc788\ub294 \ub370\uc774\ud130\uc14b \ud30c\uc77c\uc744\uc744 \ubaa8\ub450 \ucc3e\uc544 \ub9ac\uc2a4\ud2b8\ub85c \ub9cc\ub4e6\n\"\"\"\nall_files = glob.glob(\"\/kaggle\/input\/yahoo*\/*\/*\/*\/*\/*.npz\")\n#print(all_files)\nprint(\"file count=\", len(all_files))\n\"\"\"\n\uac01\uac01\uc758 \uc555\ucd95\ud30c\uc77c\uc5d0 3000\uac1c\uc758 \ud6c8\ub828 \uc774\ubbf8\uc9c0\uc640 300\uac1c\uc758 \ud14c\uc2a4\ud2b8 \uc774\ubbf8\uc9c0\uac00 \uc788\uc74c\n\"\"\"\nclass NumPyFileGenerator(Sequence):\n    def __init__(self, files):\n        self.files = files\n\n    def __len__(self):\n        return len(self.files)\n\n    def __getitem__(self, idx):\n        data = np.load(open(self.files[idx], 'rb'), allow_pickle=True)\n        #print(\"DATA= \", np.array(data))\n        x = data['MobileNetV2_bottleneck_features']\n        y = data['azure_output']\n        y2 = y[:, [2]]\n        #print(\"X dim= \", np.shape(x))\n        #print(\"X= \", x)\n        #print(\"y dim= \", np.shape(y))\n        #print(\"y= \", y)\n        #print(\"y2 dim= \", np.shape(y2))\n        #print(\"y2= \", y2)\n        return x, y2\ntraining_generator = NumPyFileGenerator(files=all_files[0:3000])\nvalidation_generator = NumPyFileGenerator(files=all_files[3000:3300])\ndef threshold_accuracy(y_true, y_pred):\n    absolute_difference = K.abs(y_true - y_pred)\n    truth_matrix = K.greater(absolute_difference, K.variable(0.05))\n    casted = K.cast(truth_matrix, 'float32')\n    final = K.mean(casted)\n    return final\n\"\"\"\nCNN \ubaa8\ub378 \uc815\uc758\n\"\"\"\nmodel = tf.keras.Sequential([\n  tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(7, 7, 1280)),\n  tf.keras.layers.Dropout(0.2),\n  tf.keras.layers.GlobalAveragePooling2D(),\n  tf.keras.layers.Dense(1)\n])\n\nmodel.compile(tf.keras.optimizers.Adam(learning_rate=0.001),\n              loss='mean_squared_error', metrics=[threshold_accuracy])\n\"\"\"\n\ud2b8\ub808\uc774\ub2dd\n\"\"\"\nprint(\"training_generator=\", len(training_generator))\nprint(\"validation_generator=\", len(validation_generator))\nepochs=30\nhistory = model.fit_generator(\n                    training_generator,\n                    validation_data=validation_generator,\n                    epochs=epochs,\n                    steps_per_epoch=len(training_generator)\/epochs,\n                    validation_steps=len(validation_generator)\/epochs,\n                    verbose=2)\n\"\"\"\n\uacb0\uacfc \uadf8\ub798\ud504\n\"\"\"\nplt.plot(history.history['threshold_accuracy'])\nplt.plot(history.history['val_threshold_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.yscale('log')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '659ff630c8cfd7'}"}
{"id":"124315","text":"\"\"\"\n##  American Sign Language\n<p>\nThe training data set contains 87,000 images which are 200x200 pixels. There are 29 classes, of which 26 are for the letters A-Z and 3 classes for SPACE, DELETE and NOTHING.\nThese 3 classes are very helpful in real-time applications, and classification.\nThe test data set contains a mere 29 images, to encourage the use of real-world test images.\n<\/p>\n\"\"\"\n\"\"\"\n## Libraries and Data Generation\n\"\"\"\n#!pip install split-folders --upgrade --quiet\nimport os\nimport torch\nimport torchvision\nimport tarfile\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom torchvision.datasets.utils import download_url\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as T\nfrom torch.utils.data import random_split\nfrom torchvision.utils import make_grid\nfrom tqdm.notebook import tqdm\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nmatplotlib.rcParams['figure.facecolor'] = '#ffffff'\n\"\"\"\n### Preparing the Dataset\n\"\"\"\nIMAGE_SIZE = 128\nBATCH_SIZE = 32\nImageDir = \"..\/input\/asl-alphabet\/asl_alphabet_train\/asl_alphabet_train\"\n#import splitfolders\n#splitfolders.ratio(ImageDir, output=\"Train-Val\", ratio = (0.85,0.15))\n# Data transforms and normalization\nstats = ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\ntrain_tfms = T.Compose([\n    T.Resize((IMAGE_SIZE,IMAGE_SIZE)),\n    T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n    T.RandomRotation(18),\n    T.ToTensor(),\n    T.Normalize(*stats, inplace=True)\n])\n\ntest_tfms = T.Compose([\n    T.Resize((IMAGE_SIZE,IMAGE_SIZE)),\n    T.ToTensor(),\n    T.Normalize(*stats, inplace=True)\n])\ntrain_ds = ImageFolder(\".\/Train-Val\/train\",train_tfms)\nval_ds = ImageFolder(\".\/Train-Val\/val\",test_tfms)\nclasses = train_ds.classes\nlen_classes = len(classes)\nlen_classes\ntrain_ds\ntrain_dl = DataLoader(train_ds, BATCH_SIZE, shuffle = True, num_workers = 3, pin_memory = True)\nval_dl = DataLoader(val_ds, BATCH_SIZE, num_workers = 3, pin_memory = True)\n\"\"\"\n## Visualization\n\"\"\"\ndef denormalize(images, means, stds):\n    means = torch.tensor(means).reshape(1, 3, 1, 1)\n    stds = torch.tensor(stds).reshape(1, 3, 1, 1)\n    return images * stds + means\n\ndef show_batch(dl):\n    for images, labels in dl:\n        fig, ax = plt.subplots(figsize=(12, 12))\n        ax.set_xticks([]); ax.set_yticks([])\n        denorm_images = denormalize(images, *stats)\n        ax.imshow(make_grid(denorm_images[:32], nrow=8).permute(1, 2, 0).clamp(0,1))\n        break\nshow_batch(train_dl)\n\"\"\"\n## Using a GPU\n\"\"\"\ndef get_default_device():\n    \"\"\"Pick GPU if available, else CPU\"\"\"\n    if torch.cuda.is_available():\n        return torch.device('cuda')\n    else:\n        return torch.device('cpu')\n    \ndef to_device(data, device):\n    \"\"\"Move tensor(s) to chosen device\"\"\"\n    if isinstance(data, (list,tuple)):\n        return [to_device(x, device) for x in data]\n    return data.to(device, non_blocking=True)\n\nclass DeviceDataLoader():\n    \"\"\"Wrap a dataloader to move data to a device\"\"\"\n    def __init__(self, dl, device):\n        self.dl = dl\n        self.device = device\n        \n    def __iter__(self):\n        \"\"\"Yield a batch of data after moving it to device\"\"\"\n        for b in self.dl: \n            yield to_device(b, self.device)\n\n    def __len__(self):\n        \"\"\"Number of batches\"\"\"\n        return len(self.dl)\ndevice = get_default_device()\ndevice\ntrain_dl = DeviceDataLoader(train_dl, device)\nval_dl = DeviceDataLoader(val_dl, device)\n\"\"\"\n## Model with Residual Blocks and Batch Normalization\n\nOne of the key changes to our CNN model is the addition of the resudial block, which adds the original input back to the output feature map obtained by passing the input through one or more convolutional layers.\n\n![](https:\/\/miro.medium.com\/max\/1140\/1*D0F3UitQ2l5Q0Ak-tjEdJg.png)\n\n\"\"\"\ndef accuracy(outputs, labels):\n    _, preds = torch.max(outputs, dim=1)\n    return torch.tensor(torch.sum(preds == labels).item() \/ len(preds))\n\nclass ImageClassificationBase(nn.Module):\n    def training_step(self, batch):\n        images, labels = batch \n        out = self(images)                  # Generate predictions\n        loss = F.cross_entropy(out, labels) # Calculate loss\n        return loss\n    \n    def validation_step(self, batch):\n        images, labels = batch \n        out = self(images)                    # Generate predictions\n        loss = F.cross_entropy(out, labels)   # Calculate loss\n        acc = accuracy(out, labels)           # Calculate accuracy\n        return {'val_loss': loss.detach(), 'val_acc': acc}\n        \n    def validation_epoch_end(self, outputs):\n        batch_losses = [x['val_loss'] for x in outputs]\n        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses\n        batch_accs = [x['val_acc'] for x in outputs]\n        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies\n        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}\n    \n    def epoch_end(self, epoch, result):\n        print(\"Epoch [{}], last_lr: {:.5f}, train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}\".format(\n            epoch, result['lrs'][-1], result['train_loss'], result['val_loss'], result['val_acc']))\ndef conv_block(in_channels, out_channels, pool=False):\n    layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), \n              nn.BatchNorm2d(out_channels), \n              nn.ReLU(inplace=True)]\n    if pool: layers.append(nn.MaxPool2d(2))\n    return nn.Sequential(*layers)\n\nclass ResNet9(ImageClassificationBase):\n    def __init__(self, in_channels, num_classes):\n        super().__init__()\n        \n        self.conv1 = conv_block(in_channels, 32)\n        self.conv2 = conv_block(32, 64, pool=True)\n        self.res1 = nn.Sequential(conv_block(64,64), conv_block(64,64))\n        \n        self.conv3 = conv_block(64, 128, pool=True)\n        self.conv4 = conv_block(128, 256, pool=True)\n        self.res2 = nn.Sequential(conv_block(256,256), conv_block(256,256))\n        \n        self.conv5 = conv_block(256,512, pool = True)\n        self.conv6 = conv_block(512,512, pool = True)\n        self.res3 = nn.Sequential(conv_block(512, 512), conv_block(512, 512))\n        \n        \n        self.classifier = nn.Sequential(nn.MaxPool2d(4), \n                                        nn.Flatten(), \n                                        nn.Dropout(0.2),\n                                        nn.Linear(512, num_classes))\n        \n    def forward(self, xb):\n        out = self.conv1(xb)\n        out = self.conv2(out)\n        out = self.res1(out) + out\n        out = self.conv3(out)\n        out = self.conv4(out)\n        out = self.res2(out) + out\n        out = self.conv5(out)\n        out = self.conv6(out)\n        out = self.res3(out) + out\n        out = self.classifier(out)\n        return out\nmodel = to_device(ResNet9(3, 29), device)\nmodel\ntorch.cuda.empty_cache()\nfor images,labels in train_dl:\n    print('images.shape:', images.shape)\n    out = model.conv1(images)\n    out = model.conv2(out)\n    out = model.res1(out)\n    out = model.conv3(out)\n    out = model.conv4(out)\n    out = model.res2(out)\n    out = model.conv5(out)\n    out = model.conv6(out)\n    out = model.res3(out)\n    out = model.classifier(out)\n   \n    print('out.shape:', out.shape)\n    break\n\"\"\"\n## Training\n\"\"\"\n@torch.no_grad()\ndef evaluate(model, val_loader):\n    model.eval()\n    outputs = [model.validation_step(batch) for batch in val_loader]\n    return model.validation_epoch_end(outputs)\n\ndef get_lr(optimizer):\n    for param_group in optimizer.param_groups:\n        return param_group['lr']\n\ndef fit_one_cycle(epochs, max_lr, model, train_loader, val_loader, \n                  weight_decay=0, grad_clip=None, opt_func=torch.optim.SGD):\n    torch.cuda.empty_cache()\n    history = []\n    \n    # Set up cutom optimizer with weight decay\n    optimizer = opt_func(model.parameters(), max_lr, weight_decay=weight_decay)\n    # Set up one-cycle learning rate scheduler\n    sched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epochs, \n                                                steps_per_epoch=len(train_loader))\n    \n    for epoch in range(epochs):\n        # Training Phase \n        model.train()\n        train_losses = []\n        lrs = []\n        for batch in tqdm(train_loader):\n            loss = model.training_step(batch)\n            train_losses.append(loss)\n            loss.backward()\n            \n            # Gradient clipping\n            if grad_clip: \n                nn.utils.clip_grad_value_(model.parameters(), grad_clip)\n            \n            optimizer.step()\n            optimizer.zero_grad()\n            \n            # Record & update learning rate\n            lrs.append(get_lr(optimizer))\n            sched.step()\n        \n        # Validation phase\n        result = evaluate(model, val_loader)\n        result['train_loss'] = torch.stack(train_losses).mean().item()\n        result['lrs'] = lrs\n        model.epoch_end(epoch, result)\n        history.append(result)\n    return history\n# without training\nhistory = [evaluate(model, val_dl)]\nhistory\n\"\"\"\n**Training Process**\n\"\"\"\nepochs = 8\nmax_lr = 0.01\ngrad_clip = 0.1\nweight_decay = 1e-4\nopt_func = torch.optim.Adam\nimport time\nstart = time.time()\n\nhistory += fit_one_cycle(epochs, max_lr, model, train_dl, val_dl, \n                             grad_clip=grad_clip, \n                             weight_decay=weight_decay, \n                             opt_func=opt_func)\n\nend = time.time()\n\nprint(f\"Finished training in {(end-start):.2f} seconds.\")\n\"\"\"\n## Plots\n\"\"\"\ndef plot_accuracies(history):\n    accuracies = [x['val_acc'] for x in history]\n    plt.plot(accuracies, '-x')\n    plt.xlabel('epoch')\n    plt.ylabel('accuracy')\n    plt.title('Accuracy vs. No. of epochs');\nplot_accuracies(history)\ndef plot_losses(history):\n    train_losses = [x.get('train_loss') for x in history]\n    val_losses = [x['val_loss'] for x in history]\n    plt.plot(train_losses, '-bx')\n    plt.plot(val_losses, '-rx')\n    plt.xlabel('epoch')\n    plt.ylabel('loss')\n    plt.legend(['Training', 'Validation'])\n    plt.title('Loss vs. No. of epochs');\nplot_losses(history)\ndef plot_lrs(history):\n    lrs = np.concatenate([x.get('lrs', []) for x in history])\n    plt.plot(lrs)\n    plt.xlabel('Batch no.')\n    plt.ylabel('Learning rate')\n    plt.title('Learning Rate vs. Batch no.');\nplot_lrs(history)\n\"\"\"\n## **Testing with Individual Images**\n\"\"\"\ntest_ds = ImageFolder(\"..\/input\/asl-alphabet\/asl_alphabet_test\",test_tfms)\ndef pred_image(img, model):\n    \n    img = to_device(img.unsqueeze(0), device)\n    img_pred = model(img)\n    \n    _, pred = torch.max(img_pred, dim = 1)\n    \n    return classes[pred[0].item()]\n\n\ndef denormalizeTest(images, means, stds):\n    means = torch.tensor(means).reshape(3, 1, 1)\n    stds = torch.tensor(stds).reshape(3, 1, 1)\n    return images * stds + means\nplt.figure(figsize=[20,16])\nfor i in range(len(test_ds)):\n    img, _ = test_ds[i]\n    pred = pred_image(img, model)\n    \n    plt.subplot(7,4,i+1)\n    img = denormalizeTest(img, *stats).permute(1,2,0)\n    plt.imshow(img)\n    plt.title(f\"Prdicted : {pred}\")\n    plt.axis(\"off\")\nplt.show()\n\"\"\"\n### Save the model\n\"\"\"\ntorch.save(model, 'SLA-model.pth')","meta":"{'source': 'AI4Code', 'id': 'e49a4a2f8b87bc'}"}
{"id":"3409","text":"\"\"\"\n# [\u8cbf\u6613\u7d71\u8a08\u3092\u5b66\u3073\u5408\u3046\u4f1a#2](https:\/\/scrapbox.io\/manabiai-lesson) \u7528\u6559\u6750\n\n# \uff08\u8ab2\u984c\uff092020\u5e74\u30001\u6708\u304b\u30896\u6708\u306e\u30de\u30b9\u30af\u95a2\u9023\n\n\n## \u81ea\u7fd2\u8ab2\u984c \n- \u30de\u30b9\u30af\u306e\u88fd\u9020\u6a5f\u68b0\u3092\u8cfc\u5165\u3057\u305f\u306e\u306f\u3069\u306e\u56fd\uff1f\u3000\u7a0e\u95a2\u306f\u3069\u3053\u304c\u591a\u3044\uff1f\n- \u30de\u30b9\u30af\u306e\u7d20\u6750\u3092\u8cfc\u5165\u3059\u308b\u306e\u306f\u3069\u306e\u56fd\uff1f\u3000\u7a0e\u95a2\u306f\u3069\u3053\u304c\u591a\u3044\uff1f\n- \u30de\u30b9\u30af\u306e\u8f38\u5165\u306f\u3001\u3069\u306e\u56fd\u304c\u591a\u3044\uff1f\n\"\"\"\n%%time\n#  \u3053\u306e\u30bb\u30eb\uff08jupyter \u3067\u306e\u30d7\u30ed\u30b0\u30e9\u30e0\u306e\u5b9f\u884c\u5358\u4f4d\u3067\u3059\u3002\uff09\u306f\u3001\u30e9\u30a4\u30d6\u30e9\u30ea\u3092\u8aad\u307f\u8fbc\u307f\u3001sqlite \u30c7\u30fc\u30bf\u3068\u63a5\u7d9a\u3057\u3066\u3001\u4e00\u6642\u7684\u306a\u30c6\u30fc\u30d6\u30eb\u3092\u4f5c\u6210\u3057\u307e\u3059\u3002\n# pandas \u3068\u3044\u3046\u30c7\u30fc\u30bf\u3092\u6271\u3046\u30e9\u30a4\u30d6\u30e9\u30ea\u3092\u8aad\u307f\u8fbc\u307f\u307e\u3059\u3002\n# \u3053\u306e\u30d7\u30ed\u30b0\u30e9\u30e0\u3067\u306f\u3001\u30c7\u30fc\u30bf\u64cd\u4f5c\u306f\uff33\uff31\uff2c\u3092\u901a\u3058\u3066\u884c\u3046\u306e\u3067\u3001pandas \u306f\u3001\u30b0\u30e9\u30d5\u3092\u66f8\u304f\u305f\u3081\u306b\u4f7f\u3046\u306e\u304c\u4e3b\u3067\u3059\u3002\nimport pandas as pd\nimport numpy as np\nimport pandas.io.sql as psql\n\n# sqlite\u3092\u8aad\u307f\u8fbc\u3080\u30e9\u30a4\u30d6\u30e9\u30ea\nimport sqlite3\n\n# \u7dda\u5f62\u56de\u5e30\u3000\u4f7f\u3046\u983b\u5ea6\u306f\u3042\u307e\u308a\u306a\u3044\u3067\u3059\u304c\u3001\u3068\u308a\u3042\u3048\u305a\u3001\u3044\u308c\u3066\u304a\u304d\u307e\u3059\u3002\nfrom sklearn import linear_model\nclf = linear_model.LinearRegression()\n\n\n\n# HTML\u3067\u8868\u793a\u3059\u308b\u3000\u30a8\u30af\u30bb\u30eb\u306b\u30b3\u30d4\u30da\u3059\u308b\u3068\u304d\u306b\u4fbf\u5229\nfrom IPython.display import display, HTML\n\n# markdown \u7528\nfrom tabulate import tabulate\n\n# \u65e5\u6642\u3092\u6271\u3046\nfrom datetime import datetime as dt\nimport time\n\n# \u30b0\u30e9\u30d5\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\n%matplotlib inline\n\n# system \u95a2\u4fc2\u306e\u30e9\u30a4\u30d6\u30e9\u30ea\nimport sys\n# os \u306e\u6a5f\u80fd\u3092\u4f7f\u3046\u30e9\u30a4\u30d6\u30e9\u30ea\nimport os\n# \u6b63\u898f\u8868\u73fe\nimport re\n\n# json,yaml \u5f62\u5f0f\u3092\u6271\u3046\nimport json\nimport yaml\n\n# \u5909\u6570\u306e\u72b6\u614b\u3092\u8abf\u3079\u308b\nimport inspect\n\n# \u6587\u5b57\u30b3\u30fc\u30c9\nimport codecs\n\n# Web \u304b\u3089\u30c7\u30fc\u30bf\u3092\u53d6\u5f97\u3059\u308b\nimport requests\n\n# \u8cbf\u6613\u7d71\u8a08\u306e\u30c7\u30fc\u30bf\n# http:\/\/www.customs.go.jp\/toukei\/info\/tsdl_e.htm\n# \u30b3\u30fc\u30c9\u3000\u8f38\u51fa\u306f\u65e5\u672c\u8a9e\u306e\u307f\n# https:\/\/www.customs.go.jp\/toukei\/sankou\/code\/code_e.htm \n\n# sqlite \u306b show tables \u304c\u306a\u3044\u306e\u3067\u88dc\u8db3\u3059\u308b\u3082\u306e\nshow_tables = \"select tbl_name from sqlite_master where type = 'table'\"\n# describe \u3082\u306a\u3044\u3067\u3001\u88dc\u5b8c\u3057\u307e\u3059\u3002\ndesc = \"PRAGMA table_info([{table}])\"\n# \u30e1\u30e2\u30ea\u3067\u3001sqlite \u3092\u4f7f\u3044\u307e\u3059\u3002kaggle \u306e\u30b9\u30af\u30ea\u30d7\u30c8\u4e0a\u3067\u306f\u3001\u30aa\u30f3\u30e1\u30e2\u30ea\u3067\u306a\u3044\u3068\u65b0\u898f\u30c6\u30fc\u30d6\u30eb\u304c\u3064\u304f\u308c\u307e\u305b\u3093\n# \u30d7\u30ed\u30b0\u30e9\u30e0\u306e\u4e00\u884c\u304c\u9577\u3044\u3068\u304d\u306f\u3000\\\u3000\u3067\u6539\u884c\u3057\u307e\u3059\u3002\nconn = \\\n    sqlite3.connect(':memory:')\n\n# sql \u3092\u5b9f\u884c\u3059\u308b\u305f\u3081\u306e\u5909\u6570\u3067\u3059\u3002\ncursor = conn.cursor()\n\n# 1997 \u5e74\u304b\u3089\u30012019 \u5e74\u307e\u3067\u306e\u5e74\u30d9\u30fc\u30b9\u306e\u30c7\u30fc\u30bf\u3067\u3059\u3002\u30c6\u30fc\u30d6\u30eb\u306f\u3001year_from_1997 \n# year_from_1997\nattach = 'attach \"..\/input\/japan-trade-statistics\/y_1997.db\" as y_1997'\ncursor.execute(attach)\n\n# 2018 \u5e74\u306e\u6708\u5225\u96c6\u8a08 \u30c6\u30fc\u30d6\u30eb\u540d\u3082 ym_2018 \nattach = 'attach \"..\/input\/japan-trade-statistics\/ym_2018.db\" as ym_2018'\ncursor.execute(attach)\n\n# 2019 \u5e74\u306e\u6708\u5225\u96c6\u8a08 \u30c6\u30fc\u30d6\u30eb\u540d\u3082 ym_2019\nattach = 'attach \"..\/input\/japan-trade-statistics\/ym_2019.db\" as ym_2019'\ncursor.execute(attach)\n\n# 2020 \u5e74\u306e\u6708\u5225\u96c6\u8a08 \u30c6\u30fc\u30d6\u30eb\u540d\u3082 ym_2020\nattach = 'attach \"..\/input\/japan-trade-statistics\/ym_2020.db\" as ym_2020'\ncursor.execute(attach)\n\n# hs code,country,HS\u30b3\u30fc\u30c9\u3067\u3059\u3002\u4f7f\u3044\u3084\u3059\u3044\u3088\u3046\u306b pandas\u3000\u306b\u5909\u66f4\u3057\u3066\u304a\u304d\u307e\u3059\u3002\nattach = 'attach \"..\/input\/japan-trade-statistics\/codes.db\" as code'\ncursor.execute(attach)\n# import hs,country code as pandas\ntmpl = \"{hs}_{lang}_df =  pd.read_sql('select * from code.{hs}_{lang}',conn)\"\nfor hs in ['hs2','hs4','hs6','hs6','hs9']:\n    for lang in ['jpn','eng']:\n        exec(tmpl.format(hs=hs,lang=lang))        \n\n# \u56fd\u30b3\u30fc\u30c9\u3082 pandas \u3067\u6271\u3048\u308b\u3088\u3046\u306b\u3057\u307e\u3059\u3002\n# country table: country_eng,country_jpn\ncountry_eng_df = pd.read_sql('select * from code.country_eng',conn)\ncountry_eng_df['Country']=country_eng_df['Country'].apply(str)\ncountry_jpn_df = pd.read_sql('select * from code.country_jpn',conn)\ncountry_jpn_df['Country']=country_jpn_df['Country'].apply(str)\n\n# custom  table: code.custom \u7a0e\u95a2\u5225\u306e\u30b3\u30fc\u30c9\u3067\u3059\ncustom_df = pd.read_sql('select * from code.custom',conn)\nattach = 'attach \"..\/input\/japan-trade-statistics\/custom_from_2012.db\" as custom_from'\ncursor.execute(attach)\nattach = 'attach \"..\/input\/custom-2016\/custom_2018.db\" as custom_2018'\ncursor.execute(attach)\nattach = 'attach \"..\/input\/custom-2016\/custom_2019.db\" as custom_2019'\ncursor.execute(attach)\n\n#attach = 'attach \"..\/input\/japan-trade-statistics\/custom_2020.db\" as custom_2020'\n#cursor.execute(attach)\n\n# \u8a08\u7b97\u6642\u9593\u3092\u7bc0\u7d04\u3059\u308b\u305f\u3081\u306b\u3001\u5e74\u306e\u30c7\u30fc\u30bf\u304b\u3089\u30012019 \u5e74\u3092\u5207\u308a\u51fa\u3057\u307e\u3059\u3002\n# \u6700\u521d\u306e\u306f\u30a8\u30e9\u30fc\u51e6\u7406\u3067\u3059\u3002y_2019 \u3068\u3044\u3046\u30c6\u30fc\u30d6\u30eb\u304c\u5b58\u5728\u3059\u308b\u3068\u3001\u65b0\u898f\u306b y_2019 \u3092\u4f5c\u308d\u3046\u3068\u3059\u308b\u3068\u30a8\u30e9\u30fc\u306b\u306a\u308a\u307e\u3059\u3002\n# error \u306e\u5834\u5408\u306f\u3001\u4f55\u3082\u305b\u305a\u3001\u6b21\u306b\u3059\u3059\u307f\u307e\u3059\u3002\ntry:\n    cursor.execute('drop table y_2019')\nexcept:\n    pass\n\n# \u3053\u308c\u304b\u3089\u304c\u3001SQl \u306b\u306a\u308a\u307e\u3059\u3002\u8907\u6570\u884c\u3067\u66f8\u304f\u3053\u3068\u304c\u591a\u3044\u306e\u3067sql \u3068\u3044\u3046\u5909\u6570\u306b\u8907\u6570\u884c\u3092\u4ee3\u5165\u3057\u307e\u3059\u3002\n# \u6700\u5f8c\u306e [1:-1] \u306f\u3001\u4e00\u884c\u76ee\uff08\u6539\u884c\u3067\u7a7a\u767d\uff09\u3068\u6700\u5f8c\u306e\u884c\uff08\u3053\u308c\u3082\u6539\u884c\u3060\u3051\u3067\u7a7a\u767d\uff09\u3092\u3068\u308a\u306e\u305e\u304f\u305f\u3081\u3067\u3059\u3002\n# 0 \u304b\u3089\u59cb\u307e\u308b\u306e\u3067\u30011 \u3060\u3068\u3001\uff12\u884c\u76ee\u304b\u3089\u6700\u5f8c\u306e\u884c\u306e\u3072\u3068\u3064\u624b\u524d\u307e\u3067\u3067\u3059\u3002\nsql = \"\"\"\ncreate table y_2019 \nas select * from year_from_1997\nwhere Year = 2019\n\"\"\"[1:-1]\n# \u4e0a\u8a18\u306e sql \u3092\u5b9f\u884c\u3057\u3057\u3066\u30012019 \u5e74\u306e\u30c7\u30fc\u30bf\u3092\u3064\u304f\u308a\u307e\u3059\u3002\ncursor.execute(sql)\nconn.commit()\n\n# sql \u306e\u8aac\u660e\u3067\u3059\u3002\n# create table \u30c6\u30fc\u30d6\u30eb\u540d : \u30c6\u30fc\u30d6\u30eb\u3092\u65b0\u898f\u4f5c\u6210\u3000\u3053\u3053\u3067\u306f\u3001y_2019 \n# as select * from  \u30c6\u30fc\u30d6\u30eb\u540d\u3000: \u30c6\u30fc\u30d6\u30eb\u540d(year_from_1997)\u304b\u3089\u3064\u304f\u308a\u307e\u3059\u3002\n# where Year = 2019 : 2019 \u5e74\u306e\u30c7\u30fc\u30bf\u3092\u6307\u5b9a\u3057\u307e\u3059\u3002Year \u306f\u3001\u6570\u5024\u306a\u306e\u3067\u30012019 \u3068\u66f8\u304d\u307e\u3059\u3002\n\n\n# https:\/\/www.customs.go.jp\/toukei\/srch\/index.htm?M=01&P=1,1,,,,,,,,4,1,2019,0,0,0,2,020230100,,,,,,,,,,6,120,,,,,,,,,,,,,,,,,,,,,20\n\n# graph \u7528\u306e\u3000color\u3000https:\/\/matplotlib.org\/examples\/color\/named_colors.htmlsql_sample \n\"\"\"\n# \u4e00\u6642\u30c6\u30fc\u30d6\u30eb\u4f5c\u6210 2018.1-2020\u5e74\u306e\u6708\u5225\u30c7\u30fc\u30bf\n# \u4e00\u6642\u30c6\u30fc\u30d6\u30eb\u306f\u3001\u30a8\u30e9\u30fc\u306a\u308b\u3068\u524a\u9664\u3055\u308c\u308b\u3088\u3046\u3067\u3059\u3002\u30bb\u30eb\u5b9f\u884c\u6642\u306b\u30a8\u30e9\u30fc\u306b\u306a\u3063\u305f\u3089\u3001\u4e00\u6642\u30c6\u30fc\u30d6\u30eb\u3092\u3064\u304f\u308a\u306a\u304a\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n\"\"\"\n# ym_2018_2020 2018-2020 \u306e\u6708\u5225\u96c6\u8a08\u306e\u30c7\u30fc\u30bf\u3092\u307e\u3068\u3081\u307e\u3059\u3002\n# \u5e74\uff0b\u6708\u306e\u30ab\u30e9\u30e0(ym)\u3092\u3064\u304f\u308a\u307e\u3059\u3002\n# \u5e74\u306f\u3001\u6574\u6570\u3001\u6708\u306f\u3001\u6587\u5b57\u5217\u306a\u306e\u3067\u3001\u578b\u5909\u63db\u3068\u6587\u5b57\u5217\u7d50\u5408\u3092\u884c\u3044\u307e\u3059\u3002\n# CAST(Year AS  str )||month as ym \u304c\u305d\u306e\u51e6\u7406\u3092\u3057\u3066\u3044\u308b\u90e8\u5206\u3067\u3059\u3002\n# \u6587\u5b57\u5217\u7d50\u5408\u304c\u3001|| \u306a\u306e\u3067\u9055\u548c\u611f\u3042\u308a\u307e\u3059\u304c\u3001\u3057\u3087\u3046\u304c\u306a\u3044\u3067\u3059\u3002\n\ntry:\n    cursor.execute('drop table ym_2018_2020')\nexcept:\n    pass\n\nsql = \"\"\"\ncreate table ym_2018_2020\nas select CAST(Year AS  str )||month as ym,* from ym_2018\n\"\"\"[1:-1]\ncursor.execute(sql)\n\nsql = \"\"\"\ninsert into  ym_2018_2020\n select CAST(Year AS  str )||month as ym,* from ym_2019\n\"\"\"[1:-1]\ncursor.execute(sql)\n\nsql = \"\"\"\ninsert into  ym_2018_2020\n select CAST(Year AS  str )||month as ym,* from ym_2020\n\"\"\"[1:-1]\ncursor.execute(sql)\n\nconn.commit()\n# \u4fbf\u5229\u306a\u30af\u30e9\u30b9\uff08sql \u5b9f\u884c + \u30b0\u30e9\u30d5\uff09ut.\u95a2\u6570\u540d\u3067\u4f7f\u3044\u307e\u3059\u3002\nclass util():\n    def sql(self,sql):\n        return(pd.read_sql(sql,conn))\n \n    # \u30b0\u30e9\u30d5\u4f5c\u6210 \u4e00\u7cfb\u5217\u306e\u307f\n    def g1(self,df,x,y,color='b'):\n        plt.figure(figsize=(20, 10))\n\n        ax = sns.lineplot(x=x,y=y,data=df,linewidth=7.0,color=color)\n        # \u3053\u308c\u306f\u3001x\u8ef8\uff08\u6642\u7cfb\u5217\uff09\u306e\u5358\u4f4d\u304c\u7701\u7565\u3055\u308c\u306a\u3044\u3088\u3046\u306b\u3059\u308b\u8a2d\u5b9a\n        # \u4f55\u3082\u3057\u306a\u3044\u3068\u30012000,2005,2010\u306e\u3088\u3046\u306b\u4e00\u5e74\u5206\u304c\u3068\u3070\u3055\u308c\u3066\u3057\u307e\u3044\u307e\u3059\u3002\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) \n        \n    # \u30b0\u30e9\u30d5\u4f5c\u6210 2\u7cfb\u5217\u3000\u8f38\u51fa\u5165\u3000\u6bd4\u8f03\u306b\u3064\u304b\u3044\u307e\u3059\u3002\u8f38\u51fa\u304c\u9752\u3001\u8f38\u5165\u304c\u8d64\n    def g2(self,df,x,y,hue,palette={1: \"b\", 2: \"r\"}):\n        plt.figure(figsize=(20, 10))\n        ax  = sns.lineplot(x=x,y=y,hue=hue,linewidth = 7.0,\n             palette=palette,\n             data=df)\n        # \u51e1\u4f8b\u306e\u4f4d\u7f6e\u3000\uff12\u306f\u5de6\u4e0a\n        ax.legend_._loc = 2\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(1))    \n        \n    # \u8907\u6570\u7cfb\u5217\u306e\u30b0\u30e9\u30d5\n    def gx(self,df,x,y,hue,palette={}):\n        plt.figure(figsize=(20, 10))\n        if palette == {}:\n            ax  = sns.lineplot(x=x,y=y,hue=hue,linewidth = 7.0,data=df)\n        else:\n            ax  = sns.lineplot(x=x,y=y,hue=hue,linewidth = 7.0,palette=palette,data=df)\n        # \u51e1\u4f8b\u306e\u4f4d\u7f6e\u3000\uff12\u306f\u5de6\u4e0a\n        ax.legend_._loc = 2\n        ax.xaxis.set_major_locator(ticker.MultipleLocator(1))    \n        \n    def bar(self,df,y,x,prefix='',color='b'):\n        # \u8272\u898b\u672c\n        #https:\/\/matplotlib.org\/examples\/color\/named_colors.html\n        # \u8272\u306e\u610f\u5473\u3000\u5408\u8a08: gold     \u8f38\u51fa: b (blue) \u8f38\u5165: r ( red )\u3000\u3092\u3064\u304b\u3063\u3066\u3044\u307e\u3059\u3002\n        if len(prefix) > 0:\n            df[y] = df[y].map(lambda x: 'hs' + str(x))\n        ax = sns.barplot(y=y, x=x, data=df,color=color)\n        plt.show()\n        plt.close()\n\n\n    # \u8f38\u51fa\u5165\u30b3\u30fc\u30c9\u306eurl \u3092\u8868\u793a\u3059\u308b\n    # \u8f38\u5165 \n    def hs_url(self,hs_code,exp_imp=2,yyyy_mm='2020_4'):\n        # \u8f38\u51fa https:\/\/www.customs.go.jp\/yusyutu\/index.htm\n        # \u8f38\u5165 https:\/\/www.customs.go.jp\/tariff\/index.htm\n        hs = hs_code[0:2]\n    \n        if exp_imp == 1:\n            ex = 'yusyutu'\n        else:\n            ex = 'tariff'\n        \n        tmpl = 'https:\/\/www.customs.go.jp\/{ex}\/{yyyy_mm}\/data\/print_j_{hs}.htm'\n        print(tmpl.format(ex=ex,yyyy_mm=yyyy_mm,hs=hs))\n\n    # db \u3068\u306e\u63a5\u7d9a conn \u306f\u3001global \u5909\u6570\u3068\u3057\u3066\u4f7f\u3046 \n    def hs_table_create(self,hs_code,tables=['y_2019','year_from_1997','ym_2018_2020']):\n        \n        if len(hs_code) not in (2,4,6,9):\n            print(hs_code + ': \u6841\u6570\u304c\u304a\u304b\u3057\u3044\u3067\u3059\u3002')\n            return\n        \n        hs = 'hs' + str(len(hs_code))\n        \n        sql = \"\"\"\n        create table hs{hs_code}_{table}\n        as select * from {table}\n        where {hs} = '{hs_code}'\n        \"\"\"[1:-1]\n        \n        for table in tables:\n            tg = 'drop table hs{hs_code}_{table}'.format(hs_code=hs_code,table=table)\n            print(tg)\n            try:\n                cursor.execute(tg)\n            except:\n                pass\n            cursor.execute(sql.format(hs=hs,hs_code=hs_code,table=table))\n\n        conn.commit()\n        \n    def hs_name_get(self,hs_code):\n        hs = len(hs_code)\n        if hs not in (2,4,6,9):\n            print('HS \u30b3\u30fc\u30c9\u306e\u9577\u3055\u304c\u307e\u3061\u304c\u3063\u3066\u3044\u307e\u3059\u3002 ' + str(hs))\n        hs = str(hs)\n        print(hs_code)\n        text = 'hs' + hs + '_eng_df.query(' +\"'\"+ 'hs' + hs + '==\"' + hs_code + '\"' + \"')\"\n        df = eval(text)\n        print(df['hs' + hs + '_name'].values[0])\n        text = 'hs' + hs + '_jpn_df.query(' +\"'\"+ 'hs' + hs + '==\"' + hs_code + '\"' + \"')\"\n        df = eval(text)\n        print(df['hs' + hs + '_name'].values[0])\n\n            \n        \n\n    #  \u56fd\u30b3\u30fc\u30c9(\u8907\u6570) \u306e\u30c7\u30fc\u30bf\u3092\u62bd\u51fa\u3000\u56fd\u30b3\u30fc\u30c9\u306f\u3001\u6587\u5b57\u5217\u306e\u306f\u305a\u3060\u304c\u3001\u3068\u304d\u3069\u304d\u306a\u308b\u6574\u6570\u306b\u306a\u308b\u306e\u3067\u6ce8\u610f\n    def countries_table_create(self,countries=['105','304','103','106','601'],tables=['y_2019','year_from_1997','ym_2018_2020']):\n        clist = \"('\" + \"','\".join(countries) + \"')\" \n        sql = \"\"\"\n        create table countries_{table}\n        as select * from {table}\n        where Country in {clist}\n        \"\"\"[1:-1]\n        \n        for table in tables:\n            tg = 'drop table countries_{table}'.format(table=table)\n            print(tg)\n            try:\n                cursor.execute(tg)\n            except:\n                pass\n            cursor.execute(sql.format(clist=clist,table=table))\n\n        conn.commit()\n        \n    # \u56fd\u5225\u6298\u308c\u7dda\u30b0\u30e9\u30d5\u306e\u3068\u304d\u306b\u3001\u56fd\u4e0e\u3048\u308b\u8272\u3067\u3059\u3002\n    def national_colors(self):\n        return ({'105': ['\u4e2d\u56fd', 'gold'],\n        '304': ['\u30a2\u30e1\u30ea\u30ab', 'red'],\n         '103': ['\u97d3\u56fd', 'blue'],\n         '106:': ['\u53f0\u6e7e', 'cyan'],\n         '601:': ['\u30aa\u30fc\u30b9\u30c8\u30e9\u30ea\u30a2', 'green'],\n         '111:': ['\u30bf\u30a4', 'violet'],\n         '213:': ['\u30c9\u30a4\u30c4', 'lightgrey'],\n         '110:': ['\u30d9\u30c8\u30ca\u30e0', 'crimson'],\n         '108:': ['\u9999\u6e2f', 'orangered'],\n         '112:': ['\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb', 'aqua'],\n         '147:': ['\u30a2\u30e9\u30d6\u9996\u9577\u56fd\u9023\u90a6', 'black'],\n         '137:': ['\u30b5\u30a6\u30b8', 'darkgreen'],\n         '118:': ['\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2', 'darkorange'],\n         '113:': ['\u30de\u30ec\u30fc\u30b7\u30a2', 'yellow'],\n         '205:': ['\u30a4\u30ae\u30ea\u30b9', 'darkblue'],\n         '224:': ['\u30ed\u30b7\u30a2', 'pink'],\n         '117:': ['\u30d5\u30a3\u30ea\u30d4\u30f3', 'olive'],\n         '302:': ['\u30ab\u30ca\u30c0', 'salmon'],\n         '210:': ['\u30d5\u30e9\u30f3\u30b9', 'indigo'],\n         '305:': ['\u30e1\u30ad\u30b7\u30b3', 'greenyellow']})\n    \n    # \u8679\u306e7\u8272\u3092\u5272\u308a\u5f53\u3066\u308b\n    def rank_color(self,xlist):\n        clist = ['red','ornage','yellow','green','blue','indigo','violet']\n        palette = {xlist[i]:clist[i] for i in range(len(xlist))}\n        return(palette)\n\n\nut = util()\n%%time\n# \u4e0a\u8a18\u306e %%time \u306f\u5b9f\u884c\u6642\u9593\u3092\u8868\u793a\u3059\u308b\u3082\u306e\u3067\u3059\u3002\u306a\u304f\u3066\u3082\u826f\u3044\u3067\u3059\u3002\u307e\u305f\u3001\u5b9f\u611f\u3068\u3057\u3066\u306f\u3082\u3063\u3068\u9577\u3044\u3067\u3059\u3002\n# \n# 2020\/01\u3000\u3068\u30012020\/02\u3000\u3092\u6bd4\u8f03\u3059\u308b\u305f\u3081\u306b\u4e00\u6642\u30c6\u30fc\u30d6\u30eb\u3092\u4f5c\u6210\u3057\u307e\u3059\n\ntry:\n    cursor.execute('drop table tmp_1')\nexcept:\n    pass\n\n# 2020\/01 \u306e\u30c7\u30fc\u30bf\u3067\u3000\u54c1\u76ee(hs9)\u3067\u96c6\u8a08\u30571\u5104\u5186\u4ee5\u4e0a\u3092\u62bd\u51fa\nsql = \"\"\"\ncreate table tmp_1 \nas select exp_imp,hs9,CAST(sum(Value) as int) as ym01\nfrom ym_2018_2020\nwhere ym='202001' \ngroup by exp_imp,hs9\nhaving  ym01 > 100000\n\"\"\"[1:-1]\ncursor.execute(sql)\n\ntry:\n    cursor.execute('drop table tmp_2')\nexcept:\n    pass\n\n# 2020\/02 \u306e\u30c7\u30fc\u30bf\u3092\u62bd\u51fa\u3000\u54c1\u76ee(hs9)\u3067\u96c6\u8a08\nsql = \"\"\"\ncreate table tmp_2\nas select exp_imp,hs9,sum(Value) as ym02\nfrom ym_2018_2020\nwhere ym='202002'\ngroup by exp_imp,hs9\n\"\"\"[1:-1]\ncursor.execute(sql)\n# 1\u6708\u306b\u306f\u3042\u3063\u3066\u30012\u6708\u306b \u306a\u3044\u30c7\u30fc\u30bf\u306f\u3042\u308b\u304b\u306e\u30c1\u30a7\u30c3\u30af\u3000\u7d50\u679c\u306f\u306a\u3057\n\nsql = \"\"\"\nselect hs9 from \ntmp_1 where hs9 not in (select hs9 from tmp_2)\n\"\"\"[1:-1]\n\ndf = pd.read_sql(sql,conn)\ndf\n# 1\u67082\u6708\u306e\u6bd4\u8f03\u6e96\u5099\u30001\u6708\u30682\u6708\u306e\u30c7\u30fc\u30bf\u306e\u5408\u8a08 total \u3092\u3064\u304f\u308a\u3001\uff12\u6708\u306e\u5272\u5408(ratio)\u3092\u51fa\u3057\u307e\u3059\u3002\n\n\n\nsql = \"\"\"\nselect t2.exp_imp,t2.hs9,CAST(ym01 as real) as ym01,CAST(ym02 as real) as ym02,ym01+ym02 as total\nfrom tmp_1 t1,tmp_2 t2\nwhere t2.exp_imp = t1.exp_imp and\nt2.hs9 = t1.hs9\n\"\"\"[1:-1]\n\n\"\"\"\ndf = pd.read_sql(sql,conn)\n# 1\u67082\u6708\u306e\u5408\u8a08\u3067\u30012\u6708\u306e\u5272\u5408(ratio)\u3092\u3060\u3057\u307e\u3059\u3002\u9762\u5012\u306a\u306e\u3067\u3001pandas \u3067\u51fa\u3057\u3066\u3044\u307e\u3059\u3002\ndf['ratio'] = df['ym02']\/df['total']\n# \u3002df \u306f\u4e00\u6642\u7684\u306b\u4f7f\u7528\u3059\u308b\u5909\u6570\u540d\u306a\u306e\u3067\u3001\u5909\u6570\u540d\u3092\u3064\u3051\u307e\u3059\ndf_01_02 = df.copy()\n\"\"\"\n\n''\n# 100\u5104\u5186\u4ee5\u4e0a\u3067\u3001\u8f38\u51fa\u304c\u6e1b\u3063\u305f\u3068\u3053\u308d \u30bf\u30fc\u30dc\u30b8\u30a7\u30c3\u30c8841112000\u3001\u304b\u306a\u308a\u6e1b\u3063\u305f\u306e\u306f\u300184490000\u3000\u4e0d\u7e54\u5e03\u306e\u88fd\u9020\u6a5f\u68b0\uff08\u591a\u5206\uff09860310000\u3000\u8ca8\u8eca\uff08\uff1f\uff09\n# \u9762\u767d\u3044\u306e\u306f\u3001\u30de\u30b9\u30af\u88fd\u9020\u88c5\u7f6e\u3068\u601d\u308f\u308c\u308b 84490000\n# df_01_02.query('ym01 > 1000000 and exp_imp==1').sort_values('ratio').head(3)\n# https:\/\/www.kanzei.or.jp\/statistical\/tariff\/detail\/index\/j\/844900000 \u3067\u8abf\u3079\u308b\u306e\u304c\u3044\u3044\u3067\u3059\u3002\n# 84490000\u3000\u4e0d\u7e54\u5e03\u306e\u88fd\u9020\u6a5f\u68b0\uff08\u591a\u5206\uff091\u6708\u306b\u3059\u308b\u3069\u3044\u30d4\u30fc\u30af\u304c\u3042\u308a\u307e\u3059\u3002\nsql = \"\"\"\nselect ym,sum(Value) as Value from ym_2018_2020\nwhere \nhs9 = '844900000' and exp_imp =1\ngroup by ym,exp_imp\n\"\"\"[1:-1]\n\n\ndf = pd.read_sql(sql,conn)\nut.g1(df,'ym','Value')\n\n# 630790000   \u7d21\u7e54\u7528\u7e4a\u7dad\u3000\u304a\u305d\u3089\u304f\u3000\u30de\u30b9\u30af\u306e\u539f\u6599\n# 2\u6708\u306b\u30d4\u30fc\u30af\u304c\u3042\u308a\u307e\u3059\u3002\n\nsql = \"\"\"\nselect ym,sum(Value) as Value from ym_2018_2020\nwhere \nhs9 = '630790000' and exp_imp =1\ngroup by ym,exp_imp\n\"\"\"[1:-1]\ndf = pd.read_sql(sql,conn)\nut.g1(df,'ym','Value')\ndf.tail()\n\n# 630790029 \u8f38\u5165\u3000\u30de\u30b9\u30af\u306e\u8f38\u5165\n# \uff11\u6708\u306b\u5897\u3048\u307e\u3057\u305f\u304c\u3001\uff12\u6708\u3067\u843d\u3061\u30663\u6708\u306f\u56de\u5fa9\u3067\u3059\nsql = \"\"\"\nselect ym,sum(Value) as Value from ym_2018_2020\nwhere \nhs9 = '630790029' and exp_imp =2 \ngroup by ym,exp_imp\n\"\"\"[1:-1]\ndf = pd.read_sql(sql,conn)\nut.g1(df,'ym','Value')\n\n# 2020\/05\u306e\u30de\u30b9\u30af\u8f38\u5165\u3000\u56fd\u5225\u30e9\u30f3\u30ad\u30f3\u30b0\nsql = \"\"\"\nselect y.Country,Country_name,sum(Value) as Value \nfrom ym_2018_2020 y,country_eng c\nwhere \nhs9 = '630790029' and \nexp_imp =2 and \nym='202005' and\ny.Country = c.Country\ngroup by y.Country\norder by Value desc\n\"\"\"[1:-1]\ndf = pd.read_sql(sql,conn).head(10)\n\nax = sns.barplot(y=\"Country_name\", x=\"Value\", data=df.head(10),color='r')","meta":"{'source': 'AI4Code', 'id': '06692bc0da9b40'}"}
{"id":"76871","text":"\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nLooking LSTM Detailly !\n<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n![](https:\/\/www.csail.mit.edu\/sites\/default\/files\/2020-08\/FedTech-DeepLearning.jpg)\n\"\"\"\n\"\"\"\n### This time, I try Looking LSTM Detailly ( Especially Model's Weights )! \n\"\"\"\n\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nImport Libraries and Load Datasets\n<\/h1>\n<\/div>\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom keras import models, layers\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\n\nimport matplotlib.font_manager as fm\nbest_font = fm.FontProperties(fname='..\/input\/staatfont\/Staatliches-Regular.ttf')\n\"\"\"\n### I use bitcoin price dataset.\n### LSTM Showing great accuracy in Time series predict!\n\"\"\"\n\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nData processing and make simple model\n<\/h1>\n<\/div>\n\"\"\"\ndata =pd.read_csv(\"..\/input\/bitcoin-historical-data\/bitstampUSD_1-min_data_2012-01-01_to_2021-03-31.csv\")\ndata = data[['Timestamp','Open']]\ndata['Timestamp'] = pd.to_datetime(data['Timestamp'],unit='s').dt.date\ndata = data.dropna()\ndata = data.groupby('Timestamp').mean()\n\ndata = data.reset_index(drop=True)\ndata.columns=['price']\n\nscaler = MinMaxScaler()\ndata['price'] = scaler.fit_transform(np.array(data['price']).reshape(-1,1))\n\nX = []\ny = []\nfor i in range(len(data)-5):\n    X.append(list(data.loc[i:i+4,\"price\"]))\n    y.append(data.loc[i+5,\"price\"])\n    \nX = np.array(X)\ny = np.array(y)\nX = X.reshape(-1,5,1)\n\nmodel = models.Sequential()\nmodel.add(layers.LSTM(5,input_shape=X.shape[1:]))\nmodel.add(layers.Dense(1))\nmodel.compile(optimizer='adam',loss='MSE')\nmodel.summary()\nmodel.fit(X, y, epochs=5,verbose=2,validation_split=0.3)\n\"\"\"\n### I use only Price data and Windowing size is 5\n### I just make simple model.\n### If you want more great performance, Try increase Windowing size and NN\n\"\"\"\n\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nLook at model's Weights\n<\/h1>\n<\/div>\n\"\"\"\nnames = [weight.name for layer in model.layers for weight in layer.weights]\nweights = model.get_weights()\n\nnp.set_printoptions(suppress=True)\nfor name, weight in zip(names, weights):\n    print(name, weight.shape)\n    print(weight)\n\n    layer_type = name.split('\/')[1]\n    if layer_type == 'kernel:0':\n        kernel_0 = weight\n    if layer_type == 'recurrent_kernel:0':\n        recurrent_kernel_0 = weight\n    elif layer_type == 'bias:0':\n        bias_0 = weight\n    print()\n\"\"\"\n### The LSTM Model has 3 weights\n### 1. kernel\n### 2. recurrent_kernel\n### 3. bias\n\"\"\"\n\"\"\"\n![](https:\/\/www.oreilly.com\/library\/view\/neural-networks-and\/9781492037354\/assets\/mlst_1413.png)\n\"\"\"\n\"\"\"\n### This image help to understand LSTM's contruction\n\"\"\"\nkernel_weights = weights[0]\nrecurrent_kernel_weights = weights[1]\nbias = weights[2]\n\nn = 1\nunits = 5  # LSTM layers\n\n# (1, 20) embedding dims, units * 4\nWi = kernel_weights[:, 0:units]\nWf = kernel_weights[:, units:2 * units]\nWc = kernel_weights[:, 2 * units:3 * units]\nWo = kernel_weights[:, 3 * units:]\n\n# (5, 20) units, units * 4\nUi = recurrent_kernel_weights[:, 0:units]\nUf = recurrent_kernel_weights[:, units:2 * units]\nUc = recurrent_kernel_weights[:, 2 * units:3 * units]\nUo = recurrent_kernel_weights[:, 3 * units:]\n\n# (20,) units * 4\nbi = bias[0:units]\nbf = bias[units:2 * units]\nbc = bias[2 * units:3 * units]\nbo = bias[3 * units:]\n\ndef sigmoid(x):\n    return 1 \/ (1 + np.exp(-x))\nprint('Wf: ',Wf,'\\nWi: ',Wi,'\\nWo: ',Wo,'\\nWc: ',Wc,)\n\nprint('\\nUf: ',Uf,'\\nUi: ',Ui,'\\nUo: ',Uo,'\\nUc: ',Uc,)\n\nprint('\\nbf: ',bf,'\\nbi: ',bi,'\\nbo: ',bo,'\\nbc: ',bc,)\n\"\"\"\n![](https:\/\/wikimedia.org\/api\/rest_v1\/media\/math\/render\/svg\/2db2cba6a0d878e13932fa27ce6f3fb71ad99cf1)\n\"\"\"\n\"\"\"\n### Using weights, We can know Cell_state values(Ct) and Hidden_state(ht) values\n\"\"\"\nht_1 = np.zeros(n * units).reshape(n, units)\nCt_1 = np.zeros(n * units).reshape(n, units)\n\nresults = []\nfor t in range(0, len(X[2000,:])):\n    xt = np.array(X[2000,t])\n    ft = sigmoid(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf)  # forget gate\n    it = sigmoid(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi)  # input gate\n    ot = sigmoid(np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo)  # output gate\n    Ct = ft * Ct_1 + it * np.tanh(np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc)\n    ht = ot * np.tanh(Ct)\n\n    ht_1 = ht  # hidden state, previous memory state\n    Ct_1 = Ct  # cell state, previous carry state\n\n    results.append(ht)\n    print(t,': ht', ht)\nmodel.predict(X[2000:2001])\n\"\"\"\n### Using this calculation, We can get same values with model's predict\n### last hidden_state value(ht[4]) == model.predict value\n\"\"\"\n\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nWhich column will have the biggest impact?\n<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n### I want to know that Which columns have the biggest impact.\n### So, I calculate this LSTM process\n\"\"\"\nht_1 = np.zeros(n * units).reshape(n, units)\nCt_1 = np.zeros(n * units).reshape(n, units)\n\nh_t_value = []\n\ninfluence_h_t_value = []\nfor t in range(0, len(X[1000,:])):\n    xt = np.array(X[1000,t])\n    ft = sigmoid(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf)  # forget gate\n    influence_ft = (np.dot(ht_1, Uf))\/(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf) * ft\n\n    it = sigmoid(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi)  # input gate\n    influence_it = (np.dot(ht_1, Ui))\/(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi) * it\n\n    ot = sigmoid(np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo)  # output gate\n    influence_ot = np.dot(ht_1, Uo) \/ (np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo) * ot\n\n    gt =  np.tanh(np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc)\n    influence_gt =np.dot(ht_1, Uc) \/ (np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc) * gt\n    \n    Ct = ft * Ct_1 + it * gt\n    influence_ct = influence_ft * Ct_1 + influence_it * influence_gt\n    ht = ot * np.tanh(Ct)\n    influence_ht = influence_ot * (influence_ct\/Ct) * ht\n    \n    influence_h_t_value.append(influence_ht)\n\n    ht_1 = ht  # hidden state, previous memory state\n    Ct_1 = Ct  # cell state, previous carry state\n    \n    h_t_value.append(ht)\n    \ninfluence_h_t_value.append(h_t_value[-1])\nfor i in range(len(influence_h_t_value)-1,0,-1):\n    influence_h_t_value[i] = influence_h_t_value[i] - influence_h_t_value[i-1]\n    \ninfluence_h_t_value = influence_h_t_value[1:]\nimpact_columns = np.dot(influence_h_t_value,weights[3]) + (weights[4]\/5)\n\nfor i in range(len(impact_columns)):\n    print('columns_number : ',i, 'impact value : ', float(impact_columns[i]))\n    \nprint('\\nSum of value : ', float(sum(np.dot(influence_h_t_value,weights[3]) + (weights[4]\/5))))\n\nprint('\\nkeras model_predict : ', float(model.predict(X[1000:1001])))\n\"\"\"\n### I've used three days to do this. \ud83d\ude34\n\"\"\"\n\"\"\"\n### Then, Why am i obsessed with the impact?\n\"\"\"\n\"\"\"\n<div style=\"color:white;\n           display:fill;\n           border-radius:5px;\n           background-color:blue;\n           font-size:110%;\n           font-family:Verdana;\n           letter-spacing:0.5px\">\n<h1 style=\"text-align: center;\n           padding: 10px;\n              color:white\">\nTrying on NLP ! ( Review Data )\n<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n### I just try that on NLP\n\"\"\"\ndata = pd.read_csv('..\/input\/womens-ecommerce-clothing-reviews\/Womens Clothing E-Commerce Reviews.csv')\ndata = data[['Review Text','Rating']]\ndata = data.dropna()\npositive = data[(data['Rating'] == 5)].sample(2370,random_state=100)\nnegative = data[(data['Rating'] == 2) | (data['Rating'] == 1)]\ndata = pd.concat([negative,positive])\ndata = data.reset_index(drop=True)\n\ndata['Rating'] = data['Rating'].apply(lambda x : 1 if x==5 else 0)\n\"\"\"\n### I used Womens Clothing E-Commerce Reviews dataset\n\"\"\"\ndata.head(5)\ndata.tail(5)\n\"\"\"\n### Rating mean that 0 is Negative review, and 1 is Positive review\n\"\"\"\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\n\ndef data_processing(text):\n    return_arr = []\n    text = re.sub(r\"[^a-zA-Z]\",\" \",text)\n    text = re.sub(r\" {2,}\",\" \",text)\n    text = text.lower()\n    words = word_tokenize(text)\n    s = PorterStemmer()\n    stopword = stopwords.words('english')\n    for t in words:\n        if t not in stopword:\n            return_arr.append(t)\n            \n    return_arr = [s.stem(w) for w in return_arr]\n    return return_arr\n\ndata['processing'] = data['Review Text'].apply(data_processing)\n\"\"\"\n### I only use alphabet text, (delete special character or number)\n### And, delete stopwords, changing analogous term.\n\"\"\"\nlen_arr = []\nfor i in range(len(data)):\n    len_arr.append(len(data.loc[i,'processing']))\n    \nimport seaborn as sns\nsns.histplot(len_arr)\ndef data_processing2(text):\n    return_arr = []\n    text = re.sub(r\"[^a-z]\",\" \",text)\n    text = re.sub(r\" {2,}\",\" \",text)\n    return text\n\nnegative_sentences = data[data['Rating'] ==0]['processing']\npositive_sentences = data[data['Rating'] ==1]['processing']\n\nnegative_sentences = str(list(negative_sentences))\nnegative_sentences = data_processing2(negative_sentences)\n\nnegative_sentences = negative_sentences.split(' ')\nnegative_sentences = pd.DataFrame(negative_sentences)[0].value_counts()\nnegative_sentences = pd.DataFrame(negative_sentences)\n\npositive_sentences = str(list(positive_sentences))\npositive_sentences = data_processing2(positive_sentences)\n\npositive_sentences = positive_sentences.split(' ')\npositive_sentences = pd.DataFrame(positive_sentences)[0].value_counts()\npositive_sentences = pd.DataFrame(positive_sentences)\n\ncon = pd.concat([negative_sentences,positive_sentences],axis=1)\n\ncon.columns = ['negative','positive']\n\ncon = con.dropna()\n\ncon['negative_value'] = con[['negative','positive']].apply(lambda x : x[0]\/(x[0]+x[1]) *-1,axis=1)\ncon['positive_value'] = con[['negative','positive']].apply(lambda x : x[1]\/(x[0]+x[1]),axis=1)\n\ncon['total_value'] = con['negative_value'] + con['positive_value']\ncon = con.reset_index()\ncon = con.drop(['negative','positive','negative_value','positive_value'],axis=1)\nword_index =con['index'].to_list()\ncon = np.array(con)\n\"\"\"\n### And, I just use, Rate of Negative words, and Positive word \n\n### It mean\n\n### Negative Rate : -1 * Negatvie Counts \/ (Negative Counts + Positive Counts)\n### Positive Rate : 1 * Positive Counts \/ (Negative Counts + Positive Counts)\n\n### After Sum Two : Negative Rate + Positive Rate\n\"\"\"\ncon[:10]\nfrom tqdm import tqdm\n\nX = []\nfor sen in tqdm(data['processing']):\n    word_arr =[]\n    for word in sen:\n        if word in word_index:\n            word_arr.append(float(con[con[:,0] ==word,1]))\n        else:\n            word_arr.append(0)\n    X.append(word_arr)\nX = pd.DataFrame(X)\nX = X.fillna(0)\nX = X.loc[:,:50]\nX= X.to_numpy()\ny = np.array(data['Rating'])\nX = X.reshape(4740,51,1)\nX.shape, y.shape\nfrom tensorflow.keras.layers import Embedding, Dense,LSTM\nfrom tensorflow.keras.models import Sequential\n\nmodel = Sequential()\nmodel.add(LSTM(51,input_shape=X.shape[1:],activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])\nmodel.summary()\n\"\"\"\n### Just use simple LSTM Model\n\"\"\"\nmodel.fit(X,y, batch_size=128, epochs=15, validation_split=0.3)\nnames = [weight.name for layer in model.layers for weight in layer.weights]\nweights = model.get_weights()\n\nkernel_weights = weights[0]\nrecurrent_kernel_weights = weights[1]\nbias = weights[2]\n\nn = 1\nunits = 51  # LSTM layers\n\nWi = kernel_weights[:, 0:units]\nWf = kernel_weights[:, units:2 * units]\nWc = kernel_weights[:, 2 * units:3 * units]\nWo = kernel_weights[:, 3 * units:]\n\nUi = recurrent_kernel_weights[:, 0:units]\nUf = recurrent_kernel_weights[:, units:2 * units]\nUc = recurrent_kernel_weights[:, 2 * units:3 * units]\nUo = recurrent_kernel_weights[:, 3 * units:]\n\nbi = bias[0:units]\nbf = bias[units:2 * units]\nbc = bias[2 * units:3 * units]\nbo = bias[3 * units:]\ndef make_plot(number):\n    ht_1 = np.zeros(n * units).reshape(n, units)\n    Ct_1 = np.zeros(n * units).reshape(n, units)\n\n    h_t_value = []\n\n    influence_h_t_value = []\n    for t in range(0, len(X[number,:])):\n        xt = np.array(X[number,t])\n        ft = sigmoid(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf)  # forget gate\n        influence_ft = (np.dot(ht_1, Uf))\/(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf) * ft\n\n        it = sigmoid(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi)  # input gate\n        influence_it = (np.dot(ht_1, Ui))\/(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi) * it\n\n        ot = sigmoid(np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo)  # output gate\n        influence_ot = np.dot(ht_1, Uo) \/ (np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo) * ot\n\n        gt =  np.tanh(np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc)\n        influence_gt =np.dot(ht_1, Uc) \/ (np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc) * gt\n\n        Ct = ft * Ct_1 + it * gt\n        influence_ct = influence_ft * Ct_1 + influence_it * influence_gt\n        ht = ot * np.tanh(Ct)\n        influence_ht = influence_ot * (influence_ct\/Ct) * ht\n\n        influence_h_t_value.append(influence_ht)\n\n        ht_1 = ht  # hidden state, previous memory state\n        Ct_1 = Ct  # cell state, previous carry state\n\n        h_t_value.append(ht)\n\n    influence_h_t_value.append(h_t_value[-1])\n    for i in range(len(influence_h_t_value)-1,0,-1):\n        influence_h_t_value[i] = influence_h_t_value[i] - influence_h_t_value[i-1]\n\n    influence_h_t_value = influence_h_t_value[1:]\n\n    impact_columns = np.dot(influence_h_t_value,weights[3]) + (weights[4]\/units)\n\n    if model.predict(X[number:number+1]) > 0.5:\n        b_color = 'lightgreen'\n    else:\n        b_color ='lightcyan'\n\n    fig = plt.figure(figsize=(15,3),facecolor=b_color)\n\n    for k in range(len(data.loc[number,'processing'])):\n        s = data.loc[number,'processing'][k]\n        va = round(float(impact_columns[k]),2)\n        if va > 0.5:\n            color ='green'\n        elif va< -0.3:\n            color ='blue'\n        else:\n            color ='black'\n\n        if k < 17:\n            plt.text(s=s, x=k*0.7, y=0,font=best_font,fontsize=20,color=color,va='center',ha='center')\n            plt.text(s=va,x=k*0.7, y=-0.1,font=best_font,fontsize=20,color=color,va='center',ha='center')\n        elif k < 34:\n            plt.text(s=s, x=k*0.7 - 17*0.7, y=-0.2,font=best_font,fontsize=20,color=color,va='center',ha='center')\n            plt.text(s=va,x=k*0.7- 17*0.7, y=-0.3,font=best_font,fontsize=20,color=color,va='center',ha='center')\n        else:\n            plt.text(s=s, x=k*0.7 - 34*0.7, y=-0.4,font=best_font,fontsize=20,color=color,va='center',ha='center')\n            plt.text(s=va,x=k*0.7- 34*0.7, y=-0.5,font=best_font,fontsize=20,color=color,va='center',ha='center')\n\n    plt.xlim(0,10)\n    plt.ylim(-0.5,0.1)\n    plt.axis('off')\n    plt.show()\n\"\"\"\n### If influence value is more than 0.5 : Green color\n### If influence value is lower than -0.5 : blue color\n\n### The background color mean too\n\"\"\"\n\"\"\"\n### ( I don't consider activation function like sigmoid )\n\"\"\"\nmake_plot(489)\nmake_plot(2243)\nmake_plot(2378)\nmake_plot(2628)\nmake_plot(4560)\nmake_plot(4339)\n\"\"\"\n### I expect if you use word2vec or FastText. etc Can get more meaningful accuracy.\n### If you have Good idea, feel free to review comments plz.\n### I always welcom feedback\n\"\"\"\n\"\"\"\n### reference\n* http:\/\/docs.likejazz.com\/lstm\/\n* http:\/\/colah.github.io\/posts\/2015-08-Understanding-LSTMs\/\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8d38a8b4820145'}"}
{"id":"66080","text":"\"\"\"\n<div>\n    <h1 align=\"center\">Tabular Playground Series - Jul 2021<\/h1>\n    <h1 align=\"center\">XGBoost & LeaveOneGroupOut & Ensembling<\/h1>\n    <h4 align=\"center\">By: Somayyeh Gholami & Mehran Kazeminia<\/h4>\n<\/div>\n\"\"\"\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n<div class=\"alert alert-success\">\n    <h1 align=\"center\">If you find this work useful, please don't forget upvoting :)<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n## Import\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom xgboost import XGBRegressor\nfrom catboost import CatBoostRegressor\nfrom sklearn.linear_model import Ridge\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeaveOneGroupOut\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Data Set\n\"\"\"\nDF1 = pd.read_csv('..\/input\/tabular-playground-series-jul-2021\/train.csv')\n\nDF2 = pd.read_csv('..\/input\/tabular-playground-series-jul-2021\/test.csv')\n\nSAM = pd.read_csv('..\/input\/tabular-playground-series-jul-2021\/sample_submission.csv')\nMV1 = DF1.isnull().sum()\nMV2 = DF2.isnull().sum()\n\nprint(f'Missing Value 1:  {MV1[MV1 > 0]}')\nprint(f'Missing Value 2:  {MV2[MV2 > 0]}')\ndisplay(DF1, DF2)\n# display(DF1.info(), DF2.info())\n# display(DF1.describe().transpose())\n# display(DF2.describe().transpose())\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\ndata1 = DF1.copy()\ndata2 = DF2.copy()\nX = data1.drop(columns = ['target_carbon_monoxide', 'target_benzene', 'target_nitrogen_oxides'])\nX['date_time'] = X['date_time'].astype('datetime64[ns]').astype(np.int64)\/10**9\n\ndisplay(X)\ny1 = data1.target_carbon_monoxide\ny2 = data1.target_benzene\ny3 = data1.target_nitrogen_oxides\n# display(y1, y2, y3)\nXX = data2.copy()\nXX['date_time'] = XX['date_time'].astype('datetime64[ns]').astype(np.int64)\/10**9\n\ndisplay(XX)\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Split\n\"\"\"\ntrain_X, val_X, train_y1, val_y1 = train_test_split(X, y1, test_size=0.50, random_state=123)\ntrain_X, val_X, train_y2, val_y2 = train_test_split(X, y2, test_size=0.50, random_state=123)\ntrain_X, val_X, train_y3, val_y3 = train_test_split(X, y3, test_size=0.50, random_state=123)\nval_X.to_csv(\"val_X.csv\",index=False)\n\nval_y1.to_csv(\"val_y1.csv\",index=False)\nval_y2.to_csv(\"val_y2.csv\",index=False)\nval_y3.to_csv(\"val_y3.csv\",index=False)\n\"\"\"\n<div class=\"alert alert-success\">\n    <h1 align=\"center\">XGBRegressor<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n## Validation Model - 1 \n\n### [ target_carbon_monoxide ]\n\"\"\"\nmodel1v = XGBRegressor(max_depth=6,\n                       n_estimators=250,\n                       learning_rate=0.08,\n                       subsample=0.7,\n                       alpha=0.5,\n                       random_state=123)                           \n        \nmodel1v.fit(train_X, train_y1, verbose=100)\noof_pred1 = model1v.predict(val_X)\n\noof_pred1 = np.clip(oof_pred1, 0.30, y1.max())\n# oof_pred1 = np.clip(oof_pred1, y1.min(), y1.max())\n\nprint(40 * '=')\nprint(f'Mean Absolute Error: {mean_absolute_error(val_y1, oof_pred1)}')\nprint(40 * '=')\nmodel1v.feature_importances_\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Validation Model - 2 \n\n### [ target_benzene ]\n\"\"\"\nmodel2v = XGBRegressor(max_depth=6,\n                       n_estimators=400,\n                       learning_rate=0.07,\n                       subsample=0.7,\n                       alpha=0.7,\n                       random_state=123)          \n\nmodel2v.fit(train_X, train_y2, verbose=100)\noof_pred2 = model2v.predict(val_X)\n\noof_pred2 = np.clip(oof_pred2, 0.10, y2.max())\n# oof_pred2 = np.clip(oof_pred2, y1.max(), y2.max())\n\nprint(40 * '=')\nprint(f'Mean Absolute Error: {mean_absolute_error(val_y2, oof_pred2)}')\nprint(40 * '=')\nmodel2v.feature_importances_\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Validation Model - 3 \n\n### [ target_nitrogen_oxides ]\n\"\"\"\nmodel3v = XGBRegressor(max_depth=8,\n                       n_estimators=500,\n                       learning_rate=0.03,\n                       subsample=0.7,\n                       alpha=0.8,\n                       random_state=123)                           \n\nmodel3v.fit(train_X, train_y3, verbose=100)\noof_pred3 = model3v.predict(val_X)\n\noof_pred3 = np.clip(oof_pred3, 20.0, y3.max())\n# oof_pred3 = np.clip(oof_pred3, y3.min(), y3.max())\n\nprint(40 * '=')\nprint(f'Mean Absolute Error: {mean_absolute_error(val_y3, oof_pred3)}')\nprint(40 * '=')\nmodel3v.feature_importances_\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Feature Importances\n\"\"\"\naxis_x  = X.columns.values\naxis_y1 = model1v.feature_importances_\naxis_y2 = model2v.feature_importances_\naxis_y3 = model3v.feature_importances_\n\nplt.style.use('seaborn-whitegrid') \nplt.figure(figsize=(16, 6), facecolor='lightgray')\nplt.title(f'\\nX G B o o s t\\n\\nF e a t u r e   I m p o r t a n c e s\\n', fontsize=14)  \n\nplt.scatter(axis_x, axis_y1, s=120, label='target_carbon_monoxide') \nplt.scatter(axis_x, axis_y2, s=120, label='target_benzene')\nplt.scatter(axis_x, axis_y3, s=120, label='target_nitrogen_oxides')\nplt.legend(fontsize=12, loc=2)\nplt.show() \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Model - 1 \n\n### [ target_carbon_monoxide ]\n\"\"\"\nmodel1 = XGBRegressor(max_depth=6,\n                      n_estimators=250,\n                      learning_rate=0.08,\n                      subsample=0.7,\n                      alpha=0.5,\n                      random_state=123)                         \n\nmodel1.fit(X, y1)\npred1 = model1.predict(XX)\npred1 = np.clip(pred1, 0.30, y1.max())\ndisplay(pred1, pred1.shape) \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Model - 2 \n\n### [ target_benzene ]\n\"\"\"\nmodel2 = XGBRegressor(max_depth=6,                     \n                      n_estimators=400,\n                      learning_rate=0.07,\n                      subsample=0.7,\n                      alpha=0.7,\n                      random_state=123)        \n\nmodel2.fit(X, y2)\npred2 = model2.predict(XX)\npred2 = np.clip(pred2, 0.10, y2.max())\ndisplay(pred2, pred2.shape) \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n## Model - 3 \n\n### [ target_nitrogen_oxides ]\n\"\"\"\nmodel3 = XGBRegressor(max_depth=8,\n                      n_estimators=500,\n                      learning_rate=0.03,\n                      subsample=0.7,\n                      alpha=0.8,\n                      random_state=123)                           \n\nmodel3.fit(X, y3)\npred3 = model3.predict(XX)\npred3 = np.clip(pred3, 20.0, y3.max())\ndisplay(pred3, pred3.shape) \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\nsub_xgb = SAM.copy()\n\nsub_xgb['target_carbon_monoxide'] = pred1\nsub_xgb['target_benzene'] = pred2\nsub_xgb['target_nitrogen_oxides'] = pred3\ndisplay(sub_xgb)\nsub = sub_xgb\nsub.to_csv(\"submission_xgb.csv\",index=False)\n# Public Score: 0.23087 \n!ls\n\"\"\"\n<div class=\"alert alert-success\">\n    <h1 align=\"center\">LeaveOneGroupOut<\/h1>\n<\/div>\n\"\"\"\n\"\"\"\n## Data Augmentation\n\"\"\"\nmonths1 = []\nfor i in range(len(data1)):  \n    \n    row  = data1.iloc[i,0]    \n    mon  = int(row[5:7])\n    #day = int(row[8:10])\n    #hou = int(row[11:13])    \n    if (mon == 1): mon=12  \n    months1.append(mon)   \n    \ndata1['months'] = months1\ndisplay(data1)    \nmonths2 = []\nfor i in range(len(data2)):  \n    \n    row  = data2.iloc[i,0]    \n    mon  = int(row[5:7])\n    #day = int(row[8:10])\n    #hou = int(row[11:13])  \n    months2.append(mon)   \n    \ndata2['months'] = months2\ndisplay(data2)    \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\ngroups = data1['months']\ndisplay(groups)\nlogo = LeaveOneGroupOut()\n\nprint(logo.get_n_splits(X, y1, groups))\nprint(logo.get_n_splits(X, y2, groups))\nprint(logo.get_n_splits(X, y3, groups))\nfor train_index, test_index in logo.split(X, y1, groups):\n              \n    print(f'Train index:\\n{train_index}')    \n    print(f'\\nTest index:\\n{test_index}')\n    print(70 * '=') \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\npred1_leave = np.zeros(len(XX))\nfor train_index, test_index in logo.split(X, y1, groups):\n\n    X_train, X_test = X.iloc[train_index], X.iloc[test_index]   \n    y_train, y_test = y1.iloc[train_index], y1.iloc[test_index]\n    \n    model1.fit(X_train, y_train.ravel())  \n    pred1_leave += (model1.predict(XX)) \/ 10\n\ndisplay(pred1_leave, pred1_leave.shape) \npred2_leave = np.zeros(len(XX))\nfor train_index, test_index in logo.split(X, y2, groups):\n\n    X_train, X_test = X.iloc[train_index], X.iloc[test_index]   \n    y_train, y_test = y2.iloc[train_index], y2.iloc[test_index]\n    \n    model2.fit(X_train, y_train.ravel())  \n    pred2_leave += (model2.predict(XX)) \/ 10\n\ndisplay(pred2_leave, pred2_leave.shape) \npred3_leave = np.zeros(len(XX))\nfor train_index, test_index in logo.split(X, y3, groups):\n\n    X_train, X_test = X.iloc[train_index], X.iloc[test_index]   \n    y_train, y_test = y3.iloc[train_index], y3.iloc[test_index]\n    \n    model3.fit(X_train, y_train.ravel())  \n    pred3_leave += (model3.predict(XX)) \/ 10\n\ndisplay(pred3_leave, pred3_leave.shape) \n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\nsub_leave = SAM.copy()\n\nsub_leave['target_carbon_monoxide'] = pred1_leave\nsub_leave['target_benzene'] = pred2_leave\nsub_leave['target_nitrogen_oxides'] = pred3_leave\ndisplay(sub_leave)\nsub = sub_leave\nsub.to_csv(\"submission_leave.csv\",index=False)\n# Public Score: 0.22736\n!ls\n\"\"\"\n<div class=\"alert alert-success\">\n    <h1 align=\"center\">Ensembling<\/h1>\n<\/div>\n\"\"\"\ndef ensembling(main, support, coeff1, coeff2, coeff3): \n    \n    suba  = main.copy() \n    subav = suba.values\n       \n    subb  = support.copy()\n    subbv = subb.values    \n           \n    ense  = main.copy()    \n    ensev = ense.values  \n \n    for i in range (len(main)):\n        \n        pera1 = subav[i, 1]\n        pera2 = subav[i, 2]\n        pera3 = subav[i, 3]\n        \n        perb1 = subbv[i, 1]\n        perb2 = subbv[i, 2]\n        perb3 = subbv[i, 3]\n\n        per1 = (pera1 * coeff1) + (perb1 * (1.0 - coeff1))\n        per2 = (pera2 * coeff2) + (perb2 * (1.0 - coeff2))\n        per3 = (pera3 * coeff3) + (perb3 * (1.0 - coeff3))\n        \n        ensev[i, 1] = per1\n        ensev[i, 2] = per2\n        ensev[i, 3] = per3\n        \n    ense.iloc[:, 1:] = ensev[:, 1:] \n    \n    ###############################    \n    X  = suba.iloc[:, 1]\n    Y1 = subb.iloc[:, 1]\n    Y2 = ense.iloc[:, 1]\n    \n    plt.style.use('seaborn-whitegrid') \n    plt.figure(figsize=(9, 9), facecolor='lightgray')\n    plt.title(f'\\nP R E D I C T  1\\n\\ntarget_carbon_monoxide\\n')   \n    \n    \n    plt.scatter(X, Y1, s=2.0, label='Support')    \n    plt.scatter(X, Y2, s=2.0, label='Generated')\n    plt.scatter(X, X , s=0.1, label='Main(X=Y)')\n    \n    plt.legend(fontsize=12, loc=2)\n    plt.show()     \n    ###############################      \n    X  = suba.iloc[:, 2]\n    Y1 = subb.iloc[:, 2]\n    Y2 = ense.iloc[:, 2]\n    \n    plt.style.use('seaborn-whitegrid') \n    plt.figure(figsize=(9, 9), facecolor='lightgray')\n    plt.title(f'\\nP R E D I C T  2\\n\\ntarget_benzene\\n')   \n    \n    \n    plt.scatter(X, Y1, s=2.0, label='Support')    \n    plt.scatter(X, Y2, s=2.0, label='Generated')\n    plt.scatter(X, X , s=0.1, label='Main(X=Y)')\n    \n    plt.legend(fontsize=12, loc=2)\n    plt.show()     \n    ############################### \n    X  = suba.iloc[:, 3]\n    Y1 = subb.iloc[:, 3]\n    Y2 = ense.iloc[:, 3]\n    \n    plt.style.use('seaborn-whitegrid') \n    plt.figure(figsize=(9, 9), facecolor='lightgray')\n    plt.title(f'\\nP R E D I C T  3\\n\\ntarget_nitrogen_oxides\\n')   \n    \n    \n    plt.scatter(X, Y1, s=2.0, label='Support')    \n    plt.scatter(X, Y2, s=2.0, label='Generated')\n    plt.scatter(X, X , s=0.1, label='Main(X=Y)')\n    \n    plt.legend(fontsize=12, loc=2)\n    plt.show()     \n    ############################### \n    \n    return ense      \n\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\nThanks to: @paddykb https:\/\/www.kaggle.com\/paddykb\/tps-07-gam-baseline \n\"\"\"\nsub21744 = pd.read_csv('..\/input\/tps7-21744\/submission_gam.csv')\n\nsub_ense = ensembling(sub21744, sub_leave, 0.65, 0.55, 0.75)\nsub = sub_ense\nsub.to_csv(\"submission_ense.csv\",index=False)\n# Public Score: \n!ls\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"\n\"\"\"\n<div class=\"alert alert-success\">  \n<\/div>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '79d15bfc2fdcbb'}"}
{"id":"47780","text":"\"\"\"\n# Student Alcohol Consumption\n\n### Exploratory Data Analysis\n\"\"\"\n\"\"\"\nIn this notebook we are going to see how to perform an exploratory data analysis, a step that should be performed over every new dataset before to proceed with the development of predictive models. In this case, our goal is to understand what are the factors that affect the performance of students at high school. In particular, we are interested to know the impact of the consumption of alcohol.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nmath = pd.read_csv(\"..\/input\/student-mat.csv\")\n\"\"\"\nLet's see what the dataset looks like.\n\"\"\"\nmath.head()\nmath.columns\nmath.describe()\n\"\"\"\nWe have some variables that could be interesting. Some of the variables are categorical, and other are continuous. They require a different type of analysis.\n\"\"\"\n\"\"\"\nIt is highly convenient to add the average grade to the dataframe.\n\"\"\"\nmath[\"Average\"] = (math['G1'] + math['G2'] + math['G3']) \/ 3\n\"\"\"\nAlso, it would be very nice to have a variable showing if the student has or has not passed the course, but we are not sure if that it is computed as the average of the three grades. So, let's call it if the student has been approved (1 - approved, 0 - not approved).\n\"\"\"\nmath[\"Approved\"] = [ (1 if x > 10 else 0) for x in math[\"Average\"] ]\n\"\"\"\n### School\n\"\"\"\n\"\"\"\nSince we have data from two different schools, let's see if there are any differences in grades by school\n\"\"\"\nmath[\"school\"].unique()\nlen(math[math[\"school\"] == 'GP'])\nlen(math[math[\"school\"] == 'MS'])\n\"\"\"\n46 students is barely statistically significant. Moreover if we take into account that for model evaluation we have to split the data in train\/test subsets, and that the sampling should be stratified. \n\"\"\"\n\"\"\"\nAnyway, check if school is a good predictior.\n\"\"\"\ndata = [list( (math[math[\"school\"] == 'GP']['G1'] + math[math[\"school\"] == 'GP']['G2'] + math[math[\"school\"] == 'GP']['G3']) \/ 3),\n        list( (math[math[\"school\"] == 'MS']['G1'] + math[math[\"school\"] == 'MS']['G2'] + math[math[\"school\"] == 'MS']['G3']) \/ 3)]\nplt.boxplot(data)\nplt.xticks(np.arange(3), ['', 'Gabriel Pereira', 'Mousinho da Silveira'])\nplt.title(\"Grades per School\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"School\")\nplt.show()\nplt.show()\n\"\"\"\nIt seems there are no relevant differences.\n\"\"\"\n\"\"\"\nLet's see why people have chosen one school or the ohter.\n\"\"\"\nmath[math[\"school\"] == 'GP']['reason'].value_counts().plot(kind='bar')\nmath[math[\"school\"] == 'MS']['reason'].value_counts().plot(kind='bar')\n\"\"\"\nFortunately is not due to school \"reputation\", since there are no differences in grades.\n\"\"\"\n\"\"\"\n### Internet\n\"\"\"\n\"\"\"\nLet's see, for example, if having Internet at home makes any difference in grades.\n\"\"\"\nmath[\"internet\"].unique()\nlen(math[math[\"internet\"] == 'yes']), len(math[math[\"internet\"] == 'no'])\ndata = [list(math[math[\"internet\"] == \"yes\"][\"Average\"]), list(math[math[\"internet\"] == \"no\"][\"Average\"])]\nplt.boxplot(data)\nplt.xticks(np.arange(3), ['', 'Yes', 'No'])\nplt.title(\"Internet at Home\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Internet\")\nplt.show()\n\"\"\"\nNo, it seems it does not.\n\"\"\"\n\"\"\"\n### Identify Predictive Features\n\"\"\"\n\"\"\"\nThe same work we have done with the \"internet\" variable can be done with the rest of the categorical variables\n\"\"\"\ndata = [list(math[math[\"sex\"]        == \"M\"][\"Average\"]),   list(math[math[\"sex\"]        == \"F\"][\"Average\"]),\n        list(math[math[\"address\"]    == \"U\"][\"Average\"]),   list(math[math[\"address\"]    == \"R\"][\"Average\"]),\n        list(math[math[\"famsize\"]    == \"LE3\"][\"Average\"]), list(math[math[\"famsize\"]    == \"GT3\"][\"Average\"]),\n        list(math[math[\"Pstatus\"]    == \"T\"][\"Average\"]),   list(math[math[\"Pstatus\"]    == \"A\"][\"Average\"]),\n        list(math[math[\"schoolsup\"]  == \"yes\"][\"Average\"]), list(math[math[\"schoolsup\"]  == \"no\"][\"Average\"]),        \n        list(math[math[\"higher\"]     == \"yes\"][\"Average\"]), list(math[math[\"higher\"]     == \"no\"][\"Average\"]),\n        list(math[math[\"nursery\"]    == \"yes\"][\"Average\"]), list(math[math[\"nursery\"]    == \"no\"][\"Average\"]), \n        list(math[math[\"activities\"] == \"yes\"][\"Average\"]), list(math[math[\"activities\"] == \"no\"][\"Average\"]),\n        list(math[math[\"paid\"]       == \"yes\"][\"Average\"]), list(math[math[\"paid\"]       == \"no\"][\"Average\"]),        \n        list(math[math[\"famsup\"]     == \"yes\"][\"Average\"]), list(math[math[\"famsup\"]     == \"no\"][\"Average\"]),        \n        list(math[math[\"romantic\"]   == \"yes\"][\"Average\"]), list(math[math[\"romantic\"]   == \"no\"][\"Average\"]),        \n       ]\n\"\"\"\nLet's make the size of the figures a little bit bigger.\n\"\"\"\nfrom matplotlib.pylab import rcParams\nrcParams['figure.figsize'] = 20, 10\nplt.boxplot(data)\nplt.xticks(np.arange(23), [\"\", \"Male\", \"Female\", \"Urban\", \"Rural\", \"LE3\", \"GE3\", \"Together\", \"Apart\", \"Support-Y\", \"Support-N\", \n                          \"High-Y\", \"High-N\", \"Nursery-Y\", \"Nursery-N\", \"Activities-Y\", \"Activities-N\", \"Paid-Y\", \"Paid-N\",\n                          \"Famsup-Y\", \"Famsup-N\", \"Romance-Y\", \"Romance-N\"])\nplt.title(\"Predictive Feautres\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Feature\")\nplt.show()\n\"\"\"\nTwo good candidates as predictive features are if the student plans to study higher education and if the student has extra educational support. In the former case, probably, because students that want to continue studies make an extra effor to get better grades; and in the latter case because it seems that bad students require additional study support.\n\"\"\"\n\"\"\"\n### Multicategory variables\n\"\"\"\n\"\"\"\nFor the analysis of non-binary categorical variables we will use a simmilar technique.\n\"\"\"\nmath[[\"Mjob\", \"Average\"]].boxplot(by=\"Mjob\")\nplt.title(\"Mother Jobs\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Job\")\nplt.show()\nmath[[\"Fjob\", \"Average\"]].boxplot(by=\"Fjob\")\nplt.title(\"Father Jobs\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Job\")\nplt.show()\nmath[[\"Fjob\", \"Average\"]].boxplot(by=\"Fjob\")\nplt.title(\"Student's Guardian\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Guardian\")\nplt.show()\n\"\"\"\nAll the three variables have low predictive power to the final grade, and so, we will not use them in the final model.\n\"\"\"\n\"\"\"\n### Alcohol Consumption\n\"\"\"\n\"\"\"\nThe same technique applied in the above section can be used to check if alcohol consumption is an indicator of poor school performance.\n\"\"\"\nmath[[\"Dalc\", \"Average\"]].boxplot(by=\"Dalc\")\nplt.title(\"Daily Alcohol Consumption\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Level of Consumption\")\nplt.show()\nmath[[\"Walc\", \"Average\"]].boxplot(by=\"Walc\")\nplt.title(\"Weelend Alcohol Consumption\")\nplt.ylabel(\"Average Grades\")\nplt.xlabel(\"Level of Consumption\")\nplt.show()\n\"\"\"\nIt seems that alcohol consumption is not strongly related to school performance.\n\"\"\"\n\"\"\"\n### Predictive Models\n\"\"\"\n\"\"\"\nGiven the characteristics of the dataset (number of samples and type of variables) I would recommend to use decision trees as the family of candidate models to consider. An advantage of decision tress is the interpretability of results, so we can understand why do students fail to pass exams.\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\n\"\"\"\nLet's use the numberical variables\n\"\"\"\nattributes = [\"age\", \"Medu\", \"Fedu\", \"traveltime\", \"studytime\", \"failures\", \"famrel\", \"freetime\", \"goout\", \"Dalc\", \"Walc\", \"health\", \"absences\"]\nX = math[attributes]\ny = math[\"Approved\"]\n\"\"\"\nAnd the two identified categorical attributes.\n\"\"\"\nX = X.assign(schoolsup = [ (1 if x == \"yes\" else 0) for x in math[\"schoolsup\"] ])\nX = X.assign(higher = [ (1 if x == \"yes\" else 0) for x in math[\"higher\"] ])\nattributes.append(\"schoolsup\")\nattributes.append(\"higher\")\nX.head()\n\"\"\"\nFit a single model\n\"\"\"\nmodel = DecisionTreeClassifier(min_samples_leaf=20)\nmodel.fit(X, y)\nmodel.score(X, y)\n\"\"\"\nLet's see what would happen in case of a random guessing.\n\"\"\"\nnp.sum(math[\"Approved\"]) \/ len(math)\n\"\"\"\nIt seems that the model has \"true\" prediction capabilities.\n\"\"\"\n\"\"\"\nLet's see how the tree looks like\n\"\"\"\nimport graphviz\nfrom sklearn import tree\ndot_data = tree.export_graphviz(model, out_file=None)\ngraph = graphviz.Source(dot_data)\ngraph\nattributes[5]\n\"\"\"\nIt seems that if a student has already failed, he will fail again.\n\"\"\"\nattributes[13]\n\"\"\"\nAnd that if the student is getting external support is because it is likely that he will fail again\n\"\"\"\n\"\"\"\nThe amount of alcohol ingested during week days nor weekends is not a predictive variable according to the identified model (it does not appear until the sixth level of the tree).\n\"\"\"\n\"\"\"\n### Advanced Test\n\"\"\"\n\"\"\"\nThe previous model was tested on the same training sample. A more realistic testing requires to use a separate training\/testing subsets.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\nmodel = DecisionTreeClassifier(min_samples_leaf=20)\nmodel.fit(X_train, y_train)\nmodel.score(X_test, y_test)\n\"\"\"\nWe still have some predictive capabilities.\n\"\"\"\n\"\"\"\nAnd a more advanced testing uses a cross validation approach.\n\"\"\"\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import ShuffleSplit\nmodel = DecisionTreeClassifier(min_samples_leaf=20)\ncv_ss = ShuffleSplit(n_splits=100, test_size=0.3, random_state=1)\nscores = cross_val_score(model, X, y, cv=cv_ss, n_jobs=-1)\nprint(\"Accuracy: %0.2f (+\/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n\"\"\"\nNow we can say we are confident about the reported accuracy. Unfortunately, the model has low predictive power.\n\"\"\"\n\"\"\"\n### Conclusions\n\"\"\"\n\"\"\"\nThe original question was if alcohol consumption affects the performance of students at school. Of course, it is impossible to answer that question given the fact that we have data from only two schools. The only question that could be answered with the dataset provided is if alcohol consumption is \"somehow related\" to school performance for the students of that school and for that particular year, and it turned out that it does not.\n\nA serious study would require a large sample of randomly selected students and schools.\n\nThe causal implication of alcohol consumption to school performance can only be proved by means of running a controlled experiment. Unfortunately, that cannot be done in practice, sice we can not ask students to consume large amounts of alcohol during an accademic year.\n\nA final note about \"research ethics\" is worth mentioning. It is highly surprising that the authors of the study have disclosed the real names of the schools from which the data was gathered. Morevoer, if we take into account that the dataset is, by no means, statistically significant. That could lead to all sorts of mistakes and misunderstandings that should have been avoided. \n\"\"\"\n\"\"\"\n### Future work\n\"\"\"\n\"\"\"\nSince we have a second dataset, the \"language\" dataset, it would be very nice to check if the grades of both datasets are correlated, and if not, if the conclusions are different. A difficult problem is how to relate the students from both datasets, what it is called \"identity matching\" problem. Fortunately, the authors of the dataset have provided a solution to this problem (in the form of an R script).\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '580924c402c143'}"}
{"id":"106326","text":"\"\"\"\n# Load data\n\"\"\"\nimport matplotlib.image as mpimg\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\n# advanced ploting\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore', category=FutureWarning)\n\n# Image manipulations\nfrom PIL import Image\n\n# Timing utility\nfrom timeit import default_timer as timer\n\nfrom IPython.core.interactiveshell import InteractiveShell\n\n# Printing out all outputs\nInteractiveShell.ast_node_interactivity = 'all'\nimport torchvision\nfrom torchvision import transforms, datasets, models\n\nimport torch\nimport matplotlib.pyplot as plt\nimport os\nfrom torch import optim, cuda\nfrom torch.utils.data import DataLoader, sampler\nfrom torch.autograd import Variable\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv2d, MaxPool2d\nfrom torch.nn import Module, Softmax, BatchNorm2d, Dropout\n\nimport gc\nos.listdir('..\/input\/ptbdb-ecg\/PTB\/train')\nECG_list = os.listdir('..\/input\/ptbdb-ecg\/PTB\/train')\n\nn_classes = len(ECG_list)\n\nprint(f'There are {n_classes} different classes.')\nECG_list\nN_imgs = os.listdir('..\/input\/ptbdb-ecg\/PTB\/train\/N')\nprint('# of Normal beats: ',len(N_imgs))\nM_imgs = os.listdir('..\/input\/ptbdb-ecg\/PTB\/train\/M')\nprint('number of mycardial infarction beats: ',len(M_imgs))\ndef imshow(image):\n    \"\"\"Display image\"\"\"\n    plt.figure(figsize=(6, 6))\n    plt.imshow(image)\n    plt.axis('off')\n    plt.show()\nimport matplotlib.image as mpimg\nimage = mpimg.imread(os.path.join('..\/input\/ptbdb-ecg\/PTB\/train\/M', M_imgs[0]))\n\nimshow(image)\n\n\nprint(image.shape)\nprint(type(image))\n\n\n# Define a function which will plot several images\n\ndef image_shows(folder, number_of_images):\n    \n    n=number_of_images;\n    \n    folder_list = os.listdir(folder)\n    \n    fig, axes = plt.subplots(nrows = 1, ncols=n, figsize=(20, 10))\n    \n    for i in range(n):\n        \n        print(os.path.join(folder, folder_list[i]))\n        \n        image = mpimg.imread(os.path.join(folder, folder_list[i]));\n        \n        axes[i].imshow(image);\n# Examples of N\nimage_shows(folder = '..\/input\/ptbdb-ecg\/PTB\/train\/N', number_of_images = 6)\nimport shutil\nfrom os import walk\nlen(os.listdir('..\/input\/ptbdb-ecg\/PTB\/train\/M')), len(os.listdir('..\/input\/ptbdb-ecg\/PTB\/test\/M'))\n\nlen(os.listdir('..\/input\/ptbdb-ecg\/PTB\/train\/N')), len(os.listdir('..\/input\/ptbdb-ecg\/PTB\/test\/N'))\n# no. of files\n\ndef list_files(startpath):\n    \n    for root, dirs, files in os.walk(startpath):\n        \n        level = root.replace(startpath, '').count(os.sep)\n        \n        indent = ' ' * 4 * (level)\n        \n        print('{}{}'.format(indent, os.path.basename(root)), '-', len(os.listdir(root)))\n        \nfolder = '..\/input\/ptbdb-ecg\/PTB\/'\nlist_files(folder)\ndef imshow(image):\n    \"\"\"Display image\"\"\"\n    plt.figure(figsize=(6, 6))\n    plt.imshow(image)\n    plt.axis('off')\n    plt.show()\nimage = mpimg.imread(os.path.join('..\/input\/ptbdb-ecg\/PTB\/train\/M', M_imgs[0]))\n\nimshow(image)\nprint(image.shape)\nprint(type(image))\n# Define default PATH\n\nTRAIN_PATH        = '..\/input\/ptbdb-ecg\/PTB\/train'\n\ntransform         = transforms.Compose(\n                                       [transforms.Resize([64,64]),\n                                        transforms.Grayscale(num_output_channels=3), \n                                        transforms.ToTensor(),\n                                        transforms.Normalize((0.5), (0.5))\n                                       ])\n  \ntrain_data_set    = datasets.ImageFolder(root=TRAIN_PATH, transform=transform)\n\nbatch_size=32\n\ntrain_data_loader = DataLoader(train_data_set, batch_size=batch_size, shuffle=True)\nTEST_PATH        = '..\/input\/ptbdb-ecg\/PTB\/test'\n  \ntest_data_set    = datasets.ImageFolder(root=TEST_PATH, transform=transform)\n\ntest_data_loader = DataLoader(test_data_set, batch_size=batch_size, shuffle=True)\n# Run this to test your data loader\n\nimages, labels = next(iter(train_data_loader))\nprint(type(images))\n\nprint(images.size())\n\nprint(\"\")\nprint(\"Batch Size:   \",images.size()[0])\nprint(\"Channel Size: \",images.size()[1])\nprint(\"Image Height: \",images.size()[2])\nprint(\"Image Width:  \",images.size()[3])\ndevice=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\" )\ndevice\nimport torchvision\nmodel = models.wide_resnet50_2()\nn_fltrs=model.fc.in_features\nmodel.fc=nn.Linear(n_fltrs,2)\nmodel.to(device)\n# Define Criterion\n\ncriterion = nn.CrossEntropyLoss()\n\n# Define Optimizer\n\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n# Whether to train on a gpu and Number of gpus\n\nif cuda.is_available(): \n    \n    print(f'{cuda.device_count()} number of gpus are detected and available.')\n    \nelse:\n        \n    print(f'Train on gpu is not available')\n%%time\n\n\n# This part is working\n\nif torch.cuda.is_available():\n    \n    MODEL = model.cuda()\n    CRITERION = criterion.cuda()\n    print(\"cuda\")\n    \nelse:\n    \n    MODEL = model\n    CRITERION = criterion\n    print(\"cpu\")\n\n# Train the model\n\ntotal_step = len(train_data_loader)\nloss_list = []\nacc_list = []\n\nnum_epochs = 5\n\nclass_list = ['N', 'M']\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nall_con_mat = torch.zeros([num_epochs, 2, 2], dtype=torch.int32, device=device)\n\nfor epoch in range(num_epochs):\n    \n    f1_score_list=[0,0]\n\n    precision_list=[0,0]\n\n    recall_list=[0,0]\n    \n    delta = 0.0000000000001 \n    \n    # define empty tensor 5*5 beginning of every epoch\n    # tensor [row,column]\n    con_mat = torch.zeros([2, 2], dtype=torch.int32, device=device)\n    \n    for i, data in enumerate(train_data_loader):\n        \n        inputs, labels = data\n        inputs, labels = inputs.to(device), labels.to(device)\n        \n        # optimization\n        optimizer.zero_grad()\n        \n        # Forward to get output\n        outputs = MODEL(inputs)\n        # Calculate Loss\n        loss = CRITERION(outputs, labels)\n        # Backward propagation\n        loss.backward()\n        # Updating parameters\n        optimizer.step()\n        \n        # Store loss\n        loss_list.append(loss.item())\n    \n        # Calculate labels size\n        total = labels.size(0)\n        \n        # Outputs.data has dimension batch size * 5\n        # torch.max returns the max value of elements(_) and their indices(predicted) in the tensor array\n        _, predicted = torch.max(outputs.data, 1)\n        \n        # Calculate total number of correct labels \n        correct = (predicted == labels).sum().item()\n        \n        # Store accuracy\n        acc_list.append(correct \/ total)\n        \n        for element in range(total):\n            \n            # con_mat[row,column]\n            # con_mat[predictions, actual]\n            con_mat[predicted[element].item()-1][labels[element].item()-1] += 1\n\n        if (i + 1) % 70 == 0:                             # every 300 mini-batches...\n            \n            print('Epoch [{}\/{}], Step [{}\/{}], Loss: {:.4f}, Accuracy: {:.4f}%'\n                  \n                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item(),\n                          (correct \/ total) * 100))\n    print(con_mat)\n            \n    all_con_mat[epoch] = con_mat\n    \n    # Print Confusion Matrix\n    \n    for i in range(torch.sum(con_mat, dim=0).size(0)): \n    \n        recall_list[i] = con_mat[i][i].item()\/(torch.sum(con_mat, dim=0)[i].item()+delta)\n    \n        precision_list[i] = con_mat[i][i].item()\/(torch.sum(con_mat, dim=1)[i].item()+delta)\n    \n        f1_score_list[i] = 2 * precision_list[i]*recall_list[i]\/(precision_list[i]+recall_list[i]+delta)\n        \n    \n        print('class name: {}, total number of class: {:>5}, Correctly predicted: {:>5}, Recall: {:.2f}%, Precision: {:.4f}%, F1-Score: {:.4f}%'\n          \n                  .format(class_list[i],\n                          torch.sum(con_mat, dim=0)[i].item(),\n                          con_mat[i][i].item(), \n                          recall_list[i],\n                          precision_list[i],\n                          f1_score_list[i]\n                         ))\n    \n            \nprint('Finished Training')\n\nplt.plot(loss_list);\nplt.show();\n\nplt.plot(acc_list);\nplt.show();\nimport pandas as pd\ndf4 = pd.DataFrame(loss_list)\ndf4.to_csv(\"train_4.csv\", index=False)\nimport pandas as pd\ndf2 = pd.DataFrame(acc_list)\ndf2.to_csv(\"train_acc.csv\", index=False)\nwith plt.style.context(\"seaborn-poster\"):\n    fig, ax = plt.subplots(figsize=(12, 5));\n    plt.plot(df2,color='red',  marker='o',markerfacecolor='r', label=\"Training Acc\");\n    #plt.plot(df4,  marker='*', label=\"Validation Acc\")\n    #plt.xticks(np.arange(0, 201, 20),fontweight='bold')\n    plt.yticks(fontweight='bold');\n    plt.ylabel('Accuracy', fontsize=18, fontweight='bold');\n    plt.xlabel('epochs', fontsize=18, fontweight='bold')\n    plt.title(\"Accuracy history using CNN+LSTM\", fontweight='bold');\n    plt.legend();\n    #plt.savefig(f\"loss_history.svg\",format=\"svg\",bbox_inches='tight', pad_inches=0.2)\n    #plt.savefig(f\"loss_history.png\", format=\"png\",bbox_inches='tight', pad_inches=0.2) \n    plt.show()\n\n\n\"\"\"with plt.style.context(\"seaborn-poster\"):\n    plt.plot(df4, color='red', linewidth=5, marker='o',\n    markerfacecolor='k', markersize=12)\n    plt.show()\"\"\";\nwith plt.style.context(\"seaborn-poster\"):\n    fig, ax = plt.subplots(figsize=(12, 5))\n    plt.plot(df4,  color='red', marker='o',  label=\"Training Loss\")\n    #plt.plot(df4[\"val_loss\"],  marker='o', label=\"Validation Loss\")\n    #plt.xticks(np.arange(0, 201, 20),fontweight='bold')\n    #plt.yticks(fontweight='bold')\n    plt.ylabel('loss', fontsize=18, fontweight='bold')\n    plt.xlabel('epochs', fontsize=18, fontweight='bold')\n    plt.title(\"Loss history using SMOTE+Tomek+CNN+LSTM\", fontweight='bold')\n    plt.legend()\n    #plt.savefig(f\"loss_history.svg\",format=\"svg\",bbox_inches='tight', pad_inches=0.2)\n    #plt.savefig(f\"loss_history.png\", format=\"png\",bbox_inches='tight', pad_inches=0.2) \n    plt.show()\n%%time\n\n\nconfusion_mat = torch.zeros([2, 2], dtype=torch.int32, device=device)\n\nwith torch.no_grad():\n    \n    for data in test_data_loader:\n        \n        inputs, labels = data\n        inputs, labels = inputs.to(device), labels.to(device)\n        \n        outputs = MODEL(inputs)\n        \n        _, predicted = torch.max(outputs.data, 1)\n        \n        total = labels.size(0)\n        \n        # Calculate total number of correct labels \n        correct = (predicted == labels).sum().item()\n        \n        for element in range(total):\n            \n            # confusion_mat[row,column]\n            # confusion_mat[predictions, actual]\n            confusion_mat[predicted[element].item()-1][labels[element].item()-1] += 1\n\n    print(confusion_mat)\nclass_list = ['N', 'M']\n\nf1_score_list=[0,0]\n\nprecision_list=[0,0]\n\nrecall_list=[0,0]\n    \ndelta = 0.0000000000001 \n\n\nfor i in range(torch.sum(confusion_mat, dim=0).size(0)): \n    \n        recall_list[i] = confusion_mat[i][i].item()\/(torch.sum(confusion_mat, dim=0)[i].item()+delta)\n    \n        precision_list[i] = confusion_mat[i][i].item()\/(torch.sum(confusion_mat, dim=1)[i].item()+delta)\n    \n        f1_score_list[i] = 2 * precision_list[i]*recall_list[i]\/(precision_list[i]+recall_list[i]+delta)\n        \n    \n        print('class name: {}, total number of class: {:>5}, Correctly predicted: {:>5}, Recall: {:.4f}%, Precision: {:.4f}%, F1-Score: {:.4f}%'\n          \n                  .format(class_list[i],\n                          torch.sum(confusion_mat, dim=0)[i].item(),\n                          confusion_mat[i][i].item(), \n                          recall_list[i],\n                          precision_list[i],\n                          f1_score_list[i]\n                         ))\n\"\"\"\n# Train CNN with LSTM\n\"\"\"\n!pip install git+https:\/\/github.com\/qubvel\/segmentation_models.pytorch\n\nimport segmentation_models_pytorch as smp\nfrom segmentation_models_pytorch.encoders import get_preprocessing_fn\npreprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')\nfrom segmentation_models_pytorch.unet import Unet\nmodel = Unet(encoder_name=\"efficientnet-b0\", classes=2, aux_params={\"classes\": 2})\noptimizer = optim.Adam(model.parameters())\ncriterion = nn.BCELoss()","meta":"{'source': 'AI4Code', 'id': 'c3532d302a33c9'}"}
{"id":"84761","text":"import cv2\nimport matplotlib.pyplot as plt\n\"\"\"\n### To read the image:\n\"\"\"\nimage = cv2.imread('..\/input\/horseimage\/horse.jpeg')\nplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\nplt.axis('off')\nplt.show()\n\"\"\"\n### Creating a new image by converting the original image to grayscale\n\"\"\"\ngray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nplt.imshow(cv2.cvtColor(gray_img, cv2.COLOR_BGR2RGB))\nplt.axis('off')\nplt.show()\n\"\"\"\n### Inverting the new grayscale image\n\"\"\"\ninv_img = 255 - gray_img\nplt.imshow(cv2.cvtColor(inv_img, cv2.COLOR_BGR2RGB))\nplt.axis('off')\nplt.show()\n\"\"\"\n### blurring the image by using the Gaussian Function in OpenCV\n\"\"\"\nblurred = cv2.GaussianBlur(inv_img, (21,21), 0)\n\"\"\"\n### The final step is to invert the blurred image, then we can easily convert the image into a pencil sketch\n\"\"\"\ninv_blur = 255 - blurred\npencil_sketch = cv2.divide(gray_img, inv_blur, scale=256.0)\nplt.imshow(cv2.cvtColor(pencil_sketch, cv2.COLOR_BGR2RGB))\nplt.axis('off')\nplt.show()\n\"\"\"\n**Our pencil sketch is ready!\nThis can be replicated for any image**\n\n\"\"\"\n\"\"\"\n***Thank You!***\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9b793c1e138583'}"}
{"id":"59684","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n**Impact of Map Pick on Game Win**\n\nIn CS:GO, there is generally a map selection process between the two teams playing a match to determine what map(s) will be played. This usually involves a process of both picking maps to play, and banning away maps such that the other team cannot then pick them. \n\nA core belief is that a team should have a higher chance than the opponent to win their map pick. \n\nI wanted to quantify how often teams win their own pick. \n\n\nI started with a data set from kaggle.com with CS:GO professional matches scraped from HLTV.org spanning 11\/2015 - 3\/2020. This data was read into pandas, a data analysis library for Python.\n\nThe data can be found here: https:\/\/www.kaggle.com\/mateusdmachado\/csgo-professional-matches\n\"\"\"\nd_picks = pd.read_csv(\"\/kaggle\/input\/csgo-professional-matches\/picks.csv\")\nd_economy = pd.read_csv(\"\/kaggle\/input\/csgo-professional-matches\/economy.csv\")\nd_results = pd.read_csv(\"\/kaggle\/input\/csgo-professional-matches\/results.csv\")\nd_players = pd.read_csv(\"\/kaggle\/input\/csgo-professional-matches\/players.csv\")\n\"\"\"\n**Filtering the Data**\n\nThis dataset is quite broad as it includes all HLTV matches from the end of 2015 to March 2020. For a more applicable snapshot, I filtered the data to include only the following:\n\n* **Only include the first two games within a best of 3 Series.**\n\nMatches are most often played as best of 1's, or best of 3's. For this analysis, I will only focus on best of 3's, as most analysts generally look at pick\/ban in terms of a best of 3 series. Additionally, there is generally no \"pick\" in a best of 1 as the common methodology is for both teams to ban 3 maps until there is a surviving map to play.\n\n* **Only include games between two teams within the top 20 (at the time the game was played).**\n\nThe scene is generally focused around the top twenty, and the pick\/ban phase is considered quite important at this level. Imposing this filter also removes wins that top teams gain by farming weaker teams not near their skill level. \n\n* **Remove teams which did not pick more than 20 games**\n\nThis filter gives some strength to the analysis such that teams with only a few map picks do not generate outlier win\/loss percentages.  \n\n* **Only Include games after 12\/31\/2016**\n\nI added this filter as I wanted to create a time-span of data of about 2 years. I felt this time span was large enough to gain a good snapshot, but still small enough that it hopefully curbs part of the issue generating from player changes within a team (see disclaimer at the bottom).\n\"\"\"\n\"\"\"\n**Python Code**\n\nThe below python code cleans up the data and generates a final table that with three columns:\n\n* Team Name\n* Win Percentage on Picked Maps\n* Number of Games Played\n\"\"\"\nd_picks.rename(columns={\"team_1\":\"team_1_pick\",\"team_2\":\"team_2_pick\" }, inplace=True)\n\nnew_df = pd.merge(d_results, d_picks, left_on=\"match_id\", right_on=\"match_id\")\n\n#filter for best of 3's\nnew_df = new_df[new_df[\"best_of\"] == \"3\"]\n\n#add new column for winning team name\nnew_df[\"winning_team_name\"] = \"\"\nnew_df.loc[new_df[\"map_winner\"]==1, \"winning_team_name\"] = new_df[\"team_1\"]\nnew_df.loc[new_df[\"map_winner\"]==2, \"winning_team_name\"] = new_df[\"team_2\"]\n\n#create column for name of team who picked the map\nnew_df[\"map_picker\"] = \"\"\nnew_df.loc[new_df[\"_map\"] == new_df[\"t1_picked_1\"], \"map_picker\"] = new_df[\"team_1_pick\"]\nnew_df.loc[new_df[\"_map\"] == new_df[\"t2_picked_1\"], \"map_picker\"] = new_df[\"team_2_pick\"]\nnew_df.loc[new_df[\"_map\"] == new_df[\"left_over\"], \"map_picker\"] = \"left_over\"\n\n#remove decider games\nnew_df = new_df[new_df[\"map_picker\"] != \"left_over\"]\n\n#create column for pick win\nnew_df[\"pick_win\"] = new_df[\"winning_team_name\"] == new_df[\"map_picker\"]\n\n#create column for rank of winning team\nnew_df[\"winning_rank\"] = 0\nnew_df.loc[new_df[\"map_winner\"]==1, \"winning_rank\"] = new_df[\"rank_1\"]\nnew_df.loc[new_df[\"map_winner\"]==2, \"winning_rank\"] = new_df[\"rank_2\"]\n\n#create column for rank of losing team\nnew_df[\"losing_rank\"] = 0\nnew_df.loc[new_df[\"map_winner\"]==1, \"losing_rank\"] = new_df[\"rank_2\"]\nnew_df.loc[new_df[\"map_winner\"]==2, \"losing_rank\"] = new_df[\"rank_1\"]\n\n#filter for only teams in the top twenty\nnew_df = new_df[new_df['winning_rank']< 21]\nnew_df = new_df[new_df['losing_rank']< 21]\n\n#filter for after a certain date\nnew_df['date_x'] = pd.to_datetime(new_df['date_x'])\nnew_df = new_df[new_df['date_x'] > \"12-31-2016\"]\n\n#groupby team\ngrouper = new_df.groupby(\"map_picker\")[\"pick_win\"].value_counts(normalize=True)\ngrouper = grouper[grouper.index.isin([True], level=1)]\n\n#Remove redundant index and sort\ngrouper = grouper.reset_index(level=1, drop=True)\ngrouper = grouper.sort_values(ascending = False)\ngrouper = grouper.to_frame()\ngrouper = grouper.reset_index()\n\n#Add column based on number of games\nfilter_series = new_df[\"map_picker\"].value_counts()\nfilter_series = filter_series.to_frame()\nfilter_series = filter_series.reset_index()\ngrouper = pd.merge(grouper, filter_series, left_on=\"map_picker\", right_on=\"index\")\ngrouper = grouper.drop(\"index\", 1)\ngrouper.rename(columns={\"map_picker_x\":\"Team\",\"pick_win\": \"Win Percentage\", \"map_picker_y\":\"Number of Games\" }, inplace=True)\ngrouper = grouper[grouper[\"Number of Games\"] > 20]\nprint(grouper)\n\"\"\"\n**Analysis**\n\nThe generated information was quite interesting to me for a number of reasons:\n\n* **Astralis** - It provides just more evidence that Astralis is the best core of all time. Even other strong teams above (FaZe, Liquid, Evil Geniuses) are over 10% below that of Astralis. I imagine this percentage is boosted heavily by their Nuke streak, as well as generally being unbeatible (on any map) in 2018. \n\n* **Ence** - Ence being second feeds into the general narrative that Ence was a good team because of tactics and guile, using aspects such as map pick\/ban to gain wins over better teams. It impresses me they were able to have the second highest win percentage on their own pick, while still being so far below the other elite teams in terms of skill. It is also a further indictment of their choice to kick Aleksib. I don't think they could ever have reached this percentage without them. \n\n* **Space Soldiers** - It is interesting that they are so high on the list. I imagine this is a function of farming low top 20 teams online, but I would have to look more into the data to determine the exact cause. \n\n* **General** - It appears to me that while your map pick can generate an increased chance to win a game, you still have to be a quality team in order to execute. Your map pick is by no means a free win, even if you are a tactical team. For example, BIG is second to last, and they are known to follow a strong gameplan. Additionally, neither North nor Optic, which were at times led by MSL with a fairly rigid system, have strong winrates (Optic is even last).  \n\n**Disclaimer**\n\nThe data used for this project is not perfect as it includes online matches and does not account for player changes within a team. However, I thought this was a fun exercise in data science and a bit illuminating as to the impact of pick\/ban. Please let me know if you see any issues with the data.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6e21eed5ad569d'}"}
{"id":"128567","text":"\"\"\"\n# Breast Cancer Prediction Model\n\"\"\"\n\"\"\"\n## Importing primary Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\nimport plotly.express as px\nimport pandas_profiling as pp\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ndf = pd.read_csv(\"\/kaggle\/input\/breast-cancer-wisconsin-data\/data.csv\")\ndf\ndf.info()\nround(df.isna().sum() * 100 \/ len(df) , 2).sort_values(ascending = False)\ndf.drop([\"Unnamed: 32\" , \"id\"] , axis = 1 , inplace = True)\n\"\"\"\n## Basic Preprocessing and EDA\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\nlb = LabelEncoder()\ndf[\"diagnosis\"] = lb.fit_transform(df[\"diagnosis\"])\nplt.figure(figsize = (15 , 6))\ndf.dtypes.value_counts().plot.pie(explode=[0.3,0.3] , autopct='%1.2f%%' , shadow=True)\nsns.countplot(data = df , x = \"diagnosis\" )\nplt.figure(figsize = (20 , 10))\nsns.heatmap(df.corr() , annot = True , cmap = \"coolwarm\")\n\"\"\"\n### Dropping Highly correlated columns \/ Features \n\"\"\"\ndf.drop([\"perimeter_mean\" , \"perimeter_worst\"] , axis = 1 , inplace = True)\ndf.hist(edgecolor = \"black\" , figsize = (15 , 15));\n\"\"\"\n## Outliers Treatment\n1. Skewness in the range of [-3 , 3]\n2. Kurtosis in the range of [-1 , 10]\n\"\"\"\nfor i in range(len(df.skew())):\n    if df.skew()[i] > 3 or df.skew()[i] < -3:\n        print(f\"{df.skew().index[i]} with skewness of {df.skew()[i] : >{20}}\")\n        print(\"\\n\")\n        plt.figure(figsize = (15 , 6))\n        sns.histplot(data = df , x = df.columns[i] , hue = \"diagnosis\" , kde = True)\n        plt.show()\n        print(\"\\n\\n\")\nfor i in range(len(df.kurtosis())):\n    if df.kurtosis()[i] > 10 or df.kurtosis()[i] < -10:\n        print(f\"{df.kurtosis().index[i]} with kurtosis of {df.kurtosis()[i] : >{20}}\")\n        print(\"\\n\")\n        plt.figure(figsize = (15 , 6))\n        sns.histplot(data = df , x = df.columns[i] , hue = \"diagnosis\" , kde = True)\n        plt.show()\n        print(\"\\n\\n\")\n\"\"\"\nThere are outliers in the above columns\n\"\"\"\ndf_temp = df.copy()\n\"\"\"\n### Treating Outliers\n\"\"\"\ndf[\"diagnosis\"].value_counts()\n# Percentile Cutoff method\n\nouts = [\"radius_se\" , \"perimeter_se\" , \"area_se\" , \"smoothness_se\" , \"concavity_se\" , \"fractal_dimension_se\"]\n\nfor i in outs:\n    df[i].loc[df[i] < np.percentile(df[i] , [1])[0] * 0.3] = np.percentile(df[i] , [1])[0]\n    df[i].loc[df[i] > np.percentile(df[i] , [99])[0] * 3] = np.percentile(df[i] , [99])[0]\n# Exponential Smothening\n\nfor i in outs:\n    df[i] = np.log(df[i] + 1)\n\"\"\"\n### Rechecking for outliers after the Treatment\n\"\"\"\nfor i in range(len(df.skew())):\n    if df.skew()[i] > 3 or df.skew()[i] < -3:\n        print(f\"{df.skew().index[i]} with skewness of {df.skew()[i] : >{20}}\")\n        print(\"\\n\")\n        plt.figure(figsize = (15 , 6))\n        sns.histplot(data = df , x = df.columns[i] , hue = \"diagnosis\" , kde = True)\n        plt.show()\n        print(\"\\n\\n\")\nfor i in range(len(df.kurtosis())):\n    if df.kurtosis()[i] > 10 or df.kurtosis()[i] < -10:\n        print(f\"{df.kurtosis().index[i]} with kurtosis of {df.kurtosis()[i] : >{20}}\")\n        print(\"\\n\")\n        plt.figure(figsize = (15 , 6))\n        sns.histplot(data = df , x = df.columns[i] , hue = \"diagnosis\" , kde = True)\n        plt.show()\n        print(\"\\n\\n\")\n\"\"\"\nWe Removed most of the outliers\n\"\"\"\n\"\"\"\n### Checking for multicollinearity\n\"\"\"\nfrom sklearn.feature_selection import mutual_info_classif as mif\n\nmif_values = mif(df.drop([\"diagnosis\"] , axis = 1) , df[\"diagnosis\"])\n\npd.DataFrame(mif_values , index = df.drop([\"diagnosis\"] , axis = 1).columns).sort_values(by = 0 , ascending = False)\n\"\"\"\nTherefore , no issues of multicollinearity\n\"\"\"\n\"\"\"\n## Train Test Split\n\"\"\"\nX = df.drop([\"diagnosis\"] , axis = 1)\ny = df[\"diagnosis\"]\ny.value_counts()\nfrom sklearn.model_selection import train_test_split\n\nX_train , X_test , y_train , y_test = train_test_split(X , y , test_size = 0.2 , random_state = 42)\nlen(X_train) , len(X_test) , len(y_train) , len(y_test)\n\"\"\"\n## Feature Scaling\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\nints = X.columns\n\nX_train[ints] = scaler.fit_transform(X_train[ints])\nX_test[ints] = scaler.transform(X_test[ints])\n\"\"\"\n## Model Fitting\n\"\"\"\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom lightgbm import LGBMClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom sklearn.metrics import confusion_matrix , roc_auc_score , f1_score , accuracy_score , classification_report , roc_curve , auc , plot_roc_curve\nfrom sklearn.model_selection import cross_val_score\nmodels = []\nmodels.append((\"XGBClassifier\", XGBClassifier(objective = 'binary:logistic' , random_state = 42 , eval_metric='mlogloss')))\nmodels.append((\"CatBoostClassifier\", CatBoostClassifier(random_state = 42 , verbose = 0)))\nmodels.append((\"RandomForest\", RandomForestClassifier(random_state = 42 , n_estimators = 200)))\nmodels.append((\"ExtraTreeRegressor\", ExtraTreesClassifier(random_state = 42 , n_estimators = 200)))\nmodels.append((\"Gradient Boosting Classifier\" , GradientBoostingClassifier(random_state = 42)))\nmodels.append((\"LightGBM\" , LGBMClassifier(random_state = 42 , n_estimators = 200)))\nmodels.append((\"Logistic Regression\", LogisticRegression(random_state = 42)))\nmodels.append((\"KNeigbors\", KNeighborsClassifier()))\ndef metrics(model , X_train , y_train , X_test , y_test , params = False):\n    \n    mod = model[1].fit(X_train , y_train)\n    preds = model[1].predict(X_test)\n    accuracies = cross_val_score(estimator = model[1], X = X_train , y = y_train, cv = 10)\n    cm = confusion_matrix(y_test , preds)\n    cf = classification_report(y_test , preds)\n    roc = roc_auc_score(y_test , model[1].predict_proba(X_test)[: , 1])\n    fpr, tpr, thresholds = roc_curve(y_test, preds)\n    ac = auc(fpr, tpr)\n    f1 = f1_score(y_test , preds)\n    \n    \n    print(\"\\n\")\n    print(model[0])\n    \n    print(\"\\n\")\n    if params:\n        print(f\"Best Parameters are : \\n\" , model[1].best_params_)\n        print(\"\\n\")\n        \n    print(f\"Confusion matrix : \\n\")\n    plt.figure(figsize = (8, 5))\n    sns.heatmap(cm, cmap = 'coolwarm', annot = True, annot_kws = {'fontsize': 20})\n    plt.show()\n    print(\"\\n\")\n    \n    print(f\"Training score : {model[1].score(X_train , y_train):.4f}\")\n    print(\"\\n\") \n    \n    print(f\"Test Score : {model[1].score(X_test , y_test):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"K-fold accuracy : {np.mean(accuracies):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"Standard Deviation of Accuracies in k-fold : {np.std(accuracies):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"ROC AUC Score: {roc:.4f}\")\n    print('\\n')\n    \n    print(f\"F1 Score: {f1:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"AUC : {ac:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"Classification report : \\n\\n{cf}\")\n    print(\"\\n\")\n\n    plt.figure(figsize = (8, 5))\n    plot_roc_curve(model[1], X_test, y_test , color = '#FF4500')\n    plt.plot([0, 1], [0, 1], linestyle = '--', color = '#7CFC00')\n    plt.show()\n    print(\"\\n\")\n    print(\"*\"*100)\n    \n    print(\"\\n\\n\")\n    \n    sam = []\n    sam.append(model[0])\n    sam.append(model[1].score(X_train , y_train))\n    sam.append(model[1].score(X_test , y_test))\n    sam.append(np.mean(accuracies))\n    sam.append(np.std(accuracies))\n    sam.append(roc)\n    sam.append(f1)\n    sam.append(ac)\n    \n    return sam , mod\n%%time\n\npre_final = []\n\nfor i in models:\n    sam = metrics(i , X_train , y_train , X_test , y_test)\n    pre_final.append(sam)\ndata_pre_final = [x[0] for x in pre_final]\n\"\"\"\n## Model Evaluation and Visualization\n\"\"\"\nme = pd.DataFrame(data_pre_final , columns = [\"Model\" , \"Train Score\" , \"Test Score\" , \"K-fold Accuracy\" , \"K-fold Std\" , \"ROC_AUC_Score\" , \"F1 Score\" , \"AUC\"])\n\nme.sort_values(by = [ \"F1 Score\" , \"AUC\" , \"ROC_AUC_Score\" , \"K-fold Std\" , \"K-fold Accuracy\" , \"Test Score\" , \"Train Score\"] , inplace = True , ascending = [False , False , False , True , False , False , False])\nme = me.reset_index(drop = True)\nme\nplt.figure(figsize = (10 , 6))\nsns.barplot(y = \"Model\" , x = \"F1 Score\" , data = me)\nplt.title(\"Model Comparision based on F1 Score\");\nplt.figure(figsize = (10 , 6))\nsns.barplot(y = \"Model\" , x = \"AUC\" , data = me)\nplt.title(\"Model Comparision based on AUC\");\nplt.figure(figsize = (10 , 6))\nsns.barplot(y = \"Model\" , x = \"ROC_AUC_Score\" , data = me)\nplt.title(\"Model Comparision based on ROC_AUC_Score\");\nplt.figure(figsize = (10 , 6))\nsns.barplot(y = \"Model\" , x = \"K-fold Accuracy\" , data = me)\nplt.title(\"Model Comparision based on K-fold Accuracy\");\n\"\"\"\n## Model Evaluation with Voting Classifier\n\"\"\"\nfrom sklearn.ensemble import VotingClassifier\n\nvoting_models = models\nvoting_soft = VotingClassifier(estimators = voting_models , voting = \"soft\")\nvoting_soft.fit(X_train , y_train)\ndef metrics_others(model , X_train , y_train , X_test , y_test , params = False):\n    \n    preds = model.predict(X_test)\n    cm = confusion_matrix(y_test , preds)\n    cf = classification_report(y_test , preds)\n    roc = roc_auc_score(y_test , model.predict_proba(X_test)[: , 1])\n    fpr, tpr, thresholds = roc_curve(y_test, preds)\n    ac = auc(fpr, tpr)\n    f1 = f1_score(y_test , preds)\n    \n    print(f\"Confusion matrix : \\n\")\n    plt.figure(figsize = (8, 5))\n    sns.heatmap(cm, cmap = 'coolwarm', annot = True, annot_kws = {'fontsize': 20})\n    plt.show()\n    print(\"\\n\")\n    \n    print(f\"Training score : {model.score(X_train , y_train):.4f}\")\n    print(\"\\n\") \n    \n    print(f\"Test Score : {model.score(X_test , y_test):.4f}\")\n    print(\"\\n\")\n    \n    print(f\"ROC AUC Score: {roc:.4f}\")\n    print('\\n')\n    \n    print(f\"F1 Score: {f1:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"AUC : {ac:.4f}\")\n    print(\"\\n\")\n    \n    print(f\"Classification report : \\n\\n{cf}\")\n    print(\"\\n\")\n\n    plt.figure(figsize = (8, 5))\n    plot_roc_curve(model, X_test, y_test , color = '#FF4500')\n    plt.plot([0, 1], [0, 1], linestyle = '--', color = '#7CFC00')\n    plt.show()\n    print(\"\\n\")\n    print(\"*\"*100)\n    \n    print(\"\\n\\n\")\n    \n    sam = []\n    sam.append(model.score(X_train , y_train))\n    sam.append(model.score(X_test , y_test))\n    sam.append(roc)\n    sam.append(f1)\n    sam.append(ac)\n    \n    return sam\nsoft = metrics_others(voting_soft , X_train , y_train , X_test , y_test)\n\"\"\"\n## Model Evaluation with Catboost\n\"\"\"\nfrom catboost import CatBoostClassifier\ncat = CatBoostClassifier(loss_function = \"MultiClass\", \n                         eval_metric = \"TotalF1\",\n                         random_seed = 42 , \n                         classes_count = 2 ,\n                         depth = 10 ,\n                         iterations = 3500 , \n                         learning_rate = 0.1 ,\n                         leaf_estimation_iterations = 1 ,\n                         l2_leaf_reg = 1 ,\n                         bootstrap_type = \"Bayesian\" , \n                         bagging_temperature = 1 , \n                         random_strength = 1 ,\n                         od_type = \"Iter\", \n                         border_count = 100 ,\n                         od_wait = 50)\n%%time\n\ncat.fit(X_train , y_train , use_best_model = True , eval_set=[(X_test , y_test)] , verbose = True)\ncat_preds = cat.predict(X_test)\nf1_score(y_test , cat_preds)\nfinal_cat = metrics_others(cat , X_train , y_train , X_test , y_test)\n\"\"\"\n## Final model can be Logistic Regression \/ CatBoost Classifier\n\"\"\"\n\"\"\"\n### CatBoost\n\"\"\"\nf1_score(y_test , cat.predict(X_test))\nroc_auc_score(y_test , cat.predict_proba(X_test)[: , 1])\n\"\"\"\n### Linear Model\n\"\"\"\nlinear = pre_final[5][1]\nf1_score(y_test , linear.predict(X_test))\nroc_auc_score(y_test , linear.predict_proba(X_test)[: , 1])\n\"\"\"\n## Since CatBoost Has More F1_Score , ROC_AUC_Score . We use Catboost\n\"\"\"\nf1_score(y_test , cat.predict(X_test))\n\"\"\"\n# Don't forget to upvote if you like the notebook . Thank You .  \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ec7bb6d0dc9739'}"}
{"id":"44431","text":"\"\"\"\n# Recurrent Neural Network\n\n## References\n\n1. [Udacity's Deep Learning Nanodegree](https:\/\/classroom.udacity.com\/nanodegrees\/nd101-ent\/syllabus\/core-curriculum) \n2. [Machine Talk](https:\/\/machinetalk.org\/2019\/02\/08\/text-generation-with-pytorch\/)\n3. [KD Nuggets tutorial on text generation via LSTM](https:\/\/www.kdnuggets.com\/2020\/07\/pytorch-lstm-text-generation-tutorial.html)\n4. [Pytorch official documentation](https:\/\/pytorch.org\/tutorials\/intermediate\/char_rnn_generation_tutorial.html)\n\nSome applications of deep-learning involve temporal-dependencies i.e. dependencies over time i.e. not just on current input but also on past inputs. RNNs are similar to feed-forward networks but in addition to *memory*.<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/RNNs%20-%20Temporal%20Dependencies.png?raw=1\" width=\"250\" height=\"40%\"><\/img>\n\nIn RNNs, the current output *y* depends not only on current input *x*, but also on memory element *s*, that takes into account past inputs. \n\nRNNs also attempt to address the need of capturing information in previous inputs by maintaining internal memory elements called *States.*<br><br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/RNNs-%20States.png?raw=1\" width=\"300\"><\/img>\n\n## Applications of RNNs\n\n1. Some of the applications of RNN requires predicting the next word in the sentence which requires looking at *last few words instead of the current one.*\n\n2. Sentiment Analysis\n3. Speech Recognition\n4. Time Series Prediction\n5. NLP\n6. Gesture Recognition\n\n## Structure of RNNs\nBelow are the folded and unfolded sructure of RNNs - <br>\n\n| Folded RNN                                                    | Un-folded RNN                                               |\n|---------------------------------------------------------------|-------------------------------------------------------------|\n| <img  src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/RNN-%20Folded%20Model.png?raw=1\" width=\"300\"><\/img> | <img  src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/RNNs%20-%20Unfolded.png?raw=1\" width=\"300\"><\/img> |\n\n\n\"\"\"\n\"\"\"\n# Back Propogation Through Time (BPTT)\n\nLets look at the timestep t=3, the error associated w.r.t Wx depends on : vector S3 and its predecessor S2 and S1.<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/BPTT.png?raw=1\" width=\"600\"><\/img><br>\n\nLooking at the pattern above while calculating the *accumulative gradient*, we can generalize the formula for Back Propogation Through Time (BPTT)as follows - <br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/General%20formula%20for%20BPTT.png?raw=1\" width=\"300\"><\/img><br>\n\n\n\"\"\"\n\"\"\"\n# Drawbacks of RNNs\n\n## Vanishing Gradient Problem\n\nIn RNNs, if we continue to back-propogate further after 8-9 time steps, the contributions of information (graident) keeps on decreading geometrically over time which is known as the *vanishing gradient problem.* Here is where the **LSTM** comes into picture.<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/LSTM%20Intro.png?raw=1\" width=\"600\"><\/img>\n\n## Exploding Gradient Problem\n\nIn RNNs we can also have the opposite problem, called the *exploding gradient* problem, in which the value of the gradient grows uncontrollably. A simple solution for the exploding gradient problem is **Gradient Clipping.**\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/Gradient%20Clipping.png?raw=1\" width=\"500\"><\/img>\n\n\"\"\"\n\"\"\"\n# Long Short Term Memory Cells (LSTM Cells)\n\n## Basics of LSTM\n\nBasic RNN was unable to retain long term memory to make prediction regarding the current picture is that od a wolf or dog. This is where LSTM comes into picture. The LSTM cell allows a recurrent system to learn over many time steps without the fear of losing information due to the vanishing gradient problem. It is fully differentiable, therefore gives us the option of easily using backpropagation when updating the weights. Below is the a sample mathematical model of an LSTM cell - <br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/01.lstm_cell.png?raw=1\" width=\"300\"><\/img><br>\n\n\nIn an LSTM, we would expect the following behaviour -\n\n\n| Expected Behaviour of LSTM                                                                   | Reference Diagram                                                       |\n|----------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|\n| 1. Long Term Memory (LTM) and Short Term Memory (STM) to combine and produce correct output. | <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/05.%20lstm_basics_1.png?raw=1\" width=\"300\"> |\n| 2. LTM and STM and event should update the new LTM.                                          | <\/img>  <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/06.%20lstm_basics_2.png?raw=1\" width=\"300\"><\/img>  |\n| 3. LTM and STM and event should update the new STM.                                          | <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/07.%20lstm_basics_3.png?raw=1\" width=\"300\"><\/img>          |\n\n\n\n## How LSTMs work?\n\n| LSTM consists of 4 types of gates -  <br>1. Forget Gate<br>  2. Learn Gate<br> 3. Remember Gate<br> 4. Use Gate<br> | <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/10.%20lstm_architecture_02.png?raw=1\" width=\"530px\" height=\"250px\"><\/img> |\n|-------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|\n\n### LSTM Explained\nAssume the following - \n1. LTM = Elephant\n2. STM = Fish\n3. Event = Wolf\/Dog\n\n| LSTM Operations                                                                                                                                                                                            | Reference Video                                      |\n|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------|\n| **LSTM places LTM, STM and Event as follows -**<br> 1. Forget Gate = LTM<br>  2. Learn Gate = STM + Event<br> 3. Remember Gate = LTM + STM + Event<br> 4. Use Gate = LTM + STM + Event<br> 5. In the end, LTM and STM are updated.<br> | <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/Animated%20GIF-downsized_large.gif?raw=1\"><\/img> |\n\n\n## General Architecture of LSTM \n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/LSTM%20Architecture.png?raw=1\" width=\"400\"><img>\n\n\n\n\n## Learn Gate\nLearn gate takes into account **short-term memory and event** and then ignores a part of it and retains only a part of information.<br>\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/11.%20learn_gate.png?raw=1\" height=\"200px\" width=\"500px\"><\/img>\n\n### Mathematically Explained\nSTM and Event are combined together through **activation function** (tanh), which we further multiply it by a **ignore factor** as follows -<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/12.lean_gate_equation.png?raw=1\" height=\"200px\" width=\"500px\"><\/img>\n\n## Forget Gate\nForget gate takes into account the LTM and decides which part of it to keep and which part of LTM is useless and forgets it. LTM gets multiplied by a **forget factor** inroder to forget useless parts of LTM. <br>\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/13.%20forget_gate.png?raw=1\" height=\"200px\" width=\"500px\"><\/img>\n\n## Remember Gate\nRemember gate takes LTM coming from Forget gate and STM coming from Learn gate and combines them together. Mathematically, remember gate adds LTM and STM.<br><br>\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/14.%20remember_gate.png?raw=1\" height=\"200px\" width=\"400px\"><\/img> <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/15.%20remember_gate_equation.png?raw=1\" height=\"200px\" width=\"450px\"><\/img>\n\n## Use Gate\nUse gate takes what is useful from LTM and what's useful from STM and generates a new LTM.<br><br>\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/16.%20use_gate.png?raw=1\" height=\"200px\" width=\"400px\"><\/img> <img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/17.%20use_gate_equation.png?raw=1\" height=\"200px\" width=\"450px\"><\/img>\n\n\n\n\n\n\n\"\"\"\n\"\"\"\n# RNNs and LSTM for Text Generation\n\n\n## Drawbacks of one-hot encoding \n\nConsidering an example of an excert from a book containing large collection of dataset and when you use these words as an input to RNN, we can one-hot encode them, but this would mean that we will end up having giant vector with mostly zeros except that one entry as shown below:<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/One%20hot%20encoded%20vectors.png?raw=1\" width=\"500\"><\/img>\n\nThen we pass this one-hot encoded vector into hidden-layer of RNN and the result is a huge matrix of values most of which are zeros because of the initial one-hot encoding and this is really *computaionally inefficient*.<br>\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/Computationally%20in-efficient.png?raw=1\" width=\"500\"><\/img>\n\nThis is where *Embeddings* come into picture.\n\n\n## Word Embeddings\n\nWord embeddings is a general technique of reducing the dimensionality of text data, but the embedding models can also learn some interesting traits about words in a vocabulary.<br>\n\nEmbeddings can improve the ability of neural networks to learn from text data by representing them as *lower dimensional vectors.*\n\nThe idea here is when we multiply one-hot encoded vector with weight-matrix, returns only the row of the matrix that corresponds to the 1 or the on input unit.<br><br>\n\nHence, instead of doing matrix multiplication, we use weight-matrix as a look-up table and instead of representing words as one-hot vectors, we encode each word with a unique integer.\n\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/Embedding%20Lookup.png?raw=1\" width=\"500\"><\/img>\n\n\n\"\"\"\n\"\"\"\n# Look-up Tables\n\nConsidering the example of \"heart\" mentioned above, we see that \"heart\" is encoded as the integer \"958\", we can look-up the embedding vector for this word in the 958th row of the embedding weight matrix. This is called a *look-up table*\n\n## Dimensions of Look-up table\n\nIf we have a vocabulary of 10k words, then we will have a 10k row embedded weight matrix. The width of the table is called *embedding dimensions*.\n\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/embedding_lookup_table.png?raw=1\" width=\"500\"><\/img>\n\n\"\"\"\n\"\"\"\n# Word2Vec Models\n\nWord2Vec model provides much efficient representations by finding vectors that represents words.<br>\n\nThere are 2 architectures for implementing Word2Vec -\n1. CBOW (Continous Bag Of Words)\n2. Skip-gram\n\n\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/word2vec_architectures.png?raw=1\" width=\"500\"><\/img>\n\n\nWe have implemened *Talking Points* using the *Skip-gram* model.\n\"\"\"\n# 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 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\nimport os\n\nimport pandas as pd\ndf = pd.read_csv('\/kaggle\/input\/massive-stock-news-analysis-db-for-nlpbacktests\/raw_partner_headlines.csv')\ndf.head()\nnews = []\nfor i, j in df.iterrows():\n    news.append(j['headline'])\n    \nprint(len(news))\nnews[:1]\nlen(news)\nnews = news[:109233]\nlen(news)\nos.path.join('\/kaggle\/working', 'finance_news.txt')\nf = open('\/kaggle\/working\/finance_news.txt', 'w')\nf.write('\\n'.join(news))\nf.close()\n\"\"\"\n# Pre-processing Stock News \n\nThe following section pre-processes our text file so that -\n1. Any punctuation are converted into tokens, so a period is changed to a bracketed period.\n2. In this data set, there aren't any periods, but it will help in other NLP problems.\n3. It removes all words that show up five or fewer times in the dataset.This will greatly reduce issues due to noise in the data and improve the quality of the vector representations.\n4. It returns a list of words in the text.\n\"\"\"\nimport os\nimport pickle\nimport torch\n\n\nSPECIAL_WORDS = {'PADDING': '<PAD>'}\n\n\ndef load_data(path):\n    \"\"\"\n    Load Dataset from File\n    \"\"\"\n    input_file = os.path.join(path)\n    with open(input_file, \"r\") as f:\n        data = f.read()\n\n    return data\n\n\ndef preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):\n    \"\"\"\n    Preprocess Text Data\n    \"\"\"\n    text = load_data(dataset_path)\n    \n    # Ignore notice, since we don't use it for analysing the data\n    text = text[81:]\n\n    token_dict = token_lookup()\n    for key, token in token_dict.items():\n        text = text.replace(key, ' {} '.format(token))\n\n    text = text.lower()\n    text = text.split()\n\n    vocab_to_int, int_to_vocab = create_lookup_tables(text + list(SPECIAL_WORDS.values()))\n    int_text = [vocab_to_int[word] for word in text]\n    pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb'))\n\n\ndef load_preprocess():\n    \"\"\"\n    Load the Preprocessed Training data and return them in batches of <batch_size> or less\n    \"\"\"\n    return pickle.load(open('preprocess.p', mode='rb'))\n\n\ndef save_model(filename, decoder):\n    save_filename = os.path.splitext(os.path.basename(filename))[0] + '.pt'\n    torch.save(decoder, save_filename)\n\n\ndef load_model(filename):\n    save_filename = os.path.splitext(os.path.basename(filename))[0] + '.pt'\n    return torch.load(save_filename)\ndata_dir = '\/kaggle\/working\/finance_news.txt'\ntext = load_data(data_dir)\n\"\"\"\n# Vocab2int & Int2vocab\n\nHere we are creating 2 dictionaries to convert words to integers (`vocab_to_int`) and integers to vocab (`int_to_vocab`). The integers are assigned in descending order of the frequency, so the most frequent word, \"the\",  is given the integer \"0\" and the next most frequent word is given \"1\" and so on.\n\"\"\"\nview_line_range = (0, 10)\n\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n\nlines = text.split('\\n')\nprint('Number of lines: {}'.format(len(lines)))\nword_count_line = [len(line.split()) for line in lines]\nprint('Average number of words in each line: {}'.format(np.average(word_count_line)))\n\nprint()\nprint('The lines {} to {}:'.format(*view_line_range))\nprint('\\n'.join(text.split('\\n')[view_line_range[0]:view_line_range[1]]))\nfrom collections import Counter\n\ndef create_lookup_tables(text):\n    \"\"\"\n    Create lookup tables for vocabulary\n    :param text: The text of tv scripts split into words\n    :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n    \"\"\"\n    # TODO: Implement Function\n    word_count = Counter(text)\n    sorted_vocab = sorted(word_count, key = word_count.get, reverse=True)\n    int_to_vocab = {ii:word for ii, word in enumerate(sorted_vocab)}\n    vocab_to_int = {word:ii for ii, word in int_to_vocab.items()}\n    \n    # return tuple\n    return (vocab_to_int, int_to_vocab)\n\ndef token_lookup():\n    \"\"\"\n    Generate a dict to turn punctuation into a token.\n    :return: Tokenized dictionary where the key is the punctuation and the value is the token\n    \"\"\"\n    # TODO: Implement Function\n    token = dict()\n    token['.'] = '<PERIOD>'\n    token[','] = '<COMMA>'\n    token['\"'] = 'QUOTATION_MARK'\n    token[';'] = 'SEMICOLON'\n    token['!'] = 'EXCLAIMATION_MARK'\n    token['?'] = 'QUESTION_MARK'\n    token['('] = 'LEFT_PAREN'\n    token[')'] = 'RIGHT_PAREN'\n    token['-'] = 'QUESTION_MARK'\n    token['\\n'] = 'NEW_LINE'\n    return token\n\npreprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)\nint_text, vocab_to_int, int_to_vocab, token_dict = load_preprocess()\ntrain_on_gpu = torch.cuda.is_available()\n\"\"\"\n# Batching Data\n\n We'll use `TensorDataset` to provide a known format to our dataset; in combination with DataLoader, it will handle batching, shuffling, and other dataset iteration functions.<br>\nWe can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n\n```python\ndata = TensorDataset(feature_tensors, target_tensors)\ndata_loader = torch.utils.data.DataLoader(data, batch_size=batch_size)\n```\n\nFor example, say we have these as input:<br>\n```\nwords = [1, 2, 3, 4, 5, 6, 7]\nsequence_length = 4\n```\nOur first feature_tensor should contain the values:<br>\n```\n[1, 2, 3, 4]\n```\nAnd the corresponding target_tensor should just be the next \"word\"\/tokenized word value:<br>\n```\n5\n```\nThis should continue with the second feature_tensor, target_tensor being:<br>\n```\n[2, 3, 4, 5]  # features\n6             # target\n```\n\"\"\"\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch\nimport numpy as np\n\n\ndef batch_data(words, sequence_length, batch_size):\n    \"\"\"\n    Batch the neural network data using DataLoader\n    :param words: The word ids of the TV scripts\n    :param sequence_length: The sequence length of each batch\n    :param batch_size: The size of each batch; the number of sequences in a batch\n    :return: DataLoader with batched data\n    \"\"\"\n    # TODO: Implement function\n    n_batches = len(words)\/\/batch_size\n    x, y = [], []\n    words = words[:n_batches*batch_size]\n    \n    for ii in range(0, len(words)-sequence_length):\n        i_end = ii+sequence_length        \n        batch_x = words[ii:ii+sequence_length]\n        x.append(batch_x)\n        batch_y = words[i_end]\n        y.append(batch_y)\n    \n    data = TensorDataset(torch.from_numpy(np.asarray(x)), torch.from_numpy(np.asarray(y)))\n    data_loader = DataLoader(data, shuffle=True, batch_size=batch_size)\n        \n    \n    # return a dataloader\n    return data_loader\n\n# test dataloader\n\ntest_text = range(50)\nt_loader = batch_data(test_text, sequence_length=5, batch_size=10)\n\ndata_iter = iter(t_loader)\nsample_x, sample_y = data_iter.next()\n\nprint(sample_x.shape)\nprint(sample_x)\nprint()\nprint(sample_y.shape)\nprint(sample_y)\n\"\"\"\n# Talking Points Model\n\n## Genral Architecture\n\n### Embedding Layer\n\nThe model should take our word tokens and firstly pass it through our embedding layer. This layer will be responsible for converting out word tokens or integers into embeddings of specific size. These word embeddings are then fed to the next layer of LSTM cells. <br>\n\nThe main purpose of using embedding layer is dimensionality reduction.\n\n### Contiguous LSTM Layer\n\nOur LSTM layer is defined by *hidden state size and number of layers*. At each step, an LSTM cell will produce an output and a new hidden state. The hidden state will be passed to next cell as input (memory representation.)\n\n### Final Fully Connected Linear Layer\n\nThe output generated by LSTM cell will be then fed into a *Sigmoid activated fully-connected linear layer.* This layer is responsible for mapping LSTM output to desired output size.\n\nThe output of the sigmoid function will be the probability distribution of most likely next word.<br><br>\n\n\n<img src=\"https:\/\/github.com\/purvasingh96\/Talking-points-global-hackathon\/blob\/master\/assets\/lstm_rnn_2.png?raw=1\" height=\"500\"><\/img>\n\n\"\"\"\nimport torch.nn as nn\n\nclass RNN(nn.Module):\n    \n    def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):\n        \"\"\"\n        Initialize the PyTorch RNN Module\n        :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n        :param output_size: The number of output dimensions of the neural network\n        :param embedding_dim: The size of embeddings, should you choose to use them        \n        :param hidden_dim: The size of the hidden layer outputs\n        :param dropout: dropout to add in between LSTM\/GRU layers\n        \"\"\"\n        super(RNN, self).__init__()\n        # TODO: Implement function\n        \n        # define embedding layer\n        self.embedding = nn.Embedding(vocab_size, embedding_dim)\n        \n        # define lstm layer\n        self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)\n        \n        \n        # set class variables\n        self.vocab_size = vocab_size\n        self.output_size = output_size\n        self.embedding_dim = embedding_dim\n        self.hidden_dim = hidden_dim\n        self.n_layers = n_layers\n        \n        # define model layers\n        self.fc = nn.Linear(hidden_dim, output_size)\n    \n    \n    def forward(self, x, hidden):\n        \"\"\"\n        Forward propagation of the neural network\n        :param nn_input: The input to the neural network\n        :param hidden: The hidden state        \n        :return: Two Tensors, the output of the neural network and the latest hidden state\n        \"\"\"\n        # TODO: Implement function   \n        batch_size = x.size(0)\n        x=x.long()\n        \n        # embedding and lstm_out \n        embeds = self.embedding(x)\n        lstm_out, hidden = self.lstm(embeds, hidden)\n        \n        # stack up lstm layers\n        lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)\n        \n        # dropout, fc layer and final sigmoid layer\n        out = self.fc(lstm_out)\n        \n        # reshaping out layer to batch_size * seq_length * output_size\n        out = out.view(batch_size, -1, self.output_size)\n        \n        # return last batch\n        out = out[:, -1]\n\n        # return one batch of output word scores and the hidden state\n        return out, hidden\n    \n    \n    def init_hidden(self, batch_size):\n        '''\n        Initialize the hidden state of an LSTM\/GRU\n        :param batch_size: The batch_size of the hidden state\n        :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n        '''\n        # create 2 new zero tensors of size n_layers * batch_size * hidden_dim\n        weights = next(self.parameters()).data\n        if(train_on_gpu):\n            hidden = (weights.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(), \n                     weights.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n        else:\n            hidden = (weights.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n                     weights.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n        \n        # initialize hidden state with zero weights, and move to GPU if available\n        \n        return hidden\ndef forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n    \"\"\"\n    Forward and backward propagation on the neural network\n    :param decoder: The PyTorch Module that holds the neural network\n    :param decoder_optimizer: The PyTorch optimizer for the neural network\n    :param criterion: The PyTorch loss function\n    :param inp: A batch of input to the neural network\n    :param target: The target output for the batch of input\n    :return: The loss and the latest hidden state Tensor\n    \"\"\"\n    \n    # TODO: Implement Function\n    \n    # move data to GPU, if available\n    if(train_on_gpu):\n        rnn.cuda()\n    \n    # creating variables for hidden state to prevent back-propagation\n    # of historical states \n    h = tuple([each.data for each in hidden])\n    \n    rnn.zero_grad()\n    # move inputs, targets to GPU \n    inputs, targets = inp.cuda(), target.cuda()\n    \n    output, h = rnn(inputs, h)\n    \n    loss = criterion(output, targets)\n    \n    # perform backpropagation and optimization\n    loss.backward()\n    nn.utils.clip_grad_norm_(rnn.parameters(), 5)\n    optimizer.step()\n\n    # return the loss over a batch and the hidden state produced by our model\n    return loss.item(), h\n\ndef train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):\n    batch_losses = []\n    \n    rnn.train()\n\n    print(\"Training for %d epoch(s)...\" % n_epochs)\n    for epoch_i in range(1, n_epochs + 1):\n        \n        # initialize hidden state\n        hidden = rnn.init_hidden(batch_size)\n        \n        for batch_i, (inputs, labels) in enumerate(train_loader, 1):\n            \n            # make sure you iterate over completely full batches, only\n            n_batches = len(train_loader.dataset)\/\/batch_size\n            if(batch_i > n_batches):\n                break\n            \n            # forward, back prop\n            loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden)          \n            # record loss\n            batch_losses.append(loss)\n\n            # printing loss stats\n            if batch_i % show_every_n_batches == 0:\n                print('Epoch: {:>4}\/{:<4}  Loss: {}\\n'.format(\n                    epoch_i, n_epochs, np.average(batch_losses)))\n                batch_losses = []\n\n    # returns a trained rnn\n    return rnn\n# Data params\n# Sequence Length\nsequence_length = 10  # of words in a sequence\n# Batch Size\nbatch_size = 128\n\n# data loader - do not change\ntrain_loader = batch_data(int_text, sequence_length, batch_size)\n# Training parameters\n# Number of Epochs\nnum_epochs = 10\n# Learning Rate\nlearning_rate = 0.001\n\n# Model parameters\n# Vocab size\nvocab_size = len(vocab_to_int)\n# Output size\noutput_size = vocab_size\n# Embedding Dimension\nembedding_dim = 200\n# Hidden Dimension\nhidden_dim = 250\n# Number of RNN Layers\nn_layers = 2\n\n# Show stats for every n number of batches\nshow_every_n_batches = 500\n# create model and move to gpu if available\nrnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5)\nif train_on_gpu:\n    rnn.cuda()\n\n# defining loss and optimization functions for training\noptimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\n# training the model\ntrained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches)\n\n# saving the trained model\nsave_model('.\/save\/trained_rnn', trained_rnn)\nprint('Model Trained and Saved')\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\n\n_, vocab_to_int, int_to_vocab, token_dict = load_preprocess()\ntrained_rnn = load_model('.\/save\/trained_rnn')\nimport torch.nn.functional as F\n\ndef generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):\n    \"\"\"\n    Generate text using the neural network\n    :param decoder: The PyTorch Module that holds the trained neural network\n    :param prime_id: The word id to start the first prediction\n    :param int_to_vocab: Dict of word id keys to word values\n    :param token_dict: Dict of puncuation tokens keys to puncuation values\n    :param pad_value: The value used to pad a sequence\n    :param predict_len: The length of text to generate\n    :return: The generated text\n    \"\"\"\n    rnn.eval()\n    \n    # create a sequence (batch_size=1) with the prime_id\n    current_seq = np.full((1, sequence_length), pad_value)\n    current_seq[-1][-1] = prime_id\n    predicted = [int_to_vocab[prime_id]]\n    \n    for _ in range(predict_len):\n        if train_on_gpu:\n            current_seq = torch.LongTensor(current_seq).cuda()\n        else:\n            current_seq = torch.LongTensor(current_seq)\n        \n        # initialize the hidden state\n        hidden = rnn.init_hidden(current_seq.size(0))\n        \n        # get the output of the rnn\n        output, _ = rnn(current_seq, hidden)\n        \n        # get the next word probabilities\n        p = F.softmax(output, dim=1).data\n        if(train_on_gpu):\n            p = p.cpu() # move to cpu\n         \n        # use top_k sampling to get the index of the next word\n        top_k = 5\n        p, top_i = p.topk(top_k)\n        top_i = top_i.numpy().squeeze()\n        \n        # select the likely next word index with some element of randomness\n        p = p.numpy().squeeze()\n        word_i = np.random.choice(top_i, p=p\/p.sum())\n        \n        # retrieve that word from the dictionary\n        word = int_to_vocab[word_i]\n        predicted.append(word)     \n        \n        # the generated word becomes the next \"current sequence\" and the cycle can continue\n        current_seq = np.roll(current_seq.cpu(), -1, 1)\n        current_seq[-1][-1] = word_i\n    \n    gen_sentences = ' '.join(predicted)\n    \n    # Replace punctuation tokens\n    for key, token in token_dict.items():\n        ending = ' ' if key in ['\\n', '(', '\"'] else ''\n        gen_sentences = gen_sentences.replace(' ' + token.lower(), key)\n    gen_sentences = gen_sentences.replace('\\n ', '\\n')\n    gen_sentences = gen_sentences.replace('( ', '(')\n    \n    # return all the sentences\n    return gen_sentences\n\ngen_length = 50 # modify the length to your preference\nprime_words = ['tesla'] # name for starting the script\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfor prime_word in prime_words:\n    pad_word = SPECIAL_WORDS['PADDING']\n    generated_script = generate(trained_rnn, vocab_to_int[prime_word], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\n    print(generated_script)\n\"\"\"\n## Future Work\n\nThere are few things which I would like to work on to improvise the model's performance-\n\n1. Use of bidirectional LSTM\n2. Pre-trained word embeddings such as GloVe or FastText\n3. Larger dataset that focuses on impact of corona pandemic on stocks.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '51e5eabb46fc4f'}"}
{"id":"118306","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\n\nwarnings.filterwarnings('ignore')\nsns.set()\n# 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\n\"\"\"\n# 0) Let's explore our data\n\"\"\"\ndata = pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ndata.head(3)\ndata.shape\n\"\"\"\n## Feature description \n|Feature|Description|Value|\n|---|---|---|\n|survival|Survival |0 = No, 1 = Yes\n|pclass|Ticket class|1 = 1st, 2 = 2nd, 3 = 3rd\n|sex||\n|Age|Age in year|\n|sibsp|\t# of siblings \/ spouses aboard the Titanic\t|\n|parch|\t# of parents \/ children aboard the Titanic\t|\n|ticket|\tTicket number\t|\n|fare\tPassenger fare\t|\n|cabin\t|Cabin number\t|\n|embarked\t|Port of Embarkation|\tC = Cherbourg, Q = Queenstown, S = Southampton\n\"\"\"\n\"\"\"\n## Declare the color for each target\n\"\"\"\nsurvived = sns.color_palette()[2]   # Green\ndied = sns.color_palette()[3]       # Red\ndata_vis = data.copy()\ndata_vis['Survived'] = data_vis['Survived'].replace({0:'Died', 1:'Survived'})\n\"\"\"\n## 0.1) Looking into 'passenger class'\n\"\"\"\nsns.countplot(data=data_vis, x='Pclass', hue='Survived', palette={'Died':died, 'Survived':survived})\nplt.xticks([0,1,2],['Upper class','Middle class','Lower class'])\nplt.xlabel('Passenger Class')\nplt.title('Survivors\/Deaths in each passenger class')\nplt.show()\n\"\"\"\nWe can obviously see that passengers in 'Upper class' are more likely to survive than other classes, While the 'Lower class' passengers are died the most.\n\"\"\"\n\"\"\"\n## 0.2) Looking into 'Age'\n\"\"\"\n#sns.histplot(data=data_vis, x='Age', hue='Survived', multiple='layer', element='step', palette={'Died':died, 'Survived':survived}, hue_order=['Survived','Died'])\n\nplt.hist(data_vis[data_vis['Survived']=='Died']['Age'], histtype='stepfilled', color=died, alpha=0.6, label='Died', bins=np.linspace(0,80,20))\nplt.hist(data_vis[data_vis['Survived']=='Survived']['Age'], histtype='stepfilled', color=survived, alpha=0.6, label='Survived', bins=np.linspace(0,80,20))\nplt.title('Survivors\/Deaths\\' distribution')\nplt.xlabel('Age')\nplt.ylabel('Count')\nplt.legend(title='Survived')\nplt.show()\n\"\"\"\nFrom histogram above, we see that most passengers are 20-50 years old. <br>\nAlso, we notice that child passenger(0-20 years old) has more survived than died.  \n\"\"\"\n\"\"\"\n## 0.3) Looking into 'gender'\n\"\"\"\nsns.countplot(data=data_vis, x='Sex', hue='Survived', palette={'Died':died, 'Survived':survived})\nplt.title('Survivors\/Deaths\\' gender')\nplt.xlabel('Gender')\nplt.show()\n\"\"\"\nThere are a very obvious trend here. Male is much more likely to die than female. <br>\n\n\"\"\"\n\"\"\"\n### My guess by looking to the data, <br>\n'Upper class', 'Children', 'Female' passenger are more likely to survie.\n\"\"\"\n\"\"\"\n## 0.4) Looking into 'embarked town'\n\"\"\"\nsns.countplot(data=data_vis, x='Embarked', hue='Survived', palette={'Died':died, 'Survived':survived})\nplt.xticks([0,1,2],['Southampton', 'Cherbourg',  'Queenstown'])\nplt.title('Survivors\/Deaths classified by embarked town')\nplt.xlabel('Embarked town')\nplt.show()\n\"\"\"\n# 1) Preprocessing\n\"\"\"\n\"\"\"\n## 1.1) Feature Selection\n\"\"\"\n\"\"\"\n### Drop identity: 'PassengerID', 'Name', 'Ticket'\n\"\"\"\ndata.drop(['PassengerId', 'Name', 'Ticket'], axis=1, inplace=True)\ndata.head(3)\n\"\"\"\n## 1.2) Missing value\n\"\"\"\nmissing = pd.DataFrame(data.isnull().sum()\/len(data), columns=['NaN'])\n\nmissing.style.background_gradient(cmap=sns.light_palette(\"red\", as_cmap=True))\n\"\"\"\nWe see that 'Cabin' is 77.1% missing. Thus, we manage to drop this feature.\n\"\"\"\ndata = data.drop(['Cabin'], axis=1)\n\"\"\"\n'Age' will be imputed with its mean.\n\"\"\"\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(missing_values=np.nan, strategy='mean').fit(data[['Age']])\n\ndata_imputed = data.copy()\ndata_imputed[['Age']] = imputer.transform(data_imputed[['Age']])\n\n\"\"\"\n'Embarked' will be forwward filled.\n\"\"\"\ndata_imputed.fillna(method='ffill', inplace=True)\ndata_imputed.isnull().sum()\n\"\"\"\n## 1.3) Encoding categorical features**\n\"\"\"\ndata_imputed.head(3)\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.compose import ColumnTransformer\n\nX, y = data_imputed.drop('Survived',axis=1), data_imputed[['Survived']]\n\n\nohe = OneHotEncoder().fit(X.loc[:,['Sex','Embarked']])\n\nct = ColumnTransformer([\n    ('One Hot Encode', ohe, [1,6])\n], remainder='passthrough')\n\n\ndata_imputed_encoded = ct.fit_transform(X)\n\"\"\"\n## 1.4) Scale the data\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(data_imputed_encoded, y, test_size=0.2, stratify=y)\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler().fit(X_train)\n\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\"\"\"\n# 2) Building the learning models\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix, classification_report, plot_roc_curve, roc_auc_score\n\nmodels = dict()\n\nmodels['Logistic Regression'] = LogisticRegression()\nmodels['Decision Tree'] = DecisionTreeClassifier()\nmodels['Random Forest'] = RandomForestClassifier(criterion='gini',\n                                           n_estimators=1750,\n                                           max_depth=7,\n                                           min_samples_split=6,\n                                           min_samples_leaf=6,\n                                           max_features='auto',\n                                           oob_score=True,\n                                           n_jobs=-1,) \nmodels['Gradient Boosting'] = GradientBoostingClassifier()\nmodels['Support Vector'] = SVC()\nmodels['Naive Bayes'] = GaussianNB()\n\n\ndef fit_models(models, X_train_scaled, y_train):\n    for x in models:\n        models[x].fit(X_train_scaled, y_train)\n        print(x+': fitted')\n\ndef get_report(models, X_test_scaled, y_test):\n    reports = dict()\n    for x in models:\n        model = models[x]\n        y_pred = model.predict(X_test_scaled)\n        reports[x] = [confusion_matrix(y_test, y_pred),classification_report(y_test, y_pred), roc_auc_score(y_test, y_pred)]\n        print(x+': reported')\n    return reports\n\nfit_models(models, X_train_scaled, y_train)\nreports = get_report(models, X_test_scaled, y_test)\nfor each in reports:\n    cm, cr, roc = reports[each]\n    print('------------'+each+'------------')\n    print(roc)\n    print(cm)\n    print(cr)\ndef PREPROCESS(data):\n    \n    # 1.1) Feature Selection: drop identity\n    data.drop(['PassengerId', 'Name', 'Ticket'], axis=1, inplace=True)\n    \n    # 1.2) Missing Value\n        # Drop too many missing\n    data.drop(['Cabin'], axis=1, inplace=True)\n        # Impute numerical feaure\n    data_imputed = data.copy()\n    data_imputed[['Age']] = imputer.transform(data_imputed[['Age']])\n        # Forward fill categorical features\n    data_imputed.fillna(method='ffill', inplace=True)\n    \n    # 1.3) Encode categorical features\n    data_imputed_encoded = ct.fit_transform(data_imputed)\n    \n    # 1.4) Scale the data\n    X_test_scaled = scaler.transform(data_imputed_encoded)\n    \n    return X_test_scaled\n    \nTEST = pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\nindex = TEST['PassengerId']\nTEST.head(3)\nTEST_PREPROCESS = PREPROCESS(TEST)\ntest_pred = models['Support Vector'].predict(TEST_PREPROCESS)\n\nout = pd.DataFrame({'Survived':test_pred}, index=index)\nout.to_csv('OUTPUT_2.csv')","meta":"{'source': 'AI4Code', 'id': 'd9aba0efba8334'}"}
{"id":"28126","text":"# 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\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\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom tensorflow.keras.optimizers import Adam\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\n\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud \nimport plotly.graph_objects as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport seaborn as sns\n\nimport numpy as np \nimport pandas as pd\n\nimport random as rn\ndata = pd.read_csv('..\/input\/trip-advisor-hotel-reviews\/tripadvisor_hotel_reviews.csv')\ndata.head()\n\"\"\"\n### Total examples\n\"\"\"\nprint('Examples in data: {}'.format(len(data)))\n\"\"\"\n### Any null values\n\"\"\"\ndata.isna().sum()\n\"\"\"\n## Class Distribution\n\"\"\"\nclass_dist = data['Rating'].value_counts()\n\ndef ditribution_plot(x,y,name):\n    fig = go.Figure([\n        go.Bar(x=x, y=y)\n    ])\n\n    fig.update_layout(title_text=name)\n    fig.show()\nditribution_plot(x= class_dist.index, y= class_dist.values, name= 'Class Distribution')\n\"\"\"\n## Most used Words\n\"\"\"\ndef wordCloud_generator(data, title=None):\n    wordcloud = WordCloud(width = 800, height = 800,\n                          background_color ='black',\n                          min_font_size = 10\n                         ).generate(\" \".join(data.values))\n    # plot the WordCloud image                        \n    plt.figure(figsize = (8, 8), facecolor = None) \n    plt.imshow(wordcloud, interpolation='bilinear') \n    plt.axis(\"off\") \n    plt.tight_layout(pad = 0) \n    plt.title(title,fontsize=30)\n    plt.show() \nwordCloud_generator(data['Review'], title=\"Most used words in reviews\")\n\"\"\"\n# Data preprocessing\n\"\"\"\nX = data['Review'].copy()\ny = data['Rating'].copy()\n\"\"\"\n### Label Encoding\n\"\"\"\nencoding = {1: 0,\n            2: 1,\n            3: 2,\n            4: 3,\n            5: 4\n           }\n\nlabels = ['1', '2', '3', '4', '5']\n\ny = data['Rating'].copy()\ny.replace(encoding, inplace=True)\n\"\"\"\n### Split data into train\/test\n\"\"\"\nfrom sklearn.model_selection import train_test_split\ntrain_texts, test_texts, train_labels, test_labels = train_test_split(\n    X.values.tolist(), y, test_size=.33, random_state=67, stratify=y)\n\nprint(\"Examples in train data: {}\".format(len(train_texts)))\nprint(\"Examples in test data: {}\".format(len(test_texts)))\n\"\"\"\n### Tokenizing\n\"\"\"\nfrom transformers import DistilBertTokenizer\ntokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')\n\nseq_len = 350\n\ntrain_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=seq_len)\ntest_encodings = tokenizer(test_texts, truncation=True, padding=True, max_length=seq_len)\n\ninput_ids_train = np.array(train_encodings['input_ids']) \nattention_mask_train = np.array(train_encodings['attention_mask'])\n\ninput_ids_test = np.array(test_encodings['input_ids']) \nattention_mask_test = np.array(test_encodings['attention_mask'])\n# Example\nexp_sen = 1\n\nprint(\"\\nExample:\\n\")\nprint(\"Sentence:\\n{}\".format(train_texts[exp_sen]))\nprint(\"\\nAfter tokenizing :\\n{}\".format(tokenizer.encode(train_texts[exp_sen])))\nprint(\"\\nAfter padding :\\n{}\".format(input_ids_train[exp_sen]))\n\"\"\"\n# Model building and training\n#### Steps:\n1. Load the pretrained Bert model\n2. Pass whole data from Bert and calculate the final hidden states\n3. Train a custom model on a first vector of final hidden states of bert\n\"\"\"\n\"\"\"\n### Loading DistilBert model\n\"\"\"\nfrom transformers import TFDistilBertModel\n\nbert = TFDistilBertModel.from_pretrained('distilbert-base-uncased')\n\"\"\"\n### Passing data through bert\n![](http:\/\/jalammar.github.io\/images\/distilBERT\/bert-output-tensor-selection.png)\n[Source](http:\/\/jalammar.github.io\/a-visual-guide-to-using-bert-for-the-first-time\/)\n\"\"\"\n# Creating bert model\ninp_ids = L.Input(shape=(seq_len,), dtype=tf.int32) # Shape:(batch_size, seq_len)\nattention_mask = L.Input(shape=(seq_len,), dtype=tf.int32) # Shape:(batch_size, seq_len)\nlast_hidden_state = bert(inp_ids,attention_mask=attention_mask)[0] # Shape:(batch_size, seq_len, 768)\nout = last_hidden_state[:,0,:] # Shape:(Batch_size, 768)\n\nbert_model = tf.keras.Model(inputs=[inp_ids, attention_mask], outputs=out)\n\n# Passing data from bert pretrained model and extracting the final state.\n\nprint(\"Passing train data\")\nbert_output_train = bert_model.predict(\n    [input_ids_train,attention_mask_train], batch_size=16, verbose=1)\n\nprint(\"Passing test data\")\nbert_output_test = bert_model.predict(\n    [input_ids_test,attention_mask_test], batch_size=16, verbose=1)\nprint(\"Bert output train: {}\".format(bert_output_train.shape))\nprint(\"Bert output test: {}\".format(bert_output_test.shape))\n\"\"\"\n### Building a custom model\n\"\"\"\nseed_value = 1337\nnp.random.seed(seed_value)\ntf.random.set_seed(seed_value)\nrn.seed(seed_value)\n\nmodel = tf.keras.Sequential([\n    L.Input(shape=(768)),\n    L.Dense(128,activation='relu'),\n    L.Dropout(0.5),\n    L.Dense(5, activation=\"softmax\")\n])\n\n\nmodel.compile(loss=SparseCategoricalCrossentropy(),\n              optimizer='adam',metrics=['accuracy']\n             )\n\nmodel.summary()\n\"\"\"\n### Training\n\"\"\"\n# Passing bert output for training\nhistory = model.fit(\n    bert_output_train, train_labels, epochs=22, validation_split=0.12, batch_size=32, verbose=2)\n\"\"\"\n### Training history\n\"\"\"\nfig = px.line(\n    history.history, y=['loss', 'val_loss'],\n    labels={'index': 'epoch', 'value': 'loss'}\n)\n\nfig.show()\nfig = px.line(\n    history.history, y=['accuracy', 'val_accuracy'],\n    labels={'index': 'epoch', 'value': 'accuracy'}\n)\n\nfig.show()\n\"\"\"\n# Evaluating\n\"\"\"\npred = model.predict_classes(bert_output_test)\n\"\"\"\n### Accuracy\n\"\"\"\nprint('Accuracy: {}'.format(accuracy_score(pred, test_labels)))\n\"\"\"\n### MAE\n\"\"\"\nprint(\"Mean absolute error: {}\".format(mean_absolute_error(pred,test_labels)))\n\"\"\"\n### RMSE\n\"\"\"\nprint(\"Root mean square error: {}\".format(np.sqrt(mean_squared_error(pred,test_labels))))\n\"\"\"\n### Confusion matrix\n\"\"\"\nconf = confusion_matrix(test_labels, pred)\n\ncm = pd.DataFrame(\n    conf, index = [i for i in labels],\n    columns = [i for i in labels]\n)\n\nplt.figure(figsize = (12,7))\nsns.heatmap(cm, annot=True, fmt=\"d\")\nplt.show()\n\"\"\"\n### Classification Report\n\"\"\"\nprint(classification_report(test_labels, pred, target_names=labels))","meta":"{'source': 'AI4Code', 'id': '33c6df6a624725'}"}
{"id":"67693","text":"\"\"\"\nHi everyone,\n1. Today I will analyze \"Lower Back Pain Symptoms\" dataset.\n1. Then I will try some supervised machine learning algorithms.\n\nLet's start with including some necessary libraries.\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n#For ignoring warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nprint(os.listdir(\"..\/input\"))\ndata = pd.read_csv(\"..\/input\/Dataset_spine.csv\")\n\"\"\"\nI think it is time to look our dataset.\n\"\"\"\ndata.sample(5)\n\"\"\"\nAs you can see above, we have columns named like  \"Col1, Col2, ..\". \n1. We have a column named\" Class_att\". We need to learn its unique values.\n1. And then we need to get rid of the \"Unnamed : 13\" column, also we need to delete rows which has NaN value.\n\nLet's learn our unique classes.\n\"\"\"\ndata[\"Class_att\"].unique()\ndata.dropna(axis = 1, inplace = True)\ndata.sample()\n\"\"\"\nIt is time to find relevances between our data values.\n* To do this, I will use Seaborn library.\n\"\"\"\n#correlation map\nimport seaborn as sns\nf, ax = plt.subplots(figsize = (18,18))\nsns.heatmap(data.corr(), annot = True, fmt = '.2f', ax = ax)\nplt.show()\n\"\"\"\nOur data looks separable.\n* Let's look some relevant values graph.\n\"\"\"\ndata.Col2.plot(label = \"Col2\")\ndata.Col1.plot(label = \"Col1\")\nplt.xlabel(\"index\", color = \"red\")\nplt.ylabel(\"values\", color = \"red\")\nplt.legend()\nplt.title(\"Col1 and Col2\")\nplt.show()\n\"\"\"\nAs you can see, there is a significant discrimination.\n* If you want more detailed correlation graphic for each value:\n\"\"\"\ncolor_list = ['red' if i=='Abnormal' else 'green' for i in data.loc[:,'Class_att']]\npd.plotting.scatter_matrix(data.loc[:, data.columns != 'Class_att'],\n                                       c=color_list,\n                                       figsize= [15,15],\n                                       diagonal='hist',\n                                       alpha=0.5,\n                                       s = 200,\n                                       marker = '.',\n                                       edgecolor= \"black\")\nplt.show()\n\"\"\"\nLet's find out how many class types we have.\n\"\"\"\nsns.countplot(data = data, x = \"Class_att\")\nplt.show()\ndata.loc[:,\"Class_att\"].value_counts()\n\"\"\"\nAs you can see above, we have 2 types of data whose are Abnormal and normal.\n\n<br>***We have learned enough about our data so now we can apply some supervised learning algorithms.***\n<h2> Supervised Machine Learning Topics:<\/h2>\n\n1. KNN Classifier (with Grid Search)\n1. KNN Classifier with Principal Component Analysis (PCA)\n1. KNN Classifier with Linear Discriminant Analysis (LDA)\n1. Logistic Regression Classifier\n1. Decision Tree Classifier With K-fold Cross Validation And Confusion Matrix\n1. Naive Bayes Classifier\n1. Random Forest Classifier\n1. Support Vector Machine Classifier\n\n<br>Let's get started!\n\"\"\"\n\"\"\"\n**KNN Classifier**\n<br>The idea is to find a predefined number of training samples closest in distance to the new point, and predict the label from these.\n![0_Sk18h9op6uK9EpT8_.png](attachment:0_Sk18h9op6uK9EpT8_.png)\n1. First thing we need to do is seperating our data to x and y.\n1. Then split data to train and test\n1. And apply KNN with Grid Search\n\"\"\"\n#x, y Split and Normalization\nx_data = data.iloc[:, 0:12].values\nx = (x_data - np.min(x_data)) \/ (np.max(x_data) - np.min(x_data))#Normalization\ny = data.iloc[:, 12]\n\n#Train, Test Split\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.1, random_state = 1)\n\n#Grid Search\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.grid_search import GridSearchCV\ngrid = {\"n_neighbors\":np.arange(1,50)}\nknn = KNeighborsClassifier()\nknn_cv = GridSearchCV(knn, grid, cv = 10)#cv = How many data split do we want\nknn_cv.fit(x_train, y_train)\nprint(\"Best number of neighbors is {}\".format(knn_cv.best_params_[\"n_neighbors\"]))\nprint(\"Best score is {}\".format(round(knn_cv.best_score_,2)))\n\n#Grid Search Visualization\nscore = []\nfor i in range(1,50):\n    knn2 = KNeighborsClassifier(n_neighbors = i)\n    knn2.fit(x_train, y_train)\n    score.append(knn2.score(x_test, y_test))\nplt.plot(np.arange(1,50), score)\nplt.xlabel(\"Number of neighbors\", color = \"red\", fontsize = 14)\nplt.ylabel(\"Score\", color = \"red\", fontsize = 14)\nplt.show()\n\"\"\"\n**KNN Classifier with Principal Component Analysis (PCA)**\n1. PCA is basically lowers dimension of the data.\n1. PCA helps us when we try to vizualize higher dimensioned data.\n\nSo let's apply PCA to our data.\n\n\n\"\"\"\n#Clone our data\ndata_pca = data.copy()\ndata_pca[\"Class_att\"] = [1 if i == \"Abnormal\" else 0 for i in data_pca[\"Class_att\"]]\n#Then put it in PCA\nfrom sklearn.decomposition import PCA\npca_model = PCA(n_components = 6)\npca_model.fit(data_pca)\ndata_pca = pca_model.transform(data_pca)\n# PCA Variance\nplt.bar(range(pca_model.n_components_), pca_model.explained_variance_ratio_*100 )\nplt.xlabel('PCA n_components',size=12,color='red')\nplt.ylabel('Variance Ratio(%)',size=12,color='red')\nplt.show()\n\"\"\"\nAs you can see below, if we increase the number of components, our data variance is **sharply decreasing,**\n<br>which is good because this feature provides us **less complex data shape and less calculating time.**\n* Now let's  learn **KNN with PCA.**\n\"\"\"\n#In this scenario, I want my data in 2 dimension.\npca_model = PCA(n_components = 2)\npca_model.fit(data_pca)\ndata_pca = pca_model.transform(data_pca)\nprint(\"My old shape:\", data.shape)\nprint(\"My new shape:\", data_pca.shape)\nx_pca = data_pca[:,0]\ny_pca = data_pca[:,1]\nplt.scatter(x_pca, y_pca, c = [\"red\",\"green\"])\nplt.show()\n\n\"\"\"\nAs you can see, **we have converted (310, 13) to (310, 2) and vizualized**\n* But wait a minute, what about scores?\n<br>Let's find out them!\n\"\"\"\n# KNN\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_normal = KNeighborsClassifier()\nknn_normal.fit(x_train, y_train)\nprint(\"KNN without PCA score :\", knn_normal.score(x_test, y_test))\n\n\n## KNN With PCA\n#Train, Test Split\nx_pca = x_pca.reshape(-1,1)\ny_pca = y_pca.reshape(-1,1)\ny_pca_edit = [round(float(i),0) for i in y_pca]\ny_pca_edit = [\"Abnormal\" if i>0 else \"Normal\" for i in y_pca_edit]\ny_pca_edit = np.array(y_pca_edit)\nfrom sklearn.model_selection import train_test_split\nx_pca_train, x_pca_test, y_pca_train, y_pca_test = train_test_split(x_pca, y_pca_edit, test_size = 0.1, random_state = 1)\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_pca = KNeighborsClassifier()\nknn_pca.fit(x_pca_train, y_pca_train)\nprint(\"KNN with PCA score    :\", knn_pca.score(x_pca_test, y_pca_test))\n\"\"\"\nThere is a difference between \"*with and without KNN with PCA*\" score, **so PCA is really helpful when we need less data shape. Also if you have a less varience then you should use PCA.**\n\"\"\"\n\"\"\"\n**KNN Classifier with Linear Discriminant Analysis (LDA)**\n1. LDA is similar to PCA but **in LDA, we try to find best dimension that separates columns perfectly.**\n1. Vice versa in PCA, we try to **separate all values from each other.**\n\nSo let's apply LDA to our data.\n\n\n\"\"\"\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nlda = LinearDiscriminantAnalysis(n_components = 2)# 13 ----> 2\nx_train_lda = lda.fit_transform(x_train, y_train)\nx_test_lda = lda.transform(x_test)\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_lda = KNeighborsClassifier()\nknn_lda.fit(x_train_lda, y_train)\n\nprint(\"KNN score :\", knn_normal.score(x_test, y_test))\nprint(\"KNN with PCA score    :\", knn_pca.score(x_pca_test, y_pca_test))\nprint(\"KNN with LDA score    :\", knn_lda.score(x_test_lda, y_test))\n\"\"\"\n**Logistic Regression Classifier**\n<br>Logistic regression is named for the function used at the core of the method, the logistic function. Logistic regression is also a simple neural network because it has weight, bias and learning rate. In short, it has an iteration that tries to find bias and weights.\n<br>Input values (x) are combined linearly using weights or coefficient values to predict an output value (y). If the output value is higher than 0.5 then it predicts 1, else it predicts 0. \n![Logistic-Function.png](attachment:Logistic-Function.png)\n\n<br>Each column in your input data has an associated w and b coefficients that must be **learned** from your training data\n<br>\n<br>Let's implement Logistic Regression to our data.\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression(max_iter = 100)#max_iter is for forward and backward propogation\nlr.fit(x_train, y_train)\nlr.score(x_test, y_test)\n\"\"\"\n<h1>**Decision Tree Classifier With K-fold Cross Validation And Confusion Matrix**<\/h1>\n\n<br>**Confusion Matrix** is a table that is often used to describe the performance of a classification model on a set of test data for which the true values are known. \n![confusion_matrix_simple2.png](attachment:confusion_matrix_simple2.png)\n<br>**K-fold Cross Validation** is a *resampling procedure used to evaluate machine learning models on a limited data sample*. It has a single parameter called **k that refers to the number of groups that a given data sample is to be split into.** If k is given k=10 then this means our given data will be split into 10 pieces and also this means we have 10-fold cross-validation.\n![K-fold_cross_validation_EN.jpg](attachment:K-fold_cross_validation_EN.jpg)\n<br>**Decision Tree Classifier,** repetitively divides the working area(plot) into sub part by identifying lines.\n![1_1CchuZc1nLM3B60zS7A1yw.png](attachment:1_1CchuZc1nLM3B60zS7A1yw.png)\n<br>Let's implement Decision Tree Classifier to our data.\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\ndtc = DecisionTreeClassifier(random_state = 1)\ndtc.fit(x_train, y_train)\n\n#K-fold Cross Validation\nfrom sklearn.model_selection import cross_val_score\ncvs_scores = cross_val_score(knn_normal, x_pca_test, y_pca_test, cv=5) #cv=5 means, we will split our data into 5 pieces\nprint(\"Cross Validation score is\", cvs_scores.mean())\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, dtc.predict(x_test))\nprint(\"Confusion Matrix \\n\",cm)\n\"\"\"\nSo we have 23 true predictions and 8 false predictions\n\"\"\"\n\"\"\"\n**Naive Bayes Classifier**\nNaive Bayes classifier uses probability theory to classify data. Naive Bayes classifier algorithms make use of Bayes' theorem. The key insight of Bayes' theorem is that the probability of an event can be adjusted as new data is introduced.\n\"\"\"\n#x, y Split and Normalization\nx_data = data.iloc[:, 0:12].values\nx = (x_data - np.min(x_data)) \/ (np.max(x_data) - np.min(x_data))#Normalization\ny = data.iloc[:, 12]\n\n#Train, Test Split\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.1, random_state = 1)\n\ny_train=y_train.values.reshape(-1,1)\ny_test=y_test.values.reshape(-1,1)\n\n#Naive bayes\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\ny_pred = gnb.fit(x_train, y_train)\n\nprint(\"Navie Bayes score is\", gnb.score(x_test, y_test))\n\"\"\"\n**Random Forest Classifier**\n<br>Random forest builds multiple decision trees and merges them together to get a more accurate and stable prediction.\n![random%20forest.PNG](attachment:random%20forest.PNG)\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier(max_depth=2, random_state=0, n_estimators=100)\n#max_depth = The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure\n#n_estimators = The number of trees in the forest.\nrfc.fit(x_train, y_train)\n\nprint(\"Random Forest score is\", rfc.score(x_test, y_test))\n\"\"\"\n**Support Vector Machine Classifier**\n<br> In this algorithm, we plot each data item as a point in n-dimensional space (where n is number of features you have) with the value of each feature being the value of a particular coordinate. Then, we perform classification by finding the hyper-plane that differentiate the two classes very well.\n![svm.PNG](attachment:svm.PNG)\n\"\"\"\nfrom sklearn import svm\nmodel = svm.SVC() \nmodel.fit(x_train, y_train)\nprint(\"Support Vector Machine score is\", model.score(x_test, y_test))\n\"\"\"\n<h1>Conclusion<\/h1>\nThere are a few of supervised machine learning methods in this paper and wrote this to remember all of these methods.\n\n<h1>References<\/h1>\n* scikit-learn.org\n* machinelearningmastery.com\/k-fold-cross-validation\/\n* dataschool.io\/simple-guide-to-confusion-matrix-terminology\/\n* analyticsvidhya.com\/blog\/2017\/09\/understaing-support-vector-machine-example-code\/\n* towardsdatascience.com\/the-random-forest-algorithm-d457d499ffcd\n* www.techopedia.com\/definition\/32335\/naive-bayes\nanalyticsvidhya.com\/blog\/2017\/09\/naive-bayes-explained\/\n\n<br>See you later in Deep Learning!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7c9a9cd845a698'}"}
{"id":"95","text":"\"\"\"\n## How to Build a Content-Based Recommender System For Your Product ??\n\"\"\"\n\"\"\"\n### Presenting users with the most relevant information is an important task for any product to fulfill. To do this properly, you need to be able to extract their preferences from your raw data. Here\u2019s a framework for you to start doing that.\n\"\"\"\n\"\"\"\n![Inner-blog-image.png](attachment:Inner-blog-image.png)\n\"\"\"\n\"\"\"\n## Recommender systems\n### There are two main data selection methods:\n\n* ### Collaborative-filtering: In collaborative-filtering items are recommended, for example movies, based on how similar your user profile is to other users\u2019, finds the users that are most similar to you and then recommends items that they have shown a preference for. This method suffers from the so-called cold-start problem: If there is a new movie, no-one else would\u2019ve yet liked or watched it, so you\u2019re not going to have this in your list of recommended movies, even if you\u2019d love it.\n\n* ### Content-based filtering: This method uses attributes of the content to recommend similar content. It doesn\u2019t have a cold-start problem because it works through attributes or tags of the content, such as actors, genres or directors, so that new movies can be recommended right away.\n\n### Based on this, I\u2019m going to introduce you to content-based filtering for a movie recommender system. I\u2019ll use Python as the programming language for the implementation.\n\"\"\"\n# 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 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\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\n\"\"\"\n### Step 1: Choosing your data\n* ### The first thing to do when starting a data science project is to decide what data sets are going to be relevant to your problem. This stage of the project is referred to as data selection and is highly important because if you choose the wrong data source, you won\u2019t get successful performance.\n\"\"\"\ndata = pd.read_csv('\/kaggle\/input\/news-dataset-18920\/result_final.csv')\ndata.shape\ndata.head()\n\"\"\"\n* ### Data cleaning and selecting few columns we will be requiring for the recomendation--\n\"\"\"\ndata = data.drop_duplicates(subset=None, keep='first', inplace=False)\ndata.shape\ndata.insert(0,'id',range(0,data.shape[0]))\ndata\nds = data[['date','title','text','link']]\nds.shape\nds = ds.dropna()\nds = ds.drop_duplicates(subset=None, keep='first', inplace=False)\nds.insert(0,'id',range(0,ds.shape[0]))\nds.shape\nds.head()\n\"\"\"\n## Step 2: Encoding your data\n### There are a number of popular encoding schemes but the main ones are:\n\n* ### One-hot encoding\n* ### Term frequency\u2013inverse document frequency (TF-IDF) encoding\n* ### Word embeddings\n### For our example, we will use the term frequency\u2013inverse document frequency (TF-IDF) encoding scheme.\n\"\"\"\n\"\"\"\n![1_3Ig7VSgscBzXaYa0Q-UM1w.png](attachment:1_3Ig7VSgscBzXaYa0Q-UM1w.png)\n\"\"\"\n\"\"\"\n\n### The advantage of TF-IDF encoding is that it will weigh a term (a tag for a movie in our example) according to the importance of the term within the document: The more frequently the term appears, the larger its weight will be. At the same time, it weighs the item inversely to the frequency of this term across the entire dataset: It will emphasise terms that are relatively rare occurrences in the general dataset but of importance to the specific content at hand.\n\"\"\"\n\"\"\"\n## Importing Liberaries\n\"\"\"\nfrom nltk.corpus import stopwords\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk.tokenize import RegexpTokenizer\nimport re\nimport string\nimport random\n\"\"\"\n## Applying all the functions in text column and storing as a cleaned_desc\n\"\"\"\n# Function for removing NonAscii characters\n#def _removeNonAscii(s):\n#    return \"\".join(i for i in s if  ord(i)<128)\n\n# Function for converting into lower case\ndef make_lower_case(text):\n    return text.lower()\n\n# Function for removing stop words\ndef remove_stop_words(text):\n    text = text.split()\n    stops = set(stopwords.words(\"english\"))\n    text = [w for w in text if not w in stops]\n    texts = [w for w in text if w.isalpha()]\n    texts = \" \".join(texts)\n    return texts\n\n# Function for removing punctuation\ndef remove_punctuation(text):\n    tokenizer = RegexpTokenizer(r'\\w+')\n    text = tokenizer.tokenize(text)\n    text = \" \".join(text)\n    return text\n\n# Function for removing the html tags\ndef remove_html(text):\n    html_pattern = re.compile('<.*?>')\n    return html_pattern.sub(r'', text)\n\n# Applying all the functions in description and storing as a cleaned_desc\n#ds['cleaned_desc'] = ds['text'].apply(_removeNonAscii)\nds['cleaned_desc'] = ds['text'].apply(func = make_lower_case)\nds['cleaned_desc'] = ds.cleaned_desc.apply(func = remove_stop_words)\nds['cleaned_desc'] = ds.cleaned_desc.apply(func=remove_punctuation)\nds['cleaned_desc'] = ds.cleaned_desc.apply(func=remove_html)\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\n## analyzer -- to select individual words# default \n## max_df[0.0,1.0] - used to ignore words with frequency more than 0.8 these words can be useless words as these words may appear only once and may not have a significant meaning\n## min_df -- similar reason as the above one. \n## use_idfbool, default=True  -- Enable inverse-document-frequency reweighting.\n\ntf = TfidfVectorizer(analyzer='word',stop_words='english',max_df=0.8,min_df=0.0,use_idf=True,ngram_range=(1,3))\ntfidf_matrix = tf.fit_transform(ds['cleaned_desc'])\n\"\"\"\n### This is how a tfidf vector looks like. \n\"\"\"\npd.DataFrame(tfidf_matrix.toarray(), columns=tf.get_feature_names())\n\"\"\"\n### <i>Now, we have a representation of every item in terms of its description. Next, we need to calculate the relevance or similarity of one document to another.<\/i>\n\"\"\"\n\"\"\"\n## Vector Space Model\n* ### In this model, each item is stored as a vector of its attributes (which are also vectors) in an n-dimensional space, and the angles between the vectors are calculated to determine the similarity between the vectors.\n\n\"\"\"\n\"\"\"\n![1_LWoRop9T6hC7zhi32UxhCQ.png](attachment:1_LWoRop9T6hC7zhi32UxhCQ.png)\n\"\"\"\n\"\"\"\n* ### The method of calculating the user\u2019s likes \/ dislikes \/ measures is calculated by taking the cosine of the angle between the user profile vector (Ui ) and the document vector; or in our case, the angle between two document vectors.\n* ### The ultimate reason behind using cosine is that the value of cosine will increase as the angle between vectors with decreases, which signifies more similarity.\n\"\"\"\n\"\"\"\n![1_Q4xQoV8k_7S7xB-NfvFdrw.png](attachment:1_Q4xQoV8k_7S7xB-NfvFdrw.png)\n\"\"\"\ncosine_similarities = linear_kernel(tfidf_matrix, tfidf_matrix)\nresults = {}\nfor idx, row in ds.iterrows():\n    similar_indices = cosine_similarities[idx].argsort()[:-100:-1]\n    similar_items = [(cosine_similarities[idx][i], ds['id'][i]) for i in similar_indices]\n    results[row['id']] = similar_items[1:]\nprint('done!')\n\nsimilar_indices[:100]\n\ndef item(id):\n    return ds.loc[ds['id'] == id]['title'].tolist()[0].split(' - ')[0]\n\n# Just reads the results out of the dictionary.\ndef recommend(item_id, num):\n    print(\"Recommending \" + str(num) + \" products similar to \" + item(item_id) + \"...\")\n    print(\"-------\")\n    recs = results[item_id][:num]\n    for rec in recs:\n        print(\"Recommended : \" + item(rec[1]) + \" (score:\" + str(rec[0]) + \")\",end='\\n\\n')\n\nrecommend(item_id=10, num=15)\ncosine_similarities\n\"\"\"\n### A recommender system has to decide between two methods for information delivery when providing the user with recommendations:\n* ### Exploitation. The system chooses documents similar to those for which the user has already expressed a preference.\n* ### Exploration. The system chooses documents where the user profile does not provide evidence to predict the user\u2019s reaction.<br><br>\n### <b>We are going to use <u>Exploitation method <\/u><\/b>\n\"\"\"\ndef recomendation(idx,no_of_news_article):\n    #get similarity values with other articles\n    similarity_score = list(enumerate(cosine_similarities[idx]))\n    similarity_score = sorted(similarity_score, key=lambda x: x[1], reverse=True)\n    # Get the scores of the n most similar news articles. Ignore the first movie.\n    similarity_score = similarity_score[1:no_of_news_article+1]\n    \n    print(\"Article Read -- \" + ds['title'].iloc[idx] +\" link --\"+ ds['link'].iloc[idx])\n    print(\" ---------------------------------------------------------- \")\n    news_indices = [i[0] for i in similarity_score]\n    for i in range(len(news_indices)):\n        print(\"Recomendation \"+ str(i+1)+\" --- \" +str(news_indices[i])+\"(IDX)  \"+str(ds['date'].iloc[news_indices[i]])+\" : \"+\n              ds['title'].iloc[news_indices[i]] +\" || Link --\"+ ds['link'].iloc[news_indices[i]] +\" score -- \"+ str(similarity_score[i][1]))\n        print()\n\"\"\"\n## Test 1 - when min_df=0.2 shape 1496 rows \u00d7 31 columns\n\"\"\"\nidx=3  #min_df=0.2 shape 1496 rows \u00d7 31 columns\nno_of_news_article=10\nrecomendation(idx,no_of_news_article)\n\"\"\"\n## Test 2 - when min_df=0.1 shape 1496 rows \u00d7 144 columns\n\"\"\"\nidx=3   #min_df=0.1  shape 1496 rows \u00d7 144 columns\nno_of_news_article=10\nrecomendation(idx,no_of_news_article)\n\"\"\"\n## Test 3 - when min_df=0.0 shape 1496 rows \u00d7 588777 columns\n\"\"\"\nidx=3  #min_df=0.0 shape 1496 rows \u00d7 588777 columns\nno_of_news_article=10\nrecomendation(idx,no_of_news_article)\n\"\"\"\n### So When the size of the corpous is very large the similarity score decreases but predicitions are much better. And the score decreses because of regulersation there for nid_df - 0.0 was better in this case. \n### However this is not true every time. \n\"\"\"\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n## analyzer -- to select individual words# default \n## max_df[0.0,1.0] - used to ignore words with frequency more than 0.8 these words can be useless words as these words may appear only once and may not have a significant meaning\n## min_df -- similar reason as the above one. \n## use_idfbool, default=True  -- Enable inverse-document-frequency reweighting.\n\ntf = TfidfVectorizer(analyzer='word',stop_words='english',max_df=0.8,min_df=0.0,use_idf=True,ngram_range=(1,3))\ntfidf_matrix = tf.fit_transform(ds['cleaned_desc'])\ncosine_similarities = cosine_similarity(tfidf_matrix, tfidf_matrix)\nidx=3  #min_df=0.0 shape 1496 rows \u00d7 31 columns\nno_of_news_article=10\nrecomendation(idx,no_of_news_article)\n\"\"\"\n## So what have we done till now -- \n* ### We have implemented vector space method to map the documents where the tfidf -> first maps doc X words matrix .. \n* ### Then  we have found cosine similarity between the documents similar to  Singular Vector Decomposition where we have found the relation of documents with other's on the bases of text the other documents have and recommended the top n articles he may like\n\"\"\"\n\"\"\"\n## Conclusion -- \n\n### We have succesfully created a recomendation system but this may not the that efficient for a very large corpous thus we will try to implement a probablistic model for the same.\n\n### Note: we wil not be using Latent semantic Analysis as we do not want to find any kighlighting words in the corpous rather find a relation between one so instead of LSA we are going  for topic modelling for a change to see if it works.. \n### We are goning to see LDA and LSH for this process.\n\"\"\"\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n## analyzer -- to select individual words# default \n## max_df[0.0,1.0] - used to ignore words with frequency more than 0.8 these words can be useless words as these words may appear only once and may not have a significant meaning\n## min_df -- similar reason as the above one. \n## use_idfbool, default=True  -- Enable inverse-document-frequency re-weighting.\n\ntf = TfidfVectorizer(analyzer='word',stop_words='english',max_df=0.8,min_df=0.1,use_idf=False,ngram_range=(1,3))\ntfidf_matrix = tf.fit_transform(ds['cleaned_desc'])\ncosine_similarities = cosine_similarity(tfidf_matrix, tfidf_matrix)\npd.DataFrame(tfidf_matrix.toarray(), columns=tf.get_feature_names())\nidx=3  #min_df=0.0 shape 1496 rows \u00d7 31 columns\nno_of_news_article=10\nrecomendation(idx,no_of_news_article)\n\n* seeing a significant change in the similarity score as it has not been L2 regulerised. \nfrom sklearn.cluster import KMeans\n\nnum_clusters = 5\n\nkm = KMeans(n_clusters=num_clusters)\n\n%time km.fit(tfidf_matrix)\n\nclusters = km.labels_.tolist()\nds.insert(2,'cluster',clusters)\n\n#ds.insert(0,'id',range(0,ds.shape[0]))\nds.head()\nds['cluster'].value_counts()\nfrom scipy.cluster.hierarchy import ward, dendrogram\nfrom sklearn.metrics.pairwise import cosine_similarity\ndist = 1 - cosine_similarity(tfidf_matrix)\n\nlinkage_matrix = ward(dist) #define the linkage_matrix using ward clustering pre-computed distances\n\nfig, ax = plt.subplots(figsize=(15, 200)) # set size\nax = dendrogram(linkage_matrix)\n\nplt.tick_params(\\\n    axis= 'x',          # changes apply to the x-axis\n    which='both',      # both major and minor ticks are affected\n    bottom='off',      # ticks along the bottom edge are off\n    top='off',         # ticks along the top edge are off\n    labelbottom='off',\n               width=10000)\n\nplt.tight_layout() #show plot with tight layout\n\n## Implementing Topic modelling -- LSH ","meta":"{'source': 'AI4Code', 'id': '002aed65301beb'}"}
{"id":"123298","text":"\"\"\"\nUpsample\/downsample functions based on Sckit-image work weird for me. (don't know how to use mode='edge', 'constant')\n\nFollowings are numpy-based upsample\/downsample functions which are compatible with those in other common kernels.\n\n1. Preparation\n1. Result\n    1. Numpy.pad\n    1. Sckit-image\n\"\"\"\n\"\"\"\n# 1. Preparation\n\"\"\"\n\"\"\"\n## Import libraries\n\"\"\"\nimport os\nimport sys\nimport random\n\nimport pandas as pd\nimport numpy as np\n\n%matplotlib inline\n\nimport cv2\nfrom tqdm import tqdm_notebook, tnrange\nfrom itertools import chain\nfrom skimage.io import imread, imshow, concatenate_images\nfrom skimage.transform import resize\nfrom skimage.morphology import label\n\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\nimport gc\ngc.collect()\n# Set some parameters\nim_width = 101\nim_height = 101\nim_chan = 1\nbasicpath = '..\/input\/'\npath_train = basicpath + 'train\/'\npath_test = basicpath + 'test\/'\n\npath_train_images = path_train + 'images\/'\npath_train_masks = path_train + 'masks\/'\npath_test_images = path_test + 'images\/'\nimg_size_ori = 101\nimg_size_target = 128\n\"\"\"\n## Load images\n\"\"\"\n# Loading of training\/testing ids and depths\n\ntrain_df = pd.read_csv(basicpath+\"train.csv\", index_col=\"id\", usecols=[0])\ndepths_df = pd.read_csv(basicpath+\"depths.csv\", index_col=\"id\")\ntrain_df = train_df.join(depths_df)\ntest_df = depths_df[~depths_df.index.isin(train_df.index)]\n\nlen(train_df)\ntrain_df[\"images\"] = [np.array(load_img(path_train_images+\"{}.png\".format(idx), grayscale=True)) \/ 255 for idx in tqdm_notebook(train_df.index)]\ntrain_df[\"masks\"] = [np.array(load_img(path_train_masks+\"{}.png\".format(idx), grayscale=True)) \/ 255 for idx in tqdm_notebook(train_df.index)]\n\"\"\"\n## Define a showing image function\n\"\"\"\nimport cv2\nfrom IPython.display import display, Image\ndef cvshow(image, format='.png', rate=255 ):\n    decoded_bytes = cv2.imencode(format, image*rate)[1].tobytes()\n    display(Image(data=decoded_bytes))\n    return\n\"\"\"\n# 2. Results\n\"\"\"\n\"\"\"\n## A. Numpy.pad\n\"\"\"\n\"\"\"\n### constant\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 128\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return np.pad(img, [(img_size_target-img_size_ori)\/\/2,(img_size_target-img_size_ori)-(img_size_target-img_size_ori)\/\/2], 'constant', constant_values=(0,0))\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return img[(img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2, (img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2]\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))\n\"\"\"\n### edge\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 128\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return np.pad(img, [(img_size_target-img_size_ori)\/\/2,(img_size_target-img_size_ori)-(img_size_target-img_size_ori)\/\/2], 'edge')\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return img[(img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2, (img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2]\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))\n\"\"\"\n### reflect\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 128\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return np.pad(img, [(img_size_target-img_size_ori)\/\/2,(img_size_target-img_size_ori)-(img_size_target-img_size_ori)\/\/2], 'reflect')\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return img[(img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2, (img_size_target-img_size_ori)\/\/2:img_size_ori+(img_size_target-img_size_ori)\/\/2]\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))\n\"\"\"\n# B. sckit-image\n\"\"\"\n\"\"\"\n### constant\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 128\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_target, img_size_target), cval = 0, mode='constant', preserve_range=True)\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_ori, img_size_ori), mode='constant', preserve_range=True)\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, 128, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))\n\"\"\"\n\n### edge\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 128\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_target, img_size_target), mode='edge', preserve_range=True)\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_ori, img_size_ori), mode='edge', preserve_range=True)\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, 128, 128, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))\n\"\"\"\n### refrect\n\"\"\"\nimg_size_ori = 101\nimg_size_target = 200\n\ndef upsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_target, img_size_target), order=0, mode='reflect', preserve_range=True)\n    \ndef downsample(img):\n    if img_size_ori == img_size_target:\n        return img\n    return resize(img, (img_size_ori, img_size_ori), order=0, mode='reflect', preserve_range=True)\norig_img = np.squeeze(np.array(train_df.images.tolist()).reshape(-1, 101, 101, 1)[100, :, :, :])\ncvshow(orig_img)\nedge_mag_img = np.squeeze(np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 1)[100, :, :, :])\ncvshow(edge_mag_img)\ncvshow(downsample(edge_mag_img))","meta":"{'source': 'AI4Code', 'id': 'e2b1bbcce5845c'}"}
{"id":"25541","text":"# import the libraries\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\n#Load the dataset\ndf = pd.read_csv(r'..\/input\/ntt-data-global-ai-challenge-06-2020\/COVID-19_and_Price_dataset.csv')\n#get the shape of the data\ndf.shape\n#get information about the dataframe\ndf.info()\ndf['Date'] = pd.to_datetime(df['Date'])\n#Visuvalize the relation between oil pirce and Worlt total cases\nx=df['Price']\ny=df['World_total_cases']\nplt.figure(figsize = (20,10));\nplt.plot(x,y,'g--')\nplt.title('Oil Price  Vs  World_total_cases')\nplt.xlabel('Oil Price')\nplt.ylabel('Covid_total_cases')\n#get the location of the World_total_cases\ndf.columns.get_loc(\"World_total_cases\")\n\n#selecting the last 5 columns from dataframe\ncorr_df=df[df.columns[[841,842,843,844,849]]]\n# Explore the top 5 rows of the dataset\ncorr_df.head()\n#Finding the coorelation\ncorrelation=corr_df.corr()\nimport seaborn as sns\nf, ax = plt.subplots(figsize=(10, 8))\nsns.heatmap(correlation,vmin=0, vmax=1, annot=True, fmt=\"g\", cmap='coolwarm')\ncols = [0,841,842,843,844,849]\ndata= df[df.columns[cols]]\n#Print the top 5 rows\ndata.head()\ndata=data.set_index('Date')\n#Separate the target variable and rest of the variables using .iloc to subset the data.\nX = data.iloc[:,:-1]\ny=data.iloc[:,-1]\n#convert the dataset into an optimized data structure called Dmatrix that XGBoost supports\ndata_dmatrix = xgb.DMatrix(data=X,label=y)\n#create the train and test set for cross-validation\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)\n# instantiate an XGBoost regressor object by calling the XGBRegressor()\nxg_reg = xgb.XGBRegressor(objective ='reg:linear', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = 5, alpha = 10, n_estimators = 10)\n#Fit the regressor to the training set and make predictions on the test set\nxg_reg.fit(X_train,y_train)\npreds = xg_reg.predict(X_test)\n#Compute the rmse by invoking the mean_sqaured_error function from sklearn's metrics module.\nrmse = np.sqrt(mean_squared_error(y_test, preds))\nprint(\"RMSE: %f\" % (rmse))\n\"\"\"\nRMSE for the price prediction came out to be around 17.16645\n\"\"\"\n#k-fold Cross Validation using XGBoost\nparams = {\"objective\":\"reg:linear\",'colsample_bytree': 0.3,'learning_rate': 0.1,'max_depth': 5, 'alpha': 10}\ncv_results = xgb.cv(dtrain=data_dmatrix, params=params, nfold=3,num_boost_round=50,early_stopping_rounds=10,metrics=\"rmse\", as_pandas=True, seed=123)\n\ncv_results.head()\nprint((cv_results[\"test-rmse-mean\"]).tail(1))\n\"\"\"\n# **RMSE for the price prediction has reduced as compared to last time and came out to be around 0.993286**\n\"\"\"\n#Visualize Feature Importance (features are ordered according to how many times they appear)\nimport matplotlib.pyplot as plt\nxgb.plot_importance(xg_reg)\nplt.rcParams['figure.figsize'] = [5, 5]\nplt.show()","meta":"{'source': 'AI4Code', 'id': '2f04c97e1b306b'}"}
{"id":"120203","text":"# 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 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\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy .stats import norm \n\ndf = pd.read_csv('..\/input\/preprocess-choc\/dfn.csv')\ndf\n%matplotlib inline\nplt.hist(df.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nplt.show()\nfrom scipy.stats import norm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.hist(df.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nrng=np.arange(df.rating.min(),df.rating.max(),0.1)\nplt.plot(rng,norm.pdf(rng,df.rating.mean(),df.rating.std()))\nplt.show()\n#matplotlib. rcParams['figure.figsize']=(10,6)\n\n#i dont know why the bell curve isnt plotting in Kaggle(was plotting in JN),Trouble shoot and let me know\n\"\"\"\n# 1.MinMax method\n\"\"\"\n\"\"\"\n\n\n#max rating\ndf.rating.max()\n#mean rating\ndf.rating.mean()\n#std. deviation of rating\ndf.rating.std()\n\"\"\"\n#max rating df.rating.max()\n\n#mean rating df.rating.mean()\n\n#std. deviation of rating df.rating.std()\n\n#so my upper limit will be my mean value plus 3 sigma\nupper_limit=df.rating.mean()+3*df.rating.std()\nupper_limit\n#my lowar limit will be my mean - 3 sigma\nlowar_limit=df.rating.mean()-3*df.rating.std()\nlowar_limit\n#now that my outliers are defined, i want to see what are my outliers\ndf[(df.rating>upper_limit)|(df.rating<lowar_limit)]\n#now we will visualise the good data\nnew_data=df[(df.rating<upper_limit)& (df.rating>lowar_limit)]\nnew_data\n#shape of our new data\nnew_data.shape\n#shape of our outliers\ndf.shape[0]-new_data.shape[0]\n\"\"\"\n# **2. Zscore**\n\"\"\"\n\"\"\"\n# Now we will try to remove the outliers by z scores\n# z score tells how many standard deviations  away a data point is\n# in our case mean is 3.198 and std deviation is 0.434\n# so our Z SCORE for datapoint 4.5 is 4.5-3.198(mean)\/0.434(std)= 1.847\n\"\"\"\n#now we will calculate the z score of all our datapoints and display in a dataframe\ndf['zscore']=(df.rating-df.rating.mean())\/df.rating.std()\ndf\n![z.png]\n#figuring out all the datapoints more than 3\ndf[df['zscore']>3]\n#figuring out all the datapoints less than 3\ndf[df['zscore']<-3]\n#displaying the outliers with respect to the zscores\ndf[(df.zscore<-3)|(df.zscore>3)]\nnew_data_1=df[(df.zscore>-3)& (df.zscore<3)]\nnew_data_1\nfigure=df.boxplot(column=\"rating\", figsize=(20,20))\nfigure=new_data_1.boxplot(column=\"rating\", figsize=(20,20))\nfrom scipy.stats import norm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.hist(df.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nrng=np.arange(df.rating.min(),df.rating.max(),0.1)\nplt.plot(rng,norm.pdf(rng,df.rating.mean(),df.rating.std()))\nplt.show()\n#matplotlib. rcParams['figure.figsize']=(10,6)\n\n#i dont know why the bell curve isnt plotting in Kaggle(was plotting in JN),Trouble shoot and let me know\nfrom scipy.stats import norm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.hist(new_data_1.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nrng=np.arange(new_data_1.rating.min(),new_data_1.rating.max(),0.1)\nplt.plot(rng,norm.pdf(rng,new_data_1.rating.mean(),new_data_1.rating.std()))\nplt.show()\n#matplotlib. rcParams['figure.figsize']=(10,6)\n\n#i dont know why the bell curve isnt plotting in Kaggle(was plotting in JN),Trouble shoot and let me know\n\"\"\"\n# **3.Inter Quartile Range**\n\"\"\"\ndf=df.drop(['zscore'],axis=1)\ndf.describe()\nQ1=df.rating.quantile(0.25)\nQ3=df.rating.quantile(0.75)\nQ1,Q3\n#WHICH MEANS THAT Q1 CORRESPONDS TO 25% OF ALL THE HEIGHT DISTRIBUTION IS BELOW 3.0\n#Q3 CORRESPONDS TO 75% OF ALL THE HEIGHT DISTRIBUTION IS BELOW 3.5\n#NOW WE WILL CALCULATE THE IQR\nIQR=Q3-Q1\nIQR\n#NOW WE WILL DEFINE THE UPPER LIMITS AND LOWAR LIMITS\nLOWAR_LIMIT=Q1-1.5*IQR\nUPPER_LIMIT=Q3+1.5*IQR\nLOWAR_LIMIT,UPPER_LIMIT\n#NOW WE SHALL DISPLY THE OUTLIERS rating\ndf[(df.rating<LOWAR_LIMIT)|(df.rating>UPPER_LIMIT)]\n#NOW WE WILL DISPLAY THE REMAINING SAMPLES ARE WITHIN THE RANGE\nWithout_outliers_data = df[(df.rating>LOWAR_LIMIT)&(df.rating<UPPER_LIMIT)]\nfigure=df.boxplot(column=\"rating\", figsize=(20,20))\n\nfigure=Without_outliers_data.boxplot(column=\"rating\", figsize=(20,20))\nfrom scipy.stats import norm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.hist(df.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nrng=np.arange(df.rating.min(),df.rating.max(),0.1)\nplt.plot(rng,norm.pdf(rng,df.rating.mean(),df.rating.std()))\nplt.show()\n#matplotlib. rcParams['figure.figsize']=(10,6)\n\n#i dont know why the bell curve isnt plotting in Kaggle(was plotting in JN),Trouble shoot and let me know\nfrom scipy.stats import norm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.hist(Without_outliers_data.rating,bins=20,rwidth=0.8)\nplt.xlabel('rating')\nplt.ylabel('count')\nrng=np.arange(Without_outliers_data.rating.min(),df.rating.max(),0.1)\nplt.plot(rng,norm.pdf(rng,Without_outliers_data.rating.mean(),Without_outliers_data.rating.std()))\nplt.show()\n#matplotlib. rcParams['figure.figsize']=(10,6)\n\n#i dont know why the bell curve isnt plotting in Kaggle(was plotting in JN),Trouble shoot and let me know\ndf_enc = pd.read_csv('..\/input\/preprocess-choc\/10 best RD_Feature')\ndf_enc\na = df_enc.loc[:,~df_enc.columns.duplicated()]\na\n\nb = a.drop('rating', axis = 1)\nX = b.iloc[:,0:11]  \ny = a.iloc[:,2]    \n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train,y_train, X_test,y_test = train_test_split(X, y, test_size=0.3)\ny\n\"\"\"\n# 4. Isolation forest method\n\"\"\"\n\nfrom scipy import stats\n\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors import LocalOutlierFactor\n\nimport matplotlib.dates as md\nfrom scipy.stats import norm\n%matplotlib inline \nimport seaborn as sns \nsns.set_style(\"whitegrid\") #possible choices: white, dark, whitegrid, darkgrid, ticks\n\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nfrom plotly import tools\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\npd.set_option('float_format', '{:f}'.format)\npd.set_option('max_columns',250)\npd.set_option('max_rows',150)\nclf = IsolationForest(max_samples='auto', random_state = 1, contamination= 0.02)\npreds = clf.fit_predict(X)\ndf['isoletionForest_outliers'] = preds\ndf['isoletionForest_outliers'] = df['isoletionForest_outliers'].astype(str)\ndf['isoletionForest_scores'] = clf.decision_function(X)\nprint(df['isoletionForest_outliers'].value_counts())\n\ndf[152:156]\n!pip install eif\nimport eif as iso\nfig, ax = plt.subplots(figsize=(20, 7))\nax.set_title('Distribution of Extended Isolation Scores', fontsize = 15, loc='center')\nsns.distplot(df['isoletionForest_scores'],color='red',label='if',hist_kws = {\"alpha\": 0.5});\n\n\nfig, ax = plt.subplots(figsize=(30, 7))\nax.set_title('Extended Outlier Factor Scores Outlier Detection', fontsize = 15, loc='center')\n\nplt.scatter(X.iloc[:, 0], X.iloc[:, 1], color='g', s=3., label='Data points')\nradius = (df['isoletionForest_scores'].max() - df['isoletionForest_scores']) \/ (df['isoletionForest_scores'].max() - df['isoletionForest_scores'].min())\nplt.scatter(X.iloc[:, 0], X.iloc[:, 1], s=2000 * radius, edgecolors='r', facecolors='none', label='Outlier scores')\nplt.axis('tight')\nlegend = plt.legend(loc='upper left')\nlegend.legendHandles[0]._sizes = [10]\nlegend.legendHandles[1]._sizes = [20]\nplt.show();\n\n\n\n\nclf = LocalOutlierFactor(n_neighbors=11)\ny_pred = clf.fit_predict(X)\n\ndf['localOutlierFactor_outliers'] = y_pred.astype(str)\nprint(df['localOutlierFactor_outliers'].value_counts())\ndf['localOutlierFactor_scores'] = clf.negative_outlier_factor_\n\n\n\"\"\"\n# 5. Local outliers method\n\"\"\"\nfig, ax = plt.subplots(figsize=(20, 7))\nax.set_title('Distribution of Local Outlier Factor Scores', fontsize = 15, loc='center')\nsns.distplot(df['localOutlierFactor_scores'],color='red',label='eif',hist_kws = {\"alpha\": 0.5});\n\n\n\nfig, ax = plt.subplots(figsize=(30, 7))\nax.set_title('Local Outlier Factor Scores Outlier Detection', fontsize = 15, loc='center')\n\nplt.scatter(X.iloc[:, 0], X.iloc[:, 1], color='g', s=3., label='Data points')\nradius = (df['localOutlierFactor_scores'].max() - df['localOutlierFactor_scores']) \/ (df['localOutlierFactor_scores'].max() - df['localOutlierFactor_scores'].min())\nplt.scatter(X.iloc[:, 0], X.iloc[:, 1], s=2000 * radius, edgecolors='r', facecolors='none', label='Outlier scores')\nplt.axis('tight')\nlegend = plt.legend(loc='upper left')\nlegend.legendHandles[0]._sizes = [10]\nlegend.legendHandles[1]._sizes = [20]\nplt.show();\n\n","meta":"{'source': 'AI4Code', 'id': 'dd196a059c0f46'}"}
{"id":"119451","text":"\"\"\"\n<h1><center><font size = \"6\">**Default of Credit Card Clients - Predictive Models**<\/font><\/center><\/h1>\n<a id='0'><font size = \"5\">**Content**<\/font><\/a>\n- <a href='#1'>Introduction<\/a>\n- <a href='#2'>Load Packages and Data<\/a>\n- <a href='#3'>Check and Examination of the Data<\/a>\n    - <a href='#31'>Overview the data<\/a>\n    - <a href='#32'>Check Data Unbalance<\/a>\n    - <a href='#33'>Data Conversion<\/a>\n- <a href='#4'>Data Exploration and Data Visualization<\/a>\n- <a href='#5'>Predictive models<\/a>\n    - <a href='#51'>Random Forrest Classifier<\/a> \n    - <a href='#52'>Decision Tree Classifier<\/a>\n    - <a href='#53'>KNN Classifier<\/a> \n    - <a href='#54'>Adaboost Classifier<\/a> \n    - <a href='#55'>Roc-Auc Curve<\/a>\n    - <a href='#56'>Cross Validation for Algorithms<\/a>\n    - <a href='#57'>Comparison of Algorithms<\/a>\n    - <a href='#58'>Change the Features Used for Algorithm<\/a>\n- <a href='#6'>Conclusions<\/a>\n- <a href='#7'>References<\/a>\n\"\"\"\n\"\"\"\n# <a id=\"1\">Introduction<\/a>  \n\n## Preface\nFirst of all, I would like to thank my friend ***H\u00fclya Nur Ayta\u00e7***, who helped me with this project. My goal in this project is to examine the characteristics of people who have not paid or have not paid off their loan debt based on this data. During this review, I will use data visualization, machine learning and similar tools. Since this problem is a classification problem, I will use different algorithms -they are available for classification problem- for create model. I will try finding that optimal parameters for these algorithms. Finally, I will compare that achievement scores of algorithms and I will have an idea for this problem.\n\n## Information\nThis dataset contains information on default payments, demographic factors, credit data, history of payment, and bill statements of credit card clients in Taiwan from ***April 2005*** to ***September 2005***. \n\n## Inspiration and Idea\nSome ideas for exploration:\n\n* How does the probability of default payment vary by categories of different demographic variables?\n* Which variables are the strongest predictors of default payment?\n\n## Content of Data\n* **ID**: ID of each client\n* **LIMIT_BAL**: Amount of given credit in NT dollars (includes individual and family\/supplementary credit\n* **SEX**: Gender (1=male, 2=female)\n* **EDUCATION**: (0=?, 1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown)\n* **MARRIAGE**: Marital status (0=?,1=married, 2=single, 3=others)\n* **AGE**: Age in years\n* **PAY_0**: Repayment status in September, 2005 (-1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above)\n* **PAY_2**: Repayment status in August, 2005 (scale same as above)\n* **PAY_3**: Repayment status in July, 2005 (scale same as above)\n* **PAY_4**: Repayment status in June, 2005 (scale same as above)\n* **PAY_5**: Repayment status in May, 2005 (scale same as above)\n* **PAY_6**: Repayment status in April, 2005 (scale same as above)\n* **BILL_AMT1**: Amount of bill statement in September, 2005 (NT dollar)\n* **BILL_AMT2**: Amount of bill statement in August, 2005 (NT dollar)\n* **BILL_AMT3**: Amount of bill statement in July, 2005 (NT dollar)\n* **BILL_AMT4**: Amount of bill statement in June, 2005 (NT dollar)\n* **BILL_AMT5**: Amount of bill statement in May, 2005 (NT dollar)\n* **BILL_AMT6**: Amount of bill statement in April, 2005 (NT dollar)\n* **PAY_AMT1**: Amount of previous payment in September, 2005 (NT dollar)\n* **PAY_AMT2**: Amount of previous payment in August, 2005 (NT dollar)\n* **PAY_AMT3**: Amount of previous payment in July, 2005 (NT dollar)\n* **PAY_AMT4**: Amount of previous payment in June, 2005 (NT dollar)\n* **PAY_AMT5**: Amount of previous payment in May, 2005 (NT dollar)\n* **PAY_AMT6**: Amount of previous payment in April, 2005 (NT dollar)\n* **default.payment.next.month**: Default payment (1=yes, 0=no)\n\"\"\"\n\"\"\"\n# <a id=\"2\">Load Packages and Data<\/a>\n## Load Packages\n\"\"\"\n# 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 in \nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score,roc_auc_score,accuracy_score,roc_curve\nimport itertools\nfrom sklearn.model_selection import GridSearchCV\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n## Read the Data\n\"\"\"\ndata = pd.read_csv('..\/input\/default-of-credit-card-clients-dataset\/UCI_Credit_Card.csv')\n\"\"\"\n## Properties of Dataset\n\"\"\"\ndata.columns\ndata.shape\ndata.head(10)\ndata.info()\n\"\"\"\nWe see that there are no empty values here. But as an alternative, we can look at it like this.\n\"\"\"\ndata.isnull().sum().sort_values(ascending=False)\n\"\"\"\n# <a id=\"3\">Check and Examination of Data<\/a>\n## <a id=\"31\">Overview the Data<\/a>\nIn this section, I will both rename and assign values. As state below, I find a few missing or suspicious data.  Fortunately, I can assignment because that data is so scarce that it can be ignored.\n* In the Education attribute, 0-4-5-6 numbers value assigned as a 4.\n\"\"\"\ndata.EDUCATION.value_counts()\n\"\"\"\n* In the Marriage attribute, the value 0 means unknown and the value 3 means other. Therefore, the value 0 assigned as 3.\n\"\"\"\ndata.MARRIAGE.value_counts()\n\"\"\"\nIn addition, attributes need to be renamed. For example,\n* default.payment.next.month ---> def_pay\n* PAY_0 ---> PAY_1\n\"\"\"\ndata = data.rename(columns={'default.payment.next.month': 'def_pay', \n                            'PAY_0': 'PAY_1'})\nfill = (data.EDUCATION == 5) | (data.EDUCATION == 6) | (data.EDUCATION == 0)\ndata.loc[fill, 'EDUCATION'] = 4\ndata.loc[data.MARRIAGE == 0, 'MARRIAGE'] = 3\ndata.columns\ndata.EDUCATION.value_counts()\ndata.MARRIAGE.value_counts()\n\"\"\"\n## <a id=\"32\">Check Data Unbalanced<\/a>\nIn this section, statistical analysis and interpretation of attributes will be performed.\n\n 1. Firstly, I want to learn about the demographic structure and measure its imbalance.\n\"\"\"\ndata.EDUCATION.describe()\ndata.SEX.describe()\ndata.MARRIAGE.describe()\ndata.AGE.describe()\n\"\"\"\nAccording to this information, most person who in this dataset, graduate of university, single or women. In next sections, I will examine different situations by each other of these attributes. I will be searching effect of these attributes against default payment. Instead of using the age feature in this way, I could use it more intermittently.\n\n\"\"\"\n\"\"\"\n 2. Now, I research on payment and bill. Actually, If we think as the period, in April 2005 between September 2005, we have sequentially periodically previous payment, bill amount and payment. In contrast, I don't know from previous period to April 2005.\n\"\"\"\ndata.PAY_1.describe()\ndata.PAY_2.describe()\ndata.PAY_3.describe()\ndata.PAY_4.describe()\ndata.PAY_5.describe()\ndata.PAY_6.describe()\ndata.BILL_AMT1.describe()\ndata.BILL_AMT2.describe()\ndata.BILL_AMT3.describe()\ndata.BILL_AMT4.describe()\ndata.BILL_AMT5.describe()\ndata.BILL_AMT6.describe()\ndata.PAY_AMT1.describe()\ndata.PAY_AMT2.describe()\ndata.PAY_AMT3.describe()\ndata.PAY_AMT4.describe()\ndata.PAY_AMT5.describe()\ndata.PAY_AMT6.describe()\ndata.LIMIT_BAL.describe()\n\"\"\"\nThis statistical information, show us these attributes don't unbalanced. \n\"\"\"\n\"\"\"\n## <a id='33'>Data Conversion<\/a>\nIn this section, I will look for relationships to reach our target question by creating new data attributes. \nI create a function called <i>formgroup<\/i> to group columns easily. In addition, I will make searches with combinations of other features that affect the feature I am targeting and in addition, I will apply intermittent partitioning to make better use of the age column.\n\"\"\"\ndef formgroup(Col1, Col2):\n    res = data.groupby([Col1, Col2]).size().unstack()\n    return res\ndata['SE_MA'] = data.SEX * data.MARRIAGE\nformgroup('SE_MA', 'def_pay')\ndata['SE_MA_2'] = 0\ndata.loc[((data.SEX == 1) & (data.MARRIAGE == 1)) , 'SE_MA_2'] = 1 #married man\ndata.loc[((data.SEX == 1) & (data.MARRIAGE == 2)) , 'SE_MA_2'] = 2 #single man\ndata.loc[((data.SEX == 1) & (data.MARRIAGE == 3)) , 'SE_MA_2'] = 3 #divorced man\ndata.loc[((data.SEX == 2) & (data.MARRIAGE == 1)) , 'SE_MA_2'] = 4 #married woman\ndata.loc[((data.SEX == 2) & (data.MARRIAGE == 2)) , 'SE_MA_2'] = 5 #single woman\ndata.loc[((data.SEX == 2) & (data.MARRIAGE == 3)) , 'SE_MA_2'] = 6 #divorced woman\nformgroup('SE_MA_2', 'def_pay')\ndel data['SE_MA']\ndata = data.rename(columns={'SE_MA_2': 'SE_MA'})\n\"\"\"\nI'm going to classify the ages by dividing them into 5 separate parts. The distribution of the histogram is as follows.\n\"\"\"\ndata['AgeBin'] = 0 #creates a column of 0\ndata.loc[((data['AGE'] > 20) & (data['AGE'] < 30)) , 'AgeBin'] = 1\ndata.loc[((data['AGE'] >= 30) & (data['AGE'] < 40)) , 'AgeBin'] = 2\ndata.loc[((data['AGE'] >= 40) & (data['AGE'] < 50)) , 'AgeBin'] = 3\ndata.loc[((data['AGE'] >= 50) & (data['AGE'] < 60)) , 'AgeBin'] = 4\ndata.loc[((data['AGE'] >= 60) & (data['AGE'] < 70)) , 'AgeBin'] = 5\ndata.loc[((data['AGE'] >= 70) & (data['AGE'] < 81)) , 'AgeBin'] = 6\nplt.figure()\nplt.title('20den baslayarak 10 ar 10 ar ya\u015f aral\u0131\u011f\u0131 ve say\u0131lar\u0131')\ndata.AgeBin.hist()\nplt.show()\n\"\"\"\nPayment distributions according to age ranges are as follows.\n\"\"\"\nagedefpay=formgroup('AgeBin', 'def_pay')\nprint(agedefpay)\nagesex=formgroup('AgeBin', 'SEX')\nprint(agesex)\ndata['SE_AG'] = 0\ndata.loc[((data.SEX == 1) & (data.AgeBin == 1)) , 'SE_AG'] = 1 #erkek 20'li\ndata.loc[((data.SEX == 1) & (data.AgeBin == 2)) , 'SE_AG'] = 2 #erkek 30'lu\ndata.loc[((data.SEX == 1) & (data.AgeBin == 3)) , 'SE_AG'] = 3 #erkek 40'l\u0131\ndata.loc[((data.SEX == 1) & (data.AgeBin == 4)) , 'SE_AG'] = 4 #erkek 50'li\ndata.loc[((data.SEX == 1) & (data.AgeBin == 5)) , 'SE_AG'] = 5 #erkek 60+\ndata.loc[((data.SEX == 2) & (data.AgeBin == 1)) , 'SE_AG'] = 6 #kad\u0131n 20'li\ndata.loc[((data.SEX == 2) & (data.AgeBin == 2)) , 'SE_AG'] = 7 #kad\u0131n 30'lu\ndata.loc[((data.SEX == 2) & (data.AgeBin == 3)) , 'SE_AG'] = 8 #kad\u0131n 40'l\u0131\ndata.loc[((data.SEX == 2) & (data.AgeBin == 4)) , 'SE_AG'] = 9 #kad\u0131n 50'li\ndata.loc[((data.SEX == 2) & (data.AgeBin == 5)) , 'SE_AG'] = 10 #kad\u0131n 60+\nformgroup('SE_AG', 'def_pay')\n\"\"\"\nAktif Kullan\u0131m\n\"\"\"\ndata['active_6'] = 1\ndata['active_5'] = 1\ndata['active_4'] = 1\ndata['active_3'] = 1\ndata['active_2'] = 1\ndata['active_1'] = 1\ndata.loc[((data.PAY_6 == 0) & (data.BILL_AMT6 == 0) & (data.PAY_AMT6 == 0)) , 'active_6'] = 0\ndata.loc[((data.PAY_5 == 0) & (data.BILL_AMT5 == 0) & (data.PAY_AMT5 == 0)) , 'active_5'] = 0\ndata.loc[((data.PAY_4 == 0) & (data.BILL_AMT4 == 0) & (data.PAY_AMT4 == 0)) , 'active_4'] = 0\ndata.loc[((data.PAY_3 == 0) & (data.BILL_AMT3 == 0) & (data.PAY_AMT3 == 0)) , 'active_3'] = 0\ndata.loc[((data.PAY_2 == 0) & (data.BILL_AMT2 == 0) & (data.PAY_AMT2 == 0)) , 'active_2'] = 0\ndata.loc[((data.PAY_1 == 0) & (data.BILL_AMT1 == 0) & (data.PAY_AMT1 == 0)) , 'active_1'] = 0\npd.Series([data[data.active_6 == 1].def_pay.count(),\n          data[data.active_5 == 1].def_pay.count(),\n          data[data.active_4 == 1].def_pay.count(),\n          data[data.active_3 == 1].def_pay.count(),\n          data[data.active_2 == 1].def_pay.count(),\n          data[data.active_1 == 1].def_pay.count()], [6,5,4,3,2,1])\ndata['average_5'] = ((data['BILL_AMT5'] - (data['BILL_AMT6'] - data['PAY_AMT5']))) \/ data['LIMIT_BAL']\ndata['average_4'] = (((data['BILL_AMT5'] - (data['BILL_AMT6'] - data['PAY_AMT5'])) +\n                 (data['BILL_AMT4'] - (data['BILL_AMT5'] - data['PAY_AMT4']))) \/ 2) \/ data['LIMIT_BAL']\ndata['average_3'] = (((data['BILL_AMT5'] - (data['BILL_AMT6'] - data['PAY_AMT5'])) +\n                 (data['BILL_AMT4'] - (data['BILL_AMT5'] - data['PAY_AMT4'])) +\n                 (data['BILL_AMT3'] - (data['BILL_AMT4'] - data['PAY_AMT3']))) \/ 3) \/ data['LIMIT_BAL']\ndata['average_2'] = (((data['BILL_AMT5'] - (data['BILL_AMT6'] - data['PAY_AMT5'])) +\n                 (data['BILL_AMT4'] - (data['BILL_AMT5'] - data['PAY_AMT4'])) +\n                 (data['BILL_AMT3'] - (data['BILL_AMT4'] - data['PAY_AMT3'])) +\n                 (data['BILL_AMT2'] - (data['BILL_AMT3'] - data['PAY_AMT2']))) \/ 4) \/ data['LIMIT_BAL']\ndata['average_1'] = (((data['BILL_AMT5'] - (data['BILL_AMT6'] - data['PAY_AMT5'])) +\n                 (data['BILL_AMT4'] - (data['BILL_AMT5'] - data['PAY_AMT4'])) +\n                 (data['BILL_AMT3'] - (data['BILL_AMT4'] - data['PAY_AMT3'])) +\n                 (data['BILL_AMT2'] - (data['BILL_AMT3'] - data['PAY_AMT2'])) +\n                 (data['BILL_AMT1'] - (data['BILL_AMT2'] - data['PAY_AMT1']))) \/ 5) \/ data['LIMIT_BAL']\naverage=data[['LIMIT_BAL', 'average_5', 'BILL_AMT5', 'average_4', 'BILL_AMT4','average_3', 'BILL_AMT3',\n    'average_2', 'BILL_AMT2', 'average_1', 'BILL_AMT1', 'def_pay']].sample(20)\nprint(average)\n\"\"\"\nPeriodical active use limit approximately according to the monthly period.\n\"\"\"\ndata['InvoiceLimit_6'] = (data.LIMIT_BAL - data.BILL_AMT6) \/ data.LIMIT_BAL\ndata['InvoiceLimit_5'] = (data.LIMIT_BAL - data.BILL_AMT5) \/ data.LIMIT_BAL\ndata['InvoiceLimit_4'] = (data.LIMIT_BAL - data.BILL_AMT4) \/ data.LIMIT_BAL\ndata['InvoiceLimit_3'] = (data.LIMIT_BAL - data.BILL_AMT3) \/ data.LIMIT_BAL\ndata['InvoiceLimit_2'] = (data.LIMIT_BAL - data.BILL_AMT2) \/ data.LIMIT_BAL\ndata['InvoiceLimit_1'] = (data.LIMIT_BAL - data.BILL_AMT1) \/ data.LIMIT_BAL\nInvoiceLimit=data[['InvoiceLimit_6', 'InvoiceLimit_5', 'InvoiceLimit_4', 'InvoiceLimit_3', 'InvoiceLimit_2',\n   'InvoiceLimit_1', 'def_pay']].sample(20)\nprint(InvoiceLimit)\n\"\"\"\nIn addition, I would like to separate the numerical data that shows the time of payment of payments made in the data set. This is because we can look for a new payment plan and the impact of these attributes on our target.\n\"\"\"\ndata['PAY_1_-1'] = (data.PAY_1 == -1)\ndata['PAY_1_-2'] = (data.PAY_1 == -2)\ndata['PAY_1_0'] = (data.PAY_1 == 0)\ndata['PAY_1_1'] = (data.PAY_1 == 1)\ndata['PAY_1_2'] = (data.PAY_1 == 2)\ndata['PAY_1_3'] = (data.PAY_1 == 3)\ndata['PAY_1_4'] = (data.PAY_1 == 4)\ndata['PAY_1_5'] = (data.PAY_1 == 5)\ndata['PAY_1_6'] = (data.PAY_1 == 6)\ndata['PAY_1_7'] = (data.PAY_1 == 7)\ndata['PAY_1_8'] = (data.PAY_1 == 8)\n\ndata['PAY_2_-1'] = (data.PAY_1 == -1)\ndata['PAY_2_-2'] = (data.PAY_1 == -2)\ndata['PAY_2_0'] = (data.PAY_1 == 0)\ndata['PAY_2_1'] = (data.PAY_1 == 1)\ndata['PAY_2_2'] = (data.PAY_1 == 2)\ndata['PAY_2_3'] = (data.PAY_1 == 3)\ndata['PAY_2_4'] = (data.PAY_1 == 4)\ndata['PAY_2_5'] = (data.PAY_1 == 5)\ndata['PAY_2_6'] = (data.PAY_1 == 6)\ndata['PAY_2_7'] = (data.PAY_1 == 7)\ndata['PAY_2_8'] = (data.PAY_1 == 8)\n\ndata['PAY_3_-1'] = (data.PAY_1 == -1)\ndata['PAY_3_-2'] = (data.PAY_1 == -2)\ndata['PAY_3_0'] = (data.PAY_1 == 0)\ndata['PAY_3_1'] = (data.PAY_1 == 1)\ndata['PAY_3_2'] = (data.PAY_1 == 2)\ndata['PAY_3_3'] = (data.PAY_1 == 3)\ndata['PAY_3_4'] = (data.PAY_1 == 4)\ndata['PAY_3_5'] = (data.PAY_1 == 5)\ndata['PAY_3_6'] = (data.PAY_1 == 6)\ndata['PAY_3_7'] = (data.PAY_1 == 7)\ndata['PAY_3_8'] = (data.PAY_1 == 8)\n\ndata['PAY_4_-1'] = (data.PAY_1 == -1)\ndata['PAY_4_-2'] = (data.PAY_1 == -2)\ndata['PAY_4_0'] = (data.PAY_1 == 0)\ndata['PAY_4_1'] = (data.PAY_1 == 1)\ndata['PAY_4_2'] = (data.PAY_1 == 2)\ndata['PAY_4_3'] = (data.PAY_1 == 3)\ndata['PAY_4_4'] = (data.PAY_1 == 4)\ndata['PAY_4_5'] = (data.PAY_1 == 5)\ndata['PAY_4_6'] = (data.PAY_1 == 6)\ndata['PAY_4_7'] = (data.PAY_1 == 7)\ndata['PAY_4_8'] = (data.PAY_1 == 8)\n\ndata['PAY_5_-1'] = (data.PAY_1 == -1)\ndata['PAY_5_-2'] = (data.PAY_1 == -2)\ndata['PAY_5_0'] = (data.PAY_1 == 0)\ndata['PAY_5_1'] = (data.PAY_1 == 1)\ndata['PAY_5_2'] = (data.PAY_1 == 2)\ndata['PAY_5_3'] = (data.PAY_1 == 3)\ndata['PAY_5_4'] = (data.PAY_1 == 4)\ndata['PAY_5_5'] = (data.PAY_1 == 5)\ndata['PAY_5_6'] = (data.PAY_1 == 6)\ndata['PAY_5_7'] = (data.PAY_1 == 7)\ndata['PAY_5_8'] = (data.PAY_1 == 8)\n\ndata['PAY_6_-1'] = (data.PAY_1 == -1)\ndata['PAY_6_-2'] = (data.PAY_1 == -2)\ndata['PAY_6_0'] = (data.PAY_1 == 0)\ndata['PAY_6_1'] = (data.PAY_1 == 1)\ndata['PAY_6_2'] = (data.PAY_1 == 2)\ndata['PAY_6_3'] = (data.PAY_1 == 3)\ndata['PAY_6_4'] = (data.PAY_1 == 4)\ndata['PAY_6_5'] = (data.PAY_1 == 5)\ndata['PAY_6_6'] = (data.PAY_1 == 6)\ndata['PAY_6_7'] = (data.PAY_1 == 7)\ndata['PAY_6_8'] = (data.PAY_1 == 8)\ndata['PAY_6_8'] = (data.PAY_1 == 8)\n\"\"\"\n## <a id='4'>Data Exploration and Data Visualization<\/a>\n\"\"\"\n\"\"\"\nWe will continue here by looking for attributes that are effective for our target and trying to see a specific attribute. By doing this I will explain the data set and make it explainable with visualization.\n\"\"\"\npd.crosstab(data.SEX,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by Sex')\nplt.xlabel('Sex (1 = Male, 2 = Female)' )\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\n\"\"\"\nI see our target characteristics are unstable here. I need to make sure that any model I install doesn't memorize the data.\n\"\"\"\npd.crosstab(data.MARRIAGE,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by Marriage')\nplt.xlabel('Marriage(1=married, 2=single ,3=others)' )\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\npd.crosstab(data.EDUCATION,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by Education')\nplt.xlabel('Education(1=Graduate School, 2=University ,3=High School ,4=Others)' )\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\npd.crosstab(data.AgeBin,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by AgeBin')\nplt.xlabel('Age Bin\\n (for 1) Age = [20,30) \\n (for 2) Age = [30,40) \\n' +\n           ' (for 3) Age = [40,50) \\n (for 4) Age = [50,60) \\n (for 5) Age = [60,70) \\n(for 6) Age = [70,81)')\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\npd.crosstab(data.AgeBin,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by AgeBin')\nplt.xlabel('Age Bin\\n (for 1) Age = [20,30) \\n (for 2) Age = [30,40) \\n' +\n           ' (for 3) Age = [40,50) \\n (for 4) Age = [50,60) \\n (for 5) Age = [60,70) \\n(for 6) Age = [70,81)')\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\npd.crosstab(data.SE_MA,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by SEX and MARRIAGE')\nplt.xlabel('SEX & MARRIAGE\\n 1 = Married Man, 2 = Single Man, 3 = Divorced Man, 4 = Married Woman, 5 = Single Woman, 6 = Divorced Woman')\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\npd.crosstab(data.SE_AG,data.def_pay,normalize=False).plot(kind=\"bar\",rot=0,figsize=(20,6))\nplt.title('Default Payment by SEX and AGE')\nplt.xlabel('SEX & AGE\\n 1 = 20s Man, 2 = 30s Man, ..., 5 = 60s Man, 6 = 20s Woman, 7 = 30s Woman, ..., 10 = 60s Woman')\nplt.legend([\"No Payment\", \"Paying\"])\nplt.ylabel('Frequency')\nplt.grid()\nplt.show()\n\"\"\"\n# <a id=\"5\">Predictive Models<\/a>\nFirstly, I must be choice the features of dataset for create predictive models. In previous stages, I was create many columns for to gain better results. For example, AgeBin, SE_AG etc. These are could be given idea to me. That's reason why I use a lot of columns because everything normal and nobody do not default payment. \nWhile I create model, I will select random state equal to 42. Then, I divide dataset as training and testing with percent of 20. After the model, I will use cross validation for prevent over-learning.\n\"\"\"\nfeatures = ['LIMIT_BAL', 'EDUCATION','BILL_AMT1', 'BILL_AMT2',\n            'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1',\n            'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6', \n            'SE_MA', 'AgeBin', 'SE_AG', 'average_5', 'average_4',\n            'average_3', 'average_2', 'average_1', 'InvoiceLimit_5', 'InvoiceLimit_6',\n            'InvoiceLimit_4', 'InvoiceLimit_3', 'InvoiceLimit_2','InvoiceLimit_1',\n            'active_6','active_5','active_4','active_3','active_2','active_1','PAY_1_-1',\n            'PAY_1_-2', 'PAY_1_0', 'PAY_1_1', 'PAY_1_2', 'PAY_1_3', 'PAY_1_4', \n            'PAY_1_5', 'PAY_1_6', 'PAY_1_7', 'PAY_1_8', 'PAY_2_-1', 'PAY_2_-2', \n            'PAY_2_0', 'PAY_2_1', 'PAY_2_2', 'PAY_2_3', 'PAY_2_4', 'PAY_2_5', \n            'PAY_2_6', 'PAY_2_7', 'PAY_2_8', 'PAY_3_-1', 'PAY_3_-2', 'PAY_3_0', \n            'PAY_3_1', 'PAY_3_2', 'PAY_3_3', 'PAY_3_4', 'PAY_3_5', 'PAY_3_6', \n            'PAY_3_7', 'PAY_3_8', 'PAY_4_-1', 'PAY_4_-2', 'PAY_4_0', 'PAY_4_1', \n            'PAY_4_2', 'PAY_4_3', 'PAY_4_4', 'PAY_4_5', 'PAY_4_6', 'PAY_4_7', \n            'PAY_4_8', 'PAY_5_-1', 'PAY_5_-2', 'PAY_5_0', 'PAY_5_2', 'PAY_5_3', \n            'PAY_5_4', 'PAY_5_5', 'PAY_5_6', 'PAY_5_7', 'PAY_5_8', 'PAY_6_-1', \n            'PAY_6_-2', 'PAY_6_0', 'PAY_6_2', 'PAY_6_3', 'PAY_6_4', 'PAY_6_5', \n            'PAY_6_6', 'PAY_6_7', 'PAY_6_8']\ntarget = 'def_pay'\ny = data['def_pay'].copy()\nX = data[features].copy()\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n\ndata_train = X_train.join(y_train)\n\"\"\"\n## <a id=\"51\">Random Forest Classifier<\/a>\nWhile I create model of random forest classifier, I choose optimal parameters. I used grid search cv algorithms for optimal parameters but I don't show in here.\n\"\"\"\nrfclassifier = RandomForestClassifier(random_state=42,n_estimators=200,criterion='entropy',\n                                       max_features='sqrt',max_depth=7,verbose=False)\nrfclassifier.fit(X_train[features], y_train)\nrfprediction = rfclassifier.predict(X_test[features])\nprint('Accuracy of Random Forest Classifier: ',accuracy_score(rfprediction,y_test))\ncmrf = pd.crosstab(y_test.values, rfprediction, rownames=['Actual'], colnames=['Predicted'])\nfig, (ax1) = plt.subplots(ncols=1, figsize=(5,5))\nsns.heatmap(cmrf, fmt=\"d\",\n            xticklabels=['Not Default', 'Default'],\n            yticklabels=['Not Default', 'Default'],\n            annot=True,ax=ax1,\n            linewidths=.2,linecolor=\"Green\", cmap=\"Greens\")\nplt.title('Confusion Matrix for Random Forest', fontsize=14)\nplt.show()\n\nrocaucscorerf=roc_auc_score(y_test.values, rfprediction)\nprint('Roc Score: ',rocaucscorerf)\n\"\"\"\n## <a id=\"52\">Decision Tree Classifier<\/a>\nIf you want to choose optimal parameters for any algorithm, either you will using Grid Search Cv algorithm or you will trying different parameters.\n\"\"\"\ndtclassifier = DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=4,\n                       max_features=None, max_leaf_nodes=20,\n                       min_impurity_decrease=0.0, min_impurity_split=None,\n                       min_samples_leaf=1, min_samples_split=5,\n                       min_weight_fraction_leaf=0.0, presort=False,\n                       random_state=42, splitter='best')\ndtclassifier.fit(X_train, y_train)\ndtprediction = dtclassifier.predict(X_test)\nprint('Accuracy of Decision Tree:', accuracy_score(dtprediction,y_test))\ncmdt = pd.crosstab(y_test.values, dtprediction, rownames=['Actual'], colnames=['Predicted'])\nfig, (ax2) = plt.subplots(ncols=1, figsize=(5,5))\nsns.heatmap(cmdt, fmt = \"d\",\n            xticklabels=['Not Default', 'Default'],\n            yticklabels=['Not Default', 'Default'],\n            annot=True,ax=ax2,\n            linewidths=.2,linecolor=\"Red\", cmap=\"Reds\")\nplt.title('Confusion Matrix for Decision Tree', fontsize=14)\nplt.show()\n\nrocaucscoredt=roc_auc_score(y_test.values, dtprediction)\nprint('Roc Score: ',rocaucscoredt)\n\"\"\"\n## <a id=\"53\">K-Nearest Neighbors<\/a>\nI use minkowski distance as metric for optimal knn algorithm.\n\"\"\"\nknnclassifier=KNeighborsClassifier(n_neighbors=8,algorithm='auto',\n                                    leaf_size=30,metric='minkowski')\nknnclassifier.fit(X_train, y_train)\ntrainaccuracy=knnclassifier.score(X_train, y_train)\ntestaccuracy=knnclassifier.score(X_test, y_test)\npredictionknn=knnclassifier.predict(X_test)\nprint('train accuracy: {}\\ntest accuracy: {}\\n'.format(trainaccuracy,testaccuracy))\ncmknn = pd.crosstab(y_test.values, predictionknn, rownames=['Actual'], colnames=['Predicted'])\nfig, (ax3) = plt.subplots(ncols=1, figsize=(5,5))\nsns.heatmap(cmknn, fmt=\"d\",\n            xticklabels=['Not Default', 'Default'],\n            yticklabels=['Not Default', 'Default'],\n            annot=True,ax=ax3,\n            linewidths=.2,linecolor=\"Blue\", cmap=\"Blues\")\nplt.title('Confusion Matrix for KNN', fontsize=14)\nplt.show()\n\n\nrocaucscoreknn=roc_auc_score(y_test.values, predictionknn )\nprint('Roc Score: ',rocaucscoreknn)\n\"\"\"\n## <a id=\"54\">AdaBoost<\/a>\nLearning rate is very important topic because if learning rate is chosen small value, model might not learning to success. On the contrary, if learning rate is chosen big value, model could assume it was the most successful at learning. In summary, if learning rate is chosen optimally, I can obtain most successful model.\n\"\"\"\nadaboostclassifier = AdaBoostClassifier(base_estimator=None, \n                                         n_estimators=50, \n                                         learning_rate=1.5, \n                                         algorithm='SAMME', \n                                         random_state=42)\n\nadaboostclassifier.fit(X_train[features], y_train.values)\nadaboostprediction = adaboostclassifier.predict(X_test[features])\nprint('Accuracy of Ada Boost:', accuracy_score(adaboostprediction,y_test))\ncmadaboost = pd.crosstab(y_test.values, adaboostprediction, \n                     rownames=['Actual'], colnames=['Predicted'])\nfig, (ax4) = plt.subplots(ncols=1, figsize=(5,5))\nsns.heatmap(cmadaboost, fmt=\"d\",\n            xticklabels=['Not Default', 'Default'],\n            yticklabels=['Not Default', 'Default'],\n            annot=True,ax=ax4,\n            linewidths=.2,linecolor=\"Purple\", cmap=\"Purples\")\nplt.title('Confusion Matrix for Adaboost', fontsize=14)\nplt.show()\n\nrocaucscoreadaboost=roc_auc_score(y_test.values, adaboostprediction)\nprint('Roc Score: ',rocaucscoreadaboost)\n\"\"\"\n## <a id=\"55\">ROC-AUC CURVE<\/a>\nAUC - ROC curve is a performance measurement for classification problem at various thresholds settings. ROC is a probability curve and AUC represents degree or measure of separability.\n\"\"\"\ny_pred_proba_DT = dtclassifier.predict_proba(X_test)[::,1]\nfpr1, tpr1, _ = roc_curve(y_test, y_pred_proba_DT)\nauc1 = roc_auc_score(y_test, y_pred_proba_DT)\n\ny_pred_proba_RF = rfclassifier.predict_proba(X_test)[::,1]\nfpr2, tpr2, _ = roc_curve(y_test,  y_pred_proba_RF)\nauc2 = roc_auc_score(y_test, y_pred_proba_RF)\n\ny_pred_proba_KNN = knnclassifier.predict_proba(X_test)[::,1]\nfpr3, tpr3, _ = roc_curve(y_test,  y_pred_proba_KNN)\nauc3 = roc_auc_score(y_test, y_pred_proba_KNN)\n\ny_pred_proba_ADABOOST = adaboostclassifier.predict_proba(X_test)[::,1]\nfpr4, tpr4, _ = roc_curve(y_test,  y_pred_proba_ADABOOST)\nauc4 = roc_auc_score(y_test, y_pred_proba_ADABOOST)\n\nplt.figure(figsize=(10,7))\nplt.title('ROC', size=15)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot(fpr1,tpr1,label=\"Decision Tree, auc=\"+str(round(auc1,2)))\nplt.plot(fpr2,tpr2,label=\"Random Forest, auc=\"+str(round(auc2,2)))\nplt.plot(fpr3,tpr3,label=\"KNearest Neighbor, auc=\"+str(round(auc3,2)))\nplt.plot(fpr4,tpr4,label=\"AdaBoost, auc=\"+str(round(auc4,2)))\nplt.legend(loc='best', title='Models', facecolor='white')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.box(False)\nplt.grid()\nplt.show()\n\n\"\"\"\n## <a id=\"56\">K-Fold Cross Validation for Algorithms<\/a>\nI want to compare and select models for my problem because this method has a lower bias than other methods.\n\"\"\"\nclf_list = [DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=4,\n                                   max_features=None, max_leaf_nodes=20,\n                                   min_impurity_decrease=0.0, min_impurity_split=None,\n                                   min_samples_leaf=1, min_samples_split=5,\n                                   min_weight_fraction_leaf=0.0, presort=False,\n                                   random_state=42, splitter='best'), \n            RandomForestClassifier(random_state=42,n_estimators=200,criterion='entropy',\n                                    max_features='sqrt',max_depth=7,verbose=False),\n            KNeighborsClassifier(n_neighbors=8,algorithm='auto',\n                                    leaf_size=30,metric='minkowski'), \n            AdaBoostClassifier(base_estimator=None, \n                                    n_estimators=50, \n                                    learning_rate=1.5, \n                                    algorithm='SAMME', \n                                    random_state=42)\n           ]\n# use Kfold to evaluate the normal training set\nkf = KFold(n_splits=5,random_state=42,shuffle=True)\n\nmdl = []\nfold = []\nfscr = []\nrocscr = []\naccscr = []\n\n\nfor i,(train_index, test_index) in enumerate(kf.split(data_train)):\n    training = data.iloc[train_index,:]\n    valid = data.iloc[test_index,:]\n    print(i)\n    for clf in clf_list:\n        model = clf.__class__.__name__\n        feats = training[features] #defined above\n        label = training['def_pay']\n        valid_feats = valid[features]\n        valid_label = valid['def_pay']\n        clf.fit(feats,label) \n        pred = clf.predict(valid_feats)\n        fscore = f1_score(y_true = valid_label, y_pred = pred)\n        rocscore = roc_auc_score(valid_label, pred)\n        accscore = accuracy_score(y_true = valid_label, y_pred = pred)\n        fold.append(i+1)\n        fscr.append(fscore)\n        rocscr.append(rocscore)\n        accscr.append(accscore)\n        mdl.append(model)\n        print(model)\n\"\"\"\n## <a id=\"57\">Comparison of Algorithms<\/a>\nI obtain most successful model with Random Forest Classifier or Adaboost Classifier for this problem. According to Roc-Auc Curve, I want to develop Random Forest Classifier.\n\"\"\"\nperformance = pd.DataFrame({'Model': mdl, 'Score':fscr,\n                            'Roc_Auc_Score':rocscr,'Accuracy_Score':accscr,'Fold':fold})\n\ndtcc = performance[performance['Model'] == 'DecisionTreeClassifier']\nrfcc = performance[performance['Model'] == 'RandomForestClassifier']\nabcc = performance[performance['Model'] == 'AdaBoostClassifier']\nknnn = performance[performance['Model'] == 'KNeighborsClassifier']\n\nplt.figure(figsize=(15,10))\nplt.plot(dtcc.Fold,dtcc.Score,'red',label=\"DT F1\",marker='o')\nplt.plot(dtcc.Fold,dtcc.Roc_Auc_Score,'firebrick',label=\"DT Roc\",marker='x')\nplt.plot(dtcc.Fold,dtcc.Accuracy_Score,'rosybrown',label=\"DT Acc\",marker='.')\n\nplt.plot(rfcc.Fold,rfcc.Score,'olive',label=\"RF F1\",marker='o')\nplt.plot(rfcc.Fold,rfcc.Roc_Auc_Score,'yellowgreen',label=\"RF Roc\",marker='x')\nplt.plot(rfcc.Fold,rfcc.Accuracy_Score,'lightgreen',label=\"RF Acc\",marker='.')\n\nplt.plot(knnn.Fold,knnn.Score,'purple',label=\"KNN F1\",marker='o')\nplt.plot(knnn.Fold,knnn.Roc_Auc_Score,'violet',label=\"KNN Roc\",marker='x')\nplt.plot(knnn.Fold,knnn.Accuracy_Score,'fuchsia',label=\"KNN Acc\",marker='.')\n\nplt.plot(abcc.Fold,abcc.Score,'lightskyblue',label=\"AdaB F1\",marker='o')\nplt.plot(abcc.Fold,abcc.Roc_Auc_Score,'blue',label=\"AdaB Roc\",marker='x')\nplt.plot(abcc.Fold,abcc.Accuracy_Score,'navy',label=\"AdaB Acc\",marker='.')\n\nplt.title(\"Classifiers\")\nplt.grid()\nplt.legend(loc='best')\nplt.show()\nplt.figure(figsize=(10,8))\nplt.plot(dtcc.Fold,dtcc.Score,'r',label=\"DecisionTreeClassifier\",marker='o')\nplt.plot(rfcc.Fold,rfcc.Score,'b',label=\"RandomForestClassifier\",marker='o')\nplt.plot(knnn.Fold,knnn.Score,'c',label=\"KNeighborsClassifier\",marker='o')\nplt.plot(abcc.Fold,abcc.Score,'g',label=\"AdaBoostClassifier\",marker='o')\nplt.title(\"Classifiers F1 Score\")\nplt.grid()\nplt.legend(loc='best')\nplt.show()\nplt.figure(figsize=(10,8))\nplt.plot(dtcc.Fold,dtcc.Roc_Auc_Score,'r',label=\"DecisionTreeClassifier\",marker='o')\nplt.plot(rfcc.Fold,rfcc.Roc_Auc_Score,'b',label=\"RandomForestClassifier\",marker='o')\nplt.plot(knnn.Fold,knnn.Roc_Auc_Score,'c',label=\"KNeighborsClassifier\",marker='o')\nplt.plot(abcc.Fold,abcc.Roc_Auc_Score,'g',label=\"AdaBoostClassifier\",marker='o')\nplt.title(\"Classifiers Roc Score\")\nplt.grid()\nplt.legend(loc='best')\nplt.show()\nplt.figure(figsize=(8,8))\nplt.plot(dtcc.Fold,dtcc.Accuracy_Score,'r',label=\"DecisionTreeClassifier\",marker='o')\nplt.plot(rfcc.Fold,rfcc.Accuracy_Score,'b',label=\"RandomForestClassifier\",marker='o')\nplt.plot(knnn.Fold,knnn.Accuracy_Score,'c',label=\"KNeighborsClassifier\",marker='o')\nplt.plot(abcc.Fold,abcc.Accuracy_Score,'g',label=\"AdaBoostClassifier\",marker='o')\nplt.title(\"Classifiers Accuracy Score\")\nplt.grid()\nplt.legend(loc='best')\nplt.show()\n\"\"\"\n## <a id=\"58\">Change the Features Used for Algorithm<\/a>\nI want to show features important. That's reason why, I select more little features. While I select new features, I want to choose the more efficient features for default payment.\n\"\"\"\nnew_features = ['LIMIT_BAL', 'BILL_AMT1', 'BILL_AMT2',\n            'BILL_AMT3', 'BILL_AMT5', 'PAY_AMT1',\n            'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6', \n            'average_4','average_3', 'average_2', 'average_1', 'InvoiceLimit_5',\n            'InvoiceLimit_4', 'InvoiceLimit_3', 'InvoiceLimit_2','InvoiceLimit_1', \n            'PAY_1_1', 'PAY_1_2',\n            'PAY_2_0', 'PAY_2_2', 'PAY_2_3', \n            'PAY_3_0', \n            'PAY_3_1', 'PAY_3_2', 'PAY_3_3', 'PAY_4_0', 'PAY_4_1', \n            'PAY_4_2', 'PAY_4_3', 'PAY_5_0', 'PAY_5_2', 'PAY_5_3',\n            'PAY_6_2']\n\nrfclassifier_new = RandomForestClassifier(random_state=42,n_estimators=200,criterion='entropy',\n                                       max_features='sqrt',max_depth=7,verbose=False)\nrfclassifier_new.fit(X_train[new_features], y_train)\nrfprediction_new = rfclassifier_new.predict(X_test[new_features])\nprint('Accuracy of New Random Forest: ',accuracy_score(rfprediction_new,y_test))\ncmrf_new = pd.crosstab(y_test.values, rfprediction_new, rownames=['Actual'], colnames=['Predicted'])\nfig, (ax5) = plt.subplots(ncols=1, figsize=(5,5))\nsns.heatmap(cmrf_new, fmt=\"d\",\n            xticklabels=['Not Default', 'Default'],\n            yticklabels=['Not Default', 'Default'],\n            annot=True,ax=ax5,\n            linewidths=.2,linecolor=\"Green\", cmap=\"Greens\")\nplt.title('Confusion Matrix in New Random Forest', fontsize=14)\nplt.show()\nrocaucscorerf=roc_auc_score(y_test.values, rfprediction)\nprint('Roc Score: ',rocaucscorerf)\ntmp = pd.DataFrame({'Features': new_features, 'Importance of Features': rfclassifier_new.feature_importances_})\ntmp = tmp.sort_values(by='Importance of Features',ascending=False)\nplt.figure(figsize = (25,15))\nplt.title('Importance of Features',fontsize=14)\ns = sns.barplot(x='Features',y='Importance of Features',data=tmp)\ns.set_xticklabels(s.get_xticklabels(),rotation=90)\nplt.grid()\nplt.show()\n\"\"\"\n## <a id=\"6\">Conclusion<\/a>\n<p>This success may be successful for the entire data set, but I have not found a clear classification as the common characteristic of credit card users who make the default payment. I just find that payment delays play an important role for those performing with 2 to default payment. This shows that between the dates given to me there may be an economic crisis or any social problem may have occurred.As a solution, I think that configuring a payment plan would be more accurate for credit card users to make their default payments. I also believe I could have found a more accurate result if there had been a classification of loans taken in this data set.<\/p>\n<p> ***\"14 March \u2013 Mainland China passed the Anti-Secession Law, a bill to prevent Taiwan from being an independent nation.\"***<\/p>\n<p>In view of this situation, I believe there may have been an economic crisis in Taiwan because blocking independence could also be a major obstacle to the country's economic independence. I believe that if there was a drastic difference in the country's import and export figures after the creation of this law, the default payments could be realized through configuration. As a result, instead of looking for answers to the personality characteristic problem of the people who make the default payments with this data set, we can ask the questions of how to take precautions or how to configure payment during a period of economic crisis. A new payment plan, which will be delayed by 2 months as shown in this data, will be an important decision for the realization of the default payment. <\/p>\n\"\"\"\n\"\"\"\n## <a id=\"7\">Referances<\/a>\n* https:\/\/en.wikipedia.org\/wiki\/2005_in_Taiwan\n* https:\/\/pandas.pydata.org\/\n* https:\/\/numpy.org\/\n* https:\/\/matplotlib.org\/\n* https:\/\/en.wikipedia.org\/wiki\/Random_forest\n* https:\/\/en.wikipedia.org\/wiki\/Decision_tree\n* https:\/\/en.wikipedia.org\/wiki\/K-nearest_neighbors_algorithm\n* https:\/\/en.wikipedia.org\/wiki\/AdaBoost\n* https:\/\/towardsdatascience.com\/understanding-auc-roc-curve-68b2303cc9c5\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dbbb4b93f12977'}"}
{"id":"42005","text":"import os\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport librosa\nimport librosa.display\nimport IPython.display as ipd\n\nimport sklearn\n\nimport warnings\nwarnings.filterwarnings('ignore')\ntrain_audio_dir = '..\/input\/birdsong-recognition\/train_audio'\ntrain = pd.read_csv('..\/input\/birdsong-recognition\/train.csv')\nbase_dir = '..\/input\/birdsong-recognition\/train_audio\/'\ntrain['full_path'] = base_dir + train['ebird_code'] + '\/'+ train['filename']\ntrain[train['ebird_code']== 'amered'].sample(1, random_state = 33)['full_path'].values[0]\namered = train[train['ebird_code']== 'amered'].sample(1, random_state = 33)['full_path'].values[0]\npingro = train[train['ebird_code'] == \"pingro\"].sample(1, random_state = 33)['full_path'].values[0]\nvesspa = train[train['ebird_code'] == \"vesspa\"].sample(1, random_state = 33)['full_path'].values[0]\n\n\n\naudio_file, _ = librosa.effects.trim(y)\n\n# the result is an numpy ndarray\nprint('Audio File:', audio_file, '\\n')\nprint('Audio File shape:', np.shape(audio_file))\nipd.Audio(amered)\naudio_amered, sr = librosa.load(amered)\n\"\"\"\n#  Spectrogram \n\"\"\"\nn_fft = 2048 # FFT window size\nhop_length = 512\n\nD_amered = np.abs(librosa.stft(audio_amered, n_fft = n_fft, hop_length = hop_length))\n\nDB_amered = librosa.amplitude_to_db(D_amered, ref = np.max)\nlibrosa.display.specshow(DB_amered, sr = sr, hop_length = hop_length, x_axis = 'time', \n                         y_axis = 'log', cmap = 'cool')\n\"\"\"\n* Spectrogram tells....\n* Most of the energy is concenterated between above 2048 frequency and 8192 frequency.\n\n* Whenever vibration of sound becomes strong, the intensity get dark.\n\n* At 0.6s the intensity is strong, it means there is bird sound. Likewise at 2 and at 4.2s.\n\"\"\"\n\"\"\"\n# #Let see Sound Waves\n\n\"\"\"\n\nplt.Figure(figsize=(16,9))\nplt.title(('Sound waves'), fontsize=16)\n\nlibrosa.display.waveplot(y= audio_amered, sr = sr, color = \"#A300F9\")\n\"\"\"\nthe chirping sound occur at 0.6, 1.8(approx) amd 4\n\"\"\"\n\"\"\"\n# Zero-Crossing\n\"\"\"\nn0 = 9000\nn1 = 9100\nplt.figure(figsize=(14, 5))\nplt.plot(audio_amered[n0:n1])\nplt.grid()\nzero_amered = librosa.zero_crossings(audio_amered, pad=False)\nprint('change rate {}'.format(sum(zero_amered)))\n\"\"\"\nIn speech processing, the zero-crossing counts can help distinguish between voiced and un-voiced speech.  \nUn-voiced sounds are very noise-like ('Shh' and 'Sss' for example). \nIn addition, zero-crossings could also be used to determine if your signal has a DC offset.  \nIf you signal is 'muted' and you are not seeing alot of zero-crossings might mean that your signal is offset from the zero-line\n\"\"\"\n\"\"\"\n# spectral centroid\n\"\"\"\nspectral_centroids = librosa.feature.spectral_centroid(audio_amered, sr=sr)[0]\n\n# Shape is a vector\nprint('Centroids:', spectral_centroids, '\\n')\nprint('Shape of Spectral Centroids:', spectral_centroids.shape, '\\n')\n\n# Computing the time variable for visualization\nframes = range(len(spectral_centroids))\n\n# Converts frame counts to time (seconds)\nt = librosa.frames_to_time(frames)\n\nprint('frames:', frames, '\\n')\nprint('t:', t)\n\n# Function that normalizes the Sound Data\ndef normalize(x, axis=0):\n    return sklearn.preprocessing.minmax_scale(x, axis=axis)\nplt.figure(figsize = (16, 6))\nlibrosa.display.waveplot(audio_amered, sr=sr, alpha=0.4, color = '#A300F9', lw=3)\nplt.plot(t, normalize(spectral_centroids), color='#FFB100', lw=2)\nplt.legend([\"Spectral Centroid\", \"Wave\"])\nplt.title(\"Spectral Centroid: Cangoo Bird\", fontsize=16);\n\"\"\"\n(https:\/\/medium.com\/@jehoshaphatia\/100-days-of-ml-code-day-034-985f64a73c)\n\"\"\"\n\"\"\"\n \u201cThe spectral centroid is a measure used in digital signal processing to characterise a spectrum. It indicates where the \u201ccenter of mass\u201d of the spectrum is located. Perceptually, it has a robust connection with the impression of \u201cbrightness\u201d of a sound\u201d\nSpectral Centroid tells us something about the timbre of a sound. Specifically, it gives us information about how bright a sound is. Visually, you can understand Spectral Centroid by imagining you have a frequency spectrum made out of solid object\n\nSpectra Centroid can be a nice feature if timbre is relevant to the thing you are trying to model.\n\"\"\"\n\"\"\"\n#  Spectral Rolloff \n\"\"\"\nspectral_rolloff = librosa.feature.spectral_rolloff(audio_amered, sr=sr)[0]\n\n\nframes = range(len(spectral_rolloff))\n\nt = librosa.frames_to_time(frames)\n\n\n\nplt.figure(figsize = (16, 6))\nlibrosa.display.waveplot(audio_amered, sr=sr, alpha=0.4, color = '#A300F9', lw=3)\nplt.plot(t, normalize(spectral_rolloff), color='#FFB100', lw=3)\nplt.legend([\"Spectral Rolloff\", \"Wave\"])\nplt.title(\"Spectral Rolloff: Amered Bird\", fontsize=16);\n\"\"\"\nThe roll-off is a measure of spectral shape useful for distinguishing voiced from unvoiced speech. The\nfrequency below which 85% of the magnitude distribution of the spectrum is concentrated is known as Roll-Off.\n\"\"\"\n\"\"\"\nMore to go...\n\"\"\"\n\"\"\"\nhttps:\/\/www.kaggle.com\/andradaolteanu\/birdcall-recognition-eda-and-audio-fe\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4d654cadaceba1'}"}
{"id":"33701","text":"\"\"\"\nHello all!!!\n\nHope u all are doing good ;)\n\nHere, I've done exploratory data analysis for the AirBnb Dataset from Kaggle.\n\nI've included histograms and interective maps. Hope u like this.\n\nIf you like this notebook, feel free to upvote this.\n\nHappy Coding...\n\"\"\"\n#importing required libraries\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport geopandas as gpd\nimport math\nimport folium\nfrom folium import Choropleth, Circle, Marker\nfrom folium.plugins import HeatMap, MarkerCluster\n#importing the dataset\nairbnb = pd.read_csv(\"\/kaggle\/input\/new-york-city-airbnb-open-data\/AB_NYC_2019.csv\")\n#exploring the dataset\nairbnb.head(10)\nairbnb.describe()\nairbnb.info()\nairbnb.shape\nairbnb.isnull().sum()\n#preprocessing the dataset\nairbnb['reviews_per_month'].fillna(value = 0 , inplace = True)\nairbnb.drop(['id' , 'host_id' , 'host_name' ,'last_review'] , axis = 1 , inplace = True)\nairbnb.head()\n\"\"\"\n# Visualizing the dataset\n\"\"\"\nsns.catplot(x=\"neighbourhood_group\", kind = \"count\", data = airbnb)\nplt.show()\nsns.catplot(x=\"neighbourhood_group\", kind = \"count\", data = airbnb)\nplt.show()\nneighbourhood_top10 = airbnb[\"neighbourhood\"].value_counts().head(10)\ndf_neighbourhood_top10 = pd.DataFrame(neighbourhood_top10)\ndf_neighbourhood_top10 = df_neighbourhood_top10.reset_index()\nf, ax = plt.subplots(figsize = (15,5))\nsns.barplot(x =\"index\", y = \"neighbourhood\" ,data = df_neighbourhood_top10)\nplt.show()\nairbnb_price = airbnb.groupby([\"room_type\"])[\"price\"].median()\ndf_airbnb_price = pd.DataFrame(airbnb_price)\ndf_airbnb_price = df_airbnb_price.reset_index()\n\nsns.catplot(x=\"room_type\", y=\"price\",kind = \"bar\", palette = \"Accent\",  data = df_airbnb_price)\nplt.title(\"Room_type price by it's median\")\nplt.show()\nairbnb_reviews = airbnb.groupby([\"neighbourhood_group\"])[\"number_of_reviews\"].sum()\ndf_airbnb_reviews = pd.DataFrame(airbnb_reviews)\ndf_airbnb_reviews = df_airbnb_reviews.reset_index()\n\nsns.scatterplot(x=\"neighbourhood_group\", y=\"number_of_reviews\", data = df_airbnb_reviews)\nplt.title(\"Total Reviews by neighbourhood_group\")\nplt.show()\nairbnb_night = airbnb.groupby([\"neighbourhood_group\"])[\"minimum_nights\"].mean().round(2)\ndf_airbnb_night = pd.DataFrame(airbnb_night)\ndf_airbnb_night = df_airbnb_night.reset_index()\nsns.catplot(x=\"minimum_nights\", y = \"neighbourhood_group\",kind=\"bar\",data = df_airbnb_night)\nplt.title(\"Minimum_nights mean by neighbourhood_group\")\nplt.show()\nairbnb_proportion = airbnb.groupby([\"neighbourhood_group\"])[\"room_type\"].value_counts()\ndf_airbnb_proportion = pd.DataFrame(airbnb_proportion)\ndf_airbnb_proportion.rename(columns={\"room_type\":\"Total of values\"}, inplace = True)\n\n\nairbnb_count = airbnb.groupby([\"neighbourhood_group\"])[\"room_type\"].count()\ndf_airbnb_count = pd.DataFrame(airbnb_count)\n\n\ndf_airbnb_proportion[\"Total\"] = 0\n\ndf_airbnb_proportion.loc[\"Bronx\"][\"Total\"]= df_airbnb_count.room_type.loc[\"Bronx\"]\ndf_airbnb_proportion.loc[\"Brooklyn\"][\"Total\"]= df_airbnb_count.room_type.loc[\"Brooklyn\"]\ndf_airbnb_proportion.loc[\"Manhattan\"][\"Total\"]= df_airbnb_count.room_type.loc[\"Manhattan\"]\ndf_airbnb_proportion.loc[\"Queens\"][\"Total\"]= df_airbnb_count.room_type.loc[\"Queens\"]\ndf_airbnb_proportion.loc[\"Staten Island\"][\"Total\"]= df_airbnb_count.room_type.loc[\"Staten Island\"]\n\ndf_airbnb_proportion = df_airbnb_proportion.reset_index()\n\ndf_airbnb_proportion[\"Proportion\"] = (df_airbnb_proportion[\"Total of values\"]\/df_airbnb_proportion[\"Total\"]).round(2)\n\nsns.catplot(x=\"neighbourhood_group\",\n            y = \"Proportion\",\n            kind = \"bar\",\n            hue = \"room_type\",\n            data = df_airbnb_proportion)\nplt.title(\"Room_type proportion for each neighbourhood_group\")\nplt.show()\nsns.relplot(x=\"latitude\", y=\"longitude\", palette = \"Set2\", hue = \"neighbourhood_group\", data = airbnb)\nplt.show()\ncorr = airbnb.corr()\nsns.heatmap(corr, annot=True, cmap='coolwarm')\nplt.figure(figsize = (15, 15))\nplt.style.use('seaborn-white')\nplt.subplot(221)\nsns.scatterplot(x=\"latitude\", y=\"longitude\",hue=\"neighbourhood_group\", data=airbnb)\nplt.subplot(222)\nsns.scatterplot(x=\"latitude\", y=\"longitude\",hue=\"room_type\", data=airbnb)\nplt.subplot(223)\nsns.scatterplot(x=\"latitude\", y=\"longitude\",hue=\"price\", data=airbnb)\nplt.subplot(224)\nsns.scatterplot(x=\"latitude\", y=\"longitude\",hue=\"availability_365\", data=airbnb)\nplt.show()\ngeomap = folium.Map(location=[40.7128,-74.0060], tiles='cartodbpositron', zoom_start=12)\n# Adding a heatmap to the base map\nHeatMap(data=airbnb[['latitude', 'longitude']], radius=10).add_to(geomap)\ngeomap","meta":"{'source': 'AI4Code', 'id': '3e157ab020ad28'}"}
{"id":"109928","text":"# 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 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\n\"\"\"\n![ott1.jpeg](attachment:ott1.jpeg)\n\"\"\"\n\"\"\"\n# Wanna Binge some movies? Confused? \n\n\n# Here 's the solution.\n\n\n# \n\n\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='red'>\n          <span>\n            We will get following answers:- :\n            <\/span>   \n    <\/font>\n<\/h2>\n\n(1)  Which OTT platform is the best for IMDB 9+ Movies\/Shows\n\n(2)  On which OTT Platforms, Nolan and Russo Brother's movies are available?\n\n(3)  Best Thrillers\/ Actions\/ Adventure\/ Sci-fi Movies and its OTT platform\n\"\"\"\n\"\"\"\n![upvote.jpg](attachment:upvote.jpg)\n\"\"\"\n\"\"\"\n<h2>   \n      <span>          \n           Contents\n    <\/span>\n       \n<\/h2>\n<span>\n    <ul>\n        <li><a href='#intro'>1. Introduction<\/a><\/li>\n        <ul>\n            <li><a href='#background'>1.1 Background info<\/a><\/li>\n            <li><a href='#data'>1.2 Dataset information<\/a><\/li>\n        <\/ul>\n        <li><a href='#libraries'>2. Python Libraries<\/a><\/li>\n        <ul>\n            <li><a href='#python'>2.1 Import Python Libraries<\/a><\/li>\n         <\/ul>\n        <li><a href='#understand'>3. Understanding the data<\/a><\/li>\n        <ul>\n            <li><a href='#import'>3.1 Importing the input csv<\/a><\/li>\n            <li><a href='#inspect'>3.2 Overview the dataframes<\/a><\/li>\n            <li><a href='#unwanted'>3.3 Observe Null Values<\/a><\/li>\n            <li><a href='#unwanted'>3.4 Pandas Profiling<\/a><\/li>\n        <\/ul>\n              <li><a href='#eda'>4. EDA (Exploratory Data Anslysis)<\/a><\/li>\n        <ul>\n            <li><a href='#app_Rating'>4.1 Highest ROtten Tomatoes Movies\/Shows<\/a><\/li>\n            <li><a href='#rating_cate'>4.2 Highest IMDB Rating<\/a><\/li>\n            <li><a href='#type'>4.3 Top Movies and its OTT Platform<\/a><\/li>        \n            <li><a href='#type'>4.4 Top Language Movies<\/a><\/li>        \n            <li><a href='#type'>4.5 Best Christopher Nolan's Movies<\/a><\/li>        \n            <li><a href='#type'>4.6 Best Russo Brother's Movies<\/a><\/li>        \n            <li><a href='#type'>4.7 Best Thriller Movies\/Shows<\/a><\/li>        \n            <li><a href='#type'>4.8 Movies\/Shows on OTT Platforms<\/a><\/li>        \n            <li><a href='#type'>4.9 Best Animation Movies\/Show<\/a><\/li>                       \n        <\/ul>\n            <li><a href='#low'>6. Netflix Overview<\/a><\/li>\n        <ul>\n            <li><a href='#low_app'>6.1 Available Languages<\/a><\/li>\n             <li><a href='#tools'>6.2 Top Runtime movies\/shows<\/a><\/li>\n             <li><a href='#age'>6.3 Top IMDB Movies <\/a><\/li>\n             <li><a href='#age'>6.4 Top Thriller Movies <\/a><\/li>\n             <li><a href='#age'>6.5 Top SCIFI Movies <\/a><\/li>\n             <li><a href='#age'>6.6 Top action Movies <\/a><\/li>\n             <li><a href='#age'>6.7 Top  animation Movies <\/a><\/li> \n        <\/ul> \n          <li><a href='#low'>7. HULU Overview<\/a><\/li>\n        <ul>\n            <li><a href='#low_app'>7.1 Available Languages<\/a><\/li>\n             <li><a href='#tools'>7.2 Top Runtime movies\/shows<\/a><\/li>\n             <li><a href='#age'>7.3 Top IMDB Movies <\/a><\/li>\n             <li><a href='#age'>7.4 Top Thriller Movies <\/a><\/li>\n             <li><a href='#age'>7.5 Top SCIFI Movies <\/a><\/li>\n             <li><a href='#age'>7.6 Top action Movies <\/a><\/li>\n             <li><a href='#age'>7.7 Top  animation Movies <\/a><\/li> \n        <\/ul> \n          <li><a href='#low'>8. Prime Video Overview<\/a><\/li>\n        <ul>\n            <li><a href='#low_app'>8.1 Available Languages<\/a><\/li>\n             <li><a href='#tools'>8.2 Top Runtime movies\/shows<\/a><\/li>\n             <li><a href='#age'>8.3 Top IMDB Movies <\/a><\/li>\n             <li><a href='#age'>8.4 Top Thriller Movies <\/a><\/li>\n             <li><a href='#age'>8.5 Top SCIFI Movies <\/a><\/li>\n             <li><a href='#age'>8.6 Top action Movies <\/a><\/li>\n             <li><a href='#age'>8.7 Top  animation Movies <\/a><\/li> \n        <\/ul> \n        <li><a href='#low'>9. Disney+ Overview<\/a><\/li>\n        <ul>\n            <li><a href='#low_app'>9.1 Available Languages<\/a><\/li>\n             <li><a href='#tools'>9.2 Top Runtime movies\/shows<\/a><\/li>\n             <li><a href='#age'>9.3 Top IMDB Movies <\/a><\/li>\n             <li><a href='#age'>9.4 Top Thriller Movies <\/a><\/li>\n             <li><a href='#age'>9.5 Top SCIFI Movies <\/a><\/li>\n             <li><a href='#age'>9.6 Top action Movies <\/a><\/li>\n             <li><a href='#age'>9.7 Top  animation Movies <\/a><\/li> \n        <\/ul>          \n                <li><a href='#obser'>10. Conclusion<\/a><\/li>\n                                \n\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='red'>\n          <span>\n            1. Introduction :\n            <\/span>   \n    <\/font>\n<\/h2>\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            1.1 Background Information\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\n\"\"\"\nOver the last few years, audiences in India have shifted their focus from TV to online streaming platforms. Out of the many platforms Hotstar, Netflix and Amazon Prime Video are currently the most popular ones.\n\nHowever, this is not the only platform where people can watch unlimited movies and series, we have other OTT platforms that are making a tremendous business including Amazon Prime, Netflix.\n\nOn this related note, we have jotted down the features of all the platforms while also breaking down the have\u2019s and have-nots of each. So let\u2019s begin.\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            1.2 Dataset Information :\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\n\"\"\"\n \n* ID:  Movie ID\n\n* Title: Movie Title\n\n* Year: Release Year\n\n* Age: Age restriction\n\n* IMDB: IMDB Rating\n\n* ROttern Tomatoes: Tomatoes Rating\n\n* Netflix, Hulu,Prime Video, Disney+ : OTT Platforms\n\n* Type: Movie Genres\n\n* DIrectors: Movie Director\n\n![](http:\/\/)* Country: Release in Country\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='red'>\n          <span>\n            2. Python Libraries :\n            <\/span>   \n    <\/font>\n<\/h2>\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            2.1: Import Python Libraries\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\n# for visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom plotly.offline import iplot\nimport cufflinks as cf\ncf.go_offline()\n\n# for data overview\nfrom pandas_profiling import ProfileReport\nimport plotly.graph_objects as go\nfig = go.Figure()\nimport re\n\"\"\"\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='red'>\n          <span>\n            3. Understanding the data\n            <\/span>   \n    <\/font>\n<\/h2>\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            3.1 Importing the input csv\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data = pd.read_csv(\"\/kaggle\/input\/movies-on-netflix-prime-video-hulu-and-disney\/MoviesOnStreamingPlatforms_updated.csv\")\nmovie_data.head(5)\nmovie_data.shape\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            3.2 Overview the dataframes\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data.info()\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            3.3 Observe Null Values\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data.isnull().sum()\n# Deal with null values\n\nAge_Null = round(movie_data['Age'].isnull().sum()\/len(movie_data['Age']) * 100 , 2)\nGenres_Null = round(movie_data['Genres'].isnull().sum()\/len(movie_data['Genres']) * 100 , 2)\nDirectors_Null = round(movie_data['Directors'].isnull().sum()\/len(movie_data['Directors']) * 100 , 2)\nRuntime_Null = round(movie_data['Runtime'].isnull().sum()\/len(movie_data['Runtime']) * 100 , 2)\nLanguage_Null = round(movie_data['Language'].isnull().sum()\/len(movie_data['Language']) * 100 , 2)\nCountry_Null = round(movie_data['Country'].isnull().sum()\/len(movie_data['Country']) * 100 , 2)    \nRotten_Null = round(movie_data['Rotten Tomatoes'].isnull().sum()\/len(movie_data['Rotten Tomatoes']) * 100 , 2)                          \nprint(\"Age Null: {}%\".format(Age_Null))\nprint(\"Genres_Null: {}%\".format(Genres_Null))\nprint(\"Directors_Null: {}%\".format(Directors_Null))\nprint(\"Runtime_Null : {}%\".format(Runtime_Null))\nprint(\"Language_Null: {}%\".format(Language_Null))\nprint(\"Country_Null: {}%\".format(Country_Null))\nprint(\"Rotten_Null: {}%\".format(Rotten_Null))\n\n# Let deal with Age Column\nmovie_data['Age'].value_counts(), movie_data['Age'].shape\nmovie_data['Age'].value_counts().iplot('bar')\n\"\"\"\nOnly less movies are targetted to the audience below age 12. and mostly OTT platforms include movie with  some age erstriction 18+\n\"\"\"\nmovie_data[movie_data['Age'].isnull()].shape\nmovie_data[movie_data['Age'].isnull()]\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            3.4 Pandas Profiling\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\n!pip install pandas-profiling\n\nprofile = ProfileReport(movie_data, title=\"Pandas Profiling Report\")\n\nprofile\n\"\"\"\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='orange'>\n          <span>\n            4. EDA (Exploratory Data Anslysis)\n            <\/span>   \n    <\/font>\n<\/h2>\n\"\"\"\n# Highest Rotten tomatoes Movies and available platform\nprint(movie_data.columns)\nmovie_data.head(3)\n\"\"\"\nThe Tomatometer score represents the percentage of professional critic reviews that are positive for a given film or television show. .\n\"\"\"\n# ROtten tomatoes\nmovie_data['Rotten Tomatoes'].value_counts()\n\"\"\"\nSooo many values, Let make it general or round figure\n\"\"\"\nimport re\n\ndef convert_str_to_int(val):\n    new_val =  re.sub('%','',val)\n    return(int(new_val))\n\ndef round_fix(data):\n    data_str = str(data).strip()\n    if data_str != 'nan':\n        data = convert_str_to_int(data_str)\n        if data in range(0,11):\n#             print(data)\n            return '10'\n        if data in range(11,21):\n            return '20'\n        if data in range(21,31):\n            return '30'\n        if data in range(31,41):\n            return '40'\n        if data in range(41,51):\n            return '50'\n        if data in range(51,61):\n            return '60'\n        if data in range(61,71):\n            return '70'\n        if data in range(71,81):\n            return '80'\n        if data in range(81,91):\n            return '90'\n\n        if data in range(91,101):\n            return '100'\n\n\nmovie_data['Rotten_Tomatoes_overview'] = movie_data['Rotten Tomatoes'].apply(round_fix)\nmovie_data['Rotten_Tomatoes_overview'].value_counts().iplot(kind='bar', bins=20, xTitle = 'Rotten Tomatoes Ratings', yTitle='Number of movies', title='OTT ROtten TOmatoes')\n\"\"\"\nObservations:- \n\nNumber of approx 100 % Rotten Tomatoes movies are more in the OTT Platforms which means Movies available are reviews and liked by audiences.\n\n\nCOntent in OTT are better and accepted by audience.\n\"\"\"\nmovie_data['Rotten_Tomatoes_overview'].value_counts()\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.1 Highest ROtten Tomatoes Movies\/Shows\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nnetflix_count = movie_data[movie_data['Rotten_Tomatoes_overview'] == '100']['Netflix'].sum()\nHulu_count = movie_data[movie_data['Rotten_Tomatoes_overview'] == '100']['Hulu'].sum()\nDisney_count = movie_data[movie_data['Rotten_Tomatoes_overview'] == '100']['Disney+'].sum()\nprime_count = movie_data[movie_data['Rotten_Tomatoes_overview'] == '100']['Prime Video'].sum()\n\nindexes = ['Netflix', 'Hulu', 'Disney', 'Amazon Prime']\nvalues = [netflix_count, Hulu_count, Disney_count,prime_count]\nnetflix_count\nfrom plotly.subplots import make_subplots\n\nfig = make_subplots(\nrows=1,cols=2, subplot_titles=[\"Highest Rottem Tomatoes movies\"],\nspecs=[[{'type':'bar'},{'type':'pie'}]])\n\nfig.add_trace(go.Bar(x=indexes, y=values), row=1,col=1)\nfig.add_trace(go.Pie(labels=indexes, values=values), row=1,col=2)\n\n\"\"\"\nObservations:-\n\nAmazon prime has highest rotten tomatoes movies as compared to other platform.\n\n\nSo, next time, Amazon Prime should be on the First prority\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.2 Highest IMDB Rating\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data['IMDb'].value_counts()\n# convert it to round values\ndef round_val(data):\n    if str(data) != 'nan':\n        return round(data)\n    \nmovie_data['IMDB_group'] = movie_data['IMDb'].apply(round_val)\nvalues = movie_data['IMDB_group'].value_counts().sort_index(ascending=False).tolist()\nindex = movie_data['IMDB_group'].value_counts().sort_index(ascending=False).index\nvalues,index\nimport seaborn as sns\n\nmovie_data['IMDB_group'].value_counts().iplot('bar', xTitle='IMDB Rating', yTitle='Num of Movies', title='IMDB RATING OVERVIEW')\n\n\"\"\"\nObservations:-\n\nEven though there are maximum 100 % rotten tomatoes movies in the OTT Platform, Majority of the movies has only rating 6-7 out of 10.\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.3 Top Movies and its OTT Platform\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nnetflix_count = movie_data[(movie_data['IMDB_group'] == 9) | (movie_data['IMDB_group'] == 8)]['Netflix'].sum()\n\nnetflix_count\nnetflix_count = movie_data[(movie_data['IMDB_group'] == 9) & (movie_data['IMDB_group'] == 8)]['Netflix'].sum()\nHulu_count = movie_data[movie_data['IMDB_group'] == 9]['Hulu'].sum()\nDisney_count = movie_data[movie_data['IMDB_group'] == 9]['Disney+'].sum()\nprime_count = movie_data[movie_data['IMDB_group'] == 9]['Prime Video'].sum()\n\nindexes = ['Netflix', 'Hulu', 'Disney', 'Amazon Prime']\nvalues = [netflix_count, Hulu_count, Disney_count,prime_count]\nfig = make_subplots(\nrows=1,cols=2, subplot_titles=[\"Top IMDB Rated Movies\"],\nspecs=[[{'type':'bar'},{'type':'pie'}]])\n\nfig.add_trace(go.Bar(x=indexes, y=values), row=1,col=1)\nfig.add_trace(go.Pie(labels=indexes, values=values), row=1,col=2)\n\n\n\"\"\"\nObservations:\n    \nTop IMDB movies are present in the Amazon prime \n\"\"\"\n# let explore Amazon Prime movies\nprime_movies = movie_data[(movie_data['IMDB_group'] == 9) & (movie_data['Prime Video'] == 1)]\n\n\n\nprime_movies.shape\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.4 Top Language Movies\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nprime_movies['Language'].value_counts().iplot('bar')\n\"\"\"\nObservations:-\n\n\nTO target larger audience, top imdb movies are dubbed in English\n\nBest part is : it also includes Hindi movies too\n\"\"\"\nprime_movies[prime_movies['Language'] == 'Hindi']['Title'].value_counts()\n\"\"\"\nTop IMDB Rated SHows\/Movies on Amazon Prime (Hindi Language)\n\nAnand,\n\nGOlmaal\n\nZakir Khan\n\n\n\"\"\"\n\"\"\"\n#Check about my favourite director:-\n(1) Nolan\n(2) RUsso brothers\n\n\n\n\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.5 Best Christopher Nolan's Movies\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data.head(4)\nnolan_movie = movie_data[movie_data['Directors'] == 'Christopher Nolan']\nnolan_movie\nnolan_movie[['Title', 'Netflix','Hulu','Disney+','Prime Video', 'IMDB_group']]\n\"\"\"\nObservations:\n\nNolan movies are basically have imdb rating above 7, which is very rare.\n\nAlso, this is expected because Nolan is visionary director\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.6 Best Russo Brother's Movies\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nrusso_movie =  movie_data[movie_data['Directors'] == 'Anthony Russo,Joe Russo']\nrusso_movie[['Title', 'Netflix','Hulu','Disney+','Prime Video', 'IMDB_group']]\n\"\"\"\nObservation:\n\nRusso Brothers are extra-ordinary directors who have movies rating above 7+.\n\nAlso, They have deal with the Disney+ as DIsney+ has more Russo movies as compared to other OTT platform.\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.7 Highly Recommended Movies\/Shows\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nmovie_data[:10]['Title']\n\"\"\"\nRecommended movies\n\"\"\"\ndef ott_platform(data):\n    if data == 1:\n        return 'netflix'\n    else:\n        return data\n    \nmovie_data['Netflix'] = movie_data['Netflix'].apply(ott_platform)\ndef hulu_platform(data):\n    if data == 1:\n        return 'hulu'\n    else:\n        return data\n    \ndef disney_platform(data):\n    if data == 1:\n        return 'disney'\n    else:\n        return data\n    \ndef prime_platform(data):\n    if data == 1:\n        return 'prime'\n    else:\n        return data\n\n    \n    \nmovie_data['Hulu'] = movie_data['Hulu'].apply(hulu_platform)    \nmovie_data['Prime Video'] = movie_data['Prime Video'].apply(prime_platform)  \nmovie_data['Disney+'] = movie_data['Disney+'].apply(disney_platform)  \nmovie_data\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.8 Movies\/Shows on OTT Platforms\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\n\"\"\"\nwe will take  major category in the movie type like thriller, comedy, fantasy etc.\n\nif movie is based on comedy, romance, we will categorize as comedy\n\"\"\"\ndef check_thriller(data):\n#     printdata)\n    if str(data).strip() != 'nan':\n#         print(data)\n        if 'horror' in data.lower():\n            return 'horror'\n        elif 'thriller' in data.lower():\n            return 'thriller'\n        elif 'sci-fi' in data.lower():\n            return 'sci-fi'\n        elif 'documentary' in data.lower():\n            return 'documentary'\n        elif 'action' in data.lower():\n            return 'action'\n        elif 'animation' in data.lower():\n            return 'animation'\n        elif 'comedy' in data.lower():\n            return 'comedy'\n        elif 'western' in data.lower():\n            return  'western'\n        elif 'drama' in data.lower():\n            return 'drama'\n        elif 'fantasy' in data.lower():\n            return 'fantasy'\n        elif 'romance' in data.lower():\n            return 'romance'\n        elif 'music' in data.lower():\n            return 'music'\n        elif 'adventure' in data.lower():\n            return 'adventure'\n        elif 'sport' in data.lower():\n            return 'sport'\n        elif 'reality-tv' in data.lower() or 'talk-show' in data.lower() or 'game-show' in data.lower():\n            return 'tv-show'\n        elif 'history' in data.lower():\n            return 'history'\n        elif 'family' in data.lower():\n            return 'family'\n        elif 'biography' in data.lower():\n            return 'biography'\n        elif 'biography' in data.lower():\n            return 'biography'\n        elif 'mystery' in data.lower():\n            return 'Mystery'\n        elif 'war' in data.lower():\n            return 'war'\n        \nmovie_data['mov_type'] = movie_data['Genres'].apply(check_thriller)\nmovie_data[movie_data['mov_type'].isnull()]['Genres'].unique()\nmovie_data['mov_type'].value_counts().iplot('bar')\n\"\"\"\nObservations:\n\n\nOTT Platforms mostly have movies like documentary, horror, action, and drama\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.9 Best Thriller Movies\/Shows\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\n top_movie = movie_data[movie_data['IMDB_group'] == 9]\ntop_movie['mov_type'].value_counts().iplot(kind='bar')\n\"\"\"\nObservations:\n\n\nIMDB 9+ rating shows available on OTT platforms are documentary and drama type.\n\nlet explore one by one, as per the user's choice\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.8 Movies\/Shows on OTT Platforms\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\ntop_movie[top_movie['Netflix']=='netflix']['mov_type'].value_counts().values\nnet_index = top_movie[top_movie['Netflix']=='netflix']['mov_type'].value_counts().index.tolist()\nnet_val = (top_movie[top_movie['Netflix']=='netflix']['mov_type'].value_counts().values.tolist())\n\nprime_index = top_movie[top_movie['Prime Video']=='prime']['mov_type'].value_counts().index\nprime_val = (top_movie[top_movie['Prime Video']=='prime']['mov_type'].value_counts().values.tolist())\n\ndisney_index = top_movie[top_movie['Disney+']=='disney']['mov_type'].value_counts().index\ndisney_val = (top_movie[top_movie['Disney+']=='disney']['mov_type'].value_counts().values.tolist())\n\nhulu_index = top_movie[top_movie['Hulu']=='hulu']['mov_type'].value_counts().index\nhulu_val = (top_movie[top_movie['Hulu']=='hulu']['mov_type'].value_counts().values.tolist())\ntop_movie[top_movie['mov_type'] == 'animation']\nprint(net_index)\nprint(net_val)\nfig = make_subplots(\nrows=1,cols=2, subplot_titles=[\"Netflix v\/s Prime\"],\nspecs=[[{'type':'pie'},{'type':'pie'}]])\n\nfig.add_trace(go.Pie(labels=net_index, values=net_val, title='Netflix'), row=1,col=1)\nfig.add_trace(go.Pie(labels=prime_index, values=prime_val, title='Prime'), row=1,col=2)\nfig.update_layout(height=800, width=1000, title_text='Top IMDB Movies\/Show')\n\n\"\"\"\nObservations:\n\n\nDOcumentary movies are more available in Prime as compared to Netflix where it has more animation movies\/\n\n\nHere, winner is Netflix, because it has focus equally on all the genre like thriller, sport, animation or documentary. Hence, Audience will binge watch Netflix more because of the varieties available\n\"\"\"\nprint(hulu_index)\nprint(hulu_val)\nprint(disney_index)\nprint(disney_val)\nfig = make_subplots(\nrows=1,cols=2, subplot_titles=[\"Disney v\/s Hulu\"],\nspecs=[[{'type':'pie'},{'type':'pie'}]])\n\nfig.add_trace(go.Pie(labels=hulu_index, values=hulu_val, title='Hulu'), row=1,col=1)\nfig.add_trace(go.Pie(labels=disney_index, values=disney_val, title='DIsney'), row=1,col=2)\nfig.update_layout(height=400, width=600, title_text='Top IMDB Movies\/Show')\n\"\"\"\nObservations:\n\n\nDisney only has SCI-FI movies like avengers movies and similiar. (because it is new in the market of OTT)\nHulu mainly focus on Drama and thriller equally as these two domains are most liked by audiences\n\"\"\"\n# Top THriller movies\ntop_movie.head(3)\nthriller_top = top_movie[top_movie['mov_type'] =='thriller']\nthriller_top[['Title','Netflix','Hulu','Prime Video','Disney+']]\n\"\"\"\nObservations:\n\n\nHighly Recommended THriller movies to watch once in a life.\n\nIt also contains Parasite (Oscar 2019 Best movie) which is available on prime.\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n           4.9 Best Animation Movies\/Show\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nanimation_top = thriller_top = top_movie[top_movie['mov_type'] =='animation']\nanimation_top.head(12)\n\"\"\"\nObservations:\n    \nOnly 9+IMDB Rating movie is : True: Happy Hearts Day - Netflix\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.10 Top Action Movies\/Shows\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\naction_top = thriller_top = top_movie[top_movie['mov_type'] =='action']\naction_top.head(12)\n\"\"\"\nObservations:\n\n\nBest Action Movie:   The Mountain 2   - Prime\n\"\"\"\n\"\"\"\n<a id=\"intro\"><\/a>\n<h3>   \n    <font  color='orange'>\n          <span>\n            4.11 Best SCI-FI Movies\/Shows\n            <\/span>   \n    <\/font>\n<\/h3>\n\"\"\"\nsci_top = thriller_top = top_movie[top_movie['mov_type'] =='sci-fi']\nsci_top.head(12)[['Title','Netflix','Hulu', 'Disney+', 'Prime Video']]\nmovie_data[movie_data['Title'] == 'Avengers: Infinity War'][['Title', 'IMDB_group']]\n\"\"\"\nAvengers has 8 IMDB Rating.\n\nTherefore, we have only considered movies which have exact 9+ IMDB Rating. \n\"\"\"\nmovie_data['Language'].value_counts()\n\"\"\"\nOTT contains almost all the languages in the database\n\"\"\"\nmovie_data['Age'].value_counts().iplot('bar', xTitle='Age Group', yTitle='Movies',title='Age Data')\n\"\"\"\nAs censor board 's rules are not applicable in the OTT platforms, there are certain age restriction in the movies like action, violence, graphical content and many more.\n\n\"\"\"\n\"\"\"\nConclusion\n\"\"\"\n# Netflix movies\n\nmovie_data.head(3)\nnetflix_movies = movie_data[movie_data['Netflix'] == 'netflix']\nhulu_movies = movie_data[movie_data['Hulu'] == 'hulu']\ndisney_movies = movie_data[movie_data['Disney+'] == 'disney']\nprime_movies = movie_data[movie_data['Prime Video'] == 'prime']\nnetflix_movies.drop(['Hulu','Disney+','Prime Video', 'Unnamed: 0'], axis=1, inplace=True)\nhulu_movies.drop(['Netflix','Disney+','Prime Video', 'Unnamed: 0'], axis=1, inplace=True)\ndisney_movies.drop(['Hulu','Netflix','Prime Video', 'Unnamed: 0'], axis=1, inplace=True)\nprime_movies.drop(['Hulu','Disney+','Netflix', 'Unnamed: 0'], axis=1, inplace=True)\nprint(\"Netflix Movies: \", netflix_movies.shape[0])\nprint(\"Hulu Movies: \", hulu_movies.shape[0])\nprint(\"Disney+ Movies: \", disney_movies.shape[0])\nprint(\"Prime Movies: \", prime_movies.shape[0])\n# Netflix Movies\n\"\"\"\n<a id=\"intro\"><\/a>\n<h2>   \n    <font  color='red'>\n          <span>\n            5. Netflix Overview\n            <\/span>   \n    <\/font>\n<\/h2>\n\"\"\"\nnetflix_movies.head(4)\nnetflix_movies['Language'].value_counts()[:30].iplot('bar')\n\"\"\"\nIn Netflix, English language is common in all the movies.\n\"\"\"\n# Runtime\nruntime_net = netflix_movies.sort_values(by='Runtime',ascending=False).head(20)\nruntime_net\n\nsns.barplot(data=runtime_net, y='Title',x='Runtime')\nplt.title('Top Runtime movies on Netflix')\nnet_movies = netflix_movies[netflix_movies['IMDb'] > 8]\nnet_movies_count = net_movies.shape[0]\nprint(\"Movies with IMDB 8+ Rating in netflix: {}\".format(net_movies_count))\nnet_movies = net_movies.sort_values(by='IMDb', ascending=False).head(10)\nsns.barplot(data=net_movies, y='Title',x='IMDb')\nplt.title('Top IMDB movies on Netflix')\nmovie_type = netflix_movies['mov_type'].value_counts().index.tolist()\nprint(movie_type[:9])\n# thriller movies\n\ndef movie_plot(movie) : \n    print(movie)\n    thriller_net = netflix_movies[netflix_movies['mov_type'] == movie]\n    net_movies = thriller_net.sort_values(by='IMDb', ascending=False).head(10)\n    sns.barplot(data=net_movies, y='Title',x='IMDb')\n    plt.title('Top 10 {} movies on Netflix'.format(movie))\n\nmovie_plot('thriller')\nmovie_plot('sci-fi')\nmovie_plot('action')\nmovie_plot('horror')\nmovie_plot('animation')\nhulu_movies.head(4)\ndef run_time(dataframe,ott):\n    runtime_data = dataframe.sort_values(by='Runtime',ascending=False).head(10)\n    sns.barplot(data=runtime_data,y='Title',x='Runtime')\n    plt.title(\"Top Runtime movies on {}\".format(ott))\ndef top_imdb(dataframe,ott):\n    movies = dataframe[dataframe['IMDb'] > 8]\n    movies = movies.sort_values(by='IMDb',ascending=False).head(10)\n    sns.barplot(data=movies,y='Title',x='IMDb')\n    plt.title(\"Top IMDB movies on {}\".format(ott))\ndef movie_plot_plat(movie, dataframe, ott) : \n    print(movie)\n    thriller_net = dataframe[dataframe['mov_type'] == movie]\n    net_movies = thriller_net.sort_values(by='IMDb', ascending=False).head(10)\n    sns.barplot(data=net_movies, y='Title',x='IMDb')\n    plt.title('Top 10 {} movies on {}'.format(movie, ott))\n# HULU\n\nrun_time(hulu_movies,'HULU')\ntop_imdb(hulu_movies, 'HULU')\nmovie_plot_plat('thriller',hulu_movies,'hulu')\nmovie_plot_plat('action',hulu_movies,'hulu')\nmovie_plot_plat('horror',hulu_movies,'hulu')\nmovie_plot_plat('animation',hulu_movies,'hulu')\nmovie_plot_plat('sci-fi',hulu_movies,'hulu')\n# diSNEY+\n\nrun_time(disney_movies,'Disney')\n\n\ntop_imdb(disney_movies, 'Disney')\n\nmovie_plot_plat('thriller',disney_movies,'Disney')\n\nmovie_plot_plat('action',disney_movies,'Disney')\n\nmovie_plot_plat('horror',disney_movies,'Disney')\n\nmovie_plot_plat('animation',disney_movies,'Disney')\n\nmovie_plot_plat('sci-fi',disney_movies,'Disney')\n# Prime\n\nrun_time(prime_movies,'Prime')\ntop_imdb(prime_movies, 'Prime')\n\nmovie_plot_plat('thriller',prime_movies,'Prime')\nmovie_plot_plat('action',prime_movies,'Prime')\nmovie_plot_plat('horror',prime_movies,'Prime')\nmovie_plot_plat('animation',prime_movies,'Prime')\nmovie_plot_plat('sci-fi',prime_movies,'Prime')\n\"\"\"\n![upvote.jpg](attachment:upvote.jpg)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'ca042dcf507eec'}"}
{"id":"31794","text":"\"\"\"\n# IMPORT\n\"\"\"\n# 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns \n%matplotlib inline\n\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u043c\u043e\u0434\u0443\u043b\u0438 \u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0434\u0430\u0442\u043e\u0439 \u0438 \u0432\u0440\u0435\u043c\u0435\u043d\u0435\u043c\nfrom datetime import datetime\nfrom datetime import timedelta\n\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u043c\u043e\u0434\u0443\u043b\u044c \u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u043d\u044b\u043c\u0438 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u044f\u043c\u0438\nimport re\n\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u0443\u0434\u043e\u0431\u043d\u044b\u0439 \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430:\nfrom sklearn.model_selection import train_test_split\n\nimport math # \u0434\u043b\u044f \u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043d\u0430\u0442\u0443\u0440\u0430\u043b\u044c\u043d\u044b\u0445 \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u043e\u0432\n\nimport requests \nfrom bs4 import BeautifulSoup\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\n\nRANDOM_SEED = 42\n!pip freeze > requirements.txt\nDATA_DIR = '\/kaggle\/input\/sf-dst-restaurant-rating\/'\ndf_train = pd.read_csv(DATA_DIR+'\/main_task.csv')\ndf_test = pd.read_csv(DATA_DIR+'kaggle_task.csv')\nsample_submission = pd.read_csv(DATA_DIR+'\/sample_submission.csv')\n\"\"\"\n# DATA\n\"\"\"\ndf_train.head()\ndata[data.City == 'Luxembourg']\n\"\"\"\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0438 \u043d\u0430 \u0442\u043e, \u043a\u0430\u043a\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0435 \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c\u0438\"\"\"\ndf_train.info()\ndf_test.head()\ndf_test.info()\n# \u0414\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0432 \u043e\u0431\u0435\u0438\u0445 \u0447\u0430\u0441\u0442\u044f\u0445 (\u0438 \u0432 \u0442\u0440\u0435\u043d\u0438\u0440\u043e\u0432\u043e\u0447\u043d\u043e\u0439 \u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439) \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u044d\u0442\u0438 \u0447\u0430\u0441\u0442\u0438 \u0432 \u043e\u0434\u0438\u043d \u0434\u0430\u0442\u0430\u0441\u0435\u0442\ndf_train['sample'] = 1 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0442\u0440\u0435\u0439\u043d\ndf_test['sample'] = 0 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u043d\u0430\u0448 \u0442\u0435\u0441\u0442\ndf_test['Rating'] = 0 # \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043d\u0443\u043b\u044f\u043c\u0438 \u0440\u0435\u0439\u0442\u0438\u043d\u0433 \u0432 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0447\u0430\u0441\u0442\u0438, \u0433\u0434\u0435 \u0435\u0433\u043e \u043f\u043e\u043a\u0430 \u043d\u0435\u0442\ndata = df_test.append(df_train, sort=False).reset_index(drop=True) # \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c\ndata.nunique(dropna=False)\n\"\"\"\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0432 \u0434\u0430\u043d\u043d\u044b\u0445\"\"\"\nplt.figure(figsize = (5,5))\nsns.heatmap(data = data.isnull())\nprint(data.Reviews[5], type(data.Reviews[5]))\nprint(data['Cuisine Style'][5], type(data['Cuisine Style'][5]))\n#\u0434\u0430\u043d\u043d\u044b\u0435 \u0433\u0440\u044f\u0437\u043d\u044b\u0435, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 \u0440\u0435\u0432\u044c\u044e \u0438 \u0442\u0438\u043f\u044b \u043a\u0443\u0445\u043d\u0438 \u0441\u043f\u0430\u0440\u0441\u0438\u043b\u0438 \u0441\u043f\u0438\u0441\u043a\u043e\u043c, \u043d\u043e \u043f\u043e \u0444\u043e\u0440\u043c\u0430\u0442\u0443 \u0434\u0430\u043d\u043d\u044b\u0435 \u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435\n\"\"\"\n# DATA CLEANING AND PREPARATION\n\"\"\"\n\"\"\"\u0417\u0430\u043f\u043e\u043b\u043d\u0438\u043c \u043f\u0443\u0441\u0442\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0432\u044c\u044e \u043d\u0443\u043b\u044f\u043c\u0438, \u043d\u043e \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u0433\u043e\u0432\u043e\u0440\u044f\u0449\u0438\u0439 \u043e \u043f\u0443\u0441\u0442\u043e\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0438 \u0440\u0435\u0432\u044c\u044e.\"\"\"\ndata['rev_isna'] = pd.isna(data['Number of Reviews']).astype('uint8')\ndata['Number of Reviews'].fillna(0, inplace=True)\n\"\"\"\u0415\u0449\u0451 \u0440\u0430\u0437 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\"\"\"\ndata.nunique(dropna = False)\n\"\"\"\n#### \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f City\n\u041f\u0440\u0438\u0437\u043d\u0430\u043a - \u0433\u043e\u0440\u043e\u0434 \u043c\u043e\u0436\u043d\u043e \u0440\u0430\u0437\u0431\u0438\u0442\u044c \u043d\u0430 dummy \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435, \u0430 \u0442\u0430\u043a \u0436\u0435 \u043f\u0435\u0440\u0435\u0432\u0435\u0441\u0442\u0438 \u0432 \u0447\u0438\u0441\u043b\u043e \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435 \u0438 \u0432 \u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u044d\u0442\u043e \u043a\u0430\u043a \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u0438\u043b\u0438 \u043d\u043e\u0440\u043c\u0438\u0440\u043e\u0432\u0430\u0442\u044c Ranking \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0433\u043e\u0440\u043e\u0434\u043e\u0432 \u0438 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0441\u043e\u0441\u0442\u0430\u0432\u043d\u043e\u0439.\n\"\"\"\n\"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a rest_ratio, \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435 \u0438 \u043f\u043e\u043f\u0443\u043b\u044f\u0446\u0438\u0438\"\"\"\nrestaurants = data.City.value_counts()\npopulation = pd.Series ({\n    'London':8.982, 'Paris':2.148,'Madrid':6.642,'Barcelona':5.575,\n    'Berlin':3.769,'Milan':1.352,'Rome':2.873, 'Prague':1.309,\n    'Lisbon':0.548, 'Vienna':1.897, 'Amsterdam':0.822, 'Brussels':0.174,\n    'Hamburg':1.899, 'Munich':1.472, 'Lyon':0.513, 'Stockholm':0.976,\n    'Budapest':1.752, 'Warsaw':1.708, 'Dublin':1.388, 'Copenhagen':0.602,\n    'Athens':0.664, 'Edinburgh':0.482, 'Zurich':0.403, 'Oporto':0.214,\n    'Geneva':0.499, 'Krakow':0.760, 'Oslo':0.681, 'Helsinki':0.631,\n    'Bratislava':0.424, 'Luxembourg':0.614, 'Ljubljana':0.293})\nrest_ratio = restaurants \/ 1000 \/ population\ndata['rest_ratio'] = data.apply(lambda x: rest_ratio[x.City], axis = 1)\ndata['dCity'] = data['City']\ndata = pd.get_dummies(data, columns=[ 'dCity'])\ncapitals = ['Mariehamn', 'Tirana', 'Andorra la Vella', 'Vienna',\n            'Minsk', 'Brussels', 'Sarajevo', 'Sofia',\n            'Zagreb', 'Nicosia', 'Prague', 'Copenhagen',\n            'Tallinn', 'T\u00f3rshavn', 'Helsinki', 'Paris',\n            'Berlin', 'Gibraltar', 'Athens', 'St. Peter Port',\n            'Budapest', 'Reykjavik', 'Dublin', 'Douglas',\n            'Rome', 'Saint Helier', 'Pristina', 'Riga',\n            'Vaduz', 'Vilnius', 'Luxembourg', 'Skopje',\n            'Valletta', 'Chi\u0219in\u0103u', 'Monaco', 'Podgorica',\n            'Amsterdam', 'Oslo', 'Warsaw', 'Lisbon',\n            'Bucharest', 'Moscow', 'City of San Marino', 'Belgrade',\n            'Bratislava', 'Ljubljana', 'Madrid', 'Longyearbyen',\n            'Stockholm', 'Bern', 'Kiev', 'London', 'Vatican City']\ndata['is_capital'] = data.City.apply(lambda x: 1 if x in capitals else 0)\n\"\"\"\n#### \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f Price Range\n\u041e\u043d\u0438 \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u044b \u0432 \u043f\u043e\u0440\u044f\u0434\u043a\u0435 \u0432\u043e\u0437\u0440\u0430\u0441\u0442\u0430\u043d\u0438\u044f \u0438\u043b\u0438 \u0443\u0431\u044b\u0432\u0430\u043d\u0438\u044f, \u0437\u043d\u0430\u0447\u0438\u0442, \u0441\u0442\u0440\u043e\u0433\u043e \u0433\u043e\u0432\u043e\u0440\u044f, \u043d\u0435 \u044f\u0432\u043b\u044f\u044e\u0442\u0441\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c\u0438 \u0438 \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u0437\u0430\u043c\u0435\u043d\u0435\u043d\u044b \u043d\u0430 \u0447\u0438\u0441\u043b\u0430 1,2,3\n\"\"\"\ndata['Price Range'].value_counts()\ndata['price_isna'] = pd.isna(data['Price Range']).astype('uint8') #\u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043e\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044f \u0446\u0435\u043d\u043e\u0432\u043e\u0433\u043e \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430\ndata['Price Range'] = data.apply(lambda x: x['Price Range'].replace('$$ - $$$', '2').replace('$$$$', '3').replace('$', '1')\n                                 if type(x['Price Range']) == str else 2,axis = 1)\ndata['Price Range'] = data.apply(lambda x: float(x['Price Range']), axis = 1)\ndata.sample(5)\n\"\"\"\u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u043c \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u043e\u043b\u0435\u0437\u043d\u044b\u0445 \u0444\u0443\u043d\u043a\u0446\u0438\u0439 \u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0434\u0430\u0442\u0430\u043c\u0438 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 \u0440\u0435\u0432\u044c\u044e\"\"\"\n# def d_time (cell): #\u0444\u0443\u043d\u043a\u0446\u0438\u044f \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0440\u0430\u0437\u043d\u0438\u0446\u0443 \u043f\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0438 \u0432 \u0434\u043d\u044f\u0445 \u043c\u0435\u0436\u0434\u0443 \u0434\u0432\u0443\u043c\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u043c\u0438 \u0440\u0435\u0432\u044c\u044e\n#     try:\n#         x = cell.split(',')[2:]\n#         x = pd.Series(x).apply(lambda x: x.replace('[','').replace(']','').replace(\"'\",'').replace(' ',''))\n#         x = x.apply(lambda x: datetime.strptime(x,'%d\/%m\/%Y'))\n#         delta_x=x[1]-x[0]\n#         return abs(delta_x.days)\n#     except:\n#         return -1 # \u0447\u0442\u043e\u0431\u044b \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f NaN \u043d\u0435 \u043c\u0435\u0448\u0430\u043b\u0438 \u0438 \u0432\u044b\u0434\u0435\u043b\u044f\u043b\u0438\u0441\u044c \u043a\u0430\u0440\u0434\u0438\u043d\u0430\u043b\u044c\u043d\u043e \ndef fresh_date (cell): #\u0424\u0443\u043d\u043a\u0446\u0438\u044f, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u0435\u0442 \u0434\u0430\u0442\u0443 \u0441\u0430\u043c\u043e\u0433\u043e \u0441\u0432\u0435\u0436\u0435\u0433\u043e \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u043d\u043e\u0433\u043e \u043e\u0442\u0437\u044b\u0432\u0430 \u0434\u043b\u044f \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430\"\"\"\n    try:\n        x = cell.split(',')[2:]\n        x = pd.Series(x).apply(lambda x: x.replace('[','').replace(']','').replace(\"'\",'').replace(' ',''))\n        x = x.apply(lambda x: datetime.strptime(x,'%d\/%m\/%Y'))\n        fresh_x = max(x[0],x[1])\n        return fresh_x\n    except:\n        return None\n\"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0441\u0438\u043d\u0442\u0435\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0434\u0430\u0442\u044b \u0441\u0430\u043c\u043e\u0433\u043e \u0441\u0432\u0435\u0436\u0435\u0433\u043e \u043e\u0442\u0437\u044b\u0432\u0430 \u043e \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0435\"\"\"\ndata['rev_date'] = data.apply(lambda x: fresh_date(x['Reviews']), axis = 1)\ndata['rev_date'] = data['rev_date'].apply(lambda x: (x - datetime.now()).days)\ndata['rev_date'].fillna(data['rev_date'].mean(), inplace = True)\ndata['rev_date'] = (data['rev_date'] - data['rev_date'].mean())\ndata['rev_date'] = (data['rev_date'] \/ np.linalg.norm(data['rev_date']))\n\"\"\"\n#### \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a Cuisine Style \u0438 \u0440\u0430\u0437\u0431\u0435\u0440\u0451\u043c \u0435\u0433\u043e \u043d\u0430 Dummy-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435\n\"\"\"\n\"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u0434\u043b\u044f \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0433\u0434\u0435 \u0442\u0438\u043f \u043a\u0443\u0445\u043d\u0438 \u043d\u0435 \u0443\u043f\u043e\u043c\u044f\u043d\u0443\u0442\"\"\"\ndata['cuisine_isna'] = pd.isna(data['Cuisine Style']).astype('uint8')\n\"\"\"\u041e\u0447\u0438\u0441\u0442\u0438\u043c \u0441\u0442\u0440\u043e\u043a\u0438 \u043e\u0442 \u0432\u0441\u0435\u0433\u043e \u043b\u0438\u0448\u043d\u0435\u0433\u043e, \u0432\u043a\u043b\u044e\u0447\u0430\u044f \u043f\u0440\u043e\u0431\u0435\u043b\u044b \u0438 \u043e\u0441\u0442\u0430\u0432\u0438\u043c \u0442\u043e\u043b\u044c\u043a\u043e \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u0438-\u0437\u0430\u043f\u044f\u0442\u044b\u0435\"\"\"\ndata['Cuisine Style'] = data.apply(lambda x: x['Cuisine Style'].replace('[','').replace(']','').replace(\"'\",'').replace(' ','') \n                                   if type(x['Cuisine Style']) != float else x['Cuisine Style'], axis = 1)\n\n\"\"\"\u0420\u0430\u0437\u0431\u0435\u0440\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d \u0441\u0442\u0440\u043e\u043a\u043e\u0439, \u043d\u0430 \u0434\u0430\u043c\u043c\u0438-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u043f\u043e \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044e\"\"\"\nstyles = data['Cuisine Style'].str.get_dummies(',').sum().sort_values(ascending = False)\nstyles_drop = [x for x in styles.index if styles[x] < 100] # \u0438\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0438\u043c\u0441\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u043c\u0438 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u043c\u0435\u044e\u0442 \u0431\u043e\u043b\u044c\u0448\u0435 1000 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432\n\n\"\"\"\u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0438\u0432\u0448\u0438\u0439\u0441\u044f \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \"\"\"\ndata = data.join(data['Cuisine Style'].str.get_dummies(',').drop(styles_drop, axis = 1), how = 'left')\n\nstyles[:50]\n\"\"\"\n\u041d\u0430\u043f\u0438\u0448\u0435\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e-\u0444\u0438\u043b\u043b\u0435\u0440, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0434\u043e\u0437\u0430\u043f\u043e\u043b\u043d\u0438\u0442 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0432 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u0445 Cuisine Styles \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 Review.\n\"\"\"\ndata.VegetarianFriendly.value_counts() #\u0434\u043b\u044f \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438 \u043f\u043e\u0441\u0447\u0438\u0442\u0430\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0435\u0433\u0435\u0442\u0430\u0440\u0438\u0430\u043d\u0441\u043a\u0438\u0445 \u0437\u0430\u0432\u0435\u0434\u0435\u043d\u0438\u0439 \u0434\u043e \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438\npattern = re.compile('[A-Z][a-z]*') #\u0440\u0435\u0433\u0443\u043b\u044f\u0440\u043d\u043e\u0435 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u0432\u044b\u0442\u0430\u0449\u0438\u0442 \u0438\u0437 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0442\u0435\u0433\u0438\ndef fill_styles (row):\n    for style in styles.drop(styles_drop).index:\n        x = pattern.match(style)[0]\n        try:\n            if x.lower() in row.Reviews.lower(): #\u0438\u0449\u0435\u043c \u0442\u0435\u0433\u0438 \u0432 \u043e\u0442\u0437\u044b\u0432\u0430\u0445\n                row[style] = 1\n        except:\n            continue\n    return row\ndata = data.apply(lambda x: fill_styles(x),axis = 1)\ndata.VegetarianFriendly.value_counts() # \u0438 \u043f\u043e\u0441\u043b\u0435\nlocal = pd.Series ({\n    'London':'British', 'Paris':'French','Madrid':'Spanish','Barcelona':'Spanish',\n    'Berlin':'German','Milan':'Italian','Rome':'Italian', 'Prague':'Czech',\n    'Lisbon':'Portuguese', 'Vienna':'Austrian', 'Amsterdam':'Dutch', 'Brussels':'Belgian',\n    'Hamburg':'German', 'Munich':'German', 'Lyon':'French', 'Stockholm':'Scandinavian',\n    'Budapest':'Hungarian', 'Warsaw':'Polish', 'Dublin':'British', 'Copenhagen':'Scandinavian',\n    'Athens':'Greek', 'Edinburgh':'British', 'Zurich':'CentralEuropean', 'Oporto':'Portuguese',\n    'Geneva':'EasternEuropean', 'Krakow':'Polish', 'Oslo':'Scandinavian', 'Helsinki':'Scandinavian',\n    'Bratislava':'EasternEuropean', 'Luxembourg':'French', 'Ljubljana':'EasternEuropean'})\ndata['is_local'] = data.apply(lambda x: 1 if x[local[x.City]] == 1 else 0, axis = 1)\ndata.sample(5)\n\"\"\"\n# EDA\n\"\"\"\ndf_train = data[data['sample'] == 1]\n\"\"\"\u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 ranking\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(20, 10));\ndf_train['Ranking'].hist(bins=100, ax=axes[0])\ndf_train.boxplot(column='Ranking', ax=axes[1])\n\"\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 Ranking \u043f\u043e \u0433\u043e\u0440\u043e\u0434\u0430\u043c (\u0441\u043b\u0435\u0432\u0430) \u0438 \u0442\u0438\u043f\u0430\u043c \u043a\u0443\u0445\u043e\u043d\u044c (\u0441\u043f\u0440\u0430\u0432\u0430)\"\nfig, axes = plt.subplots(1, 2, figsize=(20, 10));\nfor x in (df_train['City'].value_counts())[0:10].index:\n    df_train['Ranking'][df_train['City'] == x].hist(bins=100, ax = axes[0])\nfor x in styles[0:10].index:\n    df_train[df_train[x] == 1]['Ranking'].hist(bins = 100, ax = axes[1])\nplt.show()\n\"\"\"\n\u041c\u044b \u0432\u0438\u0434\u0438\u043c,\u0447\u0442\u043e \u043f\u043e \u0433\u043e\u0440\u043e\u0434\u0430\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a ranking \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0430 \u043f\u043e \u0432\u0438\u0434\u0430\u043c \u043a\u0443\u0445\u043e\u043d\u044c \u044d\u043a\u0441\u043f\u043e\u043d\u0435\u043d\u0446\u0438\u0430\u043b\u044c\u043d\u043e.\n\"\"\"\ndf_train['sqrt_ranking'] = data.apply(lambda x: x.Ranking**(1\/3), axis = 1)\n\"\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 Ranking \u043f\u043e \u0433\u043e\u0440\u043e\u0434\u0430\u043c (\u0441\u043b\u0435\u0432\u0430) \u0438 \u0442\u0438\u043f\u0430\u043c \u043a\u0443\u0445\u043e\u043d\u044c (\u0441\u043f\u0440\u0430\u0432\u0430)\"\nfig, axes = plt.subplots(1, 2, figsize=(20, 10));\nfor x in (df_train['City'].value_counts())[0:10].index:\n    df_train['sqrt_ranking'][df_train['City'] == x].hist(bins=100, ax = axes[0])\nfor x in styles[0:10].index:\n    df_train[df_train[x] == 1]['sqrt_ranking'].hist(bins = 100, ax = axes[1])\nplt.show()\n\n#\u0432\u0438\u0434\u0438\u043c, \u0447\u0442\u043e \u043a\u0443\u0431\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043a\u043e\u0440\u0435\u043d\u044c \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430 Ranking \u043f\u043e \u043a\u0443\u0445\u043d\u044f\u043c \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e, \u0432\u043e\u0437\u044c\u043c\u0435\u043c \u0435\u0433\u043e \u0432 \u0441\u0435\u0442 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\ndf_train['ln_ranking'] = data.apply(lambda x: math.log(x.Ranking), axis = 1)\n\"\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043d\u0430\u0442\u0443\u0440\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430 Ranking \u043f\u043e \u0433\u043e\u0440\u043e\u0434\u0430\u043c (\u0441\u043b\u0435\u0432\u0430) \u0438 \u0442\u0438\u043f\u0430\u043c \u043a\u0443\u0445\u043e\u043d\u044c (\u0441\u043f\u0440\u0430\u0432\u0430)\"\nfig, axes = plt.subplots(1, 2, figsize=(20, 10));\nfor x in (df_train['City'].value_counts())[0:10].index:\n    df_train['ln_ranking'][df_train['City'] == x].hist(bins=100, ax = axes[0])\nfor x in styles[0:10].index:\n    df_train[df_train[x] == 1]['ln_ranking'].hist(bins = 100, ax = axes[1])\nplt.show()\n\n\"\"\"\n#### \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u043c\u0430\u0442\u0440\u0438\u0446\u0443 \u043a\u043e\u0440\u0435\u043b\u043b\u044f\u0446\u0438\u0438\n\"\"\"\nc_mat = data.drop(['sample'], axis=1).corr()\nplt.rcParams['figure.figsize'] = (30,25)\nsns.heatmap(c_mat)\nprint('\u0420\u0430\u043d\u0433 \u043c\u0430\u0442\u0440\u0438\u0446\u044b - {}, det(c_mat) = {}'.format(np.linalg.matrix_rank(c_mat), np.linalg.det(c_mat)))\nc_mat.shape\n\"\"\"\n\u0420\u0430\u043d\u0433 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u043a\u043e\u0440\u0435\u043b\u043b\u044f\u0446\u0438\u0439 \u043d\u0435 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c \u0431\u043b\u0438\u0437\u043e\u043a \u043a \u043d\u0443\u043b\u044e, \u043c\u0430\u0442\u0440\u0438\u0446\u0430 \u043f\u043b\u043e\u0445\u043e \u043e\u0431\u0443\u0441\u043b\u043e\u0432\u043b\u0435\u043d\u0430, \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043c\u0443\u043b\u044c\u0442\u0438\u043a\u043e\u043b\u043b\u0438\u043d\u0435\u0430\u0440\u043d\u044b.\n\u041c\u044b \u0432\u0438\u0434\u0438\u043c, \u0447\u0442\u043e \u0441\u0438\u043b\u044c\u043d\u043e \u0441\u043a\u043e\u0440\u0435\u043b\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u044b \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 price_isna \u0438 cuisine_isna, Bar \u0438 Pub, Japanese \u0438 Sushi\n\u041c\u043e\u0436\u0435\u043c \u0438\u0445 \u043f\u043e\u043f\u0430\u0440\u043d\u043e \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u0442\u044c, \u043f\u0435\u0440\u0432\u0443\u044e \u043f\u0430\u0440\u0443 \u043f\u043e\u0434\u0435\u043b\u0438\u0442\u044c \u0434\u0440\u0443\u0433 \u043d\u0430 \u0434\u0440\u0443\u0433\u0430, \u0430 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0435 \u043b\u043e\u0433\u0438\u0447\u0435\u0441\u043a\u0438 \u0441\u043b\u043e\u0436\u0438\u0442\u044c (\u0418\u041b\u0418)\n\"\"\"\n# \"\"\"\u041d\u043e\u0440\u043c\u0430\u043b\u0438\u0437\u0443\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a Ranking \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0437\u0430\u0432\u0435\u0434\u0435\u043d\u0438\u0439 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435\"\"\"\n# data['nRanking'] = data.Ranking \/ data.nCity \n# data.drop(['Ranking','nCity'], axis = 1, inplace = True)\n# #\u0431\u044b\u043b\u043e \u0432 \u0441\u0442\u0430\u0440\u043e\u0439 \u0440\u0435\u0432\u0438\u0437\u0438\u0438, nCity \u0437\u0430\u043c\u0435\u043d\u0435\u043d\u043e \u043d\u0430 rest_ratio\n\"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u0431\u0430\u0440\u044b \u0438 \u043f\u0430\u0431\u044b, \u044f\u043f\u043e\u043d\u0441\u043a\u0443\u044e \u043a\u0443\u0445\u043d\u044e \u0438 \u0441\u0443\u0448\u0438\"\"\"\ndata['Bar_Pub'] = data.Bar | data.Pub\ndata.drop(['Bar','Pub'], axis = 1, inplace = True)\n\ndata['Japan_Sushi'] = data.Japanese | data.Sushi\ndata.drop(['Japanese','Sushi'], axis = 1, inplace = True)\n\"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043e\u0431 \u043e\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u0438 \u0446\u0435\u043d\u043e\u0432\u043e\u0433\u043e \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u0438 \u043a\u0443\u0445\u043d\u0438 \u0432 \u043e\u0434\u0438\u043d \u043f\u0440\u0438\u0437\u043d\u0430\u043a data_missing\"\"\"\ndata['data_missing'] = data.cuisine_isna | data.price_isna\ndata.drop(['cuisine_isna','price_isna'], axis = 1, inplace = True)\n\"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u0432\u0435\u0433\u0430\u043d\u043e\u0432 \u0441 \u0432\u0435\u0433\u0435\u0442\u0430\u0440\u0438\u0430\u043d\u0446\u0430\u043c\u0438\"\"\"\ndata['vegan_and_veg'] = data.VeganOptions | data.VegetarianFriendly\ndata.drop(['VeganOptions','VegetarianFriendly'], axis = 1, inplace = True)\n# #\u0435\u0449\u0451 \u0440\u0430\u0437 \u0432\u0437\u0433\u043b\u044f\u043d\u0443\u0432 \u043d\u0430 \u043c\u0430\u0442\u0440\u0438\u0446\u0443 \u043a\u043e\u0440\u0435\u043b\u043b\u044f\u0446\u0438\u0438, \u043c\u043e\u0436\u043d\u043e \u0443\u0432\u0438\u0434\u0435\u0442\u044c, \u0447\u0442\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a data_missing \u0432\u044b\u0441\u043e\u043a\u043e \u043e\u0431\u0440\u0430\u0442\u043d\u043e \u0441\u043a\u043e\u0440\u0435\u043b\u043b\u0438\u0440\u043e\u0432\u0430\u043d \u0441 Price Range (-0.9)\n# c_mat = data.drop(['sample'], axis=1).corr()\n# print(c_mat['Price Range'].data_missing)\n# #\u043c\u043e\u0436\u043d\u043e \u0438\u0437\u0431\u0430\u0432\u0438\u0442\u044c\u0441\u044f \u043e\u0442 data_missing\n# data.drop(['data_missing'], axis = 1, inplace = True)\n\n# \u0442\u0430\u043a \u0431\u044b\u043b\u043e \u0432 \u0441\u0442\u0430\u0440\u043e\u0439 \u0440\u0435\u0432\u0438\u0437\u0438\u0438\nc_mat = data.drop(['sample'], axis=1).corr() #\u043f\u0440\u043e\u0432\u0435\u0440\u0438\u043c \u043d\u0430\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043f\u043e\u043c\u0435\u043d\u044f\u043b\u043e\u0441\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044f \u043c\u0430\u0442\u0440\u0438\u0446\u044b\nprint('\u0420\u0430\u043d\u0433 \u043c\u0430\u0442\u0440\u0438\u0446\u044b - {}, det(c_mat) = {}'.format(np.linalg.matrix_rank(c_mat), np.linalg.det(c_mat)))\nc_mat.shape\nc_mat = data.drop(['sample'], axis=1).corr()\nplt.rcParams['figure.figsize'] = (30,25)\nsns.heatmap(c_mat)\ndata.drop('is_capital', axis = 1, inplace = True)\n\"\"\"\n# Data Preprocessing\n\u0417\u0430\u0432\u0435\u0440\u043d\u0435\u043c \u043f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0443 \u0432 \u043e\u0434\u043d\u0443 \u0444\u0443\u043d\u043a\u0446\u0438\u044e\n\"\"\"\n#\u0438\u043c\u043f\u043e\u0440\u0442\u0438\u0440\u0443\u0435\u043c \u0432\u0441\u0435 \u0437\u0430\u043d\u043e\u0432\u043e\ndf_train = pd.read_csv(DATA_DIR+'\/main_task.csv')\ndf_test = pd.read_csv(DATA_DIR+'\/kaggle_task.csv')\ndf_train['sample'] = 1 # \u0442\u0440\u0435\u0439\u043d\ndf_test['sample'] = 0 # \u0442\u0435\u0441\u0442\ndf_test['Rating'] = 0 # \u0442\u0430\u0440\u0433\u0435\u0442\n\ndata = df_test.append(df_train, sort=False).reset_index(drop=True) # \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c\ndata.info()\ndef preproc_data(df_input):\n    '''includes several functions to pre-process the predictor data.'''\n    \n    df_output = df_input.copy()\n    \n    # ################### 1. \u041f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 ############################################################## \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043d\u0435 \u043d\u0443\u0436\u043d\u044b\u0435 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\n    df_output.drop(['Restaurant_id','ID_TA','URL_TA'], axis = 1, inplace=True)\n    \n    \n    # ################### 2. NAN ############################################################## \n    \"\"\"\u0417\u0430\u043f\u043e\u043b\u043d\u0438\u043c \u043f\u0443\u0441\u0442\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0432\u044c\u044e \u043d\u0443\u043b\u044f\u043c\u0438, \u043d\u043e \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a, \u0433\u043e\u0432\u043e\u0440\u044f\u0449\u0438\u0439 \u043e \u043f\u0443\u0441\u0442\u043e\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0438 \u0440\u0435\u0432\u044c\u044e.\"\"\"\n    df_output['rev_isna'] = pd.isna(df_output['Number of Reviews']).astype('uint8')\n    df_output['Number of Reviews'].fillna(0, inplace=True)\n    \n    \n    # ################### 3. Encoding ##############################################################\n    \"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c dummy-\u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0433\u043e\u0440\u043e\u0434\u043e\u0432\"\"\"\n    df_output['dCity'] = df_output.City\n    df_output = pd.get_dummies(df_output, columns=['dCity'], dummy_na=True)\n    \n    df_output['price_isna'] = pd.isna(df_output['Price Range']).astype('uint8') #\u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043e\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044f \u0446\u0435\u043d\u043e\u0432\u043e\u0433\u043e \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430\n    df_output['Price Range'] = df_output.apply(lambda x: x['Price Range'].replace('$$ - $$$', '2').replace('$$$$', '3').replace('$', '1')\n                                 if type(x['Price Range']) == str else 2,axis = 1)\n    df_output['Price Range'] = df_output.apply(lambda x: float(x['Price Range']), axis = 1)\n    \n    \"\"\"\u041e\u0447\u0438\u0441\u0442\u0438\u043c \u0441\u0442\u0440\u043e\u043a\u0443 \u0441\u043e \u0441\u0442\u0438\u043b\u044f\u043c\u0438 \u043a\u0443\u0445\u043d\u0438 \u043e\u0442 \u043b\u0438\u0448\u043d\u0438\u0445 \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432\"\"\"\n    df_output['cuisine_isna'] = pd.isna(data['Cuisine Style']).astype('uint8')\n    df_output['Cuisine Style'] = df_output.apply(lambda x: x['Cuisine Style'].replace('[','').replace(']','').replace(\"'\",'').replace(' ','') \n                                   if type(x['Cuisine Style']) != float else x['Cuisine Style'], axis = 1)\n\n    \"\"\"\u0420\u0430\u0437\u0431\u0435\u0440\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d \u0441\u0442\u0440\u043e\u043a\u043e\u0439, \u043d\u0430 \u0434\u0430\u043c\u043c\u0438-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u043f\u043e \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044e\"\"\"\n    styles = df_output['Cuisine Style'].str.get_dummies(',').sum().sort_values(ascending = False)\n    styles_drop = [x for x in styles.index if styles[x] < 100] # \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0438\u043c\u0441\u044f \u0442\u043e\u043b\u044c\u043a\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u043c\u0438 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u043c\u0435\u044e\u0442 \u0431\u043e\u043b\u044c\u0448\u0435 100 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432\n\n    \"\"\"\u041f\u0440\u0438\u0441\u043e\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0438\u0432\u0448\u0438\u0439\u0441\u044f \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c \u043d\u043e\u0432\u044b\u0445 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \"\"\"\n    df_output = df_output.join(df_output['Cuisine Style'].str.get_dummies(',').drop(styles_drop, axis = 1), how = 'left')\n    \n    \"\"\"\u0414\u043e\u0437\u0430\u043f\u043e\u043b\u043d\u0438\u043c \u043f\u043e\u043b\u0443\u0447\u0438\u0432\u0448\u0438\u0435\u0441\u044f dummy-\u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0440\u0435\u0432\u044c\u044e\"\"\"\n    df_output = df_output.apply(lambda x: fill_styles(x),axis = 1)\n    \n    \"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043e\u0431 \u043e\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u0438 \u0446\u0435\u043d\u043e\u0432\u043e\u0433\u043e \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u0430 \u0438 \u043a\u0443\u0445\u043d\u0438 \u0432 \u043e\u0434\u0438\u043d \u043f\u0440\u0438\u0437\u043d\u0430\u043a data_missing\"\"\"\n    df_output['data_missing'] = df_output.cuisine_isna | df_output.price_isna\n    df_output.drop(['cuisine_isna','price_isna'], axis = 1, inplace = True)\n    \n    \n    # ################### 4. Feature Engineering ####################################################\n    \n    \"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a rest_ratio, \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435 \u0438 \u043f\u043e\u043f\u0443\u043b\u044f\u0446\u0438\u0438\"\"\"\n    population = pd.Series ({\n    'London':8.982, 'Paris':2.148,'Madrid':6.642,'Barcelona':5.575,\n    'Berlin':3.769,'Milan':1.352,'Rome':2.873, 'Prague':1.309,\n    'Lisbon':0.548, 'Vienna':1.897, 'Amsterdam':0.822, 'Brussels':0.174,\n    'Hamburg':1.899, 'Munich':1.472, 'Lyon':0.513, 'Stockholm':0.976,\n    'Budapest':1.752, 'Warsaw':1.708, 'Dublin':1.388, 'Copenhagen':0.602,\n    'Athens':0.664, 'Edinburgh':0.482, 'Zurich':0.403, 'Oporto':0.214,\n    'Geneva':0.499, 'Krakow':0.760, 'Oslo':0.681, 'Helsinki':0.631,\n    'Bratislava':0.424, 'Luxembourg':0.614, 'Ljubljana':0.293})\n    rest_ratio = restaurants \/ 1000 \/ population\n    df_output['rest_ratio'] = df_output.apply(lambda x: rest_ratio[x.City], axis = 1)\n    \n    local = pd.Series ({\n    'London':'British', 'Paris':'French','Madrid':'Spanish','Barcelona':'Spanish',\n    'Berlin':'German','Milan':'Italian','Rome':'Italian', 'Prague':'Czech',\n    'Lisbon':'Portuguese', 'Vienna':'Austrian', 'Amsterdam':'Dutch', 'Brussels':'Belgian',\n    'Hamburg':'German', 'Munich':'German', 'Lyon':'French', 'Stockholm':'Scandinavian',\n    'Budapest':'Hungarian', 'Warsaw':'Polish', 'Dublin':'British', 'Copenhagen':'Scandinavian',\n    'Athens':'Greek', 'Edinburgh':'British', 'Zurich':'\u0421entralEuropean', 'Oporto':'Portuguese',\n    'Geneva':'EasternEuropean', 'Krakow':'Polish', 'Oslo':'Scandinavian', 'Helsinki':'Scandinavian',\n    'Bratislava':'EasternEuropean', 'Luxembourg':'French', 'Ljubljana':'EasternEuropean'})\n    df_output['is_local'] = df_output.apply(lambda x: 1 if x[local[x.City]] == 1 else 0,axis = 1)\n    \n    \"\"\"C\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a is_capital - \u0441\u0442\u043e\u043b\u0438\u0446\u0430 \u043b\u0438 \u0433\u043e\u0440\u043e\u0434\"\"\"\n    capitals = ['Mariehamn', 'Tirana', 'Andorra la Vella', 'Vienna',\n            'Minsk', 'Brussels', 'Sarajevo', 'Sofia',\n            'Zagreb', 'Nicosia', 'Prague', 'Copenhagen',\n            'Tallinn', 'T\u00f3rshavn', 'Helsinki', 'Paris',\n            'Berlin', 'Gibraltar', 'Athens', 'St. Peter Port',\n            'Budapest', 'Reykjavik', 'Dublin', 'Douglas',\n            'Rome', 'Saint Helier', 'Pristina', 'Riga',\n            'Vaduz', 'Vilnius', 'Luxembourg', 'Skopje',\n            'Valletta', 'Chi\u0219in\u0103u', 'Monaco', 'Podgorica',\n            'Amsterdam', 'Oslo', 'Warsaw', 'Lisbon',\n            'Bucharest', 'Moscow', 'City of San Marino', 'Belgrade',\n            'Bratislava', 'Ljubljana', 'Madrid', 'Longyearbyen',\n            'Stockholm', 'Bern', 'Kiev', 'London', 'Vatican City']\n    df_output['is_capital'] = df_output.City.apply(lambda x: 1 if x in capitals else 0)\n    \n#     \"\"\"\u041d\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a Ranking \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435\"\"\"\n#     df_output['pRanking'] = df_output.apply(lambda x: x.Ranking \/ population[x.City], axis = 1)\n    \"\"\"\u041d\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a Ranking \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0438 \u043b\u044e\u0434\u0435\u0439 \u0432 \u0433\u043e\u0440\u043e\u0434\u0435\"\"\"\n    df_output['nRanking'] = df_output.apply(lambda x: x.Ranking \/ restaurants[x.City],\n                                            axis = 1)\n    df_output['\u0441uberoot_rank'] = df_output.apply(lambda x: x.Ranking**(1\/3) \/ restaurants[x.City], axis = 1)\n    df_output['ln_ranking'] = df_output.apply(lambda x: math.log(x.Ranking), axis = 1)\n    df_output.drop('Ranking', axis = 1, inplace = True) #\u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0434\u0440\u043e\u043f\u043d\u0435\u043c\n        \n    \"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u0431\u0430\u0440\u044b \u0438 \u043f\u0430\u0431\u044b, \u044f\u043f\u043e\u043d\u0441\u043a\u0443\u044e \u043a\u0443\u0445\u043d\u044e \u0438 \u0441\u0443\u0448\u0438\"\"\"\n    df_output['Bar_Pub'] = df_output.Bar | df_output.Pub\n    df_output.drop(['Bar','Pub'], axis = 1, inplace = True)\n\n    df_output['Japan_Sushi'] = df_output.Japanese | df_output.Sushi\n    df_output.drop(['Japanese','Sushi'], axis = 1, inplace = True)\n    \n    \"\"\"\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u043c \u0432\u0435\u0433\u0430\u043d\u043e\u0432 \u0441 \u0432\u0435\u0433\u0435\u0442\u0430\u0440\u0438\u0430\u043d\u0446\u0430\u043c\u0438\"\"\"\n    df_output['vegan_and_veg'] = df_output.VeganOptions | df_output.VegetarianFriendly\n    df_output.drop(['VeganOptions','VegetarianFriendly'], axis = 1, inplace = True)\n    \n    \"\"\"\u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0441\u0438\u043d\u0442\u0435\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u0434\u0430\u0442\u044b \u0441\u0430\u043c\u043e\u0433\u043e \u0441\u0432\u0435\u0436\u0435\u0433\u043e \u043e\u0442\u0437\u044b\u0432\u0430 \u043e \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0435\"\"\"\n    df_output['rev_date'] = df_output.apply(lambda x: fresh_date(x['Reviews']), axis = 1)\n    df_output['rev_date'] = df_output['rev_date'].apply(lambda x: (x - datetime.now()).days)\n    df_output['rev_date'].fillna(df_output['rev_date'].mean(), inplace = True)\n    df_output['rev_date'] = df_output['rev_date'] - df_output['rev_date'].mean()\n    df_output['rev_date'] = (df_output['rev_date'] \/ np.linalg.norm(df_output['rev_date'])) * 10**15\n    \n    df_output['rev_ratio'] = df_output.apply(lambda x: x['Number of Reviews'] \/ population[x.City],\n                                            axis = 1)\n   \n    \n    \n    # ################### 5. Clean #################################################### \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0435\u0449\u0435 \u043d\u0435 \u0443\u0441\u043f\u0435\u043b\u0438 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c, \n    # \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u0445 \u0441 dtypes \"object\" \u043e\u0431\u0443\u0447\u0430\u0442\u044c\u0441\u044f \u043d\u0435 \u0431\u0443\u0434\u0435\u0442, \u043f\u0440\u043e\u0441\u0442\u043e \u0432\u044b\u0431\u0435\u0440\u0438\u043c \u0438\u0445 \u0438 \u0443\u0434\u0430\u043b\u0438\u043c\n    object_columns = [s for s in df_output.columns if df_output[s].dtypes == 'object']\n    df_output.drop(object_columns, axis = 1, inplace=True)\n    \n    # ################### 6. Essential feature set  #################################################### \n#     features = ['nRanking','Rating','Number of Reviews', 'rest_ratio', 'rev_ratio', 'rev_date',\n#                  '\u0441uberoot_rank', 'dCity_Rome','dCity_Madrid', 'Price Range', 'data_missing',\n#                 'dCity_Amsterdam','sample']\n#     df_output = df_output[features]\n    \n    return df_output\n\"\"\"\n# ML\n\"\"\"\ndf_preproc = preproc_data(data)\ndf_preproc.sample(10)\n\"\"\"\u0415\u0449\u0451 \u0440\u0430\u0437 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0432\u0441\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438, \u0443\u0431\u0435\u0434\u0438\u043c\u0441\u044f \u0447\u0442\u043e \u043d\u0435\u0442 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432\"\"\"\ndf_preproc.info()\n# \u0422\u0435\u043f\u0435\u0440\u044c \u0432\u044b\u0434\u0435\u043b\u0438\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u0443\u044e \u0447\u0430\u0441\u0442\u044c\ntrain_data = df_preproc.query('sample == 1').drop(['sample'], axis=1)\ntest_data = df_preproc.query('sample == 0').drop(['sample'], axis=1)\n\ny = train_data.Rating.values            # \u0442\u0430\u0440\u0433\u0435\u0442\nX = train_data.drop(['Rating'], axis=1)\n# \u0440\u0430\u0437\u043e\u0431\u044c\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435, \u0432\u044b\u0434\u0435\u043b\u0438\u043c 20% \u043d\u0430 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044e\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_SEED)\ntest_data.shape, train_data.shape, X.shape, X_train.shape, X_test.shape # \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u043c\n\"\"\"\n# ML\n\"\"\"\n# \u0418\u043c\u043f\u043e\u0440\u0442\u0438\u0440\u0443\u0435\u043c \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u044b\u0435 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438:\nfrom sklearn.ensemble import RandomForestRegressor # \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f \u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u043c\u043e\u0434\u0435\u043b\u0438\nfrom sklearn import metrics # \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u043e\u0446\u0435\u043d\u043a\u0438 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 \u043c\u043e\u0434\u0435\u043b\u0438\n# \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043c\u043e\u0434\u0435\u043b\u044c\nregr = RandomForestRegressor(n_estimators=100)\n\n# \u041e\u0431\u0443\u0447\u0430\u0435\u043c \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043d\u0430\u0431\u043e\u0440\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\nregr.fit(X_train, y_train)\n\n# \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043e\u0431\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n# \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0432 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e y_pred\ny_pred = regr.predict(X_test)\ny_pred = (y_pred * 2).round() \/ 2\n# \u0421\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u0435\u043c \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f (y_pred) \u0441 \u0440\u0435\u0430\u043b\u044c\u043d\u044b\u043c\u0438 (y_test), \u0438 \u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043e\u043d\u0438 \u0432 \u0441\u0440\u0435\u0434\u043d\u0435\u043c \u043e\u0442\u043b\u0438\u0447\u0430\u044e\u0442\u0441\u044f\n# C\u0447\u0438\u0442\u0430\u0435\u043c Mean Absolute Error (MAE)\nprint('MAE:', metrics.mean_absolute_error(y_test, y_pred))\n# \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0432\u0430\u0436\u043d\u043e\u0441\u0442\u044c \u0444\u0438\u0447\nplt.rcParams['figure.figsize'] = (10,10)\nfeat_importances = pd.Series(regr.feature_importances_, index=X.columns)\nfeat_importances.nlargest(15).plot(kind='barh')\n\"\"\"\n# Submission\n\"\"\"\ntest_data.sample(10)\ntest_data = test_data.drop(['Rating'], axis=1)\nsample_submission\npredict_submission = regr.predict(test_data)\npredict_submission = (predict_submission * 2).round() \/ 2\npredict_submission\nsample_submission['Rating'] = predict_submission\nsample_submission.to_csv('submission.csv', index=False)\nsample_submission.head(10)","meta":"{'source': 'AI4Code', 'id': '3a8a78c1da979b'}"}
{"id":"26016","text":"# 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\n\"\"\"\n# **Imports**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nsns.set_style('whitegrid')\ndftrain = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/train.csv')\ndftest = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/test.csv')\n\"\"\"\n# **Checkout Data Structures**\n\"\"\"\ndftrain.head()\n#shape of train dataset\ndftrain.shape\ndftrain.describe().transpose()\n#average SalePrice is $180,921\ndftrain.info()\n#mixture of int, obj and some float\n#shape of test dataset\ndftest.shape\n#see distribution of SalesPrice\nplt.figure(figsize=(10,6))\nsns.histplot(dftrain['SalePrice'])\n#most houses are around $100,000 to $200,000\n#seem like outlier starts at >450,000\ndftrain.corr()['SalePrice'].sort_values(ascending=False)\n#corr >=0.5 ['OverallQual', 'GrLivArea', 'GarageCars', 'GarageArea', 'TotalBsmtSF', '1stFlrSF', 'FullBath', 'TotRmsAbvGrd', 'YearBuilt', 'YearRemodAdd']\n#corr (-) ['KitchenAbvGr', 'EnclosedPorch', 'MSSubClass', 'OverallCond', 'YrSold', 'LowQualFinSF', 'MiscVal', 'BsmtHalfBath', BsmtFinSF2]\n\"\"\"\n# **Exploratory Data Analysis**\n\"\"\"\n\"\"\"\nOverall Quality of Materials and finishes\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='OverallQual', y='SalePrice', data=dftrain)\n#house with higher overall material and finish quality has higher sales price\n\"\"\"\nGound Living Area (sqrft)\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='GrLivArea', y='SalePrice', data=dftrain)\n#strong linear regression shown in the graph\n#should cut out houses that has above ground living area over 4,500 sqrft because its outlier will make the model less accurate\ndftrain = dftrain.drop(dftrain[dftrain['SalePrice']>600000].index)\ndftrain = dftrain.drop(dftrain[dftrain['GrLivArea']>4000].index)\n\"\"\"\nTotal Basement Area (sqrft)\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='TotalBsmtSF', y='SalePrice', data=dftrain)\n#some linear relationship but should cut out the outliers too (>3000)\ndftrain = dftrain.drop(dftrain[dftrain['TotalBsmtSF']>3000].index)\n\"\"\"\nGarage Area (sqrft)\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='GarageArea', y='SalePrice', data=dftrain)\n#cut out outliers\ndftrain = dftrain.drop(dftrain[dftrain['GarageArea']>1200].index)\n\"\"\"\nGarage Car Capacity\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='GarageCars', y='SalePrice', data=dftrain)\n\"\"\"\nFirst Floor sqrft\n\"\"\"\nplt.figure(figsize=(10,6))\nsns.scatterplot(x='1stFlrSF', y='SalePrice', data=dftrain)\n\"\"\"\n# **Feature Engineering**\n\"\"\"\n\"\"\"\nSeperate Features\n\"\"\"\ndftrain = dftrain.drop(['Id'], axis=1)\n\nxy_train = dftrain\n\ntest_id = dftest['Id']\n\nx_test = dftest.drop(['Id'], axis=1)\n#created ttdf to do feature engineer on both train and test df at the same time\nttdf = pd.concat([xy_train, x_test], axis=0)\nlen(ttdf)\n#create table to see null values\nnull_values = pd.DataFrame(ttdf.isnull().sum().sort_values(ascending=False), columns=['Sum_null'])\nnull_values = null_values[null_values['Sum_null']>0]\nnull_values['Percent'] = (null_values['Sum_null']\/2906)*100\nnull_values['Features'] = null_values.index\n\nnull_values\n\"\"\"\n**Work with Missing Values**\n\"\"\"\nplt.figure(figsize=(10,10))\nsns.heatmap(ttdf.isnull(), yticklabels=False, cbar=False, cmap='PuBu')\nttdf = ttdf.drop((null_values[(null_values['Sum_null']>100)&(null_values['Sum_null']<1420)]).index, axis=1)\nttdf = ttdf.drop(null_values[null_values['Sum_null']>2000].index, axis=1)\n\"\"\"\nDrop duplicated info columns\n\"\"\"\nttdf = ttdf.drop(['OverallCond'], axis=1)\nttdf = ttdf.drop(['BsmtCond'], axis=1)\nttdf = ttdf.drop(['LandSlope'], axis=1)\nttdf = ttdf.drop(['1stFlrSF'], axis=1)\nttdf = ttdf.drop(['2ndFlrSF'], axis=1)\nttdf = ttdf.drop(['HouseStyle'], axis=1)\nttdf = ttdf.drop(['RoofMatl'], axis=1)\n\"\"\"\nDrop Year built info\n\"\"\"\nttdf = ttdf.drop(['YearBuilt'], axis=1)\nttdf = ttdf.drop(['YearRemodAdd'], axis=1)\n\"\"\"\nFill null with info got from description file\n\"\"\"\nttdf['MasVnrType'] = ttdf['MasVnrType'].fillna('none')\nttdf['BsmtExposure'] = ttdf['BsmtExposure'].fillna('no_bsmt')\nttdf['BsmtFinType1'] = ttdf['BsmtFinType1'].fillna('no_bsmt')\nttdf['BsmtFinType2'] = ttdf['BsmtFinType2'].fillna('no_bsmt')\nttdf['BsmtQual'] = ttdf['BsmtQual'].fillna('no_bsmt')\n\"\"\"\nFill null with mean values\n\"\"\"\nttdf['MasVnrArea'] = ttdf['MasVnrArea'].fillna(value=ttdf['MasVnrArea'].mean())\n\"\"\"\n**Combine features**\n\"\"\"\nttdf['Bathrooms_total'] = (ttdf['FullBath'] + ttdf['BsmtFullBath'] + (0.5* (ttdf['HalfBath']+ttdf['BsmtHalfBath'])))\n\nttdf.drop(['FullBath'], axis=1, inplace=True)\nttdf.drop(['BsmtFullBath'], axis=1, inplace=True)\nttdf.drop(['HalfBath'], axis=1, inplace=True)\nttdf.drop(['BsmtHalfBath'], axis=1, inplace=True)\nttdf['PorchTotalSF'] = (ttdf['OpenPorchSF'] + ttdf['EnclosedPorch'] + ttdf['3SsnPorch'] + ttdf['ScreenPorch'])\n\nttdf.drop(['OpenPorchSF'], axis=1, inplace=True)\nttdf.drop(['EnclosedPorch'], axis=1, inplace=True)\nttdf.drop(['3SsnPorch'], axis=1, inplace=True)\nttdf.drop(['ScreenPorch'], axis=1, inplace=True)\n\"\"\"\n**Convert Categorical Feature to Dummy Variables**\n\"\"\"\nttdf.info()\nttdf.shape\nttdf.select_dtypes(include='object').columns\nmszoning = pd.get_dummies(ttdf['MSZoning'], drop_first=True)\nstreet = pd.get_dummies(ttdf['Street'], drop_first=True)\nlotshape = pd.get_dummies(ttdf['LotShape'], drop_first=True)\nlandcontour = pd.get_dummies(ttdf['LandContour'], drop_first=True)\nutilities = pd.get_dummies(ttdf['Utilities'], drop_first=True)\nlotconfig = pd.get_dummies(ttdf['LotConfig'], drop_first=True)\nneighborhood = pd.get_dummies(ttdf['Neighborhood'], drop_first=True)\ncondition1 = pd.get_dummies(ttdf['Condition1'], drop_first=True)\ncondition2 = pd.get_dummies(ttdf['Condition2'], drop_first=True)\nbldgtype = pd.get_dummies(ttdf['BldgType'], drop_first=True)\nroofstyle = pd.get_dummies(ttdf['RoofStyle'], drop_first=True)\nexterior1st = pd.get_dummies(ttdf['Exterior1st'], drop_first=True)\nexterior2nd = pd.get_dummies(ttdf['Exterior2nd'], drop_first=True)\nmasvnrtype = pd.get_dummies(ttdf['MasVnrType'], drop_first=True)\nexterqual = pd.get_dummies(ttdf['ExterQual'], drop_first=True)\nextercond = pd.get_dummies(ttdf['ExterCond'], drop_first=True)\nfoundation = pd.get_dummies(ttdf['Foundation'], drop_first=True)\nbsmtqual = pd.get_dummies(ttdf['BsmtQual'], drop_first=True)\nbsmtexposure = pd.get_dummies(ttdf['BsmtExposure'], drop_first=True)\nbsmtfintype1 = pd.get_dummies(ttdf['BsmtFinType1'], drop_first=True)\nbsmtfintype2 = pd.get_dummies(ttdf['BsmtFinType2'], drop_first=True)\nheating = pd.get_dummies(ttdf['Heating'], drop_first=True)\nheatingqc = pd.get_dummies(ttdf['HeatingQC'], drop_first=True)\ncentralair = pd.get_dummies(ttdf['CentralAir'], drop_first=True)\nelectrical = pd.get_dummies(ttdf['Electrical'], drop_first=True)\nkitchenqual = pd.get_dummies(ttdf['KitchenQual'], drop_first=True)\nfunctional = pd.get_dummies(ttdf['Functional'], drop_first=True)\npaveddrive = pd.get_dummies(ttdf['PavedDrive'], drop_first=True)\nsaletype = pd.get_dummies(ttdf['SaleType'], drop_first=True)\nsalecondition = pd.get_dummies(ttdf['SaleCondition'], drop_first=True)\nttdf = pd.concat([ttdf, mszoning, street, salecondition, saletype, paveddrive, functional, kitchenqual, electrical, centralair, heatingqc, heating, bsmtfintype2, bsmtfintype1, bsmtexposure, bsmtqual, foundation, extercond, exterqual, masvnrtype, exterior2nd, exterior1st, roofstyle, bldgtype, condition2, condition1, neighborhood, lotconfig, utilities, landcontour, lotshape], axis=1)\nttdf.drop(['MSZoning', 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'RoofStyle', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'Heating', 'HeatingQC', 'CentralAir', 'Electrical', 'KitchenQual', 'Functional', 'PavedDrive', 'SaleType', 'SaleCondition'], axis=1, inplace=True)\nttdf.info()\n#now all columns in numeric form\n\"\"\"\n# **Create Model**\n\"\"\"\n\"\"\"\nSeperate train and test data\n\"\"\"\nttdf.shape\nttdf.isnull().sum().sort_values()\ntrainxy = ttdf[0:1447]\ntrainxy.isnull().sum().sort_values()\ntrainxy = trainxy.dropna()\ny_train = trainxy['SalePrice'].values\nx_train = trainxy.drop(\"SalePrice\",1).values\nx_test = ttdf[1447:].drop(\"SalePrice\", 1).values\n\"\"\"\n**Data Preprocessing** \n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.transform(x_test)\nx_train.shape\nx_test.shape\n\"\"\"\n**Model Creation (ANN)**\n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, explained_variance_score\nmse = mean_squared_error\nmodel = Sequential()\n\nmodel.add(Dense(190, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(90, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\n\nmodel.compile(optimizer='adam', loss='mse')\n\nmodel.fit(x=x_train, y=y_train, batch_size=180, epochs=750)\n\"\"\"\n**See Loss history**\n\"\"\"\nmodel_loss = pd.DataFrame(model.history.history)\nmodel_loss.plot()\n\"\"\"\n# **Predictions**\n\"\"\"\npredictions = model.predict(x_test)\nPredictions = predictions.flatten()\nPredictions = pd.Series(Predictions)\nPredictions\nTest_Id = pd.Series(test_id)\nsubmission = pd.DataFrame({'Id': Test_Id, 'SalePrice': Predictions})\nsubmission.tail(20)\nsubmission = submission.fillna(value=submission['SalePrice'].mean())\n\"\"\"\n**Save Submission File**\n\"\"\"\nsubmission.to_csv('HPPredictSubmission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '2fe69753e47e41'}"}
{"id":"117074","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.feature_selection import mutual_info_regression\nfrom sklearn.model_selection import train_test_split as tts\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\ntrain_file = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/train.csv\") \n# Load the testing dataset\ntest_file = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/test.csv\")\npd.set_option('display.max_columns', None)\nprint(train_file.shape)\ntrain_file.head(3)\n\"\"\"\n## Data Information\n- Null value finding\n- Table Information\n- 5pt Summary\n\"\"\"\ntrain_file[[i for i in train_file.columns if train_file[i].isnull().sum()>0]].isnull().sum()\n#Table Information\ntrain_file.info()\ntrain_file.describe()\n\"\"\"\n## Feature Engineering - Data Cleaning and Creating an ADS for Analysis\n\"\"\"\n#if the columns having more than 50% of missing values, then i'm removing it\ntrain_file = train_file.drop(['Id', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature'], axis = 1)\n\n# As per our data, if Bmst value is Not available -> No basement, Garage value is Not available -> No Garage, Alley Value is NA -> No alley Access\ntrain_file['BsmtQual'] = np.where(train_file['BsmtQual'].isnull() == True, \"No Basement\", train_file['BsmtQual'])\ntrain_file['BsmtCond'] = np.where(train_file['BsmtCond'].isnull() == True, \"No Basement\", train_file['BsmtCond'])\ntrain_file['BsmtExposure'] = np.where(train_file['BsmtExposure'].isnull() == True, \"No Basement\", train_file['BsmtExposure'])\ntrain_file['BsmtFinType1'] = np.where(train_file['BsmtFinType1'].isnull() == True, \"No Basement\", train_file['BsmtFinType1'])\ntrain_file['BsmtFinType2'] = np.where(train_file['BsmtFinType2'].isnull() == True, \"No Basement\", train_file['BsmtFinType2'])\n#--------------------\ntrain_file['Alley'] = np.where(train_file['Alley'].isnull() == True, \"No Alley Access\", train_file['Alley'])\n#--------------------\ntrain_file['GarageType'] = np.where(train_file['GarageType'].isnull() == True, \"No Garage\", train_file['GarageType'])\ntrain_file['GarageYrBlt'] = np.where(train_file['GarageYrBlt'].isnull() == True, \"No Garage\", train_file['GarageYrBlt'])\ntrain_file['GarageFinish'] = np.where(train_file['GarageFinish'].isnull() == True, \"No Garage\", train_file['GarageFinish'])\ntrain_file['GarageQual'] = np.where(train_file['GarageQual'].isnull() == True, \"No Garage\", train_file['GarageQual'])\ntrain_file['GarageCond'] = np.where(train_file['GarageCond'].isnull() == True, \"No Garage\", train_file['GarageCond'])\n#Replace the grouped mode value of MasVnrType, Elecctrical, MasVnrArea\ntrain_file['MasVnrType'] = train_file.groupby(['YearBuilt'], sort=False)['MasVnrType'].apply(lambda x: x.fillna(x.mode().iloc[0]))\ntrain_file['Electrical'] = train_file.groupby(['YearBuilt'], sort=False)['Electrical'].apply(lambda x: x.fillna(x.mode().iloc[0]))\ntrain_file['MasVnrArea'] = train_file['MasVnrArea'].fillna(train_file.groupby(['YearBuilt'])['MasVnrArea'].transform('mean'))\n\"\"\"\n#### Treating the Null Values for LotFrontage \n- In our dataset, We have 259 null values for lotfrontage, if we replace with mean\/median or some random values, It might effects on accuracy or model performance. To make model more efficiency, I'm predicting the value by consdering the relavent parameters of lotfrontage.\n- Here I'm making LotFrontage as a dependent variable and rest all are independent variables. All the null values of LotFrontage, I'm considering as test dataset. So that we can predict the missing values.\n\"\"\"\ntrain_LotFrontage_main = train_file[train_file.LotFrontage.isnull() != True]\ntest_LotFrontage_main = train_file[train_file.LotFrontage.isnull() == True]\n#--------------------\ntest_LotFrontage = test_LotFrontage_main.drop('LotFrontage', axis = 1)\ntrain_LotFrontage_xtrain = train_LotFrontage_main[['LotArea', 'Street', 'LotShape', 'LandSlope', 'LotConfig', 'HouseStyle', 'GarageArea']]\ntrain_LotFrontage_ytrain = train_LotFrontage_main['LotFrontage']\n#--------------------\ntest_LotFrontage = test_LotFrontage[['LotArea', 'Street', 'LotShape', 'LandSlope', 'LotConfig', 'HouseStyle', 'GarageArea']]\n\"\"\"\nBefore training the model, we make sure that all the features are in the form of int or float. But we have categorical features in our dataset. For \"Logconig, Street\" I'm used one hot enoding because those two columns are nominal categories for for \"LotShape, LandSlope, HouseStyle\" I'm used ordinal encoding technique.\n\"\"\"\n#Lotconfig and Street are falls under Nominal category. So, I used nominal encoding technique to convert it to integer\ntrain_LotFrontage_xtrain_Nomina_Encoding = pd.get_dummies(train_LotFrontage_xtrain[['LotConfig', 'Street']])\ntrain_LotFrontage_xtrain = pd.concat([train_LotFrontage_xtrain, train_LotFrontage_xtrain_Nomina_Encoding], 1)\ntrain_LotFrontage_xtrain = train_LotFrontage_xtrain.drop(['LotConfig', 'Street'], axis = 1)\n#--------------------\n#LotShape, LandSlope and HouseStyle are falls under Ordinal category. So, I used Ordinal encoding technique to convert it to integer\ntrain_LotFrontage_xtrain['LotShape'] = train_LotFrontage_xtrain.LotShape.map({'IR3':0, 'IR2':1, 'IR1': 2, 'Reg': 3})\ntrain_LotFrontage_xtrain['LandSlope'] = train_LotFrontage_xtrain.LandSlope.map({'Sev':0, 'Mod':1, 'Gtl': 2})\ntrain_LotFrontage_xtrain['HouseStyle'] = train_LotFrontage_xtrain.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\ntrain_LotFrontage_xtrain = train_LotFrontage_xtrain.drop('LotConfig_FR3', axis = 1)\n#Lotconfig and Street are falls under Nominal category. So, I used nominal encoding technique to convert it to integer\ntest_LotFrontage_Nomina_Encoding = pd.get_dummies(test_LotFrontage[['LotConfig', 'Street']])\ntest_LotFrontage = pd.concat([test_LotFrontage, test_LotFrontage_Nomina_Encoding], 1)\ntest_LotFrontage = test_LotFrontage.drop(['LotConfig', 'Street'], axis = 1)\n#--------------------\n#LotShape, LandSlope and HouseStyle are falls under Ordinal category. So, I used Ordinal encoding technique to convert it to integer\ntest_LotFrontage['LotShape'] = test_LotFrontage.LotShape.map({'IR3':0, 'IR2':1, 'IR1': 2, 'Reg': 3})\ntest_LotFrontage['LandSlope'] = test_LotFrontage.LandSlope.map({'Sev':0, 'Mod':1, 'Gtl': 2})\ntest_LotFrontage['HouseStyle'] = test_LotFrontage.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\n#By using Random Forest Algorithm I replaced the missing values of LotFrontage with predicted values\nreg_rf = RandomForestRegressor(n_estimators=1000,min_samples_split=2,min_samples_leaf=1,max_features='sqrt',max_depth=25)\nreg_rf.fit(train_LotFrontage_xtrain, train_LotFrontage_ytrain)\ny_pred= reg_rf.predict(test_LotFrontage)\ntest_LotFrontage_main['LotFrontage'] = y_pred\nprint(\"Accuracy on Traing set: \",reg_rf.score(train_LotFrontage_xtrain,train_LotFrontage_ytrain))\n\ntrain_file = test_LotFrontage_main.append(train_LotFrontage_main).sort_index()\nprint(train_file[[i for i in train_file.columns if train_file[i].isnull().sum()>0]].isnull().sum())\ntrain_file.head(3)\n\"\"\"\n## Feature Selection-Information gain - mutual information In Regression Problem Statements\n\n- Feature Selection-Information gain - mutual information In Regression Problem Statements Mutual Information\n\n- Estimate mutual information for a continuous target variable.\n\n- Mutual information (MI) between two random variables is a non-negative value, which measures the dependency between the variables. It is equal to zero if and only if two random variables are independent, and higher values mean higher dependency.\n\n- The function relies on nonparametric methods based on entropy estimation from k-nearest neighbors distances\n\n- Mutual information is calculated between two variables and measures the reduction in uncertainty for one variable given a known value of the other variable.\n\n\"\"\"\ntrain_file = train_file[['LotFrontage','LotArea','Alley','LotShape','Utilities','LandSlope','HouseStyle','OverallQual','OverallCond','YearBuilt','YearRemodAdd','ExterQual','ExterCond','BsmtQual','BsmtCond','BsmtExposure','BsmtFinType1','BsmtFinSF1','BsmtFinType2','BsmtFinSF2','BsmtUnfSF','TotalBsmtSF','HeatingQC','CentralAir','1stFlrSF','2ndFlrSF','LowQualFinSF','GrLivArea','BsmtFullBath','BsmtHalfBath','FullBath','HalfBath','BedroomAbvGr','KitchenAbvGr','KitchenQual','TotRmsAbvGrd','Fireplaces','GarageCars','GarageArea','GarageQual','GarageCond','PavedDrive','WoodDeckSF','OpenPorchSF','EnclosedPorch','3SsnPorch','ScreenPorch','PoolArea','YrSold', 'SalePrice']]\ntrain_file['Alley'] = np.where(train_file['Alley'] == 'No Alley Access', 0, 1)\ntrain_file['LotShape'] = train_file.LotShape.map({'IR3':0, 'IR2':1, 'IR1': 2, 'Reg': 3})\ntrain_file['Utilities'] = train_file.Utilities.map({'ELO':0, 'NoSeWa':1, 'NoSewr': 2, 'AllPub': 3})\ntrain_file['LandSlope'] = train_file.LandSlope.map({'Sev':0, 'Mod':1, 'Gtl': 2})\ntrain_file['HouseStyle'] = train_file.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\ntrain_file['ExterQual'] = train_file.ExterQual.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\ntrain_file['ExterCond'] = train_file.ExterCond.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\ntrain_file['BsmtQual'] = train_file.BsmtQual.map({'Po':1, 'Fa':2, 'TA': 3, 'Gd': 4,'Ex': 5, 'No Basement': 0})\ntrain_file['BsmtCond'] = train_file.BsmtCond.map({'Po':1, 'Fa':2, 'TA': 3, 'Gd': 4,'Ex': 5, 'No Basement': 0})\ntrain_file['BsmtExposure'] = train_file.BsmtExposure.map({'No Basement':0, 'No':1, 'Mn': 2, 'Av': 3,'Gd': 4})\ntrain_file['BsmtFinType1'] = train_file.BsmtFinType1.map({'Unf':1, 'LwQ':2, 'Rec': 3, 'BLQ': 4,'ALQ': 5,'GLQ': 6, 'No Basement': 0})\ntrain_file['BsmtFinType2'] = train_file.BsmtFinType2.map({'Unf':1, 'LwQ':2, 'Rec': 3, 'BLQ': 4,'ALQ': 5,'GLQ': 6, 'No Basement': 0})\ntrain_file['HeatingQC'] = train_file.HeatingQC.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\ntrain_file['CentralAir'] = np.where(train_file['CentralAir'] == 'Y', 1, 0)\ntrain_file['KitchenQual'] = train_file.KitchenQual.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\ntrain_file['GarageQual'] = train_file.GarageQual.map({'Po':1, 'Fa':2, 'TA': 3, 'Gd': 4,'Ex': 5, 'No Garage': 0})\ntrain_file['GarageCond'] = train_file.GarageCond.map({'Po':1, 'Fa':2, 'TA': 3, 'Gd': 4,'Ex': 5, 'No Garage': 0})\ntrain_file['PavedDrive'] = train_file.PavedDrive.map({'N':0, 'P':1, 'Y': 2})\n\ntrain_file['YearBuilt'] = train_file['YrSold'] - train_file['YearBuilt']\ntrain_file['YearRemodAdd'] = train_file['YrSold'] - train_file['YearRemodAdd']\n\ntrain_file = train_file.rename(columns={\"YearBuilt\": \"BuiltYearsBack\", \"YearRemodAdd\": \"RemodYearsBack\"})\nprint(train_file.shape)\ntrain_file.head(3)\n# Spliting data for training the model. Splitting the data will be done at the begining of feature seletion phase\nX = train_file.drop('SalePrice', axis = 1)\ny = train_file['SalePrice']\nX_train, X_test, Y_train, Y_test = tts(X, y, test_size=0.20,random_state=42)\n\"\"\"\nScaled the data for each metrics by using feature scaling techniques to reduce the bias, to normalize the data within a range and speeding up the calculation while training the model. After applying the Standard Scaler, data range is in between -3 to 3\n\n\"\"\"\nStandardscaler = StandardScaler()\nX_train_col = X_train.columns\nX_train_ADS = pd.DataFrame(Standardscaler.fit_transform(X_train),columns = X_train_col )\nX_train_ADS.head(2)\n# determine the mutual information\nmutual_info = mutual_info_regression(X_train_ADS.fillna(0), Y_train)\nmutual_info = pd.Series(mutual_info)\nmutual_info.index = X_train_ADS.columns\nmutual_info.sort_values(ascending=False)\n#--------------------\n#Considering the columns for training the model which are atleast 10% of information shared with dependent variable\/feature\nReq_Cols = list(mutual_info[mutual_info>0.1].index)\nReq_Cols\n#Creating the Training ADS with selected columns\nTrain_ADS = X_train_ADS[Req_Cols]\nTrain_ADS.head(3)\n#Applying Scaling technique to Test Dataset\nStandardscaler = StandardScaler()\nX_test_col = X_test.columns\nX_test_ADS = pd.DataFrame(Standardscaler.fit_transform(X_test),columns = X_test_col )\n#--------------------\n#Creating the Testing ADS with selected columns\nTest_ADS = X_test_ADS[Req_Cols]\nprint(Test_ADS.shape)\nTest_ADS.head(2)\n\n\"\"\"\n## Linear regression\n\"\"\"\nlinear_reg = LinearRegression()\nlinear_reg.fit(Train_ADS, Y_train)\ny_pred= linear_reg.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",linear_reg.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",linear_reg.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\n\"\"\"\nIn linear reegression we didn't obtain good acuracy. So, Lets try with another alogorithm: RandomForest Regressor\n\n## KNeighbors Regressor \n\"\"\"\nfrom sklearn.neighbors import KNeighborsRegressor\nneigh = KNeighborsRegressor(n_neighbors=2)\nneigh.fit(Train_ADS, Y_train)\ny_pred= neigh.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",neigh.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",neigh.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\n\"\"\"\nCompare with Linear regressor, accuracy for KNN with K=2 is better. So I performed hyper parameter tunning to find the optimal K value\n\"\"\"\nScore = []\nfor i in range(1,40):\n    knn = KNeighborsRegressor(n_neighbors=i)\n    knn.fit(Train_ADS, Y_train)\n    pred_i = knn.predict(Test_ADS)\n    score_1=r2_score(Y_test,pred_i)\n    Score.append(score_1)\n\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40),Score,color='blue', linestyle='dashed', \n         marker='o',markerfacecolor='red', markersize=1)\nplt.title('Accuracy vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Accuracy')\nprint(\"Max Accuracy error:-\",max(Score),\"at K =\",Score.index(max(Score))+1)\n\"\"\"\nAfter hyper parameter tuning we obtain good acuracy. But, Lets try with another alogorithm: RandomForest Regressor\n\n## RandomForest Regressor \n\"\"\"\nreg_rf = RandomForestRegressor()\nreg_rf.fit(Train_ADS, Y_train)\ny_pred= reg_rf.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",reg_rf.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",reg_rf.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\n\"\"\"\nIn RandomForest Regressor, accuracy is comparitively better than than above two models. To improve the accuracy, hyperparameter tuing is performed\n\"\"\"\nfrom sklearn.model_selection import RandomizedSearchCV\n#Randomized Search CV\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 2000, num = 40)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(5, 40, num = 6)]\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10, 15, 20,25,30,35,40,100]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 5, 10]\n\nrandom_grid = {'n_estimators': n_estimators,\n               'max_features': max_features,\n               'max_depth': max_depth,\n               'min_samples_split': min_samples_split,\n               'min_samples_leaf': min_samples_leaf}\n\nrf_random = RandomizedSearchCV(estimator = reg_rf, param_distributions = random_grid,scoring='neg_mean_squared_error', n_iter = 10, cv = 5, verbose=2, random_state=42, n_jobs = 1)\n\nrf_random.fit(Train_ADS, Y_train)\nrf_random.best_params_\nreg_rf = RandomForestRegressor(n_estimators=1220,min_samples_split=2,min_samples_leaf=1,max_features='sqrt',max_depth=33)\nreg_rf.fit(Train_ADS, Y_train)\ny_pred= reg_rf.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",reg_rf.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",reg_rf.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\n\"\"\"\nAfter hyper parameter tuning we obtain good acuracy. But, Lets try with another alogorithm: XGB Regressor\n\n## XGBoost Regressor \n\"\"\"\n#!pip install xgboost\nimport xgboost as XGB\n\nxgb_model = XGB.XGBRegressor()\nxgb_model.fit(Train_ADS, Y_train)\ny_pred= xgb_model.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",xgb_model.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",xgb_model.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\nlearning_rate = [0.01, 0.1]\nmax_depth = [int(x) for x in np.linspace(5, 40, num = 6)]\nmin_child_weight = [int(x) for x in np.linspace(1, 20, num = 6)]\nsubsample =  [0.5, 0.7]\ncolsample_bytree = [0.5, 0.7]\nobjective = ['reg:squarederror']\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 2000, num = 40)]\n\n\nrandom_grid = {'learning_rate': learning_rate,\n               'max_depth': max_depth,\n               'min_child_weight': min_child_weight,\n               'subsample': subsample,\n               'colsample_bytree': colsample_bytree,\n               'objective': objective,\n               'n_estimators': n_estimators}\n\n\nrf_random = RandomizedSearchCV(estimator = xgb_model, param_distributions = random_grid,scoring='neg_mean_squared_error', n_iter = 10, cv = 5, verbose=2, random_state=42, n_jobs = 1)\n\nrf_random.fit(Train_ADS, Y_train)\nrf_random.best_params_\nxgb_model = XGB.XGBRegressor(subsample=0.5, objective='reg:squarederror', n_estimators=1561, min_child_weight=16, max_depth=12, learning_rate=0.01, colsample_bytree=0.5)\nxgb_model.fit(Train_ADS, Y_train)\ny_pred= xgb_model.predict(Test_ADS)\nscore_1=r2_score(Y_test,y_pred)\nprint(\"Accuracy on Traing set: \",xgb_model.score(Train_ADS,Y_train))\nprint(\"Accuracy on Testing set: \",xgb_model.score(Test_ADS,Y_test))\nprint(\"R2 score\", score_1)\n\"\"\"\n## Feature Engineering & Feature Selection For Test Dataset\n\"\"\"\ntest_file[[i for i in test_file.columns if test_file[i].isnull().sum()>0]].isnull().sum()\ntest_file['BuiltYearsBack'] = test_file['YrSold'] - test_file['YearBuilt']\ntest_file['RemodYearsBack'] = test_file['YrSold'] - test_file['YearRemodAdd']\n\ntrain_LotFrontage_main = test_file[test_file.LotFrontage.isnull() != True]\ntest_LotFrontage_main = test_file[test_file.LotFrontage.isnull() == True]\n\n\ntest_LotFrontage = test_LotFrontage_main.drop('LotFrontage', axis = 1)\ntrain_LotFrontage_xtrain = train_LotFrontage_main[['LotArea', 'Street', 'LotShape', 'LandSlope', 'LotConfig', 'HouseStyle', 'GarageArea']]\ntrain_LotFrontage_ytrain = train_LotFrontage_main['LotFrontage']\n\ntest_LotFrontage = test_LotFrontage[['LotArea', 'Street', 'LotShape', 'LandSlope', 'LotConfig', 'HouseStyle', 'GarageArea']]\n\n#Lotconfig and Street are falls under Nominal category. So, I used nominal encoding technique to convert it to integer\ntrain_LotFrontage_xtrain_Nomina_Encoding = pd.get_dummies(train_LotFrontage_xtrain[['LotConfig', 'Street']])\ntrain_LotFrontage_xtrain = pd.concat([train_LotFrontage_xtrain, train_LotFrontage_xtrain_Nomina_Encoding], 1)\ntrain_LotFrontage_xtrain = train_LotFrontage_xtrain.drop(['LotConfig', 'Street'], axis = 1)\n\n#LotShape, LandSlope and HouseStyle are falls under Ordinal category. So, I used Ordinal encoding technique to convert it to integer\ntrain_LotFrontage_xtrain['LotShape'] = train_LotFrontage_xtrain.LotShape.map({'IR3':0, 'IR2':1, 'IR1': 2, 'Reg': 3})\ntrain_LotFrontage_xtrain['LandSlope'] = train_LotFrontage_xtrain.LandSlope.map({'Sev':0, 'Mod':1, 'Gtl': 2})\ntrain_LotFrontage_xtrain['HouseStyle'] = train_LotFrontage_xtrain.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\ntrain_LotFrontage_xtrain = train_LotFrontage_xtrain.drop('LotConfig_FR3', axis = 1)\n\n#Lotconfig and Street are falls under Nominal category. So, I used nominal encoding technique to convert it to integer\ntest_LotFrontage_Nomina_Encoding = pd.get_dummies(test_LotFrontage[['LotConfig', 'Street']])\ntest_LotFrontage = pd.concat([test_LotFrontage, test_LotFrontage_Nomina_Encoding], 1)\ntest_LotFrontage = test_LotFrontage.drop(['LotConfig', 'Street','LotConfig_FR3'], axis = 1)\n\n#LotShape, LandSlope and HouseStyle are falls under Ordinal category. So, I used Ordinal encoding technique to convert it to integer\ntest_LotFrontage['LotShape'] = test_LotFrontage.LotShape.map({'IR3':0, 'IR2':1, 'IR1': 2, 'Reg': 3})\ntest_LotFrontage['LandSlope'] = test_LotFrontage.LandSlope.map({'Sev':0, 'Mod':1, 'Gtl': 2})\ntest_LotFrontage['HouseStyle'] = test_LotFrontage.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\n\n\ntrain_LotFrontage_xtrain[[i for i in train_LotFrontage_xtrain.columns if train_LotFrontage_xtrain[i].isnull().sum()>0]].isnull().sum()\ntest_file['GarageArea'] = test_file['GarageArea'].fillna(test_file.groupby('HouseStyle')['GarageArea'].transform('mean'))\n\n\n#By using Random Forest Algorithm I replaced the missing values of LotFrontage with predicted values\nreg_rf = RandomForestRegressor(n_estimators=1000,min_samples_split=2,min_samples_leaf=1,max_features='sqrt',max_depth=25)\nreg_rf.fit(train_LotFrontage_xtrain.fillna(0), train_LotFrontage_ytrain)\ny_pred= reg_rf.predict(test_LotFrontage)\ntest_LotFrontage_main['LotFrontage'] = y_pred\nprint(\"Accuracy on Traing set: \",reg_rf.score(train_LotFrontage_xtrain.fillna(0),train_LotFrontage_ytrain))\n#--------------------\nTest_ADS = test_LotFrontage_main.append(train_LotFrontage_main).sort_index()\nTest_ADS = Test_ADS[Req_Cols]\nTest_ADS['BsmtQual'] = np.where(Test_ADS['BsmtQual'].isnull() == True, \"No Basement\", Test_ADS['BsmtQual'])\nTest_ADS['BsmtFinType1'] = np.where(Test_ADS['BsmtFinType1'].isnull() == True, \"No Basement\", Test_ADS['BsmtFinType1'])\nTest_ADS['HouseStyle'] = Test_ADS.HouseStyle.map({'1Story':0, '1.5Fin':1, '1.5Unf': 2, '2Story':3, '2.5Fin':4, '2.5Unf': 5, 'SFoyer':6, 'SLvl':7})\nTest_ADS['ExterQual'] = Test_ADS.ExterQual.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\nTest_ADS['BsmtQual'] = Test_ADS.BsmtQual.map({'Po':1, 'Fa':2, 'TA': 3, 'Gd': 4,'Ex': 5, 'No Basement': 0})\nTest_ADS['BsmtFinType1'] = Test_ADS.BsmtFinType1.map({'Unf':1, 'LwQ':2, 'Rec': 3, 'BLQ': 4,'ALQ': 5,'GLQ': 6, 'No Basement': 0})\nTest_ADS['HeatingQC'] = Test_ADS.HeatingQC.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\nTest_ADS['KitchenQual'] = Test_ADS.KitchenQual.map({'Po':0, 'Fa':1, 'TA': 2, 'Gd': 3,'Ex': 4})\nTest_ADS.head(4)\nTest_col = Test_ADS.columns\nTest_ADS = pd.DataFrame(Standardscaler.fit_transform(Test_ADS),columns = Test_col )\nprint(Train_ADS.shape)\nTest_ADS.head(2)\n\"\"\"\n## Sales price prediction for test dataset\n\"\"\"\n#Applying Scaling technique to Test Dataset\nStandardscaler = StandardScaler()\nX_test_col = X.columns\nTrain_ADS = pd.DataFrame(Standardscaler.fit_transform(X),columns = X_test_col )\n\n#Creating the Testing ADS with selected columns\nTrain_ADS = Train_ADS[Req_Cols]\nprint(Train_ADS.shape)\nTrain_ADS.head(2)\nY_train = y\nxgb_model = XGB.XGBRegressor(subsample=0.5,  n_estimators=1561, min_child_weight=16, max_depth=12, learning_rate=0.01, colsample_bytree=0.5)\nxgb_model.fit(Train_ADS, Y_train)\ny_pred= xgb_model.predict(Test_ADS)\n\nprint(\"Accuracy on Traing set: \",xgb_model.score(Train_ADS,Y_train))\n\ntest_file['Pred Price'] = y_pred\n\nSub_file = test_file[['Id','Pred Price']]\nSub_file.head(10)\n#Sub_file.to_csv('\/submission.csv',index=False)\n\"\"\"\nI've tried with three algorithms (Linear Regression, KNN, Random Forest) and hyperparameter tuning for XGB regressor. If you like the notebook the Please Upvote add up your comments to this nootebook Happy coding\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd75bd00928a778'}"}
{"id":"47821","text":"\"\"\"\n# Hello World\n\"\"\"\n\"\"\"\nKaggle kernels are Jupyter Notebooks that are hosted in the cloud and have access to the all data as well as making submissions! They're worth trying out \ud83d\udc4d\n\nBelow is a hyper-fast walk through of how to access the Music Classficiaton competition data\n\"\"\"\n\"\"\"\n## Run Bash Commands\n\"\"\"\n!ls \/kaggle\/input\/music-classification\/kaggle\n\"\"\"\n## Import your fav Python libs\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\"\"\"\n## Read Music Classification Data\n\"\"\"\n\"\"\"\n### Read Labels DataFrame\n\"\"\"\nROOT_DIR = '\/kaggle\/input\/music-classification\/kaggle\/'\n\n## Read the training data labels csv file\ndfLabels = pd.read_csv(ROOT_DIR + 'labels.csv')\ndfLabels\n\"\"\"\n### Read Song DataFrame\n\"\"\"\n## Read individual song file\ndfSong = pd.read_csv(ROOT_DIR + 'training\/' + dfLabels.id[0], header=None)\ndfSong\n\"\"\"\n## Visualizing your Song Data\n\"\"\"\n## Display wave form of song\n# Aesthetics :\n# - Select just the start of song, also apply some smoothing so its easier to see\n# - Each column (ie song channel) is different color\n\ndfSong[:200].rolling(5).mean().plot.line(figsize=(16,8), title=\"Song Wave Form (by Channel)\")\n## Plot distribution of values for each channel\n# Aesthetics : \n# - Based on above graph, values typically fall between -100 and 100, trim bounds\n\ndfSong.plot.density(xlim=(-100,100), figsize=(12, 8), title=\"Distribution of values for each channel\")","meta":"{'source': 'AI4Code', 'id': '58181f11834e2a'}"}
{"id":"119441","text":"\"\"\"\n# FrenchNews : CAC40 prediction with deep learning and news sentiment analysis\n##### Go to the link below for the original tutorial file modified for stocks prediction.\nhttps:\/\/www.tensorflow.org\/tutorials\/structured_data\/time_series\n\nNote : I\u2019v correct the this tutorial to make it plot the validation data and not the train data.\n\nSome models don't converge, i think it's because there is a lot of nose in the stocks market...\n\n\n\"\"\"\n\"\"\"\n## Setup\n\"\"\"\nimport os\nimport datetime\n\nimport IPython\nimport IPython.display\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport tensorflow as tf\n\nmpl.rcParams['figure.figsize'] = (8, 6)\nmpl.rcParams['axes.grid'] = False\n\"\"\"\n##  dataset import\n\n\n\"\"\"\nCSV_FILE_NAME_OUTPUT_MOY = '..\/input\/french-financial-news\/FrenchNewsDayConcat.csv'\n\ndf = pd.read_csv(CSV_FILE_NAME_OUTPUT_MOY)\n\ndf\n\"\"\"\nLet's take a glance at the data. Here are the first few rows:\n\"\"\"\ndate_time = pd.to_datetime(df.pop('Date'), format='%Y.%m.%d %H:%M:%S')\n\ndate_time\ndf.head()\n#On supprime les collones inutiles\ndf.pop('Nbr Day')\ndf.pop('NbrNewsJour')\ndf.head()\n\"\"\"\nHere is the evolution of a few features over time. \n\"\"\"\nplot_cols = ['Open','Mean sent text','Day Sent Vader Text','Volume']\nplot_features = df[plot_cols]\nplot_features.index = date_time\n_ = plot_features.plot(subplots=True)\n\nplot_features = df[plot_cols][:48]\nplot_features.index = date_time[:48]\n_ = plot_features.plot(subplots=True)\n\"\"\"\n### Inspect and cleanup\n\"\"\"\n\"\"\"\nNext look at the statistics of the dataset:\n\"\"\"\ndf.describe().transpose()\ndf['Volume'].plot()\n\"\"\"\n## Data error correction : \n####    -> Volume min value = 0 , it's an error ?  \n####       Not so easy to correct, we can try to remplace this 0 by the mean of the curve :\n\n\n\n\"\"\"\n# Il y a des donn\u00e9s manquantes dans les Volumes, on remplace les 0 par la moyenne\nVolume = df['Volume']\n\nmeanVol = Volume.mean()\n\nbad_Volume = Volume == 0.0\nVolume[bad_Volume] = meanVol\n\ndf.describe().transpose()\n\"\"\"\n### Feature engineering\n\nBefore diving in to build a model it's important to understand your data, and be sure that you're passing the model appropriately formatted data.\n\"\"\"\nplt.hist2d(df['High'], df['Low'], bins=(50, 50), vmax=10)\nplt.colorbar()\nplt.xlabel('High')\nplt.ylabel('Low')\n########################################################\n# Pour faciliter la convergence du model, il faut absolument d\u00e9finir une seul variable qui contien l'info du cours.\n# Actuelement cette info est dans Open \/ Close \/ High \/ Low.\n# Il faut calculer les diff\u00e9rences comme \"Open_Close_Var\" et \"Amplitude\" pour \"Adj Close\" et autre, ex Open-Min ...\n# A d\u00e9terminer pour permetre de r\u00e9cuperer un max d'info avec une seul variable de cours.\n########################################################\n\"\"\"\nBut this will be easier for the model to interpret if you convert the MIN \/ MAX columns to AMPLITUDE:\n\"\"\"\n# Convert to amplitude.\ndf['Amplitude'] = df['High'] - df['Low']\n\ndf['Amplitude']\ndf['Open_Close_Var'] = df['Close'] - df['Open']\n\ndf['Open_Close_Var']\nplt.hist2d(df['Amplitude'], df['Open_Close_Var'], bins=(50, 50), vmax=5)\nplt.colorbar()\nplt.xlabel('Amplitude')\nplt.ylabel('Open_Close_Var')\nax = plt.gca()\nax.axis('tight')\ndf['Open_Low_Var'] = df['Open'] - df['Low']\n\ndf['Close_High_Var'] = df['Close'] - df['High']\n\n#df['Close_AdjClose'] = df['Close'] - df['Adj Close']\n#df['Close_AdjClose']\n\n#Suppresion des variables de cours redondantes\ndf.pop('High')\ndf.pop('Low')\ndf.pop('Close')\n\n#pour le cac40 AdjClose est inutile car indentique \u00e0 Close\ndf.pop('Adj Close')\ndf.describe().transpose()\n'''\n#####################\n## Ajout de features  -> non utilis\u00e9 car rend difficile la convergence du model\n#####################\n\n#Moyenne et d\u00e9riv\u00e9\nfor column in df:\n    df[column+'_mean10'] = df[column].rolling(window=10,min_periods=0).mean()\n    df[column+'_diff'] = df[column].diff()\n    df[column+'_diff'][0] = df[column+'_diff'][1]\n    \nplt.plot(np.array(df['Mean sent text']))\nplt.plot(np.array(df['Mean sent text_diff']))\n'''\ndf\n\n\"\"\"\n#### Time\n\"\"\"\n\"\"\"\nSimilarly the `Date Time` column is very useful, but not in this string form. Start by converting it to seconds:\n\"\"\"\ntimestamp_s = date_time.map(datetime.datetime.timestamp)\ntimestamp_s\n\"\"\"\nThe time in seconds is not a useful model input. The stock market could maybe have year, month and week periodicity... \n\nThere are many ways you could deal with periodicity.\n\nA simple approach to convert it to a usable signal is to use `sin` and `cos` to convert the time to clear \"Time of day\" and \"Time of year\" signals:\n\"\"\"\nweek = 7*24*60*60     # 5 jours ouvr\u00e9s par semaines\nmonth = 30.4167*24*60*60\nyear = 365.2425*24*60*60    # 254 jours ouvr\u00e9s par ann\u00e9s\nyear10 = 365.2425*24*60*60*10    # 254 jours ouvr\u00e9s par ann\u00e9s\n\n\ndf['week sin'] = np.sin(timestamp_s * (2 * np.pi \/ week))\ndf['week cos'] = np.cos(timestamp_s * (2 * np.pi \/ week))\n\ndf['month sin'] = np.sin(timestamp_s * (2 * np.pi \/ month))\ndf['month cos'] = np.cos(timestamp_s * (2 * np.pi \/ month))\n\ndf['Year sin'] = np.sin(timestamp_s * (2 * np.pi \/ year))\ndf['Year cos'] = np.cos(timestamp_s * (2 * np.pi \/ year))\n\ndf['10 Year sin'] = np.sin(timestamp_s * (2 * np.pi \/ year10))\ndf['10 Year cos'] = np.cos(timestamp_s * (2 * np.pi \/ year10))\nplt.plot(np.array(df['week sin'])[:20])\nplt.plot(np.array(df['week cos'])[:20])\nplt.xlabel('Time [Day]')\nplt.title('Time of week signal')\nplt.plot(np.array(df['month sin'])[:100])\nplt.plot(np.array(df['month cos'])[:100])\nplt.xlabel('Time [Day]')\nplt.title('Time of month signal')\nplt.plot(np.array(df['Year sin'])[:365])\nplt.plot(np.array(df['Year cos'])[:365])\nplt.xlabel('Time [Day]')\nplt.title('Time of Year signal')\nplt.plot(np.array(df['10 Year sin'])[:365])\nplt.plot(np.array(df['10 Year cos'])[:365])\nplt.xlabel('Time [Day]')\nplt.title('Time of 10 Year signal')\n#Limitation de la taille de memoire GPU utilis\u00e9, sur RTX3090, 18Go\n'''\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU\n  try:\n    tf.config.experimental.set_virtual_device_configuration(\n        gpus[0],\n        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=18000)])   #18 Go\n    logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n    print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n  except RuntimeError as e:\n    # Virtual devices must be set before GPUs have been initialized\n    print(e)\n'''\n\"\"\"\nThis gives the model access to the most important frequency features. In this case you knew ahead of time which frequencies were important. \n\nIf you didn't know, you can determine which frequencies are important using an `fft`. To check our assumptions, here is the `tf.signal.rfft` of the temperature over time. Note the obvious peaks at frequencies near `1\/year` and `1\/day`: \n\"\"\"\nfft = tf.signal.rfft(df['Open'])\nf_per_dataset = np.arange(0, len(fft))\n\nn_samples_h = len(df['Open'])\nday_per_year = 365.2524\nyears_per_dataset = n_samples_h\/(day_per_year)\n\nf_per_year = f_per_dataset\/years_per_dataset\nplt.step(f_per_year, np.abs(fft))\nplt.xscale('log')\nplt.ylim(0, 150000)\nplt.xlim([0.1, max(plt.xlim())])\nplt.xticks([1, 12, 52.1429], labels=['1\/Year', '1\/mounth', '1\/week'])\n_ = plt.xlabel('Frequency (log scale)')\nfft = tf.signal.rfft(df['month sin'])\nf_per_dataset = np.arange(0, len(fft))\n\nn_samples_h = len(df['month sin'])\nday_per_year = 365.2524\nyears_per_dataset = n_samples_h\/(day_per_year)\n\nf_per_year = f_per_dataset\/years_per_dataset\nplt.step(f_per_year, np.abs(fft))\nplt.xscale('log')\nplt.ylim(0, 150)\nplt.xlim([0.1, max(plt.xlim())])\nplt.xticks([1, 12, 52.1429], labels=['1\/Year', '1\/mounth', '1\/week'])\n_ = plt.xlabel('Frequency (log scale)')\nfft = tf.signal.rfft(df['Day Sent Vader Text URL'])\nf_per_dataset = np.arange(0, len(fft))\n\nn_samples_h = len(df['Mean sent text'])\nday_per_year = 365.2524\nyears_per_dataset = n_samples_h\/(day_per_year)\n\nf_per_year = f_per_dataset\/years_per_dataset\nplt.step(f_per_year, np.abs(fft))\nplt.xscale('log')\nplt.ylim(0, 20)\nplt.xlim([0.1, max(plt.xlim())])\nplt.xticks([1, 12, 52.1429], labels=['1\/Year', '1\/mounth', '1\/week'])\n_ = plt.xlabel('Frequency (log scale)')\n#check dataset\ndf.describe().transpose()\n\"\"\"\n### Split the data\n\"\"\"\n\"\"\"\nWe'll use a `(70%, 20%, 10%)` split for the training, validation, and test sets. Note the data is **not** being randomly shuffled before splitting. This is for two reasons.\n\n1. It ensures that chopping the data into windows of consecutive samples is still possible.\n2. It ensures that the validation\/test results are more realistic, being evaluated on data collected after the model was trained.\n\"\"\"\ncolumn_indices = {name: i for i, name in enumerate(df.columns)}\n\nn = len(df)\ntrain_df = df[0:int(n*0.7)]\nval_df = df[int(n*0.7):int(n*0.9)]\ntest_df = df[int(n*0.9):]\n\nnum_features = df.shape[1]\nn\ntrain_df\nval_df\n\"\"\"\n### Normalize the data\n\nIt is important to scale features before training a neural network. Normalization is a common way of doing this scaling. Subtract the mean and divide by the standard deviation of each feature.\n\"\"\"\ntest_df\nnum_features\n#On v\u00e9rifie la d\u00e9coupe du dataset\nplt.plot(train_df['Open'],label='train_df')\nplt.plot(val_df['Open'],label='val_df')\nplt.plot(test_df['Open'],label='test_df')\nplt.legend()\nplt.xlabel('Time [Day]')\nplt.title('Data set split check')\n#Affichage des donn\u00e9s de test\n\nplt.figure(figsize=(16, 4))\nplt.plot(test_df['Open'],label='test_df')\nplt.legend()\nplt.xlabel('Time [Day]')\nplt.title('Data set split check')\n\"\"\"\nThe mean and standard deviation should only be computed using the training data so that the models have no access to the values in the validation and test sets.\n\nIt's also arguable that the model shouldn't have access to future values in the training set when training, and that this normalization should be done using moving averages. That's not the focus of this tutorial, and the validation and test sets ensure that you get (somewhat) honest metrics. So in the interest of simplicity this tutorial uses a simple average.\n\"\"\"\ntrain_mean = train_df.mean()\ntrain_std = train_df.std()\n\ntrain_df = (train_df - train_mean) \/ train_std\nval_df = (val_df - train_mean) \/ train_std\ntest_df = (test_df - train_mean) \/ train_std\ntrain_df\n#On v\u00e9rifie la d\u00e9coupe du dataset\nplt.figure(figsize=(15, 6))\nplt.plot(train_df['Volume'],label='train_df')\nplt.plot(val_df['Volume'],label='val_df')\nplt.plot(test_df['Volume'],label='test_df')\nplt.legend()\nplt.xlabel('Time [Day]')\nplt.title('Data set split check')\n#On v\u00e9rifie la d\u00e9coupe du dataset\nplt.figure(figsize=(15, 6))\nplt.plot(train_df['Open'],label='train_df')\nplt.plot(val_df['Open'],label='val_df')\nplt.plot(test_df['Open'],label='test_df')\nplt.legend()\nplt.xlabel('Time [Day]')\nplt.title('Data set split check')\n\"\"\"\nNow peek at the distribution of the features. Some features do have long tails, but there are no obvious errors like the `-9999` wind velocity value.\n\"\"\"\ndf_std = (df - train_mean) \/ train_std\ndf_std = df_std.melt(var_name='Column', value_name='Normalized')\nplt.figure(figsize=(12, 6))\nax = sns.violinplot(x='Column', y='Normalized', data=df_std)\n_ = ax.set_xticklabels(df.keys(), rotation=90)\n\"\"\"\n## Data windowing\n\nThe models in this tutorial will make a set of predictions based on a window of consecutive samples from the data. \n\nThe main features of the input windows are:\n\n* The width (number of time steps) of the input and label windows\n* The time offset between them.\n* Which features are used as inputs, labels, or both. \n\nThis tutorial builds a variety of models (including Linear, DNN, CNN and RNN models), and uses them for both:\n\n* *Single-output*, and *multi-output* predictions.\n* *Single-time-step* and *multi-time-step* predictions.\n\nThis section focuses on implementing the data windowing so that it can be reused for all of those models.\n\n\"\"\"\n\"\"\"\nDepending on the task and type of model you may want to generate a variety of data windows. Here are some examples:\n\n1. For example, to make a single prediction 24h into the future, given 24h of history you might define a window like this:\n\n  ![One prediction 24h into the future.](images\/raw_window_24h.png)\n\n2. A model that makes a prediction 1h into the future, given 6h of history would need a window like this:\n\n  ![One prediction 1h into the future.](images\/raw_window_1h.png)\n\"\"\"\n\"\"\"\nThe rest of this section defines a `WindowGenerator` class. This class can:\n\n1. Handle the indexes and offsets as shown in the diagrams above.\n1. Split windows of features into a `(features, labels)` pairs.\n2. Plot the content of the resulting windows.\n3. Efficiently generate batches of these windows from the training, evaluation, and test data, using `tf.data.Dataset`s.\n\"\"\"\n\"\"\"\n### 1. Indexes and offsets\n\nStart by creating the `WindowGenerator` class. The `__init__` method includes all the necessary logic for the input and label indices.\n\nIt also takes the train, eval, and test dataframes as input. These will be converted to `tf.data.Dataset`s of windows later.\n\"\"\"\nclass WindowGenerator():\n  def __init__(self, input_width, label_width, shift,\n               train_df=train_df, val_df=val_df, test_df=test_df,\n               label_columns=None):\n    # Store the raw data.\n    self.train_df = train_df\n    self.val_df = val_df\n    self.test_df = test_df\n\n    # Work out the label column indices.\n    self.label_columns = label_columns\n    if label_columns is not None:\n      self.label_columns_indices = {name: i for i, name in\n                                    enumerate(label_columns)}\n    self.column_indices = {name: i for i, name in\n                           enumerate(train_df.columns)}\n\n    # Work out the window parameters.\n    self.input_width = input_width\n    self.label_width = label_width\n    self.shift = shift\n\n    self.total_window_size = input_width + shift\n\n    self.input_slice = slice(0, input_width)\n    self.input_indices = np.arange(self.total_window_size)[self.input_slice]\n\n    self.label_start = self.total_window_size - self.label_width\n    self.labels_slice = slice(self.label_start, None)\n    self.label_indices = np.arange(self.total_window_size)[self.labels_slice]\n\n  def __repr__(self):\n    return '\\n'.join([\n        f'Total window size: {self.total_window_size}',\n        f'Input indices: {self.input_indices}',\n        f'Label indices: {self.label_indices}',\n        f'Label column name(s): {self.label_columns}'])\n\"\"\"\nHere is code to create the 2 windows shown in the diagrams at the start of this section:\n\"\"\"\nw1 = WindowGenerator(input_width=24, label_width=1, shift=24,\n                     label_columns=['Open'])\nw1\nw1.label_columns_indices\nw1.column_indices\nw1.input_width\nw1.total_window_size\nw1.label_indices\nw2 = WindowGenerator(input_width=6, label_width=1, shift=1,\n                     label_columns=['Open'])\nw2\nw2 = WindowGenerator(input_width=60, label_width=1, shift=1,\n                     label_columns=['Open'])\nw2\n\"\"\"\n### 2. Split\nGiven a list consecutive inputs, the `split_window` method will convert them to a window of inputs and a window of labels.\n\nThe example `w2`, above, will be split like this:\n\n![The initial window is all consecutive samples, this splits it into an (inputs, labels) pairs](images\/split_window.png)\n\nThis diagram doesn't show the `features` axis of the data, but this `split_window` function also handles the `label_columns` so it can be used for both the single output and multi-output examples.\n\"\"\"\ndef split_window(self, features):\n  inputs = features[:, self.input_slice, :]\n  labels = features[:, self.labels_slice, :]\n  if self.label_columns is not None:\n    labels = tf.stack(\n        [labels[:, :, self.column_indices[name]] for name in self.label_columns],\n        axis=-1)\n\n  # Slicing doesn't preserve static shape information, so set the shapes\n  # manually. This way the `tf.data.Datasets` are easier to inspect.\n  inputs.set_shape([None, self.input_width, None])\n  labels.set_shape([None, self.label_width, None])\n\n  return inputs, labels\n\nWindowGenerator.split_window = split_window\nprint(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n\n\"\"\"\nTry it out:\n\"\"\"\n#######################################################################################\n####            ATTENTION, ICI ON UTILISE train_df AU LIEU DE test_df !!!!!\n#######################################################################################\n\n# Stack three slices, the length of the total window:\n\"\"\"\nexample_window = tf.stack([np.array(train_df[:w2.total_window_size]),\n                           np.array(train_df[100:100+w2.total_window_size]),\n                           np.array(train_df[200:200+w2.total_window_size])])\n\"\"\"\n\nexample_window = tf.stack([np.array(test_df[:w2.total_window_size]),\n                           np.array(test_df[10:10+w2.total_window_size]),\n                           np.array(test_df[20:20+w2.total_window_size])])\n\n\n\nexample_inputs, example_labels = w2.split_window(example_window)\n\nprint('All shapes are: (batch, time, features)')\nprint(f'Window shape: {example_window.shape}')\nprint(f'Inputs shape: {example_inputs.shape}')\nprint(f'labels shape: {example_labels.shape}')\n\"\"\"\nTypically data in TensorFlow is packed into arrays where the outermost index is across examples (the \"batch\" dimension). The middle indices are the \"time\" or \"space\" (width, height) dimension(s). The innermost indices are the features.\n\nThe code above took a batch of 3, 7-timestep windows, with 19 features at each time step. It split them into a batch of 6-timestep, 19 feature inputs, and a 1-timestep 1-feature label. The label only has one feature because the `WindowGenerator` was initialized with `label_columns=['T (degC)']`. Initially this tutorial will build models that predict single output labels.\n\"\"\"\n\"\"\"\n### 3. Plot\n\nHere is a plot method that allows a simple visualization of the split window:\n\"\"\"\nw2.example = example_inputs, example_labels\ndef plot(self, model=None, plot_col='Open', max_subplots=3):\n  inputs, labels = self.example\n  plt.figure(figsize=(15, 10))\n  plot_col_index = self.column_indices[plot_col]\n  max_n = min(max_subplots, len(inputs))\n  for n in range(max_n):\n    plt.subplot(3, 1, n+1)\n    plt.ylabel(f'{plot_col} [normed]')\n    plt.plot(self.input_indices, inputs[n, :, plot_col_index],\n             label='Inputs', marker='.', zorder=-10)\n\n    if self.label_columns:\n      label_col_index = self.label_columns_indices.get(plot_col, None)\n    else:\n      label_col_index = plot_col_index\n\n    if label_col_index is None:\n      continue\n\n    plt.scatter(self.label_indices, labels[n, :, label_col_index],\n                edgecolors='k', label='Labels', c='#2ca02c', s=64)\n    if model is not None:\n      predictions = model(inputs)\n      plt.scatter(self.label_indices, predictions[n, :, label_col_index],\n                  marker='X', edgecolors='k', label='Predictions',\n                  c='#ff7f0e', s=64)\n\n    if n == 0:\n      plt.legend()\n\n  plt.xlabel('Time [day]')\n\nWindowGenerator.plot = plot\n\"\"\"\nThis plot aligns inputs, labels, and (later) predictions based on the time that the item refers to:\n\"\"\"\nw2.plot()\n\"\"\"\nYou can plot the other columns, but the example window `w2` configuration only has labels for the `T (degC)` column.\n\"\"\"\nw2.plot(plot_col='Volume')\n\"\"\"\n### 4. Create `tf.data.Dataset`s\n\"\"\"\n\"\"\"\nFinally this `make_dataset` method will take a time series `DataFrame` and convert it to a `tf.data.Dataset` of `(input_window, label_window)` pairs using the `preprocessing.timeseries_dataset_from_array` function.\n\"\"\"\ndef make_dataset(self, data):\n  data = np.array(data, dtype=np.float32)\n  ds = tf.keras.preprocessing.timeseries_dataset_from_array(\n      data=data,\n      targets=None,\n      sequence_length=self.total_window_size,\n      sequence_stride=1,\n      shuffle=True,\n      batch_size=32,)   #batch_size=32\n\n  ds = ds.map(self.split_window)\n\n  return ds\n\nWindowGenerator.make_dataset = make_dataset\n\"\"\"\nThe `WindowGenerator` object holds training, validation and test data. Add properties for accessing them as `tf.data.Datasets` using the above `make_dataset` method. Also add a standard example batch for easy access and plotting:\n\"\"\"\n@property\ndef train(self):\n  return self.make_dataset(self.train_df)\n\n@property\ndef val(self):\n  return self.make_dataset(self.val_df)\n\n@property\ndef test(self):\n  return self.make_dataset(self.test_df)\n\n@property\ndef example(self):\n  \"\"\"Get and cache an example batch of `inputs, labels` for plotting.\"\"\"\n  #result = getattr(self, '_example', None)\n  #########################################\n  result = next(iter(self.test))\n  if result is None:\n    # No example batch was found, so get one from the `.train` dataset\n    print(\" #### No example batch was found, so get one from the `.train` dataset ####\")\n    #########################################\n    #result = next(iter(self.train))\n    result = next(iter(self.test))\n    # And cache it for next time\n    self._example = result\n  return result\n\nWindowGenerator.train = train\nWindowGenerator.val = val\nWindowGenerator.test = test\nWindowGenerator.example = example\n\"\"\"\nNow the `WindowGenerator` object gives you access to the `tf.data.Dataset` objects, so you can easily iterate over the data.\n\nThe `Dataset.element_spec` property tells you the structure, `dtypes` and shapes of the dataset elements.\n\"\"\"\n# Each element is an (inputs, label) pair\n#w2.train.element_spec\n#############################################\nw2.test.element_spec\nw2.plot()\n\"\"\"\nIterating over a `Dataset` yields concrete batches:\n\"\"\"\n#for example_inputs, example_labels in w2.train.take(1):\n#############################################\nfor example_inputs, example_labels in w2.test.take(1):\n  print(f'Inputs shape (batch, time, features): {example_inputs.shape}')\n  print(f'Labels shape (batch, time, features): {example_labels.shape}')\nw2.plot()\n\"\"\"\n## Single step models\n\nThe simplest model you can build on this sort of data is one that predicts a single feature's value, 1 timestep (1h) in the future based only on the current conditions.\n\nSo start by building models to predict the `T (degC)` value 1h into the future.\n\n![Predict the next time step](images\/narrow_window.png)\n\nConfigure a `WindowGenerator` object to produce these single-step `(input, label)` pairs:\n\"\"\"\nw2.plot()\nsingle_step_window = WindowGenerator(\n    input_width=1, label_width=1, shift=1,\n    label_columns=['Open'])\nsingle_step_window\n\"\"\"\nThe `window` object creates `tf.data.Datasets` from the training, validation, and test sets, allowing you to easily iterate over batches of data.\n\n\"\"\"\n#for example_inputs, example_labels in single_step_window.train.take(1):\n#############################################\nfor example_inputs, example_labels in single_step_window.test.take(1):\n  print(f'Inputs shape (batch, time, features): {example_inputs.shape}')\n  print(f'Labels shape (batch, time, features): {example_labels.shape}')\n#Creat a funtion to plot training loss\ndef plotLoss():\n    loss = history.history['loss']\n    val_loss = history.history['val_loss']\n    mean_absolute_error = history.history['mean_absolute_error']\n\n    epochs = range(1, len(loss) + 1)\n\n    plt.plot(epochs, loss, label='Training loss')\n    plt.plot(epochs, val_loss, label='Validation loss')\n    plt.plot(epochs, mean_absolute_error, label='mean_absolute_error')\n    plt.title('Training and validation loss')\n    plt.legend()\n\n    plt.show()\n\"\"\"\n### Baseline\n\nBefore building a trainable model it would be good to have a performance baseline as a point for comparison with the later more complicated models.\n\nThis first task is to predict temperature 1h in the future given the current value of all features. The current values include the current temperature. \n\nSo start with a model that just returns the current temperature as the prediction, predicting \"No change\". This is a reasonable baseline since temperature changes slowly. Of course, this baseline will work less well if you make a prediction further in the future.\n\n![Send the input to the output](images\/baseline.png)\n\"\"\"\nclass Baseline(tf.keras.Model):\n  def __init__(self, label_index=None):\n    super().__init__()\n    self.label_index = label_index\n\n  def call(self, inputs):\n    if self.label_index is None:\n      return inputs\n    result = inputs[:, :, self.label_index]\n    return result[:, :, tf.newaxis]\n\"\"\"\nInstantiate and evaluate this model:\n\"\"\"\nbaseline = Baseline(label_index=column_indices['Open'])\n\nbaseline.compile(loss=tf.losses.MeanSquaredError(),\n                 metrics=[tf.metrics.MeanAbsoluteError()])\n\nval_performance = {}\nperformance = {}\nval_performance['Baseline'] = baseline.evaluate(single_step_window.val)\nperformance['Baseline'] = baseline.evaluate(single_step_window.test, verbose=0)\n\"\"\"\nThat printed some performance metrics, but those don't give you a feeling for how well the model is doing.\n\nThe `WindowGenerator` has a plot method, but the plots won't be very interesting with only a single sample. So, create a wider `WindowGenerator` that generates windows 24h of consecutive inputs and labels at a time. \n\nThe `wide_window` doesn't change the way the model operates. The model still makes predictions 1h into the future based on a single input time step. Here the `time` axis acts like the `batch` axis: Each prediction is made independently with no interaction between time steps.\n\"\"\"\nwide_window = WindowGenerator(\n    input_width=40, label_width=40, shift=1,\n    label_columns=['Open'])\n\nwide_window\n\"\"\"\nThis expanded window can be passed directly to the same `baseline` model without any code changes. This is possible because the inputs and labels have the same number of timesteps, and the baseline just forwards the input to the output:\n\n  ![One prediction 1h into the future, ever hour.](images\/last_window.png)\n\"\"\"\nprint('Input shape:', wide_window.example[0].shape)\nprint('Output shape:', baseline(wide_window.example[0]).shape)\n\"\"\"\nPlotting the baseline model's predictions you can see that it is simply the labels, shifted right by 1h.\n\"\"\"\nwide_window.plot(baseline)\n\"\"\"\nIn the above plots of three examples the single step model is run over the course of 24h. This deserves some explanation:\n\n* The blue \"Inputs\" line shows the input temperature at each time step. The model recieves all features, this plot only shows the temperature.\n* The green \"Labels\" dots show the target prediction value. These dots are shown at the prediction time, not the input time. That is why the range of labels is shifted 1 step relative to the inputs.\n* The orange \"Predictions\" crosses are the model's prediction's for each output time step. If the model were predicting perfectly the predictions would land directly on the \"labels\".\n\"\"\"\n\"\"\"\n### Linear model\n\nThe simplest **trainable** model you can apply to this task is to insert linear transformation between the input and output. In this case the output from a time step only depends on that step:\n\n![A single step prediction](images\/narrow_window.png)\n\nA `layers.Dense` with no `activation` set is a linear model. The layer only transforms the last axis of the data from `(batch, time, inputs)` to `(batch, time, units)`, it is applied independently to every item across the `batch` and `time` axes.\n\"\"\"\nlinear = tf.keras.Sequential([\n    tf.keras.layers.Dense(units=1)\n])\nprint('Input shape:', single_step_window.example[0].shape)\nprint('Output shape:', linear(single_step_window.example[0]).shape)\n\"\"\"\nThis tutorial trains many models, so package the training procedure into a function:\n\"\"\"\n# To gain computation time y limited the MAX_EPOCHS.\n# You can try biger value but take care to overfiting :p\nMAX_EPOCHS = 1000 #4000\n\ndef compile_and_fit(model, window, patience=4000):  #40\n  early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',\n                                                    patience=patience,\n                                                    mode='min')\n\n  model.compile(loss=tf.losses.MeanSquaredError(),\n                optimizer=tf.optimizers.Adam(),  #learning_rate=0.001\n                metrics=[tf.metrics.MeanAbsoluteError()])\n\n  history = model.fit(window.train, epochs=MAX_EPOCHS,\n                      validation_data=window.val,\n                      callbacks=[early_stopping])\n  return history\n\"\"\"\nTrain the model and evaluate its performance:\n\"\"\"\nMAX_EPOCHS = 1000\nhistory = compile_and_fit(linear, single_step_window)\n\nIPython.display.clear_output()\n\nval_performance['Linear'] = linear.evaluate(single_step_window.val)\nperformance['Linear'] = linear.evaluate(single_step_window.test, verbose=0)\n\"\"\"\nLike the `baseline` model, the linear model can be called on batches of wide windows. Used this way the model makes a set of independent predictions on consecutive time steps. The `time` axis acts like another `batch` axis. There are no interactions between the predictions at each time step.\n\n![A single step prediction](images\/wide_window.png)\n\"\"\"\nplotLoss()\nprint('Input shape:', wide_window.example[0].shape)\nprint('Output shape:', baseline(wide_window.example[0]).shape)\n\"\"\"\nHere is the plot of its example predictions on the `wide_window`, note how in many cases the prediction is clearly better than just returning the input temperature, but in a few cases it's worse:\n\"\"\"\nwide_window.plot(linear)\nlinear.summary()  ###\n\"\"\"\nOne advantage to linear models is that they're relatively simple to  interpret.\nYou can pull out the layer's weights, and see the weight assigned to each input:\n\"\"\"\nplt.bar(x = range(len(train_df.columns)),\n        height=linear.layers[0].kernel[:,0].numpy())\naxis = plt.gca()\naxis.set_xticks(range(len(train_df.columns)))\n_ = axis.set_xticklabels(train_df.columns, rotation=90)\n\"\"\"\nSometimes the model doesn't even place the most weight on the input `T (degC)`. This is one of the risks of random initialization. \n\"\"\"\n\"\"\"\n### Dense\n\nBefore applying models that actually operate on multiple time-steps, it's worth checking the performance of deeper, more powerful, single input step models.\n\nHere's a model similar to the `linear` model, except it stacks several a few `Dense` layers between the input and the output: \n\"\"\"\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import regularizers\n\n\ndense = tf.keras.Sequential([\n    tf.keras.layers.Dense(units=10),\n    tf.keras.layers.Dense(units=10),\n    tf.keras.layers.Dense(units=5),\n    tf.keras.layers.Dense(units=1),\n])\n\nMAX_EPOCHS = 200\nhistory = compile_and_fit(dense, single_step_window)\n\nIPython.display.clear_output()\n\nval_performance['Dense'] = dense.evaluate(single_step_window.val)\nperformance['Dense'] = dense.evaluate(single_step_window.test, verbose=0)\nplotLoss()\nwide_window.plot(dense)\ndense.summary()\n\"\"\"\n### Multi-step dense\n\nA single-time-step model has no context for the current values of its inputs. It can't see how the input features are changing over time. To address this issue the model needs access to multiple time steps when making predictions:\n\n![Three time steps are used for each prediction.](images\/conv_window.png)\n\n\"\"\"\n\"\"\"\nThe `baseline`, `linear` and `dense` models handled each time step independently. Here the model will take multiple time steps as input to produce a single output.\n\nCreate a `WindowGenerator` that will produce batches of the 3h of inputs and, 1h of labels:\n\"\"\"\n\"\"\"\nNote that the `Window`'s `shift` parameter is relative to the end of the two windows.\n\n\"\"\"\nCONV_WIDTH = 10\nconv_window = WindowGenerator(\n    input_width=CONV_WIDTH,\n    label_width=1,\n    shift=1,\n    label_columns=['Open'])\n\nconv_window\nconv_window.plot()\nplt.title(\"Given 10 days inputs, predict on day into the future.\")\n\"\"\"\nYou could train a `dense` model on a multiple-input-step window by adding a `layers.Flatten` as the first layer of the model:\n\"\"\"\nmulti_step_dense = tf.keras.Sequential([\n    # Shape: (time, features) => (time*features)\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(units=1),\n    # Add back the time dimension.\n    # Shape: (outputs) => (1, outputs)\n    tf.keras.layers.Reshape([1, -1]),\n])\nprint('Input shape:', conv_window.example[0].shape)\nprint('Output shape:', multi_step_dense(conv_window.example[0]).shape)\nMAX_EPOCHS = 300\nhistory = compile_and_fit(multi_step_dense, conv_window)\n\nIPython.display.clear_output()\nval_performance['Multi step dense'] = multi_step_dense.evaluate(conv_window.val)\nperformance['Multi step dense'] = multi_step_dense.evaluate(conv_window.test, verbose=0)\nplotLoss()\nmulti_step_dense.summary()\nconv_window.plot(multi_step_dense)\n\"\"\"\nThe main down-side of this approach is that the resulting model can only be executed on input windows of exactly this shape. \n\"\"\"\nprint('Input shape:', wide_window.example[0].shape)\ntry:\n  print('Output shape:', multi_step_dense(wide_window.example[0]).shape)\nexcept Exception as e:\n  print(f'\\n{type(e).__name__}:{e}')\n\"\"\"\nThe convolutional models in the next section fix this problem.\n\"\"\"\n\"\"\"\n### Convolution neural network\n \nA convolution layer (`layers.Conv1D`) also takes multiple time steps as input to each prediction.\n\"\"\"\n\"\"\"\nBelow is the **same** model as `multi_step_dense`, re-written with a convolution. \n\nNote the changes:\n* The `layers.Flatten` and the first `layers.Dense` are replaced by a `layers.Conv1D`.\n* The `layers.Reshape` is no longer necessary since the convolution keeps the time axis in its output.\n\"\"\"\nconv_model = tf.keras.Sequential([\n    tf.keras.layers.Conv1D(filters=8,\n                           kernel_size=(CONV_WIDTH,)),\n    tf.keras.layers.Dense(units=1),\n])\n\"\"\"\nRun it on an example batch to see that the model produces outputs with the expected shape:\n\"\"\"\nprint(\"Conv model on `conv_window`\")\nprint('Input shape:', conv_window.example[0].shape)\nprint('Output shape:', conv_model(conv_window.example[0]).shape)\n\"\"\"\nTrain and evaluate it on the ` conv_window` and it should give performance similar to the `multi_step_dense` model.\n\"\"\"\nMAX_EPOCHS = 50\nhistory = compile_and_fit(conv_model, conv_window)\n\nIPython.display.clear_output()\nval_performance['Conv'] = conv_model.evaluate(conv_window.val)\nperformance['Conv'] = conv_model.evaluate(conv_window.test, verbose=0)\nplotLoss()\nconv_window.plot(conv_model)\nconv_model.summary()\nwide_window = WindowGenerator(\n    input_width=60, label_width=60, shift=1,\n    label_columns=['Open'])\n\nwide_window\n\"\"\"\nThe difference between this `conv_model` and the `multi_step_dense` model is that the `conv_model` can be run on inputs of any length. The convolutional layer is applied to a sliding window of inputs:\n\n![Executing a convolutional model on a sequence](images\/wide_conv_window.png)\n\nIf you run it on wider input, it produces wider output:\n\"\"\"\nprint(\"Wide window\")\nprint('Input shape:', wide_window.example[0].shape)\nprint('Labels shape:', wide_window.example[1].shape)\nprint('Output shape:', conv_model(wide_window.example[0]).shape)\n\"\"\"\nNote that the output is shorter than the input. To make training or plotting work, you need the labels, and prediction to have the same length. So build a `WindowGenerator` to produce wide windows with a few extra input time steps so the label and prediction lengths match: \n\"\"\"\nLABEL_WIDTH = 20\nINPUT_WIDTH = LABEL_WIDTH + (CONV_WIDTH - 1)\nwide_conv_window = WindowGenerator(\n    input_width=INPUT_WIDTH,\n    label_width=LABEL_WIDTH,\n    shift=1,\n    label_columns=['Open'])\n\nwide_conv_window\nprint(\"Wide conv window\")\nprint('Input shape:', wide_conv_window.example[0].shape)\nprint('Labels shape:', wide_conv_window.example[1].shape)\nprint('Output shape:', conv_model(wide_conv_window.example[0]).shape)\n\"\"\"\nNow you can plot the model's predictions on a wider window. Note the 3 input time steps before the first prediction. Every prediction here is based on the 3 preceding timesteps:\n\"\"\"\nwide_conv_window.plot(conv_model)\n\"\"\"\n### Recurrent neural network\n\nA Recurrent Neural Network (RNN) is a type of neural network well-suited to time series data. RNNs process a time series step-by-step, maintaining an internal state from time-step to time-step.\n\nFor more details, read the [text generation tutorial](https:\/\/www.tensorflow.org\/tutorials\/text\/text_generation) or the [RNN guide](https:\/\/www.tensorflow.org\/guide\/keras\/rnn). \n\nIn this tutorial, you will use an RNN layer called Long Short Term Memory ([LSTM](https:\/\/www.tensorflow.org\/versions\/r2.0\/api_docs\/python\/tf\/keras\/layers\/LSTM)).\n\"\"\"\n\"\"\"\nAn important constructor argument for all keras RNN layers is the `return_sequences` argument. This setting can configure the layer in one of two ways.\n\n1. If `False`, the default, the layer only returns the output of the final timestep, giving the model time to warm up its internal state before making a single prediction: \n\n![An lstm warming up and making a single prediction](images\/lstm_1_window.png)\n\n2. If `True` the layer returns an output for each input. This is useful for:\n  * Stacking RNN layers. \n  * Training a model on multiple timesteps simultaneously.\n\n![An lstm making a prediction after every timestep](images\/lstm_many_window.png)\n\"\"\"\nlstm_model = tf.keras.models.Sequential([\n    # Shape [batch, time, features] => [batch, time, lstm_units]\n    tf.keras.layers.LSTM(1, return_sequences=True),\n    # Shape => [batch, time, features]\n    tf.keras.layers.Dense(units=5),\n    tf.keras.layers.Dense(units=1)\n])\n\"\"\"\nWith `return_sequences=True` the model can be trained on 24h of data at a time.\n\nNote: This will give a pessimistic view of the model's performance. On the first timestep the model has no access to previous steps, and so can't do any better than the simple `linear` and `dense` models shown earlier.\n\"\"\"\nprint('Input shape:', wide_window.example[0].shape)\nprint('Output shape:', lstm_model(wide_window.example[0]).shape)\nMAX_EPOCHS = 250\nhistory = compile_and_fit(lstm_model, wide_window)\n\nIPython.display.clear_output()\nval_performance['LSTM'] = lstm_model.evaluate(wide_window.val)\nperformance['LSTM'] = lstm_model.evaluate(wide_window.test, verbose=0)\nplotLoss()\nwide_window.plot(lstm_model)\nlstm_model.summary()\n\"\"\"\n### Performance\n\"\"\"\n\"\"\"\nWith this dataset typically each of the models does slightly better than the one before it.\n\"\"\"\nx = np.arange(len(performance))\nwidth = 0.3\nmetric_name = 'mean_absolute_error'\nmetric_index = lstm_model.metrics_names.index('mean_absolute_error')\nval_mae = [v[metric_index] for v in val_performance.values()]\ntest_mae = [v[metric_index] for v in performance.values()]\n\nplt.ylabel('mean_absolute_error [Open, normalized]')\nplt.bar(x - 0.17, val_mae, width, label='Validation')\nplt.bar(x + 0.17, test_mae, width, label='Test')\nplt.xticks(ticks=x, labels=performance.keys(),\n           rotation=45)\n_ = plt.legend()\nfor name, value in performance.items():\n  print(f'{name:12s}: {value[1]:0.4f}')\n\"\"\"\n### Multi-output models\n\nThe models so far all predicted a single output feature, `T (degC)`, for a single time step.\n\nAll of these models can be converted to predict multiple features just by changing the number of units in the output layer and adjusting the training windows to include all features in the `labels`.\n\n\"\"\"\nsingle_step_window = WindowGenerator(\n    # `WindowGenerator` returns all features as labels if you \n    # don't set the `label_columns` argument.\n    input_width=1, label_width=1, shift=1)\n\nwide_window = WindowGenerator(\n    input_width=24, label_width=24, shift=1)\n\nfor example_inputs, example_labels in wide_window.train.take(1):\n  print(f'Inputs shape (batch, time, features): {example_inputs.shape}')\n  print(f'Labels shape (batch, time, features): {example_labels.shape}')\n\"\"\"\nNote above that the `features` axis of the labels now has the same depth as the inputs, instead of 1.\n\"\"\"\n\"\"\"\n#### Baseline\n\nThe same baseline model can be used here, but this time repeating all features instead of selecting a specific `label_index`.\n\"\"\"\nbaseline = Baseline()\nbaseline.compile(loss=tf.losses.MeanSquaredError(),\n                 metrics=[tf.metrics.MeanAbsoluteError()])\nval_performance = {}\nperformance = {}\nval_performance['Baseline'] = baseline.evaluate(wide_window.val)\nperformance['Baseline'] = baseline.evaluate(wide_window.test, verbose=0)\n\n\"\"\"\n\n#### Dense\n\"\"\"\ndense = tf.keras.Sequential([\n    tf.keras.layers.Dense(units=10),\n    tf.keras.layers.Dense(units=10),\n    tf.keras.layers.Dense(units=5),\n    tf.keras.layers.Dense(units=1),\n    tf.keras.layers.Dense(units=num_features)\n])\nMAX_EPOCHS = 50\n\nhistory = compile_and_fit(dense, single_step_window)\n\nIPython.display.clear_output()\nval_performance['Dense'] = dense.evaluate(single_step_window.val)\nperformance['Dense'] = dense.evaluate(single_step_window.test, verbose=0)\n\nplotLoss()\n\"\"\"\n#### RNN\n\n\"\"\"\n%%time\nwide_window = WindowGenerator(\n    input_width=24, label_width=24, shift=1)\n\nlstm_model = tf.keras.models.Sequential([\n    # Shape [batch, time, features] => [batch, time, lstm_units]\n    tf.keras.layers.LSTM(32, return_sequences=True),\n    # Shape => [batch, time, features]\n    tf.keras.layers.Dense(units=num_features)\n])\n\nMAX_EPOCHS = 20\n\nhistory = compile_and_fit(lstm_model, wide_window)\n\nIPython.display.clear_output()\nval_performance['LSTM'] = lstm_model.evaluate( wide_window.val)\nperformance['LSTM'] = lstm_model.evaluate( wide_window.test, verbose=0)\n\nplotLoss()\n\nprint()\n\"\"\"\n<a id=\"residual\"><\/a>\n\n#### Advanced: Residual connections\n\nThe `Baseline` model from earlier took advantage of the fact that the sequence doesn't change drastically from time step to time step. Every model trained in this tutorial so far was randomly initialized, and then had to learn that the output is a a small change from the previous time step.\n\nWhile you can get around this issue with careful initialization, it's  simpler to build this into the model structure.\n\nIt's common in time series analysis to build models that instead of predicting the next value, predict how the value will change in the next timestep.\nSimilarly, \"Residual networks\" or \"ResNets\" in deep learning refer to architectures where each layer adds to the model's accumulating result.\n\nThat is how you take advantage of the knowledge that the change should be small.\n\n![A model with a residual connection](images\/residual.png)\n\nEssentially this initializes the model to match the `Baseline`. For this task it helps models converge faster, with slightly better performance.\n\"\"\"\n\"\"\"\nThis approach can be used in conjunction with any model discussed in this tutorial. \n\nHere it is being applied to the LSTM model, note the use of the `tf.initializers.zeros` to ensure that the initial predicted changes are small, and don't overpower the residual connection. There are no symmetry-breaking concerns for the gradients here, since the `zeros` are only used on the last layer.\n\"\"\"\nclass ResidualWrapper(tf.keras.Model):\n  def __init__(self, model):\n    super().__init__()\n    self.model = model\n\n  def call(self, inputs, *args, **kwargs):\n    delta = self.model(inputs, *args, **kwargs)\n\n    # The prediction for each timestep is the input\n    # from the previous time step plus the delta\n    # calculated by the model.\n    return inputs + delta\n%%time\nresidual_lstm = ResidualWrapper(\n    tf.keras.Sequential([\n    tf.keras.layers.LSTM(32, return_sequences=True),\n    tf.keras.layers.Dense(\n        num_features,\n        # The predicted deltas should start small\n        # So initialize the output layer with zeros\n        kernel_initializer=tf.initializers.zeros)\n]))\n\nMAX_EPOCHS = 20\nhistory = compile_and_fit(residual_lstm, wide_window)\n\nIPython.display.clear_output()\nval_performance['Residual LSTM'] = residual_lstm.evaluate(wide_window.val)\nperformance['Residual LSTM'] = residual_lstm.evaluate(wide_window.test, verbose=0)\n\nplotLoss()\n\nprint()\n\"\"\"\n#### Performance\n\"\"\"\n\"\"\"\nHere is the overall performance for these multi-output models.\n\"\"\"\nx = np.arange(len(performance))\nwidth = 0.3\n\nmetric_name = 'mean_absolute_error'\nmetric_index = lstm_model.metrics_names.index('mean_absolute_error')\nval_mae = [v[metric_index] for v in val_performance.values()]\ntest_mae = [v[metric_index] for v in performance.values()]\n\nplt.bar(x - 0.17, val_mae, width, label='Validation')\nplt.bar(x + 0.17, test_mae, width, label='Test')\nplt.xticks(ticks=x, labels=performance.keys(),\n           rotation=45)\nplt.ylabel('MAE (average over all outputs)')\n_ = plt.legend()\nfor name, value in performance.items():\n  print(f'{name:15s}: {value[1]:0.4f}')\n\"\"\"\nThe above performances are averaged across all model outputs.\n\"\"\"\n\"\"\"\n## Multi-step models\n\nBoth the single-output and multiple-output models in the previous sections made **single time step predictions**, 1h into the future.\n\nThis section looks at how to expand these models to make **multiple time step predictions**.\n\nIn a multi-step prediction, the model needs to learn to predict a range of future values. Thus, unlike a single step model, where only a single future point is predicted, a multi-step model predicts a sequence of the future values.\n\nThere are two rough approaches to this:\n\n1. Single shot predictions where the entire time series is predicted at once.\n2. Autoregressive predictions where the model only makes single step predictions and its output is fed back as its input.\n\nIn this section all the models will predict **all the features across all output time steps**.\n\n\"\"\"\n\"\"\"\nFor the multi-step model, the training data again consists of hourly samples. However, here, the models will learn to predict 24h of the future, given 24h of the past.\n\nHere is a `Window` object that generates these slices from the dataset:\n\"\"\"\nOUT_STEPS = 5\nIN_WIDTH = 10\n\nmulti_window = WindowGenerator(input_width=IN_WIDTH,\n                               label_width=OUT_STEPS,\n                               shift=OUT_STEPS)\n\nmulti_window.plot()\nmulti_window\n\"\"\"\n### Baselines\n\"\"\"\n\"\"\"\nA simple baseline for this task is to repeat the last input time step for the required number of output timesteps:\n\n![Repeat the last input, for each output step](images\/multistep_last.png)\n\"\"\"\nclass MultiStepLastBaseline(tf.keras.Model):\n  def call(self, inputs):\n    return tf.tile(inputs[:, -1:, :], [1, OUT_STEPS, 1])\n\nlast_baseline = MultiStepLastBaseline()\nlast_baseline.compile(loss=tf.losses.MeanSquaredError(),\n                      metrics=[tf.metrics.MeanAbsoluteError()])\n\nmulti_val_performance = {}\nmulti_performance = {}\n\nmulti_val_performance['Last'] = last_baseline.evaluate(multi_window.val)\nmulti_performance['Last'] = last_baseline.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(last_baseline)\n\"\"\"\nSince this task is to predict 24h given 24h another simple approach is to repeat the previous day, assuming tomorrow will be similar:\n\n![Repeat the previous day](images\/multistep_repeat.png)\n\"\"\"\nclass RepeatBaseline(tf.keras.Model):\n  def call(self, inputs):\n    return inputs\n\nrepeat_baseline = RepeatBaseline()\nrepeat_baseline.compile(loss=tf.losses.MeanSquaredError(),\n                        metrics=[tf.metrics.MeanAbsoluteError()])\n\nif OUT_STEPS == IN_WIDTH:\n    multi_val_performance['Repeat'] = repeat_baseline.evaluate(multi_window.val)\n    multi_performance['Repeat'] = repeat_baseline.evaluate(multi_window.test, verbose=0)\n\n    multi_window.plot(repeat_baseline)\n\"\"\"\n### Single-shot models\n\nOne high level approach to this problem is use a \"single-shot\" model, where the model makes the entire sequence prediction in a single step.\n\nThis can be implemented efficiently as a `layers.Dense` with `OUT_STEPS*features` output units. The model just needs to reshape that output to the required `(OUTPUT_STEPS, features)`.\n\"\"\"\n\"\"\"\n#### Linear\n\nA simple linear model based on the last input time step does better than either baseline, but is underpowered. The model needs to predict `OUTPUT_STEPS` time steps, from a single input time step with a linear projection. It can only capture a low-dimensional slice of the behavior, likely based mainly on the time of day and time of year.\n\n![Predct all timesteps from the last time-step](images\/multistep_dense.png)\n\"\"\"\nmulti_linear_model = tf.keras.Sequential([\n    # Take the last time-step.\n    # Shape [batch, time, features] => [batch, 1, features]\n    tf.keras.layers.Lambda(lambda x: x[:, -1:, :]),\n    # Shape => [batch, 1, out_steps*features]\n    tf.keras.layers.Dense(OUT_STEPS*num_features,\n                          kernel_initializer=tf.initializers.zeros),\n    # Shape => [batch, out_steps, features]\n    tf.keras.layers.Reshape([OUT_STEPS, num_features])\n])\n\nMAX_EPOCHS = 300\n\nhistory = compile_and_fit(multi_linear_model, multi_window)\n\nIPython.display.clear_output()\n\nplotLoss()\n\nmulti_val_performance['Linear'] = multi_linear_model.evaluate(multi_window.val)\nmulti_performance['Linear'] = multi_linear_model.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(multi_linear_model)\n\nmulti_linear_model.summary()\n\"\"\"\n#### Dense\n\nAdding a `layers.Dense` between the input and output gives the linear model more power, but is still only based on a single input timestep.\n\"\"\"\nmulti_dense_model = tf.keras.Sequential([\n    # Take the last time step.\n    # Shape [batch, time, features] => [batch, 1, features]\n    tf.keras.layers.Lambda(lambda x: x[:, -1:, :]),\n    # Shape => [batch, 1, dense_units]\n    tf.keras.layers.Dense(20),\n    # Shape => [batch, out_steps*features]\n    tf.keras.layers.Dense(OUT_STEPS*num_features,\n                          kernel_initializer=tf.initializers.zeros),\n    # Shape => [batch, out_steps, features]\n    tf.keras.layers.Reshape([OUT_STEPS, num_features])\n])\n\nMAX_EPOCHS = 300\nhistory = compile_and_fit(multi_dense_model, multi_window)\n\nIPython.display.clear_output()\n\nplotLoss()\n\nmulti_val_performance['Dense'] = multi_dense_model.evaluate(multi_window.val)\nmulti_performance['Dense'] = multi_dense_model.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(multi_dense_model)\n\nmulti_dense_model.summary()\n\"\"\"\n#### CNN\n\"\"\"\n\"\"\"\nA convolutional model makes predictions based on a fixed-width history, which may lead to better performance than the dense model since it can see how things are changing over time:\n\n![A convolutional model sees how things change over time](images\/multistep_conv.png)\n\"\"\"\nCONV_WIDTH = 3\nmulti_conv_model = tf.keras.Sequential([\n    # Shape [batch, time, features] => [batch, CONV_WIDTH, features]\n    tf.keras.layers.Lambda(lambda x: x[:, -CONV_WIDTH:, :]),\n    # Shape => [batch, 1, conv_units]\n    tf.keras.layers.Conv1D(64, kernel_size=(CONV_WIDTH)),\n    # Shape => [batch, 1,  out_steps*features]\n    tf.keras.layers.Dense(OUT_STEPS*num_features,\n                          kernel_initializer=tf.initializers.zeros),\n    # Shape => [batch, out_steps, features]\n    tf.keras.layers.Reshape([OUT_STEPS, num_features])\n])\n\n'''\nmulti_conv_model = tf.keras.Sequential([\n    # Shape [batch, time, features] => [batch, CONV_WIDTH, features]\n    tf.keras.layers.Lambda(lambda x: x[:, -CONV_WIDTH:, :]),\n    # Shape => [batch, 1, conv_units]\n    tf.keras.layers.Conv1D(1024, activation='relu', kernel_size=(CONV_WIDTH)),\n    # Shape => [batch, 1,  out_steps*features]\n    tf.keras.layers.Dense(2048, activation='relu'),\n    tf.keras.layers.Dense(2048, activation='relu'),\n    tf.keras.layers.Dense(2048, activation='relu'),\n    tf.keras.layers.Dense(2048, activation='relu'),\n    tf.keras.layers.Dense(512, activation='relu'),  \n    tf.keras.layers.Dense(256, activation='relu'),\n    tf.keras.layers.Dense(OUT_STEPS*num_features,\n                          kernel_initializer=tf.initializers.zeros),\n    # Shape => [batch, out_steps, features]\n    tf.keras.layers.Reshape([OUT_STEPS, num_features])\n])\n'''\nMAX_EPOCHS = 100\nhistory = compile_and_fit(multi_conv_model, multi_window)\n\nIPython.display.clear_output()\n\nplotLoss()\n\nmulti_val_performance['Conv'] = multi_conv_model.evaluate(multi_window.val)\nmulti_performance['Conv'] = multi_conv_model.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(multi_conv_model)\n\nmulti_conv_model.summary()\n\"\"\"\n#### RNN\n\"\"\"\n\"\"\"\nA recurrent model can learn to use a long history of inputs, if it's relevant to the predictions the model is making. Here the model will accumulate internal state for 24h, before making a single prediction for the next 24h.\n\nIn this single-shot format, the LSTM only needs to produce an output at the last time step, so set `return_sequences=False`.\n\n![The lstm accumulates state over the input window, and makes a single prediction for the next 24h](images\/multistep_lstm.png)\n\n\"\"\"\nmulti_lstm_model = tf.keras.Sequential([\n    # Shape [batch, time, features] => [batch, lstm_units]\n    # Adding more `lstm_units` just overfits more quickly.\n    tf.keras.layers.LSTM(64, return_sequences=False),\n    # Shape => [batch, out_steps*features]\n    tf.keras.layers.Dense(OUT_STEPS*num_features,\n                          kernel_initializer=tf.initializers.zeros),\n    # Shape => [batch, out_steps, features]\n    tf.keras.layers.Reshape([OUT_STEPS, num_features])\n])\nMAX_EPOCHS = 30\nhistory = compile_and_fit(multi_lstm_model, multi_window)\n\nIPython.display.clear_output()\n\nplotLoss()\n\nmulti_val_performance['LSTM'] = multi_lstm_model.evaluate(multi_window.val)\nmulti_performance['LSTM'] = multi_lstm_model.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(multi_lstm_model)\n\nmulti_lstm_model.summary()\n\"\"\"\n### Advanced: Autoregressive model\n\nThe above models all predict the entire output sequence in a single step.\n\nIn some cases it may be helpful for the model to decompose this prediction into individual time steps. Then each model's output can be fed back into itself at each step and predictions can be made conditioned on the previous one, like in the classic [Generating Sequences With Recurrent Neural Networks](https:\/\/arxiv.org\/abs\/1308.0850).\n\nOne clear advantage to this style of model is that it can be set up to produce output with a varying length.\n\nYou could take any of the single-step multi-output models trained in the first half of this tutorial and run  in an autoregressive feedback loop, but here you'll focus on building a model that's been explicitly trained to do that.\n\n![Feedback a model's output to its input](images\/multistep_autoregressive.png)\n\n\"\"\"\n\"\"\"\n#### RNN\n\nThis tutorial only builds an autoregressive RNN model, but this pattern could be applied to any model that was designed to output a single timestep.\n\nThe model will have the same basic form as the single-step `LSTM` models: An `LSTM` followed by a `layers.Dense` that converts the `LSTM` outputs to model predictions.\n\nA `layers.LSTM` is a `layers.LSTMCell` wrapped in the higher level `layers.RNN` that manages the state and sequence results for you (See [Keras RNNs](https:\/\/www.tensorflow.org\/guide\/keras\/rnn) for details).\n\nIn this case the model has to manually manage the inputs for each step so it uses `layers.LSTMCell` directly for the lower level, single time step interface.\n\"\"\"\nclass FeedBack(tf.keras.Model):\n  def __init__(self, units, out_steps):\n    super().__init__()\n    self.out_steps = out_steps\n    self.units = units\n    self.lstm_cell = tf.keras.layers.LSTMCell(units)\n    # Also wrap the LSTMCell in an RNN to simplify the `warmup` method.\n    self.lstm_rnn = tf.keras.layers.RNN(self.lstm_cell, return_state=True)\n    self.dense = tf.keras.layers.Dense(num_features)\nfeedback_model = FeedBack(units=32, out_steps=OUT_STEPS)\n\"\"\"\nThe first method this model needs is a `warmup` method to initialize its internal state based on the inputs. Once trained this state will capture the relevant parts of the input history. This is equivalent to the single-step `LSTM` model from earlier:\n\"\"\"\ndef warmup(self, inputs):\n  # inputs.shape => (batch, time, features)\n  # x.shape => (batch, lstm_units)\n  x, *state = self.lstm_rnn(inputs)\n\n  # predictions.shape => (batch, features)\n  prediction = self.dense(x)\n  return prediction, state\n\nFeedBack.warmup = warmup\n\"\"\"\nThis method returns a single time-step prediction, and the internal state of the LSTM:\n\"\"\"\nprediction, state = feedback_model.warmup(multi_window.example[0])\nprediction.shape\n\"\"\"\nWith the `RNN`'s state, and an initial prediction you can now continue iterating the model feeding the predictions at each step back as the input.\n\nThe simplest approach to collecting the output predictions is to use a python list, and `tf.stack` after the loop.\n\"\"\"\n\"\"\"\nNote: Stacking a python list like this only works with eager-execution, using `Model.compile(..., run_eagerly=True)` for training, or with a fixed length output. For a dynamic output length you would need to use a `tf.TensorArray` instead of a python list, and `tf.range` instead of the python `range`.\n\"\"\"\ndef call(self, inputs, training=None):\n  # Use a TensorArray to capture dynamically unrolled outputs.\n  predictions = []\n  # Initialize the lstm state\n  prediction, state = self.warmup(inputs)\n\n  # Insert the first prediction\n  predictions.append(prediction)\n\n  # Run the rest of the prediction steps\n  for n in range(1, self.out_steps):\n    # Use the last prediction as input.\n    x = prediction\n    # Execute one lstm step.\n    x, state = self.lstm_cell(x, states=state,\n                              training=training)\n    # Convert the lstm output to a prediction.\n    prediction = self.dense(x)\n    # Add the prediction to the output\n    predictions.append(prediction)\n\n  # predictions.shape => (time, batch, features)\n  predictions = tf.stack(predictions)\n  # predictions.shape => (batch, time, features)\n  predictions = tf.transpose(predictions, [1, 0, 2])\n  return predictions\n\nFeedBack.call = call\n\"\"\"\nTest run this model on the example inputs:\n\"\"\"\nprint('Output shape (batch, time, features): ', feedback_model(multi_window.example[0]).shape)\n\"\"\"\nNow train the model:\n\"\"\"\nMAX_EPOCHS = 50\nhistory = compile_and_fit(feedback_model, multi_window)\n\nIPython.display.clear_output()\n\nplotLoss()\n\nmulti_val_performance['AR LSTM'] = feedback_model.evaluate(multi_window.val)\nmulti_performance['AR LSTM'] = feedback_model.evaluate(multi_window.test, verbose=0)\nmulti_window.plot(feedback_model)\n\nfeedback_model.summary()\n\"\"\"\n### Performance\n\"\"\"\n\"\"\"\nThere are clearly diminishing returns as a function of model complexity on this problem.\n\"\"\"\nx = np.arange(len(multi_performance))\nwidth = 0.3\n\n\nmetric_name = 'mean_absolute_error'\nmetric_index = lstm_model.metrics_names.index('mean_absolute_error')\nval_mae = [v[metric_index] for v in multi_val_performance.values()]\ntest_mae = [v[metric_index] for v in multi_performance.values()]\n\nplt.bar(x - 0.17, val_mae, width, label='Validation')\nplt.bar(x + 0.17, test_mae, width, label='Test')\nplt.xticks(ticks=x, labels=multi_performance.keys(),\n           rotation=45)\nplt.ylabel(f'MAE (average over all times and outputs)')\n_ = plt.legend()\n\"\"\"\nThe metrics for the multi-output models in the first half of this tutorial show the performance averaged across all output features. These performances similar but also averaged across output timesteps. \n\"\"\"\nfor name, value in multi_performance.items():\n  print(f'{name:8s}: {value[1]:0.4f}')\n\"\"\"\nThe gains achieved going from a dense model to convolutional and recurrent models are only a few percent (if any), and the autoregressive model performed clearly worse. So these more complex approaches may not be worth while on **this** problem, but there was no way to know without trying, and these models could be helpful for **your** problem.\n\"\"\"\n\"\"\"\n## Next steps\n\nThis tutorial was a quick introduction to time series forecasting using TensorFlow.\n\n* For further understanding, see:\n  * Chapter 15 of [Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow](https:\/\/www.oreilly.com\/library\/view\/hands-on-machine-learning\/9781492032632\/), 2nd Edition \n  * Chapter 6 of [Deep Learning with Python](https:\/\/www.manning.com\/books\/deep-learning-with-python).\n  * Lesson 8 of [Udacity's intro to TensorFlow for deep learning](https:\/\/www.udacity.com\/course\/intro-to-tensorflow-for-deep-learning--ud187), and the [exercise notebooks](https:\/\/github.com\/tensorflow\/examples\/tree\/master\/courses\/udacity_intro_to_tensorflow_for_deep_learning) \n* Also remember that you can implement any [classical time series model](https:\/\/otexts.com\/fpp2\/index.html) in TensorFlow, this tutorial just focuses on TensorFlow's built-in functionality.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dbb4269a7211b4'}"}
{"id":"65130","text":"\"\"\"\n# Analysis of US Election Results. Election Possible outcome simulation.\n\"\"\"\n\"\"\"\nThis notebook is aimed to provide exploratory data analysis (EDA), understanding of used datasets, simulation of possible outcomes of the elections by finding all variations of states where non of the presidential candidates received 50% of votes.\nAs usual I begin with importing libraries that are useful for this project.\n\"\"\"\nimport pandas as pd\npd.options.display.float_format = \"{:,.4f}\".format\n\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport sys\n\n\"\"\"\n# 1. Uploading Data\n\"\"\"\n\"\"\"\nI will be doing EDA and simulation only for presidential elections. Hence the first step is getting data for presidential elections.\nI will add a dataset with electoral votes for each state.\n\"\"\"\npresident_county_data = '..\/input\/us-election-2020\/president_county.csv'\n\npresident_county_candidate_data = '..\/input\/us-election-2020\/president_county_candidate.csv'\n\npresident_state_data = '..\/input\/us-election-2020\/president_state.csv'\n\nelectortal_votes = '..\/input\/electoralvotes\/ElectoralVotes.csv'\n\npopulation = '..\/input\/population\/nst-est2019-alldata.csv'\n\n\"\"\"\nIt is much easier to use all imported libraries and all manipulations where datasets are presented in dataframe format. All files are small enough in order to painlessly convert them using pandas library. Let's do the conversion.\n\"\"\"\ndf_president_county = pd.read_csv(president_county_data)\ndf_president_county_candidate = pd.read_csv(president_county_candidate_data)\ndf_president_state = pd.read_csv(president_state_data)\ndf_electortal_votes = pd.read_csv(electortal_votes)\ndf_population = pd.read_csv(population)\n\"\"\"\nI have loaded electoral votes by state. Let's perform EDA on this dataset.\nFor the future analysis it would be intersting to compare electoral votes and population by state.\n\"\"\"\n\"\"\"\n# 2.Exploratory Data Analysis (EDA)\n\"\"\"\ndf_electortal_votes.info()\ndf_electortal_votes.describe()\n\"\"\"\nGood news! No missing data or any suprising values. \nMinimum electoral votes = 3.  \nMedian number of electoral votes  = 8 (need to take into consideration that maximum value is 55). \nMost of the states have electoral votes less than 12. \n\nLet's see what state has the most electoral votes and how many states have same electoral vote. \n\"\"\"\n\"\"\"\n# 2.1. Electoral Votes Dataset Analysis\n\"\"\"\ndf_electortal_votes_orderd=df_electortal_votes.sort_values(by=['Electoral Votes'])\n\nx = list(df_electortal_votes_orderd['US State'])\ny = list(df_electortal_votes_orderd['Electoral Votes'])\n#ax = df_electortal_votes.plot.bar(x,y,  color ='maroon', width = 0.4, figsize = (20,20), legend = False)\n#ax.set_xlabel('States')\n#ax.set_ylabel('Count')\nplt.figure(figsize = (20,20))\nax = plt.bar(x,y, color ='maroon')\nplt.xticks(x, df_electortal_votes_orderd['US State'], rotation='vertical')\nplt.xlabel('State', fontweight ='bold') \nplt.ylabel('Electoral Votes', fontweight ='bold') \n#plt.savefig(\"ElectoralVotes.jpg\")\n\n\"\"\"\nIt is very clear that California is a leader in electoral votes. \n\"\"\"\ndf_electortal_votes_orderd.groupby(['Electoral Votes']).agg({'US State':'count'}).rename(columns={'US State':'US_State_Count'}).reset_index()\nVotes_bins = pd.IntervalIndex.from_tuples([(0,6), (6, 12), (12, 18), (18, 55)])\ndf_electortal_votes_bin = pd.cut(df_electortal_votes['Electoral Votes'],Votes_bins)\ndf_electortal_votes_bin.value_counts()\n\"\"\"\nThe highest number of states (8 states) have electoral votes = 3, than 6 states have electoral votes = 6. \nAfter grouping by bins, we can see that 22 out of 51 states have electoral votes less or equal to 6.\nI can say that 3,4,5,6 are the most popular values of the electoral votes. And over 50% states have electoral votes lass than 13.\n\nThe highest number of electoral votes = 55 belong to California. Second higher number of electoral votes = 38 to Texas.\n\nThe next step in the analysis of electoral votes dataset would be comparison to the population by state. I would expect correlation between electoral votes and population. \n\nLet's invetsigte population dataset and join it with the electoral votes in order to see the correlations between electoral votes and population.\n\nAvailable data set of 2019 population.\n\"\"\"\n\"\"\"\n# 2.2. Electoral Votes and Population\n\"\"\"\ndf_population.info()\ndf_population.describe()\nprint(df_population.head())\ndf_population_2019 = df_population[[\"STATE\", \"NAME\",\"POPESTIMATE2019\"]]\ndf_population_2019 = df_population_2019[df_population_2019[\"STATE\"] > 0].rename(columns = {'NAME':'state'})\n\ndf_population_2019.sort_values(['state'], ascending=True)\n\"\"\"\nMerging electoral votes dataset with population. Data I found for 2019 year.\n\"\"\"\ndf_electortal_votes_population_2019 = pd.merge(df_electortal_votes,df_population_2019, how = 'left', left_on ='US State', right_on = 'state' )\ndf_electortal_votes_population_2019 = df_electortal_votes_population_2019.drop(['STATE', 'US State'], axis=1)\ndf_electortal_votes_population_2019\ncorr_matrix = df_electortal_votes_population_2019.corr()\ncorr_matrix\n\n\"\"\"\nThe table above called correlation matrix and shows correlation between population and electoral votes.\nFrom this table you can see that population and electoral votes have very high correlation.\nAnother way to visualize the relationship between two measured data variables is with a scatterplot.\n\n\"\"\"\nax = df_electortal_votes_population_2019.plot.scatter(x = 'POPESTIMATE2019', y = 'Electoral Votes', figsize = (4,4))\nax.set_ylabel('Electoral Votes')\nax.set_xlabel('Population 2019')\nax.axhline(0, color = 'grey', lw = 1)\nax.axvline(0, color = 'grey', lw = 1)\nax\n\"\"\"\n# 2.3. Presidential Race Datasets Analysis\n\"\"\"\nprint(\"About dataset: General information about reporting votes to presidential race by county.\\n\")\ndf_president_county.info()\nprint(df_president_county.head())\ndf_president_county.describe()\n\"\"\"\nIntersting that maximum values of current votes are higher than total votes. \nLet's check where the maximum value are located and what percent column shows us.\n\"\"\"\ndf_president_county_test = df_president_county.copy()\ndf_president_county_test['Dif'] = df_president_county_test['total_votes'] - df_president_county_test['current_votes']\ndf_president_county_test.sort_values(['Dif'], ascending=True)\n\"\"\"\nLos Angeles and Sacramento  County \tcurrent_votes count exceeds total_votes count, however the column 'percent' does not show that, showing 95%. I would not trust the column 'percent' since it is not clear on how  percent column is calulated.  \nLet's calulate  % of current votes conmpare to total votes by state. \n\"\"\"\ndf_president_county_group= df_president_county.groupby(['state']).agg({'current_votes':'sum','total_votes':'sum'})\ndf_president_county_group['percent_calc'] = 100 * (df_president_county_group['current_votes']\/df_president_county_group['total_votes'])\ndf_president_county_group['difference'] = df_president_county_group['total_votes'] - df_president_county_group['current_votes']\ndf_president_county_group.sort_values('percent_calc', ascending=False).reset_index()\ndf_president_county_group[df_president_county_group['percent_calc'] > 100].reset_index()\n\"\"\"\n16 states have current number of votes higher than total votes. Different reasons could be for that including the representation of the total votes column. If that column represents only registered to vote residents.\nAnyway it seams very unusual to have higher number of current_votes compare to total_votes. \nThe current votes higher than total votes in California for over 1,6 Mln\n\"\"\"\n\"\"\"\n# 3.Election Results Analysis\n\"\"\"\n\"\"\"\nThe further analysis will be related to the elections results. I will work with 2 datasets:  president_state and president_county_candidate\n\"\"\"\nprint(\"About dataset: Described information about candidate votes to presidential race by county.\\n\")\nprint(df_president_county_candidate.head())\ndf_president_county_candidate.info()\ndf_president_county_candidate.describe()\n\"\"\"\nI would like to explore further minimum and maximum values for total votes. \nWhere do they position and what information I can get from them. I will start with minimum value for total votes = 0\n\"\"\"\ndf_president_county_candidate[df_president_county_candidate['total_votes'] == 0].count()\ndf_president_county_candidate[df_president_county_candidate['total_votes'] == 0].groupby('candidate').count()\n\"\"\"\nTotal number of records with 0 votes = 4,724, some of them belong to Trump and Biden, other condidates and the higher number to 'write-ins'. \nLet's check the statistic for candidate = 'Write-ins'.\n\"\"\"\ndf_president_county_candidate.info()\ndf_president_county_candidate['candidate'].unique().tolist()\ndf_president_county_candidate_write_ins= df_president_county_candidate[df_president_county_candidate['candidate'] ==' Write-ins']\ndf_president_county_candidate_write_ins\ndf_president_county_candidate_write_ins_state = df_president_county_candidate_write_ins.groupby('state').agg({'total_votes':'sum'}).sort_values(by=['total_votes'], ascending=False).reset_index()\ndf_president_county_candidate_write_ins_state\n\"\"\"\nLet's check the states that do not have write-ins. \n\"\"\"\ndf_president_county_candidate_state=df_president_county_candidate.groupby('state').agg({'total_votes':'sum'})\ndf_president_county_candidate_state\ndf_states_without_write_ins = pd.merge(df_president_county_candidate_state,df_president_county_candidate_write_ins_state,on= 'state', how='outer',indicator=True)\ndf_states_without_write_ins[df_states_without_write_ins['_merge']!='both']\n\"\"\"\nHence there are 10 states that do not have 'write_ins'.\n\nLet's analysis the data for our 2 main candidates - Joe Biden and Donald Trump\n\"\"\"\n\"\"\"\n# 3.1. Joe Biden vs Donald Trump\n\"\"\"\ndf_president_county_candidate_main = df_president_county_candidate[(df_president_county_candidate.candidate=='Joe Biden')| (df_president_county_candidate.candidate=='Donald Trump')]\ndf_president_county_candidate_main\ngroup_col = ['state','candidate']\ndf_president_county_candidate_main_group= df_president_county_candidate_main.groupby(group_col).agg({'total_votes':'sum'}).reset_index()\ndf_president_county_candidate_main_group=df_president_county_candidate_main_group.set_index('state')\ndf_president_county_candidate_main_group\n\ndf_president_county_candidate_total = df_president_county_candidate.groupby(['candidate']).agg({'total_votes':'sum'})\ndf_president_county_candidate_total.plot(kind='bar', color ='lightblue',figsize= (20,10))\n\"\"\"\nIt is no surprise that Joe Biden and Donald Trump are the main candidates. Let's see who are other candidates and who got the most votes.\n\"\"\"\ndf_president_county_candidate_not_main_total = df_president_county_candidate_total[(df_president_county_candidate_total.index != \"Joe Biden\") & (df_president_county_candidate_total.index != \"Donald Trump\")]\ndf_president_county_candidate_not_main_total.sort_values(by='total_votes', ascending=False)\n#df_president_county_candidate_total.plot(kind='bar', color ='lightblue',figsize= (20,10))\ndf_president_county_candidate_not_main_total.plot(kind='bar', color ='lightgray',figsize= (20,10))\n\"\"\"\nClearly Jo Jorgensen is a leader with over 1Mln votes. And for comparison Kanye West got 66K. \n\"\"\"\ndf_president_county_candidate_main_total = df_president_county_candidate_total[(df_president_county_candidate_total.index == \"Joe Biden\") | (df_president_county_candidate_total.index == \"Donald Trump\")]\ndf_president_county_candidate_main_total\ndf_president_county_candidate_main_total.plot(kind='bar', color ='orange',figsize= (20,10))\nprint(\"About dataset: General information about reporting votes to presidential race by state.\\n\")\nprint(df_president_state.head())\ndf_president_state.info()\ndf_president_state.describe()\ndf_president_county_total_votes = df_president_county.groupby(['state']).agg({'total_votes':'sum'}).reset_index()\ndf_president_county_total_votes.head()\n\"\"\"\nI want to compare total votes in two datasets : total votes by county and total votes by state.\n\"\"\"\ndf_total_votes_check = pd.merge(df_president_county_total_votes,df_president_state,how = 'inner', on = 'state')\ndf_total_votes_check['vote_diff'] = df_total_votes_check['total_votes_y'] - df_total_votes_check['total_votes_x']\ndf_total_votes_check\n\"\"\"\nThe highest difference in total votes in Illinois. I am not sure whether it is issue in provided datsets or not.\n\"\"\"\ndf_total_votes_check.sort_values(by='vote_diff', ascending=True)\ndf_president_county_candidate_main_group.head()\ndf_president_state.head()\ndf_president_candidate_main = pd.merge(df_president_county_candidate_main_group, df_president_state, how='left', on ='state').rename(columns = {'total_votes_x':'candidate_votes','total_votes_y':'reg_votes'})\ndf_president_candidate_main.head()\n\"\"\"\nI want to calculate percentage that our 2 main candidates received for each state.\n\"\"\"\ndf_president_candidate_main['percent'] = (df_president_candidate_main['candidate_votes'] \/ df_president_candidate_main['reg_votes']).astype('float').round(4)\ndf_president_candidate_main.head()\ndf_president_candidate_main.sort_values(by=['state','percent'], ascending = False)\ndf_president_candidate_main['winner'] = 'False'\ndf_president_candidate_main.loc[df_president_candidate_main['percent'] > 0.50, 'winner'] = 'True'\n\ndf_president_candidate_main\ndf_president_candidate_main_ev = pd.merge(df_president_candidate_main, df_electortal_votes, how='left',left_on='state', right_on ='US State')\ndf_president_candidate_main_ev\ndf_president_candidate_main_pivot = df_president_candidate_main.pivot(index='state', columns ='candidate', values ='candidate_votes')\n\ndf_president_candidate_main_pivot.head()\n\"\"\"\nI want to explore two types of graphs to see which representation is visually better.\n\"\"\"\ndf_president_candidate_main_pivot.plot(kind='bar',stacked = True,figsize= (20,10))\ndf_president_candidate_main_pivot2 = df_president_candidate_main.pivot(index='state', columns ='candidate', values ='percent')\n\ndf_president_candidate_main_pivot2.plot(kind='bar',yticks =[0.0,0.2,0.3,0.4,0.5,0.6,0.8,1.0,1.2] , stacked = True,figsize= (30,20)).yaxis.grid(linestyle='--') # horizontal  lines\n\n#df_president_candidate_main_pivot2.plot(kind='bar',stacked = True,figsize= (20,10))\n#plt.grid(True, which = 'major',linestyle='--')\n\n\"\"\"\nAnd Illinois again. Looks like they have over 100 %. I would definitely consider some issue in data with this results.\n\"\"\"\ndf_president_candidate_main_Illinois = df_president_candidate_main[df_president_candidate_main['state']=='Illinois']\ndf_president_candidate_main_Illinois\ndf_president_candidate_main_California = df_president_candidate_main[df_president_candidate_main['state']=='California']\ndf_president_candidate_main_California\n\"\"\"\nBelow is the list of states where neither Trump or Biden received at least 50%. It is 5 states. \n\"\"\"\ndf_president_candidate_main_pivot2_states=df_president_candidate_main_pivot2[(df_president_candidate_main_pivot2['Donald Trump']< 0.50) & (df_president_candidate_main_pivot2['Joe Biden']< 0.50)]\ndf_president_candidate_main_pivot2_states\n\ndf_president_candidate_main_pivot2_states=df_president_candidate_main_pivot2_states.reset_index()\ndf_president_candidate_main_pivot2_states\n\"\"\"\n# 3.2. Total electoral votes calculation.\n\"\"\"\nmerge_final =  pd.merge(df_president_candidate_main_pivot2,df_electortal_votes,how='inner',left_on='state', right_on='US State')\n\nmerge_final\nmerge_final = merge_final.set_index('US State')\n\nmerge_final_trump = merge_final[merge_final['Donald Trump']>0.50].agg({'Electoral Votes':'sum'})\nmerge_final_trump\nmerge_final_biden = merge_final[merge_final['Joe Biden']>0.50].agg({'Electoral Votes':'sum'})\nmerge_final_biden\nmerge_final_dispute_states=merge_final[(merge_final['Donald Trump']< 0.50) & (merge_final['Joe Biden']< 0.50)]\nmerge_final_dispute_states\nmerge_final_dispute_states[[\"Donald Trump\",\"Joe Biden\"]].plot(kind='bar',yticks =[0.0,0.3,0.5,0.7,1.0], figsize= (10,5)).yaxis.grid(linestyle='--') \n\"\"\"\n# 3.3.Simulation Possible Outcomes for 5 States\n\"\"\"\n\"\"\"\nLet's try to play with the possibility of winning for Biden or Trump by only 5 states where non of them got 50%\n\"\"\"\nmerge_final_dispute_states_total = merge_final_dispute_states['Electoral Votes'].sum()\nprint(\"Total electoral votes for states where no one got 50%: \")\nprint(merge_final_dispute_states_total)\nprint(\"Number of electoral votes Trump needs to win: \")\nprint(270 - int(merge_final_trump))\nprint(\"Number of electoral votes Biden needs to win: \")\nprint(270 - int(merge_final_biden))\n\"\"\"\nTo win the election Biden needs any of two states (out of 5 with less than 50%), where Trumps needs any 3 states. It is  obvious even at this step that Biden has higher chances of winning.\nThe outcome will be dending who wins each state. \nTo Win Trum needs - 3 States and Biden needs 2 states.\nHence probabilty of winning to Biden is 3\/5 , which is 60%\nProbality of winning to Trump is 2\/5, which is 40%\nLet's play with final outcome. \n\"\"\"\n\"\"\"\n**I want to find all possible combinations. ** \n\n\n\n\"\"\"\n#from itertools import combinations\nimport itertools as it\n#comb = combinations([1,2,3],2)\ncomb = it.product(['Trump','Biden'], repeat=5)\n#comb =  it.permutations([1,2,3,4,5],5)\npossible = []\nfor i in list(comb):\n    possible.append(i)\n    print(i)\n    \nprint(possible)\n\ncolumns=list(merge_final_dispute_states.index.values)\ncolumns\n\"\"\"\nThe dataframe below indicates who won the state. We have total 32 combinations\n\"\"\"\ndf_combinations = pd.DataFrame(possible,columns=columns)\nprint(df_combinations) \ndf_combinations['Total_Trump'] = 0\ndf_combinations['Total_Biden'] = 0\ndf_combinations['Elections Won'] = 'Default'\ndf_combinations\ndf_combinations_transposed = df_combinations.transpose()\ndf_combinations_transposed\nfinal_states = merge_final_dispute_states.drop(['Donald Trump', 'Joe Biden'], axis=1)\nfinal_states\ndf_combinations_votes = df_combinations_transposed.join(final_states, how='left').fillna(0)\ndf_combinations_votes\ndf_combinations_votes_copy = df_combinations_votes.copy()\nfor i in df_combinations_votes_copy.columns:\n        trump_votes = 0\n        biden_votes = 0\n        for j in range(5):\n            if df_combinations_votes_copy[i][j] =='Trump':\n                trump_votes =  trump_votes + df_combinations_votes['Electoral Votes'][j] \n            if df_combinations_votes_copy[i][j] =='Biden':\n                biden_votes =  biden_votes + df_combinations_votes['Electoral Votes'][j] \n        df_combinations_votes_copy[i][5] = trump_votes + int(merge_final_trump.values)\n        df_combinations_votes_copy[i][6] = biden_votes + int(merge_final_biden.values) \n        if df_combinations_votes_copy[i][5] >= 270:\n            df_combinations_votes_copy[i][7] = 'Trump'\n        if df_combinations_votes_copy[i][6] >= 270:\n            df_combinations_votes_copy[i][7] = 'Biden'\n        if df_combinations_votes_copy[i][5] == df_combinations_votes_copy[i][6]:\n            df_combinations_votes_copy[i][7] =  'Draw'\n\ndf_combinations_votes_copy\ndf_combinations_votes_copy_drop = df_combinations_votes_copy.drop(['Electoral Votes'], axis=1)\ndf_combinations_votes_copy_drop\nelections_combinations = df_combinations_votes_copy_drop.transpose()\nelections_combinations\n\"\"\"\nInteresting that Draw would happen in one case based on table above.\n\"\"\"\nelections_combinations_graph = elections_combinations.drop(['Arizona', 'Georgia', 'North Carolina', 'Pennsylvania', 'Wisconsin'], axis = 1) \nelections_combinations_graph\nimport plotly.express as px\n\nfig = px.scatter(elections_combinations_graph, y=\"Elections Won\")\n\nfig.update_traces(marker=dict(color='LightSkyBlue', size=20,\n                              line=dict(width=1,\n                                        color='DarkSlateGrey')),\n                  selector=dict(mode='markers'))\n\nfig.show()\n\"\"\"\nIt is clear that Biden has higher chances to win. Biden has 26 combinations to win elections where Trump only - 5\n\"\"\"\nBiden_won = elections_combinations_graph[elections_combinations_graph['Elections Won']=='Biden'].count()['Elections Won']\nBiden_won\n\nTrump_won = elections_combinations_graph[elections_combinations_graph['Elections Won']=='Trump'].count()['Elections Won']\nTrump_won\n\"\"\"\n*We all now know the elections results. It was fun playing with provided data and get some new information.  *\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7824ed3b65663d'}"}
{"id":"114656","text":"# Basic Libraries\nimport numpy as np\nimport pandas as pd\n\n# Visualizations Libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport plotly.express as px\nfrom plotly.offline import iplot\nfrom plotly.subplots import make_subplots\nimport plotly.offline as py\nimport plotly.figure_factory as ff\n\n\n# Data Pre-processing Libraries\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler,OneHotEncoder,PowerTransformer,OrdinalEncoder\nfrom sklearn.model_selection import train_test_split,cross_validate, cross_val_score,GridSearchCV\nfrom sklearn.pipeline import Pipeline,make_pipeline\n\nfrom sklearn.compose import make_column_transformer,make_column_selector\nfrom sklearn.feature_selection import SelectKBest,f_classif,mutual_info_classif,chi2,SelectFromModel\n\n# Modelling Libraries\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC,LinearSVC,SVR\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom lightgbm import LGBMClassifier\n\n# Evaluation & CV Libraries\nfrom sklearn.metrics import precision_score,accuracy_score,mean_squared_error,r2_score,confusion_matrix\nfrom sklearn.metrics import classification_report, plot_confusion_matrix,roc_auc_score,f1_score,recall_score\n\nimport optuna\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nplt.rcParams[\"figure.figsize\"] = (10,6)\npd.set_option(\"max_columns\",100)\npd.set_option(\"max_rows\",900)\npd.set_option(\"max_colwidth\",200)\ndata = pd.read_csv(\"..\/input\/heart-failure-prediction\/heart.csv\")\ndf=data.copy()\ndf.head()\ndf.describe()\ndf.skew()\ndef missing(df):\n    missing_number = df.isnull().sum().sort_values(ascending=False)\n    missing_percent = (df.isnull().sum()\/df.isnull().count()).sort_values(ascending=False)\n    missing_values = pd.concat([missing_number, missing_percent], axis=1, keys=['Missing_Number', 'Missing_Percent'])\n    return missing_values\n\nmissing(df)\ndf.duplicated().sum()\nnumerical= df.drop(['HeartDisease'], axis=1).select_dtypes('number').columns\n\ncategorical = df.select_dtypes('object').columns\ndf[\"HeartDisease\"].value_counts()\nmatrix = np.triu(df.corr())\nfig,ax = plt.subplots(figsize=(12,6),dpi=100)\nsns.heatmap(df.corr(),annot=True,vmax=1,vmin=-1,center=0,ax=ax,mask=matrix,fmt=\".2f\");\nplt.figure(figsize=(15,5))\nsns.countplot(x ='Age', data = df)\nplt.title('Age Distribution')\nplt.ylabel('Age')\nplt.show();\nplt.figure(figsize=(15,5))\nplt.subplot(221)\nsns.histplot(x='Age', data=df, kde =True)\nplt.title('Age Distribution')\nplt.xlabel('Age')\nplt.ylabel('Count')\n\nplt.subplot(222)\nsns.histplot(x ='Cholesterol', data=df, color='red', kde = True)\nplt.title('Cholesterol Distribution')\nplt.xlabel('Cholesterol')\nplt.ylabel('Count')\n\nplt.figure(figsize=(15,5))\nplt.subplot(223)\nsns.histplot(x='MaxHR', data=df, kde =True)\nplt.title('MaxHR Distribution')\nplt.xlabel('MaxHR')\nplt.ylabel('Count')\n\nplt.subplot(224)\nsns.histplot(x ='RestingBP', data=df, color='red', kde = True)\nplt.title('RestingBP Distribution')\nplt.xlabel('RestingBP')\nplt.ylabel('Count');\nplt.figure(figsize=(8,8))\n\nexplode = [0,0.1]\nplt.pie(df['Sex'].value_counts(), explode=explode,autopct='%1.1f%%', shadow=True,startangle=140)\nplt.legend(labels=['Male','Female'])\nplt.title('Male and Female Distribution')\nplt.axis('off');\nfig,ax = plt.subplots(figsize=(6,6),dpi =100)\nsns.countplot(x='Sex', data=df,ax=ax)\nplt.title('Sex Distribution')\nplt.xlabel('Sex')\nplt.ylabel('Count')\nfor p in ax.patches:\n    ax.annotate(str(p.get_height()), (p.get_x() +0.4, p.get_height() + 10));\npx.histogram(df, x=df.ExerciseAngina, color=\"HeartDisease\",facet_col=\"Sex\")\npx.histogram(df, x=\"RestingECG\", color=\"HeartDisease\",facet_col=\"Sex\")\npx.histogram(df, x=\"Sex\", color=\"HeartDisease\",width=800)\npx.box(df,x=df.MaxHR,facet_col=\"HeartDisease\",animation_frame=df.Age)\nplt.figure(figsize=(8,8))\n\nexplode = [0,0.1]\nplt.pie(df['HeartDisease'].value_counts(), explode=explode,autopct='%1.1f%%', shadow=True,startangle=140)\nplt.legend(labels=['1','0'])\nplt.title('HeartDisease Distribution')\nplt.axis('off');\n\"\"\"\n## **Compare models with default values.**\n\"\"\"\nohe = OneHotEncoder(sparse=False,handle_unknown=\"ignore\")\nscaled = StandardScaler()\n\nX= df.drop('HeartDisease', axis=1)\ny= df['HeartDisease']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n\nct =make_column_transformer((ohe,categorical),\n                            (scaled,numerical),remainder='passthrough')\n\npipe = make_pipeline(ct,LogisticRegression(random_state=42,class_weight=\"balanced\"))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nlog_f1 = f1_score(y_test, y_pred)\nlog_recall = recall_score(y_test, y_pred)\nlog_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"LOG_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\n\npipe = make_pipeline(ct,KNeighborsClassifier())\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nknn_f1 = f1_score(y_test, y_pred)\nknn_recall = recall_score(y_test, y_pred)\nknn_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"KNN_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\npipe = make_pipeline(ct,SVC(random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nsvc_f1 = f1_score(y_test, y_pred)\nsvc_recall = recall_score(y_test, y_pred)\nsvc_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"SVM_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\npipe = make_pipeline(ct,DecisionTreeClassifier(random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\ndt_f1 = f1_score(y_test, y_pred)\ndt_recall = recall_score(y_test, y_pred)\ndt_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"DT_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\npipe = make_pipeline(ct,RandomForestClassifier(random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\n\nrf_f1 = f1_score(y_test, y_pred)\nrf_recall = recall_score(y_test, y_pred)\nrf_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"RF_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\npipe = make_pipeline(ct,AdaBoostClassifier(n_estimators=50, random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\n\nada_f1 = f1_score(y_test, y_pred)\nada_recall = recall_score(y_test, y_pred)\nada_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"ADABOOST_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\n\npipe = make_pipeline(ct,GradientBoostingClassifier(random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\n\ngb_f1 = f1_score(y_test, y_pred)\ngb_recall = recall_score(y_test, y_pred)\ngb_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"GRAD\u0130ENT BOST\u0130NG_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\npipe = make_pipeline(ct,XGBClassifier(random_state=42))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\n\nxgb_f1 = f1_score(y_test, y_pred)\nxgb_recall = recall_score(y_test, y_pred)\nxgb_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"XGB_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\npipe = make_pipeline(ct,CatBoostClassifier(random_state=42,verbose=0))\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\ncat_f1 = f1_score(y_test, y_pred)\ncat_recall = recall_score(y_test, y_pred)\ncat_auc = roc_auc_score(y_test, y_pred)\nprint(\"-------------------------\")\nprint(\"CATBOOST_MODEL\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\n\ncompare = pd.DataFrame({\"Model\": [\"Logistic Regression\", \"KNN\", \"SVM\", \"Decision Tree\", \"Random Forest\", \"AdaBoost\",\n                                 \"GradientBoost\", \"XGBoo\",\"CatBoost\"],\n                        \"F1\": [log_f1, knn_f1, svc_f1, dt_f1, rf_f1, ada_f1, gb_f1, xgb_f1,cat_f1 ],\n                        \"Recall\": [log_recall, knn_recall, svc_recall, dt_recall, rf_recall, ada_recall, gb_recall, xgb_recall,cat_recall],\n                        \"ROC_AUC\": [log_auc, knn_auc, svc_auc, dt_auc, rf_auc, ada_auc, gb_auc, xgb_auc,cat_auc]})\n\ndef labels(ax):\n    for p in ax.patches:\n        width = p.get_width()                        # get bar length\n        ax.text(width,                               # set the text at 1 unit right of the bar\n                p.get_y() + p.get_height() \/ 2,      # get Y coordinate + X coordinate \/ 2\n                '{:1.3f}'.format(width),             # set variable to display, 2 decimals\n                ha = 'left',                         # horizontal alignment\n                va = 'center')                       # vertical alignment\n    \nplt.figure(figsize=(14,10))\nplt.subplot(311)\ncompare = compare.sort_values(by=\"F1\", ascending=False)\nax=sns.barplot(x=\"F1\", y=\"Model\", data=compare, palette=\"Blues_d\")\nlabels(ax)\n\nplt.subplot(312)\ncompare = compare.sort_values(by=\"Recall\", ascending=False)\nax=sns.barplot(x=\"Recall\", y=\"Model\", data=compare, palette=\"Blues_d\")\nlabels(ax)\n\nplt.subplot(313)\ncompare = compare.sort_values(by=\"ROC_AUC\", ascending=False)\nax=sns.barplot(x=\"ROC_AUC\", y=\"Model\", data=compare, palette=\"Blues_d\")\nlabels(ax)\nplt.show()\n\"\"\"\n## **SVC Model**\n\"\"\"\ndef objective(trial):\n    \n    X= df.drop('HeartDisease', axis=1)\n    y= df['HeartDisease']\n    \n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n    \n    params = {\"C\":trial.suggest_int(\"C\",1,5),\n             \"degree\":trial.suggest_int(\"degree\",2,6),\n             \"kernel\": trial.suggest_categorical(\"kernel\",(\"rbf\",\"linear\")),\n             \"coef0\":trial.suggest_float(\"coef0\",0,1)}\n    ct =  make_column_transformer((StandardScaler(),make_column_selector(dtype_exclude=object)),\n         (OneHotEncoder(sparse=False,handle_unknown=\"ignore\"),make_column_selector(dtype_include=object)),remainder=\"passthrough\")\n    \n    model =SVC(random_state=42)\n    pipe = make_pipeline(ct,model)\n    pipe.fit(X_train,y_train)\n    preds = pipe.predict(X_test)\n    pred_labels = np.rint(preds)\n    accuracy = accuracy_score(y_test, pred_labels)\n    return accuracy\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=50, timeout=600)\n\n    trial = study.best_trial\n\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\nsvc_model = SVC(C= 2,degree= 2,kernel = \"rbf\",coef0=  0.4371031882388341,random_state=42,verbose =0 )\n\nct = make_column_transformer((ohe,categorical),\n                            (scaled,numerical),remainder='passthrough')\n\npipe = make_pipeline(ct,svc_model)\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nprint(\"-------Test Scores-------\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\nprint(\"-------Train Scores-------\")\nprint(confusion_matrix(y_train, y_pred_train))\nprint(classification_report(y_train, y_pred_train))\n\"\"\"\n\n## **RandomForest Model**\n\"\"\"\nohe =  OneHotEncoder(sparse=False,handle_unknown=\"ignore\")\nmodel = RandomForestClassifier(random_state=42, class_weight=\"balanced\")\nscaled = StandardScaler()\nX= df.drop('HeartDisease', axis=1)\ny= df['HeartDisease']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nct =make_column_transformer((ohe,categorical),\n                            (scaled,numerical),remainder='passthrough')\n\npipe = make_pipeline(ct,model)\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nprint(\"-------Test Scores-------\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\nprint(\"-------Train Scores-------\")\nprint(confusion_matrix(y_train, y_pred_train))\nprint(classification_report(y_train, y_pred_train))\ndef objective(trial):\n    X= df.drop('HeartDisease', axis=1)\n    y= df['HeartDisease']\n    \n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n    \n    ct =make_column_transformer((ohe,categorical),\n                                (scaled,numerical),remainder='passthrough')\n\n    \n    param = {\"n_estimators\":trial.suggest_int(\"n_estimators\",100,500),\n        \"max_depth\": trial.suggest_float(\"max_depth\",1,10),\n        \"max_samples\": trial.suggest_float(\"max_samples\",0.01,1)}\n\n    rf_model = RandomForestClassifier(random_state=42,**param,n_jobs=-1,verbose=False)\n    pipe = make_pipeline(ct,rf_model)\n    pipe.fit(X_train,y_train)\n\n    preds = pipe.predict(X_test)\n    pred_labels = np.rint(preds)\n    accuracy = accuracy_score(y_test, pred_labels)\n    return accuracy\n\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=50, timeout=600)\n\n    trial = study.best_trial\n\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\nrf_model = RandomForestClassifier(n_estimators = 105,max_depth = 8.415478369250112,\n                                  max_samples = 0.8643345901350294,random_state=42)\n\nct = make_column_transformer((ohe,categorical),\n                            (scaled,numerical),remainder='passthrough')\n\npipe = make_pipeline(ct,rf_model)\npipe.fit(X_train,y_train)\ny_pred = pipe.predict(X_test)\ny_pred_train = pipe.predict(X_train)\n\nprint(\"-------Test Scores-------\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\nprint(\"-------Train Scores-------\")\nprint(confusion_matrix(y_train, y_pred_train))\nprint(classification_report(y_train, y_pred_train))\n\"\"\"\n## **CatBoostClassifier Model**\n\"\"\"\ndef objective(trial):\n    X= df.drop('HeartDisease', axis=1)\n    y= df['HeartDisease']\n    categorical_features_indices = np.where(X.dtypes != np.float)[0]\n    \n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n    param = {\n        \"objective\": trial.suggest_categorical(\"objective\", [\"Logloss\", \"CrossEntropy\"]),\n        \"colsample_bylevel\": trial.suggest_float(\"colsample_bylevel\", 0.01, 0.1),\n        \"depth\": trial.suggest_int(\"depth\", 1, 12)}\n    \n    cat_model = CatBoostClassifier(**param)\n    cat_model.fit(X_train, y_train, eval_set=[(X_test, y_test)], cat_features=categorical_features_indices,verbose=0, early_stopping_rounds=100)\n    preds = cat_model.predict(X_test)\n    pred_labels = np.rint(preds)\n    accuracy = accuracy_score(y_test, pred_labels)\n    return accuracy\n\nif __name__ == \"__main__\":\n    study = optuna.create_study(direction=\"maximize\")\n    study.optimize(objective, n_trials=75)\n\n    print(\"Best trial:\")\n    trial = study.best_trial\n\n    print(\"  Value: {}\".format(trial.value))\n\n    print(\"  Params: \")\n    for key, value in trial.params.items():\n        print(\"    {}: {}\".format(key, value))\nX= df.drop('HeartDisease', axis=1)\ny= df['HeartDisease']\ncategorical_features_indices = np.where(X.dtypes != np.float)[0]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\nmodel = CatBoostClassifier(verbose=False,random_state=42,\n                          objective= 'Logloss',\n                          colsample_bylevel= 0.08369028629134112,\n                          depth= 9)\n\nmodel.fit(X_train, y_train,cat_features=categorical_features_indices,eval_set=(X_test, y_test))\ny_pred = model.predict(X_test)\n\nprint(\"-------Test Scores-------\")\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test,y_pred))\n\nprint(\"-------Train Scores-------\")\nprint(confusion_matrix(y_train, y_pred_train))\nprint(classification_report(y_train, y_pred_train))","meta":"{'source': 'AI4Code', 'id': 'd2b9fc5d87c684'}"}
{"id":"61869","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n**Applying A Deep Neural Network**\n\"\"\"\n\n#Importign libraries\n\nimport pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\n#Importing the Dataset\ndf = pd.read_csv('..\/input\/Concrete_Data_Yeh.csv')\nx_org = df.drop('csMPa',axis=1).values\ny_org = df['csMPa'].values\n\n\n## Knowing The Data\n# #Correlation heatmap\ncorr = df.corr()\nsns.heatmap(corr,xticklabels=True,yticklabels=True,annot = True,cmap ='coolwarm')\nplt.title(\"Correlation Between Variables\")\nplt.savefig('1.png')\n\n# # pair Plot\nsns.pairplot(df,palette=\"husl\",diag_kind=\"kde\")\nplt.savefig('2.png')\n\n# Using Test\/Train Split\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(x_org,y_org, test_size=0.3)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Building ANN As a Regressor\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import backend\n\n\n#Defining Root Mean Square Error As our Metric Function \ndef rmse(y_true, y_pred):\n\treturn backend.sqrt(backend.mean(backend.square(y_pred - y_true), axis=-1))\n\n\n#Building  first layer Layers \nmodel=Sequential()\n\nmodel.add(Dense(64,input_dim=8,activation = 'relu'))\n\n# Bulding Second and third layer\nmodel.add(Dense(32,activation='relu'))\nmodel.add(keras.layers.normalization.BatchNormalization())\n\n# Output Layer\nmodel.add(Dense(1,activation='linear'))\n\n\n# Optimize , Compile And Train The Model \nopt =keras.optimizers.Adam(lr=0.0015)\n\nmodel.compile(optimizer=opt,loss='mean_squared_error',metrics=[rmse])\nhistory = model.fit(X_train,y_train,epochs = 35 ,batch_size=32,validation_split=0.1)\n\nprint(model.summary())\n\n# Predicting and Finding R Squared Score\n\ny_predict = model.predict(X_test)\n\nfrom sklearn.metrics import r2_score\nprint(r2_score(y_test,y_predict))\n\n# Plotting Loss And Root Mean Square Error For both Training And Test Sets\nplt.plot(history.history['rmse'])\nplt.plot(history.history['val_rmse'])\nplt.title('Root Mean Squared Error')\nplt.ylabel('rmse')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.savefig('4.png')\nplt.show()\n\n\"\"\"\n***looks like a good Score***\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7214b5bbd20e50'}"}
{"id":"43582","text":"\"\"\"\n**I am very new with Data Analysis, so please bare with me. Any and every feedback is appreciated.**\n\nA few points to note:\n1. I need help to know which ML model is the best to select and use for such kind of a prediction.\n2. I have placed a few doubts in the comments (it's in the PREDICTIVE ANALYSIS section).\n3. Please do state if there are better ways to plot certain correlations.\n\"\"\"\n#Import Libraries\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib \nimport matplotlib.pyplot as plt\n%matplotlib inline \n#read csv\ndata = pd.read_csv(\"..\/input\/body-performance-data\/bodyPerformance.csv\")\n#create dataframe\ndf = pd.DataFrame(data)\n\"\"\"\n# DATA PREPROCESSING\n\"\"\"\ndf.shape\n#check for missing values\ndf.isna().sum()\n#Rename columns\ndf = df.rename(columns={\"body fat_%\":\"body_fat\", \"height_cm\":\"height\", \"weight_kg\":\"weight\", \"sit and bend forward_cm\":\"bend_forward\", \"gripForce\":\"grip_force\",\"sit-ups counts\":\"sit_ups\", \"broad jump_cm\":\"broad_jump\"})\ndf.sample(5)\n\"\"\"\n# DATA VISUALIZATION\n\"\"\"\n#Gender and height \/ weight\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,2,1)\nsns.boxplot(x=\"gender\", y=\"height\", data=df, ax=ax)\nax = plt.subplot(1,2,2)\nsns.boxplot(x=\"gender\", y=\"weight\", data=df, ax=ax)\n\"\"\"\nInsight 1: Males tend to be taller and heavier than females.\n\"\"\"\n#Gender and body fat\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,1,1)\nsns.boxplot(x=\"gender\", y=\"body_fat\", data=df, ax=ax)\n\"\"\"\nInsight 2: Females, on average, have a slightly higher body fat % than males.\n\"\"\"\n#Gender and gripforce\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,1,1)\nsns.boxplot(x=\"gender\", y=\"grip_force\", data=df, ax=ax)\ndf.groupby(\"gender\").mean()\n\"\"\"\nInsight 3: Males tend to have a higher grip force on average compared to females.\n\"\"\"\n#Age and body fat\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,1,1)\nsns.scatterplot(x=\"age\", y=\"body_fat\", data=df, ax=ax)\n\"\"\"\nInsight 4: There seems to be no correlation between age and body fat %\n\"\"\"\n#Diastolic with bodyfat\n#Diastolic with age\n#Diastolic with gender\nplt.figure(figsize=(15,5))\nax = plt.subplot(1,3,1)\nsns.scatterplot(x=\"diastolic\", y=\"body_fat\", data=df, ax=ax)\nax = plt.subplot(1,3,2)\nsns.scatterplot(x=\"diastolic\", y=\"age\", data=df, ax=ax)\nax = plt.subplot(1,3,3)\nsns.boxplot(x=\"gender\", y=\"diastolic\", data=df, ax=ax)\nax.set(ylim=(25,130))\n\"\"\"\nInsight 5: There seems to be no correlation between diastolic blood pressure and body fat % as well as no correlation between diastolic blood pressure and age.\nHowever, males tend to have higher diastolic blood pressure compared to females.\n\"\"\"\n#Systolic with bodyfat\n#Systolic with age\n#Systolic with gender\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,3,1)\nsns.scatterplot(x=\"systolic\", y=\"body_fat\", data=df, ax=ax)\nax = plt.subplot(1,3,2)\nsns.scatterplot(x=\"systolic\", y=\"age\", data=df, ax=ax)\nax = plt.subplot(1,3,3)\nsns.scatterplot(x=\"gender\", y=\"systolic\", data=df, ax=ax)\n\"\"\"\nInsight 6: There seems to be no correlation between systolic blood pressure and body fat % as well as no correlation between systolic blood pressure and age. However, males tend to have higher systolic blood pressure compared to females.\n\"\"\"\n#Body fat and gripfore\n#Body fat and bend forward\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,2,1)\nsns.scatterplot(x=\"body_fat\", y=\"grip_force\", data=df, ax=ax)\nax = plt.subplot(1,2,2)\nsns.scatterplot(x=\"body_fat\", y=\"bend_forward\", data=df, ax=ax)\n\"\"\"\nInsight 7: People with a lower body fat % have a higher grip force.\nThere seems to be no correlation between body fat % and ability to bendforward.\n\"\"\"\n#Body fat and sit ups\n#Body fat and broadjump\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,2,1)\nsns.scatterplot(x=\"body_fat\", y=\"sit_ups\", data=df, ax=ax)\nax = plt.subplot(1,2,2)\nsns.scatterplot(x=\"body_fat\", y=\"broad_jump\", data=df, ax=ax)\n\"\"\"\nInsight 8: People with a lower body fat % tend to be able to do a higher amount of sit ups. Moreover, people with a lower body fat % tend to be able to able to have a higher broad jump distance. \n\"\"\"\n#Class and gender\n#Class and age\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,2,1)\nsns.countplot(x=\"class\", hue=\"gender\", data=df, ax=ax)\nax = plt.subplot(1,2,2)\nsns.boxplot(x=\"class\", y=\"age\", data=df, ax=ax)\ndf.groupby(\"class\")[\"age\"].mean()\n\"\"\"\nInsight 9: It is difficult to state whether averagely more males fall under a certain class than females, because in the dataset, there are 8467 males compared to 4926 females.\nHowever, from the 2nd plot, we can infer that the average age for class A seems to be considerably lower than the other classes.\n\"\"\"\n#Class and body fat\nplt.figure(figsize=(10,5))\nax = plt.subplot(1,2,1)\nsns.boxplot(x=\"class\", y=\"body_fat\", data=df, ax=ax)\nax.set(ylim=(0,60))\ndf.groupby(\"class\")[\"body_fat\"].mean()\n\"\"\"\nInsight 10: On average, people in Class A tend to have a lower body fat %.\n\"\"\"\n#Class and sit ups, bendforward, broad jump\nplt.figure(figsize=(15,5))\nax = plt.subplot(1,3,1)\nsns.boxplot(x=\"class\", y=\"sit_ups\", data=df, ax=ax)\nax = plt.subplot(1,3,2)\nsns.boxplot(x=\"class\", y=\"bend_forward\", data=df, ax=ax)\nax.set(ylim=(-30,50))\nax = plt.subplot(1,3,3)\nsns.boxplot(x=\"class\", y=\"broad_jump\", data=df, ax=ax)\ndf.groupby(\"class\")[\"sit_ups\", \"bend_forward\", \"broad_jump\"].mean()\n\"\"\"\nInsight 11: On average, people in Class A tend to be able to do more sit ups, bend more forward and able to jump further than the people in other classes.\n\"\"\"\n\"\"\"\n# DATA MODELING AND PREDICTIVE ANALYSIS\n\"\"\"\n#import libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import XGBRegressor\nimport numpy as np\ntempdf=df\ntempdf.sample()\n#Changing gender and class column to numerical values\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\nlabel = le.fit_transform(tempdf[\"gender\"])\ntempdf.drop(\"gender\", axis=1)\ntempdf[\"gender\"] = label\nlabel = le.fit_transform(tempdf[\"class\"])\ntempdf.drop(\"class\", axis=1)\ntempdf[\"class\"] = label\ntempdf.sample()\n#split data into train and test data\ntrain_x,test_x,train_y,test_y = train_test_split(tempdf.iloc[:,:-1],tempdf.iloc[:,-1],test_size = 0.2)\n#XGBoost model\nmodel = XGBRegressor(max_depth = 6)\nmodel.fit(train_x, train_y)\n#Set target object value\ntarget = model.predict(test_x)\ntarget = target.round(0)\ntarget = np.array(target)\ntarget = target.astype(int)\n#Calculate MSE\nmean_squared_error(target, test_y)\ntarget[:5]\ntest_y[:5].values\n#NEED HELP WITH THIS: How to make the predicted values into whole numbers like the CLASS column i.e., (0,1,2,3)? \n#{The method I used was to first round all the numbers to the 0th decimal place, then I converted the array to integer values.}\n#Calculate accuracy of model\naccuracy = accuracy_score(test_y, target)\nprint(\"Accuracy: %.2f%%\" % (accuracy*100))\n#NEED HELP WITH THIS: Is this a good accuracy score? (I'm assuming not)\n#What is a better model here to use to obtain a higher accuracy score?","meta":"{'source': 'AI4Code', 'id': '50558cd066af94'}"}
{"id":"132993","text":"\"\"\"\nInstalling packages used to clean and visualize the data. There are other packages\/functions used later down for each type of regression.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib \nfrom matplotlib import pyplot as plt\nimport sklearn\nimport seaborn as sns\nimport scipy as sp\nfrom scipy import stats\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\"\"\"\nNext, I uploaded and looked at a rough summary of the datasets.\n\"\"\"\n\n\ntrain = pd.read_csv('..\/input\/launchds-classification\/bank-train.csv')\ntest = pd.read_csv('..\/input\/launchds-classification\/bank-test.csv')\n\ntrain.head() # lots of categorical variables\ntrain.describe() # pdays, previous, y is very skewed\n\"\"\"\nThe features Pdays and Previous were heavily skewed in their distribution of values, so I thought it would be interesting to plot them and see what's up.\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(10, 2), sharey=False, dpi=100)\nsns.distplot(train['pdays'] , color=\"dodgerblue\", ax=axes[0], axlabel='Pdays')\nsns.distplot(train['previous'] , color=\"deeppink\", ax=axes[1], axlabel='Previous')\n\n\"\"\"\nNext, I wanted to see if there were any null values, what the balance of 1s versus 0s were in the response variable, and see how many observations there are.\n\"\"\"\nprint(train.isnull().apply(sum), '\\n') # no null values\nprint(train.groupby('y').count()['id'], '\\n') # 29245=0, 3705=1\nprint('There are',len(test),'testing observations') # 8238 testing observations\n\"\"\"\nNext came the task of transforming the categorical variables. I wanted to leave the features default, housing, loan, and poutcome as a [0,1,2] for [No,Yes,Unknown]. That could be revised later as a potential way to cut down on information. I also wanted day of the week and month to preserve the order as they fall in a calendar, so I modified them to 1-5 for Mon-Fri and 1-12 for jan-dec. Two things to note here: (1) there were no jan or feb data in the month column and no sat or sun in the day column (2) I went back later to see if coding each month\/day in it's own column would be useful and it significantly hurt my model, so I switched back to keeping them within the same variable.\n\"\"\"\ntrain.head()\n'''categorical: \njob: 'admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management',\n       'retired', 'self-employed', 'services', 'student', 'technician',\n       'unemployed', 'unknown'\nmarital: 'divorced', 'married', 'single', 'unknown'\neducation: 'basic.4y', 'basic.6y', 'basic.9y', 'high.school', 'illiterate',\n       'professional.course', 'university.degree', 'unknown'\ndefault: 'no', 'unknown', 'yes'\nhousing: 'no', 'unknown', 'yes'\nloan: 'no', 'unknown', 'yes'\ncontact: 'cellular', 'telephone'\nmonth: 'apr', 'aug', 'dec', 'jul', 'jun', 'mar', 'may', 'nov', 'oct',\n       'sep'\nday_of_week: 'fri', 'mon', 'thu', 'tue', 'wed'\npoutcome: 'failure', 'nonexistent', 'success'\n''' \n\ndef yes_no_uk(x):\n  '''used to transform default, housing, and loan'''\n  if x=='yes':\n    return(1)\n  elif x=='no':\n    return(0)\n  elif x=='unknown':\n    return(2)\n  \ndef poutcome(x):\n  '''used to transform poutcome'''\n  if x=='success':\n    return(1)\n  elif x=='failure':\n    return(0)\n  elif x=='nonexistent':\n    return(2)\n\ndef day_of_week(x):\n  '''used to transform day_of_week'''\n  if x=='mon':\n    return(1)\n  elif x=='tue':\n    return(2)\n  elif x=='wed':\n    return(3)\n  elif x=='thu':\n    return(4)\n  elif x=='fri':\n    return(5)\n  \ndef month(x):\n  '''used to transform month'''\n  if x=='jan':\n    return(1)\n  elif x=='feb':\n    return(2)\n  elif x=='mar':\n    return(3)\n  elif x=='apr':\n    return(4)\n  elif x=='may':\n    return(5)\n  elif x=='jun':\n    return(6)\n  elif x=='jul':\n    return(7)\n  elif x=='aug':\n    return(8)\n  elif x=='sep':\n    return(9)\n  elif x=='oct':\n    return(10)\n  elif x=='nov':\n    return(11)\n  elif x=='dec':\n    return(12)\n\n# transforming training ordinal variables\ndefault_labels = train['default'].apply(yes_no_uk)\nhousing_labels = train['housing'].apply(yes_no_uk)\nloan_labels = train['loan'].apply(yes_no_uk)\nmonth_labels = train['month'].apply(month)\nday_labels = train['day_of_week'].apply(day_of_week)\npoutcome_labels = train['poutcome'].apply(poutcome)\n\n# transforming test data rdinal variables\ndefault_labels2 = test['default'].apply(yes_no_uk)\nhousing_labels2 = test['housing'].apply(yes_no_uk)\nloan_labels2 = test['loan'].apply(yes_no_uk)\nmonth_labels2 = test['month'].apply(month)\nday_labels2 = test['day_of_week'].apply(day_of_week)\npoutcome_labels2 = test['poutcome'].apply(poutcome)\n\"\"\"\nNext I had to transform the categorical features that did not have a pre-defined order through one-hot encoding. These were the marital, job, education, and contact columns. I made sure to specify which 'unknown' corresponded to which variable for easy interpretation later.\n\"\"\"\n# transforming categorical variables\nmarital_labels = pd.get_dummies(train['marital'])\njob_labels = pd.get_dummies(train['job'])\neducation_labels = pd.get_dummies(train['education'])\ncontact_labels = pd.get_dummies(train['contact'])\n\n# making sure the unknowns have a specific label\nmarital_labels.columns = ['divorced', 'married', 'single', 'unknown.marital']\njob_labels.columns = ['admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management',\n       'retired', 'self-employed', 'services', 'student', 'technician',\n       'unemployed', 'unknown.job']\neducation_labels.columns = ['basic.4y', 'basic.6y', 'basic.9y', 'high.school', 'illiterate',\n       'professional.course', 'university.degree', 'unknown.education']\n\n\n\n# transforming test data\nmarital_labels2 = pd.get_dummies(test['marital'])\njob_labels2 = pd.get_dummies(test['job'])\neducation_labels2 = pd.get_dummies(test['education'])\ncontact_labels2 = pd.get_dummies(test['contact'])\n\n# making sure the unknowns have a specific label\nmarital_labels2.columns = ['divorced', 'married', 'single', 'unknown.marital']\njob_labels2.columns = ['admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management',\n       'retired', 'self-employed', 'services', 'student', 'technician',\n       'unemployed', 'unknown.job']\neducation_labels2.columns = ['basic.4y', 'basic.6y', 'basic.9y', 'high.school', 'illiterate',\n       'professional.course', 'university.degree', 'unknown.education']\n\"\"\"\nThen it came time ot piece the training and testing data back together, with the numerical features from the original data and the modified ordinal\/categoricla features just created.\n\"\"\"\ntrain_y = train['y']\ntrain2 = train[['id', 'age', 'duration', 'campaign','pdays', 'previous', 'emp.var.rate', 'cons.price.idx',\n       'cons.conf.idx', 'euribor3m', 'nr.employed']]\n\ntrain2['default'] = default_labels\ntrain2['housing'] = housing_labels\ntrain2['loan'] = loan_labels\ntrain2['month'] = month_labels\ntrain2['day'] = day_labels\ntrain2['poutcome'] = poutcome_labels\n\ntrain2 = pd.concat([train2, marital_labels], axis=1)\ntrain2 = pd.concat([train2, job_labels], axis=1)\ntrain2 = pd.concat([train2, education_labels], axis=1)\ntrain2 = pd.concat([train2, contact_labels], axis=1)\n\ntrain2['y'] = train_y\ntest2 = test[['id', 'age', 'duration', 'campaign','pdays', 'previous', 'emp.var.rate', 'cons.price.idx',\n       'cons.conf.idx', 'euribor3m', 'nr.employed']]\n\ntest2['default'] = default_labels2\ntest2['housing'] = housing_labels2\ntest2['loan'] = loan_labels2\ntest2['month'] = month_labels2\ntest2['day'] = day_labels2\ntest2['poutcome'] = poutcome_labels2\n\ntest2 = pd.concat([test2, marital_labels2], axis=1)\ntest2 = pd.concat([test2, job_labels2], axis=1)\ntest2 = pd.concat([test2, education_labels2], axis=1)\ntest2 = pd.concat([test2, contact_labels2], axis=1)\n\"\"\"\nThen I began a journey of trying different feature selection methods to see what woudl yield the best result. I started by comparing the correlation of each feature with the y variable. Through that I created two new feature sets, one that had features with abs(corr)>0.01 and one wiht abs(corr)>0.05. Then I used all three feature sets to go throgh some basic models that I will touch on later.\n\"\"\"\ncorr = pd.DataFrame()\nfor a in list('y'):\n    for b in list(train2.columns.values):\n        corr.loc[b, a] = train2.corr().loc[a, b]\n        \nsns.heatmap(corr)\nprint(corr['y'].sort_values())\n\n# variables with abs(corr)<0.01\n'''\nbasic.4y              -0.009658\nhigh.school           -0.009604\nhousemaid             -0.008696\nself-employed         -0.008180\nunknown.job           -0.003743\ntechnician            -0.001249\nmanagement            -0.000280\nloan                   0.000409\nprofessional.course    0.000415\nunknown.marital        0.002550\nilliterate             0.007441\nday                    0.008814\n'''\ntrain3 = train2[['age', 'duration', 'campaign', 'pdays', 'previous',\n       'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m',\n       'nr.employed', 'default', 'housing', 'month', 'poutcome',\n       'divorced', 'married', 'single', 'admin.',\n       'blue-collar', 'entrepreneur', 'retired',\n       'services', 'student', 'unemployed',\n       'basic.6y', 'basic.9y', 'university.degree',\n       'unknown.education', 'cellular', 'telephone']]\ntest3 = test2[['age', 'duration', 'campaign', 'pdays', 'previous',\n       'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m',\n       'nr.employed', 'default', 'housing', 'month', 'poutcome',\n       'divorced', 'married', 'single', 'admin.',\n       'blue-collar', 'entrepreneur', 'retired',\n       'services', 'student', 'unemployed',\n       'basic.6y', 'basic.9y', 'university.degree',\n       'unknown.education', 'cellular', 'telephone']]\n\n# variables with abs(corr)<0.05\n\"\"\"\nbasic.9y              -0.043711\nmarried               -0.042574\nservices              -0.031471\nbasic.6y              -0.024711\nentrepreneur          -0.016653\ndivorced              -0.010230\nbasic.4y              -0.009658\nhigh.school           -0.009604\nhousemaid             -0.008696\nself-employed         -0.008180\nunknown.job           -0.003743\ntechnician            -0.001249\nmanagement            -0.000280\nloan                   0.000409\nprofessional.course    0.000415\nunknown.marital        0.002550\nilliterate             0.007441\nday                    0.008814\nhousing                0.011729\nunemployed             0.014542\nunknown.education      0.016053\nage                    0.027631\nadmin.                 0.030412\nmonth                  0.036602\n\"\"\"\ntrain4 = train2[['duration', 'campaign', 'pdays', 'previous',\n       'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m',\n       'nr.employed', 'default', 'poutcome', 'single', 'blue-collar','retired',\n       'student', 'university.degree', 'cellular', 'telephone']]\n\ntest4 = test2[['duration', 'campaign', 'pdays', 'previous',\n       'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m',\n       'nr.employed', 'default', 'poutcome', 'single', 'blue-collar','retired',\n       'student', 'university.degree', 'cellular', 'telephone']]\n\"\"\"\nThen I made my own split on the training set to have a train_training and train_testing set to use for checking the validity of the model. There are definitley better ways that taking the last 2000 rows as the testing set, but that was the easiest way to replicate across all datasets. The y split wil also be the same for all feature sets, so i only had to define that once.\n\"\"\"\ntrain2_lite = train2.iloc[:-2000, :-1]\ntrainy_lite = train2.iloc[:-2000, -1]\ntrain2_test = train2.iloc[-2000:, :-1]\ntrainy_test = train2.iloc[-2000:, -1]\n\ntrain3_lite = train3.iloc[:-2000, :-1]\ntrain3_test = train3.iloc[-2000:, :-1]\n\ntrain4_lite = train4.iloc[:-2000, :-1]\ntrain4_test = train4.iloc[-2000:, :-1]\n\"\"\"\nTo start I performed a basic logistic regression on all 3 feature sets, and printed the results below. I used f1 score (which wants to be maximized) because I couldn't find the f mean score metric. The accuracy score is also a good measure of how well the model does at prediction. Further analysis could try different types of logistic regression other than 'liblinear'.\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlogis = LogisticRegression(solver='liblinear',fit_intercept=True)\n\nlogis_test = logis.fit(train2_lite, trainy_lite)\npreds = logis_test.predict(train2_test)\nprint(sklearn.metrics.f1_score(trainy_test, preds))\nprint(sklearn.metrics.accuracy_score(trainy_test, preds))\n\nlog_test2 = logis.fit(train3_lite, trainy_lite)\npreds2 = log_test2.predict(train3_test)\nprint(sklearn.metrics.f1_score(trainy_test, preds2))\nprint(sklearn.metrics.accuracy_score(trainy_test, preds2))\n\nlog_test3 = logis.fit(train4_lite, trainy_lite)\npreds3 = log_test3.predict(train4_test)\nprint(sklearn.metrics.f1_score(trainy_test, preds3))\nprint(sklearn.metrics.accuracy_score(trainy_test, preds3))\n\n\n\"\"\"\nRemoving the features I did barely improved the model, so I tried selecting a different subset of features using an ANOVA F-test. I used all variables that were significant at an alpha=0.01 level and ran another logistic regression. \n\"\"\"\nfrom sklearn.feature_selection import f_regression\n(F_vals, p_vals) = f_regression(train2_lite, trainy_lite)\n\ncols = list(train2_lite.columns[p_vals<0.01])\ntrainF = train2[cols]\n\ntrainF_lite = trainF.iloc[:-2000, :-1]\ntrainF_test = trainF.iloc[-2000:, :-1]\nlog_testF = logis.fit(trainF_lite, trainy_lite)\npredsF = log_testF.predict(trainF_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsF))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsF))\n# no better than original\n\"\"\"\nSo since that turned out any better than the original logistic regressions, I tried a new approach with Linear, Ridge, and Lasso regressions. (Spoiler this didn't really work out either) I messed around with different values of lambda, but the higher values caused the performance of the model to decrease, and the lower values were the same as the linear regression. This is something I could come back to and spend time refining, but I decided to see if there was a better group of features that I hadn't uncovered yet.\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\n\n\nlr = LinearRegression()\nlinreg = lr.fit(train2_lite, trainy_lite)\npredsLR = linreg.predict(train2_test)>0.32\nprint(sklearn.metrics.f1_score(trainy_test, predsLR))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsLR))\n\nrr = Ridge(alpha=0.000001, normalize=True)\nridge = rr.fit(train2_lite, trainy_lite)\npredsR = ridge.predict(train2_test)>0.32\nprint(sklearn.metrics.f1_score(trainy_test, predsR))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsR))\n\nlasso = Lasso(alpha=0.00000000001, normalize=True)\nlass = lasso.fit(train2_lite, trainy_lite)\npredsLass = lass.predict(train2_test)>0.32\nprint(sklearn.metrics.f1_score(trainy_test, predsLass))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsLass))\n\"\"\"\nWelcome to Decision trees! I did a Decision Tree Classification and Random Forest Classification to see what features they decided were important. My thought was that I could take the top 10 or so features that were of note and go back and try some of the simpler regressions with that new subset of features.\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\ntree = DecisionTreeClassifier()\ntreeD = tree.fit(train2_lite, trainy_lite)\npredsTD = treeD.predict(train2_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsTD))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsTD))\n\nforest = RandomForestClassifier(criterion = 'entropy')\nforestR = forest.fit(train2_lite, trainy_lite)\npredsF = forestR.predict(train2_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsF))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsF))\nprint(pd.DataFrame({'Gain': treeD.feature_importances_}, index = train2_lite.columns).sort_values('Gain', ascending = False))\nprint(pd.DataFrame({'Importance': forestR.feature_importances_}, index = train2_lite.columns).sort_values('Importance', ascending = False))\n\"\"\"\nI found that there was significant overlap between the two methods of determining feature importance. The top 10 features from decision tree and random forest are shown below with dashes next to features that were included in both.\n\nDecision Tree\nduration               0.302235-\nid                     0.153253-\nage                    0.070679-\neuribor3m              0.053408-\nnr.employed            0.037945-\npdays                  0.034321-\ncampaign               0.032640-\nday                    0.030208-\nemp.var.rate           0.024689\nmonth                  0.021207\n\nRandom Forest\nduration             0.327945-\nnr.employed          0.154874-\nid                   0.116405-\nage                  0.074104-\neuribor3m            0.037914-\ncampaign             0.032394-\ncons.conf.idx        0.023777\nday                  0.023379-\npdays                0.022481-\nhousing              0.013133\n\nUsing this imformation, I created a new set of the training data with all of these features shown above. the ones not included in both top 10 were within the top 15 of the other feature list, so I felt comfortable including them. I didn't include month however, because I felt that variable had too much going on with it.\n\"\"\"\ntrainT = train2[['duration', 'id', 'age', 'euribor3m', 'nr.employed', \n                 'pdays', 'campaign', 'day', 'cons.conf.idx', 'housing',\n                'emp.var.rate']]\ntrainT_lite = trainT.iloc[:-2000,:]\ntrainT_test = trainT.iloc[-2000:, :]\n\ntestT = test2[['duration', 'id', 'age', 'euribor3m', 'nr.employed', \n                 'pdays', 'campaign', 'day', 'cons.conf.idx', 'housing',\n                'emp.var.rate']]\n\"\"\"\nThen I went back to the two tree models and input the new set of features to see if the model performance improved. they actually performed slightly better with the removal of variables, so I think I reduced a bit of overfitting that was occuring. I'd be curious to go back and try parsing down the variables even more later.\n\"\"\"\ntreeD2 = tree.fit(trainT_lite, trainy_lite)\npredsTD2 = treeD2.predict(trainT_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsTD2))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsTD2))\n\n\nforest2 = RandomForestClassifier(criterion = 'gini')\nforestR2 = forest2.fit(trainT_lite, trainy_lite)\npredsF2 = forestR2.predict(trainT_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsF2))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsF2))\n\"\"\"\nI then ran a Linear\/Ridge\/Lasso\/Bayes Regression on this new set of features selected by the trees, and I reached my best model so far. Again, I tried playing around with values of lambda, but I couldn't get a good compromise without reducing the model performance. I did adjust the cutoff value to 0.3 (instead of 0.5) for the Linear\/Ridge\/Lasso becuase that gave the bet accuracy and f1 score. My first submission was of this linear regression model.\n\"\"\"\nlinregT = lr.fit(trainT_lite, trainy_lite)\npredsLRT = linregT.predict(trainT_test)>0.3\nprint(sklearn.metrics.f1_score(trainy_test, predsLRT))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsLRT))\n\n\nrr = Ridge(alpha=0.000001, normalize=True)\nridgeT = rr.fit(trainT_lite, trainy_lite)\npredsRT = ridgeT.predict(trainT_test)>0.3\nprint(sklearn.metrics.f1_score(trainy_test, predsRT))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsRT))\n\n\nlassoT = Lasso(alpha=0.000001, normalize=True)\nlassT = lassoT.fit(trainT_lite, trainy_lite)\npredsLassT = lassT.predict(trainT_test)>0.3\nprint(sklearn.metrics.f1_score(trainy_test, predsLassT))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsLassT))\n\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\nmodel = gnb.fit(trainT_lite, trainy_lite)\npredsG = model.predict(trainT_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsG))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsG))\n\n\n\"\"\"\nI decided to run another logistic regression. It performed fairly well, and although the accuracy score was one of the highest to date, the f1 score was still fairly low, so I believe there still may be overfitting happening. I will go back later and try an even more reduced subset of variables.\n\"\"\"\nlogis_test2 = logis.fit(train2_lite, trainy_lite)\npredsL = logis_test2.predict(train2_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsL))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsL))\n\"\"\"\nNext, I moved onto Support Vector Machines (SVM), which gave me my second best entry to date. This took a minute to run, but was really a\n\"\"\"\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import  LogisticRegression\nclassifier = SVC(kernel=\"linear\")\n\nsvm = classifier.fit(trainT_lite, trainy_lite)\npredsSVM = svm.predict(trainT_test)\nprint(sklearn.metrics.f1_score(trainy_test, predsSVM))\nprint(sklearn.metrics.accuracy_score(trainy_test, predsSVM))\n\"\"\"\nI also tried K-Nearest Neighbors which was fairly successful, but not as good as SVM or Linear Regression. \n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier \nknn = KNeighborsClassifier()\nknn.fit(trainT_lite, trainy_lite)\npredKNN = knn.predict(trainT_test)\nprint(sklearn.metrics.f1_score(trainy_test, predKNN))\nprint(sklearn.metrics.accuracy_score(trainy_test, predKNN))\n\n\"\"\"\nIt was at this point that I was convinced that I needed to go back and parse down my feature subset even more, so I took only the features that were included in the the top 10 of both Decision Tree and Random Forest. No different selection of features improved Linear\/Ridge\/Lasso\/Bayes\/Logistic, so I went back to the drawing board. Something way back when I switched categorical variables to numeric probably want optimized.\n\"\"\"\n\"\"\"\nWhen we joined as a group, we attmpted imputing the unknown values, which was very difficult and did not get us anywhere. We also tried different methods of feature selection (stepwise, further reduction based on tree importance) and those did not yield good results either. We also tried oversampling to help balance out the number of successes and failures in the response column, but that actually hurt our model performance. \n\n\n\nBased on all of the attempts above, we submitted our top three models:\n1. Linear regression with a cutoff of 0.3 on the top 13 features most important to decision tree and random forest\n2. SVM on the top 13 features most important to decision tree and random forest\n3. Random Forest on the top 13 features most important to decision tree and random forest\n\nThe code for producing the final predictions is shown below. The accuracy and f1score of the same models but with the training data can be found in the previous sections.\n\"\"\"\n# 1. Linear Regression\nlr = LinearRegression()\nlinregT = lr.fit(trainT, train.iloc[:, -1]) # best so far\nprediction1 = linregT.predict(testT)>0.3\n\ndef TF(x):\n  if x==True:\n    return(1)\n  elif x==False:\n    return(0)\n\nsubmission = pd.concat([test.id, pd.Series(prediction1)], axis = 1)\nsubmission.columns = ['id', 'Predicted']\nsubmission['Predicted'] = submission['Predicted'].apply(TF)\nsubmission.to_csv('submission.csv', index=False)\n\n# 2. SVM\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import  LogisticRegression\n#classifier = SVC(kernel=\"linear\")\n#svm = classifier.fit(trainT, train.iloc[:, -1])\npredictions3 = svm.predict(testT)\nsubmission = pd.concat([test.id, pd.Series(predictions3)], axis = 1)\nsubmission.columns = ['id', 'Predicted']\nsubmission.to_csv('submission.csv', index=False)\n\n\n# 3. Random Forest\nforest2 = RandomForestClassifier(criterion = 'gini')\nforestR2 = forest2.fit(trainT, train.iloc[:, -1])\npredsF2 = forestR2.predict(testT)\nsubmission = pd.concat([test.id, pd.Series(predsF2)], axis = 1)\nsubmission.columns = ['id', 'Predicted']\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'f4a54bcfb19723'}"}
{"id":"31957","text":"# 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\n# Solving this problem as my first practice problem \n#Steps to solve any machine learning problem \n# 1: Load dataset\n# 2: EDA \n# 3: Build linear model \n# 4: Evaluate the model \n# 5: Predict with some data \nimport numpy as np\nimport pandas as pd \nimport matplotlib as mt \nimport seaborn as sns \n\n%matplotlib inline \ntrain_data = pd.read_csv(\"\/kaggle\/input\/random-linear-regression\/train.csv\")\ntest_data = pd.read_csv(\"\/kaggle\/input\/random-linear-regression\/test.csv\")\n# EDA \n# 1: check the data type of the data \n\ntrain_data.info()\ntrain_data.head()\n# check the relation ship among the data. If we can apply linear regression \nsns.pairplot(train_data)\n\"\"\"\nWe can see X and Y are positive co related. Lets check if what is the co relation among the two data point \n\n\"\"\"\ntrain_data.corr()\nfrom sklearn.linear_model import  LinearRegression\nlg = LinearRegression()\n\n# while training model fit failed due to null value in the data. Check if there is any null\ntrain_data.isnull().values.any()\ntrain_data = train_data.dropna()\nlg.fit(train_data[['x']],train_data.y)\n# check the coeff and y intercept \nlg.intercept_\nlg.coef_\nX_test = test_data[['x']]\nY_test = test_data.y\nY_predict = lg.predict(X_test);\n# not lets check the r^2 value  \nfrom sklearn.metrics import r2_score\nr2_score(Y_test,Y_predict)\n\"\"\"\nBest possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a  score of 0.0. :) \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3ad7d87b4b2ab2'}"}
{"id":"26009","text":"\"\"\"\n# Toxic Comment Analysis\n\"\"\"\n\"\"\"\nThe internet has given people the freedom of speech like no other. Yet, quoting the late Uncle Ben:\n> with great internet connection, comes great responsibility\n\nIndeed, it is tempting to just use word embedding combined with a sequence-based model such as LSTM , but I won't understand why does it work in this case. Does it really solve the biased prediction problem? Not to mention why auxiliary attributes improve the performance of the model and is widely used. For this reason, I reside to the \"traditional\" EDA method, hoping to get a better sense of the dataset before preprocessing or developing any models. There is no fancy stuff going on, but I believe we can still learn a thing or two using simple methods.\n\nIn this kernel, I explore some features of the toxic comments that is not commonly discussed in other EDA kernels. First, I look into annotators and their labels. Since every comments can have different number of annotators, is there any difference in the agreement level? Next, I revisited toxic subtypes and identity columns to see whether those attributes can help us identify toxic comments. I continue with lexical analysis, hoping to find any distinguishable characteristics between toxic and safe comments. Finally, I dig deeper into the unintended bias and see what kind of comments are misclassified using a simple keyword-based prediction.\n\nCan we capture some toxic villains today?\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/media.giphy.com\/media\/3xz2BIIBBvBS8iDofm\/giphy.gif\" alt=\"internet-fight-spiderman\" \/> <br \/>\n*(source: giphy)*\n\"\"\"\n# basic imports\nimport string\nimport re\nimport gc\nfrom collections import Counter\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom mpl_toolkits.mplot3d import Axes3D\nimport seaborn as sns\nimport pickle\n\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk import pos_tag\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom tqdm._tqdm_notebook import tqdm_notebook as tqdm; tqdm.pandas()\n\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve\nfrom sklearn.decomposition import TruncatedSVD\n\n# dataframe options to display the whole comments\npd.set_option('display.max_colwidth', -1)\n\n# extra config to have better visualization\nsns.set(\n    style='whitegrid',\n    palette='coolwarm',\n    rc={'grid.color' : '.96'}\n)\nplt.rcParams['font.size'] = 12\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['axes.labelweight'] = 'bold'\nplt.rcParams['axes.titlesize'] = 20\nplt.rcParams['axes.titleweight'] = 'bold'\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\nplt.rcParams['legend.fontsize'] = 14\nplt.rcParams['figure.titlesize'] = 30\nplt.rcParams[\"figure.titleweight\"] = 'bold'\n# pandas dataframe background gradient to consider all rows and columns.\n# By default, background gradient styling in pandas only consider by column.\n# function taken from: https:\/\/stackoverflow.com\/questions\/38931566\/pandas-style-background-gradient-both-rows-and-columns\ndef background_gradient(s, m, M, cmap='PuBu', low=0, high=1):\n    rng = M - m\n    norm = colors.Normalize(m - (rng * low),\n                            M + (rng * high))\n    normed = norm(s.values)\n    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]\n    return ['background-color: %s' % color for color in c]\n# data loading\n# use only training set\ntrain = pd.read_csv('..\/input\/train.csv')\ntrain.columns\ntoxic_subtypes = [\n    'severe_toxicity',\n    'obscene',\n    'threat',\n    'insult',\n    'identity_attack',\n    'sexual_explicit'\n]\n\nidentity_attrs = [\n    'asian', 'atheist', 'bisexual',\n    'black', 'buddhist', 'christian', 'female', 'heterosexual', 'hindu',\n    'homosexual_gay_or_lesbian', 'intellectual_or_learning_disability',\n    'jewish', 'latino', 'male', 'muslim', 'other_disability',\n    'other_gender', 'other_race_or_ethnicity', 'other_religion',\n    'other_sexual_orientation', 'physical_disability',\n    'psychiatric_or_mental_illness', 'transgender', 'white',\n]\n\nidentity_attrs_group = {\n    'gender': ['female', 'male', 'transgender', 'other_gender'],\n    'race': ['asian', 'black', 'jewish', 'latino', 'white', 'other_race_or_ethnicity'],\n    'religion': ['atheist', 'buddhist', 'christian', 'hindu', 'muslim', 'other_religion'],\n    'sexual_orientation': ['bisexual', 'heterosexual', 'homosexual_gay_or_lesbian', 'other_sexual_orientation'],\n    'disability': ['intellectual_or_learning_disability', 'physical_disability', 'psychiatric_or_mental_illness', 'other_disability']\n}\n\"\"\"\n# 1. Understanding Toxic Annotations\n\"\"\"\n\"\"\"\nThe first part examines the dependent variable and potential auxiliary attributes.\n\"\"\"\n\"\"\"\n## 1.1 Toxic comments distribution\n\"\"\"\n# create a 0 or 1 column and see the proportion\ntrain['is_toxic'] = train['target'] >= 0.5\ntoxic_count = train['is_toxic'].value_counts()\ntoxic_prop = toxic_count \/ len(train['is_toxic'])\nprint(\"There are {:,} ({:.2f}%) toxic comments out of {:,} comments in the dataset\".format(\n    toxic_count[True],\n    toxic_count[True] * 100 \/ len(train['is_toxic']),\n    len(train['is_toxic'])\n))\n\"\"\"\nToxic comments account only 8% of the training data, meaning we are dealing with **imbalanced** dataset. How about the actual agreed toxicity level distribution of the annotators?\n\"\"\"\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = sns.kdeplot(train['target'], shade=True, ax=ax)\n_ = ax.set(xlabel='Annotator Toxicity Agreement', ylabel='Density')\n\"\"\"\nAs expected, most of the comments were deemed non-toxic by all of the annotators. However, when it comes to toxic comments, it is hardly unanimous. The number of comments with target score equal to 1.0 is really small. Another boggling thing is the number of annotators for each comment can be different. Is it correct to assume that more annotators means more believable? Let's check if the toxicity of a comment is related to the number of annotators.\n\"\"\"\ntrain['log_toxicity_annotator_count'] = np.log10(train['toxicity_annotator_count'])\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = train['log_toxicity_annotator_count'].hist(bins=15, density=True, ax=ax)\n_ = ax.set(xlabel='log10(annotator count)', ylabel='Density')\n\"\"\"\nThere seems to be two clusters in terms of the number of annotators: below 10^1.5 and above 10^1.5. Is there any difference in the toxicity agreement of those two clusters?\n\"\"\"\ntrain['many_annotators'] = train['log_toxicity_annotator_count'] >= 1.5\n\nprint(\"There are {:,} comments with number of annotators below 10^1.5 and {:,} above 10^1.5.\".format(\n    len(train[train['log_toxicity_annotator_count'] < 1.5]),\n    len(train[train['log_toxicity_annotator_count'] >= 1.5])\n))\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 7.5))\n\n_ = sns.kdeplot(\n    train[~train['many_annotators']]['target'], \n    shade=True,\n    ax=ax1\n)\n_ = ax1.set_title('number of annotators < 10^1.5')\n_ = ax1.set_ylabel('density')\n_ = ax1.set_ylabel('#annotators')\n\n_ = sns.kdeplot(\n    train[train['many_annotators']]['target'], \n    shade=True,\n    ax=ax2\n)\n_ = ax2.set_title('number of annotators >= 10^1.5')\n_ = ax2.set_ylabel('density')\n_ = ax2.set_ylabel('#annotators')\n\n\"\"\"\nThe two graphs above reveal some degree of correlation between the number of annotators with the toxic comments. When the number of annotators is more than 10^1.5, the target score peaked towards 0.7. Looking at the data description page, this phenomenon is intentional due to imposed strategy, although we are not presented with the details:\n> Some comments were seen by many more than 10 annotators (up to thousands), due to sampling and strategies used to enforce rater accuracy.\n\nBy analysing the number of annotators, we can exploit the information to give more attention to comments with more annotators when we train our model. This initial analysis suggests the possibility of various weight for each comment depending on the number of annotators. \n\nThe following sub-sections about subtypes and identities are common in other EDA kernels as well, but it is good to re-visit them. I see subtypes are being used as auxiliary attributes during training but not identities, what could be the reason?\n\"\"\"\n\"\"\"\n## 1.2 Toxic Subtypes Distribution\n\"\"\"\n\"\"\"\nLet's find out which sub-types are the most common.\n\"\"\"\nsubtypes_count = (train[toxic_subtypes] > 0.5).sum(axis=0).sort_values(ascending=False)\nsubtypes_prop = np.round(subtypes_count * 100 \/ len(train), 2)\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = sns.barplot(x=subtypes_count.index, y=subtypes_count.values, ax=ax)\n_ = ax.set_title('Toxic Subtypes Distribution (with % of all comments)')\n_ = ax.set_xlabel('Toxic Subtypes')\n_ = ax.set_ylabel('#Comments')\n\nfor p, label in zip(ax.patches, subtypes_prop.values):\n    ax.annotate(\"{:.2f}%\".format(label), (p.get_x()+0.275, p.get_height()+500))\n\"\"\"\nAs shown, it is clear that *insult* is the dominant type of toxic comments. The number of *insult* comments is 10x the number of the closest next two categories: *obscene* and *identity_attack*. I am not quite sure what each type means, it is good to see an example for each:\n\"\"\"\nsubtype_examples = []\nfor subtype_col in toxic_subtypes:\n    comment = train[[subtype_col, 'toxicity_annotator_count', 'comment_text']].sort_values(\n        by=[subtype_col, 'toxicity_annotator_count'], ascending=False).iloc[0]\n    subtype_examples.append({\n        'subtype' : subtype_col,\n        'comment' : comment['comment_text'],\n        'subtype_toxicity_level' : comment[subtype_col],\n        'num_annotators' : comment['toxicity_annotator_count']\n    })\nsubtype_examples_df = pd.DataFrame(subtype_examples).set_index('subtype')\nsubtype_examples_df\n\"\"\"\nLooking at the examples, it seems this subtypes are not supposed to be mutually exclusive. The example of *sexual_explicit* also has some degree of *insult* (\"...rethuglican rugrats, pleasure, or, on rare occasion, shooting Ping Pong balls...\"). Similarly with the example of *obscene* which include some sort of threat (\"Quarantine should end with a bullet between the eyes ... Bear spray to the face.\"). How related each types and also with the target?\n\"\"\"\ncorr = train[toxic_subtypes + ['target']].corr()\ncorr.style.apply(background_gradient, m=corr.min().min(), M=corr.max().max()).set_precision(2)\n\"\"\"\nTo my surprise, *insult* and *target* correlation score is really high: 0.93! Although *obscene* and *identity_attack* have 0.49 and 0.45, respectively, but 0.93 is just another level. Maybe we should focus on predicting *insult* as the definition of *toxic*?\n\"\"\"\n\"\"\"\n## 1.3 Identity Distribution\n\"\"\"\nidentity_df = train[identity_attrs].dropna(axis=0, how='all')\nprint(\"There are {:,} ({:.2f}% of all training set) identity-labelled comments, out of which {:,} ({:.2f}%) are not identity offensive.\".format(\n    len(identity_df),\n    len(identity_df) * 100 \/ len(train),\n    len(identity_df[np.sum(identity_df, axis=1) == 0]),\n    len(identity_df[np.sum(identity_df, axis=1) == 0]) * 100 \/ len(identity_df)\n))\n\"\"\"\nThe first reason why identity columns are not as helpful as subtypes is the data availability. Only 22.45% of the training set are labelled and half of them are not considered toxic. Let's explore the distribution of comments that have been labelled with identities:\n\"\"\"\nidentity_count = (identity_df > 0.5).sum(axis=0).sort_values(ascending=False)\nidentity_prop = np.round(identity_count * 100 \/ len(identity_df), 2)\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = sns.barplot(x=identity_count.values, y=identity_count.index, ax=ax)\n_ = ax.set_title('Identity Distribution (with % of all identity-labeled comments)')\n_ = ax.set_xlabel('Identity Labels')\n_ = ax.set_ylabel('#Comments')\n\nfor p, label in zip(ax.patches, identity_prop.values):\n    ax.annotate(\"{:.2f}%\".format(label), (p.get_width(), p.get_y()+0.6))\n\"\"\"\nAnd if we group the identity columns:\n\"\"\"\nidentity_group_count = pd.Series(\n    dict(\n        (g, np.sum(identity_count[identity_count.index.isin(identity_attrs_group[g])])) \n        for g in identity_attrs_group)\n).sort_values(ascending=False)\nidentity_group_prop = np.round(identity_group_count * 100 \/ len(identity_df), 2)\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = sns.barplot(x=identity_group_count.index, y=identity_group_count.values, ax=ax)\n_ = ax.set_title('Identity Distribution (with % of all comments w\/ identity data)')\n_ = ax.set_xlabel('Identity Types')\n_ = ax.set_ylabel('#Comments')\n\nfor p, label in zip(ax.patches, identity_group_prop.values):\n    ax.annotate(\"{:.2f}%\".format(label), (p.get_x()+0.275, p.get_height()+500))\n\"\"\"\nThe most popular identity is regarding *gender* followed by *religion* and *race*, still not so dominating as *insult* subtype. How about the correlation with the *target*?\n\"\"\"\nidentity_group_df = pd.DataFrame()\nfor g in identity_attrs_group:\n    identity_group_df[g] = np.max(identity_df[identity_attrs_group[g]], axis=1)\nidentity_group_w_target_df = identity_group_df.join(train['target'], how='left')\ncorr = identity_group_w_target_df.corr()\ncorr.style.apply(background_gradient, m=corr.min().min(), M=corr.max().max()).set_precision(2)\n\"\"\"\nWith such low correlation, identity columns are not a promising auxiliary attributes. Except *race* and *sexual_orientation*, the correlation to target is almost 0. Even *race*, which has the highest correlation, only score 0.22.\n\"\"\"\n\"\"\"\n## 1.4 Toxic Subtypes and Identity Correlation\n\"\"\"\n\"\"\"\nAs we are interested about *insult* subtypes, is there any correlation between the identity columns to the subtypes?\n\"\"\"\nidentity_group_w_subtypes_df = identity_group_df.join(train[toxic_subtypes], how='left')\ncorr = identity_group_w_subtypes_df.corr()\ncorr = corr.loc[toxic_subtypes, list(identity_attrs_group.keys())]\ncorr.style.apply(background_gradient, m=corr.min().min(), M=corr.max().max()).set_precision(2)\n\"\"\"\nOf course *identity_attack* is somewhat correlated with the identity columns, but we do not find any meaningful correlation between any of the identity groups with either *target* or *insult*. Thus, identity columns are not really helpful when we want to predict *target*.\n\"\"\"\n\"\"\"\n# 2. Comments Analysis\n\"\"\"\n\"\"\"\n## 2.1 Lexical analysis\n\"\"\"\n\"\"\"\nThe purpose of the lexical analysis is to see comments characteristic before moving on to understanding them semantically. Can we get some clue about the toxicity of a comment based on the total number of characters in the comment or the average word length? Another aspect that we can investigate is the part-of-speech. The hypothesis is that toxic comments consist of adjectives. Let's consult the data to find the answer:\n\"\"\"\ndef plot_cdf(ax, df, col, xlabel):\n    _ = ax.hist(df[(df['target'] >= 0.5) & (df[col] < df[col].quantile(.99))][col], 200, \n                               density=True, histtype='step', color='red',\n                               cumulative=True, label='toxic')\n    _ = ax.hist(df[(df['target'] < 0.5) & (df[col] < df[col].quantile(.99))][col], 200,\n                               density=True, histtype='step', color='blue',\n                               cumulative=True, label='non-toxic')\n    _ = ax.legend(loc='upper left')\n    _ = ax.set_xlabel(xlabel)\n    _ = ax.set_ylabel('Proportion')\n    \n    return ax\ntrain['char_length'] = train['comment_text'].progress_apply(lambda c: len(c))\ntrain['tokenized_comment'] = train['comment_text'].progress_apply(\n    lambda c: [t.lower() for t in re.split(\"[\\s\\-\u2014]+\", c.translate(str.maketrans('', '', string.punctuation))) if len(t) > 0]\n)\ntrain['num_tokens'] = train['tokenized_comment'].progress_apply(lambda c: len(c))\ntrain['average_token_length'] = train['tokenized_comment'].progress_apply(lambda c: np.mean([len(t) for t in c]) if len(c) > 0 else 0)\ntrain['comment_sentences'] = train['comment_text'].progress_apply(lambda c: sent_tokenize(c))\ntrain['number_of_sentences'] = train['comment_sentences'].progress_apply(lambda s: len(s))\ntrain['capital_letters_prop'] = train['comment_text'].progress_apply(lambda c: sum(1 for i in c if i.isupper()) \/ len(c))\ntrain['non_alphanumeric_prop'] = train['comment_text'].progress_apply(lambda c: sum(1 for t in c if not t.isalnum()) \/ len(c))\nfig, axs = plt.subplots(nrows=3, ncols=2, sharey=True, figsize=(18, 18))\nplt.suptitle('Lexical CDF')\n\n_ = plot_cdf(axs[0,0], train, 'char_length', 'Number of Characters')\n_ = plot_cdf(axs[0,1], train, 'num_tokens', 'Number of Tokens')\n_ = plot_cdf(axs[1,0], train, 'average_token_length', 'Average Token Length')\n_ = plot_cdf(axs[1,1], train, 'number_of_sentences', 'Number Of Sentences')\n_ = plot_cdf(axs[2,0], train, 'capital_letters_prop', 'Capital Letters Proportion')\n_ = plot_cdf(axs[2,1], train, 'non_alphanumeric_prop', 'Non-Alphanumeric Proportion')\n\"\"\"\nWell, there is no significant difference between toxic and safe comments in any of the plots. We can observe, barely, that toxic comments tend to be longer with more number of tokens (or words). However, there is an usual spike for non-toxic comments with more than 950 characters. Seems some safe comments are (extremely) elaborative, but in general the longer means more likely to be toxic, also as shown by the number of sentences plot.\n\nAnother hypothesis is that using a lot of capital letters and punctuation marks (e.g. a burst of exclamation or question marks) might signal toxic comments. However, there is no evidence of such thing in terms of capital letters and non-alphanumeric proportion. If that's the case, then using lower-case and removing alpha-numeric should be fine. It is worth to take another look at this with POS analysis.\n\"\"\"\n\"\"\"\n## 2.2 POS analysis\n\"\"\"\n\"\"\"\nIt is remarkable how a human can call another human with obscure words in an online forum. Based on personal observation, I suspect toxic comments contain more adjective than safe comments. Fortunately, NLTK has a default POS tagger for english. It might not work that well for online forum contents due to colloquial languages, but it can help us to some extent in verifying our hypothesis.\n\nFor the POS analysis, I am going to use downsampling for the non-toxic class mainly due to memory limitation. Downsampling is done randomly.\n\"\"\"\nn = len(train[train['target'] >= 0.5])\ntrain_sample = pd.concat([train[train['target'] >= 0.5].sample(n=n, random_state=1336), train[train['target'] < 0.5].sample(n=2*n, random_state=1337)])\ndel identity_df\ndel train\n_ = gc.collect()\n\nn_train_sample = len(train_sample)\nprint(\"The number of samples: {:,}\".format(n_train_sample))\ntrain_sample_pos = train_sample.join(\n    train_sample['tokenized_comment'].progress_apply(\n        lambda c: pd.Series(Counter('POS_' + p[:2] + '_prop' for w,p in pos_tag(c))) \/ len(c)\n    )\n)\npos_columns = ['POS_JJ_prop', 'POS_NN_prop', 'POS_IN_prop',\n       'POS_PR_prop', 'POS_VB_prop', 'POS_CC_prop', 'POS_MD_prop',\n       'POS_RB_prop', 'POS_TO_prop', 'POS_DT_prop', 'POS_WD_prop',\n       'POS_EX_prop', 'POS_WP_prop', 'POS_CD_prop', 'POS_WR_prop',\n       'POS_PD_prop', 'POS_RP_prop', 'POS_UH_prop', 'POS_FW_prop',\n       'POS_\\'\\'_prop', 'POS_PO_prop', 'POS_$_prop']\ntrain_sample_pos[pos_columns + ['target']].corr()['target'].sort_values(ascending=False)[1:]\n\"\"\"\nAlthough small, these POS tags have positive correlation with the target value:\n1. PR: pronouns (her, hers, himself)\n2. PD: predeterminers (all, half, both)\n3. JJ: adjectives\n4. RP: particles (about)\n\nThey are not as significant as expected, but we can get a sense of the construction of a toxic comment. Let's see the CFD:\n\"\"\"\nfig, axs = plt.subplots(nrows=2, ncols=2, sharey=True, figsize=(18, 12))\nplt.suptitle('POS CDF')\n\n_ = plot_cdf(axs[0,0], train_sample_pos, 'POS_PR_prop', 'Pronoun Proportion')\n_ = plot_cdf(axs[0,1], train_sample_pos, 'POS_PD_prop', 'Predeterminer Proportion')\n_ = plot_cdf(axs[1,0], train_sample_pos, 'POS_JJ_prop', 'Adjectives Proportion')\n_ = plot_cdf(axs[1,1], train_sample_pos, 'POS_RP_prop', 'Particles Proportion')\n\"\"\"\nOn the other side, these POS tags are a sign of a safe comments:\n1. PO: possessive ending (person's)\n2. CD: digits\n3. UH: interjection (uh, yeah, ah)\n4. IN: preposition\/conjunction (on, in, but)\n\nThis means, we should put more attention when we are handling those words during preprocessing. It is better to keep numbers, but maybe we can change them as a same token (\"DIGIT\"). Handling possesive ending seems relevant. Interjection, which seems to be meaningless, is worth a second look. Lastly, we need to be cautious about stopwords removal, does it remove prepositions? Before concluding, see in details for those 4 POS tags:\n\"\"\"\nfig, axs = plt.subplots(nrows=2, ncols=2, sharey=True, figsize=(18, 12))\nplt.suptitle('POS CDF')\n\n_ = plot_cdf(axs[0,0], train_sample_pos, 'POS_PO_prop', 'Possessive Ending Proportion')\n_ = plot_cdf(axs[0,1], train_sample_pos, 'POS_CD_prop', 'Digits Proportion')\n_ = plot_cdf(axs[1,0], train_sample_pos, 'POS_UH_prop', 'Interjection Proportion')\n_ = plot_cdf(axs[1,1], train_sample_pos, 'POS_IN_prop', 'Preposition Proportion')\n\"\"\"\nFor possessive endings, there are not many occurrences of the POS (looking at the number of \"steps\" in the chart) and it might be overfitting to those specific comments. This may also be the case for interjection. In terms of digits and preposition, however, higher proportion tend to be a safe comment.\n\nNote that since the POS tags correlation with the target value is really small either for positive and negative, it might not be that useful for predicting target value. Nevertheless, it offers a hint if using stopwords provide better results than removing them.\n\"\"\"\n\"\"\"\n# 3. Vocabulary\n\"\"\"\n\"\"\"\nAfter we analyse the lexical characteristic of the comments, we are ready to touch the surface of semantic analysis. I am using a simple method called Term Frequency - Inverse Document Frequency (TF-IDF) to capture the importance of a word in a comment. TF-IDF has many flaws, of course, but it is a quick way of feature engineering without building any models. Moreover, it is definitely better than just a frequency-based bag-of-words. Subsequently, I use (yet another) simple naive bayes model to find which terms are important predictors.\n\"\"\"\n\"\"\"\n## 3.1 TF-IDF\n\"\"\"\n\"\"\"\nOne of the weakness of TF-IDF is the inability to capture the similarity of the same word on different forms. As an illustration, \"available\" and \"availability\" are just as different as \"apple\" and \"duck\". The only way to capture the relationship between words are their co-occurrences in sentences. To handle this, I am using a stemmer. Stemming is not a fool-proof technique because we will lose some degree of information by doing so. However, as I want to analyze which word is the most relevant for a toxic\/safe comments, not building the most accurate model, stemming should come in handy for now. Also, stopwords are not removed as preposition and interjection are positively correlated with safe comments.\n\"\"\"\nstemmer = SnowballStemmer(\"english\")\ntrain_sample['stemmed_comment'] = train_sample['tokenized_comment'].progress_map(lambda c: ' '.join([stemmer.stem(t) for t in c]))\ncomment_df = train_sample[['comment_text', 'stemmed_comment', 'toxicity_annotator_count', 'target']].sample(frac=1, random_state=1338)\ndel train_sample_pos\ndel train_sample\n_ = gc.collect()\n# constructing TF-IDF term-weighting vocabulary\n# Only words that occur in at least 50 comments are included\nvectorizer = TfidfVectorizer(min_df=50, max_df=.15, ngram_range=(1, 2))\ntrain_n = int(0.1 * n_train_sample)\nX_train = vectorizer.fit_transform(comment_df[:train_n]['stemmed_comment'])\nX_test = vectorizer.transform(comment_df[train_n:]['stemmed_comment'])\ny_train = comment_df[:train_n]['target'] >= 0.5\ny_test = comment_df[train_n:]['target'] >= 0.5\nprint(\"Number of vocabulary: {:,}\".format(len(vectorizer.get_feature_names())))\n\"\"\"\nWe can see which terms have the highest weight by using the average of TF-IDF value:\n\"\"\"\navg_tfidf = np.asarray(X_train.mean(axis=0)).ravel().tolist()\nweights_df = pd.DataFrame({'term': vectorizer.get_feature_names(), 'avg_tfidf': avg_tfidf})\nweights_df.sort_values(by='avg_tfidf', ascending=False).head(25)\n\"\"\"\nIt is interesting to see that among the highest average tf-idf are mostly what are usually considered as stopwords (he, so, an). We can see that those terms have the highest weights, but are they a good predictor for toxic comments? Naive Bayes to the rescue.\n\"\"\"\n\"\"\"\n## 3.2 Naive Bayes\n\"\"\"\n\"\"\"\nWe want to model a comment being toxic given the term weights of words in the comment. We calculate the probability by looking at the probability of a toxic comments among all comments, probability of each word in a toxic comment, and the probability of the word itself among all corpora.\n\nBecause we have 6.857 words in our vocabulary, each comment is represented as a vector with length 6.857, and most of the elements are zeros. In the end, our goal is to see which words are predictors of toxic\/safe comments.\n\"\"\"\ndef informative_features(vectorizer, clf, n=20):\n    feature_names = vectorizer.get_feature_names()\n    coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))\n    top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])\n    for (coef_1, fn_1), (coef_2, fn_2) in top:\n        print(\"\\t{:8.4f} * {:15}\\t\\t{:8.4f} * {:15}\".format(coef_1, fn_1, coef_2, fn_2))\n\"\"\"\nBecause we are dealing with imbalanced dataset, I am using sample weighting. As the number of safe comments are twice the number of toxic comments in the sample, the weight of the toxic comments are twice the weight of a safe comment during training. In other words, we force the model to perform well on predicting a toxic comment correctly.\n\"\"\"\nnb_model = MultinomialNB()\nnb_model.fit(X_train, y_train, sample_weight=list(y_train * 0.5 + 0.5))\ny_pred_nb = nb_model.predict(X_test)\ny_prob_nb = nb_model.predict_proba(X_test)[:,1]\nroc_auc = roc_auc_score(y_test, y_prob_nb)\nfpr, tpr, threshold = roc_curve(y_test, y_prob_nb)\nprint(confusion_matrix(y_test, y_pred_nb))\nfig, ax = plt.subplots(figsize=(12, 7.5))\n_ = ax.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)\n_ = ax.legend(loc = 'lower right')\n_ = ax.plot([0, 1], [0, 1],'r--')\n_ = ax.set_title('Receiver Operating Characteristic')\n_ = ax.set_ylabel('True Positive Rate')\n_ = ax.set_xlabel('False Positive Rate')\ninformative_features(vectorizer, nb_model)\n\"\"\"\nThe left and right column shows keywords that contribute the most to predict as safe and toxic, respectively. Indeed some stopwords are a good predictor (his, will, an, by), so definitely we have to tailor which stopwords to be removed. Stopwords like \"the\" and \"of\" can still be removed, because they appeared in the list but does not contribute to the meaning itself (\"latter\" should suffice as a standalone token as it has the same meaning as \"the latter\").\n\"\"\"\npred_df = pd.DataFrame()\npred_df['true'] = y_test.astype(int)\npred_df['prob'] = y_prob_nb\nfp_indices = pred_df[(pred_df['true'] == 0) & (pred_df['prob'] >= 0.5)]['prob'].sort_values(ascending=False).index\ntp_indices = pred_df[(pred_df['true'] == 0) & (pred_df['prob'] < 0.5)]['prob'].index\ncomment_df.loc[fp_indices[:25]][['comment_text', 'target', 'toxicity_annotator_count']].sort_values(['target'])\n\"\"\"\nLooking at some examples of false positive, we can observe some comments that have arguable target value. I cannot understand why \"Effin moron\" and \"Crooked Jerk!\" are not considered toxic comments. Even a comment like \"You're a stone-cold MO-Ron.\" has a target value of 0. Those might suggest that we have to take extra measure in cleaning the dataset.\n\nWe can also see comments that have target value really close to the toxic threshold (0.5) have be rounded as \"safe\" comments questionably. \"Overpaid, childish, morons\" is definitely an insult, but still half of 71 annotators considered it to be safe. As the data is imbalanced, it is considerable to neglect comments with doubtful target value during training, maybe it is good to ignore comments that has value between 0.4 to 0.6.\n\nFinally, we can see the \"biased\" classification of a comment if we are using keyword-based modeling. As this competition suggested, using keywords only is not sufficient to predict toxic comments. Many safe comments are labelled as toxic due to the keywords, while it really depends on the context. \"There is no white supremacist in the White House.\" is an excellent example of a safe comment (target value = 0) that might be mis-classified due to 2 occurrences of \"white\" word. And we know that this is a difficult task when the model is only presented with a two-word comment \"Not clowns?\" and asked to determine whether it is toxic or not without any additional context when the word \"clown\" is used in other comments with a mixed sentiment. Hard, even for sequence-based models. Or is it?\n\"\"\"\n\"\"\"\n# 4. Lesson Learned\n\"\"\"\n\"\"\"\nThese are the key insights I have gathered from this EDA that should help during preprocessing and when building the actual model:\n1. We are dealing with imbalanced dataset (92% vs 8%). I do not see any public kernels talk about how to handle this issue (or if we **should** handle this issue).\n2. There is a correlation between the number of annotators and the toxicity value, which might suggest to take number of annotators into account during training. Not as feature, of course, because the test set does not provide the number of annotators. It can be useful as a sample-weighting method.\n3. The most popular toxic subtypes is insult, it dominates other subtypes. Even more intriguing, it has a (really) high correlation with target value, which bear a thought if the toxic definition in this dataset is actually \"insulting\".\n4. Identity attributes are not helpful to predict target value due to the low label availability and absence of correlation.\n5. There is a negligible difference in comment length, capital letters proportion, and alpha-numeric occurrence between toxic and safe comments. One can consider to do lowercase transformation and remove punctuations.\n6. Some measurement into preprocessing: Don't remove digits (rather, replace to a \"DIGIT\" token, for example). It is an indication of a safe comment. Also, not all stopwords should be removed.\n7. Some comments have a questionable target value, which means cleaning the (noisy) dataset is important before training the model. How to detect them? This is a subject for another kernel.\n8. Comments with target value in the edge of the threshold is not reliable, consider ignoring comments with target value too close to 0.5. Or better yet, train a separate model to identify this (Ensemble?).\n\"\"\"\n\"\"\"\n**FIN**: If you find anything wrong with my approach or something can be improved, kindly write in the comment below. All comments are welcome, but no toxic comments please ;)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2fe248e3208c31'}"}
{"id":"119310","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nprint(os.listdir(\"..\/input\/brent-oil-prices\"))\n\"\"\"\n# Input Data\n\"\"\"\ndf = pd.read_csv(\"..\/input\/brent-oil-prices\/BrentOilPrices.csv\")\ndf.head()\n\"\"\"\n# Data Preprocessing\n\"\"\"\n\"\"\"\n1) Need to convert Date column to standard format\n\"\"\"\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\ndf['Date'] = pd.to_datetime(df['Date'], format=\"%b %d, %Y\")\ndf.head()\n\"\"\"\n# Data Exploration\n\"\"\"\n\"\"\"\n**Visualizing Full Data as a line plot**\n\"\"\"\ng = sns.lineplot(x='Date',y='Price',data = df)\nplt.title(\"Brent Oil Price Trend\")\n\"\"\"\n**Function to plot Oil Price Trend between specific period**\n\"\"\"\ndef plot_price_trend(df, start_date, end_date):\n    \"\"\"\n    This function filters the dataframe for the specified date range and \n    plots the line plot of the data using seaborn.\n    \n    The dataframe may not be indexed on any Datetime column.\n    In this case, we use mask to filter out the date.\n    \n    PS - There is another function provided later in the notebook \n    which used indexed column to filter data\n    \"\"\"\n    mask = (df['Date'] > start_date) & (df['Date'] <= end_date)\n    sdf = df.loc[mask]\n    plt.figure(figsize = (10,5))\n    chart = sns.lineplot(x='Date',y='Price',data = sdf)\n#     chart.set_xticklabels(chart.get_xticklabels(), rotation=45)\n    plt.title(\"Brent Oil Price Trend\")\nplot_price_trend(df,'2017-01-01','2019-01-01')\n\"\"\"\n# Forecast Model\n\"\"\"\n\"\"\"\n# 1) Using Prophet\n\"\"\"\n\"\"\"\nStep 1) - First we import the Prophet class from fbprophet module and then create an instance of this.\n\"\"\"\nfrom fbprophet import Prophet\nm = Prophet()\n\"\"\"\nStep 2) - Note that Prophet requires the date column as 'ds' and outcome varible as 'y'.\nSo we change this in our dataframe and check its data.\n\"\"\"\npro_df = df\npro_df.columns = ['ds','y']\npro_df.head()\n\"\"\"\nStep 3) - Next we fit this dataframe into the model object created and then create a forecast for the Oil Price for the next 90 days. \n\nThis might take ~1mins\n\"\"\"\nm.fit(pro_df)\nfuture = m.make_future_dataframe(periods = 90)\nforecast = m.predict(future)\n\"\"\"\nStep 4) - We check the forecast data has several components - trend, weakly and yearly seasonality - and for each of these components, we have the lower and upper confidence intervals data.\n\"\"\"\nforecast.head()\n\"\"\"\nStep 5) - We plot these components of the forecast fit model.\n\"\"\"\nm.plot_components(forecast)\nm.plot(forecast)\n\"\"\"\nStep 6)- Next we want to visualize side by side the original data and the forecast data. So for this, we join the original and forecast data on the column 'ds'\n\"\"\"\ncmp_df = forecast.set_index('ds')[['yhat','yhat_lower','yhat_upper']].join(pro_df.set_index('ds'))\ncmp_df.head()\ncmp_df.tail(5)\n\"\"\"\nNote that the original y data is NaN towards the end because, these are the predicted dates.\n\"\"\"\n\"\"\"\nStep 7 - Then, we visualize the original and forecast data alongside each other\n\"\"\"\nplt.figure(figsize=(17,8))\n#plt.plot(cmp_df['yhat_lower'])\n#plt.plot(cmp_df['yhat_upper'])\nplt.plot(cmp_df['yhat'])\nplt.plot(cmp_df['y'])\nplt.legend()\nplt.show()\n\"\"\"\nStep 8) - From above graph, we are not able to readily see how many months data was forecast. \n\nSo, We need a function which will show us the original and forecast data between a specified date range.\n\"\"\"\ndef plot_price_forecast(df,start_date, end_date):\n    \"\"\"\n    This function filters the dataframe for the specified date range and \n    plots the actual and forecast data.\n    \n    Assumption: \n    - The dataframe has to be indexed on a Datetime column\n    This makes the filtering very easy in pandas using df.loc\n    \"\"\"\n    cmp_df = df.loc[start_date:end_date]\n    plt.figure(figsize=(17,8))\n    plt.plot(cmp_df['yhat'])\n    plt.plot(cmp_df['y'])\n    plt.legend()\n    plt.show()\n\"\"\"\nStpe 9) - Using this function, we can see that, the original graph (orange) does not have data towards the end. This data can be taken from the forecasted graph (blue). \n\"\"\"\nplot_price_forecast(cmp_df,'2017-01-01','2020-01-01')\n\"\"\"\n# 2) Using ARIMA\n\"\"\"\n\"\"\"\nStep 1) - First we import the required libraries\n\"\"\"\nfrom statsmodels.tsa.arima_model import ARIMA    # ARIMA Modeling\nfrom statsmodels.tsa.stattools import adfuller   # Augmented Dickey-Fuller Test for Checking Stationary\nfrom statsmodels.tsa.stattools import acf, pacf  # Finding ARIMA parameters using Autocorrelation\nfrom statsmodels.tsa.seasonal import seasonal_decompose # Decompose the ARIMA Forecast model\n\"\"\"\nStep 2) - Arima requires the date column to be set as index\n\"\"\"\narima_df = df.set_index('ds')\narima_df.head()\n\"\"\"\nStep 3) - Next we write a function that plots the Rolling mean and standard deviation and then checks the stationarity of the time series using Augmented Dickey - Fuller Test\n\nCredit - https:\/\/www.kaggle.com\/freespirit08\/time-series-for-beginners-with-arima\n\"\"\"\n# Perform Augmented Dickey\u2013Fuller test to check if the given Time series is stationary:\ndef test_stationarity(ts):\n    \n    #Determing rolling statistics\n    rolmean = ts.rolling(window=12).mean()\n    rolstd = ts.rolling(window=12).std()\n\n    #Plot rolling statistics:\n    orig = plt.plot(ts, color='blue',label='Original')\n    mean = plt.plot(rolmean, color='red', label='Rolling Mean')\n    std = plt.plot(rolstd, color='black', label = 'Rolling Std')\n    plt.legend(loc='best')\n    plt.title('Rolling Mean & Standard Deviation')\n    plt.show(block=False)\n    \n    #Perform Dickey-Fuller test:\n    print('Results of Dickey-Fuller Test:')\n    dftest = adfuller(ts['y'], autolag='AIC')\n    dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])\n    for key,value in dftest[4].items():\n        dfoutput['Critical Value (%s)'%key] = value\n    print(dfoutput)\n\"\"\"\nStep 4) - Next, we use this function to check if our given timeseries data is stationary or not\n\"\"\"\ntest_stationarity(arima_df)\n\"\"\"\nObservation - The null hypothesis of ADF test is the Time series is NOT stationary. We see that the Test Statistic (-1.95) is higher than 10% Critical Value (-2.56). This means this result is statistically significant at 90% confidence interval and so, we fail to reject the null hypothesis. \n\nThis means that our time series data is NOT stationary.\n\"\"\"\n\"\"\"\nStep 5) - Some definitions - \n\nCorrelation - Describes how much two variables depend on each other. \n\nPartial Correlation - When multiple variables are involved, two variables may have direct relation as well as indirect relation (i.e x1 and x3 are related and x2 and x3 are related. Due to this indirect relation, x1 and x2 might be related). This is called partial correlation.\n\nAuto Correlation - In a time series data, variable at a time step is dependent upon its lag values. This is called auto-correlation (i.e. variable depending upon its own values)\n\nPartial Autocorrelation - describes correlation of a variable with its lag values after removing the effect of indirect correlation.\n\n\n\"\"\"\nfrom statsmodels.graphics.tsaplots import plot_acf,plot_pacf\nplot_acf(arima_df)\nplot_pacf(arima_df)\n# Implementing own function to create ACF plot\ndef get_acf_plot(ts):\n    #calling acf function from stattools\n    y = ts['y']\n    lag_acf = acf(y, nlags=500)\n    plt.figure(figsize=(16, 7))\n    plt.plot(lag_acf, marker=\"o\")\n    plt.axhline(y=0,linestyle='--',color='gray')\n    plt.axhline(y=-1.96\/np.sqrt(len(y)),linestyle='--',color='gray')\n    plt.axhline(y=1.96\/np.sqrt(len(y)),linestyle='--',color='gray')\n    plt.title('Autocorrelation Function')\n    plt.xlabel('number of lags')\n    plt.ylabel('correlation')\n    \ndef get_pacf_plot(ts):\n    #calling pacf function from stattools\n    y = arima_df['y']\n    lag_pacf = pacf(y, nlags=50)\n    plt.figure(figsize=(16, 7))\n    plt.plot(lag_pacf, marker=\"o\")\n    plt.axhline(y=0,linestyle='--',color='gray')\n    plt.axhline(y=-1.96\/np.sqrt(len(y)),linestyle='--',color='gray')\n    plt.axhline(y=1.96\/np.sqrt(len(y)),linestyle='--',color='gray')\n    plt.title('Partial Autocorrelation Function')\n    plt.xlabel('number of lags')\n    plt.ylabel('correlation')\nget_acf_plot(arima_df)\nget_pacf_plot(arima_df)\n\"\"\"\nStep 6) - Next we see some methods to make the data stationary\n\"\"\"\n# Log Transformation\nts_log = np.log(arima_df)\nplt.plot(ts_log)\n# Moving Average of last 12 values\nmoving_avg = ts_log.rolling(12).mean()\nplt.plot(ts_log)\nplt.plot(moving_avg, color='red')\n# Differencing\nts_log_ma_diff = ts_log - moving_avg\nts_log_ma_diff.head(12)\nts_log_ma_diff.dropna(inplace=True)\ntest_stationarity(ts_log_ma_diff)\n# Exponentially weighted moving average \nexpwighted_avg = ts_log.ewm(halflife=12).mean()\n\nplt.plot(ts_log)\nplt.plot(expwighted_avg, color='red')\nts_log_ewma_diff = ts_log - expwighted_avg\ntest_stationarity(ts_log_ewma_diff)\n\"\"\"\nStep 8) - ARIMA models\n\"\"\"\nts_log_diff = ts_log - ts_log.shift()\nplt.plot(ts_log_diff)\nts_log_diff.dropna(inplace=True)\ntest_stationarity(ts_log_diff)\nfrom statsmodels.tsa.seasonal import seasonal_decompose\ndecomposition = seasonal_decompose(ts_log, freq = 30)\n\ntrend = decomposition.trend\nseasonal = decomposition.seasonal\nresidual = decomposition.resid\n\nplt.subplot(411)\nplt.plot(ts_log, label='Original')\nplt.legend(loc='best')\nplt.subplot(412)\nplt.plot(trend, label='Trend')\nplt.legend(loc='best')\nplt.subplot(413)\nplt.plot(seasonal,label='Seasonality')\nplt.legend(loc='best')\nplt.subplot(414)\nplt.plot(residual, label='Residuals')\nplt.legend(loc='best')\nplt.tight_layout()\nts_log_decompose = residual\nts_log_decompose.dropna(inplace=True)\ntest_stationarity(ts_log_decompose)\nmodel = ARIMA(ts_log, order=(2, 1, 2))  \nresults_ARIMA = model.fit(disp=-1)  \nplt.plot(ts_log_diff)\nplt.plot(results_ARIMA.fittedvalues, color='red')\n# plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))\n\"\"\"\n# 3) Using LSTM\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'db7b3799aa62b9'}"}
{"id":"15209","text":"\"\"\"\nCreates a EfficientNetV2 Model as defined in:\nMingxing Tan, Quoc V. Le. (2021). \nEfficientNetV2: Smaller Models and Faster Training\narXiv preprint arXiv:2104.00298.\nimport from https:\/\/github.com\/d-li14\/mobilenetv2.pytorch\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport math\n\n__all__ = ['effnetv2_s', 'effnetv2_m', 'effnetv2_l', 'effnetv2_xl']\n\n\ndef _make_divisible(v, divisor, min_value=None):\n    \"\"\"\n    This function is taken from the original tf repo.\n    It ensures that all layers have a channel number that is divisible by 8\n    It can be seen here:\n    https:\/\/github.com\/tensorflow\/models\/blob\/master\/research\/slim\/nets\/mobilenet\/mobilenet.py\n    :param v:\n    :param divisor:\n    :param min_value:\n    :return:\n    \"\"\"\n    if min_value is None:\n        min_value = divisor\n    new_v = max(min_value, int(v + divisor \/ 2) \/\/ divisor * divisor)\n    # Make sure that round down does not go down by more than 10%.\n    if new_v < 0.9 * v:\n        new_v += divisor\n    return new_v\n\n\n# SiLU (Swish) activation function\nif hasattr(nn, 'SiLU'):\n    SiLU = nn.SiLU\nelse:\n    # For compatibility with old PyTorch versions\n    class SiLU(nn.Module):\n        def forward(self, x):\n            return x * torch.sigmoid(x)\n\nclass SELayer(nn.Module):\n    def __init__(self, inp, oup, reduction=4):\n        super(SELayer, self).__init__()\n        self.avg_pool = nn.AdaptiveAvgPool2d(1)\n        self.fc = nn.Sequential(\n                nn.Linear(oup, _make_divisible(inp \/\/ reduction, 8)),\n                SiLU(),\n                nn.Linear(_make_divisible(inp \/\/ reduction, 8), oup),\n                nn.Sigmoid()\n        )\n\n    def forward(self, x):\n        b, c, _, _ = x.size()\n        y = self.avg_pool(x).view(b, c)\n        y = self.fc(y).view(b, c, 1, 1)\n        return x * y\n\n\ndef conv_3x3_bn(inp, oup, stride):\n    return nn.Sequential(\n        nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n        nn.BatchNorm2d(oup),\n        SiLU()\n    )\n\n\ndef conv_1x1_bn(inp, oup):\n    return nn.Sequential(\n        nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n        nn.BatchNorm2d(oup),\n        SiLU()\n    )\n\n\nclass MBConv(nn.Module):\n    def __init__(self, inp, oup, stride, expand_ratio, use_se):\n        super(MBConv, self).__init__()\n        assert stride in [1, 2]\n\n        hidden_dim = round(inp * expand_ratio)\n        self.identity = stride == 1 and inp == oup\n        if use_se:\n            self.conv = nn.Sequential(\n                # pw\n                nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),\n                nn.BatchNorm2d(hidden_dim),\n                SiLU(),\n                # dw\n                nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n                nn.BatchNorm2d(hidden_dim),\n                SiLU(),\n                SELayer(inp, hidden_dim),\n                # pw-linear\n                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n                nn.BatchNorm2d(oup),\n            )\n        else:\n            self.conv = nn.Sequential(\n                # fused\n                nn.Conv2d(inp, hidden_dim, 3, stride, 1, bias=False),\n                nn.BatchNorm2d(hidden_dim),\n                SiLU(),\n                # pw-linear\n                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n                nn.BatchNorm2d(oup),\n            )\n\n\n    def forward(self, x):\n        if self.identity:\n            return x + self.conv(x)\n        else:\n            return self.conv(x)\n\n\nclass EffNetV2(nn.Module):\n    def __init__(self, cfgs, num_classes=1000, width_mult=1.):\n        super(EffNetV2, self).__init__()\n        self.cfgs = cfgs\n\n        # building first layer\n        input_channel = _make_divisible(24 * width_mult, 8)\n        layers = [conv_3x3_bn(3, input_channel, 2)]\n        # building inverted residual blocks\n        block = MBConv\n        for t, c, n, s, use_se in self.cfgs:\n            output_channel = _make_divisible(c * width_mult, 8)\n            for i in range(n):\n                layers.append(block(input_channel, output_channel, s if i == 0 else 1, t, use_se))\n                input_channel = output_channel\n        self.features = nn.Sequential(*layers)\n        # building last several layers\n        output_channel = _make_divisible(1792 * width_mult, 8) if width_mult > 1.0 else 1792\n        self.conv = conv_1x1_bn(input_channel, output_channel)\n        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n        self.classifier = nn.Linear(output_channel, num_classes)\n\n        self._initialize_weights()\n\n    def forward(self, x):\n        x = self.features(x)\n        x = self.conv(x)\n        x = self.avgpool(x)\n        x = x.view(x.size(0), -1)\n        x = self.classifier(x)\n        return x\n\n    def _initialize_weights(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n                m.weight.data.normal_(0, math.sqrt(2. \/ n))\n                if m.bias is not None:\n                    m.bias.data.zero_()\n            elif isinstance(m, nn.BatchNorm2d):\n                m.weight.data.fill_(1)\n                m.bias.data.zero_()\n            elif isinstance(m, nn.Linear):\n                m.weight.data.normal_(0, 0.001)\n                m.bias.data.zero_()\n\n\ndef effnetv2_s(**kwargs):\n    \"\"\"\n    Constructs a EfficientNetV2-S model\n    \"\"\"\n    cfgs = [\n        # t, c, n, s, SE\n        [1,  24,  2, 1, 0],\n        [4,  48,  4, 2, 0],\n        [4,  64,  4, 2, 0],\n        [4, 128,  6, 2, 1],\n        [6, 160,  9, 1, 1],\n        [6, 256, 15, 2, 1],\n    ]\n    return EffNetV2(cfgs, **kwargs)\n\n\ndef effnetv2_m(**kwargs):\n    \"\"\"\n    Constructs a EfficientNetV2-M model\n    \"\"\"\n    cfgs = [\n        # t, c, n, s, SE\n        [1,  24,  3, 1, 0],\n        [4,  48,  5, 2, 0],\n        [4,  80,  5, 2, 0],\n        [4, 160,  7, 2, 1],\n        [6, 176, 14, 1, 1],\n        [6, 304, 18, 2, 1],\n        [6, 512,  5, 1, 1],\n    ]\n    return EffNetV2(cfgs, **kwargs)\n\n\ndef effnetv2_l(**kwargs):\n    \"\"\"\n    Constructs a EfficientNetV2-L model\n    \"\"\"\n    cfgs = [\n        # t, c, n, s, SE\n        [1,  32,  4, 1, 0],\n        [4,  64,  7, 2, 0],\n        [4,  96,  7, 2, 0],\n        [4, 192, 10, 2, 1],\n        [6, 224, 19, 1, 1],\n        [6, 384, 25, 2, 1],\n        [6, 640,  7, 1, 1],\n    ]\n    return EffNetV2(cfgs, **kwargs)\n\n\ndef effnetv2_xl(**kwargs):\n    \"\"\"\n    Constructs a EfficientNetV2-XL model\n    \"\"\"\n    cfgs = [\n        # t, c, n, s, SE\n        [1,  32,  4, 1, 0],\n        [4,  64,  8, 2, 0],\n        [4,  96,  8, 2, 0],\n        [4, 192, 16, 2, 1],\n        [6, 256, 24, 1, 1],\n        [6, 512, 32, 2, 1],\n        [6, 640,  8, 1, 1],\n    ]\n    return EffNetV2(cfgs, **kwargs)\nimport os\nimport json\nimport glob\nimport random\nimport collections\n\nimport numpy as np\nimport pandas as pd\nimport pydicom as dicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sys \n\nimport time\n\nimport torch\nfrom torch import nn\nfrom torch.utils import data as torch_data\nfrom sklearn import model_selection as sk_model_selection\nfrom torch.nn import functional as torch_functional\n\n#from sklearn.model_selection import StratifiedKFold\n\"\"\"\n## Support Function\n\"\"\"\ndef load_dicom(path):\n    image = dicom.read_file(path)\n    data = image.pixel_array\n    data = data - np.min(data)\n    if(np.max(data) != 0):\n        data = data\/np.max(data)\n    data = (data *256).astype(np.uint8)\n    data = cv2.resize(data, (256, 256))\n    data = cv2.cvtColor(data,cv2.COLOR_GRAY2RGB)\n    return data\ndef is_valid_image(path, threshold=32768):\n    data = load_dicom(path)\n    if (np.count_nonzero(data) > threshold):\n        return True\n    else:\n        return False\ndef set_seed(seed):\n    random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n        torch.backends.cudnn.deterministic = True\n\nset_seed(42)\n\"\"\"\n## Visualize on labels\n\"\"\"\nclass DataCustomer(torch_data.Dataset):\n    def __init__(self, paths, labels):\n        self.paths = paths\n        self.labels = labels\n    def __len__(self):\n        return len(self.labels)\n    def __getitem__(self, index):\n        data_path = self.paths[index]\n        data = load_dicom(data_path)\n        data = torch.tensor(data).float()\n        \n        data = torch.reshape(data, (3,256,256))\n        Y = torch.tensor(self.labels[index]).float()\n        return {\"X\":data, \"y\":Y}\nclass LossMeter:\n    def __init__(self):\n        self.avg = 0\n        self.n = 0\n\n    def update(self, val):\n        self.n += 1\n        # incremental update\n        self.avg = val \/ self.n + (self.n - 1) \/ self.n * self.avg\n\n        \nclass AccMeter:\n    def __init__(self):\n        self.avg = 0\n        self.n = 0\n        \n    def update(self, y_true, y_pred):\n        y_true = y_true.cpu().numpy().astype(int)\n        y_pred = y_pred.cpu().numpy() >= 0\n        last_n = self.n\n        self.n += len(y_true)\n        true_count = np.sum(y_true == y_pred)\n        # incremental update\n        self.avg = true_count \/ self.n + last_n \/ self.n * self.avg\nclass Trainer:\n    def __init__(\n        self, \n        model, \n        device, \n        optimizer, \n        criterion, \n        loss_meter, \n        score_meter\n    ):\n        self.model = model\n        self.device = device\n        self.optimizer = optimizer\n        self.criterion = criterion\n        self.loss_meter = loss_meter\n        self.score_meter = score_meter\n        \n        self.best_valid_score = -np.inf\n        self.n_patience = 0\n        \n        self.messages = {\n            \"epoch\": \"[Epoch {}: {}] loss: {:.5f}, score: {:.5f}, time: {} s\",\n            \"checkpoint\": \"The score improved from {:.5f} to {:.5f}. Save model to '{}'\",\n            \"patience\": \"\\nValid score didn't improve last {} epochs.\"\n        }\n    \n    def fit(self, epochs, train_loader, valid_loader, save_path, patience):        \n        for n_epoch in range(1, epochs + 1):\n            self.info_message(\"EPOCH: {}\", n_epoch)\n            \n            train_loss, train_score, train_time = self.train_epoch(train_loader)\n            valid_loss, valid_score, valid_time = self.valid_epoch(valid_loader)\n            \n            self.info_message(\n                self.messages[\"epoch\"], \"Train\", n_epoch, train_loss, train_score, train_time\n            )\n            \n            self.info_message(\n                self.messages[\"epoch\"], \"Valid\", n_epoch, valid_loss, valid_score, valid_time\n            )\n\n            if True:\n#             if self.best_valid_score < valid_score:\n                self.info_message(\n                    self.messages[\"checkpoint\"], self.best_valid_score, valid_score, save_path\n                )\n                self.best_valid_score = valid_score\n                self.save_model(n_epoch, save_path)\n                self.n_patience = 0\n            else:\n                self.n_patience += 1\n            \n            if self.n_patience >= patience:\n                self.info_message(self.messages[\"patience\"], patience)\n                break\n            \n    def train_epoch(self, train_loader):\n        self.model.train()\n        t = time.time()\n        train_loss = self.loss_meter()\n        train_score = self.score_meter()\n        \n        for step, batch in enumerate(train_loader, 1):\n            X = batch[\"X\"].to(self.device)\n            targets = batch[\"y\"].to(self.device)\n            self.optimizer.zero_grad()\n            outputs = torch.sigmoid(self.model(X)).squeeze(1)\n            \n            loss = self.criterion(outputs, targets)\n            loss.backward()\n\n            train_loss.update(loss.detach().item())\n            train_score.update(targets, outputs.detach())\n\n            self.optimizer.step()\n            \n            _loss, _score = train_loss.avg, train_score.avg\n            message = 'Train Step {}\/{}, train_loss: {:.5f}, train_score: {:.5f}'\n            self.info_message(message, step, len(train_loader), _loss, _score, end=\"\\r\")\n        \n        return train_loss.avg, train_score.avg, int(time.time() - t)\n    \n    def valid_epoch(self, valid_loader):\n        self.model.eval()\n        t = time.time()\n        valid_loss = self.loss_meter()\n        valid_score = self.score_meter()\n\n        for step, batch in enumerate(valid_loader, 1):\n            with torch.no_grad():\n                X = batch[\"X\"].to(self.device)\n                targets = batch[\"y\"].to(self.device)\n                \n                #torch.sigmoid(model(batch[\"X\"].to(device)))\n                \n                outputs = torch.sigmoid(self.model(X)).squeeze(1)\n                loss = self.criterion(outputs, targets)\n\n                valid_loss.update(loss.detach().item())\n                valid_score.update(targets, outputs)\n                \n            _loss, _score = valid_loss.avg, valid_score.avg\n            message = 'Valid Step {}\/{}, valid_loss: {:.5f}, valid_score: {:.5f}'\n            self.info_message(message, step, len(valid_loader), _loss, _score, end=\"\\r\")\n        \n        return valid_loss.avg, valid_score.avg, int(time.time() - t)\n    \n    def save_model(self, n_epoch, save_path):\n        torch.save(\n            {\n                \"model_state_dict\": self.model.state_dict(),\n                \"optimizer_state_dict\": self.optimizer.state_dict(),\n                \"best_valid_score\": self.best_valid_score,\n                \"n_epoch\": n_epoch,\n            },\n            save_path,\n        )\n    \n    @staticmethod\n    def info_message(message, *args, end=\"\\n\"):\n        print(message.format(*args), end=end)\ndf = pd.read_csv(\"..\/input\/dfdxinnhathemattroi\/filetrainxin.csv\", index_col = False)\n\nindx = df['patient_id'].unique()\nindx_train, indx_val = sk_model_selection.train_test_split(\n    indx,\n    test_size = 0.2,\n    random_state = 42,\n)\ndf_train = df[df['patient_id'].isin(indx_train)]\ndf_valid = df[df['patient_id'].isin(indx_val)]\ndisplay(len(df_train['patient_id'].unique()))\ndisplay(len(df_valid['patient_id'].unique()))\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# #device = \"cpu\"\n\n\n# train_data_retriever = DataCustomer(\n#     df_train[\"file_paths\"].values, \n#     df_train[\"label\"].values, \n# )\n\n# valid_data_retriever = DataCustomer(\n#     df_valid[\"file_paths\"].values, \n#     df_valid[\"label\"].values,\n# )\n\n# train_loader = torch_data.DataLoader(\n#     train_data_retriever,\n#     batch_size=64,\n#     shuffle=True,\n#     num_workers=8,\n# )\n\n# valid_loader = torch_data.DataLoader(\n#     valid_data_retriever, \n#     batch_size=64,\n#     shuffle=False,\n#     num_workers=8,\n# )\n\n# model = effnetv2_s(num_classes = 1)\n# model.to(device)\n\n# checkpoint = torch.load(\"..\/input\/v336epoch\/best-modelv3.pth\")\n# model.load_state_dict(checkpoint[\"model_state_dict\"])\n\n# optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n# criterion = torch_functional.binary_cross_entropy_with_logits\n\n# trainer = Trainer(\n#     model, \n#     device, \n#     optimizer, \n#     criterion, \n#     LossMeter, \n#     AccMeter\n# )\n\n# history = trainer.fit(\n#     7, \n#     train_loader, \n#     valid_loader, \n#     \"best-modelv4.pth\", \n#     100,\n# )\n\"\"\"\n# FILTER TESTDATA WITH THRESHOLD = 10 AND ONLY USE T2w SCAN TYPE\n\"\"\"\nsample_df = pd.read_csv('..\/input\/dfdxinnhathemattroi\/filetestxin.csv', index_col = False)\nsample_df.shape\ntmp = sample_df.paths.values\ntmp[0]\nIMG_PATH_TEST = \"..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/test\"\nf = []\nfor (dirpath, dirnames, filenames) in os.walk(IMG_PATH_TEST):\n    f.extend(os.path.join(dirpath, x) for x in filenames)\n    \ntest_file_paths_df = pd.DataFrame({'file_paths': f})\ntest_file_paths_df['directory'] = IMG_PATH_TEST\ntest_file_paths_df['dataset'] = test_file_paths_df['file_paths'].str.split(\"\/\", n = 7, expand = True)[3]\ntest_file_paths_df['patient_id'] = test_file_paths_df['file_paths'].str.split(\"\/\", n = 7, expand = True)[4]\ntest_file_paths_df['scan_type'] = test_file_paths_df['file_paths'].str.split(\"\/\", n = 7, expand = True)[5]\ntest_file_paths_df['file'] = test_file_paths_df['file_paths'].str.split(\"\/\", n = 7, expand = True)[6]\ndisplay(test_file_paths_df.head(2))\ntest_file_paths_df.shape[0]\ntest_df=test_file_paths_df[test_file_paths_df['file_paths'].isin(tmp)]\ndisplay(test_df.shape)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodels = []\nfor i in range(1):\n    model = effnetv2_s(num_classes = 1)\n    model.to(device)\n    \n    checkpoint = torch.load(\"..\/input\/v557epoch\/v5-57epoch.pth\",map_location=torch.device('cpu'))\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n    model.eval()\n    \n    models.append(model)\n_id = test_df['patient_id'].map(int).tolist()\nclass TestDataCustomer(torch_data.Dataset):\n    def __init__(self, paths):\n        self.paths = paths\n        \n    def __len__(self):\n        return len(self.paths)\n    \n    def __getitem__(self, index):\n        data_path = self.paths[index]\n        data = load_dicom(data_path)\n        \n        data = torch.tensor(data).float()\n        data = torch.reshape(data, (3,256,256))\n        \n        return {\"X\": data, \"id\": _id[index]}\nsubmission = pd.read_csv(\"..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/sample_submission.csv\")\n\ntest_data_retriever = TestDataCustomer( \n    test_df['file_paths'].values,\n)\n\ntest_loader = torch_data.DataLoader(\n    test_data_retriever,\n    batch_size=64,\n    shuffle=False,\n    num_workers=8,\n)\ny_pred = []\nids = []\n\nfor e, batch in enumerate(test_loader):\n    print(f\"{e}\/{len(test_loader)}\", end=\"\\r\")\n    with torch.no_grad():\n        tmp_pred = np.zeros((batch[\"X\"].shape[0], ))\n        for model in models:\n            tmp_res = torch.sigmoid(model(batch[\"X\"].to(device))).cpu().numpy().squeeze()\n            tmp_pred += tmp_res\n        y_pred.extend(tmp_pred)\n        ids.extend(batch[\"id\"].numpy().tolist())\nsubmission = pd.DataFrame({\"BraTS21ID\": ids, \"MGMT_value\": y_pred})\nsubmission = submission.groupby(['BraTS21ID'], as_index = False).median()\nsubmission.to_csv(\"submission.csv\",float_format='{:.1f}'.format, encoding='utf-8', index=False)\nsubmission\nplt.figure(figsize=(5, 5))\nplt.hist(submission[\"MGMT_value\"]);\n\"\"\"\n## WORK IN PROGRESS...\n\"\"\"\n# # def is_valid_image(path, threshold=10):\n# #     data = load_dicom(path)\n# #     if np.mean(data)<threshold:\n# #         return False\n# #     else:\n# #         return True\n\n\n# def change_path(path):\n#     path = path.replace(\"rsna-miccai-png\",\"rsna-miccai-brain-tumor-radiogenomic-classification\")\n#     path = path.replace(\".png\", \".dcm\")\n#     return path","meta":"{'source': 'AI4Code', 'id': '1bc88d970e55f1'}"}
{"id":"57943","text":"\"\"\"\n# Amazon Fine Food Reviews Analysis\n\n\nData Source: https:\/\/www.kaggle.com\/snap\/amazon-fine-food-reviews <br>\n\nEDA: https:\/\/nycdatascience.com\/blog\/student-works\/amazon-fine-foods-visualization\/\n\n\nThe Amazon Fine Food Reviews dataset consists of reviews of fine foods from Amazon.<br>\n\nNumber of reviews: 568,454<br>\nNumber of users: 256,059<br>\nNumber of products: 74,258<br>\nTimespan: Oct 1999 - Oct 2012<br>\nNumber of Attributes\/Columns in data: 10 \n\nAttribute Information:\n\n1. Id\n2. ProductId - unique identifier for the product\n3. UserId - unqiue identifier for the user\n4. ProfileName\n5. HelpfulnessNumerator - number of users who found the review helpful\n6. HelpfulnessDenominator - number of users who indicated whether they found the review helpful or not\n7. Score - rating between 1 and 5\n8. Time - timestamp for the review\n9. Summary - brief summary of the review\n10. Text - text of the review\n\n\n#### Objective:\nGiven a review, determine whether the review is positive (Rating of 4 or 5) or negative (rating of 1 or 2).\n\n<br>\n[Q] How to determine if a review is positive or negative?<br>\n<br> \n[Ans] We could use the Score\/Rating. A rating of 4 or 5 could be cosnidered a positive review. A review of 1 or 2 could be considered negative. A review of 3 is nuetral and ignored. This is an approximate and proxy way of determining the polarity (positivity\/negativity) of a review.\n\n\n\n\"\"\"\n\"\"\"\n## Loading the data\n\nThe dataset is available in two forms\n1. .csv file\n2. SQLite Database\n\nIn order to load the data, We have used the SQLITE dataset as it easier to query the data and visualise the data efficiently.\n<br> \n\nHere as we only want to get the global sentiment of the recommendations (positive or negative), we will purposefully ignore all Scores equal to 3. If the score id above 3, then the recommendation wil be set to \"positive\". Otherwise, it will be set to \"negative\".\n\"\"\"\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\nimport sqlite3\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport string\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve, auc\nfrom nltk.stem.porter import PorterStemmer\n\nimport re\n# Tutorial about Python regular expressions: https:\/\/pymotw.com\/2\/re\/\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\nfrom gensim.models import Word2Vec\nfrom gensim.models import KeyedVectors\nimport pickle\n\nfrom tqdm import tqdm\nimport os\n\"\"\"\n# [1]. Reading Data\n\"\"\"\nos.listdir()\ncon = sqlite3.connect('..\/input\/database.sqlite')\n#filtering only positive and negative reviews i.e. \n# not taking into consideration those reviews with Score=3\n# SELECT * FROM Reviews WHERE Score != 3 LIMIT 500000, will give top 500000 data points\n# you can change the number to any other number based on your computing power\n\n# filtered_data = pd.read_sql_query(\"\"\" SELECT * FROM Reviews WHERE Score != 3 LIMIT 500000\"\"\", con) \n# for tsne assignment you can take 5k data points\n\nfiltered_data = pd.read_sql_query(\"\"\" SELECT * FROM Reviews WHERE Score != 3 LIMIT 5000\"\"\", con) \n# Give reviews with Score>3 a positive rating, and reviews with a score<3 a negative rating.\ndef partition(x):\n    if x < 3:\n        return 0\n    return 1\n#changing reviews with score less than 3 to be positive and vice-versa\nactualScore = filtered_data['Score']\npositiveNegative = actualScore.map(partition) \nfiltered_data['Score'] = positiveNegative\nprint(\"Number of data points in our data\", filtered_data.shape)\nfiltered_data.head(3)\ndisplay = pd.read_sql_query(\"\"\"\nSELECT UserId, ProductId, ProfileName, Time, Score, Text, COUNT(*)\nFROM Reviews\nGROUP BY UserId\nHAVING COUNT(*)>1\n\"\"\", con)\nprint(display.shape)\ndisplay.head()\ndisplay[display['UserId']=='AZY10LLTJ71NX']\ndisplay['COUNT(*)'].sum()\n\"\"\"\n#  Exploratory Data Analysis\n\n## [2] Data Cleaning: Deduplication\n\nIt is observed (as shown in the table below) that the reviews data had many duplicate entries. Hence it was necessary to remove duplicates in order to get unbiased results for the analysis of the data.  Following is an example:\n\"\"\"\ndisplay= pd.read_sql_query(\"\"\"\nSELECT *\nFROM Reviews\nWHERE Score != 3 AND UserId=\"AR5J8UI46CURR\"\nORDER BY ProductID\n\"\"\", con)\ndisplay.head()\n\"\"\"\nAs can be seen above the same user has multiple reviews of the with the same values for HelpfulnessNumerator, HelpfulnessDenominator, Score, Time, Summary and Text  and on doing analysis it was found that <br>\n<br> \nProductId=B000HDOPZG was Loacker Quadratini Vanilla Wafer Cookies, 8.82-Ounce Packages (Pack of 8)<br>\n<br> \nProductId=B000HDL1RQ was Loacker Quadratini Lemon Wafer Cookies, 8.82-Ounce Packages (Pack of 8) and so on<br>\n\nIt was inferred after analysis that reviews with same parameters other than ProductId belonged to the same product just having different flavour or quantity. Hence in order to reduce redundancy it was decided to eliminate the rows having same parameters.<br>\n\nThe method used for the same was that we first sort the data according to ProductId and then just keep the first similar product review and delelte the others. for eg. in the above just the review for ProductId=B000HDL1RQ remains. This method ensures that there is only one representative for each product and deduplication without sorting would lead to possibility of different representatives still existing for the same product.\n\"\"\"\n#Sorting data according to ProductId in ascending order\nsorted_data=filtered_data.sort_values('ProductId', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')\n#Deduplication of entries\nfinal=sorted_data.drop_duplicates(subset={\"UserId\",\"ProfileName\",\"Time\",\"Text\"}, keep='first', inplace=False)\nfinal.shape\n#Checking to see how much % of data still remains\n(final['Id'].size*1.0)\/(filtered_data['Id'].size*1.0)*100\n\"\"\"\n<b>Observation:-<\/b> It was also seen that in two rows given below the value of HelpfulnessNumerator is greater than HelpfulnessDenominator which is not practically possible hence these two rows too are removed from calcualtions\n\"\"\"\ndisplay= pd.read_sql_query(\"\"\"\nSELECT *\nFROM Reviews\nWHERE Score != 3 AND Id=44737 OR Id=64422\nORDER BY ProductID\n\"\"\", con)\n\ndisplay.head()\nfinal=final[final.HelpfulnessNumerator<=final.HelpfulnessDenominator]\n#Before starting the next phase of preprocessing lets see the number of entries left\nprint(final.shape)\n\n#How many positive and negative reviews are present in our dataset?\nfinal['Score'].value_counts()\n# Code referred from https:\/\/stackoverflow.com\/questions\/31749448\/how-to-add-percentages-on-top-of-bars-in-seaborn\nax = final['Score'].value_counts().plot(kind='bar', \n                                         fontsize=13);\nax.set_alpha(0.8)\nax.set_title(\"Score class distribution\", fontsize=18)\nax.set_ylabel(\"Count\", fontsize=18);\n#ax.set_yticks([0, 5, 10, 15, 20])\nax.set_xticklabels(['Positive','Negative'], rotation=0, fontsize=11)\n\n# create a list to collect the plt.patches data\ntotals = []\n\n# find the values and append to list\nfor i in ax.patches:\n    totals.append(i.get_height())\n\n# set individual bar lables using above list\ntotal = sum(totals)\n\n# set individual bar lables using above list\nfor i in ax.patches:\n    # get_x pulls left or right; get_height pushes up or down\n    #ax.text(i.get_x()-.03, i.get_height()+.5, \\\n     #       str(round((i.get_height()\/total)*100, 2))+'%', fontsize=15,\n      #          color='dimgrey')\n      # Decreasing the i.get_x()+.12 will shift the text to left side and decreasing the i.get_height()-14 will bring the text down\n    ax.text(i.get_x()+.04, i.get_height()-350, \\\n            str(round((i.get_height()\/total)*100, 2))+'%', fontsize=20,\n                color='white')\n\"\"\"\n**Observations:** It is evident that the data points that we have selected contains 84% of positive score and 16% of negative score.\n\"\"\"\n\"\"\"\n# [3].  Text Preprocessing.\n\nNow that we have finished deduplication our data requires some preprocessing before we go on further with analysis and making the prediction model.\n\nHence in the Preprocessing phase we do the following in the order below:-\n\n1. Begin by removing the html tags\n2. Remove any punctuations or limited set of special characters like , or . or # etc.\n3. Check if the word is made up of english letters and is not alpha-numeric\n4. Check to see if the length of the word is greater than 2 (as it was researched that there is no adjective in 2-letters)\n5. Convert the word to lowercase\n6. Remove Stopwords\n7. Finally Snowball Stemming the word (it was obsereved to be better than Porter Stemming)<br>\n\nAfter which we collect the words used to describe positive and negative reviews\n\"\"\"\n# printing some random reviews\nsent_0 = final['Text'].values[0]\nprint(sent_0)\nprint(\"=\"*50)\n\nsent_1000 = final['Text'].values[1000]\nprint(sent_1000)\nprint(\"=\"*50)\n\nsent_1500 = final['Text'].values[1500]\nprint(sent_1500)\nprint(\"=\"*50)\n\nsent_4900 = final['Text'].values[4900]\nprint(sent_4900)\nprint(\"=\"*50)\n# remove urls from text python: https:\/\/stackoverflow.com\/a\/40823105\/4084039\nsent_0 = re.sub(r\"http\\S+\", \"\", sent_0)\nsent_1000 = re.sub(r\"http\\S+\", \"\", sent_1000)\nsent_150 = re.sub(r\"http\\S+\", \"\", sent_1500)\nsent_4900 = re.sub(r\"http\\S+\", \"\", sent_4900)\n\nprint(sent_0)\n# https:\/\/stackoverflow.com\/questions\/16206380\/python-beautifulsoup-how-to-remove-all-tags-from-an-element\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(sent_0, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_1000, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_1500, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_4900, 'lxml')\ntext = soup.get_text()\nprint(text)\n# https:\/\/stackoverflow.com\/a\/47091490\/4084039\nimport re\n\ndef decontracted(phrase):\n    # specific\n    phrase = re.sub(r\"won't\", \"will not\", phrase)\n    phrase = re.sub(r\"can\\'t\", \"can not\", phrase)\n\n    # general\n    phrase = re.sub(r\"n\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'re\", \" are\", phrase)\n    phrase = re.sub(r\"\\'s\", \" is\", phrase)\n    phrase = re.sub(r\"\\'d\", \" would\", phrase)\n    phrase = re.sub(r\"\\'ll\", \" will\", phrase)\n    phrase = re.sub(r\"\\'t\", \" not\", phrase)\n    phrase = re.sub(r\"\\'ve\", \" have\", phrase)\n    phrase = re.sub(r\"\\'m\", \" am\", phrase)\n    return phrase\nsent_1500 = decontracted(sent_1500)\nprint(sent_1500)\nprint(\"=\"*50)\n#remove words with numbers python: https:\/\/stackoverflow.com\/a\/18082370\/4084039\nsent_0 = re.sub(\"\\S*\\d\\S*\", \"\", sent_0).strip()\nprint(sent_0)\n#remove spacial character: https:\/\/stackoverflow.com\/a\/5843547\/4084039\nsent_1500 = re.sub('[^A-Za-z0-9]+', ' ', sent_1500)\nprint(sent_1500)\n# https:\/\/gist.github.com\/sebleier\/554280\n# we are removing the words from the stop words list: 'no', 'nor', 'not'\n# <br \/><br \/> ==> after the above steps, we are getting \"br br\"\n# we are including them into stop words list\n# instead of <br \/> if we have <br\/> these tags would have revmoved in the 1st step\n\nstopwords= set(['br', 'the', 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \"you're\", \"you've\",\\\n            \"you'll\", \"you'd\", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \\\n            'she', \"she's\", 'her', 'hers', 'herself', 'it', \"it's\", 'its', 'itself', 'they', 'them', 'their',\\\n            'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', \"that'll\", 'these', 'those', \\\n            'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \\\n            'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \\\n            'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\\\n            'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\\\n            'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\\\n            'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \\\n            's', 't', 'can', 'will', 'just', 'don', \"don't\", 'should', \"should've\", 'now', 'd', 'll', 'm', 'o', 're', \\\n            've', 'y', 'ain', 'aren', \"aren't\", 'couldn', \"couldn't\", 'didn', \"didn't\", 'doesn', \"doesn't\", 'hadn',\\\n            \"hadn't\", 'hasn', \"hasn't\", 'haven', \"haven't\", 'isn', \"isn't\", 'ma', 'mightn', \"mightn't\", 'mustn',\\\n            \"mustn't\", 'needn', \"needn't\", 'shan', \"shan't\", 'shouldn', \"shouldn't\", 'wasn', \"wasn't\", 'weren', \"weren't\", \\\n            'won', \"won't\", 'wouldn', \"wouldn't\"])\n# Combining all the above stundents \nfrom tqdm import tqdm\npreprocessed_reviews = []\n# tqdm is for printing the status bar\nfor sentance in tqdm(final['Text'].values):\n    sentance = re.sub(r\"http\\S+\", \"\", sentance)\n    sentance = BeautifulSoup(sentance, 'lxml').get_text()\n    sentance = decontracted(sentance)\n    sentance = re.sub(\"\\S*\\d\\S*\", \"\", sentance).strip()\n    sentance = re.sub('[^A-Za-z]+', ' ', sentance)\n    # https:\/\/gist.github.com\/sebleier\/554280\n    sentance = ' '.join(e.lower() for e in sentance.split() if e.lower() not in stopwords)\n    preprocessed_reviews.append(sentance.strip())\npreprocessed_reviews[1500]\n\"\"\"\n<h2><font color='red'>[3.2] Preprocess Summary<\/font><\/h2>\n\"\"\"\n## Similartly you can do preprocessing for review summary also.\n# Combining all the above stundents \nfrom tqdm import tqdm\npreprocessed_summary = []\n# tqdm is for printing the status bar\nfor sentence in tqdm(final['Summary'].values):\n    sentence = re.sub(r\"http\\S+\", \"\", sentence)\n    sentence = BeautifulSoup(sentence, 'lxml').get_text()\n    sentence = decontracted(sentence)\n    sentence = re.sub(\"\\S*\\d\\S*\", \"\", sentence).strip()\n    sentence = re.sub('[^A-Za-z]+', ' ', sentence)\n    # https:\/\/gist.github.com\/sebleier\/554280\n    sentence = ' '.join(e.lower() for e in sentence.split() if e.lower() not in stopwords)\n    preprocessed_summary.append(sentence.strip())\npreprocessed_summary[150]\n\"\"\"\n# [4] Featurization\n\"\"\"\n\"\"\"\n## [4.1] BAG OF WORDS\n\"\"\"\n#BoW\ncount_vect = CountVectorizer() #in scikit-learn\ncount_vect.fit(preprocessed_reviews)\nprint(\"some feature names \", count_vect.get_feature_names()[:10])\nprint('='*50)\n\nfinal_counts = count_vect.transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_counts))\nprint(\"the shape of out text BOW vectorizer \",final_counts.get_shape())\nprint(\"the number of unique words \", final_counts.get_shape()[1])\n\"\"\"\n**Note:** The final_counts is a sparse matrix and we will need to convert it to a dense matrix before applying t-sne.\n\"\"\"\n\"\"\"\n## [4.2] Bi-Grams and n-Grams.\n\"\"\"\n#bi-gram, tri-gram and n-gram\n\n#removing stop words like \"not\" should be avoided before building n-grams\n# count_vect = CountVectorizer(ngram_range=(1,2))\n# please do read the CountVectorizer documentation http:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.feature_extraction.text.CountVectorizer.html\n# you can choose these numebrs min_df=10, max_features=5000, of your choice\ncount_vect = CountVectorizer(ngram_range=(1,2), min_df=10, max_features=5000)\nfinal_bigram_counts = count_vect.fit_transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_bigram_counts))\nprint(\"the shape of out text BOW vectorizer \",final_bigram_counts.get_shape())\nprint(\"the number of unique words including both unigrams and bigrams \", final_bigram_counts.get_shape()[1])\n\"\"\"\n**Note:** The final_bigram_counts is a sparse matrix and we will need to convert it to a dense matrix before applying t-sne.\n\"\"\"\n\"\"\"\n## [4.3] TF-IDF\n\"\"\"\ntf_idf_vect = TfidfVectorizer(ngram_range=(1,2), min_df=10)\ntf_idf_vect.fit(preprocessed_reviews)\nprint(\"some sample features(unique words in the corpus)\",tf_idf_vect.get_feature_names()[0:10])\nprint('='*50)\n\nfinal_tf_idf = tf_idf_vect.transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_tf_idf))\nprint(\"the shape of out text TFIDF vectorizer \",final_tf_idf.get_shape())\nprint(\"the number of unique words including both unigrams and bigrams \", final_tf_idf.get_shape()[1])\n\"\"\"\n**Note:** The final_tf_idf is a sparse matrix and we will need to convert it to a dense matrix before applying t-sne.\n\"\"\"\n\"\"\"\n## [4.4] Word2Vec\n\"\"\"\n# Train your own Word2Vec model using your own text corpus\ni=0\nlist_of_sentance=[]\nfor sentance in preprocessed_reviews:\n    list_of_sentance.append(sentance.split())\n# Using Google News Word2Vectors\n\n# in this project we are using a pretrained model by google\n# its 3.3G file, once you load this into your memory \n# it occupies ~9Gb, so please do this step only if you have >12G of ram\n# we will provide a pickle file wich contains a dict , \n# and it contains all our courpus words as keys and  model[word] as values\n# To use this code-snippet, download \"GoogleNews-vectors-negative300.bin\" \n# from https:\/\/drive.google.com\/file\/d\/0B7XkCwpI5KDYNlNUTTlSS21pQmM\/edit\n# it's 1.9GB in size.\n\n\n# http:\/\/kavita-ganesan.com\/gensim-word2vec-tutorial-starter-code\/#.W17SRFAzZPY\n# you can comment this whole cell\n# or change these varible according to your need\n\nis_your_ram_gt_16g= False\nwant_to_use_google_w2v = False\nwant_to_train_w2v = True\n\nif want_to_train_w2v:\n    # min_count = 5 considers only words that occured atleast 5 times\n    w2v_model=Word2Vec(list_of_sentance,min_count=5,size=50, workers=4)\n    print(w2v_model.wv.most_similar('great'))\n    print('='*50)\n    print(w2v_model.wv.most_similar('worst'))\n    \nelif want_to_use_google_w2v and is_your_ram_gt_16g:\n    if os.path.isfile('GoogleNews-vectors-negative300.bin'):\n        w2v_model=KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\n        print(w2v_model.wv.most_similar('great'))\n        print(w2v_model.wv.most_similar('worst'))\n    else:\n        print(\"you don't have gogole's word2vec file, keep want_to_train_w2v = True, to train your own w2v \")\nw2v_words = list(w2v_model.wv.vocab)\nprint(\"number of words that occured minimum 5 times \",len(w2v_words))\nprint(\"sample words \", w2v_words[0:50])\n\"\"\"\n## [4.4.1] Converting text into vectors using wAvg W2V, TFIDF-W2V\n\"\"\"\n\"\"\"\n#### [4.4.1.1] Avg W2v\n\"\"\"\n# average Word2Vec\n# compute average word2vec for each review.\nsent_vectors = []; # the avg-w2v for each sentence\/review is stored in this list\nfor sent in tqdm(list_of_sentance): # for each review\/sentence\n    sent_vec = np.zeros(50) # as word vectors are of zero length 50, you might need to change this to 300 if you use google's w2v\n    cnt_words =0; # num of words with a valid vector in the sentence\/review\n    for word in sent: # for each word in a review\/sentence\n        if word in w2v_words:\n            vec = w2v_model.wv[word]\n            sent_vec += vec\n            cnt_words += 1\n    if cnt_words != 0:\n        sent_vec \/= cnt_words\n    sent_vectors.append(sent_vec)\nprint(len(sent_vectors))\nprint(len(sent_vectors[0]))\nprint(\"the type of count vectorizer \",type(sent_vectors))\nprint(\"the shape of out text TFIDF vectorizer \",len(sent_vectors))\n\"\"\"\n**Note:** The sent_vectors is a dense list and doesn't require conversion to a dense array.\n\"\"\"\n\"\"\"\n#### [4.4.1.2] TFIDF weighted W2v\n\"\"\"\n# S = [\"abc def pqr\", \"def def def abc\", \"pqr pqr def\"]\nmodel = TfidfVectorizer()\nmodel.fit(preprocessed_reviews)\n# we are converting a dictionary with word as a key, and the idf as a value\ndictionary = dict(zip(model.get_feature_names(), list(model.idf_)))\n# TF-IDF weighted Word2Vec\ntfidf_feat = model.get_feature_names() # tfidf words\/col-names\n# final_tf_idf is the sparse matrix with row= sentence, col=word and cell_val = tfidf\n\ntfidf_sent_vectors = []; # the tfidf-w2v for each sentence\/review is stored in this list\nrow=0;\nfor sent in tqdm(list_of_sentance): # for each review\/sentence \n    sent_vec = np.zeros(50) # as word vectors are of zero length\n    weight_sum =0; # num of words with a valid vector in the sentence\/review\n    for word in sent: # for each word in a review\/sentence\n        if word in w2v_words and word in tfidf_feat:\n            vec = w2v_model.wv[word]\n#             tf_idf = tf_idf_matrix[row, tfidf_feat.index(word)]\n            # to reduce the computation we are \n            # dictionary[word] = idf value of word in whole courpus\n            # sent.count(word) = tf valeus of word in this review\n            tf_idf = dictionary[word]*(sent.count(word)\/len(sent))\n            sent_vec += (vec * tf_idf)\n            weight_sum += tf_idf\n    if weight_sum != 0:\n        sent_vec \/= weight_sum\n    tfidf_sent_vectors.append(sent_vec)\n    row += 1\nprint(\"the type of count vectorizer \",type(tfidf_sent_vectors))\nprint(\"the shape of out text TFIDF vectorizer \",len(tfidf_sent_vectors))\n\"\"\"\n**Note:** The tfidf_sent_vectors is a dense list and doesn't require conversion to a dense array.\n\"\"\"\n\"\"\"\n# [5] Applying TSNE\n\"\"\"\n\"\"\"\n<ol> \n    <li> you need to plot 4 tsne plots with each of these feature set\n        <ol>\n            <li>Review text, preprocessed one converted into vectors using (BOW)<\/li>\n            <li>Review text, preprocessed one converted into vectors using (TFIDF)<\/li>\n            <li>Review text, preprocessed one converted into vectors using (AVG W2v)<\/li>\n            <li>Review text, preprocessed one converted into vectors using (TFIDF W2v)<\/li>\n        <\/ol>\n    <\/li>\n    <li> <font color='blue'>Note 1: The TSNE accepts only dense matrices<\/font><\/li>\n    <li> <font color='blue'>Note 2: Consider only 5k to 6k data points <\/font><\/li>\n<\/ol>\n\"\"\"\n\"\"\"\n**NOTE:** From the [paper](http:\/\/www.jmlr.org\/papers\/volume9\/vandermaaten08a\/vandermaaten08a.pdf) :\n\n> The perplexity can be interpreted as a smooth measure of the effective number of neighbors. The\nperformance of SNE is fairly robust to changes in the perplexity, and typical values are between 5\nand 50.\n\nTakling reference from https:\/\/distill.pub\/2016\/misread-tsne\/ and the paper, I will use use perplexity values : 5, 30, 50, 100\n\"\"\"\nfrom sklearn.manifold import TSNE\nfrom sklearn.preprocessing import StandardScaler\n# configuring the parameteres\n# the number of components = 2\n# default perplexity = 30\n# default learning rate = 200\n# default Maximum number of iterations for the optimization = 1000\n\"\"\"\n## [5.1] Applying TNSE on Text BOW vectors\n\"\"\"\n# Convert the sparse matrix to a dense matrix\nfinal_counts_dense = final_counts.todense()\n# Standardize the data\nbow_standardized_data = StandardScaler().fit_transform(final_counts_dense)\n# bow model 1, perplexity = 5, n_iter = 250\n# perplexity is the number of points in the neighborhood\n# n_iter is the step size\n\nbow_model_1 = TSNE(n_components=2, perplexity=5, n_iter=250, random_state = 507)\n# fit_transform(raw_documents[, y]): Learn the vocabulary dictionary and return term-document matrix. \n# This is equivalent to fit followed by the transform, but more efficiently implemented.\n# reference: https:\/\/stackoverflow.com\/questions\/23838056\/what-is-the-difference-between-transform-and-fit-transform-in-sklearn#answer-53032201\n\nbow_data_1 = bow_model_1.fit_transform(bow_standardized_data)\nbow_data_1.T # taking a look at the values of bow_data_1.T\nfinal['Score'][0:5]\nbow_final_data_1 = np.vstack((bow_data_1.T,final['Score'])).T\nbow_final_data_1 = pd.DataFrame(bow_final_data_1,columns=('Dim_1', 'Dim_2', \"Review\"))\nbow_final_data_1.head()\n# Plotting the bow model #1\nll = sns.FacetGrid(bow_final_data_1,hue='Review',height=8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\n# https:\/\/stackoverflow.com\/questions\/45201514\/edit-seaborn-legend#answer-45211976\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n\nplt.title('bow model #1 with perplexity = 5, n_iter = 250')\nplt.show()\n\"\"\"\n**Observation:** If we take the minimum value of n_iter = 250, we dont get a well differentiated plot. The positive comment is covered by the negative ones and henceforth, we will consider values greater than 250.\n\"\"\"\n# bow model 2, perplexity = 60, n_iter = 1000\nbow_model_2 = TSNE(n_components=2, perplexity=60, n_iter=1000, random_state = 507)\nbow_data_2 = bow_model_2.fit_transform(bow_standardized_data)\nbow_final_data_2 = np.vstack((bow_data_2.T,final['Score'])).T\nbow_final_data_2 = pd.DataFrame(bow_final_data_2,columns=('Dim_1', 'Dim_2', \"Review\"))\nbow_final_data_2.head()\n#Plotting the bow model #2\nll = sns.FacetGrid(bow_final_data_2,hue='Review',height=8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('bow model #2 with perplexity = 60, n_iter = 1000')\nplt.show()\n\"\"\"\n**Observation:** Increasing the n_iter to 1000 has increased the stability of the plot.\n\"\"\"\n# bow model 3, perplexity = 30, n_iter = 5000\nbow_model_3 = TSNE(n_components=2, perplexity=30, n_iter=5000, random_state = 507)\nbow_data_3 = bow_model_3.fit_transform(bow_standardized_data)\nbow_final_data_3 = np.vstack((bow_data_3.T,final['Score'])).T\nbow_final_data_3 = pd.DataFrame(bow_final_data_3,columns=('Dim_1', 'Dim_2', \"Review\"))\nbow_final_data_3.head()\n# Plotting the bow model #3\nll= sns.FacetGrid(bow_final_data_3,hue='Review',height=8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('bow model #3 with perplexity = 30, n_iter = 5000')\nplt.show()\n\"\"\"\n**Observation:** In this model, we have increased the perplexity as well as the n_iter and it can be seen that the points are more grouped as compared to the earlier model where the points were scattered.\n\"\"\"\n# bow model 4, perplexity = 100, n_iter = 5000\nbow_model_4 = TSNE(n_components=2, perplexity=100, n_iter=5000, random_state = 507)\nbow_data_4 = bow_model_4.fit_transform(bow_standardized_data)\nbow_final_data_4 = np.vstack((bow_data_4.T,final['Score'])).T\nbow_final_data_4 = pd.DataFrame(bow_final_data_4,columns=('Dim_1', 'Dim_2', \"Review\"))\nbow_final_data_4.head()\n# Plotting the bow model #4\nll = sns.FacetGrid(bow_final_data_4,hue='Review',height=8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('bow model #4 with perplexity = 100, n_iter = 5000')\nplt.show()\n\"\"\"\n**Observation:** Not much difference can be observed with new values of perplexity and n_iter. The plot has already become stable with values from the last model.\n\"\"\"\n\"\"\"\n## [5.2] Applying TNSE on Text TFIDF vectors\n\"\"\"\n# Convert the sparse matrix to a dense matrix\nfinal_tfidf_dense = final_tf_idf.todense()\n# Standardize the data\ntfidf_standardized_data = StandardScaler().fit_transform(final_tfidf_dense)\n# tfidf model #1, perplexity = 5, n_iter = 1000\ntfidf_model_1 = TSNE(n_components=2,perplexity=5,n_iter=1000, random_state = 507)\ntfidf_data_1 = tfidf_model_1.fit_transform(tfidf_standardized_data)\ntfidf_data_1.T\nfinal['Score'][0:10]\ntfidf_final_data_1 = np.vstack((tfidf_data_1.T,final['Score'])).T\ntfidf_final_data_1 = pd.DataFrame(tfidf_final_data_1,columns=('Dim_1','Dim_2','Review'))\ntfidf_final_data_1.head()\nll = sns.FacetGrid(tfidf_final_data_1,hue = 'Review',size = 6).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n\nplt.title('tfidf model #1 with perplexity = 5, n_iter = 1000')\nplt.show()\n\"\"\"\n**Observation:** The plot is not stable yet and is dispersed.\n\"\"\"\n# tfidf model #2, perplexity = 30, n_iter = 5000\ntfidf_model_2 = TSNE(n_components=2,perplexity=30,n_iter=5000, random_state = 507)\ntfidf_data_2 = tfidf_model_2.fit_transform(tfidf_standardized_data)\ntfidf_final_data_2 = np.vstack((tfidf_data_2.T,final['Score'])).T\ntfidf_final_data_2 = pd.DataFrame(tfidf_final_data_2,columns=('Dim_1','Dim_2','Review'))\ntfidf_final_data_2.head()\nll = sns.FacetGrid(tfidf_final_data_2,hue = 'Review',size = 6).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf model #2 with perplexity = 30, n_iter = 5000')\nplt.show()\n\"\"\"\n**Observation:** The plot looks stable at the provided parameters. Due to class imbalance, we see only a few negative (blue) points. \n\"\"\"\n# tfidf model #3, perplexity = 100, n_iter = 5000\ntfidf_model_3 = TSNE(n_components=2,perplexity=100,n_iter=5000, random_state = 507)\ntfidf_data_3 = tfidf_model_1.fit_transform(tfidf_standardized_data)\ntfidf_final_data_3 = np.vstack((tfidf_data_3.T,final['Score'])).T\ntfidf_final_data_3 = pd.DataFrame(tfidf_final_data_3,columns=('Dim_1','Dim_2','Review'))\ntfidf_final_data_3.head()\nll = sns.FacetGrid(tfidf_final_data_3,hue = 'Review',size = 6).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf model #3 with perplexity = 100, n_iter = 5000')\nplt.show()\n\"\"\"\n**Observation:** Most of the points are clustered around the top right handside of the plot and is not stable.\n\"\"\"\n# tfidf model #4, perplexity = 50, n_iter = 1000\ntfidf_model_4 = TSNE(n_components=2,perplexity=50,n_iter=1000, random_state = 507)\ntfidf_data_4 = tfidf_model_4.fit_transform(tfidf_standardized_data)\ntfidf_final_data_4 = np.vstack((tfidf_data_4.T,final['Score'])).T\ntfidf_final_data_4 = pd.DataFrame(tfidf_final_data_4,columns=('Dim_1','Dim_2','Review'))\ntfidf_final_data_4.head()\nll = sns.FacetGrid(tfidf_final_data_1,hue = 'Review',size = 6).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf model #4 with perplexity = 50, n_iter = 1000')\nplt.show()\n\"\"\"\n**Observation:** We have increased the perplexity and reduced the iterations but we cannot confidently say that the plot is stable.\n\"\"\"\n\"\"\"\n## [5.3] Applying TNSE on Text Avg W2V vectors\n\"\"\"\n# Convert the sparse matrix to a dense matrix\n# We dont need to convert it to dense matrix as it already is a dense vector\n# Standardize the data\nsent_vectors_standardized = StandardScaler().fit_transform(sent_vectors)\n# average word2vec model #1, perplexity = 5, n_iter = 5000\navgw2v_model_1 = TSNE(n_components=2,perplexity=5,n_iter = 5000)\navgw2v_data_1 = avgw2v_model_1.fit_transform(sent_vectors_standardized)\navgw2v_data_1.T\nfinal['Score'][0:10]\navgw2v_final_data_1 = np.vstack((avgw2v_data_1.T,final['Score'])).T\n\navgw2v_final_data_1 = pd.DataFrame(avgw2v_final_data_1,columns=('Dim_1','Dim_2','Review'))\n\navgw2v_final_data_1.head()\nll = sns.FacetGrid(avgw2v_final_data_1,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('Avg word2vec model #1 with Perplexity = 5 and n_iter = 5000')\nplt.show()\n# average word2vec model #2 with perplexity = 30, n_iter = 5000\navgw2v_model_2 = TSNE(n_components=2,perplexity=30,n_iter = 5000)\navgw2v_data_2 = avgw2v_model_2.fit_transform(sent_vectors_standardized)\navgw2v_final_data_2 = np.vstack((avgw2v_data_2.T,final['Score'])).T\navgw2v_final_data_2 = pd.DataFrame(avgw2v_final_data_2,columns=('Dim_1','Dim_2','Review'))\navgw2v_final_data_2.head()\nll = sns.FacetGrid(avgw2v_final_data_2,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('Avg word2vec model #2 with Perplexity = 30 and n_iter = 5000')\nplt.show()\n# average word2vec model #3 with perplexity = 60, n_iter = 5000\navgw2v_model_3 = TSNE(n_components=2,perplexity=60,n_iter = 5000)\navgw2v_data_3 = avgw2v_model_3.fit_transform(sent_vectors_standardized)\navgw2v_final_data_3 = np.vstack((avgw2v_data_3.T,final['Score'])).T\navgw2v_final_data_3 = pd.DataFrame(avgw2v_final_data_3,columns=('Dim_1','Dim_2','Review'))\navgw2v_final_data_3.head()\nll = sns.FacetGrid(avgw2v_final_data_3,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('Avg word2vec model #3 with Perplexity = 60 and n_iter = 5000')\nplt.show()\n# average word2vec model #4 with perplexity = 100, n_iter = 2500\navgw2v_model_4 = TSNE(n_components=2,perplexity=100,n_iter = 2500)\navgw2v_data_4 = avgw2v_model_4.fit_transform(sent_vectors_standardized)\navgw2v_final_data_4 = np.vstack((avgw2v_data_4.T,final['Score'])).T\navgw2v_final_data_4 = pd.DataFrame(avgw2v_final_data_4,columns=('Dim_1','Dim_2','Review'))\navgw2v_final_data_4.head()\nll = sns.FacetGrid(avgw2v_final_data_4,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('Avg word2vec model #4 with Perplexity = 100 and n_iter = 2500')\nplt.show()\n\"\"\"\n## [5.4] Applying TNSE on Text TFIDF weighted W2V vectors\n\"\"\"\n# Convert the sparse matrix to a dense matrix\n# No need as it is already in its dense form\n# Standardize the data\ntfidf_sent_vectors_standardized_data  = StandardScaler().fit_transform(tfidf_sent_vectors)\n# tfidf-ww2v model 1, perplexity = 5, n_iter = 5000\ntfidf_ww2v_model_1 = TSNE(n_components=2,perplexity=5,n_iter = 5000)\ntfidf_ww2v_data_1 = tfidf_ww2v_model_1.fit_transform(tfidf_sent_vectors_standardized_data)\ntfidf_ww2v_data_1.T\nfinal['Score'][0:10]\ntfidf_ww2v_final_data_1 = np.vstack((tfidf_ww2v_data_1.T,final['Score'])).T\n\ntfidf_ww2v_final_data_1 = pd.DataFrame(tfidf_ww2v_final_data_1,columns=('Dim_1','Dim_2','Review'))\n\ntfidf_ww2v_final_data_1.head()\nll= sns.FacetGrid(tfidf_ww2v_final_data_1,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf weighted word2vec model #1 with perplexity = 5 and n_iter = 5000')\nplt.show()\n# tfidf-ww2v model 2, perplexity = 30, n_iter = 3000\ntfidf_ww2v_model_2 = TSNE(n_components=2,perplexity=30,n_iter = 3000)\ntfidf_ww2v_data_2 = tfidf_ww2v_model_2.fit_transform(tfidf_sent_vectors_standardized_data)\ntfidf_ww2v_final_data_2 = np.vstack((tfidf_ww2v_data_2.T,final['Score'])).T\ntfidf_ww2v_final_data_2 = pd.DataFrame(tfidf_ww2v_final_data_2,columns=('Dim_1','Dim_2','Review'))\ntfidf_ww2v_final_data_2.head()\nll = sns.FacetGrid(tfidf_ww2v_final_data_2,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf weighted word2vec model #2 with perplexity = 30 and n_iter = 3000')\nplt.show()\n# tfidf-ww2v model 3, perplexity = 60, n_iter = 5000\ntfidf_ww2v_model_3 = TSNE(n_components=2,perplexity=60,n_iter = 5000)\ntfidf_ww2v_data_3 = tfidf_ww2v_model_3.fit_transform(tfidf_sent_vectors_standardized_data)\ntfidf_ww2v_final_data_3 = np.vstack((tfidf_ww2v_data_3.T,final['Score'])).T\ntfidf_ww2v_final_data_3 = pd.DataFrame(tfidf_ww2v_final_data_3,columns=('Dim_1','Dim_2','Review'))\ntfidf_ww2v_final_data_3.head()\nll = sns.FacetGrid(tfidf_ww2v_final_data_3,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf weighted word2vec model #3 with perplexity = 60 and n_iter = 5000')\nplt.show()\n# tfidf-ww2v model 4, perplexity = 100, n_iter = 3000\ntfidf_ww2v_model_4 = TSNE(n_components=2,perplexity=100,n_iter = 3000)\ntfidf_ww2v_data_4 = tfidf_ww2v_model_4.fit_transform(tfidf_sent_vectors_standardized_data)\ntfidf_ww2v_final_data_4 = np.vstack((tfidf_ww2v_data_4.T,final['Score'])).T\ntfidf_ww2v_final_data_4 = pd.DataFrame(tfidf_ww2v_final_data_4,columns=('Dim_1','Dim_2','Review'))\ntfidf_ww2v_final_data_4.head()\nll = sns.FacetGrid(tfidf_ww2v_final_data_4,hue = 'Review',size = 8).map(plt.scatter,'Dim_1','Dim_2').add_legend()\n\nnew_labels = ['Positive', 'Negative']\nfor t, l in zip(ll._legend.texts, new_labels): t.set_text(l);\n    \nplt.title('tfidf weighted word2vec model #4 with perplexity = 100 and n_iter = 3000')\nplt.show()\n\"\"\"\n# [6] Conclusions\n\"\"\"\n# Write few sentance about the results that you got and observation that you did from the analysis\n\"\"\"\n1. There's no such value which we can call correct and it satifies all the different models. We have to **experiment with the values** of perplexity and n_iter until the t-sne plot becomes stable.\n2. The **more the number of iternations the better.** As we saw in one of the bow model, if we used n_iter = 250, the visualization on the review type was not well sorted. The plotting of the model  may be stable for a value less than 5000 but it is always better to keep the value of n_iter = 5000, as keeping it low may not yield expected results.\n3. The positive and the negative **reviews seem to be overlap** each other. This means there are **certain words which occur in both the reviews and as a result positve and negative review classes are not easily separable.**\n4. The **class imbalance** also played a role, as most of the review text was largely positive. We need to address this imbalance class of Review text so that our analysis can fetch better results.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6b00f8432c51c9'}"}
{"id":"114877","text":"\"\"\"\n# PUBG Finish Placement Prediction\n\nAutor: Daniel Martinez Bielostotzky\n\"\"\"\n\"\"\"\n## Table of contents\n* **Imports: Dataset, Libraries and Usefull Functions**\n* **Preprocessing: Missing Values**\n* **Feature Engenieering: Team and Match Features**\n* **Feature Selection and Outliers**\n* **LightGBM Model**\n* **Test Data Prediction and Submit**\n\"\"\"\n\"\"\"\n## Imports: Dataset, Libraries and Usefull Functions\n\nFor this notebook, I'll use two functions that are from a kind of EDA framework that I always use and that its open to contributions on [GitHub](https:\/\/github.com\/Bielos\/EDA-Framework).\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sn\n\ndef get_null_observations(dataframe, column):\n    return dataframe[pd.isnull(dataframe[column])]\n\ndef delete_null_observations(dataframe, column):\n    fixed_df = dataframe.drop(get_null_observations(dataframe,column).index)\n    return fixed_df\n    \ndef get_missing_data_table(dataframe):\n    total = dataframe.isnull().sum()\n    percentage = dataframe.isnull().sum() \/ dataframe.isnull().count()\n    \n    missing_data = pd.concat([total, percentage], axis='columns', keys=['TOTAL','PERCENTAGE'])\n    return missing_data.sort_index(ascending=True)\n\ndf = pd.read_csv('..\/input\/train_V2.csv')\ndf.head()\n\"\"\"\n## Preprocessing: Missing Values\n\nTo check the integrity of the data, the missing values and data types are displayed.\n### Missing Vales\nUsing *get_missing_data_table* we can see that the training dataset has only one record with a missing value in the 'winPlacePerc' column since it is the target column no completion method can be applied.\n\"\"\"\nget_missing_data_table(df)\ndf = delete_null_observations(dataframe=df, column='winPlacePerc')\nget_missing_data_table(df)\n\"\"\"\n## Feature Engenieering: Team and Match Features\nGrouping records by *groupId* and *matchId* the features *teamKills* (Sum of kills in the team), *teamSize* (Total number of players in the team), *matchKills* and *matchSize* are created. \n\"\"\"\n# Adding team features\ndf_team_dict = (df.groupby('groupId', as_index = True)\n          .agg({'Id':'count', 'kills':'sum'})\n          .rename(columns={'Id':'teamSize', 'kills':'teamKills'})).to_dict()\n\nteamKills = []\nteamSize = []\n\nfor teamId in df['groupId']:\n    teamKills.append(df_team_dict['teamKills'][teamId])\n    teamSize.append(df_team_dict['teamSize'][teamId])\n\ndf['teamKills'] = teamKills\ndf['teamSize'] = teamSize\ndf.head()\n# Adding match features\ndf_team = (df.groupby('groupId', as_index = False)\n          .agg({'Id':'count', 'matchId':lambda x: x.unique()[0], 'kills':'sum'})\n          .rename(columns={'Id':'teamSize', 'kills':'teamKills'})).reset_index()\n\ndf_match = (df_team.groupby('matchId', as_index = True)\n           .agg({'teamSize':'sum', 'teamKills':'sum'})\n           .rename(columns={'teamSize':'matchSize', 'teamKills':'matchKills'})).to_dict()\nmatchSize = []\nmatchKills = []\n\nfor matchId in df['matchId']:\n    matchSize.append(df_match['matchSize'][matchId])\n    matchKills.append(df_match['matchKills'][matchId])\n\ndf['matchSize'] = matchSize\ndf['matchKills'] = matchKills\ndf.head()\n\"\"\"\n## Feature Selection and Outliers\n\nFeatures that represent IDs are meaningless for any model so they are dropped out. \n\"\"\"\n#Drop insignificant features\ndf.drop(['Id'], axis='columns', inplace=True)\ndf.drop(['groupId'], axis='columns', inplace=True)\ndf.drop(['matchId'], axis='columns', inplace=True)\ndf.head()\n\"\"\"\n### Outliers\nSome records may be rare cases and may affect the generalization power of the model because they are just noise.\n\nThe outliers to be deleted are:\n1.  Records with low *matchDuration* (According to box plot) \n1. Players with 0 *rideDistance* and *roadKills* greater than 0\n\"\"\"\n# matchDuration boxplot\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nsn.boxplot(data=df['matchDuration'], ax= ax)\nax.set(title='Match Duration Box Plot')\nplt.show()\n# Delete Outliers according to matchDuration\nprevious_record_size = df.shape[0]\n\nh_spread = df['matchDuration'].quantile(.75) - df['matchDuration'].quantile(.25)\nlimit = df['matchDuration'].quantile(.25) - 2 * h_spread\ndf.drop(df[df['matchDuration'] < limit].index, inplace=True)\n\nnew_record_size = df.shape[0]\nprint('Total records deleted: {} ({:.7%} of previous record size)'.format(previous_record_size - new_record_size, 1 - new_record_size \/ previous_record_size))\n# Delete Outliers according to rideDistance and roadKills\nprevious_record_size = df.shape[0]\n\ndf.drop(df.query('rideDistance == 0 and roadKills > 0').index, inplace=True)\n\nnew_record_size = df.shape[0]\nprint('Total records deleted: {} ({:.7%} of previous record size)'.format(previous_record_size - new_record_size, 1 - new_record_size \/ previous_record_size))\n\"\"\"\n## LightGBM Model\n\nA LightGBM model is used to predict the target *winPlacePerc*,  the model use 15000 iterations, 70% of features and 90% of training data per tree\n\"\"\"\n# Label encode matchType\n\nfrom sklearn import preprocessing\nencoder = preprocessing.LabelEncoder()\ndf['matchType'] = encoder.fit_transform(df['matchType'])\n\ndf.head()\n# X and y split\ny = df['winPlacePerc'].values\nX = df.drop(['winPlacePerc'], axis='columns').values\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n#LightGBM\nimport lightgbm as lgb\n\n# create dataset for lightgbm\nlgb_train = lgb.Dataset(X_train, y_train, categorical_feature=[12])\nlgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)\n\n# set matchType\n\nparams = {\n        \"objective\" : \"regression\",\n        \"metric\" : \"mae\",\n        \"n_estimators\":15000,\n        \"early_stopping_rounds\":100,\n        \"num_leaves\" : 31, \n        \"learning_rate\" : 0.05, \n        \"bagging_fraction\" : 0.9,\n        \"bagging_seed\" : 0, \n        \"num_threads\" : 4,\n        \"colsample_bytree\" : 0.7\n        }\n\nmodel = lgb.train(params,\n                lgb_train,\n                num_boost_round=20,\n                valid_sets=lgb_eval,\n                early_stopping_rounds=5,\n                verbose_eval=1000)\n\"\"\"\n## Test Data Prediction and Submit\n\"\"\"\ndf_test = pd.read_csv('..\/input\/test_V2.csv')\ndf_test['matchType'] = encoder.transform(df_test['matchType'])\ndf_test_team_dict = (df_test.groupby('groupId', as_index = True)\n          .agg({'Id':'count', 'kills':'sum'})\n          .rename(columns={'Id':'teamSize', 'kills':'teamKills'})).to_dict()\n\nteamKills_test = []\nteamSize_test = []\n\nfor teamId in df_test['groupId']:\n    teamKills_test.append(df_test_team_dict['teamKills'][teamId])\n    teamSize_test.append(df_test_team_dict['teamSize'][teamId])\n\ndf_test['teamKills'] = teamKills_test\ndf_test['teamSize'] = teamSize_test\n\ndf_team_test = (df_test.groupby('groupId', as_index = False)\n          .agg({'Id':'count', 'matchId':lambda x: x.unique()[0], 'kills':'sum'})\n          .rename(columns={'Id':'teamSize', 'kills':'teamKills'})).reset_index()\n\ndf_match_test = (df_team_test.groupby('matchId', as_index = True)\n           .agg({'teamSize':'sum', 'teamKills':'sum'})\n           .rename(columns={'teamSize':'matchSize', 'teamKills':'matchKills'})).to_dict()\nmatchSize_test = []\nmatchKills_test = []\n\nfor matchId in df_test['matchId']:\n    matchSize_test.append(df_match_test['matchSize'][matchId])\n    matchKills_test.append(df_match_test['matchKills'][matchId])\n\ndf_test['matchSize'] = matchSize_test\ndf_test['matchKills'] = matchKills_test\n\nX_testdata = df_test.drop(['Id','groupId','matchId'], axis='columns').values\n\ndf_test['winPlacePerc'] = model.predict(X_testdata, num_iteration=model.best_iteration)\nsubmission = df_test[['Id', 'winPlacePerc']]\nsubmission.to_csv('submission.csv', index=False)\nprint('Done!')","meta":"{'source': 'AI4Code', 'id': 'd31dcb72662351'}"}
{"id":"120036","text":"\"\"\"\n# Table of Contents:\n1. [Introduction](#section-one)\n    - [Problem Statement](#subsection-one)\n    - [About Project](#subsection-two)\n    - [Objectives of project](#subsection-three)\n2. [Prepare Data for Consumption](#section-two)\n    - [Import Libraries](#subsection-five)\n    - [Meet and Greet Data](#subsection-six)\n    - [Data Cleaning](#subsection-seven)\n3. [Data Visualization](#section-three)\n    - [Duration of calls vs Job roles](#subsection-eight)\n    - [Campaign vs Duration calls](#subsection-nine)\n    - [Campaign vs Month](#subsection-ten)\n    - [Distribution of Quarterly Indicators](#subsection-eleven)\n    - [Marital Status vs Price index](#subsection-twelve)\n    - [Positive deposits vs attributes](#subsection-thirteen)\n    - [Correlation plot of attributes](#subsection-fourteen)\n4. [Feature Engineering](#section-four)\n    - [Handling Outliers](#subsection-fifteen)\n    - [Education- category clubbing](#subsection-sixteen)\n    - [Encoding - Month and Day of week](#subsection-seventeen)\n    - [Encoding 999 in pdays as 0](#subsection-eighteen)\n    - [Ordinal Number Encoding](#subsection-nineteen)\n    - [Ordinal Encoding](#subsection-twenty)\n    - [Frequency encoding](#subsection-twentyone)\n    - [Target Guided Ordinal Encoding](#subsection-twentytwo)\n    - [Standardization of numerical variables](#subsection-twentythree)\n    - [Feature Selection](#subsection-twentyfour)\n    - [Train and Test Split (80:20)](#subsection-twentyfive)\n5. [Modelling our Data](#section-five)\n    - [Model Selection](#subsection-twentysix)\n    - [Logistic regression with Hyperparameter tuning](#subsection-twentyseven)\n    - [Support vector classifier](#subsection-twentyeight)\n6. [Conclusion](#section-six)\n    \n\"\"\"\n\"\"\"\n<a id=\"section-one\"><\/a>\n# Introduction\n\n![12.jpg](attachment:12.jpg)\n<a id=\"subsection-one\"><\/a>\n## Problem Statement\nThere has been a revenue decline for the Portuguese bank and they would like to know what actions to take. After investigation, we found out that the root cause is that their clients are not depositing as frequently as before. Knowing that term deposits allow banks to hold onto a deposit for a specific amount of time, so banks can invest in higher gain financial products to make a profit. In addition, banks also hold better chance to persuade term deposit clients into buying other products such as funds or insurance to further increase their revenues. As a result, the Portuguese bank would like to identify existing clients that have higher chance to subscribe for a term deposit and focus marketing effort on such clients.\n\n## About Dataset \nIt is a dataset that describing Portugal bank marketing campaigns results.Conducted campaigns were based mostly on direct phone calls, offering bank client to place a term deposit. If after all marking afforts client had agreed to place deposit - target variable marked 'yes', otherwise 'no'\n\nSource of the data:\nhttps:\/\/archive.ics.uci.edu\/ml\/datasets\/bank+marketing\n<a id=\"subsection-two\"><\/a>\n# About Project\nIn this project, I will analyze the Bank lead's dataset and create a classification algorithm with full end feature engineering and EDA\n\n## Project Summary:\nI'm a Data Analyst of XYZ consultancy Ltd. The ABC Portugal Bank approached our service and requested us to create a classfication algorithm to automatically place their prospective leads on having a term deposit in their bank. We will be creating a classification algorithm and also suggest them the insights we derive from this dataset and also help them to narrow down their leads into marketing funnel and in the end make a term deposit.\n<a id=\"subsection-three\"><\/a>\n# Objectives of project:\n\n* Meet and Greet Data\n* Prepare the Data for consumption (Feature Engineering and Selection)\n* Perform Exploratory Analysis (Visualizations)\n* Model the Data using Machine Learning\n* Validate and implement data model\n* Optimize and Strategize\n\n<a id=\"section-two\"><\/a>\n# Prepare Data for Consumption\n<a id=\"subsection-five\"><\/a>\n## Import Libraries\n\nLet's import all necessary libraries for the analysis and along with it let's bring down our dataset\n\"\"\"\n## Database Phase\nimport pandas as pd\nimport numpy as np\n\n# Machine Learning Phase\nimport sklearn \nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import BernoulliNB \nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\n\n#Metrics Phase\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import cross_val_score\n\n#Visualization Phase\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pylab as pylab\n%matplotlib inline\npd.set_option('display.max_columns', 500)\nmpl.style.use('ggplot')\nsns.set_style('white')\npylab.rcParams['figure.figsize'] = 12,8\n\n#ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n<a id=\"subsection-six\"><\/a>\n## Meet and Greet data\n\nOur first step is to create the get the csv and welcome it. Later we should dissect and perform descriptive analyis. Well that escalated quickly.\n\"\"\"\nbank=pd.read_csv(\"..\/input\/bank-marketing-campaigns-dataset\/bank-additional-full.csv\",sep=';')\nbank_copy=bank.copy()\n\n## print shape of dataset with rows and columns and information \nprint (\"The shape of the  data is (row, column):\"+ str(bank_copy.shape))\nprint (bank_copy.info())\n\"\"\"\n**Dataset:** \n\nWe have 4118 instances and 21 features. The information says there are no null values. Fishy right? anyway we will strictly scrutinize each feature and check for suspicious records and manipulate them\n\n**Attributes:**\n**Bank client data:**\n\n1. **Age** : Age of the lead (numeric)\n2. **Job** : type of job (Categorical) \n3. **Marital** : Marital status (Categorical)\n4. **Education** :  Educational Qualification of the lead (Categorical)\n5. **Default:** Does the lead has any default(unpaid)credit (Categorical)\n6. **Housing:** Does the lead has any housing loan? (Categorical) \n7. **loan:** Does the lead has any personal loan? (Categorical)\n\n**Related with the last contact of the current campaign:**\n\n8. **Contact:** Contact communication type (Categorical)\n9. **Month:** last contact month of year (Categorical) \n10. **day_of_week:** last contact day of the week (categorical)\n11. **duration:** last contact duration, in seconds (numeric). \n\n**Important note:** Duration highly affects the output target (e.g., if duration=0 then y='no'). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.\n\n**Other attributes:**\n\n12. **campaign:** number of contacts performed during this campaign and for this client (numeric)\n13. **pdays:** number of days that passed by after the client was last contacted from a previous campaign(numeric; 999 means client was not previously contacted))\n14. **previous:** number of contacts performed before this campaign and for this client (numeric)\n15. **poutcome:** outcome of the previous marketing campaign (categorical)\n\n**Social and economic context attributes**\n\n16. **emp.var.rate:** employment variation rate - quarterly indicator (numeric)\n17. **cons.price.idx:** consumer price index - monthly indicator (numeric)\n18. **cons.conf.idx:** consumer confidence index - monthly indicator (numeric)\n19. **euribor3m:** euribor 3 month rate - daily indicator (numeric)\n20. **nr.employed:** number of employees - quarterly indicator (numeric)\n\n**Output variable (desired target):**\n\n21. **y** - has the client subscribed a term deposit? (binary: 'yes','no')\n\"\"\"\n\"\"\"\nLet's check out the general overview of the dataframe\n\"\"\"\nbank_copy.head()\nbank_copy.dtypes\n#Checking out the statistical parameters\nbank_copy.describe()\n#Checking out the categories and their respective counts in each feature\nprint(\"Job:\",bank_copy.job.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Marital:\",bank_copy.marital.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Education:\",bank_copy.education.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Default:\",bank_copy.default.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Housing loan:\",bank_copy.housing.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Personal loan:\",bank_copy.loan.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Contact:\",bank_copy.contact.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Month:\",bank_copy.month.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Day:\",bank_copy.day_of_week.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Previous outcome:\",bank_copy.poutcome.value_counts(),sep = '\\n')\nprint(\"-\"*40)\nprint(\"Outcome of this campaign:\",bank_copy.y.value_counts(),sep = '\\n')\nprint(\"-\"*40)\n\"\"\"\n**Insights:**\n\n* We got `unknown` category in each feature, we should figure out how to deal with that\n* This campaign only operated during weekdays\n* I can't understand what is `non-existent` category in previous outcome aka `poutcome`, if you have figured out what is it let me know in the comments.\n\"\"\"\n\"\"\"\n<a id=\"subsection-seven\"><\/a>\n# Data Cleaning\n## Checking for missing values\nFirst lets check it visually\n\"\"\"\nimport missingno as msno \nmsno.matrix(bank_copy)\n\"\"\"\nLooks like we don't have any null values except one. But plots sometimes deceive us, numbers don't. Let's check with the numbers\n\"\"\"\nprint('Data columns with null values:',bank_copy.isnull().sum(), sep = '\\n')\n\"\"\"\nWe have the records of null values and looks like **we don't have any null values.**\n\"\"\"\n\"\"\"\n<a id=\"section-three\"><\/a>\n# Data Visualization\nSince we have much numerical data, let's keep our plots much targetted towards our machine learning models. Also let's figure out which feature importances and prune away least important ones\n<a id=\"subsection-eight\"><\/a>\n## Duration of calls vs Job roles\n\"\"\"\nimport plotly.express as px\n\nfig = px.box(bank_copy, x=\"job\", y=\"duration\", color=\"y\")\nfig.update_traces(quartilemethod=\"exclusive\") # or \"inclusive\", or \"linear\" by default\nfig.show()\n\"\"\"\n**Insights:**\n* The leads who have not made a deposit have lesser duration on calls\n* Comparing the average, the blue collar, entrepreneur have high duration in calls and student, retired have less duration in average\n* Large distribution of leads were from self employed clients and management people.\n\"\"\"\n\"\"\"\n<a id=\"subsection-nine\"><\/a>\n## Campaign vs Duration calls\n\"\"\"\nfig = px.scatter(bank_copy, x=\"campaign\", y=\"duration\", color=\"y\")\nfig.show()\n\"\"\"\n**Insights:**\n* The more the duration the calls were, they had higher probability in making a deposit\n* Duration of calls faded as the time period of campaign extended further\n* There were many positive leads in the initial days of campaign \n\"\"\"\n\"\"\"\n<a id=\"subsection-ten\"><\/a>\n## Campaign vs Month\n\"\"\"\nplt.bar(bank_copy['month'], bank_copy['campaign'])\n\"\"\"\n**Insights:**\n* We can see the campaign were mostly concentrated in the starting of the bank period ( May, June and July)\n* Usually education period starts during that time so there is a possibility that parents make deposits in the name of their children\n* They also have made their campaign in the end of the bank period.\n\"\"\"\n\"\"\"\n<a id=\"subsection-eleven\"><\/a>\n## Distribution of Quarterly Indicators\n\"\"\"\nplt.subplot(231)\nsns.distplot(bank_copy['emp.var.rate'])\nfig = plt.gcf()\nfig.set_size_inches(10,10)\n\nplt.subplot(232)\nsns.distplot(bank_copy['cons.price.idx'])\nfig = plt.gcf()\nfig.set_size_inches(10,10)\n\nplt.subplot(233)\nsns.distplot(bank_copy['cons.conf.idx'])\nfig = plt.gcf()\nfig.set_size_inches(10,10)\n\nplt.subplot(234)\nsns.distplot(bank_copy['euribor3m'])\nfig = plt.gcf()\nfig.set_size_inches(10,10)\n\nplt.subplot(235)\nsns.distplot(bank_copy['nr.employed'])\nfig = plt.gcf()\nfig.set_size_inches(10,10)\n\"\"\"\n**Insights:**\n* We can see there is a high employee variation rate which signifies that they have made the campaign when there were high shifts in job due to conditions of economy\n* The Consumer price index is also good which shows the leads where having good price to pay for goods and services may be that could be the reason to stimulate these leads into making a deposit and plant the idea of savings\n* Consumer confidence index is pretty low as they don't have much confidence on the fluctuating economy\n* The 3 month Euribor interest rate is the interest rate at which a selection of European banks lend one another funds denominated in euros whereby the loans have a maturity of 3 months. In our case the interest rates are high for lending their loans \n* The number of employees were also at peak which can increase their income index that could be the reason the campaign targetted the leads who were employeed to make a deposit\n\n\"\"\"\n\"\"\"\n<a id=\"subsection-twelve\"><\/a>\n## Marital Status vs Price index\n\"\"\"\nsns.violinplot( y=bank_copy[\"marital\"], x=bank_copy[\"cons.price.idx\"] )\n\"\"\"\n**Insights:**\n* There are very minute differences among the price index\n* Married leads have considerably have an upper hand as they have index contributing as couple \n\n\"\"\"\n\"\"\"\n<a id=\"subsection-thirteen\"><\/a>\n## Positive deposits vs attributes\n\"\"\"\nbank_yes = bank_copy[bank_copy['y']=='yes']\n\n\ndf1 = pd.crosstab(index = bank_yes[\"marital\"],columns=\"count\")    \ndf2 = pd.crosstab(index = bank_yes[\"month\"],columns=\"count\")  \ndf3= pd.crosstab(index = bank_yes[\"job\"],columns=\"count\") \ndf4=pd.crosstab(index = bank_yes[\"education\"],columns=\"count\")\n\nfig, axes = plt.subplots(nrows=2, ncols=2)\ndf1.plot.bar(ax=axes[0,0])\ndf2.plot.bar(ax=axes[0,1])\ndf3.plot.bar(ax=axes[1,0])\ndf4.plot.bar(ax=axes[1,1])       \n\"\"\"\n**Insights:**\n* Married leads have made high deposits followed by single\n* There were much deposist made during may month as it is the start of bank period\n* Leads who work in administrative position made deposits followed by technicians and blue collar employees\n* Leads who had atleast university degree had made te deposits followed by highschool\n\n\"\"\"\n\"\"\"\n<a id=\"subsection-fourteen\"><\/a>\n## Correlation plot of attributes\n\"\"\"\nf,ax=plt.subplots(figsize=(10,10))\nsns.heatmap(bank_copy.corr(),annot=True,linewidths=0.5,linecolor=\"black\",fmt=\".1f\",ax=ax)\nplt.show()\n\"\"\"\n**Insights:**\n* The indicators have correlation among themselves\n* Number of employees rate is highly correlated with employee variation rate\n* Consumer price index is highly correlated with bank interest rate( higher the price index, higher the interest rate)\n* Employee variation rate also correlates with the bank interest rates\n\n\n\"\"\"\n\"\"\"\n<a id=\"section-four\"><\/a>\n# Feature Engineering\n<a id=\"subsection-fifteen\"><\/a>\n## Handling outliers\nLet's check out our numerical feature outliers through boxplot\n\"\"\"\nplt.figure(figsize = (15, 30))\nplt.style.use('seaborn-white')\nax=plt.subplot(521)\nplt.boxplot(bank_copy['age'])\nax.set_title('age')\nax=plt.subplot(522)\nplt.boxplot(bank_copy['duration'])\nax.set_title('duration')\nax=plt.subplot(523)\nplt.boxplot(bank_copy['campaign'])\nax.set_title('campaign')\nax=plt.subplot(524)\nplt.boxplot(bank_copy['pdays'])\nax.set_title('pdays')\nax=plt.subplot(525)\nplt.boxplot(bank_copy['previous'])\nax.set_title('previous')\nax=plt.subplot(526)\nplt.boxplot(bank_copy['emp.var.rate'])\nax.set_title('Employee variation rate')\nax=plt.subplot(527)\nplt.boxplot(bank_copy['cons.price.idx'])\nax.set_title('Consumer price index')\nax=plt.subplot(528)\nplt.boxplot(bank_copy['cons.conf.idx'])\nax.set_title('Consumer confidence index')\nax=plt.subplot(529)\nplt.boxplot(bank_copy['euribor3m'])\nax.set_title('euribor3m')\nax=plt.subplot(5,2,10)\nplt.boxplot(bank_copy['nr.employed'])\nax.set_title('No of employees')\n\n\"\"\"\nWe see that many features doesn't have much outliers except for age,duration and campaign. So, let's fix only those features using IQR method.\n\"\"\"\nnumerical_features=['age','campaign','duration']\nfor cols in numerical_features:\n    Q1 = bank_copy[cols].quantile(0.25)\n    Q3 = bank_copy[cols].quantile(0.75)\n    IQR = Q3 - Q1     \n\n    filter = (bank_copy[cols] >= Q1 - 1.5 * IQR) & (bank_copy[cols] <= Q3 + 1.5 *IQR)\n    bank_copy=bank_copy.loc[filter]\nplt.figure(figsize = (15, 10))\nplt.style.use('seaborn-white')\nax=plt.subplot(221)\nplt.boxplot(bank_copy['age'])\nax.set_title('age')\nax=plt.subplot(222)\nplt.boxplot(bank_copy['duration'])\nax.set_title('duration')\nax=plt.subplot(223)\nplt.boxplot(bank_copy['campaign'])\nax.set_title('campaign')\n\"\"\"\nNow that we have removed outliers, we can proceed for more feature engineering techniques.\n\"\"\"\n\"\"\"\n<a id=\"subsection-sixteen\"><\/a>\n## Education- category clubbing\n\nHere we are clubbing category in education such as 'basic.9y','basic.6y','basic.4y' to 'middle school' \n\"\"\"\nbank_features=bank_copy.copy()\nlst=['basic.9y','basic.6y','basic.4y']\nfor i in lst:\n    bank_features.loc[bank_features['education'] == i, 'education'] = \"middle.school\"\n\nbank_features['education'].value_counts()\n\"\"\"\nGreat, we have clubbed all the categories in education into one\n\"\"\"\n\"\"\"\n<a id=\"subsection-seventeen\"><\/a>\n## Encoding - Month and Day of week\n\nEncoding the categories in month and day of week to the respective numbers.\n\"\"\"\nmonth_dict={'may':5,'jul':7,'aug':8,'jun':6,'nov':11,'apr':4,'oct':10,'sep':9,'mar':3,'dec':12}\nbank_features['month']= bank_features['month'].map(month_dict) \n\nday_dict={'thu':5,'mon':2,'wed':4,'tue':3,'fri':6}\nbank_features['day_of_week']= bank_features['day_of_week'].map(day_dict) \nbank_features.loc[:, ['month', 'day_of_week']].head()\n\"\"\"\nWe have hard encoded the month and day of week features\n\"\"\"\n\"\"\"\n<a id=\"subsection-eighteen\"><\/a>\n## Encoding 999 in pdays as 0\n\nEncoding 999 in pdays feature( i.e clients who haven't been contacted for the previous campaign) into 0\n\"\"\"\nbank_features.loc[bank_features['pdays'] == 999, 'pdays'] = 0\nbank_features['pdays'].value_counts()\n\"\"\"\nWe have converted 999 to 0 in pdays\n\"\"\"\n\"\"\"\n<a id=\"subsection-nineteen\"><\/a>\n## Ordinal Number Encoding\nHere we are gonna encode the features which has yes,no and unknown. We'll assign yes:1,no:0 and unknown:-1\n\"\"\"\ndictionary={'yes':1,'no':0,'unknown':-1}\nbank_features['housing']=bank_features['housing'].map(dictionary)\nbank_features['default']=bank_features['default'].map(dictionary)\nbank_features['loan']=bank_features['loan'].map(dictionary)\ndictionary1={'no':0,'yes':1}\nbank_features['y']=bank_features['y'].map(dictionary1)\nbank_features.loc[:,['housing','default','loan','y']].head()\n\"\"\"\nWe have encoded the yes\/no features with hard encoding \n\"\"\"\n\"\"\"\n<a id=\"subsection-twenty\"><\/a>\n## Ordinal Encoding \n\"\"\"\ndummy_contact=pd.get_dummies(bank_features['contact'], prefix='dummy',drop_first=True)\ndummy_outcome=pd.get_dummies(bank_features['poutcome'], prefix='dummy',drop_first=True)\nbank_features = pd.concat([bank_features,dummy_contact,dummy_outcome],axis=1)\nbank_features.drop(['contact','poutcome'],axis=1, inplace=True)\nbank_features.loc[:,['dummy_telephone','dummy_nonexistent','dummy_success']].head()\n\"\"\"\nWe have performed one-hot encoding for the above features and dropped the original features\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentyone\"><\/a>\n## Frequency encoding\nLet's use frequency encoding with job and education features in our dataset\n\"\"\"\nbank_job=bank_features['job'].value_counts().to_dict()\nbank_ed=bank_features['education'].value_counts().to_dict()\n\"\"\"\nConverted the frequency into key value pairs. Let's map them\n\"\"\"\nbank_features['job']=bank_features['job'].map(bank_job)\nbank_features['education']=bank_features['education'].map(bank_ed)\n\nbank_features.loc[:,['job','education']].head()\n\"\"\"\nWe have encoded the job and education feature based on its frequency \n\"\"\"\n\"\"\"\n<a id=\"subsection-twentytwo\"><\/a>\n## Target Guided Ordinal Encoding\nLets encode marital feature based on the target 'y' . First let's find the mean of target with respect to  marital feature\n\n\"\"\"\nbank_features.groupby(['marital'])['y'].mean()\nordinal_labels=bank_features.groupby(['marital'])['y'].mean().sort_values().index\nordinal_labels\n\"\"\"\nWe have sorted the categories based on the mean with respect to our outcome\n\"\"\"\nordinal_labels2={k:i for i,k in enumerate(ordinal_labels,0)}\nordinal_labels2\n\"\"\"\nChanged into key:value pairs, let's map them\n\"\"\"\nbank_features['marital_ordinal']=bank_features['marital'].map(ordinal_labels2)\nbank_features.drop(['marital'], axis=1,inplace=True)\nbank_features.marital_ordinal.value_counts()\n\"\"\"\nWe have encoded the marital feature\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentythree\"><\/a>\n## Standardization of numerical variables\n\"\"\"\nbank_scale=bank_features.copy()\nCategorical_variables=['job', 'education', 'default', 'housing', 'loan', 'month',\n       'day_of_week','y', 'dummy_telephone', 'dummy_nonexistent',\n       'dummy_success', 'marital_ordinal']\n\n\nfeature_scale=[feature for feature in bank_scale.columns if feature not in Categorical_variables]\n\n\nscaler=StandardScaler()\nscaler.fit(bank_scale[feature_scale])\nscaled_data = pd.concat([bank_scale[['job', 'education', 'default', 'housing', 'loan', 'month',\n       'day_of_week','y', 'dummy_telephone', 'dummy_nonexistent',\n       'dummy_success', 'marital_ordinal']].reset_index(drop=True),\n                    pd.DataFrame(scaler.transform(bank_scale[feature_scale]), columns=feature_scale)],\n                    axis=1)\nscaled_data.head()\n\"\"\"\nWe have scaled our numerical features as you can see from the head.\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentyfour\"><\/a>\n## Feature Selection\nLet's check the feature importances and prune our features to make our model perform well.\n\"\"\"\nX=scaled_data.drop(['y'],axis=1)\ny=scaled_data.y\n\nmodel = ExtraTreesClassifier()\nmodel.fit(X,y)\nfeat_importances = pd.Series(model.feature_importances_, index=X.columns)\nfeat_importances.nlargest(17).plot(kind='barh')\nplt.show()\n\"\"\"\nFrom the bar plot we can see the importances of features based on it's impact towards output. Let's take up the top 15 features\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentyfive\"><\/a>\n## Train and Test Split (80:20)\nLet's drop the required features and split the data into train and test\n\"\"\"\nX=scaled_data.drop(['pdays','month','cons.price.idx','loan','housing','emp.var.rate','y'],axis=1)\ny=scaled_data.y\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,train_size=0.8,random_state=1)\nprint(\"Input Training:\",X_train.shape)\nprint(\"Input Test:\",X_test.shape)\nprint(\"Output Training:\",y_train.shape)\nprint(\"Output Test:\",y_test.shape)\n\"\"\"\n<a id=\"section-five\"><\/a>\n# Modelling our Data\nLet's enter into the crucial phase of building THE machine learning model. Before checking \"what could be the best algorithm for prediction\" we have to decide on the \"why\". It is highly important.\n\n## Why?\nOur main aim is to predict whether there is a deposit made made owing to those values from the features. The output is either going to be 0 or 1. So we can decide that we can use classification models for our problem\n\n## What ?\nTo decide on what can be the best possible classification models let's not waste time running models. Instead we do quality code by creating cross validation and check all the model accuracy at once. After that we will select one model based on it's accuracy.\n<a id=\"subsection-twentysix\"><\/a>\n## Model Selection\nLet's dig onto select the best classifier model \n\"\"\"\n#creating the objects\nlogreg_cv = LogisticRegression(random_state=0)\ndt_cv=DecisionTreeClassifier()\nknn_cv=KNeighborsClassifier()\nsvc_cv=SVC()\nnb_cv=BernoulliNB()\ncv_dict = {0: 'Logistic Regression', 1: 'Decision Tree',2:'KNN',3:'SVC',4:'Naive Bayes'}\ncv_models=[logreg_cv,dt_cv,knn_cv,svc_cv,nb_cv]\n\n\nfor i,model in enumerate(cv_models):\n    print(\"{} Test Accuracy: {}\".format(cv_dict[i],cross_val_score(model, X, y, cv=10, scoring ='accuracy').mean()))\n\"\"\"\nFrom the test results, we can see high accuracy in SVC followed by Logistic regression. Let's fit and predict\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentyseven\"><\/a>\n## Logistic regression with Hyperparameter tuning\nLet's fit the model in logistic regression with parameter tuning and figure out the accuracy of our model\n\"\"\"\nparam_grid = {'C': np.logspace(-4, 4, 50),\n             'penalty':['l1', 'l2']}\nclf = GridSearchCV(LogisticRegression(random_state=0), param_grid,cv=5, verbose=0,n_jobs=-1)\nbest_model = clf.fit(X_train,y_train)\nprint(best_model.best_estimator_)\nprint(\"The mean accuracy of the model is:\",best_model.score(X_test,y_test))\n\"\"\"\nWe have got the best parameters for the model and the mean accuracy is 92.4%\n\"\"\"\nlogreg = LogisticRegression(C=0.18420699693267145, random_state=0)\nlogreg.fit(X_train, y_train)\ny_pred = logreg.predict(X_test)\nprint('Accuracy of logistic regression classifier on test set: {:.2f}'.format(logreg.score(X_test, y_test)))\n\"\"\"\n92% accurate. That's really good. Let's check out confusion matrix and see the classification report\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\\n\",confusion_matrix)\nprint(\"Classification Report:\\n\",classification_report(y_test, y_pred))\n\"\"\"\n**Insights:**\n\n* The Confusion matrix result is telling us that we have **6399+178** correct predictions and **397+139** incorrect predictions.\n* The Classification report reveals that we have **94%** precision which means the accuracy that the model classifier not to label an instance positive that is actually negative which is important as we shouldn't label a lead as positive in making a term deposit when he\/she isn't interested in making a deposit\n\"\"\"\n\"\"\"\n### ROC Curve\nLet's check out the performance of our model through ROC curve\n\"\"\"\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nlogit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))\nfpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])\nplt.figure()\nplt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([-0.01, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\n\"\"\"\nFrom the ROC curve we can infer that our logistic model has classified the prospective leads who made deposit correctly rather than predicting false positive. The more the ROC curve(red) lies towards the top left side the better our model is. We can choose any value between **0.8 to 0.9** for the threshold value which can reap us true positive results\n\"\"\"\n\"\"\"\n<a id=\"subsection-twentyeight\"><\/a>\n## Support vector classifier\nLet's fit our best model from model selection and predict outcome.\n\n**Note: Hyperparameter tuning of SVM took more than hours to run in my device. So I'm bypassing hyperparameter tuning for this section.**\n\"\"\"\nsvc_classifier = SVC(random_state = 0)\nsvc_classifier.fit(X_train,y_train)\ny_pred=svc_classifier.predict(X_test)\n\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\nprint(\"Classification Report:\\n\",classification_report(y_test,y_pred))\n\"\"\"\nWe have 91% accuracy and Also we have 92% precision\n\"\"\"\n\"\"\"\n<a id=\"section-six\"><\/a>\n# Conclusion\n![11.jpg](attachment:11.jpg)\nFrom the EDA and model selection part we can clearly identify duration playing an important attribute in defining the outcome of our dataset. It is absolute that the more the leads are interested in starting a deposit will have higher number of calls and the call duration will be higher than the average. We have also figured out that job and education also acts as a crucial deciding factor and influences the outcome alot.\n\nHere are the few recommendations for the bank than can help improve the deposit rate\n\n* Classify job roles based on corporate tiers and approach all tier 1 employees within few days after the campaign commences\n* Listen to the leads and extract more information to deliver the best deposit plan, which can increase the duration of calls and that can lead to a deposit\n* Approaching the leads during the start of new bank period(May-July) will be a good choice as many have shown positive results from data history\n* Tune the campaign according to the national econometrics, don't chanelize the expenses on campaign when the national economy is performing poor\n\n\"\"\"\n\"\"\"\n## Please leave critical feedback in comment section, also check out my [other notebooks](https:\/\/www.kaggle.com\/notebooks?sortBy=dateRun&group=profile&pageSize=20)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dcc2449d9ac9ab'}"}
{"id":"38154","text":"\"\"\"\n### **What we need to solve the problem:**\n* Initial step\n    * git init\n    * import libraries\n    * etc\n* Data processing\n    * Plotting random images\n    * Split data\n    * Define resizing if it needed\n* Build the model\n    * Build a network\n    * Run it\n    * Plot acc and loss\n    * Repeat\n* Evaluate on test data\n\"\"\"\n\"\"\"\n### **Initial step**\nBasic initial step, import required libraries, etc\n\n*   os - for handling paths\n*   cv2 - best lib for image processing\n*   matplotlib - plot images and results\n*   zipfile - obviously work with zip archives\n*   tensorflow - self-explanatory\n*   randrange - we will use for selecting random images\n*   shutil - for copying\/moving images to a different folder\n\n\"\"\"\n%matplotlib inline\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import Adam\nfrom random import randrange\nfrom shutil import copytree, move, rmtree\n\"\"\"\n### Data processing\nSince the \"input\" folder is read-only we need to copy files for future manipulation.\nThis workbook allows just copy from zipping without unzipping operation.\n\"\"\"\nINPUT_DATA_DIR = '..\/input\/cell_images\/cell_images'\nROOT_DATA_DIR = '..\/cell_images'\ncopytree(INPUT_DATA_DIR, ROOT_DATA_DIR)\n\"\"\"\nLet's define the paths of data and explore how many images we have.\n\"\"\"\nINF_DIR = os.path.join(ROOT_DATA_DIR, 'Parasitized')\nUNINF_DIR = os.path.join(ROOT_DATA_DIR, 'Uninfected')\n\ninf_fnames = os.listdir(INF_DIR)\nuninf_fnames = os.listdir(UNINF_DIR)\n\nprint(f'Amount of parasitized images: {len(inf_fnames)}')\nprint(f'Amount of uninfected images: {len(uninf_fnames)}')\nprint(f'Total Images: {len(inf_fnames) + len(uninf_fnames)}')\n\"\"\"\nDefine the matplotlib figure and plot 4 Parasitized and 4 Uninfected images.\n\nHere I use randrange for selecting a random image index. Rerun the cell for ploting different image.\n\"\"\"\nnrows, ncols = 4, 4\nfig_size = 3 \n\nfig = plt.gcf()\nfig.set_size_inches(ncols * fig_size, nrows * fig_size)\n\ninf_pic_paths = [os.path.join(INF_DIR, inf_fnames[randrange(len(inf_fnames))]) \n                for _ in range(4) \n                ]\n\nuninf_pic_paths = [os.path.join(UNINF_DIR, uninf_fnames[randrange(len(uninf_fnames))]) \n                for _ in range(4) \n                ]\n\nfor i, img_path in enumerate(inf_pic_paths + uninf_pic_paths):  \n    sp = plt.subplot(nrows, ncols, i + 1)\n    sp.axis('Off') # Don't show axes (or gridlines)\n\n    img = mpimg.imread(img_path)\n    plt.imshow(img)\n\nplt.show()\n\"\"\"\nDefine the function that will split the data.\n\nIt's pretty simple. \n\nDefining names \/ create folder \/ moving images.\n\"\"\"\ndef split_data(sourse, split_size):\n    #Create root folder for valid&test data\n    root_folder_name = ROOT_DATA_DIR.strip('\/').split('\/')[-1]\n    valid_test_folder = ROOT_DATA_DIR.replace(root_folder_name,\n                                            'valid_test_' + root_folder_name)\n    try:\n        os.mkdir(valid_test_folder)\n    except:\n        pass\n    \n    folders = os.listdir(sourse)\n    for folder in folders:\n        try:\n            os.mkdir(os.path.join(valid_test_folder, folder))\n        except:\n            pass\n        fnames = os.listdir(os.path.join(sourse, folder))\n        start_split = len(fnames) - int(len(fnames) * split_size)\n        splited_fnames = fnames[start_split:]\n        for fname in splited_fnames:\n            s_dir = os.path.join(sourse, folder, fname)\n            d_dir = os.path.join(valid_test_folder, folder, fname)\n            move(s_dir, d_dir)\n        print(f'Moved {len(splited_fnames)} files')\n\n\"\"\"\nCall the function.\n\n*hint. If you want plot images after splitting you will need to redefine file names. Just rerun the cell above the plot.*\n\"\"\"\nsplit_data(ROOT_DATA_DIR, 0.2)\n\"\"\"\nOur data set contain images with 150 by 150 pixels.\n\nI found that for this problem we don't need such resolution so I decide to resize the image.\n\nTo find out how it will look I use cv2 for resizing and plot the image.\n\"\"\"\nimg_size = 64\ndim = img_size, img_size\n\nimg_path = os.path.join(INF_DIR, inf_fnames[0])\nimg = cv2.imread(img_path)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nimg = cv2.resize(img, dim)\n\nplt.imshow(img)\nplt.show()\n\"\"\"\nAfter splitting we have 2 folders. One contains a training set and another for validation and test sets.\n\nLet's define training generator and add some image augmentation.\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n        rescale=1.\/255,\n        rotation_range=45,\n        shear_range=0.2,\n        vertical_flip=True,\n        horizontal_flip=True,\n        )\n\ntrain_generator = train_datagen.flow_from_directory(\n        '..\/cell_images',  \n        target_size=dim, \n        batch_size=32,\n        class_mode='binary',\n        )\n\"\"\"\nNow I define validation and test generator.\n\nI use build in functionality for splitting one folder into two sets.\n\nSinge validation and test set should be from one distribution. This is a perfect solution.\n\"\"\"\nvalid_test_datagen = ImageDataGenerator(\n        rescale=1.\/255,\n        validation_split=0.5\n        )\n\nvalid_generator = valid_test_datagen.flow_from_directory(\n        '..\/valid_test_cell_images',  \n        target_size=dim, \n        batch_size=32,\n        class_mode='binary',\n        subset='training',\n        )\n\ntest_generator = valid_test_datagen.flow_from_directory(\n        '..\/valid_test_cell_images',  \n        target_size=dim, \n        batch_size=32,\n        class_mode='binary',\n        subset='validation',\n        )\n\"\"\"\n### Build the model\nDefine the model.\n\nThis is our playground. Add and delete layers, try to find a perfect solution.\n\"\"\"\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', padding='same', input_shape=(64, 64, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D(2, 2), \n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dropout(0.5),\n    \n    tf.keras.layers.Dense(1024, activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.5),\n    \n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.5),\n    \n    tf.keras.layers.Dense(1, activation='sigmoid')\n])\n\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['acc'])\n\"\"\"\nExplore our model.\n\"\"\"\nmodel.summary()\n\"\"\"\nFinally lets train the model.\n\nI don't define steps_per_epoch since according to official documentation when we use the sequential model we don't need to do this.\n\nLts's try 50 epoch.\n\"\"\"\nhistory = model.fit_generator(\n        train_generator,\n        epochs=20,\n        validation_data=valid_generator,\n        )\n\"\"\"\nPlot our accuracy and loss for understanding problems: \"high bias\" and \"high variance\".\n\"\"\"\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\"\"\"\n### Evaluate on test data\nAfter finishing playing with model and we are happy with achieved accuracy.\n\nEvaluate your model on the test set.\n\"\"\"\nmodel.evaluate_generator(test_generator, verbose=1)\n\"\"\"\nAfter ~50 epochs acc will be > 97%\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '464c123dcc65ce'}"}
{"id":"7984","text":"import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split, cross_val_score, RepeatedStratifiedKFold, GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, make_scorer, recall_score, roc_auc_score\nfrom xgboost import XGBClassifier, plot_importance\nfrom pdpbox import pdp, get_dataset, info_plots\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline\n\"\"\"\nThe dataset is from kaggle [data](https:\/\/www.kaggle.com\/santoshd3\/bank-customers)   \n\"\"\"\ndf = pd.read_csv('..\/input\/bank-customers\/Churn Modeling.csv')\ndf.head()\ndf.info()\n\"\"\"\nWe can see there are no missing values. The datatypes are all good. \n\"\"\"\nprint(df.columns)\ndf.drop(df.columns[[0,1]], axis=1, inplace=True)\n\nunique_vals = {}\nprint('Unique values for each feature:\\n')\nfor column in df.columns:\n    unique_vals[column]=df[column].unique()\n    print(len(unique_vals[column]), 'unique values of ', column)\n\"\"\"\nNo replicated CustomerId. Numbers of unique values of Gender, HasCrCard, IsActiveMember, Exited are legit.\n\"\"\"\nfig, axes = plt.subplots(4, 3, figsize=(15,15))\nsns.histplot(ax=axes[0, 0], data=df, x=\"CreditScore\", hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[0, 1], data=df, x='Age', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[0, 2], data=df, x='Tenure', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[1, 0], data=df, x='Balance', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[1, 1], data=df, x='NumOfProducts', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[1, 2], data=df, x='EstimatedSalary', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[2, 0], data=df, x='Geography', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[2, 1], data=df, x='Gender', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[2, 2], data=df, x='HasCrCard', hue=\"Exited\", multiple=\"stack\")\nsns.histplot(ax=axes[3, 0], data=df, x='IsActiveMember', hue=\"Exited\", multiple=\"stack\")\n\"\"\"\nWe can see generally, customers from the following groups are more likely to exit: \n1. Over the age of 40.\n2. From Germany.\n3. Female.\n\nCustomers from the following groups are less likely to exit: \n1. Having 2 products.\n2. Active members. \n\"\"\"\ncols = ['CreditScore', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'EstimatedSalary', 'Exited']\nsns.pairplot(df[cols], hue='Exited', kind='hist', height=2)\nplt.show();\n# encode the categorical features\ncat_features = ['Geography', 'Gender']\nohe = OneHotEncoder(sparse=False, dtype='int64', drop='if_binary')\ncat_encoded = ohe.fit_transform(df[cat_features])\ncolumn_name = ohe.get_feature_names(cat_features)\nohe_frame =  pd.DataFrame(cat_encoded, columns= column_name)\ndf = pd.concat([df.select_dtypes(exclude='object'), ohe_frame], axis=1)\n#df.info()\ncorrmatrix = df.corr()\nf, ax = plt.subplots(figsize=(12, 9))\nax = sns.heatmap(corrmatrix, vmax=.8, square=True, annot=True, cmap=\"YlGnBu\")\n\"\"\"\nSomething interesting: Balance of customers from different countries varies a lot. \n\"\"\"\nX = df.drop(['Exited'], axis=1)\ny = df['Exited']\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=4)\n\nparam_grid = {'max_depth':range(3,15),'criterion':['gini','entropy']}\nrf = RandomForestClassifier(random_state=4)\nmodel_rf = GridSearchCV(rf, param_grid=param_grid)\nmodel_rf.fit(X_train, y_train)\npred_test = model_rf.predict(X_test)\nprint('Classification Report of RandomForestClassifier: \\n', classification_report(y_test, pred_test))\n#scores = cross_val_score(model_rf, X, y, scoring='roc_auc')\n#roc_auc_score(y_test, model_rf.predict_proba(X_test)[:, 1], average='weighted')\n#print ('cross validation score of RandomForestClassifier: %.8f'%scores.mean())\n\"\"\"\nWe can see the recall is not good, meaning a lot of false negatives. Let's try to improve that if we don't want to miss potentially positive cases. \n\"\"\"\nrf1 = model_rf.best_estimator_\nimportances1 = rf1.feature_importances_\nfeature_importances = pd.Series(importances1, index=X.columns)\nfeature_importances.nlargest(12).plot(kind='barh')\nrf2 = RandomForestClassifier(random_state=4, class_weight={0:1,1:5})\n# For imbalanced sample: less 'Exited'=1 present, give 'Exited'=1 more weight. \nscorer = make_scorer(recall_score)\nmodel_rf2 = GridSearchCV(rf2, param_grid=param_grid, scoring=scorer)\nmodel_rf2.fit(X_train, y_train)\npred_test = model_rf2.predict(X_test)\nprint('Classification Report of RandomForestClassifier: \\n', classification_report(y_test, pred_test))\n\"\"\"\nIt seems we achieve a good recall though the accuracy is relatively low. We need to tune the model according to our business objectives, like intervening before the exiting happens. In such cases, we may be willing to sacrifice accuracy for recall.\n\"\"\"\nbest_rf = model_rf2.best_estimator_\nimportances = best_rf.feature_importances_\nfeature_importances = pd.Series(importances, index=X.columns)\nfeature_importances.nlargest(12).plot(kind='barh')\nfor target_feature in ['Age', 'NumOfProducts', 'IsActiveMember']:\n    pdp_i = pdp.pdp_isolate(model=best_rf, dataset=X, model_features=X.columns, feature=target_feature)\n    pdp.pdp_plot(pdp_i, target_feature, figsize=(8,5))\n\"\"\"\nLet's try another model:\n\"\"\"\nxgb = XGBClassifier()\n\"\"\"\nparam_grid = {'learning_rate': [0.01, 0.05], \n#        'min_child_weight': [1, 5],\n#        'subsample': [0.6, 0.8],\n#        'colsample_bytree': [0.6, 0.8, 1.0],\n        'max_depth': [5, 8],\n#        'n_estimators': [100, 500]\n        }\n\nmodel_xgb = GridSearchCV(estimator=xgb, param_grid=param_grid, scoring='roc_auc')\n\"\"\"\nxgb.fit(X_train, y_train)\npred_test = xgb.predict(X_test)\nprint('Classification Report of XGBClassifier: \\n', classification_report(y_test, pred_test))\n#scores = cross_val_score(model_xgb, X, y, scoring='roc_auc')\n#print ('cross validation score of XGBClassifier: %.8f'%scores.mean())\nxgb = XGBClassifier(scale_pos_weight=5)\nxgb.fit(X_train, y_train)\npred_test = xgb.predict(X_test)\nprint('Classification Report of XGBClassifier: \\n', classification_report(y_test, pred_test))\nplot_importance(xgb)","meta":"{'source': 'AI4Code', 'id': '0ecca6c422e224'}"}
{"id":"75825","text":"\"\"\"\n# Task for Today  \n\n***\n\n## Company Market Cap Prediction  \n  \nGiven *data about big companies*, let's try to predict the **market capitalization** of a given company.  \n  \nWe will use a variety of regression models to make our predictions.\n\"\"\"\n\"\"\"\n# Getting Started\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n\nimport warnings\nwarnings.filterwarnings(action='ignore')\ndata = pd.read_csv('..\/input\/fortune-500-data-2021\/Fortune_1000.csv')\ndata\ndata.info()\n\"\"\"\n# Preprocessing\n\"\"\"\ndef preprocess_inputs(df):\n    df = df.copy()\n    \n    # Drop unused columns\n    df = df.drop(['rank', 'rank_change', 'company', 'newcomer', 'prev_rank', 'CEO', 'Website', 'Ticker'], axis=1)\n    \n    # Encode missing values\n    df['Market Cap'] = df['Market Cap'].replace('-', np.NaN).astype(np.float)\n    \n    # Drop missing target rows\n    missing_target_rows = df[df['Market Cap'].isna()].index\n    df = df.drop(missing_target_rows, axis=0).reset_index(drop=True)\n    \n    # Fill remaining missing values\n    df['profit'] = df['profit'].fillna(df['profit'].mean())\n    \n    # Binary encoding\n    for column in ['ceo_founder', 'ceo_woman', 'profitable']:\n        df[column] = df[column].replace({'no': 0, 'yes': 1})\n    \n    # One-hot encoding\n    for column in ['sector', 'city', 'state']:\n        dummies = pd.get_dummies(df[column], prefix=column)\n        df = pd.concat([df, dummies], axis=1)\n        df = df.drop(column, axis=1)\n    \n    # Split df into X and y\n    y = df['Market Cap']\n    X = df.drop('Market Cap', axis=1)\n    \n    # Train-test split\n    X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, shuffle=True, random_state=1)\n    \n    # Scale X\n    scaler = StandardScaler()\n    scaler.fit(X_train)\n    X_train = pd.DataFrame(scaler.transform(X_train), index=X_train.index, columns=X_train.columns)\n    X_test = pd.DataFrame(scaler.transform(X_test), index=X_test.index, columns=X_test.columns)\n    \n    return X_train, X_test, y_train, y_test\nX_train, X_test, y_train, y_test = preprocess_inputs(data)\nX_train\ny_train\n\"\"\"\n# Training\n\"\"\"\nmodels = {\n    \"     Linear Regression\": LinearRegression(),\n    \"Linear Regression (L2)\": Ridge(),\n    \"Linear Regression (L1)\": Lasso(),\n    \"         Decision Tree\": DecisionTreeRegressor(),\n    \"        Neural Network\": MLPRegressor(),\n    \"         Random Forest\": RandomForestRegressor(),\n    \"     Gradient Boosting\": GradientBoostingRegressor()\n}\n\nfor name, model in models.items():\n    model.fit(X_train, y_train)\n    print(name + \" trained.\")\n\"\"\"\n# Results\n\"\"\"\nfor name, model in models.items():\n    y_pred = model.predict(X_test)\n    rmse = np.sqrt(np.mean((y_test - y_pred)**2))\n    print(name + \" RMSE: {:.2f}\".format(rmse))\nfor name, model in models.items():\n    r2 = model.score(X_test, y_test)\n    print(name + \" R^2 Score: {:.5f}\".format(r2))\n\"\"\"\n# Data Every Day  \n\nThis notebook is featured on Data Every Day, a YouTube series where I train models on a new dataset each day.  \n\n***\n\nCheck it out!  \nhttps:\/\/youtu.be\/fiwSBIS6N9c\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8b59cf3d00a5ba'}"}
{"id":"138953","text":"# What this is doing? please refer to my above linked kernel\n#!pip install ..\/input\/pretrainedmodels\/pretrainedmodels-0.7.4\/pretrainedmodels-0.7.4\/ > \/dev\/null\npackage_path = '..\/input\/underscripts\/'\nimport sys\nsys.path.append(package_path)\nimport pdb\nimport os\nimport cv2\nimport torch\nimport time\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader, Dataset\nfrom  albumentations  import (\n    HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,\n    Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,\n    IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine,\n    IAASharpen, IAAEmboss, RandomContrast, RandomBrightness, Flip, OneOf, Compose,NoOp,Normalize\n) # \u56fe\u50cf\u53d8\u6362\u51fd\u6570\nfrom albumentations.torch import ToTensor\nimport warnings\nimport random\nwarnings.filterwarnings(\"ignore\")\nseed = 69\nrandom.seed(seed)\nos.environ[\"PYTHONHASHSEED\"] = str(seed)\nnp.random.seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.backends.cudnn.deterministic = True\nimport torch.utils.data as data\nfrom model import Unet\nfrom upp_model import UPPnet\nfrom sklearn.model_selection import StratifiedKFold\n# some preprocessing\n# https:\/\/www.kaggle.com\/amanooo\/defect-detection-starter-u-net\ntrain = pd.read_csv('..\/input\/severstal-steel-defect-detection\/train.csv')\ntrain['ImageId'], train['ClassId'] = zip(*train['ImageId_ClassId'].str.split('_'))\ntrain['ClassId'] = train['ClassId'].astype(int)\ntrain = train.pivot(index='ImageId',columns='ClassId',values='EncodedPixels')\ntrain['defects'] = train.count(axis=1)\ntrain = train.reset_index()\nskf = StratifiedKFold(n_splits=5,random_state=42)\nfor i,(trn_idx,val_idx)in enumerate(skf.split(train,train[\"defects\"])):\n    train_fold = train.iloc[trn_idx]\n    valid_fold = train.iloc[val_idx]\n    train_fold.to_csv(\".\/train_fold_{}.csv\".format(i),index=False)\n    valid_fold.to_csv(\".\/valid_fold_{}.csv\".format(i),index=False)\n#https:\/\/www.kaggle.com\/paulorzp\/rle-functions-run-lenght-encode-decode\ndef mask2rle(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels= img.T.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\ndef make_mask(row_id, df):\n    '''Given a row index, return image_id and mask (256, 1600, 4)'''\n    fname = df.iloc[row_id][\"ImageId\"]\n    labels = df.iloc[row_id][1:5]\n    masks = np.zeros((256, 1600, 4), dtype=np.float32) # float32 is V.Imp\n    # 4:class 1\uff5e4 (ch:0\uff5e3)\n\n    for idx, label in enumerate(labels.values):\n        if label is not np.nan:\n            label = label.split(\" \")\n            positions = map(int, label[0::2])\n            length = map(int, label[1::2])\n            mask = np.zeros(256 * 1600, dtype=np.uint8)\n            for pos, le in zip(positions, length):\n                mask[pos:(pos + le)] = 1\n            masks[:, :, idx] = mask.reshape(256, 1600, order='F')\n    return fname, masks\nclass SteelDataset(Dataset):\n    def __init__(self, df, data_folder, mean, std, phase):\n        self.df = df\n        self.root = data_folder\n        self.mean = mean\n        self.std = std\n        self.phase = phase\n        self.transforms = get_transforms(phase, mean, std)\n        self.fnames = self.df.index.tolist()\n\n    def __getitem__(self, idx):\n        image_id, mask = make_mask(idx, self.df)\n        image_path = os.path.join(self.root, \"train_images\",  image_id)\n        img = cv2.imread(image_path)\n        augmented = self.transforms(image=img, mask=mask)\n        img = augmented['image']\n        mask = augmented['mask'] # 1x256x1600x4\n        mask = mask[0].permute(2, 0, 1) # 1x4x256x1600\n        return img, mask\n\n    def __len__(self):\n        return len(self.fnames)\n\n\ndef get_transforms(phase, mean, std):\n    list_transforms = []\n    if phase == \"train\":\n        list_transforms.extend(\n            [OneOf([\n                HorizontalFlip(),\n                ShiftScaleRotate(p=1),\n                NoOp(),\n            ]),\n            OneOf([\n                Blur(blur_limit=2,p=0.1),\n                GaussNoise(),\n                NoOp(),\n            ]),\n            OneOf([\n                CLAHE(clip_limit=0.8),\n                NoOp(),\n            ])\n            ]\n        )\n    list_transforms.extend(\n        [\n            Normalize(mean=mean, std=std, p=1),\n            ToTensor(),\n        ]\n    )\n    list_trfms = Compose(list_transforms)\n    return list_trfms\n\ndef provider(\n    data_folder,\n    df_path,\n    phase,\n    mean=None,\n    std=None,\n    batch_size=8,\n    num_workers=4,\n):\n    '''Returns dataloader for the model training'''\n    df = pd.read_csv(df_path)\n    \n    image_dataset = SteelDataset(df, data_folder, mean, std, phase)\n    if phase==\"train\":\n        dataloader = DataLoader(\n            image_dataset,\n            batch_size=batch_size,\n            num_workers=num_workers,\n            pin_memory=False,\n            shuffle=True,   \n        )\n    else:\n        dataloader = DataLoader(\n            image_dataset,\n            batch_size=batch_size,\n            num_workers=num_workers,\n            pin_memory=False,\n            shuffle=False\n        )\n    return dataloader\ndef predict(X, threshold):\n    '''X is sigmoid output of the model'''\n    X_p = np.copy(X)\n    preds = (X_p > threshold).astype('uint8')\n    return preds\n\ndef metric(probability, truth, threshold=0.5, reduction='none'):\n    '''Calculates dice of positive and negative images seperately'''\n    '''probability and truth must be torch tensors'''\n    batch_size = len(truth)\n    with torch.no_grad():\n        probability = probability.view(batch_size, -1)\n        truth = truth.view(batch_size, -1)\n        assert(probability.shape == truth.shape)\n\n        p = (probability > threshold).float()\n        t = (truth > 0.5).float()\n\n        t_sum = t.sum(-1)\n        p_sum = p.sum(-1)\n        neg_index = torch.nonzero(t_sum == 0)\n        pos_index = torch.nonzero(t_sum >= 1)\n\n        dice_neg = (p_sum == 0).float()\n        dice_pos = 2 * (p*t).sum(-1)\/((p+t).sum(-1))\n\n        dice_neg = dice_neg[neg_index]\n        dice_pos = dice_pos[pos_index]\n        dice = torch.cat([dice_pos, dice_neg])\n\n        dice_neg = np.nan_to_num(dice_neg.mean().item(), 0)\n        dice_pos = np.nan_to_num(dice_pos.mean().item(), 0)\n        dice = dice.mean().item()\n\n        num_neg = len(neg_index)\n        num_pos = len(pos_index)\n\n    return dice, dice_neg, dice_pos, num_neg, num_pos\n\nclass Meter:\n    '''A meter to keep track of iou and dice scores throughout an epoch'''\n    def __init__(self, phase, epoch):\n        self.base_threshold = 0.5 # <<<<<<<<<<< here's the threshold\n        self.base_dice_scores = []\n        self.dice_neg_scores = []\n        self.dice_pos_scores = []\n        self.iou_scores = []\n\n    def update(self, targets, outputs):\n        probs = torch.sigmoid(outputs)\n        dice, dice_neg, dice_pos, _, _ = metric(probs, targets, self.base_threshold)\n        self.base_dice_scores.append(dice)\n        self.dice_pos_scores.append(dice_pos)\n        self.dice_neg_scores.append(dice_neg)\n        preds = predict(probs, self.base_threshold)\n        iou = compute_iou_batch(preds, targets, classes=[1])\n        self.iou_scores.append(iou)\n\n    def get_metrics(self):\n        dice = np.mean(self.base_dice_scores)\n        dice_neg = np.mean(self.dice_neg_scores)\n        dice_pos = np.mean(self.dice_pos_scores)\n        dices = [dice, dice_neg, dice_pos]\n        iou = np.nanmean(self.iou_scores)\n        return dices, iou\n\ndef epoch_log(phase, epoch, epoch_loss, meter, start):\n    '''logging the metrics at the end of an epoch'''\n    dices, iou = meter.get_metrics()\n    dice, dice_neg, dice_pos = dices\n    print(\"Loss: %0.4f | IoU: %0.4f | dice: %0.4f | dice_neg: %0.4f | dice_pos: %0.4f\" % (epoch_loss, iou, dice, dice_neg, dice_pos))\n    return dice, iou\n\ndef compute_ious(pred, label, classes, ignore_index=255, only_present=True):\n    '''computes iou for one ground truth mask and predicted mask'''\n    pred[label == ignore_index] = 0\n    ious = []\n    for c in classes:\n        label_c = label == c\n        if only_present and np.sum(label_c) == 0:\n            ious.append(np.nan)\n            continue\n        pred_c = pred == c\n        intersection = np.logical_and(pred_c, label_c).sum()\n        union = np.logical_or(pred_c, label_c).sum()\n        if union != 0:\n            ious.append(intersection \/ union)\n    return ious if ious else [1]\n\ndef compute_iou_batch(outputs, labels, classes=None):\n    '''computes mean iou for a batch of ground truth masks and predicted masks'''\n    ious = []\n    preds = np.copy(outputs) # copy is imp\n    labels = np.array(labels) # tensor to np\n    for pred, label in zip(preds, labels):\n        ious.append(np.nanmean(compute_ious(pred, label, classes)))\n    iou = np.nanmean(ious)\n    return iou\n!ls ..\/input\/uppres18\/\n#model = Unet(encoder_type=\"resnet\",encoder_name=\"resnet18\",classes=4,activation=None)\nmodel = UPPnet(encoder_type=\"resnet\",encoder_name=\"resnet18\",classes=4,activation=None)\nckpt_path = \"..\/input\/uppres18\/upp-resnet18_fold_3.pth\"\ndevice = torch.device(\"cuda\")\nmodel.to(device)\nstate = torch.load(ckpt_path,map_location=lambda storage,loc:storage)\nmodel.load_state_dict(state[\"state_dict\"])\n\"\"\"\n**CyclicLR**\n\"\"\"\n# code inspired from: https:\/\/github.com\/anandsaha\/pytorch.cyclic.learning.rate\/blob\/master\/cls.py\nfrom torch.optim.optimizer import Optimizer\nclass CyclicLR(object):\n    def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,\n                 step_size=2000, mode='triangular', gamma=1.,\n                 scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):\n\n        if not isinstance(optimizer, Optimizer):\n            raise TypeError('{} is not an Optimizer'.format(\n                type(optimizer).__name__))\n        self.optimizer = optimizer\n        self.lr_history = []\n        if isinstance(base_lr, list) or isinstance(base_lr, tuple):\n            if len(base_lr) != len(optimizer.param_groups):\n                raise ValueError(\"expected {} base_lr, got {}\".format(\n                    len(optimizer.param_groups), len(base_lr)))\n            self.base_lrs = list(base_lr)\n        else:\n            self.base_lrs = [base_lr] * len(optimizer.param_groups)\n\n        if isinstance(max_lr, list) or isinstance(max_lr, tuple):\n            if len(max_lr) != len(optimizer.param_groups):\n                raise ValueError(\"expected {} max_lr, got {}\".format(\n                    len(optimizer.param_groups), len(max_lr)))\n            self.max_lrs = list(max_lr)\n        else:\n            self.max_lrs = [max_lr] * len(optimizer.param_groups)\n\n        self.step_size = step_size\n\n        if mode not in ['triangular', 'triangular2', 'exp_range'] \\\n                and scale_fn is None:\n            raise ValueError('mode is invalid and scale_fn is None')\n\n        self.mode = mode\n        self.gamma = gamma\n        \n        #scheduler althorighms\n        if scale_fn is None:\n            if self.mode == 'triangular':\n                self.scale_fn = self._triangular_scale_fn\n                self.scale_mode = 'cycle'\n            elif self.mode == 'triangular2':\n                self.scale_fn = self._triangular2_scale_fn\n                self.scale_mode = 'cycle'\n            elif self.mode == 'exp_range':\n                self.scale_fn = self._exp_range_scale_fn\n                self.scale_mode = 'iterations'\n        else:\n            self.scale_fn = scale_fn\n            self.scale_mode = scale_mode\n        \n        self.batch_step(last_batch_iteration + 1)\n        self.last_batch_iteration = last_batch_iteration\n\n    def batch_step(self, batch_iteration=None):\n        if batch_iteration is None:\n            batch_iteration = self.last_batch_iteration + 1\n        self.last_batch_iteration = batch_iteration\n        for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):\n            param_group['lr'] = lr\n\n    def _triangular_scale_fn(self, x):\n        return 1.\n\n    def _triangular2_scale_fn(self, x):\n        return 1 \/ (2. ** (x - 1))\n\n    def _exp_range_scale_fn(self, x):\n        return self.gamma**(x)\n\n    def get_lr(self):\n        step_size = float(self.step_size)\n        #why 2* step_size?\n        cycle = np.floor(1 + self.last_batch_iteration \/ (2 * step_size))\n        x = np.abs(self.last_batch_iteration \/ step_size - 2 * cycle + 1)\n\n        lrs = []\n        param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)\n        for param_group, base_lr, max_lr in param_lrs:\n            base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))\n            if self.scale_mode == 'cycle':\n                lr = base_lr + base_height * self.scale_fn(cycle)\n            else:\n                lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)\n            lrs.append(lr)\n        self.lr_history.append(lrs)\n        return lrs\n\"\"\"\n**Dice Loss**\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\ntry:\n    from itertools import  ifilterfalse\nexcept ImportError: # py3k\n    from itertools import  filterfalse as ifilterfalse\n    \n\"\"\"\n===================================\nDice Loss\n\"\"\"\ndef make_one_hot(input,num_classes):\n    \"\"\"Convert class index tensor to one hot encoding tensor.\n    Args:\n         input: A tensor of shape [N, 1, *]\n         num_classes: An int of number of class\n    Returns:\n        A tensor of shape [N, num_classes, *]\n    \"\"\"\n    shape = np.array(input.shape)\n    shape[1] = num_classes\n    shape = tuple(shape)\n    result = torch.zeros(shape)\n    result = result.scatter_(1,input.cpu(),1)\n    return result\n\nclass BinaryDiceLoss(nn.Module):\n    \"\"\"Dice loss of binary class\n    Args:\n        smooth: A float number to smooth loss, and avoid NaN error, default: 1\n        p: Denominator value: \\sum{x^p} + \\sum{y^p}, default: 2\n        predict: A tensor of shape [N, *]\n        target: A tensor of shape same with predict\n        reduction: Reduction method to apply, return mean over batch if 'mean',\n            return sum if 'sum', return a tensor of shape [N,] if 'none'\n    Returns:\n        Loss tensor according to arg reduction\n    Raise:\n        Exception if unexpected reduction\n    \"\"\"\n    def __init__(self, smooth=1, p=1, reduction='mean'):\n        super(BinaryDiceLoss, self).__init__()\n        self.smooth = smooth\n        self.p = p\n        self.reduction = reduction\n        \n    def forward(self, predict, target):\n        assert predict.shape[0] == target.shape[0], \"predict & target batch size don't match\"\n        predict = predict.contiguous().view(predict.shape[0], -1)\n        target = target.contiguous().view(target.shape[0], -1)\n        \n        if torch.sum(target)>0:\n            num = torch.sum(torch.mul(F.sigmoid(predict),target),dim=1)+self.smooth\n            den = torch.sum(F.sigmoid(predict)+target,dim=1)+self.smooth\n\n            num_ = torch.sum(torch.mul(F.sigmoid(-predict),1-target),dim=1)+self.smooth\n            den_ = torch.sum(F.sigmoid(-predict)+(1-target),dim=1)+self.smooth\n\n            loss_1 = 1-num\/den\n            loss_2 = 1-num_\/den_\n            return (loss_1.sum()+loss_2.sum())\/2\n        else:#no loss for no signals samples\n            return Variable(torch.FloatTensor([0]),requires_grad=True).cuda()[0]\n\nclass DiceLoss(nn.Module):\n    \"\"\"Dice loss, need one hot encode input\n    Args:\n        weight: An array of shape [num_classes,]\n        ignore_index: class index to ignore\n        predict: A tensor of shape [N, C, *]\n        target: A tensor of same shape with predict\n        other args pass to BinaryDiceLoss\n    Return:\n        same as BinaryDiceLoss\n    \"\"\"\n    def __init__(self,weight=None,ignore_index=None,**kwargs):\n        super(DiceLoss, self).__init__()\n        self.kwargs = kwargs\n        self.weight = weight\n        self.ignore_index = ignore_index\n        \n    def forward(self,predict,target):\n        assert predict.shape == target.shape, 'predict & target shape do not match'\n        dice = BinaryDiceLoss(**self.kwargs)\n        total_loss = 0\n        #predict = F.softmax(predict,dim=1)\n        for i in range(target.shape[1]):\n            if i != self.ignore_index:\n                dice_loss = dice(predict[:, i], target[:, i])\n                if self.weight is not None:\n                    assert self.weight.shape[0] == target.shape[1], \\\n                        'Expect weight shape [{}], get[{}]'.format(target.shape[1], self.weight.shape[0])\n                    dice_loss *= self.weights[i]\n                total_loss += dice_loss\n        return total_loss\/target.shape[1]\nclass SingleFoldTrainer(object):\n    '''This class takes care of training and validation of our model'''\n    def __init__(self, model,fold_num=0,batch_size ={\"train\": 4, \"valid\": 4},accumulation_step=32,lr=5e-4,num_epochs=20,\\\n                 criterion=torch.nn.BCEWithLogitsLoss(),optim = \"Adam\",scheduler=None):\n        self.fold_num = fold_num\n        self.batch_size = batch_size\n        self.accumulation_steps = accumulation_step \/\/ self.batch_size['train']\n        self.lr = lr\n        self.num_epochs = num_epochs\n        self.best_loss = float(\"inf\")\n        self.phases = [\"train\", \"valid\"]\n        self.device = torch.device(\"cuda:0\")\n        torch.set_default_tensor_type(\"torch.cuda.FloatTensor\")\n        self.net = model\n        self.base_criterion = torch.nn.BCEWithLogitsLoss()\n        self.criterion = DiceLoss()\n        if optim==\"Adam\":\n            self.optimizer = torch.optim.Adam(self.net.parameters(), lr=self.lr)\n        elif optim==\"SGD\":\n            self.optimizer = torch.optim.SGD(self.net.parameters(),lr=self.lr)\n        self.scheduler = CyclicLR(self.optimizer,base_lr = self.lr*0.1,max_lr = self.lr,\n                                 step_size=int(len(pd.read_csv(\".\/train_fold_{}.csv\".format(fold_num)))\/self.accumulation_steps),\\\n                                  mode=\"triangular\",gamma=0.994)\n        \n        self.net = self.net.to(self.device)\n        cudnn.benchmark = True\n        self.dataloaders = {\n            phase: provider(\n                data_folder=data_folder,\n                df_path=\".\/{}_fold_{}.csv\".format(phase,fold_num),\n                phase=phase,\n                mean=(0.485, 0.456, 0.406),\n                std=(0.229, 0.224, 0.225),\n                batch_size=self.batch_size[phase],\n            )\n            for phase in self.phases\n        }\n        self.losses = {phase: [] for phase in self.phases}\n        self.iou_scores = {phase: [] for phase in self.phases}\n        self.dice_scores = {phase: [] for phase in self.phases}\n        \n    def forward(self, images, targets):\n        images = images.to(self.device)\n        masks = targets.to(self.device)\n        outputs = self.net(images)\n        if self.criterion is None:\n            loss = 0.5*self.base_criterion(outputs[0], masks)+self.base_criterion(outputs[1], masks)\n        else:\n            loss = 0.5*self.base_criterion(outputs[0], masks)+self.base_criterion(outputs[1], masks)+\\\n             0.5*(self.criterion(outputs[0],masks))+self.criterion(outputs[1],masks)\n        return loss, outputs\n\n    def iterate(self, epoch, phase):\n        meter_1 = Meter(phase, epoch)\n        meter_2 = Meter(phase, epoch)\n        start = time.strftime(\"%H:%M:%S\")\n        print(f\"Starting epoch: {epoch} | phase: {phase} | \u23f0: {start}\")\n        batch_size = self.batch_size[phase]\n        self.net.train(phase == \"train\")\n        dataloader = self.dataloaders[phase]\n        running_loss = 0.0\n        total_batches = len(dataloader)\n        self.optimizer.zero_grad()\n        for itr, batch in enumerate(dataloader): # replace `dataloader` with `tk0` for tqdm\n            images, targets = batch\n            loss, outputs = self.forward(images, targets)\n            loss = loss \/ self.accumulation_steps\n            if phase == \"train\":\n                loss.backward()\n                if (itr + 1 ) % self.accumulation_steps == 0:\n                    #self.scheduler.batch_step()\n                    self.optimizer.step()\n                    self.optimizer.zero_grad()\n            running_loss += loss.item()\n            outputs = [output.detach().cpu() for output in outputs]\n            meter_1.update(targets, outputs[0])\n            meter_2.update(targets, outputs[1])\n        epoch_loss = (running_loss * self.accumulation_steps) \/ total_batches\n        dice, iou = epoch_log(phase, epoch, epoch_loss, meter_1, start)\n        dice, iou = epoch_log(phase, epoch, epoch_loss, meter_2, start)\n        self.losses[phase].append(epoch_loss)\n        self.dice_scores[phase].append(dice)\n        self.iou_scores[phase].append(iou)\n        torch.cuda.empty_cache()\n        return epoch_loss\n\n    def start(self):\n        for epoch in range(self.num_epochs):\n            self.iterate(epoch, \"train\")\n            state = {\n                \"epoch\": epoch,\n                \"best_loss\": self.best_loss,\n                \"state_dict\": self.net.state_dict(),\n                \"optimizer\": self.optimizer.state_dict(),\n            }\n            val_loss = self.iterate(epoch, \"valid\")\n            #self.scheduler.step(val_loss)\n            if val_loss < self.best_loss:\n                print(\"******** New optimal found, saving state ********\")\n                state[\"best_loss\"] = self.best_loss = val_loss\n                torch.save(state, \".\/{}_deep_fold_{}.pth\".format(self.net.name,self.fold_num))\n            print()\n            \n            if (epoch+1)%int(self.num_epochs\/4)==0:\n                torch.save(state,\"\/{}_fold_{}_ck_{}.pth\".format(self.net.name,self.fold_num,int(self.num_epochs\/(epoch+1))))\nsample_submission_path = '..\/input\/severstal-steel-defect-detection\/sample_submission.csv'\ntrain_df_path = '..\/input\/severstal-steel-defect-detection\/train.csv'\ndata_folder = \"..\/input\/severstal-steel-defect-detection\/\"\ntest_data_folder = \"..\/input\/severstal-steel-defect-detection\/test_images\"\nmodel_trainer = SingleFoldTrainer(model,fold_num=3,batch_size ={\"train\": 4, \"valid\": 4},\\\n                                  accumulation_step=64,lr=2.0e-4,num_epochs=16)\nmodel_trainer.start()\n# PLOT TRAINING\nlosses = model_trainer.losses\ndice_scores = model_trainer.dice_scores # overall dice\niou_scores = model_trainer.iou_scores\n\ndef plot(scores, name):\n    plt.figure(figsize=(15,5))\n    plt.plot(range(len(scores[\"train\"])), scores[\"train\"], label=f'train {name}')\n    plt.plot(range(len(scores[\"train\"])), scores[\"valid\"], label=f'val {name}')\n    plt.title(f'{name} plot'); plt.xlabel('Epoch'); plt.ylabel(f'{name}');\n    plt.legend(); \n    plt.show()\n\nplot(losses, \"BCE loss\")\nplot(dice_scores, \"Dice score\")\nplot(iou_scores, \"IoU score\")","meta":"{'source': 'AI4Code', 'id': 'ff6b78bb92ca6c'}"}
{"id":"21458","text":"\"\"\"\n***If you find this notebook useful then please upvote.***\n\n\"\"\"\n# 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\n#Importing required packages.\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\n#from sklearn.svm import SVC\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n%matplotlib inline\n#Loading dataset\nrwine = pd.read_csv('..\/input\/red-wine-quality-cortez-et-al-2009\/winequality-red.csv')\n\"\"\"\n## Data Preprocessing and Visualization\n\"\"\"\n#Let's check how the data is distributed\nrwine.head()\n#knowing number of features and data size\nrow,col=rwine.shape\nprint(row,\",\",col)\n#Data Information \nrwine.info()\n# There is no null values, and no categorical data\n#knowing the number of red wine quality classes\nrwine['quality'].value_counts()\n#Making binary classificaion for the target by dividing wine as g for good and b for bad.\n#Dividing wine as good and bad by giving the limit for the quality\nbins = (2, 5.5, 8)\ngroups = ['b', 'g']\nrwine['quality'] = pd.cut(rwine['quality'], bins = bins, labels = groups)\nL_quality = LabelEncoder()\nrwine['quality'] = L_quality.fit_transform(rwine['quality'])\n\nrwine['quality'].value_counts()\n#fig, axs = plt.subplots(5,2,figsize=(15,15))\n#axs[0, 0].hist(rwine['fixed acidity'],bins=10) #original data\n#axs[0, 0].set_title('fixed acidity')\n#axs[0, 1].hist(rwine['volatile acidity'],bins=10) \n#axs[0, 1].set_title('volatile acidity')\n\ndf_train = rwine.sample(frac=0.7, random_state=0)\ndf_test = rwine.drop(df_train.index)\n\n# Split features and target\nX_train = df_train.drop('quality', axis=1)\nX_test = df_test.drop('quality', axis=1)\ny_train = df_train['quality']\ny_test = df_test['quality']\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.Sequential([\n    layers.Dense(1024, activation='relu', input_shape=[11]),\n    layers.Dropout(0.3),\n    layers.BatchNormalization(),\n    layers.Dense(1024, activation='relu'),\n    layers.Dropout(0.3),\n    layers.BatchNormalization(),\n    layers.Dense(1024, activation='relu'),\n    layers.Dropout(0.3),\n    layers.BatchNormalization(),\n    layers.Dense(1, activation='sigmoid'),])\nmodel.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['binary_accuracy'],\n)\n\nhistory = model.fit(\n    X_train, y_train,\n    validation_data=(X_test, y_test),\n    batch_size=250,\n    epochs=100,\n    verbose=0\n)\n\n\n# Show the learning curves\nhistory_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot();\nhistory_df.loc[:, ['binary_accuracy', 'val_binary_accuracy']].plot()\n\nprint((\"Best Validation Loss: {:0.4f}\" +\\\n      \"\\nBest Validation Accuracy: {:0.4f}\")\\\n      .format(history_df['val_loss'].min(), \n              history_df['val_binary_accuracy'].max()))","meta":"{'source': 'AI4Code', 'id': '27672b8c8bcfaf'}"}
{"id":"83038","text":"\"\"\"\n# Intel image multi label classification using transfer learning\n\nmulti label CNN Classification for: \n\nmountain, street, glacier, buildings, sea,forest\n\nI'll try different type of networks while using transfer learning\n\nhttps:\/\/towardsdatascience.com\/illustrated-10-cnn-architectures-95d78ace614d\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n# Import Packages\n\"\"\"\nimport numpy as np\nimport os\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sn; sn.set(font_scale=1.4)\nfrom sklearn.utils import shuffle           \nimport matplotlib.pyplot as plt             \nimport cv2                                 \nimport tensorflow as tf                \nfrom tqdm import tqdm\nfrom keras.preprocessing import image\nfrom keras import applications\n#import efficientnet\nfrom keras import callbacks\nfrom keras.models import Sequential\n\n!pip install -U efficientnet\nclass_names = ['mountain', 'street', 'glacier', 'buildings', 'sea', 'forest']\nclass_names_label = {class_name:i for i, class_name in enumerate(class_names)}\n\nnb_classes = len(class_names)\n\nIMAGE_SIZE = (150, 150)\nclass_names_label\n\"\"\"\n# Loading the Data\nWe have to write a load_data function that load the images and the labels from the folder.\n\"\"\"\ndef load_data():\n    \"\"\"\n        Load the data:\n            - 14,034 images to train the network.\n            - 3,000 images to evaluate how accurately the network learned to classify images.\n    \"\"\"\n    \n    datasets = ['..\/input\/intel-image-classification\/seg_train\/seg_train', '..\/input\/intel-image-classification\/seg_test\/seg_test']\n    output = []\n    \n    # Iterate through training and test sets\n    for dataset in datasets:\n        \n        images = []\n        labels = []\n        \n        print(\"Loading {}\".format(dataset))\n        \n        # Iterate through each folder corresponding to a category\n        for folder in os.listdir(dataset):\n            label = class_names_label[folder]\n            \n            # Iterate through each image in our folder\n            for file in tqdm(os.listdir(os.path.join(dataset, folder))):\n                \n                # Get the path name of the image\n                img_path = os.path.join(os.path.join(dataset, folder), file)\n                \n                # Open and resize the img\n                image = cv2.imread(img_path)\n                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n                image = cv2.resize(image, IMAGE_SIZE) \n                \n                # Append the image and its corresponding label to the output\n                images.append(image)\n                labels.append(label)\n                \n        images = np.array(images, dtype = 'float32')\n        labels = np.array(labels, dtype = 'int32')   \n        \n        output.append((images, labels))\n\n    return output\n(train_images, train_labels), (test_images, test_labels) = load_data()\ntrain_images[0].shape\ntrain_images, train_labels = shuffle(train_images, train_labels, random_state=7)\ntrain_labels_unique, train_counts = np.unique(train_labels, return_counts=True)\ntest_labels_unique, test_counts = np.unique(test_labels, return_counts=True)\npd.DataFrame({'train': train_counts,\n                    'test': test_counts}, \n             index=class_names\n            ).plot.bar()\nplt.show()\n\"\"\"\n# explore the dataset\n\n\"\"\"\nn_train = train_labels.shape[0]\nn_test = test_labels.shape[0]\n\nprint (\"Number of training examples: {}\".format(n_train))\nprint (\"Number of testing examples: {}\".format(n_test))\nprint (\"Each image -RGB  shape is: {}\".format(IMAGE_SIZE))\nplt.pie(train_counts,\n        explode=(0, 0, 0, 0, 0, 0) , \n        labels=class_names,\n        autopct='%1.1f%%')\nplt.axis('equal')\nplt.title('Proportion of each observed category')\nplt.show()\n\"\"\"\n## Scal image dataset\n\"\"\"\ntrain_images = train_images \/ 255.0 \ntest_images = test_images \/ 255.0\n\"\"\"\n## Visualize the data\nWe can display a random image from the training set.\n\"\"\"\ndef display_random_image(class_names, images, labels):\n    \"\"\"\n        Display a random image from the images array and its correspond label from the labels array.\n    \"\"\"\n    \n    index = np.random.randint(images.shape[0])\n    plt.figure()\n    plt.imshow(images[index])\n    plt.xticks([])\n    plt.yticks([])\n    #plt.grid(False)\n    plt.title('Image #{} : '.format(index) + class_names[labels[index]])\n    plt.show()\ndisplay_random_image(class_names, train_images, train_labels)\n\"\"\"\nWe can also display the first 25 images from the training set directly with a loop to get a better view\n\"\"\"\ndef display_examples(class_names, images, labels):\n    \"\"\"\n        Display 25 images from the images array with its corresponding labels\n    \"\"\"\n    \n    fig = plt.figure(figsize=(10,10))\n    fig.suptitle(\"Some examples of images of the dataset\", fontsize=16)\n    for i in range(25):\n        plt.subplot(5,5,i+1)\n        plt.xticks([])\n        plt.yticks([])\n        plt.grid(False)\n        plt.imshow(images[i], cmap=plt.cm.binary)\n        plt.xlabel(class_names[labels[i]])\n    plt.show()\ndisplay_examples(class_names, train_images, train_labels)\n#model.summary()\n\"\"\"\nWe fit the model to the data from the training set. The neural network will learn by itself the pattern in order to distinguish each category.\n\"\"\"\ndef plot_accuracy_loss(history,model_name):\n    \"\"\"\n        Plot the accuracy and the loss during the training of the nn.\n    \"\"\"\n    fig = plt.figure(figsize=(10,5))\n\n    # Plot accuracy\n    plt.subplot(221)\n    plt.plot(history.history['acc'],'bo--', label = \"acc\")\n    plt.plot(history.history['val_acc'], 'ro--', label = \"val_acc\")\n    plt.title(\"train_acc vs val_acc\" + model_name)\n    plt.ylabel(\"accuracy\")\n    plt.xlabel(\"epochs\")\n    plt.legend()\n\n    # Plot loss function\n    plt.subplot(222)\n    plt.plot(history.history['loss'],'bo--', label = \"loss\")\n    plt.plot(history.history['val_loss'], 'ro--', label = \"val_loss\")\n    plt.title(\"train_loss vs val_loss\"  + model_name)\n    plt.ylabel(\"loss\")\n    plt.xlabel(\"epochs\")\n\n    plt.legend()\n    plt.show()\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n# VGG19\n\"\"\"\nmodel = applications.VGG19(weights='imagenet', include_top=False)\n\ntrain_features = model.predict(train_images)\ntest_features = model.predict(test_images)\nn_train, x, y, z = train_features.shape\nn_test, x, y, z = test_features.shape\nnumFeatures = x * y * z\nmodel2 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape = (x, y, z)),\n    tf.keras.layers.Dense(100, activation=tf.nn.relu),\n    tf.keras.layers.Dense(6, activation=tf.nn.softmax)\n])\n\nmodel2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\n\nhistory2 = model2.fit(train_features, train_labels, batch_size=512, epochs=25, validation_split = 0.25)\nplot_accuracy_loss(history2,\"VGG19\")\ntest_loss = model2.evaluate(test_features, test_labels)\ndel model\ndel model2\n\"\"\"\n# InceptionV3\n\"\"\"\nmodel = applications.InceptionV3(weights='imagenet', include_top=False)\ntrain_features = model.predict(train_images)\ntest_features = model.predict(test_images)\nn_train, x, y, z = train_features.shape\nn_test, x, y, z = test_features.shape\nnumFeatures = x * y * z\n\nmodel2 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape = (x, y, z)),\n    tf.keras.layers.Dense(100, activation=tf.nn.relu),\n    tf.keras.layers.Dense(6, activation=tf.nn.softmax)\n])\nmodel2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\n\nhistory2 = model2.fit(train_features, train_labels, batch_size=128, epochs=15, validation_split = 0.2)\nplot_accuracy_loss(history2,\"InceptionV3\")\ntest_loss = model2.evaluate(test_features, test_labels)\ndel model\ndel model2\n\"\"\"\n# InceptionResNetV2\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\nmodel = applications.InceptionResNetV2(weights='imagenet', include_top=False)\ntrain_features = model.predict(train_images)\ntest_features = model.predict(test_images)\nn_train, x, y, z = train_features.shape\nn_test, x, y, z = test_features.shape\nnumFeatures = x * y * z\n\nmodel2 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape = (x, y, z)),\n    tf.keras.layers.Dense(100, activation=tf.nn.relu),\n    tf.keras.layers.Dense(6, activation=tf.nn.softmax)\n])\nmodel2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\n\nhistory2 = model2.fit(train_features, train_labels, batch_size=256, epochs=25, validation_split = 0.25)\nplot_accuracy_loss(history2,\"InceptionResNetV2\")\ntest_loss = model2.evaluate(test_features, test_labels)\ndel model\ndel model2\n\"\"\"\n# DenseNet201\n\"\"\"\n\"\"\"\n![image.png](attachment:image.png)\n\"\"\"\nmodel_DenseNet201 = applications.DenseNet201(weights='imagenet', include_top=False)\ntrain_features_DenseNet201 = model_DenseNet201.predict(train_images)\ntest_features_DenseNet201 = model_DenseNet201.predict(test_images)\nn_train, x, y, z = train_features_DenseNet201.shape\nn_test, x, y, z = test_features_DenseNet201.shape\n\nmodel2_DenseNet201 = tf.keras.Sequential([\n    tf.keras.layers.Flatten(input_shape = (x, y, z)),\n    tf.keras.layers.Dense(100, activation=tf.nn.relu),\n    tf.keras.layers.Dense(6, activation=tf.nn.softmax)\n])\nmodel2_DenseNet201.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\n\nhistory2_DenseNet201 = model2_DenseNet201.fit(train_features_DenseNet201, train_labels, batch_size=1024, epochs=30, validation_split = 0.15)\nplot_accuracy_loss(history2_DenseNet201,\"DenseNet201\")\ntest_loss = model2_DenseNet201.evaluate(test_features_DenseNet201, test_labels)\ndel model_DenseNet201\ndel model2_DenseNet201\n\"\"\"\n# EfficientNet\n\"\"\"\nfrom efficientnet.keras import EfficientNetB7\n\"\"\"\nModel is allocating too much memory - need to run standalone \n\"\"\"\nif 0 :\n    model = EfficientNetB7(weights='imagenet', include_top=False)\n    train_features = model.predict(train_images)\n    test_features = model.predict(test_images)\n    n_train, x, y, z = train_features.shape\n    n_test, x, y, z = test_features.shape\n\n    model2 = tf.keras.Sequential([\n        tf.keras.layers.Flatten(input_shape = (x, y, z)),\n        tf.keras.layers.Dense(100, activation=tf.nn.relu),\n        tf.keras.layers.Dense(6, activation=tf.nn.softmax)\n    ])\nif 0 :   \n    model2.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])\n\n    history2 = model2.fit(train_features, train_labels, batch_size=1024, epochs=30, validation_split = 0.15)\n    plot_accuracy_loss(history2,\"EfficientNetB7\")\nif 0 :   \ntest_loss = model2.evaluate(test_features, test_labels)\n\"\"\"\n## Huge thanks for Vincent Liu :) \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '987d64e280363d'}"}
{"id":"69173","text":"# 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\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Activation,Dropout\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Flatten,Dropout,Conv2D,MaxPooling2D, BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, Callback\nfrom keras.optimizers import Adam\n\"\"\"\nImporting Dataset\n\"\"\"\ntrain = pd.read_csv('..\/input\/fashionmnist\/fashion-mnist_train.csv')\ntest = pd.read_csv('..\/input\/fashionmnist\/fashion-mnist_test.csv')\n\"\"\"\nChecking the shape of the dataset.It has pixels that range from 0-255\n\"\"\"\nprint(train.shape)\nprint(test.shape)\ntrain.head(5)\ntest.head(5)\n\"\"\"\nFinding any missing values.\n\"\"\"\nprint(\"train missing values:\", train.isnull().any().sum())\nprint(\"test missing values:\", test.isnull().any().sum())\n\"\"\"\nGetting our y into a different variable and splitting the data\n\"\"\"\nX = train.iloc[:,1:] #taking all but the first row\nY = train.iloc[:,0] #taking only the first row as this is the label\n\n#splitting dataframe using train_test_split\nx_train , x_test , y_train , y_test = train_test_split(X, Y , test_size=0.1, random_state=42)\nclass_names = ['T_shirt\/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\nplt.figure(figsize=(10, 10))\nfor i in range(36):\n    plt.subplot(6, 6, i + 1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(X.loc[i].values.reshape((28,28))) #calling the .values of each row\n    label_index = int(Y[i]) #setting as an int as the number is stored as a string\n    plt.title(class_names[label_index])\nplt.show()\n\"\"\"\nNormalizing the pixels into the range 0 to 1.\n\"\"\"\nx_train =x_train\/255.0\nx_test=x_test\/255.0\n#reshape\nx_train =x_train.values.reshape(-1, 28,28,1)\n#reshape\nx_test = x_test.values.reshape(-1, 28,28,1)\n#label encoding\ny_train = to_categorical(y_train, num_classes=10)\ny_test  = to_categorical(y_test, num_classes=10)\nprint(\"X_train shape: \", x_train.shape)\nprint(\"X_test shape: \", x_test.shape)\nprint(\"y_train shape: \", y_train.shape)\nprint(\"y_test shape: \", y_test.shape)\n\"\"\"\nData Augumnetation.Increase the size of data so that model can get more images to train.\n\"\"\"\nfrom keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(\n        rotation_range= 10,\n        zoom_range = 0.1,\n        width_shift_range = 0.1,\n        height_shift_range = 0.1\n)\n\ndatagen.fit(x_train)\ntrain_generator = datagen.flow(x_train, y_train, batch_size = 64)\n\nvalidation_generator = datagen.flow(x_test, y_test, batch_size = 64)\n\"\"\"\nCreating the Model\n\"\"\"\nmodel = Sequential() # Initialize the sequential model\n\n# Add CNN convolutions with BatchNormalization and MaxPooling2D\n# Avoid overfitting with Dropout\nmodel.add(Conv2D(32, kernel_size = (3,3), input_shape=(28, 28, 1), padding = 'Same', activation='relu'))\nmodel.add(Conv2D(64, kernel_size = (3,3), padding = 'Same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=1, padding='valid'))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, kernel_size = (3,3), padding = 'Same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=1, padding='valid'))\nmodel.add(Dropout(0.2))\n\n# Convert our matrix to 1-D set of features \nmodel.add(Flatten())\n\n# Add fully-conected layers\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.20))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.35))\nmodel.add(Dense(10, activation='softmax'))\n# Defining the call backs EarlyStopping and myCallback which will stop the training\n# if the accuracy reaches 99%\n\nclass myCallback(Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if(logs.get('accuracy')>0.999):\n            print(\"\\nReached 99.9% accuracy so cancelling training!\")\n            self.model.stop_training = True\n\n# Instantiate callback\nmycallback = myCallback()\n\n\nearly_stopping_callback = EarlyStopping(monitor='val_loss', \n                                        patience=3,\n                                        verbose = 2,\n                                        restore_best_weights=True)\n\n\nfrom tensorflow.keras.optimizers import Adam\n\nmodel.compile(optimizer = Adam(lr = 1e-3),\n              loss = 'categorical_crossentropy',\n              metrics = ['accuracy'])\nmodel.summary()\n!pip install visualkeras\nimport visualkeras\n\nvisualkeras.layered_view(model)\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch = x_train.shape[0] \/\/ 128,\n    epochs = 50,\n    validation_data = validation_generator,\n    validation_steps = x_test.shape[0] \/\/ 64,\n    callbacks = [mycallback,early_stopping_callback]\n)\nplt.figure(figsize=(10, 7))\nacc = history.history[\"accuracy\"]\nloss = history.history[\"loss\"]\n\nepochs = range(len(acc))\nval_acc = history.history[\"val_accuracy\"]\nval_loss = history.history[\"val_loss\"]\n\n\nplt.plot(epochs, acc, \"g\", label=\"Accuracy\")\nplt.plot(epochs, loss, \"r\", label=\"Loss\")\n\nplt.plot(epochs, val_acc, \"orange\", label=\"Validation Accuracy\")\nplt.plot(epochs, val_loss, \"brown\", label=\"Vlaidation Loss\")\nplt.title(\"Model Accuracy And Loss\")\nplt.legend()\nplt.show()\n# Save the model\nmodel.save('model.h5')\npredict=model.predict(x_test)\ny_pred=[]\nfor i in range(len(predict)):\n    y_pred.append(np.argmax(predict[i]))\nfor i in range(5):\n    print(y_pred[i])\ny = np.argmax(y_test, axis=-1)\ny\nmat=confusion_matrix(y,y_pred)\nmat\n\"\"\"\nUPVOTE if you like this Notebook :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7f5532876807fa'}"}
{"id":"73019","text":"\"\"\"\n# Key Insights\n### Job location is the top deciding factor of Data Engineers' salary variation in this dataset (R-Square 30%+)\nOverall average estimated salary of a data engineer is about USD 100K, and median is USD 97K, whereas a data engineer in California earns USD 128K, for both mean and median.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n### Plenty of high-paid opportunities for Data Engineer are in San Diego. \nOne-third of California's Data Engineer jobs come from San Diego. Data Engineers are paid 33K higher than the average. Meanwhile Data Engineers in many Texas and Florida cities are highly undervalued.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n### On Data Engineers' job titles, functional keywords matter much more than seniorities. These functional keywords on titles may be a clue in identifying high-paying Data Engineer positions.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n### 70% of Data Engineer jobs do not require Master\/PHD degrees. Experience\/skill\/knowledge in SQL, PYTHON, SPARK, AWS and Data Security are more required.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n### These experience\/skills\/knowledge may help boost your earnings as a Data Engineer.\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n### Larger firms do not necessarily pay more to Data Engineers.\nInstead, high demands with slightly higher salaries are found in clusters such as follows. Meanwhile, a big portion of data engineer positions are released from financially unpublic firms.\n* **California Small firms (especially 51-200 employees & USD5-50M revenues)** \n* **California medium-large businesses (1001-5000 employees & 50M-1B revenues unknown)**\n![image.png](attachment:image.png)\n\"\"\"\n\"\"\"\n# About\n## Dataset\nThis dataset was created by [picklesueat](https:\/\/github.com\/picklesueat\/data_jobs_data) and contains more than 2000 job listing for data engineer positions (all assumed to be open positions at the time the dataset was published in July 2020), with features such as:\n\n* Salary Estimate\n* Location\n* Company Rating\n* Job Description\n  and more.\n\n## Objectives\n* What kind of Data Engineer jobs get higher salaries? (Job Title, Job Description, EasyApply)\n* What kind of companies pay more? (Rating, Company, Size, *Years established (now - Founded)*, Type of ownership, Industry & Sector, Revenue)\n* Does job\/headquarters location matter to salaries?\n\n## Methodologies\n\n1. Exploratory Data Analysis (distribution, boxplot, barcharts, errorbars, heatmaps, scatterplots...etc.)\n2. T-test\n3. Multiple Regression\n\n## Limitations and Assumptions\n\n* The results only reflet the outcome at the time the dataset was published, which is pressumed to be July 2020. Seasonal variation is disregarded (not a time-series data).\n* Somehow remote positions are not found in this dataset, so the impact of pandemic (more jobs becoming remote) on salary cannot be measured.\n* The salary estimates come from Glassdoor, which may not reflect the actual salaries.\n* The dataset is assumed to reflect the traits of the actual job market.\n* The salaries are nominal, not adjusted by living costs or consumer price index.\n\"\"\"\n\"\"\"\n# Data Preparation\n\"\"\"\n\"\"\"\n## Import Libraries and Dataset\n\"\"\"\nimport numpy as np \n# large, multi-dimensional arrays and matrices, \n# along with a large collection of high-level mathematical functions to operate on these arrays.\nimport pandas as pd\n# data structures and operations for manipulating numerical tables and time series\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nfrom matplotlib.ticker import PercentFormatter\n# plotting\nimport plotly.express as px\n# graph\nimport plotly.graph_objects as go\n# graph\nimport seaborn as sns\n# t-test\nfrom scipy import stats\n# regression\nfrom sklearn import datasets, linear_model\nfrom sklearn.linear_model import LinearRegression\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\n# Word Cloud\nfrom wordcloud import WordCloud\ndata=pd.read_csv('..\/input\/data-engineer-jobs\/DataEngineer.csv')\n\"\"\"\n## Explore the Data\n\"\"\"\ndata.head(2)\n\"\"\"\nData includes job title , salary estimation , job description , rating ,company name , location and many more ...\n\"Easy Apply\" should be the function that applicants can directly apply a job directly through 3rd party jobboard (e.g. Glassdoor, LinkedIn...) without logging into the hiring company's career site.\n\"\"\"\ndata.describe(include='all')\n\"\"\"\n## Data Cleaning\n\"\"\"\n# Check for missing values\ndef missing_values_table(df):\n    # number of missing values\n    mis_val = df.isnull().sum()\n    # % of missing values\n    mis_val_percent = 100 * mis_val \/ len(df)\n    # make table # axis '0' concat along index, '1' column\n    mis_val_table = pd.concat([mis_val,mis_val_percent],axis=1) \n    # rename columns\n    mis_val_table_ren_columns = mis_val_table.rename(\n        columns = {0:'Missing Values',1:'% of Total Values'})\n    # sort by column\n    mis_val_table_ren_columns = mis_val_table_ren_columns[mis_val_table_ren_columns.iloc[:,1]!=0].sort_values(\n        '% of Total Values',ascending=False).round(1) #Review\n    print(\"Your selected datset has \"+str(df.shape[1])+\" columns and \"+str(len(df))+\" observations.\\n\"\n         \"There are \"+str(mis_val_table_ren_columns.shape[0])+\" columns that have missing values.\")\n    # return the dataframe with missing info\n    return mis_val_table_ren_columns\n\nmissing_values_table(data)\ndata['Easy Apply'].value_counts()\ndata['Competitors'].value_counts()\n\"\"\"\nAs some of the columns contains -1 or '-1.0' or '-1' etc . We need to clean this(This is kind of null values)\n\"\"\"\n# Replace -1 or -1.0 or '-1' to NaN\ndata=data.replace(-1,np.nan)\ndata=data.replace(-1.0,np.nan)\ndata=data.replace('-1',np.nan)\nmissing_values_table(data)\n\"\"\"\nNow you can see there are lots of missing values in the dataset. Most positions don't support the Easy Apply function. Competitors are not identified for majority of the companies.\n\"\"\"\n#Remove '\\n' from Company Name. \ndata['Company Name'],_=data['Company Name'].str.split('\\n', 1).str\n# 1st column after split, 2nd column after split (delete when '_')\n# string.split(separator, maxsplit) maxsplit default -1, which means all occurrances\n# Split salary into two columns min salary and max salary.\ndata['Salary Estimate'],_=data['Salary Estimate'].str.split('(', 1).str\n# Split salary into two columns min salary and max salary.\ndata['Min_Salary'],data['Max_Salary']=data['Salary Estimate'].str.split('-').str\ndata['Min_Salary']=data['Min_Salary'].str.strip(' ').str.lstrip('$').str.rstrip('K').fillna(0).astype('int')\ndata['Max_Salary']=data['Max_Salary'].str.strip(' ').str.lstrip('$').str.rstrip('K').fillna(0).astype('int')\n# lstrip is for removing leading characters\n# rstrip is for removing rear characters\n#Drop the original Salary Estimate column\ndata.drop(['Salary Estimate'],axis=1,inplace=True)\n# To estimate the salary with regression and other analysis, better come up with one number: Est_Salary = (Min_Salary+Max_Salary)\/2\ndata['Est_Salary']=(data['Min_Salary']+data['Max_Salary'])\/2\n# Create a variable for how many years a firm has been founded\ndata['Years_Founded'] = 2020 - data['Founded']\n# A final look at the data before analysis\ndata.head(2)\n\"\"\"\n# Exploratory Analysis\n\"\"\"\n\"\"\"\n## Salary Distribution of All Data Engineers\n\"\"\"\nplt.figure(figsize=(13,5))\nsns.set() #style==background\nsns.distplot(data['Min_Salary'], color=\"b\")\nsns.distplot(data['Max_Salary'], color=\"r\")\n\nplt.xlabel(\"Salary ($'000)\")\nplt.legend({'Min_Salary':data['Min_Salary'],'Max_Salary':data['Max_Salary']})\nplt.title(\"Distribution of Min & Max Salary\",fontsize=19)\nplt.xlim(0,210)\nplt.xticks(np.arange(0, 210, step=10))\nplt.tight_layout()\nplt.show()\n\"\"\"\n* By the modes of distribution, we can say Data Engineer's minimum salary is 55K and maximum 105K.\n* The Salaries distributions of Data Engineers are quite spread.\n\"\"\"\nmin_max_view = data.sort_values(['Min_Salary','Max_Salary'],ascending=True).reset_index(drop=True).reset_index()\nf, (ax_box, ax_line) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\": (0.05,1)},figsize=(13,5))\nmean=min_max_view['Est_Salary'].mean()\nmedian=min_max_view['Est_Salary'].median()\n\nbpv = sns.boxplot(y='Est_Salary',data=min_max_view, ax=ax_box).set(ylabel=\"Est. Salary ($'000)\")\nax_box.axhline(mean, color='k', linestyle='--')\nax_box.axhline(median, color='y', linestyle='-')\n\nlp1 = sns.lineplot(x='index',y='Min_Salary',data=min_max_view, color='b')\nlp2 = sns.lineplot(x='index',y='Max_Salary',ax=ax_line,data=min_max_view, color='r')\nax_line.axhline(mean, color='k', linestyle='--')\nax_line.axhline(median, color='y', linestyle='-')\n\nplt.legend({'Min_Salary':data['Min_Salary'],'Max_Salary':data['Max_Salary'],'Mean':mean,'Median':median})\nplt.title(\"Salary Estimates of Each Engineer\",fontsize=19)\nplt.xlabel(\"Observations\")\nplt.tight_layout()\nplt.show()\n\"\"\"\nAnother view the see the distribution of salary min, max, mean and median: \n* X-axis: the id(index) of all observations sorted by ascending order of min salaries.\n* There's 50% chance a data engineer's salary would be **at least** (minimum) higher than 75K.\n* There's 95% chance a data engineer's salary is within 40K-160K.\n\"\"\"\nsns.set(style='white')\n\nf, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.2, 1)},figsize=(13,5))\nmean=data['Est_Salary'].mean()\nmedian=data['Est_Salary'].median()\n\nbph = sns.boxplot(data['Est_Salary'], ax=ax_box).set(xlabel=\"\")\nax_box.axvline(mean, color='k', linestyle='--')\nax_box.axvline(median, color='y', linestyle='-')\n\ndp = sns.distplot(data['Est_Salary'],ax=ax_hist, color=\"g\").set(xlabel=\"Est. Salary ($'000)\")\nax_hist.axvline(mean, color='k', linestyle='--')\nax_hist.axvline(median, color='y', linestyle='-')\n\nplt.legend({'Mean':mean,'Median':median})\nplt.xlim(0,210)\nplt.xticks(np.arange(0,210,step=10))\nplt.tight_layout() #Adjust the padding between and around subplots\nplt.show()\n\"\"\"\nFocus only on Est. Salary(Avg. of Min & Max). Both mean and median are around 100K.\n\"\"\"\n\"\"\"\n## Distribution of Company Ages\n\"\"\"\nsns.set(style='white')\n\nf, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.2, 1)},figsize=(13,5))\nmean=data['Years_Founded'].mean()\nmedian=data['Years_Founded'].median()\n\nbph = sns.boxplot(data['Years_Founded'], ax=ax_box).set(xlabel=\"\")\nax_box.axvline(mean, color='k', linestyle='--')\nax_box.axvline(median, color='y', linestyle='-')\n\ndp = sns.distplot(data['Years_Founded'],ax=ax_hist, color=\"g\").set(xlabel=\"Years_Founded\")\nax_hist.axvline(mean, color='k', linestyle='--')\nax_hist.axvline(median, color='y', linestyle='-')\n\nplt.legend({'Mean':mean,'Median':median})\nplt.xlim(0,240)\nplt.xticks(np.arange(0,240,step=10))\nplt.tight_layout() #Adjust the padding between and around subplots\nplt.show()\n\"\"\"\n## Distribution of Company Ratings\n\"\"\"\nsns.set(style='white')\n\nf, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.2, 1)},figsize=(13,5))\nmean=data['Rating'].mean()\nmedian=data['Rating'].median()\n\nbph = sns.boxplot(data['Rating'], ax=ax_box).set(xlabel=\"\")\nax_box.axvline(mean, color='k', linestyle='--')\nax_box.axvline(median, color='y', linestyle='-')\n\ndp = sns.distplot(data['Rating'],ax=ax_hist, color=\"g\").set(xlabel=\"Ratings\")\nax_hist.axvline(mean, color='k', linestyle='--')\nax_hist.axvline(median, color='y', linestyle='-')\n\nplt.legend({'Mean':mean,'Median':median})\nplt.xlim(0,6)\nplt.xticks(np.arange(0,6,step=1))\nplt.tight_layout() #Adjust the padding between and around subplots\nplt.show()\n\"\"\"\n## Hires and Salary Estimates by Firms (Top 20)\n\"\"\"\n\"\"\"\nI want to know the companies actively hiring Data Engineers and the estimated salaries they offer.\n\"\"\"\n# First I count the positions opened by the companies.\ndf_by_firm=data.groupby('Company Name')['Job Title'].count().reset_index().sort_values(\n    'Job Title',ascending=False).head(20).rename(columns={'Job Title':'Hires'})\n# When we reset the index, the old index is added as a column, and a new sequential index is used\n# Merge with original data to get salary estimates.\nSal_by_firm = df_by_firm.merge(data,on='Company Name',how='left')\nsns.set(style=\"white\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Company Name',data=Sal_by_firm,ax=ax_bar, palette='Set2').set(ylabel=\"\")\nsns.pointplot(x='Est_Salary',y='Company Name',data=Sal_by_firm, join=False,ax=ax_point).set(\n    ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n* The lines in the Salary chart represent 95% confidence interval, whereas points are point estimates.\n* Amazon was hiring most data engineers at by USD100K+.\n* Apple and Management Decisions, Inc. are with the highest est. salaries.\n* All sample sizes for those companies are lower than 30, so we'd better be conservative about the est. salaries by firms.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Job Location Cities (Top 20)\n\"\"\"\ndf_by_city=data.groupby('Location')['Job Title'].count().reset_index().sort_values(\n    'Job Title',ascending=False).head(20).rename(columns={'Job Title':'Hires'})\nSal_by_city = df_by_city.merge(data,on='Location',how='left')\nsns.set(style=\"white\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Location',data=Sal_by_city,ax=ax_bar, palette='Set2').set(ylabel=\"\")\nsns.pointplot(x='Est_Salary',y='Location',data=Sal_by_city, join=False,ax=ax_point).set(\n    ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n* Cities in CA and TX hire the most Data Engineers. Citywise, New York and Chicago are also on top of the chart.\n* Salaries are higher in cities of CA.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Job Location States\n\"\"\"\ndata['City'],data['State'] = data['Location'].str.split(', ',1).str\ndata['State']=data['State'].replace('Arapahoe, CO','CO')\nstateCount = data.groupby('State')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).reset_index(drop=True)\nstateCount = stateCount.merge(data, on='State',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='State',data=stateCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='State',data=stateCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\nNot many states are hiring Data engineers. Though there are more opportunities in TX, CA offers much higher pay.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Headquarters Location (Top 20)\n\"\"\"\ndata['HQCity'],data['HQState'] = data['Headquarters'].str.split(', ',1).str\ndata['HQState']=data['HQState'].replace('NY (US), NY','NY')\nHQCount = data.groupby('HQState')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).head(20).reset_index(drop=True)\nHQCount = HQCount.merge(data, on='HQState',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='HQState',data=HQCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='HQState',data=HQCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n* Big portion of companies hiring Data Engineers are headquartered in California. \n* With such high level of demand, Data engineers' salaries are obviously undervalued.\n* We can also see foreign companies like India, Japan and UK.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Revenue\n\"\"\"\nRevCount = data.groupby('Revenue')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).reset_index(drop=True)\n#Make the Revenue column clean\nRevCount[\"Revenue_USD\"]=['Unknown','10+ billion','100-500 million','50-100 million','2-5 billion','10-25 million','25-50 million','1-5 million','5-10 billion','<1 million','1-2 billion','0.5-1 billion','5-10 million']\n#Merge the new Revenue back to data\nRevCount2 = RevCount[['Revenue','Revenue_USD']]\nRevCount = RevCount.merge(data, on='Revenue',how='left')\ndata=data.merge(RevCount2,on='Revenue',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Revenue_USD',data=RevCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Revenue_USD',data=RevCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n1,000+ (40%+) of Data Engineer jobs are released from financially unpublic or medium businesses.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Size\n\"\"\"\nSizeCount = data.groupby('Size')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).reset_index(drop=True)\nSizeCount = SizeCount.merge(data, on='Size',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Size',data=SizeCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Size',data=SizeCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\nGiant companies hire the most Data Engineers but they don't necessarily pay more.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Sector (Top 12)\n\"\"\"\nSecCount = data.groupby('Sector')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).reset_index(drop=True)\nSecCount = SecCount.merge(data, on='Sector',how='left')\nSecCount = SecCount[SecCount['Hires']>29]\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Sector',data=SecCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Sector',data=SecCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n* IT companies hire the most Data Engineers, followed by Business Services and Finance companies.\n* Healthcare-related Data Engineer jobs seem to have better pay.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Type of Ownership\n\"\"\"\nOwnCount = data.groupby('Type of ownership')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Hires'}).sort_values(\n    'Hires', ascending=False).reset_index(drop=True)\nOwnCount = OwnCount.merge(data, on='Type of ownership',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Hires',y='Type of ownership',data=OwnCount,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Type of ownership',data=OwnCount, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\nPrivate companies' demand are higher, and the salary offers are comparable to public firms.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Job Titles\n\"\"\"\n\"\"\"\n\u2193Here's a series operations to create and clean a dataset to dissect texts in Job Titles and Descriptions\n\"\"\"\n# create a new dataset from original data\ntext_Analysis = data[['Job Title','Job Description','Est_Salary','Max_Salary','Min_Salary','City','State','Easy Apply','Revenue_USD','Rating','Size','Industry','Sector','Type of ownership','Years_Founded','Company Name','HQState']]\n# remove special characters and unify some word use\ntext_Analysis['Job_title_2']= text_Analysis['Job Title'].str.upper().replace('[^A-Za-z0-9]+', ' ',regex=True)\ntext_Analysis['Job_title_2']= text_Analysis['Job_title_2'].str.upper().replace(\n    ['\u00c2','AND ','WITH ','SYSTEMS','OPERATIONS','ANALYTICS','SERVICES','ENGINEERS','NETWORKS','GAMES','MUSICS','INSIGHTS','SOLUTIONS','JR ','MARKETS','STANDARDS','FINANCE','PRODUCTS','DEVELOPERS','SR '],\n    ['','','','SYSTEM','OPERATION','ANALYTIC','SERVICE','ENGINEER','NETWORK','GAME','MUSIC','INSIGHT','SOLUTION','JUNIOR ','MARKET','STANDARD','FINANCIAL','PRODUCT','DEVELOPER','SENIOR '],regex=True)\n# unify some word use\ntext_Analysis['Job_title_2']= text_Analysis['Job_title_2'].str.upper().replace(\n    ['BUSINESS INTELLIGENCE','INFORMATION TECHNOLOGY','QUALITY ASSURANCE','USER EXPERIENCE','USER INTERFACE','DATA WAREHOUSE','DATA ANALYST','DATA BASE','DATA QUALITY','DATA GOVERNANCE','BUSINESS ANALYST','DATA MANAGEMENT','REPORTING ANALYST','BUSINESS DATA','SYSTEM ANALYST','DATA REPORTING','QUALITY ANALYST','DATA ENGINEER','BIG DATA','SOFTWARE ENGINEER','MACHINE LEARNING','FULL STACK','DATA SCIENTIST','DATA SCIENCE','DATA CENTER','ENTRY LEVEL','NEURAL NETWORK','SYSTEM ENGINEER'],\n    ['BI','IT','QA','UX','UI','DATA_WAREHOUSE','DATA_ANALYST','DATABASE','DATA_QUALITY','DATA_GOVERNANCE','BUSINESS_ANALYST','DATA_MANAGEMENT','REPORTING_ANALYST','BUSINESS_DATA','SYSTEM_ANALYST','DATA_REPORTING','QUALITY_ANALYST','DATA_ENGINEER','BIG_DATA','SOFTWARE_ENGINEER','MACHINE_LEARNING','FULL_STACK','DATA_SCIENTIST','DATA_SCIENCE','DATA_CENTER','ENTRY_LEVEL','NEURAL_NETWORK','SYSTEM_ENGINEER'],regex=True)\n# unify some word use\ntext_Analysis['Job_title_2']= text_Analysis['Job_title_2'].str.upper().replace(\n    ['DATA_ENGINEER JUNIOR','DATA_ENGINEER SENIOR','DATA  REPORTING_ANALYST'],\n    ['JUNIOR DATA_ENGINEER','SENIOR DATA_ENGINEER','DATA_REPORTING_ANALYST'],regex=True)\n\"\"\"\n\u2193Preparing for visualisation\n\"\"\"\njobCount=text_Analysis.groupby('Job_title_2')[['Job Title']].count().reset_index().rename(\n    columns={'Job Title':'Count'}).sort_values('Count',ascending=False)\njobSalary = text_Analysis.groupby('Job_title_2')[['Max_Salary','Est_Salary','Min_Salary']].mean().sort_values(\n    ['Max_Salary','Est_Salary','Min_Salary'],ascending=False)\njobSalary['Spread']=jobSalary['Max_Salary']-jobSalary['Est_Salary']\njobSalary=jobSalary.merge(jobCount,on='Job_title_2',how='left').sort_values('Count',ascending=False).head(20)\nf, axs = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\":(1,0.5)},figsize=(13,8))\n\nax = axs[0]\nax.errorbar(x='Job_title_2',y='Est_Salary',data=jobSalary,yerr=jobSalary['Spread'],fmt='o')\nax.set_ylabel('Est. Salary ($\\'000)')\n\nax = axs[1]\nsns.barplot(x=jobSalary['Job_title_2'],y=jobSalary['Count']).set(xlabel=\"\")\n\nplt.xticks(rotation=65,horizontalalignment='right')\nplt.tight_layout()\n\"\"\"\nAgain created a bar chart & error bar combo intended to see the salaries and counts, but not very effective (most sample sizes are under 30) as there are too many ways in presenting a position's name even some wordings are standardized. \n\n### Regression model may be a better approach: some certain keywords in job title\/desc may be correlated with salary pay.\n\"\"\"\n\"\"\"\n# Regression Analysis\n\"\"\"\n\"\"\"\n## Correlation: Job Title Keywords vs Salary\n\"\"\"\n# get top keywords\ns = text_Analysis['Job_title_2'].str.split(expand=True).stack().value_counts().reset_index().rename(\n    columns={'index':'KW',0:'Count'})\nS = s[s['Count']>29]\nS\n# write get_keyword method\ndef get_keyword(x):\n   x_ = x.split(\" \")\n   keywords = []\n   try:\n      for word in x_:\n         if word in np.asarray(S['KW']):\n            keywords.append(word)\n   except:\n      return -1\n\n   return keywords\n# get keywords from each row\ntext_Analysis['KW'] = text_Analysis['Job_title_2'].apply(lambda x: get_keyword(x))\n# create dummy columns by keywords\nkwdummy = pd.get_dummies(text_Analysis['KW'].apply(pd.Series).stack()).sum(level=0).replace(2,1)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True).replace(np.nan,0)\n# run t-test for top keywords to see their correlation with salaries\ntext_columns = list(text_Analysis.columns)\nttests=[]\nfor word in text_columns:\n    if word in set(S['KW']):\n        ttest = stats.ttest_ind(text_Analysis[text_Analysis[word]==1]['Est_Salary'],\n                                     text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests.append([word,ttest])\n        \nttests = pd.DataFrame(ttests,columns=['KW','R'])\nttests['R']=ttests['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests['Statistic'],ttests['P-value']=ttests['R'].str.split(', ',1).str\nttests=ttests.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests\n# Selecting keywords with p-value <0.1 into multiple regression model.\nttest_pass = list(ttests[ttests['P-value'].astype(float)<0.1]['KW'])\nprint(*ttest_pass,sep=' + ')\nTitleBar=ttests[ttests['P-value'].astype(float)<0.05]\nTitleBar['Statistic']=(TitleBar['Statistic'].astype(float)\/101)*100\nTitleBar=TitleBar.sort_values('Statistic',ascending=False).replace(\n    'ENGINEER','*OTHER*_ENGINEER').replace('_',' ',regex=True)\nTitleBar['KW']='\"' + TitleBar['KW'] + '\"'\nfig = plt.figure(figsize=(13, 5))\nsns.barplot(x='KW',y='Statistic',data=TitleBar).set(xlabel=\"\",ylabel=\"Salary Performance (%) \\n Against Average\")\n\nplt.xticks(rotation=45,horizontalalignment='right')\n# run regression\n# Remove variables with p-value >0.05 one by one until all <0.05\ntitleMod_final = ols(\"Est_Salary ~ SOFTWARE_ENGINEER + NETWORK + SECURITY + SYSTEM_ENGINEER + SYSTEM + SOFTWARE + MACHINE_LEARNING + ENGINEER + DATA_ENGINEER\",\n               data=text_Analysis).fit()\nprint(titleMod_final.summary())\n\"\"\"\n* The seniorities are not relevant, but functional words (SOFTWARE, NETWORK...) are.\n* This model can explain less than 5% of variations in salaries.\n\"\"\"\n# Plot with scatterplots\nfig = plt.figure(figsize=(13, 13))\nfig = sm.graphics.plot_partregress_grid(titleMod_final,fig=fig)\nfig.tight_layout(pad=1.0)\n# Sorry somebody tell me how to remove that \"Partial Regression Plot\"\n\"\"\"\n## Correlation: Job Description vs Salary\n\"\"\"\ntext_Analysis['Job_Desc2'] = text_Analysis['Job Description'].replace('[^A-Za-z0-9]+', ' ',regex=True)\ntext_Analysis['Job_Desc2'] = text_Analysis['Job_Desc2'].str.upper().replace(\n    ['COMPUTER SCIENCE','ENGINEERING DEGREE',' MS ','BUSINESS ANALYTICS','SCRUM MASTER','MACHINE LEARNING',' ML ','POWER BI','ARTIFICIAL INTELLIGENCE',' AI ','ALGORITHMS','DEEP LEARNING','NEURAL NETWORK','NATURAL LANGUAGE PROCESSING','DECISION TREE','CLUSTERING','PL SQL'],\n    ['COMPUTER_SCIENCE','ENGINEERING_DEGREE',' MASTER ','BUSINESS_ANALYTICS','SCRUM_MASTER','MACHINE_LEARNING',' MACHINE_LEARNING ','POWER_BI','ARTIFICIAL_INTELLIGENCE',' ARTIFICIAL_INTELLIGENCE ','ALGORITHM','DEEP_LEARNING','NEURAL_NETWORK','NATURAL_LANGUAGE_PROCESSING','DECISION_TREE','CLUSTER','PLSQL'],regex=True)\n# Create a list of big data buzzwords to see if those words in JD would influence the salary\nbuzzwords = ['COMPUTER_SCIENCE','MASTER','MBA','SQL','PYTHON','R','PHD','BUSINESS_ANALYTICS','SAS','PMP','SCRUM_MASTER','STATISTICS','MATHEMATICS','MACHINE_LEARNING','ARTIFICIAL_INTELLIGENCE','ECONOMICS','TABEAU','AWS','AZURE','POWER_BI','ALGORITHM','DEEP_LEARNING','NEURAL_NETWORK','NATURAL_LANGUAGE_PROCESSING','DECISION_TREE','REGRESSION','CLUSTER','ORACLE','EXCEL','TENSORFLOW','HADOOP','SPARK','NOSQL','SAP','ETL','API','PLSQL','MONGODB','POSTGRESQL','ELASTICSEARCH','REDIS','MYSQL','FIREBASE','SQLITE','CASSANDRA','DYNAMODB','OLTP','OLAP','DEVOPS','PLATFORM','NETWORK','APACHE','SECURITY']\n# Count the JD keywords.\nS2 = text_Analysis['Job_Desc2'].str.split(expand=True).stack().value_counts().reset_index().rename(\n    columns={'index':'KW',0:'Count'})\nS2 = S2[S2['KW'].isin(buzzwords)].reset_index(drop=True)\n# .sort_values('Count',ascending=False)\nS2_TOP = S2[S2['Count']>29]\nS2_TOP_JD = S2_TOP\nS2_TOP_JD['KW'] = S2_TOP_JD['KW'] +'_JD'\nS2_TOP_JD\nwordCloud = WordCloud(width=450,height= 300).generate(' '.join(S2['KW']))\nplt.figure(figsize=(19,9))\nplt.axis('off')\nplt.title(\"Keywords in Data Engineer Job Descriptions\",fontsize=20)\nplt.imshow(wordCloud)\nplt.show()\n# write get_keyword method\ndef get_keyword(x):\n   x_ = x.split(\" \")\n   keywords = []\n   try:\n      for word in x_:\n         if word + '_JD' in np.asarray(S2_TOP_JD['KW']):\n            keywords.append(word + '_JD')\n   except:\n      return -1\n\n   return keywords\n# get keywords from each row\ntext_Analysis['JDKW'] = text_Analysis['Job_Desc2'].apply(lambda x: get_keyword(x))\n# create dummy columns by keywords\nkwdummy = pd.get_dummies(text_Analysis['JDKW'].apply(pd.Series).stack()).sum(level=0)\n# Since a JD sometimes repeat a keyword, the value may >1\n# But what we want to know is whether the appearance of the keyword impact the salary, not frequency\n# So values >1 have to be replaced by 1, but there must be a better way than coding like this \u2193\nkwdummy = kwdummy.replace([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,35,39],\n                         [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])\n# merge back the dummy columns to the main dataset\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\n# let's see if number of buzzwords contained or how wordy the JD is would have impact.\ntext_Analysis['JDKWlen']=text_Analysis['JDKW'].str.len()\ntext_Analysis['JDlen']=text_Analysis['Job Description'].str.len()\n# run t-test for top keywords to see their correlation with salaries\ntext_columns = list(text_Analysis.columns)\nttests_JD=[]\nfor word in text_columns:\n    if word in set(S2_TOP_JD['KW']):\n        ttest2 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_JD.append([word,ttest2])\n\nttests_JD = pd.DataFrame(ttests_JD,columns=['KW','R'])\nttests_JD['R']=ttests_JD['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_JD['Statistic'],ttests_JD['P-value']=ttests_JD['R'].str.split(', ',1).str\nttests_JD=ttests_JD.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_JD\nJDBar=ttests_JD[(ttests_JD['P-value'].astype(float)<0.05)&(ttests_JD['Statistic'].astype(float)>0)]\nJDBar['Statistic']=(JDBar['Statistic'].astype(float)\/101)*100\nJDBar=JDBar.sort_values('Statistic',ascending=False).replace('_JD','',regex=True).replace('_',' ',regex=True)\nJDBar['KW']='\"' + JDBar['KW'] + '\"'\nfig = plt.figure(figsize=(13, 5))\nsns.barplot(x='KW',y='Statistic',data=JDBar).set(xlabel=\"\",ylabel=\"Salary Markup %\")\n\nplt.xticks(rotation=45,horizontalalignment='right')\n#Selecting keywords with p-value <0.1 into multiple regression model.\nttest_JD_pass1 = list(ttests_JD[ttests_JD['P-value'].astype(float)<0.05]['KW'])\nprint(*ttest_JD_pass1,sep=' + ')\n#Run regression and remove variables with p-value >0.05 one by one until all <0.05\nJDMod = ols(\"Est_Salary ~ CLUSTER_JD + COMPUTER_SCIENCE_JD + ALGORITHM_JD + PLATFORM_JD + PYTHON_JD + CASSANDRA_JD\",\n               data=text_Analysis).fit()\nprint(JDMod.summary())\n\"\"\"\nIt is unclear why 'Cluster' or 'Clustering' in JD would lead to lower salaries.\n\"\"\"\nfig = plt.figure(figsize=(13, 13))\nfig = sm.graphics.plot_partregress_grid(JDMod,fig=fig)\nfig.tight_layout(pad=1.0)\n\"\"\"\n## Correlation: Job Location (State) vs Salary\n\"\"\"\n# create dummy columns by State\nkwdummy = pd.get_dummies(text_Analysis['State'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\nS3 = text_Analysis['State'].value_counts().reset_index().rename(\n    columns={'index':'State','State':'Count'})\nS3_Top = S3[S3['Count']>29]\nS3_Top\n#run t-test for top states hiring engineers to see their correlation with salaries\ntext_columns = list(text_Analysis.columns)\nttests_state=[]\nfor word in text_columns:\n    if word in set(S3_Top['State']):\n        ttest3 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_state.append([word,ttest3])\n\nttests_state = pd.DataFrame(ttests_state,columns=['State','R'])\nttests_state['R']=ttests_state['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_state['Statistic'],ttests_state['P-value']=ttests_state['R'].str.split(', ',1).str\nttests_state=ttests_state.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_state\n#Selecting states with p-value <0.1 into multiple regression model.\nttest_state_pass = list(ttests_state[ttests_state['P-value'].astype(float)<0.1]['State'])\nprint(*ttest_state_pass,sep=' + ')\nStateMod = ols(\"Est_Salary ~ FL + CA + TX\",\n               data=text_Analysis).fit()\nprint(StateMod.summary())\n\"\"\"\nThe regional difference (job location) is the most crucial factor to the salary variation.\n\"\"\"\nfig = plt.figure(figsize=(13, 13))\nfig = sm.graphics.plot_partregress_grid(StateMod,fig=fig)\nfig.tight_layout(pad=1.0)\n\"\"\"\n## Correlation: Job Location (City) vs Salary\n\"\"\"\ntext_Analysis['City']=text_Analysis['City'].str.replace(' ','_',regex=True)\nS35 = text_Analysis['City'].value_counts().reset_index().rename(\n    columns={'index':'City','City':'Count'})\nS35_Top = S35[S35['Count']>29]\n# create dummy columns by City\nkwdummy = pd.get_dummies(text_Analysis[text_Analysis['City'].isin(np.asarray(S35_Top['City']))]['City'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\n#run t-test for top cities hring data engineers to see their correlation with salaries\ntext_columns = list(text_Analysis.columns)\nttests_city=[]\nfor word in text_columns:\n    if word in set(S35_Top['City']):\n        ttest35 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_city.append([word,ttest35])\n\nttests_city = pd.DataFrame(ttests_city,columns=['City','R'])\nttests_city['R']=ttests_city['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_city['Statistic'],ttests_city['P-value']=ttests_city['R'].str.split(', ',1).str\nttests_city=ttests_city.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_city\n#Selecting cities with p-value <0.1 into multiple regression model.\nttest_city_pass = list(ttests_city[ttests_city['P-value'].astype(float)<0.1]['City'])\nprint(*ttest_city_pass,sep=' + ')\nCityMod = ols(\"Est_Salary ~ Irving + Jacksonville + Houston + Fort_Worth + San_Jose + San_Diego + Los_Angeles + San_Antonio + Sunnyvale\",\n               data=text_Analysis).fit()\nprint(CityMod.summary())\n\"\"\"\n## Correlation: HQ Location (State) vs Salary\n\"\"\"\nS31 = text_Analysis['HQState'].value_counts().reset_index().rename(\n    columns={'index':'HQState','HQState':'Count'}).replace(0,'Unknown_State')\nS31_Top = S31[S31['Count']>29]\nS31_Top['HQState_HQ'] = [s + '_HQ' for s in S31_Top['HQState']]\n# create dummy columns by HQ State\nkwdummy = pd.get_dummies(S31_Top['HQState_HQ'].apply(pd.Series).stack()).sum(level=0)\nS31_Top2 = S31_Top.merge(kwdummy,left_index=True,right_index=True,how='left').drop(['Count'],axis=1)\ntext_Analysis = text_Analysis.merge(S31_Top2,on='HQState',how='left').replace(np.nan,0)\ntext_columns = list(text_Analysis.columns)\nttests_HQstate=[]\nfor word in text_columns:\n    if word in set(S31_Top['HQState_HQ']):\n        ttest31 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_HQstate.append([word,ttest31])\n\nttests_HQstate = pd.DataFrame(ttests_HQstate,columns=['HQState_HQ','R'])\nttests_HQstate['R']=ttests_HQstate['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_HQstate['Statistic'],ttests_HQstate['P-value']=ttests_HQstate['R'].str.split(', ',1).str\nttests_HQstate=ttests_HQstate.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_HQstate\nttest_HQstate_pass = list(ttests_HQstate[ttests_HQstate['P-value'].astype(float)<0.1]['HQState_HQ'])\nprint(*ttest_HQstate_pass,sep=' + ')\nHQStateMod = ols(\"Est_Salary ~ FL_HQ + TX_HQ + CA_HQ\",\n               data=text_Analysis).fit()\nprint(HQStateMod.summary())\n\"\"\"\nCompanies headquartered in CA pay more.\n\"\"\"\n\"\"\"\n## More Variables: Revenue, Size, Sector, Industry and Type of Ownership\n\"\"\"\n#Remove special characters.\ntext_Analysis['Revenue_USD'] = text_Analysis['Revenue_USD'].replace('[^A-Za-z0-9]+', '_',regex=True).replace(['_1_million','Unknown','5_10_billion'],['Small_Business','RevUnknown','Large_Corp'])\ntext_Analysis['Size'] = text_Analysis['Size'].replace('[^A-Za-z0-9]+', '_',regex=True).replace(['51_to_200_employees','10000_employees'],['SMB','Giant']).replace('Unknown','SizeUnknown')\ntext_Analysis['Sector'] = text_Analysis['Sector'].replace('[^A-Za-z0-9]+', '_',regex=True).replace('Unknown','SectorUnknown').replace(['Government','Unknown'],['GovSec','SectorUnknown'])\ntext_Analysis['Industry'] = text_Analysis['Industry'].replace('[^A-Za-z0-9]+', '_',regex=True).replace('Unknown','IndUnknown')\ntext_Analysis['Type of ownership'] = text_Analysis['Type of ownership'].replace('[^A-Za-z0-9]+', '_',regex=True).replace('Unknown','OwnUnknown')\n#Rename column name for running regression later.\ntext_Analysis = text_Analysis.rename(columns={\"Easy Apply\":\"Easy_Apply\"})\n\"\"\"\n### [Create Revenue Variables for Multiple Regression]\n\"\"\"\n# create dummy columns by Revenue\nkwdummy = pd.get_dummies(text_Analysis['Revenue_USD'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\nS4 = text_Analysis['Revenue_USD'].value_counts().reset_index().rename(\n    columns={'index':'Revenue_USD','Revenue_USD':'Count'})\nS4_Top = S4[S4['Count']>29]\nS4_Top\n\"\"\"\nRevenue '0' are those NaN values replaced for making dummy columns and are to be ignored.\n\"\"\"\n#run t-test to see the salary differences by companies' revenue.\ntext_columns = list(text_Analysis.columns)\nttests_rev=[]\nfor word in text_columns:\n    if word in set(S4_Top['Revenue_USD']):\n        ttest4 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_rev.append([word,ttest4])\n\nttests_rev = pd.DataFrame(ttests_rev,columns=['Revenue_USD','R'])\nttests_rev['R']=ttests_rev['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_rev['Statistic'],ttests_rev['P-value']=ttests_rev['R'].str.split(', ',1).str\nttests_rev=ttests_rev.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_rev\n#Selecting revenues with p-value <0.1 into multiple regression model.\nttest_rev_pass = list(ttests_rev[ttests_rev['P-value'].astype(float)<0.1]['Revenue_USD'])\nprint(*ttest_rev_pass,sep=' + ')\n\"\"\"\n### [Create Size Variables for Multiple Regression]\n\"\"\"\nkwdummy = pd.get_dummies(text_Analysis['Size'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\nS5 = text_Analysis['Size'].value_counts().reset_index().rename(\n    columns={'index':'Size','Size':'Count'})\nS5_Top = S5[S5['Count']>29]\nS5_Top\n\"\"\"\nSize '0' are those NaN values replaced for making dummy columns and are to be ignored.\n\"\"\"\ntext_columns = list(text_Analysis.columns)\nttests_size=[]\nfor word in text_columns:\n    if word in set(S5_Top['Size']):\n        ttest5 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_size.append([word,ttest5])\n\nttests_size = pd.DataFrame(ttests_size,columns=['Size','R'])\nttests_size['R']=ttests_size['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_size['Statistic'],ttests_size['P-value']=ttests_size['R'].str.split(', ',1).str\nttests_size=ttests_size.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_size\n\"\"\"\nIt's statistically significant that giants tend to pay 2K less and SMBs pay 2K more than average companies.\n\"\"\"\nttest_size_pass = list(ttests_size[ttests_size['P-value'].astype(float)<0.1]['Size'])\nprint(*ttest_size_pass,sep=' + ')\n\"\"\"\n### [Create Sector Variables for Multiple Regression]\n\"\"\"\nkwdummy = pd.get_dummies(text_Analysis['Sector'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\nS6 = text_Analysis['Sector'].value_counts().reset_index().rename(\n    columns={'index':'Sector','Sector':'Count'})\nS6_Top = S6[S6['Count']>29]\nS6_Top\ntext_columns = list(text_Analysis.columns)\nttests_sec=[]\nfor word in text_columns:\n    if word in set(S6_Top['Sector']):\n        ttest6 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_sec.append([word,ttest6])\n\nttests_sec = pd.DataFrame(ttests_sec,columns=['Sector','R'])\nttests_sec['R']=ttests_sec['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_sec['Statistic'],ttests_sec['P-value']=ttests_sec['R'].str.split(', ',1).str\nttests_sec=ttests_sec.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_sec\n\"\"\"\nBiotech and Pharmaceuticals sectors pay more.\n\"\"\"\nttest_sec_pass = list(ttests_sec[ttests_sec['P-value'].astype(float)<0.1]['Sector'])\nprint(*ttest_sec_pass,sep=' + ')\n\"\"\"\n### [Create Type of Ownership Variables for Multiple Regression]\n\"\"\"\nkwdummy = pd.get_dummies(text_Analysis['Type of ownership'].apply(pd.Series).stack()).sum(level=0)\ntext_Analysis = text_Analysis.merge(kwdummy,left_index=True,right_index=True,how='left').replace(np.nan,0)\nS8 = text_Analysis['Type of ownership'].value_counts().reset_index().rename(\n    columns={'index':'Type_of_ownership','Type of ownership':'Count'})\nS8_Top = S8[S8['Count']>29]\nS8_Top\ntext_columns = list(text_Analysis.columns)\nttests_own=[]\nfor word in text_columns:\n    if word in set(S8_Top['Type_of_ownership']):\n        ttest8 = stats.ttest_ind(text_Analysis[text_Analysis[word]>0]['Est_Salary'],\n                                 text_Analysis[text_Analysis[word]==0]['Est_Salary'])\n        ttests_own.append([word,ttest8])\n\nttests_own = pd.DataFrame(ttests_own,columns=['Type_of_ownership','R'])\nttests_own['R']=ttests_own['R'].astype(str).replace(['Ttest_indResult\\(statistic=','pvalue=','\\)'],['','',''],regex=True)\nttests_own['Statistic'],ttests_own['P-value']=ttests_own['R'].str.split(', ',1).str\nttests_own=ttests_own.drop(['R'],axis=1).sort_values('P-value',ascending=True)\nttests_own\nttest_own_pass = list(ttests_own[ttests_own['P-value'].astype(float)<0.1]['Type_of_ownership'])\nprint(*ttest_own_pass,sep=' + ')\n\"\"\"\n# Final Regression Model (California rocks!)\n\"\"\"\n\"\"\"\n\u2193The combined regression model before considering interaction terms.\n\"\"\"\nModC = ols(\"Est_Salary ~ FL + CA + TX + CASSANDRA_JD + ENGINEER + Irving + Houston + Fort_Worth + San_Diego + San_Antonio\",\n               data=text_Analysis).fit()\n# Rating, Years_Founded, Easy_Apply, PHD\/Master, Sector, Size, Type_of_ownership not significant\nprint(ModC.summary())\n# Trying different interaction terms.\ntext_Analysis['CA_CA_HQ']=text_Analysis['CA']*text_Analysis['CA_HQ']\ntext_Analysis['PYTHON_CASSANDRA']=text_Analysis['PYTHON_JD']*text_Analysis['CASSANDRA_JD']\ntext_Analysis['CA_PYTHON']=text_Analysis['CA']*text_Analysis['PYTHON_JD']\ntext_Analysis['CA_CASSANDRA']=text_Analysis['CA']*text_Analysis['CASSANDRA_JD']\ntext_Analysis['ENGINEER_FL']=text_Analysis['ENGINEER']*text_Analysis['FL']\ntext_Analysis['ENGINEER_CA']=text_Analysis['ENGINEER']*text_Analysis['CA']\ntext_Analysis['ENGINEER_TX']=text_Analysis['ENGINEER']*text_Analysis['TX']\ntext_Analysis['ENGINEER_CA_HQ']=text_Analysis['ENGINEER']*text_Analysis['CA_HQ']\ntext_Analysis['ENGINEER_PYTHON']=text_Analysis['ENGINEER']*text_Analysis['PYTHON_JD']\ntext_Analysis['ENGINEER_CASSANDRA']=text_Analysis['ENGINEER']*text_Analysis['CASSANDRA_JD']\ntext_Analysis['ENGINEER_Irving']=text_Analysis['ENGINEER']*text_Analysis['Irving']\ntext_Analysis['ENGINEER_Houston']=text_Analysis['ENGINEER']*text_Analysis['Houston']\ntext_Analysis['ENGINEER_Fort_Worth']=text_Analysis['ENGINEER']*text_Analysis['Fort_Worth']\ntext_Analysis['ENGINEER_San_Antonio']=text_Analysis['ENGINEER']*text_Analysis['San_Antonio']\n# Final model considering interaction terms.\nModC = ols(\"Est_Salary ~ FL + CA + TX + CASSANDRA_JD + ENGINEER + Irving + Houston + Fort_Worth + San_Diego + San_Antonio\",\n               data=text_Analysis).fit()\n# Rating, Years_Founded, Easy_Apply, PHD, Sector, Size, Type_of_ownership not significant\nprint(ModC.summary())\n\"\"\"\n* Regional difference (job location) is still the most deciding factor to salary variations.\n* Citywise, San Diego, CA is the best. In TX, only some cites' salaries are significantly lower, but some others such as Austin or Dallas are not.\n* Data Engineer with Apache Cassandra experience\/knowledge get higer pay.\n* If the position name does not directly contain 'Data Engineer', the salaries tend to be 4K lower.\n\"\"\"\nfig = plt.figure(figsize=(13, 26))\nfig = sm.graphics.plot_partregress_grid(ModC,fig=fig)\nfig.tight_layout(pad=1.0)\n\"\"\"\n# Deeper Look at California - Salary Distribution\n\"\"\"\n# create a separate dataset for CA\ndata_CA = data[data['State']=='CA']\npd.set_option('display.max_columns', None)\ndata_CA.describe(include='all')\nsns.set(style='white')\n\nf, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {\"height_ratios\": (0.2, 1)},figsize=(13,5))\nmean=data['Est_Salary'].mean()\nmedian=data['Est_Salary'].median()\n\nbph = sns.boxplot(data['Est_Salary'], ax=ax_box).set(xlabel=\"\")\nax_box.axvline(mean, color='k', linestyle='--')\nax_box.axvline(median, color='y', linestyle='-')\n\ndp1 = sns.distplot(data_CA['Est_Salary'],ax=ax_hist, color=\"r\").set(xlabel=\"Est. Salary ($'000)\")\ndp2 = sns.distplot(data['Est_Salary'],ax=ax_hist, color=\"g\").set(xlabel=\"Est. Salary ($'000)\")\nax_hist.axvline(mean, color='k', linestyle='--')\nax_hist.axvline(median, color='y', linestyle='-')\n\nplt.legend({'Mean (All)':mean,'Median (All)':median,'California':data_CA['Est_Salary'],'All':data['Est_Salary']})\nplt.xlim(0,210)\nplt.xticks(np.arange(0,210,step=10))\nplt.tight_layout() #Adjust the padding between and around subplots\nplt.show()\n\"\"\"\nCompared with that of the US as a whole, the salary distribution in CA shifts to the right, indicating overall higher salary payments.\n\"\"\"\n\"\"\"\n# [Heatmap] Number, Size and Salary of Hiring Companies (CA vs All)\n\"\"\"\n\"\"\"\nTo have an overview on the number, size and salary of those hiring companies and compare the outcomes between CA and all US, I want to create a heatmap.\n\"\"\"\n# Create a table for heatmap of number of companies with different sizes and revenues\nFirm_Size = data.pivot_table(columns=\"Size\",index=\"Revenue_USD\",values=\"Company Name\",aggfunc=pd.Series.nunique).reset_index()\nFirm_Size = Firm_Size[['Revenue_USD','1 to 50 employees','51 to 200 employees','201 to 500 employees','501 to 1000 employees','1001 to 5000 employees','5001 to 10000 employees','10000+ employees']]\nFirm_Size = Firm_Size.reindex([11,2,9,4,7,10,5,0,1,6,8,3,12])\nFirm_Size = Firm_Size.set_index('Revenue_USD').replace(np.nan,0)\n\n# Create a table for heatmap of number of companies with different sizes and revenues in CA\nFirm_Size_CA = data_CA.pivot_table(columns=\"Size\",index=\"Revenue_USD\",values=\"Company Name\",aggfunc=pd.Series.nunique).reset_index()\nFirm_Size_CA = Firm_Size_CA[['Revenue_USD','1 to 50 employees','51 to 200 employees','201 to 500 employees','501 to 1000 employees','1001 to 5000 employees','5001 to 10000 employees','10000+ employees']]\nFirm_Size_CA = Firm_Size_CA.reindex([11,2,9,4,7,10,5,0,1,6,8,3,12])\nFirm_Size_CA = Firm_Size_CA.set_index('Revenue_USD').replace(np.nan,0)\n\n# Create table for heatmap of salaries by companies with different sizes and revenues\nFirm_Size_Sal = data.pivot_table(columns=\"Size\",index=\"Revenue_USD\",values=\"Est_Salary\",aggfunc=np.mean).reset_index()\nFirm_Size_Sal = Firm_Size_Sal[['Revenue_USD','1 to 50 employees','51 to 200 employees','201 to 500 employees','501 to 1000 employees','1001 to 5000 employees','5001 to 10000 employees','10000+ employees']]\nFirm_Size_Sal = Firm_Size_Sal.reindex([11,2,9,4,7,10,5,0,1,6,8,3,12])\nFirm_Size_Sal = Firm_Size_Sal.set_index('Revenue_USD').replace(np.nan,0)\n\n# Create table for heatmap of salaries by companies with different sizes and revenues in CA\nFirm_Size_CA_Sal = data_CA.pivot_table(columns=\"Size\",index=\"Revenue_USD\",values=\"Est_Salary\",aggfunc=np.mean).reset_index()\nFirm_Size_CA_Sal = Firm_Size_CA_Sal[['Revenue_USD','1 to 50 employees','51 to 200 employees','201 to 500 employees','501 to 1000 employees','1001 to 5000 employees','5001 to 10000 employees','10000+ employees']]\nFirm_Size_CA_Sal = Firm_Size_CA_Sal.reindex([11,2,9,4,7,10,5,0,1,6,8,3,12])\nFirm_Size_CA_Sal = Firm_Size_CA_Sal.set_index('Revenue_USD').replace(np.nan,0)\nf, axs = plt.subplots(nrows=2,ncols=2, sharey=True,sharex=True, figsize=(13,9))\n\nfs = sns.heatmap(Firm_Size,annot=True,fmt='.0f',annot_kws={\"size\": 12},cmap=\"YlGnBu\", ax=axs[0,0]).set(title=\"Number of Companies in the US\",xlabel=\"\")\nfsc = sns.heatmap(Firm_Size_CA,annot=True,fmt='.0f',annot_kws={\"size\": 12},cmap=\"YlGnBu\", ax=axs[0,1]).set(title=\"Number of Companies in CA\",xlabel=\"\",ylabel=\"\")\nfss = sns.heatmap(Firm_Size_Sal,annot=True,fmt='.0f',annot_kws={\"size\": 12},cmap=\"Oranges\",ax=axs[1,0]).set(title=\"Avg. Salaries in the US\")\nfscs = sns.heatmap(Firm_Size_CA_Sal,annot=True,fmt='.0f',annot_kws={\"size\": 12},cmap=\"Oranges\",ax=axs[1,1]).set(title=\"Avg. Salaries in CA\",ylabel=\"\")\n\nplt.setp([a.get_xticklabels() for a in axs[1,:]],rotation=45,ha='right')\nplt.tight_layout()\nplt.show()\n\"\"\"\n* A big portion of source of data engineer hiring are from giants (10K+ employees & USD10B+ revenues).\n* There's high demand among financially unpublic firms (Revenue 'Unknown'). And they pay similar or even slightly higher salaries to data engineers than giants.\n* In California, Small firms (especially 51-200 employees & USD5-50M revenues) and medium-large businesses (1001-5000 employees & 50M-1B revenues unknown) pay more.\n* Companies in CA obviously pay more (27K+).\n\"\"\"\n\"\"\"\n## Who are those high-paying small firms in CA?\n\"\"\"\nca_sal_by_firm = data_CA.groupby('Company Name')[['Est_Salary']].mean().reset_index()\nSmallHighPay = data_CA[((data_CA['Revenue_USD']=='5-10 million')|(data_CA['Revenue_USD']=='10-25 million')|(data_CA['Revenue_USD']=='25-50 million'))&(\n    data_CA['Size']=='51 to 200 employees')]['Company Name'].value_counts().reset_index().rename(\n    columns={'index':'Company Name','Company Name':'Hires'})\nSmallHighPay = SmallHighPay.merge(ca_sal_by_firm, on='Company Name',how='left')\nSmallHighPay = SmallHighPay.merge(data_CA[['Company Name','Rating','Headquarters','Type of ownership','Industry','Sector','Years_Founded','Competitors']], on='Company Name',how='left')\nSmallHighPay = SmallHighPay.drop_duplicates().reset_index(drop=True)\nSmallHighPay\nSmallHighPay.describe(include='all')\n\"\"\"\n### Characters of those high-paying small firms in CA\n* Most are private companies (51-200 employees & USD5-50M revenues). \n* More than half are IT companies.\n* Avg. hires: 1.4; Avg. rating 4 (higher than ttl. avg. 3.8); Avg. company age: 18.7 (ttl. avg. 37); Avg. salary: 138K (ttl. avg. 100)\n\"\"\"\n\"\"\"\n## Who are those high-paying medium-large businesses in CA?\n\"\"\"\nMLHighPay = data_CA[((data_CA['Revenue_USD']=='50-100 million')|(\n    data_CA['Revenue_USD']=='100-500 million')|(\n    data_CA['Revenue_USD']=='0.5-1 billion'))&(\n    data_CA['Size']=='1001 to 5000 employees')]['Company Name'].value_counts().reset_index().rename(\n    columns={'index':'Company Name','Company Name':'Hires'})\nMLHighPay = MLHighPay.merge(ca_sal_by_firm, on='Company Name',how='left')\nMLHighPay = MLHighPay.merge(data_CA[['Company Name','Rating','Headquarters','Type of ownership','Industry','Sector','Years_Founded','Competitors']], on='Company Name',how='left')\nMLHighPay = MLHighPay.drop_duplicates().reset_index(drop=True)\nMLHighPay\nMLHighPay.describe(include='all')\n\"\"\"\n### Characters of those high-paying medium-large businesses in CA \n* Half are private IT companies (1001-5000 employees & 50M-1B revenues unknown). \n* Avg. hires: 1.3; Avg. rating 4 (higher than ttl. avg. 3.5); Avg. company age: 29.5 (ttl. avg. 37); Avg. salary: 132K (ttl. avg. 100)\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Revenues (CA)\n\"\"\"\nRevCountCA = data_CA.groupby('Revenue_USD')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Count'}).sort_values(\n    'Count', ascending=False).reset_index(drop=True)\nRevCountCA = RevCountCA.merge(data_CA, on='Revenue_USD',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Count',y='Revenue_USD',data=RevCountCA,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Revenue_USD',data=RevCountCA, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\nIn CA, a dominant portion of data engineers positions are largely released by companies with revenues information unknown.\n\"\"\"\n\"\"\"\n## Hires and Salary Estimates by Sizes (CA)\n\"\"\"\nSizeCountCA = data_CA.groupby('Size')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Count'}).sort_values(\n    'Count', ascending=False).reset_index(drop=True)\nSizeCountCA = SizeCountCA.merge(data_CA, on='Size',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Count',y='Size',data=SizeCountCA,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Size',data=SizeCountCA, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n# More on California Data Engineer Salary (Sector & Type of Ownership)\n\"\"\"\n\"\"\"\n### Hires and Salary Estimates by Sectors (CA)\n\"\"\"\nSecCountCA = data_CA.groupby('Sector')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Count'}).sort_values(\n    'Count', ascending=False).head(12).reset_index(drop=True)\nSecCountCA = SecCountCA.merge(data_CA, on='Sector',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Count',y='Sector',data=SecCountCA,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Sector', join=False,data=SecCountCA,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n### Hires and Salary Estimates by Types of Ownership (CA)\n\"\"\"\nOwnCountCA = data_CA.groupby('Type of ownership')[['Job Title']].count().reset_index().rename(columns={'Job Title':'Count'}).sort_values(\n    'Count', ascending=False).reset_index(drop=True)\nOwnCountCA = OwnCountCA.merge(data_CA, on='Type of ownership',how='left')\nsns.set(style=\"whitegrid\")\nf, (ax_bar, ax_point) = plt.subplots(ncols=2, sharey=True, gridspec_kw= {\"width_ratios\":(0.6,1)},figsize=(13,7))\nsns.barplot(x='Count',y='Type of ownership',data=OwnCountCA,ax=ax_bar)\nsns.pointplot(x='Est_Salary',y='Type of ownership',data=OwnCountCA, join=False,ax=ax_point).set(ylabel=\"\",xlabel=\"Salary ($'000)\")\n\nplt.tight_layout()\n\"\"\"\n# Upvote if you like my work!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '86685466eee703'}"}
{"id":"10277","text":"pip install pygal\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt \nimport plotly as plot\nimport pygal as py\nimport squarify as sq\nimport missingno as msg\nimport sklearn\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline \ndf=pd.read_csv(\"..\/input\/internet-service-churn\/internet_service_churn.csv\",engine=\"python\",encoding=\"utf-8 \")\ndf\ndf.head(10)\ndf.shape\ndf.dtypes\ndf[\"churn\"].dtype\ndf_cols=df.columns.tolist()\nfor i in df.columns.tolist():\n    print(i)\ndf.describe().transpose()\ndf.isnull().sum()\ndf.info()\nmsg.heatmap(df);plt.show()\ndf.drop('id',axis='columns', inplace=True)\ndf\nlist_sub1=df[[\"is_tv_subscriber\",\"is_movie_package_subscriber\"]].sum()\nlist_sub1\nprint (\"How many are not tv subscriber :\" , df[df[\"is_tv_subscriber\"]==0].count()[\"churn\"])\nprint (\"How many are not movie_package_subscriber :\" , df[df[\"is_movie_package_subscriber\"]==0].count()[\"churn\"])\nlist_sub1.plot.bar()\n# create data\nx = [\"is_tv_subscriber\",\"is_movie_package_subscriber\"]\ny1 = [df[df[\"is_tv_subscriber\"]==1].count()[\"is_tv_subscriber\"],df[df[\"is_tv_subscriber\"]==0].count()[\"is_tv_subscriber\"]]\ny2 = [df[df[\"is_movie_package_subscriber\"]==1].count()[\"is_movie_package_subscriber\"],df[df[\"is_movie_package_subscriber\"]==0].count()[\"is_movie_package_subscriber\"]]\n  \nplt.bar(x, y1, color='g')\nplt.bar(x, y2, bottom=y1, color='b')\nplt.legend([\"subscriber\",\"not a subscriber\"])\nplt.title(\"subscribers both for tv and mobile\")\nplt.show()\nsns.boxplot(x=\"churn\",y=\"subscription_age\",data=df);plt.show() \ndf[\"is_tv_subscriber\"].count()\nsubscribers=[\"is_tv_subscriber\",\"is_movie_package_subscriber\"]\nfor i in subscribers:\n    sns.categorical.boxenplot(x=\"churn\",y=\"bill_avg\",data=df,hue=i);plt.title(\"avg bill of \"+ i)\n    plt.show()\ndf.loc[:,[\"subscription_age\",\"bill_avg\"]]\nlist2=list(df.loc[:,[\"subscription_age\",\"bill_avg\"]].columns)\nfor i in list2:\n    df[i].plot.hist(bins=20,title= str(i)+ \" historgram\")\n    plt.show()\ncorrelation=df.corr();correlation\nsns.set_palette(\"Accent\")\nplt.figure(figsize=(15,8))\nsns.heatmap(correlation,vmin=-1,vmax=1,annot=True);plt.show()\ndf2=df.loc[:,[\"subscription_age\",\"bill_avg\",\"reamining_contract\",\"service_failure_count\",\"download_avg\",\"upload_avg\"]]\nfor i in df2.columns.tolist():\n    df[i].plot.box(patch_artist = True,notch ='True')\n    plt.title(\"boxplot for \"+ str(i))\n    plt.show()\n    print([df[i].quantile(0.25),df[i].quantile(0.5),df[i].quantile(0.75),df[i].quantile(1)])\nsns.set_style(\"darkgrid\")\nsns.countplot(x=\"download_over_limit\",hue=\"churn\",data=df);plt.show()\ndf=df.dropna()\nsns.pairplot(df,hue=\"churn\");plt.show() \n\"\"\"\n# Feature Selection\n\"\"\"\n\"\"\"\n# univariate selection\n\"\"\"\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\ndf[\"subscription_age\"]=[abs(i) for i in df[\"subscription_age\"]]\ny=df[\"churn\"]\nx=df.loc[:,[\"is_tv_subscriber\",\"is_movie_package_subscriber\",\"subscription_age\",\"bill_avg\",\"reamining_contract\",\"service_failure_count\",\"download_avg\",\"upload_avg\",\"download_over_limit\"]]\nbestcolumns=SelectKBest(score_func=chi2,k=\"all\")\nfit=bestcolumns.fit(x,y)\ndf_scores=pd.DataFrame(fit.scores_)\ndfcolumns=pd.DataFrame(x.columns)\nfeatureScores=pd.concat([dfcolumns,df_scores],axis=1)\nfeatureScores.columns=[\"Features\",\"scores\"]\nfeatureScores\nX_kbest = bestcolumns.fit_transform(x, y)\nprint('Original number of features:', x.shape[1])\nprint('Reduced number of features:', X_kbest.shape[1])\nfeatureScores.plot.bar(x=\"Features\",y=\"scores\") #using chi method for feature selection\nplt.show()\n#result doesn't show well . so,we used another method\n\"\"\"\n# Filter method for the feature selection using information gain\n\"\"\"\nfrom sklearn.feature_selection import mutual_info_classif\nimportant_features =mutual_info_classif(x,y)\nfeat_importances=pd.Series(important_features,df.columns[0:len(df.columns)-1])\nfeat_importances\nfeat_importances.plot.barh(color=\"teal\");plt.show()\n# Import libraries\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import tree\nfrom sklearn.ensemble import RandomForestClassifier\n# Normalize feature vector\nX2 = StandardScaler().fit_transform(x)\nx_train, x_test, y_train, y_test = train_test_split(X2, y, test_size = 0.30, random_state = 0)\nclf = RandomForestClassifier(n_estimators=100, random_state=0)\nclf.fit(x_train, y_train)\ny_pred = clf.predict(x_test)\ny_pred\n\nplt.figure(num=None, figsize=(10,8), dpi=80, facecolor='firebrick', edgecolor='pink')\n\nfeat_importances = pd.Series(clf.feature_importances_, index= x.columns)\n\nfeat_importances.nlargest(10).plot(kind='barh')\n\"\"\"\nMost important features or columns are:\"subscription_age\",\"bill_avg\",\"reamining_contract\",\"download_avg\",\"upload_avg\"\n\"\"\"\ndf.reset_index()\nfrom sklearn.tree import DecisionTreeClassifier\ndf2=df.loc[:,[\"subscription_age\",\"bill_avg\",\"reamining_contract\",\"download_avg\",\"upload_avg\",\"churn\"]]\ndf2=df2.reset_index();df2\na=df2.loc[:,[\"subscription_age\",\"bill_avg\",\"reamining_contract\",\"download_avg\",\"upload_avg\"]]\ny=df2[\"churn\"]\n#Using the train_test_split to create train and test sets.\na_train, a_test, y_train, y_test = train_test_split(a, y, random_state = 50, test_size = 0.25)\na\nclf = DecisionTreeClassifier(criterion = 'entropy')\n#Training the decision tree classifier. \nclf.fit(a_train, y_train)\ny_pred=clf.predict(a_train)\ny_pred\nfrom sklearn.metrics import accuracy_score\nprint('Accuracy Score on train data: ', accuracy_score(y_true=y_train, y_pred=clf.predict(a_train)))\nprint('Accuracy Score on test data: ', accuracy_score(y_true=y_test, y_pred=clf.predict(a_test)))\nclf.predict([[11.94,32,1.38,69.4,4.0]])\n# Creating some predictions.\nfrom sklearn.model_selection import cross_val_predict\ny_train_pred = cross_val_predict(clf, a_train, y_train, cv=3)\n\n\n# Constructing the confusion matrix.\nfrom sklearn.metrics import confusion_matrix\nmatrix=confusion_matrix(y_train, y_train_pred)\nmatrix\nconfusion_matrix(y_test,clf.predict(a_test))\nsns.heatmap(confusion_matrix(y_train, y_train_pred),annot=True);\nplt.title(\"Confusion matrix for train data\");plt.show()\nprint(\"accuracy using confusion matrix for train data =\" , (matrix[0,0]+matrix[1,1])*100\/(matrix[0,0]+matrix[1,1]+matrix[0,1]+matrix[1,0]))\nmatrix2=confusion_matrix(y_test,clf.predict(a_test))\n\nprint(\"accuracy using confusion matrix for test data =\" , (matrix2[0,0]+matrix2[1,1])*100\/(matrix2[0,0]+matrix2[1,1]+matrix2[0,1]+matrix2[1,0]))\npip install pydotplus\n#create tree for decision tree classifier\nfrom io import StringIO  \nfrom IPython.display import Image as image  \nfrom sklearn.tree import export_graphviz\nimport pydotplus\ndot_data = StringIO()\nexport_graphviz(clf, out_file=dot_data,  \n                filled=True, rounded=True,\n                special_characters=True)\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue())  \nimage(graph.create_png())","meta":"{'source': 'AI4Code', 'id': '12d9363dae9799'}"}
{"id":"19938","text":"\"\"\"\n<font size=\"6\"><b>House price - Advanced Regression Technique<\/b><\/font>\n\nShout out to these notebooks that helped me a lot in my first notebook on Kaggle:\n- <a href=\"https:\/\/www.kaggle.com\/pmarcelino\/comprehensive-data-exploration-with-python\">Comprehensive data exploration with Python - PEDRO MARCELINO<\/a>\n- <a href=\"https:\/\/www.kaggle.com\/dgawlik\/house-prices-eda\">House Prices EDA - DOMINIK GAWLIK<\/a>\n- <a href=\"https:\/\/www.kaggle.com\/gcdatkin\/top-10-house-price-regression-competition-nb\">House Price Regression Competition NB - GABRIEL ATKIN<\/a>\n\"\"\"\n\"\"\"\n# 1. Overview\n\n**Data**\n\nThe data set is about house price in Ames, Iowa. It contains 79 explainatory variables describing some aspects of residential homes.\n\n**Goal**\n\nThe goal is to predict the sale price for each house based on given 79 explainatory variables.\n\n**Metric**\n\nPredictions are evaluated using RMSE between the logarithm of the predicted value and the logarithm of the observed sales price.\n\"\"\"\n# import libraries\n# Essentials\nimport numpy as np\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Plot\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')\n\n# preprocessing\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom category_encoders import MEstimateEncoder\n\n# models\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom sklearn.linear_model import Ridge, RidgeCV\nfrom sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier\n\n# stats\nfrom scipy.stats import norm\nfrom scipy import stats\n# import training data\ntrain_df = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\n# drop id column\ntrain_df = train_df.drop(columns= 'Id')\nprint(f\"Size of training set: {train_df.shape}\")\ntrain_df.head()\n# import test data\ntest_df = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\ntest_id = test_df['Id']\n# drop id column\ntest_df = test_df.drop(columns='Id')\nprint(f\"Size of test set: {test_df.shape}\")\ntest_df.head()\ncols = train_df.columns\nquantitatives = train_df.select_dtypes(exclude={'object'}).columns\nqualitatives = train_df.select_dtypes(include={'object'}).columns\nprint(f\"Number of quantitative variables: {len(quantitatives)}\")\nprint(quantitatives)\nprint(f\"Number of qualitative variables: {len(qualitatives)}\")\nprint(qualitatives)\ntrain_df.describe()\n\"\"\"\n# 2. Explainatory Data Analysis\n\"\"\"\n\"\"\"\n## 2.1. Examine Target Variable (Sale Price)\nFirst, we examine the distribution of SalePrice\n\"\"\"\nsns.distplot(train_df['SalePrice'], fit= norm)\nplt.title(\"Sale Price distribution\")\nplt.xlabel(\"Sale Price\")\nplt.ylabel(\"Frequency\")\n\nfig = plt.figure()\nres = stats.probplot(train_df['SalePrice'], plot= plt)\n# skewness and kurtosis\nprint(f\"Skewness: {train_df['SalePrice'].skew()}\")\nprint(f\"Kurtosis: {train_df['SalePrice'].kurt()}\")\n\"\"\"\nThe SalePrice is positive skewed, and show peakedness.\n\"\"\"\n\"\"\"\n## 2.2. Numerical Variables\n\n**Heatmap**\n\"\"\"\ncorr_matrix = train_df.corr()\n\nfig = plt.figure(figsize=(12, 8))\nsns.heatmap(corr_matrix)\nplt.title(\"Correlation heatmap\")\ntop10_corr = corr_matrix.sort_values('SalePrice', ascending= False)[0:10]\ntop10_corr = top10_corr.loc[:, top10_corr.index]\n\nfig = plt.figure(figsize= (6, 6))\nsns.heatmap(top10_corr, annot= True)\nplt.title(\"Zoom in heatmap\")\n\"\"\"\nHighly related variables:\n- 'TotalBsmtSF' and '1stFlrSF'\n- 'GarageCars' and 'GarageArea'\n- 'GrLivArea' and 'TotRmsAbvGrd'\n- 'YearBuilt' and 'GarageYrBlt'\n\nVariables that correlated with 'SalePrice': 'OverallQual', 'GrLivArea', 'GarageArea', 'TotalBsmtSF', 'YearBuilt'. '1stFlrSF', 'GarageCars', 'TotRmsAbvGrd' are excluded because they are related to one of those 4. 'FullBath' is considered not so important.\n\n\n\n**Relation of numerical variables to 'SalePrice'**\n\"\"\"\nn_rows = 12\nn_cols = 3\n\nfig, axs = plt.subplots(n_rows, n_cols, figsize= (4*n_cols, 3*n_rows))\n\nfor row in range(n_rows):\n    for col in range(n_cols):\n        i = row * n_cols + col\n        if i > len(quantitatives) - 2:\n            break\n        variable = quantitatives[i]\n        sns.scatterplot(x= train_df[variable], y= train_df['SalePrice'], ax= axs[row, col])\n\nplt.tight_layout()\nplt.show()\n\"\"\"\nFrom those charts, highly correlated variables mentioned above have sort of linear relationship with 'SalePrice'. Those charts also imply some exponential relationships, so we can log transform some features to get a better model.\n\nCandidates for log transformation: 'LotFrontage', 'LotArea', 'BsmtFinSF1', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'GrLivArea', 'GarageArea'.\n\nWe can see that some variables are rather categorical variables, and some outliers need to be eliminate.\n\n**Outliers**\n\"\"\"\n# outliers in GrLivArea\ntrain_df = train_df.drop(train_df.loc[(train_df['GrLivArea'] > 4000) & (train_df['SalePrice'] < 200000)].index)\nsns.scatterplot(x= train_df['GrLivArea'], y= train_df['SalePrice'])\n# outliers in TotalBsmtSF\ntrain_df = train_df.drop(train_df[train_df['TotalBsmtSF'] > 6000].index)\nsns.scatterplot(x= train_df['TotalBsmtSF'], y= train_df['SalePrice'])\n\"\"\"\n## 2.3. Categorical Variables\n\n**Relation of categorical variables to 'SalePrice'**\n\"\"\"\nn_rows = 15\nn_cols = 3\n\nfig, axs = plt.subplots(n_rows, n_cols, figsize= (4*n_cols, 3*n_rows))\n\nfor row in range(n_rows):\n    for col in range(n_cols):\n        i = row * n_cols + col\n        if i >= len(qualitatives):\n            break\n        variable = qualitatives[i]\n        sns.boxplot(x= train_df[variable], y= train_df['SalePrice'], ax= axs[row, col])\n        \nplt.tight_layout()\nplt.show()\n\"\"\"\nFrom the plots:\n- Variables having good disparity with respect to 'SalePrice' are: \u2018MSZoning\u2019, \u2019Neighborhood\u2019, \u2018Condition1\u2019, \u2018Condition2\u2019, \u2018RoofMatl\u2019, \u2018MatVnrType\u2019, \u2019ExterQual\u2019, \u2018BsmtQual\u2019, \u2018BsmtCond\u2019, \u2018CentralAir\u2019, \u2019KitchenQual\u2019, \u2018SaleType\u2019, \u2018SaleCondition\u2019.\n- House that have excellent Pool Quality tends to have higher sale price.\n- Partial sale condition tends to have higher sale price.\n\n# 3. Data Preprocessing\n## 3.1. Missing value\n\n\n\n\"\"\"\ntrain_missing_value = train_df.isnull().sum().sort_values(ascending= False)\ntrain_missing_value = train_missing_value[train_missing_value > 0]\ntrain_missing_value\ntest_missing_value = test_df.isnull().sum().sort_values(ascending= False)\ntest_missing_value = test_missing_value[test_missing_value > 0]\ntest_missing_value\n# cut saleprice\nsale_price = train_df['SalePrice']\ntrain_df = train_df.drop(columns={'SalePrice'})\n# combine test and training data\nall_data = pd.concat([train_df, test_df], ignore_index= True)\nall_data.shape\ndef knn_regressor_fill(col, df):\n    df = df.copy()\n    numeric_non_na_cols = df.select_dtypes(exclude= {'object'}).loc[:, df.isnull().sum() == 0].columns\n\n    train = df.loc[df[col].isna() == False][numeric_non_na_cols]\n    labels = df.loc[df[col].isna() == False][col]\n    test = df.loc[df[col].isna() == True][numeric_non_na_cols]\n\n    knn = KNeighborsRegressor()\n    knn.fit(train, labels)\n    preds = knn.predict(test)\n    \n    df.loc[df[col].isna() == True, col] = preds\n    return df[col]\ndef knn_clf_fill(col, df):\n    df = df.copy()\n    numeric_non_na_cols = df.select_dtypes(exclude= {'object'}).loc[:, df.isnull().sum() == 0].columns\n\n    train = df.loc[df[col].isna() == False][numeric_non_na_cols]\n    labels = df.loc[df[col].isna() == False][col]\n    test = df.loc[df[col].isna() == True][numeric_non_na_cols]\n\n    knn = KNeighborsClassifier()\n    knn.fit(train, labels)\n    preds = knn.predict(test)\n    \n    df.loc[df[col].isna() == True, col] = preds\n    return df[col]\n# Missing Categorical variables can be consider as None or NA\nfill_na = ['PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu', 'GarageCond', 'GarageType',\n          'GarageFinish', 'GarageQual', 'BsmtExposure', 'BsmtFinType2', 'BsmtCond', 'BsmtQual', 'BsmtFinType1']\nfill_cat = ['Electrical', 'MSZoning', 'Functional', 'Utilities', 'KitchenQual', 'SaleType', 'Exterior2nd', 'Exterior1st', 'GarageCars']\nfill_num = ['LotFrontage', 'BsmtFinSF1', 'BsmtFinSF2', 'GarageArea', 'TotalBsmtSF', 'GarageYrBlt']\nfill_0 = ['MasVnrArea', 'BsmtHalfBath', 'BsmtFullBath', 'BsmtUnfSF']\n\nfor col in fill_na:\n    all_data[col].fillna('NA', inplace= True)\n\nfor col in fill_cat:\n    #val = train_df[col].mode()[0] \n    #all_data[col].fillna(val, inplace= True)\n    # fill with knn maybe ??\n    all_data[col] = knn_clf_fill(col, all_data)\n\nfor col in fill_num:\n    #val =train_df[col].mean()\n    #all_data[col].fillna(val, inplace= True)\n    # fill with knn maybe ??\n    all_data[col] = knn_regressor_fill(col, all_data)\n    \nfor col in fill_0:\n    all_data[col].fillna(0, inplace= True)\n    \nall_data['MasVnrType'].fillna('None', inplace= True)\n\nprint(f\"Number of missing data: {all_data.isnull().sum().sum()}\")\n\"\"\"\n## 3.2. Features Engineering\n\n\"\"\"\n\"\"\"\nAdd more features\n\"\"\"\n# creating features\nall_data['TotBathRms'] = all_data['FullBath'] + all_data['BsmtFullBath'] + 0.5*(all_data['HalfBath'] + all_data['BsmtHalfBath'])\nall_data['TotOutsideSF'] = all_data['OpenPorchSF'] + all_data['EnclosedPorch'] + all_data['3SsnPorch'] + \\\n                            all_data['ScreenPorch'] + all_data['WoodDeckSF']\nall_data[\"LivLotRatio\"] = all_data['GrLivArea'] \/ all_data['LotArea']\nall_data[\"Spaciousness\"] = (all_data['1stFlrSF'] + all_data['2ndFlrSF']) \/ all_data['TotRmsAbvGrd']\nall_data['hasPool'] = all_data['PoolArea'].apply(lambda x: 1 if x > 0 else x)\nall_data['hasGarage'] = all_data['GarageArea'].apply(lambda x: 1 if x > 0 else x)\nall_data['hasBsmt'] = all_data['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else x) \n\"\"\"\nTarget Encoding\n\"\"\"\ntarget_encoding_cols = train_df.select_dtypes(include= {'object'}).nunique()\ntarget_encoding_cols = target_encoding_cols[target_encoding_cols > 10].index\ntarget_encoding_cols\nencoder = MEstimateEncoder(cols= target_encoding_cols.values.tolist(), m= 2)\nencoder.fit(all_data[:len(train_df)], sale_price)\nall_data = encoder.transform(all_data)\n\"\"\"\n## 3.3. Data Transformation\nFirst, we fix skewness in 'SalePrice'\n\"\"\"\nsale_price = np.log1p(sale_price)\n\n# plot the SalePrice again to check normality\nsns.distplot(sale_price, fit= norm)\nplt.title(\"Sale Price distribution\")\nplt.xlabel(\"Sale Price\")\nplt.ylabel(\"Frequency\")\n\nfig = plt.figure()\nres = stats.probplot(sale_price, plot= plt)\n\"\"\"\nNow, we log transform skewed numerical variables.\n\"\"\"\nskewness_df = pd.DataFrame(train_df.skew(), columns=['Skewness'], \\\n                           index= train_df.select_dtypes(exclude=['object']).columns)\nskewness_df['Skewed'] = skewness_df['Skewness'].apply(lambda x: True if abs(x) > 0.5 else False)\nskewness_df\nlog_transform_cols = skewness_df[skewness_df['Skewed'] == True].index.to_list()\nfor col in log_transform_cols:\n    all_data.loc[all_data[col] > 0][col+'_log'] = np.log1p(all_data.loc[all_data[col] > 0][col])\n\"\"\"\n## 3.4. Encode Categorical Variables\n\"\"\"\nall_data = pd.get_dummies(all_data)\nall_data.shape\n\"\"\"\n# 4. Train Model\n## 4.1. Split Data\n\n\"\"\"\nX_train = all_data[:len(train_df)]\ny_train = sale_price\nX_test = all_data[len(train_df):]\n\nprint(f\"Number of training observations: {X_train.shape[0]}\")\n\"\"\"\n## 4.2. Set up model and metric\n\"\"\"\nkf = KFold(n_splits= 5, random_state= 7, shuffle= True)\nrf_params = {\n    'n_estimators': 1000,\n    'max_depth' : 10,\n    'random_state': 5\n}\n\nGBR_params = {\n    'learning_rate': 0.0511,\n    'n_estimators': 5000,\n    'max_depth' : 5,\n    'n_iter_no_change' : 5,\n    'random_state' : 5\n}\n\nxgboost_params = {\n    'learning_rate' : 0.115,\n    'max_depth' : 6,\n    'n_estimators' : 500,\n    'random_state' : 5,\n    'subsample' : 0.8,\n    'gamma' : 0.05,\n    'random_state' : 5\n}\n\nridge_params = {\n    'alphas' : np.array([1, 1.511, 0.95, 0.93, 0.01, 0.05]),\n    'cv' : kf\n}\nmodels = {\n    \"Ridge\" : RidgeCV(**ridge_params),\n    \"RandomForest\": RandomForestRegressor(**rf_params),\n    \"GradientBoosting\": GradientBoostingRegressor(**GBR_params),\n    \"XGBoost\": XGBRegressor(**xgboost_params)\n}\n\"\"\"\n## 4.3. Train Model and Evaluate\n\"\"\"\nfor name, model in models.items():\n    model.fit(X_train, y_train)\n    print(name + \" trained\")\nfor name, model in models.items():\n    scores = -cross_val_score(model, X_train, y_train, scoring='neg_root_mean_squared_error', n_jobs= -1, cv=kf)\n    print(f\"{name}: {scores} -- Average: {scores.mean()}\")\n\n\"\"\"\n## 4.4. Prediction and Submission\n\"\"\"\nfinal_preds = 0.1 * np.expm1(models['RandomForest'].predict(X_test)) \\\n            + 0.2 * np.expm1(models['GradientBoosting'].predict(X_test)) \\\n            + 0.35 * np.expm1(models['XGBoost'].predict(X_test)) \\\n            + 0.35 * np.expm1(models['Ridge'].predict(X_test))\n\nfinal_preds\nsubmission = pd.concat([test_id, pd.Series(final_preds, name='SalePrice')], axis=1)\nsubmission\nsubmission.to_csv('.\/submission.csv', index=False, header=True)","meta":"{'source': 'AI4Code', 'id': '2474589a16c4e3'}"}
{"id":"15282","text":"\"\"\"\n# Wrangling of Pak Election DATA\n\"\"\"\n\"\"\"\n## Importing liabraries required\n\"\"\"\n# 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\n\"\"\"\n## Loading data using pandas.read_csv\n\"\"\"\nNA_2002 = pd.read_csv(\"..\/input\/predict-pakistan-elections-2018\/National Assembly 2002 - Updated.csv\",encoding = \"ISO-8859-1\")\nNA_2008 = pd.read_csv(\"..\/input\/predict-pakistan-elections-2018\/National Assembly 2008.csv\",encoding = \"ISO-8859-1\")\nNA_2013 = pd.read_csv(\"..\/input\/predict-pakistan-elections-2018\/National Assembly 2013 - Updated.csv\",encoding = \"ISO-8859-1\")\n\"\"\"\n## Getting information about dataset\n\"\"\"\nprint('Data Dimentions of NA_2002:',NA_2002.shape)\nprint('Data Dimentions of NA_2008:',NA_2008.shape)\nprint('Data Dimentions of NA_2013:',NA_2013.shape)\nprint(\"NA_ 2002.csv\")\nNA_2002.info()\nprint(\"NA_2008.csv\")\nNA_2008.info()\nprint(\"NA_2013.csv\")\nNA_2013.info()\n\"\"\"\n### Issues in data:\nUnnamed Columns in NA_2008 and NA_2013.\n\nTotal number of columns in NA_2013 because there is and extra Unnamed column with no data.\n\nData type of Turnout Column is not approriate. It must be float64.\n\"\"\"\n\"\"\"\n### Cleaning data\n\"\"\"\n\"\"\"\nChanging Data type of Turnout to flot.\n\"\"\"\nNA_2008['Turnout'] = NA_2008['Turnout'].str.rstrip('%').str.rstrip(' ')\nNA_2013['Turnout'] = NA_2013['Turnout'].str.rstrip('%').str.rstrip(' ')\nNA_2008['Turnout'] = pd.to_numeric(NA_2008['Turnout'], errors='coerce')\nNA_2013['Turnout'] = pd.to_numeric(NA_2013['Turnout'], errors='coerce')\n\"\"\"\nRenaming Unnamed column to district\n\"\"\"\nNA_2008.rename(columns={'Unnamed: 0':'District'}, inplace=True)\nNA_2013.rename(columns={'Unnamed: 0':'District'}, inplace=True)\n\"\"\"\nDroping extra column \"Unnamed\" with no data\n\"\"\"\nNA_2013 = NA_2013.drop('Unnamed: 11', axis=1)\n\"\"\"\n### Rechecking data\n\"\"\"\nprint(\"NA_ 2002.csv\")\nNA_2002.info()\nprint(\"NA_2008.csv\")\nNA_2008.info()\nprint(\"NA_2013.csv\")\nNA_2013.info()\nprint('First 5 Rows of NA_2002')\nNA_2002.head()\n\"\"\"\nColumn names are different in NA_2002.\n\nWe will change them to make all columns nemes similar.\n\"\"\"\nNA_2002.rename(columns={'Constituency_title':'ConstituencyTitle', 'Candidate_Name':'CandidateName', 'Total_Valid_Votes':'TotalValidVotes', 'Total_Rejected_Votes':'TotalRejectedVotes', 'Total_Votes':'TotalVotes', 'Total_Registered_Voters':'TotalRegisteredVoters', }, inplace=True)\nNA_2002.columns\nprint('First 5 Rows of NA_2008')\nNA_2008.head()\nprint('First 5 Rows of NA_2013')\nNA_2013.head()\n\"\"\"\nLooking of Nan values in Data\n\n\"\"\"\nprint(\"NA_2002\", NA_2002.isnull().any(), \"\\nNA_2008: \", NA_2008.isnull().any(), \"\\nNA_2013:\", NA_2013.isnull().any())\n\"\"\"\n### Concat all 3 datasets into 1:\n\"\"\"\ndf = pd.concat([NA_2002, NA_2008, NA_2013])\ndf.shape\ndf.head()\ndf.isnull().any()\n# get all the unique values in the 'District' column\n#df['District'] = df['District'].astype(str)\ndist = df['District'].unique()\n#dist.sort()\ndist\n# convert to lower case\ndf['District'] = df['District'].str.lower()\n# remove trailing white spaces\ndf['District'] = df['District'].str.strip()\ndist = df['District'].unique()\n#dist.sort()\ndist\nimport fuzzywuzzy\nfrom fuzzywuzzy import process\nimport chardet\n# get the top 10 closest matches to \"charsadda\"\nmatches = fuzzywuzzy.process.extract(\"charsadda\", dist, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)\n\n# take a look at them\nmatches\n# function to replace rows in the provided column of the provided dataframe\n# that match the provided string above the provided ratio with the provided string\ndef replace_matches_in_column(df, column, string_to_match, min_ratio = 90):\n    # get a list of unique strings\n    strings = df[column].unique()\n    \n    # get the top 10 closest matches to our input string\n    matches = fuzzywuzzy.process.extract(string_to_match, strings, \n                                         limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)\n\n    # only get matches with a ratio > 90\n    close_matches = [matches[0] for matches in matches if matches[1] >= min_ratio]\n\n    # get the rows of all the close matches in our dataframe\n    rows_with_matches = df[column].isin(close_matches)\n\n    # replace all rows with close matches with the input matches \n    df.loc[rows_with_matches, column] = string_to_match\n# use the function we just wrote to replace close matches to \"charsadda\" \nreplace_matches_in_column(df=df, column='District', string_to_match=\"charsadda\")\ndist = df['District'].unique()\n#dist.sort()\ndist\nreplace_matches_in_column(df=df, column='District', string_to_match=\"nowshera\")\nreplace_matches_in_column(df=df, column='District', string_to_match=\"rawalpindi\")\nreplace_matches_in_column(df=df, column='District', string_to_match=\"sheikhupura\")\nreplace_matches_in_column(df=df, column='District', string_to_match=\"shikarpur\")\nreplace_matches_in_column(df=df, column='District', string_to_match=\"nankana sahib\")\ndel dist\n\npty = df['Party'].unique()\npty.sort()\npty\ndf['Party'] = df['Party'].replace(['MUTTHIDA\\xa0MAJLIS-E-AMAL\\xa0PAKISTAN'], 'Muttahidda Majlis-e-Amal Pakistan')\ndf['Party'] = df['Party'].replace(['Pakistan Muslim League'], 'Pakistan Muslim League (QA)')\n#converting text to lower case & removing white spaces\ndf['Party'] = df['Party'].str.lower()\ndf['Party'] = df['Party'].str.strip()\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Balochistan National Movement\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Independent\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Istiqlal Party\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Jamote Qaumi Movement\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Labour Party Pakistan\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Mohib-e-Wattan Nowjawan Inqilabion Ki Anjuman (MNAKA)\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Muttahida Qaumi Movement\") # Muttahida Qaumi Movement Pakistan\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Muttahidda Majlis-e-Amal\") # Muttahidda Majlis-e-Amal Pakistan\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"National Peoples Party\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Nizam-e-Mustafa Party\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pak Muslim Alliance\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Awami Party\")\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Democratic Party\")\n# After analyzing each of the below strings.\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Muslim League (QA)\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Muslim League (N)\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Muslim League (J)\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Muslim League (F)\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Peoples Party Parliamentarians\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Peoples Party(Shaheed Bhutto)\", min_ratio =95)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Peoples Party(Sherpao)\", min_ratio =97)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Pakistan Tehreek-e-Insaf\", min_ratio =95)\nreplace_matches_in_column(df=df, column='Party', string_to_match=\"Saraiki Sooba Movement Pakistan\", min_ratio =95)\ndf['Party'] = df['Party'].str.lower()\n# few fixes taken from https:\/\/www.kaggle.com\/usman786\/exploratory-data-analysis-for-interesting-insights\/notebook\ndf['Party'].replace(['muttahida qaumi movement pakistan'], 'muttahida qaumi movement', inplace = True)\ndf['Party'].replace(['indeindependentdente','independent (retired)','indepndent'], 'independent',inplace = True)\ndf['Party'].replace(['indeindependentdente','independent (retired)','indepndent'], 'independent',inplace = True)\ndf['Party'].replace(['muttahidda majlis-e-amal pakistan','mutthida\\xa0majlis-e-amal\\xa0pakistan'\n                     ,'mutthida\u00ef\u00bf\u00bdmajlis-e-amal\u00ef\u00bf\u00bdpakistan'] \n                     ,'muttahidda majlis-e-amal' ,inplace = True)\ndf['Party'].replace(['nazim-e-mistafa'], 'nizam-e-mustafa party' ,inplace = True)\ndf['Party'].replace(['pakistan muslim league (qa)'], 'pakistan muslim league (q)' ,inplace = True)\ndf['Party'].replace(['pakistan muslim league council'], 'pakistan muslim league (c)' ,inplace = True)\ndf['Party'].replace(['pakistan muslim league \\x93h\\x94 haqiqi'], 'pakistan muslim league haqiqi' ,inplace = True)\ndf['Party'].replace(['pakistan muslim league(z)'], 'pakistan muslim league (z)' ,inplace = True)\ndf['Party'].replace(['pakistan peoples party(shaheed bhutto)'], 'pakistan peoples party (shaheed bhutto)' ,inplace = True)\ndf['Party'].replace(['pakistan peoples party parliamentarians'], 'pakistan peoples party parliamentarians' ,inplace = True)\ndf['Party'].replace(['pakistan sariaki party'], 'Pakistan Siraiki Party (T)' ,inplace = True)\ndf['Party'].replace(['pasban'], 'pasban pakistan' ,inplace = True)\ndf['Party'].replace(['qaumi watan party (sherpao)'], 'qaumi watan party' ,inplace = True)\ndf['Party'].replace(['tehreek-e-suba hazara'], 'tehreek-e-suba hazara pakistan' ,inplace = True)\n#...\ndf['Party'].replace(['pashtoonkhwa milli awami party'], 'pakhtoonkhwa milli Awami party' ,inplace = True)\ndf['Party'].replace(['pakistan amn party'], 'pakistan aman party' ,inplace = True)\ndf['Party'].replace(['pakistan awami inqelabi'], 'Pakistan Awami Inqelabi League' ,inplace = True)\ndf['Party'].replace(['pakistan freedom party'], 'pakistan freedom movement' ,inplace = True)\ndf['Party'].replace(['pakistan insani haqook party (pakistan human rights party)'], 'pakistan human rights party' ,inplace = True)\ndf['Party'].replace(['awami justice party'], 'awami justice party pakistan' ,inplace = True)\ndf['Party'].replace(['indeindependentdent'], 'independent' ,inplace = True)\ndf['Party'].replace(['jamiat ulama-e-pakistan  (noorani)'], 'jamiat ulama-e-pakistan (noorani)' ,inplace = True)\ndf['Party'].replace(['jumiat ulma-e-islam(nazryati)'], 'jamiat ulma-e-islam nazryati pakistan' ,inplace = True)\ndf['Party'].replace(['majlis-e-wahdat-e-muslimeen pakistan'], 'Majlis Wahdat-e-Muslimeen Pakistan' ,inplace = True)\ndf['Party'].replace(['markazi jamat-al-hadais'], 'Markazi Jamiat Ahl-e-Hadith' ,inplace = True)\ndf['Party'].replace(['mohib-e-wattan nowjawan inqilabion ki anjuman (mnaka)'], 'Muhib-e-Watan Noujawan Anqlabion Ki Anjuman (MNAKA)' ,inplace = True)\n\npty = df['Party'].unique()\npty.sort()\npty\n#convert textual content to lower case & remove trailing white spaces\ndf['CandidateName'] = df['CandidateName'].str.lower()\ndf['CandidateName'] = df['CandidateName'].str.strip()\n# remove mr at the beginning of names.\ndf['CandidateName'] = df.loc[:, 'CandidateName'].replace(regex=True, to_replace=\"mr \", value=\"\")\ndf['CandidateName'] = df.loc[:, 'CandidateName'].replace(regex=True, to_replace=\"mrs \", value=\"\")\ndf['CandidateName'] = df.loc[:, 'CandidateName'].replace(regex=True, to_replace=\"miss \", value=\"\")\n#df['CandidateName'] = df.loc[:, 'CandidateName'].replace(regex=True, to_replace=\"mis \", value=\"\")\ndf['CandidateName'].head(10)\ncn = df['CandidateName'].unique()\ncn.sort()\nprint(\"cn size: \", cn.shape, \"\\nValues: \", cn) \n# Lets observe few to set the threshold for fuzzywuzzy\nfuzzywuzzy.process.extract(\"zumurad khan\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >90\nfuzzywuzzy.process.extract(\"zobaida jalal\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >79\n#fuzzywuzzy.process.extract(\"barkat ali\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >90\n#fuzzywuzzy.process.extract(\"sher muhammad baloch\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >90\n#fuzzywuzzy.process.extract(\"gulab baloch\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >90\n#fuzzywuzzy.process.extract(\"babu gulab\", cn, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # acceptance value >90\nreplace_matches_in_column(df=df, column='CandidateName', string_to_match=\"zumurad khan\", min_ratio=92)\nreplace_matches_in_column(df=df, column='CandidateName', string_to_match=\"zobaida jalal\", min_ratio=80)\nreplace_matches_in_column(df=df, column='CandidateName', string_to_match=\"barkat ali\", min_ratio=90)\nreplace_matches_in_column(df=df, column='CandidateName', string_to_match=\"muhammad yasin baloch\", min_ratio=90)\n\nfor candi in df['CandidateName'].unique(): # 7000\n    replace_matches_in_column(df=df, column='CandidateName', string_to_match=candi, min_ratio=90)\n\n# let us know the loop is completed\nprint(\"All done!\")\n\"\"\"\nSaving this concatinated file as 'NA2002-18.csv' \n\"\"\"\ndf.to_csv('NA_2002-18.csv', index=None) \n\"\"\"\n# Next Steps in progress..\n\"\"\"\n\"\"\"\n ### Please Upvote this notebook and comment about my work.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '1bedfc9ccb4575'}"}
{"id":"124432","text":"\"\"\"\n\n![Imagen2](https:\/\/i.imgur.com\/2NwRKmD.png)\n\n<center> <h1> CURSO: INTRODUCCI\u00d3N AL LENGUAJE PYTHON <\/h1><\/center>\n<br>\n<center><h1> CAP\u00cdTULO 2: ESTRUCTURAS Y MANIPULACI\u00d3N DE DATOS<\/h1><\/center>\n\n---\n### TABLA DE CONTENIDO\n\n\n### 1. [Estructuras de datos](#ESTRUCTURAS-DE-DATOS)\n\n* Tuplas\n* Listas\n* Diccionarios\n\n### 2. [Lectura de datos](#LECTURA-DE-DATOS)\n\n* Formato **TXT**\n* Formato **CSV**\n* Formato **EXCEL**\n   \n### 3.  [Resumen de datos](#RESUMEN-DE-DATOS)\n\n### 4.  [Trabajo 02](#Trabajo-02)\n\n\n\"\"\"\n\"\"\"\n# **ESTRUCTURAS DE DATOS**\n---\n##  1. **TUPLAS:** \nConjunto ordenado de valores de cualquier objeto: un n\u00famero, una cadena, una funci\u00f3n, una clase, una instancia, etc.\n\n## **Definici\u00f3n:**\n\n        NombreTupla = (valores)\n\"\"\"\n\"\"\"\n**Ejemplo:** Creaci\u00f3n de las variables\n\"\"\"\nNombre='Cesar Guevara'\nEdad=33\ntalla=1.73\nCasado=False\nEdad\n\"\"\"\nGenerando una **tupla** usando las variables creadas\n\"\"\"\ntupla1=(Nombre,Edad,talla,Casado)\ntupla1\n\"\"\"\nUsando el comando **type** podemos saber el tipo de estructura del objeto **tupla1**\n\"\"\"\ntype(tupla1)\n\"\"\"\nUsando el comando **len** podemos saber la cantidad de registros de la tupla\n\"\"\"\nn=len(tupla1)\nn\n\"\"\"\n##  2. **Listas:** \nConjunto ordenado de valores de cualquier objeto: un n\u00famero, una cadena, una funci\u00f3n, una clase, una instancia, etc.\n\n## **Definici\u00f3n:**\n\n        NombreListado = [valores]\n\"\"\"\n\"\"\"\n### **Ejemplo:** Generando el listado\n\"\"\"\nlista1=[Nombre,Edad,talla,Casado]\nlista1\n\"\"\"\nUsando el comando **type** podemos saber el tipo de estructura del objeto **lista1**\n\"\"\"\ntype(lista1)\n\"\"\"\nUsando el comando **len** podemos saber la cantidad de registros del listado\n\"\"\"\nn=len(lista1)\nn\n\"\"\"\n## **\u00bfCu\u00e1l es la diferencia entre una tupla y un listado?**\n\"\"\"\n\"\"\"\n##  **Tama\u00f1o:** \nLas tupla ocupan un menor espaci\u00f3.\n\"\"\"\ntupla1\n\"\"\"\nUsando el comando **getsizeof** del paquete **sys** podemos saber el tama\u00f1o del objeto\n\"\"\"\nimport sys\nsys.getsizeof(tupla1)\nlista1\nsys.getsizeof(lista1)\n\"\"\"\n## **Inmutables:**\n\nLas tuplas no permiten modificaciones en cambio las lista si permiten cambios.\n\"\"\"\ntupla1\ntupla1[0]='C\u00e9sar Guevara Quispe'\nlista1\nlista1[0]='C\u00e9sar Guevara Quispe'\nlista1\n\"\"\"\n## **\u00bfQu\u00e9 operaciones me permite realizar un listado?**\n\"\"\"\n\"\"\"\nAgregar valores al final del listado\n\"\"\"\nlista1.append('Lima')\nlista1\n\"\"\"\nInsertardo valores en cualquier posici\u00f3n de la lista\n\"\"\"\nlista1.insert(2,\"Cesar.guevaraq@gmail.com\")\nlista1\n\"\"\"\nEliminando valores de la lista seg\u00fan su posici\u00f3n\n\"\"\"\ndel lista1[3]\nlista1\n\"\"\"\n## **\u00bfSe puede convertir un listado a una tupla?**\n\"\"\"\n\"\"\"\nUsando el comando **tuple** podemos convertir un listado a una tupla. \n\"\"\"\ntupla2=tuple(lista1)\ntupla2\ntype(tupla2)\n\"\"\"\nDe igual manera usando el comando **list** podemos convertir una tupla a una lista.\n\"\"\"\nlista2=list(tupla1)\nlista2\ntype(lista2)\n\"\"\"\n##  3. **Diccionarios:** \nLa estructura permite utilizar una clave(Nombre) para acceder a los valores.\n\n## **Definici\u00f3n:**\n\n        NombreDiccionario = {\"Nombre\":valores}\n\"\"\"\n\"\"\"\n**Nota:** En python no se declara el tipo de variable, generalmente reconoce a que tipo pertenece seg\u00fan el valor asignado.\n\"\"\"\nDatosPersonales={\n                 \"Nombre\":['Cesar Guevara','Jose Honores'],#Caracteres\n                 \"Edad\":[33,35],#Enteros\n                 \"Talla\":[1.73,1.72],#Flotantes\n                 \"Ciudad\":['Lima','Arequipa']#Caracteres\n                 }\nDatosPersonales\nDatosPersonales['Nombre']\n\"\"\"\nUsando la libreria **pandas**\n\"\"\"\nimport pandas as pd\ntabla1 = pd.DataFrame(DatosPersonales)\ntabla1\ntabla1.columns\nregistro=pd.Series(['Diego Rojas',29,1.75,'Lima'],index=tabla1.columns)\ntabla1=tabla1.append(registro,ignore_index=True) \ntabla1\ntabla1.info()\n\"\"\"\n# **LECTURA DE DATOS**\n\"\"\"\n\"\"\"\nUsando el comando **listdir**  para revisar la carpeta de trabajo **input**\n\"\"\"\nimport os\nos.listdir(\"..\/input\")\n\"\"\"\nPara usar el comando **listdir** tenemos que cargar el paquete os. \n\"\"\"\n\"\"\"\n## **1. Lectura de una data en formato txt**\n\"\"\"\nimport pandas as pd\ndatostxt=pd.read_table('..\/input\/data.txt',encoding=\"iso-8859-1\")\ndatostxt.head(10)\ndatostxt.info()\nlen(datostxt.index)\n\"\"\"\n## **2. Lectura de una data en formato CSV**\n\"\"\"\nimport pandas as pd\ndatoscsv = pd.read_csv('..\/input\/Datos_Clientes.csv',sep=\";\",encoding=\"iso-8859-1\")\ndatoscsv.head(20)\n\"\"\"\n## **3. Lectura de una data en formato Excel**\n\"\"\"\nimport pandas as pd\nfile = pd.ExcelFile('..\/input\/PD1-2018.xlsx',sheetname='Hoja1')\nfile\ndatosexcel=file.parse()\ndatosexcel.head(20)\ndatosexcel.info()\n\"\"\"\n# **RESUMEN DE DATOS**\n---\n\n## **ESTAD\u00cdSTICA GENERAL**\n\n![Imagen4](https:\/\/i.imgur.com\/xGXsfvi.png)\n\n## **ESTAD\u00cdSTICA DESCRIPTIVA**\n----\n### **MEDIDAS DESCRIPTIVAS**\n\n### **1. MEDIDAS DE TENDENCIA CENTRAL**\n\nLas medidas de tendencia central son empleadas para resumir a los datos que ser\u00e1n sometidos a un estudio estad\u00edstico, se les llama as\u00ed porque generalmente la acumulaci\u00f3n m\u00e1s alta de datos se encuentra en los valores intermedios. \n\n>* **Media:** Es la media aritm\u00e9tica (o promedio) de los valores de una variable.  Suma de los valores entre la cantidad de datos.\n>* **Mediana:** Es un valor que divide a las observaciones en dos grupos con el mismo n\u00famero de individuos. Es conveniente usarlo cuando los datos son asim\u00e9tricos, ya que no es sensible a valores extremos.\n>* **Moda:** Es el\/los valor\/es que mas veces se repite en los datos; por tanto, es donde la distribuci\u00f3n de frecuencia alcanza su m\u00e1ximo valor.\n![Imagen7](https:\/\/i.imgur.com\/jhQ9HhI.png)\n\"\"\"\nx=datoscsv['Venta']\nx\n\"\"\"\n### Calculando el **promedio**\n\"\"\"\nimport numpy as np\nnp.mean(x)\n\"\"\"\n### Calculando la **mediana**\n\"\"\"\nimport numpy as np\nnp.median(x)\n\"\"\"\n### Calculando la **moda**\n\"\"\"\ncolores=[\"red\", \"blue\", \"blue\", \"red\", \"green\", \"red\", \"red\"]\nfrom collections import Counter\nCounter(colores)\nfrom statistics import mode\nmode(colores)\n\"\"\"\n### **2. MEDIDAS DE DISPERSI\u00d3N**\n\nLas medidas de dispersi\u00f3n, muestran la variabilidad de una distribuci\u00f3n de datos, indicando por medio de un n\u00famero. Cuanto  mayor sea ese valor, mayor ser\u00e1 la variabilidad, cuanto menor sea, m\u00e1s homog\u00e9neos ser\u00e1n. As\u00ed se sabe si todos los casos son parecidos o var\u00edan mucho entre ellos.\n\n>* **Rango:** Es la diferencia entre el mayor y el menos de los datos. Casi no se emplea debido a que depende \u00fanicamente de dos valores.\n>* **Desviaci\u00f3n est\u00e1ndar:** Es una medida de la dispersi\u00f3n de los datos alrededor de su  media.\n>* **Varianza:** Se define como el cuadrado de la desviaci\u00f3n est\u00e1ndar y se representa S2.\n>* **Coeficiente de variaci\u00f3n:** Es una medida relativa (no tiene dimensiones) que permite comparar el nivel de dispersi\u00f3n de dos muestras de variables estad\u00edsticas diferentes.\n![Imagen6](https:\/\/i.imgur.com\/QBgy3Oi.png)\n\"\"\"\nx=datoscsv['Venta']\n\"\"\"\nCalculando el valor m\u00e1ximo de la variable **X**\n\"\"\"\nmax(x)\n\"\"\"\nCalculando el valor m\u00ednimo de la variable **X**\n\"\"\"\nmin(x)\n\"\"\"\nCalculando el **Rango**  de **X**\n\"\"\"\nRango=max(x)-min(x)\nRango\n\"\"\"\n### Calculando la **desviaci\u00f3n**\n\"\"\"\nimport numpy as np\nnp.std(x)\n\"\"\"\n### Calculando el **coeficiente de variaci\u00f3n**\n\"\"\"\nimport numpy as np\nnp.std(x)\/np.mean(x)*100\n\"\"\"\n### **3. MEDIDAS DE FORMA**\n\nLas medidas de forma permiten comprobar si una distribuci\u00f3n de datos tiene caracter\u00edsticas especiales como simetr\u00eda, asimetr\u00eda, nivel de concentraci\u00f3n de datos y nivel de apuntamiento que la clasifiquen en un tipo particular de distribuci\u00f3n.\n\n> *  **Coeficiente de asimetr\u00eda(AS):** Es un indicador del grado de asimetr\u00eda que presenta una distribuci\u00f3n de datos.\n![Imagen5](https:\/\/i.imgur.com\/mijOZ8W.png)\n>\n>*  **kurtosis:** Indica que tan apuntada o achatada se encuentra una distribuci\u00f3n de datos.\n\n![Imagen5](https:\/\/i.imgur.com\/jRn4msV.png)\n\"\"\"\nx=datoscsv['Venta']\n\"\"\"\n### Calculando el **coeficiente de asimetria**\n\"\"\"\nfrom scipy.stats import skew \nskew(x)\n\"\"\"\n### Calculando la **kurtosis**\n\"\"\"\nfrom scipy.stats import kurtosis \nkurtosis(x)\n\"\"\"\nUsando el comando **describe** podemos obtener las estad\u00edsticas descriptivas del **dataframe**\n\"\"\"\ndatoscsv.describe()\n\"\"\"\n Tambien podemos obtener **estad\u00edsticas descriptivas** para una agrupaci\u00f3n de registros usando la opci\u00f3n **groupby**\n\"\"\"\nResumen1=datoscsv.groupby(['Segmento'])['Venta'].describe()\nResumen1\n\"\"\"\nPodriamos especificar la estadistica descriptiva usando la opci\u00f3n **agg**\n\"\"\"\nResumen2=datoscsv.groupby(['Segmento'])['Venta'].agg([np.mean])\nResumen2\n\"\"\"\n### Ejemplo:\n\"\"\"\nimport numpy as np\nResumen2=datoscsv.groupby(['Segmento'])['Venta'].agg([np.mean,np.median,np.std])\nResumen2\n\"\"\"\n### **Criterio:**\n    \n* Si  Media < Mediana,  Entonces los datos presenta sesgo a la izquerda.\n* Si  Media = Mediana,  Entonces los datos no presenta sesgo.\n* Si  Media > Mediana,  Entonces los datos presenta sesgo a la derecha.\n\"\"\"\n\"\"\"\nGraficando la distribuci\u00f3n de la variable **venta**\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nplt.subplots(figsize=(10,6))\nsns.kdeplot(np.log(x),color='blue', shade = True)\nSegmentos=datoscsv['Segmento'].unique()\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nplt.subplots(figsize=(10,6))\nsns.kdeplot(datoscsv['Venta'][(datoscsv['Segmento'] =='Bodega')],color=\"Blue\", shade= True)\nsns.kdeplot(datoscsv['Venta'][(datoscsv['Segmento'] =='Despensa')],color=\"Red\", shade= True)\nsns.kdeplot(datoscsv['Venta'][(datoscsv['Segmento'] =='Reposicion')],color=\"Green\", shade= True)\n\"\"\"\n### TABLAS CRUZADAS\n\"\"\"\ndatosexcel.head(10)\nimport pandas as pd\npd.crosstab(datosexcel['Categor\u00eda'],datosexcel['Condici\u00f3n'])\nimport pandas as pd\npd.crosstab(datosexcel['Categor\u00eda'],datosexcel['Condici\u00f3n'],margins=True)\n\"\"\"\n# Trabajo 02\n\n* 1. Crear un dataframe mediante la lectura de un archivo de datos: \n* 2. Analizar los datos datos usando las **estad\u00edsticas descriptivas**.\n\"\"\"\n\"\"\"\n___\n<center> \n__[Regresar a la tabla de contenidos](#TABLA-DE-CONTENIDO)__\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e4d54f4543d92a'}"}
{"id":"87752","text":"\"\"\"\n<div style=\"display: block; height: 500px; overflow:hidden; text-align:center\">\n     <img src=\"https:\/\/imgur.com\/dhGIBOt.jpg\" style=\"top: 0px;border-radius: 20px; \">\n<\/div>\n\"\"\"\n\"\"\"\n# 1. Imports\n\"\"\"\n#\nimport numpy as np\nimport pandas as pd\nimport random\n\n# image\nfrom PIL import Image\n\n# folder\nimport os\nimport glob\n\n# visu\nimport matplotlib.pyplot as plt\nplt.rc('image', cmap='gray')\n\n# sklearn\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\n#tensorflow\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.utils import to_categorical\n\"\"\"\n# 2. Loading images\n\"\"\"\n\"\"\"\nThere are four shape categories. The images are loaded in a numpy array as matrix and associated categories are loaded in an independent array.\n\"\"\"\ncategories = [\"circle\", \"square\", \"star\", \"triangle\"]\n\"\"\"\nAll images are of size 200 x 200. Because of memory limitation in Kaggle, keeping 200 x 200 is not possible. Let's divide the height and width by two.\n\"\"\"\nim_width = 100\nim_height = 100\n%%time\n\ndata = []\ntarget = []\n\nfor cat in categories:\n    filelist = glob.glob('\/kaggle\/input\/four-shapes\/shapes\/' + cat + '\/*.png')\n    target.extend([cat for _ in filelist])\n    data.extend([np.array(Image.open(fname).resize((im_width, im_height))) for fname in filelist])\n#\ndata_array = np.stack(data, axis=0)\n\"\"\"\nSo we have 14970 tensor images of width 100 and height 100, each pixel being defined by Black (0) or white (255):\n\"\"\"\ndata_array.shape\n\"\"\"\nLet's have a look at several random shape images and associated label of our dataset:\n\"\"\"\nfig = plt.figure(figsize=(20,15))\ngs = fig.add_gridspec(4, 4)\n#\nfor line in range(0, 3):\n    for row in range(0, 3):\n        num_image = random.randint(0, data_array.shape[0])\n        ax = fig.add_subplot(gs[line, row])\n        ax.axis('off');\n        ax.set_title(target[num_image])\n        ax.imshow(data_array[num_image]);\n\"\"\"\n# 3. Train test split\n<b> Let's split the dataset in a train set to train model and a test set for evaluation.<\/b> We will build the train set with 80% of the dataset and the test set with the 20% remaining. We keep the class repartition by setting the parameter `stratify` to `target` (which is the list containing the labels).\n\"\"\"\npd.DataFrame(target).value_counts()\/len(target)\nX_train, X_test, y_train, y_test = train_test_split(data_array, np.array(target), test_size=0.2, stratify=target)\npd.DataFrame(y_train).value_counts()\/len(y_train)\npd.DataFrame(y_test).value_counts()\/len(y_test)\n\"\"\"\n# 4. Preparing the data\n\"\"\"\n\"\"\"\n## Normalization\n\"\"\"\n\"\"\"\nTo ease the convergence of the algorithm, it is usefull to normalize the data. See here what are the maximum and minimum values in the data, and normalize it accordingly (the resulting image intensities should be between 0 and 1).\n\"\"\"\nprint(X_train.max())\nprint(X_train.min())\nX_test_norm = np.round((X_test\/255), 3).copy()\nX_train_norm = np.round((X_train\/255), 3).copy()\nprint(X_train_norm.max())\nprint(X_train_norm.min())\n\"\"\"\nHere again, we can check the normalised pictures randomly:\n\"\"\"\nfig = plt.figure(figsize=(20,15))\ngs = fig.add_gridspec(4, 4)\n#\nfor line in range(0, 3):\n    for row in range(0, 3):\n        num_image = random.randint(0, X_train_norm.shape[0])\n        ax = fig.add_subplot(gs[line, row])\n        ax.axis('off');\n        ax.set_title(y_train[num_image])\n        ax.imshow(X_train_norm[num_image]);\n\"\"\"\n## Target encoding\n\"\"\"\n\"\"\"\nHere we convert targets. First, from string to numerical values, each category becoming an integer, from 0 to 3 (as there are four different shape categories):\n\"\"\"\ndisplay(np.array(y_train).shape)\ndisplay(np.unique(y_train))\ndisplay(np.array(y_test).shape)\ndisplay(np.unique(y_test))\n\"\"\"\nFitting the encoder on train set:\n\"\"\"\nencoder = LabelEncoder().fit(y_train)\n\"\"\"\nApplying on both train and test set:\n\"\"\"\ny_train_cat = encoder.transform(y_train)\ny_test_cat = encoder.transform(y_test)\n\"\"\"\nAnd now, we convert the result to one-hot encoded target so that they can be used to train a classification neural network. We use `to_categorical` from tensorflow library:\n\"\"\"\ny_train_oh = to_categorical(y_train_cat)\ny_test_oh = to_categorical(y_test_cat)\npd.DataFrame(y_test_oh).head()\n\"\"\"\n## Expanding dimension for the correct model intput dim\n\"\"\"\n\"\"\"\n<b>The deep learning model needs a 4 dimensions tensor to work with. Here we have grayscale pictures with no channel. It means the matrices of our black and white pictures are of shape 3. We need to add an extra dimension so algorithm can accept it.<\/b>\n\"\"\"\nX_train_norm = X_train_norm.reshape(-1, 100, 100, 1)\nX_test_norm = X_test_norm.reshape(-1, 100, 100, 1)\nX_train_norm.shape\n\"\"\"\n# 5. Convolutionnal neural network\n\"\"\"\n\"\"\"\nNow, let's define the Convolutional Neural Network.\n\n<b>The CNN that is composed of:<\/b>\n\n* a Conv2D layer with 32 filters, a kernel size of (3, 3), the relu activation function, a padding equal to same and the correct input_shape\n* a MaxPooling2D layer with a pool size of (2, 2)\n* a Conv2D layer with 64 filters, a kernel size of (3, 3), the relu activation function, and a padding equal to same\n* a MaxPooling2D layer with a pool size of (2, 2)\n* a Conv2D layer with 128 filters, a kernel size of (3, 3), the relu activation function, and a padding equal to same\n* a MaxPooling2D layer with a pool size of (3, 3)\n* a Flatten layer\n* a dense function with 120 neurons with the relu activation function\n* a dense function with 60 neurons with the relu activation function\n* a dropout layer (with a rate of 0.5), to regularize the network\n* a dense function related to the task: multiclassification of 4 classes\n\"\"\"\ndef initialize_model():\n    model = Sequential()\n    model.add(layers.Conv2D(32, (3, 3), activation=\"relu\", input_shape=(im_height, im_width, 1), padding='same'))\n    model.add(layers.MaxPool2D(pool_size=(2, 2)))\n    model.add(layers.Conv2D(64, (3, 3), activation=\"relu\", padding='same'))\n    model.add(layers.MaxPool2D(pool_size=(2, 2)))\n    model.add(layers.Conv2D(128, (3, 3), activation=\"relu\", padding='same'))\n    model.add(layers.MaxPool2D(pool_size=(3, 3)))\n    model.add(layers.Flatten())\n    model.add(layers.Dense(120, activation='relu'))\n    model.add(layers.Dense(60, activation='relu'))\n    model.add(layers.Dropout(rate=0.2))\n    model.add(layers.Dense(4, activation='softmax'))\n\n    return model\nmodel = initialize_model()\nmodel.summary()\ndef compile_model(model):\n    model.compile(optimizer='adam',\n                  loss='categorical_crossentropy',\n                  metrics=\"accuracy\")\n    return model\n\"\"\"\nHere I set an early stopping after 5 epochs and set the parameter `restore_best_weights` to `True` so that the weights of best score on monitored metric - here `val_accuracy` (accuracy on test set) - are restored when training stops. This way the model has the best accuracy possible on unseen data.\n\"\"\"\nmodel = initialize_model()\nmodel = compile_model(model)\nes = EarlyStopping(patience=5, monitor='val_accuracy', restore_best_weights=True)\n\nhistory = model.fit(X_train_norm, y_train_oh,\n                    batch_size=16,\n                    epochs=1000,\n                    validation_split=0.3,\n                    callbacks=[es])\n\"\"\"\n# 6. Results\n\"\"\"\n\"\"\"\n<b>So we have a wonderful 100% accuracy for this shape recognition algorithm!<span style=\"font-size:50pt\">\ud83d\udd25\ud83d\ude80<\/span><\/b>\n\"\"\"\ndef plot_history(history, title='', axs=None, exp_name=\"\"):\n    if axs is not None:\n        ax1, ax2 = axs\n    else:\n        f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\n    \n    if len(exp_name) > 0 and exp_name[0] != '_':\n        exp_name = '_' + exp_name\n    ax1.plot(history.history['loss'], label='train' + exp_name)\n    ax1.plot(history.history['val_loss'], label='val' + exp_name)\n    ax1.set_ylim(-0.1, 0.1)\n    ax1.set_title('loss')\n    ax1.legend()\n\n    ax2.plot(history.history['accuracy'], label='train accuracy'  + exp_name)\n    ax2.plot(history.history['val_accuracy'], label='val accuracy'  + exp_name)\n    ax2.set_ylim(0.9, 1.1)\n    ax2.set_title('Accuracy')\n    ax2.legend()\n    return (ax1, ax2)\n\nplot_history(history, title='', axs=None, exp_name=\"\");\n\"\"\"\n<b>We can check the accuracy:<\/b>\n\"\"\"\nmodel.evaluate(X_test_norm, y_test_oh, verbose=0)\n\"\"\"\n<b>And make predictions on test set to show, for random images of the test set, that the predicted label for each images is the good one:<\/b>\n\"\"\"\npredictions = model.predict(X_test_norm)\nfig = plt.figure(figsize=(20,15))\ngs = fig.add_gridspec(4, 4)\n#\nfor line in range(0, 3):\n    for row in range(0, 3):\n        num_image = random.randint(0, X_test_norm.shape[0])\n        ax = fig.add_subplot(gs[line, row])\n        ax.axis('off');\n        ax.set_title(\"Predicted: \" + categories[list(np.round(predictions[num_image])).index(1)])\n        ax.imshow(X_test_norm[num_image]);\nfig.suptitle(\"Predicted label for the displayed shapes\", fontsize=25, x=0.42);\n\"\"\"\n<b>Thank you for reading \ud83d\ude4f\ud83c\udffb If you like please upvote. If you have any suggestion of improvment or if you notice some mistakes please feel free to comment<\/b><br><br>\n<b style=\"color:royalblue\">V. Bonnet<\/b>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a0ee1afee1ee87'}"}
{"id":"10288","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport pandas as pd\nimport numpy as np\nimport os\nfrom matplotlib import pyplot as plt\n# Get all the file names from the tree of path provided. Please note that the downloaded zipped Kaggle file is extracted under \n# the following path . i.e. 'Idexcel\\Data\\''\n\npath = r'..\/input\/'\n\nfiles = []\nfiles_others = []\n# r=root, d=directories, f = files\nfor r, d, f in os.walk(path):\n    for file in f:\n        if '.csv' in file:\n            files.append(os.path.join(r, file))\n        elif '.pdf' in file:\n            files_others.append(os.path.join(r, file))\n\n# Print all the file names from it's directory tree along with it's column name\nfor file_counter in files:\n    #print(file_counter)\n    with open(file_counter, 'r', encoding=\"utf8\") as f:\n        print(file_counter)\n        print(f.readline())\n#From the above file name, it's path and their column names, it's found that below three files are required to answer Q2 and Q3\n# covid-statistics-by-us-states-daily-updates.csv, hospital-capacity-by-state-20-population-contracted.csv and definitive-healthcare-usa-hospital-beds.csv\n\ndf_covid_stat = pd.read_csv(r'..\/input\/uncover\/UNCOVER\/covid_tracking_project\/covid-statistics-by-us-states-daily-updates.csv')\ndf_hospital_capacity = pd.read_csv('..\/input\/uncover\/UNCOVER\/harvard_global_health_institute\/hospital-capacity-by-state-20-population-contracted.csv')\n# All the states where patients are hospitalised, it is expected to get the ventilators ready to face the eventuality. \n# Hence ventilators are required where 'No of positive patients are more than 90% of hospital beds' for that particular state.\n\n# Read statistics data for the last information collected date. As, the data against each dates are running sum of the respective column values.\n\nchoose_date = df_covid_stat[\"date\"] == df_covid_stat[\"date\"].max()\ndf_covid_stat_new = df_covid_stat[choose_date]\n\n# Join the datasets which are required for answering Q2 and select the useful columns\n\ndf_ventolator_analysis = pd.merge(df_covid_stat_new, df_hospital_capacity, on='state')\ndf_ventolator_analysis_columns = df_ventolator_analysis[[\"state\", \"positive\", \"hospitalized\",\"death\",\"total_icu_beds\"]]\n\ndf_ventolator_analysis_columns.describe()\n# Above description shows, hospitalized column has less number of available data. So, Find the unique values of hospitalized column\n\ndf_ventolator_analysis_columns[\"hospitalized\"].unique()\ndf_ventolator_analysis_columns = df_ventolator_analysis_columns.fillna(0)\ndf_ventolator_analysis_columns.info()\nthreshold = 0.5\nstate_potions = df_ventolator_analysis_columns[\"hospitalized\"]\/df_ventolator_analysis_columns[\"total_icu_beds\"] > threshold\ndf_ventolator_analysis_columns = df_ventolator_analysis_columns[state_potions]\ndf_ventolator_analysis_columns[\"hospitalized_to_icu_beds_percent\"] = df_ventolator_analysis_columns[\"hospitalized\"] * 100\/df_ventolator_analysis_columns[\"total_icu_beds\"]\ndf_ventolator_analysis_columns\n# Get the visualization for above analysis\n\nlabels = df_ventolator_analysis_columns[\"state\"]\nx1 = df_ventolator_analysis_columns[\"hospitalized_to_icu_beds_percent\"]\nx = np.arange(len(labels))  # the label locations\nwidth = 0.6  # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width\/2, x1, width, label='hospitalized_to_icu_beds',  color = 'r')\n\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('hospitalized_to_icu_beds')\nax.set_xlabel('States')\nax.set_title('Hospitalized Vs ICU_beds_percent')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend(loc='best', bbox_to_anchor=(1, 0.5),\n          fancybox=True, shadow=True, ncol=5)\n\"\"\"\n#From the above calculation\/Visualization of hospitalized_to_icu_beds_percent, it's clear that ICU beds are always available to every HOSPITALIZED covid patient. But, NY has three times more hospitalized than ICU beds available. Hence NY needs more ICU bed and ventilators.\n\"\"\"\n\"\"\"\n[The population of clinician and patients need more protective equipments in below scenario.\n1) The ratio of infected patients to the number of hospital staffs are more.](http:\/\/)\n\"\"\"\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\ndf_definitive_health_care = pd.read_csv('..\/input\/uncover\/UNCOVER\/esri_covid-19\/esri_covid-19\/definitive-healthcare-usa-hospital-beds.csv')\ndf_hospital_capacity = pd.read_csv('..\/input\/uncover\/UNCOVER\/harvard_global_health_institute\/hospital-capacity-by-state-20-population-contracted.csv')\n\n#Get the unique values of num_staffe\ndf_definitive_health_care[\"num_staffe\"].unique\n# Replace the **** on num_staffe to zero.\n\ndf_definitive_health_care.loc[(df_definitive_health_care.num_staffe == '****'),'num_staffe']=0\n#df_definitive_health_care.head(10)\n# Group by total number of staff per state\ndf_definitive_health_care_columns = df_definitive_health_care[[\"hq_state\",\"num_staffe\"]]\ndf_definitive_health_care_columns.astype({'num_staffe': 'float'}).dtypes\n\ndf_definitive_health_care_columns[\"num_staffe\"] = df_definitive_health_care_columns[\"num_staffe\"].astype(str).astype(int)\nprint(df_definitive_health_care_columns.dtypes)\ndf_definitive_health_care.info()\n# Aggregate the data\n\ndf_state_vs_staff = df_definitive_health_care_columns.groupby([\"hq_state\"])[\"num_staffe\"].aggregate(sum)\ndf_state_vs_staff_group = pd.DataFrame(df_state_vs_staff).reset_index()\ndf_state_vs_staff_group.columns = ['hq_state', 'num_staffe']\n#df_state_vs_staff_group[\"num_staffe\"]\ndf_protective_analysis = pd.merge(df_state_vs_staff, df_hospital_capacity, how='inner', left_on='hq_state', right_on = 'state')\ndf_protective_analysis_columns = df_protective_analysis[[\"state\", \"adult_population\", \"num_staffe\"]]\n\ndf_protective_analysis_columns.describe()\nthreshold = 360\nstate_options = df_protective_analysis_columns[\"adult_population\"]\/df_protective_analysis_columns[\"num_staffe\"] > threshold\ndf_protective_analysis_columns = df_protective_analysis_columns[state_options]\ndf_protective_analysis_columns[\"population_to_med_staff_percent\"] = df_protective_analysis_columns[\"adult_population\"]\/df_protective_analysis_columns[\"num_staffe\"]\ndf_protective_analysis_columns.sort_values(\"population_to_med_staff_percent\" , ascending=False, inplace=False)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set(color_codes=True)\n\n# Get the visualization\n\nlabels = df_protective_analysis_columns[\"state\"]\nx1 = df_protective_analysis_columns[\"population_to_med_staff_percent\"]\nx = np.arange(len(labels))  # the label locations\nwidth = 0.6  # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width\/2, x1, width, label='Population_to_med_staff',  color = 'r')\n\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Population_to_med_staff')\nax.set_xlabel('States')\nax.set_title('Population Vs Medical Staff')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend(loc='best', bbox_to_anchor=(1, 0.5),\n          fancybox=True, shadow=True, ncol=5)\n\"\"\"\nFrom the above analysis and Visualization, it's clear that States like VT, MD, OR, WA, CO, NH, CA, UT, ID need more protective equipment. As the ratio of the population to the hospital staff availability is high. So, they have to attend more patient. They might have to work extended hours as well. Hence they need more safety protective equipment.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '12df288dd879c9'}"}
{"id":"42058","text":"\"\"\"\n\n\n![image](https:\/\/miro.medium.com\/max\/1200\/0*UEtwA2ask7vQYW06.png)\n\"\"\"\n\"\"\"\n## Introduction and Imports\nn this notebook, I will be using only Machine Learning methods to get decent prediction scores. There are much better and sophisticated ways (like RNN, GRU, Fine-tuning BERT, etc) but you have seen them on a lot of notebook already.\n\nThe main aim of this notebook is to just show how quickly and easily you can do Text Classification using Basic Machine Learning Methods, rather than spend waiting 1 hour for a model to train!\n\nIf you like this notebook, please make sure to give an upvote, it helps a lot and motivates me to make much more good-quality content\n\nIf you don't like my work, please leave a comment on what can I do to make it better!\n\"\"\"\n\"\"\"\n<p style=\"color:red\">If you like this notebook, please make sure to give an upvote, it helps a lot and motivates me to make much more good-quality content<\/p>\n<p style=\"color:blue\">If you don't like my work, please leave a comment on what can I do to make it better!<\/p>\n<hr>\n<h3 style=\"color:aqua\">Edits:<\/h3>\n<ul>\n<li style=\"color:green\">All Classifiers now classify for all 3 categories and not just 2. Good Validation Accuracy is maintained.<\/li>\n<\/ul>\n\"\"\"\n# 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 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\nfrom sklearn.preprocessing import LabelEncoder,LabelBinarizer\nimport lightgbm as lgb\nimport catboost as ct\nimport sklearn\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.model_selection import KFold,RepeatedStratifiedKFold,RandomizedSearchCV,GridSearchCV,cross_val_score\nfrom sklearn.feature_extraction.text import TfidfTransformer,CountVectorizer,ENGLISH_STOP_WORDS\nimport nltk\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import roc_auc_score, confusion_matrix, plot_confusion_matrix, plot_precision_recall_curve\ndataset=pd.read_csv('..\/input\/60k-stack-overflow-questions-with-quality-rate\/train.csv')\ndataset.head()\ndraft_dataset=dataset\ndataset.sort_values('CreationDate',inplace=True)\n\"\"\"\n# Data Preprocessing and Some EDA\n\"\"\"\nlb=LabelEncoder()\nnew_data=lb.fit_transform(dataset.CreationDate)\n#dataset['DateCatCOl']=new_data\ndataset.head()\ndataset.drop(['Id','CreationDate'],axis=1,inplace=True)\ndataset.head()\ndataset.Y.value_counts().to_dict()\ndataset['Y']=dataset.Y.map({'LQ_CLOSE': 0, 'LQ_EDIT': 1, 'HQ': 2})\ndataset\nimport re\ndef clean_tags(T):\n    T=T.lower()\n    text=re.sub(r'<','',T)\n    text=re.sub(r'>',' ',text)\n    return text\n\ndataset['Tags']=dataset['Tags'].map(clean_tags)\ndataset.head()\ndataset.Tags.value_counts()[:10]\ncount_v=CountVectorizer()\ntags_vecorized=count_v.fit_transform(dataset.Tags)\ndataset.drop('Tags',axis=1,inplace=True)\ndataset.head()\n\"\"\"\n    x=x.lower()\n    x=re.sub(r'<p>',\" \",x)\n    x=re.sub(r'[^(a-zA-Z)\\s]','', x)\n    x=x.strip(os.linesep)\n    x=re.sub(r'[\\n\\r]+', '', x)\n    x=x.strip()\n\"\"\"\nimport os\ndef clean_body(x):\n    x=x.lower()\n    x=re.sub(r'[^(a-zA-Z)\\s]','', x)\n    return x\n\ndataset['Body']=dataset.Body.map(clean_body)\ndataset.head()\n\"\"\"\nLet's join the title and the body of the text data so that we can use both of them in our classification\n\"\"\"\ndataset['CombineTextandBody']=dataset['Title']+' '+dataset['Body']\ndataset.head()\ndataset.drop(['Title','Body'],axis=1,inplace=True)\ndataset.head()\nlabel=dataset.pop('Y')\ndataset.head()\n\"\"\"\n## Splitting the Data\nLet's now split the dataset into training and validation sets\n\"\"\"\ntrain_x,test_x,train_y,test_y=train_test_split(dataset,label,test_size=0.15,random_state=42)\ntrain_x.shape,test_x.shape\ntrain_x.head()\n\"\"\"\n## Vectorizing the Data\nLet's vectorize the data so it's in the numerical format\n\"\"\"\ntfidf=TfidfVectorizer()\ntransform_text_train=tfidf.fit_transform(train_x.CombineTextandBody)\ntransform_text_test=tfidf.transform(test_x.CombineTextandBody)\ntransform_text_train.shape\n\"\"\"\n## created some folds \n\"\"\"\nrskf=RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=42)\n\"\"\"\n## Modelling\nLet's start with different non-deep learning approaches for this task.\n\"\"\"\n\"\"\"\n# 1. Logistic Regression\n\nLet's first start with our good old, Logistic Regression!\n\"\"\"\nlr_classifier = LogisticRegression(C=1.)\nlr_classifier.fit(transform_text_train, train_y)\ntransform_text_test.shape,test_y.shape\nprint(f\"Validation Accuracy of Logsitic Regression Classifier is: {(lr_classifier.score(transform_text_test, test_y))*100:.2f}%\")\nscore=cross_val_score(lr_classifier,transform_text_train, train_y,cv=3,n_jobs=-1)\n\"\"\"\ncross-validation score of logistic classifier \n\"\"\"\nscore\n\"\"\"\n# 2. XGBoost\nFinally, let's use the XGBoost Classifier and then we'll compare all the different classifiers so far\n\"\"\"\nxg_classifier = XGBClassifier(n_estimators=500,n_jobs=-1,random_state=42)\nxg_classifier.fit(transform_text_train, train_y)\n\"\"\"\nPrint the accuracy score of the XG boost classifier\n\"\"\"\nprint(f\"Validation Accuracy of XGBoost Clf. is: {(xg_classifier.score(transform_text_test, test_y))*100:.2f}%\")\n\"\"\"\n# 3. Multinomial Naive Bayes\nLet's now switch to the naive the bayes, the NAIVE BAYES!\n\"\"\"\nnb_classifier = MultinomialNB()\nnb_classifier.fit(transform_text_train, train_y)\n\"\"\"\nPrint the accuracy score of the naive bayes classifier\n\"\"\"\n\nprint(f\"Validation Accuracy of Naive Bayes Classifier is: {(nb_classifier.score(transform_text_test, test_y))*100:.2f}%\")\n\"\"\"\n# 4. Light GBM Model\n\"\"\"\nlgb_model=lgb.LGBMClassifier()\nlgb_model.fit(transform_text_train, train_y)\n\"\"\"\nPrint the accuracy score of the lgb_model classifier\n\"\"\"\n\nprint(f\"Validation Accuracy of lgb_model Classifier is: {(lgb_model.score(transform_text_test, test_y))*100:.2f}%\")\n\"\"\"\n## Hyper parameter tuning of light GBM \n\"\"\"\nfrom scipy.stats import randint as sp_randint\nfrom scipy.stats import uniform as sp_uniform\nparam_test ={'num_leaves': sp_randint(6, 50), \n             'min_child_samples': sp_randint(100, 500), \n             'min_child_weight': [1e-5, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4],\n             'subsample': sp_uniform(loc=0.2, scale=0.8), \n             'colsample_bytree': sp_uniform(loc=0.4, scale=0.6),\n             'reg_alpha': [0, 1e-1, 1, 2, 5, 7, 10, 50, 100],\n             'reg_lambda': [0, 1e-1, 1, 5, 10, 20, 50, 100],\n            'learning_rate':[0.1,0.01,0.05,0.001,0.005,0.03,0.003,0.006,0.08]}\nlgb_model.get_params()\nRS=RandomizedSearchCV(\n    estimator=lgb_model, param_distributions=param_test,\n    cv=3,\n    refit=True,\n    random_state=42,\n    verbose=True)\nRS.fit(transform_text_train, train_y)\n\"\"\"\n### best parameters and best score of LIght GBM\n\"\"\"\nRS.best_estimator_,RS.best_params_,RS.best_score_\n\"\"\"\n**Note: since we got very good result with logistic regression we make it simple beacuase light GBM takes lot of time to train and find optimum result. hence we can compromise with some accuracy and avoid some complexity we can go with logistic Regression.**\n\nTip:- From my experiance most of the time we generally go for complex model but we should always start with some basic model if they dont work then we should go for some complex models.\n\"\"\"\nparameter_list={\n    'C':[0.10,0.6,0,3.0,4.0,5.,6.,9.,0.11,0.12,0.15,0.14,0.20],\n    'solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga']\n}\n\nlr_classifier_2 = LogisticRegression(n_jobs=-1,random_state=42)\n\nlog_tune=RandomizedSearchCV(\n    estimator=lr_classifier_2, param_distributions=parameter_list,\n    cv=3,\n    refit=True,\n    random_state=42,\n    verbose=True)\n\nlog_tune.fit(transform_text_train, train_y)\n\"\"\"\n## Best Parameter and best score of logistic Regression \n\"\"\"\nlog_tune.best_estimator_,log_tune.best_params_,log_tune.best_score_","meta":"{'source': 'AI4Code', 'id': '4d80c03eda700d'}"}
{"id":"68997","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n### Load Libraries\n\"\"\"\n\n# Data manipulation libraries\nimport pandas as pd\nimport numpy as np\n\n##### Scikit Learn modules needed for Logistic Regression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder,MinMaxScaler , StandardScaler, OneHotEncoder\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\n\n# Plotting libraries\nfrom IPython.display import SVG\nfrom graphviz import Source\nfrom IPython.display import display\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes = True)\n%matplotlib inline\n\"\"\"\n### Load Training Data\n\"\"\"\ndf = pd.read_csv(\"..\/input\/train.csv\")\ndf.head()\nprint(df.describe())\n\"\"\"\n### Explore Training Data\n\"\"\"\n# Select only numerical columns for data analysis\ndf_numeric = df._get_numeric_data()\nprint(df_numeric.columns)\nexclude_dates = ['Id','YearBuilt','YearRemodAdd','MoSold', 'YrSold','SalePrice']\ndf_numeric = df_numeric.drop(exclude_dates,axis=1)\nprint(df_numeric.columns)\n# Explore data visually\n# Build Correlation Matrix to study multi collinearity\ncorrelation = df_numeric.corr()\n#print(correlation)\n\nfig , ax = plt.subplots()\nfig.set_figwidth(18)\nfig.set_figheight(18)\nsns.heatmap(correlation,annot=True,cmap=\"YlGnBu\")\n\"\"\"\n### Visual Observation\n- Several numerical variables are strongly correlated viz Garage Cars with Garage Area or Ground Levl Area with Total rooms above\n- We could either remove of of the correlated values but can also engineer a metric as ratio of two quantities\n- In my current example I have kept all the correlated values and opted for reducing dimensions of numerical variables by using PCA\n\"\"\"\n\"\"\"\n### Build Preprocessing Pipeline -\n- created separate strategy to handle numerical and categorical variables\n\n#### Preprocessing of Numerical Features - \n- Imputation using Mean (however added median as part of grid search in below code)\n- opted for standard scaling of numerical values\n- Dimentionality Reduction using PCA\n\n#### Categorical Variables\n- Imputed missing values with word _'missing'_\n- Tranformation using One hot encoding\n\"\"\"\n# We create the preprocessing pipelines for both numeric and categorical data.\n\nnumeric_features = [x for x in df_numeric.columns]\nnumeric_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='mean')),\n    ('scaler', StandardScaler()),\n    ('pca', PCA(n_components= 2))])\n\nall_numeric_columns = exclude_dates + numeric_features\ncategorical_features = [x for x in df.columns if x not in all_numeric_columns ]\n# categorical_features = [x for x in df.columns if x not in df_numeric + exclude_dates]\n#print(categorical_features)\ncategorical_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', numeric_transformer, numeric_features),\n        ('cat', categorical_transformer, categorical_features)])\n\n# Append classifier to preprocessing pipeline.\n# Now we have a full prediction pipeline.\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                      ('classifier', RandomForestRegressor())])\n\"\"\"\n### Split Data in Training & test sets (80\/20 ratio)\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(df[numeric_features + categorical_features], \n                                                    df[\"SalePrice\"], test_size=0.2,random_state =42)\nparam_grid = {\n    'preprocessor__num__imputer__strategy': ['mean', 'median'],\n    'classifier__max_features': [\"auto\",\"sqrt\", \"log2\"],\n    #'classifier__max_iter' :[100,150,200],\n    'classifier__n_estimators': [10,50,100,200],\n    'classifier__max_depth':[2,4,8]\n}\n\ngrid_search_rfr = GridSearchCV(clf, param_grid, cv=10, iid=False,verbose= 2 , n_jobs = -1)\ngrid_search_rfr.fit(X_train, y_train)\n\nprint((\"best Linear Regression from grid search: %.3f\"\n       % grid_search_rfr.score(X_test, y_test)))\nprint(\"Best Parameter Setting is {}\".format(grid_search_rfr.best_params_))\ntest_df = pd.read_csv(\"..\/input\/test.csv\")\ntest_df_columns = [x for x in test_df if x not in exclude_dates]\n\n# Load Submission File\nsample_submission = pd.read_csv(\"..\/input\/sample_submission.csv\")\ny_prediction = grid_search_rfr.predict(test_df[test_df_columns])\nsubmission = pd.DataFrame({\"Id\":sample_submission[\"Id\"].values, \"SalePrice\":y_prediction.tolist()})\nsubmission.to_csv(\"submission_randomfr_V1.csv\",index=False)\n\"\"\"\n### Thats all for the day folks !! Oh yes and I havent touched upon time based variables, kept them for next iterations to come :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7f033f69354e3e'}"}
{"id":"78143","text":"\"\"\"\n# A Traditional Data Science Approach\n\"\"\"\n\"\"\"\nAnother thing that came to my mind on seeing game replays is that I can use this for training.([First thing that came to mind is here](https:\/\/www.kaggle.com\/arunprathap\/interpreting-replay-json)) I am setting aside RL agent level training which is already covered in other notebooks and thinking intuitively which of the fields in given data actually matters and how I can approach the game from a data science perspective.\n\"\"\"\n\"\"\"\n## Get the JSON\n\"\"\"\n\"\"\"\nThough I have used a sample JSON for this notebook, the following link can help you get more JSON.\n\n[Notebook](https:\/\/www.kaggle.com\/robga\/google-football-episode-scraper) of [@robga](https:\/\/www.kaggle.com\/robga) and the [dataset](https:\/\/www.kaggle.com\/robga\/gfootball001) used in his notebook.\n\"\"\"\n\"\"\"\n## Import basic Libaries & Modules\n\"\"\"\n# 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 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\n\"\"\"\n## Enter URL of the game of interest\n\"\"\"\nurl = 'https:\/\/www.kaggleusercontent.com\/episodes\/3634538.json'\n\"\"\"\n## Load JSON from URL\n\"\"\"\nimport urllib, json\n\nresponse = urllib.request.urlopen(url)\ndata = json.loads(response.read())\n\"\"\"\n### Format Step Data\n\"\"\"\n\"\"\"\nThis consists of same data (for 3002 steps) mirrored appropriately for the left and right players, and giving action, active player and sticky action fields which differ between left and right players.\n\"\"\"\n\"\"\"\nRefer [link](https:\/\/github.com\/google-research\/football\/blob\/master\/gfootball\/doc\/observation.md) for details on how to interpret these values. The fields that you may need to use may depend on your specific implementation. I am just giving an outline assuming you are using all fields. Note that you get double data with each game since left and right player data can be used for training. If you game plan depends on steps, consider adding step information also to your data.\n\"\"\"\n\"\"\"\nThe metric to be used should be something that gives insight in to how effective was this action and I am yet to think about it.\n\"\"\"\n\"\"\"\nFirst index is for step(0 to 3001) and second for player(0 or 1)\n\"\"\"\n\"\"\"\nLets see a sample for step 1000.\n\"\"\"\ndata['steps'][1000][0]\ndata['steps'][1000][1]\n\"\"\"\nThe action corresponds to our output for training along with appropriate metric that determines how effective this action was.\n\"\"\"\n\"\"\"\nLets see which are the input features we need. The player that we are controlling is the most important thing. So 'left team roles' and 'left team tired factor' corresponding to 'active' player ('designated' is redundant since we are controlling only one player) is important. 'left team active' and 'left team yellow cards' corresponding to 'active' player also matter if you are planning to work out some offensive strategies. 'sticky actions' matter since that is part of the ongoing strategy of the team.\n\"\"\"\n\"\"\"\nThe ball is the big thing in the game and definitely 'ball' position, 'ball rotation' and 'ball direction' matters. Since our active player is always the one nearest to the ball, it may be beneficial to have a feature for distance between active player and ball as well. You will have to fit all this within the three laws of motion framework to get things moving in the game.\n\"\"\"\n\"\"\"\nNothing matters if the ball is unclaimed or in possession of the opposite team throughout the game. You need possession of ball for atleast as many steps as the number of goals you want (assuming you are the master player who gets a goal every time your feet touches the ball). So 'ball owned team', 'ball owned player' matters as well.\n\"\"\"\n\"\"\"\nTo know where your enemy is gives you the tactical advantage. You dont want to have a shot at goal post when you have enemy players on the strike side who can take possession of the ball. A high pass may save you the game. So there comes the right team positions, direction, tired factor, etc.\n\"\"\"\n\"\"\"\nHow good are you without having friends around. It's always effective to have 11 sets of feet in the ground than one to cover more ground. You can always pass the ball around the field waiting for opportunities or just fiddle around the field if you know where your friends are located. So the left player position, direction, tired factor, etc also plays a role in determining my action.\n\"\"\"\n\"\"\"\nThe 'game mode' is the next big thing as you don't want to worry about where your enemy is or you team mates are in atleast some of the modes.\n\"\"\"\n\"\"\"\nHope you liked my approach of intuitively going though the observation fields.\n\"\"\"\n\"\"\"\n### EOF\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8f94fb84ac1c15'}"}
{"id":"48993","text":"\"\"\"\n### This notebook is applying fast.ai Tabular data lesson concepts on titanic training data competition\n\"\"\"\nimport fastbook\nfastbook.setup_book()\nfrom fastbook import *\nfrom pandas.api.types import is_string_dtype, is_numeric_dtype, is_categorical_dtype\nfrom fastai.tabular.all import *\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom dtreeviz.trees import *\nfrom IPython.display import Image, display_svg, SVG\nfrom sklearn.model_selection import train_test_split\ntitanic_train_input_data=pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\nprocs = [Categorify, FillMissing]\ninput_columns=['PassengerId','Pclass', 'Name', 'Sex', 'Age', 'SibSp',\n       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']\nX_train, X_cv, y_train, y_cv = train_test_split(titanic_train_input_data[input_columns], titanic_train_input_data[\"Survived\"], test_size=0.2, random_state=0)\ntitanic_train_input_data=titanic_train_input_data.append(titanic_train_input_data.tail(1))\nlast_added_row=titanic_train_input_data.tail(1)\ntitanic_train_input_data.loc[last_added_row.index.values,'Fare']=float(\"NaN\")\ntitanic_train_input_data.tail(1)\nsplits = (list(X_train.index.values),list(X_cv.index.values))\n#Declare dependent variable and automatically deduce the continuous vs categorical variables\ndep_var=['Survived']\ncont,cat = cont_cat_split(titanic_train_input_data, 1, dep_var=dep_var)\ncont,cat\n#Tabular Pandas\nto = TabularPandas(titanic_train_input_data, procs, cat, cont, y_names=dep_var, splits=splits)\n#Display train and validation lengths\nlen(to.train),len(to.valid)\n\nto.show(3)\nto.items.head(3)\ntitanic_train_input_data.columns\n#Build simple decision tree classifier\nxs,y = to.train.xs,to.train.y\nvalid_xs,valid_y = to.valid.xs,to.valid.y\nfrom sklearn.tree import DecisionTreeClassifier\ndecision_model=DecisionTreeClassifier(max_leaf_nodes=4)\ndecision_model.fit(xs,y)\n#Lets see the tree that was built\ndraw_tree(decision_model, xs, size=10, leaves_parallel=True, precision=2)\n#Dtree visualization\nsamp_idx = np.random.permutation(len(y))[:500]\ndtreeviz(decision_model, xs.iloc[samp_idx], y.iloc[samp_idx], xs.columns, dep_var,\n        fontname='DejaVu Sans', scale=1.6, label_fontsize=10,\n        orientation='LR')\nfrom sklearn.metrics import confusion_matrix \nfrom sklearn.metrics import accuracy_score\ndef calc_accuracy(pred,y):\n    tn,fp,fn,tp=confusion_matrix(y,pred).ravel()\n    print(tn,fp,fn,tp)\n    return round(accuracy_score(y,pred), 6)\ndef model_accuracy(m, x, y): return calc_accuracy(m.predict(x), y)\nmodel_accuracy(decision_model, valid_xs, valid_y)\ndecision_model.get_n_leaves(), len(xs)\nxs\n#Decision modelwith no max leaf nodes\ndecision_model_nomax=DecisionTreeClassifier()\ndecision_model_nomax.fit(xs,y)\nacc=model_accuracy(decision_model_nomax, valid_xs, valid_y)\nprint(acc)\ndecision_model_nomax.get_n_leaves(), len(xs)\ndecision_model_minsamplesleaf=DecisionTreeClassifier(min_samples_leaf=15)\ndecision_model_minsamplesleaf.fit(xs,y)\nacc=model_accuracy(decision_model_minsamplesleaf, valid_xs, valid_y)\nprint(acc)\ndecision_model_nomax.get_n_leaves(), len(xs)\ntitanic_test_data=pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\nto_tst = to.new(titanic_test_data)\nto_tst.process()\nto_tst.items.head(3)\nprint(\"Writing submission file:\")\ny_test=decision_model_minsamplesleaf.predict(to_tst.items)\ntitanic_test_data[\"Survived\"]=y_test\ntitanic_test_data[[\"PassengerId\",\"Survived\"]].to_csv(\"titanic_decision_tree.csv\",index=False)\n# 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\n\nimport numpy as np \nimport pandas as pd \nfrom sklearn.ensemble import RandomForestClassifier \nfrom sklearn.datasets import make_classification \nfrom sklearn.metrics import confusion_matrix \nfrom sklearn.model_selection import train_test_split \nfrom sklearn.metrics import accuracy_score\nimport scipy.stats\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nimport math\nfrom scipy.stats import pearsonr\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimp = SimpleImputer(missing_values=np.nan, strategy='most_frequent')\nfrom sklearn.preprocessing import LabelEncoder\nlabel_encoder_sex = LabelEncoder()\n\ndef map_risk_categorical(data,cv_data,test_data,columns,target_column):\n    for column in columns:\n        print(column+\" unique values:\")\n        print(data[column].unique())\n        mean_encodings=data.groupby(column)[target_column].mean()\n        print(mean_encodings)\n        mean_encodings['']=data[column].mode()\n        data[column]=data[column].map(mean_encodings)\n        data[column]=round(data[column].astype(float),2)\n        cv_data[column]=cv_data[column].map(mean_encodings)\n        cv_data[column]=round(cv_data[column].astype(float),2)\n        test_data[column]=test_data[column].map(mean_encodings)\n        test_data[column]=round(test_data[column].astype(float),2)\n        imp.fit(data[[column]])\n        cv_data[[column]]=imp.transform(cv_data[[column]])\n        test_data[[column]]=imp.transform(test_data[[column]])\n    return (data.copy(),cv_data.copy(),test_data.copy())\n\ndef print_correlation(data,columns,class_column):\n    dist={}\n    for column in columns:\n        print(\"Correlation of \"+column+\" with \"+class_column)\n        print(pearsonr(data[column],data[class_column]))\n        \ndef print_summary(data,columns,filter_query):\n    normal_stats={}\n    for column in columns:\n        normal_stats[column]={}\n        if filter_query != \"\":\n            total_count=data.query(filter_query)[column].count()\n            print(\"Total count\"+str(total_count))\n            print(data.query(filter_query)[[column]].describe())\n            normal_stats[column]=(data.query(filter_query)[column].mean(),data.query(filter_query)[column].std())\n        else:\n            print(data[column].describe())\n    return normal_stats.copy()\n\ndef map_data(data): \n    gender_mapping={\"male\":1,\"female\":0} \n    embarked_mapping={\"S\":1,\"C\":2,\"Q\":3} \n    cabin_mapping={\"A\":1,\"B\":2,\"C\":3,\"D\":4,\"E\":5,\"F\":6,\"G\":7} \n    #data[\"Sex\"]=data[\"Sex\"].map(gender_mapping,na_action='ignore')\n    #data[\"Sex\"]=label_encoder_sex.fit_transform(data[\"Sex\"])\n    data[\"Embarked\"]=data[\"Embarked\"].map(embarked_mapping,na_action='ignore') \n    data[\"Cabin\"]=data[\"Cabin\"].map(lambda x:x[0],na_action='ignore') \n    data[\"Cabin\"]=data[\"Cabin\"].map(cabin_mapping,na_action='ignore')\n    data[[\"Pclass\",\"Sex\",\"Fare\",\"Embarked\",\"Age\"]]=imp.fit_transform(data[[\"Pclass\",\"Sex\",\"Fare\",\"Embarked\",\"Age\"]])\n    data[\"Cabin\"]=data[\"Cabin\"].fillna(0)\n    return data.copy()\n\ndef map_risk_numeric(data,columns,risk_map,complement_flag):\n    for column in columns:\n        norm_stats_mean,norm_stats_stdev=risk_map[column]\n        print(\"mean:\"+str(norm_stats_mean)+\" std:\"+str(norm_stats_stdev)+\" for \"+column)\n        norm_stats=scipy.stats.norm(norm_stats_mean,norm_stats_stdev)\n        data[column]=norm_stats.cdf(data[column])\n        data[column]=round(data[column],2)\n        #if complement_flag==1:\n        #    data[new_column]=round(1-data[new_column],2)\n    return data.copy()\n\ntitanic_train_input_data=pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntitanic_test_data=pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n#train_columns=[\"Pclass\",\"Age\",\"Sex\",\"Fare\",\"Embarked\",\"Cabin\",\"SibSp\",\"Parch\"]\ntrain_columns=[\"Sex\",\"Pclass\",\"Pclass_Sex\",\"Cabin\",\"Age\",\"Pclass_Age\",\"Sex_Fare\",\"Family_Size\"]\ncategorical_columns=[\"Pclass\",\"Sex\",\"Cabin\",\"Pclass_Sex\",\"Age\",\"Pclass_Age\",\"Family_Size\",\"SibSp\",\"Parch\",\"Fare_Per_Person\",\"Sex_Fare\"]\nnumeric_columns=[]\ninput_columns=categorical_columns+numeric_columns\n\n\ntitanic_train_input_data=map_data(titanic_train_input_data.copy())\ntitanic_test_data=map_data(titanic_test_data.copy())\n\ntitanic_train_input_data['Family_Size']=titanic_train_input_data['SibSp']+titanic_train_input_data['Parch']+1\ntitanic_train_input_data['Fare_Per_Person']=titanic_train_input_data['Fare']\/(titanic_train_input_data['Family_Size'])\ntitanic_train_input_data['Fare_Per_Person']=round(titanic_train_input_data['Fare_Per_Person'],2)\ntitanic_train_input_data['Pclass_Sex']=titanic_train_input_data['Pclass'].map(str)+titanic_train_input_data['Sex'].map(str)\ntitanic_train_input_data['Age']=round(titanic_train_input_data['Age']\/5)\ntitanic_train_input_data['Fare_Per_Person']=round(titanic_train_input_data['Fare_Per_Person']\/20)\ntitanic_train_input_data['Pclass_Age']=titanic_train_input_data['Pclass'].map(str)+titanic_train_input_data['Age'].map(str)\ntitanic_train_input_data['Sex_Fare']=titanic_train_input_data['Sex'].map(str)+titanic_train_input_data['Fare_Per_Person'].map(str)\ntitanic_train_input_data['Sex_Age']=titanic_train_input_data['Sex'].map(str)+titanic_train_input_data['Age'].map(str)\ntitanic_train_input_data['Age_Cabin']=titanic_train_input_data['Age'].map(str)+titanic_train_input_data['Cabin'].map(str)\n\nX_train, X_cv, y_train, y_cv = train_test_split(titanic_train_input_data[input_columns], titanic_train_input_data[\"Survived\"], test_size=0.2, random_state=0)\n\ntitanic_train_data=titanic_train_input_data.iloc[X_train.index.values].copy()\n\ntitanic_test_data['Family_Size']=titanic_test_data['SibSp']+titanic_test_data['Parch']\ntitanic_test_data['Fare_Per_Person']=titanic_test_data['Fare']\/(titanic_test_data['Family_Size']+1)\ntitanic_test_data['Fare_Per_Person']=round(titanic_test_data['Fare_Per_Person']\/20)\ntitanic_test_data['Pclass_Sex']=titanic_test_data['Pclass'].map(str)+titanic_test_data['Sex'].map(str)\ntitanic_test_data['Age']=round(titanic_test_data['Age']\/5)\ntitanic_test_data['Pclass_Age']=titanic_test_data['Pclass'].map(str)+titanic_test_data['Age'].map(str)\ntitanic_test_data['Sex_Fare']=titanic_test_data['Sex'].map(str)+titanic_test_data['Fare_Per_Person'].map(str)\ntitanic_test_data['Sex_Age']=titanic_test_data['Sex'].map(str)+titanic_test_data['Age'].map(str)\ntitanic_test_data['Age_Cabin']=titanic_test_data['Age'].map(str)+titanic_test_data['Cabin'].map(str)\n\n#Over sampling\n#count_survived_0, count_survived_1 = titanic_train_data.Survived.value_counts()\n\n#titanic_survived_0 = titanic_train_data[titanic_train_data[\"Survived\"] == 0]\n#titanic_survived_1 = titanic_train_data[titanic_train_data[\"Survived\"] == 1]\n#titanic_train_data_survived_1_over = titanic_survived_1.sample(count_survived_0, replace=True)\n#titanic_train_data_over = pd.concat([titanic_survived_0, titanic_train_data_survived_1_over], axis=0)\n\n\nprint(\"Survived class numeric vals:\")\n#print_unique_vals(titanic_train_data,numeric_columns,\"Survived==1\")\nsurvived_normal_stats=print_summary(titanic_train_data,numeric_columns,\"Survived==1\")\nprint(\"-------------------------\") \nprint(\"Not Survived class numeric vals:\")\n#print_unique_vals(titanic_train_data,numeric_columns,\"Survived==0\")\nnot_survived_normal_stats=print_summary(titanic_train_data,numeric_columns,\"Survived==0\")\nprint(\"--------------------------\")\nprint(\"Correlation:\")\n#print_correlation(titanic_train_data,categorical_columns,\"Survived\")\n#print_correlation(titanic_train_data,numeric_columns,\"Survived\")\n\ntitanic_train_data,X_cv,titanic_test_data=map_risk_categorical(titanic_train_data,X_cv,titanic_test_data,categorical_columns,\"Survived\")\n#titanic_train_data=map_risk_numeric(titanic_train_data,numeric_columns,survived_normal_stats,0)\n#X_cv=map_risk_numeric(X_cv,numeric_columns,survived_normal_stats,0)\n#titanic_test_data=map_risk_numeric(titanic_test_data,numeric_columns,survived_normal_stats,0)\n#sc = StandardScaler()\n#titanic_train_data[numeric_columns] = sc.fit_transform(titanic_train_data[numeric_columns])\n#X_cv[numeric_columns] = sc.fit_transform(X_cv[numeric_columns])\ntitanic_test_original=titanic_test_data.copy()\n#titanic_test_data[numeric_columns] = sc.fit_transform(titanic_test_data[numeric_columns])\n\ntitanic_train_data[train_columns+[\"PassengerId\",\"Name\",\"Survived\"]].to_csv(\"titanic_mapped_risk.csv\",index=False)\n\n#from sklearn.naive_bayes import ComplementNB\n#clf = ComplementNB()\n#clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(100,100), random_state=7,max_iter=5000,activation='relu')\n#clf = RandomForestClassifier(max_depth=5, random_state=0,max_features=2)\nclf = LogisticRegression(random_state=7,C=0.1)\n\n#clf=Sequential()\n#clf.add(Dense(units=10, activation=\"relu\",kernel_initializer='glorot_uniform',input_dim=6))\n#clf.add(Dense(units=10, activation=\"relu\",kernel_initializer='glorot_uniform'))\n#clf.add(Dense(units=1, activation = 'sigmoid',kernel_initializer='glorot_uniform'))\n#clf.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n#clf.fit(tf.constant(titanic_train_data[train_columns].values,'float32'), tf.constant(y_train.values,'float32'), epochs = 100)\n#y_pred=clf.predict(tf.constant(X_cv[train_columns].values,'float32'))\nclf.fit(titanic_train_data[train_columns], y_train)\ny_pred=clf.predict_proba(X_cv[train_columns])\ny_pred_df=pd.DataFrame(y_cv)\n#y_pred_df[\"Survived_Prob\"]=y_pred[:,0]\ny_pred_df[\"Not_Survived_Prob\"]=y_pred[:,0]\ny_pred_df[\"Survived_Prob\"]=y_pred[:,1]\ny_pred_df[\"Not_Survived_Prob\"]=round(y_pred_df[\"Not_Survived_Prob\"],2)\ny_pred_df[\"Survived_Prob\"]=round(y_pred_df[\"Survived_Prob\"],2)\ny_pred_df.columns=[\"Survived\",\"Not_Survived_Prob\",\"Survived_Prob\"]\n#y_pred_df.columns=[\"Survived\",\"Survived_Prob\"]\npredictions=X_cv.merge(y_pred_df,left_index=True,right_index=True)\npredictions=predictions.merge(titanic_train_input_data,left_index=True,right_index=True)\npredictions[\"Survived_Prediction\"]=predictions[\"Survived_Prob\"].map(lambda x:(1 if x>=0.5 else 0))\npredictions.query(\"Survived_x==1 & Survived_Prediction!=1\").to_csv(\"predictions_fn.csv\",index=False)\npredictions.query(\"Survived_x==0 & Survived_Prediction==1\").to_csv(\"predictions_fp.csv\",index=False)\n#print(predictions.query(\"Survived_Prediction!=Survived\"))\n#predictions.query(\"Survived_x==1 & Survived_Prediction!=1\").Family_Size.hist()\n\ntn,fp,fn,tp=confusion_matrix(y_cv,predictions[\"Survived_Prediction\"]).ravel()\n\nprint(tn,fp,fn,tp)\nprint(accuracy_score(y_cv,predictions[\"Survived_Prediction\"]))\n#print(clf.coef_[0])\n\nprint(\"Writing submission file:\")\ny_test=clf.predict(titanic_test_data[train_columns])\n#y_test=clf.predict(tf.constant(titanic_test_data[train_columns].values,'float32'))\ntitanic_test_original[\"Survived\"]=y_test\ntitanic_test_original[\"Survived\"]=titanic_test_original[\"Survived\"].map(lambda x:(1 if x>=0.5 else 0))\ntitanic_test_original[[\"PassengerId\",\"Survived\"]].to_csv(\"titanic_random_2.csv\",index=False)","meta":"{'source': 'AI4Code', 'id': '5a3a12e00887bd'}"}
{"id":"40035","text":"\"\"\"\n1. # ****LightGBM prediction of on Eye open\/closed state from EEG Data\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n%matplotlib inline\nprint(os.listdir(\"..\/input\"))\n\ninputData = pd.read_csv(r\"..\/input\/eeg_clean.csv\");\nprint(inputData.dtypes)\nprint(inputData.columns)\nprint(\"Data shape:\",inputData.shape)\nprint(inputData.head())\nprint(inputData.describe())\nprint(inputData.info())\n# Check for any nulls\nprint(inputData.isnull().sum())\n\n# Lets convert the open\/closed category for eye into integers\ninputData['eye']=inputData[\"eye\"].astype('category')\ninputData[\"eye\"] = inputData[\"eye\"].cat.codes\n\nprint (\"************************************\")\nprint (\"EXPERIMENT WITH TEST AND TRAIN SPLIT\")\nprint (\"************************************\")\nfrom sklearn.model_selection import train_test_split\nsplitRatio = 0.2\ntrain , test = train_test_split(inputData,test_size = splitRatio,random_state = 123,shuffle=True)\n\nplt.figure(figsize=(12,6))\nplt.subplot(121)\ntrain[\"eye\"].value_counts().plot.pie(labels = [\"1-open\",\"0-closed\"],\n                                              autopct = \"%1.0f%%\",\n                                              shadow = True,explode=[0,.1])\nplt.title(\"proportion of target class in train data\")\nplt.ylabel(\"\")\nplt.subplot(122)\ntest[\"eye\"].value_counts().plot.pie(labels = [\"1-open\",\"0-closed\"],\n                                             autopct = \"%1.0f%%\",\n                                             shadow = True,explode=[0,.1])\nplt.title(\"proportion of target class in test data\")\nplt.ylabel(\"\")\nplt.show()\n\n\n#Seperating Predictor and target variables\n\ntrain_X = train[[x for x in train.columns if x not in [\"eye\"]]]\ntrain_Y = train[[\"eye\"]]\ntest_X  = test[[x for x in test.columns if x not in [\"eye\"]]]\ntest_Y  = test[[\"eye\"]]\n\nimport lightgbm as lgbm\nfrom sklearn.metrics import classification_report,confusion_matrix,accuracy_score,roc_curve,auc\n# create dataset for lightgbm\n\nlgb_train = lgbm.Dataset(train_X, train_Y)\nlgb_eval = lgbm.Dataset(test_X, test_Y, reference=lgb_train)\nparams = {\n    'objective' :'binary',\n    'tree_learner':'data',\n    'learning_rate' : 0.1,\n    'num_leaves' :99 ,\n    'feature_fraction': 0.8, \n    'bagging_fraction': 0.8, \n    'bagging_freq':1,\n    'boosting_type' : 'gbdt',\n    'metric': 'binary_logloss'\n}\n\nclassifier = lgbm.train(params, lgb_train, 700)\npredictions = classifier.predict(test_X)\npredictedLabels = (predictions>0.35).astype(int)\nprint (\"\\naccuracy_score :\",accuracy_score(test_Y,predictedLabels))\nprint (\"\\nclassification report :\\n\",(classification_report(test_Y,predictedLabels)))\nplt.figure(figsize=(13,10))\nplt.subplot(221)\nsns.heatmap(confusion_matrix(test_Y,predictedLabels),annot=True,fmt = \"d\",linecolor=\"k\",linewidths=3)\nplt.title(\"CONFUSION MATRIX\",fontsize=20)\npredicting_probabilites = predictions\nfpr,tpr,thresholds = roc_curve(test_Y,predicting_probabilites)\nplt.subplot(222)\nplt.plot(fpr,tpr,label = (\"Area_under the curve :\",auc(fpr,tpr)),color = \"r\")\nplt.plot([1,0],[1,0],linestyle = \"dashed\",color =\"k\")\nplt.legend(loc = \"best\")\nplt.title(\"ROC - CURVE & AREA UNDER CURVE\",fontsize=20)    \ndataframe = pd.DataFrame(classifier.feature_importance(),train_X.columns).reset_index()\ndataframe = dataframe.rename(columns={\"index\":\"features\",0:\"coefficients\"})\ndataframe = dataframe.sort_values(by=\"coefficients\",ascending = False)\nplt.subplot(223)\nax = sns.barplot(x = \"coefficients\" ,y =\"features\",data=dataframe,palette=\"husl\")\nplt.title(\"FEATURE IMPORTANCES\",fontsize =20)\nfor i,j in enumerate(dataframe[\"coefficients\"]):\n    ax.text(.011,i,j,weight = \"bold\")\nplt.show()\n\n\n","meta":"{'source': 'AI4Code', 'id': '49b639133b2ee1'}"}
{"id":"36622","text":"\"\"\"\n# Sentiment Analysis of IMDB Movie Reviews\n\"\"\"\n\"\"\"\n**Problem Statement:**\n\nIn this, we have to predict the number of positive and negative reviews based on sentiments by using different classification models.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize.toktok import ToktokTokenizer\nfrom nltk.stem import WordNetLemmatizer\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, f1_score, accuracy_score, confusion_matrix\nfrom sklearn.svm import SVC, LinearSVC\n\nimport re,string\nfrom wordcloud import WordCloud,STOPWORDS\ndata = pd.read_csv('..\/input\/imdb-dataset-of-50k-movie-reviews\/IMDB Dataset.csv')\nprint(data.shape)\ndata.head()\n#Summary of the dataset\ndata.describe()\n#Class Distrubution\ndata['sentiment'].value_counts()\n\"\"\"\n### Change Target variable\n\"\"\"\n## 0 as Negative and 1 as Positive\ndata.sentiment = data.sentiment.apply(lambda x: 0 if x=='negative' else 1)\n\"\"\"\n<h1>Feature Engineering<\/h1>\n\n### Indirect features:\n- count of sentences\n- count of title words\n- count of stop words\n- count of words\n- count\/percentage of unique words\n- count\/percentage of punctuations\n\"\"\"\n## Indirect features\neng_stopwords = set(stopwords.words(\"english\"))\n\ndata[\"count_words_title\"] = data[\"review\"].apply(lambda x: len([w for w in str(x).split() if w.istitle()]))\ndata[\"count_stopwords\"] = data[\"review\"].apply(lambda x: len([w for w in str(x).lower().split() if w in eng_stopwords]))\n\ndata['count_word'] = data[\"review\"].apply(lambda x: len(str(x).split()))\ndata['count_unique_word'] = data[\"review\"].apply(lambda x: len(set(str(x).split())))\ndata[\"count_punctuations\"] = data[\"review\"].apply(lambda x: len([c for c in str(x) if c in string.punctuation]))\ndata['word_unique_percent'] = data['count_unique_word'] * 100 \/ data['count_word']\ndata['punct_percent'] = data['count_punctuations'] * 100 \/ data['count_word']\n\n## Reordering the columns \ndata = data[['review', 'count_words_title', 'count_stopwords',\n             'count_word', 'count_unique_word', 'count_punctuations',\n             'word_unique_percent', 'punct_percent','sentiment']]\ndata.head()\nplt.hist(data[data['sentiment']==0]['count_word'], range=(0,1500), color='red', edgecolor='black', \n         label='positive reviews', alpha=0.5)\nplt.hist(data[data['sentiment']==1]['count_word'], range=(0,1500), color='green', edgecolor='black', \n         label='negative reviews', alpha=0.1)\n\nplt.title('Word Count Distribution')\nplt.xlabel('Word Count')\nplt.legend()\nplt.show()\n\"\"\"\n## Text Preprocessing of Reviews\n\"\"\"\n\"\"\"\n<b> In machine learning task, cleaning or pre-processing the data is as important as model building if not more. And when it comes to unstructured data like text, this process is of most importance. IMDB reviews are posted by users manually, so we observe high usage of contractions and chat words in it. Also, some reviews are collected from other sites, so we also observe usage of many HTML tags in dataset.<\/b>\n\n**a. Clean Contractions or Chat Words:**\nAs this is manually entered reviews, people do use a lot of abbreviated words in chat and so it is important for us to expand all such chat words and contractions used. I\u2019ve used list of slangs and contractions from repo.\n\n**b. Lower Casing** Lower casing is a common text preprocessing technique. The idea is to convert the input text into same casing format so that 'text', 'Text' and 'TEXT' are treated the same way. This is more helpful for text featurization techniques like frequency, tfidf as it helps to combine the same words together thereby reducing the duplication and get correct counts \/ tfidf values.\n\n**c. Removal Of Stop Words**\nStopwords are commonly occuring words in a language like 'the', 'a' and so on. They can be removed from the text most of the times, as they don't provide valuable information for downstream analysis. These stopword lists are already compiled for different languages and we can safely use them. For example, the stopword list for english language is,\n\n**d. Lemmatization**\nLemmatization is similar to stemming in reducing inflected words to their word stem but differs in the way that it makes sure the root word (also called as lemma) belongs to the language. As a result, this one is generally slower than stemming process. I\u2019m using standard WordNetLemmatizer for work.\n\n**e. Removal Of Urls & HTML Tags:**\nWe found large usage of HTML tags in dataset. To make sense of dataset, such tags to be removed.\n\n**f. Removal Of Punctuations** In this process, we remove the punctuations (!\"#$%&\\'()*+,-.\/:;<=>?@[\\\\]^_`{|}~) from the text data. This is a text standardization process that will help to treat 'hurray' and 'hurray!' in the same way. Note of caution- This process has to be performed after removal of HTML tags else some standard tags of HTML will partially get removed in this process and afterwards HTML removal process will not give suitable results.\n\"\"\"\n# Removing all punctuations from Text\nmapping = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\",\"he'll\": \"he will\", \"he's\": \"he is\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \"how'll\": \"how will\", \"how's\": \"how is\",  \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \"I'll've\": \"I will have\",\"I'm\": \"I am\", \"I've\": \"I have\", \"i'd\": \"i would\", \"i'd've\": \"i would have\", \"i'll\": \"i will\",  \"i'll've\": \"i will have\",\"i'm\": \"i am\", \"i've\": \"i have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\",\"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\",\"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \"so've\": \"so have\",\"so's\": \"so as\", \"this's\": \"this is\",\"that'd\": \"that would\", \"that'd've\": \"that would have\", \"that's\": \"that is\", \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \"weren't\": \"were not\", \"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\",  \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \"where've\": \"where have\", \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who's\": \"who is\", \"who've\": \"who have\", \"why's\": \"why is\", \"why've\": \"why have\", \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\",\"y'all'd've\": \"you all would have\",\"y'all're\": \"you all are\",\"y'all've\": \"you all have\",\"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \"you're\": \"you are\", \"you've\": \"you have\" }\nPUNCT_TO_REMOVE = string.punctuation # '!\"#$%&\\'()*+,-.\/:;<=>?@[\\\\]^_`{|}~'\neng_stopwords = set(stopwords.words(\"english\"))\nlemmatizer = WordNetLemmatizer()\n\ndef remove_punctuation(text):\n    return text.translate(str.maketrans('', '', PUNCT_TO_REMOVE))\n\ndef clean_contractions(text, mapping):\n    specials = [\"\u2019\", \"\u2018\", \"\u00b4\", \"`\"]\n    for s in specials:\n        text = text.replace(s, \"'\")\n    text = ' '.join([mapping[t] if t in mapping else t for t in text.split(\" \")])\n    return text\n\ndef remove_stopwords(text):\n    return \" \".join([word for word in str(text).split() if word not in eng_stopwords])\n\ndef word_replace(text):\n    return text.replace('<br \/>','')\n\ndef lemmatize_words(text):\n    return \" \".join([lemmatizer.lemmatize(word) for word in text.split()])\n\ndef remove_urls(text):\n    url_pattern = re.compile(r'https?:\/\/\\S+|www\\.\\S+')\n    return url_pattern.sub(r'', text)\n\ndef remove_html(text):\n    html_pattern = re.compile('<.*?>')\n    return html_pattern.sub(r'', text)\n\ndef preprocess(text):\n    text = clean_contractions(text, mapping)\n    text = text.lower()\n    text = word_replace(text)\n    text = remove_urls(text)\n    text = remove_html(text)\n    text = remove_stopwords(text)\n    text = remove_punctuation(text)\n    text = lemmatize_words(text)\n    \n    return text\ndata[\"reviews_preprocessed\"]=data[\"review\"].apply(lambda text: preprocess(text))\ndata.head()\n\"\"\"\n# Word Cloud\n\"\"\"\n# Positive Reviews.\nplt.figure(figsize=(15, 15))\nwc = WordCloud(max_words=200, width=1000, height=500, stopwords=STOPWORDS).generate(\" \".join(data[data.sentiment==1].reviews_preprocessed))\nplt.imshow(wc, interpolation='bilinear')\n# Negative Reviews.\nplt.figure(figsize=(15, 15))\nwc = WordCloud(max_words=200, width=1000, height=500, stopwords=STOPWORDS).generate(\" \".join(data[data.sentiment==0].reviews_preprocessed))\nplt.imshow(wc, interpolation='bilinear')\n\"\"\"\n- From these word clouds, we are not able to judge any starling differences in both the sentiments by looking at words. We don\u2019t see usage of extreme negative connotation or abusive language used while writing negative reviews.\n\"\"\"\n\"\"\"\n### Utility Function\n\"\"\"\ndef metrics(model, x , y):\n    y_pred = model.predict(x)\n    acc = accuracy_score(y, y_pred)\n    f1 = f1_score(y, y_pred)\n    print(\"\\nAccuracy: \", round(acc,3))\n    print(\"\\nF1 Score: \", round(f1,3))\n    \n    cm=confusion_matrix(y, y_pred)\n    plt.figure(figsize=(4, 4))\n    sns.heatmap(cm, annot=True, cmap='coolwarm', xticklabels=[0,1], fmt='d', annot_kws={\"fontsize\":19})\n    plt.xlabel(\"Predicted\", fontsize=16)\n    plt.ylabel(\"Actual\", fontsize=16)\n    plt.show()\n\"\"\"\n# Model based on Indirect Features\n\"\"\"\nX = data[['count_words_title', 'count_stopwords',\n        'count_word', 'count_unique_word', 'count_punctuations',\n        'word_unique_percent', 'punct_percent']]\n\ny = data['sentiment']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n[i.shape for i in [X_train, X_test, y_train, y_test]]\nlinear_svc = LinearSVC(penalty='l2', dual=False)\nlinear_svc.fit(X_train, y_train)\nmetrics(linear_svc, X_test, y_test)\n\"\"\"\n- As expected, this model is giving us poor accuracy of 58% as we depicted in EDA. Indirect features have very similar trends and patterns across both the classes, we have seen in EDA portion.\n\"\"\"\n\"\"\"\n## N-gram Analysis\n- The order that words are used in text is not random. In English, for example, you can say \"the red apple\" but not \"apple red the\". The general idea is that you can look at each pair (or double, triple etc.) of words that occur next to each other. In a sufficently-large corpus, you're likely to see \"the red\" and \"red apple\" several times, but less likely to see \"apple red\" and \"red the\". This is useful to know if, for example, you're trying to figure out what someone is more likely to say to help decide between possible output for an automatic speech recognition system. These co-occuring words are known as \"n-grams\", where \"n\" is a number saying how long a string of words you considered.\n\"\"\"\n#dtype: string\ntexts = ' '.join(data['reviews_preprocessed'])\ntexts_to_list = texts.split(\" \")\ndef draw_n_gram(texts_to_list, i):\n    n_gram = (pd.Series(nltk.ngrams(texts_to_list, i)).value_counts())[:11]\n    n_gram_df = pd.DataFrame(n_gram)\n    n_gram_df = n_gram_df.reset_index()\n    n_gram_df = n_gram_df.rename(columns={\"index\": \"word\", 0: \"count\"})\n    print(n_gram_df.head(10))\n    plt.figure(figsize=(10,5))\n    return sns.barplot(x='count', y='word', data=n_gram_df, palette=\"Blues_d\")\n\"\"\"\n## Unigram Analysis\n\"\"\"\ndraw_n_gram(texts_to_list, 1)\n\"\"\"\n## Bigram Analysis\n\"\"\"\ndraw_n_gram(texts_to_list, 2)\n\"\"\"\n## Trigram Analysis\n\"\"\"\ndraw_n_gram(texts_to_list, 3)\n\"\"\"\n## Quadgram Analysis\n\"\"\"\ndraw_n_gram(texts_to_list, 4)\nX_train, X_test, y_train, y_test = train_test_split(data['reviews_preprocessed'], data['sentiment'], test_size=0.2, random_state=0)\n[i.shape for i in [X_train, X_test, y_train, y_test]]\nword_vectorizer = TfidfVectorizer(\n    sublinear_tf=True,\n    strip_accents='unicode',\n    analyzer='word',\n    token_pattern=r'\\w{1,}',\n    stop_words='english',\n    ngram_range=(1, 4),\n    max_features=8000\n)\n\nword_vectorizer.fit(data['reviews_preprocessed'])\n\ntfidf_train = word_vectorizer.transform(X_train)\ntfidf_test = word_vectorizer.transform(X_test)\n\nprint('Shape of tfidf_train:', tfidf_train.shape)\nprint('Shape of tfidf_test:', tfidf_test.shape)\nword_vectorizer2 = TfidfVectorizer(\n    sublinear_tf=True,\n    strip_accents='unicode',\n    analyzer='word',\n    token_pattern=r'\\w{1,}',\n    stop_words='english',\n    ngram_range=(1, 4),\n    max_features=None\n)\n\nword_vectorizer2.fit(data['reviews_preprocessed'])\n\ntfidf_train2 = word_vectorizer2.transform(X_train)\ntfidf_test2 = word_vectorizer2.transform(X_test)\n\nprint('Shape of tfidf_train:', tfidf_train2.shape)\nprint('Shape of tfidf_test:', tfidf_test2.shape)\nlinear_svc = LinearSVC(penalty='l2', dual=False)\nlinear_svc.fit(tfidf_train, y_train)\nmetrics(linear_svc, tfidf_test, y_test)\nlinear_svc = LinearSVC(penalty='l2', dual=False)\nlinear_svc.fit(tfidf_train2, y_train)\nmetrics(linear_svc, tfidf_test2, y_test)\n\"\"\"\n### **2) Count Vectorizer-** \n\n\"\"\"\ncv=CountVectorizer(analyzer='word', token_pattern=r'\\w{1,}',\n                   ngram_range=(1,3),max_features=10000)\ncv.fit(data['reviews_preprocessed'])\ncv_train = cv.transform(X_train)\ncv_test = cv.transform(X_test)\nprint('Shape of cv_train:', cv_train.shape)\nprint('Shape of cv_test:', cv_test.shape)\ncv4=CountVectorizer(analyzer='word', token_pattern = r'\\w{1,}',\n                    ngram_range=(1,4),max_features=10000)\ncv4.fit(data['reviews_preprocessed'])\ncv4_train = cv4.transform(X_train)\ncv4_test = cv4.transform(X_test)\nprint('Shape of cv_train:', cv4_train.shape)\nprint('Shape of cv_test:', cv4_test.shape)\nlinear_svc = LinearSVC(C=0.5, dual=False, random_state=42)\nlinear_svc.fit(cv_train, y_train)\n\nmetrics(linear_svc, cv_test, y_test)\nlinear_svc = LinearSVC(penalty='l2', dual=False, random_state=42)\nlinear_svc.fit(cv4_train, y_train)\n\nmetrics(linear_svc, cv4_test, y_test)","meta":"{'source': 'AI4Code', 'id': '436c78a43afb0e'}"}
{"id":"38744","text":"\"\"\"\n# Keras, How to use pretrained model?\n\npretrained \ubaa8\ub378\uc744 \ud558\ub294 \ubc95\uc744 \uc18c\uac1c\ud569\ub2c8\ub2e4.\n\n\ub300\ubd80\ubd84\uc758 \uc18c\uc2a4\ucf54\ub4dc\ub294 \ub2e4\ub978 \ucf54\ub4dc\ub97c \ucc38\uace0\ud558\uc5ec\uc11c \uc81c\uac00 \uc218\uc815\ud55c \ucf54\ub4dc\ub9cc \uc124\uba85\uc744 \ub4dc\ub9ac\ub3c4\ub85d\ud558\uaca0\uc2b5\ub2c8\ub2e4.\n\n\ub9cc\uc57d \uce90\uae00\uc5d0\uc11c \uc81c\uacf5\ud558\ub294 \ucee4\ub110\uc744 \uc0ac\uc6a9\ud558\uc2e0\ub2e4\uba74,  \n\uaf2d \uc6b0\uce21 `Settings`\uc5d0\uc11c `GPU` \uc640 `Internet` \ud56d\ubaa9\uc744 `On`\uc73c\ub85c \ud65c\uc131\ud654 \ud574\uc8fc\uc2dc\uae38 \ubc14\ub78d\ub2c8\ub2e4.\n\n## References\n\n\ub300\ubd80\ubd84\uc758 \ucf54\ub4dc\ub294 \uae40\ud0dc\uc9c4\ub2d8 \ubca0\uc774\uc2a4\ub77c\uc778 \ucf54\ub4dc\uc640 \ud5c8\ud0dc\uba85\ub2d8\uc758 \uc774\ubbf8\uc9c0 Cropping \ucf54\ub4dc\ub97c \uc0ac\uc6a9\ud558\uc600\uc2b5\ub2c8\ub2e4.  \n\uc88b\uc740 \uc790\ub8cc \uc81c\uacf5\ud574\uc8fc\uc154\uc11c \uac10\uc0ac\ud569\ub2c8\ub2e4!\n\n* [Applications - Keras Documentation](https:\/\/keras.io\/applications\/)\n* [\uae40\ud0dc\uc9c4\ub2d8 \ucee4\ub110: [3rd ML Month] Car Model Classification Baseline](https:\/\/www.kaggle.com\/fulrose\/3rd-ml-month-car-model-classification-baseline)\n* [\ud5c8\ud0dc\uba85\ub2d8 \ucee4\ub110: [3rd ML Month] Car Image Cropping](https:\/\/www.kaggle.com\/tmheo74\/3rd-ml-month-car-image-cropping)\n\n## Introduction\n\nKeras Documentation\uc5d0\uc11c\ub294 Pretrained \ubaa8\ub378\uc5d0 \ub300\ud574\uc120 \ub2e4\uc74c\uacfc \uac19\uc774 \ub9d0\ud558\uace0 \uc788\uc2b5\ub2c8\ub2e4.\n> The top-1 and top-5 accuracy refers to the model's performance on the ImageNet validation dataset.\n\n\uc774\ub294 ImageNet \ub370\uc774\ud130\uc14b\uc744 \uc0ac\uc6a9\ud574\uc11c \ud559\uc2b5\uc744 \uc2dc\ud0a8 weights\ub77c\ub294 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n## What is a pretrained model?\n\n\ubbf8\ub9ac\uc798 \ud559\uc2b5\ub41c \ubaa8\ub378 \ud30c\uc77c\uc744 \ub2e4\uc6b4\ubc1b\uc544, \ud574\ub2f9 \ud30c\uc77c\ub85c Weight\ub97c \ucd08\uae30\ud654 \uc2dc\ud0a4\ub294 \uac83\uc744 Pretrained \ubaa8\ub378\uc774\ub77c \ud558\uace0,\n\n\uc774\ub7ec\ud55c \ud559\uc2b5\ubc95\uc744 **Transfer Learning(\uc804\uc774\ud559\uc2b5)** \uc774\ub77c \ud569\ub2c8\ub2e4.\n\n\ub2e4\uc74c\ubd80\ud130 \uc804\uc774 \ud559\uc2b5\uc5d0 \ud544\uc694\ud55c \ucf54\ub4dc \uc218\uc815 \ubd80\ubd84\ub9cc \uc124\uba85\ud574 \ub4dc\ub9ac\ub3c4\ub85d \ud558\uaca0\uc2b5\ub2c8\ub2e4.\n\n\"\"\"\n\"\"\"\n# Cropped Image Dataset\n\"\"\"\nimport gc\nimport os\nimport glob\nimport zipfile\nimport warnings\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nimport cv2\nimport PIL\nfrom PIL import ImageOps, ImageFilter, ImageDraw\nDATA_PATH = '..\/input\/'\nos.listdir(DATA_PATH)\n# \uc774\ubbf8\uc9c0 \ud3f4\ub354 \uacbd\ub85c\nTRAIN_CROP_PATH = \".\/train_crop\"\nTEST_CROP_PATH = \".\/test_crop\"\nTRAIN_IMG_PATH = os.path.join(DATA_PATH, 'train')\nTEST_IMG_PATH = os.path.join(DATA_PATH, 'test')\n\n# CSV \ud30c\uc77c \uacbd\ub85c\ndf_train = pd.read_csv(os.path.join(DATA_PATH, 'train.csv'))\ndf_test = pd.read_csv(os.path.join(DATA_PATH, 'test.csv'))\ndf_class = pd.read_csv(os.path.join(DATA_PATH, 'class.csv'))\ndf_train.head()\ndf_test.head()\n\"\"\"\n\ud0dc\uba85\ub2d8\uc774 \uc791\uc131\ud558\uc2e0 \ud568\uc218\uc5d0\uc11c Resize \uae30\ub2a5\uc744 \ucd94\uac00\ud558\uc600\uc2b5\ub2c8\ub2e4.\n\n\uacf5\uc778\ub41c CNN \ub124\ud2b8\uc6cc\ud06c\uc758 Input shape\uc744 \ubcf4\uc2dc\uba74 `224 * 224`, `299 * 299` \uc640 \uac19\uc740 shape\uc73c\ub85c \uc774\ub8e8\uc5b4\uc838 \uc788\uae30 \ub54c\ubb38\uc5d0,  \n\ubbf8\ub9ac \ub370\uc774\ud130\ub97c \uc900\ube44\ud558\ub294 \ub2e8\uacc4\uc5d0\uc11c shape\uc744 \uc9c0\uc815\ud558\uace0 reshape(resize)\uc744 \ud558\uace0 \uc800\uc7a5\ud560 \uac83 \uc785\ub2c8\ub2e4.\n\"\"\"\ndef crop_resize_boxing_img(img_name, margin=16, size=(224, 224)) :\n    if img_name.split('_')[0] == \"train\" :\n        PATH = TRAIN_IMG_PATH\n        data = df_train\n    elif img_name.split('_')[0] == \"test\" :\n        PATH = TEST_IMG_PATH\n        data = df_test\n        \n    img = PIL.Image.open(os.path.join(PATH, img_name))\n    pos = data.loc[data[\"img_file\"] == img_name, \\\n                   ['bbox_x1','bbox_y1', 'bbox_x2', 'bbox_y2']].values.reshape(-1)\n\n    width, height = img.size\n    x1 = max(0, pos[0] - margin)\n    y1 = max(0, pos[1] - margin)\n    x2 = min(pos[2] + margin, width)\n    y2 = min(pos[3] + margin, height)\n\n    return img.crop((x1,y1,x2,y2)).resize(size)\n\"\"\"\n# Process Train Image Data Crop\n\"\"\"\n!mkdir {TRAIN_CROP_PATH}\n%%time\nfor i, row in df_train.iterrows():\n    cropped = crop_resize_boxing_img(row['img_file'])\n    cropped.save(f\"{TRAIN_CROP_PATH}\/{row['img_file']}\")\n\"\"\"\n# Process Test Image Data Crop\n\"\"\"\n!mkdir {TEST_CROP_PATH}\n%%time\nfor i, row in df_test.iterrows():\n    cropped = crop_resize_boxing_img(row['img_file'])\n    cropped.save(f\"{TEST_CROP_PATH}\/{row['img_file']}\")\n\"\"\"\n# Cropped Image Eye Checking\n\"\"\"\ntmp_imgs = df_train['img_file'][100:105]\nplt.figure(figsize=(12,20))\n\nfor num, f_name in enumerate(tmp_imgs):\n    img = PIL.Image.open(os.path.join(TRAIN_IMG_PATH, f_name))\n    plt.subplot(5, 2, 2*num + 1)\n    plt.title(f_name)\n    plt.imshow(img)\n    plt.axis('off')\n    \n    img_crop = PIL.Image.open(f\"train_crop\/{f_name}\")\n    plt.subplot(5, 2, 2*num + 2)\n    plt.title(f_name + ' cropped')\n    plt.imshow(img_crop)\n    plt.axis('off')\n\"\"\"\n## Modeling\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ndf_train[\"class\"] = df_train[\"class\"].astype('str')\n\ndf_train = df_train[['img_file', 'class']]\ndf_test = df_test[['img_file']]\n\nits = np.arange(df_train.shape[0])\ntrain_idx, val_idx = train_test_split(its, train_size = 0.8, random_state=42)\n\nX_train = df_train.iloc[train_idx, :]\nX_val = df_train.iloc[val_idx, :]\n\nprint(X_train.shape)\nprint(X_val.shape)\nprint(df_test.shape)\nimport tensorflow as tf\nfrom tensorflow.keras.applications.mobilenet import preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n# Parameter\nimg_size = (224, 224)\nnb_train_samples = len(X_train)\nnb_validation_samples = len(X_val)\nnb_test_samples = len(df_test)\nepochs = 20\nbatch_size = 32\n\n# Define Generator config\ntrain_datagen = ImageDataGenerator(\n    horizontal_flip = True, \n    vertical_flip = False,\n    preprocessing_function=preprocess_input\n)\nval_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\ntest_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\n# Make Generator\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=X_train, \n    directory=TRAIN_CROP_PATH,\n    x_col = 'img_file',\n    y_col = 'class',\n    target_size = img_size,\n    color_mode='rgb',\n    class_mode='categorical',\n    batch_size=batch_size,\n    seed=42\n)\n\nvalidation_generator = val_datagen.flow_from_dataframe(\n    dataframe=X_val, \n    directory=TRAIN_CROP_PATH,\n    x_col='img_file',\n    y_col='class',\n    target_size=img_size,\n    color_mode='rgb',\n    class_mode='categorical',\n    batch_size=batch_size,\n    shuffle=False\n)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=df_test,\n    directory=TEST_CROP_PATH,\n    x_col='img_file',\n    y_col=None,\n    target_size= img_size,\n    color_mode='rgb',\n    class_mode=None,\n    batch_size=batch_size,\n    shuffle=False\n)\n\"\"\"\n\uc800 \uac19\uc740 \uacbd\uc6b0 \ubaa8\ub378\uc744 `MobileNet` \uc73c\ub85c \uc0ac\uc6a9\ud558\uc600\ub294\ub370,  \n\ubaa8\ub378\uc774 \uac00\ubccd\uace0 \ube60\ub974\uac8c \ud559\uc2b5\ub418\uc11c, \ud14c\uc2a4\ud2b8\uc5d0 \uc6a9\uc774\ud574 \ub9ce\uc774 \uc0ac\uc6a9\ud558\uace0\uc788\uc2b5\ub2c8\ub2e4.\n\n\ubaa8\ub378\uc744 \uad50\uccb4\ud558\uba74\uc11c \uac00\uc7a5 \uc88b\uc740 \uc544\ud0a4\ud14d\uccd0\ub97c \ucc3e\ub294 \uc791\uc5c5\ub3c4 \uc88b\uc740 \uc2a4\ucf54\uc5b4\ub97c \uc5bb\ub294\ub370 \uc88b\uc744 \uac83 \uac19\uc2b5\ub2c8\ub2e4.\n\"\"\"\nfrom tensorflow.keras.applications.mobilenet import MobileNet, preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Activation, Conv2D, GlobalAveragePooling2D\n\"\"\"\nCNN \ubaa8\ub378\uc744 \ucd08\uae30\ud654 \ud560\ub54c \ub2e4\uc74c\uacfc \uac19\uc774 `weights='imagenet'`\uc744 Keras\uc5d0\uc11c \ubaa8\ub378\uc744 \uc790\ub3d9\uc73c\ub85c \ub2e4\uc6b4\ubc1b\uc544 \ub85c\ub529\ud569\ub2c8\ub2e4.\n\npretrained \ubaa8\ub378\uc758 top layer\ub294 Fully connected layer\ub85c 1000\uac1c\ub97c \ubd84\ub958\ud558\ub294 \uc6a9\ub3c4\uc785\ub2c8\ub2e4.\n\n\uc774 \ubb38\uc81c\uc5d0\uc11c\ub294 196\uac00\uc9c0\uc758 \ubd84\ub958\ub97c \ud559\uc2b5\uc2dc\ucf1c\uc57c \ud558\uae30\ub54c\ubb38\uc5d0  \n`inclue_top=False` \uc635\uc158\uc73c\ub85c \ud574\ub2f9 \ub808\uc774\uc5b4\ub97c \ubd84\ub9ac\uc2dc\ud0a8 \ud6c4,\n`Dense(196)`\uc744 \ucd94\uac00\ud558\uc154\uc57c \ud569\ub2c8\ub2e4.\n\n\ud0dc\uc9c4\ub2d8\uc758 \uae30\ubcf8 \ucf54\ub4dc\uad6c\uc870\uac00 \uc774\ubbf8 \uadf8\ub807\uac8c \ub418\uc5b4\uc788\uae30 \ub54c\ubb38\uc5d0 \uc635\uc158\ub9cc \ucd94\uac00\ud558\uc2dc\uba74 \ub429\ub2c8\ub2e4.\n\"\"\"\n# for layer in resNet_model.layers:\n#     layer.trainable = False\n#     print(layer,layer.trainable)\n\nmobileNetModel = MobileNet(weights='imagenet', include_top=False)\n\nmodel = Sequential()\nmodel.add(mobileNetModel)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(196, activation='softmax', kernel_initializer='he_normal'))\nmodel.summary()\nfrom sklearn.metrics import f1_score\n\ndef micro_f1(y_true, y_pred):\n    return f1_score(y_true, y_pred, average='micro')\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])\ndef get_steps(num_samples, batch_size):\n    if (num_samples % batch_size) > 0 :\n        return (num_samples \/\/ batch_size) + 1\n    else :\n        return num_samples \/\/ batch_size\n\"\"\"\nValidation score\uac00 \uac00\uc7a5 \uc88b\uc740 \ubaa8\ub378\uc744 \uc0ac\uc6a9\ud558\uae30 \uc704\ud574 `ModelCheckpoint`\ub97c \uc0ac\uc6a9\ud558\uc600\uc2b5\ub2c8\ub2e4.\n\n\uc774\ub97c \uc0ac\uc6a9\ud558\uba74 `monitor`\uc635\uc158\uc5d0 \uc9c0\uc815\ub41c \uc2a4\ucf54\uc5b4\uac00 \uac00\uc7a5 \uc88b\uc744 \ub54c \ubaa8\ub378 \ud30c\uc77c(weights)\uc744 \uc800\uc7a5\ud569\ub2c8\ub2e4.\n\n\ub2e4\uc74c\uacfc \uac19\uc774 \uc0ac\uc6a9\ud558\uc2e4 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\n%%time\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\nfilepath = \"my_mobilenet_model_{val_acc:.2f}_{val_loss:.4f}.h5\"\n\nckpt = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True)\nes = EarlyStopping(monitor='val_acc', min_delta=0, patience=3, verbose=1, mode='auto')\n\ncallbackList = [ckpt]\n\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch = get_steps(nb_train_samples, batch_size),\n    epochs=epochs,\n    validation_data = validation_generator,\n    validation_steps = get_steps(nb_validation_samples, batch_size),\n    callbacks = callbackList\n)\ngc.collect()\n# Plot training & validation accuracy values\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\"\"\"\n## Submission\n\"\"\"\n\"\"\"\n\uba3c\uc800 \uac00\uc7a5 \uc88b\uc740 \ubaa8\ub378\uc744 \ub85c\ub529\ud558\uae30 \uc704\ud574 \ub530\ub85c \ud30c\uc77c\uc744 \uc815\ub82c\ud574\uc8fc\uace0,  \n\ub9c8\uc9c0\ub9c9 \uc778\ub371\uc2a4 \ud30c\uc77c\uc744 \ubaa8\ub378\uc5d0 \ub85c\ub529\ud569\ub2c8\ub2e4.\n\"\"\"\nmodel_list = sorted([i for i in os.listdir() if \"my_\" in i])\nmodel_list\nmodel.load_weights(model_list[-1])\n%%time\ntest_generator.reset()\nprediction = model.predict_generator(\n    generator = test_generator,\n    steps = get_steps(nb_test_samples, batch_size),\n    verbose=1\n)\npredicted_class_indices=np.argmax(prediction, axis=1)\n\n# Generator class dictionary mapping\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\npredictions = [labels[k] for k in predicted_class_indices]\n\nsubmission = pd.read_csv(os.path.join(DATA_PATH, 'sample_submission.csv'))\nsubmission[\"class\"] = predictions\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head()\n!rm -rf *_crop\n\"\"\"\n### \ub05d\uae4c\uc9c0 \ubd10\uc8fc\uc154\uc11c \uac10\uc0ac\ud569\ub2c8\ub2e4!\n\n**\uc88b\uc740 \ub300\ud68c\uc640 \uc790\ub8cc\ub97c \uacf5\uc720\ud574 \uc8fc\uc2e0 \uce90\uae00 \ucf54\ub9ac\uc544 \ubd84\ub4e4\uaed8 \uac10\uc0ac\ub4dc\ub9bd\ub2c8\ub2e4.**\n\n**\uc7ac\ubc0c\uac8c \uce90\uae00\ud574\uc694^^**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '475ae848bac990'}"}
{"id":"92390","text":"\"\"\"\nThis inference notebook is the same as @kkiller's [one](https:\/\/www.kaggle.com\/kneroma\/clean-fast-simple-bird-identifier-inference). Please upvote the original notebook.\n\nIn this Notebook, I just lower the threshold. And it seems that LB will increase with smaller thresh, maybe which overfitting the public leaderboard.\n\"\"\"\ntry:\n    import resnest\nexcept ModuleNotFoundError:\n    !pip install -q \"..\/input\/resnest50-fast-package\/resnest-0.0.6b20200701\/resnest\"\nimport numpy as np\nimport librosa as lb\nimport soundfile as sf\nimport pandas as pd\nimport cv2\nfrom pathlib import Path\nimport re\n\nimport torch\nfrom torch import nn\nfrom  torch.utils.data import Dataset, DataLoader\n\nfrom tqdm.notebook import tqdm\n\nimport time\nfrom resnest.torch import resnest50\n\"\"\"\n# Configs\n\"\"\"\nNUM_CLASSES = 397\nSR = 32_000\nDURATION = 5\nTHRESH = 0.11\n\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"DEVICE:\", DEVICE)\n\nTEST_AUDIO_ROOT = Path(\"..\/input\/birdclef-2021\/test_soundscapes\")\nSAMPLE_SUB_PATH = \"..\/input\/birdclef-2021\/sample_submission.csv\"\nTARGET_PATH = None\n    \nif not len(list(TEST_AUDIO_ROOT.glob(\"*.ogg\"))):\n    TEST_AUDIO_ROOT = Path(\"..\/input\/birdclef-2021\/train_soundscapes\")\n    SAMPLE_SUB_PATH = None\n    # SAMPLE_SUB_PATH = \"..\/input\/birdclef-2021\/sample_submission.csv\"\n    TARGET_PATH = Path(\"..\/input\/birdclef-2021\/train_soundscape_labels.csv\")\n\"\"\"\n# Data\n\"\"\"\nclass MelSpecComputer:\n    def __init__(self, sr, n_mels, fmin, fmax, **kwargs):\n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax\n        kwargs[\"n_fft\"] = kwargs.get(\"n_fft\", self.sr\/\/10)\n        kwargs[\"hop_length\"] = kwargs.get(\"hop_length\", self.sr\/\/(10*4))\n        self.kwargs = kwargs\n\n    def __call__(self, y):\n\n        melspec = lb.feature.melspectrogram(\n            y, sr=self.sr, n_mels=self.n_mels, fmin=self.fmin, fmax=self.fmax, **self.kwargs,\n        )\n\n        melspec = lb.power_to_db(melspec).astype(np.float32)\n        return melspec\ndef mono_to_color(X, eps=1e-6, mean=None, std=None):\n    mean = mean or X.mean()\n    std = std or X.std()\n    X = (X - mean) \/ (std + eps)\n    \n    _min, _max = X.min(), X.max()\n\n    if (_max - _min) > eps:\n        V = np.clip(X, _min, _max)\n        V = 255 * (V - _min) \/ (_max - _min)\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(X, dtype=np.uint8)\n\n    return V\n\ndef crop_or_pad(y, length):\n    if len(y) < length:\n        y = np.concatenate([y, length - np.zeros(len(y))])\n    elif len(y) > length:\n        y = y[:length]\n    return y\nclass BirdCLEFDataset(Dataset):\n    def __init__(self, data, sr=SR, n_mels=128, fmin=0, fmax=None, duration=DURATION, step=None, res_type=\"kaiser_fast\", resample=True):\n        \n        self.data = data\n        \n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax or self.sr\/\/2\n\n        self.duration = duration\n        self.audio_length = self.duration*self.sr\n        self.step = step or self.audio_length\n        \n        self.res_type = res_type\n        self.resample = resample\n\n        self.mel_spec_computer = MelSpecComputer(sr=self.sr, n_mels=self.n_mels, fmin=self.fmin,\n                                                 fmax=self.fmax)\n    def __len__(self):\n        return len(self.data)\n    \n    @staticmethod\n    def normalize(image):\n        image = image.astype(\"float32\", copy=False) \/ 255.0\n        image = np.stack([image, image, image])\n        return image\n    \n    def audio_to_image(self, audio):\n        melspec = self.mel_spec_computer(audio) \n        image = mono_to_color(melspec)\n        image = self.normalize(image)\n        return image\n\n    def read_file(self, filepath):\n        audio, orig_sr = sf.read(filepath, dtype=\"float32\")\n\n        if self.resample and orig_sr != self.sr:\n            audio = lb.resample(audio, orig_sr, self.sr, res_type=self.res_type)\n          \n        audios = []\n        for i in range(self.audio_length, len(audio) + self.step, self.step):\n            start = max(0, i - self.audio_length)\n            end = start + self.audio_length\n            audios.append(audio[start:end])\n            \n        if len(audios[-1]) < self.audio_length:\n            audios = audios[:-1]\n            \n        images = [self.audio_to_image(audio) for audio in audios]\n        images = np.stack(images)\n        \n        return images\n    \n        \n    def __getitem__(self, idx):\n        return self.read_file(self.data.loc[idx, \"filepath\"])\ndata = pd.DataFrame(\n     [(path.stem, *path.stem.split(\"_\"), path) for path in Path(TEST_AUDIO_ROOT).glob(\"*.ogg\")],\n    columns = [\"filename\", \"id\", \"site\", \"date\", \"filepath\"]\n)\nprint(data.shape)\ndata.head()\ndf_train = pd.read_csv(\"..\/input\/birdclef-2021\/train_metadata.csv\")\n\nLABEL_IDS = {label: label_id for label_id,label in enumerate(sorted(df_train[\"primary_label\"].unique()))}\nINV_LABEL_IDS = {val: key for key,val in LABEL_IDS.items()}\n\"\"\"\n# Inference\n\"\"\"\ntest_data = BirdCLEFDataset(data=data)\nlen(test_data), test_data[0].shape\ndef load_net(checkpoint_path, num_classes=NUM_CLASSES):\n    net = resnest50(pretrained=False)\n    net.fc = nn.Linear(net.fc.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ncheckpoint_paths = [\n#     Path('..\/input\/bridclef-resnest50-weight\/birdclef_resnest50_fold4_epoch_29_f1_val_07694_20210513205331.pth'),\n#     Path('..\/input\/bridclef-resnest50-weight\/birdclef_resnest50_fold1_epoch_18_f1_val_07636_20210512152028.pth'),\n#     Path('..\/input\/bridclef-resnest50-weight\/birdclef_resnest50_fold2_epoch_24_f1_val_07728_20210512202556.pth'),\n#     Path('..\/input\/bridclef-resnest50-weight\/birdclef_resnest50_fold3_epoch_28_f1_val_07609_20210513105835.pth'),\n    Path('..\/input\/kkiller-birdclef-models-public\/birdclef_resnest50_fold0_epoch_10_f1_val_06471_20210417161101.pth')\n]\n\n\nnets = [\n        load_net(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths\n]\n@torch.no_grad()\ndef get_thresh_preds(out, thresh=None):\n    thresh = thresh or THRESH\n    o = (-out).argsort(1)\n    npreds = (out > thresh).sum(1)\n    preds = []\n    for oo, npred in zip(o, npreds):\n        preds.append(oo[:npred].cpu().numpy().tolist())\n    return preds\ndef get_bird_names(preds):\n    bird_names = []\n    for pred in preds:\n        if not pred:\n            bird_names.append(\"nocall\")\n        else:\n            bird_names.append(\" \".join([INV_LABEL_IDS[bird_id] for bird_id in pred]))\n    return bird_names\ndef predict(nets, test_data, names=True):\n    preds = []\n    with torch.no_grad():\n        for idx in  tqdm(list(range(len(test_data)))):\n            xb = torch.from_numpy(test_data[idx]).to(DEVICE)\n            pred = 0.\n            for net in nets:\n                o = net(xb)\n                o = torch.sigmoid(o)\n\n                pred += o\n\n            pred \/= len(nets)\n            \n            if names:\n                pred = get_bird_names(get_thresh_preds(pred))\n\n            preds.append(pred)\n    return preds\npred_probas = predict(nets, test_data, names=False)\nprint(len(pred_probas))\npreds = [get_bird_names(get_thresh_preds(pred, thresh=THRESH)) for pred in pred_probas]\n# preds[:2]\ndef preds_as_df(data, preds):\n    sub = {\n        \"row_id\": [],\n        \"birds\": [],\n    }\n    \n    for row, pred in zip(data.itertuples(False), preds):\n        row_id = [f\"{row.id}_{row.site}_{5*i}\" for i in range(1, len(pred)+1)]\n        sub[\"birds\"] += pred\n        sub[\"row_id\"] += row_id\n        \n    sub = pd.DataFrame(sub)\n    \n    if SAMPLE_SUB_PATH:\n        sample_sub = pd.read_csv(SAMPLE_SUB_PATH, usecols=[\"row_id\"])\n        sub = sample_sub.merge(sub, on=\"row_id\", how=\"left\")\n        sub[\"birds\"] = sub[\"birds\"].fillna(\"nocall\")\n    return sub\nsub = preds_as_df(data, preds)\nprint(sub.shape)\nsub\nsub.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': 'a985dcaf465165'}"}
{"id":"117942","text":"\"\"\"\n# **Title: EDA for sales dataset for an Online store**\n\"\"\"\n\"\"\"\n> Welcome to this Exploratory Data Analysis (EDA) project, in which we will address a dataset that contains sales of an online store in the United States of America over the period from the beginning of January 2019 until the beginning of the same month of the following year 2020 across 8 US states [ CA ,NY ,TX ,MA ,GA ,WA ,OR ,ME ].\r\n\r\n*  During this trip, we will explore the information inside the file to determine the problems in it and certainly address them, to be 100% valid and clean for the beginning of collecting the necessary information, and then put it in a comprehensive conclusion for all the information that must be mentioned. I hope that the presentation will be organized and comfortable, and I will be very welcome for any opinions or modifications. Thank you very much.\n\"\"\"\n\"\"\"\n# **Stage 0: Exploring the given data**\n\"\"\"\n\"\"\"\n* **Import the required modules.**\n\"\"\"\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\n\"\"\"\n* **Import the dataset and start exploring.**\n\"\"\"\ndf = pd.read_csv('..\/input\/sales-data-set\/all_data.csv')\r\ndf\n\"\"\"\n* **Number of rows and columns in this dataset.**\n\"\"\"\ndf.shape\n\"\"\"\n* **Information about every column's data type.**\n\"\"\"\ndf.info()\n\"\"\"\n* **Columns names.**\n\"\"\"\ndf.columns\n\"\"\"\n* **Number of NaN values for each column.**\n\"\"\"\ndf.isnull().sum()\ndf.loc[df.duplicated()]\n\"\"\"\n* **List of unique values in `Product` column.**\n\"\"\"\ndf.Product.unique()\ndf.Product.value_counts()\n\"\"\"\n* **Generate descriptive statistics.**\n\"\"\"\ndf.describe()\n\"\"\"\n* **Number of unique values in each column.**\n\"\"\"\ndf.nunique()\n\"\"\"\n# **Stage 1: Assessing the data.**\n\"\"\"\n\"\"\"\n> **Content issues detected:**\n\"\"\"\n\"\"\"\n* **NaN Values** :\r\n  * There are 545 NaN values. These values sgould be removed to ensure that the dataset is completely clean.\r\n* **Data Entry errors** :\r\n  * in **`Product`** column, There are 355 values with the name 'Product' . This should be a *data entry error* from combining table in csv file manually.\r\n  * Another issue in the same column; there are some items duplicated in the same order for no reason. Maybe it's another software crash or data entry error, whatever.\r\n* **Duplicated values** :\r\n  * These duplicated values are Combination of NaN values and data entry errors.\n\"\"\"\n\"\"\"\n> **Data type issues detected:**\n\"\"\"\n\"\"\"\n* **`Quantity Ordered`** column :\r\n  * should be changed to integer to count the total number of each product.\r\n* **`Price Each`** column :\r\n  * should be changed to float to count the total sales for each product.\r\n* **`Order Date`** column:\r\n  * should be changed to datetime to do some calucaltions about the preffered time of day or month or year, time classification calculations at all.\r\n* New columns can be created:\r\n  * **`ZIP Code`** column:\r\n   * Contains a five-digit number extracted from `Purchase Address` column, represents the mail box for every area, and can be helpful when sending the product using postal address.\r\n  * **`State`** Column:\r\n   * to help in doing stats about sales in every state.\r\n  * **`Day of week`** Column: \r\n   * to help in doing stats about the preffered day of week for order decision.\r\n  * **`Hour of day`** Column:\r\n   * to give information about the most frequent time of day to make an order.\n\"\"\"\n\"\"\"\n> **I think it's all clear now about issues and how to fix it. One stage left before starting doing data science job; Cleaning the data.**\n\"\"\"\n\"\"\"\n# **Stage 2: Cleaning the data.**\n\"\"\"\n\"\"\"\n* **Taking a copy of the dataset to perform the cleaning process without changing the real data**\n\"\"\"\ndf_clean = df.copy()\r\ndf\n\"\"\"\n> ## **Fixing content issues:**\n\"\"\"\n\"\"\"\n> **Step 1: Removing data-entry-error values:**\n\"\"\"\ndf_clean.loc[df_clean.duplicated()].sort_values('Order Date',ascending = False)\n\"\"\"\n* **Displaying the Duplicated values together:**\n\"\"\"\n\"\"\"\n*Roughly speaking, these values \u200b\u200bare duplicated because the data entry specialist has stitched the sales tables together as new values \u200b\u200bwith new indexes, ignoring the row and column order.*\n\"\"\"\ndf_clean.loc[df_clean['Product']=='Product']\n\"\"\"\n* **Drop the previous values out of the dataset**\n\"\"\"\ndf_clean.drop(df_clean.index[df_clean['Product'] == 'Product'], inplace = True)\n\"\"\"\n* **Check if it's done or not.**\n\"\"\"\ndf_clean.loc[df_clean['Product']=='Product']\n\"\"\"\n*It seems like it's done, so we can jump into the next step!*\n\"\"\"\n\"\"\"\n> **Step 2: Removing NaN values:**\n\"\"\"\n\"\"\"\n* **Displaying NaN values together**\n\"\"\"\ndf_clean.loc[df_clean['Order ID'].isnull()]\n\"\"\"\n* **Deleting NaN values**\n\"\"\"\ndf_clean.dropna(inplace=True)\ndf_clean.loc[df_clean['Order ID'].isnull()]\n\"\"\"\n>  **Cool ; to the last step, before we start our EDA!!!**\n\"\"\"\n\"\"\"\n> **Step 3: Removing duplicated values.**\n\"\"\"\n\"\"\"\n* **Search for duplicated values:**\n\"\"\"\ndf_clean.groupby(['Order ID','Product'])['Order ID'].count().nlargest()\n\"\"\"\nAs an example, let's search with random `Order ID` value:\n\"\"\"\ndf_clean.loc[df_clean['Order ID']=='142071']\n\"\"\"\nThat's another big issue that makes the the data somekind missleading, so it's a must to drop these duplicated values.\n\"\"\"\ndf_clean.drop_duplicates(subset=['Order ID','Product'],keep='first',inplace=True)\ndf_clean.groupby(['Order ID','Product'])['Order ID'].count()\ndf_clean.loc[df_clean['Order ID']=='142071']\n\"\"\"\n> **Now, finally we can say: WE HAVE CLEAN DATA 100%, but one another issue still not fixed: changing data types in some columns,and creating new columns to make your EDA more easier.** \n\"\"\"\n\"\"\"\n> ## **fixing data type issues:**\n\"\"\"\ndf_clean.info()\n\"\"\"\n> **Step 1: changing some columns to the appropriate data type.**\n\"\"\"\ndf_clean['Order Date']=pd.to_datetime(df_clean['Order Date'],errors='coerce')\ndf_clean['Price Each']= pd.to_numeric(df_clean['Price Each'])\ndf_clean['Quantity Ordered']=df_clean['Quantity Ordered'].astype(int)\n\"\"\"\n> **Step 2: Creating new columns.**\n\"\"\"\n\"\"\"\n* **Creating `ZIP Code` column.**\n\"\"\"\ndf_clean['ZIP Code']=df_clean['Purchase Address'].str[-6:]\n\"\"\"\n* **Editing `Purchase Address` column.**\n\"\"\"\ndf_clean['Purchase Address']=df_clean['Purchase Address'].str[:-6]\n\"\"\"\n* **Creating `State` column.**\n\"\"\"\ndf_clean['State']=df_clean['Purchase Address'].str[-2:]\r\ndf_clean['State']=df_clean['State'].astype('category')\n\"\"\"\n* **Creating `Order Year` column.**\n\"\"\"\ndf_clean['Order Year']=df_clean['Order Date'].dt.year\r\ndf_clean['Order Year']=df_clean['Order Year'].astype('category')\n\"\"\"\n* **Creating `Order Month` column.**\n\"\"\"\ndf_clean['Order Month']=df_clean['Order Date'].dt.month\r\ndf_clean['Order Month']=df_clean['Order Month'].astype('category')\n\"\"\"\n* **Creating `Order Day of Week` column.**\n\"\"\"\ndf_clean['Order Day of Week']=df_clean['Order Date'].dt.dayofweek\n\"\"\"\n* **Creating `Order Hour of Day` column.**\n\"\"\"\ndf_clean['Order Hour of Day']=df_clean['Order Date'].dt.hour\r\ndf_clean['Order Hour of Day']=df_clean['Order Hour of Day'].astype(int)\n\"\"\"\n> **Display the dataset in its clean state.**\n\"\"\"\ndf_clean\n\"\"\"\n> **The dataset ordered by `Order Date`.**\n\"\"\"\ndf_clean = df_clean.sort_values('Order Date')\r\ndf_clean.reset_index(drop=True,inplace=True)\r\ndf_clean\n\"\"\"\n> For more accurate analysis, we need to drop the values with date: `2020-01-01` to have the data for a complete year.\n\"\"\"\ndf_clean.loc[df_clean['Order Year']==2020].count()[0]\ndf_clean.drop(df_clean.index[df_clean['Order Year'] ==2020], inplace = True)\ndf_clean\n\"\"\"\n> **Saving clean data**\n\"\"\"\ndf_clean.to_csv('online_store_clean.csv')\ndf_clean.info()\ndf_clean.duplicated().sum()\ndf_clean.isnull().sum()\ndf_clean.describe()\n\"\"\"\n# **Stage 3: Exploratory Data Analysis (EDA) and Data Visualization**\n\"\"\"\n\"\"\"\n## **Setting some parameters for a better data visualization**\n\"\"\"\nplt.style.use(['seaborn'])\r\nSMALL_SIZE = 14\r\nMEDIUM_SIZE = 16\r\nBIGGER_SIZE = 18\r\nplt.rc('font', size=SMALL_SIZE)          # controls default text sizes\r\nplt.rc('axes', titlesize=BIGGER_SIZE)     # fontsize of the axes title\r\nplt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels\r\nplt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels\r\nplt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels\r\nplt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize\r\nplt.rc('figure', titlesize=BIGGER_SIZE,figsize=(15,10))  # fontsize of the figure title and figure size\r\n\n\"\"\"\n## **Research Question 0: How many orders are made in 2019?**\n\"\"\"\ndf_clean['Order ID'].nunique()\n\"\"\"\n## **Research Question 1: How much was the total sales value during 2019?**\n\"\"\"\ndf_clean['Price Each'].sum().astype(int)\n\"\"\"\n## **Research Question 2: How much was the total sales for each month?**\n\"\"\"\ndf_clean.groupby(['Order Month'])['Price Each'].sum().astype(int)\ndf_clean.groupby(['Order Month'])['Price Each'].sum().astype(int).plot(kind='line',color = 'black',linestyle = '--',figsize = (15,7.5))\r\ndf_clean.groupby(['Order Month'])['Price Each'].sum().astype(int).plot(kind='bar')\r\nplt.xticks(np.arange(0,12,1),labels=['January','Febraury','March','April','May','June','July','August','September','October','November','December'],fontstyle = 'oblique')\r\nplt.xlabel('Months of the year')\r\nplt.ylabel('Number of Orders')\r\nplt.title('The Total Sales For Each Month In 2019')\r\nplt.show()\ndf_clean.groupby(['Order Month'])['Price Each'].sum().astype(int).plot(kind='pie',shadow=True,autopct='%.2f%%',figsize=(18,20))\r\nplt.title('The Total Sales For Each Month In 2019')\r\nplt.legend(title='Months', bbox_to_anchor=(1.05, 1), loc='upper left')\r\nplt.show()\n\"\"\"\n## **Research Question 3: How many pieces did the store sell during 2019?**\n\"\"\"\ndf_clean['Quantity Ordered'].sum()\n\"\"\"\n## **Research Question 4: What is the most requested item from the store?**\n\"\"\"\ndf_clean.groupby(['Product'])['Product'].count().nlargest(20)\ndf_clean.groupby('Product')['Product'].count().nlargest(20).plot(kind='bar',figsize=(15,7.5))\r\nplt.title('The most requested item in 2019')\r\nplt.ylabel('Number of Orders')\r\nplt.show()\ndf_clean.groupby('Product')['Product'].count().nlargest(20).plot(kind='pie',figsize=(18,20),shadow=True,autopct='%.2f%%')\r\nplt.title('The most requested item in 2019')\r\nplt.legend(title='Products', bbox_to_anchor=(1.15, 1), loc='upper left')\r\nplt.show()\n\"\"\"\n## **Research Question 5: How much did each item represent in total sales? And which piece was the highest share of sales?**\n\"\"\"\ndf_clean.groupby('Product')['Price Each'].sum().nlargest(20)\ndf_clean.groupby('Product')['Price Each'].sum().nlargest(20).plot(kind='bar',figsize = (15,7.5))\r\nplt.title('Total Sales For Each Product')\r\nplt.ylabel('Sales per Million')\r\nplt.show()\ndf_clean.groupby('Product')['Price Each'].sum().nlargest(20).plot(kind='pie',figsize = (18,20),shadow=True,autopct='%.2f%%')\r\nplt.title('Total Sales For Each Product')\r\nplt.ylabel('Sales per Million')\r\nplt.legend(title='Products', bbox_to_anchor=(1.05, 1), loc='upper left')\r\nplt.show()\n\"\"\"\n## **Research Question 6: How much was each state's share of the purchases?**\n\"\"\"\ndf_clean.groupby(['State'])['Price Each'].sum().astype(int).nlargest(10)\nplt.subplot(2, 2, 1)\ndf_clean.groupby(['State'])['Price Each'].sum().astype(int).nlargest(10).plot(kind='bar',figsize=(15,15))\nplt.subplot(2, 2, 2)\ndf_clean.groupby(['State'])['Price Each'].sum().astype(int).plot(kind='pie',figsize=(15,15),shadow=True,autopct='%.2f%%',explode = [0.1,0,0,0,0,0,0,0])\nplt.ylabel('Percentage For Each State')\nplt.title('Which state represents the highest precentage of purchases?',loc='center')\nplt.legend(title='States', bbox_to_anchor=(1.05, 1), loc='upper left')\nplt.show()\n\"\"\"\n## **Research Question 7: What are the details of the biggest order?**\n\"\"\"\ndf_clean['Order ID'].value_counts()\ndf_clean.loc[df_clean['Order ID']=='160873']\n\"\"\"\n## **Research Question 8: Where is the address where the biggest number of purchases have been delivered?**\n\"\"\"\ndf_clean.groupby(['Purchase Address'])['Purchase Address'].count().nlargest()\ndf_clean.loc[df_clean['Purchase Address']=='193 Forest St, San Francisco, CA'].sort_values('Purchase Address')\n\"\"\"\n## **Research Question 9: Which mailbox was the largest number of purchases sent to?**\n\"\"\"\ndf_clean.groupby(['ZIP Code'])['ZIP Code'].count().nlargest(10)\ndf_clean.groupby(['ZIP Code'])['ZIP Code'].count().plot(kind='pie',shadow=False,autopct='%.2f%%',explode = [0,0,0.15,0,0,0,0.15,0.15,0,0],figsize=(15,15))\r\nplt.title('Which Mailbox receives the most orders?')\r\nplt.legend(title='ZIP Codes', bbox_to_anchor=(1.1, 1), loc='upper left')\r\nplt.show()\n\"\"\"\n## **Research Question 10: What is the most popular day of the week on which products are purchased from the store?**\n\"\"\"\ndf_clean['Order Day of Week'].value_counts().nlargest(7)\ndf_clean['Order Day of Week'].value_counts(normalize=True).nlargest(7)*100\ndf_clean['Order Day of Week'].value_counts(sort=False).plot(kind='line')\r\nplt.xticks(np.arange(0,7,1),labels=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],fontstyle = 'oblique')\r\nplt.title('The popular day of week to make an order')\r\nplt.xlabel('Day of Week')\r\nplt.ylabel('Number of orders')\r\nplt.show()\n\"\"\"\n## **Research Question 11: What is the most popular time of the day on which products are purchased from the store?**\n\"\"\"\ndf_clean['Order Hour of Day'].value_counts(sort=False).plot(kind='bar')\r\ndf_clean['Order Hour of Day'].value_counts(sort=False).plot(kind='line',color = 'black',linestyle = '--')\r\nplt.xlabel('Hour')\r\nplt.ylabel('Number of Orders')\r\nplt.title(\"The most popular hour to make an order\")\r\nplt.show()\n\"\"\"\n## **Research Question 12: Which smart phone is the most popular to be ordered?**\n\"\"\"\ndf_clean.loc[df_clean.Product=='iPhone'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\ndf_clean.loc[df_clean.Product=='Google Phone'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\ndf_clean.loc[df_clean.Product=='Vareebadd Phone'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\nplt.xticks(np.arange(0,12,1),labels=['January','Febraury','March','April','May','June','July','August','September','October','November','December'],fontstyle = 'oblique')\r\nplt.legend(title = 'Smart Phones',labels=['iPhone','Google Phone','Vareebadd Phone'])\r\nplt.ylabel('Number of Orders')\r\nplt.show()\r\n\n\"\"\"\n## **Research Question 13: Which headphone is the most popular to be ordered?**\n\"\"\"\ndf_clean.loc[df_clean.Product=='Wired Headphones'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\ndf_clean.loc[df_clean.Product=='Bose SoundSport Headphones'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\ndf_clean.loc[df_clean.Product=='Apple Airpods Headphones'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\nplt.xticks(np.arange(0,12,1),labels=['January','Febraury','March','April','May','June','July','August','September','October','November','December'],fontstyle = 'oblique')\r\nplt.legend(title = 'Headphones',labels=['Wired Headphones','Bose SoundSport Headphones','Apple Airpods Headphones'])\r\nplt.ylabel('Number of Orders')\r\nplt.show()\n\"\"\"\n## **Research Question 14: Which laptop is the most popular to be ordered?**\n\"\"\"\ndf_clean.loc[df_clean.Product =='ThinkPad Laptop'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\ndf_clean.loc[df_clean.Product=='Macbook Pro Laptop'].groupby(['Order Month'])['Order ID'].count().plot(kind='line')\r\nplt.xticks(np.arange(0,12,1),labels=['January','Febraury','March','April','May','June','July','August','September','October','November','December'],fontstyle = 'oblique')\r\nplt.legend(title = 'Laptops',labels=['ThinkPad Laptop','Macbook Pro Laptop'])\r\nplt.ylabel('Number of Orders')\r\nplt.show()\r\n\n\"\"\"\n# **Stage 4: Results and Conclusion**\n\"\"\"\n\"\"\"\nIn conclusion, and after this long process, I came out with these observations:\r\n> * During the year 2019 : the store received **178,406** orders, during which **208,689** items were purchased, with a total sales estimated at approximately **$34 million**.\r\n> * The most sales for a single month were in **December**, at nearly **$4.5 million (about 13.4% of the total sales)**.\r\n> * The most requested item from the store was for **\"USB-C Charging Cable\"**, with about **21,900** pieces, and it was followed by a small difference, **\"Lightning Charging Cable\"**, with about **21,600** pieces.\r\n > * The highest share of sales profits was the **Macbook Pro Laptop** with about **$8 million (23.43% of the total sales)**, and the **iPhone** came in second place with about **$4.8 million (13.97% of the total sales)**.\r\n > * **California** topped the states in terms of sales, with sales accounting for **39.76% of total sales**, amounting to approximately **$13.6 million**.\r\n > * Products that were mailed to **California alone** via PO Boxes: *\"90001\"* and *\"94016\"* **(74,198 products)**, make up **37.43% of the products**.\r\n > * The most day of the week in which customers purchase products is **Tuesday (27,128 requests, or 14.61% of the total requests)**, but the percentages are very close among the rest of the week, as the lowest day in orders was on **Friday (26,211 requests, or 14.12% of the total requests)**.\r\n > * Throughout the day, the number of requests took a certain pattern, as it **decreased from midnight until four o\u2019clock in the morning**, from which it gradually increased until it **gradually stabilized with the noon hours** and **decreased again until three o\u2019clock in the afternoon**, from which **it rises again until it reaches its highest level at seven o\u2019clock at night** and then **gradually decreases Until midnight**.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd8fbfdb0a47126'}"}
{"id":"18408","text":"\"\"\"\n# Prior work\n\nThis section is the code from a [strong kernel made by yorko@](https:\/\/www.kaggle.com\/kashnitsky\/model-validation-in-a-competition).\nWe took it derectly to v6\/v7 outputs.\n\"\"\"\nimport os\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import hstack\nimport eli5\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import TimeSeriesSplit, cross_val_score, GridSearchCV\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.linear_model import LogisticRegression\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom IPython.display import display_html\ndef prepare_sparse_features(path_to_train, path_to_test, path_to_site_dict,\n                           vectorizer_params, after_load_fn=None):\n    times = ['time%s' % i for i in range(1, 11)]\n    train_df = pd.read_csv(path_to_train, index_col='session_id', parse_dates=times)\n    test_df = pd.read_csv(path_to_test, index_col='session_id', parse_dates=times)\n    train_df = train_df.sort_values(by='time1')\n    \n    if after_load_fn is not None:\n        train_df = after_load_fn(train_df)\n        test_df = after_load_fn(test_df)\n    \n    with open(path_to_site_dict, 'rb') as f:\n        site2id = pickle.load(f)\n    id2site = {v:k for (k, v) in site2id.items()}\n    id2site[0] = 'unknown'\n    \n    sites = ['site%s' % i for i in range(1, 11)]\n    train_sessions = train_df[sites].fillna(0).astype('int').apply(lambda row: ' '.join([id2site[i] for i in row]), axis=1).tolist()\n    test_sessions = test_df[sites].fillna(0).astype('int').apply(lambda row: ' '.join([id2site[i] for i in row]), axis=1).tolist()\n    vectorizer = TfidfVectorizer(**vectorizer_params)\n    X_train = vectorizer.fit_transform(train_sessions)\n    X_test = vectorizer.transform(test_sessions)\n    y_train = train_df['target'].astype('int').values\n    \n    train_times, test_times = train_df[times], test_df[times]\n    \n    return X_train, X_test, y_train, vectorizer, train_times, test_times\n\ndef add_time_features(times, X_sparse, add_hour=True):\n    hour = times['time1'].apply(lambda ts: ts.hour)\n    morning = ((hour >= 7) & (hour <= 11)).astype('int').values.reshape(-1, 1)\n    day = ((hour >= 12) & (hour <= 18)).astype('int').values.reshape(-1, 1)\n    evening = ((hour >= 19) & (hour <= 23)).astype('int').values.reshape(-1, 1)\n    night = ((hour >= 0) & (hour <=6)).astype('int').values.reshape(-1, 1)\n    \n    objects_to_hstack = [X_sparse, morning, day, evening, night]\n    feature_names = ['morning', 'day', 'evening', 'night']\n    \n    if add_hour:\n        # we'll do it right and scale hour dividing by 24\n        objects_to_hstack.append(hour.values.reshape(-1, 1) \/ 24)\n        feature_names.append('hour')\n        \n    X = hstack(objects_to_hstack)\n    return X, feature_names\n\ndef add_day_month(times, X_sparse):\n    day_of_week = times['time1'].apply(lambda t: t.weekday()).values.reshape(-1, 1)\n    month = times['time1'].apply(lambda t: t.month).values.reshape(-1, 1) \n    # linear trend: time in a form YYYYMM, we'll divide by 1e5 to scale this feature \n    year_month = times['time1'].apply(lambda t: 100 * t.year + t.month).values.reshape(-1, 1) \/ 1e5\n    \n    objects_to_hstack = [X_sparse, day_of_week, month, year_month]\n    feature_names = ['day_of_week', 'month', 'year_month']\n        \n    X = hstack(objects_to_hstack)\n    return X, feature_names\n\ndef pre_process():\n    X_train_with_times1, new_feat_names = add_time_features(train_times, X_train_sites)\n    X_test_with_times1, _ = add_time_features(test_times, X_test_sites)\n    X_train_with_times1.shape, X_test_with_times1.shape\n\n    X_train_with_times2, new_feat_names = add_time_features(train_times, X_train_sites, add_hour=False)\n    X_test_with_times2, _ = add_time_features(test_times, X_test_sites, add_hour=False)\n    \n    train_durations = (train_times.max(axis=1) - train_times.min(axis=1)).astype('timedelta64[ms]').astype(int)\n    test_durations = (test_times.max(axis=1) - test_times.min(axis=1)).astype('timedelta64[ms]').astype(int)\n\n    scaler = StandardScaler()\n    train_dur_scaled = scaler.fit_transform(train_durations.values.reshape(-1, 1))\n    test_dur_scaled = scaler.transform(test_durations.values.reshape(-1, 1))\n    \n    X_train_with_time_correct = hstack([X_train_with_times2, train_dur_scaled])\n    X_test_with_time_correct = hstack([X_test_with_times2, test_dur_scaled])\n    \n    X_train_final, more_feat_names = add_day_month(train_times, X_train_with_time_correct)\n    X_test_final, _ = add_day_month(test_times, X_test_with_time_correct)    \n    \n    feat_names = new_feat_names + ['sess_duration'] + more_feat_names\n    \n    return X_train_final, X_test_final, feat_names\n\n# A helper function for writing predictions to a file\ndef write_to_submission_file(predicted_labels, out_file,\n                             target='target', index_label=\"session_id\"):\n    predicted_df = pd.DataFrame(predicted_labels,\n                                index = np.arange(1, predicted_labels.shape[0] + 1),\n                                columns=[target])\n    predicted_df.to_csv(out_file, index_label=index_label)\n\n    \ndef train_and_predict(model, X_train, y_train, X_test, cv, site_feature_names, \n                      new_feature_names=None, scoring='roc_auc',\n                      top_n_features_to_show=30, submission_file_name='submission.csv'):\n    \n    \n    cv_scores = cross_val_score(model, X_train, y_train, cv=cv, \n                            scoring=scoring, n_jobs=4)\n    print('CV scores', cv_scores)\n    print('CV mean: {}, CV std: {}'.format(cv_scores.mean(), cv_scores.std()))\n    model.fit(X_train, y_train)\n    \n    if new_feature_names:\n        all_feature_names = site_feature_names + new_feature_names \n    else: \n        all_feature_names = site_feature_names\n    \n    display_html(eli5.show_weights(estimator=model, \n                  feature_names=all_feature_names, top=top_n_features_to_show))\n    \n    if new_feature_names:\n        print('New feature weights:')\n    \n        print(pd.DataFrame({'feature': new_feature_names, \n                        'coef': model.coef_.flatten()[-len(new_feature_names):]}))\n    \n    test_pred = model.predict_proba(X_test)[:, 1]\n    write_to_submission_file(test_pred, submission_file_name) \n    \n    return cv_scores\n\n# A helper function for writing predictions to a file\ndef write_to_submission_file(predicted_labels, out_file,\n                             target='target', index_label=\"session_id\"):\n    predicted_df = pd.DataFrame(predicted_labels,\n                                index = np.arange(1, predicted_labels.shape[0] + 1),\n                                columns=[target])\n    predicted_df.to_csv(out_file, index_label=index_label)\n\n    \ndef train_and_predict(model, X_train, y_train, X_test, cv, site_feature_names, \n                      new_feature_names=None, scoring='roc_auc', show_eli=False,\n                      top_n_features_to_show=30, submission_file_name='submission.csv'):\n    \n    \n    cv_scores = cross_val_score(model, X_train, y_train, cv=cv, \n                            scoring=scoring, n_jobs=4)\n    print('CV scores', cv_scores)\n    print('CV mean: {}, CV std: {}'.format(cv_scores.mean(), cv_scores.std()))\n    model.fit(X_train, y_train)\n    \n    if new_feature_names:\n        all_feature_names = site_feature_names + new_feature_names \n    else: \n        all_feature_names = site_feature_names\n\n    if show_eli:\n        display_html(eli5.show_weights(estimator=model, \n                      feature_names=all_feature_names, top=top_n_features_to_show))\n    \n    if new_feature_names:\n        print('New feature weights:')\n    \n        print(pd.DataFrame({'feature': new_feature_names, \n                        'coef': model.coef_.flatten()[-len(new_feature_names):]}))\n    \n    test_pred = model.predict_proba(X_test)[:, 1]\n    write_to_submission_file(test_pred, submission_file_name) \n    \n    return cv_scores    \nPATH_TO_DATA = '..\/input\/'\nSEED = 17\ntime_split = TimeSeriesSplit(n_splits=10)\nlogit = LogisticRegression(C=1, random_state=SEED, solver='liblinear')\n%%time\nX_train_sites, X_test_sites, y_train, vectorizer, train_times, test_times = prepare_sparse_features(\n    path_to_train=os.path.join(PATH_TO_DATA, 'train_sessions.csv'),\n    path_to_test=os.path.join(PATH_TO_DATA, 'test_sessions.csv'),\n    path_to_site_dict=os.path.join(PATH_TO_DATA, 'site_dic.pkl'),\n    vectorizer_params={'ngram_range': (1, 5), \n                       'max_features': 50000,\n                       'tokenizer': lambda s: s.split()}\n)\n\nX_train_final, X_test_final, new_feat_names = pre_process()\n\"\"\"\n### Submission 6: local 0.913373+-0.0650 | 0.95062 pub\n\"\"\"\ncv_scores6 = train_and_predict(model=logit, X_train=X_train_final, y_train=y_train,\n                               X_test=X_test_final, cv=time_split,\n                               site_feature_names=vectorizer.get_feature_names(),\n                               new_feature_names=new_feat_names,\n                               submission_file_name='subm6.csv')\n\"\"\"\n### Submission 7: local 0.9164614+-0.0641 | 0.95055 pub\n\"\"\"\nc_values = np.logspace(-2, 2, 20)\nlogit_grid_searcher = GridSearchCV(estimator=logit, param_grid={'C': c_values}, scoring='roc_auc', n_jobs=4, cv=time_split, verbose=1)\n%%time\nlogit_grid_searcher.fit(X_train_final, y_train);\nlogit_grid_searcher.best_score_, logit_grid_searcher.best_params_\nfinal_model = logit_grid_searcher.best_estimator_\ncv_scores7 = train_and_predict(model=final_model, X_train=X_train_final, y_train=y_train, \n                               X_test=X_test_final, \n                               site_feature_names=vectorizer.get_feature_names(),\n                               new_feature_names=new_feat_names,\n                               cv=time_split, submission_file_name='subm7.csv')\ncv_scores7 > cv_scores6\n\"\"\"\n# Fixing Cross-Validation\n\"\"\"\n\"\"\"\nAs we seen in prior work, tuning hyper-parameters helped only in 6 folds out of 10 and our public score dropped from 0.95062 to 0.95055 after hyper-parameters tuning. Before we'll start fixing things, let's look at the dates in the dataset.\n\"\"\"\nimport re\nimport pickle\n\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nsns.set()\n\nPATH = Path('..\/input\/')\n\ntimes = ['time%s' % i for i in range(1, 11)]\n\ndef plot_series(df, field, label, **kwargs):\n    df = df.copy()\n    df['date'] = pd.DatetimeIndex(df[field]).normalize()\n    df = (df['date'].value_counts()\/len(df)).sort_index().resample('1D').interpolate()\n    df.plot(label=label, **kwargs)\n    \ndf_train = pd.read_csv(PATH\/'train_sessions.csv', index_col='session_id', parse_dates=times)\ndf_test = pd.read_csv(PATH\/'test_sessions.csv', index_col='session_id', parse_dates=times)\nfig , (ax1,ax2) = plt.subplots(2,1,figsize = (16, 12 )) \nfig.suptitle('Year-Month Distributions', fontsize=16)\nsns.countplot((df_train.time1.dt.year * 100 + df_train.time1.dt.month).apply(str), ax=ax1)\nax1.set_title(\"Train distribution\") \nsns.countplot((df_test.time1.dt.year * 100 + df_test.time1.dt.month).apply(str), ax=ax2)\nax2.set_title(\"Test distribution\");\nplot_series(df_train, 'time1', 'train-all', figsize=(24, 8))\nplot_series(df_train[df_train['target']==1], 'time1', 'train-alice')\nplot_series(df_test, 'time1', 'test')\nplt.legend();\n\"\"\"\n![image.png](attachment:image.png)\n\nThere are few patterns here:\n\n* Jan-Nov 2013 has data in the 12th day of each month and nothing else in the days 1-12.\n* Jan-Dec 2014 has data in the days 1-5 of each month and nothing else in the days 1-12.\n* Nov-Dec 2013 has some data in days 12+\n* Jan-May 2014 has some data in days 12+\n\nWhat is so special about number 12? Looks like the dataset has parsing error: we have dates in two formats: YYYY-MM-DD and YYYY-DD-MM.\n\"\"\"\n\"\"\"\n### Let's try to fix it\n\"\"\"\ndef fix_incorrect_date_formats(df, columns_to_fix):\n    for time in columns_to_fix:\n        d = df[time]\n        d_fix = d[d.dt.day <= 12]\n        d_fix = pd.to_datetime(d_fix.apply(str), format='%Y-%d-%m %H:%M:%S')\n        df.loc[d_fix.index.values, time] = d_fix\n    return df\ndf_train_fixed = fix_incorrect_date_formats(df_train, times)\ndf_test_fixed = fix_incorrect_date_formats(df_test, times)\nplot_series(df_train_fixed, 'time1', 'train-all', figsize=(24, 8))\nplot_series(df_train_fixed[df_train_fixed['target']==1], 'time1', 'train-alice')\nplot_series(df_test_fixed, 'time1', 'test')\nplt.legend();\nfig , (ax1,ax2) = plt.subplots(1,2,figsize = ( 15 , 6 )) \nfig.suptitle('Year-Month Distributions', fontsize=16)\nsns.countplot((df_train_fixed.time1.dt.year * 100 + df_train_fixed.time1.dt.month).apply(str), ax=ax1)\nax1.set_title(\"Train distribution\") \nsns.countplot((df_test_fixed.time1.dt.year * 100 + df_test_fixed.time1.dt.month).apply(str), ax=ax2)\nax2.set_title(\"Test distribution\");\n\"\"\"\nNow, after the fix is applied, the data has nice distributions across the different months and all the spikes and gaps are gone. Bonus: there is a nice overlap between train and test datasets.\n\nAfter this transformation, you can use ```TimeSeriesSplit``` or ```StratifiedKFold```: both CV schemas should give a good correlation between local CV scores and the public leaderbords scores. And you can use CV to perform hyper-parameters tuning.\n\"\"\"\n\"\"\"\n# Testing the Same Models After the Dates Fix\n\"\"\"\n%%time\nX_train_sites, X_test_sites, y_train, vectorizer, train_times, test_times = prepare_sparse_features(\n    after_load_fn=(lambda df: fix_incorrect_date_formats(df, times)), # Applying fix\n    path_to_train=os.path.join(PATH_TO_DATA, 'train_sessions.csv'),\n    path_to_test=os.path.join(PATH_TO_DATA, 'test_sessions.csv'),\n    path_to_site_dict=os.path.join(PATH_TO_DATA, 'site_dic.pkl'),\n    vectorizer_params={'ngram_range': (1, 5), \n                       'max_features': 50000,\n                       'tokenizer': lambda s: s.split()}\n)\n\nX_train_final, X_test_final, new_feat_names = pre_process()\n\"\"\"\n### Submission 8: local 0.9052172+-0.102551 | 0.94843 pub\n\"\"\"\ntime_split = TimeSeriesSplit(n_splits=10)\nlogit = LogisticRegression(C=1, random_state=SEED, solver='liblinear')\ncv_scores8 = train_and_predict(model=logit, X_train=X_train_final, y_train=y_train,\n                               X_test=X_test_final, cv=time_split,\n                               site_feature_names=vectorizer.get_feature_names(),\n                               new_feature_names=new_feat_names,\n                               submission_file_name='subm8.csv')\n\"\"\"\nUnfortunately, the change dropped the score. But before we discard it as bad, let's check if hyper-parameters tuning will work.\n\"\"\"\n\"\"\"\n### Submission 9: local 0.9099734+-0.09774 | 0.94922 pub\n\"\"\"\nc_values = np.logspace(-2, 2, 20)\nlogit_grid_searcher = GridSearchCV(estimator=logit, param_grid={'C': c_values}, scoring='roc_auc', n_jobs=4, cv=time_split, verbose=1)\n%%time\nlogit_grid_searcher.fit(X_train_final, y_train);\nlogit_grid_searcher.best_score_, logit_grid_searcher.best_params_\nfinal_model = logit_grid_searcher.best_estimator_\ncv_scores9 = train_and_predict(model=final_model, X_train=X_train_final, y_train=y_train, \n                               X_test=X_test_final, \n                               site_feature_names=vectorizer.get_feature_names(),\n                               new_feature_names=new_feat_names,\n                               cv=time_split, submission_file_name='subm9.csv')\ncv_scores9 > cv_scores8\n\"\"\"\nWe got a good boost here. The hyper-parameters tuning works now and local CV correlates with public leaderbord. Now, because we can trust our validation schema, it is possible to assess quality of submissions without submits to public leaderbord.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '21a3a05b578766'}"}
{"id":"10356","text":"\"\"\"\n![https:\/\/www.googleapis.com\/download\/storage\/v1\/b\/kaggle-user-content\/o\/inbox%2F3244747%2Fdf2bd9836c198215ed033d0678a02ef2%2Fheader.png?generation=1604778403014926&alt=media](https:\/\/www.googleapis.com\/download\/storage\/v1\/b\/kaggle-user-content\/o\/inbox%2F3244747%2Fdf2bd9836c198215ed033d0678a02ef2%2Fheader.png?generation=1604778403014926&alt=media)\n\"\"\"\n!pip install --upgrade plotly-geo\n!pip install --upgrade geopandas\n!pip install --upgrade pyshp\n!pip install --upgrade shapely\n# 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)\nimport plotly.figure_factory as ff\nimport plotly.express as px\nimport time\nfrom datetime import datetime\n\"\"\"\n## US Voting Results\n\"\"\"\ndatafile = pd.read_csv('..\/input\/us-election-2020\/president_state.csv')\nstate_codes = pd.read_csv('..\/input\/coordinates\/world_country_and_usa_states_latitude_and_longitude_values.csv')\ndatafile = datafile.merge(state_codes, left_on='state', right_on='usa_state')\nfig = px.choropleth(datafile, locations='usa_state_code', color=\"total_votes\",\n                           range_color=(0, 10000000),\n                           locationmode = 'USA-states',  \n                           scope=\"usa\",\n                           title='USA Presidential Votes Counts' \n                          )\nfig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.show()\n\"\"\"\n## 2020 USA Election: Vote Percentages by State\n\"\"\"\n#referennce : https:\/\/www.kaggle.com\/paultimothymooney\/2020-usa-election-vote-percentages-by-state\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndf_president_county = pd.read_csv('\/kaggle\/input\/us-election-2020\/president_county_candidate.csv')\ndf_president_county = df_president_county[df_president_county.party.isin(['DEM','REP'])]\ndf_president_county = df_president_county.groupby(['state','party'])[\"total_votes\"].sum()\ndf_president_county = df_president_county.reset_index()\n\nstate_codes = pd.read_csv('\/kaggle\/input\/coordinates\/world_country_and_usa_states_latitude_and_longitude_values.csv')\nstate_codes = state_codes[['usa_state','usa_state_code']]\ndf_president_county = df_president_county.merge(state_codes, left_on='state', right_on='usa_state')\ndf_president_county = df_president_county.drop(['usa_state'], axis=1)\ndf_president_county_dummy = pd.get_dummies(df_president_county['party'])\ndf_president_county = df_president_county.join(df_president_county_dummy)\ndf_president_county['DEM_votes'] = df_president_county['DEM'] * df_president_county['total_votes'] \ndf_president_county['REP_votes'] = df_president_county['REP'] * df_president_county['total_votes'] \ndf_president_county = df_president_county.groupby(['state','usa_state_code'])[\"DEM_votes\",\"REP_votes\"].sum()\ndf_president_county = df_president_county.reset_index()\ndf_president_county['percent_democrat'] = df_president_county['DEM_votes']*100\/(df_president_county['REP_votes']+df_president_county['DEM_votes'])\nfig = px.choropleth(df_president_county, \n                    locations=\"usa_state_code\", \n                    color = \"percent_democrat\",\n                    locationmode = 'USA-states', \n                    hover_name=\"state\",\n                    range_color=[25,75],\n                    color_continuous_scale = 'RdBu',#blues\n                    scope=\"usa\",\n                    title='2020 USA Election: Percent of Population Voting for the Democratic Party')\nfig.show()\n\"\"\"\n## Governor's County Results\n\"\"\"\nflips_main = pd.read_csv('..\/input\/flips-for-maps\/Flip_v2.csv')\nflips = flips_main[['State','County Full Name','FIPS Full County']]\nflips.columns = ['state','county','Flips']\nflips.head(2)\nflips.info()\ngov_county = pd.read_csv('..\/input\/us-election-2020\/governors_county.csv')\ngov_county.head(2)\n\"\"\"\n## Delaware\n\"\"\"\nDelaware_County = gov_county[gov_county['state'] == 'Delaware']\nDelaware_Flips = flips[flips['state']=='Delaware']\nDelaware_County = Delaware_County.merge(Delaware_Flips, on='county', how='left')\nDelaware_County = Delaware_County.drop(['state_y'],axis=1)\nDelaware_County.head(2)\ncounty = Delaware_County['county'].tolist()\nvalues = Delaware_County['current_votes'].tolist()\nfips = Delaware_County['Flips'].tolist()\n\nendpts = list(np.mgrid[min(values):max(values):4j])\n\nfig = ff.create_choropleth(\n    fips=fips, values=values, scope=['Delaware'], show_state_data=True,\n    binning_endpoints=endpts, round_legend_values=True,\n    plot_bgcolor='rgb(229,229,229)',\n    paper_bgcolor='rgb(229,229,229)',\n    legend_title='Total Votes by County',\n    show_hover=True,\n    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n    exponent_format=True,\n    title='Delaware'\n)\nfig.update_layout(height=400, width=750, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.layout.template = None\nfig.show()\n\"\"\"\n## Indiana\n\"\"\"\nIndiana_County = gov_county[gov_county['state'] == 'Indiana']\nIndiana_Flips = flips[flips['state']=='Indiana']\nIndiana_Flips.info()\nIndiana_County = Indiana_County.merge(Indiana_Flips, on='county', how='left')\nIndiana_County = Indiana_County.drop(['state_y'],axis=1)\nIndiana_County.head(2)\ncounty = Indiana_County['county'].tolist()\nvalues = Indiana_County['current_votes'].tolist()\nfips = Indiana_County['Flips'].tolist()\n\nendpts = list(np.mgrid[min(values):max(values):4j])\n\nfig = ff.create_choropleth(\n    fips=fips, values=values, scope=['Indiana'], show_state_data=True,\n    binning_endpoints=endpts, round_legend_values=True,\n    plot_bgcolor='rgb(229,229,229)',\n    paper_bgcolor='rgb(229,229,229)',\n    legend_title='Total Votes by County',\n    show_hover=True,\n    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n    exponent_format=True,\n    title='Indiana'\n)\nfig.update_layout(height=400, width=750, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.layout.template = None\nfig.show()\n\"\"\"\n## Missouri\n\"\"\"\nMissouri_County = gov_county[gov_county['state'] == 'Missouri']\nMissouri_Flips = flips[flips['state']=='Missouri']\nMissouri_County = Missouri_County.merge(Missouri_Flips, on='county', how='left')\nMissouri_County = Missouri_County.drop(['state_y'],axis=1)\nMissouri_County.head(2)\ncounty = Missouri_County['county'].tolist()\nvalues = Missouri_County['current_votes'].tolist()\nfips = Missouri_County['Flips'].tolist()\n\nendpts = list(np.mgrid[min(values):max(values):4j])\n\nfig = ff.create_choropleth(\n    fips=fips, values=values, scope=['Missouri'], show_state_data=True,\n    binning_endpoints=endpts, round_legend_values=True,\n    plot_bgcolor='rgb(229,229,229)',\n    paper_bgcolor='rgb(229,229,229)',\n    legend_title='Total Votes by County',\n    show_hover=True,\n    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n    exponent_format=True,\n    title='Missouri'\n)\nfig.update_layout(height=400, width=750, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.layout.template = None\nfig.show()\n\"\"\"\n## Montana\n\"\"\"\nMontana_County = gov_county[gov_county['state'] == 'Montana']\nMontana_Flips = flips[flips['state']=='Montana']\nMontana_County = Montana_County.merge(Montana_Flips, on='county', how='left')\nMontana_County = Montana_County.drop(['state_y'],axis=1)\nMontana_County.head(2)\ncounty = Montana_County['county'].tolist()\nvalues = Montana_County['current_votes'].tolist()\nfips = Montana_County['Flips'].tolist()\n\nendpts = list(np.mgrid[min(values):max(values):4j])\n\nfig = ff.create_choropleth(\n    fips=fips, values=values, scope=['Montana','North Dakota'], show_state_data=True,\n    binning_endpoints=endpts, round_legend_values=True,\n    plot_bgcolor='rgb(229,229,229)',\n    paper_bgcolor='rgb(229,229,229)',\n    legend_title='Total Votes by County',\n    show_hover=True,\n    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},\n    exponent_format=False,\n    title='Montana'\n)\nfig.update_layout(height=400, width=750, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.layout.template = None\nfig.show()\n\"\"\"\n## Come back for more updates!!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '12ffa6f48fd24d'}"}
{"id":"132723","text":"# 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))\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline\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\nimport tensorflow as tf\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.applications import *\nfrom tensorflow.keras.preprocessing.image import *\nfrom tensorflow.keras.utils import plot_model\n!pip install livelossplot\nfrom livelossplot import PlotLossesKeras\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras import backend as K\nimport os\nfrom PIL import Image\nimport cv2\nfrom collections import Counter\n!pip install imutils\nfrom imutils import *\nfrom scipy.spatial.distance import cosine, euclidean\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n!pip install plotly\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport plotly as ply\nfrom sklearn.metrics import *\nply.offline.init_notebook_mode(connected=True)\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n%matplotlib inline\nVAL_LOC = \"..\/input\/mias-classes-gdf\/MIAS_Data\/Val\"\nTRAIN_LOC = \"..\/input\/mias-classes-gdf\/MIAS_Data\/Train\"\nTEST_LOC = \"..\/input\/mias-classes-gdf\/MIAS_Data\/Test\"\ntrain_data = TRAIN_LOC\nval_data = VAL_LOC\nmasked_data = TEST_LOC\ntrain_names = []; val_names = []; masked_names = []\ntrain_names_count = []; val_names_count = []; masked_names_count = []\n\nfor class_ in sorted(os.listdir(train_data)):\n    train_names.append(class_)\n    train_names_count.append(len(os.listdir(os.path.join(train_data, class_))))\n\nfor class_ in sorted(os.listdir(val_data)):\n    val_names.append(class_)\n    val_names_count.append(len(os.listdir(os.path.join(val_data, class_))))\n\nfor class_ in sorted(os.listdir(masked_data)):\n    masked_names.append(class_)\n    masked_names_count.append(len(os.listdir(os.path.join(masked_data, class_))))\nfig = make_subplots(rows=1, cols=3)\nfig.add_trace(go.Bar(name='training', x=train_names, y=train_names_count), row = 1, col = 1)\nfig.add_trace(go.Bar(name='validation', x=val_names, y=val_names_count), row = 1, col = 2)\nfig.add_trace(go.Bar(name='testing', x=masked_names, y=masked_names_count), row = 1, col = 3)\n\nfig.update_layout(title_text=\"Data\", title_x = 0.5)\nfig.show()\nnum_classes=3\ndef list_of_shapes(img_location, name):\n    shapes = []\n    for img in os.listdir(os.path.join(img_location, name)):\n        img_arr = cv2.imread(os.path.join(img_location, name, img))\n        shapes.append(img_arr.shape)\n    \n    return shapes\nG_train_shapes = list_of_shapes(train_data, \"G\")\nD_train_shapes = list_of_shapes(train_data, \"D\")\nF_train_shapes = list_of_shapes(train_data, \"F\")\n\n\nG_val_shapes = list_of_shapes(val_data, \"G\")\nD_val_shapes = list_of_shapes(val_data, \"D\")\nF_val_shapes = list_of_shapes(val_data, \"F\")\n\n\nshapes = G_train_shapes + D_train_shapes + G_val_shapes + D_val_shapes + F_train_shapes + F_val_shapes \nwidths = [shape[1] for shape in shapes]\nheights = [shape[0] for shape in shapes]\nIMG_SHAPE = (224,224,3)\ndef euclidean_distance(vectors):\n\t# unpack the vectors into separate lists\n\t(featsA, featsB) = vectors\n\n\t# compute the sum of squared distances between the vectors\n\tsumSquared = K.sum(K.square(featsA - featsB), axis=1,\n\t\tkeepdims=True)\n\n\t# return the euclidean distance between the vectors\n\treturn K.sqrt(K.maximum(sumSquared, K.epsilon()))\ndef make_pairs(images, labels):\n\t# initialize two empty lists to hold the (image, image) pairs and\n\t# labels to indicate if a pair is positive or negative\n\tpairImages = []\n\tpairLabels = []\n\n\t# calculate the total number of classes present in the dataset\n\t# and then build a list of indexes for each class label that\n\t# provides the indexes for all examples with a given label\n\tnumClasses = len(np.unique(labels))\n \n\tidx = [np.where(labels == i)[0] for i in range(0,3)]\n\n\t# loop over all images\n\tfor idxA in range(len(images)):\n\t\t# grab the current image and label belonging to the current\n\t\t# iteration\n\t\tcurrentImage = images[idxA]\n\t\tlabel = labels[idxA]\n\n\t\t# randomly pick an image that belongs to the *same* class\n\t\t# label\n\t\tidxB = np.random.choice(idx[label])\n\t\tposImage = images[idxB]\n\n\t\t# prepare a positive pair and update the images and labels\n\t\t# lists, respectively\n\t\tpairImages.append([currentImage, posImage])\n\t\tpairLabels.append([1])\n\n\t\t# grab the indices for each of the class labels *not* equal to\n\t\t# the current label and randomly pick an image corresponding\n\t\t# to a label *not* equal to the current label\n\t\tnegIdx = np.where(labels != label)[0]\n\t\tnegImage = images[np.random.choice(negIdx)]\n\n\t\t# prepare a negative pair of images and update our lists\n\t\tpairImages.append([currentImage, negImage])\n\t\tpairLabels.append([0])\n\n\t# return a 2-tuple of our image pairs and labels\n\treturn (np.array(pairImages), np.array(pairLabels))\ndef load_data(img_location, name):\n    imgs = []\n    labels = []\n    for img in os.listdir(os.path.join(img_location, name)):\n        img_arr = cv2.imread(os.path.join(img_location, name, img))\n        img_arr = cv2.resize(img_arr, (IMG_SHAPE[1], IMG_SHAPE[0]))\n        labels.append(name)\n        imgs.append(img_arr)\n    \n    return imgs, labels    \nG_train_imgs, G_train_labels = load_data(train_data,\"G\")\nD_train_imgs, D_train_labels = load_data(train_data,\"D\")\nG_val_imgs, G_val_labels = load_data(val_data,\"G\")\nD_val_imgs, D_val_labels = load_data(val_data,\"D\")\nF_train_imgs, F_train_labels = load_data(train_data,\"F\")\nF_val_imgs, F_val_labels = load_data(val_data,\"F\")\n\ntrain_imgs = G_train_imgs + D_train_imgs + F_train_imgs \ntrain_labels = G_train_labels + D_train_labels + F_train_labels \n\nval_imgs = G_val_imgs + D_val_imgs +F_val_imgs \nval_labels = G_val_labels + D_val_labels +F_val_labels \ntrain_imgs = np.array(train_imgs)\nval_imgs = np.array(val_imgs)\n\ntrain_imgs.shape, val_imgs.shape\nfig=plt.figure(figsize=(15,15))\ncolumns = 2\nrows = 2\nfor i in range(1, columns*rows +1):\n    img = np.random.randint(10)\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(train_imgs[i])\nplt.show()\nfig=plt.figure(figsize=(15,15))\ncolumns = 2\nrows = 2\nfor i in range(1, columns*rows +1):\n    img = np.random.randint(10)\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(val_imgs[i])\nplt.show()\nfrom collections import Counter\nprint(Counter(train_labels))\nprint(Counter(val_labels))\ntrain_enc_labels = []; val_enc_labels = []\n\nencoding = dict({\"G\" : 0, \"D\" : 1, \"F\" : 2 })\nfor label in train_labels:\n    train_enc_labels.append(encoding[label])\n\nfor label in val_labels:\n    val_enc_labels.append(encoding[label])\n\ntrain_enc_labels = np.array(train_enc_labels, \"int\")\nval_enc_labels = np.array(val_enc_labels, \"int\")\nprint(f\"train_imgs shape : {train_imgs.shape}\")\nprint(f\"val_imgs shape : {val_imgs.shape}\")\nprint(f\"train_enc_labels shape : {train_enc_labels.shape}\")\nprint(f\"val_enc_labels shape : {val_enc_labels.shape}\")\ntrain_pairs, train_pair_labels = make_pairs(train_imgs, train_enc_labels)\nval_pairs, val_pair_labels = make_pairs(val_imgs, val_enc_labels)\nprint(f\"train_pairs shape : {train_pairs.shape}\")\nprint(f\"val_pairs shape : {val_pairs.shape}\")\nprint(f\"train_pair_labels shape : {train_pair_labels.shape}\")\nprint(f\"val_pair_labels shape : {val_pair_labels.shape}\")\n\nimages = []\nfor i in np.random.choice(np.arange(0, len(train_pairs)), size=(49,)):\n\t# grab the current image pair and label\n\timageA = train_pairs[i][0]\n\timageB = train_pairs[i][1]\n\tlabel = train_pair_labels[i]\n\t# to make it easier to visualize the pairs and their positive or\n\t# negative annotations, we're going to \"pad\" the pair with two\n\t# pixels along the top, bottom, and right borders, respectively\n\toutput = np.zeros((300, 600, 3), dtype=\"uint8\")\n\tpair = np.hstack([imageA, imageB])\n\toutput[2:226, 2:450,:] = pair\n\t# set the text label for the pair along with what color we are\n\t# going to draw the pair in (green for a \"positive\" pair and\n\t# red for a \"negative\" pair)\n\ttext = \"neg\" if label[0] == 0 else \"pos\"\n\tcolor = (225, 0, 0) if label[0] == 0 else (0, 255, 0)\n\t# create a 3-channel RGB image from the grayscale pair, resize\n\t# it from 60x36 to 96x51 (so we can better see it), and then\n\t# draw what type of pair it is on the image\n\tvis = cv2.merge([output])\n\tvis = cv2.resize(vis, (96, 51), interpolation=cv2.INTER_LINEAR)\n\tcv2.putText(vis, text, (20, 12), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2)\n\t# add the pair visualization to our list of output images\n\timages.append(vis)\n# construct the montage for the images\nmontage = build_montages(images, (96, 51), (7, 7))[0]\n# show the output montage\nplt.figure(figsize=(20, 20))\nplt.xticks([])\nplt.yticks([])\nprint(\"The images pairs will not appear if we have normalized the image data\")\nplt.imshow(montage);\nplt.imsave(\"Montage.jpeg\", montage)\ndef build_siamese_model(inputShape, embeddingDim=48):\n\t# specify the inputs for the feature extractor network\n\tinputs = Input(inputShape)\n\n\t# define the first set of CONV => RELU => POOL => DROPOUT layers\n\tx = Conv2D(64, (2, 2), padding=\"same\", activation=\"relu\")(inputs)\n\tx = MaxPooling2D(pool_size=(2, 2))(x)\n\tx = Dropout(0.3)(x)\n\n\t# second set of CONV => RELU => POOL => DROPOUT layers\n\tx = Conv2D(64, (2, 2), padding=\"same\", activation=\"relu\")(x)\n\tx = MaxPooling2D(pool_size=2)(x)\n\tx = Dropout(0.3)(x)\n\n\t# prepare the final outputs\n\tpooledOutput = GlobalAveragePooling2D()(x)\n\toutputs = Dense(embeddingDim, name=\"Emdedding\")(pooledOutput)\n\n\t# build the model\n\tmodel = Model(inputs, outputs)\n\n\t# return the model to the calling function\n\treturn model\n# configure the siamese network\nimgA = Input(shape=IMG_SHAPE)\nimgB = Input(shape=IMG_SHAPE)\nfeatureExtractor = build_siamese_model(IMG_SHAPE, 128)\nfeatsA = featureExtractor(imgA)\nfeatsB = featureExtractor(imgB)\n\n# finally, construct the siamese network\ndistance = Lambda(euclidean_distance, name=\"Euclidean_distance\")([featsA, featsB])\noutputs = Dense(1, activation=\"sigmoid\", name=\"similarity\")(distance)\nmodel = Model(inputs=[imgA, imgB], outputs=outputs, name=\"SiameseNetwork\")\n\n\n# compile the model\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\",\tmetrics=[\"accuracy\"])\nplot_model(featureExtractor, to_file='featureExtractor.png', show_shapes=True, show_layer_names=True)\nplot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)\nfeatureExtractor.summary()\nmodel.summary()\nEPOCHS = 100\nc1= PlotLossesKeras()\nc2=EarlyStopping(monitor=\"val_loss\",\n    min_delta=0,\n    patience=0,\n    verbose=0,\n    mode=\"auto\",\n    baseline=None,\n    restore_best_weights=False)\n\nprint(train_pairs[:, 0].shape)\nprint(train_pair_labels[:].shape)\nx_train = np.array([train_pairs[:, 0], train_pairs[:, 1]])\ny_train = train_pair_labels[:]\nx_val = np.array([val_pairs[:, 0], val_pairs[:, 1]])\ny_val = val_pair_labels[:]\n\nprint(f\"x_train shape : {x_train.shape}\")\nprint(f\"y_train shape : {y_train.shape}\")\nprint(f\"x_val shape : {x_val.shape}\")\nprint(f\"y_val shape : {y_val.shape}\")\nBATCH_SIZE = 32; EPOCHS = 100\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\ntrain_history = model.fit([train_pairs[:, 0], train_pairs[:, 1]], train_pair_labels[:],\n                          batch_size = BATCH_SIZE,callbacks=[c1],\n                          epochs = EPOCHS)\nmodel.evaluate( [val_pairs[:, 0], val_pairs[:, 1]], val_pair_labels[:])\n\"\"\"\nMy colab Notebook\nhttps:\/\/colab.research.google.com\/drive\/1Jp1ODGrGIb6B-9OLGdBejzUGWMpMaeYT#scrollTo=xymXaSbHBFZ3\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f423039bc2744d'}"}
{"id":"122548","text":"\"\"\"\n# Exploring the twitterverse for feelings on NPIs in response to COVID-19 in Canada\n\n# Introduction\n\n**Question:** How is twitter responding to NPIs?\n\n**Motivation:** To understand the public\u2019s response to non-pharmaceutical interventions (NPIs) across Canada, we may be able to leverage sentiment analysis of social media platforms. Which interventions were positively or negatively recieved?\n\n**Solution:** A very casual, exploratory sentiment analysis of tweets by intervention categories.\n\n**Take-aways:**\n1. A dataset of tweets related to the interventions in the CAN-NPI dataset\n2. Investigation on how sentiment analyses can go wrong\n3. A first-go at a workflow to roughly understand how people feel about interventions.\n\nI am no expert, so would love to get some feedback and any expertise, expecially regarding improvement of the sentiment analyses, pulling tweets, and data visualization :) \n\n\n# Method\n\n## Data\n\nI use the CAN-NPI dataset (`covid19-challenges\/npi_canada.csv`), and use any tweets that contained any of the `source_urls` from this dataset which were pulled using [twint](https:\/\/github.com\/twintproject\/twint).\n\n\n## Overview\n0. **Set up:** Load packages, import modules, download data.\n1. **Data Preprocessing:** Clean the tweets\n2. **Data Analysis:** Comparison of sentiment analysis on text-only and a custom sentiment analysis that incorporates the sentiment of emojis.\n3. **Visualization:** Plot the proportion of positive, negative, and neutral tweets of intervention categories with \"sufficient\" tweet coverage.\n\"\"\"\n\"\"\"\n## Set Up\n\"\"\"\n# download necessary packages\n!pip install langdetect\n!pip install emoji\n# load modules\nimport pandas as pd\nfrom datetime import datetime, date, timedelta\nimport numpy as np\nimport re\nimport os\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport nltk \nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport gensim\nfrom sklearn.model_selection import cross_val_score, StratifiedShuffleSplit,train_test_split, GroupShuffleSplit\nfrom langdetect import detect\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom textblob import TextBlob\n\n\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n# load CAN-NPI dataset\nnpis_csv = \"\/kaggle\/input\/covid19-challenges\/npi_canada.csv\"\nraw_data = pd.read_csv(npis_csv,encoding = \"ISO-8859-1\")\n# remove any rows that don't have a start_date, region, or intervention_category\ndf = raw_data.dropna(how='any', subset=['start_date', 'region', 'intervention_category'])\ndf['region'] = df['region'].replace('Newfoundland', 'Newfoundland and Labrador')\nnum_rows_removed = len(raw_data)-len(df)\nprint(\"Number of rows removed: {}\".format(num_rows_removed))\n\n# get all regions\nregions = list(set(df.region.values))\nprint(\"Number of unique regions: {}\".format(len(regions)))\n\n# get all intervention categories\nnum_cats = list(set(df.intervention_category.values))\nnum_interventions = len(num_cats)\nprint(\"Number of unique intervention categories: {}\".format(len(num_cats)))\n\n# get earliest start date and latest start date\ndf['start_date'] = pd.to_datetime(df['start_date'], format='%Y-%m-%d')\nearliest_start_date = df['start_date'].min()\nlatest_start_date = df['start_date'].max()\nnum_days = latest_start_date - earliest_start_date\nprint(\"Analyzing from {} to {} ({} days)\".format(earliest_start_date.date(), latest_start_date.date(), num_days))\nprint(\"DONE READING DATA\")\n# load tweets\nmerged_tweets_csv = '\/kaggle\/input\/npi-twitterverse-april-30\/tweets_to_intervention_category.source_urls.tsv'\ncolnames = [\"npi_record_id\", \"intervention_category\", \"oxford_government_response_category\", \"source_url\", \"id\", \"conversation_id\", \"created_at\", \"date\", \"time\", \"timezone\", \"user_id\", \"username\", \"name\", \"place\", \"tweet\", \"mentions\", \"urls\", \"photos\", \"replies_count\", \"retweets_count\", \"likes_count\", \"hashtags\", \"cashtags\", \"link\", \"retweet\", \"quote_url\", \"video\", \"near\", \"geo\", \"source\", \"user_rt_id\", \"user_rt\", \"retweet_id\", \"reply_to\", \"retweet_date\", \"translate\", \"trans_src\", \"trans_dest\"]\ntweets_df = pd.read_csv(merged_tweets_csv, encoding = \"utf-8\", error_bad_lines=False, engine='python', names=colnames)\n# drop any rows without tweets - aka any interventions supported by non-tweeted media urls\ntweets_df = tweets_df.dropna(how='any', subset=['npi_record_id', 'intervention_category', 'tweet'])\n\n# only get english tweets\ndata = []\nfor index, row in tweets_df.iterrows():\n    # detect only english tweets\n    tweet = row['tweet'].strip()\n    if tweet != \"\":\n        language =\"\"\n        try:\n            language = detect(tweet)\n        except:\n            language = \"error\"\n        if language == \"en\":\n            data.append([row['intervention_category'], tweet])\ntweets_df_en = pd.DataFrame(data, columns=[\"intervention_category\", \"tweet\"])\nprint(\"Number of non-english tweets = {}\".format(len(tweets_df) - len(tweets_df_en)))\nprint(\"Number of tweets collected = {}\".format(len(tweets_df_en)))\n\"\"\"\n## Data Preprocessing\n\nI performed some standard text preprocessing on the tweets. I masked any URLs, usernames, and removed any hashtags or non-alpabetical characters. Any words with repeated characters were shortened (for ex. \"hellooooooo\"-->\"hello\").\n\nSome non-standard practices I used, included removal of words that highly influenced the sentiment analysis but I found did not make much sense in this context. For example, words that such as \"first\", \"positive\", or \"confirmed\", seemed to drive the polarity scores positively. This makes sense intuitively in other contexts. However, in the CAN-NPI dataset, this unfairly skewed the sentiments of tweets related to \"First death announcements\" or \"General case announcements\".\n\n### Examples of the pitfalls when using off-the-shelf sentiment analyses in NPI sentiment analyses\n\"\"\"\n# Here's a few examples of First death announcements\nex1 = \"Here's a wrap of the latest coronavirus news in Canada: 77 cases, one death, an outbreak in a B.C. nursing home and Ottawa asks provinces about their critical supply gaps.  https:\/\/www.theglobeandmail.com\/canada\/article-bc-records-canadas-first-coronavirus-death\/\"\nex2 = \"B.C. records Canada\u2019s first coronavirus death  http:\/\/dlvr.it\/RRZPGL  pic.twitter.com\/pn8T4yumQJ\"\nprint(\"Example 1 = {}\".format(ex1))\nprint(\"Example 2 = {}\".format(ex2))\n\"\"\"\nThese are just announcements, pretty neutral but the scores are the following:\n\"\"\"\nex1_tb = TextBlob(ex1)\nex1_ss = ex1_tb.sentiment[0]\nprint(\"Example 1 has score={}\".format(ex1_ss))\nex2_tb = TextBlob(ex2)\nex2_ss = ex2_tb.sentiment[0]\nprint(\"Example 2 has score={}\".format(ex2_ss))\n\"\"\"\nWords like \"first\" in other contexts is pretty positive, but not in this case. What is the effect of removing this word on the sentiment score?\n\"\"\"\nex = \"first coronavirus death\"\nex_tb = TextBlob(ex)\nex_ss = ex_tb.sentiment[0]\nprint(\"{} with score={}\".format(ex, ex_ss))\n\nex = \"coronavirus death\"\nex_tb = TextBlob(ex)\nex_ss = ex_tb.sentiment[0]\nprint(\"{} with score={}\".format(ex, ex_ss))\n\"\"\"\nIt got more positive with the word \"first\". Moving forward, I remove other words that show that same pattern such as \"confirm\", and \"positive\".\n\"\"\"\nimport re \nimport nltk\nnltk.download('punkt')\n\ndef tweet_preprocess(text):\n  '''Return tokenized text with \n  rsemoved URLs, usernames, hashtags, weird characters, repeated\n  characters, stop words, and numbers\n  '''\n  text = text.lower()\n  text = re.sub('((www\\.[^\\s]+)|(https?:\/\/[^\\s]+))', 'URL', text) # remove URLs\n  text = re.sub(r'@[A-Za-z0-9]+','USER',text) # removes any usernames in tweets\n  text = re.sub(r'#([^\\s]+)', r'\\1', text) # remove the # in #hashtag\n  text = re.sub('[^a-zA-Z0-9-*. ]', ' ', text) # remove any remaining weird characters\n  words = word_tokenize(text)  # remove repeated characters (helloooooooo into hello)\n  ignore = set(stopwords.words('english'))\n  more_ignore = {'at', 'and', 'also', 'or', \"http\", \"ca\", \"www\", \"https\", \"com\", \"twitter\", \"html\", \"news\", \"link\", \\\n                 \"positive\", \"first\", \"First\", \"confirmed\", \"confirm\", \"confirms\"}\n  ignore.update(more_ignore)\n  #porter = PorterStemmer()\n  #cleaned_words_tokens = [porter.stem(w) for w in words if w not in ignore]\n  cleaned_words_tokens = [w for w in words if w not in ignore]\n  cleaned_words_tokens = [w for w in cleaned_words_tokens if w.isalpha()]\n\n  return cleaned_words_tokens\n\"\"\"\n## Data analysis\n\n### Sentiment analysis (text-based only)\n\"\"\"\ndef run_sentiment_analysis(tweets_df):\n  tweets_df[\"sentiment\"] = 0\n  for index, row in tweets_df.iterrows():\n    tokens = tweet_preprocess(row['tweet'])\n    clean_text = ' '.join(tokens)\n    analysis = TextBlob(row['tweet'])\n    analysis_after_clean = TextBlob(clean_text)\n\n    print(\"{}: {} \\n before cleaning score={}, after cleaning score={}\".format(row['intervention_category'], row['tweet'], analysis.sentiment[0], analysis_after_clean.sentiment[0]))\n\n    if analysis.sentiment[0]>0:\n      print('Positive')\n    elif analysis.sentiment[0]<0:\n      print('Negative')\n    else:\n      print('Neutral')\n    print(\"======================================\")\nrun_sentiment_analysis(tweets_df_en[:5])\n\"\"\"\n### Sentiment analysis (text+emoji)\n\nI found that some tweets that were clearly positive, were not being scored as such. \n\nFor example, this Public Announcement: \n> \"THANK YOU Government of #Canada ! \u2764\u2764\u2764\u2764\u2764\u2764 Government of #Canada evacuating Canadians on board #DiamondPrincess cruise ship   https:\/\/bit.ly\/2UVjHgx  #outbreak #COVID19 #SARSCoV2 #Coronavirus #nCoV2019 #COVID\u30fc1\"\n\nHad a polarity score of 0.0. However, it's hard to argue that it's a neutral tweet.\n\nI wondered if there was a way to better account for the use of emojis. Previous work, seemed to show that incorporating emojis significantly improves polarity scores and often \"dominate[s] the sentiment conveyed by textual cues and forms a good proxy for the polarity of text\" [(Hogenboom et al., 2015)](https:\/\/personal.eur.nl\/frasincar\/papers\/JWE2015\/jwe2015.pdf). I introduce a *very rough* modified sentiment score using the emoji sentiment mapping and scoring scheme from [Novak et al., 2015](https:\/\/journals.plos.org\/plosone\/article?id=10.1371\/journal.pone.0144296#pone.0144296.ref006). Here, they give a sentiment score for each emoji.\n\nDue to the lack of availability of labeled tweets, emojis are sometimes used to \"distantly\" label the sentiment of tweets [(Felbo et al., 2017)](https:\/\/arxiv.org\/pdf\/1708.00524.pdf). Given that previous work actually use the emojis as labels and often dominate the sentiment, I use a rule-based method, where emojis with a \"high\" score either negative or positive determine the overall sentiment of the tweet. For cases, where there are multiple emojis, I average the sentiment scores. While the emoji sentiment mappings provided previously are fairly comprehensive, in some cases, the emojis are not found in their set. In these cases, I do not take these emojis into account when averaging their scores.\n\nIf no emojis exist, I use the sentiment analysis on the preprocessed tweets. After manual inspection, I found that sometimes the sentiment scores did not make sense again. I determine a very strict threshold based on a subset of tweets, only classifying a tweet as positive if the sentiment scores are greater than 0.25 and negative if less than -0.25.\n\"\"\"\n# download sentiment map\n!wget https:\/\/www.clarin.si\/repository\/xmlui\/bitstream\/handle\/11356\/1048\/Emoji_Sentiment_Data_v1.0.csv\nimport emoji\n\n# get emoji sentiment map\nemoji_sent_csv = \"Emoji_Sentiment_Data_v1.0.csv\"\nemoji_data = pd.read_csv(emoji_sent_csv,encoding = \"ISO-8859-1\")\n\ndef extract_emojis(str):\n  return ''.join(c for c in str if c in emoji.UNICODE_EMOJI)\n\ndef calc_emoji_sent(e):\n    e_uc = '0x{:X}'.format(ord(e)).lower()\n    #print(e_uc)\n    count_pos =0\n    count_neg =0\n    count_neutral = 0\n    sr = emoji_data.loc[emoji_data[\"Unicode codepoint\"] == e_uc.lower()]\n    score = -100\n    if not sr.empty:\n        oc = int(sr[\"Occurrences\"].astype(int))\n        num_pos = int(sr[\"Positive\"].astype(int))\n        num_neut = int(sr[\"Neutral\"].astype(int))\n        num_neg = int(sr[\"Negative\"].astype(int))\n        score = 1*num_pos\/oc + -1*num_neg\/oc + 0*num_neut\/oc\n    #print(\"{} with score={}\".format(e, score))\n    return score\n\ndef run_sentiment_analysis_mod(tweets_df):\n  tweets_df[\"sentiment_score\"] = 0.0\n  tweets_df[\"sentiment_class\"] = \"\"\n\n  for index, row in tweets_df.iterrows():\n    tokens = tweet_preprocess(row['tweet'])\n    clean_text = ' '.join(tokens)\n    analysis = TextBlob(row['tweet'])\n    analysis_after_clean = TextBlob(clean_text)\n    c_score = analysis_after_clean.sentiment[0]\n    \n    # add emojis in sentiment analysis\n    emojis_detected = extract_emojis(row['tweet'])\n    avg_emoji_sent_score = 0\n    emoji_counts = 0\n    if emojis_detected:\n        for e in emojis_detected:\n            em_sent_score = calc_emoji_sent(e)\n            if em_sent_score == -100:\n              continue\n            avg_emoji_sent_score += em_sent_score\n            emoji_counts += 1\n        if emoji_counts > 0:\n            avg_emoji_sent_score = avg_emoji_sent_score\/emoji_counts\n        #print(avg_emoji_sent_score)\n\n\n    # final score calculations\n    score = 0.0\n    label = \"NEUTRAL\"\n    if avg_emoji_sent_score > 0.10:\n        score = avg_emoji_sent_score\n        label = \"POSITIVE\"\n    elif avg_emoji_sent_score < -0.10:\n        score = avg_emoji_sent_score\n        label = \"NEGATIVE\"\n    else:\n        score = analysis_after_clean.sentiment[0]\n        if score > 0.25:\n          label = \"POSITIVE\"\n        elif score < -0.25:\n          label = \"NEGATIVE\"\n    tweets_df.at[index, \"sentiment_score\"] = score\n    tweets_df.at[index, \"sentiment_class\"] = label \n    '''print(\"=============================\")\n    print(row[\"intervention_category\"] + \"\\n\")\n    print(row['tweet'])\n    print(clean_text)\n    print(\"Score (no clean) = {}\".format(analysis.sentiment[0]))\n    print(\"Score (clean) = {}\".format(c_score))\n    print(\"Final Score = {}\".format(score))\n    print(label)'''\n  return tweets_df\n\nmod_tweets_df = run_sentiment_analysis_mod(tweets_df)\n\"\"\"\n## Results (Preliminary)\n\nLet's see the proportion of sentiment classes by intervention category for intervention categories with at least 50 tweets. \n\"\"\"\nimport plotly.graph_objects as go\nimport plotly\n\ndef split_data_by_class(tweets_df):\n    total_tweets_by_cat = tweets_df.groupby('intervention_category')[\"id\"].count().reset_index(name=\"count\").sort_values(\"intervention_category\", ascending=False)\n    counts = tweets_df.groupby(['intervention_category',\"sentiment_class\"])[\"id\"].count().reset_index(name=\"count\").sort_values(\"intervention_category\", ascending=False)\n    counts[\"proportion\"] = 0.0\n    for index, row in counts.iterrows():\n        total_tweets = int(total_tweets_by_cat.loc[total_tweets_by_cat[\"intervention_category\"] == row[\"intervention_category\"]][\"count\"].astype(int))\n        counts.at[index, \"proportion\"] = row[\"count\"]\/total_tweets\n\n    y = counts[\"intervention_category\"].unique().tolist()\n\n    # fill gaps - some sentiment_class + intervention_category combinations are empty\n    # and it messes up my graphs :(\n    fill_data = []\n    for ic in y:\n      for sc in [\"POSITIVE\", \"NEUTRAL\", \"NEGATIVE\"]:\n        subset = counts[(counts.sentiment_class == sc) & (counts.intervention_category == ic)]\n        if subset.empty:\n          fill_data.append([ic, sc, 0, 0.0])\n    fill_data_df = pd.DataFrame(fill_data, columns=[\"intervention_category\", \"sentiment_class\", \"count\", \"proportion\"])\n    full_counts = counts.append(fill_data_df).sort_values(\"intervention_category\", ascending=False)\n\n    return full_counts, y\n\ndef plot(full_counts, y, measure):\n    # only plot intervention_category if it had \"sufficient\" number of tweets\n    THRESH = 50\n    total_tweets_by_cat = tweets_df.groupby('intervention_category')[\"id\"].count().reset_index(name=\"count\").sort_values(\"intervention_category\", ascending=False)\n    if measure == \"proportion\":\n      # find all intervention_category with enough tweets\n      y = total_tweets_by_cat[total_tweets_by_cat[\"count\"] > THRESH][\"intervention_category\"].unique().tolist()\n      full_counts = full_counts[full_counts.intervention_category.isin(y)]\n\n    # split up by sentiment_class\n    pos_counts = full_counts.loc[full_counts[\"sentiment_class\"] == \"POSITIVE\"]\n    neg_counts = full_counts.loc[full_counts[\"sentiment_class\"] == \"NEGATIVE\"]\n    neut_counts = full_counts.loc[full_counts[\"sentiment_class\"] == \"NEUTRAL\"]\n    print(\"Mean {} for positive class: {}\".format(measure, round(pos_counts[measure].mean(),2)))\n    print(\"Mean {} for negative class: {}\".format(measure, round(neg_counts[measure].mean(),2)))\n    print(\"Range {} for positive class: {}-{}\".format(measure, round(pos_counts[measure].min(),2), round(pos_counts[measure].max(),2)))\n    print(\"Range {}  for negative class: {}-{}\".format(measure, round(neg_counts[measure].min(),2), round(neg_counts[measure].max(),2)))\n    \n    fig = go.Figure()\n    fig.add_trace(go.Bar(\n        y=y,\n        x=pos_counts[measure],\n        name='Positive',\n        orientation='h',\n        marker=dict(\n            color='rgba(90, 191,165, 1.0)',\n            line=dict(color='rgba(255, 255, 255, 1.0)', width=1)\n        )\n    ))\n    fig.add_trace(go.Bar(\n        y=y,\n        x=neg_counts[measure],\n        name='Negative',\n        orientation='h',\n        marker=dict(\n            color='rgba(230, 130, 130, 1.0)',\n            line=dict(color='rgba(255, 255, 255, 1.0)', width=1)\n        )\n    ))\n    fig.add_trace(go.Bar(\n        y=y,\n        x=neut_counts[measure],\n        name='Neutral',\n        orientation='h',\n        marker=dict(\n            color='rgba(190, 203, 200, 1.0)',\n            line=dict(color='rgba(255, 255, 255, 1.0)', width=1)\n        )\n    ))\n\n\n    fig.update_layout(width=800, height=1200,barmode='stack', \n                      template='plotly_white',\n                      bargap=0.5, # gap between bars of adjacent location coordinates.\n                      #bargroupgap=0.5 # gap between bars of the same location coordinate.\n                     )\n    fig.show()\n    #plotly.offline.iplot(fig, filename='fig.png')\n\nfull_counts, y = split_data_by_class(mod_tweets_df)\nplot(full_counts,y, \"proportion\")\nplot(full_counts,y, \"count\")\n\"\"\"\n### Main points\n\n* Majority of tweets are neutral\n* When not neutral, for the most part twitter is responding pretty positively to the NPIs, with a mean proportion of 0.17.\n* There was an order of magnitute difference in the number of tweets related to school closure with >20K tweets. The next closest intervention category was Emergency economic funding with 2650 tweets.\n\"\"\"\n\"\"\"\n# Discussion\n\nThis work is in development still but it's interesting to see the pitfalls of sentiment analyses especially in the context of NPIs in response to COVID-19. \n\n## Future work\n* Pull tweets from the Oxford Government Response Tracker, and see how the feelings differ in different regions.\n* Sentiment analysis over time\n* Sentiment analysis by region\n* Use Twitter API to pull more tweets and replies. Tweepy is limited in the replies it pulls. I expect that most of the tweets here will be neutral as they are often coming from government officials or websites distributing news. I could possibly gain more of the public's perspective if I catch more replies.\n* Evaluating how the different preprocessing steps influence sentiment\n* Possibly develop a sentiment classifier. Off-the-shelf classfiers such as TextBlob do not seem to perform as well in cases such as described above with any general case announcements or first death announcements where words like \"positive\", \"confirmed\", and \"first\" are likely positive in sentiment in other contexts but not in the context of NPIs and COVID.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e155773026187b'}"}
{"id":"9274","text":"# 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 in \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 \"..\/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))\nprint(len(filenames))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n**Import Packages and Libraries**\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torchvision\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom torchvision import transforms\n\"\"\"\n**CSV Files Pasing and Visualisation-**\n\"\"\"\nfile_path1 ='..\/input\/test.csv'\nfile_path2 ='..\/input\/train.csv'\nfile_path3 ='..\/input\/sample_submission.csv'\ntest = pd.read_csv(file_path1)\ntrain = pd.read_csv(file_path2)\nsample_submission=pd.read_csv(file_path3)\nprint(train.shape[0], test.shape[0]) \ntest.head()\ntrain.head()\nsample_submission.head()\n\"\"\"\n**Data Visualisation**\n\"\"\"\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nwith open('\/kaggle\/input\/test_images\/b16787f65d49.png', 'rb') as file:\n    img=Image.open(file)\n    plt.axis('off')\n    plt.imshow(img)\n    #print(img.size)\n\n#print(img.format)\n\"\"\"\n**Dataset Class**\n\"\"\"\nclass ImageDataset(Dataset):\n    def __init__(self, csv_file, root_dir, transform = None, train = True):\n        self.label_frame = pd.read_csv(csv_file)\n        self.root_dir = root_dir\n        self.transform = transform\n        self.train = train\n        \n    def __len__(self):\n        return len(self.label_frame)\n    \n    def __getitem__(self, indx):\n        img_name = os.path.join(self.root_dir, self.label_frame.iloc[indx, 0] + '.png')\n        img = Image.open(img_name)\n        if self.transform:\n            img = self.transform(img)\n            \n        if self.train == True:\n            label = self.label_frame.iloc[indx, 1]\n            label = np.array([label])\n            return img, label\n        else:\n            return img, img_name           \n            \n\"\"\"\n**Data Preprocessing and Loading**\n\"\"\"\ntransform = transforms.Compose([transforms.Resize((224, 224)),\n                                transforms.Grayscale(3),\n                                transforms.ToTensor(), \n                                transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])                                               \ntrain_data = ImageDataset(\"..\/input\/train.csv\", \"..\/input\/train_images\", transform = transform, train = True)\ntest_data = ImageDataset(\"..\/input\/test.csv\", \"..\/input\/test_images\", transform = transform, train = False)\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=False)\nlen(train_loader), len(test_loader)\nfor data in train_loader:\n    img, lab = data\n    print(lab[0].shape)\n    print(img[0].shape)\n    break\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.models as models\nfrom tqdm import tqdm_notebook\nmodel = models.resnet18(pretrained=True)\nfor param in model.parameters():\n    param.requires_grad = False\nmodel.fc = nn.Linear(512, 5)\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available else 'cpu')\nmodel.to(device)\nloss_fn = nn.CrossEntropyLoss()\nopt = optim.Adam(model.parameters())\nprint(lab[0].shape)\nprint(lab[9,:])\nfor i in tqdm_notebook(range(5)):\n    for data in tqdm_notebook(train_loader):\n        image, label = data\n        label = label.squeeze(1)\n        image, label = image.to(device), label.to(device)\n        \n        opt.zero_grad()\n        out = model(image)\n        loss = loss_fn(out, label)\n        loss.backward()\n        opt.step()\n        torch.save(model.state_dict(), \"best_model.pth\")\n        del image, label, out\n        torch.cuda.empty_cache()\n        \n        \nmodel.load_state_dict(torch.load(\"best_model.pth\"))\nmodel.to(device)\nmodel.eval()\n\noutputs = []\nfor test_img, test_filename in tqdm_notebook(test_loader):\n        test_img = test_img.to(device)\n        output = model(test_img)\n        num, ind = torch.max(output, 1)\n        output =  ind.squeeze().cpu().numpy()\n        outputs.extend(output)\n\nsubmission = test\nsubmission['diagnosis'] = outputs\nsubmission.head()\nsubmission.to_csv( 'submission.csv')","meta":"{'source': 'AI4Code', 'id': '11218e0a463a91'}"}
{"id":"119795","text":"\"\"\"\n![123](data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wCEAAkGBxITERUTExIWFhUXGSAbGRgWGRggHRweGBkbHxkaHR8YHSsiGxslHx8fITEjJSkrLi8uGiAzODMuNygtLisBCgoKDg0OGxAQGy0lICYtLy0tKy0yMC8tNS8tLi0tLS0tLy0tLS0tLS0tLy0tLS0tLS0tLS0tLy4tLS0uLS81Lf\/AABEIAKIBNwMBIgACEQEDEQH\/xAAcAAEAAgMBAQEAAAAAAAAAAAAABQYBBAcDAgj\/xABFEAACAQMDAgUBBgIHBQcFAQABAhEAAyEEEjEFQQYTIlFhMgcUQnGBkSOhUlNik7HR0xZygvDxFSQzc5LB4TSjsrPCF\/\/EABoBAQADAQEBAAAAAAAAAAAAAAABAgMEBQb\/xAAuEQACAgEEAQMCBgEFAAAAAAAAAQIRAwQSITFRE0FhgcEiMnGRobEFFCNS0fD\/2gAMAwEAAhEDEQA\/AOJ0pXRPs90hv6LWWksadtQHsixcvWbJCG5cIfc91SPV6UVTJLMNo5I7pOlZBzuldkfovTTrNZZ3W9NeW3btpd1FgeQL+5mv7UuAWxKbFSRxuZZ5PovTdPo7zWupaLTGz92th7tm2m1mu6hkOotsFDIQrruURG2VEbZz9X4BxeldR6n4NewbOja2ly2b9y4LyWrfmXdNbt27gi4q7pMsvP1ECYivXrPhWxb6\/owtlfumrZLi2ysKARFy2V+DmO24DtRZEDlNK7Pd8Dae42tuae0htai2Bp9wxZv+eLV23P4drmZj6WxxWrc+x+2GUHVXEAuC073LSqGNz0o1qHO5Tc2pBg+qfzlZUDkVK6RpvsubytLdvXzbV0uPqfSCbC27bOnf1blHeI+a8eu+ALOm0Q1Q1F26AEZmt2g1phcjcEdGbYVnm4FBOBzU+pEHPaV76nZuPl7inbeADxmYMc14VcgUpSgFKUoBSlKAUpSgM0pU50fw5d1CblZVkkKDPqK88Ax\/z7VKVlJ5Iwjuk6RBVmvS\/ZZGKsIYGCD2IryqC6d8o+qt\/hPoNi9ZZ7pyW2j1ER6eRByxnEyBtyMwahVm8FaqbhsMSA\/qUgTBVTODg+nOe6irQq+Tl1u\/0W4OmuePBX9bpzbuMhyVJH7V4VI+IEK6q8Cu0i43p9s4H6cVJeHfC7am29zftAJA9MzCkycyATCggHM+1RTbpF3nhDGpzdLj+St19AV937RRip5Bg\/pUj4ZUHVW5EwSQCYllUlBPb1AUrmjWU0oOfhWaOo0jpG9GXdxuBE\/v\/wA5Fa9Xrxzfs+SiKsOW3fTtMeoSB+FTIx\/Z+IFGpJU6MtNmeXHvaoxSlKg3FKUoBSlKAUpSgFWp\/HOp+4HQJbsW7B2k+WjBpR1YNu3EliVEk1VaVDSfYLd1fx\/qdVa8rUWtPdBCbmNsh3NsEIxZWBDDc2Vj6iODFauq8X3rlprL27LIbS2VEXP4du2QUVIfsw3EtJJ5JGKrdKjYiSyf7Y6g6IaO4tu7aVSiG4G3orMj7VZWB2hkQgGfpA4EV76bx3qEtaW2tqxGkbdZYq5ZSTLZL5DHkccQBAiqUpsiCzdO8ca2za1Fq24C6i55jYyrzO9DPpMge\/0ivTqHjrVXQPRp7beYt17lmyiPcuI25XuMBk7vViMk1VaU2R8Atut+0HXXfvYZ1jWKq3QFwAi7QEz6ZXB95r41\/jrVXbD2SthfNVVu3Usot26qcB3HPA7DiqrSmyPgClKVYgUpSgFKUoBSlKAUpSgFXLwb10IvksQJbBJgEHlJjGRiceo5BAmm1kUTadoxz4I5obJFk8aaZhdVyPqWDMzjgmQO0Af7tSPS\/Ctq5pg7PBZS2\/MLjAgdhIk\/mPy9+j6q3q9IbF361H1ASQROy5k55gx7H+kKjuha27p7v3a6OD6QZGYO0Aggw04+SPc1pxd+zPNc83pPHF1KD\/deUVjU2Sjsh5UkH8wYNSnhN41lk\/2iP3Uj9ea2fGPSjaveYpLW7hLK3ycsD3BzOexFRnQzGps\/+Yvv7ieKp0zvco5cDa90\/wCje8Y241bkRDBWBHB3KOPfOP0qc8KaoppGcgkWyxEd42tE9jJP\/q+Kh\/FalnS5IIYEY\/stn4\/EIiQRBkzNS\/Q7W3pt\/wB3Vm\/IKQuPg7T+wq8fzM481PTQjLyl9imai6XYseWMn9asPgjQF7xucC2MGY9RB\/8A5DH8wB3qtRVz6YBY0peTPlNcgTG522Kfg5XH5ngZpHu2dWsbWLZHuXCK94h1fm6i40kjdCkmcLgfvz+tRprb6bpfNurbkLuOWPYASx+YAJjvVo694csWtM1xSAUgTuJLNuIII4yIMgAY\/dTdsl5seDbifbpL+il1mkVePDvhi09qbizdaIViygbgSo9JBziSfcwMSUU26RfPqIYI7plHrFSHWdOlu+6p9IOMz2EjPsZH+daFDaMlKKkvcxSlKgkUpSgFKUoBSlWXpPgTqWps+dZ0lx7Z4b0ruHuodgWHyAahtLsFapUr0vw9q9RfOns6e495Z3JtgrGDv3QEg49UZxW11Dwfr7F+3YvaZ0uXTttglYckxtVwdpPGJ7j3FN6BAUqSv9D1Can7o1phqNwTy8TuaNo5jMjMxmtrWeFNbaS9cuWGVNOwW60p6GbbtBhszvXieabkSQdKtNr7POqNbW4ujuMjKGBBQyCJBADTxVb1Fh0Yo6sjqYZWBBBHIIOQaKSfRB5UqS6L0TU6u55emsvdeJIUcD3YnCj8yPatjovhfWau49rT6d7j2\/rA2gLkiGZiFBkGM5g+1NyQIWlb3Vul39Nda1ftNbuLyrD34I7EfIxWjUgUpSgFKUoDNWTwh0S1qPM8wn0bYAMfVuycSRgcEciq3NbGh1r2m3I0GIPsQeQfipVXyZZ4znjcYOn7MmPE\/QRp23Ju2FisOIKmJA5yCJz8H4Jr9XHpfia3cBt6m2pU\/Ag5zk5B+Zic4rx634V2HdYaVOQj4aCYwThh+cHjnNS4p8o5cOplBrHn4fs\/Z\/UgeldQaxdFxe3I\/pA8qfz\/AMYParPrtCLyAyQ4XdbuFhJUlmTcB6gYhZPcCPxVV9JoWZo2mRyCKvGmtJatW1c+tBiJ3KHLEwRjAC4PufekY2U1mWMGnH8x93bPn2ES4CJDSDytxB29gZED2IE5NafSvDiLdUtcG5CG2hWP0jcJkARgd+9bWm1hZLu5sgekyB2aR8yJH6gcE19tqSUUwUcbgS05wTBnhOT7CDJiteDzVLKk4xdJ+Pk+tL0Zbzm027052yCZAAAB9vfHae5jc1HR1tWnQGEKNCns20bj75554\/IVF+H9Q6ajaZBKtIM5AE\/+371Kdf17LqltvhSsRjG47SSBzxkfHfvZVVnPkeb1tifFX+xWP9mkcrsuYJyCDIAjdBiGIBn9qx4ksELcIU+t1G6cegNKKJwAQDOZmpQHZvlybgO0kjvJ9Ik5mOfY1u3UDKqYeTs2kychT2+kzuafmqbUzt\/1U4yTbtLz+\/8A0Vjwb01i5vcBQwHvlG3N8ADuff4rU8RdaN47FP8ADU4nltoIU5yABgD5PvVw6vYNrSNbsAsHESOdoI3nA7sY\/U1TendLhTddSwUgLbAMsZySBnYvf3kDEyKSW1Ujo02WGabzz\/SKNvwv0HzG8y5ARRuG7AIBEsfdRz+mccut+JmZitiFQDaGgbmAkTJyJBjGfc19eJuqEbrKEzgXGwAQsQoAJ2riYn2BgyKq9Q3SpHTiwvLL1cv0XsvkEzWKUqp3ClKUApSlAKUpQGxobatdtq5hWdQx9gSAT+1dW+2LxLrdL1K3a09+5YtWbSG2lskKeclRhxjbBBELEZNchrpnT\/tZIt2hq9BY1d6wALV+5AdYiCZRvVIBkEZAPOaymnadWSSHQer6heg9T1wuMNZc1KpcvDDhf4IwR9Mb2AiNs4iBXzoOq37\/AIa1F+\/de5d0uqQ2Llw7nVg1mIZsmN7czgxwIqu9F+0nUWdTqb1y1ZvW9WZv2GWLZwR6RmDGCSG3fik5ry8ZePX1lhNLZ01rSaVDu8q13bOSQFEZmAoyZM4imx30Dq6dLtXuo6brhG3T\/cjfuHGLiKFhvkI3\/wBmqZpeoPqPD3V77\/Vd1aufjddsGB8CY\/Sq1pfH9630l+mBBtYmLu4yqM4Zk2xBk7hM8NWj0\/xUbXTNR04WgV1FxXNzcZXabZjbGfo9+9FjYL79qHX9XpLfSjptTdtf91UkI5CsQqRuX6W\/UGs\/ar4VfWdZdLBso33ZLjm64QE7mTmMmAv6Co5PtbXy7Cv0vTXLlhFS3cukMy7QBIlJXicGqJ4l67e12pfU3yC7xhRCqAICqCTAA\/8AcnJpGEv0B1D7KDq9B1MdMe5aNu4DeYWyrgkWzENEjgSP7I+Z+fCGvtXNJ1LQLrl0WpfVNcW6zbJUMsqGkH8DSAZhu4mudeCvEZ6fq01S2xcKhhtLbZ3LHIBr56R1m1a1Z1V7TC+N5cWmchdxaQW9J3Ae3B7+1S8bbYL19vdtVuaBDcF28uni5cxucAgK5j3YOf1NcoqY8Udeva7Uvqbx9T8AfSqjCqvsAP3MnkmoetYKlQFKUqxBmlZq9+HOg6W7pQ7KHY4P8QqQ0n0RgcQe5MwORExjuMNRqI4IqUk+64KGBSKtWu8LTmwT\/aR+RP0wfn2IxHJkVEX+hahcG0cexU\/\/AIk0cWhj1WKfUl+j4ZGVP9C6jdJWySSjHaP6S7iPpIzH9njn3MxidKvk7RZcn2CtP+FWjw\/0l7Y3tbbfjaCCIBn1EnjiO3M+1TFNsy1eXGsbum\/Yu\/QUTyQJ9QVQe\/qAAM++czzEduKp4islLxxtVjgmY+c5Jj961tTf2PKNMRmMTGRB5WZ\/Sp7TdYs3rLI4HyrcAsY5PGT6TzJ\/Q72mqPno4p4Z+p+ZPv4K55lvay7mIEMxAiRkYmZgsBEcknjjTGsVgyuSJIKtyViY3EZb2479oitjWdKthni\/tCAE7kbG4TnE44iDxUHqFVWA37h+IqOM5AzDYzzGYrFs9rDCM1xf7Fj6X1S594BLFkXd3MPs49gzEFVmATIxmD6eIdY1x1urHoJUmeCpJEk9yZgH3AjInV6WlkCCNu8Y8wbmI5ZtoP0+kRCkk9iBWp0+8VLI7rLSrhiDumdrMZXIZicsW4EDaDU7uKKPBB5HNLpdfHub1vVLd9Z2o4iCHCmQMGCMrg8ZGAe0yGhK24tT5juSCAWAUQdxAYDkd8EieBk1PUOhgq7sT2dcgAQATuM4gCBwO3FSPSdUggMfqY7iTA27GHJ4ncf5fFFIZtP+Hi68Fg1Ovm7ACGAB3gEgTxGBxxGOKdbdxbN6QxUnbIkAnaoYST\/amZ9uAKmegaUNNx08su34lIMGIkTjuT7wT7V49W08t5YBZSDu4ABIMcmAwGYJ\/Stdto8eOeMcqil139zlFwmTJJPcnvW10zp7XrgRf1MEwPfH7fnVq0\/hK3vY37kBclVgemclmP0j9Pc159U8Q6e0vl6W2BHeBA9zP1M3zMDsTWGyuz3\/APWep+HCm359keut8L2RpmuIHDKC25mBnaoYgxAj8sgxzVHqZ13iG7dQ24RFPIQEdyYyTAk9uYFQ1Q2n0baWGWEX6rvngxSlKg6RSlKAUpSgFdB8I\/Zu+t6bqNbvZXTd5NsARc8tZbn3MqPkGqHp7DXHVEBZ3YKoHJLGAP1Nfolus9N6Zc0Ohuam6lzSpBW2o8p2vLDNd9M8kvgiN0mayySa4RJyDwH4Tt69NYz3GT7vZNxdoHqMMYM9sVXej6UXr9m0SQLlxEJHIDsASP3rtvQ\/D\/3LW9ctBYttpjct+2y4LhAHwp3J\/wANcZ8L\/wD1ul\/8+1\/+xaiMrtg6Zrfss6d94Oit9UK6vtbuWwZJXcBiOVzg\/pXMNV0a+mouaby2e9bdkZbYLGUMEiBJHzHFdv6n4N1tzxIutFmNKrW2N0vbiEsqD6d276hHH8s1seFdfaujq9\/S+Y986vnS+SbxtAIEZPOBQqSLhyMiYzFUWRr5Bxfwl4Vv9Q1J01ohGAJY3A0Lt7NtBIPbPtUTa0F5rhtLauG4JlAjFhHMqBIiu9dK6k3+0oU2X0xu6QealzypusoYq82yVJ2wMH8B9q1Ps2u3fuGvuEX21\/3ojUeQNP5+NsAC6pTbO\/Ef04qfVYOFpYZm2BWLkxtAJafaOZ+KmegeFtTqtYmjCG1daSfNVxtAUmWG2QDETHJFdo0l7f1XqL2tKbHUBoh5KXfKLNch5cFWKGf4SzPYgxmofoPUOsL1bpv\/AGlCeYl1FO20GdSCzK+zhty28YwF7lpPKwc80vh2yi9QTVNfW\/pRFoWrbFGaWkudnoQgAgkrgzmIqvWen3mttcW1ca2v1OqMVWOZYCB+tdf0j3ivic3p8yFGYnaPPFvjtsC\/pVt8P\/ewekLogP8As86b+PAtwSbf4p9Qbdn08sWnvUeq0D876PpOoujdasXbgmJS27CRkiVHMVq3LZBIIIIMEHBBHIIPBrtg60+j6Lrb2hdUC9RuLaKhSvlm4NoAIIgrA\/Kqr9vOnVerMVABeyjNHc+pZ\/ZR+1Xjkt0DnNe1jUOhlHZSO6kg\/wAq8azWxDSfDJfpmu1haLNy6zCTALEAcEmcASck+9b+s63rE2rqEDDO0XE9PyV2wD+Y960\/DHVlsXZdZVhBIALLBkET\/OrbrfFOiaFJZxg7lVoBAAyH7xPYjtEVePXZ5epco5aWLcvKXJX9B1RbtwA+ZbJEABi6EnsUfIUn2ODxGCLDr7jIyksx9jhGIgQZA7jvHvWA3T7xm0E3AiAsI0\/kFXd\/wkcflXv1C3bQAujNjAk4559WQfzn+U6RTSODPljKcVta+H3\/ADyQV216ySAFADGSYgiVBPJmQMZ59qjUvlbkpuIk4BIJXuMZGO\/bntUr1Agi4fMZlBOAIWWnb\/vcDEDAwcVFBgtsug9X0szEejcDkAZzxJ+R3qjO7CrX8Hr1rU+W6G28yA3qCtnaAD6lOCMEEmSGnmoXSM+9fLy5MLgHJwIB75x88VsdYvq1wlc9pAgHbhSB2G0D2n2FfPT71w30a2ssrAqsnaAGkD1HCD5PEyazb5O3HHbj+a9\/uTXV\/Dmoto95iCTyA2QgABGAA4yASB+H5qtrfO7cfUc\/VJ5ESfeOf0rr3UNdauaZ7e4fRnZyAcDaD9X\/AF74HL71rSqxHmXGE8qgAA9\/U0sf2\/yvkil0cX+P1eTNGSyR5Xhext6G1p7zmA6fAde85AYTAAzG6OeMCweFLGn3blVztaA7gHBgDaBwxM5iQDVJsG3I3bokzEcQNpEzmZkflmrJqbls2QtlVlmCkgyAWWWgkAKIle0Kc5mogzTV4nJbU3T\/AI8kn1fxEGbbZG1QeRAJA4UFeBzJHM+3Oem3g1xmDOqxLMD6zEmeTH7+3JIqs6SyWnttBJn47fnOKktDejcP6Sx\/MEH+X7E1opNs5MmnhCG2J7eL7juoP0o3qCDifc\/0jEZ+YEcVTavnXrH\/AHZSCSgPpP8AvLJH5ggiqI4zVcnZ2f46S9Ol7M+aClbej6fdu\/QhOYngSeBJxJ7Dk1md8pJK26NSlb2v6Zesx5iEA8HBB\/VZE\/rWjQRlGSuLtGKUpQkUpSgPWzdZGDoxVlIKspIIIyCCMgj3r61eqe45e47O7cs7FmMCBJbJxj9KxprBuOqL9TsFE+7GBXZfE\/iPS9GvW+n2On2L1pbanUPdUF7m6ZzETGZMjMAACs5Sp8Lkk5M\/X9WSSdVfJK7CTduZTPoPqyuTjjJrRtXCpDKSCDIIMEEcEEcGuw+E+maXqHTeplEsaNH1ClHuQVsoPLY+puMA4BAloECqhrPs41FvXjRNfsDdb81bzvttm3JG7Od2D6RPE8ZqIzj10CuarxBrLilLmr1DqeVe7cIP5gtBrW0HUL1h99m7ctPEbrbsrQe0qQYroPRPBbaPqvT99yxqdPfcm3ctkMjhR6gQcSJHuPnBiQfR2vuniI+Wk29UQh2rKjz2ELj0iPao3xXCQOXNr7xu+cbtzzZnzN7b5990zPzNeuk6tqLVxrtu\/dt3Gnc6XHVmkyZZTJk5zVz\/AP8AJ9X5W7ztP958vzfue\/8AjbPePece04mnhr7MW1WjsaptbYsLfZkRbsglw7IqCSAzNtJAGfg1O+AKQOoXhd84XrnnTPmb23zxO6d0\/M19avqd+7cF27fu3LgiHd2ZhtMiGYyIORVs6X9mupuXdVbv3rOmTSMFu3rreiWyu0mMEEHMYYd8V7dR+zDUJrbOhtX7d29ctea5hlS2kkbixksJHYe2M03wsFOPVtR\/E\/j3f4v\/AIv8R\/4kTG\/Pr5PM819abrWqt2zZt6m8lozNtbjhDPMqDBn8qmvF3gu5ordu+t+zqdPdJVb1hpXcJlTGJweCfpPFVWrra1wDZGuu+V5Pmv5RO7y9zbJ99sxPzFNdrrt5t96691ojdcZmMDgSxJitalTSIPoCsEVOeEDaGoBuxwdm6I3yImccTz3irj1a3bUje0WyQpVlOxcE9wV3cQ3YkjMAC6has4s+s9PJs2t8WcyivS1YZjCqWPsASf5VdrnU+mpOxVJk4NtT3xBK\/p+Xua0\/+37B3SbnqPGy2V\/9LEBvyI\/zEONe4jqskuoNfqaXR+l3UcO6lFBkk8iIP0iSD3yB+1Wq7qdrMjpuRiYxxwRE8gY9J9hxUD07qWnPpN28PXuG+CJ7f0p\/IiPUZ7Grv0CFaWALGCGkkspAPpYYK95Ef4RrjV8Hl\/5Cck98l9ih9R0hVyoBOcDvBEjAzwefzrZ0PStygOCoeCVOGIV+QOdpnmBkY5mrn1LrOnsvDAk8kBVI98gHJ+D\/AJ1A67qFvUnZZIUzMFYLQMbROWxxPae0VLivJTFqss4pbGl\/y+5TOsaTy3I4JLekfhUH05nPf9q1bOsdVZBG1uQR8j9e0fkTUhr9EZdjcViJaFInJkyJ9ByTtjmRjExdm2CwBIUHuf8An\/4rBnv42nHnmiZsa5wHW9cKg8AGILHLqFEQNuQOcccjR6lq90LKuRH8SDLYx9QBHz7kTTW2UEKu8vMBD+AEmEjJLSf07iSY0WUgwRBHINBGEbtGBW905vUF3MAT+ExmCFP7mJ9i3vXnolTd6pPsoE7mkALyMd\/0jvUv1BIVG9RJDbzMQWUKICkqFaJkfUDE+0ojJNXXk2NFZuByQyndIadoPrBU7sztJMGCRPyKkW6WBBttKtkbp4iZLRAwe+3nioW1edrm8Ybtt7R7fH\/zVm0r+Sq7zDEDcg5MfSTBxAjBgkz2rSJ5OplJdP6Gzprd5UZTMmB+BpC8D1fh4HPGBWnaIV2iyWI5Is21gsexZFgyRHqaR271s9U8Q+XZG+3unsWAHAzt2mMRn\/rUb0rxVYIIdRaInbyRBBlZUd\/ThhHoGe1WlV1Zy4YZ3CU9l\/p\/6zF3xalolTpXDd5ubeeIAWI\/5715WfF9o4a2yRxtgxzx6lj+ZnM9qgvEmuS9dm3JVRtBJ59RM5E9+9Q9ZubPVx6DFKCcotN\/LLV4o8RWr9sJbRhlZLRwoMEAEgMZyR88yaqtKxVW7dnZhwxxR2R6FKUqDUUpSgPu1cKkMpggyD7EcGuu9S6t0LqjWtZrNRd099UVb1kK5D7T2KocGSJBBiMA5rj9KpKFknRx4g6cnS+p6Wwzp595W09q4GLFFa2TLAFRG0wGMwBknJs3+23S21emdro9Gh8lbxsu3kXpENsdPVifUAR24JriVKr6SB2jxL460Xn9LuLrG1R0t1jecWTbJDgDeF2quI4WoZ\/E+h29bsi8xXWP5th\/LeGYlnKERK+ohZIiJP58wpT0kDvHUvtK0t+z94Tqd\/S3fJj7smntufNgwQz2yCs9twkRlTVQ0vijSDpfSdObv8XTa0Xby7H9KC7dbdO2GwwMKSc8VzalPRQs\/RPROq2dVe6pqEVr+jvXLAUnTveQm3ZthwbAi7PHqK7cA9qjesdcHTuuW9Vqr2+1qdJshbZR9OhZSs2ySY3L3zlsenPHeieIdVpGZtNfe0W+racGOJBwY7SMSa1eo667fuG7euPcuNyzsST7ZPYe3aqLFyLL59p3iO1fs2bNrqd3Ww5dw1i3bRcEIQVto24BiCPUDP4Yg84pSt4x2qgKUpUkGaTWKUBmlelm2WYKolmIAA7k4Aqz2\/BF0gE3EBiWADHaJgyQIPbiefbNEm+jLLnxYq3urKsjQa6B4duh7Ki4YUHEzDCZiQJ2gkk\/Ax3Ixo\/DGnsDfcbey\/UXHoWPjif94n8q8G8QWEbanqHBhRGMEySRJGJhuTntWkVt7PK1OdalbcSbr36NTqO5mJbmc\/5VF3U7+3f57frVxvqtxPMREgCR3GBnEAyAIzI9J71GaZlLRtCliFIE7WDEKQQDggEkEEce\/NmjPBnpVXRX+pBTtcQGaSwBwDMcfhk7jE8beJqW8PWbdwNbQFXiYaGkArwwAIzBM8bQRBrR1ejIuFACTugDuZOP1OKtfgqxbVHJkXJzHMDbAM8CZPyQOYEVjG5G+qzqGC1fwQvVdDbtXWjYjuzATuuGDiQqk+pjKiRGDxIiutf\/AIgLQ4TAgBeJ2\/h7HsR2jirB4v0m7UO6DcggbgPTIUbgOxIMzHvPzUHp7DFgFndOIxkd57RzNVkueDfTTTxpyduufgkrGqtlg3llWP4LW6SxlR+MgmC3KqfVIkEVaOhdfsXV8lrQUQYUwyxMx2Le5BBmIzVWPSMBi4AI9ReRmTwI3MDHIE4OBifjTWGLDaCTyNszjM+\/zVo3Ew1OPHmj2+Onb4Lx4g0NlLfmWwqvJAgAHIyIAzgzJmoXpVhjubPEliDzuHeJz3jMTWUFw2S+8sSQGMmQDMjPuYk959snOo1q6ez6kDM0gA\/qC09u4jIM\/pWja7POxwmo+mnbujU69pX1ILWWD7JBBwTkAETxgqsGOPmKp2o0z22K3EZWHZgQf51N2\/EC7pe2SezBiSOezzIyfTMCcVLaHqOie2LbCAMBbnGSfUCBCNGJDZAB\/LF1JnrY5ZNPCnFtfHf8FJrFW3qXhRY3WLm4H6Y9Sn4DLOfYZn3nFQ2p6FqLYZmtnavJBB7TODMfPbvUOLR1Y9VimuH9HwyKpSlQdApSlAKUpQClKUApSlAKUpQClKUApSlAKUpQClKUApSlAbnS9X5V1LkA7ex+RH79x8xVp6l4xV19IZm7bwoA52scksw\/Tj5iqXWKlSa4Rz5dLjyyUprlGxqNW9yNzExwDwJ5gcD9K8AYrFZqDdJJUi2eFOpZe259BUkg9yCNsY5mOMmpnR6fzru9D6RDE\/tGB89hmAar\/QdG62murAZ5Cs24BVWSzyvaREZkrEENVk6U6aOwxuNPJ3LEzHpA5wQdokjljGDWsHfZ4esjFSbx\/mfFf2e+ttm2SFSWBY7ZOGPBMnjJEYJJx71DIDdhPUGP07QNszxtUCB2nJn9a+rfW7V0lrgKschlJ9+DPaO4z\/OpF4bY+9WVRkjklmxPz3g9wfircPowW\/GkprnyV3SwrbiGn3VtpHv2z\/h+dTt3SJeFt90AbYwAMsd2BOyCJ+d3xNeen6U0qSYGDwZyJECPV74nvUz0rSqqukH6sBwAeAcfLBce+KKIzahL8Ue0V3WsjNBUhEEKqxyTLEnPcnOZgVu6K2gBm04AIIO6TPIDfTu7GBHvFa+pKLeYc\/xCAvM+rA+favLr\/iLa5S3AIAG8c5EnbEAAkzxOOe1OEXUZ5ajFPySVkW7e5VO5j+EgggDiQGG7mCP51XfFnT7wY3T6rbcEGds8Axx7fBwYNQTa99wcMQwMhgSCD7gjINXXoHXl1C+VcUeZBz\/TBifScT324GJERVNylwdHoZNK1lX4vJz81irT1zws1pTctmVySrYIA5K59YwT+Q75NVeqNNdnq4s0Msd0HZ76XUvbYMjFSO4+M59\/1q6WPFljyYIKscsoHpb+kAQZJOfq94k81RKUjJrozz6XHmrd7A1ilKg6BSlKAUpSgPWwF3DeSFnJUAmPgEgE\/rW95ej\/AK3Uf3Vv\/VqMq\/dH8A29TY0txNRcD6lLrGbS+XZ8gkM11\/MlbbEMFaMxxNVk0uySqeXo\/wCt1H91b\/1aeXo\/63Uf3Vv\/AFatF7wItrTWtReuXhbuacX\/ADUtBrUldwslt\/puRABYAFjtHYn0699n6aVnZtQ9zT+U7271u2sM9ptl2y4L+hlb8+\/cECm+PkFT8vR\/1uo\/urf+rTy9H\/W6j+6t\/wCrUr4n8J\/crdlrl0s160GUKo2i4rFdRZZgx9VowD7kxiKq9XXPTBJ+Xo\/63Uf3Vv8A1a89Smm2ny3vFuwe2gHOZIuE8fFaFKmiBSlKkClKUApSlAKUpQClKUBmpDo3Tm1F1baz7sR2A5P+XyQO9Z6H0w6i8tpTEnLHgCQJ\/nH5kVcxaTQ6e6yoQxA+oyT6oAMqJ5BxEAHmrRjfL6OPVar0\/wDbjzN9fUyeoae1qPJYqqhQqicLkjLZg7cg+3JFQXjHrCXSLVohkViSwEAmSBGBODJJ7n4k1u\/eZ2LMZZjJPya86OdqiuHQwhNZG22l9L8mVcirP0x7j6Tas\/8AiQ2QMMV2xPeViB7mqvV48LqU0nnHKKzMRHBHH+E\/G2ohyyda9sE65tUQ3WurMbhRZC2\/QB\/u4Y89yP2A9ql\/B2pd\/MJMiVG2c8PnOMTgSOPiqUxqb8PdebTbhBZWzExDDhh+hIPEg1MZc8kajS3gcYK3wSfU9EgulwWy2\/aCswtwBxiYkFXHsJ9qhvE1orqHkzIUg5zKjOe8zPzNbOu8Qtd1KXSDtWBtJkkQA+Yj1ARgcR7Vv+PtIoNm6mVZSoI4gZWB25I\/4alq02jPE5YskIz7af2dfsVCtvp+ra1cW4sSpkTwfcH4IwfzrUpVD0WlJUy66nxghs7UtsrBYAwVHx8pHbb2j5FMNfNZqXJvsyw6fHhTUF2YpSlQbClKUApSlAKUpQHpbiRIJE5AMGO8GDB\/Q10C39o9u2lmxZ0CppUS7bvWDeLC+L2z1M3liLilZDwTkgQK53Sqyipdkl6Hj5UF9LOnuW7N+0bTWPvE2lDAB3RPKAW6VB9XG5iSDxX10z7RPKfVK2m8zTai753kPdE27m8MSr+XBU5BUrkRnmaHSo9OILd1fxj950P3W9ae463mu2773V3Ju5TaLQ3KRk5EtnHFVGlKtGKXQFKUqSBSlKAUpSgFKUoBSlKAUpSgNzp2vuWXD222sMdjg8gg4IrY6z1u7qSDcIAHCrMD9ySfzJJqMFDS3VFHjg5b2lfn3MUpShcyKuqo9rQMDyFbemZXfwWB\/MD\/AKVVOmOq3rbN9IdScTgMJx3q7+INXpxp2Ije07BIJPmbpymSBO6TgmcSQatFcNnBrG3OEKtXZz6sVmsVU7zNXPTKdT08W5G5WOzcYkoJOTgDawXPcj2JFNq3+EOr2UttbvbRyQTuAP5le4\/wPvE2h3Rx65S2KUFbTT4KldtkEggggwQeQRyD818VKeI9al7UXLiD0scYiYETAwJ5iouqs64ScoptU66MUpShIpSlAKUpQClKUApSlAKUpQClKUApSlAKUpQClKUApSlAKUpQClKUApSlAKUpQClKUArNYpQClKUArNYpQClKUApSlAKUpQClKUApSlAf\/9k=)\n\"\"\"\n\"\"\"\n# \u0627\u0633\u062a\u062f\u0639\u0627\u0621 \u0627\u0644\u0645\u0643\u062a\u0627\u0628\u0627\u062a \u0627\u0644\u0645\u0637\u0644\u0648\u0628\u0647 \u0644\u0644\u0639\u0645\u0644 \n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport cv2\nimport os\nimport re\nimport pydicom\nimport matplotlib.pyplot as plt\nimport warnings\nimport pandas_profiling as pp\nimport glob\nimport ast\nimport math\nimport matplotlib\nimport wandb\nfrom PIL import Image\nimport albumentations as A\nimport torch\nimport pydicom as dicom\nfrom matplotlib import pyplot as plt\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n# \u062a\u062d\u0645\u064a\u0644 \u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a\n\n\"\"\"\npath = '\/kaggle\/input\/siim-covid19-detection\/'\nos.listdir(path)\ntrain_image = pd.read_csv(path+'train_image_level.csv')\ntrain_df = pd.read_csv(path+'train_study_level.csv')\nsample_submission = pd.read_csv(path+'sample_submission.csv')\n\"\"\"\n# \u0628\u064a\u0627\u0646 \u062d\u062c\u0645 \u0643\u0644 \u0645\u0644\u0641 \u0645\u0646 \u0627\u0644\u0645\u0644\u0641\u0627\u062a \u0627\u0644\u062a\u0649 \u062a\u062d\u062a\u0648\u0649 \u0639\u0644\u0649 \u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a\n\"\"\"\nlen(sample_submission)\nlen(train_image)\n\"\"\"\n# \u0639\u0631\u0636 \u0628\u0639\u0636 \u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a \n\"\"\"\ntrain_image.head(10)\n\"\"\"\n# \u0639\u0631\u0636 \u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0639\u0646 \u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u062a\u062f\u0631\u064a\u0628\n\"\"\"\ntrain_image.info()\ntrain_image.describe()\ntrain_image.count()\ntrain_image.isnull()\ntemp12 = train_image.loc[0, 'StudyInstanceUID']\ntemp12\ntemp123= train_image.loc[0, 'StudyInstanceUID']\ntemp123\nboxes =ast.literal_eval(train_image.loc[0, 'boxes'])\nboxes\n\"\"\"\n# \u0628\u0646\u0627\u0621 \u062f\u0627\u0644\u0647 \u0644\u0645\u0633\u062a\u062e\u0631\u062c \u0627\u0644\u0635\u0648\u0631\u0647\n\n\"\"\"\n\"\"\"\n**\u0627\u0638\u0647\u0627\u0631 \u0628\u0639\u0636 \u0627\u0644\u0635\u0648\u0631**\n\"\"\"\ndef extraction(i):\n    path_train = path + 'train\/' + train_image.loc[i, 'StudyInstanceUID']\n    last_folder_in_path = os.listdir(path_train)[0]\n    path_train = path_train + '\/{}\/'.format(last_folder_in_path)\n    img_id = train_image.loc[i, 'id'].replace('_image','.dcm')\n    print(img_id)\n    data_file = dicom.dcmread(path_train+img_id)\n    img = data_file.pixel_array\n    return img\nsample_img = extraction(0)\nsample_img\n\"\"\"\n# \u0627\u0638\u0647\u0627\u0631 \u0645\u0643\u0627\u0646 \u0627\u0644 **boxes**\n\"\"\"\ntrain_image.loc[0, 'boxes']\n\"\"\"\n# \u0639\u0631\u0636 \u0628\u0639\u0636  \u0627\u0644\u0623\u0645\u062b\u0644\u0629\n**\u0644\u0646\u0642\u0648\u0645 \u0628\u0631\u0633\u0645 \u0628\u0639\u0636 \u0627\u0644\u0623\u0645\u062b\u0644\u0629 \u0645\u0639 \u0635\u0648\u0631\u0629 \u0627\u0644\u0635\u062f\u0631 \u0628\u0627\u0644\u0623\u0634\u0639\u0629 \u0627\u0644\u0633\u064a\u0646\u064a\u0629 \u0648\u0627\u0644\u0645\u0631\u0628\u0639\u0627\u062a \u0627\u0644\u0645\u062d\u064a\u0637\u0629 \u0648\u0627\u0644\u0645\u0644\u0635\u0642 \u0627\u0644\u0630\u0649 \u062a\u0628\u064a\u0646\u0647**\n\"\"\"\nfig, ax = plt.subplots(1,1, figsize=(8,4))\nfor box in boxes:\n    p = matplotlib.patches.Rectangle((box['x'], box['y']),\n                                      box['width'], box['height'],\n                                      ec='r', fc='none', lw=1.5)\n    ax.add_patch(p)\nax.imshow(sample_img, cmap='gray')\nplt.show()\nfig, axs = plt.subplots(3, 3, figsize=(20, 20))\nfig.subplots_adjust(hspace = .1, wspace=.1)\naxs = axs.ravel()\n\nfor row in range(9):\n    study = train_image.loc[row, 'StudyInstanceUID']\n    path_in = path+'train\/'+study+'\/'\n    folder = os.listdir(path_in)\n    path_file = path_in+folder[0]\n    filename = os.listdir(path_file)[0]\n    file_id = filename.split('.')[0]\n    \n    data_file = dicom.dcmread(path_file+'\/'+file_id+'.dcm')\n    img = data_file.pixel_array\n    if (train_image.loc[row, 'boxes']!=train_image.loc[row, 'boxes']) == False:\n        boxes = ast.literal_eval(train_image.loc[row, 'boxes'])\n    \n        for box in boxes:\n            p = matplotlib.patches.Rectangle((box['x'], box['y']), box['width'], box['height'],\n                                     ec='r', fc='none', lw=2.)\n            axs[row].add_patch(p)\n    axs[row].imshow(img, cmap='gray')\n    axs[row].set_title(train_image.loc[row, 'label'].split(' ')[0])\n    axs[row].set_xticklabels([])\n    axs[row].set_yticklabels([])\nlabel_dict = {0: 'none', 1: 'simple_opacity', 2: 'double_opacity'}\ndef split_label(s):\n    split_string = s.split(' ')\n    if len(split_string)==6 and 'none' in split_string:\n        return 0\n    elif len(split_string)==6 and 'opacity' in split_string:\n        return 1\n    else:\n        return 2\nOpacityCount = train_image['label'].str.count('opacity')\nOpacityCount\ntrain_image['OpacityCount'] = OpacityCount.values\ntrain_image\n\"\"\"\n# \u0644\u0646\u0642\u0648\u0645 \u0628\u062a\u0648\u0632\u064a\u0639 \u0627\u0644\u0641\u0626\u0627\u062a \u0627\u0644\u0649 \u062b\u0644\u0627\u062b \u0648\u0639\u0631\u0636\u0647\u0645 \u0639\u0644\u0649 \u0627\u0644\u0631\u0633\u0645\n\n\"\"\"\ntrain_image['OpacityCount'].value_counts().sort_index().rename(label_dict).plot.bar(rot=0, color='orange', alpha=0.6, grid=True, figsize=(8,4), fontsize=16)\nplt.show()\ntrain_df.sum()[1:].plot.bar(rot=45, color='orange', alpha=0.6, grid=True, figsize=(8,4), fontsize=12)\nplt.show()\n\"\"\"\n# \u0644\u0646\u0642\u0645 \u0628\u0641\u062a\u062d\u0645\u0644\u0641 test_df\n\"\"\"\ntrain_df['id'].isnull().sum()\ntrain_df['id'].str.split('_')\nimport matplotlib.pylab as pylab\n\"\"\"\n# \u0644\u0646\u0642\u0648\u0645 \u0647\u0646\u0627 \u0628\u062a\u0648\u0632\u064a\u0639 \u0627\u0644\u0633\u0645\u0627\u062a \u0627\u0644\u0641\u0635\u0644\n\"\"\"\nparams = {'legend.fontsize': 'x-large',\n          'figure.figsize': (20, 32),\n         'axes.labelsize': 'x-large',\n         'axes.titlesize':'x-large',\n         'xtick.labelsize':'x-large',\n         'ytick.labelsize':'x-large'}\npylab.rcParams.update(params)\n\nfig, ax = plt.subplots(4,2)\nsns.kdeplot(train_df[\"Negative for Pneumonia\"], shade=True,ax=ax[0,0],color=\"#ffb4a2\")\nax[0,0].set_title(\"Negative for Pneumonia Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\nsns.countplot(x = train_df[\"Negative for Pneumonia\"], ax=ax[0,1],color=\"#ffb4a2\")\nax[0,1].set_title(\"Negative for Pneumonia Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\n\nsns.kdeplot(train_df[\"Typical Appearance\"], shade=True,ax=ax[1,0],color=\"#e5989b\")\nax[1,0].set_title(\"Typical Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\nsns.countplot(x = train_df[\"Typical Appearance\"], ax=ax[1,1],color=\"#e5989b\")\nax[1,1].set_title(\"Typical Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\n\nsns.kdeplot(train_df[\"Indeterminate Appearance\"], shade=True,ax=ax[2,0],color=\"#b5838d\")\nax[2,0].set_title(\"Indeterminate Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\nsns.countplot(x = train_df[\"Indeterminate Appearance\"], ax=ax[2,1],color=\"#b5838d\")\nax[2,1].set_title(\"Indeterminate Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\n\nsns.kdeplot(train_df[\"Atypical Appearance\"], shade=True,ax=ax[3,0],color=\"#6d6875\")\nax[3,0].set_title(\"Atypical Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\nsns.countplot(x = train_df[\"Atypical Appearance\"], ax=ax[3,1],color=\"#6d6875\")\nax[3,1].set_title(\"Atypical Appearance Distribution\",font=\"Serif\", fontsize=20,weight=\"bold\")\n\nfig.subplots_adjust(wspace=0.2, hspace=0.4, top=0.93)\nplt.show()\npp.ProfileReport(train_image)","meta":"{'source': 'AI4Code', 'id': 'dc5e0b3dde1775'}"}
{"id":"23484","text":"\"\"\"\n![image.png](attachment:ee776dcb-7c9e-4ff5-b3d0-46debbb172c3.png)\n\"\"\"\n\"\"\"\nIn this competition, you\u2019ll simulate a ventilator connected to a sedated patient's lung. The best submissions will take lung attributes compliance and resistance into account.\n\"\"\"\nfrom IPython.core.display import display, HTML\n\nimport pandas as pd\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport glob\nimport os\nimport gc\n\nfrom joblib import Parallel, delayed\n\nfrom sklearn import preprocessing, model_selection\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.metrics import r2_score\n\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport numpy.matlib\nimport warnings\nwarnings.simplefilter('ignore')\n\"\"\"\n<span style=\"color: orange; font-family: Segoe UI; font-size: 1.9em; font-weight: 300;\">Train data read<\/span>\n\"\"\"\ntrain = pd.read_csv('..\/input\/ventilator-pressure-prediction\/train.csv')\ntrain\n\"\"\"\n### HEATMAP\n\"\"\"\nplt.figure(figsize=(10,8))\nsns.heatmap(train.corr(), vmin=-1.0, vmax=1.0, annot=True, cmap='coolwarm', linewidths=0.1)\nplt.show()\n\"\"\"\n<span style=\"color: orange; font-family: Segoe UI; font-size: 1.9em; font-weight: 300;\">Test data read<\/span>\n\"\"\"\ntest = pd.read_csv('..\/input\/ventilator-pressure-prediction\/test.csv')\ntest\n\"\"\"\n<pre>\nid - globally-unique time step identifier across an entire file\nbreath_id - globally-unique time step for breaths\nR - lung attribute indicating how restricted the airway is (in cmH2O\/L\/S). Physically, this is the change in pressure per change in flow (air volume per time). Intuitively, one can imagine blowing up a balloon through a straw. We can change R by changing the diameter of the straw, with higher R being harder to blow.\nC - lung attribute indicating how compliant the lung is (in mL\/cmH2O). Physically, this is the change in volume per change in pressure. Intuitively, one can imagine the same balloon example. We can change C by changing the thickness of the balloon\u2019s latex, with higher C having thinner latex and easier to blow.\ntime_step - the actual time stamp.\nu_in - the control input for the inspiratory solenoid valve. Ranges from 0 to 100.\nu_out - the control input for the exploratory solenoid valve. Either 0 or 1.\npressure - the airway pressure measured in the respiratory circuit, measured in cmH2O.\n\"\"\"\n\"\"\"\nThe first control input is a continuous variable from 0 to 100 representing the percentage the inspiratory solenoid valve is open to let air into the lung (i.e., 0 is completely closed and no air is let in and 100 is completely open). The second control input is a binary variable representing whether the exploratory valve is open (1) or closed (0) to let air out.\n\"\"\"\n\"\"\"\n<span style=\"color: orange; font-family: Segoe UI; font-size: 1.9em; font-weight: 300;\">Train data Analyze<\/span>\n\"\"\"\nlen(train.breath_id.unique())\ntrain.describe()\n\"\"\"\n### breath_id 1\n\"pressure\" seems to come a little later than \"u_in\".\n\"\"\"\ncheck = train[train['breath_id']==1]\n#check['check'] = (np.log1p(check['u_in'] )+ np.log1p(check['u_out'])*2)*4\nsamples = [\"u_in\",\"pressure\",'u_out']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\ncheck\n\"\"\"\n### breath_id 2\n\"\"\"\ncheck = train[train['breath_id']==2]\n\ncheck['check'] = (np.log1p(check['u_in'] )+ np.log1p(check['u_out'])*2)*4\nsamples = [\"u_in\",\"pressure\",'u_out']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n### breath_id 3\n\"\"\"\ncheck = train[train['breath_id']==3]\n\nsamples = [\"u_in\",\"pressure\",'u_out']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n### breath_id 1-9\n\"\"\"\nplt.figure(figsize=(20,5))\nfor i in range(1,10):\n check = train[train['breath_id']==i]\n\n samples = [\"u_in\",\"pressure\",'u_out']\n\n    \n plt.plot(check[\"time_step\"],check['u_in'],color='r')\n plt.plot(check[\"time_step\"],check['pressure'],color='b')\n plt.plot(check[\"time_step\"],check['u_out'],color='y')\n plt.legend(fontsize=12)\n\"\"\"\n### shift1 \n\"\"\"\nplt.figure(figsize=(20,5))\nfor i in range(1,10):\n check = train[train['breath_id']==i]\n\n samples = [\"u_in\",\"pressure\",'u_out']\n a = check['u_in'].shift(1)\n b = check['pressure'].shift(1) \n    \n plt.plot(check[\"time_step\"],check['u_in']-a,color='r')\n plt.plot(check[\"time_step\"],check['pressure']-b,color='b')\n plt.legend(fontsize=12)\n\"\"\"\n### shift2\n\"\"\"\nplt.figure(figsize=(20,5))\nfor i in range(1,10):\n check = train[train['breath_id']==i]\n\n samples = [\"u_in\",\"pressure\",'u_out']\n a = check['u_in'].shift(2)\n b = check['pressure'].shift(2) \n    \n plt.plot(check[\"time_step\"],check['u_in']-a,color='r')\n plt.plot(check[\"time_step\"],check['pressure']-b,color='b')\n plt.legend(fontsize=12)\n\"\"\"\n### shift3\n\"\"\"\nplt.figure(figsize=(20,5))\nfor i in range(1,10):\n check = train[train['breath_id']==i]\n\n samples = [\"u_in\",\"pressure\",'u_out']\n a = check['u_in'].shift(3)\n b = check['pressure'].shift(3) \n    \n plt.plot(check[\"time_step\"],check['u_in']-a,color='r')\n plt.plot(check[\"time_step\"],check['pressure']-b,color='b')\n plt.legend(fontsize=12)\n\"\"\"\n### shift4\n\"\"\"\nplt.figure(figsize=(20,5))\nfor i in range(1,10):\n check = train[train['breath_id']==i]\n\n samples = [\"u_in\",\"pressure\",'u_out']\n a = check['u_in'].shift(4)\n b = check['pressure'].shift(4) \n    \n plt.plot(check[\"time_step\"],check['u_in']-a,color='r')\n plt.plot(check[\"time_step\"],check['pressure']-b,color='b')\n plt.legend(fontsize=12)\n\"\"\"\n### u_in and u_in.shift(2)\n\"\"\"\ncheck = train[train['breath_id']==3]\ncheck['u_in_lag'] = check['u_in'].shift(2).fillna(0)\nsamples = [\"u_in\",\"pressure\",'u_in_lag']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\n\"\"\"\n### C and R\n\"\"\"\nfig, ax = plt.subplots(figsize = (12, 8))\nplt.subplot(2, 2, 1)\nsns.countplot(x='R', data=train)\nplt.title('Counts of R in train');\nplt.subplot(2, 2, 2)\nsns.countplot(x='R', data=test)\nplt.title('Counts of R in test');\nplt.subplot(2, 2, 3)\nsns.countplot(x='C', data=train)\nplt.title('Counts of C in train');\nplt.subplot(2, 2, 4)\nsns.countplot(x='C', data=test)\nplt.title('Counts of C in test');\n\"\"\"\nthanks https:\/\/www.kaggle.com\/artgor\/ventilator-pressure-prediction-eda-fe-and-models\n\"\"\"\n\"\"\"\n### What is R&C?\nR and C seem to be adjusted for each patient.\n\"\"\"\ncheck = train[train['breath_id']==1]\nsamples = [\"u_in\",\"pressure\",'R','C']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\ncheck = train[train['breath_id']==2]\nsamples = [\"u_in\",\"pressure\",'R','C']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\ncheck.head()\ncheck = train[train['breath_id']==3]\nsamples = [\"u_in\",\"pressure\",'R','C']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## ewm=15\n\"\"\"\ncheck['ewm_u_in_mean'] = check.groupby('breath_id')['u_in'].ewm(halflife=15).mean().reset_index(level=0,drop=True)\ncheck['ewm_u_in_std'] = check.groupby('breath_id')['u_in'].ewm(halflife=15).std().reset_index(level=0,drop=True) \ncheck['ewm_u_in_corr'] = check.groupby('breath_id')['u_in'].ewm(halflife=15).corr().reset_index(level=0,drop=True) \nsamples = [\"ewm_u_in_mean\",\"ewm_u_in_std\",\"ewm_u_in_corr\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## ewm=8\n\"\"\"\ncheck['ewm_u_in_mean'] = check.groupby('breath_id')['u_in'].ewm(halflife=8).mean().reset_index(level=0,drop=True)\ncheck['ewm_u_in_std'] = check.groupby('breath_id')['u_in'].ewm(halflife=8).std().reset_index(level=0,drop=True) \ncheck['ewm_u_in_corr'] = check.groupby('breath_id')['u_in'].ewm(halflife=8).corr().reset_index(level=0,drop=True) \nsamples = [\"ewm_u_in_mean\",\"ewm_u_in_std\",\"ewm_u_in_corr\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## Rolling=15\n\"\"\"\ncheck[[\"15_in_max\",\"15_out_std\"]] = check.groupby('breath_id')['u_in'].rolling(window=15,min_periods=1).agg({\"15_in_max\":\"max\",\"15_in_std\":\"std\"}).reset_index(level=0,drop=True)\nsamples = [\"15_in_max\",\"15_out_std\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## Rolling=8\n\"\"\"\ncheck[[\"8_in_max\",\"8_out_std\"]] = check.groupby('breath_id')['u_in'].rolling(window=8,min_periods=1).agg({\"8_in_max\":\"max\",\"8_in_std\":\"std\"}).reset_index(level=0,drop=True)\nsamples = [\"8_in_max\",\"8_out_std\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## Rolling=4\n\"\"\"\ncheck[[\"4_in_max\",\"4_out_std\"]] = check.groupby('breath_id')['u_in'].rolling(window=4,min_periods=1).agg({\"4_in_max\":\"max\",\"4_in_std\":\"std\"}).reset_index(level=0,drop=True)\nsamples = [\"4_in_max\",\"4_out_std\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\nplt.legend(fontsize=12)\n\"\"\"\n## u_in_cumsum\n\"\"\"\ncheck['u_in_cumsum'] = (check['u_in']).groupby(check['breath_id']).cumsum()\nsamples = ['u_in',\"u_in_cumsum\",\"pressure\"]\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\n#plt.plot(check[\"seconds_in_bucket\"],check_trade[\"size\"],label=\"trade_parquet\")\nplt.legend(fontsize=12)\n\"\"\"\n<span style=\"color: orange; font-family: Segoe UI; font-size: 1.9em; font-weight: 300;\">Test data Analyze<\/span>\n\"\"\"\nlen(test.breath_id.unique())\ntest.describe()\ncheck = test[test['breath_id']==0]\n\nsamples = [\"u_in\",'u_out']\n\nplt.figure(figsize=(20,5))\n\nfor num,idx in enumerate(samples):\n    \n    plt.plot(check[\"time_step\"],check[idx],label=idx)\n#plt.plot(check[\"seconds_in_bucket\"],check_trade[\"size\"],label=\"trade_parquet\")\nplt.legend(fontsize=12)\n\"\"\"\n<span style=\"color: orange; font-family: Segoe UI; font-size: 1.9em; font-weight: 300;\">Submit data read<\/span>\n\"\"\"\nsub = pd.read_csv('..\/input\/ventilator-pressure-prediction\/sample_submission.csv')\nsub\n\"\"\"\n\ud83d\ude3a\ud83d\ude05\u3299\ud83d\udd30\ud83d\uddd1\u2b1b\ud83d\udfe5\ud83d\udfe8\ud83d\udfe9\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2b364b410e14ce'}"}
{"id":"59784","text":"#impot Labiraries\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n#Load Breast Cancer Data \nBreastCancer = load_breast_cancer()\n#X Data\nX = BreastCancer.data\n# Y Data\nY = BreastCancer.target\n#Splitting Data\nx_train , x_test , y_train , y_test = train_test_split(X,Y,test_size=0.32,random_state=23)\n\n'''\nSklearn.naive_bayes.MultinomialNB(alpha)\n'''\nMultinomialNBModel = MultinomialNB(alpha=1.0)\nMultinomialNBModel.fit(x_train , y_train)\n\n#Calculating Score for training and Testing\nprint('MultinoialNBModel Train score is : ' , MultinomialNBModel.score(x_train,y_train))\nprint('MultinomialNBModel Test score is : ' , MultinomialNBModel.score(x_test,y_test))\n\ny_pred=MultinomialNBModel.predict(x_test)\ny_pred_proba=MultinomialNBModel.predict(x_test)\n#printting prediction\nprint('predicted value for MultinomialNBModel is : \\n',y_pred[:5])\nprint('prediction probabilaties value for MultinomialNBModel is :\\n ' ,y_pred_proba[:7])\n#Calculate Confusion Matrix \n#y_test is the real result\n#y_pred is prediction for model\n\nCM = confusion_matrix(y_test , y_pred)\nprint('confuion Matrix is : \\n', CM)\n\n\"\"\"\n**14 and 2 unmatching\n55 and 112 matching**\n\"\"\"\n#Drawing Confuion Matrix\nsns.heatmap(CM,center=True)\nplt.show(block=None)","meta":"{'source': 'AI4Code', 'id': '6e518e7a18d0ca'}"}
{"id":"106919","text":"\"\"\"\n# Please vote my notebook if you liked the work !\nThe notebook is still in progress !\n\"\"\"\n\"\"\"\n# Table of Content\n* [Context](#context)\n* [Profiling season](#profile)\n* [1. Let's start with Tableau](#tableau)\n    * [age attendance for season](#attendance)\n    * [grouping partecipant by employer category](#category)\n    * [Donations in first healthcamp](#donations)\n    * [Who share the most on social media](#social)\n\n    \n\"\"\"\n\"\"\"\n# **Context**<a id=\"context\">\n\nMedCamp organizes health camps in several cities with low work-life balance. They reach out to working people and ask them to register for these health camps. For those who attend, MedCamp provides them the facility to undergo health checks or increase awareness by visiting various stalls (depending on the format of the camp).\n\nMedCamp has conducted 65 such events over a period of 4 years and they see a high drop off between \u201cRegistration\u201d and the Number of people taking tests at the Camps. In the last 4 years, they have stored data of ~110,000 registrations they have done.\n\nOne of the huge costs in arranging these camps is the amount of inventory you need to carry. If you carry more than the required inventory, you incur unnecessarily high costs. On the other hand, if you carry less than the required inventory for conducting these medical checks, people end up having bad[](http:\/\/) experience.<\/a>\n\"\"\"\n\"\"\"\n# Questions on this dataset :\n1. Let's profile the attendant - what's the main group of ages that partecipates and which employeer category they belong to ?\n2. If we profile the seasons in which the healthcamp has been launched, how does donation goes ?\n3. Wanting to check the marketing campaign, which social media is used more for each LOI (level of income) ?\n\"\"\"\n\"\"\"\n<a id=\"profile\"> <\/a>\n# Profiling the healthcamps with seasons \n\n\"\"\"\nimport datetime\nfrom dateutil.rrule import rrule, MONTHLY\n\ndef list_months_in_date(start_date: datetime, end_date : datetime) -> list :\n    strt_dt = datetime.datetime.strptime(start_date, \"%d-%b-%y\")\n    end_dt = datetime.datetime.strptime(end_date, \"%d-%b-%y\")\n    dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt, until=end_dt)]\n    distinct_months = []\n    months = [date.strftime(\"%B\") for date in dates if date.strftime(\"%B\") not in distinct_months]\n    distinct_months = list(set(months))\n    \n    return distinct_months    \nimport pandas as pd\n\ndf_med_camps = pd.read_csv(\"..\/input\/healthcare-analytics\/Train\/Health_Camp_Detail.csv\",sep=',',delimiter=',')\n#Format dates with pandas\ndf_med_camps\ndf_med_camps[\"Camp_Start_Date\"] = pd.to_datetime(df_med_camps[\"Camp_Start_Date\"], format=\"%d-%b-%y\")\ndf_med_camps[\"Camp_End_Date\"] = pd.to_datetime(df_med_camps[\"Camp_End_Date\"], format=\"%d-%b-%y\")\n#map the months with a dictionary and map\ns = {6:\"Summer\", 7:\"Summer\", 8:\"Summer\", 9:\"Autumn\", 10: \"Autumn\",11:\"Autumn\",12:\"Winter\",1:\"Winter\",2:\"Winter\",3:\"Spring\",4:\"Spring\",5:\"Spring\"} \ndf_med_camps[\"label\"] = df_med_camps.filter(like=\"Date\").apply(lambda d: d.dt.month.map(s)).agg(\",\".join, axis=1)\ndf_med_camps\n#remove duplicates in label (seasons)\nnew_season = list(df_med_camps.label.str.split(\",\"))\nnew_season\nnew_seasons2 = [str((set(season))).replace('{','').replace(\"'\",'').replace('}','') for season in new_season]\ntype(new_seasons2)\ndf_med_camps['label'] = new_seasons2\ndf_med_camps.to_csv('Health_Camp_details_season.csv', encoding='utf-8',index=False)\n\"\"\"\n# Let's start with Tableau <a id=\"tableau\">\n\n![source_data.png](attachment:source_data.png)<\/a>\n\n\"\"\"\n\"\"\"\nBy linking patient profile with second and third healthcamp and health camp details <a id =\"attendance\"><\/a>\n\n![age_presence_for_season.png](attachment:age_presence_for_season.png)\n\n\"\"\"\n\"\"\"\nWe can consider that for 2nd,3rd healthcamp:\n* In autumn Season, range of age who attended the healthcamps was 32-52 plus a group of 70-74\n* In spring Season, range of age who attended the healthcamps was 34-49 plus a group of 70-74\n* In Summer Season, range of age who attended the healthcamps was 34-51 plus a group of 70-74\n* The healthcamps who lasted in summer and winter, the group was 34-52 plus a group of 70-74\n* the group of age from 60 to 69 in 2nd and 3rd healthcamps in Summer\/Winter\/Autumn were very low as attendance\n\"\"\"\n\"\"\"\n# Partecipant by employee category\n<a id =\"category\"><\/a>\n![istogram.png](attachment:istogram.png)\n\n\"\"\"\n\"\"\"\nAnalyzing attendance in relation to employer category, we can find 6 top categories :\n* Technology (73%)\n* Others     (68%)\n* Consulting (57%)\n* Software Industry (48%)\n* Banking, Finances and services, Insurance (46%)\n* Education (38%)\n\"\"\"\n\"\"\"\nOr looking it as a Heatmap :\n\n![heatmap_attendance_by_category.png](attachment:heatmap_attendance_by_category.png)\n\n<a id=\"donations\"><\/a>\n\"\"\"\n\"\"\"\n# If we focus on the donations from first healthcamp\n![amountdonationsbyseasonsFirstCamp.png](attachment:amountdonationsbyseasonsFirstCamp.png)\n\"\"\"\n\"\"\"\n* For season Autumn and Winter, if healthcamp last only one season, donations are higher\n  if healthcamps last more than one seasons, donations drops of -75%\n* For season summer, if healthcamp is held from winter to summer, donation drop to 34% related to donations in summer and winter\n* For season spring, donations are very low\n* If healthcamp is held from Autumn to Summer, we earn -96% donations less\n\"\"\"\n\"\"\"\n# Who shares the most on social media ? <a id =\"social\"><\/a>\n![SHaredPeoples.png](attachment:SHaredPeoples.png)\n\"\"\"\n\"\"\"\nWe can see that for the 6 levels of income, \n\n* In first 3 tiers, Linkedin is preferited social media, followed by online site news and facebook\n* From tier 4 to 6, we cannot say too much due to drop of data, but Facebook,Linkedin and Online feeds remains the favorites\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c46d20378b786c'}"}
{"id":"125648","text":"\"\"\"\n# Ethereum Classic as a BigQuery Dataset\n\nIn preparation for the Ethereum Classic dataset being available on Google BigQuery, we prepared a few awesome queries you can run here on this Kaggle notebook. \n\nThis notebook will go over queries you can run for Ethereum Classic, including getting top rich list, hashrate analysis, and daily gini coefficient measurement. Some queries will try to compare with other blockchain networks.\n\nWe will also be plotting our queries with [Plotly](https:\/\/plot.ly\/), which we will be installing in this notebook.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nfrom google.cloud import bigquery\n!pip install plotly\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)\nclient = bigquery.Client()\nethereum_classic_dataset_ref = client.dataset('crypto_ethereum_classic', project='bigquery-public-data')\n\"\"\"\n## Top Miners By Rewards in the Last 30 Days\n\nHere, we try to find out who are the top miners by the address of the block mined in the last 30 days. We will run the following query as a string in python through the BigQuery client.\n```\nWITH mined_block AS (\n  SELECT miner, DATE(timestamp)\n  FROM `bigquery-public-data.ethereum_classic_blockchain.blocks` \n  WHERE DATE(timestamp) > DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)\n  ORDER BY miner ASC)\nSELECT miner, COUNT(miner) AS total_block_reward \nFROM mined_block \nGROUP BY miner \nORDER BY total_block_reward ASC\n```\n\nLet's run it.\n\"\"\"\nquery = \"\"\"\nWITH mined_block AS (\n  SELECT miner, DATE(timestamp)\n  FROM `bigquery-public-data.crypto_ethereum_classic.blocks` \n  WHERE DATE(timestamp) > DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)\n  ORDER BY miner ASC)\nSELECT miner, COUNT(miner) AS total_block_reward \nFROM mined_block \nGROUP BY miner \nORDER BY total_block_reward DESC\nLIMIT 10\n\"\"\"\n\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\ntop_miners = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\n# Look at the first 10 headlines\ntop_miners.head(10)\n\"\"\"\n## Plotly Library for Plotting\nIn this notebook, we will be using [Plotly](https:\/\/plot.ly\/) for plotting our charts. You can sign up for a free account to get your API key in order to generate the charts if you choose to run this notebook on your own.\n\nLet's start by plotting the top miners by their block reward as a pie chart.\n\"\"\"\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport plotly.graph_objs as go\nlabels = top_miners['miner']\nvalues = top_miners['total_block_reward']\n\ntrace = go.Pie(labels=labels, values=values)\n\niplot([trace])\n\"\"\"\n## Top Miners By Block Rewards All Time\n\nNow, let's make it more interesting and plot the total rewards of everyone who has ever mined Ethereum Classic from the genesis block.\n\nWe will limit it to just miners who's daily block rewards are greater than 100. This allows us to save on computing and plotting the traces in this Kaggle notebook.\n\nWe can use the query here:\n```\n#standardSQL\n-- MIT License\n-- Copyright (c) 2019 Yaz Khoury, yaz.khoury@gmail.com\n\nSELECT miner, \n    DATE(timestamp) as date,\n    COUNT(miner) as total_block_reward\nFROM `bigquery-public-data.crypto_ethereum_classic.blocks` \nGROUP BY miner, date\nHAVING COUNT(miner) > 100\nORDER BY date, COUNT(miner) ASC\n```\n\"\"\"\nquery = \"\"\"\n#standardSQL\n-- MIT License\n-- Copyright (c) 2019 Yaz Khoury, yaz.khoury@gmail.com\n\nSELECT miner, \n    DATE(timestamp) as date,\n    COUNT(miner) as total_block_reward\nFROM `bigquery-public-data.crypto_ethereum_classic.blocks` \nGROUP BY miner, date\nHAVING COUNT(miner) > 100\nORDER BY date, COUNT(miner) ASC\n\"\"\"\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\ntop_miners_by_date = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\ntop_miners_by_date.head(10)\ndate_series = top_miners_by_date['date'].unique()\ndate_series\ntraces = []\nminer_series = top_miners_by_date['miner'].unique()\n\nfor index, miner in enumerate(miner_series):\n    miner_reward_by_date = top_miners_by_date.loc[top_miners_by_date['miner'] == miner]\n    miner_reward = miner_reward_by_date['total_block_reward']\n    miner_date = miner_reward_by_date['date']\n    trace = dict(\n        x=miner_date,\n        y=miner_reward,\n        mode='lines',\n        stackgroup='one'\n    )\n    traces.append(trace)\nfig = dict(data=traces)\n\niplot(fig)\n\"\"\"\n## Daily Gini Coefficient of Ethereum Classic Mining Rewards By Miners\n\nNow, we shall compute the [Gini coefficient](https:\/\/en.wikipedia.org\/wiki\/Gini_coefficient).\n\nThe Gini coefficient is a statistical measure of distribution used to measure income or wealth distribution among a population. From the [Investopedia article](https:\/\/www.investopedia.com\/terms\/g\/gini-index.asp):\n> A country in which every resident has the same income would have an income Gini coefficient of 0. A country in which one resident earned all the income, while everyone else earned nothing, would have an income Gini coefficient of 1.\n\nHere, we are calculating the daily block reward distribution among addresses based on which mining address received a block daily.\n\nThe query uses what was constructed earlier and borrows from the implementation of the [Daily Balance Gini query](https:\/\/medium.com\/google-cloud\/calculating-gini-coefficient-in-bigquery-3bc162c82168) here. \n\nAlso, just for fun, we shall calculate the [Simple Moving Average](https:\/\/www.investopedia.com\/terms\/s\/sma.asp) of the Gini, using a 7 and 30 day windows. Simple Moving Average of SMA takes a set of values and their time periods, averages out a sum of the values divided by the chosen time window. \n\nThe query value for those here will be `gini_sma_7` and `gini_sma_30`.\n\nPlease not that this only calculates the gini of those miners who earned more than 1% of the block rewards in a day, otherwise, it'll always go to 1 due to many mining just 1 block.\n\"\"\"\nquery = \"\"\"\n#standardSQL\n-- MIT License\n-- Copyright (c) 2019 Yaz Khoury, yaz.khoury@gmail.com\n\nWITH total_reward_book AS (\n  SELECT miner, \n    DATE(timestamp) as date,\n    COUNT(miner) as total_block_reward\n  FROM `bigquery-public-data.crypto_ethereum_classic.blocks` \n  GROUP BY miner, date\n  HAVING COUNT(miner) > 100\n),\ntotal_reward_book_by_date AS (\n SELECT date, \n        miner AS address, \n        SUM(total_block_reward \/ POWER(10,0)) AS value\n  FROM total_reward_book\n  GROUP BY miner, date\n),\ndaily_rewards_with_gaps AS (\n  SELECT\n    address, \n    date,\n    SUM(value) OVER (PARTITION BY ADDRESS ORDER BY date) AS block_rewards,\n    LEAD(date, 1, CURRENT_DATE()) OVER (PARTITION BY ADDRESS ORDER BY date) AS next_date\n  FROM total_reward_book_by_date\n),\ncalendar AS (\n  SELECT date \n  FROM UNNEST(GENERATE_DATE_ARRAY('2015-07-30', CURRENT_DATE())) AS date\n),\ndaily_rewards AS (\n  SELECT address, \n    calendar.date, \n    block_rewards\n  FROM daily_rewards_with_gaps\n  JOIN calendar ON daily_rewards_with_gaps.date <= calendar.date \n  AND calendar.date < daily_rewards_with_gaps.next_date\n),\nsupply AS (\n  SELECT date,\n    SUM(block_rewards) AS total_rewards\n  FROM daily_rewards\n  GROUP BY date\n),\nranked_daily_rewards AS (\n  SELECT daily_rewards.date AS date,\n    block_rewards,\n    ROW_NUMBER() OVER (PARTITION BY daily_rewards.date ORDER BY block_rewards DESC) AS rank\n  FROM daily_rewards\n  JOIN supply ON daily_rewards.date = supply.date\n  WHERE SAFE_DIVIDE(block_rewards, total_rewards) >= 0.01\n  ORDER BY block_rewards DESC\n),\ndaily_gini AS (\n  SELECT date,\n    -- (1 \u2212 2B) https:\/\/en.wikipedia.org\/wiki\/Gini_coefficient\n    1 - 2 * SUM((block_rewards * (rank - 1) + block_rewards \/ 2)) \/ COUNT(*) \/ SUM(block_rewards) AS gini\n  FROM ranked_daily_rewards\n  GROUP BY DATE\n)\nSELECT date,\n  gini,\n  AVG(gini) OVER (ORDER BY date ASC ROWS 7 PRECEDING) AS gini_sma_7,\n  AVG(gini) OVER (ORDER BY date ASC ROWS 30 PRECEDING) AS gini_sma_30\nFROM daily_gini\nORDER BY date ASC\n\"\"\"\n\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\nmining_reward_gini_by_date = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\nmining_reward_gini_by_date.head(10)\ntraces = []\nx = mining_reward_gini_by_date['date']\ngini_list = ['gini', 'gini_sma_7', 'gini_sma_30']\nfor gini in gini_list:\n    y = mining_reward_gini_by_date[gini]\n    trace = dict(\n        x=x,\n        y=y,\n        hoverinfo=f'{gini}',\n        mode='lines'\n    )\n    traces.append(trace)\nfig = dict(data=traces)\n\niplot(fig, validate=False)\n\"\"\"\n## Latest Daily Balance of Ethereum Classic (Top 20 Rich List)\n\nThis next query, adapted from this [Medium post by Evgeny Medvedev](https:\/\/medium.com\/google-cloud\/how-to-query-balances-for-all-ethereum-addresses-in-bigquery-fb594e4034a7) will get us the latest daily balance for Ethereum Classic.\n\nWe can order it by balance, getting us a nice rich list we can plot.\n\"\"\"\nquery = \"\"\"\nwith double_entry_book as (\n    -- debits\n    select to_address as address, value as value\n    from `bigquery-public-data.crypto_ethereum_classic.traces`\n    where to_address is not null\n    and status = 1\n    and (call_type not in ('delegatecall', 'callcode', 'staticcall') or call_type is null)\n    union all\n    -- credits\n    select from_address as address, -value as value\n    from `bigquery-public-data.crypto_ethereum_classic.traces`\n    where from_address is not null\n    and status = 1\n    and (call_type not in ('delegatecall', 'callcode', 'staticcall') or call_type is null)\n    union all\n    -- transaction fees debits\n    select miner as address, sum(cast(receipt_gas_used as numeric) * cast(gas_price as numeric)) as value\n    from `bigquery-public-data.crypto_ethereum_classic.transactions` as transactions\n    join `bigquery-public-data.crypto_ethereum_classic.blocks` as blocks on blocks.number = transactions.block_number\n    group by blocks.miner\n    union all\n    -- transaction fees credits\n    select from_address as address, -(cast(receipt_gas_used as numeric) * cast(gas_price as numeric)) as value\n    from `bigquery-public-data.crypto_ethereum_classic.transactions`\n)\nselect address, \nsum(value) \/ 1000000000 as balance\nfrom double_entry_book\ngroup by address\norder by balance desc\nlimit 20\n\"\"\"\n\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\ntop_address_rich_list = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\ntop_address_rich_list.head(10)\nlabels = top_address_rich_list['address']\nvalues = top_address_rich_list['balance']\n\ntrace = go.Pie(labels=labels, values=values)\n\niplot([trace])\n\"\"\"\n## Daily Top Balance Gini Coefficient\n\nNow, we will try getting daily top rich list from the genesis until now and then calculate the gini coefficient of the rich list.\n\nIn this context, the gini coefficient will be a measure of income inequality among wallet addresses based on how much ether balance is in each wallet. Of course, this assumes 1 person = 1 wallet, but a person can have multiple wallets. It will also query for top 10k addresses to be used in gini analysis. That will include exchange account balances, which we don't take into account eliminating from the dataset.\n\nThe query was written by from **[Evegeny Medvedev and Allen Day for this Google Blog Post](https:\/\/cloud.google.com\/blog\/products\/data-analytics\/introducing-six-new-cryptocurrencies-in-bigquery-public-datasets-and-how-to-analyze-them)**. I added some further analysis towards the end to measure the Simple Moving Average of the Gini for the past 7 and 30 days.\n\"\"\"\nquery = \"\"\"\nwith \ndouble_entry_book as (\n    -- debits\n    select to_address as address, value as value, block_timestamp\n    from `bigquery-public-data.crypto_ethereum_classic.traces`\n    where to_address is not null\n    and status = 1\n    and (call_type not in ('delegatecall', 'callcode', 'staticcall') or call_type is null)\n    union all\n    -- credits\n    select from_address as address, -value as value, block_timestamp\n    from `bigquery-public-data.crypto_ethereum_classic.traces`\n    where from_address is not null\n    and status = 1\n    and (call_type not in ('delegatecall', 'callcode', 'staticcall') or call_type is null)\n    union all\n    -- transaction fees debits\n    select miner as address, sum(cast(receipt_gas_used as numeric) * cast(gas_price as numeric)) as value, block_timestamp\n    from `bigquery-public-data.crypto_ethereum_classic.transactions` as transactions\n    join `bigquery-public-data.crypto_ethereum_classic.blocks` as blocks on blocks.number = transactions.block_number\n    group by blocks.miner, block_timestamp\n    union all\n    -- transaction fees credits\n    select from_address as address, -(cast(receipt_gas_used as numeric) * cast(gas_price as numeric)) as value, block_timestamp\n    from `bigquery-public-data.crypto_ethereum_classic.transactions`\n),\ndouble_entry_book_by_date as (\n    select \n        date(block_timestamp) as date, \n        address, \n        sum(value \/ POWER(10,0)) as value\n    from double_entry_book\n    group by address, date\n),\ndaily_balances_with_gaps as (\n    select \n        address, \n        date,\n        sum(value) over (partition by address order by date) as balance,\n        lead(date, 1, current_date()) over (partition by address order by date) as next_date\n        from double_entry_book_by_date\n),\ncalendar as (\n    select date from unnest(generate_date_array('2015-07-30', current_date())) as date\n),\ndaily_balances as (\n    select address, calendar.date, balance\n    from daily_balances_with_gaps\n    join calendar on daily_balances_with_gaps.date <= calendar.date and calendar.date < daily_balances_with_gaps.next_date\n),\n supply as (\n    select\n        date,\n        sum(balance) as daily_supply\n    from daily_balances\n    group by date\n),\nranked_daily_balances as (\n    select \n        daily_balances.date,\n        balance,\n        row_number() over (partition by daily_balances.date order by balance desc) as rank\n    from daily_balances\n    join supply on daily_balances.date = supply.date\n    where safe_divide(balance, daily_supply) >= 0.0001\n    ORDER BY safe_divide(balance, daily_supply) DESC\n), \ngini_daily as (\n   select\n    date,\n    -- (1 \u2212 2B) https:\/\/en.wikipedia.org\/wiki\/Gini_coefficient\n    1 - 2 * sum((balance * (rank - 1) + balance \/ 2)) \/ count(*) \/ sum(balance) as gini\n  from ranked_daily_balances\n  group by date\n)\nselect date,\n    gini,\n    avg(gini) over (order by date asc rows 7 preceding) as gini_sma7,\n    avg(gini) over (order by date asc rows 30 preceding) as gini_sma30\nfrom gini_daily\norder by date asc\n\"\"\"\n\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\ndaily_balance_gini = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\ndaily_balance_gini.head(10)\ntraces = []\nx = daily_balance_gini['date']\ngini_list = ['gini', 'gini_sma7', 'gini_sma30']\nfor gini in gini_list:\n    y = daily_balance_gini[gini]\n    trace = dict(\n        x=x,\n        y=y,\n        hoverinfo=f'{gini}',\n        mode='lines'\n    )\n    traces.append(trace)\nfig = dict(data=traces)\n\niplot(fig, validate=False)\n\"\"\"\n# Daily Hashrate\n\nHashrate is a measure of difficulty over block time. We can measure this by getting the delta time of each block timestamp from the previous block timestamp.\n\nWe can average it out by day. That is, the query can average out all difficulty and delta times per day and divide them by one another. We can further divide by 1 billion to get the GH\/s.\n\nWe will use the following query I wrote for the Daily Hashrate.\n\n```\n#standardSQL\n-- MIT License\n-- Copyright (c) 2019 Yaz Khoury, yaz.khoury@gmail.com\n\nWITH block_rows AS (\n  SELECT *, ROW_NUMBER() OVER (ORDER BY timestamp) AS rn\n  FROM `bigquery-public-data.crypto_ethereum_classic.blocks`\n),\ndelta_time AS (\n  SELECT\n  mp.timestamp AS block_time,\n  mp.difficulty AS difficulty,\n  TIMESTAMP_DIFF(mp.timestamp, mc.timestamp, SECOND) AS delta_block_time\n  FROM block_rows mc\n  JOIN block_rows mp\n  ON mc.rn = mp.rn - 1\n),\nhashrate_book AS (\n  SELECT TIMESTAMP_TRUNC(block_time, DAY) AS block_day,\n  AVG(delta_block_time) as daily_avg_block_time,\n  AVG(difficulty) as daily_avg_difficulty\n  FROM delta_time\n  GROUP BY TIMESTAMP_TRUNC(block_time, DAY)\n)\nSELECT block_day,\n(daily_avg_difficulty\/daily_avg_block_time)\/1000000000 as hashrate\nFROM hashrate_book\nORDER BY block_day ASC\n```\n\"\"\"\nquery = \"\"\"\n#standardSQL\n-- MIT License\n-- Copyright (c) 2019 Yaz Khoury, yaz.khoury@gmail.com\n\nWITH block_rows AS (\n  SELECT *, ROW_NUMBER() OVER (ORDER BY timestamp) AS rn\n  FROM `bigquery-public-data.crypto_ethereum_classic.blocks`\n),\ndelta_time AS (\n  SELECT\n  mp.timestamp AS block_time,\n  mp.difficulty AS difficulty,\n  TIMESTAMP_DIFF(mp.timestamp, mc.timestamp, SECOND) AS delta_block_time\n  FROM block_rows mc\n  JOIN block_rows mp\n  ON mc.rn = mp.rn - 1\n),\nhashrate_book AS (\n  SELECT TIMESTAMP_TRUNC(block_time, DAY) AS block_day,\n  AVG(delta_block_time) as daily_avg_block_time,\n  AVG(difficulty) as daily_avg_difficulty\n  FROM delta_time\n  GROUP BY TIMESTAMP_TRUNC(block_time, DAY)\n)\nSELECT block_day,\n(daily_avg_difficulty\/daily_avg_block_time)\/1000000000 as hashrate\nFROM hashrate_book\nORDER BY block_day ASC\n\"\"\"\n\nquery_job = client.query(query)\niterator = query_job.result()\nrows = list(iterator)\n# Transform the rows into a nice pandas dataframe\ndaily_hashrate = pd.DataFrame(data=[list(x.values()) for x in rows], columns=list(rows[0].keys()))\ndaily_hashrate.head(10)\ntrace = go.Scatter(\n    x=daily_hashrate['block_day'],\n    y=daily_hashrate['hashrate'],\n    mode='lines'\n)\ndata = [trace]\niplot(data)","meta":"{'source': 'AI4Code', 'id': 'e71422f3468894'}"}
{"id":"50732","text":"\"\"\"\n# Imports\n\"\"\"\n!pip install pmdarima\nimport pandas as pd\nimport numpy as np\nimport pandas_datareader as pdr\nimport datetime as dt\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\nimport seaborn as sns\n\n\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom pmdarima import auto_arima\nplt.rcParams['figure.figsize'] = (20,15)\nticker = \"GOOG\"\nstart = dt.datetime(2015,1,1)\ndf = pdr.get_data_yahoo(ticker,start=start)\ndf= df[['Close']]\ndf[:20]\ndf.plot()\nresult = seasonal_decompose(np.log(df), period=5) \nresult.plot();\n# Make dataframe more additive using log transform\ndf = np.log(df)\ndf\n\"\"\"\n# Stationarity\n\"\"\"\n'''Clearly, series is not stationary but we shall check it using adf test. We shall also check seasonality using acf'''\nprint(f'The p-value of the series is {adfuller(df.Close)[1]}')\n\"\"\"\nHence, series is not stationary. Next, we check the seasonality using acf plot.\n\"\"\"\nplot_acf(df.dropna(), lags=40);\n\"\"\"\n# Auto ARIMA\n\"\"\"\nmodel = auto_arima(df, max_p=6, max_q=3, m=5, seasonal=True, max_P=4, max_Q=4, max_D=2, max_order=None,\n                   d=None, trace=True, trend='ct',\n                   out_of_sample_size = int(len(df)*.2),\n                   error_action='ignore',   # we don't want to know if an order does not work\n                   suppress_warnings=True,  # we don't want convergence warnings\n                   stepwise=True) # set to stepwise)\n#model_fit = model.fit()\nmodel.summary()\nmodel = SARIMAX(df, order=(0,2,1), seasonal_order=(0,0,0,5))\nmodel_fit = model.fit()\nmodel_fit.summary()\nfc = model_fit.predict(-51)\nplt.plot(fc, label='Forecast')\nplt.plot(df[-50:], label='Original')\nplt.legend()\n\n#fc.plot()\n\"\"\"\nSo last 51 values were forecasted quiet well. But we shall see forecast in future (for period of 30 days) is not good. \n\"\"\"\nperiod = 30 # for forecast\nfc = model_fit.forecast(period)\nstart = dt.date.today() + dt.timedelta(days=1)\nfc_ind = pd.date_range(start=start, periods=period)\nfc.index = fc_ind\n\n# plotting last 25 + period values\nplt.plot(df[-25:],label='Original')\nplt.plot(fc, label='Future Forecast')\nplt.legend()\n\"\"\"\nWe will do LSTM in, TO BE SHARED soon!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5d5894baa5d18e'}"}
{"id":"108101","text":"\"\"\"\n# Amazon Alexa Reviews Analysis\n\"\"\"\n\"\"\"\n### The aim is to analyse Alexa's reviews by NLP. If the feedback is positive, the result is 1, else it is 0. Using logistic regression, I have tried to classify the feedback as positive or negative.\n\"\"\"\n\"\"\"\n### Importing Libraries\n\"\"\"\nimport pandas as pd\nimport nltk \nnltk.download('stopwords')                 # download the stopwords from NLTK\n\nimport re                                  # library for regular expression operations\nimport string                              # for string operations\n\nfrom nltk.corpus import stopwords          # module for stop words that come with NLTK\nfrom nltk.stem import PorterStemmer        # module for stemming\nfrom nltk.tokenize import TweetTokenizer   # module for tokenizing strings\n\nfrom sklearn.linear_model import LogisticRegression  \nfrom sklearn.feature_extraction.text import CountVectorizer  \nfrom sklearn.model_selection import train_test_split  \nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt            # library for visualization\nimport seaborn as sns\n\"\"\"\n### Getting our Data\n\"\"\"\ndf = pd.read_csv('..\/input\/amazon-alexa\/amazon_alexa.csv')\ndf\n\"\"\"\n### Data Preprocessing\n\"\"\"\ndf = df.drop(['rating', 'date', 'variation'], axis = 1)\ndf\ndf.isnull().any()  # checking for null values\ndf.info()\ndef process_rev(rev):\n    \"\"\"Process review function.\n    Input:\n        rev: a string containing a review\n    Output:\n        rev_clean: a list of words containing the processed review\n\n    \"\"\"\n    stemmer = PorterStemmer()\n    stopwords_english = stopwords.words('english')\n    # tokenize reviews\n    tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True,\n                               reduce_len=True)\n    rev_tokens = tokenizer.tokenize(rev)\n\n    rev_clean = []\n    for word in rev_tokens:\n        if (word not in stopwords_english and  # remove stopwords\n                word not in string.punctuation):  # remove punctuation\n            # rev_clean.append(word)\n            stem_word = stemmer.stem(word)  # stemming word\n            rev_clean.append(stem_word)\n\n    return rev_clean\n# using the process_rev function for:\n# 1. Removing stop words\n# 2. Tokenization\n# 3. Stemming\nA = []\na = df['verified_reviews']\nfor i in a:\n  i = process_rev(i)\n  A.append(i)\ndf['verified_reviews'] = A\ndf\n\"\"\"\n### Vectorizing\n\"\"\"\ncv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) \ndf['verified_reviews'] = df['verified_reviews'].apply(lambda x: \" \".join(x) )  # to join all words in the lists\nX = cv.fit_transform(df['verified_reviews'])  # predictor variable 'X'\ndf\ny = pd.DataFrame(df['feedback'])  # respose variable 'y'\ny.head()\n\"\"\"\n### Splitting for Training and Testing\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)  # splitting in the ratio 80:20\n\"\"\"\n### Model\n\"\"\"\nclassifier = LogisticRegression(random_state = 0)\nclassifier.fit(X_train, y_train)\n\"\"\"\n### Making Predictions\n\"\"\"\ny_pred = classifier.predict(X_test)\ny_pred\n\"\"\"\n### Checking Accuracy\n\"\"\"\nroc_auc_score(y_test, y_pred)\n\"\"\"\n# Predictions are 68.25% accurate.\n\"\"\"\n\"\"\"\n### Results' Visualization\n\"\"\"\ncm = confusion_matrix(y_test, y_pred)\ncm\nplt.figure(figsize=(6,6))\nsns.heatmap(cm, annot=True, fmt=\".0f\", linewidths=0.5, square = True, cmap = 'Pastel1')\nplt.ylabel('Actual label')\nplt.xlabel('Predicted label')\nall_sample_title = 'Accuracy Score: {0}'.format(roc_auc_score(y_test, y_pred))\nplt.title(all_sample_title, size = 15)","meta":"{'source': 'AI4Code', 'id': 'c6b60cfe496244'}"}
{"id":"123801","text":"\"\"\"\n<p style='text-align: center;'><span style=\"color: #000508; font-family: Segoe UI; font-size: 2.6em; font-weight: 300;\">SUPERVISED CONTRASTIVE LEARNING<\/span><\/p>\n\"\"\"\n\"\"\"\n![](https:\/\/paperswithcode.com\/media\/methods\/Screen_Shot_2020-06-12_at_12.43.14_PM.png)\n\"\"\"\n\"\"\"\nContrastive learning applied to self-supervised representation learning has seen a resurgence in recent years, leading to state of the art performance in the unsupervised training of deep image models. Modern batch contrastive approaches subsume or significantly outperform traditional contrastive losses such as triplet, max-margin and the N-pairs loss. In this work, we extend the self-supervised batch contrastive approach to the fully-supervised setting, allowing us to effectively leverage label information. <strong>Clusters of points belonging to the same class are pulled together in embedding space, while simultaneously pushing apart clusters of samples from different classes.<\/strong> We analyze two possible versions of the supervised contrastive (SupCon) loss, identifying the best-performing formulation of the loss. On ResNet-200, we achieve top-1 accuracy of 81.4% on the ImageNet dataset, which is 0.8% above the best number reported for this architecture. We show consistent outperformance over cross-entropy on other datasets and two ResNet variants. The loss shows benefits for robustness to natural corruptions and is more stable to hyperparameter settings such as optimizers and data augmentations\n\n*Supervised Contrastive Learning*: https:\/\/arxiv.org\/abs\/2004.11362\n\"\"\"\n\"\"\"\n<span style=\"text-align: center; color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Research Paper Walkthrough<\/span>\n\"\"\"\n\"\"\"\n<style>\n    iframe {display: block; margin: 0 auto;}\n<\/style>\n\n<iframe width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/MpdbFLXOOIw\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n\"\"\"\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Install Libraries<\/span>\n\"\"\"\n!pip install -q timm pytorch-metric-learning\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Import Packages<\/span>\n\"\"\"\nimport os\nimport cv2\nimport copy\nimport time\nimport random\nimport math\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.cuda import amp\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, GroupKFold\nfrom sklearn.metrics import roc_auc_score, f1_score\n\nfrom tqdm.notebook import tqdm\nfrom collections import defaultdict\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\nimport timm\nfrom pytorch_metric_learning import losses\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Training Configuration<\/span>\n\"\"\"\nclass CFG:\n    seed = 42\n    model_name = 'tf_efficientnet_b4_ns'\n    img_size = 512\n    scheduler = 'CosineAnnealingLR'\n    T_max = 10\n    lr = 1e-5\n    min_lr = 1e-6\n    batch_size = 16\n    weight_decay = 1e-6\n    num_epochs = 10\n    num_classes = 11014\n    embedding_size = 512\n    n_fold = 5\n    n_accumulate = 4\n    temperature = 0.1\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nTRAIN_DIR = '..\/input\/shopee-product-matching\/train_images\/'\nTEST_DIR = '..\/input\/shopee-product-matching\/test_images\/'\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Set Seed for Reproducibility<\/span>\n\"\"\"\ndef set_seed(seed = 42):\n    '''Sets the seed of the entire notebook so results are the same every time we run.\n    This is for REPRODUCIBILITY.'''\n    np.random.seed(seed)\n    random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    \n    # When running on the CuDNN backend, two further options must be set\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n    \n    # Set a fixed value for the hash seed\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    \n\nset_seed(CFG.seed)\ndf_train = pd.read_csv('..\/input\/shopee-folds\/folds.csv')\ndf_train['file_path'] = df_train.image.apply(lambda x: os.path.join(TRAIN_DIR, x))\ndf_train.head(5)\nle = LabelEncoder()\ndf_train.label_group = le.fit_transform(df_train.label_group)\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Dataset Class<\/span>\n\"\"\"\nclass ShopeeDataset(Dataset):\n    def __init__(self, root_dir, df, transforms=None):\n        self.root_dir = root_dir\n        self.df = df\n        self.transforms = transforms\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        img_path = self.df.iloc[index, -1]\n        img = cv2.imread(img_path)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        label = self.df.iloc[index, -3]\n        \n        if self.transforms:\n            img = self.transforms(image=img)[\"image\"]\n            \n        return img, label\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Augmentations & Transforms<\/span>\n\"\"\"\ndata_transforms = {\n    \"train\": A.Compose([\n        A.Resize(CFG.img_size, CFG.img_size),\n        A.HorizontalFlip(p=0.5),\n        A.RandomBrightnessContrast(\n                brightness_limit=(-0.1,0.1), \n                contrast_limit=(-0.1, 0.1), \n                p=0.5\n            ),\n        A.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            ),\n        ToTensorV2()], p=1.),\n    \n    \"valid\": A.Compose([\n        A.Resize(CFG.img_size, CFG.img_size),\n        A.Normalize(\n                mean=[0.485, 0.456, 0.406], \n                std=[0.229, 0.224, 0.225], \n                max_pixel_value=255.0, \n                p=1.0\n            ),\n        ToTensorV2()], p=1.)\n}\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Training Function<\/span>\n\n<p> Uses Automatic Mixed Precision to speed up training process and Gradient Accumulation to increase batch size<br>\nRefer this <a href=\"https:\/\/www.kaggle.com\/c\/cassava-leaf-disease-classification\/discussion\/199631\">Discussion<\/a> to know more about mixed precision training <br>\nRefer this <a href=\"https:\/\/www.kaggle.com\/c\/cassava-leaf-disease-classification\/discussion\/217133\">Discussion<\/a> to know more about gradient accumulation<\/p>\n\"\"\"\ndef train_model(model, criterion, optimizer, scheduler, num_epochs, dataloaders, dataset_sizes, device, fold):\n    start = time.time()\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_loss = np.inf\n    history = defaultdict(list)\n    scaler = amp.GradScaler()\n\n    for step, epoch in enumerate(range(1,num_epochs+1)):\n        print('Epoch {}\/{}'.format(epoch, num_epochs))\n        print('-' * 10)\n\n        # Each epoch has a training and validation phase\n        for phase in ['train','valid']:\n            if(phase == 'train'):\n                model.train() # Set model to training mode\n            else:\n                model.eval() # Set model to evaluation mode\n            \n            running_loss = 0.0\n            \n            # Iterate over data\n            for inputs,labels in tqdm(dataloaders[phase]):\n                inputs = inputs.to(CFG.device)\n                labels = labels.to(CFG.device)\n\n                # forward\n                # track history if only in train\n                with torch.set_grad_enabled(phase == 'train'):\n                    with amp.autocast(enabled=True):\n                        outputs = model(inputs)\n                        loss = criterion(outputs, labels)\n                        loss = loss \/ CFG.n_accumulate\n                    \n                    # backward only if in training phase\n                    if phase == 'train':\n                        scaler.scale(loss).backward()\n\n                    # optimize only if in training phase\n                    if phase == 'train' and (step + 1) % CFG.n_accumulate == 0:\n                        scaler.step(optimizer)\n                        scaler.update()\n                        scheduler.step()\n                        \n                        # zero the parameter gradients\n                        optimizer.zero_grad()\n\n\n                running_loss += loss.item()*inputs.size(0)\n            \n            epoch_loss = running_loss\/dataset_sizes[phase]            \n            history[phase + ' loss'].append(epoch_loss)\n\n            print('{} Loss: {:.4f}'.format(\n                phase, epoch_loss))\n            \n            # deep copy the model\n            if phase=='valid' and epoch_loss <= best_loss:\n                best_loss = epoch_loss\n                best_model_wts = copy.deepcopy(model.state_dict())\n                PATH = f\"Fold{fold}_{best_loss}_epoch_{epoch}.bin\"\n                torch.save(model.state_dict(), PATH)\n\n        print()\n\n    end = time.time()\n    time_elapsed = end - start\n    print('Training complete in {:.0f}h {:.0f}m {:.0f}s'.format(\n        time_elapsed \/\/ 3600, (time_elapsed % 3600) \/\/ 60, (time_elapsed % 3600) % 60))\n    print(\"Best Loss \",best_loss)\n\n    # load best model weights\n    model.load_state_dict(best_model_wts)\n    return model, history\ndef run_fold(model, criterion, optimizer, scheduler, device, fold, num_epochs=10):\n    valid_df = df_train[df_train.fold == fold]\n    train_df = df_train[df_train.fold != fold]\n    \n    train_data = ShopeeDataset(TRAIN_DIR, train_df, transforms=data_transforms[\"train\"])\n    valid_data = ShopeeDataset(TRAIN_DIR, valid_df, transforms=data_transforms[\"valid\"])\n    \n    dataset_sizes = {\n        'train' : len(train_data),\n        'valid' : len(valid_data)\n    }\n    \n    train_loader = DataLoader(dataset=train_data, batch_size=CFG.batch_size, num_workers=4, pin_memory=True, shuffle=True)\n    valid_loader = DataLoader(dataset=valid_data, batch_size=CFG.batch_size, num_workers=4, pin_memory=True, shuffle=False)\n    \n    dataloaders = {\n        'train' : train_loader,\n        'valid' : valid_loader\n    }\n\n    model, history = train_model(model, criterion, optimizer, scheduler, num_epochs, dataloaders, dataset_sizes, device, fold)\n    \n    return model, history\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Load Model<\/span>\n\"\"\"\nmodel = timm.create_model(CFG.model_name, pretrained=True)\nin_features = model.classifier.in_features\nmodel.classifier = nn.Linear(in_features, CFG.embedding_size)\n\nout = model(torch.randn(1, 3, CFG.img_size, CFG.img_size))\nprint(f'Embedding shape: {out.shape}')\n\nmodel.to(CFG.device);\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Custom Implementation<\/span>\n\"\"\"\n\"\"\"\n<span style=\"color: #000508; font-family: Segoe UI; font-size: 2.0em; font-weight: 300;\">Implementation converted to Pytorch from <a href=\"https:\/\/www.kaggle.com\/dimitreoliveira\/cassava-leaf-supervised-contrastive-learning\">this<\/a> amazing notebook<\/span>\n\"\"\"\nclass SupervisedContrastiveLoss(nn.Module):\n    def __init__(self, temperature=0.1):\n        super(SupervisedContrastiveLoss, self).__init__()\n        self.temperature = temperature\n\n    def forward(self, feature_vectors, labels):\n        # Normalize feature vectors\n        feature_vectors_normalized = F.normalize(feature_vectors, p=2, dim=1)\n        # Compute logits\n        logits = torch.div(\n            torch.matmul(\n                feature_vectors_normalized, torch.transpose(feature_vectors_normalized, 0, 1)\n            ),\n            self.temperature,\n        )\n        return losses.NTXentLoss(temperature=0.5)(logits, torch.squeeze(labels))\n\"\"\"\nVersion 5: Loss from Pytorch Metric Learning Library <br>\nVersion 6: Custom Implementation with temperature for NTXentLoss 0.07 <br>\nVersion 7: Custom Implementation with temperature for NTXentLoss 0.5\n\"\"\"\n# Custom Implementation\ncriterion = SupervisedContrastiveLoss(temperature=CFG.temperature).to(CFG.device)\n# criterion = losses.SupConLoss(temperature=CFG.temperature).to(CFG.device)\noptimizer = optim.Adam(model.parameters(), lr=CFG.lr, weight_decay=CFG.weight_decay)\nscheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=CFG.T_max, eta_min=CFG.min_lr)\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Run Fold 0<\/span>\n\"\"\"\nmodel, history = run_fold(model, criterion, optimizer, scheduler, device=CFG.device, fold=0, num_epochs=CFG.num_epochs)\n\"\"\"\n<span style=\"color: #0087e4; font-family: Segoe UI; font-size: 2.3em; font-weight: 300;\">Visualize Training & Validation Metrics<\/span>\n\"\"\"\nplt.style.use('fivethirtyeight')\nplt.rcParams[\"font.size\"] = \"20\"\nfig = plt.figure(figsize=(22,8))\nepochs = list(range(CFG.num_epochs))\nplt.plot(epochs, history['train loss'], label='train loss')\nplt.plot(epochs, history['valid loss'], label='valid loss')\nplt.ylabel('Loss', fontsize=20)\nplt.xlabel('Epoch', fontsize=20)\nplt.legend()\nplt.title('Loss Curve');\n\"\"\"\n![Upvote!](https:\/\/img.shields.io\/badge\/Upvote-If%20you%20like%20my%20work-07b3c8?style=for-the-badge&logo=kaggle)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e3abb9a916283a'}"}
{"id":"137399","text":"\"\"\"\n# Video game success EDA \n\"\"\"\n\"\"\"\nIn this document, I tried to conduct a visual analysis of data from video game datasets.\n\n\n\"\"\"\n\"\"\"\nI hope you like what I did, I will be glad to comments.\n\nI judged the data not biased, as at the moment I have a ps5, xbox series s, nintendo switch and nintendo 3ds, yes, it's a bit overkill, but I like it)\n\"\"\"\n\"\"\"\n# Importing libraries\n\"\"\"\nimport math\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport datetime\nimport seaborn as sns\nimport re\nimport warnings\nfrom scipy import stats as st\nimport matplotlib.lines as mlines\n\nwarnings.filterwarnings('ignore')\n\"\"\"\n# Local functions\n\"\"\"\n\"\"\"\n**The description of the functions is written in Russian for an obvious reason - I'm from Russia)**\n\"\"\"\ndef fills_good(data, main_column, function, group_columns):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u043f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0434\u0430\u043d\u043d\u044b\u0445, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0437\u0430\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438;\n    main_column - \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u043f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u044b \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f;\n    function - \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0431\u0443\u0434\u0435\u0442 \u043f\u0440\u0438\u043c\u0435\u043d\u044f\u0442\u044c\u0441\u044f \u043f\u0440\u0438\n         \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0438 \u043f\u0443\u0441\u0442\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0432 \u043a\u0430\u0432\u044b\u0447\u043a\u0430\u0445 ('mean','median'...);\n    group_columns - \u0441\u0442\u043e\u043b\u0431\u0446\u044b \u0434\u043b\u044f \u0433\u0440\u0443\u043f\u043f\u0438\u0440\u043e\u0432\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 \u0432 \u0432\u0438\u0434\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 [...] \n         \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0431\u0443\u0434\u0435\u0442 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438\n         \u0441 \u0433\u0440\u0443\u043f\u043f\u0438\u0440\u043e\u0432\u043a\u043e\u0439 \u043f\u043e \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u043c \u0441\u0442\u043e\u043b\u0431\u0446\u0430\u043c.\n    \"\"\"\n    \n    data[main_column] = data[main_column].fillna(data.groupby(group_columns)[main_column].transform(function))\n    \ndef pre_research(data, column, range_min=0, range_max=0, clr='blue'):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u0440\u0435\u0434\u0432\u0430\u0440\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0433\u043e \u0430\u043d\u0430\u043b\u0438\u0437\u0430 \u0434\u0430\u043d\u043d\u044b\u0445\n    \u0414\u0430\u043d\u043d\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u044b\u0432\u0435\u0434\u0435\u0442 \u0443\u043d\u0438\u043a\u0430\u043b\u044c\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u043e\u0433\u043e\n    \u0441\u0442\u043e\u043b\u0431\u0446\u0430 \u0438 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u0442 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443.\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0434\u0430\u043d\u043d\u044b\u0445, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043d\u0443\u0436\u043d\u043e \u0430\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c;\n    column - \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0441\u0442\u043e\u043b\u0431\u0446\u0430, \u043f\u043e \u043a\u043e\u0442\u043e\u0440\u043e\u043c\u0443 \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u0442\u0441\u044f \u0430\u043d\u0430\u043b\u0438\u0437;\n    range_min, range_max - \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435\n        \u0433\u0440\u0430\u043d\u0438\u0447\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0435 \u043d\u0430 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443\n        \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u044e\u0442\u0441\u044f \u043c\u0438\u043d\u0438\u043c\u0443\u043c\u043e\u043c \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0443\u043c\u043e\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0441\u0442\u043e\u043b\u0431\u0446\u0430, \n        \u043f\u0440\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u043c\u043e\u0436\u043d\u043e \u0432\u043d\u0435\u0441\u0442\u0438 \u043d\u0443\u0436\u043d\u044b\u0435 \u0437\u0430\u043d\u0447\u0435\u043d\u0438\u044f \u0434\u043b\u044f \n        \u043c\u0430\u0441\u0448\u0442\u0430\u0431\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b.\n    clr - \u0446\u0432\u0435\u0442 \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b.\n    \"\"\"\n    \n    print(f'1% percentile: {data[column].quantile(.1)}')\n    print(f'50% percentile: {data[column].quantile(.50)}')\n    print(f'99% percentile: {data[column].quantile(.99)}')\n    # \u0412 \u0441\u0442\u043e\u043b\u0431\u0446\u0435 \u0435\u0441\u0442\u044c \u0432\u044b\u0431\u0440\u043e\u0441\u044b \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439, \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \n    # \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043d\u044f\u0442\u044c \u043a\u0430\u043a \u0447\u0430\u0441\u0442\u043e \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u044e\u0442\u0441\u044f \u0431\u043e\u043b\u044c\u0448\u0438\u0435 \u0438 \u043e\u0447\u0435\u043d\u044c \u043c\u0430\u043b\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n    data1 = data.copy()\n    fig = plt.figure(figsize=(15, 6)) \n    if range_min==range_max:\n        range_min = data[column].min()\n        range_max = data[column].max()\n    else:\n        data1 = data1[data1[column]<data1[column].quantile(range_max)]\n        data1 =  data1[data1[column]>data1[column].quantile(range_min)]\n    \n    sns.histplot(data1[column], kde=True, bins=len(data1[column].unique()), color=clr)\n    plt.title(f\"{column} histogram\")\n    plt.ylabel(f\"{column} count\")\n    plt.xlabel(column)\n\n    plt.show()\n    \n\ndef print_hist(series,bins, title):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    series - \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0433\u0438\u0441\u0442\u043e\u0433\u0440\u0430\u043c\u043c\u044b;\n    bins - \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0442\u0432\u043e \u043a\u043e\u0440\u0437\u0438\u043d;\n    title - \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0438\u043a\u0430.\n    \n        \u0414\u043b\u044f \u0443\u043b\u0443\u0447\u0448\u0435\u043d\u0438\u044f \u0432\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\n    \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f\n    \u0441\u0447\u0438\u0442\u0430\u044e\u0442\u0441\u044f \u043f\u043e 1 \u0438 99\u043c\u0443 \u043f\u0435\u0440\u0441\u0435\u043d\u0442\u0438\u043b\u044e\n    \"\"\"   \n    \n    fig = plt.figure(figsize=(15, 6)) \n    min_range = series.quantile(.1)\n    max_range = series.quantile(.99)\n    hist = plt.hist(series, bins, range = (min_range,max_range))\n    grid1 = plt.grid(True)\n    plt.title(title)\n    plt.show()\n    print(f'Mean value: {round(series.mean(),2)}')\n    print(f'Median value: {round(series.median(),2)}')\n    \n\ndef print_matrix(data, sub_columns, min_size=9, max_size=9):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0434\u0438\u0430\u0433\u0440\u0430\u043c\u043c \u0440\u0430\u0441\u0441\u0435\u044f\u043d\u0438\u044f\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445;\n    main_column - \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u0439 \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u0434\u0430\u043d\u043d\u044b\u0445, \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u0442\u043e\u0440\u043e\u0433\u043e \u0431\u0443\u0434\u0435\u0442\n        \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u0430\u043d\u0430\u043b\u0438\u0437 - '\u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435_\u0441\u0442\u043e\u043b\u0431\u0446\u0430';\n    sub_columns - \u0432\u0441\u043f\u043e\u043c\u043e\u0433\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0441\u0442\u043e\u043b\u0431\u0446\u044b, \u0432\u043b\u0438\u044f\u043d\u0438\u0435 \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u0430\n        \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u0439 \u0441\u0442\u043e\u043b\u0431\u0435\u0446 \u043c\u044b \u043e\u0446\u0435\u043d\u0438\u0432\u0430\u0435\u043c - ['1','2','3',...];\n    min_size, max_size - \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u0430\n        \u043a\u0430\u0436\u0434\u043e\u0439 \u044f\u0447\u0435\u0439\u043a\u0438 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432 \u0434\u044e\u0439\u043c\u0430\u0445 (\u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - 9 \u0434\u044e\u0439\u043c\u043e\u0432).\n    \"\"\"\n    \n    #pivot_data = data.pivot_table(index = main_column, \n    #                        values = sub_columns)\n    pivot_data = data[sub_columns]\n    pd.plotting.scatter_matrix(pivot_data, diagonal = 'kde',figsize=(min_size, max_size)) \n\ndef print_scatter(data, x, y, labels, clr = \"g\", min_size=15, max_size=8):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0434\u0438\u0430\u0433\u0440\u0430\u043c\u043c \u0440\u0430\u0441\u0441\u0435\u044f\u043d\u0438\u044f\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445;\n    x, y - \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432, \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0431\u0443\u0434\u0435\u0442\n        \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u0430\u043d\u0430\u043b\u0438\u0437 - '\u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435_\u0441\u0442\u043e\u043b\u0431\u0446\u0430';\n    labels - \u043c\u0430\u0441\u0441\u0438\u0432 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0439 \u0434\u0438\u0430\u0433\u0440\u0430\u043c\u043c\u044b \u0438 \u043e\u0441\u0435\u0439 - ['\u0417\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a','x_name','y_name'];\n    clr - \u0446\u0432\u0435\u0442 \u0442\u043e\u0447\u0435\u043a;\n    min_size, max_size - \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u0430\n        \u043a\u0430\u0436\u0434\u043e\u0439 \u044f\u0447\u0435\u0439\u043a\u0438 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u0432 \u0434\u044e\u0439\u043c\u0430\u0445 (\u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - 9 \u0434\u044e\u0439\u043c\u043e\u0432).\n    \"\"\"\n    \n    plt.figure(figsize=(min_size, max_size)) \n    plt.scatter( x, y, data=data,alpha=0.2,color=clr)\n    plt.title(labels[0],fontsize=15)\n    plt.xlabel(labels[1],fontsize=13)\n    plt.ylabel(labels[2],fontsize=13)\n    plt.grid()\n    plt.show()\n    \ndef print_plt_lines(data, categ_column, x, y, lines, labels=['','','']):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u0438\u0445 \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432 \u043d\u0430 \u043e\u0434\u043d\u0438\u0445 \u043a\u043e\u043e\u0440\u0434\u0438\u043d\u0430\u0442\u0430\u0445\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445;\n    x, y - \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432, \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0431\u0443\u0434\u0435\u0442\n        \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u0430\u043d\u0430\u043b\u0438\u0437 - '\u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435_\u0441\u0442\u043e\u043b\u0431\u0446\u0430';\n    lines - \u043c\u0430\u0441\u0441\u0438\u0432 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0439 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 - ['name1','name2','name3'.....];\n    labels - \u043c\u0430\u0441\u0441\u0438\u0432 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0439 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 - ['\u0417\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a','x_name','y_name'];\n\n    \"\"\"\n    \n    fig = plt.figure(figsize=(15, 6)) \n    for i in lines:\n        plot_data = data[data[categ_column]==i]\n        plt.plot( \n            plot_data[x],\n            plot_data[y], \n            linestyle= '-', \n#             marker='o',\n            linewidth=2, \n            alpha=0.9,\n            )\n    plt.grid(True)\n    plt.title(labels[0])\n    plt.xlabel(labels[1])\n    plt.ylabel(labels[2])\n    plt.legend(lines)\n    plt.show()\n\n    \ndef lolipop_plot(data, y, x,labels, color1='orange', color2='gray', color_lim=150):\n    \"\"\"\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f Lolipop \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432:\n\n    \u0414\u043b\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043f\u0435\u0440\u0435\u0434\u0430\u0442\u044c \u0435\u0439\n    \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0435 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u044b:\n    \n    data - \u043c\u0430\u0441\u0441\u0438\u0432 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445;\n    x, y - \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432, \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u0431\u0443\u0434\u0435\u0442\n        \u043f\u0440\u043e\u0432\u043e\u0434\u0438\u0442\u044c\u0441\u044f \u0430\u043d\u0430\u043b\u0438\u0437 - '\u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0435_\u0441\u0442\u043e\u043b\u0431\u0446\u0430';\n    labels - \u043c\u0430\u0441\u0441\u0438\u0432 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u0439 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445 - ['\u0417\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a','x_name','y_name'];\n    color1 - \u0446\u0432\u0435\u0442 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u044f, \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - 'orange';\n    color2 - \u0446\u0432\u0435\u0442 \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0432\u044b\u0434\u0435\u043b\u0435\u043d\u0438\u044f, \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - 'gray'; \n    color_lim - \u0433\u0440\u0430\u043d\u0438\u0446\u0430 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f \u0446\u0432\u0435\u0442\u0430 \u043f\u043e \u043e\u0441\u0438 \u0425, \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e - 150.\n\n    \"\"\"\n    \n    \n    data = data.sort_values(by = y)\n    \n    my_range=range(1,len(data.index)+1)\n    my_color=np.where(data[y] > color_lim, color1, color2)\n    fig = plt.figure(figsize=(15, 6)) \n    plt.hlines(y=my_range, xmin=0, xmax=data[y], color=my_color)\n    plt.scatter(data[y], my_range, color=my_color, alpha=1)\n    plt.yticks(my_range, data[x])\n    plt.title(labels[0])\n    plt.xlabel(labels[1])\n    plt.ylabel(labels[2])\n    plt.grid()\n    plt.show()\n\"\"\"\n# Exploring data from a files\n\"\"\"\n\"\"\"\n## Data description\n\"\"\"\n\"\"\"\n    Name \u2014 the name of the game\n    Platform \u2014 videogame platform\n    year \u2014 year of release\n    Genre \u2014 genre of the game\n    NA_sales \u2014 sales in North America\n    EU_sales \u2014 sales in Europe\n    JP_sales \u2014 sales in Japan\n    Other_sales \u2014 sales in other countries (Russia for example)\n    Critic_Score \u2014 critic score (maximum - 100)\n    User_Score \u2014 user score (maximum - 10)\n    Rating rating from the ESRB organization (eng. Entertainment Software Rating Board). This association determines the rating of computer games and assigns them a suitable age category.\n\nThe data is collected from two sets from kaggle, in the description above the columns that we will use in EDA\n\"\"\"\n\"\"\"\n## Exploring data\n\"\"\"\ndf_sales = pd.read_csv('..\/input\/videogamesales\/vgsales.csv')\ndf_sales['Name']\ndf_score = pd.read_csv('..\/input\/video-game-sales-with-ratings\/Video_Games_Sales_as_at_22_Dec_2016.csv')\ndf_score = df_score.rename({\"Year_of_Release\":\"Year\"}, axis=1)\ndf = df_score.merge(df_sales, how='left')\ndf.info()\ndf\n\"\"\"\nWe will reduce the column names to lowercase:\n\"\"\"\ndf.columns = df.columns.str.lower()\ndf\n\"\"\"\nAt the stage of data preprocessing, the following changes must be made:\n\n| col name        | Type replace           | Data gaps  |\n| ------------- |:-------------:| -----:|\n|  name     | not required | delete rows |\n| platform\t | not required    |    not required |\n| year\t | int    |   median replase |\n| genre\t | not required    |    delete rows |\n| na_sales\t | not required    |    not required |\n| eu_sales\t | not required    |    not required |\n| jp_sales\t | not required    |    not required |\n| other_sales\t | not required    |    not required |\n| critic_score\t | not required    |    not required |\n| user_score\t | float    |    not required |\n| rating\t | not required    |    fill- \"no_rate\" |\n\"\"\"\n\"\"\"\n# Data preprocessing\n\"\"\"\ndf = df.dropna(subset=['name'])\nfills_good(df, 'year', 'median', 'platform')\ndf['year'] = df['year'].astype('int')\npre_research(df, 'year', clr='orange')\n\"\"\"\nIn 2007-2010, there was a noticeable surge in the game development market\n\"\"\"\npre_research(df, 'na_sales', range_max=0.99, clr='cyan')\n\"\"\"\nLet's see which games are knocked out for the 999th percentile\n\"\"\"\ndf.loc[df['na_sales'] > df['na_sales'].quantile(.999)]\n\"\"\"\nNo emissions, all games are real mastodons of the market. Most of them are from Nintendo, who would doubt it)\n\"\"\"\npre_research(df, 'eu_sales', range_max=0.99, clr='blue')\npre_research(df, 'jp_sales', range_max=0.99, clr='red')\npre_research(df, 'other_sales', range_max=0.99, clr='olive')\npre_research(df, 'critic_score', clr='green')\n\"\"\"\nThere are tbd values in the data of the 'user_score' column, according to the metacritic site tbd is an insufficient number of ratings (below 4x), so we will replace these values in the column with NaN\n\"\"\"\ndf.loc[df['user_score']=='tbd','user_score'] = np.nan\ndf['user_score'] = df['user_score'].astype('float')\n\n# Let's bring the user ratings to the same scale as the critics' ratings\n\ndf['user_score'] = df['user_score']*10\npre_research(df, 'user_score', clr='purple')\ndf['rating'] = df['rating'].fillna('no_rate')\ndf\ndf['sum_sales'] = df[['na_sales','eu_sales','jp_sales','other_sales']].sum(axis=1)\ndf\n\"\"\"\n# Research data analysis\n\"\"\"\n\"\"\"\nLet's look at how many games were released in different years.\n\"\"\"\npre_research(df, 'year')\ndf.groupby('year')['year'].count()\n\n\"\"\"\nWe will not take into account the data below 1995 in the EDA, at that time there was the first noticeable growth of the gaming industry, which is most likely associated with the widespread distribution of CDs and consoles\n\"\"\"\ndf = df.query('year >= 1995').copy()\n\"\"\"\nLet's see how sales by platform have changed. Select the platforms with the highest total sales and build a distribution by year. For what characteristic period of time do new platforms appear and old ones disappear?\n\"\"\"\ndf_sales_by_year = df.pivot_table(index = ['year',\n                                           'platform'], \n                                  values = 'sum_sales', \n                                  aggfunc = 'sum').reset_index()\ndf_sales_by_year\n\n\"\"\"\nWe calculate the lifetime of different gaming platforms\n\"\"\"\ndf_sales_by_year.groupby('platform')['platform'].count().sort_values(ascending = False)\ndf_sales_by_year.groupby('platform')['sum_sales'].sum().sort_values(ascending = False)\n\"\"\"\n-------------\nWe will build various graphs to visualize and compare the indicators of different platforms\n\"\"\"\nlabels = ['Total sales of PlayStation and PC games by year',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_sales_by_year, \n                'platform', \n                'year', \n                'sum_sales', \n                ['PS', \n                 'PS2', \n                 'PS3', \n                 'PS4', \n                 'PSP',\n                 'PSV',\n                 'PC',],\n               labels)\n\"\"\"\nThe graph shows that the previous generation of PS consoles is supported from 4 to 6 years\n\nThe peak of the number of copies of games sold on this platform = 2001-2005, just a year after the release of ps2, when video game manufacturers fully began to master the new hardware, in these years there were continuations of already iconic titles from ps1, as well as new games that later received sequels on new generations of consoles\n\nPSP and PSVita are portable consoles, it is not surprising that the sales charts of these consoles are lower than the rest of the charts\n\nPS Vita - Sony's most failed console\n\"\"\"\nlabels = ['Total sales of games on Xbox and PC platforms by year',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_sales_by_year, \n                'platform', \n                'year', \n                'sum_sales', \n                [ 'XB', \n                 'X360',\n                 'XOne',\n                 'PC',\n                ],\n               labels)\n\"\"\"\nMicrosoft entered the video game industry in 2000 with a competitor to the Playstation 2 console in the Xbox video.\n\nFrom the graphs, we can conclude about the colossal success in terms of selling Xbox 360 console games compared to the previous console, it's too early to judge sales on the new Xbox One console for 2014, but the dynamics of the first years of sales are not encouraging.\n\nXbox consoles are supported for 4 years after the release of the new version\n\"\"\"\nlabels = ['Total sales of games on the Nintendo and PC platforms by year',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_sales_by_year, \n                'platform', \n                'year', \n                'sum_sales', \n                [ 'GB', \n                 'SNES',\n                 'N64',\n                 'Wii',\n                 'WiiU',\n                 'GC',\n                 'DS','PC',\n                ],\n               labels)\n\"\"\"\nNintendo consoles are clearly different from Xbox and PS, they released gaming consoles before 1995 and occupied their niche market with exclusive game series that fans of this company loved.\n\nWe also see that the cycle of production of Nintendo consoles is very different from competitors and the life cycle of each console of this company is unique\n\nIt is worth noting that the Nintendo DS console is a portable console, it should be taken into account only in comparison with other portable consoles, since most titles for this type of device come out at their own prices and are exclusive.\n\"\"\"\n\"\"\"\nLet's compare the sales of games on stationary consoles Nintendo, Xbox and PS, as well as on PC.\n\"\"\"\nlabels = ['Total sales of games on the Nintendo, Xbox, PS and PC platforms by year',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_sales_by_year, \n                'platform', \n                'year', \n                'sum_sales', \n                [ 'PS', \n                 'PS2', \n                 'PS3', \n                 'PS4', \n                 'XB', \n                 'X360',\n                 'XOne',\n                 'Wii',\n                 'WiiU',\n                 'PC',\n                ],\n               labels)\n\"\"\"\nin 2005-2010, the Xbox 360 console was clearly ahead of its competitor in terms of game sales, this is due to the fact that Microsoft released its console a year earlier and the cost of the console was lower than the cost of the PS3. \n\nThere were also few good titles in the launch line of PS3 games, and the Xbox360 console had both new games and compatibility with old games and discs.\n\nBy 2010, Sony had already managed to release a sufficient number of exclusive games, which allowed it to outpace competitors in sales of games on the console.\n\nIf we compare the sales charts of games on the new generation of consoles, it is clearly visible that the PlayStation 4 console is 2 times ahead of the Xbox One console in sales in 2014-2016 (even if the fir provided incomplete data for 2016)\n\nPersonal computers have been lagging behind in terms of game sales for all years, most likely this is due to the ease of piracy on this type of device\n\"\"\"\n\"\"\"\n----------------------\nFrom the data considered, we can determine the actual period for the study.\n\nWe will consider the video game market in accordance with the past and current generation of consoles, i.e. since 2004, as well as limit the choice of data \n\nLet's divide our data into 2 categories: stationary and portable consoles\n\nStationary: 'PS3', 'PS4', 'X360','XOne', 'Wii', 'WiiU', as well as 'PC'\n\nPortable: 'DS', 'PSP', 'PSV'\n\n\nLet's highlight the corresponding graphs in the table and set a mark on the portability of consoles for convenience\n\"\"\"\ndf_sales_by_year = df_sales_by_year.query('(year >=2004)&(platform in [\"PS3\",\"PS4\", \"X360\",\"XOne\", \"Wii\", \"WiiU\", \"PC\",\"DS\", \"PSP\", \"PSV\"])')\ndf_sales_by_year['portable'] = 0\ndf_sales_by_year.loc[df_sales_by_year['platform'].apply(lambda x:x in [ 'DS', 'PSP', 'PSV']), 'portable'] = 1\n\"\"\"\nLet's build a graph for stationary consoles\n\"\"\"\nlabels = ['Total sales of games on the Nintendo, Xbox, PS and PC platforms by year',\n          'Year',\n          '\u043c',\n          ]\nprint_plt_lines(df_sales_by_year.query('year >=2005'), \n                'platform', \n                'year', \n                'sum_sales', \n                [ 'PS3', 'PS4', 'X360','XOne', 'Wii', 'WiiU', 'PC',\n                ],\n               labels)\n\"\"\"\nLet's build a graph for portable consoles\n\"\"\"\nlabels = ['Total sales of games on portable consoles by year',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_sales_by_year, \n                'platform', \n                'year', \n                'sum_sales', \n                [ 'DS', 'PSP', 'PSV',\n                ],\n               labels)\n\"\"\"\nConsider the total sales for each gaming device for the entire period of life under consideration\n\"\"\"\ndf_lolipop = df_sales_by_year.pivot_table(index = 'platform', \n                                          values = 'sum_sales', \n                                          aggfunc = 'sum').reset_index().sort_values(by = 'sum_sales')\ndf_lolipop['portable'] = 0\ndf_lolipop.loc[df_lolipop['platform'].apply(lambda x:x in [ 'DS', 'PSP', 'PSV']), 'portable'] = 1\n\nmy_range=range(1,len(df_lolipop.index)+1)\nmy_color=np.where(df_lolipop ['portable'] == 1, 'orange', 'green')\nfig = plt.figure(figsize=(15, 6)) \nplt.hlines(y=my_range, xmin=0, xmax=df_lolipop['sum_sales'], color=my_color)\nplt.scatter(df_lolipop['sum_sales'], my_range, color=my_color, alpha=1)\n \n\nplt.yticks(my_range, df_lolipop['platform'])\nplt.title(\"The total number of copies of games sold for the entire life cycle of the gaming device from 2005 to 2016.\")\nplt.xlabel('Number of copies of games sold, mln.')\nplt.ylabel('Gaming device')\nplt.grid()\n\n# We make the legend manually, we will enter the notation for the lines\n\norange_line = mlines.Line2D([], [], color='orange', marker='o',\n                          markersize=5, label='Portable console')\ngreen_line = mlines.Line2D([], [], color='green', marker='o',\n                          markersize=5, label='Stationary consoles and PCs')\nplt.legend(handles=[green_line,orange_line],loc=4)\nplt.show()\n\"\"\"\nFrom the graph of total sales of games on all gaming devices, it can be seen that in the previous generation, the Xbox 360 leads by a small margin, with a slight lag in 2nd and 3rd place, the PS3 and Wii consoles are located\n\nAmong portable consoles, the total dominance of the Nintendo DS is noticeable, the PSP sold more than 2 times fewer games over the same period of time, the PS Vita lags behind all gaming devices.\n\nIn the new generation of consoles, PS4 is currently leading, twice ahead of its competitor in the face of Xbox One, WiiU is also a lagging console, games for it are not in demand around the world.\n\"\"\"\n\"\"\"\nLet's build the \"Box with a mustache\" graphs for the types of consoles under study, for this we will select them from our main data table\n\"\"\"\nstations = ['PS3', 'PS4', 'X360','XOne', 'Wii', 'WiiU', 'PC']\nportable = ['DS', 'PSP', 'PSV']\nall_platforms = stations + portable\npast_gen = ['Wii', 'PS3', 'X360']\nnext_gen = ['WiiU', 'PS4', 'XOne']\nmain_df = df[df['platform'].apply(lambda x: x in all_platforms) ]\nmain_df['portable'] = 0\nmain_df.loc[main_df['platform'].apply(lambda x:x in [ 'DS', 'PSP', 'PSV']), 'portable'] = 1\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot platform sales\")\nplt.grid()\nplt.show()\n\"\"\"\nThe Wii console has some kind of game that sold more than 80 million copies, we will cut off this value when plotting graphs, but we will take into account that this title cannot be ignored when planning a strategy, it is very popular, let's see what kind of game it is\n\n\"\"\"\nmega_title = main_df.query('sum_sales > 40')\nmega_title\nmain_df_drop_wii_sports = main_df.query('sum_sales < 40')\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_drop_wii_sports, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_drop_wii_sports, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot platform sales without wii sports\")\nplt.grid()\nplt.show()\n\"\"\"\nWii Sport was a so-called system seller, he used all the technological capabilities of the new Wii console controllers, which caused a boom in sales of this title and consoles, respectively\n\nLet's build boxes with moustaches for different types of consoles:\n\"\"\"\nmain_df_pg = main_df.query('sum_sales < 40')[main_df['platform'].apply(lambda x: x in past_gen)]\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_pg, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_pg, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot for consoles of the last generation\")\nplt.xlabel('Game platform')\nplt.ylabel('Number of copies of games sold')\nplt.grid()\nplt.show()\n\"\"\"\nFrom the graph, we can conclude that most of the games are sold in the amount of up to 3 million copies, we will limit the number of copies sold on the graph in order to examine the distribution in more detail\n\"\"\"\nmain_df_pg = main_df.query('sum_sales < 5')[main_df['platform'].apply(lambda x: x in past_gen)]\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_pg, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_pg, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot for consoles of the last generation \")\nplt.xlabel('Game platform')\nplt.ylabel('Number of copies of games sold')\nplt.grid()\nplt.show()\n\"\"\"\nIt can be concluded that on Wii consoles, the distribution schedule is more compressed vertically, which means that most of the games sold are sold up to 1 million copies, in the case of Xbox 360 and PS3, we see that their sales spread is more vertically distributed, this is due to the fact that compared to Wii on the consoles in question, in addition to exclusive games, multiplatform games that simply do not exist on Wii are sold well\n\"\"\"\n\"\"\"\nLet's build the same graphics for the new generation of consoles:\n\"\"\"\nmain_df_ng = main_df.query('sum_sales < 5')[main_df['platform'].apply(lambda x: x in next_gen)]\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_ng, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_ng, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot for consoles of the new generation \")\nplt.xlabel('Game platform')\nplt.ylabel('Number of copies of games sold')\nplt.grid()\nplt.show()\n\"\"\"\nThe picture is the same, a little more games are sold for PS4, a little worse for Xbox One and WiiU games are sold much worse and even visually you can see how much less games are being developed for this platform (orange dots on the graph).\n\nUnlike its predecessor, WiiU does not have a title in its arsenal that would sell this console and have sky-high sales, most likely this is a miscalculation by Nintendo.\n\"\"\"\nmain_df_port = main_df.query('sum_sales < 40')[main_df['platform'].apply(lambda x: x in portable)]\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_port, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_port, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot for consoles of the portable consoles\")\nplt.xlabel('Game platform')\nplt.ylabel('Number of copies of games sold')\nplt.grid()\nplt.show()\n\"\"\"\nThe Nintendo DS console has a lot of games that have sold more than 5 million copies, while both Sony consoles have almost no such games\n\"\"\"\nmain_df_port = main_df.query('sum_sales < 2')[main_df['platform'].apply(lambda x: x in portable)]\n\nfig = plt.figure(figsize=(15, 15)) \nax = sns.boxplot(x='platform', y='sum_sales', data=main_df_port, palette='rainbow_r')\nax = sns.stripplot(x='platform', y='sum_sales', data=main_df_port, palette='plasma', jitter=0.2, size=2.5)\nplt.title(\"Boxplot for consoles of the portable consoles\")\nplt.xlabel('Game platform')\nplt.ylabel('Number of copies of games sold')\nplt.grid()\nplt.show()\n\"\"\"\nIf you do not take into account the large titles of the Nintendo DS, it can be said that on average the PSP platform was almost as popular as the Nintendo DS\n\nThe PS Vita console can be considered a failure.\n\"\"\"\n\"\"\"\n--------------------\n\"\"\"\n\"\"\"\nConsider the impact of reviews from critics and users on the sale of games for various platforms, we will consider stationary consoles of the last generation:\n\"\"\"\n\"\"\"\nLet's construct matrices of scattering diagrams\n\"\"\"\ndata_to_plot = main_df.loc[main_df['platform'].apply(lambda x: x in next_gen),\n                           ['na_sales',\n                        'eu_sales',\n                        'jp_sales',\n                        'critic_score',\n                        'user_score',\n                        'platform']].sort_values(by='platform', ascending=True)\nmy_color={'PS4':'#3148FA', 'XOne':'#45DE6B','WiiU':'#FA737B'}\nmatrix_plot = sns.pairplot(data_to_plot,\n                           hue=\"platform\", \n                           kind='scatter', \n                           hue_order = ['PS4','XOne','WiiU'],\n                           diag_kind='auto', \n                           palette=my_color,\n                           plot_kws=dict(alpha=0.3),\n                           diag_kws=dict(alpha=1, fill=False),\n                          )\nmatrix_plot.fig.suptitle(\"Matrix of scattering diagrams for consoles of the current generation \\n 2012-2016.\", y = 1.05)\nplt.show()\n\n# In the data for this block, we will again remove the super popular Wii Sport game, we realized that it is fire, Nintendo fans will not be offended\n\ndata_to_plot = main_df.query('sum_sales < 40').loc[main_df['platform'].apply(lambda x: x in past_gen),\n                           ['na_sales',\n                        'eu_sales',\n                        'jp_sales',\n                        'critic_score',\n                        'user_score',\n                        'platform']].sort_values(by='platform', ascending=True)\nmy_color={'PS3':'#3148FA', 'X360':'#45DE6B','Wii':'#FA737B'}\nmatrix_plot = sns.pairplot(data_to_plot,\n                           hue=\"platform\", \n                           kind='scatter', \n                           hue_order = ['PS3','X360','Wii'],\n                           diag_kind='auto', \n                           palette=my_color,\n                           plot_kws=dict(alpha=0.3),\n                           diag_kws=dict(alpha=1, fill=False),\n                          )\nmatrix_plot.fig.suptitle(\"Matrix of scattering diagrams for consoles of the last generation \\n 2005-2016.\", y = 1.05)\nplt.show()\n\ndata_to_plot = main_df.loc[main_df['platform'].apply(lambda x: x in portable),\n                           ['na_sales',\n                        'eu_sales',\n                        'jp_sales',\n                        'critic_score',\n                        'user_score',\n                        'platform']].sort_values(by='platform', ascending=True)\nmy_color={'PSP':'#3148FA', 'DS':'#45DE6B','PSV':'#FA737B'}\nmatrix_plot = sns.pairplot(data_to_plot,\n                           hue=\"platform\", \n                           kind='scatter', \n                           hue_order = ['DS','PSP','PSV'],\n                           diag_kind='auto', \n                           palette=my_color,\n                           plot_kws=dict(alpha=0.3),\n                           diag_kws=dict(alpha=1, fill=False),\n                          )\nmatrix_plot.fig.suptitle(\"Matrix of scattering diagrams for portable consoles of the last generation \\n 2004-2016.\", y = 1.05)\nplt.show()\n\"\"\"\nFrom the presented scatter plot matrices, it can be concluded that critics' ratings have a greater impact on sales, or they correspond more to reality, because critics evaluate the game unbiasedly (ideally) and this is confirmed by the market, as well as vice versa, the market sees critics' ratings and buys the game more often. This trend can be traced on all platforms in all years.\n\nAbout user ratings, we can say that on older platforms, their performance in comparison with sales tends to critics' ratings, but on new-generation consoles, gamers are hungry for games and, regardless of user ratings, sales of many games are large compared to other games in the same generation.\n\"\"\"\n\"\"\"\nLet's calculate the Pearson correlation coefficients and build their visualization\n\"\"\"\nfor i in all_platforms:\n    corr = main_df.loc[main_df['platform']== i, \n                          ['year',\n                           'sum_sales',\n                           'critic_score',\n                           'user_score']].corr()\n    fig = plt.figure(figsize=(6, 5))\n    sns.heatmap(corr, \n                annot=True, \n                annot_kws={\"size\": 11},\n                cmap=\"BuGn\"\n               )\n    plt.title(f\"Correlation matrix for consoles {i}\")\n    plt.show()\n\"\"\"\nFrom the presented correlation matrices, the following conclusions can be drawn:\n* For Xbox and Playstation consoles, critics' ratings are weak, but they affect the total sales of games;\n* For the Wii console, critics' ratings do not affect total game sales;\n* For all consoles, user ratings have almost no effect on total game sales;\n* Critics' ratings and user ratings correlate noticeably more on controversial consoles than on widespread ones;\n* On new-generation consoles, user ratings even have a negative correlation with sales, which confirms our conclusions regarding gaming hunger among gamers on new consoles.\n----------------\n\"\"\"\n\"\"\"\nLet's look at the general distribution of games by genre.\n\"\"\"\ndf_genre_by_year = df.pivot_table(index=['genre','year'], \n                                  values='sum_sales',\n                                 aggfunc = 'sum').reset_index()\ndf_genre_by_year['genre'].unique()\nlabels = ['Total sales of games by genre',\n          'Year',\n          'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_genre_by_year, \n                'genre', \n                'year', \n                'sum_sales', \n                [ \n       'Racing', 'Role-Playing', 'Shooter', 'Simulation', 'Sports',\n       'Strategy'\n                ],\n               labels)\ndf_sales_by_year['platform'].unique()\nlabels = ['Total sales of games by genre',\n 'Year',\n 'Number of games sold, mln.',\n          ]\nprint_plt_lines(df_genre_by_year, \n                'genre', \n                'year', \n                'sum_sales', \n                [ 'Action', 'Adventure', 'Fighting', 'Misc', 'Platform', 'Puzzle',\n                ],\n               labels)\n\"\"\"\nFrom the charts by year, you can select favorites - these are 'Action', 'Sports', 'Role-Playing', 'Misc', 'Shooter', let's make sure of this by building a Lolipop chart by genre:\n\"\"\"\ndf_lolipop = df_genre_by_year.pivot_table(index = 'genre', \n                                          values = 'sum_sales', \n                                          aggfunc = 'sum').reset_index().sort_values(by = 'sum_sales')\nlabels = ['Total number of copies of games sold by genre from 2005 to 2016',\n'Number of copies of games sold, million',\n'Genre']\nlolipop_plot(df_lolipop, 'sum_sales', 'genre',labels, color1='orange', color2='gray', color_lim=500)\n\n\"\"\"\nThe graph shows that the games of the \"Action\" category have a large gap in sales from other genres, most likely such a jump is due to the fact that this is a fairly extensive genre and many games can be included in this category\n\nThe \"Sports\" genre owes its popularity to the previously reviewed Wii Sport\n\nIt is also possible to distinguish genres that are not popular - fighting games, simulators, adventures, strategies and puzzles, these are definitely niche genres of games, platformers could also be attributed to them, however, due to their diversity, platformers noticeably break ahead in sales and find their user\n\"\"\"\n\"\"\"\n-------------------------\n\"\"\"\n\"\"\"\nLet's form user portraits by region (NA, EU, JP), define:\n\n     The most popular platforms (top 5). Describe the differences in sales shares.\n     The most popular genres (top 5). Explain the difference.\n     Does the ESRB rating affect sales in a particular region?\n\"\"\"\ndf_lolipop\ndf_lolipop_platform = main_df.pivot_table(index = 'platform', \n                                          values = ['na_sales', 'eu_sales','jp_sales'],\n                                          aggfunc = 'sum').reset_index().sort_values(by = 'na_sales')\nlabels = ['Total number of copies of games sold by platform type in North America from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_platform, 'na_sales', 'platform',labels, color_lim=150)\nprint(df_lolipop_platform[['platform','na_sales']].sort_values(by='na_sales', ascending = False).reset_index())\nlabels = ['Total number of copies of games sold by platform type in Europe from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_platform, 'eu_sales', 'platform',labels, color_lim=150)\nprint(df_lolipop_platform[['platform','eu_sales']].sort_values(by='eu_sales', ascending = False).reset_index())\n\nlabels = ['Total number of copies of games sold by platform type in Japan from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_platform, 'jp_sales', 'platform',labels, color_lim=50)\nprint(df_lolipop_platform[['platform','jp_sales']].sort_values(by='jp_sales', ascending = False).reset_index())\n\n\"\"\"\nThe differences between different markets are clearly visible. In Japan, they love Japanese consoles, in Europe they love everything, but they love PS more, in America they prefer American Xbox consoles, which are practically not used in Japan\n\"\"\"\n\"\"\"\n-------------------\n\"\"\"\n\"\"\"\nConsider the distribution by genre depending on the selected region:\n\"\"\"\ndf_lolipop_genre = main_df.pivot_table(index = 'genre', \n                                          values = ['na_sales', 'eu_sales','jp_sales'],\n                                          aggfunc = 'sum').reset_index().sort_values(by = 'na_sales')\nlabels = ['Total number of copies of games sold by genre in North America from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_genre, 'na_sales', 'genre',labels, color_lim=150)\nprint(df_lolipop_genre[['genre','na_sales']].sort_values(by='na_sales', ascending = False).reset_index())\nlabels = ['Total number of copies of games sold by genre in Europe from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_genre, 'eu_sales', 'genre',labels, color_lim=110)\nprint(df_lolipop_genre[['genre','eu_sales']].sort_values(by='eu_sales', ascending = False).reset_index())\n\nlabels = ['Total number of copies of games sold by genre in Japan from 2005 to 2016',\n'Number of copies of games sold, million',\n'Platform']\nlolipop_plot(df_lolipop_genre, 'jp_sales', 'genre',labels, color_lim=25)\nprint(df_lolipop_genre[['genre','jp_sales']].sort_values(by='jp_sales', ascending = False).reset_index())\n\n\"\"\"\nThere are genres that are popular all over the world: Action, Sports, RPG, but there are also outstanding values, for example, there are many platformer fans in Japan, this is due to the widespread use of portable consoles, platformers are most often played on them\n\"\"\"\ndf_lolipop_rating = main_df.pivot_table(index = 'rating', \n                                          values = ['na_sales', 'eu_sales','jp_sales'],\n                                          aggfunc = 'sum').reset_index().sort_values(by = 'na_sales')\nlabels = ['Total number of copies of games sold by ESRB rating in North America from 2005 to 2016',\n'Number of copies of games sold, million',\n'Rating']\nlolipop_plot(df_lolipop_rating, 'na_sales', 'rating',labels, color_lim=400)\nprint(df_lolipop_rating[['rating','na_sales']].sort_values(by='na_sales', ascending = False).reset_index())\nlabels = ['Total number of copies of games sold by ESRB rating in Europe from 2005 to 2016',\n'Number of copies of games sold, million',\n'Rating']\nlolipop_plot(df_lolipop_rating, 'eu_sales', 'rating',labels, color_lim=230)\nprint(df_lolipop_rating[['rating','eu_sales']].sort_values(by='eu_sales', ascending = False).reset_index())\n\nlabels = ['Total number of copies of games sold by ESRB rating in Japan from 2005 to 2016',\n'Number of copies of games sold, million',\n'Rating']\nlolipop_plot(df_lolipop_rating, 'jp_sales', 'rating',labels, color_lim=50)\nprint(df_lolipop_rating[['rating','jp_sales']].sort_values(by='jp_sales', ascending = False).reset_index())\n\"\"\"\n\"E\" (\"Everyone\") \u2014 \"For everyone\": The content is quite suitable for the age category from 6 years. Such games may also appeal to adults. Games with this rating may contain minimal violence, mostly of a \"cartoon\" nature. The first game to receive this rating was The Simpsons Cartoon Studio, released in 1996. Originally \"K-A\" (\"Kids to Adults\")\n\n\"T\" (\"Teen\") \u2014 \"Teenagers\": The game is suitable for people from 13 years old. Projects from this category may contain violence, obscene scenes, rude humor, moderately explicit sexual content, blood or infrequent use of profanity.\n\n\"M\" (\"Mature\") \u2014 \"For adults\": The game materials are not suitable for teenagers under the age of 17. Projects with this rating may contain quite violent violence, a large amount of blood with dismemberment, obscene sex scenes or rude profanity that is undesirable for a younger audience. \n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fc9099330adf64'}"}
{"id":"23995","text":"\"\"\"\n# Classification of Images using ConvNets ( Convolutional Neural Network).\n\n### In this Jupyter notebook, we will learn some cool stuff regarding the below topics.\n\n1. DataFrame Creation\n2. Image Processing\n4. ConvNet Implementation\n5. Making Predictions\n6. Creating a Sample data\n\n### So let's get started, so we will start with understanding the dataset. this dataset contains images of some scenarios, this scenarios are listed below:\n\n1. Buildings\n2. Glaciers\n3. Street\n4. Forest\n5. Sea\n6. Mountain\n\n### and what we have to do is create a ConvNet that can classify if given image is one of the scenarios we got. So this dataset can be confusing at times becuase if you convert the images to black and white.\n### then the model would predict mountain as glacier and glacier as mountain and also same with some Images of streets and buildings. The original dimension of images are (150 , 150 ,3 ), i.e are described below:\n\n#### Orginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\n\"\"\"\n\"\"\"\n## Step 1 : Importing our Libraries\n\"\"\"\n# Importing all the libraries that we will need\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport cv2\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import confusion_matrix\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D , MaxPooling2D , Flatten\nfrom keras.layers import Dense , Dropout , Dense\nfrom keras.preprocessing.image import load_img\nfrom sklearn.utils import shuffle\nfrom random import randint\n\n\n# We will print all the directory names from our input to get a idea what all we have to make the magic happen\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    print(dirname)\n\n\"\"\"\n## Step 2 : Preparing our dataset\n\"\"\"\n# Training data\n# filenames_train is here a list to store all our images with their paths\n# category_train is here a list to store each image's category\n\nfilenames_train = []\ncategory_train = []\n\n# saving the training data path to variable training_data\ntraining_data = os.listdir(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\")\n\n# As every image is in it's particular directory we will have to enter in each of the respective directory\nfor dir in training_data:\n    \n    print(str(dir))\n    \n    for file in os.listdir(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/\"+dir):\n        \n        # Appending the files to filenames_train list\n        filenames_train.append(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/\"+dir+\"\/\"+file)\n        \n        # Appending the Categories to category_train\n        category_train.append(dir)\n        \n    print(\"Process finished for :\" + str(dir))\n    \n    \n    \n# Creating a Dataframe from our Lists\n\ndf_train = pd.DataFrame({\n    \"File_name\":filenames_train,\n    \"Category\":category_train\n})\n# First five instances \n\ndf_train.head(10)\n# Last 10 instances\n\ndf_train.tail(10)\n# Getting count of each Category\n\ndf_train['Category'].value_counts()\n# Plotting a bar graph of count for each category\n\ndf_train['Category'].value_counts().plot.bar()\n# Same process as training\n# filenames_test is here a list to store all our images with their paths\n# category_test is here a list to store each image's category\n\nfilenames_test = []\ncategory_test = []\n\n# saving the testing data path to variable training_data\ntesting_data = os.listdir(\"\/kaggle\/input\/intel-image-classification\/seg_test\/seg_test\")\n\n# As every image is in it's particular directory we will have to enter in each of the respective directory\nfor dir in testing_data:\n    \n    print(str(dir))\n    \n    for file in os.listdir(\"\/kaggle\/input\/intel-image-classification\/seg_test\/seg_test\/\"+dir):\n        \n        # Appending the files to filenames_train list\n        filenames_test.append(\"\/kaggle\/input\/intel-image-classification\/seg_test\/seg_test\/\"+dir+\"\/\"+file)\n        \n        # Appending the Categories to category_train\n        category_test.append(dir)\n        \n    print(\"Process finished for :\" + str(dir))\n        \n        \n# Creating a Dataframe from our Lists    \n        \ndf_test = pd.DataFrame({\n    \"File_name\" : filenames_test,\n    \"Category\" : category_test\n})\n# First 10 instances of testing data\n\ndf_test.head(10)\n# Last 10 instances of testing data\n\ndf_test.tail(10)\n# Shuffling the training dataset\n\ndf_train = shuffle(df_train)\ndf_train.head(10)\n# Shuffling the testing dataset\n\ndf_test = shuffle(df_test)\ndf_test.head(10)\n# Just to Clarify that images have appropriate labels\n\ni = 0\nfor index , row in df_train.iterrows():\n    if i <=10: \n        print(row['File_name'] + \"----->\" + row['Category'])\n        i += 1\n\"\"\"\n> ### Mountain Image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/mountain\/3641.jpg\")\nplt.imshow(img)\nplt.title(\"Mountain\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/mountain\/3641.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n> ### Sea Image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/sea\/2229.jpg\")\nplt.imshow(img)\nplt.title(\"Sea\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/sea\/2229.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n> ### Glacier Image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/glacier\/16182.jpg\")\nplt.imshow(img)\nplt.title(\"Glacier\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/glacier\/16182.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n> ### Building Image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/buildings\/18084.jpg\")\nplt.imshow(img)\nplt.title(\"Building\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/buildings\/18084.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n> ### Forest image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/forest\/13444.jpg\")\nplt.imshow(img)\nplt.title(\"Forest\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/forest\/13444.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n> ### Street image\n\"\"\"\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/street\/13586.jpg\")\nplt.imshow(img)\nplt.title(\"Street\")\nplt.show()\nimg = load_img(\"\/kaggle\/input\/intel-image-classification\/seg_train\/seg_train\/street\/13586.jpg\")\nimg = np.array(img)\nimg.shape\n\"\"\"\nOrginial dimension of Image:\n*  height = 150\n*  width = 150\n*  channels = 3\n\"\"\"\n\"\"\"\n# Step 3 : Image Preprocessing\n\"\"\"\n# X_train and Y_train are lists here to store our training data, where X_train will store the images and Y_train will store the labels\n\nX_train = []\nY_train = []\n\n# The df.iterrows() function will iterate through each row\nfor index , row in df_train.iterrows():\n    \n    try:\n        \n        # Reading the image\n        img = cv2.imread(row['File_name'] , cv2.IMREAD_COLOR)\n        \n        # Resizing the image to our desired dimensions\n        img = cv2.resize(img ,(128,128))\n    \n        # Appending the image as numpy arrays to X_train\n        X_train.append(np.array(img))\n        \n        # Appending the labels to Y_train\n        Y_train.append(row['Category'])\n    except:\n        pass\n    \n# Just to check how many images were skipped and X_train and Y_train have same data count    \nprint(len(X_train))\nprint(len(Y_train))\n# X_test and Y_test are lists here to store our testing data, where X_test will store the images and Y_test will store the labels\n\nX_test = []\nY_test = []\n\n# The df.iterrows() function will iterate through each row\nfor index , row in df_test.iterrows():\n    \n    try:\n        \n        # Reading the image\n        img = cv2.imread(row['File_name'] , cv2.IMREAD_COLOR)\n        \n        # Resizing the image to our desired dimensions\n        img = cv2.resize(img ,(128,128))\n    \n        # Appending the image as numpy arrays to X_test\n        X_test.append(img)\n        \n        # Appending the labels to Y_test\n        Y_test.append(row['Category'])\n    except:\n       pass\n    \nprint(len(X_test))\nprint(len(Y_test))\n\"\"\"\n## Step 4 : Plotting the images\n\"\"\"\n# We will be plotting some images with the labels\n\nimport random\n\nfig , ax = plt.subplots(2,10)\nplt.subplots_adjust(bottom=0.3 , top = 0.5 , hspace = 0)\nfig.set_size_inches(25,25)\n\nfor i in range(0,2):\n    for j in range(0,10):\n        l = random.randint(0,len(Y_train))\n        ax[i,j].imshow(X_train[l])\n        ax[i,j].set_title(Y_train[l])\n        ax[i,j].set_aspect('equal')\n# Converting our datasets to numpy arrays\n\nX_train = np.array(X_train)\nY_train = np.array(Y_train)\nX_test = np.array(X_test)\nY_test = np.array(Y_test)\n# Reshaping our Y data to be a array of [value , 1]\n\nY_train = Y_train.reshape(-1,1)\nY_test = Y_test.reshape(-1,1)\nohe = OneHotEncoder()\nY_train = ohe.fit_transform(Y_train)\nY_test = ohe.fit_transform(Y_test)\n# Displaying all the Categories \n\nohe.categories_\n# Getting the output of the transformed data\n\nprint(Y_train[1])\n\n# The shape here will be (1 , 6), becuase one hot encoder encoder the data as (1 , numoffeatures array)\n# like assuming Building is encoded to [1,0,0,0,0,0]\nprint(Y_train[1].shape)\n\"\"\"\n## Step 5 : Implementing Convolutional Neural Network\n\"\"\"\nmodel = Sequential()\n\n#First Conv layer\nmodel.add(Conv2D(32 , (3,3) , activation = 'relu' , input_shape = (128 , 128 , 3)))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\n#Second Conv layer\nmodel.add(Conv2D(64 , (3,3) , activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\n#Third Conv layer\nmodel.add(Conv2D(128 , (3,3) , activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\n#Fourth Conv layer\nmodel.add(Conv2D(256, (3,3) , activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\n#Fifth Conv layer\nmodel.add(Conv2D(256, (3,3) , activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(Flatten())\n\n#First Dense layer\nmodel.add(Dense(256 , activation = 'relu'))\n\n# 25% Neurons will get deactivated simulataneously\nmodel.add(Dropout(0.25))\n\n# Second Dense layer\nmodel.add(Dense(64 , activation = 'relu'))\n\n# 50% Neurons will get deactivated simultaneously\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(6 , activation = 'softmax'))\n# This will give us the summary of our model\n\nmodel.summary()\n# Defining the rules for our model\n\nmodel.compile(loss = 'categorical_crossentropy' , optimizer = 'adam' , metrics = ['accuracy'])\n# Fitting our model to training data\n\nmodel.fit(X_train , Y_train , epochs = 40 , batch_size = 64)\n# Evaluating our model on test data\n\nloss , accuracy = model.evaluate(X_test , Y_test , batch_size = 32)\n\nprint('Test accuracy: {:2.2f}%'.format(accuracy*100))\n# Transforming the data back to original and saving it to Y_test_labele_data\n\nY_test_labeled_data  = ohe.inverse_transform(Y_test)\n# Assuring the data if converted or not\n\nY_test_labeled_data[0:5]\n# Predicting the values for X_test\n\nY_pred = model.predict(X_test).round()\n# Transforming the data to labels\n\nY_pred = ohe.inverse_transform(Y_pred)\n# Assuring if data is converted or not\n\nY_pred[0:5]\n# Generating a heat map for confusion matrix\n\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n\nx_ticklabels = ['buildings', 'forest', 'glacier', 'mountain', 'sea', 'street']\n\ny_ticklabels = ['buildings', 'forest', 'glacier', 'mountain', 'sea', 'street']\n\ncm = confusion_matrix(Y_test_labeled_data , Y_pred) \n\nprint(cm)\n\nplt.subplots(figsize = (20,15))\n\nsns.heatmap(cm , xticklabels = x_ticklabels , yticklabels = y_ticklabels)\n\"\"\"\n## Step 6 : Generating data to be predicted\n\"\"\"\n# Using the data from seg_pred to predict some sample images\n\nseg_pred = os.listdir(\"\/kaggle\/input\/intel-image-classification\/seg_pred\/seg_pred\")\nfig , ax = plt.subplots(5,10)\nplt.subplots_adjust(top = 0.7 , bottom = 0.3 , hspace = 0.7)\nfig.set_size_inches(25,25)\nrandom_values = []\n\n# Plotting the some random Images\nfor i in range(5):\n    for j in range(10):\n        l = random.randint(0, len(seg_pred))\n        img = cv2.imread(\"\/kaggle\/input\/intel-image-classification\/seg_pred\/seg_pred\/\"+seg_pred[l])\n        ax[i,j].imshow(img)\n        ax[i,j].set_title(seg_pred[l])\n        ax[i,j].set_aspect('equal')\n        random_values.append(seg_pred[l])\n    \nprint(len(random_values))\n# Image processing converting the images before feeding them to the model\n\nimages_to_be_predicted = []\nfor i in random_values:\n    img = cv2.imread(\"\/kaggle\/input\/intel-image-classification\/seg_pred\/seg_pred\/\"+i)\n    img = cv2.resize(img , (128,128))\n    images_to_be_predicted.append(np.array(img))\n    \nprint(images_to_be_predicted[1].shape)\nimages_to_be_predicted = np.array(images_to_be_predicted)\npredicted_values = model.predict(images_to_be_predicted).round()\nprint(predicted_values[0:5])\npredicted_values = ohe.inverse_transform(predicted_values)\nprint(predicted_values[0:5])\n\"\"\"\n## Step 7 : Predicting and Plotting the new data.\n\"\"\"\n# PLotting Image with their predicted labels, you are the witness of how good the model performs\n\nfig , ax = plt.subplots(5,10)\nplt.subplots_adjust(top = 0.7 , bottom = 0.3 , hspace = 0.7)\nfig.set_size_inches(25,25)\nk = 0\n\nfor i in range(5):\n    for j in range(10):\n        ax[i,j].imshow(images_to_be_predicted[k])\n        ax[i,j].set_title(predicted_values[k])\n        ax[i,j].set_aspect('equal')\n        k +=1\n        \n\"\"\"\n### Please upvote, if this impementation of ConvNets was interesting and you learnt something. And comment if I missed something or messed up the code somewhere, after all we all are programmers \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2c14bb552dc31e'}"}
{"id":"77014","text":"\"\"\"\nAutoGluon is an auto-ml package, developed by J Mueller, X Shi, A Smola:\n\nMueller, Jonas, Xingjian Shi, and Alexander Smola. \"Faster, Simpler, More Accurate: Practical Automated Machine Learning with Tabular, Text, and Image Data.\" Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining. 2020.\n\nFor tabular data, AutoGluon can produce models to predict the values in one column based on the values in the other columns. With just a single call to fit(), you can achieve high accuracy in standard supervised learning tasks (both classification and regression).\n\nIn the economy of a competition it can help you to create benchmarks, get insights on models' workings and accelerate your experimentations.\n\"\"\"\n\"\"\"\nInstalling the latest Scikit-learn\n\"\"\"\n!pip install scikit-learn -U\n\"\"\"\nInstalling LightGBM for GPU\n\"\"\"\n!rm -r \/opt\/conda\/lib\/python3.7\/site-packages\/lightgbm\n!git clone --recursive https:\/\/github.com\/Microsoft\/LightGBM\n!apt-get install -y -qq libboost-all-dev\n# If you have trouble with cmake, run this: ldd \"$(type -p cmake)\"\n# and find out what library is missing or has a wrong version\n# !rm \/opt\/conda\/lib\/libcurl.so.4\n# %%bash\n# cd LightGBM\n# mkdir build\n# cd build\n# cmake -DUSE_GPU=1 -DOpenCL_LIBRARY=\/usr\/local\/cuda\/lib64\/libOpenCL.so -DOpenCL_INCLUDE_DIR=\/usr\/local\/cuda\/include\/ ..\n# make -j$(nproc)\n!mkdir -p \/etc\/OpenCL\/vendors && echo \"libnvidia-opencl.so.1\" > \/etc\/OpenCL\/vendors\/nvidia.icd\n!rm -r LightGBM\n\"\"\"\nInstalling AutoGluon\n\"\"\"\n!pip install autogluon \n# Importing core libraries\nimport numpy as np\nimport pandas as pd\nimport gc\n\n# Importing AutoGluon\nfrom autogluon.tabular import TabularDataset, TabularPredictor\n\n# Scikit Learn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.pipeline import Pipeline\n# Derived from the original script https:\/\/www.kaggle.com\/gemartin\/load-data-reduce-memory-usage \n# by Guillaume Martin\n\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() \/ 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    end_mem = df.memory_usage().sum() \/ 1024**2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) \/ start_mem))\n    return df\n# Loading data \nX_train = pd.read_csv(\"..\/input\/tabular-playground-series-nov-2021\/train.csv\").set_index('id')\nX_test = pd.read_csv(\"..\/input\/tabular-playground-series-nov-2021\/test.csv\").set_index('id')\nX_train.head()\n# Feature engineering\n# unique_values = X_train.iloc[:1000].nunique() < 0\n# categoricals = [col for col in  unique_values.index[unique_values < 10] if col!='target']\nnumeric = [col for col in X_train.columns  if col!='target']\n# print(\"categoricals\",categoricals)\nprint(\"numeric\",numeric)\nX_train['mean_numeric'] = X_train[numeric].mean(axis=1)\nX_train['std_numeric'] = X_train[numeric].std(axis=1)\nX_train['min_numeric'] = X_train[numeric].min(axis=1)\nX_train['max_numeric'] = X_train[numeric].max(axis=1)\n\nX_test['mean_numeric'] = X_test[numeric].mean(axis=1)\nX_test['std_numeric'] = X_test[numeric].std(axis=1)\nX_test['min_numeric'] = X_test[numeric].min(axis=1)\nX_test['max_numeric'] = X_test[numeric].max(axis=1)\n\nnumeric+=['mean_numeric','std_numeric','min_numeric','max_numeric']\nprint(\"numeric\",numeric)\nX_train.head()\n# X_train.columns.tolist()\n# Feature selection\nfeatures = ['f0',\n 'f1',\n 'f2',\n 'f3',\n 'f4',\n 'f5',\n 'f6',\n 'f7',\n 'f8',\n 'f9',\n 'f10',\n 'f11',\n 'f12',\n 'f13',\n 'f14',\n 'f15',\n 'f16',\n 'f17',\n 'f18',\n 'f19',\n 'f20',\n 'f21',\n 'f22',\n 'f23',\n 'f24',\n 'f25',\n 'f26',\n 'f27',\n 'f28',\n 'f29',\n 'f30',\n 'f31',\n 'f32',\n 'f33',\n 'f34',\n 'f35',\n 'f36',\n 'f37',\n 'f38',\n 'f39',\n 'f40',\n 'f41',\n 'f42',\n 'f43',\n 'f44',\n 'f45',\n 'f46',\n 'f47',\n 'f48',\n 'f49',\n 'f50',\n 'f51',\n 'f52',\n 'f53',\n 'f54',\n 'f55',\n 'f56',\n 'f57',\n 'f58',\n 'f59',\n 'f60',\n 'f61',\n 'f62',\n 'f63',\n 'f64',\n 'f65',\n 'f66',\n 'f67',\n 'f68',\n 'f69',\n 'f70',\n 'f71',\n 'f72',\n 'f73',\n 'f74',\n 'f75',\n 'f76',\n 'f77',\n 'f78',\n 'f79',\n 'f80',\n 'f81',\n 'f82',\n 'f83',\n 'f84',\n 'f85',\n 'f86',\n 'f87',\n 'f88',\n 'f89',\n 'f90',\n 'f91',\n 'f92',\n 'f93',\n 'f94',\n 'f95',\n 'f96',\n 'f97',\n 'f98',\n 'f99',\n 'mean_numeric',\n 'std_numeric',\n 'min_numeric',\n 'max_numeric']\n\nX_train = X_train[features + ['target']]\nX_test = X_test[features]\n### REDUCE MEMORY USAGE\nX_train = reduce_mem_usage(X_train)\nX_test = reduce_mem_usage(X_test)\ngc.collect()\nVALIDATION = False\nif VALIDATION is True:\n    X_train, X_val = train_test_split(X_train, test_size=int(len(X_train) * 0.2), random_state=42)\n    train_data = TabularDataset(X_train)\n    val_data = TabularDataset(X_val)\nelse:\n    train_data = TabularDataset(X_train)\n    val_data = TabularDataset(X_train.iloc[:100_000, :])\n\nSUBSAMPLE = False\nRANDOM_STATE = 0\nif SUBSAMPLE is True:\n    subsample_size = 100_000  # subsample subset of data for faster demo, try setting this to much larger values\n    train_data = train_data.sample(n=subsample_size, random_state=RANDOM_STATE)\n    \ntrain_data.head()\nlabel = 'target'\nprint(\"Summary of target variable: \\n\", train_data[label].describe())\n!mkdir agModels\n\"\"\"\nYou can actually use the optimized parameters that you can find on public kernels to boost your AutoGluon performances.\n\nFor instance these parameters are from the high scoring notebook https:\/\/www.kaggle.com\/dlaststark\/tps-1021-la-dee-da by DLASTSTARK\n\"\"\"\nxgb_params = {\n    'objective': 'binary:logistic',\n    'eval_metric': 'auc',\n    'tree_method': 'gpu_hist',\n    'use_label_encoder': False,\n    'n_estimators': 10000,\n    'max_depth': 3,\n    'subsample': 0.5,\n    'colsample_bytree': 0.5,\n    'learning_rate': 0.01187,\n#     'gpu_id': 0,\n#     'predictor': 'gpu_predictor'\n}\n\ncb_params = {\n    'loss_function' : 'CrossEntropy',\n    'eval_metric' : 'AUC',\n    'iterations' : 10000,\n    'grow_policy' : 'SymmetricTree',\n    'use_best_model' : True,\n    'depth' : 5,\n    'l2_leaf_reg' : 3.0,\n    'random_strength' : 1.0,\n    'learning_rate' : 0.1,\n#     'task_type' : 'GPU',\n#     'devices' : '0',\n    'verbose' : 0\n}\n\nlgb_params = {\n    'objective' : 'binary',\n    'metric' : 'auc',\n    'max_depth' : 3,\n    'num_leaves' : 7,\n    'n_estimators' : 5000,\n    'colsample_bytree' : 0.3,\n    'subsample' : 0.5,\n    'reg_alpha' : 18,\n    'reg_lambda' : 17,\n    'learning_rate' : 0.095,\n#     'device' : 'gpu'\n}\nsave_path = 'agModels'  # specifies folder to store trained models\npresets='best_quality'\nmetric = 'roc_auc'\nhours = 8.0\npredictor = (TabularPredictor(label=label, eval_metric=metric, path=save_path)\n             .fit(train_data,\n                  excluded_model_types = ['KNN', 'XT' ,'RF', 'NN', 'FASTAI'],\n                  hyperparameters = {'GBM': lgb_params, \n                                     'CAT': cb_params,\n                                     'XGB': xgb_params\n                                    },\n                  presets=presets,\n                  time_limit= int(60 * 60 * hours))\n            )\n\nresults = predictor.fit_summary(show_plot=True)\nleaderboard = predictor.leaderboard(val_data)\ntest_data = TabularDataset(X_test)\ntest_preds = predictor.predict_proba(test_data)\n# Predicting and submission\nsubmission = pd.DataFrame({'id':X_test.index, \n                           'target': test_preds.iloc[:,1].ravel()})\n\nsubmission.to_csv(\"submission_autogluon_PL.csv\", index=False)\nsubmission","meta":"{'source': 'AI4Code', 'id': '8d79138e837088'}"}
{"id":"139032","text":"!cp ..\/input\/gdcm-conda-install\/gdcm.tar .\n!tar -xvzf gdcm.tar\n!conda install --offline .\/gdcm\/gdcm-2.8.9-py37h71b2a6d_0.tar.bz2\nimport pandas as pd \ndf = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\nif df.shape[0] == 2477:\n    fast_sub = True\n    df.to_csv('submission.csv', index=False)\nelse:\n    fast_sub = False\nimport os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    # Original from: https:\/\/www.kaggle.com\/raddar\/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data \/ np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data\n\ndef resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    \n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        im = im.resize((size, size), resample)\n    \n    return im\n\nimage_id = []\nstudy_id = []\ndim0 = []\ndim1 = []\nsplit = 'test'\nsave_dir = f'\/kaggle\/tmp\/{split}\/image\/'\nos.makedirs(save_dir, exist_ok=True)\n\nfor dirname, _, filenames in tqdm(os.walk(f'..\/input\/siim-covid19-detection\/{split}')):\n    for file in filenames:\n        # set keep_ratio=True to have original aspect ratio\n        xray = read_xray(os.path.join(dirname, file))\n        im = resize(xray, size=512)  \n        im.save(os.path.join(save_dir, file.replace('.dcm', '.png')))\n        image_id.append(file.replace('.dcm', ''))\n        study_id.append(dirname.split('\/')[-2])\n        dim0.append(xray.shape[0])\n        dim1.append(xray.shape[1])\n        \n        if len(dim0) >10 and fast_sub:\n            break\n    if len(dim0) >10 and fast_sub:\n            break\nmeta = pd.DataFrame.from_dict({'image_id': image_id, 'dim0': dim0, 'dim1': dim1, 'study_id': study_id})\nmeta.to_csv('test_meta.csv', index=False)\n!mkdir det_txt\n!mkdir det\n! pip install ..\/input\/siim-libs\/addict-2.4.0-py3-none-any.whl >> \/dev\/null\n! pip install ..\/input\/siim-libs\/timm-0.4.12-py3-none-any.whl >> \/dev\/null\n! pip install ..\/input\/siim-libs\/ensemble_boxes-1.0.6-py3-none-any.whl >> \/dev\/null\n! pip install ..\/input\/siim-libs\/loguru-0.5.3-py3-none-any.whl >> \/dev\/null\n! pip install ..\/input\/siim-libs\/thop-0.0.31.post2005241907-py3-none-any.whl >> \/dev\/null\n! pip install ..\/input\/pycocotools\/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl >> \/dev\/null\n! pip install ..\/input\/omegaconf\/omegaconf-2.0.5-py3-none-any.whl >> \/dev\/null\n!cp -r ..\/input\/siim-v5-mh\/* .\n!python inference.py --is_val 0 --output_path det_txt\/ --input_path '\/kaggle\/tmp\/test\/image\/*png' --weight_path '\/kaggle\/input\/siim-v5-weights\/*\/*\/*\/best.pt'\n!cp -r ..\/input\/yolox-inference\/* .\n!python inference.py -f ..\/input\/yolox-weights\/yolox_weights\/yolox_siim_d_f0.py -c ss --path '\/kaggle\/tmp\/test\/image\/*png' \\\n    --wei_dir ..\/input\/yolox-weights\/yolox_weights\/ --conf 0.0001 --nms 0.5 --tsize 384 --save_result --device gpu\n!cp -r ..\/input\/siimeffdet\/* .\n!python predict_oof_det.py --is_val 0 --test_path '\/kaggle\/tmp\/test\/image\/*png' --model_dir ..\/input\/siim-det-models\/\n! cp det\/* det_txt\n! python ensemble1.py --input_path  'det_txt\/*txt' --image_path '\/kaggle\/tmp\/test\/image\/*png' --thr 0.001\n#mask_dir = f'\/kaggle\/tmp\/{split}\/mask\/'\n#os.makedirs(mask_dir, exist_ok=True)\n#!cp -r ..\/input\/siimsegs\/* .\n#!python train_seg.py --image_path '\/kaggle\/tmp\/test\/image\/*png' --weight_path best_loss.pth\n!cp -r ..\/input\/siim-cls-code\/* .\n!python main.py -C n_cf11_6 -M test -W ..\/input\/siim-cls-weights\/n_cf11_6_f3\/\n!python main.py -C n_cf11 -M test -W ..\/input\/siim-cls-weights\/n_cf11_l1\/\n!python main.py -C n_cf11_7 -M test -W ..\/input\/siim-cls-weights\/n_cf11_7\/\n#!python main.py -C n_cf11_8 -M test -W ..\/input\/siim-cls-weights\/n_cf11_8\/\n!python main.py -C n_cf11_9 -M test -W ..\/input\/siim-cls-weights\/n_cf11_9\/\n!python main.py -C n_cf11_10 -M test -W ..\/input\/siim-cls-weights\/n_cf11_10\/\n!python main.py -C n_cf11_1 -M test -W ..\/input\/siim-cls-weights\/n_cf_11_1\/\n!python main.py -C n_cf11_rot1 -M test -W ..\/input\/siim-cls-weights\/n_cf11_rot1\/\n!pip install -q ..\/input\/landmark-additional-packages\/EfficientNet-PyTorch\/EfficientNet-PyTorch-master \n!pip install -U ..\/input\/landmark-additional-packages\/timm-0.4.12-py3-none-any.whl # to fix \n!pip install ..\/input\/siim-libs\/segmentation_models_pytorch-0.1.3-py3-none-any.whl --no-deps  \n\"\"\"\n## Model difinition\n\"\"\"\nimport sys\nsys.path.append('..\/usr\/lib\/siim_cov_model_v0\/')\nfrom siim_cov_model_v0 import *\n\"\"\"\n## tools and difinition\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport tqdm\nimport cv2\nimport glob\nimport math\nimport csv\nimport torch\nimport operator\nimport sys\nimport os\nfrom path import Path\nfrom skimage.io import imread\nfrom scipy.ndimage.interpolation import zoom\nimport matplotlib.pyplot as plt\nfrom skimage.transform import resize\nimport torchvision\nfrom scipy.stats import rankdata\n\nfrom torchvision.transforms import (\n    ToTensor, Normalize, Compose, Resize, CenterCrop, RandomCrop,\n    RandomHorizontalFlip, RandomAffine, RandomVerticalFlip, RandomChoice, ColorJitter, RandomRotation)\n\nsys.path.append('..\/input\/siim-covid-aggron-eecf6c\/covid19-aggron')\n\n# from utils import parse_args, prepare_for_result\n# from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler\n# from models import get_model\nfrom losses import get_loss, get_class_balanced_weighted\n# from dataloaders import get_dataloader\n# from utils import load_matched_state\nfrom configs import Config\n# import seaborn as sns\n# from dataloaders.transform_loader import get_tfms\n\nfrom sklearn.metrics import f1_score, roc_auc_score, average_precision_score\n\"\"\"\n## Uncompress test data\n\"\"\"\ntest_path = '\/kaggle\/tmp\/test\/image\/'\nclass COVIDDataset(torch.utils.data.Dataset):\n    def __init__(self, df, cfg=None, tfms=None, path='.'):\n        self.df = df\n        self.cfg = cfg\n        self.tfms = tfms\n        self.tensor_tfms = torchvision.transforms.Compose([\n            torchvision.transforms.ToTensor(),\n            torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n            # torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n        ])\n        self.path = '.\/'\n        # self.path = Path('\/home\/sheep\/kaggle\/siim')\n        self.studys = self.df['StudyInstanceUID'].unique()\n        print(len(self.studys))\n        self.cols = ['Negative for Pneumonia', 'Typical Appearance', 'Indeterminate Appearance', 'Atypical Appearance']\n        self.cols2index = {x: i for i, x in enumerate(self.cols)}\n        self.path = path\n\n    def __len__(self):\n        return len(self.studys)\n\n    def __getitem__(self, idx):\n        study_id = self.studys[idx]\n        sub_df = self.df[self.df.StudyInstanceUID == study_id].copy()\n        images = []\n        masks = []\n        study = [idx for _ in range(sub_df.shape[0])]\n        image_as_study = []\n        bbox = []\n        label_study = 0\n        has_masks = []\n        iids = []\n        for i, row in sub_df.iterrows():\n            img = cv2.imread(str(self.path + f'\/{row.ImageUID}.png'))\n            sz = self.cfg.transform.size\n            mask = np.zeros((sz, sz))\n            has_mask = 1\n            has_masks.append(has_mask)\n            label = 0\n            if self.tfms:\n                tf = self.tfms(image=img, mask=mask)\n                img = tf['image']\n                mask = tf['mask']\n            if not img.shape[0] == self.cfg.transform.size:\n                img = cv2.resize(img, (self.cfg.transform.size, self.cfg.transform.size))\n            # resize to aux\n            if self.cfg.transform.size == 512:\n                msksz = 32\n            elif self.cfg.transform.size == 384:\n                msksz = 24\n            elif self.cfg.transform.size == 640:\n                msksz = 40\n            elif self.cfg.transform.size == 700:\n                msksz = 44\n            elif self.cfg.transform.size == 720:\n                msksz = 45\n            elif self.cfg.transform.size == 768:\n                msksz = 48\n            else:\n                msksz = 32\n            mask = cv2.resize(mask, (msksz, msksz))\n            masks.append(torch.FloatTensor(mask).view(1, mask.shape[0], mask.shape[1]))\n            img = self.tensor_tfms(img)\n            images.append(img)\n            image_as_study.append(label)\n            iids.append(row.ImageUID)\n        images = torch.stack(images)\n        masks = torch.stack(masks)\n        return images, study, label_study, image_as_study, masks, iids\n    \ndef idoit_collect_func(batch):\n    img, study, lbl, image_as_study, bbox, has_masks = [], [], [], [], [], []\n    for im, st, lb, ias, bb, has_m in batch:\n        img.extend(im)\n        study.extend(st)\n        lbl.append(lb)\n        image_as_study.extend(ias)\n        bbox.extend(bb)\n        has_masks.extend(has_m)\n    return torch.stack(img), study, torch.tensor(lbl), torch.tensor(image_as_study), torch.stack(bbox), has_masks\ndef load_model(cfg):\n    if cfg.model.name == 'v2m_aux':\n        #     def __init__(self, name, dropout=0, pool='AdaptiveAvgPool2d'):\n        drop = cfg.model.param.get('dropout', 0)\n        pool = cfg.model.param.get('last_pool', 'AdaptiveAvgPool2d')\n        return AUXNet(name='tf_efficientnetv2_m', dropout=drop, pool=pool)\n    elif cfg.model.name == 'v2m_aux_v2':\n        drop = cfg.model.param.get('dropout', 0)\n        pool = cfg.model.param.get('last_pool', 'AdaptiveAvgPool2d')\n        return AUXNetV2(name='tf_efficientnetv2_m', dropout=drop, pool=pool)\n    elif cfg.model.name == 'b5_aux':\n        drop = cfg.model.param.get('dropout', 0)\n        pool = cfg.model.param.get('last_pool', 'AdaptiveAvgPool2d')\n        return AUXNetb5(name='tf_efficientnetv2_m', dropout=drop)\n    elif cfg.model.name == 'v2l_aux':\n        drop = cfg.model.param.get('dropout', 0)\n        pool = cfg.model.param.get('last_pool', 'AdaptiveAvgPool2d')\n        return AUXNetL(name='tf_efficientnetv2_l', dropout=drop)\ndef predict_run(RUN, test, is_none = False):\n    df = pd.read_csv(f'{RUN}\/train.log', sep='\\t')\n    fold2epochs = {}\n    for i in range(0, 5):\n        eph = df[df.Fold == i].sort_values('F1@0.3', ascending=False).iloc[0].Epochs\n        fold2epochs[i] = int(eph)\n\n    print(fold2epochs.values())\n\n    predicted = []\n    # load the model\n    models = []\n    for f in range(5):\n        cfg = Config.load_json(f'{RUN}\/config.json')\n        cfg.experiment.run_fold = f\n        model = load_model(cfg).cuda()\n        load_matched_state(model, torch.load(\n            glob.glob(f'{RUN}\/checkpoints\/f{f}*-{fold2epochs[f]}*')[0]))\n        model.eval()\n        models.append(model)\n        \n    # inference\n    test_ds = COVIDDataset(test, cfg=cfg, path=test_path)\n    test_dl = torch.utils.data.DataLoader(test_ds, num_workers=2, batch_size=32, collate_fn=idoit_collect_func)\n    with torch.no_grad():\n        results = []\n        predicted, image_ids = [], []\n        for i, (img, study_index, lbl_study, label_image, mask_t, iids) in tqdm.tqdm(enumerate(test_dl)):\n            img = img.cuda()\n            sz = img.size()[0]\n            img = torch.stack([img,img.flip(-1)],0) # hflip\n            img = img.view(-1, 3, img.shape[-1], img.shape[-1])\n            preds = []\n            for m in models:\n                with torch.cuda.amp.autocast():\n                    logits, mask = m(img)\n                logits = logits.float()\n                if cfg.loss.name == 'bce':\n                    logits = torch.sigmoid(logits)\n                else:\n                    logits = torch.softmax(logits, 1)\n                cls = (logits[:sz] + logits[sz:]) \/ 2\n                preds.append(cls)\n            predicted.append(torch.stack(preds).mean(0).cpu())\n            image_ids.extend(iids)\n    if is_none:\n        return pd.DataFrame(torch.cat(predicted).numpy(), index=image_ids,\n             columns=['Negative for Pneumonia', 'Typical Appearance'])\n    else:\n        return pd.DataFrame(torch.cat(predicted).numpy(), index=image_ids,\n             columns=['Negative for Pneumonia', 'Typical Appearance', 'Indeterminate Appearance', 'Atypical Appearance'])\n\"\"\"\n## Test assets\n\"\"\"\ntest = pd.read_csv('test_meta.csv')[[\"image_id\", \"study_id\"]]\ntest = test.rename(columns={\"image_id\": \"ImageUID\", \"study_id\": \"StudyInstanceUID\"})\nfor e in ['Negative for Pneumonia', 'Typical Appearance', 'Indeterminate Appearance', 'Atypical Appearance']:\n    test[e] = 0\ntest.head()\n\"\"\"\n## BCE loss with pl\n\"\"\"\nr9 = predict_run(\n    '..\/input\/siim-covid-aux-bce-agg-exp-rot-30-20-v2l-pl\/aux_bce_agg_exp_rot_30_20_v2l_pl.upload', test)\nr8 = predict_run(\n    '..\/input\/aux-bce-agg-exp-rot-30-20-b5-pl\/aux_bce_agg_exp_rot_30_20_b5_pl.upload', test)\nr = predict_run(\n    '..\/input\/siim-covid-aux-aug-v2m-lm-aggron-40-clean-cut1\/aux_aug_v2m_lm_aggron_40_clean_cut1.yaml_upload', test)\nr3 = predict_run(\n    '..\/input\/siim-covid-aux-bce-agg-exp-rot-30-20-pl\/aux_bce_agg_exp_rot_30_20_pl.upload', test)\n\"\"\"\n## CE model\n\"\"\"\nr2 = predict_run(\n    '..\/input\/siim-covid-aux-bce-v2m-lm-aggron-40-clean-cut1-pl\/aux_bce_v2m_lm_aggron_40_clean_cut1_bce_pl.upload', test)\nr4 = predict_run(\n    '..\/input\/siim-cov-dddddd-dbg-1-aux-2\/dddddd_dbg_1_aux_2_upload', test)\nr5 = predict_run(\n    '..\/input\/siim-cov-clean-oof-clean-agree-upload\/clean_oof_clean_agree_upload', test)\nr6 = predict_run(\n    '..\/input\/siim-cov-aux-aug-agg-exp-rot-30\/aux_aug_agg_exp_rot_30.yaml_upload', test)\nr7 = predict_run(\n    '..\/input\/siim-cov-model-modelv2upload\/model_modelV2.upload', test)\nimage_result = (r + r2 + r3 + 0.5 * r4 + r5 + r6 + 0.75 * r7 + r8 + r9) \/ 8.25\nimage_result = image_result.reset_index()\nimage_result.to_csv('sheep_df.csv')\n\"\"\"\n**2 class**\n\"\"\"\nclass AUXNet(nn.Module):\n    def __init__(self, name, dropout=0, pool='AdaptiveAvgPool2d'):\n        super(AUXNet, self).__init__()\n\n        print('[ AUX model ] dropout: {}, pool: {}'.format(dropout, pool))\n        e = timm.models.__dict__[name](pretrained=False, drop_rate=0.3, drop_path_rate=0.2)\n        self.model = e\n        self.b0 = nn.Sequential(\n            e.conv_stem,\n            e.bn1,\n            e.act1,\n        )\n        self.b1 = e.blocks[0]\n        self.b2 = e.blocks[1]\n        self.b3 = e.blocks[2]\n        self.b4 = e.blocks[3]\n        self.b5 = e.blocks[4]\n        self.b6 = e.blocks[5]\n        self.b7 = e.blocks[6]\n        self.b8 = nn.Sequential(\n            e.conv_head, #384, 1536\n            e.bn2,\n            e.act2,\n        )\n\n        self.logit = nn.Linear(1280,2)\n        self.mask = nn.Sequential(\n            nn.Conv2d(176, 128, kernel_size=3, padding=1),\n            nn.BatchNorm2d(128),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(128, 128, kernel_size=3, padding=1),\n            nn.BatchNorm2d(128),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(128, 1, kernel_size=1, padding=0),\n        )\n\n        self.dropout = nn.Dropout(p=dropout)\n\n        if pool == 'AdaptiveAvgPool2d':\n            self.pooling = nn.AdaptiveAvgPool2d(1)\n        elif pool == 'gem':\n            self.pooling = GeM()\n\n    # @torch.cuda.amp.autocast()\n    def forward(self, image):\n        batch_size = len(image)\n        # x = 2*image-1     # ; print('input ',   x.shape)\n        x = image\n\n        x = self.b0(x) #; print (x.shape)  # torch.Size([2, 40, 256, 256])\n        x = self.b1(x) #; print (x.shape)  # torch.Size([2, 24, 256, 256])\n        x = self.b2(x) #; print (x.shape)  # torch.Size([2, 32, 128, 128])\n        x = self.b3(x) #; print (x.shape)  # torch.Size([2, 48, 64, 64])\n        x = self.b4(x) #; print (x.shape)  # torch.Size([2, 96, 32, 32])\n        x = self.b5(x) #; print (x.shape)  # torch.Size([2, 136, 32, 32])\n        #------------\n        mask = self.mask(x)\n        #-------------\n        x = self.b6(x) #; print (x.shape)  # torch.Size([2, 232, 16, 16])\n        x = self.b7(x) #; print (x.shape)  # torch.Size([2, 384, 16, 16])\n        x = self.b8(x) #; print (x.shape)  # torch.Size([2, 1536, 16, 16])\n        # x = F.adaptive_avg_pool2d(x,1).reshape(batch_size,-1)\n        x = nn.Flatten()(self.pooling(x))\n        x = self.dropout(x)\n        logit = self.logit(x)\n        return logit, mask\nnone_1 = predict_run(\n    '..\/input\/two-class-bce-fix-valid-bbox-two-classes-12-pl-2x\/two_class_bce_fix_valid_bbox_two_classes_12_pl_2x.upload', test, True)\nnone_2 = predict_run(\n    '..\/input\/two-class-bce-fix-valid-bbox-two-classes-12upload\/two_class_bce_fix_valid_bbox_two_classes_12.upload', test, True)\nnone_result = (none_1 + none_2) \/ 2\nnone_result.to_csv('public_test_sheep_predict_none.csv')\n! python tocsv.py --input_path  'test_v5neg_2a.txt' --meta_path 'test_meta.csv'\ndef prob2str(row):\n    return f'negative {row.pred_cls1:.6f} 0 0 1 1 typical {row.pred_cls2:.6f} 0 0 1 1 indeterminate {row.pred_cls3:.6f} 0 0 1 1 atypical {row.pred_cls4:.6f} 0 0 1 1'\n    #return f''\ndef combine_image(row):\n     return f'none {row.pred_cls5:.6f} 0 0 1 1 {row.PredictionString}'\n        #return f''\ndef tosub(df1):\n    df1_image = df1[['image_id', 'pred_cls1', 'pred_cls5', 'PredictionString']].copy()\n    df1_image.rename(columns={\"image_id\": \"id\"}, inplace=True)\n    df1_image['id'] = df1_image['id'].apply(lambda x: f'{x}_image')\n    df1_image['PredictionString'] = df1_image.apply(lambda r: combine_image(r), axis=1) \n    df1_image = df1_image[['id', 'PredictionString']]\n    \n    df1_study = df1[['study_id', 'pred_cls1', 'pred_cls2', 'pred_cls3', 'pred_cls4']].copy()\n    df1_study = df1_study.groupby('study_id').agg('mean').reset_index()\n    df1_study.rename(columns={\"study_id\": \"id\"}, inplace=True)\n    df1_study['id'] = df1_study['id'].apply(lambda x: f'{x}_study')\n    df1_study[\"PredictionString\"] = df1_study.apply(lambda r: prob2str(r), axis=1) \n    df1_study = df1_study[['id', 'PredictionString']]\n\n    df1_sub = pd.concat([df1_study, df1_image])\n\n    return df1_sub\ndf1 = pd.read_csv('n_cf11_9.csv') \ndf2 = pd.read_csv('n_cf11.csv')#.head(10)\ndf3 = pd.read_csv('n_cf11_6.csv')\ndf4 = pd.read_csv('n_cf11_7.csv')\ndf5 = pd.read_csv('n_cf11_10.csv')\ndf6 = pd.read_csv('n_cf11_rot1.csv')\ndf7 = pd.read_csv('n_cf11_1.csv')\n#df8 = pd.read_csv('n_cf11_8.csv')\n\ndf2 = df1[[\"image_id\"]].merge(df2, on=[\"image_id\"])\ndf3 = df1[[\"image_id\"]].merge(df3, on=[\"image_id\"])\ndf4 = df1[[\"image_id\"]].merge(df4, on=[\"image_id\"])\ndf5 = df1[[\"image_id\"]].merge(df5, on=[\"image_id\"])\ndf6 = df1[[\"image_id\"]].merge(df6, on=[\"image_id\"])\ndf7 = df1[[\"image_id\"]].merge(df7, on=[\"image_id\"])\n#df8 = df1[[\"image_id\"]].merge(df8, on=[\"image_id\"])\n\nsheep_df = pd.read_csv('sheep_df.csv')\nsheep_df = sheep_df.rename(columns={\"index\": \"image_id\", \"Negative for Pneumonia\": \"pred_cls1\", \n                         \"Typical Appearance\": \"pred_cls2\", \"Indeterminate Appearance\": \"pred_cls3\",\n                        \"Atypical Appearance\": \"pred_cls4\"})\nsheep_df = df2[[\"image_id\"]].merge(sheep_df, on=[\"image_id\"])\n\nfor col in ['pred_cls1', 'pred_cls2', 'pred_cls3', 'pred_cls4', 'pred_cls5']:\n    df1[col] = (df1[col] + df2[col] + df3[col] + df4[col] + df5[col] + df6[col] + df7[col])\/7\n    \nfor col in ['pred_cls1', 'pred_cls2', 'pred_cls3', 'pred_cls4']:\n    df1[col] = (1*df1[col] + sheep_df[col])\/2\n    \nsheep_none_df = pd.read_csv('public_test_sheep_predict_none.csv')\nsheep_none_df[\"image_id\"] = sheep_none_df['Unnamed: 0']\nsheep_none_df = df1[[\"image_id\"]].merge(sheep_none_df, on=[\"image_id\"])\n\n#df1['pred_cls5'] = sheep_none_df['Negative for Pneumonia']\ndf1['pred_cls5'] = 2*(1-df1['pred_cls5']) + 1*sheep_df['pred_cls1'] + 1*sheep_none_df['Negative for Pneumonia']\n\nimage_sub = pd.read_csv('v5_50.csv')\nimage_sub = df1[[\"image_id\"]].merge(image_sub, on=[\"image_id\"])\ndf1['PredictionString'] = image_sub['PredictionString']\ndf_sub  = tosub(df1)\ndf_sub.tail()\ndf_sub.head()\n!rm -r .\/*\ndf_sub.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'ff98073dd31c69'}"}
{"id":"133814","text":"\"\"\"\nIt is a fork of https:\/\/www.kaggle.com\/hukuda222\/nfl-simple-model-using-lightgbm\n\nMany thanks to hukuda222: https:\/\/www.kaggle.com\/hukuda222\n\n## Introduction\nI will introduce a simple method using lightGBM as a starter.\nfor the original notebook\ncredit and many thanks to hukuda222\n\"\"\"\n\"\"\"\n## import\nLoad the necessary libraries.\n\"\"\"\nimport os\nimport pandas as pd\nfrom kaggle.competitions import nflrush\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nimport random\nimport gc\nimport pickle\nimport tqdm\ndef GPI(data):\n    return (0.100000*np.tanh(np.where(np.where(data[\"Y15\"]>=15.970001, data[\"Y7\"], data[\"Y15\"] )<20.0, data[\"NflId16\"], ((((np.where(np.where(3.0>=20.709999, data[\"X11\"], data[\"X11\"] )<12.0, data[\"JerseyNumber3\"], data[\"PlayerWeight13\"] )) - (data[\"S6\"]))) - (data[\"S6\"])) )) +\n            0.100000*np.tanh(((data[\"X19\"]) + (np.where(((data[\"X19\"]) + (np.where(((data[\"X7\"]) + (np.where(((np.where(data[\"Dis2\"]<0.400000, data[\"Orientation7\"], data[\"Dir17\"] )) * (data[\"PlayerWeight14\"]))>=15.170002, data[\"Orientation7\"], (-1.0*((data[\"X19\"]))) )))>=15.170002, data[\"Orientation7\"], (-1.0*((data[\"X19\"]))) )))>=15.170002, data[\"Dir17\"], (-1.0*((data[\"X8\"]))) )))) +\n            0.100000*np.tanh(np.where(np.where(data[\"S17\"]<0.070000, data[\"PlayerWeight10\"], ((data[\"Orientation12\"]) * (data[\"NflId4\"])) )>=190.0, data[\"PlayerWeight10\"], (-1.0*((data[\"NflId4\"]))) )) +\n            0.100000*np.tanh(np.where(data[\"VisitorTeamAbbr\"]>=0.070000, np.where(data[\"YardLine\"]<2.0, ((((data[\"VisitorTeamAbbr\"]) \/ 2.0)) \/ 2.0), data[\"Y1\"] ), np.where(data[\"Dir15\"]<1.0, (-1.0*((data[\"Y19\"]))), data[\"Y1\"] ) )) +\n            0.100000*np.tanh(np.where(data[\"PlayerCollegeName6\"]<20.0, data[\"X4\"], ((((((((data[\"Distance\"]) * (((np.where(data[\"Orientation1\"]<0.410000, data[\"WindSpeed\"], ((data[\"Distance\"]) * (data[\"YardLine\"])) )) * (data[\"YardLine\"]))))) * (data[\"YardLine\"]))) - (data[\"Quarter\"]))) * (data[\"Orientation1\"])) )) +\n            0.100000*np.tanh(np.where(data[\"Orientation13\"]>=20.0, np.where(np.where(np.where(np.where(data[\"Distance\"]>=2.0, data[\"Orientation13\"], (10.0) )>=20.0, (10.0), data[\"YardLine\"] )>=2.0, data[\"PlayerWeight10\"], data[\"Distance\"] )>=20.0, (10.0), data[\"YardLine\"] ), np.where(np.where(data[\"Orientation2\"]<0.710000, 0.0, data[\"PlayerCollegeName5\"] )<0.710000, (-1.0*((data[\"Distance\"]))), (12.69783782958984375) ) )) +\n            0.100000*np.tanh(np.where(data[\"Orientation14\"]>=9.0, np.where(np.where(data[\"Orientation13\"]<16.020000, ((data[\"Orientation5\"]) * 2.0), data[\"Orientation14\"] )<0.650000, (-1.0*((data[\"X21\"]))), ((((data[\"Orientation14\"]) * (data[\"Orientation12\"]))) * 2.0) ), np.where(data[\"Orientation13\"]<16.020000, data[\"Orientation2\"], data[\"Orientation13\"] ) )) +\n            0.100000*np.tanh(np.where(np.where(((data[\"DefendersInTheBox\"]) * 2.0)>=20.290009, np.where(np.where(data[\"Position0\"]>=16.209991, data[\"Position9\"], np.where(np.where(data[\"Dir19\"]>=160.0, data[\"X0\"], np.where(data[\"Position9\"]<0.410000, data[\"DisplayName21\"], data[\"Dir19\"] ) )>=20.570007, data[\"DisplayName21\"], -3.0 ) )>=20.570007, data[\"Dir20\"], -3.0 ), -3.0 )>=20.360008, -3.0, data[\"X13\"] )) +\n            0.100000*np.tanh(((np.where(data[\"DefendersInTheBox\"]<10.0, np.where(data[\"X17\"]<15.570007, np.where(data[\"X11\"]<15.570007, data[\"Distance\"], data[\"X11\"] ), data[\"X11\"] ), np.where(np.where(np.where(data[\"DefendersInTheBox\"]<0.420000, data[\"X11\"], np.where(data[\"Y5\"]<20.699997, data[\"Dis2\"], data[\"X17\"] ) )<15.570007, data[\"Dis2\"], data[\"JerseyNumber8\"] )<15.570007, (-1.0*((data[\"X11\"]))), data[\"X17\"] ) )) \/ 2.0)) +\n            0.100000*np.tanh(np.where(np.where(data[\"HomeTeamAbbr\"]>=0.460000, np.where(data[\"Dir1\"]>=0.460000, np.where(data[\"Dir17\"]>=0.460000, np.where(data[\"Distance\"]<2.0, data[\"YardLine\"], data[\"Distance\"] ), data[\"HomeTeamAbbr\"] ), data[\"HomeTeamAbbr\"] ), data[\"X11\"] )>=2.0, data[\"X11\"], (-1.0*(((6.0)))) )) +\n            0.100000*np.tanh(np.where(data[\"Dir14\"]<15.529999, data[\"X12\"], np.where(np.where(data[\"Dir14\"]>=192.0, data[\"Dir5\"], data[\"Dir14\"] )<20.809998, data[\"X13\"], ((np.where(((((((data[\"X8\"]) \/ 2.0)) \/ 2.0)) + (data[\"X4\"]))<15.529999, data[\"Distance\"], ((data[\"DB\"]) * 2.0) )) + (((((-3.0) * 2.0)) \/ 2.0))) ) )) +\n            0.100000*np.tanh(((((((((((data[\"DB\"]) * (3.0))) - (3.0))) * 2.0)) - (data[\"DB\"]))) * (3.0))) +\n            0.100000*np.tanh(((data[\"PlayerHeight20\"]) - (((((((((-3.0) * (((-3.0) - (((((((data[\"S16\"]) \/ 2.0)) - (data[\"DB\"]))) * (data[\"OffensePersonnel\"]))))))) - (data[\"OffensePersonnel\"]))) * (data[\"DB\"]))) * (data[\"OffensePersonnel\"]))))) +\n            0.100000*np.tanh(np.where(data[\"Orientation19\"]>=1.0, np.where(np.where(data[\"Orientation19\"]<20.680008, data[\"DisplayName18\"], data[\"Orientation19\"] )<0.610000, -2.0, data[\"X19\"] ), ((data[\"PlayerHeight10\"]) - (np.where(data[\"Orientation12\"]>=120.0, np.where(data[\"DisplayName18\"]>=120.0, data[\"Orientation19\"], ((data[\"DisplayName18\"]) * (data[\"Orientation19\"])) ), ((data[\"Orientation19\"]) * (2.0)) ))) )) +\n            0.100000*np.tanh(((np.where((((np.where(((data[\"DB\"]) * ((6.0)))<14.0, -3.0, (6.0) )) + (data[\"S20\"]))\/2.0)<0.060000, ((np.where(-3.0<14.0, -3.0, data[\"DB\"] )) * 2.0), data[\"DB\"] )) * 2.0)) +\n            0.100000*np.tanh(((np.where(((data[\"YardLine\"]) * 2.0)<6.0, data[\"YardLine\"], data[\"Y0\"] )) + (((np.where(data[\"OffenseFormation\"]<6.0, data[\"YardLine\"], (((data[\"Y17\"]) + (((((1.0) - (data[\"DefendersInTheBox\"]))) - (data[\"DefendersInTheBox\"]))))\/2.0) )) + (((((data[\"YardLine\"]) * 2.0)) - (data[\"DefendersInTheBox\"]))))))) +\n            0.100000*np.tanh((((((-1.0*((2.0)))) + ((((((-1.0*((data[\"S14\"])))) + (np.where(data[\"DB\"]<2.0, np.where(data[\"PossessionTeam\"]<20.619995, (-1.0*((2.0))), (-1.0*((data[\"X19\"]))) ), np.where(data[\"Dir3\"]<0.660000, data[\"PossessionTeam\"], data[\"X19\"] ) )))) + (data[\"PossessionTeam\"]))))) * 2.0)) +\n            0.100000*np.tanh(((((((-3.0) * 2.0)) + (((data[\"DB\"]) * (data[\"DB\"]))))) + (np.where(((2.0) + (data[\"X13\"]))<15.760010, np.where(((((-3.0) * 2.0)) + (((data[\"DB\"]) * (data[\"DB\"]))))<0.410000, data[\"DB\"], ((-3.0) * 2.0) ), data[\"A11\"] )))) +\n            0.100000*np.tanh(((data[\"DefendersInTheBox\"]) * (np.where(((data[\"DefendersInTheBox\"]) + (((data[\"Dis16\"]) - (np.where(np.where(data[\"Y6\"]<20.339996, data[\"PlayerHeight6\"], data[\"Y9\"] )>=15.529999, np.where(data[\"X1\"]>=15.529999, 1.0, ((data[\"Dis16\"]) - (np.tanh((data[\"PlayerHeight6\"])))) ), np.tanh((data[\"PlayerHeight6\"])) )))))<9.0, data[\"DefendersInTheBox\"], ((-3.0) \/ 2.0) )))) +\n            0.100000*np.tanh(((data[\"X17\"]) * (((data[\"OffensePersonnel\"]) * ((((((((6.0)) * (((((data[\"X17\"]) - (data[\"S5\"]))) + ((((6.0)) * (-1.0))))))) - (data[\"S5\"]))) + ((((6.0)) * (-1.0))))))))) +\n#             0.100000*np.tanh(np.where(((data[\"A1\"]) * (((np.where(data[\"DefendersInTheBox\"]<11.0, data[\"X8\"], data[\"DefendersInTheBox\"] )) - ((10.66025257110595703)))))>=0.410000, np.where(data[\"X8\"]>=11.0, (6.0), (((9.0)) - (data[\"Position6\"])) ), (-1.0*((((data[\"X8\"]) * (np.where(data[\"X8\"]>=11.0, data[\"X8\"], ((data[\"X8\"]) - (data[\"Position6\"])) )))))) )) +\n#             0.100000*np.tanh(((((((((data[\"DB\"]) - (data[\"DL\"]))) * 2.0)) + (((data[\"X6\"]) - (2.0))))) * (((((data[\"X6\"]) * (((data[\"DB\"]) + (((((data[\"DB\"]) - (data[\"DL\"]))) * 2.0)))))) + (((-2.0) * ((6.60063505172729492)))))))) +\n#             0.100000*np.tanh(((((((((((((np.where((((0.0) + (data[\"DB\"]))\/2.0)>=2.0, data[\"NflId6\"], data[\"Distance\"] )) * (data[\"A12\"]))) - ((((0.0) + (data[\"DB\"]))\/2.0)))) * (data[\"A12\"]))) - ((((data[\"A12\"]) + (data[\"DB\"]))\/2.0)))) * (data[\"NflId6\"]))) - ((((2.0) + (data[\"DB\"]))\/2.0)))) +\n#             0.100000*np.tanh(np.where(((data[\"PlayerWeight0\"]) + (2.0))>=192.0, data[\"PlayerWeight0\"], (((-1.0*((np.where((((-1.0*((np.where(((data[\"PlayerWeight0\"]) + (data[\"OffenseFormation\"]))>=192.0, data[\"PlayerWeight0\"], (((-1.0*((data[\"OffenseFormation\"])))) + (data[\"Dir11\"])) ))))) + (data[\"Dir11\"]))>=0.0, 1.0, data[\"PlayerWeight0\"] ))))) + (data[\"Dir11\"])) )) +\n#             0.100000*np.tanh(((((np.where(((((data[\"DefendersInTheBox\"]) * 2.0)) - (-1.0))>=20.419998, 0.0, np.where((((9.0)) + (data[\"X8\"]))>=20.419998, data[\"X8\"], -3.0 ) )) - (data[\"DB\"]))) - (data[\"DB\"]))) +\n#             0.100000*np.tanh(np.where(np.where((((((-1.0*((np.where(data[\"Dis1\"]<0.060000, -3.0, data[\"DL\"] ))))) \/ 2.0)) - (-3.0))<0.410000, data[\"Dis1\"], ((((data[\"A18\"]) * ((14.82150459289550781)))) * 2.0) )<0.410000, -3.0, (((((((14.82150459289550781)) * ((14.82150459289550781)))) * 2.0)) * 2.0) )) +\n#             0.100000*np.tanh(np.where(((((data[\"X14\"]) + ((11.61672115325927734)))) \/ 2.0)>=13.0, data[\"X3\"], np.where(((1.0) + (data[\"X3\"]))<20.360352, (((((9.0)) - (np.where(np.where(data[\"X14\"]<1.0, (12.86960315704345703), ((1.0) + (data[\"X3\"])) )>=13.0, data[\"PlayerHeight8\"], (12.86959934234619141) )))) * 2.0), ((2.0) * 2.0) ) )) +\n#             0.100000*np.tanh(((np.where(((((data[\"X15\"]) - ((10.10870170593261719)))) * 2.0)>=2.0, data[\"X16\"], np.where(((((data[\"X15\"]) - ((10.10870170593261719)))) * 2.0)<1.0, data[\"DB\"], ((data[\"X15\"]) * 2.0) ) )) + ((-1.0*((((data[\"DB\"]) * 2.0))))))) +\n#             0.100000*np.tanh(((np.where(data[\"X12\"]<100.0, np.where(((-1.0) + (((data[\"Distance\"]) + (np.where(data[\"PlayerWeight2\"] < -9998, data[\"X12\"], data[\"X12\"] )))))<20.770004, data[\"Distance\"], data[\"PlayerWeight2\"] ), np.where(data[\"X6\"]<100.0, np.where(data[\"X12\"]>=100.0, ((data[\"Distance\"]) + (data[\"X12\"])), data[\"Distance\"] ), data[\"Distance\"] ) )) - (data[\"DefendersInTheBox\"]))) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X14\"]>=13.0, data[\"X14\"], np.where(data[\"X14\"]>=12.0, data[\"Dis12\"], np.where(data[\"X14\"]<9.0, ((np.where(data[\"X14\"]<9.0, data[\"Position0\"], data[\"OffensePersonnel\"] )) + (data[\"X14\"])), ((data[\"OffensePersonnel\"]) + (-3.0)) ) ) )>=12.0, (((((data[\"DB\"]) + (-3.0))\/2.0)) * (data[\"X14\"])), -3.0 )) +\n#             0.100000*np.tanh(((data[\"YardLine\"]) - (np.where(data[\"X3\"]<14.0, np.where(np.where(data[\"YardLine\"]<14.810001, data[\"PlayerCollegeName1\"], 3.0 )<14.810001, -3.0, data[\"DB\"] ), np.where(data[\"YardLine\"]>=20.450005, 3.0, np.where(data[\"X3\"]<14.810001, data[\"PlayerCollegeName1\"], np.where(data[\"PlayerCollegeName1\"]>=20.450005, np.where(data[\"Dis18\"]<14.0, 3.0, data[\"DB\"] ), data[\"DB\"] ) ) ) )))) +\n#             0.100000*np.tanh(np.where(data[\"X2\"]<20.809998, np.where(np.where(data[\"X17\"]<20.809998, data[\"X3\"], data[\"X2\"] )>=12.0, data[\"X3\"], (-1.0*((data[\"X2\"]))) ), np.where(np.where(data[\"X17\"]<20.809998, data[\"X17\"], data[\"X16\"] )>=12.0, data[\"X17\"], ((((((-1.0*((data[\"X17\"])))) * 2.0)) + (data[\"X2\"]))\/2.0) ) )) +\n#             0.100000*np.tanh(((((np.where((((data[\"OffensePersonnel\"]) + (((-3.0) + (-3.0))))\/2.0)<20.699997, ((-3.0) + (np.where(data[\"X18\"]<9.0, data[\"X8\"], data[\"YardLine\"] ))), data[\"YardLine\"] )) + (-2.0))) + ((-1.0*((((data[\"DB\"]) - (np.where(-2.0>=20.620003, data[\"YardLine\"], data[\"YardLine\"] ))))))))) +\n#             0.100000*np.tanh(np.where(0.0>=2.0, data[\"DefendersInTheBox\"], np.where(np.where(data[\"DefendersInTheBox\"]>=0.410000, data[\"DefendersInTheBox\"], data[\"X5\"] )<10.0, np.where(data[\"X5\"]>=13.0, np.where(data[\"X7\"]>=13.0, data[\"X16\"], (-1.0*(((5.0)))) ), np.where(data[\"X13\"]<20.310005, -3.0, data[\"JerseyNumber10\"] ) ), (-1.0*((((data[\"X5\"]) - (data[\"JerseyNumber7\"]))))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"GameHour\"]<0.670000, np.where(((data[\"DefendersInTheBox\"]) * (3.0))>=20.240005, ((data[\"X10\"]) * 2.0), ((data[\"DefendersInTheBox\"]) * 2.0) ), data[\"DefendersInTheBox\"] )<15.529999, np.where(((data[\"X20\"]) * 2.0)>=20.469994, data[\"DefendersInTheBox\"], -3.0 ), -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"YardLine\"]<6.0, np.where(((((((data[\"X10\"]) + (((-3.0) * (data[\"YardLine\"]))))) + (data[\"DefendersInTheBox\"]))) * (data[\"YardLine\"]))<20.469994, ((data[\"OffensePersonnel\"]) + (1.0)), ((np.where(((data[\"DB\"]) * (data[\"YardLine\"]))<20.469994, -3.0, data[\"DefendersInTheBox\"] )) * 2.0) ), data[\"YardLine\"] )) +\n#             0.100000*np.tanh(((((((((np.where(np.where(((((np.where(data[\"DefendersInTheBox\"]<0.710000, data[\"Distance\"], (9.67302703857421875) )) - (data[\"DefendersInTheBox\"]))) * ((11.92878818511962891)))>=20.419998, data[\"Distance\"], -1.0 )<0.710000, data[\"Distance\"], (9.67302703857421875) )) - (data[\"DefendersInTheBox\"]))) * ((11.92878818511962891)))) - (data[\"DefendersInTheBox\"]))) * (data[\"X4\"]))) +\n#             0.100000*np.tanh((((((np.where((((data[\"X9\"]) + (-1.0))\/2.0)>=13.0, data[\"PlayerWeight13\"], ((np.where(data[\"PlayerCollegeName2\"]>=20.299988, np.where(data[\"X4\"]>=13.0, np.where(np.where(data[\"DefendersInTheBox\"]<20.699997, data[\"Orientation17\"], data[\"X9\"] )<20.699997, -1.0, data[\"PlayerWeight13\"] ), -1.0 ), data[\"X9\"] )) - (data[\"S15\"])) )) + (data[\"DefendersInTheBox\"]))\/2.0)) - (data[\"X9\"]))) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(data[\"PlayerCollegeName7\"]>=20.240005, data[\"Orientation2\"], data[\"PlayerCollegeName7\"] )<100.0, data[\"X12\"], data[\"X10\"] )<19.849609, data[\"PlayerCollegeName12\"], np.where(np.where(np.where(-1.0>=20.240005, data[\"X1\"], data[\"PlayerCollegeName7\"] )<100.0, data[\"X12\"], data[\"YardLine\"] )<19.849609, data[\"X7\"], data[\"X16\"] ) )<100.0, data[\"X16\"], (-1.0*((data[\"PlayerCollegeName12\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Y14\"]<1.0, data[\"X12\"], data[\"X12\"] )<15.170002, -2.0, ((data[\"X12\"]) + ((((-1.0*((data[\"X8\"])))) + (np.where(np.where(((np.where(((data[\"X20\"]) * 2.0)>=190.0, data[\"X12\"], -2.0 )) * 2.0)>=190.0, data[\"Y14\"], -2.0 )<20.339996, data[\"X8\"], (-1.0*((data[\"PlayerHeight6\"]))) ))))) )) +\n#             0.100000*np.tanh(np.where(data[\"Orientation15\"]<2550449.0, np.where((((data[\"Distance\"]) + ((((data[\"Distance\"]) + (1.0))\/2.0)))\/2.0)<7.0, ((np.where(np.where(np.where(data[\"YardLine\"]<20.339996, data[\"Distance\"], data[\"Humidity\"] )>=16.610352, data[\"Dir13\"], -2.0 )<11.0, -2.0, data[\"X4\"] )) + (-1.0)), data[\"X12\"] ), -2.0 )) +\n#             0.100000*np.tanh(np.where(data[\"X9\"]>=0.0, np.where(((data[\"X14\"]) \/ 2.0)>=20.310005, np.where(data[\"X1\"]>=100.0, ((data[\"Distance\"]) - (data[\"PlayerHeight20\"])), np.where(np.where(data[\"PlayerHeight20\"]<8.0, data[\"X14\"], data[\"X0\"] )>=100.0, ((1.0) - (((data[\"Distance\"]) \/ 2.0))), data[\"Distance\"] ) ), ((data[\"Distance\"]) - (data[\"DB\"])) ), data[\"Distance\"] )) +\n#             0.100000*np.tanh(np.where(np.where((((data[\"A18\"]) + (data[\"YardLine\"]))\/2.0)<6.0, ((data[\"Distance\"]) + ((-1.0*((data[\"YardLine\"]))))), np.where(np.where(data[\"NflId20\"]<2552586.0, (((-1.0*((data[\"A18\"])))) \/ 2.0), data[\"Distance\"] )>=2.0, data[\"PlayerCollegeName16\"], np.where(data[\"PlayerCollegeName16\"]<15.700001, data[\"NflId20\"], 1.0 ) ) )<2.0, -2.0, data[\"YardLine\"] )) +\n#             0.100000*np.tanh(np.where(((data[\"PlayerHeight0\"]) * 2.0)<20.360008, np.where(((np.where(data[\"PlayerHeight20\"]<2.0, np.where(data[\"X2\"]<20.480003, data[\"S0\"], -2.0 ), data[\"S0\"] )) + (-2.0))<1.0, ((data[\"PlayerHeight0\"]) * 2.0), (-1.0*((data[\"Humidity\"]))) ), np.where(np.where(data[\"A3\"]<0.420000, -2.0, data[\"Humidity\"] )<0.420000, -2.0, data[\"Humidity\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerCollegeName0\"]>=6.0, data[\"Dir1\"], (-1.0*((data[\"JerseyNumber2\"]))) )>=20.619995, np.where(data[\"OffensePersonnel\"]>=16.100006, ((np.where(data[\"NflId6\"]<2539306.0, data[\"Dir1\"], data[\"JerseyNumber2\"] )) - (data[\"X11\"])), np.where(((data[\"YardLine\"]) * 2.0)>=9.0, data[\"YardLine\"], (-1.0*((data[\"PlayerCollegeName0\"]))) ) ), (-1.0*((data[\"Dir1\"]))) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName12\"]<0.070000, data[\"Distance\"], ((np.where(((np.where(((((data[\"Distance\"]) - (data[\"DefendersInTheBox\"]))) - (data[\"S12\"]))<0.070000, data[\"S12\"], ((data[\"PlayerCollegeName12\"]) - (-2.0)) )) - (data[\"DefendersInTheBox\"]))<0.070000, ((data[\"A14\"]) * (data[\"A14\"])), data[\"Distance\"] )) - (data[\"DefendersInTheBox\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"PlayerCollegeName18\"]) \/ 2.0)<14.0, np.where(data[\"PlayerCollegeName18\"]<20.450005, np.where(data[\"Y2\"]>=17.850006, data[\"PlayerCollegeName2\"], -2.0 ), (-1.0*((data[\"X1\"]))) ), data[\"DefendersInTheBox\"] )<8.0, np.where(data[\"PossessionTeam\"]<0.660000, np.where(data[\"X10\"]<20.450005, data[\"DefendersInTheBox\"], -3.0 ), data[\"PlayerCollegeName18\"] ), (-1.0*((data[\"Y2\"]))) )) +\n#             0.100000*np.tanh(np.where(np.tanh((((np.where(np.where(data[\"S8\"]<0.410000, data[\"S8\"], (((-3.0) + (data[\"DB\"]))\/2.0) )>=0.660000, ((np.where((((data[\"Distance\"]) + (-2.0))\/2.0)<0.410000, data[\"FieldPosition\"], data[\"DefendersInTheBox\"] )) \/ 2.0), data[\"Stadium\"] )) + (data[\"DefendersInTheBox\"]))))>=1.0, -3.0, np.where(data[\"S8\"]<0.410000, 0.0, data[\"DefendersInTheBox\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dir0\"]<91.0, data[\"Dir0\"], np.where(data[\"X13\"]<91.0, np.where(data[\"GameHour\"]<0.610000, 2.0, data[\"Orientation2\"] ), data[\"Dis16\"] ) )>=20.370117, ((np.where(np.where(2.0<0.610000, data[\"X17\"], data[\"Orientation19\"] )<0.610000, data[\"X13\"], data[\"Orientation19\"] )) - (((((data[\"Orientation1\"]) \/ 2.0)) \/ 2.0))), (-1.0*((data[\"Orientation19\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"NflId9\"]<2552603.0, data[\"S17\"], ((data[\"Dis5\"]) * 2.0) )<0.690000, np.where(data[\"S17\"]>=2552586.0, ((data[\"NflId9\"]) * 2.0), ((np.where(data[\"Orientation7\"]<19.230469, data[\"Dis5\"], data[\"DisplayName0\"] )) - (data[\"Orientation5\"])) ), np.where(data[\"Orientation7\"]<20.310005, data[\"DisplayName19\"], ((((data[\"DisplayName0\"]) - (data[\"Orientation5\"]))) - (data[\"DisplayName19\"])) ) )) +\n#             0.100000*np.tanh(np.where(data[\"X5\"]<20.360008, data[\"PlayerCollegeName15\"], np.where(np.where(np.where(((np.where(data[\"S11\"]>=0.670000, data[\"VisitorScoreBeforePlay\"], -2.0 )) - (data[\"S15\"]))>=0.660000, data[\"A4\"], ((data[\"PlayerHeight13\"]) - ((9.81951904296875000))) )>=0.660000, data[\"S15\"], ((((-2.0) * 2.0)) * 2.0) )>=0.660000, data[\"A6\"], ((-3.0) * 2.0) ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(((data[\"A19\"]) - (data[\"S2\"]))<0.660000, np.where(data[\"S4\"]<6.0, data[\"A19\"], data[\"Dir2\"] ), data[\"Dir2\"] )<20.539993, np.where(data[\"S1\"]<6.0, data[\"DB\"], data[\"Orientation4\"] ), data[\"Y10\"] )>=20.809998, data[\"Y10\"], ((np.where(data[\"DB\"]<6.0, data[\"A6\"], data[\"PlayerCollegeName19\"] )) - (data[\"S4\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"Dis6\"]<0.060000, data[\"PossessionTeam\"], np.where(data[\"Dis14\"]<0.060000, data[\"Position18\"], np.where(np.where(data[\"PossessionTeam\"]>=15.880005, data[\"Position18\"], data[\"A2\"] )>=3.0, np.where(data[\"Position18\"]<13.0, data[\"S10\"], np.where(data[\"Position18\"]<20.450005, (-1.0*((3.0))), data[\"S15\"] ) ), np.where(data[\"PlayerCollegeName11\"]<131.0, data[\"Dis6\"], (-1.0*((data[\"S15\"]))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"DefendersInTheBox\"]<6.0, data[\"DefendersInTheBox\"], np.where(2.0>=105.0, data[\"PlayerWeight1\"], np.where(data[\"PlayerCollegeName10\"]>=20.539993, np.where(data[\"DefendersInTheBox\"]<11.0, np.where(data[\"Position2\"]>=0.670000, np.where(data[\"Orientation16\"]>=0.670000, ((data[\"A17\"]) - (((data[\"S9\"]) - (-1.0)))), data[\"DefendersInTheBox\"] ), data[\"PlayerCollegeName10\"] ), data[\"DefendersInTheBox\"] ), data[\"PlayerHeight17\"] ) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X16\"]<173.0, np.where(data[\"PlayerCollegeName9\"]<173.0, data[\"PlayerWeight21\"], ((data[\"PlayerCollegeName8\"]) - (data[\"Orientation12\"])) ), data[\"PlayerCollegeName9\"] )<192.0, data[\"Temperature\"], np.where(((np.where(data[\"Orientation12\"]<173.0, data[\"PlayerWeight21\"], data[\"Y9\"] )) - (data[\"PlayerCollegeName9\"]))>=190.0, data[\"PlayerCollegeName9\"], ((data[\"X16\"]) - (data[\"Orientation2\"])) ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Y3\"]<15.170002, 0.0, np.where(np.where(np.where(np.where(data[\"VisitorScoreBeforePlay\"]<20.469994, data[\"PlayerCollegeName18\"], data[\"S9\"] )>=20.299988, data[\"Distance\"], 0.0 )<2.0, data[\"Dis16\"], data[\"VisitorScoreBeforePlay\"] )<2.0, data[\"Dis16\"], ((data[\"PlayerHeight0\"]) * 2.0) ) )<2.0, data[\"Dis21\"], data[\"PlayerCollegeName16\"] )>=0.630000, data[\"VisitorScoreBeforePlay\"], (-1.0*((data[\"S9\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(np.where(data[\"Dir21\"]>=29.0, data[\"Orientation10\"], data[\"Position9\"] )>=20.809998, np.where(data[\"Dir21\"]>=29.0, data[\"Orientation10\"], data[\"S0\"] ), data[\"Position3\"] )>=19.559570, np.where(data[\"Y19\"]>=19.559570, data[\"PlayerCollegeName2\"], data[\"Position9\"] ), data[\"S0\"] )<18.549988, data[\"Dir21\"], data[\"NflIdRusher\"] )>=2550449.0, data[\"NflId8\"], (-1.0*((data[\"PlayerCollegeName2\"]))) )) +\n#             0.100000*np.tanh(((data[\"Orientation20\"]) - (np.where(np.where(np.where((5.01929426193237305)<20.360352, np.where(((data[\"X20\"]) * 2.0)>=131.0, (8.0), (((((data[\"Position10\"]) + (data[\"PossessionTeam\"]))\/2.0)) * 2.0) ), data[\"X19\"] )>=19.559570, data[\"PossessionTeam\"], ((data[\"PossessionTeam\"]) * (data[\"HomeScoreBeforePlay\"])) )>=20.809998, data[\"Dir18\"], ((data[\"Position10\"]) * 2.0) )))) +\n#             0.100000*np.tanh(((np.where(np.where(data[\"Dis11\"]>=0.440000, np.where(data[\"Dis11\"]<0.420000, data[\"PlayerWeight16\"], data[\"Dir4\"] ), data[\"PlayerWeight16\"] )<191.0, data[\"NflId20\"], ((np.where(data[\"Dis11\"]>=0.410000, np.where(data[\"A1\"]>=0.660000, np.where(data[\"OffensePersonnel\"]<20.619995, (-1.0*((data[\"DefendersInTheBox\"]))), data[\"Y20\"] ), data[\"DB\"] ), data[\"DB\"] )) - (data[\"DefendersInTheBox\"])) )) + (data[\"A1\"]))) +\n#             0.100000*np.tanh((-1.0*((np.where(np.where(np.where(data[\"DisplayName16\"]<11.0, data[\"Dis12\"], np.where(data[\"X4\"]<91.0, data[\"JerseyNumber3\"], data[\"Dis12\"] ) )>=11.0, np.where(np.where(data[\"Dis12\"]<0.070000, data[\"Orientation20\"], np.where(data[\"Position21\"]<0.070000, data[\"Orientation20\"], data[\"OffensePersonnel\"] ) )<11.0, data[\"X4\"], data[\"OffensePersonnel\"] ), data[\"Dis12\"] )<20.619995, data[\"X4\"], (-1.0*((data[\"Position15\"]))) ))))) +\n#             0.100000*np.tanh(np.where(((data[\"PossessionTeam\"]) * 2.0)>=0.060000, np.where(data[\"Position12\"]>=20.680008, data[\"PlayerHeight0\"], np.where(data[\"JerseyNumber16\"]>=20.419998, np.where(data[\"Y6\"]<20.440002, ((3.0) * 2.0), np.where(np.where(data[\"Dis3\"]<0.410000, data[\"X19\"], data[\"Position12\"] )>=14.619999, (-1.0*((((data[\"PlayerHeight10\"]) * 2.0)))), data[\"Y21\"] ) ), data[\"JerseyNumber16\"] ) ), (-1.0*((data[\"PlayerHeight0\"]))) )) +\n#             0.100000*np.tanh(np.where(data[\"DefendersInTheBox\"]<6.0, np.where(data[\"A16\"]<20.290009, data[\"DefendersInTheBox\"], data[\"NflId11\"] ), np.where(np.where(data[\"Y7\"]<20.0, np.where(data[\"A16\"]<0.429999, data[\"A7\"], data[\"JerseyNumber1\"] ), data[\"DefendersInTheBox\"] )>=20.0, data[\"S17\"], ((data[\"A20\"]) - (np.where(data[\"OffenseFormation\"]>=6.0, data[\"S17\"], np.where(data[\"OffenseFormation\"]>=6.0, data[\"JerseyNumber1\"], (3.0) ) ))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dis18\"] < -9998, -2.0, ((data[\"Position5\"]) * 2.0) )>=14.0, np.where(data[\"PlayerCollegeName10\"]>=20.469994, np.where(np.where(np.where(data[\"PlayerHeight20\"]<8.0, data[\"A11\"], -2.0 )>=0.0, np.where(data[\"A11\"]<0.0, data[\"Position5\"], data[\"PlayerHeight12\"] ), data[\"Orientation1\"] )<8.0, data[\"DisplayName8\"], (-1.0*((data[\"S12\"]))) ), data[\"PlayerHeight12\"] ), data[\"Position5\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"JerseyNumber21\"]>=20.360008, data[\"WindDirection\"], np.where(data[\"DefendersInTheBox\"]<7.0, data[\"WindDirection\"], ((((data[\"X10\"]) \/ 2.0)) * (data[\"Dis19\"])) ) )<13.0, (-1.0*((data[\"WindDirection\"]))), np.where(data[\"Y8\"]>=20.709999, data[\"A4\"], ((((((data[\"X10\"]) \/ 2.0)) * (data[\"Dis19\"]))) - (data[\"Position19\"])) ) )) +\n#             0.100000*np.tanh(np.where(data[\"Dis9\"]<0.410000, np.where(np.where(data[\"Position7\"]>=13.770000, np.where(data[\"Orientation20\"]>=20.419998, data[\"Dis13\"], (-1.0*((data[\"A8\"]))) ), data[\"Dis2\"] )<0.410000, np.where((-1.0*((data[\"X11\"])))<15.0, data[\"A8\"], data[\"Dir15\"] ), -2.0 ), np.where(data[\"Dir15\"]<191.0, -2.0, data[\"Position7\"] ) )) +\n#             0.100000*np.tanh(np.where(data[\"DefendersInTheBox\"]<6.0, data[\"DefendersInTheBox\"], (-1.0*((np.where(np.where(((data[\"PlayerCollegeName8\"]) - (data[\"PlayerWeight9\"]))<14.669998, np.where(data[\"PlayerHeight1\"]<12.0, data[\"PlayerCollegeName14\"], data[\"VisitorTeamAbbr\"] ), data[\"S21\"] )<29.0, np.where(-1.0<16.100006, np.where(data[\"Dir19\"]<6.0, data[\"DB\"], (-1.0*((data[\"PlayerWeight9\"]))) ), data[\"X9\"] ), data[\"Dir16\"] )))) )) +\n#             0.100000*np.tanh(np.where((-1.0*((data[\"PlayerHeight0\"])))<20.480003, np.where(np.where(data[\"PlayerHeight0\"]>=2532966.0, (5.21651887893676758), data[\"Y0\"] )>=19.940430, np.where(data[\"OffensePersonnel\"]>=19.940430, (((data[\"A3\"]) + (np.where(data[\"PlayerCollegeName2\"]>=122.0, data[\"Orientation7\"], (-1.0*((data[\"PlayerHeight0\"]))) )))\/2.0), ((((data[\"PlayerHeight0\"]) - ((5.21651887893676758)))) - (data[\"PlayerHeight21\"])) ), data[\"A3\"] ), data[\"PlayerCollegeName2\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Orientation12\"]>=160.0, np.where(np.where(np.where(data[\"PlayerCollegeName4\"]<160.0, data[\"DisplayName0\"], data[\"Dir12\"] )<160.0, data[\"X0\"], ((-3.0) \/ 2.0) )>=0.670000, np.where(data[\"Dir12\"]<160.0, np.where(data[\"PlayerCollegeName4\"]<160.0, data[\"DisplayName0\"], 0.0 ), data[\"Dir12\"] ), data[\"DisplayName4\"] ), data[\"Orientation8\"] )>=160.0, data[\"S11\"], (-1.0*((data[\"S1\"]))) )) +\n#             0.100000*np.tanh(np.where((((-1.0*((data[\"Stadium\"])))) + (np.where(data[\"DefendersInTheBox\"]>=6.0, np.where(np.where(data[\"Dis2\"]>=20.440002, 3.0, data[\"WindSpeed\"] )>=20.440002, data[\"Dir14\"], data[\"NflId20\"] ), 3.0 )))<20.360008, data[\"DefendersInTheBox\"], ((((data[\"GameWeather\"]) - (data[\"Stadium\"]))) - (data[\"PlayerCollegeName11\"])) )) +\n#             0.100000*np.tanh(((np.where(data[\"FieldPosition\"]>=14.810001, ((np.where(data[\"FieldPosition\"]>=14.810001, np.where(data[\"S15\"]<1.0, data[\"S15\"], np.where(data[\"HomeTeamAbbr\"]<12.0, data[\"FieldPosition\"], np.where(data[\"HomeTeamAbbr\"]>=14.810001, np.where(data[\"HomeTeamAbbr\"]<20.619995, data[\"Distance\"], data[\"PlayerHeight18\"] ), data[\"A4\"] ) ) ), data[\"A4\"] )) - (data[\"S15\"])), data[\"A4\"] )) - (data[\"S15\"]))) +\n#             0.100000*np.tanh(np.where(data[\"Y17\"]>=23.0, np.where(np.where(data[\"YardLine\"]>=20.240005, np.where(data[\"JerseyNumber17\"]<20.339996, ((data[\"PlayerCollegeName4\"]) * 2.0), data[\"PlayerCollegeName14\"] ), data[\"PlayerCollegeName6\"] )>=192.0, data[\"PlayerCollegeName4\"], np.where(np.where(((data[\"PlayerCollegeName4\"]) * 2.0)<94.0, data[\"JerseyNumber5\"], data[\"PlayerWeight8\"] )<192.0, data[\"PlayerCollegeName6\"], -2.0 ) ), np.where(data[\"PlayerCollegeName6\"]<20.339996, data[\"JerseyNumber21\"], -2.0 ) )) +\n#             0.100000*np.tanh(np.where(data[\"DisplayName17\"]<131.0, (-1.0*((data[\"S18\"]))), np.where(data[\"Y20\"]<33.0, np.where(data[\"DisplayName8\"]<131.0, (-1.0*((data[\"DisplayName8\"]))), np.where(data[\"Y20\"]>=20.339996, np.where(data[\"JerseyNumber15\"]>=20.339996, ((((data[\"PlayerCollegeName0\"]) - (data[\"DefendersInTheBox\"]))) \/ 2.0), (-1.0*((data[\"DefendersInTheBox\"]))) ), data[\"PlayerCollegeName0\"] ) ), (-1.0*((data[\"Y20\"]))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X15\"]<20.620003, data[\"A9\"], data[\"A12\"] )>=2.0, data[\"PlayerHeight9\"], np.where(np.where(data[\"DB\"]<6.0, data[\"PlayerHeight9\"], np.where(data[\"JerseyNumber16\"]<20.620003, data[\"A12\"], data[\"A9\"] ) )<0.420000, data[\"S13\"], np.where(np.where(data[\"JerseyNumber16\"]<20.620003, data[\"Orientation16\"], data[\"A9\"] )>=2.0, data[\"DB\"], (-1.0*((data[\"S12\"]))) ) ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Position14\"]>=20.619995, data[\"PlayerHeight17\"], np.where(np.where(np.where(np.where(-2.0>=2555281.0, data[\"Position14\"], data[\"JerseyNumber2\"] )>=14.0, ((data[\"PlayerCollegeName4\"]) \/ 2.0), data[\"S2\"] )>=6.0, ((data[\"Orientation19\"]) \/ 2.0), 0.0 )>=6.0, data[\"JerseyNumber18\"], 0.0 ) )<14.0, data[\"JerseyNumber2\"], data[\"Dis13\"] )<0.420000, data[\"PlayerCollegeName4\"], -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"DisplayName1\"]>=190.0, np.where(np.where(np.where(data[\"Y8\"]>=20.709999, data[\"Orientation11\"], data[\"PlayerHeight5\"] )<12.0, data[\"Dir16\"], data[\"Dir21\"] )>=192.0, ((((np.where(data[\"DisplayName16\"]<20.240005, np.where(data[\"PlayerHeight5\"]<20.240005, data[\"DisplayName16\"], data[\"DisplayName16\"] ), data[\"DisplayName7\"] )) \/ 2.0)) - (data[\"X0\"])), ((data[\"X0\"]) - (data[\"DisplayName16\"])) ), data[\"VisitorScoreBeforePlay\"] )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight5\"]<0.070000, data[\"A8\"], ((np.where(np.where(data[\"S16\"]<20.619995, np.where(np.where(data[\"A7\"]<20.0, data[\"PlayerHeight20\"], data[\"NflIdRusher\"] )<2.0, data[\"X9\"], data[\"DL\"] ), data[\"PlayerHeight5\"] )<20.450005, np.where(data[\"S16\"]<2.0, 3.0, (-1.0*((data[\"NflIdRusher\"]))) ), data[\"PlayerHeight5\"] )) - (data[\"Quarter\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Dis1\"]>=0.060000, np.where(np.where(np.where(data[\"Dir10\"]<21.809998, data[\"X0\"], data[\"A2\"] )>=14.0, data[\"Position11\"], data[\"Y10\"] )>=20.0, data[\"Dir0\"], data[\"Dis8\"] ), data[\"Position11\"] )<20.620003, data[\"Dis1\"], data[\"Dir18\"] )<14.0, np.where(((data[\"PlayerCollegeName8\"]) \/ 2.0)<20.719994, data[\"Y16\"], (-1.0*((data[\"Dir0\"]))) ), data[\"Y10\"] )) +\n#             0.100000*np.tanh(np.where(data[\"JerseyNumber21\"]<20.570007, np.where(data[\"JerseyNumber21\"]<14.0, data[\"Position18\"], np.where(-3.0<191.0, ((data[\"A15\"]) - (data[\"Dir1\"])), np.where(data[\"JerseyNumber16\"] < -9998, ((data[\"A15\"]) - (data[\"S9\"])), data[\"Temperature\"] ) ) ), np.where(data[\"Position18\"]<19.540009, ((data[\"A8\"]) - (data[\"S9\"])), data[\"PossessionTeam\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(data[\"Y21\"]>=29.0, np.where(data[\"S5\"]>=1.0, ((data[\"X9\"]) - (data[\"Orientation11\"])), data[\"DisplayName2\"] ), data[\"DisplayName2\"] )<20.539993, data[\"X14\"], ((data[\"X9\"]) - (data[\"Orientation11\"])) )>=29.0, data[\"A4\"], data[\"X13\"] )<20.539993, data[\"X13\"], ((data[\"S8\"]) - (data[\"PlayerCollegeName12\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"A14\"]>=0.650000, ((data[\"VisitorScoreBeforePlay\"]) - (np.where(data[\"PlayerHeight15\"]>=12.0, data[\"Orientation19\"], np.where(data[\"Dis2\"]>=20.709999, data[\"Dir6\"], np.where(data[\"JerseyNumber10\"]>=20.709999, np.where(data[\"PlayerCollegeName9\"]>=20.709999, np.where(data[\"Orientation19\"]>=99.0, data[\"Dis5\"], data[\"NflIdRusher\"] ), np.tanh((-1.0)) ), 0.0 ) ) ))), ((data[\"A14\"]) - (data[\"NflIdRusher\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"JerseyNumber7\"]>=19.070007, np.where(np.where(data[\"DisplayName0\"]>=16.029999, data[\"Dis2\"], (((((-1.0*((data[\"Y0\"])))) * 2.0)) * 2.0) )>=0.070000, np.where(data[\"Y11\"]>=19.070007, ((data[\"X9\"]) - (data[\"Y0\"])), ((data[\"Dis2\"]) * 2.0) ), (((4.0)) - (data[\"Position10\"])) ), np.tanh(((-1.0*(((4.0)))))) )) +\n#             0.100000*np.tanh(np.where(data[\"A13\"]<0.400000, (-1.0*((data[\"GameWeather\"]))), np.where(np.where(data[\"A21\"]>=1.0, (((data[\"A21\"]) + ((-1.0*((data[\"LB\"])))))\/2.0), ((data[\"DL\"]) - (data[\"S8\"])) )>=0.060000, np.where(np.where(data[\"DefendersInTheBox\"]>=18.549988, data[\"GameWeather\"], data[\"A21\"] )<0.690000, data[\"DL\"], data[\"Stadium\"] ), ((data[\"A13\"]) - (data[\"PlayerHeight5\"])) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X21\"]>=102.0, -3.0, data[\"DefendersInTheBox\"] )>=6.0, np.where(np.where(data[\"A3\"]<3.0, np.where(data[\"PlayerCollegeName2\"]<20.809998, data[\"JerseyNumber8\"], np.where(data[\"X6\"]<20.809998, data[\"PlayerCollegeName8\"], data[\"PlayerWeight21\"] ) ), data[\"PlayerCollegeName2\"] )>=192.0, (-1.0*((data[\"Dir3\"]))), data[\"NflIdRusher\"] ), data[\"X21\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dir0\"]>=20.469994, np.where(data[\"X16\"]<16.079987, data[\"X7\"], np.where(data[\"Dis15\"]>=0.070000, np.where(np.where(data[\"X8\"]<20.719994, data[\"Dis15\"], data[\"A10\"] )>=0.410000, data[\"A17\"], data[\"Dis3\"] ), (-1.0*((np.where(data[\"X8\"]<20.719994, -3.0, data[\"A10\"] )))) ) ), ((data[\"Dis3\"]) * 2.0) )>=0.670000, data[\"X16\"], -3.0 )) +\n#             0.100000*np.tanh(((np.where(np.where(((data[\"S14\"]) * (data[\"PlayerHeight5\"]))>=20.620003, data[\"Orientation5\"], data[\"X18\"] )>=94.0, -2.0, data[\"S6\"] )) - (((data[\"OffenseFormation\"]) - (np.where(np.where(data[\"A13\"]>=0.660000, data[\"Y5\"], ((data[\"Y5\"]) - (data[\"Orientation5\"])) )<9.0, np.where(data[\"OffenseFormation\"]<19.260010, 0.0, data[\"PlayerHeight5\"] ), data[\"GameHour\"] )))))) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerHeight13\"]<9.0, np.where(data[\"JerseyNumber2\"]>=10.0, np.where(data[\"Dir8\"]>=20.469994, data[\"PlayerCollegeName2\"], data[\"S15\"] ), data[\"Position13\"] ), np.where(data[\"PlayerCollegeName2\"]<29.0, data[\"X16\"], np.where(data[\"Position13\"]>=0.640000, data[\"Position13\"], data[\"JerseyNumber2\"] ) ) )<29.0, (-1.0*((np.where(data[\"PlayerCollegeName2\"]<29.0, data[\"X16\"], data[\"PlayerHeight20\"] )))), ((data[\"JerseyNumber2\"]) * 2.0) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(np.where(((data[\"S20\"]) \/ 2.0)>=0.630000, data[\"PlayerHeight5\"], ((-3.0) * 2.0) )<0.700000, ((data[\"Y11\"]) \/ 2.0), data[\"Y11\"] )<20.680008, data[\"Dir18\"], data[\"S20\"] )>=20.680008, data[\"PlayerHeight5\"], data[\"Orientation2\"] )<29.0, data[\"FieldPosition\"], np.where(data[\"A15\"]>=0.420000, -3.0, data[\"Y11\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Orientation18\"]<191.0, data[\"X0\"], data[\"Dis19\"] )<20.680008, np.where(data[\"Orientation21\"]<191.0, data[\"Orientation18\"], ((data[\"Orientation18\"]) - (data[\"Orientation18\"])) ), np.where(data[\"Dis5\"]<0.070000, data[\"Orientation18\"], ((data[\"A21\"]) - (np.where(((data[\"X3\"]) - (data[\"X16\"]))>=0.070000, data[\"S10\"], data[\"Orientation18\"] ))) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName3\"]<131.0, np.where(data[\"Position0\"]<0.420000, data[\"Position14\"], ((data[\"A1\"]) + (-2.0)) ), np.where(np.where(data[\"A1\"]>=0.660000, data[\"PlayerCollegeName19\"], np.where(data[\"X17\"]<14.0, data[\"JerseyNumber1\"], data[\"Position0\"] ) )<20.360008, -2.0, np.where(data[\"JerseyNumber1\"]>=20.360008, data[\"Position0\"], -1.0 ) ) )) +\n#             0.100000*np.tanh(np.where(((data[\"PlayerCollegeName17\"]) * (data[\"Dis1\"]))>=16.209991, np.where(((data[\"Position1\"]) * (data[\"Dis1\"]))<0.670000, data[\"PlayerCollegeName17\"], np.where(data[\"Dis6\"]<0.060000, data[\"X11\"], np.where(np.where(data[\"DisplayName21\"]<20.970001, -2.0, data[\"DefendersInTheBox\"] )<6.0, data[\"PlayerCollegeName17\"], -2.0 ) ) ), np.where(data[\"A11\"]<0.420000, -2.0, data[\"PlayerCollegeName17\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"A5\"]>=758.0, data[\"Position1\"], np.where(data[\"A5\"]<1.0, data[\"JerseyNumber11\"], np.where(data[\"Y17\"]>=20.970001, data[\"A5\"], data[\"Orientation12\"] ) ) )<15.579987, ((data[\"Orientation12\"]) - (data[\"PlayerCollegeName20\"])), ((np.where(data[\"Dir15\"]<20.419998, data[\"A5\"], data[\"Position2\"] )) - (np.where(data[\"Dir15\"]>=20.970001, data[\"Position8\"], data[\"JerseyNumber7\"] ))) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight9\"]<0.420000, data[\"Dis21\"], np.where(data[\"DisplayName2\"]>=29.0, np.where(data[\"JerseyNumber19\"]>=29.0, np.where(data[\"Dir8\"]>=190.0, data[\"S11\"], np.where(((data[\"Y8\"]) \/ 2.0)<20.970001, np.where(data[\"PlayerHeight9\"]<14.0, np.where(data[\"Dis21\"]<0.060000, data[\"Y8\"], (-1.0*((data[\"DisplayName11\"]))) ), data[\"JerseyNumber19\"] ), data[\"Dir8\"] ) ), data[\"A14\"] ), data[\"S11\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerCollegeName9\"]>=18.549988, np.where(np.where(np.where(data[\"PlayerHeight0\"]<0.070000, -3.0, np.where(np.where(data[\"JerseyNumber8\"]>=18.549988, data[\"PlayerHeight11\"], data[\"PlayerHeight0\"] )>=10.0, data[\"PlayerCollegeName9\"], np.tanh((data[\"A12\"])) ) )>=6.0, data[\"PlayerCollegeName9\"], data[\"X0\"] )>=122.0, data[\"PlayerCollegeName9\"], data[\"DefendersInTheBox\"] ), data[\"PlayerCollegeName9\"] )>=10.0, data[\"PlayerCollegeName9\"], -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"Y7\"]>=14.0, np.where(data[\"Y4\"]<20.360008, data[\"X16\"], np.where(data[\"JerseyNumber6\"]<29.0, data[\"A13\"], ((np.where(data[\"Position19\"]<23.0, np.where(data[\"HomeTeamAbbr\"]<20.480003, (-1.0*((data[\"Y7\"]))), np.where(data[\"HomeTeamAbbr\"]>=15.009998, data[\"A3\"], (-1.0*((data[\"Y7\"]))) ) ), (-1.0*((data[\"Position19\"]))) )) \/ 2.0) ) ), data[\"DefendersInTheBox\"] )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Dis2\"]<16.270000, data[\"Dis2\"], np.where(data[\"Orientation19\"]>=0.440000, data[\"Dis11\"], data[\"JerseyNumber1\"] ) )>=0.420000, data[\"Position14\"], np.where(np.where(data[\"Y20\"]<20.970001, data[\"A4\"], data[\"Dis11\"] )>=0.420000, data[\"DefendersInTheBox\"], data[\"DisplayName19\"] ) )>=20.0, np.where(data[\"DisplayName21\"]>=20.470001, ((data[\"Dir15\"]) - (data[\"DisplayName10\"])), data[\"Orientation19\"] ), data[\"DisplayName10\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dis17\"]>=0.440000, data[\"Quarter\"], data[\"HomeScoreBeforePlay\"] )<15.139999, np.where(np.where(data[\"PlayerCollegeName20\"]>=10.0, data[\"JerseyNumber3\"], data[\"HomeScoreBeforePlay\"] )<20.699997, np.where(data[\"HomeScoreBeforePlay\"]>=11.0, -2.0, data[\"A10\"] ), np.where(data[\"HomeScoreBeforePlay\"]<0.710000, (-1.0*((data[\"PlayerCollegeName20\"]))), data[\"HomeScoreBeforePlay\"] ) ), (-1.0*((((data[\"PlayerWeight3\"]) * 2.0)))) )) +\n#             0.100000*np.tanh(np.where(data[\"PossessionTeam\"]<1.0, np.where(data[\"YardLine\"]>=120.0, data[\"X15\"], (-1.0*((data[\"Orientation0\"]))) ), np.where(((np.where(np.where(data[\"Y5\"]>=20.570007, data[\"A3\"], data[\"A16\"] )>=0.710000, np.where(data[\"S11\"]>=0.710000, data[\"Orientation0\"], data[\"PossessionTeam\"] ), data[\"Y16\"] )) \/ 2.0)>=20.440002, data[\"PossessionTeam\"], (-1.0*((data[\"Orientation0\"]))) ) )) +\n#             0.100000*np.tanh(np.where(((data[\"Dir14\"]) \/ 2.0)>=20.0, np.where(data[\"PlayerCollegeName10\"]<12.0, data[\"Orientation21\"], np.where(data[\"Orientation21\"]>=15.529999, np.where(data[\"Dir7\"]<20.340004, -3.0, np.tanh((((data[\"PlayerCollegeName10\"]) - (data[\"PlayerWeight18\"])))) ), data[\"Dir14\"] ) ), ((((data[\"PlayerWeight18\"]) - (data[\"Orientation21\"]))) * (data[\"DB\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"Position21\"]>=0.070000, np.where(np.where(np.where(data[\"Orientation8\"]<10.0, data[\"Position21\"], data[\"Dir12\"] )<10.0, ((((data[\"Orientation8\"]) - (data[\"Dir17\"]))) - (data[\"Dir3\"])), data[\"Dir12\"] )<19.589996, (-1.0*((((data[\"Orientation8\"]) - (data[\"PlayerWeight7\"]))))), ((data[\"Orientation8\"]) - (data[\"PlayerWeight7\"])) ), (-1.0*((data[\"Orientation6\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"Y9\"]) - (data[\"Y8\"]))>=20.699997, -1.0, data[\"Y3\"] )<14.189999, -2.0, np.where(data[\"A9\"]>=0.660000, np.where(np.where(data[\"Y9\"]>=16.170013, data[\"Orientation6\"], np.where(data[\"Y3\"]>=16.170013, data[\"S15\"], data[\"Y9\"] ) )<20.360008, (-1.0*((data[\"PlayerCollegeName11\"]))), data[\"Y9\"] ), np.tanh((-1.0)) ) )) +\n#             0.100000*np.tanh(np.where(((data[\"A5\"]) - (data[\"S12\"]))>=2495328.0, data[\"A15\"], np.where(((data[\"PlayerHeight9\"]) * (data[\"A15\"]))>=20.440002, data[\"PlayerHeight18\"], np.where(data[\"A5\"]<0.410000, ((data[\"Position17\"]) \/ 2.0), np.where(data[\"Dis4\"]<0.070000, data[\"X8\"], np.where(((data[\"Dis10\"]) * 2.0)<0.070000, data[\"X8\"], ((data[\"A5\"]) - (data[\"S12\"])) ) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight3\"]<0.650000, data[\"S0\"], np.where(data[\"DB\"]>=6.0, data[\"Position15\"], np.where(data[\"Position15\"]<0.650000, data[\"Dis17\"], np.where(np.where(np.where(data[\"Position15\"]>=20.680008, data[\"Dis17\"], np.where(data[\"OffensePersonnel\"]>=20.680008, data[\"S10\"], data[\"Dis3\"] ) )>=0.460000, data[\"DisplayName11\"], data[\"S10\"] )>=20.340004, data[\"DB\"], ((data[\"S10\"]) - (data[\"DB\"])) ) ) ) )) +\n#             0.100000*np.tanh(((np.where(np.where(data[\"Orientation10\"]>=20.340004, np.where(data[\"Orientation2\"]>=20.340004, ((np.where(data[\"PlayerCollegeName2\"]<16.490002, data[\"Dis9\"], data[\"Dis6\"] )) * (np.where(data[\"FieldPosition\"]>=20.360008, data[\"Dis6\"], data[\"X5\"] ))), data[\"Orientation10\"] ), data[\"X3\"] )<20.709999, data[\"Orientation2\"], (-1.0*((data[\"Orientation10\"]))) )) \/ 2.0)) +\n#             0.100000*np.tanh(np.where(np.where(data[\"S11\"]>=190.0, data[\"Dir5\"], np.where(((data[\"DisplayName2\"]) * 2.0)>=758.0, np.where(data[\"S11\"]<6.0, data[\"S4\"], ((data[\"PlayerHeight15\"]) - (data[\"PlayerHeight12\"])) ), data[\"PlayerHeight15\"] ) )<2.0, np.where(data[\"S11\"]<6.0, data[\"S4\"], data[\"PlayerHeight15\"] ), ((((data[\"PlayerHeight15\"]) - (data[\"PlayerHeight12\"]))) - (data[\"Week\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X21\"]>=20.450005, data[\"Position6\"], np.where(np.where(np.where(data[\"A15\"]>=0.710000, data[\"DefendersInTheBox\"], data[\"VisitorTeamAbbr\"] )<10.0, data[\"Dir3\"], data[\"A15\"] )<20.450005, data[\"JerseyNumber18\"], data[\"X21\"] ) )>=20.0, np.where(np.where(data[\"HomeScoreBeforePlay\"]<0.410000, data[\"Dir3\"], data[\"Humidity\"] )<20.450005, -3.0, data[\"X21\"] ), ((np.tanh((-3.0))) \/ 2.0) )) +\n#             0.099961*np.tanh(np.where(np.where(((data[\"DefendersInTheBox\"]) * 2.0)>=15.009998, np.where(((((data[\"X20\"]) - (data[\"DefendersInTheBox\"]))) \/ 2.0)<12.0, data[\"Dis14\"], data[\"Orientation9\"] ), data[\"X20\"] )<94.0, np.where(data[\"X11\"]>=23.0, np.where(data[\"X11\"]<20.480003, (-1.0*((data[\"NflId17\"]))), data[\"Orientation9\"] ), -3.0 ), (((-1.0*((data[\"X6\"])))) \/ 2.0) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerCollegeName11\"]>=20.570007, data[\"PlayerCollegeName18\"], data[\"A2\"] )<18.290009, data[\"PlayerHeight13\"], np.where(data[\"X6\"]<18.290009, data[\"PlayerHeight13\"], np.where(data[\"PlayerHeight13\"]>=12.0, data[\"PlayerHeight10\"], np.where(data[\"PlayerHeight13\"]<0.060000, data[\"Humidity\"], ((np.where(data[\"A18\"]<0.660000, np.where(data[\"PlayerHeight13\"]<20.470001, data[\"PlayerCollegeName0\"], data[\"PlayerHeight13\"] ), data[\"X6\"] )) - (data[\"Orientation13\"])) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"A7\"]<0.420000, data[\"A6\"], np.where(np.where(2.0<0.440000, data[\"DL\"], ((np.where(data[\"Y2\"]<20.709999, (((np.where(data[\"Y2\"]<20.709999, data[\"DisplayName6\"], data[\"DisplayName21\"] )) + (data[\"DL\"]))\/2.0), data[\"DisplayName21\"] )) \/ 2.0) )<191.0, data[\"PlayerCollegeName0\"], ((np.where(data[\"Orientation10\"]<191.0, data[\"S8\"], -2.0 )) - (data[\"PlayerHeight19\"])) ) )) +\n#             0.100000*np.tanh(((np.where(data[\"JerseyNumber11\"]<20.570007, np.where(np.where(data[\"Y21\"]>=20.570007, data[\"JerseyNumber18\"], data[\"VisitorTeamAbbr\"] )>=20.570007, data[\"DisplayName17\"], np.where(data[\"PlayerHeight17\"]<20.340004, data[\"Y21\"], data[\"VisitorTeamAbbr\"] ) ), data[\"X16\"] )) - (np.where(data[\"VisitorTeamAbbr\"]>=6.0, np.where(((data[\"PlayerHeight17\"]) * 2.0)>=20.570007, data[\"X10\"], data[\"X19\"] ), data[\"JerseyNumber18\"] )))) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"X0\"]>=94.0, data[\"Dis2\"], data[\"S5\"] )<0.650000, -1.0, data[\"NflId12\"] )<2532966.0, np.where(data[\"Orientation5\"]<99.0, np.where(np.where(np.where(data[\"X0\"]>=20.470001, data[\"Dis2\"], data[\"NflId12\"] )>=19.940430, data[\"Dir12\"], data[\"Dis2\"] )>=19.589996, -2.0, data[\"X0\"] ), data[\"Dis2\"] ), -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName3\"]<20.619995, np.where(data[\"A15\"]>=0.710000, data[\"S6\"], ((data[\"A9\"]) - (data[\"S6\"])) ), ((((((np.where(data[\"S0\"]>=3.0, ((data[\"A9\"]) - (data[\"S6\"])), ((np.where(((data[\"X20\"]) * 2.0)<190.0, data[\"X15\"], data[\"PlayerCollegeName3\"] )) - (data[\"X13\"])) )) * 2.0)) * 2.0)) * 2.0) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Location\"]>=20.809998, np.where(data[\"VisitorTeamAbbr\"]>=20.809998, data[\"JerseyNumber1\"], ((data[\"PlayerCollegeName9\"]) \/ 2.0) ), data[\"VisitorTeamAbbr\"] )<20.340004, ((data[\"JerseyNumber1\"]) \/ 2.0), np.where(np.where(np.where(-2.0<2495328.0, np.where(data[\"VisitorTeamAbbr\"]<2495328.0, data[\"A9\"], data[\"PlayerCollegeName9\"] ), data[\"Position5\"] )<3.0, data[\"A21\"], data[\"Location\"] )<3.0, -2.0, data[\"PlayerCollegeName9\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Dis21\"]<0.070000, data[\"Dis21\"], np.where(data[\"PlayerCollegeName0\"]<192.0, data[\"Dir20\"], -2.0 ) )>=20.680008, data[\"Y18\"], data[\"Dis21\"] )>=0.420000, np.where(((np.where(np.where(data[\"Dir20\"]>=191.0, -2.0, data[\"HomeScoreBeforePlay\"] )<0.070000, data[\"X17\"], data[\"Dir20\"] )) * (data[\"Dis21\"]))<20.469994, -2.0, data[\"Dis21\"] ), data[\"A16\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dis21\"]<0.060000, np.where(data[\"A12\"]<0.060000, data[\"Dis21\"], (((data[\"JerseyNumber13\"]) + (2.0))\/2.0) ), data[\"Distance\"] )<20.310005, np.where(data[\"X15\"]>=20.570007, np.where(np.where(((((data[\"Dis21\"]) \/ 2.0)) * (data[\"JerseyNumber4\"]))<10.0, data[\"A12\"], 0.0 )<0.429999, data[\"DB\"], -1.0 ), -1.0 ), data[\"JerseyNumber4\"] )) +\n#             0.100000*np.tanh(np.where(data[\"Y14\"]<15.170002, data[\"A10\"], np.where(np.where(np.where(data[\"X0\"]<20.339996, -1.0, np.where((((data[\"X18\"]) + ((-1.0*((data[\"X13\"])))))\/2.0)<0.710000, -1.0, np.where(data[\"Y14\"]<0.0, data[\"Y14\"], data[\"S17\"] ) ) )<0.420000, data[\"X18\"], -2.0 )<20.770004, data[\"Y14\"], (-1.0*((data[\"X13\"]))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"S12\"]) - (data[\"S9\"]))<0.650000, np.where(data[\"Position5\"]>=11.0, data[\"Dir21\"], data[\"HomeTeamAbbr\"] ), data[\"S9\"] )<20.419998, np.where(((data[\"S12\"]) - (data[\"S9\"]))>=2.0, np.where(data[\"Position5\"]>=11.0, data[\"PlayerCollegeName6\"], data[\"HomeTeamAbbr\"] ), (-1.0*((((data[\"PlayerCollegeName6\"]) - (data[\"X10\"]))))) ), data[\"X18\"] )) +\n#             0.100000*np.tanh(np.where(((data[\"S17\"]) * (np.where(data[\"Y0\"]>=15.170002, data[\"S17\"], data[\"PlayerWeight13\"] )))<20.339996, np.where(data[\"PlayerHeight19\"]>=13.0, data[\"A12\"], np.where(((data[\"A12\"]) \/ 2.0)<0.710000, np.where(data[\"Position2\"]<20.339996, (-1.0*((data[\"Position11\"]))), data[\"PossessionTeam\"] ), np.where(data[\"PossessionTeam\"]<20.719994, data[\"A12\"], (-1.0*((data[\"PlayerHeight19\"]))) ) ) ), data[\"PlayerHeight19\"] )) +\n#             0.100000*np.tanh(np.where(data[\"DefendersInTheBox\"]<6.0, data[\"Humidity\"], np.where(data[\"A17\"]>=0.660000, np.where(data[\"Humidity\"]>=0.660000, np.where(data[\"Dir13\"]>=128.0, ((data[\"A4\"]) - (3.0)), np.where(np.where(data[\"A17\"]>=128.0, 0.0, data[\"PlayerCollegeName10\"] )<128.0, -1.0, data[\"Dir13\"] ) ), data[\"S2\"] ), ((data[\"Dir13\"]) - (data[\"X14\"])) ) )) +\n#             0.100000*np.tanh(((np.where(data[\"A21\"]>=1.0, np.where(data[\"JerseyNumber15\"]>=20.310005, np.where(data[\"PlayerHeight5\"]<11.0, np.where(data[\"Dis4\"]<0.670000, np.where(data[\"PlayerCollegeName10\"]>=20.770004, data[\"Dis4\"], data[\"PlayerHeight5\"] ), (-1.0*((data[\"JerseyNumber15\"]))) ), (-1.0*((data[\"PlayerHeight5\"]))) ), data[\"A21\"] ), (-1.0*((np.where(data[\"JerseyNumber15\"]>=20.310005, (-1.0*((data[\"PlayerHeight5\"]))), data[\"JerseyNumber15\"] )))) )) \/ 2.0)) +\n#             0.100000*np.tanh(np.where(data[\"X4\"]>=20.469994, np.where(np.where(data[\"Dir15\"]<20.240005, data[\"Dir11\"], np.where(data[\"Dis8\"]>=0.690000, data[\"X10\"], data[\"PlayerHeight17\"] ) )<8.0, data[\"JerseyNumber10\"], np.where(np.where(data[\"Orientation8\"]>=13.0, data[\"Orientation8\"], data[\"X0\"] )<20.469994, data[\"NflId14\"], ((data[\"A21\"]) - (3.0)) ) ), ((3.0) - (data[\"PlayerHeight17\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"S2\"]>=0.610000, data[\"DisplayName20\"], data[\"S18\"] )<130.0, data[\"S18\"], ((np.where(np.where(data[\"Y5\"]>=20.339996, data[\"Position16\"], data[\"S2\"] )>=3.0, np.where(np.where(data[\"PlayerHeight15\"]>=0.610000, np.where(data[\"S18\"]>=0.610000, data[\"Dir6\"], data[\"OffensePersonnel\"] ), data[\"S2\"] )>=85.0, -3.0, data[\"Dir6\"] ), data[\"Dir6\"] )) * (data[\"Dir6\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"Position1\"]) * 2.0)>=15.700012, data[\"Dis21\"], data[\"S19\"] )>=0.410000, ((np.where(data[\"Orientation10\"]>=13.0, np.where(np.where(data[\"S19\"]<6.0, data[\"JerseyNumber16\"], data[\"Position1\"] )>=13.0, (-1.0*((((data[\"JerseyNumber14\"]) - (data[\"X5\"]))))), data[\"PlayerCollegeName2\"] ), -1.0 )) * 2.0), ((data[\"JerseyNumber14\"]) - (data[\"X5\"])) )) +\n#             0.099961*np.tanh(np.where(np.where(data[\"Y19\"]<18.549988, data[\"A12\"], np.where(data[\"PlayerWeight2\"]<191.0, data[\"A5\"], data[\"PlayerCollegeName21\"] ) )>=149.0, np.where(data[\"OffenseFormation\"]>=6.0, (-1.0*((data[\"A5\"]))), data[\"A5\"] ), np.where(data[\"A5\"]<0.410000, data[\"OffenseFormation\"], (((-1.0*((np.where(data[\"OffenseFormation\"]>=6.0, (-1.0*((data[\"A3\"]))), data[\"A3\"] ))))) * 2.0) ) )) +\n#             0.100000*np.tanh(((((data[\"DisplayName5\"]) - (np.where(((((data[\"X6\"]) - (data[\"Position14\"]))) - (data[\"Position14\"]))<20.240005, data[\"X10\"], data[\"DisplayName20\"] )))) - (np.where(((np.where(data[\"X16\"]<18.290009, data[\"Orientation10\"], data[\"X16\"] )) - (data[\"Position14\"]))<20.240005, ((data[\"DisplayName4\"]) - (data[\"DisplayName20\"])), data[\"DisplayName20\"] )))) +\n#             0.100000*np.tanh(np.where(data[\"Dis8\"]>=0.070000, np.where(np.where(data[\"PossessionTeam\"]>=15.0, data[\"Orientation9\"], np.where(data[\"JerseyNumber9\"]>=12.0, data[\"VisitorTeamAbbr\"], data[\"Orientation9\"] ) )>=20.470001, np.where(np.where(data[\"Position5\"]>=20.770004, data[\"Dis8\"], data[\"PossessionTeam\"] )>=20.470001, data[\"Dis21\"], 3.0 ), np.where(data[\"PlayerHeight21\"]>=9.0, data[\"PossessionTeam\"], (-1.0*((data[\"Orientation9\"]))) ) ), (-1.0*((data[\"X12\"]))) )) +\n#             0.100000*np.tanh(((((np.where(np.where(data[\"PlayerCollegeName5\"]<20.0, ((data[\"Orientation4\"]) * 2.0), np.where(data[\"Stadium\"]<20.0, 0.0, ((data[\"Position2\"]) * 2.0) ) )<20.310005, np.where(data[\"Stadium\"]<13.0, np.where(data[\"A18\"]<0.650000, data[\"A18\"], data[\"DisplayName17\"] ), ((data[\"Orientation4\"]) * 2.0) ), data[\"PlayerCollegeName5\"] )) \/ 2.0)) - (data[\"Dir0\"]))) +\n#             0.099961*np.tanh(np.where(np.where(data[\"Y5\"]>=20.360352, data[\"Y6\"], data[\"Orientation3\"] )<11.0, data[\"X13\"], np.where(data[\"JerseyNumber16\"]<12.0, data[\"Y1\"], np.where(data[\"Y5\"]>=20.450005, np.where(data[\"PlayerHeight1\"]>=0.610000, np.where(data[\"Y1\"]>=20.450005, np.where(data[\"S5\"]>=0.610000, 0.0, data[\"PlayerWeight18\"] ), (-1.0*((data[\"NflId9\"]))) ), data[\"NflId9\"] ), (-1.0*((data[\"Y5\"]))) ) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"S19\"]<0.670000, (-1.0*((data[\"Position2\"]))), data[\"PlayerCollegeName16\"] )>=20.619995, np.where(data[\"X11\"]>=20.619995, np.where(data[\"WindSpeed\"]<20.699997, np.where(np.where(data[\"DisplayName21\"]>=20.419998, data[\"Dir1\"], data[\"WindSpeed\"] )>=14.0, -3.0, data[\"Orientation16\"] ), np.where(data[\"PlayerCollegeName16\"]>=20.619995, data[\"Dis2\"], -1.0 ) ), -3.0 ), data[\"PlayerCollegeName16\"] )))\n            0)\n\ndef GPII(data):\n    return (4.212334 +\n            0.100000*np.tanh(np.where(data[\"OffensePersonnel\"]<12.0, ((np.where(data[\"YardLine\"]>=16.079987, np.where(np.where(np.where(data[\"OffensePersonnel\"]>=758.0, data[\"X9\"], data[\"Orientation3\"] )>=0.660000, data[\"PossessionTeam\"], (-1.0*((data[\"DefendersInTheBox\"]))) )>=0.060000, data[\"YardLine\"], -3.0 ), data[\"YardLine\"] )) - (((data[\"DefendersInTheBox\"]) * 2.0))), (-1.0*((data[\"Orientation3\"]))) )) +\n            0.100000*np.tanh(np.where(np.where(((data[\"DB\"]) * (data[\"DB\"]))>=20.480003, data[\"X11\"], ((np.where(data[\"X11\"]<20.360008, data[\"A17\"], np.where(((data[\"DB\"]) * (data[\"S14\"]))>=20.480003, data[\"X0\"], np.where(data[\"X8\"]>=20.480003, data[\"DB\"], data[\"PlayerHeight8\"] ) ) )) * 2.0) )>=20.770004, data[\"Dir9\"], (-1.0*((data[\"X8\"]))) )) +\n            0.100000*np.tanh(((((((np.where(data[\"X20\"]>=23.0, (((7.0)) - (np.where(data[\"DefendersInTheBox\"]>=1.0, data[\"DefendersInTheBox\"], data[\"X20\"] ))), ((((((((np.where(data[\"X20\"]>=23.0, data[\"X20\"], ((data[\"DB\"]) - (data[\"DefendersInTheBox\"])) )) * 2.0)) * 2.0)) * 2.0)) - (data[\"DefendersInTheBox\"])) )) * 2.0)) * 2.0)) * 2.0)) +\n            0.100000*np.tanh(((((((((((((np.where((5.0)<0.410000, data[\"OffensePersonnel\"], (((7.04423713684082031)) - (data[\"DefendersInTheBox\"])) )) * 2.0)) * (np.where(((data[\"OffensePersonnel\"]) - (data[\"DB\"]))<29.0, data[\"OffensePersonnel\"], (0.0) )))) - (3.0))) - (-2.0))) * (np.where(data[\"OffensePersonnel\"]<29.0, data[\"PlayerWeight21\"], (5.0) )))) * 2.0)) +\n            0.100000*np.tanh(np.where(np.where(data[\"Y3\"]>=14.810001, np.where(((data[\"DefendersInTheBox\"]) * 2.0)<14.810001, np.where(np.where(data[\"Y3\"]>=14.619999, np.where(data[\"JerseyNumber1\"]<14.619999, data[\"Y10\"], data[\"X7\"] ), data[\"DefendersInTheBox\"] )>=14.619999, data[\"X21\"], np.where(data[\"JerseyNumber1\"]<12.0, 2.0, data[\"X7\"] ) ), -3.0 ), -3.0 )>=20.480003, data[\"DefendersInTheBox\"], ((-3.0) * 2.0) )) +\n            0.100000*np.tanh((((-1.0*((data[\"Distance\"])))) + (((np.where(data[\"DB\"]<15.700001, data[\"Y18\"], -1.0 )) * (((np.where(((data[\"Dir11\"]) - (((((data[\"DefendersInTheBox\"]) * 2.0)) + (data[\"DefendersInTheBox\"]))))<15.700001, data[\"Distance\"], ((-1.0) + (data[\"Distance\"])) )) - (data[\"DefendersInTheBox\"]))))))) +\n            0.100000*np.tanh(np.where(data[\"Orientation18\"]>=2.0, np.where((((data[\"Orientation18\"]) + (data[\"S6\"]))\/2.0)>=20.0, np.where((((-3.0) + (data[\"DefendersInTheBox\"]))\/2.0)>=2.0, np.where((((data[\"Humidity\"]) + (data[\"VisitorTeamAbbr\"]))\/2.0)>=2.0, np.where(data[\"PlayerWeight5\"]<190.0, data[\"DefendersInTheBox\"], ((data[\"S6\"]) - (data[\"DefendersInTheBox\"])) ), 3.0 ), data[\"Orientation18\"] ), -3.0 ), data[\"Humidity\"] )) +\n            0.100000*np.tanh(((np.where(data[\"Distance\"]<20.440002, ((np.where(-3.0<20.699997, data[\"Distance\"], data[\"Distance\"] )) - ((((9.0)) * (np.where(data[\"Distance\"]>=20.339996, data[\"S0\"], ((data[\"Dis0\"]) * 2.0) ))))), data[\"Distance\"] )) - (((data[\"DefendersInTheBox\"]) * (np.where(data[\"S0\"]>=20.339996, 3.0, ((data[\"Dis4\"]) * 2.0) )))))) +\n            0.100000*np.tanh(np.where(np.where((((((((-1.0*((data[\"A3\"])))) + (data[\"X16\"]))\/2.0)) + ((-1.0*((data[\"A3\"])))))\/2.0)>=20.680008, -2.0, data[\"X9\"] )>=33.0, data[\"Position15\"], (-1.0*(((5.84260702133178711)))) )) +\n            0.100000*np.tanh(((data[\"DB\"]) - (np.where(((data[\"DB\"]) - (data[\"DefendersInTheBox\"]))<0.0, np.where(data[\"JerseyNumber20\"]>=20.340004, np.where(np.where(data[\"X21\"]<20.450005, -3.0, np.where(data[\"DisplayName7\"]<20.450005, data[\"DisplayName13\"], data[\"OffensePersonnel\"] ) )>=20.340004, data[\"OffenseFormation\"], data[\"DisplayName7\"] ), data[\"DisplayName7\"] ), (-1.0*((data[\"DefendersInTheBox\"]))) )))) +\n            0.100000*np.tanh(np.where(np.where(np.where(data[\"X12\"]>=16.610352, np.where(data[\"GameHour\"]>=0.610000, data[\"Y9\"], data[\"Distance\"] ), -2.0 )>=16.170013, data[\"Dir8\"], data[\"GameHour\"] )>=20.450005, np.where(np.where(data[\"X9\"]>=85.0, -3.0, data[\"X20\"] )<1.0, ((np.where(data[\"X12\"]>=85.0, -3.0, data[\"GameHour\"] )) - (data[\"DefendersInTheBox\"])), data[\"Distance\"] ), -2.0 )) +\n            0.100000*np.tanh(np.where(np.where(((data[\"Orientation12\"]) \/ 2.0)>=9.0, np.where(data[\"Distance\"]>=9.0, data[\"JerseyNumber4\"], -2.0 ), (-1.0*((data[\"Distance\"]))) )>=9.0, np.where(((data[\"JerseyNumber11\"]) \/ 2.0)>=13.770000, data[\"JerseyNumber11\"], np.where(((data[\"X6\"]) \/ 2.0)<20.440002, data[\"X18\"], (-1.0*((((data[\"JerseyNumber11\"]) \/ 2.0)))) ) ), (-1.0*((data[\"JerseyNumber4\"]))) )) +\n            0.100000*np.tanh(np.where(np.where(data[\"PossessionTeam\"]>=0.630000, np.where(np.where(data[\"PlayerHeight11\"]>=10.0, data[\"PlayerHeight4\"], data[\"Dis19\"] )<0.630000, ((np.where(data[\"Dir11\"]<14.0, data[\"X7\"], (-1.0*((data[\"PlayerHeight4\"]))) )) - ((-1.0*((data[\"S2\"]))))), data[\"X7\"] ), -2.0 )<20.719994, (-1.0*((data[\"PlayerHeight11\"]))), data[\"PossessionTeam\"] )) +\n            0.100000*np.tanh(np.where(np.where(np.where(1.0<0.070000, data[\"OffenseFormation\"], ((data[\"Orientation19\"]) \/ 2.0) )<14.810001, -2.0, np.where(data[\"X15\"]<20.469994, data[\"X4\"], data[\"Orientation19\"] ) )>=19.940430, np.where(np.where(np.where(data[\"X4\"]<91.0, data[\"Orientation19\"], -3.0 )>=0.650000, data[\"X4\"], data[\"X17\"] )<91.0, data[\"X18\"], -3.0 ), (-1.0*((data[\"DisplayName15\"]))) )) +\n            0.100000*np.tanh(np.where(data[\"YardLine\"]>=13.0, np.where(data[\"DB\"] < -9998, data[\"X5\"], np.where(data[\"DefendersInTheBox\"]>=6.0, np.where(data[\"JerseyNumber4\"]>=20.360008, ((data[\"X11\"]) - (data[\"X5\"])), (-1.0*((np.where(data[\"Distance\"]>=9.0, data[\"Distance\"], -3.0 )))) ), data[\"X11\"] ) ), np.where(data[\"Distance\"]>=9.0, data[\"DB\"], ((data[\"Distance\"]) * (-3.0)) ) )) +\n            0.100000*np.tanh(np.where(np.where(np.where(((data[\"X11\"]) \/ 2.0)<18.0, data[\"X11\"], np.where(data[\"Orientation11\"]<11.0, data[\"JerseyNumber3\"], np.where(data[\"Orientation11\"]>=2543480.0, data[\"X11\"], np.where(((data[\"JerseyNumber3\"]) \/ 2.0)<18.0, data[\"Orientation2\"], (-1.0*((data[\"X17\"]))) ) ) ) )>=20.339996, data[\"S14\"], data[\"Y6\"] )<11.0, data[\"S10\"], ((data[\"Y6\"]) - (data[\"PlayerCollegeName14\"])) )) +\n            0.100000*np.tanh(np.where(np.where(np.where(data[\"Y19\"]>=20.570007, np.where(data[\"Position7\"]>=2.0, np.where(np.where(data[\"A6\"]<20.719994, ((data[\"X9\"]) - (data[\"DisplayName0\"])), data[\"Dis13\"] )>=20.809998, -3.0, data[\"HomeTeamAbbr\"] ), data[\"YardLine\"] ), data[\"Position7\"] )>=14.0, data[\"A6\"], data[\"PlayerWeight1\"] )>=20.699997, -3.0, np.where(data[\"YardLine\"]<7.0, -3.0, data[\"Position7\"] ) )) +\n            0.100000*np.tanh(((np.where(np.where(np.where(np.where(data[\"Orientation12\"]>=0.0, data[\"X13\"], data[\"PlayerWeight10\"] )<105.0, data[\"Dir12\"], -3.0 )>=122.0, data[\"X14\"], (-1.0*((2.0))) )>=15.839996, data[\"Orientation12\"], (-1.0*((np.where(data[\"Orientation12\"]<190.0, ((data[\"Orientation10\"]) - (data[\"PlayerCollegeName8\"])), data[\"VisitorScoreBeforePlay\"] )))) )) - (data[\"Dir17\"]))) +\n            0.100000*np.tanh(np.where(np.where(((np.where(data[\"A4\"]>=2.0, data[\"A18\"], data[\"A5\"] )) * (data[\"YardLine\"]))>=20.469994, data[\"A4\"], data[\"Dis20\"] )<0.650000, -2.0, np.where(data[\"Dir1\"]<6.0, data[\"Dir8\"], np.where(((((data[\"YardLine\"]) - (data[\"Dir1\"]))) * (data[\"PlayerHeight9\"]))>=20.480003, (-1.0*((data[\"DisplayName8\"]))), data[\"Dir21\"] ) ) )) +\n            0.100000*np.tanh(np.where(np.where(data[\"YardLine\"]>=20.709999, data[\"YardLine\"], -2.0 )>=6.0, ((np.where(data[\"Position10\"]<20.0, data[\"S21\"], data[\"A9\"] )) - (np.where(data[\"Position10\"]>=20.240005, data[\"S21\"], data[\"S19\"] ))), np.where(data[\"Distance\"]>=9.0, np.where(data[\"YardLine\"]>=20.709999, data[\"YardLine\"], ((data[\"Temperature\"]) - (data[\"YardLine\"])) ), -2.0 ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Orientation7\"]>=20.339996, np.where(data[\"DisplayName15\"]>=20.469994, np.where(((data[\"S4\"]) \/ 2.0)<0.660000, data[\"S4\"], data[\"Position6\"] ), data[\"A3\"] ), data[\"Y21\"] )>=20.370117, data[\"Distance\"], np.where(np.where(np.where(data[\"DisplayName15\"]>=192.0, data[\"Orientation14\"], data[\"Orientation4\"] )<91.0, data[\"PlayerCollegeName9\"], data[\"Position6\"] )<191.0, (-1.0*((data[\"S4\"]))), data[\"S4\"] ) )) +\n#             0.100000*np.tanh(np.where(data[\"Orientation13\"]<0.420000, data[\"DefendersInTheBox\"], np.where(np.where(((data[\"Distance\"]) * (data[\"YardLine\"]))>=20.699997, data[\"Orientation13\"], data[\"Distance\"] )>=6.0, np.where(data[\"A11\"]>=0.660000, np.where(np.where(data[\"YardLine\"] < -9998, data[\"A1\"], data[\"JerseyNumber2\"] )>=20.809998, data[\"HomeScoreBeforePlay\"], (-1.0*((data[\"Distance\"]))) ), (-1.0*((data[\"HomeScoreBeforePlay\"]))) ), (-1.0*((data[\"PlayerWeight7\"]))) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight0\"]<0.420000, (-1.0*((data[\"YardLine\"]))), np.where(data[\"A17\"]>=0.700000, ((np.where(np.where(data[\"VisitorScoreBeforePlay\"]<0.420000, -2.0, data[\"S11\"] )>=0.700000, data[\"YardLine\"], data[\"DB\"] )) - (data[\"PlayerHeight19\"])), np.where(((data[\"Dis1\"]) \/ 2.0)<0.070000, np.where(data[\"VisitorScoreBeforePlay\"]<0.420000, -2.0, data[\"PlayerHeight19\"] ), (-1.0*((data[\"DisplayName19\"]))) ) ) )) +\n#             0.100000*np.tanh(((-3.0) + (np.where(np.tanh((np.where(np.where(data[\"PlayerHeight11\"]<0.680000, -3.0, data[\"A21\"] )<0.680000, ((data[\"PlayerHeight8\"]) * ((0.08087398856878281))), data[\"A21\"] )))<0.680000, data[\"OffenseFormation\"], data[\"A21\"] )))) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"JerseyNumber16\"]<20.339996, np.where(data[\"OffenseFormation\"]<20.339996, np.where(data[\"Dir13\"]<20.339996, data[\"S4\"], data[\"Orientation15\"] ), 1.0 ), data[\"PlayerHeight13\"] )>=13.0, ((data[\"JerseyNumber16\"]) * 2.0), data[\"DisplayName1\"] )<190.0, data[\"S8\"], ((((((((((data[\"A14\"]) - (data[\"S4\"]))) * 2.0)) * 2.0)) * 2.0)) * 2.0) )) +\n#             0.100000*np.tanh(((((np.where(np.where(data[\"Dis21\"]<0.710000, data[\"OffenseFormation\"], 0.0 )<0.650000, data[\"JerseyNumber8\"], np.where(data[\"S12\"]<0.410000, ((data[\"A5\"]) - (data[\"S12\"])), ((np.where(data[\"A5\"]<0.410000, data[\"PlayerCollegeName16\"], ((data[\"A5\"]) - (data[\"S12\"])) )) + (data[\"A4\"])) ) )) - (data[\"S16\"]))) + (data[\"A4\"]))) +\n#             0.100000*np.tanh(np.where(np.where(data[\"A16\"]>=0.650000, data[\"S15\"], np.where(((data[\"FieldPosition\"]) - (data[\"PlayerHeight20\"]))<19.849609, data[\"A16\"], data[\"A1\"] ) )>=0.660000, np.where(data[\"A13\"]>=0.660000, ((((data[\"FieldPosition\"]) - (data[\"PlayerHeight20\"]))) - (data[\"PlayerHeight20\"])), (-1.0*((data[\"X0\"]))) ), (-1.0*((data[\"X0\"]))) )) +\n#             0.100000*np.tanh(np.where(data[\"X15\"]>=102.0, (-1.0*((data[\"DisplayName8\"]))), np.where(data[\"X1\"]<16.009766, (-1.0*((data[\"X15\"]))), (((np.where(data[\"Location\"]<20.699997, data[\"X15\"], (-1.0*((np.where(data[\"Orientation10\"]<20.709999, data[\"DisplayName8\"], data[\"X15\"] )))) )) + (((np.where(((data[\"A9\"]) \/ 2.0)>=0.470000, data[\"PlayerCollegeName5\"], data[\"DisplayName8\"] )) \/ 2.0)))\/2.0) ) )) +\n#             0.100000*np.tanh(np.where(data[\"Orientation5\"]<102.0, data[\"S7\"], np.where(np.where(data[\"Dir15\"]<19.559570, data[\"Orientation5\"], ((data[\"Orientation5\"]) - (data[\"DisplayName17\"])) )<95.0, np.where(data[\"JerseyNumber6\"]<20.709999, data[\"X2\"], np.where(data[\"Orientation5\"]<19.559570, data[\"Dis7\"], ((data[\"A12\"]) - (data[\"S16\"])) ) ), -2.0 ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerHeight21\"]>=6.0, np.where(data[\"S1\"]<1.0, data[\"Orientation8\"], data[\"Y21\"] ), data[\"NflId3\"] )>=192.0, 3.0, ((np.where(data[\"Position16\"]<1.0, np.where(data[\"X12\"]<95.0, data[\"PlayerWeight9\"], -1.0 ), ((np.where(data[\"Position16\"]<1.0, data[\"NflId3\"], data[\"A10\"] )) - (data[\"S9\"])) )) * (data[\"S9\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(((data[\"A6\"]) * (data[\"X10\"]))>=20.290009, ((data[\"A6\"]) * (data[\"JerseyNumber3\"])), data[\"X9\"] )>=19.540009, np.where(np.where(np.where(data[\"Dis7\"]>=0.460000, data[\"A6\"], data[\"Dir6\"] )<20.339996, data[\"JerseyNumber3\"], -2.0 )<20.450005, data[\"PlayerCollegeName0\"], data[\"Dis18\"] ), -2.0 )>=10.0, data[\"Week\"], (-1.0*((data[\"JerseyNumber3\"]))) )) +\n#             0.100000*np.tanh(np.where(((data[\"PlayerWeight20\"]) - (((data[\"PlayerCollegeName10\"]) - (data[\"JerseyNumber2\"]))))<6.0, data[\"Y8\"], np.where(data[\"DefendersInTheBox\"]<6.0, data[\"DisplayName1\"], np.where(((data[\"PlayerCollegeName10\"]) - (data[\"S9\"]))<19.559570, data[\"HomeTeamAbbr\"], np.where(data[\"DisplayName21\"]<20.680008, data[\"HomeTeamAbbr\"], (-1.0*((((data[\"DisplayName1\"]) - (((data[\"PlayerCollegeName10\"]) - (data[\"DisplayName1\"]))))))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"YardLine\"]>=6.0, np.where(data[\"DisplayName12\"]>=12.0, np.where(data[\"YardLine\"]>=12.0, np.where(data[\"PlayerHeight19\"]>=20.339996, data[\"DisplayName11\"], np.where(data[\"A9\"]<2.0, ((data[\"PlayerHeight19\"]) + ((-1.0*((data[\"Position5\"]))))), np.where(data[\"YardLine\"]>=14.0, data[\"PlayerHeight2\"], (-1.0*((data[\"Position5\"]))) ) ) ), data[\"DisplayName11\"] ), data[\"WindSpeed\"] ), (-1.0*((data[\"WindSpeed\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where((((((data[\"S7\"]) - (np.where(-1.0<0.0, data[\"PlayerHeight0\"], data[\"PlayerCollegeName0\"] )))) + (np.where(data[\"PlayerHeight0\"]<6.0, data[\"Dir1\"], data[\"PlayerCollegeName0\"] )))\/2.0)<20.240005, data[\"PlayerHeight0\"], data[\"Dis11\"] )>=0.420000, data[\"PlayerHeight14\"], ((data[\"A10\"]) + (-3.0)) )>=0.420000, data[\"PlayerHeight0\"], -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"DisplayName0\"]>=99.0, ((np.where(np.where(data[\"Y1\"]>=15.880005, data[\"Dis13\"], data[\"PlayerHeight13\"] )<0.420000, np.where(data[\"YardLine\"]>=6.0, data[\"A18\"], -1.0 ), (-1.0*((data[\"PlayerHeight13\"]))) )) * 2.0), ((np.where(data[\"Y1\"]<20.419998, data[\"Y1\"], np.where(data[\"PlayerHeight13\"]>=6.0, data[\"DisplayName0\"], -1.0 ) )) - (data[\"X1\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"DefendersInTheBox\"]<6.0, ((data[\"Position8\"]) - (data[\"DL\"])), np.where(data[\"PlayerHeight21\"]<6.0, ((data[\"Position8\"]) - (data[\"DL\"])), np.where(data[\"Stadium\"]<6.0, np.where(data[\"Y16\"]<20.340004, -2.0, data[\"Stadium\"] ), ((((data[\"Y16\"]) - (np.where(data[\"Y16\"]>=16.009766, data[\"DisplayName19\"], ((data[\"DL\"]) \/ 2.0) )))) \/ 2.0) ) ) )) +\n#             0.099961*np.tanh(np.where(data[\"A17\"]>=0.680000, np.where(data[\"Orientation17\"]<20.360008, (-1.0*((data[\"Dis1\"]))), np.where(np.where(data[\"A8\"]<0.470000, data[\"PlayerHeight8\"], data[\"A8\"] )<1.0, data[\"Dis1\"], ((data[\"Distance\"]) - (data[\"DL\"])) ) ), (-1.0*((((data[\"Distance\"]) - (data[\"PlayerHeight8\"]))))) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Dir5\"]<9.0, data[\"Position18\"], np.where(data[\"Y9\"]<9.0, data[\"Y0\"], data[\"PlayerCollegeName3\"] ) )>=128.0, np.where(np.where(data[\"Position6\"]>=20.360352, data[\"Position6\"], data[\"Orientation3\"] )>=191.0, data[\"S11\"], (-1.0*((np.where(data[\"Y8\"]>=23.0, ((data[\"A1\"]) - (data[\"S11\"])), data[\"Dir5\"] )))) ), ((data[\"A1\"]) - (data[\"S11\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(data[\"S12\"]<0.660000, data[\"Position7\"], data[\"PlayerCollegeName7\"] )>=20.450005, data[\"Dir8\"], data[\"HomeScoreBeforePlay\"] )>=20.709999, data[\"HomeScoreBeforePlay\"], np.where(np.where(data[\"HomeScoreBeforePlay\"]<0.660000, data[\"HomeScoreBeforePlay\"], data[\"Position7\"] )>=20.450005, data[\"Dir8\"], data[\"PlayerCollegeName10\"] ) )<11.0, data[\"HomeScoreBeforePlay\"], ((-1.0) - (data[\"Dir16\"])) )) +\n#             0.100000*np.tanh(((data[\"A9\"]) + (((data[\"A21\"]) * (np.where(((data[\"A21\"]) * (np.where(data[\"A21\"]>=190.0, data[\"PlayerHeight9\"], (-1.0*(((((1.0) + (((data[\"A21\"]) * (np.where(data[\"Orientation8\"]>=190.0, (-1.0*((data[\"PlayerHeight9\"]))), (-1.0*((data[\"A21\"]))) )))))\/2.0)))) )))>=20.310005, data[\"A21\"], -2.0 )))))) +\n#             0.100000*np.tanh(np.where(data[\"VisitorScoreBeforePlay\"]>=0.710000, np.where(data[\"Orientation11\"]<192.0, np.where(data[\"VisitorScoreBeforePlay\"]<20.680008, data[\"A16\"], np.where(data[\"X17\"]<20.680008, data[\"VisitorScoreBeforePlay\"], -1.0 ) ), np.where(np.where(data[\"VisitorScoreBeforePlay\"]<6.0, data[\"Orientation11\"], data[\"S4\"] )<15.0, np.where(data[\"VisitorScoreBeforePlay\"]<20.680008, data[\"GameHour\"], -1.0 ), (-1.0*((3.0))) ) ), (-1.0*((data[\"S4\"]))) )) +\n#             0.100000*np.tanh((-1.0*((np.where(data[\"PlayerCollegeName0\"]<20.620003, data[\"Position9\"], np.where(np.where(np.where(data[\"DisplayName20\"]>=20.339996, np.where(np.where(np.where(data[\"DisplayName20\"]>=0.410000, data[\"X17\"], data[\"Dis8\"] )>=20.480003, ((data[\"PlayerHeight12\"]) * 2.0), -1.0 )<16.010010, data[\"Dis5\"], data[\"X12\"] ), data[\"S1\"] )<0.410000, data[\"Orientation14\"], data[\"Orientation9\"] )>=192.0, data[\"PlayerWeight6\"], -3.0 ) ))))) +\n#             0.100000*np.tanh(np.where(((np.where(np.where(np.where(data[\"JerseyNumber3\"]>=85.0, data[\"PlayerCollegeName20\"], ((data[\"Dis9\"]) \/ 2.0) )<20.310005, data[\"DisplayName5\"], data[\"Dis4\"] )<120.0, data[\"Dis0\"], np.where(data[\"Orientation13\"]<120.0, (-1.0*((data[\"Dis4\"]))), data[\"Dis4\"] ) )) + (((data[\"Dis9\"]) \/ 2.0)))<0.420000, data[\"S8\"], (-1.0*((data[\"Y19\"]))) )) +\n#             0.100000*np.tanh(np.where(((np.where(((np.where(np.where(np.where(data[\"Dis3\"]>=0.410000, data[\"PlayerCollegeName21\"], data[\"Dis2\"] )<20.709999, -2.0, data[\"PlayerCollegeName18\"] )<20.709999, data[\"A1\"], data[\"Dir7\"] )) + (-2.0))>=0.410000, data[\"Dir7\"], data[\"Dis3\"] )) + (-3.0))>=0.410000, data[\"PlayerCollegeName21\"], (-1.0*((data[\"X20\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"Distance\"]) + (-2.0))<0.060000, data[\"Position3\"], data[\"Y17\"] )>=20.809998, np.where(np.where(data[\"X15\"]<0.060000, -3.0, data[\"JerseyNumber18\"] )>=20.809998, np.where(data[\"DisplayName16\"]<190.0, -3.0, np.where(data[\"VisitorTeamAbbr\"]>=6.0, data[\"Y17\"], (-1.0*((data[\"PlayerCollegeName1\"]))) ) ), (-1.0*((data[\"DefendersInTheBox\"]))) ), (-1.0*((data[\"VisitorTeamAbbr\"]))) )) +\n#             0.100000*np.tanh(((np.where(data[\"Dis8\"]>=0.070000, np.where(data[\"Position21\"]>=0.650000, np.where(data[\"Position11\"]<0.070000, data[\"Position9\"], np.where(np.where(data[\"Position21\"]>=20.450005, data[\"Dir21\"], data[\"DisplayName10\"] )<173.0, np.where(data[\"Position21\"]<20.719994, data[\"S0\"], (-1.0*((data[\"Position21\"]))) ), np.where(data[\"Y19\"]>=20.539993, data[\"GameHour\"], -1.0 ) ) ), -3.0 ), -3.0 )) * 2.0)) +\n#             0.100000*np.tanh(((data[\"X21\"]) - (np.where(np.where(data[\"PlayerCollegeName3\"]>=20.709999, np.where(np.where(data[\"Dis6\"]<0.060000, data[\"PlayerHeight9\"], data[\"PlayerCollegeName11\"] )>=20.809998, ((data[\"JerseyNumber19\"]) - (data[\"PlayerHeight17\"])), data[\"Dis0\"] ), data[\"Dis0\"] )>=20.709999, data[\"PlayerCollegeName11\"], np.where(((data[\"Dis0\"]) * (data[\"Dis6\"]))>=0.070000, data[\"Dir11\"], ((data[\"PlayerCollegeName11\"]) - (data[\"PlayerCollegeName11\"])) ) )))) +\n#             0.100000*np.tanh(np.where((-1.0*((data[\"Humidity\"])))>=14.0, data[\"DisplayName6\"], ((np.where(data[\"Position14\"]<20.299988, data[\"X13\"], (-1.0*((data[\"A6\"]))) )) * (np.where(np.where(data[\"Humidity\"]<20.419998, data[\"A6\"], np.where(data[\"JerseyNumber6\"]>=16.010010, np.where(data[\"Dis11\"]<0.070000, -3.0, data[\"X13\"] ), data[\"JerseyNumber6\"] ) )>=11.0, data[\"Position14\"], (-1.0*((data[\"X13\"]))) ))) )) +\n#             0.100000*np.tanh(np.where(data[\"Dir0\"]<15.139999, -2.0, np.where(data[\"Dis2\"]>=0.410000, -2.0, np.where(data[\"Orientation10\"]>=20.419998, np.where(data[\"Dir3\"]>=192.0, np.where(data[\"X11\"]<20.619995, -1.0, np.where(data[\"Orientation10\"]>=192.0, (-1.0*((data[\"S15\"]))), data[\"S15\"] ) ), data[\"S15\"] ), np.where(data[\"Dis2\"]>=20.0, data[\"Orientation10\"], (-1.0*((data[\"NflId17\"]))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight4\"]>=0.410000, np.where(((data[\"PlayerHeight4\"]) - ((-1.0*((np.where(data[\"X5\"]>=19.589996, data[\"PlayerWeight12\"], data[\"S14\"] ))))))>=192.0, np.where(data[\"Position10\"]<20.570007, np.where(data[\"Y4\"]>=20.539993, data[\"Dis17\"], data[\"Position10\"] ), ((data[\"A14\"]) - (data[\"S14\"])) ), data[\"PlayerWeight19\"] ), data[\"Dis17\"] )) +\n#             0.100000*np.tanh(np.where(data[\"JerseyNumber14\"]>=11.0, np.where(data[\"Position13\"]<0.690000, np.where(data[\"Y1\"]>=13.770000, data[\"X19\"], data[\"WindSpeed\"] ), ((data[\"Y1\"]) - (np.where(data[\"JerseyNumber2\"]>=15.579987, np.where(np.where(np.where(data[\"Dis17\"]<0.429999, -1.0, data[\"Y20\"] )>=0.660000, data[\"WindSpeed\"], data[\"JerseyNumber21\"] )>=20.539993, data[\"Y20\"], data[\"PlayerCollegeName10\"] ), data[\"NflIdRusher\"] ))) ), data[\"Dis17\"] )) +\n#             0.100000*np.tanh(np.where(data[\"OffensePersonnel\"]>=20.339996, np.where(data[\"PlayerHeight16\"]>=6.0, data[\"Stadium\"], np.tanh((-2.0)) ), (-1.0*((np.where(data[\"A2\"]<2.0, ((data[\"PlayerHeight16\"]) * (np.where(((data[\"A2\"]) * (np.where(data[\"DefendersInTheBox\"]>=6.0, data[\"JerseyNumber11\"], (-1.0*((data[\"DisplayName13\"]))) )))>=6.0, data[\"PlayerHeight2\"], np.tanh((-2.0)) ))), -2.0 )))) )) +\n#             0.100000*np.tanh(np.where(data[\"FieldPosition\"]>=20.709999, np.where(data[\"VisitorTeamAbbr\"]<20.709999, data[\"Position20\"], ((data[\"X13\"]) - (((data[\"Y2\"]) * 2.0))) ), np.where(data[\"Position20\"]<20.299988, np.where(data[\"VisitorTeamAbbr\"]<20.619995, data[\"FieldPosition\"], (-1.0*((data[\"VisitorTeamAbbr\"]))) ), np.where(((data[\"FieldPosition\"]) * 2.0)<16.490234, ((data[\"Y2\"]) * 2.0), (-1.0*((data[\"X8\"]))) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight1\"]<0.670000, data[\"PlayerCollegeName9\"], np.where(np.where(data[\"PlayerHeight0\"]>=14.0, data[\"A6\"], data[\"Y12\"] )<9.0, data[\"PlayerCollegeName9\"], np.where(np.where(data[\"Orientation3\"]>=191.0, data[\"A18\"], data[\"JerseyNumber21\"] )<0.690000, data[\"PlayerCollegeName17\"], np.where(data[\"Dir12\"]<6.0, data[\"Dir12\"], ((data[\"A6\"]) - (data[\"Orientation8\"])) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"Dis15\"]>=0.070000, np.where(data[\"X19\"]<9.0, data[\"Dir10\"], np.where(np.where(np.where(-2.0>=20.709999, data[\"PlayerWeight14\"], np.tanh((data[\"Dis16\"])) )<0.070000, data[\"Orientation15\"], np.where(data[\"X19\"]<20.339996, data[\"Orientation15\"], data[\"Dis15\"] ) )<20.770004, data[\"PlayerHeight17\"], -2.0 ) ), np.where(data[\"X19\"]<20.339996, data[\"PlayerCollegeName14\"], (-1.0*((data[\"Orientation15\"]))) ) )) +\n#             0.100000*np.tanh(((data[\"PlayerCollegeName18\"]) * (np.where(np.where(data[\"Y11\"]<20.440002, np.where(np.where(data[\"X13\"]<20.340004, -1.0, data[\"S13\"] )>=0.460000, data[\"JerseyNumber3\"], data[\"X16\"] ), data[\"X16\"] )<20.419998, data[\"S1\"], np.where(np.where(data[\"PlayerCollegeName16\"]<20.450005, data[\"PlayerCollegeName15\"], data[\"X19\"] )<20.0, data[\"JerseyNumber3\"], ((data[\"A20\"]) - (data[\"S1\"])) ) )))) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Position2\"]>=6.0, np.where(np.where(data[\"Position20\"]>=2532966.0, data[\"Position20\"], data[\"X13\"] )<20.620003, data[\"Position2\"], data[\"X19\"] ), np.where(data[\"Y3\"]>=15.570007, ((data[\"Position20\"]) - (data[\"JerseyNumber14\"])), data[\"Orientation6\"] ) )>=13.0, data[\"Position2\"], data[\"DisplayName6\"] )>=20.079987, data[\"Position20\"], (-1.0*((data[\"Orientation6\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(((np.where(data[\"PlayerCollegeName19\"]<0.660000, data[\"Orientation5\"], data[\"PlayerCollegeName19\"] )) - (data[\"X7\"]))>=20.680008, np.where(np.where(data[\"Orientation8\"]>=20.770004, np.where(data[\"Orientation5\"]>=20.770004, data[\"JerseyNumber1\"], data[\"Orientation5\"] ), (-1.0*((data[\"PlayerHeight3\"]))) )>=20.360008, data[\"Orientation8\"], data[\"Dis16\"] ), ((data[\"X7\"]) \/ 2.0) )<20.340004, data[\"PlayerHeight3\"], (-1.0*((data[\"PlayerHeight3\"]))) )) +\n#             0.100000*np.tanh(np.where(-1.0>=20.0, data[\"S1\"], np.where(((np.where(np.where(data[\"Position18\"]>=20.0, data[\"DisplayName0\"], ((np.where(np.where(data[\"Dir13\"]<131.0, data[\"DisplayName0\"], data[\"Orientation8\"] )<192.0, -1.0, data[\"Dir13\"] )) * (data[\"Position18\"])) )<192.0, -1.0, data[\"A17\"] )) * (data[\"Dir13\"]))<15.839996, -2.0, data[\"DisplayName0\"] ) )) +\n#             0.100000*np.tanh(np.where(data[\"S1\"]>=0.400000, ((np.where(np.where(((data[\"PossessionTeam\"]) \/ 2.0)<0.070000, data[\"Position9\"], data[\"Dir1\"] )>=191.0, ((data[\"Position9\"]) \/ 2.0), ((data[\"Orientation0\"]) - (np.where(data[\"S2\"]<0.070000, 0.0, data[\"Dir1\"] ))) )) - (((((data[\"PossessionTeam\"]) \/ 2.0)) \/ 2.0))), ((data[\"Dir1\"]) - (((data[\"JerseyNumber17\"]) * 2.0))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(((data[\"S17\"]) * 2.0)>=16.010010, np.where(data[\"Dir6\"]>=0.060000, data[\"Dir6\"], -3.0 ), ((data[\"Position21\"]) * 2.0) )>=16.010010, np.where(data[\"PlayerCollegeName10\"]>=16.010010, np.where(data[\"Humidity\"]>=0.060000, data[\"Dir18\"], 3.0 ), data[\"Dir6\"] ), data[\"PlayerCollegeName7\"] )<160.0, ((data[\"S17\"]) * 2.0), -3.0 )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Orientation19\"]>=192.0, np.where(data[\"X9\"]>=105.0, (-1.0*((data[\"PlayerHeight19\"]))), np.where(data[\"Dir1\"]>=105.0, data[\"WindSpeed\"], data[\"JerseyNumber2\"] ) ), np.where(data[\"Y6\"]<20.339996, data[\"Dir2\"], (10.90363693237304688) ) )>=20.339996, data[\"Orientation19\"], 0.0 )>=20.339996, data[\"Y6\"], (-1.0*((data[\"Y6\"]))) )) +\n#             0.099961*np.tanh(np.where(np.where(np.where(np.where(np.where(data[\"S1\"] < -9998, data[\"X12\"], data[\"DisplayName9\"] )<20.440002, data[\"X12\"], np.where(data[\"Position19\"]<20.440002, data[\"X12\"], np.where(data[\"A21\"]<0.610000, data[\"PlayerCollegeName17\"], data[\"A21\"] ) ) )>=16.490002, 2.0, data[\"Y2\"] )>=9.0, data[\"A2\"], data[\"PlayerCollegeName18\"] )>=20.310005, data[\"S1\"], (-1.0*((data[\"S1\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Dir6\"]>=191.0, np.where(np.tanh((data[\"PlayerCollegeName8\"]))>=1.0, -3.0, data[\"Orientation18\"] ), data[\"PlayerCollegeName8\"] )>=15.839996, data[\"Orientation18\"], data[\"PlayerCollegeName8\"] )>=191.0, ((data[\"Position12\"]) * (np.where(np.where(data[\"Position4\"]>=15.839996, data[\"Orientation18\"], data[\"PlayerCollegeName8\"] )>=191.0, data[\"PlayerCollegeName8\"], -3.0 ))), -3.0 )) +\n#             0.100000*np.tanh(np.where(data[\"Position2\"]>=0.660000, np.where(((data[\"Position1\"]) \/ 2.0)>=0.660000, np.where(data[\"Dis17\"]>=0.440000, data[\"PlayerCollegeName10\"], np.where(data[\"S4\"]<20.450005, np.where(np.where(data[\"Turf\"]>=0.640000, np.where(data[\"PlayerCollegeName10\"]>=20.480003, data[\"S16\"], data[\"HomeTeamAbbr\"] ), data[\"PlayerCollegeName10\"] )>=15.139999, data[\"X21\"], -2.0 ), data[\"HomeTeamAbbr\"] ) ), data[\"Turf\"] ), data[\"S16\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"X9\"]<99.0, np.where(((np.where(((np.where(data[\"A21\"]<0.410000, (-1.0*((data[\"Dis2\"]))), data[\"PlayerHeight3\"] )) * 2.0)<0.410000, -3.0, data[\"GameHour\"] )) * (data[\"Dis2\"]))<0.410000, ((data[\"X5\"]) * (data[\"Dis2\"])), data[\"Humidity\"] ), data[\"PlayerHeight21\"] )>=20.0, data[\"X19\"], (-1.0*((((data[\"PlayerHeight3\"]) * 2.0)))) )) +\n#             0.099961*np.tanh(np.where(np.where((-1.0*((np.where(data[\"Orientation17\"]<20.130005, -2.0, data[\"Orientation6\"] ))))>=0.070000, np.where(-2.0<0.060000, data[\"PlayerCollegeName9\"], data[\"DL\"] ), np.where(np.where(data[\"Dir7\"]<20.130005, -2.0, data[\"Orientation6\"] )>=122.0, data[\"YardLine\"], data[\"Dir12\"] ) )<20.240005, data[\"Position2\"], ((data[\"JerseyNumber1\"]) - (data[\"Dir20\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"JerseyNumber9\"]>=20.450005, np.where(data[\"DisplayName3\"]>=20.699997, np.where(data[\"Y9\"]>=11.0, np.where(data[\"Dir0\"]>=14.189999, ((data[\"YardLine\"]) + (-2.0)), (-1.0*((data[\"Y9\"]))) ), (-1.0*((data[\"X17\"]))) ), (-1.0*((data[\"Dir0\"]))) ), ((data[\"X17\"]) - (np.where(data[\"YardLine\"]>=14.189999, data[\"X2\"], data[\"YardLine\"] ))) )) +\n#             0.100000*np.tanh(np.where((8.0)<0.650000, -1.0, np.where(data[\"Position4\"]<0.400000, -3.0, ((np.where(((np.where(np.where(np.where(data[\"Dir2\"]<0.420000, data[\"PlayerHeight1\"], data[\"JerseyNumber1\"] )>=18.549988, ((data[\"Location\"]) - (data[\"A15\"])), data[\"X9\"] )<20.130005, data[\"Dir10\"], data[\"PlayerHeight1\"] )) * 2.0)>=20.419998, data[\"OffensePersonnel\"], data[\"A15\"] )) - (data[\"PlayerHeight1\"])) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Location\"]<19.269989, np.where(np.where(data[\"Y9\"]>=19.269989, data[\"PlayerHeight6\"], -1.0 )<0.410000, np.where(data[\"X13\"]<20.419998, data[\"Y9\"], ((data[\"Y9\"]) * (data[\"Dis19\"])) ), (-1.0*((data[\"Position10\"]))) ), np.where(data[\"Position10\"]<20.809998, data[\"A13\"], data[\"YardLine\"] ) )<2.0, (-1.0*((data[\"X14\"]))), ((data[\"Location\"]) * 2.0) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"X10\"]>=0.060000, data[\"PlayerCollegeName2\"], -3.0 )<149.0, np.where(np.where(data[\"A6\"]>=0.710000, -3.0, data[\"PlayerCollegeName2\"] )<20.619995, data[\"JerseyNumber17\"], data[\"S1\"] ), np.where(np.where(data[\"PlayerHeight18\"]>=0.710000, data[\"A6\"], data[\"Dis14\"] )>=0.650000, -3.0, data[\"Orientation14\"] ) )<20.619995, data[\"A6\"], -3.0 )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"Dis13\"]) \/ 2.0)<0.060000, data[\"Dis6\"], data[\"A15\"] )<0.410000, data[\"Y11\"], ((np.where(data[\"Y11\"]<20.809998, data[\"A8\"], np.where(data[\"Dis6\"]<0.060000, data[\"Y11\"], np.where(data[\"Orientation11\"]<21.670013, data[\"PlayerHeight13\"], ((((data[\"Dis14\"]) - (data[\"Dis13\"]))) - (data[\"Dis13\"])) ) ) )) * 2.0) )) +\n#             0.100000*np.tanh(np.where(-3.0>=192.0, data[\"JerseyNumber16\"], np.where(np.where(data[\"Orientation14\"]>=8.0, data[\"PlayerWeight17\"], data[\"A15\"] )>=20.809998, np.where(data[\"JerseyNumber16\"]>=20.360008, np.where(np.where(((data[\"Y21\"]) \/ 2.0)>=15.0, data[\"X6\"], data[\"PlayerHeight0\"] )>=15.0, data[\"PlayerWeight17\"], ((data[\"Orientation7\"]) - (data[\"PlayerWeight17\"])) ), data[\"Position21\"] ), data[\"PlayerWeight17\"] ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight13\"]>=0.670000, ((np.where(data[\"PlayerHeight12\"]<12.0, ((np.where(data[\"DefendersInTheBox\"]<6.0, data[\"Stadium\"], np.where(np.where(data[\"Y21\"]<20.719994, data[\"PlayerHeight12\"], data[\"Dir9\"] )>=20.719994, np.where(data[\"Dis10\"]<0.070000, data[\"Y21\"], 0.0 ), (-1.0*((data[\"Humidity\"]))) ) )) \/ 2.0), data[\"PlayerHeight0\"] )) \/ 2.0), data[\"Humidity\"] )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Position14\"]<11.0, -1.0, data[\"Position0\"] )>=11.0, np.where(data[\"PlayerCollegeName4\"]<11.0, data[\"DefendersInTheBox\"], data[\"Position0\"] ), data[\"Y0\"] )<20.709999, data[\"NflId2\"], np.where(data[\"DefendersInTheBox\"]<6.0, data[\"NflId5\"], np.where(((data[\"DisplayName13\"]) - (data[\"Y0\"]))<20.699997, data[\"PlayerWeight17\"], np.where(data[\"YardLine\"]>=11.0, -3.0, data[\"YardLine\"] ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"S15\"]<0.440000, ((data[\"OffensePersonnel\"]) - (data[\"GameWeather\"])), np.where(data[\"Y5\"]<20.709999, data[\"Position21\"], np.where(np.where(np.where(data[\"Position21\"]>=0.070000, data[\"S15\"], data[\"Position21\"] )>=1.0, data[\"GameWeather\"], data[\"A12\"] )<20.620003, (-1.0*((((data[\"Position21\"]) - (data[\"OffensePersonnel\"]))))), ((data[\"Position21\"]) - (data[\"OffensePersonnel\"])) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"A8\"]<0.429999, ((data[\"DisplayName2\"]) - (data[\"DisplayName20\"])), np.where(data[\"PlayerHeight20\"]<2.0, data[\"NflId17\"], np.where(data[\"Position19\"]<2.0, data[\"A8\"], np.where(data[\"YardLine\"]>=20.570007, np.where(data[\"NflId17\"]<2552603.0, ((data[\"DisplayName2\"]) - (data[\"DisplayName20\"])), (-1.0*((data[\"PlayerHeight13\"]))) ), (-1.0*((data[\"DisplayName20\"]))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"Y7\"]>=14.0, np.where(data[\"Y10\"]>=19.940430, np.where(data[\"VisitorScoreBeforePlay\"]<20.370117, np.where(data[\"OffensePersonnel\"]<19.940430, np.where(data[\"Y11\"]>=19.940430, data[\"VisitorScoreBeforePlay\"], (-1.0*(((((data[\"Dis18\"]) + (data[\"Y7\"]))\/2.0)))) ), data[\"PlayerHeight16\"] ), (-1.0*((data[\"PlayerHeight16\"]))) ), (-1.0*((data[\"JerseyNumber11\"]))) ), np.where(data[\"Y16\"]<20.809998, data[\"PlayerHeight16\"], data[\"OffensePersonnel\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerHeight10\"]<11.0, np.where(data[\"Orientation6\"]<21.670013, data[\"Orientation4\"], data[\"S12\"] ), data[\"X17\"] )<20.130005, np.where(data[\"JerseyNumber14\"]>=20.450005, np.where(np.where(data[\"Dis21\"]<0.070000, data[\"PlayerHeight10\"], data[\"Orientation4\"] )>=20.450005, ((data[\"Orientation6\"]) - (data[\"Dir5\"])), data[\"Orientation4\"] ), data[\"Orientation4\"] ), (-1.0*((data[\"S21\"]))) )) +\n#             0.100000*np.tanh(np.where(data[\"S2\"]>=1.0, np.where(data[\"S2\"]>=6.0, ((data[\"PlayerHeight4\"]) * 2.0), np.where(data[\"A3\"]>=0.410000, np.where(data[\"Position16\"]>=6.0, -2.0, np.where(data[\"Dis14\"]>=0.410000, -2.0, np.where(data[\"JerseyNumber5\"]>=20.539993, data[\"A3\"], data[\"PlayerHeight1\"] ) ) ), np.where(data[\"Position16\"]>=20.539993, data[\"Orientation21\"], -2.0 ) ) ), ((data[\"PlayerHeight4\"]) * 2.0) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"JerseyNumber4\"]<20.0, ((data[\"JerseyNumber21\"]) \/ 2.0), data[\"PlayerCollegeName0\"] )>=20.620003, np.where(data[\"Dis17\"]>=0.410000, data[\"JerseyNumber21\"], np.where(data[\"X11\"]<99.0, np.where(data[\"JerseyNumber21\"]>=20.709999, np.where(data[\"PlayerWeight11\"]<192.0, -2.0, data[\"S4\"] ), -3.0 ), ((data[\"Dir8\"]) - (data[\"PlayerWeight10\"])) ) ), ((data[\"Dir8\"]) - (data[\"PlayerWeight10\"])) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"S13\"]>=0.410000, data[\"JerseyNumber1\"], -3.0 )<20.419998, ((data[\"PlayerCollegeName16\"]) - (data[\"PlayerCollegeName21\"])), np.where(data[\"Y7\"]<20.469994, data[\"X4\"], np.where(data[\"JerseyNumber9\"]>=91.0, ((data[\"PlayerCollegeName16\"]) - (data[\"JerseyNumber9\"])), np.where(data[\"OffenseFormation\"]<6.0, -3.0, np.where(data[\"JerseyNumber9\"]<20.620003, -3.0, data[\"JerseyNumber9\"] ) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"Orientation6\"]>=190.0, ((((data[\"Orientation14\"]) - (np.where(data[\"Y16\"]>=16.490002, data[\"Dir14\"], data[\"PlayerCollegeName5\"] )))) - (np.where(np.where(data[\"Orientation14\"]<20.570007, data[\"Dir14\"], data[\"Y11\"] )>=16.490002, np.where(data[\"Position2\"]<23.0, data[\"Dir14\"], (-1.0*((data[\"X17\"]))) ), data[\"DisplayName2\"] ))), ((data[\"DL\"]) - (data[\"S17\"])) )) +\n#             0.100000*np.tanh(((data[\"PlayerCollegeName9\"]) - (np.where(data[\"PlayerHeight20\"]<0.070000, (((data[\"Dir4\"]) + (data[\"X10\"]))\/2.0), np.where(np.where(data[\"Dir3\"]<20.340004, data[\"X10\"], np.where(data[\"Y21\"]<19.070007, ((((data[\"Dir3\"]) - (data[\"X2\"]))) - ((((data[\"Dir4\"]) + (data[\"X2\"]))\/2.0))), data[\"PlayerCollegeName9\"] ) )>=20.619995, data[\"DisplayName21\"], (5.73773288726806641) ) )))) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName4\"]<9.0, (-1.0*((data[\"A18\"]))), np.where(data[\"A7\"]<0.410000, data[\"PossessionTeam\"], np.where(((data[\"PossessionTeam\"]) * 2.0)<0.470000, -2.0, np.where(data[\"A5\"]<0.470000, data[\"PlayerCollegeName17\"], np.where(np.where(data[\"PossessionTeam\"]>=23.0, data[\"PlayerCollegeName17\"], data[\"HomeScoreBeforePlay\"] )<23.0, data[\"PlayerCollegeName17\"], (((-1.0*((data[\"PlayerCollegeName4\"])))) * 2.0) ) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName17\"]>=20.619995, np.where(np.where(np.where((((np.where(data[\"Dis0\"]>=20.419998, -2.0, data[\"Dis0\"] )) + (data[\"Stadium\"]))\/2.0)>=19.260010, data[\"X13\"], -2.0 )<16.410000, -3.0, data[\"Distance\"] )<8.0, np.where(data[\"Dis0\"]>=0.070000, data[\"Position7\"], -2.0 ), -3.0 ), np.where(data[\"WindSpeed\"]<20.339996, -2.0, data[\"X20\"] ) )) +\n#             0.100000*np.tanh(((((data[\"PlayerCollegeName15\"]) + (np.where(((data[\"S21\"]) * (np.where(data[\"PlayerCollegeName15\"]<20.770004, data[\"Dis5\"], data[\"S21\"] )))<20.0, ((np.where(data[\"Orientation10\"]<20.770004, ((data[\"X18\"]) - (data[\"PlayerCollegeName15\"])), np.where(data[\"PlayerCollegeName15\"]<20.770004, data[\"Orientation10\"], data[\"S21\"] ) )) - (data[\"Orientation13\"])), data[\"Dis5\"] )))) \/ 2.0)) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"PlayerCollegeName9\"]<20.619995, data[\"Dis18\"], np.where(((data[\"WindSpeed\"]) - (data[\"JerseyNumber6\"]))>=0.650000, np.where(data[\"Y7\"]>=19.829987, ((data[\"X19\"]) \/ 2.0), ((data[\"PlayerCollegeName9\"]) \/ 2.0) ), ((data[\"Y7\"]) * 2.0) ) )>=20.699997, data[\"Orientation10\"], data[\"VisitorTeamAbbr\"] )<20.290009, data[\"Orientation10\"], ((((data[\"X11\"]) \/ 2.0)) - (data[\"JerseyNumber6\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"PossessionTeam\"]<0.690000, -1.0, np.where(np.tanh((data[\"PlayerHeight4\"]))>=1.0, (((data[\"A9\"]) + (-2.0))\/2.0), ((np.where(data[\"YardLine\"]<19.070007, np.where(data[\"Dir1\"]<19.070007, data[\"X15\"], ((data[\"PlayerHeight4\"]) - (data[\"PlayerCollegeName1\"])) ), ((data[\"Dir1\"]) - (data[\"X15\"])) )) \/ 2.0) ) )) +\n#             0.100000*np.tanh(np.where(data[\"S3\"]<6.0, np.where(np.where(data[\"Dir18\"]>=20.440002, ((data[\"A21\"]) * 2.0), (-1.0*((data[\"Orientation4\"]))) )<6.0, np.where(data[\"DB\"]<6.0, np.where(data[\"Dis5\"]<0.070000, data[\"HomeTeamAbbr\"], (-1.0*((data[\"A21\"]))) ), np.where(data[\"Dir3\"]<20.719994, (-1.0*((data[\"HomeTeamAbbr\"]))), data[\"DB\"] ) ), data[\"A21\"] ), data[\"Orientation4\"] )) +\n#             0.099961*np.tanh(np.where(data[\"Orientation6\"]>=20.809998, np.where(np.where(data[\"Dir21\"]<190.0, np.where(np.where(data[\"Position18\"]>=20.0, ((((-1.0*((data[\"Dir14\"])))) + (data[\"X6\"]))\/2.0), data[\"PlayerHeight5\"] )<0.060000, data[\"Position18\"], ((((-1.0*((data[\"DisplayName19\"])))) + (data[\"Dir14\"]))\/2.0) ), data[\"Orientation6\"] )>=0.660000, data[\"Orientation6\"], (-1.0*((data[\"PlayerHeight5\"]))) ), (-1.0*((data[\"PlayerHeight16\"]))) )) +\n#             0.099883*np.tanh(np.where(np.where(data[\"Dis2\"]>=0.070000, data[\"Dis0\"], data[\"Dis2\"] )>=0.070000, ((np.where(data[\"X0\"]>=20.240005, data[\"X0\"], data[\"DB\"] )) - (data[\"Location\"])), np.where(np.where(data[\"X0\"]>=20.240005, data[\"X17\"], data[\"DB\"] )<6.0, data[\"X16\"], (-1.0*((data[\"X17\"]))) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerCollegeName14\"]<14.189999, np.where(data[\"X2\"]<21.290009, data[\"DisplayName21\"], ((data[\"Week\"]) - (data[\"HomeTeamAbbr\"])) ), np.where(((((((data[\"HomeTeamAbbr\"]) * (data[\"S18\"]))) + ((-1.0*((data[\"X10\"])))))) * 2.0)>=20.440002, data[\"X8\"], np.where(data[\"X2\"]<21.290009, data[\"X2\"], ((data[\"Week\"]) - (((data[\"HomeTeamAbbr\"]) * 2.0))) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"PlayerHeight15\"]>=0.070000, np.where(((data[\"X15\"]) - (data[\"X20\"]))>=0.660000, data[\"VisitorScoreBeforePlay\"], np.where(data[\"Dis21\"]>=0.070000, np.where(np.where(((data[\"Distance\"]) - (data[\"YardLine\"]))>=0.660000, data[\"PlayerWeight9\"], data[\"Dis21\"] )>=0.660000, data[\"Distance\"], -3.0 ), data[\"X12\"] ) ), (((((data[\"X15\"]) - (data[\"X20\"]))) + (data[\"VisitorScoreBeforePlay\"]))\/2.0) )) +\n#             0.100000*np.tanh(np.where(data[\"A20\"]<3.0, np.where(data[\"A7\"]<3.0, np.where(np.where(data[\"X1\"]<20.680008, data[\"X6\"], np.where(np.where(data[\"X13\"]<20.680008, data[\"Dis12\"], data[\"JerseyNumber2\"] )<20.680008, 3.0, data[\"JerseyNumber5\"] ) )>=20.620003, -2.0, np.where(data[\"A7\"]>=0.410000, data[\"S8\"], data[\"X14\"] ) ), ((data[\"S8\"]) * 2.0) ), data[\"A7\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"OffensePersonnel\"]>=19.070007, np.where(data[\"JerseyNumber9\"]<19.589996, -2.0, data[\"X17\"] ), data[\"Distance\"] )>=19.070007, data[\"Dir6\"], np.where(data[\"S12\"]>=1.0, np.where((((data[\"JerseyNumber9\"]) + (np.where(data[\"Orientation1\"]>=20.619995, np.where(data[\"Orientation1\"]>=190.0, data[\"Orientation19\"], -2.0 ), data[\"JerseyNumber9\"] )))\/2.0)>=19.589996, -2.0, data[\"Orientation1\"] ), data[\"OffensePersonnel\"] ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(np.where(np.where(np.where(data[\"A10\"]<0.410000, data[\"Dis10\"], data[\"PlayerCollegeName21\"] )>=20.770004, data[\"JerseyNumber18\"], data[\"DisplayName5\"] )<94.0, data[\"WindDirection\"], data[\"Distance\"] )<16.809998, data[\"PlayerCollegeName16\"], data[\"JerseyNumber12\"] )<94.0, data[\"JerseyNumber18\"], data[\"Down\"] )<16.809998, data[\"PlayerCollegeName16\"], data[\"A8\"] )<16.410000, data[\"PlayerCollegeName21\"], ((data[\"A8\"]) - (data[\"X0\"])) )) +\n#             0.100000*np.tanh(np.where(data[\"S20\"]>=0.660000, ((np.where(((data[\"S20\"]) - (1.0))>=0.0, data[\"DisplayName14\"], data[\"PlayerHeight5\"] )) - (np.where(np.where(np.where(data[\"Dis12\"]>=0.410000, data[\"PlayerCollegeName10\"], np.where(data[\"Dis12\"]>=0.410000, data[\"PlayerCollegeName10\"], -2.0 ) )>=131.0, ((data[\"PlayerHeight12\"]) \/ 2.0), data[\"PlayerHeight5\"] )>=0.710000, data[\"DisplayName10\"], data[\"Dis12\"] ))), data[\"PlayerHeight21\"] )) +\n#             0.100000*np.tanh(np.where(data[\"Position0\"]>=0.410000, np.where((((np.where(data[\"S6\"]>=0.680000, np.where(data[\"X4\"]<20.699997, data[\"PlayerHeight12\"], -1.0 ), data[\"S6\"] )) + (data[\"S9\"]))\/2.0)>=0.680000, ((data[\"OffenseFormation\"]) - (data[\"PlayerHeight12\"])), np.where(data[\"Position1\"]>=0.680000, np.where(data[\"Position0\"]<20.699997, data[\"X19\"], -1.0 ), data[\"X19\"] ) ), data[\"PlayerHeight12\"] )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PossessionTeam\"]<20.570007, data[\"Position11\"], data[\"Dir5\"] )>=20.709999, data[\"Dis6\"], np.where(np.where(data[\"Dis2\"]>=0.440000, np.where(data[\"Dir5\"]>=20.339996, data[\"Dir2\"], data[\"S4\"] ), data[\"PossessionTeam\"] )>=20.339996, data[\"PossessionTeam\"], ((np.where(data[\"Dis2\"]>=0.440000, ((data[\"Dir5\"]) - (data[\"X19\"])), data[\"X21\"] )) - (data[\"X19\"])) ) )) +\n#             0.100000*np.tanh(np.where(np.where(3.0>=0.650000, np.where(data[\"Y14\"]<20.470001, data[\"Position8\"], data[\"PlayerWeight16\"] ), data[\"Dis19\"] )<20.339996, data[\"Position8\"], ((data[\"Dir19\"]) - (np.where(np.where(np.where(((data[\"JerseyNumber6\"]) - (data[\"PlayerCollegeName4\"]))>=20.240005, data[\"Dis19\"], data[\"Position3\"] )<0.710000, -2.0, data[\"Dis19\"] )<0.070000, data[\"Position3\"], ((data[\"DisplayName21\"]) \/ 2.0) ))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(np.where(data[\"Dis9\"]>=0.070000, data[\"PlayerHeight7\"], data[\"Orientation21\"] )>=10.0, (-1.0*((data[\"YardLine\"]))), data[\"DisplayName17\"] )>=173.0, data[\"Orientation21\"], data[\"Orientation8\"] )<192.0, ((data[\"Orientation21\"]) * 2.0), -2.0 )) +\n#             0.099961*np.tanh(np.where(np.where(((data[\"X3\"]) - (data[\"JerseyNumber17\"]))<20.699997, ((data[\"NflId19\"]) - (data[\"NflId7\"])), data[\"JerseyNumber17\"] ) < -9998, data[\"NflId19\"], np.where(np.where(np.where(data[\"GameWeather\"]>=20.310005, data[\"NflId7\"], data[\"Position16\"] )>=20.310005, data[\"PlayerCollegeName9\"], data[\"Dis2\"] )>=16.490002, ((data[\"NflId19\"]) - (data[\"NflId7\"])), ((data[\"X3\"]) - (data[\"JerseyNumber17\"])) ) )) +\n#             0.099961*np.tanh(np.where(((data[\"X16\"]) - (data[\"X7\"]))>=0.460000, np.where(data[\"A20\"]<0.440000, (((-1.0*((data[\"X10\"])))) * 2.0), ((data[\"Orientation1\"]) - (data[\"X10\"])) ), (-1.0*((np.where(data[\"A20\"]<0.440000, ((data[\"X7\"]) - (data[\"Orientation1\"])), ((data[\"Orientation1\"]) - (data[\"X16\"])) )))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Position1\"]>=20.440002, data[\"DisplayName0\"], data[\"Orientation1\"] )<100.0, data[\"NflId9\"], data[\"Y4\"] )<2555281.0, np.where(np.where(data[\"Position3\"]>=20.440002, data[\"PlayerCollegeName0\"], data[\"Orientation1\"] )<100.0, data[\"Orientation1\"], data[\"Dis21\"] ), np.where(data[\"Y4\"]<20.440002, np.where(data[\"Position10\"]<11.0, (-1.0*((data[\"Position3\"]))), data[\"Position3\"] ), (-1.0*((data[\"Position3\"]))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Position3\"]>=0.060000, data[\"Dir21\"], (-1.0*((data[\"PlayerWeight4\"]))) )<10.0, data[\"PlayerHeight9\"], np.where(np.where(((data[\"PlayerHeight9\"]) * (data[\"PlayerHeight9\"]))>=95.0, data[\"S18\"], data[\"Dis8\"] )<0.410000, np.where(np.where(data[\"Dir21\"]>=190.0, data[\"Position3\"], data[\"Y0\"] )<20.339996, data[\"Orientation1\"], (-1.0*((data[\"S18\"]))) ), (-1.0*((data[\"Position3\"]))) ) )) +\n#             0.100000*np.tanh(np.where(np.where(((data[\"JerseyNumber21\"]) - (data[\"X4\"]))<20.480003, np.where(data[\"JerseyNumber0\"]<11.0, data[\"X20\"], data[\"PlayerCollegeName17\"] ), data[\"S21\"] )<20.709999, data[\"PlayerCollegeName17\"], ((((data[\"X4\"]) - (data[\"X20\"]))) + (np.where(data[\"JerseyNumber21\"]<14.0, np.where(((data[\"X4\"]) - (data[\"PlayerCollegeName17\"]))<0.070000, data[\"S10\"], data[\"X16\"] ), -2.0 ))) )) +\n#             0.100000*np.tanh(np.where(np.where((((-2.0) + (np.where(np.tanh((data[\"A15\"]))>=0.440000, np.where(np.where(data[\"A21\"]<20.620003, np.where(data[\"A21\"]<1.0, data[\"Dis11\"], data[\"Position9\"] ), ((2.0) * 2.0) )<0.410000, data[\"DL\"], data[\"A21\"] ), data[\"DisplayName11\"] )))\/2.0)<0.650000, data[\"Dis11\"], data[\"PlayerWeight14\"] )>=0.440000, data[\"PlayerWeight14\"], (-1.0*((data[\"Dir15\"]))) )) +\n#             0.100000*np.tanh(np.where((((((np.where(np.where(((data[\"A20\"]) * (data[\"Orientation12\"]))>=131.0, data[\"Position19\"], data[\"A21\"] )>=20.450005, data[\"X9\"], ((data[\"A21\"]) * (data[\"PlayerWeight9\"])) )) \/ 2.0)) + (data[\"Orientation12\"]))\/2.0)<131.0, -3.0, np.where(data[\"DisplayName11\"]>=19.070007, np.where(data[\"X9\"]<20.620003, (-1.0*((data[\"Position19\"]))), data[\"DisplayName16\"] ), data[\"Orientation12\"] ) )) +\n#             0.100000*np.tanh(((np.where(np.where(np.where(data[\"PlayerWeight12\"]<19.260010, data[\"Position12\"], (((data[\"Dis15\"]) + (data[\"YardLine\"]))\/2.0) )<20.539993, np.where(((data[\"Dis15\"]) * 2.0)>=0.710000, data[\"Dis3\"], np.where(data[\"Y0\"]<20.809998, data[\"PlayerWeight12\"], data[\"Position12\"] ) ), ((data[\"Dis18\"]) * 2.0) )>=0.710000, data[\"PlayerWeight3\"], data[\"Orientation21\"] )) - (data[\"PlayerWeight14\"]))) +\n#             0.100000*np.tanh(np.where(data[\"Orientation8\"]>=192.0, ((data[\"Dis3\"]) * 2.0), np.where(data[\"A1\"]>=20.620003, data[\"PlayerCollegeName11\"], np.where(data[\"PlayerCollegeName11\"]>=99.0, np.where(np.where(np.where(data[\"Orientation8\"]>=122.0, data[\"FieldPosition\"], data[\"A21\"] )>=20.0, data[\"PlayerCollegeName8\"], (-1.0*((data[\"Y20\"]))) )>=20.0, data[\"PlayerWeight10\"], (-1.0*((data[\"Orientation8\"]))) ), ((((data[\"Dis18\"]) * 2.0)) * 2.0) ) ) )) +\n#             0.100000*np.tanh(((np.where(data[\"Dis19\"]>=0.070000, ((data[\"DisplayName5\"]) \/ 2.0), np.where(data[\"Dis19\"]>=0.070000, ((data[\"DisplayName5\"]) \/ 2.0), ((np.where(data[\"Y5\"]>=20.680008, data[\"X20\"], data[\"A9\"] )) * (data[\"Y5\"])) ) )) - (((np.where(data[\"X0\"]>=20.680008, np.where(data[\"Orientation1\"]>=20.680008, data[\"YardLine\"], data[\"Y17\"] ), data[\"Y5\"] )) * (data[\"Y5\"]))))) +\n#             0.100000*np.tanh(np.where(data[\"NflId0\"]>=2495328.0, (((-1.0*((np.where(data[\"YardLine\"]<20.360008, data[\"Orientation11\"], (-1.0*((data[\"Position15\"]))) ))))) * (data[\"NflId0\"])), np.where(data[\"Orientation11\"]<20.770004, 3.0, np.where(np.where(data[\"Y5\"]<20.770004, -3.0, data[\"Y5\"] )<20.709999, (-1.0*((data[\"NflId0\"]))), np.where(data[\"Position15\"]<18.290009, data[\"Position15\"], -3.0 ) ) ) )) +\n#             0.100000*np.tanh(np.where((((np.where(np.where(np.where(np.where(data[\"Position12\"]>=20.619995, data[\"PlayerHeight1\"], data[\"JerseyNumber16\"] )<20.709999, data[\"Y6\"], data[\"Position12\"] )>=20.539993, data[\"S5\"], data[\"X16\"] )<20.339996, data[\"X16\"], data[\"PlayerHeight1\"] )) + (data[\"Y6\"]))\/2.0)>=19.829987, data[\"Position12\"], (-1.0*((np.where(data[\"Position12\"]<0.410000, (-1.0*((data[\"S4\"]))), data[\"JerseyNumber16\"] )))) )) +\n#             0.099961*np.tanh(np.where(data[\"Position2\"]<0.420000, np.where(data[\"PlayerHeight10\"]>=20.719994, data[\"PlayerHeight5\"], ((data[\"PlayerHeight10\"]) - (data[\"PlayerHeight5\"])) ), np.where(data[\"Position2\"]>=20.719994, ((data[\"A3\"]) - (data[\"A2\"])), np.where(data[\"A5\"]<0.420000, data[\"DisplayName16\"], np.where(data[\"PlayerCollegeName20\"]>=120.0, ((data[\"A3\"]) - (data[\"A2\"])), ((data[\"PlayerHeight10\"]) - (data[\"A2\"])) ) ) ) )) +\n#             0.100000*np.tanh(((np.where(data[\"S14\"]>=1.0, np.where(np.where(np.where(data[\"Orientation2\"]>=20.620003, data[\"Position21\"], data[\"X4\"] )>=0.660000, data[\"S5\"], data[\"Position21\"] )>=1.0, data[\"X12\"], data[\"Position21\"] ), ((data[\"PlayerHeight3\"]) * (np.where(data[\"Orientation2\"]>=20.620003, np.where(data[\"Position21\"]>=0.660000, data[\"X12\"], data[\"Position21\"] ), data[\"S5\"] ))) )) - (data[\"JerseyNumber16\"]))) +\n#             0.100000*np.tanh(np.where(np.where(data[\"PlayerHeight17\"]>=9.0, data[\"Dir15\"], data[\"PlayerCollegeName18\"] )>=192.0, data[\"VisitorScoreBeforePlay\"], (-1.0*((np.where(data[\"PlayerHeight17\"]<0.650000, data[\"DefendersInTheBox\"], np.where(data[\"PlayerCollegeName4\"]>=192.0, np.where(data[\"VisitorScoreBeforePlay\"]>=9.0, data[\"X7\"], data[\"PlayerCollegeName18\"] ), ((data[\"X19\"]) - (np.where(data[\"VisitorScoreBeforePlay\"]>=0.070000, data[\"JerseyNumber6\"], data[\"PlayerCollegeName18\"] ))) ) )))) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Orientation15\"]<99.0, data[\"Orientation15\"], data[\"Dir7\"] )<99.0, np.where(data[\"PlayerCollegeName12\"]<192.0, ((((data[\"PlayerCollegeName6\"]) - (data[\"PlayerWeight5\"]))) - (((np.where(data[\"JerseyNumber12\"]>=20.240005, data[\"PlayerCollegeName6\"], -3.0 )) - (data[\"PlayerWeight5\"])))), data[\"PlayerWeight5\"] ), data[\"JerseyNumber12\"] )<20.450005, data[\"FieldPosition\"], ((data[\"PlayerCollegeName6\"]) - (data[\"PlayerWeight5\"])) )) +\n#             0.099961*np.tanh(np.where(data[\"Y4\"]<9.0, data[\"DisplayName5\"], np.where(np.where(data[\"A20\"]>=1.0, ((np.where(data[\"FieldPosition\"]<20.539993, data[\"Dis6\"], data[\"Dis0\"] )) * (np.where(data[\"X10\"]<20.770004, data[\"X10\"], data[\"PlayerCollegeName20\"] ))), data[\"FieldPosition\"] )<9.0, data[\"PlayerHeight3\"], -1.0 ) )) +\n#             0.099961*np.tanh(np.where(data[\"A17\"]>=20.339996, data[\"A17\"], np.where(np.where(np.where(np.tanh((data[\"Dis4\"]))<0.070000, data[\"PlayerWeight18\"], ((data[\"PlayerHeight5\"]) * 2.0) )<20.339996, data[\"PlayerCollegeName17\"], data[\"DisplayName19\"] )<190.0, ((data[\"A17\"]) \/ 2.0), np.where(data[\"Orientation11\"]<20.539993, ((data[\"PlayerHeight5\"]) * 2.0), np.where(data[\"Y6\"]<20.539993, data[\"PlayerWeight14\"], (-1.0*((data[\"PlayerWeight14\"]))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(np.where(np.where(data[\"Position15\"]<20.440002, np.where(data[\"Dir4\"]<20.310005, data[\"Position19\"], data[\"A8\"] ), data[\"X1\"] )<20.440002, data[\"Position19\"], np.where(data[\"Dir4\"]<20.310005, data[\"Dis2\"], data[\"A8\"] ) )>=1.0, np.where(np.where(data[\"PlayerCollegeName9\"]>=190.0, data[\"Dis2\"], data[\"PlayerCollegeName9\"] )>=20.620003, data[\"Dis2\"], data[\"Position15\"] ), (-1.0*((data[\"PlayerCollegeName9\"]))) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Y9\"]<20.450005, data[\"Y9\"], data[\"Y9\"] )<20.809998, data[\"Position11\"], np.where(data[\"A14\"]>=0.680000, np.where(data[\"VisitorTeamAbbr\"]>=14.0, np.where(np.where(((data[\"X18\"]) - (-1.0))<20.699997, data[\"Dis1\"], data[\"A8\"] )<0.420000, (-1.0*((data[\"VisitorTeamAbbr\"]))), data[\"Dir2\"] ), (-1.0*((data[\"A8\"]))) ), (-1.0*((data[\"Y9\"]))) ) )) +\n#             0.100000*np.tanh(np.where(np.where((((data[\"PlayerCollegeName2\"]) + (0.0))\/2.0)>=20.450005, data[\"JerseyNumber18\"], np.where(data[\"WindDirection\"]<20.620003, data[\"JerseyNumber12\"], data[\"Dis15\"] ) )<20.450005, data[\"A17\"], np.where(np.where(data[\"PlayerCollegeName17\"]<20.539993, np.where(data[\"A5\"]>=19.589996, data[\"PlayerCollegeName2\"], data[\"Dis15\"] ), data[\"A5\"] )<0.440000, data[\"Distance\"], -3.0 ) )) +\n#             0.100000*np.tanh(np.where(data[\"Position13\"]<19.589996, np.tanh((np.tanh((np.tanh((data[\"Position17\"])))))), np.where(np.where(data[\"X0\"]>=20.360008, ((data[\"Position3\"]) \/ 2.0), data[\"A19\"] )<1.0, data[\"PlayerHeight9\"], np.where(data[\"PlayerHeight9\"]<1.0, data[\"Y0\"], np.where(data[\"Position3\"]>=20.419998, ((data[\"Position17\"]) \/ 2.0), (-1.0*((((((data[\"Y0\"]) * 2.0)) \/ 2.0)))) ) ) ) )) +\n#             0.100000*np.tanh(np.where(data[\"HomeTeamAbbr\"]>=19.849609, ((((data[\"A13\"]) + (((data[\"A13\"]) - (np.where(data[\"A13\"]>=0.660000, data[\"S13\"], data[\"PlayerWeight17\"] )))))) + (((data[\"S21\"]) - (data[\"S4\"])))), (-1.0*((np.tanh((np.where(data[\"Orientation16\"]>=190.0, ((data[\"A13\"]) + (((data[\"A13\"]) - (data[\"S4\"])))), data[\"S18\"] )))))) )) +\n#             0.100000*np.tanh(np.where(np.where(data[\"Position2\"]>=0.060000, np.where(np.where(data[\"Orientation4\"]<20.770004, data[\"Dir1\"], np.where(data[\"JerseyNumber9\"]<20.770004, data[\"PlayerCollegeName15\"], data[\"Orientation4\"] ) )<190.0, data[\"Dis1\"], data[\"S11\"] ), data[\"PlayerWeight20\"] )>=1.0, np.where(-1.0<2552603.0, np.where(data[\"Dir1\"]<20.770004, data[\"YardLine\"], data[\"PlayerHeight3\"] ), data[\"Orientation4\"] ), (-1.0*((data[\"PlayerHeight3\"]))) )) +\n#             0.100000*np.tanh(np.where(data[\"Dir18\"]>=20.770004, np.where(((np.where(np.where(data[\"PlayerHeight15\"]<20.699997, data[\"HomeScoreBeforePlay\"], data[\"A21\"] )>=2.0, np.where(data[\"A4\"]<2.0, np.where(data[\"A21\"]<2.0, data[\"X17\"], data[\"Dir18\"] ), data[\"HomeScoreBeforePlay\"] ), data[\"A4\"] )) \/ 2.0)<20.809998, data[\"Dir18\"], (-1.0*((((data[\"VisitorTeamAbbr\"]) \/ 2.0)))) ), (-1.0*((data[\"NflId9\"]))) )) +\n#             0.100000*np.tanh(np.where(((data[\"A15\"]) - (data[\"S4\"]))>=0.690000, np.where(data[\"Dir4\"]<20.809998, data[\"Dis20\"], data[\"Dir16\"] ), ((np.where(((data[\"Orientation4\"]) * (data[\"Dis20\"]))>=20.480003, np.where(data[\"PlayerCollegeName10\"]<20.340004, data[\"Dir15\"], data[\"Dir4\"] ), data[\"PlayerCollegeName1\"] )) - (data[\"PlayerWeight13\"])) )))\n            0)\n\"\"\"\n## train data\nThe shape of train data is 509762 \u00d7 49.\nBut, since one set consists of 22 lines, the actual number of data is 23171.\nI converted it to a format that is easy to use.\n\"\"\"\nenv = nflrush.make_env()\ntrain_df = pd.read_csv('\/kaggle\/input\/nfl-big-data-bowl-2020\/train.csv', low_memory=False)\ntrain_df.iloc[0, :]\ntrain_df.head()\nunused_columns = [\"GameId\",\"PlayId\",\"Team\",\"Yards\",\"TimeHandoff\",\"TimeSnap\"]\nunique_columns = []\nfor c in train_df.columns:\n    if c not in unused_columns+[\"PlayerBirthDate\"] and len(set(train_df[c][:11]))!= 1:\n        unique_columns.append(c)\n        print(c,\" is unique\")\nunique_columns+=[\"BirthY\"]\nok = True\nfor i in range(0,509762,22):\n    p=train_df[\"PlayId\"][i]\n    for j in range(1,22):\n        if(p!=train_df[\"PlayId\"][i+j]):\n            ok=False\n            break\nprint(\"train data is sorted by PlayId.\" if ok else \"train data is not sorted by PlayId.\")\nok = True\nfor i in range(0,509762,11):\n    p=train_df[\"Team\"][i]\n    for j in range(1,11):\n        if(p!=train_df[\"Team\"][i+j]):\n            ok=False\n            break\nprint(\"train data is sorted by Team.\" if ok else \"train data is not sorted by Team.\")\n\"\"\"\nSince the training data was sorted, preprocessing can be done easily.\n\"\"\"\nall_columns = []\nfor c in train_df.columns:\n    if c not in unique_columns + unused_columns+[\"DefensePersonnel\",\"GameClock\",\"PlayerBirthDate\"]:\n        all_columns.append(c)\nall_columns.append(\"DL\")\nall_columns.append(\"LB\")    \nall_columns.append(\"DB\")\nall_columns.append(\"GameHour\")   \nfor c in unique_columns:\n    for i in range(22):\n        all_columns.append(c+str(i))\nlbl_dict = {}\nfor c in train_df.columns:\n    if c == \"DefensePersonnel\":\n        arr = [[int(s[0]) for s in t.split(\", \")] for t in train_df[\"DefensePersonnel\"]]\n        train_df[\"DL\"] = pd.Series([a[0] for a in arr])\n        train_df[\"LB\"] = pd.Series([a[1] for a in arr])\n        train_df[\"DB\"] = pd.Series([a[2] for a in arr])\n    elif c == \"GameClock\":\n        arr = [[int(s[0]) for s in t.split(\":\")] for t in train_df[\"GameClock\"]]\n        train_df[\"GameHour\"] = pd.Series([a[0] for a in arr])\n    elif c == \"PlayerBirthDate\":\n        arr = [[int(s[0]) for s in t.split(\"\/\")] for t in train_df[\"PlayerBirthDate\"]]\n        train_df[\"BirthY\"] = pd.Series([a[2] for a in arr])\n    elif train_df[c].dtype=='object' and c not in unused_columns: \n        lbl = preprocessing.LabelEncoder()\n        lbl.fit(list(train_df[c].values))\n        lbl_dict[c] = lbl\n        train_df[c] = lbl.transform(list(train_df[c].values))\ntrain_data=np.zeros((509762\/\/22,len(all_columns)))\nfor i in tqdm.tqdm(range(0,509762,22)):\n    count=0\n    for c in all_columns:\n        if c in train_df:\n            train_data[i\/\/22][count] = train_df[c][i]\n            count+=1\n    for c in unique_columns:\n        for j in range(22):\n            train_data[i\/\/22][count] = train_df[c][i+j]\n            count+=1        \ndata = [0 for i in range(199)]\nfor y in y_train_:\n    data[int(y+99)]+=1\nplt.plot([i-99 for i in range(199)],data)\ny_train_ = np.array([train_df[\"Yards\"][i] for i in range(0,509762,22)])\nX_train = pd.DataFrame(data=train_data,columns=all_columns)\na = X_train.copy()\na['Yards'] = y_train_\na.to_csv('mungedtrain.csv',index=False)\n\"\"\"\nSince the variance is small, I standardized the objective variable.\n\"\"\"\ny_train = np.zeros(len(y_train_),dtype=np.float)\nfor i in range(len(y_train)):\n    y_train[i]=(y_train_[i])\n\nscaler = preprocessing.StandardScaler()\nscaler.fit([[y] for y in y_train])\ny_train = np.array([y[0] for y in scaler.transform([[y] for y in y_train])])\n\"\"\"\n## evaluation\nContinuous Ranked Probability Score (CRPS) is derived based on the predicted scalar value.\nThe CRPS is computed as follows:\n$$\nC=\\frac{1}{199N}\\sum_{m=1}^N\\sum_{n=-99}^{99}(P(y\\geq n)-H(n-Y_m))^2\n$$\n$H(x)=1$ if $x\\geq 0$ else $0$\n\"\"\"\n\"\"\"\n## make submission\n\nWhen there is a label that does not exist in the training data, it is handled as nan.\nIf you can check the error one by one and complement it, you will get better score.\n\"\"\"\nindex = 0\nfor (test_df, sample_prediction_df) in tqdm.tqdm(env.iter_test()):\n    for c in test_df.columns:\n        if c == \"DefensePersonnel\":\n            try:\n                arr = [[int(s[0]) for s in t.split(\", \")] for t in test_df[\"DefensePersonnel\"]]\n                test_df[\"DL\"] = [a[0] for a in arr]\n                test_df[\"LB\"] = [a[1] for a in arr]\n                test_df[\"DB\"] = [a[2] for a in arr]\n            except:\n                test_df[\"DL\"] = [np.nan for i in range(22)]\n                test_df[\"LB\"] = [np.nan for i in range(22)]\n                test_df[\"DB\"] = [np.nan for i in range(22)]\n        elif c == \"GameClock\":\n            try:\n                arr = [[int(s[0]) for s in t.split(\":\")] for t in test_df[\"GameClock\"]]\n                test_df[\"GameHour\"] = pd.Series([a[0] for a in arr])\n            except:\n                test_df[\"GameHour\"] = [np.nan for i in range(22)]\n        elif c == \"PlayerBirthDate\":\n            try:\n                arr = [[int(s[0]) for s in t.split(\"\/\")] for t in test_df[\"PlayerBirthDate\"]]\n                test_df[\"BirthY\"] = pd.Series([a[2] for a in arr])\n            except:\n                test_df[\"BirthY\"] = [np.nan for i in range(22)]\n        elif c in lbl_dict and test_df[c].dtype=='object'and c not in unused_columns\\\n            and not pd.isnull(test_df[c]).any():\n            try:\n                test_df[c] = lbl_dict[c].transform(list(test_df[c].values))\n            except:\n                test_df[c] = [np.nan for i in range(22)]\n    count=0\n    test_data = np.zeros((1,len(all_columns)))\n\n    for c in all_columns:\n        if c in test_df:\n            test_data[0][count] = test_df[c][index]\n            count+=1\n    for c in unique_columns:\n        for j in range(22):\n            test_data[0][count] = test_df[c][index + j]\n            count+=1        \n    X_test = pd.DataFrame(data=test_data,columns=all_columns).fillna(-9999)\n    y_pred = np.zeros(199)        \n    y_pred_p = np.round(.5*GPI(X_test).values[0]+.5*GPII(X_test).values[0])\n    y_pred_p += 99\n    for j in range(199):\n        if j>=y_pred_p+10:\n            y_pred[j]=1.0\n        elif j>=y_pred_p-10:\n            y_pred[j]=(j+10-y_pred_p)*0.05\n    env.predict(pd.DataFrame(data=[y_pred],columns=sample_prediction_df.columns))\n    index += 22\nenv.write_submission_file()\n\"\"\"\nThe organizers seemed to expect to predict one by one, so I did. \nHowever, it seems that it is likely to be faster to predict at once after all the evaluation data is acquired by dummy input.\n\n\nThis model is a simple one that has not been tuned, so I think we can still expect a better score.\nPlease let me know if you have any opinions or advice.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f6108a8d054d4e'}"}
{"id":"137306","text":"\"\"\"\n# IMPORTING NECESSARY LIBRARIES\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom sklearn.utils import resample\nfrom scipy.stats import zscore\n!pip install imblearn\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn import metrics\nfrom collections import Counter\n\nfrom sklearn.metrics import r2_score, roc_auc_score, roc_curve, average_precision_score\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report, plot_confusion_matrix\n\nfrom sklearn.model_selection import GridSearchCV\nimport statsmodels.api as sm\n\n\"\"\"\n# 1.  IMPORTING AND WAREHOUSING DATA\n\"\"\"\ncolnames = ['P_incidence', 'P_tilt', 'L_angle', 'S_slope', 'P_radius', 'S_Degree', 'Class']\ndata1 = pd.read_csv(\"\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_3C_weka.csv\", names = colnames, index_col = False, header = 0)\ndata1\n\"\"\"\n# 2. DATA CLEANSING \n\"\"\"\n\"\"\"\n## A. Treating the Datatypes and correcting values wherever required:\n\"\"\"\ndata1.info()\nprint(data1['Class'].unique())\ndef classifier (x):\n    if x == 'Normal':\n        x = 0\n        return x\n    elif x =='Hernia':\n        x = 1\n        return x\n    else:\n        x=2\n        return x\ndata1['Class'] = data1['Class'].apply(classifier)\nprint(data1['Class'].unique())\n\"\"\"\n## B. Treating outliers within Dataset and replacing them with appropriate values:\n\"\"\"\ndata1.boxplot(column = ['P_incidence', 'P_tilt', 'L_angle', 'S_slope', 'P_radius', 'S_Degree'], figsize = (15,5))\nprint(data1.quantile(0.04))\nprint(data1.quantile(0.96))\ndata1[\"P_incidence\"]=np.where(data1[\"P_incidence\"]>data1[\"P_incidence\"].quantile(0.96),data1[\"P_incidence\"].quantile(0.96),data1['P_incidence'])\ndata1[\"P_tilt\"] = np.where(data1[\"P_tilt\"] < data1[\"P_tilt\"].quantile(0.04),data1[\"P_tilt\"].quantile(0.04),data1['P_tilt'])\ndata1[\"P_tilt\"] = np.where(data1[\"P_tilt\"] >data1[\"P_tilt\"].quantile(0.96),data1[\"P_tilt\"].quantile(0.96),data1['P_tilt'])\ndata1[\"L_angle\"] = np.where(data1[\"L_angle\"] > data1[\"L_angle\"].quantile(0.96),data1[\"L_angle\"].quantile(0.96),data1['L_angle'])\ndata1[\"S_slope\"] = np.where(data1[\"S_slope\"] > data1[\"S_slope\"].quantile(0.96),data1[\"S_slope\"].quantile(0.96),data1['S_slope'])\ndata1[\"P_radius\"] = np.where(data1[\"P_radius\"] < data1[\"P_radius\"].quantile(0.04),data1[\"P_radius\"].quantile(0.04),data1['P_radius'])\ndata1[\"P_radius\"] = np.where(data1[\"P_radius\"] > data1[\"P_radius\"].quantile(0.96),data1[\"P_radius\"].quantile(0.96),data1['P_radius'])\ndata1[\"S_Degree\"] = np.where(data1[\"S_Degree\"] > data1[\"S_Degree\"].quantile(0.96),data1[\"S_Degree\"].quantile(0.96),data1['S_Degree'])\ndata1.boxplot(column = ['P_incidence', 'P_tilt', 'L_angle', 'S_slope', 'P_radius', 'S_Degree'], figsize = (15,5))\n\"\"\"\n# 3. DATA ANALYSIS AND VISUALISATION:\n\"\"\"\nfig, ax = plt.subplots(figsize = (20,6))\nax.set_title('Class split', color = 'red')\nsns.countplot(x = 'Class', data = data1)\n\"\"\"\n## A.Performing detailed statistical analysis on the data\n\"\"\"\n\"\"\"\nApplying stats model to find p values\n\"\"\"\nx = data1.iloc[:,:6]\ny = data1['Class']\nx2 = sm.add_constant(x)\nest = sm.OLS(y, x2)\nest2 = est.fit()\nprint(est2.summary())\n\"\"\"\n-->We find that the P_Radius and S_Degree emerge as winners for Significant Parameters for prdicting Class\n\"\"\"\n\"\"\"\nFinding Pearsons CorrelationCoefficients\n\"\"\"\ncor =data1.corr()\ncor\nf, ax = plt.subplots(figsize=(20, 20))\nsns.heatmap(cor, annot=True, cmap='cool', ax=ax)\nplt.show()\n\"\"\"\n-->From Heat Map we find that \"S-Degree\", \"L - Angle\" and \"P-Incidence\" have high correlation coefficients. \n\"\"\"\n\"\"\"\nApplying Pair Plots for Significant Variables to see whether the variables make the class apart \n\"\"\"\n\"\"\"\n## B.Multivariate, Bivariate and Univariate analysis\n\"\"\"\nsns.pairplot (data=data1,vars = ['P_incidence','L_angle','P_radius','S_Degree'],  hue = 'Class', palette = 'bright')\n\"\"\"\nThe Selected Significant Variables definitely try to make the class apart atleast the Class 2 values and the same is evident from the below relation plots\n\"\"\"\nsns.relplot(x=\"P_radius\",y=\"S_Degree\",col='Class', data=data1, palette = 'bright')\n\"\"\"\nNormal class range of P_radius and S_Degree lies between 120 - 135 and below 10 respectievely\n\"\"\"\nsns.relplot(x=\"S_Degree\",y=\"P_incidence\",col='Class', data=data1, palette = 'warm')\n\"\"\"\nNormal Class Range for P incidence lies within 45 - 60 whereas the values outside this range falls under abnormal class\n\"\"\"\nsns.relplot(x=\"L_angle\",y=\"S_Degree\",col='Class', data=data1, palette = 'warm')\n\"\"\"\nNormal Class Range for L angle lies within 25 - 50 whereas the values outside this range falls under abnormal class\n\"\"\"\nfig, ax = plt.subplots(1,6, figsize = (12,4))\nsns.histplot(data1['P_incidence'],bins = 24,kde = True, ax = ax[0])\nax[0].set_title(\"DIST OF P_incidence\")\nsns.histplot(data1['P_tilt'],bins = 24,kde = True, ax = ax[1])\nax[1].set_title(\"DIST OF P_tilt\")\nsns.histplot(data1['L_angle'],bins = 24,kde = True, ax = ax[2])\nax[2].set_title(\"DIST OF L_angle\")\nsns.histplot(data1['S_slope'],bins = 24,kde = True, ax = ax[3])\nax[3].set_title(\"DIST OF S_slope\")\nsns.histplot(data1['P_radius'],bins = 24,kde = True, ax = ax[4])\nax[4].set_title(\"DIST OF P_radius\")\nsns.histplot(data1['S_Degree'],bins = 24,kde = True, ax = ax[5])\nax[5].set_title(\"DIST OF S_Degree\")\n\nplt.tight_layout()\ndata1.skew()\n\"\"\"\nThe values of P incidence, P radius and s slope are normally distributed.\nAlmost all the values are multimodal.\n\"\"\"\n\"\"\"\n# 4. DATA PRE - PROCESSING:\n\"\"\"\n\"\"\"\n## A. Splitting the Predicting and Target variables with normalising the data. \n\"\"\"\nx = data1.iloc[:,:6]\ny = data1['Class']\nxz = x.apply(zscore)\nxztrain, xztest, ytrain, ytest = train_test_split(xz, y, test_size=0.3, random_state=20)\ncounter = Counter (ytrain)\nprint(counter)\n\"\"\"\nWe find that the class 2 is a majority class, and the other two classes are minority classes, which will be balnced by Over sampling with SMOTE Technique, Since we dont want to eliminate the target attribute by downsizing the majority class.\n\"\"\"\n\"\"\"\n## B. Target Balancing and Train - Test Split of data. \n\"\"\"\nsmote = SMOTE(random_state = 20)\nxtrain1, ytrain1 = smote.fit_resample(xztrain, ytrain)\nprint(xtrain1.shape)\ncounter = Counter (ytrain1)\nprint (counter)\n\"\"\"\n# 5. MODEL TRAINING, TESTING AND TUNING:\n\"\"\"\n\"\"\"\n## A. Designing and training a KNN Claasifier - K = 10(sqrt(105))\n\"\"\"\nmodelkn = KNeighborsClassifier(n_neighbors = 10)\nmodelkn.fit(xtrain1, ytrain1)\n\"\"\"\n## B.Displaying the Accuracies for Train and Test Data\n\"\"\"\nprint(\"The accuracy for train data is:\", modelkn.score(xtrain1, ytrain1))\nprint(\"The accuracy for test data is:\", modelkn.score(xztest, ytest))\n\"\"\"\n## C. Displaying and explaining the Classification Report:\n\"\"\"\nypred = modelkn.predict(xztest)\nprint(\"CLASSIFICATION REPORT: \\n\",classification_report(ytest,ypred))\nprint(\"CONFUSION MATRIX: \\n\",confusion_matrix(ytest,ypred))\nprint(\"CROSS TAB: \\n\", pd.crosstab(ytest, ypred, rownames=['True'], colnames=['Predicted'], margins=True))\nplot_confusion_matrix(modelkn,xztest,ytest)\n\"\"\"\n1. The Errors values in the above model is to the value of around 20 on a overall dataset of 217 entries which work out to be around 10%.\n\"\"\"\n\"\"\"\n2. The Recall values for classes 1 & 2 are above 80%, whereas the recall for class 0 is about 61%, which means that the Model is not biased on the majority class after balancing the dataset.\n\"\"\"\n\"\"\"\n3. The model accuracy on the testing Dataset is above 70%.\n\"\"\"\n\"\"\"\n## D. Automating the Task of finding the best K values:\n\"\"\"\nmylist =np.arange(1,50)\ntrsco = []\ntesco = []\nbestk = []\nfor k in mylist:\n    modelkn = KNeighborsClassifier(n_neighbors=k)\n    modelkn.fit(xtrain1, ytrain1)\n    ypredtr = modelkn.predict(xtrain1)\n    ypredte = modelkn.predict(xztest)\n    trscores = metrics.accuracy_score(ypredtr, ytrain1)\n    tescores = metrics.accuracy_score(ypredte, ytest)\n    trsco.append(trscores)\n    tesco.append(tescores)\n    if trscores>0.85:\n        bestklist = [k,trscores,tescores]\n        bestk.append(bestklist)\n    #print('>%d,train:%0.3f,test:%0.3f' %(k,trscores,tescores))\n#print(bestk)\noptk = []\nfor x,y,z in bestk:\n    k = x\n    optk.append(x)\nprint(\"K values giving training scores more than 85% are:\", optk)\n\"\"\"\nThe optimal k values for the accuracy of above 85% on the training data set are listed from the above code.\n\"\"\"\nplt.plot(mylist,trsco,'-o', label = \"Train\")\nplt.plot(mylist,tesco,'-o', label = \"Test\")\nplt.legend()\nplt.show()\n\"\"\"\nAbove plot shows that the TRaining and Test Scores converge to the same point and the following obsevations are made,\n\"\"\"\n\"\"\"\n1. The training accuracy scores continue to drop from K value of 1 and converge towards testing data scores.\n\"\"\"\n\"\"\"\n2. The testing accuracy scores initially elevate to a level where it stabilises and then drops significantly.\n\"\"\"\n\"\"\"\n3. We select the k values in this range where it stabilises for testing data and tune our model for better results.\n\"\"\"\n\"\"\"\n## E. Tuning the Paramters for best recall values:\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ngrid_params = {'n_neighbors':[5,6,7],'weights':['uniform', 'distance'],\n'leaf_size':list(range(1,20)),'algorithm':['ball_tree','kd_tree','brute'],'metric':['euclidean','manhattan']}\n\ngs = GridSearchCV(KNeighborsClassifier(), grid_params,scoring = 'recall', verbose = 1, cv = 3, n_jobs = -1)\ngs_results = gs.fit(xztest, ytest)\nprint(gs_results.best_estimator_)\nprint(gs_results.best_params_)\n\"\"\"\nIgnoring warning since the values are turning out to be Non - Finite for some iteration values\n\"\"\"\nmodelkn1 = KNeighborsClassifier( n_neighbors= 7, algorithm='ball_tree', leaf_size=1, metric='euclidean',weights= 'uniform')\nmodelkn1.fit(xtrain1, ytrain1)\n\"\"\"\nSelecting the model with best parameters as above\n\"\"\"\nprint(modelkn1.score(xtrain1, ytrain1))\n\"\"\"\nThe Training scores have improved from 86% to above 90%.\n\"\"\"\nypredte = modelkn1.predict(xztest)\ntescores = accuracy_score(ypredte, ytest)\ntescores\n\"\"\"\nThe test data acuuracy scores have improved from 76% to above 83%.\n\"\"\"\n\"\"\"\n## AOC FOR PREDICTING THE ABNORMALITIES:\n\"\"\"\nyproba1 = modelkn1.predict_proba(xztest)[:,1]\nyproba2 = modelkn1.predict_proba(xztest)[:,2]\nyproba12 = yproba1+yproba2\nytestnew = list()\nfor x in ytest:\n    if x == 2:\n        x = 1\n        ytestnew.append(x)\n    else:\n        x = x\n        ytestnew.append(x)\nfpr, tpr, thresholds = roc_curve(ytestnew, yproba12)\nplt.plot([0,1],[0,1])\nplt.plot(fpr,tpr, label='Knn')\nplt.xlabel('fpr')\nplt.ylabel('tpr')\nplt.title('Knn(n_neighbors=11) ROC curve')\nplt.show()\n\nfrom sklearn.metrics import roc_auc_score\nprint(\"AREA UNDER THE CURVE IS:\",roc_auc_score(ytestnew,yproba12))\nprint(\"CLASSIFICATION REPORT: \\n\",classification_report(ytest,ypredte))\nprint(\"CONFUSION MATRIX: \\n\",confusion_matrix(ytest,ypredte))\nprint(\"CROSS TAB: \\n\", pd.crosstab(ytest, ypredte, rownames=['True'], colnames=['Predicted'], margins=True))\nplot_confusion_matrix(modelkn1,xztest,ytest,cmap = 'cool')\n\"\"\"\n# 6. CONCLUSION AND IMPROVISATION:\n\"\"\"\n\"\"\"\n## A. CONCLUSION:\n\"\"\"\n\"\"\"\nThe Errors values in the above model is to the value less than 20 on a overall dataset of 217 entries which work out to be less than 10%, when compared to above 10% before tuning.\n\"\"\"\n\"\"\"\nThe Recall values for classes 2 is about 89% when compared 84% in the earlier model.\n\"\"\"\n\"\"\"\nThe model accuracy on the testing Dataset is about 82%\n\"\"\"\n\"\"\"\nHence we Conclude that the modelkn1 is the best after parameter tuning for predicting the abnormalities in the biomechanical features for classifying against Hernia and Spondolysthesis.\n\"\"\"\n\"\"\"\n## B. IMPROVISATION:\n\"\"\"\n\"\"\"\n1. Data Collection should have tried to achieve the target balancing initially itself.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fc6591d92c9417'}"}
{"id":"36490","text":"# 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 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\n\"\"\"\n# Exploratory Data Analysis (EDA) IPL Analysis 2008 To 2019\n\"\"\"\nimport numpy as np              # used to read and preprocess data\nimport seaborn as sns           # used to working with arrays Single or MultiDiementional\nimport pandas as pd             # Visualisation of data\nimport matplotlib.pyplot as plt # Visualisation of data\n%matplotlib inline\ndata=pd.read_csv('\/kaggle\/input\/ipldata\/matches.csv')\ndata.head()\ndata.shape\n\"\"\"\n## Data Cleaning Process\n\"\"\"\n# removing unwanted coloumns\ncolumns_to_remove = ['id','umpire1','umpire2','umpire3']\ndata.drop(labels=columns_to_remove,axis=1,inplace=True)\ndata.head()\ndata['team1'].unique()\ndata['team2'].unique()\n\"\"\"\n## Eliminating redundancy\n\n#### There were two entries for the same city as 'Delhi Daredevils' and 'Delhi Capitals' Also we will consider those cities which are regular from first season to last season\n\"\"\"\ndata.at[data['team1']=='Delhi Daredevils','team1']='Delhi Capitals'\ndata.at[data['team2']=='Delhi Daredevils','team2']='Delhi Capitals'\ndata.at[data['winner']=='Delhi Daredevils','winner']='Delhi Capitals'\nconsistent_teams = ['Royal Challengers Bangalore',\n       'Kolkata Knight Riders', 'Kings XI Punjab',\n       'Sunrisers Hyderabad', 'Mumbai Indians', \n       'Rajasthan Royals', 'Chennai Super Kings',      \n       'Delhi Capitals']\ndata = data[(data['team1'].isin(consistent_teams)) & (data['team2'].isin(consistent_teams))]\nprint(data['team1'].unique())\nprint(data['team2'].unique())\ndata.head()\ndata.shape\n\"\"\"\n## Final Result Of All Season\n\"\"\"\nsns.set_style(\"darkgrid\")\nfig=plt.gcf()\nfig.set_size_inches(15,5)\nplt.xticks(rotation=0,fontsize=12)\nplt.yticks(fontsize=16)\nresults=pd.DataFrame(data['result'].value_counts())\nresults['name']=results.index  # store index as ht in name\nplt.bar(results['name'],results['result'],color=['orange','green'])\ncount=0\nfor i in results['result']:\n    plt.text(count-0.10,i+0.1,str(i),size=15,color='black',rotation=0)\n    count+=1\n    \n#  count-0.15 for center align\n#  i+0.1 for Vertical Alignment\n\nplt.title('Final Result',fontsize=20)\nplt.xlabel('Result',fontsize=15)\nplt.ylabel('Total no. of matches (2008-2019)',fontsize=15)\n\"\"\"\n## Total no.of wins by each Team\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,10.5)\nwins=pd.DataFrame(data['winner'].value_counts())\nwins['name']=wins.index\nplt.xticks(rotation=90,fontsize=12)\nplt.yticks(fontsize=16)\nplt.bar(wins['name'],\n        wins['winner'],\n        color=['#15244C','#FFFF48','#292734','#EF2920','#CD202D','#ECC5F2',\n               '#294A73','#D4480B','#242307','#FD511F','#158EA6','#E82865',\n               '#005DB7','#C23E25','#E82865']\n        ,alpha=0.8)\ncount=0\nfor i in wins['winner']:\n    plt.text(count-0.15,i-4,str(i),size=15,color='black',rotation=90)\n    count+=1\nplt.title('Total wins by each team',fontsize=20)\nplt.xlabel('Teams',fontsize=15)\nplt.ylabel('Total no. of matches won(2008-2019)',fontsize=14)\n#plt.show()\n\"\"\"\n## Top 10 players with most MOM awards\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,10.5)\nM_O_M=pd.DataFrame(data['player_of_match'].value_counts())\nM_O_M['name']=M_O_M.index\nM_O_M=M_O_M.head(10)\nplt.xticks(rotation=90,fontsize=12)\nplt.yticks(fontsize=16)\nplt.bar(M_O_M['name'],M_O_M['player_of_match'],\n        color=['#CD202D','#EF2920','#D4480B','#15244C','#FFFF48','#EF2920',\n               '#FFFF48','#FFFF48','#292734','#FFFF48','#ECC5F2','#EF2920',\n               '#292734','#15244C','#005DB7','#005DB7','#292734','#15244C',\n               '#FFFF48','#CD202D'],alpha=0.8)\ncount=0\nfor i in M_O_M['player_of_match']:\n    plt.text(count-0.15,i+0.1,str(i),size=15,color='black',rotation=0)\n    count+=1\n    \n#  count-0.15 for center align\n#  i+0.1 for Vertical Alignment\n\nplt.title('Top 20 Man Of The Match Winners(2008-2019)',fontsize=20)\nplt.xlabel('Players Name',fontsize=15)\nplt.ylabel('Total Awards Count',fontsize=14)\n\"\"\"\n## Matches hosted in each city\n\"\"\"\n\"\"\"\n#### Here we found that two different names of same city (Bangalore and Bangaluru) so we consider one unique name instead of two\n\"\"\"\ndata.at[data['city']=='Bengaluru','city']='Bangalore'\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,10.5)\ncities=pd.DataFrame(data['city'].value_counts())\ncities['name']=cities.index\n#cities=cities.head(10)\nplt.xticks(rotation=90,fontsize=12)\nplt.yticks(fontsize=16)\nplt.bar(cities['name'],cities['city'],alpha=0.8)\ncount=0\nfor i in cities['city']:\n    plt.text(count-0.18,i+0.1,str(i),size=15,color='black',rotation=0)\n    count+=1\nplt.title('Total Matches Hosted At Each City ',fontsize=20)\nplt.xlabel('City',fontsize=15)\nplt.ylabel('Total Number Of Matches Hosted',fontsize=14)\n\"\"\"\n## No. of matches hosted at each stadium\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,10.5)\nVenue=pd.DataFrame(data['venue'].value_counts())\nVenue['name']=Venue.index\nplt.xticks(rotation=90,fontsize=12)\nplt.yticks(fontsize=16)\nplt.bar(Venue['name'],Venue['venue'],alpha=0.8)\ncount=0\nfor i in Venue['venue']:\n    plt.text(count-0.18,i+0.1,str(i),size=15,color='black',rotation=0)\n    count+=1\nplt.title('Total Matches Hosted At Each venue ',fontsize=20)\nplt.xlabel('Venue',fontsize=15)\nplt.ylabel('Total Number Of Matches Hosted',fontsize=14)\n\"\"\"\n## MI vs CSK head to head\n\"\"\"\nhead_to_head = ['Mumbai Indians','Chennai Super Kings',]\n# we consider only those matches played bitween MI and CSK\ndata_MIvsCSK = data[(data['team1'].isin(head_to_head)) & (data['team2'].isin(head_to_head))]\n# we can also use this method to find head to head clash\n# we consider only those matches played bitween MI and CSK\n# data_MIvsCSK=data[np.logical_or\n#       (np.logical_and(data['team1']=='Mumbai Indians',data['team2']=='Chennai Super Kings')\n#                  ,np.logical_and(data['team2']=='Mumbai Indians',data['team1']=='Chennai Super Kings'))]\nprint(data_MIvsCSK['team1'].unique())\nprint(data_MIvsCSK['team2'].unique())\nsns.set(style='dark')\nfig=plt.gcf()\nfig.set_size_inches(10,8)\nsns.countplot(data_MIvsCSK['winner'],order=data_MIvsCSK['winner'].value_counts().index)\nplt.text(-0.1,15,str(data_MIvsCSK['winner'].value_counts()['Mumbai Indians']),size=29,color='white')\nplt.text(0.9,9,str(data_MIvsCSK['winner'].value_counts()['Chennai Super Kings']),size=29,color='white')\nplt.xlabel('Winner',fontsize=15)\nplt.ylabel('Count',fontsize=15)\nplt.yticks(fontsize=0)\nplt.title('MI vs CSK - head to head')\nplt.show()\n\"\"\"\n## MI vs CSK - Best performers\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,8)\nsns.countplot(data_MIvsCSK['player_of_match'],order=data_MIvsCSK['player_of_match'].value_counts().index,palette='Set2')\nplt.title('All man of the match awards in MI-CSK games',fontsize=15)\nplt.yticks([1,2,3],[1,2,3],fontsize=15)\nplt.xticks(fontsize=15,rotation=90)\nplt.xlabel('Man of the match',fontsize=15)\nplt.ylabel('Count',fontsize=15)\nplt.show()\n\"\"\"\n## Toss decision statistics for all MI vs CSK matches - Venue wise\n\"\"\"\n\"\"\"\n#### this graph shows that what decision teams takes after winning toss\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,8)\nsns.countplot(data_MIvsCSK['venue'],order=data_MIvsCSK['venue'].value_counts().index,palette='Set2',hue=data['toss_decision'])\nplt.title('Toss decision at each venue in MIvCSK matches',fontsize=15)\nplt.yticks(fontsize=15)\nplt.xticks(fontsize=15,rotation=90)\nplt.xlabel('Venue',fontsize=15)\nplt.ylabel('Count',fontsize=15)\nplt.legend(loc=5,fontsize=15)\nplt.show()\n\"\"\"\n## Decision based on toss winning for both teams\n\"\"\"\nsns.set(style='darkgrid')\nfig=plt.gcf()\nfig.set_size_inches(18.5,8)\nsns.countplot(data_MIvsCSK['toss_winner'],order=data_MIvsCSK['toss_winner'].value_counts().index,palette='Set2',hue=data['toss_decision'])\nplt.title('Toss decision statistics for both team',fontsize=15)\nplt.yticks(fontsize=15)\nplt.xticks(fontsize=15)\nplt.xlabel('Toss winner',fontsize=15)\nplt.ylabel('Count',fontsize=15)\nplt.text(-0.25,6,str(int((7\/15)*100)+1)+'%',fontsize=29)\nplt.text(0.15,7,str(int((8\/15)*100))+'%',fontsize=29)\nplt.text(0.75,7,str(int((8\/13)*100)+1)+'%',fontsize=29)\nplt.text(1.15,4,str(int((5\/13)*100))+'%',fontsize=29)\nplt.legend(['Field first','Bat first'],loc='best',fontsize=15)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '43335962459a84'}"}
{"id":"112634","text":"\"\"\"\n# EDA\nAgora que os dados est\u00e3o dispon\u00edveis, podemos explor\u00e1-los. Nessa etapa, os dados ser\u00e3o analisados e visualizados com o intuito de se obter insights e informa\u00e7\u00f5es adicionais.\n\nInicialmente, vamos d\u00e1 uma olhada superficial na descri\u00e7\u00e3o dispon\u00edvel dos dados. No pr\u00f3rprio site da competi\u00e7\u00e3o do [Kaggle](https:\/\/www.kaggle.com\/c\/house-prices-advanced-regression-techniques) pode-se notar que os dados correspondem a **81 colunas e 1460 linhas**.\n\n\"\"\"\n\"\"\"\n## Features (Colunas)\n\nAnalisa algumas das **Features** de cada observa\u00e7\u00e3o e suas respectivas descri\u00e7\u00f5es.\n\n- **Id**: ID \u00fanica para identificar do im\u00f3vel - \ud83c\udd94\n- **SalePrice** : Pre\u00e7o de venda  - \ud83c\udfaf\n- **MSSubClass**: Classifica\u00e7\u00e3o do tipo de constru\u00e7\u00e3o.\n- **MSZoning**: Classifica\u00e7\u00e3o geral de zona.\n- **LotFrontage**: Distancia em p\u00e9s de rua conectada a propriedade.\n- **LotArea**: Tamanho da propriedade dem p\u00e9s quadrados.\n- **Street** : Tipo de acesso pela estrada.\n- **Alley** : Tipo de acesso por becos.\n- **LotShape**: Planicidade de propriedade.\n- **LandCountour** : Tipo de acesso pela estrada.\n- **Utilities** : Tipo de servi\u00e7os dispon\u00edveis.\n- **LotConfig**: Configura\u00e7\u00e3o do lote.\n- **LandSlope** : Inclina\u00e7\u00e3o da propriedade.\n- ...\n\"\"\"\n# Import EDA libraries\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport missingno as msno\n\n# Ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# Load data\ntrain = pd.read_csv(\"..\/input\/train.csv\", infer_datetime_format=True)\n# Brief visualization\ntrain.head()\n# Brief infomatin\ntrain.info()\n\"\"\"\nVamos observar algumas estat\u00edsticas das colunas.\n\"\"\"\n# Brief description\ntrain.describe()\n# Features\ntrain.columns\n# Size\ntrain.shape\n\"\"\"\n## Limpeza\n\nAgora que temos uma no\u00e7\u00e3o geral dos dados, vamos realizar algumas opera\u00e7\u00f5es para verificar se se h\u00e1 dados faltando, duplicados ou outras inconsist\u00eancias.\n\"\"\"\n# Look for duplicates\ntrain.duplicated().sum()\n# Look for missing data\ntrain.isna().sum().sum()\nmsno.matrix(train)\nmiss_count = train.isna().sum()\nmiss_count = miss_count[miss_count > 0]\nmiss_count\n# Shows which missings values occurs simultaneously on both columns\nax = msno.heatmap(train, cmap='RdBu')\n# Show unique values in missing columns\ndef get_unique_values_col(df):\n    data = {}\n    for col, s in df.iteritems():\n        data[col] = s.unique()\n    return pd.Series(data)\nunique_mc = get_unique_values_col(train[miss_count.index])\nunique_mc\n\"\"\"\nTemos dados muitos ricos, por\u00e9m escassos. Nesse caso, remover observa\u00e7\u00f5es com valores faltando \u00e9 inaceit\u00e1vel.\n\nPode-se notar que os conjuntos de colunas abaixo possuem dados faltando em simultaneamente:\n\n- `MasVnrType` e `MasVnrArea`: **8**.\n- `BsmtQual`, `BsmtCond`, `BsmtExposure`, `BsmtFinType1` e `BsmtFinType2`: **37\/38**.\n- `GarageType`, `GarageYrBlt`, `GarageFinish`, `GarageQual` e `GarageCond`: **81**.\n\nTemos que lidar com os dados faltando de cada tipo feature individualmente. As abordagens usadas foram:\n\n- **Categ\u00f3ricas**: Olhando as descri\u00e7\u00e3o das features, vemos que, com excep\u00e7\u00e3o da `MasVnrType`, as vari\u00e1veis `NaN` significa a falta da feature. Ent\u00e3o, vamos adicionar uma categoria `None` para os dados faltando, e assumir que os dados faltando na categoria `MasVnrType` seja a aus\u00eancia da feature. Al\u00e9m disso, vamos definir as vari\u00e1veis num\u00e9ricas `MSSubClass`, `OverallQual` e `OverallCond` como categ\u00f3ricas, conforme a sua descri\u00e7\u00e3o.\n\n- **Num\u00e9ricas**: Imputar os valores que fa\u00e7am sentido com o que a vari\u00e1vel representa.\n  - `LotFrontage`: Vamos substituir os valores faltando pela **mediana** da coluna.\n  - `MasVnrArea `: Como assumimos que os valores faltando s\u00e3o aus\u00eancia da feature, substitu\u00edmos por **0**.\n  - `GarageYrBlt`: Como nesses casos n\u00e3o existe garagem, vamos subtitu\u00ed-lo por um valor imposs\u00edvel que lhe d\u00ea destaque, nesse caso **0**.\n\"\"\"\n# Cleaned data\nc_train = train.copy()\n\n# Imput categorical columns\nmiss_cat_cols = ['Alley', 'MasVnrType', 'BsmtQual', 'BsmtCond', 'BsmtExposure',\n                 'BsmtFinType1', 'BsmtFinType2', 'Electrical', 'FireplaceQu',\n                 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond',\n                 'PoolQC', 'Fence', 'MiscFeature']\nc_train[miss_cat_cols] = train[miss_cat_cols].fillna('None')\n\n# Tranform numerical variables in categorical variables\ncat_feat = ['MSSubClass', 'OverallQual', 'OverallCond'] + list(train.select_dtypes('object').columns)\nc_train[cat_feat] = c_train[cat_feat].astype('category')\n\nprint(f\"Empty entries: {c_train[miss_cat_cols].isna().sum().sum()}\")\nc_train[miss_cat_cols].head()\nfrom sklearn.preprocessing import Imputer\n\n# Imput numeric columns\nc_train['LotFrontage'] = train.LotFrontage.fillna(train.LotFrontage.median())\nc_train['MasVnrArea'] = train.MasVnrArea.fillna(0)\nc_train['GarageYrBlt'] = train.GarageYrBlt.fillna(0)\n\nprint(f\"Empty entries: {c_train.isna().sum().sum()}\")\nc_train.head()\n\"\"\"\n## Visualizar os Dados\n\nAgora que s\u00f3 temos dados completos e n\u00e3o duplicados, vamos verificar a consist\u00eancia dos valores das colunas. Para isso, iremos plotar algumas visualiza\u00e7\u00f5es.\n\"\"\"\nc_train.describe()\n\"\"\"\n## Vari\u00e1veis Num\u00e9ricas\n\"\"\"\n# Look at Target variable\nfig, ax = plt.subplots(figsize=(12, 8))\nsns.distplot(c_train.SalePrice, ax=ax)\nc_train.drop('SalePrice', axis=1).hist(bins=40, figsize=(20, 16))\nplt.tight_layout()\n\"\"\"\n## Vari\u00e1veis Categ\u00f3ricas\n\"\"\"\n# Some of the main categorical features\nfig, ax = plt.subplots(figsize=(12,10))\nsns.violinplot(x='OverallQual', y='SalePrice', data=c_train, ax=ax)\n# Some of the main categorical features\nfig, ax = plt.subplots(figsize=(12,10))\nsns.violinplot(x='OverallCond', y='SalePrice', data=c_train, ax=ax)\n# Some of the main categorical features\nfig, ax = plt.subplots(figsize=(12,10))\nsns.violinplot(x='MSSubClass', y='SalePrice', data=c_train, ax=ax)\n\"\"\"\nNesse caso, considerando os dados de fontes confi\u00e1veis, remover outlier pode ser um problema.\n\nIsso fica claro quando verificamos que boa parte dos valores que parecem ser outliers s\u00e3o representados dessa forma devido a n\u00e3o exist\u00eancia da feature mostrado pelo alto pico em 0.\n\n**Assim, n\u00e3o haver\u00e1 a remo\u00e7\u00e3o de outliers.**\n\"\"\"\n\"\"\"\n## Procurar por Correla\u00e7\u00f5es\n\nVerificando as correla\u00e7\u00f5es das vari\u00e1veis com a nossa vari\u00e1vel alvo, podemos tirar conclus\u00f5es sobre as vari\u00e1veis mais **importantes** ou poss\u00edvelmente **redudantes**.\n### Vari\u00e1veis Num\u00e9ricas\n\"\"\"\nnum_corr_matrix = c_train.corr()\nnum_corr_target = num_corr_matrix['SalePrice'].sort_values(ascending=False)\nnum_corr_target.plot.barh(color='steelblue', figsize=(20, 12));\nplt.title('Correlation with Sale Price')\nfig, ax = plt.subplots(figsize=(22, 12))\nsns.heatmap(num_corr_matrix, ax=ax, annot=False, cmap='coolwarm', vmin=-1., vmax=1.)\n\"\"\"\n### Vari\u00e1veis Categ\u00f3ricas\nNese caso, usaremos o [Correlation Ratio](https:\/\/en.wikipedia.org\/wiki\/Correlation_ratio) para criar um valor num\u00e9rico que indique a influ\u00eancia da categoria no nosso valor num\u00e9rico.\n\"\"\"\n# Correlation ratio definition\ndef correlation_ratio(categories, measurements):\n    \"\"\"\n    Calculate the correlation ratio between the categoryes and the measurement\n    \n    Args: \n        categories: Iterable with categories\n        measurements: Iterable with the measurements\n    \n    Return:\n        eta: Correlation ratio\n    \"\"\"\n    fcat, _ = pd.factorize(categories)\n    cat_num = np.max(fcat)+1\n    y_avg_array = np.zeros(cat_num)\n    n_array = np.zeros(cat_num)\n    for i in range(0,cat_num):\n        cat_measures = measurements[np.argwhere(fcat == i).flatten()]\n        n_array[i] = len(cat_measures)\n        y_avg_array[i] = np.average(cat_measures)\n    y_total_avg = np.sum(np.multiply(y_avg_array,n_array))\/np.sum(n_array)\n    numerator = np.sum(np.multiply(n_array,np.power(np.subtract(y_avg_array,y_total_avg),2)))\n    denominator = np.sum(np.power(np.subtract(measurements,y_total_avg),2))\n    if numerator == 0:\n        eta = 0.0\n    else:\n        eta = numerator\/denominator\n    return eta\n# Categorical feature correlated with numeric target\ncat_cols = c_train.select_dtypes('category').columns\ncat_corr_target = pd.Series([correlation_ratio(c_train[c], c_train['SalePrice']) for c in cat_cols], index=cat_cols)\n\ncat_corr_target.sort_values(ascending=False).plot.barh(color='steelblue', figsize=(20, 12));\nplt.title('Correlation with Sale Price')\n\"\"\"\nPodemos perceber algumas coisas:\n- A vari\u00e1vel num\u00e9rica de maior correla\u00e7\u00e3o \u00e9 `GrLivArea`, \u00e1re de habita\u00e7\u00e3o no t\u00e9rreo.\n- A vari\u00e1vel categ\u00f3rica de maior correla\u00e7\u00e3o \u00e9 `OverallQual`, qualidade geral dos materiais e acabamento.\n- Correla\u00e7\u00f5es entre vari\u00e1veis mostrando redund\u00e2ncia, como `GarageCars` e `GarageArea`.\n- Vari\u00e1veis com pouca influ\u00eancia na vari\u00e1vel alvo.\n\nVamos tentar sanar alguns desses problemas no pr\u00f3ximo t\u00f3pico.\n\"\"\"\n\"\"\"\n## Feature Engineering\n\nAqui vamos tentar combinar\/manipular as colunas para que as informa\u00e7\u00f5es presentes nelas e a correla\u00e7\u00e3o com a vari\u00e1vel alvo fiquem o mais claro poss\u00edvel.\n\n\"\"\"\n\"\"\"\n### Sele\u00e7\u00e3o de Features\n\nVendo o **heatmap** anterior podemos perceber que algumas features apresentam pouqu\u00edssima correla\u00e7\u00e3o com as vari\u00e1veis alvo. Adicionalmente, fica claro que algumas possuem uma correla\u00e7\u00e3o muito pr\u00f3xima e acabam sendo informa\u00e7\u00e3o redudante.\n\n- Remover features com correla\u00e7\u00e3o absoluta com a vari\u00e1vel alvo menor que **0.1**.\n- Remover uma das features com correla\u00e7\u00e3o absoluta entre si maior que **0.8**.\n\n\"\"\"\n# Removendo Vari\u00e1veis de baixa correla\u00e7\u00e3o com o alvo\nthres_t = 0.1\nnum_corr_matrix = c_train.corr()\ncols_target = num_corr_matrix['SalePrice'][(num_corr_matrix['SalePrice'] > thres_t) |\n                                           (num_corr_matrix['SalePrice'] < -thres_t)].sort_values(ascending=True).index\ncols_target\nnew_num_corr_matrix = c_train[cols_target].corr()\n# Removing numeric variable highly correlated\nthres_i = 0.8\ncols_corr = {}\nfor c in cols_target:\n    series = new_num_corr_matrix[c].drop(c)\n    if np.any([np.any(series > thres_i), np.any(series < -thres_i)]):\n        cols_corr[c] = series.idxmax()\n# Select just one of the pair with highest correlation\nremove_cols = set([k if new_num_corr_matrix['SalePrice'][k] < new_num_corr_matrix['SalePrice'][v] else v for k, v in cols_corr.items() ])\nn_cols = [c for c in cols_target if c not in remove_cols]\nn_cols\n# Categorical columns\nthres_c = 0.1\nc_cols = [c for c, v in cat_corr_target.iteritems() if v > thres_c]\nc_cols\n# Filters data\nf_cols = c_cols + n_cols\nf_train = c_train[f_cols]\nf_train.head()\n# Check new correlations\nf_num_corr_matrix = f_train[n_cols].corr()\nfig, ax = plt.subplots(figsize=(22, 12))\nsns.heatmap(f_num_corr_matrix, ax=ax, annot=True, cmap='coolwarm', vmin=-1., vmax=1.)\n# Filtered results\nf_cat_corr_target = pd.Series([correlation_ratio(f_train[c], f_train['SalePrice']) for c in c_cols], index=c_cols)\n\nf_cat_corr_target.sort_values(ascending=False).plot.barh(color='steelblue', figsize=(20, 12));\nplt.title('Correlation with Sale Price')\n\"\"\"\n**Assim, com as features filtradas, resta apenas os dados mais relacionados com a nossa vari\u00e1vel alvo.**\n\nVisualizar a vari\u00e1vel alvo com as mais correlacionadas.\n\"\"\"\n# Dynamic plot\nfrom bokeh.plotting import output_file, figure, show\nfrom bokeh.models.tools import HoverTool\nfrom bokeh.io import output_notebook\n\n# Notebook mode\noutput_notebook()\n\n# New sample for manipulated df\nx = f_train['GrLivArea']\ny = f_train['SalePrice']\nTOOLS = \"hover,pan,wheel_zoom,box_zoom,reset,save\"\np = figure(title=\"Ground Living Area X Sale Price\", tools=TOOLS,\n           y_range=(y.min(), y.max()), x_range=(x.min(), x.max()))\n\np.circle('GrLivArea', 'SalePrice', source=f_train)\n# Linear Regression\nslope, intercept = np.polyfit(x, y, 1)\nreg_x = np.linspace(x.min(), x.max())\np.line(reg_x, reg_x*slope+intercept, color='red')\np.xaxis[0].axis_label = 'Square Feet (ft\u00b2)'\np.yaxis[0].axis_label = 'Price ($)'\n\np.hover.tooltips = [\n    # add to this\n    (\"(Ground Living Area, Sale Price)\", \"($x, $y)\"),\n]\nshow(p)\n\n# Check correlation between variables\n# sns.scatterplot(x='distance', y='fare_amount', data=f_train[columns].sample(100000))\n# Generate dynamic boxplot\ny = f_train[\"SalePrice\"].copy()\nx = f_train[\"OverallQual\"].copy()\n# Boxplot of categorical feature\nfig, ax = plt.subplots(figsize=(12, 8))\nsns.boxenplot(x, y, color='steelblue', ax=ax)\nax.set_title(\"Overall Quality x Price\")\n\"\"\"\nDe fato, podemos ver uma clara rela\u00e7\u00e3o enetre as vari\u00e1veis nesse gr\u00e1ficos.\n\"\"\"\n\"\"\"\n# Machine Learning - Cria\u00e7\u00e3o de Modelos\n\n\"\"\"\n\"\"\"\nCom os dados limpos e modificados, podemos prepar\u00e1-los para modelos de ML\/DL. \n\"\"\"\n# Recap of data types\nf_train.info()\n# Recap of data format\nprint(f_train.shape)\nf_train.head()\n\"\"\"\n## Preparando as Vari\u00e1veis para os Modelos\nAgora, vamos manipular as vari\u00e1veis para que elas reflitam corretamente o seu significado no modelo.\n\n1. **Removendo Vari\u00e1veis de Identifica\u00e7\u00e3o**: Nesse caso, isso j\u00e1 foi feito durante o **Feature Engineering**.\n2. **Modificando Vari\u00e1veis Categ\u00f3ricas**: Todas as vari\u00e1veis categ\u00f3ricas devem ser mapeadas usando o t\u00e9cnica de *One-hot encoding*.\n3. **Preparando Vari\u00e1veis C\u00edclicas**: N\u00e3o h\u00e1 veri\u00e1veis c\u00edclicas.\n4. **Ajustando a Magnitude das Vari\u00e1veis Num\u00e9ricas**: Outra etapa muito importante que tem o prop\u00f3sito de ignorar a intensidade absoluta das vari\u00e1veis. Assim, dando \u00eanfase as varia\u00e7\u00f5es relativas.\n5. **Separando a Vari\u00e1vel Alvo**: Nesse caso, iremos separa a vari\u00e1vel `SalePrice` do restante do dataset.\n6. **Dividindo o Dataset em Treino\/Teste**: Usaremos uma propor\u00e7\u00e3o de 80% treino 20% teste.\n\n\"\"\"\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.model_selection import train_test_split\n# Managing categorical variables\ncat_cols = f_train.select_dtypes('category').columns\ndf_dummies = pd.get_dummies(f_train[cat_cols], prefix=cat_cols, drop_first=True)\nX_cat = df_dummies\nX_cat.head()\n# Scaling numeric variables\nscaler = RobustScaler()\nscale_features = list(f_train.select_dtypes(exclude='category').columns)\nscale_features.remove('SalePrice')\nX_num = f_train[scale_features].copy()\nX_num[scale_features] = scaler.fit_transform(f_train[scale_features].values)\nX_num.head()\n# Features and target\nX = pd.concat([X_num, X_cat], axis=1)\ny = f_train['SalePrice']\nX.head()\nprint(X.shape)\nprint(y.shape)\n# Split data\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)\nprint(X_train.shape)\nprint(y_train.shape)\n\"\"\"\n## Testando Modelos\n\nCom os dados prontos para os modelos, podemos test\u00e1-los aplicando v\u00e1rios modelos. Inicialmente, os seguintes modelos foram testados:\n- Regress\u00e3o Linear: Modelo linear simples.\n- \u00c1rvore de Decis\u00e3o: Modelo de \u00e1rvore simples.\n- Random Forest: Conjunto de modelo de \u00e1rvore.\n- Boosting Algorithms: Algoritmos amplamente usados, similar ao random forest, mas com regulariza\u00e7\u00e3o.\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_squared_error\nimport xgboost as xgb\n# SKlearn Models\nlin_reg = LinearRegression()\ntree_reg = DecisionTreeRegressor()\nforest_reg = RandomForestRegressor()\n\n# Scores with x-validation\nlin_scores = cross_val_score(lin_reg, \n                             X_train, \n                             y_train,\n                             scoring = \"neg_mean_squared_error\", \n                             cv = 10)\n\ndecision_scores = cross_val_score(tree_reg,\n                                  X_train, \n                                  y_train,\n                                  scoring = \"neg_mean_squared_error\", \n                                  cv = 10)\n\nforest_scores = cross_val_score(forest_reg,\n                                X_train, \n                                y_train,\n                                scoring = \"neg_mean_squared_error\", \n                                cv = 10)\n# Boost Models\nxgb_reg = xgb.XGBRegressor(n_jobs=12).fit(X_train, y_train)\n\n# Scores with x-validation\nxgb_scores = cross_val_score(xgb_reg, \n                             X_train, \n                             y_train,\n                             scoring = \"neg_mean_squared_error\", \n                             cv = 10)\n# Test Results\nlin_rmse_scores = np.sqrt(-lin_scores)\ndecision_rmse_scores = np.sqrt(-decision_scores)\nforest_rmse_scores = np.sqrt(-forest_scores)\nxgb_rmse_scores = np.sqrt(-xgb_scores)\n# decision_rmse_test = mean_squared_error(y_test, tree_reg.predict(X_test))\n# forest_rmse_test = mean_squared_error(y_test, forest_reg.predict(X_test))\n# xgb_rmse_test = mean_squared_error(y_test, xgb_reg.predict(X_test))\n\n# Results\nprint(\"Linear Regression Results:\")\n# print(f\"Test MSE: {lin_rmse_test:.2f}\")\nprint(f\"CV RMSE: {lin_rmse_scores.mean():.2f} +\/- {lin_rmse_scores.std() * 2:.2f}\\n\")\nprint(\"Decision Tree Regressor Results:\")\n# print(f\"Test MSE: {decision_rmse_test:.2f}\")\nprint(f\"CV RMSE: {decision_rmse_scores.mean():.2f} +\/- {decision_rmse_scores.std() * 2:.2f}\\n\")\nprint(\"Random Forest Regressor Results:\")\n# print(f\"Test MSE: {forest_rmse_test:.2f}\")\nprint(f\"CV RMSE: {forest_rmse_scores.mean():.2f} +\/- {forest_rmse_scores.std() * 2:.2f}\\n\")\nprint(\"X-Gradient Boosting Results:\")\n# print(f\"Test MSE: {xgb_rmse_test:.2f}\")\nprint(f\"CV RMSE: {xgb_rmse_scores.mean():.2f} +\/- {xgb_rmse_scores.std() * 2:.2f}\\n\")\n\"\"\"\n## Sintonizando Hyper-par\u00e2metros\n\nVamos testar v\u00e1rios valores de hyper-parametros para encontrarmos o melhor resultado poss\u00edvel do modelo.\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\ny_train.shape\n# Grid of parameters\nparameters = {'max_depth': [3, 6],\n              'learning_rate': [0.15, 0.75],\n              'n_estimators': [250, 300],\n              }\nfit_parameters = {'early_stopping_rounds':range(4, 12, 2),\n                  'eval_set': (X_test, y_test)\n                  }\ngrid_reg = GridSearchCV(xgb_reg,\n                        parameters,\n                        scoring='neg_mean_squared_error',\n                        cv= 10,\n                        n_jobs=12)\ngrid_reg.fit(X_train, y_train)\nxgb_rmse_test = mean_squared_error(y_test, grid_reg.best_estimator_.predict(X_test))\n\n# Results\nprint(f\"Best Parameters: {grid_reg.best_params_}\")\nprint(f\"Best Mean CV Score: {np.sqrt(-grid_reg.best_score_):.2f}\")\nprint(f\"Test MSE: {np.sqrt(xgb_rmse_test):.2f}\")\n\n\"\"\"\n## Resultados\n\nAqui est\u00e3o os resultados obtidos dos modelos testados.\n\"\"\"\nmodelos = [\"CV Decision Tree Regressor\", \"CV Random Forest Regressor\", \"CV Linear Regression\",\n           \"CV XGBoost Regressor\", \"CV Tunned XGBoost Regressor\"]\nmses = [decision_rmse_scores.mean(), forest_rmse_scores.mean(), lin_rmse_scores.mean(),\n        xgb_rmse_scores.mean(), np.sqrt(-grid_reg.best_score_)]\n\nfig, ax = plt.subplots(figsize=(8, 6))\nax.set_xlabel(\"MSE\")\nax.set_ylabel(\"Model\")\nax.set_title(\"MSE Error - Lower Better\")\nsns.barplot(y=modelos, x=mses, color=\"steelblue\", ax=ax)\n\nafig, ax = plt.subplots(figsize=(16, 16))\nxgb.plot_importance(xgb_reg, height=.5, ax=ax)\n\"\"\"\n## Poss\u00edveis Melhorias\n\n- Utilizar mais dados\n- Continuar procurando melhores hyper-par\u00e2metros\n- Aplicar Deep Learning\n\n\"\"\"\n\"\"\"\n# Save Model\n\nSubmiss\u00e3o no Kaggle compara resultados.\n\"\"\"\n# Save model\nimport pickle\npickle.dump(grid_reg.best_estimator_, open(\"model_house.pt\", \"wb\"))\n# Load model\nimport pickle\nbest_model = pickle.load(open(\"model_house.pt\", \"rb\"))","meta":"{'source': 'AI4Code', 'id': 'cef2ce8299b71c'}"}
{"id":"102868","text":"# 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\n#Load packages\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy.stats import randint\nfrom sklearn.metrics import roc_curve, roc_auc_score, auc\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import confusion_matrix,plot_confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split,cross_val_score,KFold\nfrom sklearn.metrics import classification_report,accuracy_score,precision_score,recall_score,f1_score\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder,StandardScaler,OrdinalEncoder,LabelBinarizer\nfrom sklearn.ensemble import RandomForestClassifier\ndf = pd.read_csv('..\/input\/depression-anxiety-stress-scales\/DASS_data_21.02.19\/data.csv', sep=r'\\t', engine='python')\ndf.head()\nprint(df.shape)\nprint(df.dtypes)\n\"\"\"\n**Extracting the psych questions and storing their answers into a separate dataframe.**\n\"\"\"\n# Extract the columns with just the answers to the first 42 questions\ndf2 = df.loc[:,::3]\ndf3 = df2.iloc[:,0:42]\ndf3.head()\n# Dataframe summary statistics\ndf3.describe()\n# Majority of the people (average value) confessesed that they were anxious\/upset to some extent.\n# Making a correlation plot for df3\nplt.figure(figsize=(16, 16))\nsns.heatmap(df3.corr(), cmap='BuPu')\n\"\"\"\n**Extracting the personality questions and storing their answers into a separate dataframe.**\n\"\"\"\n# Now extracting the dataframe with personality identification questions\nprint(\"Index of TIPI1 column is: \" + str(df.columns.get_loc(\"TIPI1\")))\ndf4 = df.iloc[:,131:141]\ndf4.head()\n\"\"\"\n***About 53% of the participants agree moderately\/strongly that they are anxious\/easily upset!***\n\"\"\"\n# Pie chart to visualize the Anxious\/Easily upset personality type\ndf4['TIPI4'].value_counts().plot(kind='pie', autopct='%1.0f%%')\n# So how can we predict their personality based on the questions they answered earlier?\n\"\"\"\n**Changing the multi-class target variable (TIPI4 - Personality type:Anxiety,Easily Upset) to binary (1:Anxiety, 0:No Anxiety)**\n\"\"\"\n# Setting target and features for basic classfication model\ndf4[\"TIPI4\"] = df4[\"TIPI4\"].replace([5, 4, 3, 2, 1], 0)\ndf4[\"TIPI4\"] = df4[\"TIPI4\"].replace([7, 6], 1)\ntarget = df4[\"TIPI4\"] \nfeatures = df3\n\"\"\"\n**Extracting the participants' background info and storing the responses in a separate dataframe.**\n\"\"\"\nbkgd_features = df.loc[:, [\"education\", \"urban\", \"gender\", \"engnat\", \"age\", \"religion\", \"orientation\",\"race\", \"voted\", \"married\", \"familysize\"]]\nbkgd_features.head()\n# Making a correlation plot for background features - don't see any multicollinearity!\nplt.figure(figsize=(8, 5))\nsns.heatmap(bkgd_features.corr(), cmap='BuPu')\n\"\"\"\n**Merging the background info df with the target variable**\n\"\"\"\nbkgd_table = pd.concat([bkgd_features, target], axis=1)\nbkgd_table.head()\n\"\"\"\n# Analyzing the age column \n\"\"\"\nmean_age_ofAnxiety = bkgd_table.groupby(bkgd_table[\"TIPI4\"] == 1)[\"age\"].mean()\nprint(\"Average age of people w\/ anxiety is \" + str(\"%.2f\" % mean_age_ofAnxiety.iloc[1]) + \" years\")\n# Getting the correlation between the married feature and anxiety\n# printing out categories of education column - some participants entered 0?!\nprint(bkgd_table['married'].unique())\ndata1 = bkgd_table[bkgd_table[\"married\"] > 0]\nprint(data1['married'].unique())\ndf1_crosstab = pd.crosstab(data1[\"TIPI4\"], data1[\"married\"])\ndf1_crosstab.head()\ndf1_crosstab.loc[len(df1_crosstab.index)] = df1_crosstab.iloc[1, :]\/ (df1_crosstab.iloc[0, :] + df1_crosstab.iloc[1, :])\npd.options.display.float_format = \"{:,.2f}\".format\ndf1_new = df1_crosstab.rename(columns={1: 'Never Married',2: 'Currently Married', 3: 'Previously Married'}, index={0: 'No Anxiety', 1: 'Anxiety', 2: '%'})\ndf1_new.head()\n# It's interesting to see that 42% of both currently and previously married people have anxiety issues.\n# Not suprisingly, the # of single people w\/ anxiety is 12% higher than that of currently and previously married people.\n\"\"\"\n# Analyzing the orientation column \n\"\"\"\n# printing out categories of sexual orientation- some participants entered 0?!\ndata2 = bkgd_table[bkgd_table[\"orientation\"] > 0]\ndf2_crosstab = pd.crosstab(data2[\"TIPI4\"], data2[\"orientation\"])\ndf2_crosstab.head()\ndf2_crosstab.loc[len(df2_crosstab.index)] = df2_crosstab.iloc[1, :]\/ (df2_crosstab.iloc[0, :] + df2_crosstab.iloc[1, :])\npd.options.display.float_format = \"{:,.2f}\".format\ndf2_new = df2_crosstab.rename(columns={1: 'He',2: 'Bi', 3: 'Ho', 4: 'A', 5:'Other' }, index={0: 'No Anxiety', 1: 'Anxiety', 2: '%'})\ndf2_new.head()\n# It was interesting to see that 56% of both the homosexual and asexual populations (individually) have anxiety issues. \n# This number is 7% lower for the heterosexual population and 5% higher for the bisexual population.\n\"\"\"\n# Analyzing the race column \n\"\"\"\n# printing out categories of race column - some participants entered 0?!\ndata3 = bkgd_table[bkgd_table[\"race\"] > 0]\ndf3_crosstab = pd.crosstab(data3[\"TIPI4\"], data3[\"race\"])\ndf3_crosstab.head()\ndf3_crosstab.loc[len(df3_crosstab.index)] = df3_crosstab.iloc[1, :]\/ (df3_crosstab.iloc[0, :] + df3_crosstab.iloc[1, :])\npd.options.display.float_format = \"{:,.2f}\".format\ndf3_new = df3_crosstab.rename(columns={10: 'Asian',20: 'Arab', 30: 'Black', 40: 'Indigenous Australian', 50:'Native American', 60:'White', 70:'Other' }, index={0: 'No Anxiety', 1: 'Anxiety', 2: '%'})\ndf3_new.head()\n# About 50% of most racial populations have anxiety issues. This is consistent with the initial pie chart visualization. \n# But interestingly, about 62% of the the Native American population suffer from anxiety issues.\n\"\"\"\n# Analyzing the education column \n\"\"\"\n# printing out categories of education column - some participants entered 0?!\nprint(bkgd_table['education'].unique())\ndata4 = bkgd_table[bkgd_table[\"education\"] > 0]\nprint(data4['education'].unique())\n# getting correlation between education level and anxiety\nEd_level = ['Less than high school','High School','Uni degree','Grad degree']\ndf4_crosstab = pd.crosstab(data4[\"TIPI4\"], data4[\"education\"])\ndf4_crosstab.head()\ndf4_crosstab.loc[len(df4_crosstab.index)] = df4_crosstab.iloc[1, :]\/ (df4_crosstab.iloc[0, :] + df4_crosstab.iloc[1, :])\npd.options.display.float_format = \"{:,.2f}\".format\ndf4_new = df4_crosstab.rename(columns={1: 'Some HS',2: 'HS', 3: 'UG', 4: 'GRAD' }, index={0: 'No Anxiety', 1: 'Anxiety', 2: '%'})\ndf4_new.head()\n# It's not suprising to see that as the education level increases (from Some HS to GRAD degree) the \n# % participants w\/anxiety decreases.\n\"\"\"\n# Building a Random Forest model to predict anxiety w\/ background info and psych questions\n\"\"\"\n\"\"\"\n**Merging the background info df and psych questions df**\n\"\"\"\ndata = pd.concat([df3, bkgd_features, target], axis=1)\n#Drop na observations\ndata_final=data.dropna(how='any')\ndata_final_2 = data_final.loc[~((data_final['education'] == 0) | (data_final['urban'] == 0)|(data_final['gender'] == 0)|(data_final['engnat'] == 0)|(data_final['age'] == 0)|(data_final['religion'] == 0)|(data_final['orientation'] == 0)|(data_final['race'] == 0)|(data_final['voted'] == 0)|(data_final['married'] == 0)|(data_final['familysize'] == 0))]\ndata_final_2.head()\n\n# Normalize the feature columns\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nmin_max_scaler = preprocessing.MinMaxScaler()\nall_features_final = data_final_2.drop(\"TIPI4\", axis = 1)\ntarget_final = data_final_2[\"TIPI4\"]\nX_minmax = min_max_scaler.fit_transform(all_features_final)\nX_train, X_test, y_train, y_test = train_test_split(X_minmax, target_final, test_size=0.2, random_state=42)\n#Define the model\nRFmod = RandomForestClassifier(random_state=1)\n\n#Choose some hyperparameter values \nRFparams={'n_estimators':randint(10,1000),'max_features':['sqrt',None],\n          'max_depth':randint(1,10),'min_samples_leaf':randint(1,10)}\n#Run the random search\nclfRF = RandomizedSearchCV(RFmod,RFparams,#model and parameters\n                             cv=10,#number of cross validation folds\n                             scoring='roc_auc',#accuracy metric\n                             n_iter=1)#number of random parameter combinations\nclfRF.fit(X_train,y_train)\n#Look at the parameters for the best model\nclfRF.best_estimator_\n# Compute the training and testing set ROC curves\nclfpreds_train = clfRF.best_estimator_.predict_proba(X_train).T[1]\nfpr1, tpr1, thresh1 = roc_curve(y_train, clfpreds_train)\nroc_auc_train= roc_auc_score(y_train, clfpreds_train)\n\nclfpreds_test = clfRF.best_estimator_.predict_proba(X_test).T[1]\nfpr2, tpr2, thresh2 = roc_curve(y_test, clfpreds_test)\nroc_auc_test= roc_auc_score(y_test, clfpreds_test)\n\n# Plot the ROC curves\nplt.plot([0, 1], [0, 1], linestyle='--')\nplt.plot(fpr1, tpr1, label='Training set (AUC = %0.2f)' % roc_auc_train)\nplt.plot(fpr2, tpr2, label='Testing set (AUC = %0.2f)' % roc_auc_test)\nplt.xlim([-0.01, 1.0])\nplt.ylim([0.0, 1.01])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend(loc='lower right');\nplt.show()\n\"\"\"\n# Next try out a neural network model!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'bd071509831672'}"}
{"id":"22450","text":"\"\"\"\n**Created by Sanskar Hasija**\n\n**\ud83e\udd16LightAutoML Classification - Titanic**\n\n**15 NOVEMBER 2021**\n\n\"\"\"\n\"\"\"\n# <center> \ud83e\udd16LIGHTAUTOML CLASSIFICATION - TITANIC<\/center>\n## <center>If you find this notebook useful, support with an upvote\ud83d\udc4d<\/center>\n\"\"\"\n\"\"\"\n# Installing LightAutoML\n\"\"\"\nfrom IPython.display import clear_output\n\n!pip install -U lightautoml\nclear_output()\n\"\"\"\n# Imports\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom lightautoml.automl.presets.tabular_presets import TabularUtilizedAutoML\nfrom lightautoml.tasks import Task\nfrom sklearn.metrics import f1_score\n\"\"\"\n# Data Loading and Preprocessing\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntest = pd.read_csv('..\/input\/titanic\/test.csv')\nsubs = pd.read_csv('..\/input\/titanic\/gender_submission.csv')\n\ndrop_elements = ['PassengerId', 'Name', 'Ticket', 'Cabin', 'SibSp','Parch']\ntrain = train.drop(drop_elements, axis = 1)\ntest = test.drop(drop_elements, axis = 1)\n\ndef checkNull_fillData(df):\n    for col in df.columns:\n        if len(df.loc[df[col].isnull() == True]) != 0:\n            if df[col].dtype == \"float64\" or df[col].dtype == \"int64\":\n                df.loc[df[col].isnull() == True,col] = df[col].mean()\n            else:\n                df.loc[df[col].isnull() == True,col] = df[col].mode()[0]\n                \ncheckNull_fillData(train)\ncheckNull_fillData(test)\n\nstr_list = [] \nnum_list = []\nfor colname, colvalue in train.iteritems():\n    if type(colvalue[1]) == str:\n        str_list.append(colname)\n    else:\n        num_list.append(colname)\n        \ntrain = pd.get_dummies(train, columns=str_list)\ntest = pd.get_dummies(test, columns=str_list)\n\"\"\"\n# AutoML\n\"\"\"\nN_THREADS = 4 \nN_FOLDS = 5 \nRANDOM_STATE = 12\nTEST_SIZE = 0.2 \nTIMEOUT = 1800  #30 mins\n\ndef f1_metric(y_true, y_pred, **kwargs):\n    return f1_score(y_true, (y_pred > 0.5).astype(int), **kwargs)\n\ntask = Task('binary', metric = f1_metric)\nroles = {\n    'target': 'Survived',\n}\nautoml = TabularUtilizedAutoML(task = task, \n                       timeout = TIMEOUT,\n                       cpu_limit = N_THREADS,\n                       random_state=RANDOM_STATE,\n                       general_params = {'use_algos': [['linear_l2', 'lgb', 'lgb_tuned']]},\n                       reader_params = {'n_jobs': N_THREADS})\nhistory = automl.fit_predict(train, roles = roles , verbose =1 )\n\"\"\"\n### Submission\n\"\"\"\ntest_pred = automl.predict(test)\nsubs['Survived'] = (test_pred.data[:, 0] > 0.5).astype(int)\nsubs.to_csv('lightautoml.csv', index = False)\nsubs.head()","meta":"{'source': 'AI4Code', 'id': '294ebc78dd1a84'}"}
{"id":"104430","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\ndf_train = pd.read_csv('\/kaggle\/input\/hdfc-2019\/DataSet\/Train.csv')\ndf_test = pd.read_csv('\/kaggle\/input\/hdfc-2019\/DataSet\/Test.csv')\ndf_train.shape, df_test.shape\ndf_train.head()\n\"\"\"\n# Col1 has an unique data & Col2 is Target variable\n\"\"\"\ndf_test.head()\nX = df_train.drop(['Col1','Col2'], axis=1)\ny = df_train.Col2\n\nXTest = df_test.drop(['Col1'], axis=1)\ny.value_counts(normalize=True) * 100\n\"\"\"\n# More information about train and test dataframe\n\"\"\"\nX.info()\nXTest.info()\n\"\"\"\n# Something is fishy:\n> **X** has 2 object type features but **XTest** has 11 object type features\n\n> Ideally X and XTest dataframe should contain features with same datatype.\n\"\"\"\nfor col in X.select_dtypes('object').columns:\n    print(col)\n    print(X[col].unique())\n    print(\"--------------------------------------------------------------------\\n\")\nfor col in XTest.select_dtypes('object').columns:\n    print(col)\n    print(XTest[col].unique())\n    print(\"--------------------------------------------------------------------\\n\")\n\"\"\"\n# Clean the data:\n\n> * We will convert string numerical data to float.\n\n> * We will convert '-' sign to nan\n\n\n\"\"\"\ndef convert_to_float(row):\n    if row == '-':\n        return np.nan\n    else:\n        return float(row)\ncolumns_need_treatment = list(X.select_dtypes('object').columns) + list(XTest.select_dtypes('object').columns)\nprint(len(columns_need_treatment))\nprint(columns_need_treatment)\nfor col in columns_need_treatment:\n    X[col] = X[col].apply(convert_to_float)\n    XTest[col] = XTest[col].apply(convert_to_float)\n\"\"\"\n# Does data contains duplicate rows or features ?\n\n\"\"\"\nduplicate_rows_in_train = X.duplicated()\nduplicate_rows_in_test = XTest.duplicated()\n\nprint(\"Train data contains %d duplicate rows and Test data contains %d duplicate rows.\"%(sum(duplicate_rows_in_train), \n                                                                                             sum(duplicate_rows_in_test)))\ny[duplicate_rows_in_train].value_counts(normalize=True)\ny[duplicate_rows_in_train].head(30)\nX['duplicate_row'] = False\nXTest['duplicate_row'] = False\n\nX.loc[duplicate_rows_in_train, 'duplicate_row'] = True\nXTest.loc[duplicate_rows_in_test, 'duplicate_row'] = True\nfeatures = X.columns\nduplicate_columns = set()\nfor i in range(len(features)):\n    for j in range(i+1, len(features)):\n        if np.all(X[features[i]] == X[features[j]]):\n            print(features[i], features[j])\n            duplicate_columns.add(features[j])\nprint(\"Number of duplicate columns:\",len(duplicate_columns))\nselected_features = [_ for _ in X.columns if _ not in duplicate_columns]\nprint(\"Selected_Features :\",len(selected_features))\nRANDOM_SEED = 1\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.metrics import f1_score\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom hyperopt import STATUS_OK, Trials, fmin, hp, tpe\nfrom sklearn.model_selection import StratifiedKFold\nX_train, X_valid, y_train, y_valid = train_test_split(X[selected_features], y, \n                                                      random_state=RANDOM_SEED, \n                                                      test_size=0.2)\ndef score(params):\n    try:\n\n        print(\"Training with params: \",params)\n        num_round = int(params['n_estimators'])\n        del params['n_estimators']\n        dtrain = xgb.DMatrix(X_train, label=y_train)\n        dvalid = xgb.DMatrix(X_valid, label=y_valid)\n        watchlist = [(dtrain, 'train'),(dvalid, 'eval')]\n        gbm_model = xgb.train(params, dtrain, num_round,\n                              evals=watchlist,\n                              verbose_eval=False)\n        predictions = gbm_model.predict(dvalid,\n                                        ntree_limit=gbm_model.best_iteration + 1)\n        predictions = (predictions >= 0.5).astype('int')\n        score = f1_score(y_valid, predictions, average='weighted')\n        print(\"\\tScore {0}\\n\\n\".format(score))\n        \n        # The score function should return the loss (1-score)\n        # since the optimize function looks for the minimum\n        loss = 1 - score\n        return {'loss': loss, 'status': STATUS_OK}\n   \n    # In case of any exception or assertionerror making score 0, so that It can return maximum loss (ie 1)\n    except AssertionError as obj:\n        #print(\"AssertionError: \",obj)\n        loss = 1 - 0\n        return {'loss': loss, 'status': STATUS_OK}\n\n    except Exception as obj:\n        #print(\"Exception: \",obj)\n        loss = 1 - 0\n        return {'loss': loss, 'status': STATUS_OK}\n\ndef optimize(\n             trials, \n             max_evals, \n             random_state=RANDOM_SEED):\n\n\n    \"\"\"\n    This is the optimization function that given a space (space here) of \n    hyperparameters and a scoring function (score here), finds the best hyperparameters.\n    \"\"\"\n    # To learn more about XGBoost parameters, head to this page: \n    # https:\/\/github.com\/dmlc\/xgboost\/blob\/master\/doc\/parameter.md\n    space = {\n        'n_estimators': hp.quniform('n_estimators', 100, 300, 1),\n        'eta': hp.quniform('eta', 0.025, 0.5, 0.025),\n        # A problem with max_depth casted to float instead of int with\n        # the hp.quniform method.\n        'max_depth':  hp.choice('max_depth', np.arange(1, 7, dtype=int)),\n        'min_child_weight': hp.quniform('min_child_weight', 1, 6, 1),\n        'subsample': hp.quniform('subsample', 0.5, 1, 0.05),\n        'gamma': hp.quniform('gamma', 0, 1, 0.05),\n        'colsample_bytree': hp.quniform('colsample_bytree', 0.5, 1, 0.05),\n        'scale_pos_weight': hp.quniform('scale_pos_weight', 1,4, 0.05),\n        \"reg_alpha\": hp.quniform('reg_alpha', 0, 1, 0.05),\n        \"reg_lambda\": hp.quniform('reg_lambda', 1, 5, 0.05),\n        'eval_metric': 'logloss',\n        'objective': 'binary:logistic',\n        # Increase this number if you have more cores. Otherwise, remove it and it will default \n        # to the maxium number. \n        'nthread': 4,\n        'booster': 'gbtree',\n        'tree_method': 'exact',\n        'silent': 1,\n        'seed': random_state\n    }\n    # Use the fmin function from Hyperopt to find the best hyperparameters\n    best = fmin(score, \n                space, \n                algo=tpe.suggest, \n                trials=trials, \n                max_evals=max_evals)\n    return best\n\ntrials = Trials()\nMAX_EVALS = 25\n\nbest_hyperparams = optimize(trials, MAX_EVALS)\nprint(\"The best hyperparameters are: \", \"\\n\")\nprint(best_hyperparams)\n\"\"\"\n# Best Hyper-parameters\n\"\"\"\nbest_hyperparams\nparam = best_hyperparams\nnum_round = int(param['n_estimators'])\ndel param['n_estimators']\n\"\"\"\n# OOF (Out of Fold Prediciton): \n\n\"\"\"\nnum_splits = 5\nskf = StratifiedKFold(n_splits= num_splits, random_state= RANDOM_SEED, shuffle=True)\ndxtest = xgb.DMatrix(XTest[selected_features])\ny_test_pred = np.zeros((XTest[selected_features].shape[0], 1))\nprint(y_test_pred.shape)\ny_valid_scores = []\n\nX_TRAIN = X[selected_features].copy()\nY_TRAIN = y.copy()\nX_TRAIN = X_TRAIN.reindex()\nY_TRAIN = Y_TRAIN.reindex()\n\nfold_cnt = 1\nfor train_index, test_index in skf.split(X_TRAIN,Y_TRAIN):\n    print(\"FOLD .... \",fold_cnt)\n    fold_cnt += 1\n    \n    print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n    X_train, X_valid = X_TRAIN.iloc[train_index], X_TRAIN.iloc[test_index]\n    y_train, y_valid = Y_TRAIN.iloc[train_index], Y_TRAIN.iloc[test_index]\n    \n    dtrain = xgb.DMatrix(X_train, label=y_train)\n    dvalid = xgb.DMatrix(X_valid, label=y_valid)\n    \n    evallist = [(dtrain, 'train'), (dvalid, 'eval')]\n\n    # Training xgb model\n    bst = xgb.train(param, dtrain, num_round, evallist, verbose_eval=50)\n    \n    # Predict Validation\n    y_pred_valid = bst.predict(dvalid, ntree_limit=bst.best_iteration + 1)\n    y_valid_scores.append(f1_score(y_valid, (y_pred_valid >= 0.5).astype(int), average='weighted'))\n   \n    # Predict Test \n    y_pred = bst.predict(dxtest, ntree_limit=bst.best_iteration+1)\n    \n    y_test_pred += y_pred.reshape(-1,1)\n\n#Normalize test predicted probability\ny_test_pred \/= num_splits\ny_valid_scores\nprint(\"Average validation_score: \",np.mean(y_valid_scores))\noutput = df_test[['Col1']].copy()\noutput['Col2'] = (y_test_pred >= 0.5).astype(int)\noutput.head()\noutput['Col2'].value_counts()\/output.shape[0] * 100\noutput.to_csv(\".\/predict_hdfc_xgb_oof.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': 'bfd9603af41d50'}"}
{"id":"114976","text":"\"\"\"\n# Mushroom Classification using Random Forest Classifier\n___\n\n### Task Details\nPerform Mushroom Classification using Random Forest Classification.\n\n### Evaluation\nThe notebook which gives highest accuracy.\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\ndataset = pd.read_csv(\"..\/input\/mushroom-classification\/mushrooms.csv\")\ndataset.head()\ndataset.shape\nsns.heatmap(dataset.isnull(),yticklabels=False,cbar=False,cmap='viridis')\ncolumns = dataset.columns\ncolumns\nfor i in columns:\n    print(i,\": \",dataset[i].unique())\n\"\"\"\n___\n# Ordinal Encoder\n\nBy using Ordinal Encoder, we can change the data type of an object to numerical.\nBecause of all the dataset is an object, both X and y is transformed by Ordinal Encoder.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import OrdinalEncoder\n\nX = dataset.drop(['class'],axis=1)\ny = dataset['class']\n\ncategorical_cols_X = [cname for cname in X.columns if \n                    X[cname].dtype == \"object\"]\ngood_label_cols = ['class']\n\nlabel_y_train = dataset.drop(categorical_cols_X, axis=1)\nordinal_encoder = OrdinalEncoder()\nlabel_y_train[good_label_cols] = ordinal_encoder.fit_transform(dataset[good_label_cols])\n\nX_train, X_test, y_train, y_test = train_test_split(X,label_y_train,train_size=0.8, test_size=0.2,random_state=0)\n\nlabel_X_train = X_train\nlabel_X_test = X_test\nlabel_X_train[categorical_cols_X] = ordinal_encoder.fit_transform(X_train[categorical_cols_X])\nlabel_X_test[categorical_cols_X] = ordinal_encoder.transform(X_test[categorical_cols_X])\nX_test\ny_train.tail()\nmodel = RandomForestClassifier()\nmodel.fit(label_X_train, y_train)\npreds = model.predict(label_X_test)\nprint(mean_absolute_error(y_test, preds))\ny_test\n# preds = model.predict(label_X_test)\npreds\nresult = pd.DataFrame({'class': preds })\nresult.tail()\nX_test.reset_index(drop=True, inplace=True)\nresult.reset_index(drop=True, inplace=True)\n\nsubmission = pd.concat([result,X_test],axis=1)\nsubmission.head()\nX_test.reset_index(drop=True, inplace=True)\ny_test.reset_index(drop=True, inplace=True)\n\ntesting = pd.concat([y_test,X_test],axis=1)\ntesting.head()\ndataset.head()\nfrom sklearn.metrics import accuracy_score\naccuracy=accuracy_score(y_test,preds)\nprint(\"Random Forest Classifier Accuracy Value: {:.2f}\".format(accuracy))","meta":"{'source': 'AI4Code', 'id': 'd34a3476941ee2'}"}
{"id":"31711","text":"\"\"\"\n# M5 Forecasting Competition GluonTS Template\n\nThis notebook can be used as a starting point for participating in the [M5 forecasting competition](https:\/\/www.kaggle.com\/c\/m5-forecasting-accuracy\/overview) using GluonTS-based tooling.\n\"\"\"\n\"\"\"\n### Standard imports\n\nFirst we import standard data manipulation libraries.\n\"\"\"\n%matplotlib inline\nimport mxnet as mx\nfrom mxnet import gluon\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport os\nfrom tqdm.autonotebook import tqdm\nfrom pathlib import Path\n\n!pip install gluonts\n\"\"\"\nWe also define globally accessible variables, such as the prediction length and the input path for the M5 data. Note that `single_prediction_length` corresponds to the length of the validation\/evaluation periods, while `submission_prediction_length` corresponds to the length of both these periods combined.\n\nBy default the notebook is configured to run in submission mode (`submission` will be `True`), which means that we use all of the data for training and predict new values for a total length of `submission_prediction_length` for which we don't have ground truth values available (performance can be assessed by submitting prediction results to Kaggle). In contrast, setting `submission` to `False` will instead use the last `single_prediction_length`-many values of our training set as validation points (and hence these values will not be used for training), which enables us to validate our model's performance offline.\n\"\"\"\nsingle_prediction_length = 28\nsubmission_prediction_length = single_prediction_length * 2\nm5_input_path=\"..\/input\/m5-forecasting-accuracy\"\nsubmission=True\n\nif submission:\n    prediction_length = submission_prediction_length\nelse:\n    prediction_length = single_prediction_length\n\"\"\"\n### Reading the M5 data into GluonTS\n\nFirst we need to convert the provided M5 data into a format that is readable by GluonTS. At this point we assume that the M5 data, which can be downloaded from Kaggle, is present under `m5_input_path`.\n\"\"\"\ncalendar = pd.read_csv(f'{m5_input_path}\/calendar.csv')\nsales_train_validation = pd.read_csv(f'{m5_input_path}\/sales_train_validation.csv')\nsample_submission = pd.read_csv(f'{m5_input_path}\/sample_submission.csv')\nsell_prices = pd.read_csv(f'{m5_input_path}\/sell_prices.csv')\n\"\"\"\nWe start the data convertion process by building dynamic features (features that change over time, just like the target values). Here, we are mainly interested in the event indicators `event_type_1` and `event_type_2`. We will mostly drop dynamic time features as GluonTS will automatically add some of these as part of many models' transformation chains.\n\"\"\"\ncal_features = calendar.drop(\n    ['date', 'wm_yr_wk', 'weekday', 'wday', 'month', 'year', 'event_name_1', 'event_name_2', 'd'], \n    axis=1\n)\ncal_features['event_type_1'] = cal_features['event_type_1'].apply(lambda x: 0 if str(x)==\"nan\" else 1)\ncal_features['event_type_2'] = cal_features['event_type_2'].apply(lambda x: 0 if str(x)==\"nan\" else 1)\n\ntest_cal_features = cal_features.values.T\nif submission:\n    train_cal_features = test_cal_features[:,:-submission_prediction_length]\nelse:\n    train_cal_features = test_cal_features[:,:-submission_prediction_length-single_prediction_length]\n    test_cal_features = test_cal_features[:,:-submission_prediction_length]\n\ntest_cal_features_list = [test_cal_features] * len(sales_train_validation)\ntrain_cal_features_list = [train_cal_features] * len(sales_train_validation)\n\"\"\"\nWe then go on to build static features (features which are constant and series-specific). Here, we make use of all categorical features that are provided to us as part of the M5 data.\n\"\"\"\nstate_ids = sales_train_validation[\"state_id\"].astype('category').cat.codes.values\nstate_ids_un , state_ids_counts = np.unique(state_ids, return_counts=True)\n\nstore_ids = sales_train_validation[\"store_id\"].astype('category').cat.codes.values\nstore_ids_un , store_ids_counts = np.unique(store_ids, return_counts=True)\n\ncat_ids = sales_train_validation[\"cat_id\"].astype('category').cat.codes.values\ncat_ids_un , cat_ids_counts = np.unique(cat_ids, return_counts=True)\n\ndept_ids = sales_train_validation[\"dept_id\"].astype('category').cat.codes.values\ndept_ids_un , dept_ids_counts = np.unique(dept_ids, return_counts=True)\n\nitem_ids = sales_train_validation[\"item_id\"].astype('category').cat.codes.values\nitem_ids_un , item_ids_counts = np.unique(item_ids, return_counts=True)\n\nstat_cat_list = [item_ids, dept_ids, cat_ids, store_ids, state_ids]\n\nstat_cat = np.concatenate(stat_cat_list)\nstat_cat = stat_cat.reshape(len(stat_cat_list), len(item_ids)).T\n\nstat_cat_cardinalities = [len(item_ids_un), len(dept_ids_un), len(cat_ids_un), len(store_ids_un), len(state_ids_un)]\n\"\"\"\nFinally, we can build both the training and the testing set from target values and both static and dynamic features.\n\"\"\"\nfrom gluonts.dataset.common import load_datasets, ListDataset\nfrom gluonts.dataset.field_names import FieldName\n\ntrain_df = sales_train_validation.drop([\"id\",\"item_id\",\"dept_id\",\"cat_id\",\"store_id\",\"state_id\"], axis=1)\ntrain_target_values = train_df.values\n\nif submission == True:\n    test_target_values = [np.append(ts, np.ones(submission_prediction_length) * np.nan) for ts in train_df.values]\nelse:\n    test_target_values = train_target_values.copy()\n    train_target_values = [ts[:-single_prediction_length] for ts in train_df.values]\n\nm5_dates = [pd.Timestamp(\"2011-01-29\", freq='1D') for _ in range(len(sales_train_validation))]\n\ntrain_ds = ListDataset([\n    {\n        FieldName.TARGET: target,\n        FieldName.START: start,\n        FieldName.FEAT_DYNAMIC_REAL: fdr,\n        FieldName.FEAT_STATIC_CAT: fsc\n    }\n    for (target, start, fdr, fsc) in zip(train_target_values,\n                                         m5_dates,\n                                         train_cal_features_list,\n                                         stat_cat)\n], freq=\"D\")\n\ntest_ds = ListDataset([\n    {\n        FieldName.TARGET: target,\n        FieldName.START: start,\n        FieldName.FEAT_DYNAMIC_REAL: fdr,\n        FieldName.FEAT_STATIC_CAT: fsc\n    }\n    for (target, start, fdr, fsc) in zip(test_target_values,\n                                         m5_dates,\n                                         test_cal_features_list,\n                                         stat_cat)\n], freq=\"D\")\n\"\"\"\nJust to be sure, we quickly verify that dataset format is correct and that our dataset does indeed contain the correct target values as well as dynamic and static features.\n\"\"\"\nnext(iter(train_ds))\n\"\"\"\n### Define the estimator\n\nHaving obtained our training and testing data, we can now create a GluonTS estimator. In our example we will use the `DeepAREstimator`, an autoregressive RNN which was developed primarily for the purpose of time series forecasting. Note however that you can use a variety of different estimators. Also, since GluonTS is mainly target at probabilistic time series forecasting, lots of different output distributions can be specified. In the M5 case, we think that the `NegativeBinomialOutput` distribution best describes the output.\n\nFor a full list of available estimators and possible initialization arguments see https:\/\/gluon-ts.mxnet.io\/api\/gluonts\/gluonts.model.html.\n\nFor a full list of available output distributions and possible initialization arguments see https:\/\/gluon-ts.mxnet.io\/api\/gluonts\/gluonts.distribution.html.\n\"\"\"\nfrom gluonts.model.deepar import DeepAREstimator\nfrom gluonts.distribution.neg_binomial import NegativeBinomialOutput\nfrom gluonts.trainer import Trainer\n\nestimator = DeepAREstimator(\n    prediction_length=prediction_length,\n    freq=\"D\",\n    distr_output = NegativeBinomialOutput(),\n    use_feat_dynamic_real=True,\n    use_feat_static_cat=True,\n    cardinality=stat_cat_cardinalities,\n    trainer=Trainer(\n        learning_rate=1e-3,\n        epochs=100,\n        num_batches_per_epoch=50,\n        batch_size=32\n    )\n)\n\npredictor = estimator.train(train_ds)\n\"\"\"\n### Generating forecasts\n\nOnce the estimator is fully trained, we can generate predictions from it for the test values.\n\"\"\"\nfrom gluonts.evaluation.backtest import make_evaluation_predictions\n\nforecast_it, ts_it = make_evaluation_predictions(\n    dataset=test_ds,\n    predictor=predictor,\n    num_samples=100\n)\n\nprint(\"Obtaining time series conditioning values ...\")\ntss = list(tqdm(ts_it, total=len(test_ds)))\nprint(\"Obtaining time series predictions ...\")\nforecasts = list(tqdm(forecast_it, total=len(test_ds)))\n\"\"\"\n### Local performance validation (if `submission` is `False`)\n\nSince we don't want to constantly submit our results to Kaggle, it is important to being able to evaluate performace on our own validation set offline. To do so, we create a custom evaluator which, in addition to GluonTS's standard performance metrics, also returns `MRMSSE` (corresponding to the mean RMSSE). Note that the official score for the M5 competition, the `WRMSSE`, is not yet computed. A future version of this notebook will replace the `MRMSSE` by the `WRMSSE`.\n\"\"\"\nif submission == False:\n    \n    from gluonts.evaluation import Evaluator\n    \n    class M5Evaluator(Evaluator):\n        \n        def get_metrics_per_ts(self, time_series, forecast):\n            successive_diff = np.diff(time_series.values.reshape(len(time_series)))\n            successive_diff = successive_diff ** 2\n            successive_diff = successive_diff[:-prediction_length]\n            denom = np.mean(successive_diff)\n            pred_values = forecast.samples.mean(axis=0)\n            true_values = time_series.values.reshape(len(time_series))[-prediction_length:]\n            num = np.mean((pred_values - true_values)**2)\n            rmsse = num \/ denom\n            metrics = super().get_metrics_per_ts(time_series, forecast)\n            metrics[\"RMSSE\"] = rmsse\n            return metrics\n        \n        def get_aggregate_metrics(self, metric_per_ts):\n            wrmsse = metric_per_ts[\"RMSSE\"].mean()\n            agg_metric , _ = super().get_aggregate_metrics(metric_per_ts)\n            agg_metric[\"MRMSSE\"] = wrmsse\n            return agg_metric, metric_per_ts\n        \n    \n    evaluator = M5Evaluator(quantiles=[0.5, 0.67, 0.95, 0.99])\n    agg_metrics, item_metrics = evaluator(iter(tss), iter(forecasts), num_series=len(test_ds))\n    print(json.dumps(agg_metrics, indent=4))\n\"\"\"\n### Converting forecasts back to M5 submission format (if `submission` is `True`)\n\nSince GluonTS estimators return a sample-based probabilistic forecasting predictor, we first need to reduce these results to a single prediction per time series. This can be done by computing the mean or median over the predicted sample paths.\n\"\"\"\nif submission == True:\n    forecasts_acc = np.zeros((len(forecasts), prediction_length))\n    for i in range(len(forecasts)):\n        forecasts_acc[i] = np.mean(forecasts[i].samples, axis=0)\n\"\"\"\nWe then reshape the forecasts into the correct data shape for submission ...\n\"\"\"\nif submission == True:\n    forecasts_acc_sub = np.zeros((len(forecasts)*2, single_prediction_length))\n    forecasts_acc_sub[:len(forecasts)] = forecasts_acc[:,:single_prediction_length]\n    forecasts_acc_sub[len(forecasts):] = forecasts_acc[:,single_prediction_length:]\n\"\"\"\n.. and verfiy that reshaping is consistent.\n\"\"\"\nif submission == True:\n    np.all(np.equal(forecasts_acc[0], np.append(forecasts_acc_sub[0], forecasts_acc_sub[30490])))\n\"\"\"\nThen, we save our submission into a timestamped CSV file which can subsequently be uploaded to Kaggle.\n\"\"\"\nif submission == True:\n    import time\n\n    sample_submission = pd.read_csv(f'{m5_input_path}\/sample_submission.csv')\n    sample_submission.iloc[:,1:] = forecasts_acc_sub\n\n    submission_id = 'submission_{}.csv'.format(int(time.time()))\n\n    sample_submission.to_csv(submission_id, index=False)\n\"\"\"\n### Plotting sample predictions\n\nFinally, we can also visualize our predictions for some of the time series.\n\"\"\"\nplot_log_path = \".\/plots\/\"\ndirectory = os.path.dirname(plot_log_path)\nif not os.path.exists(directory):\n    os.makedirs(directory)\n    \ndef plot_prob_forecasts(ts_entry, forecast_entry, path, sample_id, inline=True):\n    plot_length = 150\n    prediction_intervals = (50, 67, 95, 99)\n    legend = [\"observations\", \"median prediction\"] + [f\"{k}% prediction interval\" for k in prediction_intervals][::-1]\n\n    _, ax = plt.subplots(1, 1, figsize=(10, 7))\n    ts_entry[-plot_length:].plot(ax=ax)\n    forecast_entry.plot(prediction_intervals=prediction_intervals, color='g')\n    ax.axvline(ts_entry.index[-prediction_length], color='r')\n    plt.legend(legend, loc=\"upper left\")\n    if inline:\n        plt.show()\n        plt.clf()\n    else:\n        plt.savefig('{}forecast_{}.pdf'.format(path, sample_id))\n        plt.close()\n\nprint(\"Plotting time series predictions ...\")\nfor i in tqdm(range(5)):\n    ts_entry = tss[i]\n    forecast_entry = forecasts[i]\n    plot_prob_forecasts(ts_entry, forecast_entry, plot_log_path, i)","meta":"{'source': 'AI4Code', 'id': '3a60dac4c33836'}"}
{"id":"29772","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nimport plotly.express as px\n\ndata = pd.read_csv('..\/input\/suicide-rates-overview-1985-to-2016\/master.csv')\ndata['HDI for year'] = data['HDI for year'].fillna(0)\n\"\"\"\n# Which country had most number of suicides? -> Russian Federation\n\"\"\"\ncountry = data.loc[:,['country','suicides_no']]\ncountry = country.groupby('country')['suicides_no'].sum().reset_index()\ncountry = country.sort_values('suicides_no')\ncountry = country.tail(10)\nfig = px.pie(country, names='country', values='suicides_no', template='seaborn')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Which country had least number of suicides?-> Saint Kitts and Nevis\n\"\"\"\ncountry = data.loc[:,['country','suicides_no']]\ncountry = country.groupby('country')['suicides_no'].sum().reset_index()\ncountry = country.sort_values('suicides_no')\ncountry = country.head(10)\nfig = px.pie(country, names='country', values='suicides_no', template='seaborn')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Per year suicides in top 5 countries\n\"\"\"\nperc = data.loc[:,[\"year\",\"country\",'suicides_no']]\nperc['total_suicides'] = perc.groupby([perc.country,perc.year])['suicides_no'].transform('sum')\nperc.drop('suicides_no', axis=1, inplace=True)\nperc = perc.drop_duplicates()\nperc = perc[(perc['year']>=1990.0) & (perc['year']<=2012.0)]\nperc = perc.sort_values(\"year\",ascending = False)\n\ntop_countries = ['Russian Federation','United States','Japan','France',\"Ukraine\"] \nperc = perc.loc[perc['country'].isin(top_countries)]\nperc = perc.sort_values(\"year\")\nfig=px.bar(perc,x='country', y=\"total_suicides\", animation_frame=\"year\", \n           animation_group=\"country\", color=\"country\", hover_name=\"country\")\nfig.show()\n\"\"\"\n# People of which sex commit more suicide?---> Male\n\"\"\"\nsex = data.loc[:,['year','sex','suicides_no']]\nsex['total_suicides'] = sex.groupby(['year','sex'])['suicides_no'].transform('sum')\nsex.drop('suicides_no', axis=1, inplace=True)\nsex = sex.drop_duplicates()\nsex = sex[sex['year']>=2000.0]\nsex = sex.sort_values(\"year\")\nfig=px.bar(sex,x='sex', y=\"total_suicides\", animation_frame=\"year\", \n           animation_group=\"sex\", color=\"sex\", hover_name=\"sex\")\nfig.show()\n\"\"\"\nNow that's a considerable amount of difference but I think there is an ambiguity since male population may be higher, so let's consider the suicides\/100k pop col rather than total count\n\"\"\"\nsex = data.loc[:,['year','sex','suicides\/100k pop']]\nsex['total_suicides'] = sex.groupby(['year','sex'])['suicides\/100k pop'].transform('sum')\nsex.drop('suicides\/100k pop', axis=1, inplace=True)\nsex = sex.drop_duplicates()\nsex = sex[sex['year']>=2000.0]\nsex = sex.sort_values(\"year\")\nfig=px.bar(sex,x='sex', y=\"total_suicides\", animation_frame=\"year\", \n           animation_group=\"sex\", color=\"sex\", hover_name=\"sex\")\nfig.show()\n\"\"\"\nSo there was no ambiguity and the rate of suicides in male is much higher than females.\n\"\"\"\n\"\"\"\n# Year wise change in number of suicides\n\"\"\"\nyear = data.loc[:,['year','suicides_no']]\nyear['total_suicides'] = year.groupby('year')['suicides_no'].transform('sum')\nyear.drop('suicides_no', axis=1, inplace=True)\nyear = year.drop_duplicates()\nsns.lineplot(data=year, x='year', y='total_suicides')\n\"\"\"\n# People of which Age group commit more suicide? --> 35-54 years\n\"\"\"\nage = data.loc[:,['year','age','suicides_no']]\nage['total_suicides'] = age.groupby(['year','age'])['suicides_no'].transform('sum')\nage.drop('suicides_no', axis=1, inplace=True)\nage = age.drop_duplicates()\nage = age[age['year']>=2000.0]\nage = age.sort_values(\"year\")\nfig=px.bar(age,x='age', y=\"total_suicides\", animation_frame=\"year\", \n           animation_group=\"age\", color=\"age\", hover_name=\"age\")\nfig.show()\n\"\"\"\n# Relation between number of suicides and population\n\"\"\"\nsns.scatterplot(data=data, x='suicides_no', y='population')\nplt.title('Number of Suicides vs Population')\n\"\"\"\n# Relation of total number of suicides and HDI per year for top 5 countries\n\"\"\"\nhdi = data.loc[:,['country','year','suicides_no','HDI for year']]\nhdi['total_suicides'] = hdi.groupby('year')['suicides_no'].transform('sum')\nhdi.drop('suicides_no', axis=1, inplace=True)\n\nhdi['ratio'] = hdi['HDI for year']\/hdi['total_suicides']\ntop_countries = ['Russian Federation','United States','Japan','France',\"Ukraine\"] \nhdi = hdi.loc[hdi['country'].isin(top_countries)]\nhdi = hdi.drop_duplicates()\nhdi = hdi[hdi['year']>=2000]\nfor country in top_countries:\n    df = hdi[hdi['country']==country]\n    sns.lineplot(data=df, x='year', y='ratio')\n\"\"\"\nThis isn't making any sense. But my knowledge is stuck at this pint. I am not sure which plot to use to understand this in more depth. I will update it once I find out.\n\"\"\"\n\"\"\"\n# Relation of change in GDP to number of suicides\n\"\"\"\n#lets do for russia at first\nrussia = data[data['country']=='Russian Federation'].copy()\ngdp = russia.iloc[:,[1,4,9]].copy()\ngdp['total_suicides'] = gdp.groupby('year')['suicides_no'].transform('sum')\ngdp.drop('suicides_no', axis=1, inplace=True)\ngdp = gdp.drop_duplicates()\nfig = plt.figure(figsize=(20,7))\nax = fig.add_subplot(1,2,1)\nax.plot(gdp['year'], gdp.iloc[:,1])\nax.set_title('GDP per Year')\nax1 = fig.add_subplot(1,2,2)\nax1.plot(gdp['year'], gdp['total_suicides'])\nax1.set_title('Total numbe of Suicides per year')\n\"\"\"\n# Which generation commits more suicide? --> Boomers\n\n1. The Greatest Generation (or GI Generation) -> Born in 1924 or earlier\n2. The Silent Generation -> Born 1925-1945 (Sometimes listed as 1925-1942)\n3. Baby Boomers -> Born 1946-1964 (Sometimes listed as 1943-1964)\n4. Generation X -> Born 1965-1980 (Sometimes listed as 1965-1979)\n5. Millennials -> Born 1981-1996 (Sometimes listed as 1980-2000)\n6. Generation Z or Gen Z -> Born 1997-current\n\"\"\"\ngen = data.loc[:,['suicides_no','generation']]\ngen['mean'] = gen.groupby('generation')['suicides_no'].transform('sum')\ngen.drop('suicides_no', axis=1, inplace=True)\ngen = gen.drop_duplicates()\n\n\nfig = px.pie(gen, names='generation', values='mean', template='seaborn')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\nNow there is some ambiguity because GenZ population is not yet as much as other generations. \n\nSo to generalise that let's take the mean values.\n\"\"\"\ngen = data.loc[:,['suicides_no','generation']]\ngen['mean'] = gen.groupby('generation')['suicides_no'].transform('mean')\ngen.drop('suicides_no', axis=1, inplace=True)\ngen = gen.drop_duplicates()\n\n\nfig = px.pie(gen, names='generation', values='mean', template='seaborn')\nfig.update_traces(rotation=90, pull=0.05, textinfo=\"percent+label\")\nfig.show()\n\"\"\"\n# Relation between number of suicides and gdp_per_year\n\"\"\"\nfig = plt.figure(figsize=(20,7))\nsns.scatterplot(data=data, x=' gdp_for_year ($) ', y='suicides_no')\n\"\"\"\n# Relation between number of suicides and gdp_per_capita\n\"\"\"\nfig = plt.figure(figsize=(20,7))\nsns.scatterplot(data=data, x='gdp_per_capita ($)', y='suicides_no')\n\"\"\"\n# Relation between suicides_no and suicides\/100k pop\n\"\"\"\nfig = plt.figure(figsize=(20,7))\nsns.scatterplot(data=data, x='suicides_no', y='suicides\/100k pop')\nplt.title('Number of suicides vs for 100k population')\n\"\"\"\nI will end my interview with the dataset here. Will continue if I have some new questions.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '36b0e55c853928'}"}
{"id":"35871","text":"\"\"\"\n<h1>Background<\/h1>\n<p>We are going to explore some graduate admissions data for Post-Graduate Acceptance Probablilities based upon the following features:<ol>\n    <li>GRE Scores<\/li>\n    <li>TOEFL Scores<\/li>\n    <li>Undergraduate School Rating<\/li>\n    <li>Application Letter (SOP)<\/li>\n    <li>Letters of Recommendation(LOR)<\/li>\n    <li>Undergraduate GPA (CGPA)<\/li>\n    <li> Undergraduate Research<\/li>\n<\/ol>\n<\/p>\n\"\"\"\n# 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 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\ndf = pd.read_csv('\/kaggle\/input\/graduate-admissions\/Admission_Predict.csv')\n\"\"\"\n<h1>Data Exploration<\/h1>\n\"\"\"\ndf.head()\n\"\"\"\nNow to drop some of unnecessary info. We can refer to the in-built indexing rather than using the provided Serial No. Makes calling data much simpler.\n\"\"\"\ndf.drop(columns='Serial No.', inplace=True)\ndf.head()\n\"\"\"\nStarting to look better already\n\"\"\"\ndf.columns = ['GRE','TOEFL','Rating','SOP','LOR','CGPA','Research','Chance']\n\"\"\"\nNow let's rename those columns for ease of referencing.\n\"\"\"\ndf.head()\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\ndf.describe()\n\"\"\"\nLet's take a look for any missing values that may require imputing.\n\"\"\"\ndf.isnull().sum()\n\"\"\"\nWow did we luck out! Clean looking so far.\n\"\"\"\nplt.figure(figsize=(8,8))\nsns.heatmap(df.corr(), annot=True, cmap='Blues')\n\"\"\"\n<h1>Correlation<\/h1>\n<p>Taking a look at our correlation matrix, let's see some of the largest relators to Chance:<\/p>\n<ul>\n    <li>CGPA<\/li>\n    <li>GRE<\/li>\n    <li>TOEFL<\/li>\n    <\/ul>\n   \n\"\"\"\nf,(ax1,ax2) = plt.subplots(1,2, figsize=(20,5))\nax1.set_title(\"Admission Chance vs GRE Score\")\nax2.set_title(\"Admission Chance vs TOEFL Score\")\nsns.regplot(x=df.GRE, y=df.Chance, ax=ax1)\nsns.regplot(x=df.TOEFL, y=df.Chance, ax=ax2)\n\nf,(ax1,ax2) = plt.subplots(1,2, figsize=(20,5))\nax1.set_title(\"Admission Chance vs GRE (Research)\")\nax2.set_title(\"Admission Chance vs TOEFL (Research)\")\nsns.scatterplot(x=df.GRE, y=df.Chance, hue=df.Research, ax=ax1)\nsns.scatterplot(x=df.TOEFL, y=df.Chance, hue=df.Research, ax=ax2)\nsns.lmplot(x='GRE', y='Chance', hue='Research', data=df)\nplt.title(\"Admission Chance vs GRE Score (Research)\")\nsns.lmplot(x='TOEFL', y='Chance', hue='Research', data=df)\nplt.title(\"Admission Chance vs TOEFL Score (Research)\")\nsns.lmplot(x='CGPA', y='Chance', hue='Research', data=df)\nplt.title(\"Admission Chance vs CGPA\")\nf,(ax1,ax2,ax3) = plt.subplots(1,3, figsize=(20,5))\nax1.set_title(\"Admission Chance vs LOR\")\nax2.set_title(\"Admission Chance vs SOP\")\nax3.set_title(\"Admission Chance vs School Rating\")\nsns.scatterplot(x=df.LOR, y=df.Chance,ax=ax1)\nsns.scatterplot(x=df.SOP, y=df.Chance,ax=ax2)\nsns.scatterplot(x=df.Rating, y=df.Chance, ax=ax3)\n\n\"\"\"\nCertainly a point can be made for a positive trend for increases in LOR, SOP, and Rating scores. However, for the sake of developing a quick and simple initial Linear Regression Model, let's emit these for the initial run and see what happens!\n\"\"\"\n\"\"\"\n<p>Let's unpack some of the visuals that were just presented:<\/p>\n<ul>\n    <li>A visually apparent linear relationship between CGPA, GRE, and TOEFL with Acceptance Chance<\/li>\n    <li>A higher Chance based on research in conjunction with GRE and TOEFL scores<\/li>\n<\/ul>\n<p>Certainly a point can be made for a positive trend for increases in LOR, SOP, and Rating scores. However, for the sake of developing a quick and simple initial Linear Regression Model, let's emit these for the initial run and see what happens!<\/p>\n\"\"\"\nfeatures=['GRE','TOEFL','CGPA','Research']\nX=df[features]\ny=df['Chance']\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_squared_error\nscaler = StandardScaler()\nscaler.fit(X)\nX_scaled = scaler.transform(X)\nX_train,X_test,y_train,y_test = train_test_split(X_scaled,y,test_size=0.25, random_state=0)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n\"\"\"\n<p>Now we have our data scaled and split into the appropriate training and testing sets. Now it's time to develop our Linear Regression Model<\/p>\n\"\"\"\nlr = LinearRegression()\nlr.fit(X_train,y_train)\ny_hat=lr.predict(X_test)\nprint(\"R2: \",lr.score(X_test,y_test))\nprint(\"RMSE: \",np.sqrt(mean_squared_error(y_test,y_hat)))\n\"\"\"\n<h1>Conclusion<\/h1>\n<p>Using some quick feature selection and evaluation, we came up with a linear model using only 4 features (GRE, TOEFL, CGPA, and Research) to produce an effective first attempt model. This should always be a good starting point. Produce something, evaluate, and iterate!<\/p>\n\n<p>Please provide feedback and insight below. Always looking to improve!<\/p>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4218d1bb68d66e'}"}
{"id":"96048","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings \nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n# High Level Statistics:\n\n---\n\n\n\n\"\"\"\nhaberman = pd.read_csv('..\/input\/haberman.csv\/haberman.csv')\nhaberman\nhaberman.head()\n\n# Col1=age of patient during operation, col2=year of operation, col3=number of positive axillary nodes detected, col4=survival status\n# Survival status 1= the patient survived 5 years or longer , 2= the patient died within 5 years\nprint(haberman.shape) \n\n# Rows = 306 columns = 4\nhaberman.head(2)  \n\n# Prints the first 2 datasets\nhaberman.tail(3)     \n\n# Prints the last 3 datasets\nprint(haberman.columns)      \n\n# Prints all the columns present in the datas\nhaberman['status'].value_counts()     \n\n# It counts the number of unique values, that a particular column is having\n\n# In status column there are 225 patients who lived more than 5 years and 81 patients who died within 5 years\nprint(haberman.info())\n\n# There are no missing value in the data\n\n# All the data types are of type integer\n   \nhaberman.describe()\n\n# There are patients with age group 30 to 83 with a median age of 52 and with standard deviation of 10.803452\n\"\"\"\n# Univariate analysis :\n\n---\n\n\n\"\"\"\nsns.set_style('whitegrid')\nn=sns.FacetGrid(haberman, hue='status', size=4)\nn.map(sns.distplot, 'year')\nn.add_legend()\nplt.show()\n# Patients who had their operations in 1965 died quickly than other patients .\nsns.set_style('whitegrid')\nl=sns.FacetGrid(haberman, hue='status', size=4)\nl.map(sns.distplot, 'age')\nl.add_legend()\n# From below plot we can conclude that patients with age group 40 to 60 died most\n\n# Patients with age group ~55 , survived most\n\n# Patients less than age 40 are more likely to survive as the overlap of data is very less\nsns.set_style('whitegrid')\na=sns.FacetGrid(haberman, hue='status', size=6 ) \na.map(sns.distplot, 'nodes') \na.add_legend()\nplt.show()\n\n# x axis = nodes , y axis = counts i.e number of nodes\n# Patients with 0 and 1 node are more likely to survive more than the patients with nodes more than that.\nsns.kdeplot(data = haberman, x=\"nodes\")\nplt.title('Nodes vs Density plot')\nplt.show()\n\n# It gives the probability density for a given amount of nodes in a patient\nsns.ecdfplot(data=haberman, x='age')\nplt.title('CDF of age')\nplt.show()\n\n# It gives the CDF for a given age group\n# e.g : patients with age group < = 50 is 40%\nsns.ecdfplot( data = haberman )\nplt.title('CDF of all features')\nplt.show()\n\n# This plot shows all the CDF of all the given features.\n\"\"\"\n# Bivariate Analysis :\n\n---\n\n\n\"\"\"\nsns.pairplot(data = haberman , hue = 'status')\nplt.show()\n# Pair plot takes all the possible combination of pairs and plots it\n# We can observe that patients with more nodes died within 5 years from (age vs nodes) plot\nsns.pairplot(data = haberman , hue = 'status' , diag_kind='hist') \nplt.show()\n\n# Here the diagonal plots are histogram as we have mentioned in (diag_kind = 'hist')\nsns.pairplot(data = haberman , kind = 'kde' )\nplt.show()\n\n# As the number of nodes increases the contour goes away from the survival status 1 in (status vs nodes) plot\n# Other plots are not making much sense\nsns.set(style='whitegrid')\nsns.scatterplot(x='age' , y='nodes' , hue = 'status' , data=haberman ) \nplt.title('Age vs Nodes plot')\nplt.show\n# It seems that patients who died were having more nodes\nsns.set(style='whitegrid')\nsns.scatterplot(x='age' , y='nodes' , hue = 'year' , data=haberman , size = 'nodes').set_title('Age vs Nodes with year as hue')\nplt.show()\n# Size parameter increases the size of the dots in ascending order \nimport seaborn as sns\nsns.set_theme(style=\"whitegrid\")\nsns.barplot(x='status' , y='nodes' , data=haberman )\nplt.title('Status vs Nodes barplot')\nplt.show()\n# Patients having more nodes died more, within 5 years\nsns.lineplot( x = 'age' , y = 'nodes' , data=haberman)\nplt.title('Age vs Nodes lineplot')\nplt.show()\n# It shows ~55 age group patients are having highest amount of nodes\n\nsns.lineplot( y = 'nodes' , x = 'year' , hue = 'status' , palette= 'vlag' , data=haberman)\nplt.title('Year vs Nodes lineplot with status as hue')\nplt.show()\n\n# In 1962 and 1960 the death was higher , patients having more nodes\n\n# In 1964 the death was lowest with patients having lesser nodes\nsns.lineplot( x = 'age' , y = 'nodes' , hue = 'status' , palette= 'vlag' , data=haberman)\nplt.title('Age vs Nodes lineplot with status as hue')\nplt.show()\n\n# It shows ~58 age group patients are having more nodes and died within 5 years \n# We can conclude that patients with more nodes died quicker than patients with less nodes\nsns.boxplot( x = 'status' , y = 'age' , data = haberman)\nplt.title('Status vs age boxplot')\nplt.show()\n\n# The patients who died and who survived more than 5 years , their age are nearly same i.e ~53 and ~52 respectively\n# So this plot doesnt make much sense as there is over lapping of data is more than ~ 96%\nsns.boxplot( x = 'status' , y = 'nodes' , data = haberman)\nplt.title('Status vs Nodes boxplot')\nplt.show()\n# Patients who survived had less nodes and median is almost 0 but in case of ptients who died median nodes were ~3 and upto ~12\n# So number of nodes can be taken as a feature to analyze\nsns.violinplot( x = 'status' , y = 'nodes' , data = haberman )\nplt.title('Age vs Nodes violinplot')\nplt.show()\n\n# Patients who survived more than 5 years had almost 0 nodes but in case of patients who died within 5 years were having almost ~3 nodes\n\"\"\"\nConclusion:\n\n\n---\n\n\nFrom above plots we can conclude that the number of nodes is the most important feature in the breast cancer diagnosis.\nAs the number of nodes increases the patient is more likely to die.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b061817c64ac5f'}"}
{"id":"109058","text":"\"\"\"\n## HTF does Topic Modelling Work?\n\n[WIKIPEDIA](https:\/\/en.wikipedia.org\/wiki\/Topic_model) In machine learning and natural language processing, a topic model is a type of statistical model for discovering the abstract \"topics\" that occur in a collection of documents. Topic modeling is a frequently used text-mining tool for discovery of hidden semantic structures in a text body. Intuitively, given that a document is about a particular topic, one would expect particular words to appear in the document more or less frequently: \"dog\" and \"bone\" will appear more often in documents about dogs, \"cat\" and \"meow\" will appear in documents about cats, and \"the\" and \"is\" will appear approximately equally in both. A document typically concerns multiple topics in different proportions; thus, in a document that is 10% about cats and 90% about dogs, there would probably be about 9 times more dog words than cat words. The \"topics\" produced by topic modeling techniques are clusters of similar words. A topic model captures this intuition in a mathematical framework, which allows examining a set of documents and discovering, based on the statistics of the words in each, what the topics might be and what each document's balance of topics is.\n\"\"\"\n!pip install mglearn fulltext\n\nimport os\nimport re\nimport nltk\nimport IPython\nimport sklearn\nimport mglearn\nimport fulltext\nimport pyLDAvis\nimport threading\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\nfrom pandas import Series\nfrom tabulate import tabulate\nfrom bs4 import BeautifulSoup\nfrom string import punctuation\nfrom nltk.corpus import stopwords\nfrom IPython.display import display, clear_output\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nprint('complete')\nthreading.activeCount()\n\nstop_words = set(stopwords.words('english'))\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n# TRAINING DATA\n# Three articles about 3 related (auto), but different topics; Road Policing, The Auto Industry & Winter Driving\nauto_article_path_1 = \"..\/input\/toronto-star-sample-articles\/toronto-police-try-a-newold-trick.txt\"\nauto_article_path_2 = \"..\/input\/toronto-star-sample-articles\/canadian-sales-down-two-per-cent-year-over-year-in-october-while-multiple-automakers-set-records.html.txt\"\nauto_article_path_3 = \"..\/input\/toronto-star-sample-articles\/winter-car-prep-done-right.txt\"\n\n# TESTING DATA (stuff the model hasn't seen before but can hopefully recognize because of training)\n# One related article about Winter Driving\nauto_article_path_4 = \"..\/input\/toronto-star-sample-articles\/winter-of-2020-is-coming-are-you-ready.txt\"\n# URLS:\n# Article 1: https:\/\/www.thestar.com\/autos\/opinion\/2020\/11\/18\/toronto-police-try-a-newold-trick.html\n# Article 2: https:\/\/www.thestar.com\/autos\/2020\/11\/16\/canadian-sales-down-two-per-cent-year-over-year-in-october-while-multiple-automakers-set-records.html\n# Article 3: https:\/\/www.thestar.com\/autos\/advice\/2020\/11\/20\/what-ive-learned-after-15-winters-of-testing-tires.html\n# Article 4: https:\/\/www.thestar.com\/autos\/advice\/2020\/11\/27\/winter-of-2020-is-coming-are-you-ready.html\n\nwith open(auto_article_path_1, 'rb') as this_file:\n    auto_article_text_1 = this_file.read()\nprint(\"---- ARTICLE 1 RAW TEXT ----\")\nprint(auto_article_text_1[0:300])\n\nwith open(auto_article_path_2, 'rb') as this_file:\n    auto_article_text_2 = this_file.read()\nprint(\"\\n---- ARTICLE 2 RAW TEXT ----\")\nprint(auto_article_text_2[0:300])\n\nwith open(auto_article_path_3, 'rb') as this_file:\n    auto_article_text_3 = this_file.read()\nprint(\"\\n---- ARTICLE 3 RAW TEXT ----\")\nprint(auto_article_text_3[0:300])\n\nwith open(auto_article_path_4, 'rb') as this_file:\n    auto_article_text_4 = this_file.read()\nprint(\"\\n---- ARTICLE 4 RAW TEXT ----\")\nprint(auto_article_text_4[0:300])\ndef clean_up(text):\n    \n    result = re.sub(r'\\\\x?..', ' ', str(text))\n    result = str(result).replace(',', '')\n    result = str(result).replace('|', '')\n    result = str(result).replace('\"', '')\n    result = str(result).replace('*', '')\n    result = re.sub(r'\\s.\\s', ' ', str(result))\n    result = re.sub(r'\\s.{1}\\s', ' ', str(result))\n    result = str(result).replace('-', ' ')\n    result = str(result).replace('_', '')\n    result = str(result).replace('\\n', ' ')\n    result = str(result).replace('\\t', ' ')\n    result = str(result).replace('\\r', ' ')\n    result = str(result).replace('&nbsp;', ' ')\n        \n    result = str(result.lower())\n    \n    result = ''.join([c for c in result if c not in punctuation])\n    \n    result = ' '.join([w for w in result.split() if w not in stop_words])\n    \n    # Remove Multiple Spaces\n    result = re.sub(' +', ' ', str(result))\n        \n    # Remove duplicate consecutive words\n    result = re.sub(r'\\b(\\w+)\\s+\\1\\b', '', str(result)) \n    \n    result = result[1:len(result)]\n    \n    return result\n\narticle_1_clean = clean_up(auto_article_text_1)\narticle_2_clean = clean_up(auto_article_text_2)\narticle_3_clean = clean_up(auto_article_text_3)\narticle_4_clean = clean_up(auto_article_text_4)\n\nprint(\"---- ARTICLE 1 CLEAN TEXT ----\")\nprint(article_1_clean[0:300])\nprint(\"\\n---- ARTICLE 2 CLEAN TEXT ----\")\nprint(article_2_clean[0:300])\nprint(\"\\n---- ARTICLE 3 CLEAN TEXT ----\")\nprint(article_3_clean[0:300])\nprint(\"\\n---- ARTICLE 4 CLEAN TEXT ----\")\nprint(article_4_clean[0:300])\n\"\"\"\n### The Keyword Overlap or 'Bag of Words' Method\n\nThis method requires someone to label all articles.\n\"\"\"\n# Unique Words Present In Both Articles\noverlap_4_1 = len(set(article_4_clean.split()) & set(article_1_clean.split()))\noverlap_4_2 = len(set(article_4_clean.split()) & set(article_2_clean.split()))\noverlap_4_3 = len(set(article_4_clean.split()) & set(article_3_clean.split()))\n\nprint(\"Article 4 (about winter driving) Contains \" + str(overlap_4_1) + \" Words That Are Also In Article 1 (about road policing)\")\nprint(\"Article 4 (about winter driving) Contains \" + str(overlap_4_2) + \" Words That Are Also In Article 2 (about the auto industry)\")\nprint(\"Article 4 (about winter driving) Contains \" + str(overlap_4_3) + \" Words That Are Also In Article 3 (about winter driving)\")\n\nall_duplicates = overlap_4_1 + overlap_4_2 + overlap_4_3\n\nprint(\"Weight for Artile 1: \", round(overlap_4_1 \/ all_duplicates, 2), \"%\")\nprint(\"Weight for Artile 2: \", round(overlap_4_2 \/ all_duplicates, 2), \"%\")\nprint(\"Weight for Artile 3: \", round(overlap_4_3 \/ all_duplicates, 2), \"%\")\n\"\"\"\n^ Boom, that's what you'd expect. Article 3 is about Winter Driving and so it our 4th test article.\n\"\"\"\n\"\"\"\n### The Topic Modelling Way\n\n1) Mash all articles together into one 'corpus'.\n\n2) Put corpus through the 'LDA' model to determine how many topics are present.\n\n3) Label each topic logically.\n\n4) Model can then be used to output topic weights on new articles it hasn't seen.\n\n\"\"\"\ndata_corpus = [ article_1_clean, article_2_clean, article_3_clean ]\n\nvect = CountVectorizer(input='content', binary=False, min_df=.0005, max_df=0.35, ngram_range=(1,4))\n\ndtm = vect.fit_transform(data_corpus)\n\nmatrix = pd.DataFrame(dtm.toarray(), columns=vect.get_feature_names())\n\nprint(matrix.shape)\nfeature_names = vect.get_feature_names()\n\ndef runLDA(dtm, vect, n_components, alpha=None, beta=None):\n\n    print('=== LDA MODEL : ' + str(n_components) + ' TOPICS ===')\n    \n    lda_model = LatentDirichletAllocation(n_components=n_components,\n                                          doc_topic_prior=alpha,\n                                          topic_word_prior=beta,\n                                          max_iter=10, \n                                          learning_method='batch', \n                                          random_state=123,\n                                          n_jobs=-1,\n                                          verbose=1)\n    \n    lda_output = lda_model.fit(dtm)\n\n    ll = lda_model.score(dtm)                            # Log Likelyhood: Higher the better\n    perp = lda_model.perplexity(dtm)                     # Perplexity: Lower the better.\n    sorting = np.argsort(lda_model.components_)[:, ::-1] # sorted terms\n    theta = pd.DataFrame(lda_model.transform(dtm))       # document-topic matrix\n    beta = pd.DataFrame(lda_model.components_)           # components_ = topic-term matrix\n    \n    # Build Custom Topic Summary\n    no_top_words = 1000\n    weight = theta.sum(axis=0)\n    support50 = (theta > 0.5).sum(axis=0)\n    support10 = (theta > 0.1).sum(axis=0)\n    termss = list()\n    for topic_id, topic in enumerate(lda_model.components_):\n        terms = \" \".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]])\n        termss.append(terms)\n    topic_summary = pd.DataFrame({'TopicID': range(0, len(termss)), \n                                  'Support50': support50, \n                                  'Support10': support10, \n                                  'Weight': weight, \n                                  'Terms': termss})\n    return {'model': lda_model, \n            'theta': theta, \n            'beta': beta, \n            'topic_summary': topic_summary, \n            'll': ll, \n            'perp': perp,\n            'sorting': sorting,\n            'n_components': n_components}\n\n\nlda_2 = runLDA(dtm, vect, 2)\nlda_3 = runLDA(dtm, vect, 3)\nlda_4 = runLDA(dtm, vect, 4)\nlda_5 = runLDA(dtm, vect, 5)\nlda_10 = runLDA(dtm, vect, 10)\nprint('done')\n# Perplexity (lower the better?)\npp = [lda_2['perp'], lda_3['perp'], lda_4['perp'], lda_5['perp'], lda_10['perp']]\nplt.title('PERPLEXITY')\nplt.ylabel('Perplexity')\nplt.xlabel('Number Of Topics')\nplt.plot([2, 3, 4, 5, 10], pp)\nplt.show()\n\n# Log Likelyhood (higher the better?)\nll = [lda_2['ll'], lda_3['ll'], lda_4['ll'], lda_5['ll'], lda_10['ll']]\nplt.title('LOG LIKELIHOOD')\nplt.ylabel('Log Likelihood')\nplt.xlabel('Number Of Topics')\nplt.plot([2, 3, 4, 5, 10], ll)\nplt.show()\n\n# when in doubt, go for the elbow\nlda_choice = lda_3\nn_topics = lda_choice['n_components']\n# Word cloud for each topic\nfor t in range(n_topics):\n\n    # Extract terms from this LDA topic\n    topic_data = lda_3['topic_summary'].loc[t, 'Terms']\n    print(topic_data)\n    # Create and generate a word cloud\n    wordcloud = WordCloud(max_font_size = 75,\n                          max_words = 250,\n                          background_color = 'white',\n                          width = 600,\n                          height = 400).generate(str(topic_data))\n\n    # Display the generated image:\n    plt.figure(figsize=(10, 15))\n    plt.title('TOPIC ' + str(t) + ' WORDCLOUD')\n    plt.imshow(wordcloud, interpolation='bilinear')\n    plt.axis('off')\n    plt.show()\n\"\"\"\n^ so above it looks like:\n* the first topic is winter driving\n* the second topic is about policing\n* the thrid topic is about the auto industry\n\"\"\"\nunseen_document = article_4_clean\n\nprint(lda_output.transform(vect.transform([unseen_document])))\n\"\"\"\n^ If we put test article 4 through this model it gives topic 1 (index 0), which we have labelled as 'winter driving', a weight of 0.78.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c87b03c70baebe'}"}
{"id":"43255","text":"\"\"\"\n# Covid Visualiation\n\"\"\"\n\"\"\"\n# 1. Analysis of Dataset\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\ncovid_data = pd.read_csv('\/kaggle\/input\/novel-corona-virus-2019-dataset\/covid_19_data.csv');\n\ncovid_data.head()\n\n\"\"\"\n# 1.1. Missing Values\nMissing values only exist in Province\/State feature\n\"\"\"\nprint(\"Train data missing value count for each feature\")\nprint(covid_data.isnull().sum())\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(8,8)})\nsns.heatmap(covid_data.isnull(), yticklabels = False, cmap=\"YlGnBu\")\n#Total number of countries effected by Covid-19\nuniqueValues = covid_data['Country\/Region'].unique()\nprint('Total number of countries effected by Covid-19: %s' % len(uniqueValues)) \nprint(uniqueValues);\n\"\"\"\n# 1.2. Visualization\n\"\"\"\n# Convert ObservationDate to datetime object\ncovid_data['ObservationDate'] = pd.to_datetime(covid_data['ObservationDate'], format='%m\/%d\/%Y', utc=True);\n# Group data by date\ndate_grouped=covid_data.groupby([\"ObservationDate\"]).agg({\"Confirmed\":'sum',\"Recovered\":'sum',\"Deaths\":'sum'})\n\n#Calculate Active cases around the world\ndate_grouped[\"Active Cases\"] = date_grouped[\"Confirmed\"] - date_grouped[\"Recovered\"] - date_grouped[\"Deaths\"]\n\n# Total number of Confirmed cases around the world\nprint('Total number of Confirmed cases around the world: %s' % date_grouped[\"Confirmed\"].iloc[-1])\n\n# Total number of Recovered cases around the world\nprint('Total number of Recovered cases around the world: %s' % date_grouped[\"Recovered\"].iloc[-1])\n\n# Total number of Death cases around the world\nprint('Total number of Death cases around the world: %s' % date_grouped[\"Deaths\"].iloc[-1])\n\ndate_grouped.tail()\nimport plotly.graph_objects as go\nfig=go.Figure()\nfig.add_trace(go.Scatter(x=date_grouped.index, y=date_grouped[\"Confirmed\"],\n                    mode='lines+markers',\n                    name='Confirmed',marker_color='purple'))\nfig.add_trace(go.Scatter(x=date_grouped.index, y=date_grouped[\"Recovered\"],\n                    mode='lines+markers',\n                    name='Recovered', marker_color='green'))\nfig.add_trace(go.Scatter(x=date_grouped.index, y=date_grouped[\"Deaths\"],\n                    mode='lines+markers',\n                    name='Death', marker_color='red'))\nfig.update_layout(title=\"Confirmed, Recovered, Death case counts\",\n                 xaxis_title=\"Date\",yaxis_title=\"Number of Cases\",legend=dict(x=0,y=1,traceorder=\"normal\"))\nfig.show()\n# Group data by country\ncountry_grouped=covid_data.groupby(['Country\/Region','ObservationDate']).agg({\"Confirmed\":'sum',\"Recovered\":'sum',\"Deaths\":'sum'})\n\ncountry_grouped[\"Death_Percent\"] = country_grouped[\"Deaths\"] \/ country_grouped[\"Confirmed\"] * 100 \ncountry_grouped[\"Recovered_Percent\"] = country_grouped[\"Recovered\"] \/ country_grouped[\"Confirmed\"] * 100\n\n# get total sum of each country\ntotal_sum_country = country_grouped.groupby(['Country\/Region']).tail(1)\ntotal_sum_country.tail(20)\n\"\"\"\n**Top 10 Countries with Confirmed Cases**\n\"\"\"\n\ntotal_sum_country = total_sum_country.reset_index()\ntop_10_confirmed_country = total_sum_country.sort_values(by=['Confirmed'],ascending=False).head(10)\n\"\"\"\n**Pie Chart Top 10 Countries with Confirmed Case Percentage**\n\"\"\"\nfig1, ax1 = plt.subplots()\nax1.pie(top_10_confirmed_country['Confirmed'], labels=top_10_confirmed_country['Country\/Region'], autopct='%1.1f%%',\n        shadow=True, startangle=90)\nax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.\nplt.show()\n\"\"\"\n**Death Rates of Top 10 Countries with Confirmed Cases**\n\"\"\"\ntop_10_confirmed_country_death_percent = top_10_confirmed_country.sort_values(by=['Death_Percent'],ascending=False).head(10)\ntop_10_confirmed_country_death_percent.head(10)","meta":"{'source': 'AI4Code', 'id': '4fb659b2e523c3'}"}
{"id":"14804","text":"\"\"\"\n# Parkinsons disease\nA disorder of the central nervous system that affects movement, often including tremors.\nNerve cell damage in the brain causes dopamine levels to drop, leading to the symptoms of Parkinson's.\nParkinson's often starts with a tremor in one hand. Other symptoms are slow movement, stiffness and loss of balance.\nMedication can help control the symptoms of Parkinson's.\n\n\n# What are the risk factors for Parkinson's disease?\n\nAge,Sex,Genetic factors\nHead trauma,Exposure to chemicals,Medications and other drugs,Impact of smoking.\n\n\n\"\"\"\n# import important libraries\nimport pandas as pd\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# load dataset\ndf=pd.read_csv('\/kaggle\/input\/parkinsons-data-set\/parkinsons.data')\n# top 5 rows\ndf.head()\n# check rows and features in Parkinsons Data\ndf.shape\n# some important info about data like null values ,datatype\ndf.info()\n\n# in this dataset there is no null values \n# Data Analysis With Matplotlib and Seaborn\nnumeric_columns=df.select_dtypes(include=['float','int']).columns\nstring_columns=df.select_dtypes(include='object').columns\n# Total Numeric Columns\nlen(numeric_columns)\n# univariant analysis \n# histogram\nplt.figure(figsize=(30,35))\nfor i,v in enumerate(numeric_columns,1):\n    plt.subplot(6,5,i)\n    plt.title(v)\n    sns.distplot(df[v],bins=10)\nplt.show();\n# target variable analysis\nsns.countplot(df['status']);\n\n# target variable check percentage using pie chart\ndf['status'].value_counts().plot(kind='pie',autopct='%.2f');\n\n# check outliers\nplt.figure(figsize=(25,30))\nfor i,col in enumerate(numeric_columns,1):\n    plt.subplot(6,4,i)\n    sns.set_theme(style=\"whitegrid\")\n    plt.title(col)\n    sns.boxplot(df[col])\n        \nplt.show()\n\n# now fixed outlier using capping technique\n# Computing 10th, 90th percentiles and replacing the outliers\nimport numpy as np\ntenth_per=[]\nninety_per=[]\nfor i,col in enumerate(numeric_columns,1):\n    tenth_percentile = np.percentile(df[col], 10)\n    tenth_per.append(tenth_percentile)\n    ninetieth_percentile = np.percentile(df[col], 90)\n    ninety_per.append(ninetieth_percentile)\n#     print(f\"{i}  tenth percentile {tenth_percentile} ninetieth percentile {ninetieth_percentile}\")\n    \n    \n# capping\nfor index,i in enumerate(numeric_columns):\n    df[i]=df[i].apply(lambda x : tenth_per[index] if (x<tenth_per[index]) else x)\n    \n    df[i]=df[i].apply(lambda x : ninety_per[index] if (x>ninety_per[index]) else x)\n# after capping all values\n# check outliers once again\nplt.figure(figsize=(25,30))\nfor i,col in enumerate(numeric_columns,1):\n    plt.subplot(6,4,i)\n    sns.set_theme(style=\"whitegrid\")\n    plt.title(col)\n    sns.boxplot(df[col])\n        \nplt.show()\n# check correlation \nplt.figure(figsize=(19,7))\nsns.heatmap(df.corr(),annot=True);\n# top 5 rows\ndf.head()\n# independent and dependent variable\nx=df.drop(columns=['name','status'],axis=1)\ny=df['status']\n# Data Standardization\n# Al the values of the dataset of all the columns varies. So we need to convert all the values in a common range.\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\nx=scaler.fit_transform(x)\n# divide in test and train data\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=2)\n# model selection\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score, recall_score\ndef best_model(model,X,y):\n    xtrain,xtest,ytrain,ytest=train_test_split(X,y,test_size=0.2)\n    print(xtrain.shape,xtest.shape,ytrain.shape,ytest.shape)\n    model.fit(xtrain,ytrain)\n    print('Train Score',model.score(xtrain,ytrain))\n    pred=model.predict(xtest)\n    print('Prediction Score',accuracy_score(pred,ytest))\n    print('Test Score',model.score(xtest,ytest))\n    print(\"***********************************************\")\n    print(confusion_matrix(ytest,pred))\n    print(\"***********************************************\")\n    print(\"Precision Score\",precision_score(ytest,pred))\n    print(\"Recall Score\",recall_score(ytest,pred))\n    \n    \n# logistic Regression\nfrom sklearn.linear_model import LogisticRegression\nlr=LogisticRegression()\nbest_model(lr,x,y)\n# svc\nfrom sklearn.svm import SVC\nsvc=SVC(kernel='linear')\nbest_model(svc,x,y)\n# k nearest neighbour\nfrom sklearn.neighbors import KNeighborsClassifier  \nclassifier= KNeighborsClassifier(n_neighbors=5 )  \nbest_model(classifier,x,y)\n# random forest\nfrom sklearn.ensemble import RandomForestClassifier\nrf=RandomForestClassifier()\nbest_model(rf,x,y)\n\"\"\"\nsvc has highest accuracy score because\n\nEffective in high dimensional spaces.\n\nStill effective in cases where number of dimensions is greater than the number of samples.\n\n\n\"\"\"\nx=[119.992,157.302,75.6146,0.007840,0.00007,40,0.00370,55,455,76,0.005540,0.011090,0.043740,0.06545,0.022110,21.033,0.414783,0.789799,-4.813031,0.266482,2.301442,0.284654]\nresult=svc.predict(scaler.fit_transform([x]))\nif result[0]==1:\n    print(\"Parkinsons Disease\")\nelse:\n    print('Healthy')","meta":"{'source': 'AI4Code', 'id': '1b0d5c35286f59'}"}
{"id":"91653","text":"\"\"\"\n# To what extent does the difference in the average price of GNV depend on the state and or region that it is sold in?\n\n**In this notebook I endevour to answer the question above, This is done by running an anova test on the data after some cleaning has been done.**\n\"\"\"\n#import the standard data analytics libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n%matplotlib inline\nsns.set() #set style for any plots\n\n#import the data\ndata = pd.read_csv('\/kaggle\/input\/gas-prices-in-brazil\/2004-2019.tsv',sep='\\t')\ndata.columns # output the colums\n#drop irrelevant column\ndata.drop('Unnamed: 0',axis=1,inplace=True)\n# For easy interpretability, we translate the columns to english\n\ndata.rename(\ncolumns={\n        \"DATA INICIAL\": \"start_date\",\n        \"DATA FINAL\": \"end_date\",\n        \"REGI\u00c3O\": \"region\",\n        \"ESTADO\": \"state\",\n        \"PRODUTO\": \"product\",\n        \"N\u00daMERO DE POSTOS PESQUISADOS\": \"no_gas_stations\",\n        \"UNIDADE DE MEDIDA\": \"unit\",\n        \"PRE\u00c7O M\u00c9DIO REVENDA\": \"avg_price\",\n        \"DESVIO PADR\u00c3O REVENDA\": \"sd_price\",\n        \"PRE\u00c7O M\u00cdNIMO REVENDA\": \"min_price\",\n        \"PRE\u00c7O M\u00c1XIMO REVENDA\": \"max_price\",\n        \"MARGEM M\u00c9DIA REVENDA\": \"avg_price_margin\",\n        \"ANO\": \"year\",\n        \"M\u00caS\": \"month\",\n        \"COEF DE VARIA\u00c7\u00c3O DISTRIBUI\u00c7\u00c3O\": \"coef_dist\",\n        \"PRE\u00c7O M\u00c1XIMO DISTRIBUI\u00c7\u00c3O\": \"dist_max_price\",\n        \"PRE\u00c7O M\u00cdNIMO DISTRIBUI\u00c7\u00c3O\": \"dist_min_price\",\n        \"DESVIO PADR\u00c3O DISTRIBUI\u00c7\u00c3O\": \"dist_sd_price\",\n        \"PRE\u00c7O M\u00c9DIO DISTRIBUI\u00c7\u00c3O\": \"dist_avg_price\",\n        \"COEF DE VARIA\u00c7\u00c3O REVENDA\": \"coef_price\"\n    },\n    inplace=True\n)\n# view data\ndata.head()\n# convert columns that should be numeric to numbers\nnames = ['avg_price_margin','coef_price','dist_avg_price','dist_sd_price','dist_min_price','dist_max_price','coef_dist']\n\nfor col in names:\n    data[col]=pd.to_numeric(data[col],errors='coerce')\n\ndata.dtypes\n#determine if the are any missing values\n# find the shape of the data\nshape = data.shape\nmissing = data.isnull().any()\n\nprint(shape,'\\n')\nprint(missing)\n# Check how many null values there are in each of the columns that came up missing values in the previous cell.\nmargins_missing = data['avg_price_margin'].isnull().sum()\navg_price_missing = data['dist_avg_price'].isnull().sum()\nsd_price_missing = data['dist_sd_price'].isnull().sum()\ndist_min_price_missing = data['dist_min_price'].isnull().sum()\ndist_max_price_missing = data['dist_max_price'].isnull().sum()\ncoef_dist_missing = data['coef_dist'].isnull().sum()\n\n# Print the number of missing values in each column\nprint(margins_missing)\nprint(avg_price_missing)\nprint(sd_price_missing)\nprint(dist_min_price_missing)\nprint(dist_max_price_missing)\nprint(coef_dist_missing)\n\n# Drop every entry with missing values\ndata.dropna(axis=0,inplace=True)\n# Determine the number and names of the products sold in Brazil\nproducts = data['product'].unique()\nprint(len(products))\nprint(products)\n# Find the number and names of the states in Brazil\ngnv_data = data[data['product'] == 'GNV']\nstates = gnv_data['state'].unique()\nstates\n# Plot the distribution of the average price in each state\n# Although anova is robust to non normally distributed data, It is good to know if the assumption of normality holds.\nfig,ax = plt.subplots(6,4,figsize=(10,10),constrained_layout=True)\nax = ax.ravel()\n\nfor i in range(len(states)):\n    ax[i].hist(gnv_data[gnv_data.state == states[i]]['avg_price'])\n    ax[i].set_title(states[i])\n    ax[i].set_xlabel('avg price')\n\n\"\"\"\n**The is no clear distribution in the data. Nonetheless we continue are exploration.**\n\"\"\"\n# Determine how many observations we have from every state\ngnv_state_count = gnv_data.groupby('state')['avg_price'].count()\ngnv_state_count\n# separate the data into two sets, gnv_data2 has the states with less than 100 obseravtions removed \nlow_count_states = ['AMAPA','DISTRITO FEDERAL','GOIAS','MARANHAO','PARA','PIAUI','TOCANTINS']\nlow_count_states_df = gnv_data[gnv_data['state'].isin(low_count_states)]\ngnv_data2 = gnv_data.drop(low_count_states_df.index,axis=0)\nstates2 = np.setdiff1d(states,low_count_states) # Create a list of the remaining states \nprint(states2)\nprint(len(states2))\n# We determine if the data is normally distributed, by way of qqplot \n# beacuse the histogram did not provide any useful information\nfrom statsmodels.graphics.gofplots import qqplot\n\nfig,ax = plt.subplots(6,3,figsize=(10,10),constrained_layout=True)\nax = ax.ravel()\n\nfor i in range(len(states2)):\n    qqplot(gnv_data[gnv_data.state == states2[i]]['avg_price'],line='s',ax=ax[i])\n    ax[i].set_title(states2[i])\n    ax[i].set_xlabel('avg price')\n\n\n\"\"\"\n**The above looks more S-curved than normally distributed. However it is not easy to discern at this stage. Numeric tests may be more informative.**\n\"\"\"\n# Run a shapiro normality test at a 5% significance level\nfrom scipy.stats import shapiro\n\nalpha = 0.05\nreject_count = 0 # count of all the states that dont have normally distributed data\nnormal_count = 0 # count of states with normally distributed data\n\nfor i in range(len(states2)):\n    \n    stat, p = shapiro(gnv_data2[gnv_data.state == states2[i]]['avg_price'])\n    #print(states2[i])\n    #print('Statistics=%.3f, p=%.3f' % (stat, p))\n\n    if p > alpha:\n        normal_count += 1\n    else:\n        reject_count += 1\n\nprint('number of rejects =',reject_count)\nprint('number of normally distributed prices =',normal_count)\n# Next we run a normaltest to verify the results of the previous test.\nfrom scipy.stats import normaltest\n\nalpha = 0.05\nreject_count = 0\nnormal_count = 0\n\nfor i in range(len(states2)):\n    \n    stat, p = normaltest(gnv_data2[gnv_data.state == states2[i]]['avg_price'])\n    #print(states2[i])\n    #print('Statistics=%.3f, p=%.3f' % (stat, p))\n\n    if p > alpha:\n        normal_count += 1\n    else:\n        reject_count += 1\n\nprint('number of rejects =',reject_count)\nprint('number of normally distributed prices =',normal_count)\n# Next we run anova using the states as treatments and the avg_price as the response variable\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\n\nsamples = pd.DataFrame(columns=gnv_data2.columns) # Create a DataFrame to store the samples\n\nfor state in states2:\n    sample = gnv_data2[gnv_data2.state == state].sample(100) # Sample 100 values from each state.\n    samples = pd.concat([samples,sample])\n\n\nmodel = ols('avg_price ~ state', data=samples).fit()\nanova_table = sm.stats.anova_lm(model,typ=3)\n\nprint(model.summary())\nprint()\nprint(anova_table)\n\"\"\"\n**The results gotten from the anova test suggest a few things:**\n\n1) The p_value of the test for the variable state is approximately zero (4.137e-110) suggesting that the State in which GNV is sold is significant in the differences in mean seen in avg_price. That is, the means of the states are statistically different.\n\n2) The r_squared value for the model fluctuates due to the sampling however it never goes beyond 0.1, meaning that less than 10% of the variation observed in the data is attributable to the states. This is low, suggesting that the differences in avg_prices in the states is not mainly due to the states in which GNV is sold. More will be done find a suitable r_value using a sampling distribution  \n\n3) The top five states in terms of avg_price in the model are (in descending order), RIO GRANDE DO SUL, AMAZONAS, PARAIBA,SERGIPE, and MATO GROSSO DO SUL.\n\n4) For the fitted model about 10 out of 17 states are not significant (p values greater than 0.05). This suggests that their effect on the average price is negligible. This can also be seem by the coefficient of the effect. The other two states that have a significant effect on the model are PARANA, RIO DE JANEIRO, and Sao Paulo all with a pronouced negative effect.\n\"\"\"\n# Next we attempt to discern more about the r_squared value for the anova test. \n# 5,000 repitions of 100 bootstrapped samples (10,000 waaay too slow) will be used to find a distribution for the value.\n# The calculations will be hard coded for this part of the analysis.\n\nN = 5000\ns = 100\nP = len(states2)\nn = len(states2) - 1\nR_squared = []\nR_squared_a = []\nfor i in range(N):\n    samples = pd.DataFrame(columns=gnv_data2.columns)\n    for state in states2:\n        sample = gnv_data2[gnv_data2.state == state].sample(s,replace=True)\n        samples = pd.concat([samples,sample])\n    \n    state_means = samples.groupby('state')['avg_price'].mean()\n    overall_mean = samples['avg_price'].mean()\n    \n    SSA = (s*((state_means - overall_mean)**2)).sum() # Sum squared treatments\n    MSA = SSA\/n # Mean square treatments\n    SST = ((samples['avg_price']-overall_mean)**2).sum() # Total Sum squares \n    MST = SST\/(P*s - 1)\n    SSE = SST - SSA # Sum squared residuals\n    MSE = SSE\/(P*(s-1))\n    r_2 = SSA\/SST # R_squared\n    r_2a = 1-MSE\/MST # Adjusted R_squared\n    R_squared.append(r_2)\n    R_squared_a.append(r_2a)\n    \nmean_r2 = np.mean(R_squared)\nmean_r2a = np.mean(R_squared_a)\n\nfig,ax = plt.subplots(1,2,figsize=(15,5))\nax[0].hist(R_squared)\nax[0].set_title('Sampling distribution of R_squared')\nax[0].set_xlabel('R_square value')\nax[0].set_ylabel('frequency')\n\nax[1].hist(R_squared_a)\nax[1].set_title('Sampling distribution of adjusted R_squared')\nax[1].set_xlabel('R_square value')\nax[1].set_ylabel('frequency')\n\nprint('R_squared mean value is %.3f and the adjusted R-squared mean value is %.3f' % (mean_r2,mean_r2a))\n# Pair wise comparison of the top five states by avg_price\n\npair_comp = model.t_test_pairwise('state')\npair_comp_df = pair_comp.result_frame\n\n#pair_comp_df\n\nresults = pd.DataFrame([pair_comp_df.loc['RIO GRANDE DO SUL-AMAZONAS'],pair_comp_df.loc['PARAIBA-AMAZONAS'],\n                       pair_comp_df.loc['SERGIPE-AMAZONAS'],pair_comp_df.loc['MATO GROSSO DO SUL-AMAZONAS'],\n                       pair_comp_df.loc['RIO GRANDE DO SUL-MATO GROSSO DO SUL'],pair_comp_df.loc['PARAIBA-MATO GROSSO DO SUL'],\n                       pair_comp_df.loc['SERGIPE-MATO GROSSO DO SUL'],pair_comp_df.loc['SERGIPE-PARAIBA'],\n                       pair_comp_df.loc['RIO GRANDE DO SUL-PARAIBA'],pair_comp_df.loc['SERGIPE-RIO GRANDE DO SUL'] ])\nresults\n\"\"\"\n**The comparison is made between all the states in the top 5. We see that the only states whose means differed a lot are Rio Grande do Sul and Mato Grosso do sul. 1st place and 5th place respectively. The pairwise comparison shows that atleast for the states in which Gnv is highly priced there is no major statistical difference in the price. It seems like it requires a difference in average price of about 0.2 for there to be a statistically significant difference.**\n\"\"\"\n\"\"\"\n**Next, the region of the retailers is checked to see if maybe it has a better chance explaining the variability in the data.**\n\"\"\"\nfor region in gnv_data2['region'].unique():\n    sample = gnv_data2[gnv_data2.region == region].sample(100) # Sample 100 values from each state.\n    samples = pd.concat([samples,sample])\n\n\nmodel = ols('avg_price ~ region', data=samples).fit()\nanova_table = sm.stats.anova_lm(model,typ=3)\n\nprint(model.summary())\nprint()\nprint(anova_table)\n\"\"\"\n**As can be seen in the Ouput above the North is by far the most exoensive region when it comes to GNV pricing. The central west on the other hand is the cheapest area. Next, as was done before, we will attempt to find out how variability the region actually accounts for. **\n\"\"\"\n# Next we attempt to discern more about the r_squared value for the anova test. \n# 5,000 repitions of 100 bootstrapped samples (10,000 waaay too slow) will be used to find a distribution for the value.\n# The calculations will be hard coded for this part of the analysis.\n\nN = 5000\ns = 100\nP = len(states2)\nn = len(states2) - 1\nR_squared = []\nR_squared_a = []\nfor i in range(N):\n    samples = pd.DataFrame(columns=gnv_data2.columns)\n    for region in gnv_data2['region'].unique():\n        sample = gnv_data2[gnv_data2.region == region].sample(s,replace=True)\n        samples = pd.concat([samples,sample])\n    \n    region_means = samples.groupby('region')['avg_price'].mean()\n    overall_mean = samples['avg_price'].mean()\n    \n    SSA = (s*((region_means - overall_mean)**2)).sum() # Sum squared treatments\n    MSA = SSA\/n # Mean square treatments\n    SST = ((samples['avg_price']-overall_mean)**2).sum() # Total Sum squares \n    MST = SST\/(P*s - 1)\n    SSE = SST - SSA # Sum squared residuals\n    MSE = SSE\/(P*(s-1))\n    r_2 = SSA\/SST # R_squared\n    r_2a = 1-MSE\/MST # Adjusted R_squared\n    R_squared.append(r_2)\n    R_squared_a.append(r_2a)\n    \nmean_r2 = np.mean(R_squared)\nmean_r2a = np.mean(R_squared_a)\n\nfig,ax = plt.subplots(1,2,figsize=(15,5))\nax[0].hist(R_squared)\nax[0].set_title('Sampling distribution of R_squared')\nax[0].set_xlabel('R_square value')\nax[0].set_ylabel('frequency')\n\nax[1].hist(R_squared_a)\nax[1].set_title('Sampling distribution of adjusted R_squared')\nax[1].set_xlabel('R_square value')\nax[1].set_ylabel('frequency')\n\nprint('R_squared mean value is %.3f and the adjusted R-squared mean value is %.3f' % (mean_r2,mean_r2a))\n\"\"\"\n**In conclusion, the results of this notebook analysis suggest that although the state is significant in the difference between the mean avgerage price of GNV it only accounts for about 7% of the variability. Thus Although the prices vary from state to state there is one or more other factors that play a bigger role in the mean differences. The Region on the other hand accounts for only 6% of the variability about the same as the state. we do see though that the Northern states are by far the most expensive and that central western states are the cheapest. However this low value also suggests there are other factors at play.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a823bbc4e46a9b'}"}
{"id":"94961","text":"\"\"\"\n## Setup\nThis notebook requires some packages besides pytorch-lightning.\n\"\"\"\n# !pip install --quiet \"torchvision\" \"torch\" \"pytorch-lightning\" \"torchmetrics\"\n# !pip install --quiet comet-ml\nimport comet_ml\n\nfrom kaggle_secrets import UserSecretsClient\nfrom pytorch_lightning.loggers import CometLogger\nuser_secrets = UserSecretsClient()\ncomet_logger = CometLogger(\n    api_key=user_secrets.get_secret(\"COMET_API_KEY\"),\n    workspace=user_secrets.get_secret(\"COMET_WORKSPACE\"),  # Optional\n    save_dir=\".\",  # Optional\n    project_name=user_secrets.get_secret(\"COMET_PROJECT\"),  # Optional\n    # rest_api_key=user_secrets.get_secret(\"COMET_REST_API_KEY\"),  # Optional\n    # experiment_name=\"smap\",  # Optional\n)\nimport os\n\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchmetrics\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom torchvision import datasets\nfrom torchvision import models\nfrom torchvision import transforms\nfrom pytorch_lightning import Trainer\nimport pandas as pd\nfrom pytorch_lightning.utilities.seed import seed_everything\nfrom sklearn.model_selection import train_test_split\nROOT = os.path.join(\"\/kaggle\", \"input\", \"lego-minifigures-classification\")\nAVAIL_GPUS = min(1, torch.cuda.device_count())\nBATCH_SIZE = 4\nseed_everything(42)\n\"\"\"\n## Simplest example\n\nHere's the simplest most minimal example with just a training loop (no validation, no testing).\n\n**Keep in Mind** - A `LightningModule` *is* a PyTorch `nn.Module` - it just has a few more helpful features.\n\"\"\"\nclass Model(pl.LightningModule):\n    def __init__(self, classes: int):\n        super(Model, self).__init__()\n        \n        self.classes = classes\n        self.create_model()\n\n        self.train_acc = torchmetrics.Accuracy()\n        self.valid_acc = torchmetrics.Accuracy()\n        self.test_acc = torchmetrics.Accuracy()\n\n    def create_model(self):\n#        self.models = models.resnet50(pretrained=True)\n        self.models = models.mobilenet_v2(pretrained=True)\n    \n        print(self.models)\n\n        # num_ftrs = self.models.fc.in_features\n        # self.models.fc = nn.Linear(num_ftrs, self.classes)\n        num_ftrs = self.models.classifier[1].in_features\n        self.models.classifier[1] = nn.Linear(num_ftrs, self.classes)\n\n    def forward(self, x):\n        return self.models(x)\n\n    def training_step(self, batch, batch_idx):\n        images, target = batch\n        preds = self(images)\n\n        loss = F.cross_entropy(preds, target)\n        \n        _, preds = torch.max(preds, 1)\n        self.train_acc(preds, target)\n        self.log('train_acc', self.train_acc, on_step=True, on_epoch=True, prog_bar=True)\n\n        return loss\n\n    def validation_step(self, batch, batch_idx):\n        images, target = batch\n        preds = self.forward(images)\n        \n        loss = F.cross_entropy(preds, target)\n        \n        _, preds = torch.max(preds, 1)\n        self.valid_acc(preds, target)\n        self.log('valid_acc', self.valid_acc, on_step=False, on_epoch=True, prog_bar=True)\n        return loss\n\n    def test_step(self, batch, batch_idx):\n        images, target = batch\n        preds = self.forward(images)\n        \n        loss = F.cross_entropy(preds, target)\n        \n        _, preds = torch.max(preds, 1)\n        self.test_acc(preds, target)\n        self.log('test_acc', self.test_acc)\n        self.log(\"test_loss\", loss)\n        return loss\n\n    def configure_optimizers(self):\n        # return torch.optim.SGD(self.parameters(), lr=0.01, momentum=0.9)\n        return torch.optim.Adam(self.parameters(), lr=0.0001)\ndata = pd.read_csv(os.path.join(ROOT,'index.csv'))\ndata.head()\nclass LegoDataset(torch.utils.data.Dataset):\n    def __init__(self, X: list, y: list, root: str, transforms = None):\n        self.X = list(X)\n        self.y = list(y)\n\n        self.root = root\n        self.transforms = transforms\n\n    def __len__(self):\n        return len(self.X)\n\n    def __getitem__(self, index):\n        filename = os.path.join(self.root, self.X[index])\n        label = self.y[index]\n        image = Image.open(filename)\n        \n        if self.transforms is not None:\n            image = self.transforms(image)\n        \n        return image, label\nX, y = data.path, data.class_id\ny = y-1\n\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0)\nprint(len(X_train), len(X_valid))\ntrain_dataset = LegoDataset(X_train, y_train, root=ROOT, transforms=transforms.Compose([\n                                    transforms.Resize(224),\n                                    transforms.ToTensor(),\n                                    transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])\n                                   ])\n                           )\n                            \ntrain_dataset[0]\nvalid_dataset = LegoDataset(X_valid, y_valid, root=ROOT, transforms=transforms.Compose([\n                                    transforms.Resize(224),\n                                    transforms.ToTensor(),\n                                    transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])\n                                   ])\n                           )\n\nvalid_dataset[0]\ntrain_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE)\nvalid_dataloader = DataLoader(valid_dataset, batch_size=1)\nclasses = data.class_id.unique()\nprint(classes, len(classes))\nmodel = Model(classes=max(classes))\n#AVAIL_GPUS=0\n\ntrainer = Trainer(\n    logger=comet_logger,\n    callbacks=[EarlyStopping(monitor=\"valid_acc\", mode=\"max\", patience=5, min_delta=0.00)],\n    gpus=AVAIL_GPUS,\n    max_epochs=50,\n    default_root_dir=\".\/test\/\"\n)\n\nhist = trainer.fit(model, train_dataloader, valid_dataloader)\ntest_data = pd.read_csv(os.path.join(ROOT, 'test.csv'))\nvalid_dataset = LegoDataset(test_data.path, test_data.class_id-1, root=ROOT, transforms=transforms.Compose([\n                                    transforms.Resize(224),\n                                    transforms.ToTensor(),\n                                    transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])\n                                   ])\n                           )\n\ntest_dataloader = DataLoader(valid_dataset, batch_size=1)\ntrainer.test(model, test_dataloader)\n\"\"\"\n# Evaluate\n\"\"\"\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n    fig, ax = plt.subplots(figsize=(len(classes), len(classes)))\n    print(cm)\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=90)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\nimport torchmetrics\ndevice = torch.device(\"cuda\")\n\nmodel.eval()\nmodel = model.cuda()\n\nclass_names = pd.read_csv(os.path.join(ROOT, 'metadata.csv'))[\"minifigure_name\"].tolist()\n\nacc = torchmetrics.Accuracy()\n\ncm_p = []\ncm_t = []\n\nfor i, (inputs, targets) in enumerate(test_dataloader):\n    inputs = inputs.to(device)\n\n    preds = model(inputs).cpu()\n    _, preds = torch.max(preds, 1)\n    acc(preds, targets)\n\n    #      MC\n    cm_t.extend(targets.cpu().detach().numpy())\n    cm_p.extend(preds.cpu().detach().numpy())\n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(cm_t, cm_p)\n\nplot_confusion_matrix(cm, class_names, normalize=False)\nplot_confusion_matrix(cm, class_names, normalize=True)\ncomet_logger.experiment.log_confusion_matrix(cm_t, cm_p, labels=class_names)\ncomet_logger.experiment.end()","meta":"{'source': 'AI4Code', 'id': 'ae5183a93c12f5'}"}
{"id":"80770","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.metrics import r2_score, mean_squared_error\ntrain = pd.read_csv(\"\/kaggle\/input\/osic-pulmonary-fibrosis-progression\/train.csv\")\ntest = pd.read_csv(\"\/kaggle\/input\/osic-pulmonary-fibrosis-progression\/test.csv\")\nsample = pd.read_csv(\"\/kaggle\/input\/osic-pulmonary-fibrosis-progression\/sample_submission.csv\")\ntrain.head()\nprint(\"Training data size is :\",train.shape[0])\nprint(\"Testing data size is :\",test.shape[0])\ntrain.isna().sum()\n\"\"\"\n# Encoding Categorical Feature\n\"\"\"\ntrain_cat = OrdinalEncoder().fit_transform(train[['Sex', 'SmokingStatus']]) \ntrain_cat = pd.DataFrame({'Sex': train_cat[:, 0], 'SmokingStatus': train_cat[:, 1]})\n\"\"\"\n# Scaleing Numerical feature\n\"\"\"\ntrain_num = StandardScaler().fit_transform(train[['Weeks', 'Percent','Age']])  # standard scaling \ntrain_num = pd.DataFrame({'Weeks': train_num[:, 0], 'Percent': train_num[:, 1],'Age':train_num[:,2]})\ndf = pd.concat([train_cat, train_num, train['FVC']], axis = 1)\nX = df.drop('FVC',axis =1)\ny = df['FVC']\n\"\"\"\n# train Test Split\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)\n\"\"\"\n# Gradient Boosting Regressor\n\"\"\"\nparams = {'n_estimators': 300,\n          'max_depth': 7,\n          'learning_rate': 0.01}\n\nreg = GradientBoostingRegressor(**params)\n\n%time reg.fit(X_train, y_train)\n\ny_pred = reg.predict(X_test)\n\nmse = mean_squared_error(y_test, y_pred)\n\nprint(\"The mean squared error (MSE) on test set: {}\".format(mse))\ntest_score = np.zeros((params['n_estimators'],), dtype=np.float64)\nfor i, y_pred in enumerate(reg.staged_predict(X_test)):\n    test_score[i] = reg.loss_(y_test, y_pred)\n\nfig = plt.figure(figsize=(6, 6))\nplt.subplot(1, 1, 1)\nplt.title('Deviance')\nplt.plot(np.arange(params['n_estimators']) + 1, reg.train_score_, 'b-',\n         label='Training Set Deviance')\nplt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',\n         label='Test Set Deviance')\nplt.legend(loc='upper right')\nplt.xlabel('Boosting Iterations')\nplt.ylabel('Deviance')\nfig.tight_layout()\nplt.show()\n\"\"\"\n# XGB Regressor\n\"\"\"\nfrom xgboost import XGBRegressor\n\nparams = {'n_estimators': 300,\n          'max_depth': 7,\n          'learning_rate': 0.25}\n\nmodel = XGBRegressor(**params)\n\n%time model.fit(X_train,y_train)\n\ny_pred = model.predict(X_test)\n\nmse = mean_squared_error(y_test, y_pred)\n\nprint(\"The mean squared error (MSE) on test set: {}\".format(mse))\n\nprint(model.feature_importances_)\ntest_score = np.zeros((params['n_estimators'],), dtype=np.float64)\nfor i, y_pred in enumerate(reg.staged_predict(X_test)):\n    test_score[i] = reg.loss_(y_test, y_pred)\n\nfig = plt.figure(figsize=(6, 6))\nplt.subplot(1, 1, 1)\nplt.title('Deviance')\nplt.plot(np.arange(params['n_estimators']) + 1, reg.train_score_, 'b-',\n         label='Training Set Deviance')\nplt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',\n         label='Test Set Deviance')\nplt.legend(loc='upper right')\nplt.xlabel('Boosting Iterations')\nplt.ylabel('Deviance')\nfig.tight_layout()\nplt.show()\ntest_cat = OrdinalEncoder().fit_transform(test[['Sex', 'SmokingStatus']]) # categorical Encoding \ntest_cat = pd.DataFrame({'Sex': test_cat[:, 0], 'SmokingStatus': test_cat[:, 1]})\ntest_num = StandardScaler().fit_transform(test[['Weeks', 'Percent','Age']])  # standard scaling \ntest_num = pd.DataFrame({'Weeks': test_num[:, 0], 'Percent': test_num[:, 1],'Age':test_num[:,2]})\nXtest = pd.concat([test_cat, test_num], axis = 1)\ny_pred_score = reg.predict(Xtest)\ny_pred_score\npred = pd.DataFrame(y_pred_score,columns = ['FVC'])\npred['Confidence'] = pred['FVC'].std()\nsub = pd.DataFrame({'Patient_Week': sample.Patient_Week, 'FVC': pred['FVC']})\nsub = sub[['Patient_Week', 'FVC',]]\nfilename = 'submission.csv'\nsub['Confidence'] = pred['Confidence']\nsub.to_csv(filename, index=False) \nsub.head()","meta":"{'source': 'AI4Code', 'id': '9457e1bdef5843'}"}
{"id":"4034","text":"\"\"\"\n**Loading Libraries**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport missingno as msno\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix,accuracy_score,classification_report\nimport warnings\nwarnings.filterwarnings('ignore')\nx = pd.read_csv('..\/input\/titanic\/train.csv')\nx\nx.describe().T.style.bar(subset=['mean'], color='#A34843').background_gradient(subset=['std'], cmap='cividis_r').background_gradient(subset=['50%'], cmap='cividis')\nx.isnull().sum()\nmean = x['Age'].mean()\nx['Age'] = x['Age'].fillna(mean)\nx.isnull().sum()\nx.Embarked.describe()\nx.Embarked.fillna('S',inplace=True)\nx.Cabin.describe()\nx.Cabin.fillna('G6',inplace=True)\nx.isnull().sum()\n\"\"\"\n**EDA**\n\"\"\"\nmsno.matrix(x)\nsb.pairplot(x,hue=\"Survived\", palette='flare')\nsb.countplot(data = x, x=\"Sex\", palette=[\"#A939A1\",\"#43C591\"], edgecolor=\"black\", lw=3)\nplt.figure(figsize=(12,8))\nsb.heatmap(x.corr(), cmap='vlag_r', annot=True, linewidth=3)\n\"\"\"\nHere we see \"Fare\" feature has most negative correlation\n\"\"\"\n\"\"\"\n**Preprocessing**\n\"\"\"\ny =x[\"Survived\"] \nx = x.drop(['Survived'], axis=1)\nle = LabelEncoder()\nx.Sex = le.fit_transform(x.Sex)\nx.Name = le.fit_transform(x.Name)\nx.Embarked = le.fit_transform(x.Embarked)\nx.Cabin = le.fit_transform(x.Cabin)\nx.Ticket = le.fit_transform(x.Ticket)\nfit_feat = SelectKBest(score_func=f_classif)\nfit_feat.fit(x,y)\nscore = pd.DataFrame(fit_feat.scores_, columns=['Score Values'])\nscore\nx\nx = x.drop(['PassengerId','Name','Age','SibSp','Parch'], axis=1)\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, train_size=.66, random_state=17)\nsc = StandardScaler()\nxtrain = sc.fit_transform(xtrain)\nxtest = sc.fit_transform(xtest)\nxgb = XGBClassifier()\nxgb.fit(xtrain,ytrain)\n\"\"\"\n**Modeling**\n\"\"\"\nrfc = RandomForestClassifier(n_estimators=400)\nrfc.fit(xtrain,ytrain)\nypred = rfc.predict(xtest)\naccuracy_score(ypred, ytest)\nsb.heatmap(confusion_matrix(ypred,ytest),annot=True, cmap='binary')\nprint(classification_report(ypred,ytest))\nplt.bar(ypred, ytest, color='y')\nplt.xlabel(\"Predicted Value\")\nplt.ylabel(\"Tested Value\")\nplt.title(\"Accuracy Line\")\n\"\"\"\n**Please consider an upvote, if you like this kernel**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0788bb65a207a8'}"}
{"id":"93610","text":"\"\"\"\nthanks to https:\/\/www.kaggle.com\/xhlulu\/siim-covid-19-convert-to-jpg-256px  \nthanks to https:\/\/www.kaggle.com\/awsaf49\/vinbigdata-cxr-ad-yolov5-14-class-infer  \ntrain_study: https:\/\/www.kaggle.com\/h053473666\/siim-covid19-efnb7-train-study  \ntrain_image: https:\/\/www.kaggle.com\/h053473666\/siim-cov19-yolov5-train  \ntrain_2class: https:\/\/www.kaggle.com\/h053473666\/siim-covid19-efnb7-train-fold0-5-2class  \n  \nversion1:Original hyperparameters (yolov5)  \nversion4:New hyperparameters (yolov5)\n\n\"\"\"\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/libjpeg-turbo-2.1.0-h7f98852_0.tar.bz2' -c conda-forge -y\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/libgcc-ng-9.3.0-h2828fa1_19.tar.bz2' -c conda-forge -y\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/gdcm-2.8.9-py37h500ead1_1.tar.bz2' -c conda-forge -y\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/conda-4.10.1-py37h89c1867_0.tar.bz2' -c conda-forge -y\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/certifi-2020.12.5-py37h89c1867_1.tar.bz2' -c conda-forge -y\n!conda install '\/kaggle\/input\/pydicom-conda-helper\/openssl-1.1.1k-h7f98852_0.tar.bz2' -c conda-forge -y\nimport os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm\ndf = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\nif df.shape[0] == 2479:\n#if df.shape[0] == 2477: #orig\n    fast_sub = True\n    print('fast')\n    fast_df = pd.DataFrame(([['00086460a852_study', 'negative 1 0 0 1 1'], \n                         ['000c9c05fd14_study', 'negative 1 0 0 1 1'], \n                         ['65761e66de9f_image', 'none 1 0 0 1 1'], \n                         ['51759b5579bc_image', 'none 1 0 0 1 1']]), \n                       columns=['id', 'PredictionString'])\nelse:\n    fast_sub = False\n    print('slow')\n    \n\n\"\"\"\n# .dcm to .png\n\"\"\"\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    # Original from: https:\/\/www.kaggle.com\/raddar\/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data \/ np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data\ndef resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https:\/\/www.kaggle.com\/xhlulu\/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    \n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        im = im.resize((size, size), resample)\n    \n    return im\n\nsplit = 'test'\nsave_dir = f'\/kaggle\/tmp\/{split}\/'\n\nos.makedirs(save_dir, exist_ok=True)\n\nsave_dir = f'\/kaggle\/tmp\/{split}\/study\/'\nos.makedirs(save_dir, exist_ok=True)\nif fast_sub:\n    xray = read_xray('..\/input\/siim-covid19-detection\/train\/00086460a852\/9e8302230c91\/65761e66de9f.dcm')\n    im = resize(xray, size=600)  \n    study = '00086460a852' + '_study.png'\n    im.save(os.path.join(save_dir, study))\n    xray = read_xray('..\/input\/siim-covid19-detection\/train\/000c9c05fd14\/e555410bd2cd\/51759b5579bc.dcm')\n    im = resize(xray, size=600)  \n    study = '000c9c05fd14' + '_study.png'\n    im.save(os.path.join(save_dir, study))\nelse:   \n    for dirname, _, filenames in tqdm(os.walk(f'..\/input\/siim-covid19-detection\/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=600)\n            study = dirname.split('\/')[-2] + '_study.png'\n            im.save(os.path.join(save_dir, study))\n\nimage_id = []\ndim0 = []\ndim1 = []\nsplits = []\nsave_dir = f'\/kaggle\/tmp\/{split}\/image\/'\nos.makedirs(save_dir, exist_ok=True)\nif fast_sub:\n    xray = read_xray('..\/input\/siim-covid19-detection\/train\/00086460a852\/9e8302230c91\/65761e66de9f.dcm')\n    im = resize(xray, size=512)  \n    im.save(os.path.join(save_dir,'65761e66de9f_image.png'))\n    image_id.append('65761e66de9f.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\n    xray = read_xray('..\/input\/siim-covid19-detection\/train\/000c9c05fd14\/e555410bd2cd\/51759b5579bc.dcm')\n    im = resize(xray, size=512)  \n    im.save(os.path.join(save_dir, '51759b5579bc_image.png'))\n    image_id.append('51759b5579bc.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\nelse:\n    for dirname, _, filenames in tqdm(os.walk(f'..\/input\/siim-covid19-detection\/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=512)  \n            im.save(os.path.join(save_dir, file.replace('.dcm', '_image.png')))\n            image_id.append(file.replace('.dcm', ''))\n            dim0.append(xray.shape[0])\n            dim1.append(xray.shape[1])\n            splits.append(split)\nmeta = pd.DataFrame.from_dict({'image_id': image_id, 'dim0': dim0, 'dim1': dim1, 'split': splits})\n\"\"\"\n# study predict\n\"\"\"\nimport numpy as np \nimport pandas as pd\nif fast_sub:\n    df = fast_df.copy()\nelse:\n    df = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\nid_laststr_list  = []\nfor i in range(df.shape[0]):\n    id_laststr_list.append(df.loc[i,'id'][-1])\ndf['id_last_str'] = id_laststr_list\n\nstudy_len = df[df['id_last_str'] == 'y'].shape[0]\nimport tensorflow_hub as hub\n# Build model\nhub_url = '\/kaggle\/input\/efficientnetv2-tf-hub\/efficientnetv2-l-21k-ft1k\/feature-vector'\nimage_size = 600\n!pip install \/kaggle\/input\/kerasapplications -q\n!pip install \/kaggle\/input\/efficientnet-keras-source-code\/ -q --no-deps\n\nimport os\n\nimport efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndef auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n\n    return strategy\n\n\ndef build_decoder(with_labels=True, target_size=(300, 300), ext='jpg'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.cast(img, tf.float32) \/ 255.0\n        img = tf.image.resize(img, target_size)\n\n        return img\n\n    def decode_with_labels(path, label):\n        return decode(path), label\n\n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        return img\n\n    def augment_with_labels(img, label):\n        return augment(img), label\n\n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, bsize=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\"):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n\n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n\n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n\n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n\n    dset = tf.data.Dataset.from_tensor_slices(slices)\n    dset = dset.map(decode_fn, num_parallel_calls=AUTO)\n    dset = dset.cache(cache_dir) if cache else dset\n    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset\n    dset = dset.repeat() if repeat else dset\n    dset = dset.shuffle(shuffle) if shuffle else dset\n    dset = dset.batch(bsize).prefetch(AUTO)\n\n    return dset\n\n#COMPETITION_NAME = \"siim-cov19-test-img512-study-600\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\n\n#load_dir = f\"\/kaggle\/input\/{COMPETITION_NAME}\/\"\nif fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\nsub_df = sub_df[:study_len]\ntest_paths = f'\/kaggle\/tmp\/{split}\/study\/' + sub_df['id'] +'.png'\n\nsub_df['negative'] = 0\nsub_df['typical'] = 0\nsub_df['indeterminate'] = 0\nsub_df['atypical'] = 0\n\n\nlabel_cols = sub_df.columns[2:]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[7], IMSIZE[7]), ext='png')\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder\n)\n\nimage_size = 600\nbatch_size = BATCH_SIZE\nlabels = [\"negative\", \"typical\", \"indeterminate\", \"atypical\"]\n\nwith strategy.scope():\n    \n    models = []\n    \n    #models0 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models0.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model0.h5')\n    #models1 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models1.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model1.h5')\n    #models2 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models2.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model2.h5')\n    #models3 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models3.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model3.h5')\n    #models4 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models4.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model4.h5')\n    \n    models5 = tf.keras.models.load_model(\n        '..\/input\/b7600stra216m01\/model0.h5'\n    )\n    models6 = tf.keras.models.load_model(\n        '..\/input\/b7600stra216m01\/model1.h5'\n    )\n    models7 = tf.keras.models.load_model(\n        '..\/input\/b7600stra216m01\/model2.h5'\n    )\n    models8 = tf.keras.models.load_model(\n        '..\/input\/b7600stra216m01\/model3.h5'\n    )\n    models9 = tf.keras.models.load_model(\n        '..\/input\/b7600stra216m01\/model4.h5'\n    )\n    models0 = tf.keras.models.load_model(\n        '..\/input\/covid19detection-first-notebook\/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '..\/input\/covid19detection-first-notebook\/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '..\/input\/covid19detection-first-notebook\/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '..\/input\/covid19detection-first-notebook\/model3.h5'\n    )\n    \n    models.append(models0)\n    models.append(models1)\n    models.append(models2)\n    models.append(models3)\n    #models.append(models4)\n    models.append(models5)\n    models.append(models6)\n    models.append(models7)\n    models.append(models8)\n    models.append(models9)\n\n    \n    \n    \nsub_df[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) \/ len(models)\ndel models\ndel models0, models1, models2, models3, models5,models6,models7,models8,models9\n#del models0, models1, models2, models3, models4\nsub_df.columns = ['id', 'PredictionString1', 'negative', 'typical', 'indeterminate', 'atypical']\ndf = pd.merge(df, sub_df, on = 'id', how = 'left')\n\"\"\"\n# study string\n\"\"\"\nfor i in range(study_len):\n    negative = df.loc[i,'negative']\n    typical = df.loc[i,'typical']\n    indeterminate = df.loc[i,'indeterminate']\n    atypical = df.loc[i,'atypical']\n    df.loc[i, 'PredictionString'] = f'negative {negative} 0 0 1 1 typical {typical} 0 0 1 1 indeterminate {indeterminate} 0 0 1 1 atypical {atypical} 0 0 1 1'\ndf_study = df[['id', 'PredictionString']]\n\n# df.to_csv('submission.csv',index=False)\n# df\n\"\"\"\n# 2 class\n\"\"\"\nif fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\nsub_df = sub_df[study_len:]\ntest_paths = f'\/kaggle\/tmp\/{split}\/image\/' + sub_df['id'] +'.png'\nsub_df['none'] = 0\n\nlabel_cols = sub_df.columns[2]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[7], IMSIZE[7]), ext='png')\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder\n)\n\nwith strategy.scope():\n    \n    models = []\n    \n    #models0 = tf.keras.models.load_model(\n    #    '..\/input\/effv2l-covid19detection-kf-stratified-2ndclass\/model0.h5'\n    #)\n    #models1 = tf.keras.models.load_model(\n    #    '..\/input\/effv2l-covid19detection-kf-stratified-2ndclass\/model1.h5'\n    #)\n    #models2 = tf.keras.models.load_model(\n    #    '..\/input\/effv2l-covid19detection-kf-stratified-2ndclass\/model2.h5'\n    #)\n    #models3 = tf.keras.models.load_model(\n    #    '..\/input\/effv2l-covid19detection-kf-stratified-2ndclass\/model3.h5'\n    #)\n    #models4 = tf.keras.models.load_model(\n    #    '..\/input\/effv2l-covid19detection-kf-stratified-2ndclass\/model4.h5'\n    #)\n    #models0 = tf.keras.Sequential([\n    #        # Explicitly define the input shape so the model can be properly\n    #        # loaded by the TFLiteConverter\n    #        tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n    #            hub.KerasLayer(hub_url, trainable=False),\n    #        tf.keras.layers.Dropout(rate=0.2),\n    #        tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='softmax')\n    #    ])\n    #models0.load_weights('..\/input\/effv2-covid19detection-kf-stratified\/model0.h5')\n    \n    models0 = tf.keras.Sequential([\n            # Explicitly define the input shape so the model can be properly\n            # loaded by the TFLiteConverter\n            tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n                hub.KerasLayer(hub_url, trainable=False),\n            tf.keras.layers.Dropout(rate=0.2),\n            tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='sigmoid')\n        ])\n    models0.load_weights('..\/input\/effv221k-c19-kf-str-2ndcl\/model0.h5')\n    models1 = tf.keras.Sequential([\n            # Explicitly define the input shape so the model can be properly\n            # loaded by the TFLiteConverter\n            tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n                hub.KerasLayer(hub_url, trainable=False),\n            tf.keras.layers.Dropout(rate=0.2),\n            tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='sigmoid')\n        ])\n    models1.load_weights('..\/input\/effv221k-c19-kf-str-2ndcl\/model1.h5')\n    models2 = tf.keras.Sequential([\n            # Explicitly define the input shape so the model can be properly\n            # loaded by the TFLiteConverter\n            tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n                hub.KerasLayer(hub_url, trainable=False),\n            tf.keras.layers.Dropout(rate=0.2),\n            tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='sigmoid')\n        ])\n    models2.load_weights('..\/input\/effv221k-c19-kf-str-2ndcl\/model2.h5')\n    models3 = tf.keras.Sequential([\n            # Explicitly define the input shape so the model can be properly\n            # loaded by the TFLiteConverter\n            tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n                hub.KerasLayer(hub_url, trainable=False),\n            tf.keras.layers.Dropout(rate=0.2),\n            tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='sigmoid')\n        ])\n    models3.load_weights('..\/input\/effv221k-c19-kf-str-2ndcl\/model3.h5')\n    models4 = tf.keras.Sequential([\n            # Explicitly define the input shape so the model can be properly\n            # loaded by the TFLiteConverter\n            tf.keras.layers.InputLayer(input_shape=[image_size, image_size, 3]),\n                hub.KerasLayer(hub_url, trainable=False),\n            tf.keras.layers.Dropout(rate=0.2),\n            tf.keras.layers.Dense(len(labels),kernel_regularizer=tf.keras.regularizers.l2(0.0001),activation='sigmoid')\n        ])\n    models4.load_weights('..\/input\/effv221k-c19-kf-str-2ndcl\/model4.h5')\n \n    \n    models.append(models0)\n    models.append(models1)\n    models.append(models2)\n    models.append(models3)\n    models.append(models4)\n\n    \n    \n    \nsub_df[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) \/ len(models)\ndf_2class = sub_df.reset_index(drop=True)\ndel models\ndel models0, models1, models2, models3, models4\nfrom numba import cuda\nimport torch\ncuda.select_device(0)\ncuda.close()\ncuda.select_device(0)\n\"\"\"\n# yolov5 predict\n\"\"\"\nimport numpy as np, pandas as pd\nfrom glob import glob\nimport shutil, os\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GroupKFold\nfrom tqdm.notebook import tqdm\nimport seaborn as sns\nimport torch\nmeta = meta[meta['split'] == 'test']\nif fast_sub:\n    test_df = fast_df.copy()\nelse:\n    test_df = pd.read_csv('..\/input\/siim-covid19-detection\/sample_submission.csv')\ntest_df = df[study_len:].reset_index(drop=True) \nmeta['image_id'] = meta['image_id'] + '_image'\nmeta.columns = ['id', 'dim0', 'dim1', 'split']\ntest_df = pd.merge(test_df, meta, on = 'id', how = 'left')\n\ndim = 512 #1024, 256, 'original'\ntest_dir = f'\/kaggle\/tmp\/{split}\/image'\nweights_dir = '\/kaggle\/input\/siim-cov19-yolov5-train\/yolov5\/runs\/train\/exp\/weights\/best.pt'\n\nshutil.copytree('\/kaggle\/input\/yolov5-official-v31-dataset\/yolov5', '\/kaggle\/working\/yolov5')\nos.chdir('\/kaggle\/working\/yolov5') # install dependencies\n\nimport torch\n#from IPython.display import Image, clear_output  # to display images\n\n#clear_output()\n#print('Setup complete. Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))\n_det_model_path='..\/input\/covid19-det\/'\npath_1=\"\/kaggle\/input\/covid19-det\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_2=\"\/kaggle\/input\/covid19-det\/kaggle-siim-covid\/exp2\/weights\/best.pt\"\npath_3=\"\/kaggle\/input\/covid19-det\/kaggle-siim-covid\/exp3\/weights\/best.pt\"\npath_4=\"\/kaggle\/input\/covid19-det\/kaggle-siim-covid\/exp4\/weights\/best.pt\"\npath_5=\"\/kaggle\/input\/covid19-det\/kaggle-siim-covid\/exp5\/weights\/best.pt\"\n\npath_6=  \"\/kaggle\/input\/yoloxm01\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_7=  \"\/kaggle\/input\/covid19-det-x-m1\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_8=  \"\/kaggle\/input\/covid19-det-x-m2\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_9=  \"\/kaggle\/input\/covid19-det-x-m3\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_10= \"\/kaggle\/input\/covid19-det-x-m4\/kaggle-siim-covid\/exp\/weights\/best.pt\"\n\npath_11= \"\/kaggle\/input\/yolov5lm02\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_12= \"\/kaggle\/input\/yolov5lm02\/kaggle-siim-covid\/exp2\/weights\/best.pt\"\npath_13= \"\/kaggle\/input\/covid19-det-yolo-l-m4y5\/kaggle-siim-covid\/exp\/weights\/best.pt\"\npath_14= \"\/kaggle\/input\/covid19-det-yolo-l-m4y5\/kaggle-siim-covid\/exp2\/weights\/best.pt\"\n\n\nMODEL_PATH = path_1 + \" \" + path_2 + \" \" + path_3 + \" \" + path_4 + \" \" + path_5 + \" \" + path_6 + \" \" + path_7 + \" \" + path_8 + \" \" + path_9 + \" \" + path_10 + \" \" + path_11 + \" \" + path_12 + \" \" + path_13 + \" \" + path_14 \nMODEL_PATH\n\n_test_files_path = \"\/kaggle\/input\/covid19512\/test\/\"\nMODEL_PATH\n_data_dir = \"\/kaggle\/input\/covid19512\/\"\n\n\n!python detect.py --weights {MODEL_PATH} \\\n                  --source $test_dir\\\n                  --img 512 \\\n                  --conf 0.001 \\\n                  --iou-thres 0.5 \\\n                  --augment \\\n                  --save-txt \\\n                  --save-conf\n\n\ndef yolo2voc(image_height, image_width, bboxes):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    voc  => [x1, y1, x2, y1]\n\n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n\n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]\/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n\n    return bboxes\n\ntest_df\nimage_ids = []\nPredictionStrings = []\nmeta_df = pd.read_csv(_data_dir + \"meta.csv\")\n\n#for file_path in tqdm(glob('runs\/detect\/exp\/labels\/*.txt')):\nfor dir_path, _, filenames in os.walk(test_dir):\n        print(len(filenames))\nfor file in filenames:\n    file_path = 'runs\/detect\/exp\/labels\/' + file.replace(\".png\", '.txt')\n    \n    image_id = file_path.split('\/')[-1].split('.')[0]\n    w, h = test_df.loc[test_df.id==image_id,['dim1', 'dim0']].values[0]\n    #w, h = meta_df.loc[meta_df.image_id == image_id,['dim1', 'dim0']].values[0]\n\n    f = open(file_path, 'r')\n    data = np.array(f.read().replace('\\n', ' ').strip().split(' ')).astype(np.float32).reshape(-1, 6)\n    data = data[:, [0, 5, 1, 2, 3, 4]]\n    bboxes = list(np.round(np.concatenate((data[:, :2], np.round(yolo2voc(h, w, data[:, 2:]))), axis =1).reshape(-1), 12).astype(str))\n    for idx in range(len(bboxes)):\n        bboxes[idx] = str(int(float(bboxes[idx]))) if idx%6!=1 else bboxes[idx]\n    image_ids.append(image_id)\n    PredictionStrings.append(' '.join(bboxes))\n\n\npred_df = pd.DataFrame({'id':image_ids,\n                        'PredictionString':PredictionStrings})\ntest_df = test_df.drop(['PredictionString'], axis=1)\nsub_df = pd.merge(test_df, pred_df, on = 'id', how = 'left').fillna(\"none 1 0 0 1 1\")\nsub_df = sub_df[['id', 'PredictionString']]\nfor i in range(sub_df.shape[0]):\n    if sub_df.loc[i,'PredictionString'] == \"none 1 0 0 1 1\":\n        continue\n    sub_df_split = sub_df.loc[i,'PredictionString'].split()\n    sub_df_list = []\n    for j in range(int(len(sub_df_split) \/ 6)):\n        sub_df_list.append('opacity')\n        sub_df_list.append(sub_df_split[6 * j + 1])\n        sub_df_list.append(sub_df_split[6 * j + 2])\n        sub_df_list.append(sub_df_split[6 * j + 3])\n        sub_df_list.append(sub_df_split[6 * j + 4])\n        sub_df_list.append(sub_df_split[6 * j + 5])\n    sub_df.loc[i,'PredictionString'] = ' '.join(sub_df_list)\nsub_df['none'] = df_2class['none'] \nfor i in range(sub_df.shape[0]):\n    if sub_df.loc[i,'PredictionString'] != 'none 1 0 0 1 1':\n        sub_df.loc[i,'PredictionString'] = sub_df.loc[i,'PredictionString'] + ' none ' + str(sub_df.loc[i,'none']) + ' 0 0 1 1'\nsub_df = sub_df[['id', 'PredictionString']]   \ndf_study = df_study[:study_len]\ndf_study = df_study.append(sub_df).reset_index(drop=True)\ndf_study.to_csv('\/kaggle\/working\/submission.csv',index = False)  \nshutil.rmtree('\/kaggle\/working\/yolov5')\ndf_study","meta":"{'source': 'AI4Code', 'id': 'abd01e48954a8d'}"}
{"id":"87432","text":"\"\"\"\n# Overview\n\n>P.S. I decided to write this in Bahasa since there already exist many resources using English, but just very few ones in Bahasa. Hopefully by using Bahasa, local people (especially newbies like me) can understand it better and faster :) \n\n\nDi notebook ini saya akan berbagi pengalaman\/proyek saya terkait pembangunan sistem rekomendasi menggunakan beberapa teknik. Asumsi saya, pembaca sudah memahami sedikit mengenai konsep sistem rekomendasi. \n\nSistem rekomendasi bisa dikategorikan sebagai *Supervised Learning* karena memiliki target kelas yang akan diprediksi. Pendekatan yang saya gunakan pada pembangunan sistem rekomendasi kali ini yaitu *multi-class prediction*, dimana untuk masing-masing pasangan *item*-pengguna akan diprediksi berapa *rating* yang akan diberikan, dengan *range* 1 - 5.\n\nData yang saya gunakan yaitu data [Yelp Academic dataset version 6](https:\/\/www.kaggle.com\/yelp-dataset\/yelp-dataset\/version\/6), disediakan oleh Yelp yang merupakan platform review berbagai bisnis di Amerika Serikat. Untuk versi terbaru (version 9) juga sudah tersedia, namun karena keterbatasan *resources* pada Kaggle, pada notebook ini saya masih menggunakan versi 6 dengan data yang lebih sedikit.\n\"\"\"\n\"\"\"\n# Business Understanding\n\nSistem rekomendasi menjadi salah satu *tool* untuk menyajikan informasi yang sesuai dengan preferensi pengguna. Pada use case kali ini, akan dilakukan rekomendasi terhadap restoran. Rekomendasi akan dilakukan dengan memanfaatkan data historis review\/ulasan serta penilaian pengguna yang telah dilakukan sebelumnya. Dari data ini, dapat diprediksi bagaimana preferensi pengguna terhadap restoran-restoran lain yang terdapat pada platform tersebut. Restoran yang diprediksi memiliki *rating* yang tinggi akan disajikan sebagai rekomendasi terhadap user terkait\n\"\"\"\n\"\"\"\n# Data Understanding\n\nData yang akan dimanfaatkan yaitu data informasi terkait bisnis, pengguna, serta data ulasan terkait.\n\nPertama kita mulai dengan membaca dan menyimpan data-data tersebut ke *dataframe* pandas\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport json\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n## Business Data\n\"\"\"\n# Membaca data bisnis\nbiz=pd.read_csv('\/kaggle\/input\/yelpversion6\/yelp_business.csv')\nbiz.head()\nbiz.shape\n\"\"\"\nterdapat 174.567 data bisnis dengan 13 atribut\n\"\"\"\n\"\"\"\n### Memilih sebagian data \n\nkali ini kita akan mencoba  membangun rekomendasi hanya untuk bisnis **restoran**, sehingga data yang ada perlu di-*filter* dulu.\n\nkarena kolom kategori terdiri dari beberapa jenis, kita akan membaginya (split) menjadi satu kolom per kategori \n\"\"\"\n#memisahkan masing-masing kategori ke kolom berbeda\ndf_category_split = biz['categories'].str.split(';', expand=True)[[0,1,2]]\n\n# nama kolom yang baru\ndf_category_split.columns = ['category_1', 'category_2', 'category_3']\nbiz = pd.concat([biz, df_category_split], axis=1)\n\n# menghapus kolom lama 'categories'\nbiz = biz.drop(['categories'], axis=1)\nbiz.head()\n\"\"\"\nSetelah membagi kategori ke masing-masing kolom, kita akan melakukan *filter* pada data, disini kita akan memilih data **Restaurants** di *state* **PA (Pennsylvania)** dengan status *is_open* **True \/ 1**\n\"\"\"\n# Filter dataset, 'kategori: Restaurants, 'state': PA, dan 'is_open' : 1\nresto = biz.loc[(biz['category_1'] == 'Restaurants') | (biz['category_2'] == 'Restaurants') | (biz['category_3'] == 'Restaurants')]\nresto = resto.loc[(resto['state'] == 'PA')]\nresto = resto.loc[(resto['is_open'] == 1)]\nprint(resto.shape)\n\n\"\"\"\nuntuk meminimalisir memori, kita bisa menghapus data biz awal yang sudah tidak lagi digunakan\n\"\"\"\n#menghapus variabel yang tidak digunakan dan garbage collection\ndel biz\n\nimport gc\ngc.collect()\n\n\"\"\"\nkemudian, kita akan memilih kolom-kolom yang akan digunakan. Disini kita akan memanfaatkan 3 kolom saja, yaitu **business_id, review_count, stars** \n\"\"\"\nresto.head()\n#menghapus kolom yang tidak digunakan\nresto=resto.drop(['name', 'neighborhood', 'address', 'city', 'state',\n       'postal_code', 'latitude', 'longitude','is_open', 'category_1', 'category_2', 'category_3'],axis=1)\nresto.reset_index(drop=True, inplace=True)\nprint(resto.info())\nresto.head()\n\"\"\"\nData resto final yang kita gunakan adalah data di atas \n\"\"\"\n\"\"\"\n## Users Data\n\"\"\"\n# Membaca data user\nuser=pd.read_csv('\/kaggle\/input\/yelpversion6\/yelp_user.csv')\nuser.head()\n\nprint(user.shape)\n\"\"\"\n### Memilih sebagian data \n\nSama dengan sebelumnya, kali ini kita akan mem-*filter* data user. kolom *name* tidak akan digunakan. Selain itu ada baris yang akan kita buang, yaitu data **user yang tidak pernah melakukan review** (review_count=0) \n\"\"\"\n## Filter dataset\n\n# Menghapus kolom 'name'\nuser=user.drop('name',axis=1)\n\n# Memilih data user yang review_count nya >0\nuser = user.loc[(user['review_count'] > 0)]\nprint(user.shape)\nprint(user.info())\nuser.head()\n\"\"\"\n## Reviews Data\n\"\"\"\n# Membaca data review\nreviews=pd.read_csv('yelp_review.csv')\nreviews.head()\nprint(reviews.shape)\nreviews.columns\n\"\"\"\nDisini kita tidak memanfaatkan informasi 'text', sehingga kolom tersebut akan dihapus\n\"\"\"\nreviews=reviews.drop('text',axis=1)\n\"\"\"\n## Joined Data\n\"\"\"\n\"\"\"\nKetiga *dataframe* ini yaitu **resto, user, dan review** perlu digabung menjadi satu *dataframe*. Hal ini dilakukan dengan *inner join* atau *merge* yang akan menghubungkan ketiga data tersebut berdasarkan id nya\n\"\"\"\n#join resto dan reviews\nyelp_join=pd.merge(resto,reviews,on='business_id',how='inner')\n\n#join resto, reviews dengan user\nyelp_join=pd.merge(yelp_join,user,on='user_id',how='inner')\nprint(yelp_join.shape)\nyelp_join.head()\n#menghapus variabel yang tidak digunakan dan garbage collection\ndel resto\ndel reviews\ndel user\n\nimport gc\ngc.collect()\n\nyelp_join.head()\n\"\"\"\n# Data Preparation\n\nSelanjutnya kita masuk ke tahap data preparation, yaitu menyiapkan data sehingga sesuai dengan kebutuhan model\n\nPertama, perlu dilakukan beberapa penyesuaian terhadap tipe data\n\"\"\"\nprint(yelp_join.dtypes)\n\n#tipe data datetime\nyelp_join['date']=pd.to_datetime(yelp_join['date'])\nyelp_join['yelping_since']=pd.to_datetime(yelp_join['yelping_since'])\n\"\"\"\nUntuk masing-masing id yang bertipe string, akan dilakukan perubahan (index) menjadi id bertipe integer, yang dilakukan untuk penyederhanaan serta minimalisir memori \n\"\"\"\n#indexing id to number for simplicity\nbizID = pd.Categorical((pd.factorize(yelp_join.business_id)[0] + 1))\nuserID = pd.Categorical((pd.factorize(yelp_join.user_id)[0] + 1))\nreviewID = pd.Categorical((pd.factorize(yelp_join.review_id)[0] + 1))\n\nbizID=bizID.astype(int)\nuserID=userID.astype(int)\nreviewID=reviewID.astype(int)\n\nyelp_join['business_id']=bizID\nyelp_join['user_id']=userID\nyelp_join['review_id']=reviewID\n\"\"\"\nSetelah itu dilakukan penyaringan untuk data yang tidak valid atau tidak sesuai dengan kebutuhan model. Diantaranya yaitu:\n1. Data dengan tanggal review **(date)** lebih awal dibandingkan tanggal mendaftar **(yelping_since)** dianggap tidak valid, sehingga tidak disertakan dalam observasi\n2. \n\"\"\"\n## Filter dataset\n# Menghapus  incosistency: review date < yelping since\nyelp_join = yelp_join.loc[((yelp_join['date'] > yelp_join['yelping_since']) == True)]\nprint(yelp_join.shape)\nprint(yelp_join.shape)\nyelp_join.head()\nprint(yelp_join.business_id.nunique())\nprint(yelp_join.user_id.nunique())\nyelp_join['user_id'].value_counts()\nyelp_join['business_id'].value_counts()\n\"\"\"\n## Filtering data : >1 user reviewing and >1 business reviewed\n\"\"\"\nmin_resto_ratings = 1\nfilter_resto = yelp_join['business_id'].value_counts() > 1\nfilter_resto = filter_resto[filter_resto].index.tolist()\n\nmin_user_ratings = 1\nfilter_users = df_new['user_id'].value_counts() > min_user_ratings\nfilter_users = filter_users[filter_users].index.tolist()\n\ndf_new = yelp_join[(yelp_join['business_id'].isin(filter_resto)) & (yelp_join['user_id'].isin(filter_users))]\nprint('The original data frame shape:\\t{}'.format(yelp_join.shape))\nprint('The new data frame shape:\\t{}'.format(df_new.shape))\nprint(yelp_join.business_id.nunique())\nprint(yelp_join.user_id.nunique())\nyelp_join.head()\n\"\"\"\n## Exporting data for collaborative filtering (PENDING)\n\"\"\"\ncf=yelp_join\nprint(yelp_join.shape)\nyelp_join.columns\n#drop unused columns\n#cf = cf.drop(['business_id'], axis=1)\ncf = cf.drop(['stars_x'], axis=1)\ncf = cf.drop(['review_count_x'], axis=1)\n#cf = cf.drop(['review_id'], axis=1)\n#cf = cf.drop(['user_id'], axis=1)\ncf = cf.drop(['date'], axis=1)\ncf = cf.drop(['useful_x'], axis=1)\ncf = cf.drop(['funny_x'], axis=1)\ncf = cf.drop(['cool_x'], axis=1)\ncf = cf.drop(['review_count_y'], axis=1)\ncf = cf.drop(['yelping_since'], axis=1)\ncf = cf.drop(['friends'], axis=1)\ncf = cf.drop(['cool_y'], axis=1)\ncf = cf.drop(['useful_y'], axis=1)\ncf = cf.drop(['funny_y'], axis=1)\ncf = cf.drop(['fans'], axis=1)\ncf = cf.drop(['elite'], axis=1)\ncf = cf.drop(['average_stars'], axis=1)\ncf = cf.drop(['compliment_hot'], axis=1)\ncf = cf.drop(['compliment_more'], axis=1)\ncf = cf.drop(['compliment_profile'], axis=1)\ncf = cf.drop(['compliment_cute'], axis=1)\ncf = cf.drop(['compliment_list'], axis=1)\ncf = cf.drop(['compliment_note'], axis=1)\ncf = cf.drop(['compliment_plain'], axis=1)\ncf = cf.drop(['compliment_cool'], axis=1)\ncf = cf.drop(['compliment_funny'], axis=1)\ncf = cf.drop(['compliment_writer'], axis=1)\ncf = cf.drop(['compliment_photos'], axis=1)\ncf.columns\ncf.to_csv('collaborative.csv')\n\"\"\"\n## Data Exploration\n\"\"\"\nimport matplotlib.pyplot as plt\nprint(yelp_join.shape)\nyelp_join.head()\nyelp_join.dtypes\n\"\"\"\n### Rating Distribution\n\"\"\"\nyelp_join=predictor\nstars=yelp_join['rating'].value_counts()\nstars=stars.to_frame().reset_index()\nstars.columns=['rating','count']\nprint(stars)\nstars.sort_values(by=['rating'],ascending=True).plot.bar(x='rating',y='count')\n\"\"\"\n### Yelping Since\n\"\"\"\nyr=yelp_join.groupby('yelping_since')[['user_id']].count()\nyr\n# df is defined in the previous example\n\n# step 1: create a 'year' column\nyelp_join['year_of_yelping'] = yelp_join['yelping_since'].map(lambda x: x.strftime('%Y'))\n\n# step 2: group by the created columns\ngrouped_df = yelp_join.groupby('year_of_yelping')[['user_id']].count()\n\ngrouped_df\n\nyr=grouped_df.reset_index()\nyr\nyr.plot.bar(x='year_of_yelping',y='user_id')\n\"\"\"\n### Review Date\n\"\"\"\nyr=yelp_join.groupby('date')[['review_id']].count()\nyr\n# df is defined in the previous example\n\n# step 1: create a 'year' column\nyelp_join['year_of_review'] = yelp_join['date'].map(lambda x: x.strftime('%Y'))\n\n# step 2: group by the created columns\ngrouped_df = yelp_join.groupby('year_of_review')[['review_id']].count()\n\ngrouped_df\n\nyr=grouped_df.reset_index()\nyr\nyr.plot.bar(x='year_of_review',y='review_id')\n\"\"\"\n### User\n\"\"\"\nus=yelp_join.groupby('user_id')[['business_id']].count()\nus\nus=yelp_join.groupby('user_id')[['review_id']].count()\nus\n\"\"\"\n## Filtering Dataset\n\"\"\"\n\"\"\"\n### Review Date\n\"\"\"\nyelp_join.shape\n# Only the last 3 years\n#yelp_join=yelp_join.loc[(yelp_join['date'] >= '2005-10-01')]\nsdfsd=yelp_join.loc[(yelp_join['date'] >= '2005-10-01')]\n#yelp_join.shape\n#x=yelp_join.loc[(yelp_join['date'] >= '2015-01-01')]\n#x=x.loc[(x['yelping_since'] <'2015-02-01')]\nprint(sdfsd['date'].sort_values(ascending=True))\nyelp_join=yelp_join.loc[(yelp_join['date'] < '2015-01-01')]\nyelp_join.shape\nyelp_join.shape\nprint(yelp_join.business_id.nunique())\nprint(yelp_join.user_id.nunique())\n\"\"\"\n### Yelping Since\n\"\"\"\n#x=yelp_join.loc[(yelp_join['yelping_since'] >= '2015-01-01')]\nx=yelp_join.loc[(yelp_join['yelping_since'] <'2015-01-01')]\nprint(x['yelping_since'].sort_values(ascending=True))\nprint(x.shape)\nyelp_join=yelp_join.loc[(yelp_join['yelping_since'] < '2015-02-01')]\nyelp_join.shape\nprint(yelp_join['yelping_since'].sort_values(ascending=False))\n\"\"\"\n## Derived Columns\n\"\"\"\nyelp_join['no_friends']=0\nyelp_join.loc[yelp_join['friends'] == 'None', ['no_friends']] = 1\nyelp_join\nyelp_join.shape\nyelp_join['year_of_yelping']=yelp_join['year_of_yelping'].astype(int)\nyelp_join['year_of_review']=yelp_join['year_of_review'].astype(int)\nyelp_join.dtypes\n#Check check\n\n#check recent date\nprint(yelp_join[['date','yelping_since','review_id']].sort_values(by='date',ascending=False).head())\n#print(yelp_join['date'].loc[yelp_join['index']==29524])\nfrom datetime import datetime\n\nd_base = datetime(2015, 1, 1)\nprint(d_base)\nprint(yelp_join['date'].loc[yelp_join['review_id']==53024])\ndays=(d_base-(yelp_join['date'].loc[yelp_join['review_id']==53024]))\nprint(days)\nyelp_join.shape\nyelp_join.columns\n#derive columns\ndf = pd.DataFrame([])\nfor index, row in yelp_join.iterrows():\n    #total friends\n    number=row['friends'].count(\",\")+1\n    #days been yelping since\n    days=(d_base-row['yelping_since']).days\n    #total compliments\n    compnum=row['compliment_hot']+row['compliment_more']+row['compliment_cute']+row['compliment_note']+row['compliment_cool']+row['compliment_funny']+row['compliment_writer']+row['compliment_photos']\n    #total votes per user\n    votes=row['funny_y']+row['useful_y']+row['cool_y']\n    #review age\n    age=(d_base-row['date']).days\n    print(days)\n    df = df.append(pd.Series([row['review_id'],row['no_friends'],number,compnum,days,age,votes]),ignore_index=True)\n    \ndf.columns=['review_id','no_friends','total_friends','total_compliments','days_since','review_age','total_votes']\ndf.shape\n\ndf.head()\ndf.shape\ndf.loc[df['no_friends'] == 1, ['total_friends']] = 0\ndf = df.drop(['no_friends'], axis=1)\nyelp_join=pd.merge(yelp_join,df,on='review_id',how='inner')\nyelp_join.shape\nyelp_join.head()\nprint(yelp_join[['date','review_age','review_id']].sort_values(by='date',ascending=False).head())\nprint(yelp_join[['yelping_since','days_since','review_id']].sort_values(by='yelping_since',ascending=False).head())\nyelp_join=yelp_join.rename(columns={\"stars_x\": \"biz_avg_rating\",\n                          \"review_count_x\": \"biz_total_rvw\",\n                          \"stars_y\": \"rating\",\n                          \"useful_x\": \"review_useful\",\n                          \"funny_x\": \"review_funny\",\n                          \"cool_x\": \"review_cool\",\n                          \"review_count_y\": \"user_total_rvw\",\n                          \"average_stars\" : \"user_avg_rating\",\n                         })\nyelp_join['elite']\nz=yelp_join.describe()\nz\nz.to_csv('descriptive-stats.csv')\n#2019-07-27 17:36\nskew=yelp_join.skew(axis=0,numeric_only=True)\nskew.to_csv('skew.csv')\n#2019-07-27 17:36\n#export data to master file\nyelp_join.to_csv('yelp_join_added_columns.csv')\n#2019-07-27 17:36\nyelp_join.head()\n#Read data from file\nyelp_join=pd.read_csv('yelp_join_added_columns.csv',index_col=0)\nyelp_join.head()\n\"\"\"\n## Additional\n\"\"\"\nyelp_join.business_id.nunique()\n#for recent-ness column of item\nbizpopularity=yelp_join.groupby('business_id')[['review_age']].mean()\nbizpopularity\nyelp_join=pd.merge(yelp_join,bizpopularity,on='business_id',how='inner')\nyelp_join.head()\nyelp_join.shape\nyelp_join.columns\n#review metadata columns for user feature\nuserreview=yelp_join[['review_id','user_id','review_useful','review_funny','review_cool','user_total_rvw']]\n#c=userreview.groupby('user_id')[['cool_y','funny_y','useful_y','review_count_y']].mean()\nuserreview.sort_values(by='user_id')\nyelp_join.business_id.nunique()\nc=userreview.groupby('user_id').agg({'review_useful' : 'sum','review_funny' : 'sum','review_cool' : 'sum'})\nc\nyelp_join=pd.merge(yelp_join,c,on='user_id',how='inner')\nyelp_join.head()\nyelp_join.shape\nyelp_join.columns\nyelp_join.shape\nyelp_join.columns\n\"\"\"\n## Final\n\"\"\"\nprint(yelp_join.shape)\nprint(yelp_join.business_id.nunique())\nprint(yelp_join.user_id.nunique())\nyelp_join.groupby(['business_id','user_id']).size()\n\n#export\nyelp_join.to_csv('resto_full.csv')\n#2019-07-27 18:36\n#import\nimport pandas as pd\nyelp_join=pd.read_csv('resto_full.csv',index_col=0)\nyelp_join.columns\nyelp_join.shape\n\"\"\"\n# Separate Users\n\"\"\"\n\"\"\"\n## Test data\n\"\"\"\nz=yelp_join.groupby('user_id').agg({'review_id' : 'count'})\nz=z.sort_values(by='review_id',ascending=True)\nz\nz.to_csv('user-review-count.csv')\nz.describe()\n##Split test user, top 10%\nfrom sklearn.model_selection import train_test_split\nuser_train, user_test = train_test_split(z,test_size=0.1,shuffle=False)\nuser_test=user_test.reset_index()\nuser_test.sort_values(by='user_id',ascending=True)\nyelp_join.shape\nforsample = yelp_join[(yelp_join['user_id'].isin(user_test['user_id']))]\nforsample.shape\nforsample.head()\n#get 20% from the whole dataset\ntrain, test = train_test_split(forsample,test_size=0.425,shuffle=True)\ntest\ntest.to_csv('test_dataset.csv')\n\"\"\"\n## Train data: except test data\n\"\"\"\nyelp_join.shape\nprint(yelp_join.user_id.nunique())\nprint(yelp_join.business_id.nunique())\ntrain = yelp_join[(~yelp_join['review_id'].isin(test['review_id']))]\ntrain\n#for training the neural network model\ntrain.to_csv('train_dataset.csv')\nyelp_join.business_id.nunique()\nprint(yelp_join.user_id.nunique())\nprint(yelp_join.business_id.nunique())\nprint(train.user_id.nunique())\nprint(train.business_id.nunique())\n#import\nimport pandas as pd\nyelp_join=pd.read_csv('resto_full.csv',index_col=0)\ntrain=pd.read_csv('train_dataset.csv',index_col=0)\ntest=pd.read_csv('test_dataset.csv',index_col=0)\ntrain.shape\ntrain.sha\ntrain['rating'].hist()\ntest.shape\ntest['rating'].hist()\n\"\"\"\n## Dataset to be predicted: to make full rating\n\"\"\"\nprint(yelp_join.shape)\nprint(train.shape)\nprint(test.shape)\nyelp_join.user_id.nunique()\nnuser=yelp_join.user_id.unique()\nnuser\nuserset = pd.DataFrame({'user_id':nuser[:]})\nuserset\nnbiz=yelp_join.business_id.unique()\nnbiz\nbizset = pd.DataFrame({'business_id':nbiz[:]})\nbizset\nuserset['key'] = 0\nbizset['key'] = 0\n\ndf_cartesian = userset.merge(bizset,on='key',how='outer')\ndf_cartesian = df_cartesian.drop(columns=['key'])\ndf_cartesian\niddata=train[['user_id','business_id']]\niddata\ndf_1_2 = df_cartesian.merge(iddata,on=['user_id','business_id'], how='left',indicator=True)\ndf_1_not_2 = df_1_2[df_1_2[\"_merge\"] == \"left_only\"].drop(columns=[\"_merge\"])\ndf_1_not_2\niddata=test[['user_id','business_id']]\niddata\ndf_1_2 = df_1_not_2.merge(iddata,on=['user_id','business_id'], how='left',indicator=True)\ndf_final = df_1_2[df_1_2[\"_merge\"] == \"left_only\"].drop(columns=[\"_merge\"])\ndf_final\nbizf=yelp_join[['business_id','biz_avg_rating','biz_total_rvw','review_age_y']]\nbizf.sort_values(by='business_id')\nbizf=bizf.drop_duplicates()\nbizf\ndf_final= df_final.merge(bizf,on='business_id', how='left')\ndf_final\nuserf=yelp_join[['user_id','fans','user_total_rvw','user_avg_rating','days_since','total_friends','total_compliments','total_votes','review_useful_y', 'review_funny_y', 'review_cool_y']]\nuserf.sort_values(by='user_id')\nuserf=userf.drop_duplicates()\nuserf\ndf_final= df_final.merge(userf,on='user_id', how='left')\ndf_final.head()\ndf_final.sort_values(by='user_id')\ndf_final.to_csv('full-mat-predict.csv')\nimport pandas as pd\ndf_final=pd.read_csv('full-mat-predict.csv')\ndf_final.shape\ndf_final=df_final.drop('Unnamed: 0',axis=1)\ndf_final.head()\nyelp_join.columns\n\"\"\"\n# Clean data\n\"\"\"\n\"\"\"\n## Predictor\n\"\"\"\npredictor=yelp_join[['rating','biz_avg_rating', 'biz_total_rvw',\n       'review_age_y', 'fans', 'user_total_rvw', 'user_avg_rating',\n       'days_since', 'total_friends', 'total_compliments', 'total_votes',\n       'review_useful_y', 'review_funny_y', 'review_cool_y']]\npredictor.shape\npredictor.columns\npredictor.shape\nimport pandas as pd\nimport numpy as np\n\nrs = np.random.RandomState(0)\ncorr = predictor.corr()\ncorr.style.background_gradient(cmap='coolwarm')\n# 'RdBu_r' & 'BrBG' are other good diverging colormaps\nimport pandas as pd\nimport numpy as np\n\nrs = np.random.RandomState(0)\ncorr = predictor.corr()\ncorr.style.background_gradient(cmap='coolwarm')\n# 'RdBu_r' & 'BrBG' are other good diverging colormaps\ndescdata=predictor.describe()\ndescdata.to_csv('predictor-descriptive.csv')\n\"\"\"\n## Finally!\n\"\"\"\nrating=predictor['rating']\npred = predictor.drop(['rating'], axis=1)\n\n#export\npred.to_csv('predictor-new.csv')\nrating.to_csv('target-new.csv',header=False)\nimport pandas as pd\n#import\nx=pd.read_csv('predictor-new.csv',index_col=0)\ny=pd.read_csv('target-new.csv',index_col=0,header=None)\nprint(x.shape)\nx.head()\nprint(y.shape)\ny.head()\n\"\"\"\n# Pre-processing data\n\"\"\"\ndf_final.columns\ndf_final.shape\nx\nfullmatpred=df_final[['biz_avg_rating', 'biz_total_rvw',\n       'review_age_y', 'fans', 'user_total_rvw', 'user_avg_rating',\n       'days_since', 'total_friends', 'total_compliments', 'total_votes',\n       'review_useful_y', 'review_funny_y', 'review_cool_y']]\ntest=test[['biz_avg_rating', 'biz_total_rvw',\n       'review_age_y', 'fans', 'user_total_rvw', 'user_avg_rating',\n       'days_since', 'total_friends', 'total_compliments', 'total_votes',\n       'review_useful_y', 'review_funny_y', 'review_cool_y','rating']]\ntest\nx_test=test[['biz_avg_rating', 'biz_total_rvw', 'review_age_y', 'fans',\n       'user_total_rvw', 'user_avg_rating', 'days_since', 'total_friends',\n       'total_compliments', 'total_votes', 'review_useful_y', 'review_funny_y',\n       'review_cool_y']]\ny_test=test[['rating']]\nx_test\nprint(train.shape)\nprint(test.shape)\ntrain.describe().to_csv('train-describe.csv')\ntest.describe().to_csv('test-describe.csv')\n#encode target to 5 columns\n# import preprocessing from sklearn\nfrom sklearn import preprocessing\nfrom tensorflow.python import keras\nenc = preprocessing.LabelEncoder()\n\n# 2. FIT\nenc.fit(y)\n\n# 3. Transform\nlabels = enc.transform(y)\nlabels.shape\ny=keras.utils.to_categorical(labels)\n# as you can see, you've the same number of rows 891\n# but now you've so many more columns due to how we changed all the categorical data into numerical data\n\n\n#encode target to 5 columns\n# import preprocessing from sklearn\nfrom sklearn import preprocessing\nfrom tensorflow.python import keras\nenc = preprocessing.LabelEncoder()\n\n# 2. FIT\nenc.fit(y_test)\n\n# 3. Transform\nlabels = enc.transform(y_test)\nlabels.shape\ny_test=keras.utils.to_categorical(labels)\n# as you can see, you've the same number of rows 891\n# but now you've so many more columns due to how we changed all the categorical data into numerical data\n\n\ny.shape\ny_test.shape\nx.shape\n##handling outliers\nimport numpy as np\nimport numpy.ma as ma\nfrom scipy.stats import mstats\n\nlow = .05\nhigh = .95\nquant_df = x.quantile([low, high])\nprint(quant_df)\nquant_df.head()\n##handling outliers\n\n# Winsorizing\nx['biz_avg_rating']=mstats.winsorize(x['biz_avg_rating'], limits=[0.05, 0.05])\nx['biz_total_rvw']=mstats.winsorize(x['biz_total_rvw'], limits=[0.05, 0.05])\nx['review_age_y']=mstats.winsorize(x['review_age_y'], limits=[0.05, 0.05])\nx['fans']=mstats.winsorize(x['fans'], limits=[0.05, 0.05])\nx['user_total_rvw']=mstats.winsorize(x['user_total_rvw'], limits=[0.05, 0.05])\nx['user_avg_rating']=mstats.winsorize(x['user_avg_rating'], limits=[0.05, 0.05])\nx['days_since']=mstats.winsorize(x['days_since'], limits=[0.05, 0.05])\nx['total_friends']=mstats.winsorize(x['total_friends'], limits=[0.05, 0.05])\nx['total_compliments']=mstats.winsorize(x['total_compliments'], limits=[0.05, 0.05])\nx['total_votes']=mstats.winsorize(x['total_votes'], limits=[0.05, 0.05])\nx['review_useful_y']=mstats.winsorize(x['review_useful_y'], limits=[0.05, 0.05])\nx['review_funny_y']=mstats.winsorize(x['review_funny_y'], limits=[0.05, 0.05])\nx['review_cool_y']=mstats.winsorize(x['review_cool_y'], limits=[0.05, 0.05])\nquant_df.head()\nfullmatpred.loc[fullmatpred['biz_avg_rating'] < 2.5, 'biz_avg_rating'] = 2.5\nfullmatpred.loc[fullmatpred['biz_avg_rating'] > 4.5, 'biz_avg_rating'] = 4.5\nfullmatpred.loc[fullmatpred['biz_total_rvw'] < 15, 'biz_total_rvw'] = 15\nfullmatpred.loc[fullmatpred['biz_total_rvw'] > 561, 'biz_total_rvw'] = 561\nfullmatpred.loc[fullmatpred['review_age_y'] < 255, 'review_age_y'] = 255\nfullmatpred.loc[fullmatpred['review_age_y'] > 1177, 'review_age_y'] = 1178\nfullmatpred.loc[fullmatpred['fans'] < 0, 'fans'] = 0\nfullmatpred.loc[fullmatpred['fans'] > 76, 'fans'] = 76\nfullmatpred.loc[fullmatpred['user_total_rvw'] < 6, 'user_total_rvw'] = 6\nfullmatpred.loc[fullmatpred['user_total_rvw'] > 862, 'user_total_rvw'] = 862\nfullmatpred.loc[fullmatpred['user_avg_rating'] < 2.88, 'user_avg_rating'] = 2.88\nfullmatpred.loc[fullmatpred['user_avg_rating'] > 4.43, 'user_avg_rating'] = 4.43\nfullmatpred.loc[fullmatpred['days_since'] < 281, 'days_since'] = 281\nfullmatpred.loc[fullmatpred['days_since'] > 2667, 'days_since'] = 2667\nfullmatpred.loc[fullmatpred['total_friends'] < 0 , 'total_friends'] = 0\nfullmatpred.loc[fullmatpred['total_friends'] > 589 , 'total_friends'] = 589\nfullmatpred.loc[fullmatpred['total_compliments'] < 0 , 'total_compliments'] = 0\nfullmatpred.loc[fullmatpred['total_compliments'] > 966 , 'total_compliments'] = 676\nfullmatpred.loc[fullmatpred['total_votes'] < 0 , 'total_votes'] = 0\nfullmatpred.loc[fullmatpred['total_votes'] > 4728 , 'total_votes'] = 4728\nfullmatpred.loc[fullmatpred['review_useful_y'] > 201 , 'review_useful_y'] = 201\nfullmatpred.loc[fullmatpred['review_funny_y'] > 78 , 'review_funny_y'] = 78\nfullmatpred.loc[fullmatpred['review_cool_y'] > 78 , 'review_cool_y'] = 78\n\nx_test.loc[x_test['biz_avg_rating'] < 2.5, 'biz_avg_rating'] = 2.5\nx_test.loc[x_test['biz_avg_rating'] > 4.5, 'biz_avg_rating'] = 4.5\nx_test.loc[x_test['biz_total_rvw'] < 15, 'biz_total_rvw'] = 15\nx_test.loc[x_test['biz_total_rvw'] > 561, 'biz_total_rvw'] = 561\nx_test.loc[x_test['review_age_y'] < 255, 'review_age_y'] = 255\nx_test.loc[x_test['review_age_y'] > 1177, 'review_age_y'] = 1178\nx_test.loc[x_test['fans'] < 0, 'fans'] = 0\nx_test.loc[x_test['fans'] > 76, 'fans'] = 76\nx_test.loc[x_test['user_total_rvw'] < 6, 'user_total_rvw'] = 6\nx_test.loc[x_test['user_total_rvw'] > 862, 'user_total_rvw'] = 862\nx_test.loc[x_test['user_avg_rating'] < 2.88, 'user_avg_rating'] = 2.88\nx_test.loc[x_test['user_avg_rating'] > 4.43, 'user_avg_rating'] = 4.43\nx_test.loc[x_test['days_since'] < 281, 'days_since'] = 281\nx_test.loc[x_test['days_since'] > 2667, 'days_since'] = 2667\nx_test.loc[x_test['total_friends'] < 0 , 'total_friends'] = 0\nx_test.loc[x_test['total_friends'] > 589 , 'total_friends'] = 589\nx_test.loc[x_test['total_compliments'] < 0 , 'total_compliments'] = 0\nx_test.loc[x_test['total_compliments'] > 966 , 'total_compliments'] = 676\nx_test.loc[x_test['total_votes'] < 0 , 'total_votes'] = 0\nx_test.loc[x_test['total_votes'] > 4728 , 'total_votes'] = 4728\nx_test.loc[x_test['review_useful_y'] > 201 , 'review_useful_y'] = 201\nx_test.loc[x_test['review_funny_y'] > 78 , 'review_funny_y'] = 78\nx_test.loc[x_test['review_cool_y'] > 78 , 'review_cool_y'] = 78\n\nx.shape\nfullmatpred.shape\n#Normalization\nfrom sklearn.preprocessing import MinMaxScaler\n#Normalize data\nscaler = MinMaxScaler()\n# Fit only to the training data\nx = scaler.fit_transform(x)\n# Now apply the transformations to the data:\n#x_test= scaler.transform(x_test)\nfullmatpred\nfullmatpred= scaler.transform(fullmatpred)\nx_test= scaler.transform(x_test)\ntest.columns\n##Split training and test set\nfrom sklearn.model_selection import train_test_split\nx_train, x_val, y_train, y_val = train_test_split(x,y,test_size=0.2,stratify=y)\nx_test.shape\nx_val.shape\nx_test[6]\n\"\"\"\n# Modelling\n\"\"\"\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\";\n \n# The GPU id to use, usually either \"0\" or \"1\";\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\";  \n \n# Do other imports now...\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow.python import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\nfrom tensorflow.keras.optimizers import SGD,Adam\nfrom tensorflow.keras import regularizers, initializers\nfrom tensorflow.keras.callbacks import CSVLogger,EarlyStopping,ModelCheckpoint\nfrom sklearn.metrics import log_loss, confusion_matrix\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(tf.__version__)\nprint(keras.__version__)\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\nprint(\"GPU Available: \", tf.test.is_gpu_available())\n\"\"\"\n## 13 features final\n\"\"\"\ncsv_logger = CSVLogger('log-final-2.csv', append=True, separator=';')\nfrom sklearn import metrics\nfrom sklearn.metrics import log_loss, confusion_matrix\nmodel = Sequential()\nmodel.add(Dense(4,input_dim=13, activation='tanh',use_bias=True, kernel_regularizer=regularizers.l2(0.0001), bias_regularizer=regularizers.l2(0.01)))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(4, activation='tanh',use_bias=True, kernel_regularizer=regularizers.l2(0.0001), bias_regularizer=regularizers.l2(0.01)))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(8, activation='tanh',use_bias=True, kernel_regularizer=regularizers.l2(0.0001), bias_regularizer=regularizers.l2(0.01)))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(5, activation='softmax'))\nsgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9)\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=sgd,\n              metrics=['accuracy'])\n# simple early stopping\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=50,restore_best_weights=True)\n#checkpoint\n# checkpoint\nfilepath=\"weights.best.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n\nhistory=model.fit(x_train, y_train,\n          epochs=3000,batch_size=200,validation_data=(x_val, y_val),callbacks=[csv_logger,es,checkpoint]\n          )\n\ny_pred=model.predict(x_test)\nmatrix = metrics.confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\npd.DataFrame(matrix).to_csv(\"result-final-2.csv\",header=False,index=False)\n\nfrom tensorflow.keras.models import model_from_json\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"model-final-2.json\", \"w\") as json_file:\n    json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model-final-2.h5\")\nprint(\"Saved model to disk\")\n \n# later...\n# load weights\nmodel.load_weights(\"weights.best.hdf5\")\n# Compile model (required to make predictions)\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=sgd,\n              metrics=['accuracy'])\nprint(\"Created model and loaded weights from file\")\ny_pred_val=model.predict(x_val)\nacc=metrics.accuracy_score(y_val.argmax(axis=1), y_pred_val.argmax(axis=1))\nacc\nmatrix\nlen(history.history['loss'])\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\nimport matplotlib.pyplot as plt\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# load json and create model\nfrom tensorflow.keras.models import model_from_json\n\njson_file = open('model-final-2.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"model-final-2.h5\")\nprint(\"Loaded model from disk\")\n \n# evaluate loaded model on test data\nloaded_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])\nscore = loaded_model.evaluate(x_test, y_test, verbose=0)\nprint(\"%s: %.2f%%\" % (loaded_model.metrics_names[1], score[1]*100))\ny_pred=loaded_model.predict(x_test)\ny_pred\ntest.rating.value_counts()\ny_test.shape\nfrom sklearn.metrics import mean_squared_error,mean_absolute_error\nfrom math import sqrt\n\nrms = sqrt(mean_squared_error(y_test.argmax(axis=1), y_pred.argmax(axis=1)))\nprint(rms)\nmae = mean_absolute_error(y_test.argmax(axis=1), y_pred.argmax(axis=1))\nprint(mae)\nconf=metrics.confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\nprint(conf)\ndf_final.shape\nfmpred=loaded_model.predict(fullmatpred)\nfmpredrating=fmpred.argmax(axis=1)\nfmpredrating.min()\nfmpredratingdf=pd.DataFrame({'col1':fmpred[:,0],'col2':fmpred[:,1],'col3':fmpred[:,2],'col4':fmpred[:,3],'col5':fmpred[:,4]})\nfmpredratingdf\nfmpredratingdf[\"rating\"] = fmpredratingdf[[\"col1\",\"col2\",\"col3\",\"col4\",\"col5\"]].max(axis=1)\nfmpredratingdf\ndef get_status(df):\n    if df['rating'] == df['col1']:\n        return 1\n    elif df['rating'] == df['col2']:\n        return 2\n    elif df['rating'] == df['col3']:\n        return 3\n    elif df['rating'] == df['col4']:\n        return 4\n    else:\n        return 5\n\nfmpredratingdf['star'] = fmpredratingdf.apply(get_status, axis = 1)\nfmpredratingdf\nfull_matrix_id=df_final[['user_id','business_id']]\nfull_matrix_id\nrat=fmpredratingdf[['star']]\nrat=rat.rename({'star':'rating'},axis=1)\nrat\nfullpreddata=pd.concat([full_matrix_id, rat], axis=1)\nfullpreddata\nfullpreddata.to_csv('cf-predicted.csv',header=False,index=None)\ntrain=pd.read_csv('train_dataset.csv',index_col=0)\ntrain.head()\ntrain_cf=train[['user_id','business_id','rating']]\ntrain_cf.shape\nfullpreddata.head()\ntest=pd.read_csv('test_dataset.csv',index_col=0)\ntest.head()\ntest_cf=test[['user_id','business_id','rating']]\ntest_cf.shape\nfull_total=fullpreddata.append(train_cf,sort=False)\nfull_total\nfull_total.to_csv('cf-full.csv',header=False,index=None)\nfull_total\n\"\"\"\n# -------------------- \n\"\"\"\n\"\"\"\n## Alternatively: using sklearn\n\"\"\"\n##Import library\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nfrom sklearn.metrics import log_loss, confusion_matrix, accuracy_score\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.tree import DecisionTreeClassifier\n#model=MLPClassifier(hidden_layer_sizes=(4,4,8),max_iter=3000,solver='sgd',activation='tanh',alpha=0.01,learning_rate_init=0.0001,verbose=True)\n#model=MLPClassifier(hidden_layer_sizes=(8,8,8),max_iter=3000,solver='adam',activation='tanh',verbose=True)\n#model=KNeighborsClassifier(n_neighbors=1000)\n#model=LogisticRegression(multi_class='auto',solver='sag')\n#model=DecisionTreeClassifier()\nmodel=MLPClassifier(hidden_layer_sizes=(100,100),max_iter=3000,verbose=True,activation='tanh')\nmodel.fit(x_train,y_train)\n#Test the model\ny_pred = model.predict(x_test)\n#Print final result\nprint(confusion_matrix(y_test,y_pred))\nmodel.n_layers_\naccuracy = model.score(x_test,y_test)\nprint(accuracy*100,'%')\naccuracy = metrics.accuracy_score(y_test, y_pred)\naccuracy","meta":"{'source': 'AI4Code', 'id': 'a0528a8e06f20e'}"}
{"id":"62468","text":"\"\"\"\n# Compare 14 Algorithms for Mushroom classification\n## *Using Cross validation*\n\n![mushrooms](https:\/\/i.imgur.com\/JZuP141.png)\n\n# Table of contents\n\n[<h3>1. Data Description & Visualization<\/h3>](#1)\n\n[<h3>2. Data Preprocessing<\/h3>](#2)\n\n[<h3>3. Model comparison using cross validation<\/h3>](#3)\n\n[<h3>4. Prediction metrics of the best model using the test set<\/h3>](#4)\n\n## Context\nAlthough this dataset was originally contributed to the UCI Machine Learning repository nearly 30 years ago, mushroom hunting (otherwise known as \"shrooming\") is enjoying new peaks in popularity. Learn which features spell certain death and which are most palatable in this dataset of mushroom characteristics. And how certain can your model be?\n\n## Content\nThis dataset includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family Mushroom drawn from The Audubon Society Field Guide to North American Mushrooms (1981). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. This latter class was combined with the poisonous one. The Guide clearly states that there is no simple rule for determining the edibility of a mushroom; no rule like \"leaflets three, let it be'' for Poisonous Oak and Ivy.\n\nTime period: Donated to UCI ML 27 April 1987\n\n## Inspiration\n- What types of machine learning models perform best on this dataset?\n- Which features are most indicative of a poisonous mushroom?\n\n## Acknowledgements\nThis dataset was originally donated to the UCI Machine Learning repository.\n\n## Attribute Information: \n(classes: edible=e, poisonous=p)\n\n- cap-shape: bell=b,conical=c,convex=x,flat=f, knobbed=k,sunken=s\n- cap-surface: fibrous=f,grooves=g,scaly=y,smooth=s\n- cap-color: brown=n,buff=b,cinnamon=c,gray=g,green=r,pink=p,purple=u,red=e,white=w,yellow=y\n- bruises: bruises=t,no=f\n- odor: almond=a,anise=l,creosote=c,fishy=y,foul=f,musty=m,none=n,pungent=p,spicy=s\n- gill-attachment: attached=a,descending=d,free=f,notched=n\n- gill-spacing: close=c,crowded=w,distant=d\n- gill-size: broad=b,narrow=n\n- gill-color: black=k,brown=n,buff=b,chocolate=h,gray=g, green=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y\n- stalk-shape: enlarging=e,tapering=t\n- stalk-root: bulbous=b,club=c,cup=u,equal=e,rhizomorphs=z,rooted=r,missing=?\n- stalk-surface-above-ring: fibrous=f,scaly=y,silky=k,smooth=s\n- stalk-surface-below-ring: fibrous=f,scaly=y,silky=k,smooth=s\n- stalk-color-above-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o,pink=p,red=e,white=w,yellow=y\n- stalk-color-below-ring: brown=n,buff=b,cinnamon=c,gray=g,orange=o,pink=p,red=e,white=w,yellow=y\n- veil-type: partial=p,universal=u\n- veil-color: brown=n,orange=o,white=w,yellow=y\n- ring-number: none=n,one=o,two=t\n- ring-type: cobwebby=c,evanescent=e,flaring=f,large=l,none=n,pendant=p,sheathing=s,zone=z\n- spore-print-color: black=k,brown=n,buff=b,chocolate=h,green=r,orange=o,purple=u,white=w,yellow=y\n- population: abundant=a,clustered=c,numerous=n,scattered=s,several=v,solitary=y\n- habitat: grasses=g,leaves=l,meadows=m,paths=p,urban=u,waste=w,woods=d\n\n\n\n\"\"\"\n\"\"\"\n## Load the libraries:\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split # train_test\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression,PassiveAggressiveClassifier,RidgeClassifier,SGDClassifier\nfrom sklearn.neighbors import KNeighborsClassifier,RadiusNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier\nfrom sklearn.svm import LinearSVC, SVC,NuSVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_validate\nfrom time import perf_counter\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom IPython.display import Markdown, display\n\ndef printmd(string):\n    # Print with Markdowns    \n    display(Markdown(string))\n\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\"\"\"\n# 1. Data Description & Visualization<a class=\"anchor\" id=\"1\"><\/a><a class=\"anchor\" id=\"1\"><\/a>\n\"\"\"\ndf = pd.read_csv(\"..\/input\/mushroom-classification\/mushrooms.csv\")\n\n# Change the names of the class to be more explicit\n# with \"edible\" and \"poisonous\"\ndf['class'] = df['class'].map({\"e\": \"edible\", \"p\": \"poisonous\"})\ndf.iloc[:5,:8]\ndf['class'].value_counts().plot.bar(figsize = (10,5), color = ['grey','red'])\nplt.xticks(rotation=0)\nplt.title('Quantity of each class in the dataset', fontsize = 15)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\nplt.show()\n\n\"\"\"\n# 2. Data Preprocessing<a class=\"anchor\" id=\"2\"><\/a><a class=\"anchor\" id=\"1\"><\/a>\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\n\nX = df.drop(\"class\", axis = 1).copy()\ny = df['class'].copy()\n\nlabel_encoder_data = X.copy()\nlabel_encoder = LabelEncoder()\nfor col in X.columns:\n    label_encoder_data[col] = label_encoder.fit_transform(label_encoder_data[col])\n    \nX = label_encoder_data\n\n# Split the dataset\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)\n\"\"\"\n# 3. Model comparison using cross validation<a class=\"anchor\" id=\"3\"><\/a><a class=\"anchor\" id=\"3\"><\/a>\n\"\"\"\n# Create a dictionary with the model which will be tested\nmodels = {\n    \"GaussianNB\":{\"model\":GaussianNB()},\n    \"PassiveAggressiveClassifier\":{\"model\":PassiveAggressiveClassifier() },\n    \"RidgeClassifier\":{\"model\":RidgeClassifier() },\n    \"SGDClassifier\":{\"model\":SGDClassifier() },\n    \"KNeighborsClassifier\":{\"model\":KNeighborsClassifier() },\n    \"DecisionTreeClassifier\":{\"model\":DecisionTreeClassifier() },\n    \"ExtraTreeClassifier\":{\"model\":ExtraTreeClassifier() },\n    \"LinearSVC\":{\"model\":LinearSVC() },\n    \"SVC\":{\"model\":SVC() },\n    \"NuSVC\":{\"model\":NuSVC() },\n    \"MLPClassifier\":{\"model\":MLPClassifier() },\n    \"RandomForestClassifier\":{\"model\":RandomForestClassifier() },\n    \"GradientBoostingClassifier\":{\"model\":GradientBoostingClassifier() },\n    \"AdaBoostClassifier\":{\"model\":AdaBoostClassifier() }\n}\n# Use the 10-fold cross validation for each model\n# to get the mean validation accuracy and the mean training time\nfor name, m in models.items():\n    # Cross validation of the model\n    model = m['model']\n    result = cross_validate(model, X_train,y_train,cv = 10)\n    \n    # Mean accuracy and mean training time\n    mean_val_accuracy = round( sum(result['test_score']) \/ len(result['test_score']), 4)\n    mean_fit_time = round( sum(result['fit_time']) \/ len(result['fit_time']), 4)\n    \n    # Add the result to the dictionary witht he models\n    m['val_accuracy'] = mean_val_accuracy\n    m['Training time (sec)'] = mean_fit_time\n    \n    # Display the result\n    print(f\"{name:27} mean accuracy using 10-fold cross validation: {mean_val_accuracy*100:.2f}% - mean training time {mean_fit_time} sec\")\n# Create a DataFrame with the results\nmodels_result = []\n\nfor name, v in models.items():\n    lst = [name, v['val_accuracy'],v['Training time (sec)']]\n    models_result.append(lst)\n\ndf_results = pd.DataFrame(models_result, \n                          columns = ['model','val_accuracy','Training time (sec)'])\ndf_results.sort_values(by='val_accuracy', ascending=False, inplace=True)\ndf_results.reset_index(inplace=True,drop=True)\ndf_results\nplt.figure(figsize = (15,5))\nsns.barplot(x = 'model', y = 'val_accuracy', data = df_results)\nplt.title('Mean Validation Accuracy for each Model\\ny-axis between 0.8 and 1.0', fontsize = 15)\nplt.ylim(0.8,1.005)\nplt.xlabel('Model', fontsize=15)\nplt.ylabel('Accuracy',fontsize=15)\nplt.xticks(rotation=90, fontsize=12)\nplt.show()\nplt.figure(figsize = (15,5))\nsns.barplot(x = 'model', y = 'Training time (sec)', data = df_results)\nplt.title('Training time for each Model in sec', fontsize = 15)\nplt.xticks(rotation=90, fontsize=12)\nplt.xlabel('Model', fontsize=15)\nplt.ylabel('Training time (sec)',fontsize=15)\nplt.show()\n\"\"\"\n# 4. Prediction metrics of the best model using the test set<a class=\"anchor\" id=\"4\"><\/a><a class=\"anchor\" id=\"1\"><\/a>\n\"\"\"\n# Get the model with the highest mean validation accuracy\nbest_model = df_results.iloc[0]\n\n# Fit the model\nmodel = models[best_model[0]]['model']\nmodel.fit(X_train,y_train)\n\n# Predict the labels with the data set\npred = model.predict(X_test)\n\n# Display the results\nprintmd(f'## Best Model: {best_model[0]} with {best_model[1]*100}% accuracy on the test set')\nprintmd(f'## Trained in: {best_model[2]} sec')\n\n# Display a confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncf_matrix = confusion_matrix(y_test, pred, normalize='true')\nplt.figure(figsize = (10,7))\nsns.heatmap(cf_matrix, annot=True, xticklabels = sorted(set(y_test)), yticklabels = sorted(set(y_test)),cbar=False)\nplt.title('Normalized Confusion Matrix', fontsize = 23)\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '7322cb3344b292'}"}
{"id":"91032","text":"\"\"\"\n![image.png](attachment:6471aeb2-d6d0-4dfd-a35d-ff48f5695402.png)\n\"\"\"\n\"\"\"\n## CONTEXT\nThe goal of this competition, initiated by the Radiological Society of North America (RSNA) in partnership with the Medical Image Computing and Computer Assisted Intervention Society (the MICCAI Society) is to predict the methylation of the MGMT promoter, which is an important gene biomarker for treatment of brain tumors.\n\nThese predictions will be based on a database of MRI (magnetic resonance imaging) scans of several hundred patients.\n\n\n\"\"\"\n\"\"\"\n## DATA\nEach independent case has a dedicated folder identified by a five-digit number. Within each of these \u201ccase\u201d folders, there are four sub-folders, each of them corresponding to each of the structural multi-parametric MRI (mpMRI) scans, in DICOM format. The exact mpMRI scans included are:\n\n- Fluid Attenuated Inversion Recovery (FLAIR)\n- T1-weighted pre-contrast (T1w)\n- T1-weighted post-contrast (T1Gd)\n- T2-weighted (T2)\n\n\"\"\"\n\"\"\"\n### Import Dependencies\n\"\"\"\nimport os\nimport glob\nimport re\nimport math\nimport numpy as np\nimport pandas as pd\nfrom tqdm.notebook import tqdm\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pydicom as dicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n\"\"\"\n## Load the Data\n\"\"\"\ndata_directory = '..\/input\/rsna-miccai-brain-tumor-radiogenomic-classification\/'\n\ntrain_df = pd.read_csv(data_directory+\"train_labels.csv\")\ntrain_df['BraTS21ID5'] = [format(x, '05d') for x in train_df.BraTS21ID]\ntrain_df.head()\n\"\"\"\nTest data:-\n\"\"\"\ntest = pd.read_csv(\n    data_directory+'sample_submission.csv')\n\ntest['BraTS21ID5'] = [format(x, '05d') for x in test.BraTS21ID]\ntest.head(3)\n\"\"\"\n# IMAGE PREPROCESSING\nFor each patient, we will carry out a pre-processing of the images by applying these different modifications:\n\n- Load an ordered sequence of 64 MRI scan\n- Crop images to reduce black borders\n- Resize image for pre-train model\n- Apply denoising filter\n- Convert each image in 3D array\n\"\"\"\nIMAGE_SIZE = 240\nSCALE = .8\nNUM_IMAGES = 64\nMRI_TYPE = \"FLAIR\"\n# Load Single Image\ndef load_dicom_image(\n    path,\n    img_size = IMAGE_SIZE,\n    scale = SCALE):\n    '''\n    This function allows you to load a DCIM type image \n    and apply preprocessing steps such as crop, resize \n    and denoising filter to it.\n    ****************************************************\n    PARAMETERS\n    ****************************************************\n    - path : String\n        Path to the DCIM image file to load.\n    - img_size : Integer\n        Image size desired for resizing.\n    - scale : Float\n        Desired scale for the cropped image\n    - prep : Bool\n        True for a full preprocessing with\n        denoising.\n    '''\n    # Load single image\n    img = dicom.read_file(path).pixel_array\n    # Crop image\n    center_x, center_y = img.shape[1] \/ 2, img.shape[0] \/ 2\n    width_scaled, height_scaled = img.shape[1] * scale, img.shape[0] * scale\n    left_x, right_x = center_x - width_scaled \/ 2, center_x + width_scaled \/ 2\n    top_y, bottom_y = center_y - height_scaled \/ 2, center_y + height_scaled \/ 2\n    img = img[int(top_y):int(bottom_y), int(left_x):int(right_x)]\n    # Resize image\n    img = cv2.resize(img, (img_size, img_size))\n    \n    # Convert in 3D array\n    img = np.repeat(img[..., np.newaxis], 3, -1)\n    \n    return img\n\"\"\"\nWe can check the result of these different preprocessing steps on a random patient:\n\"\"\"\nsample_img = dicom.read_file(data_directory+\"train\/00046\/FLAIR\/Image-90.dcm\").pixel_array\n\npreproc_img = load_dicom_image(data_directory+\"train\/00046\/FLAIR\/Image-90.dcm\")\n\nfig = plt.figure(figsize = (12, 8))\nax1 = plt.subplot(1,2,1)\nax1.imshow(sample_img, cmap=\"gray\")\nax1.set_title(f\"Original image shape = {sample_img.shape}\")\nax2 = plt.subplot(1,2,2)\nax2.imshow(preproc_img[:,:,0], cmap=\"gray\")\nax2.set_title(f\"After Preprocessing = {preproc_img.shape}\")\nplt.show()\n\"\"\"\n### LOAD SEQUENCE OF 64 PREPROCESSED IMAGES\n\"\"\"\ndef load_dicom_images_3d(\n    scan_id,\n    num_imgs = NUM_IMAGES,\n    img_size = IMAGE_SIZE,\n    mri_type = MRI_TYPE,\n    split = \"train\"):\n    '''\n    This function allows loading an ordered sequence \n    of x preprocessed images starting from the central \n    image of each folder.\n    ****************************************************\n    PARAMETERS\n    ****************************************************\n    - scan_id : String\n        ID of the patient to load.\n    - num_imgs : Integer\n        Number of desired images of the \n        sequence.\n    - img_size : Integer\n        Image size desired for resizing.\n    - scale : Float\n        Desired scale for the cropped image\n    - mri_type : String\n        Type of scan to load (FLAIR, T1w, \n        T1wCE, T2).\n    - split : String\n        Type of split desired : Train or Test\n    '''\n    files = sorted(glob.glob(f\"{data_directory}{split}\/{scan_id}\/{mri_type}\/*.dcm\"), \n               key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])\n    middle = len(files) \/\/ 2\n    num_imgs2 = num_imgs \/\/ 2\n    p1 = max(0, middle - num_imgs2)\n    p2 = min(len(files), middle + num_imgs2)\n    img3d = np.stack([load_dicom_image(f) for f in files[p1:p2]])\n    if img3d.shape[0] < num_imgs:\n        n_zero = np.zeros((num_imgs - img3d.shape[0], img_size, img_size, 3))\n        img3d = np.concatenate((img3d, n_zero), axis = 0)\n        \n    return img3d\n\"\"\"\nHere again we can test the loading of a sequence of preprocessed images for a patient:\n\"\"\"\nsample_seq = load_dicom_images_3d(\"00046\")\nprint(\"Shape of the sequence is :-\", sample_seq.shape)\nprint(\"Dimension of the 15th image in sequence is:-\", sample_seq[15].shape)\nfig = plt.figure(figsize = (5,5))\nplt.imshow(np.squeeze(sample_seq[15][:,:,0]), cmap=\"gray\")\nplt.show()\n\"\"\"\n## LOAD PRE-TRAINED RESNET50 MODEL\nTo carry out the Transfer Learning on each image of the sequence, we will load a pre-trained model thanks to Keras.applications with the pre-trained weights on ImageNet.\nAs the notebook must be without Internet for the competition, the weights are loaded separately and imported from a specially created Dataset (..\/input\/resnet-imagenet-weights).\n\nHere we will chrger the ResNet50 model, knowing that other models have been tested such as ResNet50 and Xception.\n\n\n\"\"\"\nbase_resnet = keras.applications.ResNet50(\n    weights = None,\n    pooling = \"avg\",\n    input_shape = (IMAGE_SIZE, IMAGE_SIZE, 3),\n    include_top = False)\nbase_resnet.save_weights(\n    'base_resnet_imagenet.h5')\nbase_resnet.load_weights(\n    '.\/base_resnet_imagenet.h5')\n\n\"\"\"\nWe are also going to fix all the layers of the model so that they are not re-trained for the detection of features. The classification layer is also not loaded (include_top = False).\n\"\"\"\nbase_resnet.trainable = False\n\"\"\"\n## CREATE A MATRIX OF VECTORS BASE ON RESNET50 FOR EACH PATIENT SEQUENCE\nFor this part of Transfer Learning, we will not train the ResNet50 model but only perform the prediction for each image of the sequence of each patient.\nWe will thus obtain, for each image, a matrix of the model weights that we will integrate into a list to recreate the patient sequence.\nFinally, we are going to create a global matrix which will group together the sequences of x ResNet50.predict matrices for all the patients.\n\nLet's look at the pseudo-code:\n\"\"\"\n# Transfert Learning\n# listMatrix = []\n# for person in persons:\n#     listVectors = []\n#     for image in person.images:\n#         img = preprocess(image)\n#         vector = baseModel.predict(img)\n#         listVectors.append(vector)\n\n#     PatientMatrix = np.stack(listVectors)\n#     listMatrix.append(PatientMatrix)\ntrain = train_df[['BraTS21ID5','MGMT_value']]\nX_train = train['BraTS21ID5'].values\ny_train = train['MGMT_value'].values\n\"\"\"\nWe will apply this process for just one type of MRI scans (here is T1w type) for each patient. Each patient will therefore have 24 images for treatment.\n\"\"\"\nlistMatrix = []\nfor i, patient in enumerate(tqdm(X_train)):\n    listVectors = []\n    sequence = load_dicom_images_3d(scan_id=str(patient),mri_type=MRI_TYPE)\n    for j in range(len(sequence)):\n        img = sequence[j]\n        img = np.expand_dims(img, axis=0)\n        img = tf.keras.applications.resnet50.preprocess_input(img)\n        img_vector = base_resnet.predict(img)\n        listVectors.append(np.array(img_vector))\n    \n    PatientMatrix = np.stack(listVectors)\n    listMatrix.append(PatientMatrix)\n\"\"\"\nLet us now look at the shapes of the matrices obtained following the application of this Learning Transfer:\n\"\"\"\nprint(f\"Number of Patient matrix: {len(listMatrix)}\")\nprint(f\"Patient matrix shape: {listMatrix[0].shape}\")\nnp.array(listMatrix, dtype = object).shape\n\"\"\"\n## APPLY LSTM FOR CLASSIFICATION\nRecurrent neural networks (RNNs) are widely used in artificial intelligence when a temporal notion is involved in the data.\n\nLSTM is a complex and very powerful algorithm which will allow in our case to take into account the past elements of our sequence of images.\n\"\"\"\nmodel_input_dim = listMatrix[0].shape[2]\nmodel_input_dim\n# Create a function for lstm model\ndef get_sequence_model():\n    '''Define the LSTM architecture'''\n    model = keras.models.Sequential()\n    model.add(keras.layers.LSTM(100, input_shape=(NUM_IMAGES, model_input_dim), return_sequences=True))\n    model.add(keras.layers.Dropout(0.2))\n    model.add(keras.layers.Dense(100, activation='relu'))\n    model.add(keras.layers.Dense(1, activation='sigmoid'))\n    return model\n\"\"\"\nWe will now train this LSTM model on the matrices compiled for each patient using the Transfer Learning ResNet50.\n\nAn EarlyStopping is set up and the best model will be saved\n\"\"\"\nfrom sklearn.model_selection import KFold\n\ninputs = np.array(listMatrix)\ntargets = np.array(y_train).astype('float32').reshape((-1,1))\n\nnum_folds = 5\n\n# Define the K-fold Cross Validator\nkfold = KFold(n_splits=num_folds, shuffle=True)\n\n# K-fold Cross Validation model evaluation\nhistory = {}\nfold_no = 1\nfor train_df, valid_df in kfold.split(inputs, targets):\n    \n    train_dataset = tf.data.Dataset.from_tensor_slices((inputs[train_df], targets[train_df]))\n    valid_dataset = tf.data.Dataset.from_tensor_slices((inputs[valid_df], targets[valid_df]))\n    \n    model = get_sequence_model()\n    model.compile(loss='binary_crossentropy', \n                  optimizer='adam', \n                  metrics='accuracy')\n    \n    # Define callbacks.\n    model_save = ModelCheckpoint(f'Brain_lstm_kfold_{fold_no}.h5', \n                                 save_best_only = True, \n                                 monitor = 'val_accuracy', \n                                 mode = 'max', verbose = 1)\n    early_stop = EarlyStopping(monitor = 'val_accuracy', \n                               patience = 25, mode = 'max', verbose = 1,\n                               restore_best_weights = True)\n    \n    print('------------------------------------------------------------------------')\n    print(f'Training for fold {fold_no} ...')\n    \n    epochs = 200\n    history[fold_no] = model.fit(\n        train_dataset,\n        validation_data=valid_dataset, \n        epochs=epochs, \n        batch_size=32,\n        callbacks = [model_save, early_stop])\n    \n    # Increase fold number\n    fold_no += 1\n\"\"\"\nNow let's look at the results of this training:\n\"\"\"\nfig , ax = plt.subplots(1 , 2, figsize=(20,7))\nax = ax.ravel()\n\nfor fold in history:\n    for i, metric in enumerate([\"accuracy\", \"loss\"]):\n        ax[i].plot(history[fold].history[metric], label=\"train\"+str(fold))\n        ax[i].plot(history[fold].history[\"val_\" + metric], linestyle=\"dotted\", label=\"val\"+str(fold))\n        ax[i].set_title(\"Model {}\".format(metric))\n        ax[i].set_xlabel(\"epochs\")\n        ax[i].set_ylabel(metric)\n        ax[i].legend()\nkfold_results = pd.DataFrame(columns=[\"Fold\",\"Mean_Loss\",\"Mean_Accuracy\"])\nkey = []\nmean_loss = []\nmean_acc = []\nfor fold in history:\n    key.append(fold), \n    mean_loss.append(np.mean(history[fold].history[\"val_loss\"]))\n    mean_acc.append(np.mean(history[fold].history[\"val_accuracy\"]))\n\nkfold_results[\"Fold\"] = key\nkfold_results[\"Mean_Loss\"] = mean_loss\nkfold_results[\"Mean_Accuracy\"] = mean_acc\nkfold_results[\"Rank_Ratio\"] = (kfold_results[\"Mean_Loss\"] - kfold_results[\"Mean_Accuracy\"])\nkfold_results = kfold_results.sort_values(\"Rank_Ratio\", ascending=True)\nkfold_results\nbest_kfold_model = '.\/Brain_lstm_kfold_' + str(kfold_results.Fold.values[0]) + '.h5'\nprint(f\"The best select model is {best_kfold_model}\")\n\"\"\"\n## PREDICT ON TEST SET WITH BEST MODEL\nWe will now create the ResNet50 matrices for the test set and make the predictions on the test patients.\n\"\"\"\nX_test = test['BraTS21ID5'].values\ntest_listMatrix = []\nfor i, patient in enumerate(tqdm(X_test)):\n    test_listVectors = []\n    test_sequence = load_dicom_images_3d(scan_id=str(patient),mri_type=MRI_TYPE,split=\"test\")\n    for j in range(len(test_sequence)):\n        img = test_sequence[j]\n        img = np.expand_dims(img, axis=0)\n        img = tf.keras.applications.resnet50.preprocess_input(img)\n        img_vector = base_resnet.predict(img)\n        test_listVectors.append(np.array(img_vector))\n    \n    test_PatientMatrix = np.stack(test_listVectors)\n    test_listMatrix.append(test_PatientMatrix)\nprint(f\"Number of test patient matrix: {len(test_listMatrix)}\")\nprint(f\"Test patient matrix shape: {test_listMatrix[0].shape}\")\ntest_dataset = tf.data.Dataset.from_tensor_slices(test_listMatrix)\nlen(test_dataset)\nfinal_model = keras.models.load_model(best_kfold_model)\npredict = final_model.predict(test_dataset)\nprint(predict.shape)\npredict = predict[:,0,0]\nfinal_predict = []\nfor i in range(len(test_listMatrix)):\n    i+=1\n    final_predict.append(round(predict[((i-1)*NUM_IMAGES):(NUM_IMAGES*i)].mean(),3))\nsubmission = test[[\"BraTS21ID\",\"MGMT_value\"]]\nsubmission[\"MGMT_value\"] = final_predict\nsubmission.to_csv('submission.csv',index=False)\nsubmission.head(5)\nplt.figure(figsize=(8, 8))\nplt.hist(submission[\"MGMT_value\"])\nplt.title(\"Predicted probabilites distribution on test set\", \n          fontsize=18, color=\"#0b0a2d\")\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'a6fd38dc409fc0'}"}
{"id":"28665","text":"# 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\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as sns\n%matplotlib inline \npd.set_option('display.max_columns', None)\npath = '..\/input\/bankchurners-set2\/BankChurners.csv'\ndf = pd.read_csv(path)\ndf.head()\ndf.info()\n# dropping the last two columns\ndf.drop(df.columns[-2:], axis = 1, inplace = True)\ndf.head()\ndf.describe()\ndf.isnull().sum()\n\"\"\"\n**There are no null values in the dataset**\n\"\"\"\ndf.columns\n# dropping the clientnum column\ndf.drop('CLIENTNUM', axis = 1, inplace = True)\n\"\"\"\n## Data Preparation for model building\n\"\"\"\n\"\"\"\n#### Target column\n\"\"\"\ntarget_col = pd.get_dummies(df['Attrition_Flag'], drop_first = True)\n\ndf['target'] = target_col\n\ndf.drop('Attrition_Flag', axis = 1, inplace = True)\n\"\"\"\n#### Gender\n\"\"\"\ndf['Gender'].unique()\nd = {\n    'M': 0,\n    'F': 1\n}\ndf['Gender'] = df['Gender'].map(d)\n\"\"\"\n#### Marital_Status\n\"\"\"\nd = {\n    'Unknown': 0,\n    'Single': 1,\n    'Married': 2,\n    'Divorced': 3\n}\ndf['Marital_Status'] = df['Marital_Status'].map(d)\n\"\"\"\n#### Education_Level\n\"\"\"\ndf['Education_Level'].value_counts().index\nd = {\n    'Unknown': 0,\n    'Uneducated': 1,\n    'High School': 2,\n    'College': 3,\n    'Graduate': 4,\n    'Post-Graduate': 5,\n    'Doctorate': 6\n}\ndf['Education_Level'] = df['Education_Level'].map(d)\n\"\"\"\n#### Income_Category\n\"\"\"\nd = {\n    'Unknown': 0,\n    'Less than $40K': 1,\n    '$40K - $60K': 2,\n    '$60K - $80K': 3,\n    '$80K - $120K': 4,\n    '$120K +': 5\n}\ndf['Income_Category'] = df['Income_Category'].map(d)\n\"\"\"\n#### Card_Category\n\"\"\"\ndf['Card_Category'].value_counts().index\nd = {\n    'Blue': 0,\n    'Silver': 1,\n    'Gold': 2,\n    'Platinum': 3\n}\ndf['Card_Category'] = df['Card_Category'].map(d)\n\"\"\"\n### Models\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX = df.iloc[:, :-1]\ny = df.iloc[:, -1]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\ndec = DecisionTreeClassifier()\nrandom = RandomForestClassifier()\nnaive_bayes = GaussianNB()\nadaboost = AdaBoostClassifier() \ngradboost = GradientBoostingClassifier()\nmodels = [\n    dec, \n    random, \n    naive_bayes,\n    adaboost,\n    gradboost\n]\n\nfor model in models:\n    print(model)\n    crossval = cross_val_score(model, X, y, cv = 5)\n    print(crossval)\n    print('mean is {}'.format(crossval.mean()))\n    print(\"The standard deviation is {}\".format(crossval.std()))\n    print()\nrandom.fit(X_train, y_train)\nfrom sklearn.metrics import accuracy_score \naccuracy_score(y_test, random.predict(X_test))","meta":"{'source': 'AI4Code', 'id': '34ad5bb2e45ea0'}"}
{"id":"102294","text":"\"\"\"\n#Newly Developed System for Acetamiprid Residue Screening in the Lettuce Samples Based on a #Bioelectric Cell Biosensor\n\nAuthors:\nApostolou, T.; Loizou, K.; Hadjilouka, A.; Inglezakis, A.; Kintzios, S. Newly Developed System for Acetamiprid Residue Screening in the Lettuce Samples Based on a Bioelectric Cell Biosensor. Biosensors 2020, 10, 8. Biosensors 2020, 10(2), 8; https:\/\/doi.org\/10.3390\/bios10020008\n\nPopulation growth and increased production demands on fruit and vegetables have driven agricultural production to new heights. Nevertheless, agriculture remains one of the least optimized industries, with laboratory tests that take days to provide a clear result on the chemical level of produce. To address this problem, the authors developed a tailor-made solution for the industry that can allow multiple field tests on key pesticides, based on a bioelectric cell biosensor and the measurement of the cell membrane potential changes, according to the principle of the Bioelectric Recognition Assay (BERA).https:\/\/www.mdpi.com\/2079-6374\/10\/2\/8\n\"\"\"\n\"\"\"\n![](https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRVhK7sYVHEOjcj9f3KlUEltIXMssSc0b_SMA&usqp=CAU)prezi.com\n\"\"\"\n\"\"\"\n#Listeria\n\nListeria is a genus of bacteria that acts as an intracellular parasite in mammals. Until 1992, 10 species were known, each containing two subspecies. By 2019, 20 species had been identified. The genus received its current name, after the British pioneer of sterile surgery Joseph Lister, in 1940. Listeria species are Gram-positive, rod-shaped, and facultatively anaerobic, and do not produce endospores. The major human pathogen in the genus Listeria is L. monocytogenes. It is usually the causative agent of the relatively rare bacterial disease listeriosis, an infection caused by eating food contaminated with the bacteria.https:\/\/en.wikipedia.org\/wiki\/Listeria\n\"\"\"\n\"\"\"\n#A bacteriophage endolysin-based electrochemical impedance biosensor for the rapid detection of Listeria cells\n\nAuthors: Mona Tolba,   Minhaz Uddin Ahmed,   Chaker Tlili,   Fritz Eichenseher,   Martin J. Loessner  and  Mohammed Zourob\n\n![](https:\/\/pubs.rsc.org\/en\/Image\/Get?imageInfo.ImageType=GA&imageInfo.ImageIdentifier.ManuscriptID=C2AN35988J&imageInfo.ImageIdentifier.Year=2012)https:\/\/pubs.rsc.org\/en\/content\/articlelanding\/2012\/an\/c2an35988j#!divAbstract\n\"\"\"\n# 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)\nimport plotly.express as px\nimport seaborn as sns\nimport plotly.graph_objects as go\nimport plotly.offline as py\nimport matplotlib.pyplot as plt\nimport warnings\nfrom pandas_profiling import ProfileReport \nfrom pycaret.regression import *\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\ndf = pd.read_csv('..\/input\/carbonelectrodesmilkbiosensors\/iMicroq carbon magenta 8x\/Listeria\/G19 104 (magenta carbon)_1018.csv', encoding='ISO-8859-2')\ndf.head()\nfrom colorama import Fore, Style\n\ndef count(string: str, color=Fore.RED):\n    \"\"\"\n    Saves some work \n    \"\"\"\n    print(color+string+Style.RESET_ALL)\ndef statistics(dataframe, column):\n    count(f\"The Average value in {column} is: {dataframe[column].mean():.2f}\", Fore.RED)\n    count(f\"The Maximum value in {column} is: {dataframe[column].max()}\", Fore.BLUE)\n    count(f\"The Minimum value in {column} is: {dataframe[column].min()}\", Fore.YELLOW)\n    count(f\"The 25th Quantile of {column} is: {dataframe[column].quantile(0.25)}\", Fore.GREEN)\n    count(f\"The 50th Quantile of {column} is: {dataframe[column].quantile(0.50)}\", Fore.CYAN)\n    count(f\"The 75th Quantile of {column} is: {dataframe[column].quantile(0.75)}\", Fore.MAGENTA)\n# Print Offset Column Statistics\nstatistics(df, '0.0442')\n# Let's plot the 0.0442 column too\nplt.style.use(\"classic\")\nsns.distplot(df['0.0442'], color='blue')\nplt.title(f\"0.0442 Distribution [\\u03BC : {df['0.0442'].mean():.2f} conditions | \\u03C3 : {df['0.0442'].std():.2f} conditions]\")\nplt.xlabel(\"0.0442\")\nplt.ylabel(\"Count\")\nplt.show()\n# Print Offset Column Statistics\nstatistics(df, '-0.0197')\n# Let's plot the 0.0442 column too\nplt.style.use(\"classic\")\nsns.distplot(df['-0.0197'], color='red')\nplt.title(f\"-0.0197 Distribution [\\u03BC : {df['-0.0197'].mean():.2f} conditions | \\u03C3 : {df['-0.0197'].std():.2f} conditions]\")\nplt.xlabel(\"-0.0197\")\nplt.ylabel(\"Count\")\nplt.show()\ncorr = df.corr()\ncorr.style.background_gradient(cmap = 'coolwarm')\nimport matplotlib.gridspec as gridspec\nfrom scipy.stats import skew\nfrom sklearn.preprocessing import RobustScaler,MinMaxScaler\nfrom scipy import stats\nimport matplotlib.style as style\nstyle.use('seaborn-colorblind')\ndef plotting_3_chart(df, feature): \n    ## Creating a customized chart. and giving in figsize and everything. \n    fig = plt.figure(constrained_layout=True, figsize=(10,6))\n    ## crea,ting a grid of 3 cols and 3 rows. \n    grid = gridspec.GridSpec(ncols=3, nrows=3, figure=fig)\n    #gs = fig3.add_gridspec(3, 3)\n\n    ## Customizing the histogram grid. \n    ax1 = fig.add_subplot(grid[0, :2])\n    ## Set the title. \n    ax1.set_title('Histogram')\n    ## plot the histogram. \n    sns.distplot(df.loc[:,feature], norm_hist=True, ax = ax1)\n\n    # customizing the QQ_plot. \n    ax2 = fig.add_subplot(grid[1, :2])\n    ## Set the title. \n    ax2.set_title('QQ_plot')\n    ## Plotting the QQ_Plot. \n    stats.probplot(df.loc[:,feature], plot = ax2)\n\n    ## Customizing the Box Plot. \n    ax3 = fig.add_subplot(grid[:, 2])\n    ## Set title. \n    ax3.set_title('Box Plot')\n    ## Plotting the box plot. \n    sns.boxplot(df.loc[:,feature], orient='v', ax = ax3 );\n \n\nprint('Skewness: '+ str(df['0.0393'].skew())) \nprint(\"Kurtosis: \" + str(df['0.0393'].kurt()))\nplotting_3_chart(df, '0.0393')\n#Code from Gabriel Preda\n#plt.style.use('dark_background')\ndef plot_count(feature, title, df, size=1):\n    f, ax = plt.subplots(1,1, figsize=(4*size,4))\n    total = float(len(df))\n    g = sns.countplot(df[feature], order = df[feature].value_counts().index[:20], palette='Blues')\n    g.set_title(\"Number and percentage of {}\".format(title))\n    if(size > 2):\n        plt.xticks(rotation=90, size=8)\n    for p in ax.patches:\n        height = p.get_height()\n        ax.text(p.get_x()+p.get_width()\/2.,\n                height + 3,\n                '{:1.2f}%'.format(100*height\/total),\n                ha=\"center\") \n    plt.show()\nplot_count(\"0.0393\", \"0.0393\", df,4)\n\"\"\"\n#AutoViz: A New Tool for Automated Visualization, Written on December 28th, 2019 by Dan Roth.\n\nIt is not hard to see how helpful automated visualization can be. Within moments, the library is capable of generating highly informational plots and provides many pathways of potential expansion for a data scientist's modeling or analysis pipeline. AutoViz is meant to be integrated within a systematic iterative process. Exploratory data analysis (EDA) can be effectively initiated with AutoViz; features can be selected based on the tool's analysis and then the data can be repeatedly processed for automatic visualization. Once strong visualizations are generated, a data scientist can now jump into modeling or communicating the data with a well informed analysis. It is surprising that automated visualization options are so sparse given its many conceivable uses as an objective and practical tool, but AutoViz thankfully fulfills this role to great effect. Now let's get some visualizations going!https:\/\/danrothdatascience.github.io\/datascience\/autoviz.html\n\"\"\"\n!pip install autoviz\n\nfrom autoviz.AutoViz_Class import AutoViz_Class\nAV = AutoViz_Class()\ndf = AV.AutoViz(filename=\"\",sep=',', depVar='0.0442', dfte=df, header=0, verbose=2, \n                 lowess=False, chart_format='svg', max_rows_analyzed=150000, max_cols_analyzed=30)\n\"\"\"\n#Reference\n https:\/\/github.com\/DanRothDataScience\/autoviz_test\/blob\/master\/AutoViz_test.ipynb\nhttps:\/\/www.kaggle.com\/nareshbhat\/data-visualization-in-just-a-single-line-of-\n\"\"\"\n#Code by Olga Belitskaya https:\/\/www.kaggle.com\/olgabelitskaya\/sequential-data\/comments\nfrom IPython.display import display,HTML\nc1,c2,f1,f2,fs1,fs2=\\\n'#2B3A67','#42a7f5','Akronim','Smokum',30,15\ndef dhtml(string,fontcolor=c1,font=f1,fontsize=fs1):\n    display(HTML(\"\"\"<style>\n    @import 'https:\/\/fonts.googleapis.com\/css?family=\"\"\"\\\n    +font+\"\"\"&effect=3d-float';<\/style>\n    <h1 class='font-effect-3d-float' style='font-family:\"\"\"+\\\n    font+\"\"\"; color:\"\"\"+fontcolor+\"\"\"; font-size:\"\"\"+\\\n    str(fontsize)+\"\"\"px;'>%s<\/h1>\"\"\"%string))\n    \n    \ndhtml('Programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge, Grace Hopper quote' )","meta":"{'source': 'AI4Code', 'id': 'bc013c7f3f19eb'}"}
{"id":"52168","text":"\"\"\"\n## This is the KERAS CNN implementation for the CHEST X RAY IMAGES with > 93% validation accuracy and >85% test set accuracy**\n\n#### ANY FEEDBACK IN THE COMMENTS WILL BE HIGHLY APPRECIATED.\n\"\"\"\n\"\"\"\n\n\n### Breakdown of this notebook:\n\n1. Loading the dataset: Load the data and import the libraries.\n2. Data Preprocessing:\n     * Reading the images stored in 3 folders(Train,Val,Test).\n     * Plotting the NORMAL and PNEUMONIA images with their respective labels.\n3. Data Augmentation: Augment the train,validation and test data using ImageDataGenerator\n4. Creating and Training the Model: Create a CNN model in KERAS.\n5. Evaluation: Display the plots from the training history.\n6. Prediction: Run predictions with model.predict\n7. Conclusion: Comparing original labels with predicted labels and calculating recall score\n\"\"\"\n# 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 in \nimport warnings\nwarnings.filterwarnings('ignore')\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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport keras\nimport matplotlib.pyplot as plt\nfrom glob import glob \nfrom keras.models import Sequential \nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten, ZeroPadding2D, Conv2D, MaxPooling2D,Input,SeparableConv2D\nfrom keras.preprocessing.image import ImageDataGenerator #Data augmentation and preprocessing\nfrom keras.utils import to_categorical \nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping, ReduceLROnPlateau\nfrom keras.layers.normalization import BatchNormalization\nimport cv2\nfrom PIL import Image\nfrom pathlib import Path\nfrom sklearn.metrics import roc_auc_score,roc_curve,accuracy_score,recall_score,confusion_matrix,classification_report\n\n\"\"\"\n### Exploring the directories in our dataset\n\"\"\"\nprint(os.listdir(\"..\/input\/chest_xray\/chest_xray\"))\npath_train = \"..\/input\/chest_xray\/chest_xray\/train\"\npath_val = \"..\/input\/chest_xray\/chest_xray\/val\"\npath_test = \"..\/input\/chest_xray\/chest_xray\/test\"\n\"\"\"\n### Example plots of images in NORMAL and PNEOMONIA folder\n\"\"\"\nplt.figure(1, figsize = (15 , 7))\nplt.subplot(1 , 2 , 1)\nimg = glob(path_train+\"\/PNEUMONIA\/*.jpeg\") #Getting an image in the PNEUMONIA folder\nimg = np.asarray(plt.imread(img[0]))\nplt.title('PNEUMONIA X-RAY')\nplt.imshow(img)\n\nplt.subplot(1 , 2 , 2)\nimg = glob(path_train+\"\/NORMAL\/*.jpeg\") #Getting an image in the NORMAL folder\nimg = np.asarray(plt.imread(img[0]))\nplt.title('NORMAL CHEST X-RAY')\nplt.imshow(img)\n\nplt.show()\n\n\"\"\"\n### AUGMENTATION ON TRAINING, VALIDATION, TEST DATA\n\"\"\"\n\"\"\"\nData augmentation is a powerful technique which helps in almost every case for improving the robustness of a model. But augmentation can be much more helpful where the dataset is imbalanced. You can generate different samples of undersampled class in order to try to balance the overall distribution.\n\"\"\"\n\ntrain_gen = ImageDataGenerator(rescale = 1.\/255,\n                             shear_range = 0.2,\n                             zoom_range = 0.2,\n                             horizontal_flip=True)\n\nval_gen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_batch = train_gen.flow_from_directory(path_train,\n                                            target_size = (224, 224),\n                                            classes = [\"NORMAL\", \"PNEUMONIA\"],\n                                            class_mode = \"categorical\")\nval_batch = val_gen.flow_from_directory(path_val,\n                                        target_size = (224, 224),\n                                        classes = [\"NORMAL\", \"PNEUMONIA\"],\n                                        class_mode = \"categorical\")\ntest_batch = val_gen.flow_from_directory(path_test,\n                                         target_size = (224, 224),\n                                         classes = [\"NORMAL\", \"PNEUMONIA\"],\n                                         class_mode = \"categorical\")\n\nprint(train_batch.image_shape)\n\"\"\"\n### Creating the CNN model\n\n* I have used Keras's Functional API to build the Sequential model.I find it to be a better and easier way to deine a Convolutional Neural Net Model.Below is the reference to Functional API documentation by KERAS:-\nhttps:\/\/keras.io\/getting-started\/functional-api-guide\/\n\n* In the model, use Depthwise \"SeparableConv\" layer,which is less computationally expensive than standard \"CONV2D\" layer.The convolution operation in \"SeparableConv2D\" layer is applied to a single channel at a time, unlike normal convolution where the operation is applied to all the channels at once. With that, the number of parameters and multiplications to be done are reduced, making it faster than normal convolution. In practice that's the advantage of using it, it's really helpful in large neural net structures, MobileNet and Xception for example are based on this type of convolution. I'll recommend you watch this video, helped me a lot when I was studying. https:\/\/www.youtube.com\/watch?v=T7o3xvJLuHk\n\n\n\"\"\"\ndef build_model():\n    input_img = Input(shape=train_batch.image_shape, name='ImageInput')\n    x = Conv2D(64, (3,3), activation='relu', padding='same')(input_img)\n    x = Conv2D(64, (3,3), activation='relu', padding='same')(x)\n    x = MaxPooling2D((2,2))(x)\n    \n    x = SeparableConv2D(128, (3,3), activation='relu', padding='same')(x)\n    x = SeparableConv2D(128, (3,3), activation='relu', padding='same')(x)\n    x = MaxPooling2D((2,2))(x)\n    \n    x = SeparableConv2D(256, (3,3), activation='relu', padding='same')(x)\n    x = BatchNormalization()(x)\n    x = SeparableConv2D(256, (3,3), activation='relu', padding='same')(x)\n    x = BatchNormalization()(x)\n    x = SeparableConv2D(256, (3,3), activation='relu', padding='same')(x)\n    x = MaxPooling2D((2,2))(x)\n    \n    x = SeparableConv2D(512, (3,3), activation='relu', padding='same')(x)\n    x = BatchNormalization()(x)\n    x = SeparableConv2D(512, (3,3), activation='relu', padding='same')(x)\n    x = BatchNormalization()(x)\n    x = SeparableConv2D(512, (3,3), activation='relu', padding='same')(x)\n    x = MaxPooling2D((2,2))(x)\n    \n    x = Flatten(name='flatten')(x)\n    x = Dense(1024, activation='relu')(x)\n    x = Dropout(0.7)(x)\n    x = Dense(512, activation='relu')(x)\n    x = Dropout(0.5)(x)\n    x = Dense(2, activation='softmax')(x)\n    \n    model = Model(inputs=input_img, outputs=x)\n    \n    return model\n\"\"\"\n### Function for getting accuracy and loss plots \n\"\"\"\ndef create_plots(history):\n    \n    plt.plot(history.history['acc'])\n    plt.plot(history.history['val_acc'])\n    plt.title('Model accuracy')\n    plt.ylabel('Accuracy')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()\n\n    # Plot training & validation loss values\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('Loss')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()\nmodel= build_model()\nmodel.summary()\n\n\"\"\"\n### Here I have used 4 callbacks to get the best model\nYou can experiment by changing the number of epochs and changing the monitoring parameters. However, increasing the number of epochs increases the computation time but gives better results in visualizing the plots and getting the best model.\n\"\"\"\nbatch_size = 16\nepochs = 50\nearly_stop = EarlyStopping(patience=25,\n                           verbose = 2,\n                           monitor='val_loss',\n                           mode='auto')\n\ncheckpoint = ModelCheckpoint(\n    filepath='best_model',\n    save_best_only=True,\n    save_weights_only=True,\n    monitor='val_loss',\n    mode='auto',\n    verbose = 1)\n\nreduce = ReduceLROnPlateau(\n    monitor='val_loss',\n    factor=0.8,\n    patience=5,\n    verbose=1, \n    mode='auto',\n    min_delta=0.0001, \n    cooldown=1, \n    min_lr=0.0001\n)\n\nmodel.compile(loss='binary_crossentropy',\n              metrics=['accuracy'],\n              optimizer=Adam(lr=0.0001))\n\nhistory = model.fit_generator(epochs=epochs,\n                              callbacks=[early_stop,checkpoint,reduce],\n                              shuffle=True,\n                              validation_data=val_batch,\n                              generator=train_batch,\n                              steps_per_epoch=500,\n                              validation_steps=10,\n                              verbose=2)\n\n\"\"\"\n### Loss and accuracy plots\n\"\"\"\ncreate_plots(history)\n\"\"\"\n### Getting the images and labels from test data\n\"\"\"\noriginal_test_label=[]\nimages=[]\n\ntest_normal=Path(\"..\/input\/chest_xray\/chest_xray\/test\/NORMAL\") \nnormal = test_normal.glob('*.jpeg')\nfor i in normal:\n    img = cv2.imread(str(i))\n#     print(\"normal\",img)\n    if img.shape[2] ==1:\n        img = np.dstack([img, img, img])\n    else:\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    try:\n        img = cv2.resize(img, (224,224))\n    except Exception as e:\n        print(str(e))\n    images.append(img)\n    label = to_categorical(0, num_classes=2)\n    original_test_label.append(label)\n\ntest_pneumonia = Path(\"..\/input\/chest_xray\/chest_xray\/test\/PNEUMONIA\")\npneumonia = test_pneumonia.glob('*.jpeg')\nfor i in pneumonia:\n    img = cv2.imread(str(i))\n#     print(\"pneumonia\",img)\n    if img.shape[2] ==1:\n        img = np.dstack([img, img, img])\n    else:\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    try:\n        img = cv2.resize(img, (224,224))\n    except Exception as e:\n        print(str(e))\n    images.append(img)\n    label = to_categorical(1, num_classes=2)\n    original_test_label.append(label)    \n\n    \nimages = np.array(images)\noriginal_test_label = np.array(original_test_label)\nprint(original_test_label.shape)\n\n\norig_test_labels = np.argmax(original_test_label, axis=-1)\n# print(orig_test_labels)\n# print(p)\n\n\n\n\"\"\"\n### Prediction on test set images\n\"\"\"\np = model.predict(images, batch_size=16)\npreds = np.argmax(p, axis=-1)\nprint(preds.shape)\n\n\"\"\"\n### Evaluation of model on test set\n\"\"\"\ntest_loss, test_score = model.evaluate_generator(test_batch,steps=100)\nprint(\"Loss on test set: \", test_loss)\nprint(\"Accuracy on test set: \", test_score)\n\"\"\"\n### Validation Accuracy and Recall score\n\"\"\"\nprint(\"Accuracy: \" + str(history.history['val_acc'][-1:]))\nrecall_score(orig_test_labels,preds)\n","meta":"{'source': 'AI4Code', 'id': '600304d2b43a01'}"}
{"id":"68250","text":"\"\"\"\n<center><h1 class=\"list-group-item list-group-item-success\">Arrhythmia Detection<\/h1><\/center>\n\"\"\"\n# Importing Required Packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.layers import Conv1D\nimport wfdb                            # Package for loading the ecg and annotation\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score\nimport warnings\nwarnings.filterwarnings(\"ignore\") \nimport random\nfrom keras.layers import Bidirectional, LSTM\n# Random Initialization\nrandom.seed(42)\n# Importing Data\ndata = '..\/input\/mit-bih-arrhythmia-database\/'\n# List of Patients\npatients = ['100','101','102','103','104','105','106','107',\n           '108','109','111','112','113','114','115','116',\n           '117','118','119','121','122','123','124','200',\n           '201','202','203','205','207','208','209','210',\n           '212','213','214','215','217','219','220','221',\n           '222','223','228','230','231','232','233','234']\n# Creating a Empty Dataframe\nsymbols_df = pd.DataFrame()\n\n# Reading all .atr files \nfor pts in patients:\n    # Generating filepath for all .atr file names\n    file = data + pts\n    # Saving annotation object\n    annotation = wfdb.rdann(file, 'atr')\n    # Extracting symbols from the object\n    sym = annotation.symbol\n    # Saving value counts\n    values, counts = np.unique(sym, return_counts=True)\n    # Writing data points into dataframe\n    df_sub = pd.DataFrame({'symbol':values, 'Counts':counts, 'Patient Number':[pts]*len(counts)})\n    # Concatenating all data points  \n    symbols_df = pd.concat([symbols_df, df_sub],axis = 0)\n# Symbols Dataframe\nsymbols_df\n# Value Counts of Different symbols in data\nsymbols_df.groupby('symbol').Counts.sum().sort_values(ascending = False)\n# Non Beat Symbols\nnonbeat = ['[','!',']','x','(',')','p','t','u','`',\n           '\\'','^','|','~','+','s','T','*','D','=','\"','@','Q','?']\n\n# Abnormal Beat Symbols\nabnormal = ['L','R','V','\/','A','f','F','j','a','E','J','e','S']\n\n# Normal Beat Symbols\nnormal = ['N']\n# Classifying normal, abnormal or nonbeat\nsymbols_df['category'] = -1\nsymbols_df.loc[symbols_df.symbol == 'N','category'] = 0\nsymbols_df.loc[symbols_df.symbol.isin(abnormal), 'category'] = 1\n# Value counts of different categories\nsymbols_df.groupby('category').Counts.sum()\ndef load_ecg(file):    \n    # load the ecg\n    record = wfdb.rdrecord(file)\n    # load the annotation\n    annotation = wfdb.rdann(file, 'atr')\n    \n    # extracting the signal\n    p_signal = record.p_signal\n\n    # extracting symbols and annotation index\n    atr_sym = annotation.symbol\n    atr_sample = annotation.sample\n    \n    return p_signal, atr_sym, atr_sample\n# Accessing the ecg points for \nfile = data + patients[8]\n# Accessing the load ECG function and getting annotation.symbol, annotation.sample, signals\np_signal, atr_sym, atr_sample = load_ecg(file)\n# Analysing annotations value counts for a single record\nvalues, counts = np.unique(sym, return_counts=True)\nfor v,c in zip(values, counts):\n    print(v,c)\n# get abnormal beat index\nab_index = [b for a,b in zip(atr_sym,atr_sample) if a in abnormal][:10]\nab_index\n# Generating evenly spaced values\nx = np.arange(len(p_signal))\n\nleft = ab_index[5]-20000\nright = ab_index[5]+20000\n\nplt.figure(figsize=(20,8))\nplt.plot(x[left:right],p_signal[left:right,0],'-',label='ecg',)\nplt.plot(x[atr_sample],p_signal[atr_sample,0],'go',label ='normal')\nplt.plot(x[ab_index],p_signal[ab_index,0],'ro',label='abnormal')\n\nplt.xlim(left,right)\nplt.ylim(p_signal[left:right].min()-0.05,p_signal[left:right,0].max()+0.05)\nplt.xlabel('time index')\nplt.ylabel('ECG signal')\nplt.legend(bbox_to_anchor = (1.04,1), loc = 'upper left')\nplt.show()\ndef make_dataset(pts, num_sec, fs, abnormal):\n    # function for making dataset ignoring non-beats\n    # input:\n    #   pts - list of patients\n    #   num_sec = number of seconds to include before and after the beat\n    #   fs = frequency\n    # output: \n    #   X_all = signal (nbeats , num_sec * fs columns)\n    #   Y_all = binary is abnormal (nbeats, 1)\n    #   sym_all = beat annotation symbol (nbeats,1)\n    \n    # initialize numpy arrays\n    num_cols = 2*num_sec * fs\n    X_all = np.zeros((1,num_cols))\n    Y_all = np.zeros((1,1))\n    sym_all = []\n    \n    # list to keep track of number of beats across patients\n    max_rows = []\n    \n    for pt in pts:\n        file = data + pt\n        \n        p_signal, atr_sym, atr_sample = load_ecg(file)\n        \n        # grab the first signal\n        p_signal = p_signal[:,0]\n        \n        # make df to exclude the nonbeats\n        df_ann = pd.DataFrame({'atr_sym':atr_sym,\n                              'atr_sample':atr_sample})\n        df_ann = df_ann.loc[df_ann.atr_sym.isin(abnormal + ['N'])]\n        \n        X,Y,sym = build_XY(p_signal,df_ann, num_cols, abnormal)\n        sym_all = sym_all+sym\n        max_rows.append(X.shape[0])\n        X_all = np.append(X_all,X,axis = 0)\n        Y_all = np.append(Y_all,Y,axis = 0)\n        \n    # drop the first zero row\n    X_all = X_all[1:,:]\n    Y_all = Y_all[1:,:]\n\n    return X_all, Y_all, sym_all\n\ndef build_XY(p_signal, df_ann, num_cols, abnormal):\n    # this function builds the X,Y matrices for each beat\n    # it also returns the original symbols for Y\n    \n    num_rows = len(df_ann)\n\n    X = np.zeros((num_rows, num_cols))\n    Y = np.zeros((num_rows,1))\n    sym = []\n    \n    # keep track of rows\n    max_row = 0\n\n    for atr_sample, atr_sym in zip(df_ann.atr_sample.values,df_ann.atr_sym.values):\n\n        left = max([0,(atr_sample - num_sec*fs) ])\n        right = min([len(p_signal),(atr_sample + num_sec*fs) ])\n        x = p_signal[left: right]\n        if len(x) == num_cols:\n            X[max_row,:] = x\n            Y[max_row,:] = int(atr_sym in abnormal)\n            sym.append(atr_sym)\n            max_row += 1\n    X = X[:max_row,:]\n    Y = Y[:max_row,:]\n    return X,Y,sym\n# Parameter Values\nnum_sec = 3\nfs = 360\n# Accessing the fuction and creating a dataset with ECG digital Points\nX_all, Y_all, sym_all = make_dataset(patients, num_sec, fs, abnormal)\n# Train Test Split\nX_train, X_valid, y_train, y_valid = train_test_split(X_all, Y_all, test_size=0.33, random_state=42)\n# Relu for activation function and drop out for regularization\nmodel = Sequential()\nmodel.add(Dense(32, activation = 'relu', input_dim = X_train.shape[1]))\nmodel.add(Dropout(rate = 0.25))\nmodel.add(Dense(1, activation = 'sigmoid'))\n# Compiling model with  binary crossentropy and the adam optimizer\nmodel.compile(loss = 'binary_crossentropy',\n                optimizer = 'adam',\n                metrics = ['accuracy'])\n# Fitting the model\nmodel.fit(X_train, y_train, batch_size = 32, epochs= 10, verbose = 1)\n# Evaluation Metrics\ndef print_report(y_actual, y_pred, thresh):\n    # Function to print evaluation metrics\n    auc = roc_auc_score(y_actual, y_pred)\n    accuracy = accuracy_score(y_actual, (y_pred > thresh))\n    recall = recall_score(y_actual, (y_pred > thresh))\n    precision = precision_score(y_actual, (y_pred > thresh))\n    specificity = sum((y_pred < thresh) & (y_actual == 0)) \/sum(y_actual ==0)\n    prevalence = (sum(y_actual)\/len(y_actual))\n    print('AUC:%.3f'%auc)\n    print('Accuracy:%.3f'%accuracy)\n    print('Recall:%.3f'%recall)\n    print('Precision:%.3f'%precision)\n    print('Specificity:%.3f'%specificity)\n    print('Prevalence:%.3f'%prevalence)\n    print(' ')\n    return auc, accuracy, recall, precision, specificity\n# Predictions\ny_train_preds_dense = model.predict(X_train,verbose = 1)\ny_valid_preds_dense = model.predict(X_valid,verbose = 1)\n# Threshold Value\nthresh = (sum(y_train)\/len(y_train))[0]\n# Accessing Evaluation Metrics Function\nprint('On Train Data')\nprint_report(y_train, y_train_preds_dense, thresh)\nprint('On Valid Data')\nprint_report(y_valid, y_valid_preds_dense, thresh)\n# reshape input to [samples, time steps, features = 1] for CNN\nX_train_cnn = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\nX_valid_cnn = np.reshape(X_valid, (X_valid.shape[0], X_valid.shape[1], 1))\n\nprint(X_train_cnn.shape)\nprint(X_valid_cnn.shape)\n# Relu for activation function & Dropout for reducing overfitting by randomly removing some nodes.\nmodel = Sequential()\nmodel.add(Conv1D(filters = 128, kernel_size = 5, activation = 'relu', input_shape = (2160,1)))\nmodel.add(Dropout(rate = 0.25))\nmodel.add(Flatten())\nmodel.add(Dense(1, activation = 'sigmoid'))\n\n# compile the model with binary crossentropy, and the adam optimizer\nmodel.compile(loss = 'binary_crossentropy',\n                optimizer = 'adam',\n                metrics = ['accuracy'])\n\n# Fitting data in model\nmodel.fit(X_train_cnn, y_train, batch_size = 32, epochs= 2, verbose = 1)\n# Predictions\ny_train_preds_cnn = model.predict(X_train_cnn,verbose = 1)\ny_valid_preds_cnn = model.predict(X_valid_cnn,verbose = 1)\n# Metrics\nprint('Train');\nprint_report(y_train, y_train_preds_cnn, thresh)\nprint('Valid');\nprint_report(y_valid, y_valid_preds_cnn, thresh);\n# Bidirectional LSTM with Dropout for reducing overfitting by randomly removing some nodes.\nmodel = Sequential()\nmodel.add(Bidirectional(LSTM(64, input_shape=(X_train_cnn.shape[1], X_train_cnn.shape[2]))))\nmodel.add(Dropout(rate = 0.25))\nmodel.add(Dense(1, activation = 'sigmoid'))\nmodel.compile(\n                loss = 'binary_crossentropy',\n                optimizer = 'adam',\n                metrics = ['accuracy'])\n# Fitting Data\nmodel.fit(X_train_cnn[:10000], y_train[:10000], batch_size = 32, epochs= 1, verbose = 1)\n# Prediction\ny_train_preds_lstm = model.predict(X_train_cnn[:10000],verbose = 1)\ny_valid_preds_lstm = model.predict(X_valid_cnn,verbose = 1)\n# Metrics\nprint('Train');\nprint_report(y_train[:10000], y_train_preds_lstm, thresh)\nprint('Valid');\nprint_report(y_valid, y_valid_preds_lstm, thresh);\n\"\"\"\n#### LSTM is not working good on data because we are using a subset of data\n\"\"\"\nfrom sklearn.metrics import roc_curve, roc_auc_score\n\nfpr_valid_cnn, tpr_valid_cnn, t_valid_cnn = roc_curve(y_valid, y_valid_preds_cnn)\nauc_valid_cnn = roc_auc_score(y_valid, y_valid_preds_cnn)\n\nfpr_valid_dense, tpr_valid_dense, t_valid_dense = roc_curve(y_valid, y_valid_preds_dense)\nauc_valid_dense = roc_auc_score(y_valid, y_valid_preds_dense)\n\nfpr_valid_lstm, tpr_valid_lstm, t_valid_lstm = roc_curve(y_valid, y_valid_preds_lstm)\nauc_valid_lstm = roc_auc_score(y_valid, y_valid_preds_lstm)\n\nplt.plot(fpr_valid_cnn, tpr_valid_cnn, 'g-', label = 'CNN AUC:%.3f'%auc_valid_cnn)\nplt.plot(fpr_valid_dense, tpr_valid_dense, 'r-', label = 'Dense AUC:%.3f'%auc_valid_dense)\nplt.plot(fpr_valid_lstm, tpr_valid_lstm, 'b-', label = 'LSTM AUC:%.3f'%auc_valid_lstm)\n\nplt.plot([0,1],[0,1], 'k--')\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.legend(bbox_to_anchor = (1.04,1), loc = 'upper left')\nplt.title('Validation Set')\nplt.show()\n","meta":"{'source': 'AI4Code', 'id': '7d90588b120a3a'}"}
{"id":"87331","text":"\"\"\"\nThe objective of the competition is to predict the time it will take to complete the testing phase. The dataset represents various permutations of the characteristics of Mercedes-Benz vehicles. Reducing the algorithm run time can also help reduce carbon dioxide emissions without compromising Daimler's standards.\n\nThe dataset contains an anonymized set of variables (user-defined functions) in a Mercedes vehicle. For example, a variable could be 4WD, it could be an added air suspension, or a head display.\n\ny is the variable to be predicted, this is the time (in seconds) it took for the car to be tested for each variable\n\nVariables containing letters are categorical. Variables with 0\/1 are of binary type.\n\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n%matplotlib inline\ncolors = ['#001c57','#40948f','#a6a6a6','#99d1df']\nsns.palplot(sns.color_palette(colors))\ntrain = pd.read_csv('\/kaggle\/input\/mercedesbenz-greener-manufacturing\/train.csv')\ntest = pd.read_csv('\/kaggle\/input\/mercedesbenz-greener-manufacturing\/test.csv')\nplt.figure(figsize=(16,6))\nplt.subplot(121)\nsns.distplot(train.y.values, bins=50, color=colors[1])\nplt.title('Target Value Distribution - y\\n',fontsize=15)\nplt.xlabel('Value in Seconds'); plt.ylabel('Frequecy');\n\nplt.subplot(122)\nsns.boxplot(train.y.values, color=colors[3])\nplt.title('Target Value Distribution - y\\n',fontsize=15)\nplt.xlabel('Value in Seconds')\ntrain['y'].describe()\n\"\"\"\nThe target variable has a standard distribution of about 72 to 140 seconds. The first and third quartiles lie in the range from about 91 to 109 seconds, the median is 100 seconds, we also note that there are outliers starting from 140 seconds that we can remove from the training sample, since these values \u200b\u200bwill add noise to our algorithm.\n\n\"\"\"\ntrain.dtypes.value_counts()\ntrain.dtypes[train.dtypes=='float']\ndtype_df = train.dtypes.reset_index()\ndtype_df.columns = [\"Count\", \"Column Type\"]\ndtype_df.groupby(\"Column Type\").aggregate('count').reset_index()\ntrain.dtypes[train.dtypes=='object']\nobj_dtype = train.dtypes[train.dtypes=='object'].index\nfor i in obj_dtype:\n    print(i, train[i].unique())\ntrain.isna().sum()[train.isna().sum()>0]\nfig,ax = plt.subplots(len(obj_dtype), figsize=(18,80))\n\nfor i, col in enumerate(obj_dtype):\n    sns.boxplot(x=col, y='y', data=train, ax=ax[i])\n\"\"\"\nInference from the graphs:\n\n1) Since there is a need to reduce the testing time, the best values in the variables at which this time is minimal are az and bc (X0), y (X1), n (X2), x and h (X5) (hypothesis: on y?)\n\n2) Variables X3, X5, X6, X8 have similar distributions of values, where there are no special differences within the feature between values in the context of means and quartiles\n\n3) X0 and X2 have the greatest variety within variables, which can potentially indicate a greater usefulness of these features\n\n\"\"\"\nnum = train.dtypes[train.dtypes=='int'].index[1:]\n\"\"\"\nWe have a set of numeric variables, where the value is set to 1 or 0, so there is no need to carry out volumetric analysis. In this case, we should be interested in whether the value of indicators changes within the variables, for this we examine the variance of these variables, use the var () function, and select only those where the variance is zero (that is, always 0, or 1 on the entire dataset in variable cut)\n\"\"\"\nnan_num = []\nfor i in num:\n    if (train[i].var()==0):\n        print(i, train[i].var())\n        nan_num.append(i)\n\"\"\"\nWe received several such variables, we can remove them from the analysis, since they will not affect the target in any way, thereby increasing the performance of the algorithm.\n\"\"\"\ntrain = train.drop(columns=nan_num, axis=1)\ntrain.shape\n\"\"\"\nCovert the object data using label encoder\n\"\"\"\nfor i in obj_dtype:\n    le = LabelEncoder()\n    le.fit(list(train[i].values) + list(train[i].values))\n    train[i] = le.transform(list(train[i].values))\ntrain[obj_dtype].head()\ncorr = train[train.columns[1:10]].corr()\n\nfig,ax = plt.subplots(figsize=(12,10))\nsns.heatmap(corr, vmax=.7, square=True,annot=True);\n\"\"\"\nAmong the categorical variables, we did not find a direct relationship with the target y\n\"\"\"\nthreshold = 1\n\ncorr_all = train.drop(columns=obj_dtype, axis=1).corr()\ncorr_all.loc[:,:] =  np.tril(corr_all, k=-1) \ntrain.shape\nalready_in = set()\nresult = []\nfor col in corr_all:\n    perfect_corr = corr_all[col][corr_all[col] == threshold ].index.tolist()\n    if perfect_corr and col not in already_in:\n        already_in.update(set(perfect_corr))\n        perfect_corr.append(col)\n        result.append(perfect_corr)\nresult\n\"\"\"\nWhen analyzing numerical variables, we found that some of them have a direct correlation with others, therefore, in order to avoid multicollinearity, we can remove the variables with correlation 1 (leave one of the group), or use regularization so that the algorithm does it in automatic mode.\nHow else can we remove such variables without correlation? It's simple, we delete duplicates in the column section.\n\n\n\"\"\"\ntrain.T.drop_duplicates().T\n# Let me run an ensable model Random Forest\n\nfrom sklearn.model_selection import train_test_split\n\nx = train.drop('y',axis=1)\nx = train.drop('ID',axis=1)\ny = train['y']\nx_train,x_test, y_train, y_test = train_test_split(x, y, test_size=.2,random_state=10) \n\n\nfrom sklearn.ensemble import RandomForestRegressor\nmodel = RandomForestRegressor(n_estimators=200, max_depth=200, min_samples_leaf=4, max_features=0.2, n_jobs=-1, random_state=10)\nmodel.fit(x_train, y_train)\n\nprint(\"Traiing Score:- \",model.score(x_train,y_train)*100)\nprint(\"Testing Score:- \",model.score(x_test,y_test)*100)\n# Let me run an ensable model Gradient Boosting Regressor \n\nfrom sklearn.model_selection import train_test_split\n\nx = train.drop('y',axis=1)\nx = train.drop('ID',axis=1)\ny = train['y']\nx_train,x_test, y_train, y_test = train_test_split(x, y, test_size=.2,random_state=10) \n\n\nfrom sklearn.ensemble import GradientBoostingRegressor\nmodel = GradientBoostingRegressor()\n#model = ensemble.RandomForestRegressor(n_estimators=100, max_depth=10, min_samples_leaf=4, max_features=0.2, n_jobs=-1, random_state=0)\nmodel.fit(x_train, y_train)\n\nprint(\"Traiing Score:- \",model.score(x_train,y_train)*100)\nprint(\"Testing Score:- \",model.score(x_test,y_test)*100)\npredicted = model.predict(x_test)\npredicted\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nsns.distplot(predicted, bins=50, color=colors[1])\nplt.title('Target Value Distribution - y\\n',fontsize=15)\nplt.xlabel('Value in Seconds'); plt.ylabel('Frequecy');\n\nplt.subplot(122)\nsns.boxplot(predicted, color=colors[3])\nplt.title('Target Value Distribution - y\\n',fontsize=15)\nplt.xlabel('Value in Seconds');","meta":"{'source': 'AI4Code', 'id': 'a0239ce75d5662'}"}
{"id":"62365","text":"\"\"\"\n## Note\nIn this notebook, i just prepare the data then fine tuning VGG16 to diagnosis pneumonia. If you wanna see insight the dataset, please visit this notebook:\n\n-> https:\/\/www.kaggle.com\/luukhang\/build-alexnet-to-classifies-pneumonia.\n\nComparing the performance of pretrained of VGG16 and ResNet18, plese visit this notebook:\n\n-> https:\/\/www.kaggle.com\/luukhang\/transfer-learning-vgg16-to-classifies-pneumonia\n\"\"\"\n\"\"\"\n# 1. Import libs\n\"\"\"\n# Common lib\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\n\n# Utils\nfrom tqdm import tqdm\nimport datetime\n\n# Sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, confusion_matrix, auc\n\n# Tensorflow\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, Add, MaxPooling2D, Flatten, GlobalAveragePooling2D, Dense, Dropout\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, LearningRateScheduler, ReduceLROnPlateau\nfrom tensorflow.keras.metrics import AUC, TruePositives, TrueNegatives, FalsePositives, FalseNegatives\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img\nfrom tensorflow.keras.layers.experimental.preprocessing import Resizing, Rescaling\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.regularizers import l2\n\nprint(\"Import successfully\")\n\"\"\"\n# 2. Prepare data\n\"\"\"\n# Init variables\ninput_folder = '..\/input\/coronahack-chest-xraydataset'\ntest_img_folder = os.path.join(input_folder, 'Coronahack-Chest-XRay-Dataset', 'Coronahack-Chest-XRay-Dataset', 'test')\ntrain_img_folder = os.path.join(input_folder, 'Coronahack-Chest-XRay-Dataset', 'Coronahack-Chest-XRay-Dataset', 'train')\nmetadata_df = pd.read_csv(os.path.join(input_folder, 'Chest_xray_Corona_Metadata.csv'), index_col=0)\n# Split to train & test set\ntrain_df = metadata_df[metadata_df.Dataset_type == 'TRAIN'].reset_index(drop=True)\ntest_df = metadata_df[metadata_df.Dataset_type == 'TEST'].reset_index(drop=True)\n\n# Check train_df size + test_df size == metadata_df size\nassert train_df.size + test_df.size == metadata_df.size\n\nprint(f'Shape of train data: { train_df.shape }')\nprint(f'Shape of test data: { test_df.shape }')\n# fill na\ntrain_df.fillna('unknow', inplace=True)\ntest_df.fillna('unknow', inplace=True)\n# Image augmentation\ntrain_datagen = ImageDataGenerator(rotation_range=10,\n                              brightness_range=(0.8, 1.2),\n                              zoom_range=[0.75, 1],\n                              horizontal_flip=True)\ntest_datagen = ImageDataGenerator()\ntrain_df, valid_df = train_test_split(train_df, test_size=0.2, shuffle=True, random_state=42)\ntrain_batches = train_datagen.flow_from_dataframe(train_df,\n                                             directory=train_img_folder,\n                                             x_col='X_ray_image_name',\n                                             y_col='Label',\n                                             class_mode='binary',\n                                             batch_size=128)\n\nvalid_batches = test_datagen.flow_from_dataframe(valid_df,\n                                             directory=train_img_folder,\n                                             x_col='X_ray_image_name',\n                                             y_col='Label',\n                                             class_mode='binary',\n                                             batch_size=128)\n\ntest_batches = test_datagen.flow_from_dataframe(test_df,\n                                            directory=test_img_folder,\n                                            x_col='X_ray_image_name',\n                                            y_col='Label',\n                                            class_mode='binary',\n                                            batch_size=8,\n                                            shuffle=False)\nprint(f'Label encode: { valid_batches.class_indices }')\ntrain_batches_series = pd.Series(train_batches.classes)\nvalid_batches_series = pd.Series(valid_batches.classes)\n\nprint(f'Value count in train_batches: \\n{ train_batches_series.value_counts() }')\nprint(f'Value count in valid_batches: \\n{ valid_batches_series.value_counts() }')\n\"\"\"\n# 3. Fine tuning\n\"\"\"\ndef create_dir(dir_path):\n    if not os.path.exists(dir_path):\n        os.mkdir(dir_path)\n        \ncreate_dir('models')\n\"\"\"\n**Preprocessing layer**\n\"\"\"\nresize_and_rescale = Sequential([\n    Resizing(224, 224),\n    Rescaling(1.\/255)\n])\nmetrics = [TruePositives(name='TP'),\n           TrueNegatives(name='TN'),\n           FalsePositives(name='FP'),\n           FalseNegatives(name='FN'),\n           AUC(curve='PR', name='AUC')]\n!pip install git+https:\/\/github.com\/qubvel\/classification_models.git\nfrom classification_models.keras import Classifiers\nResNet18, preprocess_input = Classifiers.get('resnet18')\nbase_model = ResNet18((224, 224, 3), weights='imagenet', include_top=False)\n# Preprocess layer\nft_resnet18 = Sequential([resize_and_rescale]) \n# Feature extractor\nft_resnet18.add(base_model)\n# Classifier\nft_resnet18.add(GlobalAveragePooling2D())\nft_resnet18.add(Dense(1, activation='sigmoid'))\n# Freeze\n#for layer in ft_resnet34.layers[1].layers[:50]:\n#    layer.trainable = False\nresnet18_dir = 'models\/resnet18'\nresnet18_file = 'best_resnet18.hdf5'\n\ncreate_dir(resnet18_dir)\n\ncheckpoint = ModelCheckpoint(os.path.join(resnet18_dir, resnet18_file),\n                             monitor='val_loss',\n                             verbose=1,\n                             save_best_only=True,\n                             save_weights_only=False)\n\nearly_stopping = EarlyStopping(monitor='val_loss',\n                               patience=30,\n                               verbose=1,\n                               restore_best_weights=True)\n# Initialize TensorBoard\nlog_dir = 'models\/resnet18\/logs'\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)\nepochs = 200\nlr = 1e-4\n\nft_resnet18.compile(optimizer=Adam(lr=lr), loss='binary_crossentropy', metrics=metrics)\n\ntraining_time_start = datetime.datetime.now()\n\nresnet18_history = ft_resnet18.fit(train_batches,\n                                epochs=epochs,\n                                verbose=2,\n                                callbacks=[checkpoint, early_stopping],\n                                validation_data=valid_batches,\n                                steps_per_epoch=len(train_batches),\n                                validation_steps=len(valid_batches))\n\ntraining_time_end = datetime.datetime.now()\ntotal_training_seconds = (training_time_end - training_time_start).seconds\nprint('Total training time: ', str(datetime.timedelta(seconds=total_training_seconds)))\n\"\"\"\n# 4. Evaluate\n\"\"\"\nresnet18_hist_df = pd.DataFrame(resnet18_history.history)\nresnet18_hist_df.loc[:, ['loss', 'val_loss']].plot()\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.show()\nresnet18_hist_df.loc[:, ['AUC', 'val_AUC']].plot()\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.show()\nnum_of_epochs = resnet18_hist_df.shape[0]\nhalf_epoch = int(num_of_epochs \/ 2)\n\nfirst_half_resnet18_hist = resnet18_hist_df.loc[:half_epoch]\nfirst_title = f'Loss value at epoch 0 - { half_epoch }'\n\nlast_half_resnet18_hist = resnet18_hist_df.loc[half_epoch:len(resnet18_hist_df)]\nlast_title = f'Loss value at epoch { half_epoch } - { len(resnet18_hist_df) }'\n\nhists = [first_half_resnet18_hist, last_half_resnet18_hist]\ntitles = [first_title, last_title]\n\nfor i in range(2):\n    ax = hists[i][['loss', 'val_loss']].plot()\n    ax.set_xlabel('Epoch')\n    ax.set_ylabel('Loss value')\n    ax.set_title(titles[i])\nplt.show()\nfirst_title = f'AUC value at epoch 0 - { half_epoch }'\nlast_title = f'AUC value at epoch { half_epoch } - { len(resnet18_hist_df) }'\n\ntitles = [first_title, last_title]\n\nfor i in range(2):\n    ax = hists[i][['AUC', 'val_AUC']].plot()\n    ax.set_xlabel('Epoch')\n    ax.set_ylabel('AUC value')\n    ax.set_title(titles[i])\nplt.show()\nevaluate_resnet18 = ft_resnet18.evaluate(test_batches, verbose=1)\nloss, tp, tn, fp, fn, auc = evaluate_resnet18[0], evaluate_resnet18[1], evaluate_resnet18[2], evaluate_resnet18[3], evaluate_resnet18[4], evaluate_resnet18[5]\nprint(f'Test loss: { loss }')\nprint(f'True positive: { tp }')\nprint(f'True negative: { tn }')\nprint(f'False positive: { fp }')\nprint(f'False negative: { fn }')\nprint('AUC: %.2f' % auc)\n\"\"\"\n# 5. Plot PR curve and find optimal threshold\n\"\"\"\ndef find_optimal_threshold(precision, recall, threshold):\n    f1_score = (2 * precision * recall) \/ (precision + recall)\n    best_idx = np.argmax(f1_score)\n    best_threshold = threshold[best_idx]\n    return best_threshold, best_idx\n\"\"\"\n**Find the best threshold**\n\"\"\"\ny_true = test_batches.classes\ny_predict = ft_resnet18.predict(test_batches)\nprecision, recall, threshold = precision_recall_curve(y_true, y_predict)\nbest_threshold, best_idx = find_optimal_threshold(precision, recall, threshold)\nprint('Best threshold: {}'.format(best_threshold))\n\"\"\"\n**Plot ROC curve**\n\"\"\"\nplt.figure(figsize=(7, 5))\nauc_score = auc(recall, precision)\nplt.plot([1, 0], [0, 1], linestyle='--', color='black', label='No skill')\nplt.plot(recall, precision, linewidth=3, label='ResNet18')\nplt.plot(recall[best_idx], precision[best_idx], \n         marker='o', color='black', \n         label='Best_theshold', linestyle='', markersize='7')\nplt.xlabel('Recall', size=13)\nplt.ylabel('Precision', size=13)\nplt.title('Precision-Recall curve (AUC - {:.4f})'.format(auc_score), size=15)\nplt.legend()\nplt.show()\n\"\"\"\n# 6. Predict and plot confusion matrix\n\"\"\"\ny_predict = (y_predict >= best_threshold).astype('int')\ny_predict = np.reshape(y_predict, -1)\ncfs_matrix = confusion_matrix(y_true, y_predict)\nlabel = ['Normal', 'Pneumonia']\n\nplt.figure(figsize=(6, 5))\nplt.imshow(cfs_matrix, cmap=plt.cm.Reds)\nplt.colorbar()\nfor i in range(len(label)):\n    for j in range(len(label)):\n        plt.text(j, i, cfs_matrix[i, j],\n                 horizontalalignment='center', verticalalignment='center', size=14)\nplt.xticks(np.arange(len(label)), label)\nplt.yticks(np.arange(len(label)), label)\nplt.xlabel('Predicted label', size=13)\nplt.ylabel('True label', size=13)\nplt.title('Confusion matrix of ResNet18', size=15)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '72eac530ee257b'}"}
{"id":"2863","text":"\"\"\"\n# Chapter 4: Selecting Subsets of Data\n## Recipes\n* [Selecting Series data](#Selecting-Series-data)\n* [Selecting DataFrame rows](#Selecting-DataFrame-rows)\n* [Selecting DataFrame rows and columns simultaneously](#Selecting-DataFrame-rows-and-columns-simultaneously)\n* [Selecting data with both integers and labels](#Selecting-data-with-both-integers-and-labels)\n* [Speeding up scalar selection](#Speeding-up-scalar-selection)\n* [Slicing rows lazily](#Slicing-rows-lazily)\n* [Slicing lexicographically](#Slicing-Lexicographically)\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\"\"\"\n# Selecting Series data\n\"\"\"\ncollege = pd.read_csv('..\/input\/pandas-cookbook-data\/data\/college.csv', index_col='INSTNM')\ncity = college['CITY']\ncity.to_frame().head()\ncity.iloc[3]\ncity.iloc[[10,20,30]]\n\ncity.iloc[4:50:10]\ncity.loc['Heritage Christian University']\nnp.random.seed(1)\nlabels = list(np.random.choice(city.index, 4))\nlabels\ncity.loc[labels]\ncity.loc['Alabama State University':'Reid State Technical College':10]\ncity['Alabama State University':'Reid State Technical College':10]\n\"\"\"\n## There's more...\n\"\"\"\ncity.iloc[[3]]\ncity.loc['Reid State Technical College':'Alabama State University':10]\ncity.loc['Reid State Technical College':'Alabama State University':-10]\n\"\"\"\n# Selecting DataFrame rows\n\"\"\"\ncollege = pd.read_csv('..\/input\/pandas-cookbook-data\/data\/college.csv', index_col='INSTNM')\ncollege.head()\npd.options.display.max_rows = 6\ncollege.iloc[60].to_frame().T\ncollege.loc['University of Alaska Anchorage']\ncollege.iloc[[60, 99, 3]]\nlabels = ['University of Alaska Anchorage',\n          'International Academy of Hair Design',\n          'University of Alabama in Huntsville']\ncollege.loc[labels]\ncollege.iloc[99:102]\nstart = 'International Academy of Hair Design'\nstop = 'Mesa Community College'\ncollege.loc[start:stop]\n\"\"\"\n# There's more...\n\"\"\"\ncollege.iloc[[60, 99, 3]].index.tolist()\n\"\"\"\n# Selecting DataFrame rows and columns simultaneously\n\"\"\"\ncollege = pd.read_csv('..\/input\/pandas-cookbook-data\/data\/college.csv', index_col='INSTNM')\ncollege.iloc[:3, :4]\ncollege.loc[:'Amridge University', :'MENONLY']\ncollege.iloc[:, [4,6]].head()\ncollege.loc[:, ['WOMENONLY', 'SATVRMID']]\ncollege.iloc[[100, 200], [7, 15]]\nrows = ['GateWay Community College', 'American Baptist Seminary of the West']\ncolumns = ['SATMTMID', 'UGDS_NHPI']\ncollege.loc[rows, columns]\ncollege.iloc[5, -4]\ncollege.loc['The University of Alabama', 'PCTFLOAN']\ncollege.iloc[90:80:-2, 5]\nstart = 'Empire Beauty School-Flagstaff'\nstop = 'Arizona State University-Tempe'\ncollege.loc[start:stop:-2, 'RELAFFIL']\n\"\"\"\n# Selecting data with both integers and labels\n\"\"\"\ncollege = pd.read_csv('..\/input\/pandas-cookbook-data\/data\/college.csv', index_col='INSTNM')\ncol_start = college.columns.get_loc('UGDS_WHITE')\ncol_end = college.columns.get_loc('UGDS_UNKN') + 1\ncol_start, col_end\ncollege.iloc[:5, col_start:col_end]\n\"\"\"\n# There's more...\n\"\"\"\nrow_start = college.index[10]\nrow_end = college.index[15]\ncollege.loc[row_start:row_end, 'UGDS_WHITE':'UGDS_UNKN']\n\"\"\"\n# Speeding up scalar selection\n\"\"\"\ncollege = pd.read_csv('..\/input\/pandas-cookbook-data\/data\/college.csv', index_col='INSTNM')\ncn = 'Texas A & M University-College Station'\ncollege.loc[cn, 'UGDS_WHITE']\ncollege.at[cn, 'UGDS_WHITE']\n%timeit college.loc[cn, 'UGDS_WHITE']\n%timeit college.at[cn, 'UGDS_WHITE']\nrow_num = college.index.get_loc(cn)\ncol_num = college.columns.get_loc('UGDS_WHITE')\nrow_num, col_num\n%timeit college.iloc[row_num, col_num]\n%timeit college.iat[row_num, col_num]\n%timeit college.iloc[5, col_num]\n%timeit college.iat[5, col_num]\n\"\"\"\n## There's more...\n\"\"\"\nstate = college['STABBR']\nstate.iat[1000]\nstate.at['Stanford University']\n\"\"\"\n# Slicing rows lazily\n\"\"\"\n\ncollege[10:20:2]\ncity[10:20:2]\ncollege.index[4001]\nstart = 'Mesa Community College'\nstop = 'Spokane Community College'\ncollege[start:stop:1500]\ncity[start:stop:1500]\n\"\"\"\n## There's more...\n\"\"\"\ncollege[:10, ['CITY', 'STABBR']]\nfirst_ten_instnm = college.index[:10]\ncollege.loc[first_ten_instnm, ['CITY', 'STABBR']]\n\"\"\"\n# Slicing Lexicographically\n\"\"\"\n\ncollege.loc['Sp':'Su']\ncollege = college.sort_index()\ncollege.head()\npd.options.display.max_rows = 6\ncollege.loc['Sp':'Su']\ncollege = college.sort_index(ascending=False)\ncollege.index.is_monotonic_decreasing\ncollege.loc['E':'B']\ncollege.loc['E':'B']","meta":"{'source': 'AI4Code', 'id': '05715b9d652a55'}"}
{"id":"79810","text":"\"\"\"\n## Heatmap Visualization of votes among all parties in all constituency for all election years\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport os\nprint(os.listdir(\"..\/input\/election-data-wrangling\"))\n\"\"\"\n### Using Zeeshan's combined data file after data wranggling\n### Adding a new field called Seat which is a combination of Constituency, Year and Seat. This will be used for Indexing and Visualization\n\"\"\"\n## 2002 Elections ## \nNA_All = pd.read_csv(\"..\/input\/election-data-wrangling\/NA2002-18.csv\", encoding = \"ISO-8859-1\")\nNA_Less = pd.DataFrame([])\nNA_Less['Seat'] = NA_All['ConstituencyTitle'] + '-' + NA_All['Year'].astype(str) + '-' + NA_All['Seat']\nNA_Less['Party'] = NA_All['Party']\nNA_Less['Votes'] = NA_All['Votes']\nNA_Less['Year'] = NA_All['Year']\nCombinedDF = NA_Less\nCombinedDF.shape\nCombinedDF = CombinedDF.sort_values(by=['Seat','Year'])\nCombinedDF.shape\n\"\"\"\n### I had to come up with some logic in order to consider all 'Independent' candidates as one entry per Constituency. \n### Therefore I sum up votes of all Independent candidates and call it Independent party per Contituency\n\"\"\"\nCombinedDF2 = CombinedDF.groupby(['Seat', 'Party'])['Votes'].sum().reset_index()\n#CombinedDF2\nlen(CombinedDF2['Seat'].unique())\n\"\"\"\n### Adding Indexing for faster search and lookup\n\"\"\"\n#CombinedDF2.reset_index()\nCombinedDF3 = CombinedDF2.set_index(['Seat','Party'])\nprint(CombinedDF3.index.names)\n\"\"\"\n### creating list of unique seat names and party names for heatmap entry and visualization\n\"\"\"\nseat_names=CombinedDF3.index.levels[0]\nparty_names=CombinedDF3.index.levels[1]\n\"\"\"\n### Creating an empty matrix for storing heatmap data\n\"\"\"\n#matrix = pd.DataFrame(index=seat_names,columns=party_names)\n#matrix.shape\n#matrix.iloc[0,0]=50\n#matrix\nmatrix = np.zeros((len(seat_names),len(party_names)))\n#CombinedDF3.loc[('NA-1-2002-PESHAWAR-I','Muttahidda Majlis-e-Amal Pakistan')].item()\n\"\"\"\n### inserting values of votes in each constitueny for each party - takes couple of minutes to finish\n\"\"\"\nfor s in range(0,len(seat_names)):\n    for p in range (0,len(party_names)):\n        try:\n            matrix[s,p] = CombinedDF3.loc[(seat_names[s], party_names[p])].item()\n            #matrix.iloc[s,p] = CombinedDF3.loc[(seat_names[s], party_names[p])].item()\n        except KeyError:\n            continue\n        #without loopup - very slow\n        #matrix[s,p] = CombinedDF2.loc[(CombinedDF2['Seat'] == seat_names[s]) & (CombinedDF2['Party'] == party_names[p]), ['Votes']]\n\"\"\"\n### Below is the heatmap of total votes in each constituency for each party. Yellow bright color represents large number of votes where as dark green shows small number of votes\n\n### It would be nice if we can export this heatmap as image or pdf to make it a poster. I did not spend much time on it but there should be some way to do it. Happy Coding !\n\"\"\"\nmatrix2 = pd.DataFrame(matrix, index=seat_names, columns=party_names)\n#matrix2 = matrix\n#matrix2 = matrix2.fillna(0)\n#matrix2 = matrix2.astype(int)\nmatrix2.style.background_gradient(cmap='summer',axis=1)","meta":"{'source': 'AI4Code', 'id': '9289f8efa83324'}"}
{"id":"121946","text":"# \u041f\u043e\u0434\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u044b\u0435 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nrussia_reg = pd.read_csv('\/kaggle\/input\/russia-regions-in-sber-covid-competition\/russia_regions.csv')\n\"\"\"\n# \u0427\u0430\u0441\u0442\u044c 1. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432. \u0414\u0438\u043d\u0430\u043c\u0438\u043a\u0430 \u0440\u0430\u0437\u0432\u0438\u0442\u0438\u044f (\u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u044c) COVID-19 \u0432 \u0442\u0440\u0451\u0445 \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u0445 \u0420\u043e\u0441\u0441\u0438\u0438.\n\"\"\"\n# \u041e\u0442\u0434\u0435\u043b\u044c\u043d\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043e \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u041c\u043e\u0441\u043a\u0432\u0435 \u0438 \u041c\u043e\u0441\u043a\u043e\u0432\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438, \u041f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433\u0435 \u0438 \u041b\u0435\u043d\u0438\u043d\u0433\u0440\u0430\u0434\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438, \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438\n\nrussia_cases = pd.read_csv('\/kaggle\/input\/covid19-russia-regions-cases\/covid19-russia-cases-scrf.csv')\nmoscow_cases = russia_cases.loc[(russia_cases['Region\/City'] == '\u041c\u043e\u0441\u043a\u0432\u0430') | (russia_cases['Region\/City'] == '\u041c\u043e\u0441\u043a\u043e\u0432\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c')]\nspb_cases = russia_cases.loc[(russia_cases['Region\/City'] == '\u0421\u0430\u043d\u043a\u0442-\u041f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433') | (russia_cases['Region\/City'] == '\u041b\u0435\u043d\u0438\u043d\u0433\u0440\u0430\u0434\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c')]\nnsk_cases = russia_cases.loc[russia_cases['Region\/City'] == '\u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c']\n# \u0413\u0440\u0443\u043f\u043f\u0438\u0440\u0443\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043f\u043e \u0434\u0430\u0442\u0435\n\nmoscow_cases = moscow_cases.groupby('Date').sum()\nspb_cases = spb_cases.groupby('Date').sum()\nnsk_cases = nsk_cases.groupby('Date').sum()\nmoscow_cases\nspb_cases\nnsk_cases\n# \u0423\u0434\u0430\u043b\u044f\u0435\u043c \u043b\u0438\u0448\u043d\u0438\u0435 \u0441\u0442\u043e\u043b\u0431\u0446\u044b\n\nmoscow_cases.drop(['Region_ID', 'Day-Confirmed', 'Day-Deaths', 'Day-Recovered', 'Deaths', 'Recovered'], axis=1, inplace=True)\nspb_cases.drop(['Region_ID', 'Day-Confirmed', 'Day-Deaths', 'Day-Recovered', 'Deaths', 'Recovered'], axis=1, inplace=True)\nnsk_cases.drop(['Region_ID', 'Day-Confirmed', 'Day-Deaths', 'Day-Recovered', 'Deaths', 'Recovered'], axis=1, inplace=True)\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u0445 (\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(moscow_cases['Confirmed'], 'ro-', label = 'Moscow')\nplt.plot(spb_cases['Confirmed'], 'go-', label = 'Saint-Petersburg')\nplt.plot(nsk_cases['Confirmed'], 'bo-', label = 'Novosibirsk')\nplt.ylabel('Confirmed')\nplt.xlabel('Date')\nplt.grid()\nplt.legend()\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u0445 (\u041b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043e\u0442 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(np.log(moscow_cases['Confirmed']+1), 'ro-', label = 'Moscow')\nplt.plot(np.log(spb_cases['Confirmed']+1), 'go-', label = 'Saint-Petersburg')\nplt.plot(np.log(nsk_cases['Confirmed']+1), 'bo-', label = 'Novosibirsk')\nplt.grid()\nplt.ylabel('Log(confirmed)')\nplt.xlabel('Date')\nplt.legend()\n\"\"\"\n\u0410\u043d\u0430\u043b\u0438\u0437 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432: \u0438\u0441\u0445\u043e\u0434\u044f \u0438\u0437 \u0434\u0430\u043d\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432, \u0438\u0437 \u0442\u0440\u0435\u0445 \u0440\u0435\u0433\u0438\u043e\u043d\u043e\u0432 \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u0430\u044f \u043e\u0431\u043b\u0430\u0441\u0442\u044c \u0438\u043c\u0435\u0435\u0442 \u043d\u0430\u0438\u043c\u0435\u043d\u044c\u0448\u0438\u0435 \u0442\u0435\u043c\u043f\u044b \u0440\u043e\u0441\u0442\u0430 \u0447\u0438\u0441\u043b\u0430 \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u043d\u0438\u044f COVID-19 \n\"\"\"\n\"\"\"\n# \u0427\u0430\u0441\u0442\u044c 2. \u041f\u0440\u043e\u0433\u043d\u043e\u0437 \u0440\u0430\u0437\u0432\u0438\u0442\u0438\u044f COVID-19 \u0432 \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u043d\u0430 \u0438\u044e\u043d\u044c.\n\"\"\"\n\"\"\"\n\u0421\u0440\u0430\u0432\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0439 \u0430\u043d\u0430\u043b\u0438\u0437\n\"\"\"\nrussia_regions = pd.read_csv('\/kaggle\/input\/russia-regions-in-sber-covid-competition\/russia_regions.csv')\n\nimport fetch\ndata = fetch.fetch_yandex(dump_folder='')\ndata, filepath = fetch.format_csse2(data, dump_folder='')\nrussia = pd.read_csv('https:\/\/raw.githubusercontent.com\/grwlf\/COVID-19_plus_Russia\/master\/csse_covid_19_data\/csse_covid_19_time_series\/time_series_covid19_confirmed_RU.csv')\nrussia_latest = pd.read_csv(filepath)\nrussia_latest\nrus = russia.set_index('Province_State').join(russia_latest.set_index('Province_State')['Confirmed'])\nrus\ntoday = filepath[:10]\ntoday2 = today[3:5]+'\/'+today[:2]+'\/'+today[-2:]\nrus.drop(['UID','iso2','iso3','FIPS','Admin2','Country_Region','Lat','Long_','Combined_Key','code3'], axis=1, inplace=True)\nrus[today2] = rus['Confirmed']\ndel rus['Confirmed']\n\ndel rus['06\/09\/20'] # \u0423\u0434\u0430\u043b\u044f\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u0437\u0430 \u0438\u044e\u043d\u044c(\u043f\u043e\u0437\u0436\u0435 \u0434\u043e\u0431\u0430\u0432\u0438\u043c \u0432 \u043d\u0443\u0436\u043d\u043e\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435)\ndf = rus.T.iloc[-30:,:]\ndf\ndf.plot(figsize=(15,10), legend=None)\n\nplt.show()\n\"\"\"\n\u0418\u0437 \u0433\u0440\u0430\u0444\u0438\u043a\u0430 \u0441\u043b\u0435\u0434\u0443\u0435\u0442, \u0447\u0442\u043e \u0447\u0438\u0441\u043b\u043e \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0448\u0438\u0445 COVID-19 \u0432 \u041c\u043e\u0441\u043a\u0432\u0435 \u0433\u043e\u0440\u0430\u0437\u0434\u043e \u0432\u044b\u0448\u0435, \u0447\u0435\u043c \u0432 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0445 \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u0445 => \u043f\u0440\u043e\u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u0438\u0440\u0443\u0435\u043c\n\"\"\"\n(np.log(rus + 0.5).T).plot(figsize=(15,10), legend=None)\n\nplt.show()\n\ny = np.log(rus + 0.5).T\ny_m = y[y>5]\ny_m\ny_m.count().max()\nlist_columns = []\nfor column in y_m.columns:\n    list_columns.append(y_m[column].count())\n    \nfilled = pd.Series(list_columns).max()\ny_gt_148 = pd.DataFrame(data = [[0 for i in range(len(y_m.columns))] for j in range(filled)], index = range(filled), columns = y_m.columns)\ny_gt_148\nfor i in range(len(y_m.columns)):\n    temp = y_m.iloc[:,i].dropna().reset_index(drop=True)\n    y_gt_148.iloc[:temp.shape[0],i] = temp\ny_gt_148 = y_gt_148.replace(0,np.nan)\ny_gt_148\ny_gt_148.plot(figsize=(15,10), legend=None)\n\nplt.show()\n\"\"\"\n\u041d\u0430\u043f\u043e\u043b\u043d\u0438\u043b\u0438 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c \u0441 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f, \u0433\u0434\u0435 148+ \u043a\u0435\u0439\u0441\u043e\u0432 \u0432 \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0448\u043a\u0430\u043b\u0435\n\"\"\"\ny_gt_148.iloc[0,:].max()\ndelta = y_gt_148.iloc[0,:].max() - y_gt_148.iloc[0,:]\nall_in_one = y_gt_148 + delta\nall_in_one.head()\nall_in_one.plot(figsize=(15,10), legend=None)\n\nplt.show()\n# \u0410\u0432\u0442\u043e\u043d\u043e\u043c\u043d\u044b\u0435 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u043d\u0435 \u043d\u0430\u0437\u0432\u0430\u043d\u044b, \u043f\u043e\u043c\u043e\u0436\u0435\u043c \u043d\u0430\u0437\u0432\u0430\u0442\u044c\n\nrussia_regions.loc[russia_regions['iso_code'] == 'RU-NEN', 'csse_province_state'] = 'Nenetskiy autonomous oblast'\nrussia_regions.loc[russia_regions['iso_code'] == 'RU-CHU', 'csse_province_state'] = 'Chukotskiy autonomous oblast'\nrus['ind'] = rus.index\n# Altay republic > Republic of Altay\nrus.loc[rus.index == 'Altay republic', 'ind'] = 'Republic of Altay'\nrus.set_index('ind', inplace=True)\nsorted_obl = russia_regions.sort_values(['population']).reset_index()\n\nnsk_index = sorted_obl[sorted_obl['name']=='\u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u0430\u044f'].index[0]\n\nsorted_obl[nsk_index-3:nsk_index+4]\nselected_regions = list(sorted_obl[nsk_index-3:nsk_index+4]['csse_province_state'])\nshow_regions = selected_regions + ['Moscow']\nall_in_one[show_regions]\nall_in_one[show_regions].plot(figsize=(15,10))\nplt.show()\n(np.log(rus.loc[show_regions] + 0.5).T[-30:]).plot(figsize=(15,10))\nplt.show()\n\"\"\"\n\u0412 \u0434\u0432\u0443\u0445 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0445 \u0432\u044b\u0448\u0435 \u0433\u0440\u0430\u0444\u0438\u043a\u0430\u0445 \u043f\u043e\u043a\u0430\u0437\u0430\u043d\u0430 \u0434\u0438\u043d\u0430\u043c\u0438\u043a\u0430 \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u0438 6 \u0441\u0445\u043e\u0436\u0438\u0445 \u043f\u043e \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0441\u0442\u0438 \u043d\u0430\u0441\u0435\u043b\u0435\u043d\u0438\u044f \u0440\u0435\u0433\u0438\u043e\u043d\u0430\u0445\n\"\"\"\nlast_30_days = np.log(rus.loc[show_regions] + 0.5).T[-30:]\nlast_30_days.head()\nlast_30_days = last_30_days - last_30_days.loc['05\/02\/20']\nlast_30_days.head()\nlast_30_days.plot(figsize=(15,10))\n\nplt.show()\nlast_100_days = np.log(rus.loc[show_regions] + 0.5).T[-100:]\nlast_100_days.plot(figsize=(15,10))\nplt.show()\nd100 = last_100_days[last_100_days > 5]\n\nfilled2 = d100.count().max()\nd100_eq = pd.DataFrame(data = [[0 for i in range(len(d100.columns))] for j in range(filled2)], \\\n                        index = range(filled2), columns = d100.columns)\n\n# \u041d\u0430\u043f\u043e\u043b\u043d\u0438\u043c \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c \u0441 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f, \u0433\u0434\u0435 148+ \u043a\u0435\u0439\u0441\u043e\u0432 \u0432 \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0448\u043a\u0430\u043b\u0435\n\nfor i in range(len(d100.columns)):\n    temp = d100.iloc[:,i].dropna().reset_index(drop=True)\n    d100_eq.iloc[:temp.shape[0],i] = temp\n    \nd100_eq = d100_eq.replace(0,np.nan)\nprint(d100_eq.iloc[0,:].max())\ndelta = d100_eq.iloc[0,:].max() - d100_eq.iloc[0,:]\nd100_eq = d100_eq + delta\n\nprint(d100_eq.head())\n\nd100_eq.plot()\nplt.show()\nd100.plot()\nplt.show()\nd100\n\"\"\"\n# \u041f\u0435\u0440\u0432\u044b\u0439 \u0441\u043f\u043e\u0441\u043e\u0431 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f\n\"\"\"\nd100['Novosibirsk oblast'].dropna().plot(figsize=(15,10))\nplt.show()\nnsk = rus.loc['Novosibirsk oblast']\nnsk\nnsk['06\/01\/20'] = 2914\nnsk['06\/02\/20'] = 3020\nnsk['06\/03\/20'] = 3122\nnsk['06\/04\/20'] = 3226\nnsk['06\/05\/20'] = 3334\nnsk['06\/06\/20'] = 3441\nnsk['06\/07\/20'] = 3546\nnsk['06\/08\/20'] = 3648\nnsk['06\/09\/20'] = 3752\n\"\"\"\n\u0414\u043e\u0431\u0430\u0432\u0438\u043b\u0438 \u043d\u0435\u0434\u043e\u0441\u0442\u0430\u044e\u0449\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043d\u0430 \u0442\u0435\u043a\u0443\u0449\u0443\u044e \u0434\u0430\u0442\u0443\n\"\"\"\nnsk.tail()\nnsk[nsk>150].plot(figsize=(15,10))\ndelta_nsk = nsk - nsk.shift() # \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n\ndelta_nsk = delta_nsk[delta_nsk>0]\ndelta_nsk.plot(figsize=(15,10))\nplt.show()\nlog_nsk = np.log(nsk)\nlog_nsk = log_nsk[log_nsk>5]\nlog_nsk.plot(figsize=(15,10))\nplt.show()\nlog_nsk.shape # \u0440\u0430\u0437\u043c\u0435\u0440\n# \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u044b \u044f\u0447\u0435\u0439\u043a\u0438 \u0434\u043b\u044f \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f (\u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 1, \u0442.\u043a. \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043e\u0442 0 \u043d\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442)\nlog_nsk['06\/10\/20'] = 1\nlog_nsk['06\/11\/20'] = 1\nlog_nsk['06\/12\/20'] = 1\nlog_nsk['06\/13\/20'] = 1\nlog_nsk['06\/14\/20'] = 1\nlog_nsk['06\/15\/20'] = 1\nlog_nsk['06\/16\/20'] = 1\nlog_nsk['06\/17\/20'] = 1\nlog_nsk['06\/18\/20'] = 1\nlog_nsk['06\/19\/20'] = 1\nlog_nsk['06\/20\/20'] = 1\nlog_nsk['06\/21\/20'] = 1\nlog_nsk['06\/22\/20'] = 1\nlog_nsk['06\/23\/20'] = 1\nlog_nsk['06\/24\/20'] = 1\nlog_nsk['06\/25\/20'] = 1\nlog_nsk['06\/26\/20'] = 1\nlog_nsk['06\/27\/20'] = 1\nlog_nsk['06\/28\/20'] = 1\nlog_nsk['06\/29\/20'] = 1\nlog_nsk['06\/30\/20'] = 1\nlog_nsk.shape\ndf_nsk = pd.DataFrame(data = {'date' : pd.to_datetime(log_nsk.index), 'Nsk' : log_nsk.values, 'X' : range(1,71)})\n# \u041c\u043e\u0434\u0435\u043b\u044c y = x^a \u0438\u043b\u0438 ln y = a * ln x, \u043e\u0431\u0443\u0447\u0430\u0435\u043c \u043d\u0430 45 \u043d\u0430\u0431\u043b\u044e\u0434\u0435\u043d\u0438\u044f\u0445, \u0434\u0435\u043b\u0430\u0435\u043c \u043f\u0440\u043e\u0433\u043d\u043e\u0437 \u0434\u043e \u043a\u043e\u043d\u0446\u0430 \u0438\u044e\u043d\u044f (21 \u0434\u0435\u043d\u044c)\n\nX_train = np.log(df_nsk.loc[0:44,'X']).values.reshape(-1,1) \ny_train = np.log(df_nsk.loc[0:44,'Nsk']).values.reshape(-1,1)\nX_test = np.log(df_nsk.loc[45:69,'X']).values.reshape(-1,1) \nX_train = np.log(df_nsk.loc[0 : 44,'X']).values.reshape(-1,1) \ny_train = np.log(df_nsk.loc[0 : 44,'Nsk']).values.reshape(-1,1)\nX_test = np.log(df_nsk.loc[45 : 69, 'X']).values.reshape(-1,1) \n\n    # \u0421\u043a\u0430\u043b\u0438\u0440\u0443\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438, \u0434\u043b\u044f \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u0438 \u0441 \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u0438\u0437\u0430\u0446\u0438\u0435\u0439 \u0445\u043e\u0440\u043e\u0448\u043e\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\n\n    # print(scaler.mean_, scaler.var_)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n    # \u0421\u0442\u0440\u043e\u0438\u043c \u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u044e\nfrom sklearn.linear_model import LinearRegression\nreg = LinearRegression().fit(X_train_scaled, y_train)\n\n    # \u0424\u0443\u043d\u043a\u0446\u0438\u0438 \u0434\u043b\u044f 2 \u043c\u0435\u0442\u0440\u0438\u043a: \u043f\u0435\u0440\u0432\u0430\u044f - \u043a\u043e\u043d\u043a\u0443\u0440\u0441\u043d\u0430\u044f, \u0432\u0442\u043e\u0440\u0430\u044f - \u043f\u0440\u043e\u0446\u0435\u043d\u0442 \u043e\u0442\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u044f \u043e\u0442 \u0438\u0441\u0442\u0438\u043d\u044b\ndef MALE(pred, true):\n    return np.mean(np.abs(np.log10((pred + 1) \/ (true + 1))))\n\ndef AvgProc(pred, true):\n    return np.mean(np.abs((pred-true)\/true))\n\n    # \u041f\u0440\u0438\u0432\u043e\u0434\u0438\u043c \u0443 \u043a \u043a\u043e\u043b-\u0432\u0443 \u0441\u043b\u0443\u0447\u0430\u0435\u0432\ny_pred_test_exp = np.round(np.exp(np.exp(reg.predict(X_test_scaled))),0)\ny_pred_train_exp = np.round(np.exp(np.exp(reg.predict(X_train_scaled))),0)\ny_train_exp = np.round(np.exp(np.exp(y_train)),0)\n\nplt.figure(figsize=(15,10))\n\nplt.plot(df_nsk.loc[45 : 69,'date'], y_pred_test_exp) \nplt.plot(df_nsk.loc[0 : 44,'date'], y_pred_train_exp)\nplt.plot(df_nsk.loc[0 : 44,'date'], y_train_exp)\n\nplt.legend()\nplt.legend()\nplt.show()\nplt.grid\n\"\"\"\n\u041f\u0440\u043e\u0433\u043d\u043e\u0437 \u043f\u043e\u043a\u0430\u0437\u0430\u043b, \u0447\u0442\u043e \u043d\u0430 1 \u0438\u044e\u043b\u044f \u0432 \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0441\u0442\u044c \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 \u0437\u0430\u0440\u0430\u0436\u0435\u043d\u0438\u044f COVID-19 \u0441\u043e\u0441\u0442\u0430\u0432\u0438\u0442 \u043f\u043e\u0440\u044f\u0434\u043a\u0430 5000 \u0441\u043b\u0443\u0447\u0430\u0435\u0432. \u041d\u043e, \u043a\u0430\u043a \u043c\u044b \u0432\u0438\u0434\u0438\u043c \u0438\u0437 \u0433\u0440\u0430\u0444\u0438\u043a\u0430, \u0441\u043e \u0432\u0440\u0435\u043c\u0435\u043d\u0435\u043c \u0440\u0430\u0437\u043b\u0438\u0447\u0438\u044f \u043c\u0435\u0436\u0434\u0443 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0438 \u043e\u0431\u0443\u0447\u0430\u0435\u043c\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u043e\u0439 \u0440\u0430\u0441\u0442\u0443\u0442 => \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0435.\n\"\"\"\n\"\"\"\n# \u0412\u0442\u043e\u0440\u043e\u0439 \u0441\u043f\u043e\u0441\u043e\u0431 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f\n\"\"\"\n\"\"\"\n\u041f\u0440\u043e\u0433\u043d\u043e\u0437 \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d \u043f\u043e \u0430\u0432\u0442\u043e\u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u043e\u043d\u043d\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 AR(10). \u0411\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0433\u043e\u0442\u043e\u0432\u044b\u0435 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438. \n\"\"\"\n\"\"\"\n\u0422\u0435\u0441\u0442\u043e\u0432\u043e\u0435 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u0435 \u043d\u0430 10 \u0434\u043d\u0435\u0439\n\"\"\"\nfrom matplotlib import pyplot\nfrom statsmodels.tsa.ar_model import AutoReg\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nX = log_nsk.values\ntrain, test = X[1:len(X)-31], X[len(X)-31:len(X)-21] # \u041e\u0431\u0443\u0447\u0430\u0435\u043c \u043d\u0430 30 \u0434\u043d\u044f\u0445, \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u0443\u0435\u043c - 10, \u0434\u043b\u044f \u0441\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u044f \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u0441 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u043e\u043c\n\nmodel = AutoReg(train, lags=10) # lag = 10, \u0438\u0441\u0445\u043e\u0434\u044f \u0438\u0437 \u043f\u0435\u0440\u0435\u0431\u043e\u0440\u0430 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439, \u0434\u043b\u044f \u043d\u0430\u0438\u0431\u043e\u043b\u044c\u0448\u0435\u0439 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 (RMSE \u043f\u0440\u0438 lag = 10 - \u043d\u0430\u0438\u043c\u0435\u043d\u044c\u0448\u0430\u044f)\nmodel_fit = model.fit()\nprint('Coefficients: %s' % model_fit.params)\n\npredictions = model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)\nfor i in range(len(predictions)):\n    print('predicted=%f, expected=%f' % (predictions[i], test[i]))\nrmse = sqrt(mean_squared_error(test, predictions))\nprint('Test RMSE: %.3f' % rmse) # RMSE - \u0441\u0440\u0435\u0434\u043d\u0435\u043a\u0432\u0430\u0434\u0440\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0430\u044f \u043e\u0448\u0438\u0431\u043a\u0430 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0430\n\npyplot.plot(test)\npyplot.plot(predictions, color='red')\npyplot.show()\n\"\"\"\n\u0418\u0442\u043e\u0433\u043e\u0432\u043e\u0435 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0441 10 \u043f\u043e 30 \u0438\u044e\u043d\u044f (\u0432\u043a\u043b\u044e\u0447\u0438\u0442\u0435\u043b\u044c\u043d\u043e)\n\"\"\"\nX = log_nsk.values\ntrain, test = X[1:len(X)-21], X[len(X)-21:] # \u041e\u0431\u0443\u0447\u0430\u0435\u043c \u043d\u0430 39 \u0434\u043d\u044f\u0445, \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u0443\u0435\u043c - 21\n\nmodel = AutoReg(train, lags=10)\nmodel_fit = model.fit()\nprint('Coefficients: %s' % model_fit.params)\n\npredictions = model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)\nfor i in range(len(predictions)):\n    print('predicted=%f' % (predictions[i]))\n\npyplot.plot(predictions, color='red')\npyplot.show()\n\"\"\"\n*\u041f\u043e \u0434\u0430\u043d\u043d\u044b\u043c \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0430, \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u043e\u0433\u043e \u043f\u043e \u0430\u0432\u0442\u043e\u0440\u0435\u0433\u0440\u0435\u0441\u0441\u0438\u043e\u043d\u043d\u043e\u0439 \u043c\u043e\u0434\u0435\u043b\u0438 AR(10) \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0441\u0442\u044c \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 COVID-19 \u0432 \u041d\u043e\u0432\u043e\u0441\u0438\u0431\u0438\u0440\u0441\u043a\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u043d\u0430 1 \u0438\u044e\u043b\u044f 2020\u0433 \u0441\u043e\u0441\u0442\u0430\u0432\u0438\u0442 \u043f\u043e\u0440\u044f\u0434\u043a\u0430 6000, (\u043e\u0441\u044c y - \u043b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043e\u0442 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0441\u043b\u0443\u0447\u0430\u0435\u0432, x - \u043d\u043e\u043c\u0435\u0440 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u0443\u0435\u043c\u043e\u0433\u043e \u0434\u043d\u044f (10 - 30 \u0438\u044e\u043d\u044f)). \u041f\u0440\u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0438 \u0432\u044b\u0431\u043e\u0440\u043a\u0438, RMSE \u043e\u043a\u0430\u0437\u0430\u043b\u0430\u0441\u044c \u0434\u043e\u0441\u0442\u0430\u0442\u043e\u0447\u043d\u043e \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u043e\u0439, \u043f\u0440\u0438\u0447\u0435\u043c \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u0438\u0440\u0443\u0435\u043c\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043e\u043a\u0430\u0437\u0430\u043b\u0438\u0441\u044c \u0432\u044b\u0448\u0435 \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0445 => \u0438\u0437 \u0434\u0432\u0443\u0445 \u043f\u0440\u043e\u0433\u043d\u043e\u0437\u043e\u0432 \u0434\u0430\u043d\u043d\u044b\u0439 \u043e\u0442\u043b\u0438\u0447\u0430\u0435\u0442\u0441\u044f \u0431\u043e\u043b\u044c\u0448\u0435\u0439 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c\u044e. \u0421 \u0442\u043e\u0447\u043a\u0438 \u0437\u0440\u0435\u043d\u0438\u044f \u043f\u043e\u0434\u0445\u043e\u0434\u0430 \u0434\u0430\u043d\u043d\u044b\u0439 \u043f\u0440\u043e\u0433\u043d\u043e\u0437 \u0431\u043e\u043b\u0435\u0435 \u043a\u043e\u043d\u0441\u0435\u0440\u0432\u0430\u0442\u0438\u0432\u043d\u044b\u0439.  *\n\"\"\"\n\"\"\"\n# \u0427\u0430\u0441\u0442\u044c 3. \u041f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0433\u0440\u0430\u0444\u0438\u043a\u043e\u0432. \u0414\u0438\u043d\u0430\u043c\u0438\u043a\u0430 \u0440\u0430\u0437\u0432\u0438\u0442\u0438\u044f (\u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u044c, \u0441\u043c\u0435\u0440\u0442\u043d\u043e\u0441\u0442\u044c) COVID-19 \u0432 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u0438\u0445 \u0441\u0442\u0440\u0430\u043d\u0430\u0445 \u043c\u0438\u0440\u0430.\n\"\"\"\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0438 \u0440\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u0443\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043e \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u043c\u0438\u0440\u0435\n\nworld_cases = pd.read_csv('\/kaggle\/input\/updatedjohn\/csse_covid_19_data\/csse_covid_19_time_series\/time_series_covid19_confirmed_global.csv')\nworld_cases = world_cases.groupby('Country\/Region').sum()\nworld_cases.drop(['Lat', 'Long'], axis=1, inplace=True)\nworld_cases = world_cases.T\nworld_cases\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u0420\u043e\u0441\u0441\u0438\u0438, \u0413\u0435\u0440\u043c\u0430\u043d\u0438\u0438, \u0421\u0428\u0410, \u0418\u0442\u0430\u043b\u0438\u0438, \u041a\u0438\u0442\u0430\u0435 (\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(world_cases['Russia'], 'r.-', label = 'Russia')\nplt.plot(world_cases['Germany'], 'g.-', label = 'Germany')\nplt.plot(world_cases['US'], 'b.-', label = 'US')\nplt.plot(world_cases['Italy'], 'y.-', label = 'Italy')\nplt.plot(world_cases['China'], 'c.-', label = 'China')\nplt.ylabel('Confirmed')\nplt.xlabel('Date')\nplt.grid()\nplt.legend()\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0437\u0430\u0431\u043e\u043b\u0435\u0432\u0430\u0435\u043c\u043e\u0441\u0442\u0438 \u0432 \u0420\u043e\u0441\u0441\u0438\u0438, \u0413\u0435\u0440\u043c\u0430\u043d\u0438\u0438, \u0421\u0428\u0410, \u0418\u0442\u0430\u043b\u0438\u0438, \u041a\u0438\u0442\u0430\u0435 (\u041b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043e\u0442 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u0435\u0432 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(np.log(world_cases['Russia']+1), 'r.-', label = 'Russia')\nplt.plot(np.log(world_cases['Germany']+1), 'g.-', label = 'Germany')\nplt.plot(np.log(world_cases['US']+1), 'b.-', label = 'US')\nplt.plot(np.log(world_cases['Italy']+1), 'y.-', label = 'Italy')\nplt.plot(np.log(world_cases['China']+1), 'c.-', label = 'China')\nplt.ylabel('Log(confirmed)')\nplt.xlabel('Date')\nplt.grid()\nplt.legend()\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0438 \u0440\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u0443\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043e \u0441\u043c\u0435\u0440\u0442\u043d\u043e\u0441\u0442\u0438 \u0432 \u043c\u0438\u0440\u0435\n\nworld_deaths = pd.read_csv('\/kaggle\/input\/updatedjohn\/csse_covid_19_data\/csse_covid_19_time_series\/time_series_covid19_deaths_global.csv')\nworld_deaths = world_deaths.groupby('Country\/Region').sum()\nworld_deaths.drop(['Lat', 'Long'], axis=1, inplace=True)\nworld_deaths = world_deaths.T\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0441\u043c\u0435\u0440\u0442\u043d\u043e\u0441\u0442\u0438 \u0432 \u0420\u043e\u0441\u0441\u0438\u0438, \u0413\u0435\u0440\u043c\u0430\u043d\u0438\u0438, \u0421\u0428\u0410, \u0418\u0442\u0430\u043b\u0438\u0438, \u041a\u0438\u0442\u0430\u0435 (\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043c\u0435\u0440\u0442\u0435\u0439 \u043e\u0442 COVID-19 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(world_deaths['Russia'], 'r.-', label = 'Russia')\nplt.plot(world_deaths['Germany'], 'g.-', label = 'Germany')\nplt.plot(world_deaths['US'], 'b.-', label = 'US')\nplt.plot(world_deaths['Italy'], 'y.-', label = 'Italy')\nplt.plot(world_deaths['China'], 'c.-', label = 'China')\nplt.ylabel('Died')\nplt.xlabel('Date')\nplt.grid()\nplt.legend()\n# \u0413\u0440\u0430\u0444\u0438\u043a \u0441\u043c\u0435\u0440\u0442\u043d\u043e\u0441\u0442\u0438 \u0432 \u0420\u043e\u0441\u0441\u0438\u0438, \u0413\u0435\u0440\u043c\u0430\u043d\u0438\u0438, \u0421\u0428\u0410, \u0418\u0442\u0430\u043b\u0438\u0438, \u041a\u0438\u0442\u0430\u0435 (\u041b\u043e\u0433\u0430\u0440\u0438\u0444\u043c \u043e\u0442 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0441\u043c\u0435\u0440\u0442\u0435\u0439 - \u0414\u0430\u0442\u0430)\n\nfig, ax = plt.subplots(figsize=(15,10))\nplt.plot(np.log(world_deaths['Russia']+1), 'r.-', label = 'Russia')\nplt.plot(np.log(world_deaths['Germany']+1), 'g.-', label = 'Germany')\nplt.plot(np.log(world_deaths['US']+1), 'b.-', label = 'US')\nplt.plot(np.log(world_deaths['Italy']+1), 'y.-', label = 'Italy')\nplt.plot(np.log(world_deaths['China']+1), 'c.-', label = 'China')\nplt.ylabel('Log(died)')\nplt.xlabel('Date')\nplt.grid()\nplt.legend()\n\"\"\"\n# Here is the end of the presentation\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e04564d72ae066'}"}
{"id":"79752","text":"%cd \/kaggle\/working\n!git clone https:\/\/github.com\/ultralytics\/yolov5 # clone\n!cp -r \/kaggle\/input\/yolov5-lib-ds \/kaggle\/working\/yolov5\n%cd yolov5\n%pip install -qr requirements.txt  # install\n\nfrom yolov5 import utils\ndisplay = utils.notebook_init()  # check\n# Install W&B \n!pip install -q --upgrade wandb\n\n# Login \nimport wandb\n\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient() \n\npersonal_key_for_api = user_secrets.get_secret(\"WNB\")\n! wandb login $personal_key_for_api\nimport os\nimport yaml\n\ncwd = '\/kaggle\/working\/'\n\ndata = hyperparams = {'lr0': 0.01,\n 'lrf': 0.1, \n 'momentum': 0.937,  \n 'weight_decay': 0.0005,\n 'warmup_epochs': 5.0, #3.0\n 'warmup_momentum': 0.8, #0.8\n 'warmup_bias_lr': 0.1, #0.1\n 'box': 0.05,\n 'cls': 0.5, #0.5\n 'cls_pw': 1.0,\n 'obj': 1.0,\n 'obj_pw': 1.0,\n 'iou_t': 0.2,\n 'anchor_t': 4.0,\n 'fl_gamma': 0.0,\n 'hsv_h': 0.015,\n 'hsv_s': 0.7,#0.7\n 'hsv_v': 0.3,#0.3\n 'degrees': 0.0,\n 'translate': 0.1,\n 'scale': 0.7, #0.5\n 'shear': 0.0,\n 'perspective': 0.0,\n 'flipud': 0.0,\n 'fliplr': 0.5,\n 'mosaic': 0.5, #1.0 # 0.0 was better\n 'mixup': 0.5, #0.0\n 'copy_paste': 0.0}\n\nwith open(os.path.join( cwd, 'hyper.yaml' ), 'w') as outfile:\n    yaml.dump(data, outfile, default_flow_style=False)\n\ncwd = '\/kaggle\/working\/'\ndata = dict(\n    path  = cwd,\n    train = '..\/input\/cotsyolostratifiedkfold\/COTS-YOLOv5-StratifiedKFold\/images\/train',\n    val   = '..\/input\/cotsyolostratifiedkfold\/COTS-YOLOv5-StratifiedKFold\/images\/val',\n    nc    = 1,\n    names = ['cots'],\n    )\nwith open(os.path.join( cwd , 'custom.yaml'), 'w') as outfile:\n    yaml.dump(data, outfile, default_flow_style=False)\n\nf = open(os.path.join( cwd , 'custom.yaml'), 'r')\nprint('\\nyaml:')\nprint(f.read())\n!python train.py --img 960\\\n--hyp \/kaggle\/working\/hyper.yaml\\\n--batch 8\\\n--epochs 30\\\n--data \/kaggle\/working\/custom.yaml\\\n--weights yolov5l.pt \n\"\"\"\nReference : https:\/\/www.kaggle.com\/awsaf49\/great-barrier-reef-yolov5-train\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '927566c5d60bd9'}"}
{"id":"74492","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\n# Improving Matplotlib Aesthetics to emulate FiveThirtyEight.\n\"\"\"\n\"\"\"\n### Set style as default 538 style\nWe will edit it later.\n\"\"\"\nimport matplotlib.style as style\nstyle.available\n\"\"\"\nNote the style \"fivethirtyeight\" that we will begin with.\n\"\"\"\nstyle.use(\"fivethirtyeight\")\n\"\"\"\n### Import data\n\"\"\"\nworld = pd.read_csv(\"..\/input\/world-happiness-report-2021\/world-happiness-report.csv\")\nworld.head()\n\"\"\"\n### Get top 5 happiest 2021 to compare to the US over time\n\"\"\"\n# get top 5 happiest countries, 2020\ntop5_2020 = world[world[\"year\"]==2020].sort_values(by=\"Life Ladder\", ascending = False).head()[\"Country name\"]\n\n# subset by top 5 happiest and least happy countries, plus the US\nsubset = world[\n    (world[\"Country name\"].isin(top5_2020)) \n    | (world[\"Country name\"]==\"United States\")\n]\nsubset\n\"\"\"\n### Initial plot | Happiness over time\n\"\"\"\nfig, ax = plt.subplots(figsize = (14,8))\n\nfor country, group in subset.groupby(\"Country name\"):\n    group.plot(\n        ax = ax, \n        x = \"year\", \n        y = \"Life Ladder\", \n        label = country\n    )\n\nplt.show()\n\"\"\"\n### Not bad for a first plot. Let's add some things.\n\"\"\"\nfig, ax = plt.subplots(figsize = (14,8))\n\nfor country, group in subset.groupby(\"Country name\"):\n    group.plot(\n        ax = ax, \n        x = \"year\", \n        y = \"Life Ladder\", \n        label = country\n    )\n    \n### add the following: ###\n\n# y-tick label size\nax.tick_params(axis=\"both\", which=\"major\", labelsize=18)\n\n# capitalize x-label\nax.set_xlabel(\"Year\")\n\n# bold x-axis\nplt.axhline(6.5, color=\"black\", linewidth=1.5, alpha=0.6)\n\nplt.show()\n\"\"\"\n### Getting better...\n\"\"\"\nfig, ax = plt.subplots(figsize = (14,8))\n\nfor country, group in subset.groupby(\"Country name\"):\n    group.plot(\n        ax = ax, \n        x = \"year\", \n        y = \"Life Ladder\", \n        label = country\n    )\n    \nax.tick_params(axis=\"both\", which=\"major\", labelsize=18)\nax.set_xlabel(\"Year\")\nplt.axhline(6.5, color=\"black\", linewidth=1.5, alpha=0.6)\n\n### add the following: ###\n\n# add v-line next to y-tick labels\nax.set_xlim(2004.5,2021)\nplt.axvline(2004.75, color=\"black\", linewidth=1.5, alpha=0.5)\n\n# add signature bar\nax.text(\n    x = 2003.7,\n    y = 6.17,\n    s = \"   twitch.tv\/MitchsWorkshop                                                                                        Source: Gallup World Poll   \",\n    fontsize = 17,\n    color = \"#F0F0F0\",\n    backgroundcolor = \"grey\"\n)\n\n# add title\nax.text(\n    x = 2004,\n    y = 8.3,\n    s = \"The World's Top 5 Happiest Countries, and the United States\",\n    fontsize = 21,\n    fontweight = \"bold\",\n    fontfamily = \"poppins\"\n)\n\n# add subtitle\nax.text(\n    x = 2004,\n    y = 8.141,\n    s = \"Note: the y-axis is not base-0. This is purely a demonstration of improved plot aesthetics.\\nAll scores are out of 10.\",\n    fontsize = 18\n)\n\n# custom colors\ncolors = [\n    \"#3c9dbd\",\n    \"#c2762b\",\n    \"#cc274d\",\n    \"#29802c\",\n    \"#565e5e\",\n    \"#623aa6\"\n]\nleg = ax.get_legend()\nfor i,c in enumerate(colors):\n    plt.gca().get_lines()[i].set_color(c)\n\nplt.show()\n\"\"\"\n### Now let's remove the legend\n\"\"\"\nfig, ax = plt.subplots(figsize = (14,8))\n\nfor country, group in subset.groupby(\"Country name\"):\n    group.plot(\n        ax = ax, \n        x = \"year\", \n        y = \"Life Ladder\", \n        label = country\n    )\n    \nax.tick_params(axis=\"both\", which=\"major\", labelsize=18)\nax.set_xlabel(\"Year\")\nplt.axhline(6.5, color=\"black\", linewidth=1.5, alpha=0.6)\nax.set_xlim(2004.5,2021)\nplt.axvline(2004.75, color=\"black\", linewidth=1.5, alpha=0.5)\n\n# signature bar\nax.text(\n    x = 2003.7,\n    y = 6.17,\n    s = \"   twitch.tv\/MitchsWorkshop                                                                                        Source: Gallup World Poll   \",\n    fontsize = 17,\n    color = \"#F0F0F0\",\n    backgroundcolor = \"grey\"\n)\n\n# title\nax.text(\n    x = 2004,\n    y = 8.3,\n    s = \"The World's Top 5 Happiest Countries, and the United States\",\n    fontsize = 21,\n    fontweight = \"bold\",\n    fontfamily = \"poppins\"\n)\n\n# add subtitle\nax.text(\n    x = 2004,\n    y = 8.141,\n    s = \"Note: the y-axis is not base-0. This is purely a demonstration of improved plot aesthetics.\\nAll scores are out of 10.\",\n    fontsize = 18\n)\n\n# custom colors\ncolors = [\n    \"#3c9dbd\",\n    \"#c2762b\",\n    \"#cc274d\",\n    \"#29802c\",\n    \"#565e5e\",\n    \"#623aa6\"\n]\n\n# change line colors\nfor i,c in enumerate(colors):\n    plt.gca().get_lines()[i].set_color(c)\n    \n### add the following: ###\n\n# Denmark\nplt.text(\n    x = 2005.5,\n    y = 7.88,\n    s = \"Denmark\",\n    rotation = -29,\n    color = colors[0],\n    fontsize = 14,\n    fontweight = \"bold\"\n)\n\n# Finland\nplt.text(\n    x = 2006.2,\n    y = 7.7,\n    s = \"Finland\",\n    rotation = 0,\n    color = colors[1],\n    fontsize = 14,\n    fontweight = \"bold\"\n)\n\n# Iceland\nplt.text(\n    x = 2008,\n    y = 6.95,\n    s = \"Iceland\",\n    rotation = 42,\n    color = colors[2],\n    fontweight = \"bold\"\n)\n\n# Switzerland\nplt.text(\n    x = 2012,\n    y = 7.6,\n    s = \"Switzerland\",\n    rotation = -37,\n    color = colors[4],\n    fontweight = \"bold\"\n)\n\n# United States\nplt.text(\n    x = 2010,\n    y = 6.985,\n    s = \"United States\",\n    rotation = -20,\n    color = colors[5],\n    fontweight = \"bold\"\n)\n\n# Iceland (whom I originally forgot. Sorry, Iceland.)\nplt.text(\n    x = 2013,\n    y = 7.25,\n    s = \"Iceland\",\n    rotation = -25,\n    color = colors[3],\n    fontweight = \"bold\"\n)\n\n# disable legend\nax.get_legend().remove()\n\nplt.savefig(\"after.png\", bbox_inches = \"tight\") # for twitter @MitchsWorkshop\nplt.show()\n\"\"\"\n### I build things like this live on [Twitch](http:\/\/twitch.tv\/MitchsWorkshop)! Stop by and ask questions or just hang out and talk data!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '89043fc749b454'}"}
{"id":"57974","text":"\"\"\"\n# import libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport gc\n\nfrom IPython.display import clear_output\n!pip install autokeras\nclear_output()\n\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport autokeras as ak\n\"\"\"\n# global variables\n\"\"\"\nID = \"id\"\nTARGET = \"target\"\nTEST_SIZE = 0.2\nRANDOM_SEED = 42\nMAX_TRIAL = 3 # for simple test \nEPOCHS = 5  # for simple test \nVALIDATION_SPLIT = 0.15\n\"\"\"\n# load data \n\"\"\"\ntrain = pd.read_csv(\"..\/input\/tabular-playground-series-nov-2021\/train.csv\")\ntest = pd.read_csv(\"..\/input\/tabular-playground-series-nov-2021\/test.csv\")\n\"\"\"\n# delete unnecessary columns\n\"\"\"\ntrain = train.drop([ID],axis=1)\ntest = test.drop([ID],axis=1)\n\"\"\"\n# split data (input data and target data)\n\"\"\"\ny = train[TARGET]\nX = train.drop([TARGET],axis=1)\nX_test = test\n\ngc.collect()\n\"\"\"\n# scaling\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\ntotal = pd.concat([X,X_test],axis=0)\ntrans = StandardScaler()\ntrans.fit(total)\n\nX= trans.transform(X)\nX_test = trans.transform(X_test)\n\ngc.collect()\n\"\"\"\n# split data (train set and validation set)\n\"\"\"\nX_train,X_val,y_train,y_val=train_test_split(X,y,test_size=TEST_SIZE,random_state=RANDOM_SEED)\n\"\"\"\n# search best model and build best model \n\"\"\"\nclf = ak.StructuredDataClassifier(max_trials=MAX_TRIAL,seed=RANDOM_SEED)\nclf.fit(X_train, y_train, epochs=EPOCHS, validation_split=VALIDATION_SPLIT)\n\"\"\"\n# evaluate model\n\"\"\"\nclf.evaluate(X_val, y_val)\n\"\"\"\n# get best model\n\"\"\"\nmodel = clf.export_model()\nmodel.summary()\n\"\"\"\n# predict test data using best model\n\"\"\"\npred_test = model.predict(X_test)\n\"\"\"\n# submission\n\"\"\"\nsub = pd.read_csv('..\/input\/tabular-playground-series-nov-2021\/sample_submission.csv')\nsub['target']=pred_test\nsub.to_csv('sub.csv',index=False)\nsub.head()","meta":"{'source': 'AI4Code', 'id': '6b1352636728cc'}"}
{"id":"19013","text":"\"\"\" # Detect 100% Malignant Tumors! - A Machine Learning Project ## *Applying and discussing a wide variety of Machine Learning techniques to detect Malignant Tumors* --- ## Introduction <p> On this kernel we will go through the whole process of developing a Machine Learning model - from EDA to parameter tuning and model stacking. We will use the Breast Cancer dataset to try to predict if a tumor is benign or malignant. This dataset was obtained on <a href=\"https:\/\/www.kaggle.com\/uciml\/breast-cancer-wisconsin-data\">kaggle<\/a>. The link contains the complete description but all you need to know to understand this analysis will be defined here. <\/p> <p> I put a few comments on throughout the analysis to either clarify some points or give my opinion on a subject. Those are presented in blockquotes colored in dark blue. <br> <blockquote> <font color=\"darkblue\">This is a comment!<\/font> <\/blockquote> I hope you enjoy this work and can get some useful insight or piece of code from it.<\/p> **Keywords**:<br> Python, Machine Learning, Model Stacking, Feature Engineering, Health ### Contents ![](https:\/\/i.imgur.com\/TZCFAfs.png) ### TLDR Version This dataset contains information on 569 breast tumors and the mean, standard error and worst measures for 10 different properties. I start with an EDA analysing each properties' distribution, followed by the pair interactions and then the correlations with our target: the tumor diagnosis. After the EDA I set up 10 out-of-the-box models for a first evaluation and use cross-validation to measure them. I use Recall instead of Accuracy or F1-Score since I want to detect all malignant tumors. After the first results I analyse features importances, do a single round of feature selection and evaluate the models again. By the end of the chapter I analyse model errors and from the 10 first models I choose 5 for model tuning: Logistic Regression, SVC, Random Forest, Gradient Boosting and KNN. I then proceed to tune the five models using GridSearchCV and prepare the data for model stacking by predicting probabilities for both train and test sets. Using Logistic Regression as a second-level model, I tune its parameters and finish the construction phase. Finally, I test all first level models and the stacked Logistic Regression on our untouched test-set. For the first level models, using regular 0.5 threshold Logistic Regression performed best with 95,8% Recall. By lowering the threshold SVC and Logistic Regression tied with over 98% recall with SVC having a higher Accuracy. By using the model-stacking technique, Logistic Regression was able to obtain 100% Recall on the test set. On the last chapter I summarize the findings and conclusions. On Annex - A I repeat a few Machine Learning steps using SMOTE to generate new data points making the data balanced. On Annex - B I use three different dimensionality reduction techniques to see if I can reduce the dataset and still get a good test score. \"\"\" \"\"\" --- \"\"\" \"\"\" --- \"\"\" \"\"\" # 1 - The Dataset --- ## 1.1 - Introducing the Data \"\"\" \"\"\" ### General Information - Original format: csv - Dataset shape: 569 x 33 (rows x columns) - Granularity: Each row derives from an unique sample of breast mass - There are no null values in this data. - The values are in different scales ### Features in the dataset For each sample ten properties were measured: <ol> <li><b>Radius<\/b> - Mean distances from center to points on the perimeter<\/li> <li><b>Texture<\/b> - Standard deviation of gray scale values<\/li> <li><b>Perimeter<\/b><\/li> <li><b>Area<\/b><\/li> <li><b>Smoothness<\/b> - Local variation in radius lengths<\/li> <li><b>Compactness<\/b> - Perimeter^2\/Area - 1<\/li> <li><b>Concavity<\/b> - Severity of concave portions of the contour<\/li> <li><b>Concave points<\/b> - Number of concave portions of the contour<\/li> <li><b>Simmetry<\/b><\/li> <li><b>Fractal Dimension<\/b> - Coastline approximation - 1 <\/li> <\/ol> <blockquote> <font color='darkblue'> <b>From <a href=\"https:\/\/en.wikipedia.org\/wiki\/Fractal_dimension\">wikipedia<\/a>:<\/b> <br><i>[...] a <b>fractal dimension<\/b> is a ratio providing a statistical index of complexity comparing how detail in a pattern (strictly speaking, a fractal pattern) changes with the scale at which it is measured.<\/i> <\/font> <\/blockquote> And for each of these properties we have three calculated values: - **Mean** - **Standard Error** - **Worst** (Average of the 3 largest values) All the measures are float types. ### Target Our target is the categorical column *diagnosis* with either B (benign) or M (malignant).<br> There are 357 benign classes and 212 malignant classes - roughly **37% malignant tumors**. \"\"\" \"\"\" <hr\/> \"\"\" \"\"\" --- \"\"\" \"\"\" ## 1.2 - Importing Libraries \"\"\" \"\"\" We need only the basic tools for an EDA for now. \"\"\" import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set(style='whitegrid', rc={'axes.grid': False}) dataset = pd.read_csv('..\/input\/data.csv') dataset.sample(5) # Our last column is just an error in the data reading. Dropping it dataset = dataset.drop(['id', 'Unnamed: 32'], axis=1) # Creating a binary target column to allow some data manipulations later on dataset['Target'] = dataset['diagnosis'].map({'B':0, 'M':1}) # Getting lists with features. This will be useful on visualization mean_feats = np.concatenate([['diagnosis'], dataset.iloc[:,1:11].columns.tolist()]) error_feats = np.concatenate([['diagnosis'], dataset.iloc[:,11:21].columns.tolist()]) worst_feats = np.concatenate([['diagnosis'], dataset.iloc[:,21:31].columns.tolist()]) \"\"\" <hr> \"\"\" \"\"\" ## 1.3 - Defining Train\/Test sets \"\"\" from sklearn.model_selection import train_test_split train, test = train_test_split(dataset, test_size=0.3, stratify=dataset['Target'], random_state=42) \"\"\" Using the stratify parameter we can guarantee that both our train and test sets have the same proportion of both classes. We must make sure our train data is as close as possible to the data it is going to be evaluated on. \"\"\" train_diag = train.diagnosis.value_counts() \/ train.shape[0] train_diag.rename('Train', inplace=True) test_diag = test.diagnosis.value_counts() \/ test.shape[0] test_diag.rename('Test', inplace=True) pd.concat([train_diag, test_diag], axis=1) \"\"\" <hr\/> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # 2 - Exploratory Data Analysis Now we will look at individual features and combinations of features \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 2.1 - Data Distributions We are dealing with three measures: mean, std. error and the 'worst'. We should look at each separatedly. We can plot the distribution and look for skewness on the mean values but there is not much we can obtain from plotting distributions of the other two: - Std. error is already a parameter obtained from a distribution and only have positive values so it's likely that we find it to be right-skewed. - Worst is a biased subsample of the measure's samples The <a href='https:\/\/en.wikipedia.org\/wiki\/Central_limit_theorem'>Central Limit Theroem<\/a> states that the distribution of the mean values should look like a normal distribution. Let's explore that. \"\"\" train.iloc[:,1:11].hist(figsize=(10,12), bins=20, layout=(5,2), grid=False) plt.tight_layout(); \"\"\" We can see that some features are pretty skewed. We can measure its skewness using pandas *skew* method and we can try comparing it to a log transformation of the same values to see if we can reduce the skewness. \"\"\" log_means = np.log1p(train.iloc[:,1:11]) skewness = pd.DataFrame({'Original Skewness':train.iloc[:,1:11].skew(), 'Log Transformed':log_means.skew()}) skewness['Skewness Reduction'] = skewness['Original Skewness'] - skewness['Log Transformed'] skewness \"\"\" We managed to greatly reduce skewness on **Radius, Texture, Perimeter and Area**. The other features were barely influenced by our log transformation. There are four features with skewness higher than one after the log transformation: **Compactness, Concavity, Concave Points and Fractal Dimension**. Perhaps the measure error on them is higher or maybe it is somehow biased. Let's explore how are the standard errors for each measure! \"\"\" measure_index = ['radius', 'texture', 'perimeter', 'area', 'smoothness', 'compactness', 'concavity', 'concave points', 'symmetry', 'fractal_dimension'] measure_data = np.c_[train.iloc[:,1:11].mean().values, train.iloc[:,11:21].mean().values] measure_df = pd.DataFrame(data=measure_data, columns=['Mean', 'Error'], index=measure_index) measure_df['Error pct'] = 100 * measure_df['Error'] \/ measure_df['Mean'] measure_df \"\"\" This might explain part of our high skewness: from our four highly skewed features, three of them have standard errors of more than 20%! Many things can cause that (e.g. uncallibrated measuring instruments). I don't have any other ideas to explore on fractal dimensions distribution for now. For the log transformations: we will come back to them later on Chapter 5. \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 2.2 - Features Overlook We can use seaborn's amazing pairplot to give a first overview on all features and some pair interactions. ### Mean Features Plot There are a few things to point out on this plot. - From all the histograms in the grid's diagonal plots, only fractal dimension has no visual impact on the tumor's class. That is also observed in all plots on the last row\/column. This is convenient because Fractal Dimension is the unexplained skewed feature we've just talked about. This is a strong candidate for a feature selection later on. - The second lowest visual impact (I'm saying visual because we will see some numbers later) is on symmetry. - All the other features appear to have a significant impact on the classification of tumors and the scatterplots look quite 'separable'. - We also can observe some 'pretty plots' on the related geometrical features Radius, Area and Perimeter, which is to be expected. This high correlation between features might be a problem for some ML algorithms \"\"\" sns.set(style='whitegrid', font_scale=1.35, rc={'axes.grid': False}) p = sns.pairplot(train[mean_feats], hue='diagnosis', plot_kws={'alpha':0.6}, palette='magma') plt.subplots_adjust(hspace=0.05, wspace=0.05) handles = p._legend_data.values() labels = p._legend_data.keys() p.fig.legend(handles=handles, labels=labels, loc='upper center', ncol=2) p.fig.set_dpi(80); \"\"\" ### Error Features Plot This one surprised me at first. I didn't expect to find anything here - and most features' errors don't appear to have an impact - but look at Area, Perimeter, Radius and Compactness. The data suggests the higher the error on these features, the higher the chance of having a malignant tumor. How can we interpret that? Let's remember how Standard error is calculated: by dividing the standard deviation by the squareroot of the sample size. $$SE = {\\sigma\\over \\sqrt{n}}.$$ I will assume that the sample sizes do not change for each tumor sample, so the Standard error's variation is due to the Standard Deviation only. Assuming that is the case, we can interpret that the malignant tumors have higher irregularity on their geometry, which causes the higher standard deviation! \"\"\" p = sns.pairplot(train[error_feats], hue='diagnosis', plot_kws={'alpha':0.6, }, palette='magma') plt.subplots_adjust(hspace=0.05, wspace=0.05) handles = p._legend_data.values() labels = p._legend_data.keys() p.fig.legend(handles=handles, labels=labels, loc='upper center', ncol=2) p.fig.set_dpi(80); \"\"\" ### Worst Features Plot These plots look very similar to the previous one. This is to be expected since the worst features are subsamples of the mean data. It is hard to tell which one is more important for a predicting model only by looking at those visuals. We need to get some numbers to see if there is a significant difference. \"\"\" p = sns.pairplot(train[worst_feats], hue='diagnosis', plot_kws={'alpha':0.6}, palette='magma') plt.subplots_adjust(hspace=0.05, wspace=0.05) handles = p._legend_data.values() labels = p._legend_data.keys() p.fig.legend(handles=handles, labels=labels, loc='upper center', ncol=2) p.fig.set_dpi(80); \"\"\" --- \"\"\" \"\"\" ## 2.3 - Correlations To calculate the correlations we can use the pandas *corr* method. To visualize it better we can use the classic seaborn's heatmap - which is perfectly fine - but I will plot it using horizontal bar charts. <blockquote> <font color='darkblue'> <b>The downside of not plotting a heatmap<\/b> is that we do not see how features are correlated to each other: there might be redundant features we don't need to feed a machine learning model. We can already see highly correlated features from our previous plots (e.g. Perimeter and Area), but I've chosen to keep them all and let the algorithms decide for them selves which ones are important and which ones aren't (feature selection and regularization). <\/font> <\/blockquote> \"\"\" sns.set(style='whitegrid') def feat_class(feat): if 'worst' in feat: return 'Worst' elif 'mean' in feat: return 'Mean' elif 'se' in feat: return 'Standard Error' corrs = train.corr()[['Target']].sort_values('Target', ascending=False)[1:].reset_index() corrs.rename(columns={'index':'Features'}, inplace=True) corrs['Class'] = corrs['Features'].apply(feat_class) corrs['Main'] = corrs['Features'].apply(lambda x: x.split('_')[0]) \"\"\" ### Correlation by Feature Type First, lets see if we can find a predominant type of feature (*worst, mean or se*). Did we visualize it correctly in the previous plots? \"\"\" fig, ax = plt.subplots(figsize=(8,7), dpi=80) sns.barplot(data=corrs, x='Target', y='Features', ax=ax, hue='Class', dodge=False, palette='tab10') ax.legend(bbox_to_anchor=(1.0, 1.0), loc=2) ax.xaxis.tick_top() ax.xaxis.label.set_visible(False) ax.set_xlim(-0.1, 1.0) ax.yaxis.label.set_visible(False) ax.set_title('Pearson Correlation Between Target and Features by Feature Type'); \"\"\" **Insights from the plot:** - At a first look, Standard Error seems to be the least important kind of measure we are dealing with (of the 6 lowest, 5 are standard error). We correctly pointed out that it did have an impact but only on a few features (radius, area and perimeter). - Aside from that, Worst has the top 3, follower by Mean; \"\"\" \"\"\" ### Correlation by Main Features Next we will plot the same graph but grouping the correlations by their main features (area, radius, etc... ). \"\"\" plot_ord = corrs.sort_values('Features')['Features'] hue_ord = corrs.sort_values('Main')['Main'].unique() fig, ax = plt.subplots(figsize=(8,7), dpi=80) sns.barplot(data=corrs, x='Target', y='Features', ax=ax, order=plot_ord, hue='Main', hue_order=hue_ord, dodge=False, palette='Paired') ax.legend(bbox_to_anchor=(1.0, 1.0), loc=2) ax.xaxis.tick_top() ax.xaxis.label.set_visible(False) ax.yaxis.label.set_visible(False) ax.set_xlim(-0.1, 1.0) ax.set_title('Pearson Correlation Between Target and Features by Main Feature'); \"\"\" <b>Insights from the plot<\/b>: <ul> <li>We can observe that <u>for all features except for Fractal Dimension have a similar pattern<\/u>: The two highest correlated feature types are WORST and MEAN and the lowest is the STANDARD ERROR.<\/li> <li>Fractal dimension has been the exception since 3.1. Apparently all that matters in terms of this feature are the worst measures.<\/li> <\/ul> That said, we must remember that Pearson's correlation can only measure two individual features and we can't see how the combination of features influence in our target. As I've mentioned: I will keep them and let my model decide. \"\"\" \"\"\" ### Chapter Recap: - We've analysed how our features impact on our target. - We've pointed out that there are many features correlated to each other Time to do some machine learning. \"\"\" \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # 3 - First Models \"\"\" \"\"\" On this section we will: - Pick different out-of-the-box models and evaluate them in our training data; - See if the first results give us any tips on how to improve our data somehow and test some ideas (feature engineering); - Choose the top five most promising and distinct models The models we will be using are: - Logistic Regression - LDA - Support Vector Classifier (SVC) - Linear SVC - Decision Tree - Random Forests - Gradient Boos Classifier - AdaBoost Classifier - XGB - K-Nearest Neighbors \"\"\" # Importing Models from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, GradientBoostingClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC, LinearSVC from xgboost import XGBClassifier # Importing other tools from sklearn.metrics import confusion_matrix, classification_report, make_scorer from sklearn.metrics import accuracy_score, recall_score, precision_recall_curve from sklearn.model_selection import StratifiedKFold, cross_validate from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.calibration import CalibratedClassifierCV \"\"\" <hr> \"\"\" \"\"\" ## 3.1 - Setting Up the Training \"\"\" \"\"\" We have a small dataset. In order to make the most out of it we will be using cross-validation to evaluate our models . First lets create the models with standard parameters. \"\"\" # Defining random seed seed=42 # Creating Models logreg = LogisticRegression(solver='lbfgs', random_state=seed) lda = LinearDiscriminantAnalysis() svc = SVC(random_state=seed, probability=True) lin_svc = LinearSVC(random_state=seed) l_svc = CalibratedClassifierCV(lin_svc, cv=5) dtree = DecisionTreeClassifier(random_state=seed) rf = RandomForestClassifier(10, random_state=seed) gdb = GradientBoostingClassifier(random_state=seed) adb = AdaBoostClassifier(random_state=seed) xgb = XGBClassifier(random_state=seed) knn = KNeighborsClassifier() first_models = [logreg, lda, svc, l_svc, dtree, rf, gdb, adb, xgb, knn] first_model_names = ['Logistic Regression', 'LDA', 'SVC', 'Linear SVC', 'Decision Tree', 'Random Forest', 'GradientBoosting', 'AdaBoost', 'XGB', 'K-Neighbors'] # Defining other steps n_folds = 5 skf = StratifiedKFold(n_splits=n_folds, random_state=seed) std_sca = StandardScaler() \"\"\" Splitting X and Y for our training and test sets \"\"\" X_train = train.drop(['diagnosis', 'Target'] ,axis=1) y_train = train['Target'] \"\"\" --- \"\"\" \"\"\" ## 3.2 - Evaluating the first models \"\"\" \"\"\" ### Choosing the Proper Measure to Evaluate the Model Performance There are **a lot** of ways to measure the quality of your model and we must choose it carefully. This is one of the most important parts of a Machine Learning Project. Our objective isn't classifying correctly the tumors. If that was the case simply using Accuracy - which is the ratio of correctly predicted classes - would do the job. However, the objective of this analysis is **detecting malignant tumors**. And how do we measure that? Not with Accuracy, but with **RECALL**. Recall answers the following question: *from all the malignant tumors in our data, how many did we catch?*. Recall is calculated by dividing the True positives by the total number of positives (positive = malignant). It is important to realize that a high Recall doesn't mean a high Accuracy and there is often a trade-off between different performance measures. That said, we will be making our decisions based on Recall but we will also measure Accuracy to see the difference between them. Moving on! \"\"\" \"\"\" <blockquote> <font color='darkblue'> <b>Coding Explanation:<\/b><br> The code on the cell below does the following steps: <ol> <li><b>Setting up:<\/b><\/li> <ol> <li>Creates an array to store the out-of-fold predictions that we will use later on. Its shape is the training size by the number of models we have;<\/li> <li>Creates a list to store the Accuracy and Recall scores<\/li> <\/ol> <li><b>Outer Loop<\/b>: Iterating through Models<\/li> <ol> <li>Creates a data pipeline with the scaler and the model<\/li> <li>Creates two arrays to store each fold's accuracy and recall<\/li> <li>Executes the inner loop<\/li> <li>By the end of the cross-validation, stores the mean and the standard deviation for those two measures in the scores list<\/li> <\/ol> <li><b>Inner Loop<\/b>: Cross-Validation<\/li> <ol> <li>Splits the training data into train\/validation data<\/li> <li>Fits the model with the CV training data and predicts the validation data<\/li> <li>Stores the out-of-fold predictions (which is the validation predictions) in oof_preds<\/li> <li>Measures the Accuracy and Recall for the fold and stores in an array<\/li> <\/ol> <\/ol> <\/font> <\/blockquote> \"\"\" train_size = X_train.shape[0] n_models = len(first_models) oof_pred = np.zeros((train_size, n_models)) scores = [] for n, model in enumerate(first_models): model_pipeline = Pipeline(steps=[('Scaler', std_sca), ('Estimator', model)]) accuracy = np.zeros(n_folds) recall = np.zeros(n_folds) for i, (train_ix, val_ix) in enumerate(skf.split(X_train, y_train)): x_tr, y_tr = X_train.iloc[train_ix], y_train.iloc[train_ix] x_val, y_val = X_train.iloc[val_ix], y_train.iloc[val_ix] model_pipeline.fit(x_tr, y_tr) val_pred = model_pipeline.predict(x_val) oof_pred[val_ix, n] = model_pipeline.predict_proba(x_val)[:,1] fold_acc = accuracy_score(y_val, val_pred) fold_rec = recall_score(y_val, val_pred) accuracy[i] = fold_acc recall[i] = fold_rec scores.append({'Accuracy' : accuracy.mean(), 'Recall' : recall.mean()}) \"\"\" <blockquote> <font color='darkblue'> <b>Why not scale the data before? Why the pipeline?<\/b><br> This is a common and easy to avoid data-leakage mistake when using Scalers or other feature processing algorithms. In the case of standard scaling, it follows a simple process: it reads the data and calculates its mean and standard deviation then it centers the dataset mean to 0 and scales its standard deviation to 1<br> <br>Let's say we weren't using cross-validation and instead we just had a train and a validation set. If we were to fit our StandardScaler with all the data, our scaled dataset would have information on the test set distribution - aka data leakage. We don't want our model to 'see' any data other than the training set so this is to be avoided.<br> <br>This applies to cross-validation as well. When cross-validating, we create N train-validation splits and for every fold we must scale our data based on the training data only. So, how do we do that?<br> <br>We use a <b>Pipeline<\/b> which <i>glues<\/i> our Model to other data preprocessing APIs. In our case, when er fit our pipeline we are fitting and transforming the data with StandardScaler and then fitting the ML Model. This could also be done separatedly, by having more code explicitly fitting and transforming the data for each fold. However, using Pipelines (especially when there are more processing steps) makes it cleaner and more reusable\/scalable.<br> <\/font> <\/blockquote> \"\"\" \"\"\" ### First Models' Results \"\"\" measure_cols = ['Accuracy', 'Recall']#, 'Accuracy Std.Dev.', 'Recall Std.Dev.'] first_scores = pd.DataFrame(columns=measure_cols) for name, score in zip(first_model_names, scores): new_row = pd.Series(data=score, name=name) first_scores = first_scores.append(new_row) first_scores = first_scores.sort_values('Recall', ascending=False) first_scores \"\"\" This table shows us each model ordered by its Recall, descending. **Insights**: - SVC and Logistic Regression got the highest scores, while Decision Tree and LDA got the lowest. - LDA does not provide optimal results if the features are highly correlated - which some are. This poor result isn't a big surprise. - All the other models got above 95% accuracy and 90% recall on a first try. \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 3.3 - Feature Selection \"\"\" \"\"\" Most models provide a method that returns feature importances or coefficients so we can have an idea of what is being considered the most important features of our dataset. SVC, Linear SVC and KNN are the ones that don't have it. Let's see if we can find anything from the other models preferences. \"\"\" feature_names = X_train.columns feat_imp_df = pd.DataFrame(columns=first_model_names, index=feature_names) # Dropping the Models that don't have feature importances for this analysis feat_imp_df.drop(['SVC', 'Linear SVC', 'K-Neighbors'], axis=1, inplace=True) # I'm using absolute values for logistic Regression and LDA because we only care about the magnitude of the coefficient, not its direction feat_imp_df['Logistic Regression'] = np.abs(logreg.coef_.ravel()) feat_imp_df['LDA'] = np.abs(lda.coef_.ravel()) feat_imp_df['Decision Tree'] = dtree.feature_importances_ feat_imp_df['Random Forest'] = rf.feature_importances_ feat_imp_df['GradientBoosting'] = gdb.feature_importances_ feat_imp_df['AdaBoost'] = adb.feature_importances_ feat_imp_df['XGB'] = xgb.feature_importances_ \"\"\" So this is how our table looks like right now. Each model has its own measure for each feature's importances. You will notice that some measures are in different scales. In order to compare the importances between the models we need to scale them. I will use sklearn MinMaxScaler to shrink them to a [0, 1] interval and then sum the features importances for each model. \"\"\" feat_imp_df.head(3) from sklearn.preprocessing import MinMaxScaler mms = MinMaxScaler() scaled_fi = pd.DataFrame(data=mms.fit_transform(feat_imp_df), columns=feat_imp_df.columns, index=feat_imp_df.index) scaled_fi['Overall'] = scaled_fi.sum(axis=1) ordered_ranking = scaled_fi.sort_values('Overall', ascending=False) fig, ax = plt.subplots(figsize=(10,7), dpi=80) sns.barplot(data=ordered_ranking, y=ordered_ranking.index, x='Overall', palette='magma') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.xaxis.set_visible(False) ax.grid(False) ax.set_title('Feature Importances for all Models'); \"\"\" **Insights**: - Worst Perimeter is the most important features between models; - There is a clear preference for Worst features on models. The top 6 features are 'Worst'; - All Fractal Dimension features are in the bottom 5. Symmetry's Mean and S.Error is pretty low as well, but Symmetry Worst, curiously, is pretty high. This is what our models have to tell us. If we decided on dropping features based on the correlations plotted in Chapter Three we would've gotten some of them wrong. Let's try now removing the Bottom 5 and repeat the training to see if we get any better results. Just copying the code already used before. \"\"\" train_v2 = train.drop(ordered_ranking.index[:-6:-1], axis=1) test_v2 = test.drop(ordered_ranking.index[:-6:-1], axis=1) X_train_v2 = train_v2.drop(['diagnosis', 'Target'] ,axis=1) X_test_v2 = test_v2.drop(['diagnosis', 'Target'] ,axis=1) train_size = X_train_v2.shape[0] test_size = test.shape[0] n_models = len(first_models) oof_pred = np.zeros((train_size, n_models)) scores = [] for n, model in enumerate(first_models): model_pipeline = Pipeline(steps=[('Scaler', std_sca), ('Estimator', model)]) accuracy = np.zeros(n_folds) recall = np.zeros(n_folds) for i, (train_ix, val_ix) in enumerate(skf.split(X_train_v2, y_train)): x_tr, y_tr = X_train_v2.iloc[train_ix], y_train.iloc[train_ix] x_val, y_val = X_train_v2.iloc[val_ix], y_train.iloc[val_ix] model_pipeline.fit(x_tr, y_tr) val_pred = model_pipeline.predict(x_val) oof_pred[val_ix, n] = model_pipeline.predict_proba(x_val)[:,1] fold_acc = accuracy_score(y_val, val_pred) fold_rec = recall_score(y_val, val_pred) accuracy[i] = fold_acc recall[i] = fold_rec scores.append({'Accuracy' : accuracy.mean(), 'Recall' : recall.mean()}) measure_cols = ['Accuracy', 'Recall'] fs_scores = pd.DataFrame(columns=measure_cols) for name, score in zip(first_model_names, scores): new_row = pd.Series(data=score, name=name) fs_scores = fs_scores.append(new_row) fs_scores = fs_scores.sort_values('Recall', ascending=False) d={'First Scores':first_scores, 'Less Features':fs_scores} pd.concat(d, axis=1, sort=False) \"\"\" **Insights from Feature Selection**: - What changed? - Logistic Regression and LDA didn't change at all; - SVC and Gradient Boosting slightly improved (probably just one extra sample); - KNN, Decision Tree, Linear SVC and XGB got worst; - AdaBoost and Random Forest greatly improved - Our bottom models are the same as before (LDA, Decision Tree and Linear SVC). <b>It is not clear if removing the features was a good decision or not. When in doubt, opt for the simpler choice: We are removing them.<\/b> We will start our model selection by dropping Decision Tree and LDA. We will also drop Linear SVC because we can tweak the regular SVC parameters to obtain a Linear SVC. <blockquote> <font color='darkblue'> <b>Linear SVCs<\/b> train and predict really faster than a SVC with linear parameters, but once more, our dataset is small so it's not a problem <\/font> <\/blockquote> \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 3.4 - Analysing Model Errors \"\"\" \"\"\" We will start selecting the next models by creating a dataframe with all the models' out-of-fold predictions to compare their results. \"\"\" oof_dataframe = pd.DataFrame(data=oof_pred, columns=first_model_names, index=train.index) oof_dataframe['Target'] = train['Target'] oof_dataframe = oof_dataframe.drop(['LDA', 'Decision Tree', 'Linear SVC'], axis=1) \"\"\" ### Can't get them right Lets see if we can find examples that all models got the classification wrong. The function defined below does just that. \"\"\" def all_wrong(x): predictions = sum(x[:7]) target = x[7] if (target == 1 and predictions == 0) or \\ (target == 0 and predictions == 7): return True else: return False oof_dataframe['All_wrong'] = round(oof_dataframe).apply(all_wrong, axis=1) oof_dataframe.query(\"All_wrong == True\") \"\"\" We have those five tumors that no model got right. By the looks of it, AdaBoost was the one that was closest to classifying it right. (The standard threshold is 0.5 probability). I'm out of ideas to further explore these for now. \"\"\" \"\"\" ### Getting Different Opinions Simply plotting correlations will be hard to distinguish which models are least correlated with the rest. This is due to the fact that all remaining models have over 95% accuracy so their overall correlation will be high. A better way to approach this is by looking at the tumors that our models classified wrong and\/or that they didn't agree on the classification. We can map the models' predictions for 'Easy' ones (that most of them got right) and filter them out. This way we can focus only on how different their 'opinions' are. \"\"\" \"\"\" <blockquote> <h3><font color='darkblue'>On Model Stacking<\/font><\/h3> <p><font color='darkblue'> <b>'Why pick models that don't agree with each other?'<\/b><br> We are looking for uncorrelated models for model stacking and this question is a really common one. Why is it better?<br> <a href='http:\/\/blog.kaggle.com\/author\/bengorman\/'>Ben Gorman<\/a> has a nice post on this topic explaining it and I suggest you read it if you want to get the intuition on stacking. (<a href='http:\/\/blog.kaggle.com\/2016\/12\/27\/a-kagglers-guide-to-model-stacking-in-practice\/'>blog post<\/a>) <\/font><\/p> <p><font color='darkblue'> Nonetheless I will try to put it <u>in simple words<\/u> here:<br> Model Stacking is just like building any kind of team. You don't want everyone in your team good in the same things, you want diversity so you can perform well on different cases\/scenarios. If you want to build a diagnosis medical team for all kinds of scenarios you probably don't want only infectologists. Putting it this way, it is intuitively wiser to get different kinds of specializations on your team. <\/font><\/p> <p><font color='darkblue'> <u>It works exactly the same in Machine Learning.<\/u> <\/font><\/p> <p><font color='darkblue'> <b>Imagine we only had three models and had to choose two: A Linear SVC, a Logistic Regression and a KNN<\/b>. Both Linear SVC and Logistic Regression are linear models so they have similar results. Let's also say that: <\/font><\/p> <ul><font color='darkblue'> <li>We only have two features: Radius and Perimeter<\/li> <li><b>Linear SVC and Logistic Regression<\/b> perform best on cases where all features are high (high radius and perimeter)<\/li> <li><b>KNN<\/b> performs best on the opposite scenario - low radius and perimeter<\/li> <\/font><\/ul> <p><font color='darkblue'> In other words, LinearSVC and LogReg are highly correlated with eachother but not with KNN. The obvious choice is to pick KNN and one of the other ones, otherwise we will never get all cases right. Let's pick LSVC for this example. <\/font><\/p> <p><font color='darkblue'> The fantastic thing about Model Stacking is that our second level model is able to learn when to use each models' opinion for every data point. If we - ontop of Radius and Perimeter features - added the predictions from KNN and and LSVC as features, our second-level model is able to, for instance, associate high radius and perimeter cases with LSVC predictions and don't listen to KNN on such cases. <\/font><\/p> \"\"\" # We have 7 models + our target so the perfect scores would be 0 and 1 # I am also adding to the Easy Ones group cases that only one model disagrees with the rest oof_dataframe['Easy_one'] = round(oof_dataframe).sum(axis=1).isin([0, 1, 7, 8]) # We define our Hard_ones dataset by filtering easy_ones out hard_ones = oof_dataframe.query(\"Easy_one == False and \\ All_wrong == False\").drop(['Easy_one', 'All_wrong'], axis=1) plt.figure(figsize=(10,8), dpi=80) sns.heatmap(hard_ones.corr(), vmin=-0.4, vmax=0.7, annot=True) plt.title(\"Correlation between models for the 'Hard Ones'\"); \"\"\" This heatmap shows correlation between prediction probabilities for all models on the hard tumor samples defined above. We are looking at the 5% our models can't get right. **Insights:** - The most correlated models are XGB and GradientBoosting, which is to be expected. Between those two, however, GradientBoosting is less correlated with the other models (-0,44 with Logistic Regression and -0,52 with SVC). **We should keep GradientBoostin and drop XGB**; - **SVC and Logistic Regression** are the ones with the highest correlation with the Target on these hard data points and they are fundamentally different. **Keeping them**. - **KNN** also has a high correlation with the target and an overall low correlation with the other models - **stays**. - Finally we will also **keep Random Forest** to have another one besides Gradient Boosting to disagree with Logistic Regression and SVC. This leaves us with five models out of our ten initial ones: - Logistic Regression - SVC - GradientBoosting - Random Forest - KNN \"\"\" \"\"\" ### Chapter Recap: In this chapter we: - Started with a 10 model list - Trained them using cross-validation and measured Accuracy and Recall - Analysed each models' feature importances and dropped five features out of our dataset - Analysed the models' predictions for the classifications they disagreed on - Chose 5 models for the next analysis \"\"\" \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # 4 - Fine Tuning the System \"\"\" \"\"\" ## 4.1 - Hyperparameters Listed below are the five models and the parameters we are going to tune (not all will be listed). ![](https:\/\/i.imgur.com\/PMfff5N.png) \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 4.2 - Tuning Tools \"\"\" \"\"\" Sklearn's GridSearchCV is our best friend for parameter tuning. We will optimize our models for Recall. Lets start importing it. \"\"\" from sklearn.model_selection import GridSearchCV # Defining this function to make our lives easier on tuning def train_gridsearch(model, x=X_train_v2, y=y_train, name=None): t_model = model t_model.fit(x, y) print(30*'-') if name != None: print(name) print('\\nBest Parameters:') for item in t_model.best_params_.items(): print(item[0], ': ', item[1]) print('\\nScore: ', t_model.best_score_, '\\n') print(30*'-') \"\"\" <blockquote> <font color='darkblue'> A common way to start searching for parameters is to pick multiples of 10 and then refine it as you go. <br> Another way to do this is to use <b>RandomizedSearchCV<\/b> and create a large parameter space. This API will randomly pick parameters to test (this technique is more recommended if you have too many parameters to try and don't have the time) <\/font> <\/blockquote> \"\"\" \"\"\" One last thing before starting our tuning is to create another Pipeline step for the log transformation we applied in Chapter 3.1. This transformation might be helpful and we want to try it with GridSearchCV We can create a Logger class using *BaseEstimator* and *TransformerMixin* so we can put it inside a pipeline. Inside this Logger class we can define our log transformation function and set a parameter to trigger it. \"\"\" from sklearn.base import BaseEstimator, TransformerMixin class Logger(BaseEstimator, TransformerMixin): def __init__(self, apply_log = True): self.apply_log = apply_log def fit(self, X, y=None): return self def transform(self, X, y=None): logX = X.copy() if self.apply_log: logX = np.log1p(X) return logX else: return X logger = Logger() \"\"\" <hr> \"\"\" \"\"\" ## 4.3 - Logistic Regression \"\"\" \"\"\" The first model we are tuning is Logistic Regression. Let's start listing the parameters in a dictionary so we can feed our GridSearchCV \"\"\" # Logistic Regression Initial Parameters log_pams = [{'M__solver':['liblinear'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, ], 'M__penalty':['l1'], 'L__apply_log':[True, False]}, {'M__solver':['lbfgs'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, ], 'M__penalty':['l2'], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. log_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', logreg)]) log_gs = GridSearchCV(log_pipe, log_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(log_gs) \"\"\" Our best C is at 1 so we might refine our parameters near that value. A second run on parameter tuning could look like: \"\"\" # Logistic Regression Initial Parameters log_pams = [{'M__solver':['liblinear'], 'M__class_weight':['balanced'], 'M__C': [0.5, 0.75, 1, 1.25, 1.5], 'M__penalty':['l1'], 'L__apply_log':[True]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. log_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', logreg)]) log_gs = GridSearchCV(log_pipe, log_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(log_gs) \"\"\" Let's settle for that. Already a great improvement from the first model results. At least for Logistic Regression, our log transformation worked well. \"\"\" logreg_tuned = log_gs.best_estimator_ \"\"\" <hr \/> \"\"\" \"\"\" ## 4.4 - SVC \"\"\" # SVC Initial Parameters svc_pams = [{'M__kernel':['rbf'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, 100, 200], 'M__gamma':['auto', 'scale', 0.001, 0.01, 0.1], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. svc_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', svc)]) svc_gs = GridSearchCV(svc_pipe, svc_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False, refit=True) train_gridsearch(svc_gs) \"\"\" We got an amazing result for the first round of tuning for SVC. \"\"\" # SVC Second round Parameters svc_pams = [{'M__kernel':['rbf'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.05, 0.07, 0.1, 0.12, 0.15, 0.2], 'M__gamma':[0.05, 0.1, 0.15, 0.5, 1.0], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. svc_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', svc)]) svc_gs = GridSearchCV(svc_pipe, svc_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(svc_gs) \"\"\" **100%!** In our training data, through cross-validation, our model was able to predict all the malignant tumors. **This, however, comes at a cost!** SVC is probably overfitting and\/or classifying a lot of benign tumors as malign to get 100% recall. As discussed in the beginning of chapter 4, there is often a trade-off between performance measures. Let's take a quick detour and see how is this tuned SVC classifying our training data. A confusion matrix will expose this impostor! \"\"\" print(confusion_matrix(y_train, svc_gs.predict(X_train_v2))) \"\"\" As expected, SVC is 'lowering the bar' to classify malignant tumors and in that process it is wrongly classying many (128) benign tumors as malignant. Let's try tuning it again and using F1-Score instead (F1 is an average of Recall and Precision). \"\"\" # SVC Initial Parameters svc_pams = [{'M__kernel':['rbf'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, 100, 200], 'M__gamma':['auto', 'scale', 0.001, 0.01, 0.1], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. svc_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', svc)]) svc_gs = GridSearchCV(svc_pipe, svc_pams, 'f1', cv=skf, n_jobs=-1, iid=False, refit=True) train_gridsearch(svc_gs) # SVC Second Parameters svc_pams = [{'M__kernel':['rbf'], 'M__class_weight':[None, 'balanced'], 'M__C': [5, 7.5, 10, 12.5, 15], 'M__gamma':[0.005, 0.01, 0.015], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. svc_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', svc)]) svc_gs = GridSearchCV(svc_pipe, svc_pams, 'f1', cv=skf, n_jobs=-1, iid=False, refit=True) train_gridsearch(svc_gs) \"\"\" If we check the Confusion Matrix again, SVC is way more balanced now. We can also measure the Recall using cross-validation. \"\"\" print(30*'-') print('Confusion Matrix:') print(confusion_matrix(y_train, svc_gs.predict(X_train_v2))) print('\\nCV Recall Score:') print(cross_validate(svc_gs, X_train_v2, y_train, scoring='recall', cv=skf)['test_score'].mean()) print(30*'-') \"\"\" Ok, this is way better than optimizing GridSearch with Recall. We weren't able to improve the recall from the first score in Chapter 4 and the log transformation didn't help here. Moving on. \"\"\" svc_tuned = svc_gs.best_estimator_ \"\"\" <hr> \"\"\" \"\"\" ## 4.5 - GradientBoosting \"\"\" \"\"\" <blockquote> <font color='darkblue'> <b>Training GDB takes too long<\/b>. I took the starting parameters I used out of the code and put it here so I don't have to wait this long everytime.<br> <br>'max_depth':[3, 4, 6, 8], <br>'min_samples_leaf':[1, 2], <br>'max_features': [None, 0.6, 0.75, 0.9], <br>'learning_rate':[0.001, 0.01, 0.1, 1.0], <br>'n_estimators':[30, 60, 100, 200], <br>'subsample':[0.1, 0.5, 0.8, 1.0], <br>'apply_log':[False, True] \"\"\" # GradientBoosting Second round Parameters gdb_pams = {'M__max_depth':[3], 'M__min_samples_leaf':[2], 'M__max_features': [0.9, 0.95], 'M__learning_rate':[0.05, 0.1, 0.15], 'M__n_estimators':[60, 80], 'M__subsample':[0.8, 0.9, 1.0], 'L__apply_log':[False]} # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. gdb_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', gdb)]) gdb_gs = GridSearchCV(gdb_pipe, gdb_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False, refit=True) train_gridsearch(gdb_gs) \"\"\" We weren't able to improve the score on the second round of tuning. Moving on. \"\"\" gdb_tuned = gdb_gs.best_estimator_ \"\"\" <hr> \"\"\" \"\"\" ## 4.6 - Random Forest \"\"\" \"\"\" <blockquote> <font color='darkblue'> <b>Initial Parameters:<\/b> <br>'max_depth':[None, 4, 8, 16], <br>'min_samples_leaf':[1, 2], <br>'max_features': [None, 0.6, 0.75, 0.9, 'auto'], <br>'bootstrap':[True, False], <br>'n_estimators':[10, 30, 60, 100, 200], <br>'class_weight':[None, 'balanced'], <br>'apply_log':[False, True] \"\"\" # Random Forest Second round Parameters rf_pams = {'M__max_depth':[None], 'M__min_samples_leaf':[1, 2], 'M__max_features': [0.8, 0.9, 0.95], 'M__n_estimators':[8, 10, 12], 'M__class_weight':['balanced'], 'L__apply_log':[False, True]} # It is important to apply the log transformer before the scaling rf_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', rf)]) rf_gs = GridSearchCV(rf_pipe, rf_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(rf_gs) \"\"\" Quite few trees for our random forest. Moving on. \"\"\" rf_tuned = rf_gs.best_estimator_ \"\"\" <hr> \"\"\" \"\"\" ## 4.7 - K-Nearest Neighbors \"\"\" \"\"\" There is not much to tune in KNN so we will just go for a single round of tuning. \"\"\" knn_pams = {'M__n_neighbors':np.arange(2, 16), 'M__weights':['uniform', 'distance'], 'M__p':[1, 2, 3], 'L__apply_log':[False, True]} # It is important to apply the log transformer before the scaling knn_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', knn)]) knn_gs = GridSearchCV(knn_pipe, knn_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(knn_gs) \"\"\" Quite an improvement from our first attempt in Chapter 4 (0,9117). \"\"\" knn_tuned = knn_gs.best_estimator_ \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # 5 - Model Stacking \"\"\" \"\"\" So we have our five tuned models ready to be tested. Before we go into the final part of this study I will prepare a stacked model like mentioned before. We will be using **Logistic Regression** as a second-level model because it was the one which had the best scores so far. First we need the tuned models predictions. <hr> ## 5.1 - Defining the Stacking Data We can use sklearn's *cross_val_predict* to make our lives easier. \"\"\" from sklearn.model_selection import cross_val_predict tuned_models = [logreg_tuned, svc_tuned, gdb_tuned, rf_tuned, knn_tuned] tuned_names = ['Logistic Regression', 'SVC', 'GradientBoosting', 'RandomForest', 'KNNeighbors'] tuned_oof_pred = np.zeros(shape=(train_size, 5)) # 5 models for i, model in enumerate(tuned_models): tuned_oof_pred[:,i] = cross_val_predict(model, X_train_v2, method='predict_proba', y=y_train, cv=skf)[:,1] tuned_train_pred = pd.DataFrame(data=tuned_oof_pred, index=X_train_v2.index, columns=tuned_names) \"\"\" Doing the same for the test data. Here we don't need to use cross-validation: We simply fit on the training data and predict the test data. \"\"\" tuned_test_pred = np.zeros(shape=(test_size, 5)) # 5 models for i, model in enumerate(tuned_models): model.fit(X_train_v2, y_train) tuned_test_pred[:,i] = model.predict_proba(X_test_v2)[:,1] tuned_test_pred = pd.DataFrame(data=tuned_test_pred, index=X_test_v2.index, columns=tuned_names) \"\"\" We will also need to scale the training and test data and then concatenate with our first-level predictions. \"\"\" X_train_scaled = std_sca.fit_transform(X_train_v2) X_test_scaled = std_sca.transform(X_test_v2) X_train_final = np.concatenate([X_train_scaled, tuned_train_pred], axis=1) X_test_final = np.concatenate([X_test_scaled, tuned_test_pred], axis=1) \"\"\" <hr> \"\"\" \"\"\" ## 5.2 - Tuning Second Level Model \"\"\" \"\"\" Our data is ready. Only thing missing now is to tune our LogReg. We will do two quick rounds of tuning. \"\"\" # Logistic Regression Initial Parameters log_pams = [{'solver':['liblinear'], 'class_weight':[None, 'balanced'], 'C': [0.001, 0.01, 0.1, 1, 10], 'penalty':['l1']}, {'solver':['lbfgs'], 'class_weight':[None, 'balanced'], 'C': [0.001, 0.01, 0.1, 1, 10], 'penalty':['l2']}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. log_lvl2 = LogisticRegression(random_state=seed) log_lvl2_gs = GridSearchCV(log_lvl2, log_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(log_lvl2_gs, x=X_train_final, y=y_train) log_snd_lvl = log_lvl2_gs.best_estimator_ # Logistic Regression Second Round Parameters log_pams = {'solver':['liblinear'], 'class_weight':[None], 'C': [0.005, 0.01, 0.015, 0.02], 'penalty':['l1']} # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. log_lvl2 = LogisticRegression(random_state=seed) log_lvl2_gs = GridSearchCV(log_lvl2, log_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(log_lvl2_gs, x=X_train_final, y=y_train) log_snd_lvl = log_lvl2_gs.best_estimator_ \"\"\" That's the best we can get from it. **Everything ready - let's dive into the test set!** \"\"\" \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # 6 - Test Evaluation We will be evaluating all the first level models individually and the second level Logistic Regression as well. --- ## 6.1 - First Level Models We already have our test probability predictions defined for our second level model - we just need to round it to get the predictions. \"\"\" test_predictions = round(tuned_test_pred) y_test = test['Target'] \"\"\" The function defined below plots the results in a prettier way \"\"\" def confusion_plot(y_true, pred, ax, name): ax.xaxis.set_ticks_position('top') sns.heatmap(confusion_matrix(y_test, pred), ax=ax, annot=True, square=True, cbar=False, fmt='.0f', cmap='BuGn_r', vmax=10) ax.set_title(f'{name}\\n\\nPredicted') ax.set_xlabel(f'Accuracy: {100*accuracy_score(y_test, pred):.4}% \\ \\nRecall: {100*recall_score(y_test, pred):.4}%') ax.xaxis.set_label_position('bottom') ax.xaxis.label.set_fontsize(11) for tik in ax.get_xticklines(): tik.set_visible(False) for tk in ax.get_yticklabels(): tk.set_visible(False) fig, axes = plt.subplots(1,5, figsize=(12,5), dpi=80) fig.subplots_adjust(wspace=0.3) for name, col, ax in zip(tuned_names, tuned_test_pred.columns, axes): pred = np.round(tuned_test_pred[col]) confusion_plot(y_test, pred, ax, name) for tick in axes[0].get_yticklabels(): tick.set_visible(True) axes[0].set_ylabel('True'); \"\"\" **Insights from the results:** - Even though we optimized most models for Recall, recall is still always lower than accuracy. - All our models got at least 90% recall - for this data this means 6 malignant tumors not detected - Our good old Logistic Regression performed the best, **with 95,3% malgiinant tumors detected**. We have each model's probabilities. One thing we can do is to **lower the probability threshhold** (50% is the standard). This will make us potentially lose in Accuracy but get a higher Recall. The code below lowers it to 25% (arbitrarly chosen). \"\"\" fig, axes = plt.subplots(1,5, figsize=(13,6), dpi=80) fig.subplots_adjust(wspace=0.3) for name, col, ax in zip(tuned_names, tuned_test_pred.columns, axes): pred = tuned_test_pred[col].apply(lambda x: 1 if x>=0.25 else 0) confusion_plot(y_test, pred, ax, name) for tick in axes[0].get_yticklabels(): tick.set_visible(True) axes[0].set_ylabel('True'); \"\"\" All models improved with the lower threshold, now the lowest being 93.75% Recall for KNN. SVC has an incredible **98.4% Recall and 98.2% Accuracy**! Logistic Regression is right behind with the same Recall and a lower accuracy. Those two were our best models since the beginning (Chapter 4). \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## 6.2 - Second-Level Model \"\"\" \"\"\" After an amazing score on SVC, let's see if our Second-Level Logistic Regression can beat it. \"\"\" log_snd_lvl.fit(X_train_final, y_train) second_lvl_pred = pd.Series(log_snd_lvl.predict_proba(X_test_final)[:,1]) fig, ax = plt.subplots(figsize=(5,3), dpi=80) confusion_plot(y_test, np.round(second_lvl_pred), ax, 'Second-Level Logistic Regression') for tick in ax.get_yticklabels(): tick.set_visible(True) ax.set_ylabel('True'); \"\"\" Right on target! I did not expect it to perform so well. Don't even need to change the threshold - we got a **100% Recall on test set!!** That's it for our Test Evaluations. \"\"\" \"\"\" --- \"\"\" \"\"\" --- \"\"\" \"\"\" # 7. Conclusion \"\"\" \"\"\" In **Chapter One** we started introducing this study and reading the data In **Chapter Two**, exploring our data, we've found some interesting information: - We have a few right-skewed features and some of it is explained by the above 20% error - Applying a log transformation reduced overwall skewness - There are quite a few correlated features, which is expected (e.g. radius and area) - The plots hinted us of fractal dimension being a good candidate for removal - which was confirmed on chapter three - We've also studied correlations (Chapter 2.3) and the 'Worst' features appeared to be the most important. In **Chapter Three** we've worked on a first list of models using their standard parameters. We've evaluated them on Recall and Accuracy by using cross-validation. Based on the first results we did a single round of feature selection by analysing the feature importances and then we analysed the models' errors to help us decide on which ones to keep and which ones to drop. By the end of Chapter Three we had five remaining models: Logistic Regression, SVC, Random Forest, Gradient Boosting and KNN. **Chapter Four** was all about tuning the models selected on the previous chapter to optimize the hyperparameters. **Chapter Five** sets up the data for a model stacking by predicting the probabilities for each tuned model for the training and test sets and then tunes the Second-Level model - a Logistic Regression - using the new training data. Finally, **Chapter Six** evaluates all models on the untouched test-set. For the first-level models, SVC and Logistic Regression performed best (which was already hinted on chapter three without any tuning). Lowering the threshold got a 98,5% Recall for them. With the second-level Logistic Regression we were able to reach 100% Recall! Please leave your thoughts or questions in the comments. Any feedback is welcome. If you've enjoyed it, let me know by UPVOTING! This way I will get motivated to make more Kernels for you. \"\"\" \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" # <font color='darkgreen'>Annex - A: Unbalanced Data with SMOTE <\/font> As you might recall, our dataset is unbalanced: we have more benign tumors. Having unbalanced datasets might be more difficult for your model to learn how to classifiy properly. Ideally, we would need our data with classes split evenly. There are different ways to approach this problem and I suggest you reading this <a href='https:\/\/medium.com\/james-blogs\/handling-imbalanced-data-in-classification-problems-7de598c1059f'>blog post<\/a> by Hoang Minh for an introduction to the problem and other links for further reading. The most intuitive way to deal with this is to drop some of the data from the class with most ocurrences until we have a 50-50 balance. However, we have a pretty small dataset already so that is not a good option here. If we can't lower the number of benigns, we need to increase the number of malignants and gathering more real data is not feasible - so we create synthetic data. **SMOTE** (Synthetic Minority Over-Sampling Technique) is one of the methods to do that. Roughly SMOTE looks for the location of the minority class in our feature space and creates synthetic data *between* the real data. **Put in simple words**: Say we have a 1D (only one feature) data. SMOTE finds out that there are two malignant tumors with values of 10 and 12 (e.g. radius) so it creates another malignant data point between those two, with a value of 11. Enough explaining. This is how our unbalanced dataset is at the moment: \"\"\" pd.concat([train_diag, test_diag], axis=1) \"\"\" <hr> \"\"\" \"\"\" ## <font color='darkgreen'>A.1 - Balancing the Dataset We can with a few lines of code import SMOTE and generate the new data points: \"\"\" from imblearn.over_sampling import SMOTE # I'm using 6 neighbors (the default is 5) because our KNN model optimized for this number in chapter four sm = SMOTE(k_neighbors=6, random_state=seed) X_train_res, y_train_res = sm.fit_resample(X_train, y_train) X_train_bal = pd.DataFrame(data=X_train_res, columns=X_train.columns) X_train_bal = X_train_bal.drop(ordered_ranking.index[:-6:-1], axis=1) y_train_bal = pd.Series(y_train_res, name='Target') y_train_bal.value_counts() \"\"\" <hr> \"\"\" \"\"\" ## <font color='darkgreen'>A.2 - Comparing with First Scores Let's compare our first results for all 10 models with the same process used in Chapter 3 but using the balanced dataset. \"\"\" train_size = X_train_bal.shape[0] n_models = len(first_models) oof_pred = np.zeros((train_size, n_models)) scores = [] for n, model in enumerate(first_models): model_pipeline = Pipeline(steps=[('Scaler', std_sca), ('Estimator', model)]) accuracy = np.zeros(n_folds) recall = np.zeros(n_folds) for i, (train_ix, val_ix) in enumerate(skf.split(X_train_bal, y_train_bal)): x_tr, y_tr = X_train_bal.iloc[train_ix], y_train_bal.iloc[train_ix] x_val, y_val = X_train_bal.iloc[val_ix], y_train_bal.iloc[val_ix] model_pipeline.fit(x_tr, y_tr) val_pred = model_pipeline.predict(x_val) oof_pred[val_ix, n] = model_pipeline.predict_proba(x_val)[:,1] fold_acc = accuracy_score(y_val, val_pred) fold_rec = recall_score(y_val, val_pred) accuracy[i] = fold_acc recall[i] = fold_rec scores.append({'Accuracy' : accuracy.mean(), 'Recall' : recall.mean()}) measure_cols = ['Accuracy', 'Recall']#, 'Accuracy Std.Dev.', 'Recall Std.Dev.'] balanced_scores = pd.DataFrame(columns=measure_cols) for name, score in zip(first_model_names, scores): new_row = pd.Series(data=score, name=name) balanced_scores = balanced_scores.append(new_row) balanced_scores = balanced_scores.sort_values('Recall', ascending=False) d={'First Scores':first_scores, 'Rebalanced Classes':balanced_scores} pd.concat(d, axis=1, sort=False) \"\"\" We can see and overall improvement in Recall for all models. **This might be misleading because the synthetic samples are 'easy ones'. Our test scores will say if we improved or not.** For speed, we are going to continue with just two first-level models for tuning and test evaluation: Logistic Regression and KNN. \"\"\" \"\"\" <hr> \"\"\" \"\"\" ## <font color='darkgreen'>A.3 - Model Tuning Doing a single round of tuning with the same starting parameters used in chapter four. \"\"\" # Logistic Regression Initial Parameters log_pams = [{'M__solver':['liblinear'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, 100, 200], 'M__penalty':['l1', 'l2'], 'L__apply_log':[True, False]}, {'M__solver':['lbfgs'], 'M__class_weight':[None, 'balanced'], 'M__C': [0.001, 0.01, 0.1, 1, 10, 100, 200], 'M__penalty':['l2'], 'L__apply_log':[True, False]}] # It is important to apply the log transformer before the scaling otherwise we will always get 'number near 0' error. log_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', logreg)]) log_gs = GridSearchCV(log_pipe, log_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(log_gs, x=X_train_bal, y=y_train_bal) log_balanced = log_gs.best_estimator_ knn_pams = {'M__n_neighbors':np.arange(2, 10), 'M__weights':['uniform', 'distance'], 'M__p':[1, 2, 3], 'L__apply_log':[False, True]} # It is important to apply the log transformer before the scaling knn_pipe = Pipeline(steps=[('L', logger), ('S', std_sca), ('M', knn)]) knn_gs = GridSearchCV(knn_pipe, knn_pams, scoring='recall', cv=skf, n_jobs=-1, iid=False) train_gridsearch(knn_gs, x=X_train_bal, y=y_train_bal) knn_balanced = knn_gs.best_estimator_ \"\"\" <hr> \"\"\" \"\"\" ## <font color='darkgreen'>A.4 - Test Scores \"\"\" bal_names = ['Logistic Regression', 'K-Nearest Neighbors'] bal_models = [log_balanced, knn_balanced] fig, axes = plt.subplots(1,2, figsize=(7,4), dpi=80) fig.subplots_adjust(wspace=0.3) for name, mod, ax in zip(bal_names, bal_models, axes): pred = mod.predict(X_test_v2) confusion_plot(y_test, pred, ax, name) for tick in axes[0].get_yticklabels(): tick.set_visible(True) axes[0].set_ylabel('True'); \"\"\" Not great. Let's try reducing the threshold like we did in Chapter 6. \"\"\" fig, axes = plt.subplots(1,2, figsize=(7,4), dpi=80) fig.subplots_adjust(wspace=0.3) for name, mod, ax in zip(bal_names, bal_models, axes): pred = pd.Series(mod.predict_proba(X_test_v2)[:,1]).apply(lambda x: 1 if x>=0.25 else 0) confusion_plot(y_test, pred, ax, name) for tick in axes[0].get_yticklabels(): tick.set_visible(True) axes[0].set_ylabel('True'); \"\"\" **Conclusions**: - We were able to succesfully rebalance our dataset using SMOTE - However, the improvement on the training scores didn't manifest in the test scores. The models used in chapter 6 had better scores. - Many models already have a tool to deal with unbalanced datasets - such as the 'class_weight' parameter. In this dataset, creating synthetic samples wasn't useful. \"\"\" \"\"\" <hr> \"\"\" \"\"\" <hr> \"\"\" \"\"\" #","meta":"{'source': 'AI4Code', 'id': '22badb9788e047'}"}
{"id":"59068","text":"\"\"\"\n\u201cI confirm that this is my own work, except where clearly indicated.\u201d\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport os\nimport numpy as np \nfrom scipy.stats import norm \nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nimport plotly.express as px\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport plotly\nplotly.offline.init_notebook_mode() # For not show up chart error\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\n%matplotlib inline\nfrom tqdm import tqdm\n\npd.set_option('display.max_columns', 100)\n# Loading the data\ntrain = pd.read_csv('..\/input\/train-3\/train_3.csv')\ntest = pd.read_csv('..\/input\/test-3\/test_3.csv')\n\n\"\"\"\nBefore proceeding with the analysis, let's first make sure that there are no duplicate observations.\n\"\"\"\n\"\"\"\n## Data at first sight\n\"\"\"\n\"\"\"\nHere is an excerpt of the the data description for the competition:\n\n* Values of -1 indicate that the feature was missing from the observation.\n* We are after 2 outputs from the model we are going to build: ConfirmedCases and Fatalities. These columns are labeld as inter later on\n\nOk, that's important information to get us started. Let's have a quick look at the first and last rows to confirm all of this.\n\n\"\"\"\n# Projecting the first 5 rows\ntrain.head()\ntrain.tail()\n# Checking the dimensions\ntrain.shape\n\"\"\"\nLet's see if there are any duplicate observations in the training set.\n\"\"\"\n# Dropping duplicates\ntrain.drop_duplicates()\n\n# Checking the dimensions again\ntrain.shape\n\"\"\"\nNo duplicates. Let's make sure that test set has the dimensions that is suppose to have\n\"\"\"\n# Checking \ntest.shape\n\"\"\"\nWe are missing 2 variables but these are the columns that we are after, so we are good. Next, let's take a first look at the data types in the training set.\n\"\"\"\ntrain.info()\n\"\"\"\nThere are quite a few interval data as denoted by the data type **int64** and **float64**. There are also some categorical as denoted by the dtype **object**. This implies that later on we shall create dummy variables as we will see below. But first, let's turn object variables to category to let python know that these are categorical variables. \n\"\"\"\n# Setting categorical variables for training set\ntrain['continent'] = train['continent'].astype('category')\ntrain['country_code'] = train['country_code'].astype('category')\ntrain['Country_Region'] = train['Country_Region'].astype('category')\n\n# Setting categorical variables for test set\ntest['continent'] = test['continent'].astype('category')\ntest['country_code'] = test['country_code'].astype('category')\ntest['Country_Region'] = test['Country_Region'].astype('category')\n\n\"\"\"\n## Data Management\n\nTo facilitate the data management, we'll store meta-information about the variables in a DataFrame. The method for the preparation of meta-data is mainly inspired from Bert Careman's kernel from another competition https:\/\/www.kaggle.com\/bertcarremans\/data-preparation-exploration. It's great how we can learn new things via participating in competitions such as Kaggle. \n\nSo all kudos for the technique of data management seen here go to Bert.\n\"\"\"\n\"\"\"\nAs for the the meta data, the structure is will be as follows:\n\n**role**: input, ID, ConfirmedCases, Fatalities\n\n**level**: nominal, interval, ordinal keep: True or False dtype: int, float, str\n\n**keep**: True or False\n\n**dtype**: int, float, str\n\"\"\"\n# Creating the meta data\n\n\n## Something to store information\ndata = []\n\n## Creating a loop\nfor f in train.columns:\n    \n    # Defining the role for each variable\n    if f == 'ConfirmedCases':\n        role = 'ConfirmedCases'\n    elif f == 'Fatalities':\n        role = 'Fatalities'\n    elif f == 'Id':\n        role = 'Id'\n    elif f == 'Date':\n        role = 'Date'\n    else:\n        role = 'input'\n         \n    # Defining the level\n    if 'int' in f or f == 'ConfirmedCases':\n        level = 'inter'\n    elif 'int' in f or f == 'Fatalities':\n        level = 'inter'\n    elif 'int' in f or f == 'population':\n        level = 'interval'\n    elif 'cat' in f or f == 'continent':\n        level = 'nominal'\n    elif 'cat' in f or f == 'country_code':\n        level = 'nominal'\n    elif 'cat' in f or f == 'Country_Region':\n        level = 'nominal'\n    elif 'cat' in f or f == 'Id':\n        level = 'nominal'\n    elif train[f].dtype == float:\n        level = 'interval'\n    elif train[f].dtype == int:\n        level = 'interval'\n    elif train[f].dtype == 'object':\n        level = 'ordinal'\n\n        \n    # Initialize keep to True for all variables except for id\n    keep = True\n    if f == 'Id':\n        keep = False\n    \n    # Defining the data type \n    dtype = train[f].dtype\n    \n    # Creating a Dict that contains all the metadata for the variable\n    f_dict = {\n        'varname': f,\n        'role': role,\n        'level': level,\n        'keep': keep,\n        'dtype': dtype\n    }\n    data.append(f_dict)\n    \n#Saving the meta-train data\nmeta = pd.DataFrame(data, columns=['varname', 'role', 'level', 'keep', 'dtype'])\nmeta.set_index('varname', inplace=True)\n\n# Saving the meta-test data\nmeta_test = pd.DataFrame(data, columns=['varname', 'role', 'level', 'keep', 'dtype'])\nmeta_test.set_index('varname', inplace=True)\n\"\"\"\nBelow the number of variables per role and level are displayed.\n\"\"\"\n meta\n\"\"\"\nHere is also a more consise version of the data types in the data set\n\"\"\"\npd.DataFrame({'count' : meta.groupby(['role', 'level'])['role'].size()}).reset_index()\n\"\"\"\nLet's also look at the test set. This also helps verify that everything is okay with the test set as well.\n\"\"\"\npd.DataFrame({'count' : meta_test.groupby(['role', 'level'])['role'].size()}).reset_index()\n\"\"\"\nGreat. Everything seem to be working fine. Let's proceed with the analysis\n\"\"\"\n\"\"\"\n## Descriptive statistics\n\"\"\"\n\"\"\"\n### Interval Data\n\"\"\"\n\"\"\"\nLet's start via looking at the distribution of the interval data first.\n\"\"\"\n# Calling the interval data\nv = meta[(meta.level == 'interval') & (meta.keep)].index\ntrain[v].describe()\n\"\"\"\nFirst, it seems that the distributions of the variables in the dataset differ quite significantly. More precisely, the mean and the  standard deviation differs by large across variables. Also min and max are quite volatile as well. This suggests the need to scale the variables later on. \n\nIt is also clear that we have missing values (denoted by -1) in quite a few of the columns in the dataset. \n\nLet's see the quality of the data, how many values are missing from each variable.\n\"\"\"\n# Initiating an empty vector to store information\nvars_with_missing = []\n\n# Going through every column in the interval data and calculating how many missing values we have\nfor f in train.columns:\n    missings = train[train[f] == -1][f].count()\n    if missings > 0:\n        vars_with_missing.append(f)\n        missings_perc = missings\/train.shape[0]\n        \n        print('Variable {} has {} records ({:.2%}) with missing values'.format(f, missings, missings_perc))\n        \nprint('In total, there are {} variables with missing values'.format(len(vars_with_missing)))\n\"\"\"\nWe have approximately 1% of observations missing from each column. Since I was the one who compiled information from various sources, I knew this already. One of the countries\/regions in the given sets is the cruise ship \"Diamond Princess\" which obviously doesn't have any demographic information as a region as the rest of the countries\/regions. There are also a couple other countries mainly from Africa for which the WHO did not have any available demographic information however, these observations do not constitute a large number of the observations. Hence, I decide to leave these observations untouched for now.\n\"\"\"\n\"\"\"\n### Nominal Data\n\nLet's look at the nominal data next. Let's start with the cardinality.\u00b6\n\n\"\"\"\n# Calling the nominal data\nv = meta[(meta.level == 'nominal') & (meta.keep)].index\ntrain[v].describe()\n\"\"\"\nQuick observations:\n\n* 188 distinct _**Country_Code**_ values\n* 173 distinct _**Country_Region**_ values\n* 5 distinct _**Continent**_ values\n* America seems to be the continent with the most observations in the dataset. More precisely, America seems to capture appx 33% of the total observations.\n\nThe fact that we have fewer **Country_Region** values steams from that we have some Provinces included in country_code and have their own distinct country code.\n\"\"\"\n\"\"\"\n## Exploratory Data Visualization\n\"\"\"\n\"\"\"\n### Nominal\n\nLet's visualise the Confirmed cases and Fatalities per Country\/Region. \n\nThe code for this visualization comes from the Kee's kernel found in this link https:\/\/www.kaggle.com\/keedong\/covid19-exponential-model2-kee\n\n\"\"\"\ndf_now = train.groupby(['Date','Country_Region']).sum().sort_values(['Country_Region','Date']).reset_index()\ndf_now['New Cases'] = df_now['ConfirmedCases'].diff()\ndf_now['New Fatalities'] = df_now['Fatalities'].diff()\ndf_now = df_now.groupby('Country_Region').apply(lambda group: group.iloc[-1:]).reset_index(drop = True)\n\n\ndf_now = df_now.sort_values('ConfirmedCases', ascending = False)\nfig = make_subplots(rows = 2, cols = 2)\nfig.add_bar(x=df_now['Country_Region'].head(10), y = df_now['ConfirmedCases'].head(10), row=1, col=1, name = 'Total cases')\n\ndf_now = df_now.sort_values('Fatalities', ascending=False)\nfig.add_bar(x=df_now['Country_Region'].head(10), y = df_now['Fatalities'].head(10), row=1, col=2, name = 'Total Fatalities')\n\"\"\"\nTotal cases in the US are most than any other country in the world. In fatalities however, Italy has the most followed by Spain.\n\"\"\"\n# Calling the nominal data\nv = meta[(meta.level == 'nominal') & (meta.keep)].index\n\nfor f in v:\n    plt.figure()\n    fig, ax = plt.subplots(figsize=(20,10))\n    \n     # Calculate the Fatalities per category value\n    cat_perc = train[[f, 'Fatalities']].groupby([f],as_index=False).mean()\n    cat_perc.sort_values(by='Fatalities', ascending=False, inplace=True)\n    \n    # Bar plot\n    # Order the bars descending on target mean\n    sns.barplot(ax=ax, x=f, y='Fatalities', data=cat_perc, order=cat_perc[f])\n    plt.ylabel('Fatalities', fontsize=18)\n    plt.xlabel(f, fontsize=18)\n    plt.tick_params(axis='both', which='major', labelsize=18)\n    plt.show();\n\"\"\"\nIt appears that Confirmed cases in Asia top the confirmed cases anywhere else but the Fatalities are more severe in Europe. As we saw above Italy and Spain play a major role to that.\n\"\"\"\n\"\"\"\n### Interval\n\"\"\"\nv = meta[(meta.level == 'interval') & (meta.keep)].index\n\nfor f in v:\n    plt.figure()\n    fig, ax = plt.subplots(figsize=(20,10))\n    \n    # Calculate the percentage of target=1 per category value\n    cat_perc = train[[f, 'ConfirmedCases']].groupby([f],as_index=False).mean()\n    cat_perc.sort_values(by='ConfirmedCases', ascending=False, inplace=True)\n    \n    # Bar plot\n    # Order the bars descending on target mean\n    sns.barplot(ax=ax, x=f, y='ConfirmedCases', data=cat_perc, order=cat_perc[f])\n    plt.ylabel('ConfirmedCases', fontsize=18)\n    plt.xlabel(f, fontsize=18)\n    plt.tick_params(axis='both', which='major', labelsize=18)\n    plt.show();\n\"\"\"\nWe confirm our observation from the descriptive statistics part above that interval variables' distribution vary substantially across the board. We can also see here that the data seem to be right skewed, meaning we have some high potive values. \n\"\"\"\n# Correlation matrix\ncorrmat = train.corr() \n  \n# Creating the plot\ncg = sns.clustermap(corrmat, cmap =\"YlGnBu\", linewidths = 0.1); \nplt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation = 0) \n  \ncg \n# ConfirmedCases correlation matrix \n# k : number of variables for heatmap \nk = 30\n  \ncols = corrmat.nlargest(k, 'ConfirmedCases')['ConfirmedCases'].index \n  \ncm = np.corrcoef(train[cols].values.T) \nf, ax = plt.subplots(figsize =(12, 10)) \n  \nsns.heatmap(cm, ax = ax, cmap =\"binary\", \n            linewidths = 0.1, yticklabels = cols.values,  \n                              xticklabels = cols.values) \n\"\"\"\nClearly, there are high correlations amongst some variables. Will let the algorithm further below handle this when we are dealing with feature selection. \n\"\"\"\n\"\"\"\n ## Feature Engineering\n\"\"\"\n\"\"\"\n### Creating dummy variables\u00b6\n\"\"\"\n\"\"\"\nThe values of the categorical variables do not represent any order or magnitude. For instance, category 2 is not twice the value of category 1. Therefore we can create dummy variables to deal with that. We drop the first dummy variable as this information can be derived from the other dummy variables generated for the categories of the original variable.\n\"\"\"\n# Calling the nominal data\nv = meta[(meta.level == 'nominal') & (meta.keep)].index\nprint('Before dummification we have {} variables in train'.format(train.shape[1]))\ntrain = pd.get_dummies(train, columns=v, drop_first=True)\nprint('After dummification we have {} variables in train'.format(train.shape[1]))\n\"\"\"\nDoing the same thing for test set.\n\"\"\"\n# Calling the nominal data\nv = meta_test[(meta_test.level == 'nominal') & (meta_test.keep)].index\nprint('Before dummification we have {} variables in train'.format(test.shape[1]))\ntest = pd.get_dummies(test, columns=v, drop_first=True)\nprint('After dummification we have {} variables in train'.format(test.shape[1]))\n\"\"\"\nNext, we raise the interval variables to **polynomial degree=2** and create interactions between variables. Thanks to the get_feature_names method we can assign column names to these new variables.\n\"\"\"\n# Calling the interval data\nv = meta[(meta.level == 'interval') & (meta.keep)].index\npoly = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)\n\n# Creating the df with the interactions\ninteractions = pd.DataFrame(data=poly.fit_transform(train[v]), columns=poly.get_feature_names(v))\ninteractions.drop(v, axis=1, inplace=True)  # Remove the original columns\n\n# Concat the interaction variables to the train data\nprint('Before creating interactions we have {} variables in train'.format(train.shape[1]))\ntrain = pd.concat([train, interactions], axis=1)\nprint('After creating interactions we have {} variables in train'.format(train.shape[1]))\n\"\"\"\nApplying the same technique to the test set.\n\"\"\"\n# Calling the interval data\nv = meta_test[(meta_test.level == 'interval') & (meta_test.keep)].index\npoly = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)\n\n# Creating the df with the interactions\ninteractions = pd.DataFrame(data=poly.fit_transform(test[v]), columns=poly.get_feature_names(v))\ninteractions.drop(v, axis=1, inplace=True)  # Remove the original columns\n\n# Concat the interaction variables to the train data\nprint('Before creating interactions we have {} variables in train'.format(test.shape[1]))\ntest = pd.concat([test, interactions], axis=1)\nprint('After creating interactions we have {} variables in train'.format(test.shape[1]))\n\"\"\"\nMaking sure that the dataset contains no NA values.\n\"\"\"\n# Dropping NA values\ntrain = train.dropna()\n\n# Verifying that no N\/A values exist\ntrain.isnull().sum().sum()\n\"\"\"\nNo NA values. Let's move on with Feature selection.\n\"\"\"\n\"\"\"\n## Feature selection\u00b6\n\nPersonally, I prefer to let the classifier algorithm chose which features to keep as i find it more robust. Here we use RandomForest to do the job. But there is one thing that we can do ourselves. That is removing features with no or a very low variance. Sklearn has a handy method to do that; VarianceThreshold\n\"\"\"\n\"\"\"\n### VarianceThreshold\n\nBy default it removes features with zero variance. This will be really helpful here as we will see below that there are quite a few zero-variance variables. If we choose to remove features with less than 1% variance, we remove 346 variables as seen below.\n\"\"\"\n# Setting the variance threshold\nselector = VarianceThreshold(threshold=.01)\nselector.fit(train.drop(['Id', 'ConfirmedCases','Fatalities','Date'], axis=1)) # Fit to train without the variables we need for submitting\n\nf = np.vectorize(lambda x : not x) # Function to toggle boolean array elements\n\n# finding variables with lower variance than threshold\nv = train.drop(['Id', 'ConfirmedCases','Fatalities','Date'], axis=1).columns[f(selector.get_support())]\nprint('{} variables have too low variance.'.format(len(v)))\n\"\"\"\nTraining the RandomForest.\n\"\"\"\n# Getting the train and labels\nX_train = train.drop(['Id', 'ConfirmedCases','Fatalities','Date'], axis=1)\ny_train = train['Fatalities']\n\n# Getting the columns\nfeat_labels = X_train.columns\n\n# Fitting a Random Forest Classifier\nrf = RandomForestClassifier(n_estimators=1000, random_state=0, n_jobs=-1)\n\nrf.fit(X_train, y_train)\n\n# Getting the importances calculated from the RFC\nimportances = rf.feature_importances_\n\n# Sorting the variables by importance\nindices = np.argsort(rf.feature_importances_)[::-1]\n\n# Creating a loop that is going to show the importances per variable ranked from most important to less important\nfor f in range(20):\n    print(\"%2d) %-*s %f\" % (f + 1, 30,feat_labels[indices[f]], importances[indices[f]]))\n# Setting the threshold for which variables to keep based on their variance contribution\nsfm = SelectFromModel(rf, threshold='median', prefit=True)\nprint('Number of features before selection: {}'.format(X_train.shape[1]))\n\n# Throwing away all the variables which fall below the threshold level specified above\nn_features = sfm.transform(X_train).shape[1]\nprint('Number of features after selection: {}'.format(n_features))\n\n# Creating a list with the selected variables\nselected_vars = list(feat_labels[sfm.get_support()])\n# Forming the final training set based on the feature selection \ntrain = train[selected_vars + ['ConfirmedCases','Fatalities','Date']]\n\n# Applying the selected variables to the test set as well\ntest = test[selected_vars + ['Date']]\n\ntrain_copy = train\ntest_copy = test\n\"\"\"\n## Feature normalization\n\nIn the last step prior to fitting a model, there are 2 things that remain to be done:\n1. Encode the **Date** variable\n2. Scale all numerical variables\n\nThe problem with the former is that the training set and the test set have a different number of observations and different dates in each set. Thus, if we try to apply the **OneHotEncoder** this leads to different size of columns for the two sets which wouldn't work for modelling since we want both datasets to have the same exact columns to be able to predict. A get around technique is applied to make the 2 column sets equal.\n\"\"\"\n# Creating a copy of the training and test sets\ntrain_unscaled = train_copy\ntest_unscaled = test_copy\n\"\"\"\nBefore proceeding with encoding, we split the training set to training and validation sets using **Stratified Sampling** based on the population column which as we saw earlier is skewed. \n\"\"\"\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit( n_splits = 1, test_size = 0.2)\nfor train_index, test_index in split.split(train_unscaled, train_unscaled[\"population\"]):\n    train_strat = train_unscaled.loc[train_index]\n    valid_strat = train_unscaled.loc[test_index]\n\ny_train = train_strat[['ConfirmedCases','Fatalities']]\nx_train = train_strat.drop(['ConfirmedCases','Fatalities'], axis=1)\n\ny_valid = valid_strat[['ConfirmedCases','Fatalities']]\nx_valid = valid_strat.drop(['ConfirmedCases','Fatalities'], axis=1)\n# Creating copies of the datasets\ntrain_1 = x_train\ntest_1 = test_unscaled\nvalid1 = x_valid\n## Start encoding\n\n## Assigning distinct numbers to every set\ntrain_1['train_1']=2\nvalid1['train_1']=1\ntest_1['train_1']=0\n\n## Combining the 3 sets\ncombined = pd.concat([train_1, valid1, test_1])\n\n# Getting dummies from the combined dataset\ndf = pd.get_dummies(combined['Date'])\n\n# Concatinating the dummy set with the combined set\ncombined = pd.concat([combined,df], axis = 1)\n\n## Forming the 3 sets using the distinct numbers that we initially set.\ntrain_df = combined[combined[\"train_1\"]== 2]\nvalid_df = combined[combined[\"train_1\"]== 1]\ntest_df = combined[combined[\"train_1\"]==0]\n\n# Forming the end sets\ntrain_df.drop([\"train_1\"], axis = 1, inplace = True)\nvalid_df.drop([\"train_1\"], axis = 1, inplace = True)\ntest_df.drop([\"train_1\"], axis = 1, inplace = True)\n\"\"\"\nOkay, now we are ready to encode the categorical variables (**Date**) and standardise the data. Doing both at the same time for all three sets (x_train, x_valid, test) using the handy tool called **pipeline** .\n\"\"\"\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Splitting between numerical and other variables\ntrain_num = train_df.select_dtypes(include=[\"number\"])\ntrain_cat = train_df.select_dtypes(exclude=[\"number\"])\n\n# Creating a pipeline\nnum_pipeline = Pipeline([\n    ('std_scaler', StandardScaler()),\n])\n\n## Getting the numerical and categorical variables\nnum_attribs = list(train_num)\ncat_attribs = list(train_cat)\n\nfull_pipeline = ColumnTransformer([\n    (\"num\", num_pipeline, num_attribs),\n])\n\n# Applying the transformation\nx_train = full_pipeline.fit_transform(train_df)\nx_valid = full_pipeline.fit_transform(valid_df)\ntest_pip = full_pipeline.fit_transform(test_df)\ntest_df\ntest_pip.shape\n\"\"\"\n# Model Fitting\n\n## Model 1 - Decision Tree Regressor\n\nStarting the model fitting part wih a **DecisionTreeRegressor**. DecisionTreeRegressor is one the most powerful algorithms there are, mainly because of its ability to fit both parametric and non-parametric data. \n\nWhile fitting the model, will use 10-fold cross-validation with 3 repeats. As a performance metric, I use **Root Mean Squared Log Error** as required from the competition.\n\"\"\"\nfrom numpy import absolute\nfrom numpy import mean\nfrom sklearn.metrics import mean_squared_log_error\nfrom numpy import std\nfrom sklearn.datasets import make_regression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedKFold\nfrom sklearn.metrics import  make_scorer\n\nnp.random.seed(9)\n# Creating the mean squared log error metric to let Scikit library use it in cross-validation\nscorer = make_scorer(mean_squared_log_error, greater_is_better=False)\n\n# define model\nmodel = DecisionTreeRegressor()\n\n# evaluate model\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\nn_scores = cross_val_score(model, x_train, y_train, scoring= scorer, cv=cv, n_jobs=1)\n\n# summarize performance\nn_scores = absolute(n_scores)\nn_scores = np.sqrt(n_scores)\nprint('Result: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))\n\"\"\"\nThe model performed well. Let's evaluate it on the validation set.\n\"\"\"\nnp.random.seed(15)\n\n# Fitting the model on the training set\nmodel.fit(x_train,y_train)\n\n# Getting the predictions\ny_pred = model.predict(x_valid)\n\n# Calculating the loss\nloss = np.sqrt(mean_squared_log_error( y_valid, y_pred ))\nprint(loss)\n\"\"\"\n## Model 2 - Deep Neural Network using Dropout\n\nA Neural network model can be a good option for the purposes of this competition. The algorithm is extremely useful in finding patterns that are too complex for being manually extracted and taught to recognize to the machine. So let\u2019s fit a simple DNN with a small dropout rate.\n\nFor activation function in the hidden layers, **selu** is being used in order to avoid the **vanishing\/exploding gradients** problem. For further explanation about the vanishing\/exploding gradients problem feel free to see to this article https:\/\/www.semanticscholar.org\/paper\/Understanding-the-exploding-gradient-problem-Pascanu-Mikolov\/c5145b1d15fea9340840cc8bb6f0e46e8934827f. \n\nUsing selu as activation functions also leads to self-regularization which is good. Since we are using selu activation, one of the conditions for selu to work is to use **LeCun initialization**. For further information about selu activation function feel free to read this article https:\/\/arxiv.org\/pdf\/1804.02763.pdf\n\nAs for the output layer, **Relu** is being used in order ensure we only get positive values. Lastly, I am adding a **Learning Scheduler**, namely **ReduceOnPlateu**, to help improve the learning rate of the algorithm when the validation loss does not improve after 5 rounds.\n\"\"\"\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import KFold\nfrom tensorflow import keras\nimport tensorflow as tf\nimport pandas as pd\n\n\n# Adding early stopping rules, checkpoint rules and Learning scheduling to improve the learning rate.\ncheckpoint_cb = keras.callbacks.ModelCheckpoint(\"keras_model_assign_2.h5\",save_best_only = True) # making sure the model is saved at every epoch and we are saving the best weights\nearly_stopping_cb = keras.callbacks.EarlyStopping( patience = 10, restore_best_weights=True) # Early stopping rule while preserving best weights\nlr_scheduler = keras.callbacks.ReduceLROnPlateau(factor = 0.5, patience=5) # reduces the learning rate by 0.5 when the validation score doesn't improve for 5 rounds\n\noptimizer = keras.optimizers.SGD(lr= 0.001, momentum = 0.9, nesterov=True) #adding an optimization parameter to improve learning rate\n\n\n####################\n###################\nseed = 7\ncvscores = []\n\n# Converting the train set to array for indexing\nX = np.array(x_train)\nY = np.array(y_train)\n\nX_valid = np.array(x_valid)\nY_valid = np.array(y_valid)\n\nnp.random.seed(seed)\n# define 5-fold cross validation test harness\nkfold = KFold(5, True, 1)\n\nfor train, test in kfold.split(X, Y):\n  # create model\n    model2 = tf.keras.models.Sequential([\n    keras.layers.Flatten(input_shape = x_train.shape[1:]),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(100,activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(50, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dropout(rate = 0.1),\n    keras.layers.Dense(2, activation = \"relu\", kernel_initializer = \"he_normal\")\n    ])\n    \n    # Compiling the model\n    model2.compile(loss=\"mean_squared_logarithmic_error\",\n             optimizer = optimizer)\n    \n    # Fitting the model\n    history_2 = model2.fit(X[train], Y[train],epochs=200, verbose=0,\n                        validation_data = (X_valid, Y_valid),\n                        callbacks = [checkpoint_cb, early_stopping_cb, lr_scheduler])\n    \n    # Evaluating the model\n    y_pred = model2.predict(X[test])\n    loss = np.sqrt(mean_squared_log_error( Y[test], y_pred ))\n    cvscores.append(loss)\n    \nprint(\"Scores:\",cvscores)\nprint(\"Mean:\",np.mean(cvscores))\nprint(\"Standard Deviation:\",np.std(cvscores))\n\"\"\"\nLooking at the scores from every iteration, it appears that as the trainng set is shuffled in each iteration, the performance of the model deteriorates.\n\"\"\"\n\"\"\"\n# Model 3 - DNN using MC Dropout\n\nInstead of using Dropout, let's try and use Monte Carlo Dropout. MC Dropout attempts to mitigate the problem of representing model uncertainty without sacrificing either computational complexity or test accuracy so let's give it a try.\n\"\"\"\ncheckpoint_cb_2 = keras.callbacks.ModelCheckpoint(\"keras_model2_assign_2.h5\",\n                                               save_best_only = True) # making sure the model is saved at every epoch\n\n\n# defining Monte Carlo Dropout layers\nclass MCDropout(keras.layers.Dropout):\n    def call (self,inputs):\n        return super().call(inputs, training = True)\n\n################\n################\nseed = 7\ncvscores = []\nnp.random.seed(seed)\n\n# define 5-fold cross validation test harness\nkfold = KFold(5, True, 1)\n\n# Initiating K-Fold Cross-Validation while fitting the model\nfor train, test in kfold.split(X, Y):\n  # create model\n    model3 = tf.keras.models.Sequential([\n    keras.layers.Flatten(input_shape = x_train.shape[1:]),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(100,activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.Dense(50, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    MCDropout(rate =0.1),\n    keras.layers.Dense(2, activation = \"relu\", kernel_initializer = \"he_normal\")\n    ])\n    \n    # Compiling the model\n    model3.compile(loss=\"mean_squared_logarithmic_error\",\n             optimizer = optimizer)\n    \n    # Fitting the model\n    history_3 = model3.fit(X[train], Y[train],epochs=200,verbose=0, \n                        validation_data = (X_valid, Y_valid),\n                        callbacks = [early_stopping_cb,checkpoint_cb_2, lr_scheduler])\n    \n    # Evaluating the model\n    y_pred = model3.predict(X[test])\n    loss = np.sqrt(mean_squared_log_error( Y[test], y_pred ))\n    cvscores.append(loss)\n    \nprint(\"Scores:\",cvscores)\nprint(\"Mean:\",np.mean(cvscores))\nprint(\"Standard Deviation:\",np.std(cvscores))\n\"\"\"\nAdding a MCDropout layer improved the model's performance however the same problem with the first model persists. Let's fit a model that requires less tuning of hypermarameters and see how it performs.\n\"\"\"\n\"\"\"\n# Model 4 - DNN using Batch Normalisation\n\nBatch Normalization makes the networks much less sensitive to the weight initialization. The drawback is that we are adding extra computation at each layer which makes the model slower to converge and predict. Also, I choose to retain the Monte Carlo Dropout layer since it appears to improve the performance.\n\"\"\"\n# Creating a new checkpoint for a new model\ncheckpoint_3_cb = keras.callbacks.ModelCheckpoint(\"keras_model3_assign_2.h5\",\n                                               save_best_only = True) # making sure the model is saved at every epoch\n\n# Setting the model\n################\n################\nseed = 7\ncvscores = []\nnp.random.seed(seed)\n\n# define 5-fold cross validation test harness\nkfold = KFold(5, True, 1)\n\n# Initiating K-Fold Cross-Validation while fitting the model\nfor train, test in kfold.split(X, Y):\n  # create model\n    model_4 = keras.models.Sequential([\n    keras.layers.Flatten(input_shape = x_train.shape[1:]),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.BatchNormalization(),\n    keras.layers.Activation(\"selu\"),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.BatchNormalization(),\n    keras.layers.Activation(\"selu\"),\n    keras.layers.Dense(100, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.BatchNormalization(),\n    keras.layers.Activation(\"selu\"),\n    keras.layers.Dense(50, activation = \"selu\", kernel_initializer = \"lecun_normal\"),\n    keras.layers.BatchNormalization(),\n    keras.layers.Activation(\"selu\"),\n    MCDropout(rate =0.15),\n    keras.layers.Dense(2, activation = \"relu\", kernel_initializer = \"he_normal\")\n])\n\n    # Compiling the model\n    model_4.compile(loss=\"mean_squared_logarithmic_error\",\n             optimizer = optimizer)\n    \n    # Fit the model\n    history_4 = model_4.fit(X[train], Y[train],epochs=200, verbose=0,\n                        validation_data = (X_valid, Y_valid),\n                        callbacks = [early_stopping_cb, checkpoint_3_cb, lr_scheduler])\n    \n    # evaluate the model\n    y_pred = model_4.predict(X[test])\n    loss = np.sqrt(mean_squared_log_error( Y[test], y_pred ))\n    cvscores.append(loss)\n    \nprint(\"Scores:\",cvscores)\nprint(\"Mean:\",np.mean(cvscores))\nprint(\"Standard Deviation:\",np.std(cvscores))\n\"\"\"\n# Fine Tuning\n\nThe better two models in terms of performance on the validation set are the **DecisionTreeClassifier** and the **DNN with Dropout layer** (model2). To decide which one to use, let's optimize the Decision Tree Classifier using **RandomizedSearchCV** and test them both again on the validation set. \n\nThrough trial and error, I found that **sample_split** above 50 leads to overfit so I limit this variable to 50. I also set **max_depth** to 90:155 again because through trial and error values between 90:155 lead to smaller generalization error.\n\"\"\"\nfrom scipy.stats import reciprocal \nfrom sklearn.model_selection import RandomizedSearchCV\n\n\nsamples_split = range(25,50)\nmax_depth = range(90,155)\n\nparameters={'min_samples_split': samples_split,\n            'max_depth': max_depth}\nseed = 7\nrnd_search_cv = RandomizedSearchCV(model, \n                                   parameters, \n                                   n_iter = 100, \n                                   cv=3, \n                                   scoring = scorer, \n                                   random_state=0)\n\nrnd_search_cv.fit(x_train, y_train)\n\"\"\"\nLet's see which values were trialled during Randomized Search CV.\n\"\"\"\n# Collecting the results\ncvres = rnd_search_cv.cv_results_\n\n# Creating a loop that goes through the values tested and their associated scores\nfor mean_score, params in zip(-cvres[\"mean_test_score\"], cvres[\"params\"]):\n    print(mean_score,params)\n## Best parameters from optimization\nrnd_search_cv.best_params_\n\"\"\"\nLet's compare.\n\"\"\"\n# Forming the final model\noptimized_dtc = rnd_search_cv.best_estimator_\n\n# Getting predictions\nopti_dtc_final_predictions = optimized_dtc.predict(x_valid)\nmodel2_final_predictions = model2.predict(x_valid)\n\ndtc_loss = np.sqrt(mean_squared_log_error( y_valid, opti_dtc_final_predictions ))\nmodel2_loss = np.sqrt(mean_squared_log_error( y_valid, model2_final_predictions ))\n    \nprint(\"DTC Score:\",dtc_loss)\nprint(\"DNN Score:\",model2_loss)\n\"\"\"\nThe Optimized Decision Tree Classifier performs better, hence this will be the final model.\n\"\"\"\n\"\"\"\n## Output\n\nAll done, creating the output file.\n\"\"\"\n# Getting predictions\nfinal_predictions = optimized_dtc.predict(test_pip)\n\n# Creating the final submission file\nsub = pd.DataFrame(final_predictions)\nsub[\"ConfirmedCases\"] = sub[0].astype(int)\nsub[\"Fatalities\"] = sub[1].astype(int)\ncols = [0,1]\nsub.drop(sub.columns[cols],axis=1,inplace=True)\nsub.round() \nsub['ForecastId'] = range(1, len(sub) + 1)\nsub = sub[['ForecastId', 'ConfirmedCases','Fatalities']]\nsub.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '6d07f7f352d1bb'}"}
{"id":"34941","text":"\"\"\"\n# **Word Analysis**\n\"\"\"\nwordListE=[{\"word\":\"trained\",\"rt\":\"train\",\"cat\":\"v\",\"gen\":\"male\",\"num\":\"sg\",\"case\":\"\",\"per\":\"first\",\"tense\":\"simple-past\",\"aspect\":\"\"}, \n           {\"word\":\"stood\",\"rt\":\"stand\",\"cat\":\"v\",\"gen\":\"male\",\"num\":\"sg\",\"case\":\"\",\"per\":\"first\",\"tense\":\"simple-past\",\"aspect\":\"\"}, \n           {\"word\":\"walking\",\"rt\":\"walk\",\"cat\":\"v\",\"gen\":\"male\",\"num\":\"sg\",\"case\":\"\",\"per\":\"first\",\"tense\":\"present-continuous\",\"aspect\":\"\"}, \n] \ndef process(word): \n    for x in wordListE: \n        if word==x[\"word\"]: \n            if x['cat']==\"v\": \n                print(\"Root of word is : \",x['rt'],\"category is verb,\",\"gender is\",x['gen'],\",number is\",x['num'], \", tense is\", \n                      x['tense'], \", person is\", x['per'],\", aspect is:\",x['aspect'])\n            else: \n                print(\"Root of word is : \",x['rt'],\"category is noun,\",\"gender is\",x['gen'],\",number is\",x['num']) \nword = input(\"Enter the word:\")\nprint(\"Your word is:\",word)\nprocess(word)","meta":"{'source': 'AI4Code', 'id': '4058718178a5d9'}"}
{"id":"46514","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport plotly.express as px # plotly express\nimport plotly.graph_objects as go\n%matplotlib inline\nimport os\nfrom IPython.display import HTML\n\n# Input data files are available in the '\/kaggle\/input' or '..\/..\/..\/datasets\/extracts\/' directory.\nfile_input=['\/kaggle\/input','..\/..\/..\/datasets\/']\nfiles={}\nfor dirname, _, filenames in os.walk(file_input[0]):\n    for filename in filenames:\n        if 'csv' in filename:\n            files[filename.replace('.csv','')]=os.path.join(dirname, filename)\n\"\"\"\n# Effect of Weather on Coronavirus rate of spread\n\n**Brief:** Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus.\nThe virus that causes COVID-19 is mainly transmitted through droplets generated when an infected person coughs, sneezes, or exhales. These droplets are too heavy to hang in the air, and quickly fall on floors or surfaces.\n\nIn this notebook, we will try to find the correlation of weather attributes to the spread of Covid-19 (coronavirus). The notebook is spread into few sections:\n1. [Data Collection](#Data-Collection)\n2. [Data Cleanup](#Data-Cleanup)\n3. [Visualizing Cases vs Date for different Province](#Total-Cases-vs-Date-in-different-provinces)\n4. [Visualizing Rolling 7-day average of Cases vs Date for different Province](#Rolling-7-Day-average-for-cases-in-different-provinces)\n5. [Correlation Matrix](#Correlation-Matrix)\n6. Deep Dive in Total cases correlation matrix\n - [Confirmed Cases](#Confirmed-Cases)\n - [Recovered Cases](#Recovered-Cases)\n - [Death Cases](#Death-Cases)\n7. [Conclusion](#Conclusion)\n\n\n**NOTE:** This notebook deals with the correlation of weather attributes to covid-19, and not its causality, which may or may not be the same. Please keep that in mind\n\n**For the sake of ease of use, we will be use `province` as a pseudonym for Region\/States\/Provinces**\n\nAssumptions that I have taken for the data collection and processing.\n1. For weathers I took the following weather locations as a setpoint for each province.\n - **Reunion(France)** - Sainte-Marie, R\u00e9union (ROLAND GARROS AIRPORT STATION)\n - **Henan** - Zhengzhou, Henan (ZHENGZHOU XINZHENG INTERNATIONAL AIRPORT STATION)\n - **New York** - New York City, NY (LAGUARDIA AIRPORT STATION)\n - **Virginia** - Lynchburg, VA (LYNCHBURG REGIONAL AIRPORT STATION)\n - **Bermuda** - Castle Harbour, St. George's Parish (L.F. WADE INTERNATIONAL AIRPORT STATION)\n - **Maharashtra** - Mumbai, Maharashtra (CHHATRAPATI SHIVAJI INTERNATIONAL AIRPORT STATION)\n - **Lombardia** - Peschiera Borromeo, Province of Milan (LINATE AIRPORT STATION)\n - **Tasmania** - Hobart, Tasmania (HOBART INTERNATIONAL AIRPORT STATION)\n2. If the weather has any effect on coronavirus, it will take approximately 14 days for a patient to get diagnosed. So added a weather offset of 14 days\n\"\"\"\n\"\"\"\n# Data Collection\n\"\"\"\nProvinceDF=pd.DataFrame()\n\n# provinces to consider\nprovinces= ['Reunion','Quebec','Henan','New York','Virginia','Bermuda','Maharashtra','Lombardia','Tasmania']\n\ndf= pd.read_csv(files['covid_19_data'])\ndf= df[df['Province\/State'].isin(provinces)][['ObservationDate','Province\/State','Confirmed','Deaths','Recovered']]\\\n        .rename({'ObservationDate':'Date','Province\/State':'Province'},axis=1)\ndf['Date']= pd.to_datetime(df['Date'],format='%m\/%d\/%Y').dt.strftime('%Y-%m-%d')\nProvinceDF= pd.concat([ProvinceDF,df])\n\n# India States that needs to be considered\ndf= pd.read_csv(files['covid_19_india'])\ndf= df[df['State\/UnionTerritory']=='Maharashtra'][['Date','State\/UnionTerritory','Confirmed','Deaths','Cured']]\\\n        .rename({'State\/UnionTerritory':'Province','Cured':'Recovered'},axis=1)\ndf['Date']= pd.to_datetime(df['Date'],format='%d\/%m\/%y').dt.strftime('%Y-%m-%d')\nProvinceDF= pd.concat([ProvinceDF,df])\n\n# Italy Region that needs to be considered\ndf= pd.read_csv(files['covid19_italy_region'])\ndf= df[df['RegionName']=='Lombardia'][['Date','RegionName','TotalPositiveCases','Deaths','Recovered']]\\\n    .rename({'RegionName':'Province','TotalPositiveCases':'Confirmed'},axis=1)\ndf['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')\nProvinceDF= pd.concat([ProvinceDF,df])\n\nProvinceDF.head()\n\"\"\"\n**Weather data is collected from [WUNDERGROUND](https:\/\/www.wunderground.com\/)**\n\"\"\"\n# Weather data for the above Provinces\/States, pd.DateOffset for shifting dates\ntotal_weather_df=pd.DataFrame()\nfor key in provinces:\n    weather_df= pd.read_csv(files['Weather '+key])\n    weather_df['Date']= (pd.to_datetime(weather_df['valid_time_gmt'],unit='s') - pd.DateOffset(14)).dt.strftime('%Y-%m-%d')\n    weather_df= weather_df[['Date','temp','dewPt','wspd','pressure','heat_index','rh','vis','wc','wdir','feels_like','uv_index']].groupby(['Date']).agg(['min','mean','max']).reset_index()\n    weather_df.columns= weather_df.columns.map('| '.join).str.strip('| ')\n    weather_df['Province']= key\n    weather_df.drop('uv_index| min',axis=1,inplace=True)        \n    total_weather_df=pd.concat([total_weather_df,weather_df])\n    \n# merging weather data with province data\nProvinceWeatherDF= pd.merge(ProvinceDF,total_weather_df,left_on=['Date','Province'],right_on=['Date','Province'],how='left')\n\"\"\"\n#### Weather abbreviations and definitions from https:\/\/www.worldcommunitygrid.org\/lt\/images\/climate\/The_Weather_Company_APIs.pdf:\n- **temp**: The forecasted temperature for midpoint day (1pm) or midpoint night (1am) for a 12 hour daypart.\n- **dewPt**: The temperature which air must be cooled at constant pressure to reach saturation\n- **wspd**: The maximum forecasted hourly wind speed\n- **pressure**: Mean Sea Level Pressure, the equivalent pressure reading at sea level recorded at this station\n- **heat_index**: An apparent temperature. It represents what the air temperature \u201cfeels like\u201d on exposed human skin due to the combined effect of warm temperatures and high humidity\n- **rh**: (%)The relative humidity of the air, which is defined as the ratio of the amount of water vapor in the air to the amount of vapor required to bring the air to saturation at a constant temperature. \n- **vis**: Prevailing hourly visibility\n- **wc**: Wind Chill - Minimum wind chill.\n- **wdir**: Daytime average wind direction in magnetic notation. \n- **feels_like**: Hourly feels like temperature. \n- **uv_index**: Maximum UV index for the 12 hour forecast period. \n\"\"\"\n\"\"\"\n# Data Cleanup\n\"\"\"\n# Removing elements for which we dont have weather data (temp| min is one of them to consider)\nProvinceWeatherDF= ProvinceWeatherDF[~ProvinceWeatherDF['temp| min'].isna()]\n\n# adding Delta Changes(per day shifts) as different columns data and merging with the province data\nProvinceWeatherDF= pd.concat([ProvinceWeatherDF.sort_values('Date'),\n                            ProvinceWeatherDF.sort_values('Date')[['Province','Confirmed','Deaths','Recovered']]\\\n                              .groupby('Province').diff().rename({'Confirmed':'Delta Confirmed','Deaths':'Delta Deaths','Recovered':'Delta Recovered'},axis=1)],axis=1)\n\n# Cleaning data, for negative per day changes, fill the previous value\nProvinceWeatherDF['Date']= pd.to_datetime(ProvinceWeatherDF['Date'])\nProvinceWeatherDF.sort_values('Date',inplace=True)\n\nfor feature in ['Confirmed','Deaths','Recovered']:\n    ProvinceWeatherDF.loc[ProvinceWeatherDF['Delta '+feature]<0,feature]=\\\n        ProvinceWeatherDF[ProvinceWeatherDF['Delta '+feature]<0][[feature,'Delta '+feature]]\\\n            .apply(lambda row:row[feature]-row['Delta '+feature],axis=1)\n\n    # After the confirmed cases are shifted to previous value, fill the negative value of 'Delta Confirmed cases' to 0\n    ProvinceWeatherDF['Delta '+feature].clip(lower=0,inplace=True)\n\n    # fill zero values apart from first value of Province with the previous value\n    for province in ProvinceWeatherDF['Province'].unique():\n        ProvinceWeatherDF.loc[ProvinceWeatherDF['Province']==province,feature]=\\\n            ProvinceWeatherDF.loc[ProvinceWeatherDF['Province']==province,feature].mask((ProvinceWeatherDF['Province']==province)&(ProvinceWeatherDF[feature] == 0)).ffill()\n    \n    # fill NaN with 0. NaN orignates from unfilled mask above\n    ProvinceWeatherDF[feature].fillna(0,inplace=True)\n    \n    ProvinceWeatherDF.loc[ProvinceWeatherDF[feature]>0,feature+' Days']= ProvinceWeatherDF[ProvinceWeatherDF[feature]>0].groupby('Province')['Date'].rank(ascending=True)\n    ProvinceWeatherDF= pd.merge(ProvinceWeatherDF,\n                            ProvinceWeatherDF.groupby('Province').rolling('7D',on='Date')[feature].mean().reset_index().rename({feature:'Rolling '+feature},axis=1),\n                            left_on=['Date','Province'],right_on=['Date','Province'],how='right')\nProvinceWeatherDF.head()\n\"\"\"\n# Total Cases vs Date in different provinces\n\"\"\"\nfor feature in ['Confirmed','Deaths','Recovered']:\n    fig= px.line(ProvinceWeatherDF,\n            x='Date',\n            y=feature,\n            color='Province',\n            title=feature+' cases in different provinces',\n            template='plotly_dark')\n\n    fig.update_layout(yaxis=dict(type='log'))\n    fig.show()    \n\"\"\"\n# Rolling 7-Day average for cases in different provinces\n\"\"\"\nfor feature in ['Confirmed','Deaths','Recovered']:\n    fig= px.line(ProvinceWeatherDF,\n            x='Confirmed Days',\n            y='Rolling '+feature,\n            hover_name=feature,\n            color='Province',\n            title='Rolling 7-Day average for '+feature+' cases in different provinces',\n            template='plotly_dark')\n    fig.update_layout(yaxis=dict(type='log'),\n        annotations = [dict(xref='paper',\n                                        yref='paper',\n                                        x=-0.1, y=-0.2,\n                                        showarrow=False,\n                                        text ='Number of days since 1st non-zero case was recorded')]\n    )\n    fig.show()   \n\"\"\"\n# Correlation Matrix\n\"\"\"\ncorr=ProvinceWeatherDF[ProvinceWeatherDF.columns.sort_values()].corr()\nmask= np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\nfig= go.Figure(data=go.Heatmap(z=corr.mask(mask),\n                                x=corr.columns.values,\n                                y=corr.columns.values,\n                                xgap=1, ygap=1,\n                                colorscale=\"Rainbow\",\n                                colorbar_thickness=20,\n                                colorbar_ticklen=3,\n                                zmid=0),\n                layout= go.Layout(title_text='Correlation Matrix', template='plotly_dark',\n                height=900,\n                xaxis_showgrid=False,\n                yaxis_showgrid=False,\n                yaxis_autorange='reversed'))\nfig.show()\nReqColumns= ProvinceWeatherDF.columns[(ProvinceWeatherDF.columns.str.contains('Confirmed|Recovered|Deaths'))&(~ProvinceWeatherDF.columns.str.contains('Days'))]\n\n# Correlation Matrix\nCorrMatrix= pd.DataFrame(ProvinceWeatherDF.corr())\nCorrMatrix[ReqColumns].style.background_gradient(cmap='Blues')\n\"\"\"\n# Deep Dive in Total Cases feature's correlations\n\n>now we will go through one by one and see the major correlations\n\"\"\"\n\"\"\"\n### Confirmed Cases\n\"\"\"\nopColumns= ProvinceWeatherDF.columns[ProvinceWeatherDF.columns.str.contains('Confirmed|Recovered|Deaths|Days')]\nConfMatrix= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),'Confirmed']\nConfMatrix= pd.concat([ConfMatrix.abs().rename('Abs Confirmed'),ConfMatrix],axis=1).sort_values('Abs Confirmed',ascending=False)[:10]\nConfMatrix\n\"\"\"\n#### Logic behind creating the below graph:\nwe cannot put all the features to build the chart, so we will choose, which ones to show.\nTo choose that, we will do the following:\n- Get top 10 highest `absolute` correlation features for Confirmed Cases\n- Take the first 3 values, which doesn't include `days` and not a categorical data(value_counts()<4), which are not similar (pressure|mean and pressure|max are correlated), and build the chart below\n\"\"\"\nfig= px.scatter(ProvinceWeatherDF,\n               y='dewPt| min',\n               x='Confirmed',\n               color='rh| min',\n               size='vis| min',\n               hover_name='Province',\n               template='plotly_dark',\n               color_continuous_scale=\"Rainbow\",\n               opacity=1,\n              )\nfig.update_layout(xaxis={'type':'log'},yaxis={'type':'linear'})\nfig.show()\n\"\"\"\n**The above chart shows the `lower dewPt| max`, `lower rh| min` and `higher vis| max` is propotional to `higher Confirmed cases`.**\n\"\"\"\nPositiveConfirmedCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\nNegativeConfirmedCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\nfor feature in ['Confirmed','Delta Confirmed','Rolling Confirmed']:\n    Correlations= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),feature]\n    PositiveConfirmedCorr= PositiveConfirmedCorr & set(Correlations[Correlations>0].index)\n    NegativeConfirmedCorr= NegativeConfirmedCorr & set(Correlations[Correlations<0].index)\n    \n    print('\\033[1mPositive Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations>0].sort_values(ascending=False).index))\n    print('\\n\\033[1mNegative Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations<0].sort_values().index))\n    print(''.join(['_' for _ in range(80)]),'\\n')\n\"\"\"\n> If you see the above correlations, all of them have same positive\/negative correlation, with slight difference in ordering. Thus we are not building seperate graphs for each variation of confirmed cases\n\"\"\"\n\"\"\"\n### Recovered Cases\n\"\"\"\nConfMatrix= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),'Recovered']\nConfMatrix= pd.concat([ConfMatrix.abs().rename('Abs Recovered'),ConfMatrix],axis=1).sort_values('Abs Recovered',ascending=False)[:10]\nConfMatrix\nfig= px.scatter(ProvinceWeatherDF,\n               y='wspd| mean',\n               x='Recovered',\n               size='rh| min',\n               color='wdir| max',\n               hover_name='Province',\n               template='plotly_dark',\n               color_continuous_scale=\"Rainbow\",\n               opacity=1,\n              )\nfig.update_layout(xaxis={'type':'log'},yaxis={'type':'log'})\nfig.show()\n\"\"\"\n**The above chart shows the `lower wspd| mean`, `higher wdir| max` and `lower rh| mean` is propotional to higher Recovered cases.**\n\"\"\"\nPositiveRecoveredCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\nNegativeRecoveredCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\n\nfor feature in ['Recovered','Delta Recovered','Rolling Recovered']:\n    Correlations= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),feature]\n    PositiveRecoveredCorr= PositiveRecoveredCorr & set(Correlations[Correlations>0].index)\n    NegativeRecoveredCorr= NegativeRecoveredCorr & set(Correlations[Correlations<0].index)\n    \n    print('\\033[1mPositive Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations>0].sort_values(ascending=False).index))\n    print('\\n\\033[1mNegative Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations<0].sort_values().index))\n    print(''.join(['_' for _ in range(80)]),'\\n')\n\"\"\"\n> If you see the above correlations, almost of them have same positive\/negative coorelation, with slight difference in ordering. Thus we are not building seperate graphs for each variation of Recovered cases\n---\n### Death Cases\n\"\"\"\nConfMatrix= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),'Deaths']\nConfMatrix= pd.concat([ConfMatrix.abs().rename('Abs Deaths'),ConfMatrix],axis=1).sort_values('Abs Deaths',ascending=False)[:10]\nConfMatrix\nfig= px.scatter(ProvinceWeatherDF,\n               y='rh| min',\n               x='Deaths',\n               size='vis| min',\n               color='dewPt| min',\n               hover_name='Province',\n               template='plotly_dark',\n               color_continuous_scale=\"Rainbow\",\n               opacity=1,\n              )\nfig.update_layout(xaxis={'type':'log'},yaxis={'type':'log'})\nfig.show()\n\"\"\"\n**The above chart shows the `lower rh| min`, `lower dewPt| min` and `higher vis| min` is propotional to higher Death cases.**\n\"\"\"\nPositiveDeathsCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\nNegativeDeathsCorr= set(CorrMatrix.index[~CorrMatrix.index.isin(opColumns)])\n\nfor feature in ['Deaths','Delta Deaths','Rolling Deaths']:\n    Correlations= CorrMatrix.loc[~CorrMatrix.index.isin(opColumns),feature]\n    PositiveDeathsCorr= PositiveDeathsCorr & set(Correlations[Correlations>0].index)\n    NegativeDeathsCorr= NegativeDeathsCorr & set(Correlations[Correlations<0].index)\n    \n    print('\\033[1mPositive Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations>0].sort_values(ascending=False).index))\n    print('\\n\\033[1mNegative Correlation with '+feature+'(Descending Order): \\033[0m\\n\\t'+ ', '.join(Correlations[Correlations<0].sort_values().index))\n    print(''.join(['_' for _ in range(80)]),'\\n')\n\"\"\"\n> If you see the above correlations, Features for whom the graph is plotted have same positive\/negative coorelation, with slight difference in ordering. Thus we are not building seperate graphs for each variation of Death cases. But to add to the point above, *Delta Deaths* have more negative correlations than the others, hence worth looking deeply into it seperately. Maybe a different Notebook for it.\n\n\"\"\"\n\"\"\"\n# Conclusion\n   **we saw how the weather conditions effect the spread of Lockdown. The most interesting of them being the `Temperature`, which is negatively correlated to Confirmed & Death's rate of spread, but positively related to Recovered's.**\n   \nTaking intesection of all types of variation correlation(Total\/Rolling\/Delta) for each o\/p\n\"\"\"\nHTML('<h3>Absolute Positive Correlation with Confirmed Cases(intersections of all variations):<\/h3>'+\n      ', '.join(PositiveConfirmedCorr)+\n     '<br><br><h3>Absolute Negative Correlation with Confirmed Cases(intersections of all variations):<\/h3>'+\n     ', '.join(NegativeConfirmedCorr))\nHTML('<h3>Absolute Positive Correlation with Recovered Cases(intersections of all variations):<\/h3>'+\n      ', '.join(PositiveRecoveredCorr)+\n     '<br><br><h3>Absolute Negative Correlation with Recovered Cases(intersections of all variations):<\/h3>'+\n     ', '.join(NegativeRecoveredCorr))\nHTML('<h3>Absolute Positive Correlation with Death Cases(intersections of all variations):<\/h3>'+\n      ', '.join(PositiveDeathsCorr)+\n     '<br><br><h3>Absolute Negative Correlation with Death Cases(intersections of all variations):<\/h3>'+\n     ', '.join(NegativeDeathsCorr))\n\"\"\"\n#### Additional Notes:\n\nThere are few things I have tried with almost similar results, hence haven't added to this notebook(Let me know, if I should add them in seperate notebook)\n- F_regression to find top 10 important variables\n- Linear Regression for the same above reason (RMSE score was bad, hence useless)\n- DL model for the same reason (Better than LR, but still high RMSE score)\n- The 14 day offset to counter to diagnosis delay, if removed has almost the same results, hence not put in as a seperate case. You can fork and change `pd.offset(14)` to `pd.offset(0)` for same.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '55b295ae408b02'}"}
{"id":"41782","text":"\"\"\"\n<h1><center><div style=\"background-color:skyblue;border-radius:10px; padding: 10px;\">Introduction<\/div><\/center><\/h1>\n\n\ud83d\ude45\ud83c\udffd\u200d\u2640\ufe0f Motivation\n> Suppose you get a call \ud83d\udcde from your bank, and the customer care executive informs you that your card is about to expire in a week. Immediately, you check your card details and realise that it will expire in the next eight days. Now, to renew your membership, the executive asks you to verify a few details such as your credit card number, the expiry date and the CVV number. Will you share these details with the executive?\n> In such situations, you need to be careful because the details that you might share with them could grant them unhindered access to your credit card account.\n \n> Banks \ud83c\udfe6 need to be cautious about their customers\u2019 transactions, as they cannot afford to lose their customers\u2019 money to fraudsters \ud83e\uddb8\u200d\u2642\ufe0f. Every fraud is a loss to the bank, as the bank is responsible for the fraudulent transactions if they are reported within a certain time frame by the customer.\n\n\ud83c\udfaf Goal\n> The goal of this notebook is to predict the fraud transactions with high accuracy.\n\n#### Index\n\n- 1. Data preparation\n    - Exploring data, and removing unnecessary columns\n    - Transforming data\n    - Handling class imbalance\n    - Creating training and testing data\n- 2. Model building\n    - Building models\n    - Hyperparameter tuning\n- 3. Model evaluation\n    - Evaluating model using AUC ROC curve\n\"\"\"\n\"\"\"\n<h2><center> <div style=\"background-color:skyblue;border-radius:10px; padding: 10px;\">Data Prepration<\/div><\/center><\/h2>\n\n> The data contains only numerical input variables which are the result of a PCA transformation. Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, \u2026 V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are `Time` and `Amount`. Feature `Time` contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature `Amount` is the transaction Amount, this feature can be used for example-dependant cost-sensitive learning. Feature `Class` is the response variable and it takes value 1 in case of fraud and 0 otherwise.\n\"\"\"\n# Importing the libraries\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Reading the file\ndf = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\ndf.head()\n\"\"\"\n> `Class` 0 : Fair transaction \ud83d\udc4d\ud83c\udffd | 1 : Fraud transaction \ud83e\uddb8\u200d\u2642\ufe0f\n\n> `Time` column won't of much importance while indentifying a fraud, as it only contains the seconds elapsed between each transaction and the first transaction in the dataset, so I will remove it.\n\"\"\"\n# Removing the 'Time' column\ndf = df.drop(['Time'], axis = 1)\n# Checking for null values\ndf.isnull().sum().sum()\n\"\"\"\n<h3><center> <div style=\"background-color:lightpink;border-radius:10px; padding: 10px;\">Data Exploration<\/div><\/center><\/h3>\n\n> The data contains PCA transformed features, so the columns are meaningless except the `Amount` and `Class`. I will only perform the EDA which is necessary for building model.\n\"\"\"\n# Understanding amount in fraud transactions\nplt.style.use('seaborn')\nfig, ax = plt.subplots(1 ,1, figsize = (10, 6), constrained_layout = True)\n\n# I used median instead of mean to avoid outliers\nax = sns.barplot(x = 'Class', y = 'Amount', data = df, estimator = np.median, ax = ax)\n\nplt.title(\"Average Amount in Fraud Transactions\", size = 16)\n\nax.set_xticklabels(['Fair', 'Fraud'], fontsize = 14)\n\nplt.xlabel(None)\nplt.ylabel('Amount of Transaction', fontsize = 14);\n\"\"\"\n> On an average, the amount in fraud transactions is lower than fair transactions. The reason I think can be, the fraud's are smart \ud83e\udde0, they know if they do a fraud of big amount they may get caught \ud83d\ude94, so they do multiple frauds of smaller amount.\n\"\"\"\n# EDA for the features V1, V2,..., V28\nv_feaures = df.iloc[:,:-2].columns.to_list()\n\nplt.style.use('seaborn')\nfig, ax = plt.subplots(7,4, figsize = (14, 24), constrained_layout = True)\n\nfor col, axis in zip(v_feaures, ax.ravel()): # ax.ravel() kind of flattens the 2d to 1d for iteration\n    axis = sns.kdeplot(x = col, data = df, fill = True, alpha = 0.6, linewidth = 1.5, ax=axis)\n    axis.set_title(col, fontsize = 14)\n    axis.set_xlabel(None)\n    axis.set_ylabel(None)\n    \nfig.suptitle('Distribution of the features V1, V2,..., V28', fontsize = 16, y = 1.01);\n\"\"\"\n> Many features have normal distribution. Each of the PCs given by PCA is a linear combination of the original features and the original features were normally distributed , so every linear combination of them i.e. PCs are also normally distributed.\n\n> There are also some features which are skew distributed, so I will use quantile transform for this purprose. I will be considering (-0.5,0.5) range for skewness, any feature having value beyound this range will get transformed.\n\n\u2755 I have tried log transform by adding some constant to negetive values and also inverse hyperbolic tangent transform by scaling features in (-1, 1) range, but none of them reduced the skewness, so I am using quantile transform.\n\"\"\"\n\"\"\"\n<h3><center> <div style=\"background-color:lightpink;border-radius:10px; padding: 10px;\">\ud83e\udd5a Data Transformation \ud83d\udc23<\/div><\/center><\/h3>\n\"\"\"\n# Checking the skewness values\nplt.style.use('seaborn')\nfig, ax = plt.subplots(1,1, figsize = (10, 6), constrained_layout = True)\nax = df.skew(axis = 0).plot(kind = 'bar')\n\nfor i in ax.patches:\n    ax.text(x = i.get_x() + i.get_width()\/2, y = i.get_height()+0.5, \n            s = f\"{np.round(i.get_height(), 1)}\", \n            ha = 'center', size = 14, rotation = 0, color = 'black')\n    \nax.set_ylabel('Skewness', fontsize = 14)\nax.set_title('Skewness of the features', fontsize = 16);\n\"\"\"\n<h4><center> <div style=\"background-color:violet;border-radius:10px; padding: 10px;\">Quantile Transform<\/div><\/center><\/h4>\n\"\"\"\nfrom sklearn.preprocessing import quantile_transform\n\nv_features = df.iloc[:, :-2].columns\ndf[v_features] = pd.DataFrame(quantile_transform(df[v_features], n_quantiles=500), columns = v_features)\n\nprint('Skewness after Quantile Transform')\ndf[v_features].skew(axis = 0)\n\"\"\"\n> The skewness has been reduced close to 0! Now let's check for the class imbalance.\n\"\"\"\n\"\"\"\n<h3><center> <div style=\"background-color:lightpink;border-radius:10px; padding: 10px;\">Class Imbalance \u2696<\/div><\/center><\/h3>\n\n> Imbalanced classifications pose a challenge for predictive modeling as most of the machine learning algorithms used for classification were designed around the assumption of an equal number of examples for each class. This results in models that have poor predictive performance, specifically for the minority class.\n\"\"\"\n# Checking for class imbalance \nplt.style.use('seaborn')\nfig = plt.figure(figsize = (10, 6))\n\nax = sns.countplot(x = 'Class', data = df)\n\nfor i in ax.patches:\n    ax.text(x = i.get_x() + i.get_width()\/2, y = i.get_height()\/2, \n            s = f\"{np.round(i.get_height()\/len(df)*100, 3)}%\", \n            ha = 'center', size = 20, weight = 'bold', rotation = 0, color = 'black')\n\nplt.title(\"Credit Card Fraud Count\", size = 16)\n\nax.set_xticklabels(['Fair', 'Fraud'], fontsize = 14)\n\nplt.xlabel(None)\nplt.ylabel('Number of Transactions', fontsize = 14);\n\"\"\"\n> Only 0.173% tractions are fraud, which is very much less than other class. If we train our model on this unbalanced class data, then the model won't learn much from Fraud class and will try to give more importance to Fair class, which we don't want. Let's see that in action, I will train a simple logistic regression model and see its performance.\n\"\"\"\n# Splitting data into train and test\nfrom sklearn.model_selection import train_test_split\n\nX = df.drop(['Class'], axis = 1)\ny = df['Class']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.7, stratify = df['Class'], random_state = 99)\n# Training model on imbalanced class data \nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\nmodel = LogisticRegression(solver='liblinear').fit(X_train, y_train)\n\nmatrix = metrics.confusion_matrix(y_test, model.predict(X_test))\nplt.style.use('seaborn')\nfig, axis = plt.subplots(1,1, figsize=(10, 6), constrained_layout = True)\naxis = sns.heatmap(matrix, annot=True, fmt = '.0f', cbar=False, cmap='Blues',\n                        linewidths=3, square=True, ax = axis, annot_kws={\"fontsize\":20})\n\naxis.set_xlabel('Predicted', fontsize=14)\naxis.set_ylabel('Actual', fontsize=14)\naxis.set_xticklabels(['Fair','Fraud'], fontsize=12)\naxis.set_yticklabels(['Fair','Fraud'], fontsize=12, rotation=0);\nplt.title('Model Evluation using Confusion Matrix (Before Class Balancing)', fontsize = 16);\n\"\"\"\n> There are 35 False Negetives out of 148. It means that, out of 148 frauds, our model couldn't identify 35 (24%), this is mainly due to class imbalance. We don't want to let the fraud escape this easily, so let's balance the classes.\n\n> I am using SMOTE and ADASYN methods. They both are oversampling methods, i.e. they create synthetic data for manority class so that it becomes similar in count with majority class.\n\n<center><img src = https:\/\/miro.medium.com\/max\/1200\/1*0jwntVGaj7qQkr-MeueQcQ.jpeg><\/center>\n\nSMOTE (Synthetic Minority Over-sampling Technique) creates the synthetic data for minority class, using linear method. It takes two close minority points and creates a new point on a line joining the two points.\n\nADASYN (Adaptive Synthetic) uses a weighted distribution for different minority class examples according to their level of difficulty in learning, where more synthetic data is generated for minority class examples that are harder to learn compared to those minority examples that are easier to learn. It creates the synthetic data near to the minority points having less density. \n\"\"\"\nfrom imblearn.over_sampling import SMOTE, ADASYN\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\nX_train_new, y_train_new = SMOTE().fit_resample(X_train, y_train)\n\nprint('Before resmapling : ', y_train.value_counts())\nprint('After resmapling : ', y_train_new.value_counts())\n\npipeline = Pipeline([('model', LogisticRegression(solver='liblinear'))])\npipeline.fit(X_train_new, y_train_new)\nmatrix_new = metrics.confusion_matrix(y_test, pipeline.predict(X_test))\nplt.style.use('seaborn')\nfig, axis = plt.subplots(1,1, figsize=(10, 6), constrained_layout = True)\naxis = sns.heatmap(matrix_new, annot=True, fmt = '.0f', cbar=False, cmap='Blues',\n                        linewidths=3, square=True, ax = axis, annot_kws={\"fontsize\":20})\n\naxis.set_xlabel('Predicted', fontsize=14)\naxis.set_ylabel('Actual', fontsize=14)\naxis.set_xticklabels(['Fair','Fraud'], fontsize=12)\naxis.set_yticklabels(['Fair','Fraud'], fontsize=12, rotation=0);\nplt.title('Model Evluation using Confusion Matrix (After Class Balancing)', fontsize = 16);\n\"\"\"\n> There are only 9 False Negetives out of 148. It means that, out of 148 frauds, our model couldn't identify only 9 (6%) frauds. Previously, before class balancing, False Negetives were 35 (24%) and now they are 9, 4 times reduction!\n\n> Let's try with ADASYN.\n\"\"\"\n# Oversampling minority class using ADASYN\nX_train_ada, y_train_ada = ADASYN().fit_resample(X_train, y_train)\n\nprint('Before resmapling : ', y_train.value_counts())\nprint('After resmapling : ', y_train_ada.value_counts())\n\npipeline = Pipeline([('model', LogisticRegression(solver='liblinear'))])\npipeline.fit(X_train_ada, y_train_ada)\nmatrix_new = metrics.confusion_matrix(y_test, pipeline.predict(X_test))\nplt.style.use('seaborn')\nfig, axis = plt.subplots(1,1, figsize=(10, 6), constrained_layout = True)\naxis = sns.heatmap(matrix_new, annot=True, fmt = '.0f', cbar=False, cmap='Blues',\n                        linewidths=3, square=True, ax = axis, annot_kws={\"fontsize\":20})\n\naxis.set_xlabel('Predicted', fontsize=14)\naxis.set_ylabel('Actual', fontsize=14)\naxis.set_xticklabels(['Fair','Fraud'], fontsize=12)\naxis.set_yticklabels(['Fair','Fraud'], fontsize=12, rotation=0);\nplt.title('Model Evluation using Confusion Matrix (After Class Balancing)', fontsize = 16);\n\"\"\"\n> The recall is slightly improved but on the expense of precision.\n\"\"\"\n\"\"\"\n<h2><center> <div style=\"background-color:skyblue;border-radius:10px; padding: 10px;\">Model Building \ud83e\udd16<\/div><\/center><\/h2>\n\n> I am focusing on recall as, it a good measure of false negetives. If a fair transaction is predicted as fraud, then manual step can mitigate this problem but if fraud is predicted as fair, then it can cause loss to the customer as well as bank.\n\n> But if only recall the prime importance then the threshold will be set at 0 so that we get recall as 100% but very high false positives, so I am giving 50% weightage to accuracy and 50% to recall.\n\"\"\"\n\"\"\"\n<h4><center> <div style=\"background-color:violet;border-radius:10px; padding: 10px;\">Logistic Regression<\/div><\/center><\/h4>\n\"\"\"\nfrom sklearn.linear_model import LogisticRegressionCV\npipeline = Pipeline([('model', LogisticRegressionCV(solver='liblinear', cv = 5))])\npipeline.fit(X_train_ada, y_train_ada)\n\"\"\"\n> I will be using AUC ROC curve for model evaluation as it is independent of the threshold. Sklearn considers `0.5` as threshold for calculating Accuracy, Precision, Recall, etc. but the value of threshold varies with models, and so I will be using AUC ROC curve to find out the best threshold and use that to predict.\n\"\"\"\n# Plotting the ROC Curve and finding optimal threshold\n# Function for plotting ROC curve, confurion matrix and finding optimal threshold\ndef my_roc_curve(model, accuracy_weight, title, X_train, y_train):\n    from sklearn import metrics\n    # Plotting AUC ROC curve\n    y_scores = model.predict(X_train)\n    fpr, tpr, thresholds = metrics.roc_curve(y_train, y_scores)\n    \n    fig, (ax1,ax2) = plt.subplots(1,2, figsize = (12, 6), constrained_layout = True)\n    ax1.plot(fpr, tpr, color='skyblue', label='ROC')\n    ax1.plot([0, 1], [0, 1], color='pink', linestyle='--')\n    ax1.text(x = 0.8, y = 0.3,\n            s = f\"AUC : {round(metrics.roc_auc_score(y_train, y_scores),2)}\",\n            ha = 'center', size = 12, rotation = 0, color = 'black',\n            bbox=dict(boxstyle=\"round,pad=0.5\", fc='skyblue', ec=\"skyblue\", lw=2));\n\n    ax1.set_xlabel('False Positive Rate', fontsize = 12)\n    ax1.set_ylabel('True Positive Rate', fontsize = 12)\n    ax1.set_title(f'ROC curve',  fontsize=16, y=1.05)\n\n    # Plotting optimal Confusion Matrix\n    from sklearn import metrics\n    probability = model.predict_proba(X_train)\n    matrix = pd.DataFrame()\n    \n    base_accuracy = metrics.accuracy_score(y_train, model.predict(X_train))\n    base_recall = metrics.recall_score(y_train, model.predict(X_train))\n    best_score = 0.6*base_accuracy + 0.4*base_recall\n    best_thresold = 0.5\n    \n    # Finding optimul thresold to maximize > accuracy_weight*threshold_accuracy + (1-accuracy_weight)*threshold_recall\n    for threshold in np.linspace(0, 1, 100):\n        y_predict = (probability>=threshold).astype(int)[:,1]\n        threshold_accuracy = metrics.accuracy_score(y_train, y_predict)\n        threshold_recall = metrics.recall_score(y_train, y_predict)\n        weighted_score = accuracy_weight*threshold_accuracy + (1-accuracy_weight)*threshold_recall\n        \n        if weighted_score>best_score:\n            best_thresold = threshold\n            best_score = weighted_score\n    \n    y_predict = (probability>=best_thresold).astype(int)[:,1]\n    matrix = metrics.confusion_matrix(y_train, y_predict)\n\n    ax2 = sns.heatmap(matrix, annot=True, fmt = '.0f', cbar=False, cmap='Blues',\n                        linewidths=3, square=True, ax = ax2, annot_kws={\"fontsize\":20})\n    ax2.set_title(f\"Confusion Matrics | Threshold : {round(best_thresold, 2)}\", fontsize=16, y=1.05);\n    ax2.set_xlabel('Predicted', fontsize=12)\n    ax2.set_ylabel('Actual', fontsize=12)\n    ax2.set_xticklabels([0,1], fontsize=12 )\n    ax2.set_yticklabels([0,1], fontsize=12, rotation=0)\n    \n    print('Optimal Threshold for Accuracy and Recall is : ', round(best_thresold, 2))\n    print(f\"Train Accuracy for  {title}: \", round(metrics.accuracy_score(y_train, y_predict),2), \n          f\"| Train Recall for {title}: \", round(metrics.recall_score(y_train, y_predict),2))\n    \n    plt.suptitle(f'{title}', fontsize=19, y=1.05)\n    \n    # For test data\n    probability = model.predict_proba(X_test)\n    y_predict = (probability>=best_thresold).astype(int)[:,1]\n    print(f\"Test Accuracy for {title}: \", round(metrics.accuracy_score(y_test, y_predict),2),\n         f\"| Test Recall for {title}: \", round(metrics.recall_score(y_test, y_predict),2))\nmy_roc_curve(pipeline, 0.5, 'Logistic Regression', X_train_ada, y_train_ada)\n\"\"\"\n<h4><center> <div style=\"background-color:violet;border-radius:10px; padding: 10px;\">Decision Tree \ud83c\udf33<\/div><\/center><\/h4>\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import GridSearchCV\n\npipeline = Pipeline([('tree', DecisionTreeClassifier(random_state = 99))])\nparms = {'tree__max_depth': [3, 7, 11],\n        'tree__min_samples_leaf':[50, 100, 200]}\n\ntree_model = GridSearchCV(pipeline, parms, cv = 5)\ntree_model.fit(X_train_ada, y_train_ada)\n# Best Estimator\ntree_model.best_estimator_\nmy_roc_curve(tree_model, 0.5, 'Decision Tree', X_train_ada, y_train_ada)\n\"\"\"\n#### Overfitting!\n\"\"\"\n\"\"\"\n<h4><center> <div style=\"background-color:violet;border-radius:10px; padding: 10px;\">CatBoost \ud83c\udf33\u27a1\ud83c\udf33\u27a1\ud83c\udf33\u27a1\ud83c\udf33<\/div><\/center><\/h4>\n\"\"\"\nfrom catboost import CatBoostClassifier\n\ncat_model = CatBoostClassifier(task_type = 'GPU', od_type = 'Iter')\n# Creating evaluation set for catboost\nX_train_cat, X_eval, y_train_cat, y_eval = train_test_split(X_train_ada, y_train_ada, stratify = y_train_ada,\n                                                            random_state = 99)\ncat_model.fit(X_train_cat, y_train_cat, use_best_model = True,\n              eval_set = (X_eval, y_eval), verbose = 100, early_stopping_rounds = 50)\nmy_roc_curve(cat_model, 0.5, 'CatBoost', X_train_cat, y_train_cat)\nprobability = cat_model.predict_proba(X_test)\ny_predict = (probability>=0.7).astype(int)[:,1]\nmatrix = metrics.confusion_matrix(y_test, y_predict)\nmatrix\nplt.style.use('seaborn')\nfig, axis = plt.subplots(1,1, figsize=(10, 6), constrained_layout = True)\naxis = sns.heatmap(matrix, annot=True, fmt = '.0f', cbar=False, cmap='Blues',\n                        linewidths=3, square=True, ax = axis, annot_kws={\"fontsize\":20})\n\naxis.set_xlabel('Predicted', fontsize=14)\naxis.set_ylabel('Actual', fontsize=14)\naxis.set_xticklabels(['Fair','Fraud'], fontsize=12)\naxis.set_yticklabels(['Fair','Fraud'], fontsize=12, rotation=0);\nplt.title('CatBoost Confusion Matrix (Optimal Threshold)', fontsize = 16);\n\"\"\"\n> That looks good! We got a recall of 84% and 97% accuracy!\n\"\"\"\n\"\"\"\n<h4><center> <div style=\"background-color:pink;border-radius:10px; padding: 10px;\">If you like it, don't forget to upvote!<\/div><\/center><\/h4>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4cfbc2aeca8463'}"}
{"id":"60665","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt #  plotting tool\nimport seaborn as sns  #graphing tool \nimport math\n\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\ndf = pd.read_csv('..\/input\/oneYear.csv', encoding='latin-1')\ndf.head()\n\"\"\"\n# We might have other problematic values that aren't necessarily null, but we have to check for null values\n\n\"\"\"\npd.isnull(df).any()   \n\"\"\"\n# It can never hurt to try and run a few different graphs, but in this case, the bar graph wasn't particularly appropriate for our case. We'll get to some other types later\n\"\"\"\n\nax = df.plot(kind = 'bar')\n\"\"\"\n# The often forgotten problem of duplicates. Therefore we group by economy name and remove any duplicates there\n\"\"\"\ndf.groupby(['Economy']).head()\n\ndf.drop_duplicates('Economy', keep=False)\n\"\"\"\n# Perhaps viewing a scatterplot of our data could give us a little bit better visualization, and it seems to be that even the countries which scored low overall still had decent scores regarding intercountry trade. \n\"\"\"\nimport matplotlib.ticker as ticker\ntick_spacing = 5\nplt.figure(figsize=(15,15))\nx = df['Ease of doing business rank global (DB19)']\ny = df['Score-Trading across borders(DB16-19 methodology)']\nplt.scatter(df['Ease of doing business rank global (DB19)'], df['Score-Trading across borders(DB16-19 methodology)'])\nplt.xlabel('Rank')\nplt.ylabel('Score')\nplt.xticks(min(x), max(x))\nplt.show()\n\"\"\"\n# The easiest way to find outliers is very often through a boxplot, and I noticed I had two small outliers but I didn't think they would affect the overall outcome very much. \n\"\"\"\nfig1, ax1 = plt.subplots()\nax1.set_title('Breakdown of how easy it is to do business globally')\nax1.boxplot(df['Ease of doing business score global (DB17-19 methodology)'])\n\"\"\"\n# A good way to check the visualization of our data is through a histogram. Our histogram seems to be left skewed which means most of the countries are towards the top\n\"\"\"\nplt.hist(df['Ease of doing business score global (DB17-19 methodology)'])\n\"\"\"\n# Sometimes trying to run a log function on the data can affect the Skew. I tried that here but it didn't help my skew\n\"\"\"\ndef logFunction(x):\n  return np.log(x)\n\ndf1 = df['Ease of doing business score global (DB17-19 methodology)'].apply(logFunction)\nplt.hist(np.log(df1))\n\"\"\"\n# Even through all the visualization of certain columns and coordinates, we have to look at our full dataset to verify that the columns we assume are integers are actually integers. It turns out that while we assumed everything was integers, in actuality it wasn't.\n\"\"\"\ndf.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all())\n\"\"\"\n# Once we know that we have many issues with Strings, we have to drop the columns that have no data associated with them\n\"\"\"\ndf.drop(df.loc[df['Trading across Borders - Time to export: Documentary compliance (hours) (DB16-19 methodology)']=='No Practice'].index, inplace=True)\ndf.drop(df.loc[df['Rank-Trading across borders (DB19)']== ' '].index, inplace=True)\n\"\"\"\n# After this stage, it turns out that all the columns are properly stored as integers which allows us to continue wrangling\n\"\"\"\ndf.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all())\n\"\"\"\n# Aside from economy and year which are fine as strings, everything is now an integer\n\"\"\"\n\"\"\"\n# I found my minimum values which contained some of the outliers, and dropped those from the entire dataset to see if I could get more accurate readings. \n\"\"\"\ntemp = df['Ease of doing business score global (DB17-19 methodology)'].idxmin()\ndf.drop(df.loc[df['Economy']== 'Tonga'].index, inplace=True)\ndf.drop(df.loc[df['Economy']== 'Trinidad and Tobago'].index, inplace=True)\n\"\"\"\n# After running my boxplot again without the outliers, not much changed when I omitted the outliers, but that's alright. \n\"\"\"\nfig1, ax1 = plt.subplots()\nax1.set_title('Basic Plot')\nax1.boxplot(df['Ease of doing business score global (DB17-19 methodology)'], showfliers = False)\n\"\"\"\n# I was curious to see at least one other distribution and boxplot to see how they were distributed, so I decided to check out time to export across borders, and interestingly enough it was not as nicely distributed as the other column was.\n\"\"\"\nfig1, ax1 = plt.subplots()\nax1.set_title('Basic Plot')\nax1.boxplot(df['Trading across Borders - Time to export: Documentary compliance (hours) (DB16-19 methodology)'].astype(np.float))\n\"\"\"\n# And then just to check out the histogram of that column as well, it is not well distributed, and is very right skewed.\n\"\"\"\nplt.hist(df['Trading across Borders - Time to export: Documentary compliance (hours) (DB16-19 methodology)'].astype(np.float))\n\"\"\"\n### But clearly from here, just because some columns of your data are nicely distributed, it doesn't mean that all the columns of the data are going to be normally distributed.\n\"\"\"\n\"\"\"\n# Finally, just to get a better look at some of my statistics of the dataset one last time now that it's been wrangled, I had to describe it all leaving out duplicates. It turns out that hte top 25% aren't so far from each other in terms of score, and it doesn't make the biggest difference whether you're at the top or at the 75% mark. \n\"\"\"\ndf.describe()\n\"\"\"\n# Finally, I wanted to enjoy some of my hardwork and see just how correlated the tariffs were to the overall score of the specific country\n\"\"\"\ndf[pd.to_numeric(df['Ease of doing business rank global (DB19)'], errors = 'coerce').notnull()]\ncorr = df['Score-Trading across borders(DB16-19 methodology)'].corr(df['Ease of doing business score global (DB17-19 methodology)'])\nprint(corr)\n\"\"\"\n# Conclusion: After wrangling through the dataset and running some basic correlation statistics on my dataset I could enjoy the fruits of my labor and see that there was strong correlation betweeen the ease of trading across borders as well as the overall ranking of a country's business plan.  \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6fd43e29fc1136'}"}
{"id":"19281","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom xgboost import XGBClassifier\nfrom catboost import CatBoostClassifier\nfrom sklearn.metrics import accuracy_score, roc_auc_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, BaggingClassifier, AdaBoostClassifier\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\ntrain = pd.read_csv(\"..\/input\/flight-delays-fall-2018\/flight_delays_train.csv.zip\", compression='zip')\ntest = pd.read_csv(\"..\/input\/flight-delays-fall-2018\/flight_delays_test.csv.zip\", compression='zip')\n\ntrain.head()\ntest.head()\ntrain.info()\nprint('-'*45)\ntest.info()\ntrain.describe()\n# list of columns with missing values apart from target within test set\ntrain.columns[train.isna().any()]\nall_data = pd.concat([train, test], ignore_index=True)\n# change target name to make it easier\ntrain = train.rename(columns={'dep_delayed_15min':'delayed'})\nall_data = all_data.rename(columns={'dep_delayed_15min':'delayed'})\n# change target to numerical N-->0 & Y-->1\ntrain.loc[(train.delayed == 'N'), 'delayed'] = 0\ntrain.loc[(train.delayed == 'Y'), 'delayed'] = 1\nall_data.loc[(all_data.delayed == 'N'), 'delayed'] = 0\nall_data.loc[(all_data.delayed == 'Y'), 'delayed'] = 1\n\"\"\"\n# Exploratory Data Analysis & Data Cleaning\n\"\"\"\n\"\"\"\n## 1- Month\n\"\"\"\n\"\"\"\n* Let's first change the format of the variable to an int\n\"\"\"\ntrain.Month = train.Month.str.slice(start=2).astype(int)\nall_data.Month = all_data.Month.str.slice(start=2).astype(int)\nfig, ax = plt.subplots(1, 2, figsize=(18,5))\nsns.countplot('Month', data=train, ax=ax[0])\nax[0].set_title('Nb of flights by month')\nsns.countplot('Month', hue='delayed', data=train, ax=ax[1])\nax[1].set_title('Delayed\/Not delayed flights by month')\nplt.figure(figsize=(18,5))\nsns.barplot('Month', 'delayed', data=train)\nplt.show()\n\"\"\"\n* We can see that the number of flights and delays are pretty much the same for all months. However there is a slightly higher rate of delays in June, July and December maybe due to vacation time\n* We will also try to reformat this variable into 1-12 instead of c1-c12 and int type\n\"\"\"\n\"\"\"\n## 2- Day of Month\n\"\"\"\n\"\"\"\n* Again, let's first format the variable\n\"\"\"\ntrain.DayofMonth = train.DayofMonth.str.slice(start=2).astype(int)\nall_data.DayofMonth = all_data.DayofMonth.str.slice(start=2).astype(int)\nfig, ax = plt.subplots(3, 1, figsize=(15,15))\nsns.countplot('DayofMonth', data=train, ax=ax[0])\nax[0].set_title('Nb of flights by day of month')\nsns.countplot('DayofMonth', hue='delayed', data=train, ax=ax[1])\nax[1].set_title('Delayed\/not Delayed flight by day of month')\nsns.barplot('DayofMonth', 'delayed', data=train, ax=ax[2])\nax[2].set_title('Rate of delayed flights by day of month')\n\"\"\"\n* Again it's hard to say if there is much of a difference between the days of the month. However, we can say that in the last days of the month the delay rate is higher\n\"\"\"\n\"\"\"\n## 3- Day of Week\n\"\"\"\n\"\"\"\n* First let's format the variable\n\"\"\"\ntrain.DayOfWeek = train.DayOfWeek.str.slice(start=2).astype(int)\nall_data.DayOfWeek = all_data.DayOfWeek.str.slice(start=2).astype(int)\nfig, ax = plt.subplots(1, 3, figsize=(15,5))\nsns.countplot('DayOfWeek', data=train, ax=ax[0])\nax[0].set_title('Nb of flights by day of week')\nsns.countplot('DayOfWeek', hue='delayed', data=train, ax=ax[1])\nax[1].set_title('Delayed or not flights by day of week')\nsns.barplot('DayOfWeek', 'delayed', data=train, ax=ax[2])\nax[2].set_title('Rate of delayed flights by day of week')\n\n\"\"\"\n* Here we can see that Thursday and Friday have the highest rates of delayed flights where as Tuesday, Wednesday and Saturday have the lowest\n\"\"\"\n\"\"\"\n## 4- Departure Time\n\"\"\"\nplt.hist(train.DepTime)\nplt.xlabel('Departure Time')\n\"\"\"\n* We will come back to this variable once we bin it because of the large spectrum of values\n\"\"\"\n\"\"\"\n## 5- Unique Carrier\n\"\"\"\n# Nb of unique values\nlen(set(train.UniqueCarrier))\nfig, ax = plt.subplots(3, 1, figsize=(15,15))\nsns.countplot('UniqueCarrier', data=train, ax=ax[0])\nax[0].set_title('Nb of flights per unique carrier')\nsns.countplot('UniqueCarrier', hue='delayed', data=train, ax=ax[1])\nax[1].set_title('Nb of delayed\/not flights by unique carrier')\nsns.barplot('UniqueCarrier', 'delayed', data=train, ax=ax[2])\nax[2].set_title('Rate of delayed flights by unique carrier')\n\"\"\"\n* We can see that the Unique carrier variable can have a good role in the delays\n\"\"\"\n\"\"\"\n## 6- Origin\/Destination\n\"\"\"\n# Nb of unique values\nprint(len(set(train.Origin)))\nprint(len(set(train.Dest)))\n\"\"\"\n* Too many categorical values to plot. Maybe it would be a good idea to create a variable with routes Origin - Destination\n\"\"\"\n\"\"\"\n## 7- Distance\n\"\"\"\nplt.hist(train.Distance)\nplt.xlabel('Distance')\n\"\"\"\n* We can see that most of the flights are short in distance and less than 1000 miles\n* Would it be a good idea to normalize and\/or scale this variable or is the difference more meaningful this way?\n* Maybe bin this variable?\n\"\"\"\n\"\"\"\n# Feature Engineering\n\"\"\"\n\"\"\"\n## 1- New features\n\"\"\"\nall_data['Route'] = all_data['Origin'] + all_data['Dest']\nall_data['UniqueCarrier_Origin'] = all_data['UniqueCarrier'] + \"_\" + all_data['Origin']\nall_data['UniqueCarrier_Dest'] = all_data['UniqueCarrier'] + \"_\" + all_data['Dest']\nall_data['is_weekend'] = (all_data['DayOfWeek'] == 6) | (all_data['DayOfWeek'] == 7)\n# Hour and minute\nall_data['hour'] = all_data['DepTime'] \/\/ 100\nall_data.loc[all_data['hour'] == 24, 'hour'] = 0\nall_data.loc[all_data['hour'] == 25, 'hour'] = 1\nall_data['minute'] = all_data['DepTime'] % 100\n# give more importance to hour variable\nall_data['hour_sq'] = all_data['hour'] ** 2\nall_data['hour_sq2'] = all_data['hour'] ** 4\n\"\"\"\n## 2- Binning\n\"\"\"\n\"\"\"\n#### Season\n\"\"\"\nall_data['summer'] = (all_data['Month'].isin([6, 7, 8]))\nall_data['autumn'] = (all_data['Month'].isin([9, 10, 11]))\nall_data['winter'] = (all_data['Month'].isin([12, 1, 2]))\nall_data['spring'] = (all_data['Month'].isin([3, 4, 5]))\n\"\"\"\n#### Departure Time\n\"\"\"\nall_data['DayTime'] = 0\nall_data.loc[all_data.DepTime <= 600 , 'DepTime_bin'] = 'Night'\nall_data.loc[(all_data.DepTime > 600) & (all_data.DepTime <= 1200), 'DepTime_bin'] = 'Morning'\nall_data.loc[(all_data.DepTime > 1200) & (all_data.DepTime <= 1800), 'DepTime_bin'] = 'Afternoon'\nall_data.loc[(all_data.DepTime > 1800) & (all_data.DepTime <= 2600), 'DepTime_bin'] = 'Evening'\n\nall_data['DepTime_bin'] = 0\nall_data.loc[all_data.DepTime <= 600 , 'DepTime_bin'] = 'vem'\nall_data.loc[(all_data.DepTime > 600) & (all_data.DepTime <= 900), 'DepTime_bin'] = 'm'\nall_data.loc[(all_data.DepTime > 900) & (all_data.DepTime <= 1200), 'DepTime_bin'] = 'mm'\nall_data.loc[(all_data.DepTime > 1200) & (all_data.DepTime <= 1500), 'DepTime_bin'] = 'maf'\nall_data.loc[(all_data.DepTime > 1500) & (all_data.DepTime <= 1800), 'DepTime_bin'] = 'af'\nall_data.loc[(all_data.DepTime > 1800) & (all_data.DepTime <= 2100), 'DepTime_bin'] = 'n'\nall_data.loc[(all_data.DepTime > 2100) & (all_data.DepTime <= 2400), 'DepTime_bin'] = 'nn'\nall_data.loc[all_data.DepTime > 2400, 'DepTime_bin'] = 'lm'\nall_data = all_data.drop(['DepTime'], axis=1)\n\"\"\"\n#### Distance\n\"\"\"\nall_data['Dist_bin'] = 0\nall_data.loc[all_data.Distance <= 500 , 'Dist_bin'] = 'vshort'\nall_data.loc[(all_data.Distance > 500) & (all_data.Distance <= 1000), 'Dist_bin'] = 'short'\nall_data.loc[(all_data.Distance > 1000) & (all_data.Distance <= 1500), 'Dist_bin'] = 'mid'\nall_data.loc[(all_data.Distance > 1500) & (all_data.Distance <= 2000), 'Dist_bin'] = 'midlong'\nall_data.loc[(all_data.Distance > 2000) & (all_data.Distance <= 2500), 'Dist_bin'] = 'long'\nall_data.loc[all_data.Distance > 2500, 'Dist_bin'] = 'vlong'\nall_data = all_data.drop(['Distance'], axis=1)\n\"\"\"\n# Predictive Modeling\n\"\"\"\nnew_train = all_data.iloc[:100000]\nnew_test = all_data.iloc[100000:]\nfeature_columns = list(new_train.columns)\nfeature_columns.remove('delayed')\nX = new_train[feature_columns]\ny = new_train.delayed\n\n#split data\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size= 0.2, random_state=1)\n\"\"\"\n## Catboost\n\"\"\"\nall_data.head()\nfeature_columns\nmodel_ctb = CatBoostClassifier(iterations=3000, loss_function='Logloss',\n                               l2_leaf_reg=0.8, od_type='Iter',\n                               random_seed=17, silent=True)\n#model_ctb = GridSearchCV(model_ctb, {'learning_rate':[0.5, 0.1], 'n_estimators':[500, 1000]})\nmodel_ctb.fit(X_train, y_train.astype(int), cat_features=[2, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20])\npredictions = model_ctb.predict_proba(X_val)[:, 1]\naccuracy = roc_auc_score(y_val.astype(int), predictions)\nprint('Accuracy Catboost: ', accuracy)\n\"\"\"\n# Results\n\"\"\"\nmodel_ctb.fit(X, y.astype(int), cat_features=[2, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20])\nsample = pd.read_csv(\"..\/input\/flight-delays-fall-2018\/sample_submission.csv.zip\", compression='zip')\nsample.head()\npredictions = model_ctb.predict_proba(new_test[feature_columns])[:, 1]\nsubmission = pd.DataFrame({'id':range(100000),'dep_delayed_15min':predictions})\nsubmission.head(900)\nfilename = 'flight_delay.csv'\n\nsubmission.to_csv(filename,index=False)\n\nprint('Saved file: ' + filename)","meta":"{'source': 'AI4Code', 'id': '2348d6a580efc4'}"}
{"id":"63026","text":"\"\"\"\nHi! This is a try to group responses into Factors. \nIs my first Kernel so I am open to suggestions for improvement\n\"\"\"\n#Librerias\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt \n#Data\ndf = pd.read_csv(\"..\/input\/young-people-survey\/responses.csv\")\ndf.shape\n\"\"\"\nMUSIC PREFERENCES (19) 0:19\n\nMOVIE PREFERENCES (12) 19:31\n\nHOBBIES & INTERESTS (32) 31:63\n\nPHOBIAS (10) 63:73\n\nHEALTH HABITS (3) 73:76\n\nPERSONALITY TRAITS, VIEWS ON LIFE & OPINIONS (57) 76:133\n\nSPENDING HABITS (7) 133:140\n\nDEMOGRAPHICS (10 ) 140:150\n\"\"\"\n\"\"\"\nI will take only: PERSONALITY TRAITS, VIEWS ON LIFE & OPINIONS (57) 76:133\n\"\"\"\ndf = df.iloc[:, 76:133]\ndf.head(5)\n\"\"\"\n# 1. Prepare the data\n\"\"\"\n#Drop NAs\ndf = df.dropna()\n#...............................................................................................\n#Encode categorical data\nfrom sklearn.preprocessing import LabelEncoder\n\ndf = df.apply(LabelEncoder().fit_transform)\n\n\"\"\"\n# 2. Choose the factors \n\"\"\"\npip install factor_analyzer \n#Try the model with all the variables \nfrom factor_analyzer import FactorAnalyzer         # pip install factor_analyzer \nfa = FactorAnalyzer(rotation=\"varimax\")\nfa.fit(df) \n\n# Check Eigenvalues\nev, v = fa.get_eigenvalues()\nev\n\n# Create scree plot using matplotlib\nplt.scatter(range(1,df.shape[1]+1),ev)\nplt.plot(range(1,df.shape[1]+1),ev)\nplt.title('Scree Plot')\nplt.xlabel('Factors')\nplt.ylabel('Eigenvalue')\nplt.grid()\nplt.show()\n\"\"\"\nAs you can see the most usefull factors for explain the data are between 5-6 until falling significantly.\n\nWe will fit the model with 5 Factors: \n\"\"\"\n#Factor analysis with 5 Factors\nfa = FactorAnalyzer(5, rotation=\"varimax\")\nfa.fit(df)\nAF = fa.loadings_\nAF = pd.DataFrame(AF)\nAF.index = df.columns\nAF\n#Get Top variables for each Factor \nF = AF.unstack()\nF = pd.DataFrame(F).reset_index()\nF = F.sort_values(['level_0',0], ascending=False).groupby('level_0').head(5)    # Top 5 \nF = F.sort_values(by=\"level_0\")\nF.columns=[\"FACTOR\",\"Variable\",\"Varianza_Explica\"]\nF = F.reset_index().drop([\"index\"],axis=1)\nF\n#Show the Top for each Factor \nF = F.pivot(columns='FACTOR')[\"Variable\"]\nF.apply(lambda x: pd.Series(x.dropna().to_numpy()))\n\"\"\"\nFACTOR 1: Energy levels, Number of friends, Socializing...\n\nCould be: Extraversion\n\"\"\"\n\"\"\"\nFACTOR 2: Self-ciricism, Fake, Loneliness... \n\nLooks very similar to \"Neuroticism\"\n\"\"\"\n\"\"\"\nFactor 3: Thinking ahead, Prioritising workload...\n\nvery similar to \"Conscientiousness\"\n\"\"\"\n\"\"\"\nFactor 4: Children, God, Finding lost valuables\n\nThis factor could be something like \"religious\" or \"conservative\", maybe have lowest scores of a \"Openness\" in Big Five model. \n\"\"\"\n\"\"\"\nFactor 5: Appearence and gestures, Mood swings\n\nMmmm it could be \"Agreeableness\". What do you think it could be represent?\n\"\"\"\n\"\"\"\n# Conclusion: \nThe first three Factors are very clear: Extraversion, Neuroticism and Conscientiousness.\nThe other two not to much. Anyway is a very  interesting approximation\n\nMaybe doing first a PCA for remove hight correlate variables like \"God\" and \"Final judgement\"could help.\n\nWhat do you think? \n\nThanks you!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '742efd02817e85'}"}
{"id":"134397","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nprint(os.listdir(\"..\/input\"))\n# os.listdir('..\/input\/image-3jhn-chunk2\/image_3jhn_chunk2\/Image_3JHN_chunk2')\ntrain = pd.read_csv('..\/input\/champs-scalar-coupling\/train.csv')\ntest = pd.read_csv('..\/input\/champs-scalar-coupling\/test.csv')\nimage_path = [\n    '..\/input\/image-3jhn-chunk1\/image_3jhn_chunk1\/Image_3JHN_chunk1\/',\n    '..\/input\/image-3jhn-chunk2\/image_3jhn_chunk2\/Image_3JHN_chunk2\/'\n]\n\ndescription = []\nfor i, path in enumerate(image_path):\n    files = [f for f in os.listdir(path) if f.endswith('.pkl')]\n    ids = [int(f.split('_')[2].strip('.pkl')) for f in files]\n    \n    desc = train[train['id'].isin(ids)].copy()\n    desc['filename'] = path + desc['molecule_name'] + '_' + desc['id'].astype(str) + '.pkl'\n\n    description.append(desc)\n\ndescription = pd.concat(description)\ndescription.shape\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n# check if CUDA is available\ntrain_on_gpu = torch.cuda.is_available()\n\nif not train_on_gpu:\n    print('CUDA is not available.  Training on CPU ...')\nelse:\n    print('CUDA is available!  Training on GPU ...')\n\n# set seed\ntorch.manual_seed(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nnp.random.seed(0)\n\"\"\"\n### 1. Dataloader\n source: https:\/\/pytorch.org\/tutorials\/beginner\/data_loading_tutorial.html\n\"\"\"\nimport pickle\nimport os\nimport pandas as pd\nfrom torch.utils.data import Dataset, DataLoader\n\nclass CustomImageDataset(Dataset):\n   \n    def __init__(self, csv_file, transform=None):\n        self.df = csv_file # pd.read_csv(root_dir + csv_file)\n#         self.root_dir = root_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        \n        img_name = self.df.iloc[idx]['filename']\n        \n#         img_name = os.path.join(\n#             self.root_dir,\n#             str(self.df.iloc[idx]['molecule_name']) + '_' + str(self.df.iloc[idx]['id']) + '.pkl'\n#         )\n        \n        with open (img_name, 'rb') as fp:\n            image = pickle.load(fp)\n        \n        for c in range(5):\n            image[c] = np.clip(image[c], 0, 255) \/ 255\n        \n        img = torch.from_numpy(np.array(image))\n        img = img.type(torch.FloatTensor)\n        \n        sample = {'image': img,\n                  'target': self.df.iloc[idx]['scalar_coupling_constant']}\n\n        if self.transform:\n            sample['image'] = self.transform(sample['image'])\n\n        return sample['image'], sample['target']\nimage_dataset = CustomImageDataset(csv_file=description)\n\"\"\"\n## 2. Cross validation\n\"\"\"\nfrom sklearn.model_selection import GroupKFold\ngroup_kfold = GroupKFold(n_splits=5)\n\ndf = description.copy()\ndf.reset_index(drop=True, inplace=True)\n\nX = df[['id', 'molecule_name']].copy()\ny = df['scalar_coupling_constant']\ngroups = df['molecule_name'].unique()\n\nfolds = []\nfor train_idx, valid_idx in group_kfold.split(X, y, X['molecule_name']):\n    folds.append([train_idx, valid_idx])\nindex_fold = 0\n# from torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n# number of subprocesses to use for data loading\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 40\n\n# convert data to a normalized torch.FloatTensor\ntransform = transforms.Compose([\n    transforms.Normalize((0.5, 0.5, 0.5, 0.5, 0.5), (0.5, 0.5, 0.5, 0.5, 0.5))\n    ])\n\ntrain_data = CustomImageDataset(\n    csv_file=description\n#     transform=transform\n)\n\ntrain_idx, valid_idx = folds[index_fold][0], folds[index_fold][1]\n\n# define samplers for obtaining training and validation batches\ntrain_sampler = SubsetRandomSampler(train_idx)\nvalid_sampler = SubsetRandomSampler(valid_idx)\n\n# prepare data loaders (combine dataset and sampler)\ntrain_loader = torch.utils.data.DataLoader(train_data,\n                                           batch_size=batch_size,\n                                           sampler=train_sampler,\n                                           num_workers=num_workers\n                                          )\nvalid_loader = torch.utils.data.DataLoader(train_data,\n                                           batch_size=batch_size, \n                                           sampler=valid_sampler,\n                                           num_workers=num_workers\n                                          )\nclass CNN(nn.Module):\n    \"\"\"CNN.\"\"\"\n\n    def __init__(self):\n        \"\"\"CNN Builder.\"\"\"\n        super(CNN, self).__init__()\n\n        self.conv_layer = nn.Sequential(\n\n            # Conv Layer block 1\n            nn.Conv2d(in_channels=5, out_channels=20, kernel_size=3, padding=1),\n            nn.BatchNorm2d(20),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(in_channels=20, out_channels=20, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n            nn.Dropout2d(p=0.1),\n\n            # Conv Layer block 2\n            nn.Conv2d(in_channels=20, out_channels=35, kernel_size=3, padding=1),\n            nn.BatchNorm2d(35),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(in_channels=35, out_channels=35, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n            nn.Dropout2d(p=0.1),\n\n            # Conv Layer block 3\n            nn.Conv2d(in_channels=35, out_channels=50, kernel_size=3, padding=1),\n            nn.BatchNorm2d(50),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(in_channels=50, out_channels=50, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n            nn.Dropout2d(p=0.1),\n        )\n\n        self.fc_layer = nn.Sequential(\n#             nn.Dropout(p=0.3),\n            nn.Linear(800, 600),\n            nn.ReLU(inplace=True),\n            nn.Dropout(p=0.3),\n            nn.Linear(600, 300),\n            nn.ReLU(inplace=True),\n            nn.Dropout(p=0.3),\n            nn.Linear(300, 1)\n        )\n\n    def forward(self, x):\n        x = self.conv_layer(x)\n        x = x.view(x.size(0), -1)\n        x = self.fc_layer(x)\n        return x\n# import os\n# os.listdir('..\/input\/model-1-fold3')\n# create a complete CNN\nmodel = CNN()\nprint(model)\n\n# model.load_state_dict(torch.load('..\/input\/model-1-fold4\/model_best.pt'))\n\n# move tensors to GPU if CUDA is available\nif train_on_gpu:\n    model.cuda()\nimport torch.optim as optim\n\n# specify loss function (categorical cross-entropy)\ncriterion = nn.MSELoss()\nmae = nn.L1Loss()\n\n# specify optimizer\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n# number of epochs to train the model\nimport time\nn_epochs = 150\nloss_per_iter = []\nstart_time = time.time()\n\nvalid_loss_min = np.Inf     # track change in validation loss\nvalid_mae_loss_min = np.Inf # track change in validation loss\n\noutput_file_nb = 0\nmax_output_file_nb = 200\n\nfor epoch in range(1, n_epochs+1):\n\n    if (time.time() - start_time) \/ 3600 > 3 or (output_file_nb > max_output_file_nb):\n        output_file_nb += 1\n        print('Last iteration ({:.6f} --> {:.6f}).  Saving model ...'.format(\n        valid_loss_min, valid_loss))\n        torch.save(model.state_dict(), 'model_last.pt')\n        break\n    \n    # keep track of training and validation loss\n    train_loss = 0.0\n    valid_loss = 0.0\n    valid_mae_loss = 0.0\n    \n    ###################\n    # train the model #\n    ###################\n    model.train()\n    for ind, (data, target) in enumerate(train_loader):\n        print(ind, end='\\r')\n        \n        if train_on_gpu:\n            data, target = data.cuda(), target.cuda()\n        \n        optimizer.zero_grad()\n        output = model(data)\n        \n        loss = criterion(output.view(data.shape[0]), target.float())\n#         mae_score = mae(output.view(data.shape[0]), target.float())\n        \n        loss.backward()\n        optimizer.step()\n    \n        train_loss += loss.item() * data.size(0)\n        \n#         mae_train_loss +=  mae_score.item() * data.size(0)\n        \n        \n    ######################    \n    # validate the model #\n    ######################\n    model.eval()\n    for data, target in valid_loader:\n        # move tensors to GPU if CUDA is available\n        if train_on_gpu:\n            data, target = data.cuda(), target.cuda()\n\n        # forward pass: compute predicted outputs by passing inputs to the model\n        output = model(data)    \n        loss = criterion(output.view(data.shape[0]), target.float())    \n        valid_loss += loss.item() * data.size(0)\n        \n        mae_loss = mae(output.view(data.shape[0]), target.float())    \n        valid_mae_loss += mae_loss.item() * data.size(0)\n \n    # calculate average losses\n    train_loss = train_loss \/ len(train_loader.sampler)\n    valid_loss = valid_loss \/ len(valid_loader.sampler)\n    valid_mae_loss = valid_mae_loss \/ len(valid_loader.sampler)\n    \n    # print training\/validation statistics \n    print('Epoch: {} \\tTr. Loss: {:.6f} \\tVal. Loss: {:.6f} \\tMae: {:.6f}'.format(\n        epoch, train_loss, valid_loss, valid_mae_loss))\n    \n    loss_per_iter.append([train_loss, valid_loss, valid_mae_loss])\n    \n    # save model if validation loss has decreased\n    if valid_loss <= valid_loss_min:\n        output_file_nb += 1\n        print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(\n        valid_loss_min,\n        valid_loss))\n        torch.save(model.state_dict(), f'model_best.pt')\n        valid_loss_min = valid_loss\n        \n        if epoch > 20:\n            output_file_nb += 1\n            torch.save(model.state_dict(), f'model_t{round(train_loss, 3)}_v{round(valid_loss, 3)}_mae{round(valid_mae_loss, 3)}_ep{epoch}.pt')\n        \n    elif valid_loss <= 1.1 * valid_loss_min and epoch > 20:\n        output_file_nb += 1\n        print('Validation loss saved at ({:.6f}).  Saving model ...'.format(valid_loss))\n        torch.save(model.state_dict(), f'model_t{round(train_loss, 3)}_v{round(valid_loss, 3)}_mae{round(valid_mae_loss, 3)}_ep{epoch}.pt')\n    \n    elif valid_mae_loss <= 1.1 * valid_mae_loss_min and epoch > 20:\n        output_file_nb += 1\n        print('Validation loss saved at ({:.6f}).  Saving model ...'.format(valid_loss))\n        torch.save(model.state_dict(), f'model_t{round(train_loss, 3)}_v{round(valid_loss, 3)}_mae{round(valid_mae_loss, 3)}_ep{epoch}.pt')\n        \n    if valid_mae_loss < valid_mae_loss_min:\n        valid_mae_loss_min = valid_mae_loss\n        \nimport matplotlib.pyplot as plt\nplt.figure(figsize=(14,8))\nplt.plot(np.array(loss_per_iter)[:, 0], 'o-', label = 'train')\nplt.plot(np.array(loss_per_iter)[:, 1], 'o-', label = 'valid')\nplt.legend()\nplt.show()\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(14,8))\nplt.plot(np.array(loss_per_iter)[-50:, 0], 'o-', label = 'train')\nplt.plot(np.array(loss_per_iter)[-50:, 1], 'o-', label = 'valid')\nplt.legend()\nplt.show()\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(14,8))\nplt.plot(np.array(loss_per_iter)[:, 2], 'o-', label = 'mae')\nplt.legend()\nplt.show()\nprint(np.array(loss_per_iter)[:, 0].min())\nprint(np.array(loss_per_iter)[:, 1].min())\nprint(np.array(loss_per_iter)[:, 2].min())","meta":"{'source': 'AI4Code', 'id': 'f71f806a37ff96'}"}
{"id":"82318","text":"\"\"\"\nThis Kernel is based on this amazing [\u26a1Plant2021 PyTorch Lightning Starter [ Training ]\u26a1](https:\/\/www.kaggle.com\/pegasos\/plant2021-pytorch-lightning-starter-training) by [Sh1r0](https:\/\/www.kaggle.com\/pegasos). This kernel is intended to showcase [Weights and Biases](https:\/\/wandb.ai\/site) integration with PyTorch Lightning. \n\n# \u26a1 PyTorch Lightning\n\nPyTorch is an extremely powerful framework for your deep learning research. But once the research gets complicated and things like 16-bit precision, multi-GPU training, and TPU training get mixed in, users are likely to introduce bugs. **PyTorch Lightning lets you decouple research from engineering.**\n\n**PyTorch Lightning \u26a1 is not another framework but a style guide for PyTorch.**\n\nTo learn more about PyTorch Lightning check out my blog posts at Weights and Biases [Fully Connected](https:\/\/wandb.ai\/fully-connected):\n\n* [Image Classification using PyTorch Lightning](https:\/\/wandb.ai\/wandb\/wandb-lightning\/reports\/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY)\n* [Transfer Learning Using PyTorch Lightning](https:\/\/wandb.ai\/wandb\/wandb-lightning\/reports\/Transfer-Learning-Using-PyTorch-Lightning--VmlldzoyODk2MjA)\n* [Multi-GPU Training Using PyTorch Lightning](https:\/\/wandb.ai\/wandb\/wandb-lightning\/reports\/Multi-GPU-Training-Using-PyTorch-Lightning--VmlldzozMTk3NTk)\n\n# <img src=\"https:\/\/i.imgur.com\/gb6B4ig.png\" width=\"400\" alt=\"Weights & Biases\" \/>\n\nWeights & Biases helps you build better models faster with a central dashboard for your machine learning projects. It not only logs your training metrics but can log hyperparameters and output metrics, then visualize and compare results and quickly share findings with your team mates. Track everything you need to make your models reproducible with Weights & Biases\u2014 from hyperparameters and code to model weights and dataset versions. \n\n### [Check this Kaggle kernel to learn more about Weights and Biases$\\rightarrow$](https:\/\/www.kaggle.com\/ayuraj\/experiment-tracking-with-weights-and-biases)\n![img](https:\/\/i.imgur.com\/BGgfZj3.png)\n\n# PyTorch Lightning + Weights and Biases \n\nPyTorch Lightning provides a lightweight wrapper for organizing your PyTorch code and easily adding advanced features such as distributed training and 16-bit precision. W&B provides a lightweight wrapper for logging your ML experiments. It is incorporated directly into the PyTorch Lightning library, so you can check out [their documentation](https:\/\/pytorch-lightning.readthedocs.io\/en\/stable\/extensions\/generated\/pytorch_lightning.loggers.WandbLogger.html#pytorch_lightning.loggers.WandbLogger) for the API and reference info.\n\n### Use the intergration in few lines of code.\n\n```\nfrom pytorch_lightning.loggers import WandbLogger  # newline 1\nfrom pytorch_lightning import Trainer\n\nwandb_logger = WandbLogger()  # newline 2\ntrainer = Trainer(logger=wandb_logger)\n```\n\n[![thumbnail](https:\/\/i.imgur.com\/M7xZ04g.png)](https:\/\/www.youtube.com\/watch?v=hUXQm46TAKc)\n\n\"\"\"\n\"\"\"\n# \ud83e\uddf0 Imports and Setups\n\"\"\"\n!pip install --upgrade -q wandb\n\n# Install timm \n!pip install -q timm\n\"\"\"\n## Import WandbLogger\n\nCoupled with [Weights & Biases integration](https:\/\/docs.wandb.com\/library\/integrations\/lightning), you can quickly train and monitor models for full traceability and reproducibility with only 2 extra lines of code:\n\n```python\nfrom pytorch_lightning.loggers import WandbLogger\nwandb_logger = WandbLogger()\n```\nCheck out the documentation [here](https:\/\/pytorch-lightning.readthedocs.io\/en\/stable\/extensions\/generated\/pytorch_lightning.loggers.WandbLogger.html#pytorch_lightning.loggers.WandbLogger).\n\n\"\"\"\nimport wandb\nfrom pytorch_lightning.loggers import WandbLogger\n\nwandb.login()\nimport cv2\nimport timm\nimport torch\nimport numpy as np\nimport pandas as pd\n\nimport torch.nn as nn\nimport albumentations as A\nimport pytorch_lightning as pl\nimport matplotlib.pyplot as plt\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom albumentations.core.composition import Compose, OneOf\nfrom albumentations.augmentations.transforms import CLAHE, GaussNoise, ISONoise\nfrom albumentations.pytorch import ToTensorV2\n\nfrom pytorch_lightning import Trainer, seed_everything\nfrom pytorch_lightning import Callback\nfrom pytorch_lightning.loggers import CSVLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping\n\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n# \ud83d\udcc0 Hyperparameters\n\"\"\"\n# Config dictionary that will be logged to W&B.\nCONFIG = dict (\n    seed = 42,\n    train_val_split = 0.2,\n    model_name = 'resnet50',\n    pretrained = True,\n    img_size = 256,\n    num_classes = 12,\n    lr = 5e-4,\n    min_lr = 1e-6,\n    t_max = 20,\n    num_epochs = 10,\n    batch_size = 32,\n    accum = 1,\n    precision = 16,\n    n_fold = 5,\n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n)\n\n# Directories\nPATH = \"..\/input\/plant-pathology-2021-fgvc8\/\"\n\nimage_size = CONFIG['img_size']\nTRAIN_DIR = f'..\/input\/resized-plant2021\/img_sz_{image_size}\/'\nTEST_DIR = PATH + 'test_images\/'\n\n# Seed everything\nseed_everything(CONFIG['seed'])\n\"\"\"\n# \ud83d\udd27 DataModule\n\"\"\"\n# Read CSV file\ndf = pd.read_csv(PATH + \"train.csv\")\n\n# Label encode \nlabels = list(df['labels'].value_counts().keys())\nlabels_dict = dict(zip(labels, range(12)))\ndf = df.replace({\"labels\": labels_dict})\ndf.head()\nclass PlantDataset(Dataset):\n    def __init__(self, df, transform=None):\n        self.image_id = df['image'].values\n        self.labels = df['labels'].values\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.labels)\n\n    def __getitem__(self, idx):\n        image_id = self.image_id[idx]\n        label = self.labels[idx]\n        \n        image_path = TRAIN_DIR + image_id\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        augmented = self.transform(image=image)\n        image = augmented['image']\n        return {'image':image, 'target': label}\nclass PlantDataModule(pl.LightningDataModule):\n    def __init__(self, batch_size, data_dir: str = '.\/'):\n        super().__init__()\n        self.batch_size = batch_size\n        \n        # Train augmentation policy\n        self.train_transform = Compose([\n            A.RandomResizedCrop(height=CONFIG['img_size'], width=CONFIG['img_size']),\n            A.HorizontalFlip(p=0.5),\n            A.ShiftScaleRotate(p=0.5),\n            A.RandomBrightnessContrast(p=0.5),\n            A.Normalize(),\n            ToTensorV2(),\n        ])\n\n        # Validation\/Test augmentation policy\n        self.test_transform = Compose([\n            A.Resize(height=CONFIG['img_size'], width=CONFIG['img_size']),\n            A.Normalize(),\n            ToTensorV2(),\n        ])\n        \n\n    def setup(self, stage=None):\n        # Assign train\/val datasets for use in dataloaders\n        if stage == 'fit' or stage is None:\n            # Random train-validation split\n            train_df, valid_df = train_test_split(df, test_size=CONFIG['train_val_split'])\n            \n            # Train dataset\n            self.train_dataset = PlantDataset(train_df, self.train_transform)\n            # Validation dataset\n            self.valid_dataset = PlantDataset(valid_df, self.test_transform)\n                        \n    def train_dataloader(self):\n        return DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=4, drop_last=True)\n\n    def val_dataloader(self):\n        return DataLoader(self.valid_dataset, batch_size=self.batch_size, num_workers=4)\n\"\"\"\n# \ud83c\udfba LightningModule - Define the System\n\"\"\"\nclass CustomResNet(nn.Module):\n    def __init__(self, model_name='resnet18', pretrained=False):\n        super().__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained)\n        in_features = self.model.get_classifier().in_features\n        self.model.fc = nn.Linear(in_features, CONFIG['num_classes'])\n\n    def forward(self, x):\n        x = self.model(x)\n        return x\nclass LitCassava(pl.LightningModule):\n    def __init__(self, model):\n        super(LitCassava, self).__init__()\n        self.model = model\n        self.metric = pl.metrics.F1(num_classes=CONFIG['num_classes'])\n        self.criterion = nn.CrossEntropyLoss()\n        self.lr = CONFIG['lr']\n\n    def forward(self, x, *args, **kwargs):\n        return self.model(x)\n\n    def configure_optimizers(self):\n        self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)\n        self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer, T_max=CONFIG['t_max'], eta_min=CONFIG['min_lr'])\n\n        return {'optimizer': self.optimizer, 'lr_scheduler': self.scheduler}\n\n    def training_step(self, batch, batch_idx):\n        image = batch['image']\n        target = batch['target']\n        output = self.model(image)\n        loss = self.criterion(output, target)\n        score = self.metric(output.argmax(1), target)\n        logs = {'train_loss': loss, 'train_f1': score, 'lr': self.optimizer.param_groups[0]['lr']}\n        self.log_dict(\n            logs,\n            on_step=False, on_epoch=True, prog_bar=True, logger=True\n        )\n        return loss\n\n    def validation_step(self, batch, batch_idx):\n        image = batch['image']\n        target = batch['target']\n        output = self.model(image)\n        loss = self.criterion(output, target)\n        score = self.metric(output.argmax(1), target)\n        logs = {'valid_loss': loss, 'valid_f1': score}\n        self.log_dict(\n            logs,\n            on_step=False, on_epoch=True, prog_bar=True, logger=True\n        )\n        return loss\n\"\"\"\n# \ud83d\udcf2 Callbacks\n\n\"\"\"\n# Checkpoint\ncheckpoint_callback = ModelCheckpoint(monitor='valid_loss',\n                                      save_top_k=1,\n                                      save_last=True,\n                                      save_weights_only=True,\n                                      filename='checkpoint\/{epoch:02d}-{valid_loss:.4f}-{valid_f1:.4f}',\n                                      verbose=False,\n                                      mode='min')\n\n# Earlystopping\nearlystopping = EarlyStopping(monitor='valid_loss', patience=3, mode='min')\n# Custom Callback\nclass ImagePredictionLogger(Callback):\n    def __init__(self, val_samples, num_samples=32):\n        super().__init__()\n        self.num_samples = num_samples\n        self.val_imgs, self.val_labels = val_samples['image'], val_samples['target']\n        \n    def on_validation_epoch_end(self, trainer, pl_module):\n        # Bring the tensors to CPU\n        val_imgs = self.val_imgs.to(device=pl_module.device)\n        val_labels = self.val_labels.to(device=pl_module.device)\n        # Get model prediction\n        logits = pl_module(val_imgs)\n        preds = torch.argmax(logits, -1)\n        # Log the images as wandb Image\n        trainer.logger.experiment.log({\n            \"examples\":[wandb.Image(x, caption=f\"Pred:{pred}, Label:{y}\") \n                           for x, pred, y in zip(val_imgs[:self.num_samples], \n                                                 preds[:self.num_samples], \n                                                 val_labels[:self.num_samples])]\n            }, commit=False)\n\"\"\"\n> \ud83d\udccc Tip: When logging manually through `wandb.log` or `trainer.logger.experiment.log`, make sure to use `commit=False` so the logging step does not increase.\n\"\"\"\n\"\"\"\n## \u26a1 Train and Evaluate the Model with W&B\n\n\"\"\"\n# Init our data pipeline\ndatamodule = PlantDataModule(batch_size=CONFIG['batch_size'])\ndatamodule.setup()\n\n# Samples required by the custom ImagePredictionLogger callback to log image predictions.\nval_samples = next(iter(datamodule.val_dataloader()))\nval_imgs, val_labels = val_samples['image'], val_samples['target']\nval_imgs.shape, val_labels.shape\n# Init our model\nmodel = CustomResNet(model_name=CONFIG['model_name'], pretrained=CONFIG['pretrained'])\nlit_model = LitCassava(model)\n\"\"\"\nCheck out the documentation for WandbLogger [here](https:\/\/pytorch-lightning.readthedocs.io\/en\/stable\/extensions\/generated\/pytorch_lightning.loggers.WandbLogger.html#pytorch_lightning.loggers.WandbLogger).\n\n> \ud83d\udccc Tip: dditional arguments like entity, group, tags, etc. used by `wandb.init()` can be passed as keyword arguments in this logger.\n\"\"\"\n## Initialize wandb logger\nwandb_logger = WandbLogger(project='plant-pathology-lightning', \n                           config=CONFIG,\n                           group='ResNet', \n                           job_type='train')\n\n# Initialize a trainer\ntrainer = Trainer(\n            max_epochs=CONFIG['num_epochs'],\n            gpus=1,\n            accumulate_grad_batches=CONFIG['accum'],\n            precision=CONFIG['precision'],\n            callbacks=[earlystopping,\n                       ImagePredictionLogger(val_samples)],\n            checkpoint_callback=checkpoint_callback,\n            logger=wandb_logger,\n            weights_summary='top',\n)\n\n# Train the model \u26a1\ud83d\ude85\u26a1\ntrainer.fit(lit_model, datamodule)\n\n# Close wandb run\nwandb.finish() \n\"\"\"\n## Visualize Metrics\n\n![img](https:\/\/i.imgur.com\/n6P7K4M.gif)\n\n## Visualize Model Predictions\n\n![img](https:\/\/i.imgur.com\/lgkLnrt.gif)\n\n## Visualize CPU and GPU Metrics\n\n![img](https:\/\/i.imgur.com\/ZLjrbhj.gif)\n\n# \u2744\ufe0f Resources\n\nI hope you find this kernel useful and will encouage you to try out Weights and Biases. Here are some relevant links that you might want to check out:\n\n* Check out the [official documentation](https:\/\/docs.wandb.ai\/) to learn more about the best practices and advanced features. \n\n* Check out the [examples GitHub repository](https:\/\/github.com\/wandb\/examples) for curated and minimal examples. This can be a good starting point. \n\n* [Weights and Biases Fully Connected](https:\/\/wandb.ai\/fully-connected) is a home for curated tutorials, free-form dicussions, paper summaries, industry expert advices and more. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '97147fc66a873f'}"}
{"id":"52659","text":"# 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\n# Reading the train data-set\ndf_train = pd.read_csv('..\/input\/tabular-playground-series-jul-2021\/train.csv')\ndf_train.head()\n# Reading the test data-set\n\ndf_test = pd.read_csv('..\/input\/tabular-playground-series-jul-2021\/test.csv')\ndf_test.head()\n# Reading the dimension\ndf_train.shape\n# Reading the train data-set\ndf_train.info()\n#Convert to date-time format\ndf_train['date_time'] = pd.to_datetime(df_train['date_time'])\ndf_train.info()\n\"\"\"\nFrom the above output, We found that all the above variables are continuous except date_time column\n\n\"\"\"\ndf_train.describe()\ndf_train_features = ['deg_C','relative_humidity','sensor_1','sensor_2','sensor_3','sensor_4','sensor_5']\nX = df_train[df_train_features]\n# Choosing the target variables to be predicted\ny = df_train[['target_carbon_monoxide','target_benzene','target_nitrogen_oxides']]\n\"\"\"\n### <u>Building the Model<\/u>\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\n# Define model. Specify a number for random_state to ensure same results each run\nfirst_model = DecisionTreeRegressor(random_state=1)\n# Fit model\nfirst_model.fit(X, y)\nprint(\"Making predictions for the following 3 target variables:\")\nprint(X.head())\nprint(\"The predictions are\")\nprint(pd.DataFrame(first_model.predict(X.head())))\n\"\"\"\n### <u>Model Validation<\/u>\n\"\"\"\nfrom sklearn.metrics import mean_absolute_error\n\npredicted_target_values_train = first_model.predict(X)\nmean_absolute_error(y, predicted_target_values_train)\nfrom sklearn.model_selection import train_test_split\n# split data into training and validation data, for both features and target\n# The split is based on a random number generator. Supplying a numeric value to\n# the random_state argument guarantees we get the same split every time we\n# run this script.\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 0)\n# Define model\nfirst_model = DecisionTreeRegressor()\n# Fit model\nfirst_model.fit(train_X, train_y)\n\n# get predicted prices on validation data\nval_predictions = first_model.predict(val_X)\nprint(mean_absolute_error(val_y, val_predictions))\n\"\"\"\n### <u>Parameter-Tuning and check Overfitting<\/u>\n\"\"\"\n\n# We can use utility function to help compare MAE scores from different values for max_leaf_nodes:\ndef get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):\n    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)\n    model.fit(train_X, train_y)\n    preds_val = model.predict(val_X)\n    mae = mean_absolute_error(val_y, preds_val)\n    return(mae)\n# compare MAE with differing values of max_leaf_nodes\nfor max_leaf_nodes in [5, 50, 500, 5000]:\n    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)\n    print(\"Max leaf nodes: %d  \\t\\t Mean Absolute Error:  %d\" %(max_leaf_nodes, my_mae))\n\"\"\"\nThe Error in prediction of max_leaf nodes falls abruptly when the max_leaf node is 50. Beyond that the error change is not very large.So the optimum number of leaf_nodes would be 50.\n\"\"\"\n\"\"\"\n### <u>Applying the model on Test-set<\/u>\n\"\"\"\ndf_test.head()\n# Reading the dimension\ndf_test.shape\n # Reading the train data-set\ndf_test.info()\n# Converting to date-format\ndf_test['date_time'] = pd.to_datetime(df_test['date_time'])\n# Re-inspect Summary\ndf_test.info()\ndf_test_features = ['deg_C','relative_humidity','sensor_1','sensor_2','sensor_3','sensor_4','sensor_5']\nX_test = df_test[df_test_features]\nFinal_model = DecisionTreeRegressor(max_leaf_nodes=50,random_state=1)\nFinal_model.fit(X, y)\npredictions = Final_model.predict(X_test)\npredictions\noutput = pd.DataFrame(predictions,\n                 columns=['target_carbon_monoxide', 'target_benzene','target_nitrogen_oxides'])\noutput.head()\noutput.to_csv('my_submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")\n\"\"\"\n# References:\n\nKaggle - Microcourses\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '60e59435b563c3'}"}
{"id":"37997","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n**INTRODUCTION**\n\"\"\"\n\"\"\"\n*Coronaviruses (CoV) are a large family of viruses that cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS-CoV) and Severe Acute Respiratory Syndrome (SARS-CoV). A novel coronavirus (nCoV) is a new strain that has not been previously identified in humans. * \n*Coronaviruses are zoonotic, meaning they are transmitted between animals and people.  Detailed investigations found that SARS-CoV was transmitted from civet cats to humans and MERS-CoV from dromedary camels to humans. Several known coronaviruses are circulating in animals that have not yet infected humans. * - From WHO Website - [coronavirus](https:\/\/www.who.int\/health-topics\/coronavirus)\n\nPrayers for all those who are suffering the agony of this calamity!!\n\"\"\"\n# Dataset\ncov_data = pd.read_csv(\"..\/input\/novel-corona-virus-2019-dataset\/2019_nCoV_data.csv\")\ncov_data.head(20)\n# Impacted Countries from the dataset\nset(cov_data['Country'])\n# Get the top 5 countries where the incidents were recovered\ncov_data.groupby(['Country'])['Recovered'].sum().sort_values(ascending = False)[:5]\n# Get the top 10 countries where most incidents were confirmed\ncov_data.groupby(['Country'])['Confirmed'].sum().sort_values(ascending = False)[:10]\n\"\"\"\n**From the data, it is clear that China is the most impacted country from this virus. Let's go ahead and analyze data for China**\n\"\"\"\n# Prepare dataset with only data from Mainland China\nchina_cov_data = cov_data[cov_data['Country'] == \"Mainland China\"]\nchina_cov_data.head()\n# A simple time series for the confirmed cases in the country over last few days\nconfirmed_ts=china_cov_data.groupby([\"Last Update\"])[\"Confirmed\"].sum()\nconfirmed_ts.astype('float')\nplt.figure(figsize=(20,8))\nplt.title('Trend of confirmed cases in Mainland China')\nplt.xlabel('Timeline')\nplt.ylabel('Confirmed Cases')\nplt.plot(confirmed_ts);\n\"\"\"\n**Let's now see the most impacted State in China because of this virus**\n\"\"\"\n# Group the confirmed cases in each state\nstate_level_china_data = china_cov_data.groupby([\"Province\/State\"])[\"Confirmed\"].sum().sort_values(ascending = False)[:10].to_frame()\n# States in Mainland China with the most number of confirmed cases\n\nplt.rcParams['figure.figsize'] = (20, 9)\nplt.style.use('seaborn')\n\ncolor = plt.cm.ocean(np.linspace(0, 1, 15))\nstate_level_china_data.plot.bar(color = color, figsize = (25, 10))\n\nplt.title('Top regions in Mainland China with the confirmed cases',fontsize = 20)\n\nplt.xticks(rotation = 90)\nplt.show()\n\"\"\"\nHubei, the MOST impacted city because of Corona Virus!\n\"\"\"\n# PIE chart showing the significant increase in deaths with time due to this virus.\neach_day_china_data = china_cov_data.groupby([\"Last Update\"])[\"Deaths\"].sum().to_frame()\nplt.style.use('seaborn')\neach_day_china_data.plot.pie(figsize = (15, 15),subplots=True)\n\nplt.title('Day wise deaths cases in Mainland China',fontsize = 20)\nplt.xticks(rotation = 90)\nplt.show()\n\"\"\"\nThank you for reading this Kernel. A lot can be done with the dataset. Will try adding more visualizations in the coming days!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '45fb7275fd4ba4'}"}
{"id":"96990","text":"\"\"\"\n# Approach\n\n\"\"\"\n\"\"\"\n1)Each column of the datasets were checked for any data inconsistency.\n\n2)Required actions were taken for specific columns where data inconsistencies were found.\n\n3)Different regression algorithms were used to build different models.\n\n4) __RandomForestRegressor__ gave us the best model.So the .ipynb file contains only the random forest models.\n\n5)Tuning of hyperparameters were required for random forest regressor to optimize the RMSLE value.\n\n6)Best features were selected using VIF,RFE,forward elimnation,backward elimination,random forest and extra trees techniques. Features extracted using extra trees technique gave us the best model.\n\"\"\"\n\"\"\"\n# Importing Librabries\n\"\"\"\n# suppress display of warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# 'Pandas' is used for data manipulation and analysis\nimport pandas as pd \n\n# 'Numpy' is used for mathematical operations on large, multi-dimensional arrays and matrices\nimport numpy as np\n\n# 'Matplotlib' is a data visualization library for 2D and 3D plots, built on numpy\nimport matplotlib.pyplot as plt\n\n# 'Seaborn' is based on matplotlib; used for plotting statistical graphics\nimport seaborn as sns\n\n# import various functions to perform regression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import ExtraTreesRegressor\n\n#importing metrics for tabulating the result\nfrom sklearn.metrics import mean_squared_log_error\n\n#setting the plot size using rcParams\nplt.rcParams['figure.figsize'] = [15,8]\n\"\"\"\nImporting the data\n\"\"\"\ndf = pd.read_csv('..\/input\/car-prices-dataset\/train.csv')\ndf_test = pd.read_csv('..\/input\/car-prices-dataset\/test.csv')\n\"\"\"\n# Understanding the data\n\"\"\"\ndf.head()\n\"\"\"\nFrom the above display we can see that:\n\n1)The 'Levy' column contains '-' symbol.We need to look into this column.\n\n2)In the 'Doors' column there are month names which we need to remove.\n\n3)In the 'MIleage' column there is 'km' written, we need to seperate this 'km' for model building purpose.\n\"\"\"\ndf_test.head()\n\"\"\"\nFrom the above display we can see that:\n\n1)The 'Levy' column contains '-' symbol.We need to look into this column.\n\n2)In the 'Doors' column there are month names which we need to remove.\n\n3)In the 'Mileage' column there is 'km' written, we need to seperate this 'km' for model building purpose.\n\n4)We need to delete the 'Price' column as we need to predict it.\n\"\"\"\n#Understanding the shape of the data\ndf.shape\n\"\"\"\nWe can see that there are 19237 records and 18 rows\n\"\"\"\n#assigning the target variable\ny=df['Price']\n#Concatenting both the test and train datasets together so that we can perform all the rectification tasks on both the data together\ndf = df.drop(['Price'],axis=1)\ndf_test=df_test.drop(['Price'],axis=1)\ndf_merge = df.append(df_test)\ndf_merge.reset_index(inplace=True)\ndf_merge= df_merge.drop(['index'],axis=1)\n#checking the shape of the merged dataset\ndf_merge.shape\n#checking the dtypes and Unique values\ninfo = pd.DataFrame()\ninfo['DataTypes'] = df_merge.dtypes\ninfo['Unique_values'] = df_merge.nunique()\ninfo\n\"\"\"\nWe need to convert 'Mileage' column into float as we know that it is of float\/integer datatype.\n\"\"\"\ndf_merge.describe(include='object')\ndf_merge.describe(include=np.number)\n\"\"\"\nFrom the describe() function we can get the mean,count and quantiles values for numeric data and count,frequency of object type data. From the above displays it can be seen that there are no missing values.\n\"\"\"\n\"\"\"\n# Rectifying the data\n\"\"\"\n#removing the 'km' from the mileage column and converting it to float\ndf_merge['Mileage'] = pd.to_numeric(df_merge.Mileage.str.split(' ').str[0], downcast='float')\n#replacing all the '0' values with the mean values of the 'Mileage' column\ndf_merge['Mileage'] = np.where(df_merge['Mileage'] == 0.0,df_merge['Mileage'].mean(),df_merge['Mileage'])\n#checking the unique values of 'Doors' column\ndf_merge['Doors'].unique()\n#cleaning the Doors column\ndf_merge['Doors'] = np.where((df_merge['Doors'] == '04-May') | (df_merge['Doors'] == '02-Mar'), df_merge['Doors'].str.split('-').str[0],df_merge['Doors'])\n#checking the unique values of 'Doors' column after cleaning\ndf_merge['Doors'].unique()\n#checking the unique values of 'Levy' column after cleaning\ndf_merge['Levy'].unique()\n#converting the Levy column to float as it is the Tax \ndf_merge['Levy'] = pd.to_numeric(df_merge['Levy'].replace('-', '0'), downcast='float')\n#Replacing the 0 in the 'Levy' column with mean of that column\ndf_merge['Levy'] = np.where(df_merge['Levy'] == 0.0,df_merge['Levy'].mean(),df_merge['Levy'])\n#checking the unique values in the 'Engine volume' column\ndf_merge['Engine volume'].unique()\n#We can see that there are some values with 'Turbo' and some values without 'Turbo'\n#So we remove the word 'Turbo' from all records that have it\ndf_merge['Engine volume'] = pd.to_numeric(df_merge['Engine volume'].str.split(' ').str[0], downcast='float')\n#Replacing the '0' in the 'Engine volume' column with the mean value of that column\ndf_merge['Engine volume']=np.where(df_merge['Engine volume'] == 0.0,df_merge['Engine volume'].mean(),df_merge['Engine volume'])\n#Feature engineering the production year column\nimport datetime as dt\ncurrt_time = dt.datetime.now()\ndf_merge['Prod. year'] = currt_time.year - df_merge['Prod. year'] \n#Checking the dataset after all the retification\ndf_merge.head()\n\"\"\"\n# Extrapolatory Data Analysis \n\"\"\"\nsns.heatmap(df_merge.isnull(),cbar=False)\nplt.show\n\"\"\"\nWe can see that there are no missing values\n\"\"\"\nsns.heatmap(df_merge.corr(), cbar=True, annot=True)\n\n\"\"\"\nWe can see that 'Engine volume' is having high correlation with 'Cylinders' and 'Levy' columns. \n\"\"\"\n#distribution of numeric variables\ndf_merge.hist()\nplt.tight_layout()\nplt.show()\n\"\"\"\nWe can see that 'Prod. year','Levy' and 'Engine volume' columns are right skewed.\n\"\"\"\n#shapiro test to check the skewness of the target variable\nfrom scipy.stats import shapiro\nx = shapiro(y)\nif x[1] <= 0:\n    print('Negatively skewed')\nelse:\n    print('Positively Skewed')\n  \n#As from the shapiro test we can see that 'Price' column is negatively skewed we need to normlize it\ny = np.log(y)\n\"\"\"\n# Building the model\n\"\"\"\ncateg = df_merge.select_dtypes(include='object')\nnum = df_merge.select_dtypes(include = np.number)\n#getting dummies for the categorical variables\ncat_dummies = pd.get_dummies(categ,drop_first=True)\n#creating the final dataset\ndf_final = pd.concat([num,cat_dummies], axis=1)\n#checking the shape of the final dataset\ndf_final.shape\n#segregating the training and test data before model building\ntrain_data = df_final.iloc[:19237]\ntrain_data.shape\ntest_data = df_final.iloc[19237:]\ntest_data.shape\n#splitting the data into test and train\nX = train_data\nY=y\n\nX_train, X_test, y_train, y_test = train_test_split(X,Y, test_size=0.3, random_state=10)\n\n#Randomized Search CV for searching the best parameters\n\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 1200, num = 12)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(5, 30, num = 6)]\n# max_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10, 15, 100]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 5, 10]\n# Create the random grid\nrandom_grid = {'n_estimators': n_estimators,\n               'max_features': max_features,\n               'max_depth': max_depth,\n               'min_samples_split': min_samples_split,\n               'min_samples_leaf': min_samples_leaf}\n\nprint(random_grid)\nrf_model = RandomForestRegressor()\nrf_random_model = RandomizedSearchCV(estimator = rf_model, param_distributions = random_grid,scoring='neg_mean_squared_error', n_iter = 10, cv = 5, verbose=2, random_state=42, n_jobs = 1)\nrf_random_model.fit(X_train,y_train)\n#getting the best parameters\nrf_random_model.best_params_\n\"\"\"\n#  Feature selection using  extra tree regressor\n\"\"\"\n\"\"\"\nSince we need to find features to train the model so that it neither gets underfitted or overfitted, we use feature selection technique.The best feature selection technique that worked for this problem statement is using extra tree regressor.\n\"\"\"\nreg= ExtraTreesRegressor()\nreg.fit(X_train,y_train)\nExtraTreesRegressor()\n#finding important features\nfeat_importances = pd.Series(reg.feature_importances_, index=X_train.columns)\npd.DataFrame(feat_importances.nlargest(30)).index\n#instantiating the randomforest regressor using the best parameters\nmod4 = RandomForestRegressor(n_estimators= 1000, max_depth= 25,\n max_features= 'sqrt',\n min_samples_leaf=1,\n min_samples_split = 2\n )\nX1 = train_data[['Airbags', 'Mileage', 'Prod. year', 'ID', 'Gear box type_Tiptronic',\n       'Leather interior_Yes', 'Levy', 'Fuel type_Diesel', 'Engine volume',\n       'Manufacturer_HYUNDAI', 'Fuel type_Hybrid', 'Color_White',\n       'Color_Black', 'Drive wheels_Front', 'Model_FIT', 'Color_Grey',\n       'Color_Silver', 'Cylinders', 'Wheel_Right-hand drive', 'Category_Sedan',\n       'Manufacturer_TOYOTA', 'Category_Jeep', 'Gear box type_Variator',\n       'Manufacturer_SSANGYONG', 'Fuel type_Petrol', 'Drive wheels_Rear',\n       'Model_Prius']]\ny1=y\n\nX1_train, X1_test, y1_train, y1_test = train_test_split(X1,y1, test_size=0.3, random_state=10)\n#fitting the model\nmodel = mod4.fit(X1_train, y1_train)\n#predicting the data\ny_predict=model.predict(X1_test)\n#calculating the RMLSE score\nRMLSE=np.sqrt(mean_squared_log_error(np.exp(y1_test),np.exp(y_predict)))\n#Printing the RMLSE score\nRMLSE\n\"\"\"\n# Finding best features using random forest regressor\n\"\"\"\nmod3 = RandomForestRegressor(n_estimators= 1000, max_depth= 25,\n max_features= 'sqrt',\n min_samples_leaf=1,\n min_samples_split = 2\n )\nmodel_random = mod3.fit(X_train, y_train)\nfeat_importances = pd.Series(model_random.feature_importances_, index=X_train.columns)\npd.DataFrame(feat_importances.nlargest(50)).index\nX2=train_data[['Airbags', 'Mileage', 'Prod. year', 'ID', 'Gear box type_Tiptronic',\n       'Leather interior_Yes', 'Levy', 'Fuel type_Diesel', 'Engine volume',\n       'Manufacturer_HYUNDAI', 'Fuel type_Hybrid', 'Color_White',\n       'Color_Black', 'Drive wheels_Front', 'Model_FIT', 'Color_Grey',\n       'Color_Silver', 'Cylinders', 'Wheel_Right-hand drive', 'Category_Sedan',\n       'Manufacturer_TOYOTA', 'Category_Jeep', 'Gear box type_Variator',\n       'Manufacturer_SSANGYONG', 'Fuel type_Petrol', 'Drive wheels_Rear',\n       'Model_Prius', 'Color_Blue', 'Category_Hatchback']]\nY2=y\n\nX2_train, X2_test, y2_train, y2_test = train_test_split(X2,Y2, test_size=0.3, random_state=10)\nmodel1 = mod4.fit(X2_train, y2_train)\ny_pred=model1.predict(X2_test)\nRMLSE1=np.sqrt(mean_squared_log_error(np.exp(y2_test),np.exp(y_pred)))\nRMLSE1","meta":"{'source': 'AI4Code', 'id': 'b224eab66fe797'}"}
{"id":"131972","text":"# 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\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\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\ndf = pd.read_csv('..\/input\/fishmarket\/fishes.csv')\n\"\"\"\n****Data Analysis and Exploration********\n\"\"\"\nsns.pairplot(df, hue=\"Species\") \nsns.countplot(data=df, x=\"Species\").set_title(\"Species Outcome\")\nsns.relplot(data=df, x=\"Weight\", y=\"Height\", hue=\"Species\", palette=\"bright\", height=6)\nsns.relplot(data=df, x=\"Length1\", y=\"Width\", hue=\"Species\", palette=\"bright\", height=6)\n\"\"\"\n# Data Preparation, Balancing and Cleanup\n\"\"\"\n# Check if there are any null values\ndf.isnull().values.any()\n# Remove null values\ndf = df.dropna()\n# Check if there are any null values\ndf.isnull().values.any()\n#Drop not needed columns \/ features\ndf.drop('Id', axis=1, inplace=True)\ndf.head()\n\"\"\"\n**Classifier Setups and Build Model**\n\"\"\"\n# Import required libraries for performance metrics\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import make_scorer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import confusion_matrix \nfrom sklearn.model_selection import train_test_split\ndef get_performance_measures(actual, prediction):\n    matrix = confusion_matrix(actual, prediction)\n    FP = matrix.sum(axis=0) - np.diag(matrix)  \n    FN = matrix.sum(axis=1) - np.diag(matrix)\n    TP = np.diag(matrix)\n    TN = matrix.sum() - (FP + FN + TP)\n\n    return(TP, FP, TN, FN)\n#Custom Scorers\n\n# # Sensitivity, hit rate, recall, or true positive rate\n# TPR = TP\/(TP+FN)\n# # Specificity or true negative rate\n# TNR = TN\/(TN+FP) \n# # Precision or positive predictive value\n# PPV = TP\/(TP+FP)\n# # Negative predictive value\n# NPV = TN\/(TN+FN)\n# # Fall out or false positive rate\n# FPR = FP\/(FP+TN)\n# # False negative rate\n# FNR = FN\/(TP+FN)\n# # False discovery rate\n# FDR = FP\/(TP+FP)\n\n# # Overall accuracy\n# ACC = (TP+TN)\/(TP+FP+FN+TN)\n\n# Also remember:\n# specificity = true negative rate\n# sensitivity = true positive rate\n\ndef sensitivity_score(y_true, y_pred, mode=\"multiclass\"):\n    if mode == \"multiclass\":\n        TP, FP, TN, FN = get_performance_measures(y_true, y_pred)\n        TPR = (TP\/(TP+FN)).mean()\n    elif mode == \"binary\":\n        TP, FP, TN, FN = get_performance_measures(y_true, y_pred)\n        TPR = (TP\/(TP+FN))[1] # Since the [0] part is the index\n    else:\n        raise Exception(\"Mode not recognized!\")\n    \n    return TPR\n\ndef specificity_score(y_true, y_pred, mode=\"multiclass\"):\n    if mode == \"multiclass\":\n        TP, FP, TN, FN = get_performance_measures(y_true, y_pred)\n        TNR = (TN\/(TN+FP)).mean()\n    elif mode == \"binary\":\n        TP, FP, TN, FN = get_performance_measures(y_true, y_pred)\n        TNR = (TN\/(TN+FP))[1]\n    else:\n        raise Exception(\"Mode not recognized!\")\n    \n    return TNR\n# Define dictionary with performance metrics\n# To know what everaging to use: https:\/\/stats.stackexchange.com\/questions\/156923\/should-i-make-decisions-based-on-micro-averaged-or-macro-averaged-evaluation-mea#:~:text=So%2C%20micro%2Daveraged%20measures%20add,is%20more%20like%20an%20average.\n\n\nscoring = {\n            'accuracy':make_scorer(accuracy_score), \n            'precision':make_scorer(precision_score, average='weighted'),\n            'f1_score':make_scorer(f1_score, average='weighted'),\n            'recall':make_scorer(recall_score, average='weighted'), \n            'sensitvity':make_scorer(sensitivity_score, mode=\"multiclass\"), \n            'specificity':make_scorer(specificity_score, mode=\"multiclass\"), \n           }\n# Import required libraries for machine learning classifiers\nfrom sklearn.tree import DecisionTreeClassifier #Decision Tree\nfrom sklearn.naive_bayes import GaussianNB #Naive Bayes\nfrom sklearn.linear_model import LogisticRegression #Logistic Regression\nfrom sklearn.svm import LinearSVC # Support Vector Machine\nfrom sklearn.neighbors import KNeighborsClassifier #K-nearest Neighbors\nfrom sklearn.cluster import KMeans #K-means\n\n# Instantiate the machine learning classifiers\ndecisionTreeClassifier_model = DecisionTreeClassifier()\ngaussianNB_model = GaussianNB()\nlogisticRegression_model = LogisticRegression(max_iter=10000)\nlinearSVC_model = LinearSVC(dual=False)\nkNeighbors_model = KNeighborsClassifier()\n# features = data frame set that contain your features that will be used as input to see if prediction is equal to actual result\n# target = data frame set (1 column usually) that will contain your target or actual results.\n# folds = this is added so we can easily change the number of folds we want to do with our data set.\n# folding is a technique to minimise overfitting and therefore make our model more accurate.\ndef models_evaluation(features, target, folds):    \n    # Perform cross-validation to each machine learning classifier\n    decisionTreeClassifier_result = cross_validate(decisionTreeClassifier_model, features, target, cv=folds, scoring=scoring)\n    gaussianNB_result = cross_validate(gaussianNB_model, features, target, cv=folds, scoring=scoring)\n    logisticRegression_result = cross_validate(logisticRegression_model, features, target, cv=folds, scoring=scoring)\n    linearSVC_result = cross_validate(linearSVC_model, features, target, cv=folds, scoring=scoring)\n    kNeighbors_result = cross_validate(kNeighbors_model, features, target, cv=folds, scoring=scoring)\n    # kMeans_result = cross_validate(kMeans_model, features, target, cv=folds, scoring=scoring)\n\n    # Create a data frame with the models perfoamnce metrics scores\n    models_scores_table = pd.DataFrame({\n      'Decision Tree':[\n                        decisionTreeClassifier_result['test_accuracy'].mean(),\n                        decisionTreeClassifier_result['test_precision'].mean(),\n                        decisionTreeClassifier_result['test_recall'].mean(),\n                        decisionTreeClassifier_result['test_sensitvity'].mean(),\n                        decisionTreeClassifier_result['test_specificity'].mean(),\n                        decisionTreeClassifier_result['test_f1_score'].mean()\n                       ],\n\n      'Gaussian Naive Bayes':[\n                                gaussianNB_result['test_accuracy'].mean(),\n                                gaussianNB_result['test_precision'].mean(),\n                                gaussianNB_result['test_recall'].mean(),\n                                gaussianNB_result['test_sensitvity'].mean(),\n                                gaussianNB_result['test_specificity'].mean(),\n                                gaussianNB_result['test_f1_score'].mean()\n                              ],\n\n      'Logistic Regression':[\n                                logisticRegression_result['test_accuracy'].mean(),\n                                logisticRegression_result['test_precision'].mean(),\n                                logisticRegression_result['test_recall'].mean(),\n                                logisticRegression_result['test_sensitvity'].mean(),\n                                logisticRegression_result['test_specificity'].mean(),\n                                logisticRegression_result['test_f1_score'].mean()\n                            ],\n\n      'Support Vector Classifier':[\n                                    linearSVC_result['test_accuracy'].mean(),\n                                    linearSVC_result['test_precision'].mean(),\n                                    linearSVC_result['test_recall'].mean(),\n                                    linearSVC_result['test_sensitvity'].mean(),\n                                    linearSVC_result['test_specificity'].mean(),\n                                    linearSVC_result['test_f1_score'].mean()\n                                   ],\n\n       'K-nearest Neighbors':[\n                        kNeighbors_result['test_accuracy'].mean(),\n                        kNeighbors_result['test_precision'].mean(),\n                        kNeighbors_result['test_recall'].mean(),\n                        kNeighbors_result['test_sensitvity'].mean(),\n                        kNeighbors_result['test_specificity'].mean(),\n                        kNeighbors_result['test_f1_score'].mean()\n                       ],\n\n      },\n\n      index=['Accuracy', 'Precision', 'Recall', 'Sensitivity', 'Specificity', 'F1 Score', ])\n    \n    # Return models performance metrics scores data frame\n    return(models_scores_table)\n# Let's try to look at our data frame again one last time\ndf.head()\n# Specify features columns\n# Actually what we are doing here is that we are just dropping the Species column since that is our class\n# and the remaining columns will then be our features (eg. inputs to come up to a class)\n# axis 0 basically means to drop all of that column\nfeatures = df.drop(columns=\"Species\", axis=0)\n\n# Now let's see what features looks like\nfeatures\n\n# Don't mind the left hand side, those are just index mainly used for viewing\nevaluationResult = models_evaluation(features, target, 5)\nview = evaluationResult\nview = view.rename_axis('Test Type').reset_index() #Add the index names to the column. This will be used for our presentation\n\n# https:\/\/pandas.pydata.org\/docs\/reference\/api\/pandas.melt.html\n# Re-Organizing our dataframe to fit our view need\nview = view.melt(var_name='Classifier', value_name='Value', id_vars='Test Type')\n# result\nsns.catplot(data=view, x=\"Test Type\", y=\"Value\", hue=\"Classifier\", kind='bar', palette=\"bright\", alpha=0.8, legend=True, height=5, margin_titles=True, aspect=2)\n# In here we just add a new column to our raw data frame, that gets the result for the highest\n# scoring classifier in every score test.\nevaluationResult['Best Score'] = evaluationResult.idxmax(axis=1)\nevaluationResult","meta":"{'source': 'AI4Code', 'id': 'f2c4e899c07db9'}"}
{"id":"3805","text":"\"\"\"\n## Customer Churn Prediction\n\"\"\"\n# By :-Chintan Chitroda\n\"\"\"\n#### The Notebook Contains 5 machine learning Algorithm.\n#### Output File is based on Logistic Regression model.\n#### XGBCLassifier Algorithm is taking time to compute so Be patient me took 15 mins on Kaggle commit and 2 mins in pc\n### Go to version 7 of Telecom-Churn-Prediction it is only solution using Logistic regression and execute quickly.\n### Note:\n#### Remove # From write to file command under each algorith for their output fill\n#### By Default the output File will be Predition of Logistic Regression Model.\n#### Its a big file Due to 5 algorithms, so suggest to donload the file and run. \n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn import metrics\ntrainds = pd.read_csv(\"\/kaggle\/input\/predict-the-churn-for-customer-dataset\/Train File.csv\")\ntestds = pd.read_csv(\"\/kaggle\/input\/predict-the-churn-for-customer-dataset\/Test File.csv\")\n\ntrainds.head(3)\ntestds.head(3)\nprint('Train Dataset Infomarion')\nprint (\"Rows     : \" ,trainds.shape[0])\nprint (\"Columns  : \" ,trainds.shape[1])\nprint (\"\\nFeatures : \\n\" ,trainds.columns.tolist())\nprint (\"\\nMissing values :  \", trainds.isnull().sum().values.sum())\nprint (\"\\nUnique values :  \\n\",trainds.nunique())\nplt.subplots(figsize=(10, 6))\nplt.title('Cooralation Matrix', size=30)\nsns.heatmap(trainds.corr(),annot=True,linewidths=0.5)\n\"\"\"\n#### Data Manipulation\n\"\"\"\ntrainds.loc[trainds['TotalCharges'].isnull()] #NUll values Present\ntrainds['TotalCharges'] = trainds['TotalCharges'].fillna(trainds['TotalCharges'].median()) #\n#trainds = trainds[trainds[\"TotalCharges\"].notnull()]\nCustomerIDS = testds['customerID']\ntrainds.drop('customerID', axis=1,inplace =True)\ntestds.drop('customerID', axis=1,inplace =True)\ntrainds.columns\ntestds.describe()\ntestds['TotalCharges'] = testds['TotalCharges'].fillna(testds['TotalCharges'].median())\ntrainds[\"InternetService\"]=trainds[\"InternetService\"].astype('str')\ntestds[\"InternetService\"]=testds[\"InternetService\"].astype('str')\ntrainds[\"TotalCharges\"] = trainds[\"TotalCharges\"].astype(float)\ntrainds[\"MonthlyCharges\"] = trainds[\"MonthlyCharges\"].astype(float)\n\ntestds[\"TotalCharges\"] = testds[\"TotalCharges\"].astype(float)\ntestds[\"MonthlyCharges\"] = testds[\"MonthlyCharges\"].astype(float)\nreplace_cols = [ 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection','TechSupport','StreamingTV', 'StreamingMovies']\nfor i in replace_cols : \n    trainds[i]  = trainds[i].replace({'No internet service' : 'No'})\n    testds[i]  = testds[i].replace({'No internet service' : 'No'})\nreplace_cols = ['MultipleLines']\nfor i in replace_cols : \n    trainds[i]  = trainds[i].replace({'No phone service' : 'No'})\n    testds[i]  = testds[i].replace({'No phone service' : 'No'})\n\"\"\"\n#### Data Exploration code:\n\"\"\"\ndef customercountplot(x):\n    z = \"Customer Count wrt \"+ x\n    plt.title(z,size=20)\n    sns.countplot(trainds[x])\ndef churnratio():\n    import plotly.offline as py\n    import plotly.graph_objs as go\n    val = trainds[\"Churn\"].value_counts().values.tolist()\n\n    trace = go.Pie(labels = [\"Not Churned\",\"Churned\"] ,\n                   values = val ,\n                   marker = dict(colors =  [ 'royalblue' ,'lime']), hole = .5)\n    layout = go.Layout(dict(title = \"Train Dataset Customers\"))\n    data = [trace]\n    fig = go.Figure(data = data,layout = layout)\n    py.iplot(fig)\ndef churnrate():\n    features = ['PhoneService','MultipleLines','InternetService',\n                'TechSupport','StreamingTV','StreamingMovies','Contract']\n    for i, item in enumerate(features):\n        if i < 3:\n            fig1 = pd.crosstab(trainds[item],trainds.Churn,margins=True)\n            fig1.drop('All',inplace=True)\n            fig1.drop('All',axis=1, inplace=True)\n            fig1.plot.bar()\n            z= 'Customer Churned wrt ' + item\n            plt.title(z,size=20)\n        elif i >=3 and i < 6:\n            fig1 = pd.crosstab(trainds[item],trainds.Churn,margins=True)\n            fig1.drop('All',inplace=True)\n            fig1.drop('All',axis=1, inplace=True)\n            fig1.plot.bar()\n            z= 'Customer Churned wrt ' + item\n            plt.title(z,size=20)\n        elif i < 9:\n            fig1 = pd.crosstab(trainds[item],trainds.Churn,margins=True)\n            fig1.drop('All',inplace=True)\n            fig1.drop('All',axis=1, inplace=True)\n            fig1.plot.bar()\n            z= 'Customer Churned wrt ' + item\n            plt.title(z,size=20)\n\"\"\"\n## Data Exploration\n\"\"\"\nchurnratio()\ncustomercountplot('Churn')\ncustomercountplot('gender')\ncustomercountplot('Contract')\ncustomercountplot('Partner')\ncustomercountplot('PhoneService')\ncustomercountplot('MultipleLines')\ncustomercountplot('StreamingTV')\ntempdf = trainds.copy()\nbins=[0,12,24,48,60,100]\ntempdf['tenure_group']=pd.cut(tempdf['tenure'],bins,labels=['0-12','12-24','24-48','48-60','>60'])\nplt.title('Customer Count wrt to tenure',size=20)\nsns.countplot(tempdf['tenure_group'])\nplt.title(\"Distribution Plot For Montly Charges\",size=20)\nsns.distplot(trainds['MonthlyCharges'],hist_kws={'edgecolor':'black','alpha':.5})\nplt.title(\"Distribution Plot For TotalCharges\",size=20)\nsns.distplot(trainds['TotalCharges'],hist_kws={'edgecolor':'black','alpha':.5})\nchurnrate()\n\"\"\"\n## Data PreProcessing\n\"\"\"\ntrain = trainds.copy()\ntest = testds.copy()\ntrain\ntrain.columns\ntrain = pd.get_dummies(train, columns=['gender', 'SeniorCitizen', 'Partner', 'Dependents',\n                                       'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity',\n                                       'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV',\n                                       'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod'])\ntest = pd.get_dummies(test, columns=['gender', 'SeniorCitizen', 'Partner', 'Dependents',\n                                       'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity',\n                                       'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV',\n                                       'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod'])\ntrain.head(3)\ntrain[\"Churn\"] = train[\"Churn\"].replace({'Yes':1,'No':0})\n# For writing solution to file\ndef writetofile(solution,filename):\n    with open(filename,'w') as file:\n        file.write('customerID,Churn\\n')\n        for (a, b) in zip(CustomerIDS, solution):\n            c=\"\"\n            if b==0:\n                c=\"No\"\n            else:\n                c='Yes'\n            file.write(str(a)+','+str(c)+'\\n')\nX = train.drop('Churn', axis=1)\ny = train['Churn']\n\"\"\"\n# Building model\n\"\"\"\n\"\"\"\n## Logistic Regression Model\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix,accuracy_score,classification_report\nfrom sklearn.metrics import f1_score\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=42)\nlogreg = LogisticRegression()\nlogreg.fit(X_train,y_train)\ny_pred=logreg.predict(X_test)\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred))\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred))\nsol2=logreg.predict(test)\nsol2\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred))\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred))\nimport collections, numpy\ncollections.Counter(sol2)\npds = pd.DataFrame(columns=['CustomerID','Churn'])\npds['CustomerID'] = CustomerIDS\npds['Churn']=sol2\npds\n\"\"\"\n## Writing Predicted Data to Solution.csv\n\"\"\"\n#writetofile(Prediction ,'filename you want to save')\nwritetofile(sol2,'Prediction-Solution')\n\"\"\"\n##### The Best accuracy Model was Logistic Regression Model .\n##### You can see other Models I Tried.\n\"\"\"\n\"\"\"\n## Decision Tree Classifier\n\"\"\"\nfrom sklearn import tree\n\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state=42)\ndt = tree.DecisionTreeClassifier(criterion='entropy', max_depth=7)\ndt = dt.fit(X_train,y_train)\n\ny_pred = dt.predict(X_test)\nsol4=dt.predict(test)\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred))\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred))\nprint(sol4)\n\"\"\"\n#### Save to file\n\"\"\"\n#writetofile(Prediction ,'filename you want to save')\n#writetofile(sol4,'Prediction-Solution')\n\"\"\"\n## XGBoost CLassifier Algorithm\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, average_precision_score\nfrom xgboost import XGBClassifier\nimport xgboost as xgb\nX_train, X_test, y_train, y_test = train_test_split( X , y, test_size=0.3, random_state=42)\nfrom sklearn.model_selection import GridSearchCV\n\nparam_test = {\n    \n    'gamma': [0.5, 1, 1.5, 2, 5],\n    'max_depth': [3, 4, 5]\n  \n}\n\nclf = GridSearchCV(estimator = \nXGBClassifier(learning_rate =0.1,\n              objective= 'binary:logistic',\n              nthread=4,\n              seed=27), \n              param_grid = param_test,\n              scoring= 'accuracy',\n              n_jobs=4,\n              iid=False,\n              verbose=10)\nclf.fit(X_train, y_train)\ny_pred= clf.predict(X_test)\nprint(y_pred)\nprint(\"Accuracy:\",accuracy_score(y_test,y_pred))\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred))\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred))\nsol3= clf.predict(test)\nprint(y_pred)\nimport collections, numpy\ncollections.Counter(sol3)\n\"\"\"\n### Save to File\n\"\"\"\n#writetofile(Prediction ,'filename you want to save')\n#writetofile(sol3,'Prediction-Solution')\n\"\"\"\n## Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.30,random_state=42)\nrf = RandomForestClassifier(n_estimators = 50, random_state = 42)\nrf.fit(X_train,y_train)\ny_pred = rf.predict(X_train)\ny_pred= clf.predict(X_test)\nprint(y_pred)\nprint(\"Accuracy:\",accuracy_score(y_test,y_pred))\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred))\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred))\nsol3 = rf.predict(test)\n#import collections, numpy\n#collections.Counter(sol3)\n\"\"\"\n### Save to File\n\"\"\"\n#writetofile(Prediction ,'filename you want to save')\n#writetofile(sol3,'Prediction-Solution')\n\"\"\"\n## Still working on this u guys can Contribute..\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '071d6d24114cac'}"}
{"id":"1543","text":"\"\"\"\n## Importing Important Libraries\n\"\"\"\n\"\"\"\n## News\n\nThe term \"news\" refers to details about current events. This can be done in a variety of ways, including word of mouth, writing, postal services, broadcasting, electronic communication, and the testimony of incident observers and witnesses. War, government, politics, education, health, the environment, economy, industry, fashion, and entertainment, as well as sporting events and quirky or unusual events, are all common topics for news coverage. Technological and social advancements, also motivated by government communication and espionage networks, have accelerated the spread of news and influenced its content.\n\n## Fake News\n\nFake news is content that is inaccurate or misleading and is perceived as news. It is sometimes used to damage a person's or entity's image or to profit from advertising revenue. Fake news, which was once popular in print, has become more prevalent with the rise of social media, especially the Facebook News Feed.The dissemination of fake news has been linked to political divide, post-truth politics, confirmation bias, and social media algorithms. It is sometimes created and spread by hostile foreign actors, particularly during elections. The use of anonymously hosted fake news websites has made prosecuting sources of fake news for libel more difficult.\n\nBy contrasting with real news, fake news can lessen the influence of real news; a Buzzfeed study showed that top fake news reports about the 2016 US presidential election generated more engagement on Facebook than top stories from major media outlets. It also has the ability to erode public confidence in serious news coverage. Thus making the classification of fake news at an early stage a very important need of the hour.\n\nWe worked on fake-and-real-news-dataset as provided by Cl\u00e9ment Bisaillon to devise some Deep learning algorithms to make classification of Fake news easier.\n\nFollowing are the models we worked on:\nFinals Deep Learning models designed :\n\n**1.      Detection of the topics that are emerging most in the analysis of Fake news.**\n\n**2.      Fake news detection using only news titles with CNN+LSTM.**\n\n**3.      Fake news Classification using RNN(LSTM) on whole text.**\n\n**4.      Fake news classification using CNN.**\n\n\n\n\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!pip install gensim # Gensim is an open-source library for unsupervised topic modeling and natural language processing\nimport nltk\nnltk.download('punkt')\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom wordcloud import WordCloud, STOPWORDS\nimport nltk\nimport re\nfrom nltk.corpus import stopwords\nimport seaborn as sns \nimport gensim\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import STOPWORDS\n\nimport plotly.express as px\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nimport tensorflow as tf\n\nimport time\nfrom sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n## Reading the Dataset\n\"\"\"\ntrue_news = pd.read_csv('..\/input\/fake-and-real-news-dataset\/True.csv')\nfake_news = pd.read_csv('..\/input\/fake-and-real-news-dataset\/Fake.csv')\n\"\"\"\n**Creating a target variable and merging the datasets for true and false news**\n\"\"\"\ntrue_news['target'] = 1\nfake_news['target'] = 0\ndf = pd.concat([true_news, fake_news]).reset_index(drop = True)\ndf['complete'] = df['title'] + ' ' + df['text']\ndf.head()\n\"\"\"\n**Checking for the null values in the data**\n\"\"\"\ndf.isnull().sum()\n\"\"\"\n## Data Cleaning\n\"\"\"\nstop_words = stopwords.words('english')\nstop_words.extend(['from', 'subject', 're', 'edu', 'use','says'])\ndef preprocess(text):\n    result = []\n    for token in gensim.utils.simple_preprocess(text):\n        if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 2 and token not in stop_words:\n            result.append(token)\n            \n    return result\n# Transforming the unmatching subjects to the same notation\ndf.subject=df.subject.replace({'politics':'PoliticsNews','politicsNews':'PoliticsNews'})\n\"\"\"\n**Distribution of Subjects between the True and Fake News**\n\"\"\"\nsub_tf_df=df.groupby('target').apply(lambda x:x['title'].count()).reset_index(name='Counts')\nsub_tf_df.target.replace({0:'False',1:'True'},inplace=True)\nsub_tf_df\nfig = px.bar(sub_tf_df, x=\"target\", y=\"Counts\",\n             color='Counts', barmode='group',\n             height=400)\nfig.show()\n\"\"\"\n**Observation The dataset looks really balanced and hence working on this is pretty easy. Thus we need not work on to make this dataset more balanced, and can safely assume this is a balanced dataset**\n\"\"\"\n\"\"\"\n## Detection of the topics that are emerging most in the analysis of Fake news.\n\"\"\"\n\"\"\"\n### Subjects receiving the most News Coverage\n\"\"\"\nsub_check=df.groupby('subject').apply(lambda x:x['title'].count()).reset_index(name='Counts')\nfig=px.bar(sub_check,x='subject',y='Counts',color='Counts',title='Count of News Articles by Subject')\nfig.show()\n\"\"\"\n**Observations Political News and World News hold the most domination counts in the data set that we have considered.**\n\"\"\"\n\"\"\"\n## Analysis to check how efficient News Headlines are to predict if the news are fake or not.\n\"\"\"\ndf['clean_title'] = df['title'].apply(preprocess)\ndf['clean_title'][0]\ndf['clean_joined_title']=df['clean_title'].apply(lambda x:\" \".join(x))\ndf.head()\n#wordcloud for true news \nplt.figure(figsize = (20,20)) \nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800 , stopwords = stop_words).generate(\" \".join(df[df.target == 1].clean_joined_title))\nplt.imshow(wc, interpolation = 'bilinear')\n\"\"\"\n**Official, White House, trump, China, North Korea are some of the most evident words present in Real news dataset.**\n\"\"\"\n#wordcloud for fake news \nplt.figure(figsize = (20,20)) \nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800 , stopwords = stop_words).generate(\" \".join(df[df.target == 0].clean_joined_title))\nplt.imshow(wc, interpolation = 'bilinear')\n\"\"\"\n**Video, Obama, trump, hillary are some of the most evident words present in Fake news dataset.**\n\"\"\"\n\"\"\"\n## Lets Look at the Count of Words Distribution in the Title\n\"\"\"\nmaxlen = -1\nfor doc in df.clean_joined_title:\n    tokens = nltk.word_tokenize(doc)\n    if(maxlen<len(tokens)):\n        maxlen = len(tokens)\nprint(\"The maximum number of words in a title is =\", maxlen)\nfig = px.histogram(x = [len(nltk.word_tokenize(x)) for x in df.clean_joined_title], nbins = 50)\nfig.show()\n\"\"\"\n**Observation: The maximum number of titles ranges from 7-8 words on average. It will be difficult to determine whether the news is real or false based on these few words alone. But we're hoping we won't get a lot of accuracy just by looking at the title. Let us continue with our forecast.**\n\"\"\"\n\"\"\"\n## Model 1: Fake news detection using only news titles with CNN + LSTM\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(df.clean_joined_title, df.target, test_size = 0.2,random_state=2, stratify = df.target)\nprint(X_test.head())\nprint(y_test.head())\nlengths = [len(x) for x in df.clean_joined_title]\nmax_length = max(lengths)\nmax_length\ntrunc_type = 'post'\npadding_type = 'post'\n\n\n\"\"\"\n**Tokenizing and the padding the titles so that all have the same length, which is the length of the longest title**\n\"\"\"\nembedding_dim = 100\noov_tok = \"<OOV>\"\n\ntokenizer = Tokenizer(oov_token=oov_tok)\ntokenizer.fit_on_texts(X_train)\n\nword_index = tokenizer.word_index\nvocab_size=len(word_index)\n\nsequences = tokenizer.texts_to_sequences(X_train)\npadded = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\n\n\ntest_sequences = pad_sequences(tokenizer.texts_to_sequences(X_test), maxlen=max_length, padding=padding_type, truncating=trunc_type)\n\nprint(X_train[0], y_train[0])\n\n\"\"\"\n**We will be using CNN + LSTM, which are genrally used for the task of generating textual descriptions of images. \nIn our model CNN will be used as feature extracter on the textual input and pass the it to LSTM through hidden layer for classification.**\n\"\"\"\nfrom keras.callbacks import EarlyStopping\noverfitCallback = EarlyStopping(monitor='val_loss',\n                              min_delta=0,\n                              patience=5,\n                              verbose=0, mode='auto')\n\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Embedding(vocab_size+1, 15, input_length=max_length),\n    tf.keras.layers.Dropout(0.3),\n    tf.keras.layers.Conv1D(64, 5, activation='relu'),\n    tf.keras.layers.MaxPooling1D(pool_size=4),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\nmodel.summary()\n\nnum_epochs = 50\nhistory = model.fit(padded, y_train, epochs=num_epochs, validation_data=(test_sequences, y_test), verbose=2, callbacks=[overfitCallback])\n\nprint(\"Training Complete\")\n\"\"\"\n**To avoid too much overfitting, an early stopping callback was described. The model is made up of six layers that are stacked in a specific order. After 7 epochs, the model stopped early and has a 95 percent validation accuracy.**\n\"\"\"\nhistory_dict = history.history\n\nacc = history_dict['accuracy']\nval_acc = history_dict['val_accuracy']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\nepochs = history.epoch\n\nplt.figure(figsize=(12,9))\nplt.plot(epochs, loss, 'r', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss', size=20)\nplt.xlabel('Epochs', size=20)\nplt.ylabel('Loss', size=20)\nplt.legend(prop={'size': 20})\nplt.show()\n\nplt.figure(figsize=(12,9))\nplt.plot(epochs, acc, 'g', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy', size=20)\nplt.xlabel('Epochs', size=20)\nplt.ylabel('Accuracy', size=20)\nplt.legend(prop={'size': 20})\nplt.ylim((0.5,1))\nplt.show()\n\"\"\"\n\n## Model 2: Text Classification with RNN on whole text\n\"\"\"\ndf.head()\ndf_whole = df.loc[:,[\"complete\",\"target\"]]\ndf_whole.head()\ndf_whole['clean_text'] = df['complete'].apply(preprocess)\ndf_whole['clean_text'][0]\n\"\"\"\n**Now we'll tokenize our data using Tensorflow's tokenizer**\n\"\"\"\n\ntokenizer = Tokenizer(num_words=5000)\ntokenizer.fit_on_texts(df_whole['complete'])\nx_tokenized = tokenizer.texts_to_sequences(df_whole['complete'])\n\nx = df_whole[\"complete\"]\ny = df_whole[\"target\"]\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=18)\n\"\"\"\n**Normalizing our data: changing it to lower case, getting rid of extra spaces, and url links.**\n\"\"\"\ndef normalize(data):\n    normalized = []\n    for i in data:\n        i = i.lower()\n        # get rid of urls\n        i = re.sub('https?:\/\/\\S+|www\\.\\S+', '', i)\n        # get rid of non words and extra spaces\n        i = re.sub('\\\\W', ' ', i)\n        i = re.sub('\\n', '', i)\n        i = re.sub(' +', ' ', i)\n        i = re.sub('^ ', '', i)\n        i = re.sub(' $', '', i)\n        normalized.append(i)\n    return normalized\n\nX_train = normalize(X_train)\nX_test = normalize(X_test)\n#Convert text to vectors, our classifier only takes numerical data. \nmax_vocab = 10000\ntokenizer = Tokenizer(num_words=max_vocab)\ntokenizer.fit_on_texts(X_train)\n# tokenize the text into vectors \nX_train = tokenizer.texts_to_sequences(X_train)\nX_test = tokenizer.texts_to_sequences(X_test)\n\"\"\"\n**Apply padding so we have the same length for each article**\n\"\"\"\nX_train = tf.keras.preprocessing.sequence.pad_sequences(X_train, padding='post', maxlen=256)\nX_test = tf.keras.preprocessing.sequence.pad_sequences(X_test, padding='post', maxlen=256)\n\"\"\"\n### Building the RNN.\n\"\"\"\n\"\"\"\n**RNNs are a form of Neural Network in which the output from the previous step is used as input in the current step.**\n\n**Here we built a Sequential model that processes sequences of texts, embeds each texts into a 32-dimensional vector, then processes the sequence of vectors using 2 Bidirectional LSTM layers of 64 units and 16 units respectively because when working with text its important to take into account the context of the text.**\n\"\"\"\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Embedding(max_vocab, 32),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,  return_sequences=True)),\n    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(16)),\n    tf.keras.layers.Dense(64, activation='relu'),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(1)\n])\n\nmodel.summary()\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True)\nmodel.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n              optimizer=tf.keras.optimizers.Adam(),\n              metrics=['accuracy'])\n\nhistory = model.fit(X_train, y_train, epochs=10,validation_split=0.1, batch_size=30, shuffle=True, callbacks=[early_stop])\n\"\"\"\n**To avoid too much overfitting, an early stopping callback was described. The model is made up of 5 layers that are stacked in a specific order. After 4 epochs, the model stopped early and has a 98\npercent validation accuracy.**\n\"\"\"\n\"\"\"\n**Visualizing our training over time**\n\"\"\"\nhistory_dict = history.history\n\nacc = history_dict['accuracy']\nval_acc = history_dict['val_accuracy']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\nepochs = history.epoch\n\nplt.figure(figsize=(12,9))\nplt.plot(epochs, loss, 'r', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss', size=20)\nplt.xlabel('Epochs', size=20)\nplt.ylabel('Loss', size=20)\nplt.legend(prop={'size': 20})\nplt.show()\n\nplt.figure(figsize=(12,9))\nplt.plot(epochs, acc, 'g', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy', size=20)\nplt.xlabel('Epochs', size=20)\nplt.ylabel('Accuracy', size=20)\nplt.legend(prop={'size': 20})\nplt.ylim((0.5,1))\nplt.show()\nmodel.evaluate(X_test, y_test)\n\"\"\"\n**Evaluation on test data gave loss: 0.0512 - accuracy: 0.9860**\n\"\"\"\npred = model.predict(X_test)\n\nbinary_predictions = []\n\nfor i in pred:\n    if i >= 0.5:\n        binary_predictions.append(1)\n    else:\n        binary_predictions.append(0) \nprint('Accuracy on testing set:', accuracy_score(binary_predictions, y_test))\nprint('Precision on testing set:', precision_score(binary_predictions, y_test))\nprint('Recall on testing set:', recall_score(binary_predictions, y_test))\nmatrix = confusion_matrix(binary_predictions, y_test, normalize='all')\nplt.figure(figsize=(16, 10))\nax= plt.subplot()\nsns.heatmap(matrix, annot=True, ax = ax)\n\n# labels, title and ticks\nax.set_xlabel('Predicted Labels', size=20)\nax.set_ylabel('True Labels', size=20)\nax.set_title('Confusion Matrix', size=20) \nax.xaxis.set_ticklabels([0,1], size=15)\nax.yaxis.set_ticklabels([0,1], size=15)\n\"\"\"\n## Model 3:  Fake news classification on whole text Using CNN\n\"\"\"\nlength_array = [len(s) for s in X_train]\nSEQUENCE_LENGTH = int(np.quantile(length_array,0.75))\nprint(SEQUENCE_LENGTH)\n\"\"\"\n**Building and training our convolutional neural network using keras' sequential api.**\n\"\"\"\n# We've added 1 because or word index has numbers from 1 to end but we've added 0 tokens in padding so our vocab now has \n#len(tokenizer.word_index) + 1\nVOCAB_LENGTH = len(tokenizer.word_index) + 1\nVECTOR_SIZE = 100\n\ndef getModel():\n    \"\"\"\n    Returns a trainable Sigmoid Convolutional Neural Network\n    \"\"\"\n    model = keras.Sequential()\n    model.add(layers.Embedding(input_dim= VOCAB_LENGTH, output_dim=VECTOR_SIZE, input_length=SEQUENCE_LENGTH))\n    \n    model.add(layers.Conv1D(128,kernel_size=4))\n    model.add(layers.BatchNormalization())\n    model.add(layers.Activation(\"relu\"))\n    model.add(layers.MaxPooling1D(2))\n    \n    model.add(layers.Conv1D(256,kernel_size=4))\n    model.add(layers.BatchNormalization())\n    model.add(layers.Activation(\"relu\"))\n    model.add(layers.MaxPooling1D(2))\n    \n    model.add(layers.Conv1D(512,kernel_size=4))\n    model.add(layers.BatchNormalization())\n    model.add(layers.Activation(\"relu\"))\n    model.add(layers.MaxPooling1D(2))\n    \n    model.add(layers.Flatten())\n    model.add(layers.Dense(1,activation=\"sigmoid\"))\n    \n    model.compile(loss=\"binary_crossentropy\",optimizer=\"adam\",metrics=[\"accuracy\"])\n    \n    return model\n\nmodel = getModel()\nmodel.summary()\nhistory = model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=1)\n\"\"\"\n**Convolutiona Neural network with**:\n* 3 Conv1D layers with 128, 256 and 512 filters with kernel size set to 4 meaning each output is calculated based on previous 4 time steps and relu activation.\n* 3 MaxPooling1D layers to downsample the input representation by taking the maximum value over the window of size 2.\n* 1 Flatten layer to flatten the output of the convolutional layers to create a single long feature vector.\n* 1 Dense layers with 1 neuron and sigmoid activation.\n\n**Gives 97% validation accuracy with 1 epoch.**\n\"\"\"\n\"\"\"\n## Creating a deployable model\n\"\"\"\n\"\"\"\n**Saving weights of our model and pickle our tokenizer.**\n\"\"\"\nmodel.save_weights(\"trained_model.h5\")\nimport pickle\nwith open(\"tokenizer.pickle\",mode=\"wb\") as F:\n    pickle.dump(tokenizer,F)\n\"\"\"\n**Saving our label map using json library.**\n\"\"\"\nimport json\nlabel_map = {0:\"Fake\",\n             1:\"Real\"\n            }\n\njson.dump(label_map,open(\"label_map.json\",mode=\"w\"))\n\"\"\"\n**Making sure our text data is clean.**\n\"\"\"\ndef cleanText(text):\n    cleaned = re.sub(\"[^'a-zA-Z0-9]\",\" \",text)\n    lowered = cleaned.lower().strip()\n    return lowered\nx_cleaned = [cleanText(t) for t in x]\nclass DeployModel():\n    \n    def __init__(self,weights_path,tokenizer_path,seq_length,label_map_path\n                ):\n        \n        self.model = getModel()\n        self.model.load_weights(weights_path)\n        self.tokenizer = pickle.load(open(tokenizer_path,mode=\"rb\"))\n        self.seq_len = seq_length\n        self.label_map = json.load(open(label_map_path))\n    \n    def _prepare_data(self,text):\n        \n        cleaned = cleanText(text)\n        tokenized = self.tokenizer.texts_to_sequences([cleaned])\n        padded = pad_sequences(tokenized,maxlen=self.seq_len)\n        return padded\n    \n    def _predict(self,text):\n        \n        text = self._prepare_data(text)\n        pred = int(self.model.predict_classes(text)[0])\n        return str(pred)\n    \n    def result(self,text):\n        \n        pred = self._predict(text)\n        return self.label_map[pred]\ndeploy_model = DeployModel(weights_path=\".\/trained_model.h5\",\n                           tokenizer_path=\".\/tokenizer.pickle\",\n                           seq_length=SEQUENCE_LENGTH,\n                           label_map_path=\".\/label_map.json\"\n                          )\ntest_text_real = x_cleaned[1000]\nprint(test_text_real)\nprint(\"\\n\\n===========================\")\nprint(\"Results: \",deploy_model.result(test_text_real))\ntest_text_fake = x_cleaned[30000]\nprint(test_text_fake)\nprint(\"\\n\\n===========================\")\nprint(\"Results: \",deploy_model.result(test_text_fake))","meta":"{'source': 'AI4Code', 'id': '02dd47972ce13e'}"}
{"id":"8912","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib as plt\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\ntrain= pd.read_csv('\/kaggle\/input\/titanic\/train.csv')\ntrain.head()\n\ntrain.shape\ntest=pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\ntest1=pd.read_csv('\/kaggle\/input\/titanic\/test.csv')\n\ntest.head()\ntest.shape\ntrain.head()\n#setting 'PassengerId' as Index\ntrain.set_index(['PassengerId'],inplace=True)\ntest.set_index(['PassengerId'],inplace=True)\ntest.head()\ntrain.isnull().sum()\n\ntest.isnull().sum()\n\ntrain.dtypes\n#missing value treatment\n\n#first lets get a visual on these\nimport missingno as mn\nmn.matrix(train)\nmn.matrix(test)\n#lets start imputing 'Age'\ntrain['Age2']=train['Age'].fillna(train.Age.median())\ntrain.head()\ntest['Age_test']=test['Age'].fillna(test.Age.median())\ntrain.head()\ntest.head()\ntrain.isnull().sum()\ntest.isnull().sum()\n#using fillna to fill 'Embarked' section values\ntrain.Embarked.value_counts()\n#S is the dominant column\ntrain.Embarked.fillna('S',inplace=True)\ntrain.isnull().sum()\n#filling 'Fare' with mean\ntest.Fare.fillna(test.Fare.mean(),inplace=True)\ntrain.isnull().sum()\n#'cabin' contains more than 80% missing values, so dropping that as well as 'age' from before.\ntrain.drop(['Age','Cabin'],axis=1,inplace=True)\ntest.drop(['Age','Cabin'],axis=1,inplace=True)\ntrain.isnull().sum()\ntest.isnull().sum()\n#no more missing values, now lets handle categorical data.\n#transforming 'Sex' from object to int\ntrain['Sex']=train.Sex.apply(lambda x:0 if x=='female' else 1)\ntest['Sex']=test.Sex.apply(lambda x:0 if x=='female' else 1)\ntest.Sex.head()\n#removing outliers from 'Fare'\nsns.boxplot('Survived','Fare',data=train)\ntrain['Fare']=train[train['Fare']<=400]\ntest['Fare']=test[test['Fare']<=400]\n#feature_engineering\ntrain['family_size']=train['SibSp']+train['Parch']+1 #+1 if alone\ntest['family_size']=test['SibSp']+test['Parch']+1 #+1 if alone\n\ntrain.head()\ntest.head()\n#creating categories acc. to family_size\ndef family_group(size):\n    a=''\n    if(size<=1):\n        a='alone'\n    elif(size<=4):\n        a='small'\n    else:\n        a='large'\n    return a\ntrain['family_group']=train.family_size.map(family_group)\ntest['family_group']=test.family_size.map(family_group)\n\ntrain.head()\n#creating categories acc. to age\ndef age_group(age):\n    a=''\n    if(age<=1):\n        a='infant'\n    elif(age<=4):\n        a='small'\n    elif(age<=14):\n        a='child'\n    elif(age<=25):\n        a='young'\n    elif(age<=40):\n        a='adult'\n    elif(age<=55):\n        a='mid-age'\n    else:\n        a='old'\n    return a\ntrain['age_group']=train.Age2.map(age_group)\ntest['age_group']=test.Age_test.map(age_group)\ntrain.age_group.value_counts()\n\n#creating categories acc. to fare: fare per person\ntrain['fare_per_person']=train['Fare']\/train['family_size']\ntest['fare_per_person']=test['Fare']\/test['family_size']\n\ndef fare_group(fare):\n    a=''\n    if(fare<=4):\n        a='very-low'\n    elif(fare<=10):\n        a='low'\n    elif(fare<=20):\n        a='mid'\n    elif(fare<=45):\n        a='high'\n    else:\n        a='very-high'\n    return a\ntrain['fare_group']=train.fare_per_person.map(fare_group)\ntest['fare_group']=test.fare_per_person.map(fare_group)\n\ntest.fare_group.value_counts()\n#creating dummy variables\ntrain=pd.get_dummies(train,columns=['Embarked','family_group','age_group','fare_group'],drop_first=True)\ntest=pd.get_dummies(test,columns=['Embarked','family_group','age_group','fare_group'],drop_first=True)\n\n#will do onehotencoding\ntrain.shape\ntest.shape\n#dropping unnecessary columns\ntrain.drop(['Name','Ticket','Fare','Age2','fare_per_person','family_size'],axis=1,inplace=True)# Fare and fare-per_person are replaced by fare_group, age by age_group, family by family_group\ntest.drop(['Name','Ticket','Fare','Age_test','fare_per_person','family_size'],axis=1,inplace=True)\ntest.head()\nX=train.drop('Survived',1)\ny=train['Survived']\n\n\nfrom xgboost import XGBClassifier\nxgb=XGBClassifier()\n\nfrom sklearn.model_selection import cross_val_score\nscore = cross_val_score(xgb, X, y, n_jobs=1, scoring= 'accuracy')\nprint(score)\nround(np.mean(score)*100, 2)\ntest.head()\nxgb=XGBClassifier()\nxgb.fit(X, y)\n#test_data = test.drop(['PassengerId'], axis=1).copy()\nprediction = xgb.predict(test)\nprint(prediction)\nprint(len(prediction))\nsubmission = pd.DataFrame({\n        \"PassengerId\": test1['PassengerId'],\n        \"Survived\": prediction\n    })\n\nsubmission.to_csv('submission.csv', index=False)\n\nsubmission = pd.read_csv('submission.csv')\n\"\"\"\n> > <a href=\".\/submission.csv\"> Download File <\/a>\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '107978e1d8cadb'}"}
{"id":"17652","text":"\"\"\"\n#  Classification using Decision Tree\n## Decision trees on Spotify Song Attributes dataset \n\"\"\"\n\"\"\"\n## 0. Importing packages\n\"\"\"\nimport pandas as pd\n\n# Dummy model and Decision Tree Classifier\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.model_selection import(\n    cross_validate,\n    train_test_split\n)\nfrom sklearn.tree import (\n    DecisionTreeClassifier,\n    export_graphviz\n)\n\n# Visualization in the EDA section\nimport altair as alt\nalt.renderers.enable('kaggle')\nimport seaborn as sns\n\n# Visualizing the final tree diagram\nimport re\nimport graphviz\nfrom IPython.display import Image\n\"\"\"\n## 1. Reading the data CSV\n\"\"\"\n# Will be required to download spotify dataset in the machine\nspotify_df = pd.read_csv('\/kaggle\/input\/spotifyclassification\/data.csv', index_col=0)\nspotify_df\n\"\"\"\n## 2. Data splitting \n\"\"\"\ntrain_df, test_df = train_test_split(spotify_df,\n                                     train_size=0.8,\n                                     random_state=2021)\nspotify_df.shape\ntrain_df.shape[0]\n\"\"\"\nTotal data frame size has 2017 examples.  \nThe test size data frame has 20% of the examples = 404  \nThe training size data frame has 80% of the examples = 1613\n\"\"\"\n\"\"\"\n## 3. Preliminary EDA\n\"\"\"\ntrain_df.info()\n\"\"\"\nLuckily, we do not have any `NAN` values in the dataset. We have a combination of numeric and text features.\n\"\"\"\ntrain_df.describe()\n\"\"\"\nThere are not much outliers in the dataset as can be seen from the ranges above.\n\"\"\"\n\"\"\"\n## 4. EDA \n\"\"\"\n\"\"\"\n### 4.1 Relationship among the features\n\"\"\"\ncorr_df = train_df.corr('spearman').stack().reset_index(name='corr')\ncorr_df.loc[corr_df['corr'] == 1, 'corr'] = 0  # Remove diagonal\n# Use abs so that we can visualize the impact of negative correaltion  \ncorr_df['abs'] = corr_df['corr'].abs()\ncorr_df.sort_values('abs', ascending=False)\nalt.Chart(corr_df).mark_circle().encode(\n    x='level_0',\n    y='level_1',\n    size='abs',\n    color=alt.Color('corr',\n                    scale=alt.Scale(scheme='blueorange',\n                                    domain=(-1, 1))))\n\"\"\"\nThe three standout correlation relationships which can be observed from the graph above are:\n1. `loudness` and `energy`\n2. `acousticness` and `energy`\n3. `danceability` and `valence`\n\nThe good thing is that the relationship is not too strong, and the rest of the features seem fairly unrelated to each other.\n\"\"\"\n\"\"\"\n### 4.2 Relationship between the features and the target\n\"\"\"\nsns.violinplot(x=\"energy\",  y=\"target\", data=train_df, orient=\"h\")\nsns.violinplot(x=\"acousticness\",  y=\"target\", data=train_df, orient=\"h\")\nsns.violinplot(x=\"tempo\",  y=\"target\", data=train_df, orient=\"h\")\n\"\"\"\nAfter trying multiple relations between the target and features, we observe that:\n1. There is some bimodality for not liking the song for features `tempo` and `energy`.\n2. `acousticness` is unimodal but it is more dense when the user likes the song.\n\"\"\"\n\"\"\"\n## 5. Data splitting \n\"\"\"\n\"\"\"\nFor our basic analysis, we are avoiding vectorizing the text columns. This can be incorporated using CountVectorzier or TD-IDF.\n\"\"\"\nX = spotify_df.drop(columns=[\"song_title\", \"artist\", \"target\"])\ny = spotify_df[\"target\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n        train_size=0.8, test_size=0.2, random_state=123)\n\"\"\"\n## 6. Hyperparameter optimization of max_depth\n\"\"\"\n\"\"\"\nBelow we define a function to calculate the validation and train score at a specific depth.\n\"\"\"\ndef cross_validate_return(X_train, y_train, depth):\n    \"\"\"\n    Fits a Decision tree basis the depth provided and \n    returns the accuracies and depth as list\n\n    Parameters\n    ----------\n    X_train: numpy.ndarray\n        The X_train part of the data\n    y_train: numpy.ndarray\n        The y_train part of the data\n    depth: int\n        The depth of the Decision Tree\n\n    Returns\n    -------\n        list of train_score, test_score, depth\n    \"\"\"\n    model = DecisionTreeClassifier(max_depth=depth, random_state=123)\n    scores = cross_validate(model, X_train, y_train, \n                        return_train_score=True, cv=10)\n    return_df = pd.DataFrame(pd.DataFrame(scores).mean()).iloc[2:].T\n    return [round(return_df.train_score[0], 3),\n            round(return_df.test_score[0],3), depth]\n\ndata = []\ni = 1\nwhile i < 26:\n    data.append(cross_validate_return(X_train, y_train, i))\n    i += 1\n\ndf = pd.DataFrame(data, columns=['train_score', 'validation_score',\n                  'max_depth'])\ndf.head(n=5)\n\"\"\"\nWe now melt the df so that we can plot train and validation score separately.\n\"\"\"\ncv_df = df.melt(value_vars=([\"train_score\", \"validation_score\"]), id_vars=[\"max_depth\"])\ncv_df.head(n=5)\nalt.Chart(cv_df).mark_line().encode(\n    x=alt.X('max_depth', title='Max depth of tree'),\n    y=alt.Y('value', title='Score value',\n           scale=alt.Scale(domain=[0.6, 1.05])), \n    color=alt.Color('variable', title='Score'))\n\"\"\"\n- We can see in the plot that we get maximum validation score at max_depth = 4 and the difference between train and validation score is the least at this point as well. This will be our optimal maximum depth. \n- We assume that since it has delivered the best validation score at this depth, the test score will be best at this point as well.\n\"\"\"\n\"\"\"\n#### **`max_depth` and the Fundamental Tradeoff**\n\"\"\"\n\"\"\"\n- Increasing the max_depth increases the training accuracy of the Decision Tree as we add more branches\/leaves to the tree and we end up adding all the random quirks of the training set.  \n- Increasing the max_depth increases the validation accuracy till a point and then it starts decreasing as the overfitting on the training set fails to generalize well on the validation set.\n\"\"\"\n\"\"\"\n## 7. Picking the best value for `max_depth`\n\"\"\"\noptimal_depth = df.max_depth[df.validation_score.argmax()]\n\nprint(\"We pick the value where the cross-validation error is \"\n      \"minimum (or the cross-validation score is the highest)\"\n      f\" at max_depth = {optimal_depth}\")\n\"\"\"\n## 8. Model performance on the test set\n\"\"\"\nprint(f\"Validation score at optimal depth: {df.validation_score[3]}\")\noptimal_model = DecisionTreeClassifier(max_depth=optimal_depth)\noptimal_model.fit(X_train, y_train)\nprint(f\"Score on test set: { optimal_model.score(X_test, y_test):.3f}\")\n\"\"\"\nTest score is less than our cross-validation score. Our optimal depth ends up giving a fair estimate of how much accuracy we can expect from our best model.\n\"\"\"\n\"\"\"\n## 9. Visualizing our optimal Decision Tree!\n\"\"\"\n# adapted from https:\/\/stackoverflow.com\/questions\/44821349\/python-graphviz-remove-legend-on-nodes-of-decisiontreeclassifier\n\ndef display_tree(feature_names, tree, counts=False):\n    \"\"\"For binary classification only\"\"\"\n    dot = export_graphviz(\n        tree,\n        out_file=None,\n        feature_names=feature_names,\n        class_names=tree.classes_.astype(str),\n        impurity=False,\n    )\n    # dot = re.sub('(\\\\\\\\nsamples = [0-9]+)(\\\\\\\\nvalue = \\[[0-9]+, [0-9]+\\])(\\\\\\\\nclass = [A-Za-z0-9]+)', '', dot)\n    if counts:\n        dot = re.sub(\"(samples = [0-9]+)\\\\\\\\n\", \"\", dot)\n        dot = re.sub(\"value\", \"counts\", dot)\n    else:\n        dot = re.sub(\n            \"(\\\\\\\\nsamples = [0-9]+)(\\\\\\\\nvalue = \\[[0-9]+, [0-9]+\\])\", \"\", dot\n        )\n        dot = re.sub(\n            \"(samples = [0-9]+)(\\\\\\\\nvalue = \\[[0-9]+, [0-9]+\\])\\\\\\\\n\", \"\", dot\n        )\n    return graphviz.Source(dot)\nImage(display_tree(X_train.columns, optimal_model).pipe(\"png\"))\n\"\"\"\n- `instrumentalness` seems the most important feature as it sits at the root and best divides the tree. In our exploratory analysis, we found `danceability` to be a good feature but it is not the best.\n- **Scaling not required:** While using Decision Tree Classification the scale doesn't matter as it does not depend on the variance in the data.\n- **More features can be added:** We can use the Bag of Words technique which throws away the order information of the word and counts the frequencies of each word in it, which is done by assigning a unique number to each word. Alternatively, we can use one-hot encoding to divide the categorical feature into multiple features with labels 0 and 1(when a particular artist is present). This could increase our data size by a big margin if the number of artists is large.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2037f6d3939e7e'}"}
{"id":"41630","text":"\"\"\"\n# **Yes Bank Stock Predication**\n\n\n\n\n\n\"\"\"\n\"\"\"\nProblem Statement - Yes Bank is a well-known bank in the Indian financial domain. Since 2018, it has been in the news because of the fraud case involving Rana Kapoor. Owing to this fact, it was interesting to see how that impacted the stock prices of the company and whether Time series models or any other predictive models can do justice to such situations. This dataset has monthly stock prices of the bank since its inception and includes closing, starting, highest, and lowest stock prices of every month. The main objective is to predict the stock\u2019s closing price of the month.\n\"\"\"\n\"\"\"\n**Let's Get to know what is stock?**\n\nA Stock or share (also known as a company\u2019s 'equity') is a financial instrument that represents ownership in a company. Units of stock are called \"shares.\" Stocks are bought and sold predominantly on stock exchanges, though there can be private sales as well, and are the foundation of many individual investors' portfolios.\n\"\"\"\n# Importing Required Library\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom numpy import math\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom scipy.stats import zscore\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn import metrics\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n# **Importing and Loading data**\n\"\"\"\n# using pandas library and 'read_csv' function to read YesBank_StockPrices csv file\ndataset = pd.read_csv('..\/input\/yes-bank-stock\/data_YesBank_StockPrices.csv')\ndataset.head()\ndataset.tail()\n\"\"\"\n# **Data Exploration**\n\"\"\"\n#information of the dataset \ndataset.info()\n#number of rows and columns \ndataset.shape\nnumerical_col = dataset.describe().columns\n\"\"\"\nThis dataset has 185 observations in it with 5 columns(features)\n\"\"\"\n\"\"\"\n**Data Distribution and mean and median of each single Indpendent variable**\n\"\"\"\nfor i in numerical_col[:]:\n  fig = plt.figure(figsize=(15,8))\n  ax = fig.gca()\n  features = dataset[i]\n  label = dataset['Close']\n  features.hist(bins = 50,ax = ax,color = 'blue')\n  ax.axvline(features.mean(),color = 'magenta',linestyle = 'dashed',linewidth = 2)\n  ax.axvline(features.median(),color = 'cyan',linestyle = 'dashed',linewidth = 2)\n  ax.set_title(i)\n\"\"\"\n# **Variable Identification and Understanding Data**\n\"\"\"\nfrom datetime import datetime\ndataset['Date'] = pd.to_datetime(dataset['Date'].apply(lambda x: datetime.strptime(x,'%b-%y')))\n#Decription of dataset \ndataset.describe(include='all')\n\"\"\"\nWith the help of describe we can conclude that data is not normally distributed as mean is higher than median in all features\n\"\"\"\n# Identify Numerical Columns\nnumerical_col = dataset.describe().columns\nnumerical_col\n# Line Plot\nplt.figure(figsize=(15,8))\nplt.plot(dataset['Close'])\nplt.plot(dataset['Open'])\nplt.plot(dataset['High'])\nplt.legend(['Close','Open','High'])\nplt.grid()\n\"\"\"\n## **Checking for NuN values and Outliers**\n\"\"\"\n# Checking Null Values\ndataset.isnull().sum()\n# checking duplicate values\nlen(dataset[dataset.duplicated()])\nplt.figure(figsize=(15,8))\ndataset.boxplot('Open')\nplt.show()\n\"\"\"\n# **Exploratory Data Analysis**\n\"\"\"\n\"\"\"\n**Dependent Variable**\n\"\"\"\nplt.figure(figsize=(15,8))\nsns.distplot(dataset['Close'],color='blue')\nplt.show()\n# For normal Distribution \nplt.figure(figsize=(15,8))\nsns.distplot(np.log10(dataset['Close']),color='blue')\nplt.show()\n\n\"\"\"\n**Independent Variable**\n\"\"\"\n# Independent variables\nplt.figure(figsize=(15,8))\nsns.distplot(dataset['Open'], color='blue')\n\nplt.figure(figsize=(15,8))\nsns.distplot(dataset['High'], color='blue')\n\nplt.figure(figsize=(15,8))\nsns.distplot(dataset['Low'], color='blue')\nplt.figure(figsize=(15,8))\nsns.distplot(np.log10(dataset['Open']), color='blue')\n\nplt.figure(figsize=(15,8))\nsns.distplot(np.log10(dataset['High']), color='blue')\n\nplt.figure(figsize=(15,8))\nsns.distplot(np.log10(dataset['Low']), color='blue')\n# Correaltion Between the Variables\ncorr = dataset.corr()\nplt.figure(figsize = (15,8))\nsns.heatmap(abs(corr),annot = True,cmap = 'coolwarm')\n\"\"\"\n**Finding Correlation Between Variables**\n\"\"\"\nfor col in numerical_col[:]:\n  fig = plt.figure(figsize = (15,8))\n  ax = fig.gca()\n  features = dataset[col]\n  label = dataset['Close']\n  correlation = features.corr(label)\n  plt.scatter(x = features,y = label)\n  plt.xlabel(col)\n  plt.ylabel('Close')\n  plt.title('Price Vs  ' + col + '_ correlation:' + str(correlation))\n  z = np.polyfit(dataset[col],dataset['Close'],1)\n  y_hat = np.poly1d(z)(dataset[col])\n  plt.plot(dataset[col] , y_hat, \"r--\",lw = 2)\nplt.show()\n\"\"\"\n**Multicollinearity**\n\"\"\"\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\ndef cal_vif(X):\n  vif = pd.DataFrame()\n  vif[\"variables\"] = X.columns\n  vif[\"VIF\"] = [variance_inflation_factor(X.values,i) for i in range(X.shape[1])]\n\n  return(vif)\ncal_vif(dataset[[i for i in dataset.describe().columns if i not in ['Close','Date']]])\nplt.figure(figsize=(15,8))\ndataset[['Close','Open']].tail(30).plot(kind='bar',figsize=(15,8))\n\"\"\"\n# **Linear Regression Model**\n\"\"\"\n\"\"\"\n**Normalization**\n\"\"\"\n# Splitting our data into Dependent and Independent Variables\nX = dataset.drop(columns=['Close','Date']).apply(zscore)\ny = np.log10(dataset['Close'])\n\"\"\"\n**Train Test Split**\n\"\"\"\n# Creating Testing and Training Datasets\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.20,random_state = 1)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n\"\"\"\n## **Linear Regrassion**\n\"\"\"\nreg = LinearRegression()\nreg_model = reg.fit(X_train,y_train)\nreg.score(X_train,y_train)\ny_test_pred = reg.predict(X_test)\ny_train_pred = reg.predict(X_train)\nreg.intercept_\nreg.coef_\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test, y_test_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_test_pred)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_test_pred))\nprint(\"R2 :\",r2_score(y_test, y_test_pred))\n# Train Performance\nprint(\"MSE :\",mean_squared_error(y_train, y_train_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_train, y_train_pred)))\nprint(\"MAE :\",mean_absolute_error(y_train, y_train_pred))\nprint(\"R2 :\",r2_score(y_train, y_train_pred))\n\"\"\"\n**Linear Regression Predication vs Actual**\n\"\"\"\n# Linear Regression Plotting\nplt.figure(figsize=(15,8))\nplt.plot(10**(np.array(y_test)))\nplt.plot(10**(y_test_pred))\nplt.legend(['Actual','Predicted'])\nplt.grid()\nplt.show()\n\"\"\"\n## **Lasso Regression**\n\"\"\"\nfrom sklearn.linear_model import Lasso\nlasso = Lasso(alpha=0.005,max_iter=3000)\nlasso_model = lasso.fit(X_train,y_train)\nlasso.score(X_train,y_train)\ny_lasso_pred = lasso.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test,y_lasso_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_lasso_pred)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_lasso_pred))\nprint(\"R2 :\",r2_score(y_test, y_lasso_pred))\n\"\"\"\n**Lasso Predication vs Actual**\n\"\"\"\nplt.figure(figsize=(15,8))\nplt.plot(y_lasso_pred)\nplt.plot(np.array(y_test))\nplt.legend([\"Predicted\",\"Actual\"])\nplt.xlabel('No of Test Data')\nplt.grid()\nplt.show()\n\"\"\"\n### **Cross Validification**\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\n# Hyper-parameter Tuning\n\nlasso_cv = Lasso()\nparameters = {'alpha':[1e-15,1e-13,1e-10,1e-8,1e-5,1e-4,1e-3,1e-2,1e-1,1,5,10,20,30,40,45,50,55,60,100,0.0014]}\nlasso_model = GridSearchCV(lasso_cv,parameters,scoring = 'neg_mean_squared_error',cv = 3)\nlasso_model.fit(X_train,y_train)\nprint(\"The best fit alpha value is found out to be :\" ,lasso_model.best_params_)\nprint(\"\\nUsing \",lasso_model.best_params_, \" the negative mean squared error is: \", lasso_model.best_score_)\ny_pred_lasso = lasso_model.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test, y_pred_lasso))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_pred_lasso)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_pred_lasso))\nprint(\"R2 :\",r2_score(y_test, y_pred_lasso))\n\"\"\"\n**Lasso Predication vs Actual (After Validification)**\n\"\"\"\n# Lasso plotting\nplt.figure(figsize=(15,8))\nplt.plot(10**(np.array(y_test)))\nplt.plot(10**(y_pred_lasso))\nplt.legend(['Actual','Predicted'])\nplt.grid()\nplt.show()\n\"\"\"\n## **Ridge Linear Regression**\n\"\"\"\nfrom sklearn.linear_model import Ridge\nridge  = Ridge(alpha=0.1)\nridge.fit(X_train,y_train)\nridge.score(X_train, y_train)\ny_ridge_pred = ridge.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test performance\n\nprint(\"MSE :\",mean_squared_error(y_test, y_ridge_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_ridge_pred)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_ridge_pred))\nprint(\"R2 :\",r2_score(y_test, y_ridge_pred))\n\"\"\"\n**Ridge Predication vs Actual**\n\"\"\"\nplt.figure(figsize=(15,8))\nplt.plot(y_ridge_pred)\nplt.plot(np.array(y_test))\nplt.legend([\"Predicted\",\"Actual\"])\nplt.xlabel('No of Test Data')\nplt.grid()\nplt.show()\n\"\"\"\n### **Cross Validification**\n\"\"\"\n# Hyper-parameter Tuning\nridge_cv = Ridge()\nparameters = {'alpha':[1e-15,1e-13,1e-10,1e-8,1e-5,1e-4,1e-3,1e-2,1e-1,1,5,10,20,30,40,45,50,55,60,100]}\nridge_model = GridSearchCV(ridge_cv,parameters,scoring='neg_mean_squared_error',cv=3)\nridge_model.fit(X_train,y_train)\nprint(\"The best fit alpha value is found out to be :\" ,ridge_model.best_params_)\nprint(\"\\nUsing \",ridge_model.best_params_, \" the negative mean squared error is: \", ridge_model.best_score_)\n# Model Predication\ny_pred_ridge  = ridge_model.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test, y_pred_ridge))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_pred_ridge)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_pred_ridge))\nprint(\"R2 :\",r2_score(y_test, y_pred_ridge))\n\"\"\"\n**Ridge Predication vs Actual (After Validification)**\n\"\"\"\nplt.figure(figsize=(15,8))\nplt.plot(y_pred_ridge)\nplt.plot(np.array(y_test))\nplt.legend([\"Predicted\",\"Actual\"])\nplt.xlabel('No of Test Data')\nplt.grid()\nplt.show()\n\"\"\"\n## **Elastic Net Linear Regression**\n\"\"\"\nfrom sklearn.linear_model import ElasticNet\nelastic = ElasticNet(alpha=0.1,l1_ratio=0.5)\nelastic.fit(X_train,y_train)\ny_elastic_pred = elastic.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test, y_elastic_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test, y_elastic_pred)))\nprint(\"MAE :\",mean_absolute_error(y_test, y_elastic_pred))\nprint(\"R2 :\",r2_score(y_test, y_elastic_pred))\n\"\"\"\n**ElasticNet Predication vs Actual**\n\"\"\"\nplt.figure(figsize=(15,8))\nplt.plot(y_elastic_pred)\nplt.plot(np.array(y_test))\nplt.legend([\"Predicted\",\"Actual\"])\nplt.xlabel('No of Test Data')\nplt.grid()\nplt.show()\n\"\"\"\n### **Cross Validification**\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\nelastic_cv = ElasticNet()\nparameters = {'alpha':[1e-15,1e-13,1e-10,1e-8,1e-5,1e-4,1e-3,1e-2,1e-1,1,5,10,20,30,40,45,50,55,60,100],'l1_ratio':[0.3,0.4,0.5,0.6,0.7,0.8,1,2]}\nelastic_model = GridSearchCV(elastic_cv,parameters,scoring='neg_mean_squared_error',cv=3)\nelastic_model.fit(X_train,y_train)\nprint(\"The best fit alpha value is found out to be :\" ,elastic_model.best_params_)\nprint(\"\\nUsing \",elastic_model.best_params_, \" the negative mean squared error is: \", elastic_model.best_score_)\ny_elastic_pred = elastic_model.predict(X_test)\n\"\"\"\n**Evaluation Matrics**\n\"\"\"\n# Test Performance\nprint(\"MSE :\",mean_squared_error(y_test, y_elastic_pred))\nprint(\"RMSE :\",math.sqrt(mean_squared_error(y_test,y_elastic_pred )))\nprint(\"MAE :\",mean_absolute_error(y_test, y_elastic_pred))\nprint(\"R2 :\",r2_score(y_test, y_elastic_pred))\n\"\"\"\n**ElasticNet Predication vs Actual (After Validification)**\n\"\"\"\nplt.figure(figsize=(15,8))\nplt.plot(10**(np.array(y_test)))\nplt.plot(10**(y_elastic_pred))\nplt.legend(['Actual','Predicted'])\nplt.grid()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '4cba611bb2caf9'}"}
{"id":"36835","text":"\"\"\"\n\n# Abstract\n\nA colleague has reached out to me for advice on a nice place to live in Istanbul. I have interpreted this request as my mission to analyze which district of Istanbul has access to more and various green spaces within a 20km distance. I have used geopy, foursquare API and a wikipedia table to scrape and manipulate data of district names, name of green spaces, their longitude and latitude values. I have used k-means algorithm to cluster the variety and used my data frame to count the number of green spaces each district has access to. After analysis, I have found that **\u00c7atalca** is the district with access to most green spaces with a wide variety and the least desirable districts are **Beylikd\u00fcz\u00fc** and **Arnavutk\u00f6y** (see my article: [The quest for a breath of fresh air](https:\/\/www.linkedin.com\/pulse\/quest-breath-fresh-air-analysis-districts-istanbul-access-sa\u011f\u0131ro\u011flu\/) and the full repo:[github_repo](https:\/\/github.com\/cansagiroglu\/Coursera_Capstone\/tree\/master\/Project_TBON)\n\n# Discussion\nThe data I have gathered with the Foursquare API is a user based collection of data, meaning the amount of data is limited with the user input, considering Foursquare lost its popularity by about 2015 or so (although a lot of the apps and services we render today use their API service) the data gathered from their resource may not have been an accurate description of the great outdoors I was looking for; thus the 20km radius I have set in order to get a variety of places. I do not believe this is of significant importance while deriving an analysis but a minor detail that needs to be mentioned.\n\nThe location data that I have gathered consisting of latitude and longitude is approximately at the center of each district, this does not necessarily mean that an individual would reside at the center of each district, once again, this is the main reason why I introduced the 20 km radius. One solution to this could have easily been using neighbourhoods rather than districts but since Istanbul has very little amount of green spaces, the analysis would have painted a darker picture than we have already produced.\n\nRandom state and number of clusters when using the k-means algorithm could have been varied to observe the effect they have on the clustering mechanism, since the access to number of green spaces and variety didn't necessarily concur with one another in my results; but nevertheless the produced results are a good representation.\n\"\"\"\n!conda install -c conda-forge folium=0.5.0 --yes # comment\/uncomment if not yet installed.\n!conda install -c conda-forge geopy --yes        # comment\/uncomment if not yet installed\n\nimport numpy as np # library to handle data in a vectorized manner\nimport pandas as pd # library for data analsysis\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\nimport json # library to handle JSON files\nfrom geopy.geocoders import Nominatim # convert an address into latitude and longitude values\nfrom pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe\n# Matplotlib and associated plotting modules\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\nimport matplotlib.pyplot as plt\n\n# import k-means from clustering stage\nfrom sklearn.cluster import KMeans\nimport folium # map rendering library\nfrom sklearn.preprocessing import StandardScaler #we are going to use this to find the optimal k for clustering\nfrom sklearn.metrics import silhouette_score #once again when finding the optimal k\n\nimport requests # library to handle requests\nimport bs4 as bs\nimport urllib.request\n\nprint('Libraries imported.')\nurl   = \"https:\/\/en.wikipedia.org\/wiki\/List_of_districts_of_Istanbul\"\nfrom IPython.display import HTML\nimport base64\n\n# Extra Helper scripts to generate download links for saved dataframes in csv format.\ndef create_download_link( df, title = \"Download CSV file\", filename = \"data.csv\"):  \n    csv = df.to_csv()\n    b64 = base64.b64encode(csv.encode())\n    payload = b64.decode()\n    html = '<a download=\"{filename}\" href=\"data:text\/csv;base64,{payload}\" target=\"_blank\">{title}<\/a>'\n    html = html.format(payload=payload,title=title,filename=filename)\n    return HTML(html)\n\npage  = urllib.request.urlopen(url).read()\nsoup  = bs.BeautifulSoup(page,'lxml')\ntable = soup.find(\"table\",class_=\"wikitable\")\nheader = [head.findAll(text=True)[0].strip() for head in table.find_all(\"th\")]\ndata   = [[td.findAll(text=True)[0].strip() for td in tr.find_all(\"td\")]\n          for tr in table.find_all(\"tr\")]\ndata    = [row for row in data if len(row) == 6] #I have 6 columns\n\nraww_df= pd.DataFrame(data,columns=header)\nraww_df.to_csv('istanbul_district_income_density_population_area.csv',index=False)\n\nraw_df = pd.DataFrame(data,columns=header)\nraw_df = raw_df[:-4] #removing last 4 rows of unneccessary info.\nraw_df = raw_df.drop(raw_df.columns[[4,5]], axis=1) #removing last 2 columns of unneccessary info.\nraw_df = raw_df.replace(',','', regex=True) #removing commas from numbers\nraw_df['Population (2019)'].astype(str).astype(float)\nraw_df['Area (km\u00b2)'].astype(str).astype(float)\nraw_df['Density (per km\u00b2)'].astype(str).astype(float) #converting from string to float\nraw_df=raw_df.sort_values(by=['District','Population (2019)','Area (km\u00b2)','Density (per km\u00b2)'], ascending=[1,1,1,1]).reset_index(drop=True)\n\nprint(raw_df.info(verbose=True))\ncreate_download_link(raww_df,\"Istanbul District List 2019(income_density_population_area)\",\"istanbul_district_income_density_population_area_2019.csv\")\ncreate_download_link(raw_df,\"Istanbul District List 2019(population_area_density)\",\"istanbul_district_population_area_density_2019\")\nraw_df.head()\ngeolocator = Nominatim(user_agent='My-Notebook')\nlokasyon=[]\nlat=[]\nlon=[]\nfor x in range(0, len(raw_df)):#some district names like \u015eile gets mistaken for Chile so we add Istanbul next to them.\n    lokasyon.append(raw_df.loc[x,'District']+', Istanbul')\nfor r in range(0, len(raw_df)):\n    location = geolocator.geocode(lokasyon[r])\n    lat.append(location.latitude)\n    lon.append(location.longitude)\nmap(float, lat)#converting to float\nmap(float, lon)\nraw_df = raw_df.assign(Latitude = lat) #adding lat and lon values for districts\nraw_df = raw_df.assign(Longitude = lon)\nraw_df = raw_df.drop(raw_df.columns[[1,2,3]], axis=1) #should've done this earlier, but firmly decided not to use population now, so, off they go.\nraw_df.head()\nraw_df.to_csv('istanbul_district_latlon.csv',index=False) #storing into a csv for proper use, whatever that means.\ncreate_download_link(raw_df,\"Istanbul District List 2019(district_lat_lon)\",\"istanbul_district_latlon.csv\")\nist = pd.read_csv('istanbul_district_latlon.csv')\n#getting the coordinates for Istanbul for map creation\naddress = 'Istanbul Turkey'\n\nlocationist = geolocator.geocode(address)\nlatitudist = locationist.latitude\nlongitudist = locationist.longitude\nprint('The geograpical coordinates for Istanbul are {}, {}.'.format(latitudist, longitudist))\n#creating a map of Istanbul with Districts\nmap_istanbul = folium.Map(location=[latitudist, longitudist], zoom_start=10)\n\n# add markers to map\nfor lat, lng, label in zip(ist['Latitude'], ist['Longitude'], ist['District']):\n    label = folium.Popup(label, parse_html=True)\n    folium.CircleMarker(\n        [lat, lng],\n        radius=6,\n        popup=label,\n        color='blue',\n        fill=True,\n        fill_color='#87cefa',\n        fill_opacity=0.5,\n    ).add_to(map_istanbul)\nmap_istanbul\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nCLIENT_ID = user_secrets.get_secret(\"Foursquare ID\")\nCLIENT_SECRET = user_secrets.get_secret(\"Foursquare secret\")\nVERSION = '20180604'\nLIMIT = 50\n\n# Get the venue names and store it in a dataframe\ndef getNearbyVenues(names, latitudes, longitudes, radius=20000):#20km radius to filter every possible option since we are dealing with districts.\n                                                                #Since we also deal with islands 20km is overkill, but would give an idea anyway.\n    venues_list=[]\n    for name, lat, lng in zip(names, latitudes, longitudes):\n        # creating API request url\n        url = 'https:\/\/api.foursquare.com\/v2\/venues\/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(\n            CLIENT_ID, \n            CLIENT_SECRET, \n            VERSION, \n            lat, \n            lng, \n            radius, \n            LIMIT)\n            \n        # GET request\n        results = requests.get(url).json()[\"response\"]['groups'][0]['items']\n        \n        # return only relevant information for each nearby venue\n        venues_list.append([(\n            name, \n            lat, \n            lng, \n            v['venue']['name'], \n            v['venue']['location']['lat'], \n            v['venue']['location']['lng'],  \n            v['venue']['categories'][0]['name']) for v in results])\n\n    nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])\n    nearby_venues.columns = ['District', \n                  'District Latitude', \n                  'District Longitude', \n                  'Venue', \n                  'Venue Latitude', \n                  'Venue Longitude', \n                  'Venue Category']\n    return(nearby_venues)\nist_venues=getNearbyVenues(names=ist['District'], latitudes=ist['Latitude'],longitudes=ist['Longitude'])\n#filtering results with parks only\nist_park=ist_venues[ist_venues['Venue Category'].str.contains('Park')]\n#and forests\nist_orman=ist_venues[ist_venues['Venue Category'].str.contains('Forest')] \n#and gardens\nist_bahce=ist_venues[ist_venues['Venue Category'].str.contains('Garden')] \n#and dogruns eventghough you may not be a dog person\nist_dog=ist_venues[ist_venues['Venue Category'].str.contains('Dog')] \n#and farms considering they are places that you can refresh\nist_cift=ist_venues[ist_venues['Venue Category'].str.contains('Farm')] \n#and parkours where you can take a walk that may be alongside a greenspace\nist_parkur=ist_venues[ist_venues['Venue Category'].str.startswith('Field')]\n#I am pushin the boundaries and counting mountain tops as green spaces too.\nist_dag=ist_venues[ist_venues['Venue Category'].str.contains('Mountain')] \n#In the context of green spaces, cemeteries are also in the mix, but I assume no one would go to a cemetery to get a breath of fresh air.\n\nist_green=ist_park #creating a dataframe where all of them are listed.\nist_green=ist_green.append(ist_orman)\nist_green=ist_green.append(ist_bahce)\nist_green=ist_green.append(ist_dag)\nist_green=ist_green.append(ist_cift)\nist_green=ist_green.append(ist_dog)\nist_green=ist_green.append(ist_parkur)\n#reseting the indexing for the dataframe\nist_green=ist_green.sort_values(by=['District','District Latitude','District Longitude','Venue','Venue Latitude','Venue Longitude','Venue Category'], ascending=[1,1,1,1,1,1,1]).reset_index(drop=True)\nist_green.to_csv('istanbul_greenspaces.csv',index=False) #storing into a csv for proper use, whatever that means.\nist_green.head()\ncreate_download_link(ist_green,\"Istanbul District List 2019(district_nearbygreen20km_venue_lat_lon)\",\"istanbul_greenspaces.csv\")\nprint('There are {} unique venues.'.format(len(ist_green['Venue'].unique()))) #No of unique green spaces\n#lets see the map where these greens are located\nfor lat, lng, label in zip(ist_green['Venue Latitude'], ist_green['Venue Longitude'], ist_green['Venue']):\n    label = folium.Popup(label, parse_html=True)\n    folium.CircleMarker(\n        [lat, lng],\n        radius=6,\n        popup=label,\n        color='green',\n        fill=True,\n        fill_color='#87cefa',\n        fill_opacity=0.5,\n    ).add_to(map_istanbul)\nmap_istanbul\n#The venues are not unique to their respective districts, lets see which district has more greenspace.\n\nplt.figure(figsize=(10,10), dpi = 100)\nplt.title('Number of Green Spaces for each District in Istanbul')\n#On x-axis\nplt.xlabel('No.of Greenspaces', fontsize = 15)\n#On y-axis\nplt.ylabel('District Name', fontsize=15)\n#giving a bar plot\nist_green.groupby('District')['Venue'].count().sort_values(ascending=True).plot(kind='barh',color='green')\n#displays the plot\nplt.show()\n#We can see from our graph that Adalar, \u00c7atalca and Maltepe are the most green Districts\n#While a total of 11 districts from Gaziosmanpa\u015fa and G\u00fcng\u00f6ren are the least green.\n# one hot encoding\nist_onehot = pd.get_dummies(ist_green[['Venue Category']], prefix=\"\", prefix_sep=\"\")\n\n# add district column back to dataframe\nist_onehot['District'] = ist_green['District'] \n\n# move district column to the first column\nfixed_columns = [ist_onehot.columns[-1]] + list(ist_onehot.columns[:-1])\nist_onehot = ist_onehot[fixed_columns]\n\n# Regroup rows by district and mean of frequency occurrence per category.\nist_grouped = ist_onehot.groupby('District').mean().reset_index()\nist_grouped.to_csv('istanbul_greenspaces_freq_district.csv',index=False) #storing into a csv for proper use, whatever that means.\n#lets check the optimal value of k we should use in order to obtain ideal clustering\nist_grouped_clustering =ist_grouped.drop('District', 1)\nist_std = StandardScaler().fit_transform(ist_grouped_clustering)\nsse = []\nsil = []\nlist_k = list(range(2, 12))\n\nfor k in list_k:\n    km = KMeans(n_clusters=k, random_state=1)\n    km.fit(ist_std)\n    sse.append(km.inertia_)\n    sil.append(silhouette_score(ist_std, km.labels_))\n\nfig, ax1 = plt.subplots(figsize=(6, 6))\n\nax2 = ax1.twinx()\nax1.plot(list_k, sse, 'bo-')\nax2.plot(list_k, sil, 'rd-')\n\nax1.set_xlabel(r'Number of clusters *k*')\nax1.set_ylabel('Sum of inner squared distance', color='b')\nax2.set_ylabel('Silhouette score', color='r')\n\nplt.show()\n# We can see k=6 is best.\nkclusters = 6\n# run k-means clustering\nkmeans = KMeans(n_clusters=kclusters, random_state=1).fit(ist_grouped_clustering)\n# check cluster labels generated for each row in the dataframe\nprint(kmeans.labels_[0:10])\nist_sorted = ist.set_index(\"District\")\nist_merged = ist_grouped.set_index(\"District\")\nist_merged['Cluster Labels'] = kmeans.labels_\nist_merged = ist_merged.join(ist_sorted)\n# creating the map for clusters\nmap_clusters = folium.Map(location=[latitudist, longitudist], tiles=\"Openstreetmap\", zoom_start=10)\n\n\n# set color scheme for the clusters\nx = np.arange(kclusters)\nys = [i+x+(i*x)**2 for i in range(kclusters)]\ncolors_array = cm.rainbow(np.linspace(0, 1, len(ys)))\nrainbow = [colors.rgb2hex(i) for i in colors_array]\n\n# add markers to the map\nmarkers_colors = []\nfor lat, lon, poi, cluster in zip(ist_merged['Latitude'], ist_merged['Longitude'], ist_merged.index.values,kmeans.labels_):\n    label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True)\n    folium.CircleMarker(\n        [lat, lon],\n        radius=10,\n        popup=label,\n        color=rainbow[cluster-1],\n        fill=True,\n        fill_color=rainbow[cluster-1],\n        fill_opacity=1).add_to(map_clusters)   \nmap_clusters\nist_merged.loc[ist_merged['Cluster Labels'] == 0, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The cluster where there is access to a forest.\nist_merged.loc[ist_merged['Cluster Labels'] == 1, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The cluster where there is only access to mainly a Park and a Field\nist_merged.loc[ist_merged['Cluster Labels'] == 2, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The the cluster where there is every category but a mountain top\nist_merged.loc[ist_merged['Cluster Labels'] == 3, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The the cluster where there is only access to a Botanical Garden\nist_merged.loc[ist_merged['Cluster Labels'] == 4, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The the cluster where there is access to a mountain top, field and a park\nist_merged.loc[ist_merged['Cluster Labels'] == 5, ist_merged.columns[[2] + list(range(0, ist_merged.shape[1]))]]\n#The the cluster where there is access to a garden.\n#We can understand from the clusters that the most variety of green spaces are in cluster2\n#And the least variety is in cluster 3 and 5 districts Beylikd\u00fcz\u00fc and Arnavutk\u00f6y\n#From our clustering map and bar graph consisting the access to number of green spaces\n#the ideal district for green space variety and quantity would be \u00c7atalca.\n#The least ideal would either be Arnavutk\u00f6y or Beylikd\u00fcz\u00fc since they only have access to\n#a single botanical garden and a garden.","meta":"{'source': 'AI4Code', 'id': '43cd4b1e41655f'}"}
{"id":"96016","text":"\"\"\"\n# Introduction\n\nThis notebook is intended to extract useful insights for the datasets of \u2018Tabular Playground Series - Mar 2021\u2019 competition in Kaggle. For this competition, it is required to tackle the Regression problem to predict a continuous target based on a number of feature columns given in the data. All of the feature columns, cat0 - cat9 are categorical, and the feature columns cont0 - cont13 are continuous.\n\nWe are going to perform the complete and comprehensive EDA as follows\n-\tAutomate the generic aspects of EDA with AutoViz, one of the leading freeware Rapid EDA tools in Pythonic Data Science world\n-\tDeep into the problem-specific advanced analytical questions\/discoveries with the custom manual EDA routines programmed on top of standard capabilities of Plotly and Matplotlib\n\n\"\"\"\n!pip install xlrd\n!pip install AutoViz\n\"\"\"\n# Initial Preparations\n\nWe are going to start with the essential pre-requisites as follows\n\n- installing *AutoViz* into this notebook\n- importing the standard Python packages we need to use down the road\n- programming the useful automation routines for repeatable data visualizations we are going to draw in the Advance Analytical EDA trials down the road\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport datetime as dt\nfrom typing import Tuple, List, Dict\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly.express as px\nimport plotly.offline\n\n\n# read data\nin_kaggle = True\n\ndef get_data_file_path(is_in_kaggle: bool) -> Tuple[str, str, str]:\n    train_path = ''\n    test_path = ''\n    sample_submission_path = ''\n\n    if is_in_kaggle:\n        # running in Kaggle, inside the competition\n        train_path = '..\/input\/tabular-playground-series-mar-2021\/train.csv'\n        test_path = '..\/input\/tabular-playground-series-mar-2021\/test.csv'\n        sample_submission_path = '..\/input\/tabular-playground-series-mar-2021\/sample_submission.csv'\n    else:\n        # running locally\n        train_path = 'data\/train.csv'\n        test_path = 'data\/test.csv'\n        sample_submission_path = 'data\/sample_submission.csv'\n\n    return train_path, test_path, sample_submission_path\n\n\n# main flow\nstart_time = dt.datetime.now()\nprint(\"Started at \", start_time)\n%%time\n# get the training set and labels\ntrain_set_path, test_set_path, sample_subm_path = get_data_file_path(in_kaggle)\n\ndf_train = pd.read_csv(train_set_path)\ndf_test = pd.read_csv(test_set_path)\n\nsubm = pd.read_csv(sample_subm_path)\n\"\"\"\n# Basic Data Overview\n\"\"\"\ndf_train.info()\n\"\"\"\n# Express EDA Analysis \n\nWe are going to invoke *AutoViz*, one of the prominent freeware Pythonic Rapid EDA tools, to quickly draw the basic insights about the data\n\"\"\"\n\"\"\"\n## Express Analysis of Training Set\n\"\"\"\n\nfrom autoviz.AutoViz_Class import AutoViz_Class\n\nAV = AutoViz_Class()\ndftc = AV.AutoViz(\n    filename='', \n    sep='' , \n    depVar='target', \n    dfte=df_train, \n    header=0, \n    verbose=1, \n    lowess=False, \n    chart_format='png', \n    max_rows_analyzed=300000, \n    max_cols_analyzed=30\n)\n\n\"\"\"\n## Express Analysis Insights\n\nAs we can see, the simple express EDA analysis yielded a lot of useful insights out of the box, in less then 20 minutes of the data crunching. Below are the key finding from the charts generated by *AutoViz* on a generic basis.\n\n### Target Class Labels\n\nIt  is manifested the training dataset has unbalanced class labels for *target* variable. Therefore one of the following techniques has to be adapted in the pre-processing and ML down the road\n\n- oversampling the data using SMOTE or similar technique to balance the class labels in the resulted training set\n- smart undersampling the data to balance the class labels in the resulted training set\n- use adequate class label weights in the modelling with GBDT-style algorithms as well as any other algorithms supporting the class label weights\n\n### Feature-to-Target Relations\n\nWe find that the training set data manifests the following relations between the *target* and feature variables\n\n- all numeric variables except *cont9* demonstrate the good association with the target\n- we may want to try ML experiments with and without *cont9* to see what adds the edge\n- since the dataset seeems to be somewhat similar to the contests in Jan 2021 and Feb 2021\n\n\n### Numeric Feature Findings\n\nIt is demonstrated that\n\n- There is a clear separation of the observations in the training and test sets into well-contained and well separable clusters by the values of *cont4* (2 clusters detected for it, subject to further clustering experiments)\n- *cont5* demonstrates much more clusters in the data, however it is almost sure  to be less productive in ML down the road (similar to what we have observed in Jan 2021 and Feb 2021)\n- Distribution of the continual variables is identic on both the training and testing sets (the details for each variables are provided below)\n- There are certain pairs of highly correlated numeric features with corr >= 0.7 ( cont0-cont01, cont0-cont7, cont1-cont2, cont1-cont8, cont7-cont10)\n- *cont0, cont1, cont2, cont3, cont6, cont7, cont8, cont9*, and *cont10* are highly skewed to the left \n- *cont5* is skewed to the right\n- *cont4* demonstrates the perfrect binomial distribution (and it can be the good feature to use in possible clustering experiments\n\n\n\n### Categorical Feature Findings\n\nFirst of all, unlike the datasets for the tabular playground competitions for Jan and Feb 2021, this dataset proved to have irrelevant (noisy) category variables. *featurewiz*, the secret sauce of *AutoViz*, detected four categories of this sort as follows\n\n- *'cat5'*\n- *'cat7'*\n- *'cat8'*\n- *'cat10'*\n\nIt is suggested to exclude such variables from the ML experiments down the road.\n\nIt has been additionally detected that the rest of the category variables show weak relations with the target and them as well as with the numeric variables (similar to what has been observed in the contests for Jan 2021 and Feb 2021). Therefore the similar ML approaches that worked in the previous playground tabular competitions will be applicable here as well.\n\n\n\n\"\"\"\nprint('We are done. That is all, folks!')\nfinish_time = dt.datetime.now()\nprint(\"Finished at \", finish_time)\nelapsed = finish_time - start_time\nprint(\"Elapsed time: \", elapsed)\n\"\"\"\n# References\n\nSince the dataset in this competition is quite similar to ones for Jan 2021 and Feb 2021 tabular playground competitions, it could be useful to review the EDA findings for the mentioned competitions too\n\n- Feb 2021 Tabular Playground Contest: https:\/\/www.kaggle.com\/gvyshnya\/generic-express-eda-with-comprehensive-insights\n- Jan 2021 Tabular Playground Contest: https:\/\/www.kaggle.com\/gvyshnya\/using-autoviz-to-build-a-comprehensive-eda\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b04ed29a5b0b14'}"}
{"id":"117856","text":"\"\"\"\n# Analysis of Airplane Crashes since 1908\n\"\"\"\n\"\"\"\n## 1. Importing modules\n\"\"\"\n# This Python 3 environment comes with many helpful analytics libraries installed\n\nimport pandas as pd #linear algebra\nimport seaborn as sns #visualization tool\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom scipy import stats as sts  #data processing, CSV file I\/O (e.g. pd.read_csv)\nimport datetime as dt\nfrom collections import Counter\nimport os\n\nprint(os.listdir(\"..\/input\/\"))\n\"\"\"\n## 2. Loading the data\n\"\"\"\ndata = pd.read_csv(\"..\/input\/Airplane_Crashes_and_Fatalities_Since_1908.csv\")\n\"\"\"\nSee first five columns to ensure our data file read correctly\n\"\"\"\ndata.head()\n\"\"\"\n## 3. Data Info and Manipulation\n\"\"\"\ndata.info()\ndata.isnull().any()\n\"\"\"\nAs we can see from the outputs above, we have some NaN values. We will replace these values with 0 for the numeric values.\n\"\"\"\ndata['Fatalities'].fillna(0, inplace = True)\ndata['Aboard'].fillna(0, inplace = True)\ndata['Ground'].fillna(0, inplace = True)\n\"\"\"\nLet's convert the 'Date' column to the appropriate format.\n\"\"\"\ndata['Date'] = pd.to_datetime(data['Date'])\ndata['Date'] = data['Date'].dt.strftime(\"%d\/%m\/%Y\")\ndata['Date'].head()\n\"\"\"\nFor visualization, I create a new column called Year.\n\"\"\"\ndata['Year'] = pd.DatetimeIndex(data['Date']).year\ndata['Year'].head()\n\"\"\"\nWith data on number of fatalities and people aboard,I create a new variable with the number of people that survived the crash and call this variable 'Survived'.I also replace any NaN value with 0 on this column.\n\"\"\"\ndata['Survived'] = data['Aboard'] - data['Fatalities']\ndata['Survived'].fillna(0, inplace = True)\n\"\"\"\nNow our dataframe looks like this.\n\"\"\"\ndata.head()\n\"\"\"\n## 4. Visualizations\n\"\"\"\nmatplotlib.rcParams['figure.figsize'] = (20, 10)\nsns.set_context('talk')\nsns.set_style('whitegrid')\nsns.set_palette('tab20')\n\"\"\"\n### 4.1 Airplane Crashes per Year \n\"\"\"\n\"\"\"\nFirst we summarise to get the count of accidents per year\n\"\"\"\ntotal_crashes_year = data[['Year', 'Date']].groupby('Year').count()\ntotal_crashes_year = total_crashes_year.reset_index()\ntotal_crashes_year.columns = ['Year', 'Crashes']\n\"\"\"\nLine plot with Seaborn.\n\"\"\"\nsns.lineplot(x = 'Year', y = 'Crashes', data = total_crashes_year)\nplt.title('Total Airplane Crashes per Year')\nplt.xlabel('years')\nplt.ylabel('number of crashes')\n\"\"\"\nWe see that after 40's, there is a significant increase in airplane crashes. The highest peaks are between 1960 and 2000.\n\"\"\"\n\"\"\"\n### 4.2 Death Toll per Year\n\"\"\"\npcdeaths_year = data[['Year', 'Fatalities']].groupby('Year').sum()\npcdeaths_year.reset_index(inplace = True)\n# Plot\nsns.lineplot(x = 'Year', y = 'Fatalities', data = pcdeaths_year)\nplt.title('Total Number of Fatalities by Air Plane Crashes per Year')\nplt.xlabel('Fatalities')\nplt.xlabel('Years')\n\"\"\"\nHere we can see the same pattern, the years that had the most accidents are also the ones with the most fatalities\n\"\"\"\n\"\"\"\n### 4.3 People Aboard Airplanes per Year\n\"\"\"\n# summarise\nabrd_per_year = data[['Year', 'Aboard']].groupby('Year').sum()\nabrd_per_year = abrd_per_year.reset_index()\n# plot\nsns.lineplot(x = 'Year', y = 'Aboard', data = abrd_per_year)\nplt.title('Total of People Aboard Airplanes per Year')\nplt.xlabel('Years')\nplt.ylabel('Count')\n\"\"\"\nFrom the 40's, the number of people aboard airplanes starts to increase. From 1960 to 2000 is where we have most people aboard, the same years with most plane crashes and fatalities.\n\"\"\"\n\"\"\"\n### 4.4 Fatalities vs Survived vs Killed on Ground\n\"\"\"\n\"\"\"\nNow we visualize how the number of fatalities compare with the number of survived and those who were killed on the ground.\n\"\"\"\n#summarise\nFSG_per_year = data[['Year', 'Fatalities', 'Survived', 'Ground']].groupby('Year').sum()\nFSG_per_year = FSG_per_year.reset_index()\n#plot\nsns.lineplot(x = 'Year', y = 'Fatalities', data = FSG_per_year, color = 'green')\nsns.lineplot(x = 'Year', y = 'Survived', data = FSG_per_year, color = 'blue')\nsns.lineplot(x = 'Year', y = 'Ground', data = FSG_per_year, color = 'red')\nplt.legend(['Fatalities', 'Survival', 'Ground'])\nplt.xlabel('Years')\nplt.ylabel('Count')\nplt.title('Fatalities vs Survived vs Killed on Ground per Year')\n\"\"\"\n### 4.5 Worst operators and dangerous locations\n\n\"\"\"\noper_list = Counter(data['Operator']).most_common(10)\noperators = []\ncrashes = []\nfor tpl in oper_list:\n    if 'Military' not in tpl[0]:\n        operators.append(tpl[0])\n        crashes.append(tpl[1])\nprint('Top 10 the worst operators')\npd.DataFrame({'Count of crashes' : crashes}, index=operators)\nloc_list = Counter(data['Location'].dropna()).most_common(10)\nlocs = []\ncrashes = []\nfor loc in loc_list:\n    locs.append(loc[0])\n    crashes.append(loc[1])\nprint('Top 10 the most dangerous locations')\npd.DataFrame({'Crashes in this location' : crashes}, index=locs)\n\"\"\"\n## 5. Text Clustering with K-Means\n\"\"\"\n\"\"\"\n### 5.1 Importing needed modules\n\"\"\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.metrics import adjusted_rand_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\"\"\"\n### 5.2 Data Preparation\n\"\"\"\n\"\"\"\nIn the 'Summary' column, we have NaN values as well, so we're going to create a new dataframe with the 'Summary' data and dropping all rows with NaN values.\n\"\"\"\ntext_data = data['Summary'].dropna()\ntext_data = pd.DataFrame(text_data)\n# for reproducibility\nrandom_state = 0 \n\"\"\"\nKMeans normally works with numbers only: we need to have numbers.To get numbers, we do feature extraction.\n\nThe feature we\u2019ll use is TF-IDF, a numerical statistic. This statistic uses term frequency and inverse document frequency.\nThe method TfidfVectorizer() implements the TF-IDF algorithm.\n\"\"\"\ndocuments = list(text_data['Summary'])\nvectorizer = TfidfVectorizer(stop_words='english') # Stop words are like \"a\", \"the\", or \"in\" which don't have significant meaning\nX = vectorizer.fit_transform(documents)\n\"\"\"\n## 5.3 Model Fitting\n\"\"\"\n\"\"\"\nAnd now we fit the model. For this analysis, we'll be using the KMeans algorithm with 5 clusters.\n\"\"\"\nmodel = MiniBatchKMeans(n_clusters=5, random_state=random_state)\nmodel.fit(X)\n\"\"\"\nWhat are the cluster center vectors?\n\"\"\"\nmodel.cluster_centers_\n# predict cluster labels for new dataset\nmodel.predict(X)\n\n# to get cluster labels for the dataset used while\n# training the model (used for models that does not\n# support prediction on new dataset).\nmodel.labels_\nprint ('Most Common Terms per Cluster:')\n\norder_centroids = model.cluster_centers_.argsort()[:,::-1] #sort cluster centers by proximity to centroid\nterms = vectorizer.get_feature_names()\n\nfor i in range(5):\n    print(\"\\n\")\n    print('Cluster %d:' % i)\n    for j in order_centroids[i, :10]: #replace 10 with n words per cluster\n        print ('%s' % terms[j]),\n    print\n\"\"\"\n## 5.4 Visualization\nTo visualize, we\u2019ll plot the features in a 2D space. As we know the dimension of features that we obtained from TfIdfVectorizer is quite large ( > 10,000), we need to reduce the dimension before we can plot. For this, we\u2019ll ues PCA to transform our high dimensional features into 2 dimensions.\n\"\"\"\n# reduce the features to 2D\npca = PCA(n_components=2, random_state=random_state)\nreduced_features = pca.fit_transform(X.toarray())\n\n# reduce the cluster centers to 2D\nreduced_cluster_centers = pca.transform(model.cluster_centers_)\nplt.scatter(reduced_features[:,0], reduced_features[:,1], c=model.predict(X))\nplt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=150, c='b')\n\"\"\"\n## 5.5 Prediction\n\"\"\"\nprint(\"\\n\")\nprint(\"Prediction\")\n\nY = vectorizer.transform([\"engine failure\"])\nprediction = model.predict(Y)\nprint(prediction)\n\nY = vectorizer.transform([\"terrorism\"])\nprediction = model.predict(Y)\nprint(prediction)\n ","meta":"{'source': 'AI4Code', 'id': 'd8d08472126d77'}"}
{"id":"90579","text":"# 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\n# Importing Liberaries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas import read_csv, set_option\nfrom pandas.plotting import scatter_matrix\n# Loading Data\nfraud_data = pd.read_csv('\/kaggle\/input\/creditcardfraud\/creditcard.csv')\n# Viewing Raw Data\nset_option('display.width', 100)\nfraud_data.head()\n# Dimension of data\nfraud_data.shape\n# Data Type\nfraud_data.info()\n\"\"\"\n> Our observations are as \n\n> NaN values do not present in the data set. Because of the Non-Null Count and number of rows in the dataset match.\n\n> There are 29 Input Variables and 1 Output Variable (Class)\n\n> The data type of all the input variables is float64 whereas the data type of out variable (Class) is int64\n\"\"\"\n# CHecking Null values\nfraud_data.isnull().sum()\n# Summarizing data\nset_option('precision', 5)\nfraud_data.describe()\n\n# Response Variable Analysis\nclass_names = {0:'Not Fraud', 1:'Fraud'}\nrvs = fraud_data.Class.value_counts().rename(index = class_names)\nprint(rvs)\n\"\"\"\n***Splitting data into training and testing data***\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ny= fraud_data[\"Class\"]\nX = fraud_data.loc[:, fraud_data.columns != 'Class']\nX_train,X_test,y_train,y_test = train_test_split(X,y, test_size=1\/6, random_state=42)\n\"\"\"\n# Data Modelling\n\"\"\"\n\"\"\"\n***Logistic Regression***\n\"\"\"\n#Import Library for Accuracy Score\nfrom sklearn.metrics import accuracy_score\n\n#Import Library for Logistic Regression\nfrom sklearn.linear_model import LogisticRegression\n\n#Initialize the Logistic Regression Classifier\nlogisreg = LogisticRegression()\n\n#Train the model using Training Dataset\nlogisreg.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = logisreg.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_logisreg = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of Logistic Regression model : ', acc_logisreg )\n\"\"\"\n***Linear Discriminent Analysis***\n\"\"\"\n#Import Library for Linear Discriminant Analysis\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n\n#Initialize the Linear Discriminant Analysis Classifier\nmodel = LinearDiscriminantAnalysis()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_lda = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of Linear Discriminant Analysis Classifier: ', acc_lda )\n\"\"\"\n***Gaussian Naive Bayes***\n\"\"\"\n#Import Library for Gaussian Naive Bayes\nfrom sklearn.naive_bayes import GaussianNB\n\n#Initialize the Gaussian Naive Bayes Classifier\nmodel = GaussianNB()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_ganb = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of Gaussian Naive Bayes : ', acc_ganb )\n\"\"\"\n***Decision Tree***\n\"\"\"\n#Import Library for Decision Tree Classifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n#Initialize the Decision Tree Classifier\nmodel = DecisionTreeClassifier()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_dtree = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of  Decision Tree Classifier : ', acc_dtree )\n\"\"\"\n***Random Forest***\n\"\"\"\n#Import Library for Random Forest\nfrom sklearn.ensemble import RandomForestClassifier\n\n#Initialize the Random Forest\nmodel = RandomForestClassifier()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_rf = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of  Random Forest : ', acc_rf )\n\"\"\"\n***Support Vector Machine***\n\"\"\"\n#Import Library for Support Vector Machine\nfrom sklearn import svm\n\n#Initialize the Support Vector Classifier\nmodel = svm.SVC()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_svc = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of Support Vector Classifier: ', acc_svc )\n\"\"\"\n***KNN***\n\"\"\"\n#Import Library for K Nearest Neighbour Model\nfrom sklearn.neighbors import KNeighborsClassifier\n\n#Initialize the K Nearest Neighbour Model with Default Value of K=5\nmodel = KNeighborsClassifier()\n\n#Train the model using Training Dataset\nmodel.fit(X_train, y_train)\n\n# Prediction using test data\ny_pred = model.predict(X_test)\n\n# Calculate Model accuracy by comparing y_test and y_pred\nacc_knn = round( accuracy_score(y_test, y_pred) * 100, 2 )\nprint( 'Accuracy of KNN Classifier: ', acc_knn )\n\"\"\"\n# Model Selection\n\"\"\"\nmodels = pd.DataFrame({\n    'Model': ['Logistic Regression', 'Linear Discriminant Analysis','Naive Bayes', 'Decision Tree', 'Random Forest', 'Support Vector Machines', \n              'K - Nearest Neighbors'],\n    'Score': [acc_logisreg, acc_lda, acc_ganb, acc_dtree, acc_rf, acc_svc, acc_knn]})\n\nmodels.sort_values(by='Score', ascending=False)\n\n\"\"\"\n>The Best model for Predicting in **Random Forest Model** with **99.96% Accuracy**\n\"\"\"\n\"\"\"\n# Confusion Matrix\nThis is a binary classification problem (Fraud or No-Fraud). Some of the commonly used terms are:\n* True positives (TP)\n        Predicted positive and are actually positive.\n* False positives (FP)\n        Predicted positive and are actually negative.\n* True negatives (TN)\n        Predicted negative and are actually negative.\n* False negatives (FN)\n        Predicted negative and are actually positive.\n\"\"\"\n\"\"\"\n![image.png](attachment:c4985768-6fd7-4dec-a7ac-0f8dd50b3a88.png)\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\nsns.heatmap(cm, annot = True);\nfrom sklearn.metrics import plot_confusion_matrix\nplot_confusion_matrix(model, X_test, y_test);\n\"\"\"\n* In this case, overall accuracy is strong, but the confusion metrics tell a different story. \n* Despite the high accuracy level, 36 out of 164 instances of fraud are missed and incorrectly predicted as nonfraud. \n* The false-negative rate is substantial. \n* The intention of a fraud detection model is to minimize these false negatives.\n\"\"\"\n\"\"\"\n**Dont Forgot Upvote!!!!!!**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a627d42919f2fe'}"}
{"id":"35646","text":"# 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        \n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\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\n\"\"\"\n# Import library\n\"\"\"\nfrom keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.applications.vgg16 import VGG16\nimport matplotlib.pyplot as plt\nfrom glob import glob\n\ntrain_path = \"..\/input\/fruits\/fruits-360\/Training\/\"\ntest_path = \"..\/input\/fruits\/fruits-360\/Test\/\"\nimg = load_img(train_path + 'Avocado\/0_100.jpg')\nplt.imshow(img)\nplt.show()\nx = img_to_array(img)\nprint(x.shape)\n\nnumberofclass = len(glob(train_path + \"\/*\"))\nprint(numberofclass)\n\"\"\"\n# VGG16\n\"\"\"\nvgg = VGG16()\nprint(vgg.summary())\nvgg_layer_list = vgg.layers\nprint(vgg_layer_list)\n\"\"\"\n# Create Model\n\"\"\"\nmodel = Sequential()\n\nfor i in range(len(vgg_layer_list)-1):\n    model.add(vgg_layer_list[i]) # add vgg_layer_list's models in our model except last model\n    \nprint(model.summary())\n\nfor layers in model.layers: # modellerim train edilmesin zaten train edilmi\u015f weight'lerimi kullanaca\u011f\u0131m\n    layers_trainable = False\n\nmodel.add(Dense(numberofclass, activation = \"softmax\"))  # added last element of our model\nprint(model.summary())\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\"\"\"\n# Image Data Generation\n\"\"\"\nfrom keras.applications.vgg16 import preprocess_input\n\ntrain_data = ImageDataGenerator(rescale=1.\/255,   # all pixel values will be between 0 an 1\n                                shear_range=0.2, \n                                zoom_range=0.2,\n                                horizontal_flip=True,\n                                preprocessing_function=preprocess_input).flow_from_directory(train_path, target_size = (224,224), batch_size = 32, class_mode = 'categorical')\n\ntest_data = ImageDataGenerator(rescale = 1.\/255, preprocessing_function=preprocess_input).flow_from_directory(test_path, target_size = (224,224), batch_size = 32, class_mode = 'categorical')\n\"\"\"\n# Train data\n\"\"\"\nhist = model.fit_generator(train_data,\n                           steps_per_epoch=1,# bu de\u011ferin normalde training_data'n\u0131n say\u0131s\u0131 kadar olmas\u0131 gerekiyor  \u015fimdilik 50 olabilir!!!\n                           epochs = 1, # 50\n                           validation_data = test_data,\n                           validation_steps= 1, # bu de\u011ferin validation datan\u0131n say\u0131s\u0131 kadar olmas\u0131 gerkeiyor \u015fimdilik 25\n                           verbose = 2,\n                           shuffle = True)\n\n\nacc = max(hist.history['accuracy'])\nval_acc = max(hist.history['val_accuracy'])\n\nprint ('Training Accuracy = ' + str(acc) )\nprint ('Validation Accuracy = ' + str(val_acc))\n\"\"\"\n# Visualization\n\"\"\"\nprint(hist.history.keys())\nplt.plot(hist.history[\"loss\"], label = \"training_loss\")\nplt.plot(hist.history[\"val_loss\"], label = \"val_loss\")\nplt.legend()\nplt.show()\nplt.figure()\nplt.plot(hist.history[\"accuracy\"], label = \"training_acc\")\nplt.plot(hist.history[\"val_accuracy\"], label = \"val_acc\")\nplt.legend()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '41af3e0ddd8c03'}"}
{"id":"41856","text":"# 1. Th\u00eam c\u00e1c th\u01b0 vi\u1ec7n c\u1ea7n thi\u1ebft\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\n# from keras.datasets import mnist\n\"\"\"\nLoad d\u1eef li\u1ec7u t\u1eeb MNIST dataset, bao g\u1ed3m 60.000 training set v\u00e0 10.000 test set. Sau \u0111\u00f3 chia b\u1ed9 traning set th\u00e0nh 2: 50.000 cho training set v\u00e0 10.000 d\u1eef li\u1ec7u cho validation set.\n\"\"\"\n# 2. Load d\u1eef li\u1ec7u MNIST\ndef load_data(path):\n    with np.load(path) as f:\n        x_train, y_train = f['x_train'], f['y_train']\n        x_test, y_test = f['x_test'], f['y_test']\n        return (x_train, y_train), (x_test, y_test)\n\n(X_train, y_train), (X_test, y_test) = load_data('..\/input\/mnist.npz')\n\n# (X_train, y_train), (X_test, y_test) = mnist.load_data()\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train \/= 255\nX_test \/= 255\n\nX_val, y_val = X_train[50000:60000,:], y_train[50000:60000]\nX_train, y_train = X_train[:50000,:], y_train[:50000]\nprint(X_train.shape)\n\"\"\"\nD\u1eef li\u1ec7u input cho m\u00f4 h\u00ecnh convolutional neural network l\u00e0 1 tensor 4 chi\u1ec1u (N, W, H, D), trong b\u00e0i n\u00e0y l\u00e0 \u1ea3nh x\u00e1m n\u00ean W = H = 28, D = 1, N l\u00e0 s\u1ed1 l\u01b0\u1ee3ng \u1ea3nh cho m\u1ed7i l\u1ea7n training. Do d\u1eef li\u1ec7u \u1ea3nh \u1edf tr\u00ean c\u00f3 k\u00edch th\u01b0\u1edbc l\u00e0 (N, 28, 28) t\u1ee9c l\u00e0 (N, W, H) n\u00ean r\u1ea7n reshape l\u1ea1i th\u00e0nh k\u00edch th\u01b0\u1edbc N * 28 * 28 * 1 \u0111\u1ec3 gi\u1ed1ng k\u00edch th\u01b0\u1edbc m\u00e0 keras y\u00eau c\u1ea7u.\n\"\"\"\n# 3. Reshape l\u1ea1i d\u1eef li\u1ec7u cho \u0111\u00fang k\u00edch th\u01b0\u1edbc m\u00e0 keras y\u00eau c\u1ea7u\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_val = X_val.reshape(X_val.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\nprint(X_train.shape)\n\"\"\"\nB\u01b0\u1edbc n\u00e0y chuy\u1ec3n \u0111\u1ed5i one-hot encoding label Y c\u1ee7a \u1ea3nh v\u00ed d\u1ee5 s\u1ed1 5 th\u00e0nh vector [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]\n\"\"\"\n# 4. One hot encoding label (Y)\nY_train = np_utils.to_categorical(y_train, 10)\nY_val = np_utils.to_categorical(y_val, 10)\nY_test = np_utils.to_categorical(y_test, 10)\nprint('D\u1eef li\u1ec7u y ban \u0111\u1ea7u ', y_train[0])\nprint('D\u1eef li\u1ec7u y sau one-hot encoding ',Y_train[0])\n\"\"\"\nB\u01b0\u1edbc n\u00e0y \u0111\u1ecbnh ngh\u0129a model:\n1. Model = Sequential() \u0111\u1ec3 n\u00f3i cho keras l\u00e0 ta s\u1ebd x\u1ebfp c\u00e1c layer l\u00ean nhau \u0111\u1ec3 t\u1ea1o model. V\u00ed d\u1ee5 input -> CONV -> POOL -> CONV -> POOL -> FLATTEN -> FC -> OUTPUT\n2.  \u1ede layer \u0111\u1ea7u ti\u00ean c\u1ea7n ch\u1ec9 r\u00f5 input_shape c\u1ee7a \u1ea3nh, input_shape = (W, H, D), ta d\u00f9ng \u1ea3nh x\u00e1m k\u00edch th\u01b0\u1edbc (28,28) n\u00ean input_shape = (28, 28, 1)\n3. Khi th\u00eam Convolutional Layer ta c\u1ea7n ch\u1ec9 r\u00f5 c\u00e1c tham s\u1ed1: K (s\u1ed1 l\u01b0\u1ee3ng layer), kernel size (W, H), h\u00e0m activation s\u1eed d\u1ee5ng. c\u1ea5u tr\u00fac: model.add(Conv2D(K, (W, H), activation='t\u00ean_h\u00e0m_activation'))\n4. Khi th\u00eam Maxpooling Layer c\u1ea7n ch\u1ec9 r\u00f5 size c\u1ee7a kernel, model.add(MaxPooling2D(pool_size=(W, H)))\n5. B\u01b0\u1edbc Flatten chuy\u1ec3n t\u1eeb tensor sang vector ch\u1ec9 c\u1ea7n th\u00eam flatten layer.\n6. \u0110\u1ec3 th\u00eam Fully Connected Layer (FC) c\u1ea7n ch\u1ec9 r\u00f5 s\u1ed1 l\u01b0\u1ee3ng node trong layer v\u00e0 h\u00e0m activation s\u1eed d\u1ee5ng trong layer, c\u1ea5u tr\u00fac: model.add(Dense(s\u1ed1_l\u01b0\u1ee3ng_node activation='t\u00ean_h\u00e0m activation'))\n\n\"\"\"\n# 5. \u0110\u1ecbnh ngh\u0129a model\nmodel = Sequential()\n \n# Th\u00eam Convolutional layer v\u1edbi 32 kernel, k\u00edch th\u01b0\u1edbc kernel 3*3\n# d\u00f9ng h\u00e0m sigmoid l\u00e0m activation v\u00e0 ch\u1ec9 r\u00f5 input_shape cho layer \u0111\u1ea7u ti\u00ean\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28,28,1)))\n\n# Th\u00eam Convolutional layer\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\n\n# Th\u00eam Max pooling layer\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Flatten layer chuy\u1ec3n t\u1eeb tensor sang vector\nmodel.add(Flatten())\n\n# Th\u00eam Fully Connected layer v\u1edbi 128 nodes v\u00e0 d\u00f9ng h\u00e0m sigmoid\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\n\n# Output layer v\u1edbi 10 node v\u00e0 d\u00f9ng softmax function \u0111\u1ec3 chuy\u1ec3n sang x\u00e1c xu\u1ea5t.\nmodel.add(Dense(10, activation='softmax'))\n# 6. Compile model, ch\u1ec9 r\u00f5 h\u00e0m loss_function n\u00e0o \u0111\u01b0\u1ee3c s\u1eed d\u1ee5ng, ph\u01b0\u01a1ng th\u1ee9c \n# \u0111\u00f9ng \u0111\u1ec3 t\u1ed1i \u01b0u h\u00e0m loss function.\nmodel.compile(loss='categorical_crossentropy',\n              optimizer='adadelta',\n              metrics=['accuracy'])\n# 7. Th\u1ef1c hi\u1ec7n train model v\u1edbi data\nnumOfEpoch = 15\nH = model.fit(X_train, Y_train, validation_data=(X_val, Y_val),\n          batch_size=128, epochs=numOfEpoch, verbose=1)\n# 8. V\u1ebd \u0111\u1ed3 th\u1ecb loss, accuracy c\u1ee7a traning set v\u00e0 validation set\nfig = plt.figure()\nplt.plot(np.arange(0, numOfEpoch), H.history['loss'], label='training loss')\nplt.plot(np.arange(0, numOfEpoch), H.history['val_loss'], label='validation loss')\nplt.plot(np.arange(0, numOfEpoch), H.history['acc'], label='accuracy')\nplt.plot(np.arange(0, numOfEpoch), H.history['val_acc'], label='validation accuracy')\nplt.title('Accuracy and Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss|Accuracy')\nplt.legend()\n# 9. \u0110\u00e1nh gi\u00e1 model v\u1edbi d\u1eef li\u1ec7u test set\nscore = model.evaluate(X_test, Y_test, verbose=0)\nprint(score)\n\"\"\"\nTa s\u1ebd d\u00f9ng k\u1ebft qu\u1ea3 \u0111\u00e1nh gi\u00e1 c\u1ee7a mode v\u1edbi test set \u0111\u1ec3 l\u00e0m k\u1ebft qu\u1ea3 cu\u1ed1i c\u00f9ng c\u1ee7a model. T\u1ee9c model c\u1ee7a ch\u00fang ta d\u1eef \u0111o\u00e1n ch\u1eef s\u1ed1 c\u00f3 \u0111\u1ed9 ch\u00ednh x\u00e1c 98.92% v\u1edbi MNIST dataset. Ngh\u0129a l\u00e0 d\u1ef1 \u0111o\u00e1n kho\u1ea3ng 100 \u1ea3nh th\u00ec sai 1 \u1ea3nh.\n\"\"\"\n# 10. D\u1ef1 \u0111o\u00e1n \u1ea3nh\nindex_test = 321\nplt.imshow(X_test[index_test].reshape(28,28), cmap='gray')\n\ny_predict = model.predict(X_test[index_test].reshape(1,28,28,1))\nprint('Gi\u00e1 tr\u1ecb d\u1ef1 \u0111o\u00e1n: ', np.argmax(y_predict))\noutput = model.predict(X_test)\nY = []\nfor i in range(output.shape[0]):\n    if np.argmax(output[i]) != np.argmax(Y_test[i]): Y.append(i)\n\nprint(Y)\nNumIm = 20\nfig = plt.figure(figsize=(15, 30))\ncolumns = 5\nrows = 10\n\nfor index in range(0, NumIm):\n    fig.add_subplot(rows, columns, index + 1)\n    \n    index_test = Y[index]\n    plt.imshow(X_test[index_test].reshape(28,28), cmap='gray')\n    y_predict = model.predict(X_test[index_test].reshape(1,28,28,1))\n    print(index + 1, ': h\u00ecnh \u1ea3nh th\u1ee9 ', index_test, ' c\u00f3 gi\u00e1 tr\u1ecb d\u1ef1 \u0111o\u00e1n v\u00e0 th\u1ef1c t\u1ebf: ', np.argmax(y_predict), ' v\u00e0 ', np.argmax(Y_test[index_test]))\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': '4d1f564faa7668'}"}
{"id":"96648","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.data import Dataset\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Flatten, MaxPool2D, Dense\nfrom tensorflow.keras.activations import relu\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy, CategoricalCrossentropy\nfrom tensorflow.keras.metrics import Accuracy, sparse_categorical_accuracy, SparseCategoricalAccuracy, CategoricalAccuracy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\"\"\"\n## networks\n\"\"\"\ndef get_shallow_cnn():\n  model = Sequential()\n  model.add(Conv2D(16, 3, activation=relu, input_shape=(28, 28, 1)))\n  model.add(MaxPool2D())\n  model.add(Conv2D(32, 3, activation=relu))\n  model.add(MaxPool2D())\n  model.add(Flatten())\n  model.add(Dense(128, activation=relu))\n  model.add(Dense(10))\n  return model\n\"\"\"\n## mnist\n\"\"\"\n\"\"\"\n### Dataset\n\nIn this section we will use the tensorflow Dataset object to create a generator for train, test, valid data and use it it to train the network.\n\"\"\"\n(x_data, y_data), (x_test, y_test) = mnist.load_data()\nx_data = x_data[..., np.newaxis]\nx_test = x_test[..., np.newaxis]\nx_data.shape, y_data.shape, x_test.shape, y_test.shape\n(x_train, x_valid, y_train, y_valid) = train_test_split(\n    x_data, y_data, test_size=0.15, random_state=42)\nprint(x_train.shape, y_train.shape)\nprint(x_valid.shape, y_valid.shape)\nprint(x_test.shape, y_test.shape)\ntrain_dataset = Dataset.from_tensor_slices((x_train, y_train))\nvalid_dataset = Dataset.from_tensor_slices((x_valid, y_valid))\ntest_dataset = Dataset.from_tensor_slices((x_test, y_test))\ntrain_dataset = train_dataset.batch(64, True)\nvalid_dataset = valid_dataset.batch(64, True)\ntest_dataset = test_dataset.batch(64, True)\nsteps_per_epoch = x_train.shape[0]\/\/64\nvalidation_steps = x_valid.shape[0]\/\/64\n\"\"\"\n#### using model compiled with 'accuracy':\n\"\"\"\nmodel1 = get_shallow_cnn()\n\nmodel1.compile(optimizer=Adam(),\n              loss=SparseCategoricalCrossentropy(True),\n              metrics=['accuracy'])\n\nhistory1 = model1.fit(train_dataset, steps_per_epoch=steps_per_epoch,\n              validation_data=valid_dataset,\n              epochs=10, validation_steps=validation_steps)\n\"\"\"\n#### using model compiled with 'sparse categorical accuracy':\n\"\"\"\nmodel2 = get_shallow_cnn()\n\nmodel2.compile(optimizer=Adam(),\n              loss=SparseCategoricalCrossentropy(True),\n              metrics=[SparseCategoricalAccuracy()])\n\nhistory2 = model2.fit(\n    train_dataset, steps_per_epoch=steps_per_epoch,\n    validation_data=valid_dataset,\n    epochs=10, validation_steps=validation_steps)\n\"\"\"\n#### using model compiled with 'Accuracy':\n\"\"\"\n\"\"\"\n\n\n```\nmodel3 = get_shallow_cnn()\n\nmodel3.compile(optimizer=Adam(),\n              loss=SparseCategoricalCrossentropy(True),\n              metrics=[Accuracy()])\n\nhistory3 = model3.fit(\n    train_dataset, steps_per_epoch=steps_per_epoch,\n    validation_data=valid_dataset,\n    epochs=10, validation_steps=validation_steps)\n\n# Results in an error:\n    ValueError: Shapes (64, 10) and (64, 1) are incompatible\n\n```\n\n\n\"\"\"\ny_train = to_categorical(y_train)\ny_valid = to_categorical(y_valid)\ny_test = to_categorical(y_test)\nprint(y_train.shape, y_valid.shape, y_test.shape)\ntrain_dataset3 = Dataset.from_tensor_slices((x_train, y_train))\nvalid_dataset3 = Dataset.from_tensor_slices((x_valid, y_valid))\ntest_dataset3 = Dataset.from_tensor_slices((x_test, y_test))\ntrain_dataset3.element_spec\ntrain_dataset3 = train_dataset3.batch(64, True)\nvalid_dataset3 = valid_dataset3.batch(64, True)\ntest_dataset3 = test_dataset3.batch(64, True)\ntrain_dataset3.element_spec\nmodel3 = get_shallow_cnn()\n\nmodel3.compile(optimizer=Adam(),\n              loss=CategoricalCrossentropy(True),\n              metrics=[CategoricalAccuracy()])\n\nhistory3 = model3.fit(\n    train_dataset3, steps_per_epoch=steps_per_epoch,\n    validation_data=valid_dataset3,\n    epochs=10, validation_steps=validation_steps)\nhistory2.history.keys()\nplt.style.use('ggplot')\nfig, axes = plt.subplots(1, 2, sharex=True, figsize=(12, 5))\n\naxes[0].set_xlabel(\"Epochs\", fontsize=14)\naxes[0].set_ylabel(\"Loss\", fontsize=14)\naxes[0].set_title('Loss vs epochs')\naxes[0].plot(history1.history[\"loss\"])\naxes[0].plot(history2.history[\"loss\"])\naxes[0].plot(history3.history[\"loss\"])\n\naxes[1].set_title('Accuracy vs epochs')\naxes[1].set_ylabel(\"Accuracy\", fontsize=14)\naxes[1].set_xlabel(\"Epochs\", fontsize=14)\naxes[1].plot(history1.history[\"accuracy\"])\naxes[1].plot(history2.history[\"sparse_categorical_accuracy\"])\naxes[1].plot(history3.history[\"categorical_accuracy\"])\n\nplt.show()\n\"\"\"\nWhy are they exactly not the same??\n\nFrom which places did the randomness creep in.\n\"\"\"\n\"\"\"\n### ImageDataGenerator\n\ntf.keras image data generator object is specifically designed for images\n\"\"\"\n(x_data, y_data), (x_test, y_test) = mnist.load_data()\nx_data = x_data[..., np.newaxis]\nx_test = x_test[..., np.newaxis]\nx_data.shape, y_data.shape, x_test.shape, y_test.shape\n(x_train, x_valid, y_train, y_valid) = train_test_split(\n    x_data, y_data, test_size=0.15, random_state=42)\nimg_generator = ImageDataGenerator(rescale=1\/255.0)\ntrain_dataset = img_generator.flow(x_train, y_train, batch_size=64)\nvalid_dataset = img_generator.flow(x_valid, y_valid, batch_size=64)\ntest_dataset = img_generator.flow(x_test, y_test, batch_size=64)\nmodel5 = get_shallow_cnn()\n\nmodel5.compile(optimizer=Adam(),\n              loss=SparseCategoricalCrossentropy(True),\n              metrics=['accuracy'])\n\nhistory5 = model5.fit(train_dataset, steps_per_epoch=steps_per_epoch,\n              validation_data=valid_dataset,\n              epochs=10, validation_steps=validation_steps)\nplt.style.use('ggplot')\nfig, axes = plt.subplots(1, 2, sharex=True, figsize=(12, 5))\n\naxes[0].set_xlabel(\"Epochs\", fontsize=14)\naxes[0].set_ylabel(\"Loss\", fontsize=14)\naxes[0].set_title('Loss vs epochs')\naxes[0].plot(history5.history[\"loss\"])\n\naxes[1].set_title('Accuracy vs epochs')\naxes[1].set_ylabel(\"Accuracy\", fontsize=14)\naxes[1].set_xlabel(\"Epochs\", fontsize=14)\naxes[1].plot(history5.history[\"accuracy\"])\n\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'b18b63e1bb0114'}"}
{"id":"63061","text":"\"\"\"\n# K Nearest Neighbors with Python\n\nWe'll try to use KNN to create a model that directly predicts a class for a new data point based off of the features.\n\n\nIn wikipedia description:\n\nIn pattern recognition, the k-nearest neighbors algorithm (k-NN) is a non-parametric method used for classification and regression. In both cases, the input consists of the k closest training examples in the feature space. The output depends on whether k-NN is used for classification or regression:\n\nIn k-NN classification, the output is a class membership. An object is classified by a plurality vote of its neighbors, with the object being assigned to the class most common among its k nearest neighbors (k is a positive integer, typically small). If k = 1, then the object is simply assigned to the class of that single nearest neighbor.\nIn k-NN regression, the output is the property value for the object. This value is the average of the values of k nearest neighbors.\nk-NN is a type of instance-based learning, or lazy learning, where the function is only approximated locally and all computation is deferred until classification. The k-NN algorithm is among the simplest of all machine learning algorithms.\n\nBoth for classification and regression, a useful technique can be used to assign weight to the contributions of the neighbors, so that the nearer neighbors contribute more to the average than the more distant ones. For example, a common weighting scheme consists in giving each neighbor a weight of 1\/d, where d is the distance to the neighbor.\n\nThe neighbors are taken from a set of objects for which the class (for k-NN classification) or the object property value (for k-NN regression) is known. This can be thought of as the training set for the algorithm, though no explicit training step is required.\n\n\nLet's grab it and use it!\n\"\"\"\n\"\"\"\n### Let's import libraries\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\ndf = pd.read_csv(\"..\/input\/breastCancer.csv\")\ndf.head()\ndf.info()\ndf.drop(columns=['Unnamed: 32'],inplace=True)\ndf.drop(columns=['id'],inplace=True)\nset(df['diagnosis'])\ndf['diagnosis'] =[ 1 if i =='M' else 0 for i in df['diagnosis']]\n\"\"\"\n# Data Visualization\n\"\"\"\nplt.figure(figsize=(12,5))\nsns.countplot(x= 'diagnosis', data=df)\ndf.plot(figsize=(18,8))\nplt.figure(figsize=(12,7))\ndf['smoothness_mean'].hist(bins=30,color='darkred',alpha=0.7)\ndf['perimeter_worst'].hist(color='blue',bins=40,figsize=(8,4))\n\n\"\"\"\nWe can figure it out better using data visualization.\n\"\"\"\n\"\"\"\n## Standardize the Variables\n\nThe KNN classifier predicts the class of a given test observation by identifying the observations that are nearest to it, the scale of the variables matters. Any variables that are on a large scale will have a much larger effect on the distance between the observations, and hence on the KNN classifier, than variables that are on a small scale.\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(df.drop('diagnosis',axis=1))\nscaled_features = scaler.transform(df.drop('diagnosis',axis=1))\ndf.columns\ndf_feat = pd.DataFrame(scaled_features,columns=df.columns[1:])\ndf_feat.head()\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(scaled_features,df['diagnosis'],test_size=0.20,random_state=101)\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=1)\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\npred\ndf['diagnosis'].head(5)\nfrom sklearn.metrics import classification_report,confusion_matrix\nprint(confusion_matrix(y_test,pred))\nprint(classification_report(y_test,pred))\n\"\"\"\n## Choosing a K Value\n\nLet's go ahead and use the elbow method to pick a good K Value:\n\"\"\"\nerror_rate = []\n\n# Will take some time\nfor i in range(1,40):\n    \n    knn = KNeighborsClassifier(n_neighbors=i)\n    knn.fit(X_train,y_train)\n    pred_i = knn.predict(X_test)\n    error_rate.append(np.mean(pred_i != y_test))\nplt.figure(figsize=(10,6))\nplt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', marker='o',\n         markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')\n\"\"\"\nHere we can see that that after arouns K>11 the error rate just tends to hover around 0.03-0.02 Let's retrain the model with that and check the classification report!\n\"\"\"\n# FIRST A QUICK COMPARISON TO OUR ORIGINAL K=1\nknn = KNeighborsClassifier(n_neighbors=1)\n\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\n\nprint('WITH K=1')\nprint('\\n')\nprint(confusion_matrix(y_test,pred))\nprint('\\n')\nprint(classification_report(y_test,pred))\n# NOW WITH K=11\nknn = KNeighborsClassifier(n_neighbors=11)\n\nknn.fit(X_train,y_train)\npred = knn.predict(X_test)\n\nprint('WITH K=11')\nprint('\\n')\nprint(confusion_matrix(y_test,pred))\nprint('\\n')\nprint(classification_report(y_test,pred))\n\"\"\"\nAs we can see, when we use K=11 the result is better.\n\nSo if it is usefull kernel for you, please vote it :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '744237dcf2171e'}"}
{"id":"138378","text":"# Setup\nimport os\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport cufflinks as cf\ninit_notebook_mode(connected=True)\ncf.go_offline()\n%matplotlib inline\n# Data file\npath = '..\/input\/market-price-of-onion-2020\/Onion Prices 2020.csv'\n\n# Reading data\nData = pd.read_csv(path)\nData.head()\n# Extracting Date & Month from arrival_date\nData['Month'] = Data['arrival_date'].apply(lambda x :x.split('\/')[1])\nData['Date'] = Data['arrival_date'].apply(lambda x :x.split('\/')[0])\nData.head()\n\"\"\"\nBefore we go indepth, \n- lets check for row & column count & also null values.\n- also number of 'States, Districts, Markets, Commodity & Variety' mentioned in data.\n\"\"\"\n# So let's determine the shape of our data.\n# Will also check for null values\n\nprint('Data Info :\\n\\tRow Count - {r:}\\n\\tColumn Count - {c:}\\n\\tNull Values - {n:}'.format(r=Data.shape[0],\n                                            c=Data.shape[1], n=Data.isna().sum().sum()))\n\n# Lets check for number of unique values for all categorical columns.\nprint('\\nValue Count :')\nfor category in ['state', 'district', 'market', 'commodity', 'variety']:\n    print(\"\\t'{c:}s' mentioned : {n:}\".format(c=category.title(), n=Data[category].nunique()))\n\"\"\"\n# ***Min, Max, Model Prices*** \n- We will have some look at **distribution plots** for onion prices.\n- **Conclusion :**\n    - a. There was a situation when ***onion price was Zero. Yes 0.*** And rised ***upto 18000 \u20b9\/Quintal minimum price.*** This would be due to ***'demand supply gap'*** We will explore this section further considering arrival dates into account. \n    - b. The prices are quite ***stable around 2000\u20b9\/Quintal*** i.e most of the time the market price was 2000\u20b9. We will also see this timezone. \n    - c. All three prices category will be highly correlated with each other which is quite obvious. \n\"\"\"\n# Min, Max & Modal Price Distribution\nplt.figure(figsize=(12, 5))\nsns.set_style('darkgrid')\nsns.distplot(a=Data['min_price'], bins=80, color='green', hist=False, label='Minimum Price')\nsns.distplot(a=Data['max_price'], bins=80, color='red', hist=False, label='Maximum Price')\nsns.distplot(a=Data['modal_price'], bins=80, color='orange', hist=False, label='Modal Price')\nplt.title('Various Price Distributions')\nplt.xlabel('Price')\nsns.despine()\n# As we saw that onion prices were zero. let's explore more into it\nprint('Zero \u20b9 Onion Prices :\\n\\tState Count : {c:}\\n\\tState List : {s:}\\n\\tVariety List : {v:}\\n'.format(c=Data[Data['min_price']==0]['state'].nunique(),\n                                                                            s=list(Data[Data['min_price']==0]['state'].unique()),\n                                                                            v=list(Data[Data['min_price']==0]['variety'].unique())))\n\n\n# Also consider onion price to be 18000\u20b9\/Quintal. \nprint('18000\u20b9\/Q Onion Price :\\n\\tState Count : {c:}\\n\\tState List : {s:}\\n\\tVariety List : {v:}'.format(c=Data[Data['min_price']==18000]['state'].nunique(),\n                                                                            s=list(Data[Data['min_price']==18000]['state'].unique()),\n                                                                            v=list(Data[Data['min_price']==18000]['variety'].unique())))\n\"\"\"\n# ***States, Month & Prices***\n- We will be analysing ***Onion Prices Situation*** for every month in **each State Seperately**\n\n\n- **Conclusion :**\n    - a. The Onion prices were **extremely high in January 2020** for every state. Highest Recorded Prices were in **Kerala & Nagaland** with **+7000 \u20b9\/Quintal**. The **main reason** for rise in price was **damage to the onion crop due to rains.**\n    - b. Then came the saviour **Rabi Season Onion crops (70% of total crops produced in a year) in month of March** in markets all over India and thus prices started to fall back to normal and were **lowest in month of May & June** for almost every State.\n    - c. Finally came ***Monsoon***. *Monsoon Rain damaged* the stored **Rabi crops** that support market demand till August-October & also **Early Kharif crops (20% of total crops produced in a year)** in farms in most of the Indian States causing a **huge Demand-Supply Gap** in every market and thus the prices have again started to rise.\n    - d. ***Most Important Conclusion*** : The **Major onion producing States** like Maharashtra, Madhya Pradesh, Karnataka, Gujarat, Rajasthan & few others will **always suffer less** than other **States where onion is not suitable** to grow for many reasons like Nagaland, Kerala, Tripura, Himachal Pradesh, Odisha & few more **when Onion production decreases.** \n       \n    \n- **Source** :\n    - 01. https:\/\/theprint.in\/india\/onion-prices-surge-to-rs-165-per-kg-govt-promises-imports-by-january-2020\/331628\/#:~:text=The%20main%20reason%20for%20rise,Maharasthra%2C%20the%20key%20growing%20state.&text=To%20boost%20supply%20and%20contain%20price%20rise%2C%20the%20government%20has,expected%20to%20arrive%20mid%2DJanuary.\n    - 02. https:\/\/theprint.in\/opinion\/how-india-can-ensure-onions-are-all-through-year-at-good-price\/334477\/#:~:text=There%20are%20three%20sowing%20seasons,harvested%20in%20March%2DMay).\n    - 03. https:\/\/theprint.in\/india\/onion-prices-could-touch-rs-100-kg-by-oct-as-heavy-rain-damaged-early-kharif-crop-rabi-stock\/499990\/#:~:text=New%20crop%20expected%20in%20November&text=Singh%20said%20retail%20prices%20may,to%20arrive%20only%20in%20November%E2%80%9D.&text=The%20rise%20in%20prices%20is,the%20major%20onion%20producing%20regions.\n\"\"\"\n# Bar Plot\n# X-axis : Months\n# Y-axis : Price\n\nfig, axes = plt.subplots(nrows=11, ncols=2, figsize=(20, 60), sharey=True)\nfig.suptitle(\"Average Onion Price in States for each month of Year 2020\", fontsize=24)\nsns.set_style(\"darkgrid\")\n\nstates_list = Data['state'].unique()     # List of all States\nrows = [x for x in range(0, 11)]\ncols = [0]\ncount = 1\n\nfor state in states_list:\n    # bar plot\n    state_fig = Data.groupby(['state', 'Month']).mean().xs(state).plot(kind='bar',ax=axes[rows[0], cols[0]])\n    state_fig.set_title(state, fontdict={'fontsize': 20, 'color' : 'red'})\n    state_fig.set_xticklabels(labels=state_fig.get_xticklabels(), rotation=360)\n    \n    # column switch\n    if cols[0] == 0:\n        cols[0] = 1\n    else :\n        cols[0] = 0\n        \n    # rows switch\n    count += 1\n    if count > 2:\n        rows.pop(0)\n        count = 1\n    \n    fig.tight_layout()\n    fig.subplots_adjust(top=0.96)\n\"\"\"\n# ***States, Arrival Dates & Prices***\n- We will be analysing ***Onion Prices Situation*** on their **Arrival in Market** in **each State Seperately**\n\n\n- **Conclusion :**\n    - a. **14 States out of 22** have seen huge **downfall in Minimum prices** for multiple times. This list includes **'Andhra Pradesh', 'Gujarat', 'Haryana', 'Karnataka', 'Kerala', 'Madhya Pradesh', 'Maharashtra', 'NCT of Delhi', 'Odisha','Punjab', 'Rajasthan', 'Telangana', 'Uttar Pradesh' & 'Uttrakhand'**. Minimum prices were as **low as 500\u20b9\/Quintal to Zero**.\n    - b. **Note** that in case of **Nagaland**, the data has constant values for Jan. & Feb. that's the reason for a straight hoizontal line. \n\"\"\"\n# Line Plot\n# X-axis : Arrival Dates\n# Y-axis : Price\n\nfig, axes = plt.subplots(nrows=22, ncols=1, figsize=(20, 100))\nfig.suptitle(\"Average Onion Price in States on Arrival in Year 2020\", fontsize=24)\nsns.set_style(\"darkgrid\")\n\nstates_list = Data['state'].unique()     # List of all States\nrows = [x for x in range(0, 22)]\ncount = 1\n                                                \nfor state in states_list:\n    # bar plot\n    state_fig = Data.sort_values(by=['Month', 'Date']).groupby(['state','arrival_date'], sort=False).mean().xs(state).reset_index().plot(kind='line',\n                                                                        ax=axes[rows[0]], x='arrival_date', marker='o', markersize=3, markerfacecolor='black')\n    state_fig.set_title(state, fontdict={'fontsize': 20, 'color' : 'red'})\n    state_fig.set_xticklabels(labels=state_fig.get_xticklabels(), rotation=360)\n    \n    # rows switch\n    rows.pop(0)\n    \n    fig.tight_layout()\n    fig.subplots_adjust(top=0.96)\n# States with Minimum Prices less than or equal to 500\u20b9\/Quintal\nstates = Data[Data['min_price'] <= 500]['state'].unique()\nprint('States with min. price <= 500\u20b9')\nfor state in states:\n    print('\\t{s:}.'.format(s=state.title()))\n#Data[(Data['min_price'] <= 500) & (Data['state']=='Andhra Pradesh')]['Month'].unique()\n\"\"\"\n# Variety, Prices & States\n- We will be relation between **variety & prices** using **box plot**\n- Also relation between **variety & states** using **count plot**\n\n\n\n- **Conclusion :**\n    - a. **Small Onions** were highly **expensive variety** of onions. Their Average price is almost **5000\u20b9\/Quintal** & arrived most in **Kerala Markets**.\n    - b. Onion Varities like **'Local, Other, Onion, Nashik, White, 1st Sort, Pusa-Red, Bombay UP'** are most preferred varities in many states.\n    - c. where as, varities like **'Puna, Telagi, Big, 2nd Sort, Pole, Dry FAQ, Medium'** are preferred in just one state or more\n\"\"\"\n# Box Plot : Variety of Onions wrt Prices\n# Count Plot : Variety of Onions wrt State\n\n\nfig, axes = plt.subplots(nrows=21, ncols=2, figsize=(20, 100))\nfig.suptitle(\"Variety of Onions & relation wrt Prices & State\", fontsize=24)\nsns.set_style(\"darkgrid\")\n\nvariety_list = Data['variety'].unique()   # List of all onion variety\nrows = [x for x in range(0, 21)]\ncols = [0]\n                                                \nfor variety in variety_list: \n    # box plot\n    box_plot = sns.boxplot(data=Data[Data['variety']==variety][['min_price', 'max_price', 'modal_price']], ax=axes[rows[0], cols[0]])\n    box_plot.set_title(variety, fontdict={'fontsize': 20, 'color' : 'red'})\n    box_plot.set_xticklabels(labels=box_plot.get_xticklabels(), rotation=360)\n    \n    # cols switch for count plot\n    cols[0] = 1\n    \n    # count plot\n    count_plot = sns.countplot(Data[Data['variety']==variety]['state'], ax=axes[rows[0], cols[0]])\n    count_plot.set_title(variety, fontdict={'fontsize': 20, 'color' : 'red'})\n    count_plot.set_xticklabels(labels=count_plot.get_xticklabels(), rotation=25, fontdict={'fontsize': 8})\n    \n    # rows & cols switch for box plot\n    rows.pop(0)\n    cols[0] = 0\n    \n    fig.tight_layout()\n    fig.subplots_adjust(top=0.96)\n\"\"\"\n# Percentage Change in Avg. Onion Prices considering Arrival Dates\n\"\"\"\n# Percentage change in prices between arrival days\n\nfig, axes = plt.subplots(nrows=22, ncols=1, figsize=(20, 100))\nfig.suptitle(\"Percentage Change in Average Onion Price in States considering Arrivals in Year 2020\", fontsize=24)\nsns.set_style(\"darkgrid\")\n\nstates_list = Data['state'].unique()     # List of all States\nrows = [x for x in range(0, 22)]\ncount = 1\n                                                \nfor state in states_list:\n    # bar plot\n    state_fig = Data.sort_values(by=['Month', 'Date']).groupby(['state','arrival_date'], sort=False).mean().xs(state).pct_change().reset_index().plot(kind='line',\n                                                                        ax=axes[rows[0]], x='arrival_date', marker='o', markersize=3, markerfacecolor='black')\n    state_fig.set_title(state, fontdict={'fontsize': 20, 'color' : 'red'})\n    state_fig.set_xticklabels(labels=state_fig.get_xticklabels(), rotation=360)\n    \n    # rows switch\n    rows.pop(0)\n    \n    fig.tight_layout()\n    fig.subplots_adjust(top=0.96)\n\n\n\"\"\"\n- If you found this notebook to be helpful, a **like** would be appreciated.\n- **Thank You :)**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'fe6bbe7097c6ac'}"}
{"id":"104217","text":"\"\"\"\n# Objective\n\"\"\"\n\"\"\"\nThe objective is to analyze the daily count of vaccinations in the top 5 countries in terms of the total vaccinations.\n\"\"\"\n# 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\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nstyle.use('dark_background')\n\nfont = {'family' : 'sans-serif',\n        'weight' : 'bold',\n        'size'   : 20}\n\nplt.rc('font', **font)\nplt.rc('xtick', labelsize=20) \nplt.rc('ytick', labelsize=20) \ndf = pd.read_csv('\/kaggle\/input\/covid-world-vaccination-progress\/country_vaccinations.csv', parse_dates = [2])\ndf.head()\ndf.shape\n\"\"\"\nThe following cell demonstrates the top 5 countries (in decreasing order) in terms of the total number of vaccinations till date.\n\"\"\"\ndf.groupby('country')['total_vaccinations'].agg(max).nlargest(5)\nsome_values = ['United States', 'China','United Kingdom', 'England', 'India']\n\nvaccines = df.loc[df['country'].isin(some_values)]\nvaccines.fillna(0.0, inplace = True)\nvaccines.isna().sum()\n\"\"\"\nDeclaring functions to group the data by country and day.\n\"\"\"\ndef GroupByCountryAndDay(df):\n    groups = df.groupby('country')\n    dailies = {}\n    for name, group in groups:\n        dailies[name] = GroupByDay(group)\n        \n    return dailies\n\ndef GroupByDay(df, func = np.mean):\n    grouped = df[['date', 'daily_vaccinations']].groupby('date')\n    daily = grouped.aggregate(func)\n    daily['date'] = daily.index\n    start = daily.date[0]\n    one_year = np.timedelta64(1, 'Y')\n    daily['years'] = (daily.date - start) \/ one_year\n    return daily\ndailies = GroupByCountryAndDay(vaccines)\ndailies.keys()\n\"\"\"\nThe keys of the dictionary (dailies) is not in the order that we want that to be. Therefore, we create another dictionary in that specific order (the order demonstrated in 'some_values'). \n\"\"\"\nreordered_dailies = {country: dailies[country] for country in some_values}\nreordered_dailies\n\"\"\"\n# Visualization\n\"\"\"\nindex = []\nnames = []\nvacc = []\n\nfor i, (name, daily) in enumerate(reordered_dailies.items()):\n    index.append(daily.index)\n    names.append(name)\n    vacc.append(daily.daily_vaccinations \/ 1000)\nnames\nfig, axs = plt.subplots(5, figsize=(15,20))\nfig.suptitle('Daily Vaccinations', fontsize = (20))\nfig.autofmt_xdate(rotation = 30)\n\nfor i, (name, daily) in enumerate(reordered_dailies.items()):\n    axs[i].scatter(index[i], vacc[i], color = 'red')\n    axs[i].set_title(name)\n    plt.tight_layout()","meta":"{'source': 'AI4Code', 'id': 'bf7350a6f98db1'}"}
{"id":"61837","text":"# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\n\"\"\"\n# 1. Data Cleaning\n\"\"\"\ntrain_data = pd.read_csv(\"\/kaggle\/input\/titanic\/train.csv\")\ntest_data = pd.read_csv(\"\/kaggle\/input\/titanic\/test.csv\")\n\nprint(train_data.head())\nlength = train_data.shape[0]\nprint(train_data.isnull().sum())\nprint(\"Percentage of data missing in Age: {}\".format((train_data[\"Age\"].isnull().sum()\/length)*100))\nprint(\"Percentage of data missing in Cabin: {}\".format((train_data[\"Cabin\"].isnull().sum()\/length)*100))\n# Since more than 77% of data is missing Cabin is droped\n\ntrain_data.drop(\"Cabin\",axis = 1,inplace = True)\nprint(train_data.isnull().sum())\n# Since only 2 values of Embarked is missing it is filled with the maximum occuring value.\n\nprint(train_data[\"Embarked\"].value_counts())\ntrain_data[\"Embarked\"].fillna(\"S\",inplace = True)\nprint(train_data.isnull().sum())\n# Seeing the Distribution of Age\n\nsns.histplot(x = train_data[\"Age\"],bins = 10)\n\"\"\"\n*We can impute age based on the Title of the Name to get better results*\n\"\"\"\ntrain_data[train_data[\"Age\"].isna()]\nsplit_name = train_data[\"Name\"].str.split(\", \",expand = True)\ntrain_data[\"Title\"] = split_name[1].str.split(\".\",expand = True)[0]\ntrain_data[\"Title\"].value_counts()\ntrain_data.groupby([\"Title\"])[\"Age\"].describe()\ntrain_data[train_data[\"Age\"].isna()][\"Title\"].value_counts()\n\"\"\"\nThe above Title has missing Age values.\nSo for each title the age is imputed with its mean\n\"\"\"\ntrain_data.loc[(train_data[\"Age\"].isna()) & (train_data[\"Title\"] == \"Mr\"),\"Age\"]= train_data[train_data[\"Title\"] == \"Mr\"][\"Age\"].mean(skipna = True)\ntrain_data.loc[(train_data[\"Age\"].isna()) & (train_data[\"Title\"] == \"Miss\"),\"Age\"]= train_data[train_data[\"Title\"] == \"Miss\"][\"Age\"].mean(skipna = True)\ntrain_data.loc[(train_data[\"Age\"].isna()) & (train_data[\"Title\"] == \"Mrs\"),\"Age\"]= train_data[train_data[\"Title\"] == \"Mrs\"][\"Age\"].mean(skipna = True)\ntrain_data.loc[(train_data[\"Age\"].isna()) & (train_data[\"Title\"] == \"Master\"),\"Age\"]= train_data[train_data[\"Title\"] == \"Master\"][\"Age\"].mean(skipna = True)\ntrain_data.loc[(train_data[\"Age\"].isna()) & (train_data[\"Title\"] == \"Dr\"),\"Age\"]= train_data[train_data[\"Title\"] == \"Dr\"][\"Age\"].mean(skipna = True)\nprint(train_data.isnull().sum())\n# Dropping Columns that are not needed for model building\n\ntrain_data.drop([\"PassengerId\",\"Name\",\"Ticket\",\"Title\"],axis = 1,inplace = True)\ntrain_data.info()\nprint(train_data[\"Sex\"].unique())\nprint(train_data[\"Embarked\"].unique())\n# Encoding Sex and Embarked values\n\ntrain_data[\"Sex\"].replace({\"male\":0,\"female\":1},inplace = True)\ntrain_data[\"Embarked\"].replace({\"S\":0,\"C\":1,\"Q\":2},inplace = True)\ntrain_data.info()\n\"\"\"\n# 2. Data Analysis\n\"\"\"\nsns.heatmap(train_data.corr(),annot = True)\nsns.countplot(x = \"Survived\",hue = \"Sex\",data = train_data)\nsns.countplot(x = \"Survived\",hue = \"Pclass\",data = train_data)\nsns.countplot(x = \"Sex\",hue = \"Pclass\",data = train_data)\nsns.countplot(x = \"SibSp\",hue = \"Survived\",data = train_data)\nsns.countplot(x = \"Parch\",hue = \"Survived\",data = train_data)\nsns.scatterplot(x = \"Age\",y = \"Fare\",hue = \"Survived\",data = train_data)\n\"\"\"\nWe are dropping SibSp and Parch since it has less impact on the Target column.\n\"\"\"\nX = train_data.drop([\"Survived\",\"SibSp\",\"Parch\"],axis = 1)\ny = train_data[\"Survived\"]\n# We shall use RandomForestClassifier\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.metrics import accuracy_score,confusion_matrix\nfrom sklearn.ensemble import RandomForestClassifier\n# Scaling Fare Column.\n\nscaler = MinMaxScaler()\nX[[\"Fare\"]] = scaler.fit_transform(X[[\"Fare\"]])\nX.head()\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3)\nmodel = RandomForestClassifier()\nmodel.fit(X_train,y_train)\nscore = cross_val_score(model,X_train,y_train,cv = 10)\nprint(\"Cross Validation Score : {}\".format(np.mean(score) * 100))\ny_pred = model.predict(X_test)\nprint(\"Model Accuracy: {}\".format(accuracy_score(y_pred,y_test)))\nprint(confusion_matrix(y_test,y_pred))\n\"\"\"\n# 3. Cleaning Test data and Predicting Value\n\"\"\"\nprint(test_data.isnull().sum())\nprint(test_data.shape)\ntest_data.drop([\"Cabin\"],axis = 1,inplace = True)\nsplit_name = test_data[\"Name\"].str.split(\", \",expand = True)\ntest_data[\"Title\"] = split_name[1].str.split(\".\",expand = True)[0]\ntest_data[\"Title\"].value_counts()\ntest_data.groupby([\"Title\"])[\"Age\"].describe()\ntest_data[test_data[\"Age\"].isna()][\"Title\"].value_counts()\ntest_data.loc[(test_data[\"Age\"].isna()) & (test_data[\"Title\"] == \"Mr\"),\"Age\"]= test_data[test_data[\"Title\"] == \"Mr\"][\"Age\"].mean(skipna = True)\ntest_data.loc[(test_data[\"Age\"].isna()) & (test_data[\"Title\"] == \"Miss\"),\"Age\"]= test_data[test_data[\"Title\"] == \"Miss\"][\"Age\"].mean(skipna = True)\ntest_data.loc[(test_data[\"Age\"].isna()) & (test_data[\"Title\"] == \"Mrs\"),\"Age\"]= test_data[test_data[\"Title\"] == \"Mrs\"][\"Age\"].mean(skipna = True)\ntest_data.loc[(test_data[\"Age\"].isna()) & (test_data[\"Title\"] == \"Master\"),\"Age\"]= test_data[test_data[\"Title\"] == \"Master\"][\"Age\"].mean(skipna = True)\ntest_data.loc[(test_data[\"Age\"].isna()) & (test_data[\"Title\"] == \"Ms\"),\"Age\"]= test_data[test_data[\"Title\"] == \"Miss\"][\"Age\"].mean(skipna = True)\ntest_data[test_data[\"Fare\"].isna()]\ntest_data[\"Fare\"].fillna(test_data[test_data[\"Pclass\"] == 3][\"Fare\"].mean(),inplace = True)\nprint(test_data.isnull().sum())\ngender_submission = pd.DataFrame(index = test_data[\"PassengerId\"])\nt_data = test_data.drop([\"PassengerId\",\"Name\",\"SibSp\",\"Parch\",\"Ticket\",\"Title\"],axis = 1)\nt_data.head()\nt_data[\"Sex\"].replace({\"male\":0,\"female\":1},inplace = True)\nt_data[\"Embarked\"].replace({\"S\":0,\"C\":1,\"Q\":2},inplace = True)\nt_data[[\"Fare\"]] = scaler.fit_transform(t_data[[\"Fare\"]])\nt_data.head()\ngender_submission[\"Survived\"] = model.predict(t_data)\ngender_submission.to_csv(\"submission.csv\")","meta":"{'source': 'AI4Code', 'id': '720837f4aff0fd'}"}
{"id":"52915","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tzlocal import get_localzone\nfrom datetime import datetime \nDATA_DIR = '\/kaggle\/input\/10-days-radiation-measurements-at-living-house'\n\"\"\"\nFile listing\n\"\"\"\ndata_files = []\n\nfor f in listdir(DATA_DIR):\n    if isfile(join(DATA_DIR, f)) \\\n        and f.endswith('.csv'):\n        data_files.append(f)\n\nprint('Source data files:')\nfor f in data_files: print(f)\n\"\"\"\nTransform date format from unix time stamp to date and calculate mean doses\n\"\"\"\nmean_dose = []\ndates = []\nfor f in data_files:\n    mse = pd.read_csv(join(DATA_DIR, f), sep=';')\n    mse[mse.columns[0]] = pd.to_datetime(mse[mse.columns[0]], \n                                         unit='ms', \n                                         utc=True)\n    mse[mse.columns[0]] = mse[mse.columns[0]]\\\n        .apply(lambda dt: dt.astimezone(get_localzone()))\n    mse[mse.columns[1]] = mse[mse.columns[1]]\\\n        .apply(lambda val: float(val.replace(',', '.')))\n    edge_date = datetime\\\n        .strptime(f.split('_')[1]\n        .split('.csv')[0], '%d.%m.%Y')\\\n        .replace(hour=15, minute=0)\\\n        .astimezone(get_localzone())\n    filtered_mse = mse[mse[mse.columns[0]] < edge_date]\n    dates.append(edge_date)\n    mean_dose.append(filtered_mse.iloc[:, [1]].values.mean())\n\ndates = np.asarray(dates).reshape(len(dates), 1)\nmean_dose = np.asarray(mean_dose).reshape(len(mean_dose), 1)\nmeans = np.concatenate((dates, mean_dose), axis=1)\nsorted_means = np.asarray(sorted(means, key=lambda x: x[0]))\nplt.figure(figsize=(13,4))\nplt.plot(sorted_means[:, 0], sorted_means[:, 1])\nplt.title('Radiation doses')\nplt.ylabel(mse.columns[1])\nplt.xlabel('date, days')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '6169025238fa0e'}"}
{"id":"93627","text":"\"\"\"\n## Introduction\nGreetings from the Kaggle bot! This is an automatically-generated kernel with starter code demonstrating how to read in the data and begin exploring. Click the blue \"Edit Notebook\" or \"Fork Notebook\" button at the top of this kernel to begin editing.\n\"\"\"\n\"\"\"\n## Exploratory Analysis\nTo begin this exploratory analysis, first use `matplotlib` to import libraries and define functions for plotting the data. Depending on the data, not all plots will be made. (Hey, I'm just a kerneling bot, not a Kaggle Competitions Grandmaster!)\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt # plotting\nimport numpy as np # linear algebra\nimport os # accessing directory structure\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\n\"\"\"\nThere is 1 csv file in the current version of the dataset:\n\n\"\"\"\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n\"\"\"\nThe next hidden code cells define functions for plotting data. Click on the \"Code\" button in the published kernel to reveal the hidden code.\n\"\"\"\n# Distribution graphs (histogram\/bar graph) of column data\ndef plotPerColumnDistribution(df, nGraphShown, nGraphPerRow):\n    nunique = df.nunique()\n    df = df[[col for col in df if nunique[col] > 1 and nunique[col] < 50]] # For displaying purposes, pick columns that have between 1 and 50 unique values\n    nRow, nCol = df.shape\n    columnNames = list(df)\n    nGraphRow = (nCol + nGraphPerRow - 1) \/ nGraphPerRow\n    plt.figure(num = None, figsize = (6 * nGraphPerRow, 8 * nGraphRow), dpi = 80, facecolor = 'w', edgecolor = 'k')\n    for i in range(min(nCol, nGraphShown)):\n        plt.subplot(nGraphRow, nGraphPerRow, i + 1)\n        columnDf = df.iloc[:, i]\n        if (not np.issubdtype(type(columnDf.iloc[0]), np.number)):\n            valueCounts = columnDf.value_counts()\n            valueCounts.plot.bar()\n        else:\n            columnDf.hist()\n        plt.ylabel('counts')\n        plt.xticks(rotation = 90)\n        plt.title(f'{columnNames[i]} (column {i})')\n    plt.tight_layout(pad = 1.0, w_pad = 1.0, h_pad = 1.0)\n    plt.show()\n\n# Correlation matrix\ndef plotCorrelationMatrix(df, graphWidth):\n    filename = df.dataframeName\n    df = df.dropna('columns') # drop columns with NaN\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    if df.shape[1] < 2:\n        print(f'No correlation plots shown: The number of non-NaN or constant columns ({df.shape[1]}) is less than 2')\n        return\n    corr = df.corr()\n    plt.figure(num=None, figsize=(graphWidth, graphWidth), dpi=80, facecolor='w', edgecolor='k')\n    corrMat = plt.matshow(corr, fignum = 1)\n    plt.xticks(range(len(corr.columns)), corr.columns, rotation=90)\n    plt.yticks(range(len(corr.columns)), corr.columns)\n    plt.gca().xaxis.tick_bottom()\n    plt.colorbar(corrMat)\n    plt.title(f'Correlation Matrix for {filename}', fontsize=15)\n    plt.show()\n\n# Scatter and density plots\ndef plotScatterMatrix(df, plotSize, textSize):\n    df = df.select_dtypes(include =[np.number]) # keep only numerical columns\n    # Remove rows and columns that would lead to df being singular\n    df = df.dropna('columns')\n    df = df[[col for col in df if df[col].nunique() > 1]] # keep columns where there are more than 1 unique values\n    columnNames = list(df)\n    if len(columnNames) > 10: # reduce the number of columns for matrix inversion of kernel density plots\n        columnNames = columnNames[:10]\n    df = df[columnNames]\n    ax = pd.plotting.scatter_matrix(df, alpha=0.75, figsize=[plotSize, plotSize], diagonal='kde')\n    corrs = df.corr().values\n    for i, j in zip(*plt.np.triu_indices_from(ax, k = 1)):\n        ax[i, j].annotate('Corr. coef = %.3f' % corrs[i, j], (0.8, 0.2), xycoords='axes fraction', ha='center', va='center', size=textSize)\n    plt.suptitle('Scatter and Density Plot')\n    plt.show()\n\n\"\"\"\nNow you're ready to read in the data and use the plotting functions to visualize the data.\n\"\"\"\n\"\"\"\n### Let's check 1st file: \/kaggle\/input\/AB_NYC_2019.csv\n\"\"\"\nnRowsRead = 1000 # specify 'None' if want to read whole file\n# AB_NYC_2019.csv has 48895 rows in reality, but we are only loading\/previewing the first 1000 rows\ndf1 = pd.read_csv('\/kaggle\/input\/AB_NYC_2019.csv', delimiter=',', nrows = nRowsRead)\ndf1.dataframeName = 'AB_NYC_2019.csv'\nnRow, nCol = df1.shape\nprint(f'There are {nRow} rows and {nCol} columns')\n\"\"\"\nLet's take a quick look at what the data looks like:\n\"\"\"\ndf1.head(5)\n\"\"\"\nDistribution graphs (histogram\/bar graph) of sampled columns:\n\"\"\"\nplotPerColumnDistribution(df1, 10, 5)\n\"\"\"\nCorrelation matrix:\n\"\"\"\nplotCorrelationMatrix(df1, 8)\n\"\"\"\nScatter and density plots:\n\"\"\"\nimport pandas as pd\nimport geopandas as gpd\nimport math\nimport folium\nfrom folium import Choropleth, Circle, Marker\nfrom folium.plugins import HeatMap, MarkerCluster\nm_1 = folium.Map(location=[40.7128,-74.0060], tiles='cartodbpositron', zoom_start=12)\n\n# Adding a heatmap to the base map\nHeatMap(data=df1[['latitude', 'longitude']], radius=10).add_to(m_1)\nplotScatterMatrix(df1, 20, 10)\n\"\"\"\n## Let's look at the heat map using geospatial function\n\"\"\"\nimport pandas as pd\nimport geopandas as gpd\nimport math\nimport folium\nfrom folium import Choropleth, Circle, Marker\nfrom folium.plugins import HeatMap, MarkerCluster\nm_1 = folium.Map(location=[40.7128,-74.0060], tiles='cartodbpositron', zoom_start=12.4)\n\n# Adding a heatmap to the base map\nHeatMap(data=df1[['latitude', 'longitude']], radius=13).add_to(m_1)\n\n# Displaying the map\nm_1\nnumber_of_reviews = df1[(df1.number_of_reviews.isin(range(42,58)))]\n# Creating a map\nm_2 = folium.Map(location=[40.7128,-74.0060], tiles='cartodbpositron', zoom_start=11.5)\n\n# Adding points to the map\nfor idx, row in number_of_reviews.iterrows():\n    Marker([row['latitude'], row['longitude']]).add_to(m_2)\n\n# Displaying the map\nm_2\n\"\"\"\n## Conclusion\nThanks to other contributors for their  codes. Please like and edit if needed.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'abda679ebd82eb'}"}
{"id":"121825","text":"\"\"\"\n**Recovering bonds from structure**\n\nThis kernel presents a method to extract the bonds between atoms in a molecule.  The inputs are the XYZ coordinates of the atoms (as found in the given structure data) and the covalent radius for each element (from wikipedia).  The output is, for each atom, a list of atom_indexes of the other atoms that it is bonded to.  The method is similar to the atomic connectivity step described here: http:\/\/proteinsandwavefunctions.blogspot.com\/2018\/01\/xyz2mol-converting-xyz-file-to-rdkit.html.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm_notebook as tqdm\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nprint(os.listdir(\"..\/input\"))\n\nKAGGLE_DIR = '..\/input'\n\n# # Atom level properties\n# MULLIKEN_CHARGES_CSV = os.path.join(KAGGLE_DIR, 'mulliken_charges.csv')\n# SCALAR_COUPLING_CONTRIBUTIONS_CSV = os.path.join(KAGGLE_DIR, 'scalar_coupling_contributions.csv')\n# MAGNETIC_SHIELDING_TENSORS_CSV = os.path.join(KAGGLE_DIR, 'magnetic_shielding_tensors.csv')\nSTRUCTURES_CSV = os.path.join(KAGGLE_DIR, 'structures.csv')\n\n# # Molecule level properties\n# POTENTIAL_ENERGY_CSV = os.path.join(KAGGLE_DIR, 'potential_energy.csv')\n# DIPOLE_MOMENTS_CSV = os.path.join(KAGGLE_DIR, 'dipole_moments.csv')\n\n# Atom-Atom interactions\nTRAIN_CSV = os.path.join(KAGGLE_DIR, 'train.csv')\nTEST_CSV = os.path.join(KAGGLE_DIR, 'test.csv')\n\"\"\"\n**Read and preprocess structure data**\n\nThe most important step here for bond detection is the addition of the atomic radius values.  There are several different definitions of atomic radius, but the most relevant in this situation is the radius of a single covalent bond.  Wikipedia maintains a table with this value at https:\/\/en.wikipedia.org\/wiki\/Atomic_radii_of_the_elements_(data_page).  I increased the values slightly in order to reduce false negatives.  Atoms that are not bonded repel each other, so it should be rare that this increase will result in false positives.\n\"\"\"\natomic_radius = {'H':0.38, 'C':0.77, 'N':0.75, 'O':0.73, 'F':0.71} # Without fudge factor\n\nfudge_factor = 0.05\natomic_radius = {k:v + fudge_factor for k,v in atomic_radius.items()}\nprint(atomic_radius)\n\nelectronegativity = {'H':2.2, 'C':2.55, 'N':3.04, 'O':3.44, 'F':3.98}\n\nstructures = pd.read_csv(STRUCTURES_CSV, dtype={'atom_index':np.int8})\n\natoms = structures['atom'].values\natoms_en = [electronegativity[x] for x in tqdm(atoms)]\natoms_rad = [atomic_radius[x] for x in tqdm(atoms)]\n\nstructures['EN'] = atoms_en\nstructures['rad'] = atoms_rad\n\ndisplay(structures.head())\n\"\"\"\n**Chemical Bond Calculation**\n\n\n\"\"\"\ni_atom = structures['atom_index'].values\np = structures[['x', 'y', 'z']].values\np_compare = p\nm = structures['molecule_name'].values\nm_compare = m\nr = structures['rad'].values\nr_compare = r\n\nsource_row = np.arange(len(structures))\nmax_atoms = 28\n\nbonds = np.zeros((len(structures)+1, max_atoms+1), dtype=np.int8)\nbond_dists = np.zeros((len(structures)+1, max_atoms+1), dtype=np.float32)\n\nprint('Calculating bonds')\n\nfor i in tqdm(range(max_atoms-1)):\n    p_compare = np.roll(p_compare, -1, axis=0)\n    m_compare = np.roll(m_compare, -1, axis=0)\n    r_compare = np.roll(r_compare, -1, axis=0)\n    \n    mask = np.where(m == m_compare, 1, 0) #Are we still comparing atoms in the same molecule?\n    dists = np.linalg.norm(p - p_compare, axis=1) * mask\n    r_bond = r + r_compare\n    \n    bond = np.where(np.logical_and(dists > 0.0001, dists < r_bond), 1, 0)\n    \n    source_row = source_row\n    target_row = source_row + i + 1 #Note: Will be out of bounds of bonds array for some values of i\n    target_row = np.where(np.logical_or(target_row > len(structures), mask==0), len(structures), target_row) #If invalid target, write to dummy row\n    \n    source_atom = i_atom\n    target_atom = i_atom + i + 1 #Note: Will be out of bounds of bonds array for some values of i\n    target_atom = np.where(np.logical_or(target_atom > max_atoms, mask==0), max_atoms, target_atom) #If invalid target, write to dummy col\n    \n    bonds[(source_row, target_atom)] = bond\n    bonds[(target_row, source_atom)] = bond\n    bond_dists[(source_row, target_atom)] = dists\n    bond_dists[(target_row, source_atom)] = dists\n\nbonds = np.delete(bonds, axis=0, obj=-1) #Delete dummy row\nbonds = np.delete(bonds, axis=1, obj=-1) #Delete dummy col\nbond_dists = np.delete(bond_dists, axis=0, obj=-1) #Delete dummy row\nbond_dists = np.delete(bond_dists, axis=1, obj=-1) #Delete dummy col\n\nprint('Counting and condensing bonds')\n\nbonds_numeric = [[i for i,x in enumerate(row) if x] for row in tqdm(bonds)]\nbond_lengths = [[dist for i,dist in enumerate(row) if i in bonds_numeric[j]] for j,row in enumerate(tqdm(bond_dists))]\nn_bonds = [len(x) for x in bonds_numeric]\n\n#bond_data = {'bond_' + str(i):col for i, col in enumerate(np.transpose(bonds))}\n#bond_data.update({'bonds_numeric':bonds_numeric, 'n_bonds':n_bonds})\n\nbond_data = {'bonds':bonds_numeric, 'n_bonds':n_bonds, 'bond_lengths':bond_lengths}\nbond_df = pd.DataFrame(bond_data)\nstructures = structures.join(bond_df)\ndisplay(structures.head(20))\n\"\"\"\n**Validation**\n\"\"\"\n\"\"\"\n**The last molecule - 133885**\n\nHere is a visualization of the xyz file generated by a program called IQmol \n\n(Info and download here: http:\/\/iqmol.org\/)\n\n![image.png](attachment:image.png)\n\nThis molecule has 16 atoms.  Below are the generated bonds.  It is fairly easy to verify that the visualization program and the generated bonds agree. (Note: IQmol uses 1-index and I use 0-index)\n\"\"\"\nstructures.tail(16)\n\"\"\"\n**Bond counts by element**\n\nBased on the number of electrons in an atom's valence shell, we know how many bonds the atom needs to form to be stable.  Hydrogen needs 1, Flourine needs 1, Oxygen needs 2, Nitrogen needs 3, and Carbon needs 4.  Bonds can be single, double, or triple, but we have not yet calculated the strength of the bonds.  Therefore there is a range of valid bond counts we could get for each atom.\n\n- Hydrogen         \n    - 1\n- Flourine\n    - 1\n- Oxygen\n    - 1 - 2\n- Nitrogen         \n    - 1 - 3\n- Carbon   \n    - 2 - 4\n    \nWhen we graph the number of bonds for each element we see that these conditions are met, with the sole exception of several Nitrogen atoms forming 4 bonds.\n\"\"\"\nelements = structures['atom'].unique()\ngraphs_per_row = 3\nrow_count = int(np.ceil(len(elements) \/ graphs_per_row))\nfig, axes = plt.subplots(row_count, graphs_per_row, figsize=(20, row_count * 5))\n\nfor i, element in enumerate(elements):\n    x = structures[structures['atom'] == element].n_bonds.value_counts().index\n    y = structures[structures['atom'] == element].n_bonds.value_counts().values\n    ax = axes[i\/\/graphs_per_row, i%graphs_per_row]\n    ax.bar(x=x, height=y, tick_label=[str(n) for n in x], label='Bond count')\n    ax.set(title=f'Bond count - {element}', xlabel='Bond count', ylabel='frequency')\n\nplt.tight_layout()\nplt.show()\nelements = structures['atom'].unique()\ngraphs_per_row = 3\nrow_count = int(np.ceil(len(elements) \/ graphs_per_row))\nfig, axes = plt.subplots(row_count, graphs_per_row, figsize=(20, row_count * 5))\n\nfor i, element in enumerate(elements):\n    y = []\n    for l in structures[structures['atom'] == element]['bond_lengths'].values:\n        y.extend(l)\n    ax = axes[i\/\/graphs_per_row, i%graphs_per_row]\n    ax.hist(y, bins=1000)\n    ax.set(title=f'Bond lengths - {element}', xlabel='Bond length', ylabel='frequency')\n\nplt.tight_layout()\nplt.show()\nstructures.head()\nstructures[\"atom_count\"] = structures.groupby(\"molecule_name\")[\"atom_index\"].transform(\"size\")\nstructures.atom.value_counts()\nstructures.head(15).groupby(\"molecule_name\")[\"atom_index\"].size()\nstructures.drop(\"bonds\",axis=1).to_csv(\"struct_bonds_v1.csv.gz\",index=False,compression=\"gzip\")","meta":"{'source': 'AI4Code', 'id': 'e00f70461e7863'}"}
{"id":"119802","text":"! pip install https:\/\/github.com\/CellProfiling\/HPA-Cell-Segmentation\/archive\/master.zip\nimport pandas as pd\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport cv2\nimport random\nimport numpy as np\n\"\"\"\n# Utils\n\"\"\"\ndef prep_images(ID, img_dir='..\/input\/hpa-single-cell-image-classification\/train\/'):\n    green_p = img_dir + f'{ID}_green.png'\n    blue_p = img_dir + f'{ID}_blue.png'\n    red_p = img_dir + f'{ID}_red.png'\n    yellow_p = img_dir + f'{ID}_yellow.png'\n\n    protein_img = cv2.imread(green_p)\n    nucleus_img = cv2.imread(blue_p)\n    microtubules_img = cv2.imread(red_p)\n    ER_img = cv2.imread(yellow_p)\n\n    return dict(protein=protein_img,\n                microtubules=microtubules_img,\n                endoplasmic_reticulum=ER_img,\n                nucleus=nucleus_img,\n                )\n\n\ndef merge_image(images):\n    \"\"\"\n    Return a 3-channel image.\n    The channels are: microtubules, endoplasmic reticulum, and nucleus\n    \"\"\"\n\n    merged = np.dstack((images['microtubules'][:, :, 0],\n                        images['endoplasmic_reticulum'][:, :, 0],\n                        images['nucleus'][:, :, 0],\n                        ))\n\n    return merged\n\n\ndef visualize(images, show_merge=True, ID=None, df=None):\n    if show_merge:\n        images['merge'] = 0\n\n    n = len(images)\n    f = plt.figure(figsize=(12, 4))\n    for i, (key, image) in enumerate(images.items()):\n        plt.subplot(1, n, i + 1)\n\n        if key == 'merge':\n            image = merge_image(images)\n\n        title = ' '.join(key.split('_')).title()\n        plt.imshow(image)\n        plt.title(title)\n        plt.xticks([])\n        plt.yticks([])\n\n        if ID is not None:\n            labels = df.set_index('ID').loc[ID, 'Label'].split('|')\n            labels = [label_map[key] for key in labels]\n            f.suptitle(labels)\n\n    f.tight_layout()\ntrain = pd.read_csv('..\/input\/hpa-single-cell-image-classification\/train.csv')\n\ntrain\n\"\"\"\n# What should I expect the data format to be?\n\"\"\"\n\"\"\"\nThe training image-level labels are provided for each sample in train.csv. The bulk of the data for images - train.zip. Each sample consists of four files. Each file represents a different filter on the subcellular protein patterns represented by the sample. The format should be [filename]_[filter color].png for the PNG files. Colors are red for microtubule channels, blue for nuclei channels, yellow for Endoplasmic Reticulum (ER) channels, and green for protein of interest.\n\"\"\"\n\"\"\"\n# What am I predicting?\n\"\"\"\n\"\"\"\nYou are predicting protein organelle localization labels for each cell in the image. Border cells are included when there is enough information to decide on the labels.\n\nThere are in total 19 different labels present in the dataset (18 labels for specific locations, and label 18 for negative and unspecific signal). The dataset is acquired in a highly standardized way using one imaging modality (confocal microscopy). However, the dataset comprises 17 different cell types of highly different morphology, which affect the protein patterns of the different organelles. All image samples are represented by four filters (stored as individual files), the protein of interest (green) plus three cellular landmarks: nucleus (blue), microtubules (red), endoplasmic reticulum (yellow). The green filter should hence be used to predict the label, and the other filters are used as references. The labels are represented as integers that map to the following:\n\"\"\"\nimage_paths = glob('..\/input\/hpa-single-cell-image-classification\/train\/*.png')\n\nlen(image_paths)\nlabel_map = {'0': 'Nucleoplasm',\n             '1': 'Nuclear membrane',\n             '2': 'Nucleoli',\n             '3': 'Nucleoli fibrillar center',\n             '4': 'Nuclear speckles',\n             '5': 'Nuclear bodies',\n             '6': 'Endoplasmic reticulum',\n             '7': 'Golgi apparatus',\n             '8': 'Intermediate filaments',\n             '9': 'Actin filaments',\n             '10': 'Microtubules',\n             '11': 'Mitotic spindle',\n             '12': 'Centrosome',\n             '13': 'Plasma membrane',\n             '14': 'Mitochondria',\n             '15': 'Aggresome',\n             '16': 'Cytosol',\n             '17': 'Vesicles and punctate cytosolic patterns',\n             '18': 'Negative'\n            }\nfor _ in range(5):\n    ID = random.choice(train.ID)\n    images = prep_images(ID)\n    visualize(images, ID=ID, df=train)\n\"\"\"\n# Cell Segmentation\n\"\"\"\nfrom hpacellseg import cellsegmentator\nfrom hpacellseg.utils import label_cell, label_nuclei\nimage_ids = []\nfor _ in range(5):\n    image_ids.append(random.choice(train.ID.unique()))\n    \nimage_dicts = [prep_images(image_id) for image_id in image_ids]\n\nimage_lists = []\nfor key in image_dicts[0].keys():\n    if key == 'protein':\n        continue\n    images = [image_dict[key][:, :, 0] for image_dict in image_dicts]\n    image_lists.append(images)\nsegmentator = cellsegmentator.CellSegmentator(nuclei_model='.nuclei_model.pth',\n                                              cell_model='.cell_model.pth',\n                                              scale_factor=0.25,\n                                              device='cuda',\n                                              padding=False,\n                                              multi_channel_model=True)\ncell_segmentations = segmentator.pred_cells(image_lists)\nnuc_segmentations = segmentator.pred_nuclei(image_lists[2])\nfor i in range(5):\n    img = merge_image(image_dicts[i])\n    nuclei_mask, cell_mask = label_cell(nuc_segmentations[i], cell_segmentations[i])\n    visualize(dict(image=img,\n                  nuclei_mask=nuclei_mask,\n                  cell_mask=cell_mask,\n                  ),\n              show_merge=False\n             )","meta":"{'source': 'AI4Code', 'id': 'dc60cf18d8e12e'}"}
{"id":"58274","text":"import random\nimport re\nfrom datetime import datetime\n\n# Data manipulation\nimport pandas as pd\nimport numpy as np\n\n# Visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Model\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nimport xgboost as xgb\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# Suppress warnings \nimport warnings\nwarnings.filterwarnings('ignore')\n\npd.options.display.max_rows = 100\n\nfrom IPython.display import display\n\n%matplotlib inline\n# Set a few plotting defaults\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = (12, 8)\nplt.rcParams['font.size'] = 14\nplt.rcParams['patch.edgecolor'] = 'k'\n\"\"\"\n\ub370\uc774\ud130\ub97c \uc77d\uc5b4\uc635\ub2c8\ub2e4.\n\"\"\"\ntrain_raw = pd.read_csv('..\/input\/train.csv')\ntest_raw = pd.read_csv('..\/input\/test.csv')\ntrain_raw.shape, test_raw.shape\n\"\"\"\nTrain \ub370\uc774\ud130\uc758 Feature, Data Type, \uacb0\uce21\uce58\uac00 \uc788\ub294\uc9c0 \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\ntrain_raw.info()\n\"\"\"\nTest \ub370\uc774\ud130\uc758 Feature, Data Type, \uacb0\uce21\uce58\uac00 \uc788\ub294\uc9c0 \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\ntest_raw.info()\ndef plot_distribution_by_target(df, field):\n    df = df[df[field].notnull()]\n\n    fig = plt.figure(figsize = (14, 12))\n    ax1 = plt.subplot(221)\n    \n    sns.kdeplot(df[field], label='Total', alpha=0.7, ax=ax1)\n    sns.kdeplot(df[df.train == 1][field], label='Train', alpha=0.7, ax=ax1)\n    sns.kdeplot(df[df.train == 0][field], label='Test', alpha=0.7, ax=ax1)\n\n    plt.xlabel(field.upper())\n    plt.ylabel('Density')\n    \n    ax2 = plt.subplot(222)\n\n    sns.boxplot(x='train', y=field, data=df, ax=ax2)\n    plt.xticks((0,1), ('Test','Train'))\n    \n    df = df[df.train == 1]\n    \n    ax3 = plt.subplot(223)\n\n    sns.kdeplot(df[df.Survived == 1][field], label='Survived', alpha=0.7, ax=ax3)\n    sns.kdeplot(df[df.Survived == 0][field], label='Not Survived', alpha=0.7, ax=ax3)\n\n    plt.xlabel(field.upper())\n    plt.ylabel('Density')\n\n    ax4 = plt.subplot(224)\n\n    sns.boxplot(x='Survived', y=field, data=df, ax=ax4)\n    plt.xticks((0,1), ('Not Survived','Survived'))\n    \n    fig.suptitle(f'{field.upper()} Distribution', fontsize=20)\n    \n    plt.show()\nRANDOM_SEED = 42\nnp.random.seed(RANDOM_SEED)\n\"\"\"\nFeature Engineering\uc744 \ud1b5\ud574 Feature\ub97c \ucd94\uac00\ud574\uac00\uba74\uc11c \uc131\ub2a5 \ubcc0\ud654\ub97c \ubcf4\uae30 \uc804\uc5d0 \uae30\ubcf8 Feature\uc758 Baseline \ubaa8\ub378 \uc131\ub2a5\uacfc Feature Importance \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\nbase_features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']\n\nX_train = train_raw[base_features]\nX_test = test_raw[base_features]\ny_train = train_raw.Survived\n\nX_train.Embarked = X_train.Embarked.fillna(X_train.Embarked.mode()[0])\nX_test.Embarked = X_test.Embarked.fillna(X_train.Embarked.mode()[0])\n\nle = LabelEncoder()\nX_train.Sex = le.fit_transform(X_train[['Sex']])\nX_test.Sex = le.transform(X_test[['Sex']])\n\nX_train.Embarked = le.fit_transform(X_train[['Embarked']])\nX_test.Embarked = le.transform(X_test[['Embarked']])\n\nmedian_imputer = SimpleImputer(strategy='median')\nX_train.Age = median_imputer.fit_transform(X_train[['Age']])\nX_test.Age = median_imputer.transform(X_test[['Age']])\n\nX_train.Fare = median_imputer.fit_transform(X_train[['Fare']])\nX_test.Fare = median_imputer.transform(X_test[['Fare']])\n\nprint(f'X_train shape : {X_train[base_features].shape}, X_test shape : {X_test[base_features].shape}')\ndef cv_model(train, train_labels, model, name, model_results=None, cv=10, scoring='accuracy'):\n    \"\"\"Perform k fold cross validation of a model\"\"\"\n    \n    cv_scores = cross_val_score(model, train, train_labels, cv=cv, scoring=scoring, n_jobs=-1)\n    print(f'{cv} Fold CV {scoring} for {name}: {round(cv_scores.mean(), 5)} with std: {round(cv_scores.std(), 5)}')\n    \n    model.fit(train, train_labels)\n    \n    if model_results is None:\n        model_results = pd.DataFrame({\n            'model': name,\n            'cv_mean': cv_scores.mean(),\n            'cv_std': cv_scores.std(),\n            #'test_score': test_score\n        }, index = [0])\n    else:\n        model_results = model_results.append(pd.DataFrame({\n            'model': name,\n            'cv_mean': cv_scores.mean(),\n            'cv_std': cv_scores.std(),\n            #'test_score': test_score\n        }, index = [0]), ignore_index = True)\n\n    return model_results, model\n\ndef show_model_results(model_results):\n    display(model_results)\n    df = model_results.copy().set_index('model')\n    df.sort_values(by='cv_mean', inplace=True)\n    df['cv_mean'].plot.bar(color = 'orange', figsize = (10, 8),\n                                      yerr = list(df['cv_std']),\n                                      edgecolor = 'k', linewidth = 2)\n    plt.title('Model Train CV Accuracy Score Results');\n    plt.ylabel('Mean CV Accuracy Score (with error bar)');\n    plt.show()\n\ndef plot_feature_importances(estimator, x_cols, n=20, threshold = 0.95):\n    try:\n        df = pd.DataFrame({'feature': x_cols, 'importance': estimator.feature_importances_})\n    except AttributeError:\n        print('model does not provide feature importances')\n        return\n    \n    # Sort features with most important at the head\n    df = df.sort_values('importance', ascending = False).reset_index(drop = True)\n    \n    # Normalize the feature importances to add up to one and calculate cumulative importance\n    df['importance_normalized'] = df['importance'] \/ df['importance'].sum()\n    df['cumulative_importance'] = np.cumsum(df['importance_normalized'])\n    \n    plt.rcParams['font.size'] = 12\n    \n    # Bar plot of n most important features\n    df.loc[:n, :].plot.barh(y = 'importance_normalized', \n                            x = 'feature', color = 'darkgreen', \n                            edgecolor = 'k', figsize = (12, 8),\n                            legend = False, linewidth = 2)\n\n    plt.xlabel('Normalized Importance', size = 18); plt.ylabel(''); \n    plt.title(f'{min(n, len(df))} Most Important Features', size = 18)\n    plt.gca().invert_yaxis()\n    \n    if threshold:\n        # Cumulative importance plot\n        plt.figure(figsize = (8, 6))\n        plt.plot(list(range(1, len(df)+1)), df['cumulative_importance'], 'b-')\n        plt.xlabel('Number of Features', size = 16); plt.ylabel('Cumulative Importance', size = 16); \n        plt.title('Cumulative Feature Importance', size = 18);\n        \n        # Number of features needed for threshold cumulative importance\n        # This is the index (will need to add 1 for the actual number)\n        importance_index = np.min(np.where(df['cumulative_importance'] > threshold))\n        \n        # Add vertical line to plot\n        plt.vlines(importance_index + 1, ymin = 0, ymax = 1.05, linestyles = '--', colors = 'red')\n        plt.show();\n        \n        print('{} features required for {:.0f}% of cumulative importance.'.format(importance_index + 1, \n                                                                                  100 * threshold))\n    \n    print(f'zero importance feature count : {len(df[df.importance == 0])}')\n    \n    return df\n\n# Dataframe to hold results\nmodel_results = pd.DataFrame(columns = ['model', 'cv_mean', 'cv_std'])\n\nmodel_results, xgb_base = cv_model(X_train[base_features], y_train, xgb.XGBClassifier(random_state=RANDOM_SEED),\n                            'XGB_Base', model_results)\n\nplot_feature_importances(xgb_base, base_features)\n\"\"\"\nFeature Engineering \uc791\uc5c5\ud558\uae30 \ud3b8\ud558\ub3c4\ub85d Train, Test \ub370\uc774\ud130\ub97c \ud569\uce69\ub2c8\ub2e4.\n\"\"\"\ntrain_raw = pd.read_csv('..\/input\/train.csv')\ntest_raw = pd.read_csv('..\/input\/test.csv')\n\ntrain_raw.Embarked = train_raw.Embarked.fillna(train_raw.Embarked.mode()[0])\ntest_raw.Embarked = test_raw.Embarked.fillna(test_raw.Embarked.mode()[0])\n\nle = LabelEncoder()\ntrain_raw.Sex = le.fit_transform(train_raw[['Sex']])\ntest_raw.Sex = le.transform(test_raw[['Sex']])\n\ntrain_raw.Embarked = le.fit_transform(train_raw[['Embarked']])\ntest_raw.Embarked = le.transform(test_raw[['Embarked']])\n\ntrain_raw['train'] = 1\ntest_raw['train'] = 0\ndata_all = pd.concat([train_raw, test_raw], axis=0).reset_index(drop=True)\n\"\"\"\n\ud569\uce5c \ub370\uc774\ud130\ub97c \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\ndata_all.info()\n\"\"\"\nSibSp + Parch + 1(\uc790\uae30\uc790\uc2e0)\uc744 \uacc4\uc0b0\ud574\uc11c family_size feature\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndata_all['family_size'] = data_all.SibSp + data_all.Parch + 1\ndef plot_by_target(df, field, col_wrap=4):\n    df = df[df.train == 1]\n    g = sns.catplot('Survived', col=field, data=df, kind='count', col_wrap=col_wrap)\n    plt.show()\n\"\"\"\nfamily_size\uc5d0 \ub530\ub978 Survived\uc758 \ubd84\ud3ec\ub97c \ud655\uc778\ud574\ubcf4\uba74 2-4\uba85\uc77c \ub54c \uc0b4\uc544\ub0a8\uc740 \uc2b9\uac1d\uc758 \ube44\uc728\uc774 \ub354 \ud070 \uac83\uc744 \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'family_size', col_wrap=3)\n\"\"\"\n\uc704 \ubd84\ud3ec\uc5d0 \ub530\ub77c \uc0b4\uc544\ub0a8\uc740 \uc2b9\uac1d\uc744 \uc798 \uad6c\ubd84\ud560 \uc218 \uc788\ub294 2-4\uba85\uc744 \uad6c\ubd84\ud574\uc11c binning\ud558\ub294 family_size_bin feature\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndef calc_family_size_bin(family_size):\n    if family_size == 1:\n        return 0\n    elif family_size <= 4: \n        return 1\n    else:\n        return 2\n        \ndata_all['family_size_bin'] = data_all.family_size.map(calc_family_size_bin)\n\"\"\"\nfamily_size_bin feature\uc5d0 \ub530\ub978 Survived\uc758 \ubd84\ud3ec\ub97c \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'family_size_bin')\n\"\"\"\n\uc2b9\uac1d\uc758 \uc774\ub984\uc744 \ubcf4\uba74 Mr, Mrs \ub4f1\uc758 Title\uc744 Feature\ub85c \ubf51\uc544\ub0bc \uc218 \uc788\uc2b5\ub2c8\ub2e4. \n\"\"\"\ndata_all['name_title'] = data_all.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\n\"\"\"\nTitle\uc758 \ubd84\ud3ec\ub97c \ubcf4\uba74 Mr, Miss, Mrs, Master\uac00 \uac00\uc7a5 \ub9ce\uace0 \ub098\uba38\uc9c0 \ub370\uc774\ud130\ub294 \ub9e4\uc6b0 \uc801\uc740 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\ndata_all.name_title.value_counts().plot.bar()\nplt.title('Name Title Count')\nplt.show()\n\"\"\"\nTitle\uacfc \uc131\ubcc4 \ub370\uc774\ud130\ub97c \ubcf4\uba74 Dr\ub97c \uc81c\uc678\ud55c \ub098\uba38\uc9c0 Title\uc740 \uc131\ubcc4\uc774 \uad6c\ubd84\ub418\ub294 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\npd.crosstab(data_all.Sex, data_all.name_title)\n\"\"\"\nTitle\uc5d0 \ub530\ub978 \ub098\uc774\uc758 Median \uac12\uc744 \ubcf4\uba74, Master\ub294 \ub0a8\uc790\uc544\uc774\uc5d0\uac8c \ubd99\uc774\ub294 Titlem\ub85c \ubcf4\uc785\ub2c8\ub2e4.\n\"\"\"\ndata_all.groupby('name_title').Age.median()\n\"\"\"\nTitle\uc5d0 \ub530\ub978 Survived \ube44\uc728\uc744 \ubcf4\uba74 \uc5ed\uc2dc \uc5ec\uc131\uc744 \uc9c0\uce6d\ud558\ub294 Title\uc758 \uc0dd\uc874\uc728\uc774 \ub192\uc740 \uac83\uacfc \ub0a8\uc790\uc774\uc9c0\ub9cc \ub098\uc774\uac00 \uc5b4\ub9b0 Master\uc758 \uc0dd\uc874\uc728\uc774 \ub192\uc740 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\ndata_all[data_all.train == 1].groupby('name_title').Survived.mean()\n\"\"\"\n\uc774\ub7ec\ud55c \uc815\ubcf4\ub97c \ubc14\ud0d5\uc73c\ub85c \uc0dd\uc874\uc728\uc774 \ub192\uc740 \ub0a8\uc790 \uc544\uc774\uc778 Master\ub97c \uc81c\uc678\ud55c \ub098\uba38\uc9c0 \ub0a8\uc790\ub97c \uc9c0\uce6d\ud558\ub294 Title\uc740 Mr\ub85c \ud569\uce58\uace0, \uc5ec\uc790\ub97c \uc9c0\uce6d\ud558\ub294 Title\uc740 \ub098\uc774\uc5d0 \ub530\ub77c Mrs, Miss\ub85c \ud569\uce69\ub2c8\ub2e4.\n\"\"\"\nname_title_dict = {\n    'Capt': 'Mr',\n    'Col': 'Mr',\n    'Don': 'Mr',\n    'Dona': 'Mrs',    \n    'Dr': 'Dr',\n    'Jonkheer': 'Mr',\n    'Lady': 'Mrs',\n    'Major': 'Mr',\n    'Master': 'Master',\n    'Miss': 'Miss',\n    'Mlle': 'Miss',\n    'Mme': 'Miss',\n    'Mr': 'Mr',\n    'Mrs': 'Mrs',\n    'Ms': 'Mrs',\n    'Rev': 'Mr',\n    'Sir': 'Mr',\n    'Countess': 'Mrs'\n}\n\ndata_all['name_title_cat'] = data_all.name_title.map(name_title_dict)\n\"\"\"\n\uc774\ub807\uac8c \uc0c8\ub85c \ub9cc\ub4e0 name_title_cat feature\uc758 Survived \ubd84\ud3ec\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4. \n\"\"\"\nplot_by_target(data_all, 'name_title_cat', col_wrap=3)\n\"\"\"\n\uc800\ub294 \uc774\ubc88\uc5d0 \ud0c0\uc774\ud0c0\ub2c9 \ubbf8\ub2c8 \uce90\uae00\uc744 \uc9c4\ud589\ud558\uba74\uc11c Ticket\uacfc Name \ub450 \uac00\uc9c0 feature\ub97c \uc790\uc138\ud788 \ubd24\ub294\ub370\uc694.\n\uac19\uc740 \uac00\uc871\uc774\uba74 \uc0dd\uc874\uc728\uc774 \uc11c\ub85c \uc5f0\uad00\uc131\uc774 \uc788\uc9c0 \uc54a\uc744\uae4c \ud558\ub294 \uac00\uc815\ud558\uc5d0 Name\uc5d0\uc11c Last Name\uc744 \ubf51\uc544\ub0b4\uc11c \uac00\uc871 \uad00\uacc4\ub97c \uc5f0\uacb0\ud574\uc92c\uc2b5\ub2c8\ub2e4.\n\uadf8\ub7f0\ub370 Last Name\uc774 \ub3d9\uc77c\ud55c \ub2e4\ub978 \uac00\uc871\uc774 \uc788\uc744 \uc218 \uc788\uae30 \ub54c\ubb38\uc5d0 Family Size\uae4c\uc9c0 \ub354\ud574\uc11c feature\ub97c \ub9cc\ub4e4\uc5c8\uc2b5\ub2c8\ub2e4.\n\ub610, Ticket \ub370\uc774\ud130\ub3c4 \uc790\uc138\ud788 \ubcf4\uba74 \uac19\uc740 \uac00\uc871\uc774 \ub3d9\uc77c\ud55c Ticket\uc778 \ub370\uc774\ud130\uac00 \ub9ce\uc740 \uac83\uc744 \uc54c \uc218 \uc788\uc5b4\uc11c \ub9c8\ucc2c\uac00\uc9c0\ub85c Last Nam\uacfc Ticket\uc744 \uc5f0\uacb0\ud574\uc11c feature\ub97c \ub9cc\ub4e4\uc5c8\uc2b5\ub2c8\ub2e4.\n\"\"\"\ndata_all['last_name'] = data_all.Name.str.extract('([A-Za-z]+),', expand=False)\ndata_all['last_name_family_size'] = data_all.apply(lambda row: row.last_name + '_' + str(row.family_size), axis=1)\ndata_all['last_name_ticket'] = data_all.apply(lambda row: row.last_name + '_' + row.Ticket, axis=1)\nticket_df = data_all.groupby('Ticket', as_index=False)['PassengerId'].count()\nticket_df.columns = ['Ticket','ticket_count']\nticket_df.head()\ndata_all = pd.merge(data_all, ticket_df, on=['Ticket'])\ndata_all = data_all.sort_values('PassengerId').reset_index(drop=True)\n\"\"\"\n\uc774\ub807\uac8c \ub9cc\ub4e0 \uac00\uc871 \uad00\uacc4\uc758 feature\ub97c \uba38\uc2e0\ub7ec\ub2dd \ubaa8\ub378\uc5d0\uc11c \uc0ac\uc6a9\ud558\ub824\uba74 \uc77c\ub2e8 \uac00\uc871\uc774 \uc5c6\ub294 \uc0ac\ub78c(family_size = 1)\uc740 \uc81c\uc678\ud574\uc57c \ud569\ub2c8\ub2e4.\n\ub610, \uc0dd\uac01\ud574\ubcf4\uba74.. \uac00\uc871\uc774 Train, Test \ub370\uc774\ud130 \uc591\ucabd\uc5d0 \ub2e4 \uc788\uc5b4\uc57c \uba38\uc2e0\ub7ec\ub2dd \ubaa8\ub378\uc5d0\uc11c Training\ud558\ub294 \uc758\ubbf8\uac00 \uc788\uc744\ud150\ub370, \uac00\uc871 \uc804\uccb4\uac00 Train \ub370\uc774\ud130\uc5d0\ub9cc \uc788\ub2e4\uba74 \uc774\ub7f0 \ub370\uc774\ud130\ub294 \uad6c\ubd84\ud574\ubd10\uc57c \uc758\ubbf8\uac00 \uc5c6\uc744\uac70\ub77c\ub294 \uac00\uc815\uc744 \uac00\uc9c0\uace0 Train, Test \uc591\ucabd\uc5d0 \ub2e4 \uac00\uc871\uc774 \uc788\ub294 \ub370\uc774\ud130\ub9cc \ubf51\uc544\uc11c Labeling \ud560 \uc218 \uc788\ub3c4\ub85d \ucc98\ub9ac\ud588\uc2b5\ub2c8\ub2e4.\n\"\"\"\nlast_name_family_size_check = data_all[data_all.family_size > 1].groupby('last_name_family_size').agg({'Survived': lambda x: x.isnull().sum()}).reset_index()\nlast_name_family_size_check.columns = ['last_name_family_size','last_name_family_size_feature']\nlast_name_family_size_check.head()\nlast_name_ticket_check = data_all[data_all.ticket_count > 1].groupby('last_name_ticket').agg({'Survived': lambda x: x.isnull().sum()}).reset_index()\nlast_name_ticket_check.columns = ['last_name_ticket','last_name_ticket_feature']\nlast_name_ticket_check.head()\ndata_all = pd.merge(data_all, last_name_family_size_check, on='last_name_family_size', how='left')\ndata_all = data_all.sort_values('PassengerId').reset_index(drop=True)\ndata_all.last_name_family_size_feature = data_all.last_name_family_size_feature.fillna(0)\ndata_all.head()\ndata_all = pd.merge(data_all, last_name_ticket_check, on='last_name_ticket', how='left')\ndata_all = data_all.sort_values('PassengerId').reset_index(drop=True)\ndata_all.last_name_ticket_feature = data_all.last_name_ticket_feature.fillna(0)\ndata_all.head()\n\"\"\"\n\uc774\ub807\uac8c \uad6c\ubd84\ud55c feature\uc5d0\uc11c \uac00\uc871 \uad00\uacc4\uac00 \uc5c6\uc774 \ud640\ub85c \ud0c4 \uc0ac\ub78c\uc774\ub098 \uac00\uc871 \uad00\uacc4\uac00 \uc788\uc9c0\ub9cc Train \ub370\uc774\ud130\uc5d0\ub9cc \uac00\uc871 \uad00\uacc4\uac00 \uc788\ub294 \ub370\uc774\ud130\ub294 X\ub85c \ud45c\uc2dc\ud569\ub2c8\ub2e4.\n\"\"\"\ndata_all.loc[data_all.last_name_family_size_feature == 0, 'last_name_family_size'] = 'X'\ndata_all.loc[data_all.last_name_ticket_feature == 0, 'last_name_ticket'] = 'X'\n\"\"\"\n\uac00\uc871 \uad00\uacc4\uac00 \uc5c6\uc774 \ud640\ub85c \ud0c4 \uc0ac\ub78c\uc774\ub098 \uac00\uc871 \uad00\uacc4\uac00 \uc788\uc9c0\ub9cc Train \ub370\uc774\ud130\uc5d0\ub9cc \uac00\uc871 \uad00\uacc4\uac00 \uc788\ub294 \ub370\uc774\ud130\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n\"\"\"\ndata_all[['last_name_family_size','Sex','Age','last_name','family_size','Name','Ticket',\n          'Survived']][data_all.last_name_family_size == 'X'].sort_values(['last_name','family_size']).head()\ndata_all[['last_name_ticket','Sex','Age','last_name','ticket_count','Name','Ticket',\n          'Survived']][data_all.last_name_ticket == 'X'].sort_values(['last_name','Ticket']).head()\n\"\"\"\n \uac00\uc871 \uad00\uacc4\uac00 \uc788\uace0, Train, Test \uc591\ucabd\uc5d0 \ub2e4 \uac00\uc871\uc774 \uc788\ub294 \ub370\uc774\ud130\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n\"\"\"\ndata_all[['last_name_family_size','Sex','Age','last_name','family_size','Name','Ticket',\n          'last_name_family_size_feature',\n          'Survived']][data_all.last_name_family_size != 'X'].sort_values(['last_name','family_size']).head(9)\ndata_all[['last_name_ticket','Sex','Age','last_name','ticket_count','Name','Ticket',\n          'last_name_ticket_feature',\n          'Survived']][data_all.last_name_ticket != 'X'].sort_values(['last_name','Ticket']).head()\n\"\"\"\n\uc5ec\uae30\uc11c \ud55c \ubc88 \ub354 \uc0dd\uac01\ud574\ubcf4\uba74, \uac00\uc871 \uad00\uacc4\uc5d0 \uc788\ub294 \uc0ac\ub78c \uc911\uc5d0 \uc0b4\uc544\ub0a8\uc740 \uc0ac\ub78c\uc774 \uc788\ub2e4\uba74, Test \ub370\uc774\ud130\uc758 \uac19\uc740 \uac00\uc871\uc778 \uc0ac\ub78c\ub3c4 \uc0b4\uc544\ub0a8\uc744 \ud655\ub960\uc774 \ub192\uc9c0 \uc54a\uc744\uae4c\ub77c\ub294 \uac00\uc815\uc744 \ud588\uc2b5\ub2c8\ub2e4.\n\uadf8\ub7ec\ud55c \uad00\uacc4\ub97c \uc5f0\uacb0\ud574\uc8fc\ub294 feature\ub97c Last Name, Family Size\uc640 Last Name, Ticket\uc5d0 \ub300\ud574 \uac01\uac01 \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\nfamily_survival = data_all.groupby(['last_name_family_size','family_size']).Survived.sum().reset_index()\nfamily_survival.columns = ['last_name_family_size','family_size','family_survival_sum']\nfamily_survival.head()\nfamily_ticket_count = data_all.groupby(['last_name','Ticket']).PassengerId.count().reset_index()\nfamily_ticket_count.columns = ['last_name','Ticket','family_ticket_count']\n\nfamily_ticket_survival = data_all.groupby(['last_name','Ticket']).Survived.sum().reset_index()\nfamily_ticket_survival.columns = ['last_name','Ticket','family_ticket_survival_sum']\n\nfamily_ticket_survival = pd.merge(family_ticket_count, family_ticket_survival, on=['last_name','Ticket'])\nfamily_ticket_survival.head()\n\"\"\"\n\ub2e4\uc74c\uacfc \uac19\uc774 feature\ub97c \uacc4\uc0b0\ud569\ub2c8\ub2e4.\n* \uac00\uc871\uc774 \uc788\uace0, \uac00\uc871 \uc911\uc5d0 \ud55c \uc0ac\ub78c\uc774\ub77c\ub3c4 \uc0b4\uc544\ub0a8\uc740 \uc0ac\ub78c\uc774 \uc788\ub2e4\uba74 1\n* \uac00\uc871\uc774 \uc804\ubd80 \uc8fd\uc5c8\ub2e4\uba74 0\n* \uc704 \ucf00\uc774\uc2a4\uc5d0 \ud574\ub2f9\ud558\uc9c0 \uc54a\ub294 default \uac12\uc740 0.5\n\"\"\"\ndef calc_family_survival(row):\n    family_survival = 0.5\n    if row['family_size'] > 1 and row['family_survival_sum'] > 0:\n        family_survival = 1\n    elif row['family_size'] > 1 and row['family_survival_sum'] == 0:\n        family_survival = 0\n        \n    return family_survival\n\nfamily_survival['family_survival'] = family_survival.apply(calc_family_survival, axis=1)\nfamily_survival[family_survival['family_size'] > 1].head()\ndef calc_family_ticket_survival(row):\n    family_ticket_survival = 0.5\n    if row['family_ticket_count'] > 1 and row['family_ticket_survival_sum'] > 0:\n        family_ticket_survival = 1\n    elif row['family_ticket_count'] > 1 and row['family_ticket_survival_sum'] == 0:\n        family_ticket_survival = 0\n        \n    return family_ticket_survival\n\nfamily_ticket_survival['family_ticket_survival'] = family_ticket_survival.apply(calc_family_ticket_survival,\n                                                                                axis=1)\nfamily_ticket_survival[family_ticket_survival['family_ticket_count'] > 1].head()\n\"\"\"\n\uc774\ub807\uac8c \ub9cc\ub4e0 \ub370\uc774\ud130\ub97c data_all\uacfc \ud569\uce69\ub2c8\ub2e4.\n\"\"\"\ndata_all = pd.merge(data_all, family_survival, on=['last_name_family_size','family_size'], how='left')\ndata_all = data_all.sort_values('PassengerId').reset_index(drop=True)\ndata_all = pd.merge(data_all, family_ticket_survival, on=['last_name','Ticket'], how='left')\ndata_all = data_all.sort_values('PassengerId').reset_index(drop=True)\n\"\"\"\n\uc774\ub807\uac8c \ub9cc\ub4e0 feature\uc640 Survived\uc758 \uad00\uacc4\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\uadf8\ub798\ud504\ub97c \ubcf4\uba74 \uac12\uc774 1\uc77c \ub54c family_ticket_survival\uc774 \uc0b4\uc544\ub0a8\uc740 \uc0ac\ub78c\uc758 \ube44\uc728\uc774 \ub354 \ub192\uc740 \uac78 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'family_survival')\nplot_by_target(data_all, 'family_ticket_survival')\n\"\"\"\nFamily Size\uc640 \ub9c8\ucc2c\uac00\uc9c0\ub85c Family Ticket Count\ub3c4 binning \ucc98\ub9ac\ub97c \ud574\uc11c feature\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all[data_all.family_ticket_count <= 2], 'family_ticket_count', col_wrap=4)\nplot_by_target(data_all[data_all.family_ticket_count > 2], 'family_ticket_count')\ndef calc_family_ticket_count_bin(family_ticket_count):\n    if family_ticket_count == 1:\n        return 0\n    elif family_ticket_count <= 4: \n        return 1\n    else:\n        return 2\n        \ndata_all['family_ticket_count_bin'] = data_all.family_ticket_count.map(calc_family_ticket_count_bin)\n\"\"\"\nfamily_ticket_count_bin feature\uc640 Survived\uc640\uc758 \ubd84\ud3ec\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'family_ticket_count_bin')\ndata_all.info()\n\"\"\"\n\uccab \ubc88\uc9f8 Feature Engineering\uc744 \ud1b5\ud574 \ub9cc\ub4e0 feature\ub97c \ucd94\uac00\ud574\uc11c Train, Test \ub370\uc774\ud130\ub97c \ub9cc\ub4ed\ub2c8\ub2e4. \n\"\"\"\nfe_1_features = [\n    'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', \n    'family_size', 'family_size_bin', 'name_title_cat', \n    'last_name_family_size', 'last_name_ticket',\n    'family_survival', 'family_ticket_survival',\n    'family_ticket_count', 'family_ticket_count_bin'\n]\n\n# label encoding\nle = LabelEncoder()\n\ndata_all.name_title_cat = le.fit_transform(data_all[['name_title_cat']])\ndata_all.last_name_family_size = le.fit_transform(data_all[['last_name_family_size']])\ndata_all.last_name_ticket = le.fit_transform(data_all[['last_name_ticket']])\n\nX_train = data_all[data_all.train == 1][fe_1_features]\nX_test = data_all[data_all.train == 0][fe_1_features]\n\nprint(f'X_train shape : {X_train.shape}, X_test shape : {X_test.shape}')\n\"\"\"\nXGBoost\ub97c \uae30\ubcf8 \uba38\uc2e0 \ub7ec\ub2dd \ubaa8\ub378\ub85c \ud574\uc11c Cross Validation \uacb0\uacfc\uc640 Feature Engineering\uc744 \ud1b5\ud55c \ubaa8\ub378 \uc131\ub2a5 \ubc0f Feature Importance \ud655\uc778, Test \ub370\uc774\ud130\ub97c \uc608\uce21\ud574\uc11c Submit\ud560 \uacb0\uacfc \ud30c\uc77c\uae4c\uc9c0 \uc0dd\uc131\ud558\ub294 function\uc744 \uc815\uc758\ud569\ub2c8\ub2e4.\n\"\"\"\ndef make_prediction(train, target, test, features, model_name, model_results=None,\n                    model=xgb.XGBClassifier(random_state=RANDOM_SEED)):\n    model_results, model = cv_model(train, target, model, \n                                         model_name, model_results)\n\n    show_model_results(model_results)\n    fi = plot_feature_importances(model, features)\n    display(fi)\n    \n    model.fit(train, target)\n    pred = model.predict(test)\n\n    output = f'{model_name}_submission_{datetime.now().strftime(\"%Y%m%d%H%M%S\")}.csv'\n    submit_df = pd.DataFrame()\n    submit_df['PassengerId'] = test_raw.PassengerId\n    submit_df['Survived'] = pred\n    \n    submit_df[['PassengerId','Survived']].to_csv(output, index=False)\n    print(f'submission file {output} is generated.')\n    \n    return model_results\n\"\"\"\nBaseline \ubaa8\ub378\uc5d0 \ube44\ud574 CV \uc131\ub2a5\uc774 \uc62c\ub77c\uac00\uace0 \uc0c8\ub86d\uac8c \ub9cc\ub4e0 feature\ub4e4\uc774 \uc911\uc694\ud55c \uc5ed\ud560\uc744 \ud55c \uac78 \ud655\uc778\ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nmodel_results = make_prediction(X_train, y_train, X_test, fe_1_features, 'XGB_FE_1', model_results)\n\"\"\"\n\ub370\uc774\ud130\ub97c \ubcf4\uba74 Ticket\uc774 \ub3d9\uc77c\ud55c \uc0ac\ub78c\uc758 Fare\uac00 \uac19\uc740 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4. Ticket\uc744 \uac19\uc774 \uad6c\ub9e4\ud55c \uc0ac\ub78c\uc758 Fare\ub97c \ub3d9\uc77c\ud558\uac8c \uae30\ub85d\ud55c \uac78\ub85c \uc608\uc0c1\ub418\ub2c8, \uac1c\uc778\ubcc4 Fare\ub97c \uacc4\uc0b0\ud558\uae30 \uc704\ud574 Fare\ub97c Ticket Count\ub85c \ub098\ub220\uc11c \uc0c8\ub85c\uc6b4 feature\ub97c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndata_all['fare_fixed'] = data_all.Fare\/data_all.ticket_count\ndata_all[['Ticket','Fare','fare_fixed','ticket_count','Pclass']][data_all.ticket_count > 1].sort_values('Ticket').head(6)\n\"\"\"\nfare_fixed\uc758 \uacb0\uce21\uce58\uc5d0 \ub300\ud574 Median \uac12\uc73c\ub85c \ucc44\uc6c1\ub2c8\ub2e4.\n\"\"\"\nfare_median = data_all.fare_fixed.median()\ndata_all['fare_fixed'] = data_all.fare_fixed.fillna(fare_median)\n\"\"\"\nSurvived\uc5d0 \ub530\ub978 fare_fixed\uc758 \ubd84\ud3ec\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n\"\"\"\nplot_distribution_by_target(data_all, 'fare_fixed')\n\"\"\"\n\uc815\uaddc \ubd84\ud3ec \uace1\uc120\uc744 \ub530\ub974\ub3c4\ub85d fare_fixed\uc5d0 \ub85c\uadf8\ub97c \ucde8\ud558\uace0 \ubd84\ud3ec\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n\"\"\"\ndata_all['fare_fixed_log'] = np.log1p(data_all.fare_fixed)\nplot_distribution_by_target(data_all, 'fare_fixed_log')\n\"\"\"\n\ub370\uc774\ud130 \uc911\uc5d0 Age\uac00 \uc911\uc694\ud55c feature\uc778\ub370 200\uac1c\uac00 \ub118\ub294 \uacb0\uce21\uce58\uac00 \uc788\uc2b5\ub2c8\ub2e4. \uacb0\uce21\uce58\ub97c \uba54\uafb8\uae30 \uc704\ud574 \ub2e8\uc21c\ud788 \uc804\uccb4 Median\uc73c\ub85c \ucc44\uc6b0\ub294 \uac83\uc774 \uc544\ub2cc \uc131\ubcc4\uacfc Title\ubcc4 Median \uac12\uc744 \uad6c\ud574 \ud574\ub2f9 \uac12\uc73c\ub85c \ucc44\uc6b0\uaca0\uc2b5\ub2c8\ub2e4.\n\"\"\"\nage_median_by_sex_title = data_all.groupby(['Sex', 'name_title'], as_index=False).Age.median()\nage_median_by_sex_title\ndata_all = pd.merge(data_all, age_median_by_sex_title, on=['Sex', 'name_title'])\ndata_all['Age'] = data_all.apply(lambda row: row.Age_x if not np.isnan(row.Age_x) else row.Age_y, axis=1)\ndata_all = data_all.drop(['Age_x','Age_y'], axis=1).sort_values('PassengerId').reset_index(drop=True)\ndata_all.info()\n\"\"\"\nSurvived\uc5d0 \ub530\ub978 Age\uc758 \ubd84\ud3ec\ub97c \ud655\uc778\ud558\uace0, binning \ucc98\ub9ac\ub97c \ud574\uc11c feature\ub97c \ub9cc\ub4ed\ub2c8\ub2e4. \n\"\"\"\nplot_distribution_by_target(data_all, 'Age')\ndef calc_age_bin(age):\n    if age <= 15:\n        return 0\n    elif age <= 30:\n        return 1\n    elif age <= 60:\n        return 2\n    else:\n        return 3\n        \ndata_all['age_bin'] = data_all.Age.map(calc_age_bin)\n\"\"\"\n\ub450 \ubc88\uc9f8 Feature Engineering\uc744 \ud1b5\ud574 \ub9cc\ub4e0 feature\ub97c \ucd94\uac00\ud574\uc11c Train, Test \ub370\uc774\ud130\ub97c \ub9cc\ub4ed\ub2c8\ub2e4. \n\"\"\"\nfe_2_features = [\n    'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', \n    'family_size', 'family_size_bin', 'name_title_cat', \n    'last_name_family_size', 'last_name_ticket',\n    'family_survival', 'family_ticket_survival',\n    'family_ticket_count', 'family_ticket_count_bin',\n    'fare_fixed_log', 'age_bin',\n]\n\n\nX_train = data_all[data_all.train == 1][fe_2_features]\nX_test = data_all[data_all.train == 0][fe_2_features]\n\nprint(f'X_train shape : {X_train.shape}, X_test shape : {X_test.shape}')\n\"\"\"\n\ubaa8\ub378\uc758 CV \uc131\ub2a5\uacfc Feature Importance\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\nmodel_results = make_prediction(X_train, y_train, X_test, fe_2_features, 'XGB_FE_2', model_results)\n\"\"\"\nTicket \ub370\uc774\ud130\ub97c \ubcf4\uba74 \ub300\ubd80\ubd84 \uc22b\uc790\ub85c \ub418\uc5b4 \uc788\uc9c0\ub9cc \ubb38\uc790\uc640 \uc22b\uc790\uc758 \uc870\ud569\uc73c\ub85c \ub41c Ticket\ub3c4 \uc788\uc2b5\ub2c8\ub2e4. Ticket \ubb38\uc790\uc5f4\uc744 Feature\ub85c \uc0ac\uc6a9\ud558\uae30 \uc704\ud574 \ud30c\uc2f1\ud569\ub2c8\ub2e4.\n\"\"\"\ndef parse_ticket_str(ticket):\n    arr = ticket.split()\n    if not arr[0].isdigit():\n        txt = arr[0].replace('.', '')\n        txt = txt.split('\/')[0]\n        return re.findall('[a-zA-Z]+', txt)[0]\n    else:\n        return None\n        \ndata_all['ticket_str'] = data_all.Ticket.map(parse_ticket_str)\n\"\"\"\nticket_str feature\uc640 Survived\uac04\uc758 \ubd84\ud3ec\ub97c \ud655\uc778\ud569\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'ticket_str')\n\"\"\"\n\ub370\uc774\ud130\ub97c \uc880 \ub354 \uc790\uc138\ud788 \ubcf4\uae30\uc704\ud574 ticket_str, Survived\ubcc4\ub85c Pclass, fare_fixed_log\uc758 \uad00\uacc4\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4. \n\"\"\"\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_str\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\n\"\"\"\nTicket\uc758 \ubb38\uc790\uc5f4\uc744 \ucc98\ub9ac\ud588\uc73c\ub2c8 \uc774\uc81c Ticket\uc758 \uc22b\uc790 \ubd80\ubd84\uc744 \ubf51\uc544\uc11c feature\ub85c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndef parse_ticket_number(ticket):\n    arr = ticket.split()\n    if len(arr) == 1 and arr[0].isdigit():\n        return int(arr[0])\n    elif len(arr) == 2 and arr[1].isdigit():\n        return int(arr[1])\n    else:\n        if arr[-1].isdigit():\n            return int(arr[-1])\n        else:\n            return np.nan\n    \ndata_all['ticket_number'] = data_all.Ticket.map(parse_ticket_number)\n\"\"\"\nTicket\uc758 \uc22b\uc790 \uc790\ub9ac\uc218\uc5d0 \ub530\ub77c \uc0dd\uc874\uc728\uc774 \ub2e4\ub974\uc9c0 \uc54a\uc744\uae4c \ud558\ub294 \uac00\uc815\uc744 \ud574\uc11c \uc790\ub9ac\uc218\ub3c4 feature\ub85c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndef parse_ticket_num_len(ticket):\n    arr = ticket.split()\n    if len(arr) == 1 and arr[0].isdigit():\n        return len(arr[0])\n    elif len(arr) == 2 and arr[1].isdigit():\n        return len(arr[1])\n    else:\n        if arr[-1].isdigit():\n            return len(arr[-1])\n        else:\n            return -1\n    \ndata_all['ticket_num_len'] = data_all.Ticket.map(parse_ticket_num_len)\n\"\"\"\nTicket \uc22b\uc790 \uc790\ub9ac\uc218\uc5d0 \ub530\ub978 Survived\uc758 \ubd84\ud3ec\ub97c \ubcf4\uba74 \ub2e4\uc12f\uc790\ub9ac \uc22b\uc790\uc758 Ticket\uc774 \uc0dd\uc874\uc728\uc774 \ub192\uc740 \uac83\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all, 'ticket_num_len')\n\"\"\"\nTicket \uc22b\uc790 \uc790\ub9ac\uc218\uc640 fare_fixed_log, Pclass\uc758 \uad00\uacc4\ub97c \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n\"\"\"\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\n\"\"\"\nTicket \uc22b\uc790 \uc55e\uc790\ub9ac\uc218\uc5d0 \ub530\ub77c \uc2b9\uac1d\uc758 \uc790\ub9ac\uac00 \uacb0\uc815\ub418\uc9c0 \uc54a\uc744\uae4c \ud558\ub294 \uac00\uc815\uc5d0 \uc790\ub9ac\uc218\ub3c4 feature\ub85c \ub9cc\ub4e4\uc5b4\ubd05\ub2c8\ub2e4.\n\ub370\uc774\ud130\uac00 \uac00\uc7a5 \ub9ce\uc740 4, 5, 6 \uae38\uc774\uc758 Ticket\uc758 \uc55e\uc790\ub9ac\uc218\ub97c \uc0ac\uc6a9\ud569\ub2c8\ub2e4.\n\n4, 5 \uae38\uc774\ub294 \ub450 \ubc88\uc9f8 \uc55e\uc790\ub9ac\uae4c\uc9c0, 6 \uc790\ub9ac \uae38\uc774\ub294 \uc138 \ubc88\uc9f8 \uc55e\uc790\ub9ac\uae4c\uc9c0 feature\ub85c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndata_all['ticket_num_len_4_prefix'] = data_all[data_all.ticket_num_len == 4].ticket_number.map(lambda x: int(str(x)[0]))\nplot_by_target(data_all, 'ticket_num_len_4_prefix', col_wrap=3)\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_4_prefix\", hue='Survived',\n                col_wrap=3, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_4_prefix_2'] = data_all[data_all.ticket_num_len == 4].ticket_number.map(lambda x: int(str(x)[:2]))\nplot_by_target(data_all, 'ticket_num_len_4_prefix_2')\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_4_prefix_2\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_5_prefix'] = data_all[data_all.ticket_num_len == 5].ticket_number.map(lambda x: int(str(x)[0]))\nplot_by_target(data_all, 'ticket_num_len_5_prefix', col_wrap=3)\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_5_prefix\", hue='Survived',\n                col_wrap=3, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_5_prefix_2'] = data_all[data_all.ticket_num_len == 5].ticket_number.map(lambda x: int(str(x)[:2]))\nplot_by_target(data_all, 'ticket_num_len_5_prefix_2')\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_5_prefix_2\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_6_prefix'] = data_all[data_all.ticket_num_len == 6].ticket_number.map(lambda x: int(str(x)[0]))\nplot_by_target(data_all, 'ticket_num_len_6_prefix', col_wrap=3)\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_6_prefix\", hue='Survived',\n                col_wrap=3, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_6_prefix_2'] = data_all[data_all.ticket_num_len == 6].ticket_number.map(lambda x: int(str(x)[:2]))\nplot_by_target(data_all, 'ticket_num_len_6_prefix_2')\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_6_prefix_2\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\ndata_all['ticket_num_len_6_prefix_3'] = data_all[data_all.ticket_num_len == 6].ticket_number.map(lambda x: int(str(x)[:3]))\nplot_by_target(data_all, 'ticket_num_len_6_prefix_3', col_wrap=5)\ng = sns.catplot(x=\"Pclass\", y=\"fare_fixed_log\", col=\"ticket_num_len_6_prefix_3\", hue='Survived',\n                col_wrap=4, data=data_all, kind=\"strip\")\nplt.show()\ndata_all[data_all.ticket_num_len_6_prefix == 1].groupby(['ticket_num_len_6_prefix_3','train'])[['PassengerId','Survived']].agg(['mean','count'])\ndata_all[data_all.ticket_num_len_6_prefix == 3].groupby(['ticket_num_len_6_prefix_3','train'])[['PassengerId','Survived']].agg(['mean','count'])\n\"\"\"\n\uc704\uc758 \ub370\uc774\ud130\ub97c \ubcf4\uba74 \uc22b\uc790 6\uc790\ub9ac Ticket\uc740 \uc55e\uc790\ub9ac\uac00 1\uc740 1\ub4f1\uc11d, 2\ub294 2\ub4f1\uc11d, 3\uc740 3\ub4f1\uc11d\uc784\uc744 \uc54c \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n1\ub4f1\uc11d \uc2b9\uac1d\uc774 \uac00\uc7a5 \ub9ce\uc774 \uc0b4\uc544\ub0a8\uace0, 3\ub4f1\uc11d \uc2b9\uac1d\uc774 \uac00\uc7a5 \ub9ce\uc774 \uc8fd\uc740 \uac83\uc744 \uc54c\uace0 \uc788\ub294\ub370\uc694.\n\uc704\uc758 \ub370\uc774\ud130\uc5d0\uc11c \uc22b\uc790 6\uc790\ub9ac Ticket \uc55e\uc790\ub9ac 3\uac1c\ub97c \ubcf4\uba74 1\ub4f1\uc11d\uc784\uc5d0\ub3c4 \uc2b9\uac1d\uc774 \ub9ce\uc774 \uc8fd\uc740 \uc790\ub9ac\uc218\uac00 \uc788\uace0 3\ub4f1\uc11d\uc784\uc5d0\ub3c4 \uc2b9\uac1d\uc774 \ub9ce\uc774 \uc0b4\uc544\ub0a8\uc740 \uc790\ub9ac\uc218\uac00 \uc788\uc5b4\uc11c \uc758\ubbf8\uc788\ub294 feature\uac00 \ub418\uc9c0 \uc54a\uc744\uae4c \uc608\uc0c1\ub429\ub2c8\ub2e4.\n\"\"\"\ndata_all.info()\n\"\"\"\n\uc138 \ubc88\uc9f8 Feature Engineering\uc744 \ud1b5\ud574 \ub9cc\ub4e0 feature\ub97c \ucd94\uac00\ud574\uc11c Train, Test \ub370\uc774\ud130\ub97c \ub9cc\ub4ed\ub2c8\ub2e4. \n\"\"\"\nfe_3_features = [\n    'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', \n    'family_size', 'family_size_bin', 'name_title_cat', \n    'last_name_family_size', 'last_name_ticket',\n    'family_survival', 'family_ticket_survival',\n    'family_ticket_count', 'family_ticket_count_bin',\n    'fare_fixed_log', 'age_bin',\n    'ticket_str', 'ticket_num_len',\n    'ticket_num_len_4_prefix', 'ticket_num_len_4_prefix_2',\n    'ticket_num_len_5_prefix', 'ticket_num_len_5_prefix_2',\n    'ticket_num_len_6_prefix', 'ticket_num_len_6_prefix_2', 'ticket_num_len_6_prefix_3',\n]\n\n# fill missing values\ndata_all.ticket_str = data_all.ticket_str.fillna('X')\n\ndata_all.ticket_num_len_4_prefix = data_all.ticket_num_len_4_prefix.fillna(-1)\ndata_all.ticket_num_len_4_prefix_2 = data_all.ticket_num_len_4_prefix_2.fillna(-1)\ndata_all.ticket_num_len_5_prefix = data_all.ticket_num_len_5_prefix.fillna(-1)\ndata_all.ticket_num_len_5_prefix_2 = data_all.ticket_num_len_5_prefix_2.fillna(-1)\ndata_all.ticket_num_len_6_prefix = data_all.ticket_num_len_6_prefix.fillna(-1)\ndata_all.ticket_num_len_6_prefix_2 = data_all.ticket_num_len_6_prefix_2.fillna(-1)\ndata_all.ticket_num_len_6_prefix_3 = data_all.ticket_num_len_6_prefix_3.fillna(-1)\n\ndata_all.ticket_num_len_4_prefix = data_all.ticket_num_len_4_prefix.astype(int)\ndata_all.ticket_num_len_4_prefix_2 = data_all.ticket_num_len_4_prefix_2.astype(int)\ndata_all.ticket_num_len_5_prefix = data_all.ticket_num_len_5_prefix.astype(int)\ndata_all.ticket_num_len_5_prefix_2 = data_all.ticket_num_len_5_prefix_2.astype(int)\ndata_all.ticket_num_len_6_prefix = data_all.ticket_num_len_6_prefix.astype(int)\ndata_all.ticket_num_len_6_prefix_2 = data_all.ticket_num_len_6_prefix_2.astype(int)\ndata_all.ticket_num_len_6_prefix_3 = data_all.ticket_num_len_6_prefix_3.astype(int)\n\n# label encoding\nle = LabelEncoder()\n\ndata_all.ticket_str = le.fit_transform(data_all[['ticket_str']])\n\nX_train = data_all[data_all.train == 1][fe_3_features]\nX_test = data_all[data_all.train == 0][fe_3_features]\n\nprint(f'X_train shape : {X_train.shape}, X_test shape : {X_test.shape}')\n\"\"\"\n\ubaa8\ub378\uc758 CV \uc131\ub2a5\uacfc Feature Importance\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\nmodel_results = make_prediction(X_train, y_train, X_test, fe_3_features, 'XGB_FE_3', model_results)\n\"\"\"\n\ub9c8\uc9c0\ub9c9\uc73c\ub85c Cabin \ub370\uc774\ud130\ub97c \ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n\"\"\"\ndata_all.Cabin.sort_values().unique()\n\"\"\"\nCabin \ubb38\uc790\uc5f4\uc5d0\uc11c \uccab \uae00\uc790\ub97c \ubf51\uc544\ub0b4\uc11c feature\ub85c \uc4f8 \uc218 \uc788\uc744 \uac83 \uac19\uc2b5\ub2c8\ub2e4. \uacb0\uce21\uce58\ub294 X\ub85c \ucc44\uc6b0\uace0 \uccab \uae00\uc790\ub97c feature\ub85c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndata_all['cabin_cat'] = data_all.Cabin.fillna('X').str[0]\n\"\"\"\n\uacb0\uce21\uce58\ub97c \uc81c\uc678\ud55c \ub370\uc774\ud130\uc758 Survived\uc5d0 \ub530\ub978 \ubd84\ud3ec\ub97c \ubd05\ub2c8\ub2e4. \ub300\ubd80\ubd84 \uc0dd\uc874\uc790 \ube44\uc728\uc774 \ub354 \ub192\uc740 \uac83\uc744 \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplot_by_target(data_all[~data_all.cabin_cat.isin(['X'])], 'cabin_cat')\n\"\"\"\n\ub610, Cabin \ub370\uc774\ud130\ub97c \ubcf4\uba74 \uacf5\ubc31\uc73c\ub85c \uad6c\ubd84\ub41c \ubb38\uc790\uc5f4\uc774 \uc788\ub294 \uac78\ub85c \ubd10\uc11c Cabin\uc744 \ub450 \uac1c \uc774\uc0c1 \uc0ac\uc6a9\ud55c \uc2b9\uac1d\ub3c4 \uc788\ub294 \uac83\uc73c\ub85c \ubcf4\uc785\ub2c8\ub2e4. \uc774\uac83\ub3c4 feature\ub85c \ub9cc\ub4ed\ub2c8\ub2e4.\n\"\"\"\ndef calc_cabin_len(cabin):\n    if type(cabin) == float:\n        return 0\n    else:\n        return len(cabin.split())\n\ndata_all['cabin_len'] = data_all.Cabin.map(calc_cabin_len)\nplot_by_target(data_all[data_all.cabin_len > 0], 'cabin_len')\n\"\"\"\n\ub124 \ubc88\uc9f8 Feature Engineering\uc744 \ud1b5\ud574 \ub9cc\ub4e0 feature\ub97c \ucd94\uac00\ud574\uc11c Train, Test \ub370\uc774\ud130\ub97c \ub9cc\ub4ed\ub2c8\ub2e4. \n\"\"\"\nfe_4_features = [\n    'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', \n    'family_size', 'family_size_bin', 'name_title_cat', \n    'last_name_family_size', 'last_name_ticket',\n    'family_survival', 'family_ticket_survival',\n    'family_ticket_count', 'family_ticket_count_bin',\n    'fare_fixed_log', 'age_bin',\n    'ticket_str', 'ticket_num_len',\n    'ticket_num_len_4_prefix', 'ticket_num_len_4_prefix_2',\n    'ticket_num_len_5_prefix', 'ticket_num_len_5_prefix_2',\n    'ticket_num_len_6_prefix', 'ticket_num_len_6_prefix_2', 'ticket_num_len_6_prefix_3',\n    'cabin_cat', 'cabin_len',\n]\n\n# label encoding\nle = LabelEncoder()\n\ndata_all.cabin_cat = le.fit_transform(data_all[['cabin_cat']])\n\nX_train = data_all[data_all.train == 1][fe_4_features]\nX_test = data_all[data_all.train == 0][fe_4_features]\n\nprint(f'X_train shape : {X_train.shape}, X_test shape : {X_test.shape}')\n\"\"\"\n\ubaa8\ub378\uc758 CV \uc131\ub2a5\uacfc Feature Importance\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\nmodel_results = make_prediction(X_train, y_train, X_test, fe_4_features, 'XGB_FE_4', model_results)\ndef plot_correlation_heatmap(df, variables):\n    # Calculate the correlations\n    corr_mat = df[variables].corr().round(2)\n\n    # Draw a correlation heatmap\n    plt.figure(figsize = (18, 16))\n    sns.heatmap(corr_mat, vmin=-0.6, vmax=0.6, center=0, cmap='viridis', annot=True)\n    plt.title('Feature Correlation Heatmap\\n')\n    plt.show()\n\"\"\"\n\uc9c0\uae08\uae4c\uc9c0 \ub9cc\ub4e0 feature\ub4e4\uacfc target feature\uc778 Survived feature \uac04\uc758 correlation\uacfc feature\ub4e4 \uac04\uc758 correlation\uc744 \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\nfeature\uc758 \uc911\uc694\uc131\uc744 \uc54c \uc218 \uc788\uace0, feature\ub4e4 \uac04\uc758 correlation\uc774 \uc9c0\ub098\uce58\uac8c \ub192\uc740 feature\ub4e4\uc740 \uc911\ubcf5\ub41c feature\ub77c \uc0ad\uc81c\ud574\uc57c \ud560 feature\ub85c \ubcfc \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\"\"\"\nplot_correlation_heatmap(data_all[data_all.train == 1], ['Survived'] + list(fe_4_features))\n\"\"\"\nCorrelation\uc774 \ub192\uc544 \uc911\ubcf5\ub41c feature\ub97c \uc815\ub9ac\ud55c \ud6c4 \ucd5c\uc885 \uc0ac\uc6a9\ud560 feature\ub4e4\uc758 correlation\uc744 \ub2e4\uc2dc \ubd05\ub2c8\ub2e4.\n\"\"\"\nfe_4_sel_features = [\n    'Pclass', 'Sex', 'Age', \n    'family_size_bin',\n    'name_title_cat', \n    'last_name_family_size',\n    'last_name_ticket',\n    'family_ticket_survival',\n    'fare_fixed_log',\n    'ticket_str',\n    'ticket_num_len_4_prefix_2',\n    'ticket_num_len_5_prefix_2',\n    'ticket_num_len_6_prefix_3',\n]\n\nplot_correlation_heatmap(data_all, ['Survived'] + list(fe_4_sel_features))\n\"\"\"\n\ucd5c\uc885 \uc120\ud0dd\ub41c feature\ub4e4\ub85c Train, Test \ub370\uc774\ud130\ub97c \ub9cc\ub4e4\uace0, \ubaa8\ub378\uc758 CV \uc131\ub2a5\uacfc Feature Importance\ub97c \ud655\uc778\ud574\ubd05\ub2c8\ub2e4.\n\"\"\"\nX_train = data_all[data_all.train == 1][fe_4_sel_features]\nX_test = data_all[data_all.train == 0][fe_4_sel_features]\n\nprint(f'X_train shape : {X_train.shape}, X_test shape : {X_test.shape}')\n\nmodel_results = make_prediction(X_train, y_train, X_test, fe_4_sel_features, 'XGB_FE_4_SEL', \n                                model_results=model_results)","meta":"{'source': 'AI4Code', 'id': '6b9ef2f62e3c24'}"}
{"id":"55179","text":"\"\"\"\nHello, it is my test notebook. Simple visualisation how law of large numbers works for beginners :)\n\nThe law of large numbers states that an observed sample average from a large sample will be close to the true population average and that it will get closer the larger the sample.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_style(\"darkgrid\")\n\"\"\"\nLet us create a dice with Pandas\n\"\"\"\ndice = pd.Series([1, 2, 3, 4, 5, 6])\ndice.to_frame()\n\"\"\"\nAnd now we can find `mean` of our dice\n\"\"\"\nprint('Avg of our dice is:', dice.mean())\ndef monte_carlo(series_list, n):\n    result = []\n    for i in range(1,n):\n        result.append(series_list.sample(i, replace=True).mean())\n    pd.Series(result).plot()\n    plt.show()\n    print('Avg of our dice is:', sum(result) \/ len(result))\n\"\"\"\nFor five rolls avg looks like that:\n\"\"\"\nmonte_carlo(dice, 5)\n\"\"\"\nLet us do more rolls\n\"\"\"\nmonte_carlo(dice, 10)\n\"\"\"\nAnd more!\n\"\"\"\nmonte_carlo(dice, 100)\nmonte_carlo(dice, 1000)\n\"\"\"\nAnd if we roll dice 10 000 times - the avg is almost equally to the true avg - 3.5\n\"\"\"\nmonte_carlo(dice, 10000)\n\"\"\"\nThe result becomes closer to the expected value as the number of trials is increased. Thus, I understood how it works. Very good mentor explained to me it in this way, maybe it will be useful to someone\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '65b0b3e337c39d'}"}
{"id":"109334","text":"# 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\n\"\"\"\n# Ulaanbaatar air quality data visualization analysis\n\"\"\"\n\"\"\"\n### About Ulaanbaatar\n\nUlaanbaatar, the capital city of Mongolia, is one of the coldest and most polluted capitals during winter times. Despite the vast territory of Mongolia, 1.5 million people - half of the population - live in a small capital city which was designed for a population of only 400000. Air pollution in Ulaanbaatar reaches to hazardous level during the winter when residents in \"ger\" district start using coal-burning stove as a heater. \n\"\"\"\n\"\"\"\n\n![Ger District](https:\/\/www.ccacoalition.org\/sites\/default\/files\/styles\/half_content_width\/public\/18262091_304.jpg?itok=AicjmQ1j&timestamp=1584443528)\n\"\"\"\n\"\"\"\n### Ban of raw coal\n\nOn 15th of May, 2019, the Government of Mongolia banned the consumption of raw coal and introduced \"refined coal briquettes\" in response to fighting the air pollution. Since the start of this policy, the smog in Ulaanbaatar city noticably decreased. Even the smog seemed to be partly disappeared visually since the ban of raw coal, it's important to check whether the actual particulate matter in the air decreased. Thus, this data visualization will mostly focus on how the ban on raw coal changed the air quality. \n\n![Refined Coal](https:\/\/scx2.b-cdn.net\/gfx\/news\/2019\/ulaanbaatari.jpg)\n\"\"\"\n\"\"\"\n### PM2.5 AND PM10\n\nParticulate matter(PM) is a mixture of many harmful solid particles and liquid droplets in the air such as soot, smoke, metals, nitrates, sulphates, dust water and rubber etc. PM2.5 refers to the atmospheric particulate matter that has a diameter of less than 2.5 micrometres, which is about 3% of the diameter of human hair. PM10 are the particles with a diameter of 10 micrometers and they are also called fine particles. The air is considered safe to breathe when the quantity of PM2.5 in the air is 60 and PM10 is 100.\n\nNote: Various studies show that PM2.5 has more severe health effects than PM10 as PM2.5 particles are so small that they can get deep into the lungs and bloodstream whereas PM10 particles can only pass through the throat, nose and surface of lung in the short term.\n\n\n\n\"\"\"\n\"\"\"\n### Data\nData from air quality monitors in Ulaanbaatar is used in this notebook.\n**Location of air quality monitors in Ulaanbaatar are shown on a map below.**\n\"\"\"\n\"\"\"\n![Location of air quality monitors on a map.png](attachment:35df2bd3-d2d2-47e3-97f0-148d8506d1a1.png)\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n#loading datasets\nam = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/amgalan-ulaanbaatar-air-quality.csv\")\nto = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/tolgoit-ulaanbaatar-air-quality.csv\")\nmi = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/misheel-expo ulaanbaatar-air-quality.csv\")\nbh = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/bayankhoshuu-ulaanbaatar-air-quality.csv\")\nni = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/nisekh-ulaanbaatar-air-quality.csv\")\nus = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/ulaanbaatar-us embassy-air-quality.csv\")\nmnb = pd.read_csv(\"..\/input\/ulaanbaatar-air-quality\/m.n.b.-ulaanbaatar-air-quality.csv\")\nam.info()\n\"\"\"\nQuick observation: These monitors started recording data at different times, and there are approximately 5 to 7 years of data(looking at the row number). Unfortunately, some monitors do not record certain type of air quality. \n\"\"\"\n#Converting data type of date (object to datetime)\nam['date'] = pd.to_datetime(am['date'])\nbh['date'] = pd.to_datetime(bh['date'])\nmnb['date'] = pd.to_datetime(mnb['date'])\nmi['date'] = pd.to_datetime(mi['date'])\nni['date'] = pd.to_datetime(ni['date'])\nto['date'] = pd.to_datetime(to['date'])\nus['date'] = pd.to_datetime(us['date'])\n\n\n#Removing space from column names\nam.columns = am.columns.str.replace(' ','')\nam = am.sort_values(by = 'date', ascending = False)\n#Converting data type of columns except date\ncols_to_convert_am = am.columns.drop('date')\nam[cols_to_convert_am] = am[cols_to_convert_am].apply(pd.to_numeric, errors='coerce')\n#Doing same data cleaning for other data sets\n#Bayankhoshuu\nbh.columns = bh.columns.str.replace(' ','')\nbh = bh.sort_values(by = 'date', ascending = False)\ncols_to_convert_bh = bh.columns.drop('date')\nbh[cols_to_convert_bh] = bh[cols_to_convert_bh].apply(pd.to_numeric, errors='coerce')\n#MNB\nmnb.columns = mnb.columns.str.replace(' ','')\nmnb = mnb.sort_values(by = 'date', ascending = False)\ncols_to_convert_mnb = mnb.columns.drop('date')\nmnb[cols_to_convert_mnb] = mnb[cols_to_convert_mnb].apply(pd.to_numeric, errors='coerce')\n#Misheel expo\nmi.columns = mi.columns.str.replace(' ','')\nmi = mi.sort_values(by = 'date', ascending = False)\ncols_to_convert_mi = mi.columns.drop('date')\nmi[cols_to_convert_mi] = mi[cols_to_convert_mi].apply(pd.to_numeric, errors='coerce')\n#Nisekh\nni.columns = ni.columns.str.replace(' ','')\nni = ni.sort_values(by = 'date', ascending = False)\ncols_to_convert_ni = ni.columns.drop('date')\nni[cols_to_convert_ni] = ni[cols_to_convert_ni].apply(pd.to_numeric, errors='coerce')\n#Tolgoit\nto.columns = to.columns.str.replace(' ','')\nto = to.sort_values(by = 'date', ascending = False)\ncols_to_convert_to = to.columns.drop('date')\nto[cols_to_convert_to] = to[cols_to_convert_to].apply(pd.to_numeric, errors='coerce')\n#US embassy\nus.columns = us.columns.str.replace(' ','')\nus = us.sort_values(by = 'date', ascending = False)\ncols_to_convert_us = us.columns.drop('date')\nus[cols_to_convert_us] = us[cols_to_convert_us].apply(pd.to_numeric, errors='coerce')\n\n\n\"\"\"\n### Amount of PM2.5 and PM10 over time at different locations\n#### PM2.5 health impacts are shown in the graph by colors and interpretations are shown below as a picture\n\n\n![PM levels](https:\/\/www.airveda.com\/resources\/images\/pm_levels.png)\n\"\"\"\n#MNB\nplt.figure(figsize=(40,10))\nsns.lineplot(x = 'date', y = 'pm25', data =mnb)\nsns.lineplot(x = 'date', y = 'pm10', data =mnb)\nplt.axvline(pd.Timestamp('2019-05-15'),color='r')\nplt.text(pd.Timestamp('2019-05-15'), 450, \"Government ban of raw coal comes into effect\", horizontalalignment='left', size='medium', color='red')\nplt.legend(labels=[\"PM2.5\", \"PM10\"])\nplt.xlabel(\"Date\")\nplt.ylabel(\"PM2.5 vs PM10\")\n\nplt.axhspan(0, 30, facecolor='green', alpha=0.1)\nplt.axhspan(30, 60, facecolor='lightgreen', alpha=0.1)\nplt.axhspan(60, 90, facecolor='yellow', alpha=0.1)\nplt.axhspan(90, 120, facecolor='orange', alpha=0.1)\nplt.axhspan(120, 250, facecolor='red', alpha=0.1)\nplt.axhspan(250, 500, facecolor='darkred', alpha=0.1)\n\"\"\"\nObservation: Data from MNB air quality monitor shows that the amount of 'PM10' droppped significantly since 2019. This dramatic decrease can be explained by the government ban of raw coal starting from 15th of May, 2019. \n\"\"\"\nplt.figure(figsize=(40,10))\nsns.lineplot(x = 'date', y = 'pm25', data =am)\nsns.lineplot(x = 'date', y = 'pm10', data =am)\nplt.axvline(pd.Timestamp('2019-05-15'),color='r')\nplt.text(pd.Timestamp('2019-05-15'), 350, \"Government ban of raw coal comes into effect\", horizontalalignment='left', size='medium', color='red')\nplt.legend(labels=[\"PM2.5\", \"PM10\"])\nplt.xlabel(\"Date\")\nplt.ylabel(\"PM2.5 vs PM10\")\n\nplt.axhspan(0, 30, facecolor='green', alpha=0.1)\nplt.axhspan(30, 60, facecolor='lightgreen', alpha=0.1)\nplt.axhspan(60, 90, facecolor='yellow', alpha=0.1)\nplt.axhspan(90, 120, facecolor='orange', alpha=0.1)\nplt.axhspan(120, 250, facecolor='red', alpha=0.1)\nplt.axhspan(250, 400, facecolor='darkred', alpha=0.1)\nplt.figure(figsize=(40,10))\nsns.lineplot(x = 'date', y = 'pm25', data =ni)\nsns.lineplot(x = 'date', y = 'pm10', data =ni)\nplt.axvline(pd.Timestamp('2019-05-15'),color='r')\nplt.text(pd.Timestamp('2019-05-15'), 350, \"Government ban of raw coal comes into effect\", horizontalalignment='left', size='medium', color='red')\nplt.legend(labels=[\"PM2.5\", \"PM10\"])\nplt.xlabel(\"Date\")\nplt.ylabel(\"PM2.5 vs PM10\")\n\nplt.axhspan(0, 30, facecolor='green', alpha=0.1)\nplt.axhspan(30, 60, facecolor='lightgreen', alpha=0.1)\nplt.axhspan(60, 90, facecolor='yellow', alpha=0.1)\nplt.axhspan(90, 120, facecolor='orange', alpha=0.1)\nplt.axhspan(120, 250, facecolor='red', alpha=0.1)\nplt.axhspan(250, 400, facecolor='darkred', alpha=0.1)\nplt.figure(figsize=(40,10))\nsns.lineplot(x = 'date', y = 'pm25', data =to)\nsns.lineplot(x = 'date', y = 'pm10', data =to)\nplt.axvline(pd.Timestamp('2019-05-15'),color='r')\nplt.text(pd.Timestamp('2019-05-15'), 350, \"Government ban of raw coal comes into effect\", horizontalalignment='left', size='medium', color='red')\nplt.legend(labels=[\"PM2.5\", \"PM10\"])\nplt.xlabel(\"Date\")\nplt.ylabel(\"PM2.5 vs PM10\")\n\nplt.axhspan(0, 30, facecolor='green', alpha=0.1)\nplt.axhspan(30, 60, facecolor='lightgreen', alpha=0.1)\nplt.axhspan(60, 90, facecolor='yellow', alpha=0.1)\nplt.axhspan(90, 120, facecolor='orange', alpha=0.1)\nplt.axhspan(120, 250, facecolor='red', alpha=0.1)\nplt.axhspan(250, 600, facecolor='darkred', alpha=0.1)\nplt.figure(figsize=(40,10))\nsns.lineplot(x = 'date', y = 'pm25', data =us)\nsns.lineplot(x = 'date', y = 'pm10', data =us)\nplt.axvline(pd.Timestamp('2019-05-15'),color='r')\nplt.text(pd.Timestamp('2019-05-15'), 350, \"Government ban of raw coal comes into effect\", horizontalalignment='left', size='medium', color='red')\nplt.legend(labels=[\"PM2.5\", \"PM10\"])\nplt.xlabel(\"Date\")\nplt.ylabel(\"PM2.5 vs PM10\")\n\nplt.axhspan(0, 30, facecolor='green', alpha=0.1)\nplt.axhspan(30, 60, facecolor='lightgreen', alpha=0.1)\nplt.axhspan(60, 90, facecolor='yellow', alpha=0.1)\nplt.axhspan(90, 120, facecolor='orange', alpha=0.1)\nplt.axhspan(120, 250, facecolor='red', alpha=0.1)\nplt.axhspan(250, 600, facecolor='darkred', alpha=0.1)\n\n\n\"\"\"\n# Air quality comparison by location\n\"\"\"\n#Create a new column \"year\"\nmnb['year'] = mnb.date.dt.year\nus['year'] = us.date.dt.year\nam['year'] = am.date.dt.year\nni['year'] = ni.date.dt.year\nto['year'] = us.date.dt.year\n\nfig, axes = plt.subplots(2, 5, sharey = True, figsize=(40,20))\nsns.boxplot(x = 'year', y = 'pm25', data=mnb[mnb.date >= '2016-01-01'], palette = 'pink', ax = axes[0, 0]).set_title(\"MNB\")\nsns.boxplot(x = 'year', y = 'pm25', data=us[us.date >= '2016-01-01'],palette = 'pink', ax = axes[0,1]).set_title(\"US Embassy\")\nsns.boxplot(x = 'year', y = 'pm25', data=am[am.date >= '2016-01-01'],palette = 'pink', ax = axes[0,2]).set_title(\"Amgalan\")\nsns.boxplot(x = 'year', y = 'pm25', data=ni[ni.date >= '2016-01-01'],palette = 'pink', ax = axes[0,3]).set_title(\"Nisekh\")\nsns.boxplot(x = 'year', y = 'pm25', data=to[(to.date >= '2016-01-01')&(to.pm25<500)],palette = 'pink', ax = axes[0,4]).set_title(\"Tolgoit\")\n\nsns.boxplot(x = 'year', y = 'pm10', data=mnb[mnb.date >= '2016-01-01'], palette = 'pink', ax = axes[1,0]).set_title(\"MNB\")\nsns.boxplot(x = 'year', y = 'pm10', data=us[(us.date >= '2016-01-01') & (us.pm10<500)],palette = 'pink', ax = axes[1,1]).set_title(\"US Embassy\")\nsns.boxplot(x = 'year', y = 'pm10', data=am[am.date >= '2016-01-01'],palette = 'pink', ax = axes[1,2]).set_title(\"Amgalan\")\nsns.boxplot(x = 'year', y = 'pm10', data=ni[ni.date >= '2016-01-01'],palette = 'pink', ax = axes[1,3]).set_title(\"Nisekh\")\nsns.boxplot(x = 'year', y = 'pm10', data=to[(to.date >= '2016-01-01') &(to.pm10<500)],palette = 'pink', ax = axes[1,4]).set_title(\"Tolgoit\")\n\nplt.title(\"PM2.5 and PM10 by location and year\")\n\n\n\nfig, axes = plt.subplots(2, 5, sharey = True, figsize=(40,20))\nsns.lineplot(x = 'year', y = 'pm25', data=mnb[mnb.date >= '2016-01-01'], palette = 'pink', ax = axes[0, 0]).set_title(\"MNB\")\nsns.lineplot(x = 'year', y = 'pm25', data=us[us.date >= '2016-01-01'],palette = 'pink', ax = axes[0,1]).set_title(\"US Embassy\")\nsns.lineplot(x = 'year', y = 'pm25', data=am[am.date >= '2016-01-01'],palette = 'pink', ax = axes[0,2]).set_title(\"Amgalan\")\nsns.lineplot(x = 'year', y = 'pm25', data=ni[ni.date >= '2016-01-01'],palette = 'pink', ax = axes[0,3]).set_title(\"Nisekh\")\nsns.lineplot(x = 'year', y = 'pm25', data=to[(to.date >= '2016-01-01')&(to.pm25<500)],palette = 'pink', ax = axes[0,4]).set_title(\"Tolgoit\")\n\nsns.lineplot(x = 'year', y = 'pm10', data=mnb[mnb.date >= '2016-01-01'], palette = 'pink', ax = axes[1,0]).set_title(\"MNB\")\nsns.lineplot(x = 'year', y = 'pm10', data=us[(us.date >= '2016-01-01') & (us.pm10<500)],palette = 'pink', ax = axes[1,1]).set_title(\"US Embassy\")\nsns.lineplot(x = 'year', y = 'pm10', data=am[am.date >= '2016-01-01'],palette = 'pink', ax = axes[1,2]).set_title(\"Amgalan\")\nsns.lineplot(x = 'year', y = 'pm10', data=ni[ni.date >= '2016-01-01'],palette = 'pink', ax = axes[1,3]).set_title(\"Nisekh\")\nsns.lineplot(x = 'year', y = 'pm10', data=to[(to.date >= '2016-01-01') &(to.pm10<500)],palette = 'pink', ax = axes[1,4]).set_title(\"Tolgoit\")\n\nplt.title(\"PM2.5 and PM10 by location and year\")\n\n\"\"\"\n### Observation\n\nThese graphs show that PM10 in air significantly decreased since the ban of raw coal; however, PM2.5 is not decreased as same as PM10. Amount of PM2.5 in the air still reaches to the hazardous level during winter times. \n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c8eea4484ce674'}"}
{"id":"92924","text":"\"\"\"\n![](http:\/\/m.economictimes.com\/thumb\/msid-70616931,width-3684,height-2068,resizemode-4,imgsize-550306\/stocks-market.jpg)\n\"\"\"\n\"\"\"\n## Portfolio Optimization using Monte Carlo Simulation\n\"\"\"\n\"\"\"\nHold up! This is an attempt by to explore the nuances of investment portfolio management and how can we optimize the same; after all at the end of the day we look to make more money with the stocks we have. I would urge you to watch the 2011 film \"Margin call\" to get the vitality of how portfolio mismanagement during increased volatility could kill one's investments.\n\n\n\n\n\"\"\"\n\"\"\"\nI've chosen some stocks of my interest here. Although if you feel you have different choices, you can get the historical data of the desired stocks NSE website [Link](https:\/\/www1.nseindia.com\/products\/content\/equities\/equities\/eq_security.htm) in .csv (Comma Separated Values) format. I've downloaded the data between the time range of **16th August 2019 - 14th August 2020** (not so historical!)\n\n\n\"\"\"\n\"\"\"\n## Stocks chosen \n\n1. Hindustan Unilever \n2. ITC \n3. Larson & Tourbo\n4. Nestle India\n5. Reliance  \n\nThe above chosen stocks are purely based on my preferences, feel free to explore with more and more stocks out there!\n\"\"\"\n#importing necessary libraries\nimport pandas as pd\nimport numpy as np\n%matplotlib inline \nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport seaborn as sns\nfrom collections import Counter   #An extremely useful library under itertools\nsns.set()\n#taking a gander at the files we have\nfile_dir = '..\/input\/historical-stock-data-of-select-common-stocks'\nx= !ls $file_dir\nx\n\nstock_dict={}\nstock_dict['HINDUNILVR']=pd.read_csv('..\/input\/historical-stock-data-of-select-common-stocks\/HINDUNILVR.csv')\nstock_dict['ITC']=pd.read_csv('..\/input\/historical-stock-data-of-select-common-stocks\/ITC.csv')\nstock_dict['LT']=pd.read_csv('..\/input\/historical-stock-data-of-select-common-stocks\/LT.csv')\nstock_dict['NESTLEIND']=pd.read_csv('..\/input\/historical-stock-data-of-select-common-stocks\/NESTLEIND.csv')\nstock_dict['RELIANCE']=pd.read_csv('..\/input\/historical-stock-data-of-select-common-stocks\/RELIANCE.csv')\n\n   \n\"\"\"\nOur dataset should consist only Equities, i.e. Series column equals to 'EQ'. In case if it's not the case with your dataset, try to filter out the Equity trades, as we are mainly concerned with the equity portfolio at the moment. The code for filtering out goes something like this... \n\"\"\"\n#filtering out the equities for ITC stocks\nstock_dict['ITC'][(stock_dict['ITC'].Series=='EQ')]\n\n\"\"\"\n# Note: \nBefore filtering out, you might be interested to know what are the different series apart from EQ. The code below returns the types of different types of series pertaining to each column. \n\"\"\"\nfor i in Counter(stock_dict).keys():\n    print(i,':', stock_dict[i].Series.unique())\n\n\n\"\"\"\n# Heads up!\nBL series is meant to indicate Block deals in the stock market. The criteria for a certain trade to qualify under BL is to have a minimum 500,000 shares or minimum value of Rs. 5 crore, executed through a single transaction viz the special \u201cBlock Deal window\u201d. The window is opened for only 35 minutes in the morning from 9:15 to 9:50AM. Interesting, right?\n\nCheck out this link to know more about the different series used in NSE. [Types of Series in NSE](https:\/\/help.tradesmartonline.in\/what-does-eq-and-be-series-stand-for-in-nse\/#:~:text=BL%3A%20This%20series%20is%20for,or%20minimum%20value%20of%20Rs.&text=IL%20%E2%80%93%20This%20series%20allows%20only,for%20FIIs%20is%20not%20breached.)\n\"\"\"\nfiltered_stocks={}\nfor i in Counter(stock_dict).keys():\n    filtered_stocks[i]= stock_dict[i][(stock_dict[i].Series=='EQ')].reset_index()\n\n\nfiltered_stocks.items()\n\"\"\"\n# Market capitalization\nFirst things first, let's try to calculate the market capitalization of the stocks and attach them to our dataset for ease. \n\"\"\"\n\n\nfor i in Counter(filtered_stocks).keys():\n    pd.DataFrame(filtered_stocks[i])['Market Cap']=pd.DataFrame(filtered_stocks[i])['Average Price']*pd.DataFrame(filtered_stocks[i])['Total Traded Quantity']\n    \nfiltered_stocks.items()\n\n\nfor i in Counter(filtered_stocks).keys(): \n    filtered_stocks[i].plot.line(x='Date', y='Market Cap', figsize=(20,10))\n    patch = mpatches.Patch(color='blue', label= i)\n    plt.legend(handles=[patch])\n    \n\n\"\"\"\n# Inference\n\n1. The massive surge of market capitalization between April-May 2020 of the Hindustan Unilever stocks. The reason can be attributed to the rise in the sales of essential commodities like alcohol based hand sanitizers (Lifebuoy), bathroom cleaners (Domex) and washing powder which has seen a demand shock owinig to the hygiene precautions during the pandemic. This amplified the positive sentiments towards the 'HINDUNILVR' stocks.\n2. Simlar trends can be observed with ITC's stocks. It's imperative that Hindustan Unilever and ITC are on a **'FMCG Race'**** this year, given that a major chunk of the consumer spending has been channelized into acquiring the essentials. Apart from that, a massive spike is seen in mid-October which is the market's reaction to ITC investing Rs. 700 Crores to open a food park in Madhya Pradesh. Check out this [link](https:\/\/www.itcportal.com\/media-centre\/press-reports-content.aspx?id=2189&type=C&news=itc-to-invest-700-crores-in-state-of-the-art-food-processing-facility-in-mp#:~:text=The%20ITC%20Limited%20%2D%20one%20of,processing%20facility%20in%20Madhya%20Pradesh.)\n3.  All eyes on Reliance Industries Limited, for it has become the most valuable company in India. The plethora of investments made in Reliance facilitated this mammoth growth even during hostile business conditions. Check out this [link](https:\/\/www.jagranjosh.com\/general-knowledge\/list-of-top-investors-in-reliance-jio-1594630586-1) here for better understaning.\n\n\n\"\"\"\n#How abot we take a gander at the trends in close prices \n\nfig, axes = plt.subplots(nrows=5, ncols=1) \nnum=0\nfor i in Counter(filtered_stocks).keys(): \n    filtered_stocks[i].plot(x='Date',y='Close Price', label=i, ax=axes[num], figsize=(15,15))\n    num += 1\nplt.show()\n\n\n\"\"\"\n# Inference#2 \nThe close prices of all the stocks have hit a low duting late march because of the announcement on 'Nationwide lockdown' made by our honourable Prime Minister on March 24, 2020. Negative business sentiments certainly caused the NSE to tank almost 25% in March, 2020. \nA gradual rebound can be seen from early June because of the government's ease in restrictions on business activities.\n\"\"\"\n#Let's build a dataframe which has only the closing prices. This is a small trick which will be handy later.\nclose={}\nfor i in Counter(filtered_stocks).keys():\n    close[i]=filtered_stocks[i]['Close Price']\nclose_price=pd.DataFrame(close)\nclose_price\n\n\"\"\"\n# Pre-requisites for the simulation \nWe will generate the returns, mean returns and the weights for our selected stocks \n\"\"\"\nreturns= close_price.pct_change().dropna()\nmean_returns=returns.mean()\nweights=np.array([])\nx=1\/5 #Weights assigned are given by 1\/n, where n is the number of stocks and in our case n=5\nfor i in range(5):\n    weights = np.append(weights, x)\nweights\n\n\"\"\"\n# Portfolio return\n\nTo put it in simple words, it is the gain or loss of your portfolio consisting of several investments: in our case the 5 equities. We are interested to find the net profit\/loss of all the stocks taken together rather than individual stocks. \n\nThe formula for the same is given by \n\n![](https:\/\/www.wallstreetmojo.com\/wp-content\/uploads\/2019\/04\/Portfolio-Return-Formula.jpg)\n\n\n**where w and r represent the weight and return of a particular stock\n**\n\"\"\"\n\"\"\"\n## Portfolio variance for a portfolio \n![](https:\/\/cdn.corporatefinanceinstitute.com\/assets\/portfolio-variance-formula-1024x84.png)\n\n### Here sigma is standard deviation and Cov is covariance\n\nThe standard deviation (i.e. sqrt of variance) can help us measure the volatility of our portfolio and is generally considered a vital statistical tool when it comes to comparing multiple values and their behavior.\n\"\"\"\n#Calculating Portfolio Return\nport_return = np.sum(weights * mean_returns)\n\n#Annual portfolio return by multiplying 252*100, where 252 is the active number of working days\nport_annual=port_return*252*100\nport_annual\n#Calculating Portfolio Volatility\ncov = returns.cov()\nport_vol = np.sqrt(np.dot(weights.T,np.dot(cov,weights)))\nport_vol\n\n\n\"\"\"\n# MONTE CARLO SIMULATION\nAccording to Investopedia, Monte Carlo simulations are used to model the probability of different outcomes in a process that cannot easily be predicted due to the intervention of random variables. It is a technique used to understand the impact of risk and uncertainty in prediction and forecasting models.\nIn our case, we will try to return the optimal portfolio allocation to maximize the returns using the historical data we have. \n\n\"\"\"\n#Let's declare the number of Portfolio to be generated\nnum_portfolio = 50000\n\n#Create an empty list for storing returns,volatility,sharpe_ratio(return\/volatility) and weightage of each stock in portfolio\nstats = np.zeros((3 + len(returns.columns),num_portfolio))\n\n\n\n#Monte Carlo Simulation\nfor i in range(num_portfolio):\n    \n    weight = np.random.rand(len(returns.columns)) #Declaring random weights\n    weight = weight\/np.sum(weight) #So that sum of all weight will be equal to 1\n\n    p_annual_return = np.sum(weight * mean_returns) * 252 #Annual Return\n    p_annual_volatility = np.sqrt(np.dot(weight.T,np.dot(cov,weight))) * np.sqrt(252) #Annual Volatility\n    \n    #Storing the values in results list\n    stats[0,i] = p_annual_return\n    stats[1,i] = p_annual_volatility\n    stats[2,i] = stats[0,i]\/stats[1,i]\n\n    for j in range(len(weight)):\n        stats[j+3,i] =  weight[j]\n        \n        \n        \n#Making a dataframe for results list of all generated Portfolio\ncols = ['Annual Return','Annual Volatility','Sharpe Ratio']\nfor num in range(len(list(returns.columns))):\n    cols.append(list(returns.columns)[num])\n\n    \nstats_df = pd.DataFrame(stats.T,columns=cols)\n\nstats_df\n\"\"\"\n# Locating 3 different portfolios\n\n1. **The portfolio with the highest Sharpe Ratio.**\nTo get the gravity of this portfolio, let's dive in a bit deep to understand the significance of Sharpe Ratio in portfolio management. Sharpe Ratio has been widely used to identify risk-adjusted return. Modern Portfolio Theory states that adding assets to a diversified portfolio that has low correlations can decrease portfolio risk without sacrificing return. Apart from that, Sharpe ratio can be used to evaluate a portfolio\u2019s performance history (as seen above). Explanation on whether a portfolio's excess returns are due to smart investment decisions or a result of too much risk can be deduced from Sharpe ratio.\n\n2. **The portfolio with the lowest volatility\/lowest risk**\nIn a beginner's perspective, a low risk portfolio is what that is desired. And this is what that separates out the speculators from the investors: calculated risks taken by the latter. \n\n3. **The portfolio with the highest volatility\/highest risk**\nSeasoned investors choose this owing to their market knowledge. A higher risk can generate good returns given a diversified portfolio. But if you're a beginner, think twice. Do some research on the investment trends. Check out the book:\"The Intelligent Investor\" by Benjamin Graham to gain insights into investments.\n\"\"\"\n#locating \n#Portfolio 1 - Sharpe ratio is the highest (Return\/Volatility)\n#Portfolio 2 - Volatility is the lowest\n            \n\n#Portfolio 1\nmax_sharpe = stats_df.iloc[stats_df['Sharpe Ratio'].idxmax()]\n\n#Portfolio 2\nmin_vol = stats_df.iloc[stats_df['Annual Volatility'].idxmin()]\n\n#Portfolio 3\nmax_vol = stats_df.iloc[stats_df['Annual Volatility'].idxmax()]\n\n\"\"\"\n   # The showdown\n   \n   Let's see all the 3 portfolios which we defined earlier. Remember this is the result of the Monte Carlo simulation which we deployed earlier.\n\"\"\"\n#Portfolio 1\nprint('The Portfolio allocation with maximum Sharpe Ratio) is:')\nprint('All values in percentage')\nround(max_sharpe* 100,2)\n#Portfolio 2\nprint('The Portfolio allocation with least Volatility is:')\nprint('All values in percentage')\nround(min_vol * 100,2)\n\n#Portfolio 3\nprint('The Portfolio allocation with most Volatility is:')\nprint('All values in percentage')\nround(max_vol * 100,2)\n\n#Plotting the simulation\nplt.figure(figsize=(20,10))\nplt.scatter(stats_df['Annual Volatility'],stats_df['Annual Return'],c =stats_df['Sharpe Ratio'],cmap='RdYlBu')\nplt.colorbar()\n\nplt.scatter(max_sharpe[1],max_sharpe[0],marker = (5,1,3),color='red',s=700) #Red - Portfolio 1\nplt.scatter(min_vol[1],min_vol[0],marker = (5,1,3),color='green',s=700) #Green - Portfolio 2\nplt.scatter(max_vol[1],max_vol[0],marker = (5,1,3),color='black',s=700) #Black - Portfolio 3\n            \n\nplt.xlabel('Volatility',fontsize = 20)\nplt.ylabel('Annual Returns',fontsize = 20)\nplt.show()\n\"\"\"\nAs a heads up, I would urge you to try to analyze the trends between deliverable quantity and the total traded quantity. There's quite some untold facts in them. Check the [link](https:\/\/www.goodreturns.in\/classroom\/2015\/10\/understanding-the-importance-shares-delivery-quantity-total-traded-quantity-400097.html) to know about the same. \nThank you! \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'aa8a98cad519c9'}"}
{"id":"47836","text":"\"\"\"\nThe starting framework for this code was taken from: \n https:\/\/www.kaggle.com\/bminixhofer\/simple-lstm-pytorch-version\n\nThere were a few adaptions made such as:\n* adding a contraction map\n* removed possesives\n* removed excess white space\n* \n* moving a lot of the processes into functions to make it easier to rerun and test things\n\nWorks Used:\n\nJeffrey Pennington, Richard Socher, and Christopher D. Manning. 2014. GloVe: Global Vectors for Word Representation. [pdf] [bib]\n\nT. Mikolov, E. Grave, P. Bojanowski, C. Puhrsch, A. Joulin. Advances in Pre-Training Distributed Word Representations\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\n# Natural Language Processing\nimport nltk\nimport re\nfrom keras.preprocessing import text, sequence\n\n# Nueral Networks\nfrom sklearn.model_selection import train_test_split\nimport torch\nfrom torch import nn\nfrom torch.utils import data\nfrom torch.nn import functional as F\n\n# Misc Stuff\nfrom tqdm._tqdm_notebook import tqdm_notebook as tqdm\nimport time\nimport random\nimport gc\nimport os\nimport multiprocessing as mp\nimport matplotlib.pyplot as plt\n# disable progress bars when submitting\ndef is_interactive():\n   return 'SHLVL' not in os.environ\n\nif not is_interactive():\n    def nop(it, *a, **k):\n        return it\n\n    tqdm = nop\n# Code was taken from this kernel: https:\/\/www.kaggle.com\/bminixhofer\/simple-lstm-pytorch-version\n\ndef clean_special_chars(text):\n    '''\n    # Credit goes to: https:\/\/www.kaggle.com\/theoviel\/improve-your-score-with-some-text-preprocessing\n\n    Takes in text as input and returns the text with spaces around each item listed \n    in the variable punct. Special characters are additionally replaced in the outputted text.'''\n\n    punct = \"\/-'?!.,#$%\\'()*+-\/:;<=>@[\\\\]^_`{|}~\" + '\"\"\u201c\u201d\u2019' + '\u221e\u03b8\u00f7\u03b1\u2022\u00e0\u2212\u03b2\u2205\u00b3\u03c0\u2018\u20b9\u00b4\u00b0\u00a3\u20ac\\\u00d7\u2122\u221a\u00b2\u2014\u2013&'\n    for p in punct:\n        text = text.replace(p, f' {p} ')\n\n    specials = {'\\u200b': ' ', '\u2026': ' ... ', '\\ufeff': '', '\u0915\u0930\u0928\u093e': '', '\u0939\u0948': ''}\n    for s in specials:\n        text = text.replace(s, specials[s])\n\n    return text\n\ndef clean_text(data):\n    punct_pattern = '|'.join([\"\u2019\", \"\u2018\", \"\u00b4\", \"`\"])\n    possess_pattern = '|'.join([\"'s\", \"s'\"])\n\n    # lowercasing the text\n    data['comment_text'] = data['comment_text'].apply((lambda x: str.lower(x)))\n    # replace incorrect\/alternative forms of apostrophes to its correct form\n    data['comment_text'] = data['comment_text'].str.replace(punct_pattern, \"'\")\n    # expand contractions \n    data['comment_text'] = data['comment_text'].apply((lambda x: expand_contractions(x)))\n    # remove endings for possessives\n    data['comment_text'] = data['comment_text'].str.replace(possess_pattern, \"\") # embeddings for 9.072% training vocab after this step\n    # separate text from symbols and punctuations\n    data['comment_text'] = data['comment_text'].apply((lambda x: clean_special_chars(x))) # embeddings for 39.745% vocab\n    # remove anything that is not characters or whitespace\n    data['comment_text'] = data['comment_text'].apply((lambda x: re.sub('[^a-zA-z\\s]', '', x)))\n    # remove excess whitespace\n    data['comment_text'] = data['comment_text'].astype(str).apply(lambda x: re.sub(' +', ' ',x))\n    \n    return data\n\n# Credit goes to: https:\/\/github.com\/kootenpv\/contractions\/blob\/master\/contractions\/__init__.py\ncontractions_dict = {\n    \"ain't\": \"are not\",\n    \"aren't\": \"are not\",\n    \"can't\": \"cannot\",\n    \"can't've\": \"cannot have\",\n    \"'cause\": \"because\",\n    \"c'mon\": \"come on\",\n    \"could've\": \"could have\",\n    \"couldn't\": \"could not\",\n    \"couldn't've\": \"could not have\",\n    \"didn't\": \"did not\",\n    \"doesn't\": \"does not\",\n    \"don't\": \"do not\",\n    \"hadn't\": \"had not\",\n    \"hadn't've\": \"had not have\",\n    \"hasn't\": \"has not\",\n    \"haven't\": \"have not\",\n    \"he'd\": \"he would\",\n    \"he'd've\": \"he would have\",\n    \"he'll\": \"he will\",\n    \"he'll've\": \"he will have\",\n    \"he's\": \"he is\",\n    \"how'd\": \"how did\",\n    \"how're\": \"how are\",\n    \"how'd'y\": \"how do you\",\n    \"how'll\": \"how will\",\n    \"how's\": \"how is\",\n    \"i'd\": \"i would\",\n    \"i'd've\": \"i would have\",\n    \"i'll\": \"i will\",\n    \"i'll've\": \"i will have\",\n    \"i'm\": \"i am\",\n    \"i've\": \"i have\",\n    \"isn't\": \"is not\",\n    \"it'd\": \"it would\",\n    \"it'd've\": \"it would have\",\n    \"it'll\": \"it will\",\n    \"it'll've\": \"it will have\",\n    \"it's\": \"it is\",\n    \"let's\": \"let us\",\n    \"ma'am\": \"madam\",\n    \"mayn't\": \"may not\",\n    \"might've\": \"might have\",\n    \"mightn't\": \"might not\",\n    \"mightn't've\": \"might not have\",\n    \"must've\": \"must have\",\n    \"mustn't\": \"must not\",\n    \"mustn't've\": \"must not have\",\n    \"needn't\": \"need not\",\n    \"needn't've\": \"need not have\",\n    \"o'clock\": \"of the clock\",\n    \"oughtn't\": \"ought not\",\n    \"oughtn't've\": \"ought not have\",\n    \"shan't\": \"shall not\",\n    \"sha'n't\": \"shall not\",\n    \"shan't've\": \"shall not have\",\n    \"she'd\": \"she would\",\n    \"she'd've\": \"she would have\",\n    \"she'll\": \"she will\",\n    \"she'll've\": \"she will have\",\n    \"she's\": \"she is\",\n    \"should've\": \"should have\",\n    \"shouldn't\": \"should not\",\n    \"shouldn't've\": \"should not have\",\n    \"so've\": \"so have\",\n    \"so's\": \"so is\",\n    \"that'd\": \"that would\",\n    \"that'd've\": \"that would have\",\n    \"that's\": \"that is\",\n    \"there'd\": \"there would\",\n    \"there'd've\": \"there would have\",\n    \"there's\": \"there is\",\n    \"they'd\": \"they would\",\n    \"they'd've\": \"they would have\",\n    \"they'll\": \"they will\",\n    \"they'll've\": \"they will have\",\n    \"they're\": \"they are\",\n    \"they've\": \"they have\",\n    \"to've\": \"to have\",\n    \"wasn't\": \"was not\",\n    \"we'd\": \"we would\",\n    \"we'd've\": \"we would have\",\n    \"we'll\": \"we will\",\n    \"we'll've\": \"we will have\",\n    \"we're\": \"we are\",\n    \"we've\": \"we have\",\n    \"weren't\": \"were not\",\n    \"what'll\": \"what will\",\n    \"what'll've\": \"what will have\",\n    \"what're\": \"what are\",\n    \"what's\": \"what is\",\n    \"what've\": \"what have\",\n    \"when's\": \"when is\",\n    \"when've\": \"when have\",\n    \"where'd\": \"where did\",\n    \"where's\": \"where is\",\n    \"where've\": \"where have\",\n    \"who'll\": \"who will\",\n    \"who'll've\": \"who will have\",\n    \"who's\": \"who is\",\n    \"who've\": \"who have\",\n    \"why's\": \"why is\",\n    \"why've\": \"why have\",\n    \"will've\": \"will have\",\n    \"won't\": \"will not\",\n    \"won't've\": \"will not have\",\n    \"would've\": \"would have\",\n    \"wouldn't\": \"would not\",\n    \"wouldn't've\": \"would not have\",\n    \"y'all\": \"you all\",\n    \"y'all'd\": \"you all would\",\n    \"y'all'd've\": \"you all would have\",\n    \"y'all're\": \"you all are\",\n    \"y'all've\": \"you all have\",\n    \"you'd\": \"you would\",\n    \"you'd've\": \"you would have\",\n    \"you'll\": \"you will\",\n    \"you'll've\": \"you shall have\",\n    \"you're\": \"you are\",\n    \"you've\": \"you have\",\n    \"doin'\": \"doing\",\n    \"goin'\": \"going\",\n    \"nothin'\": \"nothing\",\n    \"somethin'\": \"something\",\n}\n\ncontractions_re = re.compile('|'.join(contractions_dict.keys()))\ndef expand_contractions(s, contractions_dict = contractions_dict):\n    def replace(match):\n        v = match.group()\n        if v in contractions_dict:\n            return contractions_dict[v]\n    return contractions_re.sub(replace, s)\ndef load_data(size=4):\n    \n    start = time.time()\n    \n    train = pd.read_csv('..\/input\/jigsaw-unintended-bias-in-toxicity-classification\/train.csv')\n    test = pd.read_csv('..\/input\/jigsaw-unintended-bias-in-toxicity-classification\/test.csv')\n    \n    train = clean_text(train)\n    test = clean_text(test)\n     \n    x_train = train['comment_text']\n    y_train = train['target']\n    \n    x_test = test['comment_text']\n    \n    y_aux_train = train[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]\n    \n    print('Data was successfully read in and preprocessed. Time taken: ',\n      round((time.time() - start)\/60, 2), ' minutes') \n    \n    return  x_train, x_test, y_train, y_aux_train, test\ndef tokenize_text(x_train, x_test, pad_len):\n\n    MAX_WORDS = 100_000\n    \n    start = time.time()\n    \n    tokenizer = text.Tokenizer(num_words = MAX_WORDS)\n    tokenizer.fit_on_texts(list(x_train) + list(x_test))\n\n    x_train = tokenizer.texts_to_sequences(x_train)\n    x_train = sequence.pad_sequences(x_train, maxlen=pad_len)\n\n    x_test = tokenizer.texts_to_sequences(x_test)\n    x_test = sequence.pad_sequences(x_test, maxlen=pad_len)\n        \n    print('Text has been tokenized in', round((time.time() - start)\/60, 2), ' minutes')\n    \n    return x_train, x_test, tokenizer\n\ndef get_coefs(word, *arr):\n    return word, np.asarray(arr, dtype='float32')\n\ndef load_embeddings(path):\n    with open(path, encoding=\"utf8\") as f:\n        return dict(get_coefs(*line.strip().split(' ')) for line in tqdm(f))   \n\ndef build_matrix(word_index, path):\n    embedding_index = load_embeddings(path)\n    embedding_matrix = np.zeros((len(word_index) + 1, 300))\n    unknown_words = []\n    \n    for word, i in word_index.items():\n        try:\n            embedding_matrix[i] = embedding_index[word]\n        except KeyError:\n            unknown_words.append(word)\n    return embedding_matrix, unknown_words    \n\ndef make_embedder(tokenizer):\n    \n    GLOVE_PATH = '..\/input\/crawl300d2m\/crawl-300d-2M.vec'\n    CRAWL_PATH = '..\/input\/glove840b300dtxt\/glove.840B.300d.txt'\n\n    start = time.time()\n    glove_matrix, unknown_words = build_matrix(tokenizer.word_index, GLOVE_PATH)\n    crawl_matrix, unknown_words = build_matrix(tokenizer.word_index, CRAWL_PATH)\n\n    embedding_matrix = np.concatenate([crawl_matrix, glove_matrix], axis = -1)\n\n    gc.collect()\n    \n    print('Embedding matrix was successfully made. Time taken:',\n          round((time.time() - start)\/60,2), ' minutes') \n    \n    return embedding_matrix\ndef make_train_test(x_train, x_test, y_train, y_aux_train):\n    \n    # make test\/train data for pytorch\n    \n    x_train_torch = torch.tensor(x_train, dtype=torch.long).cuda()\n    x_test_torch =  torch.tensor(x_test, dtype=torch.long).cuda()\n    y_train_torch = torch.tensor(\n        np.hstack([y_train[:, np.newaxis], y_aux_train]),\n        dtype=torch.float32).cuda()\n\n    train_dataset = data.TensorDataset(x_train_torch, y_train_torch)\n    test_dataset = data.TensorDataset(x_test_torch)\n    \n    print('Pytorch data has been made.')\n    \n    return train_dataset, test_dataset, y_train_torch\nclass SpatialDropout(nn.Dropout2d):\n    def forward(self, x):\n        x = x.unsqueeze(2)    # (N, T, 1, K)\n        x = x.permute(0, 3, 2, 1)  # (N, K, 1, T)\n        x = super(SpatialDropout, self).forward(x)  # (N, K, 1, T), some features are masked\n        x = x.permute(0, 3, 2, 1)  # (N, T, 1, K)\n        x = x.squeeze(2)  # (N, T, K)\n        return x\n    \nclass NeuralNet(nn.Module):\n    def __init__(self, embedding_matrix, num_aux_targets, LSTM_UNITS, max_features):\n        super(NeuralNet, self).__init__()\n        embed_size = embedding_matrix.shape[1]\n        \n        DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS\n        \n        self.embedding = nn.Embedding(max_features, embed_size)\n        self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))\n        self.embedding.weight.requires_grad = False\n        self.embedding_dropout = SpatialDropout(0.3)\n        \n        self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)\n        self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)\n    \n        self.linear1 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)\n        self.linear2 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)\n        \n        self.linear_out = nn.Linear(DENSE_HIDDEN_UNITS, 1)\n        self.linear_aux_out = nn.Linear(DENSE_HIDDEN_UNITS, num_aux_targets)\n        \n    def forward(self, x):\n        h_embedding = self.embedding(x)\n        h_embedding = self.embedding_dropout(h_embedding)\n        \n        h_lstm1, _ = self.lstm1(h_embedding)\n        h_lstm2, _ = self.lstm2(h_lstm1)\n        \n        # global average pooling\n        avg_pool = torch.mean(h_lstm2, 1)\n        # global max pooling\n        max_pool, _ = torch.max(h_lstm2, 1)\n        \n        h_conc = torch.cat((max_pool, avg_pool), 1)\n        h_conc_linear1  = F.relu(self.linear1(h_conc))\n        h_conc_linear2  = F.relu(self.linear2(h_conc))\n        \n        hidden = h_conc + h_conc_linear1 + h_conc_linear2\n        \n        result = self.linear_out(hidden)\n        aux_result = self.linear_aux_out(hidden)\n        out = torch.cat([result, aux_result], 1)\n        \n        return out\n# Code was taken from this kernel: https:\/\/www.kaggle.com\/bminixhofer\/simple-lstm-pytorch-version\n\ndef sigmoid(x):\n    return 1 \/ (1 + np.exp(-x))\n\ndef train_model(model, train, test, loss_fn, output_dim,\n                lr=0.001, batch_size=512, n_epochs=4, \n                enable_checkpoint_ensemble=True):\n    param_lrs = [{'params': param, 'lr': lr} for param in model.parameters()]\n    optimizer = torch.optim.Adam(param_lrs, lr=lr)\n\n    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda epoch: 0.6 ** epoch)\n    \n    train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)\n    test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)\n    all_test_preds = []\n    checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]\n    \n#    model_stats = pd.DataFrame(columns = ['Epoch', 'Loss', 'Accuracy'])\n    for epoch in range(n_epochs):\n        start_time = time.time()\n        \n        scheduler.step()\n        \n        model.train()\n        avg_loss = 0.\n        \n        for data in tqdm(train_loader, disable=False):\n            x_batch = data[:-1]\n            y_batch = data[-1]\n\n            y_pred = model(*x_batch)            \n            loss = loss_fn(y_pred, y_batch)\n\n            optimizer.zero_grad()\n            loss.backward()\n\n            optimizer.step()\n            avg_loss += loss.item() \/ len(train_loader)\n            \n        model.eval()\n        test_preds = np.zeros((len(test), output_dim))\n    \n        for i, x_batch in enumerate(test_loader):\n            y_pred = sigmoid(model(*x_batch).detach().cpu().numpy())\n\n            test_preds[i * batch_size:(i+1) * batch_size, :] = y_pred\n    \n        all_test_preds.append(test_preds)\n        elapsed_time = time.time() - start_time\n        \n        print('Epoch {}\/{} \\t loss={:.4f} \\t time={:.2f}s'.format(\n              epoch + 1, n_epochs, avg_loss, elapsed_time))\n        \n\n            \n    if enable_checkpoint_ensemble:\n        test_preds = np.average(all_test_preds, weights=checkpoint_weights, axis=0)    \n    else:\n        test_preds = all_test_preds[-1]\n        \n    return test_preds\ndef seed_everything(seed=0):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\nseed_everything()\n# read in and preprocess data\nx_train, x_test, y_train, y_aux_train, test = load_data(size=1)\n\n# tokenize text\nx_train, x_test, tokenizer = tokenize_text(x_train, x_test, pad_len = 205)\n\n# embedding matrix\nembedding_matrix = make_embedder(tokenizer)\n# set variable units\nlstm_units = 128\nnum_epochs = 5\npad_length = 250\n\n# read in and preprocess data\nx_train, x_test, y_train, y_aux_train, test = load_data(size=1)\n\n# tokenize text\nx_train, x_test, tokenizer = tokenize_text(x_train, x_test, pad_len = pad_length)\n\n# embedding matrix\nembedding_matrix = make_embedder(tokenizer)\n\n# make train\/test data for pytorch\ntrain_dataset, test_dataset, y_train_torch = make_train_test(x_train, x_test, y_train, y_aux_train)\n\nall_test_preds = []\n\nstart = time.time()\n\nNUM_MODELS = 2\nfor model_idx in range(NUM_MODELS):\n    print('Model ', model_idx)\n    seed_everything(0 + model_idx)\n    \n    model = NeuralNet(\n        embedding_matrix, y_aux_train.shape[-1],\n        lstm_units, len(tokenizer.word_index) + 1)\n    model.cuda()\n    test_preds = train_model(\n        model, train_dataset, test_dataset, \n        output_dim=y_train_torch.shape[-1], n_epochs = num_epochs,\n        loss_fn=nn.BCEWithLogitsLoss(reduction='mean'))\n    \n    all_test_preds.append(test_preds)\n    print('Total time taken: ', round((time.time() - start)\/60,2), 'minutes')\n    print()\nsubmission = pd.DataFrame.from_dict({\n    'id': test['id'],\n    'prediction': np.mean(all_test_preds, axis=0)[:, 0]\n})\n\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '581e1b427fb2ca'}"}
{"id":"19085","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import preprocessing\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n\"\"\"\n# Input\n\"\"\"\nroot = \"\/kaggle\/input\/unsw-nb15\/\"\ntrain = pd.read_csv(root+\"UNSW_NB15_training-set.csv\")\ntest = pd.read_csv(root+\"UNSW_NB15_testing-set.csv\")\nlist_events = pd.read_csv(root+\"UNSW-NB15_LIST_EVENTS.csv\")\nfeatures = pd.read_csv(root+\"NUSW-NB15_features.csv\", encoding='cp1252')\n\"\"\"\nAccording to official site [here](https:\/\/www.unsw.adfa.edu.au\/unsw-canberra-cyber\/cybersecurity\/ADFA-NB15-Datasets\/), train and test data have 175341 and 82332 rows respectively.\n\"\"\"\nprint(train.shape, test.shape)\nif train.shape[0]<100000:\n    print(\"Train test sets are reversed. Fixing them.\")\n    train, test = test, train\ntrain['type'] = 'train'\ntest['type'] ='test'\ntotal = pd.concat([train, test], axis=0, ignore_index=True)\ntotal.drop(['id'], axis=1, inplace=True)\n# del train, test\n\"\"\"\n# Utils\n\"\"\"\nfrom pandas.api.types import is_datetime64_any_dtype as is_datetime\nfrom pandas.api.types import is_categorical_dtype\ndef reduce_mem_usage(df, use_float16=False):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        if is_datetime(df[col]) or is_categorical_dtype(df[col]):\n            # skip datetime type or categorical type\n            continue\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if use_float16 and c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('object')\n\n    end_mem = df.memory_usage().sum() \/ 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) \/ start_mem))\n    \n    return df\ndef standardize(df):\n    return (df-df.mean())\/df.std()\n    \ndef min_max(df):\n    return (df-df.min())\/(df.max() - df.min())\n\ndef normalize(df):\n    return pd.Dataframe(preprocessing.normalize(df), columns=df.columns)\ntotal = reduce_mem_usage(total)\n\"\"\"\n# List of Events\n\"\"\"\nlist_events.shape\nlist_events.head()\nlist_events['Attack category'].unique()\nlist_events['Attack subcategory'].unique()\n\"\"\"\n# Features\n\"\"\"\nfeatures.head(features.shape[0])\n# the Name column has camel case values\nfeatures['Name'] = features['Name'].str.lower()\n# the following 4 columns are address related and not in train dataset\nfeatures = features[~features['Name'].isin(['srcip', 'sport', 'dstip', 'dsport'])].reset_index()\nfeatures.drop(['index', 'No.'], axis=1, inplace=True)\n\"\"\"\n# Data\n\"\"\"\nnormal = train[train['label']==0]\nanomaly = train[train['label']==1]\n\"\"\"\n## Some difference with features file\n\"\"\"\nprint(sorted(set(train.columns) - set(features['Name'].values)))\nprint(sorted(set(features['Name'].values) - set(train.columns)))\n\"\"\"\nSome of the column names in features file are wrong and we are going to fix them. \n\"\"\"\nfix = {'ct_src_ ltm': 'ct_src_ltm', 'dintpkt': 'dinpkt', 'dmeansz': 'dmean', 'res_bdy_len': 'response_body_len', 'sintpkt': 'sinpkt', 'smeansz': 'smean'}\nfeatures['Name'] = features['Name'].apply(lambda x: fix[x] if x in fix else x)\nfeatures.to_csv('features.csv')\nprint(sorted(set(train.columns) - set(features['Name'].values)))\nprint(sorted(set(features['Name'].values) - set(train.columns)))\n\"\"\"\nStill there are some differences. `stime` and `ltime` both refers to when the recording stared and lasted. So they shouldn't be valuable in training, hence not being in train set makes sence. `id` is just row number and rate might be something related to packed sending speed or data rate.\n\"\"\"\n\"\"\"\n## Checking data types\n\"\"\"\ntrain.head()\ntrain.dtypes\n\"\"\"\n* categorical: state, service, proto\n* target  = attack_cat, label\n* integer but categorial = is_sm_ips_ports, ct_state_ttl, is_ftp_login\n* integer = spkts, dpkts, sbytes, dbytes, sttl, dttl, sload, dload, sloss, dloss, swin, dwin, stcpb, dtcpb, smean, dmean, trans_depth, response_body_len, ct_srv_src, ct_state_ttl, ct_dst_ltm, ct_src_dport_ltm, ct_dst_sport_ltm, ct_dst_src_ltm, ct_ftp_cmd, ct_flw_http_mthd, ct_src_ltm, ct_srv_dst, \n* decimal = dur, rate, sinpkt, dinpkt, sjit, djit, tcprtt, synack, ackdat\n\"\"\"\n\"\"\"\n# Correlation matrix\nWhy checking correlation is important ? Check these links:\n* [Why Feature Correlation Matters \u2026. A Lot!](https:\/\/towardsdatascience.com\/why-feature-correlation-matters-a-lot-847e8ba439c4) and \n* [Feature selection \u2014 Correlation and P-value](https:\/\/towardsdatascience.com\/feature-selection-correlation-and-p-value-da8921bfb3cf)\n\"\"\"\ndef show_correlation(data, method='pearson'):\n    correlation_matrix = data.corr(method='pearson') #  \u2018pearson\u2019, \u2018kendall\u2019, \u2018spearman\u2019\n    fig = plt.figure(figsize=(12,9))\n    sns.heatmap(correlation_matrix,vmax=0.8,square = True) #  annot=True, if fig should show the correlation score too\n    plt.show()\n    return correlation_matrix\n\ndef top_correlations(correlations, limit=0.9):\n    columns = correlations.columns\n    for i in range(correlations.shape[0]):\n        for j in range(i+1, correlations.shape[0]):\n            if correlations.iloc[i,j] >= limit:\n                print(f\"{columns[i]} {columns[j]} {correlations.iloc[i,j]}\")\ndef print_correlations(correlations, col1=None, col2=None):\n    columns = correlations.columns\n    for i in range(correlations.shape[0]):\n        for j in range(i+1, correlations.shape[0]):\n            if (col1 == None or col1==columns[i]) and (col2 == None or col2==columns[j]):\n                print(f\"{columns[i]} {columns[j]} {correlations.iloc[i,j]}\")\n                return\n            elif (col1 == None or col1==columns[j]) and (col2 == None or col2==columns[i]):\n                print(f\"{columns[i]} {columns[j]} {correlations.iloc[i,j]}\")\n                return\n            \ndef find_corr(df1, df2):\n    return pd.concat([df1, df2], axis=1).corr().iloc[0,1]\n\ndef corr(col1, col2='label', df=total):\n    return pd.concat([df[col1], df[col2]], axis=1).corr().iloc[0,1]\n\"\"\"\n## Pearson\n\"\"\"\ncorrelation_matrix = show_correlation(total)\ntop_correlations(correlation_matrix, limit=0.9)\n\"\"\"\n## Spearman\n\"\"\"\ncorrelation_matrix = show_correlation(train, method='spearman')\ntop_correlations(correlation_matrix, limit=0.9)\n\"\"\"\nMost correlated features are :\n* spkts, sbytes, sloss \n* dpkts, dbytes, dloss\n* sinpkt, is_sm_ips_ports\n* swin, dwin\n* tcprtt, synack\n* ct_srv_src, ct_srv_dst, ct_dst_src_ltm, ct_src_dport_ltm, ct_dst_sport_ltm \n* is_ftp_login ct_ftp_cmd\n\"\"\"\nsns.pairplot(total[['spkts', 'sbytes', 'sloss']])\nsns.pairplot(total[['dpkts', 'dbytes', 'dloss']])\nsns.pairplot(total[['sinpkt', 'is_sm_ips_ports']])\nsns.pairplot(total[['swin', 'dwin']])\n\"\"\"\n# plot utils\n\"\"\"\ndef dual_plot(col, data1=normal, data2=anomaly, label1='normal', label2='anomaly', method=None):\n    if method != None:\n        sns.distplot(data1[col].apply(method), label=label1, hist=False, rug=True)\n        sns.distplot(data2[col].apply(method), label=label2, hist=False, rug=True)\n    else:\n        sns.distplot(data1[col], label=label1, hist=False, rug=True)\n        sns.distplot(data2[col], label=label2, hist=False, rug=True)\n    plt.legend()\n    \ndef catplot(data, col):\n    ax = sns.catplot(x=col, hue=\"label\", col=\"type\",data=data, kind=\"count\", height=5, legend=False, aspect=1.4)\n    ax.set_titles(\"{col_name}\")\n    ax.add_legend(loc='upper right',labels=['normal','attack'])\n    plt.show(ax)\n\"\"\"\n# Categorical\nThese four columns are categorical: 'attack_cat', 'state', 'service', 'proto'. Among them 'attack_cat' isn't a feature.\nThese features are categorical but in integer form : 'is_sm_ips_ports', 'ct_state_ttl', 'is_ftp_login'.\n\"\"\"\ndef create_count_df(col, data=total):\n    df = pd.DataFrame(data[col].value_counts().reset_index().values, columns = [col, 'count'])\n    df['percent'] = df['count'].values*100\/data.shape[0]\n    return df.sort_values(by='percent', ascending=False)\n\"\"\"\n## Label\n0 for normal and 1 for attack records\n\"\"\"\ncreate_count_df('label', train)\ncreate_count_df('label', test)\n\"\"\"\nSo it seems the dataset is pretty balanced, unlike real world data where attack scenarios are rare. Moreover, here attack connections are more than normal connections.\n\"\"\"\n\"\"\"\n## State\nIndicates to the state and its dependent protocol, e.g. ACC, CLO, CON, ECO, ECR, FIN, INT, MAS, PAR, REQ, RST, TST, TXD, URH, URN, and (-) (if not used state)\n\"\"\"\ncol = 'state'\ncreate_count_df(col, train)\n# all other values those were few in train set, have been renamed to 'RST_and_others'\ntotal.loc[~total[col].isin(['FIN', 'INT', 'CON', 'REQ', 'RST']), col] = 'others'\ncatplot(total, col)\n# catplot(total[~total[col].isin(['INT', 'FIN', 'REQ', 'CON'])], col)\n\"\"\"\n## Service\nhttp, ftp, smtp, ssh, dns, ftp-data ,irc  and (-) if not much used service. More than half of the service data are of - category. \n\"\"\"\ncol = 'service'\ncreate_count_df(col, train)\ncatplot(total[~total[col].isin(['-', 'dns', 'http', 'smtp', 'ftp-data', 'ftp', 'ssh', 'pop3'])], col)\ntotal.loc[~total[col].isin(['-', 'dns', 'http', 'smtp', 'ftp-data', 'ftp', 'ssh', 'pop3']), col] = 'others'\n\"\"\"\n## proto\nTransaction protocol. Normal connections of train data have only 5 protocols, where anomaly connections have 129. So we'll convert all other protocols into same value.\n\"\"\"\ncol = 'proto'\ncreate_count_df(col, normal)\ncreate_count_df(col, anomaly)[:10]\n# icmp and rtp columns are in test, but not in train data\ntotal.loc[total[col].isin(['igmp', 'icmp', 'rtp']), col] = 'igmp_icmp_rtp'\ntotal.loc[~total[col].isin(['tcp', 'udp', 'arp', 'ospf', 'igmp_icmp_rtp']), col] = 'others'\n\"\"\"\n## is_sm_ips_ports\nIf source and destination IP addresses equal and port numbers (sport\/dport)  equal then, this variable takes value 1 else 0. Seems if it is 1, then the connection is always normal. This feature is highly correlated with sinpkt (0.94131890073567).\n\"\"\"\ncatplot(total, 'is_sm_ips_ports')\n\"\"\"\n## is_ftp_login\nIf the ftp session is accessed by user and password then 1 else 0. In most of the cases session has no user and password. However there are values 2 and 4 which should not be there.\n\nThis feature is totally correlated with ct_ftp_cmd, which counts the number of ftp commands. So dropping this column should be ok.\n\"\"\"\ncol = 'is_ftp_login'\nprint(corr('ct_ftp_cmd', col), corr('is_ftp_login', 'label'))\ncatplot(total, col)\ntotal.drop([col], axis=1, inplace=True)\n\"\"\"\n# Integer Features\n## ct_state_ttl\nNo. for each state according to specific range of values for source\/destination time to live (sttl\/dttl).\n\"\"\"\ncol = 'ct_state_ttl'\ncatplot(total, col)\n\"\"\"\n## ct_ftp_cmd\nNo of flows that has a command in ftp session. It has a very low correlation with target. Also is_ftp_login is highly correlated with it (0.9988554882922012).\n\"\"\"\ncatplot(total, 'ct_ftp_cmd')\ncorr('ct_ftp_cmd', 'label')\n\"\"\"\n## ct_flw_http_mthd\nNo. of flows that has methods such as Get and Post in http service. Seems 0 has more anomaly values, however the correlation is very small with target.\n\"\"\"\ncol = 'ct_flw_http_mthd'\ncatplot(total, col)\ncorr(col) # -0.012237160723\ncreate_count_df(col, total)\n\"\"\"\n## sbytes & dbytes\n* sbytes: Source to destination transaction bytes \n* dbytes: Destination to source transaction bytes\n\nThese 2 features are higly corelated to number of packets sent (spkts & dpkts). Actually, spkts * smean = sbytes. Also they are closely related to sloss and dloss. So we can drop these 2 here.\n\"\"\"\nprint(find_corr(total['spkts']*total['smean'], total['sbytes'])) # 0.999999\nprint(find_corr(total['dpkts']*total['dmean'], total['dbytes'])) # 0.99999\nprint(corr('sbytes', 'sloss'), corr('dbytes', 'dloss')) # 0.995771577240429, 0.9967111338305503\ntotal.drop(['sbytes', 'dbytes'], axis=1, inplace=True)\n\"\"\"\n## smean & dmean \nMean of the packet size transmitted. However is it just sbytes\/spkts ? The correlation says it is. So we already have this \ninfo from those other features.\n\"\"\"\ndual_plot('smean')\ndual_plot('dmean')\ntotal['smean_log1p'] = total['smean'].apply(np.log1p)\ntotal['dmean_log1p'] = total['dmean'].apply(np.log1p)\n\n# -0.02837244879012871 -0.2951728296856902 -0.05807468815031313 -0.5111549621216057\nprint(corr('smean'), corr('dmean'), corr('smean_log1p'), corr('dmean_log1p'))\n# So we have better correlation with label after applying log1p. \ntotal.drop(['smean', 'dmean'], axis=1, inplace=True)\n\"\"\"\n## spkts and dpkts\n* spkts : Source to destination packet count \n* dpkts: Destination to source packet count\n\"\"\"\ncol = 'spkts'\ndual_plot(col)\ndual_plot(col, method=np.log1p)\ntotal['spkts_log1p'] = total['spkts'].apply(np.log1p)\ntotal['dpkts_log1p'] = total['dpkts'].apply(np.log1p)\n\n# -0.043040466783819634 -0.09739388286233619 -0.3468819761209388 -0.45005074723539357\nprint(corr('spkts'), corr('dpkts'), corr('spkts_log1p'), corr('dpkts_log1p'))\n# So we have better correlation with label after applying log1p. \ntotal.drop(['spkts', 'dpkts'], axis=1, inplace=True)\n\"\"\"\n## sttl & dttl\n* sttl: Source to destination time to live value \n* dttl: Destination to source time to live value\n\nFor sttl most of the anomalies have live values around 65 and 250. Its correlation with the target value is high too.\nHowever, for dttl both types have nearly same distribution. So the correlation with target is very low.\n\"\"\"\ncol = 'sttl'\ndual_plot(col) # 0.62408238, after applying log1p 0.61556952425\ncol = 'dttl'\ndual_plot(col) # corr -0.09859087338578788\n\"\"\"\n## sloss & dloss\n* sloss: Source packets retransmitted or dropped \n* dloss: Destination packets retransmitted or dropped\n\nSloss is highly correlated with spkts and sbytes (more than .91). Similarly dloss is highly correlated with dpkts and dbytes. \nHowever, though packets sent is related loss of packets, this isn't quite linearly related like packet number and size. So we keep both for now.\n\nValues are mostly between 0 to 3. Yet some values are more than several thousands.\n\"\"\"\ndual_plot('sloss')\n# So log1p makes it easier to differentiate\ndual_plot('sloss', method=np.log1p)\ntotal['sloss_log1p'] = total['sloss'].apply(np.log1p)\ntotal['dloss_log1p'] = total['dloss'].apply(np.log1p)\n# 0.001828274080103508 -0.07596097807462938 -0.3454351103223904 -0.3701913238787703\nprint(corr('sloss'), corr('dloss'), corr('sloss_log1p'), corr('dloss_log1p') )\ntotal.drop(['sloss', 'dloss'], axis=1, inplace= True)\n\"\"\"\n## swin & dwin\nTCP window advertisement value. Except 0 and 255 other values(1-254) occur mostly once only. So we can separate them into 3 groups. And we also see after binning their correlation with target remains same.\n\"\"\"\ntotal['swin'].value_counts().loc[lambda x: x>1]\ntotal['dwin'].value_counts().loc[lambda x: x>1]\nprint(corr('swin'), corr('dwin'))\ndual_plot('swin')\nselected = ['swin', 'dwin']\nkbins = preprocessing.KBinsDiscretizer(n_bins=[3, 3], encode='ordinal', strategy='uniform')\ntotal[selected] = pd.DataFrame(kbins.fit_transform(total[selected]), columns=selected)\nprint(corr('swin'), corr('dwin'))\n\"\"\"\n## stcpb & dtcpb\nTCP base sequence number. It has a really big range, 0 to 5e9. However, anomaly connections are mostly around 0. \n\"\"\"\ncol = 'stcpb'\ndual_plot(col)\ndual_plot(col, method=np.log1p)\ntotal['stcpb_log1p'] = total['stcpb'].apply(np.log1p)\ntotal['dtcpb_log1p'] = total['dtcpb'].apply(np.log1p)\n# -0.2665849100492664 -0.2635428109654134 -0.33898970769021913 -0.33835676091281974\nprint(corr('stcpb'), corr('dtcpb'), corr('stcpb_log1p'), corr('dtcpb_log1p'))\ntotal.drop(['stcpb', 'dtcpb'], axis=1, inplace= True)\n\"\"\"\n### tcprtt & synack & ackdat\n* tcprtt is the TCP connection setup round-trip time, the sum of \u2019synack\u2019 and \u2019ackdat\u2019.\n* synack: TCP connection setup time, the time between the SYN and the SYN_ACK packets.\n* ackdat : TCP connection setup time, the time between the SYN_ACK and the ACK packets.\n\nAs tcprtt, is just the sum of other two features, it doesn't add any extra info to our models. So we can just drop it for now.\nApplying preprocessing on synack and ackdat didn't improve much. From graph we can see, anomaly connections generally have values around 0.\n\"\"\"\ntotal.drop(['tcprtt'], axis=1, inplace=True)\ndual_plot('synack')\ndual_plot('ackdat')\n\"\"\"\n## trans_depth\nRepresents the pipelined depth into the connection of http request\/response transaction. After depth 5 to 172 occurences are few.\n\"\"\"\ncol = 'trans_depth'\nprint(corr(col)) # -0.0022256544\ncreate_count_df(col, total)\n\"\"\"\n## response_body_len\nActual uncompressed content size of the data transferred from the server\u2019s http service. \nThe values range between 0 to 5.24M.\n\"\"\"\ncol = 'response_body_len'\ndual_plot(col)\ntotal[\"response_body_len_log1p\"] = total[\"response_body_len\"].apply(np.log1p)\n\n# slight improve\n# -0.018930127454048158 -0.03261972203078345\nprint(corr('response_body_len'), corr('response_body_len_log1p'))\ntotal.drop(['response_body_len'], axis=1, inplace=True)\n\"\"\"\n## ct_srv_src\nNo. of connections that contain the same service and source address in 100 connections according to the last time. Most of the normal connections are within 10. It is highly correlated to ct_srv_dst.\n\"\"\"\ncol = 'ct_srv_src'\nprint(total[col].value_counts())\nprint(corr(col)) # 0.24659616767\ndual_plot(col)\n\"\"\"\n## ct_srv_dst\nNo. of connections that contain the same service and destination address in 100 connections according to the last time. It is highly correlated to ct_srv_src too. It has a slight better correlation with label than ct_srv_src. So the other one can be dropped to check for possible improvement.\n\"\"\"\ncol = 'ct_srv_dst'\nprint(total[col].value_counts())\n# graph is same as ct_srv_src\ndual_plot(col)\n# 0.2478122357. they are very correlated 0.97946681, need to check whether dropping one benefits\nprint(corr('ct_srv_dst'), corr('ct_srv_src', 'ct_srv_dst'))\n\"\"\"\n## ct_src_ltm & ct_dst_ltm\nNo. of connections of the same source\/destination address in 100 connections according to the last recorder time.\nValues are well between 0 to 51 and very few values after 48. They are much correlated , but not to the point of dropping one.\n\"\"\"\ncol = 'ct_src_ltm'\nprint(corr(col))\ncreate_count_df(col, total)\nprint(corr('ct_dst_ltm'))\ncreate_count_df('ct_dst_ltm', total)\ncorr('ct_src_ltm', 'ct_dst_ltm')\n\"\"\"\n## ct_src_dport_ltm & ct_dst_sport_ltm\n* ct_src_dport_ltm : No of connections of the same source address and the destination port in 100 connections according to the last time.\n* ct_dst_sport_ltm: No of connections of the same destination address and the source port in 100 connections according to the last time.\n\"\"\"\nfor col in ['ct_src_dport_ltm', 'ct_dst_sport_ltm']:\n    print(corr(col))\n    print(create_count_df(col, total))\ncorr('ct_src_dport_ltm', 'ct_dst_sport_ltm')\n\"\"\"\n# Decimal Features\n## dur \nrecorded total duration. Normal connections are mostly within 5. However, this feature has a poor correlation with label.\n\n\"\"\"\ncol = 'dur'\nprint(corr(col)) # 0.0290961170, correlation gets worse after log1p\ndual_plot(col)\n\"\"\"\n## rate\nThis feature isn't mentioned is feature list. It has value upto 1M. Anomaly connections are mostly around 0.\n\"\"\"\ncol = 'rate'\nprint(corr(col))\ndual_plot(col) # cor 0.3358, after applying log1p it becomes 0.31581108\n\"\"\"\n## sinpkt & dinpkt\n* sinpkt: Source interpacket arrival time (mSec)\n* dinpkt: Destination interpacket arrival time (mSec)\n\nsinpkt is highly correlated with is_sm_ips_ports (0.9421206). Will dropping one of them benefit ?\n\"\"\"\ncol = 'sinpkt'\ncorr(col, 'is_sm_ips_ports')\nprint(corr(col)) # corr -0.1554536980863\ndual_plot(col) \ndual_plot(col, method=np.log1p)\ndual_plot('dinpkt')\ntotal['sinpkt_log1p'] = total['sinpkt'].apply(np.log1p)\ntotal['dinpkt_log1p'] = total['dinpkt'].apply(np.log1p)\n\n# slight improve in correlation\n# -0.1554536980867726 -0.030136042428744566 -0.16119699304378052 -0.07408113676641241\nprint(corr('sinpkt'), corr('dinpkt'), corr('sinpkt_log1p'), corr('dinpkt_log1p'))\ntotal.drop(['sinpkt', 'dinpkt'], axis=1, inplace= True)\n\"\"\"\n## sload & dload\n* sload: Source bits per second\n* dload: Destination bits per second\n\nThe values are really big and in bits.\n\"\"\"\ndual_plot('sload')\ndual_plot('dload')\ntotal['sload_log1p'] = total['sload'].apply(np.log1p)\ntotal['dload_log1p'] = total['dload'].apply(np.log1p)\n# 0.16524867685764016 -0.35216880416636837 0.3397788822586144 -0.5919440288535992\nprint(corr('sload'), corr('dload'), corr('sload_log1p'), corr('dload_log1p'))\ntotal.drop(['sload', 'dload'], axis=1, inplace=True)\n\"\"\"\n## sjit & djit\nSource and Destination jitter in mSec. Preprocessing didn't improve anything.\n\"\"\"\ndual_plot('sjit')\ndual_plot('djit')\n\"\"\"\n# Output\n\"\"\"\nfeatures.to_csv('features.csv', index=False)\ntrain = total[total['type']=='train'].drop(['type'], axis=1)\ntest = total[total['type']!='train'].drop(['type'], axis=1)\ntrain.to_csv('train.csv', index=False)\ntest.to_csv('test.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '22e30a85a25a89'}"}
{"id":"31447","text":"# 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\n\"\"\"\n# Video Games Sales Analysis (Beginner)\n\n![VideoGameSales](https:\/\/github.com\/Henri-debug\/Video_Games_Sales\/blob\/master\/Imgs%20for%20README\/Capa.png?raw=true)\n\n\"\"\"\n\"\"\"\n## Fields\n\n- Rank - Ranking of overall sales\n- Name - The games name\n- Platform - Platform of the games release (i.e. PC,PS4, etc.)\n- Year - Year of the game's release\n- Genre - Genre of the game\n- Publisher - Publisher of the game\n- NA_Sales - Sales in North America (in millions)\n- EU_Sales - Sales in Europe (in millions)\n- JP_Sales - Sales in Japan (in millions)\n- Other_Sales - Sales in the rest of the world (in millions)\n- Global_Sales - Total worldwide sales.\n\n\n## Credits\n- [Database Link](https:\/\/www.kaggle.com\/gregorut\/videogamesales)\n- [Database Author](https:\/\/www.kaggle.com\/gregorut)\n- [License](https:\/\/github.com\/GregorUT\/vgchartzScrape\/blob\/master\/LICENSE)\n\n# Questions\n\n- Which platform sold the most?\n- Which publisher had the most sales and in which genre did it sell the most?\n- What was the most successful game?\n\n\"\"\"\n\"\"\"\n# Libs\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Data Extraction\nvideogames_df = pd.read_csv(\"..\/input\/videogamesales\/vgsales.csv\")\nvideogames_df\n\"\"\"\n# Data Cleaning\n\"\"\"\nvideogames_df.info()\nvideogames_df.describe()\nvideogames_df.isnull().sum()\nvideogames_df = videogames_df.dropna()\nvideogames_df.isnull().sum()\nvideogames_df.describe()\nvideogames_df.Year = videogames_df.Year.astype(int)\n\"\"\"\n# Analysis\n\"\"\"\npublisher_salesDF = videogames_df.groupby('Publisher')[['NA_Sales','EU_Sales','JP_Sales','Other_Sales','Global_Sales']].sum()\npublisher_salesDF\npublisher_salesDF.max()\n\npublisher_salesDF.min()\n\"\"\"\n## Which publisher had the most sales and in which genre did it sell the most?\n\"\"\"\n# Find which publisher earned the most\n\npublisher_salesDF[publisher_salesDF['Global_Sales'] == publisher_salesDF['Global_Sales'].max()]\nnintendo_salesDF = videogames_df[videogames_df['Publisher'] == 'Nintendo']\nnintendo_salesDF\nglobalSales_genre = nintendo_salesDF.groupby('Genre')[['Global_Sales']].sum()\nglobalSales_genre\ngenre = ['Action','Adventure','Fighting','Misc','Platform','Puzzle','Racing','Role-Playing','Shooter','Simulation','Sports','Strategy']\nplt.figure(figsize=(15,10))\nsns.barplot(x = globalSales_genre['Global_Sales'], y = genre, palette='inferno')\nsns.color_palette(\"rocket\")\nplt.title(\"Nintendo Global Sales\", size = 20)\nplt.xlabel(\"Sales(In Millions)\",size = 15)\nplt.ylabel(\"Genre\", size = 15)\n\"\"\"\n## What was the most successful game?\n\n\"\"\"\nnames_games = videogames_df.groupby(['Name','Year','Publisher','Genre'])[['Global_Sales']].sum()\nnames_games\nnames_games.max()\nnames_games.min()\nnames_games[names_games['Global_Sales'] == names_games['Global_Sales'].max()]\n\"\"\"\n## Which platform sold the most?\n\"\"\"\nplatform_sales = videogames_df.groupby('Platform')[['Global_Sales']].sum()\nplatform_sales\nplatforms=['2600','3DO','3DS','DC','DS','GB','GBA','GC','GEN','GG','N64','NES','NG','PC','PCFX','PS','PS2','PS3','PS4','PSP','PSV','SAT','SCD','SNES','TG16','WS','Wii','WiiU','X360','XB','XOne']\n#create bar chart\nplt.figure(figsize=(15,10))\nsns.barplot(x = platform_sales['Global_Sales'], y = platforms, color='#2dfdd4')\nplt.title(\"Platforms Sales\", size = 20)\nplt.xlabel(\"Sales(In Millions)\",size = 15)\nplt.ylabel(\"Platform\", size = 15)","meta":"{'source': 'AI4Code', 'id': '39e356f9dee8c5'}"}
{"id":"122739","text":"import numpy as np\nimport pandas as pd\n\nimport os\n\"\"\"\n#### Train csv contains all individual masks. Goal of notebook is to combine all annotations into a single np array for training\n\"\"\"\ndf = pd.read_csv('..\/input\/sartorius-cell-instance-segmentation\/train.csv')\ndf.describe()\n\"\"\"\n#### All images are 520x704\n\"\"\"\nheight = 520\nwidth = 704\n\"\"\"\n# Make all Masks\n\"\"\"\n#Go through all images\nfor file_id in df['id'].unique():\n    file_name = f'{file_id}_mask.npy'\n    test_mask = np.zeros((height*width))\n    \n    masks = df[df['id']==file_id]['annotation']\n    \n    #Making all masks value 1 in np array\n    for mask in masks:\n        pixel = []\n        length = []\n        for i, val in enumerate(mask.split()):\n            if i % 2 == 0:\n                pixel.append(int(val)-1)\n            else:\n                length.append(int(val))\n        for pixel, length in zip(pixel,length):\n            test_mask[pixel-1:pixel+length] = 1\n    \n    test_mask = test_mask.reshape((height,width))\n    \n    np.save(file_name,test_mask)\n\"\"\"\n# Check Random Image and Mask\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport random\n\nroot = '..\/input\/sartorius-cell-instance-segmentation\/train\/'\nimages = os.listdir(root)\nimages = [x.split('.')[0] for x in images]\nindex=random.randint(0, len(images))\n\nfile_id = images[index]\n\nimage = root+file_id+'.png'\nmask = np.load(file_id+'_mask.npy')\n\nplt.figure(figsize = (15,10))\nplt.title(file_id)\nimg = mpimg.imread(image)\nimgplot = plt.imshow(img, cmap='gray')\nplt.show()\n\nplt.figure(figsize = (15,10))\nplt.imshow(mask, cmap='gray')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'e1ac11ca5fd983'}"}
{"id":"100359","text":"\"\"\"\n# Basic Text Regressor using Auto-Keras\n\nBasic implementatio for toxic comment challange.\n\"\"\"\n#test='test'\ntest='varza'\nsample=0.05\nimport sys\npackage_dir = '..\/input\/autokeras-april-2021'\nsys.path.insert(0, package_dir)\nimport matplotlib.pyplot as plt\nimport seaborn as sns, numpy as np\nfrom sklearn.linear_model import Ridge\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.stats import rankdata\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import KFold\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nimport autokeras as ak\n\"\"\"\nLoad data\n\"\"\"\npseudoscores_df = pd.read_csv(\"..\/input\/pseudoscores-jigsaw-toxic-comments\/validation_data_pseudo_scores_clasament.csv\",index_col=0)\n#https:\/\/www.kaggle.com\/crischir\/auto-keras-text-regression-cpu\/edit\/run\/85744222\nif test =='test':\n    pseudoscores_df=pseudoscores_df.sample(frac=sample)\npseudoscores_df['score']=pseudoscores_df['score']+2.90\npseudoscores_df.head(1)\ndf = pd.read_csv(\"..\/input\/jigsaw-score-augumentation\/jigsaw_train_hate_annotationprob.csv\",index_col=0)\nif test =='test':\n    df=df.sample(frac=sample)\ndf.describe()\nruddit_df = pd.read_csv(\"..\/input\/ruddit-jigsaw-dataset\/Dataset\/ruddit_with_text.csv\",index_col=0)\nif test =='test':\n    ruddit_df=ruddit_df.sample(frac=sample)\nruddit_df.head()\nruddit_df.describe()\ndf['target']=df['proposed_score3']+0.1*df['offensive_agreement_rating']\ndf[\"score_align\"]=(df['target']+0.0667)*(20.597967\/5.783141)\n\ndf['target']=df[\"score_align\"]\ndf= df[['text', 'target']]\npseudoscores_df.rename(columns={\"score\": 'target'}, inplace = True)\ndf1=pseudoscores_df[['text', 'target']]\nmermeleala_df=df.append(df1)\nmermeleala_df.describe()\nmermeleala_df.tail()\nlen(mermeleala_df)\nx = df['target']\nax = sns.displot(x, height=6, aspect=4, kde=True)\nplt.figure(figsize=(5,40))\nplt.show()\n#df[\"target\"]=df['target']+0.066618\n# ruddit_df['offensiveness_score']=ruddit_df['offensiveness_score']+0.889000\n\n# ruddit_df['offensiveness_score']=ruddit_df['offensiveness_score']*3.1091\nruddit_df.rename(columns={'txt':'text','offensiveness_score':'target'},inplace=True)\n\n\nruddit_df= ruddit_df[['text', 'target']]\n\"\"\"\nTrain test split. Not used\/usefull. \n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ntrain, valid = train_test_split(df, test_size=0.10)\n#valid, test = train_test_split(valid, test_size=0.3)\ndf_test=pd.read_csv(\"\/kaggle\/input\/jigsaw-toxic-severity-rating\/validation_data.csv\",index_col=0)\nif test =='test':\n    df_test=df_test.sample(frac=sample)\ncomments_to_score=pd.read_csv(\"\/kaggle\/input\/jigsaw-toxic-severity-rating\/comments_to_score.csv\",index_col=0)\nif test =='test':\n    comments_to_score=comments_to_score.sample(frac=sample)\nX_less_toxic =df_test.less_toxic.values\nX_more_toxic =df_test.more_toxic.values\nX_comments_to_score =comments_to_score.text.values\ntrain_data = train['text'].values\ntrain_target = train['target'].values\n\nvalid_data = valid['text'].values\nvalid_target = valid['target'].values\n\nprint(train_data.shape, train_target.shape)\nprint(valid_data.shape, valid_target.shape)\n\"\"\"\nSimple model 0.6745383286834064 \n\n* validation score with second conv block and 3 epoch:\n0.6651720472963997\n\n\"\"\"\n\"\"\"\nText regressor\n\"\"\"\n# Initialize the text regressor.\n#reg = ak.TextRegressor(overwrite=True, max_trials=2,directory='\/kaggle\/working\/models',loss='MeanAbsolutePercentageError',tuner='hyperband')  # It tries 10 different models.\nreg = ak.TextRegressor(overwrite=True, max_trials=2,directory='\/kaggle\/working\/models',loss='MeanAbsolutePercentageError')  # It tries 10 different models.\n# Feed the text regressor with training data.\nreg.fit(train_data, train_target, epochs=4)\n# Predict with the best model.\npredicted_y = reg.predict(valid_data)\n# Evaluate the best model with testing data.\nprint(reg.evaluate(valid_data, valid_target))\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np1 = reg.predict(X_less_toxic).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np2 = reg.predict(X_more_toxic).squeeze().tolist()#help(reg)\ndef compare(p1,p2):\n    z=0\n    k=0\n    n=len(p1)\n    for i in range(len(p1)):\n        if p1[i]< p2[i]:\n            z=z+1\n        else:\n            k=k+1\n            #print('nu')\n    print(z\/n)\n    return z\/n\n# Validation Accuracy\ncompare(p1,p2)\nscored_sub=reg.predict(X_comments_to_score).squeeze().tolist()\ncomments_to_score['score1_rank']=rankdata( scored_sub, method='ordinal') \ncomments_to_score['score1_df']=scored_sub\ncomments_to_score.head()\n\"\"\"\nPrepare a keras model. \n\"\"\"\ninput_node = ak.TextInput()\noutput_node = ak.TextToIntSequence()(input_node)\noutput_node = ak.Embedding()(output_node)\n# Use separable Conv layers in Keras.\noutput_node = ak.ConvBlock(separable=True)(output_node)\n#output_node = ak.ConvBlock(separable=True)(output_node)\noutput_node = ak.RegressionHead()(output_node)\nreg = ak.AutoModel(\n    inputs=input_node, outputs=output_node, overwrite=True, max_trials=3\n)\nreg.fit(train_data, train_target, epochs=7,validation_split=0.15)\n\"\"\"\nValidate results\n\"\"\"\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np3 = reg.predict(X_less_toxic).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np4 = reg.predict(X_more_toxic).squeeze().tolist()\n\n# Validation Accuracy\ncompare(p3,p4)\nscored_sub=reg.predict(X_comments_to_score).squeeze().tolist()\ncomments_to_score['score2_rank']=rankdata( scored_sub, method='ordinal') \ncomments_to_score['score2_df_agregat']=scored_sub\ndf1 = pd.read_csv(\"..\/input\/jigsaw-score-augumentation\/jigsaw_train_hate_annotationprob.csv\",index_col=0)\nif test =='test':\n    df1=df1.sample(frac=sample)\nvectorizor = TfidfVectorizer(analyzer='char_wb', max_df=0.8, min_df=1, ngram_range=(1, 3) )\n%%time\nX = vectorizor.fit_transform(df1['text'])\ntemp_score = df1[\"proposed_score\"].values\ny=np.around ( temp_score ,decimals = 2)\n%%time\nregressor=Ridge(alpha=0.7)\nregressor.fit(X, y)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['df_p0_score1_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['df_p0_score1']=temp_score\ncomments_to_score.head()\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np11 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np12 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p11,p12)\nvectorizor = TfidfVectorizer(analyzer='char_wb', max_df=0.6, min_df=1, ngram_range=(1, 4) )\n%%time\nX = vectorizor.fit_transform(df1['text'])\ntemp_score = df1[\"proposed_score2\"].values\ny=np.around ( temp_score ,decimals = 2)\n%%time\nregressor=Ridge(alpha=0.7)\nregressor.fit(X, y)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['df_p2_score1_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['df_p2_score1']=temp_score\ncomments_to_score.head()\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np11 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np12 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p11,p12)\nvectorizor = TfidfVectorizer(analyzer='char_wb', max_df=0.6, min_df=0.1, ngram_range=(1, 4) )\n%%time\nX = vectorizor.fit_transform(df1['text'])\ntemp_score = df1[\"proposed_score3\"].values\ny=np.around ( temp_score ,decimals = 2)\n%%time\nregressor=Ridge(alpha=0.7)\nregressor.fit(X, y)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['df_p3_score1_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['df_p3_score1']=temp_score\ncomments_to_score.head()\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np13 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np14 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p13,p14)\n\"\"\"\nRuddit ponderation\n\"\"\"\nruddit_df.head()\nvectorizor = TfidfVectorizer(analyzer='char_wb', max_df=0.8, min_df=1, ngram_range=(2, 5) )\n%%time\nX = vectorizor.fit_transform(ruddit_df['text'])\ntemp_score = ruddit_df[\"target\"].values\ny=np.around ( temp_score ,decimals = 3)\n%%time\nregressor=Ridge(alpha=0.5)\nregressor.fit(X, y)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['ruddit_score1_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['ruddit_score1']=temp_score\ncomments_to_score.head()\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np5 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np6 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p5,p6)\n\"\"\"\nFake dataset\n\"\"\"\n%%time\nX = vectorizor.fit_transform(mermeleala_df['text'])\ntemp_score = mermeleala_df[\"target\"].values\ny=np.around ( temp_score ,decimals = 3)\n%%time\nregressor=Ridge(alpha=0.5)\nregressor.fit(X, y)\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np7 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np8 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p5,p6)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['aggregated_score2_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['aggregated_score2']=temp_score\ncomments_to_score.head()\n\"\"\"\nAnother score\n\"\"\"\n%%time\nX = vectorizor.fit_transform(df['text'])\ntemp_score = df[\"target\"].values\ny=np.around ( temp_score ,decimals = 3)\n%%time\nregressor=Ridge(alpha=0.5)\nregressor.fit(X, y)\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np9 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np10 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p7,p8)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['df_score2_rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['dfscore2']=temp_score\ncomments_to_score.head()\n\"\"\"\nofensiveness\n\"\"\"\ndf.head()\nextend_df = pd.read_csv(\"..\/input\/jigsaw-score-augumentation\/jigsaw_train_hate_annotationprob.csv\",index_col=0)\nif test =='test':\n    extend_df=extend_df.sample(frac=sample)\n%%time\nX = vectorizor.fit_transform(extend_df['text'])\ntemp_score = extend_df[\"offensive_agreement_rating\"].values\ny=np.around ( temp_score ,decimals = 3)\n%%time\nregressor=Ridge(alpha=0.5)\nregressor.fit(X, y)\n#comments_to_score_set=vectorizor.transform(comments_to_score['text'])\n#preds = reg.predict(X_less_toxic).squeeze().tolist()\n#p1 = predictor.predict(X_less_toxic)\np11 = regressor.predict(vectorizor.transform(X_less_toxic)).squeeze().tolist()\n#p2 = predictor.predict(X_more_toxic)\np12 = regressor.predict(vectorizor.transform(X_more_toxic)).squeeze().tolist()\n# Validation Accuracy\ncompare(p9,p10)\ncomments_to_score_set=vectorizor.transform(comments_to_score['text'])\ntemp_score=regressor.predict(comments_to_score_set)\ncomments_to_score['df_score2_1rank']=rankdata( temp_score, method='ordinal')\ncomments_to_score['dfscore2_1']=temp_score\ncomments_to_score.head()\ncomments_to_score.head(50)\ncomments_to_score.columns\ncomments_to_score['grand_slam']=comments_to_score['score1_rank']+comments_to_score['score2_rank']+comments_to_score['ruddit_score1_rank']+comments_to_score['aggregated_score2_rank']+comments_to_score['df_score2_rank']+comments_to_score['df_score2_1rank']+comments_to_score['df_p0_score1_rank']+comments_to_score['df_p2_score1_rank']+comments_to_score['df_p3_score1_rank']\ncomments_to_score['grand_slam_ranks']=rankdata( comments_to_score['grand_slam'], method='ordinal')\n#comments_to_score['score']=scored_sub\nsubmission=comments_to_score.loc[:,['grand_slam_ranks']]\n\nsubmission.rename(columns={\"grand_slam_ranks\": 'score'}, inplace = True)\nsubmission.to_csv('submission.csv')\nsubmission.head()\n\"\"\"\nRuddit -dumb test\n\"\"\"\ncomments_to_score.to_csv('\/kaggle\/working\/comments_to_score.csv')\ndf_test.head()\ndf_test['p1']=p1\ndf_test['p2']=p2\ndf_test['p3']=p3\ndf_test['p4']=p4\ndf_test['p5']=p5\ndf_test['p6']=p6\ndf_test['p7']=p7\ndf_test['p8']=p8\ndf_test['p9']=p9\ndf_test['p10']=p10\n(df_test['p2']-df_test['p1']).sum()\n(df_test['p4']-df_test['p3']).sum()\n(df_test['p6']-df_test['p5']).sum()\n(df_test['p8']-df_test['p7']).sum()\n(df_test['p10']-df_test['p9']).sum()\n# submission=comments_to_score[['score']]\n# submission.to_csv('submission.csv')","meta":"{'source': 'AI4Code', 'id': 'b86bda7afe3ac3'}"}
{"id":"21951","text":"import os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nimport warnings\nwarnings.filterwarnings('ignore')\ndata = pd.read_csv('\/kaggle\/input\/drug-classification\/drug200.csv')\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ndata.shape\ndata.head()\ndata.isnull().sum()\ndata.isna().sum()\n\"\"\"\nNo missing or null values in data\n\n200 data variables and 6 features(including the label)\n\"\"\"\n\"\"\"\n## Feature analysis\n\"\"\"\ndata.info()\n\"\"\"\n## Age:\n### Age of the patient\n\"\"\"\nprint('Maximum age:',max(data['Age']))\nprint('Minimum age:',min(data['Age']))\nsb.distplot(data['Age'])\n\"\"\"\nAge ranges from 15 to 74\n\"\"\"\n\"\"\"\n## Sex:\n### Sex of the patient\n\"\"\"\ndata.Sex.value_counts()\nsb.countplot(x = data.Sex)\n\"\"\"\nSex ratio seems to be balanced.\n\nSince it is a categorical variable, we convert it to numeric using label encoder in python\n\"\"\"\n\"\"\"\n## BP:\n\n### Blood Pressure of patient\n\"\"\"\ndata.BP.value_counts()\nsb.countplot(x = data.BP)\n\"\"\"\nBP ratio seems to be balanced.\n\nSince it is a categorical variable, we convert it to numeric using label encoder in python\n\"\"\"\n\"\"\"\n## Cholesterol:\n### Cholesterol of the patient\n\"\"\"\ndata.Cholesterol.value_counts()\nsb.countplot(x = data.Cholesterol)\n\"\"\"\nCholesterol ratio seems to be balanced.\n\nSince it is a categorical variable, we convert it to numeric using label encoder in python\n\"\"\"\n\"\"\"\n## Na_to_K:\n### Sodium-Potassium ratio in patient's blood\n\"\"\"\nprint(\"Maximum Sodium-Potassium ratio:\",data.Na_to_K.max())\nprint(\"Minimum Sodium-Potassium ratio:\",data.Na_to_K.min())\nsb.distplot(data.Na_to_K)\n\"\"\"\nSodium-Potassium ratio ranges from 6.269 to 38.247\n\"\"\"\n\"\"\"\n## Drug:\n### Drug administered to the patient\n\"\"\"\ndata.Drug.value_counts()\nsb.countplot(data.Drug)\n\"\"\"\nDrug is the target column(value) or label.\n\"\"\"\n\"\"\"\n# Relationship between features and target value:\n\"\"\"\n\"\"\"\n## Age - Drug\n\"\"\"\nsb.swarmplot(x = \"Drug\", y = \"Age\",data = data)\nplt.legend(data.Drug.value_counts().index)\nplt.title(\"Age to Drug\")\nprint(\"Maximum Age for administering Drug A:\",data.Age[data.Drug == \"drugA\"].max())\nprint(\"Minimum Age for administering Drug B:\",data.Age[data.Drug == \"drugB\"].min())\n\"\"\"\nDrug A is administered to patients below 50 years.\n\nDrug B is administered to patients above 51 years.\n\"\"\"\n\"\"\"\n## Sex - Drug\n\"\"\"\nsex_drug = data.groupby(['Drug','Sex']).size().reset_index(name = 'Count')\nsb.barplot(x = 'Drug',y = 'Count', hue = 'Sex', data = sex_drug)\nplt.title('Sex to Drug')\n\"\"\"\nFrom this graph, we find Sex is not an important feature for classification.\n\"\"\"\n\"\"\"\n## BP - Drug\n\"\"\"\nBP_drug = data.groupby(['Drug','BP']).size().reset_index(name = 'Count')\nsb.barplot(x = 'Drug',y = 'Count', hue = 'BP', data = BP_drug)\nplt.title('BP to Drug')\n\"\"\"\nDrug A and Drug B is administered only for people who have HIGH blood pressure.\n\nDrug C is administered only for people who have LOW blood pressure.\n\nBP is an important feature for classification.\n\"\"\"\n\"\"\"\n## Cholesterol - Drug\n\"\"\"\nBP_drug = data.groupby(['Drug','Cholesterol']).size().reset_index(name = 'Count')\nsb.barplot(x = 'Drug',y = 'Count', hue = 'Cholesterol', data = BP_drug)\nplt.title('Cholesterol to Drug')\n\"\"\"\nDrug C is only administered for patients with HIGH Cholesterol.\n\nCholesterol is important feature to classify Drug C.\n\"\"\"\n\"\"\"\n## Na_to_K - Drug\n\"\"\"\nsb.swarmplot(x = \"Drug\", y = \"Na_to_K\",data = data)\nplt.title(\"Na_to_K - Drug\")\nprint(\"Minimum value of Na_to_K for Drug Y:\",data.Na_to_K[data.Drug == \"DrugY\"].min())\n\"\"\"\nPeople who have Na_to_K ratio is greater than 15, Drug Y is administered.\n\nWe can create a new feature from this feature for better classification of Drug Y.\n\"\"\"\n\"\"\"\n# Data preprocessing:\n\"\"\"\n\"\"\"\n## Feature Engineering\n\"\"\"\ndata['Na_to_K>15'] = np.where(data['Na_to_K'] > 15, 1, 0)\n\"\"\"\n## Label Encoding\n\"\"\"\nfrom sklearn import preprocessing \nlabel_encode = preprocessing.LabelEncoder() \nlabel_encode_list = ['Sex','BP','Cholesterol','Na_to_K>15','Drug']\n\nfor i in label_encode_list:\n    data[i] = label_encode.fit_transform(data[i])\ndata.head()\n\"\"\"\n# Train-Test split for the dataset\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx = data.drop(['Drug'], axis = 1)\ny = data.Drug\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42, shuffle = True)\n\n\ny_train = y_train.values.reshape(-1,1)\ny_test = y_test.values.reshape(-1,1)\nprint('x_train shape:', x_train.shape)\nprint('x_test shape:', x_test.shape)\nprint('y_train shape:', y_train.shape)\nprint('y_test shape:', y_test.shape)\n\"\"\"\nDataset is split into training and test data in 4:1 ratio\n\"\"\"\n\"\"\"\n# Model for the data\n\"\"\"\n\"\"\"\n## KNN Classifier\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\n\nknn.fit(x_train,y_train)\nknnPred = knn.predict(x_test)\nknn.score(x_test,y_test)\ngrid = {'n_neighbors':np.arange(1,120),\n        'p':np.arange(1,3),\n        'weights':['uniform','distance']\n       }\nknn_cv = GridSearchCV(knn,grid,cv=5)\nknn_cv.fit(x_train,y_train)\nknnCvPred = knn_cv.predict(x_test)\nknn_cv.score(x_test,y_test)\n\nknn_cv.best_params_\n\"\"\"\n## Decision Tree Classifier\n\"\"\"\nfrom sklearn import tree\ndt = tree.DecisionTreeClassifier(criterion = \"entropy\")\ndt.fit(x_train, y_train)\ndtPred = dt.predict(x_test)\ndt.score(x_test,y_test)\ngrid = {'criterion':['gini','entropy'],'max_depth':np.arange(1,5)}\ndt_cv = GridSearchCV(dt, grid, cv=5)\ndt_cv.fit(x_train, y_train)\ndtCvPred = dt_cv.predict(x_test)\nprint(dt_cv.best_params_)\ndt_cv.score(x_test,y_test)\nfrom sklearn.tree import export_graphviz\nimport graphviz\n\nclass_names = ['DrugY','drugC','drugX','drugA','drugB']\nfeature_names = ['Age','Sex','BP','Cholesterol','Na_to_K','Na_to_K>15']\n\ndot_data = export_graphviz(dt, out_file=None, filled=True, rounded=True,\n                                feature_names=feature_names,  \n                                class_names=class_names)\ngraph = graphviz.Source(dot_data)  \ngraph     \nfrom sklearn.tree import export_graphviz\nimport graphviz\n\nclass_names = ['DrugY','drugC','drugX','drugA','drugB']\nfeature_names = ['Age','Sex','BP','Cholesterol','Na_to_K','Na_to_K>15']\n\ndot_data = export_graphviz(dt_cv.best_estimator_, out_file=None, filled=True, rounded=True,\n                                feature_names=feature_names,  \n                                class_names=class_names)\ngraph = graphviz.Source(dot_data)  \ngraph     \n\"\"\"\n## Random Forest Classifier\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier(random_state = 42)\nrfc.fit(x_train, y_train)\nrfcPred = rfc.predict(x_test)\nprint(np.mean(cross_val_score(rfc, x_train, y_train, cv=5)))\nrfc.score(x_test,y_test)\ngrid = {'n_estimators':np.arange(100,1000,100),\n        'criterion':['gini','entropy'],\n       }\n\n\nrfc_cv = GridSearchCV(rfc, param_grid=grid, cv= 5)\nrfc_cv.fit(x_train, y_train)\nrfcCvPred = rfc_cv.predict(x_test)\nprint(rfc_cv.best_score_)\nprint(rfc_cv.best_params_)\nprint(rfc_cv.score(x_test,y_test))\n\"\"\"\n# Performance metrics of Models\n\n\"\"\"\n\"\"\"\n## Accuracy\n\n\"\"\"\n\"\"\"\n### Without GSCV\n\"\"\"\nacc_knn = knn.score(x_test,y_test)\nacc_dt = dt.score(x_test,y_test)\nacc_rfc = rfc.score(x_test,y_test)\nprint(acc_knn,acc_dt,acc_rfc)\n\"\"\"\n### With GSCV\n\"\"\"\nacc_cv_knn = knn_cv.score(x_test,y_test)\nacc_cv_dt = dt_cv.score(x_test,y_test)\nacc_cv_rfc = rfc_cv.score(x_test,y_test)\nprint(acc_cv_knn,acc_cv_dt,acc_cv_rfc)\n\"\"\"\n### Confusion Matrix Plot\n\"\"\"\n\"\"\"\n### Without GSCV\n\n\"\"\"\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn import metrics\nclass_names = ['DrugY','drugC','drugX','drugA','drugB']\n\ndispKnnConfMat = plot_confusion_matrix(knn, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndispKnnConfMat.ax_.set_title('Confusion Matrix for Knn')\n\ndispdtConfMat = plot_confusion_matrix(dt, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndispdtConfMat.ax_.set_title('Confusion Matrix for Decision Tree')\n\ndisprfcConfMat = plot_confusion_matrix(rfc, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndisprfcConfMat.ax_.set_title('Confusion Matrix for Random Forest Classifier')\nplt.show() \n\"\"\"\n### With GSCV\n\"\"\"\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn import metrics\nclass_names = ['DrugY','drugC','drugX','drugA','drugB']\n\ndispKnnConfMat = plot_confusion_matrix(knn_cv, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndispKnnConfMat.ax_.set_title('Confusion Matrix for Knn')\n\ndispdtConfMat = plot_confusion_matrix(dt_cv, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndispdtConfMat.ax_.set_title('Confusion Matrix for Decision Tree')\n\ndisprfcConfMat = plot_confusion_matrix(rfc_cv, x_test, y_test,cmap=plt.cm.Blues,display_labels = class_names)\ndisprfcConfMat.ax_.set_title('Confusion Matrix for Random Forest Classifier')\nplt.show() \n\"\"\"\n## Report\n\"\"\"\n\"\"\"\n### Without GSCV\n\"\"\"\nreport_knn = metrics.classification_report(y_test, knnPred,target_names=class_names)\nreport_dt = metrics.classification_report(y_test, dtPred,target_names=class_names)\nreport_rfc= metrics.classification_report(y_test, rfcPred,target_names=class_names)\nprint(report_knn,report_dt,report_rfc,sep = '\\n\\n')\n\"\"\"\n### with GSCV\n\"\"\"\nreport_knn = metrics.classification_report(y_test, knnCvPred,target_names=class_names)\nreport_dt = metrics.classification_report(y_test, dtCvPred,target_names=class_names)\nreport_rfc= metrics.classification_report(y_test, rfcCvPred,target_names=class_names)\nprint(report_knn,report_dt,report_rfc,sep = '\\n\\n')","meta":"{'source': 'AI4Code', 'id': '285d9823db2242'}"}
{"id":"3056","text":"\"\"\"\n# 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\n\"\"\"\nimport json, sys, random, os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport PIL\nimport seaborn as sns\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Activation\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D,ZeroPadding2D\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, LearningRateScheduler\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.initializers import glorot_uniform\nfrom tensorflow.keras.utils import plot_model\nfrom PIL import Image, ImageDraw \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\nimport cv2\nimport matplotlib.pyplot as plt\nfrom os import listdir\nimport time  \nimport math\nimport shutil\nfrom tqdm import tqdm\nfrom tensorflow.keras.preprocessing import image\n\n\"\"\"\n## 1.DATA PREPROCESSING AND DATA ANALYSIS\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n        rescale=1.\/255,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale = 1.\/255)\n\ntest_datagen = ImageDataGenerator(rescale = 1.\/255)\ntrain = train_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/train',\n        target_size=(400, 400),\n        batch_size=32,\n        class_mode='binary')\ntest = test_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/test',\n        target_size=(400, 400),\n        batch_size=32,\n        class_mode='binary')\nvalidation = val_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/valid',\n        target_size=(400, 400),\n        batch_size=32,\n        class_mode='binary')\nprint(train.class_indices)\nprint(test.class_indices)\nprint(validation.class_indices)\nplt.imshow(plt.imread(\"..\/input\/brats-2019-traintestvalid\/dataset\/test\/N1.jpeg\"))\n!pip install imutils\nIMG_SIZE = (224,224)\nimport imutils\nimg = cv2.imread('..\/input\/brats-2019-traintestvalid\/dataset\/test\/N2.jpeg')\nimg = cv2.resize(\n            img,\n            dsize=IMG_SIZE,\n            interpolation=cv2.INTER_CUBIC\n        )\ngray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\ngray = cv2.GaussianBlur(gray, (5, 5), 0)\n\n# threshold the image, then perform a series of erosions +\n# dilations to remove any small regions of noise\nthresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]\nthresh = cv2.erode(thresh, None, iterations=2)\nthresh = cv2.dilate(thresh, None, iterations=2)\n\n# find contours in thresholded image, then grab the largest one\ncnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\nc = max(cnts, key=cv2.contourArea)\n\n# find the extreme points\nextLeft = tuple(c[c[:, :, 0].argmin()][0])\nextRight = tuple(c[c[:, :, 0].argmax()][0])\nextTop = tuple(c[c[:, :, 1].argmin()][0])\nextBot = tuple(c[c[:, :, 1].argmax()][0])\n\n# add contour on the image\nimg_cnt = cv2.drawContours(img.copy(), [c], -1, (0, 255, 255), 4)\n\n# add extreme points\nimg_pnt = cv2.circle(img_cnt.copy(), extLeft, 8, (0, 0, 255), -1)\nimg_pnt = cv2.circle(img_pnt, extRight, 8, (0, 255, 0), -1)\nimg_pnt = cv2.circle(img_pnt, extTop, 8, (255, 0, 0), -1)\nimg_pnt = cv2.circle(img_pnt, extBot, 8, (255, 255, 0), -1)\n\n# crop\nADD_PIXELS = 0\nnew_img = img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS, extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()\nplt.figure(figsize=(15,6))\nplt.subplot(141)\nplt.imshow(img)\nplt.xticks([])\nplt.yticks([])\nplt.title('Step 1. Get the original image')\nplt.subplot(142)\nplt.imshow(img_cnt)\nplt.xticks([])\nplt.yticks([])\nplt.title('Step 2. Find the biggest contour')\nplt.subplot(143)\nplt.imshow(img_pnt)\nplt.xticks([])\nplt.yticks([])\nplt.title('Step 3. Find the extreme points')\nplt.subplot(144)\nplt.imshow(new_img)\nplt.xticks([])\nplt.yticks([])\nplt.title('Step 4. Crop the image')\nplt.show()\n\"\"\"\n## 2, BUILDING THE MODEL\n\"\"\"\n# early stopping\nes = EarlyStopping(monitor='val_accuracy', min_delta= 0.01 , patience= 5, verbose= 1, mode='auto')\nmodel = Sequential() \n\nmodel.add(Conv2D(filters=32, kernel_size= (3,3), activation= 'relu', input_shape=(400, 400,3)) )\n\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu' ))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu' ))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), activation='relu' ))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(units=512, activation='relu'))\nmodel.add(Dense(units=64, activation='relu'))\nmodel.add(Dense(units=1, activation='sigmoid'))\n\nmodel.compile(loss= \"binary_crossentropy\", optimizer='adam', metrics=['accuracy'] )\n \nmodel.summary()\nes = EarlyStopping(monitor='val_accuracy',min_delta= 0.01 ,  patience= 2, verbose= 2, mode='auto')\nmc = ModelCheckpoint(filepath=\"..\/kaggle\/working\/best_model.h5\",monitor='val_accuracy',save_best_only = True )\nmodel.fit(x=train,validation_data=validation,epochs=5,callbacks = [mc,es], steps_per_epoch=50)\npd.DataFrame(model.history.history)\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\nplt.figure(figsize=(12,10))\npd.DataFrame(model.history.history).plot(figsize=(15,8))\ndef predictor(location):\n    test_image=image.load_img(location,target_size=(400,400))\n    test_image=image.img_to_array(test_image)\n    test_image=np.expand_dims(test_image, axis=0)\n    result=model.predict(test_image)\n\n    if result[0][0] == 0:\n        \n        prediction = \"The MRI image is no of BRAIN TUMOR\"\n    else:\n        prediction = \"The MRI image is of BRAIN TUMOR\"\n    print(result[0][0])\n    return prediction\nplt.imshow(plt.imread(\"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1400.jpg\"))\npredictor(\"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1400.jpg\")\nimport PIL\nfig, axs = plt.subplots(2, 5, figsize=(20, 10))\nlst = [\"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1401.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1402.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1403.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1404.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1405.jpg\",\n       \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1400.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1401.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1402.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1403.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1404.jpg\"]\n\naxs[0][0].title.set_text(predictor(lst[0]))\naxs[0][0].imshow(PIL.Image.open(lst[0]))\naxs[0][1].title.set_text(predictor(lst[1]))\naxs[0][1].imshow(PIL.Image.open(lst[1])) \naxs[0][2].title.set_text(predictor(lst[2]))\naxs[0][2].imshow(PIL.Image.open(lst[2]))  \naxs[0][3].title.set_text(predictor(lst[3]))\naxs[0][3].imshow(PIL.Image.open(lst[3]))  \naxs[0][4].title.set_text(predictor(lst[4]))\naxs[0][4].imshow(PIL.Image.open(lst[4]))    \naxs[1][0].title.set_text(predictor(lst[5]))\naxs[1][0].imshow(PIL.Image.open(lst[5]))   \naxs[1][1].title.set_text(predictor(lst[6]))\naxs[1][1].imshow(PIL.Image.open(lst[6]))  \naxs[1][2].title.set_text(predictor(lst[7]))\naxs[1][2].imshow(PIL.Image.open(lst[7])) \naxs[1][3].title.set_text(predictor(lst[8]))\naxs[1][3].imshow(PIL.Image.open(lst[8]))  \naxs[1][4].title.set_text(predictor(lst[9]))\naxs[1][4].imshow(PIL.Image.open(lst[9]))\n\nfig.tight_layout()\n\"\"\"\n## 3. Transfer Learning for Better Accuracy\n\"\"\"\n\"\"\"\n<font color=\"green\">\nTransfer learning consists of taking features learned on one problem, and leveraging them on a new, similar problem. For instance, features from a model that has learned to identify racoons may be useful to kick-start a model meant to identify tanukis.\n\nTransfer learning is usually done for tasks where your dataset has too little data to train a full-scale model from scratch.\n\nA pre-trained model is a saved network that was previously trained on a large dataset, typically on a large-scale image-classification task. You either use the pretrained model as is or use transfer learning to customize this model to a given task.\n\nThe intuition behind transfer learning for image classification is that if a model is trained on a large and general enough dataset, this model will effectively serve as a generic model of the visual world. You can then take advantage of these learned feature maps without having to start from scratch by training a large model on a large dataset.\nFirst of all, we need repreprocess the images that can suit to our imported model.\n    \nYou will follow the general machine learning workflow.\n\n    1.Take layers from a previously trained model.\n\n    2.Freeze them, so as to avoid destroying any of the information they contain during future training rounds.\n\n    3.Add some new, trainable layers on top of the frozen layers. They will learn to turn the old features into predictions on a new dataset.\n\n    4.Train the new layers on your dataset.\n\"\"\"\nfrom tensorflow.keras.applications.mobilenet import MobileNet, preprocess_input\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n        preprocessing_function=preprocess_input,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True)\nval_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\ntest_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\ntrain = train_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/train',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\ntest = test_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/test',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\nvalidation = val_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/valid',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n        rescale=1.\/255,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale = 1.\/255)\n\ntest_datagen = ImageDataGenerator(rescale = 1.\/255)\ntrain = train_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/train',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\ntest = test_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/test',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\nvalidation = val_datagen.flow_from_directory(\n        '..\/input\/brats-2019-traintestvalid\/dataset\/valid',\n        target_size=(224, 224),\n        batch_size=32,\n        class_mode='binary')\n\"\"\"\n<font color=\"green\">\n1.Take layers from a previously trained model.\n\"\"\"\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import RMSprop\nbase_model = MobileNet(input_shape=(224, 224, 3),#we can specify the inpur shape with this parameter\n    include_top=False) # Do not include the ImageNet classifier at the top.)\n\"\"\"\n<font color=\"green\">\n2.Then, freeze the base model.\n\nIt is important to freeze the convolutional base before you compile and train the model. Freezing (by setting layer.trainable = False) prevents the weights in a given layer from being updated during training. MobileNet  has many layers, so setting the entire model's trainable flag to False will freeze all of them.\n\"\"\"\nbase_model.trainable = False # We freeze the training of the convolutions\nbase_model.summary()\n\"\"\"\n<font color=\"green\">\n3.Add some new, trainable layers on top of the frozen layers. \n\"\"\"\n# Flatten the output layer to 1 dimension\ncnn = Flatten()(base_model.output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\ncnn = Dense(units=1024, activation =\"relu\")(cnn)\n# Add a dropout rate of 0.2\ncnn = Dropout(0.2)(cnn)\n# Add a final sigmoid layer for classification\ncnn = Dense(units = 1, activation = \"sigmoid\")(cnn)\ncnn = Model( base_model.input, cnn)\ncnn.summary()\n\"\"\"\n<font color=\"green\">\n4.Train the new layers on your dataset.\n\"\"\"\ncnn.compile(optimizer = RMSprop(learning_rate=0.0001), \n              loss = 'binary_crossentropy', \n              metrics = ['accuracy'])\nes = EarlyStopping(monitor='val_accuracy',min_delta= 0.01 ,  patience= 2, verbose= 2, mode='auto')\nmc = ModelCheckpoint(filepath=\"..\/kaggle\/working\/best_modelwithtransferlearning.h5\",monitor='val_accuracy',save_best_only = True )\ncnn.fit(x=train,validation_data=validation,epochs=5,callbacks = [mc,es], steps_per_epoch=50)\nprint(cnn.evaluate(validation))\n\"\"\"\n<font color=\"green\">\nOur transfer model has nearly %98 accuracy compared to my own model. We saved this model during trainng and we will load this model,\n\"\"\"\nmodel_best = load_model(\"..\/kaggle\/working\/best_modelwithtransferlearning.h5\")\nmodel_best.evaluate(validation)\nvalidation.class_indices\ndef predictor(path):\n    img = image.load_img(path, target_size=(224,224),  )\n    i = image.img_to_array(img)\/255\n    input_arr = np.array([i])\n    input_arr.shape\n    pred = model.predict(input_arr)[0][0] \n    if pred > 0.5:\n        print(\"The MRI image is of BRAIN TUMOR\")\n    else:\n        print(\"The MRI image is of HEALTHY BRAIN WITHOUT TUMOR\")\n        \n\"\"\"\n<font color=\"green\">\nLets compare the predictions of both models with the test data. When we test two model with the same test data, as seen below the model with transfer learning preidict all of them correctly while the previous one make 3 of tehm fail prediction.\n\"\"\"\nfig, axs = plt.subplots(2, 5, figsize=(20, 10))\nlst = [\"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1401.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1402.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1403.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1404.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/yes\/y1405.jpg\",\n       \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1400.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1401.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1402.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1403.jpg\",\n      \"..\/input\/brats-2019-traintestvalid\/dataset\/valid\/no\/no1404.jpg\"]\n\naxs[0][0].title.set_text(predictor(lst[0]))\naxs[0][0].imshow(PIL.Image.open(lst[0]))\naxs[0][1].title.set_text(predictor(lst[1]))\naxs[0][1].imshow(PIL.Image.open(lst[1])) \naxs[0][2].title.set_text(predictor(lst[2]))\naxs[0][2].imshow(PIL.Image.open(lst[2]))  \naxs[0][3].title.set_text(predictor(lst[3]))\naxs[0][3].imshow(PIL.Image.open(lst[3]))  \naxs[0][4].title.set_text(predictor(lst[4]))\naxs[0][4].imshow(PIL.Image.open(lst[4]))    \naxs[1][0].title.set_text(predictor(lst[5]))\naxs[1][0].imshow(PIL.Image.open(lst[5]))   \naxs[1][1].title.set_text(predictor(lst[6]))\naxs[1][1].imshow(PIL.Image.open(lst[6]))  \naxs[1][2].title.set_text(predictor(lst[7]))\naxs[1][2].imshow(PIL.Image.open(lst[7])) \naxs[1][3].title.set_text(predictor(lst[8]))\naxs[1][3].imshow(PIL.Image.open(lst[8]))  \naxs[1][4].title.set_text(predictor(lst[9]))\naxs[1][4].imshow(PIL.Image.open(lst[9]))\nfig.tight_layout()","meta":"{'source': 'AI4Code', 'id': '05c96d3dca2067'}"}
{"id":"44406","text":"# 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\n\"\"\"\nJust a quick demo to test torchtext lib and my first experience with NLP.\n\"\"\"\ntext = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-severity-rating\/comments_to_score.csv')\nlabels = pd.read_csv('\/kaggle\/input\/jigsaw-toxic-severity-rating\/validation_data.csv')\nnew_labels = np.concatenate((np.zeros(len(labels['less_toxic'])), \n                             np.ones(len(labels['more_toxic']))))\nnew_comments = np.concatenate((labels['less_toxic'].values, \n                               labels['more_toxic'].values))\n\ndataset = np.stack((new_comments, new_labels), axis=1)\n\ndataset\nfrom torchtext.data.utils import get_tokenizer\nfrom torchtext.vocab import build_vocab_from_iterator\n\ntokenizer = get_tokenizer('basic_english')\n\ndef yield_tokens(data_iter):\n    for text, _ in data_iter:\n        yield tokenizer(text)\n        \nvocab = build_vocab_from_iterator(yield_tokens(dataset))\nvocab.set_default_index(1)\nprint(vocab.get_default_index())\ntext_pipeline = lambda x: vocab(tokenizer(x))\nlabel_pipeline = lambda x: float(x)\n\ntext_pipeline('Hello world')\nimport torch\nfrom torch.utils.data import DataLoader\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef collate_batch(batch):\n    label_list, text_list, offsets = [], [], [0]\n    for (_text, _label) in batch:\n        label_list.append(_label)\n        processed_text = torch.tensor(text_pipeline(_text), dtype=torch.int64)\n        text_list.append(processed_text)\n        offsets.append(processed_text.size(0))\n    label_list = torch.tensor(label_list, dtype=torch.float)\n    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)\n    text_list = torch.cat(text_list)\n    return label_list.unsqueeze(1).to(device), text_list.to(device), offsets.to(device)\n\ndataloader = DataLoader(dataset, batch_size=4, shuffle=True, collate_fn=collate_batch)\n\nnext(iter(dataloader))\nimport time\n\ndef train(dataloader):\n    model.train()\n    total_acc, total_count = 0, 0\n    log_interval = 500\n    start_time = time.time()\n\n    for idx, (label, text, offsets) in enumerate(dataloader):\n        optimizer.zero_grad()\n        predicted_label = model(text, offsets)\n        loss = criterion(predicted_label, label)\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)\n        optimizer.step()\n        total_acc += ((predicted_label > 0.5).float() == label).sum().item()\n        total_count += label.size(0)\n        if idx % log_interval == 0 and idx > 0:\n            elapsed = time.time() - start_time\n            print('| epoch {:3d} | {:5d}\/{:5d} batches '\n                  '| accuracy {:8.3f}'.format(epoch, idx, len(dataloader),\n                                              total_acc\/total_count))\n            total_acc, total_count = 0, 0\n            start_time = time.time()\n\ndef evaluate(dataloader):\n    model.eval()\n    total_acc, total_count = 0, 0\n\n    with torch.no_grad():\n        for idx, (label, text, offsets) in enumerate(dataloader):\n            predicted_label = model(text, offsets)\n            loss = criterion(predicted_label, label)\n            total_acc += ((predicted_label > 0.5).float() == label).sum().item()\n            total_count += label.size(0)\n    return total_acc\/total_count\nfrom torch import nn\n\nclass CustomModel(nn.Module):\n    def __init__(self, vocab_size, embed_dim):\n        super(CustomModel, self).__init__()\n        self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)\n        self.fc_1 = nn.Linear(embed_dim, 32)\n        self.relu = nn.ReLU()\n        self.fc_2 = nn.Linear(32, 1)\n        self.init_weights()\n        \n    def init_weights(self):\n        initrange = 0.5\n        self.embedding.weight.data.uniform_(-initrange, initrange)\n        self.fc_1.weight.data.uniform_(-initrange,initrange)\n        self.fc_1.bias.data.zero_()\n        self.fc_2.weight.data.uniform_(-initrange,initrange)\n        self.fc_2.bias.data.zero_()\n        \n    def forward(self, text, offsets):\n        embedded = self.embedding(text, offsets)\n        embedded = self.fc_1(embedded)\n        embedded = self.relu(embedded)\n        return torch.sigmoid(self.fc_2(embedded))\n    \nvocab_size = len(vocab)\nemsize = 128\nmodel = CustomModel(vocab_size, emsize).to(device)\nfrom torch.utils.data.dataset import random_split\nfrom torchtext.data.functional import to_map_style_dataset\nfrom sklearn.model_selection import train_test_split\n\nEPOCHS = 10 \nLR = 1.\nBATCH_SIZE = 64 \n  \ncriterion = torch.nn.BCELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=LR)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, .01, gamma=0.1)\ntotal_accu = None\ntrain_iter, test_iter = train_test_split(dataset, test_size=0.1, train_size=0.9, random_state=42)\ntrain_dataset = to_map_style_dataset(train_iter)\ntest_dataset = to_map_style_dataset(test_iter)\n\ntrain_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE,\n                              shuffle=True, collate_fn=collate_batch)\nvalid_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE,\n                              shuffle=True, collate_fn=collate_batch)\n\nfor epoch in range(1, EPOCHS + 1):\n    epoch_start_time = time.time()\n    train(train_dataloader)\n    accu_val = evaluate(valid_dataloader)\n    if total_accu is not None and total_accu > accu_val:\n        scheduler.step()\n    else:\n        total_accu = accu_val\n    \n    print('| end of epoch {:3d} | time: {:5.2f}s | valid accuracy {:8.3f} '\n          .format(epoch, time.time() - epoch_start_time, accu_val))\ndef predict(text, text_pipeline):\n    with torch.no_grad():\n        text = torch.tensor(text_pipeline(text), dtype=torch.int64).to(device)\n        offsets = [0]\n        offsets.append(text.size(0))\n        offsets = torch.tensor(offsets[:-1]).cumsum(dim=0).to(device)\n        \n        output = model(text, offsets)\n        return output\n\ntext.text=text.text.astype(str)\n    \nfor index, i in enumerate(text['text']):\n    item = predict(i, text_pipeline).item()\n    text.at[index, 'score'] = item\n    \ntext.head()\nsub_cv = text.drop('text', axis=1)\nsub_cv.to_csv('submission.csv', index=False)\n\"\"\"\nIf you liked it or found useful - plz UV ;) \n\nPS: I would like to learn more about NLP, so please share some wisdom or guidance.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '51dd8ffc817311'}"}
{"id":"80096","text":"\"\"\" # Simulaci\u00f3n del avance del COVID_19 en Madrid ## Datos: * Tama\u00f1o poblaci\u00f3n Madrid: 6.6M * Camas hospitales por capita: 0.3% * Porcentage casos asintomaticos: 17% (15.5-20.2) ([referencia](https:\/\/www.eurosurveillance.org\/content\/10.2807\/1560-7917.ES.2020.25.10.2000180)) * Mortalidad: 3.4% ([referencia](https:\/\/www.worldometers.info\/coronavirus\/coronavirus-death-rate\/)) * Casos que requieren UCI: 5% (a partir de las estad\u00edsticas publicadas para Espa\u00f1a). * Poblaci\u00f3n de Madrid por debajo de los 50 a\u00f1os: 68% ([INE](https:\/\/www.ine.es\/jaxi\/Tabla.htm?path=\/t20\/e245\/p05\/a2011\/l0\/&file=00028001.px&L=0)) \"\"\" \"\"\" ## Modelado: * Cada enfermo genera un n\u00famero de boletos diario que se sortean entre la poblaci\u00f3n. * Si alguno de esos boletos le toca a una persona sana, esta se infecta. * Los enfermos pueden estar en 4 estados: * incubando * enfermo asintomatico (asymptomatic) * enfermo leve (mild) * enfermo grave (severe), que requiere UCI * Solo los enfermos que est\u00e1n incubando la enfermedad y los asintomaticos pueden transmitir la enfermedad. Se supone que para el resto, la probabilidad de contagio se vuelve 0 al ser puestos en cuarentena. * Para cada tipo de enfermo, se contemplan tiempos medios de convalecencia y varianzas distintos. * Los periodos de convalecencia siguen una distribuci\u00f3n de [Gauss inversa](https:\/\/en.wikipedia.org\/wiki\/Inverse_Gaussian_distribution). * Los periodos de incubaci\u00f3n siguen una distribuci\u00f3n [log-normal](https:\/\/en.wikipedia.org\/wiki\/Log-normal_distribution). * Durante el periodo de incubaci\u00f3n, solo se puede contagiar la enfermedad en los \u00faltimos d\u00edas. El n\u00famero de boletos se calcula seg\u00fan la siguiente formula: $b = r^{t_1-t}*(t-t_0)\/(t_1-t_0)$, siendo $t_0$ el momento en el que la persona se contagia, $t_1$ el momento en el que desarrolla la enfermedad y $r$ un parametro de amortiguamiento. Por defecto se calcula, suponiendo que el n\u00famero de boletos se dobla cada dos d\u00edas. * Solo los enfermos graves pueden morir. * Una vez un enfermo se recupera, se vuelve immune y no puede adquirir o transmitir la enfermedad de nuevo. * El modelo contempla la posibilidad de aplicar distintas estrategias para paliar los efectos de la epidemia. * El modelado se hace en funci\u00f3n a macroparametros (no a individuos) por lo que su validez sera mayor cuando los n\u00fameros de enfermos, infectados, etc., [sean altos](https:\/\/es.wikipedia.org\/wiki\/Ley_de_los_grandes_n%C3%BAmeros) y tendra poca precisi\u00f3n cuando estos sean bajos debido a la aleatoriedad. ## Parametrizaci\u00f3n: Estos son los parametros utilizados en la modelizaci\u00f3n y los valores por defecto asignados: * `population_size=6.662e6` - poblacion de Madrid * `asymptomatic_ratio=0.17` - porcentage de enfermos que pasan la enfermedad sin manifestar ning\u00fan s\u00edntoma. * `severe_ratio=0.05` - porcentage de enfermos que en situaci\u00f3n critca que necesitan ser ingresados en la UCI. * `mortality_ratio=0.035` - porcentage de enfermos que acaban muriendo * `asymptomatic_convalescent_period_mean=2` - tiempo medio de convalecencia para enfermos asintomaticos, notese que este es el periodo medio durante el cual un enfermos asintomatico puede seguir transmitiendo el virus. * `asymptomatic_convalescent_period_variance=3` - varianza * `mild_convalescent_period_mean=8` - tiempo medio de convalecencia para enfermos que no requiren UCI. * `mild_convalescent_period_variance=4` - varianza * `severe_convalescent_period_mean=16` - tiempo medio de convalecencia para enfermos que requieren UCI. * `severe_convalescent_period_variance=8` - varianza * `daily_transmission_rate=2.0` - posibilidades de contagio diarias (boletos) generadas por un enfermo que no est\u00e1 en cuarentena. El valor por defecto se ha ajustado para reproducir la velocidad de contagio de Espa\u00f1a, +40% diario. * `preinfectious_half_period=2` - para personas en periodo de incubaci\u00f3n, tiempo medio en el cual se duplican los boletos de contagio * `incubation_mean=5` - tiempo medio de incubaci\u00f3n * `incubation_variance=7` - varianza * `infected_seed=10` - n\u00famero de infectados iniciales * `days=100` - tama\u00f1o de la simulaci\u00f3n * `ticks_per_day=4` - n\u00famero de cortes por d\u00eda, para aumentar la precisi\u00f3n de la integraci\u00f3n. ## Variables de salida El simulador calcula y devuelve una tabla con las siguientes columnas: * `day` - tiempo transcurrido en dias (numero de punto flotante) * `infectious` - n\u00famero de personas infecciosas * `asymptomatic` - n\u00famero de enfermos asintomaticos * `mild` - numero de enfermos leves * `severe` - n\u00famero de enfermos graves (UCI) * `immune` - n\u00famero de personas immunes * `infected` - n\u00famero de personas infectadas (incubando + enfermas + asintom\u00e1ticas) * `death` - n\u00famero acumulado de muertos * `healthy` - n\u00famero de personas sanas * `incubating` - n\u00famero de personas incubando la enfermedad * `sick` - n\u00famero de personas enfermas (no se contabilizan aqu\u00ed los enfermos asintom\u00e1ticos) * `ever_sick`- n\u00famero de personas que est\u00e1n o han estado enfermas * `new_sick` - n\u00famero de personas que caen enfermas en el intervalo al que referencia la fila de la tabla * `infectable` - personas susceptibles de ser infectadas (las que no son ni inmunes, ni est\u00e1n infectadas, ni han muerto) * `velocity` - velocidad a la que aumenta el n\u00famero de personas infectadas en el espacio logaritmico. * `sick_velocity` - velocidad a la que aumenta el n\u00famero de personas enfermas. * `ever_sick_velocity` - velocidad a la que aumenta el n\u00famero de personas que han estado alguna vez enfermas * `status` - al simular estrategias de contenci\u00f3n de la epidemia, este campo indica la etapa. ## Programaci\u00f3n de la simulaci\u00f3n \"\"\" import io import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy.optimize from math import erf, log, exp, sqrt from scipy.stats import invgauss \"\"\" ### C\u00e1lculo de distribuciones de probabilidad ([CDF](https:\/\/en.wikipedia.org\/wiki\/Cumulative_distribution_function)) \"\"\" def lognorm_cdf(mean, var, n_days=20, ticks_per_day=10): sigma = sqrt(log(var\/mean**2 + 1)) mu = log(mean) - 0.5*sigma**2 sqrt2sigma_inv = 1.0 \/ (sqrt(2) * sigma) def cdf(x): return (0.5 + 0.5*erf(sqrt2sigma_inv*(log(x) - mu)) if x > 0 else 0) n_ticks = n_days * ticks_per_day days = list([i\/ticks_per_day for i in range(n_ticks)]) acu = list([cdf(d) for d in days]) return acu def invgauss_cdf(mean, var, n_days=20, ticks_per_day=10): la = mean**3\/var mu = mean\/la x = list([i\/ticks_per_day for i in range(n_days*ticks_per_day)]) return invgauss.cdf(x, mu, scale=la) \"\"\" ### El simulador \"\"\" class SIRwhatever: def __init__(self, population_size=6.662e6, asymptomatic_ratio=0.17, severe_ratio=0.05, #hospital_beds_ratio=0.003, #no_bed_death_rate_multiplier=2, mortality_ratio=0.035, asymptomatic_convalescent_period_mean=2, asymptomatic_convalescent_period_variance=3, mild_convalescent_period_mean=8, mild_convalescent_period_variance=4, severe_convalescent_period_mean=16, severe_convalescent_period_variance=8, daily_transmission_rate=2.0, preinfectious_half_period=2, incubation_mean=5, incubation_variance=7, herd_immunity_ratio=0.0, days = 100, ticks_per_day = 4, infected_seed = 10, observation_delay = 0, quiet = False): self.population_size = population_size self.asymptomatic_ratio = asymptomatic_ratio self.severe_ratio = severe_ratio self.mortality_ratio = mortality_ratio self.daily_transmission_rate = daily_transmission_rate self.days = days self.ticks_per_day = ticks_per_day self.infected_seed = infected_seed self.incubation_mean = incubation_mean self.incubation_variance = incubation_variance self.preinfectious_half_period = preinfectious_half_period self.mild_convalescent_period_mean = mild_convalescent_period_mean self.mild_convalescent_period_variance = mild_convalescent_period_variance self.severe_convalescent_period_mean = severe_convalescent_period_mean self.severe_convalescent_period_variance = severe_convalescent_period_variance self.asymptomatic_convalescent_period_mean = asymptomatic_convalescent_period_mean self.asymptomatic_convalescent_period_variance = asymptomatic_convalescent_period_variance self.herd_immunity_ratio=herd_immunity_ratio self.observation_delay=observation_delay self.quiet=quiet def strategy(self, t, **kargs): return 'normal' # can I do nothing? def print_extrema(self, i, t, **kargs): if self.quiet: return if t >= 2: # we ignore the first two days in order to let the model stabilize for k in sorted(kargs.keys()): extreme = None v = kargs[k] if v[i-2] < v[i-1]: if v[i-1] > v[i]: extreme = '\u25b2' elif (v[i-1] < v[i]) and (v[i-2] > v[i-1]): extreme = '\u25bc' if extreme: line = \"%s day: %f, %s: %f\" % (extreme, t, k, v[i-1]) if k.startswith('new_'): line += \", %s: %f\" % (k[4:], kargs[k[4:]][i-1]) if (\"ever_\" + k) in kargs.keys(): line += \", ever_%s: %f\" % (k, kargs[\"ever_\" + k][i-1]) print(line) def run(self): ticks = self.days * self.ticks_per_day # loop iterations Dt = 1 \/ self.ticks_per_day z = np.zeros(ticks) healthy = z.copy() # people that is not infected death = z.copy() # acumulated deaths incubating = z.copy() # infected in the incubation stage infected = z.copy() # number of currently infected persons velocity = z.copy() # contagion velocity sick = z.copy() # people with desease simptoms new_sick = z.copy() # new people getting sick at the tick sick_velocity = z.copy() # velocity of sick cases appearing ever_sick = z.copy() # people that has ever been sick ever_sick_velocity = z.copy() # velocity of ever sick severe = z.copy() # people in severe condition mild = z.copy() # people in mild condition asymptomatic = z.copy() # infected people not showing symptoms infectious = z.copy() # infected people that is able to transmit the disease infectable = z.copy() # people that can still get the dissease symptomatic = z.copy() # sick people showing symptoms new_symptomatic = z.copy() # new people getting symptoms at the tick symptomatic_velocity = z.copy() # velocity of symptomatic cases appearing ever_symptomatic = z.copy() # people that have ever had symptoms ever_symptomatic_velocity = z.copy() # velocity of ever symptomatic cases appearing observed_ever_symptomatic = z.copy() # people that has ever been symptomatic and observed observed_ever_symptomatic_velocity = z.copy() # velocity of observed ever symptomatic # new_sick_velocity = z.copy() # velocity of new sick day = z.copy() immune = np.full(ticks, # people that has healed from the disease self.herd_immunity_ratio*self.population_size) status = list(['normal' for i in range(ticks)]) # Here the probability distributions are tabled and cached. incubation_cdf = lognorm_cdf(self.incubation_mean, self.incubation_variance, ticks_per_day = self.ticks_per_day, n_days=self.days) mild_convalescent_period_cdf = invgauss_cdf(self.mild_convalescent_period_mean, self.mild_convalescent_period_variance, ticks_per_day = self.ticks_per_day, n_days=self.days) severe_convalescent_period_cdf = invgauss_cdf(self.severe_convalescent_period_mean, self.severe_convalescent_period_variance, ticks_per_day = self.ticks_per_day, n_days=self.days) asymptomatic_convalescent_period_cdf = invgauss_cdf(self.asymptomatic_convalescent_period_mean, self.asymptomatic_convalescent_period_variance, ticks_per_day = self.ticks_per_day, n_days=self.days) preinfection_amortiguation_rate = 0.5**(1.0\/(self.preinfectious_half_period * self.ticks_per_day)) for i in range(ticks): ps = self.population_size t = i * Dt day[i] = t # For convenience, we also store the time # Number of coupons an infectious person generates at his maximum transmission_rate = self.daily_transmission_rate \/ self.ticks_per_day # Every infectious person gives away a number of coupons # everyday (actually, every tick) coupons = infectious[i] * transmission_rate # A single player may get several coupons, so we need to calculate the probability # that has a player of at least getting a coupon. We do it calculating first the # probability of not getting any coupon at all. p_contagied = 1 - exp(-coupons\/ps) # We can calculate it using an aproximation # in order to avoid numerical inestabilities # It works because ps is quite big # p_contagied = 1 - ((ps - 1)\/ps) ** coupons # probability of somebody # # not getting any ticket # And how many infectable persons do we have to play today? players = ps if i == 0: d_infected = self.infected_seed else: players -= infected[i-1] + immune[i-1] + death[i-1] d_infected = players * p_contagied # number of persons that have # been infected today infectable[i] = players - d_infected # Spread the infected over the following days, recording when they are going # to get sick filling new_sick for j in range(i+1, ticks): t1 = j - i # time elapsed since the contagion cdf0 = incubation_cdf[t1 - 1] if cdf0 == 1.0: break cdf1 = incubation_cdf[t1] d_new_sick = d_infected * (cdf1 - cdf0) new_sick[j] += d_new_sick incubating[j-1] += d_infected*(1-cdf0) # Here we also fill infectious which counts how many people is able # to generate coupons for k in range(j, i+1, -1): preinfection_rate = preinfection_amortiguation_rate**(j-k) * (k-i)\/(j-i) if preinfection_rate < 1e-4: break infectious[k] += d_new_sick * preinfection_rate # Now, we see what happens which people getting sick right now. new_sick_i = new_sick[i] # How many is there in every class? d_asymptomatic = new_sick_i * self.asymptomatic_ratio d_severe = new_sick_i * self.severe_ratio d_mild = new_sick_i - d_asymptomatic - d_severe new_symptomatic[i] = new_sick_i - d_asymptomatic # Only the severyly ill can die, so we calculate and adjusted # mortality ratio just for those severe_mortality_ratio = self.mortality_ratio \/ self.severe_ratio # The future of those getting ill today is set in stone, so we can fill # the asymptomatic, mild, severe, imune, death until the end of time for them. for j in range(i, ticks): t1 = j - i asymptomatic_cdf0=asymptomatic_convalescent_period_cdf[t1] mild_cdf0=mild_convalescent_period_cdf[t1] severe_cdf0=severe_convalescent_period_cdf[t1] severe[j] += (1-severe_cdf0)*d_severe mild[j] += (1-mild_cdf0)*d_mild asymptomatic[j] += (1-asymptomatic_cdf0)*d_asymptomatic immune[j] += ((1-severe_mortality_ratio)*severe_cdf0*d_severe + mild_cdf0*d_mild + asymptomatic_cdf0*d_asymptomatic) death[j] += severe_mortality_ratio*severe_cdf0*d_severe infectious[j] += (1-asymptomatic_cdf0)*d_asymptomatic # infected, sick and healthy are just combinations of other parameters # we keep for convenience. infected[i] = asymptomatic[i] + mild[i] + severe[i] + incubating[i] symptomatic[i] = mild[i] + severe[i] sick[i] = symptomatic[i] + asymptomatic[i] healthy[i] = infectable[i] + immune[i] # Finally, also for convenience, we calculate the velocities for some parameters. # In this context, velocity is the increase per time unit of some parameter in # the exponencial space: # velocity(a) = exp(log(a[i]) - log(a[i-1])) = a[i] \/ a[i-1] if i == 0: velocity[i] = 0 sick_velocity[i] = 0 ever_sick[i] = new_sick[0] ever_sick_velocity[i] = 0 ever_symptomatic[i] = 0 else: velocity[i] = ((infected[i]\/infected[i-1])**self.ticks_per_day - 1) sick_velocity[i] = (((sick[i]+1)\/(sick[i-1]+1))**self.ticks_per_day - 1) ever_sick[i] = ever_sick[i-1] + new_sick[i] ever_sick_velocity[i] = (((ever_sick[i] + 1) \/ (ever_sick[i-1] + 1))**self.ticks_per_day - 1) # new_sick_velocity[i] = (((new_sick[i] + 1) \/ # (new_sick[i-1] + 1))**self.ticks_per_day - 1) symptomatic_velocity[i] = (((symptomatic[i]+1)\/(symptomatic[i-1]+1)) ** self.ticks_per_day - 1) ever_symptomatic[i] = ever_symptomatic[i-1] + new_symptomatic[i] ever_symptomatic_velocity[i] = (((ever_symptomatic[i]+1) \/ (ever_symptomatic[i-1]+1)) ** self.ticks_per_day - 1) observation_delay_ticks = self.observation_delay * self.ticks_per_day if i >= observation_delay_ticks: observed_ever_symptomatic[i] = ever_symptomatic[i-observation_delay_ticks] observed_ever_symptomatic_velocity[i] = ever_symptomatic_velocity[i-observation_delay_ticks] self.print_extrema(i, t=t, sick=sick, new_sick=new_sick, ever_sick=ever_sick, severe=severe, symptomatic=symptomatic, ever_symptomatic=ever_symptomatic, new_symptomatic=new_symptomatic, asymptomatic=asymptomatic, infected=infected, incubating=incubating, infectious=infectious) # This method call allows us to simulate external actions over # the model: The Goberment! status[i] = self.strategy(t=t, sick=sick[i], ever_sick=ever_sick[i], sick_velocity=sick_velocity[i], new_sick=new_sick[i]*self.ticks_per_day, symptomatic=symptomatic[i], ever_symptomatic=ever_symptomatic[i], observed_ever_symptomatic=observed_ever_symptomatic[i], symptomatic_velocity=symptomatic_velocity[i], observed_ever_symptomatic_velocity=observed_ever_symptomatic_velocity[i], new_symptomatic=new_symptomatic[i]*self.ticks_per_day, infectious=infectious[i], infectable=infectable[i]) if i > 0 and status[i] != status[i-1] and not self.quiet: print((\"status flip: %s -> %s, day: %f, \" + \"sick: %f, daily_new_sick: %f, ever_sick: %f, \"+ \"symptomatic: %f, daily_new_symptomatic: %f, ever_symptomatic: %f, \"+ \"observed_ever_symptomatic: %f, \"+ \"infectious: %f, severe: %f, immune: %f, death: %f\") % (status[i-1], status[i], t, sick[i], new_sick[i]*self.ticks_per_day, ever_sick[i], symptomatic[i], new_symptomatic[i]*self.ticks_per_day, ever_symptomatic[i], observed_ever_symptomatic[i], infectious[i], severe[i], immune[i], death[i])) return pd.DataFrame({'day': day, 'infectious': infectious, 'asymptomatic': asymptomatic, 'symptomatic': symptomatic, 'mild': mild, 'severe': severe, 'immune': immune, 'infected': infected, 'death': death, 'healthy': healthy, 'incubating': incubating, 'sick': sick, 'ever_sick': ever_sick, 'new_sick': new_sick, 'ever_symptomatic': ever_symptomatic, 'new_symptomatic': new_symptomatic, 'infectable': infectable, 'velocity': velocity, 'sick_velocity': sick_velocity, 'ever_sick_velocity': ever_sick_velocity, 'symptomatic_velocity': symptomatic_velocity, 'ever_symptomatic_velocity': ever_symptomatic_velocity, 'observed_ever_symptomatic': observed_ever_symptomatic, 'observed_ever_symptomatic_velocity': observed_ever_symptomatic_velocity, 'status': status }) \"\"\" # Evaluaci\u00f3n Ahora que tenemos un programa que es capaz de simular el avance de la epidemia, vamos a utilizarlo para similar diversos escenarios en cada uno de los cuales seguiremos una linea de acci\u00f3n distinta. ## Caso 1: No hacemos nada Este es el caso de referencia, que pasar\u00eda de no haberse hecho nada, si dejasemos a la epidemia seguir su curso natural. \"\"\" case1 = SIRwhatever(days = 100).run() \"\"\" En la siguiente gr\u00e1fica se muestran las distintas curvas que caracterizan la evoluci\u00f3n de la epidemia. \"\"\" with sns.axes_style(\"whitegrid\"): case1.plot(x='day', y=['infected', 'sick', 'symptomatic', 'asymptomatic', 'immune', 'incubating', 'infectable', 'severe', 'death', 'healthy', 'ever_sick', 'observed_ever_symptomatic'], logy=False, ylim=(0, 7e6), figsize=(20,10)) \"\"\" Las gr\u00e1ficas de velocidad nos permiten comprobar el ajuste del parametro `daily_transmission_rate` de manera que la simulaci\u00f3n tenga un valor similar al de la realidad (en Espa\u00f1a este valor ha fluctuado entre 0.35 y 0.45). \"\"\" with sns.axes_style(\"whitegrid\"): case1.plot(x='day', y=['velocity', 'ever_symptomatic_velocity'], ylim=(-0.4, 0.7), figsize=(20,10)) case1.plot(x='day', y=['velocity', 'ever_symptomatic_velocity'], ylim=(0, 0.6), xlim=(5,40), figsize=(20,10)) \"\"\" Dibujar las curvas en escala logaritmica nos permite ver la evoluci\u00f3n de variables cuyos valores son siempre relativamente peque\u00f1os, como es el caso de `severe`, que indica el n\u00famero de enfermos que requieren tratamiento en la UCI. \"\"\" with sns.axes_style(\"whitegrid\"): case1.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(10, 7e6), figsize=(20,10)) severe_max = case1.severe.max() public_hospital_beds = 6.662e6 * 0.003 print(\"max severe: %d, public hospital beds: %d, ratio: %1.1f%%\" % (severe_max, public_hospital_beds, 100*public_hospital_beds\/severe_max)) \"\"\" Y es f\u00e1cil ver cual ser\u00eda el problema de la sanidad si no se para la epidemia: solo tendr\u00edamos camas de hospital para el 7.3% de los pacientes muy graves que requeririan ser ingresados en la UCI... y si, ya no hablamos de que entren en la UCI, solo de darles una cama en un hospital!!! Con el apoyo de la sanidad privada a lo mejor llegamos al 10 o al 12%, no cambia mucho la situacion. Y eso sin tener en cuenta, que normalmente, las camas de los hospitales ya tienen un grado de ocupaci\u00f3n alto, sin necesidad de que vengan los enfermos de coronavirus. \"\"\" print(\"max ever sick: %f, deaths: %f\" % (case1.ever_sick.max(), case1.death.max())) \"\"\" Practicamente la totalidad de la poblaci\u00f3n pasar\u00eda la enfermedad. Con la tasa de mortalidad establecida del 3.4%, habr\u00eda 227k muertes solo en la Comunidad de Madrid. \"\"\" \"\"\" ## Caso 2: Paramos el pais para siempre Solo como caso hipotetico que nos permitira ver algunos n\u00fameros interesantes. En esta simulaci\u00f3n, al llegar a los 2900 casos (n\u00famero de casos en Madrid a 14 de marzo, cuando el gobiernos declaro el estado de alerta), se aislara a la poblaci\u00f3n para siempre. Durante el periodo de aislamiento suponemos que la tasa diaria de transmision de la epidemia (`daily_transmission_rate`) se divide por 10 (m\u00e1s adelante contemplaremos otros escenarios, cambiando dicho parametro). \"\"\" ## Implementation of the Isolate N days strategy class IsolateNDays(SIRwhatever): def __init__(self, isolation_days = 15, ever_symptomatic_threshold = 2900, isolation_transmission_rate_divider = 10, after_isolation_transmission_rate_divider = 1, **kargs): super().__init__(**kargs) self.isolation_days = isolation_days self.ever_symptomatic_threshold = ever_symptomatic_threshold self.isolation_transmission_rate_divider = isolation_transmission_rate_divider self.after_isolation_transmission_rate_divider = after_isolation_transmission_rate_divider self.isolated = False self.isolated_countdown = 0 def strategy(self, t, observed_ever_symptomatic, **kargs): if self.isolated: if self.isolated_countdown < 1: self.isolated = False self.daily_transmission_rate *= (self.isolation_transmission_rate_divider \/ self.after_isolation_transmission_rate_divider) self.ever_symptomatic_threshold = self.population_size * 10 # never ever stop # the country, you lazy! else: self.isolated_countdown -= 1 else: if observed_ever_symptomatic > self.ever_symptomatic_threshold: self.isolation_day = t self.isolated = True self.isolated_countdown = self.isolation_days * self.ticks_per_day self.daily_transmission_rate \/= self.isolation_transmission_rate_divider if self.isolated: return 'isolated' else: return 'normal' case2 = IsolateNDays(days = 120, isolation_days=1000).run() with sns.axes_style(\"whitegrid\"): case2.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'symptomatic', 'infectious', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(1, 3e4), figsize=(20,10)) case2.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'symptomatic', 'infectious', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(1, 1.6e4), xlim=(18, 60), figsize=(20,10)) print(\"max ever_symptomatic: %d, max symptomatic: %d, max severe: %d, max death: %d\" % (case2.ever_symptomatic.max(), case2.symptomatic.max(), case2.severe.max(), case2.death.max())) \"\"\" La conclusi\u00f3n es que el n\u00famero de enfermos sintomaticos en Madrid aun seguir\u00e1 creciendo durante unos 7 dias hasta casi llegar a los 11k. El n\u00famero de enfermos que tendran que ingresar en la UCI rondara los 800. En Madrid [hay 641 camas de UCI](https:\/\/elpais.com\/espana\/madrid\/2020-03-14\/casi-el-30-de-camas-de-la-uci-en-madrid-ya-se-destina-a-pacientes-con-coronavirus.html) as\u00ed que llegaremos al limite de la capacidad (y eso sin tener en cuenta el grado de ocupaci\u00f3n normal de esas camas). Por otro lado vemos que hasta aproximadamente 40 d\u00edas despues de tomar medidas, no se reduce el n\u00famero de infecciosos a 10, y aun tardar\u00e1 en torno a 12 d\u00edas m\u00e1s en llegar a 1 (aunque como ya comente al inicio del notebook, cuando el n\u00famero de elementos es tan bajo, la precisi\u00f3n del modelo es muy baja y podra haber grandes variaciones entre la predicci\u00f3n y la realidad). Y todo esto, claro, suponiendo que las medidas tomadas por el gobierno son eficaces y que realmente se va a reducir la tasa de transmisi\u00f3n diaria a la d\u00e9cima parte de la actual. \"\"\" \"\"\" ### Caso 2b: \u00bfy si estamos siendo muy optimistas? \u00bfQue pasa si las medidas del gobierno no son tan eficaces y por ejemplo, solo conseguimos reducir el ratio de transmisi\u00f3n a la tercera parte? \"\"\" case2b = IsolateNDays(days=300, isolation_transmission_rate_divider=3, isolation_days=1000).run() with sns.axes_style(\"whitegrid\"): case2b.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'symptomatic', 'infectious', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(10, 7e6), figsize=(20,10)) print(\"max ever_symptomatic: %d, max symptomatic: %d, max severe: %d\" % (case2b.ever_symptomatic.max(), case2b.symptomatic.max(), case2b.severe.max())) \"\"\" Ese es, m\u00e1s o menos, el escenario [Flatten The Curve](https:\/\/thespinoff.co.nz\/society\/09-03-2020\/the-three-phases-of-covid-19-and-how-we-can-make-it-manageable\/) que algunos plantean como la soluci\u00f3n ideal... Se ve que no han hecho muchos n\u00fameros, porque por ejemplo, en este caso, la epidemia no empieza a retroceder hasta dentro de medio a\u00f1o. Llegariamos a tener 234k enfermos simultaneos de los cuales unos 25k serian muy graves. Y la relaci\u00f3n siempre es igual, si se acorta la epidemia, aumenta el numero de enfermos... si se recorta el n\u00famero de enfermos simultaneos, se alarga la epidemia... no se pueden tener las dos cosas a la vez. Adem\u00e1s, en una simulaci\u00f3n de este tipo, siempre hay parametros que pueden estar equivocados o relaciones que pueden ser diferentes a como hemos supuesto e introducir errores, pero precisamente, la relaci\u00f3n entre duraci\u00f3n y n\u00famero de enfermos m\u00e1ximo se puede comprobar de otras maneras que es correcta (el area bajo la curva de enfermos es constante cuando pr\u00e1cticamente toda la poblaci\u00f3n se contagia). \"\"\" \"\"\" ### Caso 2c: \u00bfY si estamos siendo muy pesimistas? Tambien puede ser que las medidas del gobierno pulvericen el ratio de transmision diario a por ejemplo, la centesima parte. \"\"\" case2c = IsolateNDays(days = 70, isolation_transmission_rate_divider = 100, isolation_days=1000).run() with sns.axes_style(\"whitegrid\"): case2c.plot(x='day', y=['infected', 'immune', 'incubating', 'infectable', 'symptomatic', 'infectious', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(1, 2e4), figsize=(20,10)) \"\"\" ### Caso 2d: \u00bfy si consiguiesemos cortar los contagios completamente? Estudiemos el caso limite, en el que cortamos completamente los contagios (en el simulador vamos a dividir el ratio de contagio diario por $10^8$). Aunque sea un caso irreal, esta simulaci\u00f3n nos va a permitir conocer cual es el tope inferior de la duraci\u00f3n de la epidemia. \"\"\" case2d = IsolateNDays(days=80, isolation_transmission_rate_divider=1e8, isolation_days=1000).run() with sns.axes_style(\"whitegrid\"): case2d.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'infectable', 'infectious', 'severe', 'death', 'healthy', 'ever_sick'], logy=True, ylim=(1, 2e4), figsize=(20,10)) \"\"\" Vemos que el resultado es practicamente identico al caso anterior, en el que reduciamos el ratio de transferencia diario a la centesima parte. La gr\u00e1fica nos muestra que habr\u00eda que esperar aproximadamente 3 semanas para reducir el numero de infecciosos a 10. Esas tres semanas de riesgo corresponden exclusivamente a las personas que se infectaron antes de que se tomasen medidas de aislamiento y vienen determinadas por las distribuciones de probabilidad que hemos seleccionado para los tiempos de incubaci\u00f3n y de convalecencia. Se tardo tanto en tomar medidas de aislamiento, que la masa de personas infecciosas es enorme, con un pico por encima de las 3k personas. Eso hace que aunque la probabilidad de que el proceso de incubaci\u00f3n sea superior a tres semanas es muy bajo, en n\u00fameros absolutos nos movemos en el rango de las decenas. \"\"\" with sns.axes_style(\"whitegrid\"): case2d.plot(x='day', y=['velocity', 'ever_symptomatic_velocity'], ylim=(-0.4, 0.6), figsize=(20,10)) \"\"\" ### Comparaci\u00f3n de los subcasos Ahora comparemos las curvas de infecciosos de los cuatro subcasos: \"\"\" with sns.axes_style(\"whitegrid\"): fig, ax = plt.subplots(figsize=(20, 10)) ax.set(ylim=(-0.6, 0.5)) case2.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='infectious case 2') case2b.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='infectious case 2b') case2c.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='infectious case 2c') case2d.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='infectious case 2d') with sns.axes_style(\"whitegrid\"): fig, ax = plt.subplots(figsize=(20, 10)) ax.set(ylim=(1, 1e4)) case2.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='infectious case 2') case2b.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='infectious case 2b') case2c.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='infectious case 2c') case2d.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='infectious case 2d') \"\"\" Podemos ver que el efecto de reducir en 100 veces el ratio de transmision aun tiene una importante influencia en el ritmo al que se reduce el n\u00famero de personas contagiosas dentro de la poblaci\u00f3n pero m\u00e1s alla de ese punto, ya no influye casi nada. En cualquier caso, viendo esta gr\u00e1fica la cuesti\u00f3n que cabe plantearse es si vale la pena mantener el pais en un estado de aislamiento no completo, permitiendo que la gente acuda a su trabajo e incluso utilice el transporte publico. \u00bfEs mejor este aislamiento parcial al que estamos sometidos que uno total que haga que la epidemia pase lo antes posible? \"\"\" \"\"\" ## Caso 3: Paramos el pais durante 15 d\u00edas En este escenario, de nuevo, al llegar a los 2900 casos, todo la poblaci\u00f3n de la comunidad se aisla durante 15 d\u00edas. Pasado ese periodo, volvemos al estado normal de libre circulaci\u00f3n de personas. Igual que en el caso 2, suponemos que con el aislamiento se reduce el ratio de transmision diario a la d\u00e9cima parte. \"\"\" case3 = IsolateNDays(days = 120, isolation_days=15).run() with sns.axes_style(\"whitegrid\"): case3.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'infectable', 'infectious', 'severe', 'death', 'healthy', 'ever_sick', 'new_sick'], logy=True, ylim=(10, 7e6), figsize=(20,10)) case3.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'infectable', 'infectious', 'severe', 'death', 'healthy', 'ever_sick', 'new_sick'], logy=False, ylim=(10, 2e4), xlim=(18, 50), figsize=(20,10)) \"\"\" De nuevo llegariamos a cerca de los 11k enfermos sintom\u00e1ticos para luego descender hasta 3k. Una vez levantado el aislamiento la epidemia volveria a extenderse y dos semanas despues estariamos en el mismo punto que cuando se instauro el aislamiento. El \u00faltimo d\u00eda de aislamiento aun estar\u00edamos viendo un incremento de 250 nuevos enfermos cada d\u00eda. ### Caso 3b: \u00bfProbamos a parar un mes? En vista de que parar 15 d\u00edas no es suficiente, \u00a1probemos a hacerlo durante un mes! \"\"\" case3b = IsolateNDays(days = 120, isolation_days=30).run() with sns.axes_style(\"whitegrid\"): case3b.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'infectable', 'severe', 'death', 'healthy', 'ever_sick', 'infectious'], logy=True, ylim=(10, 7e6), figsize=(20,10)) \"\"\" Pasados los 30 d\u00edas de confinamiento, aun estariamos viendo alrededor de 20 enfermos nuevos cada d\u00eda. Aproximadamente, aun tendriamos 40 personas contagiosas desperdigadas por la comunidad (es importante tener en cuenta que en la realidad esas personas contagiosas no sabriamos quienes son ni donde est\u00e1n, por lo que no se podr\u00edan aislar). Al levantar el confinamiento, esas 40 personas reiniciarian la expansi\u00f3n de la epidemia y 2 semanas despues otra vez estar\u00edamos en el punto de partida. La reexpansi\u00f3n de la epidemia ir\u00eda esta vez tan rapido como la primera y ser\u00eda completamente est\u00fapido pensar de nuevo que podr\u00edamos frenarla. \"\"\" \"\"\" ### Caso 3c: paramos el pais completamente durante un mes y medio y luego mantenemos unas condiciones menos severas En este caso se estudia el escenario en el que se mantiene la situaci\u00f3n de aislamiento total (ratio de transmision diario reducido a la decima parte) durante 45 d\u00edas y despues de ese periodo se implanta un aislamiento menos estricto (ratio de transmision diario reducido a la tercera parte). \"\"\" case3c = IsolateNDays(days = 150, isolation_days=45, isolation_transmission_rate_divider=10, after_isolation_transmission_rate_divider=3).run() with sns.axes_style(\"whitegrid\"): case3c.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'infectable', 'severe', 'death', 'healthy', 'ever_sick', 'infectious'], logy=True, ylim=(10, 7e6), figsize=(20,10)) \"\"\" Al levantar la politica de aislamiento estricta aun tendriamos algunas personas contagiosas desperdigadas por la comunidad. Mantener a partir de ese punto ciertas medidas de aislamiento relentizar\u00eda la expansi\u00f3n de la epidemia y quiza, nos permitiese manejar esos pocos focos de contag\u00edo que pudiesen quedar, reduciendolos a tiempo. En cualquier caso, notese que los factores multiplicadores del ratio de transmisi\u00f3n son valores puestos completamente a ojo (muy dificiles de medir en la practica) y cualquier variaci\u00f3n de los mismos significar\u00eda un cambio radical en la velocidad de re-expansion de la enfermedad. Podemos tratar de ver la influencia de esos factores probando con varios distintos: \"\"\" case3d2 = IsolateNDays(days = 120, isolation_days=30, isolation_transmission_rate_divider=10, after_isolation_transmission_rate_divider=2).run() case3d4 = IsolateNDays(days = 120, isolation_days=30, isolation_transmission_rate_divider=10, after_isolation_transmission_rate_divider=4).run() case3d5 = IsolateNDays(days = 120, isolation_days=30, isolation_transmission_rate_divider=10, after_isolation_transmission_rate_divider=5).run() \"\"\" Representemos el n\u00famero de infectados y la velocidad a la que evolucionan. \"\"\" with sns.axes_style(\"whitegrid\"): fig, ax = plt.subplots(figsize=(20, 10)) ax.set(ylim=(1, 1e4)) case3b.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='after divider 1.0') case3c.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='after divider 3.0') case3d2.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='after divider 2.0') case3d4.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='after divider 4.0') case3d5.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label='after divider 5.0') fig, ax = plt.subplots(figsize=(20, 10)) ax.set(ylim=(-0.4, 0.6)) case3b.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='after divider 1.0') case3c.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='after divider 3.0') case3d2.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='after divider 2.0') case3d4.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='after divider 4.0') case3d5.plot(x='day', y='velocity', logy=False, ax=ax, xlim=(15, 70), label='after divider 5.0') \"\"\" La conclusi\u00f3n que podemos sacar de estas gr\u00e1ficas es que habra que ser muy cautos en la fase post-aislamiento y seguir reduciendo las relaciones humanas al m\u00e1ximo, mientras se localizan personas o lugares expuestos porque si las condiciones de aislamiento resultan en un ratio de transmisi\u00f3n m\u00e1s alto de lo esperado, otra vez se podr\u00eda disparar la epidemia. \"\"\" \"\"\" ## Caso 4: Paramos el pais hasta que dejen de aparecer nuevos enfermos En este escenario aislamos el pais completamente hasta que dejen de aparecer enfermos, luego por si acaso aun esperamos unos d\u00edas m\u00e1s antes de levantar las restricciones. Adem\u00e1s, en el supuesto de que volviesen a aparecer nuevos casos, de nuevo iniciariamos el aislamiento, pero cada vez poniendo el umbral de nuevos casos mas bajo. \"\"\" class EverybodyIsHealthy(SIRwhatever): def __init__(self, isolation_safe_days = 10, isolation_transmission_rate_divider = 10, ever_symptomatic_thresholds = [2900, 50, 10, 10, 1], **kargs): super().__init__(**kargs) self.isolated = False self.isolation_transmission_rate_divider = isolation_transmission_rate_divider self.isolation_safe_days = isolation_safe_days self.ever_symptomatic_thresholds = ever_symptomatic_thresholds self.flips = 0 self.ever_symptomatic_at_flop = 0 def strategy(self, t, sick, new_symptomatic, infectious, observed_ever_symptomatic, **_): ever_symptomatic_threshold_ix = (self.flips if self.flips < len(self.ever_symptomatic_thresholds) else -1) ever_symptomatic_threshold = self.ever_symptomatic_thresholds[ever_symptomatic_threshold_ix] if self.isolated: if new_symptomatic < 1: self.isolation_safe_days_countdown -= 1 if self.isolation_safe_days_countdown < 1: self.isolated=False self.daily_transmission_rate *= self.isolation_transmission_rate_divider self.ever_symptomatic_at_flop = observed_ever_symptomatic else: if (observed_ever_symptomatic - self.ever_symptomatic_at_flop > ever_symptomatic_threshold): self.isolated=True self.isolation_safe_days_countdown = self.isolation_safe_days self.daily_transmission_rate \/= self.isolation_transmission_rate_divider self.flips += 1 return ('isolated' if self.isolated else 'normal') case4 = EverybodyIsHealthy(days = 250).run() with sns.axes_style(\"whitegrid\"): case4.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'severe', 'asymptomatic', 'ever_sick', 'infectable'], logy=False, figsize=(20,10), ylim=(0, 2e4)) case4.plot(x='day', y=['infected', 'symptomatic', 'immune', 'incubating', 'severe', 'asymptomatic', 'ever_sick', 'infectable'], logy=True, figsize=(20,10), ylim=(1, 2e4)) \"\"\" Este escenario pueda parecer absurdo pero cobra sentido cuando tenemos en cuenta nuestro contexto global. Aunque en un tiempo razonable consiguiesemos eliminar completamente el virus en Madrid y en toda Espa\u00f1a, este seguir\u00e1 desarrollandose en otras partes del mundo y a no ser que cerremos nuestras fronteras a cal y canto, seguiremos recibiendo un goteo poco predecible de personas infectadas que en cualquier momento pueden reiniciar la epidemia. Confiemos en que para llegado ese momento, nuestro nivel de concienciaci\u00f3n tanto a nivel personal como de nuestros gobernantes, nos fuerce a actuar de una manera m\u00e1s eficaz, permitiendonos detener la epidema con prontitud, por ejemplo, aplicando aislamientos con premura en aquellos lugares donde se detecten nuevos casos. Pero aun as\u00ed, parece poco razonable pensar que mantener al pais en ese estado de alerta, sea el contexto adecuado para propiciar la recuperaci\u00f3n economica. \u00bfPodriamos estar aislando ciudades de Espa\u00f1a durante periodos de varias semanas cada vez que se detecte un nuevo caso? En realidad este escenario lo que pone de manifiesto es la cortedad de miras de nuestros gobernantes, que han sido incapaces de coordinarse a nivel europeo para plantar cara de forma conjunta a la epidemia. El aislamiento hubiese sido mucho m\u00e1s eficaz si toda Europa lo hiciese a la vez. Ahora tendremos paises que van a distintas velocidades y eso nos va a obligara a mantener las fronteras cerradas durante mucho tiempo. \"\"\" \"\"\" ## Caso 5: Contagio estratificado controlado Con las soluciones de aislamiento estudiadas hasta ahora, aunque se consiga parar la epidemia en Espa\u00f1a, no se habr\u00e1 desarrollado immunidad de grupo y eso da lugar al problema mencionado con anterioridad relativo a que cualquier nuevo caso importado puede desencadenar de nuevo la epidemia. Por ese motivo, tambien hay quien proopone aislar unicamente a las personas de riesgo y dejar que el resto de la poblaci\u00f3n, se contagie. Por ejemplo, \u00bfque pasar\u00eda si una vez reducida la epidemia actual enviasemos a todas las personas mayores de 50 a\u00f1os (el 68% de la poblaci\u00f3n de Madrid segun datos del INE) en autobuses camino de Benidorm al tanto que dejamos que la epidemia se extienda de nuevo en Madrid entre el resto de la poblaci\u00f3n? Pasado un tiempo, la mayoria de los madrile\u00f1os menores de 50 a\u00f1os habr\u00e1n pasado la enfermedad y ser\u00e1n immunes. Puede que si entonces dejamos que nuestros mayores vuelvan, aun nos mantengamos por debajo del punto critico a partir del cual la epidemia es viable. Como sociedad, \u00bfseremos immunes al coronavirus? En concreto, vamos a realizar la simulaci\u00f3n de un escenario con las siguientes etapas: 1. Crecimiento rampante de la epidemia 2. Como en los casos anteriores, al alcanzar los 2900 enfermos symptomaticos se aplican medidas de aislamiento que reducen el ratio de transmisi\u00f3n de la enfermedad a la decima parte. 3. Una vez se alcanza el punto donde ya no aparecen m\u00e1s enfermos durante varios d\u00edas, simulamos eliminar a las personas mayores de 50 a\u00f1os y dejamos que la enfermedad progrese entre el resto. 4. La enfermedad se propaga, contag\u00eda a la mayor parte de la poblaci\u00f3n y cae. 5. Reintroducimos a las personas mayores de 50 a\u00f1os sin tomar ningun otro tipo de medida y vemos que pasa. La mortalidad por edades viene reflejada en la siguiente tabla: \"\"\" mortality_table=pd.read_csv(io.StringIO(\"\"\" population,start_age,end_age,mortality 704650,0,9,0.0 590337,10,19,0.002 834247,20,29,0.002 1227008,30,39,0.002 1049187,40,49,0.004 782873,50,59,0.013 597152,60,69,0.036 420139,70,79,0.08 284087,80,200,0.148 \"\"\")) \"\"\" Para mantener la coherencia con el resto de simulaciones, no usaremos dicha tabla tal cual, si no que la escalaremos hasta conseguir que la mortalidad global tenga el valor 3.4% (el mismo valor que hemos utilizado en el resto de casos). \"\"\" class StratifiedSpread(SIRwhatever): def __init__(self, rampant_ever_symptomatic_threshold = 2900, isolated_new_symptomatic_threshold = 1, isolated_transmission_rate_divider = 10, countdown_days = 10, stratified_transmission_rate_multiplier = 1, stratified_exclusion_age = 60, mortality_table = mortality_table, stratified_new_symptomatic_threshold = 1, **kargs): super().__init__(**kargs) self.ss_state = 'rampant' self.rampant_ever_symptomatic_threshold = rampant_ever_symptomatic_threshold self.isolated_new_symptomatic_threshold = isolated_new_symptomatic_threshold self.isolated_transmission_rate_divider = isolated_transmission_rate_divider self.countdown_days = countdown_days self.stratified_exclusion_age = stratified_exclusion_age self.stratified_new_symptomatic_threshold = stratified_new_symptomatic_threshold self.mortality_table = mortality_table self.strategies = { k: getattr(self, \"strategy_\" + k) for k in ['rampant', 'isolated', 'countdown', 'stratified', 'everybody'] } self.starts = { k: getattr(self, \"start_\" + k) for k in ['rampant', 'isolated', 'countdown', 'stratified', 'everybody'] } # we keep using the data given by the user, so we calculate the scaling # factors for the mortality table accordingly: mt_population_size = mortality_table.population.sum() self.mt_population_multiplier = self.population_size \/ mt_population_size mt_mortality_ratio = ((mortality_table.population * mortality_table.mortality).sum() \/ mt_population_size) self.mt_mortality_multiplier = self.mortality_ratio \/ mt_mortality_ratio def strategy(self, **kargs): old_state = self.ss_state state_strategy = self.strategies[old_state] new_state = state_strategy(**kargs) if new_state is None or new_state == old_state: return old_state self.ss_state = new_state state_start = self.starts[new_state] state_start(**kargs) return new_state def start_rampant(self, **kargs): pass # def strategy_rampant(self, observed_ever_symptomatic, **kargs): if (observed_ever_symptomatic > self.rampant_ever_symptomatic_threshold): return 'isolated' def start_isolated(self, **kargs): self.daily_transmission_rate \/= self.isolated_transmission_rate_divider def strategy_isolated(self, new_symptomatic, **kargs): if new_symptomatic < self.isolated_new_symptomatic_threshold: return 'countdown' def start_countdown(self, **kargs): self.countdown_ticks = self.countdown_days * self.ticks_per_day def strategy_countdown(self, **kargs): if self.countdown_ticks < 1: self.daily_transmission_rate *= self.isolated_transmission_rate_divider return 'stratified' self.countdown_ticks -= 1 def start_stratified(self, observed_ever_symptomatic, **kargs): sxa = self.stratified_exclusion_age mt = self.mortality_table mt_below_sxa = mt[mt.start_age < sxa] mt_over_sxa = mt[mt.end_age > sxa] mt_below_sxa_population = mt_below_sxa.population.sum() mt_over_sxa_population = mt_over_sxa.population.sum() mortality_ratio = ((mt_below_sxa.mortality*mt_below_sxa.population).sum()\/ mt_below_sxa_population)*self.mt_mortality_multiplier multiplier = mortality_ratio\/self.mortality_ratio self.mortality_ratio *= multiplier self.severe_ratio *= multiplier self.population_size = (self.population_size * mt_below_sxa_population \/ (mt_below_sxa_population + mt_over_sxa_population)) print(\"multiplier: %f, mortality_ratio: %f, population_size: %f\" % (multiplier, self.mortality_ratio, self.population_size)) def strategy_stratified(self, new_symptomatic, observed_ever_symptomatic, **kargs): if (new_symptomatic < self.stratified_new_symptomatic_threshold and observed_ever_symptomatic > 0.33 * self.population_size): return 'everybody' def start_everybody(self, infectable, **kargs): sxa = self.stratified_exclusion_age mt = self.mortality_table mt_below_sxa = mt[mt.start_age < sxa] mt_over_sxa = mt[mt.end_age > sxa] mt_below_sxa_population = mt_below_sxa.population.sum() mt_over_sxa_population = mt_over_sxa.population.sum() stratified_population_size = self.population_size excluded_population_size = (stratified_population_size * mt_over_sxa_population \/ mt_below_sxa_population) excluded_population_size_adjusted = excluded_population_size * self.mt_population_multiplier stratified_mortality_rate = ((mt_below_sxa.mortality*mt_below_sxa.population).sum()\/ mt_below_sxa_population) excluded_mortality_rate = ((mt_over_sxa.mortality*mt_over_sxa.population).sum()\/ mt_over_sxa_population) combined_mortality_rate = ((stratified_mortality_rate * infectable + excluded_mortality_rate * excluded_population_size_adjusted) \/ (infectable + excluded_population_size_adjusted)) multiplier = combined_mortality_rate \/ self.mortality_ratio self.mortality_ratio *= multiplier self.severe_ratio *= multiplier self.population_size = ((self.population_size \/ stratified_population_size) * stratified_population_size + excluded_population_size) print(\"multiplier: %f, mortality_ratio: %f, population_size: %f\" % (multiplier, self.mortality_ratio, self.population_size)) def strategy_everybody(self, **kargs): pass case5 = StratifiedSpread(days=400, stratified_exclusion_age=50).run() with sns.axes_style(\"whitegrid\"): case5.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'asymptomatic', 'infectious', 'severe', 'death', 'healthy', 'ever_sick', 'new_sick'], logy=True, ylim=(1, 9e6), figsize=(20,10)) case5.plot(x='day', y='velocity', logy=False, ylim=(-0.3, 0.6), figsize=(20,5)) case5.velocity[case5.day==350] \"\"\" Vemos que aunque finalmente no se detenga la epidemia, s\u00ed conseguimos reducir considerablemente el factor de crecimiento diario de la misma a la decima parte, de 0.4 a a 0.04. Eso har\u00e1 sin duda que la epidemia sea mucho m\u00e1s controlable. \"\"\" case5.death[case5.day==173] case5.severe[case5.day < 173].max() \"\"\" Desafortunadamente el n\u00famero de muertes entre la poblaci\u00f3n menor de 50 a\u00f1os ser\u00eda de 19k y llegariamos a tener a 22k enfermos graves simultaneamente. No obstante, habr\u00eda que plantearse si es posible reducir el ratio de muertos particionando a la poblaci\u00f3n en base a criterios m\u00e1s sofisticados, como por ejemplo, teniendo en cuenta el estado fisico de las personas. Tambien hay que tener en cuenta que los ratios de mortalidad y de enfermos que necesitan hospitalizaci\u00f3n son por ahora muy poco precisos, existiendo gran divergencia entre los distintos estudios publicados. \"\"\" \"\"\" ### Caso 5b: Aislamos a los mayores de 60 a\u00f1os Probemos a dejar fuera a la poblaci\u00f3n mayor de 60 a\u00f1os que representa el 20% del total. \"\"\" case5b = StratifiedSpread(days=300, stratified_exclusion_age=60).run() with sns.axes_style(\"whitegrid\"): case5b.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'infectious', 'severe', 'death', 'healthy', 'ever_sick', 'new_sick'], logy=True, ylim=(1, 7e6), figsize=(20,10)) case5b.plot(x='day', y='velocity', logy=False, ylim=(-0.3, 0.6), figsize=(20,5)) \"\"\" En este caso podemos ver que la epidemia desaparece. La immunidad de grupo no le permite desarrollarse ya m\u00e1s en nuestra comunidad. \"\"\" case5b.death.max() case5b.severe.max() \"\"\" Vemos que el coste es alto, llegando a morir mas de 38k personas solo en la Comunidad de Madrid. \"\"\" \"\"\" ### Caso 5c: Aislamos a los mayores de 40 a\u00f1os Dejando que la enfermendad se extienda entre los menores de 50 o 60 a\u00f1os hemos visto que tiene un coste muy alto en muertes. Vamos a probar con los menores de 40 para ver si eso proporcionar\u00eda alguna ventaja. \"\"\" case5c = StratifiedSpread(days=300, stratified_exclusion_age=40).run() with sns.axes_style(\"whitegrid\"): case5c.plot(x='day', y=['infected', 'sick', 'immune', 'incubating', 'infectable', 'infectious', 'severe', 'death', 'healthy', 'ever_sick', 'new_sick'], logy=True, ylim=(1, 7e6), figsize=(20,10)) case5c.plot(x='day', y='velocity', logy=False, ylim=(-0.3, 0.6), figsize=(20,5)) case5c[case5c.day==200].velocity \"\"\" Como en el caso de 50 a\u00f1os, vemos que no se detiene la epidemia, pero aun as\u00ed se relentiza su expansion. En este caso el factor de velocidad se habra reducido a casi la tercera parte, de 0.4 a 0.14. El coste en vidas, antes de la etapa final ser\u00eda todav\u00eda extremadamente alto, aproximadamente de 11k, todos menores de 40 a\u00f1os. \"\"\" \"\"\" # Efecto de los parametros en el modelo Algunos de los parametros utilizados en el simulador han sido elegidos sin demasiada rigurosidad. Antes de acabar vamos a estudiar el efecto de perturbar esos parametros sobre los resultados obtenidos de cara a determinar si introducen mucha o poca variacion en los mismos. Centremonos en los 3 parametros que pueden tener un efecto mayor en la salida del simulador: 1. Variancia del periodo de incubaci\u00f3n. 2. Tiempo medio de convalecencia de los enfermos asintomaticos. 3. Variancia del periodo de convalecencia de los enfermos asintomaticos. ## Efecto de las varianzas Primero repetimos la simulac\u00edon del caso 2 con variaciones en los parametros de varianza. \"\"\" fig, ax = plt.subplots(figsize=(20, 10)) ax.set(ylim=(1, 1e4)) for incubation_variance in [3, 7, 12]: for asymptomatic_convalescent_period_variance in [3, 6, 12]: df = IsolateNDays(days = 70, isolation_transmission_rate_divider = 10, asymptomatic_convalescent_period_variance=asymptomatic_convalescent_period_variance, incubation_variance=incubation_variance, isolation_days=70, quiet=True).run() df.plot(x='day', y='infectious', logy=True, ax=ax, xlim=(15, 70), label=('iv: %f, acpv: %f' % (incubation_variance, asymptomatic_convalescent_period_variance))) \"\"\" Se puede apreciar que el efecto de dichos parametros en los resultados de la simulaci\u00f3n es relativamente peque\u00f1o. Eso nos indica que un error en la estimaci\u00f3n de esos parametros no genera un error del mismo calibre en el resultado de la simulaci\u00f3n. ## Efecto del tiempo medio de convalecencia asintom\u00e1tica Experimentemos ahora variando el tiempo medio de convalecencia asintomatica. \"\"\" fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 2e4)) axs[1].set(ylim=(-0.2, 0.45)) for asymptomatic_convalescent_period_mean in [0.5, 1, 2, 3, 5, 8]: def f(x): df = SIRwhatever(days = 20, asymptomatic_convalescent_period_mean=asymptomatic_convalescent_period_mean, quiet=True, daily_transmission_rate=x).run() v = df[df.day==10].symptomatic_velocity - 0.4 # print(\"m: %f, x: %f, v: %f\" % (asymptomatic_convalescent_period_mean, x, v)) return v daily_transmission_rate = scipy.optimize.bisect(f, 1, 4, rtol=0.002) df = IsolateNDays(days = 120, daily_transmission_rate = daily_transmission_rate, isolation_transmission_rate_divider = 20, asymptomatic_convalescent_period_mean=asymptomatic_convalescent_period_mean, isolation_days=100, quiet=True).run() print((\"asymptomatic_convalescent_period_mean: %f, \"+ \"daily_transmission_rate: %f, symptomatic_velocity: %f\") % (asymptomatic_convalescent_period_mean, daily_transmission_rate, df.symptomatic_velocity[df.day == 10])) df.plot(x='day', y='infectious', logy=True, ax=axs[0], xlim=(15,100), label=('m: %f, dtr: %f' % (asymptomatic_convalescent_period_mean, daily_transmission_rate))) df.plot(x='day', y='velocity', logy=False, ax=axs[1], xlim=(15,100), label=('m: %f, dtr: %f' % (asymptomatic_convalescent_period_mean, daily_transmission_rate))) \"\"\" Se aprecia que, una vez ajustado el ratio de transmisi\u00f3n diario para que la velocidad de infecci\u00f3n se mantenga en el valor 0.4, la influencia del tiempo de convalecencia asintomatico medio tampoco es muy grande. En cualquier caso, a lo largo del presente estudio hemos utilizado el valor de 2 dias que es conservador y se encuentra en una franja de poca variaci\u00f3n. Si el valor real del parametro resultase ser mayor, el efecto ser\u00eda tiempos de evoluci\u00f3n m\u00e1s largos a los aqu\u00ed obtenidos. \"\"\" \"\"\" # Conclusiones \"\"\" \"\"\" 1. En el mejor de los casos, el n\u00famero de enfermos en la Comunidad de Madrid parara de crecer hasta llegar a 11k. El n\u00famero maximo de enfermos que necesiten ser ingresados en la UCI de manera simultanea rondara los 800. 2. Igualmente, en el caso ideal, suponiendo un aislamiento completo de la poblaci\u00f3n capaz de eliminar cualquier nuevo contagio, aun tendr\u00edan que pasar 3 semanas para que el numero de personas capaz de transmitir la enfermedad en la comunidad bajase a 10. 3. Asumiendo hipotesis m\u00e1s realistas sobre la eficacia de las medidas del gobierno, el tiempo necesario para llegar a reducir el n\u00famero de personas contagiosas a 10, pasa a ser de 40 d\u00edas. 4. Si se para la epidemia, no habremos desarrollado immunidad de grupo por lo que cualquier nuevo caso podr\u00eda relanzar el proceso. Esto puede ser causado tanto por personas contagiosas aun presentes en la poblaci\u00f3n o por casos importados. Estamos hablando de un problema a nivel global. No es suficiente con eliminar el virus en Madrid, Espa\u00f1a o Europa. 5. Igualmente, una vez parada la epidemia, sera aconsejable mantener un nivel de aislamiento parcial que limite la velocidad de propagaci\u00f3n de nuevos focos. 6. Permitir que la epidemia se expanda de manera controlada entre los estratos de la poblaci\u00f3n con menos riesgo nos permitir\u00eda lograr immunidad de grupo, pero el n\u00famero de muertos seria notable. A\u00f1adir por \u00faltimo que como en cualquier simulaci\u00f3n, la validez de los resultados depende en gran medida de las hipotesis realizadas, especialmente de los valores de parametrizaci\u00f3n, por lo que cualquier valor aqu\u00ed dado puede tener un grado de error importante. No obstante a nivel cualitativo si podemos comparar las curvas de evoluci\u00f3n aqu\u00ed generadas con la realidad para permitirnos determinar en que escenarios nos encontramos y tomar medidas correctivas si resulta no ser el que esperamos! Reciprocamente, seg\u00fan pase el tiempo, podremos ir ajustando los parametros de la simulaci\u00f3n tratando de ajustarlos a lo que vemos en la realidad de cara a predecir con mayor precisi\u00f3n el futuro. \"\"\" \"\"\" # Ep\u00edlogo Voy a utilizar los comentarios y preguntas sobre la simulaci\u00f3n que me esta enviando la gente para expandirla con algunos nuevos escenarios que creo que son interesantes. Tambien voy a aprovechar para responder a algunas preguntas que considero que son interesantes. ## \u00bfY las vacunas? En la simulaci\u00f3n no se habla para nada de lo que va a pasar cuando aparezca la vacuna (suponiendo que se consigue, \u00a1claro!). Para poder introducir el efecto de la vacuna en la simulaci\u00f3n tendriamos que conocer diversos parametros sobre la misma, siendo el m\u00e1s importante cuando va a estar lista, y eso sin una bola de cristal... De todas formas, en cuanto exista la vacuna y se administre a la poblaci\u00f3n el problema se acaba. Como se mostraba en el caso de propagacion controlada estratificada, una vez se immunice a al menos, el 80% de la poblaci\u00f3n la epidemia ya no es viable y se extinguira por si sola. ## Ratio de enfermos asintom\u00e1ticos El ratio de enfermos asintom\u00e1ticos esta extraido de un estudio que se hizo con los pasajeros del crucero Diana Princess. Probablemente los turistas de un crucero no sea un grupo representivo de la poblaci\u00f3n general, especialmente en lo que a distribuci\u00f3n de edades se refiere. \u00bfQue pasar\u00eda si dicho paramero estuviese muy subestimado? Vamos a verlo probemos de nuevo a simular algunos de los escenarios anteriores con valores distintos del ratio de enfermos asintomaticos. ### Caso E1a: Aislamiento de la poblaci\u00f3n para siempre cuando hay muchos enfermos asintom\u00e1ticos En la siguiente ejecuci\u00f3n del simulador se utilizan los siguientes valores del parametro `asymptomatic_rate`: 17%, 30%, 50% y 80%. El c\u00f3digo es un poco m\u00e1s complicado que en los casos estudiados hasta ahora porque hay que ajustar el resto de parametros de manera acorde. Se tienen que mantener las proporciones entre los enfermos leves y severos y a la vez conseguir que la velocidad de infecci\u00f3n inicial sea 0.4. \"\"\" with sns.axes_style(\"whitegrid\"): fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 8e4)) axs[1].set(ylim=(-0.2, 0.45)) for asymptomatic_ratio in [0.17, 0.3, 0.5, 0.8]: # we need to adjust the severe and mortality ratios accordingly severe_ratio = 0.05 \/ (1 - 0.17) * (1 - asymptomatic_ratio) mortality_ratio = 0.034 \/ (1 - 0.17) * (1 - asymptomatic_ratio) # we also need to find the daily_transmission_rate for which ever_sick_velocity is 0.4 def f(x): df = SIRwhatever(days = 40, asymptomatic_ratio=asymptomatic_ratio, mortality_ratio=mortality_ratio, severe_ratio=severe_ratio, quiet=True, daily_transmission_rate=x).run() v = df[df.day==20].observed_ever_symptomatic_velocity - 0.4 # print(\"m: %f, x: %f, v: %f\" % (asymptomatic_convalescent_period_mean, x, v)) return v daily_transmission_rate = scipy.optimize.bisect(f, 1, 4, rtol=0.002) print(\"asymptomatic_ratio: %f, severe_ratio: %f, mortality_ratio: %f, daily_transmission_rate: %f\" % (asymptomatic_ratio, severe_ratio, mortality_ratio, daily_transmission_rate)) df = IsolateNDays(days = 150, daily_transmission_rate=daily_transmission_rate, isolation_transmission_rate_divider=10, asymptomatic_ratio=asymptomatic_ratio, mortality_ratio=mortality_ratio, severe_ratio=severe_ratio, isolation_days=200).run() label = \" ar: %f\" % asymptomatic_ratio ys = ['infectious', 'symptomatic', 'death', 'immune', 'infectable'] df.plot(x='day', y=ys, logy=True, ax=axs[0], xlim=(15,100), label=[y + label for y in ys]) velocity_ys = ['velocity', 'symptomatic_velocity'] df.plot(x='day', y=velocity_ys, logy=False, ax=axs[1], xlim=(15,100), label=[y + label for y in velocity_ys]) \"\"\" Viendo las gr\u00e1ficas se puede apreciar que se relentizar\u00eda el tiempo de extinci\u00f3n de la epidemia. La raz\u00f3n es que la masa total de infectados\/contagiosos crece proporcionalmente al ratio de enfermos asintom\u00e1ticos. \"\"\" \"\"\" ### Caso E1b: \u00bfque pasa si no hacemos nada y el ratio de enfermos asintom\u00e1ticos es muy alto? Podemos hacer la misma simulaci\u00f3n para el caso en el que no se toman medidas, que ser\u00eda el peor caso posible, para ver como los distintos valores del ratio de enfermos asintomaticos afectan al n\u00famero de muertes y de enfermos graves. \"\"\" with sns.axes_style(\"whitegrid\"): fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 7e6)) axs[1].set(ylim=(-0.4, 0.45)) for asymptomatic_ratio in [0.17, 0.4, 0.8]: # we need to adjust the severe and mortality ratios accordingly severe_ratio = 0.05 \/ (1 - 0.17) * (1 - asymptomatic_ratio) mortality_ratio = 0.034 \/ (1 - 0.17) * (1 - asymptomatic_ratio) # we also need to find the daily_transmission_rate for which ever_sick_velocity is 0.4 def f(x): df = SIRwhatever(days = 40, asymptomatic_ratio=asymptomatic_ratio, mortality_ratio=mortality_ratio, severe_ratio=severe_ratio, quiet=True, daily_transmission_rate=x).run() v = df[df.day==20].observed_ever_symptomatic_velocity - 0.4 # print(\"m: %f, x: %f, v: %f\" % (asymptomatic_convalescent_period_mean, x, v)) return v daily_transmission_rate = scipy.optimize.bisect(f, 1, 4, rtol=0.002) print(\"asymptomatic_ratio: %f, severe_ratio: %f, mortality_ratio: %f, daily_transmission_rate: %f\" % (asymptomatic_ratio, severe_ratio, mortality_ratio, daily_transmission_rate)) df = SIRwhatever(days = 80, daily_transmission_rate=daily_transmission_rate, asymptomatic_ratio=asymptomatic_ratio, mortality_ratio=mortality_ratio, severe_ratio=severe_ratio).run() print(\"asymptomatic_ratio: %f, deaths: %f\" % (asymptomatic_ratio, df.death.max())) label = \" ar: %f\" % asymptomatic_ratio ys = ['infectious', 'symptomatic', 'death', 'severe', 'immune', 'infectable'] df.plot(x='day', y=ys, logy=True, ax=axs[0], xlim=(15,100), label=[y + label for y in ys]) velocity_ys = ['velocity', 'symptomatic_velocity'] df.plot(x='day', y=velocity_ys, logy=False, ax=axs[1], xlim=(15,100), label=[y + label for y in velocity_ys]) \"\"\" Como era de esperar, vemos que el n\u00famero de muertes cae al crecer el ratio de enfermos asintomaticos. No obstante, aun en el mejor caso, cuando le damos el valor 0.8, el n\u00famero de muertes estaria por encima de 50k (y solo en la Comunidad de Madrid). \"\"\" \"\"\" ## Caso E2: 9 d\u00edas despues Ya han pasado 9 d\u00edas desde que se declaro el estado de alerta y la velocidad de crecimiento de la epidemia en Espa\u00f1a parece que se ha estabilizado en torno al 20%. Podemos utilizar ese dato para ajustar la simulaci\u00f3n y ver en que escenario nos encontramos. \"\"\" days_after = 9 observed_velocity = 0.19 # First we need to look for the daily_transmission_rate_divisor that # makes the velocity go down to 0.19 one week after def f(x): sim = IsolateNDays(days=80, quiet=True, isolation_transmission_rate_divider=x) df = sim.run() v = df[df.day==(sim.isolation_day + days_after)].observed_ever_symptomatic_velocity - observed_velocity return v isolation_transmission_rate_divider_e2 = scipy.optimize.bisect(f, 1, 10, rtol=0.002) print(\"isolation_transmission_rate_divider: %f\" % isolation_transmission_rate_divider_e2) \"\"\" El valor que optenemos para el divisor del ratio de transmisi\u00f3n diario es muy malo. Como hab\u00edamos visto anteriormente, estariamos en el escenario \"FlattenTheCurve\" donde la velocidad de la epidemia se relentiza pero no lo suficiente como para pararla. Veamos que pasa si ejecutamos la simulaci\u00f3n con dicho valor: \"\"\" case_e2 = IsolateNDays(days = 300, isolation_transmission_rate_divider=isolation_transmission_rate_divider_e2, isolation_days=500).run() \"\"\" Vemos un pico de 120k pacientes severos (y solo en la Comunidad de Madrid, recordemos que la simulaci\u00f3n esta restringida a ese territorio) que es completamente inasumible por muchos hospitales de campa\u00f1a que monten. \"\"\" max(case_e2.death) \"\"\" Y ese es quiza el peor dato: m\u00e1s de 173k muertos. Echemos ahora un vistazo a las curvas: \"\"\" with sns.axes_style(\"whitegrid\"): fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 7e6)) axs[1].set(ylim=(-0.2, 0.5)) case_e2.plot(x='day', y=['infectious', 'symptomatic', 'death', 'immune', 'infectable'], logy=True, ax=axs[0], xlim=(15,230)) case_e2.plot(x='day', y=['velocity', 'symptomatic_velocity', 'ever_symptomatic_velocity'], logy=False, ax=axs[1], xlim=(15,230)) with sns.axes_style(\"whitegrid\"): fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 7e6)) axs[1].set(ylim=(-0.1, 0.45)) case_e2.plot(x='day', y=['infectious', 'symptomatic', 'death', 'immune', 'infectable'], logy=True, ax=axs[0], xlim=(20,80)) case_e2.plot(x='day', y=['velocity', 'symptomatic_velocity', 'ever_symptomatic_velocity'], logy=False, ax=axs[1], xlim=(20,80)) \"\"\" Vemos que la velocidad de propagaci\u00f3n de la epidemia se estabiliza en torno al 15% y sigue as\u00ed durante aproximandamente un mes. En ese punto, ya hay tantas personas immunes que la propagaci\u00f3n se relentiza por si misma. Si comparamos las curvas de velocidad simuladas con la realidad, vemos que probablemente el simulador este arrojando un resultado m\u00e1s optimista que el real puesto que la pendiente de la curva simulada es mucho mayor de lo que se observa en la realidad. \"\"\" \"\"\" ### Caso E2b: Reajustando la velocidad inicial Hasta ahora hab\u00edamos supuesto que la velocidad de la epidemia en Espa\u00f1a antes de tomar medidas estaba en torno al 40%, pero si nos fijamos solo en los d\u00edas previos a la toma de medidas, ese valor en realidad estaba en torno al 0.45%. Vamos a repetir la simulaci\u00f3n utilizando ese valor de partida. \"\"\" def f1(x): sim = SIRwhatever(days = 45, quiet=True, daily_transmission_rate=x) df = sim.run() v = df[df.day==(22)].observed_ever_symptomatic_velocity - 0.45 return v daily_transmission_rate_e2b = scipy.optimize.bisect(f1, 1, 3, rtol=0.002) print(\"daily_transmission_rate: %f\" % daily_transmission_rate_e2b) def f2(x): sim = IsolateNDays(days = 80, quiet=True, daily_transmission_rate = daily_transmission_rate_e2b, isolation_transmission_rate_divider=x) df = sim.run() v = df[df.day==(sim.isolation_day + days_after)].observed_ever_symptomatic_velocity - observed_velocity return v isolation_transmission_rate_divider_e2b = scipy.optimize.bisect(f2, 1, 10, rtol=0.002) print(\"isolation_transmission_rate_divider: %f\" % isolation_transmission_rate_divider_e2b) case_e2b = IsolateNDays(days = 300, daily_transmission_rate=daily_transmission_rate_e2b, isolation_transmission_rate_divider=isolation_transmission_rate_divider_e2b, isolation_days=500).run() with sns.axes_style(\"whitegrid\"): fig, axs = plt.subplots(2, figsize=(20, 15)) axs[0].set(ylim=(1, 7e6)) axs[1].set(ylim=(-0.2, 0.5)) case_e2b.plot(x='day', y=['infectious', 'symptomatic', 'death', 'immune', 'infectable'], logy=True, ax=axs[0], xlim=(15,230)) case_e2b.plot(x='day', y=['velocity', 'symptomatic_velocity', 'ever_symptomatic_velocity'], logy=False, ax=axs[1], xlim=(15,230)) \"\"\" Vemos que a groso modo, no hay muchos cambios con respecto al caso E2. Seguimos en el escenario donde practicamente toda la poblaci\u00f3n se infecta. \"\"\" \"\"\" ### Caso E2c: el escenario m\u00e1s optimista Para finalizar voy a simular el escenario m\u00e1s optimista posible que aun es compatible con lo que hemos observado en la realidad. Tambien he introducido un parametro nuevo que es el retardo de observaci\u00f3n, el","meta":"{'source': 'AI4Code', 'id': '930cd065aa7883'}"}
{"id":"135741","text":"\"\"\"\n# Identifikation von Drusenarten in OCT-Images\n### Unter der Verwendung des matterplot Mask-R-CNN Ansatzes\n\"\"\"\n\"\"\"\n**Helpful-Links:**\n* https:\/\/github.com\/matterport\/Mask_RCNN\n\"\"\"\n\"\"\"\n# Setup Umgebung\n\"\"\"\nimport sys\nimport os\nos.chdir('\/kaggle\/')\n!git clone https:\/\/www.github.com\/matterport\/Mask_RCNN.git Mask_RCNN\nos.chdir('\/kaggle\/Mask_RCNN')\nos.makedirs('logs')\n#!git clone https:\/\/github.com\/matterport\/Mask_RCNN.git\n#os.chdir(\"\/kaggle\/working\/Mask_RCNN\")\n#!rm -r samples images README.md assets LICENSE MANIFEST.in\n#!ls\n#shutil.rmtree('\/kaggle\/working\/logs')\nos.walk('\/kaggle\/input')\n!pip install -r requirements.txt\n!pip install tensorflow-gpu==1.15\n!pip install keras==2.2.5\n!conda install -c anaconda --yes cudatoolkit\n!conda install -c anaconda --yes cudnn\n\"\"\"\n## Pfade\n\"\"\"\nROOT_PATH='\/kaggle\/'\nMASK_PATH='\/kaggle\/Mask_RCNN\/'\nMODEL_PATH='\/kaggle\/Mask_RCNN\/logs\/'\nTRAIN_PATH='\/kaggle\/input\/start-train\/'\nTEST_PATH='\/kaggle\/input\/transfer-learning-test\/'\nVAL_PATH='\/kaggle\/input\/start-val\/'\nJSON_PATH='\/kaggle\/input\/json-label\/'\nTRANSFER_TRAIN_PATH = '\/kaggle\/input\/transfer-train\/'\nTRANSFER_VAL_PATH = '\/kaggle\/input\/transfer-val\/'\nTRANSFER_TEST_PATH = '\/kaggle\/input\/transfer-test\/'\n#Einmalig genutzte Befehle\n#os.makedirs('\/kaggle\/working\/mrcnn')\n#os.makedirs('\/kaggle\/working\/Mask_RCNN\/')\n#os.makedirs('\/kaggle\/working\/Mask_RCNN\/logs')\n#os.makedirs('\/kaggle\/input\/transfer_learning_test')\n#os.makedirs('\/kaggle\/input\/transfer_learning_val')\n#os.rmdir('\/kaggle\/working\/Mask_RCNN\/transfer_learning_test')\n\n#1x gebraucht\n#os.makedirs('\/kaggle\/working\/Mask_RCNN\/logs')\n#os.makedirs('\/kaggle\/working\/logs')\n#os.makedirs('\/kaggle\/logs')\n\n#for folder in os.listdir('\/'):\n#    print (folder)\n\"\"\"\n# Import\n\"\"\"\nimport json\nimport gc\nimport datetime\nimport numpy as np\nimport skimage.draw\nfrom imgaug import augmenters as iaa\nimport pandas as pd\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(ROOT_PATH)\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR)  # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\n\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\"\"\"\n#  Configurations\n\"\"\"\nclass OCTConfig(Config):\n   \n    NAME = \"OCT\"\n\n    # We use a GPU with 12GB memory, which can fit two images.\n    # Adjust down if you use a smaller GPU.\n    IMAGES_PER_GPU = 2\n\n    # Number of classes (including background)\n    # TODO CHANGE\n    NUM_CLASSES = 1 + 2 + 3 # Background + ObereSchicht + UntereSchicht + druse + hr + pseudo\n\n    # Number of training steps per epoch\n    STEPS_PER_EPOCH = 150\n    #STEPS_PER_EPOCH = 30\n\n    DETECTION_MIN_CONFIDENCE = 0.75\n\n    TRAIN_ROIS_PER_IMAGE = 100\n    \n    BACKBONE = \"resnet50\"\n    \n    MAX_GT_INSTANCES = 100\n    \n    IMAGE_MIN_DIM = 512\n    IMAGE_MAX_DIM = 512\n\"\"\"\n# Dataset\n\"\"\"\nclass OCTDataset(utils.Dataset):\n\n    def load_oct(self, subset):\n\n        self.add_class(\"oct\", 1, \"RPE\")  # adjusted here\n        self.add_class(\"oct\", 2, \"BM\")  # adjusted here\n        self.add_class(\"oct\", 3, \"druse\")  # adjusted here\n        self.add_class(\"oct\", 4, \"hr\")  # adjusted here\n        self.add_class(\"oct\", 5, \"pseudo\")  # adjusted here\n\n        dataset_dir = \"\"\n        # Train or validation dataset?\n        if subset == \"start_train\":\n            dataset_dir=TRAIN_PATH\n        if subset == \"start_val\":\n            dataset_dir=VAL_PATH\n        if subset == \"transfer_train\":\n            dataset_dir=TRANSFER_TRAIN_PATH\n        if subset == \"transfer_val\":\n            dataset_dir=TRANSFER_VAL_PATH\n        if subset == \"transfer_test\":\n            dataset_dir=TRANSFER_TEST_PATH\n            \n            numberImages = 0\n            for filename in os.listdir('\/kaggle\/input\/transfer-test\/'):\n                image_path = os.path.join(dataset_dir, filename)\n\n                image = skimage.io.imread(image_path)\n                height, width = image.shape[:2]\n                numberImages = numberImages+1\n                class_name_nums = []\n\n                self.add_image(\n                    \"oct\",\n                    image_id=filename,  # use file name as a unique image id\n                    path=image_path,\n                    width=width, height=height,\n                    polygons=[],\n                    class_list=np.array(\n                        class_name_nums))\n                \n            self.dataset_size = numberImages\n        \n        if(subset != \"transfer_test\"):\n            annotations = json.load(open(os.path.join(JSON_PATH, \"via_export_json_\"+subset+\".json\")))\n            annotations = list(annotations.values())  # don't need the dict keys\n            annotations = [a for a in annotations if a['regions']]\n\n            numberImages = 0\n\n            # Add images\n            for a in annotations:\n\n                if type(a['regions']) is dict:\n                    polygons = [r['shape_attributes'] for r in a['regions'].values()]\n                else:\n                    polygons = [r['shape_attributes'] for r in a['regions']]\n\n                class_names_str = [r['region_attributes']['shape'] for r in a['regions']]\n                class_name_nums = []\n\n                for i in class_names_str:\n                    if i == 'RPE':\n                        class_name_nums.append(1)\n                    if i == 'BM':\n                        class_name_nums.append(2)\n                    if i == 'druse':\n                        class_name_nums.append(3)\n                    if i == 'hr':\n                        class_name_nums.append(4)\n                    if i == 'pseudo':\n                        class_name_nums.append(5)\n\n                image_path = os.path.join(dataset_dir, a['filename'])\n\n                image = skimage.io.imread(image_path)\n                height, width = image.shape[:2]\n                numberImages = numberImages+1\n\n                self.add_image(\n                    \"oct\",\n                    image_id=a['filename'],  # use file name as a unique image id\n                    path=image_path,\n                    width=width, height=height,\n                    polygons=polygons,\n                    class_list=np.array(\n                        class_name_nums))  # UNSURE IF  I CAN JUST ADD THIS  HERE. OTHERWISE NEED  TO MODIFY DATASET UTIL\n\n                self.dataset_size = numberImages\n\n    def load_mask(self, image_id):\n        # If not a balloon dataset image, delegate to parent class.\n        image_info = self.image_info[image_id]\n        if image_info[\"source\"] != \"oct\":  # adjusted here\n            return super(self.__class__, self).load_mask(image_id)\n\n        # Convert polygons to a bitmap mask of shape\n        # [height, width, instance_count]\n        info = self.image_info[image_id]\n        mask = np.zeros([info[\"height\"], info[\"width\"], len(info[\"polygons\"])],\n                        dtype=np.uint8)\n        for i, p in enumerate(info[\"polygons\"]):\n            # Get indexes of pixels inside the polygon and set them to 1\n            rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])\n            mask[rr, cc, i] = 1\n\n        class_array = info['class_list']\n        return mask.astype(np.bool), class_array\n\n    def image_reference(self, image_id):\n        \"\"\"Return the path of the image.\"\"\"\n        info = self.image_info[image_id]\n        if info[\"source\"] == \"oct\":  # adjusted here\n            return info[\"path\"]\n        else:\n            super(self.__class__, self).image_reference(image_id)\n\"\"\"\n#  Training\n\"\"\"\nweights = \"coco\"\nlogs= \"logs\"\ncommand = \"train\"\n\n# Configurations\nif command == \"train\":\n    config = OCTConfig()\nconfig.display()\n\n# Create model\nif command == \"train\":\n    model = modellib.MaskRCNN(mode=\"training\", \n                              config=config, \n                              model_dir=logs)\n\nmodel.keras_model.summary()\n\n# Select weights file to load\nif weights.lower() == \"coco\":\n    weights_path = COCO_WEIGHTS_PATH\n    # Download weights file\n    if not os.path.exists(weights_path):\n        utils.download_trained_weights(weights_path)\nelif weights.lower() == \"last\":\n    # Find last trained weights\n    weights_path = model.find_last()\nelse:\n    weights_path = weights\n\n# Load weights\nprint(\"Loading weights \", weights_path)\nif weights.lower() == \"coco\":\n    # Exclude the last layers because they require a matching\n    # number of classes\n    model.load_weights(weights_path, by_name=True, exclude=[\n        \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n        \"mrcnn_bbox\", \"mrcnn_mask\"])\nelse:\n    model.load_weights(weights_path, by_name=True)\n\n\"\"\"\n## Augmentation\n\"\"\"\naugmentation = iaa.SomeOf((0, 2), [\n        iaa.Flipud(0.5),\n        iaa.Fliplr(0.5),  # horizontal flips\n        iaa.Crop(percent=(0, 0.1)),  # random crops\n\n        # Make some images brighter and some darker.\n        # In 20% of all cases, we sample the multiplier once per channel,\n        # which can end up changing the color of the images.\n        iaa.Multiply((0.8, 1.2), per_channel=0.2),\n\n        # Apply affine transformations to each image.\n        # Scale\/zoom them, translate\/move them, rotate them and shear them.\n        iaa.Affine(\n            scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n            translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n            rotate=(-25, 25),\n            shear=(-8, 8)\n        )\n    ], random_order=True)\n\nimg=mpimg.imread(TRAIN_PATH + \"DRUSEN-9689334-1.jpeg\")\nimggrid = augmentation.draw_grid(img, cols=5, rows=2)\nplt.figure(figsize=(30, 12))\n_ = plt.imshow(imggrid.astype(int))\n# Training dataset.\nprint('preparing training set')\ndataset_train = OCTDataset()\ndataset_train.load_oct(\"start_train\")\ndataset_train.prepare()\n\n# Validation dataset\nprint('preparing val set')\ndataset_val = OCTDataset()\ndataset_val.load_oct(\"start_val\")\ndataset_val.prepare()\n# starting_epoch = model.epoch\nepoch = int(dataset_train.dataset_size \/ (config.STEPS_PER_EPOCH * config.BATCH_SIZE) * 1)\n#epoch = 5\n#epochs_warmup = 1 * epoch\nepochs_warmup = 20 #Die anzahl wird beim vortraining genutzt\n#epochs_warmup = 5\nepochs_heads = 7 * epoch  # + starting_epoch\nepochs_stage4 = 7 * epoch  # + starting_epoch\n#epochs_all = 7 * epoch  # + starting_epoch\nepochs_all = 70 #die anzahl wird beim transfer genutzt\n#epochs_all = 10 #die anzahl wird beim transfer genutzt\nepochs_breakOfDawn = 5 * epoch\n\nprint(\"> Training Schedule: \\\n    \\nwarmup: {} epochs \\\n    \\nheads: {} epochs \\\n    \\nstage4+: {} epochs \\\n    \\nall layers: {} epochs \\\n    \\ntill the break of Dawn: {} epochs\".format(\n    epochs_warmup,epochs_heads,epochs_stage4,epochs_all,epochs_breakOfDawn))\n\"\"\"\n%%time\n## Training - WarmUp Stage\nprint(\"> Warm Up all layers\")\nmodel.train(dataset_train, dataset_val,\n            learning_rate=config.LEARNING_RATE \/ 10,\n            epochs=epochs_warmup,\n            layers='all',\n            augmentation=augmentation)\n\nhistory = model.keras_model.history.history\n\"\"\"\n%%time\n# Training - Stage 1\nprint(\"> Training network heads\")\nmodel.train(dataset_train, dataset_val,\n            learning_rate=0.001,\n            epochs= epochs_warmup,\n            layers='all',\n            augmentation=augmentation)\n\nhistory = model.keras_model.history.history\n\n# copy only the last version of .h5 to output\nu_ordner = os.listdir('\/kaggle\/Mask_RCNN\/logs\/')[0]\nprint(u_ordner)\n\nos.chdir(\"\/kaggle\/Mask_RCNN\/logs\/\"+u_ordner+\"\/\")\n#teste welche Datei die neuste ist\nneusterFilename = 'newFilename'\nfileCreateDate = int(0)\nfor file in os.listdir(\"\/kaggle\/Mask_RCNN\/logs\/\"+u_ordner+\"\/\"):\n    if file.endswith(\".h5\"):\n        if(int((os.path.getmtime(file))) > fileCreateDate):\n            fileCreateDate = int(os.path.getmtime(file))\n            neusterFilename = file\n            \n#kopiere Modell in output-Ordner\nkopierZeile = 'cp \/kaggle\/Mask_RCNN\/logs\/'+ u_ordner + '\/' + neusterFilename + ' \/kaggle\/working\/'\nos.system(kopierZeile)\n\nos.chdir('\/kaggle\/Mask_RCNN')\n\"\"\"\n# Transfer Part\n\"\"\"\n# clean vars\n#del dataset_train\n#del dataset_val\ngc.collect()\n%%time\n# Anpassung der Trainings- und Testdaten (Ordner)!\n# Training dataset.\nprint('preparing training set')\ndataset_train = OCTDataset()\ndataset_train.load_oct(\"transfer_train\")\ndataset_train.prepare()\n\n# Validation dataset\nprint('preparing val set')\ndataset_val = OCTDataset()\ndataset_val.load_oct(\"transfer_val\")\ndataset_val.prepare()\naugmentation = iaa.SomeOf((0, 2), [\n        iaa.Flipud(0.5),\n        iaa.Fliplr(0.5),  # horizontal flips\n        iaa.Crop(percent=(0, 0.1)),  # random crops\n\n        # Make some images brighter and some darker.\n        # In 20% of all cases, we sample the multiplier once per channel,\n        # which can end up changing the color of the images.\n        iaa.Multiply((0.8, 1.2), per_channel=0.2),\n\n        # Apply affine transformations to each image.\n        # Scale\/zoom them, translate\/move them, rotate them and shear them.\n        iaa.Affine(\n            scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n            translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n            rotate=(-25, 25),\n            shear=(-8, 8)\n        )\n    ], random_order=True)\n\nimg=mpimg.imread(\"\/kaggle\/input\/transfer-train\/DRUSEN-95633-1.jpeg\")\nimggrid = augmentation.draw_grid(img, cols=5, rows=2)\nplt.figure(figsize=(30, 12))\n_ = plt.imshow(imggrid.astype(int))\n\ngc.collect()\n# transfer learning - dursen trainieren\nmodel.train(dataset_train, dataset_val,\n            learning_rate=0.001,\n            epochs= epochs_all,\n            layers='heads',\n            augmentation=augmentation)\n\nhistory = model.keras_model.history.history\n# copy only the last version of .h5 to output\nu_ordner = os.listdir('\/kaggle\/Mask_RCNN\/logs\/')[0]\nprint(u_ordner)\n\nos.chdir(\"\/kaggle\/Mask_RCNN\/logs\/\"+u_ordner+\"\/\")\n#teste welche Datei die neuste ist\nneusterFilename = 'newFilename'\nfileCreateDate = int(0)\nfor file in os.listdir(\"\/kaggle\/Mask_RCNN\/logs\/\"+u_ordner+\"\/\"):\n    if file.endswith(\".h5\"):\n        if(int((os.path.getmtime(file))) > fileCreateDate):\n            fileCreateDate = int(os.path.getmtime(file))\n            neusterFilename = file\n            \n#kopiere Modell in output-Ordner\nkopierZeile = 'cp \/kaggle\/Mask_RCNN\/logs\/'+ u_ordner + '\/' + neusterFilename + ' \/kaggle\/working\/'\nos.system(kopierZeile)\n\nos.chdir('\/kaggle\/Mask_RCNN')\n\"\"\"\n%%time\n# Training - Stage 2\n# Finetune layers  stage 4 and up\nprint(\"> Fine tune {} stage 4 and up\".format(config.BACKBONE))\nmodel.train(dataset_train, dataset_val,\n            learning_rate=config.LEARNING_RATE,\n            epochs=epochs_stage4,\n            layers=\"4+\",\n            augmentation=augmentation)\n\nnew_history = model.keras_model.history.history\nfor k in new_history: history[k] = history[k] + new_history[k]\n\"\"\"\n\"\"\"\n%%time\n# Training - Stage 3\n# Fine tune all layers\nprint(\"> Fine tune all layers\")\nmodel.train(dataset_train, dataset_val,\n            learning_rate=config.LEARNING_RATE \/ 10,\n            epochs=epochs_all,\n            layers='all',\n            augmentation=augmentation)\n\nnew_history = model.keras_model.history.history\nfor k in new_history: history[k] = history[k] + new_history[k]\n\"\"\"\n\"\"\"\n## Metrics\n\"\"\"\nepochs = range(1, len(history['loss'])+1)\npd.DataFrame(history, index=epochs)\nplt.figure(figsize=(21,11))\n\nplt.subplot(231)\nplt.plot(epochs, history[\"loss\"], label=\"Train loss\")\nplt.plot(epochs, history[\"val_loss\"], label=\"Valid loss\")\nplt.legend()\nplt.subplot(232)\nplt.plot(epochs, history[\"rpn_class_loss\"], label=\"Train RPN class ce\")\nplt.plot(epochs, history[\"val_rpn_class_loss\"], label=\"Valid RPN class ce\")\nplt.legend()\nplt.subplot(233)\nplt.plot(epochs, history[\"rpn_bbox_loss\"], label=\"Train RPN box loss\")\nplt.plot(epochs, history[\"val_rpn_bbox_loss\"], label=\"Valid RPN box loss\")\nplt.legend()\nplt.subplot(234)\nplt.plot(epochs, history[\"mrcnn_class_loss\"], label=\"Train MRCNN class ce\")\nplt.plot(epochs, history[\"val_mrcnn_class_loss\"], label=\"Valid MRCNN class ce\")\nplt.legend()\nplt.subplot(235)\nplt.plot(epochs, history[\"mrcnn_bbox_loss\"], label=\"Train MRCNN box loss\")\nplt.plot(epochs, history[\"val_mrcnn_bbox_loss\"], label=\"Valid MRCNN box loss\")\nplt.legend()\nplt.subplot(236)\nplt.plot(epochs, history[\"mrcnn_mask_loss\"], label=\"Train Mask loss\")\nplt.plot(epochs, history[\"val_mrcnn_mask_loss\"], label=\"Valid Mask loss\")\nplt.legend()\n\nplt.show()\n\nbest_epoch = np.argmin(history[\"val_loss\"])\nscore = history[\"val_loss\"][best_epoch]\nprint(f'Best Epoch:{best_epoch+1} val_loss:{score}')\n\"\"\"\n# Result\n\"\"\"\n\"\"\"\n## Load Model\n\"\"\"\nimport os\nimport sys\nimport random\nimport math\nimport re\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom glob import glob\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR)  # To find local version of the library\nfrom mrcnn import utils\nfrom mrcnn import visualize\nfrom mrcnn.visualize import display_images\nimport mrcnn.model as modellib\nfrom mrcnn.model import log\n\n%matplotlib inline \n\n# Directory to save logs and trained model\nMODEL_DIR = MODEL_PATH\n\"\"\"\n## Configuration\n\"\"\"\nconfig = OCTConfig()\nOCT_DIR = os.path.join(ROOT_DIR, \"\")\nclass InferenceConfig(config.__class__):\n    # Run detection on one image at a time\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 1\n\nconfig = InferenceConfig()\nconfig.DETECTION_MIN_CONFIDENCE = 0.80\nconfig.display()\n\nDEVICE = \"\/cpu:0\"  # \/cpu:0 or \/gpu:0\nTEST_MODE = \"inference\"\n\ndef get_ax(rows=1, cols=1, size=16):\n    _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))\n    return ax\n\"\"\"\n## Load Validation Dataset\n\n\"\"\"\n# Load validation dataset\ndataset = OCTDataset()\ndataset.load_oct(\"transfer_val\")\n\n# Must call before using the dataset\ndataset.prepare()\n\nprint(\"Images: {}\\nClasses: {}\".format(len(dataset.image_ids), dataset.class_names))\n\nprint(dataset.image_ids)\n\"\"\"\n## Load Model\n\"\"\"\nwith tf.device(DEVICE):\n    model = modellib.MaskRCNN(mode=\"inference\", model_dir='\/kaggle\/Mask_RCNN\/logs\/',\n                              config=config)\n\nweights_path = model.find_last()\n\n# Load weights\nprint(\"Loading weights \", weights_path)\nmodel.load_weights(weights_path, by_name=True)\n\"\"\"\n## Run Detection\n\"\"\"\n#Display results\nnumberPictures=min(len(dataset.image_ids),10)\nax = get_ax(rows=numberPictures,cols=2)\n\nfor i in range(0,numberPictures):\n    image_id = random.choice(dataset.image_ids)\n    image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n        modellib.load_image_gt(dataset, config, image_id, use_mini_mask=False)\n    info = dataset.image_info[image_id]\n    print(\"image ID: {}.{} ({}) {}\".format(info[\"source\"], info[\"id\"], image_id, \n                                           dataset.image_reference(image_id)))\n    \n    # Run object detection\n    results = model.detect([image], verbose=1)\n\n    r = results[0]\n\n    visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n                                dataset.class_names, r['scores'], ax=ax[i,0],\n                                title=\"Predictions \")\n    \n    image2=mpimg.imread(dataset.image_reference(image_id))\n    ax[i,1].set_title(\"Blank\")\n    ax[i,1].imshow(image2)\n        \n    log(\"gt_class_id\", gt_class_id)\n    log(\"gt_bbox\", gt_bbox)\n    log(\"gt_mask\", gt_mask)\n\"\"\"\n## RPN Targets\n\"\"\"\n# Generate RPN trainig targets\n# target_rpn_match is 1 for positive anchors, -1 for negative anchors\n# and 0 for neutral anchors.\n#target_rpn_match, target_rpn_bbox = modellib.build_rpn_targets(\n#    image.shape, model.anchors, gt_class_id, gt_bbox, model.config)\n#log(\"target_rpn_match\", target_rpn_match)\n#log(\"target_rpn_bbox\", target_rpn_bbox)\n\n#positive_anchor_ix = np.where(target_rpn_match[:] == 1)[0]\n#negative_anchor_ix = np.where(target_rpn_match[:] == -1)[0]\n#neutral_anchor_ix = np.where(target_rpn_match[:] == 0)[0]\n#positive_anchors = model.anchors[positive_anchor_ix]\n#negative_anchors = model.anchors[negative_anchor_ix]\n#neutral_anchors = model.anchors[neutral_anchor_ix]\n#log(\"positive_anchors\", positive_anchors)\n#log(\"negative_anchors\", negative_anchors)\n#log(\"neutral anchors\", neutral_anchors)\n\n# Apply refinement deltas to positive anchors\n#refined_anchors = utils.apply_box_deltas(\n#    positive_anchors,\n#    target_rpn_bbox[:positive_anchors.shape[0]] * model.config.RPN_BBOX_STD_DEV)\n#log(\"refined_anchors\", refined_anchors, )\n\n#visualize.draw_boxes(image, boxes=positive_anchors, refined_boxes=refined_anchors, ax=get_ax())\n\n\"\"\"\n## RPN Predictions\n\"\"\"\n# Run RPN sub-graph\n#pillar = model.keras_model.get_layer(\"ROI\").output  # node to start searching from\n\n# TF 1.4 and 1.9 introduce new versions of NMS. Search for all names to support TF 1.3~1.10\n#nms_node = model.ancestor(pillar, \"ROI\/rpn_non_max_suppression:0\")\n#if nms_node is None:\n#    nms_node = model.ancestor(pillar, \"ROI\/rpn_non_max_suppression\/NonMaxSuppressionV2:0\")\n#if nms_node is None: #TF 1.9-1.10\n#    nms_node = model.ancestor(pillar, \"ROI\/rpn_non_max_suppression\/NonMaxSuppressionV3:0\")\n\n#rpn = model.run_graph([image], [\n#    (\"rpn_class\", model.keras_model.get_layer(\"rpn_class\").output),\n#    (\"pre_nms_anchors\", model.ancestor(pillar, \"ROI\/pre_nms_anchors:0\")),\n#    (\"refined_anchors\", model.ancestor(pillar, \"ROI\/refined_anchors:0\")),\n#    (\"refined_anchors_clipped\", model.ancestor(pillar, \"ROI\/refined_anchors_clipped:0\")),\n#    (\"post_nms_anchor_ix\", nms_node),\n#    (\"proposals\", model.keras_model.get_layer(\"ROI\").output),\n#])\n\n#limit = 100\n#sorted_anchor_ids = np.argsort(rpn['rpn_class'][:,:,1].flatten())[::-1]\n#visualize.draw_boxes(image, boxes=model.anchors[sorted_anchor_ids[:limit]], ax=get_ax())\n# Show top anchors with refinement. Then with clipping to image boundaries\n#limit = 50\n#ax = get_ax(1, 2)\n#pre_nms_anchors = utils.denorm_boxes(rpn[\"pre_nms_anchors\"][0], image.shape[:2])\n#refined_anchors = utils.denorm_boxes(rpn[\"refined_anchors\"][0], image.shape[:2])\n#refined_anchors_clipped = utils.denorm_boxes(rpn[\"refined_anchors_clipped\"][0], image.shape[:2])\n#visualize.draw_boxes(image, boxes=pre_nms_anchors[:limit],\n#                     refined_boxes=refined_anchors[:limit], ax=ax[0])\n#visualize.draw_boxes(image, refined_boxes=refined_anchors_clipped[:limit], ax=ax[1])\n# Show refined anchors after non-max suppression\n#limit = 50\n#ixs = rpn[\"post_nms_anchor_ix\"][:limit]\n#visualize.draw_boxes(image, refined_boxes=refined_anchors_clipped[ixs], ax=get_ax())\n# Show final proposals\n# These are the same as the previous step (refined anchors \n# after NMS) but with coordinates normalized to [0, 1] range.\n#limit = 50\n# Convert back to image coordinates for display\n#h, w = config.IMAGE_SHAPE[:2]\n#proposals = rpn['proposals'][0, :limit] * np.array([h, w, h, w])\n#visualize.draw_boxes(image, refined_boxes=proposals, ax=get_ax())\n# Get input and output to classifier and mask heads.\n#mrcnn = model.run_graph([image], [\n#    (\"proposals\", model.keras_model.get_layer(\"ROI\").output),\n#    (\"probs\", model.keras_model.get_layer(\"mrcnn_class\").output),\n#    (\"deltas\", model.keras_model.get_layer(\"mrcnn_bbox\").output),\n#    (\"masks\", model.keras_model.get_layer(\"mrcnn_mask\").output),\n#    (\"detections\", model.keras_model.get_layer(\"mrcnn_detection\").output),\n#])\n\n# Get detection class IDs. Trim zero padding.\n#det_class_ids = mrcnn['detections'][0, :, 4].astype(np.int32)\n#det_count = np.where(det_class_ids == 0)[0][0]\n#det_class_ids = det_class_ids[:det_count]\n#detections = mrcnn['detections'][0, :det_count]\n\n#print(\"{} detections: {}\".format(\n#    det_count, np.array(dataset.class_names)[det_class_ids]))\n\n#captions = [\"{} {:.3f}\".format(dataset.class_names[int(c)], s) if c > 0 else \"\"\n#            for c, s in zip(detections[:, 4], detections[:, 5])]\n#visualize.draw_boxes(\n#    image, \n#    refined_boxes=utils.denorm_boxes(detections[:, :4], image.shape[:2]),\n#    visibilities=[2] * len(detections),\n#    captions=captions, title=\"Detections\",\n#    ax=get_ax())\n\"\"\"\n##  Proposal Classification\n\"\"\"\n# Get input and output to classifier and mask heads.\n#mrcnn = model.run_graph([image], [\n#    (\"proposals\", model.keras_model.get_layer(\"ROI\").output),\n#    (\"probs\", model.keras_model.get_layer(\"mrcnn_class\").output),\n#    (\"deltas\", model.keras_model.get_layer(\"mrcnn_bbox\").output),\n#    (\"masks\", model.keras_model.get_layer(\"mrcnn_mask\").output),\n#    (\"detections\", model.keras_model.get_layer(\"mrcnn_detection\").output),\n#])\n\n# Get detection class IDs. Trim zero padding.\n#det_class_ids = mrcnn['detections'][0, :, 4].astype(np.int32)\n#det_count = np.where(det_class_ids == 0)[0][0]\n#det_class_ids = det_class_ids[:det_count]\n#detections = mrcnn['detections'][0, :det_count]\n\n#print(\"{} detections: {}\".format(\n#    det_count, np.array(dataset.class_names)[det_class_ids]))\n\n#captions = [\"{} {:.3f}\".format(dataset.class_names[int(c)], s) if c > 0 else \"\"\n#            for c, s in zip(detections[:, 4], detections[:, 5])]\n#visualize.draw_boxes(\n#    image, \n#    refined_boxes=utils.denorm_boxes(detections[:, :4], image.shape[:2]),\n#    visibilities=[2] * len(detections),\n#    captions=captions, title=\"Detections\",\n#    ax=get_ax())\n\n\"\"\"\n## Step by Step Detection\n\"\"\"\n# Proposals are in normalized coordinates. Scale them\n# to image coordinates.\n#h, w = config.IMAGE_SHAPE[:2]\n#proposals = np.around(mrcnn[\"proposals\"][0] * np.array([h, w, h, w])).astype(np.int32)\n\n# Class ID, score, and mask per proposal\n#roi_class_ids = np.argmax(mrcnn[\"probs\"][0], axis=1)\n#roi_scores = mrcnn[\"probs\"][0, np.arange(roi_class_ids.shape[0]), roi_class_ids]\n#roi_class_names = np.array(dataset.class_names)[roi_class_ids]\n#roi_positive_ixs = np.where(roi_class_ids > 0)[0]\n\n# How many ROIs vs empty rows?\n#print(\"{} Valid proposals out of {}\".format(np.sum(np.any(proposals, axis=1)), proposals.shape[0]))\n#print(\"{} Positive ROIs\".format(len(roi_positive_ixs)))\n\n# Class counts\n#print(list(zip(*np.unique(roi_class_names, return_counts=True))))\n# Display a random sample of proposals.\n# Proposals classified as background are dotted, and\n# the rest show their class and confidence score.\n#limit = 200\n#ixs = np.random.randint(0, proposals.shape[0], limit)\n#captions = [\"{} {:.3f}\".format(dataset.class_names[c], s) if c > 0 else \"\"\n#            for c, s in zip(roi_class_ids[ixs], roi_scores[ixs])]\n#visualize.draw_boxes(image, boxes=proposals[ixs],\n#                     visibilities=np.where(roi_class_ids[ixs] > 0, 2, 1),\n#                     captions=captions, title=\"ROIs Before Refinement\",\n#                     ax=get_ax())\n\"\"\"\n## Apply Bounding Box Refinement\n\"\"\"\n# Class-specific bounding box shifts.\n#roi_bbox_specific = mrcnn[\"deltas\"][0, np.arange(proposals.shape[0]), roi_class_ids]\n#log(\"roi_bbox_specific\", roi_bbox_specific)\n\n# Apply bounding box transformations\n# Shape: [N, (y1, x1, y2, x2)]\n#refined_proposals = utils.apply_box_deltas(\n#    proposals, roi_bbox_specific * config.BBOX_STD_DEV).astype(np.int32)\n#log(\"refined_proposals\", refined_proposals)\n\n# Show positive proposals\n# ids = np.arange(roi_boxes.shape[0])  # Display all\n#limit = 5\n#ids = np.random.randint(0, len(roi_positive_ixs), limit)  # Display random sample\n#captions = [\"{} {:.3f}\".format(dataset.class_names[c], s) if c > 0 else \"\"\n#            for c, s in zip(roi_class_ids[roi_positive_ixs][ids], roi_scores[roi_positive_ixs][ids])]\n#visualize.draw_boxes(image, boxes=proposals[roi_positive_ixs][ids],\n#                     refined_boxes=refined_proposals[roi_positive_ixs][ids],\n#                     visibilities=np.where(roi_class_ids[roi_positive_ixs][ids] > 0, 1, 0),\n#                     captions=captions, title=\"ROIs After Refinement\",\n#                     ax=get_ax())\n\"\"\"\n## Filter Low Confidence Detections\n\"\"\"\n#keep = np.where(roi_class_ids > 0)[0]\n#print(\"Keep {} detections:\\n{}\".format(keep.shape[0], keep))\n\n# Remove low confidence detections\n#keep = np.intersect1d(keep, np.where(roi_scores >= config.DETECTION_MIN_CONFIDENCE)[0])\n#print(\"Remove boxes below {} confidence. Keep {}:\\n{}\".format(\n#    config.DETECTION_MIN_CONFIDENCE, keep.shape[0], keep))\n\"\"\"\n## Per-Class Non-Max Suppression\n\"\"\"\n# Apply per-class non-max suppression\n#pre_nms_boxes = refined_proposals[keep]\n#pre_nms_scores = roi_scores[keep]\n#pre_nms_class_ids = roi_class_ids[keep]\n\n#nms_keep = []\n#for class_id in np.unique(pre_nms_class_ids):\n    # Pick detections of this class\n#    ixs = np.where(pre_nms_class_ids == class_id)[0]\n    # Apply NMS\n#    class_keep = utils.non_max_suppression(pre_nms_boxes[ixs], \n#                                            pre_nms_scores[ixs],\n#                                            config.DETECTION_NMS_THRESHOLD)\n    # Map indicies\n#    class_keep = keep[ixs[class_keep]]\n#    nms_keep = np.union1d(nms_keep, class_keep)\n#    print(\"{:22}: {} -> {}\".format(dataset.class_names[class_id][:20], \n#                                   keep[ixs], class_keep))\n\n#keep = np.intersect1d(keep, nms_keep).astype(np.int32)\n#print(\"\\nKept after per-class NMS: {}\\n{}\".format(keep.shape[0], keep))\n# Show final detections\n#ixs = np.arange(len(keep))  # Display all\n# ixs = np.random.randint(0, len(keep), 10)  # Display random sample\n#captions = [\"{} {:.3f}\".format(dataset.class_names[c], s) if c > 0 else \"\"\n#            for c, s in zip(roi_class_ids[keep][ixs], roi_scores[keep][ixs])]\n#visualize.draw_boxes(\n#    image, boxes=proposals[keep][ixs],\n#    refined_boxes=refined_proposals[keep][ixs],\n#    visibilities=np.where(roi_class_ids[keep][ixs] > 0, 1, 0),\n#    captions=captions, title=\"Detections after NMS\",\n#    ax=get_ax())\n\"\"\"\n## Generating Masks\n\"\"\"\n#display_images(np.transpose(gt_mask, [2, 0, 1]), cmap=\"Blues\")\n# Get predictions of mask head\n#mrcnn = model.run_graph([image], [\n#    (\"detections\", model.keras_model.get_layer(\"mrcnn_detection\").output),\n#    (\"masks\", model.keras_model.get_layer(\"mrcnn_mask\").output),\n#])\n\n# Get detection class IDs. Trim zero padding.\n#det_class_ids = mrcnn['detections'][0, :, 4].astype(np.int32)\n#det_count = np.where(det_class_ids == 0)[0][0]\n#det_class_ids = det_class_ids[:det_count]\n\n#print(\"{} detections: {}\".format(\n#    det_count, np.array(dataset.class_names)[det_class_ids]))\n# Masks\n#det_boxes = utils.denorm_boxes(mrcnn[\"detections\"][0, :, :4], image.shape[:2])\n#det_mask_specific = np.array([mrcnn[\"masks\"][0, i, :, :, c] \n#                              for i, c in enumerate(det_class_ids)])\n#det_masks = np.array([utils.unmold_mask(m, det_boxes[i], image.shape)\n#                      for i, m in enumerate(det_mask_specific)])\n#log(\"det_mask_specific\", det_mask_specific)\n#log(\"det_masks\", det_masks)\n#display_images(det_mask_specific[:4] * 255, cmap=\"Blues\", interpolation=\"none\")#\n#display_images(det_masks[:4] * 255, cmap=\"Blues\", interpolation=\"none\")\n\"\"\"\n## Visualize Activations\n\n\"\"\"\n# Get activations of a few sample layers\n#activations = model.run_graph([image], [\n#    (\"input_image\",        tf.identity(model.keras_model.get_layer(\"input_image\").output)),\n#    (\"res2c_out\",          model.keras_model.get_layer(\"res2c_out\").output),\n#    (\"res3c_out\",          model.keras_model.get_layer(\"res3c_out\").output),\n#    (\"res4w_out\",          model.keras_model.get_layer(\"res4w_out\").output),  # for resnet100\n#    (\"rpn_bbox\",           model.keras_model.get_layer(\"rpn_bbox\").output),\n#    (\"roi\",                model.keras_model.get_layer(\"ROI\").output),\n#])\n# Input image (normalized)\n#_ = plt.imshow(modellib.unmold_image(activations[\"input_image\"][0],config))\n# Backbone feature map\n#display_images(np.transpose(activations[\"res2c_out\"][0,:,:,:4], [2, 0, 1]), cols=4)","meta":"{'source': 'AI4Code', 'id': 'f988fdd3970c41'}"}
{"id":"59126","text":"\"\"\"\n# Digit Recognizer\n\"\"\"\n\"\"\"\n###### CNN on classic dataset of handwritten images\n\"\"\"\n\"\"\"\n### Importing important libraries\n\"\"\"\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nimport tensorflow as tf\n\"\"\"\n### Reading Datasets\n\"\"\"\n\"\"\"\n##### Train Dataset\n\"\"\"\ntrain = pd.read_csv('..\/input\/train.csv')\ntrain.head()\ntrain.describe()\n\"\"\"\n##### Test Dataset\n\"\"\"\ntest = pd.read_csv('..\/input\/test.csv')\ntest.head()\ntest.describe()\n\"\"\"\n### Exploratory Data Analsysis\n\"\"\"\n\"\"\"\n#### Checking for NULL values\n\"\"\"\ntrain.melt(id_vars=\"label\")['value'].isnull().sum()\ntest.melt()['value'].isnull().sum()\n\"\"\"\n#### Count of each labels\n\"\"\"\ntrain['label'].value_counts().sort_index()\n# Plot\nplt.figure(figsize=(8, 4))\nsns.set_style(\"whitegrid\")\nsns.countplot(x=\"label\", data=train)\nplt.xlabel(\"Label\")\nplt.ylabel(\"Count\")\nplt.show()\n\"\"\"\n#### Dividing the training dataset into X and y\n\"\"\"\ny = train['label']\nX = train.drop(['label'], axis = 1)\n\"\"\"\n#### Normalize the pixel data, i.e. converting values from 0 - 254 to 0 - 1 \n\"\"\"\nX = X \/ 255\ntest = test \/ 255\n\"\"\"\n#### Converting labels to numpy array\n\"\"\"\ny = np.array(y)\n\"\"\"\n#### Reshaping image to 28px X 28px dimension\n\"\"\"\nX = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\nplt.imshow(X[0][:,:,0])\n\"\"\"\n### Modelling CNN\n\"\"\"\n\"\"\"\n#### Creating train and test datasets\n\"\"\"\nrandom_seed = 4\n# Split the train and test set for the fitting\ntrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size = 0.1, random_state=random_seed)\n\"\"\"\n### Tensorflow Model\n\"\"\"\n# Tensorflow Keras CNN Model\nmodel = tf.keras.models.Sequential()\n\nmodel.add(tf.keras.layers.Conv2D(32, (3,3), padding = \"same\", activation = \"relu\", input_shape = train_X.shape[1:]))\nmodel.add(tf.keras.layers.MaxPool2D(2,2))\n\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), padding = \"same\", activation = \"relu\"))\nmodel.add(tf.keras.layers.MaxPool2D(2,2))\n\nmodel.add(tf.keras.layers.Conv2D(128, (3,3), padding = \"same\", activation = \"relu\"))\nmodel.add(tf.keras.layers.MaxPool2D(2,2))\n\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))\n\n\"\"\"\n#### Optimizer and loss function\n\"\"\"\nmodel.compile(optimizer='adam', \n              loss='sparse_categorical_crossentropy', \n              metrics=['accuracy'])\nmodel.summary()\n\"\"\"\n#### Fitting the train dataset\n\"\"\"\nmodel.fit(train_X, train_y, epochs=3)\n\"\"\"\n#### Finding the loss and accuracy of the model\n\"\"\"\nval_loss, val_acc = model.evaluate(test_X, test_y) \nval_acc\n\"\"\"\n### Predicting the submission dataframe\n\"\"\"\n\"\"\"\n#### Fitting the full train data\n\"\"\"\nmodel.fit(X, y, epochs=3)\n\"\"\"\n#### Predicting on given test data\n\"\"\"\ntest_pred = model.predict(test)\nsubmission = pd.DataFrame()\nsubmission['ImageId'] = range(1, (len(test)+1))\nsubmission['Label'] = np.argmax(test_pred, axis=1)\nsubmission.head()\nsubmission.shape\n\"\"\"\n#### Saving in a csv file\n\"\"\"\nsubmission.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': '6d25b415939f44'}"}
{"id":"6105","text":"# 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 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\n\"\"\"\nConvert the csv file into a dataframe\n\"\"\"\ndf = pd.read_csv('..\/input\/iphone-price-from-flipkartcom\/iphoneFlipkart.csv')\n\"\"\"\nThen we check the columns, number of rows and null values. Although most of the time it is given by the dataset provider in kaggle but it is better to practice this sanity checking.\n\"\"\"\ndf.info()\n\"\"\"\nNow we will dive into the dataset using the .head() method. I usually like to see first 10 and last 10 rows.\n\"\"\"\ndf.head(10)\ndf.tail(10)\n\"\"\"\n# Its time to do some exploratory data analysis.\n\"\"\"\n\"\"\"\nFirst we will check the status column. \n\"\"\"\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\ncolour = [\"#e74c3c\", \"#34495e\"]\nsns.set_style('darkgrid')\nsns.set_palette(colour)\nsns.set_context('notebook')\n\ng = sns.catplot(y = 'Status' , data = df, kind = 'count', height = 3, aspect = 3.5)\ng.set(xlabel = 'Classes', ylabel ='Samples in each class')\nplt.show()\n\n\"\"\"\nWe can see there are only two types of status and most of them are not deliverable. \n\nWe could the same for other classes as well.\n\"\"\"\ns = sns.color_palette(sns.cubehelix_palette(10))\ng = sns.catplot(y = 'Product_Name', data = df, kind = 'count', height = 12, aspect = 2, palette = s)\ng.set(xlabel = 'Samples in each class', ylabel ='Classes')\nplt.show()\n\"\"\"\nWe can see Iphone 11, Iphone XR and Iphone 8 are most available in the store.\n\"\"\"\ng = sns.pairplot(df, hue=\"Status\", palette=\"husl\", markers=[\"D\", \"o\"])\n\"\"\"\nWe can also look at the average prices for different Iphones with different storages.\n\"\"\"\ndf.groupby(['Memmory','Product_Name'])['Price'].mean()\ndf.pivot_table(values = 'Price' , index = 'Product_Name' , columns = 'Color', fill_value = 0, margins = True)\n\"\"\"\n***This is my simple work within few minutes. Hope you will like it. I am still very new in this area. So, give feedback on my mistakes. Happy Hacking :)***\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0b47bcb19e5bdb'}"}
{"id":"95653","text":"\"\"\"\n# Regression Definition \n**Regression is a statistical method used to determine the strength of the relationship between one dependent variable (Y) and a series of other changing variables (X).**\n\n**If the relationship is linear between Y and X, then it is Linear Regression**\n\"\"\"\n\"\"\"\n# Assumptions of Linear Regression\n1. X and Y are linearly related\n2. No Multicollinearity between X variables\n3. No Auto-correlation between residuals\n4. Residuals follow Normal distribution\n5. Residuals follow homoscedastic\n\"\"\"\n# Import the file\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport pandas as pd\nfrom patsy import dmatrices\n# Read the data\ndf = pd.read_csv('\/kaggle\/input\/dataset\/data.csv')\ndf.head()\n\"\"\"\n# Assumption 1\n\n**Relationship between X variable and Y variable is Linear**\n\n1. Plot the scatter plot for each X with Y\n2. Look for approximate linear relationship\n3. if it's not linear, then try to \"Drop X variable\" or \"Change the technique\" or \"apply transformation log(X)\".\n\n\n\"\"\"\nfrom matplotlib import pyplot as plt \n# Scatter plot between X1 and Output\nplt.scatter(df.X1, df.Output)\n# Scatter plot between X2 and Output\nplt.scatter(df.X2, df.Output)\n# Scatter plot between X3 and Output\nplt.scatter(df.X3, df.Output)\n# Scatter plot between X4 and Output\nplt.scatter(df.X4, df.Output)\n\"\"\"\n**from above plots it is clear that, X1 variable and X2 variable are almost Linear to Y variable**\n\"\"\"\n\"\"\"\n# Assumption 2\n\"\"\"\n\"\"\"\nNo Multicollinearity between X variables\n* There should not any significant relationship between X variables\n* VIF (Variance Inflation factor) can be used to find out the relationship between X variables\n* In VIF, each X variable is picked and regress with other X variables.\n* VIF = 1\/(1-R2)\n* Higher the R2, greater the VIF.\n* In general, VIF > 5 or VIF > 10 indicates high multicollinearity.\n\"\"\"\ndf.head(2)\ndf.columns\n# Consider only X variables\ndf1 = df[['X1', 'X2', 'X3', 'X4']]\ndf1.head(2)\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nVIF = pd.DataFrame()\nVIF['feature'] = df1.columns\nVIF['VIF'] = [variance_inflation_factor(df1.values, i) \n                          for i in range(len(df1.columns))] \nVIF\n\"\"\"\n**From above it is clear that, VIF values are > 10. It means X variables are highly correlated.**\n\"\"\"\n\"\"\"\n# Assumption 3\n\"\"\"\n\"\"\"\n**No Auto correlation between Residuals**\n* Residuals are random and independent.\n\"\"\"\n\"\"\"\n**Residuals are Random**\n\n1. For a given sample (X_train, y_train) from a Dataset, run the linear regression model.\n2. predict the output = y(pred)\n3. difference between Y and Y(pred) is Residual.\n4. If we pick another sample of (X_train, y_train), model will generate the output = y(pred) which is different from previous one. \n5. Now we have different set of Residuals. \n6. So, Residuals are Random.\n\"\"\"\n\"\"\"\n**Residuals are Independent**\n\n* Two random variables are independent if the probability of one of them taking up some value doesn\u2019t depend on what value the other variable has taken\n\n   **Example:**\n\n* When you roll a die twice, the probability of its coming up as (1,2,3,4,5,6) in the second throw does not depend on the value it came up on the first throw. So the two throws are independent random variables that can each take a value from (1,6), independent of the other throw\n\"\"\"\n\"\"\"\n**Check if residuals are independent**\n\n* sometimes patterns can be detected in the plot of 'residual errors' vs 'predicted values' or         'residual errors' vs 'actual values'.\n* Durbin-Watson test is used to check if residuals are independent or not.\n* It measures degree of correlation of each residual error with the \u2018previous\u2019 residual error\n\"\"\"\nmodel = 'Output ~  X1 + X2 + X3 + X4'\n# in Above expression, Output is Y varialble and remaning are X variables.\ny, X = dmatrices(model, df, return_type='dataframe')\ny.head(2)\nX.head(2)\n# Now split the (train\/test) data into (70\/30)\nimport numpy as np\nsplit_num = np.random.rand(len(X)) < 0.7\nX_train = X[split_num]\ny_train = y[split_num]\nX_test = X[~split_num]\ny_test = y[~split_num]\nX_train.shape\n# Build the model\nimport statsmodels.api as sm\nLR = sm.OLS(y_train, X_train).fit()\nLR.summary()\n# Predict 'Y' for the test data\ny_test_pred = LR.predict(X_test)\ny_test_pred = pd.DataFrame(y_test_pred)\ny_test_pred.head()\n# Rename the column\ny_test_pred = y_test_pred.rename(columns = {0:'Output'})\ny_test_pred.head()\n# Calculate the residual\nResidual = y_test - y_test_pred\nResidual\n# Residual vs Predicted value\nplt.scatter(x = y_test_pred, y = Residual)\nplt.xlabel('Predicted values')\nplt.ylabel('Residuals')\n\"\"\"\n**Above graph illustrates a linear pattern at the end**\n\n**If Durbin Watson value is around 2, then there is no auto correlation between residuals**\n\"\"\"\n\"\"\"\n# Assumption 4\n\"\"\"\n\"\"\"\n**Residuals are Normally Distributed**\n1. 'Skewness' and 'Kurtosis' is used to measure the normality of Residuals.\n2. Skewness of a perfectly normal distribution is 0 and its kurtosis is 3.0\n3. Statistical tests like 'Jarque Bera' or Omnibus can be used.\n4. If p value <= 0.05, then we can say distribution is normal with >= 95% cofidence.\n\"\"\"\nfrom statsmodels.compat import lzip\nimport statsmodels.stats.api as sms\n# 'Jarque Bera test' for finding the normality of Residuals\nname = ['Jarque-Bera test', 'p-value', 'Skewness', 'Kurtosis']\n# Perform 'Jarque-Bera' test\nJB_test = sms.jarque_bera(Residual)\n# Print\nlzip(name, JB_test)\n\"\"\"\n**From above it is clear that, Skewness is close to 0 and Kurtosis is close to 3**\n\n**We can confirm by plotting frequency of Residuals**\n\"\"\"\nResidual.hist(bins = 40)\nplt.show()\n\"\"\"\n**Above graph illustrates that Residuals are almost normally distributed**\n\"\"\"\n\"\"\"\n# Assumption 5\n\"\"\"\n\"\"\"\n**Residuals follow homoscedastic**\n* Homo means Same, scedastic means variance - so homoscedastic means same variance (Constant variance)\n* Heteroscedastic means - Different Variance\n\"\"\"\n\"\"\"\n**Below are few tests to find out homoscedasticity**\n1. Park test\n2. Glejser test\n3. Breusch\u2013Pagan test\n4. White test\n5. Goldfeld\u2013Quandt test\n\"\"\"\n# White test \nfrom statsmodels.stats.diagnostic import het_white\nkeys = ['Lagrange Multiplier statistic:', 'LM test\\'s p-value:', 'F-statistic:', 'F-test\\'s p-value:']\nresult = het_white(Residual, X_test)\nlzip(keys, result)\n\"\"\"\n**F test Hypothesis**\n* Null Hypothesis :     Residuals are homoscedasticity\n* Alternate hypothesis: Residuals are heteroscedasticity\n\"\"\"\n\"\"\"\n**From above, it is clear that p-value <=0.05. Hence null hypothesis is rejected.** \n\n**So Residuals follow heteroscedasticity**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'afa0dbb4e93ded'}"}
{"id":"28229","text":"\"\"\"\n## Virtual Shakespeare - Natural Language Processing\n<img src=\"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/a\/a2\/Shakespeare.jpg\" width=\"200\" height=\"200\"\/>\n\n#### Hola folks! Don't be fooled by the clickbait title.<br> In this quest to recreate Shakespeare, I was partly successful. Actually, no I wasn't.<br> Still, I was able to create a 3 year old Shakespeare, with some broken words and a bit of a hate for grammar.\n\n#### Okay, coming to this notebook. I have used a dataset of Shakespeare's works to train a model, which on giving an input text, will produce an output text of desired length.\n\n#### In the output text, you can observe that they follow the same structure as shakespeare's works, uses similar words and similar dialogues.<br> This output text is completely computer generated and not a subset of the dataset. \n\n#### The dataset has over 5 million characters, and 84 distinct characters.\n\n##### I will not be documenting the entire notebook, although comments have been provided for easy understanding.<br>As I am still learning NLP, some part of this notebook might not be correct or it may contain things that don't make sense. I'm really sorry about those. \n\n### Corrections and improvements to this notebook are most welcome. It will really help me in learning more.\n\n### Do upvote it, if you like it!\n\"\"\"\n\"\"\"\n####  I have provided a sample output at the top, please go through the entire notebook, to understand how it all works. \n\"\"\"\n#Sample output\nprint(generate_text(model, 'Et tu, Brute?', gen_size = 1000))\n#importing libraries and packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n#load the dataset containing shakespeare's works\ntext = open('..\/input\/shakespeare.txt', 'r').read()\nprint(text[:1000])\n\"\"\"\n# Dataset Statistics\n\"\"\"\ntotal_char = len(list(text))\nunique_char = len(set(text))\n\ntext_cleaned = ''\nalphalist = [chr(i) for i in range(ord('A'), ord('z')+1)]\n\nfor i in text:\n    if i.isalpha():\n        text_cleaned += i\n    else:\n        text_cleaned += ' '\n\nchar_count = {}\nfor i in text_cleaned.split():\n    if i in char_count:\n        char_count[i] += 1\n    else:\n        char_count[i] = 1\n        \ndf = pd.DataFrame(char_count.items(), columns=['Words','Count'])\ndf.sort_values('Count', axis=0, ascending=False, inplace=True)\ndf.reset_index(drop=True, inplace=True)\nprint('Total Characters: ', total_char)\nprint('Unique Characters: ', unique_char)\nprint('Most used words:')\ndisplay(df.head(10))\n\"\"\"\n# Text Preprocessing\n\"\"\"\n#Get all the unique characters\nvocab = sorted(set(text))\nvocab_size = len(vocab)\nprint(vocab)\nprint('Total uniques characters: ',vocab_size)\n#Map characters to numbers and numbers to characters\nchar_to_ind = {u:i for i,u in enumerate(vocab)}\nind_to_char = {i:u for i,u in enumerate(vocab)}\nprint(char_to_ind)\nprint('\\n')\nprint(ind_to_char)\n#encode the first 1000 characters as numbers\nencoded_text = np.array([char_to_ind[c] for c in text])\nprint(encoded_text[:1000])\n\"\"\"\n# Training Sequence\n\"\"\"\n#number of sequences to generate\nseq_len = 120\ntotal_num_seq = len(text)\/\/(seq_len+1)\nprint('Total Number of Sequences: ', total_num_seq)\n#Create training sequences\n#tf.data.Dataset.from_tensor_slices function converts a text vector\n#into a stream of character indices\nchar_dataset = tf.data.Dataset.from_tensor_slices(encoded_text)\n\nfor i in char_dataset.take(500):\n    print(ind_to_char[int(i)],end=\"\")\n#batch method converts these individual character calls into sequences\n#which we can feed in as a batch\n#we use seq_len+1 because we will use seq_len characters\n#and shift them one step forward\n#drop remainder drops the remaining characters < batch_size\nsequences = char_dataset.batch(seq_len+1, drop_remainder=True)\n#this function will grab a sequence\n#take the [0:n-1] characters as input text\n#take the [1:n] characters as target text\n#return a tuple of both\ndef create_seq_targets(seq):\n    input_txt = seq[:-1]\n    target_txt = seq[1:]\n    return input_txt, target_txt\n#this will convert the series of sequences into\n#a series of tuple containing input and target text\ndataset = sequences.map(create_seq_targets)\nfor input_txt, target_txt in dataset.take(1):\n    print(''.join([ind_to_char[i] for i in np.array(input_txt)]))\n    print('\\n')\n    print(''.join([ind_to_char[i] for i in np.array(target_txt)]))\n\n#the target is shifter 1 character forward\n#the last character is a space and is thus not visible\n\"\"\"\n# Generating training batches\n\"\"\"\nbatch_size = 128 #number of sequence tuples in each batch\nbuffer_size = 10000 #shuffle this many sequences in the dataset\n\n#first shuffle the dataset and divide it into batches\n#drop the last sequences < batch_size\ndataset = dataset.shuffle(buffer_size).batch(batch_size, drop_remainder=True)\n#count the number of batches\n#i couldn't find a function to do it in O(1)\n#please let me know\n\nx = 0\nfor i in dataset:\n    x += 1\nprint('Total Batches:', x)\nprint('Sequences in each batch: ', batch_size)\nprint('Characters in each sequence:', seq_len)\nprint('Characters in dataset: ', len(list(text)))\n\"\"\"\n# Creating the Model\n\"\"\"\n#importing keras modules\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM,Dense,Embedding,Dropout,GRU\nfrom tensorflow.keras.losses import sparse_categorical_crossentropy\n#using sparse_categorical_crossentropy because\n#out predictions will be numbers and not one hot encodings\n#we need to define a custom loss function so that we can change\n#the from_logits parameter to True\ndef sparse_cat_loss(y_true, y_pred):\n    return sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)\ndef create_model(batch_size):\n    vocab_size_func = vocab_size\n    embed_dim = 64 #the embedding dimension\n    rnn_neurons = 1024 #number of rnn units\n    batch_size_func = batch_size\n    \n    model = Sequential()\n    \n    model.add(Embedding(vocab_size_func, \n                        embed_dim, \n                        batch_input_shape=[batch_size_func, None]))\n    model.add(GRU(rnn_neurons, \n                  return_sequences=True, \n                  stateful=True, \n                  recurrent_initializer='glorot_uniform'))\n    \n    model.add(Dense(vocab_size_func))    \n    model.compile(optimizer='adam', loss=sparse_cat_loss)    \n    \n    return model\nmodel = create_model(batch_size)\nmodel.summary()\n\"\"\"\n# Training the Model\n\"\"\"\n\"\"\"\n#### As we have  created the model, random weights and biases have been assigned, so before begining training lets first check whether the model is working or not.\n\"\"\"\n#note this will generate random characters\n#dataset.take(1) contains 1 batch = 128 sequence tuples\n#model will output 120 characters per sequence\n#in the form of probability of those 84 vocab characters\nfor ex_input, ex_target in dataset.take(1):\n    ex_pred = model(ex_input)\nprint(ex_pred.shape)\n\n#changes the character probabilities to integers\nsampled_indices = tf.random.categorical(ex_pred[0], num_samples=1)\n\n#maps those integers to characters\nchar_pred = ''.join([ind_to_char[int(i)] for i in sampled_indices])\n\nprint(char_pred)\n#training the model\nmodel.fit(dataset, epochs=30, verbose=1)\n#save the model\nmodel.save('shakespeare.h5')\n\"\"\"\n# Generating text\n\"\"\"\n# importing load_model to load the keras model\nfrom tensorflow.keras.models import load_model\n#create a new model with a batch size of 1\nmodel = create_model(batch_size=1)\n\n#load the weights from the previous model to our new model\nmodel.load_weights('shakespeare.h5')\n\n#build the model\nmodel.build(tf.TensorShape([1, None]))\n\n#view model summary\nprint(model.summary())\n#function to generate text based on an input text\n#we enter the text on which our output will be based\n#we define how many characters we want in output\n\ndef generate_text(model, start_seed, gen_size=100):\n    num_generate = gen_size\n    input_eval = [char_to_ind[s] for s in start_seed]\n    input_eval = tf.expand_dims(input_eval, 0)\n    \n    text_generated = []\n    \n    model.reset_states()\n    \n    for i in range(num_generate):\n        predictions = model(input_eval)\n        predictions = tf.squeeze(predictions, 0)\n        \n        predicted_id = tf.random.categorical(predictions, num_samples=1)[-1, 0].numpy()\n        \n        input_eval = tf.expand_dims([predicted_id], 0)\n        \n        text_generated.append(ind_to_char[predicted_id])\n        \n    return (start_seed + ''.join(text_generated))\n#generate a text based on input\n#note that, this out is not part of the dataset\n#but completely auto generated\nauto_text = generate_text(model, 'How art thou?', gen_size = 1000)\nprint(auto_text)\n#download the saved model\nmodel.save('shakespeare.h5')\nfrom IPython.display import FileLink\nFileLink(r'shakespeare.h5')","meta":"{'source': 'AI4Code', 'id': '33f3bb5a8a4e70'}"}
{"id":"71181","text":"\"\"\"\n## Dataset: [Face Mask Detection](https:\/\/www.kaggle.com\/andrewmvd\/face-mask-detection)\n\"\"\"\n!git clone https:\/\/github.com\/rkuo2000\/yolov5\n%cd yolov5\n\"\"\"\n## Repro [YOLOv5](https:\/\/github.com\/ultralytics\/yolov5)\n\"\"\"\n!mkdir -p Dataset\/FaceMask\/Images\n!mkdir -p Dataset\/FaceMask\/Labels\n# copy image files\n!cp -rf \/kaggle\/input\/face-mask-detection\/images\/* Dataset\/FaceMask\/Images\n!mkdir -p Dataset\/images Dataset\/labels\n\"\"\"\n## Create Dataset\n\"\"\"\nimport os\nimport numpy as np\nfrom pathlib import Path\nfrom xml.dom.minidom import parse\nfrom shutil import copyfile\nFILE_ROOT = \"\/kaggle\/input\/face-mask-detection\/\"\nIMAGE_PATH = FILE_ROOT + \"images\"  \nANNOTATIONS_PATH = FILE_ROOT + \"annotations\"\n\nDATA_ROOT = \"Dataset\/\"\nLABELS_ROOT = DATA_ROOT + \"FaceMask\/Labels\"\nIMAGES_ROOT = DATA_ROOT + \"FaceMask\/Images\"  \n\nDEST_IMAGES_PATH = \"images\"\nDEST_LABELS_PATH = \"labels\" \nclasses = ['with_mask', 'without_mask', 'mask_weared_incorrect']\n\"\"\"\n### convert annotations (from COCO .xml to YOLO format .txt)\n\"\"\"\ndef cord_converter(size, box):\n    \"\"\"\n    convert xml annotation to darknet format coordinates\n    :param size\uff1a [w,h]\n    :param box: anchor box coordinates [upper-left x,uppler-left y,lower-right x, lower-right y]\n    :return: converted [x,y,w,h]\n    \"\"\"\n    x1 = int(box[0])\n    y1 = int(box[1])\n    x2 = int(box[2])\n    y2 = int(box[3])\n\n    dw = np.float32(1. \/ int(size[0]))\n    dh = np.float32(1. \/ int(size[1]))\n\n    w = x2 - x1\n    h = y2 - y1\n    x = x1 + (w \/ 2)\n    y = y1 + (h \/ 2)\n\n    x = x * dw\n    w = w * dw\n    y = y * dh\n    h = h * dh\n    return [x, y, w, h]\n\ndef save_file(img_jpg_file_name, size, img_box):\n    save_file_name = LABELS_ROOT + '\/' + img_jpg_file_name + '.txt'\n    print(save_file_name)\n    file_path = open(save_file_name, \"a+\")\n    for box in img_box:\n\n        cls_num = classes.index(box[0])\n\n        new_box = cord_converter(size, box[1:])\n\n        file_path.write(f\"{cls_num} {new_box[0]} {new_box[1]} {new_box[2]} {new_box[3]}\\n\")\n\n    file_path.flush()\n    file_path.close()\n    \ndef get_xml_data(file_path, img_xml_file):\n    img_path = file_path + '\/' + img_xml_file + '.xml'\n    print(img_path)\n\n    dom = parse(img_path)\n    root = dom.documentElement\n    img_name = root.getElementsByTagName(\"filename\")[0].childNodes[0].data\n    img_size = root.getElementsByTagName(\"size\")[0]\n    objects = root.getElementsByTagName(\"object\")\n    img_w = img_size.getElementsByTagName(\"width\")[0].childNodes[0].data\n    img_h = img_size.getElementsByTagName(\"height\")[0].childNodes[0].data\n    img_c = img_size.getElementsByTagName(\"depth\")[0].childNodes[0].data\n    # print(\"img_name:\", img_name)\n    # print(\"image_info:(w,h,c)\", img_w, img_h, img_c)\n    img_box = []\n    for box in objects:\n        cls_name = box.getElementsByTagName(\"name\")[0].childNodes[0].data\n        x1 = int(box.getElementsByTagName(\"xmin\")[0].childNodes[0].data)\n        y1 = int(box.getElementsByTagName(\"ymin\")[0].childNodes[0].data)\n        x2 = int(box.getElementsByTagName(\"xmax\")[0].childNodes[0].data)\n        y2 = int(box.getElementsByTagName(\"ymax\")[0].childNodes[0].data)\n        # print(\"box:(c,xmin,ymin,xmax,ymax)\", cls_name, x1, y1, x2, y2)\n        img_jpg_file_name = img_xml_file + '.jpg'\n        img_box.append([cls_name, x1, y1, x2, y2])\n    # print(img_box)\n\n    # test_dataset_box_feature(img_jpg_file_name, img_box)\n    save_file(img_xml_file, [img_w, img_h], img_box)\nfiles = os.listdir(ANNOTATIONS_PATH)\nfor file in files:\n    print(\"file name: \", file)\n    file_xml = file.split(\".\")\n    get_xml_data(ANNOTATIONS_PATH, file_xml[0])\n\"\"\"\n## split Images dataset\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nimage_list = os.listdir('Dataset\/FaceMask\/Images')\ntrain_list, test_list = train_test_split(image_list, test_size=0.2, random_state=7)\nval_list, test_list = train_test_split(test_list, test_size=0.5, random_state=8)\n\nprint('total =',len(image_list))\nprint('train :',len(train_list))\nprint('val   :',len(val_list))\nprint('test  :',len(test_list))\ndef copy_data(file_list, img_labels_root, imgs_source, type):\n\n    root_file = Path(DATA_ROOT + DEST_IMAGES_PATH + '\/' + type)\n    if not root_file.exists():\n        print(f\"Path {root_file} is not exit\")\n        os.makedirs(root_file)\n\n    root_file = Path(DATA_ROOT + DEST_LABELS_PATH + '\/' + type)\n    if not root_file.exists():\n        print(f\"Path {root_file} is not exit\")\n        os.makedirs(root_file)\n\n    for file in file_list:\n        img_name = file.replace('.png', '')\n        img_src_file = imgs_source + '\/' + img_name + '.png'\n        label_src_file = img_labels_root + '\/' + img_name + '.txt'\n\n        # print(img_sor_file)\n        # print(label_sor_file)\n        # im = Image.open(rf\"{img_sor_file}\")\n        # im.show()\n\n        # Copy image\n        DICT_DIR = DATA_ROOT + DEST_IMAGES_PATH + '\/' + type\n        img_dict_file = DICT_DIR + '\/' + img_name + '.png'\n\n        copyfile(img_src_file, img_dict_file)\n\n        # Copy label\n        DICT_DIR = DATA_ROOT + DEST_LABELS_PATH + '\/' + type\n        img_dict_file = DICT_DIR + '\/' + img_name + '.txt'\n        copyfile(label_src_file, img_dict_file)\ncopy_data(train_list, LABELS_ROOT, IMAGES_ROOT, \"train\")\ncopy_data(val_list,   LABELS_ROOT, IMAGES_ROOT, \"val\")\ncopy_data(test_list,  LABELS_ROOT, IMAGES_ROOT, \"test\")\n\"\"\"\n## Create data\/facemask.yaml\n\"\"\"\n!echo \"train: Dataset\/images\/train\\n\" > data\/facemask.yaml\n!echo \"val:   Dataset\/images\/val\\n\" >> data\/facemask.yaml\n!echo \"nc : 3\\n\" >> data\/facemask.yaml\n!echo \"names: ['With_Mask', 'Without_Mask', 'Incorrect_Mask']\\n\" >> data\/facemask.yaml\n\n!cat data\/facemask.yaml\n\"\"\"\n## Train YOLOv5\n<a href=\"..\/tree\/yolov5\/weights\">link to weight folder to upload pretrained model<\/a>\n\"\"\"\n!ls\n# Train with default Yolov5.weight\n#!python train.py --img 320 --batch 16 --epochs 50 --data data\/facemask.yaml --cfg models\/yolov5s.yaml --weights yolov5s.pt\n\n# Train with pretrained weight >>> upload newest file to folder weights\n!python train.py --img 320 --batch 16 --epochs 50 --data data\/facemask.yaml --cfg models\/yolov5s.yaml --weights weights\/pretrained.pt\n\n# save trained weights for detection\n!cp runs\/train\/exp\/weights\/pretrained.pt weights\n\"\"\"\n<h2>DOWNLOAD<\/h2>\n\n<a href=\"https:\/\/kkb-production.jupyter-proxy.kaggle.net\/k\/54994990\/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwidHlwIjoiSldUIn0..BSWsiW8jGQTSeityClU6XQ.0zu6Bt6JSZJPCQpitQEeamc-PdEpBAyG7SYqhfSzXRaJFuqRU1HMLt9djHClz9Xygk07I4cuZxK-vAa0GjjDMQP0be1F-spgZh9WfyzQQmVPzW0eqHp8XWYRX11NiYowwjEzjCumyMKFesrvXvo_801PSCNTnbjzPrQ5aOIIjxsXf5vdBVSdRRdGtN20DOxyC2zBKpW_o583tVIYs5xxmg.JGIUJ6JicuYOERIlQcA72A\/proxy\/tree\/yolov5\/weights\/best.pt\"> Download BEST weight <\/a>\n\"\"\"\n\"\"\"\n## Test YOLOv5\n\"\"\"\n\"\"\"\n### detect facemask\n\"\"\"\n!python detect.py --source Dataset\/images\/test --img-size 320 --conf 0.4 --weights weights\/pretrained.pt \n# display detected images\nfrom IPython.display import Image\nfrom glob import glob\nimport matplotlib.pyplot as plt\ntestfiles = glob('runs\/detect\/exp\/*')\n\nimg = plt.imread(testfiles[0]) \nplt.imshow(img)    \nplt.show\n!python detect.py --source \/kaggle\/input\/input-images\/facemask.jpg --img-size 320 --conf 0.4 --weights weights\/pretrained.pt \nImage('runs\/detect\/exp2\/facemask.jpg')\n!python detect.py --source \/kaggle\/input\/input-images\/facemask1.jpg --img-size 320 --conf 0.4 --weights weights\/pretrained.pt \nImage('runs\/detect\/exp3\/facemask1.jpg')","meta":"{'source': 'AI4Code', 'id': '82eddf3c6f4583'}"}
{"id":"133517","text":"\"\"\"\n# Running algorithms - Feature Engineering for fast inference\n\n\nOne of the main problem in this competition is about the inference : we have to predict outcomes one by one, which take quite some time.\nThis bottleneck also impact what we can do with feature engineering as we are limited to things that calculate fast during the inference process. \nI looked what could be used iteratively to stay within this time constraint. \nIt appears that there is a whole class of algorithms - running algorithms (or sometimes streaming algorithms) - that are designed exactly for this kind of problems.\n\nI was about to publish a notebook about financial feature engineering alone, but I figured this wouldn't be very useful without inference implementations. So I decided to fuse both and here we are : in this notebook I give you some of the usual financial feature engineering tools and, along some standard python implementation, I try to provide you with streaming algorithms that will allow you to calculate them during inference. And it turns out that using numpy is **EXTREMELY FAST**. What is not in this notebook : some way to decide what parameter value to use (lag) or on which features to use this techniques (this might be the topic of another notebook \ud83d\ude09). \n\nPlease keep in mind that those implementations are my owns. So there might be some problems (well there are some problems, I even point them out), feel free to comment with a correction. \n\nIf you want to go further, you can check my other works (about [Intraday Feature Exploration](https:\/\/www.kaggle.com\/lucasmorin\/complete-intraday-feature-exploration),[Target Engineering](https:\/\/www.kaggle.com\/lucasmorin\/target-engineering-patterns-denoising), and [using yfinance to download financial data in Ptyhon](https:\/\/www.kaggle.com\/lucasmorin\/downloading-market-data)). Feel free to upvote \/ share my notebooks.\nLucas\n\n## updates :\n\nv.11 : added a complete exemple with a model\n\nv.13 : \n\n- Did some testing and modified edge case\n- Added a dummy environnement for testing\n- will probably split training and submission\n\n## Features engineering techniques :\n\n- [Moving Average (starter)](#Moving_Average) \ud83c\udfc3\ud83c\udfc3\ud83c\udfc3\n- [Moving Moments](#Moving_Moments) (variance, skew, kurtosis) \ud83c\udfc3\ud83c\udfc3\n- [Exponentially Weighted Moving Average](#EWMA) \ud83c\udfc3\ud83c\udfc3\ud83c\udfc3\n- [Past day average ](#PDA)\ud83c\udfc3\ud83c\udfc3\n- [Paste Trade Information](#PTI) \ud83c\udfc3\ud83c\udfc3\ud83c\udfc3\n- [Differentiation ](#DIFF)\n- [Fractional differentiation](#FDIFF)\n- [Entropy](#Entropy)\n\n# Application :\n\n- [Bottleneck encoder + MLP + Keras Tuner](#MLP)\n- [Dummy Environnement](#Dummy_Env)\n- [Submission](#Submission)\n\"\"\"\n\"\"\"\n# Loading base packages\n\nNothing too surprising here. Collections deque data structure will help us keep track of past data.\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport pickle\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom numba import njit\n\nimport collections\nimport math\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\"\"\"\n# Load data\n\nLoading a pickle file. Check this notebook [pickling](https:\/\/www.kaggle.com\/quillio\/pickling) if you haven't pickled your data set yet. Check this notebook [one liner to halve your memory usage](https:\/\/www.kaggle.com\/jorijnsmit\/one-liner-to-halve-your-memory-usage) if you want to reduce memory usage before pickling.\n\"\"\"\n%%time\ntrain_pickle_file = '\/kaggle\/input\/pickling\/train.csv.pandas.pickle'\ntrain_data = pickle.load(open(train_pickle_file, 'rb'))\ntrain_data.info()\n\"\"\"\n<a id='Moving_Average'><\/a>\n# Moving Average (starter)\n\nIt is a very standard indicator for financial time series. The goal here is to build a demo. Honestly from what I have seen so far, as we have different securities in the data running windows mean doesn't appears to be that usefull for lower windows.\nIf you want to test their importance the usual pandas way of doing that is simply :\n\"\"\"\n# Don't launch that as it may consume a lot of memory)\n#rw = 10000\n#train_data_rolled = train_data.rolling(window=rw).mean()\n\"\"\"\nFor a streaming algorithm the idea is to build a class that allows to keep track of past values. Largely inspired from this [Stack exchange answer](https:\/\/stackoverflow.com\/questions\/5147378\/rolling-variance-algorithm). \n\"\"\"\nfrom collections import deque\n\nclass RunningMean:\n    def __init__(self, WIN_SIZE=20, n_size = 1):\n        self.n = 0\n        self.mean = np.zeros(n_size)\n        self.cum_sum = 0\n        self.past_value = 0\n        self.WIN_SIZE = WIN_SIZE\n        self.windows = collections.deque(maxlen=WIN_SIZE+1)\n        \n    def clear(self):\n        self.n = 0\n        self.windows.clear()\n\n    def push(self, x):\n        \n        x = fillna_npwhere_njit(x, self.past_value)\n        self.past_value = x\n        \n        self.windows.append(x)\n        self.cum_sum += x\n        \n        if self.n < self.WIN_SIZE:\n            self.n += 1\n            self.mean = self.cum_sum \/ float(self.n)\n            \n        else:\n            self.cum_sum -= self.windows.popleft()\n            self.mean = self.cum_sum \/ float(self.WIN_SIZE)\n\n    def get_mean(self):\n        return self.mean if self.n else np.zeros(n_size)\n\n    def __str__(self):\n        return \"Current window values: {}\".format(list(self.windows))\n\n# Temporary removing njit as it cause many bugs down the line\n# Problems mainly due to data types, I have to find where I need to constraint types so as not to make njit angry\n#@njit\ndef fillna_npwhere_njit(array, values):\n    if np.isnan(array.sum()):\n        array = np.where(np.isnan(array), values, array)\n    return array\n\"\"\"\n**We can check that it run fast (iterrrows allow to loop trough rows of a data frame as an interable). Here using numpy array instead of pandas datframe allow to go from 1600 it\/sec to 9000+ it\/seconds when keeping track of ALL 10000 tick lagged means. Using @gogo827jz fillna method allow to breach 10000 it\/sec.** \n\n**It also shows you how easy it is to use for inference.**\n\"\"\"\na = RunningMean(WIN_SIZE=10000)\n\nfor index, row in tqdm(train_data[:100000].iterrows()): \n    a.push(np.array(row))\n    \na.get_mean()\n\"\"\"\nI still have two main problems here :\n - <s> It doesn't seem to converge properly due to some rounding error (see below)<\/s> Thanks to @magokecol for pointing the mistake out !\n - It does not handle na as is. I propose some code to use the last value at the moment, which might be pertinent for some fetaure but probably not all of them. It is also a bit slower when activated (from 1800 it\/sec to 1400 with it\/sec).\n \nThe second point is not problematic as is, but if we want to use it properly we might either want to replicate exactly what standards library (rolling) does or we want to apply the streaming algo to our whole train set, so as not to create a discrepency between the two.\n\"\"\"\na = RunningMean(WIN_SIZE=10)\n\nfor index, row in pd.DataFrame({'col1':range(1,100)}).iterrows(): \n    a.push(np.array(row))\n    \nprint(a.get_mean())\nprint((90+91+92+93+94+95+96+97+98+99)\/10)\n\"\"\"\n# \ud83d\ude0d\n\"\"\"\n\"\"\"\n<a id='Moving_Moments'><\/a>\n# Moving Moments (variance, skew, kurtosis)\n\nThe aforementionned stack exchange post also implement the variance :\n\"\"\"\nfrom __future__ import division\nimport collections\nimport math\n\n\nclass RunningStats:\n    def __init__(self, WIN_SIZE=20, n_size = 1):\n        self.n = 0\n        self.mean = 0\n        self.run_var = 0\n        self.WIN_SIZE = WIN_SIZE\n        self.past_value = 0\n        self.windows = collections.deque(maxlen=WIN_SIZE+1)\n\n    def clear(self):\n        self.n = 0\n        self.windows.clear()\n\n    def push(self, x):\n        \n        x = fillna_npwhere_njit(x, self.past_value)\n        self.past_value = x\n\n        self.windows.append(x)\n\n        if self.n < self.WIN_SIZE:\n            # Calculating first variance\n            self.n += 1\n            delta = x - self.mean\n            self.mean += delta \/ self.n\n            self.run_var += delta * (x - self.mean)\n        else:\n            # Adjusting variance\n            x_removed = self.windows.popleft()\n            old_m = self.mean\n            self.mean += (x - x_removed) \/ self.WIN_SIZE\n            self.run_var += (x + x_removed - old_m - self.mean) * (x - x_removed)\n\n    def get_mean(self):\n        return self.mean if self.n else np.zeros(n_size)\n\n    def get_var(self):\n        return self.run_var \/ (self.n) if self.n > 1 else np.zeros(n_size)\n\n    def get_std(self):\n        return math.sqrt(self.get_var())\n\n    def get_all(self):\n        return list(self.windows)\n\n    def __str__(self):\n        return \"Current window values: {}\".format(list(self.windows))\n\n\"\"\"\nIt isn't really slower than the mean approach. So we might get the variance for almost free.\n\"\"\"\na = RunningStats(WIN_SIZE=10000)\n\nfor index, row in tqdm(train_data[:100000].iterrows()): \n    a.push(np.array(row))\n    \na.get_mean()\n\"\"\"\nI implement the modifications suggested in comments + add some way to handle missing values. As above this is not problematic for the mean. I think it might get a bit more problematic for the variance, as replacing with last values will systematically lower the variance.\n\nNote : \n- I haven't tested the variance toroughfully yet\n- The post refers to a blog wich refer to another post that gives a solution for [skew and kurtosis in C++](https:\/\/www.johndcook.com\/blog\/skewness_kurtosis\/), I'll see what I can implement myself in Python.\n\n\"\"\"\n\"\"\"\nFor reference I'll leave the pandas implementation :\n\"\"\"\n#rw = 10000\n#train_data_rolled_mean = train_data.rolling(window=rw).mean()\n#train_data_rolled_var = train_data.rolling(window=rw).var()\n#train_data_rolled_skew = train_data.rolling(window=rw).skew()\n#train_data_rolled_kurt = train_data.rolling(window=rw).kurt()\n\"\"\"\n<a id='EWMA'><\/a>\n# Exponentially Weighted Moving Average\n\nPython reference implementation :\n\"\"\"\n#train_data_ewm = train_data.ewm(span=rw, adjust=True).mean()\n\"\"\"\nGiven that exponentially weighted moving average can be calculated iteratively without any memory, I feel like it would generally be better to use such Features. I use the formula alpha = 2 \/ (N+1) that give the same 'center of mass' as the traditional mean. My implementation :\n\"\"\"\nclass RunningEWMean:\n    def __init__(self, WIN_SIZE=20, n_size = 1, lt_mean = None):\n        if lt_mean is not None:\n            self.s = lt_mean\n        else:\n            self.s = np.zeros(n_size)\n        self.past_value = np.zeros(n_size)\n        self.alpha = 2 \/(WIN_SIZE + 1)\n\n    def clear(self):\n        self.s = 0\n\n    def push(self, x):\n        \n        x = fillna_npwhere_njit(x, self.past_value)\n        self.past_value = x\n        self.s = self.alpha * x + (1 - self.alpha) * self.s\n        \n    def get_mean(self):\n        return self.s\n\"\"\"\nSomehow it seems to also work better than the standard average :\n\"\"\"\na = RunningEWMean(WIN_SIZE=10)\n\nfor index, row in pd.DataFrame({'col1':range(1,100)}).iterrows(): \n    a.push(np.array(row))\n    \nprint(a.get_mean())\nprint(pd.DataFrame({'col1':range(1,100)}).ewm(span=10, adjust=True).mean().iloc[98])\n\"\"\"\nAnd it is also a bit faster (11000 it\/second):\n\"\"\"\na = RunningEWMean(WIN_SIZE=10000)\n\nfor index, row in tqdm(train_data[:100000].iterrows()): \n    a.push(np.array(row))\n    \na.get_mean()\n\"\"\"\n<a id='PDA'><\/a>\n# Past day average\n\nGiven that some long term moving average appears to have some gain, I figured it would probably make sense to calculate past day average.\nI haven't given a lot of attention with a pythonic way but I think I can give it a shot in a streaming way :\n\"\"\"\nclass RunningPDA:\n    def __init__(self):\n        self.day = -1\n        self.past_mean = 0\n        self.cum_sum = 0\n        self.day_instances = 0\n        self.past_value = 0\n\n    def clear(self):\n        self.n = 0\n        self.windows.clear()\n\n    def push(self, x, date):\n        \n        x = fillna_npwhere_njit(x, self.past_value)\n        self.past_value = x\n        \n        # change of day\n        if date>self.day:\n            self.day = date\n            if self.day_instances > 0:\n                self.past_mean = self.cum_sum\/self.day_instances\n            else:\n                self.past_mean = 0\n            self.day_instances = 1\n            self.cum_sum = x\n            \n        else:\n            self.day_instances += 1\n            self.cum_sum += x\n\n    def get_mean(self):\n        return self.cum_sum\/self.day_instances\n\n    def get_past_mean(self):\n        return self.past_mean\n\"\"\"\nA test seems to run pretty fast (10000 it\/s)\n\"\"\"\na = RunningPDA()\n\nfor index, row in tqdm(train_data[:100000].iterrows()): \n    date=row['date']\n    a.push(np.array(row),date)\na.get_past_mean()\n\"\"\"\nWhich seems to match (weight 2.7143664 match the first value on the first row) :\n\"\"\"\ntrain_data[:200000].groupby('date').mean().iloc[30,]\n\"\"\"\nGreat news !\n\"\"\"\n\"\"\"\n<a id='PTI'><\/a>\n# Previous trade information from the same underlying\n\nAs mentionned [here](https:\/\/www.kaggle.com\/c\/jane-street-market-prediction\/discussion\/207709) feature_41 being constant over the day allow to find the previous instance with the same feature_41 caracteristic. As we don't exactly know what are in those feature we can't really know how the trade opportunities relate exactly but I speculate that they relate to the same underlying or are pretty close and that information about the previous trade of the day relating to the same underlying might be usefull. At the moment the implementation rely on a simple dictionnary. I suspect I can't really get below keeping 800-900 instances in memory for that feature engineering technique as I need at least one example of each trade. It is not a problem and the method is really fast (10000 it\/s).\n\"\"\"\nclass RunningPTI:\n    def __init__(self,base_value=0):\n        self.dictionnary = {}\n        self.base_value = base_value\n        self.day = -1\n\n    def clear(self):\n        self.dictionnary = {}\n        self.base_value = 0\n\n    def push(self, x, value, date):\n        \n                # change of day\n        if date>self.day:\n            self.day = date\n            self.dictionnary = {}\n        \n        self.past_value = self.dictionnary.get(value)\n        self.dictionnary.update({value:x})\n        \n    def get_past_value(self):\n        if self.past_value is None:\n            self.past_value = self.base_value\n        return self.past_value\n    \n    def get_dict(self):\n        return self.dictionnary\na = RunningPTI(base_value=np.nan * np.empty((1, 138)))\n\nfor index, row in tqdm(train_data[:10000].iterrows()): \n    f_41 = row['feature_41']\n    date = row['date']\n    a.push(np.array(row),f_41,date)\n    \na.get_past_value()\n\"\"\"\nNote : I haven't toroughfully tested it yet.\n\"\"\"\n\"\"\"\n<a id='DIFF'><\/a>\n# Differentiation\n\nDirect and second order differentation of averaged variables seems to have some importance, as is, change in overall trends have an importance for the problem of dealing with multiple securities. To be more clear :\n\"\"\"\n#rw = 10000\n#train_data_diff = train_data.rolling(window=rw).mean().diff(rw)\n#train_data_diff_diff = train_data.rolling(window=rw).mean().diff(rw).diff(rw)\n\"\"\"\nSeems to retain some importance when an xgboost is calibrated on them, especially for higher rw. I haven't built a running algo for them yet, but I'll probably try.\n\"\"\"\n\"\"\"\n<a id='FDIFF'><\/a>\n# Fractional differentiation\n\nVery important feature engineering tool, especially for time series *. As illustrated by Marcos Lopez de Prado in his book Advances in Financial Machine Learning, It is a great tool to remove noise without removing information. \n\nThe idea is to generalise differentiation to non integer. Applying multiple stationnarity tests while slowly increasing the fractionnal differentiation level, you can get an 'optimal' level (enough differentiation to remove noise, without removing information). \n\nHowever, I havea found that for optimal level of around -0.75 - that I found in the dataset ** - we would need longer series to make the calculation meaningful. This is illustrated in the example below : the weight for the millionth instance is still above 0.02 for the first one. This is also problematic as it means that the first instances would lack a lot of information.\n\n\\* : it is rather difficult to even use time series tools here as we have many underlying securities\n\n**  : when the adf test would even converge after lenghty calculations\n\"\"\"\ndef get_weights(d, size):\n    w = [1.]\n    for k in range(1, size):\n        w_ = -w[-1] \/ k * (d - k + 1)\n        w.append(w_)\n    w = np.array(w[::-1]).reshape(-1, 1)\n    return w\nplt.plot(get_weights(-0.75,1000000))\nplt.ylim(0,0.1)\n\"\"\"\nSo, unless someone points out a way to make fractionnal differentiation work in our data set (or that an approximation allows for some information gain), I don't really plan to make a streaming algorithm for building it.\n\"\"\"\n\"\"\"\n<a id='Entropy'><\/a>\n# Entropy rate\n\nAlso mentionned in lopez de prado's book. It relate to some physical mesure of order. I am still not entirely convinced this could work here. Especially because there is a lot of different notions of entropy and all of them are rather calculatory. For reference (outside of inference) I was able to calculate entropy on sliding windows with the pyinform package (see code below). But this is rather slow and doesn't seems to provide any information gain in my early tests.\n\nHowever I have found [a streaming implementation](https:\/\/github.com\/ajcr\/rolling) that could be reimplemented for our problem so I am mentionning it.\n\"\"\"\n#!pip install pyinform\n#from pyinform import entropy_rate\n\n#entropy_r = lambda x: entropy_rate(x,k=2)\n\n#df[feature] = (df[feature] > df[feature].mean())\n#df[feature] = df[feature].rolling(window=rw[i]).apply(entropy_r)\ndel train_data\n\"\"\"\n<a id='MLP'><\/a>\n# Application\n\"\"\"\n\"\"\"\nIn this section I give you an idea of one would apply the algo for submission.\nThe model used come from this [notebook](https:\/\/www.kaggle.com\/aimind\/bottleneck-encoder-mlp-keras-tuner-8601c5). I only show where feature engineering appears.\n\"\"\"\n\"\"\"\nLoading the packages :\n\"\"\"\nfrom tensorflow.keras.layers import Input, Dense, BatchNormalization, Dropout, Concatenate, Lambda, GaussianNoise, Activation\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.losses import BinaryCrossentropy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers.experimental.preprocessing import Normalization\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import GroupKFold\n\nfrom tqdm import tqdm\nfrom random import choices\n\n\nimport kerastuner as kt\n\nphysical_devices = tf.config.list_physical_devices('GPU')\ntry:\n          tf.config.experimental.set_memory_growth(physical_devices[0], True)\nexcept:\n          # Invalid device or cannot modify virtual devices once initialized.\n    pass\n\"\"\"\nPurgedTimeSeries CV\n\"\"\"\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection._split import _BaseKFold, indexable, _num_samples\nfrom sklearn.utils.validation import _deprecate_positional_args\n\n# modified code for group gaps; source\n# https:\/\/github.com\/getgaurav2\/scikit-learn\/blob\/d4a3af5cc9da3a76f0266932644b884c99724c57\/sklearn\/model_selection\/_split.py#L2243\nclass PurgedGroupTimeSeriesSplit(_BaseKFold):\n    \"\"\"Time Series cross-validator variant with non-overlapping groups.\n    Allows for a gap in groups to avoid potentially leaking info from\n    train into test if the model has windowed or lag features.\n    Provides train\/test indices to split time series data samples\n    that are observed at fixed time intervals according to a\n    third-party provided group.\n    In each split, test indices must be higher than before, and thus shuffling\n    in cross validator is inappropriate.\n    This cross-validation object is a variation of :class:`KFold`.\n    In the kth split, it returns first k folds as train set and the\n    (k+1)th fold as test set.\n    The same group will not appear in two different folds (the number of\n    distinct groups has to be at least equal to the number of folds).\n    Note that unlike standard cross-validation methods, successive\n    training sets are supersets of those that come before them.\n    Read more in the :ref:`User Guide <cross_validation>`.\n    Parameters\n    ----------\n    n_splits : int, default=5\n        Number of splits. Must be at least 2.\n    max_train_group_size : int, default=Inf\n        Maximum group size for a single training set.\n    group_gap : int, default=None\n        Gap between train and test\n    max_test_group_size : int, default=Inf\n        We discard this number of groups from the end of each train split\n    \"\"\"\n\n    @_deprecate_positional_args\n    def __init__(self,\n                 n_splits=5,\n                 *,\n                 max_train_group_size=np.inf,\n                 max_test_group_size=np.inf,\n                 group_gap=None,\n                 verbose=False\n                 ):\n        super().__init__(n_splits, shuffle=False, random_state=None)\n        self.max_train_group_size = max_train_group_size\n        self.group_gap = group_gap\n        self.max_test_group_size = max_test_group_size\n        self.verbose = verbose\n\n    def split(self, X, y=None, groups=None):\n        \"\"\"Generate indices to split data into training and test set.\n        Parameters\n        ----------\n        X : array-like of shape (n_samples, n_features)\n            Training data, where n_samples is the number of samples\n            and n_features is the number of features.\n        y : array-like of shape (n_samples,)\n            Always ignored, exists for compatibility.\n        groups : array-like of shape (n_samples,)\n            Group labels for the samples used while splitting the dataset into\n            train\/test set.\n        Yields\n        ------\n        train : ndarray\n            The training set indices for that split.\n        test : ndarray\n            The testing set indices for that split.\n        \"\"\"\n        if groups is None:\n            raise ValueError(\n                \"The 'groups' parameter should not be None\")\n        X, y, groups = indexable(X, y, groups)\n        n_samples = _num_samples(X)\n        n_splits = self.n_splits\n        group_gap = self.group_gap\n        max_test_group_size = self.max_test_group_size\n        max_train_group_size = self.max_train_group_size\n        n_folds = n_splits + 1\n        group_dict = {}\n        u, ind = np.unique(groups, return_index=True)\n        unique_groups = u[np.argsort(ind)]\n        n_samples = _num_samples(X)\n        n_groups = _num_samples(unique_groups)\n        for idx in np.arange(n_samples):\n            if (groups[idx] in group_dict):\n                group_dict[groups[idx]].append(idx)\n            else:\n                group_dict[groups[idx]] = [idx]\n        if n_folds > n_groups:\n            raise ValueError(\n                (\"Cannot have number of folds={0} greater than\"\n                 \" the number of groups={1}\").format(n_folds,\n                                                     n_groups))\n\n        group_test_size = min(n_groups \/\/ n_folds, max_test_group_size)\n        group_test_starts = range(n_groups - n_splits * group_test_size,\n                                  n_groups, group_test_size)\n        for group_test_start in group_test_starts:\n            train_array = []\n            test_array = []\n\n            group_st = max(0, group_test_start - group_gap - max_train_group_size)\n            for train_group_idx in unique_groups[group_st:(group_test_start - group_gap)]:\n                train_array_tmp = group_dict[train_group_idx]\n                \n                train_array = np.sort(np.unique(\n                                      np.concatenate((train_array,\n                                                      train_array_tmp)),\n                                      axis=None), axis=None)\n\n            train_end = train_array.size\n \n            for test_group_idx in unique_groups[group_test_start:\n                                                group_test_start +\n                                                group_test_size]:\n                test_array_tmp = group_dict[test_group_idx]\n                test_array = np.sort(np.unique(\n                                              np.concatenate((test_array,\n                                                              test_array_tmp)),\n                                     axis=None), axis=None)\n\n            test_array  = test_array[group_gap:]\n            \n            \n            if self.verbose > 0:\n                    pass\n                    \n            yield [int(i) for i in train_array], [int(i) for i in test_array]\nclass CVTuner(kt.engine.tuner.Tuner):\n    def run_trial(self, trial, X, y, splits, batch_size=32, epochs=1,callbacks=None):\n        val_losses = []\n        for train_indices, test_indices in splits:\n            X_train, X_test = [x[train_indices] for x in X], [x[test_indices] for x in X]\n            y_train, y_test = [a[train_indices] for a in y], [a[test_indices] for a in y]\n            if len(X_train) < 2:\n                X_train = X_train[0]\n                X_test = X_test[0]\n            if len(y_train) < 2:\n                y_train = y_train[0]\n                y_test = y_test[0]\n            \n            model = self.hypermodel.build(trial.hyperparameters)\n            hist = model.fit(X_train,y_train,\n                      validation_data=(X_test,y_test),\n                      epochs=epochs,\n                        batch_size=batch_size,\n                      callbacks=callbacks)\n            \n            val_losses.append([hist.history[k][-1] for k in hist.history])\n        val_losses = np.asarray(val_losses)\n        self.oracle.update_trial(trial.trial_id, {k:np.mean(val_losses[:,i]) for i,k in enumerate(hist.history.keys())})\n        self.save_model(trial.trial_id, model)\n# From https:\/\/medium.com\/@micwurm\/using-tensorflow-lite-to-speed-up-predictions-a3954886eb98\n\nclass LiteModel:\n    \n    @classmethod\n    def from_file(cls, model_path):\n        return LiteModel(tf.lite.Interpreter(model_path=model_path))\n    \n    @classmethod\n    def from_keras_model(cls, kmodel):\n        converter = tf.lite.TFLiteConverter.from_keras_model(kmodel)\n        tflite_model = converter.convert()\n        return LiteModel(tf.lite.Interpreter(model_content=tflite_model))\n    \n    def __init__(self, interpreter):\n        self.interpreter = interpreter\n        self.interpreter.allocate_tensors()\n        input_det = self.interpreter.get_input_details()[0]\n        output_det = self.interpreter.get_output_details()[0]\n        self.input_index = input_det[\"index\"]\n        self.output_index = output_det[\"index\"]\n        self.input_shape = input_det[\"shape\"]\n        self.output_shape = output_det[\"shape\"]\n        self.input_dtype = input_det[\"dtype\"]\n        self.output_dtype = output_det[\"dtype\"]\n        \n    def predict(self, inp):\n        inp = inp.astype(self.input_dtype)\n        count = inp.shape[0]\n        out = np.zeros((count, self.output_shape[1]), dtype=self.output_dtype)\n        for i in range(count):\n            self.interpreter.set_tensor(self.input_index, inp[i:i+1])\n            self.interpreter.invoke()\n            out[i] = self.interpreter.get_tensor(self.output_index)[0]\n        return out\n    \n    def predict_single(self, inp):\n        \"\"\" Like predict(), but only for a single record. The input data can be a Python list. \"\"\"\n        inp = np.array([inp], dtype=self.input_dtype)\n        self.interpreter.set_tensor(self.input_index, inp)\n        self.interpreter.invoke()\n        out = self.interpreter.get_tensor(self.output_index)\n        return out[0]\n\"\"\"\nLoading the data :\n\"\"\"\nTRAINING = False\nUSE_FINETUNE = True     \nFOLDS = 5\nSEED = 42\n\ntrain = pd.read_csv('..\/input\/jane-street-market-prediction\/train.csv')\nnb_trade = train.groupby('date')['date'].count()\nhigh_volume_days = [i for i, x in enumerate(np.array(nb_trade > 7000)) if x]\n\"\"\"\nI change the days a bit to remove the day previous day 85 as the continuity of JS strategy is in question (or is that a different market regime ?)\n\"\"\"\ntrain = train.query('date > 85').reset_index(drop = True) \ntrain = train.query('date not in @high_volume_days').reset_index(drop = True) \ntrain = train.astype({c: np.float32 for c in train.select_dtypes(include='float64').columns}) #limit memory use\ntrain.fillna(train.mean(),inplace=True)\ntrain = train.query('weight > 0').reset_index(drop = True)\n#train['action'] = (train['resp'] > 0).astype('int')\ntrain['action'] =  (  (train['resp_1'] > 0.00001 ) & (train['resp_2'] > 0.00001 ) & (train['resp_3'] > 0.00001 ) & (train['resp_4'] > 0.00001 ) &  (train['resp'] > 0.00001 )   ).astype('int')\n\"\"\"\nAdding some feature (long term exponentially weighted mean of feature_0 and feature_1) :\n\"\"\"\nEWM_5000 = RunningEWMean(WIN_SIZE = 5000)\nEWM_10000 = RunningEWMean(WIN_SIZE = 10000)\nEWM_20000 = RunningEWMean(WIN_SIZE = 20000)\n\ntrain_FE = []\n\nfor index, row in tqdm(train[['feature_0','feature_1']].iterrows()): \n    EWM_5000.push(np.float64(np.array(row)))\n    EWM_10000.push(np.float64(np.array(row)))\n    EWM_20000.push(np.float64(np.array(row)))\n\n    FE = {\n        'feature_0_EWM_5000' : EWM_5000.get_mean()[0],\n        'feature_1_EWM_5000' : EWM_5000.get_mean()[1],\n        'feature_0_EWM_10000' : EWM_10000.get_mean()[0],\n        'feature_1_EWM_10000' : EWM_10000.get_mean()[1],\n        'feature_0_EWM_20000' : EWM_20000.get_mean()[0],\n        'feature_1_EWM_20000' : EWM_20000.get_mean()[1],\n    }\n\n    train_FE.append(FE)\n\ntrain_FE = pd.DataFrame(train_FE)\n\"\"\"\nmerge two dataframes and add columns\n\"\"\"\ntrain = pd.concat([train,train_FE],axis=1)\n\nfeatures = [c for c in train.columns if 'feature' in c]\n\nresp_cols = ['resp_1', 'resp_2', 'resp_3', 'resp', 'resp_4']\n\nX = train[features].values\ny = np.stack([(train[c] > 0.000001).astype('int') for c in resp_cols]).T #Multitarget\n\nf_mean = np.mean(train[features[1:]].values,axis=0)\n\"\"\"\n**Create autoencoder, MLP :**\n\"\"\"\ndef create_autoencoder(input_dim,output_dim,noise=0.05):\n    i = Input(input_dim)\n    encoded = BatchNormalization()(i)\n    encoded = GaussianNoise(noise)(encoded)\n    encoded = Dense(640,activation='relu')(encoded)\n    decoded = Dropout(0.2)(encoded)\n    decoded = Dense(input_dim,name='decoded')(decoded)\n    x = Dense(320,activation='relu')(decoded)\n    x = BatchNormalization()(x)\n    x = Dropout(0.2)(x)\n    x = Dense(output_dim,activation='sigmoid',name='label_output')(x)\n    \n    encoder = Model(inputs=i,outputs=encoded)\n    autoencoder = Model(inputs=i,outputs=[decoded,x])\n    \n    autoencoder.compile(optimizer=Adam(0.001),loss={'decoded':'mse','label_output':'binary_crossentropy'})\n    return autoencoder, encoder\ndef create_model(hp,input_dim,output_dim,encoder):\n    inputs = Input(input_dim)\n    \n    x = encoder(inputs)\n    x = Concatenate()([x,inputs]) #use both raw and encoded features\n    x = BatchNormalization()(x)\n    x = Dropout(hp.Float('init_dropout',0.0,0.5))(x)\n    \n    for i in range(hp.Int('num_layers',1,5)):\n        x = Dense(hp.Int('num_units_{i}',128,256))(x)\n        x = BatchNormalization()(x)\n        x = Lambda(tf.keras.activations.swish)(x)\n        x = Dropout(hp.Float(f'dropout_{i}',0.0,0.5))(x)\n    x = Dense(output_dim,activation='sigmoid')(x)\n    model = Model(inputs=inputs,outputs=x)\n    model.compile(optimizer=Adam(hp.Float('lr',0.00001,0.1,default=0.001)),loss=BinaryCrossentropy(label_smoothing=hp.Float('label_smoothing',0.0,0.1)),metrics=[tf.keras.metrics.AUC(name = 'auc')])\n    return model\nautoencoder, encoder = create_autoencoder(X.shape[-1],y.shape[-1],noise=0.1)\nif TRAINING:\n    autoencoder.fit(X,(X,y),\n                    epochs=1002,\n                    batch_size=16384, \n                    validation_split=0.1,\n                    callbacks=[EarlyStopping('val_loss',patience=10,restore_best_weights=True)])\n    encoder.save_weights('.\/encoder.hdf5')\nelse:\n    encoder.load_weights('..\/input\/running-algos-fe-for-fast-inference\/encoder.hdf5')\nencoder.trainable = False\n\"\"\"\nTraining the model :\n\"\"\"\nmodel_fn = lambda hp: create_model(hp,X.shape[-1],y.shape[-1],encoder)\n\ntuner = CVTuner(\n        hypermodel=model_fn,\n        oracle=kt.oracles.BayesianOptimization(\n        objective= kt.Objective('val_auc', direction='max'),\n        num_initial_points=4,\n        max_trials=60))\n\nFOLDS = 5\nSEED = 42\ntf.random.set_seed(SEED)\n\nif TRAINING:\n    gkf = PurgedGroupTimeSeriesSplit(n_splits = FOLDS, group_gap=20)\n    splits = list(gkf.split(y, groups=train['date'].values))\n    tuner.search((X,),(y,),splits=splits,batch_size=16384,epochs=300,callbacks=[EarlyStopping('val_auc', mode='max',patience=3)])\n    hp  = tuner.get_best_hyperparameters(1)[0]\n    pd.to_pickle(hp,f'.\/best_hp_{SEED}.pkl')\n    for fold, (train_indices, test_indices) in enumerate(splits):\n        model = model_fn(hp)\n        X_train, X_test = X[train_indices], X[test_indices]\n        y_train, y_test = y[train_indices], y[test_indices]\n        model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=300,batch_size=16384,callbacks=[EarlyStopping('val_auc',mode='max',patience=10,restore_best_weights=True)])\n        model.save_weights(f'.\/model_{SEED}_{fold}.hdf5')\n        model.compile(Adam(hp.get('lr')\/100),loss='binary_crossentropy')\n        model.fit(X_test,y_test,epochs=6,batch_size=16384)\n        model.save_weights(f'.\/model_{SEED}_{fold}_finetune.hdf5')\n    tuner.results_summary()\nelse:\n    models = []\n    hp = pd.read_pickle(f'..\/input\/running-algos-fe-for-fast-inference\/best_hp_{SEED}.pkl')\n    for f in range(FOLDS):\n        model = model_fn(hp)\n        if USE_FINETUNE:\n            model.load_weights(f'..\/input\/running-algos-fe-for-fast-inference\/model_{SEED}_{f}_finetune.hdf5')\n        else:\n            model.load_weights(f'..\/input\/running-algos-fe-for-fast-inference\/model_{SEED}_{f}.hdf5')\n        model = LiteModel.from_keras_model(model)\n        models.append(model)\n\"\"\"\n<a id='Dummy_Env'><\/a>\n## Dummy environnement\n\"\"\"\nENV_REAL = True\n\nif (not TRAINING) & (not ENV_REAL):\n    \n    test_col = pd.read_pickle(f'..\/input\/dummy-environnement\/columns_df_test.pickle')\n\n    n_row = 15219\n\n    dummy_df = train.iloc[:n_row]\n\n    for (index, row) in tqdm(dummy_df.iterrows()):\n\n        time.sleep(0.009)\n        test_df = pd.DataFrame(row).transpose()[test_col]\n\n        test_df = pd.DataFrame(row).transpose()\n        pred_df = pd.DataFrame(columns=['action'], index = [index])\n\n        pred_df.action = 0\n\"\"\"\n<a id='Submission'><\/a>\n## Submission\n\"\"\"\nif (not TRAINING) & (ENV_REAL):\n    \n    import janestreet\n    env = janestreet.make_env()\n    th = 0.5\n    \n    EWM_5000 = RunningEWMean(WIN_SIZE = 5000,n_size = 2)\n    EWM_10000 = RunningEWMean(WIN_SIZE = 10000,n_size = 2)\n    EWM_20000 = RunningEWMean(WIN_SIZE = 20000,n_size = 2)\n\n    train_FE = []\n    \n    \n    for (test_df, pred_df) in tqdm(env.iter_test()):\n        \n        EWM_5000.push(np.float64(np.array(test_df[['feature_0','feature_1']])))\n        EWM_10000.push(np.float64(np.array(test_df[['feature_0','feature_1']])))\n        EWM_20000.push(np.float64(np.array(test_df[['feature_0','feature_1']])))\n\n        FE = []\n\n        FE = {\n            'feature_0_EWM_5000' : EWM_5000.get_mean()[0][0],\n            'feature_1_EWM_5000' : EWM_5000.get_mean()[0][1],\n            'feature_0_EWM_10000' : EWM_10000.get_mean()[0][0],\n            'feature_1_EWM_10000' : EWM_10000.get_mean()[0][1],\n            'feature_0_EWM_20000' : EWM_20000.get_mean()[0][0],\n            'feature_1_EWM_20000' : EWM_20000.get_mean()[0][1],\n        }\n\n        test_df_FE = pd.concat([test_df,pd.DataFrame(FE, index=[test_df.index[0]])],axis=1)\n\n        if test_df_FE['weight'].item() > 0:\n            x_tt = test_df_FE.loc[:, features].values\n            if np.isnan(x_tt[:, 1:].sum()):\n                x_tt[:, 1:] = np.nan_to_num(x_tt[:, 1:]) + np.isnan(x_tt[:, 1:]) * f_mean\n            pred = np.mean([model.predict(x_tt) for model in models],axis=0)\n            pred = np.mean(pred)\n            pred_df.action = np.where(pred >= th, 1, 0).astype(int)\n        else:\n            pred_df.action = 0\n            \n        env.predict(pred_df)","meta":"{'source': 'AI4Code', 'id': 'f58d1b6d3fd2cd'}"}
{"id":"54315","text":"# Import required libraries(\u5fc5\u8981\u30e9\u30a4\u30d6\u30e9\u30ea\u306e\u30a4\u30f3\u30dd\u30fc\u30c8)\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nimport pprint\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.metrics import silhouette_samples\nfrom matplotlib import cm\n# Read data(\u30c7\u30fc\u30bf\u306e\u8aad\u307f\u8fbc\u307f)\n!kaggle datasets download -d imakash3011\/customer-personality-analysis\ndf_customer = pd.read_csv('..\/input\/customer-personality-analysis\/marketing_campaign.csv', sep='\\t')\ndf_customer.head(15)\n\"\"\"\n# Data Preprocessing(\u30c7\u30fc\u30bf\u306e\u524d\u51e6\u7406)\n\"\"\"\n# Check the data(\u30c7\u30fc\u30bf\u6570\u306e\u78ba\u8a8d)\ndf_customer.shape\n\"\"\"\n\u30d5\u30a1\u30a4\u30eb\u3092\u8aad\u307f\u8fbc\u3080\u3068\u304d\u306bsep\u30e1\u30bd\u30c3\u30c9\u3092\u3057\u3066\u3057\u306a\u3044\u3068\u4e2d\u8eab\u304c\u5206\u5272\u3057\u306a\u304b\u3063\u305f\n \u2190\u5143\u306e\u30c7\u30fc\u30bf\u306e\u30b9\u30bf\u30a4\u30eb\u304c\u30c6\u30fc\u30d6\u30eb\u5f62\u5f0f\u3060\u3063\u305f\u306e\u304b??\n\n\n\"\"\"\n# Check the data type & missing value of each column(\u5404\u5217\u306e\u30c7\u30fc\u30bf\u30bf\u30a4\u30d7&\u6b20\u640d\u5024\u3092\u78ba\u8a8d)\ndf_customer.info()\n# Delete missing data rows(\u6b20\u640d\u30c7\u30fc\u30bf\u884c\u306e\u524a\u9664)\ndf_customer = df_customer.dropna().reset_index(drop = True)\ndf_customer.head(15)\n# Basic Statistics(\u57fa\u672c\u7d71\u8a08\u91cf)\ndf_customer.describe()\n# adding new columns(\u65b0\u3057\u3044\u30c7\u30fc\u30bf\u5217\u306e\u8ffd\u52a0)\ndf_customer['Age'] = 2021 - df_customer['Year_Birth']\ndf_customer['MntTotalProducts'] = df_customer['MntWines'] + df_customer['MntFruits'] + df_customer['MntMeatProducts'] + df_customer['MntFishProducts'] + df_customer['MntSweetProducts'] + df_customer['MntGoldProds']\n\n# Renaming columns(\u5217\u540d\u306e\u518d\u5b9a\u7fa9)\nnumeric_column_all = ['income', 'kidhome',\n                   'teenhome', 'recency', 'mntwines', 'mntfruits',\n                   'mntmeatproducts', 'mntfishproducts', 'mntsweetproducts',\n                   'mntgoldprods', 'numdealspurchases', 'numwebpurchases',\n                   'numcatalogpurchases', 'numstorepurchases', 'numwebvisitsmonth',\n                   'acceptedcmp3', 'acceptedcmp4', 'acceptedcmp5', 'acceptedcmp1',\n                   'acceptedcmp2', 'complain', 'z_costcontact', 'z_revenue', 'response']\n\nnumeric_columns = ['income', 'kidhome',\n                   'teenhome', 'recency', 'mntwines', 'mntfruits',\n                   'mntmeatproducts', 'mntfishproducts', 'mntsweetproducts',\n                   'mntgoldprods', 'numdealspurchases', 'numwebpurchases',\n                   'numcatalogpurchases', 'numstorepurchases', 'numwebvisitsmonth']\n\nbool_columns = ['acceptedcmp3', 'acceptedcmp4', 'acceptedcmp5', 'acceptedcmp1',\n                   'acceptedcmp2', 'complain', 'response']\ndf_customer = df_customer.rename(columns={'Response' : 'AcceptedCmp6'})\n\ncategorical_columns = ['education', 'marital_status']\n\ndate_columns = ['year_birth','dt_customer'] \n\n# Changing data types and dropping columns(\u30c7\u30fc\u30bf\u578b\u306e\u5909\u66f4&\u4e0d\u5fc5\u8981\u30c7\u30fc\u30bf\u5217\u306e\u524a\u9664)\ndf_customer['Dt_Customer'] = pd.to_datetime(df_customer['Dt_Customer'])\ndf_customer['Education'], df_customer['Marital_Status'] = df_customer['Education'].astype('category'), df_customer['Marital_Status'].astype('category')\n\ndf_customer.drop(['Z_CostContact', 'Z_Revenue'], axis=1, inplace=True)\n\n# Classifying DataFrame(\u7279\u5b9a\u7528\u9014\u306e\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u3092\u5b9a\u7fa9)\nvariable_all_df = df_customer.loc[ : , ['Age', 'Income', 'Kidhome',\n       'Teenhome', 'Recency', 'MntTotalProducts', 'MntWines', 'MntFruits',\n       'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts',\n       'MntGoldProds', 'NumDealsPurchases', 'NumWebPurchases',\n       'NumCatalogPurchases', 'NumStorePurchases', 'NumWebVisitsMonth']]\n\nvariable_df = df_customer.loc[ : , ['Year_Birth', 'Education', 'Marital_Status', 'Income', 'Kidhome',\n       'Teenhome', 'Dt_Customer', 'Recency']]\n\nmnt_df = df_customer.loc[ : , ['MntTotalProducts', 'MntWines', 'MntFruits',\n       'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts',\n       'MntGoldProds']]\nnum_purchases_df = df_customer.loc[ : , ['NumDealsPurchases', 'NumWebPurchases',\n       'NumCatalogPurchases', 'NumStorePurchases', 'NumWebVisitsMonth']]\n\ncampaign_df = df_customer.loc[ : , ['AcceptedCmp1', 'AcceptedCmp2', 'AcceptedCmp3', 'AcceptedCmp4', 'AcceptedCmp5', 'AcceptedCmp6']]\n\n\n\"\"\"\n### Confirm data distribution(\u30c7\u30fc\u30bf\u306e\u5206\u5e03\u78ba\u8a8d)\n\"\"\"\n# Function definition of box plot(\u7bb1\u30d2\u30b2\u56f3\u306e\u95a2\u6570\u5b9a\u7fa9)\ndef get_box(input_data):\n  output_data = input_data.copy()\n  fig = plt.figure(figsize=(20,100))\n  num_columns = output_data.columns\n  for i in range(len(num_columns)):\n    plt.subplot(len(num_columns), 4, i+1)\n    output_data[num_columns[i]].plot(kind = \"box\")\n  return output_data\n# illustrate the box plot of each row(\u5404\u5217\u306e\u7bb1\u30d2\u30b2\u56f3\u3092\u56f3\u793a)\ndf_var = get_box(variable_all_df)\n\"\"\"\nKidhome, Teenhome, Recency, NumStorePurchases\u306e4\u3064\u4ee5\u5916\u306e\u5217\u306b\u5916\u308c\u5024\u304c\u5b58\u5728\u3059\u308b\u4e8b\u304c\u78ba\u8a8d\u3067\u304d\u305f\n\"\"\"\n\"\"\"\n### Detect outliers using IQR(IQR\u3092\u7528\u3044\u3066\u5916\u308c\u5024\u3092\u691c\u51fa)\n\"\"\"\n# Define function of IQR(IQR\u95a2\u6570\u3092\u5b9a\u7fa9)\ndef Outlier_By_IQR(input_data):\n  output_data = input_data.copy()\n  numeric_columns_to_filter = ['Age', 'Income','MntTotalProducts', 'MntWines', 'MntFruits',\n       'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts',\n       'MntGoldProds', 'NumDealsPurchases', 'NumWebPurchases',\n       'NumCatalogPurchases', 'NumWebVisitsMonth']\n  for i in range(len(numeric_columns_to_filter)):\n    q1 = output_data[numeric_columns_to_filter[i]].quantile(0.25)\n    q3 = output_data[numeric_columns_to_filter[i]].quantile(0.75)\n    iqr = q3 - q1\n    bottom = q1 - 1.5*iqr\n    up = q3 + 1.5*iqr\n    print(numeric_columns_to_filter[i])\n    print(f'Q1\uff1a{q1}')\n    print(f'Q3\uff1a{q3}')\n    print(f'IQR\uff1a{iqr}')\n    print('Outlier is... \u5916\u308c\u5024\u306f\u2193')\n    print(output_data[numeric_columns_to_filter[i]][(output_data[numeric_columns_to_filter[i]] < bottom) | (output_data[numeric_columns_to_filter[i]] > up)])\n    print('********************************************************')\n  return output_data\n\n# Execute function of IQR(IQR\u95a2\u6570\u3092\u5b9f\u884c)\ndf_outlier = Outlier_By_IQR(variable_all_df)\n\"\"\"\n\u8cfc\u5165\u91d1\u984d\u3084\u8cfc\u5165\u7d4c\u8def\u306b\u95a2\u3057\u3066\u306f\u660e\u78ba\u306a\u5916\u308c\u5024\u306f\u5b58\u5728\u3057\u306a\u3044\u3002\n\u4e00\u65b9\u3067\u5e74\u9f62\u3084\u53ce\u5165\u306b\u95a2\u3057\u3066\u306f\u73fe\u5b9f\u7684\u3067\u306a\u3044\u5024\u3084\u660e\u3089\u304b\u306b\u6a19\u6e96\u504f\u5dee\u3092\u6b6a\u307e\u305b\u3066\u3044\u308b\u30c7\u30fc\u30bf\u304c\u3042\u308b\u305f\u3081\u3001\u5916\u308c\u5024\u3068\u3057\u3066\u6392\u9664\u3059\u308b\u3002\n\"\"\"\n# Deleting outliers(\u5916\u308c\u5024\u3092\u9664\u53bb)\nnumeric_columns_to_filter = ['Age', 'Income']\n\nQ1 = df_customer[numeric_columns_to_filter].quantile(0.25)\nQ3 = df_customer[numeric_columns_to_filter].quantile(0.75)\nIQR = Q3 - Q1\n\ndf_filtered = df_customer[~((df_customer[numeric_columns_to_filter] < (Q1 - 1.5 * IQR)) |(df_customer[numeric_columns_to_filter] > (Q3 + 1.5 * IQR))).any(axis=1)]\n\ndisplay(df_customer.shape)\ndisplay(df_filtered.shape)\n\"\"\"\n# EDA(Explanatory Data Analysis) \n\"\"\"\n# Scatter plot of purchaser characteristics <sorted by educational background>(\u8cfc\u5165\u8005\u306e\u7279\u5fb4\u306b\u95a2\u3059\u308b\u6563\u5e03\u56f3\uff1c\u5b66\u6b74\u5225\u306b\u30bd\u30fc\u30c8\uff1e)\nsns.pairplot(data=variable_df, hue='Education')\n# Scatter plot of buyer characteristics <sorted by marriage status>(\u8cfc\u5165\u8005\u306e\u7279\u5fb4\u306b\u95a2\u3059\u308b\u6563\u5e03\u56f3\uff1c\u7d50\u5a5a\u72b6\u6cc1\u5225\u306b\u30bd\u30fc\u30c8\uff1e\uff09\nsns.pairplot(data=variable_df, hue='Marital_Status')\n# Scatter plot of purchase amount by item(\u54c1\u76ee\u5225\u8cfc\u5165\u984d\u306e\u6563\u5e03\u56f3)\nsns.pairplot(data=mnt_df)\n# Scatter plot of purchase route(\u8cfc\u5165\u7d4c\u8def\u306e\u6563\u5e03\u56f3)\nsns.pairplot(data=num_purchases_df)\n# Defined by counting the number of elements in each age group(\u5404\u5e74\u9f62\u5c64\u306e\u8981\u7d20\u6570\u3092\u30ab\u30a6\u30f3\u30c8\u3057\u3066\u5b9a\u7fa9)\nage_teenager = len(df_customer[(df_customer['Age']>0)&(df_customer['Age']<20)])\nage_20s = len(df_customer[(df_customer['Age']>=20)&(df_customer['Age']<30)])\nage_30s = len(df_customer[(df_customer['Age']>=30)&(df_customer['Age']<40)])\nage_40s = len(df_customer[(df_customer['Age']>=40)&(df_customer['Age']<50)])\nage_50s = len(df_customer[(df_customer['Age']>=50)&(df_customer['Age']<60)])\nage_over60 = len(df_customer[(df_customer['Age']>=60)])\n\ndf_customer['Age Group'] = pd.Series()\n\nfor i in range(len(df_customer['Age'])):\n  if (df_customer.at[i, 'Age']<30):\n    df_customer.at[i, 'Age Group'] = 20\n  elif (df_customer.at[i, 'Age']<40):\n    df_customer.at[i, 'Age Group'] = 30\n  elif (df_customer.at[i, 'Age']<50):\n    df_customer.at[i, 'Age Group'] = 40\n  elif (df_customer.at[i, 'Age']<60):\n    df_customer.at[i, 'Age Group'] = 50\n  else:\n    df_customer.at[i, 'Age Group'] = 60\n\n# Save the count number as a dictionary by defining the column name(\u30ab\u30a6\u30f3\u30c8\u6570\u3092\u30b3\u30e9\u30e0\u540d\u3092\u5b9a\u7fa9\u3057\u3066\u8f9e\u66f8\u578b\u3067\u4fdd\u5b58)\nl1 = [\"teenager\", \"20s\", \"30s\", \"40s\", \"50s\", \"over60\"]\nl2 = [age_teenager, age_20s, age_30s, age_40s, age_50s, age_over60]\n\nage_df = pd.DataFrame({'age group' : l1, 'count' : l2})\n\nage_df\n# Illustration of age group with bar graph(\u5e74\u9f62\u5c64\u3092\u68d2\u30b0\u30e9\u30d5\u3067\u56f3\u793a)\n\nfig, ax = plt.subplots(figsize = (10, 4.8))\nplt.barh(age_df['age group'], age_df['count'], color = 'forestgreen')\nplt.title('Count of Customers by Age Group')\nplt.xlabel('Age Group')\nplt.ylabel('Count')\n# Cumulative by educational background(\u5b66\u6b74\u5225\u306b\u7d2f\u8a08)\neducation_columns = df_customer['Education'].unique()\ndataset_education = df_customer['Education'].tolist()\n\nedu_item_count = []\n\nfor edu_column in education_columns:\n  edu_count = dataset_education.count(edu_column)\n  print(f'{edu_column}\uff1a{edu_count}')\n\n  edu_item_count.append(edu_count)\n# A bar graph showing the cumulative total by educational background(\u5b66\u6b74\u5225\u7d2f\u8a08\u3092\u68d2\u30b0\u30e9\u30d5\u3067\u56f3\u793a)\ny = education_columns\nwidth = edu_item_count\n\nfig, ax = plt.subplots(figsize = (10, 4.8))\nplt.barh(y=y, width=width)\nplt.title('Count of Customers by Education')\nplt.xlabel('Count')\nplt.ylabel('Education')\n# Cumulative by marital status(\u7d50\u5a5a\u72b6\u6cc1\u5225\u306b\u7d2f\u8a08)\nmarital_columns = df_customer['Marital_Status'].unique()\ndf_customer_marital = df_customer['Marital_Status'].tolist()\n\nmar_item_count = []\n\nfor mar_col in marital_columns:\n  mar_count = df_customer_marital.count(mar_col)\n  print(f'{mar_col}\uff1a{mar_count}')\n\n  mar_item_count.append(mar_count)\n# A bar graph showing the cumulative total by marital status(\u7d50\u5a5a\u72b6\u6cc1\u5225\u7d2f\u8a08\u3092\u68d2\u30b0\u30e9\u30d5\u3067\u56f3\u793a)\ny = marital_columns\nwidth = mar_item_count\nfig, ax = plt.subplots(figsize = (10, 4.8))\nplt.barh(y=y, width=width, color='pink')\nplt.xlabel('Count')\nplt.ylabel('Marital Status')\n# Classification by income status(\u53ce\u5165\u72b6\u6cc1\u3067\u5206\u985e)\ndf_filtered['Income'].sort_values(ascending = False)\n\n# Illustrate the distribution map according to the income situation(\u53ce\u5165\u72b6\u6cc1\u3067\u30d2\u30b9\u30c8\u30b0\u30e9\u30e0\u3092\u56f3\u793a)\nfig, ax = plt.subplots(figsize = (8.0, 4.8))\nsns.distplot(df_filtered['Income'])\nplt.title('Income Distribution')\nplt.xlabel('Income($)')\nplt.ylabel('Count')\n# Illustration of purchase frequency in a bar graph\nrecency = df_customer['Recency'].value_counts()\nplt.bar(recency.index, recency.values)\n# A bar graph showing the distribution of responses to marketing campaigns(\u30de\u30fc\u30b1\u30c6\u30a3\u30f3\u30b0\u30ad\u30e3\u30f3\u30da\u30fc\u30f3\u3078\u306e\u53cd\u5fdc\u306e\u5206\u5e03\u3092\u68d2\u30b0\u30e9\u30d5\u3067\u56f3\u793a)\nfor i in range(1, 7):\n  campaign_df[f'AcceptedCmp{i}'] = campaign_df[f'AcceptedCmp{i}'].astype(str)\ncampaign_df['AcceptedCmp_all'] = campaign_df['AcceptedCmp1'] + campaign_df['AcceptedCmp2'] + campaign_df['AcceptedCmp3'] + campaign_df['AcceptedCmp4'] + campaign_df['AcceptedCmp5'] + campaign_df['AcceptedCmp6']\ncampaign_df['AcceptedCmp_all'].astype(int)\n\nx = campaign_df['AcceptedCmp_all'].unique()\nx = np.sort(x)\ny = campaign_df['AcceptedCmp_all'].value_counts()\ny = y.sort_index()\n\nfig, ax = plt.subplots(figsize=(10.0, 6.0))\nplt.bar(x=x, height=y)\nplt.title('Distribution of Response to each Campaign')\nplt.xlabel('each Campaign')\nplt.ylabel('Count')\nplt.xticks(rotation=90)\n\"\"\"\n# VS\n\"\"\"\n\"\"\"\n## Changes in EC subscribers(EC\u52a0\u5165\u8005\u306e\u63a8\u79fb)\n\"\"\"\n#  Temporarily change the index to Datetime(\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u4e00\u6642\u7684\u306b\u5909\u66f4)\ndf_customer.set_index('Dt_Customer', inplace=True)\n\ndate_enrollment = df_customer['ID'].resample('M').count()\n\nvalues_date_enrollment = date_enrollment.tolist()\nsigma_values_date_enrollment = []\nfor i in range(len((values_date_enrollment))):\n  sigma_values_date_enrollment.append(sum(values_date_enrollment[:i]))\nindex_date_enrollment = date_enrollment.index\n\nfig, ax = plt.subplots(figsize = (10.0, 4.8))\nplt.plot(index_date_enrollment, sigma_values_date_enrollment, marker = 'o')\nplt.title('Transition of Subscriber')\nplt.xlabel('Date')\nplt.ylabel ('Count of Enrollment')\nplt.show()\n\n# Redefine df_customer index(# df_customer\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u518d\u5b9a\u7fa9)\ndf_customer = df_customer.reset_index()\n\"\"\"\nNote that the Dt_Customer column comes before the ID column\nID\u5217\u306e\u524d\u306bDt_Customer\u5217\u304c\u6765\u3066\u3044\u308b\u3053\u3068\u306b\u6ce8\u610f\n\"\"\"\ndf_customer.head()\n\"\"\"\n## About the user's maximum purchase item(\u30e6\u30fc\u30b6\u30fc\u306e\u6700\u5927\u8cfc\u5165\u54c1\u76ee\u306b\u3064\u3044\u3066\uff09\n\"\"\"\n# Convert purchased product columns to numbers and determine maximum for each row(\u8cfc\u5165\u88fd\u54c1\u5217\u3092\u6570\u5b57\u306b\u5909\u63db\u3057\u3001\u5404\u884c\u306e\u6700\u5927\u3092\u5224\u5b9a)\n\ndf_customer['1st Best Product'] = pd.Series()\ndf_customer['2nd Best Product'] = pd.Series()\nbest_prod = df_customer.iloc[ : , 10:15]\nbest_prod = best_prod.rename(columns = {'MntWines' : 1, 'MntFruits' : 2, 'MntMeatProducts' : 3, 'MntFishProducts' : 4, 'MntSweetProducts' : 5, 'MntGoldProds' : 6})\n\nfor i in range(len(best_prod)):\n  d = dict(best_prod.iloc[i])\n\n  m = max(d, key=d.get)\n  df_customer['1st Best Product'].iloc[i] = int(m)\n\n  del d[m]\n  df_customer['2nd Best Product'].iloc[i] = int(max(d, key = d.get))\n\n  df_customer.head()\n# Scatter plot <total purchase vs income>(\u6563\u5e03\u56f3\uff1c\u8cfc\u5165\u7dcf\u984d\u3068\u53ce\u5165\uff1e)\nfig, ax = plt.subplots(figsize = (8.0, 4.8))\nplt.scatter(df_filtered['MntTotalProducts'], df_filtered['Income'])\nplt.title('MntTotalProducts vs Income')\nplt.ylabel('Income ($)')\nplt.xlabel('Mount of Total Products ($)')\n# Scatter plot <total purchase amount vs frequency of purchase>(\u6563\u5e03\u56f3\uff1c\u8cfc\u5165\u7dcf\u984d\u3068\u8cfc\u5165\u983b\u5ea6\uff1e)\nfig, ax = plt.subplots(figsize = (8.0, 4.8))\nplt.scatter(df_filtered['Recency'], df_filtered['MntTotalProducts'])\nplt.title('Recency vs MntTotalProducts')\nplt.xlabel('Last Days (days)')\nplt.ylabel('Mount of Total Products ($)')\n\"\"\"\n# Clustering analysis(\u30af\u30e9\u30b9\u30bf\u30ea\u30f3\u30b0\u5206\u6790\uff09\n\"\"\"\n# Check the correlation of the entire data(\u5168\u4f53\u30c7\u30fc\u30bf\u306e\u76f8\u95a2\u95a2\u4fc2\u3092\u78ba\u8a8d)\nplt.figure(figsize=(20,20))\nsns.heatmap(df_filtered.corr(), annot=True)\n\"\"\"\nMntTotalProducts\u5217\u306fMnt\u3007\u3007\u5217\u306e\u7dcf\u548c\u3067\u3042\u308a\u3053\u308c\u3089\u3068\u306e\u76f8\u95a2\u4fc2\u6570\u304c\u6975\u7aef\u306b\u9ad8\u3044\u4e8b\u304b\u3089\u30af\u30e9\u30b9\u30bf\u30ea\u30f3\u30b0\u306b\u7528\u3044\u308b\u30c7\u30fc\u30bf\u3068\u3057\u3066\u306f\u30ce\u30a4\u30ba\u3068\u5224\u65ad\u3057\u3001\u9664\u53bb\u3057\u3066\u304a\u304f\n\"\"\"\n# Store explanatory variables in a data frame(\u8aac\u660e\u5909\u6570\u3092\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u306b\u683c\u7d0d)\ndf_clustering = df_filtered.loc[ : , ['Age', 'Income', 'Kidhome', 'Teenhome', 'Recency',\n       'MntWines', 'MntFruits', 'MntMeatProducts', 'MntFishProducts',\n       'MntSweetProducts', 'MntGoldProds', 'NumDealsPurchases',\n       'NumWebPurchases', 'NumCatalogPurchases', 'NumStorePurchases',\n       'NumWebVisitsMonth']]\n\ndf_clustering.head()\n# Data standardization(\u30c7\u30fc\u30bf\u306e\u6a19\u6e96\u5316)\nscaler = StandardScaler()\nclustering_scalered = scaler.fit_transform(df_clustering)\n\"\"\"\n## Apply K-means method(K-\u5e73\u5747\u6cd5\u3092\u9069\u5fdc)\n\"\"\"\n# Difine K-means method(K-\u5e73\u5747\u6cd5\u3092\u5b9a\u7fa9)\nkmeans_kwargs = {\n    \"init\" : \"random\",\n    \"n_init\" : 10,\n    \"max_iter\" : 300,\n    \"random_state\" : 42\n}\n\nsse = []\nfor k in range(1, 11):\n  kmeans = KMeans(n_clusters=k, **kmeans_kwargs)\n  kmeans.fit(clustering_scalered)\n  sse.append(kmeans.inertia_)\n\n# Illustrated elbow method(\u30a8\u30eb\u30dc\u30fc\u6cd5\u3092\u56f3\u793a)\nplt.style.use(\"fivethirtyeight\")\nplt.plot(range(1, 11), sse, marker = \"o\")\nplt.xticks(range(1, 11))\nplt.xlabel('Number of Cluster')\nplt.ylabel('Distortion(SSE)')\nplt.title('Kmeans Number of Clustering')\nplt.show()\n\"\"\"\n\u4e0a\u8a18\u306e\u8868\uff08\u30a8\u30eb\u30dc\u30fc\u56f3\uff09\u304b\u3089\u30af\u30e9\u30b9\u591a\u6570\u306f2\u3082\u3057\u304f\u306f3\u7a0b\u5ea6\u304c\u59a5\u5f53\u3060\u3068\u8003\u3048\u3089\u308c\u308b\u3002\n\"\"\"\n# Run with 3 clusters(\u30af\u30e9\u30b9\u30bf\u30fc\u6570\u30923\u3067\u5b9f\u884c)\nkmeans = KMeans(3)\nkmeans.fit(df_clustering)\nidentified_clusters = kmeans.fit_predict(df_clustering)\n\n\ns = set(identified_clusters)\nl = list(s)\n\nprint(l)\nprint('*************************************************')\nidentified_clusters\n# Check the centroid coordinates for each cluster are stored(\u5404\u30af\u30e9\u30b9\u30bf\u30fc\u306e\u30bb\u30f3\u30c8\u30ed\u30a4\u30c9\u306e\u5ea7\u6a19\u304c\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u3053\u3068\u3092\u78ba\u8a8d)\nkmeans.cluster_centers_\n# Add a cluster to a data frame(\u30af\u30e9\u30b9\u30bf\u30fc\u3092\u30c7\u30fc\u30bf\u30d5\u30ec\u30fc\u30e0\u306b\u8ffd\u52a0)\ndf_clustering['Cluster'] = identified_clusters\ndf_clustering.head()\n\"\"\"\n## Validate the number of clusters by silhouette analysis(\u30b7\u30eb\u30a8\u30c3\u30c8\u5206\u6790\u3067\u30af\u30e9\u30b9\u30bf\u30fc\u6570\u306e\u59a5\u5f53\u6027\u3092\u78ba\u8a8d)\n\"\"\"\n# Performing silhouette analysis and illustration in bar chart(\u30b7\u30eb\u30a8\u30c3\u30c8\u5206\u6790\u306e\u5b9f\u884c\u3068\u6a2a\u68d2\u30b0\u30e9\u30d5\u3067\u306e\u56f3\u793a)\n\"\"\"\n* A scatter plot of each cluster is also illustrated when there is time\n* \u6642\u9593\u304c\u3042\u308b\u3068\u304d\u306b\u5404\u30af\u30e9\u30b9\u30bf\u306e\u6563\u5e03\u56f3\u3082\u56f3\u793a\u3059\u308b\n\"\"\"\n\nscore = silhouette_score(clustering_scalered, kmeans.labels_)\nprint(round(score, 4))\n\nsilhouette_values = silhouette_samples(df_clustering, identified_clusters, metric='euclidean')\ny_ax_lower, y_ax_upper = 0, 0\ny_ticks = []\nn_clusters = len(l)\n\n# Standardization of the number of clusters(\u30af\u30e9\u30b9\u30bf\u30fc\u6570\u306e\u6a19\u6e96\u5316)\nnp_l = np.array(l)\nnp_1 = np.array([1,1,1])\nl_std = np_l + np_1\n\nfor i, c in enumerate(l):\n  c_silhouette_vals = silhouette_values[identified_clusters == c]\n  c_silhouette_vals.sort()\n  y_ax_upper += len(c_silhouette_vals)\n  color = cm.jet(float(i) \/ n_clusters)\n  plt.barh(range(y_ax_lower, y_ax_upper),\n           c_silhouette_vals,\n           height = 1.0,\n           edgecolor = 'none',\n           color = color)\n  y_ticks.append((y_ax_lower + y_ax_upper) \/ 2)\n  y_ax_lower += len(c_silhouette_vals)\n\nsilhouette_avg = np.mean(silhouette_values)\nplt.axvline(silhouette_avg, color = 'red', linestyle = '--')\nplt.yticks(y_ticks, l_std)\nplt.ylabel('Cluster')\nplt.xlabel('silhouette coefficient')\nplt.show()\n# \u5404\u30af\u30e9\u30b9\u30bf\u30fc\u306e\u5b9a\u7fa9\u3068\u7279\u5fb4\u5206\u6790\ncluster_0 = df_clustering[df_clustering['Cluster'] == 0]\ncluster_1 = df_clustering[df_clustering['Cluster'] == 1]\ncluster_2 = df_clustering[df_clustering['Cluster'] == 2]\n# \u30af\u30e9\u30b9\u30bf\u30fc0\u306e\u7279\u5fb4\ncluster_0_desc = cluster_0.describe().transpose()\ncluster_0_desc\n# \u30af\u30e9\u30b9\u30bf\u30fc1\u306e\u7279\u5fb4\ncluster_1_desc = cluster_1.describe().transpose()\ncluster_1_desc\n# \u30af\u30e9\u30b9\u30bf\u30fc2\u306e\u7279\u5fb4\ncluster_2_desc = cluster_2.describe().transpose()\ncluster_2_desc\ncluster_index = cluster_0.index\n\ncluster_cmp = pd.DataFrame()\ncluster_cmp = cluster_cmp.append(cluster_0_desc['mean'])\ncluster_cmp = cluster_cmp.rename(index={'mean' : 'cluster_0'})\ncluster_cmp = cluster_cmp.append(cluster_1_desc['mean'])\ncluster_cmp = cluster_cmp.rename(index={'mean' : 'cluster_1'})\ncluster_cmp = cluster_cmp.append(cluster_2_desc['mean'])\ncluster_cmp = cluster_cmp.rename(index={'mean' : 'cluster_2'})\ncluster_cmp.T","meta":"{'source': 'AI4Code', 'id': '63fcdf914344c4'}"}
{"id":"88129","text":"\"\"\"\n# Toxic Comments Classification\n\"\"\"\n\"\"\"\nIn this program, we are going to classify a comment in 6 different labels such as *toxic, severe_toxic, obsene*, etc.\n\"\"\"\n\"\"\"\n## Importing libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, GlobalAvgPool1D, Dropout, Embedding,Bidirectional, Flatten, CuDNNLSTM, Conv1D, MaxPooling1D\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom tqdm import tqdm\nimport random\nimport matplotlib.pyplot as plt\n\"\"\"\n## Getting the dataset\n\"\"\"\ntraining_set = pd.read_csv(\"..\/input\/jigsaw-toxic-comment-classification-challenge\/train.csv\")\ntraining_set = training_set.drop(['id'], axis=1)\n\"\"\"\n## Analyzing the dataset\n\"\"\"\nprint(\"Number of training records :\",len(training_set))\nprint(\"Columns :\")\nfor i in training_set:\n    print(\"\\t\"+i)\n\"\"\"\nThe training set consists of 159571 records and 8 columns. The columns are very much self explanatory.<br>\n<br>\n>The **id** contains the id of our training records and is quite irrelevant for the training purpose, so we will eventually end up dropping this column.<br>\n>Then we have **comment_text**, which consists of the text of comment text.<br>\n>Rest other columns have values 0\/1 based on whether the comment text qualifies for that label.\n<br>\n\n\"\"\"\n\"\"\"\n**Now, let's take a look at how many examples of training data do we have satifying our labels.**\n\"\"\"\n#plot 2\ncolumns = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']  \ncount_ones = []\nfor i in columns:\n    count_ones.append(training_set[training_set[i]==1][i].count())\ny_pos = np.arange(len(columns))\nplt.bar(y_pos, count_ones, align=\"center\", alpha=0.5)\nplt.xticks(y_pos, columns)\nplt.ylabel(\"Number of Ones\")\nplt.title(\"Number of Ones\")\nplt.show()\n\n#plot 1\ncount_zeros = []\nfor i in columns:\n    count_zeros.append(training_set[training_set[i]==0][i].count())\ny_pos = np.arange(len(columns))\nplt.bar(y_pos, count_zeros, align=\"center\", alpha=0.5)\nplt.xticks(y_pos, columns)\nplt.ylabel(\"Number of Zeros\")\nplt.title(\"Number of Zeros\")\nplt.show()\n\"\"\"\nFrom the above plots, we can see that our training set has more records which are negative(or have '0' value). We have around 15000 records which have are positively classified as toxic and around 140000 which are classified as negative. The worst case is with the threat class, here we have aroung 500-700 positive records only, while having 160000 negative records. So, our data is could be highly biased towards predicting a comment as negative toxicity for most of the classes.\n\"\"\"\n\"\"\"\n**Let's have a look at some of the data examples.**\n\"\"\"\nfor i in range(1):\n    j = random.randint(0, 10000)\n    print(training_set.values[j])\n    \n\"\"\"\n**Okay, so enough of analyzing the data. Now, let's preprocess our data for training.**\n\"\"\"\n\"\"\"\nSince, we have text data and the semantics of text are very important to correctly classify them as being toxic, severe_toxic, and so on, we will be using pre-trained word embeddings as inputs.\n\"\"\"\n\"\"\"\n## Getting Word Embeddings\n\"\"\"\nf = open(\"..\/input\/glove-embeddings\/glove.6B.300d.txt\")\nembedding_matrix = {}\nfor line in tqdm(f):\n    temp = line.split(\" \")\n    word = temp[0]\n    embeds = np.array(temp[1:], dtype='float32')\n    embedding_matrix[word] = embeds\n\"\"\"\nFor the words which may not be present in glove word embeddings, we will be using zero vectos.\n\"\"\"\n\"\"\"\n**Let's now create x and y datasets where 'x' will be the values we will use for making predictions and 'y', the values to predict.**\n\"\"\"\nx = training_set['comment_text']\ny = training_set[columns]\n\"\"\"\nNow, we will tokenize our texts and convert them to sequences.\n\"\"\"\ntoken = Tokenizer(num_words=20000)\ntoken.fit_on_texts(x)\nseq = token.texts_to_sequences(x)\n\"\"\"\nWe will need to pad our sequences. This is useful for making all the sentences of the same size.\n\"\"\"\npadded_seq = pad_sequences(seq, maxlen=40)\nvocab_size = len(token.word_index)+1\nprint(vocab_size)\n\"\"\"\nWe will now create word embeddings for words in our dictionary.\n\"\"\"\nembeddings = np.zeros((vocab_size, 300))\nfor word, i in tqdm(token.word_index.items(), position=0):\n    embeds = embedding_matrix.get(word)\n    if embeds is not None:\n        embeddings[i] = embeds\n\"\"\"\n## Defining our models\n\"\"\"\n\"\"\"\nSince we have to make predictions for six classes, let's have a separate classifier for each of them.\n\"\"\"\n\"\"\"\n**Model for TOXIC **\n\"\"\"\nmodel1 = Sequential()\nmodel1.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel1.add(Conv1D(128, 5, activation='relu'))\nmodel1.add(MaxPooling1D(5))\nmodel1.add(Conv1D(128, 5, activation='relu'))\nmodel1.add(MaxPooling1D(3))\nmodel1.add(Flatten())\nmodel1.add(Dense(128, activation='relu'))\nmodel1.add(Dense(1, activation='sigmoid'))\n\nmodel1.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel1.summary()\nmodel1.fit(padded_seq, training_set['toxic'], epochs=3, batch_size=32, validation_split=0.2)\n\"\"\"\n**Model for SEVERE_TOXIC**\n\"\"\"\nmodel2 = Sequential()\nmodel2.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel2.add(Conv1D(128, 5, activation='relu'))\nmodel2.add(MaxPooling1D(5))\nmodel2.add(Conv1D(128, 5, activation='relu'))\nmodel2.add(MaxPooling1D(3))\nmodel2.add(Flatten())\nmodel2.add(Dense(128, activation='relu'))\nmodel2.add(Dense(1, activation='sigmoid'))\n\nmodel2.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel2.summary()\nmodel2.fit(padded_seq, training_set['severe_toxic'], epochs=2, batch_size=32, validation_split=0.2)\n\"\"\"\n**Model for OBSCENE**\n\"\"\"\nmodel3 = Sequential()\nmodel3.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel3.add(Conv1D(128, 5, activation='relu'))\nmodel3.add(MaxPooling1D(5))\nmodel3.add(Conv1D(128, 5, activation='relu'))\nmodel3.add(MaxPooling1D(3))\nmodel3.add(Flatten())\nmodel3.add(Dense(128, activation='relu'))\nmodel3.add(Dense(1, activation='sigmoid'))\n\nmodel3.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel3.summary()\nmodel3.fit(padded_seq, training_set['obscene'], epochs=2, batch_size=32, validation_split=0.2)\n\"\"\"\n**Model for THREAT**\n\"\"\"\nmodel4 = Sequential()\nmodel4.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel4.add(Conv1D(128, 5, activation='relu'))\nmodel4.add(MaxPooling1D(5))\nmodel4.add(Conv1D(128, 5, activation='relu'))\nmodel4.add(MaxPooling1D(3))\nmodel4.add(Flatten())\nmodel4.add(Dense(128, activation='relu'))\nmodel4.add(Dense(1, activation='sigmoid'))\n\nmodel4.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel4.summary()\nmodel4.fit(padded_seq, training_set['threat'], epochs=1, batch_size=32, validation_split=0.2)\n\"\"\"\n**Model for INSULT**\n\"\"\"\nmodel5 = Sequential()\nmodel5.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel5.add(Conv1D(128, 5, activation='relu'))\nmodel5.add(MaxPooling1D(5))\nmodel5.add(Conv1D(128, 5, activation='relu'))\nmodel5.add(MaxPooling1D(3))\nmodel5.add(Flatten())\nmodel5.add(Dense(128, activation='relu'))\nmodel5.add(Dense(1, activation='sigmoid'))\n\nmodel5.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel5.summary()\nmodel5.fit(padded_seq, training_set['insult'], epochs=2, batch_size=32, validation_split=0.2)\n\"\"\"\n**Model fot IDENTITY_HATE**\n\"\"\"\nmodel6 = Sequential()\nmodel6.add(Embedding(vocab_size, 300, weights = [embeddings],\n                     input_length=40, trainable=False))\nmodel6.add(Conv1D(128, 5, activation='relu'))\nmodel6.add(MaxPooling1D(5))\nmodel6.add(Conv1D(128, 5, activation='relu'))\nmodel6.add(MaxPooling1D(3))\nmodel6.add(Flatten())\nmodel6.add(Dense(128, activation='relu'))\nmodel6.add(Dense(1, activation='sigmoid'))\n\nmodel6.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel6.summary()\nmodel6.fit(padded_seq, training_set['identity_hate'], epochs=1, batch_size=32, validation_split=0.2)\n\"\"\"\n## Let's make some predictions now\n\"\"\"\ntest_set = pd.read_csv('..\/input\/jigsaw-toxic-comment-classification-challenge\/test.csv')\nx_test = test_set['comment_text']\ntoken = Tokenizer(num_words=20000)\ntoken.fit_on_texts(x_test)\nseq = token.texts_to_sequences(x_test)\ntest_padded_seq = pad_sequences(seq, maxlen=40)\ntoxic = model1.predict(test_padded_seq)\nsevere_toxic = model2.predict(test_padded_seq)\nobscene = model3.predict(test_padded_seq)\nthreat = model4.predict(test_padded_seq)\ninsult = model5.predict(test_padded_seq)\nidentity_hate = model6.predict(test_padded_seq)\ntoxic = [1 if i>=0.5 else 0 for i in toxic]\nsevere_toxic = [1 if i>=0.5 else 0 for i in severe_toxic]\nobscene = [1 if i>=0.5 else 0 for i in obscene]\nthreat = [1 if i>=0.5 else 0 for i in threat]\ninsult = [1 if i>=0.5 else 0 for i in insult]\nidentity_hate = [1 if i>=0.5 else 0 for i in identity_hate]\nid = test_set['id']\ndf = pd.DataFrame({'id':id,\n                   'toxic':toxic,\n                   'severe_toxic':severe_toxic,\n                   'obscene':obscene,\n                   'threat':threat,\n                   'insult':insult,\n                   'identity_hate':identity_hate})\ndf.to_csv(\"submission.csv\", index=False)","meta":"{'source': 'AI4Code', 'id': 'a1ac1425d2c197'}"}
{"id":"25407","text":"!pip install -U scikit-learn --q\nimport sklearn\nprint(sklearn.__version__)\nimport pandas as pd\nfrom collections import Counter\nfrom itertools import product\nfrom tqdm.notebook import tqdm\nimport numpy as np\nimport optuna\nimport shap\nimport copy\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn import preprocessing,model_selection,decomposition,compose,pipeline,metrics,ensemble,impute\nfrom sklearn.utils import class_weight,compute_sample_weight\nfrom sklearn.ensemble import GradientBoostingClassifier,GradientBoostingRegressor\nimport xgboost as xgb\nimport lightgbm as lgb\n\n\noptuna.logging.set_verbosity(optuna.logging.WARNING)\n\nshap.initjs()\ndef Preprocessor(data,scaler):\n    \n    cat_cols = data.select_dtypes('object').columns.tolist()\n    num_cols = data.select_dtypes(exclude='object').columns.tolist()\n    \n    numerical_transformer = pipeline.Pipeline(steps=[\n        ('imputer',impute.SimpleImputer(\n            missing_values=np.nan,\n            strategy='most_frequent',\n            fill_value=None,\n            verbose=0,\n            copy=True,\n            add_indicator=False\n        )),\n        ('scaler',getattr(preprocessing,scaler)())\n    ])\n\n    categorical_transformer = pipeline.Pipeline(steps=[\n        ('imputer',impute.SimpleImputer(\n            missing_values=np.nan,\n            strategy='constant',\n            fill_value='missing',\n            verbose=0,\n            copy=True,\n            add_indicator=False\n        )),\n        ('encoder',preprocessing.OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-999))\n    ])\n\n    preprocessor = compose.ColumnTransformer(transformers=[\n        ('numerical_transformer',numerical_transformer,num_cols),\n        ('categorical_transformer',categorical_transformer,cat_cols)\n    ])\n    \n    preprocessor.fit(data)\n    return preprocessor,cat_cols,num_cols\ndef cross_vall_split(df,n_split):\n    df['fold'] = None\n    kf = model_selection.KFold(n_splits=n_split,shuffle=True,random_state=1234)\n    for fold,(train_idx,valid_idx) in enumerate(kf.split(df)):\n        df.loc[valid_idx,'fold'] = fold\n    return df\ndef kde_target(var_name, df):\n    \n    if df[var_name].dtype=='object':\n        print(\"Not a numeric column\")\n        return None\n    corr = df['loan_status'].corr(df[var_name])\n    \n    FullyPaid = df.loc[df['loan_status'] == 0, var_name].median()\n    Default = df.loc[df['loan_status'] == 1, var_name].median()\n    \n    plt.figure(figsize = (12, 6))\n    \n    sns.kdeplot(df.loc[df['loan_status'] == 0, var_name], label = 'Fully Paid',)\n    sns.kdeplot(df.loc[df['loan_status'] == 1, var_name], label = 'Default',)\n\n    \n    plt.xlabel(var_name); plt.ylabel('Density'); plt.title('%s Distribution' % var_name)\n    plt.legend();\n    \n    print('The correlation between %s and the TARGET is %0.4f' % (var_name, corr))\n    \n    print('Median value for FullyPaid = %0.4f' % FullyPaid)\n    print('Median value for Default = %0.4f' % Default)\ndf = pd.read_feather('..\/input\/d\/ransakaravihara\/lending-club-loan-cleaned\/Cleaned_loandata.feather')\n\"\"\"\n### Feature engineering\n\"\"\"\nfor col in df.columns:\n    if df[col].isna().sum()>0:print(col,\"Has \",df[col].isna().sum(),\" null values\")\ndf['emp_title_test'] = df['emp_title'].fillna(\"missing\")\ndf['emp_length_test'] = df['emp_length'].fillna(\"missing\")\ncols_to_drop = ['emp_length_test','emp_title_test']\n\"\"\"\n- Create new features\n\"\"\"\ndf['issue_d_year'] = pd.DatetimeIndex(df['issue_d']).year  \ndf['issue_d_month'] = pd.DatetimeIndex(df['issue_d']).month  \ndf['last_pymnt_d_year'] = pd.DatetimeIndex(df['last_pymnt_d']).year  \ndf['last_pymnt_d_month'] = pd.DatetimeIndex(df['last_pymnt_d']).month \ndf['last_credit_pull_d_year'] = pd.DatetimeIndex(df['last_credit_pull_d']).year  \ndf['last_credit_pull_d_month'] = pd.DatetimeIndex(df['last_credit_pull_d']).month \ndf['term'] = df.term.apply(lambda x:float(x[:2]))\ndf['int_rate'] = df.int_rate .apply(lambda x:float(x.replace(\"%\",\"\")))\nlstatus_map = {v:k for k,v in dict(enumerate(df['loan_status'].unique())).items()}\n#encode target\ndf['loan_status'] = df['loan_status'].map(lstatus_map)\nint_to_lstatus = {val:key for key,val in lstatus_map.items()}\ndef plot_target_vs_cat(df,x,figsize=(30,20)):\n    if df[x].nunique()<=10:\n        nrows = round(df[x].nunique()\/2)\n        ncols = 2\n    elif df[x].nunique()<=30:\n        nrows = round(df[x].nunique()\/3)\n        ncols = 3\n    else:\n        print(\"Large unique values...skipping\")\n        return None\n    fig,ax = plt.subplots(nrows=nrows,ncols=ncols,figsize=figsize)\n    for axi,val in zip(ax.flatten(),df[x].unique()):\n        e = df.query(f\"{x}=='{val}'\").reset_index(drop=True)\n        e['loan_status'] = e['loan_status'].map(int_to_lstatus)\n        e = pd.DataFrame(e['loan_status'].value_counts()).reset_index()\n        colors = sns.color_palette('pastel')[0:len(e)]\n        axi.pie(e['loan_status'], labels = e['index'], colors = colors, autopct='%.0f%%')\n        axi.set_title(val,fontweight='bold')\n    plt.show()\ndf.select_dtypes('object').columns.tolist()\n\"\"\"\n#### plot whether emp_length feature has eny major impact on target. Also, find is there are any meaning behind missing emp_length\n\"\"\"\nplot_target_vs_cat(df,'emp_length_test',figsize=(30,30))\n\"\"\"\n#### **conclusion**\n - While all other emp_length features behave as same, emp_lenght missing behaving deferently. See the fully_paid\/default ratio of emp_title missing populations\n\"\"\"\n# Filling na\ndf['emp_length'] = df['emp_length'].fillna('missing')\n\"\"\"\n#### emp_title_test vs target column impact\n\"\"\"\ntop_20_emp = df\\\n            .groupby(['emp_title_test'])\\\n            .agg({\"id\":'count','loan_status':sum})\\\n            .reset_index()\\\n            .sort_values('id',ascending=False)\\\n            .head(20)\\\n            .reset_index(drop=True)\ntop_20_emp['default_ratio'] = top_20_emp['loan_status']\/top_20_emp['id']\ntop_20_emp\ndf['emp_title'] = df['emp_title'].fillna('missing')\ndf['emp_title'] = df['emp_title'].apply(lambda s: s.lower())\nplot_target_vs_cat(df,'revol_util',figsize=(30,30))\n\"\"\"\n#### Find home owner ship distribution against loan status\n\"\"\"\nplot_target_vs_cat(df,'home_ownership',figsize=(20,20))\nplot_target_vs_cat(df,'earliest_cr_line',figsize=(20,20))\n\"\"\"\n### Plot selected numerical features against target\n\"\"\"\nkde_target(\"loan_amnt\",df)\n\"\"\"\n## Conclusion\n - If loan amount ~10,000 or lower there is high chance to fully pay the loan\n\"\"\"\nkde_target(\"funded_amnt\",df)\n\"\"\"\n## Conclusion\n - Simmilar to the loan amount featue\n \n Cheking correlation of funded_amnt and loan_amnt\n\"\"\"\ndf['funded_amnt'].corr(df['loan_amnt'])\ncols_to_drop.append('funded_amnt')\nkde_target(\"term\",df)\n\"\"\"\n## Conclusion\n - Higher the number of payments on the loan there is high risk to loan to default\n\"\"\"\nkde_target(\"int_rate\",df)\n\"\"\"\n## Conclusion\n - Higher the interest rate on the loan there is high risk to loan to default\n\"\"\"\nkde_target(\"installment\",df)\n\"\"\"\n## Conclusion\n - Higher the installment amount there is high risk to loan will be default\n\"\"\"\nkde_target(\"earliest_cr_line\",df)\nkde_target(\"dti\",df)\nkde_target(\"tot_hi_cred_lim\",df)\ndf['last_pymnt_d_year'].fillna(df['last_pymnt_d_year'].median(),inplace=True)\ndf['last_pymnt_d_month'].fillna(df['last_pymnt_d_month'].median(),inplace=True)\ndf['last_credit_pull_d_year'].fillna(df['last_credit_pull_d_year'].median(),inplace=True)\ndf['last_credit_pull_d_month'].fillna(df['last_credit_pull_d_month'].median(),inplace=True)\ndatetime_cols = df.select_dtypes('datetime').columns.tolist()\ncols_to_drop.extend(datetime_cols)\nprint(cols_to_drop)\ndf.drop(cols_to_drop,axis=1,inplace=True)\nscaler = 'None'\ny = df['loan_status'].map(int_to_lstatus)\ny.value_counts()\ny = y.map(lstatus_map)\nids = df['id']\ndf.drop(['loan_status','id'],axis=1,inplace=True)\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test = train_test_split(df,y,test_size = 0.10 ,random_state = 2, stratify =y)\nx_train,x_valid,y_train,y_valid = train_test_split(x_train,y_train,test_size = 0.20 ,random_state = 2, stratify =y_train)\n\nx_train.shape,y_train.shape,x_test.shape,y_test.shape,x_valid.shape,y_valid.shape\ncat_cols = df.select_dtypes('object').columns.tolist()\nnum_cols = df.select_dtypes(exclude='object').columns.tolist()\n\nnumerical_transformer = pipeline.Pipeline(steps=[\n    ('scaler',getattr(preprocessing,scaler)() if scaler!='None' else None)\n])\n\ncategorical_transformer = pipeline.Pipeline(steps=[\n    ('encoder',preprocessing.OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=np.nan))\n])\n\npreprocessor = compose.ColumnTransformer(transformers=[\n    ('numerical_transformer',numerical_transformer,num_cols),\n    ('categorical_transformer',categorical_transformer,cat_cols)\n])\npreprocessor.fit(x_train)\n\nx_train = pd.DataFrame(preprocessor.transform(x_train),columns=x_train.columns)\nx_test = pd.DataFrame(preprocessor.transform(x_test),columns=x_train.columns)\nx_valid = pd.DataFrame(preprocessor.transform(x_valid),columns=x_train.columns)\n\"\"\"\n### Modeling\n##### XGBoost Modeling\n\"\"\"\ndef xgb_f1(y, t, threshold=0.5):\n    \"\"\"Helper funcion for XGBoost f1_score\"\"\"\n    t = t.get_label()\n    y_bin = [1. if y_cont > threshold else 0. for y_cont in y]\n    return 'f1',metrics.f1_score(t,y_bin)\nmodel = xgb.XGBClassifier(n_estimators=20,use_label_encoder=False,tree_method='gpu_hist',gpu_id=0,random_state=1234)\nmodel.fit(x_train,y_train,eval_set=[(x_valid,y_valid)],eval_metric=xgb_f1,verbose=False)\ntest_predictions_xgb = model.predict(x_test)\ntrain_preds_xgb = model.predict(x_train)\nvalid_preds_xgb = model.predict(x_valid)\n\ntest_proba_xgb = model.predict_proba(x_test)\ntrain_proba_xgb = model.predict_proba(x_train)\nvalid_proba_xgb = model.predict_proba(x_valid)\ncm_test_xgb = metrics.confusion_matrix(y_test,test_predictions_xgb)\ncm_train_xgb = metrics.confusion_matrix(y_train,train_preds_xgb)\n\"\"\"\n##### LighGBM Modeling\n\"\"\"\nlgb_bst = lgb.LGBMClassifier(n_estimators=20,random_state=1234)\nlgb_bst.fit(x_train,y_train,eval_set=[(x_valid,y_valid)],early_stopping_rounds=10)\ntest_predictions_lgb = lgb_bst.predict(x_test)\ntrain_preds_lgb = lgb_bst.predict(x_train)\nvalid_preds_lgb = lgb_bst.predict(x_valid)\n\ntest_proba_lgb = lgb_bst.predict_proba(x_test)\ntrain_proba_lgb = lgb_bst.predict_proba(x_train)\nvalid_proba_lgb = lgb_bst.predict_proba(x_valid)\ncm_test_lgb = metrics.confusion_matrix(y_test,test_predictions_lgb)\ncm_train_lgb = metrics.confusion_matrix(y_train,train_preds_lgb)\nfig,ax = plt.subplots(2,2,figsize=(15,15))\nmodel_cms = dict(zip(['LGB_TEST','LGB_TRAIN','XGB_TEST','XGB_TRAIN'],[cm_test_lgb,cm_train_lgb,cm_test_xgb,cm_train_xgb]))\n\nfor axi,con_mat in zip(ax.flatten(),model_cms):\n    sns.heatmap(model_cms[con_mat],annot=True,cmap='viridis',fmt=\".0f\",cbar=False,ax=axi,xticklabels=False,yticklabels=False)\n    axi.text(x=0.85,y=0,s=con_mat,backgroundcolor='y')\n\"\"\"\n### Explain the model\n\"\"\"\nxgb.plot_importance(model,max_num_features=20)\nplt.title(\"Top 20 features\")\nplt.show()\nexplainer = shap.TreeExplainer(model)\nshap_values = explainer.shap_values(x_train)\nprint(f\"Check example of {int_to_lstatus[y_train.iloc[100]]}\")\nshap.force_plot(explainer.expected_value, shap_values[100,:], x_train.iloc[100,:])\nprint(f\"Check example of {int_to_lstatus[y_train.iloc[39]]}\")\nshap.force_plot(explainer.expected_value, shap_values[39,:], x_train.iloc[39,:])\nshap.force_plot(explainer.expected_value, shap_values[:1000,:], x_train.iloc[:1000,:])\nshap.summary_plot(shap_values, x_train, plot_type=\"bar\")\nshap.summary_plot(shap_values, x_train)\n\"\"\"\n- ### Conclusions\n - High installments caused to loan to default\n - Low inquries in past 6 mnths tends to loan to default\n - Higher the loan amount, the default chance is high\n - Higher the dti(borrower's debt repayment capacity) tends to fully paid the loan\n\"\"\"\n\"\"\"\n - ##### Current model using morethan 80 features. Having such a large featueres tends to data pipeline more complicated and hard to maintain. Trying to reduce the no. of features\n\"\"\"\nvals= np.abs(shap_values).mean(0)\nfeature_importance = pd.DataFrame(list(zip(x_train.columns,vals)),columns=['col_name','feature_importance_vals'])\nfeature_importance = feature_importance.sort_values(by=['feature_importance_vals'],ascending=False).reset_index(drop=True)\nfeatures_to_use = feature_importance['col_name'][0:30].tolist()\nfiltered_cols = copy.deepcopy(features_to_use)\nfiltered_cols.append('loan_status')\ndf['loan_status'] = y\nfig, ax = plt.subplots(figsize=(20, 15))\nsns.heatmap(\n        df[features_to_use].corr(), \n        cmap = sns.diverging_palette(220, 10, as_cmap = True),\n        square=True, \n        cbar=False,\n        ax=ax,\n#         annot=True, \n        linewidths=0.1,vmax=1.0, linecolor='white',\n        annot_kws={'fontsize':12 })\n\nplt.show()\ndel df['loan_status']\nfeatures_to_use.remove('funded_amnt_inv')\nfeatures_to_use\nbst_xgb = xgb.XGBClassifier(n_estimators=20,use_label_encoder=False,tree_method='gpu_hist',gpu_id=0,random_state=1234)\nbst_xgb.fit(x_train[features_to_use],y_train,eval_set=[(x_valid[features_to_use],y_valid)],eval_metric=xgb_f1,verbose=True)\nbst_lgb = lgb.LGBMClassifier(n_estimators=20,random_state=1234)\nbst_lgb.fit(x_train[features_to_use],y_train,eval_set=[(x_valid[features_to_use],y_valid)])\ntest_predictions_lgb = bst_lgb.predict(x_test[features_to_use])\ntrain_preds_lgb = bst_lgb.predict(x_train[features_to_use])\nvalid_preds_lgb = bst_lgb.predict(x_valid[features_to_use])\n\ntest_predictions_xgb = bst_xgb.predict(x_test[features_to_use])\ntrain_preds_xgb = bst_lgb.predict(x_train[features_to_use])\nvalid_preds_xgb = bst_xgb.predict(x_valid[features_to_use])\ncm_test_lgb = metrics.confusion_matrix(y_test,test_predictions_lgb)\ncm_train_lgb = metrics.confusion_matrix(y_train,train_preds_lgb)\n\ncm_test_xgb = metrics.confusion_matrix(y_test,test_predictions_xgb)\ncm_train_xgb = metrics.confusion_matrix(y_train,train_preds_xgb)\nfig,ax = plt.subplots(2,2,figsize=(15,15))\nmodel_cms = dict(zip(['LGB_TEST','LGB_TRAIN','XGB_TEST','XGB_TRAIN'],[cm_test_lgb,cm_train_lgb,cm_test_xgb,cm_train_xgb]))\n\nfor axi,con_mat in zip(ax.flatten(),model_cms):\n    sns.heatmap(model_cms[con_mat],annot=True,cmap='viridis',fmt=\".0f\",cbar=False,ax=axi,xticklabels=True,yticklabels=True)\n    axi.text(x=0.85,y=0,s=con_mat,backgroundcolor='y')\n\"\"\"\n## As per above model test results,\n - LGB Model\n  - 0 predictions for loan defaults as fully paid\n  - 788 predictions for loan fully paid as loan defaults (This cause revenue loss for the bank)\n - XGB Model\n  - 8 predictions for loan defaults as fully paid\n  - 458 predictions for loan fully paid as loan defaults (This cause revenue loss for the bank but loss is lower than LGB)\n  \n**Hence, I'd Pick final model as XGB Model**\n\"\"\"\nfeatures_to_use = features_to_use\nfeatures_to_use.extend(['id','loan_status'])\ndf['id'] = ids\ndf['loan_status'] = y\n\"\"\"\n**Even our model preformed pretty well, saving the data for further model fine tuning. Not going to tune model in this notebook.**\n\"\"\"\nfeatures_to_use  = list(set(features_to_use))\ndf[features_to_use].to_feather('train_loan_data.feather')","meta":"{'source': 'AI4Code', 'id': '2ec0744203f014'}"}
{"id":"76260","text":"\"\"\"\n# Import Libraires \n\"\"\"\nimport os \nimport re \nfrom scipy import ndimage, misc \nfrom tqdm import tqdm\nfrom tensorflow.keras.preprocessing.image import img_to_array\n\n\nfrom skimage.transform import resize, rescale\nimport matplotlib.pyplot as plt\nimport numpy as np\nnp. random. seed(0)\nimport cv2 as cv2\n\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input, Dense ,Conv2D,MaxPooling2D ,Dropout\nfrom tensorflow.keras.layers import Conv2DTranspose, UpSampling2D, add\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.utils import plot_model\nimport tensorflow as tf\n\nprint(tf.__version__)\n\n\n\"\"\"\n# Load Data\n\"\"\"\n# to get the files in proper order\ndef sorted_alphanumeric(data):  \n    convert = lambda text: int(text) if text.isdigit() else text.lower()\n    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)',key)]\n    return sorted(data,key = alphanum_key)\n# defining the size of the image\nSIZE = 256\nhigh_img = []\npath = '..\/input\/image-super-resolution\/dataset\/Raw Data\/high_res'\nfiles = os.listdir(path)\nfiles = sorted_alphanumeric(files)\nfor i in tqdm(files):    \n    if i == '855.jpg':\n        break\n    else:    \n        img = cv2.imread(path + '\/'+i,1)\n        # open cv reads images in BGR format so we have to convert it to RGB\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        #resizing image\n        img = cv2.resize(img, (SIZE, SIZE))\n        img = img.astype('float32') \/ 255.0\n        high_img.append(img_to_array(img))\n\n\nlow_img = []\npath = '..\/input\/image-super-resolution\/dataset\/Raw Data\/low_res'\nfiles = os.listdir(path)\nfiles = sorted_alphanumeric(files)\nfor i in tqdm(files):\n    if i == '855.jpg':\n        break\n    else: \n        img = cv2.imread(path + '\/'+i,1)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        #resizing image\n        img = cv2.resize(img, (SIZE, SIZE))\n        img = img.astype('float32') \/ 255.0\n        low_img.append(img_to_array(img))\n\"\"\"\n# Data Visualization\n\"\"\"\nfor i in range(4):\n    a = np.random.randint(0,855)\n    plt.figure(figsize=(10,10))\n    plt.subplot(1,2,1)\n    plt.title('High Resolution Imge', color = 'green', fontsize = 20)\n    plt.imshow(high_img[a])\n    plt.axis('off')\n    plt.subplot(1,2,2)\n    plt.title('low Resolution Image ', color = 'black', fontsize = 20)\n    plt.imshow(low_img[a])\n    plt.axis('off')\n\"\"\"\n# Slicing and Reshaping Images\n\"\"\"\ntrain_high_image = high_img[:700]\ntrain_low_image = low_img[:700]\ntrain_high_image = np.reshape(train_high_image,(len(train_high_image),SIZE,SIZE,3))\ntrain_low_image = np.reshape(train_low_image,(len(train_low_image),SIZE,SIZE,3))\n\nvalidation_high_image = high_img[700:830]\nvalidation_low_image = low_img[700:830]\nvalidation_high_image= np.reshape(validation_high_image,(len(validation_high_image),SIZE,SIZE,3))\nvalidation_low_image = np.reshape(validation_low_image,(len(validation_low_image),SIZE,SIZE,3))\n\n\ntest_high_image = high_img[830:]\ntest_low_image = low_img[830:]\ntest_high_image= np.reshape(test_high_image,(len(test_high_image),SIZE,SIZE,3))\ntest_low_image = np.reshape(test_low_image,(len(test_low_image),SIZE,SIZE,3))\n\nprint(\"Shape of training images:\",train_high_image.shape)\nprint(\"Shape of test images:\",test_high_image.shape)\nprint(\"Shape of validation images:\",validation_high_image.shape)\n\n\"\"\"\n# Defining Model\n\"\"\"\ndef residual_block_gen(ch=64,k_s=3,st=1):\n    model=tf.keras.Sequential([\n    tf.keras.layers.Conv2D(ch,k_s,strides=(st,st),padding='same'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.LeakyReLU(),\n    tf.keras.layers.Conv2D(ch,k_s,strides=(st,st),padding='same'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.LeakyReLU(),])\n    return model\n\n\ninput_img=Input(shape=(256,256,3))\nl1=Conv2D (64,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(input_img)\nl2=Conv2D (64,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l1)\nl3=MaxPooling2D(padding='same')(l2)\nl4=Conv2D (128,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l3)\nl5=Conv2D (128,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l4)\nl6=MaxPooling2D(padding='same')(l5)\n\nl7=Conv2D (256,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l6)\nl7=residual_block_gen()(l7)\nl8=UpSampling2D()(l7)\nl9=Conv2D (128,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l8)\nl10=Conv2D (128,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l9)\nl11=add([l10,l5])\nl12=UpSampling2D()(l11)\nl13=Conv2D (64,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l12)\nl14=Conv2D (64,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l13)\nl15=add([l14,l2])\n\ndecoder=Conv2D (3,(3,3) , padding='same' ,activation='relu',activity_regularizer=regularizers.l1(10e-10))(l15)\n#out= tf.keras.filters\nautoencoder_residual=Model(input_img,decoder)\nautoencoder_residual.summary()\nplot_model(autoencoder_residual, to_file ='encoder.png',show_shapes=True)\n\"\"\"\n# Compile \n\"\"\"\nautoencoder_residual.compile(optimizer = tf.keras.optimizers.Adam(learning_rate = 0.001), loss = 'mean_absolute_error',\n              metrics = ['acc'])\n\"\"\"\n# Fitting model\n\"\"\"\nautoencoder_residual.fit(train_low_image, train_high_image, epochs = 50, batch_size = 1,\n          validation_data = (validation_low_image,validation_high_image))\n\"\"\"\n# Prediction Visualization\n\"\"\"\ndef PSNR(y_true,y_pred):\n    mse=tf.reduce_mean( (y_true - y_pred) ** 2 )\n    return 20 * log10(1\/ (mse ** 0.5))\n\ndef log10(x):\n    numerator = tf.math.log(x)\n    denominator = tf.math.log(tf.constant(10, dtype=numerator.dtype))\n    return numerator \/ denominator\n\ndef pixel_MSE(y_true,y_pred):\n    return tf.reduce_mean( (y_true - y_pred) ** 2 )\ndef plot_images(high,low,predicted):\n    plt.figure(figsize=(15,15))\n    plt.subplot(1,3,1)\n    plt.title('High Image', color = 'green', fontsize = 20)\n    plt.imshow(high)\n    plt.subplot(1,3,2)\n    plt.title('Low Image ', color = 'black', fontsize = 20)\n    plt.imshow(low)\n    plt.subplot(1,3,3)\n    plt.title('Predicted Image ', color = 'Red', fontsize = 20)\n    plt.imshow(predicted)\n   \n    plt.show()\n\nfor i in range(16,25):\n    \n    predicted = np.clip(autoencoder_residual.predict(test_low_image[i].reshape(1,SIZE, SIZE,3)),0.0,1.0).reshape(SIZE, SIZE,3)\n    plot_images(test_high_image[i],test_low_image[i],predicted)\n    print('PSNR',PSNR(test_high_image[i],predicted),'dB')\n\"\"\"\n# Saving model\n\"\"\"\nautoencoder_residual.save(\"final_model.h5\")","meta":"{'source': 'AI4Code', 'id': '8c2d1f0f1b64bd'}"}
{"id":"128308","text":"# 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)\nfrom matplotlib import pyplot as plt\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\nimport pandas as pd\ncreditcard = pd.read_csv(\"..\/input\/creditcardfraud\/creditcard.csv\",index_col=0)\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ncreditcard.head()\n# summarize the shape of the dataset\nprint(creditcard.shape)\ncreditcard.describe()\ncreditcard.info()\n\"\"\"\n## Target Distribution\n\"\"\"\nplt.hist(creditcard['Class'])\ncreditcard.Class.unique()\ncreditcard.Class.value_counts()\n\"\"\"\n# Selecting Highly Correlated Features\n\"\"\"\ncor = creditcard.corr()\n#Correlation with output variable\ncor_target = abs(cor[\"Class\"])\n#Selecting highly correlated features\nrelevant_features = cor_target[cor_target>0.2]\nrelevant_features\n#Selecting highly correlated features\nrelevant_features = cor_target[cor_target>0.1]\nrelevant_features\ndf=relevant_features.to_frame()\ndf.head()\ndf1=cor[['V1','V3','V4','V7','V10','Class']]\ndf1.head()\nimport seaborn as sns\n#Using Pearson Correlation\nplt.figure(figsize=(12,10))\n#cor = creditcard.corr()\nsns.heatmap(df1, annot=True, cmap=plt.cm.Reds)\nplt.show()\n\"\"\"\n## Finding Columns with NULL Values\n\nAs we see here, there are no null values in the dataset.\n\"\"\"\ncreditcard.isnull().sum(axis=0)","meta":"{'source': 'AI4Code', 'id': 'ec055e6ca91bbe'}"}
{"id":"83990","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport tensorflow\nfrom tensorflow.keras.models import Sequential \nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding,Bidirectional,LSTM,Dense,Dropout\nfrom tensorflow.keras.utils import to_categorical\ndf=pd.read_csv('..\/input\/twitter-and-reddit-sentimental-analysis-dataset\/Reddit_Data.csv')\ndf.head(5)\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ndist=list(df.category)\npp=[0,0,0]\nfor i in dist:\n    if i==-1:\n        pp[0]+=1\n    elif i==0:\n        pp[1]+=1\n    else:\n        pp[2]+=1\nprint(pp)\n        \n\nlabels=['Negative','Neutral','Positive']\nsns.barplot(x=labels,y=pp)\nplt.show()\ncomment=list(df.clean_comment.astype(str))\nsentiment=list(df.category)\nreddit_dict=dict(zip(comment,sentiment))\nprint(list(reddit_dict.items())[:5])\nNeg_list=[]\nPos_list=[]\nNeutral_list=[]\nfor i,j in reddit_dict.items():\n    if j==-1:\n        Neg_list.append(i)\n    elif j==0:\n        Neutral_list.append(i)\n    else:\n        Pos_list.append(i)    \nprint(Neg_list[:2],'\\n',Neutral_list[:2],'\\n',Pos_list[:2])\npos_len=[]\nfor i in Pos_list:\n    pos_len.append(len(i))\nneg_len=[]\nfor i in Neg_list:\n    neg_len.append(len(i))\nNeutral_len=[]\nfor i in Neutral_list:\n    Neutral_len.append(len(i))\nplt.subplots(figsize=(20,8))\nplt.title(\"Word Length Variation\")\nplt.plot(Neutral_len[:250],c='b',label='Neutral')\nplt.plot(neg_len[:250],c='r',label='Negative')\nplt.plot(pos_len[:250],c='g',label='Positive')\nplt.legend(loc='upper left')\nplt.show()\npos_mean=sum(pos_len)\/\/len(pos_len)\nneg_mean=sum(neg_len)\/\/len(neg_len)\nneutral_mean=sum(Neutral_len)\/\/len(Neutral_len)\ncombined_mean=(sum(pos_len)+sum(neg_len)+sum(Neutral_len))\/\/(len(pos_len)+len(neg_len)+len(Neutral_len))\nplt.title(\"Average Word Length\")\nsns.barplot(x=['Negative','Neutral','Positive','Combined'],y=[neg_mean,neutral_mean,pos_mean,combined_mean])\nplt.show()\n\"\"\"\n# Tokeinzer\n\n\"\"\"\nX=df['clean_comment'].astype('str')\nX[:5]\nlp=\"\"\nfor i in X:\n    lp+=i+\" \"\nprint(lp[:100])\nst=lp.split(' ')\ndict_len=len(set(st))\ndict_len,len(st)\ntokenizer=Tokenizer(num_words=dict_len,lower=True,oov_token=\"OOV\")\ntokenizer.fit_on_texts(X)\nlen(tokenizer.word_index)\n\nX_train=tokenizer.texts_to_sequences(X)\nX_train_padded=pad_sequences(X_train,maxlen=175,padding='post',truncating='post')\nX_train[:2]\n\"\"\"\n# One Hot Encode The Sentiment Values\n\"\"\"\ndf['category']=df['category'].replace({-1:2})\nmp={0:\"Neutral\",1:\"Positve\",2:\"Negative\"}\nY=df['category'].values\nY_hot=to_categorical(Y)\nprint(Y_hot[:3])\n\"\"\"\n# The Model\n\"\"\"\nmodel=Sequential()\nmodel.add(Embedding(dict_len,64,input_length=175))\nmodel.add(Dropout(0.3))\nmodel.add(Bidirectional(LSTM(175,return_sequences=True)))\nmodel.add(Dropout(0.3))\nmodel.add(Bidirectional(LSTM(350,return_sequences=True)))\nmodel.add(Dropout(0.3))\nmodel.add(Bidirectional(LSTM(700)))\nmodel.add(Dense(3,activation='softmax'))\nprint(model.summary())\nmodel.compile(optimizer='adam',metrics=['accuracy'],loss='categorical_crossentropy')\n\nhist=model.fit(X_train_padded,Y_hot,epochs=5,validation_split=0.2)\nplt.plot(hist.history['accuracy'],c='b',label='Training')\nplt.plot(hist.history['val_accuracy'],c='r',label='Validation')\nplt.legend(loc='lower right')\nplt.show()\nplt.plot(hist.history['loss'],c='b',label='Training')\nplt.plot(hist.history['val_loss'],c='r',label='Validation')\nplt.legend(loc='upper right')\nplt.show()\n\"\"\"\n# Check For Your Own Data\n\"\"\"\ndef predict(s):\n    X_tes=[]\n    X_tes.append(s)\n    X_test=tokenizer.texts_to_sequences(X_tes)\n    X_test_padded=pad_sequences(X_test,maxlen=175,padding='post',truncating='post')\n    sent=int(model.predict_classes(X_test_padded))\n    print(\"The Predicted Sentiment is \",mp[sent])\npol=\"The article is good but its not great moreover i would say you have done a decent job\"\npredict(pol)\nlop=\"You have done a stupid mistake which made you lose all the progress you made\"\npredict(lop)\ncom=\"It aint hard work but its honest work\"\npredict(com)\nppp=\"Lets Find out what this is going to be classified as\"\npredict(ppp)","meta":"{'source': 'AI4Code', 'id': '9a1ea1e64e4c1d'}"}
{"id":"109406","text":"\"\"\"\n## About Features\n\nAll attributes are numeric variables and they are listed bellow:\n\n- squareMeters\n- numberOfRooms\n- hasYard\n- hasPool\n- floors : number of floors\n- cityCode : zip code\n- cityPartRange : the higher the range, the more exclusive the neighbourhood is\n- numPrevOwners : number of prevoious owners\n- made : year\n- isNewBuilt\n- hasStormProtector\n- basement : basement square meters\n- attic : attic square meteres\n- garage : garage size\n- hasStorageRoom\n- hasGuestRoom : number of guest rooms\n- price : price of a house\n- category : Luxury or Basic\n\n**Our task is to predict the 'category'**\n\"\"\"\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\ndf = pd.read_csv('..\/input\/paris-housing-classification\/ParisHousingClass.csv')\ndf.head()\ndf.shape\ndf.info()\ndf.isnull().sum()\n\"\"\"\nGood! We have no null values.\n\"\"\"\ndf.describe()\n\"\"\"\n# EDA\n\"\"\"\nbackground_color = '#F8EDF4'\n\"\"\"\n### Countplot of Target Feature (Category)\n\"\"\"\nfig = plt.figure(figsize=(14, 6))\ngs = fig.add_gridspec(1, 2)\ngs.update(wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\n\naxes = [ax0, ax1]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, 'Countplot of Category\\n____________',\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontfamily='serif', fontweight='bold')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n\n# Graph\nsns.countplot(x='category', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\ndf['category'].value_counts()\n\"\"\"\n### Countplots of Categorical Features\n\"\"\"\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'hasYard'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='hasYard', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='hasYard', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['hasYard'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'hasPool'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='hasPool', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='hasPool', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['hasPool'], margins=True).style.background_gradient(cmap='Wistia')\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'cityPartRange'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='cityPartRange', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='cityPartRange', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['cityPartRange'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'numPrevOwners'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='numPrevOwners', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='numPrevOwners', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['numPrevOwners'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'isNewBuilt'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='isNewBuilt', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='isNewBuilt', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['isNewBuilt'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'hasStormProtector'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='hasStormProtector', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='hasStormProtector', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['hasStormProtector'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'hasStorageRoom'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='hasStorageRoom', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='hasStorageRoom', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['hasStorageRoom'], margins=True).style.background_gradient(cmap=\"Wistia\")\nfig = plt.figure(figsize=(16, 5))\ngs = fig.add_gridspec(1, 3)\ngs.update(hspace=0.2, wspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\n\naxes = [ax0, ax1, ax2]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, \"Countplot of 'hasGuestRoom'\\n_________________\",\n        horizontalalignment='center',\n        verticalalignment='center',\n        fontsize=18, fontweight='bold', fontfamily='serif')\nax0.set_xticklabels([])\nax0.set_yticklabels([])\nax0.tick_params(left=False, bottom=False)\nax0.spines['bottom'].set_visible(False)\n\n# Graph1\nsns.countplot(x='hasGuestRoom', data=df, ax=ax1, palette='spring_r')\nax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax1.set_xlabel('')\nax1.set_ylabel('')\n\n# Graph2\nsns.countplot(x='hasGuestRoom', data=df, hue='category', ax=ax2, palette='spring_r')\nax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\nax2.set_xlabel('')\nax2.set_ylabel('')\n\n\n# Settings\nfor ax in axes:\n    ax.set_facecolor(background_color)\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\npd.crosstab(df['category'], df['hasGuestRoom'], margins=True).style.background_gradient(cmap=\"Wistia\")\n\"\"\"\nWhat I can see from the graphs:\n\n\n- All of the categorical features are quite balanced\n- Every 'Luxury' house has Yard and Pool.\n\"\"\"\n\"\"\"\n### Distributions of Continuous Features\n\"\"\"\ncont_features = ['squareMeters', 'numberOfRooms', 'floors', 'cityPartRange', 'numPrevOwners', 'made', 'basement', 'attic', 'garage', 'hasGuestRoom', 'price']\n# I plotted them in two cells because the code becomes TOO LONG\n\nfig = plt.figure(figsize=(18, 25))\ngs = fig.add_gridspec(4, 3)\ngs.update(wspace=0.3, hspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\nax3 = fig.add_subplot(gs[1, 0])\nax4 = fig.add_subplot(gs[1, 1])\nax5 = fig.add_subplot(gs[1, 2])\n\naxes = [ax0, ax1, ax2, ax3, ax4, ax5]\nfig.patch.set_facecolor(background_color)\n\n\n# Title\nax0.text(0.5, 0.5, 'Distribution of Continuous Features\\n by Category\\n ___________________\\n',\n        fontsize=18, fontfamily='serif', fontweight='bold',\n        horizontalalignment='center',\n        verticalalignment='center')\n \nax0.text(0.5, 0.3, 'Orange : Basic\\n Red : Luxury',\n        fontsize=14, fontfamily='serif', fontweight='bold',\n        horizontalalignment='center',\n        verticalalignment='center')\n\n\n# Graphs\nfor i, ax in enumerate(axes):\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\n        \n    ax.set_facecolor(background_color)\n    \n    if i == 0:\n        ax.set_xticklabels([])\n        ax.set_yticklabels([])\n        ax.tick_params(left=False, bottom=False)\n        ax.spines[['bottom']].set_visible(False)\n    else:\n        ax.set_title(cont_features[i-1], fontsize=14, fontfamily='serif', fontweight='bold')\n        ax.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\n    \n        sns.kdeplot(x=cont_features[i-1], data=df, ax=ax, hue='category', \n                    palette='spring_r', fill=True, legend=False)\n        ax.set_xlabel('')\n        ax.set_ylabel('')\nfig = plt.figure(figsize=(18, 25))\ngs = fig.add_gridspec(4, 3)\ngs.update(wspace=0.3, hspace=0.3)\n\nax0 = fig.add_subplot(gs[0, 0])\nax1 = fig.add_subplot(gs[0, 1])\nax2 = fig.add_subplot(gs[0, 2])\nax3 = fig.add_subplot(gs[1, 0])\nax4 = fig.add_subplot(gs[1, 1])\nax5 = fig.add_subplot(gs[1, 2])\n\naxes = [ax0, ax1, ax2, ax3, ax4, ax5]\nfig.patch.set_facecolor(background_color)\n\n\n# Graphs\nfor i, ax in enumerate(axes):\n    for s in ['top', 'right', 'left']:\n        ax.spines[s].set_visible(False)\n        \n    ax.set_facecolor(background_color)\n    ax.set_title(cont_features[i+5], fontsize=14, fontfamily='serif', fontweight='bold')\n    ax.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5))\n    \n    sns.kdeplot(x=cont_features[i+5], data=df, ax=ax, hue='category', \n                palette='spring_r', fill=True, legend=False)\n    ax.set_xlabel('')\n    ax.set_ylabel('')\n\"\"\"\nI thought the distribution of 'Basic' and 'Luxury' would be quite different. But that was wrong..\n\"\"\"\n\"\"\"\n# Preprocessing\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\n\nlabel = LabelEncoder()\ndf['category'] = label.fit_transform(df['category'])\n\"\"\"\n# Modeling\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix\n\nX = df.drop('category', axis=1)\ny = df['category']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\nfrom sklearn.linear_model import LogisticRegression\n\nlogreg = LogisticRegression(C=0.3, solver='newton-cg')\nlogreg.fit(X_train, y_train)\ny_pred = logreg.predict(X_test)\n\nprint('Accuracy Score of Logistic Regression : ', accuracy_score(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\nfrom sklearn.svm import SVC\n\nsvc = SVC(C=0.2, kernel='sigmoid')\nsvc.fit(X_train, y_train)\ny_pred = svc.predict(X_test)\n\nprint('Accuracy Score of Suppor Vector Machine : ', accuracy_score(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\nfrom sklearn.ensemble import RandomForestClassifier\n\nrf = RandomForestClassifier()\nrf.fit(X_train, y_train)\ny_pred = rf.predict(X_test)\n\nprint('Accuracy Score of Random Forest : ', accuracy_score(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\nfrom sklearn.tree import DecisionTreeClassifier\n\ndt = DecisionTreeClassifier()\ndt.fit(X_train, y_train)\ny_pred = dt.predict(X_test)\n\nprint('Accuracy Score of Decision Tree : ', accuracy_score(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\n\"\"\"\nI have no idea why some models got perfect 1.0 accuracy score..\n\"\"\"\n\"\"\"\n## Pleas Upvote if you like my notebook!\n## Thank you!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c90f498c829a87'}"}
{"id":"96444","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n# Resources:\n\nhttps:\/\/www.kaggle.com\/xhlulu\/aptos-2019-densenet-keras-starter\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nimport json\nimport math\nimport os\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm\n\n%matplotlib inline\n\n# Set random seed for reproducibility.\nnp.random.seed(2019)\ntf.set_random_seed(2019)\n\"\"\"\n# Target & ID Loading\n\"\"\"\ntrain_df = pd.read_csv('..\/input\/aptos2019-blindness-detection\/train.csv')\ntest_df = pd.read_csv('..\/input\/aptos2019-blindness-detection\/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head()\n\"\"\"\n# Image Loading & Pre-processing\n\"\"\"\ndef preprocess_image(image_path, desired_size=224):\n    im = Image.open(image_path)\n    im = im.resize((desired_size, )*2, resample=Image.LANCZOS)\n    \n    return im\n# get the number of training images from the target\\id dataset\nN = train_df.shape[0]\n# create an empty matrix for storing the images\nx_train = np.empty((N, 224, 224, 3), dtype=np.uint8)\n\n# loop through the images from the images ids from the target\\id dataset\n# then grab the cooresponding image from disk, pre-process, and store in matrix in memory\nfor i, image_id in enumerate(tqdm(train_df['id_code'])):\n    x_train[i, :, :, :] = preprocess_image(\n        f'..\/input\/aptos2019-blindness-detection\/train_images\/{image_id}.png'\n    )\n# do the same thing as the last cell but on the test\\holdout set\n\nN = test_df.shape[0]\nx_test = np.empty((N, 224, 224, 3), dtype=np.uint8)\n\nfor i, image_id in enumerate(tqdm(test_df['id_code'])):\n    x_test[i, :, :, :] = preprocess_image(\n        f'..\/input\/aptos2019-blindness-detection\/test_images\/{image_id}.png'\n    )\n# pre-processing the target (i.e. one-hot encoding the target)\ny_train = pd.get_dummies(train_df['diagnosis']).values\n\nprint(x_train.shape)\nprint(y_train.shape)\nprint(x_test.shape)\n# Further target pre-processing\n\n# Instead of predicting a single label, we will change our target to be a multilabel problem; \n# i.e., if the target is a certain class, then it encompasses all the classes before it. \n# E.g. encoding a class 4 retinopathy would usually be [0, 0, 0, 1], \n# but in our case we will predict [1, 1, 1, 1]. For more details, \n# please check out Lex's kernel.\n\ny_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\ny_train_multi[:, 4] = y_train[:, 4]\n\nfor i in range(3, -1, -1):\n    y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\nprint(\"Original y_train:\", y_train.sum(axis=0))\nprint(\"Multilabel version:\", y_train_multi.sum(axis=0))\n\"\"\"\n# Train & Validation Split\n\"\"\"\nx_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train_multi, \n    test_size=0.50, \n    random_state=2019\n)\n\"\"\"\n# Create Image Augmentation Generator\n\"\"\"\nBATCH_SIZE = 13\n\ndef create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.15,  # set range for random zoom\n        # set mode for filling points outside the input boundaries\n        fill_mode='constant',\n        cval=0.,  # value used for fill_mode = \"constant\"\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=True,  # randomly flip images\n    )\n\n# Using original generator\ndata_generator = create_datagen().flow(x_train, y_train, batch_size=BATCH_SIZE, seed=2019)\n\"\"\"\n# Create Model\n\"\"\"\ndensenet = DenseNet121(\n    weights='..\/input\/densenet-keras\/DenseNet-BC-121-32-no-top.h5',\n    include_top=False,\n    input_shape=(224,224,3)\n)\ndef build_model():\n    model = Sequential()\n    model.add(densenet)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dropout(0.80))\n    model.add(layers.Dense(5, activation='sigmoid'))\n    \n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(lr=0.00010509613402110064),\n        metrics=['accuracy']\n    )\n    \n    return model\nmodel = build_model()\nmodel.summary()\n\"\"\"\n# Train Model\n\"\"\"\nclass Metrics(Callback):\n    def on_train_begin(self, logs={}):\n        self.val_kappas = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_val = y_val.sum(axis=1) - 1\n        \n        y_pred = self.model.predict(X_val) > 0.5\n        y_pred = y_pred.astype(int).sum(axis=1) - 1\n\n        _val_kappa = cohen_kappa_score(\n            y_val,\n            y_pred, \n            weights='quadratic'\n        )\n\n        self.val_kappas.append(_val_kappa)\n\n        print(f\"val_kappa: {_val_kappa:.4f}\")\n        \n        if _val_kappa == max(self.val_kappas):\n            print(\"Validation Kappa has improved. Saving model.\")\n            self.model.save('model.h5')\n\n        return\nkappa_metrics = Metrics()\n\n#history = model.fit_generator(\n#    data_generator,\n#    steps_per_epoch=x_train.shape[0] \/ BATCH_SIZE,\n#    epochs=17,\n#    validation_data=(x_val, y_val),\n#    callbacks=[kappa_metrics]\n#)\n\nhistory = model.fit_generator(\n    data_generator,\n    steps_per_epoch=x_train.shape[0] \/ BATCH_SIZE,\n    epochs=15,\n    validation_data=(x_val, y_val)\n)\n\"\"\"\n# Training Plots\n\"\"\"\nwith open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['acc', 'val_acc']].plot()\n#plt.plot(kappa_metrics.val_kappas)\n\"\"\"\n# Submission\n\"\"\"\ny_test = model.predict(x_test)\ny_test\ny_test = y_test > 0.37757874193797547\ny_test\ny_test.astype(int).sum(axis=1)\ny_test.astype(int).sum(axis=1) - 1\ny_test = y_test.astype(int).sum(axis=1) - 1\ny_test\ntest_df['diagnosis'] = y_test\ntest_df.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': 'b126fddfe3895b'}"}
{"id":"41261","text":"\"\"\"\n# Intro\n\"\"\"\n\"\"\"\n**Introduction On September 27 1994 the ferry Estonia set sail on a night voyage across the Baltic Sea from the port of Tallin in Estonia to Stockholm. She departed at 19.00 carrying 989 passengers and crew, as well as vehicles, and was due to dock at 09.30 the following morning, Tragically, the Estonia never arrived.**\n\n\n\"\"\"\n#importing libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \n%matplotlib inline\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n\nimport os\nprint(os.listdir(\"..\/input\"))\ndata = pd.read_csv(\"..\/input\/passenger-list-for-the-estonia-ferry-disaster\/estonia-passenger-list.csv\")\ndata.head()\n\"\"\"\n# Visualize the data\n\"\"\"\nsns.set_style('whitegrid')\nplt.rcParams['font.size'] = 14\nplt.rcParams['figure.figsize'] = (9, 5)\nplt.rcParams['figure.facecolor'] = '#00000000'\n\nf, axes = plt.subplots(1,1)\ng1 = sns.histplot(data[\"Age\"], color=\"red\",ax = axes,kde=True)\nplt.title(\"Distribution of age\");\nsns.violinplot(x=\"Survived\",y=\"Age\",data=data);\n\"\"\"\nAs we can see from the plot, the median age for those who survived is lower, and there also seems to be smaller variation in these ages.\n\"\"\"\n# is the chance of survival different for different countries of origin?\ndata.groupby(\"Country\")[\"Survived\"].mean().plot(kind=\"bar\");\nplotp=data.groupby(\"Survived\")[\"Survived\"].count()\nplotp.plot.pie(autopct=\"%.1f%%\");\n\"\"\"\nThe pie plot not only shows the magnitute of the disaster, it also hints us that the data are not balanced and it may cause problems to our model.\n\"\"\"\n\"\"\"\n# Pre Processing\n\"\"\"\ndata = data[['Sex','Age','Category', 'Survived',\"Country\"]]\n#we remove the name collumns since they hold no value for the model\nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder=LabelEncoder()\ndata.Category=labelencoder.fit_transform(data[\"Category\"])\ndata.Sex=labelencoder.fit_transform(data[\"Sex\"])\nprint(data)\n# Female=0 male=1, Crew=0, passenger=1\n#since the variable Country is not binary we need to make dummies\ndata = pd.get_dummies(data,drop_first=True)\ndata.head()\ndata.isna().sum()\n#fortunatly there are no missing values\n\"\"\"\n# train_test_split\n\"\"\"\ny = data['Survived']\nX = data.drop(columns=['Survived'])\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=6)\n\"\"\"\n# Model\n\"\"\"\n\"\"\"\nWe chose a Decision Tree Classifier for our model\n\n\n\"\"\"\n# Setup the parameters and distributions to sample from: param_dist\nparam_dist = {\"min_samples_leaf\": range(1, 9),\n              \"criterion\": [\"gini\", \"entropy\"]}\n\n# Instantiate a Decision Tree classifier: tree\ntree = DecisionTreeClassifier()\n\ntree_cv = GridSearchCV(tree, param_dist, cv=5)\n\n# Fit it to the data\ntree_cv.fit(X_train, y_train)\n\n# Print the tuned parameters and score\nprint(\"Tuned Decision Tree Parameters: {}\".format(tree_cv.best_params_))\nprint(\"Best score is {}\".format(tree_cv.best_score_))\n# Predict the labels of the test data: y_pred\ny_pred = tree_cv.predict(X_test)\n\n# Generate the confusion matrix \ncm0=confusion_matrix(y_test, y_pred)\nprint(classification_report(y_test, y_pred))\nf, ax = plt.subplots(figsize=(5,5))\nsns.heatmap(cm0, annot=True, linewidth=0.7, linecolor='cyan', fmt='g', ax=ax, cmap=\"BuPu\")\nplt.title('Confusion Matrix')\nplt.xlabel('Y predict')\nplt.ylabel('Y test')\nplt.show()\n\"\"\"\n**As we saw in the vizualization stage our data suffer from inbalance. As such our model can not work properly because even though we have a high score, recall for the class Survived=1 is 0,07. In order to solve this, we use oversampling.**\n\"\"\"\n\"\"\"\n# Oversampling and re-fit\n\"\"\"\n#Import the SMOTE-NC\nfrom imblearn.over_sampling import SMOTENC\n#Create the oversampler. For SMOTE-NC we need to pinpoint the column position where is the categorical features are.\nsmotenc = SMOTENC([0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],random_state = 101)\n\nX_oversample, y_oversample = smotenc.fit_resample(X_train, y_train)\n# Re-Fit it to the oversampled data\ntree_cv.fit(X_oversample, y_oversample)\n\n\nprint(\"Tuned Decision Tree Parameters: {}\".format(tree_cv.best_params_))\nprint(\"Best score is {}\".format(tree_cv.best_score_))\nmodel = tree_cv.best_estimator_\n\n# Predict the labels of the test data: y_pred\ny_pred = model.predict(X_test)\n\n# Generate the confusion matrix \ncm=confusion_matrix(y_test, y_pred)\n\nprint(classification_report(y_test, y_pred))\nf, ax = plt.subplots(figsize=(5,5))\nsns.heatmap(cm, annot=True, linewidth=0.7, linecolor='cyan', fmt='g', ax=ax, cmap=\"BuPu\")\nplt.title('Confusion Matrix')\nplt.xlabel('Y predict')\nplt.ylabel('Y test')\nplt.show()\n\"\"\"\nAs we can see the oversampling worked. Our model is now better at predicting the class Survived=1. unfortunately recall for the first class, slightly dropped.\n\"\"\"\n\"\"\"\n# Metrics\n\"\"\"\nfrom sklearn.metrics import roc_curve\n\n# Compute predicted probabilities: y_pred_prob\ny_pred_prob = model.predict_proba(X_test)[:,1]\n\n# Generate ROC curve values: fpr, tpr, thresholds\nfpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)\n\n# Plot ROC curve\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot(fpr, tpr)\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nplt.show()\n\"\"\"\nCompairing the models with and without oversampling\n\n\n\"\"\"\nfig = plt.figure(figsize=(15,15))\nax1 = fig.add_subplot(2, 2, 1) \nax1.set_title('Decision tree no oversampling') \nax2 = fig.add_subplot(2, 2, 2) \nax2.set_title('Decision tree with oversampling')\n\n\nsns.heatmap(cm0, annot=True, linewidth=0.7, linecolor='red',cmap=\"BuPu\" ,fmt='g', ax=ax1)\nsns.heatmap(cm, annot=True, linewidth=0.7, linecolor='red',cmap=\"BuPu\" ,fmt='g', ax=ax2)  \nplt.show()\nmodel.feature_importances_\ndataf=data.drop([\"Survived\"], axis=1)\ndef plot_feature_importance(importance,names,model_type):\n    feature_importance = np.array(importance)\n    feature_names = np.array(names)\n\n    data={'feature_names':feature_names,'feature_importance':feature_importance}\n    fi_df = pd.DataFrame(data)\n\n    fi_df.sort_values(by=['feature_importance'], ascending=False,inplace=True)\n\n    plt.figure(figsize=(10,8))\n\n    sns.barplot(x=fi_df['feature_importance'], y=fi_df['feature_names'])\n\n    plt.title(model_type + 'FEATURE IMPORTANCE')\n    plt.xlabel('FEATURE IMPORTANCE')\n    plt.ylabel('FEATURE NAMES')\n\n\n    \nplot_feature_importance(model.feature_importances_,dataf.columns,'Decision Tree ')\n\"\"\"\nAs we can see, for most countries, the origin of the passenger plays no role in the prediction.\n\n\n\"\"\"\n\"\"\"\nWe will remove the unnecessary features and re fit the model\n\n\n\"\"\"\n\"\"\"\n# Final re-fit\n\n\"\"\"\ny = data['Survived']\nX = data[['Age',\"Sex\",\"Category\",\"Country_Sweden\",\"Country_Latvia\",\"Country_Russia\",\"Country_Estonia\"]]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=6)\nsmotenc = SMOTENC([0,2,3,4,5,6],random_state = 101)\n\nX_oversample, y_oversample = smotenc.fit_resample(X_train, y_train)\ntree_cv.fit(X_oversample, y_oversample)\n\n\nprint(\"Tuned Decision Tree Parameters: {}\".format(tree_cv.best_params_))\nprint(\"Best score is {}\".format(tree_cv.best_score_))\n# Predict the labels of the test data: y_pred\ny_pred = tree_cv.predict(X_test)\n\n# Generate the confusion matrix \ncm3=confusion_matrix(y_test, y_pred)\n\nprint(classification_report(y_test, y_pred))\n\"\"\"\n# Final comparison of the 3 models\n\"\"\"\nfig = plt.figure(figsize=(15,15))\nax1 = fig.add_subplot(3, 3, 1) \nax1.set_title('Decision tree no oversampling') \nax2 = fig.add_subplot(3, 3, 2) \nax2.set_title('Decision tree with oversampling')\nax3 = fig.add_subplot(3, 3, 3) \nax3.set_title('Decision tree final')\n\nsns.heatmap(cm0, annot=True, linewidth=0.7, linecolor='red',cmap=\"BuPu\" ,fmt='g', ax=ax1)\nsns.heatmap(cm, annot=True, linewidth=0.7, linecolor='red',cmap=\"BuPu\" ,fmt='g', ax=ax2)  \nsns.heatmap(cm3, annot=True, linewidth=0.7, linecolor='red',cmap=\"BuPu\" ,fmt='g', ax=ax3)  \nplt.show()\n\"\"\"\n* In the end, the model that we will choose depends on its future usage and the cost of the false positives for each class.\n* **All in all i would say that the last model is the better of the 3 since it has better average recall and f1-score.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4c078c1db9d38f'}"}
{"id":"114071","text":"# 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)\nimport matplotlib.pyplot as plt\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\n\n\"\"\"\n# **Set Display Options**\nTo view complete text of Questions asked and Analysis\n\"\"\"\npd.set_option('display.max_colwidth', 250)\npd.set_option('display.max_columns', 500)\n\"\"\"\n# **Define Functions**\nThis whole notebook depends on the three functions defined below\n1. rinse(df): returns most frequent answers to each question in dataframe\n2. group_squeeze(df): returns most frequent answers per most frequent demographics in dataframe\n3. joint_squeeze(df): returns most frequent answer pairs in dataframe\n\"\"\"\ndef rinse(df):\n    unique_df = pd.DataFrame()\n    unique_dfcol = pd.DataFrame()\n    unique_dfcol['Question'] = list('x')\n    unique_dfcol['Answer'] = 0\n    unique_dfcol['Population'] = 0\n    for col in df.columns:\n        unique_dfcol['Question'] = col\n        unique_dfcol['Answer'] = df[col].mode(dropna=True)\n        unique_dfcol['Population'] = df[col].value_counts().max()\n        unique_df = unique_df.append(unique_dfcol)\n    \n    unique_df = (unique_df.reset_index()).drop('index', axis=1)\n    unique_df['Percentage(%)'] = ((unique_df['Population'] \/ len(df)) * 100).round(2)\n    unique_df = unique_df.sort_values('Percentage(%)', ascending=False)\n    #unique_df = unique_df[unique_df['Percentage(%)']>10]\n    unique_df = ((unique_df.dropna()).reset_index()).drop('index', axis=1)\n    return unique_df\ndef group_squeeze(df):\n    unique_df = pd.DataFrame()\n    rinse_df = rinse(df)\n    for feat in rinse_df['Question'].unique():\n        ans = (rinse_df[(rinse_df['Question']==feat)]).iloc[0,1]\n        ans_df = df[df[feat]==ans]\n        ans_df = ans_df.drop(feat, axis= 1)\n        unique_dfcol = rinse(ans_df)\n        unique_dfcol['Question_Group'] = feat\n        unique_dfcol['Answered_Group'] = ans\n        unique_df = unique_df.append(unique_dfcol)\n    unique_df = unique_df.sort_values('Population', ascending=False)\n    unique_df = ((unique_df.dropna()).reset_index()).drop('index', axis=1)\n    cols = list(unique_df.columns)\n    cols = cols[-2:] + cols[:-2]\n    unique_df = unique_df[cols]\n    return unique_df\ndef joint_squeeze(df):\n    unique_df = pd.DataFrame()\n    rinse_df = rinse(df)\n    for feat in rinse_df['Question'].unique():\n        ans = (rinse_df[(rinse_df['Question']==feat)]).iloc[0,1]\n        ans_df = df[df[feat]==ans]\n        ans_df = ans_df.drop(feat, axis= 1)\n        unique_dfcol = rinse(ans_df)\n        unique_dfcol['Other_Question'] = feat\n        unique_dfcol['Other_Answer'] = ans\n        unique_df = unique_df.append(unique_dfcol)\n    unique_df['Percentage(%)'] = ((unique_df['Population'] \/ len(df)) * 100).round(2)\n    unique_df = unique_df.sort_values('Percentage(%)', ascending=False)\n    unique_df = unique_df.iloc[::2]\n    unique_df = ((unique_df.dropna()).reset_index()).drop('index', axis=1)\n    cols = list(unique_df.columns)\n    cols = cols[-2:] + cols[:-2]\n    unique_df = unique_df[cols]\n    return unique_df\n\"\"\"\n# **Load Dataset**\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/kaggle-survey-2021\/kaggle_survey_2021_responses.csv', header=1)\ndf.head(2)\ndf.info()\nlen(df)\n\"\"\"\n# **General Stats**\n\"\"\"\nGeneral_Stats = rinse(df)\nGeneral_Stats.T\n\"\"\"\n**General Stats\/Introduction**\n* 84.16% of Data Scientist use python on a regular basis\n* 79.31% of Data Scientist are Men\n* 77.82% of Data Scientist recommend aspiring data scientists to learn python\n* 67.74% of Data Scientist use Matplotlib for data visualization on a regular basis\n* Amazingly, 63.36% of Data Scientist Never used TPU (Tensor Processing Unit)\n* 62.5% of Data Scientist use Jupyter Notebook (IDE) on a regular basis\n* 62.49% of Data Scientists make use of Laptops\n* 53.85% of Data Scientists use Scikit-learn framework on a regular basis\n* 53.33% of Data Scientists use Linear or Logistic Regression algorithm on a regular basis\n* 50.95% of Data Scientist use no specialized hardware \n\n\"\"\"\n\"\"\"\n# **Compared Stats**\n\"\"\"\nCompare_Stat = rinse(df)\nCompare_Stat['Q'] = Compare_Stat.Question.str[:45]\nCompare_Stat['Multiple'] = (Compare_Stat.groupby('Q')['Q'].transform('count')>1).astype('int')\nCompare_Stat = (Compare_Stat[Compare_Stat.Multiple==0]).iloc[:,:5]\nCompare_Stat = Compare_Stat.sort_values(['Q','Population'], ascending=False)\nCompare_Stat.set_index('Q', inplace=True)\nCompare_Stat = df[list(Compare_Stat.Question.values)]\n\nfor col in Compare_Stat.columns:\n    Compare_Stat[col].value_counts().head(10).plot.bar(color=list('rgbkymc'))\n    plt.title(col)\n    plt.xlabel('answers')\n    plt.ylabel('population')\n    plt.show()\n\"\"\"\n* Most data scientists use laptops, followed by personal computers\n* Majority of the data scientists are students and are aged between 25-29years\n* Majority of the data scientist have a Masters degree or will attain it in the next 2years\n* Most data scientists do not spend money on cloud computing services\n* More employers are exploring ML methods which will someday may be put into production\n* A larger section employers are in computer\/tech industry\n* More of the data scientists companies have less than 50 employees\n* A higher portion of the data scientists use statistical software for analysis at wrok\n* Most of the data scientists earn less than $1000 annually\n* A larger section of the data scientists reside in India\n* A larger section of the data scientists have between 1-3 years experience\n* 1-2 people are mostly responsible for data science workloads at places where data scientists work\n\"\"\"\nCompare_Stats = rinse(df)\nCompare_Stats['Q'] = Compare_Stats.Question.str[:45]\nCompare_Stats['Multiple'] = (Compare_Stats.groupby('Q')['Q'].transform('count')>1).astype('int')\nCompare_Stats = (Compare_Stats[Compare_Stats.Multiple==1]).iloc[:,:5]\nCompare_Stats = Compare_Stats.sort_values(['Q','Population'], ascending=False)\nCompare_Stats.set_index('Q', inplace=True)\nCompare_Stats.T\n\"\"\"\n**Media**\n* Kaggle(notebooks, forums, etc) - 43.79% is the most common favorite media source for data scientists, followed by Youtube(Kaggle YouTubem Cloud AI Adventures, etc) - 40%, then Blogs(Towards Data Science, Analytics Vidhya,etc) - 30.71%\n\n**Cloud Platforms**\n* 14.33% of Data scientist use Amazon web services (AWS) cloud platform on a regular basis as against 12.1% who use Google Cloud Platform (GCP)\n* 28.81% of Data Scientists hope to become more familiar with Google Cloud Platform(GCP) which is almost as many as 28.85% of data scientists who hope to become more familiar with Amazon Web Services(AWS) \n\n\"\"\"\n\"\"\"\n**Specialized Hardware**\n* Top most frequently used specialized hardware amongst data scientists include NVIDIA GPUs(30.94%), followed by Google Cloud TPUs(13.29), then AWS Inferentia Chips(1.6%)\n\n**Automated Machine Learning tools**\n* Google Cloud AutoML(2.89%) is the most frequently used automated ML tool, followed by Azure Automated Machine Learning(1.73%), Amazon Sagemaker Autopilot(1.45%), Databricks AutoML(1.24%), H2O Driverless AI(1.22%), and DataRobot AutoML(1.04%)\n* More data scientists hope to become more familiar with Google Cloud AutoML(18.55%) which is more than fifty-percent the number of data scientists that hope to become more familiar with Azure Automated Machine Learning(12.14%)\n\"\"\"\n\"\"\"\n**IDE & Frameworks**\n* 83.63%(62.5% + 21.13%) of data scientists use Jupyter Notebook and other jupyter IDE\n* 38.66% of data scientists use Visual Studio Code(VSCode) IDE, 28.75% use Pycharm while 18.37% use RStudio\n* The most frequently used machine learning frameworks amongst data scientists include:\n1. Scikit-learn - 53.85%\n2. TensorFlow - 36%\n3. Keras - 30.77%\n4. PyTorch - 23.44%\n5. Xgboost-23%, LightGBM-10.15%, CatBoost-5.82%, Huggingface-4.32%\n\"\"\"\n\"\"\"\n**Hosted notebook products**\n* Colab Notebooks(37.7%) is the most regularly used hosted notebook product, followed closely by Kaggle Notebooks(36.6%)\n\"\"\"\n\"\"\"\n**NLP (Natural Language Processing)**\n* Commonly used NLP methods include - Word embeddings\/vectors(10.18%), Transformer language models(9%), Encoder-decoder model(7.79%)\n\"\"\"\n\"\"\"\n# **Grouped Stats**\n\"\"\"\nGrouped_Stats = group_squeeze(df)\nGrouped_Stats = Grouped_Stats.T\nGrouped_Stats\n\"\"\"\n**Computing Devices**\n* 65.43% of Matplotlib users mostly make use of Laptops for computing\n* 70.17% of Laptop users never made use of tensor processing units(TPU)\n* 69.21% of data scientists that have never used TPU, make use of Laptops for computing\n* 84.1% of data scientists that don't use specialized hardwares, make use of Python programming language\n* Meanwhile, 50.91% of Python users do not make use of specialized hardware \n\"\"\"\n\"\"\"\n**Programming Language & Libraries**\n* 84.36% of data scientists who use Python on a regular basis, also recommend it to aspiring data scientists. 91.24% of data scientists who recommend python programming language to aspiring data scientist, also use it on a regular basis.\n* 80.43% of Python users are Men. 85.36% of male data scientists use python on a regular basis\n* 77.15% of python users make use of Matplotlib, 55.99 of python users make use of Seaborn\n* 67.25% of Matplotlib users use Seaborn. 94.02% of Seaborn users make use of Matplotlib\n* 67.2% of Matplotlib users make use of Linear or Logistic Regression algorithms\n* 50.78% of Python users make use of Decision Trees or Random Forests on a regular basis\n* 79% of Scikit-learn users make use of Linear or Logistic Regression algorithms\n\n\"\"\"\n\"\"\"\n# **Joint Stats**\n\"\"\"\nJoint_Stats = joint_squeeze(df)\nJoint_Stats = Joint_Stats.T\nJoint_Stats\n\"\"\"\n* 71% of data scientists use python and recommend it to aspiring data scientists\n* 36.99% of data scientists use both python and SQL programming languages on a regular basis\n* 32.28% of data scientists use VSCode IDE and recommend aspiring data scientists to learn python programming language first\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd1a97a496546b6'}"}
{"id":"103379","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.offline as pyo\nimport plotly.figure_factory as ff\nfrom plotly import tools\nfrom plotly.subplots import make_subplots\nfrom plotly.offline import iplot\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier\nfrom sklearn.svm import SVC\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import RocCurveDisplay\ndf=pd.read_csv('\/kaggle\/input\/health-care-data-set-on-heart-attack-possibility\/heart.csv')\ndf.head()\ndf2=df.copy()\ndf.info()\ntrain_dict=pd.DataFrame(df.dtypes,columns=['Data types'])\ntrain_dict['null']=df.isnull().sum()\ntrain_dict['unique vals']=df.nunique()\ntrain_dict['count']=df.count()\ntrain_dict\ndf.columns\ndf.describe()\n\"\"\"\nfeature distribution\n\"\"\"\ndf.hist(bins=50,figsize=((20,15)))\n\"\"\"\nEDA\n\"\"\"\nfig = px.histogram(data_frame = df,\n             x = \"sex\",\n             color=\"target\", title=\"<b>age vs target<\/b>\",   \n)\nfig.show()\nfig = px.histogram(data_frame = df,\n             x = \"fbs\",\n             color=\"target\", title=\"<b>fbs vs target<\/b>\",   \n)\nfig.show()\nfig = px.histogram(data_frame = df,\n             x = \"chol\",\n             color=\"target\", title=\"<b>chol vs target<\/b>\",   \n)\nfig.show()\nfig = px.histogram(data_frame = df,\n             x = \"ca\",\n             color=\"target\", title=\"<b>ca vs target<\/b>\",   \n)\nfig.show()\nfig = px.histogram(data_frame = df,\n             x = \"age\",\n             color=\"sex\", title=\"<b>age vs sex<\/b>\",   \n)\nfig.show()\ntrain_dict\ndf.shape\ncorrMatrix = df.corr()\nsns.heatmap(corrMatrix, annot=True)\nplt.show()\n\"\"\"\nPreprocessing\n\"\"\"\ndf.head()\ny=df.target\ndf.drop('target',1,inplace=True)\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(df,y,test_size=0.3)\nmodel = [DecisionTreeClassifier(),RandomForestClassifier(), ExtraTreesClassifier() , XGBClassifier(),GaussianNB(),KNeighborsClassifier()]\ntrainAccuracy = list()\ntestAccuracy = list()\nkfold = KFold(n_splits=10, random_state=7, shuffle=True)\n\nfor mdl in model:\n    trainResult = cross_val_score(mdl, X_train, y_train, scoring='accuracy', cv=kfold)\n    trainAccuracy.append(trainResult.mean())\n    mdl.fit(X_train, y_train)\n    y_pred = mdl.predict(X_test)\n    testResult = metrics.accuracy_score(y_test, y_pred)\n    testAccuracy.append(testResult)\nprint('The comparision\\n')\nmodelScore = pd.DataFrame({'Model' : model, 'Train_Accuracy' : trainAccuracy, 'Test_Accuracy' : testAccuracy})\nmodelScore\nprint('ExtraTreeClassifier\\n')\nmodel = ExtraTreesClassifier(n_estimators=200,max_depth=150)\nmodel.fit(X_train, y_train)\n\npred = model.predict(X_test)\nprint(metrics.classification_report(y_test,pred))\nsns.heatmap(confusion_matrix(y_test,pred), annot=True, fmt='d')\nplt.show()\n","meta":"{'source': 'AI4Code', 'id': 'bdf4360f459add'}"}
{"id":"5934","text":"\"\"\"\nIn this kernel I have applied transfer learning , I have used VGG16 pretrained model and designed the last FC layer manually which I have further connected to a softmax layer.\n\nUsing this I have acheived an acuracy of 94% with 4 epoch. Increasing the epochs might increase the efficiency further(you can try if you want!!)\n\nIn this kernal I have tried keeping a standard apporach so that the same code can be reused in other problems(ofcourse with minor tweeeks!!).\n\n\"\"\"\n\"\"\"\n# Import all required libraries\n\"\"\"\n%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom os import listdir, makedirs\nfrom os.path import join, exists, expanduser\nfrom tqdm import tqdm\nfrom sklearn.metrics import log_loss, accuracy_score\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.applications import xception\nfrom keras.applications import inception_v3\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\nfrom sklearn.linear_model import LogisticRegression\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Dropout , Lambda, Flatten\nfrom keras.optimizers import Adam ,RMSprop\nfrom sklearn.model_selection import train_test_split\nfrom keras import  backend as K\nfrom keras.preprocessing.image import ImageDataGenerator,load_img\nstart = dt.datetime.now()\n\"\"\"\n# Loading required data\n\"\"\"\nlabel=pd.read_csv(\"\/kaggle\/input\/dog-breed-identification\/labels.csv\")\nlabel\n\"\"\"\n# Selecting TOP 16\n\"\"\"\nlabel_df=pd.DataFrame(label['breed'].value_counts()).reset_index()\nlabel_df.columns=['breed_name','count']\nlabel_df=label_df.head(16)\nlabel_df\nlabel_df.sort_values(by=\"count\",ascending=False)\nlabel = label[label['breed'].isin(label_df['breed_name'])]\n\"\"\"\nAdding .jpg extension\n\"\"\"\n    \nlabel['id_ext']=label['id'].apply(lambda x:x+'.jpg')\nlabel=label.reset_index()\nlabel=label.drop(['index','id'],axis=1)\nlabel.head()\n\"\"\"\n# One hot coding of breeds\n\"\"\"\nlabel_onehot=pd.get_dummies(label,columns=['breed'],prefix=None)\nlabel_onehot\nlabel_onehot.columns\n\"\"\"\n# Renaming the columns\n\"\"\"\nlabel_onehot.columns = label_onehot.columns.str.replace(r'breed_', '')\n#label_onehot\nlabel_onehot=label_onehot.rename(columns={'id_ext':'id'})\nlabel_onehot\n\"\"\"\n# Checking a random sample\n\"\"\"\nimport random\nsample=random.choice(label_onehot['id'])\nsample\nimage=load_img(\"\/kaggle\/input\/dog-breed-identification\/train\/\"+sample)\nimage\n\"\"\"\n# Train and Test split\n\"\"\"\ntrain_df, validate_df = train_test_split(label_onehot, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()\n\n# validate_df = validate_df.sample(n=100).reset_index() # use for fast testing code purpose\n# train_df = train_df.sample(n=1800).reset_index() # use for fast testing code purpose\n\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\ntrain_df.shape,validate_df.shape\ntrain_df\n\"\"\"\n# VGG 16 pretrained model\n\"\"\"\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation,GlobalMaxPooling2D\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom keras.applications import VGG16\nfrom keras.models import Model\n\nimage_size = 224\ninput_shape = (image_size, image_size, 3)\n\nepochs = 4\nbatch_size = 16\n\npre_trained_model = VGG16(input_shape=input_shape, include_top=False, weights=\"imagenet\")\n    \nfor layer in pre_trained_model.layers[:15]:\n    layer.trainable = False\n\nfor layer in pre_trained_model.layers[15:]:\n    layer.trainable = True\n    \nlast_layer = pre_trained_model.get_layer('block5_pool')\nlast_output = last_layer.output\n    \n# Flatten the output layer to 1 dimension\nx = GlobalMaxPooling2D()(last_output)\n# Add a fully connected layer with 512 hidden units and ReLU activation\nx = Dense(512, activation='relu')(x)\n# Add a dropout rate of 0.5\nx = Dropout(0.5)(x)\n# Add a final sigmoid layer for classification\nx = layers.Dense(16, activation='softmax')(x)\n\nmodel = Model(pre_trained_model.input, x)\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),\n              metrics=['accuracy'])\n\nmodel.summary()\ntrain_df\ntrain_df.columns\n\"\"\"\n# Data Augmentation\n\"\"\"\n\"\"\"\nTraining Data\n\"\"\"\ntrain_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1.\/255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"\/kaggle\/input\/dog-breed-identification\/train\", \n    x_col='id',\n    y_col=['afghan_hound', 'airedale', 'basenji', 'beagle',\n       'bernese_mountain_dog', 'cairn', 'entlebucher', 'great_pyrenees',\n       'japanese_spaniel', 'leonberg', 'maltese_dog', 'pomeranian', 'samoyed',\n       'scottish_deerhound', 'shih-tzu', 'tibetan_terrier'],\n    class_mode='raw',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)\n\"\"\"\nValidation Data\n\"\"\"\nvalidation_datagen = ImageDataGenerator(rescale=1.\/255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"\/kaggle\/input\/dog-breed-identification\/train\", \n    x_col='id',\n    y_col=['afghan_hound', 'airedale', 'basenji', 'beagle',\n       'bernese_mountain_dog', 'cairn', 'entlebucher', 'great_pyrenees',\n       'japanese_spaniel', 'leonberg', 'maltese_dog', 'pomeranian', 'samoyed',\n       'scottish_deerhound', 'shih-tzu', 'tibetan_terrier'],\n    class_mode='raw',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)\n\"\"\"\n# Example of Data AUgmentation\n\"\"\"\nexample_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"\/kaggle\/input\/dog-breed-identification\/train\/\", \n    x_col='id',\n    y_col=['afghan_hound', 'airedale', 'basenji', 'beagle',\n       'bernese_mountain_dog', 'cairn', 'entlebucher', 'great_pyrenees',\n       'japanese_spaniel', 'leonberg', 'maltese_dog', 'pomeranian', 'samoyed',\n       'scottish_deerhound', 'shih-tzu', 'tibetan_terrier'],\n    class_mode='raw',\n)\nplt.figure(figsize=(12, 12))\nfor i in range(0, 9):\n    plt.subplot(3, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()\n\"\"\"\n# Fit the model, accuracy 94%\n\"\"\"\n# fine-tune the model\nhistory = model.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate\/\/batch_size,\n    steps_per_epoch=total_train\/\/batch_size)\nloss, accuracy = model.evaluate_generator(validation_generator, total_validate\/\/batch_size, workers=12)\nprint(\"Test: accuracy = %f  ;  loss = %f \" % (accuracy, loss))\nvalidate_df\ndef get_dog(row):\n    for i in validate_df.columns[2:]:\n        if row[i]==1:\n            return i        \nvalidate_df['breed']=validate_df.apply(get_dog,axis=1)\nvalidate_df\nvalidate_df=validate_df[['id','breed']]\nvalidate_df.shape\n\"\"\"\n# Checking output from validata data to check accuracy\n\"\"\"\nsample_test = validate_df.sample(n=9).reset_index()\n#print(sample_test)\nplt.figure(figsize=(12, 12))\nfor index, row in sample_test.iterrows():\n    filename = row['id']\n    print(filename)\n    category = row['breed']\n    img = load_img(\"\/kaggle\/input\/dog-breed-identification\/train\/\"+filename, target_size=(256, 256))\n    \n    plt.subplot(3, 3,index+1)\n    plt.imshow(img)\n    plt.xlabel('(' + \"{}\".format(category) + ')')\nplt.tight_layout()\nplt.show()\n\nend = dt.datetime.now()\nprint('Total time {} s.'.format((end - start).seconds))\n","meta":"{'source': 'AI4Code', 'id': '0b0398f6d242c8'}"}
{"id":"121747","text":"\"\"\"\n# Diabetes Health Prediction\n\"\"\"\n#import library\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nimport math\nfrom sklearn import metrics\n\"\"\"\n## Data Extraction\n\"\"\"\ndf = pd.read_csv('..\/input\/diabetes-health-indicators-dataset\/diabetes_binary_health_indicators_BRFSS2015.csv')\ndf.shape\ndf.head()\n#transform data\ndf['Diabetes_binary'] = df['Diabetes_binary'].astype('int')\ndf['HighBP'] = df['HighBP'].astype('int')\ndf['HighChol'] = df['HighChol'].astype('int')\ndf['CholCheck'] = df['CholCheck'].astype('int')\ndf['BMI'] = df['BMI'].astype('int')\ndf['Smoker'] = df['Smoker'].astype('int')\ndf['Stroke'] = df['Stroke'].astype('int')\ndf['HeartDiseaseorAttack'] = df['HeartDiseaseorAttack'].astype('int')\ndf['PhysActivity'] = df['PhysActivity'].astype('int')\ndf['Fruits'] = df['Fruits'].astype('int')\ndf['Veggies'] = df['Veggies'].astype('int')\n\ndf['HvyAlcoholConsump'] = df['HvyAlcoholConsump'].astype('int')\ndf['AnyHealthcare'] = df['AnyHealthcare'].astype('int')\ndf['NoDocbcCost'] = df['NoDocbcCost'].astype('int')\ndf['GenHlth'] = df['GenHlth'].astype('int')\ndf['MentHlth'] = df['MentHlth'].astype('int')\ndf['PhysHlth'] = df['PhysHlth'].astype('int')\ndf['DiffWalk'] = df['DiffWalk'].astype('int')\ndf['Sex'] = df['Sex'].astype('int')\ndf['Age'] = df['Age'].astype('int')\ndf['Education'] = df['Education'].astype('int')\ndf['Income'] = df['Income'].astype('int')\ndf.head()\ndf.describe()\ndf.info()\n#heatmap correlation\nplt.figure(figsize = (10,6))\nsns.heatmap(df.corr(), vmax = 0.9, square = True)\nplt.title(\"Pearson Correlation\")\nplt.show()\n#split data\nX = df.drop('Diabetes_binary', axis = 1)\ny = df['Diabetes_binary']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\"\"\"\n## Random Forest Model\n\"\"\"\n#build model\nrf = RandomForestClassifier(random_state = 1, max_features = 'sqrt', n_jobs = 1, verbose = 1)\n%time rf.fit(X_train, y_train)\nrf.score(X_test, y_test)\n#prediction\ny_pred = rf.predict(X_test)\nprint(y_pred)\n#check MSE & RMSE \nmse = metrics.mean_squared_error(y_test, y_pred)\nprint('Mean Squared Error : '+ str(mse))\nrmse = math.sqrt(metrics.mean_squared_error(y_test, y_pred))\nprint('Root Mean Squared Error : '+ str(rmse))\n#confusion matrix\nmatrix = metrics.confusion_matrix(y_test, y_pred)\nprint(matrix)\n\n#heatmap matrix\nplt.figure(figsize = (8,6))\nsns.heatmap(matrix, annot = True, fmt = \".0f\", cmap = 'viridis')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Prediction\")\nplt.ylabel(\"Actual\")\nplt.show()\n#classification report\nreport = metrics.classification_report(y_test, y_pred)\nprint(report)\n\"\"\"\n## Check Feature Importance\n\"\"\"\n#defining of feature\nfeature = pd.Series(rf.feature_importances_, index = X_train.columns).sort_values(ascending = False)\nprint(feature)\n#visualize feature\nplt.figure(figsize = (10,6))\nsns.barplot(x = feature, y = feature.index)\nplt.title(\"Feature Importance\")\nplt.xlabel('Score')\nplt.ylabel('Features')\nplt.show()\n\"\"\"\n## Visualization\n\"\"\"\n#transform data\ndf.Diabetes_binary[df['Diabetes_binary'] == 0] = 'No Diabetes'\ndf.Diabetes_binary[df['Diabetes_binary'] == 1] = 'Diabetes'\n\ndf.HighBP[df['HighBP'] == 0] = 'No High'\ndf.HighBP[df['HighBP'] == 1] = 'High BP'\n\ndf.HighChol[df['HighChol'] == 0] = 'No High Cholesterol'\ndf.HighChol[df['HighChol'] == 1] = 'High Cholesterol'\n\ndf.CholCheck[df['CholCheck'] == 0] = 'No Cholesterol Check in 5 Years'\ndf.CholCheck[df['CholCheck'] == 1] = 'Cholesterol Check in 5 Years'\n\ndf.Smoker[df['Smoker'] == 0] = 'No'\ndf.Smoker[df['Smoker'] == 1] = 'Yes'\n\ndf.Stroke[df['Stroke'] == 0] = 'No'\ndf.Stroke[df['Stroke'] == 1] = 'Yes'\n\ndf.HeartDiseaseorAttack[df['HeartDiseaseorAttack'] == 0] = 'No'\ndf.HeartDiseaseorAttack[df['HeartDiseaseorAttack'] == 1] = 'Yes'\n\ndf.PhysActivity[df['PhysActivity'] == 0] = 'No'\ndf.PhysActivity[df['PhysActivity'] == 1] = 'Yes'\n\ndf.Fruits[df['Fruits'] == 0] = 'No'\ndf.Fruits[df['Fruits'] == 1] = 'Yes'\n\ndf.Veggies[df['Veggies'] == 0] = 'No'\ndf.Veggies[df['Veggies'] == 1] = 'Yes'\n\ndf.HvyAlcoholConsump[df['HvyAlcoholConsump'] == 0] = 'No'\ndf.HvyAlcoholConsump[df['HvyAlcoholConsump'] == 1] = 'Yes'\n\ndf.AnyHealthcare[df['AnyHealthcare'] == 0] = 'No'\ndf.AnyHealthcare[df['AnyHealthcare'] == 1] = 'Yes'\n\ndf.NoDocbcCost[df['NoDocbcCost'] == 0] = 'No'\ndf.NoDocbcCost[df['NoDocbcCost'] == 1] = 'Yes'\n\ndf.GenHlth[df['GenHlth'] == 1] = 'Excellent'\ndf.GenHlth[df['GenHlth'] == 2] = 'Very Good'\ndf.GenHlth[df['GenHlth'] == 3] = 'Good'\ndf.GenHlth[df['GenHlth'] == 4] = 'Fair'\ndf.GenHlth[df['GenHlth'] == 5] = 'Poor'\n\ndf.DiffWalk[df['DiffWalk'] == 0] = 'No'\ndf.DiffWalk[df['DiffWalk'] == 1] = 'Yes'\n\ndf.Sex[df['Sex'] == 0] = 'Female'\ndf.Sex[df['Sex'] == 1] = 'Male'\n\ndf.Education[df['Education'] == 1] = 'Never Attended School'\ndf.Education[df['Education'] == 2] = 'Elementary'\ndf.Education[df['Education'] == 3] = 'Junior High School'\ndf.Education[df['Education'] == 4] = 'Senior High School'\ndf.Education[df['Education'] == 5] = 'Undergraduate Degree'\ndf.Education[df['Education'] == 6] = 'Magister'\n\ndf.Income[df['Income'] == 1] = 'Less Than $10,000'\ndf.Income[df['Income'] == 2] = 'Less Than $10,000'\ndf.Income[df['Income'] == 3] = 'Less Than $10,000'\ndf.Income[df['Income'] == 4] = 'Less Than $10,000'\ndf.Income[df['Income'] == 5] = 'Less Than $35,000'\ndf.Income[df['Income'] == 6] = 'Less Than $35,000'\ndf.Income[df['Income'] == 7] = 'Less Than $35,000'\ndf.Income[df['Income'] == 8] = '$75,000 or More'\ndf.head()\n#visualize diabetes status\nplt.figure(figsize = (8,6))\nsns.countplot(df['Diabetes_binary'])\nplt.title(\"Diabetes Status\")\nplt.show()\n#group diabetes status & BP\ndiabetes_bp = df.groupby(['Diabetes_binary', 'HighBP']).size().reset_index(name = 'Count')\nprint(diabetes_bp)\n#visualize diabetes status ~ BP\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'HighBP', data = diabetes_bp, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ BP\")\nplt.show()\n#group diabetes status & cholesterol status\ndiabetes_chol = df.groupby(['Diabetes_binary', 'HighChol']).size().reset_index(name = 'Count')\nprint(diabetes_chol)\n#visualize diabetes status ~ cholesterol status\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'HighChol', data = diabetes_chol, palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Cholesterol Status\")\nplt.show()\n#group diabetes status & cholesterol check\ndiabetes_check = df.groupby(['Diabetes_binary', 'CholCheck']).size().reset_index(name = 'Count')\nprint(diabetes_check)\n#visualize diabetes status ~ cholesterol check \nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'CholCheck', data = diabetes_check)\nplt.title(\"Dibaetes Status ~ Cholesterol Check\")\nplt.show()\n#visualize diabetes status ~ BMI\nplt.figure(figsize = (8,6))\nsns.boxplot(data = df, x = 'Diabetes_binary', y = 'BMI', palette = 'Set1')\nplt.title(\"Dibaetes Status ~ BMI\")\nplt.show()\n#group diabetes status & smoker status\ndiabetes_smoker = df.groupby(['Diabetes_binary', 'Smoker']).size().reset_index(name = 'Count')\nprint(diabetes_smoker)\n#visualize diabetes status ~ smoker status \nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Smoker', data = diabetes_smoker, palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Smoker Status\")\nplt.show()\n#group diabetes status & stroke status\ndiabetes_stroke = df.groupby(['Diabetes_binary', 'Stroke']).size().reset_index(name = 'Count')\nprint(diabetes_stroke)\n#visualize diabetes status ~ stroke status \nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Stroke', data = diabetes_stroke, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Stroke Status\")\nplt.show()\n#group diabetes status & heart diseaseor attack\ndiabetes_heart = df.groupby(['Diabetes_binary', 'HeartDiseaseorAttack']).size().reset_index(name = 'Count')\nprint(diabetes_heart)\n#visualize diabetes status ~ heart diseaseor attack\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'HeartDiseaseorAttack', data = diabetes_heart, palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Heart Diseaseor Attack\")\nplt.show()\n#group diabetes status & physical activity\ndiabetes_physical = df.groupby(['Diabetes_binary', 'PhysActivity']).size().reset_index(name = 'Count')\nprint(diabetes_physical)\n#visualize diabetes status ~ physical activity\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'PhysActivity', data = diabetes_physical)\nplt.title(\"Dibaetes Status ~ Physical Activity\")\nplt.show()\n#group diabetes status & fruits\ndiabetes_fruit = df.groupby(['Diabetes_binary', 'Fruits']).size().reset_index(name = 'Count')\nprint(diabetes_fruit)\n#visualize diabetes status ~ fruits\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Fruits', data = diabetes_fruit, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Fruits\")\nplt.show()\n#group diabetes status & veggies\ndiabetes_veggies = df.groupby(['Diabetes_binary', 'Veggies']).size().reset_index(name = 'Count')\nprint(diabetes_veggies)\n#visualize diabetes status ~ veggies\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Veggies', data = diabetes_veggies, palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Veggies\")\nplt.show()\n#group diabetes status & HvyAlcoholConsump\ndiabetes_alcohol = df.groupby(['Diabetes_binary', 'HvyAlcoholConsump']).size().reset_index(name = 'Count')\nprint(diabetes_alcohol)\n#visualize diabetes status ~ HvyAlcoholConsump\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'HvyAlcoholConsump', data = diabetes_alcohol)\nplt.title(\"Dibaetes Status ~ Alcohol Consumption\")\nplt.show()\n#group diabetes status & AnyHealthcare\ndiabetes_healthcare = df.groupby(['Diabetes_binary', 'AnyHealthcare']).size().reset_index(name = 'Count')\nprint(diabetes_healthcare)\n#visualize diabetes status ~ AnyHealthcare\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'AnyHealthcare', data = diabetes_healthcare, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Healthcare\")\nplt.show()\n#group diabetes status & doctor cost\ndiabetes_NoDocbcCost = df.groupby(['Diabetes_binary', 'NoDocbcCost']).size().reset_index(name = 'Count')\nprint(diabetes_NoDocbcCost)\n#visualize diabetes status ~ doctor cost\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'NoDocbcCost', data = diabetes_NoDocbcCost, palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Doctor Cost\")\nplt.show()\n#group diabetes status & general health\ndiabetes_general = df.groupby(['Diabetes_binary', 'GenHlth']).size().reset_index(name = 'Count')\nprint(diabetes_general)\n#visualize diabetes status ~ general health\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'GenHlth', data = diabetes_general)\nplt.title(\"Dibaetes Status ~ General Health\")\nplt.show()\n#visualize diabetes status ~ mental health\nplt.figure(figsize = (8,6))\nsns.boxplot(data = df, x = 'Diabetes_binary', y = 'MentHlth', palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Mental Health\")\nplt.show()\n#visualize diabetes status ~ physical health\nplt.figure(figsize = (8,6))\nsns.boxplot(data = df, x = 'Diabetes_binary', y = 'PhysHlth', palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Physical Health\")\nplt.show()\n#group diabetes status & difficulty walking\ndiabetes_walk = df.groupby(['Diabetes_binary', 'DiffWalk']).size().reset_index(name = 'Count')\nprint(diabetes_walk)\n#visualize diabetes status ~ difficulty walking\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'DiffWalk', data = diabetes_walk)\nplt.title(\"Dibaetes Status ~ Difficulty Walking\")\nplt.show()\n#group diabetes status & gender\ndiabetes_sex = df.groupby(['Diabetes_binary', 'Sex']).size().reset_index(name = 'Count')\nprint(diabetes_sex)\n#visualize diabetes status ~ gender\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Sex', data = diabetes_sex, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Gender\")\nplt.show()\n#visualize diabetes status ~ age\nplt.figure(figsize = (8,6))\nsns.boxplot(data = df, x = 'Diabetes_binary', y = 'Age', palette = 'Set2')\nplt.title(\"Dibaetes Status ~ Age\")\nplt.show()\n#group diabetes status & education\ndiabetes_education = df.groupby(['Diabetes_binary', 'Education']).size().reset_index(name = 'Count')\nprint(diabetes_education)\n#visualize diabetes status ~ education\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Education', data = diabetes_education)\nplt.title(\"Dibaetes Status ~ Education\")\nplt.show()\n#group diabetes status & income\ndiabetes_income = df.groupby(['Diabetes_binary', 'Income']).size().reset_index(name = 'Count')\nprint(diabetes_income)\n#visualize diabetes status ~ income\nplt.figure(figsize = (8,6))\nsns.barplot(x = 'Diabetes_binary', y = 'Count', hue = 'Income', data = diabetes_income, palette = 'Set1')\nplt.title(\"Dibaetes Status ~ Income\")\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'dfee5e74efa1e4'}"}
{"id":"68624","text":"\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\n## What is Melanoma?\n\nMelanoma, also known as malignant melanoma, is a type of skin cancer that develops from the pigment-producing cells known as melanocytes. Melanomas typically occur in the skin but may rarely occur in the mouth, intestines or eye (uveal melanoma).\n\nThe exact cause of all melanomas isn't clear, but exposure to ultraviolet (UV) radiation from sunlight or tanning lamps and beds increases your risk of developing melanoma. Limiting your exposure to UV radiation can help reduce your risk of melanoma.The risk of melanoma seems to be increasing in people under 40, especially women. Knowing the warning signs of skin cancer can help ensure that cancerous changes are detected and treated before the cancer has spread. Melanoma can be treated successfully if it is detected early.\n\n## Causes\n\n![IMG](https:\/\/www.mayoclinic.org\/-\/media\/kcms\/gbs\/patient-consumer\/images\/2013\/11\/15\/17\/40\/ds00190_-ds00439_-ds00924_-ds00925_im02400_c7_skincancerthu_jpg.jpg)\n\nMelanoma occurs when something goes wrong in the melanin-producing cells (melanocytes) that give color to your skin.\n\nNormally, skin cells develop in a controlled and orderly way \u2014 healthy new cells push older cells toward your skin's surface, where they die and eventually fall off. But when some cells develop DNA damage, new cells may begin to grow out of control and can eventually form a mass of cancerous cells.\n\n## Symptoms\n\nThe first melanoma signs and symptoms often are:\n\nA change in an existing mole\nThe development of a new pigmented or unusual-looking growth on your skin\nMelanoma doesn't always begin as a mole. It can also occur on otherwise normal-appearing skin.\n\n## Prevention\n\n\n* Wear sunscreen year-round. \n* Avoid the sun during the middle of the day.\n* Wear protective clothing.\n* Avoid tanning lamps and beds.\n* Become familiar with your skin so that you'll notice changes.\n\n\n## When to see a doctor \n\nMake an appointment with your doctor if you notice any skin changes that seem unusual.\n\n\nFor more information,[ Click here.](https:\/\/www.mayoclinic.org\/diseases-conditions\/melanoma\/symptoms-causes\/syc-20374884)\n\"\"\"\n\"\"\"\n# Load required libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom keras.layers import Input, Lambda, Dense, Flatten\nfrom keras.models import Model\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\nfrom glob import glob\nimport matplotlib.pyplot as plt\n\nfrom keras.optimizers import Adam, SGD, RMSprop\nimport tensorflow as tf\nimport cv2\nimport glob\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img\nfrom tensorflow.python.keras import backend as K\nimport plotly.graph_objects as go\nimport plotly.offline as py\nautosize =False\n\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n\n%matplotlib inline\nimport pandas as pd\ntrain_dir='\/kaggle\/input\/siim-isic-melanoma-classification\/jpeg\/train\/'\ntest_dir='\/kaggle\/input\/siim-isic-melanoma-classification\/jpeg\/test\/'\ntrain=pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/train.csv')\ntest=pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/test.csv')\n#sub  = pd.read_csv('\/kaggle\/input\/siim-isic-melanoma-classification\/sample_submission.csv')\ntrain.head()\n\"\"\"\n# Remove duplicate images from the training dataset\n\"\"\"\n# as per an ongoing discussion, there are some duplicate images in the training data, these images might adversely impact our model, \n# so, lets remove these images\ndup = pd.read_csv(\"\/kaggle\/input\/siim-list-of-duplicates\/2020_Challenge_duplicates.csv\")\n\ndrop_idx_list = []\nfor dup_image in dup.ISIC_id_paired:\n    for idx,image in enumerate(train.image_name):\n        if image == dup_image:\n            drop_idx_list.append(idx)\n\nprint(\"no. of duplicates in training dataset:\",len(drop_idx_list))\n\ntrain.drop(drop_idx_list,inplace=True)\n\nprint(\"updated dimensions of the training dataset:\",train.shape)\ntrain.target.value_counts()\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\n\"\"\"\n### Class Distribution\n\"\"\"\n# function to draw bar plot\nimport matplotlib.pyplot as plt\ndef draw_bar_plot(category,length,xlabel,ylabel,title,sub):\n    plt.subplot(2,2,sub)\n    plt.bar(category, length)\n    plt.legend()\n    plt.xlabel(xlabel, fontsize=15)\n    plt.ylabel(ylabel, fontsize=15)\n    plt.title(title, fontsize=15)\n    #plt.show()\n# lets visualize the class distribution\nplt.figure(figsize = (8,6))\nplt.bar([\"Melanoma\",\"Normal\"],[len(train[train.target==1]), len(train[train.target==0])],color = 'rg')\n\"\"\"\n**To begin with, let us first observe the benign and malignant classified images.**\n\"\"\"\ndf_benign=train[train['target']==0].sample(2000)\ndf_malignant=train[train['target']==1]\nprint('Benign Cases')\nbenign=[]\ndf_b=df_benign.head(30)\ndf_b=df_b.reset_index()\nfor i in range(30):\n    img=cv2.imread(str(train_dir + df_benign['image_name'].iloc[i]+'.jpg'))\n    img = cv2.resize(img, (224,224))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = img.astype(np.float32)\/255.\n    benign.append(img)\nf, ax = plt.subplots(5,6, figsize=(10,6))\nfor i, img in enumerate(benign):\n        ax[i\/\/6, i%6].imshow(img)\n        ax[i\/\/6, i%6].axis('off')\n        \nplt.show()\nprint('Malignant Cases')\nm=[]\ndf_m=df_malignant.head(30)\ndf_m=df_m.reset_index()\nfor i in range(30):\n    img=cv2.imread(str(train_dir + df_m['image_name'].iloc[i]+'.jpg'))\n    img = cv2.resize(img, (224,224))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = img.astype(np.float32)\/255.\n    m.append(img)\nf, ax = plt.subplots(5,6, figsize=(10,6))\nfor i, img in enumerate(m):\n        ax[i\/\/6, i%6].imshow(img)\n        ax[i\/\/6, i%6].axis('off')\n        \nplt.show()\n\"\"\"\n**Percentage of benign cases VS Malignant cases**\n\"\"\"\ntrain.info()\nimport plotly.express as px\n\nfig = px.pie(train, train['target'],color_discrete_sequence=px.colors.sequential.RdBu)\nfig.show()\n\"\"\"\nNaturally, as medical data is bound to have irregularities, about 98.2% data is benign.\n\"\"\"\ntrain_nona=train.dropna()\n#fig = px.treemap(train_nona, path=['sex', 'age_approx'], values='target', color='target')\n#fig.show()\n\"\"\"\nAlso, the samples have recorded that amount of data recorded for males is greater than that of women.\n\"\"\"\nentire=train.append(test)\naffected_areas=pd.value_counts(entire['anatom_site_general_challenge'])\nfig = go.Figure(data=[go.Pie(labels=affected_areas.index, values=affected_areas.values, hole=.3)])\nfig.update_traces(hoverinfo='label+percent', textinfo='value',textfont_size=15,\n                  marker=dict(colors=['#11100b','#ff3560'], line=dict(color='#FFFFFF', width=2.5)))\nfig.update_layout(\n    title='AFFECTED AREAS')\npy.iplot(fig)\n\"\"\"\n**Analysing Malignant data**\n\"\"\"\ndf_malignant=df_malignant.dropna()\nage_counts=pd.value_counts(df_malignant['age_approx'])\ngender_counts=pd.value_counts(df_malignant['sex'])\nanatom_site_counts=pd.value_counts(df_malignant['anatom_site_general_challenge'])\n\nfig = make_subplots(\n    rows=1, cols=3,\n    specs=[[{\"type\": \"xy\"},{\"type\": \"domain\"}, {\"type\": \"xy\"}]])\n\nfig.add_trace(go.Bar(y=age_counts.values, x=age_counts.index),row=1, col=1)\n\n\nfig.add_trace(go.Pie(values=gender_counts.values, labels=gender_counts.index,marker=dict(colors=['#100b','#f00560'], line=dict(color='#FFFFFF', width=2.5))),\n              row=1, col=2)\n\nfig.add_trace(go.Scatter(x=anatom_site_counts.index, y=anatom_site_counts.values),\n              row=1, col=3)\n\nfig.update_layout(height=700, showlegend=False)\n\nfig.update_xaxes(title_text=\"Age\", row=1, col=1)\nfig.update_xaxes(title_text=\"Site\", row=1, col=3)\n\n# Update yaxis properties\nfig.update_yaxes(title_text=\"Count\", row=1, col=1)\nfig.update_yaxes(title_text=\"Count\", row=1, col=3)\n\n# Update title and height\nfig.update_layout(title_text=\"MALIGNANT DATA wrt AGE, GENDER, SITE\",height=600, width=1000)\n\nfig.show()\n\"\"\"\nSome Inferences from the above plots are:\n* Majority of the patients who have malignant reports are in the age range of 50-80 years.\n* About 62% of the patients who tested malignant were males.\n* Torso, Upper extremity and Lower extremity are the most common sites for melanoma appearance.\n\"\"\"\n\"\"\"\n# Some insights about the training and testing data\n\n\"\"\"\n\"\"\"\n**Age diversity in training data Vs Age diversity in testing data**\n\"\"\"\nagecounts=pd.value_counts(train['age_approx'])\nfig = px.bar(train, x=agecounts.index, y=agecounts.values)\nfig.update_layout(title_text='Age counts of the training data')\nfig.show()\nagecounts=pd.value_counts(test['age_approx'])\nfig = px.bar(test, x=agecounts.index, y=agecounts.values)\nfig.update_layout(title_text='Age counts of the testing data')\nfig.show()\n\"\"\"\nThe irregularities in age groups is not as evident. Both the training and testing data have a majority of reports from the 40-50 age group. Although the reports from the age 70 and above are comparatively less in testing data than in training data.\n\"\"\"\n\"\"\"\n## Melanoma skin site appearance in training data vs in testing data\n\"\"\"\nfig = make_subplots(\n    rows=1, cols=2,\n    specs=[[{\"type\": \"domain\"}, {\"type\": \"domain\"}]])\n\nsite_train_counts=pd.value_counts(train['anatom_site_general_challenge'])\n\nfig.add_trace(go.Pie(values=site_train_counts.values, labels=site_train_counts.index,title_text='Melanoma regions for training dataset',marker=dict(colors=['#100b','#f00560'], line=dict(color='#FFFFFF', width=2.5))),\n              row=1, col=1)\n\nsite_test_counts=pd.value_counts(test['anatom_site_general_challenge'])\n\nfig.add_trace(go.Pie(values=site_test_counts.values, labels=site_test_counts.index,title_text='Melanoma regions for testing dataset',marker=dict(colors=['#100b','#f00560'], line=dict(color='#FFFFFF', width=2.5))),\n              row=1, col=2)\n\nfig.update_layout(height=700, showlegend=False)\n\nfig.show()\n\"\"\"\nSo, if we compare the training and testing data side by side, the area where melanoma signs appear are similar. The most common region is torso followed by lower extremity.\n\"\"\"\n\"\"\"\n# Modelling - VGG16 (Transfer Learning)\n\"\"\"\n\"\"\"\n## Data Preparation\n\"\"\"\n\"\"\"\n* ### Take Sample Images for training\n\"\"\"\n# Since this is a huge dataset, we would take a sample of it for training purpose\n\ndf_0=train[train['target']==0].sample(2000)\ndf_1=train[train['target']==1]\ntrain=pd.concat([df_0,df_1])\ntrain=train.reset_index()\n\"\"\"\n* ### Update Image Names\n\"\"\"\n# update image names with the whole path\ndef append_ext(fn):\n    return train_dir+fn+\".jpg\"\ntrain[\"image_name\"]=train[\"image_name\"].apply(append_ext)\n\ndef append_ext(fn):\n    return test_dir+fn+\".jpg\"\ntest[\"image_name\"]=test[\"image_name\"].apply(append_ext)\n\"\"\"\n* ### Split into train and validate dataset\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(train['image_name'],train['target'], test_size=0.2, random_state=1234)\n\ntrain=pd.DataFrame(X_train)\ntrain.columns=['image_name']\ntrain['target']=y_train\n\nvalidation=pd.DataFrame(X_val)\nvalidation.columns=['image_name']\nvalidation['target']=y_val\n\"\"\"\n* ### Resize Images\nResizing images is a critical preprocessing step in computer vision. Principally, our machine learning models train faster on smaller images. An input image that is twice as large requires our network to learn from four times as many pixels \u2014 and that time adds up.\n\"\"\"\n# resizing the images\nIMG_DIM = (224, 224)\n\n# load images\ntrain_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in train.image_name]\ntrain_imgs = np.array(train_imgs)\n\nvalidation_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in validation.image_name]\nvalidation_imgs = np.array(validation_imgs)\n\nprint('Train dataset shape:', train_imgs.shape, \n      '\\tValidation dataset shape:', validation_imgs.shape)\n# define parameters for model training\nbatch_size = 128\nnum_classes = 2\nepochs = 30\ninput_shape = (224, 224, 3)\n\"\"\"\nWe would leverage Transfer Learning Models for image classification, but why Transfer Learning and not Traditional ML\/DL Algorithms?\nLet's find out!\n\"\"\"\n\"\"\"\n# Problem with conventional ML & DL Algorithms\n\nHumans have an inherent ability to transfer knowledge across tasks. What we acquire as knowledge while learning about one task, we utilize in the same way to solve related tasks. The more related the tasks, the easier it is for us to transfer, or cross-utilize our knowledge. Some simple examples would be,\n    \n*     Know how to ride a motorbike \u2bab Learn how to ride a car\n*     Know how to play classic piano \u2bab Learn how to play jazz piano\n*     Know math and statistics \u2bab Learn machine learning\n\n![image.png](attachment:image.png)\n\nIn each of the above scenarios, we don\u2019t learn everything from scratch when we attempt to learn new aspects or topics. We transfer and leverage our knowledge from what we have learnt in the past!\n\nConventional machine learning and deep learning algorithms, so far, have been traditionally designed to work in isolation. \n\nThese algorithms are trained to solve specific tasks. The models have to be rebuilt from scratch once the feature-space distribution changes. \n\"\"\"\n\"\"\"\n# What is Transfer Learning - An Introduction\n\nIn transfer learning, you can leverage knowledge (features, weights etc) from previously trained models for training newer models and even tackle problems like having less data for the newer task!\n\n* ### Motivation for Transfer Learning\n    We have already briefly discussed that humans don\u2019t learn everything from the ground up and leverage and transfer their knowledge from previously learnt domains to newer domains and tasks. \n\n    Thus, the key motivation, especially considering the context of deep learning is the fact that most models which solve complex problems need a whole lot of data, and getting vast amounts of labeled data for supervised models can be really difficult, considering the time and effort it takes to label data points. \n    A simple example would be the ImageNet dataset, which has millions of images pertaining to different categories, thanks to years of hard work starting at Stanford!\n\n    However, getting such a dataset for every domain is tough. Besides, most deep learning models are very specialized to a particular domain or even a specific task. \n    While these might be state-of-the-art models, with really high accuracy and beating all benchmarks, it would be only on very specific datasets and end up suffering a significant loss in performance when used in a new task which might still be similar to the one it was trained on. \n    This forms the motivation for transfer learning, which goes beyond specific tasks and domains, and tries to see how to leverage knowledge from pre-trained models and use it to solve new problems!\n    \n\n* ### Understanding Transfer Learning\n\n    The first thing to remember here is that, transfer learning, is not a new concept which is very specific to deep learning. There is a stark difference between the traditional approach of building and training machine learning models, and using a methodology following transfer learning principles.\n\n    Below picture shows the difference between traditional ML vs Transfer Learning\n\n![image.png](attachment:image.png)\n\nTraditional learning is isolated and occurs purely based on specific tasks, datasets and training separate isolated models on them.\nNo knowledge is retained which can be transferred from one model to another.  In transfer learning, you can leverage knowledge\n(features, weights etc) from previously trained models for training newer models and even tackle problems like having less data for the newer task!\n\"\"\"\n\"\"\"\n**The following terminology is very important with regard to training our model:**\n\n* The batch_size indicates the total number of images passed to the model per iteration.\n\n* The weights of the units in layers are updated after each iteration.\n\n* The total number of iterations is always equal to the total number of training samples divided by the batch_size.\n\n* An epoch is when the complete dataset has passed through the network once, that is, all the iterations are completed based on data batches.\n\"\"\"\n\"\"\"\nWe will be using VGG16 model(Transfer Learning) for image classification\n\"\"\"\n\"\"\"\n### Define loss function\nWe are taking focal loss because the dataset is an imbalanced dataset\n\"\"\"\n# focal loss\ndef focal_loss(alpha=0.25,gamma=2.0):\n    def focal_crossentropy(y_true, y_pred):\n        bce = K.binary_crossentropy(y_true, y_pred)\n        \n        y_pred = K.clip(y_pred, K.epsilon(), 1.- K.epsilon())\n        p_t = (y_true*y_pred) + ((1-y_true)*(1-y_pred))\n        \n        alpha_factor = 1\n        modulating_factor = 1\n\n        alpha_factor = y_true*alpha + ((1-alpha)*(1-y_true))\n        modulating_factor = K.pow((1-p_t), gamma)\n\n        # compute the final loss and return\n        return K.mean(alpha_factor*modulating_factor*bce, axis=-1)\n    return focal_crossentropy\n\"\"\"\n### Optimizer & No. of Iterations\n\"\"\"\n# we will use Adam optimizer\nopt = Adam(lr=1e-5)\n\n#total number of iterations is always equal to the total number of training samples divided by the batch_size.\nnb_train_steps = train.shape[0]\/\/batch_size\nnb_val_steps=validation.shape[0]\/\/batch_size\n\nprint(\"Number of training and validation steps: {} and {}\".format(nb_train_steps,nb_val_steps))\n\"\"\"\n### Image Augmentation & Pixels Normalization\n\n**Image Augmentation:**\nThe idea behind image augmentation is that we follow a set process of taking in existing images from our training dataset and applying some image transformation operations to them, such as rotation, shearing, translation, zooming, and so on, to produce new, altered versions of existing images. Due to these random transformations, we don\u2019t get the same images each time, and we will leverage Python generators to feed in these new images to our model during training.\n\nThe Keras framework has an excellent utility called ImageDataGenerator that can help us in doing all the preceding operations. Let\u2019s initialize two of the data generators for our training and validation datasets.\n\n**Pixel Nomralization:**\nNeural networks process inputs using small weight values, and inputs with large integer values can disrupt \nor slow down the learning process. As such it is good practice to normalize the pixel values so that each pixel value has a value \nbetween 0 and 1. Parameter \"rescale\" used below does pixel normalization for us.\n\"\"\"\n# Pixel Normalization and Image Augmentation\ntrain_datagen = ImageDataGenerator(rescale=1.\/255, zoom_range=0.3, rotation_range=50,\n                                   width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, \n                                   horizontal_flip=True, fill_mode='nearest')\n\n# no need to create augmentation images for validation data, only rescaling the pixels\nval_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow(train_imgs, y_train, batch_size=batch_size)\nval_generator = val_datagen.flow(validation_imgs, y_val, batch_size=batch_size)\n\"\"\"\nThere are a lot of options available in ImageDataGenerator and we have just utilized a few of them. Feel free to check out the documentation to get a more detailed perspective. In our training data generator, we take in the raw images and then perform several transformations on them to generate new images. These include the following.\n\n    Zooming the image randomly by a factor of 0.3 using the zoom_range parameter.\n\n    Rotating the image randomly by 50 degrees using the rotation_range parameter.\n\n    Translating the image randomly horizontally or vertically by a 0.2 factor of the image\u2019s width \n    or height using the width_shift_range and the height_shift_range parameters.\n\n    Applying shear-based transformations randomly using the shear_range parameter.\n\n    Randomly flipping half of the images horizontally using the horizontal_flip parameter.\n\n    Leveraging the fill_mode parameter to fill in new pixels for images after we apply any of the preceding operations \n    (especially rotation or translation). In this case, we just fill in the new pixels with their nearest surrounding pixel values.\n\nLet\u2019s see how some of these generated images might look so that you can understand them better. We will take two sample images from our training dataset to illustrate the same. The first image is an image of a cat.\n\n\"\"\"\nimg_id = 100\ngenerator_100 = train_datagen.flow(train_imgs[img_id:img_id+1], train.target[img_id:img_id+1],\n                                   batch_size=1)\naug_img = [next(generator_100) for i in range(0,5)]\nfig, ax = plt.subplots(1,5, figsize=(16, 6))\nprint('Labels:', [item[1][0] for item in aug_img])\nl = [ax[i].imshow(aug_img[i][0][0]) for i in range(0,5)]\nimport gc\ndel train\ngc.collect()\n\"\"\"\n### Define VGG16 Model\n\"\"\"\nfrom keras.applications import vgg16\nfrom keras.models import Model\nimport keras\n\nvgg = vgg16.VGG16(include_top=False, weights='imagenet', \n                                     input_shape=input_shape)\n\noutput = vgg.layers[-1].output\noutput = keras.layers.Flatten()(output)\nvgg_model = Model(vgg.input, output)\n\nvgg_model.trainable = False\nfor layer in vgg_model.layers:\n    layer.trainable = False\n    \nimport pandas as pd\npd.set_option('max_colwidth', -1)\nlayers = [(layer, layer.name, layer.trainable) for layer in vgg_model.layers]\npd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])    \nvgg_model.trainable = True\n\nset_trainable = False\nfor layer in vgg_model.layers:\n    if layer.name in ['block5_conv1', 'block4_conv1']:\n        set_trainable = True\n    if set_trainable:\n        layer.trainable = True\n    else:\n        layer.trainable = False\n        \nlayers = [(layer, layer.name, layer.trainable) for layer in vgg_model.layers]\npd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])    \nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayer\nfrom keras.models import Sequential\nfrom keras import optimizers\n\nmodel = Sequential()\nmodel.add(vgg_model)\nmodel.add(Dense(512, activation='relu', input_dim=input_shape))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(1, activation='sigmoid'))\n\n\nmodel.compile(loss=focal_loss(), metrics=[tf.keras.metrics.AUC()],optimizer=opt)\n#!pip install livelossplot\n#from livelossplot import PlotLossesKeras\nfrom keras.callbacks import EarlyStopping\nes = EarlyStopping(monitor='loss', patience=3, verbose=1)\n#cb=[PlotLossesKeras()]\nmodel.fit_generator(train_generator, steps_per_epoch=nb_train_steps, epochs=epochs,callbacks=[es],\n                              validation_data=val_generator, validation_steps=nb_val_steps, \n                              verbose=1)\n\nx_test = np.load('..\/input\/siimisic-melanoma-resized-images\/x_test_224.npy')\nx_test = x_test.astype('float16')\ntest_imgs_scaled = x_test \/ 255\ndel x_test\ngc.collect()\ntarget=[]\ni = 0\nfor img in test_imgs_scaled:\n    img1=np.reshape(img,(1,224,224,3))\n    prediction=model.predict(img1)\n    i = i + 1\n    print(\"predicted image no.\",i)\n    target.append(prediction[0][0])\n# submission file\nsub=pd.read_csv(\"..\/input\/siim-isic-melanoma-classification\/sample_submission.csv\")\nsub['target']=target\n#sub.to_csv('submission.csv', index=False)\nsub.head()\n\"\"\"\n# Creating Ensemble of Models generated by training image data and by tabular data\n\"\"\"\n#img_csv=sub.copy()\ntab_csv=pd.read_csv('..\/input\/image-and-tab-csv-files\/submission_tab.csv')\n#img_csv.head()\nimg_csv=pd.read_csv('..\/input\/image-and-tab-csv-files\/submission_img.csv')\nsub=img_csv.copy()\nsub['target']= (img_csv['target'] + tab_csv['target'])\/2\n#sub['target']= img_csv['target'] * 0.8 + tab_csv['target'] * 0.2\nsub.head()\nsub.to_csv('submission.csv',index=False)","meta":"{'source': 'AI4Code', 'id': '7e50479ef1bdad'}"}
{"id":"88366","text":"\"\"\"\nThe dataset we have here belongs to 50 startups companies. Companies are going to be in a venture capitalist fund \nchallenge. We have 5 columns in dataset (R&D Spend,Administration, Marketing Spend, Profit & State). \nIn data we have information regarding how much the company in financial year has spend on different departments \nwith respective profit and state in which companies are operational.\nThe challenge here is that, all data is totally anonomous so we do not know the companies but we have to analyze \nthese 50 companies and create model that will help venture capitalists in which type of company they should \ninvest to maximize the profit.\n\nFeatures: R&D Spend, Administration, Marketing Spend, State\nTarget Variable: Profit\n\"\"\"\n\"\"\"\nImporting the Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\"\"\"\nImporting the Dataset\n\"\"\"\ndataset = pd.read_csv(\"..\/input\/50-startup-companies\/50_Startups.csv\")\ndataset.head()\n\"\"\"\nSplitting data into (X contains Features and y contains dependent variable)\n\"\"\"\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\nprint(X)\nprint(y)\n\"\"\"\nEncoding Categorical Data\n\"\"\"\n\"\"\"\nAs you can see that there are multiple descriptive values appearing in State Column. we have to apply **OneHotEncoding**, that will\nconvert descriptve values of State Column into Binary values and split into 3 different columns.\n\"\"\"\n#This code will change the categorical column into binary column\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough')\nX = np.array(ct.fit_transform(X))\nprint(X)\n\"\"\"\nPlease note that, there is no need to apply **Feature Scaling** here because in the Multi Linear Regression we have coefficients that will multiply with each feature, therefore it does not matter that some features\nhave higher values than others because coefficients will put every feature on scale.\n\"\"\"\n\"\"\"\nSplitting the dataset into Training set and Test set\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train,y_train)\ny_pred = regressor.predict(X_test)\nnp.set_printoptions(precision=2)#This is used to only get values in 2 decimals.\n\"\"\"\nNow we are going to vertically concatinate Predicted Results with Test Results\n\"\"\"\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\n\"\"\"\nWe can clearly see two vectors above. The left one is predicted profits and right one is real\nprofits from test set. As you can see in results that most of the predicted values are very close when we compare them with real values on right side.\nNow Lets evaluate the performance of our Model. There are multiple methods to evaluate model but we are going to use **RSquare** method for model evaluation.\n\"\"\"\nfrom sklearn.metrics import r2_score\nr2_score(y_test, y_pred)\n\"\"\"\nAs you can see above that our model accuracy is **93%** which is very good. So, that concludes the Basic implementation of **Multiple Linear Regression Model**. Please feel free to add in case i missed something and correct me if there is any mistake.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a21a41311c1751'}"}
{"id":"26690","text":"\"\"\"\n# Exploratory Analysis\n\"\"\"\n# Import all the libraries\nimport pandas as pd\nimport numpy as np\nfrom numpy import set_printoptions\n# import dataset\ntimes = pd.read_csv(\"..\/input\/world-university-rankings\/timesData.csv\")\ntimes.head()\nprint('dtypes of times dataset:')\ntimes.dtypes\n\n# mix between float, string and integer.\nprint('number of NaNs per column:')\ntimes.isna().sum()\n\n# 4 columns have missing values. Female male ratio has the most with 233. \n\"\"\"\n# Pre-processing\n\"\"\"\n# drop university name and country because they're strings\n# drop female male ratio because 233 rows are missing\n# drop total score because it's too similar to world rank\ntimes.drop(columns=['university_name', 'country', 'female_male_ratio', 'total_score'], inplace=True)\ntimes.head()\n# converting string values to numeric\n# world rank values are numeric from 1 to 100 afterwards they're string like 100-150\n# convert world rank to numeric and rest is converted to NaN\n# we're only interested in top 100, top 50, top 10 so we only care about the first 100 for the binarizer\n\ntimes['world_rank'] = pd.to_numeric(times['world_rank'], errors='coerce')\n\n# fill with 101 so it's below the binarize threshold of 100\ntimes['world_rank'].fillna(101, inplace=True)\n\n# binarizer converts value to 1 if it's above the threshold\n# so we need to invert world rank i.e. make negative\ntimes['world_rank'] = (times['world_rank'] * -1)\n\n# prepare object or string columns for numeric conversion\n# Few columns had \"-\" for missing value, replace with 0\n# num students has \",\", replace with nothing \"\"\n# international students has \"%\", replace with nothing \"\"\nstr_cols = times.select_dtypes(['object']).columns\ntimes[str_cols] = times[str_cols].replace('-', 0)\ntimes['num_students'] = times['num_students'].str.replace(',', '')\ntimes['international_students'] = times['international_students'].str.replace('%', '')\n\n# convert object or string columns to numeric\ntimes[str_cols] = times[str_cols].apply(pd.to_numeric, errors='coerce', axis=1)\n\n# convert international students percentage to decimal\ntimes['international_students'] = times['international_students'] \/ 100\n# determine number of NaNs\ntimes.isna().sum()\n# drop remaining NaNs \ntimes.dropna(inplace=True)\n# check dataframe, dtypes and NaNs\nprint(times.dtypes)\nprint(times.isna().sum())\ntimes.head()\n# convert times dataframe to array\ntimes_array = times.values\nX = times_array[:,1:]\ny_ = times_array[:,[0]]\nset_printoptions(precision=3, suppress=True)\nX[:5]\ny_[:5]\n# drop world_rank, not needed\ntimes.drop(columns='world_rank', inplace=True)\n# create binary variable\nfrom sklearn.preprocessing import Binarizer\n\ntop_n = -50 + (-1)\n\nbinarizer=Binarizer(threshold=top_n).fit(y_)\ny_binary=binarizer.transform(y_)\n\ny_binary[:5]\n\ny_reshaped = np.ravel(y_binary)\ny_reshaped\n# reshape using ravel() so that it works with LogisticRegression\ny_reshaped = np.ravel(y_binary)\ny_reshaped\n\"\"\"\n# Univariate selection using Chi-squared\n\"\"\"\ntimes.head()\n# Univariate selection using Chi-squared \nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2 \n\n# feature selection (we select the 3 best)\ntest = SelectKBest(score_func=chi2, k=3)\nfit = test.fit(X,y_reshaped)\nprint(\"Scores\")\n\nprint(fit.scores_)\n\nprint(\"The 3 attributes with the highest scores are: teaching, research and num_students \")\nprint()\nprint('teaching: university score for teaching')\nprint('reserach: university score for research (volume, income and reputation)')\nprint('num_students: number of students at the university')\n\nfeatures=fit.transform(X)\nfeatures[0:5,:]\n\"\"\"\n# Recursive Feature Elimination using LogisticRegression\n\"\"\"\n# Recursive Feature Elimiantion\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\n\n#Logistic regression\nmodel = LogisticRegression(solver='liblinear')\n\nrfe = RFE(model, 3) #  we want to find the 3 top features\nfit = rfe.fit(X, y_reshaped)\n\nprint(f'Number of features {fit.n_features_:d}')\nprint(f'Selected features {fit.support_}')\nprint(f'Ranking of features {fit.ranking_}')\nprint()\nprint(\"Top features seem to be teaching, research and citations\")\n\"\"\"\n# Ranking feature importance using ExtraTreeClassifier\n\"\"\"\nfrom sklearn.ensemble import ExtraTreesClassifier\n\nmodel = ExtraTreesClassifier(n_estimators=100)\nmodel.fit(X,y_reshaped)\n\nprint(model.feature_importances_)\nprint()\nprint(\"Top features seem to be citations, research and teaching\")\n\"\"\"\n## Univariate, Recursive Feature Elimination and ExtraTreeClassifier for Top 10, Top 50 and Top 100\n\"\"\"\ntop_unis = [10, 50, 100]\nunivariate = []\nrfe_ranking = []\netc_features = []\n\nfor n in top_unis:\n\n    top_n = (n + 1) * (-1)\n\n    binarizer=Binarizer(threshold=top_n).fit(y_)\n    y_binary=binarizer.transform(y_)\n\n    y_reshaped = np.ravel(y_binary)\n\n    print('*************************************************************')\n    print('Univariate Selection using Chi-Squared: top', n)\n\n    #set_printoptions(precision=3, suppress)\n\n    # feature selection (we select the 3 best)\n    test = SelectKBest(score_func=chi2, k=3)\n    fit = test.fit(X,y_reshaped)\n    print(\"Scores\")\n\n    univariate.append(fit.scores_)\n\n    features=fit.transform(X)\n    print(features[0:5,:])\n\n    print('*************************************************************')\n    print('Recursive Feature Elimination: top', n)\n    print()\n\n    model = LogisticRegression(solver='liblinear')\n\n    rfe = RFE(model, 3) #  we want to find the 3 top features\n    fit = rfe.fit(X, y_reshaped)\n\n    print(f'Number of features {fit.n_features_:d}')\n    print(f'Selected features {fit.support_}')\n    print(f'Ranking of features {fit.ranking_}')\n\n    rfe_ranking.append(fit.ranking_)\n    print()\n\n    print('*************************************************************')\n    print('ExtraTreeClassifier: top', n)\n\n    model = ExtraTreesClassifier(n_estimators=100, random_state=7)\n    model.fit(X,y_reshaped)\n\n    print(model.feature_importances_)\n    etc_features.append(model.feature_importances_)\n\nprint(times.head())\n    \nprint('top unis:', top_unis)\nprint(univariate)\nprint(rfe_ranking)\nprint(etc_features)\ntimes.head()\n# Answer for Univariate Selection. \n# First row is top 10, then top 50, then top 100\nunivariate\n# Answer for Recursive Feature Selection.\n# First row is top 10, then top 50, then top 100\nrfe_ranking\n# Answer for ExtraTreeClassifier\n# First row is top 10, then top 50, then top 100\netc_features\n\"\"\"\n# Model evaluation \n\"\"\"\n\"\"\"\n##\u00a0train-test-split and k-fold-10 validation for top 10, top 50 and top 100\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\ntop_unis = [10, 50, 100]\ntrain_test_split_accuracy = []\nk_fold_accuracy = []\n\nfor n in top_unis:\n\n    top_n = (n + 1) * (-1)\n\n    binarizer=Binarizer(threshold=top_n).fit(y_)\n    y_binary=binarizer.transform(y_)\n\n    y_reshaped = np.ravel(y_binary)\n    \n    print('*************************************************************')\n    print('train-test-split: top', n)\n    \n    # we need to make it reproducible, so we use a seed for the pseudo-random\n    test_size = 0.3\n    seed = 7\n\n    # the actual split\n    X_train, X_test, y_train, y_test = train_test_split(X, y_reshaped, test_size=test_size, random_state=seed)\n\n    # Let's do the log regresssion\n    model = LogisticRegression(solver='liblinear')\n    model.fit(X_train,y_train)\n\n    # Now let's find the accurary with the test split\n    result = model.score(X_test, y_test)\n    train_test_split_accuracy.append(result)\n\n    print(f'Accuracy {result*100:5.3f}')\n    print()\n    \n    print('*************************************************************')\n    print('k-fold-10 validation: top', n)\n    print()\n    \n    # KFold\n    splits = 10\n    kfold = KFold(n_splits=splits, random_state=seed)\n\n    #Logistic regression\n    model = LogisticRegression(solver='liblinear')\n\n    # Obtain the performance measure - accuracy\n    results = cross_val_score(model, X, y_reshaped, cv=kfold)\n    k_fold_accuracy.append(results.mean())\n    \n    print(f'Logistic regression, k-fold {splits:d} - Accuracy {results.mean()*100:5.3f}% ({results.std()*100:5.3f}%)')\n    print()\n    \n    \ntrain_test_accuracy = [ '%.3f' % elem for elem in train_test_split_accuracy]\nkfold_accuracy = [ '%.3f' % elem for elem in k_fold_accuracy]\n\nprint('Top unis: ', top_unis)\nprint(train_test_accuracy)\nprint(kfold_accuracy)\nprint('Accuracy decreases as the number of universities to be classified increases')\n\"\"\"\n# Metrics evaluation using StratifiedKFold\n\"\"\"\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\ntop_unis = [10, 50, 100]\nscoring = ['accuracy', 'neg_log_loss', 'roc_auc']\nk_fold_accuracy = []\n\nfor n in top_unis:\n\n    top_n = (n + 1) * (-1)\n\n    binarizer=Binarizer(threshold=top_n).fit(y_)\n    y_binary=binarizer.transform(y_)\n\n    y_reshaped = np.ravel(y_binary)\n\n    print('*************************************************************')\n    \n    for score in scoring:\n        \n        print('*************************************************************')\n        print(score, ', top', n)\n\n        # StratifiedKFold because top10 with kfold causes an error (bug)\n        splits = 10\n        skfold = StratifiedKFold(n_splits=splits, random_state=7)\n\n\n        #Logistic regression\n        model = LogisticRegression(solver='liblinear')\n\n        # Obtain the performance measure - accuracy\n        results = cross_val_score(model, X, y_reshaped, scoring=score, cv=skfold)\n\n        print(score, f': {results.mean():.3f}')\n        print()\n\n    print('*************************************************************')\n    print('Confusion Matrix, top', n)\n    \n    test_size=0.3\n    seed=7\n\n    X_train, X_test, Y_train, Y_test = train_test_split(X, y_reshaped, test_size=test_size, random_state=seed)\n\n    model = LogisticRegression(solver='liblinear')\n    log_reg = model.fit(X_train, Y_train)\n\n    Y_predicted = log_reg.predict(X_test)\n\n    c_matrix=confusion_matrix(Y_test, Y_predicted)\n\n    print(c_matrix)\n\n    print()\n    print(f'Accuracy {model.score(X_test, Y_test)*100:.3f}')\n    print(f'Accuracy check with conf. matrix {(c_matrix[0,0]+c_matrix[1,1])\/c_matrix.sum()*100:.3f}')\n    print()\n    \n    print('*************************************************************')\n    print('Classification Report, top', n)    \n    \n    report = classification_report(Y_test, Y_predicted, digits=3)\n    \n    print(f'Accuracy {model.score(X_test, Y_test)*100:.3f}')\n    print()\n    print(report)\n\nprint('All the scores decrease as the number of universities in the group to predict increases')","meta":"{'source': 'AI4Code', 'id': '3123324a967abd'}"}
{"id":"25069","text":"\"\"\"\n![title](https:\/\/pngriver.com\/wp-content\/uploads\/2018\/04\/Download-Twitter-PNG-HD-1-768x289.png \"Header\")\n\"\"\"\n\"\"\"\n<h1>Twitter Tweet's Model For Identifying Real Disaster Tweet's<\/h1>\n\"\"\"\n\"\"\"\n**Data Source :-** https:\/\/www.kaggle.com\/c\/nlp-getting-started\/data <br>\n\n**Twitter Tweet's Data Overview :-**<br>\n\nTwitter has become an important communication channel in times of emergency.\nThe ubiquitousness of smartphones enables people to announce an emergency they\u2019re observing in real-time. Because of this, more agencies are interested in programatically monitoring Twitter (i.e. disaster relief organizations and news agencies).\nBut, it\u2019s not always clear whether a person\u2019s words are actually announcing a disaster or what.\n\nSo, to indentify this I have build a machine learning model that predicts which Tweets are about real disasters and which one\u2019s aren\u2019t.\n\n***Number of Tweet's in Train Data-Set :-*** 7,613<br> \n***Number of Tweet's in Test Data-Set :-*** 3263<br>\n***Total Number of Tweet's :-*** 10,876<br>\n\n**Attribute's Information :-**<br>\n\n***1.*** id - a unique identifier for each tweet<br>\n***2.*** keyword - a particular keyword from the tweet (may be blank)<br>\n***3.*** location - the location the tweet was sent from (may be blank)<br>\n***4.*** text - the text of the tweet<br>\n***5.*** target - this denotes whether a tweet is about a real disaster (1) or not (0)<br>\n\n\"\"\"\n\"\"\"\n# 1. Importing Libraries :-\n\"\"\"\nimport numpy as np\nfrom bs4 import BeautifulSoup\nimport re\nfrom tqdm import tqdm\nimport string\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport nltk\nfrom matplotlib import rcParams\nfrom wordcloud import WordCloud\nfrom matplotlib import rc_params\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, roc_curve, classification_report\nfrom sklearn.metrics import precision_recall_curve, precision_score, recall_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom gensim.models import Word2Vec\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB, MultinomialNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom prettytable import PrettyTable\n%matplotlib inline\nrcParams[\"figure.figsize\"] = 8,8\nsns.set_style(\"darkgrid\")\n# plt.style.use('ggplot')\n\"\"\"\n# 2. Loading The Data-Set's :-\n\"\"\"\n\"\"\"\n***There are three files to load :-***<br><br>\n**2.1.** train.csv (consisting of {id, keyword, location, text, target} as columns)<br>\n**2.2.** test.csv  (consisting of {id, keyword, location, text} as columns)<br>\n**2.3.** y_test.csv  (consisting of target column of test.csv data)<br>\n\"\"\"\n\"\"\"\n# 2.1. Loading Train Data :-\n\"\"\"\ntrain = pd.read_csv(\"\/kaggle\/input\/nlp-getting-started\/train.csv\")\nprint(train.info())\ntrain.head()\n\"\"\"\nBy loading **train.csv** we can see through **train.info()** & through **train.head()** that there are columns having **missing values(NaN).**\n\"\"\"\n\"\"\"\n# 2.2. & 2.3. Loading Test Data with y_test Data :-\n\"\"\"\ntest = pd.read_csv(\"\/kaggle\/input\/nlp-getting-started\/test.csv\")\ny_test = pd.read_csv(\"\/kaggle\/input\/nlp-getting-started\/sample_submission.csv\")\n\n# Droping id column from y_test data-set as that same id is present in test data-set in same order.\ny_test = y_test.drop(\"id\", axis=1)\n\n# Joining test with y_test data-set to make a complete new test data-set.\ntest = pd.DataFrame.join(test, y_test)\nprint(test.info())\ntest.head()\n\"\"\"\nAfter creating a **New Test Data** we can see through **test.info()** & through **test.head()** that there are columns having **missing values(NaN)**.\n\"\"\"\nprint('There are {} rows and {} columns in train'.format(train.shape[0],train.shape[1]))\nprint('There are {} rows and {} columns in test'.format(test.shape[0],test.shape[1]))\n\"\"\"\nThere are **7613 rows** and **5 columns** in **Train**<br>\nThere are **3263 rows** and **5 columns** in **Test**\n\"\"\"\n\"\"\"\n# 3. Exploratory Data Analysis (EDA) :-<br>\n\n***Following are the parts of Exploratory Data Analysis (EDA) :-***<br><br>\n**3.1.** Heatmap For Finding Both Data-Frame's Missing Values<br>\n**3.2.** Top 10 Locations From Both Data Tweet's<br>\n**3.3.** Data Cleaning<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**3.3.1** Distribution Of Classes<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**3.3.2** Top 10 Keywords From Both Data Tweets<br>\n**3.4.** Data Pre-Processing<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**3.4.1.** Creating Final Data-Frame (Inclusive Of Train & Test Both)<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**3.4.2.** Top 15 Frequent Words In Tweet's<br><br>\nIn the following section I have tried to understand what data is about and what answers can I generate through some visual representations before & after Data Cleaning \/ Data Pre-Processing.\n\"\"\"\n\"\"\"\n# 3.1. Heatmap For Finding Both Data-Frame's Missing Values :-\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(10,10))\nsns.heatmap(train.isnull(), ax=axes[0]).set_title(\"Train Data-Frame\")\nsns.heatmap(test.isnull(), ax=axes[1]).set_title(\"Test Data-Frame\")\n\nplt.suptitle(\"Heatmap For Finding Both Data-Frame's Missing Values\", fontsize=25)\n# plt.tight_layout()\nplt.show()\n\"\"\"\n**Through Heatmap** we can see that there are many **missing values** in **location column** of both **Train & Test Data** and a few are in **keyword column** as well.<br><br> We will handle them in **Data Cleaning part.**\n\"\"\"\n\"\"\"\n# 3.2. Top 10 Locations From Both Data Tweet's :-\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(10,10))\ncommon_locations_train = train.location.value_counts()[:10]\ncommon_locations_test = test.location.value_counts()[:10]\nsns.barplot(x=common_locations_train, y=common_locations_train.index, ax=axes[0]).set_title(\"Train Data-Frame\")\nsns.barplot(x=common_locations_test, y=common_locations_test.index, ax=axes[1]).set_title(\"Test Data-Frame\")\nplt.suptitle(\"Top 10 Locations From Both Data Tweet's\", fontsize=20)\nplt.tight_layout(pad=6.0)\nplt.show()\n\"\"\"\nFrom the above diagram's we can see the most frequent locations from where the tweet's are actually posted on **Twitter** related to **Natural Disaster's**.<br><br>\nAnd we can easily conclude that in both of the data-set's **New York**, **USA**, **United States** & **Canada** are in the Top Five List.\n\"\"\"\n\"\"\"\n# 3.3. Data Cleaning :-\n\"\"\"\ntest = test.drop(\"location\", axis=1)\n\n# Droping the Missing Values \ntest = test.dropna(axis=0)\n\n# As Data's indexs are not in order so :\ntest = test.reset_index()\n\n# Now, droping the old indexs as it became a column\ntest = test.drop(\"index\", axis=1)\nprint(test.info())\ntest.head()\n\"\"\"\nAs we saw above that the **location** column in **Test Data** has too much missing value's.<br><br>\nSo, I am **droping** that column because that column doesn't also help us in any way to possibly predict whether a tweet is talking about a **real disaster or not**.\n\"\"\"\ntrain = train.drop(\"location\", axis=1)\n\n# Droping the Missing Values\ntrain = train.dropna(axis=0)\n\n# As Data's indexs are not in order so :\ntrain = train.reset_index()\n\n# Now, droping the old indexs as it became a column\ntrain = train.drop(\"index\", axis=1)\nprint(train.info())\ntrain.head()\n\"\"\"\nAs we saw above that the **location** column in **Train Data** has too much missing value's.<br><br>\nSo, I am **droping** that column because that column doesn't also help us in any way to possibly predict whether a tweet is talking about a **real disaster or not**.\n\"\"\"\n\"\"\"\n# 3.3.1. Distribution Of Classes :-\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(10,10))\nsns.barplot(x=train.target.value_counts().index, y=train.target.value_counts(), ax=axes[0]).set_title(\"Train Data-Frame\")\nsns.barplot(x=test.target.value_counts().index, y=test.target.value_counts(), ax=axes[1]).set_title(\"Test Data-Frame\")\nplt.suptitle(\"Distribution Of Classes\", fontsize=20)\nplt.tight_layout(pad=6.0)\nplt.show()\n\"\"\"\nHere we can see that our **classes are not much imbalanced** in **Train Data** & we can conclude that in our **Train Data only there are two classes like {0,1} whereas in our Test Data only 0 value target tweet's are stored.**<br><br>\nWe will handle that as well a little later after **Data Pre-Processing part.**\n\"\"\"\n\"\"\"\n# 3.3.2. Top 10 Keywords From Both Data Tweet's :-\n\"\"\"\nfig, axes = plt.subplots(1, 2, figsize=(10,10))\ncommon_keywords_train = train.keyword.value_counts()[:10]\ncommon_keywords_test = test.keyword.value_counts()[:10]\nsns.barplot(x=common_keywords_train, y=common_keywords_train.index, ax=axes[0]).set_title(\"Train Data-Frame\")\nsns.barplot(x=common_keywords_test, y=common_keywords_test.index, ax=axes[1]).set_title(\"Test Data-Frame\")\nplt.suptitle(\"Top 10 Keywords From Both Data Tweets\", fontsize=20)\nplt.tight_layout(pad=6.0)\nplt.show()\n\"\"\"\nFrom the above diagram's we can easily notice that there are **barely 2 to 3 keywords** which are **common** in both data-set's **Top 10 Keywords List**.<br><br>\nAnd these **Keywords** are even not playing any important role in predicting that whether a tweet is talking about a **real disaster or not**.\n\"\"\"\n\"\"\"\n# 3.4. Data Pre-Processing :-\n\"\"\"\nprint(train.text[20])\nprint(\"=\"*100)\nprint(train.text[120])\nprint(\"=\"*100)\nprint(train.text[220])\nprint(\"=\"*100)\nprint(train.text[320])\n\"\"\"\n**As** we can see here all the tweet's of **Train Data** are in a need of some **Polishing(Pre-Processing)** because there are various **stopwords, http:\/\/ tags & various punchuations** which aren't required while **predicting** that whether a **tweet** is talking about a **real disaster or not**.\n\"\"\"\nstopwords = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \"you're\", \"you've\", \"you'll\", \"you'd\", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', \"she's\", 'her', 'hers', 'herself', 'it', \"it's\", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', \"that'll\", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', \"don't\", 'should', \"should've\", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', \"aren't\", 'couldn', \"couldn't\", 'didn', \"didn't\", 'doesn', \"doesn't\", 'hadn', \"hadn't\", 'hasn', \"hasn't\", 'haven', \"haven't\", 'isn', \"isn't\", 'ma', 'mightn', \"mightn't\", 'mustn', \"mustn't\", 'needn', \"needn't\", 'shan', \"shan't\", 'shouldn', \"shouldn't\", 'wasn', \"wasn't\", 'weren', \"weren't\", 'won', \"won't\", 'wouldn', \"wouldn't\", \"like\", \"via\", \"u\", \"video\", \"would\", \"one\"]\n\"\"\"\nHere is the **list of words** which are **most frequently** used in any **english paragraph** or in a **group of sentences**, and which **doesn't** play any important role in **creating a model to predict anything**.<br> **So**, we are simply naming them as **stopwords** and in the **following line of codes** I will be **removing these stopwords** from our **Data of Tweet's**.\n\"\"\"\n# Pre_processing all the train data :-\nlemmatizer = WordNetLemmatizer()\ntrain.text = train.text.apply(lambda a: a.lower())\npreprocessed_train = []\nfor sentance in tqdm(train.text.values):\n    sentance = re.sub(r\"http\\S+\", \"\", sentance)\n    sentance = BeautifulSoup(sentance, 'lxml').get_text()\n    sentance = re.sub(\"\\S*\\d\\S*\", \"\", sentance).strip()\n    sentance = re.sub('[^A-Za-z]+', ' ', sentance)\n    \n    sentance = ' '.join(lemmatizer.lemmatize(e) for e in sentance.split() if e not in stopwords)\n    preprocessed_train.append(sentance.strip())\n\"\"\"\nThe above line of code ***Pre-Processed*** all the ***Train Data*** and ***stored*** it all in a list named ***preprocessed_train***.\n\"\"\"\nprint(preprocessed_train[20])\nprint(\"=\"*100)\nprint(preprocessed_train[120])\nprint(\"=\"*100)\nprint(preprocessed_train[220])\nprint(\"=\"*100)\nprint(preprocessed_train[320])\n\"\"\"\nNow we can see all our **Train Data** is **cleaned** and **Pre-Processed**.\n\"\"\"\nprint(test.text[20])\nprint(\"=\"*100)\nprint(test.text[120])\nprint(\"=\"*100)\nprint(test.text[220])\nprint(\"=\"*100)\nprint(test.text[320])\n\"\"\"\n**As** we can see here all the tweet's of **Test Data** are in a need of some **Polishing(Pre-Processing)** because there are various **stopwords, http:\/\/ tags & various punchuations** which aren't required while **predicting** that whether a **tweet** is talking about a **real disaster or not**.\n\"\"\"\n# Pre_processing all the test data :-\ntest.text = test.text.apply(lambda a: a.lower())\npreprocessed_test = []\nfor sentance in tqdm(test.text.values):\n    sentance = re.sub(r\"http\\S+\", \"\", sentance)\n    sentance = BeautifulSoup(sentance, 'lxml').get_text()\n    sentance = re.sub(\"\\S*\\d\\S*\", \"\", sentance).strip()\n    sentance = re.sub('[^A-Za-z]+', ' ', sentance)\n    \n    sentance = ' '.join(lemmatizer.lemmatize(e) for e in sentance.split() if e not in stopwords)\n    preprocessed_test.append(sentance.strip())\n\"\"\"\nThe above line of code ***Pre-Processed*** all the ***Test Data*** and ***stored*** it all in a list named ***preprocessed_test***.\n\"\"\"\nprint(preprocessed_test[20])\nprint(\"=\"*100)\nprint(preprocessed_test[120])\nprint(\"=\"*100)\nprint(preprocessed_test[220])\nprint(\"=\"*100)\nprint(preprocessed_test[320])\n\"\"\"\nNow we can see all our **Test Data** is **cleaned** and **Pre-Processed**.\n\"\"\"\n# Converting preprocessed_train List into a Series to join it back in Train Data : \nfinal_text_train = pd.Series(preprocessed_train)\nfinal_text_train.name = \"final_text\"\n\n# Joining Train Data with preprocessed_train Series & droping the old text(Tweet) column :\ntrain = pd.DataFrame.join(train, final_text_train)\ntrain = train.drop(\"text\", axis=1)\ntrain.info()\n# Converting preprocessed_test List into a Series to join it back in Test Data :\nfinal_text_test = pd.Series(preprocessed_test)\nfinal_text_test.name = \"final_text\"\n\n# Joining Test Data with preprocessed_test Series & droping the old text(Tweet) column :\ntest = pd.DataFrame.join(test, final_text_test)\ntest = test.drop(\"text\", axis=1)\ntest.info()\n\"\"\"\n# 3.4.1. Creating Final Data-Frame (Inclusive Of Train & Test Both):-\n\"\"\"\ndf = train.append(test, ignore_index=True)\n\n# Id & Keyword columns are not of any use for Creating Model or for any Prediction's :\ndf = df.drop([\"id\", \"keyword\"], axis=1)\n\nprint(df.info())\ndf.head()\nprint('Now there are {} rows & {} columns in train.'.format(train.shape[0],train.shape[1]))\nprint('Now there are {} rows & {} columns in test.'.format(test.shape[0],test.shape[1]))\nprint('Now there are {} rows & {} columns in df(The Final Data-Frame).'.format(df.shape[0],df.shape[1]))\n\"\"\"\n**Now** there are **7552 rows** & **4 columns** in **train**.<br>\n**Now** there are **3237 rows** & **4 columns** in **test**.<br><br>\n**And** there are **10789 rows** & **2 columns** in **df(The Final Data-Frame)**.\n\"\"\"\n\"\"\"\n# 3.4.2. Top 15 Frequent Words In Tweet's :-\n\"\"\"\nwords = []\nfor sentences in tqdm(df.final_text.values):\n    sentences = \"\".join(sentences.lower())\n    words.append(sentences)\nwords = ''.join(word for word in words)\nwords = nltk.word_tokenize(words)\nwords = pd.Series(words)\n\"\"\"\nIn the above line of code as we want to **plot a barplot** of some of the **most frequent words** in our whole **Data of Tweet's**.<br> **First** we will have to **join all the tweet's** with **lowering all the words and alphabet's** so that our system will easily find out the **words** which are **most frequently repeated**.<br> **Second**, we will have to **convert all the tweets** to **single-single words** to know the **frequency** of them, this can be done by using **nltk.word_tokenize()** and in the **last** we will convert all **single-single words** from a **list** to a **column** to apply a function called **value_counts()**.\n\"\"\"\nplt.figure(figsize=(10,10))\nsns.barplot(x=words.value_counts()[:15], y=words.value_counts()[:15].index)\nplt.title(\"Top 15 Frequent Words In Tweet's\", fontsize=20)\nplt.show()\n\"\"\"\nSo, we can see here the **words** which are widely used in our **Data of Tweet's**.\n\"\"\"\n\"\"\"\n# 4. Spliting Final Data-Frame Into Train, Cross-Validation,  Test :-\n\"\"\"\n# Defining Input & Output :\nX = df[\"final_text\"]\ny = df[\"target\"]\n\n# Spliting Final Data-Frame Into Train, Cross-Validation, Test :\nX_1, X_test, y_1, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\nX_train, X_cv, y_train, y_cv = train_test_split(X_1, y_1, test_size=0.2)\n\"\"\"\nHere I have used **train_test_split()** function to **break** my **Data of Tweet's** into **3 categories equally proportional to each class {0,1}** namely **:-**<br> {**Train** (For Training the Model), **Cross-Validation** (For cross checking the predictions) **&** **Test** (For final testing of our model)}.\n\"\"\"\n\"\"\"\n# 4.1. Equal Distribution Of Classes :-\n\"\"\"\nfig, axes = plt.subplots(2, 2, figsize=(10,10))\nsns.barplot(x=df.target.value_counts().index, y=df.target.value_counts(), ax=axes[0,0]).set_title(\"Final Data-Frame\")\nsns.barplot(x=y_train.value_counts().index, y=y_train.value_counts(), ax=axes[0,1]).set_title(\"Y_Train\")\nsns.barplot(x=y_cv.value_counts().index, y=y_cv.value_counts(), ax=axes[1,1]).set_title(\"Y_CV\")\nsns.barplot(x=y_test.value_counts().index, y=y_test.value_counts(), ax=axes[1,0]).set_title(\"Y_Test\")\nplt.suptitle(\"Distribution Of Classes\", fontsize=20)\nplt.tight_layout(pad=6.0)\nplt.show()\n\"\"\"\nAs we can see above all the **3 categories** are now having **equal proportion of {0,1} Classes.**<br><br>\nThis tells us that now our **Data** is all set to go for **Featurization** & then for **Creating Model by various Algorithms**.\n\"\"\"\nprint(\"Length Of X_train :-\", X_train.shape[0])\nprint(\"Length Of y_train :-\", y_train.shape[0])\nprint(\"Length Of X_test :-\", X_test.shape[0])\nprint(\"Length Of y_test :-\", y_test.shape[0])\nprint(\"Length Of X_cv :-\", X_cv.shape[0])\nprint(\"Length Of y_cv :-\", y_cv.shape[0])\n\"\"\"\n# 5. Featurization & Applying Algorithms :- \n\n\"\"\"\n\"\"\"\n***Following are the parts of my Featurization & Applying Algorithms section :-***<br>\n# 5.1.\nIn this part I am going to convert all my **Tweet's text Data into Vectors** using **Bag-Of-Words** represented by **bow** and then will apply following **Algorithms :-**<br><br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.1.1.** - **First** will apply **Logistic Regression** which is **represented** here by **log**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.1.2.** - **Second** will apply **Multi-Nomial Naive Bayes** which is **represented** here by **mnb**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.1.3.** - **Third** will apply **Decision-Tree Classifier** which is **represented** here by **dtc**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.1.4.** - **Fourth** there will be **Comaprison of Bag-Of-Words Test's** {To **find out** which **Algorithm** worked **best with Bag-Of-Words**}.\n\n# 5.2.\nIn this part I am going to convert all my **Tweet's text Data into Vectors** using **TF-IDF (Term Frequency - Inverse Document Frequency)** represented by **tfidf** and then will apply following **Algorithms :-**<br><br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.2.1.** - **First** will apply **Logistic Regression** which is **represented** here by **log**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.2.2.** - **Second** will apply **Multi-Nomial Naive Bayes** which is **represented** here by **mnb**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.2.3.** - **Third** will apply **Decision-Tree Classifier** which is **represented** here by **dtc**.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;**5.2.4.** - **Fourth** there will be **Comaprison of TF-IDF Test's** {To **find out** which **Algorithm** worked **best with TF-IDF**}.\n\n# 5.3\nHere in **Final Comparison** I will compare all the **selected Algorithms** which i will get from **both Featurization techniques {Bag-Of-Words & TF-IDF}** by **ROC & AUC Curve's**.\n\n# 5.4\nNow comes the **Conclusion** part where I will create a **Conclusion Table** with the help of **prettytable library** and will show the **results** of all of the **Algorithms** to **easily compare**.\n\"\"\"\n\"\"\"\n# 5.1. - Bag Of Words :-\n\"\"\"\nbow = CountVectorizer(ngram_range=(1,2), min_df=2)\nX_train_bow = bow.fit_transform(X_train).toarray()\nX_cv_bow = bow.transform(X_cv).toarray()\nX_test_bow = bow.transform(X_test).toarray()\n\"\"\"\nHere I have used **Bag-Of-Words** for **converting** all the **tweet's** from **text** to **vectors**. \n\"\"\"\n\"\"\"\n# 5.1.1. - Logisctic Regression :-\n\"\"\"\nlog = LogisticRegression()\nlog.fit(X_train_bow, y_train)\npre_cv_bow_log = log.predict(X_cv_bow)\npre_test_bow_log = log.predict(X_test_bow)\n\"\"\"\nAfter **training the model** with the help of **Bow & Logistic Regression** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"BOW CV Classification Report by Logistic Regression\")\nprint(classification_report(y_cv, pre_cv_bow_log))\nprint(\"=\"*100)\nprint(\"BOW Test Classification Report by Logistic Regression\")\nprint(classification_report(y_test, pre_test_bow_log))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test data**.\n\"\"\"\npreproba_cv_bow_log = log.predict_proba(X_cv_bow)[:,1]\npreproba_test_bow_log = log.predict_proba(X_test_bow)[:,1]\npreproba_train_bow_log = log.predict_proba(X_train_bow)[:,1]\n\nfpr_cv_bow_log_roc, tpr_cv_bow_log_roc, threshold_cv_bow_log_roc = roc_curve(y_cv, preproba_cv_bow_log)\nfpr_test_bow_log_roc, tpr_test_bow_log_roc, threshold_test_bow_log_roc = roc_curve(y_test, preproba_test_bow_log)\nfpr_train_bow_log_roc, tpr_train_bow_log_roc, threshold_train_bow_log_roc = roc_curve(y_train, preproba_train_bow_log)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_bow_log_roc,tpr_test_bow_log_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_log)*100))\nax.plot(fpr_cv_bow_log_roc, tpr_cv_bow_log_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_bow_log)*100))\nax.plot(fpr_train_bow_log_roc,tpr_train_bow_log_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train,preproba_train_bow_log)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\n\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_bow_log_pr, recall_test_bow_log_pr, threshold_test_bow_log_pr = precision_recall_curve(y_test, preproba_test_bow_log)\nprecision_cv_bow_log_pr, recall_cv_bow_log_pr, threshold_cv_bow_log_pr = precision_recall_curve(y_cv, preproba_cv_bow_log)\nprecision_train_bow_log_pr, recall_train_bow_log_pr, threshold_train_bow_log_pr = precision_recall_curve(y_train, preproba_train_bow_log)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_bow_log_pr, precision_test_bow_log_pr, label=\"Test\")\nax_1.plot(recall_cv_bow_log_pr, precision_cv_bow_log_pr, label=\"CV\")\nax_1.plot(recall_train_bow_log_pr, precision_train_bow_log_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_bow_log = confusion_matrix(y_test, pre_test_bow_log)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_bow_log, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\n\"\"\"\n# 5.1.2. - Naive Bayes {Multi-Nomial Naive Bayes}:-\n\"\"\"\nmnb = MultinomialNB()\nmnb.fit(X_train_bow, y_train)\npre_cv_bow_mnb = mnb.predict(X_cv_bow)\npre_test_bow_mnb = mnb.predict(X_test_bow)\n\"\"\"\nAfter **training the model** with the help of **Bow & Multi-Nomial Naive Bayes** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"BOW CV Classification Report by Multi-Nomial Naiye Bayes\")\nprint(classification_report(y_cv, pre_cv_bow_mnb))\nprint(\"=\"*100)\nprint(\"BOW Test Classification Report by Multi-Nomial Naiye Bayes\")\nprint(classification_report(y_test, pre_test_bow_mnb))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test data**.\n\"\"\"\npreproba_cv_bow_mnb = mnb.predict_proba(X_cv_bow)[:,1]\npreproba_test_bow_mnb = mnb.predict_proba(X_test_bow)[:,1]\npreproba_train_bow_mnb = mnb.predict_proba(X_train_bow)[:,1]\n\nfpr_cv_bow_mnb_roc, tpr_cv_bow_mnb_roc, threshold_cv_bow_mnb_roc = roc_curve(y_cv, preproba_cv_bow_mnb)\nfpr_test_bow_mnb_roc, tpr_test_bow_mnb_roc, threshold_test_bow_mnb_roc = roc_curve(y_test, preproba_test_bow_mnb)\nfpr_train_bow_mnb_roc, tpr_train_bow_mnb_roc, threshold_train_bow_mnb_roc = roc_curve(y_train, preproba_train_bow_mnb)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_bow_mnb_roc,tpr_test_bow_mnb_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_mnb)*100))\nax.plot(fpr_cv_bow_mnb_roc, tpr_cv_bow_mnb_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_bow_mnb)*100))\nax.plot(fpr_train_bow_mnb_roc, tpr_train_bow_mnb_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train, preproba_train_bow_mnb)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_bow_mnb_pr, recall_test_bow_mnb_pr, threshold_test_bow_mnb_pr = precision_recall_curve(y_test, preproba_test_bow_mnb)\nprecision_cv_bow_mnb_pr, recall_cv_bow_mnb_pr, threshold_cv_bow_mnb_pr = precision_recall_curve(y_cv, preproba_cv_bow_mnb)\nprecision_train_bow_mnb_pr, recall_train_bow_mnb_pr, threshold_train_bow_mnb_pr = precision_recall_curve(y_train, preproba_train_bow_mnb)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_bow_mnb_pr, precision_test_bow_mnb_pr, label=\"Test\")\nax_1.plot(recall_cv_bow_mnb_pr, precision_cv_bow_mnb_pr, label=\"CV\")\nax_1.plot(recall_train_bow_mnb_pr, precision_train_bow_mnb_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_bow_mnb = confusion_matrix(y_test, pre_test_bow_mnb)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_bow_mnb, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\n\"\"\"\n# 5.1.3. - Decision-Tree Classifier :-\n\"\"\"\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train_bow, y_train)\npre_cv_bow_dtc = dtc.predict(X_cv_bow)\npre_test_bow_dtc = dtc.predict(X_test_bow)\n\"\"\"\nAfter **training the model** with the help of **Bow & Decision-Tree Classifier** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"BOW CV Classification Report by Decision-Tree Classifier\")\nprint(classification_report(y_cv, pre_cv_bow_dtc))\nprint(\"=\"*100)\nprint(\"BOW Test Classification Report by Decision-Tree Classifier\")\nprint(classification_report(y_test, pre_test_bow_dtc))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test Data**.\n\"\"\"\npreproba_cv_bow_dtc = dtc.predict_proba(X_cv_bow)[:,1]\npreproba_test_bow_dtc = dtc.predict_proba(X_test_bow)[:,1]\npreproba_train_bow_dtc = dtc.predict_proba(X_train_bow)[:,1]\n\nfpr_cv_bow_dtc_roc, tpr_cv_bow_dtc_roc, threshold_cv_bow_dtc_roc = roc_curve(y_cv, preproba_cv_bow_dtc)\nfpr_test_bow_dtc_roc, tpr_test_bow_dtc_roc, threshold_test_bow_dtc_roc = roc_curve(y_test, preproba_test_bow_dtc)\nfpr_train_bow_dtc_roc, tpr_train_bow_dtc_roc, threshold_train_bow_dtc_roc = roc_curve(y_train, preproba_train_bow_dtc)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_bow_dtc_roc,tpr_test_bow_dtc_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_dtc)*100))\nax.plot(fpr_cv_bow_dtc_roc, tpr_cv_bow_dtc_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_bow_dtc)*100))\nax.plot(fpr_train_bow_dtc_roc, tpr_train_bow_dtc_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train, preproba_train_bow_dtc)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_bow_dtc_pr, recall_test_bow_dtc_pr, threshold_test_bow_dtc_pr = precision_recall_curve(y_test, preproba_test_bow_dtc)\nprecision_cv_bow_dtc_pr, recall_cv_bow_dtc_pr, threshold_cv_bow_dtc_pr = precision_recall_curve(y_cv, preproba_cv_bow_dtc)\nprecision_train_bow_dtc_pr, recall_train_bow_dtc_pr, threshold_train_bow_dtc_pr = precision_recall_curve(y_train, preproba_train_bow_dtc)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_bow_dtc_pr, precision_test_bow_dtc_pr, label=\"Test\")\nax_1.plot(recall_cv_bow_dtc_pr, precision_cv_bow_dtc_pr, label=\"CV\")\nax_1.plot(recall_train_bow_dtc_pr, precision_train_bow_dtc_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_bow_dtc = confusion_matrix(y_test, pre_test_bow_dtc)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_bow_dtc, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\"\"\"\n# 5.1.4. - Comaprison of Bag Of Words Test's :-\n\"\"\"\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_bow_log_roc,tpr_test_bow_log_roc, label='Logistic Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_log)*100))\nax.plot(fpr_test_bow_mnb_roc,tpr_test_bow_mnb_roc, label='Multi-Nomial Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_mnb)*100))\nax.plot(fpr_test_bow_dtc_roc,tpr_test_bow_dtc_roc, label='Decision-Tree Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_dtc)*100))\nplt.title('ROC Comparison of Logistic Vs Multi-Nomial Vs Decision-Tree in BOW', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\nfig = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_bow_log_pr, precision_test_bow_log_pr, label=\"Logistic Test PR Curve\")\nax_1.plot(recall_test_bow_mnb_pr, precision_test_bow_mnb_pr, label=\"Multi-Nomial Test PR Curve\")\nax_1.plot(recall_test_bow_dtc_pr, precision_test_bow_dtc_pr, label=\"Decision-Tree Test PR Curve\")\nplt.title('PR Curve Comparison of Logistic Vs Multi-Nomial Vs Decision-Tree in BOW', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax_1.legend()\nplt.show()\n\"\"\"\n# 5.2. - TF-IDF :-\n\"\"\"\ntfidf = TfidfVectorizer(ngram_range=(1,2), min_df=2)\nX_train_tfidf = tfidf.fit_transform(X_train).toarray()\nX_cv_tfidf = tfidf.transform(X_cv).toarray()\nX_test_tfidf = tfidf.transform(X_test).toarray()\n\"\"\"\nHere I have used **TF-IDF (Term Frequency - Inverse Term Frequency)** for **converting** all the **tweet's** from **text** to **vectors**. \n\"\"\"\n\"\"\"\n# 5.2.1. - Logisctic Regression :-\n\"\"\"\nlog = LogisticRegression()\nlog.fit(X_train_tfidf, y_train)\npre_cv_tfidf_log = log.predict(X_cv_tfidf)\npre_test_tfidf_log = log.predict(X_test_tfidf)\n\"\"\"\nAfter **training the model** with the help of **TF-IDF & Logistic Regression** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"TF-IDF CV Classification Report by Logistic Regresion\")\nprint(classification_report(y_cv, pre_cv_tfidf_log))\nprint(\"=\"*100)\nprint(\"TF-IDF Test Classification Report by Logistic Regresion\")\nprint(classification_report(y_test, pre_test_tfidf_log))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test data**.\n\"\"\"\npreproba_cv_tfidf_log = log.predict_proba(X_cv_tfidf)[:,1]\npreproba_test_tfidf_log = log.predict_proba(X_test_tfidf)[:,1]\npreproba_train_tfidf_log = log.predict_proba(X_train_tfidf)[:,1]\n\nfpr_cv_tfidf_log_roc, tpr_cv_tfidf_log_roc, threshold_cv_tfidf_log_roc = roc_curve(y_cv, preproba_cv_tfidf_log)\nfpr_test_tfidf_log_roc, tpr_test_tfidf_log_roc, threshold_test_tfidf_log_roc = roc_curve(y_test, preproba_test_tfidf_log)\nfpr_train_tfidf_log_roc, tpr_train_tfidf_log_roc, threshold_train_tfidf_log_roc = roc_curve(y_train, preproba_train_tfidf_log)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_tfidf_log_roc,tpr_test_tfidf_log_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_log)*100))\nax.plot(fpr_cv_tfidf_log_roc, tpr_cv_tfidf_log_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_tfidf_log)*100))\nax.plot(fpr_train_tfidf_log_roc,tpr_train_tfidf_log_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train,preproba_train_tfidf_log)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_tfidf_log_pr, recall_test_tfidf_log_pr, threshold_test_tfidf_log_pr = precision_recall_curve(y_test, preproba_test_tfidf_log)\nprecision_cv_tfidf_log_pr, recall_cv_tfidf_log_pr, threshold_cv_tfidf_log_pr = precision_recall_curve(y_cv, preproba_cv_tfidf_log)\nprecision_train_tfidf_log_pr, recall_train_tfidf_log_pr, threshold_train_tfidf_log_pr = precision_recall_curve(y_train, preproba_train_tfidf_log)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_tfidf_log_pr, precision_test_tfidf_log_pr, label=\"Test\")\nax_1.plot(recall_cv_tfidf_log_pr, precision_cv_tfidf_log_pr, label=\"CV\")\nax_1.plot(recall_train_tfidf_log_pr, precision_train_tfidf_log_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_tfidf_log = confusion_matrix(y_test, pre_test_tfidf_log)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_tfidf_log, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\n\"\"\"\n# 5.2.2. - Naive Bayes {Multi-Nomial Naive Bayes} :-\n\"\"\"\nmnb = MultinomialNB()\nmnb.fit(X_train_tfidf, y_train)\npre_cv_tfidf_mnb = mnb.predict(X_cv_tfidf)\npre_test_tfidf_mnb = mnb.predict(X_test_tfidf)\n\"\"\"\nAfter **training the model** with the help of **TF-IDF & Multi-Nomial Naive Bayes** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"TF-IDF CV Classification Report by Multi-Nomial Naive Bayes\")\nprint(classification_report(y_cv, pre_cv_tfidf_mnb))\nprint(\"=\"*100)\nprint(\"TF-IDF Test Classification Report by Multi-Nomial Naive Bayes\")\nprint(classification_report(y_test, pre_test_tfidf_mnb))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test data**.\n\"\"\"\npreproba_cv_tfidf_mnb = mnb.predict_proba(X_cv_tfidf)[:,1]\npreproba_test_tfidf_mnb = mnb.predict_proba(X_test_tfidf)[:,1]\npreproba_train_tfidf_mnb = mnb.predict_proba(X_train_tfidf)[:,1]\n\nfpr_cv_tfidf_mnb_roc, tpr_cv_tfidf_mnb_roc, threshold_cv_tfidf_mnb_roc = roc_curve(y_cv, preproba_cv_tfidf_mnb)\nfpr_test_tfidf_mnb_roc, tpr_test_tfidf_mnb_roc, threshold_test_tfidf_mnb_roc = roc_curve(y_test, preproba_test_tfidf_mnb)\nfpr_train_tfidf_mnb_roc, tpr_train_tfidf_mnb_roc, threshold_train_tfidf_mnb_roc = roc_curve(y_train, preproba_train_tfidf_mnb)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_tfidf_mnb_roc,tpr_test_tfidf_mnb_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_mnb)*100))\nax.plot(fpr_cv_tfidf_mnb_roc, tpr_cv_tfidf_mnb_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_tfidf_mnb)*100))\nax.plot(fpr_train_tfidf_mnb_roc,tpr_train_tfidf_mnb_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train,preproba_train_tfidf_mnb)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_tfidf_mnb_pr, recall_test_tfidf_mnb_pr, threshold_test_tfidf_mnb_pr = precision_recall_curve(y_test, preproba_test_tfidf_mnb)\nprecision_cv_tfidf_mnb_pr, recall_cv_tfidf_mnb_pr, threshold_cv_tfidf_mnb_pr = precision_recall_curve(y_cv, preproba_cv_tfidf_mnb)\nprecision_train_tfidf_mnb_pr, recall_train_tfidf_mnb_pr, threshold_train_tfidf_mnb_pr = precision_recall_curve(y_train, preproba_train_tfidf_mnb)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_tfidf_mnb_pr, precision_test_tfidf_mnb_pr, label=\"Test\")\nax_1.plot(recall_cv_tfidf_mnb_pr, precision_cv_tfidf_mnb_pr, label=\"CV\")\nax_1.plot(recall_train_tfidf_mnb_pr, precision_train_tfidf_mnb_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_tfidf_mnb = confusion_matrix(y_test, pre_test_tfidf_mnb)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_tfidf_mnb, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\n\"\"\"\n# 5.2.3. - Decision-Tree Classifier :-\n\"\"\"\ndtc = DecisionTreeClassifier()\ndtc.fit(X_train_tfidf, y_train)\npre_cv_tfidf_dtc = dtc.predict(X_cv_tfidf)\npre_test_tfidf_dtc = dtc.predict(X_test_tfidf)\n\"\"\"\nAfter **training the model** with the help of **TF-IDF & Decision-Tree Classifier** here in the above line of code I have stored **predictions** of **Cross-Validation & Test Data** for **further analysis**.\n\"\"\"\nprint(\"TF-IDF CV Classification Report by Decision-Tree Classifier\")\nprint(classification_report(y_cv, pre_cv_tfidf_dtc))\nprint(\"=\"*100)\nprint(\"TF-_IDF Test Classification Report by Decision-Tree Classifier\")\nprint(classification_report(y_test, pre_test_tfidf_dtc))\n\"\"\"\nWe can see many things from above **Classification Report's** like **Precision**, **Recall**, **F1-score**, **Accuracy** of both the predictions which we got from **Cross-Validation & Test data**.\n\"\"\"\npreproba_cv_tfidf_dtc = dtc.predict_proba(X_cv_tfidf)[:,1]\npreproba_test_tfidf_dtc = dtc.predict_proba(X_test_tfidf)[:,1]\npreproba_train_tfidf_dtc = dtc.predict_proba(X_train_tfidf)[:,1]\n\nfpr_cv_tfidf_dtc_roc, tpr_cv_tfidf_dtc_roc, threshold_cv_tfidf_dtc_roc = roc_curve(y_cv, preproba_cv_tfidf_dtc)\nfpr_test_tfidf_dtc_roc, tpr_test_tfidf_dtc_roc, threshold_test_tfidf_dtc_roc = roc_curve(y_test, preproba_test_tfidf_dtc)\nfpr_train_tfidf_dtc_roc, tpr_train_tfidf_dtc_roc, threshold_train_tfidf_dtc_roc = roc_curve(y_train, preproba_train_tfidf_dtc)\n\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_tfidf_dtc_roc,tpr_test_tfidf_dtc_roc, label='Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_dtc)*100))\nax.plot(fpr_cv_tfidf_dtc_roc, tpr_cv_tfidf_dtc_roc, label='CV ROC AUC ='+str(roc_auc_score(y_cv, preproba_cv_tfidf_dtc)*100))\nax.plot(fpr_train_tfidf_dtc_roc, tpr_train_tfidf_dtc_roc, label='Train ROC AUC ='+str(roc_auc_score(y_train, preproba_train_tfidf_dtc)*100))\nplt.title('ROC', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Receiver Operating Characteristic (ROC) Curve** on all the **threshold's** possible and then drew this above diagram from **Test, Train and Cross-Validation Data**.\n\"\"\"\nprecision_test_tfidf_dtc_pr, recall_test_tfidf_dtc_pr, threshold_test_tfidf_dtc_pr = precision_recall_curve(y_test, preproba_test_tfidf_dtc)\nprecision_cv_tfidf_dtc_pr, recall_cv_tfidf_dtc_pr, threshold_cv_tfidf_dtc_pr = precision_recall_curve(y_cv, preproba_cv_tfidf_dtc)\nprecision_train_tfidf_dtc_pr, recall_train_tfidf_dtc_pr, threshold_train_tfidf_dtc_pr = precision_recall_curve(y_train, preproba_train_tfidf_dtc)\nfig_1 = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_tfidf_dtc_pr, precision_test_tfidf_dtc_pr, label=\"Test\")\nax_1.plot(recall_cv_tfidf_dtc_pr, precision_cv_tfidf_dtc_pr, label=\"CV\")\nax_1.plot(recall_train_tfidf_dtc_pr, precision_train_tfidf_dtc_pr, label=\"Train\")\nplt.title('Precision-Recall Curve', fontsize=20)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\nax_1.legend()\nplt.show()\n\"\"\"\nIn the above line of code we plotted **Precision-Recall Curve** from **Test, Train and Cross-Validation Data**.\n\"\"\"\nconf_test_tfidf_dtc = confusion_matrix(y_test, pre_test_tfidf_dtc)\nclass_label = [\"1 (Positive)\", \"0 (Negative)\"]\ndf = pd.DataFrame(conf_test_tfidf_dtc, index = class_label, columns = class_label)\nsns.heatmap(df, annot = True,fmt=\"d\")\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"Predicted Label\")\nplt.xlabel(\"True Label\")\nplt.show()\n\"\"\"\n# 5.2.4. - Comparison of TF-IDF Test's :-\n\"\"\"\nfig = plt.figure()\nax = plt.subplot(111)\nax.plot(fpr_test_tfidf_log_roc,tpr_test_tfidf_log_roc, label='Logistic Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_log)*100))\nax.plot(fpr_test_tfidf_mnb_roc,tpr_test_tfidf_mnb_roc, label='Multi-Nomial Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_mnb)*100))\nax.plot(fpr_test_tfidf_dtc_roc,tpr_test_tfidf_dtc_roc, label='Decision-Tree Test ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_dtc)*100))\nplt.title('ROC Comparison of Logistic Vs Multi-Nomial Vs Decision-Tree in TF-IDF', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax.legend()\nplt.show()\nfig = plt.figure()\nax_1 = plt.subplot(111)\nax_1.plot(recall_test_tfidf_log_pr, precision_test_tfidf_log_pr, label=\"Logistic Test PR Curve\")\nax_1.plot(recall_test_tfidf_mnb_pr, precision_test_tfidf_mnb_pr, label=\"Multi-Nomial Test PR Curve\")\nax_1.plot(recall_test_tfidf_dtc_pr, precision_test_tfidf_dtc_pr, label=\"Decision-Tree Test PR Curve\")\nplt.title('PR Curve Comparison of Logistic Vs Multi-Nomial Vs Decision-Tree in TF-IDF', fontsize=20)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nax_1.legend()\nplt.show()\n\"\"\"\n# 5.3. - Final Comparison :-\n\"\"\"\nfig_2 = plt.figure(figsize=(15,15))\n\n# Ploting fig_2\nax_5 = plt.subplot(221)\nax_5.set_title(\"Comparing Logistic's\", fontsize=20)\nax_5.plot(fpr_test_tfidf_log_roc,tpr_test_tfidf_log_roc, label='Logistic TF-IDF ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_log)*100))\nax_5.plot(fpr_test_bow_log_roc,tpr_test_bow_log_roc, label='Logistic BOW ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_log)*100))\n\nax_6 = plt.subplot(222)\nax_6.set_title(\"Comparing Multi-Nomial Naive Baye's\", fontsize=20)\nax_6.plot(fpr_test_tfidf_mnb_roc,tpr_test_tfidf_mnb_roc, label='Multi-Nomial TF-IDF ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_mnb)*100))\nax_6.plot(fpr_test_bow_mnb_roc,tpr_test_bow_mnb_roc, label='Multi-Nomial BOW ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_mnb)*100))\n\nax_7 = plt.subplot(212)\nax_7.set_title(\"Finally Comparing Top ROC AUC Curve's\", fontsize=20)\nax_7.plot(fpr_test_tfidf_log_roc,tpr_test_tfidf_log_roc, label='Logistic TF-IDF ROC AUC ='+str(roc_auc_score(y_test,preproba_test_tfidf_log)*100))\nax_7.plot(fpr_test_bow_mnb_roc,tpr_test_bow_mnb_roc, label='Multi-Nomial BOW ROC AUC ='+str(roc_auc_score(y_test,preproba_test_bow_mnb)*100))\n\n\nax_5.legend()\nax_6.legend()\nax_7.legend()\nplt.suptitle('Final ROC AUC Comparison Of Logistic & Multi-Nomial In BOW Vs TF-IDF', fontsize=25)\nplt.show()\n\n\"\"\"\n# 5.4. - Conclusion :-\n\"\"\"\nx = PrettyTable()\nx.field_names = [\"Vectorizer\", \"Model\", \"AUC (in %)\", \"Precision Score (in %)\", \"Recall Score (in %)\"]\nx.add_row([\"BOW\", \"Logistic Regression\", round(roc_auc_score(y_test,preproba_test_bow_log)*100), round(precision_score(y_test,pre_test_bow_log)*100), round(recall_score(y_test,pre_test_bow_log)*100)])\nx.add_row([\"BOW\", \"Multi-Nomial Naive Bayes\", round(roc_auc_score(y_test,preproba_test_bow_mnb)*100), round(precision_score(y_test,pre_test_bow_mnb)*100), round(recall_score(y_test,pre_test_bow_mnb)*100)])\nx.add_row([\"BOW\", \"Decision-Tree Classifier\", round(roc_auc_score(y_test,preproba_test_bow_dtc)*100), round(precision_score(y_test,pre_test_bow_dtc)*100), round(recall_score(y_test,pre_test_bow_dtc)*100)])\nx.add_row([\"TF-IDF\", \"Logistic Regression\", round(roc_auc_score(y_test,preproba_test_tfidf_log)*100), round(precision_score(y_test,pre_test_tfidf_log)*100), round(recall_score(y_test,pre_test_tfidf_log)*100)])\nx.add_row([\"TF-IDF\", \"Multi-Nomial Naive Bayes\", round(roc_auc_score(y_test,preproba_test_tfidf_mnb)*100), round(precision_score(y_test,pre_test_tfidf_mnb)*100), round(recall_score(y_test,pre_test_tfidf_mnb)*100)])\nx.add_row([\"TF-IDF\", \"Decision-Tree Classifier\", round(roc_auc_score(y_test,preproba_test_tfidf_dtc)*100), round(precision_score(y_test,pre_test_tfidf_dtc)*100), round(recall_score(y_test,pre_test_tfidf_dtc)*100)])\nprint(x)\n\n\"\"\"\n***So, by all these Comparison's and by this Conclusion Table we can select the Best Algorithm with Best Featurization Technique which suit's our priorities \/ requirements {Like :- Some gives more priority to ROC-AUC or some give priority to Precision-Recall}.***\n\"\"\"\n\"\"\"\n![title](http:\/\/pluspng.com\/img-png\/thanks-png-hd-images-simple-graphic-tnku0195-640.png \"Header\")\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2e18e6f181f28d'}"}
{"id":"98495","text":"\"\"\"\n# Exploratory Data Analysis: an end-to-end example\n\n1. How to work with the filesystem\n2. How to work with CSV files\n3. How to do exploratory data analysis (EDA)\n4. How to display images in a grid\n5. How to create a Kaggle submission file\n\n<iframe width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/1vUeDkORVcA\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n\"\"\"\n\"\"\"\n## 1. How to work with the filesystem & directories\n\"\"\"\n# You can use shell commands with \"!\"\n!ls ..\/input\n# Pipe output to do basic analysis\n!ls ..\/input\/train\/ | wc -l\n!ls ..\/input\/train\/ | head\n!ls ..\/input\/train\/00070df0-bbc3-11e8-b2bc-ac1f6b6435d0_*.png\n# Better approach: use pathlib\nfrom pathlib import Path\n\nDATA_DIR = Path('..\/input')\nTRAIN_DIR = DATA_DIR\/'train'\nTEST_DIR = DATA_DIR\/'test'\nlist(set([str(fn).split('\/')[-1].split('_')[0] for fn in TEST_DIR.iterdir()]))[:10]\n# Use the full power of Python\ntest_ids = list(set([str(fn).split('\/')[-1].split('_')[0]  for fn in TEST_DIR.iterdir()]))\nprint('Test IDs:', len(test_ids))\ntest_ids[:10]\n# You can even create directories\nSUB_DIR = Path('files\/submissions')\nSUB_DIR.mkdir(parents=True, exist_ok=True)\n!ls files\n\"\"\"\nLearn more here: https:\/\/docs.python.org\/3\/library\/pathlib.html\n\"\"\"\n\"\"\"\n## 2. How to work with CSV files\n\"\"\"\n# You could always use shell commands\nLABELS_CSV = DATA_DIR\/'train.csv'\n!head {LABELS_CSV}\n# Enter pandas\nimport pandas as pd\n\ntrain_df = pd.read_csv(LABELS_CSV, index_col='Id')\ntrain_df.head(10)\n# You can look at a random sample\ntrain_df.sample(10)\n# Or get basic information about the data\ntrain_df.info()\n# Use Python to your advantage\ntrain_df['Target'] = train_df['Target'].str.split(' ').map(lambda x: list(map(int, x)))\ntrain_df.head(10)\n\"\"\"\n## 3. How to do Exploratory Data Analysis (EDA)\n\nPandas dataframe is a great starting point for doing EDA. It provides many utilities for plotting graphs right out of the box.\n\"\"\"\nlabel_names = [\"Nucleoplasm\", \"Nuclear membrane\", \"Nucleoli\", \"Nucleoli fibrillar center\", \n               \"Nuclear speckles\", \"Nuclear bodies\", \"Endoplasmic reticulum\", \n               \"Golgi apparatus\", \"Peroxisomes\", \"Endosomes\",\"Lysosomes\", \n               \"Intermediate filaments\", \"Actin filaments\", \"Focal adhesion sites\", \n               \"Microtubules\", \"Microtubule ends\", \"Cytokinetic bridge\", \"Mitotic spindle\", \n               \"Microtubule organizing center\", \"Centrosome\", \"Lipid droplets\", \n               \"Plasma membrane\", \"Cell junctions\", \"Mitochondria\", \"Aggresome\",   \n               \"Cytosol\", \"Cytoplasmic bodies\", \"Rods & rings\"]\nimport numpy as np\n\ndef get_label_freqs(targets, label_names, ascending=None):\n    n_classes = len(label_names)\n    freqs = np.array([0] * n_classes)\n    for lst in targets:\n        for c in range(n_classes):\n            freqs[c] += c in lst\n    data = {\n        'name': label_names, \n        'frequency': freqs, \n        'percent': (10000 * freqs \/ len(targets)).astype(int) \/ 100.,\n    }\n    cols = ['name', 'frequency', 'percent']\n    df = pd.DataFrame(data, columns=cols)\n    if ascending is not None:\n        df = df.sort_values(by='frequency', ascending=ascending)\n    return df\n# Create a frequency table\ntrain_freqs = get_label_freqs(train_df.Target, label_names, ascending=False)\ntrain_freqs\n\"\"\"\nClearly, there is a huge imbalance between the classes, and **15 of the 28 classes have less than 900 samples (~ 3% of the data)**, and 9 classes have fewer than 330 samples (~1% of the data). Any model which always predicts 0 or 'not present' for these classes is already 97% accurate.\n\nSo, it's going to be really difficult to train a model that can detect the less frequently occuring classes. This may lead to a recall of 0, which will lead to and F1 score of 0 for these classes, thus putting a ceiling of 0.465 on the evaluation metric. In fact, we might need to train a separate model for these classes.\n\"\"\"\n# Visualize the frequency table using a chart\ntrain_freqs.plot(x='name', y='frequency', kind='bar', title='Name vs. Frequency');\n# Use logarithmic axis for easier interpretation\ntrain_freqs.plot(x='name', y='frequency', kind='bar', logy=True, title='Name vs. log(Frequency)');\n\"\"\"\n## 4. How to display an image, or show multiple images in a grid?\n\"\"\"\ntrain_sample = \"ac39847a-bbb1-11e8-b2ba-ac1f6b6435d0_red.png\"\nfrom imageio import imread\nimport matplotlib.pyplot as plt\n\n# Look at one channel\/filter\nimg0 = imread(str(TRAIN_DIR\/train_sample))\nprint(img0.shape)\nplt.imshow(img0)\nplt.title(train_sample[0]);\n# Use a color map for grayscale images\nplt.imshow(img0, cmap=\"Reds\");\n# For RGB images, it \"just works\"\n!curl https:\/\/www.what-dog.net\/Images\/faces2\/scroll001.jpg -o sample.jpg\n\nimg = imread('sample.jpg')\nplt.imshow(img);\n!ls {TRAIN_DIR}\/ac39847a-bbb1-11e8-b2ba-ac1f6b6435d0_*.png\nCHANNELS = ['green', 'red', 'blue', 'yellow']\n\n# Load images for multiple channels\ndef load_image(image_id, channels=CHANNELS, img_dir=TRAIN_DIR):\n    image = np.zeros(shape=(len(channels),512,512))\n    for i, ch in enumerate(channels):\n        image[i,:,:] = imread(str(img_dir\/f'{image_id}_{ch}.png'))\n    return image\n# Plot multiple images in a grid\ndef show_image_filters(image, title, figsize=(16,5)):\n    fig, subax = plt.subplots(1, 4, figsize=figsize)\n    # Green channel\n    subax[0].imshow(image[0], cmap=\"Greens\")\n    subax[0].set_title(title)\n    # Red channel\n    subax[1].imshow(image[1], cmap=\"Reds\")\n    subax[1].set_title(\"Microtubules\")\n    # Blue channel\n    subax[2].imshow(image[2], cmap=\"Blues\")\n    subax[2].set_title(\"Nucleus\")\n    # Orange channel\n    subax[3].imshow(image[3], cmap=\"Oranges\")\n    subax[3].set_title(\"Endoplasmatic reticulum\")\n    return subax\n# Use the traning data to show appropriate labels\ndef get_labels(image_id):\n    labels = [label_names[x] for x in train_df.loc[image_id]['Target']]\n    return ', '.join(labels)\n# Look at a sample grid\nimg_id = 'ac39847a-bbb1-11e8-b2ba-ac1f6b6435d0'\nimg, title = load_image(img_id), get_labels(img_id)\nshow_image_filters(img, title);\nprint(img.shape)\n# Combine with pandas to view a random sample\nfor img_id in train_df.sample(3).index:\n    print(img_id)\n    img, title = load_image(img_id), get_labels(img_id)\n    show_image_filters(img, title)\n\"\"\"\n## 5. How to generate a submission file?\n\"\"\"\n# Let's define a sophisticated and highly accurate model\ndef model(inputs):\n    return np.random.randn(len(inputs), len(label_names))\n# Generate some predictions (logits)\npreds = model(test_ids)\nprint(preds.shape)\nprint(preds)\n# Convert them into probabilities\ndef sigmoid(x):\n    return np.reciprocal(np.exp(-x) + 1) \n\nprobs = sigmoid(preds)\nprobs\n# Convert probabilities into labels\ndef make_labels(y, thres=0.5):\n    return ' '.join([str(i) for i, p in enumerate(y) if p > thres])\n\nmake_labels(probs[0])\n# Create a pandas dataframe\nlabels = list(map(make_labels, probs))\nsub_df = pd.DataFrame({ 'Id': test_ids, 'Predicted': labels}, columns=['Id', 'Predicted'])\nsub_df.head(10)\n# Export it to a file and make sure it looks okay\nsub_fname = SUB_DIR\/'basic.csv'\nsub_df.to_csv(sub_fname, index=None)\n\n!head {sub_fname}\n# Use FileLink to download the file\nfrom IPython.display import FileLink\n\nFileLink(sub_fname)\n\"\"\"\nThe last but **MOST IMPORTANT** step is to take all of the above code (once it works as expected), and wrap it into a function (or two)\n\"\"\"\ndef make_sub(fname):\n    preds = model(test_ids)\n    probs = sigmoid(preds)\n    labels = list(map(make_labels, probs))\n    sub_df = pd.DataFrame({ 'Id': test_ids, 'Predicted': labels}, columns=['Id', 'Predicted'])\n    fpath = SUB_DIR\/fname\n    sub_df.to_csv(fpath, index=None)\n    !head {fpath}\n    return FileLink(fpath)\nmake_sub('best_submission.csv')\n\"\"\"\nNow you can generate test predictions with a single line of code!\n\"\"\"\n\"\"\"\n# Save and commit\nFinally, we you save and commit out work using Jovian, so that anyone (including you), can reproduce it later with a single command, on any machine.\n\"\"\"\n!pip install jovian --upgrade -q\nimport jovian\njovian.commit()","meta":"{'source': 'AI4Code', 'id': 'b4f584cc205b40'}"}
{"id":"54347","text":"import numpy as np \nimport pandas as pd \nimport plotly.express as px\nimport plotly.graph_objects as go\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\nstud= pd.read_csv(\"\/kaggle\/input\/students-performance-in-exams\/StudentsPerformance.csv\")\n\"\"\"\n# Bubble Chart\n\"\"\"\nfig = go.Figure(data=[go.Scatter(\n    x=[1, 2, 3, 4], y=[10, 12, 15, 16],\n    mode='markers',\n    marker_size=[20, 40, 50, 60])\n])\n\nfig.show()\nfig = go.Figure(data=[go.Scatter(\n    x=[1, 2, 3, 4], y=[8, 10, 11, 12],\n    mode='markers',\n    marker=dict(\n        color=['red', 'cyan',\n               'blue', 'yellow'],\n        opacity=[1, 0.8, 0.6, 0.4],\n        size=[40, 60, 65, 70],\n    )\n)])\n\nfig.show()\ndf = px.data.gapminder()\n\nfig = px.scatter(df.query(\"year==2007\"), x=\"gdpPercap\", y=\"lifeExp\",    size=\"pop\", color=\"continent\",\n                 hover_name=\"country\", log_x=True, size_max=60)\nfig.show()\ntips = px.data.tips()\ntips.head()\nfig = px.scatter(tips, x=\"total_bill\", y=\"size\",    size=\"tip\", color=\"tip\",\n                  size_max=20)\nfig.show()\nfig = px.scatter(tips, x=\"total_bill\", y=\"tip\",    size=\"size\", color=\"tip\",\n                  size_max=20)\nfig.show()\nfig = px.scatter(tips, x=\"tip\", y=\"size\",    size=\"total_bill\", color=\"total_bill\",\n                  size_max=30)\nfig.show()\n\"\"\"\n# Dot Plots\n\"\"\"\nstud.head()\nfig = px.scatter(stud, x=\"math score\", y=\"parental level of education\", color=\"gender\",\n                 title=\"Student Performance in Exams\"\n                )\n\nfig.show()\nfig = px.scatter(stud, x=\"reading score\", y=\"parental level of education\", color=\"test preparation course\",\n                 title=\"Student Performance in Exams\"\n                )\n\nfig.show()\nfig = px.scatter(stud, x=\"writing score\", y=\"parental level of education\", color=\"lunch\",\n                 title=\"Student Performance in Exams\"\n                )\n\nfig.show()\n\"\"\"\n# Horizontal Bar Chart \n\"\"\"\nfig = go.Figure(go.Bar(\n            x=[20, 14, 23],\n            y=['Honda', 'Suzuki', 'Yamaha'],\n            orientation='h'))\n\nfig.show()\ndf = px.data.tips()\nfig = px.bar(df, x=\"total_bill\", y=\"day\", orientation='h')\nfig.show()\nfig = px.bar(df, x=\"total_bill\", y=\"sex\", color='day', orientation='h',\n             hover_data=[\"tip\", \"size\"],\n             height=400,\n             title='Restaurant bills')\nfig.show()\nstud.info()\nfig = px.bar(stud, x=\"math score\", y=\"parental level of education\", orientation='h')\nfig.show()\nfig = px.bar(stud, x=\"reading score\", y=\"parental level of education\",color='gender', orientation='h')\nfig.show()\nfig = px.bar(stud, x=\"writing score\", y=\"parental level of education\",color='lunch', orientation='h')\nfig.show()\nfig = px.bar(stud, x=\"writing score\", y=\"parental level of education\",color='test preparation course', orientation='h')\nfig.show()\n\"\"\"\n# Gantt Chart\n\"\"\"\ndf = pd.DataFrame([\n    dict(Task=\"Development\", Start='2012-01-20', Finish='2012-02-20'),\n    dict(Task=\"Website Design\", Start='2012-01-10', Finish='2012-01-30'),\n    dict(Task=\"Deployment\", Start='2012-02-20', Finish='2012-03-30'),\n    dict(Task=\"Marketing\", Start='2012-02-25', Finish='2012-04-15')\n])\n\nfig = px.timeline(df, x_start=\"Start\", x_end=\"Finish\", y=\"Task\")\nfig.update_yaxes(autorange=\"reversed\") \nfig.show()\ndf = pd.DataFrame([\n    dict(Task=\"Development\", Start='2012-01-20', Finish='2012-02-20', Team=\"Team A\"),\n    dict(Task=\"Website Design\", Start='2012-01-10', Finish='2012-01-30', Team=\"Team B\"),\n    dict(Task=\"Deployment\", Start='2012-02-20', Finish='2012-03-30', Team=\"Team A\"),\n    dict(Task=\"Marketing\", Start='2012-02-25', Finish='2012-04-15', Team=\"Team C\")\n])\n\nfig = px.timeline(df, x_start=\"Start\", x_end=\"Finish\", y=\"Task\", color=\"Team\")\nfig.update_yaxes(autorange=\"reversed\") \nfig.show()\ndf = pd.DataFrame([\n    dict(Task=\"Development\", Start='2012-01-20', Finish='2012-02-20', Team=\"Team A\",Team_Size=20),\n    dict(Task=\"Website Design\", Start='2012-01-10', Finish='2012-01-30', Team=\"Team B\",Team_Size=15),\n    dict(Task=\"Deployment\", Start='2012-02-20', Finish='2012-03-30', Team=\"Team A\",Team_Size=20),\n    dict(Task=\"Marketing\", Start='2012-02-25', Finish='2012-04-15', Team=\"Team C\",Team_Size=32)\n])\n\nfig = px.timeline(df, x_start=\"Start\", x_end=\"Finish\", y=\"Task\",color=\"Team_Size\")\nfig.update_yaxes(autorange=\"reversed\") \nfig.show()","meta":"{'source': 'AI4Code', 'id': '640bc9c0abdff2'}"}
{"id":"121474","text":"\"\"\"\n**The goal of this analysis is to find out how a country\u2019s diet correlates with its COVID-19 mortality rate. With different food cultures across the world, it would be interesting to see what are the food categories that can best predict a country\u2019s rate of deaths. **\n\"\"\"\n\"\"\"\n# Import packages\n\"\"\"\n! pip install pandas numpy matplotlib plotly dash-core-components scikit-learn dash missingpy yellowbrick\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport dash_core_components as dcc\nimport sklearn\nimport plotly.figure_factory as ff\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\"\"\"\n# Data Exploratory and Analysis\n\"\"\"\ndf_fat_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Fat_Supply_Quantity_Data.csv')\ndf_food_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Food_Supply_Quantity_kg_Data.csv')\ndf_food_kcal = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Food_Supply_kcal_Data.csv')\ndf_protein_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Protein_Supply_Quantity_Data.csv')\ndf_food_description = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Supply_Food_Data_Descriptions.csv')\n\"\"\"\n### Food Quantity Data \n\"\"\"\ndf_food_quantity.describe()\nx=df_food_quantity.corr(method='pearson').round(3)\nff.create_annotated_heatmap(z=x[['Deaths']].sort_values(by=['Deaths'],ascending=False).values, x = ['Deaths'], y=x[['Deaths']].sort_values(by=['Deaths'],ascending=False).index.to_list(), showscale=True, colorscale='Viridis')\nx=df_food_quantity.corr(method='pearson').round(3)\nff.create_annotated_heatmap(z=x.values, x = x.index.tolist(), y=x.index.to_list(), showscale=True, colorscale='Viridis')\ndf_food_quantity.Deaths = df_food_quantity.Deaths.astype(np.float32)*100.0\ndf_food_quantity.Deaths = df_food_quantity.Deaths.map(lambda val: np.log(val + 1))\ndf_food_quantity['Undernourished'] = df_food_quantity.apply(lambda row: 2.5 if row['Undernourished'] == '<2.5' else float(row['Undernourished']), axis = 1)\n\"\"\"\n#### Distributions  \n\"\"\"\nfor feature_name in [\"Oilcrops\",'Alcoholic Beverages', 'Animal fats', 'Animal Products','Milk - Excluding Butter', 'Obesity', 'Vegetal Products']:\n    fig = go.Figure(px.histogram(df_food_quantity[feature_name],nbins=7))\n    fig.show()\n\"\"\"\nBy visualizing the histograms we can conclude the following:\n\nAnimal Products, Obesity and Vegetal Products have a roughly normal distribution. We'll probably just scale their values using z-score formula.\nAlcoholic Beverages, Animal Fats, Milk - Excluding Butter,  on the other hand, present a right skewed distribution. Maybe a log scalling we'll help us getting a normal distribution for those two features.\n\"\"\"\ndf_food_quantity = df_food_quantity.drop('Unit (all except Population)', axis=1)\ndf_food_quantity = df_food_quantity.dropna()\ndf_food_quantity.iloc[:,1:24] = df_food_quantity.iloc[:, 1:24] * 2\n# Mortality  = Deaths \/ Confirmed\ndf_food_quantity['Mortality'] = df_food_quantity['Deaths'] \/ df_food_quantity['Confirmed']\n# Distributions\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Confirmed\").update_xaxes(categoryorder=\"total descending\")\nfig.show()\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Deaths\").update_xaxes(categoryorder=\"total descending\")\nfig.show()\n# Distributions\n\n#Yemen data seem to be so over-evalued\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Mortality\").update_xaxes(categoryorder=\"total descending\")\nfig.show()\nfig = px.scatter(df_food_quantity, x=\"Confirmed\", y = \"Deaths\",size = \"Active\", hover_name='Country', log_x=False,\n                 size_max=30, trendline = \"ols\", marginal_x = \"box\",marginal_y = \"violin\", template=\"simple_white\")\nfig.show()\n# Investigate: does obesity rate affect impact of COVID-19\nfig = px.scatter(df_food_quantity[df_food_quantity.Country != 'Yemen'], x=\"Mortality\", y = \"Obesity\", size = \"Active\", hover_name='Country', log_x=False,\n                 size_max=30, template=\"simple_white\")\n\nfig.add_shape(\n        # Line Horizontal\n            type=\"line\",\n            x0=0,\n            y0=df_food_quantity[df_food_quantity.Country != 'Yemen']['Obesity'].mean(),\n            x1=df_food_quantity[df_food_quantity.Country != 'Yemen']['Mortality'].max(),\n            y1=df_food_quantity[df_food_quantity.Country != 'Yemen']['Obesity'].mean(),\n            line=dict(\n                color=\"crimson\",\n                width=4\n            ),\n    )\n\nfig.show()\nfig = px.scatter(df_food_quantity, x=\"Deaths\", y = \"Obesity\", size = \"Mortality\", hover_name='Country', log_x=False,\n                 size_max=30, template=\"simple_white\")\n\nfig.add_shape(\n        # Line Horizontal\n            type=\"line\",\n            x0=0,\n            y0=df_food_quantity['Obesity'].mean(),\n            x1=df_food_quantity['Deaths'].max(),\n            y1=df_food_quantity['Obesity'].mean(),\n            line=dict(\n                color=\"crimson\",\n                width=4\n            ),\n    )\n\nfig.show()\n\"\"\"\nConclusion: The \"high mortality\" and \"high death rate\" countries all seem to have an above average obesity rate.\n\"\"\"\n\"\"\"\n### Animal Products:  Which products make the difference between High and Low Obesity countries  ?\n\"\"\"\ndf_high_ob = df_food_quantity[df_food_quantity.Obesity > df_food_quantity['Obesity'].mean()]\ndf_low_ob = df_food_quantity[df_food_quantity.Obesity <= df_food_quantity['Obesity'].mean()]\nanimal_features = ['Animal fats', 'Aquatic Products, Other', 'Eggs', 'Fish, Seafood', 'Meat',\n                   'Milk - Excluding Butter', 'Offals']\nvegetal_features = ['Alcoholic Beverages', 'Cereals - Excluding Beer', 'Fruits - Excluding Wine', 'Miscellaneous', 'Oilcrops', 'Pulses',\n                    'Spices', 'Starchy Roots', 'Stimulants', 'Sugar & Sweeteners', 'Sugar Crops', 'Treenuts',\n                    'Vegetable Oils', 'Vegetables']\n\"\"\"\n#### High obesity rates countries : Animal products\n\"\"\"\nfig = px.pie(values = df_high_ob[animal_features].mean().tolist(), names = animal_features,\n             title='Mean food intake by Animal products groups - High Obesity Countries')\nfig.show()\nfig = px.pie(values = df_low_ob[animal_features].mean().tolist(), names = animal_features,\n             title='Mean food intake by Animal products groups - Low Obesity Countries')\nfig.show()\n\"\"\"\nAnalysis: The distributions are somewhat similar. The order of highest to lowest intake is the same (except for Offals and Animal fats). However, two things stand out:\n\nThe Milk - Excluding Butter intake int he first group is huge (almost  60% !)\nThe difference between the Fish, Seafood intake in both groups (the first - around  7% , the second - around  20% ).\n\"\"\"\n\"\"\"\n#### Vegetal products\n\"\"\"\nfig = px.pie(values = df_high_ob[vegetal_features].mean().tolist(), names = vegetal_features,\n             title='Mean food intake by Vegetal products groups - High Obesity Countries')\nfig.show()\n\nfig = px.pie(values = df_low_ob[vegetal_features].mean().tolist(), names = vegetal_features,\n             title='Mean food intake by Vegetal products groups - Low Obesity Countries')\nfig.show()\n\"\"\"\nThe intake of Starchy Roots in Low Obesity Countries is almost  20% , double that of High Obesity Countries.\nThe intake of Alcoholic Beverages is at  5.8%  in Low Obesity Countries, as in High Obesity Countries it reaches almost  10% .\n\"\"\"\n\"\"\"\n#### Obesity between countries High or Low Obesity  ? \n\"\"\"\ndf_food_quantity['ObesityAboveAverage'] = (df_food_quantity[\"Obesity\"] > df_food_quantity['Obesity'].mean()).astype(int)\nfig = px.scatter(df_food_quantity, x = 'Animal Products', y ='Vegetal Products',\n                 color='ObesityAboveAverage', hover_name = 'Country')\nfig.show()\n\"\"\"\nAnalysis: we see there is a relation between high consuption of Animal Products (comparing with Vegetal Products) and high obesity rates. Using the hover information you can find the country with highest Animal Products intake (Finland) and the one with highest Vegetal Products intake (Nigeria).\n\"\"\"\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Deaths\", facet_col = \"ObesityAboveAverage\")\nfig.update_xaxes(matches=None,categoryorder=\"total descending\")\nfig.show()\n\"\"\"\nIn the figure above, we can see clearly that the \"high obesity rate\" countries have a worst impact from COVID-19.\n\"\"\"\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Confirmed\", facet_col = \"ObesityAboveAverage\")\nfig.update_xaxes(matches=None,categoryorder=\"total descending\")\nfig.show()\nfig = px.bar(df_food_quantity, x = \"Country\", y =\"Recovered\", facet_col = \"ObesityAboveAverage\")\nfig.update_xaxes(matches=None,categoryorder=\"total descending\")\nfig.show()\n\"\"\"\n## Goal: predict Mortality \n\"\"\"\nfig = px.scatter_matrix(df_food_quantity[['Meat', 'Milk - Excluding Butter', 'Fish, Seafood',\n                         'Cereals - Excluding Beer', 'Obesity','Mortality']])\nfig.show()\n\"\"\"\nSo, we are interested in the last \"row\" of this matrix. Nothing seems particularly linear, but we'll see what we can tell from building linear models.\n\"\"\"\n\"\"\"\n### Diet vs COVID19 \n\"\"\"\ncorr_food=df_food_quantity.loc[:, df_food_quantity.columns != 'ObesityAboveAvg'].corr(method='pearson')\ncorr_final=corr_food.abs().unstack().sort_values(ascending = False)\ncorr_final.drop(corr_final.head(32).index, inplace=True)\ncorr_confirmed = corr_final['Confirmed'].head(15)\ncorr_confirmed = corr_confirmed.drop(['Recovered', 'Deaths', 'Active', 'Undernourished', 'Obesity'])\ncorr_deaths = corr_final['Deaths'].head(15)\ncorr_deaths = corr_deaths.drop(['Recovered', 'Confirmed', 'Active', 'Undernourished', 'Obesity'])\ncorr_recovered = corr_final['Recovered'].head(14)\ncorr_recovered = corr_recovered.drop(['Confirmed', 'Deaths', 'Undernourished', 'Obesity'])\ncorr_heatmap=df_food_quantity[['Deaths','Animal Products','Animal fats','Cereals - Excluding Beer','Eggs','Meat','Milk - Excluding Butter','Pulses','Starchy Roots','Sugar & Sweeteners','Vegetal Products']]\nx=corr_heatmap.corr(method='pearson')\nfig = go.Figure(ff.create_annotated_heatmap(z=x[['Deaths']].sort_values(by=['Deaths'],ascending=False).values, x = ['Deaths'], y=x[['Deaths']].sort_values(by=['Deaths'],ascending=False).index.to_list(), colorscale='Viridis'))\nfig.show()\n\ncorr_heatmap=df_food_quantity[['Confirmed','Animal Products','Animal fats','Cereals - Excluding Beer','Eggs','Meat','Milk - Excluding Butter','Pulses','Starchy Roots','Sugar & Sweeteners','Vegetal Products']]\nx=corr_heatmap.corr(method='pearson')\nfig = go.Figure(ff.create_annotated_heatmap(z=x[['Confirmed']].sort_values(by=['Confirmed'],ascending=False).values, x = ['Confirmed'], y=x[['Confirmed']].sort_values(by=['Confirmed'],ascending=False).index.to_list(), colorscale='Viridis'))\nfig.show()\n\ncorr_heatmap=df_food_quantity[['Recovered','Animal Products','Animal fats','Cereals - Excluding Beer','Eggs','Meat','Milk - Excluding Butter','Pulses','Starchy Roots','Sugar & Sweeteners','Vegetal Products']]\nx=corr_heatmap.corr(method='pearson')\nfig = go.Figure(ff.create_annotated_heatmap(z=x[['Recovered']].sort_values(by=['Recovered'],ascending=False).values, x = ['Recovered'], y=x[['Recovered']].sort_values(by=['Recovered'],ascending=False).index.to_list(), colorscale='Viridis'))\nfig.show()\n\n\"\"\"\nIndeed, we can now see that obesity has a stronger correlation with covid deaths than recovery and undernourished patients has a stronger correlation with covid recovery than deaths.\n\nThis could mean that in average, obese patients are most likely to die from covid while undernourished are most likely to survive. This is why obesity worsens outcomes from covid.\n\nSuch results are to be interpreted carefully as many other factors are to be taken into account - for example, undernourished patients are most likely to be in emerging countries, where the population is very young and most likely to survive.\n\"\"\"\n\"\"\"\n#### Health diet vs COVID19\n\"\"\"\ncorr_heatmap=df_food_quantity[['Deaths','Confirmed','Recovered','Obesity','Undernourished', 'Mortality']]\nx=corr_heatmap.corr(method='pearson').round(3)\nff.create_annotated_heatmap(z=x.values, x=x.columns.to_list(), y=x.columns.to_list(), colorscale='Viridis', showscale=True)\n\"\"\"\nIndeed, we can now see that obesity has a stronger correlation with covid deaths than recovery and undernourished patients has a stronger correlation with covid recovery than deaths.\n\nThis could mean that in average, obese patients are most likely to die from covid while undernourished are most likely to survive. This is why obesity worsens outcomes from covid.\n\nSuch results are to be interpreted carefully as many other factors are to be taken into account - for example, undernourished patients are most likely to be in emerging countries, where the population is very young and most likely to survive.\n\"\"\"\n\"\"\"\n#### Obesity average diet\n\"\"\"\nobesity_set = df_food_quantity[df_food_quantity['Obesity'] == df_food_quantity['Obesity']].sort_values(by='Obesity', ascending=False).head(10)\nobesity_mean = obesity_set.describe().iloc[1]\nobesity_mean = pd.DataFrame(obesity_mean).drop(['Deaths', 'Population','Undernourished','Obesity', 'Recovered', 'Confirmed', 'Active'], axis=0)\nobesity_mean = obesity_mean.sort_values(by='mean', ascending=False).iloc[:11]\nfig = px.pie(values = obesity_mean['mean'].values, names = obesity_mean.index.tolist(),\n             )\nfig.show()\n\"\"\"\nThe pie chart above looks a lot like the average pie chart diet we made earlier for the world consumption. The countries with the most obesity rate seem to consume more vegetables than people on average.\n\"\"\"\n\"\"\"\n#### Undernutrition average diet \n\"\"\"\nundernutrition_set = df_food_quantity[df_food_quantity['Undernourished'] == df_food_quantity['Undernourished']].sort_values(by='Undernourished', ascending=False).head(10)\nundernutrition_mean = undernutrition_set.describe().iloc[1]\nundernutrition_mean = pd.DataFrame(undernutrition_mean).drop(['Deaths', 'Population','Undernourished','Obesity', 'Recovered', 'Confirmed', 'Active',], axis=0)\nundernutrition_mean = undernutrition_mean.sort_values(by='mean', ascending=False).iloc[:11]\nfig = px.pie(values = undernutrition_mean['mean'].values, names = undernutrition_mean.index.tolist(),\n             )\nfig.show()\n\"\"\"\nNow we can easily spot the differences. Here undernourished people consume way less animal products and much more starchy roots than the world's consumption in average or the obese people on average. Moreover, they seem to be consuming a bit more alcoholic beverages.\n\"\"\"\n\"\"\"\n# Supervised Approach\n\"\"\"\n\"\"\"\n## Predict Deaths \n\"\"\"\nfeature_names = ['Animal fats', 'Alcoholic Beverages', 'Animal Products','Milk - Excluding Butter', 'Obesity', 'Vegetal Products']\nfor feature_name in feature_names:\n    fig = go.Figure(px.histogram(df_food_quantity[feature_name]))\n    fig.show()\n\"\"\"\n### Response Variables\n\"\"\"\nfeature_names = ['Deaths', 'Recovered', 'Confirmed']\nfor feature_name in feature_names:\n    fig = go.Figure(px.histogram(df_food_quantity[feature_name]))\n    fig.show()\ndef zscore(mean, std, val):\n    epsilon = 0.000001\n    return (val - mean) \/ (epsilon + std)\nfeature_names=['Animal Products', 'Obesity', 'Vegetal Products','Animal fats', 'Milk - Excluding Butter' ]\nz_score_scaled_feature_names = ['Animal Products', 'Obesity', 'Vegetal Products']\nlog_scaled_feature_names = ['Animal fats', 'Milk - Excluding Butter']\n\ntraining_df_copy =df_food_quantity.copy()\nz_score_scaled_features = training_df_copy[z_score_scaled_feature_names].copy()\n\n# Apply z-score on 'Animal Products', 'Obesity' and 'Vegetal Products'\nfor feature_name in z_score_scaled_feature_names:\n    mean = z_score_scaled_features[feature_name].mean()\n    std = z_score_scaled_features[feature_name].std()\n    z_score_scaled_features[feature_name] = zscore(mean, std, z_score_scaled_features[feature_name])\n\nlog_scaled_features = training_df_copy[log_scaled_feature_names].copy()\nfor feature_name in log_scaled_feature_names:\n  # Apply log scaling for 'Cereals - Excluding Beer'\n    log_scaled_features[feature_name] = np.log(log_scaled_features[feature_name])\ntraining_df_copy[z_score_scaled_feature_names]=z_score_scaled_features\ntraining_df_copy[log_scaled_feature_names] = log_scaled_features\nX = training_df_copy[feature_names]\ny = training_df_copy['Deaths']\nfrom sklearn.utils import shuffle\n\nanimal_features = ['Animal fats', 'Aquatic Products, Other', 'Eggs', 'Fish, Seafood', 'Meat',\n                   'Milk - Excluding Butter', 'Offals']\nvegetal_features = ['Alcoholic Beverages', 'Cereals - Excluding Beer', 'Fruits - Excluding Wine', 'Miscellaneous', 'Oilcrops', 'Pulses',\n                    'Spices', 'Starchy Roots', 'Stimulants', 'Sugar & Sweeteners', 'Sugar Crops', 'Treenuts',\n                    'Vegetable Oils', 'Vegetables']\n\ndf_mort = df_food_quantity[df_food_quantity.Country != 'Yemen'][animal_features+vegetal_features+['Obesity','Mortality']]\n# df_mort = kg_df[['Animal Products','Vegetal Products','Obesity','Mortality']]\n\ndf_mort = shuffle(df_mort)\n\nmort_features = df_mort.columns.drop('Mortality')\nmort_target = 'Mortality'\n\nprint('Model features: ', mort_features)\nprint('Model target: ', mort_target)\n\nX = df_mort[mort_features]\ny = df_mort[mort_target]\n\n\"\"\"\n## Missing Values\n\"\"\"\nfrom missingpy import MissForest\n\n# Make an instance and perform the imputation\nimputer = MissForest()\nX_imputed = imputer.fit_transform(X)\n\"\"\"\n## Data Splitting\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X_imputed, y, train_size=0.8, shuffle = True, random_state = 28)\n\"\"\"\n## Train Models \n\"\"\"\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n#Random Forest \nfrom sklearn.ensemble import RandomForestRegressor\nrandom_forest = RandomForestRegressor()\nrandom_forest.fit(X_train, y_train)\n\n#Arbre de regression\nfrom sklearn import tree\narbre_regression = tree.DecisionTreeRegressor()\narbre_regression.fit(X_train, y_train)\n\n# Regression lin\u00e9aire multiple\nfrom sklearn.linear_model import LinearRegression\nreg_multiple = LinearRegression()\nreg_multiple.fit(X_train, y_train)\n\"\"\"\n### Results \/ Predictions \n\"\"\"\nprint(reg_multiple.coef_)\nprint(reg_multiple.score(X_train, y_train))\n\"\"\"\n### Linear Regression\n\"\"\"\nprint('Mean squared error: %.2f'\n      % mean_squared_error(y_test, reg_multiple.predict(X_test)))\n# The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n      % r2_score(y_test, reg_multiple.predict(X_test)))\n\"\"\"\n### Random Forest \n\"\"\"\nprint('Mean squared error: %.2f'\n      % mean_squared_error(y_test, random_forest.predict(X_test)))\n# The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n      % r2_score(y_test, random_forest.predict(X_test)))\n\"\"\"\n### Regression Tree\n\"\"\"\nprint('Mean squared error: %.2f'\n      % mean_squared_error(y_test, arbre_regression.predict(X_test)))\n# The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n      % r2_score(y_test, arbre_regression.predict(X_test)))\n\"\"\"\n## Improve Models ?  \n\"\"\"\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\n\n# Create function to evaluate model on a few different scores\ndef show_scores(model, X_train, X_test, y_train, y_test):    \n    train_preds = model.predict(X_train)\n    test_preds = model.predict(X_test)\n    scores = {'Training MAE': mean_absolute_error(y_train, train_preds),\n              'Test MAE': mean_absolute_error(y_test, test_preds),\n              'Training MSE': mean_squared_error(y_train, train_preds),\n              'Test MSE': mean_squared_error(y_test, test_preds),\n              'Training R^2': r2_score(y_train, train_preds),\n              'Test R^2': r2_score(y_test, test_preds)}\n    return scores\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost.sklearn import XGBRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.pipeline import Pipeline\n\n# First, we create a dict with our desired models\nmodels = {'Ridge':Ridge(random_state=28),\n          'SVR':SVR(),\n          'RandomForest':RandomForestRegressor(),\n          'XGBoost':XGBRegressor(n_estimators = 1000, learning_rate = 0.05)}\n\n# Now to build the function that tests each model\ndef model_build(model, X_train, y_train, X_test, y_test, scale=True):\n    \n    if scale:\n        regressor = Pipeline([\n            ('scaler', StandardScaler()),\n            ('estimator', model)\n        ])\n    \n    else:\n        regressor = Pipeline([\n            ('estimator', model)\n        ])\n\n    # Training\n    regressor.fit(X_train, y_train)\n\n    # Scoring the training set\n\n    train_preds = regressor.predict(X_train)\n    print(f\"R2 on single split: {regressor.score(X_train, y_train)}\")\n\n    # Cross validate\n    cv_score = cross_val_score(regressor, X_train, y_train, cv = 10)\n\n    print(f\"Cross validate R2 score: {cv_score.mean()}\")\n\n    # Scoring the test set\n    for k, v in show_scores(regressor, X_train, X_test , y_train, y_test).items():\n        print(\"     \", k, v)\n        \n    \nfor name, model in models.items():\n    print(f\"==== Scoring {name} model====\")\n    \n    if name == 'RandomForest' or name == 'XGBoost':\n        model_build(model, X_train, y_train, X_test, y_test, scale=False)\n    else:\n        model_build(model, X_train, y_train, X_test, y_test,)\n    print()\n    print(40*\"=\")\n        \nmodel = RandomForestRegressor()\nmodel.fit(X_train, y_train)\n\ntest_preds = model.predict(X_test)\n\ntest_plot = pd.DataFrame(X_test, columns=X.columns)\ntest_plot['Mortality'] = y_test\ntest_plot['Mortality_pred'] = test_preds\n\ntest_plot.head()\ndef plotTest(col, target, data):\n    fig, ax = plt.subplots(figsize=[10,8])\n\n    sns.regplot(x = col, y = target, data = data, ax = ax, label=target)\n    sns.regplot(x = col, y = target+'_pred', data = data, ax = ax, label=target+'_pred')\n\n    plt.legend();\nimport seaborn as sns\nplotTest('Animal fats', 'Mortality', test_plot)\nThere are MANY factors that are important to fight against the current COVID-19 epidemic. Maintaining good eating habits helps keep our immune system healthy and ready to combat a possible disease.\nIn this notebook I tried to explore possible patterns found in data of COVID-19 and food intake in different countries. One major goal was to find the influence of obesity rates in the effect of the disease in each country. Splitting countries into HOC and LOC groups, it was possible to create a classifier, with good accuracy, predicting in which group would a country be based on its food intake data.\nHaving this, we created regression models to try to predict the Mortality of COVID-19 in countries based on ther eating habits and obesity rate. Two approaches were taken: one with all food related features taken as parameters and a simpler one. Both have issues (mainly of spread and non-linearity), but we could show use of different models and metrics.\n\"\"\"\n### Method 2\n\"\"\"\ndf_fat_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Fat_Supply_Quantity_Data.csv')\ndf_food_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Food_Supply_Quantity_kg_Data.csv')\ndf_food_kcal = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Food_Supply_kcal_Data.csv')\ndf_protein_quantity = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Protein_Supply_Quantity_Data.csv')\ndf_food_description = pd.read_csv(r'..\/input\/covid19-healthy-diet-dataset\/Supply_Food_Data_Descriptions.csv')\ndf = pd.DataFrame()\ndf[[i+'-fat' for i in ['Country', 'Alcoholic Beverages', 'Animal fats',\n       'Cereals - Excluding Beer', 'Fruits - Excluding Wine', 'Miscellaneous',\n       'Milk - Excluding Butter', 'Stimulants', 'Sugar Crops',\n       'Sugar & Sweeteners', 'Vegetable Oils']]] = df_fat_quantity[['Country', 'Alcoholic Beverages', 'Animal fats',\n       'Cereals - Excluding Beer', 'Fruits - Excluding Wine', 'Miscellaneous',\n       'Milk - Excluding Butter', 'Stimulants', 'Sugar Crops',\n       'Sugar & Sweeteners', 'Vegetable Oils']]\ndf[[i+'-kcal' for i in df_food_kcal.columns[[2,4,5,6,7,9,11,13,14,15,16,19,20,21,22,23]]]]= df_food_kcal[df_food_kcal.columns[[2,4,5,6,7,9,11,13,14,15,16,19,20,21,22,23]]]\ndf[[i+'-food' for i in df_food_quantity.columns[[1,2,3,12,17,18,19,21,23]]]]= df_food_quantity[df_food_quantity.columns[[1,2,3,12,17,18,19,21,23]]]\ndf[[i+'-protein' for i in df_protein_quantity.columns[[3,8]]]]= df_protein_quantity[df_protein_quantity.columns[[3,8]]]\ndf[[i+'-protein' for i in df_protein_quantity.columns[10:30]]]= df_protein_quantity[df_protein_quantity.columns[10:30]]\ndf['Undernourished-protein'] = df.apply(lambda row: 2.5 if row['Undernourished-protein'] == '<2.5' else float(row['Undernourished-protein']), axis = 1)\nfor feature_name in df.columns:\n    fig = go.Figure(px.histogram(df[feature_name]))\n    fig.show()\ndf = df.drop(columns=['Animal fats-food', 'Vegetal Products-food', 'Animal Products-kcal', 'Vegetal Products-kcal', 'Alcoholic Beverages-fat', 'Sugar Crops-fat', 'Sugar & Sweeteners-fat', 'Sugar & Sweeteners-food', 'Sugar Crops-protein','Aquatic Products, Other-kcal'])\nx = np.corrcoef([df_food_quantity[\"Sugar & Sweeteners\"].values.tolist(),df_protein_quantity[\"Sugar & Sweeteners\"].values.tolist(),df_food_kcal['Sugar & Sweeteners'].values.tolist(),df_fat_quantity['Sugar & Sweeteners'].values.tolist()]).round(3)\nfig = go.Figure(ff.create_annotated_heatmap(z=x,x=['Sugar & Sweeteners-food',\"Sugar & Sweeteners-protein\",\"Sugar & Sweeteners-kcal\",\"Sugar & Sweeteners-fat\"],y=['Sugar & Sweeteners-food',\"Sugar & Sweeteners-protein\",\"Sugar & Sweeteners-kcal\",\"Sugar & Sweeteners-fat\"], colorscale='Viridis', showscale=True))\nfig.show()\nfor feature_name in df.columns[44:]:\n    fig = go.Figure(px.histogram(df[feature_name]))\n    fig.show()\nfrom missingpy import MissForest\n\n# Make an instance and perform the imputation\nimputer = MissForest()\nX = imputer.fit_transform(df[df.columns[1:]].values.tolist())\ndf[df.columns[1:]] = X\ncorr_heatmap=df\nx=corr_heatmap.corr(method='pearson').round(3)\nfig = go.Figure(ff.create_annotated_heatmap(z=x[['Deaths-protein']].sort_values(by='Deaths-protein').values, x=['Deaths-protein'], y=x[['Deaths-protein']].sort_values(by='Deaths-protein').index.to_list(), colorscale='Viridis', showscale=True))\nfig.update_layout(height=1000)\nfig.show()\ncorr_heatmap=df\nx=corr_heatmap.corr(method='pearson').round(3)\nfig = go.Figure(ff.create_annotated_heatmap(z=x[['Recovered-protein']].sort_values(by='Recovered-protein').values, x=['Recovered-protein'], y=x[['Recovered-protein']].sort_values(by='Recovered-protein').index.to_list(), colorscale='Viridis', showscale=True))\nfig.show()\ndf = df.dropna()\nX = df[['Miscellaneous-protein', 'Sugar & Sweeteners-kcal', 'Meat-kcal', 'Pulses-kcal','Stimulants-protein','Oilcrops-kcal','Fruits - Excluding Wine-protein', 'Eggs-kcal']]\ny = df['Confirmed-protein']\nX = df[['Miscellaneous-protein', 'Vegetables-protein', 'Obesity-protein', 'Undernourished-protein', 'Animal fats-fat']]\ny = df['Deaths-protein']\nX = df[['Miscellaneous-protein','Stimulants-fat' ,'Treenuts-protein', 'Eggs-kcal','Offals-protein']]\ny = df['Recovered-protein']\n\"\"\"\n## Results \n\"\"\"\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nX_train, X_test, y_train, y_test = train_test_split(X.values.tolist(), y.values.tolist(), train_size=0.7, shuffle = True)\n#Random Forest \nfrom sklearn.ensemble import RandomForestRegressor\nrandom_forest = RandomForestRegressor()\nrandom_forest.fit(X_train, y_train)\n\n#Arbre de regression\nfrom sklearn import tree\narbre_regression = tree.DecisionTreeRegressor()\narbre_regression.fit(X_train, y_train)\n\n# Regression lin\u00e9aire multiple\nfrom sklearn.linear_model import LinearRegression\nreg_multiple = LinearRegression()\nreg_multiple.fit(X_train, y_train)\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, reg_multiple.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, reg_multiple.predict(X_test)))\n\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, arbre_regression.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, arbre_regression.predict(X_test)))\n\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, random_forest.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, random_forest.predict(X_test)))\n\ntest_df = pd.DataFrame()\ntest_df['random_forest_pred'] = random_forest.predict(X_test)\ntest_df['arbre_regression_pred'] = arbre_regression.predict(X_test)\ntest_df['regression_lineaire_mult_pred'] = reg_multiple.predict(X_test)\nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(random_forest)\n\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(random_forest,hist=False, qqplot=True\n)\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \nr2_score(y_test, random_forest.predict(X_test))\nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(random_forest)\n\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(random_forest,hist=False, qqplot=True\n)\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \nprint('Mean squared error: %.5f'\n              % mean_squared_error(y_test, random_forest.predict(X_test)))\n\"\"\"\n# PCA  \n\"\"\"\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=6)\npca.fit(df[df.columns[1:20]])\nprint(pca.explained_variance_ratio_)\nX = pca.transform(df[df.columns[1:20]])\ny = df['Deaths-protein']\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nX_train, X_test, y_train, y_test = train_test_split(X.tolist(), y.values.tolist(), train_size=0.8, shuffle = True)\n#Random Forest w\nfrom sklearn.ensemble import RandomForestRegressor\nrandom_forest = RandomForestRegressor()\nrandom_forest.fit(X_train, y_train)\n\n#Arbre de regression\nfrom sklearn import tree\narbre_regression = tree.DecisionTreeRegressor()\narbre_regression.fit(X_train, y_train)\n\n# Regression lin\u00e9aire multiple\nfrom sklearn.linear_model import LinearRegression\nreg_multiple = LinearRegression()\nreg_multiple.fit(X_train, y_train)\n\nprint('Linear Regression')\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, reg_multiple.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, reg_multiple.predict(X_test)))\n\nprint('Regression Tree')\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, reg_multiple.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, reg_multiple.predict(X_test)))\n\nprint('Random Forest')\nprint('Mean squared error: %.2f'\n          % mean_squared_error(y_test, reg_multiple.predict(X_test)))\n    # The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n          % r2_score(y_test, reg_multiple.predict(X_test)))\n\nprint(X.shape)\nprint(y.shape)\nr2_score(y_test, random_forest.predict(X_test))\nr2_score(y_test, arbre_regression.predict(X_test))\nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(reg_multiple)\n\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \nfrom yellowbrick.regressor import ResidualsPlot\n\nvisualizer = ResidualsPlot(reg_multiple,hist=False, qqplot=True\n)\nvisualizer.fit(X_train, y_train)  # Fit the training data to the visualizer\nvisualizer.score(X_test, y_test)  # Evaluate the model on the test data\nvisualizer.show() \n\"\"\"\n# K-Means \n\"\"\"\nX = df[['Miscellaneous-protein', 'Vegetables-protein', 'Obesity-protein',  'Animal fats-fat']].values\nfrom sklearn.preprocessing import StandardScaler\nscalerX = StandardScaler().fit(X)\nX_scaled = scalerX.transform(X)\n\n# Using the elbow method to find the optimal number of clusters\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1, 11):\n    kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)\n    kmeans.fit(X_scaled)\n    wcss.append(kmeans.inertia_)\nplt.plot(range(1, 11), wcss)\nplt.title('The Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\n#plt.show()\nfigure = plt.gcf()  # get current figure\nfigure.set_size_inches(8, 4) # set figure's size manually to your full screen (32x18)\n#plt.savefig(\"Elbow.png\", bbox_inches='tight') # bbox_inches removes extra white spaces\nplt.show()\n# K = 4 \nnum_opt_clusters=3\n\n# Fitting K-Means to the dataset\nkmeans = KMeans(n_clusters = num_opt_clusters, init = 'k-means++', random_state = 42)\ny_kmeans = kmeans.fit_predict(X_scaled)\ndataset =df[['Miscellaneous-protein', 'Vegetables-protein', 'Obesity-protein', 'Animal fats-fat']].copy()\noriginal_len=dataset.shape[0]\nfor i in range(0,original_len):\n    dataset.loc[i,\"Cluster\"]=y_kmeans[i]\n    \nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\nplt.title('Cluster Analysis',fontsize=20, fontweight='bold')\nplt.xlabel('Obesity',fontsize=16, fontweight='bold')\nplt.ylabel('Confirmed',fontsize=16, fontweight='bold')\n\nfigure = plt.gcf()  # get current figure\nfigure.set_size_inches(32, 18) # set figure's size manually to your full screen (32x18)\nplt.show()\ndataset['Deaths'] = df['Deaths-protein']\ndataset['Country'] = df['Country-fat']\ndataset.groupby('Cluster').mean()\ndataset.groupby('Cluster').count()\n\"\"\"\n# Conclusion\n\"\"\"\nIn summary, a country\u2019s COVID-19 confirmed and active cases can somehow be explained relatively well by food categories such as the calorie contents of oilcrops, and the protein content in infant food and miscellaneous\nfood. On the other hand, the same cannot be said about the death and recovered cases. This could be due to the fact that these models do not satisfy the neccessary model assumptions of having equal variance and\nnormally distributed residuals. However, it is also important to note that mortality has not had an outcome, and hence the first model should only be taken as a grain of salt. \n\nHowever, recall that this model only talks about the correlation between food categories and the rate of deaths. \n\nThere is no evidence to suggest that a country\u2019s diet has an effect on the spread of COVID-19. Additionally, there are also many other factors causing the spread of COVID-19 that are totally uncorrelated with diet, eg. how active the general public are, the preventive measures implemented by the\ncountries, density of population etc.","meta":"{'source': 'AI4Code', 'id': 'df6dd7e8ce2081'}"}
{"id":"70660","text":"\"\"\"\n# import libraries\n\"\"\"\nimport numpy as np \nimport pandas as pd \nfrom collections import OrderedDict\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn import ensemble\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import (RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier)\nfrom sklearn.svm import SVC\n\nfrom sklearn.model_selection import KFold\nimport xgboost as xgb\nfrom sklearn.datasets import make_classification\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.model_selection import cross_val_score,cross_val_predict,cross_validate\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\n\"\"\"\n# common variables\n\"\"\"\nRANDOM_STATE = 42\nmin_estimators = 30\nmax_estimators = 100\n\"\"\"\n# load data\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/titanic\/train.csv\")\ntest = pd.read_csv(\"..\/input\/titanic\/test.csv\")\n\"\"\"\n# preprocess\n\"\"\"\n#1. delete unnecessary columns\ndrop_elements = ['PassengerId', 'Name', 'Ticket', 'Cabin', 'SibSp','Parch']\ntrain = train.drop(drop_elements, axis = 1)\ntest = test.drop(drop_elements, axis = 1)\n\n#2.find null data and fill new data \ndef checkNull_fillData(df):\n    for col in df.columns:\n        if len(df.loc[df[col].isnull() == True]) != 0:\n            if df[col].dtype == \"float64\" or df[col].dtype == \"int64\":\n                df.loc[df[col].isnull() == True,col] = df[col].mean()\n            else:\n                df.loc[df[col].isnull() == True,col] = df[col].mode()[0]\n                \ncheckNull_fillData(train)\ncheckNull_fillData(test)\n\n#3.one hot encoding \nstr_list = [] \nnum_list = []\nfor colname, colvalue in train.iteritems():\n    if type(colvalue[1]) == str:\n        str_list.append(colname)\n    else:\n        num_list.append(colname)\n        \ntrain = pd.get_dummies(train, columns=str_list)\ntest = pd.get_dummies(test, columns=str_list)\n\"\"\"\n# split data\n\"\"\"\ny = train[\"Survived\"]\nX = train.drop([\"Survived\"], axis=1)\nX_test = test\n\"\"\"\n# define element models\n\"\"\"\nrf1 = RandomForestClassifier(\n            warm_start=True,\n            oob_score=True,\n            max_features='sqrt',\n            random_state=RANDOM_STATE,\n        )\n\nrf2 =  RandomForestClassifier(\n            warm_start=True,\n            max_features='log2',\n            oob_score=True,\n            random_state=RANDOM_STATE,\n        )\n\nrf3 = RandomForestClassifier(\n            warm_start=True,\n            max_features=None,\n            oob_score=True,\n            random_state=RANDOM_STATE,\n        )\n\nrf4 = RandomForestClassifier(\n            warm_start=True,\n            max_features=0.5,\n            oob_score=True,\n            random_state=RANDOM_STATE,\n        )\n\nrf5 = RandomForestClassifier(\n            warm_start=True,\n            max_features=0.7,\n            oob_score=True,\n            random_state=RANDOM_STATE,\n        )\n\n\nensemble_clfs = [(\"rf1\",rf1),(\"rf2'\",rf2),(\"rf3\",rf3),(\"rf4\",rf4),(\"rf5\",rf5)]\nerror_rate = OrderedDict((label, []) for label, _ in ensemble_clfs)\nerror_rate\nmin_oob_error = 1.0\nmin_label = \"\"\nmin_index = 0\nfor label, clf in ensemble_clfs:\n    for i in range(min_estimators, max_estimators + 1):\n        clf.set_params(n_estimators=i)\n        clf.fit(X, y)\n\n        oob_error = 1 - clf.oob_score_\n        error_rate[label].append((i, oob_error))\n        \n        if min_oob_error > oob_error:\n            min_oob_error = oob_error\n            min_label = label\n            min_index = i\n        \n#         print(\"clf.oob_score_\",clf.oob_score_)\n#         print(\"oob_error\",round(oob_error,3))\n#         print(\"\")\n        \n        \nprint(\"min_oob_error=\",min_oob_error)\nprint(\"min_label=\",min_label)\nprint(\"min_index=\",min_index)\nfor label, clf_err in error_rate.items():\n    xs, ys = zip(*clf_err)\n    plt.plot(xs, ys, label=label)\n\nplt.xlim(min_estimators, max_estimators)\nplt.xlabel(\"n_estimators\")\nplt.ylabel(\"OOB error rate\")\nplt.legend(loc=\"upper right\")\nplt.show()\n\"\"\"\n# build model using best parameter \n\"\"\"\nrf = RandomForestClassifier(\n           n_estimators = 56,\n            warm_start=True,\n            max_features='sqrt',\n            oob_score=True,\n            random_state=RANDOM_STATE\n)\nrf.fit(X,y)\n\"\"\"\n# Evaluate Model\n\"\"\"\ny_train_pred = cross_val_predict(rf, X, y, cv=3)\nprint( confusion_matrix(y, y_train_pred) )\n\nprint(\"\")\n\nprint(\"precision_score1:\",precision_score(y, y_train_pred) )\ncm = confusion_matrix(y, y_train_pred)\nprint(\"precision_score2:\",cm[1, 1] \/ (cm[0, 1] + cm[1, 1]) )\n\nprint(\"\")\n\nprint(\"recall_score1:\",recall_score(y, y_train_pred))\nprint(\"recall_score2:\",cm[1, 1] \/ (cm[1, 0] + cm[1, 1]) )\n\nprint(\"\")\n\nprint(\"f1_score1:\",f1_score(y, y_train_pred))\nprint(\"f1_score2:\", cm[1, 1] \/ (cm[1, 1] + (cm[1, 0] + cm[0, 1]) \/ 2) )\n\nprint(\"\")\n\nprint(\"roc_auc score\",roc_auc_score(y, y_train_pred) )\n\"\"\"\n# predict test data using stacking one model\n\"\"\"\npredictions = rf.predict(X_test)\n\"\"\"\n# submission\n\"\"\"\nsub = pd.read_csv(\"..\/input\/titanic\/gender_submission.csv\")\nsub[\"Survived\"] = predictions\nsub.to_csv('submission.csv', index=False)\nsub.head()","meta":"{'source': 'AI4Code', 'id': '81fcb01143b1db'}"}
{"id":"35068","text":"\"\"\"\n# Getting Started\n\nIn this tutorial, you will know how to\n- use the models in **ConvLab-2** to build a dialog agent.\n- build a simulator to chat with the agent and evaluate the performance.\n- try different module combinations.\n- use analysis tool to diagnose your system.\n\nLet's get started!\n\"\"\"\n\"\"\"\n## Environment setup\nRun the command below to install ConvLab-2. Then restart the notebook and skip this commend.\n\"\"\"\n# first install ConvLab-2 and restart the notebook\n! git clone https:\/\/github.com\/thu-coai\/ConvLab-2.git && cd ConvLab-2 && pip install -e .\ncd ConvLab-2\n\"\"\"\n## build an agent\n\nWe use the models adapted on [Multiwoz](https:\/\/www.aclweb.org\/anthology\/D18-1547)  dataset to build our agent. This pipeline agent consists of NLU, DST, Policy and NLG modules.\n\nFirst, import some models:\n\"\"\"\n# common import: convlab2.$module.$model.$dataset\nfrom convlab2.nlu.jointBERT.multiwoz import BERTNLU\nfrom convlab2.nlu.milu.multiwoz import MILU\nfrom convlab2.dst.rule.multiwoz import RuleDST\nfrom convlab2.policy.rule.multiwoz import RulePolicy\nfrom convlab2.nlg.template.multiwoz import TemplateNLG\nfrom convlab2.dialog_agent import PipelineAgent, BiSession\nfrom convlab2.evaluator.multiwoz_eval import MultiWozEvaluator\nfrom pprint import pprint\nimport random\nimport numpy as np\nimport torch\n\"\"\"\nThen, create the models and build an agent:\n\"\"\"\n# go to README.md of each model for more information\n# BERT nlu\nsys_nlu = BERTNLU()\n# simple rule DST\nsys_dst = RuleDST()\n# rule policy\nsys_policy = RulePolicy()\n# template NLG\nsys_nlg = TemplateNLG(is_user=False)\n# assemble\nsys_agent = PipelineAgent(sys_nlu, sys_dst, sys_policy, sys_nlg, name='sys')\n\"\"\"\nThat's all! Let's chat with the agent using its response function:\n\"\"\"\nsys_agent.response(\"I want to find a moderate hotel\")\nsys_agent.response(\"Which type of hotel is it ?\")\nsys_agent.response(\"OK , where is its address ?\")\nsys_agent.response(\"Thank you !\")\nsys_agent.response(\"Try to find me a Chinese restaurant in south area .\")\nsys_agent.response(\"Which kind of food it provides ?\")\nsys_agent.response(\"Book a table for 5 , this Sunday .\")\n\"\"\"\n## Build a simulator to chat with the agent and evaluate\n\nIn many one-to-one task-oriented dialog system, a simulator is essential to train an RL agent. In our framework, we doesn't distinguish user or system. All speakers are **agents**. The simulator is also an agent, with specific policy inside for accomplishing the user goal.\n\nWe use `Agenda` policy for the simulator, this policy requires dialog act input, which means we should set DST argument of `PipelineAgent` to None. Then the `PipelineAgent` will pass dialog act to policy directly. Refer to `PipelineAgent` doc for more details.\n\"\"\"\n# MILU\nuser_nlu = MILU()\n# not use dst\nuser_dst = None\n# rule policy\nuser_policy = RulePolicy(character='usr')\n# template NLG\nuser_nlg = TemplateNLG(is_user=True)\n# assemble\nuser_agent = PipelineAgent(user_nlu, user_dst, user_policy, user_nlg, name='user')\n\"\"\"\n\nNow we have a simulator and an agent. we will use an existed simple one-to-one conversation controller BiSession, you can also define your own Session class for your special need.\n\nWe add `MultiWozEvaluator` to evaluate the performance. It uses the parsed dialog act input and policy output dialog act to calculate **inform f1**, **book rate**, and whether the task is **success**.\n\"\"\"\nevaluator = MultiWozEvaluator()\nsess = BiSession(sys_agent=sys_agent, user_agent=user_agent, kb_query=None, evaluator=evaluator)\n\"\"\"\nLet's make this two agents chat! The key is `next_turn` method of `BiSession` class.\n\"\"\"\ndef set_seed(r_seed):\n    random.seed(r_seed)\n    np.random.seed(r_seed)\n    torch.manual_seed(r_seed)\n\nset_seed(20200131)\n\nsys_response = ''\nsess.init_session()\nprint('init goal:')\npprint(sess.evaluator.goal)\nprint('-'*50)\nfor i in range(20):\n    sys_response, user_response, session_over, reward = sess.next_turn(sys_response)\n    print('user:', user_response)\n    print('sys:', sys_response)\n    print()\n    if session_over is True:\n        break\nprint('task success:', sess.evaluator.task_success())\nprint('book rate:', sess.evaluator.book_rate())\nprint('inform precision\/recall\/f1:', sess.evaluator.inform_F1())\nprint('-'*50)\nprint('final goal:')\npprint(sess.evaluator.goal)\nprint('='*100)\n\"\"\"\n## Try different module combinations\n\nThe combination modes of pipeline agent modules are flexible. We support joint models such as MDBT, TRADE, SUMBT for word-DST and MDRG, HDSA, LaRL for word-Policy, once the input and output are matched with previous and next module. We also support End2End models such as Sequicity.\n\nAvailable models:\n\n- NLU: BERTNLU, MILU, SVMNLU\n- DST: RuleDST\n- Word-DST: SUMBT, TRADE, MDBT (set `sys_nlu` to `None`)\n- Policy: RulePolicy, Imitation, REINFORCE, PPO, GDPL\n- Word-Policy: MDRG, HDSA, LaRL (set `sys_nlg` to `None`)\n- NLG: Template, SCLSTM\n- End2End: Sequicity, DAMD, RNN_rollout (directly used as `sys_agent`)\n- Simulator policy: Agenda, VHUS (for `user_policy`)\n\n\"\"\"\n# available NLU models\nfrom convlab2.nlu.svm.multiwoz import SVMNLU\nfrom convlab2.nlu.jointBERT.multiwoz import BERTNLU\nfrom convlab2.nlu.milu.multiwoz import MILU\n# available DST models\nfrom convlab2.dst.rule.multiwoz import RuleDST\nfrom convlab2.dst.mdbt.multiwoz import MDBT\nfrom convlab2.dst.sumbt.multiwoz import SUMBT\nfrom convlab2.dst.trade.multiwoz import TRADE\n# available Policy models\nfrom convlab2.policy.rule.multiwoz import RulePolicy\nfrom convlab2.policy.ppo.multiwoz import PPOPolicy\nfrom convlab2.policy.pg.multiwoz import PGPolicy\nfrom convlab2.policy.mle.multiwoz import MLEPolicy\nfrom convlab2.policy.gdpl.multiwoz import GDPLPolicy\nfrom convlab2.policy.vhus.multiwoz import UserPolicyVHUS\nfrom convlab2.policy.mdrg.multiwoz import MDRGWordPolicy\nfrom convlab2.policy.hdsa.multiwoz import HDSA\nfrom convlab2.policy.larl.multiwoz import LaRL\n# available NLG models\nfrom convlab2.nlg.template.multiwoz import TemplateNLG\nfrom convlab2.nlg.sclstm.multiwoz import SCLSTM\n# available E2E models\nfrom convlab2.e2e.sequicity.multiwoz import Sequicity\nfrom convlab2.e2e.damd.multiwoz import Damd\n\"\"\"\nNLU+RuleDST or Word-DST:\n\"\"\"\n# NLU+RuleDST:\nsys_nlu = BERTNLU()\n# sys_nlu = MILU()\n# sys_nlu = SVMNLU()\nsys_dst = RuleDST()\n\n# or Word-DST:\n# sys_nlu = None\n# sys_dst = SUMBT()\n# sys_dst = TRADE()\n# sys_dst = MDBT()\n\"\"\"\nPolicy+NLG or Word-Policy:\n\"\"\"\n# Policy+NLG:\nsys_policy = RulePolicy()\n# sys_policy = PPOPolicy()\n# sys_policy = PGPolicy()\n# sys_policy = MLEPolicy()\n# sys_policy = GDPLPolicy()\nsys_nlg = TemplateNLG(is_user=False)\n# sys_nlg = SCLSTM(is_user=False)\n\n# or Word-Policy:\n# sys_policy = LaRL()\n# sys_policy = HDSA()\n# sys_policy = MDRGWordPolicy()\n# sys_nlg = None\n\"\"\"\nAssemble the Pipeline system agent:\n\"\"\"\nsys_agent = PipelineAgent(sys_nlu, sys_dst, sys_policy, sys_nlg, 'sys')\n\"\"\"\nOr Directly use an end-to-end model:\n\"\"\"\n# sys_agent = Sequicity()\n# sys_agent = Damd()\n\"\"\"\nConfig an user agent similarly:\n\"\"\"\nuser_nlu = BERTNLU()\n# user_nlu = MILU()\n# user_nlu = SVMNLU()\nuser_dst = None\nuser_policy = RulePolicy(character='usr')\n# user_policy = UserPolicyVHUS(load_from_zip=True)\nuser_nlg = TemplateNLG(is_user=True)\n# user_nlg = SCLSTM(is_user=True)\nuser_agent = PipelineAgent(user_nlu, user_dst, user_policy, user_nlg, name='user')\n\"\"\"\n## Use analysis tool to diagnose the system\nWe provide an analysis tool presents rich statistics and summarizes common mistakes from simulated dialogues, which facilitates error analysis and\nsystem improvement. The analyzer will generate an HTML report which contains\nrich statistics of simulated dialogues. For more information, please refer to `convlab2\/util\/analysis_tool`.\n\"\"\"\nfrom convlab2.util.analysis_tool.analyzer import Analyzer\n\n# if sys_nlu!=None, set use_nlu=True to collect more information\nanalyzer = Analyzer(user_agent=user_agent, dataset='multiwoz')\n\nset_seed(20200131)\nanalyzer.comprehensive_analyze(sys_agent=sys_agent, model_name='sys_agent', total_dialog=100)\n\"\"\"\nTo compare several models:\n\"\"\"\nset_seed(20200131)\nanalyzer.compare_models(agent_list=[sys_agent1, sys_agent2], model_name=['sys_agent1', 'sys_agent2'], total_dialog=100)","meta":"{'source': 'AI4Code', 'id': '408b0d59485858'}"}
{"id":"130655","text":"import torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.optim as optim\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom skimage import io, transform\nfrom PIL import Image\nimport random\n# Set random seed for reproducibility\nmanualSeed = 999\n#manualSeed = random.randint(1, 10000) # use if you want new results\nprint(\"Random Seed: \", manualSeed)\nrandom.seed(manualSeed)\ntorch.manual_seed(manualSeed)\nimg_dir = \"..\/input\/highresolution-anime-face-dataset-512x512\/portraits\/\"\nimage_list = []\nfor item in os.listdir(img_dir):\n    image_list.append(item)\n\nprint(len(image_list))\nprint(image_list[0])\n#Basic Transforms\nSIZE = (64,64)\nmean = (0.5, 0.5, 0.5)\nstd = (0.5, 0.5, 0.5)\nnorm_tran = transforms.Compose([transforms.Resize(SIZE),\n                                transforms.ToTensor(), \n                                transforms.Normalize(mean=mean, std=std)])\nclass PhotoDatasetCreater(Dataset):\n\n    def __init__(self, image_list, root_dir, transform=None):\n        \"\"\"\n        Args:\n            csv_file (string): Path to the csv file with annotations.\n            root_dir (string): Directory with all the images.\n            transform (callable, optional): Optional transform to be applied\n                on a sample.\n        \"\"\"\n        self.image_list = image_list\n        self.root_dir = root_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(image_list)\n\n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n        # Get the image path for each image\n        img_name = os.path.join(self.root_dir,self.image_list[idx])\n        #print(img_name)\n        image = Image.open(img_name)\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image\nimg_dataset = PhotoDatasetCreater(image_list=image_list,root_dir=img_dir, transform=norm_tran)\nprint(len(img_dataset))\nfig = plt.figure()\n\nfor i in range(5):\n    sample = img_dataset[i]\n    ax = plt.subplot(1, 4, i + 1)\n    plt.tight_layout()\n    ax.set_title('Sample #{}'.format(i))\n    ax.axis('off')\n    plt.imshow(sample.permute(1, 2, 0))\n\n    if i == 3:\n        plt.show()\n        break\n# Data loaders\n# Parameters for setting up data loaders\nBATCH_SIZE = 256\nNUM_WORKERS = 2\nVALIDATION_SIZE = 0.15\n# Create the dataloader\ndataloader = torch.utils.data.DataLoader(img_dataset, batch_size=BATCH_SIZE,\n                                         shuffle=True, num_workers=NUM_WORKERS)\n\n\n# Plot some training images\nreal_batch = next(iter(dataloader))\nplt.figure(figsize=(8,8))\nplt.axis(\"off\")\nplt.title(\"Training Images\")\n\nfor i in range(5):\n    sample = real_batch[i]\n    ax = plt.subplot(1, 4, i + 1)\n    plt.tight_layout()\n    ax.set_title('Sample #{}'.format(i))\n    ax.axis('off')\n    plt.imshow(sample.permute(1, 2, 0))\n\n    if i == 3:\n        plt.show()\n        break\nreal_batch.size()\n\"\"\"\n# Pytoch GAN Implementation\n\"\"\"\n#checking the availability of cuda devices\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\"\"\"\n# GAN Params \n\"\"\"\n# number of gpu's available\nngpu = 1\n# input noise dimension\nnz = 100\n# number of generator filters\nngf = 64\n#number of discriminator filters\nndf = 64\n# Number of Channels (For color images need 3)\nnc=3\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n    classname = m.__class__.__name__\n    if classname.find('Conv') != -1:\n        m.weight.data.normal_(0.0, 0.02)\n    elif classname.find('BatchNorm') != -1:\n        m.weight.data.normal_(1.0, 0.02)\n        m.bias.data.fill_(0)\nclass Generator(nn.Module):\n    def __init__(self, ngpu):\n        super(Generator, self).__init__()\n        self.ngpu = ngpu\n        self.main = nn.Sequential(\n            # input is Z, going into a convolution\n            nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False),\n            nn.BatchNorm2d(ngf * 8),\n            nn.ReLU(True),\n            # state size. (ngf*8) x 4 x 4\n            nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 4),\n            nn.ReLU(True),\n            # state size. (ngf*4) x 8 x 8\n            nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 2),\n            nn.ReLU(True),\n            # state size. (ngf*2) x 16 x 16\n            nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf),\n            nn.ReLU(True),\n            # state size. (ngf) x 32 x 32\n            nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),\n            nn.Tanh()\n            # state size. (nc) x 64 x 64\n        )\n\n    def forward(self, input):\n        if input.is_cuda and self.ngpu > 1:\n            output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n        else:\n            output = self.main(input)\n            return output\nnetG = Generator(ngpu).to(device)\nnetG.apply(weights_init)\n#load weights to test the model\n#netG.load_state_dict(torch.load('weights\/netG_epoch_24.pth'))\nprint(netG)\nclass Discriminator(nn.Module):\n    def __init__(self, ngpu):\n        super(Discriminator, self).__init__()\n        self.ngpu = ngpu\n        self.main = nn.Sequential(\n            # input is (nc) x 64 x 64\n            nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf) x 32 x 32\n            nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 2),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*2) x 16 x 16\n            nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 4),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*4) x 8 x 8\n            nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n            nn.BatchNorm2d(ndf * 8),\n            nn.LeakyReLU(0.2, inplace=True),\n            # state size. (ndf*8) x 4 x 4\n            nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n            nn.Sigmoid()\n        )\n\n    def forward(self, input):\n        if input.is_cuda and self.ngpu > 1:\n            output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n        else:\n            output = self.main(input)\n\n        return output.view(-1, 1).squeeze(1)\nnetD = Discriminator(ngpu).to(device)\nnetD.apply(weights_init)\n#load weights to test the model \n#netD.load_state_dict(torch.load('weights\/netD_epoch_24.pth'))\nprint(netD)\ncriterion = nn.BCELoss()\n# setup optimizer\noptimizerD = optim.Adam(netD.parameters(), lr=0.0002, betas=(0.5, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=0.0002, betas=(0.5, 0.999))\nfixed_noise = torch.randn(128, nz, 1, 1, device=device)\nreal_label = 1.0\nfake_label = 0.0\nniter = 1\niters = 0\nimg_list = []\ng_loss = []\nd_loss = []\nfor epoch in range(niter):\n    for i, data in enumerate(dataloader):\n        ############################\n        # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n        ###########################\n        # train with real\n        netD.zero_grad()\n        real_cpu = data.to(device)\n        batch_size = real_cpu.size(0)\n        label = torch.full((batch_size,), real_label, device=device)\n        #print(\"Real cpu size\", real_cpu.size())\n        output = netD(real_cpu)\n#         print(\"Output type {} value {}\".format(type(output), output))\n#         print(\"Label type {} value {}\".format(type(label), label))\n        errD_real = criterion(output, label)\n        errD_real.backward()\n        D_x = output.mean().item()\n\n        # train with fake\n        noise = torch.randn(batch_size, nz, 1, 1, device=device)\n        fake = netG(noise)\n        label.fill_(fake_label)\n        output = netD(fake.detach())\n        errD_fake = criterion(output, label)\n        errD_fake.backward()\n        D_G_z1 = output.mean().item()\n        errD = errD_real + errD_fake\n        optimizerD.step()\n\n        ############################\n        # (2) Update G network: maximize log(D(G(z)))\n        ###########################\n        netG.zero_grad()\n        label.fill_(real_label)  # fake labels are real for generator cost\n        output = netD(fake)\n        errG = criterion(output, label)\n        errG.backward()\n        D_G_z2 = output.mean().item()\n        optimizerG.step()\n\n        print('[%d\/%d][%d\/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f \/ %.4f' % (epoch, niter, i, len(dataloader), errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n        \n        #save the output\n        if i % 100 == 0:\n            print('saving the output')\n            utils.save_image(real_cpu,'.\/\/real_samples.png',normalize=True)\n            fake = netG(fixed_noise)\n            utils.save_image(fake.detach(),'.\/\/fake_samples_epoch_%03d.png' % (epoch),normalize=True)\n        # Check how the generator is doing by saving G's output on fixed_noise\n        if (iters % 500 == 0) or ((epoch == niter-1) and (i == len(dataloader)-1)):\n            with torch.no_grad():\n                fake = netG(fixed_noise).detach().cpu()\n            img_list.append(utils.make_grid(fake, padding=2, normalize=True))\n        iters += 1\n    \n    # Check pointing for every epoch\n    torch.save(netG.state_dict(), '.\/\/netG_epoch_%d.pth' % (epoch))\n    torch.save(netD.state_dict(), '.\/\/netD_epoch_%d.pth' % (epoch))\nplt.figure(figsize=(10,5))\nplt.title(\"Generator and Discriminator Loss During Training\")\nplt.plot(g_loss,label=\"G\")\nplt.plot(d_loss,label=\"D\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()\n# Plot the fake images from the last epoch\nplt.subplot(1,2,2)\nplt.axis(\"off\")\nplt.title(\"Fake Images\")\nplt.imshow(np.transpose(img_list[-1],(1,2,0)))\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'f03d29a7d186db'}"}
{"id":"34760","text":"\"\"\"\n# Introduction\n\"\"\"\n# Libraries loading\nimport pandas as pd\nimport os\nfrom datetime import datetime,timedelta\nimport warnings\nimport pandas as pd\n%matplotlib inline\nimport matplotlib.pyplot as plt  \nimport seaborn as sns\ncolor = sns.color_palette()\nsns.set_style('darkgrid')\nfrom scipy import stats\nfrom scipy.stats import norm, skew #statistics for normality and skewness\nimport numpy as np\nip = get_ipython()\nibe = ip.configurables[-1]\nibe.figure_formats = { 'pdf', 'png'}\nwarnings.filterwarnings(\"ignore\")\nDATA_DIR='\/kaggle\/input\/atp-and-wta-tennis-data'\ndf_atp = pd.read_csv(os.path.join(DATA_DIR,\"df_atp.csv\"),index_col=0)\ndf_atp[\"Date\"] =df_atp.Date.apply(lambda x:datetime.strptime(x, '%Y-%m-%d'))\ndf_atp.head()\nprint(\"Total number of matches : \"+str(len(df_atp)))\nprint(list(df_atp.columns))\n\"\"\"\nWe drop the ATP column (Tournament number (men)) because it does seem intuitively unimportant  specially for the prediction phase and it might be even contagious to our model if we forget it in the training phase (Example : it might add some leakage into our model)\n\"\"\"\n#verifying the shape of the dataset before droping the 'ATP' column.\nprint(\"Shape of the Dataset before droping the 'ATP' Column : {} \".format(df_atp.shape))\n\n#Saving the column (maybe for later use ?)\ndf_atp_ID = df_atp['ATP']\n\n#Droping the column \ndf_atp.drop(\"ATP\", axis = 1, inplace = True)\n\n#verifying the shape of the dataset after droping the 'ATP' column\nprint(\"\\nShape of the Dataset after droping the 'ATP' Column : {} \".format(df_atp.shape))\n\"\"\"\n## Quick glumpse at the data and answering some questions\n\"\"\"\n\"\"\"\n** 1.\tWho are the three ATP players with the most wins ? **\n\"\"\"\ndf_atp['Winner'].describe()\ndf_atp['Winner'].value_counts()[0:3]\n#Return a Series containing counts of unique values in descending order so that the first element is the most frequently-occurring element.\ndf_atp['Loser'].describe()\ndf_atp['Loser'].value_counts()[0:3]\n\"\"\"\nWe can see that 'Federer R.' is by far the player with most victories in tournaments being ahead of the second most winner in tournament by 230 matches. While 'Lopez F.' being the player with most losses in Tournaments is only ahead the second most loser one after him with only 14 matches.\n\"\"\"\n\"\"\"\nLet's see how these 3  player we were talking about have done in both victories and losses.\n\"\"\"\nprint(\"'Federer R.'  have won \" + str(len(df_atp[df_atp['Winner']=='Federer R.']) )+\" and lost \" +str(len(df_atp[df_atp['Loser']=='Federer R.' ])))\nprint(\"'Nadal R.'    have won \" + str(len(df_atp[df_atp['Winner']=='Nadal R.'])) +\" and lost \" +str(len(df_atp[df_atp['Loser']=='Nadal R.' ])))\nprint(\"'Djokovic N.' have won \" + str(len(df_atp[df_atp['Winner']=='Djokovic N.'])) +\" and lost \" +str(len(df_atp[df_atp['Loser']=='Djokovic N.' ])))\nprint(\"'Lopez F.'    have won \" + str(len(df_atp[df_atp['Winner']=='Lopez F.'])) +\" and lost \" +str(len(df_atp[df_atp['Loser']=='Lopez F.' ])))\nprint(\"'Youzhny M.'  have won \" + str(len(df_atp[df_atp['Winner']=='Youzhny M.'])) +\" and lost \" +str(len(df_atp[df_atp['Loser']=='Youzhny M.' ])))\nprint(\"'Verdasco F.' have won \" + str(len(df_atp[df_atp['Winner']=='Verdasco F.'])) +\" and lost \" +str(len(df_atp[df_atp['Loser']=='Verdasco F.' ])))\n\"\"\"\nWe can see that the top 3 performers: 'Federer R.', 'Nadal R.' and 'Djokovic N.' have won many matches but lost at most less than the quarter of that number in matches. While the top player who lost the most matches : 'Lopez F.', 'Youzhny M.' and 'Verdasco F.'  have only won about the same number of matches.\n\"\"\"\n\"\"\"\n**2.\tHow many sets did the player \u201cFederer R.\u201d win in total ?** \n\"\"\"\ndf_atp['Lsets']= pd.to_numeric(df_atp['Lsets'], errors='coerce')#tranforming str to numeric values and replcing with nan when we can't\nN_sets = df_atp['Wsets'][df_atp['Winner']=='Federer R.'].sum() + df_atp['Lsets'][df_atp['Loser']=='Federer R.'].sum()\n\nprint('\\nPlayer \u201cFederer R.\u201d won a total of : ' + str(N_sets) + ' sets.\\n')\n\"\"\"\n** 3.\tHow many sets did the player \u201cFederer R.\u201d win during the years 2016 and 2017 ?**\n\"\"\"\n\"\"\"\nNumber of sets the player 'Federer R.' won in 2016 alone:\n\"\"\"\nbeg = datetime(2016,1,1)\nend = datetime(2017,1,1)\ndf_atp_2016 = df_atp[(df_atp['Date']>=beg)&(df_atp['Date']<end)]\ndf_atp_2016['Wsets'][df_atp_2016['Winner']=='Federer R.'].sum() + df_atp_2016['Wsets'][df_atp_2016['Loser']=='Federer R.'].sum()\n\"\"\"\nNumber of sets the player 'Federer R.' won in 2017 alone:\n\"\"\"\nbeg = datetime(2017,1,1)\nend = datetime(2018,1,1)\ndf_atp_2017 = df_atp[(df_atp['Date']>=beg)&(df_atp['Date']<end)]\ndf_atp_2017['Wsets'][df_atp_2017['Winner']=='Federer R.'].sum() + df_atp_2017['Wsets'][df_atp_2017['Loser']=='Federer R.'].sum()\n\"\"\"\nNumber of sets the player 'Federer R.' won during 2016 and 2017: 68+131 = 199 or : \n\"\"\"\nbeg = datetime(2016,1,1)\nend = datetime(2018,1,1)\ndf_atp_2017 = df_atp[(df_atp['Date']>=beg)&(df_atp['Date']<=end)]\ndf_atp_2017['Wsets'][df_atp_2017['Winner']=='Federer R.'].sum() + df_atp_2017['Wsets'][df_atp_2017['Loser']=='Federer R.'].sum()\n\"\"\"\n**4.\tFor each match, what is the percentage of victories of the winner in the past ?**\n\"\"\"\nunique_player_index_and_score = {}\n#Dictionary containing the player name as a key and the tuple (player_unique_index,x,y)\n#x : number_of_matches_won\n#y : number_of_matches played\n# x and y are intiated 0 in the bigining but as we go through the data set we increment x and y by 1 if the player wins a match\n# or we increment only y with 1 if the player loses a matches\ni=0\nfor player in df_atp['Winner'].unique():\n    if player not in unique_player_index_and_score.keys():\n        unique_player_index_and_score[player] = (i,0,0)\n        i+=1\nfor player in df_atp['Loser'].unique():\n    if player not in unique_player_index_and_score.keys():\n        unique_player_index_and_score[player] = (i,0,0)\n        i+=1\n        \nprint('Number of unqiue player names : ',i)\nwinner_loser_score_tracking_vector = np.zeros((len(df_atp),2)) \n# two columns one to track the winner percetage and the other for the loser percentage \n#Sorting dataset by date so we can perform our calculation of the player prior win poucentage coorectly by looping one time trough the dataset\ndf_atp=df_atp.sort_values(by='Date')\nfor c,row in enumerate(df_atp[['Winner','Loser']].values):\n    score_winner = unique_player_index_and_score[row[0]]#Winner up-to date score tracking from the dictionary \n    score_loser = unique_player_index_and_score[row[1]]#Loser up-to date score tracking from the dictionary\n    #we consider new player that haven't yet played 5 matches as the have 20% of winning in the past \n    #(kind of a fair approach as they worked hard to get to play in the tournement:))\n    if score_winner[2]<5:\n        winner_loser_score_tracking_vector[c,0]=0.2\n    else:\n        winner_loser_score_tracking_vector[c,0] =score_winner[1]\/score_winner[2]\n    if score_loser[2]<5:\n        winner_loser_score_tracking_vector[c,1]=0.2\n    else:\n        winner_loser_score_tracking_vector[c,1] = score_loser[1]\/score_loser[2]\n    #updating the dictionary based on the new outcome of the current match\n    unique_player_index_and_score[row[0]] = (score_winner[0],score_winner[1]+1,score_winner[2]+1)#Winner\n    unique_player_index_and_score[row[1]] = (score_loser[0],score_loser[1],score_loser[2]+1)#loser\n    \ndf_atp['Winner_percentage'] = winner_loser_score_tracking_vector[:,0]\ndf_atp['Loser_percentage'] = winner_loser_score_tracking_vector[:,1]\ndf_atp['Winner_percentage'].describe()\ndf_atp['Loser_percentage'].describe()\nsns.distplot(df_atp['Winner_percentage'], label=\"Winners\")\nsns.distplot(df_atp['Loser_percentage'], label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Winners and Losers prior win probabilityt')\nplt.title('Winners and Losers prior win probability Distributionn')\nplt.legend()\n\"\"\"\nAs we say earlier, the are some winner (the top 3 or 4 performers maybe) have a prior win probability that is very high in the range of [0.75,0.82]. We can see also that Winners tend to win and loser tend to lose from the intersection of the two histograms.\n\"\"\"\nsns.distplot(df_atp['Winner_percentage'] , fit=norm);\n\n#R\u00e9cup\u00e8rer les param\u00e8tres ajust\u00e9s utilis\u00e9s par la fonction\n(mu, sigma) = norm.fit(df_atp['Winner_percentage'])\n#Tracer la ditribution\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n            loc='best')\nplt.ylabel('Frequency')\nplt.title('Winner percentage Distribution')\nfig = plt.figure()\nres = stats.probplot(df_atp['Winner_percentage'], plot=plt)\nsns.distplot(df_atp['Loser_percentage'] , fit=norm);\n\n#R\u00e9cup\u00e8rer les param\u00e8tres ajust\u00e9s utilis\u00e9s par la fonction\n(mu, sigma) = norm.fit(df_atp['Loser_percentage'])\n#Tracer la ditribution\nplt.legend(['Normal dist. ($\\mu=$ {:.2f} and $\\sigma=$ {:.2f} )'.format(mu, sigma)],\n            loc='best')\nplt.ylabel('Frequency')\nplt.title('Loser pourcentage Distribution')\nfig = plt.figure()\nres = stats.probplot(df_atp['Loser_percentage'], plot=plt)\n\"\"\"\nthe distribution of prior win probability for winner haveextremes values near 0.8  and the ditribution for losers have many values in 0.2 (these are for the playes that have not yet played 5 matches in in tournement in their lifetime). Beside that, both distributions follow an almost normal ditribution Loking at their histogram plot and probability plot expet in the range of \n\"\"\"\n\"\"\"\n## Exploratory Data analisys and Data processing:\n\"\"\"\n\"\"\"\nWe'll start by the amount of missing data:\n\"\"\"\ntrain_na = (df_atp.isnull().sum() \/ len(df_atp)) * 100\ntrain_na = train_na.drop(train_na[train_na == 0].index).sort_values(ascending=False)\nmissing_data = pd.DataFrame({'Pourcentage of missing values' :train_na})\nmissing_data\n#With a visiualisation:\nf, ax = plt.subplots(figsize=(15, 12))\nplt.xticks(rotation='90')\nsns.barplot(x=train_na.index, y=train_na)\nplt.xlabel('Columns', fontsize=15)\nplt.ylabel('Pourcentage of missing values', fontsize=15)\nplt.title('Pourcentage of missing values by variables', fontsize=15)\n\"\"\"\nSome explications about this missing values:\n- Most of the columns with big missing values are from the odds of betting sites: we shall remove all these columns and keep the columns of the three betting sites :  Bet365, EX and PS. First we are going to train a model with data containing these values and also another one with data not containing these values to see its effects on our score. We will be using thoses to also calculate how much we'll win or lose in we used a very simple betting stategy based on the prediction of our model :)\n\n- The columns L5,L4,W4,W5 (Number of games won in 5th\\4th set by match winner\\loser respectivly) have missing values because some matches have only 'best out of 3sets' rule while some have 'best out of 5sets' rules.\n- We can think intuitively that we can't use either the columns L1 trough L5 or W5 trought W1 in our predictive modeling phase training data as those variable are set after the matches finishes and we'll be using a discriminative approach in our modeling. So we'll remove those columns too. We can maybe use them if we want to calculate a modified wining set prior probability of each player (in a more advanced modelisation we can think of predicting those values).\n\nThe following columns:\n\n- MaxW= Maximum odds of match winner (as shown by Oddsportal.com)\n- MaxL= Maximum odds of match loser (as shown by Oddsportal.com)\n- AvgW= Average odds of match winner (as shown by Oddsportal.com)\n- AvgL= Average odds of match loser (as shown by Oddsportal.com)\n\nmaybe having missing as there are mssing values in some matches from all the betting site ? We shall remove them as more than 60 of these column vlues are missing.\n\n- The columns Lstes and Wsets wich mean Number of sets won by match loser\/winner can't be used in as entry data to our model as they are too know after the moatches have finished. But, we we'll keep them to make another variable witch will be the prior probability of winning a sets in the past. We will replace the nan values by mean or median after we explore these columns.\n\n- As for Lrank or WRank columns, I can't imagine another senario as the one of a new player that just got for the first time in the tournements. we will replace those too by mean or median after we explore those columns too.\n\nThe same applies to the following columns :\n\n- WPts = ATP Entry points of the match winner as of the start of the tournament\n- LPts = ATP Entry points of the match loser as of the start of the tournament\n\n\"\"\"\n#Drop the columns with missing values and that we won't be using:\nfor column in train_na.index[:26]:\n    df_atp.drop(column, axis = 1, inplace = True)\n#With a visiualisation:\ntrain_na = (df_atp.isnull().sum() \/ len(df_atp)) * 100\ntrain_na = train_na.drop(train_na[train_na == 0].index).sort_values(ascending=False)\nmissing_data = pd.DataFrame({'Pourcentage of missing values' :train_na})\nf, ax = plt.subplots(figsize=(15, 12))\nplt.xticks(rotation='90')\nsns.barplot(x=train_na.index, y=train_na)\nplt.xlabel('Columns', fontsize=15)\nplt.ylabel('Pourcentage of missing values', fontsize=15)\nplt.title('Pourcentage of missing values by variables', fontsize=15)\n\"\"\"\n- We also drop the columns W1,L1,W2,L2 as they are intuitivly useless as explained earlier.\n\n\"\"\"\ndf_atp.drop('W1', axis = 1, inplace = True)\ndf_atp.drop('L1', axis = 1, inplace = True)\ndf_atp.drop('W2', axis = 1, inplace = True)\ndf_atp.drop('L2', axis = 1, inplace = True)\n\"\"\"\nLet\"s explore the remaining columns to see what the best possible values to replace the nan values.\n\"\"\"\nsns.distplot(df_atp['WPts'].dropna(), label=\"Winners\")\nsns.distplot(df_atp['LPts'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\n\"\"\"\nseems legit to replace it by mode\n\"\"\"\nsns.distplot(df_atp['PSW'].dropna(), label=\"Winners\")\nsns.distplot(df_atp['PSL'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\n\"\"\"\nalso mode\n\"\"\"\ndf_atp['EXW']= pd.to_numeric(df_atp['EXW'], errors='coerce')\ndf_atp['EXW']= pd.to_numeric(df_atp['EXW'], errors='coerce')\nsns.distplot(df_atp['EXW'].dropna(), label=\"Winners\")\nsns.distplot(df_atp['EXL'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\ndf_atp['B365W']= pd.to_numeric(df_atp['B365W'], errors='coerce')\nsns.distplot(df_atp['B365W'].dropna(), label=\"Winners\")\nsns.distplot(df_atp['B365L'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\n\"\"\"\nalso mode\n\"\"\"\ndf_atp['Wsets']=pd.to_numeric(df_atp['Wsets'],errors='coerce' )\n#df_atp['Lsets']=pd.to_numeric(df_atp['Lsets'],errors='coerce')\n#df_atp['Wsets'].replace('scott', np.nan, inplace=True)\nsns.distplot(df_atp['Wsets'].dropna(), label=\"Winners\",kde=False)\nsns.distplot(df_atp['Lsets'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\ndf_atp['LRank']=pd.to_numeric(df_atp['LRank'],errors='coerce' )\ndf_atp['WRank']=pd.to_numeric(df_atp['WRank'],errors='coerce' )\nsns.distplot(df_atp['LRank'].dropna(), label=\"Winners\")\nsns.distplot(df_atp['WRank'].dropna(), label=\"Losers\")\nplt.ylabel('Frequency')\nplt.xlabel('Pourcentage of victory in the past')\nplt.title('Winners and Losers pourcentage Distribution')\nplt.legend()\n\"\"\"\nreplacring the value by the mode or mean then plotting poucentage of missing again.\n\"\"\"\ncolumns=['WPts','LPts','PSW','PSL','EXW','EXL','B365W','B365L','Lsets','Wsets','LRank','WRank']\nfor column in columns:\n    df_atp[column]=df_atp[column].fillna(float(df_atp[column].mode()[0]))\ntrain_na = (df_atp.isnull().sum() \/ len(df_atp)) * 100\ntrain_na = train_na.drop(train_na[train_na == 0].index).sort_values(ascending=False)\nmissing_data = pd.DataFrame({'Pourcentage of missing values' :train_na})\nmissing_data\n#No more missing values\n\"\"\"\n## More data processing for our datasets so we can use it for prediction and EDA\n\"\"\"\ndf_atp.columns\n\"\"\"\nDescription of the rest of the Data:\n- 'B365L', 'B365W','EXL', 'EXW','PSL', 'PSW' : Just betting odds for wiiner and loser repsctivly.\n- 'Bestof' : Maximum number of sets playable in match.\n- 'Comment' :Comment on the match (Completed, won through retirement of loser, or via Walkover)\n- 'Court' :  Type of court (outdoors or indoors)\n- 'Date' : date of the match obviously.\n- 'WPts','LPts' : ATP Entry points of the match winner\/loser as of the start of the tournament repectivly.\n- 'Location' : Venue of tournament.\n- 'Winner','Loser' :  Name of winner\/loser respectively.\n- 'Wsets','Lsets' : Number of sets won by match winner\/loser respectively\n- 'Round' : Round of match\n- 'Series' : Name of ATP tennis series (Grand Slam, Masters, International or International Gold)\n- 'Surface' : Type of surface (clay, hard, carpet or grass)\n- 'Tournament' : me of tounament (including sponsor if relevant)\n- 'WRank','LRank' : ATP Entry ranking of the match winner\/loser respectively as of the start of the tournament\n- 'Winner_percentage','Loser_percentage': ...\n\"\"\"\n\"\"\"\nAs we said earlier, the column 'B365L', 'B365W','EXL', 'EXW','PSL', 'PSW' will be used in a our modelisationat first and we develop also the same models without those columns. We can think of these columns as some already calculated features given to us by the betting company.\n\n- The 'comment' column is an event that happend after the matches is finisehd so we'll not be using it too.\n\n- 'Wsets' and 'Lsets' columns are that reprensents events that happens after the matche is finnished so we'll not be usig it in our model but we'll make of it a new column that reprensets the winner\/loser percentage of winning a sets in the past. But we'll drop them after we do some feature engineering with that won't include them having doing some leakage of the target variable; we'll use the calclculate the probability of a player to win a set in the past.\n\n- All the rest of the columns will be used except maybe fot the tournement name and Location that we'll need to explore them first to see.\n\"\"\"\ndf_atp.drop(\"Comment\", axis = 1, inplace = True)\ndf_atp.columns\ndf_atp.Tournament.describe()\ndf_atp.Location.describe()\nlen(df_atp)\n\"\"\"\nBoth columns have only 214,115 unique in a 52298 Data set. thinking about also removing the 2018 and 2017 matches (the later for the tests) and using a cross validation function. I'm not sure if they have any predcitve power seing the few samples for each class. but we'll be keeping them as predictive variables.\n\"\"\"\ndf_atp.describe()\n\"\"\"\n###### Calculating the player prior win set probability : \n\"\"\"\n#winner prior sets winns pourcentage column\nunique_player_index_and_score = {}\n#Dictionary containing the player name as a key and the tuple (player_unique_index,x,y)\n#x : number_of_set_won\n#y : number_of_sets_played\n# x and y are intiated 0 in the bigining but as we go through the data set we increment x Wsets(or Lsets) witch are the number of\n# won by matches winner(orloser) and we increment y by Wsets+Lsets wich is the number of stes played in that match\ni=0\nfor player in df_atp['Winner'].unique():\n    if player not in unique_player_index_and_score.keys():\n        unique_player_index_and_score[player] = (i,0,0)\n        i+=1\nfor player in df_atp['Loser'].unique():\n    if player not in unique_player_index_and_score.keys():\n        unique_player_index_and_score[player] = (i,0,0)\n        i+=1\n        \nprint('Number of unqiue player names : ',i)\nwinner_loser_score_tracking_vector = np.zeros((len(df_atp),2)) \n# two columns one to track the winner percetage and the other for the loser percentage \ndf_atp=df_atp.sort_values(by='Date')\nfor i in range(len(df_atp)):\n    row=[df_atp.Winner[i],df_atp.Loser[i]]\n    score_winner = unique_player_index_and_score[row[0]]#Winner up-to date set win score tracking from the dictionary \n    score_loser = unique_player_index_and_score[row[1]]#Loser up-to date  set win score tracking from the dictionary\n    #we consider new player that haven't yet had 15 sets yet as they had a 20% of winning in the past \n    #(kind of a fair optimist approach as the worked hard to get to play in the tournement:))\n    if int(score_winner[2])<15:\n        winner_loser_score_tracking_vector[i,0]=0.2\n    else:\n        winner_loser_score_tracking_vector[i,0] =score_winner[1]\/score_winner[2]\n    if score_loser[2]<15:\n        winner_loser_score_tracking_vector[i,1]=0.2\n    else:\n        winner_loser_score_tracking_vector[i,1] = score_loser[1]\/score_loser[2]\n    #updating the dictionary based on the new outcome of the current match\n    unique_player_index_and_score[row[0]] = (score_winner[0],score_winner[1]+float(df_atp.Wsets[i]),score_winner[2]+float(df_atp.Wsets[i]+df_atp.Lsets[i]))#Winner\n    unique_player_index_and_score[row[1]] = (score_loser[0],score_loser[1]+float(df_atp.Lsets[i]),score_loser[2]+float(df_atp.Wsets[i]+df_atp.Lsets[i]))#loser\n    \ndf_atp['Winner_set_percentage'] = winner_loser_score_tracking_vector[:,0]\ndf_atp['Loser_set_percentage'] = winner_loser_score_tracking_vector[:,1]\n\ndf_atp['Winner_set_percentage'].describe()\nsns.distplot(df_atp['Winner_set_percentage'])\ndf_atp['Loser_set_percentage'].describe()\nsns.distplot(df_atp['Loser_set_percentage'])\n\"\"\"\nAgain we can remark that winners tend to win and loser tend to lose.\n\"\"\"\n\"\"\"\n###### Calculating the Elo ranking features : \n\"\"\"\n\"\"\"\nThe Elo rating system is a method for calculating the relative skill levels of players in zero-sum games such as chess. It is named after its creator Arpad Elo, a Hungarian-American physics professor.\n\nThe difference in the ratings between two players serves as a predictor of the outcome of a match. Two players with equal ratings who play against each other are expected to score an equal number of wins. A player whose rating is 100 points greater than their opponent's is expected to score 64%; if the difference is 200 points, then the expected score for the stronger player is 76%.\n\"\"\"\n#Not mine, I took from the internet But i got a full understanding of it :)\ndef compute_elo_rankings(data):\n    \"\"\"\n    Given the list on matches in chronological order, for each match, computes \n    the elo ranking of the 2 players at the beginning of the match\n    \n    \"\"\"\n    print(\"Elo rankings computing...\")\n    players=list(pd.Series(list(data.Winner)+list(data.Loser)).value_counts().index)\n    elo=pd.Series(np.ones(len(players))*1500,index=players)\n    ranking_elo=[(1500,1500)]\n    for i in range(1,len(data)):\n        w=data.iloc[i-1,:].Winner\n        l=data.iloc[i-1,:].Loser\n        elow=elo[w]\n        elol=elo[l]\n        pwin=1 \/ (1 + 10 ** ((elol - elow) \/ 400))    \n        K_win=32\n        K_los=32\n        new_elow=elow+K_win*(1-pwin)\n        new_elol=elol-K_los*(1-pwin)\n        elo[w]=new_elow\n        elo[l]=new_elol\n        ranking_elo.append((elo[data.iloc[i,:].Winner],elo[data.iloc[i,:].Loser])) \n        if i%5000==0:\n            print(str(i)+\" matches computed...\")\n    ranking_elo=pd.DataFrame(ranking_elo,columns=[\"elo_winner\",\"elo_loser\"])    \n    ranking_elo[\"proba_elo\"]=1 \/ (1 + 10 ** ((ranking_elo[\"elo_loser\"] - ranking_elo[\"elo_winner\"]) \/ 400))   \n    return ranking_elo\nElo =  compute_elo_rankings(df_atp)\ndf_atp[\"Elo_Winner\"] = Elo[\"elo_winner\"]\ndf_atp[\"Elo_Loser\"] = Elo[\"elo_loser\"]\ndf_atp[\"Proba_Elo\"]= Elo[\"proba_elo\"]\nsns.distplot(df_atp[\"Elo_Winner\"], label=\"Winners\")\nsns.distplot(df_atp[\"Elo_Loser\"], label=\"Losers\")\nplt.legend()\n\"\"\"\nagain winners tend to win biger elo rating and loser tend to have a smaller one.\n\"\"\"\nsns.distplot(df_atp[\"Proba_Elo\"],fit=norm)\n\"\"\"\nOur distribution of probability is little skewwed trough the right.\n\"\"\"\n\"\"\"\n* Let's now drop those 'Wsets' and 'Lsets' columns as they reprensents events that happens after the matche  is finished.\n \n\"\"\"\ndf_atp.drop(['Wsets','Lsets'], axis = 1, inplace = True)\n\"\"\"\nOne last transformation of our data to augmented it and in the mean time to make it ready for modelisation and to explore it more too.\n\n-For each row describing a match we'll be having two resulting row. One with target variable 1 and we keep the columns as they are and one with the target variable 0 we put the invert the column of the wiinner with that of the loser and the column of the loser with that the wiinner and we keep the rest of the columsn as they are. That will double the amount of our traning data and will also transform our problem to a binary classification problem.\n\"\"\"\ntarget_1 = np.ones(len(df_atp))\ntarget_2 = np.zeros(len(df_atp))\ntarget_1 = pd.DataFrame(target_1,columns=['label'])\ntarget_2 = pd.DataFrame(target_2,columns=['label'])\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import OneHotEncoder\nimport category_encoders as ce\nprint(df_atp.columns)\nfeatures_categorical = df_atp[[\"Series\",\"Court\",\"Surface\",\"Round\",\"Best of\",\"Tournament\"]].copy()\nfeatures_onehot = pd.get_dummies(features_categorical)\n#tournaments_encoded = features_tournaments_encoding(df_atp)\n#features_binary = pd.concat([features_categorical_encoded,tournaments_encoded],1)\n\n## For the moment we have one row per match. \n## We \"duplicate\" each row to have one row for each outcome of each match. \n## Of course it isn't a simple duplication of  each row, we need to \"invert\" some features\n\n# Elo data\nelo_rankings = df_atp[[\"Elo_Winner\",\"Elo_Loser\",\"Proba_Elo\"]]\nelo_1 = elo_rankings\nelo_2 = elo_1[[\"Elo_Loser\",\"Elo_Winner\",\"Proba_Elo\"]]\nelo_2.columns = [\"Elo_Winner\",\"Elo_Loser\",\"Proba_Elo\"]\nelo_2.Proba_Elo = 1-elo_2.Proba_Elo\n# Player prior win probability\nwin_pourcentage = df_atp[['Winner_percentage', 'Loser_percentage']]\nwin_1 = win_pourcentage\nwin_2 = win_1[['Loser_percentage','Winner_percentage']]\nwin_2.columns = ['Winner_percentage', 'Loser_percentage']\n# Player prior win set probability\nset_win_pourcentage = df_atp[['Winner_set_percentage','Loser_set_percentage']]\nset_1 = set_win_pourcentage\nset_2 = set_1[['Loser_set_percentage','Winner_set_percentage']]\nset_2.columns = ['Winner_set_percentage','Loser_set_percentage']\n# Player entry points\nPts = df_atp[['WPts','LPts']]\nPts_1 = Pts\nPts_2 = Pts_1[['LPts','WPts']]\nPts_2.columns = ['WPts','LPts']\n# Player Entry Ranking\nRank = df_atp[['WRank','LRank']]\nRank_1 = Rank\nRank_2 = Rank_1[['LRank','WRank']]\nRank_2.columns = ['LRank','WRank']\n#Player Odds for winning\nOdds = df_atp[['EXW','EXL','PSW','PSL','B365W','B365L']]\nOdds_1 = Odds\nOdds_2 = Odds_1[['EXL','EXW','PSL','PSW','B365L','B365W']]\nOdds_2.columns = ['EXW','EXL','PSW','PSL','B365W','B365L']\n#Date \nDate_1 = df_atp.Date\nDate_2 = df_atp.Date\nelo_1.index = range(0,2*len(elo_1),2)\nelo_2.index = range(1,2*len(elo_1),2)\nwin_1.index = range(0,2*len(win_1),2)\nwin_2.index = range(1,2*len(win_1),2)\nset_1.index = range(0,2*len(set_1),2)\nset_2.index = range(1,2*len(set_1),2)\nPts_1.index = range(0,2*len(Pts_1),2)\nPts_2.index = range(1,2*len(Pts_1),2)\nRank_1.index = range(0,2*len(Rank_1),2)\nRank_2.index = range(1,2*len(Rank_1),2)\nOdds_1.index = range(0,2*len(Odds_1),2)\nOdds_2.index = range(1,2*len(Odds_1),2)\nDate_1.index = range(0,2*len(Date_1),2)\nDate_2.index = range(1,2*len(Date_1),2)\ntarget_1.index = range(0,2*len(target_1),2)\ntarget_2.index = range(1,2*len(target_1),2)\nfeatures_elo_ranking = pd.concat([elo_1,elo_2]).sort_index(kind='merge')\nfeatures_win_pourcentage = pd.concat([win_1,win_2]).sort_index(kind='merge')\nfeatures_set_pourcentage = pd.concat([set_1,set_2]).sort_index(kind='merge')\nfeatures_Pts = pd.concat([Pts_1,Pts_2]).sort_index(kind='merge')\nfeatures_Rank =  pd.concat([Rank_1,Rank_2]).sort_index(kind='merge')\nfeatures_Odds = pd.concat([Odds_1,Odds_2]).sort_index(kind='merge')\ntarget = pd.concat([target_1,target_2]).sort_index(kind='merge')\nDate = pd.concat([Date_1,Date_2]).sort_index(kind='merge').to_frame()\n'''\nfeatures_Odds.reset_index(drop=True, inplace=True)\nfeatures_elo_ranking.reset_index(drop=True, inplace=True)\n#features_onehot.reset_index(drop=True, inplace=True)\nfeatures_win_pourcentage.reset_index(drop=True, inplace=True)\nfeatures_set_pourcentage.reset_index(drop=True, inplace=True)\nfeatures_set_pourcentage.reset_index(drop=True, inplace=True)\nfeatures_Pts.reset_index(drop=True, inplace=True)\nfeatures_Rank.reset_index(drop=True, inplace=True)\nfeatures_Odds.reset_index(drop=True, inplace=True)\ntarget.reset_index(drop=True, inplace=True)\n'''\nfeatures_onehot = pd.DataFrame(np.repeat(features_onehot.values,2, axis=0),columns=features_onehot.columns)\nfeatures_onehot.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_Odds.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_elo_ranking.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_win_pourcentage.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_set_pourcentage.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_Pts.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_Rank.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nfeatures_Odds.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\ntarget.set_index(pd.Series(range(0,2*len(df_atp))), inplace=True)\nDate.set_index(pd.Series(range(0,2*len(df_atp))),inplace=True)\n### Building of the pre final dataset \n# We can remove some features to see the effect on our model\nfeatures = pd.concat([features_win_pourcentage,\n                  features_set_pourcentage,\n                  features_elo_ranking,\n                  features_Pts,\n                  features_Rank,\n                  features_Odds,\n                  features_onehot,\n                  Date,\n                  target],1)\n\n\n#Setting the 2019 matches as the test dataset.\n#beg = datetime(2016,1,1)\nend_train = datetime(2019,1,1)\nbeg_test = datetime(2019,1,1)\nend_test = datetime(2020,1,1)\ntrain = features[features['Date']<end_train]\ntest = features[(features['Date']>=beg_test)&(features['Date']<end_test)]\n#For saving the features\n#features.to_csv(\"df_atp_features.csv\",index=False)\n#loading after saveing\n#features = pd.read_csv('df_atp_features.csv')\nprint(len(train))\nprint(len(test))\n\"\"\"\n# Modeling\n\"\"\"\n\"\"\"\nLet's see what might be our most important Features at first try. .\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\ndf = features.drop(columns=['Date','label'])\nfeat_forest = RandomForestClassifier(n_jobs=-1)\nfeat_forest.fit(X=df, y=features['label'])\n\nplt.figure(figsize=(10, 10))\nfeat_imp = feat_forest.feature_importances_\n\nfeat_imp, cols = zip(*sorted(zip(feat_imp, df.columns)))\nfeat_imp = np.array(feat_imp)[-30:]\ncols = np.array(cols)[-30:]\nd = {'feat_name': cols\n    ,'feat_imp': feat_imp }\nimportance =  pd.DataFrame(data=d)\nsns.barplot( x=  importance['feat_imp'],y = importance['feat_name']\n           );\nplt.yticks(range(len(cols[-30:])), cols[-30:])\nplt.title(\"Features Relevance for Classification\")\nplt.xlabel(\"Relevance Percentage\")\n\"\"\"\nI will try to build models that are not relying on betting odds,because I've tested models relying on betting odds and the performance were great almost 98% for the best model. Let's remove those columns from the train and test set and see what we'll get; the concerned columns that needs to be removed are : 'EXW','EXL','PSW','PSL','B365W' and 'B365L'\n\"\"\"\n\"\"\"\n## Modeling and performance evaluation:\n\"\"\"\n\"\"\"\nWe will use a StratifiedKFold as our cross validation strategy(with k=10) to evaluate our models performance on the training phase. After that, we assess our models on the testing data as well and see if those score are signitifictly closer to each other or that we're over-fiting.\n\"\"\"\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split,StratifiedKFold\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, make_scorer\n# We will be using the accuracy, precision,recall and the f1  as scores to asses our model performence\n#Importing most important alogorithms \nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC#we will not be using SVM due tot he huge training time required on our dataset.\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis,LinearDiscriminantAnalysis\n\nfrom sklearn import model_selection #Cross-validation multiple scoring function\n\n#features.drop(Odds_1.columns,axis=1,inplace=True)\nX = train.drop(columns=['Date','label','EXW', 'EXL', 'PSW', 'PSL', 'B365W', 'B365L'])\nY = train['label']\n# prepare configuration for cross validation test harness\nseed = 42\n# prepare models\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('QDA',QuadraticDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier(5, n_jobs=-1)))\nmodels.append(('CART', DecisionTreeClassifier(max_depth=10)))\nmodels.append(('NB', GaussianNB()))\n#models.append(('SVM_linear', SVC(kernel=\"linear\", C=0.025)))\n#models.append(('SVM_',SVC(gamma=2, C=1)))\nmodels.append(('RandomForest',RandomForestClassifier( n_estimators=100, n_jobs=-1)))\nmodels.append(('MLP',MLPClassifier(alpha=0.0001)))\nmodels.append(('ADABoost',AdaBoostClassifier()))\n\n# evaluate each model in turn\n\nresults = []\nscoring = {'accuracy': make_scorer(accuracy_score),\n          'precision_score': make_scorer(precision_score),\n          'recall_score' : make_scorer(recall_score),\n          'f1_score' : make_scorer(f1_score)}\nnames = []\nfor name, model in models:\n    stratifiedKFold = model_selection.StratifiedKFold(n_splits=10, random_state=seed)\n    cv_results = model_selection.cross_validate(model, X, Y, cv=stratifiedKFold, scoring=scoring) \n    results.append(cv_results)\n    names.append(name)\n    msg ='-------------------------------------------------------------------------------------------------------------\\n'\n    msg = \"Model : %s \\n\" % (name)\n    msg = msg +'\\n'\n    msg =  msg + \"Accuracy :  %f (%f)\\n\" % (cv_results['test_accuracy'].mean(),cv_results['test_accuracy'].std())\n    msg =  msg + \"Precision score :  %f (%f)\\n\" % (cv_results['test_precision_score'].mean(),cv_results['test_precision_score'].std())\n    msg =  msg + \"Recall score :  %f (%f)\\n\" % (cv_results['test_recall_score'].mean(),cv_results['test_recall_score'].std())\n    msg =  msg + \"F1 score :  %f (%f)\\n\" % (cv_results['test_f1_score'].mean(),cv_results['test_f1_score'].std())\n    msg = msg + '------------------------------------------------------------------------------------------------------------\\n'\n    print(msg)\nAccuracy = []\nPrecision = []\nRecall = []\nF1 = []\nfor idx,scores in enumerate(results):\n    Accuracy.append(scores['test_accuracy'])\n    Precision.append(scores['test_precision_score'])\n    Recall.append(scores['test_recall_score'])\n    F1.append(scores['test_f1_score'])\n    \nfig = plt.figure(figsize=(14,12))\nfig.suptitle('Algorithms Comparison')\nax = fig.add_subplot(221)\nplt.boxplot(Accuracy)\nplt.title('Accuracy score')\nax.set_xticklabels(names)\nax = fig.add_subplot(222)\nplt.boxplot(Precision)\nplt.title('Precision Score')\nax.set_xticklabels(names)\nax = fig.add_subplot(223)\nplt.boxplot(Recall)\nax.set_xticklabels(names)\nplt.title('Recall score')\nax = fig.add_subplot(224)\nplt.title('F1 score')\nplt.boxplot(F1)\nax.set_xticklabels(names)\n\nplt.show()\n\n\n\"\"\"\nWe can see clearly that almoust all our models have accuracy, precision, recaal, f1 score that are somewhat descent for a first try. But the neural network model with 100 hidden layers is the most well performing by far, followed by the CART model and followed suprisingly by K nearst neighbour classifiers. Let's see if this same performance is reflected on our test set too.\n\"\"\"\n#now to test\nfrom time import time\n\nX_test = test.drop(columns=['Date','label','EXW', 'EXL', 'PSW', 'PSL', 'B365W', 'B365L'])\nY_test = test['label']\n\ny_pred = []\ntrain_time = []\n\nfor name, model in models:\n    tic = time()\n    model.fit(X, Y)\n    toc = time()\n    \n    y_pred.append(model.predict(X_test))\n    train_time.append(toc - tic)\n    \n    print(\"Classifier : {} ===> Training duration : {} sec\".format(name, train_time[-1]))\n    \n\n    \nreports = []\nmetrics = [\"Classifier\", \"Accuracy\", \"Precision\", \"Recall\", \"F1-Score\",'Training Duration (seconds)']\nfor idx, y_clf in enumerate(y_pred):\n    acc = accuracy_score(Y_test, y_clf)\n    pre = precision_score(Y_test, y_clf)\n    rec = recall_score(Y_test, y_clf)\n    f1s = f1_score(Y_test, y_clf)\n    report = (models[idx][0], acc, pre, rec, f1s,train_time[idx])\n    reports.append(report)       \ndisplay(pd.DataFrame.from_records(reports, columns=metrics))\nreports = pd.DataFrame.from_records(reports, columns=metrics)\nplt.figure(figsize=(10,10))\nplt.plot(reports['Classifier'].values, reports['Accuracy'].values,\n             label='Accuracy' )\nplt.plot(reports['Classifier'], reports['Precision'], lw=1, alpha=0.6,\n             label='Precision' )\nplt.plot(reports['Classifier'], reports['Recall'], lw=1, alpha=0.6,\n             label='Recall' )\nplt.plot(reports['Classifier'], reports['F1-Score'], lw=1, alpha=0.6,\n             label='F1-Score' )\n\n\nplt.xlabel('Algorithm')\nplt.ylabel('score')\nplt.title('Algorithms comparison on test set')\nplt.legend(loc=\"lower right\")\nplt.show()\n\"\"\"\nThe scores from the cross-validation strategy are almost close to the ones found on the test set. and as we saw in the cross valisation phase We can see clearly that almoust all our models have accuracy, precision, recaal, f1 score that are somewhat descent for a first try. But the neural network model with 100 hidden layers is the most well performing by far, followed by the Random forest and CART models wich are followed by K nearst neighbour classifiers. Let's see if this same performance is reflected on our test set too.\n\"\"\"\nfrom sklearn.metrics import roc_curve, auc\nfrom scipy import interp\n\ny_prob = []\n\nfor name, model in models:\n    y_prob.append(model.predict_proba(X_test)[:,1])\n    \ntprs = []\naucs = []\nmean_fpr = np.linspace(0, 1, 100)\n\ni = 0\nplt.figure(figsize=(10,10))\nfor idx, y_clf in enumerate(y_prob):\n    # Compute ROC curve and area the curve\n    fpr, tpr, thresholds = roc_curve(Y_test, y_clf)\n    tprs.append(interp(mean_fpr, fpr, tpr))\n    tprs[-1][0] = 0.0\n    roc_auc = auc(fpr, tpr)\n    aucs.append(roc_auc)\n    plt.plot(fpr, tpr, lw=1, alpha=0.6,\n             label='ROC  Model %s (AUC = %0.2f)' % (models[idx][0], roc_auc))\n\n    i += 1\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n         label='Chance', alpha=.7)\nplt.xlim([-0.05, 1.05])\nplt.ylim([-0.05, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\n\"\"\"\nthe neural entwork model with 100 hiddens units has the best trade-off between sensitivity (true positive rate) and specificity (1 \u2013 false positive rate ) with Area Under ROC Curve close to 1.\n\"\"\"\n\"\"\"\n# Betting\n## Using our model for betting\n\"\"\"\n\"\"\"\nWe will try to assess the return on our investement if you relied on those models for our betting decisions.\n\"\"\"\nbetting_columns = ['EXL','EXW','PSL','PSW','B365L','B365W']\n#Columns containg the Odds\nBetting_Odds =  test[betting_columns]\n\n#Our Capital will be 1500Euros for each strategy and for each betting site for a single model. \nbudget_1 = 1500\n\nimport random\n\n\ndef rollDice():\n    roll = random.randint(1,100)\n\n    if roll == 100:\n        return False\n    elif roll <= 50:\n        return False\n    elif 100 > roll >= 50:\n        return True\n\n\n'''\nSimple bettor, betting the same amount each time. This will be our baselane.\n'''\ndef simple_bettor(data,y_true,budget):\n    #return on investement for each betting site\n    ROI_1 = budget\n    ROI_2 = budget\n    ROI_3 = budget\n    wager = 10\n\n    currentWager = 0\n\n    for i in range(len(data)):\n        if rollDice() and y_true.values[i]==1:\n            ROI_1 += wager*(data['EXW'].values[i]-1)\n            ROI_2 += wager*(data['PSW'].values[i]-1)\n            ROI_3 += wager*(data['B365W'].values[i]-1)\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        elif rollDice() and y_true.values[i]==0:\n            ROI_1 -= wager\n            ROI_2 -= wager\n            ROI_3 -= wager\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        elif not rollDice() and y_true.values[i]==0:\n            ROI_1 += wager*(data['EXL'].values[i]-1)\n            ROI_2 += wager*(data['PSL'].values[i]-1)\n            ROI_3 += wager*(data['B365L'].values[i]-1)\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        else :\n            ROI_1 -= wager\n            ROI_2 -= wager\n            ROI_3 -= wager\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n    if ROI_1<0:\n        ROI_1 = 0\n    if ROI_2<0:\n        ROI_2 = 0\n    if ROI_3<0:\n        ROI_3 = 0\n    return [(ROI_1-budget)\/budget,(ROI_2-budget)\/budget,(ROI_3-budget)\/budget]\n\n\n\n#If our model predict that a player is going to win, we'll invest 10Euros on that match for that player winning \n# and compare it with the real value to see if we won or lost\n\ndef strategy_1(data,y_pred,y_true,budget):\n    '''\n    \n       If our model predict that a player is going to win, we'll invest 10Euros on that match for that player winning \n       and compare it with the real value to see if we won or lost\n       \n    '''\n    #Retrun on investement for each betting site\n    ROI_1 = budget\n    ROI_2 = budget\n    ROI_3 = budget\n    for i in range(0,len(test)):\n        if y_pred[i]==1 and y_true.values[i]==1.0:\n            ROI_1 += 10*(data['EXW'].values[i]-1)\n            ROI_2 += 10*(data['PSW'].values[i]-1)\n            ROI_3 += 10*(data['B365W'].values[i]-1)\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        elif y_pred[i]==1 and y_true.values[i]==0.0:\n            ROI_1 += -10\n            ROI_2 += -10\n            ROI_3 += -10\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        elif y_pred[i]==0 and y_true.values[i] == 1.0:\n            #checking if we are already broke\n            ROI_1 += -10\n            ROI_2 += -10\n            ROI_3 += -10\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n        else :\n            ROI_1 += 10*(data['EXL'].values[i]-1)\n            ROI_2 += 10*(data['PSL'].values[i]-1)\n            ROI_3 += 10*(data['B365L'].values[i]-1)\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n            \n    if ROI_1<0:\n        ROI_1 = 0\n    if ROI_2<0:\n        ROI_2 = 0\n    if ROI_3<0:\n        ROI_3 = 0\n    return [(ROI_1-budget)\/budget,(ROI_2-budget)\/budget,(ROI_3-budget)\/budget]\n\ndef strategy_2(data,y_proba,y_true,budget):\n    '''\n    \n      In each match we'll invest 10(probability_player_win)Euros for the player winning, and 10(probability_player_lose)Euros\n      for the player losing\n\n    \n    '''\n    ROI_1 = budget\n    ROI_2 = budget\n    ROI_3 = budget\n    for i in range(0,len(test)):\n        if y_true.values[i]==1.0:\n            ROI_1 += y_proba[i]*10*(data['EXW'].values[i]-1) -(1- y_proba[i])*10\n            ROI_2 += y_proba[i]*10*(data['PSW'].values[i]-1) - (1-y_proba[i])*10\n            ROI_3 += y_proba[i]*10*(data['B365W'].values[i]-1) - (1-y_proba[i])*10\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n        else :\n            ROI_1 += (1-y_proba[i])*10*(data['EXL'].values[i]-1) - y_proba[i]*10\n            ROI_2 += (1-y_proba[i])*10*(data['PSL'].values[i]-1) - y_proba[i]*10\n            ROI_3 += (1-y_proba[i])*10*(data['B365L'].values[i]-1) - y_proba[i]*10\n            #checking if we are already broke\n            if ROI_1<=0:\n                ROI_1 = -100000000000000000000\n            if ROI_2<=0:\n                ROI_2 = -100000000000000000000\n            if ROI_3<=0:\n                ROI_3 = -100000000000000000000                \n\n    if ROI_1<0:\n        ROI_1 = 0\n    if ROI_2<0:\n        ROI_2 = 0\n    if ROI_3<0:\n        ROI_3 = 0\n    return [(ROI_1-budget)\/budget,(ROI_2-budget)\/budget,(ROI_3-budget)\/budget]\n\n\n#P.S: Seing how we contructed the dataset (Each row repeated one time). We'll be actualy investing 20Euros of our capital in each match instead of 10\n\n        \n#Our Capital will be 1500Euros for each strategy and for each betting site for a single model. \nreports = []\nmetrics = [\"Classifier\",  \"Strat 1 EX\", \"Strat 2 EX\", \"Strat 1 PS\", \"Strat 2 PS\", \"Strat 1 B365\", \"Strat 2 B365\" ,'Random EX', 'Random PS','Random B365']\nfor idx, y_clf in enumerate(y_pred):\n    Random = simple_bettor(Betting_Odds ,Y_test,budget_1)\n    strat_1 = strategy_1(Betting_Odds,y_clf,Y_test,budget_1)\n    strat_2 = strategy_2(Betting_Odds,y_prob[idx],Y_test,budget_1)\n    report = (models[idx][0],strat_1[1],strat_2[1],strat_1[1],strat_2[1],strat_1[2],strat_2[2],Random[0],Random[1],Random[2])\n    reports.append(report)       \ndisplay(pd.DataFrame.from_records(reports, columns=metrics))\nreports = pd.DataFrame.from_records(reports, columns=metrics)\nplt.figure(figsize=(10,10))\nplt.plot(reports['Classifier'].values, reports['Strat 1 EX'].values,\n             label='EX : Strategy 1' )\nplt.plot(reports['Classifier'], reports['Strat 2 EX'], lw=1, alpha=0.6,\n             label='EX : Strategy 2' )\nplt.plot(reports['Classifier'], reports['Strat 1 PS'], lw=1, alpha=0.6,\n             label='PS : Strategy 1' )\nplt.plot(reports['Classifier'], reports['Strat 2 PS'], lw=1, alpha=0.6,\n             label='PS : Strategy 2' )\nplt.plot(reports['Classifier'], reports['Strat 1 B365'], lw=1, alpha=0.6,\n             label='B365 : Strategy 1' )\nplt.plot(reports['Classifier'], reports['Strat 2 B365'], lw=1, alpha=0.6,\n             label='B365 : Strategy 2' )\n\n\nplt.xlabel('Algorithm')\nplt.ylabel('Return on investement')\nplt.title('Algorithms ROI on Test set')\nplt.legend(loc=\"lower right\")\nplt.show()\n\"\"\"\nThe strategy number one on the EX betting site is always the most profitable for all our model. But, Only with the neural network model and the Decision tree and Random forest models we can achieve a return on investment of 30% and 25% repectivly with a Capital of 1500Euros and a 20Euros investement per match.\n\"\"\"\n\"\"\"\n### Further Improvements\n\"\"\"\n\"\"\"\n- Hyper-parameters tuning for these models.\n- Using a generative Modeling approach (Markov chain).\n\n- Trying more discriminative models : SVM, XGBOOST.\n\n- Modeling Fatigue of players.\n- Using external Data about injuries.\n\n- More features engineering (hand-crafted features).\n- Doing more extensive EDA\n\n- Changing the Encodings of our categorical variables.\n\n\n\nI did not train an SVM model on this dataset as it takes too much times to train taking into account the number of columns in the training data and the considerable number of rows.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4000c8fb342b96'}"}
{"id":"125683","text":"\"\"\"\n# 2020 Kaggle ML & DS Survey\n\"\"\"\n\"\"\"\nIn this survey dataset answered by Kagglers all over the world, I am very curious to see the characteristics of kagglers from developing countries, especially in Indonesia (since I am an Indonesian myself). I would like to know if they are so different than kagglers from the U.S, Europe, India, etc.\n\nI will compare kagglers from Indonesia to the rest of Southeast Asia and also the rest of the world. Let's see if we can find something interesting!\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ndata = pd.read_csv('..\/input\/kaggle-survey-2020\/kaggle_survey_2020_responses.csv')\ndata.head()\n##Filter out the first row with questions\ndata = data.iloc[1:]\n\"\"\"\n**Distribution of countries where Kagglers who completed the survey are from:**\n\"\"\"\nsns.set(rc={'figure.figsize':(12,8)})\nsns.set_style(\"whitegrid\", {'axes.grid' : False})\n\n##Country\nsns.countplot(y = 'Q3', data =data, order = pd.value_counts(data['Q3']).iloc[:20].index, palette='tab10')\nplt.title(\"Where are the Kagglers from?\", fontweight=\"bold\", fontsize=18)\nplt.xlabel(\"\")\nplt.ylabel(\"\")\nplt.yticks(fontsize = 14)\nplt.show()\n\"\"\"\nMost of the Kagglers are from <b>India<\/b>. The number of Kagglers from Indonesia in the dataset is more than I first expected. I will be able to use this sample for exploration. \n\"\"\"\n##Gender\nsns.countplot(y = 'Q2', data =data, order = pd.value_counts(data['Q2']).index, palette='tab10')\nplt.title(\"Gender Distribution of the Kagglers\", fontweight=\"bold\", fontsize=18)\nplt.xlabel(\"\")\nplt.ylabel(\"\")\nplt.yticks(fontsize = 14)\nplt.show()\n##Job Title\nsns.countplot(y = 'Q5', data =data, order = pd.value_counts(data['Q5']).index, palette='tab10')\nplt.title(\"What are the Kagglers working as?\", fontweight=\"bold\", fontsize=18)\nplt.xlabel(\"\")\nplt.ylabel(\"\")\nplt.yticks(fontsize = 14)\nplt.show()\n\"\"\"\nMost of the Kagglers are <b>students<\/b>. I will filter out the students later because I want to get to know the difference in characteristics for Kagglers that are employed.\n\nNext, let's divide the datasets to see the comparison of Indonesian kagglers with the rest of Southeast Asia & the world:\n\n- <b>Indonesia<\/b>: Indonesia only\n- <b>Southeast Asia<\/b>: Singapore, Vietnam, Malaysia, Thailand, Phillipines\n- <b>Rest of the World<\/b>: Other countries outside of the ones mentioned above\n\"\"\"\n##Filter out students \ndata = data[data['Q5'] != 'Student']\n\n##Indonesia\nindo = data[data['Q3'] == 'Indonesia']\n\n##Asia\nsoutheast_asia_list = ['Singapore', 'Viet Nam', 'Malaysia', 'Thailand', 'Philippines']\n\nse_asia = data[data['Q3'].isin(southeast_asia_list)]\n\n##Rest of the world\nnot_included = ['Indonesia', 'Singapore', 'Viet Nam', 'Malaysia', 'Thailand', 'Philippines']\n\nworld = data[~data['Q3'].isin(not_included)]\n\"\"\"\n- **Age & Education level**\n\"\"\"\nfig, axs = plt.subplots(nrows = 3, ncols = 2, figsize=(20,10))\nsns.countplot(y = 'Q1', data = indo, order = pd.value_counts(indo['Q1']).index, ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Age)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q1', data = se_asia, order = pd.value_counts(se_asia['Q1']).index, ax = axs[1][0], palette = 'Dark2').set_title('Southeast Asia (Age)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q1', data = world, order = pd.value_counts(world['Q1']).index, ax = axs[2][0],palette = 'tab10').set_title('Rest of the World (Age)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q4', data = indo, order = pd.value_counts(indo['Q4']).index, ax = axs[0][1], palette = 'Set1').set_title('Indonesia (Education)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q4', data = se_asia, order = pd.value_counts(se_asia['Q4']).index, ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Education)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q4', data = world, order = pd.value_counts(world['Q4']).index, ax = axs[2][1],palette = 'tab10').set_title('Rest of the World (Education)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nEven though most of the Kagglers from Indonesia seem younger than the rest of the world & Southeast Asia, the age difference is not that significant.\n\nThe difference can be seen in the education level where most of Kagglers from Indonesia only have a bachelor's degree, but Master's degree is the most popular education level for the other parts of the world.\n\nThere are also only few Indonesia kagglers that have Doctoral degree if compared to the rest of the world & Southeast Asia.\n\"\"\"\n\"\"\"\n- **Job Title, Salary Range & Company Size**\n\"\"\"\nfig, axs = plt.subplots(nrows = 3, ncols = 3, figsize=(20,10))\nsns.countplot(y = 'Q5', data = indo, order = pd.value_counts(indo['Q5']).index, ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Job Title)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q5', data = se_asia, order = pd.value_counts(se_asia['Q5']).index, ax = axs[0][1], palette = 'Dark2').set_title('Southeast Asia (Job Title)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q5', data = world, order = pd.value_counts(world['Q5']).index, ax = axs[0][2],palette = 'tab10').set_title('Rest of the World (Job Title)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q20', data = indo, order = pd.value_counts(indo['Q20']).index, ax = axs[1][0], palette = 'Set1').set_title('Indonesia (Company Size)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q20', data = se_asia, order = pd.value_counts(se_asia['Q20']).index, ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Company Size)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q20', data = world, order = pd.value_counts(world['Q20']).index, ax = axs[1][2],palette = 'tab10').set_title('Rest of the World (Company Size)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q24', data = indo, order = pd.value_counts(indo['Q24']).iloc[:5].index, ax = axs[2][0], palette = 'Set1').set_title('Indonesia (Salary Range)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q24', data = se_asia, order = pd.value_counts(se_asia['Q24']).iloc[:5].index, ax = axs[2][1], palette = 'Dark2').set_title('Southeast Asia (Salary Range)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q24', data = world, order = pd.value_counts(world['Q24']).iloc[:5].index, ax = axs[2][2],palette = 'tab10').set_title('Rest of the World (Salary Range)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nThere are more software engineering kagglers in the rest of Southeast Asia & the world compared to Indonesia. Also, the size of companies & salaries are also much lower in Indonesia.\n\"\"\"\n\"\"\"\n- **Years of Coding & ML Experience**\n\"\"\"\nfig, axs = plt.subplots(nrows = 2, ncols = 3, figsize=(20,10))\nsns.countplot(y = 'Q6', data = indo, order = pd.value_counts(indo['Q6']).index, ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Years of Coding Experience)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q6', data = se_asia, order = pd.value_counts(se_asia['Q6']).index, ax = axs[0][1], palette = 'Dark2').set_title('Southeast Asia (Years of Coding Experience)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q6', data = world, order = pd.value_counts(world['Q6']).index, ax = axs[0][2],palette = 'tab10').set_title('Rest of the World (Years of Coding Experience)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q15', data = indo, order = pd.value_counts(indo['Q15']).index, ax = axs[1][0], palette = 'Set1').set_title('Indonesia (Years of ML Experience)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q15', data = se_asia, order = pd.value_counts(se_asia['Q15']).index, ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Years of ML Experience)', fontweight=\"bold\", size=18)\nsns.countplot(y = 'Q15', data = world, order = pd.value_counts(world['Q15']).index, ax = axs[1][2],palette = 'tab10').set_title('Rest of the World (Years of ML Experience)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nIn terms of coding experience, most kagglers from Indonesia do not have as much experience compared to the rest of Southeast Asia & the world. Most kagglers everywhere are not that experienced in Machine Learning.\n\"\"\"\n\"\"\"\n- **Most Popular ML Algorithms & Frameworks**\n\"\"\"\n##World\n#Q16\nworld_q16 = world[['Q16_Part_1', 'Q16_Part_2', 'Q16_Part_3',\n                   'Q16_Part_4', 'Q16_Part_5', 'Q16_Part_6',\n                   'Q16_Part_7', 'Q16_Part_8', 'Q16_Part_9',\n                   'Q16_Part_10', 'Q16_Part_11', 'Q16_Part_12', \n                   'Q16_Part_13', 'Q16_Part_14', 'Q16_Part_15',\n                   'Q16_OTHER']]\n\nworld_q16 = pd.DataFrame({'Response':world_q16.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q16.count()})\n\nworld_q16.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q17\nworld_q17 = world[['Q17_Part_1', 'Q17_Part_2', 'Q17_Part_3',\n                  'Q17_Part_4', 'Q17_Part_5', 'Q17_Part_6',\n                  'Q17_Part_7', 'Q17_Part_8', 'Q17_Part_9',\n                  'Q17_Part_10', 'Q17_Part_11','Q17_OTHER']]\n\nworld_q17 = pd.DataFrame({'Response':world_q17.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q17.count()})\n\nworld_q17.sort_values(by='Count', ascending=False, inplace=True)\n\n##Southeast Asia\n#Q16\nse_asia_q16 = se_asia[['Q16_Part_1', 'Q16_Part_2', 'Q16_Part_3',\n                   'Q16_Part_4', 'Q16_Part_5', 'Q16_Part_6',\n                   'Q16_Part_7', 'Q16_Part_8', 'Q16_Part_9',\n                   'Q16_Part_10', 'Q16_Part_11', 'Q16_Part_12', \n                   'Q16_Part_13', 'Q16_Part_14', 'Q16_Part_15',\n                   'Q16_OTHER']]\n\nse_asia_q16 = pd.DataFrame({'Response':se_asia_q16.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q16.count()})\n\nse_asia_q16.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q17\nse_asia_q17 = se_asia[['Q17_Part_1', 'Q17_Part_2', 'Q17_Part_3',\n                  'Q17_Part_4', 'Q17_Part_5', 'Q17_Part_6',\n                  'Q17_Part_7', 'Q17_Part_8', 'Q17_Part_9',\n                  'Q17_Part_10', 'Q17_Part_11','Q17_OTHER']]\n\nse_asia_q17 = pd.DataFrame({'Response':se_asia_q17.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q17.count()})\n\nse_asia_q17.sort_values(by='Count', ascending=False, inplace=True)\n\n##Indonesia\n#Q16\nindo_q16 = indo[['Q16_Part_1', 'Q16_Part_2', 'Q16_Part_3',\n                   'Q16_Part_4', 'Q16_Part_5', 'Q16_Part_6',\n                   'Q16_Part_7', 'Q16_Part_8', 'Q16_Part_9',\n                   'Q16_Part_10', 'Q16_Part_11', 'Q16_Part_12', \n                   'Q16_Part_13', 'Q16_Part_14', 'Q16_Part_15',\n                   'Q16_OTHER']]\n\nindo_q16 = pd.DataFrame({'Response':indo_q16.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q16.count()})\n\nindo_q16.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q17\nindo_q17 = indo[['Q17_Part_1', 'Q17_Part_2', 'Q17_Part_3',\n                  'Q17_Part_4', 'Q17_Part_5', 'Q17_Part_6',\n                  'Q17_Part_7', 'Q17_Part_8', 'Q17_Part_9',\n                  'Q17_Part_10', 'Q17_Part_11','Q17_OTHER']]\n\nindo_q17 = pd.DataFrame({'Response':indo_q17.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q17.count()})\n\nindo_q17.sort_values(by='Count', ascending=False, inplace=True)\n\n##Q16 & Q17 Plot\nfig, axs = plt.subplots(nrows = 3, ncols = 2, figsize=(20,10))\nsns.barplot(y = 'Response', x='Count', data = indo_q16, order = indo_q16['Response'].iloc[:8], ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Most used ML Frameworks)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q16, order = se_asia_q16['Response'].iloc[:8], ax = axs[1][0], palette = 'Dark2').set_title('Southeast Asia (Most used ML Frameworks)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q16, order = world_q16['Response'].iloc[:8], ax = axs[2][0],palette = 'tab10').set_title('Rest of the World (Most used ML Frameworks)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = indo_q17, order = indo_q17['Response'].iloc[:8], ax = axs[0][1], palette = 'Set1').set_title('Indonesia (Most used ML Algorithms)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q17, order = se_asia_q17['Response'].iloc[:8], ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Most used ML Algorithms)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q17, order = world_q17['Response'].iloc[:8], ax = axs[2][1],palette = 'tab10').set_title('Rest of the World (Most used ML Algorithms)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nThere is not much difference here. The most popular ML frameworks for every region is scikit-learn & Tensorflow. Linear models & Random Forest are the most popular ML algorithms for all regions.\n\"\"\"\n\"\"\"\n- **Most Popular Data Science Learning Platform & Media Sources**\n\"\"\"\n##World\n#Q37\nworld_q37 = world[['Q37_Part_1', 'Q37_Part_2', 'Q37_Part_3',\n                   'Q37_Part_4', 'Q37_Part_5', 'Q37_Part_6',\n                   'Q37_Part_7', 'Q37_Part_8', 'Q37_Part_9',\n                   'Q37_Part_10', 'Q37_Part_11','Q37_OTHER']]\n\nworld_q37 = pd.DataFrame({'Response':world_q37.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q37.count()})\n\nworld_q37.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q39\nworld_q39 = world[['Q39_Part_1', 'Q39_Part_2', 'Q39_Part_3',\n                  'Q39_Part_4', 'Q39_Part_5', 'Q39_Part_6',\n                  'Q39_Part_7', 'Q39_Part_8', 'Q39_Part_9',\n                  'Q39_Part_10', 'Q39_Part_11','Q39_OTHER']]\n\nworld_q39 = pd.DataFrame({'Response':world_q39.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q39.count()})\n\nworld_q39.sort_values(by='Count', ascending=False, inplace=True)\n\n##Southeast Asia\n#Q37\nse_asia_q37 = se_asia[['Q37_Part_1', 'Q37_Part_2', 'Q37_Part_3',\n                   'Q37_Part_4', 'Q37_Part_5', 'Q37_Part_6',\n                   'Q37_Part_7', 'Q37_Part_8', 'Q37_Part_9',\n                   'Q37_Part_10', 'Q37_Part_11','Q37_OTHER']]\n\nse_asia_q37 = pd.DataFrame({'Response':se_asia_q37.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q37.count()})\n\nse_asia_q37.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q39\nse_asia_q39 = se_asia[['Q39_Part_1', 'Q39_Part_2', 'Q39_Part_3',\n                  'Q39_Part_4', 'Q39_Part_5', 'Q39_Part_6',\n                  'Q39_Part_7', 'Q39_Part_8', 'Q39_Part_9',\n                  'Q39_Part_10', 'Q39_Part_11','Q39_OTHER']]\n\nse_asia_q39 = pd.DataFrame({'Response':se_asia_q39.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q39.count()})\n\nse_asia_q39.sort_values(by='Count', ascending=False, inplace=True)\n\n##Indonesia\n#Q37\nindo_q37 = indo[['Q37_Part_1', 'Q37_Part_2', 'Q37_Part_3',\n                   'Q37_Part_4', 'Q37_Part_5', 'Q37_Part_6',\n                   'Q37_Part_7', 'Q37_Part_8', 'Q37_Part_9',\n                   'Q37_Part_10', 'Q37_Part_11','Q37_OTHER']]\n\nindo_q37 = pd.DataFrame({'Response':indo_q37.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q37.count()})\n\nindo_q37.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q39\nindo_q39 = indo[['Q39_Part_1', 'Q39_Part_2', 'Q39_Part_3',\n                  'Q39_Part_4', 'Q39_Part_5', 'Q39_Part_6',\n                  'Q39_Part_7', 'Q39_Part_8', 'Q39_Part_9',\n                  'Q39_Part_10', 'Q39_Part_11','Q39_OTHER']]\n\nindo_q39 = pd.DataFrame({'Response':indo_q39.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q39.count()})\n\nindo_q39.sort_values(by='Count', ascending=False, inplace=True)\n\n##Q37 & Q39 Plot\nfig, axs = plt.subplots(nrows = 3, ncols = 2, figsize=(20,10))\nsns.barplot(y = 'Response', x='Count', data = indo_q37, order = indo_q37['Response'].iloc[:8], ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Most Popular DS Courses)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q37, order = se_asia_q37['Response'].iloc[:8], ax = axs[1][0], palette = 'Dark2').set_title('Southeast Asia (Most Popular DS Courses)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q37, order = world_q37['Response'].iloc[:8], ax = axs[2][0],palette = 'tab10').set_title('Rest of the World (Most Popular DS Courses)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = indo_q39, order = indo_q39['Response'].iloc[:8], ax = axs[0][1], palette = 'Set1').set_title('Indonesia (Most Popular Media Sources)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q39, order = se_asia_q39['Response'].iloc[:8], ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Most Popular Media Sources)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q39, order = world_q39['Response'].iloc[:8], ax = axs[2][1],palette = 'tab10').set_title('Rest of the World (Most Popular Media Sources)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nIn Indonesia, most Kagglers are learning from Kaggle courses. For the rest of Southeast Asia & the world, Coursera is the most popular learning platform. Kaggle, Youtube & Blogs are the most popular media source in every part.\n\"\"\"\n\"\"\"\n#### Now we only look at the Data Scientists in the dataset\n\"\"\"\n##Data Scientists only\ndata_ds = data[data['Q5'] == 'Data Scientist']\n\n##Indonesia\nindo_ds = data_ds[data_ds['Q3'] == 'Indonesia']\n\n##Asia\nsoutheast_asia_list = ['Singapore', 'Viet Nam', 'Malaysia', 'Thailand', 'Philippines']\n\nse_asia_ds = data_ds[data_ds['Q3'].isin(southeast_asia_list)]\n\n##Rest of the world\nnot_included = ['Indonesia', 'Singapore', 'Viet Nam', 'Malaysia', 'Thailand', 'Philippines']\n\nworld_ds = data_ds[~data_ds['Q3'].isin(not_included)]\n\"\"\"\n- **Data Scientist's Tools & IDE**\n\"\"\"\n##World\n#Q7\nworld_q7 = world_ds[['Q7_Part_1', 'Q7_Part_2', 'Q7_Part_3',\n                   'Q7_Part_4', 'Q7_Part_5', 'Q7_Part_6',\n                   'Q7_Part_7', 'Q7_Part_8', 'Q7_Part_9',\n                   'Q7_Part_10', 'Q7_Part_11', 'Q7_Part_12', 'Q7_OTHER']]\n\nworld_q7 = pd.DataFrame({'Response':world_q7.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q7.count()})\n\nworld_q7.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q9\nworld_q9 = world_ds[['Q9_Part_1', 'Q9_Part_2', 'Q9_Part_3',\n                  'Q9_Part_4', 'Q9_Part_5', 'Q9_Part_6',\n                  'Q9_Part_7', 'Q9_Part_8', 'Q9_Part_9',\n                  'Q9_Part_10', 'Q9_Part_11','Q9_OTHER']]\n\nworld_q9 = pd.DataFrame({'Response':world_q9.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q9.count()})\n\nworld_q9.sort_values(by='Count', ascending=False, inplace=True)\n\n##Southeast Asia\n#Q7\nse_asia_q7 = se_asia_ds[['Q7_Part_1', 'Q7_Part_2', 'Q7_Part_3',\n                   'Q7_Part_4', 'Q7_Part_5', 'Q7_Part_6',\n                   'Q7_Part_7', 'Q7_Part_9','Q7_Part_10', \n                   'Q7_Part_11', 'Q7_OTHER']]\n\nse_asia_q7 = pd.DataFrame({'Response':se_asia_q7.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q7.count()})\n\nse_asia_q7.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q9\nse_asia_q9 = se_asia_ds[['Q9_Part_1', 'Q9_Part_2', 'Q9_Part_3',\n                  'Q9_Part_4', 'Q9_Part_5', 'Q9_Part_6',\n                  'Q9_Part_7', 'Q9_Part_8', 'Q9_Part_9',\n                  'Q9_Part_10', 'Q9_OTHER']]\n\nse_asia_q9 = pd.DataFrame({'Response':se_asia_q9.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q9.count()})\n\nse_asia_q9.sort_values(by='Count', ascending=False, inplace=True)\n\n##Indonesia\n#Q7\nindo_q7 = indo_ds[['Q7_Part_1', 'Q7_Part_2', 'Q7_Part_3',\n                   'Q7_Part_4', 'Q7_Part_5', 'Q7_Part_6',\n                   'Q7_Part_7','Q7_Part_10', 'Q7_Part_11', 'Q7_OTHER']]\n\nindo_q7 = pd.DataFrame({'Response':indo_q7.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q7.count()})\n\nindo_q7.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q9\nindo_q9 = indo_ds[['Q9_Part_1', 'Q9_Part_2', 'Q9_Part_3',\n                  'Q9_Part_4', 'Q9_Part_5', 'Q9_Part_6',\n                  'Q9_Part_7', 'Q9_Part_8', 'Q9_Part_9',\n                  'Q9_Part_10', 'Q9_OTHER']]\n\nindo_q9 = pd.DataFrame({'Response':indo_q9.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q9.count()})\n\nindo_q9.sort_values(by='Count', ascending=False, inplace=True)\n\n##Q37 & Q39 Plot\nfig, axs = plt.subplots(nrows = 3, ncols = 2, figsize=(20,10))\nsns.barplot(y = 'Response', x='Count', data = indo_q7, order = indo_q7['Response'].iloc[:8], ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Most Used Programming Tools)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q7, order = se_asia_q7['Response'].iloc[:8], ax = axs[1][0], palette = 'Dark2').set_title('Southeast Asia (Most Used Programming Tools)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q7, order = world_q7['Response'].iloc[:8], ax = axs[2][0],palette = 'tab10').set_title('Rest of the World (Most Used Programming Tools)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = indo_q9, order = indo_q9['Response'].iloc[:8], ax = axs[0][1], palette = 'Set1').set_title('Indonesia (Most Popular IDE)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q9, order = se_asia_q9['Response'].iloc[:8], ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Most Popular IDE)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q9, order = world_q9['Response'].iloc[:8], ax = axs[2][1],palette = 'tab10').set_title('Rest of the World (Most Popular IDE)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nAn intereseting thing to know here is that R is not as popular in Indonesia as compared to the rest of Southeast Asia & the world. Python in Jupyter Notebooks is still the most used programming tool & IDE everywhere.\n\"\"\"\n\"\"\"\n- **Data Scientist's Cloud & ML\/AI Cloud Services**\n\"\"\"\n##World\n#Q26\nworld_q26 = world_ds[['Q26_A_Part_1', 'Q26_A_Part_2', 'Q26_A_Part_3',\n                   'Q26_A_Part_4', 'Q26_A_Part_5', 'Q26_A_Part_6',\n                   'Q26_A_Part_7', 'Q26_A_Part_8', 'Q26_A_Part_9',\n                   'Q26_A_Part_10', 'Q26_A_Part_11', 'Q26_A_OTHER']]\n\nworld_q26 = pd.DataFrame({'Response':world_q26.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q26.count()})\n\nworld_q26.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q28\nworld_q28 = world_ds[['Q28_A_Part_1', 'Q28_A_Part_2', 'Q28_A_Part_3',\n                  'Q28_A_Part_4', 'Q28_A_Part_5', 'Q28_A_Part_6',\n                  'Q28_A_Part_7', 'Q28_A_Part_8', 'Q28_A_Part_9',\n                  'Q28_A_Part_10', 'Q28_A_OTHER']]\n\nworld_q28 = pd.DataFrame({'Response':world_q28.apply(lambda x:x.dropna().unique()[0]), 'Count':world_q28.count()})\n\nworld_q28.sort_values(by='Count', ascending=False, inplace=True)\n\n##Southeast Asia\n#Q26\nse_asia_q26 = se_asia_ds[['Q26_A_Part_1', 'Q26_A_Part_2', 'Q26_A_Part_3',\n                   'Q26_A_Part_4', 'Q26_A_Part_7', 'Q26_A_Part_8', \n                   'Q26_A_Part_10', 'Q26_A_Part_11', 'Q26_A_OTHER']]\n\nse_asia_q26 = pd.DataFrame({'Response':se_asia_q26.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q26.count()})\n\nse_asia_q26.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q28\nse_asia_q28 = se_asia_ds[['Q28_A_Part_1', 'Q28_A_Part_3', 'Q28_A_Part_5', \n                       'Q28_A_Part_6','Q28_A_Part_7', 'Q28_A_Part_8', \n                       'Q28_A_Part_9', 'Q28_A_Part_10', ]]\n\nse_asia_q28 = pd.DataFrame({'Response':se_asia_q28.apply(lambda x:x.dropna().unique()[0]), 'Count':se_asia_q28.count()})\n\nse_asia_q28.sort_values(by='Count', ascending=False, inplace=True)\n\n##Indonesia\n#Q26\nindo_q26 = indo_ds[['Q26_A_Part_1', 'Q26_A_Part_2', 'Q26_A_Part_3',\n                   'Q26_A_Part_4', 'Q26_A_Part_5', 'Q26_A_Part_6',\n                   'Q26_A_Part_8', 'Q26_A_Part_9','Q26_A_OTHER']]\n\nindo_q26 = pd.DataFrame({'Response':indo_q26.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q26.count()})\n\nindo_q26.sort_values(by='Count', ascending=False, inplace=True)\n\n#Q28\nindo_q28 = indo_ds[['Q28_A_Part_2', 'Q28_A_Part_4', 'Q28_A_Part_5', \n                 'Q28_A_Part_6','Q28_A_Part_7', 'Q28_A_Part_8', \n                 'Q28_A_Part_9','Q28_A_Part_10', 'Q28_A_OTHER']]\n\nindo_q28 = pd.DataFrame({'Response':indo_q28.apply(lambda x:x.dropna().unique()[0]), 'Count':indo_q28.count()})\n\nindo_q28.sort_values(by='Count', ascending=False, inplace=True)\n\n##Q37 & Q39 Plot\nfig, axs = plt.subplots(nrows = 3, ncols = 2, figsize=(20,10))\nsns.barplot(y = 'Response', x='Count', data = indo_q26, order = indo_q26['Response'].iloc[:8], ax = axs[0][0], palette = 'Set1').set_title('Indonesia (Most Popular Cloud Services)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q26, order = se_asia_q26['Response'].iloc[:8], ax = axs[1][0], palette = 'Dark2').set_title('Southeast Asia (Most Popular Cloud Services)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q26, order = world_q26['Response'].iloc[:8], ax = axs[2][0],palette = 'tab10').set_title('Rest of the World (Most Popular Cloud Services)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = indo_q28, order = indo_q28['Response'].iloc[:8], ax = axs[0][1], palette = 'Set1').set_title('Indonesia (Most Popular Cloud ML\/AI Services)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = se_asia_q28, order = se_asia_q28['Response'].iloc[:8], ax = axs[1][1], palette = 'Dark2').set_title('Southeast Asia (Most Popular Cloud ML\/AI Services)', fontweight=\"bold\", size=18)\nsns.barplot(y = 'Response', x='Count', data = world_q28, order = world_q28['Response'].iloc[:8], ax = axs[2][1],palette = 'tab10').set_title('Rest of the World (Most Popular Cloud ML\/AI Services)', fontweight=\"bold\", size=18)\n\nfor ax in axs.flat:\n    ax.set_ylabel('') \n    ax.set_xlabel('')\n    ax.tick_params(labelsize=16)\n    \nplt.tight_layout()\n\"\"\"\nUnsurprisingly, AWS & GCP dominates the cloud market everywhere. What is interesting here is that AWS Sagemaker is not seen as the top ML cloud service in Indonesia, unlike the rest of Southeast Asia & the world. GCP AI Platform is most popular in Indonesia.\n\"\"\"\n\"\"\"\nThanks for reading until the end. If you find this kernel interesting or helpful, please help by upvoting this kernel! :D\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e720b4250ca79c'}"}
{"id":"82953","text":"\"\"\"\n**Classification Algorithms**\n\nI will explain at this kernel the below to classification algorithms with examples.\n\nWe are predict feature of \"survived\" at this kernel \n\n1. Logistic Regression Classification\n2. K-NN (K-Nearest Neighbour) Classification\n3. Support Vector Machine Classification\n4. Naive Bayes Classification\n5. Decision Tree Classification\n6. Random Forest Classification\n7. Evaluation Classification Models\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\npre_dataTest = pd.read_csv(\"..\/input\/test.csv\")\npre_dataTrain = pd.read_csv(\"..\/input\/train.csv\")\ndata_sonuc = pd.read_csv(\"..\/input\/gender_submission.csv\")\npre_dataTrain.head()\npre_dataTest.head()\npre_dataTrain.info()\nprint(\"_\"*25)\npre_dataTest.info()\npre_dataTrain.describe()\npre_dataTrain.corr()\nf, ax = plt.subplots(figsize=(5,5))\nsns.heatmap(pre_dataTrain.corr(), annot=True, linewidths=0.5, linecolor=\"red\", fmt='.1f', ax=ax)\nplt.show()\n\n\"\"\"\n**Which we can use features?**\n* As we can see the higest correlation with \"survived\" is feature of \"Pclass\". And there is negative correlation between 2 feature.\n* There is a positive correlation between \"survived\" and \"Fare\" with a correlation of 0.25.\n* \"There isn't a significant correlation between other features.\" that we can interpret.\n\"\"\"\n\"\"\"\n**In that case we can visualization of data.**\n\"\"\"\ng = sns.jointplot(pre_dataTrain.Survived, pre_dataTrain.Pclass, kind=\"kde\", size=7)\nplt.savefig('graph.png')\nplt.show()\ng = sns.jointplot(pre_dataTrain.Survived, pre_dataTrain.Fare, color=\"green\" , kind=\"kde\", size=7)\nplt.savefig('graph.png')\nplt.show()\n\"\"\"\n**Model and predict**\n\nWe want classification whether passengers survived. Therefore we will use the following algorithms. \n\n* Logistic Regression Classification\n* KNN or K-Nearest Neighbors Classification\n* Support Vector Machines Classification\n* Naive Bayes Classification\n* Decision Tree Classification\n* Random Forest Classification\n* Evaluation Classification Models\n\n\"\"\"\npre_dataTrain.dropna(inplace=True)\npre_dataTest.dropna(inplace=True)\n# Data drop\ndataTrain = pre_dataTrain.drop([\"PassengerId\",\"Name\",\"Sex\", \"SibSp\", \"Parch\",\"Ticket\",\"Cabin\", \"Embarked\"], axis=1)\ndataTest = pre_dataTest.drop([\"Name\",\"Sex\",\"SibSp\", \"Parch\", \"Ticket\",\"Cabin\", \"Embarked\"], axis=1)\ndataTest.info()\ndataTest.head()\ndataTrain.info()\npre_x_train = dataTrain.drop(\"Survived\", axis=1)\nx_train = (pre_x_train-np.min(pre_x_train))\/(np.max(pre_x_train)-np.min(pre_x_train)).values\ny_train = dataTrain[\"Survived\"]\npre_x_test = dataTest.drop(\"PassengerId\", axis=1)\nx_test = (pre_x_test-np.min(pre_x_test))\/(np.max(pre_x_test)-np.min(pre_x_test)).values\nx_train.shape, y_train.shape, x_test.shape\n#Logistic Regression Classisification\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\nlr.fit(x_train,y_train)\ny_head = lr.predict(x_test)\nresult_lr = round(lr.score(x_train, y_train)*100,2)\nresult_lr\nprint(\"Result Survived Predict to Logistic Regression Class: \", lr.score(x_train, y_train))\n# KNN Classification\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\nknn.fit(x_train, y_train)\ny_head = knn.predict(x_test)\nresult_knn = round(knn.score(x_train, y_train)*100,2)\nresult_knn\nprint(\"Result Survived Predict to KNN Class.: \", knn.score(x_train, y_train))\n\n# Support Vector Machine Classification\nfrom sklearn.svm import SVC\nsvm = SVC(random_state=3)\nsvm.fit(x_train, y_train)\ny_head = svm.predict(x_test)\nresult_svm = round(svm.score(x_train, y_train)*100,2)\nresult_svm\nprint(\"Result Survived Predict to SVM Class.: \", svm.score(x_train, y_train))\n#Naive Bayes Classification\nfrom sklearn.naive_bayes import GaussianNB\nnb = GaussianNB()\nnb.fit(x_train, y_train)\ny_head = nb.predict(x_test)\nresult_nb = round(nb.score(x_train, y_train)*100,2)\nresult_nb\nprint(\"Result Survived Predict to Naive Bayes Class.: \", nb.score(x_train, y_train))\n#Decision Tree Classification\nfrom sklearn.tree import DecisionTreeClassifier\ndt = DecisionTreeClassifier(random_state=5)\ndt.fit(x_train, y_train)\ny_head = dt.predict(x_test)\nresult_dt = round(dt.score(x_train, y_train)*100,2)\nresult_dt\nprint(\"Result Survived Predict to Decision Tree Class.: \", dt.score(x_train, y_train))\n# Random Forest Classification and Evaluation Classification Models\nfrom sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=100, random_state=1)\nrf.fit (x_train, y_train)\ny_head = rf.predict(x_test)\nresult_rf = round(rf.score(x_train, y_train)*100,2)\nresult_rf\nprint(\"Result Survived Predict to Random Forest Class.: \", rf.score(x_train, y_train))\n# Evaluation Classification Models\nmodels = pd.DataFrame({\n    'Model' : ['Logistic Regression', 'KNN', 'SVM',\n               'Naive Bayes', 'Decison Tree', 'Random Forest'],\n    'Score' : [result_lr,result_knn,result_svm,\n              result_nb, result_dt, result_rf]\n})\n\nmodels.sort_values(by='Score', ascending=False)\nsubmission = pd.DataFrame({\n        \"PassengerId\": dataTest[\"PassengerId\"],\n        \"Survived\": y_head\n    })\nsubmission.to_csv('submission.csv', index=False)\n\"\"\"\n**CONCLUSION**\n\nWe can choose rank our evaluation of all the models the best result. While both Random Forest Class and Decision Tree Class result the same, we choose Random Forest Class due to its strcuture.According to this Random Forest Class. model is the best result.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9855433c665ed2'}"}
{"id":"124186","text":"\"\"\"\n# P\u00f3s Gradua\u00e7\u00e3o em Ci\u00eancia de Dados\n\n## Aula2 | Exerc\u00edcio 1\n\n* **Data de entrega:** 20\/10\/2018\n* **Professor:**  Matheus Mota\n* **Aluno 1:** Matheus Roque de Oliveira da Silva\n* **Aluno 2:** Mariana Marques Pacheco\n* **RA 1:** 183145\n* **RA 2:** 132195\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport plotly.offline as py\nimport plotly.graph_objs as go\n\"\"\"\n## Dataset - cota_parlamentar_sp.csv\n\"\"\"\ndfCotaParlamentar = pd.read_csv('..\/input\/cota_parlamentar_sp.csv', delimiter=',')\ndfCotaParlamentar.dataframeName = 'cota_parlamentar_sp.csv'\ndfCotaParlamentar.head(15)\nclassificacao = [[\"datemissao\", \"Qualitativa Ordenal\"],\n                [\"nudeputadoid\",\"Qualitativa Nominal\"],\n                [\"numlegislatura\",\"Qualitativa Ordenal\"],\n                [\"numano\",\"Qualitativa Ordenal\"],\n                [\"nummes\",\"Qualitativa Ordenal\"],\n                [\"sgpartido\",\"Qualitativa Nominal\"],\n                [\"txnomeparlamentar\",\"Qualitativa Nominal\"],\n                [\"txtdescricao\",\"Qualitativa Nominal\"],\n                [\"txtdescricaoespecificacao\",\"Qualitativa Nominal\"],\n                [\"txtfornecedor\",\"Qualitativa Nominal\"],\n                [\"vlrdocumento\",\"Qualitativa Discreta\"]]\nclassificacao = pd.DataFrame(classificacao, columns=[\"Variavel\", \"Classifica\u00e7\u00e3o\"])\nclassificacao\ndfCotaParlamentar.vlrdocumento = dfCotaParlamentar.vlrdocumento \/ 100\ndfCotaParlamentar\n\"\"\"\n## Renomear as colunas para melhor entendimento\n\"\"\"\ndfCotaParlamentar.rename(index=str, columns={'nulegislatura' : 'Inicio_Legislatura','numano' : 'Ano','nummes' : 'Mes','sgpartido' : 'Partido','txnomeparlamentar' : 'Nome_Parlamentar','txtdescricao' : 'Categoria','txtfornecedor' : 'Nome_Fornecedor','vlrdocumento' : 'Valor'}, inplace=True)\ndfCotaParlamentar\n\"\"\"\n# Analise do comportamento das vari\u00e1veis\n## Gr\u00e1ficos de frequ\u00eancia por v\u00e1riavel\n\"\"\"\ndfTotalGastos = dfCotaParlamentar[['Ano','Valor']].groupby(by='Ano').sum().rename(index=str, columns={'Valor' :'TotalGastos'})\ndfTotalGastos.index = dfTotalGastos.index.map(int)\ndfTotalGastos\ndfTotalGastosPartido = dfCotaParlamentar[['Partido','Valor']].groupby(by='Partido').sum().rename(index=str, columns={'Valor' :'TotalGastos'})\ndfTotalGastosPartido.index = dfTotalGastosPartido.index.map(str)\ndfTotalGastosPartido\ndfTotalGastosPartidoPorAno = dfCotaParlamentar[['Ano','Partido','Valor']].groupby(by=['Ano','Partido']).sum().rename(index=str, columns={'Valor' :'TotalGastos'})\n\ndfTotalGastosPartidoPorAno\ndfTotalGastosPartidoCandidato = dfCotaParlamentar[['Partido','Nome_Parlamentar','Valor']].groupby(by=['Partido','Nome_Parlamentar']).sum().rename(index=str, columns={'Valor' :'TotalGastos'})\ndfTotalGastosPartidoCandidato\n\"\"\"\n> # Gr\u00e1ficos Gerados\n\"\"\"\ntrace = go.Scatter(\n                x = dfTotalGastos.index,\n                y = dfTotalGastos.TotalGastos,\n                marker = dict(color = 'green', line=dict(color='black',width=1.5)),\n                text = dfTotalGastos.index)\nlayout = go.Layout(\n    title='Total de Gastos por ano',\n    xaxis=dict(\n        title='Ano',\n        titlefont=dict(\n            size=16\n        )\n    ),\n    yaxis=dict(\n        title='Gastos em Milhoes',\n        titlefont=dict(\n            size=16\n        )\n    )\n)\n\npy.iplot(go.Figure(data = [trace], layout=layout))\ntrace = go.Bar(\n                x = dfTotalGastosPartido.index,\n                y = dfTotalGastosPartido.TotalGastos,\n                marker = dict(color = 'green', line=dict(color='black',width=1.5)),\n                text = dfTotalGastos.index)\nlayout = go.Layout(\n    title='Total de Gastos por Partido',\n    xaxis=dict(\n        title='Partido',\n        titlefont=dict(\n            size=16\n        )\n    ),\n    yaxis=dict(\n        title='Gastos em Milhoes',\n        titlefont=dict(\n            size=16\n        )\n    )\n)\n\npy.iplot(go.Figure(data = [trace], layout=layout))","meta":"{'source': 'AI4Code', 'id': 'e460e1c8c1cf2b'}"}
{"id":"29695","text":"\"\"\"\n# \u041f\u0440\u0430\u043a\u0442\u0438\u043a\u0443\u043c \u043f\u043e \u0444\u0438\u043b\u043e\u0441\u043e\u0444\u0438\u0438\n\"\"\"\n\"\"\"\n\u0411\u043b\u043e\u043a\u043d\u043e\u0442 \u043f\u043e\u0434\u0433\u043e\u0442\u043e\u0432\u043b\u0435\u043d \u0432 \u0441\u043e\u0430\u0432\u0442\u043e\u0440\u0441\u0442\u0432\u0435 \u0441 \u0410\u043b\u0435\u043a\u0441\u0435\u0435\u043c \u041c\u043e\u0440\u043e\u0437\u043e\u0432\u044b\u043c, \u0431\u043e\u043b\u044c\u0448\u043e\u0435 \u0435\u043c\u0443 \u0441\u043f\u0430\u0441\u0438\u0431\u043e!\n\"\"\"\n\"\"\"\n\n\u041c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u044b \u0434\u043b\u044f \u0441\u0435\u043c\u0438\u043d\u0430\u0440\u0441\u043a\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u044b - \u044d\u0442\u043e \u0444\u0438\u043b\u043e\u0441\u043e\u0444\u0441\u043a\u0438\u0435 \u0442\u0435\u043a\u0441\u0442\u044b. \u0412\u0430\u043c \u043f\u0440\u0435\u0434\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0441\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 \u0442\u0435\u043a\u0441\u0442\u0430\u043c\u0438 \u0438\u0437 \u043e\u0431\u043b\u0430\u0441\u0442\u0438 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0435\u0441\u0442\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u044f\u0437\u044b\u043a\u043e\u0432. \u0417\u0430\u0434\u0430\u0447\u0430 - \u0441\u043e\u043f\u043e\u0441\u0442\u0430\u0432\u0438\u0442\u044c \u0441\u043b\u043e\u0432\u0430 \u0432 \u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e\u0441\u0442\u0438 \u043e\u0442 \u0438\u0445 \u0441\u0435\u043c\u0430\u043d\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0431\u043b\u0438\u0437\u043e\u0441\u0442\u0438 \u0438 \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0442\u0430\u043a\u0438\u043c \u043e\u0431\u0440\u0430\u0437\u043e\u043c \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043e \u043f\u0440\u0435\u0434\u043c\u0435\u0442\u043d\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438.\n\n\u0414\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0432\u0430\u043c \u043f\u0440\u0435\u0434\u043e\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0430 \u043c\u043e\u0434\u0435\u043b\u044c [fasttext](https:\/\/radimrehurek.com\/gensim\/models\/fasttext.html), \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0431\u044b\u043b\u0430 \u043e\u0431\u0443\u0447\u0435\u043d\u0430 \u043d\u0430 `3 407` \u0444\u0438\u043b\u043e\u0441\u043e\u0444\u0441\u043a\u0438\u0445 \u0442\u0435\u043a\u0441\u0442\u0430\u0445 \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \u044f\u0437\u044b\u043a\u0435. \u0421\u043b\u043e\u0432\u0430\u0440\u044c \u043c\u043e\u0434\u0435\u043b\u0438 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u0442 \u043a\u043b\u044e\u0447\u0435\u0432\u044b\u0435 \u0441\u043b\u043e\u0432\u0430 (\u0442\u0435\u0440\u043c\u044b) \u0438\u0437\u0443\u0447\u0430\u0435\u043c\u043e\u0439 \u043f\u0440\u0435\u0434\u043c\u0435\u0442\u043d\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438.\n\n\n\n\"\"\"\n\"\"\"\n## 1. \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport os\n\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nfrom gensim.models.fasttext import FastText\nimport gensim\nft_model = FastText.load('\/kaggle\/input\/philosophy-ru-large\/ft_model.model')\n\"\"\"\n\u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0441\u043b\u043e\u0432 \u0432 \u0441\u043b\u043e\u0432\u0430\u0440\u0435 \u043c\u043e\u0434\u0435\u043b\u0438.\n\"\"\"\nlen(ft_model.wv.key_to_index)\n\"\"\"\n## 2. \u041f\u043e\u0438\u0441\u043a \u043f\u043e\u0445\u043e\u0436\u0438\u0445 \u0441\u043b\u043e\u0432\n\"\"\"\n\"\"\"\n\u041c\u044b \u043c\u043e\u0436\u0435\u043c \u0443\u0442\u043e\u0447\u043d\u0438\u0442\u044c, \u0435\u0441\u0442\u044c \u043b\u0438 \u043d\u0443\u0436\u043d\u043e\u0435 \u043d\u0430\u043c \u0441\u043b\u043e\u0432\u043e \u0432 \u0441\u043b\u043e\u0432\u0430\u0440\u0435.\n\"\"\"\nprint('\u0434\u0435\u043d\u044c\u0433\u0438' in ft_model.wv.key_to_index)\n\"\"\"\n\u0418 \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043d\u0443\u0436\u043d\u043e\u0433\u043e \u043d\u0430\u043c \u0441\u043b\u043e\u0432\u0430 \u0432 \u0432\u0438\u0434\u0435 \u0435\u0433\u043e \u0432\u0435\u043a\u0442\u043e\u0440\u043e\u0432.\n\"\"\"\nprint(ft_model.wv['\u0434\u0435\u043d\u044c\u0433\u0438'])\n\"\"\"\n\u0415\u0441\u043b\u0438 \u0432 \u0441\u043b\u043e\u0432\u0430\u0440\u0435 \u043d\u0435\u0442 \u043d\u0443\u0436\u043d\u043e\u0433\u043e \u043d\u0430\u043c \u0441\u043b\u043e\u0432\u0430, \u0442\u043e \u043f\u043e\u0438\u0441\u043a \u0431\u0443\u0434\u0435\u0442 \u043f\u043e n-\u0433\u0440\u0430\u043c\u043c\u0430\u043c, \u0435\u0441\u043b\u0438 \u043e\u043d\u0438 \u0435\u0441\u0442\u044c \u0432 \u0441\u043b\u043e\u0432\u0430\u0440\u0435.\n\"\"\"\nprint('\u043f\u043e\u0441\u0442\u0431\u044b\u0442\u0438\u0435' in ft_model.wv.key_to_index)\nprint('\u043f\u043e\u0441' in ft_model.wv.key_to_index)\n\"\"\"\n\u0414\u043b\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u043d\u0430\u0438\u0431\u043e\u043b\u0435\u0435 \u043f\u043e\u0445\u043e\u0436\u0438\u0445 \u0441\u043b\u043e\u0432 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u043e \u043e\u0434\u043d\u043e \u0438\u043b\u0438 \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0441\u043b\u043e\u0432. \u041f\u0440\u0435\u0444\u0438\u043a\u0441 \"positive=\" \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u043d\u0430 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u043f\u0440\u0438\u043c\u0435\u0440\u044b \u0434\u043b\u044f \u043f\u043e\u0438\u0441\u043a\u0430, \u0430 \"negative=\" \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u043d\u0430 \u043e\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0435.\n\"\"\"\nft_model.wv.most_similar(positive=['\u043a\u0430\u0440\u043d\u0430\u043f'], topn=20)\n\"\"\"\n\u041c\u043e\u0436\u043d\u043e \u0441\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u0434\u0432\u0430 \u0441\u043b\u043e\u0432\u0430 \u043d\u0430 \u0432\u0437\u0430\u0438\u043c\u043d\u043e\u0435 \u0441\u0445\u043e\u0434\u0441\u0442\u0432\u043e:\n\"\"\"\nft_model.wv.similarity(\"\u0431\u044b\u0442\u0438\u0435\", '\u0432\u0440\u0435\u043c\u044f')\n\"\"\"\n\u0422\u043e \u0436\u0435 \u0441\u0430\u043c\u043e\u0435 \u043c\u043e\u0436\u043d\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u0441 \u0440\u0430\u0437\u043d\u044b\u043c\u0438 \u043d\u0430\u0431\u043e\u0440\u0430\u043c\u0438 \u0441\u043b\u043e\u0432.\n\"\"\"\nft_model.wv.n_similarity(['\u043f\u0430\u0440\u043c\u0435\u043d\u0438\u0434', '\u0431\u044b\u0442\u0438\u0435'], ['\u0434\u0435\u043c\u043e\u043a\u0440\u0438\u0442', '\u043d\u0435\u0431\u044b\u0442\u0438\u0435'])\n\"\"\"\n\u0422\u0430\u043a\u0436\u0435 \u043c\u043e\u0436\u043d\u043e \u0432\u044b\u0431\u0440\u0430\u0442\u044c \u0441\u043b\u043e\u0432\u043e, \u043a\u043e\u0442\u043e\u0440\u043e\u0435 \u043c\u0435\u043d\u0435\u0435 \u0432\u0441\u0435\u0433\u043e \u043f\u043e\u0445\u043e\u0436\u0435 \u043d\u0430 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0435 \u0432 \u043f\u0435\u0440\u0435\u0447\u043d\u0435 \u0441\u043b\u043e\u0432\u0430:\n\n\"\"\"\nft_model.wv.doesnt_match([\"\u0431\u044b\u0442\u0438\u0435\", '\u0432\u0440\u0435\u043c\u044f', '\u0434\u0435\u043d\u044c\u0433\u0438'])\n\"\"\"\n\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u043f\u043e\u0438\u0441\u043a\u0430 \u043f\u043e \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u043c \u0438 \u043e\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u043c \u0437\u0430\u043f\u0440\u043e\u0441\u0430\u043c \u0434\u0430\u0435\u0442 \u0431\u043e\u043b\u0435\u0435 \u0442\u043e\u0447\u043d\u044b\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442:\n\"\"\"\nft_model.wv.most_similar(positive=['\u0432\u0440\u0435\u043c\u044f', '\u0434\u0435\u043d\u044c\u0433\u0438'], negative=[\"\u0431\u044b\u0442\u0438\u0435\"], topn=20)\n\"\"\"\n\u041c\u044b \u043c\u043e\u0436\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0432\u0435\u043a\u0442\u043e\u0440\u043d\u044b\u0435 \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u044f \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u044e\u0449\u0438\u0445 \u0441\u043b\u043e\u0432 \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0433\u0440\u0430\u0444\u0430.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n%matplotlib inline\nwords = [\n'\u043a\u043e\u043d\u0444\u0443\u0446\u0438\u0439',\n'\u0444\u0430\u043b\u0435\u0441',\n'\u0430\u043d\u0430\u043a\u0441\u0438\u043c\u0430\u043d\u0434\u0440',\n'\u0430\u043d\u0430\u043a\u0441\u0438\u043c\u0435\u043d',\n'\u043f\u0438\u0444\u0430\u0433\u043e\u0440',\n'\u043f\u0430\u0440\u043c\u0435\u043d\u0438\u0434',\n'\u0437\u0435\u043d\u043e\u043d',\n'\u043c\u0435\u043b\u0438\u0441\u0441',\n'\u0433\u0435\u0440\u0430\u043a\u043b\u0438\u0442',\n'\u0430\u043d\u0430\u043a\u0441\u0430\u0433\u043e\u0440',\n'\u043b\u0435\u0432\u043a\u0438\u043f\u043f',\n'\u0434\u0435\u043c\u043e\u043a\u0440\u0438\u0442',\n'\u044d\u043c\u043f\u0435\u0434\u043e\u043a\u043b',\n'\u043f\u0440\u043e\u0442\u0430\u0433\u043e\u0440',\n'\u0433\u043e\u0440\u0433\u0438\u0439',\n'\u043f\u0440\u043e\u0434\u0438\u043a',\n'\u043f\u043b\u0430\u0442\u043e\u043d',\n'\u0430\u0440\u0438\u0441\u0442\u043e\u0442\u0435\u043b\u044c',\n'\u0441\u0435\u043d\u0435\u043a\u0430',\n'\u0430\u0432\u0440\u0435\u043b\u0438\u0439',\n'\u044d\u043f\u0438\u043a\u0443\u0440',\n'\u0433\u0438\u043f\u0430\u0442\u0438\u044f',\n'\u043f\u043b\u043e\u0442\u0438\u043d',\n'\u043f\u043e\u0440\u0444\u0438\u0440\u0438\u0439',\n'\u044f\u043c\u0432\u043b\u0438\u0445',\n'\u043e\u0440\u0438\u0433\u0435\u043d',\n'\u0430\u0432\u0433\u0443\u0441\u0442\u0438\u043d',\n'\u0442\u0435\u0440\u0442\u0443\u043b\u043b\u0438\u0430\u043d',\n'\u043c\u0430\u0439\u043c\u043e\u043d\u0438\u0434',\n'\u0444\u0430\u0440\u0430\u0431\u0438',\n'\u0430\u0432\u0435\u0440\u0440\u043e\u044d\u0441',\n'\u0431\u043e\u044d\u0446\u0438\u0439',\n'\u0430\u0431\u0435\u043b\u044f\u0440',\n'\u0431\u043e\u043d\u0430\u0432\u0435\u043d\u0442\u0443\u0440\u0430',\n'\u0430\u043a\u0432\u0438\u043d\u0441\u043a\u0438\u0439',\n'\u043e\u043a\u043a\u0430\u043c',\n'\u044d\u043a\u0445\u0430\u0440\u0442',\n'\u0441\u043f\u0438\u043d\u043e\u0437\u0430',\n'\u043b\u0435\u0439\u0431\u043d\u0438\u0446',\n'\u0434\u0435\u043a\u0430\u0440\u0442',\n'\u0433\u0435\u0433\u0435\u043b\u044c',\n'\u0431\u044d\u043a\u043e\u043d',\n'\u043b\u043e\u043a\u043a',\n'\u043c\u0438\u043b\u043b\u044c',\n'\u0433\u0430\u043b\u0438\u043b\u0435\u0439',\n'\u0431\u0435\u0440\u043a\u043b\u0438',\n'\u0441\u043f\u0435\u043d\u0441\u0435\u0440',\n'\u0430\u0432\u0435\u043d\u0430\u0440\u0438\u0443\u0441',\n'\u043c\u0430\u0445',\n'\u0433\u0435\u043b\u044c\u0432\u0435\u0446\u0438\u0439',\n'\u0433\u043e\u043b\u044c\u0431\u0430\u0445',\n'\u0434\u0438\u0434\u0440\u043e',\n'\u043b\u0430\u043c\u0435\u0442\u0440\u0438',\n'\u043a\u0430\u043d\u0442',\n'\u0432\u043e\u043b\u044c\u0442\u0435\u0440',\n'\u043c\u043e\u043d\u0442\u0435\u0441\u043a\u044c\u0435',\n'\u0440\u0443\u0441\u0441\u043e',\n'\u043a\u0443\u043f\u0435\u0440',\n'\u044e\u043c',\n'\u0433\u043e\u0431\u0431\u0441',\n'\u0448\u0435\u043b\u043b\u0438\u043d\u0433',\n'\u0434\u0430\u0440\u0432\u0438\u043d',\n'\u0444\u0435\u0439\u0435\u0440\u0431\u0430\u0445',\n'\u0448\u043e\u043f\u0435\u043d\u0433\u0430\u0443\u044d\u0440',\n'\u043a\u043e\u043d\u0442',\n'\u043c\u0430\u0440\u043a\u0441',\n'\u044d\u043d\u0433\u0435\u043b\u044c\u0441',\n'\u043b\u0435\u043d\u0438\u043d',\n'\u0440\u0430\u0441\u0441\u0435\u043b',\n'\u0432\u0438\u0442\u0433\u0435\u043d\u0448\u0442\u0435\u0439\u043d',\n'\u043a\u0430\u0440\u043d\u0430\u043f',\n'\u043f\u043e\u043f\u043f\u0435\u0440',\n'\u043a\u0443\u043d',\n'\u0444\u0435\u0439\u0435\u0440\u0430\u0431\u0435\u043d\u0434',\n'\u043b\u0430\u043a\u0430\u0442\u043e\u0441',\n'\u0433\u0443\u0441\u0441\u0435\u0440\u043b\u044c',\n'\u0445\u0430\u0439\u0434\u0435\u0433\u0433\u0435\u0440',\n'\u0441\u0430\u0440\u0442\u0440',\n'\u043a\u0430\u043c\u044e',\n'\u044f\u0441\u043f\u0435\u0440\u0441',\n'\u043d\u0438\u0446\u0448\u0435',\n'\u0431\u0435\u0440\u0433\u0441\u043e\u043d',\n'\u0434\u0438\u043b\u044c\u0442\u0435\u0439',\n'\u0448\u043f\u0435\u043d\u0433\u043b\u0435\u0440',\n'\u043e\u0440\u0442\u0435\u0433\u0430',\n'\u0438\u043b\u044c\u0435\u043d\u043a\u043e\u0432',\n'\u0437\u0438\u043d\u043e\u0432\u044c\u0435\u0432',\n'\u043c\u0430\u043c\u0430\u0440\u0434\u0430\u0448\u0432\u0438\u043b\u0438',\n'\u0449\u0435\u0434\u0440\u043e\u0432\u0438\u0446\u043a\u0438\u0439',\n'\u043f\u0430\u0441\u043a\u0430\u043b\u044c',\n'\u043a\u044c\u0435\u0440\u043a\u0435\u0433\u043e\u0440',\n'\u0448\u0435\u0441\u0442\u043e\u0432',\n'\u0431\u0435\u0440\u0434\u044f\u0435\u0432',\n'\u0431\u0430\u0440\u0442',\n'\u0444\u0443\u043a\u043e',\n'\u0441\u043e\u0441\u0441\u044e\u0440',\n'\u043b\u0430\u043a\u0430\u043d',\n'\u0436\u0438\u0436\u0435\u043a',\n'\u0434\u0435\u043b\u0435\u0437',\n'\u0434\u0435\u0440\u0440\u0438\u0434\u0430',\n'\u0431\u043e\u0434\u0440\u0438\u0439\u044f\u0440',\n'\u043b\u0438\u043e\u0442\u0430\u0440',\n'\u0430\u0440\u0435\u043d\u0434\u0442',\n'\u0440\u044d\u043d\u0434',\n'\u0434\u0443\u0433\u0438\u043d',\n'\u0445\u0430\u0440\u043c\u0430\u043d',\n'\u043c\u0435\u0439\u044f\u0441\u0443',\n'\u043b\u0430\u0442\u0443\u0440']\ndct_names = dict.fromkeys(words)\nfor key in dct_names.keys():\n    dct_names[key] = dict.fromkeys(words);\n\nfor key1 in dct_names.keys():\n    for key2 in dct_names[key1].keys():\n        if key1 == key2:\n            dct_names[key1][key2] = '-';\n        else:\n            dct_names[key1][key2] = ft_model.wv.similarity(key1, key2)\n\"\"\"\n\u041c\u043e\u0436\u043d\u043e \u0432\u0437\u044f\u0442\u044c \u0437\u0430 \u0432\u0435\u0440\u0448\u0438\u043d\u044b \u043d\u0443\u0436\u043d\u044b\u0435 \u043d\u0430\u043c \u0441\u043b\u043e\u0432\u0430, \u0430 \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u044b \u0441\u0445\u043e\u0434\u0441\u0442\u0432\u0430 \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u0432\u0435\u0441\u0430\u043c\u0438 \u0440\u0451\u0431\u0435\u0440. \u0420\u0435\u0431\u0440\u043e \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f, \u0435\u0441\u043b\u0438 \u043a\u043e\u0441\u0438\u043d\u0443\u0441\u043d\u043e\u0435 \u0441\u0445\u043e\u0434\u0441\u0442\u0432\u043e \u043c\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438 \u0431\u043e\u043b\u044c\u0448\u0435 \u043f\u043e\u0440\u043e\u0433\u043e\u0432\u043e\u0433\u043e \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f:\n\"\"\"\nimport networkx as nx\nG_sim = nx.Graph()\nG_sim.add_nodes_from(words)\n\nfor key1 in dct_names.keys():\n    for key2 in dct_names[key1].keys():\n        if key1 != key2:\n            if dct_names[key1][key2] > 0.7:\n                G_sim.add_weighted_edges_from([(key1, key2, dct_names[key1][key2])])\n\ncolors = [i\/len(G_sim.nodes) for i in range(len(G_sim.nodes))]\n\nfig = plt.figure(figsize=(12, 12))\nnx.draw(\n    G_sim,\n    with_labels=True,\n    node_color=colors,\n    edge_color=['silver'] * len(G_sim.edges()),\n    cmap=plt.cm.jet,    \n    node_size=150,\n)\n\"\"\"\n\u0422\u0430\u043a\u0436\u0435 \u0434\u043b\u044f \u0440\u0430\u043d\u0436\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0432\u0435\u0440\u0448\u0438\u043d \u043c\u043e\u0436\u043d\u043e \u0432\u044b\u0431\u0440\u0430\u0442\u044c \u043c\u0435\u0442\u0440\u0438\u043a\u0443, \u043a\u043e\u0433\u0434\u0430 \u0440\u0430\u043d\u0433 \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u0435\u0442\u0441\u044f \u043e\u0442 \u0441\u043b\u043e\u0432\u0430 1 \u0434\u043e \u0441\u043b\u043e\u0432\u0430 2 \u043f\u043e \u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u044e \u043a \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f\u043c \u0432\u0441\u0435\u0445 \u0441\u043b\u043e\u0432 \u043e\u0442 \u0441\u043b\u043e\u0432\u0430 1. \u0422\u043e \u0435\u0441\u0442\u044c \u0432\u0435\u0441\u0430 \u0434\u043b\u044f \u0432\u0442\u043e\u0440\u043e\u0439 \u043c\u0435\u0442\u0440\u0438\u043a\u0438 \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u044f\u044e\u0442\u0441\u044f \u043f\u043e \u0444\u043e\u0440\u043c\u0443\u043b\u0435: 1\/rank, \u0442\u0430\u043a \u043a\u0430\u043a \u0447\u0435\u043c \u0431\u043e\u043b\u044c\u0448\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 rank, \u0442\u0435\u043c \u0445\u0443\u0436\u0435 \u0441\u0445\u043e\u0434\u0441\u0442\u0432\u043e. \u0420\u0435\u0431\u0440\u043e \u0441\u043e\u0437\u0434\u0430\u0435\u0442\u0441\u044f \u0441 \u043f\u043e\u0440\u043e\u0433\u043e\u0432\u044b\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\u043c \u0440\u0430\u0441\u0441\u0442\u043e\u044f\u043d\u0438\u044f (rank < n).\n\"\"\"\n\"\"\"\n**\u041e\u0441\u0442\u043e\u0440\u043e\u0436\u043d\u043e, \u0441 \u0431\u043e\u043b\u044c\u0448\u0438\u043c \u0441\u043f\u0438\u0441\u043a\u043e\u043c \u0441\u043b\u043e\u0432 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u043e\u0447\u0435\u043d\u044c \u043c\u0435\u0434\u043b\u0435\u043d\u043d\u043e.**\n\"\"\"\ndct_vls = dict.fromkeys(words)\nfor key in dct_vls.keys():\n    dct_vls[key] = dict.fromkeys(words)\n\nfor key1 in dct_vls.keys():\n    for key2 in dct_vls[key1].keys():\n        if key1 == key2:\n            dct_vls[key1][key2] = '-';\n        else:\n            dct_vls[key1][key2] = ft_model.wv.rank(key1, key2)\nG_rank = nx.Graph()\nG_rank.add_nodes_from(words)\n\nfor key1 in dct_vls.keys():\n    for key2 in dct_vls[key1].keys():\n        if key1 != key2:\n            if dct_vls[key1][key2] < 50:\n                G_rank.add_weighted_edges_from([(key1, key2, 1\/dct_vls[key1][key2])])\n\ncolors = [i\/len(G_rank.nodes) for i in range(len(G_rank.nodes))]\n\nfig = plt.figure(figsize=(10, 10))\nnodes = nx.draw(\n    G_rank,\n    with_labels=True,\n    node_color=colors,\n    edge_color=['silver'] * len(G_rank.edges()),\n    cmap=plt.cm.jet,    \n    node_size=150,\n)\n\"\"\"\n\u0412\u044b\u0431\u0438\u0440\u0430\u0435\u043c \u0433\u0440\u0430\u0444 \u0441 \u043d\u0443\u0436\u043d\u044b\u043c\u0438 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0430\u043c\u0438:\n\"\"\"\nG = G_rank\n#G = G_sim\n\"\"\"\n\u041f\u0440\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u0438\u0437\u043e\u043b\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0435 \u0432\u0435\u0440\u0448\u0438\u043d\u044b.\n\"\"\"\n#G.remove_nodes_from(list(nx.isolates(G)))\n\"\"\"\n\u0422\u0430\u043a\u0436\u0435 \u043f\u0440\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u0432\u044b\u0431\u0438\u0440\u0430\u0435\u043c \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u0439 \u043f\u043e\u0434\u0433\u0440\u0430\u0444.\n\"\"\"\n#G = G.subgraph(nx.shortest_path(G.to_undirected(),'\u0430\u043d\u0430\u043a\u0441\u0438\u043c\u0435\u043d'))\n\"\"\"\n\u0421\u043c\u043e\u0442\u0440\u0438\u043c \u0445\u0430\u0440\u0430\u043a\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043a\u0438 \u0433\u0440\u0430\u0444\u0430: \u0447\u0438\u0441\u043b\u043e \u0432\u0435\u0440\u0448\u0438\u043d \u0438 \u0440\u0451\u0431\u0435\u0440, \u0441\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b, \u043a\u043b\u0438\u043a\u0438:\n\n(\u043a\u043e\u0434 \u043f\u0440\u0435\u0438\u043c\u0443\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u043e \u043e\u0442\u0441\u044e\u0434\u0430: https:\/\/www.kaggle.com\/mayeesha\/network-analysis-for-dummies-stackoverflow-data)\n\"\"\"\nprint(nx.info(G))\nnx.is_connected(G)\nnx.number_connected_components(G)\ncliques = list(nx.find_cliques(G))\nclique_number = len(list(cliques))\nprint(clique_number)\nfor clique in cliques:\n    print(clique)\nprint(nx.ego_graph(G,'\u043b\u0435\u043d\u0438\u043d',radius=2).nodes())\nnx.algorithms.clique.cliques_containing_node(G,\"\u043b\u0435\u043d\u0438\u043d\")\nsorted_cliques = sorted(list(nx.find_cliques(G)),key=len)\nmax_clique_nodes = set()\n\nfor nodelist in sorted_cliques[-4:-1]:\n    for node in nodelist:\n        max_clique_nodes.add(node)\nmax_clique = G.subgraph(max_clique_nodes)\nprint(nx.info(max_clique))\ncolors = [i\/len(max_clique.nodes) for i in range(len(max_clique.nodes))]\n\nfig = plt.figure(figsize=(10, 10))\nnodes = nx.draw(\n    max_clique,\n    with_labels=True,\n    node_color=colors,\n    edge_color=['silver'] * len(max_clique.edges()),\n    cmap=plt.cm.jet,    \n    node_size=150,\n)\n\"\"\"\n## Modularity\n\"\"\"\n\"\"\"\n\u0415\u0441\u043b\u0438 \u043c\u044b \u0445\u043e\u0442\u0438\u043c \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c, \u043d\u0430 \u043a\u0430\u043a\u0438\u0435 \u0433\u0440\u0443\u043f\u043f\u044b \u043c\u043e\u0436\u043d\u043e \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u044c \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0441\u043b\u043e\u0432\u0430, \u043f\u0440\u0438\u043c\u0435\u043d\u044f\u044e\u0442\u0441\u044f \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b \u043c\u043e\u0434\u0443\u043b\u044c\u043d\u043e\u0441\u0442\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \"\u0440\u0430\u0437\u0431\u0438\u0432\u0430\u044e\u0442\" \u0433\u0440\u0430\u0444 \u043d\u0430 \u0441\u0432\u044f\u0437\u043d\u044b\u0435 \u043a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442\u044b-\u043c\u043e\u0434\u0443\u043b\u0438. \u041f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u0447\u0430\u0441\u0442\u043e \u043f\u0440\u0438\u043c\u0435\u043d\u044f\u0435\u043c\u044b\u0439 \u0434\u043b\u044f \u044d\u0442\u0438\u0445 \u0446\u0435\u043b\u0435\u0439 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c Louvain.\n\"\"\"\n\"\"\"\n\u041f\u0440\u0438\u043c\u0435\u0440 \u0441 \u041b\u0443\u0432\u0435\u043d\u0441\u043a\u0438\u043c \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u043e\u043c:\n\"\"\"\n!pip install python-louvain\nfrom community import community_louvain\ncommunities =community_louvain.best_partition(G)\ncommunity_id = [communities[node] for node in G.nodes()]\n\nfig = plt.figure(figsize=(10, 10))\nnx.draw(\n    G,\n    with_labels=True,\n    edge_color=['silver'] * len(G.edges()),\n    cmap=plt.cm.tab20,\n    node_color=community_id,\n    node_size=150,\n)\n\"\"\"\n\u0415\u0449\u0451 \u043e\u0434\u0438\u043d \u0432\u0430\u0440\u0438\u0430\u043d\u0442 \u0432\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 (\u0438\u0441\u0442\u043e\u0447\u043d\u0438\u043a: https:\/\/stackoverflow.com\/questions\/43541376\/how-to-draw-communities-with-networkx).\n\n\u0425\u043e\u0440\u043e\u0448\u043e \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u0441 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u043c \u043f\u043e\u0434\u0433\u0440\u0430\u0444\u043e\u043c.\n\"\"\"\nG_sub = G.subgraph(nx.shortest_path(G.to_undirected(),'\u0430\u043d\u0430\u043a\u0441\u0438\u043c\u0435\u043d'))\ndef community_layout(G_sub, partition):\n  \n    pos_communities = _position_communities(G_sub, partition, scale=3.)\n\n    pos_nodes = _position_nodes(G_sub, partition, scale=1.)\n\n    pos = dict()\n    for node in G_sub.nodes():\n        pos[node] = pos_communities[node] + pos_nodes[node]\n\n    return pos\n\ndef _position_communities(G_sub, partition, **kwargs):\n\n    between_community_edges = _find_between_community_edges(G_sub, partition)\n\n    communities = set(partition.values())\n    hypergraph = nx.DiGraph()\n    hypergraph.add_nodes_from(communities)\n    for (ci, cj), edges in between_community_edges.items():\n        hypergraph.add_edge(ci, cj, weight=len(edges))\n\n    pos_communities = nx.spring_layout(hypergraph, **kwargs)\n\n    pos = dict()\n    for node, community in partition.items():\n        pos[node] = pos_communities[community]\n\n    return pos\n\ndef _find_between_community_edges(G_sub, partition):\n\n    edges = dict()\n\n    for (ni, nj) in G_sub.edges():\n        ci = partition[ni]\n        cj = partition[nj]\n\n        if ci != cj:\n            try:\n                edges[(ci, cj)] += [(ni, nj)]\n            except KeyError:\n                edges[(ci, cj)] = [(ni, nj)]\n\n    return edges\n\ndef _position_nodes(G_sub, partition, **kwargs):\n    \n    communities = dict()\n    for node, community in partition.items():\n        try:\n            communities[community] += [node]\n        except KeyError:\n            communities[community] = [node]\n\n    pos = dict()\n    for ci, nodes in communities.items():\n        subgraph = G_sub.subgraph(nodes)\n        pos_subgraph = nx.spring_layout(subgraph, **kwargs)\n        pos.update(pos_subgraph)\n\n    return pos\n\ndef output():\n    from community import community_louvain\n\n    partition = community_louvain.best_partition(G_sub)\n    pos = community_layout(G_sub, partition)\n    fig = plt.figure(figsize=(10, 10))\n\n    nx.draw(G_sub, pos, \n    with_labels=True,\n    edge_color=['silver'] * len(G_sub.edges()),\n    cmap=plt.cm.tab20,    \n    node_size=150, node_color=list(partition.values())); plt.show()\n    return\noutput()\n\"\"\"\n\u0421\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u043c \u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440\u044b \u043c\u043e\u0434\u0443\u043b\u0435\u0439 \u0432 \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c:\n\"\"\"\ncommunity_list = pd.DataFrame(np.column_stack([G.nodes, community_id]), \n                               columns=['node', 'community'])\n\ncommunity_list.community = community_list.community.astype(int)\ncommunity_list.head(10)\n\"\"\"\n## Centrality\n\"\"\"\n\"\"\"\n\u0414\u043b\u044f \u0440\u0430\u043d\u0436\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0432\u0435\u0440\u0448\u0438\u043d \u0432 \u0433\u0440\u0430\u0444\u0435 \u043c\u043e\u0436\u043d\u043e \u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u043f\u0435\u0439\u0434\u0436\u0440\u0430\u043d\u043a\u043e\u043c.\n\"\"\"\ndef eigenvector(G):\n    ev = nx.eigenvector_centrality(G)\n    df = pd.DataFrame.from_dict({\n        'node': list(ev.keys()),\n        'eigenvector': list(ev.values())\n    })\n    return df.sort_values('eigenvector', ascending=False)\neigenv = pd.DataFrame(eigenvector(G), columns=['node', 'eigenvector'])\neigenv.head(10)\ndef pr_summary(G):\n    pr = nx.pagerank(G)\n    df = pd.DataFrame.from_dict({\n        'node': list(pr.keys()),\n        'centrality_pr': list(pr.values())\n    })\n    return df.sort_values('centrality_pr', ascending=False)\npr = pd.DataFrame(pr_summary(G), columns=['node', 'centrality_pr'])\npr.head()\n\"\"\"\n\u0410 \u0442\u0430\u043a\u0436\u0435 \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u043c\u0438 \u043c\u0435\u0440\u0430\u043c\u0438 \u0446\u0435\u043d\u0442\u0440\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u0438 (\u043f\u0440\u0438 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438):\n\"\"\"\ndef cc_summary(G):\n    cc = nx.closeness_centrality(G)\n    df = pd.DataFrame.from_dict({\n        'node': list(cc.keys()),\n        'centrality_\u0441\u0441': list(cc.values())\n    })\n    return df.sort_values('centrality_\u0441\u0441', ascending=False)\ncc = pd.DataFrame(cc_summary(G), columns=['node', 'centrality_\u0441\u0441'])\ncc.head()\ndef dc_summary(G):\n    dc = nx.degree_centrality(G)\n    df = pd.DataFrame.from_dict({\n        'node': list(dc.keys()),\n        'centrality_dc': list(dc.values())\n    })\n    return df.sort_values('centrality_dc', ascending=False)\ndc = pd.DataFrame(dc_summary(G), columns=['node', 'centrality_dc'])\ndc.head()\ndef bc_summary(G):\n    bc = nx.betweenness_centrality(G)\n    df = pd.DataFrame.from_dict({\n        'node': list(bc.keys()),\n        'centrality_bc': list(bc.values())\n    })\n    return df.sort_values('centrality_bc', ascending=False)\nbc = pd.DataFrame(bc_summary(G), columns=['node', 'centrality_bc'])\nbc.head()\ndef clustering(G):\n    cl = nx.clustering(G, weight='weight')\n    df = pd.DataFrame.from_dict({\n        'node': list(cl.keys()),\n        'weight_cl': list(cl.values())\n    })\n    return df.sort_values('weight_cl', ascending=False)\ncl = pd.DataFrame(clustering(G), columns=['node', 'weight_cl'])\ncl.head()\n\"\"\"\n\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0432\u0441\u0435 \u043f\u043e\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u0438 \u0432 \u043e\u0434\u0438\u043d \u0434\u0430\u0442\u0430\u0444\u0440\u0435\u0439\u043c.\n\"\"\"\nfrom functools import reduce\n\ndfs = [community_list, eigenvector(G), cc_summary(G), dc_summary(G), bc_summary(G), pr_summary(G), clustering(G)]  \ndf_sum = reduce(lambda left,right: pd.merge(left,right,on='node'), dfs)\ndf_sum.head()\ncorr = df_sum.corr()\ncorr.style.background_gradient(cmap='coolwarm')\n\"\"\"\n## Link Prediction\n\u0418\u0441\u0442\u043e\u0447\u043d\u0438\u043a: https:\/\/www.geeksforgeeks.org\/link-prediction-predict-edges-in-a-network-using-networkx\/\n\"\"\"\n\"\"\"\n\u0422\u0435\u043f\u0435\u0440\u044c \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0441\u0442\u0430\u043d\u0434\u0430\u0440\u0442\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0441\u0432\u044f\u0437\u0435\u0439 \u043c\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438. \u041f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0438\u0437 \u043d\u0438\u0445.\n\"\"\"\n\"\"\"\nTriadic Closure:\n\"\"\"\ne = list(G.edges())\n  \ndef triadic(e):\n    new_edges = []\n  \n    for i in e:\n        a, b = i\n  \n        for j in e:\n            x, y = j\n  \n            if i != j:\n                if a == x and (b, y) not in e and (y, b) not in e:\n                    new_edges.append((b, y))\n                if a == y and (b, x) not in e and (x, b) not in e:\n                    new_edges.append((b, x))\n                if b == x and (a, y) not in e and (y, a) not in e:\n                    new_edges.append((a, y))\n                if b == y and (a, x) not in e and (x, a) not in e:\n                    new_edges.append((a, x))\n  \n    return new_edges\n\ntriadic = pd.DataFrame(triadic(e), columns=['node_1', 'node2'])\ntriadic.head(10)\n\"\"\"\nJaccard Coefficient:\n\"\"\"\njaccard_coefficient = pd.DataFrame(nx.jaccard_coefficient(G), columns=['node_1', 'node2', 'jaccard_coefficient'])\njaccard_coefficient.sort_values(by = 'jaccard_coefficient', ascending = False).head(10)\n\"\"\"\nResource Allocation Index:\n\"\"\"\nresource_allocation_index = pd.DataFrame(nx.resource_allocation_index(G), columns=['node_1', 'node2', 'resource_allocation_index'])\nresource_allocation_index.sort_values(by = 'resource_allocation_index', ascending = False).head(10)\n\"\"\"\nAdamic Adar Index:\n\"\"\"\nadamic_adar_index = pd.DataFrame(nx.adamic_adar_index(G), columns=['node_1', 'node2', 'adamic_adar_index'])\nadamic_adar_index.sort_values(by = 'adamic_adar_index', ascending = False).head(10)\n\"\"\"\nPreferential Attachment:\n\"\"\"\npreferential_attachment = pd.DataFrame(nx.preferential_attachment(G), columns=['node_1', 'node2', 'preferential_attachment'])\npreferential_attachment.sort_values(by = 'preferential_attachment', ascending = False).head(10)\n\"\"\"\n\u0412 \u0446\u0435\u043b\u044f\u0445 \u0443\u0442\u043e\u0447\u043d\u0435\u043d\u0438\u044f \u0434\u0435\u0442\u0430\u043b\u0435\u0439 \u043c\u043e\u0436\u0435\u043c \u043d\u0430\u0439\u0442\u0438 \u043d\u0430\u0438\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0439 \u043f\u0443\u0442\u044c \u043c\u0435\u0436\u0434\u0443 \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u044e\u0449\u0438\u043c\u0438 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438:\n\"\"\"\nprint(nx.shortest_path(G,source='\u043b\u0430\u043a\u0430\u0442\u043e\u0441',target='\u043a\u0430\u0440\u043d\u0430\u043f'))\nprint(nx.shortest_path(G,source='\u043b\u0430\u043a\u0430\u0442\u043e\u0441',target='\u043a\u0430\u0440\u043d\u0430\u043f', weight='weight'))\n\"\"\"\n## node2vec\n\u0418\u0441\u0442\u043e\u0447\u043d\u0438\u043a: https:\/\/github.com\/eliorc\/node2vec\n\"\"\"\n\"\"\"\n\u0417\u0430\u0447\u0435\u043c \u044d\u0442\u043e \u043d\u0430\u0434\u043e, \u0435\u0449\u0435 \u043d\u0435 \u0441\u043e\u0432\u0441\u0435\u043c \u043f\u043e\u043d\u044f\u0442\u043d\u043e. \u041f\u043e\u043a\u0430 \u0447\u0442\u043e \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u043f\u043e \u0441\u0445\u043e\u0436\u0435\u0441\u0442\u0438 \u0438 \u043a\u043b\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0432\u0435\u0440\u0448\u0438\u043d, \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u0435\u0449\u0451 \u0442\u043e\u0447\u043d\u0435\u0435 \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0438\u0445. \n\"\"\"\n!pip install node2vec\nfrom node2vec import Node2Vec\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n%matplotlib inline\nnode2vec = Node2Vec(G, dimensions=300, walk_length=30, num_walks=200, workers=4)\nn2v_model = node2vec.fit(window=10, min_count=1, batch_words=4)\nn2v_model.wv.most_similar('\u043a\u0430\u0440\u043d\u0430\u043f')\nn2v_output = pd.DataFrame(n2v_model.wv.most_similar(positive=['\u043a\u0430\u0440\u043d\u0430\u043f'], topn=30), columns=['\u0443\u043f\u043e\u043c\u0438\u043d\u0430\u043d\u0438\u044f', '\u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442'])\nimport seaborn as sns\nsns.set_theme(style=\"ticks\", color_codes=True)\ng=sns.catplot(x='\u0443\u043f\u043e\u043c\u0438\u043d\u0430\u043d\u0438\u044f', y='\u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442', data=n2v_output)\ng.set_xticklabels(rotation=45)\ng.fig.set_size_inches(15,5)\nplt.title('\u0443\u043f\u043e\u043c\u0438\u043d\u0430\u043d\u0438\u044f, \u043f\u043e\u0445\u043e\u0436\u0438\u0435 \u043d\u0430 \u0437\u0430\u043f\u0440\u043e\u0441')\nfrom node2vec.edges import HadamardEmbedder\nedges_embs = HadamardEmbedder(keyed_vectors=n2v_model.wv)\nedges_embs[('\u043a\u0430\u0440\u043d\u0430\u043f', '\u043b\u0430\u043a\u0430\u0442\u043e\u0441')]\nedges_kv = edges_embs.as_keyed_vectors()\nedges_kv.most_similar(str(('\u043a\u0430\u0440\u043d\u0430\u043f', '\u043b\u0430\u043a\u0430\u0442\u043e\u0441')))\n\"\"\"\n\u041a\u043b\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0443\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e UMAP \u0438 HDBSCAN.\n\n(\u0418\u0441\u0442\u043e\u0447\u043d\u0438\u043a: https:\/\/github.com\/Huguet57\/Information-Contrast)\n\"\"\"\nlabels = []\ntokens = []\n\nfor word in n2v_model.wv.key_to_index:\n    tokens.append(n2v_model.wv[word])\n    labels.append(word)\ntokens_norm = (tokens - np.mean(tokens))\/np.sqrt(np.var(tokens))\n!pip install umap-learn\nimport umap.umap_ as umap\n\nreducer = umap.UMAP(n_neighbors=15,\n                    min_dist=0.01,\n                    metric='euclidean',\n                    n_epochs=2000,\n                    random_state=23,\n                    verbose=True)\numap_embedding = reducer.fit_transform(tokens_norm)\numap_embedding.shape\nx = []\ny = []\nfor value in umap_embedding:\n    x.append(value[0])\n    y.append(value[1])\n    \nplt.figure(figsize=(12, 12)) \nfor i in range(len(x)):\n    plt.scatter(x[i],y[i])\n    #plt.annotate(labels[i],\n                  #xy = (x[i], y[i]),\n                  #xytext = (5, 2),\n                  #textcoords = 'offset points',\n                  #ha = 'right',\n                  #va = 'bottom')\nplt.show()\n#!pip install --upgrade --user numpy\n!pip install hdbscan --no-build-isolation --no-binary :all:\nimport hdbscan\n\nlabels_hdbscan = hdbscan.HDBSCAN(\nmin_samples=1,\nmin_cluster_size=2,\n).fit_predict(umap_embedding)\nclustered = (labels_hdbscan >= 0)\nfrom matplotlib.pyplot import figure\nfigure(figsize=(10, 10), dpi=80)\nplt.scatter(umap_embedding[~clustered, 0],\n            umap_embedding[~clustered, 1],\n            c=(0.5, 0.5, 0.5),\n            s=10,\n            alpha=0.5)\nplt.scatter(umap_embedding[clustered, 0],\n            umap_embedding[clustered, 1],\n            c=(labels_hdbscan[clustered]),\n            s=20,\n            cmap='Spectral')\nclustered_list = pd.DataFrame(np.column_stack([G.nodes, labels_hdbscan]), \n                               columns=['node', 'cluster'])\nclustered_list.head(20)\nclustered_list['cluster'].value_counts()\n\"\"\"\n# \u041a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u044f \u0442\u0435\u0440\u043c\u043e\u0432\n\"\"\"\n\"\"\"\n\u0412 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u0435 \u0440\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u044f \u0433\u0440\u0430\u0444\u0430 \u043d\u0430 \u0441\u043e\u043e\u0431\u0449\u0435\u0441\u0442\u0432\u0430 \u0443 \u043d\u0430\u0441 \u0435\u0441\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0447\u0435\u043d\u043d\u044b\u0439 \u0434\u0430\u0442\u0430\u0441\u0435\u0442. \u0415\u0441\u043b\u0438 \u0441\u043e\u043e\u0431\u0449\u0435\u0441\u0442\u0432\u0430 (\u043c\u043e\u0434\u0443\u043b\u0438) \u0445\u043e\u0440\u043e\u0448\u043e \u0438\u043d\u0442\u0435\u0440\u043f\u0440\u0435\u0442\u0438\u0440\u0443\u044e\u0442\u0441\u044f, \u0442\u043e \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0432\u0435\u043a\u0442\u043e\u0440\u043e\u0432 \u0441\u043b\u043e\u0432 \u043a\u0430\u043a \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 (\u0444\u0438\u0447\u0438) \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0446\u0435\u043b\u0435\u0432\u044b\u0445 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445. \u0420\u0430\u0441\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043f\u0440\u0438\u043c\u0435\u0440 \u0441 \u043c\u0443\u043b\u044c\u0442\u0438\u043a\u043b\u0430\u0441\u0441\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0435\u0439.\n\"\"\"\n\"\"\"\n\u0421\u043d\u043e\u0432\u0430 \u043f\u043e\u0441\u0442\u0440\u043e\u0438\u043c \u0433\u0440\u0430\u0444. \u041c\u044b \u0431\u0443\u0434\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0433\u0440\u0430\u0444 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u043b\u044f \u0432\u044b\u0447\u0438\u0441\u043b\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0446\u0435\u043b\u0435\u0439, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0432\u043e\u0437\u044c\u043c\u0451\u043c \u043b\u044e\u0431\u044b\u0435 \u043f\u043e\u043b\u043e\u0436\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043a\u043e\u044d\u0444\u0444\u0438\u0446\u0438\u0435\u043d\u0442\u0430 \u0441\u0445\u043e\u0434\u0441\u0442\u0432\u0430 \u043c\u0435\u0436\u0434\u0443 \u0441\u043b\u043e\u0432\u0430\u043c\u0438 \u0434\u043b\u044f \u043f\u043e\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u044f \u0432\u0437\u0432\u0435\u0448\u0435\u043d\u043d\u044b\u0445 \u0440\u0451\u0431\u0435\u0440 \u043c\u0435\u0436\u0434\u0443 \u0432\u0435\u0440\u0448\u0438\u043d\u0430\u043c\u0438. \n\"\"\"\ng = nx.Graph()\ng.add_nodes_from(words)\n\nfor key1 in dct_names.keys():\n    for key2 in dct_names[key1].keys():\n        if key1 != key2:\n            if dct_names[key1][key2] > 0:\n                g.add_weighted_edges_from([(key1, key2, dct_names[key1][key2])])\nfrom community import community_louvain\ncommunities =community_louvain.best_partition(g)\ncommunity_id = [communities[node] for node in g.nodes()]\n\nfig = plt.figure(figsize=(10, 10))\nnx.draw(\n    g,\n    with_labels=True,\n    edge_color=['silver'] * len(G.edges()),\n    cmap=plt.cm.tab20,\n    node_color=community_id,\n    node_size=150,\n)\ncommunity_list = pd.DataFrame(np.column_stack([g.nodes, community_id]), \n                               columns=['node', 'community'])\n\ncommunity_list.community = community_list.community.astype(int)\ndf_target = community_list.copy()\nx = [(ft_model.wv[str(i)]) for i in df_target['node']]\nemb_df_untarget = pd.DataFrame(x, index = df_target['node'])\ndf_target.set_index('node', inplace=True)\nemb_df_target = df_target.join(emb_df_untarget)\ndf_train = emb_df_target\ndata_full = df_train.copy()\nX_data = data_full.drop('community', axis=1)\ny = data_full.community\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nlabel_encoder = LabelEncoder()\nlabel_encoder = label_encoder.fit(y)\nlabel_encoded_y = label_encoder.transform(y)\nseed = 7\ntest_size = 0.33\nX_train, X_test, y_train, y_test = train_test_split(X_data, label_encoded_y,test_size=test_size, random_state=seed)\nxgb = XGBClassifier(\n    max_depth=2,\n    gamma=2,\n    eta=0.8,\n    reg_alpha=0.5,\n    reg_lambda=0.5\n)\nxgb.fit(X_train, y_train)\npredictions = xgb.predict(X_test)\naccuracy = accuracy_score(y_test, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\"\"\"\n\u0422\u0435\u043f\u0435\u0440\u044c \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u0442\u044c \u0446\u0435\u043b\u0435\u0432\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u043d\u0430 \u043d\u043e\u0432\u043e\u043c \u043d\u0430\u0431\u043e\u0440\u0435 \u0441\u043b\u043e\u0432.\n\"\"\"\npred_words = [\n\n    '\u0430\u0440\u0438\u0441\u0442\u043e\u0442\u0435\u043b\u044c',\n    '\u0441\u0442\u0430\u0433\u0438\u0440\u0430',\n    '\u043f\u043b\u0430\u0442\u043e\u043d',\n    '\u043b\u043e\u0433\u0438\u043a\u0430',\n    '\u0434\u0438\u0430\u043b\u043e\u0433\u0438',\n    '\u043d\u0430\u0443\u043a\u0438',\n    '\u0442\u0435\u043e\u0440\u0435\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435',\n    '\u043f\u0440\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435',\n    '\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430',\n    '\u043c\u0435\u0442\u0430\u0444\u0438\u0437\u0438\u043a\u0430',\n    '\u0444\u0438\u0437\u0438\u043a\u0430',\n    '\u044d\u0442\u0438\u043a\u0430',\n    '\u043f\u043e\u043b\u0438\u0442\u0438\u043a\u0430',\n    '\u043f\u0440\u0438\u0447\u0438\u043d\u0430',\n    '\u043f\u0435\u0440\u0432\u043e\u043d\u0430\u0447\u0430\u043b\u043e',\n    '\u043c\u0430\u0442\u0435\u0440\u0438\u044f',\n    '\u043f\u0435\u0440\u0432\u043e\u044d\u043b\u0435\u043c\u0435\u043d\u0442',\n    '\u0444\u043e\u0440\u043c\u0430',\n    '\u0432\u043e\u0437\u0434\u0443\u0445',\n    '\u0432\u043e\u0434\u0430',\n    '\u043e\u0433\u043e\u043d\u044c',\n    '\u0437\u0435\u043c\u043b\u044f',\n    '\u044d\u0444\u0438\u0440',\n    '\u043f\u0435\u0440\u0432\u043e\u0434\u0432\u0438\u0433\u0430\u0442\u0435\u043b\u044c',\n    '\u0443\u043c',\n    '\u0431\u043e\u0433',\n    '\u0434\u0435\u0439\u0441\u0442\u0432\u0443\u044e\u0449\u0430\u044f',\n    '\u0432\u0435\u0449\u044c',\n    '\u0446\u0435\u043b\u044c',\n    '\u0434\u0443\u0448\u0430',\n    '\u0447\u0435\u043b\u043e\u0432\u0435\u043a',\n    '\u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0435',\n    '\u0440\u0430\u0441\u0442\u0435\u043d\u0438\u0435',\n    '\u0431\u044b\u0442\u0438\u0435',\n    '\u043c\u044b\u0448\u043b\u0435\u043d\u0438\u0435',\n    '\u043f\u043e\u043d\u044f\u0442\u0438\u0435',\n    '\u0441\u0443\u0436\u0434\u0435\u043d\u0438\u0435',\n    '\u0443\u043c\u043e\u0437\u0430\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435',\n    '\u0447\u0443\u0432\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435',\n    '\u0430\u0431\u0441\u0442\u0440\u0430\u043a\u0442\u043d\u043e\u0435',\n    '\u0434\u0438\u0430\u043b\u0435\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0435',\n    '\u0430\u043f\u043e\u0434\u0438\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0435',\n    '\u043f\u043e\u0437\u043d\u0430\u043d\u0438\u0435',\n    '\u043e\u043f\u044b\u0442',\n    '\u0434\u043e\u0441\u0442\u043e\u0432\u0435\u0440\u043d\u043e\u0441\u0442\u044c',\n    '\u043e\u0449\u0443\u0449\u0435\u043d\u0438\u0435',\n    '\u0433\u043e\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u043e',\n    '\u0444\u043e\u0440\u043c\u0430',\n    '\u0441\u043e\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0435',\n    '\u0441\u0435\u043c\u044c\u044f',\n    '\u0433\u043e\u0440\u043e\u0434',\n    '\u0441\u0447\u0430\u0441\u0442\u044c\u0435',\n    '\u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0441\u0442\u0432\u043e',\n    '\u0432\u0440\u0435\u043c\u044f',\n    '\u0441\u0443\u0431\u0441\u0442\u0430\u043d\u0446\u0438\u044f',\n    '\u043e\u0442\u043d\u043e\u0448\u0435\u043d\u0438\u044f',\n    '\u043e\u0431\u044a\u0435\u043a\u0442',\n    '\u0447\u0430\u0441\u0442\u044c',\n    '\u0431\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u043e\u0435',\n    '\u0441\u0443\u0449\u0435\u0441\u0442\u0432\u043e\u0432\u0430\u043d\u0438\u0435',\n    '\u0446\u0435\u043b\u043e\u0435',\n    '\u0442\u0435\u043f\u0435\u0440\u044c',\n    '\u0434\u0432\u0438\u0436\u0435\u043d\u0438\u0435',\n    '\u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435',\n    '\u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0435\u0435',\n    '\u043f\u043e\u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435',\n    '\u0438\u0437\u043c\u0435\u0440\u0435\u043d\u0438\u0435',\n    '\u0441\u0447\u0435\u0442',\n    '\u043f\u043e\u043a\u043e\u0439',\n    '\u043d\u0435\u043f\u043e\u0434\u0432\u0438\u0436\u043d\u043e\u0435',\n    '\u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435',\n    '\u043d\u0430\u0431\u043b\u044e\u0434\u0430\u0442\u0435\u043b\u044c'\n\n]\nx1 = [(ft_model.wv[str(i)]) for i in pred_words]\nlen(x1)\nemb_df = pd.DataFrame(x1, index = pred_words)\nboosted_predictions = xgb.predict(emb_df.values)\nnode = emb_df.index\npred_results = pd.DataFrame({'node': node, 'value_prediction': boosted_predictions})\npred_results.value_prediction.value_counts()\nselect_class = pred_results.loc[pred_results['value_prediction'] == 1]\nselect_class","meta":"{'source': 'AI4Code', 'id': '368c37de14baa1'}"}
{"id":"32203","text":"#importing liberaries \nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set(style=\"whitegrid\")\nimport os\nimport glob as gb\nimport cv2\nimport tensorflow as tf\nimport keras\n#data path\ntrainpath = '..\/input\/intel-image-classification\/seg_train\/'\ntestpath = '..\/input\/intel-image-classification\/seg_test\/'\npredpath = '..\/input\/intel-image-classification\/seg_pred\/'\n#training data informations \nFolder_name=[]\nfolder_item_numbers = []\nfor folder in  os.listdir(trainpath + 'seg_train') : \n    files = gb.glob(pathname= str( trainpath +'seg_train\/\/' + folder + '\/*.jpg'))\n    Folder_name.append(folder)\n    folder_item_numbers.append(len(files))\nfoldernames=pd.DataFrame({'Folder_name':Folder_name})\nitemnumbers=pd.DataFrame({'Traning Image Numbers':folder_item_numbers})\ninformations=pd.concat([foldernames,itemnumbers],axis=1)\nprint(informations)\n\n#test data informations \nFolder_name=[]\nfolder_item_numbers = []\nfor folder in  os.listdir(testpath + 'seg_test') : \n    files = gb.glob(pathname= str( testpath +'seg_test\/\/' + folder + '\/*.jpg'))\n    Folder_name.append(folder)\n    folder_item_numbers.append(len(files))\nfoldernames=pd.DataFrame({'Folder_name':Folder_name})\nitemnumbers=pd.DataFrame({' Test Image Numbers':folder_item_numbers})\ninformations=pd.concat([foldernames,itemnumbers],axis=1)\nprint(informations)\n#prediction data informations \nFolder_name=[]\nfolder_item_numbers = []\nfor folder in  os.listdir(predpath) : \n    files = gb.glob(pathname= str( predpath + folder + '\/*.jpg'))\n    Folder_name.append(folder)\n    folder_item_numbers.append(len(files))\nfoldernames=pd.DataFrame({'Folder_name':Folder_name})\nitemnumbers=pd.DataFrame({' pred Image Numbers':folder_item_numbers})\ninformations=pd.concat([foldernames,itemnumbers],axis=1)\nprint(informations)\n#checking image size for traning data\nImage_size = []\nfor folder in  os.listdir(trainpath +'seg_train') : \n    files = gb.glob(pathname= str( trainpath +'seg_train\/\/' + folder + '\/*.jpg'))\n    for image in files: \n        read_image = plt.imread(image)\n        Image_size.append(read_image.shape)\npd.Series(Image_size).value_counts()\n#checking image size for test data\nImage_size = []\nfor folder in  os.listdir(testpath +'seg_test') : \n    files = gb.glob(pathname= str( testpath +'seg_test\/\/' + folder + '\/*.jpg'))\n    for image in files: \n        read_image = plt.imread(image)\n        Image_size.append(read_image.shape)\npd.Series(Image_size).value_counts()\n#checking image size for pred data\nImage_size = []\nfor folder in  os.listdir(predpath) : \n    files = gb.glob(pathname= str( predpath + folder + '\/*.jpg'))\n    for image in files: \n        read_image = plt.imread(image)\n        Image_size.append(read_image.shape)\npd.Series(Image_size).value_counts()\n#resize each image in all folders\n#identifing new size as 100 \n#converting images to an array as X_train and and making a labeling array for it as y_train\nnew_size=100    \nX_train = []\ny_train = []\nfor folder in  os.listdir(trainpath +'seg_train') : \n    files = gb.glob(pathname= str( trainpath +'seg_train\/\/' + folder + '\/*.jpg'))\n    for file in files: \n        image_class = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n        orignal_image = cv2.imread(file)\n        resized_image = cv2.resize(orignal_image , (new_size,new_size))\n        X_train.append(list(resized_image))\n        y_train.append(image_class[folder])\n\n#check items in X_train\nprint(\"items in X_train is:       \",len(X_train) , \" items\")\n#showing training images with labels\nplt.figure(figsize=(20,20))\nfor n , i in enumerate(list(np.random.randint(0,len(X_train),36))) : \n    plt.subplot(6,6,n+1)\n    plt.imshow(X_train[i])   \n    plt.axis('off')\n    classes = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n    def get_img_class(n):\n        for x , y in classes.items():\n            if n == y :\n                return x\n    plt.title(get_img_class(y_train[i]))\n#resize each image in all folders for Test Data\n#identifing new size as 100 \n#converting images to an array as X_test and and making a labeling array for it as y_test\nnew_size=100    \nX_test = []\ny_test = []\nfor folder in  os.listdir(testpath +'seg_test') : \n    files = gb.glob(pathname= str( testpath +'seg_test\/\/' + folder + '\/*.jpg'))\n    for file in files: \n        image_class = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n        orignal_image = cv2.imread(file)\n        resized_image = cv2.resize(orignal_image , (new_size,new_size))\n        X_test.append(list(resized_image))\n        y_test.append(image_class[folder])\n#check items in X_test\nprint(\"items in X_test is:       \",len(X_test) , \" items\")\n#showing test images with labels\nplt.figure(figsize=(20,20))\nfor n , i in enumerate(list(np.random.randint(0,len(X_test),36))) : \n    plt.subplot(6,6,n+1)\n    plt.imshow(X_test[i])   \n    plt.axis('off')\n    classes = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n    def get_img_class(n):\n        for x , y in classes.items():\n            if n == y :\n                return x\n    plt.title(get_img_class(y_test[i]))\n#resize each image in all folders for prediction Data\n#identifing new size as 100 \n#converting images to an array as X_pred\nnew_size=100    \nX_pred = []\nfor folder in  os.listdir(predpath) : \n    files = gb.glob(pathname= str( predpath + folder + '\/*.jpg'))\n    for file in files: \n        image_class = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n        orignal_image = cv2.imread(file)\n        resized_image = cv2.resize(orignal_image , (new_size,new_size))\n        X_pred.append(list(resized_image))\n#check items in X_pred\nprint(\"items in X_pred is:       \",len(X_pred) , \" items\")\n#showing some prediction images\nplt.figure(figsize=(20,20))\nfor n , i in enumerate(list(np.random.randint(0,len(X_pred),36))) : \n    plt.subplot(6,6,n+1)\n    plt.imshow(X_pred[i])   \n    plt.axis('off')\n#converting all data to array\nX_train = np.array(X_train)\nX_test = np.array(X_test)\nX_Pred = np.array(X_pred)\ny_train = np.array(y_train)\ny_test = np.array(y_test)\nprint(\"X_train shape  : \",X_train.shape)\nprint(\"X_test shape  :\" ,X_test.shape)\nprint(\"X_Pred shape :\" , X_Pred.shape)\nprint(\"y_train shape :\" ,y_train.shape)\nprint(\"y_test shape :\", y_test.shape)\n\"\"\"\nbuilding the CNN model using Keras \nwe will make Conv2D layers , MaxPooling & Denses\n\"\"\"\n\nClassification_Model_Keras = keras.models.Sequential([\n        keras.layers.Conv2D(256,kernel_size=(3,3),activation='relu',input_shape=(new_size,new_size,3)),\n        keras.layers.Conv2D(128,kernel_size=(3,3),activation='relu'),\n        keras.layers.Conv2D(64,kernel_size=(3,3),activation='relu'),\n        keras.layers.MaxPool2D(4,4),\n        keras.layers.Conv2D(128,kernel_size=(3,3),activation='relu'),    \n        keras.layers.Conv2D(64,kernel_size=(3,3),activation='relu'),    \n        keras.layers.Conv2D(32,kernel_size=(3,3),activation='relu'),\n        keras.layers.MaxPool2D(4,4),\n        keras.layers.Flatten() ,    \n        keras.layers.Dense(128,activation='relu') ,    \n        keras.layers.Dense(64,activation='relu') ,    \n        keras.layers.Dense(32,activation='relu') ,        \n        keras.layers.Dropout(rate=0.5) ,            \n        keras.layers.Dense(6,activation='softmax') ,    \n        ])\n\"\"\"\nfor compling Model:\nwe will use adam optimizer\nsparse categorical crossentropy loss as we have 6 output\n\n\n\"\"\"\nClassification_Model_Keras.compile(optimizer ='adam',\n                                   loss='sparse_categorical_crossentropy',\n                                   metrics=['accuracy'])\n\"\"\"\nModel summary \n\"\"\"\nprint('Model Summary: ')\nprint(Classification_Model_Keras.summary())\n\"\"\"\ntrain the model \nwe will  use 40 epochs\n\"\"\"\nepochs = 40\nKerasModel = Classification_Model_Keras.fit(X_train, y_train, epochs=epochs,batch_size=64,verbose=1)\n\n\"\"\"\nfinal loss & accuracy\n\"\"\"\nval_Loss, val_Acc = Classification_Model_Keras.evaluate(X_test, y_test)\n\nprint('Test Loss:', val_Loss)\nprint('Test Accuracy :', val_Acc)\n\"\"\"\npredicting Categories of X_test\n\"\"\"\ny_test_pred = Classification_Model_Keras.predict(X_test)\n\nprint('y_test_pred Shape :',y_test_pred.shape)\n\"\"\"\nCategories Prediction (y_pred) of X_Pred\n\"\"\"\ny_pred = Classification_Model_Keras.predict(X_Pred)\n\nprint('Prediction Shape for y_result : ',y_pred.shape)\n\"\"\"\n showing some random images from the predicted images and its predicting category\n\"\"\"\nplt.figure(figsize=(20,20))\nfor n , i in enumerate(list(np.random.randint(0,len(X_pred),36))) : \n    plt.subplot(6,6,n+1)\n    plt.imshow(X_pred[i])    \n    plt.axis('off')\n    classes = {'buildings':0 ,'forest':1,'glacier':2,'mountain':3,'sea':4,'street':5}\n    def get_img_class(n):\n        for x , y in classes.items():\n            if n == y :\n                return x\n    plt.title(get_img_class(np.argmax(y_pred[i])))","meta":"{'source': 'AI4Code', 'id': '3b48d26e1cfdbe'}"}
{"id":"79409","text":"!pip install -q --upgrade pip\n!pip install -q efficientnet\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport matplotlib.pyplot as plt\nimport efficientnet.tfkeras as efn\nimport seaborn as sns\n\nfrom kaggle_datasets import KaggleDatasets\nfrom keras.applications import ResNet50\n\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\nfrom tqdm.notebook import tqdm\nfrom sklearn.metrics import classification_report, confusion_matrix\n\nimport sys\nimport glob\nimport math\nimport gc\nimport time\n\nprint(f'tensorflow version: {tf.__version__}')\nprint(f'tensorflow keras version: {tf.keras.__version__}')\nprint(f'python version: P{sys.version}')\nAUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')\n\n# # set half precision policy\nmixed_precision.set_policy('mixed_bfloat16')\n\n# enable XLA optmizations\ntf.config.optimizer.set_jit(True)\n\nprint(f'Compute dtype: {mixed_precision.global_policy().compute_dtype}')\nprint(f'Variable dtype: {mixed_precision.global_policy().variable_dtype}')\nIMG_HEIGHT = 600\nIMG_WIDTH = 800\n\nIMG_SIZE = 600\nIMG_TARGET_SIZE = 512\nN_CHANNELS = 3\n\nN_TRAIN_IMGS = 21642\nN_VAL_IMGS = 5410\nBATCH_SIZE_VAL = 128 * REPLICAS # 5410 \/ 8 \/ 4\n\nN_LABELS = 5\nN_FOLDS = 5\nEPOCHS = 30\n\nBATCH_SIZE_BASE = 16\nBATCH_SIZE = BATCH_SIZE_BASE * REPLICAS\n\nTARGET_DTYPE = tf.bfloat16\n\n# ImageNet mean and standard deviation\nIMAGENET_MEAN = tf.constant([0.485, 0.456, 0.406], dtype=tf.float32)\nIMAGENET_STD = tf.constant([0.229, 0.224, 0.225], dtype=tf.float32)\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('cassava-leaf-disease-tfrecords-600x600')\ndef decode_tfrecord_train(record_bytes):\n    features = tf.io.parse_single_example(record_bytes, {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'label': tf.io.FixedLenFeature([], tf.int64),\n        'height': tf.io.FixedLenFeature([], tf.int64),\n        'width': tf.io.FixedLenFeature([], tf.int64),\n    })\n    \n    height = features['height']\n    width = features['width']\n\n    image = tf.io.decode_jpeg(features['image'])\n    image = tf.reshape(image, [height, width, N_CHANNELS])\n    \n    # get random square\n    if height > width:\n        offset = tf.random.uniform(shape=(), minval=0, maxval=height-width, dtype=tf.int64)\n        image = tf.slice(image, [offset, 0, 0], [width, width, N_CHANNELS])\n    elif width > height:\n        offset = tf.random.uniform(shape=(), minval=0, maxval=width-height, dtype=tf.int64)\n        image = tf.slice(image, [0, offset, 0], [height, height, N_CHANNELS])\n    else:\n        image = tf.slice(image, [0, 0, 0], [height, width, N_CHANNELS])\n        \n    size = tf.cast(height if height < width else width, tf.float32)\n    \n    # cast label to int8\n    label = tf.cast(features['label'], tf.uint8)\n\n    return image, label, size\n# chance of x in y to return true, used for conditional data augmentation\ndef chance(x, y):\n    return tf.random.uniform(shape=[], minval=0, maxval=y, dtype=tf.int32) < x\ndef augment_image(image, label, size):\n    # random flip image horizontally\n    image = tf.image.random_flip_left_right(image)\n    # random flip image vertically\n    image = tf.image.random_flip_up_down(image)\n    \n    # random transpose\n    if chance(1,2):\n        image = tf.image.transpose(image)\n    \n    # random crop between 75%-100%\n    crop_size = tf.random.uniform(shape=(), minval=size*0.75, maxval=size)\n    image = tf.image.random_crop(image, [crop_size, crop_size, N_CHANNELS])\n    \n    # cast to target dtype and resize\n    image = tf.image.resize(image, [IMG_TARGET_SIZE, IMG_TARGET_SIZE])\n    \n    # normalize according to imagenet mean and std\n    image \/= 255.0\n    image = (image - IMAGENET_MEAN) \/ IMAGENET_STD\n    \n    # one hot encode label\n    label = tf.one_hot(label, N_LABELS, dtype=tf.float32)\n    \n    return image, label\n\ndef read_augment_image(record_bytes):\n    image, label, size = decode_tfrecord_train(record_bytes)\n    image, label = augment_image(image, label, size)\n    \n    return image, label\n\ndef get_mix_img_idx(labels_idxs, idx):\n    idx_candidates = tf.where(labels_idxs != idx)\n    r = tf.random.uniform(minval=0, maxval=len(idx_candidates), shape=[], dtype=tf.int32)\n    idx = tf.gather(idx_candidates, r)\n    idx = tf.cast(idx, tf.int32)\n    idx = tf.squeeze(idx)\n    \n    return idx\n\"\"\"\n# Mixup Implementation\n\"\"\"\ndef mixup(images, labels, alpha=0.40):\n    l = len(images)\n    # get image factors\n    a = tfp.distributions.Beta(alpha, alpha).sample(l)\n    a_label = tf.reshape(a, shape=(l,1))\n    a_label = tf.tile(a_label, [1, N_LABELS])\n    b_label = 1 - a_label\n    \n    a_image = tf.reshape(a, shape=(l,1,1,1))\n    a_image = tf.tile(a_image, [1, IMG_TARGET_SIZE, IMG_TARGET_SIZE ,N_CHANNELS])\n    a_image = tf.cast(a_image, tf.float32)\n    b_image = 1 - a_image\n    \n    # get mixup image indices\n    if l == 2:\n        idxs = tf.constant([1, 0])\n    else:\n        labels_idxs = tf.range(len(labels))\n        idxs = tf.map_fn(lambda idx: get_mix_img_idx(labels_idxs, idx), tf.range(len(labels)))\n    \n    images_mixup = tf.gather(images, idxs)\n    labels_mixup = tf.gather(labels, idxs)\n    \n    # mixup images and labels\n    images =  images * a_image + images_mixup * b_image\n    labels = labels * a_label + labels_mixup * b_label\n    \n    images = tf.cast(images, TARGET_DTYPE)\n    \n    return images, labels\n\"\"\"\n# Cutmix\n\"\"\"\ndef create_cutmix_mask(a):\n    # create random mask size and coordinates\n    r_w = tf.cast(IMG_TARGET_SIZE * tf.math.sqrt(1 - a), tf.int32)\n    r_h = tf.cast(IMG_TARGET_SIZE * tf.math.sqrt(1 - a), tf.int32)\n    \n    if r_w == IMG_TARGET_SIZE:\n        r_x = 0\n    else:\n        r_x = tf.random.uniform(minval=0, maxval=IMG_TARGET_SIZE - r_w, shape=[], dtype=tf.int32)\n        \n    if r_h == IMG_TARGET_SIZE:\n        r_y = 0\n    else:\n        r_y = tf.random.uniform(minval=0, maxval=IMG_TARGET_SIZE - r_w, shape=[], dtype=tf.int32)\n\n    # compute padding sizes\n    pad_left = r_x\n    pad_right = IMG_TARGET_SIZE - (r_x + r_w)\n    pad_top = r_y\n    pad_bottom = IMG_TARGET_SIZE - (r_y + r_h)\n    \n    # create mask_a and mask_b\n    mask_a = tf.ones(shape=[r_w, r_h], dtype=tf.float32)\n    mask_a = tf.pad(mask_a, [[pad_left, pad_right], [pad_top, pad_bottom]], mode='CONSTANT', constant_values=0)\n    mask_a = tf.expand_dims(mask_a, axis=2)\n    \n    return mask_a\n\ndef cutmix(images, labels):\n    l = len(images)\n    a_float32 = tfp.distributions.Beta(1.0, 1.0).sample([l])\n\n    mask_b = tf.map_fn(create_cutmix_mask, a_float32)\n    mask_a = tf.math.abs(mask_b - 1)\n    \n    # images_idxs\n    if l == 2:\n        idxs = tf.constant([1, 0])\n    else:\n        labels_idxs = tf.range(len(labels))\n        idxs = tf.map_fn(lambda idx: get_mix_img_idx(labels_idxs, idx), tf.range(len(labels)))\n    \n    images_cutmix = tf.gather(images, idxs)\n    labels_cutmix = tf.gather(labels, idxs)\n    \n    a_float32_labels = tf.expand_dims(a_float32, axis=1)\n    a_float32_labels = tf.repeat(a_float32_labels, N_LABELS, axis=1)\n    labels_factor = a_float32_labels\n    labels_cutmix_factor = 1 - a_float32_labels\n    \n    # cutmix images and labels\n    images = images * mask_a + images_cutmix * mask_b\n    labels = labels * labels_factor + labels_cutmix * labels_cutmix_factor\n    \n    images = tf.cast(images, TARGET_DTYPE)\n    \n    return images, labels\n\"\"\"\n# Gridmask\n\"\"\"\ndef gridmask(images, labels):\n    l = len(images)\n    \n    d = tf.random.uniform(minval=int(IMG_TARGET_SIZE * (96\/224)), maxval=IMG_TARGET_SIZE, shape=[], dtype=tf.int32)\n    grid = tf.constant([[[0], [1]],[[1], [0]]], dtype=tf.float32)\n    grid = tf.image.resize(grid, [d, d], method='nearest')\n    \n    # 50% chance to rotate mask\n    if chance(1, 2):\n        grid = tf.image.rot90(grid, 1)\n\n    repeats = IMG_TARGET_SIZE \/\/ d + 1\n    grid = tf.tile(grid, multiples=[repeats, repeats, 1])\n    grid = tf.image.random_crop(grid, [IMG_TARGET_SIZE, IMG_TARGET_SIZE, 1])\n    grid = tf.expand_dims(grid, axis=0)\n    grid = tf.tile(grid, multiples=[l, 1, 1, 1])\n\n    images = images * grid\n    images = tf.cast(images, TARGET_DTYPE)\n    \n    return images, labels\ndef augment_batch(images, labels, augmentations=None):\n    if augmentations is None:\n        r = tf.random.uniform(minval=0, maxval=4, shape=[], dtype=tf.int32)\n    else:\n        r = tf.random.uniform(minval=0, maxval=len(augmentations), shape=[], dtype=tf.int32)\n        r = tf.gather(augmentations, r)\n        \n    if r == 0:\n        images = tf.cast(images, TARGET_DTYPE)\n        return images, labels\n    elif r == 1:\n        return mixup(images, labels)\n    elif r == 2:\n        return cutmix(images, labels)\n    elif r == 3:\n        return gridmask(images, labels)\n    else:\n        images = tf.cast(images, TARGET_DTYPE)\n        return images, labels\ndef reshape_batch(images, labels):\n    images = tf.reshape(images, shape=[BATCH_SIZE, IMG_TARGET_SIZE, IMG_TARGET_SIZE, N_CHANNELS])\n    labels = tf.reshape(labels, shape=[BATCH_SIZE, N_LABELS])\n    \n    random_idxs = tf.random.shuffle(tf.range(BATCH_SIZE))\n    images = tf.gather(images, random_idxs)\n    labels = tf.gather(labels, random_idxs)\n    \n    return images, labels\ndef get_train_dataset(bs=BATCH_SIZE, fold=0, augmentations=None):\n    ignore_order = tf.data.Options()\n    ignore_order.experimental_deterministic = False\n    \n    FNAMES_TRAIN_TFRECORDS = tf.io.gfile.glob(f'{GCS_DS_PATH}\/fold_{fold}\/train\/*.tfrecords')\n    train_dataset = tf.data.TFRecordDataset(FNAMES_TRAIN_TFRECORDS, num_parallel_reads=AUTO)\n    train_dataset = train_dataset.with_options(ignore_order)\n    train_dataset = train_dataset.prefetch(AUTO)\n    train_dataset = train_dataset.repeat()\n    train_dataset = train_dataset.map(read_augment_image, num_parallel_calls=AUTO)\n\n    train_dataset = train_dataset.batch(BATCH_SIZE_BASE)\n    train_dataset = train_dataset.map(lambda images, labels: augment_batch(images, labels, augmentations=augmentations), num_parallel_calls=REPLICAS)\n    \n    train_dataset = train_dataset.batch(REPLICAS)\n    train_dataset = train_dataset.map(reshape_batch, num_parallel_calls=1)\n    \n    train_dataset = train_dataset.prefetch(1)\n    \n    return train_dataset\n\ntrain_dataset = get_train_dataset()\ndef benchmark(num_epochs=3, n_steps_per_epoch=10, augmentations=None, bs=BATCH_SIZE):\n    dataset = get_train_dataset(augmentations=augmentations)\n    start_time = time.perf_counter()\n    for epoch_num in range(num_epochs):\n        epoch_start = time.perf_counter()\n        for idx, (images, labels) in enumerate(dataset.take(n_steps_per_epoch)):\n            if idx is 1:\n                print(images.shape, labels.shape)\n            pass\n        print(f'epoch {epoch_num} took: {round(time.perf_counter() - epoch_start, 2)}')\n    print(\"Execution time:\", round(time.perf_counter() - start_time, 2))\n    \nbenchmark(num_epochs=3, augmentations=[2,3])\n\"\"\"\nValidation dataset\n\"\"\"\ndef resize_image(image, label, size):\n    image = tf.image.resize(image, [IMG_TARGET_SIZE, IMG_TARGET_SIZE])\n    \n    return image, label, tf.cast(IMG_TARGET_SIZE, tf.float32)\ndef decode_tfrecord_val(record_bytes):\n    features = tf.io.parse_single_example(record_bytes, {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'label': tf.io.FixedLenFeature([], tf.int64),\n        'height': tf.io.FixedLenFeature([], tf.int64),\n        'width': tf.io.FixedLenFeature([], tf.int64),\n    })\n    \n    height = features['height']\n    width = features['width']\n\n    image = tf.io.decode_jpeg(features['image'])\n    image = tf.reshape(image, [height, width, N_CHANNELS])\n    \n    # get random square\n    if height > width:\n        offset = (height - width) \/\/ 2\n        image = tf.slice(image, [offset, 0, 0], [width, width, N_CHANNELS])\n    elif width > height:\n        offset = (width - height) \/\/ 2\n        image = tf.slice(image, [0, offset, 0], [height, height, N_CHANNELS])\n    else:\n        image = tf.slice(image, [0, 0, 0], [height, width, N_CHANNELS])\n    \n    # resize to target size\n    image = tf.image.resize(image, [IMG_TARGET_SIZE, IMG_TARGET_SIZE])\n    \n    # normalize according to imagenet mean and std\n    image \/= 255.0\n    image = (image - IMAGENET_MEAN) \/ IMAGENET_STD\n    \n    # cast to TARGET_DTYPE\n    image = tf.cast(image, TARGET_DTYPE)\n    \n    label = tf.cast(features['label'], tf.int32)\n    \n    # one hot encode label\n    label = tf.one_hot(label, N_LABELS, dtype=tf.int32)\n    \n    return image, label\ndef get_val_dataset(bs=BATCH_SIZE, fold=0):\n    FNAMES_VAL_TFRECORDS = tf.io.gfile.glob(f'{GCS_DS_PATH}\/fold_{fold}\/val\/*.tfrecords')\n    val_dataset = tf.data.TFRecordDataset(FNAMES_VAL_TFRECORDS, num_parallel_reads=AUTO)\n    val_dataset = val_dataset.prefetch(BATCH_SIZE_VAL)\n    val_dataset = val_dataset.repeat()\n    val_dataset = val_dataset.map(decode_tfrecord_val, num_parallel_calls=AUTO)\n    val_dataset = val_dataset.batch(bs, drop_remainder=True)\n    val_dataset = val_dataset.prefetch(1)\n    \n    return val_dataset\n\nval_dataset = get_val_dataset()\n\"\"\"\n# Lr scheduler\n\"\"\"\ndef lrfn(epoch, bs=BATCH_SIZE, epochs=EPOCHS):\n    # Config\n    LR_START = 1e-6\n    LR_MAX = 2e-4\n    LR_FINAL = 1e-6\n    LR_RAMPUP_EPOCHS = 4\n    LR_SUSTAIN_EPOCHS = 0\n    DECAY_EPOCHS = epochs  - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS - 1\n    LR_EXP_DECAY = (LR_FINAL \/ LR_MAX) ** (1 \/ (EPOCHS - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS - 1))\n\n    if epoch < LR_RAMPUP_EPOCHS: # exponential warmup\n        lr = LR_START + (LR_MAX + LR_START) * (epoch \/ LR_RAMPUP_EPOCHS) ** 2.5\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS: # sustain lr\n        lr = LR_MAX\n    else: # cosine decay\n        epoch_diff = epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS\n        decay_factor = (epoch_diff \/ DECAY_EPOCHS) * math.pi\n        decay_factor= (tf.math.cos(decay_factor).numpy() + 1) \/ 2        \n        lr = LR_FINAL + (LR_MAX - LR_FINAL) * decay_factor\n\n    return lr\n\ndef lrfn2(epoch):\n    \n    LR_START = 0.00001\n    LR_MAX = 0.00005 * strategy.num_replicas_in_sync\n    LR_MIN = 0.00001\n    LR_RAMPUP_EPOCHS = 4\n    LR_SUSTAIN_EPOCHS = 4\n    LR_EXP_DECAY = .8\n\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) \/ LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \n\n\"\"\"\n# Using Binary and Categorical focal loss\n\"\"\"\nfrom tensorflow.keras import backend as K\nimport dill\n\n\ndef binary_focal_loss(gamma=2., alpha=.25):\n    \"\"\"\n    Binary form of focal loss.\n      FL(p_t) = -alpha * (1 - p_t)**gamma * log(p_t)\n      where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.\n    References:\n        https:\/\/arxiv.org\/pdf\/1708.02002.pdf\n    Usage:\n     model.compile(loss=[binary_focal_loss(alpha=.25, gamma=2)], metrics=[\"accuracy\"], optimizer=adam)\n    \"\"\"\n    def binary_focal_loss_fixed(y_true, y_pred):\n        \"\"\"\n        :param y_true: A tensor of the same shape as `y_pred`\n        :param y_pred:  A tensor resulting from a sigmoid\n        :return: Output tensor.\n        \"\"\"\n        pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n        pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n\n        epsilon = K.epsilon()\n        # clip to prevent NaN's and Inf's\n        pt_1 = K.clip(pt_1, epsilon, 1. - epsilon)\n        pt_0 = K.clip(pt_0, epsilon, 1. - epsilon)\n\n        return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \\\n               -K.sum((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\n    return binary_focal_loss_fixed\n\n\ndef categorical_focal_loss(gamma=2., alpha=.25):\n    \"\"\"\n    Softmax version of focal loss.\n           m\n      FL = \u2211  -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)\n          c=1\n      where m = number of classes, c = class and o = observation\n    Parameters:\n      alpha -- the same as weighing factor in balanced cross entropy\n      gamma -- focusing parameter for modulating factor (1-p)\n    Default value:\n      gamma -- 2.0 as mentioned in the paper\n      alpha -- 0.25 as mentioned in the paper\n    References:\n        Official paper: https:\/\/arxiv.org\/pdf\/1708.02002.pdf\n        https:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/backend\/categorical_crossentropy\n    Usage:\n     model.compile(loss=[categorical_focal_loss(alpha=.25, gamma=2)], metrics=[\"accuracy\"], optimizer=adam)\n    \"\"\"\n    def categorical_focal_loss_fixed(y_true, y_pred):\n        \"\"\"\n        :param y_true: A tensor of the same shape as `y_pred`\n        :param y_pred: A tensor resulting from a softmax\n        :return: Output tensor.\n        \"\"\"\n\n        # Scale predictions so that the class probas of each sample sum to 1\n        y_pred \/= K.sum(y_pred, axis=-1, keepdims=True)\n\n        # Clip the prediction value to prevent NaN's and Inf's\n        epsilon = K.epsilon()\n        y_pred = K.clip(y_pred, epsilon, 1. - epsilon)\n        \n        tf.cast(y_pred, tf.float32)\n        tf.cast(y_true, tf.float32)\n        # Calculate Cross Entropy\n        cross_entropy = -y_true * K.log(y_pred)\n        print(f'type of y_pred ---- {type(y_pred)}')\n        print(f'type of y_true ---- {type(y_true)}')\n\n        # Calculate Focal Loss\n        loss = alpha * K.pow(1 - y_pred, gamma) * cross_entropy\n\n        print(f'type of k_sum ---- {type(K.sum(loss, axis=1))}')\n        tf.cast(loss, tf.float32)\n        # Sum the losses in mini_batch\n        return_list = K.sum(loss, axis=1)\n        \n        tf.cast(return_list, tf.float32)\n#         return K.sum(loss, axis=1)\n        return return_list\n\n    return categorical_focal_loss_fixed\n\"\"\"\n# Model\n\"\"\"\ndef get_model(choice):\n    # reset to free memory and training variables\n    tf.keras.backend.clear_session()\n    \n    \n    net = net_choices.get(choice)\n    with strategy.scope():\n        \n        \n        if (choice==0):\n            net = efn.EfficientNetB4(\n                include_top=False,\n                weights='noisy-student',\n                input_shape=(IMG_TARGET_SIZE, IMG_TARGET_SIZE, N_CHANNELS),\n            )\n        elif (choice==1):\n            net = ResNet50(\n                weights='imagenet',\n                include_top=False,\n            )\n        elif (choice==2):\n            net=tf.keras.applications.DenseNet201(\n                weights='imagenet',\n                include_top=False\n\n            )\n        \n        for layer in reversed(net.layers):\n            if isinstance(layer, tf.keras.layers.BatchNormalization):\n                layer.trainable = False\n                \n            else:\n                layer.trainable = True\n        \n        model = tf.keras.Sequential([\n            net,\n            tf.keras.layers.Dropout(0.45),\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dropout(0.45),\n            tf.keras.layers.Dense(N_LABELS, activation='softmax', dtype=tf.float32),\n        ])\n\n        # add metrics\n        metrics = [\n            tf.keras.metrics.CategoricalAccuracy(name='accuracy'),\n            tf.keras.metrics.TopKCategoricalAccuracy(k=2, name='top_2_accuracy'),\n        ]\n\n        optimizer = tf.keras.optimizers.Adam()\n        loss = tf.keras.losses.CategoricalCrossentropy()\n        cat_loss = categorical_focal_loss(gamma=2., alpha=.25)\n        \n        model.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n#         model.summary()\n        return model\n\"\"\"\n# Validation function\n\"\"\"\ndef show_validation_report_per_class(model, dataset, steps, name, bs):\n    print(f'--- {name} REPORT ---')\n    # classification report\n    y = np.ndarray(shape=steps * bs, dtype=np.uint16)\n    y_pred = np.ndarray(shape=steps * bs, dtype=np.uint16)\n    for idx, (images, labels) in tqdm(enumerate(dataset.take(steps)), total=steps):\n        with tf.device('cpu:0'):\n            y[idx*bs:(idx+1)*bs] = np.argmax(labels, axis=1)\n            y_pred[idx*bs:(idx+1)*bs] = np.argmax(model.predict(images).astype(np.float32), axis=1)\n            \n    print(classification_report(y, y_pred))\n    \n    # Confusion matrix\n    fig, ax = plt.subplots(1, 1, figsize=(20, 12))\n    cfn_matrix = confusion_matrix(y, y_pred, labels=range(N_LABELS))\n    cfn_matrix = (cfn_matrix.T \/ cfn_matrix.sum(axis=1)).T\n    df_cm = pd.DataFrame(cfn_matrix, index=np.arange(N_LABELS), columns=np.arange(N_LABELS))\n    ax = sns.heatmap(df_cm, cmap='Blues', annot=True, fmt='.3f', linewidths=.7, annot_kws={'size':14}).set_title(f'{name} CONFUSION MATRIX')\n    plt.xticks(fontsize=16)\n    plt.yticks(fontsize=16)\n    plt.xlabel('PREDICTED', fontsize=24, labelpad=10)\n    plt.ylabel('ACTUAL', fontsize=24, labelpad=10)\n    plt.show()\n\"\"\"\n# Plotting curves function\n\"\"\"\ndef plot_history_metric(history, metric):\n    TRAIN_EPOCHS = len(history.history['loss'])\n    x = np.arange(TRAIN_EPOCHS)\n    x_axis_labels = list(map(str, np.arange(1, TRAIN_EPOCHS+1)))\n    val = 'val' in ''.join(history.history.keys())\n    # summarize history for accuracy\n    plt.figure(figsize=(20, 10))\n    plt.plot(history.history[metric])\n    if val:\n        plt.plot(history.history[f'val_{metric}'])\n    \n    plt.title(f'Model {metric}', fontsize=30)\n    plt.ylabel(metric, fontsize=26)\n    plt.yticks(fontsize=20)\n    plt.xlabel('epoch', fontsize=26)\n    plt.xticks(x, x_axis_labels, fontsize=16) # set tick step to 1 and let x axis start at 1\n    plt.legend(['train'] + ['test'] if val else [], loc='upper left')\n    plt.grid()\n    plt.show()\n\"\"\"\n# Running model\n\"\"\"\nprint(f'TRAINING FOR {EPOCHS} EPOCHS WITH BATCH SIZE {BATCH_SIZE}\\n')\nprint(f'TRAIN IMAGES: {N_TRAIN_IMGS}, VAL IMAGES: {N_VAL_IMGS}\\n')\n\naugmentations_dic = dict({\n    0: 'None',\n    1: 'MixUp',\n    2: 'CutMix',\n    3: 'GridMask',\n})\n\nnet_choices = dict({\n    0: \"Efficientnet\",\n    1: \"ResNet\"\n})\n    \n\n\naugmentations = [2, 3] # only CutMix and GridMask is used\nchoice = 1   # choice can be 0 or 1 according to the dictionary given above\n\n# MEAN_VAL_ACC = []\n# fold = 0\n# epochs = EPOCHS\n\nfor choice in [0, 1, 2]:\n    MEAN_VAL_ACC = []\n    fold = 0\n    epochs = EPOCHS\n    for idx, fold in enumerate(range(N_FOLDS)):\n        # callbacks\n        lr_callback_1 = tf.keras.callbacks.LearningRateScheduler(lambda epoch: lrfn(epoch, epochs=epochs), verbose=1)\n    #     lr_callback_2 = tf.keras.callbacks.LearningRateScheduler(lrfn2, verbose = True)\n    #     show_lr_schedule(epochs=epochs)\n\n        # get the model\n        model = get_model(choice)\n\n        if idx is 0:\n            # model summary\n            model.summary()\n            # compute and variable data types\n            print(f'Compute dtype: {mixed_precision.global_policy().compute_dtype}')\n            print(f'Variable dtype: {mixed_precision.global_policy().variable_dtype}')\n\n        print('\\n')\n        print('*'*25, f'augmentations {augmentations}', '*'*25, '\\n')\n        print(f'fold: {fold}, epochs: {epochs}')\n        print(' AND '.join([augmentations_dic.get(i) for i in augmentations]), '\\n')\n\n        train_dataset = get_train_dataset(bs=BATCH_SIZE, fold=fold, augmentations=augmentations)\n        val_dataset = get_val_dataset(bs=BATCH_SIZE_VAL, fold=fold)\n\n        text_file = f\"profiling_{choice}.txt\"\n        \n        %prun -T text_file history = model.fit(train_dataset,steps_per_epoch = N_TRAIN_IMGS \/\/ BATCH_SIZE,validation_data = val_dataset,validation_steps = N_VAL_IMGS \/\/ BATCH_SIZE_VAL,epochs = epochs,callbacks = [lr_callback_1],verbose=1)\n\n        # add val accuracy to list\n        MEAN_VAL_ACC.append(history.history['val_accuracy'][-1])\n\n        # plot training histories\n        plot_history_metric(history, 'loss')\n        plot_history_metric(history, 'accuracy')\n        plot_history_metric(history, 'top_2_accuracy')\n\n        # show train and validation report\n        show_validation_report_per_class(model, val_dataset, N_VAL_IMGS \/\/ BATCH_SIZE_VAL, 'VALIDATION', BATCH_SIZE_VAL)\n\n        # save the model\n        model.save_weights(f'model_fold_{fold}_weights.h5')\n        model.save(f'model_{net_choices.get(choice)}_fold_{fold}.h5')\n\n        del model, train_dataset, val_dataset\n        gc.collect()\n    \n    ","meta":"{'source': 'AI4Code', 'id': '91d7617750b9a7'}"}
{"id":"70451","text":"import os\nimport cv2\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.optimizers import SGD\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Flatten, Activation, Dropout\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D\nPATH = \"..\/input\/shapes\/\"\nIMG_SIZE = 64\nShapes = [\"circle\", \"square\", \"triangle\", \"star\"]\nLabels = []\nDataset = []\n\n# From kernel: https:\/\/www.kaggle.com\/smeschke\/load-data\nfor shape in Shapes:\n    print(\"Getting data for: \", shape)\n    #iterate through each file in the folder\n    for path in os.listdir(PATH + shape):\n        #add the image to the list of images\n        image = cv2.imread(PATH + shape + '\/' + path)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n        Dataset.append(image)\n        #add an integer to the labels list \n        Labels.append(Shapes.index(shape))\n\nprint(\"\\nDataset Images size:\", len(Dataset))\nprint(\"Image Shape:\", Dataset[0].shape)\nprint(\"Labels size:\", len(Labels))\nsns.countplot(x= Labels)\nprint(\"Count of Star images:\", Labels.count(Shapes.index(\"star\")))\nprint(\"Count of Circles images:\", Labels.count(Shapes.index(\"circle\")))\nprint(\"Count of Squares images:\", Labels.count(Shapes.index(\"square\")))\nprint(\"Count of Triangle images:\", Labels.count(Shapes.index(\"triangle\")))\nindex = np.random.randint(0, len(Dataset) - 1, size= 20)\nplt.figure(figsize=(15,10))\n\nfor i, ind in enumerate(index, 1):\n    img = Dataset[ind]\n    lab = Labels[ind]\n    lab = Shapes[lab]\n    plt.subplot(4, 5, i)\n    plt.title(lab)\n    plt.axis('off')\n    plt.imshow(img)\n# Normalize images\nDataset = np.array(Dataset)\nDataset = Dataset.astype(\"float32\") \/ 255.0\n\n# One hot encode labels\nLabels = np.array(Labels)\nLabels = to_categorical(Labels)\n\n# Split Dataset to train\\test\n(trainX, testX, trainY, testY) = train_test_split(Dataset, Labels, test_size=0.2, random_state=42)\n\nprint(\"X Train shape:\", trainX.shape)\nprint(\"X Test shape:\", testX.shape)\nprint(\"Y Train shape:\", trainY.shape)\nprint(\"Y Test shape:\", testY.shape)\nclass LeNet():\n    @staticmethod\n    def build(numChannels, imgRows, imgCols, numClasses,  pooling= \"max\", activation= \"relu\"):\n        # initialize the model\n        model = Sequential()\n        inputShape = (imgRows, imgCols, numChannels)\n\n        # add first set of layers: Conv -> Activation -> Pool\n        model.add(Conv2D(filters= 6, kernel_size= 5, input_shape= inputShape))\n        model.add(Activation(activation))\n\n        if pooling == \"max\":\n            model.add(MaxPooling2D(pool_size= (2, 2), strides= (2, 2)))\n        else:\n            model.add(AveragePooling2D(pool_size= (2, 2), strides= (2, 2)))\n\n        # add second set of layers: Conv -> Activation -> Pool\n        model.add(Conv2D(filters= 16, kernel_size= 5))\n        model.add(Activation(activation))\n\n        if pooling == \"avg\":\n            model.add(AveragePooling2D(pool_size=(2, 2), strides=(2, 2)))\n        else:\n            model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n        # Flatten -> FC 120 -> Dropout -> Activation\n        model.add(Flatten())\n        model.add(Dense(120))\n        model.add(Dropout(0.5))\n        model.add(Activation(activation))\n\n        # FC 84 -> Dropout -> Activation\n        model.add(Dense(84))\n        model.add(Dropout(0.5))\n        model.add(Activation(activation))\n\n        # FC 4-> Softmax\n        model.add(Dense(numClasses))\n        model.add(Activation(\"softmax\"))\n\n        return model\nBS = 120\nLR = 0.01\nEPOCHS = 10\nopt = SGD(lr= LR)\n# First model with max pooling\nmodel = LeNet.build(3, IMG_SIZE, IMG_SIZE, 4, pooling= \"max\")\nmodel.compile(loss= \"categorical_crossentropy\", optimizer= opt, metrics= [\"accuracy\"])\nmodel.summary()\n# Train model\nH1 = model.fit(trainX, trainY, validation_data= (testX, testY), batch_size= BS,\n              epochs= EPOCHS, verbose=1)\n\n# Evaluate the train and test data\nscores_train = model.evaluate(trainX, trainY, verbose= 1)\nscores_test = model.evaluate(testX, testY, verbose= 1)\n\nprint(\"\\nModel with Max Pool Accuracy on Train Data: %.2f%%\" % (scores_train[1]*100))\nprint(\"Model with Max Pool Accuracy on Test Data: %.2f%%\" % (scores_test[1]*100))\n# Second model with average pooling\nmodel = LeNet.build(3, IMG_SIZE, IMG_SIZE, 4, pooling= \"average\")\nmodel.compile(loss= \"categorical_crossentropy\", optimizer= opt, metrics= [\"accuracy\"])\n\nmodel.summary()\n# Train model\nH2 = model.fit(trainX, trainY, validation_data= (testX, testY), batch_size= BS,\n              epochs= EPOCHS, verbose= 1)\n\n# Evaluate the train and test data\nscores_train = model.evaluate(trainX, trainY, verbose= 1)\nscores_test = model.evaluate(testX, testY, verbose= 1)\n\nprint(\"\\nModel with Average Pool Accuracy on Train Data: %.2f%%\" % (scores_train[1]*100))\nprint(\"Model with Average Pool Accuracy on Test Data: %.2f%%\" % (scores_test[1]*100))\nplt.figure(figsize=(15,5))\nplt.plot(np.arange(0, EPOCHS), H1.history[\"acc\"], label=\"Max Pool Train Acc\")\nplt.plot(np.arange(0, EPOCHS), H1.history[\"val_acc\"], label=\"Max Pool Test Acc\")\nplt.plot(np.arange(0, EPOCHS), H2.history[\"acc\"], label=\"Avg Pool Train Acc\")\nplt.plot(np.arange(0, EPOCHS), H2.history[\"val_acc\"], label=\"Avg Pool Test Acc\")\nplt.title(\"Comparing Models Train\\Test Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Accuracy\")\nplt.legend(loc=\"upper left\")\nplt.figure(figsize=(15,5))\nplt.plot(np.arange(0, EPOCHS), H1.history[\"loss\"], label=\"Max Pool Train Loss\")\nplt.plot(np.arange(0, EPOCHS), H1.history[\"val_loss\"], label=\"Max Pool Test Loss\")\nplt.plot(np.arange(0, EPOCHS), H2.history[\"loss\"], label=\"Avg Pool Train Loss\")\nplt.plot(np.arange(0, EPOCHS), H2.history[\"val_loss\"], label=\"Avg Pool Test Loss\")\nplt.title(\"Comparing Models Train\\Test Loss\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss\")\nplt.legend(loc=\"upper left\")\n\"\"\"\n**Interesting observations**\n1. The train loss for the *max pool* is lower than that of the *average pool*.\n2. The accuracy for *max pool* starts higher than *average pool*.\n3. Final accuracy for *max pool* is still higher than *average pool*.\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '819bce36d23f40'}"}
{"id":"83296","text":"\"\"\"\n# Advanced house price prediction\n## The goal is to predict the Sales Price for the dataset with the given features.\n\"\"\"\n\"\"\"\n # Importing libraries\n\"\"\"\n# 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\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport missingno as msno\nfrom scipy import stats\nfrom scipy.stats import norm\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\n\"\"\"\n### Read data\n\"\"\"\n# Reading the train and test data\ntrain_data = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/train.csv')\ntest_data = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/test.csv')\n#checking out the first lines of my DataFrame with the help of the head() function\ntrain_data.head(n=5)\ntest_data.head(n=5)\n\"\"\"\n# Explore Data\n\"\"\"\n#looking number of rows and columns in the dataset\nprint('Rows and Columns of train data: ',train_data.shape)\nprint('Rows and Columns of test data: ',test_data.shape)\n# 1460 rows and 81 columns in the data\n\"\"\"\n# Performing data analysis on train data set\n\"\"\"\n# Get the overall concise summary of the DataFrame\n# Finding non null values and datatype of each column in train data set\ntrain_data.info()\n# Finding number of missing values in each column of train data set\ntraindata_columns=[]\ntraindata_columns = train_data.columns.values\nfor column in traindata_columns:\n    if(train_data[column].isnull().sum()>0):\n        print(column,train_data[column].isnull().sum())\n## Here i am checking the percentage of missing values present in each feature\n\nfeatures_with_na=[features for features in train_data.columns if train_data[features].isnull().sum()>0]\n#step print the feature name and the percentage of missing values\nfor feature in features_with_na:\n    print(feature, np.round(train_data[feature].isnull().mean(), 4),  ' % missing values.\\n')\n# Checking numerical features\nnumerical_features = [feature for feature in train_data.columns if train_data[feature].dtype != 'O']\nprint(\"Number of numerical features: \", len(numerical_features))\n# finding the number of temporal features\ntemporal_features = [feature for feature in numerical_features if 'Year' in feature or 'Yr' in feature]\nprint(\"Number of temporal features: \", len(temporal_features))\n#Discrete features\ndiscrete_features = [feature for feature in numerical_features if len(train_data[feature].unique()) <=25 \n                     and feature not in temporal_features + ['Id']]\nprint(\"Length of discrete features: \", len(discrete_features))\n#Continous features\ncontinuous_features = [feature for feature in numerical_features if feature not in discrete_features + temporal_features + ['Id']]\nprint(\"Length of continuous features: \", len(continuous_features))\n# Finding the length of categorical features\ncategorial_features = [feature for feature in train_data.columns if train_data[feature].dtypes == 'O']\nprint(categorial_features)\nprint(\"Length of categorical features: \", len(categorial_features))\n#checking percentage of missing values in categorial data\ncategorial_with_nan = [feature for feature in categorial_features if train_data[feature].isnull().sum() > 0]\nprint(categorial_with_nan)\nfor feature in categorial_with_nan:\n    print(\"Feature {}, has {}% missing values in train dataset\", (feature, np.round(train_data[feature].isnull().mean(), 4)))\n\"\"\"\n# Handling the missing values\n\"\"\"\nfor feature in categorial_with_nan:\n    train_data[feature].fillna('Missing', inplace=True)\nprint(numerical_features)\n# Replace the missing values in train set with median\nnumerical_with_nan = [feature for feature in numerical_features if train_data[feature].isnull().sum() > 0]\nfor feature in numerical_with_nan:\n      train_data[feature].fillna(train_data[feature].median(), inplace=True)\ntrain_data.shape\n# Lets see the relation between Fullbath and SalesPrice.\nfig, ax = plt.subplots()\nax.scatter(x = train_data['FullBath'], y = train_data['SalePrice'])\nplt.ylabel('SalePrice', fontsize=15)\nplt.xlabel('FullBath', fontsize=15)\nplt.show()\n\n\"\"\"\n#### It is observed that Sales price and fullbath is negatively correlated\n\"\"\"\n\"\"\"\n#### Temporal Variables (Date-time variables)\nIn the train dataset we have 4 temporal variables\n\"\"\"\ntrain_data[temporal_features].head()\n\"\"\"\n### Lets see the relation between temporal variables and SalesPrice.\n\"\"\"\nfor feature in temporal_features:\n    data = train_data.copy()\n    \n    train_data.groupby(feature)['SalePrice'].median().plot()\n    plt.xlabel(feature)\n    plt.ylabel('SalePrice')\n    plt.title(feature)\n    plt.show()\n\"\"\"\nThe first 3 plots here look fine as the recent the year house is built\/remodling done\/garage build, the higher the SalesPrice. But in the 4th plot Sales Price is decreasing as the Year is increasing. Ideally SalesPrice should increase with every passing year.\n\nSo lets see the relation between the first 3 year variables and the Year Sold\n\"\"\"\nfor feature in temporal_features:\n    data = train_data.copy()\n    \n    if feature != 'YrSold':\n        data[feature] = data['YrSold'] - data[feature]\n        plt.scatter(data[feature], data['SalePrice'])\n        plt.xlabel(feature)\n        plt.ylabel('SalePrice')\n        plt.title(feature)\n        plt.show()\n\"\"\"\nSo above scatter plot indicates:\n\nThe lesser the difference between house YrSold and house year built\/remodling done\/garagebuilt, the higher the Sales Price. When Sales Price is less then it means the house is old with no\/not recent alterations done. So now we also know that \"Houses where faeture values are missing have comparatively low price\", because no remodelling or feature enhancements are done recently.\n\"\"\"\n# finding variables which are highly correlated (both positive and negative) with \u201cSalePrice\u201d.\ncorrmat = train_data.corr()\n\ndef getCorrelatedFeature(corrdata, threshold):\n    feature = []\n    value = []\n    for i , index in enumerate(corrdata.index):\n        if abs(corrdata[index]) > threshold:\n            feature.append(index)\n            value.append(corrdata[index])\n    df2 = pd.DataFrame(data = value, index=feature, columns=['corr value'] )\n    return df2\n\ncorr_df = getCorrelatedFeature(corrmat['SalePrice'], 0.5)\ncorr_df\n# Below features are highly correlated with SalePrice\ncolormap = plt.cm.Blues\ncorrelated_data = train_data[corr_df.index]\nfig, ax = plt.subplots(figsize=(11, 11))\nsns.heatmap(correlated_data.corr(), annot = True, annot_kws={'size': 12}, square=True,cmap=colormap, linecolor='w', linewidths=0.1)\n\"\"\"\nNow, let\u2019s have a look at the features that are highly correlated with the sale price\n\"\"\"\n# The Living area and Sale Price have roughly a linear relationship\nfig, ax = plt.subplots()\nax.scatter(x = train_data['GrLivArea'], y = train_data['SalePrice'])\nplt.ylabel('SalePrice', fontsize=15)\nplt.xlabel('GrLivArea', fontsize=15)\nplt.show()\n#Positive correlation between overallqual and salesprice\nsns.regplot(x='OverallQual', y='SalePrice', data=train_data, ci=None, scatter = False)\nsns.boxplot(y='SalePrice', x = 'GarageArea', data=train_data)\n# The below plot clearly shows a linear relationship between \u2018SalePrice\u2019 and \u2018GarageArea\u2019. The \u2018SalePrice\u2019 increases with an increase in \u2018GarageArea\u2019.\n# plot of \u2018YearBuilt\u2019 shows that the distribution is skewed towards the year 2000 and has a long tail which extends till 1900. The linear relationship between the variables is clearer in cases of recently built houses.\nsns.jointplot(x='SalePrice', y='YearBuilt', data=train_data, kind='reg', dropna = True)\n# TotalBsmtSF is very highly correlated with our target variable SalePrice and\nsns.jointplot(x='SalePrice', y='TotalBsmtSF', data=train_data, kind='scatter')\nsns.relplot(x='SalePrice', y='YearRemodAdd', data=train_data)\n# the YearRemodAdd also has a linear relationship with SalePrice.\n# It is highly negatively correlated with our target variable #Relational plot\nsns.relplot(x='SalePrice', y='FullBath', data=train_data)\n\"\"\"\n'OverallQual', 'GrLivArea' and 'TotalBsmtSF' have strong correlation with 'SalePrice'\n\"\"\"\n\"\"\"\n# Analysing Test data set\n\"\"\"\n# Finding number of missing values for test data in each column\ntest_data_columns=[]\ntest_data_columns = test_data.columns.values\nfor column in test_data_columns:\n    if(test_data[column].isnull().sum()>0):\n        print(column,test_data[column].isnull().sum())\n\"\"\"\n* Filling the missed values in test data set\n\"\"\"\ncategorial_with_nan = [feature for feature in categorial_features if test_data[feature].isnull().sum() > 0]\nfor feature in categorial_with_nan:\n    test_data[feature].fillna('Missing', inplace=True)\nnumerical_with_nan = [feature for feature in numerical_features if feature not in ['SalePrice'] and test_data[feature].isnull().sum() > 0]\nfor feature in numerical_with_nan:\n#     test[feature+'NaN'] = np.where(test[feature].isnull(), 1, 0)\n      test_data[feature].fillna(test_data[feature].median(), inplace=True)\ntest_data.head()\nprint(\"Train Dataset\", train_data.shape)\nprint(\"Test Dataset\", test_data.shape)\ntest_data[temporal_features].head()\n\"\"\"\n* Since the numeric variables are skewed, we will perform log normal distribution.\n\"\"\"\nnum_non_zero_skewed_features_train_set = ['LotFrontage', 'LotArea', '1stFlrSF', 'GrLivArea', 'SalePrice']\ntrain_data[num_non_zero_skewed_features_train_set].head()\nfor feature in num_non_zero_skewed_features_train_set:\n    train_data[feature] = np.log(train_data[feature])\n\"\"\"\nWe may assume the same numeric features will be skewed in test set as well.\n\"\"\"\nnum_non_zero_skewed_features_test_set = ['LotFrontage', 'LotArea', '1stFlrSF', 'GrLivArea']\ntest_data[num_non_zero_skewed_features_test_set].head()\nfor feature in num_non_zero_skewed_features_test_set:\n    test_data[feature] = np.log(test_data[feature])\ntrain_data[num_non_zero_skewed_features_train_set].head()\ntest_data[num_non_zero_skewed_features_test_set].head()\n\"\"\"\n### Creating dummy data\n\"\"\"\ntrain1 = train_data.copy()\ntest1 = test_data.copy()\ndata = pd.concat([train1,test1], axis=0)\ntrain_rows = train1.shape[0]\nprint(data.get('MSZoning'))\nfor feature in categorial_features:\n    dummy = pd.get_dummies(data[feature])\n    for col_name in dummy.columns:\n        dummy.rename(columns={col_name: feature+\"_\"+col_name}, inplace=True)\n    data = pd.concat([data, dummy], axis = 1)\n    data.drop([feature], axis = 1, inplace=True)\ntrain1 = data.iloc[:train_rows, :]\ntest1 = data.iloc[train_rows:, :] \ntrain1.head()\ntest1.head()\nprint(\"Train\",train1.shape)\nprint(\"Test\",test1.shape)\n\"\"\"\n# Scaling\n* Min-Max scaler is used to normalize the input features\/variables\n* now i am scaling data by creating an instance of the scaler and scaling it:\n\"\"\"\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaling_features = [feature for feature in train1.columns if feature not in ['Id', 'SalePrice']]\nscaling_features\ntrain1[scaling_features].head()\nprint(len(scaling_features))\ntrain1[scaling_features].head()\nscaler = MinMaxScaler()\nscaler.fit(train1[scaling_features])\nX_train = scaler.transform(train1[scaling_features])\nX_test = scaler.transform(test1[scaling_features])\nprint(\"Train\", X_train.shape)\nprint(\"Test\", X_test.shape)\ny_train = train1['SalePrice']\nX = pd.concat([train1[['Id','SalePrice']].reset_index(drop=True), pd.DataFrame(X_train, columns = scaling_features)], axis =1)\nprint(X.shape)\nX.head()\n\"\"\"\n# Training data\n\"\"\"\nfrom sklearn.linear_model import ElasticNet, Lasso\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\n# from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom sklearn.metrics import mean_squared_error\nfrom xgboost import XGBRegressor\nfrom lightgbm import LGBMRegressor\nfrom sklearn.svm import SVR\n# Training models using k-fold cross-validation and seeing the performance(RMSE) of all the models in the given dataset.\n# The below function rmse_cv is used to train models of the data created and it returns the RMSE score for the model based on the predictions compared with the actual predictions.\n\nn_folds = 10\ndef rmsle_cv(model):\n    kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(X_train)\n    rmse= np.sqrt(-cross_val_score(model, X_train, y_train, scoring=\"neg_mean_squared_error\", cv = kf))\n    return(rmse)\n\ndef rmsle(y_train, y_pred):\n    return np.sqrt(mean_squared_error(y_train, y_pred))\n\"\"\"\n* Here we are \"regularizing\" models ability to structurally prevent overfitting by imposing a penalty on the coefficients.\n* Below models with the optimal hyperparameters were evaluated by comparing the predictions of each model with validation data. Each model was evaluated using the root mean square error (RMSE) of model predictions, which is a metric for describing the differences between the predicted values and the observed values for SalePrice. lower RMSE scores are better.\n\"\"\"\nlasso = Lasso(alpha =0.0005, random_state=0)\nelasticNet = ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=0)\nkernelRidge = KernelRidge(alpha=0.6, kernel='polynomial', degree=2, coef0=2.5)\nsvr = SVR(C= 20, epsilon= 0.008, gamma=0.0003)\ngradientBoosting = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,\n                                   max_depth=4, max_features='sqrt',\n                                   min_samples_leaf=15, min_samples_split=10, \n                                   loss='huber', random_state =0)\nxgb = XGBRegressor(colsample_bytree=0.4603, gamma=0.0468, \n                             learning_rate=0.05, max_depth=3, \n                             min_child_weight=1.7817, n_estimators=2200,\n                             reg_alpha=0.4640, reg_lambda=0.8571,\n                             subsample=0.5213, silent=1,\n                             random_state =0, nthread = -1)\nlgbm = LGBMRegressor(objective='regression',num_leaves=5,\n                              learning_rate=0.05, n_estimators=720,\n                              max_bin = 55, bagging_fraction = 0.8,\n                              bagging_freq = 5, feature_fraction = 0.2319,\n                              feature_fraction_seed=9, bagging_seed=9,\n                              min_data_in_leaf =6, min_sum_hessian_in_leaf = 11, random_state=0)\nrandomForest = RandomForestRegressor(n_estimators=1200,\n                          max_depth=15,\n                          min_samples_split=5,\n                          min_samples_leaf=5,\n                          max_features=None,\n                          oob_score=True,\n                          random_state=0)\nscores ={}\n# Using Lasso to add the penalty equivalent to the absolute value of the sum of coefficients. This penalty is added to the \n# least square loss function and replaces the squared sum of coefficients from Ridge\nscore = rmsle_cv(lasso)\nprint(\"Lasso:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['lasso'] = (score.mean(), score.std())\nlasso_model = lasso.fit(X_train, y_train)\ny_pred_lasso = lasso_model.predict(X_train)\nrmsle(y_train,y_pred_lasso)\n# Elastic Net is the combination of both Ridge and Lasso. It adds both the sum of squared coefficients \n# and the absolute sum of the coefficients with the ordinary least square function\nscore = rmsle_cv(elasticNet)\nprint(\"ElasticNet:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['elasticNet'] = (score.mean(), score.std())\nelasticNet_model = elasticNet.fit(X_train, y_train)\ny_pred_elasticNet = elasticNet_model.predict(X_train)\nrmsle(y_train,y_pred_elasticNet)\n# Kernel ridge regression is a non-parametric form of ridge regression. The aim is to learn a function in the space induced by the respective kernel \ud835\udc58 \n# by minimizing a squared loss with a squared norm regularization term.\nscore = rmsle_cv(kernelRidge)\nprint(\"KernelRidge:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['kernelRidge'] = (score.mean(), score.std())\nkernelRidge_model = kernelRidge.fit(X_train, y_train)\ny_pred_kernelRidge = kernelRidge_model.predict(X_train)\nrmsle(y_train,y_pred_kernelRidge)\nscore = rmsle_cv(svr)\nprint(\"SVR:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['svr'] = (score.mean(), score.std())\nsvr_model = svr.fit(X_train, y_train)\ny_pred_svr = svr_model.predict(X_train)\nrmsle(y_train,y_pred_svr)\n\"\"\"\n* Using one of the machine learning technique called Gradient boosting algorithm to minimize the loss of the model\n\"\"\"\nscore = rmsle_cv(gradientBoosting)\nprint(\"GradientBoostingRegressor:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['gradientBoosting'] = (score.mean(), score.std())\ngradientBoosting_model = gradientBoosting.fit(X_train, y_train)\ny_pred_gradientBoosting = gradientBoosting_model.predict(X_train)\nrmsle(y_train,y_pred_gradientBoosting)\n\"\"\"\n* XGBRegressor is used to fine tune and retrieve optimal parameters to reduce rmse\n\"\"\"\nscore = rmsle_cv(xgb)\nprint(\"XGBRegressor:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['xgb'] = (score.mean(), score.std())\nxgb_model = xgb.fit(X_train, y_train)\ny_pred_xgb = xgb_model.predict(X_train)\nrmsle(y_train,y_pred_xgb)\nscore = rmsle_cv(lgbm)\nprint(\"LGBMRegressor:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['lgbm'] = (score.mean(), score.std())\nlgbm_model = lgbm.fit(X_train, y_train)\ny_pred_lgbm = lgbm_model.predict(X_train)\nrmsle(y_train,y_pred_lgbm)\n\"\"\"\n* Here Iam using Random Forest regression since the target variable is a continuous real number and also it combines the prediction of multiple decision trees to get more accurate final prediction.\n\"\"\"\nscore = rmsle_cv(randomForest)\nprint(\"RandomForestRegressor:: Mean:\",score.mean(), \" Std:\", score.std())\nscores['randomForest'] = (score.mean(), score.std())\nrandomForest_model = randomForest.fit(X_train, y_train)\ny_pred_randomForest = randomForest_model.predict(X_train)\nrmsle(y_train,y_pred_randomForest)\n\"\"\"\n# Stack Models\nEnsemble model: Here i am combining multiple models using ensemble model,to boost overall accuracy. \nThe combination can be implemented by aggregating the output from each model with two objectives: reducing the model error and maintaining its generalization.\n\"\"\"\ndef ensemble_models(X):\n    return ((0.1 * lasso_model.predict(X)) +\n            (0.1 * elasticNet_model.predict(X)) +\n           (0.1 * kernelRidge_model.predict(X)) +\n           (0.4 * gradientBoosting_model.predict(X)) + \n           (0.1 * xgb_model.predict(X)) +\n           (0.2 * lgbm_model.predict(X)))\naveraged_score = rmsle(y_train, ensemble_models(X_train))\nscores['averaged'] = (averaged_score, 0)\nprint('RMSLE score on train data:', averaged_score)\n\"\"\"\n# Visualize model scores\n* Plotting the predictions for each model\n\"\"\"\nsns.set_style(\"white\")\nfig = plt.figure(figsize=(20, 10))\n\nax = sns.pointplot(x=list(scores.keys()), y=[score for score, _ in scores.values()], markers=['o'], linestyles=['-'])\nfor i, score in enumerate(scores.values()):\n    ax.text(i, score[0] + 0.002, '{:.6f}'.format(score[0]), horizontalalignment='left', size='large', color='black', weight='semibold')\n\nplt.ylabel('Score (RMSE)', size=20, labelpad=12.5)\nplt.xlabel('Model', size=20, labelpad=12.5)\nplt.tick_params(axis='x', labelsize=13.5)\nplt.tick_params(axis='y', labelsize=12.5)\nplt.title('Scores of Models', size=20)\nplt.show()\n\nsubmission = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/sample_submission.csv')\nsubmission.shape\n\"\"\"\n* We have fitted the model and seen its performance. Lets predict the prices for the houses in the actual test data.\n\"\"\"\ntest_predict = np.exp(ensemble_models(X_test))\nprint(test_predict[:5])\n\"\"\"\n# Prediction submission\n\"\"\"\nsub = pd.DataFrame()\nsub['Id'] = test_data['Id']\nsub['SalePrice'] = test_predict\nsub.to_csv('submission.csv',index=False)\nsub1 = pd.read_csv('submission.csv')\nsub1.head()\n\"\"\"\nReference: https:\/\/www.kaggle.com\/charumakhijani\/house-price-prediction-top-6-on-leaderboard\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '98ed134eb1889f'}"}
{"id":"103785","text":"import itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import NullFormatter\nimport pandas as pd\nimport numpy as np\nimport matplotlib.ticker as ticker\nfrom sklearn import preprocessing\n%matplotlib inline\n\"\"\"\n### About dataset\n\"\"\"\n\"\"\"\nThis dataset is about past loans. The __Loan_train.csv__ data set includes details of 346 customers whose loan are already paid off or defaulted. It includes following fields:\n\n| Field          | Description                                                                           |\n|----------------|---------------------------------------------------------------------------------------|\n| Loan_status    | Whether a loan is paid off on in collection                                           |\n| Principal      | Basic principal loan amount at the                                                    |\n| Terms          | Origination terms which can be weekly (7 days), biweekly, and monthly payoff schedule |\n| Effective_date | When the loan got originated and took effects                                         |\n| Due_date       | Since it\u2019s one-time payoff schedule, each loan has one single due date                |\n| Age            | Age of applicant                                                                      |\n| Education      | Education of applicant                                                                |\n| Gender         | The gender of applicant                                                               |\n\"\"\"\n\"\"\"\n### Load Data From CSV File  \n\"\"\"\ndf = pd.read_csv('..\/input\/Loan payments data.csv')\ndf.head()\ndf.shape\n\"\"\"\n### Convert to date time object \n\"\"\"\ndf['due_date'] = pd.to_datetime(df['due_date'])\ndf['effective_date'] = pd.to_datetime(df['effective_date'])\ndf.head()\n\"\"\"\n# Data visualization and pre-processing\n\n\n\"\"\"\ndf['loan_status'].value_counts()\n\"\"\"\n300 people have paid off the loan on time while 100 have gone into collection \n\n\"\"\"\n\"\"\"\nLets plot some columns to underestand data better:\n\"\"\"\n# notice: installing seaborn might takes a few minutes\n!conda install -c anaconda seaborn -y\nimport seaborn as sns\n\nbins = np.linspace(df.Principal.min(), df.Principal.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'Principal', bins=bins, ec=\"k\")\n\ng.axes[-1].legend()\nplt.show()\nbins=np.linspace(df.age.min(), df.age.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'age', bins=bins, ec=\"k\")\n\ng.axes[-1].legend()\nplt.show()\n\"\"\"\n# Pre-processing:  Feature selection\/extraction\n\"\"\"\n\"\"\"\n### Lets look at the day of the week people get the loan \n\"\"\"\ndf['dayofweek'] = df['effective_date'].dt.dayofweek\nbins=np.linspace(df.dayofweek.min(), df.dayofweek.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'dayofweek', bins=bins, ec=\"k\")\ng.axes[-1].legend()\nplt.show()\n\n\"\"\"\nWe see that people who get the loan at the end of the week dont pay it off, so lets use Feature binarization to set a threshold values less then day 4 \n\"\"\"\ndf['weekend']= df['dayofweek'].apply(lambda x: 1 if (x>3)  else 0)\ndf.head()\n\"\"\"\n## Convert Categorical features to numerical values\n\"\"\"\n\"\"\"\nLets look at gender:\n\"\"\"\ndf.groupby(['Gender'])['loan_status'].value_counts(normalize=True)\n\"\"\"\n68 % of female pay there loans while only 58 % of males pay there loan\n\n\"\"\"\n\"\"\"\nLets convert male to 0 and female to 1:\n\n\"\"\"\ndf['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True)\ndf.head()\n\"\"\"\n## One Hot Encoding  \n#### How about education?\n\"\"\"\ndf.groupby(['education'])['loan_status'].value_counts(normalize=True)\n\"\"\"\n#### Feature befor One Hot Encoding\n\"\"\"\ndf[['Principal','terms','age','Gender','education']].head()\n\"\"\"\n#### Use one hot encoding technique to conver categorical varables to binary variables and append them to the feature Data Frame \n\"\"\"\nFeature = df[['Principal','terms','age','Gender']]\nFeature = pd.concat([Feature,pd.get_dummies(df['education'])], axis=1)\nFeature.drop(['Master or Above'], axis = 1,inplace=True)\nFeature.head()\n\n\"\"\"\n### Feature selection\n\"\"\"\n\"\"\"\nLets defind feature sets, X:\n\"\"\"\nX = Feature\nX[0:5]\n\"\"\"\nWhat are our lables?\n\"\"\"\ny = df['loan_status'].values\ny[0:5]\n\"\"\"\n## Normalize Data \n\"\"\"\n\"\"\"\nData Standardization give data zero mean and unit variance (technically should be done after train test split )\n\"\"\"\nX = preprocessing.StandardScaler().fit(X).transform(X)\nX[0:5]\n\"\"\"\n# Classification \n\"\"\"\n# We split the X into train and test to find the best k\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape,  y_train.shape)\nprint ('Test set:', X_test.shape,  y_test.shape)\n# Modeling\nfrom sklearn.neighbors import KNeighborsClassifier\nk = 3\n#Train Model and Predict  \nkNN_model = KNeighborsClassifier(n_neighbors=k).fit(X_train,y_train)\nkNN_model\n# just for sanity chaeck\nyhat = kNN_model.predict(X_test)\nyhat[0:5]\n# Best k\nKs=15\nmean_acc=np.zeros((Ks-1))\nstd_acc=np.zeros((Ks-1))\nConfustionMx=[];\nfor n in range(1,Ks):\n    \n    #Train Model and Predict  \n    kNN_model = KNeighborsClassifier(n_neighbors=n).fit(X_train,y_train)\n    yhat = kNN_model.predict(X_test)\n    \n    \n    mean_acc[n-1]=np.mean(yhat==y_test);\n    \n    std_acc[n-1]=np.std(yhat==y_test)\/np.sqrt(yhat.shape[0])\nmean_acc\n# Building the model again, using k=7\nfrom sklearn.neighbors import KNeighborsClassifier\nk = 7\n#Train Model and Predict  \nkNN_model = KNeighborsClassifier(n_neighbors=k).fit(X_train,y_train)\nkNN_model\n\"\"\"\n# Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nDT_model = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 4)\nDT_model.fit(X_train,y_train)\nDT_model\nyhat = DT_model.predict(X_test)\nyhat\n\"\"\"\n# Support Vector Machine\n\"\"\"\nfrom sklearn import svm\nSVM_model = svm.SVC()\nSVM_model.fit(X_train, y_train) \nyhat = SVM_model.predict(X_test)\nyhat\n\"\"\"\n# Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nLR_model = LogisticRegression(C=0.01).fit(X_train,y_train)\nLR_model\nyhat = LR_model.predict(X_test)\nyhat\n\"\"\"\n# Model Evaluation using Test set\n\"\"\"\nfrom sklearn.metrics import jaccard_similarity_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import log_loss\n\"\"\"\nFirst, download and load the test set:\n\"\"\"\n!wget -O loan_test.csv https:\/\/s3-api.us-geo.objectstorage.softlayer.net\/cf-courses-data\/CognitiveClass\/ML0101ENv3\/labs\/loan_test.csv\n\"\"\"\n### Load Test set for evaluation \n\"\"\"\ntest_df = pd.read_csv('loan_test.csv')\ntest_df.head()\n## Preprocessing\ntest_df['due_date'] = pd.to_datetime(test_df['due_date'])\ntest_df['effective_date'] = pd.to_datetime(test_df['effective_date'])\ntest_df['dayofweek'] = test_df['effective_date'].dt.dayofweek\ntest_df['weekend'] = test_df['dayofweek'].apply(lambda x: 1 if (x>3)  else 0)\ntest_df['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True)\ntest_Feature = test_df[['Principal','terms','age','Gender','weekend']]\ntest_Feature = pd.concat([test_Feature,pd.get_dummies(test_df['education'])], axis=1)\ntest_Feature.drop(['Master or Above'], axis = 1,inplace=True)\ntest_X = preprocessing.StandardScaler().fit(test_Feature).transform(test_Feature)\ntest_X[0:5]\ntest_y = test_df['loan_status'].values\ntest_y[0:5]\nknn_yhat = kNN_model.predict(test_X)\nprint(\"KNN Jaccard index: %.2f\" % jaccard_similarity_score(test_y, knn_yhat))\nprint(\"KNN F1-score: %.2f\" % f1_score(test_y, knn_yhat, average='weighted') )\nDT_yhat = DT_model.predict(test_X)\nprint(\"DT Jaccard index: %.2f\" % jaccard_similarity_score(test_y, DT_yhat))\nprint(\"DT F1-score: %.2f\" % f1_score(test_y, DT_yhat, average='weighted') )\nSVM_yhat = SVM_model.predict(test_X)\nprint(\"SVM Jaccard index: %.2f\" % jaccard_similarity_score(test_y, SVM_yhat))\nprint(\"SVM F1-score: %.2f\" % f1_score(test_y, SVM_yhat, average='weighted') )\nLR_yhat = LR_model.predict(test_X)\nLR_yhat_prob = LR_model.predict_proba(test_X)\nprint(\"LR Jaccard index: %.2f\" % jaccard_similarity_score(test_y, LR_yhat))\nprint(\"LR F1-score: %.2f\" % f1_score(test_y, LR_yhat, average='weighted') )\nprint(\"LR LogLoss: %.2f\" % log_loss(test_y, LR_yhat_prob))\n\"\"\"\n# Report\nYou should be able to report the accuracy of the built model using different evaluation metrics:\n\"\"\"\n\"\"\"\n| Algorithm          | Jaccard | F1-score | LogLoss |\n|--------------------|---------|----------|---------|\n| KNN                | 0.67    | 0.63     | NA      |\n| Decision Tree      | 0.72    | 0.74     | NA      |\n| SVM                | 0.80    | 0.76     | NA      |\n| LogisticRegression | 0.74    | 0.66     | 0.57    |\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'beacea7275b247'}"}
{"id":"84679","text":"# 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\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\n\"\"\"\n# Data Process & Analysis\n\"\"\"\ndf = pd.read_csv(\"..\/input\/bostonhoustingmlnd\/housing.csv\")\ndf.head(10)\ndf.info()\ndf.count()\ntabcorr = df.corr()\ntabcorr\nplt.figure(figsize=(12,12))\nsns.heatmap(abs(tabcorr), cmap=\"coolwarm\")\nsns.clustermap(abs(tabcorr), cmap=\"coolwarm\")\nfrom scipy.cluster import hierarchy as hc\n\ncorr = 1 - df.corr()\ncorr_condensed = hc.distance.squareform(corr)\nlink = hc.linkage(corr_condensed, method='ward')\nplt.figure(figsize=(12,12))\nden = hc.dendrogram(link, labels=df.columns, orientation='left', leaf_font_size=10)\ncorrelations = tabcorr.MEDV\nprint(correlations)\ncorrelations = correlations.drop(['MEDV'],axis=0)\nprint(abs(correlations).sort_values(ascending=False))\n\"\"\"\n# Method 1 - MLR\n\"\"\"\ndf.columns\nX = df.drop(['MEDV'], axis=1)\ny = df.MEDV\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1)\nfrom sklearn.linear_model import LinearRegression\nlm = LinearRegression()\nlm.fit(X_train, y_train)            \ny_pred = lm.predict(X_test)         \nplt.figure(figsize=(12,12))\nplt.scatter(y_test, y_pred)\nplt.plot([y_test.min(),y_test.max()],[y_test.min(),y_test.max()], color='red', linewidth=3)\nplt.xlabel(\"Prix\")\nplt.ylabel(\"Prediction de prix\")\nplt.title(\"Prix reels vs predictions\")\nsns.distplot(y_test-y_pred)\nprint(np.sqrt(mean_squared_error(y_test, y_pred)))\nlm.score(X_test,y_test)\n\"\"\"\n# Method 2 - RFR\n\"\"\"\nX = df.drop(['MEDV'], axis=1)\ny = df.MEDV\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=1)\nfrom sklearn import ensemble\nrf = ensemble.RandomForestRegressor()\nrf.fit(X_train, y_train)\ny_rf = rf.predict(X_test)\nprint(rf.score(X_test,y_test))\nplt.figure(figsize=(12,12))\nplt.scatter(y_test, y_rf)\nplt.plot([y_test.min(),y_test.max()],[y_test.min(),y_test.max()], color='red', linewidth=3)\nplt.xlabel(\"Prix\")\nplt.ylabel(\"Prediction de prix\")\nplt.title(\"Prix reels vs predictions\")\nsns.distplot(y_test-y_rf)\nprint(np.sqrt(mean_squared_error(y_test, y_rf)))\nrf.score(X_test,y_test)\n\"\"\"\n# Method 3 - XGBoost\n\"\"\"\nimport xgboost as XGB\nxgb  = XGB.XGBRegressor()\nxgb.fit(X_train, y_train)\ny_xgb = xgb.predict(X_test)\nplt.figure(figsize=(12,12))\nplt.scatter(y_test, y_xgb)\nplt.plot([y_test.min(),y_test.max()],[y_test.min(),y_test.max()], color='red', linewidth=3)\nplt.xlabel(\"Prix\")\nplt.ylabel(\"Prediction de prix\")\nplt.title(\"Prix reels vs predictions\")\nsns.distplot(y_test-y_xgb)\nprint(np.sqrt(mean_squared_error(y_test, y_xgb)))\nprint(xgb.score(X_test,y_test))","meta":"{'source': 'AI4Code', 'id': '9b50e76327e587'}"}
{"id":"58326","text":"# importing the required packages\nimport pandas as pd \nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport optuna\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom xgboost import XGBRegressor\nimport lightgbm as lgb\nimport catboost as cat\nfrom sklearn.ensemble import RandomForestRegressor \nfrom sklearn.linear_model import LogisticRegression,LinearRegression\nfrom sklearn.model_selection import StratifiedKFold,train_test_split\nfrom sklearn.metrics import roc_curve,auc\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.experimental import enable_iterative_imputer  \nfrom sklearn.impute import IterativeImputer\n# reading the data\ntrain = pd.read_csv('..\/input\/song-popularity-prediction\/train.csv')\ntest = pd.read_csv('..\/input\/song-popularity-prediction\/test.csv')\ntrain = train[~((train['energy'].isnull()) & (train['liveness'].isnull()) ) ].reset_index(drop=True)\ntrain = train[~((train['acousticness'].isnull()) & (train['instrumentalness'].isnull()) ) ].reset_index(drop=True)\ntrain = train[~((train['loudness'].isnull()) & (train['danceability'].isnull()) ) ].reset_index(drop=True)\ntrain = train[~((train['liveness'].isnull()) & (train['danceability'].isnull()) ) ].reset_index(drop=True)\nX = train.drop('song_popularity', axis=1).copy()\ny = train['song_popularity'].copy()\nX.head()\nX.info()\nX.describe(include='all')\n# droping the 'id' column from train and test\nX.drop('id', axis=1, inplace=True)\ntest.drop('id', axis=1, inplace=True)\n\n# replacing the -ve values with 0\nX.acousticness[X.acousticness<0] = 0\nX.instrumentalness[X.instrumentalness<0] = 0\n# pipeline to impute the null value and data transformation\npipeline = Pipeline([\n    ('impute', IterativeImputer(max_iter=10,random_state=42,add_indicator=False)),\n    ('transform_', QuantileTransformer()) \n])\nkf = StratifiedKFold(n_splits=10, shuffle=True, random_state=42) # stratified k fold \n\nx_test = test.copy()\nx = X.copy()\n\n# dataframe to store OOF predictions\nvalid_pred_df = pd.DataFrame()\ntest_pred_df = pd.DataFrame()\ntest_pred_df['id'] = x_test.index\nvalid_pred_df['id'] = X.index\n\nx = pd.DataFrame(pipeline.fit_transform(x),columns=x.columns)\nx_test = pd.DataFrame(data=pipeline.transform(x_test),columns=x.columns)\n\"\"\"\n# Stacking\n\n>> 3 layers of stacking done with 10 fold validation\n\n>> all the hypeparameters were tuned using optuna\n\"\"\"\n\"\"\"\n## L0\n\"\"\"\n\"\"\"\n### XGBoost_0\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\nxgb_params = {'max_depth': 8,\n 'n_estimators': 9600,\n 'learning_rate': 0.010729802684564086,\n 'subsample': 0.2,\n 'colsample_bytree': 0.7,\n 'colsample_bylevel': 0.4,\n 'reg_lambda': 12.411155548777836,\n 'reg_alpha': 0.6685496387870691,\n 'gamma': 0.0001373432756811366}\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(x, y)):\n    x_train, y_train = x.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = x.iloc[idx_valid], y.iloc[idx_valid] \n\n    model = XGBRegressor(**xgb_params, booster= 'gbtree',\n                        objective= 'binary:logistic',\n                        eval_metric = 'auc',\n                        tree_method= 'gpu_hist',\n                        predictor=\"gpu_predictor\",\n                        random_state=0, \n                        use_label_encoder=False,\n                        )\n    \n    model.fit(x_train,y_train,\n            eval_set=[(x_valid,y_valid)],\n            early_stopping_rounds=300,\n            verbose=False)\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(x_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_xgb'})\nvalid_pred_df = valid_pred_df.merge(temp_df,on = 'id')\ntest_pred_df['pred_xgb'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n### LightGBM_0\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\nlgb_params = {'max_depth': 69,\n 'n_estimators': 19600,\n 'learning_rate': 0.09074604767677533,\n 'subsample': 0.9,\n 'colsample_bytree': 0.6000000000000001,\n 'reg_lambda': 10.637736685175083,\n 'reg_alpha': 12.732914587118874,\n 'boosting_type': 'gbdt',\n 'num_leaves': 10}\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(x, y)):\n    x_train, y_train = x.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = x.iloc[idx_valid], y.iloc[idx_valid] \n\n    model = lgb.LGBMRegressor(**lgb_params, \n                               metric= 'auc', \n                               random_state= 0,\n                               )  \n    \n    model.fit(x_train, y_train,\n            eval_set=[(x_valid, y_valid)],\n            early_stopping_rounds=300,\n            verbose=False\n           )\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(x_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_lgb'})\nvalid_pred_df = valid_pred_df.merge(temp_df,on = 'id')\ntest_pred_df['pred_lgb'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\n\"\"\"\n### RandomForest_0\n\"\"\"\n\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\nrf_params = {'max_depth': 54,\n 'n_estimators': 100,\n 'max_features': 'log2',\n 'max_leaf_nodes': 128,\n 'min_samples_split': 3,\n 'min_samples_leaf': 10}\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(x, y)):\n    x_train, y_train = x.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = x.iloc[idx_valid], y.iloc[idx_valid] \n\n    model = RandomForestRegressor(**rf_params, \n                                   random_state= 0,\n                                   n_jobs = -1)  \n    \n    model.fit(x_train, y_train)\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(x_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_rf'})\nvalid_pred_df = valid_pred_df.merge(temp_df,on = 'id')\ntest_pred_df['pred_rf'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n### CatBoost_0\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\ncat_params = {'iterations': 13254,\n 'od_wait': 1174,\n 'learning_rate': 0.010958320637930964,\n 'reg_lambda': 0.01860946566788274,\n 'subsample': 0.5,\n 'random_strength': 5.132433821132644,\n 'depth': 4,\n 'grow_policy': 'Depthwise',\n 'min_child_samples': 16,\n 'border_count': 31,\n 'bagging_temperature': 0.7740200804146857}\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(x, y)):\n    x_train, y_train = x.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = x.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = cat.CatBoostRegressor(\n        random_state=0,\n        eval_metric='AUC',\n        **cat_params,\n    )\n    \n    model.fit(x_train,y_train,\n              eval_set=[(x_valid,y_valid)], \n              early_stopping_rounds=300, \n              verbose=False,\n              use_best_model=True)\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(x_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_cat'})\nvalid_pred_df = valid_pred_df.merge(temp_df,on = 'id')\ntest_pred_df['pred_cat'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n## L1\n\n>> uses the prediction of layer 0 to predict further\n\n>> all the hyperparameters here are differnet from layer 0 \n\"\"\"\n# dataframe to store the OOF prediction\nvalid_pred_1_df = pd.DataFrame()\ntest_pred_1_df = pd.DataFrame()\n\nvalid_pred_1_df['id'] = valid_pred_df['id']\ntest_pred_1_df['id'] = test_pred_df['id']\n\ndf_val = valid_pred_df.drop('id',axis = 1)\ndf_test = test_pred_df.drop('id',axis = 1)\n\ndf_test.columns = df_val.columns\n\"\"\"\n### LogisticRegresion_1\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(df_val, y)):\n    x_train, y_train = df_val.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = df_val.iloc[idx_valid], y.iloc[idx_valid]  \n\n    model = LogisticRegression()\n    \n    model.fit(x_train,y_train)\n    \n    valid_pred = model.predict_proba(x_valid)[:,1]\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict_proba(df_test)[:,1]\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_lr'})\nvalid_pred_1_df = valid_pred_1_df.merge(temp_df,on = 'id')\ntest_pred_1_df['pred_lr'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n### LinearRegression_1\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(df_val, y)):\n    x_train, y_train = df_val.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = df_val.iloc[idx_valid], y.iloc[idx_valid]   \n\n    model = LinearRegression()\n    \n    model.fit(x_train,y_train)\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(df_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_lr_1'})\nvalid_pred_1_df = valid_pred_1_df.merge(temp_df,on = 'id')\ntest_pred_1_df['pred_lr_1'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n### CatBoost_1\n\"\"\"\ntemp_dict = {}\ntemp_df = pd.DataFrame()\nvalid_preds,test_preds,scores = [],[],[]\n\ncat_params = {'iterations': 3990,\n 'od_wait': 632,\n 'learning_rate': 0.05403922778627244,\n 'reg_lambda': 0.2835239884107686,\n 'subsample': 0.8,\n 'random_strength': 3.224920718394828,\n 'depth': 7,\n 'grow_policy': 'SymmetricTree',\n 'min_child_samples': 71,\n 'border_count': 87,\n 'bagging_temperature': 0.8797092144468472}\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(df_val, y)):\n    x_train, y_train = df_val.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = df_val.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = cat.CatBoostRegressor(\n        random_state=0,\n        eval_metric='AUC',\n        **cat_params,\n    )\n    \n    model.fit(x_train,y_train,\n              eval_set=[(x_valid,y_valid)], \n              early_stopping_rounds=300, \n              verbose=False,\n              use_best_model=True)\n    \n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    temp_dict.update(dict(zip(x_valid.index,valid_pred)))\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n    \n    test_pred = model.predict(df_test)\n    test_preds.append(test_pred)\n    \ntemp_df = pd.DataFrame.from_dict(temp_dict,orient='index').reset_index().rename(columns = {'index':'id',0:'valid_cat'})\nvalid_pred_1_df = valid_pred_1_df.merge(temp_df,on = 'id')\ntest_pred_1_df['pred_cat'] = pd.DataFrame(np.column_stack(test_preds).mean(axis = 1))\n\nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n## L2\n\"\"\"\n\"\"\"\n### LinearRegression_2\n\"\"\"\nvalid_preds,test_preds,scores = [],[],[]\n\ndf_val_final = valid_pred_1_df.drop(['id'],axis = 1)\ndf_test_final = test_pred_1_df.drop(['id'],axis = 1)\ndf_test_final.columns = df_val_final.columns\n\nfor fold, (idx_train, idx_valid) in enumerate(kf.split(df_val_final, y)):\n    x_train, y_train = df_val_final.iloc[idx_train], y.iloc[idx_train]\n    x_valid, y_valid = df_val_final.iloc[idx_valid], y.iloc[idx_valid]\n    \n    model = LinearRegression()\n    \n    model.fit(x_train,y_train)\n\n    valid_pred = model.predict(x_valid)\n    valid_preds.append(valid_pred)\n\n    fpr, tpr, _ = roc_curve(y_valid, valid_pred)\n    score = auc(fpr, tpr)\n    scores.append(score)\n    \n    print(f\"Fold: {fold + 1} Score: {score}\")\n    print('--'*25)\n\n    test_pred = model.predict(df_test_final)\n    test_preds.append(test_pred)\n    \nprint(f\"Overall Validation Score : {np.mean(scores)}\")\n\"\"\"\n# Final submission\n\"\"\"\n# saving the submission\nsubmission = pd.read_csv('..\/input\/song-popularity-prediction\/sample_submission.csv')\npredictions = np.mean(np.column_stack(test_preds),axis=1)\nsubmission['song_popularity'] = predictions\nsubmission.to_csv('submission.csv', index=False)\nsubmission","meta":"{'source': 'AI4Code', 'id': '6bb98a9e28130e'}"}
{"id":"52200","text":"\"\"\"\n# Data Scientists in Poland\n## 1. Imports\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\npd.set_option('display.max_colwidth', -1)\npd.set_option('display.max_columns', None) \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## 2. Read data and show column descriptions\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/kaggle-survey-2018\/multipleChoiceResponses.csv')\ndf[:2]\n\"\"\"\n## 3. Code for simplifying DataFrame and extracting significant data about Data Scientists\n\nThe following columns are extracted here:\n- `education_degree` - the highest level of education,\n- `current_role` - the current role of a person,\n- `experience_years` - years of experience in the current role,\n- `salary_range_usd` - current yearly compensation in USD,\n- `apply_ml_in_new_areas` - True if a person applies Machine Learning in new areas,\n- `do_research_in_ml` - True if a person is doing a research in Machine Learning,\n- `lower_bound_salary_usd` - lower bound of current yearly compensation in USD,\n- `upper_bound_salary_usd` - upper bound of current yearly compensation in USD.\n\"\"\"\ndef salary_range_str_to_ranges(salary):\n    if '-' not in str(salary):\n        return None, None\n    lower, upper = salary.split(',')[0].split('-')\n    return int(lower) * 1000, int(upper) * 1000\n\ndef simplify_data_scientist_data(df):\n    df = df[['Q4', 'Q6', 'Q8', 'Q9', 'Q11_Part_4', 'Q11_Part_5', 'Q16_Part_1']].rename(columns=dict(\n        Q4='education_degree', \n        Q6='current_role', \n        Q8='experience_years', \n        Q9='salary_range_usd', \n        Q11_Part_4='apply_ml_in_new_areas', \n        Q11_Part_5='do_research_in_ml', \n        Q16_Part_1='uses_python'\n    ))\n    df['lower_bound_salary_usd'], df['upper_bound_salary_usd'] = zip(*df['salary_range_usd'].map(salary_range_str_to_ranges))\n    df['lower_bound_salary_usd'] = df['lower_bound_salary_usd'].astype(float)\n    df['upper_bound_salary_usd'] = df['upper_bound_salary_usd'].astype(float)\n    df['apply_ml_in_new_areas'] = df['apply_ml_in_new_areas'].map(pd.notnull)\n    df['do_research_in_ml'] = df['do_research_in_ml'].map(pd.notnull)\n    df = df[pd.notnull(df.lower_bound_salary_usd)]\n    return df[df.current_role == 'Data Scientist']\n\"\"\"\n## 4. Read data about Data Scientist from Poland, US and the whole world\n\"\"\"\npl_df = simplify_data_scientist_data(df[df.Q3 == 'Poland'])\npl_df\nus_df = simplify_data_scientist_data(df[df.Q3 == 'United States of America'])\nus_df\nworld_df = simplify_data_scientist_data(df)\nworld_df\n\"\"\"\n## 5. Check salary bounds for Data Scientist in Poland with experience in ranges 4-5, 5-10 years\n\nWe take here into account people which are working on ML (not only on data analysis) and they are applying ML in a new areas or\/and doing research in ML.\n\nThe range for salary is 40-70K USD, but we have only for 3 responses, so it's hard to derive any salary distribution based on it:\n\"\"\"\npl_df[\n    (pl_df.experience_years == '4-5') | (pl_df.experience_years == '5-10')\n]\n\"\"\"\nBecause of a small coverage for Poland, we are going to check salaries in US where there are 118 responses with such experience:\n\"\"\"\nlen(us_df[\n    (us_df.apply_ml_in_new_areas == True) | (us_df.do_research_in_ml == True)\n][\n    (us_df.experience_years == '4-5') | (us_df.experience_years == '5-10')\n])\n\"\"\"\nThe salary ranges in US for DS with such experience is 132-167K USD. \n\"\"\"\nus_df[\n        (us_df.apply_ml_in_new_areas == True) | (us_df.do_research_in_ml == True)\n    ][\n        (us_df.experience_years == '4-5') | (us_df.experience_years == '5-10')\n    ][['lower_bound_salary_usd', 'upper_bound_salary_usd']].mean()\n\"\"\"\nTaking into account the cost of living indexes for US and Poland (100 vs 50.9 respectively), we can derive that DS with the same experience in Poland may expect 67-85K.\n\"\"\"\n\"\"\"\n## 6. Check distributions of experience in Poland and in the world\n\nAccording to the below chart it seems there are less people in Poland which have at least 4 years of experience as Data Scientist.\n\"\"\"\npd_stats = pd.DataFrame(dict(\n    poland=pl_df.groupby('experience_years').size(),\n    world=world_df.groupby('experience_years').size(),\n)).fillna(0)\npd_stats = pd_stats.iloc[pd_stats.index.str.extract('(\\d+)', expand=False).astype(int).argsort()]\n(pd_stats \/ pd_stats.sum(axis=0) * 100).plot(kind='bar')","meta":"{'source': 'AI4Code', 'id': '60126d0c681e1c'}"}
{"id":"53986","text":"\"\"\"\n# Problem Statement\nCrime is increasing considerably day by day. Crime is among the main issues which is growing continuously in intensity and complexity. Crime patterns are changing constantly because of which it is difficult to explain behaviours in crime patterns.\n\nSo it becomes a difficult challenge for crime analysts to analyse such voluminous crime data without any computational support. A powerful system for predicting crimes is required in place of traditional crime analysis because traditional methods cannot be applied when crime data is high dimensional and complex queries are to be processed. Therefore a crime prediction and analysis tool were needed for identifying crime patterns effectively.\n\"\"\"\n\"\"\"\n# Data Exploration\nIn this section, We will load data and see it's content.\n\n## 1. Loading the data files\n\"\"\"\n# import pandas\nimport pandas as pd\n\n# load train and test as dataframes\ntrain_df = pd.read_csv(\"..\/input\/crime-prediction\/train.csv\",parse_dates=['Dates'],error_bad_lines=False)\ntest_df = pd.read_csv(\"..\/input\/crime-prediction\/test.csv\",parse_dates=['Dates'],error_bad_lines=False)\ntrain_df.isnull().any()\n\n\"\"\"\n## 2. Showing data\n\"\"\"\n# import display function from ipython\nfrom IPython.display import display, HTML\n\n# display the first rows of each dataset\ndisplay(train_df.head())\nprint(\"train shape: {}\".format(train_df.shape))\ndisplay(test_df.head())\nprint(\"test shape: {}\".format(test_df.shape))\n\"\"\"\n* As shown above, The test dataset doesn't contain 3 columns {Category, Descript, Resolution} as the category column is the target column to found in the test set.\n* The test set will be used for testing only at the end of project\n* Training data will be divided into training and testing -Validation- sets to train the models later.\n\"\"\"\n\"\"\"\n----\n# Data visualizing and preprocessing\nIn this section, We will visualize data and remove unnecessary data.\n\"\"\"\n\"\"\"\n## 1. Removing redundant features\nAs shown above, there exist 2 columns -features- that are considered as redundancy. `Descript` and `Resolution` are these 2 columns as they don't exist in the testing values and also not a label required from the models, so they should be removed.\n\"\"\"\ntrain_df = train_df.drop(columns=['Descript', 'Resolution'])\ntrain_df.head()\n\"\"\"\n## 2. Removing redundant rows\nNow, lets visualize location information\n\"\"\"\n# lets see the statistics summary of locations\nlons = train_df['X'] # longitudes \nlats = train_df['Y'] # latitudes\n\nprint(\"Longitudes summary:\")\nprint(lons.describe())\nprint(\"\\nLatitudes summary:\")\nprint(lats.describe())\n\"\"\"\n-----------------------\n**Observation:**\n* longitudes are between [-122.52, -120.5], each value different slightly from others\n* latitudes are between [37.708, 90]\n* here as shown there exist some bad values -i.e. close to 90-, the reasons that this is bad that \n    * first, san fransisco latitudes are between [37.707, 37.83269] , reference: [google maps](https:\/\/www.google.com.eg\/maps\/place\/San+Francisco,+CA,+USA\/@37.7407396,-122.4303937,12z\/data=!4m5!3m4!1s0x80859a6d00690021:0x4a501367f076adff!8m2!3d37.7749295!4d-122.4194155)\n    * second as shown in the statistics that the most values are close to 37.7\n    * Also in longitudes, san fransisco longitudes are between [-122.517652, -122.3275], from google maps\n\nNow, to demonstrate the locations, let's plot them using scatter plot\n\"\"\"\n# eliminate rows with latitudes out of San Francisco range\ntrain_df = train_df.drop(train_df[(train_df['Y'] > 37.84) | (train_df['Y'] < 37.7)].index)\n# eliminate rows with longitudes out of San Francisco range\ntrain_df = train_df.drop(train_df[((train_df['X'] > -122.32) | (train_df['X'] < -122.52))].index)\ntrain_df.describe()\n\n#from shapely.geometry import  Point\n#import geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\n#from sklearn.impute import SimpleImputer\n#from sklearn.preprocessing import LabelEncoder\n#from sklearn.model_selection import train_test_split\nimport seaborn as sns\nfrom matplotlib import cm\n#import urllib.request\n#import shutil\n#import zipfile\n#import os\n#import re\n#import contextily as ctx\n#import geoplot as gplt\n#import lightgbm as lgb\n#import eli5\n#from eli5.sklearn import PermutationImportance\n#from lightgbm import LGBMClassifier\nfrom matplotlib import pyplot as plt\n#from pdpbox import pdp, get_dataset, info_plots\n#import shap\n\"\"\"\n## 3. Visualize according to locations\n\"\"\"\nnew_lons = train_df['X'] # longitudes \nnew_lats = train_df['Y'] # latitudes\n\n# scatter plot for lons vs lats\nplt.scatter(new_lons, new_lats)\nplt.xlabel('lons')\nplt.ylabel('lats')\nplt.show()\n\n# histogram plot for lons and lats\nplt.hist(new_lons)\nplt.xlabel('lons')\nplt.ylabel('ocurrance number')\nplt.show()\nplt.hist(new_lats)\nplt.xlabel('lats')\nplt.ylabel('ocurrance number')\nplt.show()\n\"\"\"\n**Observation:**  the most crimes are in the location of longitude = [-122.44, -122.40] and latitude = [37.76, 37.80]\n\"\"\"\n\"\"\"\n### Dates & Day of the week  \nThese variables are distributed uniformly between 1\/1\/2003 to 5\/13\/2015 (and Monday to Sunday) and split between the training and the testing dataset as mentioned before. We did not notice any anomalies on these variables.  \nThe median frequency of incidents is 389 per day with a standard deviation of 48.51.\n\"\"\"\n#import seaborn as sns\ncol = sns.color_palette()\n\ntrain_df['Date'] = train_df.Dates.dt.date\ntrain_df['Hour'] = train_df.Dates.dt.hour\n\nplt.figure(figsize=(10, 6))\ndata = train_df.groupby('Date').count().iloc[:, 0]\nsns.kdeplot(data=data, shade=True)\nplt.axvline(x=data.median(), ymax=0.95, linestyle='--', color=col[1])\nplt.annotate(\n    'Median: ' + str(data.median()),\n    xy=(data.median(), 0.004),\n    xytext=(200, 0.005),\n    arrowprops=dict(arrowstyle='->', color=col[1], shrinkB=10))\nplt.title(\n    'Distribution of number of incidents per day', fontdict={'fontsize': 16})\nplt.xlabel('Incidents')\nplt.ylabel('Density')\nplt.legend().remove()\nplt.show()\n\"\"\"\nAlso, there is no significant deviation of incidents frequency throughout the week. Thus we do not expect this variable to play a significant role in the prediction.\n\"\"\"\ndata = train_df.groupby('DayOfWeek').count().iloc[:, 0]\ndata = data.reindex([\n    'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',\n    'Sunday'\n])\n\nplt.figure(figsize=(10, 5))\nwith sns.axes_style(\"whitegrid\"):\n    ax = sns.barplot(\n        data.index, (data.values \/ data.values.sum()) * 100,\n        orient='v',\n        palette=cm.ScalarMappable(cmap='Reds').to_rgba(data.values))\n\nplt.title('Incidents per Weekday', fontdict={'fontsize': 16})\nplt.xlabel('Weekday')\nplt.ylabel('Incidents (%)')\n\nplt.show()\n\"\"\"\n### Category  \nThere are 39 discrete categories that the police department file the incidents with the most common being Larceny\/Theft (19.91%), Non\/Criminal (10.50%), and Assault(8.77%).\n\"\"\"\ndata = train_df.groupby('Category').count().iloc[:, 0].sort_values(\n    ascending=False)\ndata = data.reindex(np.append(np.delete(data.index, 1), 'OTHER OFFENSES'))\n\nplt.figure(figsize=(10, 10))\nwith sns.axes_style(\"whitegrid\"):\n    ax = sns.barplot(\n        (data.values \/ data.values.sum()) * 100,\n        data.index,\n        orient='h',\n        palette=\"Reds_r\")\n\nplt.title('Incidents per Crime Category', fontdict={'fontsize': 16})\nplt.xlabel('Incidents (%)')\n\nplt.show()\n\"\"\"\n---\nFinding number of occurances of for each category in data\n\"\"\"\nfrom collections import Counter\n\ndef printCategoriesOccurrence():\n    \n    categories = train_df['Category']\n    # count the number of occurances for each category\n    occurances = Counter(categories)\n    sorted_occ = sorted(occurances.items(), key=lambda pair: pair[1], reverse=True)\n    for key, value in sorted_occ:\n        print(key, value)\n    return sorted_occ\n        \nsorted_occ = printCategoriesOccurrence()\n\"\"\"\n**Observation:**\nThe most committed crime in San Francisco is the LARCENY\/THEFT. TREA is the least.\n\"\"\"\n\"\"\"\n## 5. Data preprocessing\n\"\"\"\n\"\"\"\n**Enhanceing data imbalancing:**\nNow as shown above, The data is imbalanced and some features has very low number of contributions in data existance. And to enhance imbalanced data we can replicate the data with low contributions and give them more weights in training.\n\nHere we will replicate the data that has less than 1000 occurances to be 1000. Later we will give them more weights while training.\n\"\"\"\nimport math\n# if category size < 1000, duplicate it to be = 1000\nfor key,value in sorted_occ:\n    if value<1000:\n        \n        temp = train_df[train_df['Category'] == key]\n        train_df = train_df.append([temp]*int(math.ceil((1000-value)\/float(value))), ignore_index=True)\n\nsorted_occ = printCategoriesOccurrence()\n\"\"\"\n### Data Encoding\n\"\"\"\n# spliting train data into target and other features\ntarget = train_df['Category']\ndata = train_df.drop(columns=['Category'])\n\"\"\"\n4 features from the data given are not numbers, so we need to convert them into numbers in order to be able to train the models on them. These features are:\n* Dates\n* DayOfWeek\n* PdDistrict\n* Address\n\nWe can use label Encoding and 1-hot encoding. 1-hot encoding may produce very high numbers of dimensions due to the many data labeles in each feature, but it is better due to the problem with label encoding is that it assumes higher the categorical value, better the category which produce more errors.\n\nSo let's use one-hot encoding with the features with little unique values and use the label encoding with the features with very high unique values\n\n\"\"\"\nfeatures = ['Dates', 'DayOfWeek', 'PdDistrict', 'Address']\nfor feature in features:\n    print(\"feature: {}    unique_size: {}\".format(feature ,len(data[feature].unique())))\n\"\"\"\nAs shown above, `DayOfWeek` and `PdDistrict` can one-hot encoded. But `Address`, `Dates` should be encoded using label encoding.\n\nFor `Dates`, lets neglect the miniutes and seconds of each date as this will not affect greatly on our predictions but on the contrary it may produce good environment for overfitting, so let's convert `Dates` by our hand to integers then convert `Address` using `cat.codes` tool.\n\n### 5.1 Label Encoding\n\"\"\"\ndata.head()\nprint(str(data['Dates'][0])[:-6])\n# convert given list of dates it will trim seconds, minutes and return result\ndef trimMinAndSecFromDates(dates):\n    result = []\n    for date in dates:\n        result.append(str(date)[:-6])\n    return result\n\n# trim minutes and seconds from dates\ndata['Dates'] = trimMinAndSecFromDates(data['Dates'])\n\n# encode Dates using label encoding\ndata['Dates'] = data['Dates'].astype('category')\ndata['Dates_int'] = data['Dates'].cat.codes\n\n# encode Address using label encoding\ndata['Address'] = data['Address'].astype('category')\ndata['Address_int'] = data['Address'].cat.codes\n\ndata.head()\n\"\"\"\nNow let's drop the `Dates` and `Address` cols as they are now useless.\n\"\"\"\ndata.drop(columns=['Dates', 'Address'], inplace=True)\ndata.head()\n\"\"\"\n### 5.2 One-Hot Encoding\nNow let's one hot encode the `DayOfWeek` and `PdDistrict` using pandas.get_dummies()\n\"\"\"\n# get dummies for each feature\nDayOfWeek_dummies = pd.get_dummies(data['DayOfWeek'])\nPdDistrict_dummies = pd.get_dummies(data['PdDistrict'])\n\n# join dummies to the original dataframe\ndata = data.join(DayOfWeek_dummies)\ndata = data.join(PdDistrict_dummies)\n\ndata.head()\n\"\"\"\nNow let's drop the `DayOfWeek` and `PdDistrict` cols as they are now useless.\n\"\"\"\n\ndata.drop(columns=['DayOfWeek', 'PdDistrict'], inplace=True)\nprint(\"data size =\",len(data))\ndata.head()\n\ndata.drop(columns=['Date', 'Hour'], inplace=True)\n\nimport numpy as np\ndata[~data.isin([np.nan, np.inf, -np.inf]).any(1)].astype(np.float64)\ndata.replace([np.inf, -np.inf], np.nan)\ndata.isnull().any()\ndata.dropna()\ndata.columns\n\"\"\"\n**Observation:** Now the training data are ready to be used for our models with 21 dimensions and 885669 samples to be traind on\n\"\"\"\ndata.shape\n\"\"\"\n## 5. Data splitting\nsplit training data into train set with size 80% and test set with size 20% - i.e. validation set.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test =  train_test_split(data, target, test_size=0.2, random_state=0, stratify=target)\nprint(\"train size: {}, test size: {}\".format(X_train.shape[0], X_test.shape[0]))\n\ntarget\n\"\"\"\n\n--------------\n# Models Implementation\n\"\"\"\n\"\"\"\nWe are going to implement various models and train them on our data and comapre their performance later using using mult-class logarithmec loss.\n\"\"\"\n\"\"\"\n## 1. Implementing Models\nIn this section, we will train various model on data.\n\"\"\"\ndata.isnull().any()\n\n\"\"\"\n### Training pipline\nNow, we will train various learners, so we will make a pipline -i.e function- to call it in training the models instead of repeating it with each model. \n\nThe function returns a result dict which contains the train time, fbeta score and log loss of all samples in train data.\n\n**Hint:** We shouldn't use accuracy here as the data is imbalanced.\n\"\"\"\nfrom sklearn.metrics import log_loss, fbeta_score\nfrom time import time\n\n# train function takes learner, the train data and target\ndef train_test_pipeline(learner, X_train, y_train, X_test, y_test):\n    \n    results = {}\n    \n    # training learner\n    start = time()\n    learner.fit(X_train, y_train)\n    end = time()\n    results['train_time'] = end - start\n    \n     # remove missed classes after fitting for logloss\n    for category in list(set(target) - set(learner.classes_)):\n        X_train = X_train.drop(y_train[y_train == category].index)\n        y_train = y_train[y_train != category]\n        X_test = X_test.drop(y_test[y_test == category].index)\n        y_test = y_test[y_test != category]\n    # predict samples in training set\n    predictions = learner.predict(X_train)\n    predictions_proba = learner.predict_proba(X_train)\n    \n    # calculate fbeta and log loss\n    results['fscore'] = fbeta_score(y_train, predictions, beta=.5, average='micro')\n    results['logloss'] = log_loss(y_train, predictions_proba)\n    \n    # predict testing samples and time of prediction\n    start = time()\n    predictions = learner.predict(X_test)\n    predictions_proba = learner.predict_proba(X_test)\n    end = time()\n    results['test_time'] = end - start\n    \n    # calculate fbeta and log loss for testing set\n    results['fscore_test'] = fbeta_score(y_test, predictions, beta=.5, average='micro')\n    results['logloss_test'] = log_loss(y_test, predictions_proba)\n    \n    \n    print (\"{} trained\".format(learner.__class__.__name__))\n    \n    return results\n\n# do train_test_pipeline then visualize resutls for given models on first n samples and test on first m\n# returns predictions proba for last model in given list - this will be used for 1 model only -\ndef train_test_models(models, names=None, n=len(y_train), m=len(y_test)):\n    results = {}\n    i = 0\n    for model in models:\n        if not names:\n            model_name = model.__class__.__name__\n        else:\n            model_name = names[i]\n            i += 1\n        results[model_name] = train_test_pipeline(model, X_train[:n], y_train[:n], X_test[:m], y_test[:m])\n\n    # print results\n    for model in results:\n        model_res = results[model]\n        print (\"model: {}\".format(model))\n        print (\"fscore:\\t\\t{}\\nlogloss:\\t{}\\ntrain time:\\t{}\".format(model_res['fscore'], model_res['logloss'], model_res['train_time']))\n        print (\"fscore_test:\\t\\t{}\\nlogloss_test:\\t{}\\ntest time:\\t{}\".format(model_res['fscore_test'], model_res['logloss_test'], model_res['test_time']))\n\n    # visualize the results    \n    visualize(results, random_results)\n\"\"\"\n### Visualization\nvisualize training and testing results\n\"\"\"\nimport matplotlib.pyplot as plt\ndef visualize(results, random_results):\n    bar_width = 0.3\n    fig, ax = plt.subplots(6,1,figsize = (12,32))\n    for j, metric in enumerate(['train_time', 'fscore', 'logloss', 'test_time', 'fscore_test', 'logloss_test']):\n        ax[j].set_xlabel(\"Learners\")\n        ax[j].set_ylabel(metric)\n        ax[j].set_title(metric)\n        for k, learner in enumerate(results.keys()):\n            ax[j].bar(learner, results[learner][metric], width=bar_width)\n    \n    # add horizontal line for random model results\n    ax[0].axhline(y=random_results['train_time'], linestyle='dashed')\n    ax[1].axhline(y=random_results['fscore'], linestyle='dashed')\n    ax[2].axhline(y=random_results['logloss'], linestyle='dashed')  \n    ax[3].axhline(y=random_results['test_time'], linestyle='dashed')\n    ax[4].axhline(y=random_results['fscore_test'], linestyle='dashed')\n    ax[5].axhline(y=random_results['logloss_test'], linestyle='dashed') \n\"\"\"\n### 1.1 Naive Random Predictor\nRandom predictor which always predict the category randomly.\n\"\"\"\nimport random\nclass random_model:\n \n    def __init__(self, categories):\n        self.categories = categories\n        self.classes_ = categories\n\n    # always return a random value from categories\n    def __getRandomValue(self): return random.choice(self.categories) \n    \n    # no need for fit here\n    def fit(self, X_train, y_train): pass\n    \n    def predict(self, X):\n        result = [[] for i in range(len(X))]\n        for j in range(len(X)):\n            result[j] = self.__getRandomValue()\n        return result\n        \n    def predict_proba(self, X):\n        result = [[] for i in range(len(X))]\n        for j in range(len(X)):\n            row = [0.0]*len(self.categories)\n            prediction = self.__getRandomValue()\n            for i in range(len(self.categories)): \n                if(self.categories[i] == prediction):\n                    row[i] = 1.0\n                    break\n            result[j] = row\n        return result\n\"\"\"\n### 1.2 other models\nIn this section, We will train other models using training pipline that we implemented previously. The models to use are:\n* KNNeighbors\n* DecisionTree\n* ExtraTrees\n* Neural network MLP\n* Support vector machine\n* xgboost\n\"\"\"\n\"\"\"\n#### 1.2.1 Initializing models\nHere, we enhance imbalanced data more by putting the `class_weight` parameter = `balanced` which mean that the weights will be automatically adjusted inversely proportional to class frequencies in the input data as `n_samples \/ (n_classes * np.bincount(y))`\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC \nfrom xgboost import XGBClassifier\n\n# initializing models\nmodel_KNN = KNeighborsClassifier(n_jobs=-1, weights='distance')\nmodel_tree = DecisionTreeClassifier(class_weight='balanced')\nmodel_extraTrees = ExtraTreesClassifier(n_jobs=-1, class_weight='balanced')\nmodel_NN = MLPClassifier(learning_rate='invscaling', shuffle=True)\nmodel_SVC = SVC(probability=True, class_weight='balanced') # One-to-One\nmodel_XGB = XGBClassifier(one_drop=1)\n\"\"\"\n#### 1.2.1 Initializing models\nHere, we enhance imbalanced data more by putting the `class_weight` parameter = `balanced` which mean that the weights will be automatically adjusted inversely proportional to class frequencies in the input data as `n_samples \/ (n_classes * np.bincount(y))`\n\"\"\"\nmodel_random = random_model(categories=target.unique())\nrandom_results = train_test_pipeline(model_random, X_train, y_train, X_test, y_test)\n\"\"\"\n#### 1.2.3 train and visualize other models with small number of samples\n\"\"\"\nmodels = [model_KNN, model_tree, model_extraTrees, model_NN, model_SVC, model_XGB]\ntrain_test_models(models, n=10000, m=2000)\n\"\"\"\n**Observation:**\n\nFor training:\n* The slowest model is SVC then XGBClassifier\n* All models do better than random predictor\n\nFor test data: \n* The best model in f1 score and logloss is XGBClassifier then SVC\n* The slowest model in testing time is SVC the XGBClassifier\n* All models do better thean random predictor\n    \nAs shown, It seems that the best model to use is XGBClassifier due to it's scores and it has a suitable time in training and testing. SVC also did well but it needs huge amount of time in processing data in training and testing.\n\"\"\"\n\"\"\"\nThe XGBClassifier gives bad results than expected, This is due to that at first time we trained on very small numbers of training data, Now, let's try other classifiers on all data except SVC and ExtraTree due to that they need huge amount of available resources.\n\"\"\"\n# training other models on all data\nmodels = [model_KNN, model_tree, model_NN]\ntrain_test_models(models,n=20000,m=2000)\nmodel_NN_tuned = MLPClassifier(learning_rate='adaptive', shuffle=True, epsilon=1e-8, activation='relu',\n                               hidden_layer_sizes=100, solver='adam', verbose=True)\n\nmodels = [model_NN_tuned]\ntrain_test_models(models,n=20000,m=4000)\nX_train.isnull().any()\ny_train.isnull().any()\n\nmodel_KNN = KNeighborsClassifier(n_jobs=-1, weights='distance')\nX=X_train.iloc[0:30000]\ny=y_train.iloc[0:30000]\nmodel_KNN.fit(X_train,y_train)\nprint(\"knn training accuracy\",model_KNN.score(X,y))\nprint(model_KNN.predict(X))\n\n\nmodel_tree.fit(X,y)\nprint(\"training accuracy\",model_tree.score(X,y))\n\nmodel_extraTrees.fit(X,y)\nprint(\"training accuracy EXTRATREES\",model_extraTrees.score(X,y))\n\n'''\nmodel_SVC.fit(X,y)\nprint(\"training accuracy\",model_SVC.score(X,y))\n\nmodel_XGB.fit(X,y)\nprint(\"training accuracy XGB\",model_XGB.score(X,y))\n'''\n'''\nmodel_NN_tuned.fit(X,y)\nprint(\"knn training accuracy\",model_NN_tuned.score(X,y))\n'''\n\n","meta":"{'source': 'AI4Code', 'id': '63630600b123df'}"}
{"id":"2144","text":"\"\"\"\n## Toxic Comment Exploration Notebook \n* Loading the Data \n* Running essential EDA \n* Word Cloud Visualization \n* Knowldage Graph Visualization \n* Tensorboard Visualization \n\n\"\"\"\n\"\"\"\n## Models and Scores \n\"\"\"\n\"\"\"\n* Preceptorn Nueral Network + Word embedding Kaggle Score : 0.90994 [Press Here](https:\/\/www.kaggle.com\/ahayek84\/toxic-comment-classification-challenge)\n* GRU with Pooling + Word embeding Kaggle Score : 0.95 [Press Here](https:\/\/www.kaggle.com\/ahayek84\/fork-of-toxic-comment-classification-gru)\n* BERT pre-trained model as proof of concept  [Press Here](https:\/\/www.kaggle.com\/ahayek84\/toxic-comment-bert-tf1-proof-of-concept)\n* Bidirectional GRU with Pooling + Glove Kaggle Score : 0.98112 [Press Here](https:\/\/www.kaggle.com\/ahayek84\/toxic-comment-gru-glove)\n* Bidirectional LSTM with Pooling + Glove Kaggle Score : 0.98 [Press Here](https:\/\/www.kaggle.com\/ahayek84\/toxic-comment-lstm-glove)\n\n\n\n\n\"\"\"\n\"\"\"\n### Loading the Data\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n!pip install wordcloud\n# Start with loading all necessary libraries\nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport seaborn as sns\nimport csv\n\n\nimport collections\nprint(os.listdir(\"..\/working\/\"))\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n# Load in the dataframe\ndf = pd.read_csv(\"..\/input\/jigsaw-toxic-comment-classification-challenge\/train.csv\")\n\"\"\"\n### Running essential EDA \n\"\"\"\nprint(\"Number of rows in data =\",df.shape[0])\nprint(\"Number of columns in data =\",df.shape[1])\nprint(\"\\n\")\nprint(\"**Sample data:**\")\ndf.head()\n\nprint(\"There are {} observations and {} features in this dataset. \\n\".format(df.shape[0],df.shape[1]))\n\nprint(\"There are {} words in this dataset such as {}... \\n\".format(len(df.comment_text.unique()),\n                                                                           \", \".join(df.comment_text.unique()[0:1])))\n\ndf[[\"comment_text\"]].head()\n\"\"\"\nNow we count the number of comments under each label. (For detailed code, please refer to the GitHub link of this project.)\n\"\"\"\ncategories = list(df.columns.values)\nsns.set(font_scale = 2)\nplt.figure(figsize=(15,8))\nax= sns.barplot(categories[2:], df.iloc[:,2:].sum().values)\nplt.title(\"Comments in each category\", fontsize=24)\nplt.ylabel('Number of comments', fontsize=18)\nplt.xlabel('Comment Type ', fontsize=18)\n#adding the text labels\nrects = ax.patches\nlabels = df.iloc[:,2:].sum().values\nfor rect, label in zip(rects, labels):\n    height = rect.get_height()\n    ax.text(rect.get_x() + rect.get_width()\/2, height + 5, label, ha='center', va='bottom', fontsize=18)\nplt.show()\n\"\"\"\nCounting the number of comments having multiple labels.\n\"\"\"\nrowSums = df.iloc[:,2:].sum(axis=1)\nmultiLabel_counts = rowSums.value_counts()\nmultiLabel_counts = multiLabel_counts.iloc[1:]\nsns.set(font_scale = 2)\nplt.figure(figsize=(15,8))\nax = sns.barplot(multiLabel_counts.index, multiLabel_counts.values)\nplt.title(\"Comments having multiple labels \")\nplt.ylabel('Number of comments', fontsize=18)\nplt.xlabel('Number of labels', fontsize=18)\n#adding the text labels\nrects = ax.patches\nlabels = multiLabel_counts.values\nfor rect, label in zip(rects, labels):\n    height = rect.get_height()\n    ax.text(rect.get_x() + rect.get_width()\/2, height + 5, label, ha='center', va='bottom')\nplt.show()\n\"\"\"\n### Word Cloud visualization \n\"\"\"\n\"\"\"\nWordCloud representation of most used words in each category of comments.\n\"\"\"\n\"\"\"\n#### Utility functions for text cleaning \n\"\"\"\nimport re, string\nre_tok = re.compile(f'([{string.punctuation}\u201c\u201d\u00a8\u00ab\u00bb\u00ae\u00b4\u00b7\u00ba\u00bd\u00be\u00bf\u00a1\u00a7\u00a3\u20a4\u2018\u2019])')\ndef tokenize(s): return re_tok.sub(r' \\1 ', s).split()\ndef clean(s): return re_tok.sub(r' \\1 ', s)\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nimport re\nimport sys\nimport warnings\ndata = df\nif not sys.warnoptions:\n    warnings.simplefilter(\"ignore\")\ndef cleanHtml(sentence):\n    cleanr = re.compile('<.*?>')\n    cleantext = re.sub(cleanr, ' ', str(sentence))\n    return cleantext\ndef cleanPunc(sentence): #function to clean the word of any punctuation or special characters\n    cleaned = re.sub(r'[?|!|\\'|\"|#]',r'',sentence)\n    cleaned = re.sub(r'[.|,|)|(|\\|\/]',r' ',cleaned)\n    cleaned = cleaned.strip()\n    cleaned = cleaned.replace(\"\\n\",\" \")\n    return cleaned\ndef keepAlpha(sentence):\n    alpha_sent = \"\"\n    for word in sentence.split():\n        alpha_word = re.sub('[^a-z A-Z]+', ' ', word)\n        alpha_sent += alpha_word\n        alpha_sent += \" \"\n    alpha_sent = alpha_sent.strip()\n    return alpha_sent\ndata['comment_text'] = data['comment_text'].str.lower()\ndata['comment_text'] = data['comment_text'].apply(cleanHtml)\ndata['comment_text'] = data['comment_text'].apply(cleanPunc)\ndata['comment_text'] = data['comment_text'].apply(keepAlpha)\ndf = data.copy()\n# Start with one review:\ntext = df.comment_text[0]\n\n# Create and generate a word cloud image:\nwordcloud = WordCloud(background_color=\"white\").generate(text)\n# Display the generated image:\nplt.figure(figsize=(30,50))\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\ndef prepare_text(text_col):\n    ## decide vocab size\n    text = text_col\n    words = []\n    for t in text:\n        words.extend(tokenize(t))\n    ##print(words[:100])\n    vocab = list(set(words))\n    ##print(len(words), len(vocab))\n    words_str1 = ' '.join(str(e) for e in words)  \n    \n    # lower max_font_size, change the maximum number of word and lighten the background:\n    wordcloud = WordCloud(stopwords=STOPWORDS,\n                              collocations=False,\n                              width=2500,\n                              height=1800, background_color=\"white\").generate(words_str1)\n    plt.figure(figsize=(30,50))\n    plt.imshow(wordcloud, interpolation=\"bilinear\")\n    plt.axis(\"off\")\n    plt.show()\nprepare_text(df['comment_text'])\n\"\"\"\n### word cloud for each category \n\"\"\"\ntoxic_comments = df.loc[df.toxic != 0]['comment_text']\nsevere_toxic_comments = df.loc[df.severe_toxic != 0]['comment_text']\nobscene_comments = df.loc[df.obscene != 0]['comment_text']\nthreat_comments = df.loc[df.threat != 0]['comment_text']\ninsult_comments = df.loc[df.insult != 0]['comment_text']\nidentity_hate_comments = df.loc[df.identity_hate != 0]['comment_text']\nprepare_text(toxic_comments)\nprepare_text(severe_toxic_comments)\nprepare_text(obscene_comments)\nprepare_text(threat_comments)\nprepare_text(insult_comments)\nprepare_text(identity_hate_comments)\n\"\"\"\n### Knowledge Graph Visualization \n\"\"\"\nimport spacy\nfrom spacy import displacy\nnlp = spacy.load('en_core_web_sm')\n\nfrom spacy.matcher import Matcher \nfrom spacy.tokens import Span \n\nimport networkx as nx\n\nfrom tqdm import tqdm\ncandidate_sentences = df['comment_text']\ncandidate_sentences.shape\ndoc = nlp(\"The 22-year-old recently won ATP Challenger tournament.\")\n\nfor tok in doc:\n  print(tok.text, \"...\", tok.dep_)\ndoc = nlp(\"Nagal won the first set.\")\n\nfor tok in doc:\n  print(tok.text, \"...\", tok.dep_)\ndoc = nlp(\"the drawdown process is governed by astm standard d823\")\n\nfor tok in doc:\n  print(tok.text, \"...\", tok.dep_)\n\"\"\"\n#### Entity Pairs Extraction\n\"\"\"\ndef get_entities(sent):\n  ## chunk 1\n  ent1 = \"\"\n  ent2 = \"\"\n\n  prv_tok_dep = \"\"    # dependency tag of previous token in the sentence\n  prv_tok_text = \"\"   # previous token in the sentence\n\n  prefix = \"\"\n  modifier = \"\"\n\n  #############################################################\n  \n  for tok in nlp(sent):\n    ## chunk 2\n    # if token is a punctuation mark then move on to the next token\n    if tok.dep_ != \"punct\":\n      # check: token is a compound word or not\n      if tok.dep_ == \"compound\":\n        prefix = tok.text\n        # if the previous word was also a 'compound' then add the current word to it\n        if prv_tok_dep == \"compound\":\n          prefix = prv_tok_text + \" \"+ tok.text\n      \n      # check: token is a modifier or not\n      if tok.dep_.endswith(\"mod\") == True:\n        modifier = tok.text\n        # if the previous word was also a 'compound' then add the current word to it\n        if prv_tok_dep == \"compound\":\n          modifier = prv_tok_text + \" \"+ tok.text\n      \n      ## chunk 3\n      if tok.dep_.find(\"subj\") == True:\n        ent1 = modifier +\" \"+ prefix + \" \"+ tok.text\n        prefix = \"\"\n        modifier = \"\"\n        prv_tok_dep = \"\"\n        prv_tok_text = \"\"      \n\n      ## chunk 4\n      if tok.dep_.find(\"obj\") == True:\n        ent2 = modifier +\" \"+ prefix +\" \"+ tok.text\n        \n      ## chunk 5  \n      # update variables\n      prv_tok_dep = tok.dep_\n      prv_tok_text = tok.text\n  #############################################################\n\n  return [ent1.strip(), ent2.strip()]\nget_entities(\"the film had 200 patents\")\n#entity_pairs = []\n\n#for i in tqdm(candidate_sentences):\n#  entity_pairs.append(get_entities(i))\n## save paires\n#filename = 'entity_pairs.csv'\n#import csv\n#with open(filename, 'w') as f:\n#   writer = csv.writer(f, delimiter=',')\n#   writer.writerows(entity_pairs)  #considering my_list is a list of lists.\n## load paires \nl_entity_pairs = []\ne_file = \"..\/input\/saved-relations\/entity_pairs.csv\" ## read preloaded entity_paires\n#e_file = \"hm_data\/toxic_data\/entity_pairs.csv\" ## read session written entity paires\nwith open(e_file, 'r') as csvfile:\n    entity_pairs_file = csv.reader(csvfile, delimiter=',')\n    for row in entity_pairs_file:\n        for re in row:\n            re = re.replace('\"','')\n            re = eval(re)\n            l_entity_pairs.append(re)      \nentity_pairs = l_entity_pairs\nentity_pairs[10:20]\n\"\"\"\n### Relation \/ Predicate Extraction\n\"\"\"\ndef get_relation(sent):\n\n  doc = nlp(sent)\n\n  # Matcher class object \n  matcher = Matcher(nlp.vocab)\n\n  #define the pattern \n  pattern = [{'DEP':'ROOT'}, \n            {'DEP':'prep','OP':\"?\"},\n            {'DEP':'agent','OP':\"?\"},  \n            {'POS':'ADJ','OP':\"?\"}] \n\n  matcher.add(\"matching_1\", None, pattern) \n\n  matches = matcher(doc)\n  k = len(matches) - 1\n\n  span = doc[matches[k][1]:matches[k][2]] \n\n  return(span.text)\n #relations = [get_relation(i) for i in tqdm(candidate_sentences)]\n## save paires\n#filename = 'relations.csv'\n#import csv\n#with open(filename, 'w') as f:\n#   writer = csv.writer(f, delimiter=',')\n#   writer.writerows(relations)  #considering my_list is a list of lists.\n        \n## load relations \ne_file = \"..\/input\/saved-relations\/relations.csv\" ## read preloaded entity_paires\n#e_file = \"hm_data\/toxic_data\/relations.csv\" ## read session written entity paires\nl_relations = []\nwith open(e_file, 'r') as csvfile:\n    relations_file = csv.reader(csvfile, delimiter=',')\n    for row in relations_file:\n        for re in row:\n            l_relations.append(re)\n        #l_relations.append(''.join(row))\ntype(l_relations)\nl_relations[1]\nrelations = l_relations\ns = pd.Series(relations).value_counts()\ns[:10]\n## get as much as you want from verbs and their number of links\nprint(s[30:50])\n\"\"\"\n### Build a Knowledge Graph\n\"\"\"\n# extract subject\nsource = [i[0] for i in entity_pairs]\n\n# extract object\ntarget = [i[1] for i in entity_pairs]\n\nkg_df = pd.DataFrame({'source':source, 'target':target, 'edge':relations})\n# create a directed-graph from a dataframe\nG=nx.from_pandas_edgelist(kg_df, \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n#plt.figure(figsize=(12,12))\n\n#pos = nx.spring_layout(G)\n#nx.draw(G, with_labels=True, node_color='skyblue', edge_cmap=plt.cm.Blues, pos = pos)\n#plt.show()\n\"\"\"\n## Explore Key words in the Corpus related Entities\n\"\"\"\n\"\"\"\n#### Word : nigger\n\"\"\"\n## incoming \nG=nx.from_pandas_edgelist(kg_df[kg_df['source']==\"nigger\"], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5) # k regulates the distance between nodes\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n## outgoing\nG=nx.from_pandas_edgelist(kg_df[kg_df['edge']==\"kiss\"], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5) # k regulates the distance between nodes\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n\"\"\"\n### word : wikipedia\n\"\"\"\n## outging \nG=nx.from_pandas_edgelist(kg_df[kg_df['source']==\"wikipedia\"][:20], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5)\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n## incoming \nG=nx.from_pandas_edgelist(kg_df[kg_df['target']==\"wikipedia\"][:20], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5)\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n\"\"\"\n## Explore Key verbs (relations) in the Corpus related Entities\n\"\"\"\n\"\"\"\n### word: fuck\n\"\"\"\nG=nx.from_pandas_edgelist(kg_df[kg_df['edge']==\"fuck\"][:30], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5) # k regulates the distance between nodes\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n\"\"\"\n### word : suck\n\"\"\"\nG=nx.from_pandas_edgelist(kg_df[kg_df['edge']==\"suck\"][:25], \"source\", \"target\", \n                          edge_attr=True, create_using=nx.MultiDiGraph())\n\nplt.figure(figsize=(12,12))\npos = nx.spring_layout(G, k = 0.5)\nnx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_cmap=plt.cm.Blues, pos = pos)\nplt.show()\n\"\"\"\n### Tensorboard Visualization \n\"\"\"\n## type at local computer \n# python -m tensorboard.main --logdir=models\n## at bti_tf1 enviroment and project folder\n### copy http:\/\/localhost:6006\/ to your browser \n\"\"\"\n![test](https:\/\/raw.githubusercontent.com\/ahayek84\/bti_tf1\/master\/image\/2019-10-25_22h03_11.gif)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '0411714371fddf'}"}
{"id":"132540","text":"import os\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn.model_selection import train_test_split\n\ncnn_image_shape = (128, 128)\n\"\"\"\nAnimes will be class 0 and cartoons class 1.\n\nImport anime data.\n\"\"\"\nanime_path = '..\/input\/anime-and-cartoon-image-classification\/Training Data\/Anime\/'\n\nX = []\ny = []\n\nfor folder in os.scandir(anime_path):\n    for file in os.scandir(anime_path + folder.name):\n        img = cv2.imread(anime_path + folder.name + '\/' + file.name, cv2.IMREAD_COLOR)\n        img = cv2.resize(img, cnn_image_shape)\n        img = np.array(img, dtype='float32')\n        X.append(img)\n        y.append(0)\n\"\"\"\nImport cartoon data.\n\"\"\"\ncartoon_path = '..\/input\/anime-and-cartoon-image-classification\/Training Data\/Cartoon\/'\n\nfor folder in os.scandir(cartoon_path):\n    for file in os.scandir(cartoon_path + folder.name):\n        img = cv2.imread(cartoon_path + folder.name + '\/' + file.name, cv2.IMREAD_COLOR)\n        img = cv2.resize(img, cnn_image_shape)\n        img = np.array(img, dtype='float32')\n        X.append(img)\n        y.append(1)\n\"\"\"\nconvert arrays to numpy\n\"\"\"\nX = np.array(X)\ny = np.array(y)\n\"\"\"\nVamos ver quantas imagens temos de cada um dos \n\"\"\"\nprint(f'Number of anime images: {np.count_nonzero(y == 0)}')\n\nprint(f'Number of cartoons images: {np.count_nonzero(y == 1)}')\n\"\"\"\nPlot some images\n\"\"\"\nlabels = {0:'Anime', 1:'Cartoon'}\n\nfor i in range(5):\n    n = random.randint(0, X.shape[0])\n    plt.figure()\n    plt.title(labels[y[n]])\n    plt.imshow(X[n]\/255)\n\"\"\"\nsplit the database into 3split the database into 3\n* 80% for training\n* 10% for validation\n* 10% for test\n\"\"\"\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, shuffle=True, random_state=42)\nX_val, X_test, y_val, y_test = train_test_split(X_val, y_val, test_size=0.5, stratify=y_val, random_state=42)\n\"\"\"\nCreate the model\n\"\"\"\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Lambda, GlobalAveragePooling2D, Dropout, Dense\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.optimizers import Adam\n\n\nbefore_mobilenet = Sequential([Input((128, 128, 3)),\n                               Lambda(preprocess_input)])\n\nmobilenet = MobileNetV2(input_shape=(128, 128, 3), include_top=False)\n\nafter_mobilenet = Sequential([GlobalAveragePooling2D(),\n                              Dropout(0.3),\n                              Dense(2, activation='softmax')])\n\nmodel = Sequential([before_mobilenet, mobilenet, after_mobilenet])\n\nopt = Adam(learning_rate=0.0001)\n\nmodel.build(((None, 128, 128, 3)))\n\nmodel.compile(optimizer=opt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()\nearly_stopping = EarlyStopping(\n    patience=10,\n    min_delta=0.001,\n    restore_best_weights=True,\n)\n\nhistory = model.fit(\n    X_train, \n    y_train, \n    epochs=300, \n    validation_data=(X_test, y_test), \n    callbacks=[early_stopping]\n)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper right')\nplt.show()\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\nfrom sklearn.metrics import classification_report\n\npredictions = model.predict(X_test)\n\npredict = []\nfor i in predictions:\n    predict.append(np.argmax(i))\n    \nprint(classification_report(y_test, predict))\n\"\"\"\nTest with outside image\n\"\"\"\n\"\"\"\n![](https:\/\/a-static.mlcdn.com.br\/574x431\/painel-de-festa-cavaleiros-do-zodiaco-cdz-02-colormyhome\/colormyhome\/3455\/2b09a906f973deadbf918d1008084f28.jpg)\n\"\"\"\n!wget https:\/\/a-static.mlcdn.com.br\/574x431\/painel-de-festa-cavaleiros-do-zodiaco-cdz-02-colormyhome\/colormyhome\/3455\/2b09a906f973deadbf918d1008084f28.jpg -O cdz.jpg\nimg = cv2.imread('.\/cdz.jpg', cv2.IMREAD_COLOR)\nimg = cv2.resize(img, cnn_image_shape)\nimg = np.array(img, dtype='float32')\n\nimg = img.reshape((1, 128, 128, 3))\n\nimg.shape\nprediction = model.predict(img)\nprediction_probabilities = np.array(prediction)\nargmaxs = np.argmax(prediction_probabilities, axis=1)\nprint(argmaxs)","meta":"{'source': 'AI4Code', 'id': 'f3d38af7b2f250'}"}
{"id":"95165","text":"\"\"\"\n### Import Libraries\n\"\"\"\n# Data Libraries\nimport pandas as pd\nimport numpy as np\n\n# Visualization Libraries\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport plotly.io as pio\npio.templates.default = \"plotly_dark\"\nsns.set(style=\"darkgrid\")\n\n# Ignore Warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n### Check out the Data\n\"\"\"\n# Read in the data\nf = pd.read_csv('..\/input\/insurance\/insurance.csv')\n# Basic info of Data set\nf.info()\n# Basic Statistics on numeric columns\nf.describe()\n# Read first 5 values using head()\nf.head()\n\"\"\"\n# Exploratory data analysis\n\n#### Let's create some simple plots to check out the data!\n\"\"\"\n# Distribution of Charges for Female Sex\nfig = go.Figure()\n\nfig.add_trace(go.Histogram(x = f['charges'], y = f[f['sex'] == 'female']['charges'], marker_color='#5852a8',))\n\nfig.update_layout(title='Distribution of Charges for Female Sex',bargap=0.05,\n                  xaxis = dict(title = 'Charges'),\n                  yaxis = dict(title = 'Number of Adult Females')\n                 )\nfig.show()\n# Distribution of Charges for Male Sex\nfig = go.Figure()\n\nfig.add_trace(go.Histogram(x = f['charges'], y = f[f['sex'] == 'male']['charges'], marker_color='#5852a8',))\n\nfig.update_layout(title='Distribution of Charges for Male Sex',bargap=0.05,\n                  xaxis = dict(title = 'Charges'),\n                  yaxis = dict(title = 'Number of Adult Males')\n                 )\nfig.show()\n# Age Analysis\n\nbins = [18, 36, 56]\nnames = ['Young Age Adults (18-35)', 'Middle Age Adults (36-55)', 'Elderly Age Adults (55+)']\nd = dict(enumerate(names, 1))\nf['Age_Category'] = np.vectorize(d.get)(np.digitize(f['age'], bins))\n\nfig = go.Figure()\n\nfig.add_trace(go.Histogram(x = f['Age_Category'], marker_color='#5852a8'))\n\nfig.update_layout(title='Number of Adults Categorised by Age',\n                  xaxis = dict(title = 'Age Category'),\n                  yaxis = dict(title = 'Number of Adults'),\n                  bargap=0.05\n                 )\nfig.show()\n# BMI as per Age Category\n\nfig = px.box(f,x = f['Age_Category'], y = f['bmi'],\n             color= 'smoker', title=\"Box plot of BMI for Each Age Category (Categorised by Smoker & Non-smoker)\"\n             )\nfig.show()\n# Charges as per Age Category\n\nfig = px.box(f,x = f['Age_Category'], y = f['charges'],\n             color= 'smoker', title=\"Box plot of Charges for Each Age Category (Categorised by Smoker & Non-smoker)\"\n             )\nfig.show()\n# BMI as per Region\nfig = px.box(f,x = f['region'], y = f['bmi'],\n             color= 'smoker', title=\"Box plot of bmi for Each region (Categorised by Smoker & Non-smoker)\"\n             )\nfig.show()\n# transform Non-numerical labels (as long as they are hashable and comparable) to Numerical labels.\nfrom sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\n\n# region \nle.fit(f['region'].drop_duplicates()) \nf['region'] = le.transform(f['region'])\n\n# smoker or not ( \"1\" for Yes)\nle.fit(f['smoker'].drop_duplicates()) \nf['smoker'] = le.transform(f['smoker'])\n\n# sex (\"1\" for Male)\n\nle.fit(f['sex'].drop_duplicates()) \nf['sex'] = le.transform(f['sex'])\n\n# Correlation Heatmap\ndf = f.drop(columns = 'Age_Category')\nsns.heatmap(df.corr())\n\"\"\"\n# Linear Regression\n\n#### Let's now begin to train out regression model! We will need to first split up our data into an X array that contains the features to train on, and a y array with the target variable, in this case the charges column.\n\"\"\"\n# X and y arrays\nfrom sklearn.preprocessing import PolynomialFeatures\n\nX = f.drop(columns = ['charges','Age_Category'], axis = 1)\ny = f['charges']\n\npf = PolynomialFeatures()\nX_pf = pf.fit_transform(X)\n# Train Test Split\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_pf, y, test_size=0.25, random_state=0)\n# Creating and Training the Model\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression()\nplr = lr.fit(X_train,y_train)\n# Predictions from our Model\npredictions = lr.predict(X_test)\n# Let's grab predictions off our test set and see how well it did!\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=y_test,\n                y=predictions,\n                marker_color='white',\n                mode='markers'\n                ))\nfig.update_layout(title='Predicted Charges vs Actual Charges',\n                  xaxis = dict(title = 'Actual Charges'),\n                  yaxis = dict(title = 'Predicted Charges')\n                  )\nfig.show()\n# Score\nprint(plr.score(X_test,y_test))\n\"\"\"\n## Regression Evaluation Metrics\n\nHere are three common evaluation metrics for regression problems:\n\n**Mean Absolute Error** (MAE) is the mean of the absolute value of the errors:\n\n$$\\frac 1n\\sum_{i=1}^n|y_i-\\hat{y}_i|$$\n\n**Mean Squared Error** (MSE) is the mean of the squared errors:\n\n$$\\frac 1n\\sum_{i=1}^n(y_i-\\hat{y}_i)^2$$\n\n**Root Mean Squared Error** (RMSE) is the square root of the mean of the squared errors:\n\n$$\\sqrt{\\frac 1n\\sum_{i=1}^n(y_i-\\hat{y}_i)^2}$$\n\nComparing these metrics:\n\n- **MAE** is the easiest to understand, because it's the average error.\n- **MSE** is more popular than MAE, because MSE \"punishes\" larger errors, which tends to be useful in the real world.\n- **RMSE** is even more popular than MSE, because RMSE is interpretable in the \"y\" units.\n\nAll of these are **loss functions**, because we want to minimize them.\n\"\"\"\nfrom sklearn import metrics\n\nprint('MAE:', metrics.mean_absolute_error(y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))","meta":"{'source': 'AI4Code', 'id': 'aeae765f944b73'}"}
{"id":"4727","text":"# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('darkgrid')\n\nimport warnings\nwarnings.filterwarnings('ignore')\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\n\"\"\"\n# Load Data\n\"\"\"\ndf= pd.read_csv('\/kaggle\/input\/customer-analytics\/Train.csv')\ndf.head()\ndf.info()\ndf.isna().sum()\ndf.describe()\ndf.drop('ID', axis=1, inplace=True)\ndf.head()\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ncat_cols= ['Warehouse_block','Mode_of_Shipment', 'Product_importance', 'Gender' ]\nplt.figure(figsize=(15,10))\ni=1\nfor col in cat_cols:\n    plt.subplot(2,2,i)\n    sns.countplot(df[col])\n    i+=1\ni = 1\nplt.figure(figsize=(15,10))\nfor col in ['Cost_of_the_Product', 'Weight_in_gms', 'Discount_offered']:\n    plt.subplot(2,2,i)\n    sns.distplot(df[col])\n    i+=1\ni=1\nplt.figure(figsize=(15,10))\nfor col in ['Customer_care_calls', 'Customer_rating', 'Prior_purchases']:\n    plt.subplot(2,2,i)\n    sns.countplot(df[col], hue=df['Reached.on.Time_Y.N'])\n    i+=1\ndf['Discount_offered'].hist()\nsns.pairplot(df)\ndf= pd.get_dummies(df)\ndf.head()\ndf.drop('Gender_F', axis=1, inplace=True)\ndf.head()\nplt.figure(figsize=(15,12))\nsns.heatmap(df.corr(), annot=True, cmap='coolwarm')\n\"\"\"\n# Preprocessing\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nX= df.drop('Reached.on.Time_Y.N', axis=1)\ny= df['Reached.on.Time_Y.N']\n\nX_train, X_test, y_train, y_test= train_test_split(X,y, test_size=0.2, stratify=y)\nss= StandardScaler()\nX_train= ss.fit_transform(X_train)\nX_test=ss.transform(X_test)\n\"\"\"\n# Training Model using ML Algorithms\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report, confusion_matrix\nkey= ['LogisticRegression', 'DecisionTreeClassifier', 'RandomForestClassifier', 'KNeighborsClassifier', 'XGBClassifier', 'SVC']\nvalue= [LogisticRegression(), DecisionTreeClassifier(), RandomForestClassifier(), KNeighborsClassifier(), XGBClassifier(), SVC()]\n\nmodels= dict(zip(key, value))\nfor key,value in models.items():\n    value.fit(X_train, y_train)\n    pred= value.predict(X_test)\n    print(key)\n    print(classification_report(y_test, pred))\n    print(confusion_matrix(y_test, pred))\n        \n\"\"\"\n# Using Neural Networks\n\"\"\"\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils.np_utils import to_categorical\nX_train_arr= np.array(X_train)\ny_train_arr= np.array(to_categorical(y_train))\nX_test_arr= np.array(X_test)\ny_test_arr= np.array(to_categorical(y_test))\n\nX_train_arr.shape\ny_train.shape\nX_test_arr.shape\nfrom keras.optimizers import Adam\ndef create_model(activation, learning_rate):\n    \n    model= Sequential()\n    model.add(Dense(100, activation=activation, kernel_initializer='normal', input_shape=(18,)))\n    model.add(Dense(50, activation=activation))\n    model.add(Dense(25, activation=activation))\n    model.add(Dense(1, activation='sigmoid'))\n    my_opt= Adam(lr=learning_rate)\n\n    model.compile(optimizer=my_opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\nmodel= KerasClassifier(build_fn= create_model)\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparams= {'epochs': [20,30,40,50],\n        'batch_size': [220,330,440],\n        'activation':['relu', 'tanh'],\n        'learning_rate':[0.001, 0.01, 0.1,1]}\n\nrandom= RandomizedSearchCV(model, param_distributions= params, cv=5)\nrandom.fit(X_train, y_train)\nrandom.best_estimator_\nrandom.best_estimator_.score(X_test, y_test)\n\"\"\"\n# The accuracy on test set is still 65%. \n\"\"\"\n\"\"\"\n# Upvote and Comment if you liked :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '08c8d77dec59f2'}"}
{"id":"17749","text":"# \uc2dc\ud5d8\ud658\uacbd \uc138\ud305 (\ucf54\ub4dc \ubcc0\uacbd X)\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\ndef exam_data_load(df, target, id_name=\"\", null_name=\"\"):\n    if id_name == \"\":\n        df = df.reset_index().rename(columns={\"index\": \"id\"})\n        id_name = 'id'\n    else:\n        id_name = id_name\n    \n    if null_name != \"\":\n        df[df == null_name] = np.nan\n    \n    X_train, X_test = train_test_split(df, test_size=0.2, shuffle=True, random_state=2021)\n    y_train = X_train[[id_name, target]]\n    X_train = X_train.drop(columns=[id_name, target])\n    y_test = X_test[[id_name, target]]\n    X_test = X_test.drop(columns=[id_name, target])\n    return X_train, X_test, y_train, y_test \n    \ndf = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/train.csv\")\nX_train, X_test, y_train, y_test = exam_data_load(df, target='SalePrice', id_name='Id')\n\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\n\"\"\"\n# Data Load & Simple EDA\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\"\"\"\n# Preprocessing\n\"\"\"\nX_train = X_train.select_dtypes(exclude=['object'])\nX_test = X_test.select_dtypes(exclude=['object'])\ny_train = y_train['SalePrice']\nfrom sklearn.impute import SimpleImputer\n\nimp = SimpleImputer()\nX_train = imp.fit_transform(X_train)\nX_test = imp.transform(X_test)\nfrom sklearn.model_selection import train_test_split\nX_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state=2022)\nX_tr.shape, X_val.shape, y_tr.shape, y_val.shape\n\"\"\"\n# Model\n\"\"\"\nfrom xgboost import XGBRegressor\n\nmodel = XGBRegressor()\nmodel.fit(X_tr, y_tr, verbose=False)\npred = model.predict(X_val)\nfrom sklearn.metrics import mean_squared_error\n\ndef rmsle(y, y_pred):\n    return np.sqrt(mean_squared_error(y, y_pred))\n\nprint(\"RMSLE : \" + str(rmsle(y_val, pred)))\n\"\"\"\n# Simple Preprocessing\n\"\"\"\nX_train, X_test, y_train, y_test = exam_data_load(df, target='SalePrice', id_name='Id')\n\nidx1 = y_train['SalePrice'].quantile(0.005)>y_train['SalePrice']\nidx2 = y_train['SalePrice'].quantile(0.995)<y_train['SalePrice']\n\ny_train = y_train[~(idx1|idx2)]\nX_train = X_train[~(idx1|idx2)]\n\nX_train = X_train.select_dtypes(exclude=['object'])\nX_test = X_test.select_dtypes(exclude=['object'])\ny_train = y_train['SalePrice']\n\nimp = SimpleImputer()\nX_train = imp.fit_transform(X_train)\nX_test = imp.transform(X_test)\n\nX_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state=20222)\n\nmodel = XGBRegressor()\nmodel.fit(X_tr, y_tr)\npred = model.predict(X_val)\n\nprint(\"RMSLE : \" + str(rmsle(y_val, pred)))\n\"\"\"\n## Simple Tuning\n\"\"\"\nX_train, X_test, y_train, y_test = exam_data_load(df, target='SalePrice', id_name='Id')\n\nidx1 = y_train['SalePrice'].quantile(0.005)>y_train['SalePrice']\nidx2 = y_train['SalePrice'].quantile(0.995)<y_train['SalePrice']\n\ny_train = y_train[~(idx1 + idx2)]\nX_train = X_train[~(idx1 + idx2)]\n\nX_train = X_train.select_dtypes(exclude=['object'])\nX_test = X_test.select_dtypes(exclude=['object'])\ny_train = y_train['SalePrice']\n\nimp = SimpleImputer()\nX_train = imp.fit_transform(X_train)\nX_test = imp.transform(X_test)\n\nX_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state=20222)\n\nmodel = XGBRegressor(n_estimators=100, max_depth=4, colsample_bytree=0.9)\nmodel.fit(X_tr, y_tr)\npred = model.predict(X_val)\n\nprint(\"RMSLE : \" + str(rmsle(y_val, pred)))\n\"\"\"\n# Predict & to CSV\n\"\"\"\npred = model.predict(X_test)\noutput = pd.DataFrame({'Id': y_test['Id'], 'SalePrice': pred})\noutput.head()\noutput.to_csv(\"000000.csv\", index=False)\n\"\"\"\n# \uacb0\uacfc \uccb4\uc810\n\"\"\"\npred = model.predict(X_test)\nprint(\"RMSLE : \" + str(rmsle(y_test['SalePrice'], pred)))","meta":"{'source': 'AI4Code', 'id': '206a0ad394398e'}"}
{"id":"11528","text":"\"\"\"\nGeographic and demographic visualizations are one of the most fun parts about data visualization. They allow you to connect technical skills with facts about the reality in which we live in in a very straightforward manner. This is a short exercise for showing how you can use GeoPandas and Matplotlib libraries to visualize simple but insightful facts about a country's population.\n\"\"\"\n\"\"\"\n# Setup\n\"\"\"\nimport json\nimport pandas as pd\nimport requests\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport geopandas\nimport numpy as np\nimport contextily as cx\n\nimport plotly\nimport plotly.graph_objects as go\nplotly.offline.init_notebook_mode(connected = True)\n\n\"\"\"\n# Downloading the data\n\nThere are two types of data we need. On the one hand there is the demographic information about the geographical regions we want to study. In my case, I am interested in the population of Spain, my coutry. So I need the information about the people in each city, and its distribution across age groups, sexes and nationalities. On the other hand, we need the geographical information: geographical coordinates, shapes of the cities, etc.\n\nThe demographic information can come in a great variety of formats, and it depends on the organism that makes that data available in each country. So, don't get caught up in the particular information you have available at your country. The intention of this post is not that you replicate exactly what I do. It is much better if you create your own list of visualizations that you are interested in.\n\nIn any case, I am going to use the Spanish census population from the year 2017, available in https:\/\/opendata.esri.es\/datasets\/municipios-de-espa%C3%B1a-padron2017https:\/\/opendata.esri.es\/datasets\/municipios-de-espa%C3%B1a-padron2017\n\nIt turns out you can navigate to the downloads section and choose the file in .geojson format. In any case, the file is already available as input in the notebook.In any case, the file is already available as input in the notebook. This is the ideal format because the file contains, in addition to the census population of every town, the geometric shape of each one. Hence, we have all information we need in just one file.\n\"\"\"\n\"\"\"\n## Reading geographical data\n\nWe can load the data from a .geojson file into a GeoDataFrame.\n\nA GeoWhat?\n\nWorking with Pandas DataFrames for any type of tabular data set is convenient, easy and popular. And in this post it is expected that you already know how to use Pandas. But, when dealing with geospatial data (like the shapes of municipalities), one might need to use some other libraries like Shapely to perform some operations: calculating areas, transforming to other coordinate system...\n\nFortunately, there is a library called GeoPandas, that makes it really easy to work with tabular data with geospatial data associated to it. This library extends the datatypes used by Pandas to allow spatial operations using Shapely. It also makes plotting maps very easily since it also uses Matplotlib utilities.\n\nA GeoDataFrame is very similar to a Pandas DataFrame, but one of the columns has geometric data that Shapely can operate on. It can be loaded as:\n\n```python\ngeo_dataframe = geopandas.read_file(file_geojson)\n```\n\nLet's do it, and also apply some post-processing for making the geodataframe easier to navigate:\n\"\"\"\nfield_code_to_name_manual = {\n    \"PAD_2C02\": \"Total de personas\",\n    \"PAD_2C03\": \"Pob. 0-4\",\n    \"PAD_2C04\": \"Pob. 5-9\",\n    \"PAD_2C05\": \"Pob. 10-14\",\n    \"PAD_2C06\": \"Pob. 15-19\",\n    \"PAD_2C07\": \"Pob. 20-24\",\n    \"PAD_2C08\": \"Pob. 25-29\",\n    \"PAD_2C09\": \"Pob. 30-34\",\n    \"PAD_2C10\": \"Pob. 35-39\",\n    \"PAD_2C11\": \"Pob. 40-44\",\n    \"PAD_2C12\": \"Pob. 45-49\",\n    \"PAD_2C13\": \"Pob. 50-54\",\n    \"PAD_2C14\": \"Pob. 55-59\",\n    \"PAD_2C15\": \"Pob. 60-64\",\n    \"PAD_2C16\": \"Pob. 65-69\",\n    \"PAD_2C17\": \"Pob. 70-74\",\n    \"PAD_2C18\": \"Pob. 75-79\",\n    \"PAD_2C19\": \"Pob. 80-84\",\n    \"PAD_2C20\": \"Pob. 85 o m\u00e1s\",\n    \n    \"PAD_2C21\": \"Total de varones\",\n    \"PAD_2C22\": \"Varones 0-4\",\n    \"PAD_2C23\": \"Varones 5-9\",\n    \"PAD_2C24\": \"Varones 10-14\",\n    \"PAD_2C25\": \"Varones 15-19\",\n    \"PAD_2C26\": \"Varones 20-24\",\n    \"PAD_2C27\": \"Varones 25-29\",\n    \"PAD_2C28\": \"Varones 30-34\",\n    \"PAD_2C29\": \"Varones 35-39\",\n    \"PAD_2C30\": \"Varones 40-44\",\n    \"PAD_2C31\": \"Varones 45-49\",\n    \"PAD_2C32\": \"Varones 50-54\",\n    \"PAD_2C33\": \"Varones 55-59\",\n    \"PAD_2C34\": \"Varones 60-64\",\n    \"PAD_2C35\": \"Varones 65-69\",\n    \"PAD_2C36\": \"Varones 70-74\",\n    \"PAD_2C37\": \"Varones 75-79\",\n    \"PAD_2C38\": \"Varones 80-84\",\n    \"PAD_2C39\": \"Varones 85 o m\u00e1s\",\n    \n    \"PAD_2C40\": \"Total de mujeres\",\n    \"PAD_2C41\": \"Mujeres 0-4\",\n    \"PAD_2C42\": \"Mujeres 5-9\",\n    \"PAD_2C43\": \"Mujeres 10-14\",\n    \"PAD_2C44\": \"Mujeres 15-19\",\n    \"PAD_2C45\": \"Mujeres 20-24\",\n    \"PAD_2C46\": \"Mujeres 25-29\",\n    \"PAD_2C47\": \"Mujeres 30-34\",\n    \"PAD_2C48\": \"Mujeres 35-39\",\n    \"PAD_2C49\": \"Mujeres 40-44\",\n    \"PAD_2C50\": \"Mujeres 45-49\",\n    \"PAD_2C51\": \"Mujeres 50-54\",\n    \"PAD_2C52\": \"Mujeres 55-59\",\n    \"PAD_2C53\": \"Mujeres 60-64\",\n    \"PAD_2C54\": \"Mujeres 65-69\",\n    \"PAD_2C55\": \"Mujeres 70-74\",\n    \"PAD_2C56\": \"Mujeres 75-79\",\n    \"PAD_2C57\": \"Mujeres 80-84\",\n    \"PAD_2C58\": \"Mujeres 85 o m\u00e1s\",\n    \n    \"PAD_3C03\": \"Pob. Espa\u00f1a\",\n    \"PAD_3C04\": \"Pob. extranjera\",\n    \n    \"PAD_3C05\": \"Pob. Uni\u00f3n Europea\",\n    \"PAD_3C06\": \"Pob. Alemania\",\n    \"PAD_3C07\": \"Pob. Bulgaria\",\n    \"PAD_3C08\": \"Pob. Francia\",\n    \"PAD_3C09\": \"Pob. Italia\",\n    \"PAD_3C10\": \"Pob. Polonia\",\n    \"PAD_3C11\": \"Pob. Portugal\",\n    \"PAD_3C12\": \"Pob. Reino Unido\",\n    \"PAD_3C13\": \"Pob. Ruman\u00eda\",\n    \n    \"PAD_3C14\": \"Pob. europea no comunitaria\",\n    \"PAD_3C15\": \"Pob. Rusia\",\n    \"PAD_3C16\": \"Pob. Ucrania\",\n    \n    \"PAD_3C17\": \"Pob. \u00c1frica\",\n    \"PAD_3C18\": \"Pob. Argelia\",\n    \"PAD_3C19\": \"Pob. Marruecos\",\n    \"PAD_3C20\": \"Pob. Nigeria\",\n    \"PAD_3C21\": \"Pob. Senegal\",\n    \n    \"PAD_3C22\": \"Pob. Am\u00e9rica\",\n    \"PAD_3C23\": \"Pob. Argentina\",\n    \"PAD_3C24\": \"Pob. Bolivia\",\n    \"PAD_3C25\": \"Pob. Brasil\",\n    \"PAD_3C26\": \"Pob. Colombia\",\n    \"PAD_3C27\": \"Pob. Cuba\",\n    \"PAD_3C28\": \"Pob. Chile\",\n    \"PAD_3C29\": \"Pob. Ecuador\",\n    \"PAD_3C30\": \"Pob. Paraguay\",\n    \"PAD_3C31\": \"Pob. Per\u00fa\",\n    \"PAD_3C32\": \"Pob. Rep_Dominicana\",\n    \"PAD_3C33\": \"Pob. Uruguay\",\n    \"PAD_3C34\": \"Pob. Venezuela\",\n    \n    \"PAD_3C35\": \"Pob. Asia\",\n    \"PAD_3C36\": \"Pob. China\",\n    \"PAD_3C37\": \"Pob. Pakist\u00e1n\",\n    \n    \"PAD_3C38\": \"Pob. Ocean\u00eda y Ap\u00e1tridas\",\n    \n    \"PAD_3C39\": \"Total Varones (Todas Nacionalidades)\",\n    \"PAD_3C40\": \"Varones Espa\u00f1a\",\n    \"PAD_3C41\": \"Varones Extranjeros\",\n    \n    \"PAD_3C42\": \"Varones Uni\u00f3n Europea\",\n    \"PAD_3C43\": \"Varones Alemania\",\n    \"PAD_3C44\": \"Varones Bulgaria\",\n    \"PAD_3C45\": \"Varones Francia\",\n    \"PAD_3C46\": \"Varones Italia\",\n    \"PAD_3C47\": \"Varones Polonia\",\n    \"PAD_3C48\": \"Varones Portugal\",\n    \"PAD_3C49\": \"Varones Reino Unido\",\n    \"PAD_3C50\": \"Varones Ruman\u00eda\",\n    \n    \"PAD_3C51\": \"Varones europea no comunitaria\",\n    \"PAD_3C52\": \"Varones Rusia\",\n    \"PAD_3C53\": \"Varones Ucrania\",\n    \n    \"PAD_3C54\": \"Varones \u00c1frica\",\n    \"PAD_3C55\": \"Varones Argelia\",\n    \"PAD_3C56\": \"Varones Marruecos\",\n    \"PAD_3C57\": \"Varones Nigeria\",\n    \"PAD_3C58\": \"Varones Senegal\",\n    \n    \"PAD_3C59\": \"Varones Am\u00e9rica\",\n    \"PAD_3C60\": \"Varones Argentina\",\n    \"PAD_3C61\": \"Varones Bolivia\",\n    \"PAD_3C62\": \"Varones Brasil\",\n    \"PAD_3C63\": \"Varones Colombia\",\n    \"PAD_3C64\": \"Varones Cuba\",\n    \"PAD_3C65\": \"Varones Chile\",\n    \"PAD_3C66\": \"Varones Ecuador\",\n    \"PAD_3C67\": \"Varones Paraguay\",\n    \"PAD_3C68\": \"Varones Per\u00fa\",\n    \"PAD_3C69\": \"Varones Rep_Dominicana\",\n    \"PAD_3C70\": \"Varones Uruguay\",\n    \"PAD_3C71\": \"Varones Venezuela\",\n    \n    \"PAD_3C72\": \"Varones Asia\",\n    \"PAD_3C73\": \"Varones China\",\n    \"PAD_3C74\": \"Varones Pakist\u00e1n\",\n    \n    \"PAD_3C75\": \"Varones Ocean\u00eda y Ap\u00e1tridas\",\n    \n    \"PAD_3C76\": \"Total Mujeres (Todas Nacionalidades)\",\n    \"PAD_3C77\": \"Mujeres Espa\u00f1a\",\n    \"PAD_3C78\": \"Mujeres Extranjeros\",\n    \n    \"PAD_3C79\": \"Mujeres Uni\u00f3n Europea\",\n    \"PAD_3C80\": \"Mujeres Alemania\",\n    \"PAD_3C81\": \"Mujeres Bulgaria\",\n    \"PAD_3C82\": \"Mujeres Francia\",\n    \"PAD_3C83\": \"Mujeres Italia\",\n    \"PAD_3C84\": \"Mujeres Polonia\",\n    \"PAD_3C85\": \"Mujeres Portugal\",\n    \"PAD_3C86\": \"Mujeres Reino Unido\",\n    \"PAD_3C87\": \"Mujeres Ruman\u00eda\",\n    \n    \"PAD_3C88\": \"Mujeres europea no comunitaria\",\n    \"PAD_3C89\": \"Mujeres Rusia\",\n    \"PAD_3C90\": \"Mujeres Ucrania\",\n    \n    \"PAD_3C91\": \"Mujeres \u00c1frica\",\n    \"PAD_3C92\": \"Mujeres Argelia\",\n    \"PAD_3C93\": \"Mujeres Marruecos\",\n    \"PAD_3C94\": \"Mujeres Nigeria\",\n    \"PAD_3C95\": \"Mujeres Senegal\",\n    \n    \"PAD_3C96\": \"Mujeres Am\u00e9rica\",\n    \"PAD_3C97\": \"Mujeres Argentina\",\n    \"PAD_3C98\": \"Mujeres Bolivia\",\n    \"PAD_3C99\": \"Mujeres Brasil\",\n    \n    \"PAD_3C100\": \"Mujeres Colombia\",\n    \"PAD_3C101\": \"Mujeres Cuba\",\n    \"PAD_3C102\": \"Mujeres Chile\",\n    \"PAD_3C103\": \"Mujeres Ecuador\",\n    \"PAD_3C104\": \"Mujeres Paraguay\",\n    \"PAD_3C105\": \"Mujeres Per\u00fa\",\n    \"PAD_3C106\": \"Mujeres Rep_Domincana\",\n    \"PAD_3C107\": \"Mujeres Uruguay\",\n    \"PAD_3C108\": \"Mujeres Venezuela\",\n    \"PAD_3C109\": \"Mujeres Asia\",\n    \"PAD_3C110\": \"Mujeres China\",\n    \"PAD_3C111\": \"Mujeres Pakist\u00e1n\",\n    \"PAD_3C112\": \"Mujeres Ocean\u00eda y Ap\u00e1tridas\",\n    \"PAD_3C113\": \"Mujeres China\",\n    \n    \"PAD_3_COD_PROV\": \"C\u00f3digo Provincia\",\n    \"PAD_3_COD_CCAA\": \"C\u00f3digo Comunidad Aut\u00f3noma\",\n}\n\ndef add_localities_natcode(census_localities):\n    \n    def locality_census_to_natcode(locality_census):\n        autonomy_code = locality_census[\"Cod_CCAA\"]\n        province_code = locality_census[\"Cod_Prov\"]\n        ine = locality_census[\"Codigo\"]\n        return f\"34{autonomy_code}{province_code}{ine}\"\n    \n    localities_natcodes = census_localities.apply(locality_census_to_natcode, axis=\"columns\")\n    return census_localities.set_index(localities_natcodes).rename_axis(index=\"NATCODE\")\n\nfile_geojson = \"\/kaggle\/input\/espaa-padrn-2017\/CensusSpain2017.geojson\"\nspain_localities_info = add_localities_natcode(\n    geopandas.read_file(file_geojson)\n    .rename(columns=field_code_to_name_manual)\n)\n\"\"\"\nThe `geometry` column of `spain_localities_info`, which has been generated by Geopandas when reading the file in .geojson format, contains the shapes of the localities in Spain.\n\nA shape is nothing more than the sequence of points that, when joined together in order by straight lines, form a 2D polygon. So, for each city, we have a sequence of points that form the polygon with the shape of that city.\n\nBut, wait. The Earth is more or less like a Sphere, a 3-dimensional object. But the polygons in the `geometry` column are in a 2-dimensional space. In other words, each point of the polygon has an X and a Y coorditates.\nHow are they calculated? What is the X, Y coordinate for London for example?\n\nThe answer? They are calculated by projecting geographical locations to a Coordinate Reference System or CRS. A CRS is just a way transforming (projecting) each 3D real geographical location to a lower dimensional (2D) space. There is always a loss of information, a distortion. According to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Map_projection\">Wikipedia<\/a>:\n\n> All projections of a sphere on a plane necessarily distort the surface in some way and to some extent\n\nAnd, in which way are locations distorted? It depends on the CRS. If we take the (X, Y) coordinates for London, Madrid, and Rome for example, the distance between them in the 2D space might be different from the real one, or maybe the angles of the triangle are different. It could be that the difference in distance is more pronunciated in the X direction than the Y direction.\n\nIn general, all types of distortions occurr to some extent. Hence, the question is not how to avoid distortion, but what type of distortion we are willing to allow. What type of distortion is not very critical for our application.\n\nThe way to know the CRS of a Geopandas DataFrame is to use the `crs` property. Sometimes the `crs` property is not going to be set because the data from the source does not have a CRS specified, but usually it does. Geographical coordinates without the CRS they use are pretty useless.\n\nAnyway, in our example the geographical data came with the CRS specified.\n\"\"\"\nspain_localities_info.crs\n\"\"\"\nIt seems that the geographic information from the source (and the one that has been loaded into the `geometry` column of `spain_localities_info`) is in a CRS (Coordinate Reference System) called <a href=\"https:\/\/en.wikipedia.org\/wiki\/World_Geodetic_System#WGS84\">WGS84<\/a> or <a href=\"https:\/\/epsg.io\/4326\">EPSG:4326<\/a>, which is what we popularly know as latitude and longitude coordinate system. \n\n## Calculating the area of shapes\n\nAs we are going to study the population density of towns in Spain, we need to calculate the area. GeoPandas has the <a href=\"https:\/\/geopandas.readthedocs.io\/en\/latest\/docs\/reference\/api\/geopandas.GeoSeries.area.html?highlight=area\">builtin property `area`<\/a> for calculating the area of the polygons in the `geometry` column.\n\nHowever, as we have just seen, some types of distortions (every CRS is a distortion) are more fit to a given application than others. We need to choose the right type of distortion. The units of the WGS84 system are not in meters but in degrees and moreover one unit distance of latitude does not represent the same distance as one unit distance in longitude. And, actually, the ratio between the two changes with the latitude.\n\nIn summary, it is not the approppriate system for calculating areas because distances are deeply distorted. The area of the polygons in this system does not have meaningful units and due to the distortion that increases with latitude, we cannot even compare areas of different parts of the world.\n\nWe need to project the data onto a CRS where distances are in meters and the distortion is not too big.\n\nFor Spain, a good CRS is <a href=\"https:\/\/epsg.io\/2062-8241\">EPSG:2062<\/a>. We will project the coordinates onto this CRS using the Geopandas <a href=\"https:\/\/geopandas.readthedocs.io\/en\/latest\/docs\/reference\/api\/geopandas.GeoSeries.to_crs.html\">builtin function `to_crs`<\/a> and then calculate the area.\n\"\"\"\nspain_localities_info[\"Area\"] = spain_localities_info.to_crs(epsg=2062).geometry.area \/ 1e6\nspain_localities_info[\"Density\"] = spain_localities_info[\"Total de personas\"] \/ spain_localities_info[\"Area\"]\n\"\"\"\nNotice we have divided the area between 1000000 to transform square meters to square kilometers.\n\"\"\"\n\"\"\"\n## Plotting\n\nNow, when plotting shapes on a map, we need the map as the background and the shapes to be drawed on top. The map and the shapes must use the same CRS.\n\nThe library for adding background maps we are going to use is <a href=\"https:\/\/contextily.readthedocs.io\/en\/latest\/\">Contextily<\/a>.\nBy default, it plots maps using the CRS <a href=\"https:\/\/en.wikipedia.org\/wiki\/Web_Mercator_projection\">Web Mercator<\/a>, also called <a href=\"https:\/\/epsg.io\/3857\">EPSG:3857<\/a>, which is different from the one we are using.\n\nAlthough Contextily has the option to change it, it looks to me it is easier to convert the geometry information using the `to_crs` function of Geopandas.\n\"\"\"\nspain_localities_info = spain_localities_info.to_crs(epsg=3857)\n\"\"\"\nNow we are ready to plot!\n\"\"\"\ndef plot_map(color, name=None, normalizer=None, tick_format=None, colormap=\"brg\"):\n    fig, ax = plt.subplots(1, 1, figsize=(20, 12))\n\n    ax.set_xlim(-1250000, 600000)\n    ax.set_ylim(4250000, 5500000)\n\n    spain_localities_info.plot(\n        ax=ax,\n        column=color,\n        legend=True,\n        cmap=colormap,\n        alpha=0.75,\n        norm=normalizer,\n        legend_kwds={\"format\": tick_format}\n    )\n\n    ax.tick_params(axis=\"both\", bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False)\n\n    colorbar = fig.axes[1]\n    colorbar.tick_params(labelsize=20)\n    colorbar.set_ylabel(name, fontsize=20)\n\n    cx.add_basemap(ax, zoom=7)\n    \n    return fig\n\n\nplot_map(\n    color=\"Density\",\n    name=\"Density (people \/ km$^2$)\",\n    normalizer=matplotlib.colors.LogNorm(vmin=1, vmax=spain_localities_info.Density.max(), clip=True),\n    tick_format=\"%d\"\n);\n\"\"\"\nAnd that's it! We have our map of population density.\n\n## Further exploration: distribution of foreigners in Spain\n\nWe might ask: what parts of spain have more foreigners?\nAnother way of asking it is: is foreign population distributed accross spain the same way nationals are?\nBefore answering the question with data, I would say big cities like Madrid, Barcelona and Valencia have a bigger proportion of foreigners than the rest of Spain, but it might not be true and be just a sensation.\n\nI have thought about two ways to answer this question visually. I think the second way is better, but I will start with the first one since it is more intuitive.\n\nIn order to answer what cities of Spain have more foreigners, we should compare to the amount of nationals that are living there. For example, almost 7% of all Spaniards (nationals) in Spain are living in Madrid.\nIf the distribution of foreigners was the same as nationals, we would expect the same proportion of them to live in Madrid.\n\nHowever, if there are more (as I suspect is the case), then that would mean that in that part of Spain is more cosmopolitan\/diverse, and we want the color of that city in the map to correspond to its level of diversity.\n\nHow can we come up with a number that is significative? To me, the most intuitive is just to divide the number of actual foreigners in a city by the expected number of them:\n\n$$\nS_i = \\frac{N_i}{\\mu^{(\\text{reference})}_{i}}\n$$\n\n$$\n\\mu^{(\\text{reference})}_{i} = \\frac{\\sum_i N_i}{\\sum_i N^{(\\text{reference})}_{i}} N^{(\\text{reference})}_{i}\n$$\n\nwhere\n- $S_i$ is the Diversity Score of the $i$-th municipality\/territory\/region.\n- $N_i$ is the number of people from the target population (the foreign population in this case) in the $i$-th municipality\n- $N_i^{(\\text{reference})}$ is the number of people from the reference population (the national population in this case) in the $i$-th municipality\n- $\\mu^{(\\text{reference})}_{i}$ is the expected number of people from the target population considering the distribution of the reference population as the expected one (Spaniard population in this case)\n\"\"\"\ndef calculate_diversity_score(target_population, reference_population):\n    total_target_population = target_population.sum()\n    total_reference_population = reference_population.sum()\n    \n    expected_target_population = reference_population * total_target_population \/ total_reference_population\n    \n    return target_population \/ expected_target_population\ndiversity_score = calculate_diversity_score(\n    target_population=spain_localities_info[\"Pob. extranjera\"],\n    reference_population=spain_localities_info[\"Pob. Espa\u00f1a\"],\n)\nfig = plot_map(\n    diversity_score,\n    normalizer=matplotlib.colors.LogNorm(vmin=0.1, vmax=10, clip=True), \n    name=\"Diversity Score\",\n    tick_format=\"%.1f\",\n    colormap=\"bwr\"\n);\n\"\"\"\nRed tonalities mean that the nuber of foreigners is bigger than the expected. Blue tonalities mean the opposite.\nAs we can see, the east of Spain has, in general a bigger diversity score than the west.\n\nHowever, I find a problem with this visualization. Some town might be very big in extension, but not in population. There is, for example, a little town of less than 400 people, where only 70 of them are nationals. That part of the map is very red, but in terms of total population, it is not that relevant.\n\nHence, this visualization gives too much weight to municipalities with low density. This is why the diversity score is not very meaningful.\n\nI propose another score that will take in account the population of municipalities.\nInstead of taking the quocient, I will just take the difference between the actual and expected amount of foreigners, and then I will divide by the area of the municipality to transform it to a density. Therefore, this quantity is the \"excess\" of foreigners (the difference with respect to the expected quantity) per square kilometer that live in a municipality.\n\nIn this way, low populated towns will not be relevant at all (will appear with a white color), while very populated towns will have a weight proportional to its density.\n\nFinally, in order to appreciate the magnitude of the unbalance in the distribution of foreigners with respect the total size of the group, I will divide the current score by the mean density of foreign population per square kilometer. This way, the final quantity, which I will call Relative Deviation Density, can be thought of as the \"excess\" of proportion of foreigners per square kilometer.\n\n$$\nD_i = \\frac{N_i - \\mu^{(\\text{reference})}_{i}}{A_i \\frac{\\sum_i N_i}{\\sum_i A_i}}\n$$\n\n$$\n\\mu^{(\\text{reference})}_{i} = \\frac{\\sum_i N_i}{\\sum_i N^{(\\text{reference})}_{i}} N^{(\\text{reference})}_{i}\n$$\n\nwhere\n- $D_i$ is the Relative Deviation Density of the $i$-th municipality\/territory\/region.\n- $N_i$ is the number of people from the target population (the foreign population in this case) in the $i$-th municipality\n- $N_i^{(\\text{reference})}$ is the number of people from the reference population (the national population in this case) in the $i$-th municipality\n- $\\mu^{(\\text{reference})}_{i}$ is the expected number of people from the target population considering the distribution of the reference population as the expected one (Spaniard population in this case)\n- $A_i$ is the area of the $i$-th municipality in square kilometers\n\"\"\"\ndef calculate_relative_deviation_density(target_population, reference_population, area):\n    total_area = area.sum()\n    total_target_population = target_population.sum()\n    total_reference_population = reference_population.sum()\n    \n    expected_target_population = reference_population * total_target_population \/ total_reference_population\n    mean_target_density = total_target_population \/ total_area\n    \n    return (\n        (target_population - expected_target_population)\n        \/ (area * mean_target_density)\n    )\ndiversity_deviation_density = calculate_relative_deviation_density(\n    target_population=spain_localities_info[\"Pob. extranjera\"],\n    reference_population=spain_localities_info[\"Pob. Espa\u00f1a\"],\n    area=spain_localities_info[\"Area\"]\n)\nfig = plot_map(\n    diversity_deviation_density,\n    normalizer=matplotlib.colors.SymLogNorm(\n        linthresh=10,\n        linscale=1,\n        vmin=-diversity_deviation_density.abs().quantile(0.99),\n        vmax=diversity_deviation_density.abs().quantile(0.99),\n        clip=True\n    ),\n    name=\"Diversity Deviation Density\",\n    colormap=\"bwr\"\n)\n# fig.savefig(\"DiversityDeviationDensity.png\")\n\"\"\"\nNow we can see that, in most of Spain, as it is mostly uninhabited, the deviation is close to 0 (white color). However, in highly populated cities, we see if they present a bigger or smaller diversity than expected.\n\nIn general, foreign population is unusually high in cities of the Mediterranean coast and Madrid.\nThe counterpart are the big cities of the rest of Spain: Sevilla, Salamanca, Valladolid, Pontevedra, Santander, A Coru\u00f1a, etc.\n\n## Distribution of foreigners of specific nationalities\nNow we can do the same but selecting specific nationalities.\n\"\"\"\nnationality = \"China\"\nforeign_nationality_deviation_density = calculate_relative_deviation_density(\n    target_population=spain_localities_info[f\"Pob. {nationality}\"],\n    reference_population=spain_localities_info[\"Pob. Espa\u00f1a\"],\n    area=spain_localities_info[\"Area\"]\n)\n\nfig = plot_map(\n    foreign_nationality_deviation_density,\n    normalizer=matplotlib.colors.SymLogNorm(\n        linthresh=10,\n        linscale=1,\n        vmin=-foreign_nationality_deviation_density.abs().quantile(0.99),\n        vmax=foreign_nationality_deviation_density.abs().quantile(0.99),\n        clip=True\n    ),\n    name=f\"{nationality} Deviation Density\",\n    colormap=\"bwr\"\n)\n# fig.savefig(\"ChinaDeviationDensity.png\")\n\"\"\"\nWe can even do it using the total foreign population as a reference for the expected distribution, instead of the national distribution.\n\nIn this case, this would help detect the parts of Spain with unusually high density of, say, Germans for example, but not compared to the population of Spaniards, but to the population of foreigners.\n\nIn other words, we already know that Barcelona has lots of people from other countries, so it is not a surprise that there are lots of people from basically any country. But, given its cosmopolitanism, does it have more or less Chinese population, for example?\n\"\"\"\nnationality = \"China\"\nforeign_nationality_deviation_density = calculate_relative_deviation_density(\n    target_population=spain_localities_info[f\"Pob. {nationality}\"],\n    reference_population=spain_localities_info[\"Pob. extranjera\"],\n    area=spain_localities_info[\"Area\"]\n)\n\nfig = plot_map(\n    foreign_nationality_deviation_density,\n    normalizer=matplotlib.colors.SymLogNorm(\n        linthresh=10,\n        linscale=1,\n        vmin=-foreign_nationality_deviation_density.abs().quantile(0.99),\n        vmax=foreign_nationality_deviation_density.abs().quantile(0.99),\n        clip=True\n    ),\n    name=f\"{nationality} Deviation Density\",\n    colormap=\"bwr\"\n)\n\"\"\"\nThe maps look very similar, but they are different. We can notice that in the subtleties. For exaple, the city of Granada has an unusually low number of foreign people and, hence, an unusually low number of Chinese people living ther. However, given that Granada is like that, i.e. given that it has the number of foreigners it has, the size of the Chinese population is actually higher than expected.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '152942f6a9dd5b'}"}
{"id":"40762","text":"import os\nimport os.path\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tqdm\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import TimeSeriesSplit\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_absolute_error\n\"\"\"\n# **Load data**\n\"\"\"\nINPUT_DIR = '..\/input\/m5-forecasting-accuracy\/'\ntrain_df = pd.read_csv(os.path.join(INPUT_DIR, 'sales_train_evaluation.csv'))\nprice_df = pd.read_csv(os.path.join(INPUT_DIR, 'sell_prices.csv'))\ncalender_df = pd.read_csv(os.path.join(INPUT_DIR, 'calendar.csv'))\n\ncalender_df['date'] = pd.to_datetime(calender_df['date'])\ntrain_df.head(3)\ncalender_df\nprice_df.head(3)\n\"\"\"\nSplit *price_df* into 10 dataframes (one dataframe for each store) just to speed up the function *get_item_price* (see below):\n\"\"\"\nprice_dfs = {\n    'CA_1': price_df[price_df['store_id'] == 'CA_1'],\n    'CA_2': price_df[price_df['store_id'] == 'CA_2'],\n    'CA_3': price_df[price_df['store_id'] == 'CA_3'],\n    'CA_4': price_df[price_df['store_id'] == 'CA_4'],\n    'TX_1': price_df[price_df['store_id'] == 'TX_1'],\n    'TX_2': price_df[price_df['store_id'] == 'TX_2'],\n    'TX_3': price_df[price_df['store_id'] == 'TX_3'],\n    'WI_1': price_df[price_df['store_id'] == 'WI_1'],\n    'WI_2': price_df[price_df['store_id'] == 'WI_2'],\n    'WI_3': price_df[price_df['store_id'] == 'WI_3']\n}\n\"\"\"\nDrop the variable which we don't need anymore:\n\"\"\"\nprice_df = None\n\"\"\"\nSome functions to prepare a dataframe for one item:\n\"\"\"\ndef transform_d_dates_to_dates(d_dates):\n    return calender_df.set_index('d').loc[d_dates]['date']\n\n\ndef transform_dates_to_d_dates(dates):\n    return calender_df.set_index('date').loc[dates]['d']\n\n\ndef transform_dates_to_wm_yr_wk(dates):\n    return calender_df.set_index('date').loc[dates]['wm_yr_wk']\n\n\ndef get_avg_item_n_sold_prev_month(item_id, store_id, dates_df):\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    d_dates_month_ago = transform_dates_to_d_dates(dates_df['date'] - pd.DateOffset(days=28))\n    assert d_dates_month_ago.shape == (dates_df.shape[0],)\n    \n    first_day = int(d_dates_month_ago.iloc[0].split('_')[1]) - 28\n    last_day = int(d_dates_month_ago.iloc[-1].split('_')[1])\n    assert first_day == 310 and last_day == 1941\n    \n    tmp = train_df[\n        (train_df['item_id'] == item_id) &\n        (train_df['store_id'] == store_id)\n    ][['d_' + str(i) for i in range(first_day, last_day + 1)]]\n    assert tmp.shape == (1, dates_df.shape[0] + 28)\n    return tmp.iloc[0].rolling(28).mean().iloc[28:].to_numpy()\n\n\ndef get_item_n_sold_year_ago(item_id, store_id, dates_df):\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    d_dates_year_ago = transform_dates_to_d_dates(dates_df['date'] - pd.DateOffset(years=1))\n    assert d_dates_year_ago.shape == (dates_df.shape[0],)\n    \n    tmp = train_df[\n        (train_df['item_id'] == item_id) &\n        (train_df['store_id'] == store_id)\n    ][d_dates_year_ago]\n    assert tmp.shape == (1, dates_df.shape[0])\n    return tmp.iloc[0].to_numpy()\n\n\ndef get_item_price(item_id, store_id, dates_df):\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    wm_yr_wk = transform_dates_to_wm_yr_wk(dates_df['date']).to_numpy()\n    assert wm_yr_wk.shape == (dates_df.shape[0],)\n    \n    week_to_price = price_dfs[store_id][\n        (price_dfs[store_id]['item_id'] == item_id)\n    ].set_index('wm_yr_wk')['sell_price'].to_dict()\n    \n    price = np.full(dates_df.shape[0], np.nan)\n    for i in range(wm_yr_wk.shape[0]):\n        week = wm_yr_wk[i]\n        if week in week_to_price:\n            price[i] = week_to_price[week]\n    \n    item_price_df = pd.DataFrame(data={'price': price})\n    item_price_df = item_price_df.fillna(method='ffill').fillna(method='bfill')\n\n    assert item_price_df['price'].isna().sum() == 0\n    assert item_price_df.shape == (dates_df.shape[0], 1)\n\n    # norm_price = item_price_df['price']\n    # item_price_df['price'] \/= np.linspace(1.00, 1.05, num=item_price_df.shape[0])  # inflation\n    norm_price = item_price_df['price'].to_numpy()\n    \n    assert norm_price.shape == (dates_df.shape[0],)\n    return norm_price\n\n\ndef get_is_snap(item_id, store_id, dates_df):\n    assert 'FOODS' in item_id\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    if store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4']:\n        return dates_df['snap_CA'].to_numpy()\n    elif store_id in ['TX_1', 'TX_2', 'TX_3']:\n        return dates_df['snap_TX'].to_numpy()\n    elif store_id in ['WI_1', 'WI_2', 'WI_3']:\n        return dates_df['snap_WI'].to_numpy()\n\n    assert False\n    return None\n    \n    \ndef get_week_days_features(item_id, store_id, dates_df):\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    return pd.DataFrame(\n        index=dates_df['d'],\n        data={\n            'is_Monday': (dates_df['weekday'] == 'Monday').astype(int).to_numpy(),\n            'is_Tuesday': (dates_df['weekday'] == 'Tuesday').astype(int).to_numpy(),\n            'is_Wednesday': (dates_df['weekday'] == 'Wednesday').astype(int).to_numpy(),\n            'is_Thursday': (dates_df['weekday'] == 'Thursday').astype(int).to_numpy(),\n            'is_Friday': (dates_df['weekday'] == 'Friday').astype(int).to_numpy(),\n            'is_Saturday': (dates_df['weekday'] == 'Saturday').astype(int).to_numpy()\n        }\n    )\n    \n    \ndef get_event_features(item_id, store_id, dates_df):\n    assert len(item_id.split('_')) == 3\n    assert store_id in ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n    assert dates_df.shape == (1604, 14)\n    \n    events_df = dates_df[['date', 'd', 'event_type_1', 'event_type_2']].copy()\n    events_df['tomorrow_event_type_1'] = events_df['event_type_1'].shift(periods=-1)\n    events_df['tomorrow_event_type_2'] = events_df['event_type_2'].shift(periods=-1)\n    \n    return pd.DataFrame(\n        index=events_df['d'],\n        data={\n            'is_today_religious': (\n                (events_df['event_type_1'] == 'Religious') |\n                (events_df['event_type_2'] == 'Religious')\n            ).astype(int).to_numpy(),\n            'is_today_national': (\n                (events_df['event_type_1'] == 'National') |\n                (events_df['event_type_2'] == 'National')\n            ).astype(int).to_numpy(),\n            'is_today_cultural': (\n                (events_df['event_type_1'] == 'Cultural') |\n                (events_df['event_type_2'] == 'Cultural')\n            ).astype(int).to_numpy(),\n            'is_today_sporting': (\n                (events_df['event_type_1'] == 'Sporting') |\n                (events_df['event_type_2'] == 'Sporting')\n            ).astype(int).to_numpy(),\n            'is_tomorrow_religious': (\n                (events_df['tomorrow_event_type_1'] == 'Religious') |\n                (events_df['tomorrow_event_type_2'] == 'Religious')\n            ).astype(int).to_numpy(),\n            'is_tomorrow_national': (\n                (events_df['tomorrow_event_type_1'] == 'National') |\n                (events_df['tomorrow_event_type_2'] == 'National')\n            ).astype(int).to_numpy(),\n            'is_tomorrow_cultural': (\n                (events_df['tomorrow_event_type_1'] == 'Cultural') |\n                (events_df['tomorrow_event_type_2'] == 'Cultural')\n            ).astype(int).to_numpy(),\n            'is_tomorrow_sporting': (\n                (events_df['tomorrow_event_type_1'] == 'Sporting') |\n                (events_df['tomorrow_event_type_2'] == 'Sporting')\n            ).astype(int).to_numpy()\n        }\n    )\n\n\ndef get_item_X_y(item, is_debug):\n    assert len(item.split('_')) == 5\n    \n    dates_df = calender_df.iloc[365:]\n    \n    item_parts = item.split('_')\n    item_id = item_parts[0] + '_' + item_parts[1] + '_' + item_parts[2]\n    store_id = item_parts[3] + '_' + item_parts[4]\n    \n    df = pd.DataFrame(\n        index=dates_df['d'].to_numpy(),\n        data={\n            'avg_item_n_sold_prev_month': get_avg_item_n_sold_prev_month(item_id, store_id, dates_df),\n            'item_n_sold_year_ago': get_item_n_sold_year_ago(item_id, store_id, dates_df),\n            'price': get_item_price(item_id, store_id, dates_df)\n        }\n    )\n    \n    if 'FOODS' in item:\n        df['is_snap'] = get_is_snap(item_id, store_id, dates_df)\n        \n    df = pd.concat([\n        df,\n        get_week_days_features(item_id, store_id, dates_df),\n        get_event_features(item_id, store_id, dates_df)\n    ], axis=1)\n    assert df.isna().sum().sum() == 0\n    \n    features_to_drop = []\n    for feature in df.columns:\n        if len(df[feature].unique()) <= 1:\n            features_to_drop.append(feature)\n    df = df.drop(features_to_drop, axis=1)\n    if is_debug:\n        print('Features', features_to_drop, 'have been dropped')\n    \n    target = train_df[\n        train_df['id'] == item + '_evaluation'\n    ][\n        ['d_' + str(i) for i in range(366, 1942)]\n    ].to_numpy()[0]\n    assert target.shape == (1576,)\n    target = np.concatenate([target, np.full(28, np.nan)])\n    df['target'] = target\n\n    return df\n\"\"\"\nFunctions to train a model (one model for each item):\n\"\"\"\ndef plot_feature_importances(model, features):\n    assert len(model.coef_) == len(features)\n    plt.figure(figsize=(12, 4))\n    plt.title('FEATURE IMPORTANCES')\n    sns.barplot(x=model.coef_, y=features)\n    \n    \ndef plot_public_test(y_true, y_pred):\n    assert y_true.shape == y_pred.shape == (28,)\n    plt.figure(figsize=(14, 3))\n    plt.title('PUBLIC TEST')\n    plt.plot([i for i in range(1, 29)], y_true, label='true')\n    plt.plot([i for i in range(1, 29)], y_pred, label='pred')\n    plt.legend()\n\n\ndef train_item_model(item, is_debug):\n    df = get_item_X_y(item, is_debug)\n    assert df.shape[0] == 1604\n\n    X = df.drop(['target'], axis=1)\n    y = df['target']\n    \n    X_train = X.loc[['d_' + str(i) for i in range(366, 1914)]]  # train\n    y_train = y.loc[['d_' + str(i) for i in range(366, 1914)]]  # train\n    assert X_train.shape[0] == y_train.shape[0] == 1548\n    \n    X_valid = X.loc[['d_' + str(i) for i in range(1914, 1942)]]  # public test\n    y_valid = y.loc[['d_' + str(i) for i in range(1914, 1942)]]  # public test\n    X_test = X.loc[['d_' + str(i) for i in range(1942, 1970)]]  # private test\n    assert X_valid.shape[0] == y_valid.shape[0] == X_test.shape[0] == 28\n    \n    scaler = StandardScaler()\n    X_train = scaler.fit_transform(X_train)  # train\n    X_valid = scaler.transform(X_valid)  # public test\n    X_test = scaler.transform(X_test)  # private test\n    \n    model = Ridge()\n    model.fit(X_train, y_train)\n    \n    y_valid_pred = model.predict(X_valid)\n    y_valid_pred[y_valid_pred < 0] = 0\n    y_valid_pred[y_valid_pred > y.max()] = y.max()\n    \n    y_test_pred = model.predict(X_test)\n    y_test_pred[y_test_pred < 0] = 0\n    y_test_pred[y_test_pred > y.max()] = y.max()\n    \n    if is_debug:\n        plot_feature_importances(model, X.columns)\n        plot_public_test(y_valid, y_valid_pred)\n        print('PUBLIC TEST: mean_absolute_error =', mean_absolute_error(y_valid, y_valid_pred))\n    \n    return y_valid_pred, y_test_pred\n\"\"\"\nLet's take a look at one random dataframe:\n\"\"\"\nget_item_X_y('HOBBIES_1_004_CA_1', is_debug=True)\n\"\"\"\n# **Model for one random item**\n\"\"\"\ntrain_item_model('HOBBIES_1_004_CA_1', is_debug=True)\n\"\"\"\n# **Models for all items**\n\"\"\"\nsubmission = pd.read_csv(os.path.join(INPUT_DIR, 'sample_submission.csv'))\nfor i in tqdm.tqdm(range(train_df.shape[0])):\n    item = train_df.iloc[i]['item_id'] + '_' + train_df.iloc[i]['store_id']\n    public_test_y, private_test_y = train_item_model(item, is_debug=False)\n\n    submission.loc[\n        submission[submission['id'] == item + '_validation'].index,\n        ['F' + str(i) for i in range(1, 29)]\n    ] = public_test_y\n\n    submission.loc[\n        submission[submission['id'] == item + '_evaluation'].index,\n        ['F' + str(i) for i in range(1, 29)]\n    ] = private_test_y\nsubmission\nsubmission.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '4b14696feece32'}"}
{"id":"130845","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Any results you write to the current directory are saved as output.\nadmission = pd.read_csv('..\/input\/Admission_Predict.csv')\nadmission.head()\nadmission.info()\nadmission.isnull().sum()\ntarget = admission['Chance of Admit ']\ntarget.head()\ndf = admission.copy()\ndf.head()\ndf.nunique()\nsns.scatterplot(df['GRE Score'][:100],df['Chance of Admit '][:100],s=25,data=df);\ndf.corr()['Chance of Admit ']\ndf.drop(columns='Chance of Admit ',axis=1,inplace=True)\ndf.head()\ndf.set_index('Serial No.',inplace=True)\ndf.head()\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_valid,y_train,y_valid = train_test_split(df,target,random_state=0)\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\n\nlog_clf = LinearRegression().fit(X_train,y_train)\nlnr_clf = LinearRegression().fit(X_train,y_train)\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(log_clf.score(X_train,y_train)))\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(log_clf.score(X_valid,y_valid)))\nprint()\nprint('Accuracy of Linear regression classifier on test set: {:.3f}'.format(lnr_clf.score(X_train,y_train)))\nprint('Accuracy of Linear regression classifier on test set: {:.3f}'.format(lnr_clf.score(X_valid,y_valid)))\nfrom sklearn.tree import DecisionTreeRegressor\n\ndt_clf = DecisionTreeRegressor().fit(X_train, y_train)\n\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(dt_clf.score(X_train,y_train)))\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(dt_clf.score(X_valid,y_valid)))\n\"\"\"\nBy default the `n_neighbors` value in KNN is 5\n\"\"\"\nfrom sklearn.neighbors import KNeighborsRegressor\n\nknn_clf = KNeighborsRegressor().fit(X_train, y_train)\n\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(knn_clf.score(X_train,y_train)))\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(knn_clf.score(X_valid,y_valid)))\n\"\"\"\nThe above putput is an example of overfitting\n\"\"\"\n\"\"\"\nBy default the `n_neighbors` value to 8 and we can crealy see that we have avoided overfitting to some extent\n\"\"\"\nfrom sklearn.neighbors import KNeighborsRegressor\n\nknn_clf = KNeighborsRegressor(n_neighbors=8).fit(X_train, y_train)\n\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(knn_clf.score(X_train,y_train)))\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(knn_clf.score(X_valid,y_valid)))\nfrom sklearn.svm import SVR\n\nsvc_reg = SVR(gamma='auto').fit(X_train,y_train)\n\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(svc_reg.score(X_train,y_train)))\nprint('Accuracy of Logistic regression classifier on test set: {:.3f}'.format(svc_reg.score(X_valid,y_valid)))","meta":"{'source': 'AI4Code', 'id': 'f0996e6ebc5b6a'}"}
{"id":"106520","text":"\"\"\"\n# Extract Measurements \n\n---\n\nAround 20% of the products in the dataset contain some kind of measurement (24mm Tape, 980gr powder, 1 kg coffee). \n\nA King size bed is 76\u201d x 80\u201d and is also known as an Eastern King bed. A California King bed, marketed toward taller people, is 72\u201d x 84\u201d. If you can extract measurements, you can differentiate between 100 gram coffee vs 250 gm coffee, 8 pack coke vs 6 pack coke, or 32 GB iphone vs 64 GB iphone. Over 6000 items in the listing have at least one measurement in them.\n\n\"\"\"\n\"\"\"\n### If you fork or use this notebook, do leave an upvote!\n\"\"\"\nimport pandas as pd \n\ntrain = pd.read_csv('..\/input\/shopee-product-matching\/train.csv')\nlabel_to_images = train.groupby('label_group').posting_id.unique().to_dict()\ntrain['target'] = train.label_group.apply(lambda label: label_to_images[label])\ntrain.sample(10)\nimport re \ndef is_measurement(word): \n    measurement_cats = ['kg', 'g', 'cm', 'pcs', 'gb', 'ml', 'mm', 'gr', 'gram']\n    for m in measurement_cats: \n        pat = '(\\d+)' + m + ''\n        res = re.findall(pat, word)\n        if res != []: \n            return f' {m} '.join(res) + ' ' + m\n\n    for m in measurement_cats: \n        pat = '(\\d+) ' + m + ''\n        res = re.findall(pat, word)\n        if res != []: \n            return f' {m} '.join(res) + ' ' + m\n        \n        \n    return False \n\ntrain['measurement'] = train.title.apply(is_measurement)\nnum_products_with_measurement = len(train) - (train.measurement == False).sum()\nprint(f'{num_products_with_measurement} products containing measurements found!')\n\"\"\"\n#### If you have any suggestions or improvements, do comment below. This is still primitive code and misses some measurements. Also don't forget to upvote!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c3ab58ee3a7825'}"}
{"id":"9197","text":"\"\"\"\nWelcome to my kernel\nSkin cancer is the most common human malignancy, is primarily diagnosed visually, beginning with an initial clinical screening and followed potentially by dermoscopic analysis, a biopsy and histopathological examination. Automated classification of skin lesions using images is a challenging task owing to the fine-grained variability in the appearance of skin lesions.\n\nThis the HAM10000 (\"Human Against Machine with 10000 training images\") dataset.It consists of 10015 dermatoscopicimages which are released as a training set for academic machine learning purposes and are publiclyavailable through the ISIC archive. This benchmark dataset can be used for machine learning and for comparisons with human experts.\n\nIt has 7 different classes of skin cancer which are listed below :\n1. Melanocytic nevi\n2. Melanoma\n3. Benign keratosis-like lesions\n4. Basal cell carcinoma\n5. Actinic keratoses\n6. Vascular lesions\n7. Dermatofibroma\n\"\"\"\n\"\"\"\n# ***Objective :***\n\n   Create an online tool that can tell doctors and lab technologists the three highest probability diagnoses for a given skin lesion.    This will help them quickly identify high priority patients and speed up their workflow. The app should produce a result in less      than 3 seconds. To ensure privacy the images must be pre-processed and analysed locally and never be uploaded to an external          server.\n\"\"\"\n#importing required libraries\nfrom numpy.random import seed\nseed(42)\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport tensorflow\ntensorflow.random.set_seed(42)\n\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nimport itertools\nimport shutil\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\"\"\"\n# **LABELS :**\n\n**1. Melanocytic nevi (nv) -**\n\nMelanocytic nevi are benign neoplasms of melanocytes and appear in a myriad of variants, which all are included in our series. The variants may differ significantly from a dermatoscopic point of view.\n\n[6705 images]\n\n**2. Melanoma (mel) -**\n\nMelanoma is a malignant neoplasm derived from melanocytes that may appear in different variants. If excised in an early stage it can be cured by simple surgical excision. Melanomas can be invasive or non-invasive (in situ). We included all variants of melanoma including melanoma in situ, but did exclude non-pigmented, subungual, ocular or mucosal melanoma.\n\n[1113 images]\n\n**3. Benign keratosis-like lesions (bkl) -**\n\n\"Benign keratosis\" is a generic class that includes seborrheic ker- atoses (\"senile wart\"), solar lentigo - which can be regarded a flat variant of seborrheic keratosis - and lichen-planus like keratoses (LPLK), which corresponds to a seborrheic keratosis or a solar lentigo with inflammation and regression [22]. The three subgroups may look different dermatoscop- ically, but we grouped them together because they are similar biologically and often reported under the same generic term histopathologically. From a dermatoscopic view, lichen planus-like keratoses are especially challeng- ing because they can show morphologic features mimicking melanoma [23] and are often biopsied or excised for diagnostic reasons.\n\n[1099 images]\n\n**4. Basal cell carcinoma (bcc) -**\n\nBasal cell carcinoma is a common variant of epithelial skin cancer that rarely metastasizes but grows destructively if untreated. It appears in different morphologic variants (flat, nodular, pigmented, cystic, etc) [21], which are all included in this set.\n\n[514 images]\n\n**5. Actinic keratoses (akiec) -**\n\nActinic Keratoses (Solar Keratoses) and intraepithelial Carcinoma (Bowen\u2019s disease) are common non-invasive, variants of squamous cell car- cinoma that can be treated locally without surgery. Some authors regard them as precursors of squamous cell carcinomas and not as actual carci- nomas. There is, however, agreement that these lesions may progress to invasive squamous cell carcinoma - which is usually not pigmented. Both neoplasms commonly show surface scaling and commonly are devoid of pigment. Actinic keratoses are more common on the face and Bowen\u2019s disease is more common on other body sites. Because both types are in- duced by UV-light the surrounding skin is usually typified by severe sun damaged except in cases of Bowen\u2019s disease that are caused by human papilloma virus infection and not by UV. Pigmented variants exists for Bowen\u2019s disease [19] and for actinic keratoses [20]. Both are included in this set.\n\n[327 images]\n\n**6. Vascular lesions (vasc) -**\n\nVascular skin lesions in the dataset range from cherry angiomas to angiokeratomas [25] and pyogenic granulomas [26]. Hemorrhage is also included in this category.\n\n[142 images]\n\n**7. Dermatofibrom (df) -**\n\nDermatofibroma is a benign skin lesion regarded as either a benign proliferation or an inflammatory reaction to minimal trauma. It is brown often showing a central zone of fibrosis dermatoscopically [24].\n\n[115 images]\n\n\n[Total images = 10015]\n\"\"\"\n\"\"\"\n# **Create a directory structure :**\n\"\"\"\n#Create a Base Directory\nbase_dir = 'Base_Directory'\nos.mkdir(base_dir)\n\n#creating folders inside Base Directory\ntrain_dir = os.path.join(base_dir, 'Train_Directory')\nos.mkdir(train_dir)\nval_dir = os.path.join(base_dir, 'Validation_Directory')\nos.mkdir(val_dir)\n\n#creating separate folders for each label class in both train and validation directory\nnv = os.path.join(train_dir, 'nv')\nos.mkdir(nv)\nmel = os.path.join(train_dir, 'mel')\nos.mkdir(mel)\nbkl = os.path.join(train_dir, 'bkl')\nos.mkdir(bkl)\nbcc = os.path.join(train_dir, 'bcc')\nos.mkdir(bcc)\nakiec = os.path.join(train_dir, 'akiec')\nos.mkdir(akiec)\nvasc = os.path.join(train_dir, 'vasc')\nos.mkdir(vasc)\ndf = os.path.join(train_dir, 'df')\nos.mkdir(df)\n\n# create new folders inside val_dir\nnv = os.path.join(val_dir, 'nv')\nos.mkdir(nv)\nmel = os.path.join(val_dir, 'mel')\nos.mkdir(mel)\nbkl = os.path.join(val_dir, 'bkl')\nos.mkdir(bkl)\nbcc = os.path.join(val_dir, 'bcc')\nos.mkdir(bcc)\nakiec = os.path.join(val_dir, 'akiec')\nos.mkdir(akiec)\nvasc = os.path.join(val_dir, 'vasc')\nos.mkdir(vasc)\ndf = os.path.join(val_dir, 'df')\nos.mkdir(df)\n\"\"\"\n# Data Exploration\n\"\"\"\n#getting the metadata of the dataset\n\nmetadata = pd.read_csv('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_metadata.csv')\nmetadata.head(10)\n#Skin Cancer by class\ng = sns.catplot(x=\"dx\", kind=\"count\", palette='bright', data=metadata)\ng.fig.set_size_inches(16, 5)\n\ng.ax.set_title('Skin Cancer by Class', fontsize=20)\ng.set_xlabels('Skin Cancer Class', fontsize=14)\ng.set_ylabels('Frequency of Occurance', fontsize=14)\n\"\"\"\nThis graph shows the dataset has a major problem of class imbalance\n\"\"\"\n#Skin Cancer by sex\ng = sns.catplot(x=\"dx\", kind=\"count\", hue=\"sex\", palette='coolwarm', data=metadata)\ng.fig.set_size_inches(16, 5)\n\ng.ax.set_title('Skin Cancer by Sex', fontsize=20)\ng.set_xlabels('Skin Cancer Class', fontsize=14)\ng.set_ylabels('Frequency of Occurance', fontsize=14)\ng._legend.set_title('Sex')\n#Skin Cancer by age\ng = sns.catplot(x=\"dx\", kind=\"count\", hue=\"age\", palette='bright', data=metadata)\ng.fig.set_size_inches(16, 9)\n\ng.ax.set_title('Skin Cancer by Age', fontsize=20)\ng.set_xlabels('Skin Cancer Class', fontsize=14)\ng.set_ylabels('Frequency of Occurance', fontsize=14)\ng._legend.set_title('Age')\n# Skin Cancer occurence body localization\ng = sns.catplot(x=\"dx\", kind=\"count\", hue=\"localization\", palette='bright', data=metadata)\ng.fig.set_size_inches(16, 9)\n\ng.ax.set_title('Skin Cancer Localization', fontsize=20)\ng.set_xlabels('Skin Cancer Class', fontsize=14)\ng.set_ylabels('Frequency of Occurance', fontsize=14)\ng._legend.set_title('Localization')\n\"\"\"\n# **Splitting data into training and validation sets :**\n\"\"\"\n# this will tell us how many images are associated with each lesion_id\ndf = metadata.groupby('lesion_id').count()\n\n# now we filter out lesion_id's that have only one image associated with it\ndf = df[df['image_id'] == 1]\n\ndf.reset_index(inplace=True)\n\ndf.head(10)\n# here we identify lesion_id's that have duplicate images and those that have only one image.\n\ndef identify_duplicates(x):\n    unique_list = list(df['lesion_id'])\n    if x in unique_list:\n        return 'no_duplicates'\n    else:\n        return 'has_duplicates'\n    \n# create a new colum that is a copy of the lesion_id column\nmetadata['duplicates'] = metadata['lesion_id']\n# apply the function to this new column\nmetadata['duplicates'] = metadata['duplicates'].apply(identify_duplicates)\n\nmetadata.head(10)\nmetadata.duplicates.value_counts()\n#Now we filter out the images that don't have duplicates\ndf = metadata[metadata.duplicates == 'no_duplicates']\ndf.shape\nlabels = df['dx']\n_, validation_set = train_test_split(df, test_size=0.17, random_state=42, stratify=labels)\nvalidation_set.shape\n#creating a training set that excludes the validation set\n\n# This function identifies if an image is part of the train\n# or val set.\ndef identify_val_rows(x):\n    # create a list of all the lesion_id's in the val set\n    val_list = list(validation_set['image_id'])\n    \n    if str(x) in val_list:\n        return 'val'\n    else:\n        return 'train'\n\n# identify train and val rows\n\n# create a new column that is a copy of the image_id column\nmetadata['train_or_val'] = metadata['image_id']\n# apply the function to this new column\nmetadata['train_or_val'] = metadata['train_or_val'].apply(identify_val_rows)\n   \n# filter out train rows\ntraining_set = metadata[metadata['train_or_val'] == 'train']\n\n#Dropping the unwanted columns\ntraining_set.drop(['train_or_val', 'duplicates'], axis=1, inplace=True)\nvalidation_set.drop(['duplicates'], axis=1, inplace=True)\n\nprint(training_set.shape)\nprint(validation_set.shape)\n\"\"\"\n# **Transfer the images into the folders**\n\"\"\"\n#setting image_id as the index of the metadata\nmetadata.set_index('image_id', inplace=True)\n\n#getting list of images in each of the 2 folders\nfolder1 = os.listdir('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_1')\nfolder2 = os.listdir('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_2')\n\n#getting list of training and validation images\ntrain_list = list(training_set['image_id'])\nval_list = list(validation_set['image_id'])\n\n#transferring the training images\nfor image in train_list:\n    filename = image + '.jpg'\n    label = metadata.loc[image, 'dx']\n    \n    if filename in folder1:\n        source = os.path.join('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_1', filename)\n    elif filename in folder2:\n        source = os.path.join('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_2', filename)\n    \n    destination = os.path.join(train_dir, label, filename)\n    shutil.copyfile(source, destination)   #copy the image from source to destination\n\n#transferring the validation images\nfor image in val_list:\n    filename = image + '.jpg'\n    label = metadata.loc[image, 'dx']\n    \n    if filename in folder1:\n        source = os.path.join('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_1', filename)\n    elif filename in folder2:\n        source = os.path.join('..\/input\/skin-cancer-mnist-ham10000\/HAM10000_images_part_2', filename)\n    \n    destination = os.path.join(val_dir, label, filename)\n    shutil.copyfile(source, destination)   #copy the image from source to destination\n# check how many train images we have in each folder\n\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/akiec')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/mel')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/bcc')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/bkl')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/df')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/nv')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/vasc')))\n# check how many val images we have in each folder\n\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/nv')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/mel')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/bkl')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/bcc')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/akiec')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/vasc')))\nprint(len(os.listdir('.\/Base_Directory\/Validation_Directory\/df')))\n\"\"\"\n# **Image augumentation**\n\"\"\"\n#Since there is a class imbalance we can try to augment images of the class that has very less images\nclass_list = ['mel', 'bkl', 'bcc', 'akiec', 'vasc', 'df']\n\n\nfor image_class in class_list:\n    aug_dir = 'Augmented_Directory'\n    os.mkdir(aug_dir)        #Creating a augumentation directory\n    img_dir = os.path.join(aug_dir, 'Image_Directory')\n    os.mkdir(img_dir)\n    \n    #collecting all the images that needs to be augumented into a single folder 'Image_Directory'\n    image_list = os.listdir('.\/Base_Directory\/Train_Directory\/' + image_class)\n    for filename in image_list:\n        source = os.path.join('.\/Base_Directory\/Train_Directory', image_class, filename)\n        destination = os.path.join(img_dir, filename)\n        shutil.copyfile(source, destination)\n    path = aug_dir\n    save_path = '.\/Base_Directory\/Train_Directory\/' + image_class\n    \n    #Creating a Data Generator\n    datagen = ImageDataGenerator(rotation_range=180,\n                                 width_shift_range=0.1,\n                                 height_shift_range=0.1,\n                                 zoom_range=0.1,\n                                 horizontal_flip=True,\n                                 vertical_flip=True,\n                                 #brightness_range=(0.9,1.1),\n                                 fill_mode='nearest')\n    batch_size=50\n    aug_data = datagen.flow_from_directory(path, save_to_dir=save_path, save_format='jpg',\n                                           target_size=(224, 224), batch_size=batch_size)\n    images_wanted = 6000   #total number of images we require for each class\n    num_files = len(os.listdir(img_dir))\n    num_batch = int(np.ceil((images_wanted - num_files)\/batch_size))\n    \n    #Run the generator to create about 6000 augumented images\n    for i in range(num_batch):\n        imgs, labels = next(aug_data)\n    \n    shutil.rmtree(aug_dir)  #deleting the temporary directory with the raw images\n#The number of images per class we now have for training\n\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/nv')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/mel')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/bkl')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/bcc')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/akiec')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/vasc')))\nprint(len(os.listdir('.\/Base_Directory\/Train_Directory\/df')))\n\"\"\"\n# **Visualizing the images :**\n\"\"\"\ndef plots(ims, figsize=(20,10), rows=5, interp=False, titles=None): # 12,6\n    if type(ims[0]) is np.ndarray:\n        ims = np.array(ims).astype(np.uint8)\n        if (ims.shape[-1] != 3):\n            ims = ims.transpose((0,2,3,1))\n    f = plt.figure(figsize=figsize)\n    cols = len(ims)\/\/rows if len(ims) % 2 == 0 else len(ims)\/\/rows + 1\n    for i in range(len(ims)):\n        sp = f.add_subplot(rows, cols, i+1)\n        sp.axis('Off')\n        if titles is not None:\n            sp.set_title(titles[i], fontsize=16)\n        plt.imshow(ims[i], interpolation=None if interp else 'none')\n        \nplots(imgs, titles=None) # titles=labels will display the image labels\n\"\"\"\n# **Set up the generators :**\n\"\"\"\ntrain_path = '.\/Base_Directory\/Train_Directory'\nvalid_path = '.\/Base_Directory\/Validation_Directory'\n\nnum_train_samples = len(training_set)\nnum_val_samples = len(validation_set)\ntrain_batch_size = 10\nval_batch_size = 10\nimage_size = 224\n\ntrain_steps = np.ceil(num_train_samples\/ train_batch_size)\nval_steps = np.ceil(num_val_samples\/ val_batch_size)\n#same pre-processing that was applied to the original rgb Imagenet images that were used to train mobilenet is used to pre-process\n#this data.\ndatagen = ImageDataGenerator(\n            preprocessing_function=tensorflow.keras.applications.mobilenet.preprocess_input)\n\ntrain_batches = datagen.flow_from_directory(train_path, target_size=(image_size,image_size), batch_size=train_batch_size)\n\nvalid_batches = datagen.flow_from_directory(valid_path, target_size=(image_size,image_size), batch_size=val_batch_size)\n\ntest_batches = datagen.flow_from_directory(valid_path, target_size=(image_size,image_size), batch_size=1, shuffle=False)\n\"\"\"\n# **Modifying the MobileNet model**\n\"\"\"\n# create a copy of a mobilenet model\nmobile = tensorflow.keras.applications.mobilenet.MobileNet()\nmobile.summary()\nprint('The number of layers MobileNet has is ', len(mobile.layers))\n# CREATE THE MODEL ARCHITECTURE\n\n# Exclude the last 5 layers of the above model.\n# This will include all layers up to and including global_average_pooling2d_1\nx = mobile.layers[-6].output\n\n# Create a new dense layer for predictions\n# 7 corresponds to the number of classes\nx = Dropout(0.25)(x)\npredictions = Dense(7, activation='softmax')(x)\n\n# inputs=mobile.input selects the input layer, outputs=predictions refers to the\n# dense layer we created above.\n\nmodel = Model(inputs=mobile.input, outputs=predictions)\nmodel.summary()\n\"\"\"\n# **Training the Model :**\n\"\"\"\n# Define Top2 and Top3 Accuracy\n\nfrom tensorflow.keras.metrics import categorical_accuracy, top_k_categorical_accuracy\n\ndef top_3_accuracy(y_true, y_pred):\n    return top_k_categorical_accuracy(y_true, y_pred, k=3)\n\ndef top_2_accuracy(y_true, y_pred):\n    return top_k_categorical_accuracy(y_true, y_pred, k=2)\nmodel.compile(Adam(lr=0.01), loss='categorical_crossentropy', \n              metrics=[categorical_accuracy, top_2_accuracy, top_3_accuracy])\n#Get the labels that are associated with each index\nprint(valid_batches.class_indices)\n# Add weights to try to make the model more sensitive to melanoma\n\nclass_weights={\n    0: 1.0, # akiec\n    1: 1.0, # bcc\n    2: 1.0, # bkl\n    3: 1.0, # df\n    4: 3.0, # mel   # Try to make the model more sensitive to Melanoma.\n    5: 1.0, # nv\n    6: 1.0, # vasc\n}\nfilepath = \"model.h5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_top_3_accuracy', verbose=1, \n                             save_best_only=True, mode='max')\n\nreduce_lr = ReduceLROnPlateau(monitor='val_top_3_accuracy', factor=0.5, patience=2, \n                                   verbose=1, mode='max', min_lr=0.00001)\n                              \n                              \ncallbacks_list = [checkpoint, reduce_lr]\n\nhistory = model.fit_generator(train_batches, steps_per_epoch=train_steps, class_weight=class_weights, validation_data=valid_batches,\n                              validation_steps=val_steps, epochs=30, verbose=1, callbacks=callbacks_list)\n# get the metric names so we can use evaulate_generator\nmodel.metrics_names\n# Here the the last epoch will be used.\n\nval_loss, val_cat_acc, val_top_2_acc, val_top_3_acc = model.evaluate_generator(test_batches, steps=len(validation_set))\n\nprint('val_loss:', val_loss)\nprint('val_categorical_accuracy:', val_cat_acc)\nprint('val_top_2_accuracy:', val_top_2_acc)\nprint('val_top_3_accutacy:', val_top_3_acc)\n\"\"\"\n# **Plotting the training curves**\n\"\"\"\n# display the loss and accuracy curves\n\nimport matplotlib.pyplot as plt\n\nacc = history.history['categorical_accuracy']\nval_acc = history.history['val_categorical_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\ntrain_top2_acc = history.history['top_2_accuracy']\nval_top2_acc = history.history['val_top_2_accuracy']\ntrain_top3_acc = history.history['top_3_accuracy']\nval_top3_acc = history.history['val_top_3_accuracy']\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, acc, 'bo', label='Training cat acc')\nplt.plot(epochs, val_acc, 'b', label='Validation cat acc')\nplt.title('Training and validation cat accuracy')\nplt.legend()\nplt.figure()\n\n\nplt.plot(epochs, train_top2_acc, 'bo', label='Training top2 acc')\nplt.plot(epochs, val_top2_acc, 'b', label='Validation top2 acc')\nplt.title('Training and validation top2 accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, train_top3_acc, 'bo', label='Training top3 acc')\nplt.plot(epochs, val_top3_acc, 'b', label='Validation top3 acc')\nplt.title('Training and validation top3 accuracy')\nplt.legend()\n\n\nplt.show()\n\"\"\"\nThe validation set results are greater than training set because when training, a percentage of the features are set to zero (25% in this case as I'm using Dropout(0.25)). When testing, all features are used (and are scaled appropriately). So the model at test time is more robust - and can lead to higher testing accuracies.\n\"\"\"\n\"\"\"\n# Creating a confusion matrix to analyse better :\n\"\"\"\ntest_labels = test_batches.classes\nprint(test_batches.class_indices)\n#making a prediction on the test batch\npredictions = model.predict(test_batches, steps=len(validation_set), verbose=1)\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    print(cm)\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.tight_layout()\n#plotting confusion matrix\ncm = confusion_matrix(test_labels, predictions.argmax(axis=1))\ncm_plot_labels = ['akiec', 'bcc', 'bkl', 'df', 'mel','nv', 'vasc']\nplot_confusion_matrix(cm, cm_plot_labels, title='Confusion Matrix')\n\"\"\"\n# Classification Report\n\"\"\"\n# Get the index of the class with the highest probability score\ny_pred = np.argmax(predictions, axis=1)\n\n# Get the labels of the test images.\ny_true = test_batches.classes\nfrom sklearn.metrics import classification_report\n\n# Generate a classification report\nreport = classification_report(y_true, y_pred, target_names=cm_plot_labels)\n\nprint(report)\n# End of Model Building\n### ===================================================================================== ###\n# Convert the Model from Keras to Tensorflow.js\n!pip install tensorflowjs --ignore-installed\nimport tensorflowjs as tfjs\nos.mkdir('TFJS_Dir')\n\ntfjs.converters.save_keras_model(model, 'TFJS_Dir')\n# Deleting the image data directory to prevent a Kaggle error.\nshutil.rmtree(base_dir)","meta":"{'source': 'AI4Code', 'id': '1102c97998b802'}"}
{"id":"81830","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport plotly.express as px\nimport plotly.graph_objects as go\ndf = pd.read_csv(\"\/kaggle\/input\/country-regional-and-world-gdp\/gdp_csv.csv\")\n\ndf.head(10)\n\"\"\"\n**Finding out the names of the countries in the dataset**\n\"\"\"\ndf[\"Country Name\"].unique()\n\"\"\"\nSince the dataset is a mixture of regions and countries, it would make sense to seperate these into two sepeate datasets\n\"\"\"\n\"\"\"\n**Separating the dataset into \"regions\" and \"countries\" sub-datasets**\n\"\"\"\nregion = ['Arab World', 'Caribbean small states',\n       'Central Europe and the Baltics', 'Early-demographic dividend',\n       'East Asia & Pacific',\n       'East Asia & Pacific (excluding high income)',\n       'East Asia & Pacific (IDA & IBRD countries)', 'Euro area',\n       'Europe & Central Asia',\n       'Europe & Central Asia (excluding high income)',\n       'Europe & Central Asia (IDA & IBRD countries)', 'European Union',\n       'Fragile and conflict affected situations',\n       'Heavily indebted poor countries (HIPC)', 'High income',\n       'IBRD only', 'IDA & IBRD total', 'IDA blend', 'IDA only',\n       'IDA total', 'Late-demographic dividend',\n       'Latin America & Caribbean',\n       'Latin America & Caribbean (excluding high income)',\n       'Latin America & the Caribbean (IDA & IBRD countries)',\n       'Least developed countries: UN classification',\n       'Low & middle income', 'Low income', 'Lower middle income',\n       'Middle East & North Africa',\n       'Middle East & North Africa (excluding high income)',\n       'Middle East & North Africa (IDA & IBRD countries)',\n       'Middle income', 'North America', 'OECD members',\n       'Other small states', 'Pacific island small states',\n       'Post-demographic dividend', 'Pre-demographic dividend',\n       'Small states', 'South Asia', 'South Asia (IDA & IBRD)',\n       'Sub-Saharan Africa', 'Sub-Saharan Africa (excluding high income)',\n       'Sub-Saharan Africa (IDA & IBRD countries)', 'Upper middle income',\n       'World']\nregions = df[df['Country Name'].isin(region)]\nregions.reset_index(inplace=True, drop=True)\n\ncountries = df[~df['Country Name'].isin(region)]\ncountries.reset_index(inplace=True, drop=True)\nregions.head()\ncountries.head()\n\"\"\"\nThe focus of this notebook will be on the analysis of individual countries as opposed to regions, therefore only the dataset with individual countries will be cleaned and analysed from this point forward.\n\"\"\"\n\"\"\"\n**Finding out if each country has the same number of yearly data**\n\"\"\"\ncountries.groupby(\"Country Name\")[\"Year\"].count()\n\"\"\"\nEach country and region does not have the same number of yearly data since some countries have data going back 57 years while other countries have data going back only less than 27 years, subsequent analysis would not yield accurate results due to this mismatch. Therefore, it would make sense to create a sub-dataset with countries that have the same number of yearly data.\n\"\"\"\n\"\"\"\n**Creating a sub-dataset which only includes countries who have the latest GDP values from 2016**\n\"\"\"\ncountries2 = countries.groupby(\"Country Name\", as_index=False)[\"Year\"].max()\n\ncountries3 = countries2[countries2[\"Year\"]==2016]\n\ncountries4 = countries3[\"Country Name\"]\n\ncountries5 = countries[countries[\"Country Name\"].isin(countries4)]\n\ncountries5\n\"\"\"\n**Finding out which countries in the sub-dataset has the lowest number of years' worth of data and subsequently removing them so that we remain with an equal and sufficient amount of data for each country**\n\"\"\"\nmin_year = countries5.groupby(\"Country Name\", as_index=False)[\"Year\"].min()\n\nmin_year[\"Year\"].max()\n\"\"\"\n2013 would not be a good starting year for our analysis since it would only give us 4 years worth of data for each country, therefore we would need to remove this country and repeat this step till we are left with a starting year that would leave us with sufficient amount of data for each country.\n\"\"\"\nmin_year[min_year[\"Year\"]==2013]\ncountries6 = countries5[countries5[\"Country Name\"]!=\"Somalia\"]\n\nmin_year = countries6.groupby(\"Country Name\", as_index=False)[\"Year\"].min()\n\nmin_year[\"Year\"].max()\n\"\"\"\n2007 is still not a good starting year, therefore we will repeat the process\n\"\"\"\nmin_year[min_year[\"Year\"]==2007]\ncountries7 = countries6[countries5[\"Country Name\"]!=\"Nauru\"]\n\nmin_year = countries7.groupby(\"Country Name\", as_index=False)[\"Year\"].min()\n\nmin_year[\"Year\"].max()\nmin_year[min_year[\"Year\"]==2002]\ncountries8 = countries7[~countries7[\"Country Name\"].isin([\"American Samoa\",\"Guam\",\"Northern Mariana Islands\"])]\n\nmin_year = countries8.groupby(\"Country Name\", as_index=False)[\"Year\"].min()\n\nmin_year[\"Year\"].max()\nmin_year[min_year[\"Year\"]==2001]\ncountries9 = countries8[countries8[\"Country Name\"]!=\"Sao Tome and Principe\"]\n\nmin_year = countries9.groupby(\"Country Name\", as_index=False)[\"Year\"].min()\n\nmin_year[\"Year\"].max()\n\"\"\"\nI believe 2000 is a great starting year for our analysis since it gives us 17 years worth of data for each country\n\"\"\"\ncountry = countries9[countries9[\"Year\"]>=2000]\n\ncountry\n\"\"\"\n**Making sure that the new dataset does not have any missing years for each of the countries**\n\"\"\"\nmissing = country.groupby(\"Country Name\", as_index=False)[\"Year\"].count()\n\nmissing[missing[\"Year\"]!=17]\n\"\"\"\nSince the three countries above are missing some years as part of their data, they would need to be removed\n\"\"\"\n\"\"\"\n**Removing Afghanistan, Democratic Republic of Congo and Iraq from the dataset and creating our final dataset that will be used for the analysis**\n\"\"\"\ncountry_new = pd.DataFrame(country[~country[\"Country Name\"].isin([\"Afghanistan\",\"Congo, Dem. Rep.\",\"Iraq\"])])\n\ncountry_new.reset_index(drop=True, inplace=True)\n\ncountry_new[\"Country Name\"].nunique()\n\"\"\"\nThe new dataset has 181 countries and their corresponding 17 years worth of data from the year 2000 to 2016\n\"\"\"\ncountry_new.head()\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n**Finding out the top 15 countries with the highest GDP in 2016**\n\"\"\"\ncountries_2016 = country_new[country_new[\"Year\"]==2016]\n\ncountries_2016.sort_values(\"Value\", axis=0, ascending=False, inplace=True)\n\ncountries_2016.reset_index(drop=True, inplace=True)\n\ncountries_2016_highest = countries_2016.head(15)\n\ncountries_2016_highest\n\nfig = px.bar(countries_2016_highest, x=\"Country Name\", y=\"Value\", color=\"Country Name\",\n             color_discrete_sequence=px.colors.qualitative.Vivid)\n\nfig.update_layout(title_text=\"Top 15 Countries with the highest GDP (2016)\", title_font_size=22,\n                  height=800, width=980, yaxis_title=\"GDP($)\", xaxis_title=\"Country\",\n                  title_y=0.97, title_x=0.45)\n\nfig.show()\n\ncountries_2016_highest\n\"\"\"\n**Creating a Heatmap to represent countries GDPs in 2016**\n\"\"\"\nfig = px.choropleth(countries_2016, locations=\"Country Name\", locationmode='country names', color=\"Value\",\n                    color_continuous_scale=px.colors.sequential.Redor)\n\nfig.update_layout(title_text=\"Heatmap of GDPs for Countries in 2016\", title_font_size=24,\n                  height=800, width=1000, yaxis_title=\"GDP($)\", xaxis_title=\"Country\",\n                  title_y=0.85, title_x=0.45)\n\nfig.show()\n\"\"\"\nThe reason there are some countries that are unshaded is because we had removed some of them earlier to create a dataset with countries that have the same number of years worth of data\n\"\"\"\n\"\"\"\n**Finding out the trend of GDP from 2000 to 2016 for the top 15 countries with the highest GDP in 2016**\n\"\"\"\ncountries_highest_trend = country_new[country_new[\"Country Name\"].isin([\"United States\",\"China\",\"Japan\",\"Germany\",\"United Kingdom\",\n                                                                       \"France\",\"India\",\"Italy\",\"Brazil\",\"Canada\",\"Korea, Rep.\",\n                                                                       \"Russian Federation\",\"Spain\",\"Australia\",\"Mexico\"])]\n\nfig = px.bar(countries_highest_trend, x=\"Country Name\", y=\"Value\", color=\"Country Name\",\n             color_discrete_sequence=px.colors.qualitative.Dark24,\n             animation_frame=\"Year\", animation_group=\"Country Name\")\n\nfig.update_layout(title_text=\"Trends of Top 15 Countries with the highest GDP in 2016\", title_font_size=22,\n                  height=700, width=980, yaxis_title=\"GDP($)\", xaxis_title=\"Country\",\n                  title_y=0.97, title_x=0.45)\n\nfig.show()\n\n\"\"\"\nThe most important take-away from the graph above is the fact that in 2000, Japan had a higher GDP than that of China but because of China's high GDP growth rate, it overtook Japan after 2009\/2010. Furthermore, another important takeaway is that the United States has had the highest GDP in the world since 2000.\n\"\"\"\n\"\"\"\n**Creating a timeline graph that shows the trends of GDPs for the 181 countries in the dataset**\n\"\"\"\nfig = px.scatter(country_new, x=\"Country Name\", y=\"Value\", color=\"Country Name\",\n                 animation_frame=\"Year\", animation_group=\"Country Name\")\n\nfig.update_layout(title_text=\"GDP Trends of Countries (2000-2016)\", title_font_size=22,\n                  height=800, width=2000, yaxis_title=\"GDP($)\", xaxis_title=\"Country\",\n                  title_y=0.97, title_x=0.45)\n\nfig.show()\n\"\"\"\nThis timeline graph, though has countries squeezed together on the x-axis, reveals some important information. It shows how most countries are on the baseline of GDPs that are less than $100 billion, and most importantly, it reveals the countries that have moved away from that baseline since 2000 and have improved their GDPs drastically.This includes, apart from the top 15 countries mentioned in previous graphs, countries such as Argentina, Austria, Belgium, Chile, Colombia, Indonesia, Iran, Hong Kong, Malayisa and many more.\n\nWhat would help this analysis even further would be to see which countries have improved their GDPs the most during this time-period.\n\"\"\"\n\"\"\"\n**Finding out the countries with the highest GDP growth rates from 2000 to 2016**\n\"\"\"\ncountries_2000 = country_new[country_new[\"Year\"]==2000]\ncountries_2000.reset_index(drop=True, inplace=True)\n\ncountries_2016 = country_new[country_new[\"Year\"]==2016]\ncountries_2016.reset_index(drop=True, inplace=True)\n\ncountries_2000_value = pd.DataFrame(countries_2000[\"Value\"])\ncountries_2000_value.reset_index(drop=True, inplace=True)\n\nheader=[\"Value 2000\"]\ncountries_2000_value.columns = header\n\ncountries_2000_2016 = pd.concat([countries_2016, countries_2000_value], axis=1, ignore_index=False)\n\ncountries_2000_2016[\"GDP Growth Rate(%)\"] = ((countries_2000_2016[\"Value\"]-countries_2000_2016[\"Value 2000\"])\/countries_2000_2016[\"Value 2000\"])\n\ncountries_2000_2016.drop(labels=[\"Year\"], axis=1, inplace=True)\n\ncountries_2000_2016.sort_values(\"GDP Growth Rate(%)\", axis=0, ascending=False, kind='quicksort', inplace=True)\n\ntop_GDP = countries_2000_2016.head(15)\ntop_GDP.reset_index(drop=True, inplace=True)\n\nrounded = np.round(top_GDP[\"GDP Growth Rate(%)\"], decimals=2)\nrounded_GDP_growth = pd.DataFrame(rounded)\ntop_GDP[\"GDP Growth Rate(%)\"] = rounded_GDP_growth\n\n\nfig = px.bar(top_GDP, x=\"Country Name\", y=\"GDP Growth Rate(%)\", color=\"Country Name\",\n             color_discrete_sequence=px.colors.qualitative.Dark24, text=\"GDP Growth Rate(%)\")\n\nfig.update_layout(title_text=\"Top 15 Countries with the highest GDP Growth Rate % (2000-2016)\", title_font_size=22,\n                  height=700, width=980, yaxis_title=\"GDP Growth Rate(%)\", xaxis_title=\"Country\",\n                  title_y=0.97, title_x=0.45)\n\nfig2 = px.choropleth(countries_2000_2016, locations=\"Country Name\", locationmode='country names', color=\"GDP Growth Rate(%)\",\n                    color_continuous_scale=px.colors.sequential.Darkmint)\n\nfig2.update_layout(title_text=\"Heatmap of GDP Growth Rate % (2000-2016)\", title_font_size=24,\n                  height=800, width=1000, yaxis_title=\"GDP($)\", xaxis_title=\"Country\",\n                  title_y=0.85, title_x=0.45)\n\n\nfig.show()\nfig2.show()\n\ntop_GDP\n\"\"\"\nAs illustrated in the table and graphs above, the highest GDP growth rates from 2000 to 2016 were experienced by countries in Central & South East Asia and some countries in Sub-Saharan Africa.\n\"\"\"\n\"\"\"\n***I will be continuing this analysis further by creating a forecasting model to predict GDPs for the top 15 countries with the highest GDPs in 2016 for 2017, 2018 and 2019. Furthermore, I will be comparing these forecasts to the actual GDP values recorded for these countries, to gauge how accurate the model is.***\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9623f1327b3223'}"}
{"id":"54800","text":"pip install lifelines\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nfrom scipy import stats\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom lifelines import KaplanMeierFitter\nfrom lifelines.statistics import logrank_test\nfrom lifelines.statistics import multivariate_logrank_test\nfrom lifelines.statistics import pairwise_logrank_test\nfrom lifelines import CoxPHFitter\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\ndf = pd.read_csv('\/kaggle\/input\/telecom-churn\/telecom_churn.csv').reset_index()\ndf.head()\ndf.info()\n\"\"\"\n**Columns**:\n* Churn - 1 if customer cancelled service, 0 if not\n* AccountWeeks - number of weeks customer has had active account\n* ContractRenewal - 1 if customer recently renewed contract, 0 if not\n* DataPlan - 1 if customer has data plan, 0 if not\n* DataUsage - gigabytes of monthly data usage\n* CustServCalls - number of calls into customer service\n* DayMins - average daytime minutes per month\n* DayCalls - average number of daytime calls\n* MonthlyCharge - average monthly bill\n* OverageFee - largest overage fee in last 12 months\n* RoamMins - average number of roaming minutes\n\"\"\"\n\"\"\"\n**Create functions**\n\"\"\"\ndef countplot(data, title, title_x, annotate_x, palette):\n    \n    '''\n    : param data: categorical data.\n    : param title: chart title.\n    : param title_x: title location by x.\n    : param annotate_x: annotate location by x.\n    : param palette: colors.\n    : return bar chart   \n    '''\n    \n    fig = plt.figure(figsize = (8, 4))\n\n    ax = fig.add_axes([0, 0, 1, 1])\n\n    sns.countplot(\n        y = data,\n        palette = palette,\n        order = data.value_counts().index,\n        edgecolor = 'black',\n        lw = 2)\n\n    sns.despine(bottom = True)\n\n    plt.xticks([])\n    plt.yticks(\n        fontsize = 15,\n        color = 'black',\n        family = 'sans-serif')\n\n    plt.xlabel('')\n    plt.ylabel('')\n\n    for p in ax.patches:\n        width = p.get_width()\n        height = p.get_height()\n        x, y = p.get_xy() \n        ax.annotate('{:.0f}'.format(width), (annotate_x + width, y + height*0.5), ha='center', fontsize=15, color='black', family='sans-serif')\n\n    plt.title(\n        label = title,\n        fontsize = 20,\n        x = title_x,\n        y = 1.1,\n        family = 'sans-serif',\n        fontweight='bold')    \n\n    plt.show()\ndef stack_hist(categorial_data, data, palette, x_label, title, title_x):\n    \n    '''\n    : param categorial_data: categorical data.\n    : param data: numeric data.\n    : param palette: colors.\n    : param x_label: x_label name.\n    : param title: chart title.\n    : param title_x: title location by x.\n    : return stacked histogram   \n    '''\n    \n    plt.figure(figsize = (13, 6))\n\n    sns.histplot(\n        x=data,\n        hue=categorial_data.astype('str'),\n        palette=palette,\n        multiple='stack',\n        edgecolor='black')\n\n    sns.despine()\n\n    plt.xticks(\n        fontsize=15,\n        color='black',\n        family='sans-serif')\n    plt.yticks(\n        fontsize=15,\n        color='black',\n        family='sans-serif')\n\n    plt.xlabel(\n        xlabel=x_label,\n        fontsize=17,\n        color='black',\n        family='sans-serif',\n        fontweight='bold')\n    plt.ylabel(\n        ylabel='Count',\n        fontsize=17,\n        color='black',\n        family='sans-serif',\n        fontweight='bold')\n\n    plt.title(\n        label=title,\n        fontsize=20,\n        x=title_x,\n        y=1.1,\n        family='sans-serif',\n        fontweight='bold')\n\n    plt.legend([]).set_visible(False)\n\n    plt.show()\ndef stack_bar(data, column_1, column_2, palette, title, title_x):\n    \n    '''\n    : param data: data set.\n    : param column_1: first categorical data.\n    : param column_2: second categorical data.\n    : param palette: colors.\n    : param title: chart title.\n    : param title_x: title location by x.\n    : return stacked bar chart   \n    '''\n    \n    group = data \\\n    .groupby([column_1, column_2],as_index = False) \\\n    .agg({'index' : 'count'}) \\\n    .rename(columns={'index':'count'})\n\n    fig = plt.figure(figsize=(8, 4))\n\n    ax = fig.add_axes([0, 0, 1, 1])\n\n    sns.histplot(\n        x=group.iloc[:,0].astype('str'),\n        hue=group.iloc[:,1],\n        weights=group.iloc[:,2],\n        multiple='stack',\n        ax=ax,\n        palette=palette,\n        shrink=0.8,\n        edgecolor='black',\n        lw=2)\n\n    sns.despine(left=True)\n\n    plt.yticks([])\n    plt.xticks(\n        fontsize = 15,\n        color = 'black',\n        family = 'sans-serif')\n\n    plt.xlabel('')\n    plt.ylabel('')\n\n    plt.legend([]).set_visible(False)\n\n    for p in ax.patches:\n        width, height = p.get_width(), p.get_height()\n        x, y = p.get_xy() \n        ax.text(x+width\/2, \n                y+height\/2, \n                '{:.0f}'.format(height), \n                horizontalalignment='center', \n                verticalalignment='center',\n                fontsize=11,\n                color='white',\n                fontweight='bold',\n                family='sans-serif')\n\n    plt.title(\n        label=title,\n        fontsize=20,\n        x=title_x,\n        y=1.1,\n        family='sans-serif',\n        fontweight='bold')\n\n    plt.show()\ndef get_bootstrap(data_column_1, data_column_2, boot_it = 1000, statistic = np.mean, bootstrap_conf_level = 0.99):\n\n    '''\n    :param data_column_1: first group\n    :param data_column_2: second group\n    :param boot_it: number of bootstrap subsamples (by default - 1000)\n    :param statistic: statistic (by default - mean)\n    :param bootstrap_conf_level: significance level\n    :return p-value.\n    '''\n    \n    boot_len = max([len(data_column_1), len(data_column_2)])\n    boot_data = []\n    for i in (range(boot_it)): \n        samples_1 = data_column_1.sample(\n            boot_len, \n            replace = True \n        ).values\n        \n        samples_2 = data_column_2.sample(\n            boot_len, \n            replace = True\n        ).values\n        \n        boot_data.append(statistic(samples_1-samples_2)) \n        \n    pd_boot_data = pd.DataFrame(boot_data)\n        \n    left_quant = (1 - bootstrap_conf_level)\/2  \n    right_quant = 1 - (1 - bootstrap_conf_level) \/ 2  \n    ci = pd_boot_data.quantile([left_quant, right_quant]) \n        \n    p_1 = stats.norm.cdf(                 \n        x = 0, \n        loc = np.mean(boot_data), \n        scale = np.std(boot_data)\n    )\n    p_2 = stats.norm.cdf(\n        x = 0, \n        loc = -np.mean(boot_data), \n        scale = np.std(boot_data)\n    )\n    p_value = min(p_1, p_2) * 2       \n    \n    print(f'p-value - {p_value}')\ndef chi_2(alpha, data_1, data_2):\n    '''\n    :param alpha: significance level\n    :param data_1: first categorical data\n    :param alpha: second categorical data\n    :return result (reject\/no reject H0)\n    '''\n    print('Test chi2:')\n    alpha = alpha\n    p = stats.chi2_contingency(pd.crosstab(data_1, data_2))[1]\n    if p < 0.05:\n        print('Reject H0')\n    else:\n        print('No reject H0')\ncountplot(\n    data=df['Churn'],\n    title='Churn count',\n    title_x=0,\n    annotate_x=110,\n    palette=['#4869D6', '#FF7373'])\n\nprint(f\"Churn percentage - {round(len(df[df['Churn']==1]) \/ len(df)*100, 2)}%\")\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['AccountWeeks'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='AccountWeeks',\n    title='Duration by churn',\n    title_x=0.1\n    )\nprint(f'''AccountWeeks mean (No Churn) - {round(df[df['Churn']==0]['AccountWeeks'].mean())}\nAccountWeeks mean (Churn) - {round(df[df['Churn']==1]['AccountWeeks'].mean())}''')\nprint()\nprint(f'''std (No Churn) - {round(df[df['Churn']==0]['AccountWeeks'].std())}\nstd (Churn) - {round(df[df['Churn']==1]['AccountWeeks'].std())}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['AccountWeeks'], \n    data_column_2=df[df['Churn']==1]['AccountWeeks'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nThe duration distribution is close to normal. The distribution of the No Churn users is more variable.\n\nThe average duration of the No Churn users is less than 2 weeks, but the differences are not statistically significant.\n\"\"\"\nstack_bar(\n    data=df,\n    column_1='ContractRenewal',\n    column_2='Churn',\n    palette=['#4869D6', '#FF7373'],\n    title='Churn count by renewal contract',\n    title_x=0.35)\n\nchi_2(\n    alpha=0.01,\n    data_1=df['Churn'],\n    data_2=df['ContractRenewal'])\n\"\"\"\nThe Churn ratio among users who did not renew the contract does not differ much (~ 42%). However, the percentage of Churn users among those who extended the contract is significantly less than the share of remaining users.\n\nThe chi-square test showed that the variable has an effect on Churn.\n\"\"\"\nstack_bar(\n    data=df,\n    column_1='DataPlan',\n    column_2='Churn',\n    palette=['#4869D6', '#FF7373'],\n    title='Churn count by DataPlan',\n    title_x=0.2)\n\nchi_2(\n    alpha=0.01,\n    data_1=df['Churn'],\n    data_2=df['DataPlan'])\n\"\"\"\nThe percentage of Churn users is higher among those who do not have an Internet connection.\n\nThe chi-square test showed that the variable has an effect on Churn.\n\"\"\"\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['DataUsage'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='DataUsage',\n    title='DataUsage by churn',\n    title_x=0.1\n    )\nprint(f'''Average datause (No Churn) - {round(df[df['Churn']==0]['DataUsage'].mean(), 2)}\nAverage datause (Churn) - {round(df[df['Churn']==1]['DataUsage'].mean(), 2)}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['DataUsage'], \n    data_column_2=df[df['Churn']==1]['DataUsage'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nMost users do not exceed 1 GB.\n\nOn average, Churn users use less traffic, and these differences are statistically significant.\n\"\"\"\nstack_bar(\n    data=df,\n    column_1='CustServCalls',\n    column_2='Churn',\n    palette=['#4869D6', '#FF7373'],\n    title='Churn count by CustServCalls',\n    title_x=0.35)\n\nchi_2(\n    alpha=0.01,\n    data_1=df['Churn'],\n    data_2=df['CustServCalls'])\n\"\"\"\nMost users have made one request to technical support. Only a small part of users made more than 4 calls to technical support.\n\"\"\"\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['DayCalls'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='DayCalls',\n    title='DayCalls by churn',\n    title_x=0.1\n    )\nprint(f'''Average daycalls (No Churn) - {round(df[df['Churn']==0]['DayCalls'].mean())}\nAverage daycalls (Churn) - {round(df[df['Churn']==1]['DayCalls'].mean())}''')\nprint()\nprint(f'''std daycalls (No Churn) - {round(df[df['Churn']==0]['DayCalls'].std())}\nstd daycalls (Churn) - {round(df[df['Churn']==1]['DayCalls'].std())}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['DayCalls'], \n    data_column_2=df[df['Churn']==1]['DayCalls'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nThe distribution of the number of minutes per day is close to normal with small outliers. The distribution of Churn users is more variable.\n\nOn average, the Churn users make 1 more call per day, the differences are not statistically significant\n\"\"\"\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['MonthlyCharge'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='MonthlyCharge',\n    title='MonthlyCharge by churn',\n    title_x=0.1\n    )\nprint(f'''Average monthlycharge (No Churn) - {round(df[df['Churn']==0]['MonthlyCharge'].mean(), 2)}\nAverage monthlycharge (Churn) - {round(df[df['Churn']==1]['MonthlyCharge'].mean(), 2)}''')\nprint()\nprint(f'''std monthlycharge (No Churn) - {round(df[df['Churn']==0]['MonthlyCharge'].std())}\nstd monthlycharge (Churn) - {round(df[df['Churn']==1]['MonthlyCharge'].std())}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['MonthlyCharge'], \n    data_column_2=df[df['Churn']==1]['MonthlyCharge'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nOn average, Churn users pay more per month, and the differences are statistically significant.\n\"\"\"\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['OverageFee'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='OverageFee',\n    title='OverageFee by churn',\n    title_x=0.1\n    )\nprint(f'''Average overagefee (No Churn) - {round(df[df['Churn']==0]['OverageFee'].mean(), 2)}\nAverage overagefee (Churn) - {round(df[df['Churn']==1]['OverageFee'].mean(), 2)}''')\nprint()\nprint(f'''std overagefee (No Churn) - {round(df[df['Churn']==0]['OverageFee'].std(), 2)}\nstd overagefee (Churn) - {round(df[df['Churn']==1]['OverageFee'].std(), 2)}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['OverageFee'], \n    data_column_2=df[df['Churn']==1]['OverageFee'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nThe distribution is close to normal.\n\nOn average, the Churn users have the highest overpayment for 12 months more, and the differences are statistically significant\n\"\"\"\nstack_hist(\n    categorial_data=df['Churn'],\n    data=df['RoamMins'],\n    palette=['#4869D6', '#FF7373'],\n    x_label='RoamMins',\n    title='RoamMins by churn',\n    title_x=0.1\n    )\nprint(f'''Average roammins (No Churn) - {round(df[df['Churn']==0]['RoamMins'].mean(), 2)}\nAverage roammins (Churn) - {round(df[df['Churn']==1]['RoamMins'].mean(), 2)}''')\nprint()\nprint(f'''std roammins (No Churn) - {round(df[df['Churn']==0]['RoamMins'].std(), 2)}\nstd roammins (Churn) - {round(df[df['Churn']==1]['RoamMins'].std(), 2)}''')\nprint()\nget_bootstrap(\n    data_column_1=df[df['Churn']==0]['RoamMins'], \n    data_column_2=df[df['Churn']==1]['RoamMins'], \n    boot_it = 1000,\n    statistic = np.mean, \n    bootstrap_conf_level = 0.99 \n)\n\"\"\"\nThe distribution is close to normal.\n\nOn average, the Churn users used more roaming minutes, and the differences are statistically significant.\n\"\"\"\n\"\"\"\n# Survival analysis.\n\"\"\"\nplt.figure(figsize=(13,8))\n\nkmf = KaplanMeierFitter()\nkmf.fit(\n    durations=df['AccountWeeks'], \n    event_observed=df['Churn'])\n\nkmf.plot()\n\nplt.vlines(\n    x=kmf.median_survival_time_,\n    ymin=0,\n    ymax=0.8,\n    ls=':',\n    color='crimson',\n    lw=3)\n\nplt.ylim(0,1)\n\nplt.yticks(np.arange(0.1, 1.1, 0.1))\n\nsns.despine()\n\nplt.legend().set_visible(False)\n\nplt.xticks(\n    fontsize=15,\n    color='black',\n    family='sans-serif')\nplt.yticks(\n    fontsize=15,\n    color='black',\n    family='sans-serif')\n\nplt.xlabel(\n    xlabel='AccountWeeks',\n    fontsize=17,\n    color='black',\n    family='sans-serif',\n    fontweight='bold')\nplt.ylabel(\n    ylabel='Percentage',\n    fontsize=17,\n    color='black',\n    family='sans-serif',\n    fontweight='bold')\n\nplt.title(\n    label='Survival function',\n    fontsize=20,\n    x=0,\n    y=1.1,\n    family='sans-serif',\n    fontweight='bold')\n\nplt.show()\n\nprint(f'''50% of customers will refuse services before {int(kmf.median_survival_time_)} weeks''')\ndef surv_func(data, categorial_data, duration, event, title_x):\n\n    '''\n    :param data: data set\n    :param categorial_data: column name with categorical data\n    :param duration: column name with duration\n    :param event: column name with event\n    :param title_x: title location by x\n    :return Survival function.\n    '''\n    \n    median_surv_time_list = []\n    labels = []\n\n    plt.figure(figsize=(13,8))\n    ax = plt.subplot()\n\n    for i in data[categorial_data].unique():\n        kmf = KaplanMeierFitter()\n        kmf.fit(\n            durations=data[data[categorial_data]== i][duration], \n            event_observed=data[data[categorial_data]== i][event],\n            label=f'{i}')\n        kmf.survival_function_.plot(ax=ax)\n        median_surv_time = kmf.median_survival_time_\n        median_surv_time_list.append(median_surv_time)\n        labels.append(i)\n\n    data_median = pd.DataFrame(index=labels, data=median_surv_time_list, columns=['median'])\n\n    plt.xticks(\n        fontsize=15,\n        color='black',\n        family='sans-serif')\n    plt.yticks(\n        fontsize=15,\n        color='black',\n        family='sans-serif')\n\n    plt.xlabel(\n        xlabel=duration,\n        fontsize=17,\n        color='black',\n        family='sans-serif',\n        fontweight='bold')\n    plt.ylabel(\n        ylabel='Percentage',\n        fontsize=17,\n        color='black',\n        family='sans-serif',\n        fontweight='bold')\n\n    plt.title(\n        label=f'Survival function by {categorial_data}',\n        fontsize=20,\n        x=title_x,\n        y=1.1,\n        family='sans-serif',\n        fontweight='bold')\n\n    sns.despine()\n\n    plt.show()\n\n    print(data_median)\nsurv_func(\n    data=df,\n    categorial_data='ContractRenewal',\n    duration='AccountWeeks',\n    event='Churn',\n    title_x=0.1)\n\"\"\"\nWe can also check whether the differences are statistically significant.\n\"\"\"\nresults = logrank_test(\n    durations_A=df[df['ContractRenewal']== 0]['AccountWeeks'],\n    durations_B=df[df['ContractRenewal']== 1]['AccountWeeks'],\n    event_observed_A=df[df['ContractRenewal']== 0]['Churn'],\n    event_observed_B=df[df['ContractRenewal']== 1]['Churn'])\nresults.print_summary()\n\"\"\"\nThe differences are statistically significant.\n\n* 50% of customers who did not renew the contract will leave before 136 weeks;\n\n* 50% of clients who have extended the contract will leave before 212 weeks.\n\"\"\"\nsurv_func(\n    data=df,\n    categorial_data='DataPlan',\n    duration='AccountWeeks',\n    event='Churn',\n    title_x=0.1)\nresults = logrank_test(\n    durations_A=df[df['DataPlan']== 0]['AccountWeeks'],\n    durations_B=df[df['DataPlan']== 1]['AccountWeeks'],\n    event_observed_A=df[df['DataPlan']== 0]['Churn'],\n    event_observed_B=df[df['DataPlan']== 1]['Churn'])\nresults.print_summary()\n\"\"\"\nFrom the data presented, it can be seen that among users who have the Internet connected, the survival rate has not fallen below ~ 65%.\n\n50% of users who are not connected to the Internet leave before 193 weeks.\n\nThe differences are statistically significant.\n\"\"\"\n\"\"\"\nIn EDA, I found out that only a small proportion of users made more than 4 calls to technical support. Therefore, to analyze the survival rate and the possibility of interpreting the results, we will take into account only users who have made 4 or fewer requests.\n\"\"\"\nsurv_func(\n    data=df.query('CustServCalls <= 4'),\n    categorial_data='CustServCalls',\n    duration='AccountWeeks',\n    event='Churn',\n    title_x=0.1)\n\"\"\"\nThe worst results among those who made 4 calls in support.\n\"\"\"\n\"\"\"\nSince we have 2+ groups, we will apply a multivariate_logrank_test that tests the hypothesis that there is a statistically significant difference for at least one of the groups.\n\"\"\"\nresult = multivariate_logrank_test(\n    event_durations=df.query('CustServCalls <= 4')['AccountWeeks'],\n    event_observed=df.query('CustServCalls <= 4')['Churn'],\n    groups=df.query('CustServCalls <= 4')['CustServCalls'])\nresult.print_summary()\n\"\"\"\nThe test showed us that at least one of the groups is statistically significantly different. To find out between which groups there is a statistically significant difference, I will use pairwise_logrank_test.\n\"\"\"\nresult = pairwise_logrank_test(\n    event_durations=df.query('CustServCalls <= 4')['AccountWeeks'],\n    event_observed=df.query('CustServCalls <= 4')['Churn'],\n    groups=df.query('CustServCalls <= 4')['CustServCalls'])\nresult.print_summary()\n\"\"\"\nSince the level we set is alpha = 0.01, there are statistically significant differences between the following groups:\n* 0 and 4\n* 1 and 4\n* 2 and 4\n* 3 and 4\n\"\"\"\n\"\"\"\n# Cox\n\"\"\"\n\"\"\"\nUsing Cox regression, it is possible to determine the significance of predictors, how they affect and predict the probability of survival.\n\"\"\"\ndf.drop('index', axis=1, inplace=True)\ncoxph = CoxPHFitter(alpha = 0.01)\ncoxph.fit(df, duration_col='AccountWeeks', event_col='Churn')\ncoxph.print_summary()\nplt.figure(figsize = (13, 8))\n\ncoxph.plot()\n\"\"\"\nNext features have the significance:\n* ContractRenewal\n* CustServCalls\n* RoamMins\n\"\"\"\n\"\"\"\nFor predict let's create data set with some No Churn users\n\"\"\"\nsome_users = df[df['Churn']==1].reset_index().iloc[165:169,:]\nround(coxph.predict_survival_function(some_users, conditional_after=some_users['AccountWeeks']), 4)\n\"\"\"\nFrom the data we can see what is the probability that these users will not stop using the service\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '64f49dccd0e04b'}"}
{"id":"21892","text":"import pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\ndf = pd.read_csv('..\/input\/california-housing-prices\/housing.csv')\ndf\ndf['ocean_proximity'].value_counts()\ndf.info()\ndf.isnull().sum()\n\"\"\"\n### Total no of bedrooms has null values, we will fill them using mean\n\"\"\"\n\"\"\"\n### We wont be doing spatial analysis so we will remove the latitude and longitude columns\n\"\"\"\ndf.drop(['longitude','latitude'],axis=1,inplace =True)\ndf.info()\ndf['total_bedrooms'].fillna(df['total_bedrooms'].mean(),inplace=True)\ndf.info()\n\"\"\"\n### We have filled in the null values\n\"\"\"\ndf.head()\n\"\"\"\n# EDA\n\"\"\"\ndf.corr()\nsns.heatmap(df.corr(),annot=True);\ndf.hist(figsize=(20,15));\n\"\"\"\n### We can see that only median house age is normally distributed rest all are right skewed\n\"\"\"\nsns.scatterplot(data=df,x='median_income',y='median_house_value')\nplt.title('Median Income vs Median House value');\n\"\"\"\n#### Above plot tells us that there is a positive relation b\/w the median income and median house value telling us that more the income of the houseolds , they buy expensive property\n\"\"\"\nsns.boxplot(data=df,y='median_house_value'); #let's see the box plot to see the mean house price \ndf['median_house_value'].mean()\nsns.scatterplot(data=df,x='total_rooms',y='median_house_value')\nplt.title('Total no of rooms vs Median House value');\nsns.scatterplot(data=df,x='total_bedrooms',y='median_house_value')\nplt.title('Total no of rooms vs Median House value');\n# Let's see the distribution of of the Median house age\nsns.displot(data=df,x='housing_median_age',kde=True);\nsns.countplot(data=df,x='ocean_proximity');\ndf['ocean_proximity'].value_counts()\nhouse_near_onehocean = df[df['ocean_proximity'] == '<1H OCEAN']\nhouse_near_onehocean.describe()\ndf.groupby('ocean_proximity').mean()\n\"\"\"\n### Let's seperate the data by ocean proxmity and then see detailed information to gain insight\n\"\"\"\nhouse_near_inland = df[df['ocean_proximity'] == 'INLAND']\nhouse_near_inland.describe()\nhouse_near_bay = df[df['ocean_proximity'] == 'NEAR BAY']\nhouse_near_bay.describe()\nhouse_near_ocean = df[df['ocean_proximity'] == 'NEAR OCEAN']\nhouse_near_ocean.describe()\nhouse_near_island = df[df['ocean_proximity'] == 'ISLAND']\nhouse_near_island.describe()\n\"\"\"\n#### 1.After seperating the category by the ocean proximity we can see the average housel value and we can tell that houses located near Island are expensive which also justifies because island mostly being a vacation place has higher value of houses. But we cant rely on this data as we have information just 5 houses in this category, so to have clear idea of thus we might need more data.\n\n#### 2.Other than this we can see that houses located at the Bay area are expensive than houses of other areas.\n\n#### 3.So we can say that the location of house from nearby oceans plays vital role in prices of the houses.\n\n#### 4.There is very little positive relation as seen from plots, between the total no of rooms and bedrooms within a block and the price of the houses.\n\"\"\"\n\"\"\"\n## Feature Selection \n\"\"\"\nX = df.drop('median_house_value',axis=1)\nX = pd.get_dummies(data=X)\nX.head()\nX['ocean_proximity_<1H_OCEAN'] = X['ocean_proximity_<1H OCEAN']\nX = X.drop('ocean_proximity_<1H OCEAN',axis=1)\nX.head()\nprint('Shape of input features',X.shape) # 2D array\ny = df['median_house_value']\ny.head()\nprint('Shape of input features',y.shape)\ny.values # 1D array\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42 )\n\"\"\"\n## Model Creation\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nhouse_price_model = LinearRegression()\n\"\"\"\n#### Training model on training data\n\"\"\"\nhouse_price_model.fit(X_train,y_train)\n\"\"\"\n### Predicting the house values on test data\n\"\"\"\ny_predictions = house_price_model.predict(X_test)\ny_predictions\n\"\"\"\n### Now that we have predicted the test data using the model we need to find out the accuracy of this model and find out whether Linear Regerssion was best algo for this data\n\"\"\"\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\ny_test.mean()\n#df['median_house_value'].mean()\ny_predictions.mean()\nmean_absolute_error(y_test,y_predictions)\ndef mape(actual, pred): \n    actual, pred = np.array(actual), np.array(pred)\n    return np.mean(np.abs((actual - pred) \/ actual)) * 100\n\nmape(y_test,y_predictions)\n\"\"\"\n#### So we after calculating MAPE we found out that we are off by or we have 28.9% i.e. 29% as error rate\n\n#### So is that error acceptable - it depends on context and consider our scenario - 29 % error is surely not  completely acceptable but it can give us a fair idea about the prices of the houses\n\"\"\"\nnp.sqrt(mean_squared_error(y_test,y_predictions))\n\"\"\"\n##### We can that we have a high RMSE than our MAE, whcih suggests that for most of the data the predicted value is having fair accuracy but for few points\/data features the predicted house value is havng very high errors\n\"\"\"\n#### Accuracy of the model\nr2_score(y_test,y_predictions)\nX.columns\n\"\"\"\nSo our model accuracy is 63%\n\"\"\"\nhouse_price_model.coef_\nhouse_price_model.intercept_\n\"\"\"\n#### Now we want to know if the underlying dataset was a valid dataset for Linear Regression , by checking the residual plots if there was a sttrange pattern that we coul not see in some multidimensional level\n\n#### Let's visualize the residual plots to see that \n\"\"\"\ntest_residuals = y_test - y_predictions\ntest_residuals\nsns.scatterplot(x=y_test,y=test_residuals)\nplt.axhline(y=0,color='red')\nplt.title('Residual Plot');\n\"\"\"\n### We can see that the data residual plot shows us that the points are normally distributed along the line, so we can conclude that the underlying dataset a valid choice for Linear Regression.\n\n### As for the low model accuracy, it might be because of less data and also in model coefficients we have some negative coefficients values which we can remove to get better accuracy.\n\"\"\"\nsns.displot(test_residuals,bins=30,kde=True);\n\"\"\"\n### Even the distribution tells us that the errors\/residuals are somewhat distributed normally and also the kde shows us that the mean is pretty close to zero\n\n### Also we can see there is undershoot of a little bit but having a little bit skewed on one way or the other is not too bad.\n\"\"\"\n\"\"\"\n### Saving the model\n\"\"\"\nfrom joblib import dump\ndump(house_price_model,'House_prediction_model.joblib')","meta":"{'source': 'AI4Code', 'id': '283e7f020207a3'}"}
{"id":"95213","text":"# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n# Is there a cat in your dat?\n\nA common task in machine learning pipelines is encoding categorical variables for a given algorithm in a format that allows as much useful signal as possible to be captured.\n\nBecause this is such a common task and important skill to master, we've put together a dataset that contains only categorical features, and includes:\n\nbinary features\nlow- and high-cardinality nominal features\nlow- and high-cardinality ordinal features\n(potentially) cyclical features\n\"\"\"\n\"\"\"\n# Reading Data\n\"\"\"\n# Read the data\ntrain_d = pd.read_csv('..\/input\/cat-in-the-dat\/train.csv') \ntest_d = pd.read_csv('..\/input\/cat-in-the-dat\/test.csv')\n\"\"\"\n# Exploring and understanding our Data\n\"\"\"\ntrain_d.shape \ntest_d.shape\ntrain_d.head()\ntrain_d.tail()\ntest_d.columns\ntrain_d.columns\ntrain_d.info()\ntrain_d.describe()\n\"\"\"\n#  Is there any missing values?\n\"\"\"\ntrain_d.isnull().sum()\n\"\"\"\ngreat, our data don't have any missing values\n\"\"\"\n\"\"\"\n# The number of unique values??\n\"\"\"\nfor col in train_d.columns[1:]:\n    print(col, train_d[col].nunique())\n\"\"\"\n# Visualization and preprocessing of Binary Features :\n\"\"\"\nbinary_col = ['bin_0', 'bin_1', 'bin_2', 'bin_3', 'bin_4']\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfor n, col in enumerate(train_d[binary_col]): \n    plt.figure(n)\n    sns.countplot(x=col, data=train_d, hue='target', palette='husl')\ntrain_d['target'].value_counts()\nsns.swarmplot(x=train_d.head(250)['bin_0'], y=train_d.head(250)['target'])\nsns.swarmplot(x=train_d.head(250)['target'], y=train_d.head(250)['month'])\nsns.swarmplot(x=train_d.head(250)['target'], y=train_d.head(250)['day'])\nsns.swarmplot(x=train_d.head(250)['day'], y=train_d.head(250)['target'])\n# Histogram \nsns.distplot(a=train_d['target'], kde=False)\nsns.kdeplot(data=train_d['target'], shade=True)\n\n bin_d = train_d[['bin_0','bin_1','bin_2','bin_3', 'bin_4']]\nbin_d.head()\nfrom sklearn.preprocessing import LabelEncoder\ntrain_df=pd.DataFrame()\nlabel=LabelEncoder()\nfor col in  train_d.columns:\n    if 'bin' in col:\n        train_df[col]=label.fit_transform(train_d[col])\n    else:\n        train_df[col]=train_d[col]\n        \n\n\ntrain_df.head(3)\ntest_d.head(4)\nfrom sklearn.preprocessing import LabelEncoder\ntest_df=pd.DataFrame()\nlabel=LabelEncoder()\nfor col in  test_d.columns:\n    if 'bin' in col:\n        test_df[col]=label.fit_transform(test_d[col])\n    else:\n        test_df[col]=test_d[col]\n    \ntest_df.head(4) \nbinary_cols = ['bin_0', 'bin_1', 'bin_2', 'bin_3', 'bin_4']\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfor n, col in enumerate(train_df[binary_cols]): \n    plt.figure(n)\n    sns.countplot(x=col, data=train_df, hue='target', palette='husl')\ntrain_df.shape  ,  test_df.shape\n\"\"\"\n# Visualization and preprocessing of nominal Features :\n\"\"\"\nnominal_cols = ['nom_0', 'nom_1', 'nom_2', 'nom_3', 'nom_4', 'nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9']\nfor n, col in enumerate(train_df[nominal_cols]): \n    plt.figure(n)\n    sns.countplot(x=col, data=train_df, hue='target', palette='husl')\n\"\"\"\n# separating nominal Features\n\"\"\"\n\"\"\"\nAs we see, we have a different range of nominal features and we know that is not good way to make OneHotencoder for variables taking more than 15 different values. so, we will separate them\n\"\"\"\nlow_cardinality_nom_cols = []\nhigh_cardinality_nom_cols = []\n\n\nfor nom_col in range(10):\n    nom_col_name = \"nom_\"+str(nom_col)\n    if train_df[nom_col_name].nunique() < 10:\n        low_cardinality_nom_cols.append(nom_col_name)\n    else:\n        high_cardinality_nom_cols.append(nom_col_name)\n\nprint(\"Nominal columns low cardinality (<=10):\", low_cardinality_nom_cols)\nprint(\"Nominal columns with high cardinality (>10):\", high_cardinality_nom_cols)\n\ncol_nom = train_df.columns[6:11]\ncol_nom\n\"\"\"\n# For (low) nominal features : using OneHotEencoder to encoding variables\n\"\"\"\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Apply one-hot encoder to each column with categorical data\nOH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)\n\nOH_cols_train = pd.DataFrame(OH_encoder.fit_transform(train_df[low_cardinality_nom_cols]))\nOH_cols_test = pd.DataFrame(OH_encoder.transform(test_df[low_cardinality_nom_cols]))\n\n# One-hot encoding removed index; put it back\nOH_cols_train.index = train_df.index\nOH_cols_test.index = test_df.index\n\n# Remove categorical columns (will replace with one-hot encoding)\nnum_X_train = train_df.drop(low_cardinality_nom_cols, axis=1)\nnum_X_valid = test_df.drop(low_cardinality_nom_cols, axis=1)\n\n# Add one-hot encoded columns to numerical features\nOH_X_train = pd.concat([num_X_train, OH_cols_train], axis=1)\nOH_X_tset = pd.concat([num_X_valid, OH_cols_test], axis=1)\nOH_X_train.head()\nOH_X_tset.head()\n\"\"\"\n# Visualization and preprocessing of ordinal Features :\n\"\"\"\nord_col = ['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfor n, col in enumerate(train_df[ord_col]): \n    plt.figure(n)\n    sns.countplot(x=col, data=train_df, hue='target', palette='husl')\nfrom sklearn.preprocessing import LabelEncoder\ntrain_n=pd.DataFrame()\nlabel=LabelEncoder()\nfor col in  ['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']:\n   \n        train_n[col]=label.fit_transform(OH_X_train[col])\n    \n\n    \ndata_t = OH_X_train.drop(['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5'], axis=1) \ntrain_dd = pd.concat([data_t,train_n], axis = 1)\ntrain_dd.head()\nfrom sklearn.preprocessing import LabelEncoder\ntest_n=pd.DataFrame()\nlabel=LabelEncoder()\nfor col in  ['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']:\n   \n        test_n[col]=label.fit_transform(OH_X_tset[col])\n    \n    \ndata_t = OH_X_tset.drop(['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5'], axis=1) \ntest_dd = pd.concat([data_t,test_n], axis = 1)\ntest_dd.head(4)\n\"\"\"\n# back to high nominal : \n\"\"\"\n\"\"\"\nTrying some different ways to preprocessing high nominal like: hash, frequent, label encoder\n\"\"\"\n\"\"\"\n# Hash\n\"\"\"\nfor col in high_cardinality_nom_cols:\n    train_dd[f'hash_{col}'] = train_dd[col].apply( lambda x: hash(str(x)) % 5000 )\n    test_dd[f'hash_{col}'] = test_dd[col].apply( lambda x: hash(str(x)) % 5000 )\n\"\"\"\n# Frequent \n\"\"\"\nfor col in high_cardinality_nom_cols:\n    enc_nom_1 = (train_dd.groupby(col).size()) \/ len(train_dd)\n    train_dd[f'freq_{col}'] = train_dd[col].apply(lambda x : enc_nom_1[x])\n    #test_dd[f'enc_{col}'] = test_dd[col].apply(lambda x : enc_nom_1[x])\n\"\"\"\n# Label Encoder\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\n\n# Label Encoding\nfor f in ['nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9']:\n    if train_dd[f].dtype=='object' or test_dd[f].dtype=='object': \n        lbl = LabelEncoder()\n        lbl.fit(list(train_dd[f].values) + list(test_dd[f].values))\n        train_dd[f'le_{f}'] = lbl.transform(list(train_dd[f].values))\n        test_dd[f'le_{f}'] = lbl.transform(list(test_dd[f].values))\nnew_feat = ['hash_nom_5', 'hash_nom_6', 'hash_nom_7', 'hash_nom_8',\n            'hash_nom_9',  'freq_nom_5', 'freq_nom_6', 'freq_nom_7', \n            'freq_nom_8', 'freq_nom_9', 'le_nom_5', 'le_nom_6',\n            'le_nom_7', 'le_nom_8', 'le_nom_9']\n\nnew_da = (train_dd[high_cardinality_nom_cols + new_feat])\nnew_da.describe()\ntrain_dd[['nom_5', 'hash_nom_5', 'freq_nom_5', 'le_nom_5']].head()\ntrain_dd.head(4)\ntest_dd.head(4)\ntrain_dd.head(4)\n\"\"\"\n# choosing just one type and Dropping other:\n\"\"\"\ntrain_dd.drop([ \n                #'hash_nom_6', 'hash_nom_7', 'hash_nom_8', 'hash_nom_9',\n               'le_nom_5', 'le_nom_6', 'le_nom_7', 'le_nom_8', 'le_nom_9',\n                'freq_nom_5','freq_nom_6', 'freq_nom_7', 'freq_nom_8', 'freq_nom_9',\n              'nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9'\n         ], axis=1, inplace=True)\n\n#test_dd.drop([\n              #'hash_nom_6', 'hash_nom_7', 'hash_nom_8', 'hash_nom_9', \n #             'le_nom_5', 'le_nom_6', 'le_nom_7', 'le_nom_8', 'le_nom_9',\n  #            'freq_nom_5', 'freq_nom_6', 'freq_nom_7', 'freq_nom_8', 'freq_nom_9',\n   #           'nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9',\n    #          ], axis=1, inplace=True)\n\n\ntrain_dd.head(4)\ntest_dd.drop([\n              #'hash_nom_6', 'hash_nom_7', 'hash_nom_8', 'hash_nom_9', \n            'le_nom_5', 'le_nom_6', 'le_nom_7', 'le_nom_8', 'le_nom_9',\n  #          'freq_nom_5', 'freq_nom_6', 'freq_nom_7', 'freq_nom_8', 'freq_nom_9',\n            'nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9'\n            ], axis=1, inplace=True)\ntest_dd.head(4)\n\"\"\"\nNOW OUR DATA IS NUMERIC ^_^\n\"\"\"\n\"\"\"\n# Let's make some visualizations:\n\"\"\"\ndate_cols = ['day', 'month']\n\nfor n, col in enumerate(train_df[date_cols]): \n    plt.figure(n)\n    sns.countplot(x=col, data=train_df, hue='target', palette='husl')\nsns.scatterplot(x=train_df['bin_0'], y=train_df['ord_3'], hue=train_df['target'])\nsns.swarmplot(x=train_dd.head(10)['hash_nom_5'],\n              y=train_dd.head(10)['day'])\n# Set the width and height of the figure\nplt.figure(figsize=(10,6))\n\n# Add title\nplt.title(\"ord 3 , by Month\")\n\n# Bar chart showing average arrival delay for Spirit Airlines flights by month\nsns.barplot(x=train_dd.head(20)['month'], y=train_dd.head(20)['ord_3'])\n\n# Add label for vertical axis\nplt.ylabel(\"in \")\n# Set the width and height of the figure\nplt.figure(figsize=(10,6))\n\n# Add title\nplt.title(\"hash_nom_6  , by day\")\n\n# Bar chart showing average arrival delay for Spirit Airlines flights by month\nsns.barplot(x=train_dd.head(20)['day'], y=train_dd.head(20)['hash_nom_6'])\n\n# Add label for vertical axis\nplt.ylabel(\"in \")\n# Set the width and height of the figure\nplt.figure(figsize=(14,7))\n\n# Add title\nplt.title(\"Heatmap\")\n\n# Heatmap showing average arrival delay for each airline by month\nsns.heatmap(data=train_dd.head(15), annot=False)\n\n# Add label for horizontal axis\nplt.xlabel('data')\ncyclic_cols = ['day','month']\n\nfig, axs = plt.subplots(1, len(cyclic_cols), figsize=(8, 4))\n\nfor i in range(len(cyclic_cols)):\n    col = cyclic_cols[i]\n    ax = axs[i]\n    sns.barplot(x=col, y='target', data=train_dd, ax=ax)\n    ax.set_title(col, fontsize=14, fontweight='bold')\n    ax.legend(title=\"target\", loc='upper center')\n\"\"\"\n# split data using : model_selection\n\"\"\"\ntrain_dd.shape\n\ntest_dd.shape\n\ntrain_dd = train_dd.drop([\"id\"],axis=1)\n\n\ntrain_dd.shape\n\"\"\"\n# Separate data into training and validation sets\n\"\"\"\n# Select  predictors\ncols_to_use = [     'bin_0',      'bin_1',      'bin_2',      'bin_3',      'bin_4',\n              'day',      'month',            0,            1,            2,\n                  3,            4,            5,            6,            7,\n                  8,            9,           10,           11,           12,\n                 13,           14,           15,           16,           17,\n                 18,           19,           20,           21,           22,\n                 23,           24,      'ord_0',      'ord_1',      'ord_2',\n            'ord_3',      'ord_4',      'ord_5', 'hash_nom_5', 'hash_nom_6',\n       'hash_nom_7', 'hash_nom_8', 'hash_nom_9']\n\nX = train_dd[cols_to_use]\n\n# Select target\ny = train_dd.target\n\n# Separate data into training and validation sets\nfrom sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(X, y)\nX_train.shape\nX_valid.shape\ntest_dd.head()\n#from sklearn.ensemble import RandomForestRegressor\n#from xgboost import XGBRegressor\n\n \n#my_model = XGBRegressor(n_estimators=1000, learning_rate=0.05, n_jobs=4)\n#my_model.fit(X_train, y_train, \n #            early_stopping_rounds=5, \n  #           eval_set=[(X_valid, y_valid)], \n   #          verbose=False)\n#from sklearn.metrics import mean_absolute_error\n\n#predictions = my_model.predict(X_valid)\n\n# Calculate MAE\n#mae_1 = mean_absolute_error(y_valid, predictions) \n\n\n#print(\"Mean Absolute Error:\" , mae_1)\n#from sklearn.metrics import accuracy_score\n#acc = accuracy_score(y_valid, predictions)\n\n#print(\"accuracy_score:\" , acc)\n\ntest_X = test_dd[cols_to_use]\n\n# Use the model to make predictions\n#predicted_target = my_model.predict(test_X)\n# We will look at the predicted prices to ensure we have something sensible.\n#print(predicted_target)\n#my_submission = pd.DataFrame({'Id': test_X.index, 'target': predicted_target})\n# you could use any filename. We choose submission here\n#my_submission.to_csv('submission.csv', index=False)\n#from sklearn.linear_model import LogisticRegression\n\n#lr_m = LogisticRegression( solver=\"lbfgs\",max_iter=500,n_jobs=4)\n\n#lr_m.fit(X_train, y_train)\n#from sklearn.metrics import mean_absolute_error\n\n#predictions = lr_m.predict(test_X)\n\n# Calculate MAE\n#mae_1 = mean_absolute_error(y_valid, predictions) \n\n\n#print(\"Mean Absolute Error:\" , mae_1)\n#from sklearn.metrics import accuracy_score\n#acc = accuracy_score(y_valid, predictions)\n\n#print(\"accuracy_score:\" , acc)\n#rf_model = RandomForestRegressor(n_estimators= 280,max_depth=40,max_features=11,max_leaf_nodes=350,random_state=1)\n#rf_model.fit(X_train, y_train)\n\n#rf_val_predictions = rf_model.predict(test_X)\n\n\"\"\"\n# Using XGBRegressor model with tuning parameter\n\n\ntrying some models but, I found the XGBRegressor the best until now\n\"\"\"\nfrom xgboost import XGBRegressor\nmy_model_2 = XGBRegressor(n_estimators=700, learning_rate=0.2, n_jobs=4)\nmy_model_2.fit(X_train,y_train)\n\ntest_preds = my_model_2.predict(test_X)\n\n# generating one row  \n#X_rows = X_train.sample(frac =.03) \n  \n# checking if sample is 0.25 times data or not \n  \n#if (0.03*(len(X_train))== len(X_rows)): \n #   print( \"Cool\") \n  #  print(len(X_train))\n   # print('\\n')      \n    #print(len(X_rows))       \n \n# generating one row  \n#y_rows = y_train.sample(frac =.03) \n  \n# checking if sample is 0.25 times data or not \n  \n#if (0.03*(len(y_train))== len(y_rows)): \n #   print( \"Cool\") \n  #  print(len(y_train))\n   # print('\\n')      \n   # print(len(y_rows))   \n#parameters = [{'n_estimators': [ 800, 900, 1000], \n #                    'learning_rate': [0.05, 0.1, 0.15, 0.2]\n  #                  }]\n#from sklearn.model_selection import GridSearchCV\n#from xgboost import XGBRegressor\n#gsearch = GridSearchCV(estimator=XGBRegressor(),\n #                      param_grid = parameters, \n  #                     scoring='neg_mean_absolute_error',\n   #                    n_jobs=4,cv=3)\n\n\n#gsearch.fit(X_rows,y_rows)\n#gsearch.best_params_.get('n_estimators'), gsearch.best_params_.get('learning_rate')\n\n#final_model = XGBRegressor(n_estimators=gsearch.best_params_.get('n_estimators'), \n                          # learning_rate=gsearch.best_params_.get('learning_rate'), \n                           #n_jobs=4)\n#final_model.fit(X_rows,y_rows)\n#test_preds = final_model.predict(test_X)\n\"\"\"\n# Preparing Submission File\n\"\"\"\n\n#submission = pd.read_csv('\/kaggle\/input\/cat-in-the-dat\/sample_submission.csv', index_col='id')\nsamplesubmission = pd.read_csv('\/kaggle\/input\/cat-in-the-dat\/sample_submission.csv', index_col='id')\n\noutput = pd.DataFrame({'Id': samplesubmission.index, 'target': test_preds})\noutput.to_csv('submission.csv', index=False)\noutput.head()","meta":"{'source': 'AI4Code', 'id': 'aec6e4819a6c28'}"}
{"id":"95533","text":"# 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\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndf=pd.read_csv('..\/input\/ataljalyojana\/Atal Jal 31 March 2021 .xlsx - Sheet1.csv')\ndf.head()\ndf.State=df['State'].str.lower()\npd.crosstab(index=df['State'], columns=df['Well Depth'], margins=True)\n\"\"\"\n# inference\n* we can see that UP has maximum number of 0 data for well depth . We have to find is this a random or not\n\"\"\"\npd.crosstab(index=df['State'], columns=df['Pre_2015'], margins=True)\ndf[['State', 'Well Depth']].describe()\ndf.columns\npd.crosstab(index=df['State'], columns=df['TYPE'], margins=True)\n(pd.crosstab(index=df['State'], columns=df['Aquifier'], margins=True)).T\n\"\"\"\n# State wise analysis using contigency table\n\"\"\"\ndf['State'].value_counts()\ndf_guj=df[df['State']=='gujarat']\ndf_maha=df[df['State']=='maharashtra']\ndf_raj=df[df['State']=='rajasthan']\ndf_har=df[df['State']=='haryana']\ndf_mp=df[df['State']=='madhya pradesh']\ndf_up=df[df['State']=='uttar pradesh']\ndf_kar=df[df['State']=='karnataka']\ncol=['Well Depth', 'Pre_2015','Pre_2016','Pre_2017', 'Pre_2018', 'Pre_2019', 'Pst_2015',\n   'Pst_2016','Pst_2017','Pst_2018','Pst_2019']\n\ndf_guj[col].describe().T\ndf_guj[col].describe().T.plot(kind='bar')\ndf_guj['Well Depth'].describe()\ndf_raj['Well Depth'].describe().T\ndf_har['Well Depth'].describe().T\ndf_mp['Well Depth'].describe().T\ndf_up['Well Depth'].describe().T\ndf_kar['Well Depth'].describe().T\ndf_maha['Well Depth'].describe().T\n\"\"\"\n# Tools to visuaize the columns data\n\"\"\"\nplt.style.use('seaborn-darkgrid')\n\norange_black = ['#fdc029', '#df861d', 'FF6347', '#aa3d01',\n                '#a30e15', '#800000', '#171820']\n\nplt.rcParams['figure.figsize'] = (10,5) \nplt.rcParams['figure.facecolor'] = '#FFFACD' \nplt.rcParams['axes.facecolor'] = 'FFFFE0' \nplt.rcParams['axes.grid'] = True \nplt.rcParams['grid.color'] = orange_black[3]\nplt.rcParams['grid.linestyle'] = '--'\ndef tools_visuaize(data, ):\n    \n    plt.figure(figsize=(10,10))\n    plt.subplot(3,1,1)\n    sns.kdeplot(data=data, fill=True)\n    plt.show()\n    \n    plt.figure(figsize=(10,10))\n    plt.subplot(3,1,2)\n    sns.barplot(data=data)\n    plt.show()\n    \n    plt.figure(figsize=(10,10))\n    plt.subplot(3,1,3)\n    sns.lineplot(data=data)\n    plt.show()\n\n    \n\"\"\"\n# Columns wise Analysis \n\"\"\"\ncol1={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_well_depth':[118.984549,17.182362,87.388121,98.191765,16.751989,10.652172,52.581923],\n       'STD_depth':[69.617500,11.306925,64.949886,81.175749,14.420278,11.695323,44.848036],\n        \"Median\":[108.500000,13.750000,62.900000,82.500000,12.625000,9.080000,35.050000]}\ncon_table=pd.DataFrame(col1)\ncon_table\ntools_visuaize(con_table)\n\"\"\"\n# Pre_2015\n\"\"\"\ncol2={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pre_2015_depth':[df_guj['Pre_2015'].mean(),df_maha['Pre_2015'].mean(),\n                         df_kar['Pre_2015'].mean(),df_har['Pre_2015'].mean(),\n                         df_mp['Pre_2015'].mean(),df_up['Pre_2015'].mean(),df_raj['Pre_2015'].mean()],\n       'STD_depth_Pre_2015_depth':[df_guj['Pre_2015'].std(),df_maha['Pre_2015'].std(),\n                         df_kar['Pre_2015'].std(),df_har['Pre_2015'].std(),\n                         df_mp['Pre_2015'].std(),df_up['Pre_2015'].std(),df_raj['Pre_2015'].std()],\n        \"Median_Pre_2015_depth\":[df_guj['Pre_2015'].median(),df_maha['Pre_2015'].median(),\n                         df_kar['Pre_2015'].median(),df_har['Pre_2015'].median(),\n                         df_mp['Pre_2015'].median(),df_up['Pre_2015'].median(),df_raj['Pre_2015'].median()]}\ncon_pre_2015=pd.DataFrame(col2)\ncon_pre_2015\ntools_visuaize(con_pre_2015)\n\"\"\"\n# Pre_2016\n\"\"\"\ncol3={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pre_2016_depth':[df_guj['Pre_2016'].mean(),df_maha['Pre_2016'].mean(),\n                         df_kar['Pre_2016'].mean(),df_har['Pre_2016'].mean(),\n                         df_mp['Pre_2016'].mean(),df_up['Pre_2016'].mean(),df_raj['Pre_2016'].mean()],\n       'STD_depth_Pre_2016_depth':[df_guj['Pre_2016'].std(),df_maha['Pre_2016'].std(),\n                         df_kar['Pre_2016'].std(),df_har['Pre_2016'].std(),\n                         df_mp['Pre_2016'].std(),df_up['Pre_2016'].std(),df_raj['Pre_2016'].std()],\n        \"Median_Pre_2016_depth\":[df_guj['Pre_2016'].median(),df_maha['Pre_2016'].median(),\n                         df_kar['Pre_2016'].median(),df_har['Pre_2016'].median(),\n                         df_mp['Pre_2016'].median(),df_up['Pre_2016'].median(),df_raj['Pre_2016'].median()]}\ncon_pre_2016=pd.DataFrame(col3)\ncon_pre_2016\ntools_visuaize(con_pre_2016)\n\"\"\"\n# Pre_2017\n\"\"\"\ncol4={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pre_2017_depth':[df_guj['Pre_2017'].mean(),df_maha['Pre_2017'].mean(),\n                         df_kar['Pre_2017'].mean(),df_har['Pre_2017'].mean(),\n                         df_mp['Pre_2017'].mean(),df_up['Pre_2017'].mean(),df_raj['Pre_2017'].mean()],\n       'STD_depth_Pre_2017_depth':[df_guj['Pre_2017'].std(),df_maha['Pre_2017'].std(),\n                         df_kar['Pre_2017'].std(),df_har['Pre_2017'].std(),\n                         df_mp['Pre_2017'].std(),df_up['Pre_2017'].std(),df_raj['Pre_2017'].std()],\n        \"Median_Pre_2017_depth\":[df_guj['Pre_2017'].median(),df_maha['Pre_2017'].median(),\n                         df_kar['Pre_2017'].median(),df_har['Pre_2017'].median(),\n                         df_mp['Pre_2017'].median(),df_up['Pre_2017'].median(),df_raj['Pre_2017'].median()]}\ncon_pre_2017=pd.DataFrame(col4)\ncon_pre_2017\ntools_visuaize(con_pre_2017)\n\"\"\"\n# Pre_2018\n\"\"\"\ncol5={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pre_2018_depth':[df_guj['Pre_2018'].mean(),df_maha['Pre_2018'].mean(),\n                         df_kar['Pre_2018'].mean(),df_har['Pre_2018'].mean(),\n                         df_mp['Pre_2018'].mean(),df_up['Pre_2018'].mean(),df_raj['Pre_2018'].mean()],\n       'STD_depth_Pre_2018_depth':[df_guj['Pre_2018'].std(),df_maha['Pre_2018'].std(),\n                         df_kar['Pre_2018'].std(),df_har['Pre_2018'].std(),\n                         df_mp['Pre_2018'].std(),df_up['Pre_2018'].std(),df_raj['Pre_2018'].std()],\n        \"Median_Pre_2018_depth\":[df_guj['Pre_2018'].median(),df_maha['Pre_2018'].median(),\n                         df_kar['Pre_2018'].median(),df_har['Pre_2018'].median(),\n                         df_mp['Pre_2018'].median(),df_up['Pre_2018'].median(),df_raj['Pre_2018'].median()]}\ncon_pre_2018=pd.DataFrame(col5)\ncon_pre_2018\ntools_visuaize(con_pre_2018)\n\"\"\"\n# Pre_2019\n\"\"\"\ncol6={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pre_2019_depth':[df_guj['Pre_2019'].mean(),df_maha['Pre_2019'].mean(),\n                         df_kar['Pre_2019'].mean(),df_har['Pre_2019'].mean(),\n                         df_mp['Pre_2019'].mean(),df_up['Pre_2019'].mean(),df_raj['Pre_2019'].mean()],\n       'STD_depth_Pre_2019_depth':[df_guj['Pre_2019'].std(),df_maha['Pre_2019'].std(),\n                         df_kar['Pre_2019'].std(),df_har['Pre_2019'].std(),\n                         df_mp['Pre_2019'].std(),df_up['Pre_2019'].std(),df_raj['Pre_2019'].std()],\n        \"Median_Pre_2019_depth\":[df_guj['Pre_2019'].median(),df_maha['Pre_2019'].median(),\n                         df_kar['Pre_2019'].median(),df_har['Pre_2019'].median(),\n                         df_mp['Pre_2019'].median(),df_up['Pre_2019'].median(),df_raj['Pre_2019'].median()]}\ncon_pre_2019=pd.DataFrame(col6)\ncon_pre_2019\ntools_visuaize(con_pre_2019)\n\"\"\"\n# Pst_2015\n\"\"\"\ncoll2={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pst_2015_depth':[df_guj['Pst_2015'].mean(),df_maha['Pst_2015'].mean(),\n                         df_kar['Pst_2015'].mean(),df_har['Pst_2015'].mean(),\n                         df_mp['Pst_2015'].mean(),df_up['Pst_2015'].mean(),df_raj['Pst_2015'].mean()],\n       'STD_depth_Pst_2015_depth':[df_guj['Pst_2015'].std(),df_maha['Pst_2015'].std(),\n                         df_kar['Pst_2015'].std(),df_har['Pst_2015'].std(),\n                         df_mp['Pst_2015'].std(),df_up['Pst_2015'].std(),df_raj['Pst_2015'].std()],\n        \"Median_Pst_2015_depth\":[df_guj['Pst_2015'].median(),df_maha['Pst_2015'].median(),\n                         df_kar['Pst_2015'].median(),df_har['Pst_2015'].median(),\n                         df_mp['Pst_2015'].median(),df_up['Pst_2015'].median(),df_raj['Pst_2015'].median()]}\ncon_pst_2015=pd.DataFrame(coll2)\ncon_pst_2015\ntools_visuaize(con_pst_2015)\n\"\"\"\n# Pst_2016\n\"\"\"\ncoll3={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pst_2016_depth':[df_guj['Pst_2016'].mean(),df_maha['Pst_2016'].mean(),\n                         df_kar['Pst_2016'].mean(),df_har['Pst_2016'].mean(),\n                         df_mp['Pst_2016'].mean(),df_up['Pst_2016'].mean(),df_raj['Pst_2016'].mean()],\n       'STD_depth_Pst_2016_depth':[df_guj['Pst_2016'].std(),df_maha['Pst_2016'].std(),\n                         df_kar['Pst_2016'].std(),df_har['Pst_2016'].std(),\n                         df_mp['Pst_2016'].std(),df_up['Pst_2016'].std(),df_raj['Pst_2016'].std()],\n        \"Median_Pst_2016_depth\":[df_guj['Pst_2016'].median(),df_maha['Pst_2016'].median(),\n                         df_kar['Pst_2016'].median(),df_har['Pst_2016'].median(),\n                         df_mp['Pst_2016'].median(),df_up['Pst_2016'].median(),df_raj['Pst_2016'].median()]}\ncon_pst_2016=pd.DataFrame(coll3)\ncon_pst_2016\ntools_visuaize(con_pst_2016)\n\"\"\"\n# Pst_2017\n\"\"\"\ncoll4={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pst_2017_depth':[df_guj['Pst_2017'].mean(),df_maha['Pst_2017'].mean(),\n                         df_kar['Pst_2017'].mean(),df_har['Pst_2017'].mean(),\n                         df_mp['Pst_2017'].mean(),df_up['Pst_2017'].mean(),df_raj['Pst_2017'].mean()],\n       'STD_depth_Pst_2017_depth':[df_guj['Pst_2017'].std(),df_maha['Pst_2017'].std(),\n                         df_kar['Pst_2017'].std(),df_har['Pst_2017'].std(),\n                         df_mp['Pst_2017'].std(),df_up['Pst_2017'].std(),df_raj['Pst_2017'].std()],\n        \"Median_Pst_2017_depth\":[df_guj['Pst_2017'].median(),df_maha['Pst_2017'].median(),\n                         df_kar['Pst_2017'].median(),df_har['Pst_2017'].median(),\n                         df_mp['Pst_2017'].median(),df_up['Pst_2017'].median(),df_raj['Pst_2017'].median()]}\ncon_pst_2017=pd.DataFrame(coll4)\ncon_pst_2017\ntools_visuaize(con_pst_2017)\n\"\"\"\n# Pst_2018\n\"\"\"\ncoll5={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pst_2018_depth':[df_guj['Pst_2018'].mean(),df_maha['Pst_2018'].mean(),\n                         df_kar['Pst_2018'].mean(),df_har['Pst_2018'].mean(),\n                         df_mp['Pst_2018'].mean(),df_up['Pst_2018'].mean(),df_raj['Pst_2018'].mean()],\n       'STD_depth_Pst_2018_depth':[df_guj['Pst_2018'].std(),df_maha['Pst_2018'].std(),\n                         df_kar['Pst_2018'].std(),df_har['Pst_2018'].std(),\n                         df_mp['Pst_2018'].std(),df_up['Pst_2018'].std(),df_raj['Pst_2018'].std()],\n        \"Median_Pst_2018_depth\":[df_guj['Pst_2018'].median(),df_maha['Pst_2018'].median(),\n                         df_kar['Pst_2018'].median(),df_har['Pst_2018'].median(),\n                         df_mp['Pst_2018'].median(),df_up['Pst_2018'].median(),df_raj['Pst_2018'].median()]}\ncon_pst_2018=pd.DataFrame(coll5)\ncon_pst_2018\ntools_visuaize(con_pst_2018)\n\"\"\"\n# Pst_2019\n\"\"\"\ncoll6={'State':['Gujarat', 'Maharastra', 'Karnataka', 'Harayna','MP', 'UP', 'Rajasthan'],\n      'Mean_Pst_2019_depth':[df_guj['Pst_2019'].mean(),df_maha['Pst_2019'].mean(),\n                         df_kar['Pst_2019'].mean(),df_har['Pst_2019'].mean(),\n                         df_mp['Pst_2019'].mean(),df_up['Pst_2019'].mean(),df_raj['Pst_2019'].mean()],\n       'STD_depth_pst_2019':[df_guj['Pst_2019'].std(),df_maha['Pst_2019'].std(),\n                         df_kar['Pst_2019'].std(),df_har['Pst_2019'].std(),\n                         df_mp['Pst_2019'].std(),df_up['Pst_2019'].std(),df_raj['Pst_2019'].std()],\n        \"Median_pst_2019\":[df_guj['Pst_2019'].median(),df_maha['Pst_2019'].median(),\n                         df_kar['Pst_2019'].median(),df_har['Pst_2019'].median(),\n                         df_mp['Pst_2019'].median(),df_up['Pst_2019'].median(),df_raj['Pst_2019'].median()]}\ncon_pst_2019=pd.DataFrame(coll6)\ncon_pst_2019\ntools_visuaize(con_pst_2019)\n\"\"\"\n# Importing Plotly to visuaize the box pot \n\"\"\"\ndffs=[con_table, con_pre_2015, con_pre_2016, con_pre_2017, con_pre_2018, con_pre_2019,\n                        con_pst_2015, con_pst_2016, con_pst_2017, con_pst_2018, con_pst_2019]\n\nfrom functools import reduce\ncontigancy_table=reduce(lambda left, right: pd.merge(left, right, on=\"State\"), dffs)\ncontigancy_table.T\ntools_visuaize(contigancy_table)\n\"\"\"\n# Making the dataframe as image\n\"\"\"\ncontiganc_style=contigancy_table.style.background_gradient()\ncontiganc_style\npip install dataframe_image\nimport dataframe_image as dfi","meta":"{'source': 'AI4Code', 'id': 'af69213cdc7a56'}"}
{"id":"72613","text":"# 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\nimport matplotlib.pyplot as plt # --> for data visulization\nimport seaborn as sns # --> for data visulization\nfrom dateutil import parser # --> convert time in date time datatype\n\ndf = pd.read_csv('..\/input\/app-data\/appdata10.csv')\ndf.head()\ndf.tail()\ndf.shape\nfor i in range(0,6):\n    print(df.loc[i,'screen_list'],'\\n') \ndf.isnull().sum()\ndf.describe()\ndf.info()\nfeatures = df.columns\nfor i in features:\n    print('unique value of {} \\n {}  \\n len is {} '.format(i, df[i].unique(), len(df[i].unique())))\ndf['hour'] = df.hour.str.slice(1,3).astype(int)\ndf.head()\ndf.dtypes\ndf1 = df.drop(['first_open', 'screen_list','user','enrolled_date'], axis = 1)\ndf1.head()\n\"\"\"\n# Heatmap using Correlation metrix\n\"\"\"\nplt.figure(figsize=(14,8))\nsns.heatmap(df1.corr(),annot=True)\nplt.title('DF1 Heatmap correlatin matrix', fontsize=15)\n\"\"\"\n# pair plot \n\"\"\"\nsns.pairplot(df1, hue='enrolled') \n\"\"\"\n# countplot of enrolled\n\"\"\"\nsns.countplot(df1.enrolled)\nnot_enrolled_user = (df1.enrolled<1).sum()\nenrolled_user = (50000-not_enrolled_user).sum()\nnot_enrolled_user\nenrolled_user\n\"\"\"\n# histogram of each feature of df1\n\"\"\"\nplt.figure(figsize=(20,10))\nfeatures = df1.columns\nfor i, j in enumerate(features):\n    plt.subplot(3,3,i+1)\n    plt.title(f'Histogram of {j}', fontsize= 15)\n    bins = len(df1[j].unique())\n    plt.hist(df1[j], bins=bins,rwidth=0.8,linewidth=2, edgecolor= 'y')\nplt.subplots_adjust(hspace=0.5)\n    \n#   1) In first histogram easily find that wednesday (2) and thursday (3) less user enrolled \n#   2) In hour histogram near 8 to 12 less user enrolled \n#   3) Iin age histogram 20 to 40 aged user enrolled most \n#   4) In histogram of numscreen above 40 screen user is to less \n#   5) remaining all histogram is in 0 and 1\nfor i,j in enumerate(features):\n    print(i,j)\n\"\"\"\n# correlation bar plot with 'enrolled ' features\n\"\"\"\nsns.set()\nplt.figure(figsize=(15,7))\nplt.title('Correlation Bar Plot of Enrolled Features', fontsize= 20)\ndf2 = df1.drop(['enrolled'], axis= 1)\naxis = sns.barplot(df2.columns,df2.corrwith(df1.enrolled))\naxis.tick_params(labelsize=15, labelrotation = 20)\ndf.dtypes\ndf.head()\nscreen_data = pd.read_csv('..\/input\/app-data\/top_screens.csv').top_screens.values\nscreen_data\ntype(screen_data)\ndf['screen_list'] = df.screen_list.astype(str)+','\ndf.head()\nfor screen_name in screen_data:\n    df[screen_name] = df.screen_list.str.contains(screen_name).astype(int)\n    df['screen_list'] = df.screen_list.str.replace(screen_name+',',\"\")\ndf.shape\ndf.head()\ndf.loc[0,'screen_list']\ndf['remain_screen_list'] = df.screen_list.str.count(\",\")\n# droped both time columns\ndf.shape\ndf = df.drop(['first_open','enrolled_date','screen_list'], axis=1)\ndf.columns\n\ndf.head()\n# sum of all saving screen at one place\nsaving_screen=[\n    'Saving9',\n    'Saving1',\n    'Saving8',\n    'Saving10',\n    'Saving4',\n    'Saving7',\n    'Saving2',\n    'Saving6',\n    'Saving5',\n    'Saving2Amount'\n]\ndf['saving_screen_count']= df[saving_screen].sum(axis=1)\ndf = df.drop(columns= saving_screen)\ndf.shape\n# sum of all loan column at one place\nloan = [\n    'Loan2',\n    'Loan',\n    'Loan4',\n    'Loan3'\n]\ndf['loan_col']= df[loan].sum(axis=1)\n\ndf = df.drop(columns= loan)\n# credit column sum\ncredit = [\n    'Credit3Container',\n    'Credit3',\n    'Credit2',\n    'Credit3Dashboard',\n    'Credit1'\n]\ndf['credit_col']= df[credit].sum(axis=1)\ndf = df.drop(columns=credit)\n# for cc \ncc = [\n    'CC1',\n    'CC1Category',\n    'CC3',\n]\ndf['cc_col'] = df[cc].sum(axis=1)\ndf =df.drop(columns=cc)\ndf.shape\ndf.describe()\ndf.head() # our pure cleaned data\n# plt.figure(figsize=(20,10))\n# sns.heatmap(df.corr(),annot=True, linewidth=2) # --> its take a to much time for run\nx= df.drop(columns = 'enrolled')\ny = df['enrolled']  # our target \nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=10)\nx_train.shape\nx_test.shape\ny_train.shape\n\"\"\"\nThe multiple features in the different units so for the best accuracy need to convert all features in a single unit.\n\n\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nx_train_sc = sc.fit_transform(x_train)\nx_test_sc = sc.transform(x_test)\n\"\"\"\n# Model Building With Ml algorithm\n\"\"\"\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\n\"\"\"\n# Decision Tree Classifier\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nmodel_DTC = DecisionTreeClassifier(criterion='entropy', random_state=10)  # for gini entropy score is 0.7081\nmodel_DTC.fit(x_train,y_train)\ny_predict_DTC = model_DTC.predict(x_test)\naccuracy_score(y_test, y_predict_DTC) \n# standerd scaling data to build model\nmodel_DTC_SC =  DecisionTreeClassifier(criterion='entropy', random_state=10) # for gini 0.5502\nmodel_DTC_SC.fit(x_train_sc, y_train)\ny_predict_DTC_SC = model_DTC_SC.predict(x_test_sc)\naccuracy_score(y_test,y_predict_DTC_SC)\n\"\"\"\n#  K -  Nearest Neighbor \n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nmodel_KN = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')\nmodel_KN.fit(x_train,y_train)\ny_predicted_KN = model_KN.predict(x_test)\naccuracy_score(y_test,y_predicted_KN)\n# standerd scaling data to build model\nmodel_KN_SC  = KNeighborsClassifier(n_neighbors=5,p=2, metric='minkowski')\nmodel_KN_SC.fit(x_train_sc,y_train)\ny_predicted_KN_SC = model_KN_SC.predict(x_test_sc)\naccuracy_score(y_test,y_predicted_KN_SC)\n\"\"\"\n#  Naive Bayes\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nmod_G = GaussianNB()\nmod_G.fit(x_train,y_train)\ny_predicted_G = mod_G.predict(x_test)\naccuracy_score(y_test,y_predicted_G)\n# standerd scaling data to build model\nmod_G_SC = GaussianNB()\nmod_G_SC.fit(x_train_sc,y_train)\ny_predicted_G_SC = mod_G_SC.predict(x_test_sc)\naccuracy_score(y_test,y_predicted_G_SC)\n\"\"\"\n# Random Forest \n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nmodel_RFC = RandomForestClassifier(n_estimators=10, criterion='gini')\nmodel_RFC.fit(x_train,y_train)\ny_predicted_RFC = model_RFC.predict(x_test)\naccuracy_score(y_test,y_predicted_RFC)\n# standerd scaling data to build model\nmodel_RFC_SC = RandomForestClassifier(n_estimators=10, criterion='gini')\nmodel_RFC_SC.fit(x_train_sc,y_train)\ny_predicted_RFC_SC = model_RFC_SC.predict(x_test_sc)\naccuracy_score(y_test,y_predicted_RFC_SC)\n\"\"\"\n#  Logistic Regreesion\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression(penalty='l2', C = 1, random_state=10)\nmodel.fit(x_train,y_train)\ny_predicted_l = model.predict(x_test)\n# accuracy_score(y_test,y_predicted_l)\nmodel.score(x_test,y_test)\n# standerd scaling data to build model\nmodel_sc = LogisticRegression(penalty='l2', C = 1, random_state=10)\nmodel_sc.fit(x_train_sc, y_train)\ny_predicted_ls = model_sc.predict(x_test_sc)\naccuracy_score(y_test,y_predicted_ls)\n\"\"\"\n#  Support vactor Machine\n\"\"\"\nfrom sklearn.svm import SVC\nmodel_svc = SVC()\nmodel_svc.fit(x_train,y_train)\nmodel_svc.predict(x_test)\nmodel.score(x_test,y_test)\n\n# standerd scaling data to build model\nmodel_svc_sc= SVC()\nmodel_svc_sc.fit(x_train_sc,y_train)\ny_predicted_svc_sc = model_svc_sc.predict(x_test_sc)\naccuracy_score(y_test,y_predicted_svc_sc)\n\"\"\"\n# XGBoost \n\"\"\"\nfrom xgboost import XGBClassifier\nxgb_model = XGBClassifier(eval_metric='mlogloss', use_label_encoder=False)\n # eval_metric='mlogloss' parameter to not change behavior and not show a warning\nxgb_model.fit(x_train, y_train)\ny_pred_xgb = xgb_model.predict(x_test)\naccuracy_score(y_test, y_pred_xgb)\n# train with Standert Scaling dataset\nxgb_model_sc = XGBClassifier(eval_metric='mlogloss', use_label_encoder=False)\n#  use_label_encoder=False to handle warning\nxgb_model_sc.fit(x_train_sc, y_train)\ny_pred_xgb_sc = xgb_model_sc.predict(x_test_sc)\naccuracy_score(y_test, y_pred_xgb_sc)\ndata = { 'model_name' : ['Desicion Tree', 'K_Nearest', 'naive Bayes', 'Random forest','Logistic Regression', 'SVM', 'XGBoost'],\n        'Training Type' : ['Reguler','SC','SC','SC','SC','SC','SC'],\n        'score' : ['0.7106','0.7368','0.6967','0.7615','0.7522','0.7743','0.7814']\n}\nbest_model = pd.DataFrame(data)\nbest_model\n# we use xgboost and svm give the best score than other ML algorithm\n# but we are going with xgboost because of xgboost is much more better then svm\n\"\"\"\nConfusion Matrix\n\"\"\"\nplt.figure(figsize=(7,4))\ncm_xgb = confusion_matrix(y_test,y_pred_xgb_sc)\nsns.heatmap(cm_xgb, annot=True, fmt='g')\nplt.title('XGBoost model Confusion Matrix')\n\"\"\"\n#  Classification report\n\"\"\"\ncr_xgb = classification_report(y_test,y_pred_xgb_sc)\nprint('Classification Report --------> \\n', cr_xgb)\n\"\"\"\n# Cross Validation\n\"\"\"\nfrom sklearn.model_selection import cross_val_score\nmodel = XGBClassifier(eval_metric='mlogloss',use_label_encoder=False)\ncross_validation = cross_val_score(model, x_train_sc, y_train, cv=5)\ncross_validation\ncross_validation.mean()\n\"\"\"\n**The mean value cross-validation and XGBoost model accuracy is 78%. That means our XGBoost model is a generalized model.**\n\"\"\"\n# save the model using pickle\nimport pickle\nwith open('app_data_pickle','wb') as file:\n    pickle.dump(xgb_model_sc,file)\n# save the model using joblib\nimport joblib\njoblib.dump(xgb_model_sc,'app_data_model_joblib')","meta":"{'source': 'AI4Code', 'id': '85a94d0ad85492'}"}
{"id":"58683","text":"\"\"\"\n> **Problem overview**\n\nIn this playground competition, hosted in partnership with Google Cloud and Coursera, you are tasked with predicting the fare amount (inclusive of tolls) for a taxi ride in New York City given the pickup and dropoff locations. While you can get a basic estimate based on just the distance between the two points, this will result in an RMSE of $5-$8, depending on the model used (see the starter code for an example of this approach in Kernels). Your challenge is to do better than this using Machine Learning techniques!\n\nTo learn how to handle large datasets with ease and solve this problem using TensorFlow, consider taking the Machine Learning with TensorFlow on Google Cloud Platform specialization on Coursera -- the taxi fare problem is one of several real-world problems that are used as case studies in the series of courses. To make this easier, head to Coursera.org\/NEXTextended to claim this specialization for free for the first month!\n\"\"\"\n# import python standard library\nimport math\n\n# import data manipulation library\nimport numpy as np\nimport pandas as pd\n\n# import data visualization library\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# import model function from sklearn\nfrom sklearn.ensemble import RandomForestRegressor\n\n# import sklearn model selection\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\n\n# import sklearn model evaluation regression metrics\nfrom sklearn.metrics import mean_squared_error\n\"\"\"\n> **Acquiring training and testing data**\n\nWe start by acquiring the training and testing datasets into Pandas DataFrames.\n\"\"\"\n# acquiring training and testing data\ndf_train = pd.read_csv('..\/input\/train.csv', nrows=2000000, parse_dates=['pickup_datetime'])\ndf_test = pd.read_csv('..\/input\/test.csv', parse_dates=['pickup_datetime'])\n# visualize head of the training data\ndf_train.head(n=3)\n# visualize tail of the testing data\ndf_test.tail(n=3)\n# combine training and testing dataframe\ndf_train['datatype'], df_test['datatype'] = 'training', 'testing'\ndf_test.insert(1, 'fare_amount', 0)\ndf_data = pd.concat([df_train, df_test], ignore_index=True)\n\"\"\"\n> **Feature exploration, engineering and cleansing**\n\nHere we generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset\u2019s distribution together with exploring some data.\n\"\"\"\ndef scatterplot(numerical_x: list or str, numerical_y: list or str, data: pd.DataFrame, figsize: tuple = (4, 3), ncols: int = 5, nrows: int = None) -> plt.figure:\n    \"\"\" Return a scatter plot applied for numerical variable in x-axis vs numerical variable in y-axis.\n    \n    Args:\n        numerical_x (list or str): The numerical variable in x-axis.\n        numerical_y (list or str): The numerical variable in y-axis.\n        data (pd.DataFrame): The data to plot.\n        figsize (tuple): The matplotlib figure size width and height in inches. Default to (4, 3).\n        ncols (int): The number of columns for axis in the figure. Default to 5.\n        nrows (int): The number of rows for axis in the figure. Default to None.\n    \n    Returns:\n        plt.figure: The plot figure.\n    \"\"\"\n    \n    numerical_x, numerical_y = [numerical_x] if type(numerical_x) == str else numerical_x, [numerical_y] if type(numerical_y) == str else numerical_y\n    if nrows is None: nrows = (len(numerical_x)*len(numerical_y) - 1) \/\/ ncols + 1\n    \n    fig, axes = plt.subplots(figsize=(figsize[0]*ncols , figsize[1]*nrows), ncols=ncols, nrows=nrows)\n    axes = axes.flatten()\n    _ = [sns.scatterplot(x=vj, y=vi, data=data, ax=axes[i*len(numerical_x) + j], rasterized=True) for i, vi in enumerate(numerical_y) for j, vj in enumerate(numerical_x)]\n    return fig\ndef distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:\n    \"\"\" Return the distance between 2 points of latitude and longitude.\n    \n    Args:\n        lat1 (float): The latitude of the first coordinate.\n        lon1 (float): The longitude of the first coordinate.\n        lat2 (float): The latitude of the second coordinate.\n        lon2 (float): The longitude of the second coordinate.\n    \n    Returns:\n        float: The distance between 2 points of latitude and longitude.\n    \"\"\"\n    angle = 0.017453292519943295 #math.pi \/ 180\n    x = 0.5 - np.cos((lat2 - lat1) * angle) \/ 2 + np.cos(lat1 * angle) * np.cos(lat2 * angle) * (1 - np.cos((lon2 - lon1) * angle)) \/ 2\n    return 0.6213712 * 12742 * np.arcsin(np.sqrt(x))\n# describe training and testing data\ndf_data.describe(include='all')\n# list all features type number\ncol_number = df_data.select_dtypes(include=['number']).columns.tolist()\nprint('features type number:\\n items %s\\n length %d' %(col_number, len(col_number)))\n\n# list all features type object\ncol_object = df_data.select_dtypes(include=['object']).columns.tolist()\nprint('features type object:\\n items %s\\n length %d' %(col_object, len(col_object)))\n# feature exploration: histogram of all numeric features\n_ = df_data.hist(bins=20, figsize=(20, 15))\n# feature extraction: fare amount\ndf_data['fare_amount'] = np.log1p(df_data['fare_amount'])\n# feature extraction: combination of keyword date\ndf_data['year'] = df_data['pickup_datetime'].dt.year\ndf_data['quarter'] = df_data['pickup_datetime'].dt.quarter\ndf_data['month'] = df_data['pickup_datetime'].dt.month\ndf_data['weekofyear'] = df_data['pickup_datetime'].dt.weekofyear\ndf_data['weekday'] = df_data['pickup_datetime'].dt.weekday\ndf_data['dayofweek'] = df_data['pickup_datetime'].dt.dayofweek\ndf_data['hour'] = df_data['pickup_datetime'].dt.hour\n# feature extraction: distance\ndf_data['distance_euclidean'] = distance(df_data['pickup_latitude'], df_data['pickup_longitude'], \\\n                                         df_data['dropoff_latitude'], df_data['dropoff_longitude'])\ndf_data['distance_latitude'] = df_data['dropoff_latitude'] - df_data['pickup_latitude']\ndf_data['distance_longitude'] = df_data['dropoff_longitude'] - df_data['pickup_longitude']\n# feature extraction: distance to specific location\nnyc = (40.7128, -74.0060)\njfk = (40.6413, -73.7781)\newr = (40.6895, -74.1745)\ndf_data['distance_pickup_to_nyc'] = distance(df_data['pickup_latitude'], df_data['pickup_longitude'], nyc[0], nyc[1])\ndf_data['distance_pickup_to_jfk'] = distance(df_data['pickup_latitude'], df_data['pickup_longitude'], jfk[0], jfk[1])\ndf_data['distance_pickup_to_ewr'] = distance(df_data['pickup_latitude'], df_data['pickup_longitude'], ewr[0], ewr[1])\ndf_data['distance_dropoff_to_nyc'] = distance(df_data['dropoff_latitude'], df_data['dropoff_longitude'], nyc[0], nyc[1])\ndf_data['distance_dropoff_to_jfk'] = distance(df_data['dropoff_latitude'], df_data['dropoff_longitude'], jfk[0], jfk[1])\ndf_data['distance_dropoff_to_ewr'] = distance(df_data['dropoff_latitude'], df_data['dropoff_longitude'], ewr[0], ewr[1])\n# feature extraction: fare amount per mile\ndf_data['fare_per_mile'] = df_data['fare_amount'] \/ df_data['distance_euclidean']\ndf_data['fare_per_mile'] = df_data['fare_per_mile'].apply(lambda x: 0 if x == float('inf') else x)\ndf_data['fare_per_mile'] = df_data['fare_per_mile'].fillna(0)\n# feature exploration: fare amount\ncol_number = df_data.select_dtypes(include=['number']).columns.tolist()\n_ = scatterplot(col_number, 'fare_amount', df_data[df_data['datatype'] == 'training'])\n# feature exploration: fare per mile\ncol_number = df_data.select_dtypes(include=['number']).columns.tolist()\n_ = scatterplot(col_number, 'fare_per_mile', df_data[df_data['datatype'] == 'training'])\n# feature exploration: season dataframe\ndf_season = df_data[df_data['datatype'] == 'training'].groupby(['year', 'month'], as_index=False).agg({\n    'fare_amount': 'mean'\n})\nfig, axes = plt.subplots(figsize=(20, 3))\n_ = sns.pointplot(x='month', y='fare_amount', data=df_season, join=True, hue='year')\n# feature exploration: season dataframe\ndf_season = df_data[df_data['datatype'] == 'training'].groupby(['year', 'hour'], as_index=False).agg({\n    'fare_amount': 'mean'\n})\nfig, axes = plt.subplots(figsize=(20, 3))\n_ = sns.pointplot(x='hour', y='fare_amount', data=df_season, join=True, hue='year')\n# feature extraction: drop na\ndf_data = df_data.dropna()\n\"\"\"\nAfter extracting all features, it is required to convert category features to numerics features, a format suitable to feed into our Machine Learning models.\n\"\"\"\n# convert category codes for data dataframe\ndf_data = pd.get_dummies(df_data, columns=['datatype'], drop_first=True)\n# describe data dataframe\ndf_data.describe(include='all')\n# verify dtypes object\ndf_data.info()\n\"\"\"\n> **Analyze and identify patterns by visualizations**\n\nLet us generate some correlation plots of the features to see how related one feature is to the next. To do so, we will utilize the Seaborn plotting package which allows us to plot very conveniently as follows.\n\nThe Pearson Correlation plot can tell us the correlation between features with one another. If there is no strongly correlated between features, this means that there isn't much redundant or superfluous data in our training data. This plot is also useful to determine which features are correlated to the observed value.\n\nThe pairplots is also useful to observe the distribution of the training data from one feature to the other.\n\nThe pivot table is also another useful method to observe the impact between features.\n\"\"\"\n# compute pairwise correlation of columns, excluding NA\/null values and present through heat map\ncorr = df_data[df_data['datatype_training'] == 1].drop(['key'], axis=1).corr()\nfig, axes = plt.subplots(figsize=(20, 15))\nheatmap = sns.heatmap(corr, annot=True, cmap=plt.cm.RdBu, fmt='.1f', square=True, vmin=-0.8, vmax=0.8)\n\"\"\"\n> **Model, predict and solve the problem**\n\nNow, it is time to feed the features to Machine Learning models.\n\"\"\"\n# select all features\nx = df_data[df_data['datatype_training'] == 1].drop(['key', 'pickup_datetime', 'fare_amount', 'fare_per_mile', 'datatype_training'], axis=1)\ny = df_data[df_data['datatype_training'] == 1]['fare_amount']\n# perform train-test (validate) split\nx_train, x_validate, y_train, y_validate = train_test_split(x, y, test_size=0.25, random_state=58)\n# random forest regression model setup\nmodel_forestreg = RandomForestRegressor(n_estimators=10, max_depth=20, min_samples_split=1000, random_state=58)\n\n# random forest regression model fit\nmodel_forestreg.fit(x_train, y_train)\n\n# random forest regression model prediction\nmodel_forestreg_ypredict = model_forestreg.predict(x_validate)\n\n# random forest regression model metrics\nmodel_forestreg_rmse = mean_squared_error(y_validate, model_forestreg_ypredict) ** 0.5\nmodel_forestreg_cvscores = np.sqrt(np.abs(cross_val_score(model_forestreg, x, y, cv=5, scoring='neg_mean_squared_error')))\nprint('random forest regression\\n  root mean squared error: %0.4f, cross validation score: %0.4f (+\/- %0.4f)' %(model_forestreg_rmse, model_forestreg_cvscores.mean(), 2 * model_forestreg_cvscores.std()))\n\"\"\"\n> **Supply or submit the results**\n\nOur submission to the competition site Kaggle is ready. Any suggestions to improve our score are welcome.\n\"\"\"\n# model selection\nfinal_model = model_forestreg\n\n# prepare testing data and compute the observed value\nx_test = df_data[df_data['datatype_training'] == 0].drop(['key', 'pickup_datetime', 'fare_amount', 'fare_per_mile', 'datatype_training'], axis=1)\ny_test = pd.DataFrame(np.expm1(final_model.predict(x_test)), columns=['fare_amount'], index=df_data.loc[df_data['datatype_training'] == 0, 'key'])\n# submit the results\nout = pd.DataFrame({'key': y_test.index, 'fare_amount': y_test['fare_amount']})\nout.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '6c61021930a6e2'}"}
{"id":"110496","text":"\"\"\"\n# MERS_IGS\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly\nimport plotly.graph_objects as go\ndf=pd.read_csv('..\/input\/mers-igs\/MERS_IGS.csv')\ndf.head()\ndf['datetime'] = df['day'].map(str) + '-' + df['month'].map(str) + '-' + df['year'].map(str)\ndf['datetime']=pd.to_datetime(df['datetime'])\ndf.info()\ndf.head()\nplt.figure(figsize=(10, 8))\nplt.plot(df['year'], df['longitude'], 'b.', label = 'Longitude')\nplt.plot(df['year'], df['latitude'], 'r.', label = 'Latitude')\nplt.plot(df['year'],df['height'],'y.',label='Height')\nplt.xlabel('Date'); plt.ylabel('Residual'); plt.title('Mers ISG Residual')\nplt.legend();\ncols_plot = ['longitude', 'latitude', 'height','datetime']\naxes = df[cols_plot].plot(x='datetime',marker='.', alpha=0.5, linestyle='None', figsize=(11, 9), subplots=True)\nfor ax in axes:\n    ax.set_ylabel('Residual')\n    ax.set_xlabel('Time(Year)')\nlong_df=df.groupby('datetime')['longitude'].sum().reset_index()\nlong_df= long_df.set_index('datetime')\nlong_df.index\ny = long_df['longitude']. resample ('MS'). mean ()\ny.plot (figsize= (12, 6)) \nplt.ylabel('LONG\u0130TUDE')\nplt.xlabel('TIME')\nplt.title('MERS IGS RES\u0130DUAL')\nplt.show()\nlat_df=df.groupby('datetime')['latitude'].sum().reset_index()\nlat_df=df.set_index('datetime')\ny=lat_df['latitude'].resample('MS').mean()\ny.plot(figsize=(12,6))\nplt.ylabel('LAT\u0130TUDE')\nplt.xlabel('TIME')\nplt.title('MERS IGS RES\u0130DUAL')\nplt.show()\nh_df=df.groupby('datetime')['height'].sum().reset_index()\nh_df= h_df.set_index('datetime')\nh_df.index\ny = h_df['height']. resample ('MS'). mean ()\ny.plot (figsize= (12, 6)) \nplt.ylabel('HEIGHT')\nplt.xlabel('TIME')\nplt.title('MERS IGS RES\u0130DUAL')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'cb0ebd29749768'}"}
{"id":"22901","text":"\"\"\"\n**Project Repository:** https:\/\/github.com\/GokulKarthik\/deep-learning-projects-pytorch\n\"\"\"\nimport os\nimport time\nfrom tqdm.notebook import tqdm\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n#from torchsummary import summary\n\nimport string\nfrom collections import Counter\n#writer = SummaryWriter(os.path.join(\"runs\", \"baby-names\"))\n\"\"\"\n## 1. Load data\n\"\"\"\n\"\"\"\n[This Kaggle dataset](https:\/\/www.kaggle.com\/kaggle\/us-baby-names#NationalNames.csv) has names of the child born from 1880 to 2014 along with other features such as Gender and Count. I am going to use this to build a name generator model using sampling of the trained character level LSTM network\n\"\"\"\ndata_path = os.path.join(\"\/kaggle\", \"input\", \"us-baby-names\", \"NationalNames.csv\")\ndata = pd.read_csv(data_path)\nprint(data.shape)\ndata.head()\ndata.info()\n\"\"\"\n## 2. Clean data\n\"\"\"\ndef clean(name):\n    \n    name = name.lower().strip()\n    name = \"\".join([c for c in name if c in string.ascii_lowercase])\n    name += \".\"\n    return name\ndata['Name'] = data['Name'].apply(clean)\ndata.head()\nnames = data[['Name', 'Count']].groupby('Name').sum()\ndel names.index.name\nprint(len(names))\nnames.head()\npd.Series(names.index).apply(len).max()\nmax_length = 11\nlen_filter = pd.Series(names.index).apply(lambda x: len(x)<=max_length).tolist() # max length of 10 excluding '.'\nprint(len_filter[:10])\nprint(names.shape)\nnames = names[len_filter]\nprint(names.shape)\npd.Series(names.index).apply(len).max()\nnames = names.sort_values(by=['Count'], ascending=False)\nnames.head()\n\"\"\"\n## 3. Set training data\n\"\"\"\n\"\"\"\nWe need a list of names to start building the name generator model. One naive approach for this dataset could be to just take list of unique names. The number of uniques names is 93889, which is large. So, if we sample uniformly from the unique names, the model may learn to generate uncommon and less interesting names. Also if we use the exact counts the model will generate more common names. So we have to sample in between these two. Normalized counts can be used to sample for training.\n\"\"\"\nnames['Count'].describe()\nalpha = 0.8\nnames['Count'].apply(lambda x: np.power(x, alpha)).apply(np.int).describe()\nnames['count_normalized'] = names['Count'].apply(lambda x: np.power(x, alpha)).apply(np.int)\nnames.head()\ncount_normalized_sum = names['count_normalized'].sum()\nprint(count_normalized_sum)\nnames['p'] = names['count_normalized'] \/ count_normalized_sum\nnames.head()\nnp.random.seed(0)\nnames_list = np.random.choice(names.index, size=10**5, p=names['p'], replace=True)\nprint(len(names_list))\nprint(names_list[:50])\npd.Series(names_list).value_counts()\ndel data, names\n\"\"\"\n## 3. Define utilities\n\"\"\"\nchars = \".\" + string.ascii_lowercase\nnum_chars = len(chars)\nprint(chars)\nprint(num_chars)\nchar_to_id = {c:i for i, c in enumerate(chars)}\nid_to_char = {v:k for k, v in char_to_id.items()}\nprint(char_to_id)\nprint(id_to_char)\nprint(max_length)\n\"\"\"\n## 4. Define dataset\n\"\"\"\nclass NamesDataset(Dataset):\n    \n    def __init__(self, names_list):\n        self.names_list = names_list\n        \n    def __len__(self):\n        return len(self.names_list)\n    \n    def __getitem__(self, idx):\n        x_str = self.names_list[idx].ljust(max_length, \".\")[:max_length]\n        y_str = x_str[1:] + \".\"\n        \n        x = torch.zeros((max_length, num_chars))\n        y = torch.zeros(max_length)\n        for i, c in enumerate(x_str):\n            x[i, char_to_id[c]] = 1\n        for i, c in enumerate(y_str):\n            y[i] = char_to_id[c]\n            \n        return x, y\ntrainset = NamesDataset(names_list)\n\"\"\"\n## 5. Define dataloader\n\"\"\"\ntrain_batch_size = 256\ncpu_count = os.cpu_count()\nprint(cpu_count)\ntrain_loader = DataLoader(trainset, batch_size=train_batch_size, shuffle=True, num_workers=cpu_count)\nprint(len(train_loader))\ntrain_iter = iter(train_loader)\nX, Y = train_iter.next()\nprint(X.size(), Y.size())\n\"\"\"\n## 6. Define model\n\"\"\"\ninput_size = num_chars\nhidden_size = 54\noutput_size = num_chars\nnum_layers = 1\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\ndevice = torch.device(device)\nclass Model(nn.Module):\n    \n    def __init__(self, input_size, hidden_size, output_size, num_layers):\n        super(Model, self).__init__()\n        self.input_size = input_size\n        self.hidden_size = hidden_size\n        self.num_layers = num_layers\n        self.lstm1 = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)\n        self.fc2 = nn.Linear(hidden_size, output_size)\n        self.fc3 = nn.Linear(output_size, output_size)\n        \n    def forward(self, X, states):\n        ht, ct = states\n        batch_size = X.size(0)\n        out, (ht, ct) = self.lstm1(X, (ht, ct))\n        out = F.relu(self.fc2(out))\n        out = self.fc3(out)\n        return out, (ht, ct) # out: Size([batch_size, max_length, num_chars])\nmodel = Model(input_size=input_size, hidden_size=hidden_size, output_size=output_size, num_layers=num_layers)\nmodel = nn.DataParallel(model)\nmodel = model.to(device)\n#list(model.parameters())\nht = torch.zeros((num_layers, train_batch_size, hidden_size)).to(device)\nct = torch.zeros((num_layers, train_batch_size, hidden_size)).to(device)\n#writer.add_graph(model, (X, (ht, ct)))\n#writer.close()\n#summary(model, input_size=(max_length, num_chars))\n\"\"\"\n## 7. Set optimizer\n\"\"\"\nlr = 0.005\nstep_size = len(train_loader) * 1\ngamma = 0.95\nprint(step_size)\ncriterion = nn.CrossEntropyLoss(reduction='mean')\noptimizer = optim.Adam(model.parameters(), lr=lr)\nlr_scheduler = optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=step_size, gamma=gamma)\n\"\"\"\n## 8. Define sampler\n\"\"\"\ndef generate_name(model, start='a', k=5):\n    \n    if len(start) >= max_length:\n        return name\n    \n    with torch.no_grad():\n        \n        ht = torch.zeros((num_layers, 1, hidden_size)).to(device)\n        ct = torch.zeros((num_layers, 1, hidden_size)).to(device)\n        length = 0\n        name = start\n        \n        for char in start:\n            X = torch.zeros((1, 1, num_chars)) # [batch_size, timestep, num_chars]\n            X[0, 0, char_to_id[char]] = 1\n            out, (ht, ct) = model(X, (ht, ct))\n            length += 1\n        vals, idxs = torch.topk(out[0], k) # 0 -> first eg in a batch\n        idx = np.random.choice(idxs.cpu().numpy()[0]) # 0 -> first...\n        char = id_to_char[idx]\n        vals, idxs = torch.topk(out[0], k) # 0 -> first eg in a batch\n        idx = np.random.choice(idxs.cpu().numpy()[0]) # 0 -> first...\n        char = id_to_char[idx]\n        \n        while char != \".\" and length <= max_length-1:\n            X = torch.zeros((1, 1, num_chars)) # [batch_size, timestep, num_chars]\n            X[0, 0, char_to_id[char]] = 1\n            out, (ht, ct) = model(X, (ht, ct))\n            vals, idxs = torch.topk(out[0], k) # 0 -> first eg in a batch\n            idx = np.random.choice(idxs.cpu().numpy()[0]) # 0 -> first...\n            char = id_to_char[idx]\n            length += 1\n            name += char\n    \n        if name[-1] != \".\":\n            name += \".\"\n    \n    return name\ndef sampler(model, start='a', n=10, k=5, only_new=False):\n    \n    names = []\n    cnt = 0\n    while cnt <= n:\n        name = generate_name(model=model, start=start, k=k)\n        if only_new: \n            if name not in names_list and name not in names:\n                names.append(name)\n                cnt += 1\n        else:\n            if name not in names:\n                names.append(name)\n                cnt += 1\n    names = [name[:-1].title() for name in names]\n    \n    return names\n\"\"\"\n## 9. Train model\n\"\"\"\nepochs = 50\nprint_every_n_epochs = epochs \/\/ 10\nepoch_losses = []\nepoch_lrs = []\niteration_losses = []\niteration_lrs = []\n\nfor epoch in tqdm(range(1, epochs+1), desc=\"Epochs\"):\n    epoch_loss = 0\n    epoch_lr = 0\n    \n    for i, (X, Y) in tqdm(enumerate(train_loader, 1), total=len(train_loader), desc=\"Epoch-{}\".format(epoch)):\n    #for i, (X, Y) in enumerate(train_loader, 1):\n        X, Y = X.to(device), Y.to(device)\n        \n        ht = torch.zeros((num_layers, X.size(0), hidden_size)).to(device)\n        ct = torch.zeros((num_layers, X.size(0), hidden_size)).to(device)\n\n        optimizer.zero_grad()\n        Y_pred_logits, (ht, ct) = model(X, (ht, ct))\n        Y_pred_logits = Y_pred_logits.transpose(1, 2) # Check Loss Doc: [N, d1, C] -> [N, C, d1]\n        loss = criterion(Y_pred_logits, Y.long())\n        loss.backward(retain_graph=True)\n        optimizer.step()\n        lr_scheduler.step()\n        \n        iteration_losses.append(loss.item())\n        iteration_lrs.append(lr_scheduler.get_lr()[0])\n        epoch_loss += loss.item()\n        epoch_lr += lr_scheduler.get_lr()[0]\n        \n    epoch_loss \/= len(train_loader)\n    epoch_lr \/= len(train_loader)\n    epoch_losses.append(epoch_loss)\n    epoch_lrs.append(epoch_lr)\n    \n    if epoch % print_every_n_epochs == 0:    \n        message = \"Epoch:{}    Loss:{}    LR:{}\".format(epoch, epoch_loss, epoch_lr)\n        print(message)\n        names = sampler(model, start='jo', n=10, k=10, only_new=False)\n        print(names)\nfig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15, 8))\nax1.plot(epoch_losses, marker=\"o\", markersize=5)\nax1.set_title(\"Loss\")\nax2.plot(epoch_lrs, marker=\"o\", markersize=5)\nax2.set_title(\"LR\")\nplt.xlabel(\"Epochs\")\nplt.show()\nfig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15, 8))\nax1.plot(iteration_losses[::])\nax1.set_title(\"Loss\")\nax2.plot(iteration_lrs[::])\nax2.set_title(\"LR\")\nplt.xlabel(\"Iterations\")\nplt.show()\nwindow = 100\nplt.figure(figsize=(15, 4))\npd.Series(iteration_losses).rolling(window=window).mean().iloc[window-1:].plot()\nplt.show()\npath = os.path.join(\"\/kaggle\", \"working\", \"classifier.pth\")\ntorch.save(model.state_dict(), path)\n\"\"\"\n## 10. Generate new baby names\n\"\"\"\npath = os.path.join(\"\/kaggle\", \"working\", \"classifier.pth\")\nmodel = Model(input_size=num_chars, hidden_size=hidden_size, output_size=output_size, num_layers=num_layers)\nmodel = nn.DataParallel(model)\nmodel.load_state_dict(torch.load(path))\nnames = sampler(model, start='indi', n=10, k=5, only_new=True)\nprint(names)\nnames = sampler(model, start='herb', n=10, k=5, only_new=False)\nprint(names)\nnames = sampler(model, start='su', n=10, k=5, only_new=True)\nprint(names)\nnames = sampler(model, start='vis', n=10, k=5, only_new=True)\nprint(names)\nnames = sampler(model, start='a', n=10, k=3, only_new=True)\nprint(names)\nnames = sampler(model, start='a', n=10, k=8, only_new=True)\nprint(names)\nnames = sampler(model, start='a', n=10, k=15, only_new=True)\nprint(names)\nnames = sampler(model, start='jam', n=10, k=2, only_new=False)\nprint(names)","meta":"{'source': 'AI4Code', 'id': '2a1ca444119aee'}"}
{"id":"8914","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\npd.set_option('float_format', '{:.2f}'.format)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nimport sklearn.linear_model as model\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\nfrom sklearn.svm import SVR\nfrom sklearn.metrics import accuracy_score\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n**This notebook is a work in Progress !**\n\"\"\"\ndataset = pd.read_csv('..\/input\/BlackFriday.csv')\ndataset.head()\nprint(\"The Number of Rows:\",dataset.shape[0])\nprint(\"The Number of Columns:\",dataset.shape[1])\n\"\"\"\nSince the age data we have is a range, we try to give it a discrete value which would help us in prediction.\n\"\"\"\ndataset.Age.replace(('0-17','18-25','26-35','36-45','46-50','51-55','55+'),(0,1,2,3,4,5,6), inplace =True)\ndataset.head()\ndataset.describe(include='all')\nage0 = dataset[dataset['Age'] ==0]['Purchase'].values.sum()\nage1 = dataset[dataset['Age'] ==1]['Purchase'].values.sum()\nage2 = dataset[dataset['Age'] ==2]['Purchase'].values.sum()\nage3 = dataset[dataset['Age'] ==3]['Purchase'].values.sum()\nage4 = dataset[dataset['Age'] ==4]['Purchase'].values.sum()\nage5 = dataset[dataset['Age'] ==5]['Purchase'].values.sum()\nage6 = dataset[dataset['Age'] ==6]['Purchase'].values.sum()\n\n\nX = pd.DataFrame([age0,age1,age2,age3,age4,age5,age6])\nX.index=['0-17','18-25', '26-35','36-45','46-50','50-54','55+']\nX.plot(kind = 'bar',title=\"Total Sales based on the Age group\")\ndataset.Gender.replace(('M','F'),(0,1), inplace =True)\ndataset.head()\nMale = dataset[dataset['Gender'] ==0]['Purchase'].values.sum()\nFemale = dataset[dataset['Gender'] ==1]['Purchase'].values.sum()\n\nprint(\"Total Sales by Male: \", Male)\nprint(\"The Ratio of Male to Total: \", Male\/(Male+Female))\nprint(\"Total Sales by Female:\", Female)\nprint(\"The Ratio of Female to Total: \", Female\/(Male+Female))\nGenderPlot = pd.DataFrame([Male,Female])\nGenderPlot.index=['Male','Female']\nGenderPlot.plot(kind = 'bar',title=\"Total Sales based on the Gender\")\ncorr = dataset.corr(method='pearson')\nprint(\"Correlation of the Dataset:\",corr)\nf,ax = plt.subplots(figsize=(18, 18))\nprint(\"Plotting correlation:\")\nsns.heatmap(corr,annot= True, linewidths=.5)\nprint(\"Data Based on Occupation:\")\noccupationStat = dataset['Occupation'].value_counts(dropna = False)\noccupationStat.plot(kind='pie', figsize=(10,10))\nprint(\"Total Nan Values:\")\ntotalnan = dataset.isnull().sum(axis = 0)\nprint(totalnan)\ndataframe = dataset.drop(['User_ID'], axis=1)\n\nlabelEncoder_CityCat = LabelEncoder()\ndataframe.City_Category = labelEncoder_CityCat.fit_transform(dataframe.City_Category)\n\"\"\"\nSince we can't have categorical data for Regression but if we notice our Stay_In_Current_City_Years has 4+ Years for people staying more than 4 years. since 4+ is the only range we have, here we will replace that with four and consider 4 as everything thats more than 3.\n\"\"\"\ndataframe.Stay_In_Current_City_Years.replace(('4+'),(4), inplace =True)\n\"\"\"\nWe have some missing data in our columns, we can handle it in multiple ways. For now, we are just going to use only the datas that doesn't contain N\/A. In future versions of the notebook we will update this with other methods of handling missing data.\n\"\"\"\ndataframe.Product_Category_1 = dataframe.Product_Category_1.fillna(0)\ndataframe.Product_Category_2 = dataframe.Product_Category_2.fillna(0)\ndataframe.Product_Category_3 = dataframe.Product_Category_3.fillna(0)\ndataframe = dataframe[0:30000]\ndataframe.head()\nprint(\"No. of Rows:\", dataframe.shape[0])\n# features = dataframe.drop(['Product_ID'],axis=1)\n# X_train = features[:20000]\n# X_test = features[20000:]\n# y_train = features.Purchase[:20000]\n# y_test = features.Purchase[20000:]\n\n# # diabetes_X_train = diabetes_X[:-20]\n# # diabetes_X_test = diabetes_X[-20:]\n\n# # # Split the targets into training\/testing sets\n# # diabetes_y_train = diabetes.target[:-20]\n# # diabetes_y_test = diabetes.target[-20:]\n\n# # testtarget = features.Purchase[20000:]\n\ntestfeature = testfeature.drop(['Purchase'],axis=1)\n# testfeature = testfeature.drop(['Product_ID'],axis=1)\n# trainfeatures.drop(['Product_ID'],axis=1)\ntrainfeatures.head(10)\nfeatures_train, features_test, target_train, target_test = train_test_split(features, target, test_size=0.20, random_state=42)\nprint(trainfeatures.shape)\nprint(traintarget.shape)\nregr = model.LinearRegression()\nregr.fit(features_train,target_train)\nprediction = regr.predict(features_test)\n\nprint('Coefficients: \\n', regr.coef_)\nprint(\"Mean squared error: %.2f\"\n      % mean_squared_error(target_test, prediction))\nprint('Variance score: %.2f' % r2_score(target_test, prediction))\n\nsvr = SVR()\nsvr.fit(features_train,target_train)\nprediction_svr = svr.predict(features_test)\nscore = r2_score(target_test, prediction_svr)\nmae = mean_squared_error(prediction_svr, target_test)\nprint(\"Score:\", score)\nprint(\"Mean Absolute Error:\", mae)","meta":"{'source': 'AI4Code', 'id': '107a5b4d77fd11'}"}
{"id":"39770","text":"\"\"\"\n# Welcome to the Fashion-MNIST Challenge!\n\nWebsite reference: https:\/\/github.com\/zalandoresearch\/fashion-mnist\n\n**Author:** Gabriele Carbone\n\n**Date:** 05\/06\/2021\n\"\"\"\n##################################################\n# Imports\n##################################################\n\nimport numpy as np\nimport cv2\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom scipy.stats import entropy\n\n##################################################\n# Params\n##################################################\n\nDATA_BASE_FOLDER = '\/kaggle\/input\/image-classification-fashion-mnist'\n\n# Set seed\nnp.random.seed(0)\n\n# Adjust the font type of the plots with the one in the document\nplt.rcParams[\"font.family\"] = \"serif\"\n\"\"\"\n# Dataset\n\nThe dataset contains 50k train + 10k validation images of 10 different categories ('T-shirt\/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot').\n\nEach image is a 28x28 grayscale, and for simplicity here is flattened into a 784 dimensional vector.\n\"\"\"\n##################################################\n# Load dataset\n##################################################\n\nx_train = np.load(os.path.join(DATA_BASE_FOLDER, 'train.npy'))\nx_valid = np.load(os.path.join(DATA_BASE_FOLDER, 'validation.npy'))\nx_test = np.load(os.path.join(DATA_BASE_FOLDER, 'test.npy'))\ny_train = pd.read_csv(os.path.join(DATA_BASE_FOLDER, 'train.csv'))['class'].values\ny_valid = pd.read_csv(os.path.join(DATA_BASE_FOLDER, 'validation.csv'))['class'].values\ny_labels = ['T-shirt\/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\n# Plot random images of different classes\nplt.figure(figsize=(25, 5))\nfor idx in range(20):\n    plt.subplot(1, 20, idx + 1)\n    img = x_train[idx].reshape(28, 28)\n    plt.title(f'{y_labels[y_train[idx]]}')\n    plt.imshow(img, cmap='gray')\n    plt.axis('off')\nplt.show()\n\"\"\"\n# Processing Data\n\nWe transform the datasets into pandas DataFrame because it's easier to work with them\n\"\"\"\nx_train_df = pd.DataFrame(x_train)\nx_valid_df = pd.DataFrame(x_valid)\nx_test_df = pd.DataFrame(x_test)\n\"\"\"\n### Check for NA values\n\nThere are no observations with NA values\n\"\"\"\nprint(x_train_df.isna().sum().sum())\n\"\"\"\n### Print Shapes\n\nPrint the shapes of the **3 dataset** (x_train_df, x_valid_df, x_test) and **2 target vectors** (y_train, y_valid)\n\"\"\"\nprint(x_train_df.shape, \n      x_valid_df.shape, \n      x_test.shape, \n      y_train.shape, \n      y_valid.shape)\n\"\"\"\n### Classes' Frequency\nThe classes are very balanced, each of the classes has around the same portion of dataset (10%)\n\"\"\"\nunique, counts = np.unique(y_train, return_counts=True) # Count the unique values\n\ny_class_fr = pd.DataFrame(counts, index = y_labels)\ny_class_fr = y_class_fr.rename(columns={0: \"Count\"})   # Rename the columns\n\ndisplay(y_class_fr.transpose())                     # Display the count\n\ny_class_fr.plot.bar(legend = False)     # Create a barplot\n\"\"\"\n### Feature Selection - Entropy Method\n\nWe have a **huge number of features** in the dataset (over 700), so we need to give a priority to them\n\nWe use the metric *entropy* to understand what features might carry more information (alias, we look for the pixel that are more important in the classification process)\n\"\"\"\nentropy = pd.Series(entropy(x_train))              #compute entropy for each parameter\n\nentropy = entropy.reset_index()                    #reset the index\n\nentropy = entropy.sort_values(ascending = False, by = 0)    #sort the values from the biggest to the smallest\n\nentropy = entropy.rename(columns={0: \"Entropy\", \"index\": \"Index\"})   #rename the columns\n\"\"\"\n### Feature Scaling and Final Elaborations\n\nIn this notebook, we will fully test the K Nearest Neighbor model which is very sensible to the scale of the single features\n\nNow, *all the values in the dataset are between 0 and 255*, so  - in theory - we should obtain good results even without scaling, but for good practice we will use a **standard MinMaxScaler** anyway\n\"\"\"\n#Scale the features\nScaler = MinMaxScaler()\n\nx_train_scaled = Scaler.fit_transform(x_train_df)\nx_valid_scaled = Scaler.fit_transform(x_valid_df)\nx_test_scaled = Scaler.fit_transform(x_test_df)\n\"\"\"\n# kNN Model\n\nThe Fashion-MNIST Challenge is a **classification problem**, so using a kNN (aka k-Nearest Neighbors) can be a smart approach\n\nkNN is a **non-parametric model** (meaning that doesn't use weights or parameters learning) that, intuitively, given a certain input searches for the most similar k observation and assign a class to the input based on the most popular one among them\n\nFrom a mathematical point of view, the \"similarity\" is often computed using the l1-norm or the l2-norm (also called \"euclidean distance\")\n\nThe main advantage of kNN is the **almost non-existent time to train** (limited to the storing time) BUT **the prediction phase may take a while** because the algorithm needs to compare the input to all the observation in the dataset (for each input!)\n\n## How does it works?\n\nkNN takes as input the parameter values of the observation then computes the distances between the instance's value for a feature and the training set's value for the same feature, for each feature. Then the model process, depending on the norm used, these distances and output a number that represent the general \"distance\" of the the observation from that data point.\n\nThese results are ranked from the smallest (most similar observation of the training set) to the greatest (the least similar one).\n\nFinally, the first k observation (called **\"neighbors\"**) are taken and given the \"right\" to vote for the class of a given instance.\n\"\"\"\n\"\"\"\n![knn.PNG](attachment:18b3ba5a-7cfc-4bca-8eba-19eed2b9a33b.PNG)\n\n*Source: https:\/\/hal.archives-ouvertes.fr\/hal-01657491\/document*\n\nAs you can see from the image, with 1 and 3 neighbors we assign the new data point (the black one) to the blue class, while with 5 and 7 neighbors we assign the new data point to the grey class.\n\n**There is no optimal number of neighbors**, it depends on the specific context and dataset.\n\"\"\"\n\"\"\"\n![](https:\/\/robocrop.realpython.net\/?url=https%3A\/\/files.realpython.com\/media\/knn_01_MLgeneral_wide.74e5e2dc1094.png&w=1512&sig=492d6c64473418b06336cebadf7eb78bb7662e12)\n\n*Source: https:\/\/realpython.com\/knn-python\/*\n\nFrom a mathematical point of view, in 2D we can imagine the kNN as **a model to create \"dominance\" maps** (also called \"Voronoi Diagram Visualizations\") were, *if an instance fall inside one of these intervals, then it's assigned to the dominant class.*\n\nFrom the image above, you can see  a very simple case: for example, given that the majority of the data points in the top left side of the graph are stars then we will assign an hypotetichal new data point to \"star\" if it falls in that interval.\n\nkNN is very powerful because it can create **extremely complex boundaries with simple math.**\nFor example, in the image below you can see the complexity of a real case study and how it changes based on the number of neighbors: usually, *if we have fewer neighbors the boundaries are more complex because they are more sensible* (it takes just a single data point to change the class!)\n\"\"\"\n\"\"\"\n![knn - Copia.PNG](attachment:96789107-19c7-4f41-9f62-3382da19147c.PNG)\n\n*Source: https:\/\/hal.archives-ouvertes.fr\/hal-01657491\/document*\n\"\"\"\n# This is the final optimized model, we will use this from the start in order to speed up the computing time\n\nmodel = KNeighborsClassifier(n_neighbors = 4, \n                             weights = 'distance',\n                             algorithm = 'brute', \n                             p = 2)\n\"\"\"\n### Testing the HyperParameters\nFor both accuracy (as the primary KPI) and speed (the secondary KPI)\n\"\"\"\n# Compute the accuracy of the model\n\ndef accuracy(y_pred, y_true):\n    '''\n    input y_pred: ndarray of shape (N,)\n    input y_true: ndarray of shape (N,)\n    '''\n    return (1.0 * (y_pred == y_true)).mean()\n# Evaluate the model and append the accuracy and speed to the given lists\n# N is the number of observations\n# D is the number of parameters\n# V is the number of values tried\n\ndef execute_model_evaluation (model, x_train, y_train, x_valid, accuracy_list, speed_list):\n    '''\n    input model: sklearn kNN model\n    input x_train: pd.DataFrame of shape (N, D)\n    input y_train: ndarray of shape (N,)\n    input x_valid: pd.DataFrame of shape (N, D)\n    input accuracy_list: list of length (V)\n    input speed_list: list of legnth (V)\n    '''\n\n    # Start the time keeping\n    starting_time = time.process_time()                               \n    \n    # Fit the model with the training dataset\n    model.fit(x_train, y_train)                                       \n        \n    # Predict the new values with the model\n    y_pred = model.predict(x_valid)                                   \n\n    # End the time keeping\n    finishing_time = time.process_time()                              \n    \n    # Compute the time\n    iteration_speed = round(finishing_time - starting_time, 3)        \n    \n    # Append the time to the speed list\n    speed_list.append(iteration_speed)                                \n    \n    # Compute the accuracy\n    iteration_accuracy = round(accuracy(y_pred, y_valid) * 100, 2)    \n    \n    # Append the accuracy to the accuracy list\n    accuracy_list.append(iteration_accuracy)                          \n# Create a line plot of accuracy and speed\n# V is the number of values tried for the model\n\ndef accuracy_speed_plot(x_axis, accuracy_list, speed_list):\n    '''\n    input x_axis: ndarray of shape (V,)\n    input accuracy_list: list of length (V)\n    input speed_list: list of length (V)\n    '''\n    fig, (ax1, ax2) = plt.subplots(2,                           # Create two subplots\n                                   sharex = True,               # Remove the common inside x-axis\n                                   figsize=(12,8))              # Adjust the figure size\n\n    fig.suptitle('Accuracy in % (Top) and Speed in s (Down)', fontsize=24, fontfamily = \"serif\")   # Add the plot title\n\n    ax1.plot(x_axis, accuracy_list, linewidth = 2)   # Plot the accuracy list\n\n    ax2.plot(x_axis, speed_list, linewidth = 2)      # Plot the speed list\n    \n    ax1.tick_params(axis='y', labelsize=14)          # Adjust the y label font size\n    ax2.tick_params(axis='y', labelsize=14)          # Adjust the y label font size\n    ax2.tick_params(axis='x', labelsize=16)          # Adjust the x label font size\n# Create a bar plot of accuracy and speed\n# V is the number of values tried for the model\n\ndef accuracy_speed_barplot(x_axis, accuracy_list, speed_list):\n    '''\n    input x_axis: ndarray of shape (V,)\n    input accuracy_list: list of length (V)\n    input speed_list: list of length (V)\n    '''\n    fig, (ax1, ax2) = plt.subplots(2,                          # Create two subplots\n                                   sharex = True,              # Remove the common inside x-axis\n                                   figsize=(12,8))             # Adjust the figure size\n\n    fig.suptitle('Accuracy in % (Top) and Speed in s (Down)', fontsize=24, fontfamily = \"serif\")  # Add the plot title\n\n    ax1.bar(x_axis, accuracy_list)                             # Plot the accuracy list\n\n    ax2.bar(x_axis, speed_list)                                # Plot the speed list\n\n    ax1.tick_params(axis='y', labelsize=14)                    # Adjust the y label font size\n    ax2.tick_params(axis='y', labelsize=14)                    # Adjust the y label font size\n    ax2.tick_params(axis='x', labelsize=16)                    # Adjust the x label font size\n# Create a cool table with the accuracy and the speed for each try\n# V is the number of values tried for the model\n\ndef cool_table (values, values_name, accuracy_list, speed_list):\n    '''\n    input values: ndarray of shape (V,)\n    input values_name: string\n    input accuracy_list: list of length (V)\n    input speed_list: list of length (V)\n    output tbl: pd.DataFrame of shape(V, 3)\n    '''\n    \n    # Create a dataframe with the value tested, the accuracy and the speed\n    tbl = pd.DataFrame({'Accuracy': accuracy_list,\n                         'Time': speed_list},\n                      index= values)\n    \n    tbl.index.name = values_name                    # Rename the index\n    \n    return tbl\n\"\"\"\n### Tuning the Number of Features\nSelecting the most important features (alias the pixels) is the first step in our tuning process\n\nIn general, more features means more information and, as a consequence, more accuracy (at least in the training set...)\n\nBut, to use all features involves to major side effects:\n- **risk of overfitting the model**: as in all situations with a very high number of parameters\n- **a general decrease in speed**: expecially in a model as kNN the number of features is of the utmost importance, given that the time required increase linearly with the dataset used \n\"\"\"\n# Inizialize the two kpi lists\naccuracy_features, speed_features = [], []         \n\n#Select the desired number of features we want to test\nfeatures_numbers = np.array([1, 2, 4, 8, 16, 32, 64, 128, 256, 512, x_train_scaled.shape[1]])\n\nfor features_number in features_numbers:\n    \n    # Select the number of features\n    parameters_list = entropy.head(features_number).Index                 \n    \n    # Create a new training df with only that features\n    x_train_param = pd.DataFrame(x_train_scaled)[parameters_list]         \n    \n    # Create a new validation df with only that features\n    x_valid_param = pd.DataFrame(x_valid_scaled)[parameters_list]         \n    \n    execute_model_evaluation(model, \n                             x_train_param, y_train, \n                             x_valid_param, \n                             accuracy_features, speed_features)\n    \n\nfeatures_table = cool_table(features_numbers, '# of Features', \n                            accuracy_features, speed_features)\ndisplay('Time to run the cell: ' + str(round(sum(speed_features), 2)) + ' s')\ndisplay(features_table)\n\naccuracy_speed_plot (features_numbers, \n                     accuracy_features, speed_features)\n\"\"\"\nThe first thing we can notice is that **the accuracy increase (although not linearly) with every feature**, so we can say that - in general - all of the pixel are important. But, as we said before, we cannot use the full dataset.\n\nWe select for the final model the 512 features option, because we want a model with at least 80% accuracy, but it can't be too slow\n\nFurthermore, *we can see that the increase in accuracy is very small while the increase in the running time is linearly dependent on the size of the dataset*\n\nFor the sake of speed, during the rest of the tuning, we will use the 128 option\n\"\"\"\n# Select the 128 features with the highest entropy\nparameters_list = entropy.head(128).Index                  \n\n# Filter the features selected from the training set\nx_train = pd.DataFrame(x_train_scaled)[parameters_list]    \n\n# Filter the features selected from the validation set\nx_valid = pd.DataFrame(x_valid_scaled)[parameters_list]    \n\"\"\"\n### Tuning the number of neighbors\nThe number of neighbors computed is the \"k\" in the kNN model. *Having more neighbors means that the model will take in account more observation similar to the input.* So, if we set k = 5 the 5 most similar observations will have a right to \"vote\" and influencing the class assignment to the input, if we set k = 15 the 15 most similar observations have the right to \"vote\" and so on.\n\nExploring this hyperparameter is very important in order to **understand the optimal level of bias-variance trade-off.**\n\nUsually, if we set k too small we will have underfitting, while if we set k too large we will have overfitting.\n\nWe set the search space between 1 and 16 neighbors, and if that is not enough, we will expand the search\n\"\"\"\naccuracy_neighbors, speed_neighbors = [], []\n\nneighbors_fitted = [1, 2, 3, 4, 5, 6, 7, 10, 13, 16]\n\nfor neighbors_trial in neighbors_fitted:\n    \n    model = KNeighborsClassifier(n_neighbors = neighbors_trial,\n                                 weights = 'distance', \n                                 algorithm = 'brute', \n                                 p = 2)\n    \n    execute_model_evaluation(model, \n                             x_train, y_train, \n                             x_valid, \n                             accuracy_neighbors, speed_neighbors)\n\n    \nneighbors_table = cool_table(neighbors_fitted, '# of Neighbors', \n                             accuracy_neighbors, speed_neighbors)\n\ndisplay('Time to run the cell: ' + str(round(sum(speed_neighbors), 2)) + ' s')\ndisplay(neighbors_table)\n\naccuracy_speed_plot (neighbors_fitted, \n                     accuracy_neighbors, speed_neighbors)\n\"\"\"\nWe note that **the accuracy goes up until 3 neighbors then starts to drop.** This means that if we go over 4 neighbor we start overfitting the model.\n\nAlso, note that the speed is affected only up to the fourth neighbor, after that is constant\n\nConsidered that, we will use 3 neighbors in the next models\n\"\"\"\n\"\"\"\n### Tuning the type of weight\nkNN is a non-parametric model, so to see the word \"weight\" must be somewhat confusing\n\nThere are two types of weights in kNN:\n- *'uniform'*: this means, substantially, that there are no weights and all the distances in the features are considered with the same importance\n- *'distance'*: this means that the features will be assigned a weight based on their distance from the input. So, the more distant a feature values is the smaller the weight assigned will be the mless important the feature will be\n\nWith the 'distance' option, a feature that have values usually far from the input will have less importance \n\n**Feature scaling is extremely important for this hyperparameter!**\n\"\"\"\naccuracy_weights, speed_weights = [], []\n\nweights_fitted = ['uniform', 'distance']\n\nfor weight_trial in weights_fitted:\n    \n    model = KNeighborsClassifier(n_neighbors = 3, \n                                 weights = weight_trial,\n                                 algorithm = 'brute', \n                                 p = 2)\n    \n    execute_model_evaluation(model, \n                             x_train, y_train, \n                             x_valid, \n                             accuracy_weights, speed_weights)\n    \n\nweight_table = cool_table(weights_fitted, 'Types of Weight', \n                          accuracy_weights, speed_weights)\n\ndisplay('Time to run the cell: ' + str(round(sum(speed_weights), 2)) + ' s')\ndisplay(weight_table)\n\naccuracy_speed_barplot(weights_fitted, \n                       accuracy_weights, speed_weights)\n\"\"\"\nIn our case, **this hyperparameter doesn't seem to have a strong impact**\n\nThe accuracy is more or less the same, while *the speed is slightly increased with the 'distance' option.*\n\nConsidered that, we will use the 'distance' option in the next models\n\"\"\"\n\"\"\"\n### Tuning the type of algorithm\nThe type of algorithm is, essentially, **the \"engine\" that the model use** to process the input.\n\nThere are four option for this hyperparameter:\n- *'auto'*: the function will automatically pick the best of the other three options based on the input\n- *'ball_tree'*: will use the ball_tree algorithm. It's an algorithm that uses a binary tree to partition the data. Usually, performs well when the number of dimensions is high but, initially, require a lot of time to create the binary tree. It uses the 'triangle inequality' to create bounds and speed up the process. Complexity: O[DNlog(N)]\n- *'kd_tree'*: will use the kd_tree algorithm. Like the ball_tree, uses binary trees to recursively partition the data into smaller groups. The construction of a kd_tree is very fast because it's done by using only along the data axes. But, kd_tree becomes very slow for higher dimensionality spaces because it suffer from the 'curse of dimensionality'. Complexity: O[DNlog(N)], for larger samples O[DN]\n- *'brute'*: will use a brute force approach. Complexity: O[DN]\n\nThe main difference between the kd_tree and the ball_tree is that *kd_tree partition data along the axes, while the ball_tree partition data in a series of hyper-spheres* (in 2d they would be circles, in 3d they would be sphere, and so on)\n\"\"\"\naccuracy_algorithm, speed_algorithm = [], []\n\nalgorithms_fitted = ['auto', 'ball_tree', 'kd_tree', 'brute']\n\nfor algorithm_trial in algorithms_fitted:\n    \n    model = KNeighborsClassifier(n_neighbors = 3, \n                                 weights = 'distance', \n                                 algorithm = algorithm_trial,\n                                 p = 2,\n                                 leaf_size = 2)\n    \n    execute_model_evaluation(model, \n                             x_train, y_train, \n                             x_valid, \n                             accuracy_algorithm, speed_algorithm)\n    \nalgorithm_table = cool_table(algorithms_fitted, 'Types of Algorithms', \n                             accuracy_algorithm, speed_algorithm)\n\ndisplay('Time to run the cell: ' + str(round(sum(speed_algorithm), 2)) + ' s')\ndisplay(algorithm_table)\n    \naccuracy_speed_barplot(algorithms_fitted, \n                       accuracy_algorithm, speed_algorithm)\n\"\"\"\nWe can see that the 'auto' option probably selected the 'kd_tree' option for this dataset, thus the similar results.\n\nThe ball_tree algorithm is almost twice as fast as the kd_tree, while the brute force algorithm is almost 6 times faster than the kd_tree (and 3x faster than the ball_tree). **The brute force algorithm is faster due to the fact that doesn't need to build a binary tree like the other two.**\n\nGiven the obvious disparity in performances, we will use the brute force in the final model\n\"\"\"\n\"\"\"\n### Tuning the leaf size\n\nThe leaf size hyperparameter influences the use of the binary trees with theBallTree algorithm or the KDTree algorithm options active\n\nWith the brute force method applied, this shouldn't affect the performances whatsoever\n\"\"\"\naccuracy_leaf_size, speed_leaf_size = [], []\n\nleaf_size_fitted = [1, 2, 4, 8, 16, 32, 64]\n\nfor leaf_size_trial in leaf_size_fitted:\n    \n    model = KNeighborsClassifier(n_neighbors = 3, \n                                 weights = 'distance',\n                                 algorithm = 'brute',\n                                 leaf_size = leaf_size_trial,\n                                 p = 2)\n    \n    execute_model_evaluation(model, \n                             x_train, y_train, \n                             x_valid, \n                             accuracy_leaf_size, speed_leaf_size)\n    \nleaf_table = cool_table(leaf_size_fitted, 'Leaf Size', \n                        accuracy_leaf_size, speed_leaf_size)\n\ndisplay('Time to run the cell: ' + str(round(sum(speed_leaf_size), 2)) + ' s')\ndisplay(leaf_table)\n    \naccuracy_speed_plot(leaf_size_fitted, \n                    accuracy_leaf_size, speed_leaf_size)\n\"\"\"\nWe can see that **the accuracy is exactly the same for all the trials,** while the speed change less than 3% between the smallest and the largest trial.\n\nThis proves the indifference that the brute force method has regarding the leaf size (simply because doesn't use trees at all)\n\nIn the final model we will drop entirely this hyperparameter because it's not important to us and we want to improve readibility\n\"\"\"\n\"\"\"\n### Tuning the p parameter\nThe p-parameter indicates the way in which the kNN should compute the distances between observations and input\n\nWe will test the two main methods for computing inputs:\n- *p = 1*: also called l1-norm or manatthan distance. Compute the distance, in absolute values, between the input value and the observations.\n- *p = 2*: also called l2-norm or euclidean distance. Compute the distance by taking the root of the sum of all the squared distances between the input value and the observations\n\"\"\"\naccuracy_p, speed_p = [], []\n\np_fitted = [1, 2]\n\nfor p_trial in p_fitted:\n    \n    model = KNeighborsClassifier(n_neighbors = 3, \n                                 weights = 'distance', \n                                 algorithm = 'brute', \n                                 p = p_trial)\n    \n    execute_model_evaluation(model, \n                             x_train, y_train, \n                             x_valid, \n                             accuracy_p, speed_p)\n    \np_table = cool_table(p_fitted, 'Types of Norm', \n                     accuracy_p, speed_p)\n\ndisplay('Time to run the cell: ' + str(round(sum(speed_p), 2)) + ' s')\ndisplay(p_table)\n    \naccuracy_speed_barplot(p_fitted, \n                       accuracy_p, speed_p)\n\"\"\"\nWe can see that **the model, using the l2-norm, is almost 6x faster than using the l1-norm**\n\nThis is probably due to the fact that computing absolute values is more computationally expensive compared to squaring and rooting numbers if the problem can't be solved using an LP reformulation that lead to linear equations \n\nWhile the accuracy is sligthly higher with the l1-norm, we will use the l2-norm in the final model\n\"\"\"\n\"\"\"\n# Evaluation\n\"\"\"\n### We report the final model with all the best features\n\n# We select the 512 parameters with the highest entropy\nparameters_list = entropy.head(512).Index                            \n\nx_train_final = pd.DataFrame(x_train_scaled)[parameters_list]\n\nx_valid_final = pd.DataFrame(x_valid_scaled)[parameters_list]\n\nmodel = KNeighborsClassifier(n_neighbors = 3, \n                             weights = 'distance',\n                             algorithm = 'brute', \n                             p = 2)\n\nstarting_time = time.process_time()                    # Start the time keeping\n\nmodel.fit(x_train_final, y_train)                      # Fit the model with the training dataset\n\ny_pred = model.predict(x_valid_final)                  # Predict the new values with the model\n\nfinishing_time = time.process_time()                   # End the time keeping\n\niteration_speed = finishing_time - starting_time       # Compute the time\n\niteration_accuracy = accuracy(y_pred, y_valid) * 100   # Compute the accuracy\n\nprint ('The model has an accuracy of ' + \n       str(round(iteration_accuracy, 2)) + \n       '% and a computing speed of ' + \n       str(round(iteration_speed, 2)) + \n       ' seconds')\n\nprint('The model is capable of predicting one instance in ' + \n      str(round(iteration_speed\/y_pred.shape[0], 4)) + \n      ' seconds')\n\"\"\"\n# Author's Notes\n\nI've tried to optimize not only the model per se, but also the notebook in general:\n- Each new piece of code is commented the first time that it's used\n- The lines have an addition space between them\n    - But, if the lines are somehow connected, then you'll find them together\n- Each function's argument is broke into single lines\n    - But, if the arguments are few or simple I've left them on a single line\n- Through the notebook, I've used similar variable names, only changing the minimum possible to ease the connection between each section of the hyperparameters tuning\n- I've used the easiest plots to read (lineplots or barplots) , this is because I've favoured readibility over complexity. I feel like the informations that I wanted to share were delivered pretty well even with simple plots and I didn't want to add complexity where it wasn't necessary\n- I've added little sections of theoretical stuff to help you understand the notebook even with minimal background\n- I've tried to explain, for each hyperparameter, how it impacts the results and why\n\nThat's all. Let me know if you appreciated it!\n\"\"\"\n\"\"\"\n# Sending the submission for the challenge\n\"\"\"\n##################################################\n# Save your test prediction in y_test_pred\n##################################################\n\nx_test_final = pd.DataFrame(x_test_scaled)[parameters_list]\n\ny_test_pred = model.predict(x_test_final)\n\n# Create submission\nsubmission = pd.read_csv(os.path.join(DATA_BASE_FOLDER, 'sample_submission.csv'))\nif y_test_pred is not None:\n    submission['class'] = y_test_pred\nsubmission.to_csv('my_submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '493bf628204888'}"}
{"id":"129312","text":"\"\"\"\n# K49 MNIST\nThe K49 MNIST is a MNIST like dataset. It is formed by 49 different classes, 49 different hiraganas. Hiraganas are a Japanese alphabet, the first one that every Japanese person learns at school ([Hiragana](https:\/\/en.wikipedia.org\/wiki\/Hiragana)).\n\nIn this notebook, I will try to create a small CNN to classify these hiraganas.\n\"\"\"\n# Imports\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Machine learning\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Conv2D, Dense, Dropout, Flatten, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.metrics import categorical_accuracy\nfrom keras.losses import categorical_crossentropy\nfrom keras.models import Sequential\n\"\"\"\n## Settings\n\nHere, in the next few cells, I will just define some settings:\n* Paths to read the input data\n* n_classes : the number of classes of our output\n* learning_rate : our optimizer starting learning rate\n* image_shape : the shape of the images that I will feed into the CNN\n* n_epochs : the number of training epochs\n\"\"\"\n# Paths\ninput_path = os.path.join('..', 'input')\nclassmap_path = os.path.join(input_path, 'k49_classmap.csv')\n\nk49_train_imgs_path = os.path.join(input_path, 'k49-train-imgs.npz')\nk49_train_labels_path = os.path.join(input_path, 'k49-train-labels.npz')\nk49_test_imgs_path = os.path.join(input_path, 'k49-test-imgs.npz')\nk49_test_labels_path = os.path.join(input_path, 'k49-test-labels.npz')\n\n# Learning\nn_classes = 49\nlearning_rate = 0.001\nimage_shape = (28, 28, 1)\nn_epochs = 25\n\"\"\"\n### Classmap loading\n\nThe classmap gives us a link between the class indexes and the actual Japanese character.\n\"\"\"\n# Classmap loading : pandas dataframe that links an index to an hiragana\n# Here 0 is a 'a', 1 a 'i', 2 a 'u', ...\nk49_classmap = pd.read_csv(classmap_path)\nk49_classmap.head()\n\"\"\"\n## Data loading\n\nI just use the numpy load function to get the data inside the .npz files. The ['arr_0'] statement outputs the actual array stored inside the file.\n\"\"\"\n# Data loading\ntrain_imgs = np.load(k49_train_imgs_path)['arr_0']\ntrain_labels = np.load(k49_train_labels_path)['arr_0']\ntest_imgs = np.load(k49_test_imgs_path)['arr_0']\ntest_labels = np.load(k49_test_labels_path)['arr_0']\n# Data visualization : let's plot some hiraganas\nn = 7\nfig, axs = plt.subplots(nrows=n, ncols=n, sharex=True, sharey=True, figsize=(8, 8))\nfor i in range(n**2):\n    ax = axs[i \/\/ n, i % n]\n    ax.imshow(train_imgs[i], cmap='Greys')\n    ax.axis('off')\nplt.tight_layout()\nplt.show()\n# Let's plot the data repartition between all our classes\ntrain_labels_s = pd.Series(train_labels)\ntrain_labels_s.value_counts(sort=False).plot.bar()\n# here I still need to find a way to enlarge this plot !\n\"\"\"\nThe majority of all classes have around 6000 samples. That is good for the training phase. However, some classes have less than 1000 samples, which may cause a lack of accuracy in their prediction. For the first model, I will keep this repartition.\n\"\"\"\n\"\"\"\n## Data processing\n\nThe next four cells transform the data into a valid deep learning format. First, I use the expand_dims numpy function to get a 3D tensor representation of the data (height, width, channel).\nThen I create a training set and a validation set. And finally I one-hot encode the output so the CNN model can understand it.\n\"\"\"\n# Using expand_dims to get a nominal deep learning format for all images\n# (28, 28) --> (28, 28, 1)\ntrain_imgs = np.expand_dims(train_imgs, axis=-1)\ntest_imgs = np.expand_dims(test_imgs, axis=-1)\n# creation of a training set and a validation one\nx_train, x_val, y_train, y_val = train_test_split(train_imgs, train_labels, test_size=0.10)\n# One hot encoding util function\ndef one_hot_encoding(y):\n    y_res = np.zeros((len(y), n_classes))\n    for i in range(len(y)):\n        y_res[i][y[i]] = 1\n    return y_res\n# Get the labels in a one hot encoded version\ny_train = one_hot_encoding(y_train)\ny_val = one_hot_encoding(y_val)\n\"\"\"\n## CNN model definition\n\nThe model is composed of three blocks of two convolution layers. Each block uses BatchNormalization to facilitate the training phase. Then, the last block of the model is composed of three fully connected layers, the last one giving us a probability for each class, thanks to the softmax activation.\n\"\"\"\n# Model definition - simple CNN model\ndef define_cnn_model(input_shape, output_nodes):\n    model = Sequential()\n\n    model.add(Conv2D(32, (5, 5), strides=(1, 1), activation='relu', input_shape=input_shape))\n    model.add(Conv2D(32, (5, 5), strides=(2, 2), activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.3))\n\n    model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu'))\n    model.add(Conv2D(64, (3, 3), strides=(1, 1), activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.3))\n\n    model.add(Conv2D(96, (3, 3), strides=(1, 1), activation='relu'))\n    model.add(Conv2D(96, (3, 3), strides=(1, 1), activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.3))\n\n    model.add(Flatten())\n    model.add(Dense(512, activation='relu'))\n    model.add(Dense(256, activation='relu'))\n    model.add(Dense(output_nodes, activation='softmax'))\n    \n    return model\n\nmodel = define_cnn_model(image_shape, n_classes)\nmodel.compile(optimizer=Adam(learning_rate), loss=categorical_crossentropy, metrics=[categorical_accuracy])\n# Let's look at our model\nmodel.summary()\ntraining_recap = model.fit(x_train, y_train, epochs=n_epochs, validation_data=(x_val, y_val), batch_size=128)\nhistory = training_recap.history\ne = [i for i in range(1, n_epochs+1)]\nloss = history['loss']\nval_loss = history['val_loss']\n\nplt.plot(e, loss, val_loss)\nplt.title('Training and validation losses')\nplt.show()\n\"\"\"\nThanks to this graph, I think I'm not overfitting. That's a good thing. Moreover, it won't be useful to add more epochs.\n\"\"\"\n# Prediction on test set\nprint(\"Categorical accuracy : {:.3f}\".format(model.evaluate(test_imgs, one_hot_encoding(test_labels))[1]))\ny_pred = model.predict(test_imgs)\ny_pred = np.argmax(y_pred,axis=1)\n# Let's visualize some predictions\nn = 5\nfig, axs = plt.subplots(nrows=n, ncols=n, sharex=True, sharey=True, figsize=(15, 15))\nfor i in range(n**2):\n    ax = axs[i \/\/ n, i % n]\n    ax.imshow(test_imgs[i, :, :, 0], cmap='Greys')\n    ax.set_title('Class: {}, Predicted: {}'.format(test_labels[i], y_pred[i]))\nplt.show()\n\"\"\"\nNow, to get some insights on how my model works on the whole test set, I will use the classification report from sklearn.\n\"\"\"\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(test_labels, y_pred, target_names=k49_classmap['char']))\n\"\"\"\nThis gives us 95% accuracy, on a 49-class problem with less than 15 minutes spend in training. It's not too bad. But this score can be improved I think by finding a solution to the unbalanced class repartition of this dataset. By looking at the classification report, I remarked that the classes with the lower accuracy are the ones with the less samples.\n\"\"\"\n\"\"\"\n## Custom loss function\n\nHere, I will use the Keras backend to create a custom loss function in order to tackle the unbalanced data that we have. To do that, I will keep the categorical crossentropy structure, to which I will add some weights to penalize more errors in the low sample classes.\n\"\"\"\n# Definition of the penalization weights\ntrain_labels_s = pd.Series(train_labels)\nn_sample_per_class = train_labels_s.value_counts(sort=False)\nmax_sample_per_class = n_sample_per_class.max()\nweights = np.array([max_sample_per_class \/ w for w in n_sample_per_class])\nweights = weights \/ weights.max()\n# print(weights)\n# custom loss function\n\"\"\"\nA weighted version of categorical_crossentropy for keras (2.0.6). This lets you apply a weight to unbalanced classes.\n@url: https:\/\/gist.github.com\/wassname\/ce364fddfc8a025bfab4348cf5de852d\n@author: wassname\n\"\"\"\nfrom keras import backend as K\ndef weighted_categorical_crossentropy(weights):\n    \"\"\"\n    A weighted version of keras.objectives.categorical_crossentropy\n    \n    Variables:\n        weights: numpy array of shape (C,) where C is the number of classes\n    \n    Usage:\n        weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.\n        loss = weighted_categorical_crossentropy(weights)\n        model.compile(loss=loss,optimizer='adam')\n    \"\"\"\n    \n    weights = K.variable(weights)\n        \n    def loss(y_true, y_pred):\n        # scale predictions so that the class probas of each sample sum to 1\n        y_pred \/= K.sum(y_pred, axis=-1, keepdims=True)\n        # clip to prevent NaN's and Inf's\n        y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())\n        # calc\n        loss = y_true * K.log(y_pred) * weights\n        loss = -K.sum(loss, -1)\n        return loss\n    \n    return loss\n\ncustom_categorical_crossentropy = weighted_categorical_crossentropy(weights)\n# Redefinintion of our model\nmodel_custom_loss = define_cnn_model(image_shape, n_classes)\nmodel_custom_loss.compile(optimizer=Adam(learning_rate), loss=custom_categorical_crossentropy, metrics=[categorical_accuracy])\ntraining_recap_c = model_custom_loss.fit(x_train, y_train, epochs=n_epochs, validation_data=(x_val, y_val), batch_size=128)\n# Prediction on test set\nprint(\"Categorical accuracy : {:.3f}\".format(model_custom_loss.evaluate(test_imgs, one_hot_encoding(test_labels))[1]))\ny_pred = model_custom_loss.predict(test_imgs)\ny_pred = np.argmax(y_pred,axis=1)\nprint(classification_report(test_labels, y_pred, target_names=k49_classmap['char']))\n\"\"\"\nDo not hesitate to post any questions in the comments. And feel free to upvote if you liked this kernel :)\n\nStill to do :\n- find a solution to class imbalance (with a custom loss function)\n- a better layout for this kernel\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'eddd975319ae40'}"}
{"id":"95377","text":"\"\"\"\n## Hello, my name is George Lolaev and I will be satisfied, if you check my notebook\nI was trying to make it beginner friendly, cause I am also beginner in DataScience.\n\nIf there is anything to make better in my code, please tell me about it\n\"\"\"\n# 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\n# for cross-validation\nfrom sklearn.model_selection import cross_val_score\n\n# for preprocessing categorical features\nfrom sklearn.preprocessing import OneHotEncoder\n# for preprocessing numerical features\nfrom sklearn.impute import SimpleImputer\n\n# the model I'm gonna use\nfrom xgboost import XGBRegressor\n\n# package with statistical functions, it will be helpfull in searching outliers in our train dataset\nfrom scipy import stats\n# very useful function for fast checking differently made train-datasets\n# I recommend you to save it\n# Here it is not as helpful as it be in other cases, but anyway it makes my work faster\ndef score_dataset(X, y, model = XGBRegressor(random_state=0)):\n    score = cross_val_score(model, X, y, scoring = 'neg_mean_squared_error')\n    score = -1* score.mean()\n    score = np.sqrt(score)\n    return score\n\n# also very cool function, use it drop outliers in numerical features\n# the idea here is linked with statistal termin z-score\ndef drop_outliers(col, zscore= 3):\n    return col[np.abs(stats.zscore(col))<zscore]\n# reading our csv's\ntrain = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/train.csv', index_col='Id')\ntest = pd.read_csv('\/kaggle\/input\/house-prices-advanced-regression-techniques\/test.csv', index_col='Id')\n\n# that cols are almost empty, so they are useless\ncols_to_drop = [ 'Alley', 'PoolQC', 'Fence', 'MiscFeature']\ntrain = train.drop(cols_to_drop, axis=1)\n\n# split into features dataframe and target column\nX = train.drop(['SalePrice'], axis=1)\ny = train.SalePrice\n\n# the code will be much clearer if we defince categorical and numerical columns explicitly \ncat_cols = X.select_dtypes(include='object').columns\nnum_cols = X.select_dtypes(exclude='object').columns\n# cat-features\ncat_X = X[cat_cols]\n# num-features\nnum_X = X[num_cols]\n\n# create onehotencoder transformer to process cat-features\n# pay attention to attribute named 'handle_unknown'. It's important if we don't want to get errors with working with test dataset\nonehot_encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')\ncat_X_prep = onehot_encoder.fit_transform(cat_X)\n\n# filling nans with mean values for every column\nfor col in num_X:\n    num_X[col].fillna(num_X[col].mean(), inplace=True)\n\n# assign refined features to old columns\nfor col in num_X:\n    num_X.loc[:,col] = drop_outliers(num_X[col])\n# outliers now are nans\n# and we just use dropna method\nnum_X = num_X.dropna(axis=0)\n\n# concatenate categoricals and numericals\nX_prep = np.concatenate((num_X, cat_X_prep[num_X.index]), axis=1)\n\n# our dataset have become smaller and we must adapt target-vector to it\ny_prep = y[num_X.index]\n# just for tracking changes\n# In previous generations of that code the score was around 40'000\n# now it's much smaller :)\nscore_dataset(X_prep,y_prep, XGBRegressor(random_state=0,learning_rate=0.1,n_jobs=-1\n                                             ))\n\"\"\"\n## Let's now work with the test data\n\"\"\"\n\"\"\"\nPrerprocess acordingly the test dataset, but don't drop outliers\n\"\"\"\nX_test = test.drop(columns=cols_to_drop, axis=1)\n\ncat_X_test= X_test[cat_cols]\nnum_X_test = X_test[num_cols]\n\n# be careful! with test-dataset you should use only 'trasform' method, without fitting\ncat_X_test_prep = onehot_encoder.transform(cat_X_test)\n\n\n\nfor col in num_X_test:\n    num_X_test[col].fillna(num_X_test[col].mean(), inplace=True)\n\n\n\nX_test_prep = np.concatenate((num_X_test, cat_X_test_prep), axis=1)\n# learning_rate defines the speed of learning of our model\n# n_jobs is the number of cores of your processor that are used. value '-1' means using all cores\nmy_model = XGBRegressor(learning_rate=0.1, n_jobs=-1)\nmy_model.fit(X_prep,y_prep)\n\n# making prediction\ny_predicted = my_model.predict(X_test_prep)\n# I concatenate the id's of test dataset and predicted values into single dataframe\nresult = pd.DataFrame({'Id':test.index, 'SalePrice':y_predicted})\n# and then just convert it to csv file\nresult.to_csv('.\/result.csv', index=False)\n\"\"\"\n**Thanks for watching :)\nNow let's do that by yourself !**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'af1f5d518e780e'}"}
{"id":"86214","text":"# 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# 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\n\"\"\"\n# Load\n\"\"\"\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize']=[20,8]\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\n\n##\ndf=pd.read_csv('..\/input\/student-study-hour-v2\/Student Study Hour V2.csv')\ndisplay(df.shape)\ndisplay(df.corr())\ndisplay(df.describe())\n\n##\n# Let consider 50% of Score as pass mark\npass_mark=df.Scores.quantile(0.5)\ndf['Pass']=(df.Scores>pass_mark).astype(int)\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\nsns.scatterplot(data=df,x='Hours',y='Pass',hue=\"Pass\",style=\"Pass\",size=\"Pass\",sizes=(200, 200))\ny=df['Pass']\nX=df['Hours']\n\"\"\"\n# Changing slope and  y-intercept in Each Try (Hours Vs Pass)\n\"\"\"\n\"\"\"\n# Gradient descent Try-1\n\ndelta_m=1\n\ndelta_b=1\n\nm=m+delta_m\n\nb=b+delta_b\n\n\"\"\"\ndef gradient_descent(all_X,all_y,m,b):\n    total_error=0;y_pred=list()\n    for x,y in zip(all_X,all_y):\n        y_predict=m*x+b\n        y_pred.append(y_predict)\n        error=y_predict-y\n        total_error+=error\n        delta_m=1\n        delta_b=1\n        m=m+delta_m\n        b=b+delta_b\n    return m,b,y_pred,total_error\n# m=0;b=0\n# m,b,y_pred,total_error=gradient_descent(X,y,m,b)\n# print('m:',m,'b:',b,'total_error:',total_error)\n# plt.title('Student Studies',fontsize=24)\n# plt.xlabel('Hours',fontsize=24)\n# plt.ylabel('Pass',fontsize=24)\n# sns.scatterplot(x=X,y=y_pred)\n# plt.plot(X,y_pred)\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\n\nm=0;b=0\niteration=20\nfor i in range(iteration):\n    m,b,y_pred,total_error=gradient_descent(X,y,m,b)\n    print('m:',m,'b:',b,'total_error:',total_error)\n    sns.scatterplot(x=X,y=y_pred)\n    plt.plot(X,y_pred)\n\"\"\"\n# Result 1\n\nfrom above diagram we get that slope and  y-intercept  **Increases Largely**\n\nPoint 1 : Delta become constant\n\nPoint 2:  On each Step Slope and y-intecept increases by 1 \n\nfor\n\ndelta_m=1  # constant\n\ndelta_b=1\n\nm=m+delta_m\n\nb=b+delta_b\n\"\"\"\n\"\"\"\n# Gradient descent Try-2\n\ndelta_m=error*x\n\ndelta_b=error\n\nm=m+delta_m\n\nb=b+delta_b\n\"\"\"\ndef gradient_descent(all_X,all_y,m,b):\n    total_error=0;y_pred=list()\n    for x,y in zip(all_X,all_y):\n        y_predict=m*x+b\n        y_pred.append(y_predict)\n        error=y_predict-y\n        total_error+=error\n        delta_m=error*x\n        delta_b=error\n        m=m+delta_m\n        b=b+delta_b\n    return m,b,y_pred,total_error\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\n\nm=0;b=0\niteration=20\nfor i in range(iteration):\n    m,b,y_pred,total_error=gradient_descent(X,y,m,b)\n    print('m:',m,'b:',b,'total_error:',total_error)\n    sns.scatterplot(x=X,y=y_pred)\n    plt.plot(X,y_pred)\n\"\"\"\n# Result 2\n\nfrom above diagram we get that slope and  y-intercept  **Negative**\n\nPoint 1 : Delta varies dynamic to error and x value\n\nPoint 2:  On each Step Slope and y-intecept increases by delta value\n\nfor\n\ndelta_m=error*x  # result dynamic to x and error\n\ndelta_b=error\n\nm=m+delta_m\n\nb=b+delta_b\n\"\"\"\n\"\"\"\n# Gradient descent Try-2.1\n\ndelta_m=error*x\n\ndelta_b=error\n\nm=m + delta_m * 0.001\n        \nb=b + delta_b * 0.001\n\"\"\"\ndef gradient_descent(all_X,all_y,m,b):\n    total_error=0;y_pred=list()\n    for x,y in zip(all_X,all_y):\n        y_predict=m*x+b\n        y_pred.append(y_predict)\n        error=y_predict-y\n        total_error+=error\n        delta_m=error*x\n        delta_b=error\n        m=m + delta_m * 0.001\n        b=b + delta_b * 0.001\n    return m,b,y_pred,total_error\n\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\n\nm=0;b=0\niteration=20\nfor i in range(iteration):\n    m,b,y_pred,total_error=gradient_descent(X,y,m,b)\n    print('m:',m,'b:',b,'total_error:',total_error)\n    sns.scatterplot(x=X,y=y_pred)\n    plt.plot(X,y_pred)\n\"\"\"\n# Result 2.1\n\nfrom above diagram we get that slope and  y-intercept  **Negative**\n\nPoint 1 : Delta varies dynamic to error and x value\n\nPoint 2:  On each Step Slope and y-intecept are increases small by delta value\n\nfor\n\ndelta_m=error*x  \n\ndelta_b=error\n\nm=m + delta_m * 0.001\n        \nb=b + delta_b * 0.001\n\"\"\"\n\"\"\"\n# Gradient descent - Correct\n\ndelta_m=error*x\n\ndelta_b=error\n\nm=m - delta_m * 0.001\n        \nb=b - delta_b * 0.001\n\"\"\"\ndef gradient_descent(all_X,all_y,m,b):\n    total_error=0;y_pred=list()\n    for x,y in zip(all_X,all_y):\n        y_predict=m*x+b\n        y_pred.append(y_predict)\n        error=y_predict-y\n        total_error+=error\n        delta_m=error*x\n        delta_b=error\n        m=m - delta_m * 0.001\n        b=b - delta_b * 0.001\n    return m,b,y_pred,total_error\n\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\n\nm=0;b=0\niteration=20\nfor i in range(iteration):\n    m,b,y_pred,total_error=gradient_descent(X,y,m,b)\n    print('m:',m,'b:',b,'total_error:',total_error)\n    sns.scatterplot(x=X,y=y_pred)\n    plt.plot(X,y_pred)\n\"\"\"\n# Conclusion\n\nfrom above diagram we get that slope and  y-intercept  \n\nPoint 1 : Delta varies dynamic to error and x value\n\nPoint 2:  On each Step Slope and y-intecept are decrases by small delta value\n\nfor\ndelta_m=error*x\n\ndelta_b=error\n\nm=m - delta_m * 0.001\n        \nb=b - delta_b * 0.001\n\"\"\"\n\"\"\"\n# Gradient Descent\n\"\"\"\ndef gradient_descent(x,y,iteration=30):\n    m_current=b_current=0  #intialize m and b \n    learning_rate =0.0004 # step's \n    n=len(x)\n    for i in range(iteration):\n        y_predict = (m_current*x)+b_current #y=mx+b\n        cost = (1\/n) * sum( [val**2  for val in ( y-y_predict )]) #https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.metrics.mean_squared_error.html\n        m_next = -(2\/n)*sum(x*(y-y_predict)) #(\u2202\/\u2202m) refer above pic\n        b_next = -(2\/n)*sum(y-y_predict) #(\u2202\/\u2202b)\n        m_current = m_current - (learning_rate *m_next)\n        b_current = b_current - (learning_rate *b_next)\n        print(\"m  {}  ,b  {}  ,cost  {}  ,iteration  {} \".format(m_current,b_current,cost,i))\n        sns.scatterplot(x=x,y=y_pred)\n        plt.plot(x,y_pred)\n\nplt.title('Student Studies',fontsize=24)\nplt.xlabel('Hours',fontsize=24)\nplt.ylabel('Pass',fontsize=24)\ngradient_descent(X,y)\n\"\"\"\n# 2. II K Means Clustering\n\n1.Convergence\n\nWe should take care of Outlier and Intialization of centroid (which randomly selected) may centroid is introduced to be a \"far away\" point  in K mean \n\ninit='k-means++' > smart way to Intialization of centroid\n\ninit{\u2018k-means++\u2019, \u2018random\u2019}, callable or array-like of shape (n_clusters, n_features), default=\u2019k-means++\u2019\n\nK-means++ is the algorithm which is used to overcome the drawback posed by the k-means algorithm.\n(likelihood of picking a point as centroid is corresponding to the distance from the closest, recently picked centroid.)\n\nK  > select by elbow method\n\nTake care of all point in one cluster are close together(distance small) and distance between two cluster is large\n\nAs it is unsupervised there is no target and we can measure it by silhoutte score \n\nhttps:\/\/scikit-learn.org\/stable\/auto_examples\/cluster\/plot_kmeans_silhouette_analysis.html\n\n\n![](https:\/\/www.unioviedo.es\/compnum\/labs\/new\/d1.png)\n\n\nSilhouette Coefficient \n\nSilhouette Coefficient or silhouette score is a metric used to calculate the goodness of a clustering technique. Its value ranges from -1 to 1. \n\n![](https:\/\/miro.medium.com\/max\/712\/1*cUcY9jSBHFMqCmX-fp8BvQ.jpeg)\n\nhttps:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.cluster.KMeans.html\n\"\"\"\n\"\"\"\n**What does Kmeans inertia mean?**\n\nInertia measures how well a dataset was clustered by K-Means. It is calculated by measuring the distance between each data point and its centroid, squaring this distance, and summing these squares across one cluster. A good model is one with low inertia AND a low number of clusters ( K ).\n\n![](https:\/\/editor.analyticsvidhya.com\/uploads\/62725cluster0.PNG)\n\"\"\"\n\"\"\"\n# Elbow Method\n\"\"\"\n##\ndf=pd.read_csv('..\/input\/student-study-hour-v2\/Student Study Hour V2.csv')\nsns.scatterplot(x='Hours',y='Scores',data=df)\n\n##\nfrom sklearn.cluster import KMeans\nindiviual_cluster=[]\nnum_cluster =5\nfor i in range(1,num_cluster):\n    kmeans = KMeans(n_clusters=i, random_state=0)\n    kmeans.fit(df)\n    indiviual_cluster.append(kmeans.inertia_)\n##    \nplt.figure(figsize=(16,5))\nplt.plot(range(1,num_cluster),indiviual_cluster)\nplt.title('Elbow Method',fontsize=20)\nplt.ylabel(\"Cluster Score\",fontsize=14)\nplt.xlabel('Number of cluster',fontsize=14)\n##\nprint('indiviual_cluster ',indiviual_cluster)\nn_clusters=2\nkmeans = KMeans(n_clusters=n_clusters,init='random',random_state=0).fit(df)\npred=kmeans.predict(df)\n\n##\nprint('predict\\n',pred)\ndf['Cluster']=pd.DataFrame(pred,columns=['cluster'])\n##\nsns.lmplot(x='Hours',y='Scores',data=df,hue='Cluster')\nsns.lmplot(x='Hours',y='Scores',data=df,fit_reg=False,hue='Cluster',legend=True)\n##\nprint('Labels\\n',kmeans.labels_,'\\ncluster_centers_\\n',kmeans.cluster_centers_,'\\ninertia_\\n',kmeans.inertia_,'in n_clusters ',n_clusters)\n\"\"\"\n# Reference\n\nhttps:\/\/youtu.be\/PONM8A7Gwl4\n\nhttps:\/\/youtu.be\/vsWrXfO3wWw\n\nhttps:\/\/youtu.be\/XtE7hqFsYc4\n\nhttps:\/\/youtu.be\/_jg1UFoef1c\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '9e19cc47e0cabc'}"}
{"id":"72958","text":"\"\"\"\n<a class=\"anchor\" id=\"0\"><\/a>\n# **Keras basics for beginners**\n\n\nHello friends,\n\nIn this kernel, I will discuss Keras and Keras fundamentals. In particular, I will show how to compile, train and evaluate the model using Keras. Also, I present a Simple Linear Regression example using Keras and visualize the results. \n\nSo, let's get started.\n\"\"\"\n\"\"\"\n**I hope you find this kernel useful and your <font color=\"red\"><b>UPVOTES<\/b><\/font> would be very much appreciated**\n\"\"\"\n\"\"\"\n<a class=\"anchor\" id=\"0.1\"><\/a>\n## Table of Contents\n\n1. [Introduction to Keras](#1)\n1. [What is a backend](#2)\n1. [Keras fundamentals](#3)\n   - [Keras Sequential model](#3.1)\n   - [Keras Functional API](#3.2)\n1. [Keras layers](#4)\n   - [Sequential Model](#4.1)\n   - [Convolutional Layer](#4.2)\n   - [MaxPooling Layer](#4.3)\n   - [Dense Layer](#4.4)\n   - [Dropout Layer](#4.5)\n1. [Compile, train and evaluate model](#5)\n   - [Compile with .compile() method](#5.1)\n   - [Train with ,fit() method](#5.2)\n   - [Evaluate with .evaluate() method](#5.3)\n1. [Keras in action - Simple Linear Regression example](#6)\n1. [Conclusion](#7)\n\n\"\"\"\n\"\"\"\n## 1. Introduction to Keras <a class=\"anchor\" id=\"1\"><\/a>\n\n\n[Back to Table of Contents](#0.1)\n\n\n\n- Keras is an Open Source Neural Network library written in Python that runs on top of Theano or Tensorflow. \n\n- It is designed to be modular, fast and easy to use.\n\n- Keras High-Level API handles the way we make models, defining layers, or set up multiple input-output models. In this level, Keras also compiles our model with loss and optimizer functions, training process with fit function. \n\n- Keras doesn't handle Low-Level API such as making the computational graph, making tensors or other variables because it has been handled by the \"backend\" engine.\n\n- So, Keras doesn't handle low-level computation. Instead, it uses another library to do it, called the **Backend**. Thus, Keras is a high-level API wrapper for the low-level API, capable of running on top of TensorFlow, CNTK or Theano.\n\n- Please consult the Keras Official documentation for more information on Keras:-\n\n[Keras Official Documentation](https:\/\/keras.io\/)\n\"\"\"\n\"\"\"\n## 2. What is a backend <a class=\"anchor\" id=\"2\"><\/a>\n\n[Back to Table of Contents](#0.1)\n\n- **Backend** is a term in Keras that performs all low-level computations such as tensor products, convolutions and many other things with the help of other libraries such as Tensorflow or Theano. \n\n- So, the **backend engine** will perform the computation and development of the models. Tensorflow is the default **backend engine** but we can change it in the configuration.\n\"\"\"\n\"\"\"\n## 3. Keras fundamentals <a class=\"anchor\" id=\"3\"><\/a>\n\n[Back to Table of Contents](#0.1)\n\n\n- The main structure in Keras is the model which defines the complete graph of a network. \n\n- It is a way to organize layers.\n\n- The simplest type of model is the **Sequential model**. It is the linear stack of layers. \n\n- For more complex architectures, we should use the **Keras functional API**, which allows to build arbitrary graphs of layers.\n\"\"\"\n\"\"\"\n### 3.1 Keras Sequential model <a class=\"anchor\" id=\"3.1\"><\/a>\n\n\n- The **Sequential model** is a linear stack of layers.\n\n- We can create a Sequential model by passing a list of layer instances to the constructor as follows:-\n\n\n`from keras.models import Sequential`\n\n`from keras.layers import Dense, Activation,Conv2D,MaxPooling2D,Flatten,Dropout`\n\n`model = Sequential()`\n\n\n- We can also simply add layers via the **.add()** method as follows:-\n\n`model = Sequential()`\n\n`model.add(Dense(32, input_dim=784))`\n\n`model.add(Activation('relu'))`\n\n\n- For more detailed discussion on Keras Sequential model follow the link below:-\n\n\n[Keras Sequential model](https:\/\/keras.io\/getting-started\/sequential-model-guide\/)\n\"\"\"\n\"\"\"\n### 3.2 Keras Functional API <a class=\"anchor\" id=\"3.2\"><\/a>\n\n\n- The **Keras functional API** is used to define complex models, such as multi-output models, directed acyclic graphs, or models with shared layers.\n\n\n- For more detailed discussion on Keras Functional API follow the link below:-\n\n[Keras Functional API](https:\/\/keras.io\/getting-started\/functional-api-guide\/)\n\n\"\"\"\n\"\"\"\n## 4. Keras layers <a class=\"anchor\" id=\"4\"><\/a>\n\n\n[Back to Table of Contents](#0.1)\n\n\n- Keras consists of different types of layers which are fundamental to building blocks of Keras.\n\n- In this section, we will discuss few commonly used layers in Keras.\n\n\"\"\"\n\"\"\"\n### 4.1 Sequential Model <a class=\"anchor\" id=\"4.1\"><\/a>\n\n\n- We can create a Sequential model by passing a list of layer instances to the constructor as follows:-\n\n\n`from keras.models import Sequential`\n\n`from keras.layers import Dense, Activation,Conv2D,MaxPooling2D,Flatten,Dropout`\n\n`model = Sequential()`\n\n\n\"\"\"\n\"\"\"\n### 4.2 Convolutional Layer <a class=\"anchor\" id=\"4.2\"><\/a>\n\n\n- This is an example of convolutional layer as the input layer with the input shape of 320x320x3, with 48 filters of size 3x3 and use ReLU as an activation function.\n\n\n`input_shape=(320,320,3)`  #this is the input shape of an image 320x320x3\n\n`model.add(Conv2D(48, (3, 3), activation='relu', input_shape= input_shape))`\n\n\n- Another example is as follows:-\n\n`model.add(Conv2D(48, (3, 3), activation='relu'))`\n\"\"\"\n\"\"\"\n### 4.3 MaxPooling Layer <a class=\"anchor\" id=\"4.3\"><\/a>\n\n\n- To downsample the input representation, use MaxPool2d and specify the kernel size.\n\n\n`model.add(MaxPooling2D(pool_size=(2, 2)))`\n\"\"\"\n\"\"\"\n### 4.4 Dense Layer <a class=\"anchor\" id=\"4.4\"><\/a>\n\n\n- We can add a fully connected layer with just specifying the output size,\n\n`model.add(Dense(256, activation='relu'))`\n\"\"\"\n\"\"\"\n### 4.5 Dropout Layer <a class=\"anchor\" id=\"4.5\"><\/a>\n\n\n- We can add a dropout layer with 50% probability as follows:-\n\n`model.add(Dropout(0.5))`\n\"\"\"\n\"\"\"\n## 5. Compile, train and evaluate model <a class=\"anchor\" id=\"5\"><\/a>\n\n[Back to Table of Contents](#0.1)\n\"\"\"\n\"\"\"\n### 5.1 Compile with .compile() method <a class=\"anchor\" id=\"5.1\"><\/a>\n\n\n- After we have define our model, we will train them. \n\n- It is required to compile the network first with the loss function and optimizer function. \n\n- This will allow the network to change weights and minimized the loss.\n\n- We will compile our model with **.compile()** method as follows:-\n\n\n`model.compile(loss='mean_squared_error', optimizer='adam')`\n\n\n\"\"\"\n\"\"\"\n### 5.2 Train with .fit() method <a class=\"anchor\" id=\"5.2\"><\/a>\n\n\n- Now we want to train our model.\n\n- We can use **.fit()** method to fed the training and validation data to the model. \n\n- This will allow you to train the network in batches and set the epochs as follows:-\n\n`model.fit(X_train, X_train, batch_size=32, epochs=10, validation_data=(x_val, y_val))`\n\"\"\"\n\"\"\"\n### 5.3 Evaluate with .evaluate() method <a class=\"anchor\" id=\"5.3\"><\/a>\n\n\n- The final step is to evaluate the model with the test data.\n\n- It can be done with the **.evaluate()** method as follows:-\n\n`score = model.evaluate(x_test, y_test, batch_size=32)`\n\"\"\"\n\"\"\"\n## 6. Keras in action - Simple Linear Regression example <a class=\"anchor\" id=\"6\"><\/a>\n\n[Back to Table of Contents](#0.1)\n\"\"\"\n# Import necessary modules\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n \n# Define data for the model\nx = data = np.linspace(1,2,200)\ny = x*4 + np.random.randn(*x.shape) * 0.3\n\n\n# Create a Sequential model\nmodel = Sequential()\n\n\n# Add layers to the Sequential model\nmodel.add(Dense(1, input_dim=1, activation='linear'))\n\n\n# Compile the model\nmodel.compile(optimizer='sgd', loss='mse', metrics=['mse'])\n\n\n# Declare initial weights and bias\nweights = model.layers[0].get_weights()\nw_init = weights[0][0][0]\nb_init = weights[1][0]\nprint('Linear regression model is initialized with weights w: %.2f, b: %.2f' % (w_init, b_init)) \n\n\n# Train the model\nmodel.fit(x,y, batch_size=1, epochs=30, shuffle=False)\n\n\n# Set final weights and bias\nweights = model.layers[0].get_weights()\nw_final = weights[0][0][0]\nb_final = weights[1][0]\nprint('Linear regression model is trained to have weight w: %.2f, b: %.2f' % (w_final, b_final))\n\n\n# Predict the results\npredict = model.predict(data)\n\n\n# Visualize the results\nplt.figure(figsize=(12,8))\nplt.plot(data, predict, 'b', data , y, 'k.')\nplt.show()\n\"\"\"\nAfter training the data, the output should look like the above plot.\n\"\"\"\n\"\"\"\n## 7. Conclusion <a class=\"anchor\" id=\"7\"><\/a>\n\n\n[Back to Table of Contents](#0.1)\n\n- In this kernel, I present a high level overview of Keras - the Deep Learning library of Python.\n\n- In particular, I discuss the Keras Sequential model and Keras Functional API, common layers in Keras and how to compile, train and evaluate our model.\n\n- Then, I present a simple linear regression example using Keras\n\"\"\"\n\"\"\"\nThus, we come to the end of this kernel.\n\n\nI hope you find it useful and enjoyable.\n\"\"\"\n\"\"\"\n[Go to Top](#0)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '864cbb769c57d2'}"}
{"id":"69846","text":"\"\"\"\n# Cardio Good Fitness Case Study \nThe market research team at AdRight is assigned the task to identify the profile of the typical customer for each treadmill product offered by CardioGood Fitness. The market research team decides to investigate whether there are differences across the product lines with respect to customer characteristics. The team decides to collect data on individuals who purchased a treadmill at a CardioGoodFitness retail store during the prior three months. The data are stored in the CardioGoodFitness.csv file.\n\n### The team identifies the following customer variables to study: \n  - product purchased, TM195, TM498, or TM798; \n  - gender; \n  - age, in years; \n  - education, in years; \n  - relationship status, single or partnered; \n  - annual household income ; \n  - average number of times the customer plans to use the treadmill each week; \n  - average number of miles the customer expects to walk\/run each week; \n  - and self-rated fitness on an 1-to-5 scale, where 1 is poor shape and 5 is excellent shape.\n\n**Objective**\n- Identify differences between customers of each product\n- Explore relationships between the difference attributes of customers\n\"\"\"\n\"\"\"\n### Import required libraries:\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore') \n\n\"\"\"\n### Load Dataset:\n\"\"\"\n#Load the Cardio Dataset\n\nmydata = pd.read_csv('..\/input\/cardiogoodfitness\/CardioGoodFitness.csv')\n\"\"\"\n### Understanding the structure of Data:\n\"\"\"\nmydata.head()\nmydata.tail()\nmydata.shape\n\"\"\"\n **Observations:** There are 180 observations of 9 columns in the dataset\n\"\"\"\nmydata.dtypes\n\"\"\"\n **Observations:**\n\n1. Columns Product, Gender and Marital Status are of string datatype \n2. Columns Age, Education, Usage, Fitness, Income and Miles are of integer (numerical) datatype\n\"\"\"\nmydata.info()\n\"\"\"\n**Observations:**\n\n1. There are 6 columns of integer type\n2. There are 3 objects of string type\n3. The dataset is of approximately 12.8 kb in size\n4. There are 180 rows\n\n\"\"\"\nmydata.columns\nmydata.isnull().sum()\nmydata.describe(include ='all')\n\"\"\"\n**Observations:** \n\n**A. AGE:**\n\n    1. Customers between 18 and 50 years of age are using treadmill\n    2. Average age is 28.78 years\n    3. As there is not much difference in mean and median, the skewness in data is minimal\n\n**B. INCOME:**\n\n    1. Customers with income range of USD 29,500 to USD 104,500 are using treadmill\n    2. Considering the difference between mean and median & mean being greater than median, the data is right skewed\n    3. Standard deviation is very high\n\n**C. MILES:**\n\n    1. Customers are expected to run between 21 to 360 miles per week\n    2. Considering the difference between mean and median & mean being greater than median, the data is right skewed\n    3. Standard deviation is very high\n\"\"\"\n\"\"\"\n#### Count based on model\n\"\"\"\nmydata.Product.value_counts()\n\"\"\"\n**Observations:** \n\n1. TM195 is the most sold model\n2. TM798 is the least sold model\n\"\"\"\n\"\"\"\n#### Count based on Gender\n\"\"\"\nmydata.Gender.value_counts()\n\"\"\"\n**Observations:** \n1. Male Customers are buying more treadmills compared to Female Customers\n\"\"\"\n\"\"\"\n#### Count based on Marital Status\n\"\"\"\nmydata.MaritalStatus.value_counts()   \n\"\"\"\n**Observations:**  \n1. Partnered Customers are buying more treadmills compared to Single Customers\n\"\"\"\n\"\"\"\n#### Understanding data for Product Code TM195\n\"\"\"\nmydata[mydata['Product'] == 'TM195'].describe().T\n\"\"\"\n**Observations:**\n\n1. A total of 80 customers purchased TM195 model \n2. Average age of customer is 28.5 (Median: 26) (Range: 18 - 50)\n3. Data is right skewed.\n4. Average number of years of Education for customers is 15 (Median: 16)\n3. Customer wants to use the treadmill at least 3 times per week\n4. Customers are expected to run is 82.78 miles per week (Median: 85)\n5. Average income and median is approximately USD 46,000 \n\"\"\"\n\"\"\"\n#### Understanding data for Product Code TM498\n\"\"\"\nmydata[mydata['Product'] == 'TM498'].describe().T\n\"\"\"\n**Observations:**\n\n1. A total of 60 customers purchased TM498 model\n2. Average age of customer is 28.9 (Median: 26) (Range: 19-48)\n3. Data is right skewed.\n4. Average number of years of Education for customers is 15 (Median: 16)\n5. Customer wants use the treadmill at least 3 times per week\n6. Customers are expected to run is 60 miles per week (Median: 85)\n7. Average income is USD 46,000 (Median: USD 49,459)\n\"\"\"\n\"\"\"\n#### Understanding data for Product Code TM798\n\"\"\"\nmydata[mydata['Product'] == 'TM798'].describe().T\n\"\"\"\n**Observations:**\n\n1. A total of 40 customers purchased TM798 model\n2. Average age of customer is 29 (Median: 27) (Range: 22-48)\n3. Average number of years of Education for customers is 17 (Median: 18)\n4. Customer wants to use the treadmill at least 4-5 times per week\n5. Customers are expected to run are 166 miles per week (Median: 160)\n6. Average income is USD 75,000 (Median: USD 76,000)\n\"\"\"\n\"\"\"\n## Univeriate Analysis:\n\"\"\"\n\"\"\"\n### Analysis Based on Age\n\"\"\"\n# Historam for age\nplt.hist(mydata.Age, edgecolor = 'white')\nplt.title(\"Histogram view of Age\")\nplt.show()\n# Distribute data in Age groups\nbins = [20,25,30,35,40,45,50]\nplt.hist(mydata.Age,bins,edgecolor = 'white')\nplt.title(\"Categorical histogram of Age\")\nplt.show()\n# Distribute data in Age groups\nbins = [18,20,22,24,26,28,30,32,34]\nplt.hist(mydata.Age,bins,edgecolor = 'white')\nplt.title(\"Categorical histogram of Age\")\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Most customers are in the age range of 22 - 32\n2. Further classification reveals that most customers are of ages between 24 and 26 years, followed by customers from age group 22 and 24 years\n\"\"\"\n\"\"\"\n### Analysis based on Income\n\"\"\"\n# Visualisation of income range\nsns.distplot(mydata.Income)\nplt.title(\"Distribution Plot of Income\")\nplt.show()\n# boxplot view of income\nsns.boxplot(mydata.Income)\nplt.title(\"Box plot Plot of Income\")\nplt.show()\n\"\"\"\n**Observations:**\n\n1. There are two peaks shown by the income range of people\n2. Data is right skewed and shows outliers on the right\n3. Most Customers fall in range of USD 45,000 - USD 60,000\n4. Outliers are observed above USD 85,000\n\"\"\"\n\"\"\"\n### Analysis based on Gender\n\"\"\"\n# Number of records per gender and product model\nsns.countplot(mydata.Gender, hue=mydata.Product)\nplt.title('Gender based distribution')\nplt.show()\n# Number of records per model and per gender\nsns.countplot('Product', hue='Gender',data=mydata)\nplt.title('Gender based distribution')\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Number of male customers purchasing treadmill is more than Female Customers\n2. TM798 is the least popular model of treadmill in Female Customers\n3. TM195 is equally preferred model of treadmill in both male and Female Customers\n\"\"\"\n\"\"\"\n### Analysis based on Marital Status\n\"\"\"\n#\u00a0Number\u00a0of\u00a0records per\u00a0model\u00a0and\u00a0per\u00a0Marital Status\nsns.countplot(mydata.Product, hue=mydata.MaritalStatus)\nplt.title('Marital Status based distribution')\nplt.show()\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0model\u00a0and\u00a0per\u00a0Marital Status\nsns.countplot(mydata.MaritalStatus, hue=mydata.Product)\nplt.title('Marital Status based distribution')\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Partnered Customers have purchased treadmill more than Single Customers\n2. TM195 model is popular in both Marital Statuses\n\n\"\"\"\n\"\"\"\n### Analysis based on Usage\n\"\"\"\n#\u00a0Number\u00a0of\u00a0records based on usage per week\nsns.countplot(mydata.Usage)\nplt.title('Count based on Usage')\nplt.show()\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0model\u00a0and\u00a0for number of times of\u00a0Usage\nsns.countplot(mydata.Product, hue=mydata.Usage)\nplt.title('Usage based distribution')\nplt.show()\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0model\u00a0and\u00a0per\u00a0Usage\nsns.countplot(mydata.Usage, hue=mydata.Product)\nplt.title('Usage based distribution')\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Most customers use Treadmill at least 3 times per week\n2. TM195 is most popular amongst active customers\n3. Few customers using TM798 Model use the treadmill for 7 times in a week\n\"\"\"\n\"\"\"\n### Analysis based on Fitness Level\n\"\"\"\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0Fitness\nsns.countplot(mydata.Fitness)\nplt.title('Count based on Self Acclaimed Fitness Levels')\nplt.show()\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0model\u00a0and\u00a0for fitness rating\nsns.countplot(mydata.Product, hue=mydata.Fitness)\nplt.title('Distribution based on Fitness Levels')\nplt.show()\n#\u00a0Number\u00a0of\u00a0records\u00a0per\u00a0model\u00a0and\u00a0for fitness rating\nsns.countplot(mydata.Fitness, hue=mydata.Product)\nplt.title('Distribution based on Fitness Levels')\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Most customers have rated themselves at Level 3 of Fitness levels\n2. TM195 is most popular amongst customers at Level 3\n3. Almost all Customers at Fitness Level 5 use TM798 model\n\"\"\"\n\"\"\"\n### Analysis based on Education\n\"\"\"\n# Distribution based on number of years of education\nsns.countplot(mydata.Education)\nplt.title(\"Count based on number of years of Education\")\nplt.show()\n# Number of records per model for customer segments based on the number of years of education\nsns.countplot(mydata.Education, hue=mydata.Product)\nplt.title('Distribution based on Education')\nplt.show()\n# Number of records per model for customer segments based on the number of years of education\nplt.figure(figsize=(10,5))\nsns.countplot(mydata.Product, hue=mydata.Education)\nplt.title('Distribution based on Education')\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Most Customers using treadmill have 16 to 18 years of Education\n2. Customers with more than 20 years of education have only purchased TM798 Model\n3. TM798 is most preferred by the customer with 18 years of education\n\"\"\"\n\"\"\"\n### Analysis based on Miles planned per week\n\"\"\"\n# Distribution plot of Miles with RUG and KDE\nsns.distplot(mydata.Miles, rug=True)\nplt.title('Count based on Miles')\nplt.show()\n# Boxplot view of data based on miles\nsns.boxplot(mydata.Miles)\nplt.title(\"Boxplot of Miles\")\nplt.show()\n\"\"\"\n**Observations:**\n\n1. Outliers are seen on the higher values \n2. Customers are planning to run more than 180 miles per week\n\n\n\"\"\"\n# List the data where miles are greater than 180\nmydata[mydata['Miles'] > 180]\n\"\"\"\n## Bivariate Analysis:\n\"\"\"\n\"\"\"\n#### Average\u00a0age\u00a0for\u00a0each\u00a0model\n\"\"\"\nmydata.groupby('Product')['Age'].mean()\n\"\"\"\n#### Average\u00a0Income\u00a0for\u00a0each\u00a0model\n\"\"\"\nmydata.groupby('Product')['Income'].mean()\n\"\"\"\n#### Average\u00a0miles\u00a0per\u00a0model\n\"\"\"\nmydata.groupby('Product')['Miles'].mean()\n\"\"\"\n#### Average\u00a0of\u00a0number\u00a0of\u00a0years\u00a0of\u00a0education\u00a0for\u00a0each\u00a0model\n\"\"\"\nmydata.groupby('Product')['Education'].mean()\n\"\"\"\n### Analysis of Miles based on Age\n\"\"\"\nsns.jointplot(x = 'Age' , y = 'Miles', data = mydata)\nplt.show()\n\"\"\"\n**Observations:**\n\nThere is no definite correlation observed between Age and Miles\n\"\"\"\n\"\"\"\n### Analysis of Income based on Age\n\"\"\"\nsns.jointplot(x = 'Age' , y = 'Income', data = mydata, color='red', kind ='hex')\nplt.show()\n\"\"\"\n**Observations:**\n\nIncome increases with the age, depicting positive correlation.\n\"\"\"\n\"\"\"\n### Analysis of Miles based on Income\n\"\"\"\nsns.jointplot(x = 'Income' , y = 'Miles', data = mydata, color='orange', kind ='hex')\nplt.show()\n\"\"\"\n**Observations:**\n\nWith increase in Customer Income a slight increase is observed in Miles\n\"\"\"\n\"\"\"\n### Analysis of Income based on Gender\n\"\"\"\nsns.catplot(x = 'Gender' , y = 'Income', data = mydata)\nplt.show()\n\"\"\"\n**Observations:**\n\nMale Customers have higher income range, when compared to Female Customers\n\"\"\"\n\"\"\"\n### Analysis of Miles based on Gender\n\"\"\"\nsns.catplot(x = 'Gender' , y = 'Miles', data = mydata, kind = 'violin')\nplt.show()\n\"\"\"\n**Observations:**\n\nMale Customers plan to run more miles, when compared to Female Customers\n\"\"\"\n\"\"\"\n### Analysis of Usage based on Gender\n\"\"\"\nsns.catplot(x = 'Gender' , y = 'Usage', data = mydata, kind = 'bar')\nplt.show()\n\"\"\"\nObservations:\n\nMale Customers show higher usage per week, when compared to Female Customers\n\"\"\"\n\"\"\"\n### Analysis of Income based on Marital Status\n\"\"\"\nsns.catplot(x = 'MaritalStatus' , y = 'Income', data = mydata, kind = 'box')\nplt.show()\n\"\"\"\nObservations:\n\nPartnered Customers have higher income range, when compared to Single Customers\n\"\"\"\n\"\"\"\n### Analysis of Miles based on Marital Status\n\"\"\"\nsns.catplot(x = 'MaritalStatus' , y = 'Miles', data = mydata, kind = 'swarm')\nplt.show()\n\"\"\"\nObservations:\n\nPartnered Customers plan to run more miles, when compared to Single Customers\n\"\"\"\n\"\"\"\n## Multivariate Analysis:\n\"\"\"\n\"\"\"\n### Multicolumn catplot of Marital Status showing Gender based data compared to Income\n\"\"\"\nsns.catplot( x = \"Gender\", y = 'Income', hue = 'Product', col = 'MaritalStatus',data = mydata, kind = 'bar');\n\"\"\"\n**Observations:**\n\n1. TM798 leads all charts across Customer Segments\n2. Single Female Customers have purchased more of TM195 and TM498 models compared to Single Male Customers\n3. Single Male Customers are more than Single Female Customers \n4. Partnered Female Customers are more than Partnered Male Customers\n\"\"\"\n\"\"\"\n### Pointplot showing sales based on Education and Income\n\"\"\"\nsns.pointplot(x=mydata[\"Education\"],y=mydata[\"Income\"],hue=mydata['Product']) \nplt.show()\n\"\"\"\n**Observation:-**\n\n   1. Customers with higher education has higher income range\n   2. TM798 has higher income and higher education\n\"\"\"\n\"\"\"\n### Correlation between Numerical columns of dataset\n\"\"\"\n# Correlation of numerical values in dataset\nmydata.corr()\n# Heatmap for the correlation of numerical values in dataset\nsns.heatmap(mydata.corr(), annot=True, vmin=-1, vmax = 1) \nplt.show()\n\"\"\"\n**Observations:**\n\n1. Miles and Usage show high correlation\n2. Fitness and Miles show high correlation\n3. Education and Income show notable correlation\n4. Usage and Fitness show notable correlation\n5. Income and Usage show little correlation\n\"\"\"\n\"\"\"\n#### Pairplot of all numerical values with clasification of Product\n\"\"\"\nsns.pairplot(mydata, hue='Product')\nplt.show()\n\"\"\"\n#### Pairplot of all numerical values using KDE\n\"\"\"\nsns.pairplot(mydata, kind='kde')\nplt.show()\n\"\"\"\n## Conclusion (Important Observations):\n\n1. TM195 is most sold model, accounting for 44.44% of total sales.\n2. 57.78% of Customers are Male Customers, which is more than the Female Customers.\n3. Partnered customers account for 59.44% of sales.\n4. Most customers are between 22 to 26 years of age.\n5. TM798 is most preferred by customers with higher income range.\n\"\"\"\n\"\"\"\n## Recommendations:\n\n1. TM195 and TM498 are popular with customers in USD 45,000 and USD 60,0000 income range and can be promoted as affordable models for these income groups\n2. TM798 should be branded as Premium Model and marketed among high income groups and specific customer categories. Promotional programs can be run for upgrades from other models.\n3. Rewards programs can be launched to promote per week of usage. Gamification based on points can also be introduced, with weekly leader boards.\n4. Special promotions to be run to target Female Customers, for instance:\n    1. Discounts on Women's Day and similar celebrated ocassions\n    2. Purchase offers using Credit Card or Bank Reward points\n    3. Free additional gifts and hampers from partners\n5. Market research can be conducted to check the feasibility of attracting customers outside the age range of 18-35.\n\"\"\"\n\"\"\"\nKshitij\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '807c82ecf5331d'}"}
{"id":"134919","text":"\"\"\"\n# Importing Libraries\n\"\"\"\n!pip install siuba\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport datetime\nfrom siuba.dply.forcats import fct_lump\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### Setting the Style\n\"\"\"\nsns.set_theme(style = 'darkgrid')\n\"\"\"\n# Importing Data\n\"\"\"\ndf = pd.read_csv('\/kaggle\/input\/netflix-shows\/netflix_titles.csv')\nnetflix = df.copy()\nnetflix.head()\n\"\"\"\n### Inspecting the Data\n\"\"\"\n(netflix.isnull().sum()\/len(netflix)) * 100\n\"\"\"\n# Preprocessing\n\"\"\"\n# filling missing values for each variables\nnetflix['director'] = netflix['director'].fillna(value = 'No Director')\nnetflix['cast'] = netflix['cast'].fillna(value = 'No Cast')\nnetflix['country'] = netflix['country'].fillna(value = 'United States')\nnetflix['date_added'] = netflix['date_added'].fillna(value = datetime.datetime(2020, 1,1))\nnetflix['rating'] = netflix['rating'].fillna(value = 'Other')\n\n# lump together least\/most common factor levels into \"other\"\nnetflix['rating'] = fct_lump(netflix['rating'], n = 5)\n\n# getting the months from the dates\nnetflix['month'] = pd.to_datetime(netflix['date_added']).dt.month\n(netflix.isnull().sum()\/len(netflix)) * 100\n\"\"\"\n# Creating Useful Functions for Efficiency!\n\"\"\"\ndef column_list_tokenizer_count(df, subset_cols, secondary_col):\n\n    # Creating an empty list\n    token_list = []\n\n    # Removing any missing values just in case if they are any within the dataset. \n    # As well reseting the index.\n    clean_df = df.dropna(subset = [subset_cols])\n    clean_df.reset_index(inplace = True)\n    \n    # This for loop would go to every single row and split the string \n    # values into a list essentially tokenizing them.\n    if secondary_col == None:\n        for i, element in clean_df.iterrows():\n            for token in str(element[subset_cols]).strip(' ').split(','):\n                token_list.append([token.strip()])\n\n    # Returns a dataframe based from the appended list and counting each unique value \n    # from the inserted 'subset_cols' variable.\n        token_data = pd.DataFrame(data = token_list, columns = [token])\n        return token_data\n    else:\n        for i, element in clean_df.iterrows():\n            secondary_cols = element[secondary_col]\n            for token in str(element[subset_cols]).strip(' ').split(','):\n                token_list.append([secondary_cols, token.strip()])\n\n        token_data = pd.DataFrame(data = token_list, columns = [secondary_cols, token])\n        return token_data.value_counts().to_frame().rename(columns = {0: 'count'}).reset_index(level = [0, 1])\ndef plot_bar(x_var, y_var, df, num_colors, title_name, xlabel_name, ylabel_name, hue_col):\n    if hue_col == None:\n        plt.figure(figsize = (10,6))\n        sns.barplot(x = x_var, y = y_var, data = df, ci = False,\n                    palette = sns.dark_palette(color = '#b60c26', n_colors = num_colors, reverse = True, input = 'hsl'))\n        plt.title(title_name, fontdict = {'fontsize': 16, 'fontweight': 'bold'})\n        plt.xlabel(xlabel_name)\n        plt.ylabel(ylabel_name)\n        plt.show()\n    else:\n        plt.figure(figsize = (10,6))\n        sns.barplot(x = x_var, y = y_var, data = df, ci = False, hue = hue_col,\n                    palette = sns.dark_palette(color = '#b60c26', n_colors = num_colors, reverse = True, input = 'hsl'))\n        plt.title(title_name, fontdict = {'fontsize': 16, 'fontweight': 'bold'})\n        plt.xlabel(xlabel_name)\n        plt.ylabel(ylabel_name)\n        plt.show()\n\"\"\"\n# Genres Distribution between Movies and TV Shows\n\"\"\"\ngenre_data = (column_list_tokenizer_count(df = netflix, subset_cols = 'listed_in', secondary_col = 'type')\n             .rename(columns = {'Movie': 'type', ' Music & Musicals': 'genre'}))\ntop_genre_movies = genre_data[genre_data['type'] == 'Movie'].nlargest(n = 10, columns = 'count')\ntop_genre_movies\nplot_bar(x_var = 'count',\n         y_var = 'genre',\n         df = top_genre_movies, \n         num_colors = 10, \n         title_name = 'Top 10 Genres in Movies', \n         xlabel_name = 'Frequency', \n         ylabel_name = 'Name of Genres',\n         hue_col = None)\ntop_genre_shows = genre_data[genre_data['type'] == 'TV Show'].nlargest(n = 10, columns = 'count')\ntop_genre_shows\nplot_bar(x_var = 'count',\n         y_var = 'genre',\n         df = top_genre_shows, \n         num_colors = 10, \n         title_name = 'Top 10 Genres in TV Shows', \n         xlabel_name = 'Frequency', \n         ylabel_name = 'Name of Genres', \n         hue_col = None)\n\"\"\"\n# Content Type Distibution in the World\n\"\"\"\nplt.figure(figsize = (10, 6))\nsns.countplot(x = 'type', hue = 'rating', data = netflix, palette = sns.color_palette(\"icefire\"))\nplt.title('Rating Type Distibution in Movies and TV Shows', fontdict = {'fontsize': 16, 'fontweight': 'bold'})\nplt.xlabel('Content Type')\nplt.ylabel('Rating Frequency')\nplt.show()\ntop_10_countries = (column_list_tokenizer_count(df = netflix, subset_cols = 'country', secondary_col = None)\n                   .value_counts()\n                   .to_frame()\n                   .reset_index()\n                   .rename(columns = {' United States': 'country', 0: 'count'})\n                   .nlargest(n = 10, columns = 'count'))\n\nplot_bar(x_var = 'count',\n         y_var = 'country',\n         df = top_10_countries, \n         xlabel_name = 'Frequency', \n         ylabel_name ='Name of Countries', \n         title_name = 'Countries with the Most Content', \n         num_colors = 10, \n         hue_col = None)\ncountry_data = (column_list_tokenizer_count(df = netflix, subset_cols = 'country',secondary_col = 'type')\n                .rename(columns = {'Movie': 'type', ' United States': 'country'}))\ntop_countries_content = country_data[country_data['country'].isin(top_10_countries['country'])]\ntop_countries_content.head()\nplot_bar(x_var = 'count', \n         y_var = 'country', \n         df = top_countries_content,\n         num_colors = 2, \n         xlabel_name = 'Frequency', \n         ylabel_name = 'Name of Countries', \n         title_name = 'Which Content Type does each Country produce the most?', \n         hue_col = 'type')\nyears_count_type = (netflix[(netflix['release_year'] >= 2007) & (netflix['release_year'] < 2021)]\n                   .groupby(by = ['type', 'release_year'], as_index = False)['show_id']\n                   .count())\nyears_count_type.rename(columns = {'show_id': 'count'}, inplace = True)\nyears_count_type.head()\nplt.figure(figsize = (10, 6))\nsns.lineplot(x = 'release_year', y = 'count', hue = 'type', data = years_count_type, \n             palette = sns.dark_palette(color = '#b60c26', n_colors = 2, reverse = True, input = 'hsl'))\nplt.title('The Growth of Movies\/TV Shows over the years', fontdict = {'fontsize': 16, 'fontweight': 'bold'})\nplt.xlabel('Release Year')\nplt.xticks(ticks = years_count_type['release_year'].unique())\nplt.ylabel('Frequency')\nplt.show()\nnet_rating = (netflix\n             .groupby(by = ['month', 'rating'])['month']\n             .count()\n             .to_frame()\n             .rename(columns = {'month':'count'})\n             .reset_index())\n\nplt.figure(figsize = (10,6))\nsns.lineplot(x = 'month', \n             y = 'count', \n             data = net_rating,\n             hue = 'rating', \n             style = 'rating', \n             markers= True,\n             palette = sns.color_palette(\"icefire\"))\n\nplt.title('Which Rating Type does Netflix\\n put more into their Platform Per Month?', \n           fontdict = {'fontsize': 16, 'fontweight': 'bold'})\nplt.xticks(ticks = net_rating['month'].unique())\nplt.xlabel('Month')\nplt.ylabel('Frequency')\nplt.show()\nnet_type = (netflix\n            .groupby(by = ['month', 'rating', 'type'])['month']\n            .count()\n            .to_frame()\n            .rename(columns = {'month':'count'})\n            .reset_index())\n\ng = sns.FacetGrid(net_type, col = 'type', hue = 'rating', palette = sns.color_palette('icefire'))\ng.map(sns.lineplot, 'month', 'count')\ng.set_titles(col_template = 'Which rating type does Netflix\\n put more into their Plaform for\\n {col_name}s Per Month?')\ng.set_axis_labels('Month', 'Frequency')\ng.set(xticks = net_type['month'].unique())\ng.fig.subplots_adjust(wspace = .15, hspace = .25)\ng.add_legend()\nplt.show()\n\"\"\"\n# Director Analysis for Movies and TV Shows\n\"\"\"\ndirector_data = (column_list_tokenizer_count(df = netflix, subset_cols = 'director', secondary_col = 'type')\n                .rename(columns = {'Movie': 'type', 'Sam Dunn': 'director'}))\ndirector_data.head()\ntop_director_movies = (director_data[(director_data['type'] == 'Movie') & (director_data['director'] != 'No Director')]\n                      .nlargest(n = 10, columns = 'count'))\n\nplot_bar(x_var = 'count', y_var = 'director', hue_col = None,\n         df = top_director_movies, xlabel_name = 'Director Frequency', ylabel_name = 'Name of Directors', num_colors = 10,\n         title_name = 'Top 10 Famous Directors in Movies')\ntop_director_shows = (director_data[(director_data['type'] == 'TV Show') & (director_data['director'] != 'No Director')]\n                      .nlargest(n = 10, columns = 'count'))\n                      \nplot_bar(x_var = 'count', y_var = 'director', hue_col = None,\n         df = top_director_shows, xlabel_name = 'Director Frequency', ylabel_name = 'Name of Directors', num_colors = 10,\n         title_name = 'Top 10 Famous Directors in TV Shows')\n\"\"\"\n# Actor Analysis for Movies and TV Shows\n\"\"\"\nactor_data = (column_list_tokenizer_count(df = netflix, subset_cols = 'cast', secondary_col = 'type')\n             .rename(columns = {'Movie': 'type', 'No Cast': 'cast'}))\nactor_data.head()\ntop_actor_movies = (actor_data[(actor_data['type'] == 'Movie') & (actor_data['cast'] != 'No Cast')]\n                    .nlargest(n = 10, columns = 'count'))\n                      \nplot_bar(x_var = 'count', y_var = 'cast', hue_col = None,\n         df = top_actor_movies, xlabel_name = 'Actor Frequency', ylabel_name = 'Name of Actors', num_colors = 10,\n         title_name = 'Top 10 Famous Actors in Movies')\ntop_actor_shows = (actor_data[(actor_data['type'] == 'TV Show') & (actor_data['cast'] != 'No Cast')]\n                    .nlargest(n = 10, columns = 'count'))\n                      \nplot_bar(x_var = 'count', y_var = 'cast', hue_col = None,\n         df = top_actor_shows, xlabel_name = 'Actor Frequency', ylabel_name = 'Name of Actors', num_colors = 10,\n         title_name = 'Top 10 Famous Actors in TV Shows')","meta":"{'source': 'AI4Code', 'id': 'f80d6dbfc312ff'}"}
{"id":"109394","text":"\"\"\"\n# NBME Data Exploration\n\nThis notebook was created during a live coding session on twitch.\n\nFollow here for future streams: [Follow here](https:\/\/www.twitch.tv\/medallionstallion_)\n\nInitially I had a hard time understanding the dataset until I realized the data is from a test being taken by future doctors. This is why features and case numbers are repeated in the training set. This notebook explores some of the best\/worst test takers and hard\/easy cases.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nimport seaborn as sns\nplt.style.use('ggplot')\ntrain = pd.read_csv('..\/input\/nbme-score-clinical-patient-notes\/train.csv')\ntest = pd.read_csv('..\/input\/nbme-score-clinical-patient-notes\/test.csv')\nss = pd.read_csv('..\/input\/nbme-score-clinical-patient-notes\/sample_submission.csv')\npn = pd.read_csv('..\/input\/nbme-score-clinical-patient-notes\/patient_notes.csv')\nfeatures = pd.read_csv('..\/input\/nbme-score-clinical-patient-notes\/features.csv')\ntrain = train.merge(features, on=['case_num','feature_num'], validate='m:1')\ntrain = train.merge(pn, validate='m:1')\n# Print an example patient history notes\nprint(pn.query('pn_num == 16 and case_num == 0')['pn_history'].values[0])\n\"\"\"\n# Score the Test Takers\n- Which test takers performed best\/worst?\n- Which cases were hard or easy to score?\n\nThese results may help you when designing a model to predict the annotations.\n\"\"\"\n# Add label if the test taker correctly identified the feature\ntrain['correct'] = ~(train['annotation'] == \"[]\")\ntrain.groupby('pn_num')['correct'].mean().sort_values() \\\n    .plot(kind='hist', bins=25, figsize=(12, 5),\n          title='% of Features Correctly Noted by Doctor')\nplt.show()\n\"\"\"\n## Bad Test Taker?\nThis is an example of a test taker who labeled 27.7% of the features from this case:\n\"\"\"\nprint(train.query('pn_num == 52923')['pn_history'].values[0])\n\"\"\"\n## Perfect test taker!\n\nThis test taker captured 100% of the features.\n\"\"\"\nprint(train.query('pn_num == 71865')['pn_history'].values[0])\n\"\"\"\n# Are any \"cases\" harder for test takers?\n- We can aggregate the percent correct for each test taker.\n- Take a look at scores per case.\n\"\"\"\ntest_taker_results = train.groupby(['pn_num','case_num'])['correct'] \\\n    .mean().reset_index()\nfig, ax = plt.subplots(figsize=(12, 5))\nsns.boxplot(data=test_taker_results, x='case_num', y='correct')\nax.set_title('% of Features Captured by Case Number')\nax.set_xlabel('Case Number')\nax.set_ylabel('% of Features Captured')\nplt.show()\n\"\"\"\n# What is the best score of a test taker for each case?\n\"\"\"\nax = test_taker_results.groupby('case_num')['correct'].max() \\\n    .plot(kind='bar', color='#F8766D', figsize=(12, 5),\n         title='Best Score for Each Case', edgecolor='black')\n# This case is the hardest to get correct.\n# Even the best test taker only found 76% of the features.\ntest_taker_results.query('case_num == 2').sort_values('correct', ascending=False).head(1)\nprint(train.query('pn_num == 21325')['pn_history'].values[0])\n\"\"\"\n## Test Taker Score by Feature\n\"\"\"\ntrain.groupby('feature_num')['correct'].mean() \\\n    .plot(kind='hist', bins=50, color='#00BFC4', figsize=(12, 5),\n          title='% of Correct Annotation for Features', edgecolor='black')\nax.set_xlabel('% of Correct Annotations')\nplt.show()\n\"\"\"\n## Whats the least identified feature(s)?\n- There were 2 features that were identified only once out of 100!\n\"\"\"\ntrain.groupby('feature_num')['correct'].mean().sort_values()\ntrain.query('feature_num == 807').head()\ntrain.query('feature_num == 807').loc[\n    train.query('feature_num == 807')['pn_history'].str.lower().str.contains('hallucinations')\n]\nprint(\n    train.query('feature_num == 807').loc[\n    train.query('feature_num == 807')['pn_history'].str.lower().str.contains('hallucinations') &\n    train.query('feature_num == 807')['pn_history'].str.lower().str.contains('ambien')\n]['pn_history'].values[0]\n)\nprint(train.query('feature_num == 209').loc[\n    train.query('feature_num == 209')['pn_history'].str.lower().str.contains('stress')\n]['pn_history']\n     )\nprint(train.query('feature_num == 209').sort_values('correct') \\\n    .query('pn_num == 21054')['pn_history'].values[0])\n\"\"\"\n# Make colored annotations\n\"\"\"\n# import spacy\n# sample_text = train.query('pn_num == 16')['pn_history'].values[0]\n# # vocab = spacy.vocab.Vocab()\n# ?nlp = spacy.load(vocab)\n# doc = nlp(sample_text)\n# spacy.displacy.render(doc, style='ent', manual=True, jupyter=True)","meta":"{'source': 'AI4Code', 'id': 'c9099213cf588d'}"}
{"id":"2035","text":"\"\"\"\n# TMDB with Posters Embeddings (CNN)\nUsing PyTorch 1.0.1.post2\n\"\"\"\n\"\"\"\nThis kernel is more for fun than anything else. I am stuck at 1.98 RMSE & I don't want to scrape the internet for more features. \n\nAt this moment, it is a work in progress (an experiment). But, please, do follow along and if you have any idea on how it could be improved please leave a comment.\n\nI want to see if we can train a CNN to extract poster embeddings which could later be used as addtitionnal features in a gradient boosted tree. I created a dataset with all the posters of the training & test set (well I guess I did actually scrape the internet for more features hehe...)\n\nMy first try was to split the log of the revenue in ten different classes & train a CNN classifier. However, my results were not very satisfying with a final accuracy of about 20%.\n\nTherefore, I decided to combine some important features (determined by feature importance of a decision tree) with the output of a resnet18 (the poster embeddings).\n\nBelow, is the implementation in PyTorch. For now, I only consider the posters & the budget to predict the revenue. I will add more. \n\"\"\"\n\"\"\"\n## Setup\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torchvision.models as models\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, DataLoader\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom tqdm import tqdm_notebook as tqdm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler \nfrom collections import Counter\nimport ast\nimport os \n\n%matplotlib inline\n\nimport pdb\ntorch.__version__\ntorch.cuda.is_available()\n!ls -c ..\/input\/tmdb-box-office-prediction-posters\/tmdb_box_office_prediction_posters\/tmdb_box_office_prediction_posters\nfolder_posters = '..\/input\/tmdb-box-office-prediction-posters\/tmdb_box_office_prediction_posters\/tmdb_box_office_prediction_posters'\n!ls -c ..\/input\/tmdb-box-office-prediction\nfolder_csv = '..\/input\/tmdb-box-office-prediction'\n\"\"\"\n## Data\n\"\"\"\n# coming from an other kernel \n# will add the reference later\ndef clean(df):\n    \n    # Runtime na\n    df.loc[df.id == 1335, 'runtime'] = 119\n    df.loc[df.id == 1336, 'runtime'] = 130\n    df.loc[df.id == 2302, 'runtime'] = 100\n    df.loc[df.id == 2303, 'runtime'] = 81\n    \n    # Runtime 0\n    df.loc[df.id == 391, 'runtime'] = 86\n    df.loc[df.id == 592, 'runtime'] = 90\n    df.loc[df.id == 925, 'runtime'] = 86\n    df.loc[df.id == 978, 'runtime'] = 93\n    df.loc[df.id == 1256, 'runtime'] = 92\n    df.loc[df.id == 1542, 'runtime'] = 93\n    df.loc[df.id == 1875, 'runtime'] = 86\n    df.loc[df.id == 2151, 'runtime'] = 108\n    df.loc[df.id == 2499, 'runtime'] = 86\n    df.loc[df.id == 2646, 'runtime'] = 98\n    df.loc[df.id == 2786, 'runtime'] = 111\n    df.loc[df.id == 2866, 'runtime'] = 96\n    \n    df.loc[df.id == 3829, 'release_date'] = '6\/1\/00'\n    df.loc[df['id'] == 16,'revenue'] = 192864          # Skinning\n    df.loc[df['id'] == 90,'budget'] = 30000000         # Sommersby          \n    df.loc[df['id'] == 118,'budget'] = 60000000        # Wild Hogs\n    df.loc[df['id'] == 149,'budget'] = 18000000        # Beethoven\n    df.loc[df['id'] == 313,'revenue'] = 12000000       # The Cookout \n    df.loc[df['id'] == 451,'revenue'] = 12000000       # Chasing Liberty\n    df.loc[df['id'] == 464,'budget'] = 20000000        # Parenthood\n    df.loc[df['id'] == 470,'budget'] = 13000000        # The Karate Kid, Part II\n    df.loc[df['id'] == 513,'budget'] = 930000          # From Prada to Nada\n    df.loc[df['id'] == 797,'budget'] = 8000000         # Welcome to Dongmakgol\n    df.loc[df['id'] == 819,'budget'] = 90000000        # Alvin and the Chipmunks: The Road Chip\n    df.loc[df['id'] == 850,'budget'] = 90000000        # Modern Times\n    df.loc[df['id'] == 1112,'budget'] = 7500000        # An Officer and a Gentleman\n    df.loc[df['id'] == 1131,'budget'] = 4300000        # Smokey and the Bandit   \n    df.loc[df['id'] == 1359,'budget'] = 10000000       # Stir Crazy \n    df.loc[df['id'] == 1542,'budget'] = 1              # All at Once\n    df.loc[df['id'] == 1542,'budget'] = 15800000       # Crocodile Dundee II\n    df.loc[df['id'] == 1571,'budget'] = 4000000        # Lady and the Tramp\n    df.loc[df['id'] == 1714,'budget'] = 46000000       # The Recruit\n    df.loc[df['id'] == 1721,'budget'] = 17500000       # Cocoon\n    df.loc[df['id'] == 1865,'revenue'] = 25000000      # Scooby-Doo 2: Monsters Unleashed\n    df.loc[df['id'] == 2268,'budget'] = 17500000       # Madea Goes to Jail budget\n    df.loc[df['id'] == 2491,'revenue'] = 6800000       # Never Talk to Strangers\n    df.loc[df['id'] == 2602,'budget'] = 31000000       # Mr. Holland's Opus\n    df.loc[df['id'] == 2612,'budget'] = 15000000       # Field of Dreams\n    df.loc[df['id'] == 2696,'budget'] = 10000000       # Nurse 3-D\n    df.loc[df['id'] == 2801,'budget'] = 10000000       # Fracture\n    df.loc[df['id'] == 3889,'budget'] = 15000000       # Colossal\n    df.loc[df['id'] == 6733,'budget'] = 5000000        # The Big Sick\n    df.loc[df['id'] == 3197,'budget'] = 8000000        # High-Rise\n    df.loc[df['id'] == 6683,'budget'] = 50000000       # The Pink Panther 2\n    df.loc[df['id'] == 5704,'budget'] = 4300000        # French Connection II\n    df.loc[df['id'] == 6109,'budget'] = 281756         # Dogtooth\n    df.loc[df['id'] == 7242,'budget'] = 10000000       # Addams Family Values\n    df.loc[df['id'] == 7021,'budget'] = 17540562       #  Two Is a Family\n    df.loc[df['id'] == 5591,'budget'] = 4000000        # The Orphanage\n    df.loc[df['id'] == 4282,'budget'] = 20000000       # Big Top Pee-wee\n\n    if 'revenue' in df.columns.values:\n        power_six = df.id[df.budget > 1000][df.revenue < 100]\n\n        for k in power_six :\n            df.loc[df['id'] == k,'revenue'] =  df.loc[df['id'] == k,'revenue'] * 1000000\n            \n    return df\ndef get_features_data(df):\n    # work on a copy \n    df = df.copy()\n    \n    # transform json\n    jsons = [\n        'crew', \n        'cast', \n        'Keywords',  \n        'genres', \n        'belongs_to_collection', \n        'production_companies', \n        'production_countries', \n        'spoken_languages'\n    ]\n    for j in jsons: \n        df[j] = df[j].apply(lambda x: {} if pd.isna(x) else ast.literal_eval(x))\n        \n    # release date year \n    release_date = pd.to_datetime(df.release_date, format='%m\/%d\/%y')\n    df['release_date_year'] = release_date.dt.year.apply(lambda x: x-100 if x>2018 else x)\n    df['release_date_month'] = release_date.dt.month\n    df['release_date_day'] = release_date.dt.day\n    df['release_date_quarter'] = release_date.dt.quarter\n    df['release_date_weekday'] = release_date.dt.weekday\n    df['release_date_weekofyear'] = release_date.dt.weekofyear\n    \n    # genres \n    df.genres = df.genres.apply(lambda x: [item['name'] for item in x])\n    df['num_genres'] = df.genres.apply(lambda x: len(x))\n    df.num_genres = df.num_genres.astype('float64')\n    \n    # one hot genre \n    genres = ['Drama', 'Comedy', 'Thriller', 'Action', 'Romance', 'Crime', \n              'Adventure', 'Horror', 'Science Fiction', 'Family', \n              'Fantasy', 'Mystery', 'Animation', 'History', 'Music', 'War', \n              'Documentary', 'Western', 'Foreign']\n    \n    genres_one_hot = np.zeros((len(df.genres),len(genres)))\n    for i in range(len(df)):\n        for j, genre in enumerate(genres):\n            row = df.iloc[i]\n            if genre in row['genres']:\n                genres_one_hot[i,j] = 1 \n                \n    # cast\n    cast = df.cast.apply( lambda x: ','.join([c['name'] for c in x] ))\n    df['size_of_cast'] = cast.apply(lambda x: len(x.split(',')))\n    \n    # crew\n    df['size_of_crew'] =  df['crew'].apply(lambda x: len(x))\n    \n    df['total_crew'] = df['size_of_crew'] + df['size_of_cast']\n                \n    # budget\n    df['log_budget'] = np.log1p(df.budget)\n    df['budget_by_runtime'] = df['budget']\/df['runtime']\n    df['budget_by_popularity'] = df['budget']\/df['popularity']\n    df['release_year_by_popularity'] = df['release_date_year']\/df['popularity']\n    df['popularity_by_release_year'] = df['popularity']\/df['release_date_year']\n\n    # scaled data \n    cols_to_scale = [\n        'release_date_year',\n        'release_date_month',\n        'release_date_day',\n        'release_date_quarter',\n        'release_date_weekday',\n        'release_date_weekofyear',\n        'popularity',\n        'budget', \n        'budget_by_runtime',\n        'budget_by_popularity',\n        'runtime', \n        'num_genres',\n        'log_budget', \n        'release_year_by_popularity', \n        'popularity_by_release_year',\n        'size_of_cast',\n        'size_of_crew'\n    ]\n    # make sure it is float before \n    for col in cols_to_scale:\n         df[col].astype('float64')\n            \n    scaler = StandardScaler()\n    data = scaler.fit_transform(df[cols_to_scale])\n    \n    # add other columns not to be scaled \n    data = np.concatenate([data,genres_one_hot], axis=1)\n    \n    return data, scaler \ndf = pd.read_csv(f\"{os.path.join(folder_csv, 'train.csv')}\")\ndf = clean(df)\ntest, scaler = get_features_data(df)\ntorch.from_numpy(test[0]).float().cuda()\ndf.columns.values\nsample_img_path  = os.path.join(os.path.join(folder_posters, 'train'), f\"{df.iloc[10].id}.jpeg\")\nplt.figure(figsize=(5,5))\nplt.imshow(Image.open(sample_img_path))\nplt.axis('off')\nplt.show()\nclass MovieDataset(Dataset):\n    def __init__(self, csv_file, img_folder, transform=None, idx=None):\n        self.csv_file = csv_file\n        self.img_folder = img_folder \n        self.transform = transform\n        self.df = clean(pd.read_csv(csv_file))\n        # missing poster, will drop data for now \n        self.df.drop(self.df[self.df.id == 2303].index, inplace=True)\n        \n        # create features from dataframe \n        self.data, self.scaler = get_features_data(self.df)\n        self.fs = self.data.shape[1]\n        \n        if idx is not None:\n            self.df = self.df.iloc[idx]\n            \n        self.cols = self.df.columns.values\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, idx): \n        features = torch.from_numpy(self.data[idx,:]).float()\n        img_path = os.path.join(self.img_folder, f\"{self.df.iloc[idx].id}.jpeg\")\n        target = None\n        if 'revenue' in self.cols:\n            target = np.log1p(self.df.iloc[idx].revenue)\n        image = Image.open(img_path)   \n        if self.transform:\n            image = self.transform(image)\n        return {'images': image, 'features': features, 'targets': target}\ndef get_dataset(idx=None):\n    data_transform = transforms.Compose([\n        transforms.Resize((224,224)),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, .456, 0.406], # imagenet normalization\n                             std=[0.229, 0.224, 0.225])\n    ])\n    dataset = MovieDataset(csv_file=f\"{os.path.join(folder_csv, 'train.csv')}\", \n                           img_folder=f\"{os.path.join(folder_posters, 'train')}\", \n                           transform=data_transform, \n                           idx=idx)\n    return dataset\nidx = [i for i in range(len(df)-1)]\nidx = np.random.permutation(idx)\ntrain_idx = idx[:round(0.9*(len(idx)))]\nvalid_idx = idx[round(0.9*(len(idx))):]\nlen(valid_idx) \/ (len(valid_idx) + len(train_idx))\ntrain_dataset = get_dataset(idx=train_idx)\nvalid_dataset = get_dataset(idx=valid_idx)\nlen(valid_dataset) \/ (len(train_dataset) + len(valid_dataset))\ntrain_dataset.fs\n\"\"\"\nPrint some images and associated revenue from the MovieDataset.\n\"\"\"\ndataloader = DataLoader(get_dataset(), batch_size=4, shuffle=True, num_workers=4)\nfor _, sample_batch in enumerate(dataloader):\n    image = sample_batch['images']\n    revenue = sample_batch['targets']\n    batch_size = image.shape[0]\n    fig = plt.figure(figsize=(20,20))\n    for i in range(batch_size):\n        ax = plt.subplot(1, batch_size, i + 1)\n        plt.tight_layout()\n        data = image[i].cpu().numpy().transpose((1, 2, 0))\n        plt.imshow(np.interp(data, (data.min(), data.max()), (0, 1)))\n        ax.axis('off')\n        ax.set_title(f\"Sample {i+1}, Revenue: {revenue[i]:.2f}\")\n    plt.show()\n    break\n\"\"\"\n## Model\n\"\"\"\nclass WithPosterEmbeddings(nn.Module):\n    \n    def __init__(self, features_size, dp=0.5):\n        super().__init__()\n        self.dp = dp\n        self.img_emb_size = 10 # change image embedding size \n        self.features_size = features_size\n        \n        self.resnet18 = models.resnet18(pretrained=True)\n        # freeze all layers\n        for param in self.resnet18.parameters():\n            param.requires_grad = False\n            \n        #bs, drp, linear, relu   \n        self.resnet18.fc = nn.Sequential(\n            nn.BatchNorm1d(512),\n            nn.Dropout(self.dp),\n            nn.Linear(512, 1000, bias=True),\n            nn.ReLU(),\n            nn.BatchNorm1d(1000),\n            nn.Dropout(self.dp),\n            nn.Linear(1000, self.img_emb_size, bias=True),\n            nn.ReLU(),\n            nn.Dropout(self.dp) # dropout on the poster embeddings\n        )\n        \n        self.l1 = nn.Sequential(\n            nn.BatchNorm1d(self.img_emb_size + self.features_size), \n            nn.Linear(self.img_emb_size + self.features_size,512), \n            nn.ReLU()\n        )\n        \n        self.l2 = nn.Sequential(\n            nn.BatchNorm1d(512),\n            nn.Dropout(self.dp),\n            nn.Linear(512,256),\n            nn.ReLU(),\n            nn.BatchNorm1d(256),\n            nn.Dropout(self.dp),\n            nn.Linear(256,1) \n        )\n        \n    \"\"\" imgs: posters\n        x: features\n    \"\"\"\n    def forward(self, imgs, features, skip_cnn=False):\n        x = self.resnet18(imgs)\n        if skip_cnn: \n            x = torch.zeros(imgs.size(0),self.img_emb_size).float().cuda()\n        x = torch.cat([x, features], dim=1)\n        x = self.l2(self.l1(x))\n        \n        return x\n\"\"\"\n## Train\n\"\"\"\nfs = 36 # feature size\n\nepochs =  50\nwd = 0.001\nlr = 1e-3\ndropout=0.5\nbs = 8\ndef calculate_rmse(model, dataloader, monitor=False, skip_cnn=False):\n    criterion = nn.MSELoss()\n    model.eval()\n    losses = []\n    for sample_batch in tqdm(dataloader, disable=(not monitor)):\n        images = sample_batch['images'].cuda()\n        features = sample_batch['features'].cuda()\n        targets = sample_batch['targets'].float().cuda()\n        \n        preds = model(images, features, skip_cnn=skip_cnn)\n        loss = criterion(preds,targets)\n        \n        losses.append( loss.item() * len(sample_batch))\n        \n    # set the model to train mode\n    model.train()\n    return np.sqrt(np.mean(losses))\n\"\"\"\n```\nmodel = WithPosterEmbeddings(features_size = fs).cuda()\ndataloader_train = DataLoader(get_dataset(idx=train_idx), batch_size=bs, shuffle=True, num_workers=4)\ndataloader_iter = iter(dataloader_train)\nsample_batch = next(dataloader_iter)\nimages = sample_batch['images'].cuda()\nfeatures = sample_batch['features'].cuda()\ntargets = sample_batch['targets'].float().cuda()\n```\n\"\"\"\n# model & dataloader\nmodel = WithPosterEmbeddings(features_size = fs, dp=dropout).cuda()\ndataloader_train = DataLoader(get_dataset(idx=train_idx), batch_size=bs, shuffle=True, num_workers=4)\ndataloader_valid = DataLoader(get_dataset(idx=valid_idx), batch_size=bs, shuffle=True, num_workers=4)\n\ncriterion = nn.MSELoss()\nopt = optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\nlr_sch = lr_scheduler.ReduceLROnPlateau(opt,'min', factor=0.1, patience=10, verbose=True) # learning rate scheduler \n\ni = 0\nrunning_losses = []\ntrain_losses = []\nvalid_losses = []\nfor epoch_i in range(epochs):\n    print(f\"Epoch {epoch_i+1}\/{epochs}\")\n    running_loss = 0\n    for sample_batch in tqdm(dataloader_train):\n        images = sample_batch['images'].cuda()\n        features = sample_batch['features'].cuda()\n        targets = sample_batch['targets'].float().cuda()\n        \n        preds = model(images, features)\n        loss = criterion(preds,targets.unsqueeze(1))\n        opt.zero_grad()\n        loss.backward()\n        opt.step()\n        \n        running_losses.append((i, loss.item() ))\n        i+=1\n        \n    print('Calculating validation loss..')\n    valid_losses.append((i, calculate_rmse(model, dataloader_valid)))\n    lr_sch.step(valid_losses[-1][1])\n    \n    print('Calculating train loss..')\n    train_losses.append((i, calculate_rmse(model, dataloader_train)))\n        \n    print(f\"Loss: {train_losses[-1][1]:.3f} (train) {valid_losses[-1][1]:.3f} (valid)\")\n\"\"\"\n* Loss: 2.939 (train) 4.986 (valid)\n\"\"\"\n\"\"\"\nPlot losses\n\"\"\"\ndef plot_rmse(train_losses, valid_losses):\n    plt.figure(figsize=(10,10))\n    plt.xlabel('Iteration #')\n    plt.ylabel('RMSE loss')\n    \n    it, loss = zip(*train_losses)\n    plt.plot(it, loss, marker='o')\n    \n    it, loss = zip(*valid_losses)\n    plt.plot(it, loss, marker='o')\n    \n    plt.show()\nplot_rmse(train_losses, valid_losses)\n\"\"\"\nTo verify if the poster embeddings did learn some features, I will calculate the RMSE with & without the embeddings on the validation set. \n\"\"\"\nno_poster = calculate_rmse(model, dataloader_valid, skip_cnn=True)\nwith_poster = calculate_rmse(model, dataloader_valid, skip_cnn=False)\nprint(f\"Loss: {with_poster:.3f} (poster) {no_poster:.3f} (no poster)\")\n\"\"\"\nSo, for now, the embeddings are making things actually worst (yeah! :P)\n\nThings I want to try:\n- Data augmentation on the posters\n- Adding more features. For now I only have the budget. Add more, maybe it will help the cnn part to learn embeddings.\n- After a first training phase, freeze the features layers & train only the cnn part. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '03e3f2fa3c160d'}"}
{"id":"126043","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import Ridge\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GridSearchCV\nnp.set_printoptions(suppress=True)\ndata = pd.read_csv('..\/input\/gapminder.csv')\ndata.dtypes\ndata.head(5)\ndata = data.drop(['Region'], axis =1)\ndata.isnull().sum()\nX = data.drop(['life'], axis = 1)\ny = data.life\nX.head()\ny.head()\nTraining_Accuracy_Before = []\nTesting_Accuracy_Before = []\nTraining_Accuracy_After = []\nTesting_Accuracy_After = []\nModels = ['Linear Regression', 'Lasso Regression', 'Ridge Regression']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)\nlogreg = LinearRegression()\nlogreg.fit(X_train, y_train)\n\ntrain_score = logreg.score(X_train, y_train)\nprint(train_score)\ntest_score = logreg.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_Before.append(train_score)\nTesting_Accuracy_Before.append(test_score)\nalpha_space = np.logspace(-4, 0, 30)   # Checking for alpha from .0001 to 1 and finding the best value for alpha\nalpha_space\nridge_scores = []\nridge = Ridge(normalize = True)\nfor alpha in alpha_space:\n    ridge.alpha = alpha\n    val = np.mean(cross_val_score(ridge, X, y, cv = 10))\n    ridge_scores.append(val)\nlasso_scores = []\nlasso = Lasso(normalize = True)\nfor alpha in alpha_space:\n    lasso.alpha = alpha\n    val = np.mean(cross_val_score(lasso, X, y, cv = 10))\n    lasso_scores.append(val)\nplt.figure(figsize=(8, 8))\nplt.plot(alpha_space, ridge_scores, marker = 'D', label = \"Ridge\")\nplt.plot(alpha_space, lasso_scores, marker = 'D', label = \"Lasso\")\nplt.legend()\nplt.show()\n\"\"\"\nThrough above graph, we can see that accuracy reduces as value for alpha increases. But best value of alpha can be occupied using GridSearchCV with Cross Validation technique. As, in above chart, CV was not performed, hence we can't have confidence in what we are seeing.\n\"\"\"\n# Performing GridSearchCV with Cross Validation technique on Lasso Regression and finding the optimum value of alpha\n\nparams = {'alpha': (np.logspace(-8, 8, 100))} # It will check from 1e-08 to 1e+08\nlasso = Lasso(normalize=True)\nlasso_model = GridSearchCV(lasso, params, cv = 10)\nlasso_model.fit(X_train, y_train)\nprint(lasso_model.best_params_)\nprint(lasso_model.best_score_)\n# Using value of alpha as 0.0000171 to get best accuracy for Lasso Regression\nlasso = Lasso(alpha = 0.0000171, normalize = True)\nlasso.fit(X_train, y_train)\n\ntrain_score = lasso.score(X_train, y_train)\nprint(train_score)\ntest_score = lasso.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_Before.append(train_score)\nTesting_Accuracy_Before.append(test_score)\n# Performing GridSearchCV with Cross Validation technique on Ridge Regression and finding the optimum value of alpha\n\nparams = {'alpha': (np.logspace(-8, 8, 100))} # It will check from 1e-08 to 1e+08\nridge = Ridge(normalize=True)\nridge_model = GridSearchCV(ridge, params, cv = 10)\nridge_model.fit(X_train, y_train)\nprint(ridge_model.best_params_)\nprint(ridge_model.best_score_)\n# Using value of alpha as 0.020092 to get best accuracy for Ridge Regression\nridge = Ridge(alpha = 0.020092, normalize = True)\nridge.fit(X_train, y_train)\n\ntrain_score = ridge.score(X_train, y_train)\nprint(train_score)\ntest_score = ridge.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_Before.append(train_score)\nTesting_Accuracy_Before.append(test_score)\ncoefficients = lasso.coef_\ncoefficients\nplt.figure(figsize = (10, 6))\nplt.plot(range(len(X_train.columns)), coefficients)\nplt.xticks(range(len(X_train.columns)), X_train.columns.values, rotation = 90)\nplt.show()\nX_train.columns\n\"\"\"\nAfter looking at above features, we get to know that prevalent features are:\n    'fertility', 'HIV', 'CO2', 'BMI_male', 'GDP', 'BMI_female', 'child_mortality'\n\"\"\"\nX = data[['fertility', 'HIV', 'CO2', 'BMI_male', 'GDP', 'BMI_female', 'child_mortality']]\ny = data.life\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)\nlogreg = LinearRegression()\nlogreg.fit(X_train, y_train)\n\ntrain_score = logreg.score(X_train, y_train)\nprint(train_score)\ntest_score = logreg.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_After.append(train_score)\nTesting_Accuracy_After.append(test_score)\n# Performing GridSearchCV with Cross Validation technique on Lasso Regression and finding the optimum value of alpha\n\nparams = {'alpha': (np.logspace(-8, 8, 100))} # It will check from 1e-08 to 1e+08\nlasso = Lasso(normalize=True)\nlasso_model = GridSearchCV(lasso, params, cv = 10)\nlasso_model.fit(X_train, y_train)\nprint(lasso_model.best_params_)\nprint(lasso_model.best_score_)\n# Using value of alpha as 0.000705 to get best accuracy for Lasso Regression\nlasso = Lasso(alpha = 0.000705, normalize = True)\nlasso.fit(X_train, y_train)\n\ntrain_score = lasso.score(X_train, y_train)\nprint(train_score)\ntest_score = lasso.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_After.append(train_score)\nTesting_Accuracy_After.append(test_score)\n# Performing GridSearchCV with Cross Validation technique on Ridge Regression and finding the optimum value of alpha\n\nparams = {'alpha': (np.logspace(-8, 8, 100))} # It will check from 1e-08 to 1e+08\nridge = Ridge(normalize=True)\nridge_model = GridSearchCV(ridge, params, cv = 10)\nridge_model.fit(X_train, y_train)\nprint(ridge_model.best_params_)\nprint(ridge_model.best_score_)\n# Using value of alpha as 0.020092 to get best accuracy for Ridge Regression\nridge = Ridge(alpha = 0.020092, normalize = True)\nridge.fit(X_train, y_train)\n\ntrain_score = ridge.score(X_train, y_train)\nprint(train_score)\ntest_score = ridge.score(X_test, y_test)\nprint(test_score)\n\nTraining_Accuracy_After.append(train_score)\nTesting_Accuracy_After.append(test_score)\nplt.plot(Training_Accuracy_Before, label = 'Training_Accuracy_Before')\nplt.plot(Training_Accuracy_After, label = 'Training_Accuracy_After')\nplt.xticks(range(len(Models)), Models, Rotation = 45)\nplt.title('Training Accuracy Behaviour')\nplt.legend()\nplt.show()\nplt.plot(Testing_Accuracy_Before, label = 'Testing_Accuracy_Before')\nplt.plot(Testing_Accuracy_After, label = 'Testing_Accuracy_After')\nplt.xticks(range(len(Models)), Models, Rotation = 45)\nplt.title('Testing Accuracy Behaviour')\nplt.legend()\nplt.show()\n\"\"\"\n**Observations:**  \n  \n  Above charts clearly shows that:  \n    \n    1. Linear Regression did the highest overfitting during its training phase and hence performed worst on test set  \n    2. Ridge didn't overfit the training data much during its training phase, and hence performed good on test set  \n    3. Post ignoring irrelevant feature with the help of  Lasso regression, we fitted the models, and Ridge performed well  \n    4. Moreover, after removal of irrelevant feature:  \n                a) 'Training_Accuracy_After' less overfitted the training data and hence its line curve is lower that 'Testing_Accuracy_Before' (Can be seen in first chart)  \n                b) 'Testing_Accuracy_After' better predicted the testing data and hence its line curve is greater than 'Testing_Accuracy_Before' (Can be seen in Second chart)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e7cbd73a3d176e'}"}
{"id":"55289","text":"\"\"\"\n# Compound Polarity Analysis with vaderSentiment - Financial News Sentiment - Clustering\n\"\"\"\n\"\"\"\nSimilar to part 3.2, this notebook utilizes clustering method, an unsupervised learning method of grouping data, to put each article into their respective group of sentiment.\n\"\"\"\n\"\"\"\n## Import data\n\"\"\"\nfrom part1_cleaning import get_clean_data\nfrom part4_vaderdata import get_vader_data\ndf1, df2, df3 = get_clean_data()\nvader_df1, vader_df2, vader_df3 = get_vader_data(df1, df2, df3)\n\"\"\"\n## CNBC data\n\"\"\"\n\"\"\"\nFor CNBC dataset, I use the 2 most popular clustering algorithms, K-Means Clustering and Hierarchical clustering, to categorized the sentiments of CNBC articles.\n\"\"\"\nfrom sklearn.cluster import KMeans\nX = vader_df1.iloc[:, -2:].values\nkmeans = KMeans(n_clusters = 3, init = 'k-means++', random_state = 0)\ny_kmeans = kmeans.fit_predict(X)\nimport matplotlib.pyplot as plt\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 20, c = 'red', label = 'C1')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 20, c = 'blue', label = 'C2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 20, c = 'green', label = 'C3')\nfrom sklearn.cluster import AgglomerativeClustering\nhc3 = AgglomerativeClustering(n_clusters = 3, affinity = 'euclidean', linkage = 'ward')\ny_hc3 = hc3.fit_predict(X)\nplt.scatter(X[y_hc3 == 0, 0], X[y_hc3 == 0, 1], s = 20, c = 'red', label = 'C1')\nplt.scatter(X[y_hc3 == 1, 0], X[y_hc3 == 1, 1], s = 20, c = 'blue', label = 'C2')\nplt.scatter(X[y_hc3 == 2, 0], X[y_hc3 == 2, 1], s = 20, c = 'green', label = 'C3')\n\"\"\"\nAssessing both K-Means and Hierarchical clusters, I can see 2 different ways these clustering algorithm group given data points. In order to minimize the amount of neutral sentiments, I decided to go with Hierarchical Clustering for this data since it creates significantly less neutral sentiments\n\"\"\"\n\"\"\"\nFrom the scatter plot, I can conclude that data points colored in red (y=0) represent positive sentiment, data points colored in blue (y=1) represent negative sentiment, and data points colored in green (y=2) represent a mixed sentiment, in which I will assign as neutral.\n\"\"\"\nc_sentiments = [2 if y == 0 else 1 if y == 1 else 0 for y in y_hc3]\nc_sentiments[0:10]\n\"\"\"\n# Reuters data\n\"\"\"\nX = vader_df2.iloc[:, -2:].values\nkmeans = KMeans(n_clusters = 3, init = 'k-means++', random_state = 1)\ny_kmeans = kmeans.fit_predict(X)\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 20, c = 'red', label = 'C1')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 20, c = 'blue', label = 'C2')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 20, c = 'green', label = 'C3')\nhc3 = AgglomerativeClustering(n_clusters = 3, affinity = 'euclidean', linkage = 'ward')\ny_hc3 = hc3.fit_predict(X)\nplt.scatter(X[y_hc3 == 0, 0], X[y_hc3 == 0, 1], s = 20, c = 'red', label = 'C1')\nplt.scatter(X[y_hc3 == 1, 0], X[y_hc3 == 1, 1], s = 20, c = 'blue', label = 'C2')\nplt.scatter(X[y_hc3 == 2, 0], X[y_hc3 == 2, 1], s = 20, c = 'green', label = 'C3')\n\"\"\"\nAgain, for this dataset, both K-Means and Hierarchical clusters create a different way of grouping given data points. Knowing that the y-axis contains the preview of the article, it is possible that many articles have negative headlines, but carry positive information about the financial world nonetheless. Coupled with the effort to minimize the amount of neutral sentiments, I decided to go with K-Means Clustering for this data since it creates significantly less neutral sentiments\n\"\"\"\n\"\"\"\nFrom the scatter plot, I can conclude that data points colored in blue (y=1) represent positive sentiment, data points colored in red (y=0) represent negative sentiment, and data points colored in green (y=2) represent a mixed sentiment, in which I will assign as neutral.\n\"\"\"\n# reassign the values, which 2, 1, 0 being a positive sentiment, neutral sentiment, and negative sentiment, respectively\nr_sentiments = [2 if y == 1 else 1 if y == 2 else 0 for y in y_kmeans]\nr_sentiments[0:10]\n\"\"\"\n# The Guardian data\n\"\"\"\n\"\"\"\nSimilar to part 3.2, instead of applying a clustering model, I apply a Natural Breaks Optimization to this dataset, specifically Jenks Natural Breaks.\n\"\"\"\n!pip install jenkspy\nimport jenkspy\nX = vader_df3.iloc[:, -1].values\nbreaks = jenkspy.jenks_breaks(X, nb_class=3)\nplt.hist(X, bins = 50)\nfor b in breaks:\n    plt.vlines(b, ymin=0, ymax=11000)\nbreaks\n\"\"\"\nFrom the histogram, I can conclude that data points with sentiments below -0.2158 represent negative sentiment, data points with sentiments above 0.2584 represent positive sentiment, and data points with sentiments in between those 2 values represent neutral sentiment\n\"\"\"\ng_sentiments = [0 if x <= breaks[1] else 2 if x >= breaks[2] else 1 for x in X]\ng_sentiments[0:10]","meta":"{'source': 'AI4Code', 'id': '65e7a558b9a270'}"}
{"id":"45302","text":"\n# Load various imports \nimport pandas as pd\nimport numpy as np\nimport os\nimport librosa\nimport glob \nimport numpy as np\nimport skimage\nimport librosa.display\nimport IPython.display as ipd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense, MaxPool2D, Dropout\nfrom tensorflow.keras.utils import to_categorical \n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nimport pandas as pd\nmetadata = pd.read_csv('UrbanSound8K.csv')\nmetadata.head()\nmetadata[metadata['class']=='street_music'][['slice_file_name','fold']].iloc[0,:]\nprint(metadata['class'].value_counts())\ndef plot_spectrogram(signal, name):\n    \"\"\"Compute power spectrogram with Short-Time Fourier Transform and plot result.\"\"\"\n    spectrogram = librosa.amplitude_to_db(librosa.stft(signal))\n    plt.figure(figsize=(25, 8))\n    librosa.display.specshow(spectrogram, y_axis=\"log\")\n    plt.colorbar(format=\"%+2.0f dB\")\n    plt.title(f\"Log-frequency power spectrogram for {name}\")\n    plt.xlabel(\"Time\")\n    plt.show()\nstreet_music_file = metadata[metadata['class']=='street_music'][['slice_file_name','fold']].iloc[0,:]\ndrilling_file = metadata[metadata['class']=='drilling'][['slice_file_name','fold']].iloc[0,:]\nengine_idling_file = metadata[metadata['class']=='engine_idling'][['slice_file_name','fold']].iloc[0,:]\nchildren_playing_file = metadata[metadata['class']=='children_playing'][['slice_file_name','fold']].iloc[0,:]\ndog_bark_file = metadata[metadata['class']=='dog_bark'][['slice_file_name','fold']].iloc[0,:]\njackhammer_file = metadata[metadata['class']=='jackhammer'][['slice_file_name','fold']].iloc[0,:]\nair_conditioner_file = metadata[metadata['class']=='air_conditioner'][['slice_file_name','fold']].iloc[0,:]\nsiren_file = metadata[metadata['class']=='siren'][['slice_file_name','fold']].iloc[0,:]\ncar_horn_file = metadata[metadata['class']=='car_horn'][['slice_file_name','fold']].iloc[0,:]\ngun_shot_file = metadata[metadata['class']=='gun_shot'][['slice_file_name','fold']].iloc[0,:]\n# load sounds\nmusic, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(street_music_file[1])+'\/',str(street_music_file[0])))\ndrilling, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(drilling_file[1])+'\/',str(drilling_file[0])))\nengine_idling, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(engine_idling_file[1])+'\/',str(engine_idling_file[0])))\nchildren_playing, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(children_playing_file[1])+'\/',str(children_playing_file[0])))\ndog_bark, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(dog_bark_file[1])+'\/',str(dog_bark_file[0])))\njackhammer, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(jackhammer_file[1])+'\/',str(jackhammer_file[0])))\nair_conditioner, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(air_conditioner_file[1])+'\/',str(air_conditioner_file[0])))\nsiren, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(siren_file[1])+'\/',str(siren_file[0])))\ncar_horn, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(car_horn_file[1])+'\/',str(car_horn_file[0])))\ngun_shot, _ = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(gun_shot_file[1])+'\/',str(gun_shot_file[0])))\n# Street Music\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(street_music_file[1])+'\/',str(street_music_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(street_music_file[1])+'\/',str(street_music_file[0])))\nplot_spectrogram(music, \"music\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(street_music_file[1])+'\/',str(street_music_file[0])))\n# Drilling\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(drilling_file[1])+'\/',str(drilling_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(drilling_file[1])+'\/',str(drilling_file[0])))\nplot_spectrogram(drilling, \"drilling\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(drilling_file[1])+'\/',str(drilling_file[0])))\n# Enngine Idling\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(engine_idling_file[1])+'\/',str(engine_idling_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(engine_idling_file[1])+'\/',str(engine_idling_file[0])))\nplot_spectrogram(engine_idling, \"engine_idling\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(engine_idling_file[1])+'\/',str(engine_idling_file[0])))\n# Children Playing\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(children_playing_file[1])+'\/',str(children_playing_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(children_playing_file[1])+'\/',str(children_playing_file[0])))\nplot_spectrogram(children_playing, \"children_playing\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(children_playing_file[1])+'\/',str(children_playing_file[0])))\n# Dog Barking\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(dog_bark_file[1])+'\/',str(dog_bark_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(dog_bark_file[1])+'\/',str(dog_bark_file[0])))\nplot_spectrogram(dog_bark, \"dog_barking\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(dog_bark_file[1])+'\/',str(dog_bark_file[0])))\n# Jackhammer\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(jackhammer_file[1])+'\/',str(jackhammer_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(jackhammer_file[1])+'\/',str(jackhammer_file[0])))\nplot_spectrogram(jackhammer, \"jackhammer\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(jackhammer_file[1])+'\/',str(jackhammer_file[0])))\n# Air Conditioner\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(air_conditioner_file[1])+'\/',str(air_conditioner_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(air_conditioner_file[1])+'\/',str(air_conditioner_file[0])))\nplot_spectrogram(air_conditioner, \"airconditioner\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(air_conditioner_file[1])+'\/',str(air_conditioner_file[0])))\n# Siren\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(siren_file[1])+'\/',str(siren_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(siren_file[1])+'\/',str(siren_file[0])))\nplot_spectrogram(siren, \"siren\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(siren_file[1])+'\/',str(siren_file[0])))\n# Car_Horn\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(car_horn_file[1])+'\/',str(car_horn_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(car_horn_file[1])+'\/',str(car_horn_file[0])))\nplot_spectrogram(car_horn, \"car_horn\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(car_horn_file[1])+'\/',str(car_horn_file[0])))\n# Gun_Shot\n\ndata,sample_rate = librosa.load(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(gun_shot_file[1])+'\/',str(gun_shot_file[0])))\n_ = librosa.display.waveplot(data,sr=sample_rate)\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(gun_shot_file[1])+'\/',str(gun_shot_file[0])))\nplot_spectrogram(gun_shot, \"gun_shot\")\nipd.Audio(os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(gun_shot_file[1])+'\/',str(gun_shot_file[0])))\ndef extract_features(file_name):\n   \n    try:\n        audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast') \n        mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)\n        mfccsscaled = np.mean(mfccs.T,axis=0)\n        \n    except Exception as e:\n        print(\"Error encountered while parsing file: \", file_name)\n        return None \n     \n    return mfccsscaled\n# Set the path to the full UrbanSound dataset \nfulldatasetpath = '\/home\/ubuntu\/deep_learning\/folder'\n\nmetadata = pd.read_csv(fulldatasetpath + '\/UrbanSound8K.csv')\n\nfeatures = []\n\n# Iterate through each sound file and extract the features \nfor index, row in metadata.iterrows():\n    \n    file_name = os.path.abspath('folder\/')+'\/'+os.path.join('fold'+str(row[\"fold\"])+'\/',str(row[\"slice_file_name\"]))\n    \n    class_label = row[\"class\"]\n    data = extract_features(file_name)\n    \n    features.append([data, class_label])\n\n# Convert into a Panda dataframe \nfeaturesdf = pd.DataFrame(features, columns=['feature','class_label'])\n\nprint('Finished feature extraction from ', len(featuresdf), ' files')\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import to_categorical\n\n# Convert features and corresponding classification labels into numpy arrays\nX = np.array(featuresdf.feature.tolist())\ny = np.array(featuresdf.class_label.tolist())\n\n# Encode the classification labels\nle = LabelEncoder()\nyy = to_categorical(le.fit_transform(y)) \n\n# split the dataset \nfrom sklearn.model_selection import train_test_split \n\nx_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=0.2, random_state = 42)\nx_test.shape\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.optimizers import Adam\nfrom keras.utils import np_utils\nfrom sklearn import metrics \n\nnum_rows = 40\nnum_columns = 174\nnum_channels = 1\n\n#x_train = x_train.reshape(x_train.shape[0], num_rows, num_columns, num_channels)\n#x_test = x_test.reshape(x_test.shape[0], num_rows, num_columns, num_channels)\n\nnum_labels = yy.shape[1]\nfilter_size = 2\n\n\n# Construct model \nmodel = Sequential()\n\nmodel.add(Dense(256, input_shape=(40,)))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(256))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(num_labels))\nmodel.add(Activation('softmax'))\n# Compile the model\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n\n# Display model architecture summary \nmodel.summary()\n\n\nfrom keras.callbacks import ModelCheckpoint \nfrom datetime import datetime \n\nnum_epochs = 145\nnum_batch_size = 32\n\ncheckpointer = ModelCheckpoint(filepath='models\/weights.best.basic_cnn.hdf5', \n                               verbose=1, save_best_only=True)\nstart = datetime.now()\n\nhistory =  model.fit(x_train, y_train, batch_size=num_batch_size,epochs=145, validation_data=(x_test, y_test), callbacks=[checkpointer], verbose=1)\n\n\nduration = datetime.now() - start\nprint(\"Training completed in time: \", duration)\n# Evaluating the model on the training and testing set\nscore = model.evaluate(x_train, y_train, verbose=0)\nprint(\"Training Accuracy: \", score[1])\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Testing Accuracy: \", score[1])\n\"\"\"\n# validation\n\"\"\"\nimport librosa \nimport numpy as np \n\ndef extract_feature(file_name):\n   \n    try:\n        audio_data, sample_rate = librosa.load(file_name, res_type='kaiser_fast') \n        mfccs = librosa.feature.mfcc(y=audio_data, sr=sample_rate, n_mfcc=40)\n        mfccsscaled = np.mean(mfccs.T,axis=0)\n        \n    except Exception as e:\n        print(\"Error encountered while parsing file: \", file)\n        return None, None\n\n    return np.array([mfccsscaled])\ndef print_prediction(file_name):\n    prediction_feature = extract_feature(file_name) \n\n    predicted_vector = model.predict_classes(prediction_feature)\n    predicted_class = le.inverse_transform(predicted_vector) \n    print(\"The predicted class is:\", predicted_class[0], '\\n') \n\n    predicted_proba_vector = model.predict_proba(prediction_feature) \n    predicted_proba = predicted_proba_vector[0]\n    for i in range(len(predicted_proba)): \n        category = le.inverse_transform(np.array([i]))\n        print(category[0], \"\\t\\t : \", format(predicted_proba[i], '.32f') )\n# Class: Air Conditioner\n\nfilename = 'folder'+'\/'+os.path.join('fold'+str(street_music_file[1])+'\/'+str(street_music_file[0]))\n\nprint_prediction(filename)\n\"\"\"\n# Performance\n\"\"\"\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\nfrom sklearn.metrics import confusion_matrix, plot_confusion_matrix, classification_report\nimport seaborn as sns\ny_pred = model.predict(x_test)\n\nmatrix = confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\nplt.figure(figsize=(10,8))\nsns.heatmap(matrix, annot=True, cmap='Blues')\nplt.figure(figsize=(10,8))\nsns.heatmap(matrix\/np.sum(matrix), annot=True, \n            fmt='.2%', cmap='Blues')\nprint('Classification Report')\ntarget_names = list(le.classes_)\nprint(classification_report(y_test.argmax(axis=1), y_pred.argmax(axis=1), target_names=target_names))","meta":"{'source': 'AI4Code', 'id': '53764307c9518f'}"}
{"id":"33065","text":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\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# Introduction\n\"\"\"\n\"\"\"\nI'm intending this to be the first notebook of two working with this data. This notebook will be focused on exploratory analysis and visualization and the second will be about making predictive models.\n\"\"\"\n\"\"\"\n## Loading Data, Dealing with Missing Data, and Managing Column Names\n\"\"\"\ndata = pd.read_csv(\"\/kaggle\/input\/indian-liver-patient-records\/indian_liver_patient.csv\")\ndata.info()\n\"\"\"\nThere's 4 missing values in the Albumin and Globulin Ratio. It could be a useful predictor so it might be worthwhile to try estimating its value based on the mean of the most similar entries in the dataframe. Worst case, the data can be dropped as it's a small enough number it shouldn't affect the dataset one way or another.\n\"\"\"\nmissing = data[data.Albumin_and_Globulin_Ratio.isna()]\n\nfor index, row in missing.iterrows():\n    age, disease, gender = row[\"Age\"], row[\"Dataset\"], row[\"Gender\"]\n    new_table = data[(data[\"Age\"] == age) & (data[\"Gender\"] == gender) & (data[\"Dataset\"] == disease)]\n    print(age, disease, gender, new_table[\"Albumin_and_Globulin_Ratio\"].mean())\n    data.set_value(index, \"Albumin_and_Globulin_Ratio\", new_table[\"Albumin_and_Globulin_Ratio\"].mean())\ndata.info()\n\"\"\"\nI'm happy with the imputing for the missing values. The people with liver disease have slightly reduced ratios which would fit some possible impairment of Albumin synthesis by the liver while the people without liver disease have AGRs above 1\n\"\"\"\ndata.columns\ndata = data.rename(columns = {\"Alkaline_Phosphotase\": \"ALP\", \"Alamine_Aminotransferase\": \"ALT\", \"Aspartate_Aminotransferase\": \"AST\", \"Total_Protiens\":\"Protein\", \"Albumin_and_Globulin_Ratio\": \"AGR\", \"Dataset\": \"Liver Patient\"})\n\ndata[\"Liver Patient\"].replace(2, 0, inplace = True)\n\"\"\"\nRenaming extremely long column names to their common abbreviations; changing Dataset variable to Liver Patient so it's not confusing as well as all 2s to 0s.\n\nPreviously a 1 meant liver patient and a 2 meant a non-liver patient; currently 0 means a non-liver patient and 1 means a liver patient.\n\nAlso for reference, ALP, AST, and ALT together may be called Liver Function Tests or LFTs for short. This is common medical shorthand, and will be used in this notebook.\n\"\"\"\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\n\"\"\"\n## Count Plots\n\"\"\"\nf, axes = plt.subplots(1, 2, figsize = (10, 5))\nf.tight_layout(pad = 5)\nsns.countplot(data = data, x = \"Gender\", ax = axes[0])\nsns.countplot(data = data, x = \"Liver Patient\", ax = axes[1])\n\"\"\"\nIt's worth noting that this dataset is unbalanced in both Gender and Liver Patient status; there are considerably more men and liver patients than women and non-liver patients. It's not necessarily a problem in this case but extra caution will be required when building predictive models.\n\"\"\"\n\"\"\"\n## Pivot Tables\n\"\"\"\npd.pivot_table(data, index = \"Liver Patient\")\n\"\"\"\nThe pivot table shows mostly what's to be expected when you compare a population of liver patients with non-liver patients. Higher bilirubin levels; higher LFTs (ALT, ALP, AST); and lower Albumin and AGR levels in liver patients which is consistent with liver damage.\n\"\"\"\npd.pivot_table(data[[col for col in data.columns if col != \"Liver Patient\"]], index = \"Gender\")\n\"\"\"\nMen tend to have higher values for ALT, and AST. They also seem to have slightly lower Albumin and Protein levels as well. Bilirubin levels are much higher in men.\n\"\"\"\npd.pivot_table(data, index = [\"Liver Patient\", \"Gender\"])\n\"\"\"\nWhen combining Gender and Liver Patient status into a pivot table, a few things change. The higher ALP levels in women from the previous pivot table appears to come from the women who happen to be liver patients. Of those that aren't liver patients, men have higher ALP levels. In similar fashion, the higher Albumin and Protein numbers in women appears to be explained by the liver patients. Men still have higher ALT, AST, and Bilirubin but these differences are more pronounced in liver patients.\n\"\"\"\n\"\"\"\n## Dealing with Outliers\n\"\"\"\ndata.describe()\n\"\"\"\nMany of the liver metrics have gigantic jumps from the 75th percentile value to the max value, and this is to be expected as you'll occasionally have patients with extremely high lab values. In this case, these values are likely to severely compress graphs when running data through matplotlib and seaborn, so I'll be working on removing the high values. There's no reason to worry about abnormally low values because 0 is the lowest anything can be.\n\"\"\"\noutliers = data[[\"Total_Bilirubin\", \"Direct_Bilirubin\", \"ALP\", \"ALT\", \"AST\", \"Protein\", \"Albumin\", \"AGR\"]].copy()\nindex = outliers[(np.abs(stats.zscore(outliers)) < 2.5).all(axis = 1)].index\nindex2 = outliers[(np.abs(stats.zscore(outliers)) < 2).all(axis = 1)].index\n\noutliers_25z = data.iloc[index, ].copy()\noutliers_2z = data.iloc[index2, ].copy()\n\"\"\"\nI've made two sets filtering outliers; one set is within a z-score of 2.5 and the other is within a z-score of 2.\n\"\"\"\noutliers_25z.describe()\noutliers_2z.describe()\n\"\"\"\nUsing a z-score of 2.5 trimmed off 76 observations that had extreme values in any of the following: Bilirubin, LFTs, Protein, and\/or AGR levels. Using a z-score of 2 further trimmed off 44 observations for a grand total of 120 removals. The z-score of 2 brought down the maximum values slightly except for ALT. Whether this has an impact on distribution remains to be seen.\n\"\"\"\n\"\"\"\n## Visualization\n\"\"\"\n\"\"\"\nThe data without outliers is only necessary for the distribution plots as seaborn's boxplots can be given the showfliers argument to remove outliers from plots.\n\"\"\"\n\"\"\"\n### LFT Distribution by Gender and Chronic Liver Disease Status - Outliers > 2.5 z-score removed\n\"\"\"\nsns.set_style(\"darkgrid\")\ngraph = sns.FacetGrid(outliers_25z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"AST\")\ngraph\ngraph = sns.FacetGrid(outliers_25z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"ALT\")\ngraph\ngraph = sns.FacetGrid(outliers_25z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"ALP\")\ngraph\n\"\"\"\n### LFT Distribution by Gender and Chronic Liver Disease Status - Outliers > 2 z-score removed\n\"\"\"\ngraph = sns.FacetGrid(outliers_2z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"AST\")\ngraph\ngraph = sns.FacetGrid(outliers_2z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"ALT\")\ngraph\ngraph = sns.FacetGrid(outliers_2z, col = \"Liver Patient\", row = \"Gender\", height = 5)\ngraph.map(sns.distplot, \"ALP\")\ngraph\n\"\"\"\nBoth outlier trimmed datasets have roughly similar distributions for LFTs with the 2 z-score set having slightly less compressed graphs due to the lower max values.\n\nThe liver patients tend to have more right skewed data than the non-liver patients which fits the data description as well as medical expectations. Liver patients are more likely to have extreme values in LFTs than non-liver patients. ALP was a bit of an exception as there was a fair deal of right skewing in non-liver patients. This is fairly reasonable as liver damage is not the only source of high ALP in the body; bone disorders can also cause elevations in ALP levels. Since the non-liver patients are still patients, it follows that they could have another ALP elevating condition.\n\"\"\"\n\"\"\"\n### Boxplots with Entire Dataset\n\"\"\"\nf, axes = plt.subplots(1, 3, figsize = (15, 6))\nf.tight_layout(pad = 5)\nsns.boxplot(x = \"Liver Patient\", y = \"AST\", hue = \"Gender\", data = data, orient = 'v', ax = axes[0], showfliers = False)\nsns.boxplot(x = \"Liver Patient\", y = \"ALT\", hue = \"Gender\", data = data, orient = 'v', ax = axes[1], showfliers = False)\nsns.boxplot(x = \"Liver Patient\", y = \"ALP\", hue = \"Gender\", data = data, orient = 'v', ax = axes[2], showfliers = False)\n\"\"\"\nLFT boxplots shows much the same from the distplots from above. Although I think some of the increased variability in ALP levels is better communicated in the distplots above.\n\"\"\"\nf, axes = plt.subplots(1, 2, figsize = (15, 6))\nf.tight_layout(pad = 5)\nsns.boxplot(x = \"Liver Patient\", y = \"Total_Bilirubin\", hue = \"Gender\", data = data, orient = 'v', ax = axes[0], showfliers = False)\nsns.boxplot(x = \"Liver Patient\", y = \"Direct_Bilirubin\", hue = \"Gender\", data = data, orient = 'v', ax = axes[1], showfliers = False)\n\"\"\"\nWhile the Bilirubin levels in non-liver patients appears very low, they're actually more or less normal. Total Bilirubin of 1.2 mg\/dL or less is the roughly normal reference value and Direct Bilirubin is about 0.3 mg\/dL or less. The very large boxplots for the liver patient groups is indicative of the excess Bilirubin that's present in liver damage and the large amount of variability. On a related note, the male non-liver patients actually have somewhat elevated Bilirubin as a group but again, a few other conditions (e.g. hemolytic anemia) can cause high Bilirubin without a primary hepatic cause.\n\"\"\"\nf, axes = plt.subplots(1, 3, figsize = (15, 6))\nf.tight_layout(pad = 5)\nsns.boxplot(x = \"Liver Patient\", y = \"Protein\", hue = \"Gender\", data = data, orient = 'v', ax = axes[0], showfliers = False)\nsns.boxplot(x = \"Liver Patient\", y = \"Albumin\", hue = \"Gender\", data = data, orient = 'v', ax = axes[1], showfliers = False)\nsns.boxplot(x = \"Liver Patient\", y = \"AGR\", hue = \"Gender\", data = data, orient = 'v', ax = axes[2], showfliers = False)\n\"\"\"\n\n\nWhile there's some increased variability in the liver patients, both liver patients and non-patients have similar distributions of protein metrics (protein, albumin, AGR). The values suggest that approximately half of all patients fall below the minimum values for normal protein and albumin. Now in a liver setting, this can often be a sign of cirrhosis or severe, chronic liver disease. Basically, low protein and albumin in liver disease may suggest that the liver is so impaired that it cannot make vital proteins at a normal rate anymore. However, there are other reasons for low values including renal disease (e.g. Nephrotic Syndrome) and fluid retention (e.g. Congestive Heart Failure). These may be more applicable to the non-liver patients but can apply to the liver patients too.\n\"\"\"\n\"\"\"\n# Impressions\n\"\"\"\n\"\"\"\nThe data appears to show increased variability in Men and Liver Patients in laboratory test values with the exception of ALP and Proteins (Albumin, AGR, and Protein). As many of the included lab values strongly pertain to liver function, it's fair to see the increased variability, and higher mean values in the Liver Patient group. Epidemiological studies suggest that men are more likely to die from chronic liver disease, and so are more likely to have it over women. That could potentially explain the gender differences. \n\"\"\"\n\"\"\"\nTo move forward with this data for predictive modeling, and test values would have to be scaled. Further, given that the dataset is unbalanced on both Gender and Liver Patient status, care will have to taken to ensure that the chosen model isn't impaired by that. Potential management of the unbalanced data could be via undersampling using the imbalanced-learn package.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3ceae2f8df61e9'}"}
{"id":"72465","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport warnings as ws\nws.filterwarnings(\"ignore\")\ndf = pd.read_csv(\"\/kaggle\/input\/ipl2020-tweets\/IPL2020_Tweets.csv\")\ndf.head()\n\"\"\"\n<center style = \"color: #e11d74\" > <h1> Dealing with the Missing values <\/h1> <\/center>\n\"\"\"\ncheck_na = ((df.isna().sum() \/ df.shape[0])* 100).reset_index().rename(columns = {\"index\": \"Columns\", 0: \"missing value percentage\"})\nfig = px.bar(check_na, y='missing value percentage', x='Columns', text='missing value percentage', title = \"Percent of missing values in the columns\")\nfig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">The  Column <i> User Location hss <\/i> has the maximum no. of missing values. followed by the user_description  <\/p>\n    \n  \n\"\"\"\n\"\"\"\n# Dealing with user Location\n\"\"\"\nsns.set()\nplt.figure(figsize = (10,6))\nsns.barplot(data = df.user_location.value_counts()[:5].reset_index(), y = \"user_location\", x=\"index\", palette=\"Spectral\") \nplt.ylabel(\"Count of people\")\nplt.xlabel(\"Top Locations in the dataser\")\nplt.title(\"Top user locations in the dataset\", size = 20)\nplt.show()\n\n# For the purpose of EDA we will replace the na values of location with the  india\ndf.user_location.fillna(\"India\", inplace= True)\ndf.hashtags.fillna('[IPL2020]' , inplace = True)\ndf.isna().sum()\n\"\"\"\n<div>\n    <p style = \"color: #322f3d; font-size:22px;\"> All NaN values filled except user description which i prefereed not to fill  <\/p>\n    \n    \n  \n\"\"\"\n\"\"\"\n<h1 style =\"color: #6f4a8e;\"> Begin <\/h1> \n\"\"\"\n# estimate of verified user\ntemp = df.user_verified.replace({True: \"Verified\", False: \"Non-verfied\"}).value_counts().reset_index()\nfig = px.pie(temp, values='user_verified', names='index', color_discrete_sequence=px.colors.sequential.RdBu, title = \"User Status\")\nfig.show()\n\n\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">Clear intuaition is most peoples are NOT verfied. As the twitter is prestigious platform still it is  suffering to verify the peoples. <\/p>\n    \n  \n\n\"\"\"\nfig = px.bar(df.source.value_counts()[:10].reset_index(), y='source', x='index', text='source', title = \"Top Sources of posting\", color = \"index\")\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">Most people tends to use the twitter on the Android  phones followed by the Twitter Web app and Twitter on Iphone <\/p>\n    \n  \n\n\n\n\"\"\"\nfig = px.bar(df.hashtags.value_counts()[1:10].reset_index(), y='hashtags', x='index', text='hashtags', title = \"Top Trending of Hashtags\",  color='index')\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:19px;\">AS the BCCI announces the organization of the IPL hence it become the trending toics followed by the Dream11 <\/p>\n    \n  \n\n\n\n\"\"\"\nfig = px.scatter(data_frame=df, y=\"user_favourites\", x=\"user_followers\", size = \"user_favourites\", color = \"user_verified\",log_x=True, size_max=20)\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">Verification is still the issue here<\/p>\n\n\"\"\"\nfig = px.bar(df.user_location.value_counts()[:20].reset_index(), y='user_location', x='index', text='user_location', title = \"Top 20 locations while twitting \",  color='index')\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">As india's digital literacy is growing and the data rates are quite cheap the consumption is also increased. We can clearly build the intuiation that india is one of the biggest digital market.<\/p>\n\n\"\"\"\ndf.user_created = pd.to_datetime(df.user_created, infer_datetime_format=True)\ntemp = pd.datetime.now() - df.user_created\navg_age = []\nfor i in temp:\n    avg_age.append(int(str(i).split()[0]) \/\/ 365)\nfig = px.bar(pd.Series(avg_age).value_counts().reset_index().rename(columns = {\"index\":\"year\", 0:\"Occurances\"}), x= \"year\", y=\"Occurances\", color = \"Occurances\", title  =\"Age of the twitter account \")\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- (Tricky) <\/p>\n        <p style = \"color: #1b262c; font-size:18px;\">This is the most interesting graph. This is the distribution of the age of the people on the youtube. This assumes the creation date as thebirth and hence i calculated the age uptill today <\/p>\n\n\"\"\"\ntemp = df.is_retweet.value_counts().reset_index().replace({False: \"Not Retweeted\", True : \"ReTweeted\"})\nfig = px.pie(temp, values='is_retweet', names='index', color_discrete_sequence=px.colors.sequential.RdBu, title = \"Retweeted or not\")\nfig.show()\n\"\"\"\n<div>\n    <p style = \"color: #d54062; font-size:22px;\"> Inference :- <\/p>\n        <p style = \"color: #1b262c; font-size:20px;\">No one Retweeted<\/p>\n\n\"\"\"\n\"\"\"\n<hr style = \"font-size:20px;\">\n\"\"\"\n\"\"\"\n<div> \n    <h1 style = \"color: #cf1b1b; font-weight:bold\"> Final Conclusions <\/h1>\n    <ul>\n        <li style = \"color: #440047; font-size:18px; margin: 1.5rem;\">Text Based features have lot of NaN values<\/li>\n        <li  style = \"color: #440047; font-size:18px; margin: 1.5rem;\"> Absence of continous features gives us chance to derive new one<\/li>\n        <li  style = \"color: #440047; font-size:18px; margin: 1.5rem;\"> Indians are posting lot of tweets<\/li>\n        <li  style = \"color: #440047; font-size:18px; margin: 1.5rem;\" > IPL is one of the Hot Topics<\/li>\n        <li  style = \"color: #440047; font-size:18px; margin: 1.5rem;\"> Most users are Non - verified<\/li>\n        <li  style = \"color: #440047; font-size:18px; margin: 1.5rem;\"> Most peoples used their phones For their tweets<\/li>\n        <\/ul>\n\"\"\"\n\"\"\"\n<center> <h1 style = \"color: #fa163f; font-weight:bold\"> ^^^ UPVOTE IT ^^^  <\/h1> <\/center>\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8561dee5563c1f'}"}
{"id":"41124","text":"\"\"\"\n# Indian Lever Patients Analysis-Deep Neural Networks-Algorithm\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\n#### Create a class that will batch the data\n\n\"\"\"\n# To use the Adam optimizer, we should train and validate our data in batches. For batching we create this class.\nimport numpy as np\n# Class for loading the datasets *.npz files and do the batching for the algorithm\n# This code is reusable. You should just change Liver_disease_data everywhere in the code\nclass Liver_Disease_Data_Reader():\n    # dataset is a mandatory arugment, while the batch_size is optional. dataset values can be 'train', 'valuatoin' or 'test'\n    # If you don't input batch_size, it will automatically take the value: None\n    def __init__(self, dataset, batch_size = None):\n    \n        # The dataset that loads is one of \"train\", \"validation\", \"test\".\n        # e.g. if I call this class with x('train',5), it will load 'Liver_disease_data_train.npz' with a batch size of 5.\n        npz = np.load('..\/input\/Liver_disease_data_{0}.npz'.format(dataset))\n        \n        # Two variables that take the values of the inputs and the targets. Inputs are floats, targets are integers\n        self.inputs, self.targets = npz['inputs'].astype(np.float), npz['targets'].astype(np.int)\n        \n        # Counts the batch number, given the size you feed it later\n        # If the batch size is None, we are either validating or testing, so we want to take the data in a single batch\n        if batch_size is None:\n            self.batch_size = self.inputs.shape[0]\n        else:\n            self.batch_size = batch_size\n        self.curr_batch = 0\n        self.batch_count = self.inputs.shape[0] \/\/ self.batch_size\n    \n    # A method which loads the next batch\n    def __next__(self):\n        if self.curr_batch >= self.batch_count:\n            self.curr_batch = 0\n            raise StopIteration()\n            \n        # You slice the dataset in batches and then the \"next\" function loads them one after the other\n        batch_slice = slice(self.curr_batch * self.batch_size, (self.curr_batch + 1) * self.batch_size)\n        inputs_batch = self.inputs[batch_slice]\n        targets_batch = self.targets[batch_slice]\n        self.curr_batch += 1\n        \n        # One-hot encode the targets. In this example it's a bit superfluous since we have a 0\/1 column \n        # as a target already. But this will be useful for any classification task with more than one target column\n        classes_num = 2\n        targets_one_hot = np.zeros((targets_batch.shape[0], classes_num))\n        targets_one_hot[range(targets_batch.shape[0]), targets_batch] = 1\n        \n        # The function will return the inputs batch and the one-hot encoded targets\n        return inputs_batch, targets_one_hot\n    \n        \n    # A method needed for iterating over the batches, as we will put them in a loop\n    # This tells Python that the class we're defining is iterable, i.e. that we can use it like:\n    # for input, output in data: \n        # do things\n    # An iterator in Python is a class with a method __next__ that defines exactly how to iterate through its objects\n    def __iter__(self):\n        return self\n\"\"\"\n## Create the machine learning algorithm (i.e Deep Neural Network, here)\n\nThe building blocks of ML are:\n#### 1. Data\n     We take a historical dataset and use it to train the NN. \n     We split this data into 'train' and 'validation' and use them to prevent overfitting.\n     We feed the 'train' data in batches if you want to use Adam optimizer as your optimization algorithm\n     We use the 'test' data to find the accuracy of the model.\n#### 2. Model\n     Model is a function chosen by us, of which the parameters are weights and biases. e.g. y = x1w1 + ..+ xkwk + b (w-weight, b-bias)\n     Essentially, the idea of the ML is to find those parameters(weights and biases) for which the model has the highest predictive power\n     Note: To create a deep neural network, we should add an activation function to our model for each layer. Activation function adds non-linearity to the layer. \n     # Common activation functions are:\n        1. sigmoid(logistic)\n        2. TanH(Hyperbolic Tangent)\n        3. ReLU(Rectified Linear Unit)\n        4. Softmax ( This function usually uses in the output layer.)\n#### 3. Objective function \n     Objective function measures the predictive power[i.e variation from the model output(y) and the target(t)] of our model. \n     Objective functions are split into 1. loss (supervised learning) and 2. reward(reinforcement learning)\n     Based on the problem at hand, we aim to minimize the loss function OR maximize the reward function\n     This is a supervised learning problem, so we try to minimize the loss function, and the minimization happens by adjusting the parameters of the model (weights and biases). This adjustment is made by the optimization algorithm.\n     \n     #Common objective(loss) functions in Supervised Learning are:\n        1. For Regression problems\n            a. Mean Square Error\/Quadratic Loss\/L2 Loss\n            b. Mean Absolute Error\/L1 Loss\n            c. Mean Bias Error\n        2. For Classification problems\n            a. Cross Entropy Loss\/Negative Log Likelihood\n            b. Hinge Loss\/Multi class SVM Loss             \n#### 4. Optimization algorithm\n     Optimization algorithm adjusts parameters (weights and biases) and the modified model iterate through the steps.\n     Iteration is repeated until we find the values of the parameters (weights and biases), for which the objective function is optimal.\n     # Adam is the latest and widely using optimizer, now.\n\n\"\"\"\nimport tensorflow as tf\n\ninput_size = 10        # Input size depends on the number of input variables. We have 10 of them\noutput_size = 2        # Output size is 2, as we one-hot encoded the targets.\nhidden_layer_size = 20 # width of hidden layer\n\n# Reset the default graph, so you can fiddle with the hyperparameters and then rerun the code.\ntf.reset_default_graph()\n\n######--- NN Building block 1.DATA (Placeholders for data) ---######\n\ninputs = tf.placeholder(tf.float32, [None, input_size])\ntargets = tf.placeholder(tf.int32, [None, output_size])\n\n######--- NN Building block 2.Layer (Model + Activation function) ---######\n\n# Outline the model. We will create a net with 2 hidden layers\n\nweights_1 = tf.get_variable(\"weights_1\", [input_size, hidden_layer_size])\nbiases_1 = tf.get_variable(\"biases_1\", [hidden_layer_size])\noutputs_1 = tf.nn.relu(tf.matmul(inputs, weights_1) + biases_1)\n\nweights_2 = tf.get_variable(\"weights_2\", [hidden_layer_size, hidden_layer_size])\nbiases_2 = tf.get_variable(\"biases_2\", [hidden_layer_size])\n\noutputs_2 = tf.nn.sigmoid(tf.matmul(outputs_1, weights_2) + biases_2)\n\nweights_3 = tf.get_variable(\"weights_3\", [hidden_layer_size, output_size])\nbiases_3 = tf.get_variable(\"biases_3\", [output_size])\n\noutputs = tf.matmul(outputs_2, weights_3) + biases_3\n\n######--- NN Building block 3.Objective function ---######\n\n# Use of objective function(softmax_cross_entropy_with_logits) since this is a classification problem \nloss = tf.nn.softmax_cross_entropy_with_logits(logits=outputs, labels=targets)\nmean_loss = tf.reduce_mean(loss)\n\n# Get a 0 or 1 for every input indicating whether it output the correct answer\nout_equals_target = tf.equal(tf.argmax(outputs, 1), tf.argmax(targets, 1))\naccuracy = tf.reduce_mean(tf.cast(out_equals_target, tf.float32))\n\n######--- NN Building block 4.Optimization Algorithm ---######\n\noptimize = tf.train.AdamOptimizer(learning_rate=0.002).minimize(mean_loss)\n\n### Please note, the above NN building blocks will run and learn only when you explicitly call them in a session ###\n\n# Create a session\nsess = tf.InteractiveSession()\n\n# Initialize the variables\ninitializer = tf.global_variables_initializer()\nsess.run(initializer)\n\n# Choose the batch size\nbatch_size = 20\n\n# Set early stopping mechanisms\nmax_epochs = 100\nprev_validation_loss = 9999999.\n\n# Load the first batch of training and validation, using the class we created. \n# Arguments are ending of 'Liver_disease_data_<...>', where for <...> we input 'train', 'validation', or 'test'\n# depending on what we want to load\ntrain_data = Liver_Disease_Data_Reader('train', batch_size)\nvalidation_data = Liver_Disease_Data_Reader('validation')\n\n# Create the loop for epochs \nfor epoch_counter in range(max_epochs):\n    \n    # Set the epoch loss to 0, and make it a float\n    curr_epoch_loss = 0.\n    \n    # Iterate over the training data \n    # Since train_data is an instance of the Liver_Disease_Data_Reader class,\n    # we can iterate through it by implicitly using the __next__ method we defined above.\n    # As a reminder, it batches samples together, one-hot encodes the targets, and returns\n    # inputs and targets batch by batch\n    for input_batch, target_batch in train_data:\n        _, batch_loss = sess.run([optimize, mean_loss], \n            feed_dict={inputs: input_batch, targets: target_batch})\n        \n        #Record the batch loss into the current epoch loss\n        curr_epoch_loss += batch_loss\n    \n    # Find the mean curr_epoch_loss\n    # batch_count is a variable, defined in the Liver_Disease_Data_Reader class\n    curr_epoch_loss \/= train_data.batch_count\n    \n    # Set validation loss and accuracy for the epoch to zero\n    validation_loss = 0.\n    validation_accuracy = 0.\n    \n    # Use the same logic of the code to forward propagate the validation set\n    # There will be a single batch, as the class was created in this way\n    for input_batch, target_batch in validation_data:\n        validation_loss, validation_accuracy = sess.run([mean_loss, accuracy],\n            feed_dict={inputs: input_batch, targets: target_batch})\n    \n    # Print statistics for the current epoch\n    print('Epoch '+str(epoch_counter+1)+\n          '. Training loss: '+'{0:.3f}'.format(curr_epoch_loss)+\n          '. Validation loss: '+'{0:.3f}'.format(validation_loss)+\n          '. Validation accuracy: '+'{0:.2f}'.format(validation_accuracy * 100.)+'%')\n    \n    # Trigger early stopping if validation loss begins increasing.\n    if validation_loss > prev_validation_loss:\n        break\n        \n    # Store this epoch's validation loss to be used as previous in the next iteration.\n    prev_validation_loss = validation_loss\n    \nprint('End of training.')\n\"\"\"\n## Test the model\n\"\"\"\n# Load the test data, following the same logic as we did for the train_data and validation data\ntest_data = Liver_Disease_Data_Reader('test')\n\n# Forward propagate through the training set. This time we only need the accuracy\nfor inputs_batch, targets_batch in test_data:\n    test_accuracy = sess.run([accuracy],\n                     feed_dict={inputs: inputs_batch, targets: targets_batch})\n\n# Get the test accuracy in percentages\n# When sess.run is has a single output, we get a list (that's how it was coded by Google), rather than a float.\n# Therefore, we must take the first value from the list (the value at position 0)\ntest_accuracy_percent = test_accuracy[0] * 100.\n\n# Print the test accuracy\nprint('Test accuracy: '+'{0:.2f}'.format(test_accuracy_percent)+'%')\ninputs_batch.shape\ntargets_batch.shape","meta":"{'source': 'AI4Code', 'id': '4bc97ba005b557'}"}
{"id":"54128","text":"\"\"\"\n<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">NLP with 1.6m tweets, positive and negative tweets, can we create some ML that can predict if a tweet is either? 280 chars with links, mentions, and ugly spellling. <a href=\"https:\/\/twitter.com\/hashtag\/letsgo?src=hash&amp;ref_src=twsrc%5Etfw\">#letsgo<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/datascience?src=hash&amp;ref_src=twsrc%5Etfw\">#datascience<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/ML?src=hash&amp;ref_src=twsrc%5Etfw\">#ML<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/needmoreGPUs?src=hash&amp;ref_src=twsrc%5Etfw\">#needmoreGPUs<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/bigdata?src=hash&amp;ref_src=twsrc%5Etfw\">#bigdata<\/a><\/p>&mdash; Jonathan Henson (@sciencetition) <a href=\"https:\/\/twitter.com\/sciencetition\/status\/1305008902212399108?ref_src=twsrc%5Etfw\">September 13, 2020<\/a><\/blockquote> <script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n\"\"\"\n\"\"\"\n**Lazy or Smart?** \nThis was an exercise in creating a lighter, stripped down ML, asking the question why DS projects often follow the same script. I took out what is usually considered important steps, objects, ideals, and tested to see if there was a need.\n\nThe most important take away: **Stopwords** need to be taken into account with respect to the target data. It might make sense for articles, books, paragraphs. But for tweets? Turns out perhaps not.\n\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\nimport itertools\n\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\n\nfrom wordcloud import WordCloud\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Conv1D, Bidirectional, LSTM, Dense, Input, Dropout, SpatialDropout1D\n\nimport nltk\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport re\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\n\"\"\"\n**Load and Drop** \nHere we load our tweets into our dataframe. Not even going to give the columns proper names before we drop them. In the end all we want is sentiment and text. Print a peek to make sure we are good to go.\n\"\"\"\ndf = pd.read_csv('..\/input\/sentiment140\/training.1600000.processed.noemoticon.csv',encoding = 'latin',header=None)\ndf.columns = ['sentiment', 'x1', 'x2', 'x3', 'x4', 'text']\ndf = df.drop(['x1', 'x2', 'x3', 'x4'], axis=1)\n\nprint(df)\n\"\"\"\n**Workable data**\n4's and 0's are not very ML friendly. Since the data does not include neutral sentiment, or anything in between lets just label them Negative and Positive.\n\"\"\"\n#function to change labels to Positive or Negative\nConvert_Sentiment = {0: \"Negative\", 4: \"Positive\"}\ndef Sentiment_change(lcol):\n  return Convert_Sentiment[lcol]\ndf.sentiment = df.sentiment.apply(lambda x: Sentiment_change(x))\n\"\"\"\n**Distribution** \nIn the real world we are given data that is usually highly skewed. We were given a gift here, 50\/50 and no need to change samples.\n\"\"\"\n#lets look at our distribution\nval_count = df.sentiment.value_counts()\nprint(val_count)\n\"\"\"\n**Cleaning up the data** \nTypically you would stem or lemmatize, remove links, mentions, and stop words. Call it a day and your data is clean. However with tweets, our data is different. We dont have full sentences, or even coherent thoughts sometimes. \n\nStop words: A list of words commonly used which have little meaning. Well, it does have meaning, and if the entire context of a Positive or Negative tweet is derived from 280 chars, we are going to leave the stop words in. \n\nTwitter specific spam removed: HTTPS, HTTP, @mentions, AMP(mobile page text), and quot (meaningless)\n\n![](https:\/\/www.kdnuggets.com\/images\/cartoon-machine-learning-class.jpg)\n\"\"\"\n## Clean data. Typically stop words would be used. This study includes all words, excluding stop words in a 280 char tweet is too restrictive.\n## Remove words with no meaning, mentions and urls. \ncleaning = \"amp\\S+|quot\\S+|@\\S+|https?:\\S+|http?:\\S|[^A-Za-z0-9]\"\ndef preprocess(text):\n  text = re.sub(cleaning, ' ', str(text).lower()).strip()\n  tokens = []\n  for token in text.split():\n    tokens.append(token)\n  return \" \".join(tokens)\ndf.text = df.text.apply(lambda x: preprocess(x))\n\"\"\"\n**Get a visual, make sure they look different**\n\"\"\"\nplt.figure(figsize=(20, 20))\ncloud = WordCloud(max_words=1000, width=1000, height=800)\ncloud.generate(\" \".join(df[df.sentiment == 'Positive'].text))\nplt.imshow(cloud, interpolation='bilinear')\nplt.show()\n\"\"\"\n# Now - stop word\nDo you see the \"now\". thats a big one for Negative tweets and not for Positive ones, and it just happens to be a stop word. \n\"\"\"\nplt.figure(figsize=(20, 20))\ncloud = WordCloud(max_words=1000, width=1000, height=800)\ncloud.generate(\" \".join(df[df.sentiment == 'Negative'].text))\nplt.imshow(cloud, interpolation='bilinear')\nplt.show()\n\"\"\"\n**80\/20 as is the tradition**\n\"\"\"\n#setup for training and testing splits. \nTraining_percent = 0.8\nMAX_SEQUENCE_LENGTH = 30\ntrain_data, test_data = train_test_split(df, test_size=1-Training_percent, random_state=7) \n\"\"\"\n**TOKENS**\n\nEach tweet is going to contain multiple words, here we basically split the tweet into its individual words so we can further process.\n\"\"\"\ntokens = Tokenizer()\ntokens.fit_on_texts(train_data.text)\nword_index = tokens.word_index\n\"\"\"\nManipulating our train and tests, filled with tokens and padded to ensure identical shapes\n\"\"\"\n#pesky +1 to account for 0 starting.\nvocab_size = len(tokens.word_index) + 1\nprint(\"# of words :\", vocab_size)\nx_train = pad_sequences(tokens.texts_to_sequences(train_data.text),maxlen=MAX_SEQUENCE_LENGTH)\nx_test = pad_sequences(tokens.texts_to_sequences(test_data.text), maxlen=MAX_SEQUENCE_LENGTH)\n\nlabels = train_data.sentiment.unique().tolist()\n\nencoder = LabelEncoder()\nencoder.fit(train_data.sentiment.to_list())\n\"\"\"\nCreating our Y-Train, reshaping, and taking a peek to make sure we are on the right track. \n\"\"\"\n#Create y-train\ny_train = encoder.transform(train_data.sentiment.to_list())\ny_test = encoder.transform(test_data.sentiment.to_list())\ny_train = y_train.reshape(-1, 1)\ny_test = y_test.reshape(-1, 1)\n\nprint(\"Y Train shape: \",y_train.shape)\nprint(\"Y Test shape: \",y_test.shape)\n\"\"\"\n# What is the right number?\n\nWe are at the point where I feel like pathways really open up, we will be using GLOVE, but there are other options. We are using ADAM but there are other options. What is going to be your Learning Rate, how many Epochs are going to be run, will something as simple as batch size change our model drastically?\n\n\n![](https:\/\/i.imgflip.com\/1j9mml.jpg)\n\"\"\"\nGLOVE_EMB = '..\/input\/glove6b300dtxt\/glove.6B.300d.txt'\nEMBEDDING_DIM = 300\nLR = .005\nBATCH_SIZE = 2048\nEPOCHS = 15\n#start embedding, open glove and resolve total vectors\nembed_index = {}\nf = open(GLOVE_EMB, encoding=\"utf-8\")\nfor line in f:\n  values = line.split()\n  word = values[0]\n  vectors = np.asarray(values[1:], dtype='float32')\n  embed_index[word] = vectors\nf.close()\nprint('Word vectors: ',len(embed_index))\n#create the matrix and fill with 0s, size of total vocab words and the embeded dimentions from the Glove file used. \nemb_matrix = np.zeros((vocab_size, EMBEDDING_DIM))\n\n#get each word, get corresponding glove value, write if value exists to the embedding matrix\nfor word, i in word_index.items():\n  embedding_vector = embed_index.get(word)\n  if embedding_vector is not None:\n    emb_matrix[i] = embedding_vector\n\"\"\"\n# Trainable is FALSE.\n\nWhen trying different combinations of settings, trainable = true led to an extremely over fit model, which also took 5x as long to run. Don't do it. \n\n# No callbacks.\nThis was tested, and including callbacks did not result in a better model. I am choosing to exclude callbacks and keep the model cleaner.\n\"\"\"\n#create the embedding layer with given dimensions, vectors. Trainable false is used, if using trainable = true the model will over fit significantly\nembedding_layer = tf.keras.layers.Embedding(vocab_size,EMBEDDING_DIM,weights=[emb_matrix],input_length=MAX_SEQUENCE_LENGTH,trainable=False)\n\"\"\"\n# Is anyone an expert in this area?\nI am using the LSTM model, with pretty standard settings. Most models seem to have additional layers, but I found them not to be helpful in producing an accurate model.\n\"\"\"\n#sequence creation. \nsequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')\nembedding_sequences = embedding_layer(sequence_input)\nx = SpatialDropout1D(0.2)(embedding_sequences)\nx = Conv1D(64, 5, activation='relu')(x)\nx = Bidirectional(LSTM(64, dropout=0.1, recurrent_dropout=0.1))(x)\nx = Dense(512, activation='relu')(x)\noutputs = Dense(1, activation='sigmoid')(x)\n\nmodel = tf.keras.Model(sequence_input, outputs)\nmodel.compile(optimizer=Adam(learning_rate=LR), loss='binary_crossentropy',metrics=['accuracy'])\nprint(model.summary())\n\"\"\"\n# GPU and Coffee time\n![](https:\/\/imgs.xkcd.com\/comics\/compiling.png)\n\"\"\"\n#Here we go\nhistory = model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_data=(x_test, y_test))\n\"\"\"\nI picked too many Epochs, 10 would have been enough. The val_accuracy fluctuated a bit after 10 epochs but wasn't sustained improvement. \n\"\"\"\ns, (at, al) = plt.subplots(2, 1)\nat.plot(history.history['accuracy'], c='b')\nat.plot(history.history['val_accuracy'], c='r')\nat.set_title('model accuracy')\nat.set_ylabel('accuracy')\nat.set_xlabel('epoch')\nat.legend(['LSTM_train', 'LSTM_val'], loc='upper left')\n\nal.plot(history.history['loss'], c='m')\nal.plot(history.history['val_loss'], c='c')\nal.set_title('model loss')\nal.set_ylabel('loss')\nal.set_xlabel('epoch')\nal.legend(['train', 'val'], loc='upper left')\nplt.show()\ndef decode_sentiment(score):\n    return \"Positive\" if score > 0.5 else \"Negative\"\n\n\nscores = model.predict(x_test, verbose=1, batch_size=10000)\ny_pred_1d = [decode_sentiment(score) for score in scores]\n\"\"\"\n**Confusion Matrix**\n\nHere we can see where the model got things right and wrong. Very close to even on Positive and Negative with a slightly better job at spotting Positive tweets.\n\n# over all about an 83%\n\nWhen computed with stopwords, all else being equal, the model showed 79%. \n\"\"\"\ndef plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.Blues):\n    cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title, fontsize=20)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, fontsize=13)\n    plt.yticks(tick_marks, classes, fontsize=13)\n\n    fmt = '.2f'\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, format(cm[i, j], fmt),\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.ylabel('True label', fontsize=17)\n    plt.xlabel('Predicted label', fontsize=17)\n    \n\ncnf_matrix = confusion_matrix(test_data.sentiment.to_list(), y_pred_1d)\nplt.figure(figsize=(6, 6))\nplot_confusion_matrix(cnf_matrix, classes=test_data.sentiment.unique(), title=\"Confusion matrix\")\nplt.show()\n\nprint(classification_report(list(test_data.sentiment), y_pred_1d))\n\nmodel.save_weights(\"model.h5\")","meta":"{'source': 'AI4Code', 'id': '63a5817e22fb20'}"}
{"id":"94849","text":"#importing Libraries\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport matplotlib\nfrom matplotlib import cm\nimport geopandas as gpd\nimport plotly.express as px\nimport seaborn as sns\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)    #THIS LINE IS MOST IMPORTANT AS THIS WILL DISPLAY PLOT ON \n#NOTEBOOK WHILE KERNEL IS RUNNING\nimport plotly.graph_objects as go\n\nfrom IPython.display import HTML,display\nimport warnings\nwarnings.filterwarnings(\"ignore\")\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\n\"\"\"\n![raj-rana-nWpTGnP_jWE-unsplash%20%281%29.jpg](attachment:raj-rana-nWpTGnP_jWE-unsplash%20%281%29.jpg)\n\"\"\"\n\"\"\"\n# Introduction\n\"\"\"\n\"\"\"\n In this notebook we are  going to analyze the Indian Education System. Main focus of this analysis will be on The Enrollment and Dropout Ratio of Schools over the years. We also try find out if there is any correlation between basic amneties in school (water, electricity etc.) and the enrollment\/dropout ratios. Indian education System is divided into four main parts.\n \n 1) **Primary** : The Primary Education in India consists of students studying in Class I-IV. \n  \n \n 2) **Upper Primary**: The Upper Primary Education in India  consists of students studying in Class V-VIII.The Indian government lays emphasis on primary education (Class I-VIII) also referred to as elementary education, to children aged 6 to 14 years old. \n \n 3) **Secondary**: Secondary education in India begins after eight years of elementary education and is divided into two years of secondary education (classes IX and X) and two years of Higher secondary education (classes XI and XII)\n \n \n 4) **Higher Secondary**: Higher Secondary Education consists of students studying in Class XI & XII.\n \n **Gross Enrollment Ratio**:  Number of students enrolled in a given level of education, regardless of age, expressed as a percentage of the official school-age population corresponding to the same level of education.\n\n **Dropout Ratio** : The percentage of students failing to complete a particular school or college course. \n \n The Indian government has took many steps to increase the enrollment ratio of students . Steps like Right to Education Policy for primary school students.The government also runs \"Go to school Campaign\" to motivate young students to attend regular classes.\n\"\"\"\n#Reading the datasets\nenroll = pd.read_csv(\"..\/input\/indian-school-education-statistics\/gross-enrollment-ratio-2013-2016.csv\")\n\n\ndrop = pd.read_csv(\"..\/input\/indian-school-education-statistics\/dropout-ratio-2012-2015.csv\")\n\nwater = pd.read_csv(\"..\/input\/indian-school-education-statistics\/percentage-of-schools-with-water-facility-2013-2016.csv\")\n\ngtoilet = pd.read_csv(\"..\/input\/indian-school-education-statistics\/schools-with-girls-toilet-2013-2016.csv\")\n\nbtoilet = pd.read_csv(\"..\/input\/indian-school-education-statistics\/schools-with-boys-toilet-2013-2016.csv\")\n\ncomps = pd.read_csv(\"..\/input\/indian-school-education-statistics\/percentage-of-schools-with-comps-2013-2016.csv\")\n\nelectrs = pd.read_csv(\"..\/input\/indian-school-education-statistics\/percentage-of-schools-with-electricity-2013-2016.csv\")\n\n\n\n\n\"\"\"\n# Enrollment \n\"\"\"\nenroll.head()\n\"\"\"\nThe given dataset contains the information about male and female school enrollment ratio statewise. The data is only for three education years. These years are 2013-2014, 2014-2015 & 2015-2016.\n\nlets see the enrollment ratio of boys and girls over the years.\n\"\"\"\naienroll = enroll[enroll['State_UT']== 'All India']\n\n#reindexing the rows\naienroll = aienroll.reindex([35,109,72])\n\nenroll = enroll[enroll['State_UT']!= 'All India']\nbaienroll = aienroll.iloc[:,[0,1,2,5,8,11]]\nbaienroll = pd.melt(baienroll, id_vars=['State_UT', 'Year'], value_vars= baienroll.iloc[:,2:6])\n\ngaienroll = aienroll.iloc[:,[0,1,3,6,9,12]]\ngaienroll = pd.melt(gaienroll, id_vars=['State_UT', 'Year'], value_vars= gaienroll.iloc[:,2:6])\nplt.style.use('fivethirtyeight')\nf, axes = plt.subplots(1, 2, figsize=(20, 10))\n\nax1 = sns.barplot(x = 'Year' , y = \"value\" ,hue = \"variable\", data = baienroll, palette = 'Pastel2', edgecolor = 'black',ax=axes[0])\nax1.set(ylim=(40, 120))\naxes[0].set_title('Enrollment ratio of Boys in India',size = 20 , pad = 20)\naxes[0].set_ylabel('Enrollment ratio')\nax1.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax1.patches:\n             ax1.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=13.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nax2 = sns.barplot(x = 'Year' , y = \"value\" ,hue = \"variable\", data = gaienroll, palette = 'Pastel2', edgecolor = 'black',ax=axes[1])\nax2.set(ylim=(40, 120))\naxes[1].set_title('Enrollment ratio of Girls in India',size = 20 , pad = 20)\naxes[1].set_ylabel('Enrollment ratio')\nax2.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax2.patches:\n             ax2.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=13.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\n\"\"\"\n**Inference** : Over the years Gross Enrollment Ratio for both boys and girls increasing over the years except for the primary schools. The decrease of enrollment ratio is worrying as government took many steps to motivate students to attend primary schools.\n\nEnrollment ratio is more in primary schools as compared to the next level of education enrollment. When it comes to high school enrollment ratio its lowest among other level of education, its almost half of the enrollment ratio of primary schools. \n\n\n\n\n\"\"\"\n\"\"\"\n**Statewise Analysis for Enrollment**\n\"\"\"\nenroll.State_UT = enroll.State_UT.str.capitalize()\nenroll = enroll.replace('Pondicherry', 'Puducherry', regex=True)\nenroll = enroll.replace('NR', 0, regex=True)\nenroll = enroll.replace('@', 0, regex=True)\n\n\ncolumns = ['Higher_Secondary_Boys', 'Higher_Secondary_Girls','Higher_Secondary_Total']\nfor i , col in enumerate(columns):\n    enroll[col] = enroll[col].astype(float)\n\nenrol = enroll.copy()\nenroll = enroll.replace('2013-14', 2013, regex=True)\nenroll = enroll.replace('2014-15', 2014, regex=True)\nenroll = enroll.replace('2015-16', 2015, regex=True)\nenroll = enroll.sort_values('Year', ascending = True)\nenroll15 = enroll[enroll.Year == 2015]\nprit = enroll15.sort_values('Primary_Total', ascending = False)\nuprit = enroll15.sort_values('Upper_Primary_Total', ascending = False)\nsec = enroll15.sort_values('Secondary_Total', ascending = False)\nhsec = enroll15.sort_values('Higher_Secondary_Total', ascending = False)\nprit = pd.melt(prit, id_vars=['State_UT', 'Year'], value_vars= prit.iloc[:,2:4])\nuprit = pd.melt(uprit, id_vars=['State_UT', 'Year'], value_vars= uprit.iloc[:,5:7])\nsec = pd.melt(sec, id_vars=['State_UT', 'Year'], value_vars= sec.iloc[:,8:10])\nhsec = pd.melt(hsec, id_vars=['State_UT', 'Year'], value_vars= hsec.iloc[:,11:13])\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = prit, palette ='dark')\nax.set(xlim=(60, 158))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Enrollment ratio in Primary Schools (2015-2016)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Enrollment Ratio')\n\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = uprit, palette ='dark')\nax.set(xlim=(60, 158))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Enrollment ratio in Upper Primary Schools(2015-2016)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Enrollment Ratio')\n\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = sec, palette ='dark')\nax.set(xlim=(60, 130))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Enrollment ratio in Secondary Schools  (2015-2016)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Enrollment Ratio')\n\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = hsec, palette ='dark')\nax.set(xlim=(20, 120))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Enrollment ratio in Higher Secondary Schools (2015-2016)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Enrollment Ratio')\n\n\"\"\"\n**Enrollment over the Years**\n\"\"\"\nenrollp = enroll.iloc[:,[0,1,4]]\nenrollup = enroll.iloc[:,[0,1,7]]\nenrolls = enroll.iloc[:,[0,1,10]]\nenrollhs = enroll.iloc[:,[0,1,13]]\nfig = go.Figure(data=go.Heatmap(\n                   z= enrollp['Primary_Total'],\n                   x=enrollp['Year'],\n                   y= enrollp['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Enrollment ratio in Primary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['2013-2014','2014-2015','2015-2016']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aqua',\n    plot_bgcolor = \"aqua\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= enrollup['Upper_Primary_Total'],\n                   x=enrollup['Year'],\n                   y= enrollup['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Enrollment ratio in Upper Primary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['2013-2014','2014-2015','2015-2016']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aqua',\n    plot_bgcolor = \"aqua\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= enrolls['Secondary_Total'],\n                   x=enrolls['Year'],\n                   y= enrolls['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Enrollment ratio in Secondary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['2013-2014','2014-2015','2015-2016']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aqua',\n    plot_bgcolor = \"aqua\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= enrollhs['Higher_Secondary_Total'],\n                   x=enrollhs['Year'],\n                   y= enrollhs['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Enrollment ratio in Higher Secondary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['2013-2014','2014-2015','2015-2016']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aqua',\n    plot_bgcolor = \"aqua\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\n\"\"\"\n# Dropout\n\"\"\"\ndrop.head()\ndrop = drop.replace('NR', 0, regex=True)\ndrop = drop.replace('Uppe_r_Primary', 0, regex=True)\naidrop = drop[drop.State_UT=='All India']\ndrop = drop[drop.State_UT!='All India']\ndrop.State_UT = drop.State_UT.str.capitalize()\n\nbaidrop = aidrop.iloc[:,[0,1,2,5,8,11]]\nbaidrop = pd.melt(baidrop, id_vars=['State_UT', 'year'], value_vars= baidrop.iloc[:,2:6])\n\ngaidrop = aidrop.iloc[:,[0,1,3,6,9,12]]\ngaidrop = pd.melt(gaidrop, id_vars=['State_UT', 'year'], value_vars= gaidrop.iloc[:,2:6])\nplt.style.use('fivethirtyeight')\nf, axes = plt.subplots(1, 2, figsize=(20, 10))\n\nax1 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = baidrop, palette = 'Pastel1', edgecolor = 'black',ax=axes[0])\nax1.set(ylim=(0, 20))\naxes[0].set_title('Dropout ratio of Boys in India',size = 20 , pad = 20)\naxes[0].set_ylabel('Dropout ratio')\nax1.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax1.patches:\n             ax1.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=13.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nax2 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = gaidrop, palette = 'Pastel1', edgecolor = 'black',ax=axes[1])\nax2.set(ylim=(0, 20))\naxes[1].set_title('Dropout ratio of Girls in India',size = 20 , pad = 20)\naxes[1].set_ylabel('Dropout ratio')\nax2.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax2.patches:\n             ax2.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=13.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\ncolumns = ['Primary_Boys', 'Primary_Girls', 'Primary_Total',\n       'Upper Primary_Boys', 'Upper Primary_Girls', 'Upper Primary_Total',\n       'Secondary _Boys', 'Secondary _Girls', 'Secondary _Total',\n       'HrSecondary_Boys', 'HrSecondary_Girls', 'HrSecondary_Total']\n\nfor i , col in enumerate(columns):\n    drop[col] = drop[col].astype(float)\ndro = drop.copy()\ndrop = drop.replace('2012-13', 2013, regex=True)\ndrop = drop.replace('2013-14', 2014, regex=True)\ndrop = drop.replace('2014-15', 2015, regex=True)\ndrop = drop.sort_values('year', ascending = True)\ndrop15 = drop[drop.year == 2015]\nprid = drop15.sort_values('Primary_Total', ascending = False)\nuprid = drop15.sort_values('Upper Primary_Total', ascending = False)\nsecd = drop15.sort_values('Secondary _Total', ascending = False)\nhsecd = drop15.sort_values('HrSecondary_Total', ascending = False)\nprid = pd.melt(prid, id_vars=['State_UT', 'year'], value_vars= prid.iloc[:,2:4])\nuprid = pd.melt(uprid, id_vars=['State_UT', 'year'], value_vars= uprid.iloc[:,5:7])\nsecd = pd.melt(secd, id_vars=['State_UT', 'year'], value_vars= secd.iloc[:,8:10])\nhsecd = pd.melt(hsecd, id_vars=['State_UT', 'year'], value_vars= hsecd.iloc[:,11:13])\nprid = prid[prid.value > 0]\nuprid = uprid[uprid.value > 0]\nsecd = secd[secd.value > 0]\nhsecd = hsecd[hsecd.value > 0]\n\"\"\"\n**Primary Dropout**\n\"\"\"\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = prid, palette ='colorblind')\n#ax.set(xlim=(20, 120))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Dropout ratio in Primary Schools (2014-2015)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Dropout Ratio')\n\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = uprid, palette ='colorblind')\n#ax.set(xlim=(20, 120))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Dropout ratio in Upper Primary Schools (2014-2015)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Dropout Ratio')\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = secd, palette ='colorblind')\n#ax.set(xlim=(20, 120))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Dropout ratio in Secondery Schools (2014-2015)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Dropout Ratio')\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nax = sns.barplot(x = 'value', y ='State_UT',hue = 'variable',data = hsecd, palette ='colorblind')\n#ax.set(xlim=(20, 120))\nax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nplt.title('Dropout ratio in Higher Secondery Schools (2014-2015)',size = 20 , pad = 20)\nplt.ylabel('State\/UT')\nplt.xlabel('Dropout Ratio')\ndrop = drop.replace('Tamil  nadu', 'Tamil nadu', regex=True)\ndrop = drop.replace('Arunachal  pradesh', 'Arunachal pradesh', regex=True)\ndropp = drop.iloc[:,[0,1,4]]\ndropup = drop.iloc[:,[0,1,7]]\ndrops = drop.iloc[:,[0,1,10]]\ndrophs = drop.iloc[:,[0,1,13]]\nfig = go.Figure(data=go.Heatmap(\n                   z= dropp['Primary_Total'],\n                   x=dropp['year'],\n                   y= dropp['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Dropout ratio in Primary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['2012-2013','2013-2014','2014-2015']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aquamarine',\n    plot_bgcolor = \"aquamarine\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= dropup['Upper Primary_Total'],\n                   x=dropup['year'],\n                   y= dropup['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Dropout ratio in Upper Primary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['20012-2013','2013-2014','2014-2015']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aquamarine',\n    plot_bgcolor = \"aquamarine\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= drops['Secondary _Total'],\n                   x=drops['year'],\n                   y= drops['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Dropout ratio in Secondary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['20012-2013','2013-2014','2014-2015']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aquamarine',\n    plot_bgcolor = \"aquamarine\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\nfig = go.Figure(data=go.Heatmap(\n                   z= drophs['HrSecondary_Total'],\n                   x=drophs['year'],\n                   y= drophs['State_UT'],\n                   hoverongaps = False))\nfig.update_layout(\n    title_text= '<b>Dropout ratio in Higher Secondary Schools<b>',\n    title_x=0.5,\n    xaxis = dict(\n        tickmode = 'array',\n        tickvals = [2013,2014,2015],\n        ticktext = ['20012-2013','2013-2014','2014-2015']),\n    \n    autosize=False,\n    width= 700,\n    height=1000,\n    paper_bgcolor='aquamarine',\n    plot_bgcolor = \"aquamarine\",\n    \n    )\nfig.update_xaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.update_yaxes(tickfont=dict(family='Rockwell', color='black', size=14))\nfig.show()\n\"\"\"\n# Amneties in School (Water, Computers , Electricity & Toilets)\n\"\"\"\n\"\"\"\n**Computers**\n\"\"\"\n\ncomps.State_UT = comps.State_UT.str.capitalize()\ncom = comps[comps.State_UT == 'All india']\ncom = com.iloc[:,[0,1,2,5,9,11,12]]\ncom = pd.melt(com, id_vars=['State_UT', 'year'], value_vars= com.iloc[:,2:6])\nplt.style.use('fivethirtyeight')\nplt.figure(figsize = (10,8))\n\nax1 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = com, palette = 'Accent', edgecolor = 'black')\nax1.set(ylim=(0, 60))\nplt.title('Percentage of Schools with Computers',size = 20 , pad = 20)\nplt.ylabel('Percentage')\nax1.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax1.patches:\n             ax1.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=13.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\ncomps = comps[comps.State_UT != 'All india']\ncomps = comps.iloc[:,[0,1,2,5,9,11,12]]\ncomps.columns = [str(col) + '_comp' for col in comps.columns]\nnew_df = pd.merge(enrol, comps,  how='left', left_on=['State_UT','Year'], right_on = ['State_UT_comp','year_comp'])\ndnew_df = pd.merge(dro, comps,  how='left', left_on=['State_UT','year'], right_on = ['State_UT_comp','year_comp'])\nwater['State\/UT'] = water['State\/UT'].str.capitalize()\nwat = water[water['State\/UT']=='All india']\nwat = wat.iloc[:,[0,1,2,5,9,11,12]]\nwat = pd.melt(wat, id_vars=['State\/UT', 'Year'], value_vars= wat.iloc[:,2:6])\nwater['State\/UT'] = water[water['State\/UT']!='All india']\nwater = water.iloc[:,[0,1,2,5,9,11,12]]\nwater.columns = [str(col) + '_water' for col in water.columns]\nnew_df2 = pd.merge(new_df, water,  how='left', left_on=['State_UT','Year'], right_on = ['State\/UT_water','Year_water'])\ndnew_df2 = pd.merge(dnew_df, water,  how='left', left_on=['State_UT','year'], right_on = ['State\/UT_water','Year_water'])\nelectrs.State_UT = electrs.State_UT.str.capitalize()\nelectr = electrs[electrs.State_UT == 'All india']\nelectr = electr.iloc[:,[0,1,2,5,9,11,12]]\nelectr = pd.melt(electr, id_vars=['State_UT', 'year'], value_vars= electr.iloc[:,2:6])\n\"\"\"\n**Water and Electricity**\n\"\"\"\nplt.style.use('fivethirtyeight')\nf, axes = plt.subplots(1, 2, figsize=(20, 10))\n\nax1 = sns.barplot(x = 'Year' , y = \"value\" ,hue = \"variable\", data = wat, palette = 'Blues', edgecolor = 'black',ax=axes[0])\nax1.set(ylim=(40, 120))\naxes[0].set_title('Percentage of Schools with Water',size = 20 , pad = 20)\naxes[0].set_ylabel('Percentage')\nax1.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax1.patches:\n             ax1.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=11.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nax2 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = electr, palette = 'Greens', edgecolor = 'black',ax=axes[1])\nax2.set(ylim=(0, 120))\naxes[1].set_title('Percentage of Schools with Electricity',size = 20 , pad = 20)\naxes[1].set_ylabel('Percentage')\nax2.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax2.patches:\n             ax2.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=11.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nelectrs = electrs[electrs.State_UT != 'All india']\nelectrs = electrs.iloc[:,[0,1,2,5,9,11,12]]\nelectrs.columns = [str(col) + '_electr' for col in electrs.columns]\nnew_df3 = pd.merge(new_df2, electrs,  how='left', left_on=['State_UT','Year'], right_on = ['State_UT_electr','year_electr'])\ndnew_df3 = pd.merge(dnew_df2, electrs,  how='left', left_on=['State_UT','year'], right_on = ['State_UT_electr','year_electr'])\ngtoilet.State_UT = gtoilet.State_UT.str.capitalize()\ngtoil = gtoilet[gtoilet.State_UT == 'All india']\ngtoil = gtoil.iloc[:,[0,1,2,5,9,11,12]]\ngtoil = pd.melt(gtoil, id_vars=['State_UT', 'year'], value_vars= gtoil.iloc[:,2:6])\n\ngtoilet = gtoilet[gtoilet.State_UT != 'All india']\ngtoilet = gtoilet.iloc[:,[0,1,2,5,9,11,12]]\ngtoilet.columns = [str(col) + '_gtoil' for col in gtoilet.columns]\nnew_df4 = pd.merge(new_df3, gtoilet,  how='left', left_on=['State_UT','Year'], right_on = ['State_UT_gtoil','year_gtoil'])\ndnew_df4 = pd.merge(dnew_df3, gtoilet,  how='left', left_on=['State_UT','year'], right_on = ['State_UT_gtoil','year_gtoil'])\nbtoilet.State_UT = btoilet.State_UT.str.capitalize()\nbtoil = btoilet[btoilet.State_UT == 'All india']\nbtoil = btoil.iloc[:,[0,1,2,5,9,11,12]]\nbtoil = pd.melt(btoil, id_vars=['State_UT', 'year'], value_vars= btoil.iloc[:,2:6])\n\n\"\"\"\n**Boys and Girls Toilet**\n\"\"\"\nplt.style.use('fivethirtyeight')\nf, axes = plt.subplots(1, 2, figsize=(20, 10))\n\nax1 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = gtoil, palette = 'Greens', edgecolor = 'black',ax=axes[0])\nax1.set(ylim=(50, 120))\naxes[0].set_title('Percentage of Schools with Girls Toilet',size = 20 , pad = 20)\naxes[0].set_ylabel('Percentage')\nax1.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax1.patches:\n             ax1.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=11.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nax2 = sns.barplot(x = 'year' , y = \"value\" ,hue = \"variable\", data = btoil, palette = 'Greens', edgecolor = 'black',ax=axes[1])\nax2.set(ylim=(50, 120))\naxes[1].set_title('Percentage of Schools with Boys Toilet',size = 20 , pad = 20)\naxes[1].set_ylabel('Percentage')\nax2.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)\nfor p in ax2.patches:\n             ax2.annotate(p.get_height(), (p.get_x() + p.get_width() \/ 2., p.get_height()),\n                 ha='center', va='center', fontsize=11.5, color='black', xytext=(0, 8),\n                 textcoords='offset points')\nbtoilet = btoilet[btoilet.State_UT != 'All india']\nbtoilet = btoilet.iloc[:,[0,1,2,5,9,11,12]]\nbtoilet.columns = [str(col) + '_btoil' for col in btoilet.columns]\n\ndf = pd.merge(new_df4, btoilet,  how='left', left_on=['State_UT','Year'], right_on = ['State_UT_btoil','year_btoil'])\n\ndf2 = pd.merge(dnew_df4, btoilet,  how='left', left_on=['State_UT','year'], right_on = ['State_UT_btoil','year_btoil'])\ndthis = ['State_UT_btoil','year_btoil','State_UT_gtoil','year_gtoil','State_UT_electr',\n         'year_electr','State\/UT_water','Year_water','State_UT_comp','year_comp']\ndf = df.drop(dthis, axis=1)\ndf = df.dropna()\n\ndf2 = df2.drop(dthis, axis=1)\ndf2 = df2.dropna()\ndf.head()\n\"\"\"\n**Correlation with Enrollment Ratio**\n\"\"\"\ncorrelation = df.corr()\nplt.figure(figsize = (14,15))\nplt.style.use(\"fivethirtyeight\")\nplt.title(\"Correlations of Enrollment Ratio\")\nsns.heatmap(correlation, annot= False)\ncorrelation['All Schools_comp'].sort_values(ascending=False)\ncorrelation['All Schools_water'].sort_values(ascending=False)\ncorrelation['All Schools_electr'].sort_values(ascending=False)\ncorrelation['All Schools_btoil'].sort_values(ascending=False)\ncorrelation['All Schools_gtoil'].sort_values(ascending=False)\n\"\"\"\n**Correlation with Dropout Ratio**\n\"\"\"\ndf2.head()\ncorrelation2 = df2.corr()\nplt.figure(figsize = (14,15))\nplt.title(\"Correlations of Dropout Ratio\")\nplt.style.use(\"fivethirtyeight\")\nsns.heatmap(correlation2, annot= False)\ncorrelation2['All Schools_comp'].sort_values(ascending=False)\ncorrelation2['All Schools_water'].sort_values(ascending=False)\ncorrelation2['All Schools_electr'].sort_values(ascending=False)\ncorrelation2['All Schools_btoil'].sort_values(ascending=False)\ncorrelation2['All Schools_gtoil'].sort_values(ascending=False)","meta":"{'source': 'AI4Code', 'id': 'ae1f53f4fbcd85'}"}
{"id":"23496","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport csv\nfrom pandas import DataFrame \nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport time\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\"\"\"\n**Read Dataset using Pandas DataFrame**\n\"\"\"\ndf_uber= pd.read_csv('\/kaggle\/input\/uber-pickups-in-new-york-city\/uber-raw-data-jul14.csv')\ndf_uber.head()\ndf_uber.isnull().sum()\n\"\"\"\n**convert data\/time column into DateTime data type**\n\"\"\"\ndf_uber['Date\/Time']=df_uber['Date\/Time'].map(pd.to_datetime)\ndf_uber.info()\ndef get_DateOfMonth(dt):\n    return dt.day \ndef get_weekday(dt):\n    return dt.dayofweek \ndef get_hour(dt):\n    return dt.hour\ndef get_weekday_name(dt):\n    return dt.day_name()\ndf_uber['DOM'] =df_uber['Date\/Time'].map(get_DateOfMonth)\ndf_uber['Weekday'] =df_uber['Date\/Time'].map(get_weekday)\ndf_uber['Hour'] =df_uber['Date\/Time'].map(get_hour)\ndf_uber['DayOfWeek'] =df_uber['Date\/Time'].map(get_weekday_name)\ndf_uber.head()\ndf_pivot_hour = df_uber.pivot_table(index=['Weekday','DayOfWeek'],\n                                  values='Base',\n                                  aggfunc='count')\ndf_pivot_hour.plot(kind='bar', figsize=(8,6))\nplt.ylabel('Day of the week Frequency')\nplt.title('Journeys by Week Day');\n# An \"interface\" to matplotlib.axes.Axes.hist() method\nn, bins, patches = plt.hist(df_uber.DOM.sort_values(), bins='auto', color='#0504aa',\n                            alpha=0.7, rwidth=3.1 , range=(0.5,30.5))\nplt.grid(axis='y', alpha=0.75)\nplt.xlabel('Date of Month')\nplt.ylabel('Frequency')\nplt.title('Frequency of DOM by Uber-July14')\nplt.text(23, 45, r'$\\mu=15, b=3$')\nn, bins, patches = plt.hist(df_uber.Hour, bins='auto', color='#0504aa',\n                            alpha=0.7, rwidth=3.1 , range=(0.5,24))\nplt.grid(axis='y', alpha=0.75)\nplt.xlabel('Date of Month')\nplt.ylabel('Frequency')\nplt.title('Frequency of DOM by Uber-July14')\nplt.text(23, 45, r'$\\mu=15, b=3$')\ndf_uber['Lat'].hist(bins=100, range=(40.4,41.1))\ndf_uber['Lon'].hist(bins=100, range=(-74.2,-73.7))\n\"\"\"\n**Seaborn Kernel Density Estimation (KDE) Plot**\n\n Like the histogram, the KDE plots encode the density of observations on one axis with height along the other axis\n\"\"\"\nf, ax = plt.subplots(figsize=(8,6))\nax = sns.kdeplot(pd.Series(df_uber['DOM'], name=\"Day Of Month\"),shade=True, color='r')\nplt.show()\nf, ax = plt.subplots(figsize=(8,6))\nax = sns.kdeplot(pd.Series(df_uber['Hour'], name=\"Hour\"),shade=True, color='r')\nplt.show()\nf, ax = plt.subplots(figsize=(8,6))\nax = sns.kdeplot(pd.Series(df_uber['Lat'], name=\"Lat\"),shade=True, color='r')\nplt.show()\nf, ax = plt.subplots(figsize=(8,6))\nax = sns.kdeplot(pd.Series(df_uber['Lon'], name=\"Lon\"),shade=True, color='r')\nplt.show()","meta":"{'source': 'AI4Code', 'id': '2b3aac1e0c886e'}"}
{"id":"78430","text":"\"\"\"\n# Introduction\n\n1. Linear Regression\n2. Multiple Regression\n3. Polynomial Regression\n4. Decision Tree\n5. Random Forest\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport operator\n\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.tree import DecisionTreeRegressor, plot_tree\nfrom sklearn.ensemble import RandomForestRegressor\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\n\"\"\"\n# Dataset\n\n## Columns\n\nEach patient is represented in the data set by six biomechanical attributes derived from the shape and orientation of the pelvis and lumbar spine (each one is a column):\n\n* pelvic incidence\n* pelvic tilt\n* lumbar lordosis angle\n* sacral slope\n* pelvic radius\n* grade of spondylolisthesis\n\n\"\"\"\ndata_2c = pd.read_csv(\"\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_2C_weka.csv\")\ndata_3c = pd.read_csv(\"\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_3C_weka.csv\")\ndata = pd.concat([data_2c , data_3c] , axis=0)\ndata.head()\n\"\"\"\n## Describe\n\"\"\"\ndata.info()\ndata.describe().T\ndata[\"class\"].unique()\n\"\"\"\n## Visualize\n\"\"\"\nsns.pairplot(data , hue=\"class\");\nsns.heatmap(data.corr(), annot = True, cmap=\"coolwarm\");\n\"\"\"\n## Preprocessing\n\"\"\"\ndata.drop([\"class\" , \"pelvic_tilt\" , \"pelvic_tilt numeric\" ], axis=1, inplace=True)\ndata.head()\n\"\"\"\n# Linear Regression\n## Data Processing\n\"\"\"\nX, y = data[\"sacral_slope\"].values.reshape(-1,1), data[\"pelvic_incidence\"].values.reshape(-1,1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\"\"\"\n## Create Model & Fit\n\"\"\"\nmodel_lr = LinearRegression()\nmodel_lr.fit(X_train, y_train)\n\"\"\"\n## Get Results\n\"\"\"\nprint(\"intercept : \" , model_lr.intercept_)\nprint(\"slope : \" , model_lr.coef_)\n\"\"\"\n## Predict\n\"\"\"\ny_pred = model_lr.predict(X_test)\ny_pred_df = pd.DataFrame(y_pred, columns=[\"Predicted Response\" ])\ny_test_df = pd.DataFrame(y_test, columns=[\"Real Values\"])\npd.concat([y_test_df , y_pred_df] , axis=1)\n\"\"\"\n## Metrics\n\"\"\"\nscore = r2_score(y_test, y_pred)\nMSE = mean_squared_error(y_test, y_pred)\n\nprint(\"R2 Score : {}\".format(score))\nprint(\"MSE : {}\".format(MSE))\n\"\"\"\n## Visualize\n\"\"\"\nplt.scatter(X_test, y_test , color=\"navy\")\nplt.plot(X_test , y_pred, color=\"orange\")\nplt.xlabel(\"pelvic_incidence\")\nplt.ylabel(\"sacral_slope\")\nplt.show()\n\"\"\"\n# Multiple Linear Regression\n# Preprocessing\n\"\"\"\nX, y = data.drop([\"pelvic_incidence\"] , axis=1) , data[\"pelvic_incidence\"].values.reshape(-1,1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)\n\"\"\"\n## Create Model & Fit\n\"\"\"\nmodel_mlr = LinearRegression()\nmodel_mlr.fit(X_train, y_train)\n\"\"\"\n## Get Results\n\"\"\"\nprint(\"intercept : \" , model_mlr.intercept_)\nprint(\"slope : \" , model_mlr.coef_)\n\"\"\"\n## Predict\n\"\"\"\ny_pred_mlr = model_mlr.predict(X_test)\ny_pred_df = pd.DataFrame(y_pred_mlr, columns=[\"Predicted Response\" ])\ny_test_df = pd.DataFrame(y_test, columns=[\"Real Values\"])\npd.concat([y_test_df , y_pred_df] , axis=1)\n\"\"\"\n## Metrics\n\"\"\"\nscore = r2_score(y_test, y_pred_mlr)\nMSE = mean_squared_error(y_test, y_pred_mlr)\n\nprint(\"R2 Score : {}\".format(score))\nprint(\"MSE : {}\".format(MSE))\n\"\"\"\n# Polynomial Regression\n## Data Preprocessing\n\"\"\"\ndata_2c = pd.read_csv(\"\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_2C_weka.csv\")\ndata_3c = pd.read_csv(\"\/kaggle\/input\/biomechanical-features-of-orthopedic-patients\/column_3C_weka.csv\")\ndata = pd.concat([data_2c , data_3c] , axis=0)\ndata.drop([\"class\" , \"pelvic_tilt\" , \"pelvic_tilt numeric\" ], axis=1, inplace=True)\ndata.head()\ndata = data.sort_values(by=['degree_spondylolisthesis'])\nX, y = data[\"degree_spondylolisthesis\"].values.reshape(-1,1), data[\"pelvic_incidence\"].values.reshape(-1,1)\npoly = PolynomialFeatures(degree=3)\nX_poly = poly.fit_transform(X)\nX_train, X_test, y_train, y_test = train_test_split(X_poly, y, test_size=0.20, random_state=0)\n\"\"\"\n## Create Model & Fit\n\"\"\"\nmodel_poly = LinearRegression()\nmodel_poly.fit(X_train, y_train)\n\"\"\"\n## Get Results\n\"\"\"\nprint(\"intercept : \" , model_poly.intercept_)\nprint(\"slope : \" , model_poly.coef_)\ny_pred_poly = model_poly.predict(X_test)\ny_pred_df = pd.DataFrame(y_pred_poly, columns=[\"Predicted Response\" ])\ny_test_df = pd.DataFrame(y_test, columns=[\"Real Values\"])\npd.concat([y_test_df , y_pred_df] , axis=1)\n\"\"\"\n## Metrics\n\"\"\"\nscore = r2_score(y_test, y_pred_poly)\nMSE = mean_squared_error(y_test, y_pred_poly)\n\nprint(\"R2 Score : {}\".format(score))\nprint(\"MSE : {}\".format(MSE))\n\"\"\"\n## Visualize\n\"\"\"\ny_pred = model_poly.predict(X_poly)\nsorted_zip = sorted(zip(X,y))\nX, y = zip(*sorted_zip)\n\nplt.scatter(X, y , color=\"navy\")\nplt.plot(X , y_pred, color=\"orange\")\nplt.xlabel(\"pelvic_incidence\")\nplt.ylabel(\"sacral_slope\")\nplt.show()\n\"\"\"\n# Decision Tree\n## Preprocessing\n\"\"\"\nX, y = data.drop([\"pelvic_incidence\"] , axis=1) , data[\"pelvic_incidence\"].values.reshape(-1,1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\"\"\"\n## Create Model & Fit\n\"\"\"\ntree = DecisionTreeRegressor()\nmodel_dtree = tree.fit(X_train, y_train)\n\"\"\"\n## Predict\n\"\"\"\ny_pred = model_dtree.predict(X_test)\ny_pred_df = pd.DataFrame(y_pred, columns=[\"Predicted Response\" ])\ny_test_df = pd.DataFrame(y_test, columns=[\"Real Values\"])\npd.concat([y_test_df , y_pred_df] , axis=1)\n\"\"\"\n## Visualize\n\"\"\"\nfig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (17,10) , dpi=500 )\nplot_tree(model_dtree);\n\"\"\"\n## Metrics\n\"\"\"\nscore = r2_score(y_test, y_pred)\nMSE = mean_squared_error(y_test, y_pred)\n\nprint(\"R2 Score : {}\".format(score))\nprint(\"MSE : {}\".format(MSE))\n\"\"\"\n# Random Forest\n## Preprocessing\n\"\"\"\nX, y = data.drop([\"pelvic_incidence\"] , axis=1) , data[\"pelvic_incidence\"].values.reshape(-1,1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\"\"\"\n## Create Model & Fit\n\"\"\"\nmodel_rf = RandomForestRegressor(n_estimators=100)\nmodel_rf.fit(X_train, y_train)\n\"\"\"\n## Predict\n\"\"\"\ny_pred = model_rf.predict(X_test)\ny_pred_df = pd.DataFrame(y_pred, columns=[\"Predicted Response\" ])\ny_test_df = pd.DataFrame(y_test, columns=[\"Real Values\"])\npd.concat([y_test_df , y_pred_df] , axis=1)\n\"\"\"\n## Metrics\n\"\"\"\nscore = r2_score(y_test, y_pred)\nMSE = mean_squared_error(y_test, y_pred)\n\nprint(\"R2 Score : {}\".format(score))\nprint(\"MSE : {}\".format(MSE))","meta":"{'source': 'AI4Code', 'id': '902d693083bfc0'}"}
{"id":"135368","text":"\"\"\"\n### Trending YouTube Video Statistics\nDaily statistics for trending YouTube videos\n\n### Description\nYouTube (the world-famous video sharing website) maintains a list of the top trending videos on the platform. According to Variety magazine, \u201cTo determine the year\u2019s top-trending videos, YouTube uses a combination of factors including measuring users interactions (number of views, shares, comments and likes). Note that they\u2019re not the most-viewed videos overall for the calendar year\u201d. Top performers on the YouTube trending list are music videos (such as the famously virile \u201cGangam Style\u201d), celebrity and\/or reality TV performances, and the random dude-with-a-camera viral videos that YouTube is well-known for.\n\nThis dataset is a daily record of the top trending YouTube videos in USA for several months.\n\"\"\"\n\"\"\"\nFirst we are going to import everything we need to do the analysis\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom datetime import datetime\nimport itertools\nimport json\nimport string\nimport re    #for regex\nimport nltk\nfrom nltk.corpus import stopwords\n\nfrom nltk import pos_tag\nfrom nltk.stem.wordnet import WordNetLemmatizer \nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize import TweetTokenizer \nfrom wordcloud import WordCloud\n\n\nplt.style.use('seaborn-whitegrid')\n# Set Matplotlib defaults\nplt.rc('figure', autolayout=True)\nplt.rc('axes', labelweight='bold', labelsize='large',\n       titleweight='bold', titlesize=14, titlepad=10)\n\"\"\"\nLet's have a look at our dataset! First I will take care of the time format columns; from them I will extract three additional columns that will be helpful for the exploratory analysis (day, hour and month of publication)\n\"\"\"\n\ndata = pd.read_csv(\"..\/input\/youtube-new\/USvideos.csv\",parse_dates=[\"publish_time\"])\ndata.head(3)\n\"\"\"\n### Analyzing the time !\n\"\"\"\n# first convert trending date to datetime format\ndata[\"trending_date\"] = data[\"trending_date\"].apply(lambda x : datetime.strptime(x,\"%y.%d.%m\"))\n# create three columns , using dt function to extract dayofweek, hour and month\ndata[\"publish_day_week\"] = data[\"publish_time\"].dt.dayofweek\ndata[\"publish_hour\"] = data[\"publish_time\"].dt.hour\ndata[\"publish_month\"] = data[\"publish_time\"].dt.month\n\"\"\"\nI will see the evolution of the number of views of the videos over time; for this I use the Rolling function and I group them by week to better appreciate the trend\n\"\"\"\n# groupby trending date by views\ntime = data.groupby(\"trending_date\")[\"views\"].sum()\n\n\n# let,s plot using rolling (7 -> week)\nplt.figure(figsize=(8,4))\nsns.lineplot(data=time.rolling(7).mean(), linewidth=2.5,color=\"#EB7827\",label=\"Weekly\")\nsns.lineplot(data=time, linewidth=2.5,color=\"grey\",alpha=0.2,label=\"Dayly\")\n# using plt.grid and sns.despine you get a cleaner look in the graphics\nplt.grid(None)\nsns.despine()\nplt.title(\"Trending videos: Total views per week \")\nplt.ylabel(\"Total Views\")\n\"\"\"\nFrom April 2018 the sights will go off like a rocket! BTS has surely released a new song :) \n\"\"\"\n# Let's check how many videos there are per year in the dataset; using the same dataframe as before (Time) and reset_index, to facilitate their visualization.\nyear = time.reset_index()\n\n#now with reset_index I have two columns, the number of views and trending_date; as before I use the dt.year function to extract the year and value_counts to count them.\nyear_count = year.trending_date.dt.year.value_counts()\nyear_count.plot(kind=\"bar\",color=[\"#F6794B\",\"#E3E3E3\"])\nplt.xticks(rotation=45)\nplt.title(\"Total videos per year\")\nsns.despine()\nplt.grid(None)\n\"\"\"\nMost videos belong to 2018!\n\nLet's continue with time charts; let's see what day, month and time the videos are usually published!\n\"\"\"\n\"\"\"\nFirst I group the views by day of the week; then I create a dictionary with the days of the week to convert the numbers into strings and make the display more enjoyable\n\"\"\"\n# creating a dict\nnumeros = [*range(7)]\nday = [\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]\ndict_day = {}\nfor key,item in zip(day,numeros):\n   dict_day[item] = key\n# groupby by day of week\nday_week = data.groupby(\"publish_day_week\").size().reset_index()\n# apply dict to publish day week column using map\nday_week[\"publish_day_week\"] = day_week[\"publish_day_week\"].map(dict_day)\n\n# let,s plot \u00a1\u00a1\nplt.figure(figsize=(8,4))\ncolors = [\"#FAEFBE\",\"#FAE0A7\",\"#FAD19E\",\"#FABC96\",\"#EFA492\",\"#18BADA\",\"#6B6D8C\"]\nsns.barplot(x=\"publish_day_week\",y=0,data=day_week,palette=colors,saturation=0.8)\nplt.title(\"Total published videos per day of week\")\nplt.xlabel(\"Day of week\")\nplt.ylabel(\"Total\")\nplt.xticks(rotation=45)\nsns.despine(left=True)\n\"\"\"\nWe see that on weekends the Youtubers tend to rest and they tend to upload more videos on Thursday and Friday. Now I will do the same but with the months of the year\n\"\"\"\nnumeros_a\u00f1o = [*range(1,13)]\nmonth = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec']\n\ndict_month = {}\nfor key,item in zip(month,numeros_a\u00f1o):\n   dict_month[item] = key\n\nmonth_df = data.groupby(\"publish_month\").size().reset_index()\n\nmonth_df[\"publish_month\"] = month_df[\"publish_month\"].map(dict_month)\n\nplt.figure(figsize=(8,4))\n\nsns.barplot(x=\"publish_month\",y=0,data=month_df,palette=\"Paired\",saturation=0.8)\nplt.xlabel(\"Month\")\nplt.ylabel(\"Total\")\nplt.title(\"Total videos per month\")\nplt.xticks(rotation=45)\nsns.despine(left=True)\n\"\"\"\nAhhhh the summer months people prefer to go to the beach or the mountains instead of uploading videos, and it makes a lot of sense, you have to enjoy the good weather!\n\nAnd finally, let's see what time the Youtubers usually upload their videos!\n\"\"\"\nhour = data.groupby(\"publish_hour\").size()\n\nplt.figure(figsize=(8,4))\nsns.barplot(x=hour.index.values,y=hour.values,palette=\"mako_r\")\nsns.despine()\nplt.title(\"Number of videos uploaded per hour\")\n\"\"\"\nThere are many Youtubers who do not sleep at night! The truth is that the night is when it is quieter, there are fewer distractions and noise.\n\"\"\"\n\"\"\"\n### Channels, Youtubers...\nThere is a column in our dataframe called category_id but they are numbers; luckily there is a Json file, where we can find the video categories. \nLet's create, as we did before with the dates, a dictionary of video categories!\n\"\"\"\n# First we load the json file\n\nwith open(\"..\/input\/youtube-new\/US_category_id.json\") as f:\n    data_json = json.load(f)[\"items\"]\n# # how is a json file? well, let,say they are dictionaries within dictionaries..\ndata_json[0]\n# create a dict with titles (we go first to snippet and them title)\ntitle_dict = {}\nfor cat in data_json:\n\n    title_dict[int(cat[\"id\"])] = cat[\"snippet\"][\"title\"]\n    \n# now we use map to apply it to the dataframe so we can work better!\ndata[\"category_id\"] = data[\"category_id\"].map(title_dict)\n# let's see what percentage of videos per category are in our dataframe.\n\n# let's see what percentage of videos per category are in our dataframe. First, with value_counts and normalize we get the relative frequency\ncategorys = data[\"category_id\"].value_counts(normalize=True).reset_index()\n# rename columns names\ncategorys.rename(columns={\"index\":\"Category\",\"category_id\":\"Percentage\"},inplace=True)\n# get percentage\ncategorys[\"Percentage\"] = round(categorys[\"Percentage\"] *100,2)\n# we use style background \u00a1\ncategorys.style.background_gradient(cmap='mako_r')\n\"\"\"\nForty percent of the videos belong to the categories Music and Enterteiment \u00a1\u00a1\n\nIn our dataframe there are columns that we can play with, for example likes, dislikes; we can create new columns like the percentage of likes by views, or the percentage of dislikes by views...\n\"\"\"\n# Well, neither one nor the other, I will do better the sum of both, that is, the percentage of like\/dislikes by views....\ntotal = data[\"likes\"] + data[\"dislikes\"]\n\"\"\"\nOn second thought, I will also take into account the comments; I will create a column that will measure the percentage of user interactions based on the number of views\n\"\"\"\n# let's add up the comments.\ntotal_def = data[\"comment_count\"] + total\n# we created a new column...percentage iterations per view \u00a1\u00a1\u00a1\ndata[\"percentage_iterations_per_view\"] = round((total_def \/ data[\"views\"]) * 100,2)\n\"\"\"\nI created a small function to group, average and sort the following columns (\"views\", \"likes\", \"dislikes\", \"comment_count\", \"percentage_iterations_per_view\")\n\"\"\"\ndef data_views(groupby=\"channel_title\",by=\"percentage_iterations_per_view\",ascending=False):\n    \"\"\"\n    return dataframe groupby channels, showing mean from columns:\n    \"views\",\"likes\",\"dislikes\",\"comment_count\",\"percentage_iterations_per_view\"\n    ,sort by and ascending included\n    \"\"\"\n    return  (data\n            .groupby(groupby)[\"views\",\"likes\",\"dislikes\",\"comment_count\",\"percentage_iterations_per_view\"]\n            .mean()\n            .sort_values(by=by,ascending=ascending)\n            )\n# Let's take a look; these are the channels ordered by \"percentage_iterations_per_view\"\ndata_views().head(10)\n\"\"\"\nThese are the channels with more interactions (likes, dislikes, comments); Daily caller , Desimpedidos or KickThePj for example are the ones that have more; it would be curious to see their theme ...\n\nhttps:\/\/www.youtube.com\/user\/dailycaller\n\"\"\"\n# Which are the channels with more videos in the dataset ?\ntotal_chanel = data.groupby(\"channel_title\")[\"video_id\"].count().sort_values(ascending=False).head(10).reset_index()\ntotal_chanel.rename(columns={\"channel_title\":\"Channel_title\",\"video_id\":\"Total_videos\"},inplace=True)\ntotal_chanel.style.background_gradient(cmap='mako_r')\n# is there any relation between the number of comments and the likes\/dislikes ? well, let's chart it with a scatter plot and with size=\"comment_coun\nplt.figsize=(10,6)\nsns.scatterplot(x=\"likes\",y=\"dislikes\",size=\"comment_count\", hue=\"comment_count\",data=data,alpha=0.7)\nplt.title(\"Relation between the number of comments and the likes\/dislikes\")\nplt.grid(False)\nplt.legend( bbox_to_anchor=(1.05, 1), loc='upper left',fontsize='xx-small')\n\"\"\"\nIf we can see that the greater the increase of both likes and dislikes, the number of comments increases.\n\nLet's check the average, in percentage, of iterations per category\n\"\"\"\nmost_comment_category= data.groupby(\"category_id\")[\"percentage_iterations_per_view\"].mean()                                                                 .sort_values(ascending=False)\n                                    \ncolors = [\"#EAEBE9\" for _ in range(len(most_comment_category))]\ncolors[0] = \"#FD0B3B\"\nplt.figure(figsize=(10,6))\nsns.barplot(x=most_comment_category.index.values,y=most_comment_category.values,palette=colors,saturation=0.8,errwidth=0.4)\nplt.title(\"Average percentage iterations per category\")\nplt.xlabel(\"Categorys\")\nplt.ylabel(\"Percentage iterations\")\nplt.xticks(rotation=45)\nsns.despine(left=True)\n\"\"\"\nWe see that Music, Style or Comedy tend to have the greatest number of iteractions for videos; on the other hand, Politics and Sports do not tend to have as many, which is surprising since they are always controversial topics.\n\"\"\"\n\"\"\"\n### WordCloud\n\nNow finally we will make a WordCloud; it is a very visual and fast way to do text analysis without going into too much detail; let's see what result we get with the titles.\n\"\"\"\n#Setting the stopwords\neng_stopwords = set(stopwords.words(\"english\"))\n\nwordcloud = WordCloud(\n                          background_color='white',\n                          stopwords=eng_stopwords,\n                          max_words=1000,\n                          max_font_size=120, \n                          random_state=42\n                         ).generate(str(data['title']))\n\nprint(wordcloud)\nfig = plt.figure(1)\nplt.imshow(wordcloud)\nplt.title(\"WordCloud Titles\")\nplt.axis('off')\nplt.show()\n\"\"\"\nWell this has been a quick analysis of the videos that are trends in Youtube, in a certain period, in Usa. I hope you liked it, draw your conclusions and if you have any comments or ideas for improvement, please do not hesitate to tell me, it will be of great help to improve!\n\na hug to everyone!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f8d8abdeb2e325'}"}
{"id":"134506","text":"\"\"\"\n# Analisando dados de senten\u00e7as criminais do TJMG\n\"\"\"\n\"\"\"\nOs dados foram obtidos durante o [projeto de classifica\u00e7\u00e3o de senten\u00e7as criminais utilizando aprendizado supervisionado](https:\/\/tjfacil.wordpress.com\/2020\/07\/20\/classificando-sentencas-criminais-utilizando-aprendizado-de-maquina\/) e cont\u00e9m algumas peculiaridades:\n\n- A classifica\u00e7\u00e3o entre senten\u00e7as absolut\u00f3rias, condenat\u00f3rias e neutras foi feita utilizando aprendizado de m\u00e1quinas, com um \u00edndice de acerto de 94 a 97%.\n- As primeiras colunas [\"total_abs\", \"total_con\", e \"total_neu\"] representam o total de senten\u00e7as absolut\u00f3rias, condenat\u00f3rias e neutras de uma determinada vara (linha). Por\u00e9m, esse n\u00famero n\u00e3o significa a soma das demais colunas.\n- As colunas relativas a crimes (por exemplo [\"desacato_abs\", \"desacato_con\" e \"desacato_neu\"]) referem-se \u00e0 contagem do resultado de buscas textuais por aqueles crimes no banco de senten\u00e7as. Isso quer dizer, por exemplo, que as colunas referentes ao crime de desacato n\u00e3o contam a quantidade de senten\u00e7as em que o r\u00e9u foi denunciado pelo crime de desacato, mas a quantidade de senten\u00e7as em que a palavra desacato foi encontrada.\n\"\"\"\n\"\"\"\nImportando bibliotecas e lendo csv.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(\"..\/input\/sentencas.csv\")\n\"\"\"\nPrimeiras linhas:\n\"\"\"\ndf.head()\n\"\"\"\nPrimeiramente, vamos definir a coluna de varas como index, e eliminar algumas linhas de varas que estar\u00e3o fora da an\u00e1lise. Deixaremos de analisar a 6\u00aa e a 11\u00aa Varas Criminais, por possu\u00edrem poucas senten\u00e7as contabilizadas no geral, e as Varas de T\u00f3xicos, para afunilar o estudo nas Varas Criminais comuns.\n\"\"\"\ndf.set_index(\"vara\", drop=True, inplace=True)\ndf_varas = df.drop([\"6\", \"11\", \"t1\", \"t2\", \"t3\"])\n\"\"\"\nUm bom ponto de partida \u00e9 analisar a distribui\u00e7\u00e3o geral das senten\u00e7as classificadas entre absolut\u00f3rias, condenat\u00f3rias e neutras. \n\nComo vemos, entre os dados obtidos, o \u00edndice de condena\u00e7\u00e3o em processos criminais que s\u00e3o sentenciados na comarca de Belo Horizonte \u00e9 superior a 80%:\n\"\"\"\ndf_totais = pd.DataFrame({\n    \"Condena\u00e7\u00f5es\": df_varas[\"total_con\"],\n    \"Absolvi\u00e7\u00f5es\": df_varas[\"total_abs\"],\n    \"Neutras\": df_varas[\"total_neu\"],\n})\n\nfig, axes = plt.subplots(ncols=2, figsize=(18,6))\nfig.suptitle(\"Condena\u00e7\u00f5es x Absolvi\u00e7\u00f5es x Neutras em BH - 2014 a 2019\", fontsize=16)\ndf_totais.sum().sort_values(ascending=False).plot.bar(ax=axes[0], rot=0)\ndf_totais.sum().plot.pie(ax=axes[1], autopct=\"%1.0f%%\")\naxes[1].set_ylabel(\"\");\n\"\"\"\nEsse primeiro n\u00famero parece exageradamente alto e cabem muitas investiga\u00e7\u00f5es a seu respeito, que extrapolam os limites dos dados dispon\u00edveis.\n\nSabendo que a m\u00e9dia geral em Belo Horizonte entre os dados obtidos \u00e9 de 80%, podemos visualizar as distribui\u00e7\u00f5es de cada vara e compar\u00e1-las com a m\u00e9dia municipal.\n\"\"\"\ndf_totais_normal = df_totais.div(df_totais.sum(axis=1), axis=0).multiply(100)\nax = df_totais_normal.plot.bar(figsize=(20,6), title=\"Condena\u00e7\u00f5es x Absolvi\u00e7\u00f5es x Neutras por vara em BH - em % - 2014 a 2019\", rot=0)\nax.grid(\"on\", linewidth=.3)\nax.legend(bbox_to_anchor=(1, 1));\n\"\"\"\nApesar de existir uma varia\u00e7\u00e3o percept\u00edvel entre as varas estudadas (algumas se aproximam dos 70% de condena\u00e7\u00e3o enquanto outras ultrapassam os 90%), ela \u00e9 insuficiente para alterar a percep\u00e7\u00e3o geral dos dados: o n\u00famero de condena\u00e7\u00f5es \u00e9 muito superior ao de absolvi\u00e7\u00f5es.\n\nAlgumas varas tamb\u00e9m apresentam uma grande quantidade de senten\u00e7as neutras, o que pode indicar uma grande quantidade de casos prescritos.\n\nAp\u00f3s analisar a distribui\u00e7\u00e3o de condena\u00e7\u00f5es por varas, podemos visualizar a distribui\u00e7\u00e3o de condena\u00e7\u00f5es nas senten\u00e7as que cont\u00e9m palavras referentes aos crimes selecionados:\n\"\"\"\ndf_crimes = df_varas.drop([\"total_abs\", \"total_con\", \"total_neu\"], axis=1)\ncrimes = set([crime[:-4] for crime in df_crimes.columns])\n\ndf_crimes_totais = pd.DataFrame({\n    crime: [df_crimes[f\"{crime}_con\"].sum(), df_crimes[f\"{crime}_abs\"].sum(), df_crimes[f\"{crime}_neu\"].sum()]\n    for crime in crimes\n}, index=[\"Condena\u00e7\u00f5es\", \"Absolvi\u00e7\u00f5es\", \"Neutras\"])\n\ndf_crimes_totais = df_crimes_totais.transpose()\ndf_crimes_totais = df_crimes_totais.div(df_crimes_totais.sum(axis=1), axis=0).multiply(100)\nax = df_crimes_totais.plot.bar(figsize=(20,6), rot=0, title=\"Condena\u00e7\u00f5es x Absolvi\u00e7\u00f5es x Neutras por crime em BH - em % - 2014 a 2019\")\nax.grid(\"on\", linewidth=.3)\n\"\"\"\n\u00c9 poss\u00edvel perceber que alguns crimes, como o roubo, o furto, o tr\u00e1fico e a corrup\u00e3o, possuem \u00edndices alt\u00edssimos de condena\u00e7\u00e3o, enquanto outros, como a sonega\u00e7\u00e3o, lavagem de dinheiro, estupro e desacato possuem \u00edndices de absolvi\u00e7\u00e3o relativamente altos.\n\nOs \u00edndices de condena\u00e7\u00e3o de crimes como furto, roubo e tr\u00e1fico j\u00e1 s\u00e3o conhecidos do sistema penal brasileiro e seus clientes preferenciais. O alto \u00edndice de condena\u00e7\u00e3o por crimes de corrup\u00e7\u00e3o pode ser explicado pelos recentes epis\u00f3dios pol\u00edticos nacionais. Ironicamente, os \u00edndices de condena\u00e7\u00e3o por sonega\u00e7\u00e3o de impostos e lavagem de dinheiros est\u00e3o entre os mais baixos dispon\u00edveis.\n\nUma considera\u00e7\u00e3o a ser feita \u00e9 que boa parte dos casos de sonega\u00e7\u00e3o e lavagem de dinheiro \u00e9 julgada pela Justi\u00e7a Federal, onde os dados podem ensejar an\u00e1lise diferentes. No TJMG, entretanto, a ironia permanece.\n\nEm se falando dos clientes preferenciais do sistema penal, podemos visualizar a quantidade de senten\u00e7as que cont\u00e9m palavras referentes a cada crime estudado, para verificar quais crimes s\u00e3o mais frequentes nos tribunais de Minas Gerais.\n\"\"\"\ncrimes_count = pd.Series({\n    crime: df_crimes.loc[:,df_crimes.columns.str.startswith(crime)].transpose().sum().sum()\n    for crime in crimes\n})\n\ncrimes_count = crimes_count.div(crimes_count.sum()).multiply(100)\nax = crimes_count.sort_values(ascending=False).plot.bar(figsize=(12,6), rot=0, title=\"Senten\u00e7as por crime em BH - em % - 2014 a 2019\")\nax.grid(\"on\", linewidth=.3)\n\"\"\"\nComo esperado, processos referentes aos crimes de roubo e furto representam a maior parte dos casos julgados pela Justi\u00e7a Estadual. Aqui, como antes, cabe explicar que os crimes de tr\u00e1fico de drogas, e outros correlatos, s\u00e3o julgados em Belo Horizonte pelas Varas Especializadas em T\u00f3xicos, que n\u00e3o s\u00e3o objeto de nossa an\u00e1lise nesse momento.\n\nProsseguindo para uma an\u00e1lise mais detalhada, \u00e9 poss\u00edvel visualizar, para cada vara, a distribui\u00e7\u00e3o de condena\u00e7\u00f5es e absolvi\u00e7\u00f5es para cada um dos crimes estudados, o que permite embasar investiga\u00e7\u00f5es sobre as inclina\u00e7\u00f5es de cada ju\u00edzo sobre determinados assuntos.\n\"\"\"\ndef plot_crimes_vara_ax(vara, ax):\n    df_crimes = df_varas.drop([\"total_abs\", \"total_con\", \"total_neu\"], axis=1)\n    crimes = set([crime[:-4] for crime in df_crimes.columns])\n    df_vara = df_crimes.filter(vara, axis=0)\n    df_crimes_vara = pd.DataFrame({\n        crime: [df_vara[f\"{crime}_con\"].sum(), df_vara[f\"{crime}_abs\"].sum(), df_vara[f\"{crime}_neu\"].sum()]\n        for crime in crimes\n    }, index=[\"Condena\u00e7\u00f5es\", \"Absolvi\u00e7\u00f5es\", \"Neutras\"])                      \n    df_crimes_vara = df_crimes_vara.div(df_crimes_vara.sum()).multiply(100)\n    _ax = df_crimes_vara.transpose().plot.bar(ax=ax, rot=0, title=vara)\n    ax.legend(bbox_to_anchor=(1, 1))\n    _ax.grid(\"on\", linewidth=.3)\n_varas = [\"1\", \"4\", \"8\", \"9\"]\nfig, axes = plt.subplots(nrows=len(_varas), figsize=(20,13))\nfor i, vara in enumerate(_varas):\n    plot_crimes_vara_ax(vara, axes[i])\n\"\"\"\nCom esses gr\u00e1ficos pode-se propor, por exemplo, que o ju\u00edzo da Primeira Vara Criminal possui uma tend\u00eancia a absolver os acusados em casos de desacato, lavagem de dinheiro e sonega\u00e7\u00e3o, enquanto o ju\u00edzo da Oitava Vara Criminal mant\u00e9m ind\u00edces de condena\u00e7\u00e3o alt\u00edssimos em todos os crimes, sendo o seu maior \u00edndice de absolvi\u00e7\u00f5es em casos de estupro. \n\nAqui ainda cabe outra observa\u00e7\u00e3o. Como as categorias de cada crime apresentadas na verdade significam a quantidade de senten\u00e7as entre as dispon\u00edveis nas quais foram encontradas palavras sobre aquele crime, podemos atribuir significado aos n\u00fameros apresentados sob o t\u00edtulo de hom\u00edcio, ainda que as varas estudadas n\u00e3o possuam compet\u00eancia para o julgamento de crimes culposos contra a vida. Nesse sentido, por exemplo, a palavra homic\u00eddio pode aparecer nas senten\u00e7as ao se analisar a vida pregressa do acusado, o que indica que, nesses casos, h\u00e1 um alt\u00edssimo grau de condena\u00e7\u00e3o entre todas as varas apresentadas.\n\nAssim como fizemos acima, tamb\u00e9m \u00e9 poss\u00edvel apresentar agrupadamente a distribui\u00e7\u00e3o de condena\u00e7\u00f5es de cada vara para os crimes estudados:\n\"\"\"\ndef plot_varas_crime_ax(crime, ax):\n    df_crime = df_crimes.loc[:, df_crimes.columns.str.startswith(crime)]\n    df_crime = df_crime[[f\"{crime}_con\", f\"{crime}_abs\", f\"{crime}_neu\"]]\n    df_crime = df_crime.rename({f\"{crime}_con\": \"Condena\u00e7\u00f5es\", f\"{crime}_abs\": \"Absolvi\u00e7\u00f5es\", f\"{crime}_neu\": \"Neutras\"}, axis=1)\n    df_crime = df_crime.div(df_crime.sum(axis=1), axis=0).multiply(100)\n    ax = df_crime.plot.bar(ax=ax, rot=0, title=crime)\n    ax.grid(\"on\", linewidth=.3)\n    ax.legend(bbox_to_anchor=(1, 1))\n    ax.axes.get_xaxis().get_label().set_visible(False)\n_crimes = [\"corrupcao\", \"estelionato\", \"estupro\", \"desacato\"]\nfig, axes = plt.subplots(nrows=len(_crimes), figsize=(20,13))\nfig.suptitle(\"Condena\u00e7\u00f5es x Absolvi\u00e7\u00f5es x Neutras por vara - em % - 2014 a 2019\", fontsize=16)\nfor i, crime in enumerate(_crimes):\n    plot_varas_crime_ax(crime, axes[i])\n\"\"\"\nCom esses gr\u00e1ficos, visualiza-se por exemplo que a Primeira, a Quinta e a S\u00e9tima Varas Criminais possuem uma tend\u00eancia maior que as demais de absolver casos de desacato, enquanto a Quinta Vara Criminal lidera as absolvi\u00e7\u00f5es em casos que se referem ao crime de estupro.\n\nOs dados apresentados e outros decorrentes dessa esp\u00e9cie de an\u00e1lise podem servir tanto para embasar a tomada de decis\u00e3o estrat\u00e9gica de advogados, como tamb\u00e9m para o estudo mais aprofundado do judici\u00e1rio.\n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f74f5d013983b4'}"}
{"id":"89672","text":"# 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 in \n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\nimport os\n\n# Time\nimport time\nimport datetime\n\n# Numerical\nimport numpy as np\nimport pandas as pd\n\n# Tools\nimport itertools\nfrom collections import Counter\n\n# NLP\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\n\n# Preprocessing\nfrom sklearn import preprocessing\nfrom sklearn.utils import class_weight as cw\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\n# Model Selection\nfrom sklearn.model_selection import train_test_split\n\n# Evaluation Metrics\nfrom sklearn import metrics \nfrom sklearn.metrics import f1_score, accuracy_score,confusion_matrix,classification_report\n\n# Deep Learing Preprocessing - Keras\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing import sequence\nfrom keras.utils import to_categorical\n\n# Deep Learning Model - Keras\nfrom keras.models import Model\nfrom keras.models import Sequential\n\nfrom keras.layers import Dense, Embedding\nfrom keras.models import Sequential\n\n# Deep Learning Model - Keras - RNN\nfrom keras.layers import Embedding, LSTM, Bidirectional\n\n# Deep Learning Model - Keras - General\nfrom keras.layers import Input, Add, concatenate, Dense, Activation, BatchNormalization, Dropout, Flatten\nfrom keras.layers import LeakyReLU, PReLU, Lambda, Multiply\n\nfrom keras.preprocessing import sequence\nfrom keras import regularizers\n\n# Deep Learning Parameters - Keras\nfrom keras.optimizers import RMSprop, Adam\n\n# Visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom fastai.imports import *\nfrom fastai.text import *\npath = Path(os.path.abspath(os.curdir))\n#File Import\nfilepath = Path('..\/input')\ndf = pd.read_csv(filepath\/'Tweets.csv')\ndf.head()\n\"\"\"\n## Transfer Learning\n#### Loading pre-trained language model and fine-tuning\n\"\"\"\ndf = df[['airline_sentiment','text']]\ndf.head()\ntrain = df[:int(len(df)*.99)]\nvalid = df[int(len(df)*.99):]\nlm_dat = TextLMDataBunch.from_df(path, train, valid)\nlm_dat.save('data_lm_export.pkl')\nlm_learn = language_model_learner(lm_dat, AWD_LSTM, drop_mult=0.4)\nlm_learn.lr_find()\nlm_learn.recorder.plot()\nlm_learn.fit_one_cycle(4, 1e-2)\nlm_learn.unfreeze()\nlm_learn.lr_find(); lm_learn.recorder.plot()\nlm_learn.fit_one_cycle(4, 1e-3)\n#Encoder\nlm_learn.save_encoder('ft_enc')\n\"\"\"\n## Fine-tuning Classifier \n\n\"\"\"\n#Splitting the dataset in 80:20 ratio\ntrain = df[:int(len(df)*.80)]\nvalid = df[int(len(df)*.80):]\n# Classifier model data\ndata_clas = TextClasDataBunch.from_df(path, train, valid, vocab=lm_dat.train_ds.vocab, bs=32)\ndata_clas.save('data_clas_export.pkl') ; data_clas = load_data(path, 'data_clas_export.pkl', bs=16)\n#Building a classifier with fine-tuned encoder \nlm_learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=.3, metrics=[accuracy,Precision(average='weighted'),Recall(average='weighted')])\nlm_learn.load_encoder('ft_enc')\ndata_clas.show_batch()\nlm_learn.lr_find()\nlm_learn.recorder.plot()\nlm_learn.fit_one_cycle(4, 1e-2)\nlm_learn.freeze_to(-2)\nlm_learn.fit_one_cycle(4, slice(1e-3\/(2.6**4), 1e-3))\n#unfreezing the model and fine-tuning it\nlm_learn.unfreeze()\nlm_learn.fit_one_cycle(8, slice(1e-5\/(2.6**4),1e-5))\nlm_learn.save('final')\n#Obtaining Test Accuracy\nvalid['pred_sentiment'] = valid['text'].apply(lambda row: str(lm_learn.predict(row)[0]))\nprint(\"Test Accuracy: \", accuracy_score(valid['airline_sentiment'], valid['pred_sentiment']))\n\"\"\"\n## References\n[1] \u201cApplication to NLP, including ULMFiT fine-tuning,\u201d text | fastai. [Online]. Available: https:\/\/docs.fast.ai\/text.html#Text-models,-data,-and-training. [Accessed: 24-Jul-2019].\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a473746466fec9'}"}
{"id":"113474","text":"# 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 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\n\"\"\"\n* It can be used as a dimensionality reduction method, which can help to minimize the number of the variables (or columns of a data frame) without losing much of the original information. This is useful especially when you are building machine learning models based on the data with many variables like 100s or 1000s.\n\"\"\"\n\"\"\"\n* It is an unsupervised stastical technique used to examine the interrelations among a set of variables in order to identify the underlying structure of those variables\n\n* It is also known as general factor analysis\n\n* While regression determines a line of best fit to a dataset, factor analysis or principal component analysis determines several orthogonal lines of best fit to the dataset.Orthogonal means at right angles. The lines are perpendicular to each other in n dimensional space where n dimensional space is the variable sample space. There as many dimensions as there are variables,i.e., a dataset with 4 variables the sample space is 4 dimensional.\n\n* If we use this technique on a dataset with large numbers of variables, we can compress the amount of explained variation to just a few components.\n\n\n\"\"\"\n\"\"\"\n* PCA is just a transformation of our data and attempts to find out what features excplain the most variance in our data\n\n* We try to get rid of the components that do not explain enough the variance in our data.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nfrom sklearn.datasets import load_breast_cancer\ncancer=load_breast_cancer()\ncancer.keys()\n#This is a special type of dataset of sklearn\nprint(cancer[\"DESCR\"])\n\"\"\"\n* The data contains 569 rows and 30 variables or columns\n\n* What we are going to do is to figure out what compenents are important to explain the variance of the data.\n\"\"\"\ncancer[\"data\"]\n# This is the data\ncancer[\"feature_names\"]\n#This is the feature names of the data\n\"\"\"\n* Now we are going to combine the feature names with the data and make a dataframes\n\"\"\"\ndf=pd.DataFrame(cancer[\"data\"],columns=cancer[\"feature_names\"])\ndf.head()\n\"\"\"\n* In this dataset, there are 30 dimensions or variables, thus it is difficult to visualize all of them. We can utilize PCA to learn the two most important components of the data and visualize the data in this new two dimensional space. \n\"\"\"\n\"\"\"\n* Before we use PCA in the data, we need to standartize the variables by using standart scaler of sklearn\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\nscaler.fit(df)\nscaled_data=scaler.transform(df)\nscaled_data \n\"\"\"\n* Standart Scaler transformed our data into a numpy array and standartized all of the variables of the data \n\"\"\"\nfrom sklearn.decomposition import PCA\npca=PCA(n_components=2) # we make an instance of PCA and decide how many components we want to have\n\npca.fit(scaled_data) # We make PCA fit to our scaled data\ntransformed_data=pca.transform(scaled_data)\nscaled_data.shape\n#This is the original shape of the data with 569 rows and 30 columns\ntransformed_data.shape\n#Here we see 569 rows but 2 columns or components after PCA implementation\ntransformed_data\n\"\"\"\n* The data has been reduced to the two most important components via PCA that we can easily plot out.\n\"\"\"\nplt.figure(figsize=(15,10))\nplt.scatter(transformed_data[:,0],transformed_data[:,1])\nplt.xlabel(\"The First Principal Component\")\nplt.ylabel(\"The Second Principal Component\")\n#Here we plot all the rows of columns 1 and column 2 in a scatterplot.\n\"\"\"\n* This plot does not explain much, we can add some paramaters to the same plot in order to show the positions of the components according the target variable of the data\n\"\"\"\nplt.figure(figsize=(15,10))\nplt.scatter(transformed_data[:,0],transformed_data[:,1],c=cancer[\"target\"],cmap=\"plasma\")\nplt.xlabel(\"The First Principal Component\")\nplt.ylabel(\"The Second Principal Component\")\n#Here we plot all the rows of columns 1 and column 2 in a scatterplot.\n\"\"\"\n* This plot shows the power of PCA because based on just two principal components, we can see very clear separation of the target variable, which shows how benign and malignant tumors look like.\n\n* We utilize PCA as compression algorithm to get a clear information about the data instead of analyzing 30 columns or variables as it is case in this dataset.\n\n* However the components that has been decided by PCA do not correspond to a specific column or variable in the dataset.These two components are the combinations of the original variables of the data.\n\"\"\"\npca.components_\n\"\"\"\n* Each row represents actual componnents and each column relates back original features.\n\n* We can see the relationship better via a heatmap.\n\n* But first we need to transfor it into a dataframe in order to use the visualization libraries.\n\"\"\"\ndf_comp=pd.DataFrame(pca.components_,columns=cancer[\"feature_names\"])\ndf_comp\nplt.figure(figsize=(15,10))\nsns.heatmap(df_comp,cmap=\"magma\")\n\"\"\"\n* In this heatmap above, we see the relation between the principal components and actual features\n\n* The ligh color in the heatmap shows strong correlation between the principal components and actual features while dark colors show the opposite or negative correlation.\n\n* Actually the principal components are the combinations of all these features of the data.\n\"\"\"\n\"\"\"\n* After we get the principal components of the data, we can feed them into a machine learning algorithm because we have clear and separated components of the data instead of the complex variables.\n\n* For this data we do a logistic regression on tranformed_data instead of doing regression with the entire data.\n\n* Support vector machines can also be a good alternative for this data.\n\"\"\"\nX=transformed_data\ny=cancer[\"target\"]\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=101)\nfrom sklearn.linear_model import LogisticRegression\nlog_regression=LogisticRegression()\nlog_regression.fit(X_train,y_train)\n#Now our model is ready to predict the test data\npredictions=log_regression.predict(X_test)\npredictions\n#Now it is time to evaluate how good the predictions are\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test,predictions))\n#The precision and accuracy precentages are over %90, it is very good\n\"\"\"\n* It is obvious that we can get pretty good prediction by using just the two principal components of the data instead of using all of the dataset.\n\n* PCA can be very useful tool big data with many features.\n\"\"\"\n\"\"\"\n* Now we will also use Support Vector Machines Algorithm with the PCA\n\"\"\"\n\"\"\"\n* Because we have already siplitted data in the previous algorithm, we just skip this stage\n\"\"\"\nfrom sklearn.svm import SVC\nsvm_model=SVC()\nsvm_model.fit(X_train,y_train)\npredictions=svm_model.predict(X_test)\npredictions\nfrom sklearn.metrics import classification_report,confusion_matrix\nprint(classification_report(y_test,predictions))\n#here we get the classification report to learn how accurate our model is\n\"\"\"\n* The precision and accuracy precentages are over %90, it is very good although it is not as good as logistic regression\n\"\"\"\n\"\"\"\nIt is obvious that we can get pretty good prediction by using just the two principal components of the data instead of using all of the dataset.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'd087944e6ca8e0'}"}
{"id":"64146","text":"\"\"\"\n# import\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns \n%matplotlib inline\n\n# \u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u044b\u0439 \u0443\u0434\u043e\u0431\u043d\u044b\u0439 \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0440\u0430\u0437\u0434\u0435\u043b\u0435\u043d\u0438\u044f \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0430:\nfrom sklearn.model_selection import train_test_split\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\n# \u0432\u0441\u0435\u0433\u0434\u0430 \u0444\u0438\u043a\u0441\u0438\u0440\u0443\u0439\u0442\u0435 RANDOM_SEED, \u0447\u0442\u043e\u0431\u044b \u0432\u0430\u0448\u0438 \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u044b \u0431\u044b\u043b\u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u044b!\nRANDOM_SEED = 42\n# \u0437\u0430\u0444\u0438\u043a\u0441\u0438\u0440\u0443\u0435\u043c \u0432\u0435\u0440\u0441\u0438\u044e \u043f\u0430\u043a\u0435\u0442\u043e\u0432, \u0447\u0442\u043e\u0431\u044b \u044d\u043a\u0441\u043f\u0435\u0440\u0438\u043c\u0435\u043d\u0442\u044b \u0431\u044b\u043b\u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u044b:\n!pip freeze > requirements.txt\n\"\"\"\n# DATA\n\"\"\"\nDATA_DIR = '\/kaggle\/input\/sf-dst-restaurant-rating\/'\ndf_train = pd.read_csv(DATA_DIR+'\/main_task.csv')\ndf_test = pd.read_csv(DATA_DIR+'kaggle_task.csv')\nsample_submission = pd.read_csv(DATA_DIR+'\/sample_submission.csv')\ndf_cities = pd.read_csv('..\/input\/world-cities\/worldcities.csv')\ndf_cost=pd.read_csv('\/kaggle\/input\/2020-cost-of-living\/cost of living 2020.csv')\ndf_cities.info()\ndf_cost.info()\ndf_train.info()\ndf_train.head(5)\ndf_test.info()\ndf_test.head(5)\nsample_submission.head(5)\nsample_submission.info()\n# \u0412\u0410\u0416\u041d\u041e! \u0434\u0440\u044f \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0439 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0442\u0440\u0435\u0439\u043d \u0438 \u0442\u0435\u0441\u0442 \u0432 \u043e\u0434\u0438\u043d \u0434\u0430\u0442\u0430\u0441\u0435\u0442\ndf_train['sample'] = 1 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0440\u0435\u0439\u043d\ndf_test['sample'] = 0 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0435\u0441\u0442\ndf_test['Rating'] = 0 # \u0432 \u0442\u0435\u0441\u0442\u0435 \u0443 \u043d\u0430\u0441 \u043d\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f Rating, \u043c\u044b \u0435\u0433\u043e \u0434\u043e\u043b\u0436\u043d\u044b \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u0442\u044c, \u043f\u043e \u044d\u0442\u043e\u043c\u0443 \u043f\u043e\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u043e \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043d\u0443\u043b\u044f\u043c\u0438\n\ndata = df_test.append(df_train, sort=False).reset_index(drop=True) # \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c\ndata.info()\n\"\"\"\n\u041f\u043e\u0434\u0440\u043e\u0431\u043d\u0435\u0435 \u043f\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u043c:\n* City: \u0413\u043e\u0440\u043e\u0434 \n* Cuisine Style: \u041a\u0443\u0445\u043d\u044f\n* Ranking: \u0420\u0430\u043d\u0433 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430 \u043e\u0442\u043d\u043e\u0441\u0438\u0442\u0435\u043b\u044c\u043d\u043e \u0434\u0440\u0443\u0433\u0438\u0445 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u044d\u0442\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435\n* Price Range: \u0426\u0435\u043d\u044b \u0432 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0435 \u0432 3 \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f\u0445\n* Number of Reviews: \u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043e\u0442\u0437\u044b\u0432\u043e\u0432\n* Reviews: 2 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0445 \u043e\u0442\u0437\u044b\u0432\u0430 \u0438 \u0434\u0430\u0442\u044b \u044d\u0442\u0438\u0445 \u043e\u0442\u0437\u044b\u0432\u043e\u0432\n* URL_TA: \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430 \u043d\u0430 'www.tripadvisor.com' \n* ID_TA: ID \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430 \u0432 TripAdvisor\n* Rating: \u0420\u0435\u0439\u0442\u0438\u043d\u0433 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430\n\"\"\"\ndata.sample(5)\ndata.Reviews[1]\n\"\"\"\n\u041a\u0430\u043a \u0432\u0438\u0434\u0438\u043c, \u0431\u043e\u043b\u044c\u0448\u0438\u043d\u0441\u0442\u0432\u043e \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432 \u0443 \u043d\u0430\u0441 \u0442\u0440\u0435\u0431\u0443\u0435\u0442 \u043e\u0447\u0438\u0441\u0442\u043a\u0438 \u0438 \u043f\u0440\u0435\u0434\u0432\u0430\u0440\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0439 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438.\n\"\"\"\n\"\"\"\n## 1. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 NAN \n\u0418 \u0442\u0430\u043a, \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u0435\u0441\u0442\u044c \u0432 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0445 \u0441\u0442\u043e\u043b\u0431\u0446\u0430\u0445:\n* Cuisine Style\n* Price Range\n* Number of Reviews\n* Reviews\n\"\"\"\n\"\"\"\n\u041a\u0430\u043a\u0438\u0435 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u044b \u043a\u0443\u0445\u043d\u0438 \u0441\u0430\u043c\u044b\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435?\n\"\"\"\ndata['Cuisine Style']=data['Cuisine Style'].fillna(\"['no_data']\") #\u0437\u0430\u043c\u0435\u043d\u044f\u0435\u043c \u043f\u0440\u043e\u043f\u0443\u0441\u043a \u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u043c \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435\u043c\ndef make_a_list (line):\n    line=line[1:-1]\n    line=line.replace(\"'\", \"\")\n    line=line.split(', ')\n    return (line)\ncousine_list=[]\ndata['Cuisine Style']=data['Cuisine Style'].apply(make_a_list)\ndata['Cuisine Style'].apply(lambda x: cousine_list.extend(x))\nfrom collections import Counter\nCounter(cousine_list).most_common(3)\n\"\"\"\n\u0417\u0430\u043c\u0435\u043d\u044f\u0435\u043c 'no_data' \u043d\u0430 \u0434\u0432\u0430 \u0441\u0430\u043c\u044b\u0445 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n\"\"\"\ndef replacement (line):\n    if line == ['no_data']:\n        return ['European', 'Vegetarian Friendly']\n    else:\n        return line\ndata['Cuisine Style']=data['Cuisine Style'].apply(replacement)\ncousine_list=[]\ndata['Cuisine Style'].apply(lambda x: cousine_list.extend(x))\nCounter(cousine_list).most_common(5)\n\"\"\"\n\u0421\u0430\u043c\u0430\u044f \u0440\u0430\u0441\u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0451\u043d\u043d\u0430\u044f \u0446\u0435\u043d\u043e\u0432\u0430\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f:\n\"\"\"\ndata['Price Range'].value_counts()\n\"\"\"\n\u0421\u0440\u0435\u0434\u043d\u044f\u044f \u0446\u0435\u043d\u043e\u0432\u0430\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f \u0441\u0430\u043c\u0430\u044f \u0440\u0430\u0441\u043f\u0440\u043e\u0441\u0442\u0440\u0430\u043d\u0451\u043d\u043d\u0430\u044f. \u041d\u0430 \u043d\u0435\u0435 \u0438 \u0437\u0430\u043c\u0435\u043d\u0438\u043c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438.\n\"\"\"\ndata['Price Range']=data['Price Range'].fillna('$$ - $$$')\n\"\"\"\n\u0427\u0442\u043e \u0441 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e\u043c \u043e\u0442\u0437\u044b\u0432\u043e\u0432? \u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0440\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435. \u041d\u0430\u0439\u0434\u0451\u043c \u0441\u0440\u0435\u0434\u043d\u0435\u0435, \u043c\u0435\u0434\u0438\u0430\u043d\u0443 \u0438 \u043c\u043e\u0434\u0443.\n\"\"\"\ndata['Number of Reviews'].hist()\n\"\"\"\n\u0420\u0430\u0441\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u0438\u0435 \u043d\u0435 \u043f\u043e\u0445\u043e\u0436\u0435 \u043d\u0430 \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e\u0435. \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u043f\u043e\u0442\u043e\u043c \u043f\u0440\u0438\u0434\u0451\u0442\u0441\u044f \u043e\u0447\u0438\u0449\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435 \u043e\u0442 \u0432\u044b\u0431\u0440\u043e\u0441\u043e\u0432.\n\"\"\"\nprint(data['Number of Reviews'].mean(), data['Number of Reviews'].median())\ndata['Number of Reviews'].value_counts(ascending=False)\n\"\"\"\n\u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u043d\u0435 \u0442\u0430\u043a \u0443\u0436 \u0438 \u043c\u043d\u043e\u0433\u043e. \u0414\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u0437\u0430\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438 \u043c\u043e\u0434\u043e\u0439 - \u043d\u0443\u043b\u0435\u0432\u044b\u043c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\u043c.\n\"\"\"\ndata['Number of Reviews'].fillna(0, inplace=True)\n\"\"\"\n\u041f\u0440\u043e\u043f\u0443\u0441\u043a\u0438, \u0430 \u0437\u0430 \u043e\u0434\u043d\u043e \u0438 \u043f\u0443\u0441\u0442\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u044f \u043f\u043e\u043a\u0430 \u0447\u0442\u043e \u0437\u0430\u043c\u0435\u043d\u044e \u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u043e\u0439.\n\"\"\"\ndata['Reviews']=data['Reviews'].fillna(\"[['no_data'], ['no_date']]\")\ndata['Reviews']=data['Reviews'].apply(lambda x: x.replace(\"[[], []]\", \"[['no_data'], ['no_date']]\"))\n\"\"\"\n### 2. \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432\n\u0414\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043a\u0430\u043a\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0443 \u043d\u0430\u0441 \u043c\u043e\u0433\u0443\u0442 \u0431\u044b\u0442\u044c \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0430\u043b\u044c\u043d\u044b\u043c\u0438.\n\"\"\"\ndata.sample(5)\n\"\"\"\n#### \u0412\u043e\u0437\u044c\u043c\u0435\u043c \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a \"Price Range\".\n\"\"\"\ndef sign_to_range (x):\n    if x == \"$\":\n        return 1\n    elif x == \"$$ - $$$\":\n        return 2.5\n    else:\n        return 4\ndata['Price Range']=data['Price Range'].apply(sign_to_range)\n\"\"\"\nCuisine Style. \u041f\u043e\u0441\u043b\u0435 \u0437\u0430\u043c\u0435\u043d\u044b \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043e\u0432 \u0432 \u044f\u0447\u0435\u0439\u043a\u0430\u0445 \u044d\u0442\u043e\u0433\u043e \u0441\u0442\u043e\u043b\u0431\u0446\u0430 \u043b\u0435\u0436\u0430\u0442 \u0441\u043f\u0438\u0441\u043a\u0438. \u0414\u043e\u0431\u0430\u0432\u0438\u043c Dummie-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u043a \u043d\u0430\u0438\u0431\u043e\u043b\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u043c \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u0430\u043c \u043a\u0443\u0445\u043e\u043d\u044c. \u041d\u0430\u0438\u043c\u0435\u043d\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435 \u043e\u0442\u043d\u0435\u0441\u0435\u043c \u043a \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u0443 \"others\".\n\"\"\"\n#\u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u0437\u0430\u043d\u043e\u0432\u043e \u0441\u0444\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u0441\u043f\u0438\u0441\u043e\u043a \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u0432 \u043a\u0443\u0445\u043d\u0438.\ncousine_list=[]\ndata['Cuisine Style'].apply(lambda x: cousine_list.extend(x))\n#\u0422\u0435\u043f\u0435\u0440\u044c \u043f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c, \u043a\u0430\u043a\u0438\u0435 \u043a\u0443\u0445\u043d\u0438 \u043d\u0430\u0438\u0431\u043e\u043b\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b, \u0430 \u043a\u0430\u043a\u0438\u0435 - \u043d\u0435\u0442.\nCounter(cousine_list).most_common(150)\n\"\"\"\n\u041c\u044b, \u0432\u0435\u0434\u044c, \u043d\u0435 \u0431\u0443\u0434\u0435\u043c \u0441\u043f\u043e\u0440\u0438\u0442\u044c \u0441 \u0442\u0435\u043c, \u0447\u0442\u043e 'Vegetarian Friendly' - \u044d\u0442\u043e \u043d\u0435 \u0442\u043e \u0436\u0435, \u0447\u0442\u043e 'Vegan Options', \u0430 'Japanese' - \u043d\u0435 \u0442\u043e \u0436\u0435, \u0447\u0442\u043e 'Sushi'. \u041d\u0435 \u0432\u0438\u0436\u0443 \u0441\u043c\u044b\u0441\u043b\u0430 \u0432\u0432\u043e\u0434\u0438\u0442\u044c \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u043e\u043f\u0446\u0438\u0438, \u0447\u0442\u043e\u0431\u044b \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0442\u044c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u0441\u043f\u0438\u0441\u043a\u0430 \u043f\u043e\u0434 \u043e\u0434\u043d\u0438\u043c \u0437\u0430\u0433\u043e\u043b\u043e\u0432\u043a\u043e\u043c. \u0410, \u0432\u043e\u0442, \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u0442\u044c, n (\u0447\u0438\u0441\u043b\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u043e \u043f\u0440\u0438 \u043e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u0446\u0438\u0438) \u043d\u0430\u0438\u043c\u0435\u043d\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0445 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u0432 \u0432 \u043e\u0434\u0438\u043d - 'others' - \u0432\u0441\u0451 \u0436\u0435 \u0441\u0442\u043e\u0438\u0442.\n\"\"\"\ntop=list(pd.Series(dict((Counter(cousine_list).most_common(70)))).index) #\u041e\u0447\u0435\u043d\u044c \u0441\u0442\u0440\u0430\u043d\u043d\u044b\u0439 \u043a\u043e\u0441\u0442\u044b\u043b\u044c, \u0447\u0442\u043e\u0431\u044b \u0441\u0444\u043e\u0440\u043c\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0441\u0430\u043c\u044b\u0445 \u0447\u0430\u0441\u0442\u044b\u0445 \u043a\u0443\u0445\u043e\u043d\u044c.\nothers=(list(set(cousine_list)-set(top))) # \u0444\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0441\u0430\u043c\u044b\u0445 \u0440\u0435\u0434\u043a\u0438\u0445 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u0432\ndef other(cuisines):\n    for cuisine in cuisines:\n        if cuisine in others:\n            return 'other'\n        else:\n            return cuisine\n\ndata['Cuisine Style']=data['Cuisine Style'].apply(other) # \u043c\u0435\u043d\u044f\u0435\u043c \u043d\u0430\u0438\u043c\u0435\u043d\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u044b \u043d\u0430 \"other\"\ndummi_cuisine=pd.get_dummies(data['Cuisine Style'].apply(pd.Series).stack()).sum(level=0) # \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u0441\u0435\u0442 dummie-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\ndata=pd.concat([data,dummi_cuisine], axis=1) # \u0421\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0441 \u0441\u0435\u0442\u043e\u043c \"data\"\ndata['Cuisine Style']=data['Cuisine Style'].apply(lambda x: len(x)) # \u0412 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0435 \u044f\u0447\u0435\u0439\u043a\u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c \u043d\u043e\u0432\u044b\u0439 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\ndata.sample(2) #\u0441\u043c\u043e\u0442\u0440\u0438\u043c, \u0447\u0442\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c\n\"\"\"\n\u041e\u0442\u0437\u044b\u0432\u044b. \u0421\u0430\u043c\u044b\u0439 \u0441\u043b\u043e\u0436\u043d\u044b\u0439 \u0441 \u0442\u043e\u0447\u043a\u0438 \u0437\u0440\u0435\u043d\u0438\u044f \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0438 \u0444\u043e\u0440\u043c\u0430\u0442 \u0434\u0430\u043d\u043d\u044b\u0445.\n\"\"\"\ndata['Reviews']=data['Reviews'].replace(\"[[], []]\", \"[['no_review'], ['01\/01\/2000']]\") #\u0417\u0430\u043c\u0435\u043d\u044f\u0435\u043c \u043f\u0443\u0441\u0442\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0442\u0435\u0445\u043d\u0438\u0447\u0435\u0441\u043a\u0438\u043c\u0438.\nrev_dict=set()\ndef Reviews_reader(line):\n    line=line[2:-2]\n    line=line.split('], [')\n    line[0]=line[0].split(', ')\n    line[1]=line[1].split(', ')\n   \n    for rev in line[0]:\n        rev=(rev[1:-1]).lower()\n        rev=rev.replace('!','')\n        rev=rev.replace('.','')\n        rev=rev.split(' ')\n        for word in rev:\n            rev_dict.add(word)\n    return(line)\ndata['Reviews']=data['Reviews'].apply(Reviews_reader)\nrev_dict\nword_in_review={'Good':['gusto','nya','bellisimo','dequate','pleasantly','wunderfull','delucious','excellient','picturesque','\ud83d\udc4d\ud83d\udc4d','good','great','best','excellent','nice','delicious','lovely','tasty','amazing','fantastic','perfect','wonderful','pleasant','cozy','awesome','yummy','fabulous','cool','fine','brilliant','enjoyable','good!','outstanding','delicious!','charming','affordable','delightful','comfortable', '+','gorgeous','\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f'],\n               'Bad':['weak','only?','grubby','awseome','wash','ameri','weakest','filthy','disasterous','becareful','miserable','foo','bad','poor','stop','worst','disappointing','terrible','overpriced','rude','disappointed','horrible','mediocre','unfriendly','worse','dirty','disappointment','fo','waste','satisfying']}\n# \u0423 \u043c\u0435\u043d\u044f \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0441\u044f \u0432\u043e\u0442 \u0442\u0430\u043a\u043e\u0439 \u0441\u043b\u043e\u0432\u0430\u0440\u044c \u044d\u043f\u0438\u0442\u0435\u0442\u043e\u0432, \u0432\u0441\u0442\u0440\u0435\u0447\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u0432 \u043e\u0442\u0437\u044b\u0432\u0430\u0445. \u0412\u0438\u0434\u0438\u043c\u043e, \u0445\u0432\u0430\u043b\u0438\u0442\u044c \u043b\u044e\u0434\u0438 \u043b\u044e\u0431\u044f\u0442 \u0432\u0441\u0451 \u0436\u0435 \u0431\u043e\u043b\u044c\u0448\u0435, \u0447\u0435\u043c \u0440\u0443\u0433\u0430\u0442\u044c. \u041d\u0443, \u0438\u043b\u0438 \u043a\u0442\u043e-\u0442\u043e \u0447\u0442\u043e-\u0442\u043e \u043d\u0430\u043a\u0440\u0443\u0447\u0438\u0432\u0430\u0435\u0442.\n\ndef Reviews_counter (line): # \u0432\u0432\u043e\u0434\u0438\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0434\u043b\u044f \u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0430 \u043e\u0442\u0437\u044b\u0432\u043e\u0432 \u0432 \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\n    count=0\n    for word in line[0]:\n        if word in word_in_review['Good']:\n            count+=1\n        elif word in word_in_review['Bad']:\n            count-=1\n    return(count)\ndata['Reviews']=data['Reviews'].apply(Reviews_counter)\ndata.sample(5)\n\"\"\"\n\u0422\u0435\u043f\u0435\u0440\u044c \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u043d\u0430\u0439\u0442\u0438 \u043e\u0441\u043e\u0431\u044b\u0435 \"\u0444\u0438\u0448\u043a\u0438\" \u0433\u043e\u0440\u043e\u0434\u043e\u0432. \u0421\u043e\u0431\u0435\u0440\u0451\u043c \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0433\u043e\u0440\u043e\u0434\u043e\u0432, \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0430\u043d\u0438\u0438 \u044d\u0442\u043e\u0433\u043e \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u0430 \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c DF, \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u0449\u0438\u0439 \u0432\u0430\u0436\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0433\u043e\u0440\u043e\u0434\u043e\u0432.\n\"\"\"\ncityes=set()\ndata['City'].apply(lambda x: cityes.add(x))\ncityes\nlen(cityes)\n\"\"\"\n\u0418 \u0442\u0430\u043a, \u0443 \u043d\u0430 31 \u0433\u043e\u0440\u043e\u0434. \u0414\u043e\u0431\u0430\u0432\u0438\u043c \u0434\u043b\u044f \u0433\u043e\u0440\u043e\u0434\u043e\u0432 \u0442\u0430\u043a\u0438\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043a\u0430\u043a \u0441\u0440\u0435\u0434\u043d\u044f\u044f \u0442\u0435\u043c\u043f\u0435\u0440\u0430\u0442\u0443\u0440\u0430 \u044f\u043d\u0432\u0430\u0440\u044f \u0438 \u0438\u044e\u043b\u044f, \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u043e\u0441\u0430\u0434\u043a\u043e\u0432 \u0432 \u0433\u043e\u0434, \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0442\u0443\u0440\u0438\u0441\u0442\u043e\u0432, \u043f\u043e\u0441\u0435\u0449\u0430\u044e\u0449\u0438\u0445 \u0433\u043e\u0440\u043e\u0434 \u0437\u0430 \u0433\u043e\u0434. \u042f \u0431\u0440\u0430\u043b\u0430 \u0438\u0437 \u0438\u0437 \u043e\u0442\u043a\u0440\u044b\u0442\u044b\u0445 \u0438\u0441\u0442\u043e\u0447\u043d\u0438\u043a\u043e\u0432.\n\n\n\"\"\"\nJan_temp={'Paris':4.9, 'Stockholm':-2.3, 'London':5.0, 'Berlin':0.7, 'Munich':-0.9, 'Oporto':10,\n       'Milan':1.1, 'Bratislava':-0.4, 'Vienna':0.3, 'Rome':8.1, 'Barcelona':8.9, 'Madrid':5.9,\n       'Dublin':5.4, 'Brussels':3.3, 'Zurich':0.4, 'Warsaw':-1.8, 'Budapest':-0.4, 'Copenhagen':1.3,\n       'Amsterdam':3.3, 'Lyon':2.6, 'Hamburg':1.3, 'Lisbon':11.4, 'Prague':-1.4, 'Oslo':-2.9,\n       'Helsinki':-5, 'Edinburgh':4, 'Geneva':1.8, 'Ljubljana':-0.5, 'Athens':10.2,\n       'Luxembourg':0.8, 'Krakow':-3.6}\nJul_temp={'Paris':19.4, 'Stockholm':17.9, 'London':18.7, 'Berlin':18.6, 'Munich':17.4, 'Oporto':19.5,\n       'Milan':1.1, 'Bratislava':-0.4, 'Vienna':0.3, 'Rome':8.1, 'Barcelona':8.9, 'Madrid':5.9,\n       'Dublin':15.3, 'Brussels':17.6, 'Zurich':18.4, 'Warsaw':18.2, 'Budapest':21.2, 'Copenhagen':17.2,\n       'Amsterdam':16.5, 'Lyon':21, 'Hamburg':17.3, 'Lisbon':22.4, 'Prague':18.7, 'Oslo':17.1,\n       'Helsinki':17, 'Edinburgh':14.8, 'Geneva':19.7, 'Ljubljana':20.4, 'Athens':27.9,\n       'Luxembourg':17.4, 'Krakow':-17.9}\ntourists={'Paris':19.0, 'Stockholm':2.7, 'London':19.5, 'Berlin':6.2, 'Munich':4.2, 'Oporto':2.8,\n       'Milan':6.6, 'Bratislava':1, 'Vienna':6.6, 'Rome':10.3, 'Barcelona':7.0, 'Madrid':5.6,\n       'Dublin':5.4, 'Brussels':4.2, 'Zurich':1.5, 'Warsaw':2.8, 'Budapest':4.0, 'Copenhagen':3.2,\n       'Amsterdam':8.8, 'Lyon':3.5, 'Hamburg':6.8, 'Lisbon':3.6, 'Prague': 9.1, 'Oslo':0.7,\n       'Helsinki':0.4, 'Edinburgh':4.4, 'Geneva':1.3, 'Ljubljana':0.4, 'Athens':0.24,\n       'Luxembourg':0.9, 'Krakow':8.1}\nrains={'Paris':6.37, 'Stockholm':5.27, 'London':6.21, 'Berlin':5.7, 'Munich':6.22, 'Oporto':11.78,\n       'Milan':10.13, 'Bratislava':6.94, 'Vienna':10.31, 'Rome':9.34, 'Barcelona':6.12, 'Madrid':4.5,\n       'Dublin':7.67, 'Brussels':7.82, 'Zurich':10.85, 'Warsaw':10.02, 'Budapest':5.64, 'Copenhagen':11.64,\n       'Amsterdam':8.05, 'Lyon':7.63, 'Hamburg':7.38, 'Lisbon':6.91, 'Prague': 4.86, 'Oslo':7.40,\n       'Helsinki':6.5, 'Edinburgh':7.06, 'Geneva':9.34, 'Ljubljana':12.90, 'Athens':3.97,\n       'Luxembourg':8.31, 'Krakow':6.78}\n\ndef january_temp_column(C):\n    for  city in Jan_temp:\n        if city==C:\n            return(Jan_temp[city])\n    \ndata['january_temp']=data['City'].apply(january_temp_column)\n\ndef july_temp_column(C):\n    for  city in Jul_temp:\n        if city==C:\n            return(Jul_temp[city])\n        \ndata['july_temp']=data['City'].apply(january_temp_column)\n\ndef tourist_flow_column(C):\n    for  city in tourists:\n        if city==C:\n            return(tourists[city])\n        \ndata['tourists_flow']=data['City'].apply(tourist_flow_column)\n\ndef rain_column(C):\n    for  city in tourists:\n        if city==C:\n            return(rains[city])\ndata['rains']=data['City'].apply(rain_column)  \n\"\"\"\n\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430 \u0434\u0440\u0443\u0433\u0438\u0435 \u0438\u0441\u0442\u043e\u0447\u043d\u0438\u043a\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 \u043e \u0433\u043e\u0440\u043e\u0434\u0430\u0445\n\"\"\"\ndf_cities.head(3)\n\"\"\"\n\u0417\u0434\u0435\u0441\u044c \u043d\u0430\u0441 \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0443\u0435\u0442, \u043f\u043e\u0436\u0430\u043b\u0443\u0439, \u0442\u043e\u043b\u044c\u043a\u043e \u043d\u0430\u0441\u0435\u043b\u0435\u043d\u0438\u0435.\n\"\"\"\ndf_cities=df_cities.drop(['city_ascii','lat','lng','iso2','iso3','admin_name','capital','id'], axis='columns')\ndf_cities=df_cities.loc[df_cities.city.isin(cityes)]\ndf_cities\n\"\"\"\n\u0423\u043f\u0441. \u041a\u0430\u0436\u0435\u0442\u0441\u044f, \u0432\u0441\u0435 \u0435\u0432\u0440\u043e\u043f\u0435\u0439\u0441\u043a\u0438\u0435 \u0442\u043e\u043f\u043e\u043d\u0438\u043c\u044b \u0435\u0441\u0442\u044c \u0432 \u0421\u0428\u0410. \u041f\u0440\u0438\u0434\u0451\u0442\u0441\u044f \u043e\u0447\u0438\u0441\u0442\u0438\u0442\u044c \u0444\u0440\u0435\u0439\u043c \u043e\u0442 \u044d\u0442\u0438\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439.\n\"\"\"\ndf_cities=df_cities.loc[df_cities['country']!='United States']\nnew_city=set()\ndf_cities.city.apply(lambda x: new_city.add(x))\ncityes-new_city #\u042d\u0442\u0438\u0445 \u0433\u043e\u0440\u043e\u0434\u043e\u0432 \u043d\u0435\u0442 \u0432 \u0441\u043f\u0438\u0441\u043a\u0435. \u0418\u0445 \u043d\u0430\u0434\u043e \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c.\ndf_cities.loc[2586]=['Krakow', 'Poland',779115]\ndf_cities.loc[2587]=['Oporto', 'Portugal',240000]\ndf_cities.loc[2588]=['Zurich', 'Germany',1300000]\ndf_cities.head(35)\ndf_cost.sample(3)\n\"\"\"\n\u0417\u0434\u0435\u0441\u044c \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u0435\u0435: \u0435\u0441\u0442\u044c \u0438 \u0438\u043d\u0434\u0435\u043a\u0441 \u0446\u0435\u043d \u0432 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430\u0445, \u0438 \"\u0438\u043d\u0434\u0435\u043a\u0441 \u0431\u0438\u0433\u043c\u0430\u043a\u0430\" \u0438 \u043c\u043d\u043e\u0433\u043e \u0447\u0435\u0433\u043e \u0435\u0449\u0435. \u041d\u043e, \u043a \u0441\u043e\u0436\u0430\u043b\u0435\u043d\u0438\u044e, \u0434\u043b\u044f \u0441\u0442\u0440\u0430\u043d, \u0430 \u043d\u0435 \u0433\u043e\u0440\u043e\u0434\u043e\u0432. \u0414\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u0432\u043e\u0437\u044c\u043c\u0443 \u0442\u0430\u043a\u0438\u0435 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u044b \u043a\u0430\u043a \u0418\u043d\u0434\u0435\u043a\u0441 \u0446\u0435\u043d \u0432 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u0430\u0445, \u0438\u043d\u0434\u0435\u043a\u0441 \u0431\u0438\u0433\u043c\u0430\u043a\u0430 \u0438 \u0446\u0435\u043d\u0443 \u0430\u0440\u0435\u043d\u0434\u044b.\n\"\"\"\ndf_cost=df_cost.drop(['Rank 2020','Cost of Living Index','Cost of Living Plus Rent Index','Groceries Index','Local Purchasing Power Index','Unnamed: 9'],axis='columns')\ndf_cost=df_cost.loc[df_cost.Country.isin(df_cities['country'])]\ndf_cost.sample(5)\n#\u041c\u0435\u0440\u0436\u0438\u043c!\ndf_cities=df_cities.merge(df_cost, left_on='country',right_on= 'Country', how='inner')\ndf_cities=df_cities.drop(['country','Country'], axis='columns')\ndf_cities.sample(3)\n# \u041c\u0435\u0440\u0436\u0438\u043c \u0441 \u0431\u043e\u043b\u044c\u0448\u0438\u043c \u0444\u0440\u0435\u0439\u043c\u043e\u043c\ndata=data.merge(df_cities, left_on='City',right_on= 'city', how='inner')\ndata=data.drop(['city','City','URL_TA','ID_TA'],axis='columns')\ndata.sample(10)\n\"\"\"\n### \u0418 \u043e\u0434\u0438\u043d \u0438\u0437 \u043c\u043e\u0438\u0445 \u043b\u044e\u0431\u0438\u043c\u044b\u0445 - [\u043a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u044f \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u043e\u0432](https:\/\/ru.wikipedia.org\/wiki\/\u041a\u043e\u0440\u0440\u0435\u043b\u044f\u0446\u0438\u044f)\n\u041d\u0430 \u044d\u0442\u043e\u043c \u0433\u0440\u0430\u0444\u0438\u043a\u0435 \u0443\u0436\u0435 \u0441\u0435\u0439\u0447\u0430\u0441 \u0432\u044b \u0441\u043c\u043e\u0436\u0435\u0442\u0435 \u0437\u0430\u043c\u0435\u0442\u0438\u0442\u044c, \u043a\u0430\u043a \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0441\u0432\u044f\u0437\u0430\u043d\u044b \u043c\u0435\u0436\u0434\u0443 \u0441\u043e\u0431\u043e\u0439 \u0438 \u0441 \u0446\u0435\u043b\u0435\u0432\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439.\n\"\"\"\nplt.rcParams['figure.figsize'] = (15,10)\ndata_samp=data[['Restaurant_id','Cuisine Style','Ranking','Price Range','Number of Reviews','Reviews','Rating','sample','january_temp','july_temp','tourists_flow','rains','population','Rent Index','Restaurant Price Index','McMeal($)']]\nsns.heatmap(data_samp.drop(['sample'], axis=1).corr())\n\"\"\"\n\u0412\u043e\u043e\u0431\u0449\u0435 \u0431\u043b\u0430\u0433\u043e\u0434\u0430\u0440\u044f \u0432\u0438\u0437\u0443\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 \u0432 \u044d\u0442\u043e\u043c \u0434\u0430\u0442\u0430\u0441\u0435\u0442\u0435 \u043c\u043e\u0436\u043d\u043e \u0443\u0437\u043d\u0430\u0442\u044c \u043c\u043d\u043e\u0433\u043e \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0445 \u0444\u0430\u043a\u0442\u043e\u0432, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440:\n* \u0433\u0434\u0435 \u0431\u043e\u043b\u044c\u0448\u0435 \u041f\u0438\u0446\u0435\u0440\u0438\u0439 \u0432 \u041c\u0430\u0434\u0440\u0438\u0434\u0435 \u0438\u043b\u0438 \u041b\u043e\u043d\u0434\u043e\u043d\u0435?\n* \u0432 \u043a\u0430\u043a\u043e\u043c \u0433\u043e\u0440\u043e\u0434\u0435 \u043a\u0443\u0445\u043d\u044f \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0431\u043e\u043b\u0435\u0435 \u0440\u0430\u0437\u043d\u043e\u043e\u0431\u0440\u0430\u0437\u043d\u0430?\n\n\u043f\u0440\u0438\u0434\u0443\u043c\u0430\u0439\u0442\u0435 \u0441\u0432\u043e\u0438 \u0432\u043e\u043f\u0440\u043e\u0441 \u0438 \u043d\u0430\u0439\u0434\u0438\u0442\u0435 \u043d\u0430 \u043d\u0435\u0433\u043e \u043e\u0442\u0432\u0435\u0442 \u0432 \u0434\u0430\u043d\u043d\u044b\u0445)\n\"\"\"\n\"\"\"\n# Data Preprocessing\n\u0422\u0435\u043f\u0435\u0440\u044c, \u0434\u043b\u044f \u0443\u0434\u043e\u0431\u0441\u0442\u0432\u0430 \u0438 \u0432\u043e\u0441\u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u043c\u043e\u0441\u0442\u0438 \u043a\u043e\u0434\u0430, \u0437\u0430\u0432\u0435\u0440\u043d\u0435\u043c \u0432\u0441\u044e \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0443 \u0432 \u043e\u0434\u043d\u0443 \u0431\u043e\u043b\u044c\u0448\u0443\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u044e.\n\"\"\"\n# \u043d\u0430 \u0432\u0441\u044f\u043a\u0438\u0439 \u0441\u043b\u0443\u0447\u0430\u0439, \u0437\u0430\u043d\u043e\u0432\u043e \u043f\u043e\u0434\u0433\u0440\u0443\u0436\u0430\u0435\u043c \u0434\u0430\u043d\u043d\u044b\u0435\ndf_train = pd.read_csv(DATA_DIR+'\/main_task.csv')\ndf_test = pd.read_csv(DATA_DIR+'\/kaggle_task.csv')\ndf_train['sample'] = 1 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0440\u0435\u0439\u043d\ndf_test['sample'] = 0 # \u043f\u043e\u043c\u0435\u0447\u0430\u0435\u043c \u0433\u0434\u0435 \u0443 \u043d\u0430\u0441 \u0442\u0435\u0441\u0442\ndf_test['Rating'] = 0 # \u0432 \u0442\u0435\u0441\u0442\u0435 \u0443 \u043d\u0430\u0441 \u043d\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f Rating, \u043c\u044b \u0435\u0433\u043e \u0434\u043e\u043b\u0436\u043d\u044b \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u0442\u044c, \u043f\u043e \u044d\u0442\u043e\u043c\u0443 \u043f\u043e\u043a\u0430 \u043f\u0440\u043e\u0441\u0442\u043e \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043d\u0443\u043b\u044f\u043c\u0438\n\ndata = df_test.append(df_train, sort=False).reset_index(drop=True) # \u043e\u0431\u044a\u0435\u0434\u0438\u043d\u044f\u0435\u043c\ndata.info()\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef preproc_data(df_input):\n    \n    df_output = df_input.copy()\n    \n    # ################### 1. \u041f\u0440\u0435\u0434\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430 ############################################################## \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043d\u0435 \u043d\u0443\u0436\u043d\u044b\u0435 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438\n    df_output.drop(['Restaurant_id','ID_TA','URL_TA'], axis = 1, inplace=True)\n    \n    \n    # ################### 2. NAN ############################################################## \n    # \u0414\u0430\u043b\u0435\u0435 \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043f\u0440\u043e\u043f\u0443\u0441\u043a\u0438, \u0432\u044b \u043c\u043e\u0436\u0435\u0442\u0435 \u043f\u043e\u043f\u0440\u043e\u0431\u043e\u0432\u0430\u0442\u044c \u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435\u043c \u0441\u0440\u0435\u0434\u043d\u0438\u043c \u0438\u043b\u0438 \u0441\u0440\u0435\u0434\u043d\u0438\u043c \u043f\u043e \u0433\u043e\u0440\u043e\u0434\u0443 \u0438 \u0442\u0434...\n    df_output['Number of Reviews']=df_output['Number of Reviews'].fillna(0, inplace=True)\n    df_output['Cuisine Style']=df_output['Cuisine Style'].fillna(\"['European', 'Vegetarian Friendly']\")\n    df_output['Price Range']=data['Price Range'].fillna('$$ - $$$')\n    df_output['Reviews']=df_output['Reviews'].replace(\"[[], []]\", \"[['no_review'], ['01\/01\/2000']]\") #\u041f\u043e\u0442\u043e\u043c \u043f\u0440\u0438\u0433\u043e\u0434\u0438\u0442\u0441\u044f\n    df_output['Reviews']=df_output['Reviews'].fillna(\"[['no_review'], ['01\/01\/2000']]\")\n    # ################### 3. Encoding ############################################################## \n    # \u0434\u043b\u044f One-Hot Encoding \u0432 pandas \u0435\u0441\u0442\u044c \u0433\u043e\u0442\u043e\u0432\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f - get_dummies. \u041e\u0441\u043e\u0431\u0435\u043d\u043d\u043e \u0440\u0430\u0434\u0443\u0435\u0442 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 dummy_na\n    #\u041e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0435\u043c \u043a\u043e\u043b\u043e\u043d\u043a\u0443 \u0440\u0430\u0437\u0431\u0440\u043e\u0441\u0430 \u0446\u0435\u043d\n    def sign_to_range (x):\n        if x == \"$\":\n            return 1\n        elif x == \"$$ - $$$\":\n            return 2.5\n        else:\n            return 4\n    df_output['Price Range']=df_output['Price Range'].apply(sign_to_range)\n    \n    #\u041e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0435\u043c \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u044b \u043a\u0443\u0445\u043e\u043d\u044c\n    cousine_list=[]\n    df_output['Cuisine Style'].apply(lambda x: cousine_list.extend(x))\n    top=list(pd.Series(dict((Counter(cousine_list).most_common(70)))).index) #\u041e\u0447\u0435\u043d\u044c \u0441\u0442\u0440\u0430\u043d\u043d\u044b\u0439 \u043a\u043e\u0441\u0442\u044b\u043b\u044c, \u0447\u0442\u043e\u0431\u044b \u0441\u0444\u043e\u0440\u043c\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0441\u0430\u043c\u044b\u0445 \u0447\u0430\u0441\u0442\u044b\u0445 \u043a\u0443\u0445\u043e\u043d\u044c.\n    others=(list(set(cousine_list)-set(top))) # \u0444\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432\u043e \u0441\u0430\u043c\u044b\u0445 \u0440\u0435\u0434\u043a\u0438\u0445 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u0432\n    def other(cuisines):\n        for cuisine in cuisines:\n            if cuisine in others:\n                return 'other'\n            else:\n                return cuisine\n\n    df_output['Cuisine Style']=df_output['Cuisine Style'].apply(other) # \u043c\u0435\u043d\u044f\u0435\u043c \u043d\u0430\u0438\u043c\u0435\u043d\u0435\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u044b \u043d\u0430 \"other\"\n    dummi_cuisine=pd.get_dummies(df_output['Cuisine Style'].apply(pd.Series).stack()).sum(level=0) # \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u0441\u0435\u0442 dummie-\u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\n    df_output=pd.concat([df_output,dummi_cuisine], axis=1) # \u0421\u043e\u0435\u0434\u0438\u043d\u044f\u0435\u043c \u0441 \u0441\u0435\u0442\u043e\u043c \n    df_output['Cuisine Style']=df_output['Cuisine Style'].apply(lambda x: len(x))\n    \n    # \u0413\u043e\u0440\u043e\u0434\u0430. Feature Engineering \u0431\u0443\u0434\u0435\u0442 \u0437\u0434\u0435\u0441\u044c.\n    Jan_temp={'Paris':4.9, 'Stockholm':-2.3, 'London':5.0, 'Berlin':0.7, 'Munich':-0.9, 'Oporto':10,\n       'Milan':1.1, 'Bratislava':-0.4, 'Vienna':0.3, 'Rome':8.1, 'Barcelona':8.9, 'Madrid':5.9,\n       'Dublin':5.4, 'Brussels':3.3, 'Zurich':0.4, 'Warsaw':-1.8, 'Budapest':-0.4, 'Copenhagen':1.3,\n       'Amsterdam':3.3, 'Lyon':2.6, 'Hamburg':1.3, 'Lisbon':11.4, 'Prague':-1.4, 'Oslo':-2.9,\n       'Helsinki':-5, 'Edinburgh':4, 'Geneva':1.8, 'Ljubljana':-0.5, 'Athens':10.2,\n       'Luxembourg':0.8, 'Krakow':-3.6}\n    Jul_temp={'Paris':19.4, 'Stockholm':17.9, 'London':18.7, 'Berlin':18.6, 'Munich':17.4, 'Oporto':19.5,\n       'Milan':1.1, 'Bratislava':-0.4, 'Vienna':0.3, 'Rome':8.1, 'Barcelona':8.9, 'Madrid':5.9,\n       'Dublin':15.3, 'Brussels':17.6, 'Zurich':18.4, 'Warsaw':18.2, 'Budapest':21.2, 'Copenhagen':17.2,\n       'Amsterdam':16.5, 'Lyon':21, 'Hamburg':17.3, 'Lisbon':22.4, 'Prague':18.7, 'Oslo':17.1,\n       'Helsinki':17, 'Edinburgh':14.8, 'Geneva':19.7, 'Ljubljana':20.4, 'Athens':27.9,\n       'Luxembourg':17.4, 'Krakow':-17.9}\n    tourists={'Paris':19.0, 'Stockholm':2.7, 'London':19.5, 'Berlin':6.2, 'Munich':4.2, 'Oporto':2.8,\n       'Milan':6.6, 'Bratislava':1, 'Vienna':6.6, 'Rome':10.3, 'Barcelona':7.0, 'Madrid':5.6,\n       'Dublin':5.4, 'Brussels':4.2, 'Zurich':1.5, 'Warsaw':2.8, 'Budapest':4.0, 'Copenhagen':3.2,\n       'Amsterdam':8.8, 'Lyon':3.5, 'Hamburg':6.8, 'Lisbon':3.6, 'Prague': 9.1, 'Oslo':0.7,\n       'Helsinki':0.4, 'Edinburgh':4.4, 'Geneva':1.3, 'Ljubljana':0.4, 'Athens':0.24,\n       'Luxembourg':0.9, 'Krakow':8.1}\n    rains={'Paris':6.37, 'Stockholm':5.27, 'London':6.21, 'Berlin':5.7, 'Munich':6.22, 'Oporto':11.78,\n       'Milan':10.13, 'Bratislava':6.94, 'Vienna':10.31, 'Rome':9.34, 'Barcelona':6.12, 'Madrid':4.5,\n       'Dublin':7.67, 'Brussels':7.82, 'Zurich':10.85, 'Warsaw':10.02, 'Budapest':5.64, 'Copenhagen':11.64,\n       'Amsterdam':8.05, 'Lyon':7.63, 'Hamburg':7.38, 'Lisbon':6.91, 'Prague': 4.86, 'Oslo':7.40,\n       'Helsinki':6.5, 'Edinburgh':7.06, 'Geneva':9.34, 'Ljubljana':12.90, 'Athens':3.97,\n       'Luxembourg':8.31, 'Krakow':6.78}\n\n    def january_temp_column(C):\n        for  city in Jan_temp:\n            if city==C:\n                return(Jan_temp[city])\n    \n    df_output['january_temp']=df_output['City'].apply(january_temp_column)\n\n    def july_temp_column(C):\n        for  city in Jul_temp:\n            if city==C:\n                return(Jul_temp[city])\n        \n    df_output['july_temp']=df_output['City'].apply(january_temp_column)\n\n    def tourist_flow_column(C):\n        for  city in tourists:\n            if city==C:\n                return(tourists[city])\n        \n    df_output['tourists_flow']=df_output['City'].apply(tourist_flow_column)\n\n    def rain_column(C):\n        for  city in tourists:\n            if city==C:\n                return(rains[city])\n    df_output['rains']=df_output['City'].apply(rain_column) \n    df_output=df_output.merge(df_cities, left_on='City',right_on= 'city', how='inner')\n   \n    # \u041e\u0442\u0437\u044b\u0432\u044b. \u0441\u0430\u043c\u043e\u0435 \u0441\u043b\u043e\u0436\u043d\u043e\u0435.\n    word_in_review=word_in_review={'Good':['gusto','nya','bellisimo','dequate','pleasantly','wunderfull','delucious','excellient','picturesque','\ud83d\udc4d\ud83d\udc4d','good','great','best','excellent','nice','delicious','lovely','tasty','amazing','fantastic','perfect','wonderful','pleasant','cozy','awesome','yummy','fabulous','cool','fine','brilliant','enjoyable','good!','outstanding','delicious!','charming','affordable','delightful','comfortable', '+','gorgeous','\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f\ud83d\udc4f'],\n                                   'Bad':['weak','only?','grubby','awseome','wash','ameri','weakest','filthy','disasterous','becareful','miserable','foo','bad','poor','stop','worst','disappointing','terrible','overpriced','rude','disappointed','horrible','mediocre','unfriendly','worse','dirty','disappointment','fo','waste','satisfying']}\n    def Reviews_reader(line):\n        line=line[2:-2]\n        line=line.split('], [')\n        line[0]=line[0].split(', ')\n        line[1]=line[1].split(', ')\n   \n        for rev in line[0]:\n            rev=(rev[1:-1]).lower()\n            rev=rev.replace('!','')\n            rev=rev.replace('.','')\n            rev=rev.split(' ')\n            \n        return(line)\n    df_output['Reviews']=df_output['Reviews'].apply(Reviews_reader)\n\n    def Reviews_counter (line): # \u0432\u0432\u043e\u0434\u0438\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0434\u043b\u044f \u043f\u0435\u0440\u0435\u0432\u043e\u0434\u0430 \u043e\u0442\u0437\u044b\u0432\u043e\u0432 \u0432 \u0447\u0438\u0441\u043b\u0435\u043d\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435\n        count=0\n        for word in line[0]:\n            if word in word_in_review['Good']:\n                count+=1\n            elif word in word_in_review['Bad']:\n                count-=1\n        return(count)\n    df_output['Reviews']=df_output['Reviews'].apply(Reviews_counter)\n    \n    # ################### 5. Clean #################################################### \n    # \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0435\u0449\u0435 \u043d\u0435 \u0443\u0441\u043f\u0435\u043b\u0438 \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c, \n    # \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0430\u0445 \u0441 dtypes \"object\" \u043e\u0431\u0443\u0447\u0430\u0442\u044c\u0441\u044f \u043d\u0435 \u0431\u0443\u0434\u0435\u0442, \u043f\u0440\u043e\u0441\u0442\u043e \u0432\u044b\u0431\u0435\u0440\u0438\u043c \u0438\u0445 \u0438 \u0443\u0434\u0430\u043b\u0438\u043c\n    object_columns = [s for s in df_output.columns if df_output[s].dtypes == 'object']\n    df_output.drop(object_columns, axis = 1, inplace=True)\n    names = df_output.columns.values\n    scaler=MinMaxScaler()\n    df_output = pd.DataFrame(scaler.fit_transform(df_output))\n    df_output.columns=names\n    return  df_output\n\"\"\"\n>\u041f\u043e \u0445\u043e\u0440\u043e\u0448\u0435\u043c\u0443, \u043c\u043e\u0436\u043d\u043e \u0431\u044b\u043b\u043e \u0431\u044b \u043f\u0435\u0440\u0435\u0432\u0435\u0441\u0442\u0438 \u044d\u0442\u0443 \u0431\u043e\u043b\u044c\u0448\u0443\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0432 \u043a\u043b\u0430\u0441\u0441 \u0438 \u0440\u0430\u0437\u0431\u0438\u0442\u044c \u043d\u0430 \u043f\u043e\u0434\u0444\u0443\u043d\u043a\u0446\u0438\u0438 (\u0441\u043e\u0433\u043b\u0430\u0441\u043d\u043e \u041e\u041e\u041f). \n\"\"\"\n\"\"\"\n#### \u0417\u0430\u043f\u0443\u0441\u043a\u0430\u0435\u043c \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c \u0447\u0442\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c\n\"\"\"\ndf_preproc = preproc_data(data)\ndf_preproc.sample(10)\ndf_preproc.info()\n# \u0422\u0435\u043f\u0435\u0440\u044c \u0432\u044b\u0434\u0435\u043b\u0438\u043c \u0442\u0435\u0441\u0442\u043e\u0432\u0443\u044e \u0447\u0430\u0441\u0442\u044c\ntrain_data = df_preproc.query('sample == 1').drop(['sample'], axis=1)\ntest_data = df_preproc.query('sample == 0').drop(['sample'], axis=1)\n\ny = train_data.Rating.values            # \u043d\u0430\u0448 \u0442\u0430\u0440\u0433\u0435\u0442\nX = train_data.drop(['Rating'], axis=1)\n\"\"\"\n**\u041f\u0435\u0440\u0435\u0434 \u0442\u0435\u043c \u043a\u0430\u043a \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c \u043d\u0430\u0448\u0438 \u0434\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435, \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u043c \u0434\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 \u0435\u0449\u0435 \u043e\u0434\u0438\u043d \u0442\u0435\u0441\u0442 \u0438 \u0442\u0440\u0435\u0439\u043d, \u0434\u043b\u044f \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u0438. \n\u042d\u0442\u043e \u043f\u043e\u043c\u043e\u0436\u0435\u0442 \u043d\u0430\u043c \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c, \u043a\u0430\u043a \u0445\u043e\u0440\u043e\u0448\u043e \u043d\u0430\u0448\u0430 \u043c\u043e\u0434\u0435\u043b\u044c \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442, \u0434\u043e \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 submissiona \u043d\u0430 kaggle.**\n\"\"\"\n# \u0412\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c\u0441\u044f \u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0435 train_test_split \u0434\u043b\u044f \u0440\u0430\u0437\u0431\u0438\u0432\u043a\u0438 \u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0445 \u0434\u0430\u043d\u043d\u044b\u0445\n# \u0432\u044b\u0434\u0435\u043b\u0438\u043c 20% \u0434\u0430\u043d\u043d\u044b\u0445 \u043d\u0430 \u0432\u0430\u043b\u0438\u0434\u0430\u0446\u0438\u044e (\u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 test_size)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_SEED)\n# \u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c\ntest_data.shape, train_data.shape, X.shape, X_train.shape, X_test.shape\n\"\"\"\n# Model \n\u0421\u0430\u043c ML\n\"\"\"\n# \u0418\u043c\u043f\u043e\u0440\u0442\u0438\u0440\u0443\u0435\u043c \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u044b\u0435 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438:\nfrom sklearn.ensemble import RandomForestRegressor # \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f \u0438 \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u044f \u043c\u043e\u0434\u0435\u043b\u0438\nfrom sklearn import metrics # \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u043e\u0446\u0435\u043d\u043a\u0438 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u0438 \u043c\u043e\u0434\u0435\u043b\u0438\n# \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043c\u043e\u0434\u0435\u043b\u044c (\u041d\u0410\u0421\u0422\u0420\u041e\u0419\u041a\u0418 \u041d\u0415 \u0422\u0420\u041e\u0413\u0410\u0415\u041c)\nmodel = RandomForestRegressor(n_estimators=100, verbose=1, n_jobs=-1, random_state=RANDOM_SEED)\n# \u041e\u0431\u0443\u0447\u0430\u0435\u043c \u043c\u043e\u0434\u0435\u043b\u044c \u043d\u0430 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u043c \u043d\u0430\u0431\u043e\u0440\u0435 \u0434\u0430\u043d\u043d\u044b\u0445\nmodel.fit(X_train, y_train)\n\n# \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c \u043e\u0431\u0443\u0447\u0435\u043d\u043d\u0443\u044e \u043c\u043e\u0434\u0435\u043b\u044c \u0434\u043b\u044f \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u0438\u044f \u0440\u0435\u0439\u0442\u0438\u043d\u0433\u0430 \u0440\u0435\u0441\u0442\u043e\u0440\u0430\u043d\u043e\u0432 \u0432 \u0442\u0435\u0441\u0442\u043e\u0432\u043e\u0439 \u0432\u044b\u0431\u043e\u0440\u043a\u0435.\n# \u041f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f \u0437\u0430\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u043c \u0432 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e y_pred\ny_pred = model.predict(X_test)\n# \u0421\u0440\u0430\u0432\u043d\u0438\u0432\u0430\u0435\u043c \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f (y_pred) \u0441 \u0440\u0435\u0430\u043b\u044c\u043d\u044b\u043c\u0438 (y_test), \u0438 \u0441\u043c\u043e\u0442\u0440\u0438\u043c \u043d\u0430\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043e\u043d\u0438 \u0432 \u0441\u0440\u0435\u0434\u043d\u0435\u043c \u043e\u0442\u043b\u0438\u0447\u0430\u044e\u0442\u0441\u044f\n# \u041c\u0435\u0442\u0440\u0438\u043a\u0430 \u043d\u0430\u0437\u044b\u0432\u0430\u0435\u0442\u0441\u044f Mean Absolute Error (MAE) \u0438 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0441\u0440\u0435\u0434\u043d\u0435\u0435 \u043e\u0442\u043a\u043b\u043e\u043d\u0435\u043d\u0438\u0435 \u043f\u0440\u0435\u0434\u0441\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0439 \u043e\u0442 \u0444\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0445.\nprint('MAE:', metrics.mean_absolute_error(y_test, y_pred))\n# \u0432 RandomForestRegressor \u0435\u0441\u0442\u044c \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e\u0441\u0442\u044c \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u0441\u0430\u043c\u044b\u0435 \u0432\u0430\u0436\u043d\u044b\u0435 \u043f\u0440\u0438\u0437\u043d\u0430\u043a\u0438 \u0434\u043b\u044f \u043c\u043e\u0434\u0435\u043b\u0438\nplt.rcParams['figure.figsize'] = (10,10)\nfeat_importances = pd.Series(model.feature_importances_, index=X.columns)\nfeat_importances.nlargest(15).plot(kind='barh')\n\"\"\"\n# Submission\n\u0415\u0441\u043b\u0438 \u0432\u0441\u0435 \u0443\u0441\u0442\u0440\u0430\u0435\u0432\u0430\u0435\u0442 - \u0433\u043e\u0442\u043e\u0432\u0438\u043c Submission \u043d\u0430 \u043a\u0430\u0433\u043b\n\"\"\"\ntest_data.sample(10)\ntest_data = test_data.drop(['Rating'], axis=1)\nsample_submission\npredict_submission = model.predict(test_data)\nlen(predict_submission)\nsample_submission['Rating'] = predict_submission[:10000]\nsample_submission.to_csv('submission.csv', index=False)\nsample_submission.head(10)","meta":"{'source': 'AI4Code', 'id': '7657755f5de943'}"}
{"id":"90315","text":"from IPython.display import Image\nImage(\"..\/input\/image-house-prices-advanced-regression\/image.jpeg\")\n\n\"\"\"\n#  Predict sales prices and practice feature engineering, RFs, and gradient boosting\n\n## 1. Problem defition\n\n\n> Predict the value of the SalePrice variable. \n\n## 2. Data\n\n\nhttps:\/\/www.kaggle.com\/c\/house-prices-advanced-regression-techniques\/data\n\n\n\n    **Data Details:**\n    \n* Here's a brief version of what you'll find in the data description file.\n* SalePrice - the property's sale price in dollars. This is the target variable that you're trying to predict.\n* MSSubClass: The building class\n* MSZoning: The general zoning classification\n* LotFrontage: Linear feet of street connected to property\n* LotArea: Lot size in square feet\n* Street: Type of road access\n* Alley: Type of alley access\n* LotShape: General shape of property\n* LandContour: Flatness of the property\n* Utilities: Type of utilities available\n* LotConfig: Lot configuration\n* LandSlope: Slope of property\n* Neighborhood: Physical locations within Ames city limits\n* Condition1: Proximity to main road or railroad\n* Condition2: Proximity to main road or railroad (if a second is present)\n* BldgType: Type of dwelling\n* HouseStyle: Style of dwelling\n* OverallQual: Overall material and finish quality\n* OverallCond: Overall condition rating\n* YearBuilt: Original construction date\n* YearRemodAdd: Remodel date\n* RoofStyle: Type of roof\n* RoofMatl: Roof material\n* Exterior1st: Exterior covering on house\n* Exterior2nd: Exterior covering on house (if more than one material)\n* MasVnrType: Masonry veneer type\n* MasVnrArea: Masonry veneer area in square feet\n* ExterQual: Exterior material quality\n* ExterCond: Present condition of the material on the exterior\n* Foundation: Type of foundation\n* BsmtQual: Height of the basement\n* BsmtCond: General condition of the basement\n* BsmtExposure: Walkout or garden level basement walls\n* BsmtFinType1: Quality of basement finished area\n* BsmtFinSF1: Type 1 finished square feet\n* BsmtFinType2: Quality of second finished area (if present)\n* BsmtFinSF2: Type 2 finished square feet\n* BsmtUnfSF: Unfinished square feet of basement area\n* Total square feet of basement area\n* Heating: Type of heating\n* HeatingQC: Heating quality and condition\n* CentralAir: Central air conditioning\n* Electrical: Electrical system\n* 1stFlrSF: First Floor square feet\n* 2ndFlrSF: Second floor square feet\n* LowQualFinSF: Low quality finished square feet (all floors)\n* GrLivArea: Above grade (ground) living area square feet\n* BsmtFullBath: Basement full bathrooms\n* BsmtHalfBath: Basement half bathrooms\n* FullBath: Full bathrooms above grade\n* HalfBath: Half baths above grade\n* Bedroom: Number of bedrooms above basement level\n* Kitchen: Number of kitchens\n* KitchenQual: Kitchen quality\n* TotRmsAbvGrd: Total rooms above grade (does not include bathrooms)\n* Functional: Home functionality rating\n* Fireplaces: Number of fireplaces\n* FireplaceQu: Fireplace quality\n* GarageType: Garage location\n* GarageYrBlt: Year garage was built\n* GarageFinish: Interior finish of the garage\n* GarageCars: Size of garage in car capacity\n* GarageArea: Size of garage in square feet\n* GarageQual: Garage quality\n* GarageCond: Garage condition\n* PavedDrive: Paved driveway\n* WoodDeckSF: Wood deck area in square feet\n* OpenPorchSF: Open porch area in square feet\n* EnclosedPorch: Enclosed porch area in square feet\n* 3SsnPorch: Three season porch area in square feet\n* ScreenPorch: Screen porch area in square feet\n* PoolArea: Pool area in square feet\n* PoolQC: Pool quality\n* Fence: Fence quality\n* MiscFeature: Miscellaneous feature not covered in other categories\n* MiscVal: $Value of miscellaneous feature\n* MoSold: Month Sold\n* YrSold: Year Sold\n* SaleType: Type of sale\n* SaleCondition: Condition of sale\n\n\n\n\n\"\"\"\n\"\"\"\n##  Evaluation\n\n The evaluation metric for this competition is the RMSLE (root mean squared log error) between the actual and predicted auction prices\n \n https:\/\/www.kaggle.com\/c\/house-prices-advanced-regression-techniques\/overview\/evaluation\n\n\n\"\"\"\n\"\"\"\n# 1. Data\n\"\"\"\n\"\"\"\n## 1.1 Import Data\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nimport xgboost\ndf_train = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/train.csv')\ndf_train.head()\ndf_train.shape\ndf_train.dtypes\ndf_train.describe()\ndf_train.isna().sum()\ndf_train.corr()\n# Skewness\ndf_train.skew()\nclass_counts = df_train['SalePrice'].value_counts()\nclass_counts\n\"\"\"\n## 1.2 Data Visualisation\n\"\"\"\n# Histogram\ndf_train.hist(figsize=(20, 10))\n# Scatter plot\nfig, ax = plt.subplots()\nax.scatter(df_train['Id'], df_train['SalePrice'])\n\"\"\"\n## 1.3 Data preparation\n\"\"\"\ndef preprocess_data(df):\n    \"\"\"\n    Performs transformations on df and returns transformed df.\n    \"\"\"\n    # Fill the numeric rows with median\n    for label, content in df.items():\n        if pd.api.types.is_numeric_dtype(content):\n            if pd.isnull(content).sum():\n                # Add a binary column which tells us if the data was missing or not\n                df[label+\"_is_missing\"] = pd.isnull(content)\n                # Fill missing numeric values with median\n                df[label] = content.fillna(content.median())\n    \n        # Filled categorical missing data and turn categories into numbers\n        if not pd.api.types.is_numeric_dtype(content):\n            df[label+\"_is_missing\"] = pd.isnull(content)\n            # We add +1 to the category code because pandas encodes missing categories as -1\n            df[label] = pd.Categorical(content).codes+1\n    \n    return df\n# Process the test data \ndf_train = preprocess_data(df_train)\ndf_train.head()\n# Process the test data \ndf_train = preprocess_data(df_train)\ndf_train.head()\ndf_train.info()\n\"\"\"\n### Modelling\n\"\"\"\n\"\"\"\n ## 2.1 Building an evaluation function\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import linear_model\nfrom sklearn.linear_model import LinearRegression, Lasso\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_log_error, mean_absolute_error, r2_score\n\nX = df_train.drop('SalePrice', axis=1)\ny = df_train['SalePrice']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2)\n\n# Put models in a dictionary\nmodels = {'Logistic Regression': LogisticRegression(),\n          'linear_regression' : LinearRegression(),\n          'Random Forest': RandomForestRegressor(),\n          'linear_model' : linear_model.Lasso(alpha=0.1),\n          'XGBoost' : XGBRegressor()\n           \n          }\n\n# Create a function to fit and score models\ndef fit_and_score(models, X_train, X_test, y_train, y_test):\n    \"\"\"\n    Fits and evaluates given machine learning models.\n    models : a dict of differetn Scikit-Learn machine learning models\n    X_train : training data (no labels)\n    X_test : validation data (no labels)\n    y_train : training labels\n    y_test : validation labels\n    \"\"\"\n    # Set random seed\n    np.random.seed(42)\n    # Make a dictionary to keep model scores\n    model_scores = {}\n    # Loop through models\n    for name, model in models.items():\n        # Fit the model to the data\n        model.fit(X_train, y_train)\n        # Evaluate the model and append its score to model_scores\n        model_scores[name] = model.score(X_test, y_test)\n    return model_scores\n    \nmodel_scores = fit_and_score(models=models,\n                             X_train=X_train,\n                             X_test= X_test,\n                             y_train=y_train,\n                             y_test=y_test)\n\nmodel_scores\n\n\n\"\"\"\n## 2.2 Evaluate Models\n\"\"\"\nmodels = {'Logistic Regression': LogisticRegression(),\n          'linear_regression' : LinearRegression(),\n          'Random Forest': RandomForestRegressor(),\n          'linear_model' : linear_model.Lasso(alpha=0.1),\n          'XGBoost' : XGBRegressor()\n           \n          }\n\n# Logistic Regression\nmodel1 = LogisticRegression()\nmodel1.fit(X_train, y_train)\ny_preds = model1.predict(X_test)\nprint('Logistic Regression')\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('RMSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n# linear_regression\nmodel2 = LinearRegression()\nmodel2 = LogisticRegression()\nmodel2.fit(X_train, y_train)\ny_preds = model2.predict(X_test)\nprint('linear_regression')\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('RMSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n# Random Forest\nmodel3 = RandomForestRegressor()\nmodel3.fit(X_train, y_train)\ny_preds = model3.predict(X_test)\nprint('Random Forest')\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('RMSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n# linear_model\nmodel4 = linear_model.Lasso(alpha=0.1)\nmodel4.fit(X_train, y_train)\ny_preds = model4.predict(X_test)\nprint('linear_model')\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('RMSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n# XGBoost\nmodel5 = XGBRegressor()\nmodel5.fit(X_train, y_train)\ny_preds = model5.predict(X_test)\nprint('XGBoost')\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('RMSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n\n\n\n\n\"\"\"\n### Choising the model XGBOOST\nscore: 0.828759856683738\nRMSLE 0.021842740178599024   \n\"\"\"\n\"\"\"\n## Testing our model on a subset (to tune the hyperparameters)\n\"\"\"\n%%time\n\n# Instantiate model\nmodel = XGBRegressor()\n\n# Fit the model\nmodel.fit(X_train, y_train)\ny_preds = model.predict(X_test)\n\n\n\"\"\"\n### Hyerparameter tuning with GridSearchCV\n\n\"\"\"\nfrom sklearn.model_selection import GridSearchCV\ngrid = {'n_estimators' : [10, 1000],\n        'learning_rate': [0.01, 0.1],\n        'gamma' : [0.1, 5],\n        'max_depth' : [3, 5, 8], \n        'subsample' : [0.8 ,0.9, 1],\n        'colsample_bytree' : [0.3, 0,8],\n        'gamma' : [0.1, 5]\n        \n    \n}\n\n\nxgb_model = GridSearchCV(XGBRegressor(),\n\n                              param_grid=grid,\n                              \n                              cv=5,\n                              verbose=20)\n\nxgb_model.fit(X_train, y_train)\n\n\n# Find the best model hyperparameters\nxgb_model.best_params_\nbest_model = XGBRegressor(colsample_bytree=0.3,\n                          gamma=0.1,\n                          learning_rate=0.01,\n                          max_depth=5,\n                          n_estimators=1000,\n                          subsample=1)\n# Fit the model\nbest_model.fit(X_train, y_train)\ny_preds = best_model.predict(X_test)\n\nbest_model.score(X_test, y_test)\n\nprint('MAE', mean_absolute_error(y_test, y_preds))\nprint('MSLE', mean_squared_log_error(y_test, y_preds))\nprint('r-squared', r2_score (y_test, y_preds))\n\n\"\"\"\n### Make predictions on test data\n\"\"\"\n# Import the test data\ndf_test = pd.read_csv('..\/input\/house-prices-advanced-regression-techniques\/test.csv')\ndf_test.head()\n# Process the test data \ndf_test = preprocess_data(df_test)\ndf_test.head()\ndf_train.head()\nset(df_test.columns) - set(X_train.columns)\n# Manually adjust df_train to missing columns\ndf_test = df_test.drop('BsmtFinSF1_is_missing', axis=1)                            \ndf_test = df_test.drop('BsmtFinSF2_is_missing', axis=1)\ndf_test = df_test.drop('BsmtFullBath_is_missing', axis=1) \ndf_test = df_test.drop('BsmtHalfBath_is_missing', axis=1)\ndf_test = df_test.drop('BsmtUnfSF_is_missing', axis=1)\ndf_test = df_test.drop('GarageArea_is_missing', axis=1)\ndf_test = df_test.drop('GarageCars_is_missing', axis=1)\ndf_test = df_test.drop('TotalBsmtSF_is_missing', axis=1)\ndf_test.head()\ndf_test.head()\n# Make predictions on updated test data\n\nmodel.fit(X_train, y_train)\n\ntest_preds = model.predict(df_test)\ntest_preds\n\"\"\"\n## Format predictions asked by Kaggle\n\"\"\"\ndf_preds_test = pd.DataFrame()\ndf_preds_test['Id'] = df_test['Id']\ndf_preds_test[\"SalePrice\"] = test_preds\ndf_preds_test\n# Export prediction data\ndf_preds_test.to_csv(\".\/HousePricesAdvanced.csv\", index=False)\n\"\"\"\n## Feature importance\n\"\"\"\n# Feature Importance with Extra Trees Classifier\nfrom sklearn.ensemble import ExtraTreesClassifier\n# feature extraction\nmodel = ExtraTreesClassifier()\nmodel.fit(X, y)\nprint(model.feature_importances_)\nimport seaborn as sns\n\n# Helper function for plotting feature importance\ndef plot_features(columns, importances, n=20):\n    data = (pd.DataFrame({\"features\": columns,\n                        \"feature_importance\": importances})\n          .sort_values(\"feature_importance\", ascending=False)\n          .reset_index(drop=True))\n    \n    sns.barplot(x=\"feature_importance\",\n                y=\"features\",\n                data=data[:n],\n                orient=\"h\")\nplt.figure(figsize=(20, 6))\nplot_features(X_train.columns, best_model.feature_importances_)","meta":"{'source': 'AI4Code', 'id': 'a5a2e617ac2b87'}"}
{"id":"71937","text":"import pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom imblearn.over_sampling import SMOTE\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, confusion_matrix, recall_score, precision_score\n\nfrom sklearn.preprocessing import StandardScaler\n\n\nfrom collections import Counter\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n%matplotlib inline\ndf = pd.read_csv('..\/input\/creditcardfraud\/creditcard.csv')\n\"\"\"\n# 1. Data exploration\n\"\"\"\ndf.head()\n# Checking NaN objects\ndf.isnull().sum()\n\"\"\"\nAs we can see there are no Nan objects\n\"\"\"\n\"\"\"\n<font size=\"3.5\">Before the data preprocessing let's create some graphs:\n* heatmap of correlations between features;\n* istribution of classes graph.<\/font>\n\n\"\"\"\n# heatmap reflecting correlations between features\n\ncorr_matrix = df.corr()\n\nsns.set(rc={'figure.figsize':(40, 40)})\nsns.heatmap(data=corr_matrix, annot=True)\n# distribution of classes graph\nsns.set(rc={'figure.figsize':(10, 10)})\ndf[['Class']].value_counts().plot(kind='bar').set(xticklabels=[0, 1])\nplt.ylabel('Frequency')\nplt.xlabel('Class')\nplt.title('Distribution of classes')\n\"\"\"\n<font size=\"3.5\">After studing the graphs can make the next inferences:\n* 'Time' and 'Amount' have noteble correlation with some other features. We can drop this features;\n* on the distribution of classes graph we can see totally class disbalance;\n* also we can standardize our data.<\/font>\n\"\"\"\n\"\"\"\n# 2. Data preprocessing\n\"\"\"\n# droping 'Time' and 'Amount' from the whole train dataset\n\ndata_preproc = df.drop(['Time'], axis=1)\ndata_preproc = data_preproc.drop(['Amount'], axis=1)\n# Let's standardize features except target (\"Class\")\nstand_scl = StandardScaler()\nscaled_df = stand_scl.fit_transform(data_preproc.drop(['Class'], axis=1))\n# Let's create DataFrame containing standardized features and target\ncolumns_name = list(data_preproc)\ncolumns_name.remove('Class')\nscaled_df = pd.DataFrame(scaled_df, columns=columns_name)\nscaled_df['Class'] = df[['Class']]\nscaled_df.head()\n\"\"\"\n# 3. SMOTE\n\"\"\"\n\"\"\"\nLet's augment data for the the minority class (Class == 1) by oversampling the dataset using Synthetic Minority Oversampling Technique (SMOTE).\n\"\"\"\nX = scaled_df.drop(['Class'], axis=1)\ny = scaled_df.Class.ravel()\n# Splitting dataset on train and test samples\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\n#using SMOTE algorithm\nsmote = SMOTE()\n\n# fit X_train and y_train\nX_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)\n\n\nprint('Distribution of classes before SMOTE:', Counter(y_train))\nprint('Distribution of classes before SMOTE:', Counter(y_train_smote))\n\"\"\"\n# 4. Logistic Regression\n\"\"\"\n\"\"\"\nTo solve the classification problem let's create and fit Logistic Regression Classifier\n\"\"\"\nlr_clf = LogisticRegression()\nlr_clf.fit(X_train_smote, y_train_smote)\ny_pred = lr_clf.predict(X_test)\nprint('roc_auc_score:', roc_auc_score(y_test, y_pred))\nprint('recall_score:', recall_score(y_test, y_pred))\n\"\"\"\nWe must maximize the recall score, because we have to detect as many frauds as possible.\nLet's try different thresholds of class detecting, and chose the best one.\n\"\"\"\nlist_of_thresholds = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\nfor threshold in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:    \n    \n\n    # Creating and fitting Logistic Regression Classifier on train data\n    lr_clf = LogisticRegression()\n    lr_clf.fit(X_train_smote, y_train_smote)\n\n    # Making a prediction on test data. Evaluating metrics (roc_auc_score, recall_score, precision_score)\n    y_pred_proba = lr_clf.predict_proba(X_test)\n    y_pred = np.where(y_pred_proba[:, 1] > threshold, 1, 0)\n    r_a_score = roc_auc_score(y_test, y_pred)\n    rec_score = recall_score(y_test, y_pred)\n\n    print('threshold:', threshold)\n    print()\n    print('Primary test sample')\n    print('roc_auc_score:', r_a_score)\n    print('recall_score:', rec_score)\n    print()\n    print()\n\"\"\"\nAs we can see the best combination of roc_auc_score and recall_score reaches at the value of threshould 0.2.\n\"\"\"\nlr_clf = LogisticRegression()\nlr_clf.fit(X_train_smote, y_train_smote)\n\ny_pred_proba = lr_clf.predict_proba(X_test)\ny_pred = np.where(y_pred_proba[:, 1] > 0.2, 1, 0)\n\nprint('roc_auc_score:', roc_auc_score(y_test, y_pred))\nprint('recall_score:', recall_score(y_test, y_pred))","meta":"{'source': 'AI4Code', 'id': '845a5ee3f9672d'}"}
{"id":"67144","text":"# 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 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\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\ndataset=pd.read_csv('..\/input\/bank-customers\/Bank-Customers.csv')\ndataset.head(n=10)\ndataset.info()\ndataset.describe()\ndataset.isnull().sum()\nfeatures=dataset.iloc[:,[2,3]].values\n#Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nfeatures=StandardScaler().fit_transform(features)\n#Determing the optimal number of clusters using elbow method\nfrom sklearn.cluster import KMeans\nwcss=[]\nfor i in range(1,10):\n    kmeans=KMeans(n_clusters=i,random_state=0)\n    kmeans.fit_transform(features)\n    wcss.append(kmeans.inertia_)\nplt.plot(range(1,10),wcss)\nplt.scatter(5, wcss[5], c = 'red',s = 100)\nplt.text(5 + 0.5, wcss[5], s = '5 - Clusters', fontsize = 14)\nplt.title('Elbow Method')\nplt.xlabel('number of clusters')\nplt.ylabel('wcss')\nsns.set_style('darkgrid')\nplt.show()\n\"\"\"\nFrom the above plot,we can see that there is sharp turn at 5th cluster,after that there is no significant change in the curve.Hence n_clusters=5\n\"\"\"\nkmeans=KMeans(n_clusters=5,random_state=0)\ny_kmeans=kmeans.fit_predict(features)\n\nplt.scatter(features[y_kmeans==0,0],features[y_kmeans==0,1])\nplt.scatter(features[y_kmeans==1,0],features[y_kmeans==1,1])\nplt.scatter(features[y_kmeans==2,0],features[y_kmeans==2,1])\nplt.scatter(features[y_kmeans==3,0],features[y_kmeans==3,1])\nplt.scatter(features[y_kmeans==4,0],features[y_kmeans==4,1])\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],color='black')\nplt.title('KMeans clustering')\nplt.xlabel('Earning')\nplt.ylabel('Credit Score')\nsns.set_style('darkgrid')\nplt.show()\n\"\"\"\nThus we can clearly visualise 5 clusters on different colors and black dots indicates centroids of the clusters..\nHope you enjoyd my kernel..kindly give me an upvote\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7baf99add3788d'}"}
{"id":"71334","text":"\"\"\"\nStill a **WIP**. \n\"\"\"\n\"\"\"\n<img src=\"https:\/\/cloud.google.com\/images\/products\/tpu\/google-cloud-ai_2x.png\" width=480>\n\"\"\"\n\"\"\"\nRecently, I was lucky to get accepted into the [TRC](https:\/\/sites.research.google\/trc\/) program (short for TPU Research Cloud). I have also participated a bit in the HuggingFace TPU program (even though I wasn't much active due to personal things).\n\nIn a nutshell, this is a free (more details later) TPU program. To apply, here is the link.\n\nThe only requirement is that you follow \"ethical\" AI practices (as defined here) and share as much as possible with the team, write a blog post, a research paper, i.e. contribute something back. \n\nThe requriements don't seem that hard to achieve. \n\nTo contribute my own share, I am writing this notebook detailing my journey. I hope it is good enough. :D\n\n\nAlright, once you have access to the program, you cant start using TPUs.\n\nYou might ask: but how, given I have 0 experience with TPUs?\n\nDon't panic, I will try to make the process as smooth as possible. The documentation is good enough but there are some rough edges and I have tried to take notes of the harder bits. \n\nLet's got!\n\"\"\"\n\"\"\"\nBefore that, we will make a short detour to explain what **TPUs** are and why they might be useful to \nsome of your use cases.\n\"\"\"\n\"\"\"\n# What are TPUs?\n\"\"\"\n\"\"\"\n<img src=\"https:\/\/sites.research.google\/trc\/static\/img\/research_cloud_hero.png\" width=320>\n\"\"\"\n\"\"\"\n<img src=\"data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wCEAAkGBxITEhUSExMWFhUXGB8YGRgYGB4YGhYWFxgaGBUZFxoaHSghGB0lGxgVITEhJSkrLi4uFx80OTQtOCgtLisBCgoKDg0OGxAQGy8mHyUtLS0tLS4wLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf\/AABEIAKkBKgMBIgACEQEDEQH\/xAAcAAEAAgMBAQEAAAAAAAAAAAAABQYDBAcCAQj\/xABNEAABAwIDBAYECQgIBQUAAAABAAIRAwQSITEFBkFRBxMiYXGRFDKBsSMzQlJygpKh0SRTVJOywdLhFiVDYmOiwvAVFzVEczSjs+Lx\/8QAGgEAAgMBAQAAAAAAAAAAAAAAAAQBAgUDBv\/EADkRAAEDAQUFBQYGAQUAAAAAAAEAAhEDBBIhMVFBYXGB8CIykbHBBRNSodHhFTNCVILxFCMkYpLC\/9oADAMBAAIRAxEAPwDtCIiEIiIhCIiIQiIiEIiIhCIiIQiIiEIiIhCIiIQiIiEIiIhCIiIQiIiEIiIhCIiIQiIiEIiIhCIiIQiIiEIiIhCIiIQiw+l0\/nt+0F8u3EDLnynJUS66NrN7nO7TMRnCyA0fRkEhXYGnvGOU+oVXF36RKt+19t0qFF9WQ8tGTGkFz3cGtHMlVal0iOLSTaFpEw11SHOwtxOgYMoHOFhteja0pva9lSsHNMgy3Ij6q37jcuk8uLq9ftgB0OaJgQMg3kpd7uIaeZB8gdN6oL+Z+RHmQo+r0nOaA51k8A6fCDlOfZyyzWs\/pdYDHop\/Wj+FZtv7pWrKVSKjusY3rMILQ55DcLXOyk5CFE7y7jW9GyfcMdULw1ru0REuidB3q9M03DEYzvjPiquFQHA4ctOC3\/8Am8z9Fd+sH8K9npZaMzaO\/WD+Fctt6AyIdJIHZ5GYX2sIHby8M12DKRaSRrrs5rk51QOAB00nyXUW9LTT\/wBo79YP4V6p9KwJgWjv1g4fVUBsnZdq+jSdhxYhLnhxDw\/5oGnLgrLT3BtNQKuefr8x9FUJpDC75q4FU43vJZafSLLMfo0GHENNUS4M9YjswIkalaY6WBBPojsv8UcfYtxm5FAMNMOrBp1b1mR+5YXbh2o\/O\/rP5KjDSE3htwzy0z637LOFTC6fLPVYK3S01pg2jsv8UfgpRu\/TiAepbmJ+MPH6qpW9GxLalRqS2C1pLX4u3jGjSOIjuW3bWT8DDHyR7lD7hAujz3aqWX5N49Yq2t34d+YH6w\/wLftN5nvBIotyHGpA88KowtXhbtrUrN0cR7B+C5wuinrvfWqyrToi0xvqNLm4KwjCMjJLRCwUt\/6he+m6zLHMIBmrPraRhaVWtpMrP2hbhlfqnCk7tQM2yJaG6GVDWlhSdeXPpF6QWCcbX4C\/2g8OS6dmNmW\/6qnanM57vor1f9IzqWHFazimIq8jGhYCsLOk+dLX\/wB0cPqqq7sWNOswuM1nF5aDUc6ermMTCSrOzca3j1agkfP55ngrH3YERjz+qoPeEzMeH0W6\/pBIp9Z6OPVx4et7WCYn1I14TK0mdKUifRDy+NHuw6LONz6QYKfw2DXD1mU+SwVNyrYCSKnP4zj5KrCwA3ht35aZqXCpOB8s\/BfP+agxhno3aJwx1o1JgfJUs7fKqHBnoolwJHwvAZGewqfcbJt6eNzmtiSXlzjLWgZFpHGY9qowfUMlpcY0gkmM\/uV2tY4YDzPqqlzmnE+X0XXrnpCezHNp6hIdFYcImOzJ9YLTb0rTpZu\/WD+Fcz9JfgjE7T55M85HsHkF7ZjwgDLFlrE9xTDbPTuyR5j15pd1epegHyPoOC6OOlgfoh\/Wgf6VuXXSRgaHG2ngQKubSW4gD2OXKVz7c\/YzLuq+k97mhjMUiDOcQrXtLdVtNrPh6jgJaA6CGiOALoC5Vm0WuEbM+8fXVdaRrOE65d0fKF0zZ12K1KnVaCBUYHgHUBwBAPmthc7fvfVtqNOmxjHBjQ2SdQ0AAw0ldAt3ksaTqQCY5kJPDZknMdqyIiIQiIiEIiIhCIiIQsN5oPFarMwtm70HisTMwoQvgC9BfYX0IQojeSi021YkNB6sjERMCO4THgo3fMf1ZUH9xn+lSO89uTQruDnR1RGDLCTnnpMqN33MbLf9Bn+lXZ3hxVX908FyClavc9tNgGJxhsZSfFTW090KwpNc1pLxm8FwgAAzHkOK0t3f\/V0PpBdOvj8FU19U+5OV3lrhHHjnmlLOwOaSf6yyWjuDaxY03FgxHERI4HTwBVkt2y0F8NdGYGYB5AxmouhXBp0GNcRDAHRl\/ZyFlwH57\/NZ1W0Na4yFpUbK57JB3KSwM5\/78lrV7dhmMzw8fJaNWmR8p3mq9tXbbg51KiXYm5Oc49lvH2lc\/wDLboU1T9m1qhhsdclub0W49CrF4a2oaZGo15A8Vp228tLBHwjhhaAwMAIIABzMe9QOJ9R4lzqrjlic44R4BSOztiVatMPNQtBnstGkEhHvaj+4MOuXmnHez7FZTFpqEu+Fv9E+JbwK2ztoHSi\/2mFlpbcYPWpP8RDvcVR95LV9Cv1QqOOQOYHH2LUp3b2jJxJ8B+5dRQtN29I+X0XA2j2OXXbr+v5HyVr2he2la9p1LgO6ltMjEWugPnKYzhRFlebOp1rhz6LnUXfFEtJ8YnSTxKw2e1ajnBpAeTw1n9636lKnWaabsUD5BMFpjVo5dyPfPpkNrCJ00+c+KsfZlC0MNSw1JjGHZ+MCOYj\/AJK7dH1phsGuwQSXlgOoBcSyTGkRmpxjXFoxgNdxAIIHgYzUda7Tp1KFIU3OGHsu+SeyPVPctkMy9Z3mqVLS0OxSLbFUyOBBiDngs5ps4n7x+C17im2DBkxl48OCxuot5uPtX19Fo0LvNVNrZoVb\/CqahRm1LZzrSqCwdYaZkNzz1gHiondDZdJlFr4diqNGOXZceEZaqy0Xhr8yYIGpnOSFE7Df8EwRz95TDXipTjYUq+madTHMKn72bMp0a3V0wYIBzMnMTqo23c0uzMGNSYEiIVg35d+Uz\/cHnCrFUSJ48u5aLTfaGkmSM8DCzSLji5oEA5ard3T3iFnVqVHUzUxtwwCBxmc1aK2\/Tq7T1dpUODtO7Q0g\/gVRWYA5hdm3EMX0eKslptSwpl2Fz2tc0AwHyTnMy3TP3qtekwnIyeK6Uaro2QFbqW69xd0qVX4NjHtDx2iXQ8AiRhXRaDMLWtOoAHkFWd2XXBZQwg+j4G4Zw\/F4ex36QrUkCIwCdBnFERFClEREIRERCEREQhYbvQeK8Mbkvd3oPFeKQy\/3zUIX0hIRfQEIUNvNVqChWAb2eqJxh0EOzyjX2qM36bOy3mdKbCe\/IKV3kuWChWYSC7qi7AeI005KL35\/6VUP+GzL7KuzvDiqv7p4Llm7km6ofSC6het+CqfRPuXLt2nzdUcvlhdO2pcBtKoTkMJzPgmbQDfA6zKXsx7JPWQWvte\/FChbPDMTi1oA0kmnzUhsi6bWpCoBE5e0clTvTXXDKIeMMBrGjXIAAn2xCuVu3C0NEADkFkWym+nWLXiPXetuxuY+gCwzj0FX94NtvbVNuxpGgxcTPBuUe1aTd3n1D2vg26ls4i7vJ4lWp9GXAloJ5xn5pUpgZpPatGnULCC0wVrbH2XTpYmtaIw\/fK19ifEs+t+0VINe4E4RMt8hOq0dhsPUsy5\/tFalm\/LCxLXjWcVSOkKh+U4ubB9yrUnyCtHSOYuBDSCWDPn4KqUXZZnPmfuWtSIuhu2J81j1Gm8XbJ+imd3wTcUjhDZMeMakd6uG1NhscHPnC5oJBGpIE5qlbtuPpFEHtQ7LkF1O7pzTqfQd7ilLQ0OMHRO2Sq+kb9MwQcx146qGu6htaNIkAh0Q7TM64hx8VKbNvOtp4oj+XJZnUMdKkH0+yAAJzB7I4LJhDQABA4BY1dga+At2zVHPZLs5PNQrduYbg0S2Q2JPjpCn3Dko2+sqfZqFoxE4dMyCIn2ZFbNm8wGu1AS99oddJE6LsVkbHWR\/dHvKg9iAmkwxz95UwXEVMhPZHliKr27+1abmdWHdqnOMfN7RWtZ8KQKxrT+cVCb+mLrj6reOWirFSpKn9771lavipvkYQNDwGag\/R9M1uUSBTErCrCahhS26Gx2XdR7HOLQ1uKRzmOKsV3uPRaBFRxnwCqm6u3hZ1KjjTL8TYyMRBmc1Y7\/fyQ0m2qNGoJIzyStV1e8bh4ZJqkyjdF4DerFU3rrWtGnTYxhDGhgk5kNAA0XQqLiWtJ1IBPtColPdR13QpVetDQ9geBhkjG0GDCvlFkNA5ADyCRx254p3DZkvaIiEIiIhCIiIQiIiELU2hdMYBicBOk8Y1Vdqb40mlw6uo4DPE0DC4a5GVIbynNng79ypN5AtXRl2Co2ohWBu\/wBbnIUqvkOHt715uOkO2pgF9OqATA7I15ZHuK5W4r3ekdSNPXH7D12pMa54adpXKo5zWFwOQXRN4N9rV9CozC\/E5uCYBLS5stDozGWaiN5N97evZPtmMqB5Y1oJGXZj8FV9j7SJqA1O01oOUCSYwgk8Y716uLlpJIGucR3roymWvuFpJHw\/SNi5uffZeDgBvHrKhaT3NcCxxDgco1B7lbGXFWuGUqhcA0TUJMgxmNPYo4WReJfDGczr7FjvNpy11KgcLR6zz35T3lagYGxWrYXcRx3xnwxxxOSRBONKmZnPr10kDNXjYFg2rNbFha0w2OGHVWKlYlwDmvcQdCIgqu7lYqNqyi\/CCcTszq3n71b7am4NAa4BsZAZCO5Y1oIrVC9wnTgtWgXUmXWkj6rVGzH\/AD3eQXl2y3QSXv58FJYX\/OX0secsQXD3TPhC6++qfEVCVXso0qlcvL2hhM65DlCgt29r0n0GQ8SBLhObZJMFbm91yGW9aiAB8GYA\/cFU9nbuOpg4LhzcYEw0Z5d67ta0MwwOzRcHucXycdVob\/XTKtZrqVQPGGIGYB7iq91LmNIcIPeM\/YrezcxoiKzpGmQ4KTu90DX7T6xyHBvAJkVGBwjICNN4wjal7jy0zmTx3HaqJsC5bTr03vOFoMkrpt3t+3bRL3VIa9pDTGpIMKmVt02C9ZaurENNPHiIDTn8nxXuz3fFarWtzc\/B0PVmDOWo7gq1LjiDPHA5bt+9Xp3wDhn5710rd24p3VlTqgloAz4QW5O9mS8PoBwltRxHA5QfBV7o+2yKVp1RaC0Pc3ETk4lxyAVoa6R2Q0DgAlX0mFxMSmadV4bAJChNo0KjcJDnOAMkGNOeS2S+YIMAiZWW\/puLHAOAMa8lq2udNs5kZHvWLb6Tadqo1QMCYPjH\/op6z1HvpvBOIy8Pssj6zabHVi4vAbPsGkRzJXI31atJ9R0upl8kjQkGYnzXT7+4xUn02tDcobnkS0gx3aKi3u16Ve46y4pnDgw4RmMTRAlekswDQQG7OsOKx7Q4uIJd1x4KO2TRNaoGNIBM5uMDLVZ6kgloglsjFORg6haVHCMUjTTI8Spe0oOcGNqQC6rlAGTcOfDmu7i8OAcSeWma4tDS0lojnrktS5pyPVicsjM5cV82rtg1GYcAEOBdBJkhuEQD6ogDIKY2tscNaHUy4yYI\/eqs12btfWHDx4\/uXF924H5kHCfDyXRgdfLTgCNnUrse6O\/tu5ttaBlTHhbSmBhxNbBOumRV+X5+3IP5fb\/+UcO4+S\/QKUOKcGGCIiKEIiIhC4U3fG7\/AEup5fyWQb6Xg\/7p\/kPwU0ejm8\/wvM\/gvDuju9+bSP1ynPxR37dvX8Vh3LVo7\/sosb8Xf6U77I\/Bev6c3f6Sfshb56Prz83RP1v5Lz\/QG8\/NU\/to\/FB+3b1\/FF21aP8AFRd3vVXqQX3BJEx2Y119y0qu1C5uE1THKIUzd7oXFOMVFuekGdIn3qO\/4Y7q+tNJuECZnOB3KPxRn7dvX8VH+60f4lRc0vzoXxxoxBfImfbH4ErOatL80hdQw4nUwGzE98E+4FXb7WAMizjr+KoffR2g+Of0WKhUtweyJ8P3rcZeEZU6YZ3xmvNOlbjtCWzxw5ELPRtWn1KsnlEKKntt5wDY+frHyVqbqIMVA6euaxXNImlUc4lzg0woh0swupBzZHaJjN3d3eKmri1rtaSBi9uX3LRq3lQUnY2hokAg658lyZaHVXdp08fDI4csty0WvolsU\/DI67YK+0N4LsMFNr5GgJbLgCZIB5KRbvbtMZCq\/wCz\/JWfdCn1trSNNoAgh2QMvn1gfLyV3ovYAAQCQMzhC6vrMa4i4FLKT3Cb565rj7t8dqfnH\/Y\/kvn9M9p\/nH\/q\/wCS7J1rPm\/5Qsb6zB8n\/KFT37PgHXJW9y\/4z1zXEb7eW7qjBVMgmC4sh0EiWyuhUqMNbkRkOHcm9lsTQrvAGAMLoLR6wMyCoO13y6xrgy3quiCe00xAjKT3KHdtstEAfZWb2DBMqwwsoqOEQSqeN96evVv+5e277UjpTf5hV90\/RX963Ve9sG1O0fyuS3qhh19bPVVZlO2NSpD3MbiIaCS3sd\/NSVfeRnpouTRJaGYcJifEcFko7VtC+vXuLZw6z4qWyNOB0meK63HtGRyGS5hzXbRmc182PW6oGnSqjCYMHQa4nNMZuHJfH7e2gMhVqRw+D4eSmtxtnufbh7BBLjmc+yDGFXZtIAQTn7FyJuvO3j1tVwLzRs647FyV+8e0CD8K\/wBrP\/qrjtG5fTsS8E44yIGc5ZwpXatRvqNzJML2YEN5DTmVie0niraqFIa3j4g+TStCytLKNRx4deIXMWbbugILicTgXS31ZyJ0yyVzbYUMDm4WwSSexxaOznPis9e3wU6jsOUkun5QdlB8x5KlVNgXDH1KXWgQBUIxkCCCW+MBbhAqNzux88fRZwJYcp69Vi2izBXrNYMgYgZQF4xFlIEPLj1gOIGcMDRaVuT2sxpxz48Ft1MHU\/B5jrBimfWwj7k25oFZgKVaZpPIUztS5bVbgpudixtwkyBGATn4yqvUoljntdwcJg5cdO\/vVuq3L3EA0cA6xpmRlDAI9uRVY2oR19XT4z28fuSzzFKN+oO3cmGD\/VndvHmpXcd35fbd9Ue4r9Br897kf9Qthl8aPc7RfoRKplEREIRERCEREQhEREIWjtSzDwDnI0jv8fBU2vuhXLXU2VGdXoA+SY4zHfJV7uDl7Vhpun\/fLJQhc8\/5cVJ+Mpxy7X4rFc9GdVzQwVabQHYsg4yQCBqf7xXS2r3Ks1xaZCgtBEFcv2puLXp0n1OtZAGJ2Rd6jY7Ins5KK2tuXcULZ1yazHNDQ6A0gwYI4966dvHaB1Gs8F2LqnNADoB46aT3qM3zH9U1R\/gt\/wBKtTdENgROipUYHAk9ei5FZ31YOAYSSeAz14Qp6tSLmD0ijAIzMer4tULsGPSaPe4Lol+3su8D7la1UGXhdEf3os+nZGVGk5Hd9P6Wju5dNtqXVDOiSYcDm3F7labDatEMDA8Ow5SSST4nmqdV2a9rKb6LIxMEtnJ\/YkkDgVqUrgDtU5a8asPHnHNJGq5mBzXei99Oo2nWmDgCBPhrvGfFdEO1KfNv3rHUvmOBGJueWUqG2RdtqtBBz4qRIXIWs6LdNhA\/V8lhvbNtW1qW7KkksLZOZz0nmoXdfY1Btuw9WMbmw8\/OIJBU3Sc5rnYRJw58MpWhsOp8Cz637RTtOoalPFIVqYp1CNFz3fTZTKVwW02BjCARGkmZUVb2sA5jxVm37aDcnPPANdFW2kBsnPwT93BriP0nH7JAuMloP6hh91vbIpMdWZSeJBMZZFXbaO71CpQFMhwbTaS3taQ3JUjd5\/5RTdMSfNdHq1B1dT6DvcVxrd4Rsy3LtRHZM7Vk3Vsm21nTp1H5uBJI\/v5wPCVsVLyixsB88BMkn7s1rVKzhTp4gAAMj9UKKpXbH1Ti9VvHhJ4eKy7XbHUpIbOErTs9jbUZMxsW\/QbmarvYFstawj1xnrkZ9y8B+IwBkNFndAWVYnP94601B2nZbh94HIb06+zhzAwGAOvvxSvaMqUH0Kb8y2ATmQdQTOuYXIdr3lRzyaj8T29mdJDcgPBdet3uxy0Tk2Zyykqt7B3cYQ+q6pPWz2cPq5u0PtXpbLaYYXEY7Bz1Kw7XZv8AUuA4DPw0XPrQyHcMuB1z71t1XzQkNwRUGXPs6rd3h2XTtLhrc6jJDiNJacy0ezJaO071lSoXMYKbDEMmQDxKdAN5rhJAGiTJF1wMAnepXYlevd1OrDmyD1meQ7AAH3LJtrcuq7rauNpIaXkaacBmo3dmxuKlR\/o7mtcBmTyPBTlzsnaEEPrNIcCCJP4LjU7LiJAGnhOzRdmYtBgk9b9Vft09zbNtK1uRS+GFNj8WI+uWCTHtKuSottvrStaNGk+k84KbWkjm1oBiQrxTfIB5ifNKGJwTImMV6REUKUREQhEREIRERCFiutPasLAst3oPFYaYgff5mVCFkC+yvIK+oQoneU1OorQG4OqdOuLFB04RCjN8Xf1S\/wD8LfcFJ7xXjW0azIOLqnESwuacog5R7ConfUTsp5j+ybPIZDhwVm5jiodkVy\/YeVxRg\/KC6BdmWP8AA+5c93fH5TRGvaC6NcsGB+XyT7k1aO91qUtZu71oFshp6q1j5g\/+Na9xs+k6S5gxH5QycI0grYoUy2lQJdkWN10Hwa+lzfnDzCxbV+ZyW9YoNLHVRFrYVWVQWwW8XTBPLIKR2hWdhIZrGS2W1GgesPMLVeQTMjzSyczUXsrar6eIVQZiDz5zHEL7sG6BptbOYJkcRLiQtm9sPSGkNcA4NlrtYM6ZKsW21Kb3YXuwVGHDjHNpiHcwt32ZZDWpHtY7Bt57tmE8Fge067adXAcdMhEac4WHfh5Fx63yRkNVXqDokkSO8ZeSndu9d1raxZIAAxt7QdHHuUHd3WJxcZHdzWhcdTaGuGzPodaLMJDnEjXrPretnYdbFcUyGAZ6ae1dBJOCpl8h3uK5hs3alNtam53ZAOZHvKvx27Q6sux5PaQ3KZkZZcEjU7ThGKcpi6DK3t5Q82tJtMEugZDUjCJhQmzXiiwCtIcM209TnxPetmptl5aDSkQ2Mb8g3IA4RxKi6EvJNOSZ7dV2p7god7Jc5rq1Z1wAYTrsnTgMSmKPtQMu0aTb5JxjTd9TgpOzq1jWLxilxADeFNv97hPcrPVIMTqtKzLGgRA\/3mtt4B+UPNYK3ytjZ3rn6I95UXu+4dQzPn+0VuUaWJxhxEAGQe85FRewn\/As148O8rUs\/wCWFi2v853WxVvf9s3QgD1G+OiqNVkK379n8p8WAfcqxVZlBzPOeBWzRcQ1ojCFi1GgucZxnJSu4m1KVCpUNV2EOaADBOcqz7S3ktXARV0OeR\/BUzZ1x1YY3sYXOg82gnU8FYA63Mg1GARMyM51Hs\/elq1MFxmcetExRqENw2daqUv927qvTY+lSLmubiBxDNrgC3IldZoDstnIwPcqxu3tSuepp9X8FhAD8DhLQ3smdOA81akpEYJoGcUREUKUREQhEREIRERCFgu9B4rBTmM+Z9+Sz3YMZDioO43gtabiypXpseNWk5jl9yiCTgoJAzUwCvQKgxvVY\/pVLz\/kvX9KrH9Kpef8la47Q+BUX26ra3gj0atMx1bpjXTgobe8\/wBU1I06lvjoE3h2jZuovqda3G6mWsOIiZBIA4eajt5duWz9mvptrsc80mtwgycQAke9TTaSRA2qHuABnRcos7p1J4e0w5pkHX\/9Vlvt6qrqDAwkPdk8logjOY+5V2icsJDY79TpxXu8MiAA2PDhqn3MLnS4ZE89OWKSa8AANOccvuus7lXjq1jTc8AlssHeG6T3qZt6Yc0FzQwnVpgx7VSt0nmlbUj1jiCC\/gKbTxDj7BqeKtlHbFtAxXFKePbGvmk394wE2zuhbhoN5jyXipRbHA90LAdsWn6RS+2PxXk7ZtIn0il9sfiq4q2C1Nq3DqVpUrBga9rC7CTMEd41VBZuM9zW1RcHE8YzLJzdmdHKxb03eK3rubUOF1MwZBpkaQO8rzZ7ac2nTGHRoGvd4Lo17mCRgZ9FQta4wVG2mxLmkOzXB7iwgftFKthWd61ux57iAT7lK\/8AHT8wef8AJembXn5A80032hWGcHiPUQVxNjpHLDrfKqdy2jTcxtS26svEtxOiQPbl7V4o7Roy4NNKng4uMz9DXEpbatVpvqBqUXVx1boYBjgyO1ByyURZbRs6Ne5622LcRhrS0HDzbB9WTyXb8RruENAy3nzJC5\/4dJuJO3cPISrDutsxt1RFxUl5JOFhMN7JICttvTLWiGBuXq6x7eKpW49xFDGHnAHuAptIhgJJ7Q\/erINu2\/G4Z9sJGtUqVHdozHy5DBMUmMa3sqTdJ4DyXwud80fiow7dt\/0in9teTtu319IZ9tcoK6SFtbavH07WrVDcL20yY1g6a8dVCbqXrDa0peMQaMWeh4zyXzaNTr6NUdd8G4ESCCBGf7lzbZm0KlLFgcAHZHIGY0iRlqrBpLTGagmDuVp38qB1fE1wcMLcwZ4cwYVVeVtUw5wyAJIGkzJ4RxWKswzBEHTRaVIhrI01wWdUBL51W3sTZL7kuaxzQWiTi78lLVt0qzBrTz8eXgtTcratK3qVDWcWgtAGROc9ys97vPaOAipMSc2HTukJWtVrBxujDhKZpUqRAk48VP0d9\/RaNGm6gSGsayQ75jQCYIV+pukA8xPmuU7R3Zuq9Jj6VIFrhiHaa2WuALTmV1WiDhbOsD3JHMYp2IyyXtERCEREQhEREIRERCEVefuNs4kk2rCTmdfxVhRWa4tyMKC0HMKp7T6P7F9J7aVBlOoWnA8T2XfJOukqs7O6PrumxzS6kZM5VHAOkEQ8dXmM5XUkUuqOc264yM\/D5qoY0OvDNcpq9Hl65oBNvwLiHPBcWtwtJ7HLktKt0W3pMipRH13\/AMK7GisKxAgARwVTRaTOM8VxodFN5+do\/bf\/AAr2\/ouvT\/aUPtP\/AIV2JFYWh4ECFDqDHGSuQU+i+9DcPW0o5Y3geWGCvr+i+7M9qgJM+u\/L\/IuvIoFZwy66hSaLTmuX23R9dNpFhdSJz+W7C7F88dXnHBRz+i28IAFSgB9J+f8AlXYUVG1C0kgDHHqVJpggDHBcaqdFV8RBrUY5Ynx5YFcqmwLnq8GCmTha3KqSOzxAdTEeauaKXVXOzQ2m1uS5s\/dK7\/Nt+2F9pbqXYPxbfthdIRUlXhc7q7qX\/XMr0TRYWsLCKhJxAmfkg8lq0twr01H1Kzrd7nkGQ5wIjhnTIj7105FN7CFF3GVy2+6OrpxaWGi2Jntul2eQMNAgeC1WdF10BGOjxPrP48PVXXEVxVcAAFU0mkklcvf0eXXU9VNGdJL3YdZxRg9bvlR9XotvTEPtwIGWJ\/DQ+ouwIqtfdmAMTKksmJJwwXJbTozvWODusokAglmJ+F0GYPYU+7dOv1jX9TZwGlpbJgkkGfiY+5XtFLqhdmoFNrclzK63BvHPLmm3Y3rOsDQ53ZOWXqARlyWhW6Mb1xnraM5\/Kfx+ouuIrCu4ZR4KDRac1xh3RFeH+1o+b\/4VLX3R1dPa0B1AEZmXPcB2QIaMGQ4wuooofVc9zXOiRkpbSa0EDI5rW2bbdVRp0pnAxrZ54QBP3LZRFyXREREIRERCEREQhEREIRERCEREQhEREIRERCEREQhEREIRERCEREQhEREIRERCEREQhEREIRERCEREQhEREIRERCEREQhf\/9k=\">\n\"\"\"\n\"\"\"\n**[TPU](https:\/\/en.wikipedia.org\/wiki\/Tensor_Processing_Unit)s**, short for **Tensor Processing Units**, are custom hardware developed by Google around 2015 (probably even before), annonced in the 2016's Google I\/O event and made available to the public around 2018.\n\nSimilar to GPU which are custom hardaware adapted to graphical processing and later on to deep learning and \nother data processing tasks, TPUs have been designed from the get go to work and scale with machine learning workloads. They are, what is called **ASIC**: application-specific integrated circuit.\n\nSo far, there are mainly two versions (check the graph below) that you can use: \n\n\n- v2.8\n- v3.8\n\nThere are slight variations of each major version, check it in this table: \n\n![tpu versions](https:\/\/drive.google.com\/uc?id=15JXDTc2NAA7pafArHgdRX-wonXfs9BeN)\n\n\nNext question is: how to access these TPUs?\n\"\"\"\n\"\"\"\n# TPU VMs\n\"\"\"\n\"\"\"\nBefore we start, notice that there are many other methods but I will only focus on the \nmost convenient and scalable one I have found. Also, this method \n\nIndeed, TPUs are available using at least these methods:\n\n# TODO: Finish adapting\nInstead of setting your own TPU pod\/instance, you can also take advantage of the Colab offered TPU and the Kaggle one.\n\nHere is how to do it in Colab: https:\/\/colab.research.google.com\/notebooks\/tpu.ipynb\n\nAnd here is how to do it in Kaggle: https:\/\/www.kaggle.com\/docs\/tpu\n\n- Kaggle of course\n- TPU pods\n- Colab\n- TPU VMs\n\n\nThe last method is the one we will focus on. This is probably the easist why to get started and have your env setup with everything needed. \n\nIn fact, since you have access to a VM, what you do will be persisted.\n\nNotice that this is still an early feature (as of July 2021) so be careful (don't use it in \nproduction) and help the dev by reporting bugs. \n\"\"\"\n\"\"\"\n# What is XLA?\n\"\"\"\n\"\"\"\nIn order to use something different than Tensorflow which is equipped to understand low level TPU things, \nPyTorch needs some understanding of these things. \n\nFor that, there is [XLA](https:\/\/www.tensorflow.org\/xla?hl=en).\n\"\"\"\n\"\"\"\nHere is an extract from the [XLA Github](https:\/\/github.com\/pytorch\/xla) repo:\n    \n> PyTorch\/XLA is a Python package that uses the XLA deep learning compiler to connect the PyTorch deep learning framework and Cloud TPUs. You can try it right now, for free, on a single Cloud TPU with Google Colab, and use it in production and on Cloud TPU Pods with Google Cloud.\n\"\"\"\n\"\"\"\nUnder the hood, it uses the TF XLA [compiler](https:\/\/www.tensorflow.org\/xla).\n\"\"\"\n\"\"\"\n# Application\n\"\"\"\n\"\"\"\nAlright, enough with exposition and theory. Time for some application.\n\nFor that, we will use the Kaggle TPU and PyTorch thanks to XLA.\n\nWe will also use the CommonLit readability [dataset](https:\/\/www.kaggle.com\/c\/commonlitreadabilityprize).\n\"\"\"\n\"\"\"\n## Dataset\n\"\"\"\n\"\"\"\nWe start as usual with any PyTorch dataset.\n\nTODO: Finish adapting this dataset.\n\"\"\"\nfrom torch.utils.data import Dataset\nimport torch\n\n\nclass DatasetRetriever(Dataset):\n    def __init__(self, data, tokenizer, max_len, is_test=False):\n        self.data = data\n        self.excerpts = self.data.excerpt.values.tolist()\n        self.tokenizer = tokenizer\n        self.is_test = is_test\n        self.max_len = max_len\n    \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, item):\n        if not self.is_test:\n            excerpt, label = self.excerpts[item], self.targets[item]\n            features = convert_examples_to_features(\n                excerpt, self.tokenizer, \n                self.max_len, self.is_test\n            )\n            return {\n                'input_ids':torch.tensor(features['input_ids'], dtype=torch.long),\n                'token_type_ids':torch.tensor(features['token_type_ids'], dtype=torch.long),\n                'attention_mask':torch.tensor(features['attention_mask'], dtype=torch.long),\n                'label':torch.tensor(label, dtype=torch.double),\n            }\n        else:\n            excerpt = self.excerpts[item]\n            features = convert_examples_to_features(\n                excerpt, self.tokenizer, \n                self.max_len, self.is_test\n            )\n            return {\n                'input_ids':torch.tensor(features['input_ids'], dtype=torch.long),\n                'token_type_ids':torch.tensor(features['token_type_ids'], dtype=torch.long),\n                'attention_mask':torch.tensor(features['attention_mask'], dtype=torch.long),\n            }\n\"\"\"\n## Model\n\"\"\"\nfrom torch import nn\n\n\n# TODO: Adapt this to Pytorch Lightning.\n\nclass CommonLitModel(nn.Module):\n    def __init__(\n        self, \n        model_name, \n        config,  \n        multisample_dropout=False,\n        output_hidden_states=False\n    ):\n        super(CommonLitModel, self).__init__()\n        self.config = config\n        self.roberta = RobertaModel.from_pretrained(\n            model_name, \n            output_hidden_states=output_hidden_states\n        )\n        self.layer_norm = nn.LayerNorm(config.hidden_size)\n        if multisample_dropout:\n            self.dropouts = nn.ModuleList([\n                nn.Dropout(0.5) for _ in range(5)\n            ])\n        else:\n            self.dropouts = nn.ModuleList([nn.Dropout(0.3)])\n        self.regressor = nn.Linear(config.hidden_size, 1)\n        self._init_weights(self.layer_norm)\n        self._init_weights(self.regressor)\n \n    def _init_weights(self, module):\n        if isinstance(module, nn.Linear):\n            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n            if module.bias is not None:\n                module.bias.data.zero_()\n        elif isinstance(module, nn.Embedding):\n            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n            if module.padding_idx is not None:\n                module.weight.data[module.padding_idx].zero_()\n        elif isinstance(module, nn.LayerNorm):\n            module.bias.data.zero_()\n            module.weight.data.fill_(1.0)\n \n    def forward(\n        self, \n        input_ids=None,\n        attention_mask=None,\n        token_type_ids=None,\n        labels=None\n    ):\n        outputs = self.roberta(\n            input_ids,\n            attention_mask=attention_mask,\n            token_type_ids=token_type_ids,\n        )\n        sequence_output = outputs[1]\n        sequence_output = self.layer_norm(sequence_output)\n \n        # multi-sample dropout\n        for i, dropout in enumerate(self.dropouts):\n            if i == 0:\n                logits = self.regressor(dropout(sequence_output))\n            else:\n                logits += self.regressor(dropout(sequence_output))\n        \n        logits \/= len(self.dropouts)\n \n        # calculate loss\n        loss = None\n        if labels is not None:\n            loss_fn = torch.nn.MSELoss()\n            logits = logits.view(-1).to(labels.dtype)\n            loss = torch.sqrt(loss_fn(logits, labels.view(-1)))\n        \n        output = (logits,) + outputs[1:]\n        return ((loss,) + output) if loss is not None else output\n\n# TODO: Integrate with the TPU model. \n\"\"\"\nThat's it for today, I hope you found something useful here (or in the different links).\n\nStay tuned for the upcoming notebook: JAX meets TPUs. \n\"\"\"\n#\u00a0TODO: What about JAX? Maybe not. \n\"\"\"\n## Bonus: JAX\n\"\"\"\n\"\"\"\n[JAX](https:\/\/github.com\/google\/jax) is another interesting library that can be used with TPUs. Some even say that it is the way to go.\n\nIndeed, that makes sense since it was designed with XLA in mind.\n\"\"\"\n\"\"\"\n## Resources\n\"\"\"\n\"\"\"\nAs always, before leaving, some resources to dig deeper into the subject.\n\"\"\"\n\"\"\"\n- Original notebook for the model: https:\/\/www.kaggle.com\/rhtsingh\/commonlit-readability-prize-roberta-torch-infer-3 and \nhttps:\/\/www.kaggle.com\/tensorchoko\/commonlit-readability-roberta\n- https:\/\/cloud.google.com\/tpu\n- https:\/\/cloud.google.com\/tpu\/docs\/beginners-guide\n\n- https:\/\/www.kaggle.com\/c\/jigsaw-multilingual-toxic-comment-classification\/discussion\/159723\n\n- https:\/\/www.kaggle.com\/c\/jigsaw-multilingual-toxic-comment-classification\/discussion\/159723\n\n- https:\/\/blog.goodaudience.com\/how-to-use-google-cloud-tpus-177c3a025067\n\n- Very useful notebook on using TPU with XLA for NLP: https:\/\/www.kaggle.com\/philippsinger\/xlm-roberta-large-pytorch-pytorch-tpu?scriptVersionId=3846258\n\n- Pytorch's XLA guide: https:\/\/pytorch.org\/xla\/release\/1.7\/index.html\n\n- Introductory post to TPU VMs: https:\/\/cloud.google.com\/blog\/products\/compute\/introducing-cloud-tpu-vms\n- Cloud TPU pricing: https:\/\/cloud.google.com\/tpu\/pricing\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '8338c0308439e2'}"}
{"id":"34270","text":"\"\"\"\n![](https:\/\/cdn-images-1.medium.com\/max\/2000\/1*d-ZbdImPx4zRW0zK4QL49w.jpeg)\n\"\"\"\n%%html\n<style> \n@import url('https:\/\/fonts.googleapis.com\/css?family=Orbitron|Roboto');\nbody {background-color: gainsboro;} \na {color: #37c9e1; font-family: 'Roboto';} \nh1 {color: #37c9e1; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;} \nh2, h3 {color: slategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;}\nh4 {color: #818286; font-family: 'Roboto';}\n#span {text-shadow: 4px 4px 4px #aaa;}\ndiv.output_prompt, div.output_area pre {color: white;}\ndiv.input_prompt, div.output_subarea {color: #37c9e1;}      \ndiv.output_stderr pre {background-color: gainsboro;}  \ndiv.output_stderr {background-color: slategrey;}       \n<\/style>\n\"\"\"\n# &#128203;  Introduction\n\nLorsque vous travaillez avec pandas sur des petits dataframe (moins de 100 m\u00e9gaoctets), la performance est rarement un probl\u00e8me. Lorsque nous passons \u00e0 des donn\u00e9es plus volumineuses (de 100 m\u00e9gaoctets \u00e0 plusieurs gigaoctets), les probl\u00e8mes de performance peuvent allonger consid\u00e9rablement la dur\u00e9e d'ex\u00e9cution et faire \u00e9chouer le code en raison d'une m\u00e9moire insuffisante.\n\nDans cet article, nous allons apprendre \u00e0 optimiser  la m\u00e9moire, comment r\u00e9duire l'empreinte m\u00e9moire d'un dataframe sur les courses hippiques de pr\u00e8s de 90%, simplement en s\u00e9lectionnant les types de donn\u00e9es appropri\u00e9s pour les colonnes.\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport seaborn as sn\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\npd.options.display.max_columns = 999\ncourses = pd.read_csv(\"..\/input\/export-1-pt-utf.csv\", parse_dates=['cr-Date'])\ncourses.head()\n\n\ndataTypeDf = pd.DataFrame(courses.dtypes.value_counts()).reset_index().rename(columns={\"index\":\"variableType\",0:\"count\"})\nfig,ax = plt.subplots()\nfig.set_size_inches(20,5)\nsn.barplot(data=dataTypeDf,x=\"variableType\",y=\"count\",ax=ax,color=\"#34495e\")\nax.set(xlabel='Type de Variables', ylabel='Quantit\u00e9',title=\"Quantit\u00e9 variables par type\")\n\n\n\"\"\"\n# &#128203;  Analyse de la m\u00e9moire\n\nPar d\u00e9faut, pandas se rapproche de l'utilisation de la m\u00e9moire de la trame de donn\u00e9es pour gagner du temps. Parce que nous sommes int\u00e9ress\u00e9s par la pr\u00e9cision, nous allons r\u00e9gler le param\u00e8tre memory_usage sur'deep' pour obtenir un nombre pr\u00e9cis.\n\"\"\"\ncourses.info(memory_usage='deep')\n\"\"\"\nNous pouvons voir que nous avons 19 869 lignes et 69 colonnes. Pandas a d\u00e9tect\u00e9 automatiquement les types pour nous, avec 63 colonnes num\u00e9riques et 6 colonnes d'objets. Les colonnes d'objets sont utilis\u00e9es pour les cha\u00eenes de caract\u00e8res ou lorsqu'une colonne contient des types de donn\u00e9es mixtes.\n\nAfin de mieux comprendre o\u00f9 nous pouvons r\u00e9duire l'utilisation de la m\u00e9moire, examinons comment pandas stockent les donn\u00e9es en m\u00e9moire.\n\nDans Pandas, chaque type de donn\u00e9es entiers, flottants et objets sont stock\u00e9s s\u00e9paremment. Chaque type a une classe sp\u00e9cialis\u00e9e dans le module pandas.core.internals. Pandas utilise la classe ObjectBlock pour repr\u00e9senter le bloc contenant les colonnes de cha\u00eenes et la classe FloatBlock pour repr\u00e9senter le bloc contenant les colonnes de floats et IntBlock pour les entiers.\n\nComme chaque type de donn\u00e9es est stock\u00e9 s\u00e9par\u00e9ment, nous allons examiner l'utilisation de la m\u00e9moire par type de donn\u00e9es. Commen\u00e7ons par examiner l'utilisation moyenne de la m\u00e9moire pour le type de donn\u00e9es.\n\"\"\"\nfor dtype in ['float','int','object']:\n    # Pour retourner un sous ensemble d'un Dataframe en fonction du type des colonne\n    selected_dtype = courses.select_dtypes(include=[dtype])\n    # memory_usage retourne la m\u00e9moire utilis\u00e9e en byte des colonnes\n    usage_moyen_b = selected_dtype.memory_usage(deep=True).mean()\n    usage_moyen_mb = usage_moyen_b \/ 1024 ** 2\n    print(\"Usage moyen de la m\u00e9moire pour le type {} : {:03.2f} MB\".format(dtype,usage_moyen_mb))\n\"\"\"\nNous pouvons voir au premier coup d'oeil que la majeure partie de notre m\u00e9moire est utilis\u00e9e par nos colonnes d'objets. Nous y reviendrons plus tard, mais voyons d'abord si nous pouvons am\u00e9liorer l'utilisation de la m\u00e9moire pour nos colonnes num\u00e9riques.\n\n# &#128203; Diff\u00e9rents types d'entiers et de flottants\n\nOn trouve plusieurs types d'entiers :\n* int8\n* uint8\n* uint16\n* int16\n* int32\n* uint32\n* int64\n* uint64\n\nOn trouve plusieurs types de flottants :\n* float16\n* float32\n* float64\n\nNumpy nous permet d'avoir des infos sur les diff\u00e9rents types. La fonction numpy.iinfo nous donne les infos sur les valeurs max et min du type de variable.\n\n\"\"\"\nint_types = [\"uint8\", \"int8\", \"int16\", \"uint16\", \"int32\", \"uint32\", \"int64\", \"uint64\"]\nfor it in int_types:\n    print(np.iinfo(it))\n\"\"\"\nOn peut voir de suite les diff\u00e9rences avec les uint qui ne sont pas sign\u00e9s.\n\n# &#128203;  Optimiser nos colonnes en fonction du sous type\n\nPandas nous propose une fonction pour changer le type d'une colonne. Cette fonction est **to_numeric()**.\nComme nous l'avons vue pr\u00e9c\u00e9demment, nous utiliserons DataFrame.select_dtypes pour ne s\u00e9lectionner que les colonnes enti\u00e8res, puis nous optimiserons les types et comparerons l'utilisation de la m\u00e9moire.\n\n\"\"\"\n# Cr\u00e9ation d'une fonction de mesure de la m\u00e9moire\ndef usage_memoire(pandas_obj):\n    # Notre objet est il un Dataframe ?\n    if isinstance(pandas_obj,pd.DataFrame):\n        # Somme de toutes nos colonnes\n        usage_b = pandas_obj.memory_usage(deep=True).sum()\n    else: # C'est alors une s\u00e9rie\n        usage_b = pandas_obj.memory_usage(deep=True)\n    # convertion des bytes en Mo\n    usage_mb = usage_b \/ 1024 ** 2 \n    return \"{:03.2f} MB\".format(usage_mb)\n\n#On cr\u00e9\u00e9 un nouveau dataFrame avec uniquement les colonnes de types entiers\ncourses_int = courses.select_dtypes(include=['int'])\n# On va forcer la conversion en entier non sign\u00e9\nconvertion_int = courses_int.apply(pd.to_numeric,downcast='unsigned')\n\nprint(usage_memoire(courses_int))\nprint(usage_memoire(convertion_int))\n\n# on va cr\u00e9er un nouveau dataframe pour voir les changement de type\ncompare_ints = pd.concat([courses_int.dtypes,convertion_int.dtypes],axis=1)\ncompare_ints.columns = ['avant','apres']\ncompare_ints.apply(pd.Series.value_counts)\n\"\"\"\nOn remarque que nous sommes pass\u00e9s d'une taille de 1,52 Mb \u00e0 0,19 Mb soit une baisse de 87% de l'occupation en m\u00e9moire !\n\nOn peut voir dans le tableau qu'avant nos entiers \u00e9taient de la forme int64. D\u00e9sormais, ils sont au forat unint8.\n\nNous allons poursuivre en faisant la m\u00eame chose mais avec nos flottants.\n\n\"\"\"\ncourses_float = courses.select_dtypes(include=['float'])\nconvertion_float = courses_float.apply(pd.to_numeric,downcast='float')\n\nprint(usage_memoire(courses_float))\nprint(usage_memoire(convertion_float))\n\ncompare_floats = pd.concat([courses_float.dtypes,convertion_float.dtypes],axis=1)\ncompare_floats.columns = ['avant','apres']\ncompare_floats.apply(pd.Series.value_counts)\n\"\"\"\nNous sommes pass\u00e9s de float 64 en float 32. Du coup, on gagne presque 50% en m\u00e9moire.\n\nA partir de cela, on peut cr\u00e9er un DataFrame avec ces nouveaux types.\n\"\"\"\noptimise_gl = courses.copy()\n\noptimise_gl[convertion_int.columns] = convertion_int\noptimise_gl[convertion_float.columns] = convertion_float\n\nprint(usage_memoire(courses))\nprint(usage_memoire(optimise_gl))\n\"\"\"\nOn peut voir que globalement on a gagn\u00e9 environ 30% en m\u00e9moire. Ce qui est d\u00e9j\u00e0 pas mal. Imaginez si notre dataFrame faisait plusieurs Gigas...\n\nMaintenant essayons de nous attaquer au type Objet.\n\nLes cha\u00eenes de caract\u00e8res sont stock\u00e9es de mani\u00e8re fragment\u00e9e, ce qui consomme plus de m\u00e9moire et ralentit l'acc\u00e8s. Chaque \u00e9l\u00e9ment d'une colonne d'objet est en r\u00e9alit\u00e9 un pointeur qui contient l'\"adresse\" de l'emplacement de la valeur r\u00e9elle dans la m\u00e9moire.\n\n# &#128203; Optimisation des types Object\n\nPandas poss\u00e8de un type Categoricals. Ce type utilise des valeurs enti\u00e8res sous le capot pour repr\u00e9senter les valeurs dans une colonne, plut\u00f4t que les valeurs brutes. Pandas utilise un dictionnaire de mappage s\u00e9par\u00e9 qui mappe les valeurs enti\u00e8res sur les valeurs brutes. Cette disposition est utile lorsqu'une colonne contient un ensemble limit\u00e9 de valeurs. Lorsque nous convertissons une colonne dans la cat\u00e9gorie dtype, pandas utilise le sous-type int le plus efficace en espace qui peut repr\u00e9senter toutes les valeurs uniques dans une colonne.\n\n![](http:\/\/www.logiciels-professionnels.com\/Capture.PNG)\n\nPour avoir un aper\u00e7u des colonnes o\u00f9 nous pourrions utiliser ce type pour r\u00e9duire la m\u00e9moire, jetons un coup d'oeil au nombre de valeurs uniques de chacun de nos types d'objets.\n\n\n\"\"\"\n# On cr\u00e9\u00e9 un dataframe avec uniquement les colonnes de types objet\ncourses_obj = courses.select_dtypes(include=['object']).copy()\ncourses_obj.describe()\n\"\"\"\nUn coup d'\u0153il rapide r\u00e9v\u00e8le de nombreuses colonnes o\u00f9 il y a peu de valeurs uniques par rapport \u00e0 l'ensemble des 19869 lignes  de notre ensemble de donn\u00e9es.\n\nAvant d'aller plus loin, nous allons commencer par s\u00e9lectionner une seule de nos colonnes d'objets, et regarder ce qui se passe dans les coulisses lorsque nous la convertissons en type cat\u00e9gorique. Nous utiliserons la troisi\u00e8me colonne de notre ensemble de donn\u00e9es, cr-etat du terrain.\n\nEn regardant le tableau ci-dessus, nous pouvons voir qu'il ne contient que six valeurs uniques. Nous allons le convertir en cat\u00e9gorique en utilisant la m\u00e9thode .astype().\n\"\"\"\netat_terrain = courses_obj[\"cr-etat du terrain\"]\nprint(etat_terrain.head())\n\netat_terrain_cat = etat_terrain.astype('category')\nprint(etat_terrain_cat.head())\n\"\"\"\nComme vous pouvez le voir, outre le fait que le type de colonne a chang\u00e9, les donn\u00e9es sont exactement les m\u00eames. \n\nDans le code suivant, nous utilisons l'attribut Series.cat.codes pour retourner les valeurs enti\u00e8res que le type de cat\u00e9gorie utilise pour repr\u00e9senter chaque valeur.\n\"\"\"\netat_terrain_cat.head(10).cat.codes\n\"\"\"\nSur les premi\u00e8res courses l'\u00e9tat du terrain ne change pas et nous avons toujours la valeur 1, qui correspond \u00e0 \"terrain bon\".\n\nV\u00e9rifions ce que cela donne au niveau de la m\u00e9moire.\n\n\"\"\"\nprint(usage_memoire(etat_terrain))\nprint(usage_memoire(etat_terrain_cat))\n\"\"\"\nNous sommes pass\u00e9s de 1,3 Mo de m\u00e9moire utilis\u00e9e \u00e0 0,02 Mo de m\u00e9moire utilis\u00e9e, soit une r\u00e9duction de 98 % ! En effet, nous sommes pass\u00e9s \u00e0 6 valeurs uniques sur plus de 19 000 lignes.\n\nBien que la conversion de toutes les colonnes de ce type semble attrayante, il est important d'\u00eatre conscient des compromis \u00e0 faire. Le plus important est l'incapacit\u00e9 d'effectuer des calculs num\u00e9riques. Nous ne pouvons pas faire d'arithm\u00e9tique avec des colonnes de cat\u00e9gories ou utiliser des m\u00e9thodes comme Series.min() et Series.max() sans d'abord convertir en un vrai dtype num\u00e9rique.\n\nNous devrions nous en tenir au type de cat\u00e9gorie principalement pour les colonnes d'objets o\u00f9 moins de 50% des valeurs sont uniques. Si toutes les valeurs d'une colonne sont uniques, le type de cat\u00e9gorie finira par utiliser plus de m\u00e9moire. \n\nNous allons \u00e9crire une boucle \u00e0 it\u00e9rer sur chaque colonne d'objet, v\u00e9rifier si le nombre de valeurs uniques est inf\u00e9rieur \u00e0 50%, et si oui, le convertir au type de cat\u00e9gorie.\n\"\"\"\nconvertion_obj = pd.DataFrame()\n\n# On parcours les diff\u00e9rentes colonnes\nfor col in courses_obj.columns:\n    # Nombre de valeurs uniques\n    num_unique_valeurs = len(courses_obj[col].unique())\n    # Nombre de valeurs\n    num_total_valeurs = len(courses_obj[col])\n    # Si moins de 50% de valeurs uniques alors on change le type de colonne\n    if num_unique_valeurs \/ num_total_valeurs < 0.5:\n        convertion_obj.loc[:,col] = courses_obj[col].astype('category')\n    else:\n        convertion_obj.loc[:,col] = courses_obj[col]\n        \nprint(usage_memoire(courses_obj))\nprint(usage_memoire(convertion_obj))\n\ncompare_obj = pd.concat([courses_obj.dtypes,convertion_obj.dtypes],axis=1)\ncompare_obj.columns = ['avant','apres']\ncompare_obj.apply(pd.Series.value_counts)\n\"\"\"\nDans ce cas, toutes nos colonnes d'objets ont \u00e9t\u00e9 converties en type de cat\u00e9gorie, mais ce ne sera pas le cas avec tous les ensembles de donn\u00e9es, vous devriez donc vous assurer d'utiliser le processus ci-dessus pour v\u00e9rifier.\n\nDe plus, notre utilisation de m\u00e9moire pour nos colonnes d'objets est pass\u00e9e de 7,93 Mo \u00e0 0,15 Mo, soit une r\u00e9duction de 95 %. Combinons ceci avec le reste de notre dataframe et voyons o\u00f9 nous nous situons par rapport \u00e0 l'utilisation de m\u00e9moire de 17,1 MB que nous avons commenc\u00e9 avec.\n\"\"\"\noptimise_gl[convertion_obj.columns] = convertion_obj\n\nusage_memoire(optimise_gl)\n\"\"\"\nWow, on a vraiment fait des progr\u00e8s ! Nous avons une autre optimisation que nous pouvons faire - si vous vous souvenez de notre tableau des types, il y avait un type datetime que nous pouvons utiliser pour la premi\u00e8re colonne de notre ensemble de donn\u00e9es.\n\nIl nous reste encore un colone de type date. Pouvons nous essayer de l'optimiser ?\n\n\"\"\"\ndate = optimise_gl[\"cr-Date\"]\nprint(usage_memoire(date))\ndate.head()\n\"\"\"\nOn remarque de suite que ma colonne cr-Date est d\u00e9j\u00e0 au format date. En effet, durant l'importation depuis csv, on avait sp\u00e9cifier que cette colonne \u00e9tait au format date. Cela nous permet d'optimiser dircetement cette colonne au chargement du dataframe.\n\n# &#128203;  Importation des donn\u00e9es en fixant le type\n\nJusqu'\u00e0 pr\u00e9sent, nous avons explor\u00e9 des moyens de r\u00e9duire l'empreinte m\u00e9moire d'un dataFrame existant. En important notre fichier et puis en changeant le types des colonnes, nous avons pu optimiser la taille de notre empreinte m\u00e9moire. \n\nMais imaginons que notre fichier soit trop gros pour \u00eatre charg\u00e9 ou que nus ayons une m\u00e9moire trop petite pour le charger. Comment pouvons-nous appliquer des techniques d'\u00e9conomie de m\u00e9moire alors que nous ne pouvons m\u00eame pas cr\u00e9er le dataframe ?\n\nHeureusement, nous pouvons sp\u00e9cifier les types de colonnes  lorsque nous lisons l'ensemble des donn\u00e9es. La fonction pandas.read_csv() a quelques param\u00e8tres  qui nous permettent de le faire. C'est ce que nous venons de voir avec l'importation de la date. \nLe param\u00e8tre dtype accepte un dictionnaire dont les cl\u00e9s sont des noms de colonnes (cha\u00eenes de caract\u00e8res) et les valeurs des objets de type NumPy.\n\nTout d'abord, nous allons stocker les types finaux de chaque colonne dans un dictionnaire avec des cl\u00e9s pour les noms de colonnes, en supprimant d'abord la colonne de la date puisque celle-ci doit \u00eatre trait\u00e9e s\u00e9par\u00e9ment.\n\n\"\"\"\n# On supprime la colonne cr-Date\ndtypes = optimise_gl.drop('cr-Date',axis=1).dtypes\n\n# Serie avec le nom de la colonne\ndtypes_col = dtypes.index\n# Serie avec le type de la colonne\ndtypes_type = [i.name for i in dtypes.values]\n\n#Cr\u00e9ation d'un dictionnaire \ncolumn_types = dict(zip(dtypes_col, dtypes_type))\n\n#Affichage des r\u00e9sultats\nfor keys,values in column_types.items():\n    print(keys+\" : \"+values)\n\n\n\"\"\"\nMaintenant nous pouvons utiliser le dictionnaire, avec quelques param\u00e8tres pour la date \u00e0 lire dans les donn\u00e9es avec les types corrects en quelques lignes :\n\"\"\"\ncourses_optimisees = pd.read_csv('..\/input\/export-1-pt-utf.csv',dtype=column_types,parse_dates=['cr-Date'],infer_datetime_format=True)\n\nprint(usage_memoire(courses_optimisees))\ncourses_optimisees.head()\n\"\"\"\nPour rappel, au d\u00e9but nous \u00e9tions \u00e0 17,1 Mo et maintenant 4,5 Mo. On a gagn\u00e9 au final 73% de m\u00e9moire. &#x1F4A3; \n\"\"\"\ndataTypeDf = pd.DataFrame(courses_optimisees.dtypes.value_counts()).reset_index().rename(columns={\"index\":\"variableType\",0:\"count\"})\nfig,ax = plt.subplots()\nfig.set_size_inches(20,5)\nsn.barplot(data=dataTypeDf,x=\"variableType\",y=\"count\",ax=ax,color=\"#34495e\")\nax.set(xlabel='Type de Variables', ylabel='Quantit\u00e9',title=\"Quantit\u00e9 variables par type\")\n\"\"\"\nSi vous avez appr\u00e9ci\u00e9 ce petit article, merci de voter pour lui. \n\nSi vous voulez me joindre directement sur linkedin.\n[https:\/\/fr.linkedin.com\/in\/developpeur-windev](https:\/\/fr.linkedin.com\/in\/developpeur-windev)\n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3f1f1724ae7329'}"}
{"id":"53228","text":"\"\"\"\n# Natural Language Process(NLP)\n**Target:** <br>\nDetermining the category of the video according to the video title.\n\"\"\"\nimport numpy as np\nimport pandas as pd\ndata = pd.read_csv(\"\/kaggle\/input\/youtubevideodataset\/Youtube Video Dataset.csv\")\ndata\n\"\"\"\n>** We need header and category columns. We can delete the remaining columns.**\n\"\"\"\ndata = data.drop([\"Videourl\",\"Description\"],axis=1)\ndata\n\"\"\"\n> Let's check if there is a null value inside.\n\"\"\"\ndata is None\ndata.info()\n\"\"\"\n> Categories\n\"\"\"\ndata.Category.value_counts()\n\"\"\"\n* Travel Blog => 0\n* Science & Technology => 1\n* Food => 2\n* Art&Music => 3\n* manufacturing => 4\n* History => 5\n\"\"\"\ndata[\"Category\"] = data[\"Category\"].map({\"travel blog\":0,\"Science&Technology\":1,\"Food\":2,\"Art&Music\":3,\"manufacturing\":4,\"History\":5})\ndata\n\"\"\"\n## Regular Expression\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport nltk \nimport re\nfrom nltk.corpus import stopwords\n\ntitle_list = []\nfor title in data.Title:\n    title = re.sub(\"[^a-zA-Z]\",\" \", title)\n    title = title.lower()\n    title = nltk.word_tokenize(title)\n    lemma = nltk.WordNetLemmatizer()\n    title = [ lemma.lemmatize(word) for word in title]\n    title = \" \".join(title)\n    title_list.append(title)\n\"\"\"\n## Bag Of Words\n\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\nmax_features = 1000\ncount_vectorizer = CountVectorizer(max_features=max_features,stop_words=\"english\")\nspace_matrix = count_vectorizer.fit_transform(title_list).toarray() # 0-1\ny = data[\"Category\"].values\ny\nx = space_matrix\nx\n\"\"\"\n## Train Test Split\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.1,random_state=42)\nprint(\"x_train\",x_train.shape)\nprint(\"x_test\",x_test.shape)\nprint(\"y_train\",y_train.shape)\nprint(\"y_test\",y_test.shape)\n\"\"\"\n## Naive Bayes\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\n\nnb = GaussianNB()\nnb.fit(x_train,y_train)\n\nprint(\"Accuracy => \", nb.score(x_test,y_test)*100)\nall_words = count_vectorizer.get_feature_names()\nprint(\"Most used words: \",all_words[50:100])\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nplt.subplots(figsize=(12,12))\nwordcloud=WordCloud(background_color=\"white\",width=1024,height=768).generate(\" \".join(all_words[100:]))\nplt.imshow(wordcloud)\nplt.axis(\"off\")\nplt.show()\n#Random Forest\nfrom sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators = 10, random_state=42)\nrf.fit(x_train,y_train)\nprint(\"accuracy: \",rf.score(x_test,y_test)*100)\n#confussion matrix\ny_pred=rf.predict(x_test)\ny_true=y_test\n\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nnames=[\"travel blog\",\"Science&Technology\",\"Food\",\"Art&Music\",\"manufacturing\",\"History\"]\ncm=confusion_matrix(y_true,y_pred)\nf,ax=plt.subplots(figsize=(5,5))\nsns.heatmap(cm,annot=True,linewidth=.5,linecolor=\"r\",fmt=\".0f\",ax=ax)\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nax.set_xticklabels(names,rotation=90)\nax.set_yticklabels(names,rotation=0)\nplt.show()","meta":"{'source': 'AI4Code', 'id': '61f30e78665ea6'}"}
{"id":"133514","text":"\"\"\"\n**DAY-2**                                                                                                                                       \nWelcome to *second* day. Lets Start!\nToday we will do **Linear Regression**\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\ndata=pd.read_csv(\"..\/input\/machinelearning\/studentscores.csv\")\ndata.head()\nX=data.iloc[:, : 1].values\nY=data.iloc[:, 1].values\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test= train_test_split(X, Y, test_size=0.25, random_state=0)\nregressor= LinearRegression()\nregressor= regressor.fit(X_train, Y_train)\n# predict result\n\ny_pred=regressor.predict(X_test)\n# visualization\n#training\nimport matplotlib.pyplot as plt\nplt.scatter(X_train, Y_train, color='red')\nplt.plot(X_train, regressor.predict(X_train), color='blue')\n#testing\nplt.scatter(X_test, Y_test, color='red')\nplt.plot(X_test, regressor.predict(X_test), color='blue')\n\"\"\"\nCongratulations! You Completed second day practice.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f58be9b9807992'}"}
{"id":"38171","text":"\"\"\"\n# Import Statements\n\"\"\"\nimport numpy as np, pandas as pd, matplotlib.pyplot as plt\nimport joblib\nimport optuna\nimport sklearn \n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix, classification_report\n\"\"\"\n# Load Data\n\"\"\"\n# load data\ntrain = pd.read_csv('..\/input\/forest-cover-type-prediction\/train.csv')\n# view data\ntrain.head()\n# remove ID column from set\ntrain = train.iloc[:, 1:]\ntrain.head()\n\"\"\"\n# EDA\n\"\"\"\n# check for missing values\ntrain.isnull().values.any()\n# summary\ntrain.describe()\n# dimensions of data set \nprint(train.shape) # 55 columns\n# column names\nprint(train.columns)\n\"\"\"\n# Preprocessing\n\"\"\"\n# create cat, num, and y\nX_cat = train.iloc[:, 10:54].values\nX_num = train.iloc[:, 0:10].values\ny = train.iloc[:, -1].values\n# scale\/standardizing numerical columns\n# scaler object\nscaler = StandardScaler()\n# fit to training data\nscaler.fit(X_num)\n# scale num columns\nX_num = scaler.transform(X_num)\n\n# shape\nprint(f'Categorical Shape: {X_cat.shape}')\nprint(f'Numerical Shape: {X_num.shape}')\nprint(f'Label Shape: {y.shape}')\n# combine num and cat\nX = np.hstack((X_num, X_cat))\nprint(X.shape)\n\"\"\"\n# PCA\n\"\"\"\n# PCA to find the number of components\npca = PCA().fit(X)\nplt.plot(np.cumsum(pca.explained_variance_ratio_))\nplt.xlabel('Number of Components')\nplt.ylabel('Cumulative Explained Variance')\nplt.title('PCA Number of Components for Cumulative Variance')\n# PCA\npca = PCA(n_components = 10)\npca.fit(X)\n# print components\nprint(pca.components_)\n\n# print variances\nprint(pca.explained_variance_)\n\"\"\"\n# Logistic Regression\n\"\"\"\n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n      solver = trial.suggest_categorical('solver', ['saga', 'lbfgs'])\n      lr_clf = LogisticRegression(random_state = 1, penalty = 'none', max_iter = 500, solver = solver)\n      return sklearn.model_selection.cross_val_score(lr_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \nlr_study = optuna.create_study(direction='maximize')\nlr_study.optimize(objective, n_trials=3)\nlr = lr_study.best_trial\nprint('Accuracy: {}'.format(lr.value))\nprint(\"Best hyperparameters: {}\".format(lr.params))\n\"\"\"\n# best model \n\nlr_model = LogisticRegression(random_state = 1, \n                              penalty = 'none', \n                              max_iter = 500, \n                              solver = 'saga')\nlr_model.fit(X, y)\n\"\"\"\n# Decision Tree\n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n    max_depth = trial.suggest_int('max_depth', 2, 50)\n    min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 32)\n    dt_clf = DecisionTreeClassifier(random_state = 1, max_depth = max_depth, min_samples_leaf = min_samples_leaf)\n    return sklearn.model_selection.cross_val_score(dt_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \ndt_study = optuna.create_study(direction='maximize')\ndt_study.optimize(objective, n_trials=100)\ndt = dt_study.best_trial\nprint('Accuracy: {}'.format(dt.value))\nprint(\"Best hyperparameters: {}\".format(dt.params))\n# dt best model\ndt_model = DecisionTreeClassifier(random_state = 1, \n                                  max_depth = dt_study.best_trial.params['max_depth'], \n                                  min_samples_leaf = dt_study.best_trial.params['min_samples_leaf'])\ndt_model.fit(X, y)\n\"\"\"\n# Random Forest\n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n    n_estimators = trial.suggest_int('n_estimators', 100, 150)\n    max_depth = trial.suggest_int('max_depth', 20, 50)\n    min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 20)\n    rf_clf = RandomForestClassifier(random_state = 1, n_estimators = n_estimators, max_depth = max_depth, min_samples_leaf = min_samples_leaf)\n    return sklearn.model_selection.cross_val_score(rf_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \nrf_study = optuna.create_study(direction='maximize')\nrf_study.optimize(objective, n_trials=20)\nrf = rf_study.best_trial\nprint('Accuracy: {}'.format(rf.value))\nprint(\"Best hyperparameters: {}\".format(rf.params))\n# best model\nrf_model = RandomForestClassifier(random_state = 1, \n                                  n_estimators = rf_study.best_trial.params['n_estimators'], \n                                  max_depth = rf_study.best_trial.params['max_depth'], \n                                  min_samples_leaf = rf_study.best_trial.params['min_samples_leaf'])\n\nrf_model.fit(X, y)\n\"\"\"\n# Extra Tree Classifier\n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n    max_depth = trial.suggest_int('max_depth', 30, 50)\n    min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 20)\n    tree_clf = ExtraTreesClassifier(random_state = 0, n_estimators = 200, max_depth = max_depth, min_samples_leaf = min_samples_leaf)\n    return sklearn.model_selection.cross_val_score(tree_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \ntree_study = optuna.create_study(direction='maximize')\ntree_study.optimize(objective, n_trials=20)\ntree = tree_study.best_trial\nprint('Accuracy: {}'.format(tree.value))\nprint(\"Best hyperparameters: {}\".format(tree.params))\n# best model\ntree_model = ExtraTreesClassifier(random_state = 1, \n                                  n_estimators = 200, \n                                  max_depth = tree_study.best_trial.params['max_depth'], \n                                  min_samples_leaf = tree_study.best_trial.params['min_samples_leaf'])\n\ntree_model.fit(X, y)\n\"\"\"\n# Gradient Boosting Classifier\n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n    max_depth = trial.suggest_int('max_depth', 10, 20)\n    min_samples_leaf = trial.suggest_int('min_samples_leaf', 15, 20)\n    gradb_clf = GradientBoostingClassifier(random_state = 0, max_depth = max_depth, min_samples_leaf = min_samples_leaf)\n    return sklearn.model_selection.cross_val_score(gradb_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \ngradb_study = optuna.create_study(direction='maximize')\ngradb_study.optimize(objective, n_trials = 5)\ngradb = gradb_study.best_trial\nprint('Accuracy: {}'.format(gradb.value))\nprint(\"Best hyperparameters: {}\".format(gradb.params))\n%%time\n# best model\ngradb_model = GradientBoostingClassifier(random_state = 0,\n                                         max_depth = gradb_study.best_trial.params['max_depth'], \n                                         min_samples_leaf = gradb_study.best_trial.params['min_samples_leaf'])\n\ngradb_model.fit(X, y)\n\"\"\"\n# Extreme Gradient Boosting\n\"\"\"\n%%time\n# xgb classifier\nxgb_clf = XGBClassifier(random_state = 0, max_depth = 10)\nxgb_model = xgb_clf.fit(X, y)\nxgb_model.score(X, y)\n\"\"\"\n# AdaBoost \n\"\"\"\n%%time\n\n# optuna hyperparameter tuning\ndef objective(trial):\n    n_estimators = trial.suggest_int('n_estimators', 1, 15)\n    adab_clf = AdaBoostClassifier(random_state = 0, n_estimators = n_estimators)\n    return sklearn.model_selection.cross_val_score(adab_clf, X, y, n_jobs = -1, cv = 10).mean()\n    \nadab_study = optuna.create_study(direction='maximize')\nadab_study.optimize(objective, n_trials = 10)\nadab = adab_study.best_trial\nprint('Accuracy: {}'.format(adab.value))\nprint(\"Best hyperparameters: {}\".format(adab.params))\n# best model\nadab_model = AdaBoostClassifier(random_state = 0, \n                                n_estimators = adab_study.best_trial.params['n_estimators'])\n\nadab_model.fit(X, y)\n\"\"\"\n# Model Selection\n\"\"\"\n%%time \n# create ensemble classifier \nensemble_model = VotingClassifier(\n    estimators = [('tree', tree_model), \n                  ('rf', rf_model), \n                  ('gradb', gradb_model), \n                  ('xgb', xgb_model)],\n    voting = 'hard'\n)\n\n# fit\nensemble_model.fit(X, y)\n\n# print training accuracy\nprint('Logistic Regression Accuracy', lr_model.score(X, y))\nprint('Decision Tree Accuracy', dt_model.score(X, y))\nprint('Random Forest Accuracy', rf_model.score(X, y))\nprint('Extra Trees Accuracy', tree_model.score(X, y))\nprint('Gradient Boosting Accuracy', gradb_model.score(X, y))\nprint('Extra Gradient Boosting Accuracy', xgb_model.score(X, y))\nprint('AdaBoost Accuracy', adab_model.score(X, y))\nprint('Ensemble Accuracy:', ensemble_model.score(X, y))\n\"\"\"\n# Save Preprocessor and Models\n\"\"\"\n# save scaler\njoblib.dump(scaler, 'forest_cover_scaler.joblib')\njoblib.dump(rf_model, 'rf_model_2.joblib')\njoblib.dump(tree_model, 'tree_model_2.joblib')\njoblib.dump(gradb_model, 'gradb_model_2.joblib')\njoblib.dump(xgb_model, 'xgb_model_2.joblib')\njoblib.dump(adab_model, 'adab_model_2.joblib')\njoblib.dump(ensemble_model, 'ensemble_model_2.joblib')\nprint('Model written to file.')","meta":"{'source': 'AI4Code', 'id': '4654b49356e010'}"}
{"id":"48713","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport warnings \nwarnings.filterwarnings('ignore')\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport matplotlib.cm as cm\nimport seaborn as sns\n\nimport collections\nfrom wordcloud import WordCloud, STOPWORDS\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\"\"\"\n# Data\n\"\"\"\nmigrants = pd.read_csv('..\/input\/MissingMigrants-Global-2019-03-29T18-36-07.csv')\nmigrants.drop(['Web ID', 'URL'], axis = 1, inplace=True)\nmigrants.head()\nmigrants[migrants['Region of Incident'] == 'Mediterranean'].groupby(['Cause of Death'])['Total Dead and Missing'].sum().sort_values(ascending=False)[:15]\nmigrants.describe(exclude='O')\nmigrants.describe(exclude='number')\nmigrants.info()\n# Convert string month into numerical one\nmigrants['Reported Month(Number)'] = pd.to_datetime(migrants['Reported Month'], format='%b').apply(lambda x: x.month)\n\nmigrants[migrants['Reported Year'] == 2014]['Reported Month(Number)'].min(), migrants[migrants['Reported Year'] == 2019]['Reported Month(Number)'].max()\n\"\"\"\n- Data from Jan.2014 to March.2015\n\"\"\"\nmigrants.loc[:, 'Minimum Estimated Number of Missing'].sum(), migrants.loc[:, 'Number of Survivors'].sum(), \nprint(migrants.loc[:, 'Number of Children'].sum())\nmigrants.loc[:, 'Number of Children'].plot.box()\nprint(migrants.loc[:, 'Number of Males'].sum())\nmigrants.loc[:, 'Number of Males'].plot.box()\nprint(migrants.loc[:, 'Number of Females'].sum())\nmigrants.loc[:, 'Number of Females'].plot.box()\nmigrants.loc[:, 'Number of Survivors'].plot.box()\n\"\"\"\n### Number of missing values\n\"\"\"\nna_sum = []\nfor col in migrants.columns:\n    na_sum.append(migrants[col].isna().sum())\n\nmigrants_df = pd.DataFrame({'cols':migrants.columns,\n                            'total_na' : na_sum})\n\nmigrants_df = migrants_df.sort_values(by='total_na', ascending=False).drop(list(migrants_df[migrants_df.total_na == 0].index), axis=0)\nmigrants_df.plot.bar(x = 'cols', y = 'total_na', rot=85, fontsize=18)\ndel migrants_df\n\"\"\"\n# HeatmapWithTimestamp by using folium\n- See below animation with leftmost below date\n\"\"\"\nimport folium\nfrom folium.plugins import HeatMapWithTime\n\n\nmigrants['Location Coordinates'].fillna('0, 0', inplace = True) # initialize missing value into 0, 0  location\nmigrants['lat'] = migrants['Location Coordinates'].apply(lambda x: float(str(x).split(', ')[0]))\nmigrants['lon'] = migrants['Location Coordinates'].apply(lambda x: float(str(x).split(', ')[1]))\n\nbasemap = folium.folium.Map(location = [migrants['lat'].median(), migrants['lon'].median()], zoom_start = 2)\n\nindexes = ['{}\/{}'.format(month, year) for year in migrants['Reported Year'].unique()[::-1] for month in range(1, 13)]\n\nheat_data = [[[row['lat'], row['lon'], row['Total Dead and Missing']] for _, row in migrants[migrants['Reported Year'] == year][migrants['Reported Month(Number)'] == month].iterrows()]\n             for year in migrants['Reported Year'].unique()[::-1] for month in range(1, 13)]\n\nHeatMapWithTime(heat_data, auto_play = True, index = indexes, display_index = indexes).add_to(basemap)\nbasemap.save('Animated heatmap of migrants death or missing from 2014 to 2019 by month')\nbasemap\n\n\"\"\"\n- Most of incidents occur in Mexico-US border, Mediterranean, North Africa and Horn of Africa\n\"\"\"\n\"\"\"\n### Number of incidents by region, migration route and UNSD grouping\n\"\"\"\nmigrants['Region of Incident'].value_counts().plot.bar(rot=80, fontsize=18)\nmigrants['Migration Route'].value_counts().plot.bar(rot=80, fontsize=18)\nmigrants['UNSD Geographical Grouping'].value_counts().plot.bar(rot=80, fontsize=18)\n\"\"\"\n# Finding reason of death using wordcloud\n\"\"\"\nall_cause_death          = ' '.join(migrants['Cause of Death'].str.lower())\nall_location_description = ' '.join(migrants['Location Description'].str.lower().fillna(' '))\nall_information_source   = ' '.join(migrants['Information Source'].str.lower().fillna(' '))\ndef words_frequency(corpus):\n    stopwords = STOPWORDS\n    \n    wordcloud = WordCloud(stopwords=stopwords, background_color=\"white\", max_words=150).generate(corpus) \n    rcParams['figure.figsize'] = 10, 20\n    plt.imshow(wordcloud)\n    plt.axis(\"off\")\n    plt.show()\n    \n    # Split corpus into each words\n    filtered_words = [word for word in corpus.split() if word not in stopwords]\n    \n    # Make counter object that have each count of word\n    counted_words = collections.Counter(filtered_words)\n    \n    # Store most common words\n    words = []\n    counts = []\n    for letter, count in counted_words.most_common(10):\n        words.append(letter)\n        counts.append(count)\n\n    rcParams['figure.figsize'] = 20, 10        # set figure size\n\n    plt.title('Top words in the corpus vs their count')\n    plt.xlabel('Count')\n    plt.ylabel('Words')\n    plt.barh(words, counts, color=cm.rainbow(np.linspace(0, 1, 10)))\nwords_frequency(all_cause_death)\nwords_frequency(all_location_description)\nwords_frequency(all_information_source)\nmigrants.loc[:, ['Total Dead and Missing', 'Number Dead', 'Number of Survivors']].plot.kde()\nmigrants.loc[:, ['Number of Males', 'Number of Females', 'Number of Children']].plot.kde()\nmigrants.loc[:, ['Total Dead and Missing']].plot.kde()\nmigrants['Region of Incident'].value_counts()[:10], migrants['Migration Route'].value_counts()[:10], migrants['UNSD Geographical Grouping'].value_counts()[:10]\ndef col_frequency_with_df(df, col):\n    corpus = ' '.join(df[col].str.lower())\n    return words_frequency(corpus)\ncol_frequency_with_df(migrants.loc[migrants['UNSD Geographical Grouping'] == 'Northern Africa',  :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['UNSD Geographical Grouping'] == 'Northern America', :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['UNSD Geographical Grouping'] == 'Uncategorized',  :], 'Cause of Death')\n\"\"\"\n- Dead migrants at North Africa mostly died cause lack of medicine, vehicle accidents\n- Dead migrants at North America mostly found as skeleton and reason of death are mostly unknown\n- Dead migrants at uncategorized Mostly drowned, I think uncategorized just indicate Mediterranean\n\"\"\"\ncol_frequency_with_df(migrants.loc[migrants['Region of Incident'] == 'US-Mexico Border',    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Region of Incident'] == 'North Africa',    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Region of Incident'] == 'Mediterranean',    :], 'Cause of Death')\n\"\"\"\n- Result is similar to previous 'UNSD Geographical Grouping' part\n\"\"\"\ncol_frequency_with_df(migrants.loc[migrants['Migration Route'] == 'Central America to US',    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Migration Route'] == 'Central Mediterranean',    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Migration Route'] == 'Western Mediterranean',    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Migration Route'] == 'Eastern Mediterranean',    :], 'Cause of Death')\n\"\"\"\n- Similar to previous parts\n\"\"\"\nmigrants['Reported Year'].value_counts().sort_index().plot.bar()\n\"\"\"\n- Incidents are increasing from 2014 to 2018\n\"\"\"\nmigrants['Migration Route'].value_counts()\ncol_frequency_with_df(migrants.loc[migrants['Reported Year'] == 2014,    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Reported Year'] == 2015,    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Reported Year'] == 2016,    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Reported Year'] == 2017,    :], 'Cause of Death')\ncol_frequency_with_df(migrants.loc[migrants['Reported Year'] == 2018,    :], 'Cause of Death')\n\"\"\"\n- What about reason of death on specific year on specific region or migration route?\n\"\"\"\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2014][migrants['Region of Incident'] == 'US-Mexico Border'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2015][migrants['Region of Incident'] == 'US-Mexico Border'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2016][migrants['Region of Incident'] == 'US-Mexico Border'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2017][migrants['Region of Incident'] == 'US-Mexico Border'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2018][migrants['Region of Incident'] == 'US-Mexico Border'], 'Cause of Death')\ndef unique_year(df, location_col, location_value, value_counts_col):\n    for year in list(df['Reported Year'].unique())[::-1]:\n        print(year)\n        counts = df[df['Reported Year'] == year][df[location_col] == location_value][value_counts_col].value_counts()\n        print(counts[:5])\n        print('Total : {}'.format(counts.sum()))\n        print('-' * 30)\n        \ndef n_deadmissing_by_year(df, sum_col, location_col, location_value):\n    \"\"\"Return sum of values of some column using grouped values\"\"\"\n    \n    for year in list(df['Reported Year'].unique())[::-1]:\n        print(year)\n        Sum = df[df['Reported Year'] == year][df[location_col] == location_value].groupby(['Cause of Death'])[sum_col].sum().sort_values(ascending=False) \n        print(Sum[:15])\n        print('Total : {}'.format(Sum.sum()))\n        print('-' * 30)\nunique_year(migrants, 'Region of Incident', 'US-Mexico Border', 'Cause of Death')\n\"\"\"\n- Reason of migrants death from 2014 to 2018 in US-mexico border is mostly unknown, drowning and hyperthemia.\n- Also let's see about number of dead or missing migrants grouped by their reason of death not only about number of incidents.\n\"\"\"\n# Number of deaths by reason of death from 2014 to 2019\nprint(migrants[migrants['Region of Incident'] == 'US-Mexico Border'].groupby(['Cause of Death'])['Total Dead and Missing'].sum().sort_values(ascending=False)[:15])\nprint('@' * 30)\n\nn_deadmissing_by_year(migrants, 'Total Dead and Missing', 'Region of Incident', 'US-Mexico Border')\n\"\"\"\n- Most of case migrants died for reason such as mixed,unknown(skeleton remains) and drowning etc.\n\"\"\"\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2014][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2015][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2016][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2017][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2018][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2019][migrants['Region of Incident'] == 'North Africa'], 'Cause of Death')\nunique_year(migrants, 'Region of Incident', 'North Africa', 'Cause of Death')\n\"\"\"\n- In North Africa case, most of incidnets imply the reason of death is lack of food\/water\/medicine and vehicle accident.\n\"\"\"\n# Number of deaths by reason of death from 2014 to 2019 \nprint(migrants[migrants['Region of Incident'] == 'North Africa'].groupby(['Cause of Death'])['Total Dead and Missing'].sum().sort_values(ascending=False)[:15])\nprint('@' * 30)\n\n# Number of deaths by reason of death by year from 2014 to 2019\nn_deadmissing_by_year(migrants, 'Total Dead and Missing', 'Region of Incident', 'North Africa')\n\"\"\"\nMost of migrants in North Africa died for reason such as lack of food\/water\/medicine\/shelter, vehicle accident and violence\/abuse\/murder\n\"\"\"\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2014][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2015][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2016][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2017][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2018][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\ncol_frequency_with_df(migrants[migrants['Reported Year'] == 2019][migrants['Region of Incident'] == 'Mediterranean'], 'Cause of Death')\nunique_year(migrants, 'Region of Incident', 'Mediterranean', 'Cause of Death')\n# Number of deaths by reason of death from 2014 to 2019 \nprint(migrants[migrants['Region of Incident'] == 'Mediterranean'].groupby(['Cause of Death'])['Total Dead and Missing'].sum().sort_values(ascending=False)[:15])\nprint('@' * 30)\n\n# Number of deaths by reason of death by year from 2014 to 2019\nn_deadmissing_by_year(migrants, 'Total Dead and Missing', 'Region of Incident', 'Mediterranean')\n\"\"\"\n- Migrants in Mediterranean died for reason such as drowning mostly\n\"\"\"\n\"\"\"\n# Number of incidents on different location \n\"\"\"\nimport matplotlib as mpl\n\nfont = {'family' : 'monospace',\n        'weight' : 'bold',\n        'size'   : 18}\n\nlines = {'linewidth' : 2}\n\nmpl.rc('font', **font)\nmpl.rc('lines', **lines)\n\nf, axes = plt.subplots(6, 1, figsize=(7, 5), sharex=True)\n\nfor year, ax in zip(migrants['Reported Year'].unique(), axes):\n    sns.barplot(x=list(pd.DataFrame(migrants[migrants['Reported Year'] == year]['Migration Route'].value_counts())[:5].index),  y='Migration Route',\n                palette=\"rocket\", ax=ax, data = pd.DataFrame(migrants[migrants['Reported Year'] == year]['Migration Route'].value_counts())[:5])\n    ax.axhline(0, color=\"k\", clip_on=False)\n    ax.set_ylabel(year)\n\nplt.xticks(rotation=45)\nplt.rcParams.update({'font.size': 22})\nplt.show()\n\ndel font, lines, f, axes\ndef years_value_counts(df, col):    \n    \n    # Store whole value_counts series with their particular year into list\n    stats_of_years = [pd.DataFrame(df[df['Reported Year'] == year][col].value_counts()) for year in df['Reported Year'].unique()]\n    \n    # concat dfs with their corresponding column\n    stats_of_years         =  pd.concat(stats_of_years, axis=1)\n    stats_of_years.columns = df['Reported Year'].unique()\n    stats_of_years.fillna(0, inplace=True)\n    return stats_of_years\nroute_year   = years_value_counts(migrants, 'Migration Route')\nUNSD_year    = years_value_counts(migrants, 'UNSD Geographical Grouping')\nregion_year  = years_value_counts(migrants, 'Region of Incident')\nimport plotly.graph_objs as go\nimport plotly            as py\nfrom plotly.offline      import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)\n\nfig = go.Figure(data=[go.Bar(name = str(col), x = route_year.transpose().index, y = route_year.transpose()[col]) \n                      for col in route_year.transpose().columns],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of incidents on specific migration route by year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\n\"\"\"\n- Basically number of incidents increased since 2014 until 2016 with relatively large gap and decreased from 16 to 18 slightly. \n- Most of incidents occured at Central America to US. \n- Central Mediterranean increase until 2017. In 2018, decrease until 1\/3 amount of number of incidents on 2017.\n- Also incidents of Eastern Mediterranean decrease 2015-2017 while incidents of Western Mediterranean increase 2015-2018.\n- So most of incidents(not equivalent to number of dead or missing migrants) have occurred at borderline of US-Mexico and mediterranean.\n\"\"\"\nfig = go.Figure(data=[go.Bar(name = str(col), x = region_year.transpose().index, y = region_year.transpose()[col]) \n                      for col in region_year.transpose().columns],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of incidents on specific region by year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\n\"\"\"\n- US-Mexico border is increasing since 2014\n- Number of incidents of North Africa and Horn of Africa  fluctuate from 2015 to 2018 while number of incidents on Mediterranean keep maintained around 200\n\"\"\"\nfig = go.Figure(data=[go.Bar(name = str(col), x = UNSD_year.transpose().index, y = UNSD_year.transpose()[col]) \n                      for col in UNSD_year.transpose().columns],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of incidents on UNSD geo grouping location by year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\nfig = go.Figure(data=[go.Bar(name = str(year), \n                             x = migrants[migrants['Reported Year'] == year]['Reported Month(Number)'].value_counts().sort_index().index, \n                             y = migrants[migrants['Reported Year'] == year]['Reported Month(Number)'].value_counts().sort_index()) \n                      for year in migrants['Reported Year'].unique()[::-1]],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of migrant incidents by month on specific year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\ndel route_year, UNSD_year, region_year\n\"\"\"\n- Let's see number of death or missing migrants by month on each region\n\"\"\"\npd.to_datetime(migrants['Reported Month'], format='%b').apply(lambda x: x.month).value_counts().sort_index().plot.bar()\n\"\"\"\n- We can see some functuation.Number of missing or daed migrants decrease Jan-April and increase April-October, then decrease again October-April roughly.\n\"\"\"\n\"\"\"\n# Number of missing or death by year\n\"\"\"\nmonths = [m for m in range(1,13)]\nyears  = migrants['Reported Year'].unique()[::-1]\n\nfig = go.Figure(data=[go.Bar(\n    name = str(year), x = months,\n    \n    y = [migrants[migrants['Reported Year'] == year][migrants['Reported Month(Number)'] == month]['Total Dead and Missing'].sum() \n         for month in months]) \n                      for year in years],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of missing or dead migrants by month on specific year', font = dict(size=18))),\n                    barmode = 'group'))\n\niplot(fig)\nfig = go.Figure(data=[go.Bar(\n    name = str(year), x = [m for m in range(1,13)],\n    \n    # List of number of migrants missing or death of months by specific year\n    y = [\n        migrants[migrants['Reported Year'] == year][migrants['Reported Month(Number)'] == month]['Total Dead and Missing'].sum() \n        for month in [m for m in range(1,13)]\n    ] \n) for year in migrants['Reported Year'].unique()[::-1]],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of missing or dead migrants by month on specific year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\n\"\"\"\n### 2014\n- Mostly die from July to September and December\n\n### 2015\n- There is huge amount of migrants died or disappeared on April\n\n### 2016\n- Number of dead or missing migrants are not constant\n\n### 2017\n- There is big number of died or disappeared migrants on May and June \n\n### 2018\n- There is big number of died or disappeared migrants on June\n\"\"\"\ndef groupbar_by_month(df, region_name, barmode = 'stack'):\n    months = [m for m in range(1,13)]\n    years  = df['Reported Year'].unique()[::-1]\n\n    fig = go.Figure(data=[go.Bar(\n        name = str(year), x = months,\n\n        y = [df[df['Region of Incident'] == region_name][df['Reported Year'] == year][df['Reported Month(Number)'] == month]['Total Dead and Missing'].sum() \n             for month in months]) \n                          for year in years],\n            \n                    layout = dict(\n                        xaxis = dict(\n                            title = dict(text = 'Number of missing or dead migrants by month on specific year in {}'.format(region_name), font = dict(size=18))),\n                        barmode = barmode))\n    \n    return iplot(fig)\ngroupbar_by_month(migrants, 'US-Mexico Border', barmode = 'stack')\ngroupbar_by_month(migrants, 'US-Mexico Border', barmode = 'group')\n\"\"\"\n## Number of missing or death on US-Mexico border by year\n- Mostly there is specific month migrants die or disappear by year\n\n### 2014\n- Diying or missing of migrants increase July to September.\n\n### 2015\n- Diying or missing of migrants occurred mostly on December\n\n### 2016\n- Diying or missing of migrants mostly occurred except January - May and November.\n\n### 2017\n- There is flunctuation on months except December. And big Diying or missing of migrants occurred on December.\n\n### 2018\n- Number of died or disappeared migrants are constant except June and August.\n\n\"\"\"\ngroupbar_by_month(migrants, 'North Africa', barmode = 'stack')\ngroupbar_by_month(migrants, 'North Africa', barmode = 'group')\n\"\"\"\n## Number of missing or death on North Africa by year\n\n### 2014\n- There is just small amount of dying or missing of migrants just from April to June, July(1),  August(3) and December(1). Mostly on April to June.\n\n### 2015\n- Most of diying or missing of migrants occurred from October to December.\n\n### 2016\n- There is big diying or missing of migrants occurred on February.\n\n### 2017\n- Diying or missing of migrants increase from April to November and decrease until April\n\n### 2018\n- There is just few of diying or missing of migrants from Septembe to December. And curve is more decreasing form\n\"\"\"\ngroupbar_by_month(migrants, 'Mediterranean', barmode = 'stack')\ngroupbar_by_month(migrants, 'Mediterranean', barmode = 'group')\n\"\"\"\n## Number of missing or death on Mediterranean by year\n\n### 2014\n- Most of dying or missing occurred from May to September.\n\n### 2015\n- There is big dying or missing at April, secondly June, thirdly October, fourthly December\n\n### 2016\n- There is mountain from March to July and peak at May. They're increase from September to November.\n\n### 2017\n- Most of diying or missing of migrants occurred on first half. And they have increasing form\n\n### 2018\n- There is big diying or missing of migrants on June and decreasing form from September to December.\n\"\"\"\n\"\"\"\n## Missing or death of male, female and children by year\n\"\"\"\nfig = go.Figure(data=[go.Bar(\n    name = col, x = migrants['Reported Year'].unique()[::-1],\n    \n    y = [\n        migrants[migrants['Reported Year'] == year][col].sum() \n        for year in migrants['Reported Year'].unique()[::-1]\n    ]\n) for col in ['Number of Females', 'Number of Males', 'Number of Children']],\n                \n                layout = dict(\n                    xaxis = dict(\n                        title = dict(text = 'Number of missing or dead male, female and children migrants by year', font = dict(size=18))),\n                    barmode = 'stack'))\n\niplot(fig)\ndel fig\ndef mfc_death_by_year(df, region, barmode = 'stack'):\n    fig = go.Figure(data=[go.Bar(\n        name = col, x = df['Reported Year'].unique()[::-1],\n\n        y = [\n            df[df['Region of Incident'] == region][df['Reported Year'] == year][col].sum() \n            for year in df['Reported Year'].unique()[::-1]\n        ] \n    ) for col in ['Number of Females', 'Number of Males', 'Number of Children']],\n\n                    layout = dict(\n                        xaxis = dict(\n                            title = dict(text = 'Number of missing or dead male, female and children migrants by year in {}'.format(region), font = dict(size=18))),\n                        barmode = barmode))\n\n    return iplot(fig)\nfor region in migrants['Region of Incident'].value_counts().index:\n    mfc_death_by_year(migrants, region)\nfor region in migrants['Region of Incident'].value_counts().index:\n    mfc_death_by_year(migrants, region, barmode = 'group')\n\"\"\"\n By just seeing charts we can easily know dead migrants are mostly male, however we don't know about total migrants population and sex\/children composition of population. So we don't know actually male can easily die during migration with same(or even similar) population or there is so much male migrants with same fatalities. \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '59ade8a72e82fa'}"}
{"id":"85279","text":"\"\"\"\n**Kindly upvote !! This will make my day.....**\n\"\"\"\n#The following is an example for creating an SVM classifier by using kernels. We will be using iris dataset from scikit-learn \u2212\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn import svm,datasets\nimport matplotlib.pyplot as plt\n\n#load the input data\niris = datasets.load_iris()\n#From the dataset we are taking first two features\n\nX = iris.data[:, :2]\ny = iris.target\n\n#Next we will plot SVM boundries with original data\nx_min , x_max =  X[:,0].min() - 1, X[:,0].max()+1\ny_min , y_max = X[:,1].min() -1, X[:,1].max()+1\n\nh = (x_max\/x_min)\/100\n\nxx , yy = np.meshgrid(np.arange(x_min,x_max,h),np.arange(y_min,y_max,h))\n\nX_plot = np.c_[xx.ravel(),yy.ravel()]\n#Now, we need to provide the value of regularization parameter\nc = 1.0\n\n#Next, SVM classifier object can be created as follows \u2212\n\nsvc_classifier = svm.SVC(kernel='linear', C=c).fit(X, y)\n\nZ = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize=(15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap=plt.cm.tab10, alpha=0.3)\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('Support Vector Classifier with linear kernel')\nimport random\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef generate_random_dataset(size):\n    \"\"\" Generate a random dataset and that follows a quadratic  distribution\n    \"\"\"\n    x = []\n    y = []\n    target = []   \n    for i in range(size):\n        # class zero\n        x.append(np.round(random.uniform(0, 2.5), 1))\n        y.append(np.round(random.uniform(0, 20), 1))\n        target.append(0)        \n        # class one\n        x.append(np.round(random.uniform(1, 5), 2))\n        y.append(np.round(random.uniform(20, 25), 2))\n        target.append(1)        \n        x.append(np.round(random.uniform(3, 5), 2))\n        y.append(np.round(random.uniform(5, 25), 2))\n        target.append(1)    \n    df_x = pd.DataFrame(data=x)\n    df_y = pd.DataFrame(data=y)\n    df_target = pd.DataFrame(data=target)    \n    data_frame = pd.concat([df_x, df_y], ignore_index=True, axis=1)\n    data_frame = pd.concat([data_frame, df_target], ignore_index=True, axis=1)    \n    data_frame.columns = ['x', 'y', 'target']\n    return data_frame\n\n\n# Generate dataset\nsize = 100\ndataset = generate_random_dataset(size)\nfeatures = dataset[['x', 'y']]\nlabel = dataset['target']\n\n# Hold out 20% of the dataset for training\ntest_size = int(np.round(size * 0.2, 0))\n\n# Split dataset into training and testing sets\nx_train = features[:-test_size].values\ny_train = label[:-test_size].values\n\nx_test = features[-test_size:].values\ny_test = label[-test_size:].values\n\n# Plotting the training set\nfig, ax = plt.subplots(figsize=(12, 7))\n\n# removing to and right border\nax.spines['top'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\n\n# adding major gridlines\nax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)\nax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], color=\"#8C7298\")\nplt.show()\n\"\"\"There is a little space between two groups of data points.\nBut closer to the center,it's not clear which data point belong to which class.\n\nA quadratic curve might be a good candidate to separate these classes.\n\"\"\"\n\n\nfrom sklearn import svm\nmodel = svm.SVC(kernel = 'poly',degree=2)\nmodel.fit(x_train,y_train)\n\"\"\" To see the result of fitting this model, we can plot the decision boundary and the margin along with the dataset.\"\"\"\n\nfig,ax = plt.subplots(figsize= (12,7))\n\n#Removing to and right borders\nax.spines['top'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\n\n#Create grid to eval model\nxx = np.linspace(-1,max(features['x'])+1,len(x_train))\nyy = np.linspace(0, max(features['y']) + 1, len(y_train))\nYY,XX = np.meshgrid(yy,xx)\nxy = np.vstack([XX.ravel(), YY.ravel()]).T\n\ntrain_size = len(features[:-test_size]['x'])\n\n# Assigning different colors to the classes\ncolors = y_train\ncolors = np.where(colors == 1, '#8C7298', '#4786D1')\n\n# Plot the dataset\nax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], c=colors)\n\n# Get the separating hyperplane\nZ = model.decision_function(xy).reshape(XX.shape)\n# Draw the decision boundary and margins\nax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])\n\n# Highlight support vectors with a circle around them\nax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')\n\nplt.show()\n\"\"\" If we calculate the accuracy of this model against the testing set we get a good result, \ngranted the dataset is very small and generated at random \"\"\"\n\nfrom sklearn.metrics import accuracy_score\npredictions_poly = model.predict(x_test)\naccuracy_poly = accuracy_score(y_test, predictions_poly)\nprint(\"2nd degree polynomial Kernel\\nAccuracy (normalized): \" + str(accuracy_poly))\n\n\"\"\"The accuracy is good, but let's see if a more simplistic approach could have solved our problem.\n To fit an SVM with a linear kernel we just need to update the kernel parameter.\n \"\"\"\n\nmodel = svm.SVC(kernel='linear')\nmodel.fit(x_train,y_train)\nfig,ax = plt.subplots(figsize= (12,7))\n\n#Removing to and right borders\nax.spines['top'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.spines['right'].set_visible(False)\n\n#Create grid to eval model\nxx = np.linspace(-1,max(features['x'])+1,len(x_train))\nyy = np.linspace(0, max(features['y']) + 1, len(y_train))\nYY,XX = np.meshgrid(yy,xx)\nxy = np.vstack([XX.ravel(), YY.ravel()]).T\n\ntrain_size = len(features[:-test_size]['x'])\n\n# Assigning different colors to the classes\ncolors = y_train\ncolors = np.where(colors == 1, '#8C7298', '#4786D1')\n\n# Plot the dataset\nax.scatter(features[:-test_size]['x'], features[:-test_size]['y'], c=colors)\n\n# Get the separating hyperplane\nZ = model.decision_function(xy).reshape(XX.shape)\n# Draw the decision boundary and margins\nax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])\n\n# Highlight support vectors with a circle around them\nax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')\n\nplt.show()\nprint(\"2nd degree polynomial Kernel\\nAccuracy (normalized): \" + str(accuracy_poly))\n","meta":"{'source': 'AI4Code', 'id': '9c8023862878c1'}"}
{"id":"38031","text":"# 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\n#The Basics\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport plotly.express as px\nimport missingno as msno\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\nshootings = pd.read_csv(\"\/kaggle\/input\/us-police-shootings\/shootings.csv\")\n# Just checking\nshootings.head()\n\"\"\"\nThere are a lot of insights that can be gained from the data. By the end of this EDA a few details surrounding police shootings in the US will be understood: where most shootings occured, mental illnesses involved, racial issues, whether the police officers were wearing body cameras etc.\n\"\"\"\n\"\"\"\n**Which states are shooting hotspots?**\n\nThere are no missing values for any of the columns (variables). We can now go ahead with the data analysis. The first task is to determine which states have had the most police shootings. We shall use geocoding to convert the names of states within the dataset into latitude and longitude coordinates. This will prove useful when it comes to geographic visualization\n\"\"\"\n# First we do a little Pandas trick to get the total shootings per state\nstate_shootings=shootings.state.value_counts().reset_index()\nstate_shootings.columns=['State','Total Shootings']\nstate_shootings.head()\nimport plotly.graph_objects as go\nfig = go.Figure(data=go.Choropleth(\n    locations=state_shootings['State'],\n    z = state_shootings['Total Shootings'].astype(float),\n    locationmode = 'USA-states',\n    colorscale = 'Reds',\n    colorbar_title = \"Shootings\",\n))\n\nfig.update_layout(\n    title_text = 'Shootings per State',\n    geo_scope='usa',\n)\n\nfig.show()\n\"\"\"\n**Are Some of the Shootings Justified?**\nIt quickly becomes apparent that the map showing which states have the most police shootings can become glamorized or misinterpreted.There is a need to answer some questions pertaining to these shootings. For example, are all police shootings in California and Texas (the top 2 states) justified? Let's find out which percentage of all the shootings were the victims unarmed. We shall use the top 5 states in this case.\n\"\"\"\narmed_not=shootings.armed.value_counts().reset_index()\narmed_not.columns=['Armed','Total']\narmed_not.head(10)\n\"\"\"\nNaturally most police officers shoot when they have been threatened. In 2755 shootings the victims had guns with them,and in 708 shootings they had knives. However, in 418 instances the assailant had an 'unknown' weapon, in 348 instances they were unarmed and shockingly in 171 instances the assailant carried a toy weapon. These 3 categories (unknown, unarmed, and toy weapon) have provided the greatest amount of controversy to police shootings. For this reason they warrant their own investigation.\n\"\"\"\n# Create a dataset with only unarmed, unknown and toy weapon 'armed' categories\ncontroversial_shootings = shootings[shootings['armed'].isin(['unknown','unarmed','toy weapon'])]\ncontroversial_shootings.head()\n\"\"\"\n**Which Races Face The Most Controversial Shootings?**\n\n\"\"\"\nrace_controversial=controversial_shootings.race.value_counts().reset_index()\nrace_controversial.columns=['Race','Total']\nrace_controversial.head(5)\n# Shootings per race, for the whole dataset\nrace=shootings.race.value_counts().reset_index()\nrace.columns=['Race','Total']\nrace.head(5)\n\"\"\"\nThe breakdown of the results looks quite similar. Let's find out using pie charts\n\"\"\"\n\"\"\"\n**Pie Charts Showing Total Shootings per Race vs Controversial Shootings per Race**\n\"\"\"\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]], subplot_titles = (\"Controversial Shootings\", \"Total Shootings\"))\n\nfig.add_trace(go.Pie(labels=race_controversial['Race'], values=race_controversial['Total'], name=\"Controversial Shootings\"),\n              1, 1)\nfig.add_trace(go.Pie(labels=race['Race'], values=race['Total'], name=\"Shootings\"),\n              1, 2)\n\nfig.update_traces(hole=.4, hoverinfo=\"label+percent\")\n\nfig.update_layout(\n    title_text=\"US Police Shotings\")\nfig.show()\n\"\"\"\nIt seems that the controversial shootings (those involving unarmed assailants) have a similar proportion to the total shootings in terms of race. Thus, while the shooting of black unarmed men has received more attention on the news, it seems the US police generally needs to stop shooting individuals who are technically not a threat to them (regardless of race).\n\"\"\"\n\"\"\"\n**Body Cameras and Shootings**\n\nAfter the murder of George Floyd by the police in Minneapolis, the use of body camera footage in determining whether officers had a right to shoot, or even to murder citizens, has increased. However, there is also an increased tendency for police officers to turn off their body cameras before events go downhill. \nUsing various visualizations a link will be determined between shooting of unarmed men and the turning off of body cameras.\n\"\"\"\n# How many times body cameras were off or false\ncameras=shootings.body_camera.value_counts().reset_index()\ncameras.columns=['Body Cameras','Total']\ncameras.head(5)\n\"\"\"\nThis presents a huge challenge. This is mostly because body camera legislation is still new for many states and for this reason simply taking the False value as 'Off' could lead to wrong conclusions. It is thus quite fitting to do the same (determining how often body cameras were off) for the controvesial shootings data subset.\n\"\"\"\n# How many times body cameras were off or false\nc_cameras=controversial_shootings.body_camera.value_counts().reset_index()\nc_cameras.columns=['Body Cameras','Total']\nc_cameras.head(5)\n\"\"\"\nIt seems that any further investigation on body cameras will fall short if further information on the state laws during the time of a specific shooting are not presented.\n\"\"\"\n\"\"\"\n**Were the unarmed assailants fleeing?**\nOne reason given by many police departments is that assailants or in this case suspects were fleeing and for this reason they had to be stopped. I shall include those who had toy weapons and those who had unknown weapons i.e. use the controversial shootings data subset.\n\"\"\"\n# Were the victims fleeing arrest?\nfleeing=controversial_shootings.flee.value_counts().reset_index()\nfleeing.columns=['Fleeing?','Total']\nfleeing.head(5)\n# Bar chart of whether victims were fleeing\nfig = px.bar(fleeing, x='Fleeing?', y='Total')\nfig.show()\n\"\"\"\n**Most of the victims in the controversial shootings were not fleeing. 125 of them were on foot and 74 of them  are categorized as 'other.' It seems that many of the police departments that were invovled in these controversial shootings could really use better education on how to handle volatile situations.**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '460efb6be15818'}"}
{"id":"45430","text":"\"\"\"\n## Importing core libraries and custom estimators\n\"\"\"\n# Importing core libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import recall_score, precision_score, confusion_matrix\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.cluster import KMeans\nfrom sklearn.covariance import EllipticEnvelope\n\"\"\"\nIn the following code block, I write the implementation of anomaly detectors from Andrew Ng's Machine Learning lectures (Section 15)\n\"\"\"\n# Custom anomaly detectors\nfrom sklearn.base import BaseEstimator\nimport numpy as np\nfrom math import gamma, pi\nfrom scipy.stats import multivariate_normal\n\nclass MultivariateGaussian(BaseEstimator):\n    \"\"\"\n    Anomaly detector using the Multivariate Gaussian class\n    Based on Andrew Ng's lecture\n    \"\"\"\n    def __init__(self, epsilon=None):\n        self.epsilon = epsilon\n    \n    def fit(self, train_data):\n        X = np.array(train_data)\n        # Calculating n-dimensional mean vector (mu)\n        self.mu = np.mean(X, axis=0)\n        # Calculating n-by-n covariance matrix (Sigma)\n        self.Sigma = np.cov(X, rowvar=False)\n        assert self.Sigma.shape == (X.shape[1], X.shape[1]), f\"The covariance matrix must be {X.shape[1]} by {X.shape[1]}\"\n        return self\n\n    def predict(self, test_data):\n        X_test = np.array(test_data)\n        p_X = multivariate_normal.pdf(X_test, mean=self.mu, cov=self.Sigma, allow_singular=True)\n        assert p_X.shape == (X_test.shape[0],), f\"The predicted probability densities must be a {X_test.shape[0]}-dimensional vector\"\n        # Calculating m-dimensional prediction vector (probability density function)\n        predictions = np.where(p_X < self.epsilon, 1, 0)\n        return predictions\n\nclass MultivariateTDistribution(MultivariateGaussian):\n    \"\"\"\n    Anomaly detector using the 'fat-tail' Student's t-Distribution.\n    \"\"\"\n    def __init__(self, epsilon=None, df=None):\n        self.epsilon = epsilon\n        # Degrees of freedom parameter\n        self.df = df\n\n    def predict(self, test_data):\n        X_test = np.array(test_data)\n        df = self.df\n        n = test_data.shape[1]\n        mu = self.mu\n        Sigma = self.Sigma\n        pdf_list = []\n        # The following codes should be vectorised, any suggestions are welcomed\n        for x_test in X_test:\n            term_1_num = gamma((n+df)\/2)\n            term_1_denom = gamma((df\/2)) * df**(n\/2) * pi**(n\/2) * np.linalg.det(Sigma)**0.5\n            term_1 = term_1_num \/ term_1_denom\n            term_2 = (1 + 1\/df * (x_test - mu).T @ np.linalg.inv(Sigma) @ (x_test - mu)) ** (-1 * (n+df)\/2)\n            pdf_x = term_1 * term_2\n            pdf_list.append(pdf_x)\n        pdf_X = np.array(pdf_list)\n        assert pdf_X.shape == (X_test.shape[0],), f\"The predicted probability densities must be a {X_test.shape[0]}-dimensional vector\"\n        predictions = np.where(pdf_X < self.epsilon, 1, 0)\n        return predictions\n\nclass SimpleAnomalyDetector(BaseEstimator):\n    \"\"\"\n    Simple anomaly detector, a predicted probability density is the product of all features' probabilities.\n    Based on Andrew Ng's lecture.\n    \"\"\"\n    def __init__(self, epsilon=None):\n        self.epsilon = epsilon\n\n    def fit(self, train_data):\n        X = np.array(train_data)\n        # Calculating n-dimensional mean vector (mu)\n        self.mu = np.mean(X, axis=0).reshape(-1, 1)\n        # Calculating n-dimensional vector of feature variances (sigma)\n        self.sigma = np.var(X, axis=0).reshape(-1, 1)\n        assert self.mu.shape == (X.shape[1], 1)\n        assert self.sigma.shape == (X.shape[1], 1)\n        return self\n\n    def predict(self, test_data):\n        X_test = np.array(test_data)\n        mu = self.mu\n        sigma = self.sigma\n        term_1 = -1 * np.square(X_test - np.tile(mu, len(X_test)).T)\n        term_2 = 2 * np.tile(sigma, len(X_test)).T\n        term_3 = np.exp(term_1 \/ term_2)\n        term_4 = (1 \/ ((2*np.pi)**0.5 * np.power(sigma, np.array(0.5))))\n        term_4 = np.tile(term_4, len(X_test)).T\n        term_5 = term_3 * term_4\n        pdf_X = np.prod(term_5, axis=1)\n        assert pdf_X.shape == (X_test.shape[0],), f\"The predicted probability densities must be a {X_test.shape[0]}-dimensional vector\"\n        predictions = np.where(pdf_X < self.epsilon, 1, 0)\n        return predictions\n\"\"\"\n## Loading data - Credit Card Fraud dataset\n#### Context on the dataset\n\nV1 to V28 are PCA components of the data. Only features 'Time' and 'Amount' are untransformed features.\n\nFor more details about the dataset, visit the [Kaggle site here](https:\/\/www.kaggle.com\/mlg-ulb\/creditcardfraud).\n\n>The datasets contains transactions made by credit cards in September 2013 by european cardholders.\nThis dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. \nThe dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.\nIt contains only numerical input variables which are the result of a PCA transformation.\n\"\"\"\n# Importing the Credit Card Fraud dataset\ndata = pd.read_csv('\/kaggle\/input\/creditcardfraud\/creditcard.csv')\ny_data = data.copy()['Class'].values\noriginal_data = data.copy()\n\n# Clean data set\nnormal_only_data = data[data['Class']==0]\nprint('Normal only data shape: ', normal_only_data.shape)\n# Fraud data set\nfraud_only_data = data[data['Class']==1]\nprint('Fraud only data shape: ', fraud_only_data.shape)\n\n# Shuffling the data\nnormal_only_data = normal_only_data.sample(frac=1, random_state=42)\nfraud_only_data = fraud_only_data.sample(frac=1, random_state=42)\n\n# 80\/10\/10 data split for normal data\ntrain_set, dev_set, test_set = np.split(normal_only_data, [int(0.8*len(normal_only_data)), int(0.9*len(normal_only_data))])\ntrain_set = train_set.drop('Class', axis=1)\n\n# 50\/50 data split for fraud data\nfraud_set_1, fraud_set_2 = np.split(fraud_only_data, [int(0.5*len(fraud_only_data))])\n\n# Appending fraud data to dev and test set\ndev_set = dev_set.append(fraud_set_1)\ny_dev_set = dev_set['Class']\ndev_set = dev_set.drop('Class', axis=1)\ntest_set = test_set.append(fraud_set_2)\ny_test_set = test_set['Class']\ntest_set = test_set.drop('Class', axis=1)\n\n# Showing shapes\nfor name, data in zip(['Train data shape: ', 'Dev data shape: ', 'Test data shape: '],[train_set, dev_set, test_set]):\n    print(name, data.shape)\n# Showing the first few rows of the data\noriginal_data.head()\n\"\"\"\n## Trying out Custom Estimators - Novelty detection\nFor simplicity, I will train and test the custom and a few scikit-learn models on a novelty detection bias.\n\nNovelty detection uses clean data (normal) only to train, and predict on contaminated data. Whereas Outlier detection uses contaminated (normal + fraud) data to train.\n\nFor more information, refer to scikit-learn's [Guidance](https:\/\/scikit-learn.org\/stable\/modules\/outlier_detection.html#outlier-detection) here\n\"\"\"\n# Helper function to evaluate models\nlabels = ['Normal', 'Fraud']\ndef evaluate_model(y_true, y_preds, labels=labels):\n    cm = confusion_matrix(y_true, y_preds)\n    print('Recall score:\\n', recall_score(y_true, y_preds))\n    print('Precision score:\\n', precision_score(y_true, y_preds))\n    print('Confusion matrix:\\n')\n    cm_df = pd.DataFrame({'Normal (predicted)': (cm[0, 0], cm[1, 0]),\n                         'Fraud (predicted)': (cm[0, 1], cm[1, 1])},\n                        index=['Normal (true)', 'Fraud (true)'])\n    print(cm_df)\n# Training Multivariate Gaussian Anomaly Detector\nmvg = MultivariateGaussian(epsilon=0.05**30)\nmvg.fit(train_set)\n# Evaluating on the Dev set\nmvg_y_dev_preds = mvg.predict(dev_set)\nevaluate_model(y_dev_set, mvg_y_dev_preds)\n# Training Simple Anomaly Detector (SAD)\n# Side note: I'm still thinking about a new name for this Estimator ... suggestions are welcomed\nsimple = SimpleAnomalyDetector(epsilon=0.05**30)\nsimple.fit(train_set)\n# Evaluating on the Dev Set\ny_simple_dev_preds = simple.predict(dev_set)\nevaluate_model(y_dev_set, y_simple_dev_preds)\n# Training Multivariate T Anomaly Detector\nmvt = MultivariateTDistribution(epsilon=0.05**30, df=3)\nmvt.fit(train_set)\n# Evaluating on the Dev Set\nmvt_y_dev_preds = mvt.predict(dev_set)\nevaluate_model(y_dev_set, mvt_y_dev_preds)\n# Training Local Outlier Factor Anomaly Detector\nlof = LocalOutlierFactor(novelty=True, metric='euclidean')\nlof.fit(train_set)\n# Evaluating on the Dev set\nlof_y_dev_preds = lof.predict(dev_set)\nlof_y_dev_preds[lof_y_dev_preds==1] = 0\nlof_y_dev_preds[lof_y_dev_preds==-1] = 1\nevaluate_model(y_dev_set, lof_y_dev_preds)\n# Training Isolation Forest Anomaly Detector\nifr = IsolationForest(random_state=42, behaviour=\"new\")\nifr.fit(train_set)\n# Evaluating on the Dev Set\nifr_y_dev_preds = ifr.predict(dev_set)\nifr_y_dev_preds[ifr_y_dev_preds==1] = 0\nifr_y_dev_preds[ifr_y_dev_preds==-1] = 1\nevaluate_model(y_dev_set, ifr_y_dev_preds)\n# Training Kmeans Clustering\nkmeans = KMeans(n_clusters=2, algorithm='auto')\nkmeans.fit(train_set)\n# Evaluating KMeans on the Dev Set\nkmeans_y_dev_preds = kmeans.predict(dev_set)\n# Since KMeans only does clustering, we can decide which cluster would be Normal and which cluster would be Fraud\nkmeans_y_dev_preds = np.where(kmeans_y_dev_preds==1, 0, 1)\nevaluate_model(y_dev_set, kmeans_y_dev_preds)\n\"\"\"\n#### Contaminated dataset\n\"\"\"\n# Trying out Isolation Forest on contaminated dataset\nifr_2 = IsolationForest(random_state=42, behaviour=\"new\")\nifr_2_y_preds = ifr_2.fit_predict(original_data.drop('Class', axis=1))\nifr_2_y_preds[ifr_2_y_preds==1] = 0\nifr_2_y_preds[ifr_2_y_preds==-1] = 1\nevaluate_model(y_data, ifr_2_y_preds)\n\"\"\"\n## Trying out Neural Network Autoencoders\n\n#### Intuition\nThe basic idea behind NN Autoencoders is to learn the very low-level representations of the data. After this process hopefully the 'noise' have been minimised from the data, and the result representations (outputs of NN Autoencoders) can be used as inputs to simplier classifiers such as Logistic Regression.\n\"\"\"\nfrom keras.layers import Input, Dense\nfrom keras.models import Model, Sequential\nfrom keras import regularizers\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n# Considered using XGBoost, my it would take a while on my EY laptop\n# I use smaller sample to save computational time\ntrain_data = normal_only_data[:100000].append(fraud_only_data[:390])\ntrain_data = train_data.sample(frac=1, random_state=42)\nprint('NN Train data shape:\\n', train_data.shape)\ndev_data = normal_only_data[100000:120000].append(fraud_only_data[390:])\ndev_data = dev_data.sample(frac=1, random_state=42)\nprint('NN Dev data shape:\\n', dev_data.shape)\n# Separating X and y\nX_train_nn, y_train_nn = train_data.drop('Class', axis=1, inplace=False), train_data['Class'].values\nscaler = MinMaxScaler()\nX_train_nn = scaler.fit_transform(X_train_nn)\nprint(X_train_nn.shape, y_train_nn.shape)\nX_dev_nn, y_dev_nn = dev_data.drop('Class', axis=1, inplace=False), dev_data['Class'].values\nX_dev_nn = scaler.transform(X_dev_nn)\nprint(X_dev_nn.shape, y_dev_nn.shape)\n# Building computational graph for NN Autocencoder\n# Input layer\ninput_layer = Input(shape=(X_train_nn.shape[1],))\n\n# Encoding part\nencoded_1 = Dense(200, activation='tanh', activity_regularizer=regularizers.l1(10e-5))(input_layer)\nencoded_2 = Dense(100, activation='relu')(encoded_1)\n\n# Decoding part\ndecoded_1 = Dense(100, activation='tanh')(encoded_2)\ndecoded_2 = Dense(200, activation='tanh')(decoded_1)\n\n# Output layer\noutput_layer = Dense(X_train_nn.shape[1], activation='relu')(decoded_2)\n\n# Compiling model\nautoencoder = Model(input_layer, output_layer)\nautoencoder.compile(optimizer='adam', loss='mse')\n# Training the model\nautoencoder.fit(X_train_nn, X_train_nn,\n                batch_size=256, epochs=20,\n                shuffle=True, validation_split=0.2\n               )\nautoencoder.summary()\n# Building a computation graph to get the hidden representations of X\nhidden_representation = Sequential()\nhidden_representation.add(autoencoder.layers[0])\nhidden_representation.add(autoencoder.layers[1])\nhidden_representation.add(autoencoder.layers[2])\n# Obtaining the hidden representations of X_train\nrep_X_train = hidden_representation.predict(X_train_nn)\n# Logistic Regression - mapping NN Training output to y\nlogreg = LogisticRegression(solver='lbfgs')\nlogreg.fit(rep_X_train, y_train_nn)\n# Now moving on to the Dev Set\nrep_X_dev = hidden_representation.predict(X_dev_nn)\nnn_y_dev_preds = logreg.predict(rep_X_dev)\nnp.unique(nn_y_dev_preds)\n# Evaluating the Dev Set\nevaluate_model(y_dev_nn, nn_y_dev_preds)\n# Random Forest Classifier - training on hidden representations of X\nrf = RandomForestClassifier(random_state=42)\nrf.fit(rep_X_train, y_train_nn)\n# Evaluating on the Dev Set\nnn_y_dev_preds_rf = rf.predict(rep_X_dev)\nevaluate_model(y_dev_nn, nn_y_dev_preds_rf)","meta":"{'source': 'AI4Code', 'id': '53b4b6fae181d1'}"}
{"id":"109831","text":"from IPython.display import display, HTML\n\ndisplay(HTML(data=\"\"\"\n<style>\n    div#notebook-container    { width: 95%; }\n    div#menubar-container     { width: 65%; }\n    div#maintoolbar-container { width: 99%; }\n<\/style>\n\"\"\"))\n#to use different versions\n!pip install efficientnet\n#!pip install --upgrade tensorflow-gpu\n#!pip install --upgrade efficientnet\nimport numpy as np\nimport pandas as pd\nimport os\nimport json, codecs\nimport tensorflow as tf\nfrom efficientnet.keras import EfficientNetB0\nfrom kaggle_datasets import KaggleDatasets\nprint(tf.__version__)\n\"\"\"\n# TPU or GPU Detection\n\"\"\"\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\"\"\"\n# Data Access\n\"\"\"\n#name = !ls \/kaggle\/input\n#name\n#name = !ls \/kaggle\/input\/\n#GCS_DS_PATH = KaggleDatasets().get_gcs_path('herbarium-2020-fgvc7') # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nfor dirname,_,filenames in os.walk(\"..\/input\/herbarium-2020-fgvc7\"):\n    for filename in filenames:\n        if filename.endswith('.jpg'):\n            break\n        print(os.path.join(dirname,filename))\nwith codecs.open(\"..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/metadata.json\", 'r',\n                 encoding='utf-8', errors='ignore') as f:\n    train_meta = json.load(f)\n    \nwith codecs.open(\"..\/input\/herbarium-2020-fgvc7\/nybg2020\/test\/metadata.json\", 'r',\n                 encoding='utf-8', errors='ignore') as f:\n    test_meta = json.load(f)\ntrain_meta.keys()\ntrain_df = pd.DataFrame(train_meta['annotations'])\ntrain_df\ntrain_cat = pd.DataFrame(train_meta['categories'])\ntrain_cat.columns = ['family', 'genus', 'category_id', 'category_name']\ntrain_cat\ntrain_img = pd.DataFrame(train_meta['images'])\ntrain_img.columns = ['file_name', 'height', 'image_id', 'license', 'width']\ntrain_img\ntrain_reg = pd.DataFrame(train_meta['regions'])\ntrain_reg.columns = ['region_id', 'region_name']\ntrain_reg\ntrain_df = train_df.merge(train_cat, on='category_id', how='outer')\ntrain_df = train_df.merge(train_img, on='image_id', how='outer')\ntrain_df = train_df.merge(train_reg, on='region_id', how='outer')\ntrain_df\ntrain_df.info()\nna = train_df.file_name.isna()\nkeep = [x for x in range(train_df.shape[0]) if not na[x]]\ntrain_df = train_df.iloc[keep]\ndtypes = ['int32', 'int32', 'int32', 'int32', 'object', 'object', 'object', 'object', 'int32', 'int32', 'int32', 'object']\nfor n, col in enumerate(train_df.columns):\n    train_df[col] = train_df[col].astype(dtypes[n])\nprint(train_df.info())\ntrain_df\ntest_df = pd.DataFrame(test_meta['images'])\ntest_df.columns = ['file_name', 'height', 'image_id', 'license', 'width']\nprint(test_df.info())\ntest_df\nprint(\"Total Unique Values for each columns:\")\nprint(\"{0:10s} \\t {1:10d}\".format('train_df', len(train_df)))\nfor col in train_df.columns:\n    print(\"{0:10s} \\t {1:10d}\".format(col, len(train_df[col].unique())))\nfamily = train_df[['family', 'genus', 'category_name']].groupby(['family', 'genus']).count()\ndisplay(family.describe())\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Conv2D, MaxPool2D, Flatten, BatchNormalization, Input, concatenate\nfrom keras.optimizers import Adam\nfrom keras.utils import plot_model\nfrom sklearn.model_selection import train_test_split as tts\n\n\n\ndef xavier(shape, dtype=None):\n    return np.random.rand(*shape)*np.sqrt(1\/in_out_size)\n\n\n\ndef fg_model(shape,lr):\n    \n    actual_shape = shape\n    i = Input(actual_shape)\n    x = EfficientNetB0(weights='imagenet', include_top=False, input_shape=actual_shape, pooling='max')(i)\n    #x = Flatten()(x)\n    o1 = Dense(310, name=\"family\", activation='softmax')(x)\n    o2 = concatenate([x,o1])\n    o2 = Dense(3678, name=\"genus\", activation='softmax')(o2)\n    o3 = concatenate([x,o1,o2])\n    o3 = Dense(32094, name=\"category_id\", activation='softmax')(o3)\n    model = Model(inputs=i,outputs=[o1,o2,o3])\n    \n    model.layers[1].trainable = False\n    model.get_layer('genus').trainable = False\n    model.get_layer('category_id').trainable = False\n    \n    opt = Adam(lr=lr, amsgrad=True)\n    model.compile(optimizer=opt, loss=['sparse_categorical_crossentropy', \n                                   'sparse_categorical_crossentropy', \n                                   'sparse_categorical_crossentropy'],\n                 metrics=['accuracy'])\n    return model\n\n\n#plot_model(model, to_file='full_model_plot.png', show_shapes=True, show_layer_names=True)\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(featurewise_center=False,\n                                     featurewise_std_normalization=False,\n                                     rotation_range=180,\n                                     width_shift_range=0.1,\n                                     height_shift_range=0.1,\n                                     zoom_range=0.2)\nm = train_df[['file_name', 'family', 'genus', 'category_id']]\nfam = m.family.unique().tolist()\nm.family = m.family.map(lambda x: fam.index(x))\ngen = m.genus.unique().tolist()\nm.genus = m.genus.map(lambda x: gen.index(x))\ndisplay(m)\ntrain, verif = tts(m, test_size=0.2, shuffle=True, random_state=17)\ntrain = train[:80000]\nverif = verif[:20000]\nshape = (224,224, 3)\nepochs = 8\nbatch_size = 32\n\n#model = fg_model(shape, 0.007)\n#model.summary()\nmodel = fg_model((224,224,3), 0.007)\nmodel.summary()\n#Disable the last two output layers for training the Family\nfor layers in model.layers:\n    if layers.name == 'genus' or layers.name=='category_id':\n        layers.trainable = False\n#Train Family for 2 epochs\nmodel.fit_generator(train_datagen.flow_from_dataframe(dataframe=train,\n                                                      directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                                                      x_col=\"file_name\",\n                                                      y_col=[\"family\", \"genus\", \"category_id\"],\n                                                      target_size=(224,224),\n                                                      batch_size=batch_size,\n                                                      class_mode='multi_output'),\n                    validation_data=train_datagen.flow_from_dataframe(\n                        dataframe=verif,\n                        directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                        x_col=\"file_name\",\n                        y_col=[\"family\", \"genus\", \"category_id\"],\n                        target_size=(224,224),\n                        batch_size=batch_size,\n                        class_mode='multi_output'),\n                    epochs=epochs,\n                    steps_per_epoch=len(train)\/\/batch_size,\n                    validation_steps=len(verif)\/\/batch_size,\n                    verbose=1,\n                    workers=8,\n                    use_multiprocessing=False)\n\nmodel.save_weights(\"weights.h5\")\nmodel.save(\"model.h5\")\n#Reshuffle the inputs\ntrain, verif = tts(m, test_size=0.2, shuffle=True, random_state=17)\ntrain = train#[:500000]\nverif = verif#[:100000]\n#Make the Genus layer Trainable\nfor layers in model.layers:\n    if layers.name == 'genus':\n        layers.trainable = True\n        \n#Train Family and Genus for 2 epochs\nmodel.fit_generator(train_datagen.flow_from_dataframe(dataframe=train,\n                                                      directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                                                      x_col=\"file_name\",\n                                                      y_col=[\"family\", \"genus\", \"category_id\"],\n                                                      target_size=(224,224),\n                                                      batch_size=batch_size,\n                                                      class_mode='multi_output'),\n                    validation_data=train_datagen.flow_from_dataframe(\n                        dataframe=verif,\n                        directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                        x_col=\"file_name\",\n                        y_col=[\"family\", \"genus\", \"category_id\"],\n                        target_size=(224,224),\n                        batch_size=batch_size,\n                        class_mode='multi_output'),\n                    epochs=epochs,\n                    steps_per_epoch=len(train)\/\/batch_size,\n                    validation_steps=len(verif)\/\/batch_size,\n                    verbose=1,\n                    workers=4,\n                    use_multiprocessing=False)\n\nmodel.save_weights(\"weights.h5\")\nmodel.save(\"model.h5\")\n#Reshuffle the inputs\ntrain, verif = tts(m, test_size=0.2, shuffle=True, random_state=17)\ntrain = train#[:500000]\nverif = verif#[:100000]\n\n#Make the category_id layer Trainable\nfor layers in model.layers:\n    if layers.name == 'category_id':\n        layers.trainable = True\n        \n#Train them all for 2 epochs\nmodel.fit_generator(train_datagen.flow_from_dataframe(dataframe=train,\n                                                      directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                                                      x_col=\"file_name\",\n                                                      y_col=[\"family\", \"genus\", \"category_id\"],\n                                                      target_size=(224,224),\n                                                      batch_size=batch_size,\n                                                      class_mode='multi_output'),\n                    validation_data=train_datagen.flow_from_dataframe(\n                        dataframe=verif,\n                        directory='..\/input\/herbarium-2020-fgvc7\/nybg2020\/train\/',\n                        x_col=\"file_name\",\n                        y_col=[\"family\", \"genus\", \"category_id\"],\n                        target_size=(224,224),\n                        batch_size=batch_size,\n                        class_mode='multi_output'),\n                    epochs=epochs,\n                    steps_per_epoch=len(train)\/\/batch_size,\n                    validation_steps=len(verif)\/\/batch_size,\n                    verbose=1,\n                    workers=4,\n                    use_multiprocessing=False)\nmodel.save_weights(\"weights.h5\")\nmodel.save(\"model.h5\")","meta":"{'source': 'AI4Code', 'id': 'c9d683c476a909'}"}
{"id":"95577","text":"\"\"\"\n<h2>chaii QA - 5 Fold XLMRoberta Training + Inference in Torch w\/o Trainer API<\/h2>\n    \n<h3><span \"style: color=#444\">Introduction<\/span><\/h3>\n\nThis kernel preprocesses MLQA, XQUAD Hindi Corpus. For more information check the finetuning notebook.\n\nThis is a three part kernel,\n\n- [External Data - MLQA, XQUAD Preprocessing](https:\/\/www.kaggle.com\/rhtsingh\/external-data-mlqa-xquad-preprocessing) which preprocesses the Hindi Corpus of MLQA and XQUAD. I have used these data for training.\n\n- [chaii QA - 5 Fold XLMRoberta Torch | FIT](https:\/\/www.kaggle.com\/rhtsingh\/chaii-qa-5-fold-xlmroberta-torch-fit\/edit) This kernel showcases Finetuning (FIT) on competition + external data combining different strategies.\n\n- [chaii QA - 5 Fold XLMRoberta Torch | Infer](https:\/\/www.kaggle.com\/rhtsingh\/chaii-qa-5-fold-xlmroberta-torch-infer) The Inference kernel where we ensemble our 5 Fold XLMRoberta Models and do the submission.\n\"\"\"\n\"\"\"\n## MLQA\n\"\"\"\n!wget https:\/\/dl.fbaipublicfiles.com\/MLQA\/MLQA_V1.zip\nimport zipfile\nwith zipfile.ZipFile('\/kaggle\/working\/MLQA_V1.zip') as zip_ref:\n    zip_ref.extractall('\/kaggle\/working\/')\nimport os\nimport sys\nimport random\nimport argparse\nimport json\nimport nltk\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\n# sys.setdefaultencoding('utf8')\nrandom.seed(42)\nnp.random.seed(42)\nmlqa_train_data = '\/kaggle\/working\/MLQA_V1\/dev\/dev-context-hi-question-hi.json'\nmlqa_test_data = '\/kaggle\/working\/MLQA_V1\/test\/test-context-hi-question-hi.json'\n\nwith open(mlqa_train_data, 'r') as file_input:\n    train_file = json.load(file_input)\n    \nwith open(mlqa_test_data, 'r') as file_input:\n    test_file = json.load(file_input)\ndef preprocess(dataset, tier):\n    num_exs = 0 \n    examples = []\n\n    for articles_id in tqdm(range(len(dataset['data'])), desc=\"Preprocessing {}\".format(tier)):\n        article_paragraphs = dataset['data'][articles_id]['paragraphs']\n        for pid in range(len(article_paragraphs)):\n            context = article_paragraphs[pid]['context']\n            context = context.replace(\"''\", '\" ')\n            context = context.replace(\"``\", '\" ')\n            qas = article_paragraphs[pid]['qas'] \n            for qn in qas:\n                question = qn['question'] \n                ans_text = qn['answers'][0]['text']\n                ans_start_charloc = qn['answers'][0]['answer_start']\n                ans_end_charloc = ans_start_charloc + len(ans_text)\n                examples.append(\n                    {\n                        # 'id':articles_id,\n                        'context':context, \n                        'question':question, \n                        'answer_text':ans_text, \n                        'answer_start':ans_start_charloc, \n                        # 'answer_end':ans_end_charloc\n                    }\n                )\n\n                num_exs += 1\n    print(num_exs)    \n    return examples\nexamples_train = preprocess(train_file, 'dev')\nexamples_test = preprocess(test_file, 'test')\nexamples = examples_train + examples_test\nmlqa = pd.DataFrame(examples)\nmlqa['language'] = 'hindi'\n\"\"\"\n### XQUAD\n\"\"\"\n!git clone https:\/\/github.com\/deepmind\/xquad.git\nxquad_train_file = '\/kaggle\/working\/xquad\/xquad.hi.json'\n\nwith open(xquad_train_file, 'r') as file_input:\n    train_file = json.load(file_input)\n    \nexamples_train = preprocess(train_file, 'dev')\nxquad = pd.DataFrame(examples_train)\nxquad['language'] = 'hindi'\n\"\"\"\n### Remove downloaded files\n\"\"\"\nimport os, shutil\nfolder = '\/kaggle\/working\/'\nfor filename in os.listdir(folder):\n    file_path = os.path.join(folder, filename)\n    try:\n        if os.path.isfile(file_path) or os.path.islink(file_path):\n            os.unlink(file_path)\n        elif os.path.isdir(file_path):\n            shutil.rmtree(file_path)\n    except Exception as e:\n        print('Failed to delete %s. Reason: %s' % (file_path, e))\n\"\"\"\n### Save Data\n\"\"\"\nmlqa.to_csv('mlqa_hindi.csv', index=False)\nxquad.to_csv('xquad.csv', index=False)\nxquad.head(5)\nmlqa.head(5)","meta":"{'source': 'AI4Code', 'id': 'af7cbbf0f81abe'}"}
{"id":"18472","text":"\"\"\"\n# import libraries\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport ast\nimport os\nimport json\nimport pandas as pd\nimport torch\nimport importlib\nimport cv2 \n\nfrom shutil import copyfile\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\nfrom sklearn.model_selection import GroupKFold\nfrom PIL import Image\nfrom string import Template\nfrom IPython.display import display\n\nTRAIN_PATH = '\/kaggle\/input\/tensorflow-great-barrier-reef'\n\"\"\"\n# install YOLOX\n\"\"\"\n!git clone https:\/\/github.com\/Megvii-BaseDetection\/YOLOX -q\n\n%cd YOLOX\n!pip install -U pip && pip install -r requirements.txt\n!pip install -v -e . \n!pip install 'git+https:\/\/github.com\/cocodataset\/cocoapi.git#subdirectory=PythonAPI'\n\"\"\"\n# Prepare dataset for YOLOX to train\nThis section is taken from  notebook created by Awsaf [Great-Barrier-Reef: YOLOv5 train](https:\/\/www.kaggle.com\/awsaf49\/great-barrier-reef-yolov5-train)\n\"\"\"\ndef get_bbox(annots):\n    bboxes = [list(annot.values()) for annot in annots]\n    return bboxes\n\ndef get_path(row):\n    row['image_path'] = f'{TRAIN_PATH}\/train_images\/video_{row.video_id}\/{row.video_frame}.jpg'\n    return row\ndf = pd.read_csv(\"\/kaggle\/input\/tensorflow-great-barrier-reef\/train.csv\")\ndf.head(5)\n# Taken only annotated photos\ndf[\"num_bbox\"] = df['annotations'].apply(lambda x: str.count(x, 'x'))\ndf_train = df[df[\"num_bbox\"]>0]\n\n#Annotations \ndf_train['annotations'] = df_train['annotations'].progress_apply(lambda x: ast.literal_eval(x))\ndf_train['bboxes'] = df_train.annotations.progress_apply(get_bbox)\n\n#Images resolution\ndf_train[\"width\"] = 1280\ndf_train[\"height\"] = 720\n\n#Path of images\ndf_train = df_train.progress_apply(get_path, axis=1)\n\nkf = GroupKFold(n_splits = 5) \ndf_train = df_train.reset_index(drop=True)\ndf_train['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(kf.split(df_train, y = df_train.video_id.tolist(), groups=df_train.sequence)):\n    df_train.loc[val_idx, 'fold'] = fold\n\ndf_train.head(5)\n\"\"\"\n# Create directory for storage \n\"\"\"\nHOME_DIR = '\/kaggle\/working\/' \nDATASET_PATH = 'dataset\/images'\n\n!mkdir {HOME_DIR}dataset\n!mkdir {HOME_DIR}{DATASET_PATH}\n!mkdir {HOME_DIR}{DATASET_PATH}\/train2017\n!mkdir {HOME_DIR}{DATASET_PATH}\/val2017\n!mkdir {HOME_DIR}{DATASET_PATH}\/annotations\nSELECTED_FOLD = 4\n\nfor i in tqdm(range(len(df_train))):\n    row = df_train.loc[i]\n    if row.fold != SELECTED_FOLD:\n        copyfile(f'{row.image_path}', f'{HOME_DIR}{DATASET_PATH}\/train2017\/{row.image_id}.jpg')\n    else:\n        copyfile(f'{row.image_path}', f'{HOME_DIR}{DATASET_PATH}\/val2017\/{row.image_id}.jpg') \nprint(f'Number of training files: {len(os.listdir(f\"{HOME_DIR}{DATASET_PATH}\/train2017\/\"))}')\nprint(f'Number of validation files: {len(os.listdir(f\"{HOME_DIR}{DATASET_PATH}\/val2017\/\"))}')\n\"\"\"\n#  CREATE COCO ANNOTATION FILES\n\"\"\"\ndef save_annot_json(json_annotation, filename):\n    with open(filename, 'w') as f:\n        output_json = json.dumps(json_annotation)\n        f.write(output_json)\nannotion_id = 0\ndef dataset2coco(df, dest_path):\n    \n    global annotion_id\n    \n    annotations_json = {\n        \"info\": [],\n        \"licenses\": [],\n        \"categories\": [],\n        \"images\": [],\n        \"annotations\": []\n    }\n    \n    info = {\n        \"year\": \"2021\",\n        \"version\": \"1\",\n        \"description\": \"COTS dataset - COCO format\",\n        \"contributor\": \"\",\n        \"url\": \"https:\/\/kaggle.com\",\n        \"date_created\": \"2021-1-24\"\n    }\n    annotations_json[\"info\"].append(info)\n    \n    lic = {\n            \"id\": 1,\n            \"url\": \"\",\n            \"name\": \"Unknown\"\n        }\n    annotations_json[\"licenses\"].append(lic)\n\n    classes = {\"id\": 0, \"name\": \"starfish\", \"supercategory\": \"none\"}\n\n    annotations_json[\"categories\"].append(classes)\n\n    \n    for ann_row in df.itertuples():\n            \n        images = {\n            \"id\": ann_row[0],\n            \"license\": 1,\n            \"file_name\": ann_row.image_id + '.jpg',\n            \"height\": ann_row.height,\n            \"width\": ann_row.width,\n            \"date_captured\": \"2021-1-24T15:01:26+00:00\"\n        }\n        \n        annotations_json[\"images\"].append(images)\n        \n        bbox_list = ann_row.bboxes\n        \n        for bbox in bbox_list:\n            b_width = bbox[2]\n            b_height = bbox[3]\n            \n            # some boxes in COTS are outside the image height and width\n            if (bbox[0] + bbox[2] > 1280):\n                b_width = bbox[0] - 1280 \n            if (bbox[1] + bbox[3] > 720):\n                b_height = bbox[1] - 720 \n                \n            image_annotations = {\n                \"id\": annotion_id,\n                \"image_id\": ann_row[0],\n                \"category_id\": 0,\n                \"bbox\": [bbox[0], bbox[1], b_width, b_height],\n                \"area\": bbox[2] * bbox[3],\n                \"segmentation\": [],\n                \"iscrowd\": 0\n            }\n            \n            annotion_id += 1\n            annotations_json[\"annotations\"].append(image_annotations)\n        \n        \n    print(f\"Dataset COTS annotation to COCO json format completed! Files: {len(df)}\")\n    return annotations_json\n\n# Convert COTS dataset to JSON COCO\ntrain_annot_json = dataset2coco(df_train[df_train.fold != SELECTED_FOLD], f\"{HOME_DIR}{DATASET_PATH}\/train2017\/\")\nval_annot_json = dataset2coco(df_train[df_train.fold == SELECTED_FOLD], f\"{HOME_DIR}{DATASET_PATH}\/val2017\/\")\n\n# Save converted annotations\nsave_annot_json(train_annot_json, f\"{HOME_DIR}{DATASET_PATH}\/annotations\/train.json\")\nsave_annot_json(val_annot_json, f\"{HOME_DIR}{DATASET_PATH}\/annotations\/valid.json\")\n\"\"\"\n# Download a pretrain model\n\"\"\"\n!ls\nsh = 'wget https:\/\/github.com\/Megvii-BaseDetection\/storage\/releases\/download\/0.0.1\/yolox_s.pth'\nMODEL_FILE = 'yolox_s.pth'\nwith open('script.sh', 'w') as file:\n    file.write(sh)\n\n!bash script.sh\n\"\"\"\n# Find a configuration file\n\"\"\"\nconfig_file_template = '''\n#!\/usr\/bin\/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) Megvii, Inc. and its affiliates.\n\nimport os\n\nfrom yolox.exp import Exp as MyExp\n\n\nclass Exp(MyExp):\n    def __init__(self):\n        super(Exp, self).__init__()\n        self.depth = 1.0\n        self.width = 1.0\n        self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n        \n        # Define yourself dataset path\n        self.data_dir = \"\/kaggle\/working\/dataset\/images\"\n        self.train_ann = \"train.json\"\n        self.val_ann = \"valid.json\"\n\n        self.num_classes = 1\n\n        self.max_epoch = $max_epoch\n        self.data_num_workers = 4\n        self.eval_interval = 20  \n        \n        self.mosaic_prob = 1.0\n        self.mixup_prob = 1.0\n        self.hsv_prob = 1.0\n        self.flip_prob = 0.5\n        self.no_aug_epochs = 2\n        \n        self.input_size = (960, 960)\n        #self.mosaic_scale = (0.5, 1.5)\n        self.random_size = (10, 20)\n        self.test_size = (960, 960)\n'''\nPIPELINE_CONFIG_PATH='cots_config.py'\n\npipeline = Template(config_file_template).substitute(max_epoch = 20)\n\nwith open(PIPELINE_CONFIG_PATH, 'w') as f:\n    f.write(pipeline)\n    \n# .\/yolox\/data\/datasets\/voc_classes.py\n\nvoc_cls = '''\nVOC_CLASSES = (\n  \"starfish\",\n)\n'''\nwith open('.\/yolox\/data\/datasets\/voc_classes.py', 'w') as f:\n    f.write(voc_cls)\n\n# .\/yolox\/data\/datasets\/coco_classes.py\n\ncoco_cls = '''\nCOCO_CLASSES = (\n  \"starfish\",\n)\n'''\nwith open('.\/yolox\/data\/datasets\/coco_classes.py', 'w') as f:\n    f.write(coco_cls)\n\n# check if everything is ok    \n!more .\/yolox\/data\/datasets\/coco_classes.py\n\"\"\"\n# train\n\"\"\"\n\"\"\"\n# install pytorch\n\"\"\"\n!pip3 install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio===0.10.1+cu113 -f https:\/\/download.pytorch.org\/whl\/cu113\/torch_stable.html\n!nvidia-smi\n!sudo kill -9 <pid>\n!cp .\/tools\/train.py .\/\n!python train.py \\\n    -f cots_config.py \\\n    -d 1 \\\n    -b 32 \\\n    --fp16 \\\n    -o \\\n    -c {MODEL_FILE}   \n!cp -r YOLOX_outputs \/kaggle\/working","meta":"{'source': 'AI4Code', 'id': '21bcab970a7425'}"}
{"id":"133348","text":"\"\"\"\n#### If you want to know more about how the data is collected, Cleaned and Preprocessed You can visit this repo on my github: https:\/\/github.com\/eyadayman12\/FC-Bayern-Munich-Face-Recognation\n\"\"\"\n\"\"\"\n# Table of Contents\n<a id=\"toc\"><\/a>\n- [1. Data Description](#1)\n- [2. Import Necssaries Libraries](#2)\n- [3. Explore the Data](#3)\n    - [3.1 Information about Data](#3.1)\n    - [3.2 Visualization](#3.2)\n- [4. Assign Features and target Variable](#4)\n- [5. Spliting the data into Training and Testing Data](#5)\n- [6. Hyperparameter Tuning](#6)\n- [7. Machine Learning Modeling](#7)\n    - [7.1 SVM Model](#7.1)\n        - [7.1.1 Cross Validation](#7.1.1)\n        - [7.1.2 Accuarcy of the model](#7.1.2)\n        - [7.1.3 Confusion Matrix](#7.1.3)\n        - [7.1.4 Classification Report](#7.1.4)\n        - [7.1.5 ROC Curve](#7.1.5)\n    - [7.2 Logistic Regression Model](#7.2)\n        - [7.2.1 Cross Validation](#7.2.1)\n        - [7.2.2 Accuarcy of the model](#7.2.2)\n        - [7.2.3 Confusion Matrix](#7.2.3)\n        - [7.2.4 Classification Report](#7.2.4)\n        - [7.2.5 ROC Curve](#7.2.5)\n    - [7.3 Random Forest Model](#7.3)\n        - [7.3.1 Cross Validation](#7.3.1)\n        - [7.3.2 Accuarcy of the model](#7.3.2)\n        - [7.3.3 Confusion Matrix](#7.3.3)\n        - [7.3.4 Classification Report](#7.3.4)\n    - [7.4 Decision Tree Model](#7.4)\n        - [7.4.1 Cross Validation](#7.4.1)\n        - [7.4.2 Accuarcy of the model](#7.4.2)\n        - [7.4.3 Confusion Matrix](#7.4.3)\n        - [7.4.4 Classification Report](#7.4.4)\n    - [7.5 Bagging](#7.5)\n        - [7.5.1 Cross Validation](#7.5.1)\n        - [7.5.2 Accuarcy of the model](#7.5.2)\n        - [7.5.3 Confusion Matrix](#7.5.3)\n        - [7.5.4 Classification Report](#7.5.4)\n    - [7.6 Boosting](#7.6)\n        - [7.6.1 Cross Validation](#7.6.1)\n        - [7.6.2 Accuarcy of the model](#7.6.2)\n        - [7.6.3 Confusion Matrix](#7.6.3)\n        - [7.6.4 Classification Report](#7.6.4)\n    - [7.7 KNN](#7.7)\n        - [7.7.1 Cross Validation](#7.7.1)\n        - [7.7.2 Accuarcy of the model](#7.7.2)\n        - [7.7.3 Confusion Matrix](#7.7.3)\n        - [7.7.4 Classification Report](#7.7.4)\n    - [7.8 ANN](#7.8)\n        - [7.8.1 Build and Train the ANN](#7.8.1)\n        - [7.8.2 Accuarcy of the model](#7.8.2)\n        - [7.8.3 Loss curve](#7.8.3)\n        - [7.8.4 Confusion Matrix](#7.8.4)\n        - [7.8.5 Classification Report](#7.8.5)\n\"\"\"\n\"\"\"\n<a id=\"1\"><\/a>\n# Data Description\n\"\"\"\n\"\"\"\n***The data contains 5 Bayern Munich players and each player has about 100 random images collected from Google <br>\nso our data have 5 classes:***\n - Kingsley Coman\n - Joshua Kimmich\n - Robert Lewandowski\n - Manuel Neuer\n - Leory Sane<br><br>\n\n***Kingsley Coman Class 0***<br>\n***Joshua Kimmich Class 1***<br>\n***Robert Lewandowski Class 2***<br>\n***Manuel Neuer Class 3***<br>\n***Leory Sane Class 4***<br>\n\"\"\"\n\"\"\"\n<a d='2'><\/a>\n# Import Necssaries Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nfrom math import sqrt\n\nfrom sklearn.preprocessing import StandardScaler, robust_scale, MinMaxScaler\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom sklearn.metrics import classification_report, confusion_matrix, f1_score, roc_curve, auc\nfrom sklearn.preprocessing import LabelEncoder, label_binarize\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers \nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras.utils import to_categorical\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\"\"\"\n<a id='3'><\/a>\n# Explore the Data\n\"\"\"\ndf = pd.read_csv(\"..\/input\/fc-bayern-face-recognation\/Bayern.csv\") # read the data\ndf.head()\n\"\"\"\n<a id='3.1'><\/a>\n**Information about data**\n\"\"\"\nprint(f\"The data contains {len(df)} images\")\nprint(f\"Each image is {int(sqrt(df.shape[1] - 1))} * {int(sqrt(df.shape[1]-1))} Pixels\")\nprint(f\"Data contains {len(df.Target.unique())} Classes\")\ndf.Target.value_counts()\n\"\"\"\n<a id='3.2'><\/a>\n**Visualization**\n\"\"\"\nplt.figure(figsize=(18,12))\nplt.subplot(2,2,1)\nsns.countplot(x='Target', data=df);\n\nplt.subplot(2,2,2)\ncoman = df.Target[df.Target == 0].count()\nkimmich = df.Target[df.Target == 1].count()\nlewa = df.Target[df.Target == 2].count()\nneuer = df.Target[df.Target == 3].count()\nsane = df.Target[df.Target == 4].count()\nweights = [coman, kimmich, lewa, neuer, sane]\nlabels = ['Coman', 'Kimmich', 'Lewandowski', 'Neuer', 'Sane']\nplt.pie(weights, labels=labels, autopct='%.2f%%', explode=[0.01,0.01,0.01,0.01,0.01])\nmy_circle = plt.Circle( (0,0), 0.4, color='white')\nplt.gcf().gca().add_artist(my_circle)\nplt.legend(bbox_to_anchor=(1, 1))\nplt.show()\n\"\"\"\n<a id='4'><\/a>\n# Assign Feature and Target Variable\n\"\"\"\nX = df.drop(\"Target\", axis=1)\ny = df.Target\nX.shape\ny.shape\n\"\"\"\n<a id='5'><\/a>\n# Splitting the data into Training and Testing Data\n\"\"\"\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=150)\nprint(f\"Number of Training data: {len(X_train)}\")\nprint(f\"Number of Testing data: {len(X_test)}\")\nX_train.shape\ny_train.shape\n\"\"\"\n<a id='6'><\/a>\n# Hyperparameter Tuning\n\"\"\"\nmodel_params = {\n    'svm': {\n        'model': SVC(gamma='auto'),\n        'params' : {\n            'C': [100, 10, 1.0, 0.1, 0.001],\n            'kernel': ['rbf','linear', 'poly', 'sigmoid']\n        }  \n    },\n    'random_forest': {\n        'model': RandomForestClassifier(),\n        'params' : {\n            'max_features' : np.arange(1,21),\n            'max_features' : ['sqrt', 'log2'],\n            'n_estimators': [10,100,1000]\n        }\n    },\n    'logistic_regression' : {\n        'model': LogisticRegression(),\n        'params': {\n            'solver': ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],\n            'penalty': ['none', 'l1', 'l2', 'elasticnet'],\n            'C' : [100,10,1.0,0.1,0.01]\n        }\n    },\n    'KNN': {\n        'model' : KNeighborsClassifier(),\n        'params' : {\n            'n_neighbors' : np.arange(1,22),\n            'weights' : ['uniform', 'distance']\n        }\n    }\n}\nscores = []\n\nfor model_name, mp in model_params.items():\n    clf =  GridSearchCV(mp['model'], mp['params'], cv=5, return_train_score=False)\n    clf.fit(X, y)\n    scores.append({\n        'model': model_name,\n        'best_score': clf.best_score_,\n        'best_params': clf.best_params_\n    })\n    \ndf = pd.DataFrame(scores,columns=['model','best_score','best_params'])\ndf\n\"\"\"\n<a id='7'><\/a>\n# Modeling\n\"\"\"\ndef kfolds(model, model_name):\n    model = cross_val_score(model, X,y, cv=10)\n    model_score = np.average(model)\n    print(f\"{model_name} score on cross validation: {model_score * 100}%\")\n\ndef train(model, model_name):\n    model.fit(X_train, y_train)\n    model_train_score = model.score(X_train, y_train)\n    model_test_score = model.score(X_test, y_test)\n    print(f\"{model_name} model score on Training data: {model_train_score * 100}%\\n{model_name} model score on Testing data: {model_test_score * 100}%\")\n\ndef conf_matrix(model):\n    y_pred = model.predict(X_test)\n    cm = confusion_matrix(y_test, y_pred)\n    plt.figure(figsize=(10,8))\n    sns.heatmap(cm, annot=True);\n\ndef class_report(model):\n    y_pred = model.predict(X_test)\n    return classification_report(y_test, y_pred)\n\n\ndef roc(model):\n    y_binarize = label_binarize(y, classes=[0,1,2,3,4])\n    y_binarize.shape\n    n_classes = y_binarize.shape[1]\n    X_train, X_test, y_train, y_test = train_test_split(X,y_binarize, test_size=0.25, random_state=150)\n    classifier = OneVsRestClassifier(\n    model)\n    y_score = classifier.fit(X_train, y_train).decision_function(X_test)\n    fpr = dict()\n    tpr = dict()\n    roc_auc = dict()\n    for i in range(n_classes):\n        fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\n        roc_auc[i] = auc(fpr[i], tpr[i])\n    fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\n    roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n    plt.figure(figsize=(10,7))\n    lw = 2\n    plt.plot(\n        fpr[2],\n        tpr[2],\n        color=\"darkorange\",\n        lw=lw,\n        label=\"ROC curve (area = %0.2f)\" % roc_auc[2],\n    )\n    plt.plot([0, 1], [0, 1], color=\"navy\", lw=lw, linestyle=\"--\")\n    plt.xlabel(\"False Positive Rate\")\n    plt.ylabel(\"True Positive Rate\")\n    plt.title(\"Receiver operating characteristic\")\n    plt.legend(loc=\"lower right\")\n    plt.show()\n\"\"\"\n<a id='7.1'><\/a>\n## SVM Model\n\"\"\"\nsvm_model = SVC(kernel='linear', gamma='auto', C=100)\n\"\"\"\n<a id='7.1.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(svm_model, \"SVM\")\n\"\"\"\n<a id='7.1.2'><\/a>\n**Score of the model**\n\"\"\"\ntrain(svm_model, \"SVM\")\n\"\"\"\n<a id='7.1.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(svm_model)\n\"\"\"\n<a id='7.1.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(svm_model))\n\"\"\"\n<a id='7.1.5'><\/a>\n**ROC Curve**\n\"\"\"\nroc(svm_model)\n\"\"\"\n<a id='7.3'><\/a>\n## Random Forest\n\"\"\"\nrf_model = RandomForestClassifier(n_estimators=1000, random_state=70, max_features='sqrt')\n\"\"\"\n<a id='7.3.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(rf_model, \"Random Forest\")\n\"\"\"\n<a id='7.3.2'><\/a>\n**Accuarcy of the model**\n\"\"\"\ntrain(rf_model, \"Random Forest\")\n\"\"\"\n<a id='7.3.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(rf_model)\n\"\"\"\n<a id='7.3.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(rf_model))\n\"\"\"\n<a id='7.4'><\/a>\n## Decision Tree\n\"\"\"\ndt_model = DecisionTreeClassifier()\n\"\"\"\n<a id='7.4.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(dt_model, \"Decision Tree\")\n\"\"\"\n<a id='7.4.2'><\/a>\n**Accuarcy of the model**\n\"\"\"\ntrain(dt_model, \"Decision Tree\")\n\"\"\"\n<a id='7.4.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(dt_model);\n\"\"\"\n<a id='7.4.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(dt_model))\n\"\"\"\n<a id='7.5'><\/a>\n## Bagging\n\"\"\"\nbagg_model = BaggingClassifier(n_estimators=150)\n\"\"\"\n<a id='7.5.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(bagg_model, \"Bagging\")\n\"\"\"\n<a id='7.5.2'><\/a>\n**Accuarcy of the model**\n\"\"\"\ntrain(bagg_model, \"Bagging\")\n\"\"\"\n<a id='7.5.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(bagg_model)\n\"\"\"\n<a id='7.5.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(bagg_model))\n\"\"\"\n<a id='7.6'><\/a>\n## Boosting\n\"\"\"\ngb_model = GradientBoostingClassifier()\n\"\"\"\n<a id='7.6.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(gb_model, \"Boosting\")\n\"\"\"\n<a id='7.6.2'><\/a>\n**Accuarcy of the model**\n\"\"\"\ntrain(gb_model, \"Boosting\")\n\"\"\"\n<a id='7.6.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(gb_model)\n\"\"\"\n<a id='7.6.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(gb_model))\n\"\"\"\n<a id='7.7'><\/a>\n## KNN\n\"\"\"\nknn = KNeighborsClassifier(n_neighbors=6, weights='distance')\n\"\"\"\n<a id='7.7.1'><\/a>\n**Cross Validation**\n\"\"\"\nkfolds(knn, \"KNN\")\n\"\"\"\n<a id='7.7.2'><\/a>\n**Accuarcy of the model**\n\"\"\"\ntrain(knn, \"KNN\")\n\"\"\"\n<a id='7.7.3'><\/a>\n**Confusion Matrix**\n\"\"\"\nconf_matrix(knn)\n\"\"\"\n<a id='7.7.4'><\/a>\n**Classification Report**\n\"\"\"\nprint(class_report(knn))\n\"\"\"\n<a id='7.8'><\/a>\n## ANN\n\"\"\"\nFEATURES = [col for col in df.columns if col not in ['Target']]\nX_nn = df[FEATURES].to_numpy()\ny_nn = df['Target'].to_numpy()\nX_nn.shape\ny_nn.shape\nX_nn[0].shape\ny_nn\nLE = LabelEncoder()\ny_nn_cat = to_categorical(LE.fit_transform(y_nn))\ny_nn_cat.shape\nX_train_nn, X_test_nn, y_train_nn, y_test_nn = train_test_split(X_nn,y_nn_cat, test_size=0.25, random_state=100)\n\"\"\"\n<a id=\"7.8.1\"><\/a>\n**Build and Train the ANN**\n\"\"\"\ndef load_model(): \n    model = Sequential([\n        Dense(4096, activation ='relu', input_shape = [X.shape[1]]),\n        Dense(2048, activation ='relu'),\n        Dense(1024, activation ='relu'),\n        Dense(512, activation ='relu'),\n        Dense(5, activation='softmax'),\n    ])\n    model.compile(\n        optimizer=  tf.keras.optimizers.Adam(learning_rate = 0.0001),\n        loss='categorical_crossentropy',\n        metrics=['acc'],\n    )\n    return model\n    \nearly_stopping = callbacks.EarlyStopping(\n        patience=10,\n        min_delta=0,\n        monitor='val_loss',\n        restore_best_weights=True,\n        verbose=0,\n        mode='min', \n        baseline=None,\n    )\nplateau = callbacks.ReduceLROnPlateau(\n            monitor='val_loss', \n            factor=0.2, \n            patience=4, \n            verbose=0,\n            mode='min')\n\n\nnn_model = load_model()\nhistory = nn_model.fit(  X_train_nn , y_train_nn,\n                validation_data = (X_test_nn , y_test_nn),\n                epochs = 1000,\n                batch_size = 10,\n                callbacks = [early_stopping , plateau]\n              )\n\"\"\"\n<a id=\"7.8.2\"><\/a>\n**Accuracy of ANN**\n\"\"\"\nnn_model.evaluate(X_test_nn, y_test_nn)\n\"\"\"\n<a id=\"7.8.3\"><\/a>\n**Loss Curve**\n\"\"\"\nplt.figure(figsize=(8,6))\nloss_train = history.history['loss']\nloss_val = history.history['val_loss']\nepochs = range(1,18)\nplt.plot(epochs, loss_train, 'g', label='Training loss')\nplt.plot(epochs, loss_val, 'b', label='validation loss')\nplt.title('Training and Validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.xticks(np.arange(1,20))\nplt.legend()\nplt.show()\ny_predicted = nn_model.predict(X_test_nn)\ny_predicted\ny_predicted_labels = [np.argmax(i) for i in y_predicted]\ny_predicted_labels\ny_predicted_labels = np.array(y_predicted_labels)\ny_predicted_labels.shape\nX_train_nn, X_test_nn, y_train_nn, y_test_nn = train_test_split(X_nn,y_nn, test_size=0.25, random_state=100)\ny_test_nn.shape\ncm = tf.math.confusion_matrix(labels=y_test_nn, predictions=y_predicted_labels)\ncm\n\"\"\"\n<a id=\"7.8.4\"><\/a>\n**Confusion Matrix**\n\"\"\"\nplt.figure(figsize=(9,7))\nsns.heatmap(cm, annot=True)\n\"\"\"\n<a id=\"7.8.5\"><\/a>\n**Classification Report**\n\"\"\"\nprint(classification_report(y_test_nn, y_predicted_labels))","meta":"{'source': 'AI4Code', 'id': 'f540ffc2a6a80e'}"}
{"id":"97671","text":"# 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\n\"\"\"\n# Segundo trabalho do modulo de deep learning - Universidade do Estado do Amazonas\n## A bug's life .\n## Equipe:\n- Felipe Brasil\n- Franklin Perseu de Lima e Lima\n\"\"\"\n\"\"\"\n# Chucrute recongnition CNN\n\"\"\"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nimport tensorflow as keras\nfrom keras_preprocessing.image import ImageDataGenerator\nimport os\nfrom tensorflow.keras.optimizers import Adam, RMSprop\npath = '..\/input\/insects-recognition'\nbatch_size = 100\n\ntrain_datagen = ImageDataGenerator(rescale=1.\/255, validation_split=0.2,\n                                   rotation_range=40, horizontal_flip=True,\n                                   fill_mode='nearest')\n\ntrain_gen = train_datagen.flow_from_directory(path, target_size=(150,150),\n                    class_mode='categorical', batch_size=batch_size, \n                                              subset='training')\n\nval_gen = train_datagen.flow_from_directory(path, target_size=(150,150),\n                class_mode='categorical', batch_size=batch_size,\n                                            subset='validation')\nlabels = ['Butterfly', 'Dragonfly', 'Grasshopper', 'Ladybird', 'Mosquito']\nn_classes = len(labels)\nfor i in range(15):\n    if i%5==0:\n        fig, ax = plt.subplots(ncols=5, figsize=(15,15))\n    img, lbl = train_gen.next()\n    ax[i%5].imshow(img[2])\n    ax[i%5].set_title(labels[np.argmax(lbl[2])])\n    ax[i%5].grid(False)\n    ax[i%5].axis(False)\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu',\n                input_shape=(150, 150, 3), padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n    \n    \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu',\n                input_shape=(150, 150, 3), padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n    \n    tf.keras.layers.Conv2D(256, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n    \n    tf.keras.layers.Conv2D(512, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n        \n    tf.keras.layers.Conv2D(512, (3,3), activation='relu', padding='same'),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.3),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(1024, activation='relu'),\n    tf.keras.layers.Dropout(0.5),\n\n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.Dropout(0.5),\n    \n    tf.keras.layers.Dense(n_classes, activation='softmax')     \n])\n\n\"\"\"\n#Original - \nmodel.compile(loss = 'categorical_crossentropy', optimizer='adam', \n              metrics=['accuracy'])\n\"\"\"\n#secundario\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=RMSprop(),\n              metrics=['accuracy'])\nmodel.summary()\nsteps, val_steps = train_gen.n\/batch_size, val_gen.n\/batch_size\nnum_epochs = 100\n#Guardar o melhor modelo  \ncallbacks_list = [\n    tf.keras.callbacks.ModelCheckpoint(\n        filepath='model.h5',\n        monitor='val_loss', save_best_only=True, verbose=1),\n    tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10,verbose=1)\n]\nhistory = model.fit(train_gen, \n                    validation_data=val_gen,\n                    epochs=num_epochs,\n                    steps_per_epoch=steps, \n                    validation_steps=val_steps,\n                   callbacks = callbacks_list\n                   )\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\n\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=4)\nplt.grid(axis='both')\n\nplt.show() \n# Using the validation dataset\nscore = model.evaluate_generator(val_gen)\nprint('Val loss:', score[0])\nprint('Val accuracy:', score[1])\n\"\"\"\n# Optimizer adam \n* Val loss: 0.611824095249176\n* Val accuracy: 0.7894144058227539\n\n# Optmizer RMSprop\n* Val loss: 0.7564347982406616\n* Val accuracy: 0.7331081032752991\n\n\"\"\"\n\"\"\"\n# Vendo alguns reports\n# Usando sklearn\n\n# Classificando toda base de teste\ny_pred = model.predict_classes(x_val)\n# voltando pro formato de classes\nimport numpy as np\ny_test_c = np.argmax(y_val, axis=1)\n\nprint('Confusion Matrix')\nprint(confusion_matrix(y_test_c, y_pred))\nprint('Classification Report')\ntarget_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nprint(classification_report(y_test_c, y_pred, target_names=target_names))\"\"\"\n\"\"\"\n# Flik's recognition - transfer learning\n\"\"\"\n\"\"\"\nLibary\n\"\"\"\n# General Libs\nfrom tensorflow import keras\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing import image\n#from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3,preprocess_input\nfrom tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input\nfrom tensorflow.keras.layers import Dense, Flatten,Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam, RMSprop\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n'''\ntrain_datagen = ImageDataGenerator(rescale=1.\/255, validation_split=0.4,\n                                   rotation_range=40, horizontal_flip=True,\n                                   fill_mode='nearest')\n\ntrain_gen = train_datagen.flow_from_directory(path, target_size=(150,150),\n                    class_mode='categorical', batch_size=batch_size, \n                                              subset='training')\n\nval_gen = train_datagen.flow_from_directory(path, target_size=(150,150),\n                class_mode='categorical', batch_size=batch_size,\n                                            subset='validation')\n\n\n\n# Alguns par\u00e2metros para leitura do dataset\nim_shape = (299,299)\n\nTRAINING_DIR = '..\/input\/amazon-fruits-small\/ds_frutas_am\/train'\nTEST_DIR = '..\/input\/amazon-fruits-small\/ds_frutas_am\/test'\n\nseed = 10\n\n#BATCH_SIZE = 16\n'''\n\npath = '..\/input\/insects-recognition'\nteste = '..\/input\/imgteste'\n\nBATCH_SIZE = 100\nim_shape = (150,150)\nseed = 10\n#Using keras ImageGenerator and flow_from_directoty\n\n# Image dataset without augmentation\n#data_generator = ImageDataGenerator(preprocessing_function=preprocess_input, validation_split=0.2)\n# With augmentation\ndata_generator = ImageDataGenerator(\n        validation_split=0.2,\n        rotation_range=40,\n        #width_shift_range=0.2,\n        #height_shift_range=0.2,\n        preprocessing_function=preprocess_input,\n        #shear_range=0.2,\n        #zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest')\nval_data_generator = ImageDataGenerator(preprocessing_function=preprocess_input,validation_split=0.2)\n# Generator para parte train\ntrain_generator = data_generator.flow_from_directory(path, target_size=im_shape, shuffle=True, seed=seed,\n                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset=\"training\")\n# Generator para parte valida\u00e7\u00e3o\nvalidation_generator = val_data_generator.flow_from_directory(path, target_size=im_shape, shuffle=False, seed=seed,\n                                                     class_mode='categorical', batch_size=BATCH_SIZE, subset=\"validation\")\n\n# Generator para dataset de teste verificar aqui n\u00e9 \ntest_generator = ImageDataGenerator(preprocessing_function=preprocess_input)\ntest_generator = test_generator.flow_from_directory(teste, target_size=im_shape, shuffle=False, seed=seed,\n                                                     class_mode='categorical', batch_size=BATCH_SIZE)\n\nnb_train_samples = train_generator.samples\nnb_validation_samples = validation_generator.samples\nnb_test_samples = test_generator.samples\nclasses = list(train_generator.class_indices.keys())\nprint('Classes: '+str(classes))\nnum_classes  = len(classes)\nnb_test_samples\n# Visualizando alguns exemplos do dataset por meio do Generator criado\nplt.figure(figsize=(15,15))\nfor i in range(9):\n    #gera subfigures\n    plt.subplot(330 + 1 + i)\n    batch = train_generator.next()[0]*255\n    image = batch[0].astype('uint8')\n    plt.imshow(image)\nplt.show()\n\"\"\"\n# Transfer Learning from a Deep Model\n\"\"\"\n\"\"\"\nrede original 300 100 300\n\"\"\"\n#base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(im_shape[0], im_shape[1], 3))\nbase_model = InceptionResNetV2(weights='imagenet', include_top=False, input_shape=(im_shape[0], im_shape[1], 3))\n\nx = base_model.output\nx = Flatten()(x)\nx = Dense(300, activation='relu')(x)\n#x = Dropout(.3)(x)\n#x = Dropout(0.3)(x)\n#x = Dense(25, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(100, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(200, activation='relu')(x)\npredictions = Dense(num_classes, activation='softmax', kernel_initializer='random_uniform')(x)\n\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n# Freezing pretrained layers\nfor layer in base_model.layers:\n    layer.trainable=False\n    \n#original\noptimizer = Adam()\nmodel.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['accuracy'])\n\n#secundario\n\"\"\"model.compile(loss='categorical_crossentropy',\n              optimizer=RMSprop(),\n              metrics=['accuracy'])\"\"\"\nepochs = 100\n\n# Saving the best model\ncallbacks_list = [\n    keras.callbacks.ModelCheckpoint(\n        filepath='modelBugsLife.h5',\n        monitor='val_loss', save_best_only=True, verbose=1),\n    keras.callbacks.EarlyStopping(monitor='val_loss',patience=20,verbose=1)\n    # patience=15,\n]\n\nhistory = model.fit(\n        train_generator,\n        steps_per_epoch=nb_train_samples \/\/ BATCH_SIZE,\n        epochs=epochs,\n        callbacks = callbacks_list,\n        validation_data=validation_generator,\n        verbose = 1,\n        validation_steps=nb_validation_samples \/\/ BATCH_SIZE)\n#Vamos ver como foi o treino?\nimport matplotlib.pyplot as plt\n\nhistory_dict = history.history\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\n\nepochs_x = range(1, len(loss_values) + 1)\nplt.figure(figsize=(10,10))\nplt.subplot(2,1,1)\nplt.plot(epochs_x, loss_values, 'bo', label='Training loss')\nplt.plot(epochs_x, val_loss_values, 'b', label='Validation loss')\nplt.title('Training and validation Loss and Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n#plt.legend()\nplt.subplot(2,1,2)\nacc_values = history_dict['accuracy']\nval_acc_values = history_dict['val_accuracy']\nplt.plot(epochs_x, acc_values, 'bo', label='Training acc')\nplt.plot(epochs_x, val_acc_values, 'b', label='Validation acc')\n#plt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Acc')\nplt.legend()\nplt.show()\nfrom tensorflow.keras.models import load_model\n# Load the best saved model\nmodel = load_model('modelBugsLife.h5')\n# Using the validation dataset\nscore = model.evaluate_generator(validation_generator)\nprint('Val loss:', score[0])\nprint('Val accuracy:', score[1])\n# Using the test dataset\n# score = model.evaluate_generator(test_generator)\n# print('Test loss:', score[0])\n# print('Test accuracy:', score[1])\nimport itertools\n\n#Plot the confusion matrix. Set Normalize = True\/False\ndef plot_confusion_matrix(cm, classes, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.figure(figsize=(10,10))\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n    if normalize:\n        cm = cm.astype('float') \/ cm.sum(axis=1)[:, np.newaxis]\n        cm = np.around(cm, decimals=2)\n        cm[np.isnan(cm)] = 0.0\n    thresh = cm.max() \/ 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n# Some reports\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport numpy as np\n\n#Confution Matrix and Classification Report\nY_pred = model.predict_generator(test_generator)#, nb_test_samples \/\/ BATCH_SIZE, workers=1)\ny_pred = np.argmax(Y_pred, axis=1)\ntarget_names = classes\n\n#Confution Matrix\ncm = confusion_matrix(test_generator.classes, y_pred)\nplot_confusion_matrix(cm, target_names, normalize=False, title='Confusion Matrix')\nprint('Classification Report')\nprint(classification_report(test_generator.classes, y_pred, target_names=target_names))","meta":"{'source': 'AI4Code', 'id': 'b34eb95b2c8517'}"}
{"id":"54257","text":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os\nfrom tqdm import tqdm\n\nimport cv2\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\ntrain = pd.read_csv(\"..\/input\/shopee-code-league-2020-product-detection\/train.csv\")\nprint(train.shape)\ntrain.head(10)\n\"\"\"\n## Observations\n\n1. The labels are not shuffled\n2. The feature column contains the filename of the images\n\"\"\"\n\"\"\"\n# Take a look at the distribution of categories\n\"\"\"\nplt.figure(figsize=(10,10))\nplt.title(\"Distribution of labels for training data\")\nsns.countplot(train['category'])\n\"\"\"\n## Observations\n1. There are a total of 42 categories\n2. Category 33 is significantly lesser than the rest (approx 570), resulting in the model learning disproportionately for that category\n\n## Solution\n* We can resample the training data to contain ~570 images from each category.\n* Alternatively, we can augment images to increase the amount of data\n\n\"\"\"\n\"\"\"\n# Modifying our training dataset\n\n* In order to reduce computational storage and time taken, we will only be using the first 10 categories of which contains 1500 image each\n* Shuffle the training data so that the examples fed into the model will create an 'independent' change\n\"\"\"\nnew_train=pd.DataFrame()\n\nCATEGORIES=[n for n in range(10)]\n\nfor cat in CATEGORIES:\n    new_train=new_train.append(train[train['category']==cat][:1600])\n\ndel train\n\ntrain=new_train.sample(frac=1)\ntrain\n\"\"\"\n## Visualize the modified training dataset\n\"\"\"\nplt.figure(figsize=(10,10))\nsns.countplot(train['category'])\n\"\"\"\n# Reading the training images\n\n* Convert category labels from int to strings defined from 00 to 41.\n* Resize image resolution (trail and error)\n\"\"\"\nresized_img_dim=150\n\ndef read_img(train,resized_img_dim):\n    \n    DATADIR='..\/input\/shopee-code-league-2020-product-detection\/resized\/train'\n    X=[]\n\n    for fname,cat in tqdm(train.values):\n        if(cat<10):\n            cat='0'+str(cat)\n        else:\n            cat=str(cat)\n\n        path=os.path.join(DATADIR,cat,fname)\n\n        try:\n            img=cv2.imread(path).astype('float32')\n            img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n            img=cv2.resize(img, (resized_img_dim,resized_img_dim))\n        except:\n            pass\n        X.append(img)\n    return X\n\nX=read_img(train,resized_img_dim)\n\"\"\"\n# Setting up training labels\n* One Hot Encode labels\n\"\"\"\nfrom sklearn.preprocessing import OneHotEncoder\n\ny=train['category']\n\nohe=OneHotEncoder()\ny=ohe.fit_transform(y.values.reshape(-1,1)).astype('float32')\ny=y.todense()\n\"\"\"\n# Splitting training data\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nX=np.array(X).reshape(-1,resized_img_dim,resized_img_dim,3)\n\nxtrain,xtest,ytrain,ytest=train_test_split(X,y,test_size=0.2)\ndel X\ndel y\ndel train\n\"\"\"\n# Augmenting image\n\n* Provides a wider range of image for the model to learn from \n\"\"\"\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1.\/255, zoom_range=0.3, rotation_range=30,\n                                   width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, \n                                   horizontal_flip=True, fill_mode='constant')\n\nval_datagen = ImageDataGenerator(rescale=1.\/255)\n\ntrain_generator = train_datagen.flow(xtrain, ytrain, batch_size=30)\nval_generator = val_datagen.flow(xtest, ytest, batch_size=20)\n\"\"\"\n## Examples of augmented images\n\"\"\"\nplt.figure(figsize=(10,10))\nfor xbatch,ybatch in train_generator:\n    for i in range(1,10):\n        plt.subplot(3,3,i)\n        plt.axis('off')\n        plt.imshow(((xbatch[i]*255).astype('uint8')))\n    break\n\"\"\"\n# Training and Evaluation\n\n1. Using a simple self defined CNN\n2. Using a pretrained model (VGG)\n\n\n* Evaluation by visualizing training accuracy\/loss vs validation accuracy\/loss\n\"\"\"\nimport tensorflow as tf\nimport keras\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input, BatchNormalization\n\nfrom keras.applications.vgg19 import VGG19\n\ninput_shape_=(resized_img_dim,resized_img_dim,3)\n\nvgg=VGG19(include_top=False, input_shape=input_shape_)\n\noutput = vgg.layers[-1].output\noutput = Flatten()(output)\n\nvgg_model=Model(vgg.input,output)\n\n\nprint(vgg_model.summary())\npretrained_model = Sequential()\n\npretrained_model.add(vgg_model)\n\npretrained_model.add(Dense(256,activation='relu', input_dim=input_shape_))\npretrained_model.add(Dropout(0.4))\n\npretrained_model.add(Dense(10, activation='softmax'))\n\npretrained_model.compile(loss='categorical_crossentropy',\n              optimizer=keras.optimizers.RMSprop(lr=2e-5),\n              metrics=['accuracy'])\n\nmodel_callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0)]\n\nhistory = pretrained_model.fit_generator(train_generator, steps_per_epoch=100, epochs=100,\n                              validation_data=val_generator, validation_steps=50, \n                              verbose=1, callbacks=model_callbacks)  \n#Accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title(\"Training accuracy vs Validation accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.show()\n\n#Loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title(\"Training loss vs Validation loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.show()\nscore=pretrained_model.evaluate(xtest,ytest)","meta":"{'source': 'AI4Code', 'id': '63df972dc34ff3'}"}
{"id":"125533","text":"\"\"\"\n# \u5bf9\u4e8c\u624b\u8f66\u4ef7\u683c\u8fdb\u884c\u56de\u5f52\u9884\u6d4b\n\"\"\"\n\"\"\"\n## Step1: \u5bfc\u5165\u76f8\u5173\u6a21\u5757\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nimport seaborn as sns\n\"\"\"\n## Step2: \u5bfc\u5165\u6570\u636e\u5e76\u5bf9\u6570\u636e\u505a\u7b80\u5355\u63a2\u7d22\n\"\"\"\ndf = pd.read_csv('..\/input\/craigslist-carstrucks-data\/vehicles.csv', index_col=0)\nprint(\"data shape:\")\nprint(df.shape)\nprint(\"columns name:\")\nprint(list(df.columns))\n\"\"\"\n## Step 3: \u6570\u636e\u6e05\u6d17\n\"\"\"\n\"\"\"\n### 3.1 \u5220\u9664\u6682\u65f6\u65e0\u6cd5\u5904\u7406\u7684\u5217\u6570\u636e\uff0c\u4f8b\u5982url\u5730\u5740\uff0c\u8f66\u8f86\u56fe\u50cf\uff0c\u8f66\u8f86\u63cf\u8ff0\u7b49\n\"\"\"\nuseless_columns = ['url', 'region_url', 'VIN', 'image_url', 'description', 'state']\ndf.drop(useless_columns, axis=1, inplace=True)\nprint(\"data shape:\")\nprint(df.shape)\nprint(\"columns name:\")\nprint(list(df.columns))\n\"\"\"\n### 3.2 \u67e5\u770b\u6570\u636e\u7f3a\u5931\u60c5\u51b5\uff0c\u5bf9\u5173\u952e\u6570\u636e\u7f3a\u5931\u7684\u6837\u672c\u8fdb\u884c\u5254\u9664\n\"\"\"\ndf.isnull().any(axis=0)\ntemp = df.dropna(axis=0, subset=['year', 'manufacturer'])\nprint(\"\u5171\u5220\u9664\", df.shape[0]-temp.shape[0], \"\u884c\")\ndf = temp\n\"\"\"\n### 3.3 \u5bf9\u65e0\u6548\u6570\u636e>6\u4e2a\u7684\u8fdb\u884c\u5220\u9664\n\"\"\"\ndef count_invalid_num(series):\n    \"\"\"\n    \u67e5\u627e\u65e0\u6548\u6570\u636e\uff0c\u8fd4\u56de\u65e0\u6548\u6570\u636e\u4e2a\u6570\n    \"\"\"\n    invalid_num = series.isnull().sum()\n    if series.price <= 0:\n        invalid_num += 1\n    if series.odometer < 0:\n        invalid_num += 1\n    return invalid_num\n\ndf['invalid_num'] = df.apply(count_invalid_num, axis=1)\ndf.head()\nori_rows = df.shape[0]\ndf.drop(df[df.invalid_num > 6].index, inplace=True)\nafter_rows = df.shape[0]\nprint(\"\u5171\u5220\u9664\", ori_rows - after_rows, \"\u884c\")\n\"\"\"\n### 3.4 \u5bf9price=0\u7684\u884c\u8fdb\u884c\u5220\u9664\n\"\"\"\nori_rows = df.shape[0]\ndf.drop(df[df['price'] == 0].index, inplace = True) \nafter_rows = df.shape[0]\nprint(\"\u5171\u5220\u9664\", ori_rows - after_rows, \"\u884c\")\nprint(\"\u76ee\u524d\u6570\u636e\u5f62\u72b6\u4e3a\uff1a\", df.shape)\n\"\"\"\n## Step4: \u6570\u636e\u63d2\u8865\n\"\"\"\n\"\"\"\n### \u51c6\u5907\u63d2\u8865\u51fd\u6570\n\"\"\"\ndef fill_by_key(data:pd.DataFrame, tar_col:str, type:str, key:str, fill=False, default='GT'):\n    if type == 'median':\n        tmp = dict(data.groupby(key)[tar_col].median())\n    if type == 'mode':\n        tmp = dict(df.groupby(key)[tar_col].agg(lambda x: pd.Series.mode(x)))\n        for (k, v) in tmp.items():\n            if str(v).find('[') != -1:\n                print(k, v, '->', default)\n                tmp[k] = default\n    if type == 'mean':\n        tmp = dict(df.groupby(key)[tar_col].mean())\n    if fill:\n        df[tar_col] = df[tar_col].fillna(df[key].apply(lambda x: tmp.get(x)))\n        df.drop(df[df[tar_col].isna()].index, inplace = True)\n    else:\n        return tmp\n    \ndef fill_helper(data:pd.DataFrame, diction:dict, tar_col:str, key:str):\n    df[tar_col] = df[tar_col].fillna(df[key].apply(lambda x: diction.get(x)))\n    df.drop(df[df[tar_col].isna()].index, inplace = True)\n\"\"\"\n### 4.1 \u5bf9\u884c\u9a76\u516c\u91cc\u6570\uff08odometer\uff09\u8fdb\u884c\u63d2\u8865\n\"\"\"\nfill_by_key(df, 'odometer', 'median', 'year', True, 1000)  # \u6839\u636eyear\u7684\u4e2d\u4f4d\u6570\u8fdb\u884c\u63d2\u8865\nprint(\"\u76ee\u524d\u6570\u636e\u5f62\u72b6\u4e3a\uff1a\", df.shape)\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.2 \u5bf9\u8f66\u578b\uff08model\uff09\u7f3a\u5931\u503c\u8fdb\u884c\u63d2\u8865\n\"\"\"\nfill_ = fill_by_key(df, 'model', 'mode', 'manufacturer')\nfill_helper(df, fill_, 'model', 'manufacturer')\ndf[df.manufacturer=='hennessey'].model\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.3 \u5bf9\u8f66\u51b5\uff08condition\uff09\u8fdb\u884c\u7f3a\u5931\u503c\u63d2\u8865\n\"\"\"\ndf.condition.unique()\ndef condition2int(condition):\n    condition_dict = {'salvage':0, 'fair':1, 'good':2, 'excellent':3, 'like new':4, 'new':5}\n    try:\n        return condition_dict[condition]\n    except:\n        return np.nan\n\ndf['condition'] = df['condition'].apply(condition2int)\nfill_by_key(df, 'condition', 'median', 'year', True, 2)\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.4 \u5bf9\u8f66\u8f6e\uff08cylinders\uff09\u8fdb\u884c\u7f3a\u5931\u503c\u63d2\u8865\n\"\"\"\ndf.cylinders.unique()\ndef cylinder2int(cylinders):\n    try:\n        return int(cylinders[0])\n    except:\n        return np.nan\ndf['cylinders'] = df['cylinders'].apply(cylinder2int)\nfill_ = fill_by_key(df, 'cylinders', 'median', 'model', default=4)\nfill_helper(df, fill_, 'cylinders', 'model')\n\"\"\"\n### 4.5 \u5bf9\u71c3\u6599\u5f62\u5f0f\uff08fuel\uff09\u8fdb\u884c\u63d2\u8865\n\"\"\"\nfill_mode = fill_by_key(df, 'fuel', 'mode', 'model', default='gas')\nfill_helper(df, fill_mode, 'fuel', 'model')\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.6 \u5bf9title_status\u8fdb\u884c\u63d2\u8865\n\"\"\"\ndf.title_status.unique()\nfill_ = fill_by_key(df, 'title_status', 'mode', 'model', default='clean')\nfill_helper(df, fill_, 'title_status', 'model')\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.7 \u5bf9transmission\u3001drive\u3001size\u3001paint_color\u8fdb\u884c\u63d2\u8865\n\"\"\"\ndf.transmission.unique()\nfill_ = fill_by_key(df, 'transmission', 'mode', 'model', default='automatic')\nfill_helper(df, fill_, 'transmission', 'model')\ndf.isnull().any(axis=0)\ndf.drive.unique()\nfill_ = fill_by_key(df, 'drive', 'mode', 'model', default='fwd')\nfill_helper(df, fill_, 'drive', 'model')\ndf.isnull().any(axis=0)\ndf.paint_color.unique()\nfill_ = fill_by_key(df, 'paint_color', 'mode', 'model', default='white')\nfill_helper(df, fill_, 'paint_color', 'model')\ndf.isnull().any(axis=0)\ndf['size'].unique()\nfill_ = fill_by_key(df, 'size', 'mode', 'model', default='mid-size')\nfill_helper(df, fill_, 'size', 'model')\ndf.isnull().any(axis=0)\ndf['type'].unique()\nfill_ = fill_by_key(df, 'type', 'mode', 'model', default='other')\nfill_helper(df, fill_, 'type', 'model')\ndf.isnull().any(axis=0)\n\"\"\"\n### 4.8 \u5bf9\u7ecf\u7eac\u5ea6\uff08lat long\uff09\u8fdb\u884c\u5747\u503c\u63d2\u8865\n\"\"\"\ndf.long.fillna(df.long.mean(), inplace=True)\ndf.lat.fillna(df.lat.mean(), inplace=True)\ndf.isnull().any(axis=0)\n\"\"\"\n## Step 5: \u5efa\u7acb\u56de\u5f52\u6a21\u578b\n\"\"\"\ndf.info()\ndf.condition = df.condition.apply(lambda x: int(x))\ndf.condition.unique()\ndf.info()\ndf.cylinders = df.cylinders.apply(lambda x: int(x))\ndf.cylinders.unique()\n# !pip install catboost \u5982\u679c\u6ca1\u6709\u8fd9\u4e2a\u5305\uff0c\u5219\u5b89\u88c5\nfrom sklearn.model_selection import train_test_split\nfrom catboost import CatBoostRegressor\nX_train, X_val, y_train, y_val = train_test_split(df.loc[:, [x for x in list(df.columns) if x not in ['price', 'id']]], df.loc[:, 'price'], test_size=0.2 , random_state=2021)\nprint(X_train.shape, X_val.shape, y_train.shape, y_val.shape)\nX_train.info()\ncategorical_features_indices = np.where(X_train.dtypes != np.float)[0]\nmodel = CatBoostRegressor(iterations=1000, depth=5, cat_features=categorical_features_indices,learning_rate=0.05, logging_level='Verbose')\nmodel.fit(X_train, y_train, plot=True)\n\"\"\"\n## Step 6: \u9884\u6d4b\n\"\"\"\ny_hat = model.predict(X_val)\nimport plotly.graph_objects as go\nimport numpy as np\nN = 50\nx = np.arange(0,N)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=np.array(y_hat[:N]),mode='lines+markers',name='y_hat'))\nfig.add_trace(go.Scatter(x=x, y=np.array(y_val[:N]),mode='lines+markers',name='y_val'))\nfig.show()\n\"\"\"\n### \u53d1\u73b0\u4ef7\u683c\u9884\u6d4b\u51fa\u8d1f\u6570\uff0c\u4fee\u6539\u6570\u636e\uff0c\u8fd9\u91cc\u53ef\u4ee5\u4f53\u73b0\u51fa\u91ce\u503c\u6570\u636e\u5bf9\u6a21\u578b\u7684\u5f71\u54cd\n\"\"\"\ny_train_log, y_val_log = np.log(y_train), np.log(y_val)\nmodel.fit(X_train, y_train_log, plot=True)\ny_hat_log = model.predict(X_val)\ny_hat = np.exp(y_hat_log)\nN = 50\nx = np.arange(0,N)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=np.array(y_hat[:N]),mode='lines+markers',name='y_hat'))\nfig.add_trace(go.Scatter(x=x, y=np.array(y_val[:N]),mode='lines+markers',name='y_val'))\nfig.show()\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nrmse_val = np.sqrt(mean_squared_error(y_val_log, y_hat_log))\nprint(\"RMSE of Validation is: \", rmse_val)","meta":"{'source': 'AI4Code', 'id': 'e6e1e566e22b4b'}"}
{"id":"108117","text":"\"\"\"\n\u300e\u8cea\u554f\u300d\n\u73fe\u5728Simple Baseline\u306e\u7406\u89e3\u3092\u6df1\u3081\u3066\u3044\u307e\u3059\u3002\n\n\u9014\u4e2d\u306b\u3067\u3066\u304d\u307e\u3057\u305f\n\ndef aired_datetime(air):  \n\u7701\u7565\n\n\u306e\u4e2d\u8eab\u304c\u81ea\u529b\u3067\u89e3\u8aad\u3067\u304d\u305a\u56f0\u3063\u3066\u3044\u307e\u3059\u3002\n\u3069\u306a\u305f\u304b\u6559\u3048\u3066\u9802\u3051\u306a\u3044\u3067\u3057\u3087\u3046\u304b\uff1f\n\"\"\"\n\"\"\"\n\u96e3\u3057\u3044\u3068\u601d\u3044\u307e\u3059\uff0e\u7406\u89e3\u306e\u624b\u52a9\u3051\u304c\u3067\u304d\u308c\u3070\u3068\u601d\u3044\u307e\u3059\uff0e\n\"\"\"\nimport numpy as np\nimport pandas as pd\n# \u30e1\u30a4\u30f3\u30c7\u30fc\u30bf\u3092\u8aad\u307f\u8fbc\u3093\u3067\u898b\u307e\u3059\nX_train = pd.read_csv('\/kaggle\/input\/data-science-summer2-osaka\/train.csv')\n#\u307e\u305a\u3053\u3053\u304c\u547c\u3073\u51fa\u3055\u308c\u308b\u306e\u306f\u3042\u3068\u306eapply\u306e\u90e8\u5206\u3067\u547c\u3073\u51fa\u3055\u308c\u308b\ndef aired_datetime(air):\n    try:\n        d = pd.to_datetime('2021-08-01') - pd.to_datetime(air.split(' to ')[0])\n        d \/= pd.Timedelta('1d')\n    except:\n        d = -9999\n    return d\nX_train['Aired'] = X_train['Aired'].apply(aired_datetime)\n\"\"\"\n#### \u7591\u554f1\u3000air\u306b\u306a\u306b\u304c\u5165\u3063\u3066\u3044\u308b\u306e\u3060\u308d\u3046\u304b\n\u30fbprint(air)\u3067\u307f\u308b\n\"\"\"\n# \u30e1\u30a4\u30f3\u30c7\u30fc\u30bf\u3092\u8aad\u307f\u8fbc\u3093\u3067\u898b\u307e\u3059\nX_train = pd.read_csv('\/kaggle\/input\/data-science-summer2-osaka\/train.csv')\ndef aired_datetime(air):\n    print(air)#\u8ffd\u8a18\n    print(\"######\")\n    try:\n        d = pd.to_datetime('2021-08-01') - pd.to_datetime(air.split(' to ')[0])\n        d \/= pd.Timedelta('1d')\n    except:\n        d = -9999\n    return d\n#\u7c21\u7565\u5316\u306e\u305f\u3081\u884c\u6570\u3092\u6e1b\u3089\u3059\uff0e\u2192\u884c\u6570\u3092\u6e1b\u3089\u3057\u3066\u3082\u57fa\u672c\u540c\u3058\u51e6\u7406\u3092\u5404\u884c\u306b\u3059\u308b\u306e\u3067\u554f\u984c\u306a\u3044 20\u884c\u5206\u3067\u3044\u308d\u3044\u308d\u307f\u308b\nX_train = X_train[:10]\nX_train[\"Aired\"]\nX_train['Aired'] = X_train['Aired'].apply(aired_datetime)\n#apply\u95a2\u6570\u3068\u306f\u3069\u3046\u3084\u3089\u5404\u884c\u3092\u9806\u756a\u306b\u4ee3\u5165\u3057\u3066\u304f\u308c\u308b\u95a2\u6570\u306e\u3088\u3046\u3060\uff0c\uff08\u3053\u3053\u306f\u8abf\u3079\u308b\u3068\u3067\u3066\u304f\u308b\uff09\uff08\u4e26\u5217\u51e6\u7406\u3067\u306f\u306a\u3044\u306f\u305a\uff0e\uff0e\uff0e\uff09\n#\u307e\u305f\u4e0a\u8a18\u306e\u51e6\u7406\u3067aired_datetime\u95a2\u6570\u304c\u5b9f\u884c\u3055\u308c\u3066\u3044\u308b\u3053\u3068\u304c\u308f\u304b\u308b\uff0e\n#\u3069\u3046\u3084\u3089\u4e00\u884c\u305a\u3064X_train['Aired']\u306e\u30c7\u30fc\u30bf\u304c\u5165\u3063\u3066\u3044\u308b\u6a21\u69d8\n\"\"\"\n#### \u7591\u554f2\u3000\uff0eAired\u306e\u306a\u306b\u304c\u5909\u5316\u3057\u305f\u304b\u308f\u304b\u3089\u306a\u3044\n\u30fb\u4e00\u65e6\u30b4\u30fc\u30eb\u3092\u307f\u308b\n\n\u30fb\u5217\u540d\u3092\u5909\u66f4\u3057\u3066Aired\u3092\u66f4\u65b0\u3057\u306a\u3044\uff08\u7834\u58ca\u7684\u306a\u5909\u6570\u5909\u66f4\u3092\u3057\u306a\u3044\uff09\n\"\"\"\n# \u30e1\u30a4\u30f3\u30c7\u30fc\u30bf\u3092\u8aad\u307f\u8fbc\u3093\u3067\u898b\u307e\u3059\nX_train = pd.read_csv('\/kaggle\/input\/data-science-summer2-osaka\/train.csv')\ndef aired_datetime(air):\n    try:\n        d = pd.to_datetime('2021-08-01') - pd.to_datetime(air.split(' to ')[0])\n        d \/= pd.Timedelta('1d')\n    except:\n        d = -9999\n    return d\nX_train['Aired_fix'] = X_train['Aired'].apply(aired_datetime)#\u5217\u540d\u5909\u66f4\n#\u307f\u304f\u3089\u3079\u3066\u307f\u308b\uff0e\nX_train['Aired_fix']\n#\u307f\u304f\u3089\u3079\u3066\u307f\u308b\uff0e\nX_train['Aired']\n#\u307b\u3046\u307b\u3046\u306a\u306b\u3084\u30891998\u5e744\u67083\u65e5~1999\u5e74\uff14\u670824\u304c8521.0\u306b\u5909\u308f\u3063\u3066\u3044\u308b\u3088\u3046\u3060\n\n#\u5c71\u672c\u3055\u3093\u30b3\u30e1\u30f3\u30c8\n## Aired\u306b\u3064\u3044\u3066\u306f\u3001\u3053\u3053\u3067\u306f\u671f\u9593\u306e\u59cb\u307e\u308a\uff1f\u3060\u3051\u53d6\u308a\u51fa\u3057\u3066\u305d\u308c\u304c\u3069\u308c\u3060\u3051\u4ee5\u524d\u304b\u3092\u53d6\u308a\u51fa\u3057\u3066\u307f\u307e\u3059\u3002\n\n#\u307f\u305f\u3044\u3067\u3059\uff0c\u306a\u306e\u3067\uff0c2021-08-01\u306e\u4f55\u65e5\u524d\u306b\u653e\u9001\u304c\u59cb\u307e\u3063\u305f\u304b\u3092\u793a\u3059\u306e\u304c8521\u306e\u3088\u3046\n8521\/365\n#23\u5e74\u524d\uff0c\u3060\u3044\u305f\u3044\u3042\u3063\u3066\u305d\u3046\uff0e\u51e6\u7406\u306e\u524d\u5f8c\u3060\u3051\u308f\u304b\u3063\u305f\uff0e\n#\u3042\u3068\u306f\u7d30\u304b\u3044\u30b9\u30c6\u30c3\u30d7\u3092\u898b\u3066\u3044\u3053\u3046\u30fb1998\u5e744\u67083\u65e5~1999\u5e74\uff14\u670824\u304c8521.0\u306b\u5909\u3048\u308b\u7d30\u3044\u30b9\u30c6\u30c3\u30d7\u3092\u307f\u308c\u3070\u3088\u3055\u305d\u3046\u3060\uff0e\n#notebook\u306f\u3053\u3053\u307e\u3067\u306b\u3057\u307e\u3059\uff0e\u4e0d\u660e\u70b9\u3042\u308c\u3070\u8ffd\u8a18\u3057\u307e\u3059\u306e\u3067\uff0c\u7533\u3057\u4ed8\u3051\u304f\u3060\u3055\u3044\uff0eyone-moto","meta":"{'source': 'AI4Code', 'id': 'c6bc891c712615'}"}
{"id":"60616","text":"\"\"\"\n<center><img src ='https:\/\/medicineforthemindblog.files.wordpress.com\/2017\/08\/brain-pic.jpg' width = '600px'><\/center>\n<center><img src='https:\/\/i.imgur.com\/SZQXq1q.png' width = '600px'><\/center>\n\"\"\"\n\"\"\"\n<p style='font-size:17px;font-weight:bold'>A <span style='color:#f54025'>stroke<\/span> occurs when the blood supply to part of your brain is interrupted or reduced, preventing brain tissue from getting oxygen and nutrients. Brain cells begin to die in minutes. <span style='color:#f54025'>Stroke<\/span> has already reached epidemic proportions. Globally 1 in 4 adults over the age of 25 will have a <span style='color:#f54025'>stroke<\/span> in their lifetime. 13.7 million people worldwide will have their first <span style='color:#f54025'>stroke<\/span> this year and five and a half million will die as a result.<\/p>\n\"\"\"\n\"\"\"\n<p style = 'font-size : 17px;font-style: italic'>\n    <span style ='font-size:19px;font-weight:bold;color:#9ACD32'>Attribute Information<br><\/span>\n1) id:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; unique identifier<br>\n2) gender:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\"Male\", \"Female\" or \"Other\"<br>\n3) age:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; age of the patient<br>\n4) hypertension:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; 0 if the patient doesn't have hypertension, 1 if the patient has hypertension<br>\n5) heart_disease:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;0 if the patient doesn't have any heart diseases, 1 if the patient has a heart disease<br>\n6) ever_married:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\"No\" or \"Yes\"<br>\n7) work_type:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; \"children\", \"Govt_jov\", \"Never_worked\", \"Private\" or \"Self-employed\"<br>\n8) Residence_type:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\"Rural\" or \"Urban\"<br>\n9) avg_glucose_level:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; average glucose level in blood<br>\n10) bmi:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; body mass index<br>\n11) smoking_status:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; \"formerly smoked\", \"never smoked\", \"smokes\" or \"Unknown\"*<br>\n12) stroke:&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; 1 if the patient had a stroke or 0 if not<br>\n*Note: \"Unknown\" in smoking_status means that the information is unavailable for this patient\n<\/p>\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom catboost import CatBoostClassifier\nfrom lightgbm import LGBMClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import accuracy_score\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n<h1 id=\"heading1\">\n<span style=\"font-size:30px;color:#9ACD32;font-weight:bold\"><center>Exploring Data<\/center><\/span>\n      <a class=\"anchor-link\" href=\"https:\/\/www.kaggle.com\/alampalsingh\/notebook004d896e8c#heading1\" target =\"_self\"><\/a>\n<\/h1>\n\"\"\"\ndf = pd.read_csv('..\/input\/stroke-prediction-dataset\/healthcare-dataset-stroke-data.csv')\ndf\ndf.info()\ndf.stroke\ndf.drop(['id'],axis=1,inplace=True)\n\"\"\"\n<center><span style = 'font-size:19px;font-weight:bold'>Dividing Data into Categorical and Integer\/Float Data<\/span>\n\"\"\"\ncat = []\ninf = []\nfor i in range(0,df.shape[1]):\n    if df.iloc[:,i].dtype == object:\n        cat.append(df.iloc[:,i].name)\n    else:\n        inf.append(df.iloc[:,i].name)\n\ncat\ninf\n\"\"\"\n<center><span style = 'font-size:19px;font-weight:bold'>Categorical Data<\/span>\n\"\"\"\nfig=plt.figure(figsize=(20,10),facecolor = '#fbe7dd')\ncolumns = 3\nrows = 2\na=np.random.rand(2,3)\nfor i in range(1,len(cat)+1):\n    fig.add_subplot(rows, columns, i)\n    sns.countplot(df[cat[i-1]],palette='Spectral_r') \nplt.show()\n    \nplt.figure(figsize=(10,6),facecolor = '#fbe7dd')\nplt.pie(df.stroke.value_counts(),labels=['Stroke','No Stroke'],startangle=40,explode=[0,0.15],shadow=True,colors=['#FFA177FF','#F5C7B8FF'],autopct = '%1.1f%%')\nplt.axis('equal')\nplt.show()\n_,ax = plt.subplots(1,2,figsize=(20,8),facecolor='#fbe7dd')\nsns.countplot(df.gender,hue =  df.stroke,palette='Spectral_r',ax =ax[0])\nsns.countplot(df.smoking_status,hue = df.stroke,ax=ax[1],palette='Spectral_r')\nplt.show()\ngs0 = df[df.stroke == 0].gender.value_counts()\ngs1 = df[df.stroke == 1].gender.value_counts()\nss0 = df[df.stroke == 0].smoking_status.value_counts()\nss1 = df[df.stroke == 1].smoking_status.value_counts()\ngs1\n_,ax= plt.subplots(2,2,figsize=(20,12),facecolor='#fbe7dd')\nax[0][0].pie(gs0,labels=['Female','Male','Other'],shadow =True,autopct = '%1.1f%%',explode = [0.03,0.03,0.03],colors =['#dee9a4','#72b7a1','#de7959'])\nax[0][1].pie(gs1,labels=['Female','Male'],shadow =True,autopct = '%1.1f%%',explode = [0.03,0.03],colors =['#dee9a4','#72b7a1'])\nax[1][0].pie(ss0,labels=['Never Smoked','Formerly Smoked','Unknown','Smokes'],shadow =True,autopct = '%1.1f%%',explode = [0.04,0.04,0.04,0.04],colors =['#dee9a4','#72b7a1','#de7959','#f0d999'])\nax[1][1].pie(ss1,labels=['Never Smoked','Formerly Smoked','Unknown','Smokes'],shadow =True,autopct = '%1.1f%%',explode = [0.04,0.04,0.04,0.04],colors =['#dee9a4','#72b7a1','#de7959','#f0d999'])\nax[0][0].set_title('Stroke = 0',fontsize= 30)\nax[0][1].set_title('Stroke = 1',fontsize= 30)\nplt.show()\n#f, ax = plt.subplots(figsize=(10, 8))\n#ax.set_aspect(\"equal\")\n\n# Draw a contour plot to represent each bivariate density\n#sns.kdeplot(\n    #data=df,\n    #y=\"gender\",\n    #x=\"heart_disease\",\n    #hue=\"stroke\",\n    ##thresh=.1,\n#)\n\"\"\"\n<center><span style = 'font-size:19px;font-weight:bold'>Integer\/Float Data<\/span><\/center>\n\"\"\"\nfig=plt.figure(figsize=(20,10),facecolor='#fbe7dd')\ncolumns = 3\nrows = 2\na=np.random.rand(2,3)\nfor i in range(1,len(inf)):\n    fig.add_subplot(rows, columns, i)\n    sns.kdeplot(df[inf[i-1]],hue = df.stroke) \nplt.show()\n\ndf.gender[df.gender == 'Other']\ndf.bmi.fillna(df.bmi.mean(),inplace=True)\ndf = pd.get_dummies(df)\nx= df.drop(['stroke','gender_Other'],axis = 1)\nnu = ['age','bmi','avg_glucose_level']\nsc = StandardScaler()\nx[nu] = sc.fit_transform(x[nu])\ny = df.stroke\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=44)\n\"\"\"\n<h1 id=\"heading2\">\n<span style=\"font-size:30px;color:#9ACD32;font-weight:bold\"><center>Model Fitting<\/center><\/span>\n<a class=\"anchor-link\" href=\"https:\/\/www.kaggle.com\/alampalsingh\/notebook004d896e8c#heading2\" target ='_self'><\/a>\n<\/h1>\n\"\"\"\nscore ={}\nrfc = RandomForestClassifier()\nrfc.fit(x_train,y_train)\nscore['Random Forest'] = accuracy_score(y_test,rfc.predict(x_test))\naccuracy_score(y_test,rfc.predict(x_test))\nlgb = LGBMClassifier(learning_rate = 0.1,reg_alpha = 0.3,n_estimators = 100).fit(x_train,y_train)\nscore['LightGBM'] = (accuracy_score(y_test,lgb.predict(x_test)))\n(accuracy_score(y_test,lgb.predict(x_test)))\nxgb = XGBClassifier().fit(x_train,y_train)\nscore['XGBoost'] =accuracy_score(y_test,xgb.predict(x_test))\naccuracy_score(y_test,xgb.predict(x_test))\ncbc = CatBoostClassifier(n_estimators=150,l2_leaf_reg=0.1,verbose = 0).fit(x_train,y_train)\nscore['Cat Boost'] = accuracy_score(y_test,cbc.predict(x_test))\naccuracy_score(y_test,cbc.predict(x_test))\nkey = list(score.keys())\nval = list(float(score[k]) for k in key)\nplt.figure(figsize = (16,6))\nscore = sns.barplot(val,key,palette=\"Spectral_r\")\nfor i in range(0,len(key)):\n    score.text(val[i]\/2,i,str(np.round(val[i],4)),fontdict = dict(fontsize = 12,ha = 'center',va = 'center'),weight = 'bold')\n\"\"\"\n<center><span style=\"font-size:25px;color:#9ACD32;font-weight:bold\">If you find this notebook helpful, don't forget to <\/span><span style= 'font-size:25px;color:#b7410e;font-weight:bold'>upvote.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '6fbe556b07a12e'}"}
{"id":"83782","text":"\"\"\"\n### Hi...In this notebook i used exploratory data analysis and Linear,Random forest model for predicting the house prices.\n\"\"\"\n# 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 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\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport scipy.stats as st\n\n\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn import metrics\nimport warnings\nwarnings.filterwarnings('ignore')\n\ntrain=pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/train.csv\")\ntrain.head()\ntest=pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/test.csv\")\ntest.head()\ntrain.info()\ntrain.describe()\ntrain.shape , test.shape\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nnumeric_features = train.select_dtypes(include=[np.number])\nnumeric_features.columns\nnumeric_features.head()\n\"\"\"\n#### 1.Temporal Variables(Eg: Datetime Variables)\n\n\"\"\"\n# list of variables that contain year information\nyear_feature = [feature for feature in numeric_features if 'Yr' in feature or 'Year' in feature]\n\nyear_feature\n# Let us explore the contents of temporal  variables\nfor feature in year_feature:\n    print(feature, train[feature].unique())\nfor feature in year_feature:\n    if feature!='YrSold':\n        data=train.copy()\n        ## We will capture the difference between year variable and year the house was sold for\n        data[feature]=data['YrSold']-data[feature]\n\n        plt.scatter(data[feature],data['SalePrice'])\n        plt.xlabel( feature)\n        plt.ylabel('SalePrice')\n        plt.show()\n\"\"\"\n#### 2.Discrete Variables\n\"\"\"\ndiscrete_feature=[feature for feature in numeric_features if len(train[feature].unique())<25 and feature not in year_feature + ['Id']]\nprint(\"Discrete Variables Count: {}\".format(len(discrete_feature)))\ntrain[discrete_feature].head()\n\"\"\"\n#### Now let us find the relationship between these discrete features and Sale Price\n\"\"\"\nfor feature in discrete_feature:\n    data=train.copy()\n    data.groupby(feature)['SalePrice'].median().plot.bar()\n    plt.xlabel(feature)\n    plt.ylabel('SalePrice')\n    plt.title(feature)\n    plt.show()\n\"\"\"\n #### 3. Continuous Variables:\n\"\"\"\ncontinuous_feature=[feature for feature in numeric_features if feature not in discrete_feature+year_feature+['Id']]\nprint(\"Continuous Feature Count {}\".format(len(continuous_feature)))\n\"\"\"\nLet us analyse the continuous values with data visualisation to understand the data distribution\n\"\"\"\nfor feature in continuous_feature:\n    data=train.copy()\n    data[feature].hist(bins=25)\n    plt.xlabel(feature)\n    plt.ylabel(\"Count\")\n    plt.title(feature)\n    plt.show()\n\"\"\"\n#### 4.Categorical Features\n\"\"\"\ncategorical_features = train.select_dtypes(include=[np.object])\ncategorical_features.columns\n\"\"\"\n**Estimate Skewness and Kurtosis**\n\"\"\"\ntrain.skew(), train.kurt()\ny = train['SalePrice']\nplt.figure(1); plt.title('Johnson SU')\nsns.distplot(y, kde=False, fit=st.johnsonsu)\nplt.figure(2); plt.title('Normal')\nsns.distplot(y, kde=False, fit=st.norm)\nplt.figure(3); plt.title('Log Normal')\nsns.distplot(y, kde=False, fit=st.lognorm)\n\"\"\"\nIt is apparent that SalePrice doesn't follow normal distribution, so before performing regression it has to be transformed. While log transformation does pretty good job, best fit is unbounded Johnson distribution.\n\"\"\"\nsns.distplot(train.skew(),color='blue',axlabel ='Skewness')\nplt.figure(figsize = (12,8))\nsns.distplot(train.kurt(),color='r',axlabel ='Kurtosis',norm_hist= False, kde = True,rug = False)\n#plt.hist(train.kurt(),orientation = 'vertical',histtype = 'bar',label ='Kurtosis', color ='blue')\nplt.show()\nplt.hist(train['SalePrice'],orientation = 'vertical',histtype = 'bar', color ='blue')\nplt.show()\ntarget = np.log(train['SalePrice'])\ntarget.skew()\nplt.hist(target,color='black')\ncorrelation = numeric_features.corr()\nprint(correlation['SalePrice'].sort_values(ascending = False),'\\n')\n\"\"\"\nTo explore further we will start with the following visualisation methods to analyze the data better:\n\n - Correlation Heat Map\n - Zoomed Heat Map\n - Pair Plot \n \n\"\"\"\n\"\"\"\n### Correlation Heat Map\n\"\"\"\nf , ax = plt.subplots(figsize = (14,12))\nplt.title('Correlation of Numeric Features with Sale Price',y=1,size=16)\nsns.heatmap(correlation,square = True,  vmax=0.8)\n\"\"\"\nHeatmaps are great to detect this kind of multicollinearity situations and in problems related to feature selection like this project, it comes as an excellent exploratory tool.\n\none aspect I observed here is the 'SalePrice' correlations.As it is observed that 'GrLivArea', 'TotalBsmtSF', and 'OverallQual' saying a big 'Hello !' to SalePrice, however we cannot exclude the fact that rest of the features have some level of correlation to the SalePrice. To observe this correlation closer let us see it in Zoomed Heat Map \n\"\"\"\n\"\"\"\n#### SalePrice Correlation matrix\n\"\"\"\nk= 11\ncols = correlation.nlargest(k,'SalePrice')['SalePrice'].index\nprint(cols)\ncm = np.corrcoef(train[cols].values.T)\nf , ax = plt.subplots(figsize = (14,12))\nsns.heatmap(cm, vmax=.8, linewidths=0.01,square=True,annot=True,cmap='viridis',\n            linecolor=\"white\",xticklabels = cols.values ,annot_kws = {'size':12},yticklabels = cols.values)\n\"\"\"\nFrom above zoomed heatmap it is observed that GarageCars & GarageArea are closely correlated .\nSimilarly TotalBsmtSF and 1stFlrSF are also closely correlated.\n\n\"\"\"\n\"\"\"\n### Pair Plot \n\n#### Pair Plot between 'SalePrice' and correlated variables\n\nVisualisation of 'OverallQual','TotalBsmtSF','GrLivArea','GarageArea','FullBath','YearBuilt','YearRemodAdd' features \nwith respect to SalePrice in the form of pair plot & scatter pair plot for better understanding.\n\"\"\"\nsns.set()\ncolumns = ['SalePrice','OverallQual','TotalBsmtSF','GrLivArea','GarageArea','FullBath','YearBuilt','YearRemodAdd']\nsns.pairplot(train[columns],size = 2 ,kind ='scatter',diag_kind='kde')\nplt.show()\nsaleprice_overall_quality= train.pivot_table(index ='OverallQual',values = 'SalePrice', aggfunc = np.median)\nsaleprice_overall_quality.plot(kind = 'bar',color = 'blue')\nplt.xlabel('Overall Quality')\nplt.ylabel('Median Sale Price')\nplt.show()\n\"\"\"\n#### Box plot - OverallQual\n\"\"\"\nvar = 'OverallQual'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(12, 8))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);\n\"\"\"\n#### Box plot - Neighborhood\n\"\"\"\nvar = 'Neighborhood'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);\nxt = plt.xticks(rotation=45)\n\"\"\"\n#### Housing Price vs Sales\n\n- Sale Type & Condition\n- Sales Seasonality\n\"\"\"\nvar = 'SaleType'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);\nxt = plt.xticks(rotation=45)\nvar = 'SaleCondition'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(16, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);\nxt = plt.xticks(rotation=45)\n\"\"\"\n # Missing Value Analysis \n \nWe will first check the percentage of missing values present in each feature\n\"\"\"\n# checking percentage of missing values\ndata = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/train.csv\")\nfeatures_with_na=[features for features in data.columns if data[features].isnull().sum()>1]\nfor feature in features_with_na:\n    print(feature, np.round(data[feature].isnull().mean(), 4),  ' % of Missing Values')\n#test data\ndata_out = pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/test.csv\")\nfeatures_with_na=[features for features in data_out.columns if data[features].isnull().sum()>1]\nfor feature in features_with_na:\n    print(feature, np.round(data_out[feature].isnull().mean(), 4),  ' % of Missing Values')\n# features with some missing values with sales Price\nfor feature in features_with_na:\n    dataset = data.copy()\n    dataset[feature] = np.where(dataset[feature].isnull(), 1, 0)\n   \n    # Calculate the mean of SalePrice where the information is missing or present\n    dataset.groupby(feature)['SalePrice'].median().plot.bar()\n    plt.title(feature)\n    plt.show()\n#Deleting outliers\ntrain = train.drop(train[(train['GrLivArea']>4000) & (train['SalePrice']<300000)].index)\n\n#Check the graphic again\nfig, ax = plt.subplots()\nax.scatter(train['GrLivArea'], train['SalePrice'])\nplt.ylabel('SalePrice', fontsize=13)\nplt.xlabel('GrLivArea', fontsize=13)\nplt.show()\n\"\"\"\n### Deleting Columns\n\"\"\"\ntrain=train.drop(['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond','PoolQC','MiscFeature','Alley','Fence','FireplaceQu','Neighborhood','LotFrontage','BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath','BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2','GarageYrBlt', 'GarageArea', 'GarageCars','MasVnrType','MasVnrArea','MSZoning','Electrical','Utilities','Functional','KitchenQual','Exterior1st','Exterior2nd','SaleType','MSSubClass'],axis=1)\n\ntrain=train.dropna(axis=1)\ntest=test.dropna(axis=1)\ntrain.isnull().sum()\ntrain.info()\ntest.info()\n#train data\nsum([True for idx,row in train.iterrows() if any(row.isnull())])\n\n#test data\nsum([True for idx,row in test.iterrows() if any(row.isnull())])\n#convert categorical variable into dummy\ntrain = pd.get_dummies(train)\ntest = pd.get_dummies(test)\ntrain.isnull().sum()\ntrain.head(100)\ntest.head()\n\"\"\"\n#### Deleting different columns from test in train\n\"\"\"\na = np.intersect1d(test.columns, train.columns)\nprint (a)\ntrain_common=train[a]\ntest=test[a]\ntrain_common.head()\n\"\"\"\n# Data Splitting\n\"\"\"\nX=train_common\nY=y_train\nfrom sklearn import preprocessing\nmin_max_scaler = preprocessing.MinMaxScaler()\nX_scale = min_max_scaler.fit_transform(X)\n\nX_scale\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=42)\nprint(\"X_train's shape : \",X_train.shape)\nprint(\"X_test's shape : \",X_test.shape)\nprint(\"Y_train's shape : \",Y_train.shape)\nprint(\"Y_test's shape : \",Y_test.shape)\n\"\"\"\n# Model Building\n\"\"\"\n\"\"\"\n### Linear Regressor\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nmodel=LinearRegression(normalize=True)\nmodel.fit(X_train,Y_train)\n\"\"\"\n### Random Forest Regressor\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nrfc=RandomForestRegressor(n_estimators=10000, random_state=1, n_jobs=-1)\nrfc.fit(X_train,Y_train)\n\"\"\"\n# Interpret The Model\n\nNow the model has generated a LinearRegression model for us. Recall that a LinearRegression model consist of coefficient(s) and intercept. We can now have a look at the intercept and coefficients for our model and interpret them.\n\"\"\"\n# Model evaluation for training set\nY_train_pred = model.predict(X_train)\nrmse = (np.sqrt(mean_squared_error(Y_train, Y_train_pred))) #root mean square error\nr2 = r2_score(Y_train, Y_train_pred) # it gives the score based on the relationship between actual output and predicted output by the model\n\nprint(\"Model training performance:\")\nprint(\"---------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\nprint(\"\\n\")\nY_test_pred=model.predict(X_test)\n# Model evaluation for testing set\nB_test_pred = model.predict(X_test)\nrmse = (np.sqrt(mean_squared_error(Y_test, Y_test_pred)))\nr2 = r2_score(Y_test, Y_test_pred)\n\nprint(\"Model testing performance:\")\nprint(\"--------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\n# Model evaluation for training set\nY_train_pred = rfc.predict(X_train)\nrmse = (np.sqrt(mean_squared_error(Y_train, Y_train_pred))) #root mean square error\nr2 = r2_score(Y_train, Y_train_pred) # it gives the score based on the relationship between actual output and predicted output by the model\n\n\n\nprint(\"Model training performance:\")\nprint(\"---------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\nprint(\"\\n\")\nY_test_pred=rfc.predict(X_test)\n# Model evaluation for testing set\nB_test_pred = model.predict(X_test)\nrmse = (np.sqrt(mean_squared_error(Y_test, Y_test_pred)))\nr2 = r2_score(Y_test, Y_test_pred)\n\nprint(\"Model testing performance:\")\nprint(\"--------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\nfeat_importances = pd.Series(rfc.feature_importances_, index=X_train.columns)\nfeat_importances.nlargest(10).plot(kind='barh')\nplt.show()\nfrom sklearn.feature_selection import SelectFromModel\n# Create a selector object that will use the random forest classifier to identify\n# It will select the features based on the importance score\nrf_sfm = SelectFromModel(rfc)\nrf_sfm = rf_sfm.fit(X_train, Y_train)\nX_important_train = rf_sfm.transform(X_train)\nX_important_test = rf_sfm.transform(X_test)\nX_important_train\n# Create a new random forest classifier for the most important features\nclf_important = RandomForestRegressor(n_estimators=200, random_state=1, n_jobs=-1)\n\n# Train the new classifier on the new dataset containing the most important features\nclf_important = clf_important.fit(X_important_train, Y_train)\n# Model evaluation for training set\nY_train_pred = clf_important.predict(X_important_train)\nrmse = (np.sqrt(mean_squared_error(Y_train, Y_train_pred))) #root mean square error\nr2 = r2_score(Y_train, Y_train_pred) # it gives the score based on the relationship between actual output and predicted output by the model\n\n\n\nprint(\"Model training performance:\")\nprint(\"---------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\nprint(\"\\n\")\nY_test_pred=clf_important.predict(X_important_test)\n# Model evaluation for testing set\nB_test_pred = clf_important.predict(X_important_test)\nrmse = (np.sqrt(mean_squared_error(Y_test, Y_test_pred)))\nr2 = r2_score(Y_test, Y_test_pred)\n\nprint(\"Model testing performance:\")\nprint(\"--------------------------\")\nprint('RMSE is {}'.format(rmse))\nprint('R2 score is {}'.format(r2))\n\"\"\"\n# Output predictions\n\"\"\"\noutput_model=pd.read_csv(\"..\/input\/house-prices-advanced-regression-techniques\/sample_submission.csv\")\noutput_model.head()\ntest_imp= rf_sfm.transform(test)\noutput=clf_important.predict(test_imp)\nprediction=pd.DataFrame({'Id':test.Id,'SalePrice':output})\n\nprediction.to_csv('prediction_c.csv',index=False)\n\"\"\"\nI am simply used random forest regressor and linear regressor..If you liked this notebook upvote it....Thanks for viewing!!!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '99bf357eaf61f1'}"}
{"id":"25180","text":"# 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 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\nimport matplotlib.pyplot as plt\n\"\"\"\n# An\u00e1lise Explorat\u00f3ria da Pesquisa do DataHackers\nRodrigo Pir\u00f4po, 15 anos<br>\nGosto de  matem\u00e1tica e achei an\u00e1lise de dados interessante por mais que os dados estejam limpos **ser\u00e1 que sou ao menos um Junior na \u00e1rea?** tenho s\u00f3 uns 6 meses estudando python uns 3 s\u00f3 com Dados...\n\"\"\"\nwith open('\/kaggle\/input\/pesquisa-data-hackers-2019\/data_dictionary.txt') as file:\n    content = file.read()\n    print(content)\n    \ndata = pd.read_csv('\/kaggle\/input\/pesquisa-data-hackers-2019\/datahackers-survey-2019-anonymous-responses.csv')\npd.set_option(\"display.max_columns\", 200)\ndata.head()\n\"\"\"\n# Saturando o value_counts() para entender o que passa\n\"\"\"\ndata[\"('P5', 'living_state')\"].value_counts()\ndata[\"('D3', 'anonymized_degree_area')\"].value_counts()\ndata[\"('P8', 'degreee_level')\"].value_counts()\ndata[\"('P18', 'time_experience_before')\"].value_counts()\ndata[\"('P2', 'gender')\"].value_counts()\ndata[\"('P22', 'most_used_proggraming_languages')\"].value_counts()\ndata[\"('D1', 'living_macroregion')\"].value_counts()\ndata[\"('P10', 'job_situation')\"].value_counts()\n\"\"\"\nUtilizando a M\u00e9dia dos Sal\u00e1rios\n\"\"\"\n# Solu\u00e7\u00e3o por Lucas Trajano https:\/\/www.kaggle.com\/lucastrajano Mais r\u00e1pido que meu regex...\ndata['meanSal'] = data[\"('P16', 'salary_range')\"].fillna('$ 0\/').apply(lambda x: #get the mean in ranges\n                    int( #transform all in int in the end\n                    (int(str(x)[str(x).rfind(' ')+1:str(x).rfind('\/')].replace('.','')) # Get max in range \n                    +\n                    int(str(x)[str(x).find('$')+2:str(x).find('\/')].replace('.','')) #Get min\n                    )\/2)) #divide by 2\ndata['meanSal']\n\"\"\"\n# Onde se localizam?\n\"\"\"\ndata[\"('P5', 'living_state')\"].value_counts().plot.bar(color='#16003d', title='Regi\u00f5es que possuem mais Entendedores de Dados')\nplt.ylabel(\"N\u00famero de pessoas\")\nplt.show()\n\"\"\"\n# Quantidade por g\u00eanero\n\"\"\"\ndata[\"('P2', 'gender')\"].value_counts().plot.bar(color=['#f5005a', 'blue'], title='Homens vs Mulheres na \u00e1rea',)\nplt.xticks(rotation=0)\nplt.show()\n\"\"\"\n# Ser\u00e1 que R \u00e9 melhor que Python?\n\"\"\"\ndata[\"('P22', 'most_used_proggraming_languages')\"].value_counts().nlargest(3).plot.bar(color=['green', 'orange', 'blue'])\nplt.title(\"Linguagens mais usadas por 'Data Understanders'\")\nplt.xticks(rotation=0)\nplt.show()\n\"\"\"\n# N\u00edvel de Ensino\n\"\"\"\ndata[\"('P8', 'degreee_level')\"].value_counts().plot.barh(title='N\u00edvel de Ensino', color='#16003d')\nplt.show()\n\"\"\"\n# Situa\u00e7\u00e3o de Trabalho\n\"\"\"\ndata[\"('P10', 'job_situation')\"].value_counts().plot.barh(title='Situa\u00e7\u00e3o de Trabalho', color='#16003d')\nplt.show()\n\"\"\"\n# \u00c1rea de Gradua\u00e7\u00e3o dos Partcipantes\n\"\"\"\ndata[\"('D3', 'anonymized_degree_area')\"].value_counts().plot.barh(color='#16003d')\nplt.title('\u00c1rea de Gradua\u00e7\u00e3o dos Partcipantes')\nplt.show()\ndata.groupby(\"('P10', 'job_situation')\")['meanSal'].mean()\n\"\"\"\n# Situa\u00e7\u00e3o de Trabalho vs M\u00e9dia Salarial\n\"\"\"\ndata.groupby(\"('P10', 'job_situation')\")['meanSal'].mean().nlargest(6).plot.barh(color='#16003d')\nplt.title(\"Situa\u00e7\u00e3o de Trabalho vs M\u00e9dia Salarial\")\nplt.ylabel(\"\")\nplt.show()\ndata.groupby(\"('P5', 'living_state')\")['meanSal'].mean()\ndata.groupby(\"('P5', 'living_state')\")['meanSal'].mean().plot.bar(color='#16003d')\nplt.title(\"M\u00e9dia Salarial nas regi\u00f5es brasileiras\")\nplt.xlabel(\"\")\nplt.show()\ndata.groupby(\"('P5', 'living_state')\")['meanSal'].sum()\n\"\"\"\n# 'PIB' Salarial nas regi\u00f5es brasileiras\n\"\"\"\ndata.groupby(\"('P5', 'living_state')\")['meanSal'].sum().plot.bar(color='#16003d')\nplt.title(\"'PIB' Salarial nas regi\u00f5es brasileiras\")\nplt.xlabel(\"\")\nplt.ylabel(\"EM R$ X 10\u2076\")\nplt.show()\n# Cerca de 1231R$ a mais para os homens\ndata.groupby(\"('P2', 'gender')\")['meanSal'].mean()\n\"\"\"\n# An\u00e1lise Salarial por G\u00eanero\n\"\"\"\ndata.groupby(\"('P2', 'gender')\")['meanSal'].mean().plot.bar(color=['#f5005a', 'blue'])\nplt.title(\"Comparativo entre os sal\u00e1rios de Homens e Mulheres\")\nplt.xlabel(\"\")\nplt.ylabel(\"M\u00e9dia Salarial em R$\")\nplt.xticks(rotation=0)\nplt.show()\ndata.groupby([\"('P2', 'gender')\", \"('P5', 'living_state')\"])['meanSal'].mean()\n# Diminuindo a Frase pra ficar melhor no gr\u00e1fico\ncol_ad = \"('P17', 'time_experience_data_science')\"\ndata.loc[data[col_ad] == 'N\u00e3o tenho experi\u00eancia na \u00e1rea de dados', col_ad] = 'Sem experi\u00eancia'\n\nmen = data[data.loc[:, \"('P2', 'gender')\"] == 'Masculino'] #Linhas com sexo Masculino\nmen_state_mean = men.groupby(\"('P5', 'living_state')\")['meanSal'].mean() #M\u00e9dia Masculina por regi\u00e3o\n\nwoman = data[data.loc[:, \"('P2', 'gender')\"] == 'Feminino'] #Linhas com sexo Feminino\nwoman_state_mean = woman.groupby(\"('P5', 'living_state')\")['meanSal'].mean() #M\u00e9dia Feminina por regi\u00e3o\nmenxp = men.groupby(\"('P17', 'time_experience_data_science')\")['meanSal'].mean()\nwomanxp = woman.groupby(\"('P17', 'time_experience_data_science')\")['meanSal'].mean()\n\"\"\"\n# M\u00e9dia  Salarial por G\u00eanero e Regi\u00e3o\n\"\"\"\nplt.barh(men_state_mean.index, men_state_mean.values, color='blue')\nplt.barh(woman_state_mean.index, woman_state_mean.values, color='#f5005a')\n\nplt.xlabel(\"M\u00e9dia Salarial em R$\")\nplt.ylabel(\"Estados\")\n\nplt.title(\"Comparativo entre o sal\u00e1rio de Homens e Mulheres por Regi\u00e3o\")\n\nplt.legend(['Homens', 'Mulheres'])\nplt.show()\n\"\"\"\n# M\u00e9dia Salarial por G\u00eanero e Experi\u00eancia\n\"\"\"\nplt.barh(menxp.index, menxp.values, color='blue')\nplt.barh(womanxp.index, womanxp.values, color='#f5005a')\n\nplt.xlabel(\"M\u00e9dia Salarial em R$\")\nplt.ylabel(\"Experi\u00eancia na \u00e1rea de dados\")\nplt.legend(['Homens', 'Mulheres'])\n\nplt.title(\"Comparativo entre o sal\u00e1rio de Homens e Mulheres com mesma experi\u00eancia\")\nplt.show()\n\"\"\"\n# Experi\u00eancia em TI antes vs Sal\u00e1rio na \u00e1rea de Dados\n\"\"\"\ncol_xp = \"('P18', 'time_experience_before')\"\ndata.loc[data[col_xp] == 'N\u00e3o tive experi\u00eancia na \u00e1rea de TI\/Engenharia de Software antes de come\u00e7ar a trabalhar na \u00e1rea de dados', col_xp] = 'Sem xp em TI antes'\ndata.groupby(\"('P18', 'time_experience_before')\")['meanSal'].mean().plot.barh(color='red') #Vermelho pra variar\nplt.title(\"Experi\u00eancia em TI antes vs Sal\u00e1rio na \u00e1rea de Dados\")\nplt.ylabel(\"\")\nplt.xlabel(\"Sal\u00e1rio\")\nplt.show()\n\"\"\"\n# Conclus\u00e3o\n\"\"\"\n\"\"\"\nEntre outras coisas a pesquisa nos mostra os pontos de concentra\u00e7\u00e3o daqueles que trabalham com dados - S\u00e3o Paulo (47%) e Minas Gerais (22%),a forma\u00e7\u00e3o dos participantes - 59% dos pesquisados fizeram Computa\u00e7\u00e3o, Eng de Software ou Sistemas da Informa\u00e7\u00e3o. Em adi\u00e7\u00e3o podemos encontrar informa\u00e7\u00f5es sobre sal\u00e1rio que podem mostrar a realidade da profiss\u00e3o - A m\u00e9dia do Brasil \u00e9 de 5436 RS podendo aumentar 60% caso tenha mais de 10 anos de experi\u00eancia...em S\u00e3o Paulo fica em 6379 RS. A pesquisa nos mostra uma desigualdade em rela\u00e7\u00e3o ao s\u00e1lario entre homens e mulheres, os homens ganham em m\u00e9dia cerca de R$ 1230 a mais, mesmo tendo o tempo de experi\u00eancia igual, essa diferen\u00e7a ainda se perpetua.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '2e5224807a2e56'}"}
{"id":"95436","text":"\"\"\"\n# Hello World! \nThis is my very first machine learning project. So I expect a lot of warnings, errors and absolute-piece-of-shit validation scores. Here we go.\n\"\"\"\n# 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)\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\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\n\nimg_rows, img_cols = 28, 28\nnum_classes = 10\n\ndef prep_data(raw):\n    y = raw[:, 0]\n    out_y = keras.utils.to_categorical(y, num_classes)\n    \n    x = raw[:,1:]\n    num_images = raw.shape[0]\n    out_x = x.reshape(num_images, img_rows, img_cols, 1)\n    out_x = out_x \/ 255\n    return out_x, out_y\n\nfile = \"\/kaggle\/input\/digit-recognizer\/train.csv\"\ndata = np.loadtxt(file, skiprows=1, delimiter=',')\nx, y = prep_data(data)\n\"\"\"\n# Building The Model\n\"\"\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, Dropout\n\nmodel = Sequential()\nmodel.add(Conv2D(12, kernel_size=(3,3), activation='relu', input_shape=(img_rows, img_cols, 1)))\nmodel.add(Conv2D(12, kernel_size=(3,3), activation='relu'))\nmodel.add(Conv2D(12, kernel_size=(3,3), activation='relu'))\nmodel.add(Conv2D(12, kernel_size=(3,3), activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(num_classes, activation='softmax'))\n\"\"\"\n# Compiling\n\"\"\"\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\"\"\"\n# Fitting\n\"\"\"\nmodel.fit(x, y, batch_size=100, epochs=25, validation_split=0.2)\n\"\"\"\n# Validation Score\n\"\"\"\nscore = model.evaluate(x, y, verbose=0)\nprint(f'Test loss: {score[0]} \/ Test accuracy: {score[1]}')\n\"\"\"\n# Preparing Test Data\n\"\"\"\ndef prep_test_data(raw):\n    x = raw[:,0:]\n    num_images = raw.shape[0]\n    out_x = x.reshape(num_images, img_rows, img_cols, 1)\n    out_x = out_x \/ 255\n    return out_x\n\nval_file = \"\/kaggle\/input\/digit-recognizer\/test.csv\"\nval_data = np.loadtxt(val_file, skiprows=1, delimiter=',')\nx_test = prep_test_data(val_data)\n\"\"\"\n# Predicting & Saving\n\"\"\"\npredictions = model.predict_classes(x_test)\n\nindexes = [i for i in range(1,len(val_data)+1)]\noutput = pd.DataFrame({'ImageId': indexes,'Label': predictions})\noutput.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': 'af395a5e55d862'}"}
{"id":"80379","text":"\"\"\"\n# I. Introduction \n\n> Hi There.. Im  kind of new in Kaggle and Python and following other people recommendation I got the titanic Data set \n> It was the First Data set that I analyzed. please feel free to leave any feedback .. and thanks in advance\n\"\"\"\n\"\"\"\n# II. OBTAINING Data\n\"\"\"\n!pip install venndata\n#basic library \nimport pandas as pd\nimport numpy as np\nimport math \nimport re \n\n#visualization \nimport matplotlib.pyplot as plt\nimport matplotlib\nimport matplotlib_venn as vplt\nfrom venndata import venn   \nfrom matplotlib.colors import ListedColormap\nimport seaborn as sns \nimport cufflinks as cf \n%matplotlib inline\nsns.set_style(style = 'darkgrid')\ncf.go_offline()\nsns.set_style('whitegrid')\n\n#importing Data \ntrain= pd.read_csv('..\/input\/titanic\/train.csv')\ntest= pd.read_csv('..\/input\/titanic\/test.csv')\nID = test['PassengerId']\nVdf =pd.read_csv('..\/input\/titanic\/train.csv') #for visualization Purpose\ntrain.head()\nfig,(ax1,ax2) = plt.subplots(1,2 , figsize=(15,5))\n\nsns.heatmap(train.isnull(), yticklabels = False , cmap = 'plasma', ax = ax1)\nsns.heatmap(test.isnull(), yticklabels = False , cmap = 'plasma', ax = ax2)\nprint(\"massive missing value in Cabin & test data has Missing Data in Fare\")\n\"\"\"\n# III. Exploring Data , visualization\n\"\"\"\nVdf\n#defining values\n\nVdf['Pclass1'] = Vdf.Pclass.apply(lambda x: 1 if x==1 else 0)\nVdf['Pclass2'] = Vdf.Pclass.apply(lambda x: 1 if x==2 else 0)\nVdf['Pclass3'] = Vdf.Pclass.apply(lambda x: 1 if x==3 else 0)\nVdf['Male'] = Vdf.Sex.apply(lambda x: 1 if x=='male' else 0)\nVdf['Female'] = Vdf.Sex.apply(lambda x: 1 if x=='female' else 0)\n#Vdf['Kids'] = Vdf.Age.apply(lambda x: 1 if x<10 else 0)\n#Vdf['Adoles'] = Vdf.Age.apply(lambda x: 1 if 11>x<10 else 0)\n#Vdf['Adults'] = Vdf.Age.apply(lambda x: 1 if 19>x<50 else 0)\n#Vdf['Elder'] = Vdf.Age.apply(lambda x: 1 if x>50 else 0)\n##-----------------------------------------------------------------\n   \n\n\ndf2 = Vdf[['Survived', 'Pclass1', 'Pclass2', 'Pclass3', 'Male', 'Female']] #,'Elder','Kids','Elder','Adoles']]\nmatplotlib.rcParams['figure.figsize'] = [10, 10]\nfineTune=False\nlabels, radii, actualOverlaps, disjointOverlaps = venn.df2areas(df2, fineTune=fineTune)\nfig, ax = venn.venn(radii, actualOverlaps, disjointOverlaps, \n                    labels=labels, labelsize='auto', \n                    cmap='viridis', fineTune=fineTune)\n\nprint('General view of survivor')\nfrom IPython.display import display\nfrom PIL import Image\npath=('..\/input\/titanic-picture-ilustrive\/titanic.jpg')\ndisplay(Image.open(path))\n\"\"\"\n# From this picture I can asume \n1. People in third class has less chances to survive\n2. I get many insight and guidelines to make sure I am doing ok \n3. Any feedback it is welcome \n\"\"\"\n#Survived + Survivor segmented by sex , segmented by Pclass\nfig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize=(20,5))\nsns.countplot(x='Survived' , data=train, ax=ax1 ,palette=\"Dark2\")\nax1.set_title(\"Survived , 0 = Dead , 1 = Alive\")\nsns.countplot(x='Survived' , hue='Sex',data=train, ax=ax2, palette=\"Set1\")\nax2.set_title(\"Survived Segmented by Sex\")\nsns.countplot(x='Survived' , hue='Pclass',data=train, ax=ax3,palette=\"Paired\")\nax3.set_title(\"Survived Segmented by Sex\/Pclass\")\n\"\"\"\n# *I know there are missing values , but in order to better understand the data I create some segmentation and them I will compare them with the new graph without NAN*\n\"\"\"\nfig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize=(25,10))\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[train.Age < 15], ax=ax1,palette=\"Dark2\").set_title('Age between 0-15')\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[(train['Age'] > 16) & (train['Age'] < 25)], ax=ax2,palette=\"Paired\").set_title('Age between 16- 25')\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[(train['Age'] > 26) & (train['Age'] < 35)], ax=ax3).set_title('Age between 26- 35')\nfig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize=(25,10))\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[(train['Age'] > 36) & (train['Age'] < 45)], ax=ax1).set_title('Age between 36-45')\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[(train['Age'] > 46) & (train['Age'] < 60)], ax=ax2,palette=\"Dark2\").set_title('Age between 46- 60')\nsns.countplot(x='Survived' , hue = 'Sex' , data=train[(train['Age'] > 61) & (train['Age'] < 80)], ax=ax3).set_title('Age between 61- 80')\n\"\"\"\nFinding Missing Values in Embarked\n\n\n\"\"\"\n#Adressing missing value in Embarked in embarked \nprint(\" Missing Values in Embarked:\",train.isnull().sum()[5])\ntrain[train['Embarked'].isna()]\n#Now we have to Replace them both value \"Southampton\"\ntrain['Embarked'].fillna(\"S\", inplace = True)\n\"\"\"\n**Would be easier fill the issing data with S because is the place where most of people were coming from , but since they are only two I looked for the info : Miss. Amelie boarded the Titanic at Southampton as maid to Mrs George Nelson Stone. She travelled on Mrs Stone's ticket (#113572). Mrs Stone boarded the Titanic in Southampton on 10 April 1912 and was travelling in first class with her maid Amelie Icard. She occupied cabin B-28. I found that info in www.encyclopedia-titanica.org**\n\"\"\"\n\"\"\"\n# IV. SCRUB , Missing values - Age - Cabin , etc\n\"\"\"\n\"\"\"\n**We know some people was tarveling with their family, in titanic.org the information has been collected by famiy so i will do my best to filter those family that have 7 or 8 member and find their ages\n* 0    608 # traveling alone \n* 1    209 \n* 2     28\n* 4     18\n* 3     16 # 16 Family with 3 members\n* 8      7 # 7 Family with 8 members\n* 5      5**\n\"\"\"\n\"\"\"\n## Age\n\"\"\"\ntrain[(train.Age.isna())&(train.SibSp== 8)]\nsage_f = train[(train.Age.isna())&(train.SibSp== 8)]['Name'].to_list()\ndbirth_ = [1907,1904,1895,1892,1891,1893,1897] #their ages in www.encyclopedia-titanica.org\ndbirth= 1912 - np.array(dbirth_)  #1912 Titanic accident \ndbirth\n#Diccionaty \nkeys = sage_f\nvalues = dbirth\nnew_dict = dict(zip(keys, values))\nprint(new_dict)\nfor k, v in new_dict.items():\n    train.loc[train.Name == k, 'Age'] = v\n    \nfor k, v in new_dict.items():\n    test.loc[train.Name == k, 'Age'] = v\n\"\"\"\n**Replacing Ages\nTo fill the missing values in Age , I can easily find the average age and then apply it to all of the missing value , but instead I will filter by the Mr, Mrs , Miss, Master by doing this will be more accurate**\n\"\"\"\nsns.boxplot(x='Pclass', y='Age', data=train).set_title('Age Average per class')\n#Combining both Data set \ndata_titanic = [train,test]\n\nfor data in data_titanic: #Extracting Title \n    data['Title'] = data ['Name'].str.extract(' ([A-Za-z]+)\\.', expand = False)\ntrain.Title.value_counts().to_dict() #here I will Use Mr, Miss, Mrs, Master and the rest \"Others\"\ntit_val = {\"Mr\": 2,\"Miss\": 1,\"Mrs\": 3,\"Master\": 0,\"Dr\": 2,\"Rev\": 2,\"Col\": 2,\"Major\": 2,\"Mlle\": 2,\"Capt\": 2,\"Jonkheer\": 2,\"Countess\": 2,\"Sir\": 2,\"Mme\": 2,\"Ms\": 1,\"Don\": 2,\"Lady\": 3}\nfor data in data_titanic:\n    data['Title'] = data ['Title'].map(tit_val)\ntrain.head(2)\ntest.head(2)\n#filling values\ntrain.groupby('Title')['Age'].mean().round()\n#Now We can Fill the Age \ndef impute_age (col): \n    Age=col[0]\n    Title=col[1]\n    \n    if pd.isnull(Age):\n        \n        if Title== 0 :\n            return 5\n        elif Title == 1:\n            return 22\n        elif Title == 2:\n            return 33\n        else:\n            return 36\n    else:\n        return Age\ntrain['Age'] = train[['Age','Title']].apply(impute_age, axis = 1)\ntest['Age'] = test[['Age','Title']].apply(impute_age, axis = 1)\nfig,(ax1) = plt.subplots(1,1 , figsize=(10,5))\nsns.countplot(x = 'Survived' , data= train , hue = 'Title', ax = ax1).set_title(\"Survivor-Dead By Title\")\nprint(\"Master: 0, Miss: 1, Mr: 2, Mrs: 3\")\n\"\"\"\n## Cabin\n\"\"\"\n\"\"\"\n**> Filling Cabin Information : Cabin could be a great parameter but it has too many missing value, however I can notice the distribution was \"first class had the top decks (A-E)\",\"second class (D-F)\", and \"third class (E-G)\" In the image (on the notebook) , I can notice that, 3rd class was in the fron\/back , 2nd class was in the middle , 1st class on the top\nSo In think that Cabit and pclass are related if we change cabin to 1 2 3 we will have the same results**\n\"\"\"\ndef cabins (col):\n    classes = col[0]\n    cabin = col[1]\n    \n    if classes == 1:\n        return 3\n    elif classes == 2:\n        return 2\n    else:\n        return 1 \nfig,(ax1,ax2) = plt.subplots(1,2 , figsize=(15,5))\n\nsns.heatmap(train.isnull(), yticklabels = False , cmap = 'plasma', ax = ax1)\nsns.heatmap(test.isnull(), yticklabels = False , cmap = 'plasma', ax = ax2)\nprint(\"No Missing Values\")\n\"\"\"\n# V. Modeling \n\"\"\"\n\"\"\"\n### Test Part\n\"\"\"\np_data= train  # I will save train as p_Data because i will try so many different algorithms \nfrom sklearn.compose import ColumnTransformer, make_column_transformer\nfrom sklearn.preprocessing import OneHotEncoder,LabelEncoder,LabelBinarizer\n\n#Missing Values\n#print(p_data.isnull().sum())\np_data['Embarked'].fillna('S', inplace= True)\n\n#Step_1 Combine SibSp & Parch\np_data['F_A'] = p_data['SibSp']+p_data['Parch']\np_data['F_A'] =p_data.F_A.apply(lambda x :2 if x>0 else 1)\n\n#Step_2 Transform Cabin\np_data['Cabin_'] =p_data[['Pclass','Cabin']].apply(cabins, axis=1)\n\n#Step 3 Encoding Sex\nsex = pd.get_dummies(p_data['Sex'],drop_first= True)\np_data = pd.concat([p_data,sex],axis = 1)\n\n#step_4 Drop columns\np_data.drop(['PassengerId','Pclass','Name','SibSp','Parch','Ticket','Cabin','Sex'], axis = 1 , inplace = True)\np_data\n\n#Step 5 Onehot\nohc = OneHotEncoder()\nXtest= p_data.iloc[:,3].values\nXtest = Xtest.reshape(-1,1)\nEMB = ohc.fit_transform(Xtest).toarray()\nEB= pd.DataFrame(EMB,columns = ['S','C','Q'])\np_data = pd.concat([p_data ,EB], axis = 1)\np_data.drop('Embarked', axis = 1 , inplace = True)\np_data\n\"\"\"\n### Test Part\n\"\"\"\n#Missing Values\n#print(p_data.isnull().sum())\ntest['Title'].fillna(1, inplace= True)\ntest['Fare'].fillna(35.6271, inplace= True)\n\n#Step_1 Combine SibSp & Parch\ntest['F_A'] = test['SibSp']+test['Parch']\ntest['F_A'] =test.F_A.apply(lambda x :2 if x>0 else 1)\n\n#Step_2 Transform Cabin\ntest['Cabin_'] =test[['Pclass','Cabin']].apply(cabins, axis=1)\n\n#Step 3 Encoding Sex\nsex = pd.get_dummies(test['Sex'],drop_first= True)\ntest = pd.concat([test,sex],axis = 1)\n\n#step_4 Drop columns\ntest.drop(['PassengerId','Pclass','Name','SibSp','Parch','Ticket','Cabin','Sex'], axis = 1 , inplace = True)\n\n#Step 5 Change into Categorical \nohc = OneHotEncoder()\nXohc= test.iloc[:,2].values\nXohc= Xohc.reshape(-1,1)\nEMB = ohc.fit_transform(Xohc).toarray()\nEB= pd.DataFrame(EMB,columns = ['S','C','Q'])\ntest = pd.concat([test ,EB], axis = 1)\ntest.drop('Embarked', axis = 1 , inplace = True)\ntest\ntest_1 = test\n\"\"\"\n## Applying MinMax scaler and Standar Scaler \n\"\"\"\nfrom sklearn.model_selection import train_test_split,cross_val_score,cross_val_predict,cross_validate\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import *\n\n#Testing\ndata_1 = p_data  # <----- Standar Scaler\ndata_2 = p_data  # <----- MinMax\ndata_3 = p_data  # <----- \n\n\n#Difining X\nX_1=data_1.drop('Survived',axis = 1)\nX_2=data_2.drop('Survived',axis = 1)\nX_3=data_3.drop('Survived',axis = 1)\n\ny=p_data['Survived']\n\n#Splitting\nX_train, X_test, y_train, y_test = train_test_split(X_1, y, test_size=0.2, random_state=42,stratify=data_2['Cabin_'])\nX_train_2, X_test_2, y_train_2, y_test_2 = train_test_split(X_2, y, test_size=0.2, random_state=42,stratify=data_2['Cabin_'])\n\n\n# MinMax\nMX= MinMaxScaler()\nX_1 = MX.fit_transform(X_1)\nX_train = MX.fit_transform(X_train)\nX_test = MX.fit_transform(X_test)\ntest_MX = MX.fit_transform(test_1)\n\n# Standar Scalar \nSC = StandardScaler()\nX_2 = SC.fit_transform(X_2)\nX_train_2 = SC.fit_transform(X_train_2)\nX_test_2 = SC.fit_transform(X_test_2)\ntest_SC = SC.fit_transform(test_1)\n\nprint(\"Segmenting Data ....... into Two sets ....Done...!!  \")\nprint(\"Splitting Data into X_train and X_test... Done..!!  \")\nprint(\"Applying MinMax Scaler & Standard Scaler .... Done..!!\")\n#General Fuction to evaluate Model \n\ndef Evaluating (model,X,y,CV, criteria=True):\n    if criteria :\n        score = cross_val_score(model,X=X ,y=y ,cv=CV, scoring='accuracy', n_jobs= 4)\n        score = np.mean(score)\n        accuracy.append(score)\n    \n    else:\n        pred = cross_val_predict(model,X=X ,y=y ,cv=CV, n_jobs= 4)\n        prediction.append(pred)\n        \nprint(\"Creating General fuction to Evaluate Algorithms.....Done\")\n\"\"\"\n# Machine Learning\n\"\"\"\n\"\"\"\n## Baseline\n\"\"\"\n#Machine Learning\nfrom sklearn.linear_model import LogisticRegression\nimport xgboost as xgb\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier,BaggingClassifier\nfrom sklearn.naive_bayes import GaussianNB\n\n\nLGR = LogisticRegression()\n\nXG = xgb.XGBRFClassifier(base_score=0.5, colsample_bylevel=1, colsample_bynode=0.8,\n                colsample_bytree=0.9539552926340813, gamma=0.08955017265494192,\n                learning_rate=0.07004776526310222, max_delta_step=0,\n                max_depth=24, min_child_weight=1.667528606432285, missing=None,\n                n_estimators=230, n_jobs=1, nthread=None,\n                objective='binary:logistic', random_state=0, reg_alpha=0,\n                reg_lambda=1, scale_pos_weight=1, seed=None, silent=None,\n                subsample=0.9219040847026176, verbosity=1)\nSVM_1= svm.SVC(probability = True)\n\nSVM_2= svm.SVC()\n\nRF = RandomForestClassifier(bootstrap=False, ccp_alpha=0.0, class_weight=None,\n                       criterion='gini', max_depth=10, max_features='auto',\n                       max_leaf_nodes=None, max_samples=None,\n                       min_impurity_decrease=0.0, min_impurity_split=None,\n                       min_samples_leaf=4, min_samples_split=2,\n                       min_weight_fraction_leaf=0.0, n_estimators=600,\n                       n_jobs=None, oob_score=False, random_state=None,\n                       verbose=0, warm_start=False)\nBG = BaggingClassifier(RF)\nNB = GaussianNB()\n\naccuracy = []\nprediction =[]\n\nfor i in [LGR, XG, SVM_1, SVM_2,  RF,BG, NB]:\n      Evaluating(i,X_1,y,CV=5)        \n\nprint(\"Processing....... Done..... \")\nprint(\"Using Cross_Validation and MinMax Scaler with 5 Folds ......Check the Accuracy Below!!\")\n\nMINMAX = pd.DataFrame(accuracy, index = ['LGR','XG','SVM_1','SVM_2','RF','BG','NB'], columns = ['MINMAX_Accuracy'])\naccuracy = []\nprediction =[]\n\nfor i in [LGR,XG, SVM_1, SVM_2,  RF, BG, NB]:\n      Evaluating(i,X_2,y,CV=5)\n\n\nprint(\"Processing....... Done..... \")\nprint(\"Using Cross_Validation and Standard Scaler with 5 Folds ......Check the Accuracy Below!!\")\nSCALER = pd.DataFrame(accuracy, index = ['LGR','XG','SVM_1','SVM_2','RF','BG','NB'], columns = ['SC_Accuracy'])\n\nprint(\"It seems no to have a significant change no matter what approach I use\")\n\npd.concat([MINMAX,SCALER],axis = 1)\n\"\"\"\n## Precision Recall \n\"\"\"\n\"\"\"\n** In here i can find a balance between Recall and Precision , actually with a threshold of 0.7 using Randon Forest i got 0. 78 in the Leader board\"**\n\"\"\"\nfrom sklearn.metrics import plot_precision_recall_curve\n\nfor i in [XG, SVM_1, SVM_2,  RF, BG, NB]:\n    i.fit(X_2,y)\n\nfig,axs= plt.subplots(2,2, figsize = (20,15))\nplot_precision_recall_curve(XG,X_2,y,ax=axs[0,0])\nplot_precision_recall_curve(SVM_1,X_2,y,ax=axs[0,1])\nplot_precision_recall_curve(BG,X_2,y,ax=axs[1,0])\nplot_precision_recall_curve(RF,X_2,y,ax=axs[1,1])\nplt.show(\"Precision VS ReCall\")\n\"\"\"\n> ## Emsembling\n\"\"\"\n\"\"\"\n### Soft\n\"\"\"\nfrom sklearn.ensemble import VotingClassifier\nprint(\"Emsembling models..... RandomForest, Support Vector Machine, etc, ........\\n\")\nmodelos = [('RandomForest', RF),('BG',BG), ('SVM_1',SVM_1),('XGboost',XG)]\n\nthreshold_1 = 0.8\nthreshold_2 = 0.7\n\nVC= VotingClassifier(estimators = modelos,voting='soft',n_jobs=3)\nVC.fit(X_train_2,y_train_2)\n\nfor i in [RF, BG , SVM_1, XG,VC]:\n    \n    if i == RF:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict_proba(X_test_2)\n        y_pred = [1 if predictions[i][1]>threshold_1 else 0  for i in range(len(predictions))]\n        \n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n        \n    elif i == BG:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict_proba(X_test_2)\n        y_pred = [1 if predictions[i][1]>threshold_2 else 0  for i in range(len(predictions))]\n        \n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n        \n    else:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict(X_test_2)\n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n    \n\nprint(\"\\nTesting Vagging Classifier .... Applying Cross Validation.....!!\")\nscores = cross_val_score(estimator=VC,X=X_2,y=y,cv=5,scoring='accuracy')\nprint(\"Mean Score =\", np.mean(scores))\n\"\"\"\n### Hard\n\"\"\"\nfrom sklearn.ensemble import VotingClassifier\nprint(\"Emsembling models..... RandomForest, Support Vector Machine, etc, ........\\n\")\nmodelos = [('RandomForest', RF),('BG',BG), ('SVM_1',SVM_1),('XGboost',XG)]\n\nthreshold_1 = 0.8\nthreshold_2 = 0.8\n\nVC= VotingClassifier(estimators = modelos,voting='hard',n_jobs=3 , weights = [2,4,4,4])\nVC.fit(X_train_2,y_train_2)\n\nfor i in [RF, BG , SVM_1, XG,VC]:\n    \n    if i == RF:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict_proba(X_test_2)\n        y_pred = [1 if predictions[i][1]>threshold_1 else 0  for i in range(len(predictions))]\n        \n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n        \n    elif i == BG:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict_proba(X_test_2)\n        y_pred = [1 if predictions[i][1]>threshold_2 else 0  for i in range(len(predictions))]\n        \n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n        \n    else:\n        i.fit(X_train_2,y_train_2)\n        predictions = i.predict(X_test_2)\n        print(i.__class__.__name__,accuracy_score(y_test_2,y_pred))\n    \n\nprint(\"\\nTesting Vagging Classifier .... Applying Cross Validation.....!!\")\nscores = cross_val_score(estimator=VC,X=X_2,y=y,cv=5,scoring='accuracy')\nprint(\"Mean Score =\", np.mean(scores))\n# Prediction\ny_pred = VC.predict(test_SC)\n\nsub = pd.DataFrame()\nsub['PassengerId'] = ID\nsub['Survived'] = y_pred\nsub.to_csv('VC_prediction_1.csv', index=False)\nprint(\"Predicting .......! \")\nprint(\"Submission has been saved\")\nprint(\"Accurancy up to 0.77990\")\n\"\"\"\n# VI. Deep Learning\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential \nfrom tensorflow.keras.layers import Dense,Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import Adam\n\n#Early Stop\nearly_stop = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=25, \n        verbose=1, mode='auto', restore_best_weights=True)\n\nNN= Sequential()\n\nNN.add(Dense(9,activation = 'relu',input_shape=[9 ,]))\nNN.add(Dense(5,activation ='relu'))\nNN.add(Dropout(0.3))\nNN.add(Dense(2,activation ='relu'))\nNN.add(Dense(1,activation='sigmoid'))\nNN.compile(optimizer='adam', loss= 'binary_crossentropy', metrics = ['accuracy'] )\n\nNN.fit(x=X_train_2, y=y_train_2,validation_data = (X_test_2, y_test_2) , epochs=600,batch_size=700 ,verbose = 0)\n\n\npd.DataFrame(NN.history.history).plot()\nplt.show()\nthreshold = 0.6\n\npredictions = NN.predict_proba(test_SC)\ny_pred = [1 if predictions[i]>threshold else 0  for i in range(len(predictions))]\n\nsub = pd.DataFrame()\nsub['PassengerId'] = ID\nsub['Survived'] = y_pred\nsub.to_csv('NN_predic_0.6 prediction_500.csv', index=False)\nprint(\"Predicting 0.7829 Accuracy.......! \")\nprint(\"Submission has been saved\")\n\"\"\"\n# -----------------Final Thoughts-----------------\n1. Thanks for passing by .. I added Voting classifier, SVM , Xgossbost , And Neural Network , however They all have the same output 0.79 Score \n2. We can see here that the way we process data it is more important that the model that we use\n3. I Will keep Working on this but please feel free to leave some comments \n\"\"\"","meta":"{'source': 'AI4Code', 'id': '939bb12f1e86e5'}"}
{"id":"18965","text":"\"\"\"\n# Humpback Whale Identification with MobileNet\n* This kernel is a combination of @peter : https:\/\/www.kaggle.com\/pestipeti\/keras-cnn-starter and @beluga: https:\/\/www.kaggle.com\/gaborfodor\/greyscale-mobilenet-lb-0-892 from google doodle quickdraw competition\n\"\"\"\nimport numpy as np \nimport pandas as pd \nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mplimg\nfrom matplotlib.pyplot import imshow\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n\nfrom keras import layers\nfrom keras.preprocessing import image\nfrom keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D\nfrom keras.layers import AveragePooling2D, MaxPooling2D, Dropout\nfrom keras.models import Model\n\nimport keras.backend as K\nfrom keras.models import Sequential\n\nfrom keras.metrics import categorical_accuracy, top_k_categorical_accuracy, categorical_crossentropy\nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.applications import MobileNet\nfrom keras.applications.mobilenet import preprocess_input\n\nimport warnings\nwarnings.simplefilter(\"ignore\", category=DeprecationWarning)\nos.listdir(\"..\/input\/\")\ntrain_df = pd.read_csv(\"..\/input\/train.csv\")\ntrain_df.head()\ndef prepareImages(data, m, dataset):\n    print(\"Preparing images\")\n    X_train = np.zeros((m, 100, 100, 3))\n    count = 0\n    \n    for fig in data['Image']:\n        #load images into images of size 100x100x3\n        img = image.load_img(\"..\/input\/\"+dataset+\"\/\"+fig, target_size=(100, 100, 3))\n        x = image.img_to_array(img)\n        x = preprocess_input(x)\n\n        X_train[count] = x\n        if (count%500 == 0):\n            print(\"Processing image: \", count+1, \", \", fig)\n        count += 1\n    \n    return X_train\ndef prepare_labels(y):\n    values = np.array(y)\n    label_encoder = LabelEncoder()\n    integer_encoded = label_encoder.fit_transform(values)\n    # print(integer_encoded)\n\n    onehot_encoder = OneHotEncoder(sparse=False)\n    integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n    onehot_encoded = onehot_encoder.fit_transform(integer_encoded)\n    # print(onehot_encoded)\n\n    y = onehot_encoded\n    # print(y.shape)\n    return y, label_encoder\nX = prepareImages(train_df, train_df.shape[0], \"train\")\nX \/= 255\ny, label_encoder = prepare_labels(train_df['Id'])\ny.shape\ndef top_5_accuracy(y_true, y_pred):\n    return top_k_categorical_accuracy(y_true, y_pred, k=5)\nmodel = MobileNet(input_shape=(100, 100, 3), alpha=1., weights=None, classes=5005)\nmodel.compile(optimizer=Adam(lr=0.002), loss='categorical_crossentropy',\n              metrics=[categorical_crossentropy, categorical_accuracy, top_5_accuracy])\nprint(model.summary())\nhistory = model.fit(X, y, epochs=500, batch_size=100, verbose=1)\nplt.plot(history.history['categorical_accuracy'])\nplt.title('Model categorical accuracy')\nplt.ylabel('categorical accuracy')\nplt.xlabel('Epoch')\nplt.show()\ntest = os.listdir(\"..\/input\/test\/\")\nprint(len(test))\ncol = ['Image']\ntest_df = pd.DataFrame(test, columns=col)\ntest_df['Id'] = ''\nX = prepareImages(test_df, test_df.shape[0], \"test\")\nX \/= 255\npredictions = model.predict(np.array(X), verbose=1)\nfor i, pred in enumerate(predictions):\n    test_df.loc[i, 'Id'] = ' '.join(label_encoder.inverse_transform(pred.argsort()[-5:][::-1]))\ntest_df.head(10)\ntest_df.to_csv('submission.csv', index=False)","meta":"{'source': 'AI4Code', 'id': '22a1086994eff7'}"}
{"id":"104743","text":"# 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 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\n\"\"\"\n# Importing Data\n\"\"\"\neda=pd.read_csv('\/kaggle\/input\/titanic-dataset-from-kaggle\/train.csv')\n\"\"\"\n# Importing all the Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\neda\n\"\"\"\n# EDA(Exploratory Data Analysis) or Cleaning of the Data\n\"\"\"\neda.head()\neda.tail()\neda.info()\neda.describe()\n\"\"\"\n## Checking for Null Values\n\"\"\"\neda.isnull().sum()\n\"\"\"\n### We should 1st check whether Null values are present in the DataSet or not, before performing any cleaning on that particular column. Here age has null values,so we should fix it.\n\"\"\"\neda['Age']=eda['Age'].fillna(value=eda['Age'].mean())\neda.isnull().sum()\n\"\"\"\n## Checking for Outliers in the DataSet\n\"\"\"\neda.boxplot()\n\"\"\"\n### Outliers are present in four different columns,two of those columns are ignorable,'Age','Fare' Column Outliers should be Fixed.\n\n### It is finded and capped as below:\n\"\"\"\nIQR_Fare=eda['Fare'].quantile(0.75)-eda['Fare'].quantile(0.25)\nIQR_Fare\nUpper_OutlierLimit=eda['Fare'].quantile(0.75)+1.5*IQR_Fare\nUpper_OutlierLimit\nOutlierValues=eda[(eda['Fare']>Upper_OutlierLimit)]\nOutlierValues\neda['Fare']=np.where(eda['Fare']>65.6,eda['Fare'].quantile(0.85),eda['Fare'])\neda\nIQR_Age=eda['Age'].quantile(0.75)-eda['Age'].quantile(0.25)\nIQR_Age\nUpper_OutlierLimit2=eda['Age'].quantile(0.75)+1.5*IQR_Age\nUpper_OutlierLimit2\nOutlierValues2=eda[(eda['Age']>Upper_OutlierLimit2)]\nOutlierValues2\neda['Age']=np.where(eda['Age']>54.5,eda['Age'].quantile(0.95),eda['Age'])\neda\n\"\"\"\n### Now Outliers are capped.We can check it through BoxPlot of the Particular Columns \n\"\"\"\neda.boxplot(column=['Fare'])\nobj=eda.dtypes==np.object\nprint(obj)\n\"\"\"\n### Here,we have Name,Sex,Ticket,Cabin & Embarked columns as categorical data.\n### In the process of Cleaning,we don't require\/accept categorical data.All the data should be numeric.\n### Other thing to note here is,'Sex' and 'Embarked' Columns are not Continuous data.So we can get numeric data by creating dummies to them.\n### So we should Drop 3 Columns and create dummies for 2 columns \n\"\"\"\neda.drop(['Name','Ticket','Cabin'],axis=1,inplace=True)\neda\neda=pd.get_dummies(eda,drop_first=True)\neda\ncols=eda.columns\ncols=['PassengerId','Pclass','Age','SibSp','Parch','Fare','Sex_male','Embarked_Q','Embarked_S','Survived']\neda=eda[cols]\neda\n\"\"\"\n### We are just interchanging the columns(Dependent variable to last column) just to have good view\n\"\"\"\n\"\"\"\n# Building the model by using Logistic Regression\n\"\"\"\n\"\"\"\n### Defining x and y:\n\"\"\"\nx=eda.iloc[:,:-1].values\nx.shape\ny=eda.iloc[:,-1].values\ny.shape\n\"\"\"\n### Splitting the DataSet\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25 , random_state=5)\nx_train.shape\nx_test.shape\ny_train.shape\ny_test.shape\n\"\"\"\n### Building the Model\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\nlr.fit(x_train, y_train)\ny_pred = lr.predict(x_test)\ny_test\ny_pred\n\"\"\"\n## Confusion Matrix\n\"\"\"\nfrom sklearn.metrics import confusion_matrix\nconfusion = confusion_matrix(y_test, y_pred)\nprint(confusion)\nTN = confusion [0,0]\nFP = confusion [0,1]\nFN = confusion [1,0]\nTP = confusion [1,1]\nprint(confusion)\nprint (\"TN: \", TN)\nprint (\"FP: \", FP)\nprint (\"FN: \", FN)\nprint (\"TP: \", TP)\n\"\"\"\n## Classification Accuracy\n\"\"\"\nfrom sklearn import metrics\naccuracy = metrics.accuracy_score(y_test, y_pred)\naccuracy1 = (TN+TP)\/(TN+TP+FN+FP)\nprint (\"Accuracy from metrics: \", accuracy)\nprint (\"Accuracy Calculated: \", accuracy1)\n\"\"\"\n## Classification Error\n\"\"\"\nprint((FP+FN)\/float(TP+TN+FP+FN))\nprint(round(1-metrics.accuracy_score(y_test, y_pred),4))\n\"\"\"\n## Sensitivity\/True Positive Rate\/Recall\n\"\"\"\nprint(\"RECALL:\", metrics.recall_score(y_test,y_pred))\nprint(\"CALCULATED RECALL:\", (TP)\/(TP+FN))\n\"\"\"\n## Specificity\/True Negative Rate\n\"\"\"\nprint (\"SPECIFICITY\/TRUE NEGATIVE RATE:\", (TN)\/(TN+FP))\n\"\"\"\n## False Positive Rate\n\"\"\"\nprint(\"FALSE POSITIVE RATE: \",(FN)\/(FN+TP))\n\"\"\"\n## False Negative Rate\n\"\"\"\nprint(\"FALSE NEGATIVE RATE: \",(FP)\/(TN+FP))\n\"\"\"\n## Precision\n\"\"\"\nprint (\"Precision: \", round(metrics.precision_score(y_test,y_pred),2))\nprint (\"PRECISION CALCULATED: \", round(TP\/float(TP+FP),2))\n\"\"\"\n## f1 Score\n\"\"\"\nfrom sklearn.metrics import accuracy_score,f1_score,precision_score,recall_score,roc_auc_score\naccuracy = accuracy_score(y_test, y_pred)\nrecall = recall_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred)\nf1 = f1_score(y_test, y_pred)\nroc_auc = roc_auc_score(y_test, y_pred)\n\nprint('Accuracy is  :' ,round(accuracy,2)*100)\nprint('F1 score is :' ,round(f1,2)*100)\nprint('Precision is  :',round(precision,2)*100)\nprint('Recall is  :',round(recall,4)*100)\nprint('Roc Auc is  :',round(roc_auc,2)*100)","meta":"{'source': 'AI4Code', 'id': 'c06b54b9007521'}"}
{"id":"60553","text":"# 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\n# install pyvis framework for visualization\nprint(\"Installing pyvis:\")\n!pip install pyvis\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nfrom pyvis.network import Network\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\n\"\"\"\n# Python Libraries as a usage-clustered network\n\nThis notebook is trying to visualize the major existing python libraries as a clustored network. This work has **no claim regarding completeness**. Nevertheless, I appreciate any ideas on adding missing packages or improving clean code that would make the network maintenance much easier.\n\"\"\"\n\"\"\"\n## Defining nodes\n\nFirst, we have to add the nodes that will in general present the differen libraries. Furthermore, there are main- and subnodes which can be treated as the clusters headline.\n\nThe network graph itself basically follows a tree structure where **\"Python\"** is assigned to the **root node**. Edges that are leaving the root node will lead to **topical main clusters** that describe the different areas python is used in. Following that idea, one can find the same approach leaving the main clusters and leading to **topical sub clusters** which are more granular. Consequently, the deepest layer will be defined by the **specific libraries**.\n\nWith that setting in mind, it is clear that in some cases a library might be a *leaf node on the bottom* and a *direct child from another main cluster* at the same time. This observation makes it **hard to balance the network graph as a tree**.\n\nLet's start defining the node clusters:\n\"\"\"\nroot = [\"Python\"]\nmain_cluster = [\n    \"Visualization\", \n    \"Machine Learning\", \n    \"NLP\", \n    \"Testing\", \n    \"Data Analysis \/ EDA\", \n    \"Data Processing\", \n    \"Finance\",\n    \"Basic Usage\",\n]\nsub_cluster = [\n    \"Dashboard\",\n    \"D3.js\",\n    \"Extraordinary Visualization\", \n    \"Feature Engineering\", \n    \"FlowChart\",\n    \"Geo\",\n    \"Graph \/ Network\",\n    \"Hyperparameter Tuning\", \n    \"Information Retrieval\", \n    \"Integration\", \n    \"Interactive Visualization\",\n    \"Keras\",\n    \"Performance\",\n    \"Pytorch\",\n    \"Static Visualization\",\n    \"TimeSeries\",\n    \"Tensorflow\",\n    \"TPOT\",\n    \"XAI\",\n\n]\nlibraries = [\n     'altair',\n     'auto-sklearn',\n     'auto-viml',\n     'bokeh',\n     'candela',\n     'cufflinks',\n     'd3py',\n     'dash',\n     'dask',\n     'dtale',\n     'dtreeviz',\n     'dx_analytics',\n     'eli5',\n     'featuretools',\n     'folium',\n     'functools',\n     'fundamentalanalysis',\n     'gensim',\n     'geopandas',\n     'geopy',\n     'graph-tool',\n     'holoview',\n     'itertools',\n     'jaal',\n     'lazypredict',\n     'leaflet',\n     'lime',\n     'luminaire',\n     'lux',\n     'matplotlib',\n     'missingno',\n     'more-itertools',\n     'mutmut',\n     'neptune',\n     'networkx',\n     'neuraxle',\n     'nltk',\n     'numpy',\n     'nvd3',\n     'pandas',\n     'pandas-datareader',\n     'pandas-log',\n     'pandas-profiler',\n     'pandera',\n     'panel',\n     'pattern',\n     'plotly',\n     'polyglot',\n     'pycaret',\n     'pydantic',\n     'pyflowchart',\n     'pynlpl',\n     'pypolars',\n     'pystemmer',\n     'pyterrier',\n     'pytest',\n     'pyts',\n     'pyvis',\n     'roughviz',\n     'rshap',\n     'scikit-learn',\n     'scikit-optimize',\n     'seaborn',\n     'shapash',\n     'sigma.js',\n     'sklearn laboratory',\n     'sklearn-deap',\n     'sklearn-pandas',\n     'sklearn-xarray',\n     'spacy',\n     'sql-test',\n     'stanford corenlp python',\n     'stumpy',\n     'sweetviz',\n     'textblob',\n     'tpot',\n     'tsfresh',\n     'vaex',\n     'visdcc',\n     'vocabulary',\n     'yfinance'\n]\n\"\"\"\n## Defininng the edges\n\nNext we define the basic structur for our edges:\n\"\"\"\n# set up the edges that are building the graph\ndata = [\n    [\"Python\", \"Basic Usage\"],\n    [\"Python\", \"Finance\"],\n    [\"Python\", \"Data Processing\"],\n    [\"Python\", \"Data Analysis \/ EDA\"],\n    [\"Python\", \"Machine Learning\"],\n    [\"Python\", \"Visualization\"],\n    [\"Python\", \"Testing\"],\n    \n    [\"Basic Usage\",\"functools\"],\n    [\"Basic Usage\", \"itertools\"],\n    [\"Basic Usage\", \"more-itertools\"],\n    \n    [\"Data Processing\", \"pandas\"],\n    [\"Data Processing\", \"numpy\"],\n    [\"Data Processing\", \"Performance\"],\n    \n    [\"Performance\", \"vaex\"],\n    [\"Performance\", \"pypolars\"],\n    [\"Performance\", \"dask\"],\n    \n    [\"Finance\", \"cufflinks\"],\n    [\"Finance\", \"dx_analytics\"],\n    [\"Finance\", \"fundamentalanalysis\"],\n    [\"Finance\", \"yfinance\"],\n    \n    [\"cufflinks\", \"Visualization\"],\n    \n    [\"Machine Learning\", \"Feature Engineering\"],\n    [\"Machine Learning\", \"Hyperparameter Tuning\"],\n    [\"Machine Learning\", \"Keras\"],\n    [\"Machine Learning\", \"NLP\"],\n    [\"Machine Learning\", \"Pytorch\"],\n    [\"Machine Learning\", \"Tensorflow\"],\n    [\"Machine Learning\", \"TPOT\"],\n    [\"Machine Learning\", \"XAI\"],\n    [\"Machine Learning\", \"auto-viml\"],\n    [\"Machine Learning\", \"dtreeviz\"], \n    [\"Machine Learning\", \"pycaret\"],\n    [\"Machine Learning\", \"lazypredict\"],\n    [\"Machine Learning\", \"scikit-learn\"],\n    \n    [\"pycaret\", \"lazypredict\"],\n    \n    [\"Feature Engineering\", \"featuretools\"],\n    [\"Feature Engineering\", \"tsfresh\"],\n    \n    [\"scikit-learn\", \"sklearn-xarray\"],\n    [\"scikit-learn\", \"sklearn-pandas\"],\n    [\"scikit-learn\", \"sklearn-deap\"],\n    [\"scikit-learn\", \"auto-sklearn\"],\n    [\"scikit-learn\", \"sklearn laboratory\"],\n    \n    [\"sklearn laboratory\", \"neptune\"],\n    \n    [\"Hyperparameter Tuning\", \"neuraxle\"],\n    [\"Hyperparameter Tuning\", \"scikit-optimize\"],\n    \n    [\"XAI\", \"auto-viml\"],\n    [\"XAI\", \"eli5\"],\n    [\"XAI\", \"rshap\"],\n    [\"XAI\", \"lime\"],\n    \n    [\"NLP\", \"Information Retrieval\"],\n    [\"NLP\", \"nltk\"],\n    [\"NLP\", \"gensim\"],\n    [\"NLP\", \"scikit-learn\"],\n    [\"NLP\", \"spacy\"],\n    [\"NLP\", \"pystemmer\"],\n    [\"NLP\", \"stanford corenlp python\"],\n    [\"NLP\", \"textblob\"],\n    [\"NLP\", \"pattern\"],\n    [\"NLP\", \"polyglot\"],\n    [\"NLP\", \"pynlpl\"],\n    [\"NLP\", \"vocabulary\"],\n    \n    [\"Information Retrieval\", \"pyterrier\"],\n    \n    [\"Visualization\", \"D3.js\"],\n    [\"Visualization\", \"Dashboard\"],\n    [\"Visualization\", \"Extraordinary Visualization\"],\n    [\"Visualization\", \"FlowChart\"],\n    [\"Visualization\", \"Geo\"],\n    [\"Visualization\", \"Graph \/ Network\"],\n    [\"Visualization\", \"Interactive Visualization\"],\n    [\"Visualization\", \"Static Visualization\"],\n    \n    [\"D3.js\", \"d3py\"],\n    [\"D3.js\", \"nvd3\"],\n    \n    [\"Dashboard\", \"bokeh\"],\n    [\"Dashboard\", \"dash\"],\n    [\"Dashboard\", \"holoview\"],\n    [\"Dashboard\", \"panel\"],\n    [\"Dashboard\", \"plotly\"],\n    \n    [\"Extraordinary Visualization\", \"candela\"],\n    [\"Extraordinary Visualization\", \"roughviz\"],\n    \n    [\"FlowChart\", \"pyflowchart\"],\n    \n    [\"Geo\", \"geopy\"],\n    [\"Geo\", \"folium\"],\n    [\"Geo\", \"leaflet\"],\n    [\"Geo\", \"geopandas\"],\n    \n    [\"Graph \/ Network\", \"dtreeviz\"],\n    [\"Graph \/ Network\", \"graph-tool\"],\n    [\"Graph \/ Network\", \"jaal\"],\n    [\"Graph \/ Network\", \"networkx\"],\n    [\"Graph \/ Network\", \"pyvis\"],\n    [\"Graph \/ Network\", \"sigma.js\"],\n    [\"Graph \/ Network\", \"visdcc\"],\n    \n    [\"Interactive Visualization\", \"altair\"],\n    [\"Interactive Visualization\", \"bokeh\"],\n    [\"Interactive Visualization\", \"cufflinks\"],\n    [\"Interactive Visualization\", \"holoview\"],\n    [\"Interactive Visualization\", \"plotly\"],\n    [\"Interactive Visualization\", \"shapash\"],\n\n    [\"Static Visualization\", \"lux\"],\n    [\"Static Visualization\", \"matplotlib\"],\n    [\"Static Visualization\", \"missingno\"],\n    [\"Static Visualization\", \"pandas-profiler\"],\n    [\"Static Visualization\", \"seaborn\"],\n    [\"Static Visualization\", \"shapash\"],\n    \n    [\"Data Analysis \/ EDA\", \"TimeSeries\"],\n    [\"Data Analysis \/ EDA\", \"dtale\"],\n    [\"Data Analysis \/ EDA\", \"lux\"],\n    [\"Data Analysis \/ EDA\", \"shapash\"],\n    [\"Data Analysis \/ EDA\", \"sweetviz\"],\n    [\"Data Analysis \/ EDA\", \"missingno\"],\n    [\"Data Analysis \/ EDA\", \"pandas\"],\n    \n    [\"pandas\", \"pandas-datareader\"],\n    [\"pandas\", \"pandas-log\"],\n    [\"pandas\", \"pandas-profiler\"],\n    \n    [\"TimeSeries\", \"luminaire\"],\n    [\"TimeSeries\", \"pyts\"],\n    [\"pandas\", \"sklearn-pandas\"],\n\n    [\"TimeSeries\", \"stumpy\"],\n\n    [\"visdcc\", \"dash\"],\n\n    [\"Testing\", \"Integration\"],\n    [\"Testing\", \"mutmut\"],\n    [\"Testing\", \"pytest\"],\n    [\"Testing\", \"sql-test\"],\n\n    [\"Integration\", \"pandera\"],\n    [\"Integration\", \"pydantic\"],\n]\n\n\"\"\"\n## Building the network graph\n\nNext, we will add both, nodes and edges, to our graph. It is important to recalculate which id or number a node is assigned to, in order to draw the edges correctly. \n\"\"\"\n\"\"\"Define edges.\"\"\"\nfrom more_itertools import locate\n\ntest_nw = Network(height='750px', width=\"100%\", notebook=True)\nnodes = root + main_cluster + sub_cluster + libraries\n\n# add root node\nroot_node = list(locate(nodes, lambda x: x in root))\nroot_size, root_color = [35 for _ in root], [\"red\" for _ in root]\n\ntest_nw.add_nodes(root_node, size=root_size, label=root, color=root_color)\n\n# add main_cluster nodes\nmain_nodes = list(locate(nodes, lambda x: x in main_cluster))\nmain_size, main_color = [30 for _ in main_cluster], [\"orange\" for _ in main_cluster]\n\ntest_nw.add_nodes(main_nodes, size=main_size, label=main_cluster, color=main_color)\n\n# add sub_cluster nodes\nsub_nodes = list(locate(nodes, lambda x: x in sub_cluster))\nsub_size, sub_color = [25 for _ in sub_cluster], [\"yellow\" for _ in sub_cluster]\n\ntest_nw.add_nodes(sub_nodes, size=sub_size, label=sub_cluster, color=sub_color)\n\n# add library nodes\nlib_nodes = list(locate(nodes, lambda x: x in libraries))\nlib_size, lib_color = [15 for _ in libraries], [\"blue\" for _ in libraries]\n\ntest_nw.add_nodes(lib_nodes, size=lib_size, label=libraries, color=lib_color)\n\n# add edges\nfor edge in data:\n    node_from, node_to = list(locate(nodes, lambda x: x in edge))\n    test_nw.add_edge(node_from, node_to)\n\ntest_nw.show(\"test.html\")","meta":"{'source': 'AI4Code', 'id': '6f9e2a7b39c65a'}"}
{"id":"138696","text":"\"\"\"\n# Importing the libraries\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import mean_absolute_error\n\"\"\"\n# Reading  the data\n\"\"\"\ndf=pd.read_csv('..\/input\/diverse-algorithm-analysis-dataset-daad\/Pokemon_categorical.csv')\n\"\"\"\n# Understanding the data\n\"\"\"\ndf.columns\n\"\"\"\n**The dataset contains too many columns that we do not need.\nSo it is better to create a new dataset with only the necessary columns**\n\"\"\"\ndf2=df[['name', 'type1', 'type2', 'hp', 'attack', 'defense', 'sp_attack',\n       'sp_defense', 'speed', 'generation', 'is_legendary']]\ndf2.head()\ndf2.columns\ndf2.info()\ndf2.describe()\ndf2.corr()\n\"\"\"\n# Visualizing the data\n\"\"\"\nplt.figure(figsize=(15,7))\nsns.heatmap(df2.corr(),annot=True)\n# plotting all the data\ndf3=df2.loc[:,['attack','defense','speed']]\ndf3.plot(figsize=(15,7))\ndf3.plot(subplots=True)\nplt.show()\ndf2.plot(kind = \"hist\",y = \"defense\",bins = 50,range= (0,250))\n\"\"\"\n# Building the model\n\"\"\"\nfeatures=['hp', 'attack', 'defense', 'sp_attack',\n       'sp_defense', 'speed', 'generation']\nX=df2[features]\ny=df2.is_legendary\ntrain_x,test_x,train_y,test_y=train_test_split(X,y)\nmodel=DecisionTreeClassifier(random_state=1)\nmodel.fit(train_x,train_y)\npred=model.predict(test_x)\nprint(\"Mean absolute error: \",mean_absolute_error(test_y,pred))\nprint(\"Model score:\",model.score(test_x,test_y))\nmy_submission=pd.DataFrame({'index':test_x.index,'isLegendary':pred})\nmy_submission.to_csv('submission.csv',index=False)\n\"\"\"\n If you have any suggestions on improving this notebook, please comment \n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'feffe8a8ae19e6'}"}
{"id":"119650","text":"# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\ndf=pd.read_csv(\"..\/input\/zomato.csv\",encoding = \"ISO-8859-1\")\ncountry = pd.read_excel('..\/input\/Country-Code.xlsx')\ndf = pd.merge(df, country, on='Country Code')\ndf.head()\ndf.shape\n\"\"\"\n## 9551 rows and 21 columns are there in the dataset\n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pandas import DataFrame\n\n\"\"\"\n# Checking for the data types\n\"\"\"\ndf.dtypes\ndf.head()\ndf.describe()\n\"\"\"\n# Above is the Quick view of the dataset\n\"\"\"\ndf1=df.groupby([\"Cuisines\"])\n\"\"\"\n# Grouping data according to cuisines\n\"\"\"\ndf1.mean()\n\n\"\"\"\n# Grouping according to City\n\"\"\"\ndf2=df.groupby([\"City\"])\ndf2.mean()\ndf3=df[\"City\"].value_counts()\ndf3\n\n\n\n\ndata_country = df.groupby(['Country'], as_index=False).count()[['Country', 'Restaurant ID']]\ndata_country.head()\ndata_country.columns = ['Country', 'No of Restaurant']\nplt.figure(figsize=(20,30))\nplt.bar(data_country['Country'], data_country['No of Restaurant'],color=\"brown\")\nplt.xlabel('Country')\nplt.ylabel('No of Restaurant')\nplt.title('No of Restaurant')\nplt.xticks(rotation = 60)\n\"\"\"\n> # Inference:\n# 1. Indian city has maximum number of Zomato restaurants\n# 2. Zomato has its presence in 23 countries but the most important country is India\n\"\"\"\n\"\"\"\n# So, we should focus on India because of the above reasons\n\"\"\"\ndata_City = df[df['Country'] =='India']\nTotal_city =data_City['City'].value_counts()\nTotal_city.plot.bar(figsize=(20,10))\nplt.title('Restaurants by City')                                             \nplt.xlabel('City')\nplt.ylabel('No of Restaurants')\nplt.show()\n\"\"\"\n# Inference:\n# 1. New Delhi has the highest number of restaraunts associated with Zomato with a count of more than 5000.\n# 2. Gurgaon and Noida are behind New Delhi with count of more than 1000 restaurants associated with Zomato\n\"\"\"\nCuisine_data =df.groupby(['Cuisines'], as_index=False)['Restaurant ID'].count()\nCuisine_data.columns = ['Cuisines', 'Number of Resturants']\nTop10= (Cuisine_data.sort_values(['Number of Resturants'],ascending=False)).head(10)\nplt.figure(figsize=(20,30))\nsns.barplot(Top10['Cuisines'], Top10['Number of Resturants'])\nplt.xlabel('Cuisines', fontsize=20)\nplt.ylabel('Number of Resturants', fontsize=20)\nplt.title('Top 10 Cuisines on Zomato', fontsize=30)\nplt.show()\n\"\"\"\n# Inference:\n# 1. Restaurants providing only North-Indian cuisines are the highest in number with count of approximate 850\n# 2. Restaurants providing both Chinese and North Indian and restaurants providing only Chinese are behind the resturants providing both North-Indianwith a count of approx 450 and 380 respectively.\n\"\"\"\ndummy_cuisines=pd.get_dummies(df[\"Has Online delivery\"])\ndf4=dummy_cuisines.sum()\n\nDataFrame(df4)\nx=[\"Yes\",\"No\"]\nplt.bar(x,df4,color=\"red\")\nplt.xlabel(\"Wether the restaurant has an Online delivery\")\nplt.ylabel(\"Count of restaurants\")\n\"\"\"\n# Results:\n# 1. A bar graph presentation which shows how many restaurants    provide Online Delivery.\n \n\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\"\"\"\n# Table which shows the count of restaurants on the basis of Rating: Average,Excellent,Good,Not rated,Poor,Very Good in different cities.\n\"\"\"\npd.crosstab(df['Rating text'], df['City'])\n%matplotlib inline\nplt.figure(figsize=(20,10))\nplt.ylabel(\"Number of restaurants\")\nplt.xlabel(\"Aggregate rating\")\nsns.barplot(df[\"Aggregate rating\"],range(1,50))\n\nplt.show()\n\"\"\"\n# Result:\n# 1. Restaurants with ratings 3.3 are highest in number.\n# 2. Near about 30 restaurants are unrated.. May be they are new.\n# 3. There are no restaurants having rating less than 3,which may show that Zomato doesn't collaborate with restaurants having ratings less than 3\n\"\"\"\nfrom subprocess import check_output\nfrom wordcloud import WordCloud, STOPWORDS\nstopwords = set(STOPWORDS)\nwordcloud = (WordCloud(width=1440, height=1080, relative_scaling=1, stopwords=stopwords).generate_from_frequencies(df['Restaurant Name'].value_counts()))\n\n\nfig = plt.figure(1,figsize=(30,20))\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\n\"\"\"\n# Inference:\n# 1. Cafe Coffee Day has maximum number of restaurants associated with Zomato in INDIA followed by Domnio's Pizza and Green Chick Chop.\n\"\"\"\nfrom sklearn import neighbors\nfrom sklearn.metrics import mean_squared_error \nfrom math import sqrt\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.metrics import r2_score\nplt.figure(figsize=(10,8))\nplt.scatter(df[\"Votes\"],df[\"Average Cost for two\"],marker=\"*\",color=\"green\")\nplt.xlabel(\"Number of Votes\")\nplt.ylabel(\"Average Cost for two\")\n\n\n\"\"\"\n# From above scatter plot it is clear that there is almost no relationship between Votes(to restaraunt by its customer) and Average Cost for two.\n\"\"\"\n\"\"\"\n## Correlation between various elements of the dataset\n\"\"\"\ndf.corr()\n \ncorrmat = df.corr() \n  \nf,ax = plt.subplots(figsize =(9, 8)) \nsns.heatmap(corrmat, ax = ax, cmap =\"YlGnBu\", linewidths = 0.1) \n\"\"\"\n## KNN Regression\n\"\"\"\n\"\"\"\n## Predicting 'Average Cost for Two' using 'Currency'\n\"\"\"\n\"\"\"\n### Importing train_test_split method to split the dataset into training and testing for training the model and then testing it.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\"\"\"\n## Using KNN for regression\n\"\"\"\nx=df[['Currency']]\ny=df['Average Cost for two']\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.8,random_state=42)\ndummies=pd.get_dummies(x_train)\ndummies\ndummies2=pd.get_dummies(x_test)\ndummies2.head()\nk=[]\naccu=[]\nfor i in range(1,50):\n    model = neighbors.KNeighborsRegressor(n_neighbors = i)\n    model.fit(dummies, y_train)  #fit the model\n    pred=model.predict(dummies2) #make prediction on test set\n    a=dummies2.shape\n    accuracy = r2_score(y_test, pred)\n    print(\"For k=\",i)\n    print(\"Accuracy is -\",accuracy*100,'%') \n    k.append(i)\n    accu.append(accuracy)\n    \n\n\"\"\"\n## We can see that the best accuracy score is for K=13\n\"\"\"\nplt.plot(k,accu)\nplt.xlabel(\"Value of K\")\nplt.ylabel(\"R2_score\")\nmodel = neighbors.KNeighborsRegressor(n_neighbors = 13)\nmodel.fit(dummies, y_train)  #fit the model\npred=model.predict(dummies2) #make prediction on test set\na=dummies2.shape\naccuracy = r2_score(y_test, pred)\nfor i in range(a[0]):\n    print(\"For \",x_test.iloc[i,:])\n    print(\"average cost for two=\")\n    print(pred[i])\naccuracy = r2_score(y_test, pred)\nprint(\"Accuracy is -\",accuracy*100,'%') \n\"\"\"\n1. ## Accuracy score is 56.43%.\n\"\"\"\n\"\"\"\n## Predicting 'Average Cost for Two' using 'Currency' and 'Rating text'\n\"\"\"\nx=df[['Currency','Rating text']]\ny=df['Average Cost for two']\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.8,random_state=42)\ndummies=pd.get_dummies(x_train)\ndummies\ndummies2=pd.get_dummies(x_test)\ndummies2.head()\naccur=[]\nK1=[]\nrmse=[]\ny_test2=y_test.values##Converting y_test to numpy array\n\nfor i in range(1,50):\n    model = neighbors.KNeighborsRegressor(n_neighbors = i)\n    model.fit(dummies, y_train)  #fit the model\n    pred=model.predict(dummies2) #make prediction on test set\n    accuracy = r2_score(y_test, pred)\n    error=sqrt(mean_squared_error(y_test2,pred))\n    print(\"For K=\",i)\n    print(\"Root Mean Squared Error is-\",error)\n    print(\"Accuracy is -\",accuracy*100,'%') \n    K1.append(i)\n    rmse.append(error)\n    accur.append(accuracy)\n    \n \n\n\n\"\"\"\n## Root Mean Squared Error vs K values\n\"\"\"\nplt.plot(K1,rmse)\n\nplt.xlabel(\"Value of K\")\nplt.ylabel(\"RMSE\")\nplt.plot(rmse,accur)\nplt.xlabel(\"RMSE\")\nplt.ylabel(\"R2_score\")\n\"\"\"\n## From this plot it is clear that the highest R2_score is corressponding to the lowest value of RMSE.\n\"\"\"\n\"\"\"\n## R2_Score Error vs K values\n\"\"\"\nplt.plot(K1,accur)\n\nplt.xlabel(\"Value of K\")\nplt.ylabel(\"R2_score\")\n\"\"\"\n## We can observe that the maximum accuracy and minimum RMSE value is corressponding to the K-value=2\n\"\"\"\na=dummies2.shape\nmodel = neighbors.KNeighborsRegressor(n_neighbors = 2)\nmodel.fit(dummies, y_train)  #fit the model\npred=model.predict(dummies2) #make prediction on test set\nfor i in range(a[0]):\n    print(\"For \",x_test.iloc[i,:])\n    print(\"average cost for two=\")\n    print(pred[i])\n\naccuracy = r2_score(y_test, pred)\nprint(\"For K=\",2)\nprint(\"Accuracy is -\",accuracy*100,'%')\n\"\"\"\n## Accuracy score is about 68.92% which is significant.\n\"\"\"\n\"\"\"\n## **From above it is clear that for various currency based on rating, average cost for two varies.**\n ## For Indian rupees the average cost for two based on rating are approximated as follows-\n ## Poor-Rs.550\n ## Average-Rs.575\n ## Good-Rs.300\n ## Very good-Rs.1400\n ## Not rated-Rs.475\n ## So,with the above prediction any customer can be sure of how they have to spend for their required quality of foods on Indian Rupees\n\"\"\"\n\"\"\"\n## Using Linear Regression model\n\"\"\"\n\"\"\"\n## 1.Predicting 'Average Cost for Two' using 'Currency' and 'Rating text'\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nx=df[['Currency','Rating text']]\ny=df['Average Cost for two']\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.8,random_state=42)\ndummies=pd.get_dummies(x_train)\ndummies\ndummies2=pd.get_dummies(x_test)\ndummies2.head()\nlinear_model=LinearRegression()\nlinear_model.fit(dummies,y_train)\nlinear_model.coef_\nlinear_model.intercept_\nprediction=linear_model.predict(dummies2)\nr2_score(prediction,y_test)\nerror=sqrt(mean_squared_error(y_test,prediction))\nerror \n\"\"\"\n## The Regression model did not work well for this as r2 score is very low\n\"\"\"\n\"\"\"\n## 2.Predicting 'Average Cost for Two' using 'Price range' and 'Aggregrate Rating'\n\"\"\"\nx=df[['Aggregate rating','Price range']]\ny=df['Average Cost for two']\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.6,random_state=42)\nlinear_model=LinearRegression()\nlinear_model.fit(x_train,y_train)\nlinear_model.coef_\nlinear_model.intercept_\nprediction=linear_model.predict(x_test)\nr2_score(y_test,prediction)\nerror=sqrt(mean_squared_error(y_test,prediction))\nerror\n\"\"\"\n## Here too, the Linear Regression model didn't work well as R2_score is very low.\n## Hence, also from correlation values it is understood that we cannot use Linear Regression model for this dataset.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'dc10d38ee02806'}"}
{"id":"67110","text":"\"\"\"\n# An analysis of the 2019 Kaggle ML and DS Survey for Vim\/Emacs users\n![](https:\/\/www.kialo.com\/images\/f8ba939f-e548-4bb4-92a6-9359e7cf9088_1200x630_stretched.jpeg)\n\n## Introduction\n\nBefore Atom, before Sublime Text, before Notepad++, before Microsoft Word, before Notepad, and even before WordPerfect, there were Vi and Emacs, both of which came out in 1976. These early programmers had to write inside of a terminal. That means they could not use a mouse to click to move their cursor. People used to write code inside the terminal using just a keyboard with either Vim or Emacs, two of the oldest text editors. In fact, many people still prefer to use these text editors despite their steep learning curve because when you don't use a mouse, you can type\/write code a lot faster.\n\nThe arguments of which is better, Vim or Emacs, are more fierce than the arguments of using tabs or spaces. However, Kaggle have decided to group the two text editors together (which likely disappointed those who consider them very different). Despite this, grouping them makes sense, since they are the two most popular text editors run inside the terminal. The people who use Vim\/Emacs as their main text editor are somewhat legendary in the coding community because they have put in the years required to learn it efficiently.\n\nAs an anecdote, my professors in Computer Science all used Vim and they encouraged us to use it too, but I would say > 90% of the class (including me) did not use it because your typing is slowed so much when you have to look up so many different keyboard shortcuts\/commands. Nowadays, I use Vim rarely--only when I am SSHed into an EC2 server and I need to edit 1 or 2 lines of code (as opposed to writing ALL the code inside of it). I instead prefer to upload my completed code as a file to the cloud, or work on Jupyter Notebook in the cloud and then convert the .ipynb to a Python file. Therefore I expect that many people do not use Vim\/Emacs because of its incredibly steep learning curve.\n\n## Hypotheses\n\nSo, who are these legends who still prefer to use Vim\/Emacs? I hypothesize that they are either very old people (which means they used Vim\/Emacs when they first came out), or they are people who almost exclusively use servers\/cloud services (since many times when you SSH into a server, you may only have access to the terminal; there is often no ability for you to launch an application like Notepad). Additionally, I hypothesize that these people likely write code for the majority of their work day and do not hold manager positions but instead are full-time programmers (because why would a manager ever learn Vim\/Emacs?).\n\n## Methodology\nThis notebook will focus on the Vim\/Emacs users in ML and DS, and comparing their responses to people who do not use these text editors. As we step through, we will answer the hypotheses through data analysis.\n\"\"\"\n# import the necessary libraries\nimport numpy as np \nimport pandas as pd\n\n# Visualisation libraries\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set()\n\n# Graphics in retina format \n%config InlineBackend.figure_format = 'retina' \n\n# Increase the default plot size and set the color scheme\nplt.rcParams['figure.figsize'] = 16, 10\n#plt.rcParams['image.cmap'] = 'viridis'\n\n\nimport os\n\n# Disable warnings in Anaconda\nimport warnings\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\nos.listdir('..\/input\/kaggle-survey-2019\/')\n# Importing the 2019 Dataset\ndf_2019 = pd.read_csv('..\/input\/kaggle-survey-2019\/multiple_choice_responses.csv')\ndf_2019.columns = df_2019.iloc[0]\ndf_2019=df_2019.drop([0]) # The first row just contains the column names, so we can drop it.\n# Create a boolean column if they use Vim\/Emacs.\n# This is mainly so we don't have to refer to such a long column name every time.\ndf_2019['vim\/emacs_user'] = '  Vim \/ Emacs  ' == df_2019[\"Which of the following integrated development environments (IDE's) do you use on a regular basis?  (Select all that apply) - Selected Choice -   Vim \/ Emacs  \"] \n\"\"\"\n# Hypothesis 1\nHypothesis 1: Very old people use Vim\/Emacs, because they used it when it came out and therefore don't see the need to change to newer text editors.\n\nTo explore this, we will change the \"Age\" column from categorical to numerical (by replacing from a uniformly distributed age within the range) and look at the kernel density plots of the Vim\/Emacs distribution versus the non-Vim\/Emacs distribution. The kernel density plot is basically an estimate of the PDF of that variable.\n\"\"\"\ndf_2019['numerical_age'] = 0 # Initialize the numerical_age column\nnp.random.seed(2019) # Set random seed for reproducability\ndf_2019.loc[df_2019['What is your age (# years)?']=='18-21', 'numerical_age'] = np.random.uniform(low=18,high=22,size=df_2019.loc[df_2019['What is your age (# years)?']=='18-21'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='22-24', 'numerical_age'] = np.random.uniform(low=22,high=25,size=df_2019.loc[df_2019['What is your age (# years)?']=='22-24'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='25-29', 'numerical_age'] = np.random.uniform(low=25,high=30,size=df_2019.loc[df_2019['What is your age (# years)?']=='25-29'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='30-34', 'numerical_age'] = np.random.uniform(low=30,high=35,size=df_2019.loc[df_2019['What is your age (# years)?']=='30-34'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='35-39', 'numerical_age'] = np.random.uniform(low=35,high=40,size=df_2019.loc[df_2019['What is your age (# years)?']=='35-39'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='40-44', 'numerical_age'] = np.random.uniform(low=40,high=45,size=df_2019.loc[df_2019['What is your age (# years)?']=='40-44'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='45-49', 'numerical_age'] = np.random.uniform(low=45,high=50,size=df_2019.loc[df_2019['What is your age (# years)?']=='45-49'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='50-54', 'numerical_age'] = np.random.uniform(low=50,high=55,size=df_2019.loc[df_2019['What is your age (# years)?']=='50-54'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='55-59', 'numerical_age'] = np.random.uniform(low=55,high=60,size=df_2019.loc[df_2019['What is your age (# years)?']=='55-59'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='60-69', 'numerical_age'] = np.random.uniform(low=60,high=70,size=df_2019.loc[df_2019['What is your age (# years)?']=='60-69'].shape[0])\ndf_2019.loc[df_2019['What is your age (# years)?']=='70+', 'numerical_age']   = np.random.uniform(low=70,high=90,size=df_2019.loc[df_2019['What is your age (# years)?']=='70+'].shape[0])\nplt.rcParams['figure.figsize'] = 16, 10\nax = sns.kdeplot(df_2019.loc[~df_2019['vim\/emacs_user'],'numerical_age'], shade=True, color='blue', label='Non-Vim\/Emacs')\nsns.kdeplot(df_2019.loc[df_2019['vim\/emacs_user'], 'numerical_age'], shade=True, color='orange', label='Vim\/Emacs', ax=ax)\n\"\"\"\nInitially, from the kernel density plots we can see that the age of Vim\/Emacs users are skewed higher than non-users. However, the hypothesis was really focused on older people. Can we zoom in on people who are over 60 years old and view the kernel density plots again?\n\"\"\"\nax = sns.kdeplot(df_2019.loc[~df_2019['vim\/emacs_user'],'numerical_age'], shade=True, color='blue', label='Non-Vim\/Emacs')\nsns.kdeplot(df_2019.loc[df_2019['vim\/emacs_user'], 'numerical_age'], shade=True, color='orange', label='Vim\/Emacs', ax=ax)\nax.set_ylim(bottom=0,top=0.003) # Zoom in where the plot is low\nax.set_xlim(left=55,right=95) # Zoom in for the high ages\n\"\"\"\nIt may look like there is a high amount of people 80+ clumped on the right for Vim\/Emacs users. However, if you remember that I just sampled from a random uniform distribution, then the actual values for these numbers don't matter and what matters more is the threshold of '70+' (Try changing the random seed and see how this plot changes!).\n\nIn fact, from this plot it appears that within this small cohort, the Vim\/Emacs users have proportionately fewer people aged 60+ than non-Vim\/Emacs users.\n\"\"\"\n\"\"\"\n## Hypothesis 1 Conclusion\n\nGiven the kernel density plots, I conclude that the Vim\/Emacs users are not the hoary legends I originally believed them to be. Remember, this only applies to those participants who filled out the Kaggle survey; therefore this population may not represent the entire population of people aged 60+ who use text editors.\n\nWhat is most interesting to me is that the proportion of people aged 30-60 is higher for Vim\/Emacs people than non-Vim\/Emacs people, yet this is not true for people aged 60+. How can we explain this? Well, it takes many years to get used to these text editors due to their learning curve, and many young Kagglers simply don't have the time\/effort to learn a new text editor when there are much more important things to learn (for example, I'd rather young people learn Deep Learning than learn to use an old text editor). But why are there proportionately fewer people aged 60+? Maybe because most of these people take on manager roles\/no longer code due to their experience. Therefore they don't need to use something so technical like a text editor within the terminal but instead can rely on using more agreeable software (like Notepad or Microsoft Word).\n\nSince the hypothesis originally stated that \"very old\" people use Vim\/Emacs, I reject this and instead claim that people who use Vim\/Emacs are more likely to be 30-60 than non-Vim\/Emacs users.\n\"\"\"\n\"\"\"\n# Hypothesis 2\n\nHypothesis 2: Vim\/Emacs users almost exclusively use servers\/cloud services (since many times when you SSH into a server, you may only have access to the terminal; there is often no ability for you to launch an application like Notepad). This hypothesis is mainly based on my own experience. Namely, why would I use Vim\/Emacs when I can use something that supports a mouse like Atom or Sublime Text? The only reason I would use Vim\/Emacs is if I'm forced to because I'm SSHed into a terminal and I can't launch an application from there. \n\nTo explore this, we will look at the \"Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?\" question (because high cloud usage requires high spending on cloud computing products). Additionally, we will look at the question \"What is the primary tool that you use at work or school to analyze data?\" for people who responded with a non-Jupyter notebook answer to 'Cloud-based data software & APIs (AWS, GCP, Azure, etc.)'. Additionally, we will look at the question \"Which of the following cloud computing platforms do you use on a regular basis?\" and look at the bias for people who answered 'None' versus answering with something else (e.g. GCP, AWS, Microsoft Azure, etc.)\n\"\"\"\n\"\"\"\nFirst, let's explore the \"how much money\" question. Like last time, we need to replace the categorical range values with numerical column of np.random.uniform\n\"\"\"\nnp.random.seed(2019)\ndf_2019['cloud_money'] = 0 # Initialize numerical column\ndf_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$1-$99', 'cloud_money'] = np.random.uniform(low=1,high=100,size=df_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$1-$99'].shape[0])\ndf_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$100-$999', 'cloud_money'] = np.random.uniform(low=100,high=1000,size=df_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$100-$999'].shape[0])\ndf_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$1000-$9,999', 'cloud_money'] = np.random.uniform(low=1000,high=10000,size=df_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$1000-$9,999'].shape[0])\ndf_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$10,000-$99,999', 'cloud_money'] = np.random.uniform(low=10000,high=100000,size=df_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='$10,000-$99,999'].shape[0])\ndf_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='> $100,000 ($USD)', 'cloud_money'] = np.random.uniform(low=100000,high=200000,size=df_2019.loc[df_2019['Approximately how much money have you spent on machine learning and\/or cloud computing products at your work in the past 5 years?']=='> $100,000 ($USD)'].shape[0])\nax = sns.kdeplot(df_2019.loc[~df_2019['vim\/emacs_user'],'cloud_money'], shade=True, color='blue', label='Non-Vim\/Emacs')\nsns.kdeplot(df_2019.loc[df_2019['vim\/emacs_user'], 'cloud_money'], shade=True, color='orange', label='Vim\/Emacs', ax=ax)\n\"\"\"\nWow! Can see that so many Vim\/Emacs users actually have spent 0 dollars in the past 5 years on ML\/cloud computing products. That is kind of unexpected.\n\"\"\"\n\"\"\"\nWhat about the cloud services? I expect the majority of them NOT to use Notebook services.\n\"\"\"\n# Some questions are text responses which therefore require a lookup into the 'other_text_responses.csv'\ntext_responses = pd.read_csv('..\/input\/kaggle-survey-2019\/other_text_responses.csv')\ntext_responses.columns = text_responses.iloc[0]\ntext_responses=text_responses.drop([0]) # The first row just contains the column names, so we can drop it.\ndf_2019['What is the primary tool that you use at work or school to analyze data? (Include text response) - Cloud-based data software & APIs (AWS, GCP, Azure, etc.) - Text'] = text_responses['What is the primary tool that you use at work or school to analyze data? (Include text response) - Cloud-based data software & APIs (AWS, GCP, Azure, etc.) - Text'].astype(str).str.upper()\n# View the responses sorted by popularity\ndf_2019.loc[df_2019['vim\/emacs_user'], 'What is the primary tool that you use at work or school to analyze data? (Include text response) - Cloud-based data software & APIs (AWS, GCP, Azure, etc.) - Text'].value_counts()\n\"\"\"\nInterestingly, the majority of responses are NAN (indicating that they do not use cloud services). That is honestly shocking - that means that many of the Vim\/Emacs users are actually using it locally! Wow!\n\nFurthermore, we can see from the responses that there are many Notebook-based options that people have responded with: GOOGLE COLAB, AWS SAGEMAKER, JUPYTER NOTEBOOK, and JUPYTER LAB.\n\nThe final response, \"AZURE - UNFORTUNATELY\" is absolutely hilarious. Come on, what's so bad? Granted, I am an AWS\/GCP user, and I have used Azure once in my life, so maybe I have never been exposed to the \"unfortunate\" sides of it \ud83d\ude02\n\"\"\"\n\"\"\"\nFinally, let's look at the question \"Which of the following cloud computing platforms do you use on a regular basis?\" and look for bias of people answering None versus not. As we saw in the previous question, it actually appears that the overwhelming majority of Vim\/Emacs users do NOT use cloud services. Let's verify.\n\"\"\"\ndf_2019['uses_cloud_compute'] = ((df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Google Cloud Platform (GCP) '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Amazon Web Services (AWS) '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Microsoft Azure '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  IBM Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Alibaba Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Salesforce Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Oracle Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  SAP Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  VMware Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice -  Red Hat Cloud '].notnull()) |\n                                 (df_2019['Which of the following cloud computing platforms do you use on a regular basis? (Select all that apply) - Selected Choice - Other'].notnull())\n                                )   \n# The percentage of people who use cloud compute, grouped by if they use Vim\/Emacs or not.\ndf_2019.groupby('vim\/emacs_user')['uses_cloud_compute'].mean().to_frame('Probability of Using Cloud Compute').reset_index()\n\"\"\"\nFirst of all, we can see that Vim\/Emacs users are far more likely to use cloud services than non-Vim\/Emacs users (more than twice as likely!) However, we can still see that the majority of Vim\/Emacs users do not use the cloud. This is still extremely surprising because in my use cases, Vim\/Emacs are only used when SSHing into a cloud server. Yet these results imply more than half of all Vim\/Emacs users use it locally!\n\"\"\"\n\"\"\"\n## Hypothesis 2 Conclusion\nHypothesis 2 believed that people who use Vim\/Emacs almost exclusively use serves\/cloud services. We instead discover that 46.8% of Vim\/Emacs users actually use cloud computing platforms on a regular basis. The majority of them do not! However, to be fair, the probability of using cloud services for Vim\/Emacs users is more than twice as much as the probability of using cloud services for non-Vim\/Emacs users. This implies that Vim\/Emacs users are biased to use cloud services in comparison to the rest of the population.\n\nIt was also very surprising to see from the kernel density plot that Vim\/Emacs users rarely spend money for cloud purposes. Given the probability of using cloud services is more than twice as high as non-Vim\/Emacs users, I would have thought that they spend more money too, but it appears not to be the case.\n\"\"\"\n\"\"\"\n# Hypothesis 3\nHypothesis 3: Vim\/Emacs users likely write code for the majority of their work day and do not hold manager positions but instead are full-time programmers. This is mainly because people who use Vim\/Emacs learned all the keyboard shortcuts to code faster; therefore, they likely have enjoyed programming their whole life and don't want to give it up for a managerial position.\n\nTo look at this, we will study the \"Select the title most similar to your current role (or most recent title if retired)\" question. Let's investigate!\n\"\"\"\n# Impute the Other with the freeform text\ndf_2019['Select the title most similar to your current role (or most recent title if retired): - Other - Text'] = text_responses['Select the title most similar to your current role (or most recent title if retired): - Other - Text'].astype(str).str.upper()\nvc_vim = df_2019.loc[df_2019['vim\/emacs_user'], 'Select the title most similar to your current role (or most recent title if retired): - Selected Choice'].value_counts(normalize=True)\nvc_notvim = df_2019.loc[~df_2019['vim\/emacs_user'], 'Select the title most similar to your current role (or most recent title if retired): - Selected Choice'].value_counts(normalize=True)\n\nw = pd.DataFrame(data = [vc_vim, vc_notvim],index = ['Vim\/Emacs','Non-Vim\/Emacs'])\n\nax = w.T[['Non-Vim\/Emacs']].plot(subplots=True, layout=(1,1),kind='bar',color='blue',linewidth=1,edgecolor='k',legend=True, label='Non-Vim\/Emacs',alpha=0.25)\nw.T[['Vim\/Emacs']].plot(subplots=True, layout=(1,1),kind='bar',color='orange',linewidth=1,edgecolor='k',legend=True, label='Vim\/Emacs',alpha=0.25, ax=ax)\n\nplt.gcf().set_size_inches(10,8)\nplt.title('Job Title of Vim\/Emacs users vs. non-Vim\/Emacs users',fontsize=15)\nplt.xticks(rotation=45,fontsize='10', horizontalalignment='right')\nplt.yticks( fontsize=10)\nplt.xlabel('Job Title',fontsize=15)\nplt.ylabel('Percentage of Users',fontsize=15)\nplt.show()\n\"\"\"\n## Hypothesis 3 Conclusion\nFrom this bar plot we can see that Vim\/Emacs users are more likely to be Data Scientists, Software Engineers, Research Scientists, Data Engineers, and DBA\/Database Engineers (which are all NOT managerial roles). We can see that the proportion of Product\/Project Manager and Business Analyst (both of which are considered \"high-level\" roles) is higher for Non-Vim\/Emacs users.\n\nTherefore the hypothesis that Vim\/Emacs users hold more technical positions than managerial ones is true, and furthermore they hold more technical positions proportionately than non-Vim\/Emacs users!\n\"\"\"\n\"\"\"\nSo, after reading this kernel, are you going to learn to use Vim\/Emacs? Or maybe you already use it? Personally, I find the ease of Jupyter Noteboks to be so amazing that I don't think I could ever go back to using a text editor, or even an IDE, full-time. Maybe I'll change my mind when I enter the 30-60 age range, though :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '7b9ec3f0333173'}"}
{"id":"25018","text":"\"\"\"\n## Process Data\n\"\"\"\nimport os\nprint(os.listdir('..\/input\/555555'))\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimg = Image.open('..\/input\/555555\/photo.jpg')\nimg = img.resize((224,224))\nplt.imshow(img)\nimport numpy as np\ntest_x = np.array(img) \/ 255.0\nprint(test_x.shape)\ntest_x = test_x.reshape(1,224,224,3)\n\"\"\"\n## Load Model\n\"\"\"\n# Import Model\n#from tensorflow.keras.applications import VGG16\n#from tensorflow.keras.applications import ResNet101V2\nfrom tensorflow.keras.applications import InceptionV3\n\n#from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions\n#from tensorflow.keras.applications.resnet import preprocess_input, decode_predictions\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions\n\n# Load Model\n#model = VGG16(weights='imagenet')\n#model = ResNet101V2(weights='imagenet')\nmodel = InceptionV3(weights='imagenet')\n\"\"\"\n## Prediction\n\"\"\"\n# model prediction\npreds = model.predict(test_x)\n# decode prediction\ndec_preds =  decode_predictions(preds, top=3)[0]\nprint('Predicted:', dec_preds)","meta":"{'source': 'AI4Code', 'id': '2e011883a17927'}"}
{"id":"92984","text":"import numpy as np\nimport pandas as pd \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom gensim.models import Word2Vec\nfrom sklearn.model_selection import KFold\nimport numpy as np\nfrom tqdm import tqdm\nimport os,logging,pickle,random\nfrom sklearn import metrics as skmetrics\nimport warnings\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# from torch import nn as nn\n# from torch.nn import functional as F\n# import torch,time,os\nwarnings.filterwarnings(\"ignore\")\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.constraints import max_norm\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers import Input, Dense, Dropout, Flatten, Activation\nfrom tensorflow.keras.layers import Conv1D, Add, MaxPooling1D, BatchNormalization\nfrom tensorflow.keras.layers import Embedding, Bidirectional, GlobalMaxPooling1D\nfrom tensorflow.compat.v1.keras.layers import CuDNNLSTM\nimport tensorflow as tf\ngpus = tf.config.list_physical_devices(device_type='GPU')\ncpus = tf.config.list_physical_devices(device_type='CPU')\nprint(gpus, cpus)\ndata = pd.read_csv(\"..\/input\/protein-dataset\/train.csv\")\ndf_test = pd.read_csv(\"..\/input\/protein-dataset\/test_withid.csv\")\ndata[\"sequence\"] = data[\"xulie\"].apply(lambda x : x.upper())\ndf_test[\"sequence\"] = df_test[\"xulie\"].apply(lambda x : x.upper())\ndata[\"seqLen\"] = data[\"xulie\"].apply(lambda x : len(x))\ndf_test[\"seqLen\"] = df_test[\"xulie\"].apply(lambda x : len(x))\ndf_test.head()\ndef integer_encoding(data):\n    \"\"\"\n    - Encodes code sequence to integer values.\n    - 20 common amino acids are taken into consideration\n    and rest 4 are categorized as 0.\n    \"\"\"\n\n    encode_list = []\n    for row in data['sequence'].values:\n        row_encode = []\n        for code in row:\n            row_encode.append(char_dict.get(code, 0))\n        encode_list.append(np.array(row_encode))\n\n    return encode_list\nitemCounter = {}\nfor seq in data[\"sequence\"]:\n    for i in seq:\n        itemCounter[i] = itemCounter.get(i,0)+1\ncodes = list(itemCounter.keys())\ncodes.sort()\ncodes\ndef create_dict(codes):\n    char_dict = {}\n    for index, val in enumerate(codes):\n        char_dict[val] = index+1\n\n    return char_dict\n\nchar_dict = create_dict(codes)\n\nprint(char_dict)\nprint(\"Dict Length:\", len(char_dict))\nmax_length = 300\ndata_encode = integer_encoding(data)\ndata_pad = pad_sequences(data_encode, maxlen=max_length, padding='post', truncating='post')\ndata_ohe = to_categorical(data_pad, 23)\ndata_ohe.shape\n\"\"\"\n## \u5e8f\u5217\u957f\u5ea6\u5206\u5e03\n\"\"\"\ndef plot_seq_count(df, data_name):\n    sns.distplot(df['seqLen'].values)\n    plt.title(f'Sequence char count: {data_name}')\n    plt.grid(True)\nplt.subplot(1, 2, 1)\nplot_seq_count(data, 'Train')\n\nplt.subplot(1, 2, 2)\nplot_seq_count(df_test, 'Test')\n\nplt.subplots_adjust(right=3.0)\nplt.show()\n\"\"\"\n## \u6a21\u578b1 \u53cc\u5411LSTM\n\"\"\"\n# \u53cc\u5411LSTM\ndef BiLSTM():  \n    x_input = Input(shape=(max_length,))\n    emb = Embedding(23, 128, input_length=max_length)(x_input)\n    bi_rnn = Bidirectional(CuDNNLSTM(64, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01), bias_regularizer=l2(0.01)))(emb)\n    x = Dropout(0.3)(bi_rnn)\n\n    # softmax \n    x_output = Dense(245, activation='softmax')(x)\n\n    model1 = Model(inputs=x_input, outputs=x_output)\n    return model1\n    \n\n#model1.summary()\n\"\"\"\n## \u6a21\u578b2 ProtCNN\n\"\"\"\ndef residual_block(data, filters, d_rate):\n    \"\"\"\n    _data: input\n    _filters: convolution filters\n    _d_rate: dilation rate\n    \"\"\"\n\n    shortcut = data\n\n    bn1 = BatchNormalization()(data)\n    act1 = Activation('relu')(bn1)\n    conv1 = Conv1D(filters, 1, dilation_rate=d_rate, padding='same', kernel_regularizer=l2(0.001))(act1)\n\n    #bottleneck convolution\n    bn2 = BatchNormalization()(conv1)\n    act2 = Activation('relu')(bn2)\n    conv2 = Conv1D(filters, 3, padding='same', kernel_regularizer=l2(0.001))(act2)\n\n    #skip connection\n    x = Add()([conv2, shortcut])\n\n    return x\n\n# model\n\ndef ProtCNN():    \n    #Input(shape=(100, 21))\n    x_input = Input(shape=(max_length, 23))\n\n    #initial conv\n    conv = Conv1D(128, 1, padding='same')(x_input) \n\n    # per-residue representation\n    res1 = residual_block(conv, 128, 2)\n    res2 = residual_block(res1, 128, 3)\n\n    x = MaxPooling1D(3)(res2)\n    x = Dropout(0.5)(x)\n\n    # softmax classifier\n    x = Flatten()(x)\n    x_output = Dense(245, activation='softmax', kernel_regularizer=l2(0.0001))(x)\n\n    model2 = Model(inputs=x_input, outputs=x_output)\n    return model2\n#odel2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n#odel2.summary()\nload_model(self.saved_model, custom_objects={\"f1_score \": f1_score })\nfrom keras.models import load_model\ndef generate_submission(model_name):\n    model = load_model(f'.\/model_{model_name}\/model_{model_name}.h5', custom_objects={\"f1\": f1 })\n    test_encode = integer_encoding(df_test)\n    test_pad = pad_sequences(test_encode, maxlen=max_length, padding='post', truncating='post')\n    test_ohe = to_categorical(test_pad, 23)\n    if \"LSTM\" in model_name:\n        y_pred = model.predict(test_pad,batch_size = 256)\n    else:\n        y_pred = model.predict(test_ohe,batch_size = 256)\n    a = np.argmax(y_pred, axis=1)\n    final_pred = le.inverse_transform(a.reshape(-1, 1))\n    ans = []\n    for i in list(final_pred):\n        ans.append(i.strip()[0] + \".\" + i.strip()[1:])\n    df_test[\"category_id\"] = ans\n    output = df_test[[\"sample_id\", \"category_id\"]]\n    output.to_csv(f\"submission_{model_name}.csv\", index = None)\nle = LabelEncoder()\nle.fit(data[\"label\"])\ny = le.transform(data[\"label\"])\ny = to_categorical(y)\n#y[trainIdList].shape\n\"\"\"\n## \u6a21\u578b1\u8bad\u7ec3\uff08\u672a\u8fdb\u884c\u6a21\u578b\u4fdd\u5b58\u548c\u6d4b\u8bd5\u96c6\u63a8\u65ad\uff09\n\"\"\"\nimport os\ndef create_dir_not_exist(path):\n    if not os.path.exists(path):\n        os.mkdir(path)\ncreate_dir_not_exist(\".\/model_BiLSTM\")\ncreate_dir_not_exist(\".\/model_ProtCNN\")\nfrom tensorflow.keras import backend as K\n\ndef f1(y_true, y_pred):\n    def recall(y_true, y_pred):\n        \"\"\"Recall metric.\n\n        Only computes a batch-wise average of recall.\n\n        Computes the recall, a metric for multi-label classification of\n        how many relevant items are selected.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n        recall = true_positives \/ (possible_positives + K.epsilon())\n        return recall\n\n    def precision(y_true, y_pred):\n        \"\"\"Precision metric.\n\n        Only computes a batch-wise average of precision.\n\n        Computes the precision, a metric for multi-label classification of\n        how many selected items are relevant.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n        precision = true_positives \/ (predicted_positives + K.epsilon())\n        return precision\n    precision = precision(y_true, y_pred)\n    recall = recall(y_true, y_pred)\n    return 2*((precision*recall)\/(precision+recall+K.epsilon()))\nmodel_name = \"BiLSTM\"\ntest_encode = integer_encoding(df_test)\ntest_pad = pad_sequences(test_encode, maxlen=max_length, padding='post', truncating='post')\ntest_ohe = to_categorical(test_pad, 23)\nif \"LSTM\" in model_name:\n    y_pred = model.predict(test_pad,batch_size = 256)\nelse:\n    y_pred = model.predict(test_ohe,batch_size = 256)\na = np.argmax(y_pred, axis=1)\nfinal_pred = le.inverse_transform(a.reshape(-1, 1))\nans = []\nfor i in list(final_pred):\n    ans.append(i.strip()[0] + \".\" + i.strip()[1:])\ndf_test[\"category_id\"] = ans\noutput = df_test[[\"sample_id\", \"category_id\"]]\noutput.to_csv(f\"submission_{model_name}.csv\", index = None)\nkf = KFold(n_splits=30)\nhistories = []\nle = LabelEncoder()\ny = le.fit_transform(data[\"label\"])\ny = to_categorical(y)\nmax_length = 300 # \u6307\u5b9a\u5e8f\u5217\u957f\u5ea6\nmodel = BiLSTM()\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', f1])\nfor fold_id, (trainIdList, validIdList) in enumerate(kf.split(data)):\n    print(f\"==============Fold{fold_id}==================\")\n    print(\"TRAIN:\", len(trainIdList), \"TEST:\", len(validIdList))\n    \n    df_train = data.iloc[trainIdList]\n    df_val = data.iloc[validIdList]\n    df_train['seq_char_count']= df_train['sequence'].apply(lambda x: len(x))\n    df_val['seq_char_count']= df_val['sequence'].apply(lambda x: len(x))\n    \n    train_encode = integer_encoding(df_train)\n    val_encode = integer_encoding(df_val) \n\n    train_pad = pad_sequences(train_encode, maxlen=max_length, padding='post', truncating='post')\n    val_pad = pad_sequences(val_encode, maxlen=max_length, padding='post', truncating='post')\n    \n    train_ohe = to_categorical(train_pad, 23)\n    val_ohe = to_categorical(val_pad, 23)\n    \n    y_train = y[trainIdList]\n    y_val = y[validIdList]\n\n    es = EarlyStopping(monitor='val_loss', patience=50, verbose=1)\n    history1 = model.fit(\n        train_pad, y_train,\n        epochs=300, batch_size=256,\n        validation_data=(val_pad, y_val),\n        callbacks=[es]\n        )\n    histories.append(history1)\nmodel.save(f'.\/model_BiLSTM\/model_BiLSTM.h5')\ngenerate_submission(\"BiLSTM\")\nkf = KFold(n_splits=30)\nhistories = []\nle = LabelEncoder()\ny = le.fit_transform(data[\"label\"])\ny = to_categorical(y)\nmax_length = 300 # \u6307\u5b9a\u5e8f\u5217\u957f\u5ea6\nmodel = ProtCNN()\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', f1])\nfor fold_id, (trainIdList, validIdList) in enumerate(kf.split(data)):\n    print(f\"==============Fold{fold_id}==================\")\n    print(\"TRAIN:\", len(trainIdList), \"TEST:\", len(validIdList))\n    \n    \n    df_train = data.iloc[trainIdList]\n    df_val = data.iloc[validIdList]\n    df_train['seq_char_count']= df_train['sequence'].apply(lambda x: len(x))\n    df_val['seq_char_count']= df_val['sequence'].apply(lambda x: len(x))\n    \n    train_encode = integer_encoding(df_train)\n    val_encode = integer_encoding(df_val) \n\n    train_pad = pad_sequences(train_encode, maxlen=max_length, padding='post', truncating='post')\n    val_pad = pad_sequences(val_encode, maxlen=max_length, padding='post', truncating='post')\n    \n    train_ohe = to_categorical(train_pad, 23)\n    val_ohe = to_categorical(val_pad, 23)\n    \n    y_train = y[trainIdList]\n    y_val = y[validIdList]\n\n    es = EarlyStopping(monitor='val_loss', patience=5, verbose=1)\n    history1 = model.fit(\n        train_ohe, y_train,\n        epochs=20, batch_size=256,\n        validation_data=(val_ohe, y_val),\n        callbacks=[es]\n        )\n    histories.append(history1)\nmodel.save(f'.\/model_ProtCNN\/model_ProtCNN.h5')\ngenerate_submission(\"ProtCNN\")\n# model = load_model(f'.\/model_BiLSTM\/model_ProtCNN.h5')\n# test_encode = integer_encoding(df_test)\n# test_pad = pad_sequences(test_encode, maxlen=max_length, padding='post', truncating='post')\n# test_ohe = to_categorical(test_pad, 23)\n# y_pred = model.predict(test_ohe,batch_size = 256)\n# a = np.argmax(y_pred, axis=1)\n# final_pred = le.inverse_transform(a.reshape(-1, 1))\n# ans = []\n# for i in list(final_pred):\n#     ans.append(i.strip()[0] + \".\" + i.strip()[1:])\n# df_test[\"category_id\"] = ans\n# output = df_test[[\"sample_id\", \"category_id\"]]\n# output.to_csv(\"submission_pro.csv\", index = None)\n\"\"\"\n## \u6a21\u578b2 ProtCNN\n\"\"\"\n# def residual_block(data, filters, d_rate):\n#     \"\"\"\n#     _data: input\n#     _filters: convolution filters\n#     _d_rate: dilation rate\n#     \"\"\"\n\n#     shortcut = data\n\n#     bn1 = BatchNormalization()(data)\n#     act1 = Activation('relu')(bn1)\n#     conv1 = Conv1D(filters, 1, dilation_rate=d_rate, padding='same', kernel_regularizer=l2(0.001))(act1)\n\n#     #bottleneck convolution\n#     bn2 = BatchNormalization()(conv1)\n#     act2 = Activation('relu')(bn2)\n#     conv2 = Conv1D(filters, 3, padding='same', kernel_regularizer=l2(0.001))(act2)\n\n#     #skip connection\n#     x = Add()([conv2, shortcut])\n\n#     return x\n\n# # model\n\n# def ProtCNN():    \n#     #Input(shape=(100, 21))\n#     x_input = Input(shape=(max_length, 23))\n\n#     #initial conv\n#     conv = Conv1D(128, 1, padding='same')(x_input) \n\n#     # per-residue representation\n#     res1 = residual_block(conv, 128, 2)\n#     res2 = residual_block(res1, 128, 3)\n\n#     x = MaxPooling1D(3)(res2)\n#     x = Dropout(0.5)(x)\n\n#     # softmax classifier\n#     x = Flatten()(x)\n#     x_output = Dense(245, activation='softmax', kernel_regularizer=l2(0.0001))(x)\n\n#     model2 = Model(inputs=x_input, outputs=x_output)\n#     return model2\n# #odel2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# #odel2.summary()","meta":"{'source': 'AI4Code', 'id': 'aaa4d5ccf3800b'}"}
{"id":"82877","text":"import pandas as pd\nimport plotly as py\nimport plotly.graph_objs as go\nimport warnings\nwarnings.filterwarnings(\"ignore\")\npy.offline.init_notebook_mode(connected = True)\nmall_df = pd.read_csv('..\/input\/Mall_Customers.csv')\nmall_df.head()\nprint (mall_df)\nmall_df.shape\nmall_df.columns\nmall_df['Gender'].head()\nmall1_df = mall_df.copy()\nmall1_df.tail(5)\n\"\"\"\nDescriptive statistics of the data\n\"\"\"\nmall_df.describe().transpose()\n#Load the required packages\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Plot styling\nimport seaborn as sns; sns.set()  # for plot styling\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (16, 9)\nplt.style.use('ggplot')\n\"\"\"\nVisualizing the data using \"distplot\"\n\"\"\"\nplot_annual_income = sns.distplot(mall_df[\"Annual Income (k$)\"])\nplot_age = sns.distplot(mall_df[\"Age\"])\nplot_spending_score = sns.distplot(mall_df[\"Spending Score (1-100)\"])\n\"\"\"\nViolin Plot of Annual Income and Spending Score \n\"\"\"\nf, axes = plt.subplots(1,2, figsize=(12,6), sharex=True, sharey=True)\nv1 = sns.violinplot(data=mall_df, x='Annual Income (k$)', color=\"skyblue\",ax=axes[0])\nv2 = sns.violinplot(data=mall_df, x='Spending Score (1-100)',color=\"lightgreen\", ax=axes[1])\nv1.set(xlim=(-20,160))\n# Creating subset\nmall_df_1 = mall_df[['Annual Income (k$)', 'Spending Score (1-100)']]\nmall_df_1.head()\n\"\"\"\nApplying K-Means Clustering to find the target customers\n\"\"\"\nfrom sklearn.cluster import KMeans\n\n#Using the elbow method to find the optimum number of clusters\nwcss = []\nfor i in range(1,11):\n    km=KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0)\n    km.fit(mall_df_1)\n    wcss.append(km.inertia_)\nplt.plot(range(1,11),wcss)\nplt.title('Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('wcss')\nplt.show()\n# So..number of clusters should be 5\nkm5=KMeans(n_clusters=5,init='k-means++', max_iter=300, n_init=10, random_state=0)\ny_means = km5.fit_predict(mall_df_1)\n#Visualizing the clusters\nplt.scatter(mall_df_1[y_means==0]['Annual Income (k$)'],mall_df_1[y_means==0]['Spending Score (1-100)'],s=50, c='purple',label='Cluster1')\nplt.scatter(mall_df_1[y_means==1]['Annual Income (k$)'],mall_df_1[y_means==1]['Spending Score (1-100)'],s=50, c='blue',label='Cluster2')\nplt.scatter(mall_df_1[y_means==2]['Annual Income (k$)'],mall_df_1[y_means==2]['Spending Score (1-100)'],s=50, c='green',label='Cluster3')\nplt.scatter(mall_df_1[y_means==3]['Annual Income (k$)'],mall_df_1[y_means==3]['Spending Score (1-100)'],s=50, c='cyan',label='Cluster4')\nplt.scatter(mall_df_1[y_means==4]['Annual Income (k$)'],mall_df_1[y_means==4]['Spending Score (1-100)'],s=50, c='magenta',label='Cluster5')\n\nplt.scatter(km5.cluster_centers_[:,0], km5.cluster_centers_[:,1],s=200,marker='s', c='red', alpha=0.7, label='Centroids')\nplt.title('Customer segments')\nplt.xlabel('Annual income of customer (k$)')\nplt.ylabel('Customer: Spending Score (1-100)')\nplt.legend()\nplt.show()\n\"\"\"\nClustering with 3 variables: Age, Annual Income (k$) and Spending Score (1-100) \n\"\"\"\n# Creating subset\nmall_df_2 = mall_df[['Age', 'Annual Income (k$)', 'Spending Score (1-100)']]\nmall_df_2.head()\n#Using the elbow method to find the optimum number of clusters\nwcss = []\nfor i in range(1,11):\n    km=KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0)\n    km.fit(mall_df_2)\n    wcss.append(km.inertia_)\nplt.plot(range(1,11),wcss)\nplt.title('Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('wcss')\nplt.show()\n\"\"\"\nHence, the optimum number of clusters = 6 (Elbow Method: Above)\n\"\"\"\nkm6 = (KMeans(n_clusters = 6 ,init='k-means++', n_init = 10 ,max_iter=300, \n                        tol=0.0001,  random_state= 111  , algorithm='elkan') )\nkm6.fit(mall_df_2)\nlabels = km6.labels_\ncentroids = km6.cluster_centers_\nmall_df_2['labels'] =  labels\ntrace1 = go.Scatter3d(\n    x= mall_df_2['Age'],\n    y= mall_df_2['Spending Score (1-100)'],\n    z= mall_df_2['Annual Income (k$)'],\n    mode='markers',\n     marker=dict(\n        color = mall_df_2['labels'], \n        size= 20,\n        line=dict(\n            color= mall_df_2['labels'],\n            width= 12\n        ),\n        opacity=0.8\n     )\n)\ndata = [trace1]\nlayout = go.Layout(\n    title= 'Clusters',\n    scene = dict(\n            xaxis = dict(title  = 'Age'),\n            yaxis = dict(title  = 'Spending Score'),\n            zaxis = dict(title  = 'Annual Income')\n        )\n)\nfig = go.Figure(data=data, layout=layout)\npy.offline.iplot(fig)\n","meta":"{'source': 'AI4Code', 'id': '9827a50a93f20f'}"}
{"id":"132009","text":"\"\"\"\n## <font color='blue'>Loading of Notebook might take some time because of Plotly visualizations. Kindly be patient!!!<\/font>\n\"\"\"\n\"\"\"\n# <center><font color='red'>COVID_19 Analysis ( \u0939\u093e\u0930\u0947\u0917\u093e Corona, \u092e\u0941\u0938\u094d\u0915\u0941\u0930\u093e\u090f\u0917\u093e World )<\/font><\/center>\n\"\"\"\nfrom IPython.display import Image\nImage(filename='\/kaggle\/input\/worldcoronav\/jobs-in-the-time-of-covid-19.jpg', width=\"800\", height='50')\n\"\"\"\nCoronavirus is a family of viruses that can cause illness, which can vary from common cold and cough to sometimes more severe disease. Middle East Respiratory Syndrome (MERS-CoV) and Severe Acute Respiratory Syndrome (SARS-CoV) were such severe cases with the world already has faced.\nSARS-CoV-2 (n-coronavirus) is the new virus of the coronavirus family, which first discovered in 2019, which has not been identified in humans before. It is a contiguous virus which started from Wuhan in December 2019. Which later declared as Pandemic by WHO due to high rate spreads throughout the world. Currently (on the date 15 May 2020), this leads to a total of 300K+ Deaths across the globe, including 159K+ deaths alone in Europe.\nPandemic is spreading all over the world; it becomes more important to understand about this spread. This NoteBook is an effort to analyze the cumulative data of confirmed, deaths, and recovered cases over time. In this notebook, the main focus is to analyze the spread trend of this virus all over the world.\n\"\"\"\n\"\"\"\n#### Refence of this project : \nBlogs, Kernal & Youtube\n\"\"\"\n\"\"\"\n# <font color='blue'>Table of Content<\/font>\n- Importing the Important Library\n\n- Importing the dataset\n\n- Data Cleaning\n\n- Worldwide total Confiremed, Recovered and Deaths\n\n- Case Density Animation on World Map\n\n- Total Cases on ships\n\n- Case Over the Time with Area Plot\n\n- Folium Maps\n\n- Confirmed Cases with Choropleth Map\n\n- Deaths and Recoveries Cases\n\n- Confirmed and Death Cases with static colormaps\n\n- New Caes and Number of Countries\n\n- Top 15 Countries Case Analysis\n\n- Scatter plot for Deaths VS Confirmed Cases\n\n- Confirmed, Deaths New Cases Vs Country and Date.\n\n    - Bar Plot\n    - Line Plot\n \n - Check Groth Rate of Case\n     - Groth Rate After 100 Cases\n     - Groth Rate After 1000 Cases\n     - Groth Rate After 10000 Cases\n     - Groth Rate After 100K Cases\n \n - Tree Map Analysis\n     - Confirmed Cases\n     - Deaths Caes\n\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport plotly as py\n# py.offline.init_notebook_mode(connected = True)\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.figure_factory as ff\nfrom plotly.subplots import make_subplots\nimport folium\nimport math\nimport random\nfrom datetime import timedelta\nimport warnings\nwarnings.filterwarnings('ignore')\n# Color pallatte\ncnf = '#393e46'\ndth = '#ff2e63'\nrec = '#21bf73'\nact = '#fe9801'\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\n\"\"\"\n**Load the dataset**\n\"\"\"\ncountry_day_wise = pd.read_csv(\"\/kaggle\/input\/covid-19\/country_daywise.csv\", parse_dates = ['Date'])\ncountry_wise = pd.read_csv(\"\/kaggle\/input\/covid-19\/countrywise.csv\")\nday_wise = pd.read_csv(\"\/kaggle\/input\/covid-19\/daywise.csv\", parse_dates = ['Date'])\ncovid_19 = pd.read_csv(\"\/kaggle\/input\/covid-19\/covid_19_data_cleaned.csv\", parse_dates = ['Date'])\ncovid_19.head(5)\n# , parse_dates = ['Date']\n\"\"\"\n### Data Cleaning\n\"\"\"\ncovid_19.isnull().sum()\ncovid_19['Province\/State'].value_counts()\n# Filling missing values.\ncovid_19['Province\/State'] = covid_19['Province\/State'].fillna(\"\")\ncovid_19.head()\nConfirmed = covid_19.groupby('Date').sum()['Confirmed'].reset_index()\nRecovered = covid_19.groupby('Date').sum()['Recovered'].reset_index()\nDeaths = covid_19.groupby('Date').sum()['Deaths'].reset_index()\nActive = covid_19.groupby('Date').sum()['Active'].reset_index()\ncovid_19.info()\ncovid_19.query('Country == \"US\"')\ncovid_19.query('Country == \"Afghanistan\"')\n\"\"\"\n# Worldwide total Confiremed, Recovered and Deaths\n\"\"\"\nConfirmed.tail()\nRecovered.tail()\nActive.tail()\nDeaths.tail()\nfig = go.Figure()\nfig.add_trace(go.Scatter(x = Confirmed['Date'], y = Confirmed['Confirmed'], mode = 'lines+markers', name = 'Confirmed Cases', line = dict(color='Orange')))\nfig.add_trace(go.Scatter(x = Recovered['Date'], y = Recovered['Recovered'], mode = 'lines+markers', name = 'Recovred Cases', line = dict(color='Green')))\nfig.add_trace(go.Scatter(x = Active['Date'], y = Active['Active'], mode = 'lines+markers', name = 'Active Cases', line = dict(color='blue')))\nfig.add_trace(go.Scatter(x = Deaths['Date'], y = Deaths['Deaths'], mode = 'lines+markers', name = 'Deaths Cases', line = dict(color='Red')))\nfig.update_layout(title='Worldwide Covid 19 Casess', xaxis_tickfont_size = 14, yaxis = dict(title = 'Number of Cases'))\nfig.show()\n\n\"\"\"\n# Case Density Animation on World Map\n\"\"\"\ncovid_19.info()\n# Change Date foramt to string format\ncovid_19['Date']  = covid_19['Date'].astype(str)\ncovid_19.info()\n# Use plotly Express\nfig = px.density_mapbox(covid_19, lat = 'Lat', lon = 'Long', hover_name = 'Country', hover_data = ['Confirmed', 'Recovered', 'Deaths'], animation_frame = 'Date', color_continuous_scale = 'Portland', radius = 7, zoom = 0, height=700)\nfig.update_layout(title = 'Worldwide Covid_19 Cases with Time Laps')\nfig.update_layout(mapbox_style = 'open-street-map', mapbox_center_lon = 0)\nfig.show()\n\"\"\"\n# Total Cases on ships\n\"\"\"\n# Change string into Datetime format\ncovid_19['Date'] = pd.to_datetime(covid_19['Date'])\ncovid_19.info()\n# Ships\n# ==================\n# Find out all Grand Princess\nship_rows = covid_19['Province\/State'].str.contains('Grand Princess') | covid_19['Province\/State'].str.contains('Diamond Princess') | covid_19['Country'].str.contains('Grand Princess') | covid_19['Country'].str.contains('Diamond Princess') | covid_19['Country'].str.contains('MS Zaandam') \nship = covid_19[ship_rows]\n\ncovid_19 = covid_19[~ship_rows]\nship_latest = ship[ship['Date'] == max(ship['Date'])]\nship_latest\nship_latest.style.background_gradient(cmap = 'Pastel1_r')\n\"\"\"\n# Case Over the Time with Area Plot\n\"\"\"\ntemp = covid_19.groupby('Date')['Confirmed', 'Deaths', 'Recovered', 'Active'].sum().reset_index()\ntemp = temp[temp['Date']==max(temp['Date'])].reset_index(drop=True)\n\ntm = temp.melt(id_vars = 'Date', value_vars = ['Active', 'Deaths', 'Recovered'])\nfig = px.treemap(tm, path = ['variable'],values = 'value', height=250, width = 800, color_discrete_sequence=[act, rec, dth])\n\nfig.data[0].textinfo = 'label+text+value'\nfig.show()\n# temp = covid_19.groupby('Date').sum()\ntemp = covid_19.groupby('Date')['Recovered', 'Deaths','Active'].sum().reset_index()\ntemp = temp.melt(id_vars = 'Date', value_vars = ['Recovered', 'Deaths','Active'], var_name = 'Case', value_name = 'Count')\n\nfig = px.area(temp, x='Date', y='Count', color='Case', height=600, title='Cases over time', color_discrete_sequence=[act, rec, dth])\nfig.update_layout(xaxis_rangeslider_visible = True)\nfig.show()\n\"\"\"\n# Folium Maps\n\"\"\"\n# World wide map Cases on Folium Maps\n\n\ntemp = covid_19[covid_19['Date']==max(covid_19['Date'])]  # Latest Data Show\nm = folium.Map(location=[0,0], tiles='cartodbpositron', min_zoom = 1, max_zoom = 4, zoom_start = 1)\nfor i in range(0, len(temp)):\n    folium.Circle(location= [temp.iloc[i]['Lat'],temp.iloc[i]['Long']], color = 'crimson', fill = 'crimson',\n                 tooltip =  '<li><bold> Country: ' + str(temp.iloc[i]['Country'])+\n                            '<li><bold> Province: ' + str(temp.iloc[i]['Province\/State'])+\n                            '<li><bold> Confirmed: ' + str(temp.iloc[i]['Confirmed'])+\n                            '<li><bold> Deaths: ' + str(temp.iloc[i]['Deaths']),\n                 radius = int(temp.iloc[i]['Confirmed'])**0.5).add_to(m)\nm\n\n\n\"\"\"\n# Confirmed Cases with Choropleth Map\n\"\"\"\ncountry_day_wise.head(5)\nfig = px.choropleth(country_day_wise, locations = 'Country', locationmode = 'country names', color = np.log(country_day_wise['Confirmed']),\n                   hover_name = 'Country', animation_frame = country_day_wise['Date'].dt.strftime('%Y-%m-%d'),\n                   title = 'Cases Over Time', color_continuous_scale = px.colors.sequential.Inferno)\n\nfig.update(layout_coloraxis_showscale = True)\nfig.show()\n\"\"\"\n# Deaths and Recoveries Cases\n\"\"\"\nday_wise.head()\nfig_c = px.bar(day_wise, x = 'Date', y='Confirmed', color_discrete_sequence=[act])\nfig_d = px.bar(day_wise, x = 'Date', y='Deaths', color_discrete_sequence=[dth])\n\nfig = make_subplots(rows=1, cols=2, shared_xaxes=False, horizontal_spacing=0.1,\n                  subplot_titles=('Confirmed Cases', 'Death Cases'))\n\nfig.add_trace(fig_c['data'][0], row=1, col=1)\nfig.add_trace(fig_d['data'][0], row=1, col=2)\nfig.update_layout(height=400)\nfig.show()\n\"\"\"\n# Confirmed and Death Cases with static colormaps\n\"\"\"\nfig_c = px.choropleth(country_wise, locations='Country', locationmode='country names',\n                     color = np.log(country_wise['Confirmed']), hover_name = 'Country',\n                     hover_data = ['Confirmed'])\ntemp = country_wise[country_wise['Deaths']>0]\nfig_d = px.choropleth(temp, locations='Country', locationmode='country names',\n                     color = np.log(temp['Deaths']), hover_name = 'Country',\n                     hover_data = ['Deaths'])\n\nfig = make_subplots(rows = 1, cols=2, subplot_titles=['Confirmed','Deaths'],\n                  specs=[[{'type': 'choropleth'},{'type': 'choropleth'} ]])\nfig.add_trace(fig_c['data'][0], row=1, col=1)\nfig.add_trace(fig_d['data'][0], row=1, col=2)\n\nfig.update(layout_coloraxis_showscale=False)\nfig.show()\nfig1 = px.line(day_wise, x='Date', y='Deaths \/ 100 Cases',color_discrete_sequence=[dth])\nfig2 = px.line(day_wise, x='Date', y='Recovered \/ 100 Cases',color_discrete_sequence=[rec])\nfig3 = px.line(day_wise, x='Date', y='Deaths \/ 100 Recovered',color_discrete_sequence=['aqua'])\n\nfig = make_subplots(rows=1, cols=3, shared_xaxes=False,\n                   subplot_titles=(\"Deaths \/ 100 Cases\", 'Recovered \/ 100 Cases','Deaths \/ 100 Recovered'))\nfig.add_trace(fig1['data'][0], row=1,col=1)\nfig.add_trace(fig2['data'][0], row=1,col=2)\nfig.add_trace(fig3['data'][0], row=1,col=3)\n\nfig.update_layout(height=400)\nfig.show()\n\"\"\"\n# New Caes and Number of Countries\n\"\"\"\nfig_c = px.bar(day_wise, x='Date', y='Confirmed', color_discrete_sequence=[act])\nfig_d = px.bar(day_wise, x='Date', y='No. of Countries', color_discrete_sequence=[dth])\n\nfig = make_subplots(rows=1, cols=2, shared_xaxes=False, horizontal_spacing=0.1,\n                   subplot_titles=(\"Number of new Cases per Day\", 'No. of Countries'))\nfig.add_trace(fig_c['data'][0], row=1, col=1)\nfig.add_trace(fig_d['data'][0], row=1, col=2)\n\nfig.show()\n\"\"\"\n# Top 15 Countries Case Analysis\n\"\"\"\ncountry_wise.columns\ntop = 15\n\nfig_c = px.bar(country_wise.sort_values('Confirmed').tail(top), x='Confirmed', y='Country',\n              text = 'Confirmed', orientation='h', color_discrete_sequence=[cnf])\nfig_d = px.bar(country_wise.sort_values('Deaths').tail(top), x='Deaths', y='Country',\n              text = 'Deaths', orientation='h', color_discrete_sequence=[dth])\n\nfig_a = px.bar(country_wise.sort_values('Active').tail(top), x='Active', y='Country',\n              text = 'Active', orientation='h', color_discrete_sequence=['#434343'])\nfig_r = px.bar(country_wise.sort_values('Recovered').tail(top), x='Recovered', y='Country',\n              text = 'Recovered', orientation='h', color_discrete_sequence=[rec])\n\n# Plot Deaths \/ 100 Cases in world\n\nfig_dc = px.bar(country_wise.sort_values('Deaths \/ 100 Cases').tail(top), x='Deaths \/ 100 Cases', y='Country',\n              text = 'Deaths \/ 100 Cases', orientation='h', color_discrete_sequence=['#f84351'])\n\n# Plot Recovered \/ 100 Cases in world\n\nfig_rc = px.bar(country_wise.sort_values('Recovered \/ 100 Cases').tail(top), x='Recovered \/ 100 Cases', y='Country',\n              text = 'Recovered \/ 100 Cases', orientation='h', color_discrete_sequence=['#a45998'])\n\n# New Cases  per milion people\n\nfig_nc = px.bar(country_wise.sort_values('New Cases').tail(top), x='New Cases', y='Country',\n              text = 'New Cases', orientation='h', color_discrete_sequence=['#f04341'])\n\ntemp = country_wise[country_wise['Population']>1000000]\nfig_p = px.bar(temp.sort_values('Cases \/ Million People').tail(top), x='Cases \/ Million People', y='Country',\n              text = 'Cases \/ Million People', orientation='h', color_discrete_sequence=['#b40398'])\n\n# New Cases  per One week Changes people\n\nfig_wc = px.bar(country_wise.sort_values('1 week change').tail(top), x='1 week change', y='Country',\n              text = '1 week change', orientation='h', color_discrete_sequence=['#f04554'])\n\ntemp = country_wise[country_wise['Confirmed']>100]\nfig_wi = px.bar(temp.sort_values('1 week % increase').tail(top), x='1 week % increase', y='Country',\n              text = '1 week % increase', orientation='h', color_discrete_sequence=['#b08692'])\n\nfig = make_subplots(rows=5, cols=2, shared_xaxes=False, horizontal_spacing=0.2,\n                    vertical_spacing=.05,\n                    subplot_titles=('Confirmed Cases', 'Deaths Reported', \"Recovered Cases\",\n                                    'Active Cases','Deaths \/ 100 Cases','Recovered \/ 100 Cases',\n                                   'New Cases','Cases \/ Million People','1 week change','1 week % increase'))\n\nfig.add_trace(fig_c['data'][0], row=1, col=1)\nfig.add_trace(fig_d['data'][0], row=1, col=2)\n\nfig.add_trace(fig_r['data'][0], row=2, col=1)\nfig.add_trace(fig_a['data'][0], row=2, col=2)\n\nfig.add_trace(fig_dc['data'][0], row=3, col=1)\nfig.add_trace(fig_rc['data'][0], row=3, col=2)\n\nfig.add_trace(fig_nc['data'][0], row=4, col=1)\nfig.add_trace(fig_p['data'][0], row=4, col=2)\n\nfig.add_trace(fig_wc['data'][0], row=5, col=1)\nfig.add_trace(fig_wi['data'][0], row=5, col=2)\n\nfig.update_layout(height=4000)\nfig.show()\n\"\"\"\n# Scatter plot for Deaths VS Confirmed Cases\n\"\"\"\n# country_wise.sor_values['Deaths', ascending=False].iloc[:15, :]\ntop = 15\nfig = px.scatter(country_wise.sort_values('Deaths', ascending=False).head(top),\n                x = 'Confirmed', y='Deaths', color='Country', size='Confirmed', height=700,\n                text = 'Country', log_x = True, title='Deaths vs Confirmed Cases(Caes are on log10 Scale)')\nfig.update_traces(textposition = 'top center')\nfig.update_layout(showlegend = False)\nfig.update_layout(xaxis_rangeslider_visible= True)\nfig.show()\n\"\"\"\n# Confirmed, Deaths  New Cases Vs Country and Date.\n\"\"\"\n\"\"\"\n**Bar Plot**\n\"\"\"\ncountry_day_wise.head(2)\nfig = px.bar(country_day_wise, x = 'Date', y='Confirmed', color='Country', height=600,\n            title='Confirmed Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\nfig = px.bar(country_day_wise, x = 'Date', y='Deaths', color='Country', height=600,\n            title='Deaths Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\ncountry_day_wise.head(2)\nfig = px.bar(country_day_wise, x = 'Date', y='Recovered', color='Country', height=600,\n            title='Recovered Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\nfig = px.bar(country_day_wise, x = 'Date', y='New Cases', color='Country', height=600,\n            title='New Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\n\"\"\"\n**Line plot**\n\"\"\"\n# Confirmed Cases\nfig = px.line(country_day_wise, x = 'Date', y='Confirmed', color='Country', height=600,\n              title='Confirmed Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\n\n# Death Cases\n\nfig = px.line(country_day_wise, x = 'Date', y='Deaths', color='Country', height=600,\n              title='Deaths Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\n\n# Recovered Cases\n\nfig = px.line(country_day_wise, x = 'Date', y='Recovered', color='Country', height=600,\n              title='Recovered Cases',color_discrete_sequence=px.colors.cyclical.mygbm)\nfig.show()\n\"\"\"\n# Check Groth Rate of Case\n\"\"\"\n\"\"\"\n### Groth Rate After 100 Cases\n\"\"\"\ngt_100 = country_day_wise[country_day_wise['Confirmed']<100]\ngt_100\ngt_100 = country_day_wise[country_day_wise['Confirmed']>100]['Country'].unique()\ntemp = covid_19[covid_19['Country'].isin(gt_100)]\n\ntemp = temp.groupby(['Country', 'Date'])['Confirmed'].sum().reset_index()\ntemp = temp[temp['Confirmed']>100]\n\nmin_date = temp.groupby('Country')['Date'].min().reset_index()\nmin_date.columns = ['Country', 'Min Date']\n\nfrom_100th_case = pd.merge(temp, min_date, on='Country')\nfrom_100th_case['N days'] = (from_100th_case['Date'] - from_100th_case['Min Date']).dt.days\nfig = px.line(from_100th_case, x = 'N days', y='Confirmed', color='Country', title='N days from 100 cases',\n             height=600)\nfig.show()\n\"\"\"\n### Groth Rate After 1000 Cases\n\"\"\"\ngt_1000 = country_day_wise[country_day_wise['Confirmed']>1000]['Country'].unique()\ntemp = covid_19[covid_19['Country'].isin(gt_1000)]\n\ntemp = temp.groupby(['Country', 'Date'])['Confirmed'].sum().reset_index()\ntemp = temp[temp['Confirmed']>1000]\n\nmin_date = temp.groupby('Country')['Date'].min().reset_index()\nmin_date.columns = ['Country', 'Min Date']\n\nfrom_1000th_case = pd.merge(temp, min_date, on='Country')\nfrom_1000th_case['N days'] = (from_1000th_case['Date'] - from_1000th_case['Min Date']).dt.days\nfig = px.line(from_1000th_case, x = 'N days', y='Confirmed', color='Country', title='N days from 1000 cases',\n             height=600)\nfig.show()\n\"\"\"\n### Groth Rate After 10000 Cases \n\"\"\"\ngt_10000 = country_day_wise[country_day_wise['Confirmed']>10000]['Country'].unique()\ntemp = covid_19[covid_19['Country'].isin(gt_10000)]\n\ntemp = temp.groupby(['Country', 'Date'])['Confirmed'].sum().reset_index()\ntemp = temp[temp['Confirmed']>10000]\n\nmin_date = temp.groupby('Country')['Date'].min().reset_index()\nmin_date.columns = ['Country', 'Min Date']\n\nfrom_10000th_case = pd.merge(temp, min_date, on='Country')\nfrom_10000th_case['N days'] = (from_10000th_case['Date'] - from_10000th_case['Min Date']).dt.days\nfig = px.line(from_10000th_case, x = 'N days', y='Confirmed', color='Country', title='N days from 10000 cases',\n             height=600)\nfig.show()\n\"\"\"\n### Groth Rate After 100K Cases\n\"\"\"\ngt_100000 = country_day_wise[country_day_wise['Confirmed']>100000]['Country'].unique()\ntemp = covid_19[covid_19['Country'].isin(gt_100000)]\n\ntemp = temp.groupby(['Country', 'Date'])['Confirmed'].sum().reset_index()\ntemp = temp[temp['Confirmed']>100000]\n\nmin_date = temp.groupby('Country')['Date'].min().reset_index()\nmin_date.columns = ['Country', 'Min Date']\n\nfrom_100000th_case = pd.merge(temp, min_date, on='Country')\nfrom_100000th_case['N days'] = (from_100000th_case['Date'] - from_100000th_case['Min Date']).dt.days\nfig = px.line(from_100000th_case, x = 'N days', y='Confirmed', color='Country', title='N days from 100000 cases',\n             height=600)\nfig.show()\n\"\"\"\n# Tree Map Analysis\n\n**Confirmed Cases**\n\"\"\"\ncovid_19.head(2)\nfull_latest = covid_19[covid_19['Date'] == max(covid_19['Date'])]\n\nfig = px.treemap(full_latest.sort_values(by='Confirmed', ascending=False).reset_index(drop=True),\n                path = ['Country', 'Province\/State'], values='Confirmed', height=700,\n                title='Number of Confirmed Cases',\n                color_discrete_sequence=px.colors.qualitative.Dark2)\n\nfig.data[0].textinfo = 'label+text+value'\nfig.show()\n\"\"\"\n**Deaths Cases**\n\"\"\"\nfull_latest = covid_19[covid_19['Date'] == max(covid_19['Date'])]\n\nfig = px.treemap(full_latest.sort_values(by='Confirmed', ascending=False).reset_index(drop=True),\n                path = ['Country', 'Province\/State'], values='Deaths', height=700,\n                title='Number of Deaths Cases',\n                color_discrete_sequence=px.colors.qualitative.Dark2)\n\nfig.data[0].textinfo = 'label+text+value'\nfig.show()\n\"\"\"\n### If you like my kernel please consider upvoting it.\n\n\n### Thank you\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f2d34d71143d15'}"}
{"id":"44757","text":"\nimport pandas as pd\nimport plotly.offline as pyo\nimport plotly.express as px\nimport plotly.graph_objects as go\npd.options.plotting.backend = 'plotly'\nsales1 = pd.read_csv('..\/input\/sample-sales-data\/sales_data_sample.csv', encoding = 'unicode_escape')\nsales1.head(3)\n\"\"\"\n# How many quantity ordered of each product and compare to price\nFirst of all sum the number of quantity ordered for each product\n\"\"\"\ncompa1 = sales1.groupby(['PRODUCTLINE'])['QUANTITYORDERED'].sum().reset_index()\ncompa1\n\"\"\"\nTo compare price of each product to the sum of number of quantity ordered, get price of each product.\n\"\"\"\ncompa2 = sales1.groupby('PRODUCTLINE')['PRICEEACH'].mean().reset_index()\ncompa2\nbar_data = go.Bar(\n          x = compa1['PRODUCTLINE'],\n          y = compa1['QUANTITYORDERED'],\n          name = 'Quantity Ordered',\n          text = compa1['QUANTITYORDERED'],\n          texttemplate = '%{text:.2s}',\n          textposition = 'inside',\n          yaxis = 'y1',\n          marker=dict(\n                 color=compa1['QUANTITYORDERED'],\n                 colorscale='phase',\n                 showscale=False),\n         customdata=compa1[['PRODUCTLINE', 'QUANTITYORDERED']],\n         hovertemplate =\n          '<br><b>Product<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Q.Ordered<\/b>: %{customdata[1]:,0f}'\n)\n\nline_data = go.Scatter(\n          x = compa2['PRODUCTLINE'],\n          y = compa2['PRICEEACH'],\n          name = 'Price of Product',\n          text = compa2['PRICEEACH'],\n          mode = 'markers + lines',\n          yaxis = 'y2',\n          marker=dict(color='#bd3786'),\n          customdata=compa2[['PRODUCTLINE', 'PRICEEACH']],\n          hovertemplate =\n          '<br><b>Product<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Price<\/b>: $%{customdata[1]:0f}'\n    \n)    \n\n\n\ndata = [bar_data, line_data]\n\nlayout = go.Layout(\n             title={\n                'text': 'Quantity ordered and price of each product ',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n\n             xaxis=dict(title='<b>Name of Product<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Quantity Ordered<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             yaxis2=dict(title='<b>Price of Each Product ($)<\/b>', overlaying='y', side='right',\n                         color='rgb(230, 34, 144)',\n                         showline=True,\n                         showgrid=False,\n                         showticklabels=True,\n                         linecolor='rgb(104, 204, 104)',\n                         linewidth=2,\n                         ticks='outside',\n                         tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                         )\n\n                 ),\n\n             legend=dict(title='',\n                         x=0.3,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color=\"green\", #this code is available only for legend title\n                         uniformtext_minsize=15,\n                         uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure1 = go.Figure(data=data, layout=layout)\n\nfigure1.show()\n\n\"\"\"\n# Compare sales and quantity ordered of each product\n\"\"\"\ncompa3 = sales1.groupby(['PRODUCTLINE'])[['QUANTITYORDERED', 'SALES']].sum().reset_index()\ncompa3\nbar_data1 = go.Bar(\n          x = compa3['PRODUCTLINE'],\n          y = compa3['QUANTITYORDERED'],\n          name = 'Quantity Ordered',\n          text = compa3['QUANTITYORDERED'],\n          texttemplate = '%{text:.2s}',\n          textposition = 'inside',\n          yaxis = 'y1',\n          offsetgroup=1,\n          marker=dict(color='#1E6B99'),\n         customdata=compa3[['PRODUCTLINE', 'QUANTITYORDERED', 'SALES']],\n         hovertemplate =\n          '<br><b>Product<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Q.Ordered<\/b>: %{customdata[1]:,.0f}'\n)\n\nbar_data2 = go.Bar(\n          x = compa3['PRODUCTLINE'],\n          y = compa3['SALES'],\n          name = 'Sales',\n          text = compa3['SALES'],\n          texttemplate = '%{text:.2s}',\n          textposition = 'auto',\n          yaxis = 'y2',\n          offsetgroup=2,\n          marker=dict(color='#B45513'),\n          customdata=compa3[['PRODUCTLINE', 'QUANTITYORDERED', 'SALES']],\n          hovertemplate =\n          '<br><b>Product<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Sales<\/b>: $%{customdata[2]:,.0f}'\n    \n)    \n\n\n\ndata = [bar_data1, bar_data2]\n\nlayout = go.Layout(\n             title={\n                'text': 'Sales of ordered quantity',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n             height=600,\n\n             xaxis=dict(title='<b>Name of Product<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Quantity Ordered<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             yaxis2=dict(title='<b>Sales ($)<\/b>', overlaying='y', side='right',\n                         color='rgb(230, 34, 144)',\n                         showline=True,\n                         showgrid=False,\n                         showticklabels=True,\n                         linecolor='rgb(104, 204, 104)',\n                         linewidth=2,\n                         ticks='outside',\n                         tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                         )\n\n                 ),\n\n             legend=dict(title='',\n                         x=0.3,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color=\"green\", #this code is available only for legend title\n                         uniformtext_minsize=15,\n                         uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\"\"\"\n# Count each status of products\n\"\"\"\ncompa4 = sales1.groupby('STATUS')['PRODUCTLINE'].count()\ncompa4\nCancelled = sales1.loc[sales1['STATUS'] == 'Cancelled'].count()[0]\nCancelled\nDisputed = sales1.loc[sales1['STATUS'] == 'Disputed'].count()[0]\nDisputed\nIn_Process = sales1.loc[sales1['STATUS'] == 'In Process'].count()[0]\nIn_Process\nOn_Hold = sales1.loc[sales1['STATUS'] == 'On Hold'].count()[0]\nOn_Hold\nResolved = sales1.loc[sales1['STATUS'] == 'Resolved'].count()[0]\nResolved\nShipped = sales1.loc[sales1['STATUS'] == 'Shipped'].count()[0]\nShipped\nlabels = ['Cancelled', 'Disputed', 'In Process', 'On Hold', 'Resolved', 'Shipped']\nvalues = [Cancelled, Disputed, In_Process, On_Hold, Resolved, Shipped]\n\n\nfigure = go.Figure(data=[go.Pie(labels=labels, values=values,\n                               \n                \n                hoverinfo='label+value+percent',\n                textinfo='label+percent',\n                textfont=dict(size=13),\n                insidetextorientation='radial',\n                           \n)])\n\nfigure.show()\n\"\"\"\n# Calculate yearly sales value\n\"\"\"\ncompa5 = sales1.groupby(['YEAR_ID'])[['SALES', 'QUANTITYORDERED']].sum().reset_index()\ncompa5.head()\nbar_data1 = go.Bar(\n          x = compa5['YEAR_ID'],\n          y = compa5['SALES'],\n          name = 'Sales',\n          text = compa5['SALES'],\n          texttemplate = '%{text:.2s}',\n          textposition = 'inside',\n          yaxis = 'y1',\n          marker=dict(color=' #7F8C8D'),\n          customdata=compa5[['YEAR_ID', 'SALES', 'QUANTITYORDERED']],\n          hovertemplate =\n          '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Sales<\/b>: $%{customdata[1]:,.0f}'\n)\n\nline_data2 = go.Scatter(\n          x = compa5['YEAR_ID'],\n          y = compa5['QUANTITYORDERED'],\n          name = 'Quantity Ordered',\n          text = compa5['QUANTITYORDERED'],\n          mode = 'markers + lines',\n          yaxis = 'y2',\n          marker=dict(color='#DC7633 '),\n          customdata=compa5[['YEAR_ID', 'SALES', 'QUANTITYORDERED']],\n          hovertemplate =\n          '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Quantity Ordered<\/b>: %{customdata[2]:,.0f}'\n    \n)    \n\n\n\ndata = [bar_data1, line_data2]\n\nlayout = go.Layout(\n             title={\n                'text': 'Yearly Sales and Quantity Ordered',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n             height=550,\n\n             xaxis=dict(title='<b>Year<\/b>',\n                        tick0=0,\n                        dtick=1,\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Total Sales ($)<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             yaxis2=dict(title='<b>Total Quantity Ordered<\/b>', overlaying='y', side='right',\n                         color='rgb(230, 34, 144)',\n                         showline=True,\n                         showgrid=False,\n                         showticklabels=True,\n                         linecolor='rgb(104, 204, 104)',\n                         linewidth=2,\n                         ticks='outside',\n                         tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                         )\n\n                 ),\n\n             legend=dict(title='Trend',\n                         x=0.8,\n                         y=0.95,\n                         orientation='v',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color=\"green\", #this code is available only for legend title\n                         uniformtext_minsize=15,\n                         uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\"\"\"\n# Calculate monthly sales\n\"\"\"\nmonthly_sales = sales1.groupby(['YEAR_ID','MONTH_ID'])['SALES'].sum().reset_index()\nmonthly_sales.head(3)\nyear_2003 = monthly_sales[monthly_sales['YEAR_ID'] == 2003]\nyear_2003\nyear_2004 = monthly_sales[monthly_sales['YEAR_ID'] == 2004]\nyear_2005 = monthly_sales[monthly_sales['YEAR_ID'] == 2005]\ndata_2003 = go.Scatter(\n                    x = year_2003['MONTH_ID'],\n                    y = year_2003['SALES'],\n                    name = '2003',\n                    mode = 'markers + lines',\n                    customdata=year_2003[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\ndata_2004 = go.Scatter(\n                    x = year_2004['MONTH_ID'],\n                    y = year_2004['SALES'],\n                    name = '2003',\n                    mode = 'markers + lines',\n                    customdata=year_2004[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\ndata_2005 = go.Scatter(\n                    x = year_2005['MONTH_ID'],\n                    y = year_2005['SALES'],\n                    name = '2003',\n                    mode = 'markers + lines',\n                    customdata=year_2005[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\n\ndata = [data_2003, data_2004, data_2005]\n\nlayout = go.Layout(\n             title={\n                'text': 'Monthly Sales',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n             height=600,\n\n             xaxis=dict(title='<b>Month<\/b>',\n                        tick0=0,\n                        dtick=1,\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             legend=dict(title='',\n                         x=0.3,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color=\"green\", #this code is available only for legend title\n#                          uniformtext_minsize=15,\n#                          uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\"\"\"\nIn the above chart, there are three legends, 2003, 2004, 2005.\n\"\"\"\n\"\"\"\n# Compare growth rate of sales to actual sales\nCreate new column 'GROWTH RATE' inside data frame 'monthly_sales'\n\"\"\"\nmonthly_sales['GROWTH RATE'] = monthly_sales['SALES'].pct_change()\nmonthly_sales.head(3)\nyear_2003_g = monthly_sales[monthly_sales['YEAR_ID'] == 2003]\nyear_2003_g.head(3)\nyear_2004_g = monthly_sales[monthly_sales['YEAR_ID'] == 2004]\nyear_2005_g = monthly_sales[monthly_sales['YEAR_ID'] == 2005]\nbar_2003 = go.Bar(\n          x = year_2003['MONTH_ID'],\n          y = year_2003['SALES'],\n          name = '2003',\n          marker = dict(color='rgb(240, 128, 128)'),\n          yaxis = 'y1',\n          customdata=year_2003[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\nbar_2004 = go.Bar(\n          x = year_2004['MONTH_ID'],\n          y = year_2004['SALES'],\n          name = '2004',\n           marker = dict(color='rgb(239, 11, 173)'),\n          yaxis = 'y1',\n          customdata=year_2004[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\nbar_2005 = go.Bar(\n          x = year_2005['MONTH_ID'],\n          y = year_2005['SALES'],\n          name = '2005',\n          marker = dict(color='rgb(11, 180, 239)'),\n          yaxis = 'y1',\n          customdata=year_2005[['YEAR_ID', 'MONTH_ID', 'SALES']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Sales<\/b>: $%{customdata[2]:,.0f}<\/br>'\n)\n\ndata_g_2003 = go.Scatter(\n                    x = year_2003_g['MONTH_ID'],\n                    y = year_2003_g['GROWTH RATE'],\n                    name = '2003',\n                    mode = 'markers + lines',\n                    customdata=year_2003_g[['YEAR_ID', 'MONTH_ID', 'GROWTH RATE']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Growth Rate<\/b>: %{customdata[2]:,.2f}<\/br>',\n                    yaxis = 'y2',\n                    marker = dict(color='rgb(33, 47, 61)'),\n                    line=dict(dash='dash')\n)\n\ndata_g_2004 = go.Scatter(\n                    x = year_2004_g['MONTH_ID'],\n                    y = year_2004_g['GROWTH RATE'],\n                    name = '2004',\n                    mode = 'markers + lines',\n                    customdata=year_2004_g[['YEAR_ID', 'MONTH_ID', 'GROWTH RATE']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Growth Rate<\/b>: %{customdata[2]:,.2f}<\/br>',\n                    yaxis = 'y2',\n                    marker = dict(color='rgb(11, 239, 204)'),\n                    line=dict(dash='dash')\n)\n\ndata_g_2005 = go.Scatter(\n                    x = year_2005_g['MONTH_ID'],\n                    y = year_2005_g['GROWTH RATE'],\n                    name = '2005',\n                    mode = 'markers + lines',\n                    customdata=year_2005_g[['YEAR_ID', 'MONTH_ID', 'GROWTH RATE']],\n                    hovertemplate =\n                    '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n                    '<b>Month<\/b>: %{customdata[1]}'+\n                    '<br><b>Growth Rate<\/b>: %{customdata[2]:,.2f}<\/br>',\n                     yaxis = 'y2',\n                     marker = dict(color='rgb(11, 87, 239)'),\n                     line=dict(dash='dash')\n)\n\ndata = [bar_2003, bar_2004, bar_2005, data_g_2003, data_g_2004, data_g_2005]\n\nlayout = go.Layout(\n             title={\n                'text': 'Actual Sales and Growth Rate',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n             height=600,\n\n             xaxis=dict(title='<b>Month<\/b>',\n                        tick0=0,\n                        dtick=1,\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Actual Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             yaxis2=dict(title='<b>Growth Rate<\/b>', overlaying='y', side='right',\n                         color='rgb(230, 34, 144)',\n                         showline=True,\n                         showgrid=False,\n                         showticklabels=True,\n                         linecolor='rgb(104, 204, 104)',\n                         linewidth=2,\n                         ticks='outside',\n                         tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                         )\n\n                 ),\n\n             legend=dict(title='',\n                         x=0.3,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color=\"green\", #this code is available only for legend title\n                         uniformtext_minsize=15,\n                         uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\n\n          \n\"\"\"\n# Count size of deal\n\"\"\"\ndeal = sales1.groupby(['COUNTRY', 'DEALSIZE'])['SALES'].count().reset_index()\ndeal.head()\nsmall = sales1.loc[sales1['DEALSIZE'] == 'Small'].count()[0]\nsmall\nmedium = sales1.loc[sales1['DEALSIZE'] == 'Medium'].count()[0]\nlarge = sales1.loc[sales1['DEALSIZE'] == 'Large'].count()[0]\nlabels = ['Small', 'Medium', 'Large']\nvalues = [small, medium, large]\ncolors = ['#E67E22 ','#FF00FF', '#CD5C5C']\n\nfigure = go.Figure(data=[go.Pie(labels=labels, values=values,\n                               \n                marker=dict(colors=colors),\n                hoverinfo='label+value+percent',\n                textinfo='label+value',\n                textfont=dict(size=13),\n                insidetextorientation='radial',\n                           \n)])\n\nfigure.show()\n\"\"\"\n# Calculate sales from top 10 countries\n\"\"\"\ntop_countries = sales1.groupby(['COUNTRY'])[['SALES','QUANTITYORDERED']].sum().sort_values(by=['SALES'], ascending=False).nlargest(10, columns=['SALES']).reset_index()\ntop_countries\nbar_data = go.Bar(\n          x = top_countries['SALES'],\n          y = top_countries['COUNTRY'],\n          text = top_countries['SALES'],\n          texttemplate = '%{text:.2s}',\n          textposition = 'inside',\n          marker=dict(\n                 color=top_countries['SALES'],\n                 colorscale='portland',\n                 showscale=False),\n          orientation='h',\n          customdata=top_countries[['QUANTITYORDERED', 'COUNTRY', 'SALES']],\n          hovertemplate =\n          '<br><b>Country<\/b>: %{y}<br><extra><\/extra>'+\n          '<b>Sales<\/b>: $%{x:,.0f}'+\n          '<br><b>Quantity Ordered<\/b>: %{customdata[0]:,.0f}<br>'\n          \n          \n)\n\nlayout = go.Layout(\n    title={\n                'text': 'Top 10 Countries',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='closest',\n             height=600,\n\n             xaxis=dict(title='<b>Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Country<\/b>',\n                        autorange='reversed',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=False,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n    \n            uniformtext_minsize=12,\n            uniformtext_mode='hide'\n\n                  \n\n)\n\nfigure2 = go.Figure(data=bar_data, layout=layout)\n\nfigure2.show()\n\n\n\n\"\"\"\n# Calculate number of monthly active customer\n\"\"\"\nmonthly_customer = sales1.groupby(['YEAR_ID','MONTH_ID'])['CUSTOMERNAME'].nunique().reset_index()\nmonthly_customer.head(3)\nyear_2003_cus = monthly_customer[monthly_customer['YEAR_ID'] == 2003]\nyear_2003_cus.head(3)\nyear_2004_cus = monthly_customer[monthly_customer['YEAR_ID'] == 2004]\nyear_2005_cus = monthly_customer[monthly_customer['YEAR_ID'] == 2005]\ncus_data1 = go.Bar(\n          x = year_2003_cus['MONTH_ID'],\n          y = year_2003_cus['CUSTOMERNAME'],\n          name = '2003',\n          text = year_2003_cus['CUSTOMERNAME'],\n          texttemplate = '%{text:,.0f}',\n          textposition = 'outside',\n          marker = dict(color='rgb(108, 34, 230)'),\n          customdata=year_2003_cus['YEAR_ID'],\n          hovertemplate =\n          '<br><b>Year<\/b>: %{customdata}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x:,.0f}'+\n          '<br><b>Customer<\/b>: %{y:,.0f}<br>',\n          \n          \n)\n\ncus_data2 = go.Bar(\n          x = year_2004_cus['MONTH_ID'],\n          y = year_2004_cus['CUSTOMERNAME'],\n          name = '2004',\n          text = year_2004_cus['CUSTOMERNAME'],\n          texttemplate = '%{text}',\n          textposition = 'outside',\n          marker = dict(color='rgb(34, 150, 230)'),\n          customdata=year_2004_cus['YEAR_ID'],\n          hovertemplate =\n          '<br><b>Year<\/b>: %{customdata}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x:,.0f}'+\n          '<br><b>Customer<\/b>: %{y:,.0f}<br>'\n          \n          \n          \n)\n\ncus_data3 = go.Bar(\n          x = year_2005_cus['MONTH_ID'],\n          y = year_2005_cus['CUSTOMERNAME'],\n          name = '2005',\n          text = year_2005_cus['CUSTOMERNAME'],\n          texttemplate = '%{text:,.0f}',\n          textposition = 'outside',\n          marker = dict(color='rgb(34, 230, 117)'),\n          customdata=year_2005_cus['YEAR_ID'],\n          hovertemplate =\n          '<br><b>Year<\/b>: %{customdata}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x:,.0f}'+\n          '<br><b>Customer<\/b>: %{y:,.0f}<br>'\n          \n          \n)\n\ndata = [cus_data1, cus_data2, cus_data3]\n\nlayout = go.Layout(\n             barmode='group',\n             title={\n                'text': 'Monthly Active Customer',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n    \n             xaxis=dict(title='<b>Month<\/b>',\n                        tick0=0,\n                        dtick=1,\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Customer<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             \n\n             legend=dict(title='',\n                         x=0.25,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color='green', #this code is available only for legend title\n                         uniformtext_minsize=1,\n                         uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\"\"\"\n# Calculate average sales in each month\n\"\"\"\naverage_sales = sales1.groupby(['YEAR_ID','MONTH_ID'])[['SALES', 'QUANTITYORDERED']].mean().reset_index()\naverage_sales.head(3)\nave_2003 = average_sales[average_sales['YEAR_ID'] == 2003]\nave_2003.head(3)\nave_2004 = average_sales[average_sales['YEAR_ID'] == 2004]\nave_2005 = average_sales[average_sales['YEAR_ID'] == 2005]\ndata_2003 = go.Scatter(\n   x = ave_2003['MONTH_ID'],\n   y = ave_2003['SALES'],\n   name = '2003',\n   mode = 'markers + lines',\n   customdata=ave_2003[['YEAR_ID', 'QUANTITYORDERED']],\n   hovertemplate =\n          '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x}'+\n          '<br><b>Av.Sales<\/b>: %{y:.1f}<br>'+\n          '<b>Av.Quantity Ordered<\/b>: %{customdata[1]:,.2f}',\n            line=dict(dash='dash')\n   \n)\n\ndata_2004 = go.Scatter(\n   x = ave_2004['MONTH_ID'],\n   y = ave_2004['SALES'],\n   name = '2004',\n   mode = 'markers + lines',\n   customdata=ave_2004[['YEAR_ID', 'QUANTITYORDERED']],\n   hovertemplate =\n          '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x}'+\n          '<br><b>Av.Sales<\/b>: %{y:.1f}<br>'+\n          '<b>Av.Quantity Ordered<\/b>: %{customdata[1]:,.2f}',\n            line=dict(dash='dash')\n   \n)\n\ndata_2005 = go.Scatter(\n   x = ave_2005['MONTH_ID'],\n   y = ave_2005['SALES'],\n   name = '2005',\n   mode = 'markers + lines',\n   customdata=ave_2005[['YEAR_ID', 'QUANTITYORDERED']],\n   hovertemplate =\n          '<br><b>Year<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Month<\/b>: %{x}'+\n          '<br><b>Av.Sales<\/b>: %{y:.1f}<br>'+\n          '<b>Av.Quantity Ordered<\/b>: %{customdata[1]:,.2f}'\n            \n)\n\ndata = [data_2003, data_2004, data_2005]\n\nlayout = go.Layout(title={\n                'text': 'Average Sales per Month',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='x',\n    \n             xaxis=dict(title='<b>Month<\/b>',\n                        tick0=0,\n                        dtick=1,\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Average Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n             \n\n             legend=dict(title='',\n                         x=0.35,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color='green', #this code is available only for legend title\n#                          uniformtext_minsize=1,\n#                          uniformtext_mode='hide',\n\n                 )\n\n\n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()\n\n\"\"\"\n# Compare sales of each country on scatter chart\n\"\"\"\nproduct_sales1 = sales1.groupby(['COUNTRY','PRODUCTLINE'])[['QUANTITYORDERED', 'SALES']].sum().reset_index()\nproduct_sales1\ndata = go.Scatter(\n  x = product_sales1['QUANTITYORDERED'],\n  y = product_sales1['SALES'],\n  mode = 'markers',\n  customdata=product_sales1[['COUNTRY', 'PRODUCTLINE']],\n  hovertemplate =\n          '<br><b>Country<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>Product<\/b>: %{customdata[1]}'+\n          '<br><b>Quantity Ordered<\/b>: %{x:,.0f}<br>'+\n          '<b>Sales<\/b>: $%{y:,.0f}',\n    marker=dict(\n        size=20,\n        color=product_sales1['QUANTITYORDERED'],\n        colorscale='mrybm', \n        showscale=False)\n\n)\n\nlayout = go.Layout(title={\n                'text': 'Sales of Ordered Quantity',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='closest',\n    \n             xaxis=dict(title='<b>Quantity Ordered<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                )\n             \n    )       \n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()                   \n             \n\"\"\"\n# Compare sales of each country on bubble chart\n\"\"\"\nproduct_sales2 = sales1.groupby(['COUNTRY', 'STATE', 'CITY', 'PRODUCTLINE', 'DEALSIZE'])[['QUANTITYORDERED', 'SALES']].sum().reset_index()\nproduct_sales2\nproduct_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Small']\ndata1 = go.Scatter(\n  x = product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Small'],\n  y = product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Small'],\n  mode = 'markers',\n  customdata=product_sales2[['COUNTRY', 'STATE',  'CITY', 'PRODUCTLINE', 'QUANTITYORDERED', 'SALES']],\n  hovertemplate =\n          '<br><b>Country<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>State<\/b>: %{customdata[1]}'+\n          '<br><b>City<\/b>: %{customdata[2]}<\/br>'+\n          '<b>Product<\/b>: %{customdata[3]}'+\n          '<br><b>Q.Ordered<\/b>: %{customdata[4]:,.0f}<\/br>'+\n          '<b>Sales<\/b>: $%{customdata[5]:,.0f}',\n    marker=dict(\n        size=2000*product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Small']\/product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Small'],\n        color=product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Small'],\n        colorscale='mrybm', \n        showscale=False),\n    name='Small'\n\n)\n\ndata2 = go.Scatter(\n  x = product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Medium'],\n  y = product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Medium'],\n  mode = 'markers',\n  customdata=product_sales2[['COUNTRY', 'STATE',  'CITY', 'PRODUCTLINE', 'QUANTITYORDERED', 'SALES']],\n  hovertemplate =\n          '<br><b>Country<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>State<\/b>: %{customdata[1]}'+\n          '<br><b>City<\/b>: %{customdata[2]}<\/br>'+\n          '<b>Product<\/b>: %{customdata[3]}'+\n          '<br><b>Q.Ordered<\/b>: %{customdata[4]:,.0f}<\/br>'+\n          '<b>Sales<\/b>: $%{customdata[5]:,.0f}',\n    marker=dict(\n        size=2000*product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Medium']\/product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Medium'],\n        color=product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Medium'],\n        colorscale='mrybm', \n        showscale=False),\n    name='Medium'\n\n)\n\ndata3 = go.Scatter(\n  x = product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Large'],\n  y = product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Large'],\n  mode = 'markers',\n  customdata=product_sales2[['COUNTRY', 'STATE',  'CITY', 'PRODUCTLINE', 'QUANTITYORDERED', 'SALES']],\n  hovertemplate =\n          '<br><b>Country<\/b>: %{customdata[0]}<br><extra><\/extra>'+\n          '<b>State<\/b>: %{customdata[1]}'+\n          '<br><b>City<\/b>: %{customdata[2]}<\/br>'+\n          '<b>Product<\/b>: %{customdata[3]}'+\n          '<br><b>Q.Ordered<\/b>: %{customdata[4]:,.0f}<\/br>'+\n          '<b>Sales<\/b>: $%{customdata[5]:,.0f}',\n    marker=dict(\n        size=4000*product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Large']\/product_sales2['SALES'][product_sales2['DEALSIZE'] == 'Large'],\n        color=product_sales2['QUANTITYORDERED'][product_sales2['DEALSIZE'] == 'Large'],\n        colorscale='mrybm', \n        showscale=False),\n    name='Large'\n\n)\n\ndata = [data1, data2, data3]\n\nlayout = go.Layout(title={\n                'text': 'Sales of Ordered Quantity',\n                'y': 0.93,\n                'x': 0.5,\n                'xanchor': 'center',\n                'yanchor': 'top'},\n             titlefont={'family': 'Oswald',\n                        'color': 'rgb(230, 34, 144)',\n                        'size': 25},\n\n             hovermode='closest',\n             height=600,      \n    \n             xaxis=dict(title='<b>Quantity Ordered<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                            family='Arial',\n                            size=12,\n                            color='rgb(17, 37, 239)'\n                        )\n\n                ),\n\n             yaxis=dict(title='<b>Sales<\/b>',\n                        color='rgb(230, 34, 144)',\n                        showline=True,\n                        showgrid=True,\n                        showticklabels=True,\n                        linecolor='rgb(104, 204, 104)',\n                        linewidth=2,\n                        ticks='outside',\n                        tickfont=dict(\n                           family='Arial',\n                           size=12,\n                           color='rgb(17, 37, 239)'\n                        )\n\n                ),\n              \n            legend=dict(title='',\n                         x=0.25,\n                         y=0.95,\n                         orientation='h',\n                         bgcolor='rgba(255, 255, 255, 0)',\n                         traceorder=\"normal\",\n                         font=dict(\n                              family=\"sans-serif\",\n                              size=12,\n                              color='#000000')),\n\n                         legend_title_font_color='green', #this code is available only for legend title       \n             \n    )       \n\nfigure2 = go.Figure(data=data, layout=layout)\n\nfigure2.show()             ","meta":"{'source': 'AI4Code', 'id': '527398539362e2'}"}
{"id":"134763","text":"# 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)\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns #visualization of the variables\n\nfrom scipy.stats import chi2_contingency, ttest_ind\n\nfrom xgboost import XGBClassifier\nfrom sklearn import preprocessing\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score, f1_score\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\n\"\"\"\n## Stroke Prediction Research:\n\nThe main question is that we want to understand how the predictor variables can help estimate the probability of sufferign a stroke. \n\n* Is there other than age relationship?\n* Does having a heart disease or high BMI and glucose level related to have a higher change of suffering a stroke?\n\n### Plans:\nWe should visualize a distribution of the target variable, which is the stroke, then a distribution of variables in respect to the target variable.\n1. Split the model into categorial features and objects. - Done. Do Hot encoding?\n2. Call the distributions on an object based way e.g. fig, ax.\n3. Continue building on the models. Next XGBoost.\n4. Predict, predict, predict.\n5. Draw final conclusions.\n6. Add an index to notebook.\n7. Add more distribution visualizations.\n\n### Models: \nLogistic regression, random forest and xgboost.\n\"\"\"\n\"\"\"\n### Exploratory Data Analysis (EDA)\n\nIs nothing but data exploration technique to understand the various aspects of the data. The idea is to check for relationship between variables and to check their distributions.\n\n\n* It follow a systematic set of steps to explore the data in the most efficient way possible\n\"\"\"\n\"\"\"\nSteps:\n1. Understand the Data\n\n2. Clean up the Data\n3. Analysis of Relationship between variables\n\"\"\"\n#Import Dataset to Pandas Dataframe\ndata = pd.read_csv(os.path.join(dirname, filename))\n\"\"\"\n### 1. Understanding the Data\n\"\"\"\ndata.head()\ndata.tail()\n\"\"\"\nFrom this quick overview, it comes to mind that we can use different variables correlations. Like age against stroke. We see that there are many variables that can be related to having a stroke: age, being married, work, etc.\n\"\"\"\n\"\"\"\n### Features or data points. \n\"\"\"\n\"\"\"\nTo find out how many columns, how many entries and if there are some missing values. We can use dataframe.info()\n\"\"\"\ndata.columns\ndata.info()\n#Categorical info\ncat_feat = ['gender', 'ever_married', 'work_type', 'Residence_type', 'smoking_status']\n#remove categorial data from our set to create the model. Can be added encoded later in the process.\nnum_feat = data.drop(cat_feat, axis = 1)\n\"\"\"\nAnother way to get the number of rows and columsn is using the data.shape panda feature. It returns a tuple. First one is for the rows and second one is for the number of columns.\n\"\"\"\ndata.shape\n#12 variables and 5110 observations\n\"\"\"\n### Describing the data statistically speaking function\n\"\"\"\n\"\"\"\nThe describe function allows us to have basic statistical information of the data. This is useful because it allows us to detect possible outliers or any strange data.\n\"\"\"\n#data = data.drop('Id', axis = 1).describe()\ndata.describe()\n\"\"\"\nWe see that most people are on the 43 years of age. Then we can see that the mean of bmi of the population in study is at 28.\n\nA healty range of a person BMI is between 18-25. \n\nThe BMI depends on different factors, Like height, muscle and body type.\n\nNote on the avg of glucose level below 140 is normal. Between 140-199 is pre-diabetes. \n\n\"\"\"\nnum_feat = num_feat.drop('id', axis = 1)\nnum_feat.describe()\n# num_feat.groupby(num_feat['bmi'].isnull()).mean()\nnum_feat.isna().sum()\n#97.6 BMI? That is odd. Let's find out how many \nnum_feat[num_feat['bmi']==97.6]\ndata[data['bmi']==97.6]\n\"\"\"\nThis is excessively strange. What should do with this data row. Only one entry with a very high bmi. Has hypertension. It's a young age male, who work in the private sector and live in a rural area with a glucose level that seems correct and has not suffered a stroke.\n\nProably we will need to do an imputation to update his bmi base on median bmi for his age and other related features.\n\nBut for now we are going to remove it for the purpose of fixing the distribution.\n\"\"\"\nnum_feat = num_feat[num_feat['bmi']!=97.6]\n#Checking again\nnum_feat[num_feat['bmi']>40] #sort_values('bmi')\nnum_feat.describe()\nnum_feat[num_feat.bmi > 40].describe()\nnum_feat.groupby('stroke').mean()\n\"\"\"\nThe average age of people that has suffered a strok are a 67 with a bmi of 30 or over.\n\nSo, it shows there is is more entries with abnormal Body Mass Index. Let's check for those with a BMI over 40 with obesity class 2\n\"\"\"\nnum_feat.groupby(num_feat.bmi > 40)[['stroke', 'hypertension', 'heart_disease']].sum()\nbmi_over_40 = num_feat[num_feat['bmi'] > 40 ]\nbmi_over_40[num_feat['stroke'] == 1 ].sort_values(by='age')\n\"\"\"\nWe see that the corelation of suffering a stroke is not just age, but having a bmi over 40 and a higher sugar level. \n\"\"\"\nplt.figure(figsize = (9,7))\nsns.scatterplot(x = 'bmi', y = 'avg_glucose_level', hue = 'stroke', data =bmi_over_40)\nplt.show()\n\"\"\"\n### Adult Body Mass Index (BMI)\n\nBMI does not measure body fat directly, but research has shown that BMI is moderately correlated with more direct measures of body fat obtained from skinfold thickness measurements, bioelectrical impedance, underwater weighing, dual energy x-ray absorptiometry (DXA) and other methods 1,2,3. Furthermore, BMI appears to be strongly correlated with various adverse health outcomes consistent with these more direct measures of body fatness\n\"\"\"\n\"\"\"\n### Check for unique values\n\"\"\"\n#check for unique values\ndata.nunique()\n\"\"\"\nIt seems the majorities of values are binaries, which mean that they are categorical values e.g. \"yes\" or \"no\" except for gender which is says it has 3 types. We need to check if that is not because a typo or blank entries. \n\nThe categorial variables with more different values are the following in ascending order:\n1. smoking_status          4\n2. work_type               5\n\n\"\"\"\n\"\"\"\n### Checking Specific Unique values\n\"\"\"\ndata.gender.unique()\n\"\"\"\n### Distribution of gender\n\n\"\"\"\ndata.gender.value_counts()\n\"\"\"\nGiven the fact the other gender is only 1 value. We can remove that data point from our study.\n\"\"\"\ndata = data[data['gender']!='Other']\ndata.smoking_status.unique()\ndata.smoking_status.value_counts()\ndata[data['smoking_status'] == 'Unknown']\n#smokers and goverment jobs\nsmokers = data[data['smoking_status']=='smokes']\n\nsmokers.work_type.value_counts(normalize=True)\n\"\"\"\n### Age distribution of smokers\n\n\"\"\"\nsmokers['age'].groupby(smokers['age']).count()\n\"\"\"\nGiven the fact that of those who are smokers. Only a few smoke at young ages and at late ages as well. So, let's see if we can slice the data from 35 - 65 years of age.\n\"\"\"\nage_smokers = smokers['age'].groupby(smokers['age']).count()\n\nage_smokers[35:65].sort_values(ascending=False, axis=0)\n\"\"\"\nAccording to this result we can see that the mayority of smokers account for more than 10 are effectively on the age range of 35 through 63. With the exception of of less smokers at the age of 41, 37, 62 and 64 of age, only 9 smokers. \n\nOn the visualiaztion section we can plot this one out to see the histogram distribution. \n\"\"\"\n#smokers and goverment jobs\nunkn_smokers = data[data['smoking_status']=='Unknown']\n\nunkn_smokers.work_type.value_counts(normalize=True)\ndata.work_type.unique()\n\"\"\"\n## Step 2: Cleaning the data\n\"\"\"\ndata.isnull().sum() \n\"\"\"\nQuestions:\nNo missing values except for BMI. Should we need to fill those empty values\n\"\"\"\ndata['bmi'].isnull().sum()\/len(data)*100 \n\"\"\"\nWe have 4% of BMI missing data. \n\"\"\"\n#handling missing values\ndata['bmi'] = data['bmi'].fillna(round (data['bmi'].median(), 2))\ndata.isnull().sum()\n\"\"\"\nChecking for outliers:\nis a datapoint that differ from other observations\n\"\"\"\n\"\"\"\n### Relationship Analysis\n\"\"\"\ndata.columns\ncorelation = data.drop('id', axis = 1).corr()\nplt.figure(figsize=(7,7))\nsns.heatmap(corelation, xticklabels =corelation.columns, yticklabels = corelation.columns, annot=True)\nplt.show()\n\"\"\"\nAs we can see it looks that the more related variable to stroke is the age feature. We may consider to use a model to only use the wanted variables to remove id for example.\n\"\"\"\nplt.figure(figsize=(7,7))\nsns.heatmap(corelation, xticklabels =corelation.columns, yticklabels = corelation.columns,\n            vmin=-1, vmax=1, center=0,annot=True)\nplt.show()\n\"\"\"\n## Data Visualizations\n\"\"\"\n\"\"\"\nChecking the distribution of the target variable(stroke)\n\"\"\"\ndata.columns\nsns.countplot(x = 'smoking_status', data = data)\nplt.title(\"Count Plot for smoking status\")\nplt.show()\nsns.countplot(x = 'work_type', data = data)\nplt.title('Count Plot for Work Type')\nplt.show()\nnum_data = num_feat\n#Ploting the distribution of Stroke\nsns.countplot(x='stroke', data=num_data)\nplt.show()\nx = pd.DataFrame(num_data.groupby(['stroke'])['stroke'].count())\n\n# plot\nfig, ax = plt.subplots(figsize = (6,6), dpi = 70)\nax.barh([1], x.stroke[1], height = 0.7, color = 'red')\nplt.text(-1150,-0.08, 'Healthy',{'font': 'Serif','weight':'bold','Size': '16','style':'normal', 'color':'green'})\n#plt.text(5000,-0.08, '95%',{'font':'Serif','weight':'bold' ,'size':'16','color':'green'})\nplt.text(5000,-0.08, f\"{(num_data.shape[0]\/num_data.shape[0]*100) - (x.shape[0]\/(num_data.shape[0])*100)*100:.0f}%\" ,{'font':'Serif','weight':'bold' ,'size':'16','color':'green'})\nax.barh([0], x.stroke[0], height = 0.7, color = 'green')\nplt.text(-1000,1, 'Stroke', {'font': 'Serif','weight':'bold','Size': '16','style':'normal', 'color':'red'})\nplt.text(300,1, f\"{((x.shape[0]\/data.shape[0])*100)*100:.0f}%\",{'font':'Serif', 'weight':'bold','size':'16','color':'red'})\n\nfig.patch.set_facecolor('#f6f5f5')\nax.set_facecolor('#f6f5f5')\n\nplt.text(-1150,1.77, 'Percentage of People Having Strokes' ,{'font': 'Serif', 'Size': '25','weight':'bold', 'color':'black'})\nplt.text(4650,1.65, 'Stroke ', {'font': 'Serif','weight':'bold','Size': '16','weight':'bold','style':'normal', 'color':'red'})\nplt.text(5650,1.65, '|', {'color':'black' , 'size':'16', 'weight': 'bold'})\nplt.text(5750,1.65, 'Healthy', {'font': 'Serif','weight':'bold', 'Size': '16','style':'normal', 'weight':'bold','color':'green'})\nplt.text(-1150,1.5, 'It is a highly unbalanced distribution,\\nand clearly seen that 4 in 100 people are susceptible \\nto strokes.', \n        {'font':'Serif', 'size':'12.5','color': 'black'})\n\nax.axes.get_xaxis().set_visible(False)\nax.axes.get_yaxis().set_visible(False)\nax.spines['bottom'].set_visible(False)\nax.spines['left'].set_visible(True)\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.figure(figsize = (16,11))\nplt.subplot(2,3,1)\nsns.countplot(x = 'gender', data = data)\nplt.title('Countplot of Gender distribution')\n\nplt.subplot(2,3,2)\nsns.countplot(x = 'ever_married', data = data)\nplt.title('Countplot of Married status distribution')\n\nplt.subplot(2,3,3)\nsns.countplot(x='work_type', data = data)\nplt.title('Countplot of Work Type distribution')\n\nplt.subplot(2,3,4)\nsns.countplot(x = 'Residence_type', data = data)\nplt.title('Countplot of Residence type distribution')\n\nplt.subplot(2,3,5)\nsns.countplot(x = 'smoking_status',data = data)\nplt.title('Countplot of Smoking status distribution')\n\nplt.subplot(2,3,6)\nsns.countplot(x = 'heart_disease',data = data)\nplt.title('Countplot of Heart Disease distribution')\nplt.show()\n\"\"\"\n### Distribution of BMI\n\"\"\"\n\"\"\"\nShape and the spread with histograms and box plots\n\"\"\"\nnum_data = num_feat\n#handling missing values\nnum_data['bmi'] = num_data['bmi'].fillna(round (num_data['bmi'].median(), 2))\n# Checking the distribution of the predictor variables. \n# Here, we will use both distplot and boxplot as shown below. \n# Let us plot each variable to show its distribution in the dataset.\n#fig, ax = plt.subplots(figsize = (6,6), dpi = 70)\nplt.figure(1)\nplt.title('BMI Distribution before droping the abnormal entry')\nplt.subplot(121), sns.distplot(num_data['bmi'])\nplt.subplot(122), num_data['bmi'].plot.box(figsize=(16,5))\nplt.show()\n\"\"\"\nStroke Distrution of people with a BMI over 40\n\"\"\"\nplt.figure(1)\nplt.title('Stroke Distribution with BMI over 40')\nplt.subplot(121), sns.distplot(bmi_over_40['bmi'])\nplt.subplot(122), bmi_over_40['bmi'].plot.box(figsize=(16,5))\nplt.show()\n\n\"\"\"\n### Distribution of Age\n\"\"\"\nplt.figure(1)\nplt.subplot(121), sns.distplot(data['age'])\nplt.subplot(122), data['age'].plot.box(figsize=(16,5))\nplt.show()\n\"\"\"\n### Distribution of Heart Disease\n\"\"\"\nplt.figure(1)\nplt.subplot(121), sns.countplot(data['heart_disease'])\nplt.subplot(122), data['heart_disease'].plot.box(figsize=(16,5))\nplt.show()\n\"\"\"\n### Distribution of AVG Glucose Level\n\"\"\"\nplt.figure(1)\nplt.subplot(121), sns.distplot(data['avg_glucose_level'])\nplt.subplot(122), data['avg_glucose_level'].plot.box(figsize=(16,5))\nplt.show()\n\"\"\"\n### Plotting relationships in the dataset. \n\nThere are different ways to display relationships using a dataset. You can use pair plots, joint plots, correlations, etc. we will the use pairplot to find out relationships in the dataset.\n\"\"\"\n#sns.pairplot(corelation)\n\nimport warnings\nwarnings.filterwarnings('ignore')\nsns.pairplot(data, hue= 'stroke')\nplt.show()\nsns.relplot(x='stroke', y='age', hue='gender', data=data ) \nplt.show()\n\"\"\"\nWith this it seems that a confusion matrix and a logistic regression may whow a better relationship because this is showing that there is not a linear relationship. \n\"\"\"\n\"\"\"\nFrom this bar chart we can clearly see that for people over 40 years old the majority suffered a stroke. We have an uptick at age 40 then it drops until about age 55 through 65 and drops again and goes all the way up at age 80.\n\"\"\"\n# Scatter Plot\nplt.figure(figsize = (9,7))\nsns.scatterplot(x = 'bmi', y = 'avg_glucose_level', hue = 'stroke', data =bmi_over_40)\nplt.title('Stroke cases - For those with a BMI over 40 ',y=1.05)\n\nplt.xlabel('BMI Level')\nplt.ylabel('Avg Glucose Level')\nplt.show()\n\"\"\"\n## Hypothesis Testing\n\n##### Chi Square testing\n\"\"\"\ndef chi2_dependency(data_df, x,y):\n    ctab = pd.crosstab(data_df[x], data_df[y])\n    stat, p, dof, expected = chi2_contingency(ctab)\n    alpha1 = 0.05\n    alpha2 = 0.01\n    print('--------------Chi Squared Hypothesis Test Results-------------------')\n    print('Variable X: ',x)\n    print('Variable Y: ',y)\n    if p<alpha1 and p > alpha2:\n        print('P-value: ',p)\n        print('We reject the NUll Hypothesis H0')\n        print('There is some evidence to suggest that {} and {} are dependent'.format(x,y))\n    if p < alpha1 and p < alpha2:\n        print('P-value: ',p)\n        print('We reject the NUll Hypothesis H0')\n        print('There is substantial evidence to suggest that {} and {} are dependent'.format(x,y))\n    else:\n        print('P-value: ',p)\n        print('We fail to reject the NUll Hypothesis H0')\n        print('There is no evidence to suggest that {} and {} are independent'.format(x,y))\n        \n    print()\nchi2_dependency(data,'gender','stroke')\nchi2_dependency(data,'ever_married','stroke')\nchi2_dependency(data,'hypertension','stroke')\nchi2_dependency(data,'heart_disease','stroke')\nchi2_dependency(data,'work_type','stroke')\nchi2_dependency(data,'Residence_type','stroke')\nchi2_dependency(data,'smoking_status','stroke')\n\"\"\"\n* Gender and Residential Type do not seem to have an impact on stroke\n* Smoking Status, Work Type, Heart Disease, Hypertension and Married status have an impact on stroke\n\"\"\"\ndata.columns\nctab = pd.crosstab(data['smoking_status'], data['stroke'])\n\n\nctab.plot.bar(stacked = True, figsize = (8,5))\nplt.xlabel('Smoking Status')\nplt.ylabel('Stroke')\nplt.title('Smoking Status and Stroke')\nplt.show()\nctab = pd.crosstab(data['ever_married'], data['stroke'])\n\nctab.plot.bar(stacked = True, figsize = (8,5))\nplt.xlabel('Ever Married')\nplt.ylabel('Stroke')\nplt.title('Married Status and Stroke')\nplt.show()\n\nprint('Ratio of stroke affected from ever_married class',\n      len(data[data['stroke']==1])\/len(data[data['ever_married']=='Yes']))\n      \nprint('Ratio of stroke affected from never married class',\n      len(data[data['stroke']==1])\/len(data[data['ever_married']=='No']))\nctab = pd.crosstab(data['hypertension'], data['stroke'])\n\nctab.plot.bar(stacked = True, figsize = (8,5))\nplt.xlabel('hypertension')\nplt.ylabel('Stroke')\nplt.title('hypertension Status and Stroke')\nplt.show()\n\nprint('Ratio of stroke affected from hypertension=1 class',\n      len(data[data['stroke']==1])\/len(data[data['hypertension']==1]))\n      \nprint('Ratio of stroke affected from no hypertension class',\n      len(data[data['stroke']==1])\/len(data[data['hypertension']==0]))\n\"\"\"\nAlmost 50% of samples having hypertension were found to have suffered stroke\n\"\"\"\nctab = pd.crosstab(data['heart_disease'], data['stroke'])\n\nctab.plot.bar(stacked = True, figsize = (8,5))\nplt.xlabel('heart_disease')\nplt.ylabel('Stroke')\nplt.title('heart_disease and Stroke')\nplt.show()\n\nprint('Ratio of stroke affected from heart_disease = 1 class',\n      len(data[data['stroke']==1])\/len(data[data['heart_disease']==1]))\n      \nprint('Ratio of stroke affected from no heart_disease class',\n      len(data[data['stroke']==1])\/len(data[data['heart_disease']==0]))\n\"\"\"\nAlmost 90% of samples having heartdisease were found to have suffered stroke\n\"\"\"\n\"\"\"\n#### T-tests\n\"\"\"\n\"\"\"\nWe will perform 2 sample t-test on 'BMI' column to check if the mean BMI of stroke group is different from the non stroke group.\n<br><\/br>\nBefore performing this test we will check ratio of variance of each group\n\"\"\"\ndata[data['stroke']==0]['bmi'].var()\/data[data['stroke']==1]['bmi'].var()\n\"\"\"\nSince the ratio of variance < 4, we will assume them to be having equal variance\n\"\"\"\nstatistic, pval = ttest_ind(a=data[data['stroke']==0]['bmi']  , b = data[data['stroke']==1]['bmi'], equal_var=True)\npval\n\"\"\"\n* Since pvalue < 0.01, we reject the Null Hypothesis H0\n* We can conclude that the population BMI mean of stroke vs non-stroke groups are different\n\"\"\"\n\"\"\"\n\n\nNow we can start creating our model and start our predictions. Also, we can include other features to see if there is any other related variable. \n\"\"\"\n\"\"\"\n### Data Transformation\n\"\"\"\ntarget_col = ['stroke']\nnum_cols = ['id', 'age', 'avg_glucose_level', 'bmi']\ncat_cols = [col for col in data.columns if col not in num_cols+target_col]\n\"\"\"\n### Label encoding\n\"\"\"\n\"\"\"\nLabel encode the binary categorical columns containing strings\n\"\"\"\nfrom sklearn import preprocessing\n\nlabel_encoder = preprocessing.LabelEncoder()\ndata['gender'] = label_encoder.fit_transform(data['gender'])\ndata['ever_married'] = label_encoder.fit_transform(data['ever_married'])\ndata['Residence_type'] = label_encoder.fit_transform(data['Residence_type'])\n\"\"\"\nOne-hot encode the multi category columns\n\"\"\"\ndata = pd.get_dummies(data, prefix = ['work_type'], columns = ['work_type'])\ndata = pd.get_dummies(data, prefix = ['smoking_status'], columns = ['smoking_status'])\n\"\"\"\n## Training the Data\n\nWe will now split our dataset before we train it. X will contain all the Independent variables while y will have the Dependent variable ('stroke')\n\"\"\"\n#Splitting the dataset\nx = num_data.drop('stroke', axis=1)\ny = num_data.stroke\n\n\"\"\"\nAfter successfully splitting the dataset, let us train it using train_test_split.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, train_size = 0.3, random_state=1)\n#include categorical values in the dataset\n#Since we are using a Tree based model, One-Hot encoding is not an absolute necessity\n#However, this dataset, train and test sets will be updated whenever one-hot encoding will be used\nfrom sklearn.model_selection import train_test_split\n\n#Splitting the dataset\nx = data.drop('stroke', axis=1)\ny = data.stroke\n\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, train_size = 0.3, random_state=1)\n\"\"\"\n## Building the Models\n\nAs I stated earlier, we will use four models i.e. Random Forests, Decision Trees, Support Vector Machine and XGBoost to get the best accuracy score. \u2018Accuracy\u2019 metric is used to evaluate models. It is the ratio of the number of correctly predicted instances in a dataset divided by the total number of instances in the dataset. We will proceed further to explore more metrics to determine the best model.\n\"\"\"\n#Let explore with the Random Forests Algo\n#Before proceeding for tree based models, lets check rank of feature importance on a decision tree\nfrom sklearn.tree import DecisionTreeClassifier\ndt = DecisionTreeClassifier()\ndt.fit(xtrain,ytrain)\nprint(len(xtrain.columns.tolist()))\nlen(dt.feature_importances_)\nplt.figure(figsize = (8,8))\nsns.barplot(x = dt.feature_importances_, y = xtrain.columns.tolist())\n\"\"\"\n### Random Forests Classifier\n\"\"\"\n#Building the model using RandomForest\nfrom sklearn.ensemble import RandomForestClassifier\n\nrfc = RandomForestClassifier(n_estimators=500)\nrfc.fit(xtrain, ytrain)\npreds = rfc.predict(xtest)\n\nprint('Predictions',list(preds[0:500]))\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(ytest, preds)\n\"\"\"\nTrue positive are on the upper left. Then the botton right is the true negative. Which means, that I was supposed a negative and the model got a negative.\n\nThe false positive is the number on the upper right. \nFalse negative are the numbers on the bottom left. \n\"\"\"\n\"\"\"\nHere we have the True negatives or 0s because we don't have many cases of strokes. Meaning that 3,388 people did not have a stroke.\n\nOn the inverse we have the True positive or 1s for those who suffered a stroke.\n\n  is the False negative, those who were predicted as 1 but they were 0s. Number 13 \n\"\"\"\n#To find the False Negatives and Predictions. \nxp = (ytest == 0 and preds == 1)\n\"\"\"\n## Accuracy Score\n\nThe accuracy score for this Random forest classifier\n\"\"\"\nfrom sklearn.metrics import accuracy_score\naccuracy_score(ytest,preds)\nfrom sklearn.metrics import f1_score\nf1_score(ytest, preds, average='micro')\n\"\"\"\nTrue positive are on the upper left. Then the botton right is the true negative. Which means, that I was supposed a negative and the model got a negative.\n\nThe false positive is the number on the upper right. \nFalse negative are the numbers on the bottom left. \n\"\"\"\n\"\"\"\n### Gradient Boost Classifier\n\"\"\"\n\"\"\"\nInclude categorical values in the dataset.\nSince we are using a Tree based model, One-Hot encoding is not an absolute necessity\n\nHowever, this dataset, tran and test sets will be update whenever one-hot enconding will be use\n\"\"\"\n#Splitting the data set\nx = data.drop('stroke', axis = 1)\ny = data.stroke\n\nxtrain, xtest, ytrain, ytest = train_test_split(x,y, train_size = 0.3, random_state =1)\nfrom sklearn.ensemble import GradientBoostingClassifier\n\ngbc = GradientBoostingClassifier(random_state = 123, n_estimators = 500)\ngbc.fit(xtrain, ytrain)\npreds = gbc.predict(xtest)\n\nprint(preds)\naccuracy_score(ytest,preds)\nprint(confusion_matrix(ytest, preds))\nprint(classification_report(ytest, preds))\n\"\"\"\nf1-score is very good for umbalanced data. \n\"\"\"\n\"\"\"\n### Gradient Boost Classifier\n\"\"\"\nfrom sklearn.ensemble import GradientBoostingClassifier\n\ngbc = GradientBoostingClassifier(random_state = 123, n_estimators = 500)\ngbc.fit(xtrain,ytrain)\npreds = gbc.predict(xtest)\nprint(confusion_matrix(ytest, preds))\nprint(classification_report(ytest, preds, output_dict = True))\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\n#### Using SMOTE\n<br>\nSMOTE is a technique to artificially oversample the minority class by creating synthetic samples. These synthetic samples are created by finding the intermediate values between neighbouring samples of minority class<br>\n<br>\nSMOTE is applied ONLY on the training set and not on the test set to avoid biased results\n\"\"\"\nfrom imblearn.over_sampling import SMOTE\nsm = SMOTE(random_state = 2)\nxtrain_mod, ytrain_mod = sm.fit_resample(xtrain, ytrain)\ngbc2 = GradientBoostingClassifier(random_state = 123, n_estimators = 30, max_depth = 2)\ngbc2.fit(xtrain_mod,ytrain_mod)\npreds = gbc2.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n#print(classification_report(ytest, preds, output_dict = True))\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\n### XGBoost Classifier\n\"\"\"\n#Fitting model on non-SMOTE dataset\nxgb1 = XGBClassifier(n_estimators = 250)\nxgb1.fit(xtrain, ytrain)\npreds = xgb1.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = xgb1.predict(xtrain)\nprint('Train Accuracy Score: ',accuracy_score(ytrain, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain, train_preds))\n\nprint('Test Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n#Fitting model on SMOTE dataset\nxgb = XGBClassifier(n_estimators = 255, reg_alpha=0.5, reg_lambda = 0.4, max_depth= 1)\nxgb.fit(xtrain_mod, ytrain_mod)\npreds = xgb.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n#print(classification_report(ytest, preds, output_dict = True))\n\ntrain_preds = xgb.predict(xtrain_mod)\nprint('Train Accuracy Score: ',accuracy_score(ytrain_mod, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain_mod, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\n### Gaussian Naive Bayes\n\"\"\"\n#Applying on non-SMOTE dataset\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\ngnb.fit(xtrain, ytrain)\n\npreds = gnb.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = gnb.predict(xtrain)\nprint('Train Accuracy Score: ',accuracy_score(ytrain, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n#Applying on SMOTE dataset\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\ngnb.fit(xtrain_mod, ytrain_mod)\n\npreds = gnb.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = gnb.predict(xtrain_mod)\nprint('Train Accuracy Score: ',accuracy_score(ytrain_mod, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain_mod, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\nWe observe that there is a significant increase in True negatives, but there are also a significant increase in false negatives\n\"\"\"\n\"\"\"\nEarlier, we had noticed that Gender and Residence_type do not have an impact on stroke. \n<br><\/br>\nTo strengthen our classifier, they can be dropped from train and test X dataset\n\"\"\"\n#Removing non-impactful features\nxtrain_mod_dropped = xtrain_mod.drop(['gender', 'Residence_type'], axis = 1)\nxtest_dropped = xtest.drop(['gender', 'Residence_type'], axis = 1)\n\ngnb = GaussianNB()\ngnb.fit(xtrain_mod_dropped, ytrain_mod)\n\npreds = gnb.predict(xtest_dropped)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = gnb.predict(xtrain_mod_dropped)\nprint('Train Accuracy Score: ',accuracy_score(ytrain_mod, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain_mod, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\n### K Nearest Neighbour Classifier\n\"\"\"\n#Applying on SMOTE dataset\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier(n_neighbors=3)\nknn.fit(xtrain, ytrain)\n\npreds = knn.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = knn.predict(xtrain)\nprint('Train Accuracy Score: ',accuracy_score(ytrain, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n#Applying on SMOTE dataset\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=2, p=1)\n\nknn.fit(xtrain_mod, ytrain_mod)\n\npreds = knn.predict(xtest)\nprint(confusion_matrix(ytest, preds))\n\ntrain_preds = knn.predict(xtrain_mod)\nprint('Train Accuracy Score: ',accuracy_score(ytrain_mod, train_preds))\nprint('Train F1 Score: ',f1_score(ytrain_mod, train_preds))\n\nprint('Accuracy Score: ',accuracy_score(ytest, preds))\nprint('F1 Score: ',f1_score(ytest,preds))\n\"\"\"\n## References\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'f7c002d401fd54'}"}
{"id":"73363","text":"\"\"\"\n## Detection of Female and Male eyes using Convolutional Neural Networks\n\n<p><img src = \"https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn:ANd9GcRQtQnWtMBaRN0OznlOnl98spYju8ijAMTUVA&usqp=CAU\" alt align=\"center\"><\/p>\n\n#### Dataset information:\n\n- The data was collected to train a model to distinguish between images containing Female eyes and images of Male eyes, so the whole problem is binary classification.\n\n\nThe data is divided into 2 folders:\n- The folder `` femaleeyes`` contains 5202 images and the folder `` maleeyes`` contains 6323 images for training and testing the model.\n\nThe dataset can be found on the `` Kaggle`` platform at the link below:\n\n- https:\/\/www.kaggle.com\/pavelbiz\/eyes-rtte\n\"\"\"\n\"\"\"\n## 1. Imports from libraries\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport os\nimport os.path\nfrom pathlib import Path\nimport glob\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, BatchNormalization, GlobalAveragePooling2D, SpatialDropout2D\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.applications.xception import Xception\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.mobilenet import MobileNet\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.utils import plot_model\nfrom sklearn.metrics import confusion_matrix, classification_report, recall_score, precision_score, f1_score, roc_auc_score, roc_curve\nfrom tensorflow.keras.preprocessing import image\nfrom PIL import Image\n\"\"\"\n## 2. Organizing Training and Testing Dataframes\n\"\"\"\n# Selecting Dataset Folder Paths\nf_dir_ = Path('..\/input\/eyes-rtte\/femaleeyes')\nm_dir_ = Path('..\/input\/eyes-rtte\/maleeyes')\nfemaleeyes_filepaths = list(f_dir_.glob(r'**\/*.jpg'))\nmaleeyes_filepaths = list(m_dir_.glob(r'**\/*.jpg'))\n\n# Mapping the labels\nfm_labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], femaleeyes_filepaths))\nml_labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], maleeyes_filepaths))\n\n# Paths & labels femalee eyes\nfm_filepaths = pd.Series(femaleeyes_filepaths, name = 'File').astype(str)\nfm_labels = pd.Series(fm_labels, name='Label')\n\n# Paths & labels malee eyes\nml_filepaths = pd.Series(maleeyes_filepaths, name = 'File').astype(str)\nml_labels = pd.Series(ml_labels, name='Label')\n\n# Concatenating...\nfemaleeyes_df = pd.concat([fm_filepaths, fm_labels], axis=1)\nmaleeyes_df = pd.concat([ml_filepaths, ml_labels], axis=1)\n\ndf = pd.concat([femaleeyes_df, maleeyes_df])\n\ndf = df.sample(frac = 1, random_state = 56).reset_index(drop = True)\nvc = df['Label'].value_counts()\nplt.figure(figsize = (9, 5))\nsns.barplot(x = vc.index, y = vc)\nplt.title(\"Number of images for each category in the Training Dataset\", fontsize = 11)\nplt.show()\n\"\"\"\n## 3. Observing the images\n\"\"\"\nplt.style.use(\"dark_background\")\nfigure = plt.figure(figsize=(2,2))\nx = plt.imread(df[\"File\"][34])\nplt.imshow(x)\nplt.xlabel(x.shape)\nplt.title(df[\"Label\"][34])\nfigure = plt.figure(figsize=(2, 2))\nx = plt.imread(df[\"File\"][11])\nplt.imshow(x)\nplt.xlabel(x.shape)\nplt.title(df[\"Label\"][11])\nfig, axes = plt.subplots(nrows = 5,\n                        ncols = 5,\n                        figsize = (7, 7),\n                        subplot_kw = {\"xticks\":[],\"yticks\":[]})\n\nfor i,ax in enumerate(axes.flat):\n    ax.imshow(plt.imread(df[\"File\"][i]))\n    ax.set_title(df[\"Label\"][i])\nplt.tight_layout()\nplt.show()\n\"\"\"\n## 3. Dividing into training and testing sets\nNow we need to convert our data into training and testing sets. We will use 75% of the images as our training data and test our model on the remaining 25% with Scikit-learn's train_test_split function.\n\"\"\"\ntrainset_df, testset_df = train_test_split(df, train_size = 0.75, random_state = 4)\n\ndisplay(trainset_df.head())\n\ntestset_df.head()\n# converting the Label to a numeric format for testing later...\nLE = LabelEncoder()\n\ny_test = LE.fit_transform(testset_df[\"Label\"])\n# Viewing data in training dataset\nprint('Training Dataset:')\n\nprint(f'Number of images: {trainset_df.shape[0]}')\n\nprint(f'Number of images with malee eyes: {trainset_df[\"Label\"].value_counts()[0]}')\nprint(f'Number of images with femalee eyes: {trainset_df[\"Label\"].value_counts()[1]}\\n')\n\n# Viewing data in test dataset\nprint('Test Dataset:')\n\nprint(f'Number of images: {testset_df.shape[0]}')\n\nprint(f'Number of images with malee eyes: {testset_df[\"Label\"].value_counts()[0]}')\nprint(f'Number of images with femalee eyes: {testset_df[\"Label\"].value_counts()[1]}\\n')\n\"\"\"\n## 4. Generating batches of images\nIn this part we will generate batches of images increasing the training data, for the test database we will just normalize the data using [ImageDataGenerator](https:\/\/keras.io\/api\/preprocessing\/image\/#imagedatagenerator-class)\n\nParameters of ``ImageDataGenerator``:\n\n    rescale - Transform image size (normalization of data)\n    shear_range - Random geometric transformations\n    zoom_range - Images that will be zoomed\n    rotation_range - Degree of image rotation\n    width_shift_range - Image Width Change Range\n    height_shift_range - Image height change range\n    horizontal_flip - Rotate images horizontally\n    vertical_flip - Rotate images vertically\n    validation_split - Images that have been reserved for validation (0-1)\n\"\"\"\ntrain_datagen = ImageDataGenerator(rescale = 1.\/255,\n                                    shear_range = 0.2,\n                                    zoom_range = 0.1,\n                                    rotation_range = 20,\n                                    width_shift_range = 0.1,\n                                    height_shift_range = 0.1,\n                                    horizontal_flip = True,\n                                    vertical_flip = True,\n                                    validation_split = 0.1)\n\ntest_datagen = ImageDataGenerator(rescale = 1.\/255)\n\"\"\"\n## 5. Directory of training, validation and test images\n\nHere we make the division of the image bases for training, validation and testing of the model, for that we use the [flow_from_dataframe](https:\/\/keras.io\/api\/preprocessing\/image\/#flowfromdataframe-method)\n\nParameters of ``flow_from_directory``:\n\n    dataframe - Dataframe containing the images directory\n    x_col - Column name containing the images directory\n    y_col - Name of the column containing what we want to predict\n    target_size - size of the images (remembering that it must be the same size as the input layer)\n    color_mode - RGB color standard\n    class_mode - binary class mode (cat\/dog)\n    batch_size - batch size (32)\n    shuffle - Shuffle the data\n    seed - optional random seed for the shuffle\n    subset - Subset of data being training and validation (only used if using validation_split in ImageDataGenerator)\n\"\"\"\nprint(\"Preparing the training dataset ...\")\ntraining_set = train_datagen.flow_from_dataframe(\n    dataframe = trainset_df,\n    x_col = \"File\",\n    y_col = \"Label\",\n    target_size = (75, 75),\n    color_mode = \"rgb\",\n    class_mode = \"binary\",\n    batch_size = 32,\n    shuffle = True,\n    seed = 2,\n    subset = \"training\")\n\nprint(\"Preparing the validation dataset ...\")\nvalidation_set = train_datagen.flow_from_dataframe(\n    dataframe = trainset_df,\n    x_col = \"File\",\n    y_col = \"Label\",\n    target_size = (75, 75),\n    color_mode =\"rgb\",\n    class_mode = \"binary\",\n    batch_size = 32,\n    shuffle = True,\n    seed = 2,\n    subset = \"validation\")\n\nprint(\"Preparing the test dataset ...\")\ntest_set = test_datagen.flow_from_dataframe(\n    dataframe = testset_df,\n    x_col = \"File\",\n    y_col = \"Label\",\n    target_size = (75, 75),\n    color_mode =\"rgb\",\n    class_mode = \"binary\",\n    shuffle = False,\n    batch_size = 32)\n\nprint('Data generators are ready!')\nprint(\"Training: \")\nprint(training_set.class_indices)\nprint(training_set.image_shape)\nprint(\"---\" * 8)\nprint(\"Validation: \")\nprint(validation_set.class_indices)\nprint(validation_set.image_shape)\nprint(\"---\" * 8)\nprint(\"Test: \")\nprint(test_set.class_indices)\nprint(test_set.image_shape)\n\"\"\"\nUse of callbacks to monitor models and see if metrics will improve, otherwise training is stopped.\n\n``EarlyStopping`` parameters:\n\n    monitor - Metrics that will be monitored\n    patience - Number of times without improvement in the model, after these times the training is stopped\n    restore_best_weights - Restores best weights if training is interrupted\n\"\"\"\n# Callbacks\ncb = [EarlyStopping(monitor = 'loss', mode = 'min', patience = 15, restore_best_weights = True)]\n\"\"\"\n## 6. Construction of the first model (ConvNet)\n\nCNNs are a specific type of artificial neural network that is very effective for image classification because they are able to take into account the spatial coherence of the image, that is, that pixels close to each other are often related.\n\nThe construction of a CNN begins with specifying the model type. In our case, we will use a ``Sequential`` model.\n\n<p><img src = \"https:\/\/i.ibb.co\/0jWhFsW\/ConvNet.png\" alt><\/p>\n\"\"\"\n\"\"\"\n###### Step 1 - Convolution\nFeature Detector and Feature Map\n\n    Number of filters (32)\n    Dimensions of the feature detector (3, 3)\n    Definition of height \/ width and RGB channels (128, 128, 3)\n    Activation function to remove negative values from the image - 'relu'\n    Processing acceleration - BatchNormalization\n\"\"\"\nCNN = Sequential()\n\nCNN.add(Conv2D(32, (3, 3), input_shape = (75, 75, 3), activation = 'relu'))\nCNN.add(BatchNormalization())\n\"\"\"\n###### Step 2 - Max Pooling\nReduced image size by focusing on the most important features\n\n     Matrix definition with a total of 4 pixels (2, 2)\n\"\"\"\nCNN.add(MaxPooling2D(pool_size = (2, 2)))\n\"\"\"\n###### Step 3 - Hidden Layers\n\"\"\"\nCNN.add(Conv2D(32, (3, 3), activation = 'relu'))\nCNN.add(MaxPooling2D(pool_size = (2, 2)))\nCNN.add(Conv2D(64, (3, 3), activation = 'relu'))\nCNN.add(SpatialDropout2D(0.2))\nCNN.add(MaxPooling2D(pool_size = (2, 2)))\n\"\"\"\n###### Step 4 - Flattening\n    \n     Transforming the matrix to a vector to enter the Artificial Neural Network layer\n\"\"\"\nCNN.add(Flatten())\n\"\"\"\n###### Step 5 - Dense Neural Networks\n\nParameters of the `` RNA``:\n\n     Dense - All neurons connected\n     units - Number of neurons that are part of the hidden layer\n     activation - Activation function that will be inserted\n     Dropout - is used to decrease the chance of overfitting (20% of the input neurons are zeroed)\n\nParameters of the ``EarlyStopping``:\n\n     monitor - Metric to be monitored\n     patience - Number of seasons without improvement in the model, after the training is interrupted\n     restore_best_weights - Restores the best weights if training is interrupted\n\"\"\"\n# Input layer\nCNN.add(Dense(units = 128, activation = 'relu'))\nCNN.add(Dropout(0.2))\n# Output layer (binary classification)\nCNN.add(Dense(units = 1, activation = 'sigmoid'))\n\nprint(CNN.summary())\nplot_model(CNN, to_file='CNN_model.png', show_layer_names = True , show_shapes = True)\n\"\"\"\n###### Step 6 - Model compilation and training\n\nNow that we have specified the model architecture, we will compile the model for training. For this, we need to specify the loss function (what we are trying to minimize), the optimizer (how we want to do to minimize the loss) and the metric (how we will judge the model's performance). Next, we will call .fit to start training the process.\n\n``Compile`` parameters:\n\n     optimizer - descent of the gradient and descent of the stochastic gradient\n     loss - Loss function (binary_crossentropy as there is only one exit)\n     metrics - Evaluation metrics (obs - more than one can be placed)\n\n``Fit`` parameters:\n\n     train_data - training database\n     epochs - number of seasons\n     validation_data - test database\n     callbacks - Using EarlyStopping\n     validation_steps - number of images to validation\n\"\"\"\n# Compile\nCNN.compile(optimizer='adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Start of counting time...\nstart = dt.datetime.now()\n\n# Train\nCNN_model = CNN.fit(training_set, epochs = 50, validation_data = validation_set, callbacks = cb)\n\n# End of counting time...\nend = dt.datetime.now()\ntime_CNN = end - start\nprint ('\\nTraining and validation time is: ', time_CNN)\n\"\"\"\n###### Step 7 - Model training history\n\nWe can see how accuracy improves over time, eventually leveling off. Correspondingly, the loss decreases over time. Plots like these can help diagnose overfitting. If we had seen an upward curve in the loss of validation over time (a U shape in the graph), we would suspect that the model was starting to memorize the test set and would not generalize well to new data.\n\"\"\"\nacc = CNN_model.history['accuracy']\nval_acc = CNN_model.history['val_accuracy']\nloss = CNN_model.history['loss']\nval_loss = CNN_model.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.title('Training and validation accuracy')\nplt.plot(epochs, acc, 'red', label='Training acc')\nplt.plot(epochs, val_acc, 'blue', label='Validation acc')\nplt.legend()\n\nplt.figure()\nplt.title('Training and validation loss')\nplt.plot(epochs, loss, 'red', label='Training loss')\nplt.plot(epochs, val_loss, 'blue', label='Validation loss')\n\nplt.legend()\n\nplt.show()\n\"\"\"\n###### Step 8 - Viewing results and generating forecasts\n\"\"\"\nscore_CNN = CNN.evaluate(test_set)\nprint(\"Test Loss:\", score_CNN[0])\nprint(\"Test Accuracy:\", score_CNN[1])\ny_pred_CNN = CNN.predict(test_set)\ny_pred_CNN = np.round(y_pred_CNN)\n\nrecall_CNN = recall_score(y_test, y_pred_CNN)\nprecision_CNN = precision_score(y_test, y_pred_CNN)\nf1_CNN = f1_score(y_test, y_pred_CNN)\nroc_CNN = roc_auc_score(y_test, y_pred_CNN)\nprint(classification_report(y_test, y_pred_CNN))\nplt.figure(figsize = (6, 4))\n\nsns.heatmap(confusion_matrix(y_test, y_pred_CNN),annot = True, fmt = 'd')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\n\nplt.show()\n# Save the model\nmodelFileName = 'cats-dogs-classifier.h5'\nCNN.save(modelFileName)\nprint('model saved as', modelFileName)\n\"\"\"\n## 9. Construction of the second model (Inception)\nThe [InceptionV3](https:\/\/keras.io\/api\/applications\/inceptionv3\/) model proposed by Szegedy et al. (2015), is a CNN architecture that seeks to solve several large-scale image recognition problems and can also be used in transfer learning problems. Its differential is the presence of convolutional characteristics extractor modules. These modules have the functionality to learn with fewer parameters that contain a greater range of information.\n\n<p><img src = \"https:\/\/cloud.google.com\/tpu\/docs\/images\/inceptionv3onc--oview.png?hl=pt-br\" alt><\/p>\n\"\"\"\n\"\"\"\n###### Step 1 - Base model creation\n    input_shape - Setting the height\/width and RGB channels (128, 128, 3)\n    include_top - Fully connected layer will not be included on top\n    weights - Pre-training using imagenet\n\"\"\"\nCNN_base_inc = InceptionV3(input_shape = (75, 75, 3), include_top = False, weights = 'imagenet')\nfor layer in CNN_base_inc.layers:\n    layer.trainable = False\n\"\"\"\n###### Step 2 - Flattening\n    Transforming the matrix to a vector to enter the Artificial Neural Network layer\n\"\"\"\nx = layers.Flatten()(CNN_base_inc.output)\n\"\"\"\n###### Step 3 - Dense Neural Networks\n\n    Dense - All connected neurons\n    units - Number of neurons that are part of the hidden layer\n    activation - Activation function that will be inserted\n    Dropout - is used to decrease the chance of overfitting (40% of input neurons are zeroed)\n\"\"\"\nx = layers.Dense(256, activation='relu')(x)\nx = layers.Dropout(0.1)(x)\nx = layers.Dense(1, activation='sigmoid')(x)\n\nCNN_inc = Model(CNN_base_inc.input, x)\n\"\"\"\n###### Step 4 - Model compilation and training\n\nNow that we have specified the model architecture, we will compile the model for training. For this, we need to specify the loss function (what we are trying to minimize), the optimizer (how we want to do to minimize the loss) and the metric (how we will judge the model's performance). Next, we will call .fit to start training the process.\n\n``Compile`` parameters:\n\n     optimizer - descent of the gradient and descent of the stochastic gradient\n     loss - Loss function (binary_crossentropy as there is only one exit)\n     metrics - Evaluation metrics (obs - more than one can be placed)\n\n``Fit`` parameters:\n\n     train_data - training database\n     epochs - number of seasons\n     validation_data - test database\n     callbacks - Using EarlyStopping\n     validation_steps - number of images to validation\n\"\"\"\n# Compilation\nCNN_inc.compile(optimizer = RMSprop(lr = 0.0001), loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Start of counting time\nstart = dt.datetime.now()\n\n# Training and validation\nCNN_inc_history = CNN_inc.fit(training_set, epochs = 50, validation_data = validation_set, callbacks = cb)\n\n# End of Time Counting\nend = dt.datetime.now()\ntime_CNN_inc = end - start\nprint ('\\nTraining and validation time is: ', time_CNN_inc)\n\"\"\"\n###### Step 5 - Model training history\n\nWe can see how accuracy improves over time, eventually leveling off. Correspondingly, the loss decreases over time. Plots like these can help diagnose overfitting. If we had seen an upward curve in the loss of validation over time (a U shape in the graph), we would suspect that the model was starting to memorize the test set and would not generalize well to new data.\n\"\"\"\nacc = CNN_inc_history.history['accuracy']\nval_acc = CNN_inc_history.history['val_accuracy']\nloss = CNN_inc_history.history['loss']\nval_loss = CNN_inc_history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.title('Training and validation accuracy')\nplt.plot(epochs, acc, 'red', label='Training acc')\nplt.plot(epochs, val_acc, 'blue', label='Validation acc')\nplt.legend()\n\nplt.figure()\nplt.title('Training and validation loss')\nplt.plot(epochs, loss, 'red', label='Training loss')\nplt.plot(epochs, val_loss, 'blue', label='Validation loss')\n\nplt.legend()\n\nplt.show()\n\"\"\"\n###### Step 6 - Viewing results and generating forecasts\n\"\"\"\nscore_inc = CNN_inc.evaluate(test_set)\nprint(\"Test Loss:\", score_inc[0])\nprint(\"Test Accuracy:\", score_inc[1])\ny_pred_inc = CNN_inc.predict(test_set)\ny_pred_inc = np.round(y_pred_inc)\n\nrecall_inc = recall_score(y_test, y_pred_inc)\nprecision_inc = precision_score(y_test, y_pred_inc)\nf1_inc = f1_score(y_test, y_pred_inc)\nroc_inc = roc_auc_score(y_test, y_pred_inc)\nprint(classification_report(y_test, y_pred_inc))\nplt.figure(figsize = (6, 4))\n\nsns.heatmap(confusion_matrix(y_test, y_pred_inc),annot = True, fmt = 'd')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\n\nplt.show()\n# Save the model\nmodelFileName = 'fire_classifier_model-inc.h5'\nCNN_inc.save(modelFileName)\nprint('model saved as', modelFileName)\n\"\"\"\n## 10. Construction of the third model (Xception)\nThe [Xception](https:\/\/www.tensorflow.org\/api_docs\/python\/tf\/keras\/applications\/Xception) model proposed by Chollet et al.(2016), is a CNN architecture similar to the Inception described above and, has the difference that the initiation modules were replaced by separable convolutions in depth. Xception has the same amount of parameters as InceptionV3 with a total of 36 convolutional layers. Thus, having a more efficient use of parameters.\n\n<p><img src = \"https:\/\/miro.medium.com\/max\/1688\/1*J8dborzVBRBupJfvR7YhuA.png\" alt><\/p>\n\"\"\"\n\"\"\"\n###### Step 1 - Base model creation\n\n    input_shape - Setting the height\/width and RGB channels (128, 128, 3)\n    include_top - Fully connected layer will not be included on top\n    weights - Pre-training using imagenet\n\"\"\"\nCNN_base_xcep = Xception(input_shape = (75, 75, 3), include_top = False, weights = 'imagenet')\nCNN_base_xcep.trainable = False\n\"\"\"\n###### Step 2 - Dense Neural Networks\n\n    Dense - All connected neurons\n    units - Number of neurons that are part of the hidden layer\n    activation - Activation function that will be inserted\n    Dropout - is used to decrease the chance of overfitting (40% of input neurons are zeroed)\n\"\"\"\nCNN_xcep = Sequential()\nCNN_xcep.add(CNN_base_xcep)\nCNN_xcep.add(GlobalAveragePooling2D())\nCNN_xcep.add(Dense(128))\nCNN_xcep.add(Dropout(0.1))\nCNN_xcep.add(Dense(1, activation = 'sigmoid'))\n\nCNN_xcep.summary()\nplot_model(CNN_xcep, show_layer_names = True , show_shapes = True)\n\"\"\"\n###### Step 4 - Model compilation and training\n\nNow that we have specified the model architecture, we will compile the model for training. For this, we need to specify the loss function (what we are trying to minimize), the optimizer (how we want to do to minimize the loss) and the metric (how we will judge the model's performance). Next, we will call .fit to start training the process.\n\n``Compile`` parameters:\n\n     optimizer - descent of the gradient and descent of the stochastic gradient\n     loss - Loss function (binary_crossentropy as there is only one exit)\n     metrics - Evaluation metrics (obs - more than one can be placed)\n\n``Fit`` parameters:\n\n     train_data - training database\n     epochs - number of seasons\n     validation_data - test database\n     callbacks - Using EarlyStopping\n     validation_steps - number of images to validation\n\"\"\"\n# Compilation\nCNN_xcep.compile(optimizer='adam', loss = 'binary_crossentropy',metrics=['accuracy'])\n\n# Start of counting time\nstart = dt.datetime.now()\n\n# Training and validation\nCNN_xcep_history = CNN_xcep.fit(training_set, epochs = 50, validation_data = validation_set, callbacks = cb)\n\n# End of Time Counting\nend = dt.datetime.now()\ntime_CNN_xcep = end - start\nprint ('\\nTraining and validation time: ', time_CNN_xcep)\n\"\"\"\n###### Step 5 - Model training history\n\nWe can see how accuracy improves over time, eventually leveling off. Correspondingly, the loss decreases over time. Plots like these can help diagnose overfitting. If we had seen an upward curve in the loss of validation over time (a U shape in the graph), we would suspect that the model was starting to memorize the test set and would not generalize well to new data.\n\"\"\"\nacc = CNN_xcep_history.history['accuracy']\nval_acc = CNN_xcep_history.history['val_accuracy']\nloss = CNN_xcep_history.history['loss']\nval_loss = CNN_xcep_history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.title('Training and validation accuracy')\nplt.plot(epochs, acc, 'red', label='Training acc')\nplt.plot(epochs, val_acc, 'blue', label='Validation acc')\nplt.legend()\n\nplt.figure()\nplt.title('Training and validation loss')\nplt.plot(epochs, loss, 'red', label='Training loss')\nplt.plot(epochs, val_loss, 'blue', label='Validation loss')\n\nplt.legend()\n\nplt.show()\n\"\"\"\n###### Step 8 - Viewing results and generating forecasts\n\"\"\"\nscore_xcep = CNN_xcep.evaluate(test_set)\nprint(\"Test Loss:\", score_xcep[0])\nprint(\"Test Accuracy:\", score_xcep[1])\ny_pred_xcep = CNN_xcep.predict(test_set)\ny_pred_xcep = np.round(y_pred_xcep)\n\nrecall_xcep = recall_score(y_test, y_pred_xcep)\nprecision_xcep = precision_score(y_test, y_pred_xcep)\nf1_xcep = f1_score(y_test, y_pred_xcep)\nroc_xcep = roc_auc_score(y_test, y_pred_xcep)\nprint(classification_report(y_test, y_pred_xcep))\nplt.figure(figsize = (6, 4))\n\nsns.heatmap(confusion_matrix(y_test, y_pred_xcep),annot = True, fmt = 'd')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\n\nplt.show()\nmodelFileName = 'fire_classifier_model-xcep.h5'\nCNN_xcep.save(modelFileName)\nprint('model saved as', modelFileName)\n\"\"\"\n## 12. Construction of the fourth model (MobileNet)\nThe MobileNet model proposed by Howard et al. (2017), is a CNN architecture that were created to perform computer vision tasks on mobile devices and embedded systems. They are based on in-depth separable convolution operations, which lessens the burden of operations in the first layers.\n\n<p><img src = \"https:\/\/nitheshsinghsanjay.github.io\/images\/mobtiny_fig.PNG\" alt><\/p>\n\"\"\"\n\"\"\"\n###### Step 1 - Base model creation\n\n    input_shape - Setting the height\/width and RGB channels (128, 128, 3)\n    include_top - Fully connected layer will not be included on top\n    weights - Pre-training using imagenet\n\"\"\"\nCNN_base_mobilenet = MobileNet(input_shape = (75, 75, 3), include_top = False, weights = 'imagenet')\nfor layer in CNN_base_mobilenet.layers:\n    layer.trainable = False\n\"\"\"\n###### Step 2 - Dense Neural Networks\n\n    Dense - All connected neurons\n    units - Number of neurons that are part of the hidden layer\n    activation - Activation function that will be inserted\n    Dropout - is used to decrease the chance of overfitting (40% of input neurons are zeroed)\n\"\"\"\nCNN_mobilenet = Sequential()\nCNN_mobilenet.add(BatchNormalization(input_shape = (75, 75, 3)))\nCNN_mobilenet.add(CNN_base_mobilenet)\nCNN_mobilenet.add(BatchNormalization())\nCNN_mobilenet.add(GlobalAveragePooling2D())\nCNN_mobilenet.add(Dropout(0.5))\nCNN_mobilenet.add(Dense(1, activation = 'sigmoid'))\n\nCNN_mobilenet.summary()\nplot_model(CNN_mobilenet, show_layer_names = True , show_shapes = True)\n\"\"\"\n###### Step 4 - Model compilation and training\n\nNow that we have specified the model architecture, we will compile the model for training. For this, we need to specify the loss function (what we are trying to minimize), the optimizer (how we want to do to minimize the loss) and the metric (how we will judge the model's performance). Next, we will call .fit to start training the process.\n\n``Compile`` parameters:\n\n     optimizer - descent of the gradient and descent of the stochastic gradient\n     loss - Loss function (binary_crossentropy as there is only one exit)\n     metrics - Evaluation metrics (obs - more than one can be placed)\n\n``Fit`` parameters:\n\n     train_data - training database\n     epochs - number of seasons\n     validation_data - test database\n     callbacks - Using EarlyStopping\n     validation_steps - number of images to validation\n\"\"\"\n# Compilation\nCNN_mobilenet.compile(optimizer='adam',loss = 'binary_crossentropy', metrics=['accuracy'])\n\n# Start of counting time\nstart = dt.datetime.now()\n\n# Training and validation\nCNN_mobilenet_history = CNN_mobilenet.fit(training_set, epochs = 50, validation_data = validation_set, callbacks = cb)\n\n# End of Time Counting\nend = dt.datetime.now()\ntime_CNN_mobilenet = end - start\nprint ('\\nTraining and validation time: ', time_CNN_mobilenet)\n\"\"\"\n###### Step 5 - Model training history\n\nWe can see how accuracy improves over time, eventually leveling off. Correspondingly, the loss decreases over time. Plots like these can help diagnose overfitting. If we had seen an upward curve in the loss of validation over time (a U shape in the graph), we would suspect that the model was starting to memorize the test set and would not generalize well to new data.\n\"\"\"\nacc = CNN_mobilenet_history.history['accuracy']\nval_acc = CNN_mobilenet_history.history['val_accuracy']\nloss = CNN_mobilenet_history.history['loss']\nval_loss = CNN_mobilenet_history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.title('Training and validation accuracy')\nplt.plot(epochs, acc, 'red', label='Training acc')\nplt.plot(epochs, val_acc, 'blue', label='Validation acc')\nplt.legend()\n\nplt.figure()\nplt.title('Training and validation loss')\nplt.plot(epochs, loss, 'red', label='Training loss')\nplt.plot(epochs, val_loss, 'blue', label='Validation loss')\n\nplt.legend()\n\nplt.show()\n\"\"\"\n###### Step 8 - Viewing results and generating forecasts\n\"\"\"\nscore_mn = CNN_mobilenet.evaluate(test_set)\nprint(\"Test Loss:\", score_mn[0])\nprint(\"Test Accuracy:\", score_mn[1])\ny_pred_mn = CNN_mobilenet.predict(test_set)\ny_pred_mn = np.round(y_pred_mn)\n\nrecall_mn = recall_score(y_test, y_pred_mn)\nprecision_mn = precision_score(y_test, y_pred_mn)\nf1_mn = f1_score(y_test, y_pred_mn)\nroc_mn = roc_auc_score(y_test, y_pred_mn)\nprint(classification_report(y_test, y_pred_mn))\nplt.figure(figsize = (6, 4))\n\nsns.heatmap(confusion_matrix(y_test, y_pred_mn),annot = True, fmt = 'd')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\n\nplt.show()\n# Save the model\nmodelFileName = 'fire_classifier_model-mobilenet.h5'\nCNN_mobilenet.save(modelFileName)\nprint('model saved as', modelFileName)\n\"\"\"\n## 13. Viewing the results of all models\n\"\"\"\nmodels= [('ConvNet', time_CNN, np.mean(CNN_model.history['accuracy']), np.mean(CNN_model.history['val_accuracy'])),\n         ('Inception', time_CNN_inc, np.mean(CNN_inc_history.history['accuracy']), np.mean(CNN_inc_history.history['val_accuracy'])),\n         ('Xception', time_CNN_xcep, np.mean(CNN_xcep_history.history['accuracy']), np.mean(CNN_xcep_history.history['val_accuracy'])),\n         ('MobileNet', time_CNN_mobilenet, np.mean(CNN_mobilenet_history.history['accuracy']), np.mean(CNN_mobilenet_history.history['val_accuracy']))]\n\ndf_all_models = pd.DataFrame(models, columns = ['Model', 'Time', 'Training accuracy (%)', 'Validation Accuracy (%)'])\n\ndf_all_models\nmodels = [('ConvNet', score_CNN[1], recall_CNN, precision_CNN, f1_CNN, roc_CNN),\n          ('Inception', score_inc[1], recall_inc, precision_inc, f1_inc, roc_inc),\n          ('Xception', score_xcep[1], recall_xcep, precision_xcep, f1_xcep, roc_xcep),\n          ('MobileNet', score_mn[1], recall_mn, precision_mn, f1_mn, roc_mn)]\n\ndf_all_models_testset = pd.DataFrame(models, columns = ['Model', 'Test accuracy (%)', 'Recall (%)', 'Precision (%)', 'F1 (%)', 'AUC'])\n\ndf_all_models_testset\nplt.subplots(figsize=(12, 10))\nsns.barplot(y = df_all_models_testset['Test accuracy (%)'], x = df_all_models_testset['Model'], palette = 'icefire')\nplt.xlabel(\"Models\")\nplt.title('Accuracy')\nplt.show()\nr_probs = [0 for _ in range(len(y_test))]\nr_auc = roc_auc_score(y_test, r_probs)\nr_fpr, r_tpr, _ = roc_curve(y_test, r_probs)\n\nfpr_cnn, tpr_cnn, _ = roc_curve(y_test, y_pred_CNN)\nfpr_inc, tpr_inc, _ = roc_curve(y_test, y_pred_inc)\nfpr_xcep, tpr_xcep, _ = roc_curve(y_test, y_pred_xcep)\nfpr_mn, tpr_mn, _ = roc_curve(y_test, y_pred_mn)\nsns.set_style('darkgrid')\n\nplt.plot(r_fpr, r_tpr, linestyle='--', label='Random prediction (AUROC = %0.3f)' % r_auc)\n\nplt.plot(fpr_cnn, tpr_cnn, marker='.', label='ConvNet (AUROC = %0.3f)' % roc_CNN)\nplt.plot(fpr_inc, tpr_inc, marker='.', label='Inception (AUROC = %0.3f)' % roc_inc)\nplt.plot(fpr_xcep, tpr_xcep, marker='.', label='Xception (AUROC = %0.3f)' % roc_xcep)\nplt.plot(fpr_mn, tpr_mn, marker='.', label='MobileNet (AUROC = %0.3f)' % roc_mn)\n\nplt.title('ROC Plot')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend() \nplt.show()\ntest_set.class_indices\nplt.style.use(\"dark_background\")\n\n\nfig, axes = plt.subplots(nrows = 4,\n                         ncols = 4,\n                         figsize = (15, 15),\n                        subplot_kw={'xticks': [], 'yticks': []})\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(plt.imread(testset_df[\"File\"].iloc[i]))\n    ax.set_title(f\"True: {testset_df.Label.iloc[i]}\\n Predicted:\\nConvNet: {y_pred_CNN[i]}\\nInception: {y_pred_inc[i]}\\nXception: {y_pred_xcep[i]}\\nMobileNet: {y_pred_mn[i]}\")\nplt.tight_layout()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '86f8d1785b6c97'}"}
{"id":"37979","text":"# 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\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import IsolationForest\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.impute import KNNImputer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Lasso, Ridge, ElasticNet\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import RidgeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn.ensemble import VotingClassifier\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import RandomOverSampler\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import RFE\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import roc_auc_score\n\n\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\ntrain = pd.read_csv('..\/input\/iba-ml1-mid-project\/train.csv')\ntest = pd.read_csv('..\/input\/iba-ml1-mid-project\/test.csv')\ndf = train.replace(',','.', regex=True).astype(float) #changed the type to float as data type one of the columns was object\niso=IsolationForest(contamination=0.10)\nimp=SimpleImputer(strategy='mean')\nX=df[['age','number_dependent_family_members', 'monthly_income', 'number_of_credit_lines', 'real_estate_loans', 'ratio_debt_payment_to_income','credit_line_utilization','number_of_previous_late_payments_up_to_59_days','number_of_previous_late_payments_up_to_89_days','number_of_previous_late_payments_90_days_or_more']]\ny=df[['defaulted_on_loan']]\n\nrus=RandomUnderSampler(random_state=42)\nros=RandomOverSampler(random_state=42)\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8) \n\n\"\"\"\nAny train_size ratio yielded same results.\n\"\"\"\nX_rus_train, y_rus_train = rus.fit_resample(X_train, y_train)\n\n\"\"\"\nDecided to undersample the data since oversampling would take much more time to calculate.\n\"\"\"\nsns.scatterplot(data=X_rus_train, x='age', y='monthly_income') #taking on pair plot to compair it to after outlier removal \n\noutlier_predXtr = iso.fit_predict(imp.fit_transform(X_rus_train)) #checking outliers in X_train\nmask=outlier_predXtr != -1\nX_train2, y_train2 = X_rus_train.iloc[mask, :], y_rus_train.iloc[mask] #updating training dataset\nsns.scatterplot(data=X_train2, x='age', y='monthly_income') \n\n\"\"\"\nWe can see that number of outliers decreased previous operation\n\"\"\"\nestimator=SVR(kernel='linear')\nnumerics = ['age','number_dependent_family_members', 'monthly_income', 'number_of_credit_lines', 'real_estate_loans', 'ratio_debt_payment_to_income','credit_line_utilization','number_of_previous_late_payments_up_to_59_days','number_of_previous_late_payments_up_to_89_days','number_of_previous_late_payments_90_days_or_more']\nnumeric_transformer = Pipeline(steps=[\n    ('impute', KNNImputer()),\n    ('scaler', MinMaxScaler())\n    ])\n\ncolumn_preprocessing = ColumnTransformer(transformers=[\n    ('numeric', numeric_transformer, numerics)\n    \n    ])\n\nmodel = Pipeline(steps=[\n    ('preprocessing', column_preprocessing),\n    ('feat_select', RFE(estimator)),\n    ('classification', VotingClassifier(estimators=[\n        ('dt', DecisionTreeClassifier()),\n        ('knn', KNeighborsClassifier()),\n        ('randomforest', RandomForestClassifier())\n    ], voting='soft'))\n    ])\n\n  \nparam_space = {\n    'preprocessing__numeric__impute__n_neighbors':[3,9],\n    'classification__knn__n_neighbors':[3,9],\n    'classification__dt__max_depth':[5,7],\n    'feat_select__n_features_to_select':[4,7]\n    }\ngs= GridSearchCV(model, param_space, cv= 15, scoring='roc_auc', refit='precision_score')\n\ngs.fit(X_train2, y_train2.values.ravel() )\n\ny_predict=gs.predict(X_test) #find target values on test dataset\ny_predict\n\"\"\"\nInitially I was calculating roc_auc_score by using gs.predict which would show 75% score. Later I realized that the task is to find probabilities of positive and negative cases, so I used gs.predict_proba which showed better results of ~82%\n\"\"\"\ny_predict_probs = gs.predict_proba(X_test) #find probabilities of target values on test dataset\ny_predict_probs\nplot_confusion_matrix(gs, X_test, y_test) \npositive_probs = y_predict_probs[:, 1]\n\nroc_auc_score(y_test, positive_probs)\n\nnewtest=test.drop(['Id'], axis=1).replace(',','.', regex=True).astype(float) #preparing test data\nresultsprob=gs.predict_proba(newtest) # .replace(',','.', regex=True).astype(float))\nresultsprob.shape #checking the size \nresultsdfprob=pd.DataFrame(resultsprob[:,1], columns = ['Predicted'])\nresultsdfprob.index.name = 'Id'\nresultsdfprob.index += 1 \nresultsdfprob.to_csv('submission proba Aghamir Aghazada.csv')\n\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve\nfrom matplotlib import pyplot\nfpr, tpr, thresholds = roc_curve(y_test, positive_probs)\n\npyplot.plot(fpr, tpr, marker='.', label='model')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.plot([0, 1], [0, 1], linestyle='--', label='No Skill')\npyplot.legend()\npyplot.show()","meta":"{'source': 'AI4Code', 'id': '45f54c087c9869'}"}
{"id":"53551","text":"#The aim of the data analysis is to select the suitable methods to forcast the students' grades in period three by using some parameters that have correlations with G3.\n#import necessary libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.linear_model import LinearRegression, SGDRegressor, Ridge\nfrom sklearn.model_selection import GridSearchCV\n\"\"\"\n1. Reading data\n\"\"\"\n# Reading data\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\ndata=pd.read_csv('\/kaggle\/input\/student-grade-prediction\/student-mat.csv')\ndata.head()\n#Showing all columns of the data\ndata.columns\n\"\"\"\n2. Processing data\n\"\"\"\n#We need to predict the grade of G3 by using the data including G1, G2, health, absences.\n#We will decide which colunmns we need to set as the features\n#The features we choose based on the common sense are \"Medu\", \"Fedu\", \"traveltime\", \"studytime\", \"famrel\", \"Dalc\", \"Walc\" , \"health\", \"absences\", \"G1\", and \"G2\"\n#Setting these columns as x\nx=data[[\"Medu\", \"Fedu\", \"traveltime\", \"studytime\", \"famrel\", \"Dalc\", \"Walc\" , \"health\", \"absences\", \"G1\", \"G2\"]]\nprint(x)\nx.head()\ny=data[\"G3\"]\nprint(y.head())\n#Check if the data contains Nan value\nna_cols=data.isna().any()\nna_cols = na_cols[na_cols == True] \nprint(na_cols)\n#It turns out the data do not contain any Nan\n#The statistics of G3\nm= y.value_counts().sort_values()\nprint(m)\n\"\"\"\n3. Drawing pictures\n\"\"\"\n#We can draw some pictures to mark the relationship between the factors that may influence G3 \nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"Medu\"], y, width=0.5)\nplt.show()\n#The higer their mothers' education levels are, the higer the grade students can achieve in the period three.\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"Fedu\"], y, width=0.5)\nplt.show()\n#The connection between fathers' education and students' grades are weak.\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"traveltime\"], y, width=0.5)\nplt.show()\n#It seems that less travel time contributes to a higher grade.\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"studytime\"], y, width=0.5)\nplt.show()\n#The grades are not obviously different when the students spend different time in studying. The tendency is that more studytime may contribute to a better grade.\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"famrel\"], y, width=0.5)\nplt.show()\n#The high quality family relationship promotes the students' performance on grades \nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"Dalc\"], y, width=0.5)\nplt.show()\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"Walc\"], y, width=0.5)\nplt.show()\n#The students using alchohol at weekends does littel influence on their grades. However, the students using much alchohol at weekdays tend to have higher grades.\nplt.figure(figsize=(20, 8), dpi=100)\nplt.scatter(data[\"health\"], y)\nplt.show()\n#It seems that the students whose health level is two have the competitive advantage in grades\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"absences\"], y, width=0.5)\nplt.show()\n#It is obvious that less absence number links to a higher degree\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"G1\"], y, width=0.5)\nplt.show()\n#The students who acquire the higher grade in period one tend to gain the higer grade in period three\nplt.figure(figsize=(20, 8), dpi=100)\nplt.bar(data[\"G2\"], y, width=0.5)\nplt.show()\n#The students who acquire the higher grade in period two tend to gain the higer grade in period three\n#After the analysis, we can exclude factor of \"Walc\" and \"Fedu\" , which have less correlation with G3 \nx_new=x.drop([\"Walc\", \"Fedu\"], axis=1)\nprint(x_new.head())\n\"\"\"\n4. Preparing data for machine learning\n\"\"\"\n#Dividing the data as parts of test and train\nx_train, x_test, y_train, y_test=train_test_split(x_new, y, random_state=6)\n#standardizing x data\ntransfer = StandardScaler()\nx_train = transfer.fit_transform(x_train)\nx_test = transfer.transform(x_test)\n\"\"\"\n5. Machine learning methods\n\"\"\"\n#Using Random Forest\nestimator=RandomForestClassifier(n_estimators=10, criterion=\"entropy\", max_depth=8, bootstrap=True, max_features=\"auto\")\nestimator.fit(x_train, y_train)\ny_predict=estimator.predict(x_test)\naccuracy = estimator.score(x_test, y_test)\nprint(\"The accuracy by RandomForest:\\n\", accuracy)\n#Using Xgboost\nestimator= XGBClassifier()\nestimator.fit(x_train, y_train)\ny_predict=estimator.predict(x_test)\naccuracy = estimator.score(x_test, y_test)\nprint(\"The accuracy by Xgboost:\\n\", accuracy)\n#Using linear Regression\nestimator=LinearRegression(fit_intercept=True)\nestimator.fit(x_train, y_train)\nprint(estimator.coef_)\nprint(estimator.intercept_)\ny_predict=estimator.predict(x_test)\nprint(\"Forcasted number by Linear regression\uff1a\\n\", y_predict)\nprint(\"The accuracy by linear regression:\\n\", accuracy)\n#Using Ridge\nestimator=Ridge(alpha=1, max_iter=10000)\nestimator.fit(x_train, y_train)\nprint(estimator.coef_)\nprint(estimator.intercept_)\ny_predict=estimator.predict(x_test)\nprint(\"Forcasted number by Ridge\uff1a\\n\", y_predict)\naccuracy = estimator.score(x_test, y_test)\nprint(\"The accuracy by Ridge:\\n\", accuracy)\n#Using gridsearch to find the best parameters\nparam_dict = {\"alpha\": [0.5, 0.6, 0.7, 0.8, 0.9, 1], \"max_iter\":[10000, 50000, 100000, 150000, 200000]}\nestimator = GridSearchCV(estimator, param_grid=param_dict, cv=10)\nestimator.fit(x_train,y_train)\nprint(\"best parameters:\\n\", estimator.best_params_)\nprint(\"best estimator\uff1a\\n\", estimator.best_estimator_)\nprint(\"best score:\\n\", estimator.best_score_)\n#Using SDGRegressor\nestimator=SGDRegressor(max_iter=10000)\nestimator.fit(x_train, y_train)\nprint(estimator.coef_)\nprint(estimator.intercept_)\ny_predict=estimator.predict(x_test)\nprint(\"Forcasted number by SDGRegressor\uff1a\\n\", y_predict)\naccuracy = estimator.score(x_test, y_test)\nprint(\"The accuracy by SGDRegressor:\\n\", accuracy)\n\"\"\"\nconclusion: \n1. As we can see, the best forcasting methods are SGDRegressor and Ridge to forcast the students' grades in the third period. \n2. The past grades in period 1 and period 2 play the key roles in determining the final grades of the students. Study is a continued process. Please build the foundation at the beginning!\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '62940ecd8b4486'}"}
{"id":"130499","text":"# 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 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\ndf=pd.read_csv('\/kaggle\/input\/housing-prices-in-metropolitan-areas-of-india\/Mumbai.csv')\ndf.shape\npd.set_option('display.max_columns',None)\ndf.head()\nnumeric_data=df.select_dtypes(exclude='object').drop(['Price'],axis=1).copy()\nnumeric_data.head()\ncategorical_data=df.select_dtypes(include='object')\ncategorical_data.head()\n#Count plot (categorical, univariate analysis)\nimport matplotlib.pyplot as plt\nimport seaborn as sns \n\ndf1=df.copy()\ndf1['Area'] = pd.cut(df1['Area'], bins=[0, 250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000, np.inf])\nfig=plt.figure(figsize=(20,30))\nfor i,col in enumerate(numeric_data):\n    fig.add_subplot(10,4,i+1)\n    sns.countplot(df1[col])\n    plt.xlabel(col,size=15)\n    plt.xticks(rotation=90)\nplt.tight_layout(pad=1)\nplt.show()\n \nfig,ax=plt.subplots(figsize=(23,20))\nax.set_title('Houses at each Location',fontsize=20)\nsns.countplot(y='Location',data=df, order=df.Location.value_counts().index[:50])\nax.set_xlabel('Locations',fontsize=20)\nax.set_ylabel('No. of Houses',fontsize=20)\nplt.show()\n#Count plot (categorical, univariate analysis)\nfig=plt.figure(figsize=(18,20))\nsns.countplot(df1['Area'])\nplt.xlabel('Area',fontsize=15)\nplt.ylabel('No. of Houses',fontsize=15)\nplt.xticks(rotation=40)\nplt.tight_layout(pad=1)\nplt.show()\ndf2=df.copy().replace(9,np.nan)\ndf2=df2.fillna(method='bfill',axis=0).fillna(0)\ndf2.head()\n#Correlation\nnum=df2.select_dtypes(exclude='object')\nnumeric_correlation=num.corr()\nplt.figure(figsize=(10,10))\nplt.title('Correlation')\nsns.heatmap(numeric_correlation>0.8, annot=True, square=True)\nprint(numeric_correlation['Price'].sort_values(ascending=False))\n#dropping features due to high correlation\ndf2.drop(['Hospital','AC','Refrigerator','LiftAvailable'],axis=1,inplace=True)\n#Missing Values\npd.DataFrame(df2.isnull().sum(), columns=['sum']).sort_values(by=['sum'],ascending=False).head(51)\nplt.figure(figsize=(10,6))\nplt.title(\"Distrubution of SalePrice\")\ndist = sns.distplot(df2['Price'],norm_hist=False)\nplt.figure(figsize=(10,6))\nplt.title(\"Distrubution of SalePrice\")\ndist = sns.distplot(np.log(df2['Price']),norm_hist=False)\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom xgboost import XGBRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom lightgbm import LGBMRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom catboost import CatBoostRegressor\nfrom sklearn.model_selection import train_test_split\n\nx = df2.drop(['Price'], axis=1) \ny = np.log1p(df2['Price'])\nX_train, X_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=1)\n\ncategorical_cols = [cname for cname in x.columns if\n                    x[cname].dtype == \"object\"] \n                \n\n\nnumerical_cols = [cname for cname in x.columns if\n                 x[cname].dtype in ['int64','float64','uint8']]\n\n\nmy_cols = numerical_cols + categorical_cols\nX_train = X_train[my_cols].copy()\nX_val = X_val[my_cols].copy()\nprint(categorical_cols,numerical_cols)\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\n\nnum_transformer = Pipeline(steps=[\n    ('num_imputer', SimpleImputer(strategy='constant'))\n    ])\n\ncat_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))\n    ])\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num',num_transformer,numerical_cols),       \n        ('cat',cat_transformer,categorical_cols),\n        ])\n# Reversing log-transform on y\ndef inv_y(transformed_y):\n    return np.exp(transformed_y)\n\nn_folds = 10\n# XGBoost\nmodel = XGBRegressor(learning_rate=0.01, n_estimators=3460, max_depth=3, min_child_weight=0,gamma=0, subsample=0.7,colsample_bytree=0.7,objective='reg:squarederror', nthread=-1,scale_pos_weight=1, seed=27, reg_alpha=0.00006)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                      ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('XGBoost: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))\n\n\n# Lasso  \nfrom sklearn.linear_model import LassoCV\n\nmodel = LassoCV(max_iter=1e7,  random_state=14, cv=n_folds)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                          ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('Lasso: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))\n\n# GradientBoosting   \nmodel = GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=4, random_state=5)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                          ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('Gradient: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))\n\"\"\"\n# Only using columns with no missing (not available) values\n\"\"\"\ndf3=df[['Price','Area','No. of Bedrooms','Resale','Location']].copy()\ndf3.head()\nfrom sklearn.model_selection import train_test_split\n\nx = df3.drop(['Price'], axis=1) \ny = np.log1p(df3['Price'])\nX_train, X_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=1)\n\ncategorical_cols = [cname for cname in x.columns if\n                    x[cname].dtype == \"object\"] \n                \n\n\nnumerical_cols = [cname for cname in x.columns if\n                 x[cname].dtype in ['int64','float64','uint8']]\n\n\nmy_cols = numerical_cols + categorical_cols\nX_train = X_train[my_cols].copy()\nX_val = X_val[my_cols].copy()\nprint(categorical_cols,numerical_cols)\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\n\nnum_transformer = Pipeline(steps=[\n    ('num_imputer', SimpleImputer(strategy='constant'))\n    ])\n\ncat_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))\n    ])\n\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num',num_transformer,numerical_cols),       \n        ('cat',cat_transformer,categorical_cols),\n        ])\n# XGBoost\nmodel = XGBRegressor(learning_rate=0.01, n_estimators=3460, max_depth=3, min_child_weight=0,gamma=0, subsample=0.7,colsample_bytree=0.7,objective='reg:squarederror', nthread=-1,scale_pos_weight=1, seed=27, reg_alpha=0.00006)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                      ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('XGBoost: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))\n\n\n# Lasso  \nfrom sklearn.linear_model import LassoCV\n\nmodel = LassoCV(max_iter=1e7,  random_state=14, cv=n_folds)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                          ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('Lasso: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))\n\n# GradientBoosting   \nmodel = GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=4, random_state=5)\nclf = Pipeline(steps=[('preprocessor', preprocessor),\n                          ('model', model)])\nclf.fit(X_train, y_train)\npredict = clf.predict(X_val)\nprint('Gradient: ' + str(mean_absolute_error(inv_y(predict), inv_y(y_val))))","meta":"{'source': 'AI4Code', 'id': 'eff8871e2fc686'}"}
{"id":"100585","text":"\"\"\"\n# Bitcoin forecast with Keras\nAn attempt to predict the price of Bitcoin with Keras.\n\nBut I got some Problems.\n\n\n# # Used Sources\n\n* *1 This gave me apparently good results. [First steps and basis for forecasting](https:\/\/towardsdatascience.com\/bitcoin-price-prediction-using-lstm-9eb0938c22bd)\n* *2 But then I read this and tried the improvements mentioned. [For corrections and optimizations](https:\/\/stackoverflow.com\/questions\/48760472\/how-to-use-a-keras-rnn-model-to-forecast-for-future-dates-or-events)\n\nBoth of got me to the code and plot above.\n\n\n# # My questions now \n* How to get better results? \n* How to predict 1 to X days of the (real) future? How to get the \"unknown\"?\n\n\n\"\"\"\nimport numpy as np \nimport pandas as pd \nfrom matplotlib import pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.python.compiler.tensorrt import trt_convert as trt\n\nimport keras as ke\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\n\n#from keras.models import Model\n#from keras.models import Sequential\n#from keras.layers import Dense\n#from keras.layers import LSTM, CuDNNLSTM\n\nfrom sklearn.preprocessing import MinMaxScaler\nmin_max_scaler = MinMaxScaler()\n\nprint(tf.__version__)\nprint(ke.__version__)\nprint(\"ready\")\n\"\"\"\nReading CSV with Bitcoin-Close-Prices only.\n\"\"\"\ndf = pd.read_csv(\"..\/input\/historical_data_btc_only_close.csv\", delimiter=';')\ndf_norm = df\n\nprint(df_norm)\n\"\"\"\nSplitting into test and train.\n\"\"\"\nprediction_days = 30\n\ndf_train= df[:len(df)-prediction_days]\ndf_test= df[len(df)-prediction_days:]\n\n\"\"\"\nReshaping the sets like mentioned in \"Used Sources\" *2. \n\"\"\"\ntraining_set = df_train.values\ntraining_set = min_max_scaler.fit_transform(training_set)\n\nx_train = training_set[0:len(training_set)-1]\ny_train = training_set[1:len(training_set)]\nx_train = np.reshape(x_train, (1, len(x_train), 1))\ny_train = np.reshape(y_train, (1, len(y_train), 1))\n\nprint(x_train.shape)\nprint(y_train.shape)\nprint(y_train)\nprint(x_train)\nfrom tensorflow.python.compiler import tensorrt as trt\n\nnum_units = 4\nactivation_function = 'sigmoid'\noptimizer = 'RMSProp'\nloss_function = 'binary_crossentropy'\nbatch_size = 1 # Only 1 due to a problem where a size was requested by which the passed model can be divided. \nnum_epochs = 50\n\n# Initialize the RNN\nregressor = Sequential()\n\n# Adding the input layer and the LSTM layer\nregressor.add(LSTM(units = num_units, \n                   #activation = activation_function, \n                   input_shape=(None, 1), \n                   stateful=False, \n                   return_sequences=True,\n                   batch_input_shape=(1, None, 1)\n#                    input_shape=(1, len(x_train), 1)\n                  ))\n\n# Adding the output layer\nregressor.add(Dense(units = 1))\n\n# Compiling the RNN\nregressor.compile(optimizer = optimizer, loss = loss_function)\n\n# Using the training set to train the model\nimport time\nstart = time.time()\nregressor.fit(x_train, y_train, batch_size = batch_size, epochs = num_epochs)\nend = time.time()\nregressor.summary()\nprint(end - start)\n\"\"\"\nShaping, scaling, starting prediction, printing the numbers. \n\"\"\"\ntest_set = df_test.values\nprint(test_set.shape)\nshape1 = test_set.shape[0] \nshape2 = test_set.shape[1]\n\n\ninputs = np.reshape(test_set, (shape1, shape2))\nprint(inputs.shape)\n\ninputs = min_max_scaler.transform(inputs)\nprint(inputs.shape)\n\ninputs = np.reshape(inputs, (1, shape1, shape2))\nprint(inputs.shape)\n\npredicted_price = regressor.predict(inputs)\n\nprint(predicted_price.shape)\n# print((predicted_price))\n\npredicted_price = np.reshape(predicted_price, (shape1, shape2))\nprint(predicted_price.shape)\n\npredicted_price = min_max_scaler.inverse_transform(predicted_price)\n\nprint(predicted_price.size)\nprint(predicted_price)\nprint(test_set.size)\n\n# regressor.predict_proba\nfor i in range(0, prediction_days):\n    print(test_set[i][0],\"-\" , predicted_price[i][0],\"\\tDifference: \" ,test_set[i][0]-predicted_price[i][0])\nplt.figure(figsize=(25, 25), dpi=80, facecolor = 'w', edgecolor = 'k')\n\nplt.plot(test_set[:, 0], color='red', label='Real BTC Price')\nplt.plot(predicted_price[:, 0], color = 'blue', label = 'Predicted BTC Price')\n\nplt.title('BTC Price Prediction', fontsize = 40)\nplt.xlabel('Time', fontsize=40)\nplt.ylabel('BTC Price(USD)', fontsize = 40)\nplt.legend(loc = 'best')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'b8dbe2cfdc8bf0'}"}
{"id":"90568","text":"\"\"\"\n# Libraries and Data import\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport datetime\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom urllib.request import urlopen\nimport json\nimport ipywidgets as widgets\nfrom IPython.display import clear_output\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom plotly.offline import init_notebook_mode\ninit_notebook_mode(connected=True)\n\n#If needed other libraries will be called during the project \ndf = pd.read_csv('..\/input\/sales-forecasting\/train.csv')\n\"\"\"\n# Data exploration\n\"\"\"\ndf.head()\ndf.info()\n#Missing Values \ndf.isnull().sum()\ndf[df['Postal Code'].isnull()]['City'].unique()\n\"\"\"\nAll observations with missing Postal Code are from the city of Burlington, we can either fill it or drop all the column since it wont be used in this analysis.\n\"\"\"\n#Ok, lets fill it :D\ndf['Postal Code'] = df['Postal Code'].fillna(5401)\n#Quick convert of Order Date and Shipe Date into Date form \ndf['Order Date'] = pd.to_datetime(df['Order Date'])\ndf['Ship Date'] = pd.to_datetime(df['Ship Date'])\n\n#Add Order Year column\ndf['Order Year'] = df['Order Date'].apply(lambda x:x.year)\n#Add Order month column\ndf['Order Month'] = df['Order Date'].apply(lambda x:datetime.datetime(x.year,x.month,1))\n\n#Add a column containing : The number of week\/Year ([1,52]\/Year) in which the order was made \ndf['Order Week'] = df['Order Date'].apply(lambda x:f'{x.year}\/{x.isocalendar()[1]}')\n\n#Add a column containing : The number of the day [1,7] the order was made\ndf['Order Day number'] = df['Order Date'].apply(lambda x:x.isocalendar()[2])\n\n#Sort Data by Order date\ndf.sort_values(['Order Date'],inplace=True)\n#Unique values (This steps gives little insights about what sub-series we might consider)\nfor c in df.columns :\n    print(f\"Number of {c} unique values : {df[c].nunique()}\")\n\n\"\"\"\n==> We can analyze total sales or sales per category\/subcategories or Shipe mode utilization... \n\"\"\"\n\"\"\"\n# Data Visualization\n\"\"\"\n\"\"\"\n### Ship Mode and Lead Time\n\"\"\"\nspecs = [[{'type':'domain'}, {'type':'domain'}], [{'type':'domain'}, {'type':'domain'}]]\nfig = make_subplots(rows=2,cols=2,specs=specs)\nfig.add_trace(go.Pie(labels=['Standard Class','Second Class', 'First Class' , 'Same Day'],\n                     values=df[df['Order Year']==2015]['Ship Mode'].value_counts(),title='2015'),1,1)\nfig.add_trace(go.Pie(labels=['Standard Class','Second Class', 'First Class' , 'Same Day'],\n                     values=df[df['Order Year']==2016]['Ship Mode'].value_counts(),title='2016'),1,2)\nfig.add_trace(go.Pie(labels=['Standard Class','Second Class', 'First Class' , 'Same Day'],\n                     values=df[df['Order Year']==2017]['Ship Mode'].value_counts(),title='2017'),2,1)\nfig.add_trace(go.Pie(labels=['Standard Class','Second Class', 'First Class' , 'Same Day'],\n                     values=df[df['Order Year']==2018]['Ship Mode'].value_counts(),title='2018'),2,2)\n\nfig.update_layout(title_text='Shipe mode rate per year',title_x=0.5)\n#Lead Time distribution per Segment :\ndf['Lead_Time']=(df['Ship Date']-df['Order Date']).apply(lambda x:x.days)\nfig = px.histogram(df[df['Lead_Time']>0], x=\"Lead_Time\", color=\"Segment\",labels={'Lead_Time':'Lead Time in days'})\nfig.show()\n\"\"\"\nThere is some anomalies in ship dates, some of them are anterior to the order date. Only those yielding a positive lead time are plotted. Results are confusing, Shipe Date column is not credible...\n\"\"\"\n\"\"\"\n### Sales mapping (Choropleth)\n\"\"\"\n#A Dictionary containing State codes, these codes will be used for the next plot\ncodes = {'Alabama': 'AL','Alaska': 'AK','Arizona': 'AZ','Arkansas': 'AR','California': 'CA','Colorado': 'CO','Connecticut': 'CT','Delaware': 'DE','District of Columbia':'DC','Florida': 'FL','Georgia': 'GA','Hawaii': 'HI','Idaho': 'ID','Illinois': 'IL','Indiana': 'IN','Iowa': 'IA','Kansas': 'KS','Kentucky': 'KY','Louisiana': 'LA','Maine': 'ME','Maryland': 'MD','Massachusetts': 'MA','Michigan': 'MI','Minnesota': 'MN','Mississippi': 'MS','Missouri': 'MO','Montana': 'MT','Nebraska': 'NE','Nevada': 'NV','New Hampshire': 'NH','New Jersey': 'NJ','New Mexico': 'NM','New York': 'NY','North Carolina': 'NC','North Dakota': 'ND','Ohio': 'OH','Oklahoma': 'OK','Oregon': 'OR','Pennsylvania': 'PA','Rhode Island': 'RI','South Carolina': 'SC','South Dakota': 'SD','Tennessee': 'TN','Texas': 'TX','Utah': 'UT','Vermont': 'VT','Virginia': 'VA','Washington': 'WA','West Virginia': 'WV','Wisconsin': 'WI','Wyoming': 'WY'}\n#Create a widget to vary year [2015,2018], in order to visualize each year plot (It's not working on kaggle)\nc=2015\nint_range = widgets.IntSlider(min=2015,max=2018,description=\"Plot's Year\")\ndisplay(int_range)\n\ndef on_value_change(change):\n    global c \n    c=change['new']\n    clear_output(wait=True)\n    display(int_range)\n    sales_percity = pd.DataFrame(df[df['Order Year']==c].groupby('State')['Sales'].sum())\n    sales_percity.reset_index(inplace=True)\n    sales_percity['state_code'] = sales_percity['State'].apply(lambda x:codes[x])\n\n    data = dict(type = 'choropleth',\n            locations = sales_percity['state_code'],\n            locationmode = 'USA-states',\n            colorscale= 'Portland',\n            text= sales_percity['State'],\n            z=sales_percity['Sales'],\n            colorbar = {'title':'Colorbar Title'})\n    layout = dict(geo = {'scope':'usa'},title=f'Sales per State in {c}',title_x=0.5)\n    choromap = go.Figure(data = [data],layout = layout)\n    iplot(choromap)\n\nint_range.observe(on_value_change, names='value')\non_value_change({'new':2015})\n\"\"\"\n    1\/ Through all years states of California and New York have the greatest total sales value\n    2\/ Texas has a medium total sales value compared to California and New York\n    3\/ In the last year Washington total sales value increased considerably.\n\"\"\"\n\"\"\"\n### Sales per Year per Category\n\"\"\"\nsales_percategory = pd.DataFrame(df.groupby(['Category','Order Year'],sort=False)['Sales'].sum()).sort_values('Order Year')\nsales_percategory.sort_values(['Category','Order Year'],inplace=True)\nsales_percategory.reset_index(inplace=True)\nfig = px.bar(sales_percategory,x='Order Year',y='Sales',title='Sales per Year per Category',\n             color='Category',labels={'Order Year':'Year','Sales':'Sales (c)'},barmode='group')\nfig.update_layout(xaxis_tickformat = 'd',autosize=False,width=1100,height=600,title_x=0.5)\n\nfig.show()\n\"\"\"\n==> All categories sales exhibit an increasing trend, except in 2016 where Technology and Office Supplies sales diminished.\nThis is better remarked through the next growth rate graph.\n\"\"\"\nsales_percategory['Sales n-1']=sales_percategory['Sales'].shift()\nsales_percategory['Growth Rate'] = round(((sales_percategory['Sales']-sales_percategory['Sales n-1'])\/sales_percategory['Sales n-1']),4)\nfig2 = px.bar(sales_percategory[sales_percategory['Order Year']!=2015],x='Order Year',y='Growth Rate',\n              title='Sales Growth Rate per Year per Category',\n             color='Category',labels={'Order Year':'Year','Growth Rate':'GR'},text='Growth Rate',barmode='group')\nfig2.update_traces( texttemplate='%{text:.2%s}', textposition='outside')\nfig2.update_layout(uniformtext_minsize=8, uniformtext_mode='hide',title_x=0.5)\nfig2.show()\n\"\"\"\n### Monthly sales per Category\n\"\"\"\n#Group sales per week and per categories\nsales_category_month = pd.DataFrame(df.groupby(['Category','Order Month'],sort=False)['Sales'].sum())\nsales_category_month.reset_index(inplace=True)\nsales_category_month.sort_values(['Category','Order Month'],inplace=True)\nfig = px.line(sales_category_month,x='Order Month',y='Sales',color='Category',\n             hover_data={\"Order Month\": \"|%B  %Y\"})\nfig.update_layout(autosize=False,width=1000,height=600,title_x=0.5,title_text='Monthly sales per Category')\nfig.update_xaxes(\n    dtick=\"M1\",\n    tickformat=\"%b \\n\\n\\n\\n\\n\\n\\n %Y\",ticklabelmode=\"period\")\nfig.show()\n\"\"\"\n### Weekly sales per category\n\"\"\"\nsales_category_week = pd.DataFrame(df.groupby(['Category','Order Week'],sort=False)['Sales'].sum())\nsales_category_week.reset_index(inplace=True)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=sales_category_week[sales_category_week['Category']=='Office Supplies']['Order Week'],\n                         y=sales_category_week[sales_category_week['Category']=='Furniture']['Sales'],name='Furniture'))\nfig.add_trace(go.Scatter(x=sales_category_week[sales_category_week['Category']=='Office Supplies']['Order Week'],\n                         y=sales_category_week[sales_category_week['Category']=='Office Supplies']['Sales'],name='Office Supplies'))\nfig.add_trace(go.Scatter(x=sales_category_week[sales_category_week['Category']=='Office Supplies']['Order Week'],\n                         y=sales_category_week[sales_category_week['Category']=='Technology']['Sales'],name='Technology'))\nfig.update_layout(autosize=False,width=1200,height=600,title_x=0.5,title_text='Weekly sales per Category',\n                 xaxis_title='Date (Week number\/Year)',yaxis_title='Profit value')\n\"\"\"\n# Furniture monthly sales analysis\n\"\"\"\n\"\"\"\n### Preprocessing\n\"\"\"\nfrom statsmodels.tsa.ar_model import AutoReg\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom dateutil.parser import parse\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom sklearn.metrics import mean_squared_error,mean_absolute_error\n#Creating a data frame containing Monthly sales of furniture\nX_frame = sales_category_month[sales_category_month['Category']=='Furniture'][['Order Month', 'Sales']]\nX_frame.set_index('Order Month',inplace=True)\n#Add a column containing first difference of sales (sales(t)-sales(t-1))\nX_frame['Sales diff 1'] = X_frame['Sales'].diff()\n#Add a column containing logarithmic transformation of sales also its first and second order difference\nX_frame['log Sales'] = np.log(X_frame['Sales'])\nX_frame ['log Sales diff 1'] = X_frame['log Sales'].diff()\nX_frame['log Sales diff 2'] = X_frame ['log Sales diff 1'].diff()\n#Set series to be equal to 2nd order difference of logarithmic transformation\n#At first trial using Raw sales yields a curved trend, after transforming it using logarithmic function the serie becomes non stationary. \n#Differencing it bring it back to stationarity and attenuate the trend effect. \n#Set a training set containing years 2015\/2016\/2017 observations and test set containing year 2018 observations.\nX = np.array(X_frame['log Sales diff 2'].dropna() )\nX_train = X[:-12]\nX_test = X[-12:]\n#Plotting X_train\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,167)),y=X_train,name='True values'))\nfig.update_layout(title_text='Time serie plot',title_x=0.5)\n\"\"\"\n## Stationarity test :\n\"\"\"\nfrom statsmodels.tsa.stattools import adfuller\nadf_resutls = adfuller(X_train,maxlag=10)\nprint(f'ADF test results are :')\nprint('ADF Statistic: %f' % adf_resutls[0])\nprint('p-value: %f' % adf_resutls[1])\nprint('Critical Values:')\nfor key, value in adf_resutls[4].items():\n    print('\\t%s: %.3f' % (key, value))\nif adf_resutls[0]<=-2.9 :\n    print('==> Non-stationarity can be rejected')\nelse :\n    print('==> Non-stationarity cannot be rejected')\n\"\"\"\n## Autocorrelation and partial autocorrelation graphs :\n\"\"\"\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfig,axes = plt.subplots(nrows=1,ncols=2,figsize=(15,6))\nplot_pacf(X_train,lags=14,ax=axes[0])\nplot_acf(X_train,lags=14,ax=axes[1])\nplt.show()\n\"\"\"\nAccording to the Partial Autocorrelation plot, Arima((2,2,1)*(0,0,0,0)) is a good candidate. Because second spike in Partial Autocorrelation graph is close to the significance treshhold let's remove this order from the model. The model becomes Arima((1,2,1)*(0,0,0,0))\n\"\"\"\n\"\"\"\n### Additive decomposition\n\"\"\"\n#The value of period is justified by the monthly sales per category plots which suspects a saisonality of 12 months for Furniture category and this value has a relative good effect on the trend composant\nadditive_decomposition = seasonal_decompose(X_train,period=12,model='additive')\nplt.rcParams.update({'figure.figsize': (16,12)})\nadditive_decomposition.plot().suptitle('Additive Decomposition', fontsize=16)\nplt.tight_layout()\n\"\"\"\n## ARIMA Model\n\"\"\"\nimport statsmodels.api as sm\n#Reset time serie to be the logarithmic transformation of Sales, differentiation is done automatically in SARIMAX function. \nX = np.array(X_frame['log Sales'].dropna() )\nX_train = X[:-12]\nX_test = X[-12:]\n#The saisonality term is added after comparison of bic metric and due to the last remark on the decomposition graph\norder= (1,2,1)\nseasonal_order = (1,0,0,12)\ntrend='c'\nmodel1_fit = sm.tsa.statespace.SARIMAX(X_train,order=order,seasonal_order=seasonal_order,trend=trend,enforce_invertibility=False,\n                                      enforce_stationarity=False).fit()\nfitted_values= model1_fit.fittedvalues\n#Plot true and predicted sales for the training set\nRMSE = np.sqrt(mean_squared_error(X_train[12:],fitted_values[12:]))\nMAE = mean_absolute_error(X_train[12:],fitted_values[12:])\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,167)),y=X_train,name='True values'))\nfig.add_trace(go.Scatter(x=np.array(range(12,167)),y=fitted_values[12:],name='Predicted Values'))\nfig.update_layout(title_text='Time serie plot',title_x=0.5)\n#Monthly prediction: This function gives month by month predictions. \n#If next 2 months sales are to be predicted, the function predicts the value for the first month and add it's true value to the training set then predicts for 2nd month\ndef month_prediction(X,Xtest_len=12,order=(0,0,0),seasonal_order=(2,0,1,12),trend='c'):\n    predictions1 =[]\n    for j in range(Xtest_len):\n        X_train = X[0:len(X)-Xtest_len+j]\n        model1 =  sm.tsa.statespace.SARIMAX(X_train,order=order,seasonal_order=seasonal_order,\n                            enforce_invertibility=False,enforce_stationarity=False,trend=trend)\n      \n            \n        model1_fit = model1.fit()\n        prediction_step = model1_fit.predict(start=len(X_train),end=len(X_train))\n        predictions1.append(prediction_step)\n    predictions1 = np.reshape(predictions1,((Xtest_len),))\n    RMSE = np.sqrt(mean_squared_error(X[len(X)-Xtest_len:],predictions1))\n    MAE = mean_absolute_error(X[len(X)-Xtest_len:],predictions1)\n    \n    return predictions1 , RMSE , MAE\n#Test set predictions\npredictions1,RMSE,MAE = month_prediction(X,Xtest_len=12,order=order,seasonal_order=seasonal_order,trend=trend)\n#Plot Test results\nRMSE = np.sqrt(mean_squared_error(X_test,predictions1))\nMAE = mean_absolute_error(X_test,predictions1)\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,12)),y=X[-12:],name='True Values'))\nfig.add_trace(go.Scatter(x=np.array(range(0,12)),y=np.array(predictions1),name='Predicted Values'))\n\"\"\"\nThese results contain predictions of logarithmic transformation of sales. For next, predicted and true sales are plotted\n\"\"\"\ntransformed_predictions = np.exp(np.array(predictions1))\ntransformed_Xtest = np.exp(np.array(X_test))\nRMSE = np.sqrt(mean_squared_error(transformed_Xtest,transformed_predictions))\nMAE = mean_absolute_error(transformed_Xtest,transformed_predictions)\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,12)),y=transformed_Xtest,name='True Values'))\nfig.add_trace(go.Scatter(x=np.array(range(0,12)),y=transformed_predictions,name='Predicted Values'))\n\"\"\"\n# Total weekly sales\n\"\"\"\n\"\"\"\n### Preprocessing\n\"\"\"\n#Same transformations as the previous analysis\nX_frame = pd.DataFrame(df.groupby(['Order Week'],sort=False)['Sales'].sum())\nX_frame['Sales diff 1'] = X_frame['Sales'].diff()\nX_frame['log Sales'] = np.log(X_frame['Sales'])\nX_frame ['log Sales diff 1'] = X_frame['log Sales'].diff()\nX_frame['log Sales diff 2'] = X_frame['log Sales diff 1'].diff()\n#Same split as the previous analysis 2015\/2016\/2017 for training and 2018 for test\nX = np.array(X_frame['log Sales diff 2'].dropna() )\nX_train = X[:-52]\nX_test = X[-52:]\n#Plot time series\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,208)),y=X_train,name='True values'))\nfig.update_layout(title_text='Time series plot',title_x=0.5)\n\"\"\"\n### Stationarity test\n\"\"\"\nadf_resutls = adfuller(X_train,maxlag=10)\nprint(f'ADF test results are :')\nprint('ADF Statistic: %f' % adf_resutls[0])\nprint('p-value: %f' % adf_resutls[1])\nprint('Critical Values:')\nfor key, value in adf_resutls[4].items():\n    print('\\t%s: %.3f' % (key, value))\nif adf_resutls[0]<=-2.9 :\n    print('==> Non-stationarity can be rejected')\nelse :\n    print('==> Non-stationarity cannot be rejected')\n\"\"\"\n### PACF and ACF\n\"\"\"\nfig,axes = plt.subplots(nrows=1,ncols=2,figsize=(15,6))\nplot_pacf(X_train,lags=52,ax=axes[0])\nplot_acf(X_train,lags=52,ax=axes[1])\n\nplt.show()\n\"\"\"\n### Additive decomposition\n\"\"\"\n#Decomposition :\nadditive_decomposition = seasonal_decompose(X_train,period=52,model='additive')\nplt.rcParams.update({'figure.figsize': (16,12)})\nadditive_decomposition.plot().suptitle('Additive Decomposition', fontsize=16)\nplt.tight_layout()\n\"\"\"\n    1\/ When using Raw Sales Data, we get a curved trend, in order to attenuate it, a logarithmic transformation had been applied but the serie became non statitionary.\n    2\/ the first order difference brought the series back to stationarity.\n\n\"\"\"\n\"\"\"\n## ARIMA Model \n\"\"\"\nX = np.array(X_frame['log Sales'].dropna() )\nX_train = X[:-52]\nX_test = X[-52:]\n#Set lag orders\norder = ([1,2,3,4,18,32],2,1)\nseasonal_order=(1,0,0,12)\ntrend='c'\n#Fit the model \nmodel2_fit = sm.tsa.statespace.SARIMAX(X_train,order=order,seasonal_order=seasonal_order,trend=trend,enforce_invertibility=False,\n                                      enforce_stationarity=False).fit()\nfitted_values2= model2_fit.fittedvalues\n#Plot true and predicted sales for the training set\nRMSE = np.sqrt(mean_squared_error(X_train[52:],fitted_values2[52:]))\nMAE = mean_absolute_error(X_train[52:],fitted_values2[52:])\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,167)),y=X_train,name='True values'))\nfig.add_trace(go.Scatter(x=np.array(range(52,167)),y=fitted_values2[52:],name='Predicted Values'))\nfig.update_layout(title_text='Time serie plot',title_x=0.5)\n#Weekly prediction : This function plays the same role as monthly prediction function but on a window of a week\ndef week_prediction(X,Xtest_len=12,order=(0,0,0),seasonal_order=(2,0,1,12),trend='c'):\n    predictions1 =[]\n    for j in range(Xtest_len):\n        X_train = X[0:len(X)-Xtest_len+j]\n        \n        model1 =  sm.tsa.statespace.SARIMAX(X_train,order=order,seasonal_order=seasonal_order,\n                            enforce_invertibility=False,enforce_stationarity=False,trend=trend)\n      \n            \n        model1_fit = model1.fit()\n        prediction_step = model1_fit.predict(start=len(X_train),end=len(X_train))\n        predictions1.append(prediction_step)\n    predictions1 = np.reshape(predictions1,((Xtest_len),))\n    RMSE = np.sqrt(mean_squared_error(X[len(X)-Xtest_len:],predictions1))\n    MAE = mean_absolute_error(X[len(X)-Xtest_len:],predictions1)\n    \n    return predictions1 , RMSE , MAE\npredictions2,RMSE,MAE = month_prediction(X,Xtest_len=52,order=order,seasonal_order=seasonal_order,trend=trend)\n#Plot test results\nRMSE = np.sqrt(mean_squared_error(X_test,predictions2))\nMAE = mean_absolute_error(X_test,predictions2)\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,52)),y=X_test,name='True Values'))\nfig.add_trace(go.Scatter(x=np.array(range(0,52)),y=np.array(predictions2),name='Predicted Values'))\n#Transform back and plot real values\ntransformed_predictions = np.exp(np.array(predictions2))\ntransformed_Xtest = np.exp(np.array(X_test))\nRMSE = np.sqrt(mean_squared_error(transformed_Xtest,transformed_predictions))\nMAE = mean_absolute_error(transformed_Xtest,transformed_predictions)\nprint(f'Train Root Mean Squared Error = {RMSE}')\nprint(f'Test Mean Absolute Error = {MAE}')\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=np.array(range(0,52)),y=transformed_Xtest,name='True Values'))\nfig.add_trace(go.Scatter(x=np.array(range(0,52)),y=transformed_predictions,name='Predicted Values'))\n\"\"\"\n### Predicting next week sales :\n\"\"\"\n#Train the model on all data\nmodel2_fit = sm.tsa.statespace.SARIMAX(X,order=order,seasonal_order=seasonal_order,trend=trend,enforce_invertibility=False,\n                                      enforce_stationarity=False).fit()\nfitted_values = model2_fit.fittedvalues\n#Predict next week sale value\nnext_week_prediction = model2_fit.predict(start=len(X),end=len(X))\nprint(f'Next week sales value prediction is equal to : {round(np.exp(next_week_prediction[0]),2)} (cur)')\n#Plot results\nfig = go.Figure()\ntransformed_fitted = np.exp(fitted_values)\nfig.add_trace(go.Scatter(x=np.array(range(200,212)),y=X_frame['Sales'].iloc[200:],name='True Values'))\nfig.add_trace(go.Scatter(x=np.array(range(200,212)),y=transformed_fitted[200:],name='Predicted Values'))\nfig.add_trace(go.Scatter(x=np.array(range(209,211)),y=np.array([transformed_fitted[-1],np.exp(next_week_prediction[0])]),\n                         line = dict(color='red', width=4, dash='dash'),\n                         name='Next week prediction'))\n\n\"\"\"\n### Monthly sales time series plot shows that each catogory has a different behavior, in next parts we will predict future weekly sales per category...\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a6233eab187dcb'}"}
{"id":"122315","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# Input data files are available in the \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\nimport seaborn as sns\nfrom sklearn import linear_model\n\"\"\"\n #   Selection of data in KDD process\n\"\"\"\npath_to_file=\"..\/input\/googleplaystore.csv\"\ndata=pd.read_csv(path_to_file,encoding='utf-8')\n\"\"\"\n# Preprossesing  data in KDD PROCESS\n\"\"\"\n\"\"\"\nIn observing the dataset we realied that some of the apps listed were not even released as yet.\nWe also spotted the pattern that these apps all contained some NULL values and would not be important \nfor our analysis so we decided to get rid of them.\n\"\"\"\n##checking for all null values in dataset\nmissing_data_results =data.isnull().sum()\nprint(missing_data_results)\n\n\"\"\"\nComplete case analysis, Complete case analysis followed by nearest-neighbor assignment for partial data, Partial data cluster analysis, Replacing missing values or incomplete data with means Imputation are all ways to deals with missing data. However we decided to delete all rows where  column values is null\n\"\"\"\n#loops through dataset and delete rows where column values is null\ndata =data.dropna()\ndata.isnull().sum()\n\"\"\"\nObserving the install columns we realized that it contains string characters and as such we remove those charaters in order to work with integer values.\n                   BEFORE:                                    \n![image.png](attachment:image.png)\n\n\"\"\"\n#Below we are using the regex \\D to remove any non-digit characters\ndata['Installs']=data['Installs'].replace(regex=True,inplace=False,to_replace=r'\\D',value=r'')\n#data['Installs']=data['Installs'].replace(regex=True,inplace=True,to_replace=r'\\D',value=r'')\n#data.Installs\n\n\"\"\"\nAFTER:\n![image.png](attachment:image.png)\n\"\"\"\ndata['Installs']\nnp.sort(data.Installs)\n#for col in data.columns:\n  #  data[col]=np.sort(data[col].values)\n\"\"\"\n        **Check for duplicate records**\n\"\"\"\ndata.shape\ndupes=data.duplicated()\nsum(dupes)\n\ndata=data.drop_duplicates()\ndata.shape\n\"\"\"\nChecking to see if we are working with ligit data types\n\"\"\"\ndata.dtypes\n    \ndata['Price']=data['Price'].replace(regex=True,inplace=False,to_replace=r'\\D',value=r'')\n#converting installs and Price to appropriate data types\ndata[\"Installs\"] = pd.to_numeric(data[\"Installs\"])\ndata[\"Reviews\"] = pd.to_numeric(data[\"Reviews\"])\ndata[\"Price\"] = pd.Float64Index(data[\"Price\"])\ndata.dtypes\n\"\"\"\n**VISUALIZATIONS**\n\"\"\"\n\"\"\"\n1. Number of Apps available basedon content ratings\n\"\"\"\ndata.columns =data.columns.str.replace(' ', '_')\n#Apps available based on Content rating\nplt.figure(figsize=(10,10))\nsns.countplot(x='Content_Rating',data=data,)\nplt.xticks(rotation=45)\nplt.title(\"Number of Apps available based on Content rating\")\n\n\"\"\"\n2. Plot to show the distribution of apps from each category in the data set. \n\"\"\"\n\n#data['Category'].value_counts()\nplt.figure(figsize=(12,12))\ndata['Category'].value_counts().plot(kind='bar',title='Distribution of Categories')\nplt.xlabel('Categories')\nplt.ylabel('Number of Apps')\n\n\n\"\"\"\n        *Most installed apps based on Category*\n\"\"\"\n\nplt.figure(figsize=(12,12))\nsns.barplot(x='Installs',y='Category',data=data,ci=None)\nplt.title(\"Number of Apps installed based on Category\")\n\n\"\"\"\n3. In the series of steps to determine what appp to develop we would like to identify whether there are more downloads for \"Paid\" or \"Free\" apps\n\"\"\"\ndata['Type'].value_counts().plot(kind='bar',title='Distribution App Types')\nplt.xlabel('Type of Apps')\nplt.ylabel('Count')\n\"\"\"\nApplication of knowledge from dataset.....\nSelect all apps where there downloads are between 10000 and 10000000\n________________________________________________________________________________\n\"\"\"\n\nfind=((data.Installs.values >=10000)& (data.Installs.values <=10000000))\ndata1 = data[find]\ndata1\n#Viewing install column after dividing dataset\ndata1.hist(column= 'Installs')\nlen(data1.Installs.values)\n\"\"\"\n# Transformation step in KDD process\n\"\"\"\ndata1.Reviews\n#qcut tries to divide up the underlying data into equal sized bins.\ndata1.Reviews=pd.qcut(data1.Reviews,20)\ntree_data = data1[['Installs','Category','Type','Reviews']]\ntree_data\ndata1.Installs.value_counts()\ntree_data['Installs'] = pd.cut(tree_data['Installs'], [9999\n,50000\n,100000\n,500000\n,1000000\n,5000000\n,10000000\n                                              ])\ntree_data.Installs.value_counts()\ntree_data.Installs.value_counts()\n# Encoder function.....transforming\ndef encoder(dataset):\n    from sklearn.preprocessing import LabelEncoder\n    #dictionary to store values\n    encoder = {}\n    for column in dataset.columns:\n        # Only creating encoder for categorical data types\n      #  if not np.issubdtype(dataset[column].dtype, np.number) and column != 'Installs':\n            encoder[column]= LabelEncoder().fit(dataset[column])\n            #returning the dictionary with values\n    return encoder\ntree_data\n#transforming tree data\nencoded_labels = encoder(tree_data)\nprint(\"Encoded Values for each Label\")\nprint(\"=\"*32)\nfor column in encoded_labels:\n    print(\"=\"*32)\n    print('Encoder(%s) = %s' % (column, encoded_labels[column].classes_ ))\n    print(pd.DataFrame([range(0,len(encoded_labels[column].classes_))], columns=encoded_labels[column].classes_, index=['Encoded Values']  ).T)\ndata1.Installs.value_counts()\ntransformed_data= tree_data.copy()\nfor col in transformed_data.columns:\n    if col in encoded_labels:\n       transformed_data[col] = encoded_labels[col].transform(transformed_data[col])\nprint(\"Transformed data set with category and type encoded\")\nprint(\"=\"*32)\ntransformed_data\n\"\"\"\n# Data Mining  in KDD process\n\"\"\"\n\"\"\"\n*************************************Multinomial LogisticRegression************************\n# Aim: Does the numbr of Installs for an app incrof installs go up with increase in reviews?\nType of algorithm ?\n    -supervised machine learning algorithm\nType ofsupervised machine learning?\n    - Classification since dependent variable is categorical and dealing with current behavior\n        \n    \n\"\"\"\nfrom sklearn.model_selection import train_test_split\n#Seperate our data into independent X and dependent Y \nX_data = transformed_data[['Category','Type']]\nY_data= transformed_data['Installs']\nX_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, test_size=0.30)\nfrom sklearn import linear_model\nfrom sklearn.naive_bayes import GaussianNB\n# creating multinomial model since we have more than one predictor then fit training data.\nregr = linear_model.LogisticRegression(solver='newton-cg')\n#regr = linear_model.LogisticRegression(multi_class='multinomial', solver='newton-cg').fit(pd.DataFrame(X_train),Y_train)\n#regr = GaussianNB()\nregr.fit(pd.DataFrame(X_train),Y_train)\n#given a trained model, we are predicting the label of a new set of X test data.\nPrediction = regr.predict(pd.DataFrame(X_test))\ntransformed_data['Installs'].value_counts()\nprint(Prediction)\n# The coefficient of our determinant(x)\nprint('Coefficients: \\n', regr.coef_)\nregr.intercept_\nfrom sklearn.metrics import r2_score\n# Use score method to get accuracy of model\nprint('Variance score:%2f'% r2_score(Y_test,Prediction)) \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import metrics\ncm = metrics.confusion_matrix(Y_test,Prediction)\nprint(cm)\ncm.shape\nplt.figure(figsize=(5,5))\nplt.imshow(cm, interpolation='nearest', cmap='Pastel1')\nplt.title('Confusion matrix', size = 15)\nplt.colorbar()\nplt.xticks(Prediction)\nplt.yticks(Y_test)\nplt.tight_layout()\nplt.ylabel('Actual label')\nplt.xlabel('Predicted label')\nwidth,height = cm.shape\nfor x in range(width):\n for y in range(height):\n  plt.annotate(str(cm[x][y]), xy=(y, x), \n  horizontalalignment='center',\n  verticalalignment='center')\n\"\"\"\n### check correlation between Category and Installs variables\nnp.corrcoef(transformed_data.Category,transformed_data.Installs)\n\n\"\"\"\ndata1\nplt.scatter(transformed_data.Category,transformed_data.Installs)\nplt.show()\nnp.corrcoef(transformed_data.Type,transformed_data.Installs)\n\nplt.scatter(transformed_data.Type,transformed_data.Installs)\nplt.show()\nnp.corrcoef(transformed_data.Type,transformed_data.Installs)\n\"\"\"\n# Interpretation\/ Evaluation of our Regression Model\n\"\"\"\n\"\"\"\n**Regression Explanation**\nThe score above indicates that our model is extreamly bad!! We considered many solutions such as using different models and allocating  a larger training sample, none of which worked. We then observed the relationship between our two independent variables and dependent variable. There are of no relation and as such contributing to our bad model. So in conclusion, we went wrong in selecting our independent variables!! :(\n\"\"\"\n\"\"\"\n# We attempted to use decision tree to give a better visual of the question above but had some problem......*not one of our algorithm!* \n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\n\nfrom sklearn import tree\n# Create the classifier with a maximum depth of 2 using entropy as the criterion for choosing most significant nodes\n# to build the tree\nclf = DecisionTreeClassifier(criterion='entropy',min_samples_split=2)\n# Hint : Change the max_depth to 10 or another number to see how this affects the tree\nclf.fit(X_train, Y_train)\npd.DataFrame([ \"%.2f%%\" % perc for perc in (clf.feature_importances_ * 100)\n], index = X_data.columns, columns = ['Feature Significance in Decision Tree'])\nimport graphviz\nY_data\ndot_data = tree.export_graphviz(clf,out_file=None,\n\nfeature_names=X_data.columns,\nclass_names= None,\nfilled=True, rounded=True, proportion=True,\nnode_ids=True, #impurity=False,\nspecial_characters=True)\ngraph = graphviz.Source(dot_data)\n\ngraph\ntree.export_graphviz(clf,out_file='tree.dot') \ncorrmat = transformed_data.corr()\n#f, ax = plt.subplots()\np =sns.heatmap(corrmat, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))\ntransformed_data['Reviews'].corr(transformed_data['Installs'])\n\"\"\"\n# **********************Linear Regression************************\nType of algorithm ?\n    -supervised machine learning algorithm\nType ofsupervised machine learning?\n    - Classification since dependent variable is categorical and dealing with current behavior\n        \n\"\"\"\n\"\"\"\n# Aim: Does the amount of installs go up with increase in reviews?\n\"\"\"\nX_data1 = transformed_data['Reviews']\nY_data1 = transformed_data['Installs']\nfrom sklearn.model_selection import train_test_split\n\nX_train1, X_test1, y_train1, y_test1 = train_test_split(X_data1, Y_data1, test_size=0.30)\nreg1 = linear_model.LinearRegression()\nreg1.fit(pd.DataFrame(X_train1),y_train1)\nPrediction1 = reg1.predict(pd.DataFrame(X_test1))\ny_test1.index\nPrediction1[:12]\nreg1.coef_\nreg1.intercept_\nreg1.score(pd.DataFrame(X_test1),y_test1)\nplt.scatter(X_test1,y_test1,  color='black')\nplt.plot(X_test1,Prediction1,color='blue', linewidth=3)\n\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\nimport seaborn as sns\nsns.set(style=\"whitegrid\")\n# Plot the residuals after fitting a linear model\nsns.residplot(X_train1, y_train1, lowess=True, color=\"b\")\ninstall = 0.2*4 -0.354\ninstall\n\"\"\"\n# Output of linear regression\n**install = 0.2review -0.354**\n\"\"\"\n\"\"\"\n# Interpretation\/ Evaluation of Linear model\nThe linear regression module was considered better than the multinomial regression as the coefficient of determination had a higher value. The R^2 value for this module was 0.85 which means that Installs have an 85 percent chance of being predicted from Reviews.\n\n\"\"\"\n\"\"\"\n# K-MEANS\n\"\"\"\n\"\"\"\n  **CLUSTERING******\n  Aim: Can we identify groups based on Review and Installs?\nIf that is the case, developers could develop Apps of a certain category based on the reviews\n\"\"\"\n\"\"\"\n*************************************k-Nearest Neighbors Method************************\nType of algorithm ?\n    -supervised machine learning algorithm\nType ofsupervised machine learning?\n    - Classification since dependent variable is categorical and dealing with current behavior\n\"\"\"\ncluster_data = transformed_data[['Reviews','Installs']]\ncluster_data.head(50)\ncluster_data.plot(kind='scatter',x='Reviews',y='Installs')\n# Is there any missing data\nmissing_data_results = cluster_data.isnull().sum()\nprint(missing_data_results)\ndata_values = cluster_data.iloc[ :, :].values\ndata_values\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.cluster import KMeans\nmms = MinMaxScaler()\nmms.fit(data_values)\ndata_transformed = mms.transform(data_values)\nSum_of_squared_distances = []\nK = range(1,15)\nfor i in K:\n    km = KMeans(n_clusters=i)\n    km = km.fit(data_transformed)\n    Sum_of_squared_distances.append(km.inertia_)\nplt.plot(K, Sum_of_squared_distances, 'bx-')\nplt.xlabel('k')\nplt.ylabel('WCSS')\nplt.title('Computing WCSS for KMeans++')\nplt.xlabel(\"Number of clusters\")\nplt.show()\nkmeans = KMeans(n_clusters=3, init=\"k-means++\", n_init=10, max_iter=300)\ncluster_data[\"cluster\"] = kmeans.fit_predict( data_values )\ncluster_data\n#viewing amount of elements in clusters\ncluster_data['cluster'].value_counts()\n\nimport seaborn as sns\nsns.set(color_codes=True)\n\ncluster_data['cluster'].value_counts().plot(kind='bar',title='Distribution of Apps')\ngrouped_cluster_data = cluster_data.groupby('cluster')\ngrouped_cluster_data\ngrouped_cluster_data.plot(subplots=True)\nsns.pairplot(cluster_data,hue=\"cluster\")\n\"\"\"\n# Interpretation\/ Evaluation of K-Mean\n\"\"\"\n\"\"\"\nWith the clustering algorithm, we used the elbow method to deduce the number of groups we could possible obtain. After trying the various K values, we decided that K =3 give the most suitable results. With K= 3 we deduce that apps each group has at least 2000 apps which are group together based on their Installs and Reviews. The values for installs show the different bins in which apps bring for the 3 groups. It can be deduced that apps in group 0 are apps received more installs than review, while group 1 on shows that the apps in that group received.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'e0ee0e90cd299f'}"}
{"id":"58086","text":"\"\"\"\n# Simple Logit Regression to Predict Election Candidate Winners\n\nRegression performed against:\n* Number of competitors\n* Number of days campaigning\n* Fraction of total money available\/spent by the candidate\n\nhttps:\/\/www.kaggle.com\/danerbland\/electionfinance\n\"\"\"\n# 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 in \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 \"..\/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# Any results you write to the current directory are saved as output.\n\nfrom sklearn.model_selection import train_test_split\n\nimport seaborn as sns\n# sns.set()\nsns.set(rc={'figure.figsize':(11.7,8.27)})\n\"\"\"\n### Load data and clean\n\"\"\"\ndat = pd.read_csv('\/kaggle\/input\/electionfinance\/CandidateSummaryAction1.csv',\n                 parse_dates=['cov_sta_dat','cov_end_dat'])\n\n# Convert dollars to floats\ndef convdollars2float(dfcol):\n    val = dfcol.str.replace('$','').str.replace(',','').str.replace('(','-').str.replace(')','').astype('float32')\n    return val\n\nfor colname in ['cas_on_han_beg_of_per','cas_on_han_clo_of_per','net_con','net_ope_exp','deb_owe_by_com','deb_owe_to_com']:\n    dat[colname] = convdollars2float(dat[colname])\n\n# Convert winner column to boolean\ndat['winner'] = dat['winner'].apply(lambda val: float(int(val=='Y')))\n\ndat.head(10)\n\"\"\"\n### Derive data (add new columns)\n\"\"\"\n\n#\u00a0Add column: time length cov_end_dat - cov_sta_dat\ndat['cov_dat_len_days'] = (dat['cov_end_dat'] - dat['cov_sta_dat']).dt.days\n# Drop where this column has negative value\ndat = dat[ dat['cov_dat_len_days'] >= 0 ]\n\n# Add column: number of competitiors\n\n# First, construct lookup table of number of candidates running for each district\nnum_comp_lookup = dat.groupby(['can_off_sta','can_off_dis'])['can_id'].count().to_dict()\n\n#\u00a0Then perform lookup on this table to append number of competitors\ndef fcn(row):\n    key = (row.can_off_sta,row.can_off_dis)\n    if key in num_comp_lookup:\n        return num_comp_lookup[key]\n#     else:\n#        # Handling NaNs:\n#        num_competitors = 0\ndat['num_comp'] = dat.apply(lambda row: fcn(row), axis=1)\n\n# Drop rows where number of competitors couldn't be calculated (>0) and where uncontested (>1)\ndat = dat[ dat['num_comp'] > 1 ]\n\n# Add column: fraction of spend for this district\n\n# First, construct lookup table of total spend for this district\ntotal_net_con_for_district = dat.groupby(['can_off_sta','can_off_dis'])['net_con'].sum().to_dict()\n\n# Add column giving this total of net contributions\ndef fcn(row):\n    key = (row.can_off_sta,row.can_off_dis)\n    if key in num_comp_lookup:\n        return total_net_con_for_district[key]\n#     else:\n#        # Handling NaNs:\n#        num_competitors = 0\ndat['total_net_con_for_district'] = dat.apply(lambda row: fcn(row), axis=1)\n\n# Calculate the fraction\ndat['fraction_net_con_for_district'] = dat['net_con'] \/ dat['total_net_con_for_district']\n# # Add column: tot_comp per vote\n# dat['net_con_per_vote'] = dat['net_con']\/dat['votes']\ndat.head()\n# Winning probability is function of:\n# Number of competitors: num_comp\n# Number of days campaigning: cov_dat_len_days ???TBC TODO is this what this column refers to???\n# Fraction of total money available\/spent by the candidate: fraction_net_con_for_district ???TBC TODO is this what this column refers to???\n\n# COLS_TO_REGRESS = ['num_comp','cov_dat_len_days','fraction_net_con_for_district']\n# COLS_TO_REGRESS = ['fraction_net_con_for_district']\nCOLS_TO_REGRESS = ['num_comp','cov_dat_len_days']\n\n_ = dat[['winner']+COLS_TO_REGRESS].dropna()\n\ny = _['winner']\nX = _[COLS_TO_REGRESS]\n\nimport statsmodels.api as sm\nlogit_model=sm.Logit(y,X)\nresult=logit_model.fit()\nprint(result.summary2())\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\n# ROC Curve\n\nimport matplotlib.pyplot as plt \nplt.rc(\"font\", size=14)\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nlogit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))\nfpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])\n\nplt.figure()\nplt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.savefig('Log_ROC')\nplt.show()\n# Classification report\nfrom sklearn.metrics import classification_report\ny_pred = logreg.predict(X_test)\nprint(classification_report(y_test, y_pred))\n# Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix = confusion_matrix(y_test, y_pred)\nprint(confusion_matrix)\n\"\"\"\n### Full printout of results\n\"\"\"\n# Add column of predictions alongside each row\ndat_grp_preds = dat[['can_id']+COLS_TO_REGRESS].dropna(axis=0)\n\ndat_grp_preds['winner_prediction'] = logreg.predict( dat_grp_preds[COLS_TO_REGRESS] )\n\ndat_grp_preds = dat_grp_preds.set_index('can_id')\n\ndat_grp_preds.head()\n\n# Join main data with predictions data on can_id\n_ = dat.set_index('can_id')\n_ = _.join(dat_grp_preds['winner_prediction'])\n# Group the data by district\n# dat_grp = dat.groupby(['can_off_sta','can_off_dis','can_inc_cha_ope_sea']).sum()\n_grp = _.set_index(['can_off_sta','can_off_dis']).sort_values(by=['can_off_sta','can_off_dis'])\n_grp","meta":"{'source': 'AI4Code', 'id': '6b4c57a838deb2'}"}
{"id":"34209","text":"\"\"\"\nHi all,\nIf you haven't seen my previous Kernel please check it out [here.](http:\/\/https:\/\/www.kaggle.com\/tubaspandas\/logical-encoding-and-correlation-analysis) I will try to predict the value of a FIFA player by using Keras. Please share your feedback and ratings so that I can improve myself. I have explained how I cleaned this dataset in my previous Kernel. So I will go ahead with the prepared data. You could find the preprocessing below.\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\noriginal =  pd.read_csv('..\/input\/data.csv')\nfi=original\nfi=pd.DataFrame(fi)\nfi = fi.drop(columns='Unnamed: 0')\nfi = fi.drop(columns='ID')\nfi = fi.drop(columns='Photo')\nfi = fi.drop(columns='Flag')\nfi = fi.drop(columns='Club Logo')\nfi = fi.drop(columns='Joined')\n#Correct currencies\ncurs=[\"Release Clause\", \"Value\", \"Wage\"]\nfor cur in curs:\n    \n    def curr_value(x):\n        x = str(x).replace('\u20ac', '')\n        if('M' in str(x)):\n            x = str(x).replace('M', '')\n            x = float(x) * 1000000\n        elif('K' in str(x)):\n            x = str(x).replace('K', '')\n            x = float(x) * 1000\n        return float(x)\n    fi[cur] = fi[cur].apply(curr_value)\n   \n#Correct -Dismiss + values\ncols=[\"LS\", \"ST\", \"RS\", \"LW\", \"LF\", \"CF\", \"RF\", \"RW\",\"LAM\", \"CAM\", \"RAM\", \"LM\", \"LCM\", \"CM\", \"RCM\", \"RM\", \"LWB\", \"LDM\",\"CDM\", \"RDM\", \"RWB\", \"LB\", \"LCB\", \"CB\", \"RCB\", \"RB\"]\nfor col in cols:\n    fi[col]=fi[col].str[:-2]\n    fi[col]=fi[col].astype(float)\n    \n#Convert contract end\nfi['Contract Valid Until']=fi['Contract Valid Until'].str[-4:]\nfi['Contract Valid Until']=fi['Contract Valid Until'].astype(float)\n    \n#Corect height values \nfi['Height']=fi['Height'].str.replace(\"'\",'.')\nfi['Height']=fi['Height'].astype(float)\n\n#Correct Weight\nfi['Weight']=fi['Weight'].str[:-3]\nfi['Weight']=fi['Weight'].astype(float)\n\n#X and y assignments\n#fi=(fi[fi[\"Position\"]!=\"GK\"])\nX = fi.loc[:, fi.columns != 'Value']\ny=fi.loc[:,['Value']]\nX = X.drop(columns='Name')\nX = X.drop(columns='Real Face')\n#identify Object columns\nobj_df = X.select_dtypes(include=['object']).copy()\nobj_df.head()\n\n\"\"\"\nIn my previous Kernel, I have encoded the values with label encoding this time I will use get_dummies.\n\"\"\"\n#Encoding -1\nX_dum=pd.get_dummies(X[obj_df.columns], dummy_na=True,drop_first=True)\nX = pd.concat([X.drop(obj_df.columns, axis=1), pd.get_dummies(X[obj_df.columns])], axis=1)\n#See Correlations & Drop highly correlated attributes\nX1 = pd.DataFrame(X)\ncorr = X1.corr()\ncorr_matrix = X1.corr().abs()\nupper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))\nto_drop = [column for column in upper.columns if any(upper[column] > 0.95)]\nX=X.drop(columns=to_drop, axis=1)\ncolumnlist=X.columns.tolist()\n# Taking care of missing data\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\nimputer = imputer.fit(X)\nX_m = imputer.transform(X)\nX=pd.DataFrame(X_m)\n\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\nimputer = imputer.fit(y)\ny = imputer.transform(y)\ny=pd.DataFrame(y)\n\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values = 0, strategy = 'mean', axis = 0)\nimputer = imputer.fit(y)\ny = imputer.transform(y)\ny=pd.DataFrame(y)\n\n#Split Dataset Test vs. Train\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 42)\n\n\"\"\"\nI will use Keras for a regression purpose so I needed to define \"coeff_determination\" metrics. I have taken it from a Data Science blog which I could not remember right now. I have changed what I have copied a little bit according to my requirements. It was the most useful tip that I have taken from the internet while preparing this Kernel.\n\"\"\"\ndef coeff_determination(y_test, y_pred):\n    from keras import backend as K\n    SS_res =  K.sum(K.square( y_test-y_pred ))\n    SS_tot = K.sum(K.square( y_test - K.mean(y_test) ) )\n    return ( 1 - SS_res\/(SS_tot + K.epsilon()))\n#deep learning with keras lib\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom keras import backend as K\n# Initialising the ANN\nregressor = Sequential()\n# Adding the input layer and the first hidden layer\nregressor.add(Dense(output_dim = 624, kernel_initializer='normal', activation = 'relu', input_dim = 1248))\n# Adding the second hidden layer\nregressor.add(Dense(output_dim = 300, kernel_initializer='normal', activation = 'relu'))\n# Adding the 3rd hidden layer\nregressor.add(Dense(output_dim = 150, kernel_initializer='normal', activation = 'relu'))\n# Adding the 4th hidden layer\nregressor.add(Dense(output_dim = 75, kernel_initializer='normal', activation = 'relu'))\n# Adding the output layer\nregressor.add(Dense(output_dim = 1, kernel_initializer='normal', activation = 'linear'))\n# Compiling the ANN\ndef coeff_determination(y_test, y_pred):\n    from keras import backend as K\n    SS_res =  K.sum(K.square( y_test-y_pred ))\n    SS_tot = K.sum(K.square( y_test - K.mean(y_test) ) )\n    return ( 1 - SS_res\/(SS_tot + K.epsilon()))\nregressor.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics = [coeff_determination])\n# Fitting the ANN to the Training set-I have tried it with different batch sizes and epochs but it was overfitted\nregressor.fit(X_train, y_train, batch_size = 950, nb_epoch = 7)\n\"\"\"\nAs you can see above I have chosen to utilize 3 hidden layers for this prediction. With 1000 batch size I have chosen to use 7 epochs. I did not try grid search in order to find the optimal settings. Since the dataset is not huge in terms of size, I have tried and failed several times in order to find the above settings. Now let's see the visualization of the prediction.\n\"\"\"\n# Predicting the Test set results\ny_pred = regressor.predict(X_test)\n#Visualize Predicted vs. Actual\nimport matplotlib.pyplot as plt\n_, ax = plt.subplots(1, 1, figsize=(10, 10))\nax.scatter(x = range(0, y_test.size), y=y_test, c = 'green', label = 'Actual', alpha = 0.4)\nax.scatter(x = range(0, y_pred.size), y=y_pred, c = 'red', label = 'Predicted', alpha = 0.4)\nplt.title('Actual vs. Predicted')\nplt.xlabel('Test Size')\nplt.ylabel('y Value')\ndef millions(x, pos):\n    'The two args are the value and tick position'\n    return '\u20ac%1.1fM' % (x * 1e-6)\nax.yaxis.set_major_formatter(plt.FuncFormatter(millions))\nplt.legend()\nplt.show()\n\"\"\"\nR squared is \"0.94\". And I am suspicious about this result so I need to validate the result with K Fold Cross-Validation Method. Unfortunately below solution which is commonly used does not work for Keras. After a short investigaiton, I found out that there is a solution for the cross-validation of Keras.\n\"\"\"\n\"\"\"\"# Applying k-Fold Cross Validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = regressor, X = X_train, y = y_train, cv = 30)\nprint(accuracies)\nprint(accuracies.mean())\nprint(accuracies.std())\"\"\"\"\"\n#Avoid data type error\ny_pred = y_pred.round().astype(int)\ny[0] = y[0].round().astype(int)\n#K-Fold Corss Validation\nfrom sklearn.model_selection import StratifiedKFold\nkfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)\ncvscores = []\nfor train, test in kfold.split(X, y):\n  # create model\n    model = Sequential()\n    model.add(Dense(624, input_dim=1248, activation='relu'))\n    model.add(Dense(300, activation='relu'))\n    model.add(Dense(150, activation='relu'))\n    model.add(Dense(75, activation='relu'))\n    model.add(Dense(1, activation='linear'))\n    # Compile model\n    model.compile(loss='mean_squared_error', optimizer='adam', metrics=[coeff_determination])\n    # Fit the model\n    model.fit(X_train, y_train, epochs=7, batch_size=950)\n    # evaluate the model\n    scores = model.evaluate(X_test, y_test, verbose=0)\n    print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n    cvscores.append(scores[1] * 100)\nprint(\"%.2f%% (+\/- %.2f%%)\" % (np.mean(cvscores), np.std(cvscores)))\n\"\"\"\nI hope you enjoyed this Kernel. I have used Keras with an empiric way this may not be the ideal approach so I can make some additions to this Kernel in the following days. A\/B Test Result: The value of a FIFA Player can predicted with the R Squared treshold 0.85.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '3f0241b74f4c8e'}"}
{"id":"128789","text":"\"\"\"\nIn this notebook, \n\n**I am fine-tuning the pre-trained BERT_Base_Uncased on the 'Quora Questions\" Dataset of IIITB,**\n\nto classify the sentences into sincere and insincere.\n\n<h1 class=\"list-group-item list-group-item-action active\" data-toggle=\"list\" style='background:green; border:9; color:white' role=\"tab\" aria-controls=\"home\"><center>Contents<\/center><\/h1>\n\n1. [Intuition into the BERT Architecture](#BERT_Architecture)\n2. [Classification Task](#Classification_Task)\n3. [Loading Pre-trained BERT Base Uncased](#Loading_Pre-trained_BERT_Base_Uncased)\n4. [Tokenization](#BERT_Tokenizer)\n5. [Fine Tuning](#Fine_Tuning)\n6. [Predictions](#Predictions)\n\"\"\"\n\"\"\"\n## Intuition into the BERT Architecture\n\"\"\"\n\"\"\"\n![](https:\/\/images.prismic.io\/peltarionv2\/e2931afe-0ec2-4485-b26c-74b7b4fae208_BERT_token_encoder.svg)\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport spacy\nfrom tqdm import tqdm\nimport re, gc, os\nimport time\nimport pickle\npd.set_option('display.max_colwidth',None)\nimport warnings\nwarnings.filterwarnings('ignore')\n\"\"\"\n## Preprocessing of the data\n\"\"\"\n# Process the data sets\n\ndef load_data():\n    train = pd.read_csv('..\/input\/quora\/train.csv')\n    train.drop_duplicates(keep='first')\n    test  = pd.read_csv('..\/input\/quora\/test.csv')\n    submission  = pd.read_csv('..\/input\/quora\/sample_submission.csv')\n    return train, test, submission\n\ntrain, test,_= load_data()\nround(train['target'].value_counts(normalize=True)*100) # unbalanced data\ntrain.head()\n# lowercase\ntrain['question_text'] = train['question_text'].apply(lambda x:x.lower())\ntest['question_text'] = test['question_text'].apply(lambda x:x.lower())\ndef remove_qmark(s):\n    return re.sub(r\"[\/?.,']+\",'',s)\n\ntrain['question_text'] = train['question_text'].apply(lambda x:remove_qmark(x))\ntest['question_text']  = test['question_text'].apply(lambda x:remove_qmark(x))\n# remove whitespace\ntrain['question_text'] = train['question_text'].apply(lambda x:' '.join(x.split()))\ntest['question_text'] = test['question_text'].apply(lambda x: ' '.join(x.split()))\ntrain.rename(columns= {'qid':'idx','target':'label'},inplace =True)\ntest.rename(columns= {'qid':'idx'},inplace =True)\ntrain.head(1)\ntrain.info()\n!pip install s3fs -q\n!pip install fsspec==0.8.7 -qq\n!pip install --no-index --find-links ..\/input\/hf-datasets\/wheels datasets -qq\nimport datasets\nfrom datasets import Dataset\nfrom sklearn.utils import shuffle\nindex = train[:128000].index\ntrain = shuffle(train[:128000])\ntrain.index = index\nlen(train)*.2\ntrain.info()\ndf_train = train[:-25600].reset_index(drop=True) #156672 divisible by 64\ndf_valid = train[-25600:].reset_index(drop=True)\ntrain_dataset = Dataset.from_pandas(df_train)\nvalid_dataset = Dataset.from_pandas(df_valid)\ndf_train.shape,df_valid.shape\ntrain_dataset[0]\ndef change_transformers_dataset_2_right_format(dataset, label_name): \n    return dataset.map(lambda example: {'label': example[label_name]}, remove_columns=[label_name])\n\"\"\"\n## Classification Task\n\nWe are extracting the cls_head embeddings from the final encoder layer of the BERT to train the BERT and Classifier to get the final model.\n\"\"\"\n!pip install transformers  -q\nimport transformers\nprint(transformers.__version__)\n\"\"\"\n## Loading Pre-trained BERT Base Uncased\n\"\"\"\nfrom transformers import AutoTokenizer\n\nmodel_checkpoint= \"..\/input\/bert-base-uncased\"    \ntokenizer = AutoTokenizer.from_pretrained(model_checkpoint,use_fast=True)\ntask = \"sst2\"\nbatch_size = 64\n\"\"\"\n## Tokenizing the input sentences\n\"\"\"\ndef tokenizer_function(examples):\n    return tokenizer(examples['question_text'],max_length =133,padding=True,truncation=True)\nencoded_train = train_dataset.map(tokenizer_function, batched=True)\nencoded_valid = valid_dataset.map(tokenizer_function, batched=True)\nprint(encoded_train[0])\ngc.collect()\nencoded_train.set_format('torch',columns=['input_ids','attention_mask','label'])\nencoded_valid.set_format('torch',columns=['input_ids','attention_mask','label'])\ngc.collect()\nencoded_valid.set_format('torch',columns=['input_ids','attention_mask','label'])\n\"\"\"\n## Fine Tuning the pre-trained BERT Base Uncased \n\n> Feature Extraction: gathering the embeddings from the last encoder and training only classifier\n\n> Training both BERT model and Classifier\n\"\"\"\nfrom datasets import load_metric\nmetric = load_metric(\"accuracy\")\nmetric\nfrom transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer\n\nmetric_name = \"accuracy\"\nmodel_name = model_checkpoint.split(\"\/\")[-1]\n\n\nargs = TrainingArguments(\n    output_dir ='\/results',\n    evaluation_strategy = \"epoch\",\n    learning_rate=2e-5,\n    per_device_train_batch_size=batch_size,\n    per_device_eval_batch_size=batch_size,\n    num_train_epochs=2,\n    weight_decay=0.01,\n    load_best_model_at_end=True,\n    metric_for_best_model=metric_name,\n    do_predict=True\n)\nimport sklearn\nfrom sklearn import metrics\nfrom sklearn.metrics import precision_recall_fscore_support,accuracy_score\n\ndef compute_metrics(pred):\n    labels = pred.label_ids\n    preds = pred.predictions.argmax(-1)\n    precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='micro')\n    acc = accuracy_score(labels, preds)\n    return {\n        'accuracy': acc,\n        'f1': f1,\n        'precision': precision,\n        'recall': recall\n    }\nmodel = AutoModelForSequenceClassification.from_pretrained(model_checkpoint, num_labels=2)\nimport torch\n# determine the device we will be using for training\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nprint(\"[INFO] training using {}\".format(torch.cuda.get_device_name(0)))\ntorch.cuda.empty_cache()\ntrainer = Trainer(\n    model,\n    args,\n    train_dataset=encoded_train,\n    eval_dataset =encoded_valid,\n    tokenizer=tokenizer,\n    compute_metrics=compute_metrics\n)\ntrainer.train()\ntrainer.evaluate()\n#del train,encoded_train,encoded_valid\ngc.collect()\n\"\"\"\n### Submission\n\"\"\"\ntest.info()\ntest_dataset = Dataset.from_pandas(test)\nencoded_test = test_dataset.map(tokenizer_function, batched=True)\nencoded_test.set_format('torch',columns=['input_ids','attention_mask'])\nencoded_test[0]\n#encoded_test_input_ids = encoded_test['input_ids']\n#encoded_test_attention_mask = encoded_test['attention_mask']\ngc.collect()\noutput = trainer.predict(encoded_test)\npreds = output[0]#predictions\nlabels = np.argmax(preds,axis=1)\n_,_,sub = load_data()\nsub.head()\nsub['target'] = labels\nsub['target'].value_counts()\nsub.info()\nsub.head(10)","meta":"{'source': 'AI4Code', 'id': 'ece4d70d31b8ed'}"}
{"id":"124933","text":"\"\"\"\n![](https:\/\/www.unmc.edu\/chri\/_images\/Clinical-Trial-Basics-Diagram.jpg)unmc.edu\n\"\"\"\n# 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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.offline as py\nimport plotly.express as px\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\nfrom colorama import Fore, Style\n\nnRowsRead = 1000 # specify 'None' if want to read whole file\n# ham_lyrics.csv has 3634 rows in reality, but we are only loading\/previewing the first 1000 rows\ndf = pd.read_csv('..\/input\/covid19-clinical-trials\/covid_clinical trials.csv', delimiter=',', nrows = nRowsRead)\ndf.dataframeName = 'covid19-clinical-trials\/covid_clinical trials.csv'\nnRow, nCol = df.shape\nprint(f'There are {nRow} rows and {nCol} columns')\nprint(Fore.BLUE + 'Data shape: ',Style.RESET_ALL,df.shape)\ndf.head()\ndf.isnull().sum()\n#Code from Gabriel Preda\n#plt.style.use('dark_background')\ndef plot_count(feature, title, df, size=1):\n    f, ax = plt.subplots(1,1, figsize=(4*size,4))\n    total = float(len(df))\n    g = sns.countplot(df[feature], order = df[feature].value_counts().index[:20], palette= ('#32a852', '#a84e32', '#3242a8'))\n    g.set_title(\"Number and percentage of {}\".format(title))\n    if(size > 2):\n        plt.xticks(rotation=90, size=8)\n    for p in ax.patches:\n        height = p.get_height()\n        ax.text(p.get_x()+p.get_width()\/2.,\n                height + 3,\n                '{:1.2f}%'.format(100*height\/total),\n                ha=\"center\") \n    plt.show()\nplot_count(\"Sponsor\/Collaborators\", \"Sponsor\/Collaborators\", df,4)\nplot_count(\"Locations\", \"Locations\", df,4)\nplot_count(\"Acronym\", \"Acronym\", df,4)\nplot_count(\"Status\", \"Status\", df,4)\nplot_count(\"Phases\", \"Phases\", df,4)\nplot_count(\"Funded Bys\", \"Funded Bys\", df,4)\nplot_count(\"Study Type\", \"Study Type\", df,4)\nplot_count(\"Study Designs\", \"Study Designs\", df,4)\nplot_count(\"Study Results\", \"Study Results\", df,4)\n\"\"\"\n#Handling Missing Values\n\"\"\"\n# categorical features with missing values\ncategorical_nan = [feature for feature in df.columns if df[feature].isna().sum()>0 and df[feature].dtypes=='O']\nprint(categorical_nan)\n# replacing missing values in categorical features\nfor feature in categorical_nan:\n    df[feature] = df[feature].fillna('None')\ndf[categorical_nan].isna().sum()\n# Lets first handle numerical features with nan value\nnumerical_nan = [feature for feature in df.columns if df[feature].isna().sum()>1 and df[feature].dtypes!='O']\nnumerical_nan\ndf[numerical_nan].isna().sum()\n## Replacing the numerical Missing Values\n\nfor feature in numerical_nan:\n    ## We will replace by using median since there are outliers\n    median_value=df[feature].median()\n    \n    df[feature].fillna(median_value,inplace=True)\n    \ndf[numerical_nan].isnull().sum()\n#Code by Taha07  https:\/\/www.kaggle.com\/taha07\/data-scientists-jobs-analysis-visualization\/notebook\n\ncolor = plt.cm.RdBu(np.linspace(0,1,20))\ndf[\"Phases\"].value_counts().sort_values(ascending=False).head(20).plot.pie(y=\"Status\",colors=color,autopct=\"%0.1f%%\")\nplt.title(\"Phases of Clinical Trials\")\nplt.axis(\"off\")\nplt.show()\n#Code by Taha07  https:\/\/www.kaggle.com\/taha07\/data-scientists-jobs-analysis-visualization\/notebook\n\ncolor = plt.cm.rainbow(np.linspace(0,1,20))\ndf[\"Study Type\"].value_counts().sort_values(ascending=False).head(15).plot.pie(y=\"Status\",colors=color,autopct=\"%0.1f%%\")\nplt.title(\"Study Type of Clinical Trials\")\nplt.axis(\"off\")\nplt.show()\n#Code by Taha07  https:\/\/www.kaggle.com\/taha07\/data-scientists-jobs-analysis-visualization\/notebook\n\ncolor = plt.cm.Pastel1(np.linspace(0,1,30))\ndf[\"Study Designs\"].value_counts().sort_values(ascending=False).head(10).plot.pie(y=\"Status\",colors=color,autopct=\"%0.1f%%\")\nplt.title(\"Study Designs of Clinical Trials\")\nplt.axis(\"off\")\nplt.show()\n\"\"\"\n#I couldn't make my Decision Tree neither the Genetic Algorithm. Then I gave up. I'll try another aproach later. \n\"\"\"\n#Code by Olga Belitskaya https:\/\/www.kaggle.com\/olgabelitskaya\/sequential-data\/comments\nfrom IPython.display import display,HTML\nc1,c2,f1,f2,fs1,fs2=\\\n'#eb3434','#eb3446','Akronim','Smokum',30,15\ndef dhtml(string,fontcolor=c1,font=f1,fontsize=fs1):\n    display(HTML(\"\"\"<style>\n    @import 'https:\/\/fonts.googleapis.com\/css?family=\"\"\"\\\n    +font+\"\"\"&effect=3d-float';<\/style>\n    <h1 class='font-effect-3d-float' style='font-family:\"\"\"+\\\n    font+\"\"\"; color:\"\"\"+fontcolor+\"\"\"; font-size:\"\"\"+\\\n    str(fontsize)+\"\"\"px;'>%s<\/h1>\"\"\"%string))\n    \n    \ndhtml('Mar\u00edlia Prata, @mpwolke ist hier' )","meta":"{'source': 'AI4Code', 'id': 'e5d05c059d2dc3'}"}
{"id":"46100","text":"\"\"\"\n# Using Energy Efficiency Dataset for Linear Regression\n\"\"\"\n\"\"\"\nThe data source is from https:\/\/archive.ics.uci.edu\/ml\/datasets\/Energy+efficiency\n\nThis notebook will explore the dataset and use linear regression to explain the relationship between the independent variables and dependent variable (heating load) with random forest regressor to be used as a model for feature selection. \n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.ensemble import RandomForestRegressor as rf_reg\nfrom sklearn.model_selection import RandomizedSearchCV as randomCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error as MSE\nfrom sklearn import feature_selection\nfrom sklearn.linear_model import LinearRegression as l_reg\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import r2_score\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import cross_validate\nfrom plotnine import *\nfrom matplotlib import gridspec\nfrom sklearn.preprocessing import StandardScaler\nimport pprint\n\"\"\"\n# Data Loading\n\"\"\"\n\"\"\"\nThis section is to load the data into the notebook for data exploration and statistical modelling purposes.\n\"\"\"\nenergy_df=pd.read_csv(r'..\/input\/eergy-efficiency-dataset\/ENB2012_data.csv')\nenergy_df.head()\n\"\"\"\nAdding column name for each column in the dataframe for clearer understanding and easier data slicing using pandas.\n\"\"\"\nenergy_df.columns=[\"relative_compactness\",\"surface_area\",\"wall_area\",\"roof_area\",\"overall_height\",\"orientaion\",\n                   \"glazing_area\",\"glazing_area_dist\",\"heating_load\",\"cooling_load\"]\n\"\"\"\n# Data Exploration & Transformation\n\"\"\"\n\"\"\"\nThis section will explore data through summary table, histogram and correlation matrix to understand the data, explore the relationship between the variables and check whether the data contain any missing values. \n\"\"\"\nenergy_df.describe()\n\"\"\"\nBased on the counts in the summary table above, there are no missing values for each variable as the counts for each variable are the same. However, glazing area and glazing area distribution have values 0 for some instances. \n\"\"\"\nenergy_df.loc[energy_df[\"glazing_area\"]==0].describe()\nenergy_df.loc[energy_df[\"glazing_area_dist\"]==0].describe()\n\"\"\"\nBased on the 2 summary tables above, when glazing area or glazing area distribution is 0, the other also contain value 0. So, if glazing area or glazing area distribution are valued at 0 for a building, it can be assumed that the building itself do not have glazing area. \n\"\"\"\nenergy_df.hist(figsize=(15,15))\nplt.show()\n\"\"\"\nLooking at heating load and cooling, they seem to be heavily skewed to the right. Therefore, log transformation will be done on heating load and cooling load to make them more normalised in term of distribution\n\"\"\"\nenergy_df[\"log_heating_load\"]=np.log(energy_df[\"heating_load\"])\nenergy_df[\"log_heating_load\"].hist(bins=6)\nplt.show()\nenergy_df[\"log_cooling_load\"]=np.log(energy_df[\"cooling_load\"])\nenergy_df[\"log_cooling_load\"].hist(bins=6)\nplt.show()\n\"\"\"\nAfter log transformation on heating and cooling loads, both variables' distributions look better but both show bimodal distribution as two peaks are formed. \n\"\"\"\nsns.pairplot(energy_df)\nplt.show()\ncorr = energy_df.corr()\nmask = np.zeros_like(corr, dtype=bool)\nmask[np.triu_indices_from(mask)] = True\nf, ax = plt.subplots(figsize=(12, 10))\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\nsns.heatmap(corr, mask=mask,cmap=cmap, vmax=.9, center=0, square=True, linewidths=.5, annot=True,cbar_kws={\"shrink\": .5})\nplt.show()\n\"\"\"\nrelative compactness is highly correlated to surface area, roof area and overall height. Therefore, feature selection is required to reduce the number of features that are highly correlated.\n\nheating load is highly correlated to cooling load which suggested that only 1 of them can be used as dependent factor to determine energy efficiency of the building. Therefore, log heating load is selected as dependent variable to determine energy efficiency in term of heating load.  \n\"\"\"\n\"\"\"\n# Using Raw Data (Log_heating_load)\n\"\"\"\n\"\"\"\nUsing the dataset above with log heating load as the main dependent variable, the data is split into train and test datasets with the ratio of 80:20. After splitting, feature selection and model fitting using linear regression will be done to test the performance of linear regression after feature selection.\n\"\"\"\nenergy_df_f=energy_df.copy()\nenergy_df_f.drop([\"heating_load\",\"cooling_load\"],axis=1,inplace=True)\n#energy_df_f.drop([\"log_heating_load\",\"cooling_load\"],axis=1,inplace=True)\n\nenergy_X=energy_df_f.iloc[:,:-2]\nenergy_Y=energy_df_f.loc[:,[\"log_heating_load\"]]\n#energy_Y=energy_df_f.loc[:,[\"heating_load\"]]\n\nenergy_train_X,energy_test_X,energy_train_Y,energy_test_Y=\\\ntrain_test_split(energy_X,energy_Y,test_size=0.20,random_state=48)\n\nprint(energy_train_X.shape)\nprint(energy_test_X.shape)\n\"\"\"\nTrain dataset has 614 instances while test dataset has 154 instances with 8 variables including log heating load after dropping heating load and cooling load. \n\"\"\"\n\"\"\"\n## Randomised Grid Search for Random Forest Regressor\n\"\"\"\n\"\"\"\nThis section will use the data with log heating load as the main dependent variable to do a randomised cross validation search for random forest regressor to tune the hyperparameters for random forest regressor. The random forest regressor is used as feature selection model as the model can calculate the weight importance for each variable based on the proportion of each variable is used in the model to partition the data in a way that the predicted value is closer to the actual value in dependent variable.\n\"\"\"\ndef rf_regr_cv_model(min_sample_split_in,min_sample_leaf_in,max_feature_in):\n    rf_grid={\"min_samples_split\":min_sample_split_in,\n             \"min_samples_leaf\":min_sample_leaf_in,\"max_features\":max_feature_in}\n    regr = rf_reg(max_depth=3, random_state=48)\n    rf_reg_cv = randomCV(regr, rf_grid, random_state=48,scoring='neg_root_mean_squared_error',cv=5)\n    return rf_reg_cv\n\"\"\"\nThe function above is to create a randomised cross-validation search process using random forest regressor as base model to tune the hyperparameters in the model. The hyperparameters to be tuned are minimum sample split, minimum sample size in the leaf and maximum features to be used in each regression tree. The model is regularised with maximum depth of 3 and using seed number 48 to prevent overfitting. Root mean squared error (RMSE) is used as the scoring criteria to determine the best set of hyperparameters.\n\"\"\"\nmin_sample_split=np.arange(10,35,5)\nmin_sample_leaf=np.arange(10,35,5)\nmax_feature=np.arange(3,7,1)\n\nrf_reg_search=rf_regr_cv_model(min_sample_split_in=min_sample_split,min_sample_leaf_in=min_sample_leaf,\n                            max_feature_in=max_feature)\nrf_reg_search.fit(energy_train_X,np.ravel(energy_train_Y))\n\"\"\"\nUsing the rf_regr_cv_model and the hyperparameters declared, train dataset will be fitted into the model to determine the best set of hyperparameters for the model. \n\"\"\"\nprint(\"Best parameters set:\",rf_reg_search.best_params_)\nprint(\"Best score:\",rf_reg_search.best_score_)\n\"\"\"\nBased on the randomised CV search result above, the model performs the best when:\n1. the sample split at 30 \n2. each leaf has 10 instances\n3. 6 features are used\n\nThe model is refitted with the best set of hyperparameters found in randomised CV search.\n\"\"\"\nregr_rf_best=rf_reg(min_samples_split= 30, min_samples_leaf=10, max_features=6,max_depth=3,random_state=48)\nregr_rf_best.fit(energy_train_X,np.ravel(energy_train_Y))\npredicted_train_Y=regr_rf_best.predict(energy_train_X)\npredicted_test_Y=regr_rf_best.predict(energy_test_X)\nprint(\"RMSE for Train set:\",MSE(predicted_train_Y,energy_train_Y,squared=False))\nprint(\"RMSE for Test set:\",MSE(predicted_test_Y,energy_test_Y,squared=False))\n\"\"\"\nLooking at the model performance in term of RMSE, the model seems to be overfitting as RMSE in test is higher than in train. But, the difference is quite small, around 0.02.\n\"\"\"\n\"\"\"\n## Feature Selection\n\"\"\"\n\"\"\"\nThis section will conduct feature selection using weight importance calculated from the random forest regressor to select the features to be used in linear regression\n\"\"\"\nfeature_list=list(energy_train_X.columns)\nfeature_impt=list(regr_rf_best.feature_importances_)\nfeature_impt_dict=dict(zip(feature_list,feature_impt))\nfeature_impt_dict=dict(sorted(feature_impt_dict.items(), key=lambda item: item[1],reverse=True))\nfeature_impt_dict\n\"\"\"\nLooking at the list above, relative compactness, surface area, overall height, roof area and glazing area are the top 5 features. However, there are 2 pairs of variables that are high correlated:\n1. relative compactness with surface area\n2. roof area with surface area\n3. overall height with roof area\n4. relative compactness with overall height\n\n\"\"\"\nfinal_feature_list=[\"relative_compactness\",\"overall_height\",\"glazing_area\",\"wall_area\",\"roof_area\",\"surface_area\"]\n\"\"\"\nA feature list is created with the roof area and surface area as the last 2 features as linear regression will be done using forward selection by adding variables one by one according to the feature list and selecting the smallest RMSE and biggest r2.\n\"\"\"\n\"\"\"\n## Forward Selection Linear Regression\n\"\"\"\n\"\"\"\nThis section will conduct linear regression model fitting using forward selection by adding variables one by one into the model. The best model will be the one with the biggest negative RMSE and biggest r2. \n\"\"\"\ndef l_reg_cv(train_X,train_Y,feature_list):\n    rmse_list_train=[]\n    rmse_list_test=[]\n    r2_list_train=[]\n    r2_list_test=[]\n    for i in range(1,len(feature_list)+1):\n        train_X_temp=train_X.loc[:,feature_list[:i]]\n        cv_results_temp = cross_validate(l_reg(), train_X.loc[:,final_feature_list[:i]],train_Y, \n                            cv=5,scoring=[\"neg_root_mean_squared_error\",\"r2\"],return_train_score=True)\n        mean_rmse_train=np.mean(cv_results_temp[\"train_neg_root_mean_squared_error\"])\n        mean_r2_train=np.mean(cv_results_temp[\"train_r2\"])\n        mean_rmse_test=np.mean(cv_results_temp[\"test_neg_root_mean_squared_error\"])\n        mean_r2_test=np.mean(cv_results_temp[\"test_r2\"])\n        rmse_list_train.append(mean_rmse_train)\n        r2_list_train.append(mean_r2_train)\n        rmse_list_test.append(mean_rmse_test)\n        r2_list_test.append(mean_r2_test)\n        rmse_df=pd.DataFrame(zip(rmse_list_train,rmse_list_test,r2_list_train,r2_list_test))\n        rmse_df.columns=[\"Mean RMSE Train\",\"Mean RMSE Test\",\"Mean R2 Train\",\"Mean R2 Test\"]\n        rmse_df.index=rmse_df.index+1\n    return rmse_df\n\"\"\"\nThe function above is to do a linear regression model fitting based on the feature list. The data with independent variables (train_X) will be sliced according to the variables in the feature list and fit into the model with dependent variable. Then, RMSE and R2 will be calculated for each set of independent variables fitted into the model to find out which set of independent variables is the most optimal to fit into the model. \n\"\"\"\nrmse_cv=l_reg_cv(energy_train_X,np.ravel(energy_train_Y),final_feature_list)\nrmse_cv\nfig,ax=plt.subplots(1,2,figsize=(10,5))\nsns.lineplot(data=rmse_cv.iloc[:,:2],ax=ax[0])\nsns.lineplot(data=rmse_cv.iloc[:,2:],ax=ax[1])\nax[0].set_title(\"Mean Negative RMSE \\n Based on Number of Features\")\nax[1].set_title(\"Mean R2 Based on Number of Features\")\nplt.show()\n\"\"\"\nLooking at the graphs and the table above, linear regression with 5 features seems to be better as it has higher negative mean RMSE and higher mean R2 in test set compared to others. Furthermore, means for negative RMSE and R2 in test slightly decreased when using 6 features. \n\nTherefore,the most optimal number of features to be used in linear regression is 5 and the selected 5 features are relative_compactness, overall_height, glazing_area, wall_area and roof_area.\n\"\"\"\n\"\"\"\n## Best Fit Linear Regression Model\n\"\"\"\n\"\"\"\nThis section will be refitted the linear regression model using the top 5 features in the previous section.\n\"\"\"\nl_reg_best=l_reg()\nl_reg_best.fit(energy_train_X.loc[:,final_feature_list[:5]],np.ravel(energy_train_Y))\npred_train_Y_best=l_reg_best.predict(energy_train_X.loc[:,final_feature_list[:5]])\npred_test_Y_best=l_reg_best.predict(energy_test_X.loc[:,final_feature_list[:5]])\nprint(\"RMSE for Train set:\",MSE(pred_train_Y_best,energy_train_Y,squared=False))\nprint(\"RMSE for Test set:\",MSE(pred_test_Y_best,energy_test_Y,squared=False))\n\"\"\"\nThe difference between test and train in RMSE is at least 0.01 which is quite small. \n\"\"\"\nprint(\"R2 for Train set:\",r2_score(pred_train_Y_best,energy_train_Y))\nprint(\"R2 for Test set:\",r2_score(pred_test_Y_best,energy_test_Y))\n\"\"\"\nThe difference between test and train is at least 0.02 which is quite small.\n\nTherefore, the current model should be sufficient to predict the energy efficiency of a building in term of log heating load as the model can explain 90% of the variation in the data according to R2 and has small RMSE. \n\"\"\"\ndict(zip(final_feature_list[:5],np.exp(l_reg_best.coef_)))\n\"\"\"\nBased on the coefficients above:\n1. Heating load will be increased by a multiplicative factor of 2.43 when relative compactness increases by 1. \n2. Heating load will be increased by a multiplicative factor of 1.30 when overall height increases by 1. \n3. Heating load will be increased by a multiplicative factor of 2.86 when glazing area increases by 1. \n4. Wall area and roof area affect the heating load but lesser magnitude compared to the previous 3 factors. \n\"\"\"\n\"\"\"\n## Model Diagnostics\n\"\"\"\n\"\"\"\nThis section will look at the prediction performance of the model by plotting scatter plot for comparison between actual and predicted values, histogram for prediction errors and residual plot. \n\"\"\"\ndef predictVSactual(actual_y,y_predict,title_label):\n    fig,ax=plt.subplots(1,len(actual_y),figsize=(15,15))\n    for i,col in enumerate(actual_y,0):\n        ax[i].plot(np.ravel(actual_y[i]),\n                   np.ravel(y_predict[i]),'o',markeredgecolor=\"black\")\n        ax[i].set_title(title_label[i])\n        ax[i].set_xlabel('Actual Values')\n        ax[i].set_ylabel('Predicted Values')\n        ax[i].set(aspect='equal')\n        x=ax[i].get_xlim()\n        y=ax[i].get_xlim()\n        ax[i].plot(x,y, ls=\"--\", c=\".3\")\n    return fig,ax\n#+np.random.normal(0.1, 0.005,len(actual_y[i]))\n\"\"\"\nThe function above is to plot two scatter plots side by side with train on the left and test on the right using actual values and predicted values that store in list as inputs. \n\"\"\"\nactual_y_energy=[energy_train_Y,energy_test_Y]\npred_y_energy=[pred_train_Y_best,pred_test_Y_best]\npredictVSactual(actual_y_energy,pred_y_energy,\n                [\"Scatter Plot: Prediction Comparison (Train)\",\"Scatter Plot: Prediction Comparison (Test)\"])\nplt.show()\n\"\"\"\nLooking at the scatter plot, the model seems to be underestimated the heating load as more points situated at the right side of the diagonal line. \n\"\"\"\ndef residual_plot(actual_y,predict_y,title_label):\n    fig,ax=plt.subplots(1,len(actual_y),figsize=(10,5))\n    for i,col in enumerate(actual_y,0):\n        sns.residplot(x=actual_y[i], y=predict_y[i], lowess=True, color=\"g\",ax=ax[i])\n        ax[i].set_title(title_label[i])\n    return fig,ax\nresidual_plot(actual_y_energy,pred_y_energy,[\"Train\",\"Test\"])\nplt.show()\n\"\"\"\nLooking at the residual plots, they indicated that the residuals are in the range of -0.35 to 0.4. There are some outliers in train and test datasets as there are some instances with residuals greater than 0.3 or lesser than -0.3. The residual plots do not show any particular trends in the residuals. \n\"\"\"\nraw_pred_err_list=[]\n\nfor i in range(0,len(actual_y_energy)):\n    list_temp=[]\n    list_temp=actual_y_energy[i].to_numpy().ravel()-pred_y_energy[i]\n    raw_pred_err_list.append(list_temp)\nraw_pred_err_label=[\"Raw Prediction Errors (Train)\",\"Raw Prediction Errors (Test)\"]\ndef raw_predict_err_hist(err_predict_list,bin_no,title_label):\n    fig,ax=plt.subplots(1,len(err_predict_list),figsize=(10,5))\n    for i,col in enumerate(err_predict_list,0):\n        sns.histplot(x=err_predict_list[i],bins=bin_no,kde=True,ax=ax[i])\n        ax[i].set_title(title_label[i])\n    return fig,ax\nraw_predict_err_hist(raw_pred_err_list,bin_no=7,title_label=raw_pred_err_label)\nplt.show()\n\"\"\"\nLooking at the histogram above, the residuals are normally distributed with long left tails. Most prediction errors are in the range of -0.1 to 0.1.\n\"\"\"\n\"\"\"\n# Using Raw Data (Log_cooling_load)\n\"\"\"\n\"\"\"\nFor this section, cooling load is used to find out the relationships for the same features with cooling load. \n\"\"\"\nenergy2_X=energy_df_f.iloc[:,:-2]\nenergy2_Y=energy_df_f.loc[:,[\"log_cooling_load\"]]\n#energy_Y=energy_df_f.loc[:,[\"heating_load\"]]\n\nenergy2_train_X,energy2_test_X,energy2_train_Y,energy2_test_Y=\\\ntrain_test_split(energy2_X,energy2_Y,test_size=0.20,random_state=48)\nrmse_cv2=l_reg_cv(energy2_train_X,np.ravel(energy2_train_Y),final_feature_list)\nrmse_cv2\nfig,ax=plt.subplots(1,2,figsize=(10,5))\nsns.lineplot(data=rmse_cv2.iloc[:,:2],ax=ax[0])\nsns.lineplot(data=rmse_cv2.iloc[:,2:],ax=ax[1])\nax[0].set_title(\"Mean Negative RMSE \\n Based on Number of Features\")\nax[1].set_title(\"Mean R2 Based on Number of Features\")\nplt.show()\n\"\"\"\nLooking at the table and graphs above, the appropriate number of features are 5 as using 6 features do not show any great improvement on RMSE and R2 for both train and test datasets. \n\"\"\"\nl_reg2_best=l_reg()\nl_reg2_best.fit(energy2_train_X.loc[:,final_feature_list[:5]],np.ravel(energy2_train_Y))\npred2_train_Y_best=l_reg2_best.predict(energy2_train_X.loc[:,final_feature_list[:5]])\npred2_test_Y_best=l_reg2_best.predict(energy2_test_X.loc[:,final_feature_list[:5]])\nprint(\"RMSE for Train set:\",MSE(pred2_train_Y_best,energy2_train_Y,squared=False))\nprint(\"RMSE for Test set:\",MSE(pred2_test_Y_best,energy2_test_Y,squared=False))\n\"\"\"\nThe difference between test and train in RMSE is at least 0.01.\n\"\"\"\nprint(\"R2 for Train set:\",r2_score(pred2_train_Y_best,energy2_train_Y))\nprint(\"R2 for Test set:\",r2_score(pred2_test_Y_best,energy2_test_Y))\n\"\"\"\nR2 for test is lower when using log cooling load as dependent variable instead of log heating load. \n\"\"\"\n\"\"\"\n## Model Diagnostics\n\"\"\"\nactual2_y_energy=[energy2_train_Y,energy2_test_Y]\npred2_y_energy=[pred2_train_Y_best,pred2_test_Y_best]\n\npredictVSactual(actual2_y_energy,pred2_y_energy,\n                [\"Scatter Plot: Prediction Comparison (Train)\",\"Scatter Plot: Prediction Comparison (Test)\"])\nplt.show()\n\"\"\"\nSimilar to using log heating load as dependent variable, the model seems to be underestimated the cooling load as most points are at the right side of the diagonal line. \n\"\"\"\nresidual_plot(actual2_y_energy,pred2_y_energy,[\"Train\",\"Test\"])\nplt.show()\n\"\"\"\nThe range of the residuals is between -0.3 to 0.3. The residual plots do not show any particular trends in the residuals. \n\"\"\"\nraw_pred2_err_list=[]\n\nfor i in range(0,len(actual2_y_energy)):\n    list_temp=[]\n    list_temp=actual2_y_energy[i].to_numpy().ravel()-pred2_y_energy[i]\n    raw_pred2_err_list.append(list_temp)\nraw_pred2_err_label=[\"Raw Prediction Errors (Train)\",\"Raw Prediction Errors (Test)\"]\nraw_predict_err_hist(raw_pred2_err_list,bin_no=8,title_label=raw_pred2_err_label)\nplt.show()\n\"\"\"\nLooking at the histograms above, the residuals are approximately normally distributed. The prediction errors seem to be larger using log cooling load compared to log heating load.\n\"\"\"\n\"\"\"\n# Interpretation on Regression Coefficients\n\"\"\"\nprint(\"Log heating load as dependent variable:\")\ndict(zip(final_feature_list[:5],np.exp(l_reg_best.coef_)))\n\"\"\"\nBased on the coefficients above:\n\n1. Heating load will be increased by a multiplicative factor of 2.43 when relative compactness increases by 1.\n2. Heating load will be increased by a multiplicative factor of 1.30 when overall height increases by 1.\n3. Heating load will be increased by a multiplicative factor of 2.86 when glazing area increases by 1.\n4. Wall area and roof area do affect the heating load but lesser magnitude compared to the previous 3 factors.\n\nTherefore, lower building with low relative compactness and small glazing area requires less energy to warm up the indoor environment. Smaller wall area and roof area also reduce energy required to warm up the indoor environment.\n\"\"\"\nprint(\"Log cooling load as dependent variable:\")\ndict(zip(final_feature_list[:5],np.exp(l_reg2_best.coef_)))\n\"\"\"\nBased on the coefficients above:\n\n1. Cooling load will be reduced by a multiplicative factor of 0.36 when relative compactness increases by 1.\n2. Cooling load will be increased by a multiplicative factor of 1.23 when overall height increases by 1.\n3. Cooling load will be increased by a multiplicative factor of 1.88 when glazing area increases by 1.\n4. Wall area and roof area do affect the cooling load but lesser magnitude compared to the previous 3 factors.\n\nTherefore, lower building with high relative compactness and small glazing area requires less energy to cool down the indoor environment. Smaller wall area and bigger roof area also reduce energy required to cool down the indoor environment.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '54f8068e688b8b'}"}
{"id":"108657","text":"# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nimport seaborn as sns\nfrom sklearn.preprocessing import scale \nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nfrom sklearn.metrics import roc_auc_score,roc_curve\nimport statsmodels.formula.api as smf\nfrom sklearn.linear_model import LogisticRegression\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\nimport pandas as pd\ndf = pd.read_csv(\"..\/input\/breast-cancer-wisconsin-data\/data.csv\")\ndata = df.copy()\ndata.drop([\"Unnamed: 32\", \"id\"], axis=1, inplace=True)                  # Unnamed: 32 sutunu veriye baktigimizda nan lardan olusuyor ondan drop edelim\ndata.diagnosis = [1 if each == \"M\" else 0 for each in data.diagnosis]   # binary yani 0 ile 1 degerlerden olusturmamiz gerekiyor. object lerden olusuyor bunun yerine 0 ile 1 lerden olurmali. cunku bize int veya float lazim\ndata.head()\ndata.describe()\ny = data.diagnosis.values\nx_data = data.drop([\"diagnosis\"], axis=1)\n# x degerlerimiz baktigimizda degerlerin cok buyuk oldugu gorulur. Dolayisiyla verimizi normallestirmemiz gerekiyor\n\n#*** Normalize ***#\nx = (x_data - np.min(x_data))\/(np.max(x_data) - np.min(x_data)).values\nX_train, X_test, y_train, y_test = train_test_split(x, y, \n                                                    test_size=0.30, \n                                                    random_state=42)\n\"\"\"\n# Logistic Regresyon\n\n* Amac henuz gozlenmemis bir x deger seti geldiginde bunun sonucunda olusacak olan sinifi ortaya cikarmak tahmin etmek bir siniflandirici cikarmaktir.\n* Siniflandirma problemi icin bagimli ve bagimsiz degiskenler arasindaki iliskiyi tanimlayan linear bir model kurmaktir.\n* Bagimli degiskenin 1 yada 0 olmasi durumuyla ilgilenir yada evet veya hayir durumu\n* Bize int veya float degerlerle is yapar\n\"\"\"\n\"\"\"\n## MODEL\n\n\"\"\"\n# statsmodels araciligiyla model kurup fit yapalim. Burda bize modelin anlamliligi ve hangi degiskenin ne kadar etki ettigi bu tablodan cikiyor\n\nloj = sm.Logit(y, x)\nloj_model= loj.fit()\nloj_model.summary()\nfrom sklearn.linear_model import LogisticRegression\nloj = LogisticRegression(solver = \"liblinear\")\nloj_model = loj.fit(x,y)\nloj_model\n# sabit degeri\nloj_model.intercept_\n# butun bagimsiz degiskenlerin katsayi degerleri\nloj_model.coef_\n\"\"\"\n## PREDICT and MODEL TUNNING\n\"\"\"\n# tahmini yapalim\ny_pred = loj_model.predict(x)\n# Gercekte 1 iken 1(PP) olanlar 1 iken 0(PN) olanlar, gercekte 0 iken 1(NP) olanlar 0 iken 0(NN) olanlar\nconfusion_matrix(y, y_pred)\n# accuracy degerine bakalim\naccuracy_score(y, y_pred)\n# en detayli bir siniflandirma algoritmasinin sonuclarini degerlendirecek ciktilardan biri\nprint(classification_report(y, y_pred))\n# ilk 10 model tahmini\nloj_model.predict(x)[0:10]\n# yukarda 1 ve 0 verdigi degerlerden ziyade asil degerlerini versin istiyorsak 'predict_proba' modulunu kullanarak gercek degerleri\n# matriste 0. indexinde veya sol tarafi 0 a ait degerleri, 1. indexinde veya sag tarafi 1 e ait degerleri verir \nloj_model.predict_proba(x)[0:10][:,0:2]                # ilk 10\n# simdi yukardaki 'predict_proba' on tahmin olasilik degerlerini model haline getirmeye calisalim\ny_probs = loj_model.predict_proba(x)\ny_probs = y_probs[:,1]\ny_probs[0:10]               # ilk 10\n# burdaki tahmin degerlerimizi donguye sokup 0.5 ten buyuklere 1 ve kucuk olanlara 0 versin\ny_pred = [1 if i > 0.5 else 0 for i in y_probs]\n# yukardaki degere baktigimizda degisikligi farketmis oluruz ama burda degisiklik yok cunku dogrulanmasi gereken cok bir deger yokmus demekki. Bunu yapma amacimiz modelimizi dogrulamaktir.\ny_pred[0:10]\nconfusion_matrix(y, y_pred)\naccuracy_score(y, y_pred)\nprint(classification_report(y, y_pred))\n# bunu yukarda yaptik ilk 5 eleman gorunsun\nloj_model.predict_proba(x)[:,1][0:5]\nlogit_roc_auc = roc_auc_score(y, loj_model.predict(x))\nfpr, tpr, thresholds = roc_curve(y, loj_model.predict_proba(x)[:,1])\nplt.figure()\nplt.plot(fpr, tpr, label='AUC (area = %0.2f)' % logit_roc_auc)\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Oran\u0131')\nplt.ylabel('True Positive Oran\u0131')\nplt.title('ROC')\nplt.show()\n# mavi cizgi kurmus oldugumuz model ile ilgili basarimizin grafigi\n# kirmizi cizgi hicbirsey yapmasak modelimiz bu sekilde olacak\n\n\n# Sekilde goruldugu gibi cok degistirilmesi veya dogrulanmasi gereken deger bulamadi bu veride.\n\n\n# test train ayirma islemine tabi tutalim\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.20, random_state = 42)\n# Modelimizi olusturup fit edelim\nloj = LogisticRegression(solver = \"liblinear\")\nloj_model = loj.fit(X_train,y_train)\nloj_model\n# dogrulanma skorunu bulalim\naccuracy_score(y_test, loj_model.predict(X_test))\n# dogrulanmis modelin CV skoru bulalim\ncross_val_score(loj_model, X_test, y_test, cv = 10).mean()\n\"\"\"\n# KNN (K-Nearst Neigbourhood)\n\n\"\"\"\n\"\"\"\n* Tahminler gozlem benzerligine gore yapilir. Bana arkadasini soyle sana kim oldugunu soyleyeyeyim mantigi ile calisir.\n\n* Bagimsiz degiskenler ile diger degiskenler arasindaki uzaklik hesaplanir. en yakin k adet gozlemi bulup bunun icin en yakin gozlenen sinif model sinifidir.\n\"\"\"\n# model kurma\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\nknn_model = knn.fit(X_train, y_train)\nknn_model\n# tahmin degeri\ny_pred = knn_model.predict(X_test)\naccuracy_score(y_test, y_pred)\n# detayli ciktimizida alalim. \nprint(classification_report(y_test, y_pred))\n\"\"\"\n##  MODEL TUNNING \n\"\"\"\n# KNN parametrelerini bulma\nknn_params = {\"n_neighbors\": np.arange(1,50)}\n# siniflandirmasi ve CV ile fit yapalim\nknn = KNeighborsClassifier()\nknn_cv = GridSearchCV(knn, knn_params, cv=10)\nknn_cv.fit(X_train, y_train)\n# bunu sadece gozlemlemek icin yapiyoruz. Final modeli onemli bizim icin\nprint(\"En iyi skor:\" + str(knn_cv.best_score_))\nprint(\"En iyi parametreler: \" + str(knn_cv.best_params_))\n# yukarida ciktida ortaya cikan n_neighbors 11 cikmisti bunu kullanarak KNN olusturulup tuned edelim\nknn = KNeighborsClassifier(11)\nknn_tuned = knn.fit(X_train, y_train)\n# simdide test in tuned score una bakalim\nknn_tuned.score(X_test, y_test)\n# tahmin degeri\ny_pred = knn_tuned.predict(X_test)\naccuracy_score(y_test, y_pred)\n\"\"\"\n# SVC (Support Vector for Classification)\n\"\"\"\n\"\"\"\n* Amac iki sinif arasindaki ayrimin(marjinin) optimum olmasini saglayacak hiper-duzlemi bulmaktir\n\n* Linear ve NonLinear SVM ler mevcut.\n\"\"\"\n# model ve nesne olusturma fit ile beraber yapalim\nfrom sklearn.svm import SVC\n\nsvm_model = SVC(kernel = \"linear\").fit(X_train, y_train)\nsvm_model\ny_pred = svm_model.predict(X_test)\naccuracy_score(y_test, y_pred)\n\"\"\"\n## MODEL TUNNING\n\"\"\"\n# C parametresi olusturulacak olan dogrunun veya ayrimin olusturulmasiyla ilgili bir kontrol etme imkani saglayan parametredir\n# C degeri 0 olamaz hata verir ondan 1 den baslasin\n\nsvc_params = {\"C\": np.arange(1,10)}\nsvc = SVC(kernel = \"linear\")\n\nsvc_cv_model = GridSearchCV(svc,svc_params, \n                            cv = 10, \n                            n_jobs = -1, \n                            verbose = 2 )\n\nsvc_cv_model.fit(X_train, y_train)\n# en iyi parametre degerleri\nprint(\"En iyi parametreler: \" + str(svc_cv_model.best_params_))\n# tuned edip fit leyelim\nsvc_tuned = SVC(kernel = \"linear\", C = 5).fit(X_train, y_train)\n# simdi gercek deger ile tahmin edilen degerin karsilastirma islemini yapalim\ny_pred = svc_tuned.predict(X_test)\naccuracy_score(y_test, y_pred)\n\"\"\"\n# Naive Bayes Model\n\n* Olasilik temelli bir modelleme teknigidir. Amac belirli bir ornegin her bir sinifa ait olma olasiliginin kosullu olasilik temelli hesaplanmasidir.\n\n* e-ticaret veya cok sinifli veri setlerinde gayet iyi calistigi gorulmustur. \n\n*Ornek aylik geliri 2000 olan bu kisi krediyi odeyebilir mi?\nbu tarz orneklerde gayet uygun bir modeldir.\n\"\"\"\n\"\"\"\n## MODEL, TAHMIN VE MODEL TUNNING\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nnb = GaussianNB()\nnb_model = nb.fit(X_train, y_train)\nnb_model\n# tahmin islemini yapalim\nnb_model.predict(X_test)[0:10]\ny_pred = nb_model.predict(X_test)\naccuracy_score(y_test, y_pred)\ncross_val_score(nb_model, X_test, y_test, cv = 10).mean()\n\"\"\"\n### As we can see between 4 models(Logistic Regresyon, KNN, SVC and Naive Bayes) SVC is most suitable model in Breast Cancer Wisconsin data. SVC model can explain accuracy score 98% of this data.\n\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c7b73dadc5ff16'}"}
{"id":"52244","text":"\"\"\"\n* Guy Kabiri\n* https:\/\/www.kaggle.com\/guykabiri\n\"\"\"\n\"\"\"\n# Intro\nIn this competition I will investigate the data of passengers who boarded the Titanic.  \nI will try to study the connection between the different features in this data in order to create a model which will be able to predict whether a passenger survived or not.  \nI will use two types of models with different features to find the best model for this data.\n* SGD - a GD-like linear regression algorithm.\n* MLP - an artificial nueral network.\n\"\"\"\n\"\"\"\n# Imports\n\"\"\"\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport sklearn\nfrom sklearn import metrics\nfrom sklearn import datasets\nfrom sklearn import pipeline\nfrom sklearn import linear_model\nfrom sklearn import preprocessing\nfrom sklearn import model_selection\nfrom sklearn import neural_network\n\"\"\"\n# Import The Data\n\"\"\"\ntrain_csv = pd.read_csv('..\/input\/titanic\/train.csv')\ntitanic_df = pd.DataFrame(train_csv)\ntest_csv = pd.read_csv('..\/input\/titanic\/test.csv')\ntest = pd.DataFrame(test_csv)\n\"\"\"\n# Explore The Data\n\nFirst of all, let's see the keys.\n\"\"\"\ndisplay(titanic_df.keys())\n\"\"\"\nUnderstanding the keys meaning:\n* `PassengareId` - Id of the passenger .\n* `Survived` - Whether the passenger survives or not.\n* `Pclass` - The ticket class (SES)\n* `Name` - Name of the passenger.\n* `Sex` - Gender of the passenger.\n* `Age` - Age of the passenger.\n* `SibSp` - Number of siblings and spouse.\n* `Parch` - Number of parents and children.\n* `Ticket` - Ticket number.\n* `Fare` - How much the passenger paid.\n* `Cabin` - Cabin of the passenger.\n* `Embarked` - Which port the passenger borded.\n\"\"\"\n\"\"\"\n## Variable Analysis\n* Categorical Variables: Survived, Sex, Cabin and Embarked.\n* Ordinal Variables: Pclass, SubSp and Parch\n* Numerical Variables: Age and Fare.\n\"\"\"\n\"\"\"\nNow let's observe the data and it's structure.\nIt contains 891 rows with 11 features and the target which means if a passenger survived or not.\n\"\"\"\nsurvived = titanic_df[\"Survived\"]\ntitanic_df = titanic_df.drop(\"Survived\", axis=1)\ntitanic_df.insert(0, \"Survived\", survived)\ndisplay(titanic_df)\ntitanic_df.info()\n\"\"\"\n## Handle Non-Numerical Variables and Missing Values\n\n\"\"\"\ntitanic_df.isna().sum()\n\"\"\"\n### Name Variable:\nThe name seem to be irrelevent to the chance of a passenger to survive, but we can use it to extract a passenger's title into a `Title` categorical variable.\nFirst let's see all the different titles the passengers have.\n\"\"\"\ntitanic_df[\"Title\"] = titanic_df[\"Name\"].str.extract(' ([A-Za-z]+)\\.', expand=False)\npd.crosstab(titanic_df[\"Title\"], titanic_df[\"Sex\"])\npd.crosstab(titanic_df.Title ,titanic_df.Sex).T.style.background_gradient() #Checking the Initials with the Sex\n\"\"\"\nThere are a lot of titles, some of them can be combined.\n* Combine all the rates titles into `Rare`.\n* Combine the variante of `Miss`.\n* Combine the variante of `Msr`.\n\"\"\"\ntitanic_df[\"Title\"] = titanic_df[\"Title\"].replace([\"Lady\", \"Countess\",\"Capt\", \"Col\",\\\n \t\"Don\", \"Dr\", \"Major\", \"Rev\", \"Sir\", \"Jonkheer\", \"Dona\"], \"Other\")\n\ntitanic_df[\"Title\"] = titanic_df[\"Title\"].replace(\"Mlle\", \"Miss\")\ntitanic_df[\"Title\"] = titanic_df[\"Title\"].replace(\"Ms\", \"Miss\")\ntitanic_df[\"Title\"] = titanic_df[\"Title\"].replace(\"Mme\", \"Mrs\")\n\npd.crosstab(titanic_df.Title ,titanic_df.Survived, values=titanic_df.Age, aggfunc='mean').T.style.background_gradient() #Checking the Initials with the Sex\nsns.barplot(x=\"Title\", y=\"Survived\", data=titanic_df)\n\"\"\"\nNow the `Title` variable can be converted into a categorical variable.\n\"\"\"\ntitanic_df[\"Title_cat\"] = titanic_df[\"Title\"].map({'Mr' : 0, 'Mrs' : 1, 'Miss' : 2, 'Master' : 3, 'Other' : 4})\ndisplay(titanic_df[[\"Title\", \"Title_cat\"]])\ntitanic_df[[\"Title\", \"Title_cat\"]].isna().any()\n\"\"\"\nNow let's perform this manipulation on the test as well.\n\"\"\"\ntest[\"Title\"] = test[\"Name\"].str.extract(' ([A-Za-z]+)\\.', expand=False)\n\ntest[\"Title\"] = test[\"Title\"].replace([\"Lady\", \"Countess\",\"Capt\", \"Col\",\\\n \t\"Don\", \"Dr\", \"Major\", \"Rev\", \"Sir\", \"Jonkheer\", \"Dona\"], \"Other\")\n\ntest[\"Title\"] = test[\"Title\"].replace(\"Mlle\", \"Miss\")\ntest[\"Title\"] = test[\"Title\"].replace(\"Ms\", \"Miss\")\ntest[\"Title\"] = test[\"Title\"].replace(\"Mme\", \"Mrs\")\n\ntest[\"Title_cat\"] = test[\"Title\"].map({'Mr' : 0, 'Mrs' : 1, 'Miss' : 2, 'Master' : 3, 'Other' : 4})\n\ntest[\"Title_cat\"].isna().any()\n\"\"\"\n### Embarked Variable:\n`Embarked` indicates in which port a passenger boarded the Titanic.  \nIt could be crutial to determine whether a passenger survived or not becuase it might indicate on a passenger's room location on the titanic.\n\"\"\"\nsns.barplot(x=\"Embarked\", y=\"Survived\", data=titanic_df)\n\"\"\"\nIt looks like there are some diffrences in surviving chances between the different `Embarked` locations.  \nThere are only 3 unique values, it will be converted into 3 binary variables.\nBut before we change the variavble into a numerical one, we need to fill the missing values, it can be filled with the most common value.\n\"\"\"\ntitanic_df[\"Embarked\"] = titanic_df[\"Embarked\"].fillna(titanic_df[\"Embarked\"].mode()[0])\ntitanic_df[\"Embarked_s\"] = titanic_df[\"Embarked\"].map({ 'S' : 1, 'C' : 0, 'Q' : 0, np.nan : 0}).astype(int)\ntitanic_df[\"Embarked_c\"] = titanic_df[\"Embarked\"].map({ 'S' : 0, 'C' : 1, 'Q' : 0, np.nan : 0}).astype(int)\ntitanic_df[\"Embarked_q\"] = titanic_df[\"Embarked\"].map({ 'S' : 0, 'C' : 0, 'Q' : 1, np.nan : 0}).astype(int)\n\ndisplay(titanic_df[[\"Embarked\", \"Embarked_s\", \"Embarked_c\", \"Embarked_q\"]])\ntitanic_df[\"Embarked\"].isna().any()\n\"\"\"\nThe test dataset does not miss any `Embarked` values, let's just convert it to 3 binary variables as well.\n\"\"\"\ntest[\"Embarked_s\"] = test[\"Embarked\"].map({ 'S' : 1, 'C' : 0, 'Q' : 0, np.nan : 0}).astype(int)\ntest[\"Embarked_c\"] = test[\"Embarked\"].map({ 'S' : 0, 'C' : 1, 'Q' : 0, np.nan : 0}).astype(int)\ntest[\"Embarked_q\"] = test[\"Embarked\"].map({ 'S' : 0, 'C' : 0, 'Q' : 1, np.nan : 0}).astype(int)\n\ntest[[\"Embarked_s\", \"Embarked_c\", \"Embarked_q\"]].isna().any()\n\"\"\"\n### Sex Variable:\nThe gender of a passenger might have a strong connection to surviving chances because rescures might help first to women.\n\n\"\"\"\nsns.barplot(x=\"Sex\", y=\"Survived\", data=titanic_df)\n\"\"\"\nAs predicted, female had much higher chance to survive.  \n`Sex` is a non-numerical column, we will convert into two binary variables `Male`, and `Female`.\n\"\"\"\ntitanic_df[\"Male\"] = 0\ntitanic_df[\"Female\"] = 0\ntitanic_df[\"Male\"] = titanic_df[\"Sex\"].map( {'female': 0, 'male': 1} ).astype(int)\ntitanic_df[\"Female\"] = titanic_df[\"Sex\"].map( {'male': 0, 'female': 1} ).astype(int)\ndisplay(titanic_df[[\"Sex\", \"Male\", \"Female\"]])\n\"\"\"\nConvert the test dataset to binary as well.\n\"\"\"\ntest[\"Male\"] = 0\ntest[\"Female\"] = 0\ntest[\"Male\"] = test[\"Sex\"].map( {'female': 0, 'male': 1} ).astype(int)\ntest[\"Female\"] = test[\"Sex\"].map( {'male': 0, 'female': 1} ).astype(int)\ntest[[\"Male\", \"Female\"]].isna().any()\n\"\"\"\n### Pclass Variable:\n`Pclass` indicates a passenger class, it indicates his room location and could affect his surviving chances.\n\"\"\"\ntemp = pd.crosstab(titanic_df.Pclass ,titanic_df.Survived, values=titanic_df.Survived, aggfunc='count').T.style.background_gradient() #Checking the Initials with the Sex\ndisplay(temp)\nsns.countplot('Pclass',data=titanic_df, hue='Survived')\n\"\"\"\nIt is clear that a passenger from 1st class and 2nd class has much more chances to survive compare to 3rd class passengers.\n\"\"\"\n\"\"\"\n### Age Variable:\n`Age` missing 177 value, not too much in terms of this data size, it can be filled with the median value of passengers with similar values, to decide which values, let's see the correlation between `Age` and the other features.\n\"\"\"\ncorr = abs(titanic_df.corr())    # get the data correlation\nplt.figure(figsize=(12,8))\nmask = np.triu(np.ones_like(corr, dtype=bool))\nsns.heatmap(corr, mask=mask, annot=True, cmap=plt.cm.Reds, vmin=0, vmax=1, linewidth=.5)\nplt.show()\nsns.catplot(y=\"Age\", x=\"Pclass\", hue=\"Survived\", kind=\"violin\", data=titanic_df)\n\"\"\"\nIt look like there is a dipendency between `Age`, `Pclass`, and `Title_cat`.\nLet's try to fill the emtpy `Age` values with the means of those 2 variables.\n\"\"\"\ndef convert_title(df):\n    means = df.groupby([\"Title_cat\", \"Pclass\"])[\"Age\"].mean()\n    for i in range(df[\"Title_cat\"].nunique()):\n     for j in range(means[i].shape[0]):\n            df.loc[ (df.Age.isnull()) & (df.Title_cat == i) & (df.Pclass == j +1 ), 'Age'] = means[i][j+1]\n            \nconvert_title(titanic_df)\nprint(titanic_df[\"Age\"].isna().any())            \nprint(titanic_df[\"Age\"])\n\"\"\"\nWe need to fill the missing `Age` values in the test dataset.\n\"\"\"\nconvert_title(test)\ntest.Age.isna().any()\n\"\"\"\n### Back to `Title`\nNow after done handling the `Age` feature, we can convert the `Title_cat` into seperate binary features.\n\"\"\"\nsns.catplot(x=\"Title\", kind=\"count\", palette=sns.color_palette(\"deep\"), data=titanic_df)\ndef convert_titles_binary(data):\n    data[\"Mr\"] = 0\n    data[\"Mrs\"] = 0\n    data[\"Miss\"] = 0\n    data[\"Master\"] = 0\n    data[\"Mr\"] = data[\"Title\"].map({'Mr' : 1, 'Mrs' : 0, 'Miss' : 0, 'Master' : 0, 'Other' : 0})\n    data[\"Mrs\"] = data[\"Title\"].map({'Mr' : 0, 'Mrs' : 1, 'Miss' : 0, 'Master' : 0, 'Other' : 0})\n    data[\"Miss\"] = data[\"Title\"].map({'Mr' : 0, 'Mrs' : 0, 'Miss' : 1, 'Master' : 0, 'Other' : 0})\n    data[\"Master\"] = data[\"Title\"].map({'Mr' : 0, 'Mrs' : 0, 'Miss' : 0, 'Master' : 1, 'Other' : 0})\n\nconvert_titles_binary(titanic_df)\nconvert_titles_binary(test)\n\ntitanic_df[[\"Mr\", \"Mrs\", \"Miss\", \"Master\"]].isna().any()\ntest[[\"Mr\", \"Mrs\", \"Miss\", \"Master\"]].isna().any()\n\"\"\"\n### Cabin Variable\n`Cabin` which indicates where a passenger was staying at the titanic, is missing 687 values out of 891, that's about 77% of missing values.\nFor now we will try to drop that variable from this model and will see if adding it later on will improve the results.\n\n\"\"\"\ntitanic_df.drop(\"Cabin\", axis=1, inplace=True)\nprint(titanic_df.isna().any())\n\ntest.drop(\"Cabin\", axis=1, inplace=True)\nprint(test.isna().any())\n\"\"\"\n## Feature Engeneering\n\"\"\"\n\"\"\"\n`Parch` and `SibSp` could be merged into one `FamilySize` variable.\n\"\"\"\ntitanic_df[\"FamilySize\"] = titanic_df[\"Parch\"] + titanic_df[\"SibSp\"] + 1\ntitanic_df[[\"FamilySize\", \"Survived\"]].groupby([\"FamilySize\"], as_index=False).mean().sort_values(by=\"Survived\", ascending=False)\n\"\"\"\nCreating the `FamilySize` variable for the test dataset as well.\n\"\"\"\ntest[\"FamilySize\"] = test[\"Parch\"] + test[\"SibSp\"] + 1\n\"\"\"\nWe can see that when a passenger has some relatives traveled with him, he had some better chances to survived.  \nWe can create another feature that might increase the model accuracy.  \n`IsAlone` feature will indicate whether a passenger was traveling alone or with relatives.\n\"\"\"\ntitanic_df['IsAlone'] = 0\ntitanic_df.loc[titanic_df['FamilySize'] == 1, 'IsAlone'] = 1\n\ntest['IsAlone'] = 0\ntest.loc[test['FamilySize'] == 1, 'IsAlone'] = 1\n\"\"\"\nWe can assume that as the age growth, the class of a passenger could growth too, lets see a graph to demonstrate.\n\"\"\"\nsns.regplot(x=\"Age\", y=\"Pclass\", data=titanic_df, logx=True)\n\"\"\"\nWe know the 1st class is better than 2nd class, and 2nd class is better than 3rd class.  \nIn this graph we can actually see that the more a passenger is older, his class is higher.\n\"\"\"\n\"\"\"\nAs observed before, it look like `Pclass`, and `Age` have some correlation between them, we may assume that the age of a passenger's may indicates which class he was travled at.  \nOlder people sometimes tend to have more money and it could indicate they traveled in higher class.  \nWe will try to create a new feature `AgePclass` as a multiplation between those two features.\n\"\"\"\ntitanic_df[\"AgePclass\"] = titanic_df[\"Age\"] * titanic_df[\"Pclass\"]\ntest[\"AgePclass\"] = test[\"Age\"] * test[\"Pclass\"]\ndef age_band(num):\n    for i in range(1, 100):\n        if num < 10*i :  return f'{(i-1) * 10} ~ {i*10}'\n\n        \ntitanic_df['age_band'] = titanic_df['Age'].apply(age_band)\ntitanic_age = titanic_df[['age_band', 'Survived']].groupby('age_band')['Survived'].value_counts().sort_index().unstack().fillna(0)\ntitanic_age['Survival rate'] = titanic_age[1] \/ (titanic_age[0] + titanic_age[1]) * 100\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 7))\n\n# ax2\ncolor_map = ['#d4dddd' for _ in range(9)]\ncolor_map[0] = color_map[8] = '#244747'\n\nax.bar(titanic_age['Survival rate'].index, titanic_age['Survival rate'], \n       color=color_map, width=0.55, \n       edgecolor='black', \n       linewidth=0.7)\n\n\n\nfor s in [\"top\",\"right\",\"left\"]:\n    ax.spines[s].set_visible(False)\n\n\n\nfor i in titanic_age['Survival rate'].index:\n    ax.annotate(f\"{titanic_age['Survival rate'][i]:.02f}%\", \n                   xy=(i, titanic_age['Survival rate'][i] + 2.3),\n                   va = 'center', ha='center',fontweight='light', \n                   color='#4a4a4a')\n\n\n# mean line + annotation\nmean = titanic_df['Survived'].mean() *100\nax.axhline(mean ,color='black', linewidth=0.4, linestyle='dashdot')\n    \n\n# Title & Subtitle    \nfig.text(0.06, 1, 'Age Band and Survival Rate', fontsize=15)\n\ngrid_y_ticks = np.arange(0, 101, 20)\nax.set_yticks(grid_y_ticks)\nax.grid(axis='y', linestyle='-', alpha=0.4)\n\nplt.tight_layout()\nplt.show()\n\"\"\"\nFrom this graph it looks like there are different surviving chances across the different age bands.  \nWe will create a new `AgeBand` feature.\n\"\"\"\ndef createAgeBand(dataset):\n    dataset.loc[ dataset['Age'] <= 10, 'AgeBand'] = 0\n    dataset.loc[(dataset['Age'] > 10) & (dataset['Age'] <= 20), 'AgeBand'] = 1\n    dataset.loc[(dataset['Age'] > 20) & (dataset['Age'] <= 30), 'AgeBand'] = 2\n    dataset.loc[(dataset['Age'] > 30) & (dataset['Age'] <= 40), 'AgeBand'] = 3\n    dataset.loc[(dataset['Age'] > 40) & (dataset['Age'] <= 50), 'AgeBand'] = 4\n    dataset.loc[(dataset['Age'] > 50) & (dataset['Age'] <= 60), 'AgeBand'] = 5\n    dataset.loc[(dataset['Age'] > 60) & (dataset['Age'] <= 70), 'AgeBand'] = 6\n    dataset.loc[(dataset['Age'] > 70) & (dataset['Age'] <= 80), 'AgeBand'] = 7\n    dataset.loc[ dataset['Age'] > 80, 'AgeBand'] = 8\n    \n\ncreateAgeBand(titanic_df)\ntitanic_df.AgeBand.isna().any()\nsns.barplot(x=\"AgeBand\", y=\"Survived\", palette=sns.color_palette(\"coolwarm\"), data=titanic_df)\ncreateAgeBand(test)\ntest.AgeBand.isna().any()\n\"\"\"\n## Train\n\"\"\"\nprint(titanic_df.isna().sum().any())\nprint(test.isna().sum().any())\n\"\"\"\n### SGD Train with `FamilySize` Featrure:\n\"\"\"\ndata_fs = titanic_df[[\"AgePclass\", \"Fare\", \"Mr\", \"Mrs\", \"Miss\", \"Master\", \"Embarked_s\", \"Embarked_c\", \"Embarked_q\", \"Male\", \"Female\", \"FamilySize\", \"Survived\"]]\nt_fs = data_fs[\"Survived\"]\nx_fs = data_fs.drop('Survived', axis=1)\n\nx_train_fs, x_test_fs, t_train_fs, t_test_fs = sklearn.model_selection.train_test_split(x_fs, t_fs, test_size=0.2, random_state=0)\nSGD_cls_fs = pipeline.make_pipeline(preprocessing.StandardScaler(), linear_model.SGDClassifier(loss='log', alpha=0, learning_rate='constant', eta0=0.01)).fit(x_train_fs, t_train_fs)\ny_train_prob_fs = SGD_cls_fs.predict_proba(x_train_fs)\ny_test_prob_fs = SGD_cls_fs.predict_proba(x_test_fs)\n\nacurSGD_fs_train = SGD_cls_fs.score(x_train_fs, t_train_fs)\nacurSGD_fs_valid = SGD_cls_fs.score(x_test_fs, t_test_fs)\nceSGD_fs_train = metrics.log_loss(t_train_fs, y_train_prob_fs)\nceSGD_fs_valid = metrics.log_loss(t_test_fs, y_test_prob_fs)\n\nprint('Accuracy score on train', acurSGD_fs_train)\nprint('Accuracy score on validation', acurSGD_fs_valid)\nprint()\nprint('CE on train', ceSGD_fs_train)\nprint('CE on test',ceSGD_fs_valid)\n\"\"\"\n### SGD Train with `IsAlone` Featrure:\n\"\"\"\ndata_ia = titanic_df[[\"AgePclass\", \"Fare\", \"Mr\", \"Mrs\", \"Miss\", \"Master\", \"Embarked_s\", \"Embarked_c\", \"Embarked_q\", \"Male\", \"Female\", \"IsAlone\", \"Survived\"]]\nt_ia = data_ia[\"Survived\"]\nx_ia = data_ia.drop('Survived', axis=1)\n\nx_train_ia, x_test_ia, t_train_ia, t_test_ia = sklearn.model_selection.train_test_split(x_ia, t_ia, test_size=0.2, random_state=0)\nSGD_cls_ia = pipeline.make_pipeline(preprocessing.StandardScaler(), linear_model.SGDClassifier(loss='log', alpha=0, learning_rate='constant', eta0=0.01)).fit(x_train_ia, t_train_ia)\ny_train_prob_ia = SGD_cls_ia.predict_proba(x_train_ia)\ny_test_prob_ia = SGD_cls_ia.predict_proba(x_test_ia)\nacurSGD_ia_train = SGD_cls_ia.score(x_train_ia, t_train_ia)\nacurSGD_ia_valid = SGD_cls_ia.score(x_test_ia, t_test_ia)\nceSGD_ia_train = metrics.log_loss(t_train_ia, y_train_prob_ia)\nceSGD_ia_valid = metrics.log_loss(t_test_ia, y_test_prob_ia)\n\nprint('Accuracy score on train', acurSGD_ia_train)\nprint('Accuracy score on validation', acurSGD_ia_valid)\nprint()\nprint('CE on train', ceSGD_ia_train)\nprint('CE on test',ceSGD_ia_valid)\n\"\"\"\nWe get better results with `FamilySize` feature and not with `IsAlone` so we will continue with it.\n\"\"\"\n\"\"\"\n### SGD Train with `AgeBand` Featrure:\n\"\"\"\ndata_ab = titanic_df[[\"AgePclass\", \"AgeBand\", \"Fare\", \"Mr\", \"Mrs\", \"Miss\", \"Master\", \"Embarked_s\", \"Embarked_c\", \"Embarked_q\", \"Male\", \"Female\", \"FamilySize\", \"Survived\"]]\nt_ab = data_ab[\"Survived\"]\nx_ab = data_ab.drop('Survived', axis=1)\n\nx_train_ab, x_test_ab, t_train_ab, t_test_ab = sklearn.model_selection.train_test_split(x_ab, t_ab, test_size=0.2, random_state=0)\nSGD_cls_ab = pipeline.make_pipeline(preprocessing.StandardScaler(), linear_model.SGDClassifier(loss='log', alpha=0, learning_rate='constant', eta0=0.01)).fit(x_train_ab, t_train_ab)\ny_train_prob_ab = SGD_cls_ab.predict_proba(x_train_ab)\ny_test_prob_ab = SGD_cls_ab.predict_proba(x_test_ab)\nacurSGD_ab_train = SGD_cls_ab.score(x_train_ab, t_train_ab)\nacurSGD_ab_valid = SGD_cls_ab.score(x_test_ab, t_test_ab)\nceSGD_ab_train = metrics.log_loss(t_train_ab, y_train_prob_ab)\nceSGD_ab_valid = metrics.log_loss(t_test_ab, y_test_prob_ab)\n\nprint('Accuracy score on train', acurSGD_ab_train)\nprint('Accuracy score on validation', acurSGD_ab_valid)\nprint()\nprint('CE on train', ceSGD_ab_train)\nprint('CE on test',ceSGD_ab_valid)\n\"\"\"\nWe can see that the accuracy is a little bit higher and the loss is a little bit smaller in this model.\n\"\"\"\n\"\"\"\n### MLP Train with `FamilySize` Featrure:\n\"\"\"\nMLP_cls_fs = neural_network.MLPClassifier(activation='logistic', solver='sgd', alpha=0, max_iter=10000).fit(x_train_fs, t_train_fs)\ny_train_prob_fs = MLP_cls_fs.predict_proba(x_train_fs)\ny_test_prob_fs = MLP_cls_fs.predict_proba(x_test_fs)\nacurMLP_fs_train =  MLP_cls_fs.score(x_train_fs, t_train_fs)\nacurMLP_fs_valid = MLP_cls_fs.score(x_test_fs, t_test_fs)\nceMLP_fs_train = metrics.log_loss(t_train_fs, y_train_prob_fs)\nceMLP_fs_valid = metrics.log_loss(t_test_fs, y_test_prob_fs)\n\nprint('Accuracy score on train', acurMLP_fs_train)\nprint('Accuracy score on validation', acurMLP_fs_valid)\nprint()\nprint('CE on train', ceMLP_fs_train)\nprint('CE on test',ceMLP_fs_valid)\n\"\"\"\n### MLP Train with `IsAlone` Featrure:\n\"\"\"\nMLP_cls_ia = neural_network.MLPClassifier(activation='logistic', solver='sgd', alpha=0, max_iter=10000).fit(x_train_ia, t_train_ia)\ny_train_prob_ia = MLP_cls_ia.predict_proba(x_train_ia)\ny_test_prob_ia = MLP_cls_ia.predict_proba(x_test_ia)\nacurMLP_ia_train =  MLP_cls_ia.score(x_train_ia, t_train_ia)\nacurMLP_ia_valid = MLP_cls_ia.score(x_test_ia, t_test_ia)\nceMLP_ia_train = metrics.log_loss(t_train_ia, y_train_prob_ia)\nceMLP_ia_valid = metrics.log_loss(t_test_ia, y_test_prob_ia)\n\nprint('Accuracy score on train', acurMLP_ia_train)\nprint('Accuracy score on validation', acurMLP_ia_valid)\nprint()\nprint('CE on train', ceMLP_ia_train)\nprint('CE on test',ceMLP_ia_valid)\n\"\"\"\n### MLP Train with `AgeBand` Featrure:\n\"\"\"\nMLP_cls_ab = neural_network.MLPClassifier(activation='logistic', solver='sgd', alpha=0, max_iter=10000).fit(x_train_ab, t_train_ab)\ny_train_prob_ab = MLP_cls_ab.predict_proba(x_train_ab)\ny_test_prob_ab = MLP_cls_ab.predict_proba(x_test_ab)\nacurMLP_ab_train =  MLP_cls_ab.score(x_train_ab, t_train_ab)\nacurMLP_ab_valid = MLP_cls_ab.score(x_test_ab, t_test_ab)\nceMLP_ab_train = metrics.log_loss(t_train_ab, y_train_prob_ab)\nceMLP_ab_valid = metrics.log_loss(t_test_ab, y_test_prob_ab)\n\nprint('Accuracy score on train', acurMLP_ab_train)\nprint('Accuracy score on validation', acurMLP_ab_valid)\nprint()\nprint('CE on train', ceMLP_ab_train)\nprint('CE on test',ceMLP_ab_valid)\n\"\"\"\n# Compare the Models\n\"\"\"\nprint([acurSGD_fs_train, acurSGD_ia_train, acurSGD_ab_train, acurMLP_fs_train, acurMLP_ia_train, acurMLP_ab_train])\nprint([acurSGD_fs_valid, acurSGD_ia_valid, acurSGD_ab_valid, acurMLP_fs_valid, acurMLP_ia_valid, acurMLP_ab_valid])\nprint([ceSGD_fs_train, ceSGD_ia_train, ceSGD_ab_train, ceMLP_fs_train, ceMLP_ia_train, ceMLP_ab_train])\nprint([ceSGD_fs_valid, ceSGD_ia_valid, ceSGD_ab_valid, ceMLP_fs_valid, ceMLP_ia_valid, ceMLP_ab_valid])\nnames = [\"SGD FamilySize\", \"SGD IsAlone\", \"SGD FamilySize-AgeBand\", \"MLP FamilySize\", \"MLP IsAlone\", \"MLP FamilySize-AgeBand\"]\ntrain_acur = [acurSGD_fs_train, acurSGD_ia_train, acurSGD_ab_train, acurMLP_fs_train, acurMLP_ia_train, acurMLP_ab_train]\nvalid_acur = [acurSGD_fs_valid, acurSGD_ia_valid, acurSGD_ab_valid, acurMLP_fs_valid, acurMLP_ia_valid, acurMLP_ab_valid]\ntrain_loss = [ceSGD_fs_train, ceSGD_ia_train, ceSGD_ab_train, ceMLP_fs_train, ceMLP_ia_train, ceMLP_ab_train]\nvalid_loss = [ceSGD_fs_valid, ceSGD_ia_valid, ceSGD_ab_valid, ceMLP_fs_valid, ceMLP_ia_valid, ceMLP_ab_valid]\n\ndf = pd.DataFrame(list(zip(names, train_acur, valid_acur, train_loss, valid_loss)), columns = ['Name', 'Train_accuracy', 'Validation_accuracy', 'Train_loss', 'Validation_loss'])\nsns.catplot(x=\"Train_accuracy\", y=\"Name\", hue=\"Name\", kind=\"bar\", palette=sns.color_palette(\"deep\"), data=df, height=5, aspect=4)\nsns.catplot(x=\"Train_loss\", y=\"Name\", hue=\"Name\", kind=\"bar\", palette=sns.color_palette(\"deep\"), data=df, height=5, aspect=4)\nsns.catplot(x=\"Validation_accuracy\", y=\"Name\", hue=\"Name\", kind=\"bar\", palette=sns.color_palette(\"deep\"), data=df, height=5, aspect=4)\nsns.catplot(x=\"Validation_loss\", y=\"Name\", hue=\"Name\", kind=\"bar\", palette=sns.color_palette(\"deep\"), data=df, height=5, aspect=4)\n\"\"\"\nWe can see that the best train results was with SGD with `AgeBand` feature.  \nThe best validation results was with SGD with `AgeBand` feature as well.  \nAlso, the smallest loss (train, and validation) was with SGD with `AgeBand` feature.  \nSo we will use this model with the test.\n\"\"\"\n\"\"\"\n# Test\n\"\"\"\n\"\"\"\nThe test dataset missing one value in `Fare` variable, we will fill it with the mean of passengers with the same `Pclass`, `Title_cat`.\n\"\"\"\ntest[\"Fare\"] = test[\"Fare\"].fillna(test[\"Fare\"].mean())\ntest.Fare.isna().any()\ntest_ac = test[[\"AgePclass\", \"AgeBand\", \"Fare\", \"Mr\", \"Mrs\", \"Miss\", \"Master\", \"Embarked_s\", \"Embarked_c\", \"Embarked_q\", \"Male\", \"Female\", \"FamilySize\"]]\n\ny_pred = SGD_cls_ab.predict(test_ac)\n\nsubmission = pd.DataFrame({\n        \"PassengerId\": test[\"PassengerId\"],\n        \"Survived\": y_pred\n    })\nsubmission.to_csv('submission.csv', index=False)\n\"\"\"\n# Score\n\n![](https:\/\/user-images.githubusercontent.com\/52006798\/99272182-2b9a3600-2830-11eb-9432-a078aad8da1c.jpg)\n![](https:\/\/user-images.githubusercontent.com\/52006798\/99245606-85890480-280c-11eb-8ac3-c0783006dacf.jpg)\n![](https:\/\/user-images.githubusercontent.com\/52006798\/99245667-a2bdd300-280c-11eb-8149-dcd446f4e8d5.jpg)\n\"\"\"\n\"\"\"\n# Links\n\n\n* Fill `Embarked` missing values with the most common values. [Suggested here](https:\/\/www.kaggle.com\/startupsci\/titanic-data-science-solutions#Completing-a-categorical-feature)\n\n* Create `Title` feature instead of `Name`. [Suggested here](https:\/\/www.kaggle.com\/startupsci\/titanic-data-science-solutions#Creating-new-feature-extracting-from-existing)\n\n* Drop `PassengerId`, `Cabin` and `Ticket`. [Suggested here](https:\/\/www.kaggle.com\/ldfreeman3\/a-data-science-framework-to-achieve-99-accuracy#3.22-Clean-Data)\n\n* Dropping `SibSp` and `Parch` in favor for `FamilySize` feature. [Suggested here](https:\/\/www.kaggle.com\/startupsci\/titanic-data-science-solutions#Create-new-feature-combining-existing-features)\n\n* Consider `isAlone` feature instead of `SibSp`, `Parch` and `FamilySize`. [Suggested here](https:\/\/www.kaggle.com\/startupsci\/titanic-data-science-solutions#Create-new-feature-combining-existing-features)\n\n* Consider change `Age` into an ordinal variable based on age ranges. [Suggested here](https:\/\/www.kaggle.com\/startupsci\/titanic-data-science-solutions#Create-new-feature-combining-existing-features)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '60263e7a88c656'}"}
{"id":"49371","text":"\"\"\"\n# Import all critical libraries\n\"\"\"\n#For working with dataframes and numbers\n\nimport pandas as pd\nimport numpy as np\n\n\n#For Exploratory data analysis\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\nimport seaborn as sns\n%matplotlib inline\n\n#Modelling and eveluation\nimport sklearn.model_selection as ms\n#from xgboost import XGBClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nimport sklearn.metrics as sklm\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import roc_curve,auc\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n#import datasets\ntrain = pd.read_csv(\"..\/input\/train_technidus_clf.csv\")\ntest = pd.read_csv(\"..\/input\/test_technidus_clf.csv\")\n\"\"\"\n# Exploratory data analysis\n\"\"\"\n\"\"\"\nIt is an approach of analysing data to summarise main characteristics often with visual methods.\n\"\"\"\n#Conduct mini data check\/analysis\n\ntest.shape\ntrain.head()\ntest.shape\n#Check data for missing values\n#train.isnull().sum()\ntrain.isnull().sum()\n#Check category split\n#train.BikeBuyer.value_counts()\ntrain.BikeBuyer.value_counts()\n\"\"\"\n#Conduct full EDA\n\nUnivariate analysis\n\nAt this stage, we explore variables one by one. Method to perform uni-variate analysis \nwill depend on whether the variable type\u00a0is categorical or\u00a0continuous\n\nContinuous Variables:-\u00a0In case of continuous variables, we need to understand the central tendency \nand spread of the variable. These are measured using various statistical metrics visualization methods as shown below\n\nCategorical Variables:- For categorical variables, we\u2019ll use frequency table to understand distribution \nof\u00a0each category. We can also read as percentage of values\u00a0under each category. \nIt can be be measured using two metrics, Count and Count% against each category. \nBar chart can be used as visualization.\n\"\"\"\n\"\"\"\nBivariate analysis\n\nBi-variate Analysis finds out the relationship between two variables. Here, we look for\u00a0association and disassociation between variables at a pre-defined significance level. We can perform bi-variate analysis for any combination of categorical and continuous variables. The combination can be: Categorical & Categorical, Categorical & Continuous and Continuous & Continuous. Different methods are used to tackle these combinations during analysis process.\n\nContinuous & Continuous: While doing bi-variate analysis between two continuous variables, we should look at scatter plot. It is a nifty way to\u00a0find out the relationship between two variables. The pattern of scatter plot indicates the relationship between variables. The relationship can be linear or non-linear.\n\nCategorical & Categorical:\u00a0To find the relationship between two categorical variables, we can use following methods:\n\nTwo-way table: We can start\u00a0analyzing the relationship by creating a two-way table of count and count%. The rows represents the category of one variable and the columns represent\u00a0the categories of the other variable. We show count or count% of observations available in each combination of row and column categories.\n\"\"\"\n#Univariate continuous- Histogram\ntrain[\"AveMonthSpend\"].plot.hist(color='blue',bins=50)\nplt.show()\n#Univariate categorical- Countplot(Barplot)\nf, ax = plt.subplots(figsize=(8, 4))\nsns.countplot(\"Occupation\", data=train)\n#Bivariate analysis \n#Continuous and categorical (Box plot)\nsns.boxplot('BikeBuyer','AveMonthSpend', data=train)\n#Bivariate analysis \n#Continuous and continuous\nplt.scatter('AveMonthSpend',\"YearlyIncome\", data = train)\n\"\"\"\n# Feature Engineering\n\"\"\"\n\"\"\"\n#Feature Engineering\n\nFeature engineering is the science (and art) of extracting more information from existing data. \nYou are not adding any new data here, but you are actually making the data you already have more useful.\n\nFeature engineering itself can be divided in 2 steps:\n* Variable transformation.\n* Variable \/ Feature creation.\n\n\"\"\"\n#Example is generating Age column from Birth date variable\ntrain.BirthDate.head(2)\ntrain['Birthdate_int'] = train.BirthDate.str[-4:]\ntrain  = train.dropna(subset=['Birthdate_int'])\ntrain['Birthdate_int'] = train['Birthdate_int'].astype(int)\ntrain['Birthdate_int'].head()\ntrain['today_date'] = 1998\ntrain['Age'] = train['today_date']-train['Birthdate_int']\ntrain['Age'].head()\n\"\"\"\n# Outlier treatment\n\"\"\"\n\"\"\"\n#Outlier treatment\n\nOutlier is a commonly used\u00a0terminology by analysts and data scientists as\u00a0it needs\u00a0close attention else \nit\u00a0can result in wildly wrong\u00a0estimations. Simply speaking,\u00a0Outlier is an observation that appears far away and \ndiverges from an overall pattern in a sample.\n\n\nMost commonly used method to detect outliers is visualization. We use various visualization methods, \nlike Box-plot, Histogram, Scatter Plot \n\nDeleting observations:\u00a0We delete outlier values if it is due to data entry error, data processing error or \noutlier observations are very small in numbers. We can also use trimming at both ends to remove outliers.\n\nTransforming and binning values:\u00a0Transforming variables can also eliminate outliers.\nNatural log of a value reduces the variation caused by extreme values. Binning is also a form of variable transformation. \n\nImputing:\u00a0Like\u00a0imputation\u00a0of missing values, we can also impute\u00a0outliers. \nWe can use mean, median, mode imputation methods. Before imputing values, we should analyse if it is natural outlier \nor artificial. \n\nTreat separately:\u00a0If there are significant number of outliers, we should treat them separately\u00a0in the statistical model. \n\"\"\"\n#Deletion\n#For example delete age greater than 90 years\ntrain['Age'] = train['Age']<90\n#Example of Binning\nbins = [0,25,45,55,100]\nlabels = [\"0-24\",\"25-44\", \"45-55\",\"56-100\"]\ntrain[\"Agebin\"] = pd.cut(train.Age,bins = bins,labels=labels)\n#train.Agebin.value_counts()\ntrain[['Age','Agebin']].head()\n\"\"\"\n# Missing value treatment\n\"\"\"\n\"\"\"\n#Missing value treatment\n\nDeletion:\u00a0Deletion methods are used when the nature of missing data is \u201cMissing completely at random\u201d else \nnon random missing values can bias the model output. \n\nMean\/ Mode\/ Median Imputation:\u00a0Imputation is a method\u00a0to fill in the missing values with estimated ones. \nSimilar case Imputation\n\nPrediction Model: \u00a0Prediction model is one of the sophisticated method\u00a0for handling missing data. \n\nKNN Imputation: In this method of imputation, the missing values of an\u00a0attribute\u00a0are imputed using the given number of attributes that are most similar to the attribute whose values are missing. \n\"\"\"\n#Deletion\n#Pairwise\n#train = train.dropna(axis=1,how='any')\n#listwise\n#train = train.dropna(axis=1,how='all')\n\n#Mean\/mode imputation\ntrain['Age'].fillna(train['Age'].mean(), inplace=True) \ntrain['Age'].fillna(train['Age'].mode()[0], inplace=True) \n\"\"\"\n# Feature Selection\n\"\"\"\n\"\"\"\n#Feature Selection\n\nFilter methods are generally used as a preprocessing step. \nThe selection of features is independent of any machine learning algorithms.\nInstead, features are selected on the basis of their scores in various statistical tests \nfor their correlation with the outcome variable. The correlation is a subjective term here\n\nForward Selection: Forward selection is an iterative method in which we start with having no feature in the model. \nIn each iteration, we keep adding the feature which best improves our model till \nan addition of a new variable does not improve\u00a0the performance of the model.\n\n\n\"\"\"\ncorr= train.corr()\n#corr\nf, ax = plt.subplots(figsize=(10, 5))\nsns.heatmap(corr,cmap='coolwarm',linewidths=2.0, annot=True)\n\"\"\"\n# Modelling\n\"\"\"\n#Convert selected variables to array which scikit learn recognises\nX = train[['NumberCarsOwned',\n          'NumberChildrenAtHome',\n          'YearlyIncome','CountryRegionName']]\ny = train['BikeBuyer']\nXb=test[['NumberCarsOwned',\n          'NumberChildrenAtHome',\n          'YearlyIncome','CountryRegionName']]\n#Convert categorical variables to numerical through one-hotencoding\nX=pd.get_dummies(X)\nXb=pd.get_dummies(Xb)\n\"\"\"\n# Validation\n\"\"\"\n\"\"\"\n#Holdout method\n\nTo avoid the resubstitution error, the data is split into two different datasets labeled as a training and a testing dataset. \nThis can be a 60\/40 or 70\/30 or 80\/20 split. This technique is called the hold-out validation technique. \nIn this case, there is a likelihood that uneven distribution of different classes of data is found in training and test dataset. To fix this, the training and test dataset is created with equal distribution of different classes of data. This process is called stratification.\n\n\"\"\"\n#Holdout 30%\nfrom sklearn.model_selection import train_test_split\nx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size =0.3)\n#Build various models\n#Logistic regression\nfrom sklearn.linear_model import LogisticRegression\nmodel=LogisticRegression()\n#model = LogisticRegression()\nmodel.fit(x_train, y_train)\n\n#Evaluate logistic regression\npred_cv = model.predict(x_cv)\nscore = accuracy_score(y_cv,pred_cv)\nprint('accuracy_score',score)\n#Build Random forest\nfrom sklearn.ensemble import RandomForestClassifier\nmodel1 = RandomForestClassifier(random_state=1, max_depth=110,n_estimators= 1400,class_weight=\"balanced\")\nmodel1.fit(X,y)\n#Evaluate RF\npred_cv = model.predict(x_cv)\nscore = accuracy_score(y_cv,pred_cv)\nprint('accuracy_score',score)\n#Save for submission\ntest['BikeBuyer']=model1.predict(Xb)\ntest['CustomerID']= test['CustomerID']\ntest['BikeBuyer'] = test['BikeBuyer'].astype(int)\ntest[['CustomerID','BikeBuyer']].head(10)\ntest[['CustomerID','BikeBuyer']].to_csv('perfrect_score2.csv',index= False)","meta":"{'source': 'AI4Code', 'id': '5ae66d85e8cdb9'}"}
{"id":"87873","text":"\"\"\"\n#According to Slava Pasedko @slavapasedko. Columns description\n\n1. \u0427\u0430\u0441\u0442\u044c (idk, really)\n2. \u0413\u043e\u0434 (year of the game)\n3. \u041a\u043e\u043c\u0430\u043d\u0434\u0430 (team - host)\n4. \u0421\u043e\u043f\u0435\u0440\u043d\u0438\u043a (team - guest)\n5. \u041c\u0438\u043d\u0443\u0442\u044b (time of the game)\n6. \u0421\u0445\u0435\u043c\u0430 (soccer scheme, 5-4-1 etc)\n7. \u0417\u0430\u0431\u0438\u0442\u043e (how much host team scored)\n8. \u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043e (how much their competitors scored)\n9. \u0423\u0434\u0430\u0440\u044b (hits to football goal)\n10. \u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440 (when hit was right in the direction)\n11. \u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 (passing the ball (times))\n12. \u0422\u043e\u0447\u043d\u044b\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 (when passing the ball was accurate)\n13. \u041d\u0430\u0432\u0435\u0441\u044b (soccer canopy)\n14. \u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b (when the canopy was accurate)\n15. \u0412\u043b\u0430\u0434\u0435\u043d\u0438\u0435 (how much time in percentage host team had the ball)\n16. xG (expected goals ) https:\/\/www.sports.ru\/tribuna\/blogs\/triumphator\/1565293.html\n17. PPDA (Passes Allowed Per Defensive Action) - soccer static metric which allows determining pressure intensity through game\n\"\"\"\n#codes from Rodrigo Lima  @rodrigolima82\nfrom IPython.display import Image\nImage(url = 'https:\/\/encrypted-tbn0.gstatic.com\/images?q=tbn%3AANd9GcRH1ZkhpgLMpW8mwLLLXs8IGaYaIRQSlTgyuN1luLQ0KFXqdp43',width=400,height=400)\n\"\"\"\nImage behance.net - Russian Premier League identity.\n\"\"\"\n# 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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Input data files are available in the \"..\/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# Any results you write to the current directory are saved as output.\nnRowsRead = 1000 # specify 'None' if want to read whole file\ndf = pd.read_csv('..\/input\/russian-premier-league\/repository\/ilikeevb--football-prediction-29a122c\/data\/RPL.csv', delimiter=';', encoding = \"cp1251\", nrows = nRowsRead)\ndf.dataframeName = 'RPL.csv'\nnRow, nCol = df.shape\nprint(f'There are {nRow} rows and {nCol} columns')\ndf.head()\ndf.dtypes\ndf[\"\u0413\u043e\u0434\"].plot.hist()\nplt.show()\ndf[\"\u0423\u0434\u0430\u0440\u044b\"].plot.hist()\nplt.show()\ndf[\"\u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043e\"].plot.hist()\nplt.show()\ndf[\"\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b\"].plot.box()\nplt.show()\ndf[\"\u041c\u0438\u043d\u0443\u0442\u044b\"].plot.box()\nplt.show()\nsns.pairplot(df, x_vars=['\u0417\u0430\u0431\u0438\u0442\u043e'], y_vars='\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438', markers=\"+\", size=4)\nplt.show()\ndfcorr=df.corr()\ndfcorr\nsns.heatmap(dfcorr,annot=True,cmap='winter')\nplt.show()\nfig, axes = plt.subplots(1, 1, figsize=(14, 6))\nsns.boxplot(x='\u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043e', y='\u041c\u0438\u043d\u0443\u0442\u044b', data=df, showfliers=False);\nfig, axes = plt.subplots(1, 1, figsize=(14, 6))\nsns.boxplot(x='\u0423\u0434\u0430\u0440\u044b', y='\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440', data=df, showfliers=False);\nfig, axes = plt.subplots(1, 1, figsize=(14, 6))\nsns.boxplot(x='\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b', y='\u041d\u0430\u0432\u0435\u0441\u044b', data=df, showfliers=False);\ng = sns.jointplot(x=\"\u0427\u0430\u0441\u0442\u044c\", y=\"\u041c\u0438\u043d\u0443\u0442\u044b\", data=df, kind=\"kde\", color=\"m\")\ng.plot_joint(plt.scatter, c=\"w\", s=30, linewidth=1, marker=\"+\")\ng.ax_joint.collections[0].set_alpha(0)\ng.set_axis_labels(\"$\u0427\u0430\u0441\u0442\u044c$\", \"$\u041c\u0438\u043d\u0443\u0442\u044b$\");\n\"\"\"\n# codes from Binu https:\/\/www.kaggle.com\/biphili\/seaborn-matplotlib-plot-to-visualize-iris-data\n# codes from ShivaSandeep https:\/\/www.kaggle.com\/shivasandeep\/advertising-data\n\"\"\"\nimport matplotlib.style\n\nimport matplotlib as mpl\n\nmpl.style.use('classic')\nsns.jointplot(df['\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b'],df['\u041d\u0430\u0432\u0435\u0441\u044b'],data=df,kind='scatter')\nsns.jointplot(df['\u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043e'],df['\u041c\u0438\u043d\u0443\u0442\u044b'],data=df,kind='scatter')\nsns.jointplot(df['\u0417\u0430\u0431\u0438\u0442\u043e'],df['\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438'],data=df,kind='kde',space=0,color='g')\nfig=sns.jointplot(x='\u0413\u043e\u0434',y='\u041d\u0430\u0432\u0435\u0441\u044b',kind='hex',data=df)\ng = (sns.jointplot(\"\u0423\u0434\u0430\u0440\u044b\", \"\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440\",data=df, color=\"r\").plot_joint(sns.kdeplot, zorder=0, n_levels=6))\nax= sns.boxplot(x=\"\u041c\u0438\u043d\u0443\u0442\u044b\", y=\"\u041d\u0430\u0432\u0435\u0441\u044b\", data=df)\nax= sns.stripplot(x=\"\u041c\u0438\u043d\u0443\u0442\u044b\", y=\"\u041d\u0430\u0432\u0435\u0441\u044b\", data=df, jitter=True, edgecolor=\"gray\")\n\nboxtwo = ax.artists[2]\nboxtwo.set_facecolor('yellow')\nboxtwo.set_edgecolor('black')\nboxthree=ax.artists[1]\nboxthree.set_facecolor('red')\nboxthree.set_edgecolor('black')\nboxthree=ax.artists[0]\nboxthree.set_facecolor('green')\nboxthree.set_edgecolor('black')\n\nplt.show()\nfig=plt.gcf()\nfig.set_size_inches(10,7)\nfig=sns.violinplot(x='\u0427\u0430\u0441\u0442\u044c',y='\u041f\u0440\u043e\u043f\u0443\u0449\u0435\u043d\u043e',data=df)\nplt.figure(figsize=(15,10))\nplt.subplot(2,2,1)\nsns.violinplot(x='\u0423\u0434\u0430\u0440\u044b',y='\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440',data=df)\nplt.subplot(2,2,2)\nsns.violinplot(x='\u0423\u0434\u0430\u0440\u044b',y='\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440',data=df)\nplt.subplot(2,2,3)\nsns.violinplot(x='\u0423\u0434\u0430\u0440\u044b',y='\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440',data=df)\nplt.subplot(2,2,4)\nsns.violinplot(x='\u0423\u0434\u0430\u0440\u044b',y='\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440',data=df)\nsns.set(style=\"darkgrid\")\nfig=plt.gcf()\nfig.set_size_inches(10,7)\nfig = sns.swarmplot(x=\"\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438\", y=\"\u0422\u043e\u0447\u043d\u044b\u0435 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0438\", data=df)\nsns.set(style=\"whitegrid\")\nfig=plt.gcf()\nfig.set_size_inches(10,7)\nax = sns.violinplot(x=\"\u041d\u0430\u0432\u0435\u0441\u044b\", y=\"\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b\", data=df, inner=None)\nax = sns.swarmplot(x=\"\u041d\u0430\u0432\u0435\u0441\u044b\", y=\"\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b\", data=df,color=\"white\", edgecolor=\"black\")\nfig=sns.lmplot(x=\"\u0423\u0434\u0430\u0440\u044b\", y=\"\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440\",data=df)\n# venn2\nfrom matplotlib_venn import venn2\n\u041c\u0438\u043d\u0443\u0442\u044b = df.iloc[:,0]\n\u0417\u0430\u0431\u0438\u0442\u043e = df.iloc[:,1]\n\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438 = df.iloc[:,2]\n\u041d\u0430\u0432\u0435\u0441\u044b = df.iloc[:,3]\n# First way to call the 2 group Venn diagram\nvenn2(subsets = (len(\u041c\u0438\u043d\u0443\u0442\u044b)-15, len(\u0417\u0430\u0431\u0438\u0442\u043e)-15, 15), set_labels = ('\u041c\u0438\u043d\u0443\u0442\u044b', '\u0417\u0430\u0431\u0438\u0442\u043e'))\nplt.show()\n# donut plot\nfeature_names = \"\u041c\u0438\u043d\u0443\u0442\u044b\",\"\u0417\u0430\u0431\u0438\u0442\u043e\",\"\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438\"\nfeature_size = [len(\u041c\u0438\u043d\u0443\u0442\u044b),len(\u0417\u0430\u0431\u0438\u0442\u043e),len(\u041f\u0435\u0440\u0435\u0434\u0430\u0447\u0438)]\n# create a circle for the center of plot\ncircle = plt.Circle((0,0),0.2,color = \"white\")\nplt.pie(feature_size, labels = feature_names, colors = [\"red\",\"green\",\"blue\",\"cyan\"] )\np = plt.gcf()\np.gca().add_artist(circle)\nplt.title(\"Number of Each Feature\")\nplt.show()\n\"\"\"\nArea plot gives us a visual representation of Various dimensions of Russian 1er League.\n\"\"\"\ndf.plot.area(y=['\u0423\u0434\u0430\u0440\u044b','\u0423\u0434\u0430\u0440\u044b \u0432 \u0441\u0442\u0432\u043e\u0440','\u041d\u0430\u0432\u0435\u0441\u044b','\u0422\u043e\u0447\u043d\u044b\u0435 \u043d\u0430\u0432\u0435\u0441\u044b'],alpha=0.4,figsize=(12, 6));\n#word cloud\nfrom wordcloud import WordCloud, ImageColorGenerator\ntext = \" \".join(str(each) for each in df.\u041f\u043e\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044c)\n# Create and generate a word cloud image:\nwordcloud = WordCloud(max_words=200,colormap='Set3', background_color=\"black\").generate(text)\nplt.figure(figsize=(10,6))\nplt.figure(figsize=(15,10))\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='Bilinear')\nplt.axis(\"off\")\nplt.figure(1,figsize=(12, 12))\nplt.show()\n#word cloud\nfrom wordcloud import WordCloud, ImageColorGenerator\ntext = \" \".join(str(each) for each in df.\u041f\u0440\u043e\u0438\u0433\u0440\u0430\u0432\u0448\u0438\u0439)\n# Create and generate a word cloud image:\nwordcloud = WordCloud(max_words=200,colormap='Set3', background_color=\"green\").generate(text)\nplt.figure(figsize=(10,6))\nplt.figure(figsize=(15,10))\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='Bilinear')\nplt.axis(\"off\")\nplt.figure(1,figsize=(12, 12))\nplt.show()\nnRowsRead = 1000 # specify 'None' if want to read whole file\ndf1 = pd.read_csv('..\/input\/russian-premier-league\/data\/RPL.csv', delimiter=';', encoding = \"cp1251\", nrows = nRowsRead)\ndf1.dataframeName = 'RPL.csv'\nnRow, nCol = df.shape\nprint(f'There are {nRow} rows and {nCol} columns')\ndf1.head()\n#word cloud\nfrom wordcloud import WordCloud, ImageColorGenerator\ntext = \" \".join(str(each) for each in df1.\u0421\u043e\u043f\u0435\u0440\u043d\u0438\u043a)\n# Create and generate a word cloud image:\nwordcloud = WordCloud(max_words=200,colormap='Set3', background_color=\"blue\").generate(text)\nplt.figure(figsize=(10,6))\nplt.figure(figsize=(15,10))\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='Bilinear')\nplt.axis(\"off\")\nplt.figure(1,figsize=(12, 12))\nplt.show()\n\"\"\"\nKaggle Notebook Runner:Mar\u00edlia Prata @mpwolke\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'a124b8ec40ffb2'}"}
{"id":"60870","text":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\nimport os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\ndf=pd.read_csv(\"\/kaggle\/input\/covid-world-vaccination-progress\/country_vaccinations.csv\")\n# df.head()\ndf.info()\ndf.memory_usage().sum()\/pow(2,10)\n\n\"\"\"\n# Data preparation and summary\n\"\"\"\n\"\"\"\nClean data\n* remove rows where `daily_vaccinations` are NaN\n\"\"\"\nprint( df.shape)\noriginal_rows = df.shape[0]\n# df[pd.isnull(df.daily_vaccinations)]\ndf = df.dropna(subset=['daily_vaccinations'])\ndeleted_rows =  original_rows - df.shape[0]\nprint( \"deleted \" + str(deleted_rows\/original_rows*100)+\"% data\" )\n\"\"\"\n## List of vaccines\n\"\"\"\ndef flat_unique_elements(array_of_array):\n    vaccine_list = []\n    for childArray in array_of_array:\n        for child in childArray.split(\",\"):\n            if child.strip() not in vaccine_list:\n                vaccine_list.append(child.strip())\n    return vaccine_list\n\nvaccines = flat_unique_elements(df['vaccines'].unique())\n\nprint(\"list of all vaccines  -\\n\", vaccines)\n\"\"\"\n## List of vaccines and countries who have started its vaccination\n\n     vaccine    country\n     \n     vaccine 1  country 1, 3\n     vaccine 2  country 1, 4\n\"\"\"\nvaccine_country_list = pd.DataFrame(columns = ['vaccines','country'])\ndf_vaccine_country = df[[\"country\", \"vaccines\"]].drop_duplicates()\n# for vaccine in vaccines:\nfor vaccine in vaccines:\n    c = df_vaccine_country[df_vaccine_country.vaccines.str.contains(vaccine)]\n    d = df_vaccine_country[df_vaccine_country.vaccines.map(lambda p : vaccine in p)]\n    a = flat_unique_elements(c.country)\n    s = \",\".join(x for x in a)\n    vaccine_country_list = vaccine_country_list.append({'vaccines': vaccine, 'country': s}, ignore_index=True)\n\nprint(vaccine_country_list)\n\"\"\"\n## Find out which vaccines are used by a country\n\n    country     vaccines\n\n    country 1   vaccine 1, 2, 3\n    country 1   vaccine 1, 2, 3\n\"\"\"\ncountry_vaccines = df[['country','vaccines']].drop_duplicates()\nall_country = df['country'].unique()\n\ncountry_vaccine = pd.DataFrame(columns = ['country','vaccines'])\n\nif(all_country.size==country_vaccines.shape[0]):\n    country_vaccine = country_vaccines\nelse:\n    for country in all_country:\n        vacciness= country_vaccines[ country_vaccines.country == country ]\n        a= \",\".join( str(x) for x in flat_unique_elements(vacciness.vaccines) )\n        country_vaccine = country_vaccine.append({'country': country , 'vaccines': str(a) }, ignore_index=True)\n\nprint(country_vaccine)\n\"\"\"\n# Task 1\n\"\"\"\n\"\"\"\n##  What vaccines are used and in which countries?\n\"\"\"\nvaccine_country_list\n\"\"\"\n\n## Q2. What country is vaccinated more people?\n\"\"\"\nmost_vaccinated_country = df.loc[df.total_vaccinations.idxmax()]\nmost_vaccinated_country\n\"\"\"\n# Visualization\n\"\"\"\n\"\"\"\n## Plot indias vaccine progress\n\"\"\"\n\nrequired_columns = ['country', 'date', 'total_vaccinations', 'people_vaccinated', 'people_fully_vaccinated', 'vaccines']\n\nindian_vaccine_data= df.loc[df['country']==\"India\",required_columns]\nprint(indian_vaccine_data.head())\n# indian_vaccine_data.plot( indian_vaccine_data['date'], indian_vaccine_data['total_vaccinations'])\nindian_vaccine_data.plot()\n\"\"\"\n##  Number of days of vaccination campaingn\n\"\"\"\ncountry_days_of_vaccination =df.country.where(df.people_vaccinated>0).value_counts()\ncountry_days_of_vaccination.plot()","meta":"{'source': 'AI4Code', 'id': '70475ddd4a758f'}"}
{"id":"87801","text":"import os\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn import metrics\nimport sys\nif not sys.warnoptions:\n    import warnings\n    warnings.simplefilter(\"ignore\")\nimport plotly as py\nimport plotly.graph_objs as go\npy.offline.init_notebook_mode(connected = True)\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\nimport plotly.figure_factory as ff\n\"\"\"\n# REGRESSION\n\"\"\"\ndiamonds = pd.read_csv(\"\/kaggle\/input\/diamonds\/diamonds.csv\")\n\ndiamonds.info()\nsns.lmplot(y=\"carat\", x=\"price\", hue=\"clarity\", data= diamonds, fit_reg= False)\nsns.lmplot(y=\"carat\", x=\"price\", hue=\"cut\", data= diamonds, fit_reg= False)\nsns.set(style = \"whitegrid\", font_scale = 1.5)\n\nf, axes = plt.subplots(3, figsize = (8,16))\n\nsns.countplot(y = \"clarity\", data = diamonds, ax = axes[0])\n\nsns.countplot(y = \"color\", data = diamonds, ax = axes[1])\n\nsns.countplot(y = \"cut\", data = diamonds, ax = axes[2])\n\nplt.tight_layout()\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder()\ncut = diamonds.iloc[:,1:2]\ncolor = diamonds.iloc[:,2:3]\nclarity = diamonds.iloc[:,3:4]\ncut = ohe.fit_transform(cut).toarray()\ncolor = ohe.fit_transform(color).toarray()\nclarity = ohe.fit_transform(clarity).toarray()\n\ndiamonds.drop(columns = ['cut', 'color', 'clarity'], inplace = True)\n\ncut = pd.DataFrame(cut)\ncolor = pd.DataFrame(color)\nclarity = pd.DataFrame(clarity)\n\ndiamonds = pd.concat([diamonds, cut, color, clarity], axis = 1)\n\nX = diamonds.drop(columns = 'price').values\nY = diamonds.iloc[:,3:4].values\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test,y_train,y_test = train_test_split(X, Y,test_size=0.2, random_state=0)\n\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(x_train)\nX_test = sc.fit_transform(x_test)\n\"\"\"\n# OLS Regression Results\n\"\"\"\nimport statsmodels.api as sm \n\nX_l = diamonds.iloc[:,[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n].values\nr_ols = sm.OLS(endog = diamonds.iloc[:,-1:], exog =X_l).fit()\n\nprint(r_ols.summary())\n\"\"\"\n**Significance Level: 0.05 we do not screen because there is no column exceeding this value.**\n\"\"\"\n\"\"\"\n## Linear Regression\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(x_train,y_train)\ny_pred_linReg = lin_reg.predict(x_test)\n\nprint(r2_score(y_test, y_pred_linReg))\n\nprint('coef', lin_reg.coef_,'\\n\\n')\n\nprint('intercept', lin_reg.intercept_)\n\"\"\"\n## Polynomial Regression\n\"\"\"\n\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree = 1) \nx_poly = poly_reg.fit_transform(x_train) \nx_poly2 = poly_reg.fit_transform(x_test) \nlin_reg = LinearRegression()\nlin_reg.fit(x_poly, y_train)\ny_pred_poly = lin_reg.predict(x_poly2)\n\nprint(r2_score(y_test, y_pred_poly))\n\"\"\"\n## Support Vector Regression\n\"\"\"\nfrom sklearn.svm import SVR\nsvr_reg = SVR(kernel = 'linear')\nsvr_reg.fit(X_train, y_train)\ny_pred_svr = svr_reg.predict(X_test)\n\nprint(r2_score(y_test, y_pred_svr))\n\"\"\"\nKernel trick: 'rbf', 'poly', 'linear', 'sigmoid', 'precomputed'\n\"\"\"\n\"\"\"\n## Decision Tree\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\ndt_reg = DecisionTreeRegressor(random_state = 0)\ndt_reg.fit(X_train,y_train)\ny_pred_dt = dt_reg.predict(X_test)\n\nprint(r2_score(y_test, y_pred_dt))\n\"\"\"\n## Random Forest\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\nrf_reg = RandomForestRegressor(random_state = 0, n_estimators = 100)\nrf_reg.fit(X_train, y_train)\ny_pred_rf = rf_reg.predict(X_test)\n\nprint(r2_score(y_test, y_pred_rf))\n\"\"\"\n## XGBRegressor\n\"\"\"\nfrom xgboost import XGBRegressor\nxgb = XGBRegressor(n_estimators = 100)\nxgb.fit(x_train, y_train)\ny_pred_xgb = xgb.predict(x_test)\n\nprint(r2_score(y_test, y_pred_xgb))\n\"\"\"\n# CLASSIFICATION\n\"\"\"\niris = sns.load_dataset('iris')\niris.head()\niris.info()\nfor n in range(0,150):\n    if iris['species'][n] == 'setosa':\n        plt.scatter(iris['sepal_length'][n], iris['sepal_width'][n], color = 'red')\n        plt.xlabel('sepal_length')\n        plt.ylabel('sepal_width')\n    elif iris['species'][n] == 'versicolor':\n        plt.scatter(iris['sepal_length'][n], iris['sepal_width'][n], color = 'blue')\n        plt.xlabel('sepal_length')\n        plt.ylabel('sepal_width')\n    elif iris['species'][n] == 'virginica':\n        plt.scatter(iris['sepal_length'][n], iris['sepal_width'][n], color = 'green')\n        plt.xlabel('sepal_length')\n        plt.ylabel('sepal_width')\nsns.lmplot(x = 'sepal_length', y = 'sepal_width', data = iris, hue = 'species', col = 'species')\n\"\"\"\n## Preprocessing\n\"\"\"\nX = iris.iloc[:,:4].values\ny = iris.iloc[:,4:5].values\n\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 0)\n\n\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(x_train)\nX_test = sc.fit_transform(x_test)\n\"\"\"\n## Modelling\n\"\"\"\ndef model_evaluate(model, test):\n    y_pred = model.predict(test)\n    print(classification_report(y_test, y_pred))\n    cm = confusion_matrix(y_test, y_pred)\n\n    categories = ['Setosa', 'Versicolor', 'Virginica']\n    \n    sns.heatmap(cm, cmap = 'Blues', fmt = '', annot = True,\n                xticklabels = categories, yticklabels = categories)\n\n    plt.xlabel(\"Predicted values\", fontdict = {'size':14}, labelpad = 10)\n    plt.ylabel(\"Actual values\"   , fontdict = {'size':14}, labelpad = 10)\n    plt.title (\"Confusion Matrix\", fontdict = {'size':18}, pad = 20)\n\"\"\"\n## Logistic Regression\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression()\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## Support Vector Classifier\n\"\"\"\nfrom sklearn.svm import SVC\nmodel = SVC(kernel = 'linear') #kernel = poly, rbf, precomputed\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## Naive Bayes\n\n* **Gaussian Naive Bayes**\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nmodel = GaussianNB()\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n* **Multinomial Naive Bayes**\n\"\"\"\nfrom sklearn.naive_bayes import MultinomialNB\nmodel = MultinomialNB()\nmodel.fit(x_train, y_train)\n\nmodel_evaluate(model, x_test)\n\"\"\"\n* **Complement Naive Bayes**\n\"\"\"\nfrom sklearn.naive_bayes import ComplementNB\nmodel = ComplementNB()\nmodel.fit(x_train, y_train)\n\nmodel_evaluate(model, x_test)\n\"\"\"\n* **Bernoulli Naive Bayes**\n\"\"\"\nfrom sklearn.naive_bayes import BernoulliNB\nmodel = BernoulliNB()\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n* **Categorical Naive Bayes**\n\"\"\"\nfrom sklearn.naive_bayes import CategoricalNB\nmodel = CategoricalNB()\nmodel.fit(x_train, y_train)\n\nmodel_evaluate(model, x_test)\n\"\"\"\n## KNeighbors Classifier\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nmodel = KNeighborsClassifier(n_neighbors = 3, metric = 'minkowski')\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## Decision Tree Classifier\n\"\"\"\nfrom sklearn.tree import DecisionTreeClassifier\nmodel = DecisionTreeClassifier(random_state = 0)\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## Random Forest Classifier\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(n_estimators = 10, criterion = 'entropy')\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## AdaBoost\n\"\"\"\nfrom sklearn.ensemble import AdaBoostClassifier\nmodel = AdaBoostClassifier(n_estimators = 50)\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n## Other\n\n* **XGBClassifier**\n\"\"\"\nfrom xgboost import XGBClassifier\nmodel = XGBClassifier(n_estimators = 100)\nmodel.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n* **ExplainableBoostingClassifier**\n\"\"\"\n!pip install interpret\nfrom interpret.glassbox import ExplainableBoostingClassifier\nebm = ExplainableBoostingClassifier()\nebm.fit(X_train, y_train)\n\nmodel_evaluate(model, X_test)\n\"\"\"\n# CLUSTERING\n\"\"\"\nmall_customers = pd.read_csv('\/kaggle\/input\/customer-segmentation-tutorial-in-python\/Mall_Customers.csv')\nmall_customers.head()\nmall_customers.info()\nmall_customers.describe()\nlab = mall_customers[\"Gender\"].value_counts().keys().tolist()\nval = mall_customers[\"Gender\"].value_counts().values.tolist()\n\ntrace = go.Pie(labels = lab ,\n               values = val ,\n               marker = dict(colors =  [ 'royalblue' ,'lime'],\n                             line = dict(color = \"white\",\n                                         width =  1.3)\n                            ),\n               rotation = 20,\n               hoverinfo = \"label+value+text\",\n               hole = .5\n              )\nlayout = go.Layout(dict(title = \"Customer attrition in data\",\n                        plot_bgcolor  = \"rgb(243,243,243)\",\n                        paper_bgcolor = \"rgb(243,243,243)\",\n                       )\n                  )\n\ndata = [trace]\nfig = go.Figure(data = data, layout = layout)\npy.iplot(fig)\nsns.set(style=\"darkgrid\",font_scale=1.5)\nf, axes = plt.subplots(1,3,figsize=(20,8))\nsns.distplot(mall_customers[\"Age\"], ax = axes[0], color = 'y')     \nsns.distplot(mall_customers[\"Annual Income (k$)\"], ax = axes[1], color = 'g')\nsns.distplot(mall_customers[\"Spending Score (1-100)\"],ax = axes[2], color = 'r')\nplt.tight_layout()\ndz=ff.create_table(mall_customers.groupby('Gender').mean())\npy.iplot(dz)\nplt.figure(figsize=(8,4))\nsns.heatmap(mall_customers.corr(),annot=True,cmap=sns.cubehelix_palette(light=1, as_cmap=True),fmt='.2f',linewidths=2)\nplt.show()\nx = mall_customers.iloc[:,2:]\nprint(x.head())\nx = x.values\nkMeans = KMeans(n_clusters = 3, init = 'k-means++')\ny_pred = kMeans.fit_predict(x)\nprint('Pred:\\n', y_pred)\nprint('\\n\\ninertia: ', kMeans.inertia_, '\\n\\nclusters centers:\\n', kMeans.cluster_centers_)\nresult = []\nfor i in range(1, 12):\n    kMeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 123)\n    kMeans.fit(x)        \n    result.append(kMeans.inertia_)\n\n\nplt.plot(range(1,12), result)\nplt.title('WCSS')\nplt.show()\nkMeans = KMeans(n_clusters = 6, init = 'k-means++') \ny_pred_kMeans = kMeans.fit_predict(x)\nprint('Pred:\\n', y_pred_kMeans)\nprint('\\n\\ninertia: ', kMeans.inertia_, '\\n\\nclusters centers:\\n', kMeans.cluster_centers_)\n\"\"\"\n## Hierarchical Clustering\n\"\"\"\nagglomerative = AgglomerativeClustering(n_clusters = 6, affinity = 'euclidean', linkage = 'ward')\ny_pred_agg = agglomerative.fit_predict(x)\nprint('Pred:\\n', y_pred_agg)\nimport scipy.cluster.hierarchy as sch\ndendrogram = sch.dendrogram(sch.linkage(x, method = 'ward'))\nplt.show()\nf, (ax1, ax2) = plt.subplots(1, 2, sharey='col', num = 10, figsize = (15,5))\n\nax1.scatter( x = 'Annual Income (k$)' ,y = 'Spending Score (1-100)' , data = mall_customers , c = y_pred_kMeans,s = 100)\nax1.title.set_text('KMeans')\n\nax2.scatter( x = 'Annual Income (k$)' ,y = 'Spending Score (1-100)' , data = mall_customers , c = y_pred_agg,s = 100)\nax2.title.set_text('Agglomerative')\nf.show()\n\"\"\"\n**throwing the age column**\n\"\"\"\nx = mall_customers.iloc[:,3:].values\n\nkMeans = KMeans(n_clusters = 6, init = 'k-means++') \ny_pred_kMeans = kMeans.fit_predict(x)\nprint('Pred:\\n', y_pred_kMeans)\nprint('\\n\\ninertia: ', kMeans.inertia_, '\\n\\nclusters centers:\\n', kMeans.cluster_centers_)\n\nresult = []\nfor i in range(1, 14):\n    kMeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 123)\n    kMeans.fit(x)        \n    result.append(kMeans.inertia_)\n\n\nplt.plot(range(1,14), result)\nplt.title('WCSS')\nplt.show()\nprint('K-Means')\nkMeans = KMeans(n_clusters = 5, init = 'k-means++') \ny_pred_kMeans = kMeans.fit_predict(x)\nprint('Pred:\\n', y_pred_kMeans)\nprint('\\n\\ninertia: ', kMeans.inertia_, '\\n\\nclusters centers:\\n', kMeans.cluster_centers_)\n\nprint('\\n\\nAgglomerative')\nagglomerative = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')\ny_pred_agg = agglomerative.fit_predict(x)\nprint('Pred:\\n', y_pred_agg)\nf, (ax1, ax2) = plt.subplots(1, 2, sharey='col', num = 10, figsize = (15,5))\n\nax1.scatter( x = 'Annual Income (k$)' ,y = 'Spending Score (1-100)' , data = mall_customers , c = y_pred_kMeans,s = 100)\nax1.title.set_text('K-Means')\nax2.scatter( x = 'Annual Income (k$)' ,y = 'Spending Score (1-100)' , data = mall_customers , c = y_pred_agg,s = 100)\nax2.title.set_text('Agglomerative')\nf.show()\n","meta":"{'source': 'AI4Code', 'id': 'a101c009606fa1'}"}
{"id":"14407","text":"\"\"\"\n## Import Package\n\"\"\"\nimport pandas as pd\nimport tensorflow as tf\n\"\"\"\n## Create CSV File\n\"\"\"\nwith open(\"data.csv\", 'w') as f:\n    \n    f.write(\"NumRooms,Type,Price\\n\") # column names in csv\n    f.write(\"5,A,25000\\n\")\n    f.write(\"NA,B,30000\\n\")\n    f.write(\"10,C,10000\\n\")\n    f.write(\"NA,NA,50000\\n\")\n\"\"\"\n## Read Data\n\"\"\"\ndf = pd.read_csv(\"data.csv\")\ndf\n\"\"\"\n## Handle Missing Value\n\"\"\"\n# access element in dataframe through intger-location based index\ninputs = df.iloc[:, 0:2]\noutputs = df.iloc[:, 2]\ninputs\n# two ways to handle missing value: imputation or deletion\n# we fill missing value with imputation\ninputs.mean()\ninputs = inputs.fillna(inputs.mean())\ninputs\n# NaN is considered sa discrete or catogorical value\n# hence, we can do \"one-hot encoding\" on this column\ninputs = pd.get_dummies(data=inputs, dummy_na=True)\ninputs\n\"\"\"\n## Convert Data to Tensor\n\"\"\"\n# convert dataframe to numpy array\ninputs = inputs.values\noutputs = outputs.values\ninputs, outputs\ninput_tensor = tf.constant(inputs)\noutput_tensor = tf.constant(outputs)\ninput_tensor\noutput_tensor","meta":"{'source': 'AI4Code', 'id': '1a4a3c656958d9'}"}
{"id":"96095","text":"#----- EDA Libraries -------\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport missingno as mn\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom IPython.display import Image\nImage(filename='..\/input\/fifa-pic\/Ronaldo-copertina.jpg', height='50',width='800')\n\"\"\"\n# Contents\n- Data CLeaning\n- Visualisation\n- Barplots\n- Histograms\n- PieChart\n- Scatter Plot\n- Radar Plot\n\"\"\"\n# Loading the data\ndata = pd.read_csv('..\/input\/fifa19\/data.csv')\ndata.head()\n\"\"\"\n### Step 1 Data Cleaning\n\"\"\"\n# Dropping some of the features\n\ndata.drop(['Unnamed: 0','ID','Photo','Flag','Club Logo'],axis = 1, inplace = True)\ndata.head()\n# Size of the data\ndata.shape\ndata.columns\n# Missing values\nround(100*(data.isnull().sum()\/len(data)),2)[:50]\n# Missing values\nround(100*(data.isnull().sum()\/len(data)),2)[50:]\n# We will drop all the rows having less than or equal to 10 percent missing values\nvar1 = [ 'LS', 'ST', 'RS', 'LW',\n       'LF', 'CF', 'RF', 'RW', 'LAM', 'CAM', 'RAM', 'LM', 'LCM', 'CM', 'RCM',\n       'RM', 'LWB', 'LDM', 'CDM', 'RDM', 'RWB', 'LB', 'LCB', 'CB', 'RCB', 'RB']\ndata.dropna(axis = 0, subset= var1,inplace = True)\ndata['ST']\nround(100*(data.isnull().sum()\/len(data)),2)[:50]\nround(100*(data.isnull().sum()\/len(data)),2)[50:]\nvar2 = ['Club','Contract Valid Until','Release Clause','Joined']\ndata.dropna(axis = 0 , subset=var2,inplace = True)\n# Dropping the entire column of Loaned From as it has 93 percent approx missing values\ndata.drop(['Loaned From'],axis = 1,inplace = True)\n# Checking for any missing value in the data\ndata.isnull().sum().any()\n# Shape after removing rows and columns\ndata.shape\ndata.columns\n\"\"\"\n### Step 2 EDA\n\n- Taking one feature at a time\n\n#### Visualising using barplot\n\"\"\"\nnation_10_player = data['Nationality'].value_counts()[:11]\nnation_10_player.plot.bar()\nplt.title('Top 10 countries with most number of players in FIFA')\nplt.xlabel('Country')\nplt.ylabel('Number of players')\n# Top 20 countries with the most young players\nnation_10_age = data.groupby(['Nationality'])['Age'].mean().sort_values(ascending = True)[:20]\nnation_10_age.plot.bar(figsize = (15,12))\nplt.title('Top 20 countries with most young players')\nplt.xlabel('Country')\nplt.ylabel('Age')\n# Top 11 players under 25 years of age with best 'Overall' \nyoung_best_overall = data[data['Age'] <= 25][:12]\nyoung_best_overall[['Name','Overall','Age']]\nplt.figure(figsize=(15,12))\nplt.title('Player under 25 years of age with best Overall rating')\nax = sns.barplot(x = 'Name' , y = 'Overall', data = young_best_overall)\n\n# Top 10 teams to pick if your playing a crucial match\ntop_club_potential = data.groupby('Club')['Potential'].mean().sort_values(ascending = False)[:11]\ntop_club_potential.plot.bar()\nplt.xlabel('Club')\nplt.ylabel('Potential')\n# Using the following function to convert the 'Value' feature from 'object' dtype to 'int' dtype\ndef get_value(x):\n    float_value = float(x[1:-1])\n    if x[-1] == 'M':\n        float_value = float_value * 1000000\n    elif x[-1] == 'K':\n        float_value = float_value * 1000\n    else:\n        float_value == 0\n    return float_value    \ndata.Value = data.Value.apply(get_value)          \n# Converting the dype from 'Float' to 'int'\ndata.Value = data.Value.astype('int64')\n# After conversion\ndata.Value\n# Top 10 most expensive players\ntop_exp_player = data[['Name','Value']].sort_values(by = 'Value', ascending = False)[:11]\ntop_exp_player\nplt.figure(figsize=(15,8))\nsns.barplot(x = top_exp_player['Name'], y = top_exp_player['Value'], data = top_exp_player)\nplt.title('Top 10 most expensive players')\ndata.Wage\n# Using the following function to convert the 'Wage' feature from 'object' dtype to 'int' dtype\ndef get_value(x):\n    float_value = int(x[1:-1])\n    if x[-1] == 'K':\n        int_value = float_value * 1000\n    else:\n        int_value == 0\n    return int_value    \ndata.Wage = data.Wage.apply(get_value) \n# Top 10 most highly paid players\ntop_paid_player = data[['Name','Wage']].sort_values(by = 'Wage', ascending = False)[:11]\ntop_paid_player\nplt.figure(figsize=(15,8))\nsns.barplot(x = top_paid_player['Name'], y = top_paid_player['Wage'], data = top_paid_player)\nplt.title('Top 10 most paid players')\n# Top 10 nation that pays their players well\ntop_paid_nation = data.groupby(['Nationality'])['Wage'].mean().sort_values(ascending = False)[:11]\ntop_paid_nation.plot.bar()\nplt.title('Top 10 nation that pays their players well')\nplt.ylabel('Wage')\n\"\"\"\n#### Look like Dominican Republic pays significantly well as compareed to other nations\n\"\"\"\n# Histogram dipicting the distribution of age among players\nx = data.Age\nsns.set(style =\"dark\", palette=\"colorblind\", color_codes=True)\nax = sns.distplot(x,bins = 58,color = 'g',kde = False)\nax.set_xlabel('Age')\nax.set_ylabel('Number of players')\n\"\"\"\n#### So most player's age ranges from 20 - 30 years\n\"\"\"\n# Pieplot depicting the number of right footer vs left footer\ndata['Preferred Foot'].value_counts().plot.pie()\n# Top 10 right footer players\nright_footer = data[data['Preferred Foot'] == 'Right']\nbest_right_footer = right_footer[['Name','Overall']].sort_values(by = 'Overall',ascending = False)\nbest_right_footer[:11]\n# Top 10 left footer players\nleft_footer = data[data['Preferred Foot'] == 'Left']\nbest_left_footer = left_footer[['Name','Overall']].sort_values(by = 'Overall',ascending = False)\nbest_left_footer[:11]\n# Box plot to find whether left footer have better 'Overall' or right footer\nsns.boxplot(x = data['Preferred Foot'], y = data['Overall'], data = data)\n\"\"\"\n#### From the above boxplot we can see that it does not matter much which is your preferred foot\n\"\"\"\n# Boxplot dipicting whose got better 'Shortpower', left or right?\nsns.boxplot(x = data['Preferred Foot'], y = data['ShotPower'], data = data)\n# Boxplot dipicting the crossing ability of left and right footer\nsns.boxplot(x = data['Preferred Foot'], y = data['Crossing'], data = data)\n\"\"\"\n#### We can see that left footers are slightly better when it comes to crossing capability\n\"\"\"\ndata.columns\n\"\"\"\n### Scatter Plots\n\"\"\"\n# Scatterplot dipicting the linear relationship between 'Acceleration' and 'SprintSpeed'\nsns.scatterplot(x = data['Acceleration'], y = data['SprintSpeed'], data = data)\n# Scatterplot dipicting the linear relationship between 'Agility' and 'SprintSpeed'\nsns.scatterplot(x = data['Agility'], y = data['SprintSpeed'], data = data)\n# Scatterplot dipicting the relationship between 'Agression' and 'StandingTackle'\nsns.scatterplot(x = data['Aggression'], y = data['StandingTackle'], data = data, hue = data['Stamina'])\nsns.scatterplot(x = data['Curve'], y = data['Crossing'], data = data, hue = data['Preferred Foot'])\n\"\"\"\n#### The ball crossed by a left footer would curve slightly more than a right footer`\n\"\"\"\n# Some body type are incorrect\ndata['Body Type'].value_counts()\n# Changing them with normal bodytype\ndata['Body Type'].replace({'Messi':'Normal','Neymar':'Normal','Akinfenwa':'Normal','Shaqiri':'Normal','C. Ronaldo':\n                          'Normal','PLAYER_BODY_TYPE_25':'Normal'},inplace = True)\ndata['Body Type'].value_counts().plot.pie()\n# Boxplot for Stamina and Acceleration\nsns.scatterplot(x = data['Stamina'], y = data['Acceleration'], data = data, hue = data['Body Type'])\n\"\"\"\n#### Majority of players with leaner body have better acceleration but less stamina\n\"\"\"\nsns.scatterplot(x = data['FKAccuracy'], y = data['Curve'], data = data, hue = data['Preferred Foot'])\n\"\"\"\n#### The more you can curve the ball better is your FreeKick Accuracy\n\"\"\"\ndata.columns\nmessi = pd.DataFrame(dict(\n    att=[97,94,96,86,72],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\nronaldo = pd.DataFrame(dict(\n    att=[88,76,94,91,88],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\nsilva = pd.DataFrame(dict(\n    att=[89,77,94,64,78],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\nneymar = pd.DataFrame(dict(\n    att=[96,87,95,90,81],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\nsalah = pd.DataFrame(dict(\n    att=[89,60,88,91,84],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\nramos = pd.DataFrame(dict(\n    att=[63,72,84,75,84],\n    theta=['Dribbling','FKAccuracy','BallControl',\n        'SprintSpeed','Stamina']))\n\"\"\"\n### Radar Charts\n\"\"\"\nfig = px.line_polar(data_frame=messi ,r = 'att', theta='theta',line_close=True,title = 'Lionel Messi')\nfig.update_traces(fill='toself')\nfig.show()\nfig = px.line_polar(ronaldo, r = 'att', theta='theta',line_close=True,title = 'Critiano Ronaldo')\nfig.update_traces(fill='toself')\nfig.show()\nfig = px.line_polar(silva, r = 'att', theta='theta',line_close=True,title = 'David Silva')\nfig.update_traces(fill='toself')\nfig.show()\nfig = px.line_polar(neymar, r = 'att', theta='theta',line_close=True,title = 'Neymar Jr')\nfig.update_traces(fill='toself')\nfig.show()\nfig = px.line_polar(salah, r = 'att', theta='theta',line_close=True,title = 'Mohammad Salah')\nfig.update_traces(fill='toself')\nfig.show()\nfig = px.line_polar(ramos, r = 'att', theta='theta',line_close=True,title = 'Sergio Ramos')\nfig.update_traces(fill='toself')\nfig.show()\n\"\"\"\n#### Radar charts dipicting the skills of few best fifa players\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b07b135558fb5a'}"}
{"id":"106117","text":"\"\"\"\n# Using Keras and distilBERT to classify tweets\n\"\"\"\n\"\"\"\n### Install simpletransformers\n\"\"\"\n!pip install --upgrade transformers\n!pip install simpletransformers\n\"\"\"\n### Import necessary packages\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport re\nimport string\nimport tqdm\nimport nltk\nnltk.download('stopwords')\nnltk.download('wordnet')\nfrom wordcloud import WordCloud\nfrom wordcloud import STOPWORDS\nfrom nltk.corpus import stopwords\nfrom tqdm.notebook import tqdm\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport tensorflow_hub as hub\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\n\nimport gc\nfrom tqdm.autonotebook import tqdm\n\nfrom sklearn.metrics import accuracy_score,f1_score\n\nimport sklearn\n\nimport torch\nfrom simpletransformers.classification import ClassificationModel\n\n\"\"\"\n### Loading data\n\"\"\"\ntrain_data = pd.read_csv(\"..\/input\/tweets-with-sarcasm-and-irony\/train.csv\")\ntest_data = pd.read_csv(\"..\/input\/tweets-with-sarcasm-and-irony\/test.csv\")\n\"\"\"\n### Remove recurring tweets to prevent ambiguity\n\"\"\"\ntrain_tweets=train_data['tweets'].tolist()\ntest_tweets=test_data['tweets'].tolist()\ndef keep_uniques(array, df):\n    dels=[]\n    for i in array:\n        if array.count(i)>1:\n            dels.append(i)\n    dels=list(set(dels))\n    for i in dels:\n        df.drop( df[ df['tweets'] == i ].index, inplace=True)\n    return df\ntrain_data=keep_uniques(train_tweets, train_data)\ntest_data=keep_uniques(test_tweets, test_data)\nlen(train_data['tweets'].unique())\nlen(test_data['tweets'].unique())\n\"\"\"\n### Exploring Dataset\n\"\"\"\ntrain_data.describe().T\ntrain_data = train_data.sample(frac = 1)\ntest_data = test_data.sample(frac = 1)\ntrain_data['class'].value_counts()\n\"\"\"\nHere, we see that the `regular` class has 18k tweets, which causes our dataset to be imbalanced. So we shall delete some tweets from this class\n\"\"\"\ntemp=train_data.loc[train_data['class'] == 'regular']\nlis=temp['tweets'].tolist()\n\nimport random\nreg_del=[]\nvisited=set()\nfor _ in range(3600):\n    n=random.randint(0,18556)\n    if n not in visited:\n        reg_del.append(lis[n])\n        \n        \nfor i in reg_del:\n    train_data.drop( train_data[ train_data['tweets'] == i ].index, inplace=True)\ntrain_data['class'].value_counts()\ntest_data['class'].value_counts()\ntest_data = test_data.dropna()\n\"\"\"\n## Data Cleaning & Preprocessing\n\"\"\"\ndef clean(tweet): \n    \n\n    # Special characters\n    tweet = re.sub(r\"\\x89\u00db_\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00d2\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00d3\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00cfWhen\", \"When\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00cf\", \"\", tweet)\n    tweet = re.sub(r\"China\\x89\u00db\u00aas\", \"China's\", tweet)\n    tweet = re.sub(r\"let\\x89\u00db\u00aas\", \"let's\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00f7\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00aa\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\\x9d\", \"\", tweet)\n    tweet = re.sub(r\"\u00e5_\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00a2\", \"\", tweet)\n    tweet = re.sub(r\"\\x89\u00db\u00a2\u00e5\u00ca\", \"\", tweet)\n    tweet = re.sub(r\"from\u00e5\u00cawounds\", \"from wounds\", tweet)\n    tweet = re.sub(r\"\u00e5\u00ca\", \"\", tweet)\n    tweet = re.sub(r\"\u00e5\u00c8\", \"\", tweet)\n    tweet = re.sub(r\"Jap\u00cc_n\", \"Japan\", tweet)    \n    tweet = re.sub(r\"\u00cc\u00a9\", \"e\", tweet)\n    tweet = re.sub(r\"\u00e5\u00a8\", \"\", tweet)\n    tweet = re.sub(r\"Suru\u00cc\u00a4\", \"Suruc\", tweet)\n    tweet = re.sub(r\"\u00e5\u00c7\", \"\", tweet)\n    tweet = re.sub(r\"\u00e5\u00a33million\", \"3 million\", tweet)\n    tweet = re.sub(r\"\u00e5\u00c0\", \"\", tweet)\n    \n    #emojis\n    emoji_pattern = re.compile(\n        '['\n        u'\\U0001F600-\\U0001F64F'  # emoticons\n        u'\\U0001F300-\\U0001F5FF'  # symbols & pictographs\n        u'\\U0001F680-\\U0001F6FF'  # transport & map symbols\n        u'\\U0001F1E0-\\U0001F1FF'  # flags\n        u'\\U00002702-\\U000027B0'\n        u'\\U000024C2-\\U0001F251'\n        ']+',\n        flags=re.UNICODE)\n    tweet =  emoji_pattern.sub(r'', tweet)\n    \n    # usernames mentions like \"@abc123\"\n    ment = re.compile(r\"(@[A-Za-z0-9]+)\")\n    tweet =  ment.sub(r'', tweet)\n    \n    # Contractions\n    tweet = re.sub(r\"he's\", \"he is\", tweet)\n    tweet = re.sub(r\"there's\", \"there is\", tweet)\n    tweet = re.sub(r\"We're\", \"We are\", tweet)\n    tweet = re.sub(r\"That's\", \"That is\", tweet)\n    tweet = re.sub(r\"won't\", \"will not\", tweet)\n    tweet = re.sub(r\"they're\", \"they are\", tweet)\n    tweet = re.sub(r\"Can't\", \"Cannot\", tweet)\n    tweet = re.sub(r\"wasn't\", \"was not\", tweet)\n    tweet = re.sub(r\"don\\x89\u00db\u00aat\", \"do not\", tweet)\n    tweet = re.sub(r\"aren't\", \"are not\", tweet)\n    tweet = re.sub(r\"isn't\", \"is not\", tweet)\n    tweet = re.sub(r\"What's\", \"What is\", tweet)\n    tweet = re.sub(r\"haven't\", \"have not\", tweet)\n    tweet = re.sub(r\"hasn't\", \"has not\", tweet)\n    tweet = re.sub(r\"There's\", \"There is\", tweet)\n    tweet = re.sub(r\"He's\", \"He is\", tweet)\n    tweet = re.sub(r\"It's\", \"It is\", tweet)\n    tweet = re.sub(r\"You're\", \"You are\", tweet)\n    tweet = re.sub(r\"I'M\", \"I am\", tweet)\n    tweet = re.sub(r\"shouldn't\", \"should not\", tweet)\n    tweet = re.sub(r\"wouldn't\", \"would not\", tweet)\n    tweet = re.sub(r\"i'm\", \"I am\", tweet)\n    tweet = re.sub(r\"I\\x89\u00db\u00aam\", \"I am\", tweet)\n    tweet = re.sub(r\"I'm\", \"I am\", tweet)\n    tweet = re.sub(r\"Isn't\", \"is not\", tweet)\n    tweet = re.sub(r\"Here's\", \"Here is\", tweet)\n    tweet = re.sub(r\"you've\", \"you have\", tweet)\n    tweet = re.sub(r\"you\\x89\u00db\u00aave\", \"you have\", tweet)\n    tweet = re.sub(r\"we're\", \"we are\", tweet)\n    tweet = re.sub(r\"what's\", \"what is\", tweet)\n    tweet = re.sub(r\"couldn't\", \"could not\", tweet)\n    tweet = re.sub(r\"we've\", \"we have\", tweet)\n    tweet = re.sub(r\"it\\x89\u00db\u00aas\", \"it is\", tweet)\n    tweet = re.sub(r\"doesn\\x89\u00db\u00aat\", \"does not\", tweet)\n    tweet = re.sub(r\"It\\x89\u00db\u00aas\", \"It is\", tweet)\n    tweet = re.sub(r\"Here\\x89\u00db\u00aas\", \"Here is\", tweet)\n    tweet = re.sub(r\"who's\", \"who is\", tweet)\n    tweet = re.sub(r\"I\\x89\u00db\u00aave\", \"I have\", tweet)\n    tweet = re.sub(r\"y'all\", \"you all\", tweet)\n    tweet = re.sub(r\"can\\x89\u00db\u00aat\", \"cannot\", tweet)\n    tweet = re.sub(r\"would've\", \"would have\", tweet)\n    tweet = re.sub(r\"it'll\", \"it will\", tweet)\n    tweet = re.sub(r\"we'll\", \"we will\", tweet)\n    tweet = re.sub(r\"wouldn\\x89\u00db\u00aat\", \"would not\", tweet)\n    tweet = re.sub(r\"We've\", \"We have\", tweet)\n    tweet = re.sub(r\"he'll\", \"he will\", tweet)\n    tweet = re.sub(r\"Y'all\", \"You all\", tweet)\n    tweet = re.sub(r\"Weren't\", \"Were not\", tweet)\n    tweet = re.sub(r\"Didn't\", \"Did not\", tweet)\n    tweet = re.sub(r\"they'll\", \"they will\", tweet)\n    tweet = re.sub(r\"they'd\", \"they would\", tweet)\n    tweet = re.sub(r\"DON'T\", \"DO NOT\", tweet)\n    tweet = re.sub(r\"That\\x89\u00db\u00aas\", \"That is\", tweet)\n    tweet = re.sub(r\"they've\", \"they have\", tweet)\n    tweet = re.sub(r\"i'd\", \"I would\", tweet)\n    tweet = re.sub(r\"should've\", \"should have\", tweet)\n    tweet = re.sub(r\"You\\x89\u00db\u00aare\", \"You are\", tweet)\n    tweet = re.sub(r\"where's\", \"where is\", tweet)\n    tweet = re.sub(r\"Don\\x89\u00db\u00aat\", \"Do not\", tweet)\n    tweet = re.sub(r\"we'd\", \"we would\", tweet)\n    tweet = re.sub(r\"i'll\", \"I will\", tweet)\n    tweet = re.sub(r\"weren't\", \"were not\", tweet)\n    tweet = re.sub(r\"They're\", \"They are\", tweet)\n    tweet = re.sub(r\"Can\\x89\u00db\u00aat\", \"Cannot\", tweet)\n    tweet = re.sub(r\"you\\x89\u00db\u00aall\", \"you will\", tweet)\n    tweet = re.sub(r\"I\\x89\u00db\u00aad\", \"I would\", tweet)\n    tweet = re.sub(r\"let's\", \"let us\", tweet)\n    tweet = re.sub(r\"it's\", \"it is\", tweet)\n    tweet = re.sub(r\"can't\", \"cannot\", tweet)\n    tweet = re.sub(r\"don't\", \"do not\", tweet)\n    tweet = re.sub(r\"you're\", \"you are\", tweet)\n    tweet = re.sub(r\"i've\", \"I have\", tweet)\n    tweet = re.sub(r\"that's\", \"that is\", tweet)\n    tweet = re.sub(r\"i'll\", \"I will\", tweet)\n    tweet = re.sub(r\"doesn't\", \"does not\", tweet)\n    tweet = re.sub(r\"i'd\", \"I would\", tweet)\n    tweet = re.sub(r\"didn't\", \"did not\", tweet)\n    tweet = re.sub(r\"ain't\", \"am not\", tweet)\n    tweet = re.sub(r\"you'll\", \"you will\", tweet)\n    tweet = re.sub(r\"I've\", \"I have\", tweet)\n    tweet = re.sub(r\"Don't\", \"do not\", tweet)\n    tweet = re.sub(r\"I'll\", \"I will\", tweet)\n    tweet = re.sub(r\"I'd\", \"I would\", tweet)\n    tweet = re.sub(r\"Let's\", \"Let us\", tweet)\n    tweet = re.sub(r\"you'd\", \"You would\", tweet)\n    tweet = re.sub(r\"It's\", \"It is\", tweet)\n    tweet = re.sub(r\"Ain't\", \"am not\", tweet)\n    tweet = re.sub(r\"Haven't\", \"Have not\", tweet)\n    tweet = re.sub(r\"Could've\", \"Could have\", tweet)\n    tweet = re.sub(r\"youve\", \"you have\", tweet)  \n    tweet = re.sub(r\"don\u00e5\u00abt\", \"do not\", tweet)   \n            \n    # Character entity references\n    tweet = re.sub(r\"&amp;\", \"&\", tweet)\n    \n    # html tags\n    html = re.compile(r'<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')\n    tweet = re.sub(html, '', tweet)\n    \n    # Urls\n    tweet = re.sub(r\"https?:\\\/\\\/t.co\\\/[A-Za-z0-9]+\", \"\", tweet)\n    tweet = re.sub(r'https?:\/\/\\S+|www\\.\\S+','', tweet)\n        \n    #Punctuations and special characters\n    \n    tweet = re.sub('[%s]' % re.escape(string.punctuation),'',tweet)\n    \n    tweet = tweet.lower()\n    \n    splits = tweet.split()\n    splits = [word for word in splits if word not in set(nltk.corpus.stopwords.words('english'))]\n    tweet = ' '.join(splits)\n    \n    \n    return tweet\ntqdm.pandas() \n\ntrain_data['cleaned_text']= train_data['tweets'].progress_apply((lambda x: clean(x))) \ntest_data['cleaned_text'] = test_data['tweets'].progress_apply((lambda x: clean(x)))\ntrain_data.head()\n\"\"\"\n## EDA and Visualization\n\"\"\"\nsns.set(rc={'figure.figsize':(10,10)})\nsns.countplot(train_data['class'])\nfrom wordcloud import WordCloud\nstopwords = nltk.corpus.stopwords.words('english')\n\nplt.figure(figsize=(12,6))\ntext = ' '.join(train_data.cleaned_text[train_data['class']=='regular'])\nwc = WordCloud(background_color='white',stopwords=stopwords).generate(text)\nplt.imshow(wc)\nplt.axis('off')\nplt.title('Regular Tweets',fontsize=25)\n\nplt.figure(figsize=(12,6))\ntext = ' '.join(train_data.cleaned_text[train_data['class']=='irony'])\nwc1 = WordCloud(background_color='white',stopwords=stopwords).generate(text)\nplt.imshow(wc1)\nplt.axis('off')\nplt.title('Irony Tweets',fontsize=25)\n\nplt.figure(figsize=(12,6))\ntext = ' '.join(train_data.cleaned_text[train_data['class']=='sarcasm'])\nwc2 = WordCloud(background_color='white',stopwords=stopwords).generate(text)\nplt.imshow(wc2)\nplt.axis('off')\nplt.title('Sarcasm Tweets',fontsize=25)\n\nplt.figure(figsize=(12,6))\ntext = ' '.join(train_data.cleaned_text[train_data['class']=='figurative'])\nwc3 = WordCloud(background_color='white',stopwords=stopwords).generate(text)\nplt.imshow(wc3)\nplt.axis('off')\nplt.title('Figurative Tweets',fontsize=25)\n\"\"\"\n### Encode our text classes\n\"\"\"\ndef encode_target(t_class):\n    t_class=str(t_class)\n    class_dict = {\n        'irony':0,\n        'sarcasm':1,\n        'regular':2,\n        'figurative':3\n    }\n    return class_dict[t_class]\ntrain_data[\"target\"] = train_data['class'].apply(lambda x: encode_target(x))\ntest_data[\"target\"] = test_data['class'].apply(lambda x: encode_target(x))\n\"\"\"\n### Preparing our train and test sets\n\"\"\"\ntrain = train_data[['cleaned_text','target']]\ntrain.columns = ['text','labels']\n\ntest = test_data[['cleaned_text','target']]\ntest.columns = ['text','labels']\n\ntrain.head()\ntest.head()\n\"\"\"\n## Building the model\n\n### Setting up the model arguments\n\"\"\"\n\nmodel_type = 'distilbert'\nmodel_name = 'distilbert-base-uncased'\nseed = 100\nmodel_args =  {'fp16': False,\n               'train_batch_size': 128,\n               'gradient_accumulation_steps': 2,\n#                'do_lower_case': True,\n               'learning_rate': 1e-5,\n               'overwrite_output_dir': True,\n               'manual_seed': seed,\n               'num_train_epochs': 4}\n\"\"\"\n### Defining model\n\"\"\"\nmodel = ClassificationModel(model_type, model_name,num_labels=4, args=model_args) \n\"\"\"\n### Training model\n\"\"\"\nmodel.train_model(train,acc=accuracy_score)\n\"\"\"\n### Evaluate on the test set\n\"\"\"\nresult, model_outputs, wrong_predictions = model.eval_model(test,acc=accuracy_score)\nprint(\"TEST SET EVALUATION:\")\nprint(\"====================================\")\nprint(\"%s: %.2f%%\" % ('Accuracy', result['acc']*100))\nprint(\"%s: %.5f\" % ('Final Loss', result['eval_loss']))\n\"\"\"\n### Please upvote if this helped :)\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c2f29e2e703c30'}"}
{"id":"65523","text":"\"\"\"\n **Dog Breed Classification**\n\"\"\"\nimport os\nimport warnings\nimport random\nfrom shutil import copyfile\nimport numpy as np\nimport pandas as pd\nimport itertools\n#data visualization libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pathlib\n#deep learning libraries\nimport tensorflow as tf\nfrom keras.optimizers import Adam\nfrom keras.layers import Conv2D, Flatten, Dense, MaxPooling2D, Dropout\nfrom keras.models import Sequential\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom keras.preprocessing.image import ImageDataGenerator\n#importing ResNet50 model\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\n#train and test directories\ndir_train='..\/input\/dog-breed-identification\/train'\ndir_test='..\/input\/dog-breed-identification\/test'\n\n#labels have image name and dog breed in a csv file and sample_submission contain details of test set\ndf_train= pd.read_csv('..\/input\/dog-breed-identification\/labels.csv',dtype=str)\ndf_test= pd.read_csv('..\/input\/dog-breed-identification\/sample_submission.csv',dtype=str)\n#images are in jpg format and to match their names in csv file we appending 'jpg' in it\ndef append_ext(fn):\n    return fn+\".jpg\"\ndf_train[\"id\"] = df_train[\"id\"].apply(append_ext)\ndf_test[\"id\"] = df_test[\"id\"].apply(append_ext)\n\"\"\"\n***Training Data***\n\"\"\"\n#As instructed all other breeds except suggested ones are deleted\ninc_breed=['beagle','chihuahua','doberman','french_bulldog','golden_retriever','malamute','pug','saint_bernard', 'scottish_deerhound',\n'tibetan_mastiff']\nfor i,breed in df_train.iterrows():\n    if breed[1] not in inc_breed:\n        df_train=df_train.drop([i])\n       \nlen(df_train)\n\"\"\"\n***Training set and Test set***\n\"\"\"\nprint(df_train.head())\ndf_test.head()\n\"\"\"\n***Training Images***\n\"\"\"\n#display some images with help of matplotlib\nsource_path = \"..\/input\/dog-breed-identification\/train\"\nsub_class = os.listdir(source_path)\n\nfig = plt.figure(figsize=(10,5))\nfor i in range(len(sub_class[:8])):\n    plt.subplot(2,4,i+1)\n    imag = plt.imread(os.path.join(source_path,sub_class[i+7]))\n    plt.imshow(imag, cmap=plt.get_cmap('gray'))\n    plt.axis('off')\n\"\"\"\n***Data Preprocessing***\n\"\"\"\n#Generating batches of tensor image data with real-time data augmentation.\ntrain_datagen=ImageDataGenerator( rescale=1.\/255.,\n                                  rotation_range = 20,\n                                  brightness_range=[0.2,1.0],\n                                  width_shift_range = 0.2,\n                                  height_shift_range = 0.2,\n                        \n                                  horizontal_flip = True,\n                                \n                                  validation_split=0.1\n                                  )\n#Generating batches of tensor image data with real-time data augmentation for training set.\ntrain_generator=train_datagen.flow_from_dataframe(\ndirectory=dir_train,\ndataframe=df_train,\nx_col=\"id\",\ny_col=\"breed\",\nsubset=\"training\",\nbatch_size=32,\nseed=42,\nshuffle=True,\nclass_mode=\"categorical\",\ntarget_size=(224,224)\n\n)\n\"\"\"\n***Validation Data***\n\"\"\"\n#Generating batches of tensor image data with real-time data augmentation for validation set set.\nvalidation_generator=train_datagen.flow_from_dataframe(\ndirectory=dir_train,\ndataframe=df_train,\nx_col=\"id\",\ny_col=\"breed\",\nsubset=\"validation\",\nbatch_size=32,\nseed=42,\nshuffle=True,\nclass_mode=\"categorical\",\ntarget_size=(224,224)\n)\n\"\"\"\n***Test Data***\n\"\"\"\ntest_datagen=ImageDataGenerator(rescale=1.\/255.)\n#Generating batches of tensor image data with real-time data augmentation for Test set.\n\ntest_generator=test_datagen.flow_from_dataframe(\ndirectory=dir_test,\ndataframe=df_test,\nx_col=\"id\",\ny_col=None,\nbatch_size=32,\nseed=42,\nshuffle=False,\nclass_mode=None,\ntarget_size=(224,224),\n)\nclasses=len(inc_breed)\nclasses\n\"\"\"\n***Using Pretrained Model : ResNet50***\n\"\"\"\n#Freezing Resnet50 model to avoid weight updation\npretrained_model =ResNet50(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=(224,224,3)\n    )\n#defing model\nmodel =Sequential([ \n        pretrained_model,  \n        Flatten(),\n#         tf.keras.layers.GlobalAveragePooling2D(),\n        Dense(2048, activation='relu'),\n        Dropout(0.5),\n\n        Dense(256, activation='relu'),\n        Dropout(0.5),\n        Dense(64, activation='relu'),\n        Dropout(0.3),\n    \n        Dense(10, activation='softmax')\n    ])\n#as mentioned f1score, recall, precision are defined as our judging criteria for model\nfrom keras import backend as bd\n\ndef recall_m(y_true, y_pred):\n    true_positives =bd.sum(bd.round(bd.clip(y_true*y_pred,0,1)))\n    possible_positives =bd.sum(bd.round(bd.clip(y_true,0,1)))\n    recall =true_positives\/(possible_positives+bd.epsilon())\n    return recall\n\ndef precision_m(y_true, y_pred):\n    true_positives =bd.sum(bd.round(bd.clip(y_true*y_pred,0,1)))\n    predicted_positives =bd.sum(bd.round(bd.clip(y_pred,0,1)))\n    precision = true_positives \/ (predicted_positives+bd.epsilon())\n    return precision\n\ndef f1_m(y_true, y_pred): \n    precision =precision_m(y_true,y_pred)\n    recall =recall_m(y_true,y_pred)\n    return (2*((precision*recall)\/(precision+recall+bd.epsilon())))\n#stochastic gradient descent is used as optimizer and categorical_crossentropy is used for multiclass classification.\nopt=Adam(lr=1e-4)\nmodel.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['acc',f1_m,precision_m, recall_m])\nmodel.summary()\n\"\"\"\n***Model Fitting***\n\"\"\"\n#model fitting with 50 epochs\nstep_size_ =train_generator.n\/\/train_generator.batch_size\nvalid_step_size_ =validation_generator.n\/\/validation_generator.batch_size\nhistory =model.fit(train_generator,\n                    steps_per_epoch=step_size_,\n                    validation_data=validation_generator,\n                    validation_steps=valid_step_size_ ,\n                    epochs=50,\n#                     \n                   )\n\"\"\"\n***Plotting Curves***\n\"\"\"\n#plot of epoch vs accuracy for trainig set and epoch vs validation_accuracy for validation set\nacc=history.history['acc']\nval_acc=history.history['val_acc']\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs=range(len(acc))\n\nfig=plt.figure(figsize=(14,7))\nplt.plot(epochs,acc,'r', label='training Accuracy')\nplt.plot(epochs,val_acc,'b', label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('accuracy')\nplt.title(' training vs validation accuracy')\nplt.legend(loc='lower right')\nplt.show()\n\n#plot of epoch vs loss for trainig set and epoch vs validation_loss for validation set\n\nfig2=plt.figure(figsize=(14,7))\nplt.plot(epochs,loss,'r', label='training Accuracy')\nplt.plot(epochs,val_loss,'b', label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('accuracy')\nplt.title(' training vs validation accuracy')\nplt.legend(loc='upper right')\nplt.show()\n\n#judging criterias of our model\nloss, accuracy, f1_score, precision, recall = model.evaluate(validation_generator,batch_size=32)\n\nprint(\"Loss:\", loss)\nprint(\"Accuracy:\", accuracy)\nprint(\"F1 Score:\", f1_score)\n\"\"\"\n***Saving the Model for in future use\n\"\"\"\n#saving model for further use \nmodel.save(\"DogClassificationByResNet2.h5\")\n\"\"\"\n***model prediction on test data(sample_submission.csv)***\n\"\"\"\n#prediction on test set using test generator\npred=model.predict(test_generator)\n#sample test file\ndf_submission = pd.read_csv('\/kaggle\/input\/dog-breed-identification\/sample_submission.csv', usecols= inc_breed+['id'])\ndf_submission.head()\n\"\"\"\n***updating the values of probability***\n\"\"\"\n#prediction on sample test file    \ndf_submission.iloc[:,1:] = pred\ndf_submission.head()\n#size of data\ndf_submission.shape","meta":"{'source': 'AI4Code', 'id': '78dc2a9b2a04bf'}"}
{"id":"59041","text":"\"\"\"\n<center><h1> Handwritten characters in ancient Japanese manuscripts Image classification using CNN  <\/h1><\/center>\n![jm](http:\/\/www.tameshigiri.ca\/wp-content\/uploads\/2014\/07\/yagyu_full.jpg)\n\"\"\"\nimport time\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom __future__ import absolute_import, division, print_function\ntf.logging.set_verbosity(tf.logging.INFO)\n\nimport os\nprint(os.listdir(\"..\/input\"))\ntrain_img = np.load('..\/input\/kmnist-train-imgs.npz')['arr_0']\ntest_img= np.load('..\/input\/kmnist-test-imgs.npz')['arr_0']\ntrain_label = np.load('..\/input\/kmnist-train-labels.npz')['arr_0']\ntest_label = np.load('..\/input\/kmnist-test-labels.npz')['arr_0']\nchar_df = pd.read_csv(r'..\/input\/kmnist_classmap.csv')\nchar_df\nprint('train images shape {}\\ntest images shape {}'.format(train_img.shape , \n                                                            test_img.shape))\nprint('train label shape {}\\ntest label shape {}'.format(train_label.shape , \n                                                        test_label.shape))\ntrain_label[:5]\nplt.figure(1 , figsize = (15 , 9))\nn = 0\nfor i in range(49):\n    n += 1\n    plt.subplot(7 , 7 , n)\n    plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)\n    plt.imshow(train_img[i] , cmap = 'gray')\n    plt.xticks([]) , plt.yticks([])\n    plt.xlabel('class {}'.format(train_label[i]))\n    \nplt.show()\nplt.figure(1 , figsize = (15 , 9))\nn = 0\nfor i in range(49):\n    n += 1\n    plt.subplot(7 , 7 , n)\n    plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)\n    plt.imshow(test_img[i] , cmap = 'gray')\n    plt.xticks([]) , plt.yticks([])\n    plt.xlabel('class {}'.format(test_label[i]))\n    \nplt.show()\ntrain_img = train_img.astype(np.float32)\ntest_img = test_img.astype(np.float32)\ntrain_label = train_label.astype(np.int32)\ntest_label = test_label.astype(np.int32)\ntrain_img = train_img\/255\ntest_img = test_img\/255\ntrain_X = train_img.reshape([-1 , 28 , 28 , 1])\ntest_X = test_img.reshape([-1 , 28 , 28 , 1])\ntrain_X      = np.pad(train_X, ((0,0),(2,2),(2,2),(0,0)), 'constant')\ntest_X = np.pad(test_X, ((0,0),(2,2),(2,2),(0,0)), 'constant')\ntf.reset_default_graph()\ndef cnn_model_fn(features , labels , mode ):\n    input_layer = tf.reshape(features['x'] , [ -1 , 32 , 32 , 1])\n    \n    conv1 = tf.layers.conv2d(\n        inputs = input_layer , \n        filters = 6 , \n        kernel_size = [5 , 5],\n        padding = 'valid',\n        activation = tf.nn.tanh\n        )\n    pool1 = tf.layers.average_pooling2d(inputs = conv1 , \n                                        pool_size = [2 , 2] \n                                        , strides = 2 )\n\n    conv2 = tf.layers.conv2d(\n        inputs = pool1,\n        filters = 16 , \n        kernel_size = [5 , 5] ,\n        padding  = 'valid',\n        activation = tf.nn.tanh\n        )\n    \n    pool2 = tf.layers.average_pooling2d(inputs = conv2 , \n                                        pool_size = [2 , 2] \n                                        , strides = 2 )\n\n    conv3 = tf.layers.conv2d(\n        inputs = pool2 , \n        filters = 120 , \n        kernel_size = [5 , 5],\n        padding = 'valid',\n        activation = tf.nn.tanh\n        )\n    conv3_flat = tf.layers.flatten(conv3)\n    dense = tf.layers.dense(\n        inputs = conv3_flat , \n        units = 84 , \n        activation = tf.nn.tanh\n        )\n    logits = tf.layers.dense(\n        inputs = dense,\n        units = 10 \n        ) \n    \n    predictions = {'classes' : tf.argmax(input = logits , axis = 1 ),\n                  'probabilities' : tf.nn.softmax(logits , name = 'softmax_tensor')}\n    \n    if mode == tf.estimator.ModeKeys.PREDICT:\n        return tf.estimator.EstimatorSpec(mode = mode , \n                                          predictions = predictions)\n    \n    #Calculate Loss\n    loss = tf.losses.sparse_softmax_cross_entropy(labels = labels , logits = logits )\n    \n    if mode == tf.estimator.ModeKeys.TRAIN:\n        optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)\n        train_op = optimizer.minimize(\n            loss = loss , \n            global_step = tf.train.get_global_step()\n            )\n        return tf.estimator.EstimatorSpec(mode = mode , loss = loss , train_op = train_op)\n    \n    eval_metric_ops = {\n        'accuracy' : tf.metrics.accuracy(labels = labels ,\n                                         predictions =  predictions['classes'])\n    }\n    \n    return tf.estimator.EstimatorSpec(mode = mode , loss = loss , eval_metric_ops = eval_metric_ops)\ncnn_image_classifier = tf.estimator.Estimator(\n    model_fn = cnn_model_fn , model_dir = '\/tmp\/model_checkpoints' \n    )\ntensors_to_log = {'probabilities':'softmax_tensor'}\nlogging_hook = tf.train.LoggingTensorHook(\n    tensors = tensors_to_log , every_n_iter = 50 \n    )\ntrain_input_fn = tf.estimator.inputs.numpy_input_fn(\n    x = {'x':train_X},\n    y = train_label , \n    batch_size = 100 ,\n    num_epochs = None , \n    shuffle = True\n    )\n\ncnn_image_classifier.train(input_fn = train_input_fn,\n                          steps = 1, \n                          hooks = [logging_hook])\ncnn_image_classifier.train(input_fn = train_input_fn , steps = 10000)\neval_input_fn = tf.estimator.inputs.numpy_input_fn(\n    x = {'x' : test_X},\n    y = test_label , \n    num_epochs = 1,\n    shuffle = False\n    )\n\neval_results = cnn_image_classifier.evaluate(input_fn = eval_input_fn)\nprint(eval_results)\npred_input_fn = tf.estimator.inputs.numpy_input_fn(\n    x = {'x' : test_X},\n    y = test_label,\n    num_epochs = 1,\n    shuffle = False\n    )\n\ny_pred = cnn_image_classifier.predict(input_fn = pred_input_fn)\nclasses = [p['classes'] for p in y_pred]\nplt.figure(1 , figsize = (15  , 9 ))\nn = 0 \nfor i in range(49):\n    n += 1 \n    plt.subplot(7 , 7 , n)\n    plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)\n    r = np.random.randint(0 , 10000 , 1)[0]\n    plt.imshow(test_img[r] , cmap = 'gray')\n    plt.xticks([]) , plt.yticks([])\n    plt.xlabel('True : {}\\nPred : {} '.format(test_label[r] , classes[r]) )\n    \nplt.show()","meta":"{'source': 'AI4Code', 'id': '6cfd76cf2cb66c'}"}
{"id":"57694","text":"import numpy as np\nimport pandas as pd\nimport catboost as catb\nfrom sklearn.ensemble import RandomForestRegressor\nimport shutil\nimport os\n\"\"\"\n# Make some preparations\n\"\"\"\ndata_train = pd.read_csv('\/kaggle\/input\/commonlitreadabilityprize\/train.csv')\ndata_test  = pd.read_csv('\/kaggle\/input\/commonlitreadabilityprize\/test.csv')\nsubmission = pd.read_csv(\"\/kaggle\/input\/commonlitreadabilityprize\/sample_submission.csv\")\ny = data_train['target']\nerror = data_train['standard_error']\ndata_train\ndata_test\ndata_train = data_train.drop('target', axis=1)\ndata_train = data_train.drop('standard_error', axis=1)\ndata_train\ndata_test\nall_data = pd.DataFrame(np.vstack((data_train, data_test)))\nall_data\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n#nltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport re\nstopword = stopwords.words('english')\nwn = nltk.WordNetLemmatizer()\nimport gensim\nfrom gensim.models import Word2Vec\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom xgboost import XGBRegressor\nimport string\nstring.punctuation\ndef remove_punct(text):\n    text_nopunct = \"\".join([char for char in text if char not in string.punctuation])\n    return text_nopunct\n\ndef tokenize_(text):\n    tokens = re.split('\\W+', text)\n    return tokens\n\ndef remove_stopwords(tok_list):\n    text = [word for word in tok_list if word not in stopword]\n    return text\n\ndef lemmatizing(tok_text):\n    text = [wn.lemmatize(word) for word in tok_text]\n    return text\n\ndef joini(text):\n    words = [\" \".join(text) for word in text]\n    return words\n%%time\nall_data[3]  = pd.DataFrame(all_data[3].apply(lambda x: remove_punct(x)))\nall_data[3]  = all_data[3].apply(lambda x: tokenize_(x.lower()))\nall_data[3]  = all_data[3].apply(lambda x: remove_stopwords(x))\nall_data[3]  = all_data[3].apply(lambda x: lemmatizing(x)) \n#all_data[3]  = all_data[3].apply(lambda x: joini(x)) \nfor i in range(len(all_data[3])):\n    all_data[3][i] = joini(all_data[3][i])\nfor i in range(len(all_data[3])):\n    all_data[3][i] = all_data[3][i][0]\nall_data[3][2]\nTfidf_vectorizer = TfidfVectorizer(stop_words=stopwords.words('english'))\nall_data_vect = pd.DataFrame(Tfidf_vectorizer.fit_transform(all_data[3]).toarray())\nall_data_vect\nX = all_data_vect[:2834]\nX_test = all_data_vect[2834:2841]\n%%time\ncatboost_est = catb.CatBoostRegressor(task_type=\"GPU\")\n#est = RandomForestRegressor()\n#catboost_est.fit(X, y)\ncatboost_est.fit(X, y)\ncatboost_est.predict(X_test)\n#est.predict(X_test)\nsubmission['target'] = catboost_est.predict(X_test)\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission\n#shutil.rmtree(\"\/kaggle\/working\/catboost_info\")\nos.remove(\"kaggle\/working\/catboost_info\/time_left.tsv\")\nos.remove(\"kaggle\/working\/catboost_info\/learn_error.tsv\")\nos.remove(\"kaggle\/working\/catboost_info\/learn\/events.out.tfevents\")\nos.remove(\"kaggle\/working\/catboost_info\/catboost_training.json\")","meta":"{'source': 'AI4Code', 'id': '6a84dcb24f2612'}"}
{"id":"61472","text":"\"\"\"\n1-VER\u0130 HAZIRLAMA A\u015eAMASI\n\n\"\"\"\n\"\"\"\nGerekli k\u00fct\u00fcphaneleri \u00e7a\u011f\u0131ral\u0131m \n\"\"\"\n#Genel komutlar\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pandas import read_csv\nfrom sklearn.preprocessing import MinMaxScaler\nimport os\nimport math\n#RMSE ile tahmin hatalar\u0131m\u0131 belirlemek i\u00e7in sqrt \u00e7a\u011f\u0131rd\u0131m.(evaluate forecast)\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\n#Verisetini ay\u0131klamak i\u00e7in \u00e7a\u011f\u0131rd\u0131m\nfrom numpy import split\nfrom numpy import array\n#TimeSerieslerde kullan\u0131lan k\u00fct\u00fcphaneler\nfrom datetime import timedelta\n#Tensorflow k\u00fct\u00fcphaneleri\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import Sequence\n\n\"\"\"\n\u00d6\u011frenme setini \u00e7a\u011f\u0131rd\u0131m.Verisetimi google drive'a kaydedip \u00e7a\u011f\u0131rd\u0131m.\n\n\n\"\"\"\npath = \"..\/input\/solar-radiation-dataset\/solar_angles_dataset.csv\"\ndf = pd.read_csv(path)\ndf.head()\n\"\"\"\nVerisetini olu\u015fturuken olu\u015fan bo\u015f s\u00fctunu sildim\n\"\"\"\ndf.info()\ndf=df.drop(['Julian day',\"Top. azimuth angle (eastward from N)\",\"Topocentric zenith angle\"], axis = 1) \ndf=df\n\"\"\"\n-Zaman s\u00fctunlar\u0131n\u0131 birle\u015ftirip datetime'a \u00e7evirdim, sonra di\u011fer s\u00fctunlar\u0131 sildim.\n\n-Datetime s\u00fctununu index yapt\u0131m .\n\"\"\"\ncols = [\"Date (M\/D\/YYYY)\",\"Time (H:MM:SS)\"]\ndf[\"date_time\"] = df[cols].apply(lambda row: \"\".join(row.values.astype(str)), axis=1)\ndf['date_time'] = pd.to_datetime(df['date_time'], format='%m\/%d\/%Y%H:%M:%S')\ndf=df.drop([\"Date (M\/D\/YYYY)\",\"Time (H:MM:SS)\" ,\"Unnamed: 0\"], axis = 1)\n# Split into training, validation and test datasets.\n# Since it's timeseries we should do it by date.\ntest_cutoff_date = df['date_time'].max() - timedelta(days=1)\nval_cutoff_date = test_cutoff_date - timedelta(days=14)\n\ndf_test = df[df['date_time'] > test_cutoff_date]\ndf_val = df[(df['date_time'] > val_cutoff_date) & (df['date_time'] <= test_cutoff_date)]\ndf_train = df[df['date_time'] <= val_cutoff_date]\n\n#check out the datasets\nprint('Test dates: {} to {}'.format(df_test['date_time'].min(), df_test['date_time'].max()))\nprint('Validation dates: {} to {}'.format(df_val['date_time'].min(), df_val['date_time'].max()))\nprint('Train dates: {} to {}'.format(df_train['date_time'].min(), df_train['date_time'].max()))\ndf_test=df_test.set_index('date_time') #Columnu index yapmak i\u00e7in\ndf_val=df_val.set_index('date_time') #Columnu index yapmak i\u00e7in\ndf_train=df_train.set_index('date_time') #Columnu index yapmak i\u00e7in\ndf_train.plot(figsize=(16,8))\nlen(df_train)\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nscaler.fit(df_train)\nscaled_train=scaler.transform(df_train)\nscaled_test =scaler.transform(df_test)\nscaled_val=scaler.transform(df_val)\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nn_input =4\nn_features =1\ntrain_generator = TimeseriesGenerator(scaled_train,scaled_train,length=n_input,batch_size = 1)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nmodel =Sequential()\nmodel.add(LSTM(64,activation =\"relu\",input_shape=(n_input,n_features)))\nmodel.add(Dense(1))\nmodel.compile(optimizer =\"adam\",loss=\"mse\")\nmodel.summary()\n\nmodel.fit_generator(train_generator,epochs=10)\nmodel.history.history.keys()  \nmyloss = model.history.history[\"loss\"]\nplt.plot(range(len(myloss)),myloss)\n\"\"\"\nForecast Visualisation\n\"\"\"\ntest_predictions = []\n\nfirst_eval_batch = scaled_train[-n_input:]\ncurrent_batch = first_eval_batch.reshape((1, n_input, n_features))\n\nfor i in range(len(df_test)):\n    \n    # get prediction 1 time stamp ahead ([0] is for grabbing just the number instead of [array])\n    current_pred = model.predict(current_batch)[0]\n    \n    # store prediction\n    test_predictions.append(current_pred) \n    \n    # update batch to now include prediction and drop first value\n    current_batch = np.append(current_batch[:,1:,:],[[current_pred]],axis=1)\ntrue_predictions = scaler.inverse_transform(test_predictions)\ntrue_predictions\ndf_test['Predictions'] = true_predictions\ndf_test.plot(figsize=(20,8))","meta":"{'source': 'AI4Code', 'id': '715d2fd95fb41d'}"}
{"id":"108814","text":"\"\"\"\n# **ABOUT HEART ATTACK**\n\"\"\"\n\"\"\"\n> A heart attack (Cardiovascular diseases) occurs when the flow of blood to the heart muscle suddenly becomes blocked. From WHO statistics every year 17.9 million dying from heart attack. The medical study says that human life style is the main reason behind this heart problem. Apart from this there are many key factors which warns that the person may\/maynot getting chance of heart attack.\n\n> <img style=\"float: centre;\" src=\"https:\/\/img.lovepik.com\/photo\/50074\/6189.jpg_wh860.jpg\" width=\"600px\"\/>\n\n> This dataset contain some medical information of patients which tells whether that person getting a heart attack chance is less or more. Using the information explore the dataset and classify the target variable using different Machine Learning models and findout which algorithm suitable for this dataset.\n\"\"\"\n\"\"\"\n## Table of Contents\n1) Import Packages\n\n2) EDA\n\n3) Preparing ML models\n\n4) Models evaluation\n\n5) Ensembling\n\n6) Conclusion\n\"\"\"\n\"\"\"\n## Packages Required\n\"\"\"\n#loading dataset\nimport pandas as pd\nimport numpy as np\n#visualisation\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n#EDA\nfrom collections import Counter\nimport pandas_profiling as pp\n# data preprocessing\nfrom sklearn.preprocessing import StandardScaler\n# data splitting\nfrom sklearn.model_selection import train_test_split\n# data modeling\nfrom sklearn.metrics import confusion_matrix,accuracy_score,roc_curve,classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n#ensembling\nfrom mlxtend.classifier import StackingCVClassifier\ndata = pd.read_csv('..\/input\/health-care-data-set-on-heart-attack-possibility\/heart.csv')\ndata.head()\ndata.info()\n\"\"\"\n## **EDA**\n\"\"\"\npp.ProfileReport(data)\n\"\"\"\n## **Model prepration**\n\"\"\"\ny = data[\"target\"]\nX = data.drop('target',axis=1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state = 0)\n\"\"\"\n**Before applying algorithm we should check whether the data is equally splitted or not, because if data is not splitted equally it will cause for data imbalacing problem**\n\"\"\"\nprint(y_test.unique())\nCounter(y_train)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\"\"\"\n## **ML models**\n\nHere I take different machine learning algorithm and try to find algorithm which predict accurately.\n\n1. Logistic Regression\n2. Naive Bayes\n3. Random Forest Classifier\n4. Extreme Gradient Boost\n5. K-Nearest Neighbour\n6. Decision Tree\n7. Support Vector Machine\n\n\"\"\"\nm1 = 'Logistic Regression'\nlr = LogisticRegression()\nmodel = lr.fit(X_train, y_train)\nlr_predict = lr.predict(X_test)\nlr_conf_matrix = confusion_matrix(y_test, lr_predict)\nlr_acc_score = accuracy_score(y_test, lr_predict)\nprint(\"confussion matrix\")\nprint(lr_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of Logistic Regression:\",lr_acc_score*100,'\\n')\nprint(classification_report(y_test,lr_predict))\nm2 = 'Naive Bayes'\nnb = GaussianNB()\nnb.fit(X_train,y_train)\nnbpred = nb.predict(X_test)\nnb_conf_matrix = confusion_matrix(y_test, nbpred)\nnb_acc_score = accuracy_score(y_test, nbpred)\nprint(\"confussion matrix\")\nprint(nb_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of Naive Bayes model:\",nb_acc_score*100,'\\n')\nprint(classification_report(y_test,nbpred))\nm3 = 'Random Forest Classfier'\nrf = RandomForestClassifier(n_estimators=20, random_state=12,max_depth=5)\nrf.fit(X_train,y_train)\nrf_predicted = rf.predict(X_test)\nrf_conf_matrix = confusion_matrix(y_test, rf_predicted)\nrf_acc_score = accuracy_score(y_test, rf_predicted)\nprint(\"confussion matrix\")\nprint(rf_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of Random Forest:\",rf_acc_score*100,'\\n')\nprint(classification_report(y_test,rf_predicted))\nm4 = 'Extreme Gradient Boost'\nxgb = XGBClassifier(learning_rate=0.01, n_estimators=25, max_depth=15,gamma=0.6, subsample=0.52,colsample_bytree=0.6,seed=27, \n                    reg_lambda=2, booster='dart', colsample_bylevel=0.6, colsample_bynode=0.5)\nxgb.fit(X_train, y_train)\nxgb_predicted = xgb.predict(X_test)\nxgb_conf_matrix = confusion_matrix(y_test, xgb_predicted)\nxgb_acc_score = accuracy_score(y_test, xgb_predicted)\nprint(\"confussion matrix\")\nprint(xgb_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of Extreme Gradient Boost:\",xgb_acc_score*100,'\\n')\nprint(classification_report(y_test,xgb_predicted))\nm5 = 'K-NeighborsClassifier'\nknn = KNeighborsClassifier(n_neighbors=10)\nknn.fit(X_train, y_train)\nknn_predicted = knn.predict(X_test)\nknn_conf_matrix = confusion_matrix(y_test, knn_predicted)\nknn_acc_score = accuracy_score(y_test, knn_predicted)\nprint(\"confussion matrix\")\nprint(knn_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of K-NeighborsClassifier:\",knn_acc_score*100,'\\n')\nprint(classification_report(y_test,knn_predicted))\nm6 = 'DecisionTreeClassifier'\ndt = DecisionTreeClassifier(criterion = 'entropy',random_state=0,max_depth = 6)\ndt.fit(X_train, y_train)\ndt_predicted = dt.predict(X_test)\ndt_conf_matrix = confusion_matrix(y_test, dt_predicted)\ndt_acc_score = accuracy_score(y_test, dt_predicted)\nprint(\"confussion matrix\")\nprint(dt_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of DecisionTreeClassifier:\",dt_acc_score*100,'\\n')\nprint(classification_report(y_test,dt_predicted))\nm7 = 'Support Vector Classifier'\nsvc =  SVC(kernel='rbf', C=2)\nsvc.fit(X_train, y_train)\nsvc_predicted = svc.predict(X_test)\nsvc_conf_matrix = confusion_matrix(y_test, svc_predicted)\nsvc_acc_score = accuracy_score(y_test, svc_predicted)\nprint(\"confussion matrix\")\nprint(svc_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of Support Vector Classifier:\",svc_acc_score*100,'\\n')\nprint(classification_report(y_test,svc_predicted))\nimp_feature = pd.DataFrame({'Feature': ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach',\n       'exang', 'oldpeak', 'slope', 'ca', 'thal'], 'Importance': xgb.feature_importances_})\nplt.figure(figsize=(10,4))\nplt.title(\"barplot Represent feature importance \")\nplt.xlabel(\"importance \")\nplt.ylabel(\"features\")\nplt.barh(imp_feature['Feature'],imp_feature['Importance'],color = 'rgbkymc')\nplt.show()\nlr_false_positive_rate,lr_true_positive_rate,lr_threshold = roc_curve(y_test,lr_predict)\nnb_false_positive_rate,nb_true_positive_rate,nb_threshold = roc_curve(y_test,nbpred)\nrf_false_positive_rate,rf_true_positive_rate,rf_threshold = roc_curve(y_test,rf_predicted)                                                             \nxgb_false_positive_rate,xgb_true_positive_rate,xgb_threshold = roc_curve(y_test,xgb_predicted)\nknn_false_positive_rate,knn_true_positive_rate,knn_threshold = roc_curve(y_test,knn_predicted)\ndt_false_positive_rate,dt_true_positive_rate,dt_threshold = roc_curve(y_test,dt_predicted)\nsvc_false_positive_rate,svc_true_positive_rate,svc_threshold = roc_curve(y_test,svc_predicted)\n\n\nsns.set_style('whitegrid')\nplt.figure(figsize=(10,5))\nplt.title('Reciver Operating Characterstic Curve')\nplt.plot(lr_false_positive_rate,lr_true_positive_rate,label='Logistic Regression')\nplt.plot(nb_false_positive_rate,nb_true_positive_rate,label='Naive Bayes')\nplt.plot(rf_false_positive_rate,rf_true_positive_rate,label='Random Forest')\nplt.plot(xgb_false_positive_rate,xgb_true_positive_rate,label='Extreme Gradient Boost')\nplt.plot(knn_false_positive_rate,knn_true_positive_rate,label='K-Nearest Neighbor')\nplt.plot(dt_false_positive_rate,dt_true_positive_rate,label='Desion Tree')\nplt.plot(svc_false_positive_rate,svc_true_positive_rate,label='Support Vector Classifier')\nplt.plot([0,1],ls='--')\nplt.plot([0,0],[1,0],c='.5')\nplt.plot([1,1],c='.5')\nplt.ylabel('True positive rate')\nplt.xlabel('False positive rate')\nplt.legend()\nplt.show()\n\"\"\"\n# **Model Evaluation**\n\"\"\"\nmodel_ev = pd.DataFrame({'Model': ['Logistic Regression','Naive Bayes','Random Forest','Extreme Gradient Boost',\n                    'K-Nearest Neighbour','Decision Tree','Support Vector Machine'], 'Accuracy': [lr_acc_score*100,\n                    nb_acc_score*100,rf_acc_score*100,xgb_acc_score*100,knn_acc_score*100,dt_acc_score*100,svc_acc_score*100]})\nmodel_ev\ncolors = ['red','green','blue','gold','silver','yellow','orange',]\nplt.figure(figsize=(12,5))\nplt.title(\"barplot Represent Accuracy of different models\")\nplt.xlabel(\"Accuracy %\")\nplt.ylabel(\"Algorithms\")\nplt.bar(model_ev['Model'],model_ev['Accuracy'],color = colors)\nplt.show()\n\"\"\"\n## **Ensembling**\n\n> **In order to increase the accuracy of the model we use ensembling. Here we use stacking technique.**\n\"\"\"\nscv=StackingCVClassifier(classifiers=[xgb,knn,svc],meta_classifier= svc,random_state=42)\nscv.fit(X_train,y_train)\nscv_predicted = scv.predict(X_test)\nscv_conf_matrix = confusion_matrix(y_test, scv_predicted)\nscv_acc_score = accuracy_score(y_test, scv_predicted)\nprint(\"confussion matrix\")\nprint(scv_conf_matrix)\nprint(\"\\n\")\nprint(\"Accuracy of StackingCVClassifier:\",scv_acc_score*100,'\\n')\nprint(classification_report(y_test,scv_predicted))\n\"\"\"\n# **Conclusion**\n\n1) Extreme Gradient Boost gives the best Accuracy compared to other models.\n\n2) Exercise induced angina,Chest pain is major symptoms of heart attack.\n\n3) Ensembling technique increase the accuracy of the model.\n\n**Feel free to ask any question related to this topic. I'm happy to answer. If you like my work don't hesitate to upvote.**\n\n**HAPPY LEARNING :-)**\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'c7fc47f3751e57'}"}
{"id":"10165","text":"\"\"\"\n**INTRODUCTION**\n\"\"\"\n\"\"\"\n1) Basic\n2) Functions\n\"\"\"\nprint(\"Hello World\")\n\"\"\"\n**2) VARIABLES**\n\"\"\"\n\"\"\"\n*2.1) Strings *:\n\"\"\"\nv_message = \"hello world\"\n\nprint(\"Hi\")\nprint(v_message)\nv_name = \"gazi\"\nv_surname = \"erdogan\"\n\nv_fullname = v_name + v_surname\nprint(v_fullname)\nv_fullname = v_name + \" \" + v_surname\n\nprint(v_fullname)\nv_num1 = \"100\"\nv_num2 = \"200\"\nv_numSum1 = v_num1 + v_num2\nprint(v_numSum1)\n#length\nv_lenFull = len(v_fullname)\nprint(\"v_fullname : \" ,v_fullname, \" and lenght is : \" ,v_lenFull)\nv_titleF = v_fullname.title()\nprint(\"v_fullname :\", v_fullname ,  \" and title is : \" , v_titleF)\n#upper :\nv_upperF = v_fullname.upper()\n\n#lower\nv_lowerF = v_fullname.lower()\nprint(\"v_fullname : \" , v_fullname , \" Upper : \" , v_upperF , \" Lower : \" , v_lowerF)\n\nv_2ch = v_fullname[11]\nprint(v_2ch)\n\"\"\"\n*2.2) NUMBERS :*\n\"\"\"\nv_num1 = 100\nv_num2 = 200\nv_sum1 = v_num1 + v_num2\n\nprint(v_sum1 , \" and  type : \" , type(v_sum1))\n#it will get error\n#v_sum2 = v_num1 + v_name\n#print(v_sum2)\nv_num1 = v_num1 + 50\nv_num2 = v_num2 - 25.5\nv_sum1 = v_num1 + v_num2\n\nprint(v_num1)\nprint(\"v_sum1 : \",v_sum1 , \" type : \" , type(v_sum1))\nv_fl1 = 25.5\nv_fl2 = 15.5\nv_s3 = v_fl1 + v_fl2\n\nprint(v_s3 , type(v_s3))\n\"\"\"\n**2) FUNCTIONS**\n\"\"\"\ndef f_SayHello():\n    print(\"Hi. I am coming from f_SayHello\")\n    \ndef f_SayHello2():\n    print(\"Hi. I am coming from f_SayHello2\")\n    print(\"Good\")\n    \nf_SayHello()\nf_SayHello2()\ndef f_sayMessage(v_Message1):\n    print(v_Message1 , \" came from 'f_sayMessage'\")\n    \ndef f_getFullName(v_FirstName , v_Surname , v_Age):\n    print(\"Welcome \" , v_FirstName , \" \" , v_Surname , \" your age : \" , v_Age)\n    \nf_sayMessage(\"How are you ?\")\nf_getFullName(\"Gazi\" , \"ERDO\u011eAN\" , 36)\ndef f_Calc1(f_Num1 , f_Num2 , f_Num3):\n    v_Sonuc = f_Num1 + f_Num2 + f_Num3\n    print(\"Sonu\u00e7 = \" ,\" \" , v_Sonuc)\n    \nf_Calc1(100 , 250 , 50)\n# return function\ndef f_Calc2(v_Num1 , v_Num2 , v_Num3):\n    v_Out = v_Num1+v_Num2+v_Num3*2\n    print(\"Hi from f_Calc2\")\n    return v_Out\n    \nv_gelen =  f_Calc2(1,2,3)\nprint(\"Score is : \" , v_gelen)\n# Default Functions :\ndef f_getSchoolInfo(v_Name,v_StudentCount,v_City = \"ISTANBUL\"):\n    print(\"Name : \" , v_Name , \" St Count : \" , v_StudentCount \n          , \" City : \" , v_City)\nf_getSchoolInfo(\"AAIHL\" , 521)\nf_getSchoolInfo(\"Ankara Fen\" , 521 , \"ANKARA\")\n# Flexible Functions :\n\ndef f_Flex1(v_Name , *v_messages):\n    print(\"Hi \" , v_Name , \" your first message is : \" , v_messages[2])\nf_Flex1(\"Gazi\" , \"Selam\" , \"Naber\" , \"\u0130yisindir \u0130n\u015fallah\")\n# Lambda Function :\n\nv_result1 = lambda x : x*3\nprint(\"Result is : \" , v_result1(6))\ndef f_alan(kenar1,kenar2):\n    print(kenar1*kenar2)\n    \n    \nf_alan(3,5)","meta":"{'source': 'AI4Code', 'id': '12aa3aaede0dbb'}"}
{"id":"15840","text":"# 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\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\n\"\"\"\n# <font color='#6f7578'>Palmer Archipelago (Antarctica) penguin data EDA and decision tree model<\/font>\n\"\"\"\n\"\"\"\n## <font color='#34b4eb'>Exploration of data set and creation of decision tree model to make prediction on species given penguin features<\/font>\n\"\"\"\ndf = pd.read_csv(\"\/kaggle\/input\/palmer-archipelago-antarctica-penguin-data\/penguins_size.csv\")\ndf.head()\ndf[\"species\"].unique()\ndf.isnull().sum()\ndf.info()\ndf = df.dropna()\ndf.info()\ndf[\"island\"].unique()\ndf[\"sex\"].unique()\ndf[df[\"sex\"] == \".\"]\ndf[df[\"species\"] == \"Gentoo\"].groupby(\"sex\").describe().transpose()\n\"\"\"\n## <font color='#34b4eb'>Given the mean feature values \".\" leans towards being a female<\/font>\n\"\"\"\ndf.at[336,\"sex\"] = \"FEMALE\"  \ndf.loc[336]\nsns.pairplot(df,hue=\"species\",palette=\"Paired\")\nsns.catplot(x=\"species\", y=\"culmen_length_mm\", data=df, kind=\"box\", col=\"sex\", palette=\"Paired\")\ndf.head()\n\"\"\"\n## <font color='#34b4eb'>Create dummy variables and drop the label<\/font>\n\"\"\"\nX = pd.get_dummies(df.drop(\"species\", axis=1), drop_first=True)\nX\ny = df[\"species\"]\ny\n\"\"\"\n## <font color='#34b4eb'>NB - no scaling of data required for decision tree algorithm<\/font>\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n# train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)\nfrom sklearn.tree import DecisionTreeClassifier\n\"\"\"\n## <font color='#34b4eb'>Will just create the model with default hyperparameters<\/font>\n\"\"\"\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train,y_train)\nbase_preds = model.predict(X_test)\nbase_preds\nfrom sklearn.metrics import classification_report, plot_confusion_matrix\nprint(classification_report(y_test,base_preds))\nplot_confusion_matrix(model,X_test,y_test,cmap=\"Accent\")\n\"\"\"\n## <font color='#34b4eb'>Only 3 penguins were misclassified<\/font>\n\"\"\"\nmodel.feature_importances_\nX.columns\npd.DataFrame(index=X.columns, data=model.feature_importances_)\npd.DataFrame(index=X.columns, data=model.feature_importances_,columns=[\"feature importance\"]).sort_values(\"feature importance\")\nfrom sklearn.tree import plot_tree\nplt.figure(figsize=(11,11),dpi=150)\nplot_tree(model,feature_names=X.columns, filled=True);","meta":"{'source': 'AI4Code', 'id': '1ce678aebb7f0a'}"}
{"id":"31803","text":"\"\"\"\n\n---\n\n<h1 style=\"text-align: center;font-size: 40px;\">Sign Language Classification using CNN<\/h1>\n\n---\n\n<center><img src=\"https:\/\/www.dictionary.com\/e\/wp-content\/uploads\/2018\/01\/american_sign_language4-790x310.jpg\n\"width=\"500\" height=\"600\"><\/center>\n\n---\n\n\n\n\"\"\"\n\"\"\"\n#### Dataset Info:\n\n- The dataset format is patterned to match closely with the classic MNIST. Each training and test case represents a label (0-25) as a one-to-one map for each alphabetic letter A-Z (and no cases for 9=J or 25=Z because of gesture motions). The training data (27,455 cases) and test data (7172 cases) are approximately half the size of the standard MNIST but otherwise similar with a header row of label, pixel1,pixel2\u2026.pixel784 which represent a single 28x28 pixel image with grayscale values between 0-255. The original hand gesture image data represented multiple users repeating the gesture against different backgrounds. The Sign Language MNIST data came from greatly extending the small number (1704) of the color images included as not cropped around the hand region of interest. To create new data, an image pipeline was used based on ImageMagick and included cropping to hands-only, gray-scaling, resizing, and then creating at least 50+ variations to enlarge the quantity. The modification and expansion strategy was filters ('Mitchell', 'Robidoux', 'Catrom', 'Spline', 'Hermite'), along with 5% random pixelation, +\/- 15% brightness\/contrast, and finally 3 degrees rotation. Because of the tiny size of the images, these modifications effectively alter the resolution and class separation in interesting, controllable ways.\n\"\"\"\n# 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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom sklearn.preprocessing import LabelBinarizer\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Flatten,Dense,Dropout,MaxPool2D,Conv2D\n\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\ndf_train = pd.read_csv(\"\/kaggle\/input\/sign-language-mnist\/sign_mnist_train\/sign_mnist_train.csv\")\ndf_train.head()\ndf_test = pd.read_csv(\"\/kaggle\/input\/sign-language-mnist\/sign_mnist_test\/sign_mnist_test.csv\")\ndf_test.head()\ndf_train.describe()\ndf_train.info()\ndf_test.info()\ntrain_label = df_train[\"label\"]\ntest_label = df_test[\"label\"]\nplt.style.use(\"ggplot\")\nplt.figure(figsize =(9,5))\nsns.countplot(x= df_train['label'],data = df_train)\nplt.show()\ndf_train.drop(\"label\",axis=1,inplace=True)\ndf_train.head()\ndf_test.drop(\"label\",axis=1,inplace=True)\ndf_test.head(2)\nx_train = df_train.values\nx_train\nx_train = x_train.reshape(-1,28,28,1)\nx_test = df_test.values.reshape(-1,28,28,1)\n\"\"\"\n### One Hot Encoding:\n\n- Converting integer labels into binary Form using Label Binarizer\n\"\"\"\nlb = LabelBinarizer()\ny_train = lb.fit_transform(train_label)\ny_test = lb.fit_transform(test_label)\nplt.figure(figsize=(9,7))\nfor i in range(6):\n    plt.subplot(2,3,i+1)\n    plt.imshow(x_train[i],cmap='gray')\n    plt.xlabel(np.argmax(y_train[i]))\n    \nplt.show()\n\"\"\"\n#### Data Augmentation:\n\"\"\"\ntrain_datagen = ImageDataGenerator(rescale=(1.\/255),rotation_range = 30,\n                                  width_shift_range = 0.2,height_shift_range =0.2,\n                                  shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\n\nval_datagen = ImageDataGenerator(rescale=(1.\/255))\n\"\"\"\n#### Model Building:\n\"\"\"\nfrom tensorflow.keras import Sequential\nmodel = Sequential()\nmodel.add(Conv2D(32,(3,3),padding = 'same',input_shape=(28,28,1),activation = 'relu'))\nmodel.add(MaxPool2D((2,2)))\n\nmodel.add(Conv2D(64,(3,3),padding = 'same',activation = 'relu'))\nmodel.add(MaxPool2D((2,2)))\n\nmodel.add(Conv2D(128,(3,3),padding = 'same',activation = 'relu'))\nmodel.add(MaxPool2D((2,2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dense(24,activation=\"softmax\"))\nmodel.summary()\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics='accuracy')\nfrom tensorflow.keras.callbacks import ModelCheckpoint,EarlyStopping\n\ncheckpoint = ModelCheckpoint('sign_lan.h5',monitor ='val_acc',verbose=1,save_best_only=True,mode='max')\nearlystop = EarlyStopping(monitor = 'val_acc',verbose=1,mode='max')\nhistory = model.fit_generator(generator = train_datagen.flow(x_train,y_train,batch_size=32),\n                              validation_data = val_datagen.flow(x_test,y_test),epochs=15,verbose=1)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nloss,acc = model.evaluate_generator(val_datagen.flow(x_test,y_test))\nprint(f\"Accuracy: {acc*100}\")\nprint(f\"Loss: {loss}\")\nx_test = x_test\/255.\ny_pred = model.predict_classes(x_test)\ny_te = np.argmax(y_test,axis=1)\ny_te\nfrom sklearn.metrics import accuracy_score\naccuracy_score(y_te,y_pred)\n\"\"\"\n#### Confusion Matrix:\n\"\"\"\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(y_te,y_pred))\n\"\"\"\n#### Models Performance:\n\"\"\"\nplt.figure(figsize=(12,8))\nfor i in range(10):\n    plt.subplot(2,5,i+1)\n    plt.imshow(x_test[i],cmap='gray')\n    plt.xlabel(f\"Actual: {y_te[i]}\\n Predicted: {y_pred[i]}\")\n    \nplt.tight_layout()\nplt.show()","meta":"{'source': 'AI4Code', 'id': '3a8d4f48780b17'}"}
{"id":"28677","text":"import numpy as np # linear algebra\nimport random\nimport pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)\nimport os\nimport tensorflow as tf\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimport cv2\nimport shutil\nfrom glob import glob\n# Helper libraries\nimport matplotlib.pyplot as plt\nimport math\n%matplotlib inline\nprint(tf.__version__)\ndata_root='\/kaggle\/input\/covidct\/'\npath_positive_cases = os.path.join('\/kaggle\/input\/covidct\/CT_COVID\/')\npath_negative_cases = os.path.join('\/kaggle\/input\/covidct\/CT_NonCOVID\/')\n\"\"\"\n### Datasets Overview \n\"\"\"\n# jpg and png files\npositive_images_ls = glob(os.path.join(path_positive_cases,\"*.png\"))\n\nnegative_images_ls = glob(os.path.join(path_negative_cases,\"*.png\"))\nnegative_images_ls.extend(glob(os.path.join(path_negative_cases,\"*.jpg\")))\ncovid = {'class': 'CT_COVID',\n         'path': path_positive_cases,\n         'images': positive_images_ls}\n\nnon_covid = {'class': 'CT_NonCOVID',\n             'path': path_negative_cases,\n             'images': negative_images_ls}\ntotal_positive_covid = len(positive_images_ls)\ntotal_negative_covid = len(negative_images_ls)\nprint(\"Total Positive Cases Covid19 images: {}\".format(total_positive_covid))\nprint(\"Total Negative Cases Covid19 images: {}\".format(total_negative_covid))\nimage_positive = cv2.imread(os.path.join(positive_images_ls[1]))\nimage_negative = cv2.imread(os.path.join(negative_images_ls[5]))\n\nf = plt.figure(figsize=(8, 8))\nf.add_subplot(1, 2, 1)\nplt.imshow(image_negative)\nf.add_subplot(1,2, 2)\nplt.imshow(image_positive)\nprint(\"Image COVID Shape {}\".format(image_positive.shape))\nprint(\"Image Non COVID Shape {}\".format(image_negative.shape))\n\"\"\"\n### Create Train-Test Directory \n\"\"\"\n# Create Train-Test Directory\nsubdirs  = ['train\/', 'test\/']\nfor subdir in subdirs:\n    labeldirs = ['CT_COVID', 'CT_NonCOVID']\n    for labldir in labeldirs:\n        newdir = subdir + labldir\n        os.makedirs(newdir, exist_ok=True)\n# Copy Images to test set\n\n# seed random number generator\nrandom.seed(237)\n# define ratio of pictures used for testing \ntest_ratio = 0.2\n\n\nfor cases in [covid, non_covid]:\n    total_cases = len(cases['images']) #number of total images\n    num_to_select = int(test_ratio * total_cases) #number of images to copy to test set\n    \n    print(cases['class'], num_to_select)\n    \n    list_of_random_files = random.sample(cases['images'], num_to_select) #random files selected\n\n    for files in list_of_random_files:\n        shutil.copy2(files, 'test\/' + cases['class'])\n# Copy Images to train set\nfor cases in [covid, non_covid]:\n    image_test_files = os.listdir('test\/' + cases['class']) # list test files \n    for images in cases['images']:\n        if images.split('\/')[-1] not in (image_test_files): #exclude test files from shutil.copy\n            shutil.copy2(images, 'train\/' + cases['class'])\ntotal_train_covid = len(os.listdir('\/kaggle\/working\/train\/CT_COVID'))\ntotal_train_noncovid = len(os.listdir('\/kaggle\/working\/train\/CT_NonCOVID'))\ntotal_test_covid = len(os.listdir('\/kaggle\/working\/test\/CT_COVID'))\ntotal_test_noncovid = len(os.listdir('\/kaggle\/working\/test\/CT_NonCOVID'))\n\nprint(\"Train sets images COVID: {}\".format(total_train_covid))\nprint(\"Train sets images Non COVID: {}\".format(total_train_noncovid))\nprint(\"Test sets images COVID: {}\".format(total_test_covid))\nprint(\"Test sets images Non COVID: {}\".format(total_test_noncovid))\n\"\"\"\n### Simple CNN Model\n[Tensorflow Tutorial](https:\/\/www.tensorflow.org\/tutorials\/images\/classification)\n\"\"\"\nbatch_size = 128\nepochs = 15\nIMG_HEIGHT = 150\nIMG_WIDTH = 150\ntrain_image_generator = ImageDataGenerator(rescale=1.\/255) # Generator for our training data\ntest_image_generator = ImageDataGenerator(rescale=1.\/255) # Generator for our validation data\ntrain_dir = os.path.join('\/kaggle\/working\/train')\ntest_dir = os.path.join('\/kaggle\/working\/test')\n\n\ntotal_train = total_train_covid + total_train_noncovid\ntotal_test = total_test_covid + total_test_noncovid\ntrain_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,\n                                                           directory=train_dir,\n                                                           shuffle=True,\n                                                           target_size=(IMG_HEIGHT, IMG_WIDTH),\n                                                           class_mode='binary')\ntest_data_gen = test_image_generator.flow_from_directory(batch_size=batch_size,\n                                                              directory=test_dir,\n                                                              target_size=(IMG_HEIGHT, IMG_WIDTH),\n                                                              class_mode='binary')\nmodel = Sequential([\n    Conv2D(32, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3)),\n    MaxPooling2D(2, 2),\n    Conv2D(64, 3, padding='same', activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(64, 3, padding='same', activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dense(1)\n])\nmodel.compile(optimizer='adam',\n              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n              metrics=['accuracy'])\nmodel.summary()\nhistory = model.fit_generator(\n    train_data_gen,\n    steps_per_epoch=total_train \/\/ batch_size,\n    epochs=epochs,\n    validation_data=test_data_gen,\n    validation_steps=total_test \/\/ batch_size\n)\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\"\"\"\nVoil\u00e0! By modifying the CNN we obtain a clear improvement in performance on the validation set\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '34b235d51256cd'}"}
{"id":"51429","text":"\"\"\"\n## <font color='red'>DISCLAIMER: If you want to run our system with your own input, we have mentioned in RED, the cells you need to run. Thank you! <\/font>\n\"\"\"\n\"\"\"\n# Introduction:\nWith the growing risk of fast pace spread of COVID-19 across the globe, there is an extreme need for potential way forward or approaches to break the chain if not cure. Currently, there is significant research & literature around the similar situation during previous epidemics spread which may not be specific for current situation but still very valuable. This might provide us with right approaches and improved policy measures which will aid us to fight this battle. We, as AI & NLP researchers, hope to leverage this research, ideas, reports or any data to find close to accurate and quickly actionable insights to control the spread via medical or non-Pharma interventions.\n\nWith this, we hope to bring in our approach \/ engine which can help community members to find right literature using the methods of NLP, Deep Learning & Search. The approach mainly uses Facebook AI Similarity Search (FAISS) for indexing documents and Google's Universal Sentence Encoder for the text embeddings.\n\nThe approach was designed keeping in mind the task of finding the right insights for \u201cWhat do we know about non-pharmaceutical interventions?\u201d but we expanded its reach to solve sub-questions or any relevant questions from all 10 tasks specified in CORD-19 Challenge by Kaggle community.\n\"\"\"\n\"\"\"\n# Team members:\nWe, the Text Analytics team, are pleased to provide to the Kaggle community, an Information Retrieval system using NLP, Machine Learning and Deep Learning techniques.  \n\n[Bharat Hegde], [Rohit Rangarajan], [Prathamesh Karmalkar], [Harsha Gurulingappa], [Gerard Megaro]\n\"\"\"\n\"\"\"\n# Problem statement:\nWe started with the goal of solving the task \"What do we know about non-pharmaceutical interventions?\", but ended up developing a solution which would work across all given tasks and questions.\n\"\"\"\n\"\"\"\n# Our approach:\n* We extract docs from the dataset using NLTK, Theme Extractor (proprietary algorithm to be published in September 2020) and JSON parser. Each doc is a json object of the form:\n        {\n            'sentence': '....',\n            'section': '....',\n            'paper_title': '....',\n            'authors': [],\n            'paragraph': '....',\n            'themes': []\n        }\n* The themes are identified from the abstract of the paper in which the sentence appears.        \n\n* Once all docs are extracted, we obtain the sentence embeddings for all sentences extracted from each of these docs, using Google\u2019s Universal Sentence Encoder. \n\n* We then index all the embeddings into one of the available FAISS indexes, called the ScalarQuantizer (https:\/\/github.com\/facebookresearch\/faiss\/wiki\/Faiss-building-blocks:-clustering,-PCA,-quantization).  \n\n* Then, when user makes a query, we convert the query to its text embedding using the same Universal Sentence Encoder and query our index. \n\n* The index returns the id of the embeddings (along with L2 distance) which are most similar to the query embedding. We then map those ids to the corresponding doc objects to display the details to the user.\n\n* We also provide additional information, such as the paragraph context in which the sentence appears, the paper containing the sentence, the authors of the paper, title of that paper, and section name. Therefore the  user can look into the paper for more detais regarding the query.\n\n* We also provide a ThemeCloud which gives a pictorial representation of the themes being talked about in the paper.  \n\"\"\"\n\"\"\"\n# Our approach:\n\"\"\"\n\"\"\"\n![flowchart.png](attachment:flowchart.png)\n\"\"\"\n\"\"\"\n# Indexing stage\n\"\"\"\n\"\"\"\n![diagram1.png](attachment:diagram1.png)\n\"\"\"\n\"\"\"\n# Querying stage\n\"\"\"\n\"\"\"\n![diagram2.png](attachment:diagram2.png)\n\"\"\"\n\"\"\"\n## Dataset: \n\n33375 papers across 4 folders: \n\n* biorxiv_medrxiv - 1053 papers\n\n* comm_use_subset - 9315 papers\n\n* custom_license - 20657 papers\n\n* noncom_use_subset - 2350 papers\n\n\"\"\"\n\"\"\"\n# Algorithm for theme extraction:\nTheme extraction helps to define the context and content of a conversation providing a highly valuable combination of contextual phrases. Phrase themes provide an excellent view of the context of conversation and is useful on all content length from one line to hundred-page document. Theme identification is one of the most fundamental tasks in qualitative research. System takes unstructured data as input and extracts semantic themes based on context of the data.\n\nStep 1: Pre-process the input verbatim for identifying the themes\n\nStep 2: Identify & split verbatim into multiple sentences to identify individual themes at sentence level (Themes specific to each question)\n\nStep 3: Algorithm extracts the themes using tokenization, PoS tags, chunks, dependency parse tree as features of the input verbatim.\n\nStep 4: Extract first set of themes from input verbatim\n\nStep 5: Algorithm uses heuristic approach to prune contextually less significant chains from the extracted theme set\n\n## The code below makes use of our internal tool for extracting themes from text. This will not work in external networks. It has been provided only for documentation purposes.\n\"\"\"\nimport requests\nimport json\n\nheaders = {'accept': 'application\/json','Content-Type': 'text\/plain'}\nparams = (('annotationTypes', '*'),('language', 'en'))\n\ndef get_json_object(text):\n    return requests.post('<our url>', headers=headers, params=params, data=text).json()\n\n# Output: json string\ndef get_json_str(json_obj):\n    return json.dumps(json_obj)\n\n# Output: beautified json string\ndef get_pretty_json(json_str):\n    return json.dumps(json_str, indent=4)\n\n# Output: List of themes\ndef get_themes(text):\n    json_obj = get_json_object(text)\n    json_array = json_obj[\"annotationDtos\"]\n    return json_array[-1][\"themes\"]\n\"\"\"\n# Download Google Universal Sentence Encoder for extracting sentence embedding from text\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\nimport tensorflow_hub as hub\nembed = hub.load(\"https:\/\/tfhub.dev\/google\/universal-sentence-encoder\/4\")\n\"\"\"\n# Define function to join words in a list into one string\n### This method is useful when extracting author names from the provided json files\n\"\"\"\ndef lst_to_str(word_list):\n    return ' '.join(word_list).strip()\n\"\"\"\n# Collect sentences as python list\n#### In the below code, we make use of NLTK's sentence tokenizer to extract sentences out of paragraphs. We also tried spaCy's tokenizer, but found this to be faster.\n\"\"\"\nimport numpy as np\nimport json\nimport os\nimport csv\nimport time\nfrom nltk.tokenize import sent_tokenize\n\nroot = '\/kaggle\/input\/dataset\/CORD-19-research-challenge\/'\nfolders = ['biorxiv_medrxiv\/biorxiv_medrxiv\/', 'comm_use_subset\/comm_use_subset\/', \n           'noncomm_use_subset\/noncomm_use_subset\/', 'custom_license\/custom_license\/']\n\n\ndef collect_sentences():\n    index_in_docs = 0\n    num_files_processed = 0\n    sentences_np_array = np.empty(100000000, dtype=object)\n\n    start = time.time()\n    for folder in folders:\n        for filename in os.listdir(root+folder):\n            if filename.endswith(\".json\"): \n                input_file_path = root+folder+filename\n                with open(input_file_path) as f:\n                    data = json.load(f)\n\n                    # Collect abstract sentences\n                    abstracts = data['abstract']\n                    for content in abstracts:\n                        abstract_para = content['text']\n                        sentences = sent_tokenize(abstract_para)\n                        for sentence in sentences:\n                            sentences_np_array[index_in_docs] = sentence\n                            index_in_docs += 1\n\n                    # Collect body sentences\n                    body_texts = data['body_text']\n                    for content in body_texts:\n                        body_para = content['text']\n                        sentences = sent_tokenize(body_para)\n                        for sentence in sentences:\n                            sentences_np_array[index_in_docs] = sentence\n                            index_in_docs += 1\n                num_files_processed += 1            \n                print('Num files processed: ' + str(num_files_processed))\n                print('Time taken since beginning = ' + str(time.time()-start))\n    np.save('sentences.npy', sentences_np_array) \n\"\"\"\n# Collect json docs\n#### The lines calling the get_themes() method have been commented since the method will only work in our internal environment\n\"\"\"\nimport json\nimport os\nimport csv\nimport time\nfrom nltk.tokenize import sent_tokenize\n\nroot = '\/kaggle\/input\/dataset\/CORD-19-research-challenge\/'\nfolders = ['biorxiv_medrxiv\/biorxiv_medrxiv\/', 'comm_use_subset\/comm_use_subset\/', \n           'noncomm_use_subset\/noncomm_use_subset\/', 'custom_license\/custom_license\/']\n\ndef collect_json_docs():\n    docs = np.empty(100000000, dtype=np.object) \n\n    index_in_docs = 0\n    num_files_processed = 0\n    num_docs_collected = 0\n\n    start = time.time()\n    for folder in folders:\n        for filename in os.listdir(root+folder):\n            if filename.endswith(\".json\"): \n                input_file_path = root+folder+filename\n                print(input_file_path)\n                with open(input_file_path) as f:\n                    data = json.load(f)\n\n                    # Collect paper title\n                    paper_title = data['metadata']['title']\n\n                    # Collect authors' names\n                    authors = data['metadata']['authors']\n                    authors_names = []\n\n                    for author in authors:\n                        first_name = author['first']\n                        middle_name = author['middle']\n                        last_name = author['last']\n                        author_name = first_name + ' ' + lst_to_str(middle_name) + ' ' + last_name\n                        authors_names.append(author_name)\n\n                    # Collect abstract sentences\n                    abstracts = data['abstract']\n                    for content in abstracts:\n                        abstract_para = content['text']\n                        section = content['section']\n                        sentences = sent_tokenize(abstract_para)\n    #                     para_themes = get_themes(abstract_para)\n                        for sentence in sentences:\n                            new_doc = {\n                                \"sentence\": sentence,\n                                \"section\": section,\n                                \"paper_title\": paper_title,\n                                \"authors\": authors_names,\n                                \"paragraph\": abstract_para\n    #                             \"para_themes\": para_themes\n                            }\n                            print(new_doc)\n                            docs[index_in_docs] = new_doc\n                            index_in_docs += 1\n                            num_docs_collected += 1\n\n                    # Collect body sentences\n                    body_texts = data['body_text']\n                    for content in body_texts:\n                        body_para = content['text']\n                        section = content['section']\n                        sentences = sent_tokenize(body_para)\n    #                     para_themes = get_themes(body_para)\n                        for sentence in sentences:\n                            new_doc = {\n                                \"sentence\": sentence,\n                                \"section\": section,\n                                \"paper_title\": paper_title,\n                                \"authors\": authors_names,\n                                \"paragraph\": body_para\n    #                             \"para_themes\": para_themes\n                            }\n                            print(new_doc)\n                            docs[index_in_docs] = new_doc\n                            index_in_docs += 1\n                            num_docs_collected += 1\n                num_files_processed += 1\n\n    np.save('docs', docs) # by default, allow pickle = True\n\"\"\"\n# Load docs.npy\n### docs.npy file contains json objects - each json object contains the section_name, author names, paper title, sentence, themes, and paragraph in which the sentence occurs.\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\nimport numpy as np\ndocs = np.load('\/kaggle\/input\/jsondocs\/docs.npy', allow_pickle=True)\n\"\"\"\n# Why Google's Universal Sentence Encoder?\n\n    We tried Sentence Transformer for the embeddings, it had 768 dimension representation and \n    thus it occupied more size (768 * ~ 7 million sentences = 18 GB approx). Also, time taken \n    to generate the embeddings for 7 million sentences was around 3.5 hours with K80 GPU on AWS Sagemaker.\n    You can refer to Sentence Tranformer here: https:\/\/github.com\/UKPLab\/sentence-transformers\n    \n    But in case of Google Universal Sentence Encoder, it has 512 dimensional vector embedding \n    for each sentence, thereby occupying less space (512 * ~ 7 million sentences = 12 GB approx), \n    but equally effective as Sentence Transformer. Time complexity is O(n)(n is length of sentence).\n    Embeddings were computed on Sagemaker, with configuration 8 virtual CPUs, one V100 GPU of \n    16 GB memory, and 61 GB RAM. This took around 20 minutes to compute all embeddings - way faster. \n    It took 1325 seconds to compute 7191466 embeddings.    \n\"\"\"\n\"\"\"\n# Extract embeddings from the 'sentence' field of docs collected above - using Google Universal Sentence Encoder - and save them!\n\n\"\"\"\n\"\"\"\n### Extract the sentences from docs loaded above\n\"\"\"\ndef collect_sentences():\n    sentences=[]\n    for jsonobject in docs:\n        sentences.append(jsonobject['sentence'])\n\"\"\"\n### Generate embeddings for sentences collected above. We ran the below code in AWS Sagemaker because of RAM issue in Kaggle (resource exhausted error). Total size of embeddings.npy was around 12 GB. It is removed from notebook because of lack of space.\n\"\"\"\nimport tensorflow as tf\nimport time\n\n \ndef generate_embeddings():\n    start = time.time()\n    index=0\n    batch_size = 3000\n    num_rows=len(sentences)\n\n\n    embeddings = np.empty((num_rows,512), dtype=np.float32)\n    while index < num_rows:\n        end_index = index+batch_size\n        if end_index > num_rows:\n            break\n        embeddings[index:end_index,:] = embed(sentences[index:end_index])\n        index += batch_size\n\n    if index < num_rows:\n        embeddings[index:num_rows,:] = embed(sentences[index:num_rows])\n\n    np.save('embeddings\/embeddings.npy', embeddings) # removed from working directory\n\"\"\"\n# Why FAISS for indexing the embeddings?\nFaiss is a library developed by Facebook AI Research, for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. Faiss provides lightning fast search through 1 billion vectors.\n\nTotal size of the index after indexing the embeddings was around 12 GB. Faiss provides a Scalar Quantization technique using which we were able to reduce the size to around 3 GB (32 bit float to 6 bit representation).\n\nWe used L2 euclidean distance provided by FAISS, for computing distance between embeddings. Since we are computing similarity using L2 distance, loss of accuracy due to quantization does not affect query results. \n\n\nSearch operation in our case is linear and time complexity is O(n)(n is total number of embeddings indexed).\n\"\"\"\n\"\"\"\n# Install FAISS to use GPU\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\n!python -m pip install --upgrade faiss faiss-gpu\n\"\"\"\n# Load embeddings from npy file and index the embeddings into FAISS, and save the index in correct directory. \n### Please note: 'embeddings.npy' file is not available in notebook - so this cell will throw an error. \n### Index was created in AWS Sagemaker and uploaded in data directory in \/kaggle\/input\/vector\/vector_6.index\n\n\"\"\"\nimport numpy as np\nimport faiss\n\ndef create_index():\n    embeddings = np.load('embeddings\/embeddings.npy',mmap_mode='r')\n    index = faiss.IndexScalarQuantizer(512,faiss.ScalarQuantizer.QT_6bit) \n    index.train(embeddings)\n    index.add(embeddings)\n\n    faiss.write_index(index, \"vector_6.index\")\n\"\"\"\n# Search docs matching user query\n\"\"\"\n\"\"\"\n## Load index from directory where it was saved. Index can be saved and loaded from disk.\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\nimport faiss\nindex = faiss.read_index(\"\/kaggle\/input\/vector\/vector_6.index\", faiss.IO_FLAG_MMAP|faiss.IO_FLAG_READ_ONLY)  # load the index\n\"\"\"\n## Search the index\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\nimport time\nquery = [\"What has been published concerning research and development and evaluation efforts of vaccines and therapeutics for COVID-19?\"]\nquery_vector = embed(query)\nquery_vector = np.asarray(query_vector, dtype=np.float32)\n\nstart = time.time()\nD, I = index.search(query_vector, 10)  \n\"\"\"\n# Visualize the results!\n\"\"\"\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\n!pip install json2html\nfrom wordcloud import WordCloud, STOPWORDS \nimport matplotlib.pyplot as plt \nimport pandas as pd \nfrom json2html import *\nfrom IPython.core.display import display, HTML\n\"\"\"\n## <font color='red'>RUN BELOW CELL! ---> <\/font>\n\"\"\"\nstopwords = set(STOPWORDS)\n\nfor id_index in I[0]:\n    doc = docs[id_index]\n    html = json2html.convert(doc)\n    html = html.replace(\"<td>\", \"<td style='text-align:left'>\")\n    display(HTML(html))\n    themes_list = doc['themes']\n    final_theme_string = ''\n    for theme in themes_list:\n        words = theme.replace('-', ' ').split()\n        t = '_'.join(words)\n        final_theme_string = final_theme_string + ' ' + t\n        \n    # plot the WordCloud image  \n    if doc['themes'] and doc['themes'][0]:\n        wordcloud = WordCloud(width = 700,height = 200,stopwords = stopwords,min_font_size = 8, \n                              max_font_size=20, background_color='white', \n                              prefer_horizontal=1).generate(final_theme_string)\n        plt.figure(figsize = (10, 10), linewidth=10, edgecolor=\"#04253a\")\n        plt.imshow(wordcloud, interpolation=\"bilinear\") \n        plt.axis(\"off\") \n        plt.show() \n    display(HTML(\"<hr style='height:3px; color:black'>\"))\n\"\"\"\n# Write to excel sheet\n\"\"\"\nimport pandas as pd\nwriter = pd.ExcelWriter('QueryResult1.xlsx', engine='xlsxwriter')\n\ndef writepaperdetails(query,retrivallines,subquestion):\n    print(subquestion)\n    print(retrivallines)\n    Rpaper_title=[]\n    Rsection=[]\n    Rsentence=[]\n    Rparagraph=[]\n    Rthemes=[]\n   \n    for retrivalline in retrivallines:\n        Rpaper_title.append(docs[retrivalline]['paper_title'])\n        Rsection.append(docs[retrivalline]['section'])\n        Rsentence.append(docs[retrivalline]['sentence'])\n        Rparagraph.append(docs[retrivalline]['paragraph'])\n        Rthemes.append(docs[retrivalline]['themes'])\n       \n    df = pd.DataFrame()\n    dfquery=pd.DataFrame()\n    df['PAPER_TITLE']=Rpaper_title\n    df['SECTION']=Rsection\n    df['SENTENCE']=Rsentence\n    df['PARAGRAPH']=Rparagraph\n    df['THEMES']=Rthemes\n    dfquery['QUERY']=[query]\n   \n   \n    dfquery.to_excel(writer, sheet_name=\"QUERY_\"+str(subquestion))\n    df.to_excel(writer, sheet_name=\"QUERY_\"+str(subquestion),startrow=4)\ndef generate_excel_files(query, I):\n    for i,q in enumerate(query):\n        writepaperdetails(q,I.tolist()[i],i)\n    writer.save()\n\"\"\"\n# Pros and cons of our approach:\n## Pros:\n* Using embeddings at a sentence level helps to capture maximum information, and thus is highly effective when searching for contextually similar sentences. Representing the documents at paragraph level (with fixed vector or average of sentence embeddings) causes loss of information. Hence sentence-level embeddings helps us.\n\n* Even though we end up in more number of embeddings due to more number of sentences (compared to number of paragraphs), the query results are very accurate.\n\n* Scalable approach to information retrieval\n\n## Cons:\n* Response time after query execution is a bit slow currently, due to the index we are using - it takes on an average 75 seconds for response\n* Hard disk and RAM space is crucial for our approach - to store embeddings, index, text documents, etc. and also to compute embeddings\n* Recommendation for Kaggle: We had to make use of AWS Sagemaker, which is a costly affair. Please provide better RAM support.\n* The dataset has now been increased to more papers, but we are not using the latest dataset due to storage constraints on Kaggle\n\n\"\"\"\n\"\"\"\n## Further scope of our project:\n* Extend our approach to work with the latest dataset - additional 40k papers approx\n* Re-rank the query results to answer specific questions by considering keywords - for eg. If a query contains 'covid-19' or 'coronavirus', it is possible in our approach that some results related to pneumonia or ebola could come up.\n* Quantitative data like time, number of patients, number of beds, etc. can be extracted from the query results\n* Experiment with other index types that FAISS supports\n* Searching can done faster by applying clustering on fiass indexes and search only the specific cluser whose centroid is closest to the query embedding.\n* Product Quantizers in FAISS can be used for further compression of the index.\n\"\"\"\n\"\"\"\n# Results for tasks in excel files:\nClick on the results corresponding to each task to see results fetched by our system for each subquestion in the task. \n\n## <font color='blue'>NOTE: Papers which do not have 'abstract' section won't have themes and thus you will be able to see empty cells in 'themes' column when such papers are returned by the system - since we obtain themes from abstract.<\/font>\n\"\"\"\n\"\"\"\nTask1: What is known about transmission, incubation, and environmental stability?\n\n[Task1 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_1.xlsx)\n\"\"\"\n\"\"\"\nTask2: What do we know about COVID-19 risk factors?\n\n[Task2 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_2.xlsx)\n\"\"\"\n\"\"\"\nTask3: What do we know about virus genetics, origin, and evolution?\n\n[Task3 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_3.xlsx)\n\"\"\"\n\"\"\"\nTask4: What do we know about vaccines and therapeutics?\n\n[Task4 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_4.xlsx)\n\"\"\"\n\"\"\"\nTask5: What has been published about medical care?\n\n[Task5 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_5.xlsx)\n\"\"\"\n\"\"\"\nTask6: What do we know about non-pharmaceutical interventions?\n\n[Task6 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_6.xlsx)\n\"\"\"\n\"\"\"\nTask8: What do we know about diagnostics and surveillance?\n\n[Task8 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_8.xlsx)\n\"\"\"\n\"\"\"\nTask9: What has been published about ethical and social science considerations?\n    \n[Task9 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_9.xlsx)    \n\"\"\"\n\"\"\"\nTask10: What has been published about information sharing and inter-sectoral collaboration?\n\n[Task10 results](https:\/\/sagemaker-eu-central-1-922643591083.s3.eu-central-1.amazonaws.com\/KaggleOut\/QueryResult_TASK_10.xlsx)\n\"\"\"\n\"\"\"\n# References:\n1. FAISS: https:\/\/engineering.fb.com\/data-infrastructure\/faiss-a-library-for-efficient-similarity-search\/ \n\n2. Universal Sentence Encoder: https:\/\/tfhub.dev\/google\/universal-sentence-encoder\/4 \n\n3. ThemeCloud\/WordCloud: https:\/\/amueller.github.io\/word_cloud\/generated\/wordcloud.WordCloud.html \n\n4. spaCy: https:\/\/spacy.io\/\n\n5. NLTK: https:\/\/www.nltk.org\/\n\n6. Sentence Transformer: https:\/\/github.com\/UKPLab\/sentence-transformers\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '5e9e04ed9ad258'}"}
{"id":"96014","text":"\"\"\"\n**Seminar Arbeit**\n\nIn diesem Notebook wird zum Einen die von Kaggle bereitgestellte \u00dcbung und zum Anderen selbst erlerntes Wissen verwendet, um einen von uns ausgew\u00e4hlten Datensatz zu bearbeiten. Der Datensatz enth\u00e4lt \u00fcber 16.000 Daten \u00fcber Videospiele und deren Einnahmen am Markt.\n\"\"\"\n# 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 in \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 \"..\/input\/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"..\/input\"))\n\n# Any results you write to the current directory are saved as output.\n\"\"\"\nZun\u00e4chst werden einige Pakete ben\u00f6tigt. Diese sind allerdings von Anfang an importiert und es musste keine \u00c4nderung vorgenommen werden. Die print-Funktion zeigt lediglich an, welche Dateien sich in dem Pfad befinden. Hier befindet sich unsere csv-Datei, welche im n\u00e4chsten Schritt in die Variable \"vgd\" geladen und aufgerufen wird.\n\"\"\"\n# Dateipfad in einer Variable speichern\nvideo_games_path = '..\/input\/Video_Games_Sales_as_at_22_Dec_2016.csv'\n# Daten auslesen\nvgd = pd.read_csv(video_games_path)\n# Zusammenfassung der Daten ausgeben\nvgd.describe()\n\"\"\"\nDie \u00dcbersicht der Daten ist sehr \u00e4hnlich wie die der \u00dcbung. Auch hier ist auf den ersten Blick zu erkennen, dass einige Spalten nicht vollst\u00e4ndig mit Daten bef\u00fcllt sind (z.B. Critic_Score). F\u00fcr ein Seminar an der FH-Wedel k\u00f6nnten bereits zu Anfang einige Fragen gestellt werden, damit sich die Studenten n\u00e4her mit den Daten besch\u00e4ftigen.\n\n- Wie viele Daten sind vorhanden?\n- Wie ist der durchschnittliche Critic Score?\n- Wie alt ist das \u00e4lteste Spiel in dem Datensatz?\n\"\"\"\n\"\"\"\nDie unten stehende Funktion ist ein zusammenfassender Aufruf der Spaltennamen:\n\"\"\"\nvgd.columns\n\"\"\"\n**Daten f\u00fcr das Modell ausw\u00e4hlen**\n\nF\u00fcr diesen Datensatz sollen die Preise der Spiele vorhergesagt werden. Dazu ist es notwendig zu wissen, welche Daten hierf\u00fcr verwendet werden sollen. Zum einen muss das \"Prediction Target\" und zum anderen die \"Features\" bestimmt werden, mit dessen Hilfe die Vorhersage germacht wird.\n\n\"\"\"\n\"\"\"\n**Fehlende Daten erkennen**\n\nWie bereits am Anfang erkannt besitzen die Spalten eine unterschiedliche Anzahl an vorhandenen Daten. Mit der nachfolgenden Funktion werden diese erkannt und anschlie\u00dfend ausgegeben.\n\"\"\"\n\ndef missing_values_table(df):\n        # Anzahl der fehlenden Daten\n        mis_val = df.isnull().sum()\n        \n        # Anzahl der fehlenden Daten in %\n        mis_val_percent = 100 * df.isnull().sum() \/ len(df)\n        \n        # Erstellen einer Tabelle mit den Ergebnissen\n        mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)\n        \n        # Benennung der Spalten\n        mis_val_table_ren_columns = mis_val_table.rename(\n        columns = {0 : \"Missing Values\", 1 : \"% of Total Values\"})\n        \n        # Absteigendes Sortieren der Zeilen\n        mis_val_table_ren_columns = mis_val_table_ren_columns[\n            mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(\n        \"% of Total Values\", ascending=False).round(1)\n        \n        \n        \n        return mis_val_table_ren_columns\n#Aufrufen der Tabelle\nmissing_values_table(vgd)\n\"\"\"\nWie zu erkennen ist, fehlen in diesem Datensatz eine Menge an Daten - teilweise \u00fcber 50%. Um mit einem Modell weiterzuarbeiten, werden diese vorerst entfernt. Daher werden alle fehlenden Daten entfernt und in eine neue Variable gespeichert.\n\"\"\"\nvgd_clean = vgd.dropna(axis=0)\n\"\"\"\nDie vorherige Funktion ruft erneut die Tabelle auf. Allerdings sind dieses Mal keine Daten enthalten, da alle fehlenden Daten gel\u00f6scht wurden.\n\"\"\"\nmissing_values_table(vgd_clean)\n\"\"\"\nDer Datensatz wird nun erneut in einer zusammengefassten Darstellung aufzurufen. Jede Spalte hat jetzt die gleiche Anzahl an Daten, wobei diese von \u00fcber 16.000 auf 6825 geschrumpft sind.\n\"\"\"\nvgd_clean.describe()\n\"\"\"\n**Prediction Target & Features festlegen**\n\nWie zu Anfang erw\u00e4hnt, sollen die weltweiten Ums\u00e4tze vorhergesagt werden. Wie in der \u00dcbung m\u00fcssen hierf\u00fcr zun\u00e4chst das \"Prediction Target\" und die \"Features\" festgelegt werden. Das Prediction Target ist in diesem Fall die Spalte Global_Sales. Als Features werden folgende Werte genommen:\n\n\nUser Score, Critic Score, Rating, Year of Release, Genre\n\"\"\"\n#Prediction Target\ny = vgd_clean.Global_Sales\n\n# neue Features werden f\u00fcr das Modell genommen\nvgd_features = ['User_Score', 'User_Count', 'Critic_Score', 'Critic_Count']\n\nX = vgd_clean[vgd_features]\n\"\"\"\nDie Prediction ist in der Variable y gespeichert und die Features in der Variable X. Diese werden in den Folgenden Zeilen aufgerufen.\n\"\"\"\ny.describe()\n\"\"\"\nVon allen 6825 Spielen liegt der h\u00f6chste Wert bei 82.53, wobei hier die Angabe in Millionen gemacht wird. Der niedrigste Wert liegt bei 0.01 und der Durchschnitt bei 0.77.\n\"\"\"\nX.describe(include=\"all\")\n\"\"\"\n\"NaN\" steht f\u00fcr \"Not a Number\". Ob das f\u00fcr die vorhersage vom Nachteil ist, wussten wir zu diesem Zeitpunkt nicht und haben es daher vorerst ignoriert.\n\"\"\"\n\"\"\"\n**Aufrufen der ersten 5 Eintr\u00e4ge**\n\"\"\"\ny.head()\nX.head()\n\"\"\"\nBeim Aufrufen der ersten f\u00fcnf Eintr\u00e4ge f\u00e4llt auf, dass die Nummerierung in der linken Spalte nicht fortlaufend ist. Das liegt daran, dass wir zu Anfang des Notebook fehlende Eintrage gel\u00f6scht haben. So war zum Beispiel in Zeile 1 ein fehlender Wert enthalten, wodurch diese gel\u00f6scht wurde.\n\"\"\"\n\"\"\"\n**Modell entwickeln**\n\nDas Modell wird zun\u00e4chst wie in der \u00dcbung mit dem DecisionTreeRegressor erstellt.\n\"\"\"\nfrom sklearn.tree import DecisionTreeRegressor\n\nvgd_model = DecisionTreeRegressor(random_state=1)\n\nvgd_model.fit(X, y)\nvgd_model = DecisionTreeRegressor(random_state=1)\n\nvgd_model.fit(X, y)\n\"\"\"\nMit den neuen Features kann der Code ausgef\u00fchrt werden und wir beginnen damit eine Vorhersage f\u00fcr die ersten und letzen f\u00fcnf Spiele zu machen:\n\"\"\"\nX.head()\ny.head()\nprint(\"Die ersten 5 Spiele:\")\nprint(vgd_model.predict(X.head()))\nprint(\"Die letzen 5 Spiele:\")\nprint(vgd_model.predict(X.tail()))\n\"\"\"\nZum Vergleich die tats\u00e4chlichen Ums\u00e4tze:\n\"\"\"\nprint(\"Die ersten 5 Spiele:\")\nprint(y.head())\nprint(\"Die letzen 5 Spiele:\")\nprint(y.tail())\n\"\"\"\n**Fehlerabwichung**\n\nAuf den ersten Blick sieht es so aus, als w\u00fcrde das Modell in dieser Form immer die korrekten Preise vorhersagen. Mithilfe des MAE (Mean Absolute Error) soll die Fehlerabweichung ermittelt werden.\n\nNOTE: Der MAE wird in diesem Fall nur \"In-Sample\" berechnet. Das Problem dahinter wird im n\u00e4chsten Teil beschrieben\n\"\"\"\nfrom sklearn.metrics import mean_absolute_error\n\nprediction = vgd_model.predict(X)\nmean_absolute_error(y, prediction)\n\"\"\"\nDie Abweichung der Vorhersagen ist tats\u00e4chlich so gering, das sie nicht weiter beachtet bzw. durch die geringe Gr\u00f6\u00dfe nicht angezeigt wird.\n\"\"\"\n\"\"\"\n**Test- und Trainingsdaten**\n\nDas Problem dieser Abweichung besteht darin, dass nur ein einziges \"Sample\" verwendet wird. Als Beispiel kann hier der \"Publisher\" verwendet werden (auch wenn er als Feature nicht verwendet wurde). Haben Spiele des selben Herstellers immer einen hohen Umsatz, lernt der Algorithmus aus diesem Muster und wird auch f\u00fcr zuk\u00fcnftige Spiele dieses Herstellers einen h\u00f6heren Umsatz vorhersagen. \n\nAus diesem Grund werden Datens\u00e4tze in Tainings- und Testdaten aufgeteilt. Aus dem Datensatz werden einige Daten als Testdaten verwendet, um mit diesen das Trainingsmodell pr\u00e4ziser zu gestalten und auf bisher unbekannte Daten anzuwenden.\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=0)\n\nvgd_model = DecisionTreeRegressor()\n\nvgd_model.fit(train_X, train_y)\n\nval_prediction = vgd_model.predict(val_X)\n\"\"\"\nMit train_X und val_X wird die Aufteilung gezeigt. Hier ist zu sehen, dass in etwa 80% der Daten als Testdaten und 20% als Trainingsdaten verwendet werden.\n\"\"\"\ntrain_X\nval_X\nprint(mean_absolute_error(val_y, val_prediction))\n\"\"\"\nWie zu sehen ist, ist die eigentliche Fehlerabweichung deutlich h\u00f6her als gedacht. Sie liegt sogar \u00fcber dem durchschnittlichen Wert der Global_Sales von 0.77. Ein Grund hierf\u00fcr k\u00f6nnte die Wahl unserer Features sein. F\u00fcr ein pr\u00e4zises Modell m\u00fcssten auch andere Spalten wie Rating oder Genre mit einbezogen werden. Wie genau ein String als Feature verwendet werden kann, wird in der \u00dcbung allerdings nicht erw\u00e4hnt.\n\nZudem haben wir auch mehr als die H\u00e4lfte der Daten aufgrund von fehlenden Werten entfernt. Auch hier kann es bessere Methoden geben, welche ein tieferes Verst\u00e4ndnis \u00fcber Machine Learning erfordern.\n\n\"\"\"\n\"\"\"\nZum Vergleich noch einmal der MAE ohne Trainingsdaten:\n\"\"\"\nmean_absolute_error(y, prediction)\n\"\"\"\n**Modell verfeinern**\n\nEin weg das Modell zu verfeinern ist die tiefe des Entscheidungsbaumes zu ver\u00e4ndern. Ist ein Modell unpr\u00e4zise in den Testdaten, liefert aber gute Ergebnisse in den Trainingsdaten spricht man von 'Overfitting'. Sind auch die Trainingsdaten unpr\u00e4zise, so spricht man von 'Underfitting'. Ziel ist es, die richtige aufteilung des Entscheidungsbaumes zu finden. In unserem Fall sprechen wir von Overfitting, da der MAE der Testdaten deutlich h\u00f6her ist.\n\n![decisiontree](http:\/\/i.imgur.com\/2q85n9s.png)\n\nQuelle: https:\/\/www.kaggle.com\/dansbecker\/underfitting-and-overfitting\n\n\"\"\"\n\"\"\"\nWie in der \u00dcbung verfeinern wir in unserem Modell die tiefe des Entscheidungsbaumes und lassen uns den MAE f\u00fcr unterschiedliche \"Leaf Nodes\" ausgeben.\n\"\"\"\ndef get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):\n    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)\n    model.fit(train_X, train_y)\n    preds_val = model.predict(val_X)\n    mae = mean_absolute_error(val_y, preds_val)\n    return(mae)\nfor max_leaf_nodes in [5, 10, 50, 100, 500]:\n    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)\n    print(\"Max leaf Nodes: \", max_leaf_nodes, \"\\t\\t\", \"MAE: \", my_mae)\n\"\"\"\nEine \"Baumtiefe\" von 50 beitet hierbei den besten MAE. Mit 0.691 liegt die Abweichung zwar unter dem Durchschnitt, allerdings ist sie weitergin sehr hoch.\n\nDennoch wird mit dieser Tiefe jetzt erneut eine Vorhersage gemacht.\n\"\"\"\nvgd_model = DecisionTreeRegressor(random_state=1, max_leaf_nodes=50)\n\nvgd_model.fit(train_X, train_y)\nprint(vgd_model.predict(val_X.head()))\n\"\"\"\nund mit den tats\u00e4chlichen Daten verglichen.\n\"\"\"\nprint(val_y.head())\n\"\"\"\nBeim Vergleich wird aufgezeigt, wie ungenau die Vorhersage ist. Lediglich ein Wert (4621) kommt dem tats\u00e4chlichen ergebnis nahe. Die Fehlerabweichung bei einer Baumteife von 50 war zwar geringer, aber dennos nicht ausreichend f\u00fcr das Modell. Daher wird nun geguckt, ob der RandomForestDegressor eine bessere alternative bietet.\n\"\"\"\nfrom sklearn.ensemble import RandomForestRegressor\n\nforest_model = RandomForestRegressor(random_state=1)\nforest_model.fit(train_X, train_y)\nvgd_preds = forest_model.predict(val_X)\nprint(mean_absolute_error(val_y, vgd_preds))\n\"\"\"\nAuch durch den RandonForestDegressor konnte der MAE nicht verbessert werden und lag sogar \u00fcber dem vorherigen MAE von 0.691.\n\nF\u00fcr ein Seminar an der FH Wedel ist der MAE ein valider Wert f\u00fcr die Beurteilung und Bewertung der Studenten. Doch auch andere Methoden k\u00f6nnen f\u00fcr eine Vorhersage verwendet werden. Dazu geh\u00f6rt die Lineare Regression. Diese war zwar nicht Teil der \u00dcbung, gibt aber einen weiteren Wert f\u00fcr eine sp\u00e4tere Bewertung der Arbeit.\n\"\"\"\n\"\"\"\n**Lineare Regression**\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nclf = LinearRegression()\n# Modell erstellen\nclf.fit(train_X, train_y)\n# Vorhersage der ersten und letzen 5 Daten\nprint(clf.predict(val_X.head()))\nprint(clf.predict(val_X.tail()))\n# Vergleich mit den urspr\u00fcnglichen Daten\nprint(val_y.head())\nprint(val_y.tail())\n\"\"\"\nAuch durch die lineare Regression werden keine pr\u00e4zisen Vorhersagen durchgef\u00fchrt. Das macht deutlich, dass das Modell noch weiter ausgebaut werden muss. \u00c4hnlich wie der MAE kann auch bei der Linearen Regression ein Wert f\u00fcr die Validierung bestimmt werden.\n\"\"\"\nclf.score(val_X, val_y)\n\"\"\"\nDer Score der Linearen Regression liegt hier bei 10,49%, was bedeutet das unsere Vorhersagen zu fast 90% ungenau sind. Aus diesem Grund werden in den folgenden Code Zeilen einige Methoden aus der \u00dcbung angewendet, um das Modell zu verfeinern.\n\"\"\"\n# Get list of categorical variables\ns = (train_X.dtypes == 'object')\nobject_cols = list(s[s].index)\n\nprint(\"Categorical variables:\")\nprint(object_cols)\n# Function for comparing different approaches\ndef score_dataset(train_X, val_X, train_y, val_y):\n    model = RandomForestRegressor(n_estimators=50, random_state=0)\n    model.fit(train_X, train_y)\n    preds = model.predict(val_X)\n    return mean_absolute_error(val_y, preds)\ndrop_train_X = train_X.select_dtypes(exclude=['object'])\ndrop_val_X = val_X.select_dtypes(exclude=['object'])\n\nprint(\"MAE from Approach 1 (Drop categorical variables):\")\nprint(score_dataset(drop_train_X, drop_val_X, train_y, val_y))\nfrom sklearn.preprocessing import LabelEncoder\n\n# Make copy to avoid changing original data \nlabel_X_train = train_X.copy()\nlabel_X_valid = val_X.copy()\n\n# Apply label encoder to each column with categorical data\nlabel_encoder = LabelEncoder()\nfor col in object_cols:\n    label_X_train[col] = label_encoder.fit_transform(train_X[col])\n    label_X_valid[col] = label_encoder.transform(val_X[col])\n\nprint(\"MAE from Approach 2 (Label Encoding):\") \nprint(score_dataset(label_X_train, label_X_valid, train_y, val_y))\n\"\"\"\nDoch auch hier konnte der MAE nicht verbessert werden und liegt weiterhin im Bereich von 0.7.\n\"\"\"\n\"\"\"\n**Fazit**\n\nDie \u00dcbung von Kaggle bietet einen guten ersten Einblick in das Thema Machine Learning. Anhand eines Beispiels werden die grundlegenden Prinzipien verdeutlicht. Allerdings konnte die \u00dcbung nicht erfolgreich auf unseren Datensatz angewendet werden. Unser Modell ist sehr ungenau und ohne ein tieferes Verst\u00e4ndnis in die Materie f\u00e4llt es schwer neue L\u00f6sungsans\u00e4tze zu finden. Die M\u00f6glichkeiten im Machine Learning sind so gro\u00df, dass sie kaum durch kleine \u00dcbungen abgebildet werden k\u00f6nnen. \n\nDamit wir besser verstehen wieso unser Modell ungeau ist, haben wir unsere Daten grafisch Dargestellt. Die grafische Darstellung war nicht Teil der von uns durchgef\u00fchrten \u00dcbungen. \n\"\"\"\n\"\"\"\n**Grafische Ansichten**\n\n\"\"\"\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nplt.style.use(\"fivethirtyeight\")\n\n# \u00c4nderung der Schrift\nplt.rcParams[\"font.size\"] = 24\nplt.rcParams[\"figure.facecolor\"] = \"white\"\nplt.rcParams[\"axes.facecolor\"] = \"white\"\n\n# Internal ipython tool for setting figure size\nfrom IPython.core.pylabtools import figsize\nfigsize(15, 12)\n\"\"\"\nIn unserem Notebook haben wir versucht anhand von vier Features die Global Sales vorherzusagen. Um die Daten grafisch zu betrachten haben wir jeweils ein Feature mit unserem Predicted Target gegen\u00fcbergestellt:\n\"\"\"\nplt.scatter(vgd_clean['User_Count'], vgd_clean['Global_Sales'])\nplt.scatter(vgd_clean['User_Score'], vgd_clean['Global_Sales'])\nplt.scatter(vgd_clean['Critic_Score'], vgd_clean['Global_Sales'])\nplt.scatter(vgd_clean['Critic_Count'], vgd_clean['Global_Sales'])\n\"\"\"\nHierbei ist zu erkennen, dass einige der Daten als Au\u00dfreiser betrachtet werden k\u00f6nnen, da sie nicht in das allgemeine Muster der grafik passen. Um diese Ausrei\u00dfer zu entfernen benutzen wir die unten aufgef\u00fchrte Funktion. Hier werden alle Daten im Bereich unter 25% bzw. \u00fcber 75% markiert und in den folgenden Codezeilen aus den jeweiligen Spalten entfernt.\n\"\"\"\ndef rm_outliers(df, list_of_keys):\n    df_out = df\n    for key in list_of_keys:\n        # Calculate first and third quartile\n        first_quartile = df_out[key].describe()[\"25%\"]\n        third_quartile = df_out[key].describe()[\"75%\"]\n\n        # Interquartile range\n        iqr = third_quartile - first_quartile\n\n        # Remove outliers\n        removed = df_out[(df_out[key] <= (first_quartile - 3 * iqr)) |\n                    (df_out[key] >= (third_quartile + 3 * iqr))] \n        df_out = df_out[(df_out[key] > (first_quartile - 3 * iqr)) &\n                    (df_out[key] < (third_quartile + 3 * iqr))]\n    return df_out, removed\nvgd_clean, rmvd_global = rm_outliers(vgd_clean, [\"Global_Sales\"])\nvgd_clean.describe()\n\"\"\"\nFast 400 der insgesamt 6825 Daten in der Spalte \"Global_Sales\" wurden als Au\u00dfrei\u00dfer identifiziert und entfernt.\n\"\"\"\nvgd_clean, rmvd_global = rm_outliers(vgd_clean, [\"User_Count\"])\nvgd_clean.describe()\n\"\"\"\nDie Spalte \"User_Count\" beinhaltet anschlie\u00dfend sogar fast 600 Ausrei\u00dfer, wohingegen bei den letzten beiden Spalte keine weitere Ver\u00e4nderung auftritt.\n\"\"\"\nvgd_clean, rmvd_global = rm_outliers(vgd_clean, [\"Critic_Score\"])\nvgd_clean.describe()\nvgd_clean, rmvd_global = rm_outliers(vgd_clean, [\"Critic_Count\"])\nvgd_clean.describe()\n\"\"\"\nInsgesamt sind jetzt noch 5811 Daten vorhanden. Auf Basis dieser Daten wird nun erneut der MAE, sowie der Score der logistischen Regression ermittelt.\n\"\"\"\ny = vgd_clean.Global_Sales\n\nvgd_features = ['User_Score', 'Critic_Score', 'User_Count','User_Score']\n\nX = vgd_clean[vgd_features]\nfrom sklearn.model_selection import train_test_split\n\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, random_state=0)\n\nvgd_model = DecisionTreeRegressor()\n\nvgd_model.fit(train_X, train_y)\n\nval_prediction = vgd_model.predict(val_X)\nprint(mean_absolute_error(val_y, val_prediction))\n\"\"\"\nDer MAE konnte von 0.691 auf 0.431 gesenkt werden. Das liegt unter dem Durchschnitt, aber noch immer ist die Fehlerabweichung sehr hoch.\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nclf = LinearRegression()\nclf.fit(train_X, train_y)\nprint(clf.predict(val_X.head()))\nprint(clf.predict(val_X.tail()))\nprint(val_y.head())\nprint(val_y.tail())\nclf.score(val_X, val_y)\n\"\"\"\nDer Score der logistischen Regression konnte auf fast 12% Ansteigen, aber auch hier zeigt sich, dass unser Modell weiterhin ungenau ist.\n\nDurch das Betrachten der Daten anhand von grafischen Abbildungen konnten weitere Fehlerquellen erkannt werden. Durch die Entfernung von Ausrei\u00dfern konnte der MAE um fast die h\u00e4lfte reduziert werden. F\u00fcr die weitere Verfeinerung des Modells m\u00fcssten weitaus mehr Kenntnisse im Bereich Machine Learning vorhanden sein. Die \u00dcbung an sich beitet einen guten Einstieg, reicht aber f\u00fcr die Bearbeitung einer Competition nicht aus.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b04e926c97f8d6'}"}
{"id":"94919","text":"\"\"\"\n# Import Library\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nfrom torchvision import transforms, models\nfrom torchvision.utils import make_grid\nfrom torch.utils.data import Dataset, random_split, DataLoader, WeightedRandomSampler\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\n\nimport time\nimport os\nfrom PIL import Image\n\n! pip install jovian\nimport jovian\n\"\"\"\n# Data Preparation\n\"\"\"\nMETADATA_COVID = '..\/input\/covid-chest-xray\/metadata.csv'\nCOVID_ROOT = '..\/input\/covid-chest-xray\/images'\n\nPNEUMONIA_ROOT = '..\/input\/chest-xray-pneumonia\/chest_xray'\nPNEUMONIA_TRAIN_ALL = PNEUMONIA_ROOT + '\/train'\n# PNEUMONIA_TRAIN = PNEUMONIA_ROOT+'\/train\/PNEUMONIA'\n# NORMAL_TRAIN = PNEUMONIA_ROOT+'\/train\/NORMAL'\n# PNEUMONIA_TEST = PNEUMONIA_ROOT+'\/test\/PNEUMONIA'\n# NORMAL_TEST = PNEUMONIA_ROOT+'\/test\/NORMAL'\n\n#target label\nTARGET_LABEL = {0: 'NORMAL',\n               1: 'PNEUMONIA',\n               2: 'COVID19'}\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nproject_name = 'chest X-ray'\npneumonia_data = []\nfor dirname, _, filenames in os.walk(PNEUMONIA_TRAIN_ALL):\n    for filename in filenames:\n        if filename.endswith(\".jpeg\"):\n            pneumonia_data.append(os.path.join(dirname, filename))\n\nimage = []\nlabel = []\nfor i in range(len(pneumonia_data)):\n    image.append(pneumonia_data[i].split('\/')[-1])\n    label.append(pneumonia_data[i].split('\/')[-2])\n# pneoumonia and normal data\ndf_pneumonia = pd.DataFrame({\"label\": label, \"image_file\": image})\ndf_pneumonia.head()\nsns.countplot(df_pneumonia['label'])\nplt.title('Pneumonia train dataset');\n#covid19 data\ndf = pd.read_csv(METADATA_COVID)\ndf_pa = df.drop(df[df.view != 'PA'].index) #only take PA(from back to front film closer to chest) View\ncovid19 = df_pa[df_pa['finding']=='COVID-19'] #only take covid-19 label\ncovid19 = covid19[['finding', 'filename']] #take its label and image file\ncovid19.columns = (['label', 'image_file']) #change columns name same to pneumonia\n#covid19[covid19['image_file'].str.endswith('.gz')]\ncovid19.reset_index(drop=True, inplace=True)\nprint('Data size:' , len(covid19))\ncovid19.head()\n#takes normal and pneumonia only 300 images\nnormal = df_pneumonia[df_pneumonia['label']=='NORMAL']\nnormal = normal.sample(frac=1, axis=0, random_state=7).reset_index(drop=True) #suffle rows\nnormal = normal[:141] #same with covid19 data\n\npneumonia = df_pneumonia[df_pneumonia['label']=='PNEUMONIA']\npneumonia = pneumonia.sample(frac=1, axis=0, random_state=7).reset_index(drop=True)\npnuemonia = pneumonia[:141] #same with covid19 data\n\n#concat all data (covid, pneumonia and normal)\nall_data = pd.concat([normal, pnuemonia, covid19], ignore_index=True)\nall_data = all_data.sample(frac=1, axis=0, random_state=7).reset_index(drop=True)\nall_data.head(10)\nsns.countplot(all_data['label'])\nplt.title('All Datasets');\n\"\"\"\n## Load All Data and Exploration\n\"\"\"\n#split dataset\nX_trainval, X_test, y_trainval, y_test = train_test_split(all_data['image_file'].values,\n                                                      all_data['label'].values, test_size=0.05,\n                                                      stratify=all_data['label'].values, random_state=7)\n\nX_train, X_val, y_train, y_val = train_test_split(X_trainval, y_trainval, stratify=y_trainval, test_size=0.1,\n                                                  random_state=7)\n\nlen(X_train), len(X_val), len(X_test)\nclass Xray_split(Dataset):\n    def __init__(self, root_dir_pnue, root_dir_covid, X, y, transform=None):\n        self.pnue_root = root_dir_pnue\n        self.covid_root = root_dir_covid\n        self.X = X\n        self.y = y\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.X)\n    \n    def __getitem__(self, idx):\n        image, label = self.X[idx], self.y[idx]\n        if self.y[idx] == 'COVID-19':\n            label = 2\n            img_fname = str(self.covid_root) + \"\/\" + str(image)\n            img = Image.open(img_fname).convert(\"L\")           \n            if self.transform:\n                img = self.transform(img)\n        \n        if self.y[idx] == 'NORMAL':\n            label = 0\n            img_fname = str(self.pnue_root) + \"\/NORMAL\/\" + str(image)\n            img = Image.open(img_fname)\n          \n \n            if self.transform:\n                img = self.transform(img)\n        \n        if self.y[idx] == 'PNEUMONIA':\n            label = 1\n            img_fname = str(self.pnue_root) + \"\/PNEUMONIA\/\" + str(image)\n            img = Image.open(img_fname)\n            \n            if self.transform:\n                img = self.transform(img)\n                \n        return img, int(label)\n# mean = [0.4947]\n# std = [0.2226]\nmean = [0.0960, 0.0960, 0.0960]\nstd = [0.9341, 0.9341, 0.9341]\n\ntrain_transform = transforms.Compose([transforms.Resize((512, 512)),\n                                      transforms.Grayscale(3), #output 3 channel grayscale\n                                      transforms.RandomResizedCrop((224, 224)),\n                                      transforms.RandomRotation(15),\n                                      transforms.ToTensor(),\n                                      transforms.Normalize(mean, std)\n                                     ])\n\nval_transform = transforms.Compose([transforms.Resize((512, 512)),\n                                    transforms.Grayscale(3),\n                                    transforms.ToTensor(),\n                                    transforms.Normalize(mean, std),\n                                   ])\n\ntest_transform = transforms.Compose([transforms.Resize((512, 512)),\n                                     transforms.Grayscale(3),\n                                     transforms.ToTensor(),\n                                     transforms.Normalize(mean, std),\n                                   ])\n\n\ntrain_set = Xray_split(PNEUMONIA_TRAIN_ALL, COVID_ROOT, X_train, y_train, train_transform)\nval_set = Xray_split(PNEUMONIA_TRAIN_ALL, COVID_ROOT, X_val, y_val, val_transform)\ntest_set = Xray_split(PNEUMONIA_TRAIN_ALL, COVID_ROOT, X_test, y_test, test_transform)\n#look the training data (already transformed)\nfig = plt.figure(figsize=(20, 5))\n\nfor i in range(30):\n    image, label = train_set[i]\n    ax = fig.add_subplot(3, 10, i+1, xticks=[], yticks = [])\n    ax.imshow(image[0], cmap='gray')\n    ax.set_title(TARGET_LABEL[label], color=(\"green\" if label == 0 else 'red'))\n\"\"\"\n# Dataloader\n\"\"\"\n#find the mean and std\n\n# nimages = 0\n# mean = 0.\n# std = 0.\n# for batch, _ in train_loader:\n#     # Rearrange batch to be the shape of [B, C, W * H]\n#     batch = batch.view(batch.size(0), batch.size(1), -1)\n#     # Update total number of images\n#     nimages += batch.size(0)\n#     # Compute mean and std here\n#     mean += batch.mean(2).sum(0) \n#     std += batch.std(2).sum(0)\n\n# # Final step\n# mean \/= nimages\n# std \/= nimages\n\n# print(mean)\n# print(std)\nbatch_size = 32 #have used 64 and 128 but 32 works better\n\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True)\nval_loader = torch.utils.data.DataLoader(val_set, batch_size=batch_size*2, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=False)\ndef show_batch(dl):\n    for images, labels in dl:\n        fig, ax = plt.subplots(figsize=(20, 25))\n        ax.set_xticks([]); ax.set_yticks([])\n        ax.imshow(make_grid(images, nrow=16).permute(1, 2, 0))\n        break\nshow_batch(train_loader)\n\"\"\"\n# Modelling\n\"\"\"\n#for get learning rate parameter\ndef get_lr(optimizer):\n    for param_group in optimizer.param_groups:\n        return param_group['lr']\n\n#training loop\ndef fit(epochs, model, train_loader, val_loader, criterion, optimizer, scheduler):\n    torch.cuda.empty_cache()\n    \n    #save variabel\n    train_losses = []\n    test_losses = []\n    train_scores = []\n    val_score = []\n    lrs = []\n\n    fit_time = time.time()\n    for e in range(epochs):\n        since = time.time()\n        running_loss = 0\n        train_score = 0\n        \n        #training loop#\n        for image, label in train_loader:\n            #training phase\n            model.train()\n            \n            image = image.to(device); label = label.to(device);\n            \n            output = model(image)\n            #accuracy calulcation\n            ps = torch.exp(output)\n            _, top_class = ps.topk(1, dim=1)\n            correct = top_class == label.view(*top_class.shape)\n            train_score += torch.mean(correct.type(torch.FloatTensor))\n            #loss\n            loss = criterion(output, label)\n            #backward pass\n            loss.backward()\n            #update weight\n            optimizer.step()\n            optimizer.zero_grad()\n            \n            scheduler.step() \n            lrs.append(get_lr(optimizer))\n            running_loss += loss.item()\n            \n        else:\n            model.eval()\n            test_loss = 0\n            scores = 0\n            #validation loop#\n            with torch.no_grad():\n                for image, label in val_loader:\n                    image = image.to(device); label = label.to(device);\n\n                    output = model(image)\n\n                    #accuracy calulcation\n                    ps = torch.exp(output)\n                    _, top_class = ps.topk(1, dim=1)\n                    correct = top_class == label.view(*top_class.shape)\n                    scores += torch.mean(correct.type(torch.FloatTensor))\n                    #loss\n                    loss = criterion(output, label)                                  \n                    test_loss += loss.item()\n            \n            #calculation mean for each batch\n            train_losses.append(running_loss\/len(train_loader))\n            test_losses.append(test_loss\/len(val_loader))\n            train_scores.append(train_score\/len(train_loader))\n            val_score.append(scores\/len(val_loader))\n\n            print(\"Epoch: {}\/{}.. \".format(e+1, epochs),\n                  \"Train Loss: {:.3f}.. \".format(running_loss\/len(train_loader)),\n                  \"Val Loss: {:.3f}.. \".format(test_loss\/len(val_loader)),\n                  \"Train acc Score: {:.3f}.. \".format(train_score\/len(train_loader)),\n                  \"Val acc : {:.3f}.. \".format(scores\/len(val_loader)),\n                  \"Lr: {:.4f} \".format(get_lr(optimizer)),\n                  \"Time: {:.2f}s\" .format(time.time()-since)\n                 )\n        \n    history = {'train_loss' : train_losses, 'val_loss': test_losses, \n               'train_acc': train_scores, 'val_acc':val_score, 'lrs': lrs}\n    print('Total time: {:.2f} m' .format((time.time()- fit_time)\/60))\n    return history\n\ndef plot_loss(history, n_epoch):\n    epoch = [x for x in range(1, n_epoch+1)]\n    plt.plot(epoch, history['train_loss'], label='Train_loss')\n    plt.plot(epoch, history['val_loss'], label='val_loss')\n    plt.title('Loss per epoch')\n    plt.ylabel('Loss')\n    plt.xlabel('epoch')\n    plt.legend(); \n    plt.show()\n\ndef plot_score(history, n_epoch):\n    epoch = [x for x in range(1, n_epoch+1)]\n    plt.plot(epoch, history['train_acc'], label='Train_acc')\n    plt.plot(epoch, history['val_acc'], label='val_acc')\n    plt.title('Accuracy per epoch')\n    plt.ylabel('score')\n    plt.xlabel('epoch')\n    plt.legend(); \n    plt.show()\n\ndef plot_lr(history):\n    plt.plot(history['lrs'], label='learning rate')\n    plt.title('One Cycle Learning Rate')\n    plt.ylabel('Learning Rate')\n    plt.xlabel('steps')\n    plt.legend(); \n    plt.show()\n\"\"\"\n## Mobilenet_v2\n\"\"\"\noutput_label = 3\n\nmodel_mobile = models.mobilenet_v2(pretrained=True)\n\nmodel_mobile.classifier = nn.Sequential(nn.Linear(in_features=1280, out_features=output_label))\n\nmodel_mobile.to(device);\nmodel_mobile\nmax_lr = 0.0001\nepoch = 20\nweight_decay = 1e-4\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model_mobile.parameters(), lr=max_lr, weight_decay=weight_decay)\nsched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epoch, \n                                            steps_per_epoch=len(train_loader))\n\nhistory_mobile = fit(epoch, model_mobile, train_loader, val_loader, criterion, optimizer, sched)\ntorch.save(model_mobile.state_dict(),'mobilenet.pth')\nplot_score(history_mobile, epoch)\nplot_loss(history_mobile, epoch)\nplot_lr(history_mobile)\njovian.reset()\njovian.log_hyperparams(arch='mobile_net', \n                       epochs=epoch, \n                       lr=max_lr, \n                       scheduler='one-cycle', \n                       weight_decay=weight_decay,\n                       opt='Adam')\n\njovian.log_metrics(val_loss=history_mobile['val_loss'][-1], \n                   val_acc=history_mobile['val_acc'][-1].item(),\n                   train_loss=history_mobile['train_loss'][-1],\n                   time='7.79m')\n\"\"\"\n## Resnet18\n\"\"\"\nmodel_resnet18 = models.resnet18(pretrained=True)\nmodel_resnet18.fc = nn.Linear(512, output_label)\n\nmodel_resnet18.to(device)\nmodel_resnet18\nmax_lr = 0.0001\nepoch = 20\nweight_decay = 1e-4\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model_resnet18.parameters(), lr=max_lr, weight_decay=weight_decay)\nsched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epoch, \n                                            steps_per_epoch=len(train_loader))\n\nhistory_re18 = fit(epoch, model_resnet18, train_loader, val_loader, criterion, optimizer, sched)\ntorch.save(model_resnet18.state_dict(),'resnet18.pth')\nplot_score(history_re18, epoch)\nplot_loss(history_re18, epoch)\nplot_lr(history_re18)\njovian.log_hyperparams(arch='resnet18', \n                       epochs=epoch, \n                       lr=max_lr, \n                       scheduler='one-cycle', \n                       weight_decay=weight_decay, \n                       opt='Adam')\n\njovian.log_metrics(val_loss=history_re18['val_loss'][-1], \n                   val_acc=history_re18['val_acc'][-1].item(),\n                   train_loss=history_re18['train_loss'][-1],\n                   time='7.58m')\n\"\"\"\n## VGG16\n\"\"\"\nmodel_vgg16 = models.vgg16(pretrained=True)\nmodel_vgg16.classifier = nn.Sequential(nn.Linear(in_features=25088, out_features=30, bias=True),\n                                        nn.ReLU(inplace=True),\n                                        nn.Dropout(p=0.5, inplace=False),\n                                        nn.Linear(in_features=30, out_features=3, bias=True)\n                                       )\nmodel_vgg16.to(device)\nmodel_vgg16\noptimizer = optim.Adam(model_vgg16.parameters(), lr=max_lr, weight_decay=weight_decay)\nsched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epoch, \n                                            steps_per_epoch=len(train_loader))\n\nhistory_vgg16 = fit(epoch, model_vgg16, train_loader, val_loader, criterion, optimizer, sched)\ntorch.save(model_vgg16.state_dict(),'vgg16.pth')\nplot_score(history_vgg16, epoch)\nplot_loss(history_vgg16, epoch)\nplot_lr(history_vgg16)\njovian.log_hyperparams(arch='VGG16', \n                       epochs=epoch, \n                       lr=max_lr, \n                       scheduler='one-cycle', \n                       weight_decay=weight_decay, \n                       opt='Adam')\n\njovian.log_metrics(val_loss=history_vgg16['val_loss'][-1], \n                   val_acc=history_vgg16['val_acc'][-1].item(),\n                   train_loss=history_vgg16['train_loss'][-1],\n                   time='8.44m')\n\"\"\"\n# Evaluation and Report\n\"\"\"\ndef predict_dataset(dataset, model):\n    model.eval()\n    model.to(device)\n    torch.cuda.empty_cache()\n    predict = []\n    y_true = []\n    for image, label in dataset:\n        #image = image.to(device); label= label.to(device)\n        image = image.unsqueeze(0)\n        image = image.to(device);\n        \n        output = model(image)\n        ps = torch.exp(output)\n        _, top_class = ps.topk(1, dim=1)\n        \n        predic = np.squeeze(top_class.cpu().numpy())\n        predict.append(predic)\n        y_true.append(label)\n    return list(y_true), list(np.array(predict).reshape(1,-1).squeeze(0))\n\ndef report(y_true, y_predict, title='MODEL OVER TEST SET'):\n    print(classification_report(y_true, y_predict))\n    sns.heatmap(confusion_matrix(y_true, y_predict), annot=True)\n    plt.yticks(np.arange(0.5, len(TARGET_LABEL)), labels=list(TARGET_LABEL.values()), rotation=0);\n    plt.xticks(np.arange(0.5, len(TARGET_LABEL)), labels=list(TARGET_LABEL.values()), rotation=45)\n    plt.title(title)\n    plt.show()\n    \ndef plot_predict(test_set, y_predict):\n    \"\"\"it takes longer time to plot, if you want it faster\n    comment or delete tight_layout\n    \"\"\"\n    fig = plt.figure(figsize=(20, 20))\n\n    for i in range(len(test_set)):\n        image, label = test_set[i]\n        ax = fig.add_subplot(4, 6, i+1, xticks=[], yticks = [])\n        ax.imshow(image[0], cmap='gray')\n        ax.set_title(\"{}({})\" .format(TARGET_LABEL[y_predict[i]], TARGET_LABEL[label]), \n                      color=(\"green\" if y_predict[i] == label else 'red'), fontsize=12)\n\n    plt.tight_layout() #want faster comment or delete this\n    plt.show()\ny_true, y_predict = predict_dataset(test_set, model_mobile)\nreport(y_true, y_predict, title='Mobilenet_v2 Over Test Set')\nplot_predict(test_set, y_predict)\ny_true, y_predict = predict_dataset(test_set, model_resnet18)\nreport(y_true, y_predict, 'Resnet18')\nplot_predict(test_set, y_predict)\ny_true, y_predict = predict_dataset(test_set, model_vgg16)\nreport(y_true, y_predict, 'VGG16')\nplot_predict(test_set, y_predict)\njovian.commit(project=project_name, environment=None)","meta":"{'source': 'AI4Code', 'id': 'ae3e4a5dcf343d'}"}
{"id":"106982","text":"# 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\n\"\"\"\n# load libraries\n\"\"\"\n# as usual, let us load all the necessary libraries\nimport numpy as np  # numerical computation with arrays\nimport pandas as pd # library to manipulate datasets using dataframes\nimport scipy as sp  # statistical library\n\n# below sklearn libraries for different models\nfrom sklearn.tree import DecisionTreeClassifier as DecisionTree\nfrom sklearn.ensemble import RandomForestClassifier as RandomForest\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.impute import KNNImputer\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import MinMaxScaler\n\n# plot \nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\ndf = pd.read_csv('..\/input\/agricultural-survey-of-african-farm-households\/data.csv')\ndf.head()\n# print a summary of the values for each covariate in the dataset\ndf.describe()\n#describing the dataset statistics\nstat = df.describe().T\nstat[['mean', 'max', 'min']]\n# get a summary of how many rows in the dataset and how many missing values is in each column\ndf.info()\n#Checking nan values in the df Data\ndf.isna().sum()\n\"\"\"\n# **Pre-process the data**\n\"\"\"\n# Drop unimportant covariates\n#here we drop all the variables that are not helpful in the model building\ndf.drop(columns=['interviewer', 'vname','Unnamed: 0' ],axis=1,inplace=True)\n\n# Step 2: Drop ALL redundant covariates\n\ndf.drop(columns=['adjtempshifts1_1','adjtempshifts2_1', 'adjtempshifts3_1','adjrainfallshifts1_1','adjrainfallshifts2_1','adjrainfallshifts3_1'], axis=1, inplace=True)\n# drop longtermrainfallshifts3 since it does not contain any record for the whole dataset.\ndf.drop(columns=['longtermrainfallshifts3' ],axis=1,inplace=True)\n#fill the non values.\ndf = df.fillna(0)\ndf.head()\nlow = 0.05\nhigh = 0.95\n\n# Step 1: compute 5% percentile and the 95% percentile of each column in the dataset\nquantile_df = df.quantile([low, high])\nquantile_df\n\"\"\"\n# Visualizations\n\"\"\"\n#pie chart visualization for gender1\nftype = df['gender1']\nList = [1,2]\nCount = [sum(map(lambda x: x==i,ftype)) for i in List]\nPerc = [x*100.0\/sum(Count) for x in Count]\nplt.pie(Perc,None,List,autopct='%1.1f%%')\nplt.show()\n#pie chart visualization for age\nftype = df['gender2']\nList = [1,2]\nCount = [sum(map(lambda x: x==i,ftype)) for i in List]\nPerc = [x*100.0\/sum(Count) for x in Count]\nplt.pie(Perc,None,List,autopct='%1.1f%%')\nplt.show()\n#pie chart visualization for age\nftype = df['gender3']\nList = [1,2]\nCount = [sum(map(lambda x: x==i,ftype)) for i in List]\nPerc = [x*100.0\/sum(Count) for x in Count]\nplt.pie(Perc,None,List,autopct='%1.1f%%')\nplt.show()","meta":"{'source': 'AI4Code', 'id': 'c4868a137bd9d5'}"}
{"id":"95890","text":"\"\"\"\n# <center style=\"background-color:#63809e; color:white;\">Employee Burn Rate Prediction<\/center>\n\n<center><img src=\"https:\/\/smallville.com.au\/wp-content\/uploads\/2019\/12\/10-Questions-To-Ask-Yourself-To-Monitor-Your-Mental-HealthAsset-1@4x-100.jpg\" ><\/center>\n\n<br><br>\n## <center style=\"background-color:#6abada; color:white;\">About<\/center>\n<div style=\"text-align: justify;\">Understanding what will be the Burn Rate for the employee working in an organization based on the current pandemic situation where work from home is a boon and a bane. How are employees' Burn Rate affected based on various conditions provided? Through this notebook, we are going to understand and observe the mental health of all the employees for a company with the dataset provided. So, we need to predict the burn-out rate of employees based on the provided features thus helping the company to take appropriate measures for their employees' health and keep measures to improve their throughput.<\/div> \n<br>\n\n\n<div style=\"text-align: justify;\">Globally, World Mental Health Day is celebrated on <b>October 10<\/b> each year. The objective of this day is to raise awareness about mental health issues around the world and mobilize efforts in support of mental health. According to an anonymous survey, about <b>450 million<\/b> people live with mental disorders that can be one of the primary causes of poor health and disability worldwide. These days when the world is suffering from a pandemic situation, it becomes really hard to maintain mental fitness.\n <\/div>\n\"\"\"\n\"\"\"\n## <center style=\"background-color:#6abada; color:white;\">Featues in our Data<\/center>\n\n* `Employee ID`: The unique ID allocated for each employee (example: **fffe390032003000**)\n* `Date of Joining`: The date time when the employee has joined the organization (example: **2008-12-30**)\n* `Gender`: The gender of the employee (**Male\/Female**) \n* `Company Type`: The type of company where the employee is working (**Service\/Product**)\n* `WFH Setup Available`: Is the work from home facility available for the employee (**Yes\/No**)\n* `Designation`: The designation of the employee of work in the organization.\n    * In the range of **[0.0, 5.0]** bigger is higher designation.\n* `Resource Allocation`: The amount of resource allocated to the employee to work, ie. number of working hours. \n    * In the range of **[1.0, 10.0]** (higher means more resource)\t\n* `Mental Fatigue Score`: The level of fatigue mentally the employee is facing. \n    * In the range of **[0.0, 10.0]** where 0.0 means no fatigue and 10.0 means completely fatigue.\n* `Burn Rate`: The value we need to predict for each employee telling the rate of Bur out while working.\n    * In the range of **[0.0, 1.0]** where the higher the value is more is the burn out.\n\"\"\"\n\"\"\"\n# Getting and Understanding Data\n\"\"\"\n\"\"\"\n## Importing Libraries\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom scipy import stats \nimport scipy.stats as st\n\n# !pip install pandas-profiling\nfrom pandas_profiling import ProfileReport\n\n# !pip install cufflinks\nimport cufflinks as cf\nimport plotly.offline\ncf.go_offline()\ncf.set_config_file(offline=False, world_readable=True)\n\nimport os\nimport re\n\"\"\"\n## Getting Data\n\"\"\"\nfor dirname, _, filenames in os.walk('\/kaggle\/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nTRAIN_DATA_URL = \"\/kaggle\/input\/are-your-employees-burning-out\/train.csv\"\nTEST_DATA_URL = \"\/kaggle\/input\/are-your-employees-burning-out\/test.csv\"\nSAMPLE_DATA_URL = \"\/kaggle\/input\/are-your-employees-burning-out\/sample_submission.csv\"\n\ndf = pd.read_csv(TRAIN_DATA_URL)\ndf_test = pd.read_csv(TEST_DATA_URL)\nprint(df.shape)\ndf.tail()\n\"\"\"\n## Profiling Data \n\"\"\"\nprofile = ProfileReport(df, title='Pandas Profiling Report')\nprofile.to_file(\".\/BurnOut_Profiling.html\")\nprofile.to_widgets()\nnum_cols = [\"Designation\", \"Resource Allocation\", \"Mental Fatigue Score\", \"Burn Rate\"]\ndf[num_cols].iplot()\n\"\"\"\n## Understanding Data\n\"\"\"\ndf.describe()\ndf.info()\n\"\"\"\n## Dealing with missing values\n\"\"\"\ndf.isna().sum()\ndf.dropna(subset = [\"Burn Rate\"], inplace=True)\nprint(df.shape)\ndf = df.fillna(df.median())\nprint(\"Are there any value missing now? \"+str(df.isna().any().any()))\nprint(\"Numerical valued features counts:----------\", end=\"\\n\\n\")\n\nprint(df[\"Designation\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"Resource Allocation\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"Mental Fatigue Score\"].value_counts(), end=\"\\n\\n\")\n\"\"\"\n# Exploratory Data Analysis\n\"\"\"\nsns_plot = sns.pairplot(df, height=2.5)\nsns_plot.savefig(\"pairplot.png\")\n\"\"\"\n## Checking Data Normality\n\"\"\"\ndef normalize_features(original_data):\n    fitted_data, fitted_lambda = stats.boxcox(original_data) \n    fig, ax = plt.subplots(1, 2) \n\n    # plotting the original data(non-normal) and  \n    # fitted data (normal) \n    sns.distplot(original_data, hist = False, kde = True, \n                kde_kws = {'shade': True, 'linewidth': 2},  \n                label = \"Non-Normal\", color =\"green\", ax = ax[0]) \n\n    sns.distplot(fitted_data, hist = False, kde = True, \n                kde_kws = {'shade': True, 'linewidth': 2},  \n                label = \"Normal\", color =\"green\", ax = ax[1]) \n\n    # adding legends to the subplots \n    plt.legend(loc = \"upper right\") \n\n    # rescaling the subplots \n    fig.set_figheight(5) \n    fig.set_figwidth(10)\n    return fitted_data\noriginal_data = df.drop(df[df[\"Mental Fatigue Score\"] <= 0.0].index)[\"Mental Fatigue Score\"]\nnormalize_features(original_data)\noriginal_data = df.drop(df[df[\"Designation\"] <= 0.0].index)[\"Designation\"]\nnormalize_features(original_data)\noriginal_data = df.drop(df[df[\"Resource Allocation\"] <= 0.0].index)[\"Resource Allocation\"]\nnormalize_features(original_data)\noriginal_data = df.drop(df[df[\"Burn Rate\"] <= 0.0].index)[\"Burn Rate\"]\nnormalize_features(original_data)\n\"\"\"\n# Feature Engineering\n\"\"\"\n\"\"\"\n## Categorize features\n\"\"\"\ndef categorize_designation(data):\n    if data[\"Designation\"] <= 1.0:\n        return 0\n    if data[\"Designation\"] > 1.0 and data[\"Designation\"] <= 2.0:\n        return 1\n    if data[\"Designation\"] > 2.0 and data[\"Designation\"] <= 5.0:\n        return 2\n    return -1\n\n\ndef categorize_resource(data):\n    if data[\"Resource Allocation\"] <= 3.0:\n        return 0\n    if data[\"Resource Allocation\"] > 3.0 and data[\"Resource Allocation\"] <= 5.0:\n        return 1\n    if data[\"Resource Allocation\"] > 5.0 and data[\"Resource Allocation\"] <= 10.0:\n        return 2\n    return -1\n    \n\ndef categorize_Mental_Fatigue(data):\n    if data[\"Mental Fatigue Score\"] <= 4.0:\n        return 0\n    if data[\"Mental Fatigue Score\"] > 4.0 and data[\"Mental Fatigue Score\"] <= 5.0:\n        return 1\n    if data[\"Mental Fatigue Score\"] > 5.0 and data[\"Mental Fatigue Score\"] <= 6.0:\n        return 2\n    if data[\"Mental Fatigue Score\"] > 6.0 and data[\"Mental Fatigue Score\"] <= 7.0:\n        return 3\n    if data[\"Mental Fatigue Score\"] > 7.0:\n        return 4\n    return -1\n\n\n\ndf[\"categorize_designation\"] = df.apply(categorize_designation, axis=1)\ndf[\"categorize_resource\"] = df.apply(categorize_resource, axis=1)\ndf[\"categorize_Mental_Fatigue\"] = df.apply(categorize_Mental_Fatigue, axis=1)\n\ndf_test[\"categorize_designation\"] = df_test.apply(categorize_designation, axis=1)\ndf_test[\"categorize_resource\"] = df_test.apply(categorize_resource, axis=1)\ndf_test[\"categorize_Mental_Fatigue\"] = df_test.apply(categorize_Mental_Fatigue, axis=1)\nprint(\"Cetegorized valued features values:----------\", end=\"\\n\\n\")\n\nprint(df[\"categorize_designation\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"categorize_resource\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"categorize_Mental_Fatigue\"].value_counts(), end=\"\\n\\n\")\n\"\"\"\n## Date of Joining\n\"\"\"\ncurrent_date = pd.to_datetime('today')\n\ndf[\"Date of Joining\"] = pd.to_datetime(df[\"Date of Joining\"])\ndf_test[\"Date of Joining\"] = pd.to_datetime(df_test[\"Date of Joining\"])\ndef create_days_count(data):\n    return (current_date - data[\"Date of Joining\"])\n\ndf[\"days_count\"] = df.apply(create_days_count, axis=1)\ndf[\"days_count\"] = df[\"days_count\"].dt.days\n\ndf_test[\"days_count\"] = df_test.apply(create_days_count, axis=1)\ndf_test[\"days_count\"] = df_test[\"days_count\"].dt.days\n\"\"\"\n## Encoding Features\n\"\"\"\nprint(df[\"Gender\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"Company Type\"].value_counts(), end=\"\\n\\n\")\nprint(df[\"WFH Setup Available\"].value_counts(), end=\"\\n\\n\")\none = 1\nzero = 0\n\ndef gender_encoder(data):\n    if data[\"Gender\"] == \"Female\":\n        return one\n    return zero\n\n\ndef wfh_setup_encoder(data):\n    if data[\"WFH Setup Available\"] == \"Yes\":\n        return one\n    return zero\n\n\ndef company_encoder(data):\n    if data[\"Company Type\"] == \"Service\":\n        return one\n    return zero\n\n\n\ndf[\"Gender\"] = df.apply(gender_encoder, axis=1)\ndf[\"WFH Setup Available\"] = df.apply(wfh_setup_encoder, axis=1)\ndf[\"Company Type\"] = df.apply(company_encoder, axis=1)\n\ndf_test[\"Gender\"] = df_test.apply(gender_encoder, axis=1)\ndf_test[\"WFH Setup Available\"] = df_test.apply(wfh_setup_encoder, axis=1)\ndf_test[\"Company Type\"] = df_test.apply(company_encoder, axis=1)\n\"\"\"\n## Normalize Data\n\"\"\"\nnorm_cols = [\"Designation\", \"Resource Allocation\", \"Mental Fatigue Score\"]\n#              + [\"days_count\", \"categorize_designation\", \"categorize_resource\", \"categorize_Mental_Fatigue\"]\n\ntrain_df_min = df[norm_cols].min()\ntrain_df_max = df[norm_cols].max()\n\ndf[norm_cols] = (df[norm_cols] - train_df_min)\/(train_df_max - train_df_min)\ndf_test[norm_cols] = (df_test[norm_cols] - train_df_min)\/(train_df_max - train_df_min)\ndf.head()\n\"\"\"\n## Removing useless columns\n\"\"\"\ndf.drop(['Date of Joining', \"Employee ID\"], axis=1, inplace=True)\nclean_df_test = df_test.drop(['Date of Joining', \"Employee ID\"], axis=1)\n\"\"\"\n# Understand Correlation\n\"\"\"\ndf.corr()\nplt.figure(figsize=(16, 6))\nheatmap = sns.heatmap(df.corr(), vmin=-1, vmax=1, annot=True)\nheatmap.set_title('Correlation Heatmap', fontdict={'fontsize':12}, pad=12);\nplt.savefig(\"correlation_heatmap.png\")\n# df = df.loc[:, [\"WFH Setup Available\", \"Designation\", \"Resource Allocation\", \"Mental Fatigue Score\", \"Burn Rate\"]]\n# clean_df_test = df_test.loc[:, [\"WFH Setup Available\", \"Designation\", \"Resource Allocation\", \"Mental Fatigue Score\"]]\n\"\"\"\n## Working with clean data\n\"\"\"\nclean_df = df.copy()\n\ndf.to_csv(\"clean_df_train.csv\", index=False)\ntrain_file_path = \".\/clean_df_train.csv\"\nnew_df = pd.read_csv(train_file_path)\n\nclean_df_test.to_csv(\"clean_df_test.csv\", index=False)\ntest_file_path = \".\/clean_df_test.csv\"\nnew_df_test = pd.read_csv(test_file_path)\n\nnew_df_test.head()\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(clean_df.loc[:, clean_df.columns != \"Burn Rate\"],\n                                                    clean_df.loc[:, clean_df.columns == \"Burn Rate\"],\n                                                    test_size=0.2, \n                                                    random_state=42)\n\"\"\"\n# Model Training and Predicitons\n\n<center><img src=\"https:\/\/media.giphy.com\/media\/JstFYY8FwlBm48n7De\/giphy.gif\" width=70%><\/center>\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.svm import SVR\nfrom catboost import CatBoostRegressor\nfrom sklearn.neural_network import MLPRegressor\n\nfrom sklearn.ensemble import StackingRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\n\nimport xgboost\n\n\nfrom sklearn.metrics import r2_score\ndef print_r2_score(y_train, train_pred, y_test, test_pred):\n    r2_train = r2_score(y_train, train_pred)\n    print(\"Score LR Train: \"+str(round(100*r2_train, 4))+\" %\")\n\n    r2_test = r2_score(y_test, test_pred)\n    print(\"Score LR Test: \"+str(round(100*r2_test, 4))+\" %\")\nsub = pd.read_csv(TEST_DATA_URL)\nsub = sub.loc[:, [\"Employee ID\"]]\n\"\"\"\n## Linear Regression\n\"\"\"\nlr_model = LinearRegression()\nlr_model.fit(X_train, y_train)\n\ntrain_pred_linear = lr_model.predict(X_train)\ntest_pred_linear = lr_model.predict(X_test)\nprint_r2_score(y_train, train_pred_linear, y_test, test_pred_linear)\n\nlr_main_pred = lr_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = lr_main_pred\nsub.to_csv('submission_lr.csv', index=False)\n\"\"\"\n## Ridge\n\"\"\"\nridge_model = Ridge()\nridge_model.fit(X_train, y_train)\n\ntrain_pred_ridge = ridge_model.predict(X_train)\ntest_pred_ridge = ridge_model.predict(X_test)\nprint_r2_score(y_train, train_pred_ridge, y_test, test_pred_ridge)\n\nridge_main_pred = ridge_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = ridge_main_pred\nsub.to_csv('submission_lasso.csv', index=False)\n\"\"\"\n## Lasso\n\"\"\"\nlasso_model = Lasso(alpha=0.1)\nlasso_model.fit(X_train, y_train)\n\ntrain_pred_lasso = lasso_model.predict(X_train)\ntest_pred_lasso = lasso_model.predict(X_test)\nprint_r2_score(y_train, train_pred_lasso, y_test, test_pred_lasso)\n\nlasso_main_pred = lasso_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = ridge_main_pred\nsub.to_csv('submission_ridge.csv', index=False)\n\"\"\"\n## Elastic net\n\"\"\"\nelastic_model = ElasticNet()\nelastic_model.fit(X_train, y_train)\n\ntrain_pred_elastic = elastic_model.predict(X_train)\ntest_pred_elastic = elastic_model.predict(X_test)\nprint_r2_score(y_train, train_pred_elastic, y_test, test_pred_elastic)\n\nelastic_main_pred = elastic_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = elastic_main_pred\nsub.to_csv('submission_elastic.csv', index=False)\n\"\"\"\n## SVR\n\"\"\"\nsvr_model = SVR(C=1, gamma=1e-6)\nsvr_model.fit(X_train, y_train)\n\ntrain_pred_svr = svr_model.predict(X_train)\ntest_pred_svr = svr_model.predict(X_test)\nprint_r2_score(y_train, train_pred_svr, y_test, test_pred_svr)\n\nsvr_main_pred = svr_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = svr_main_pred\nsub.to_csv('submission_svr.csv', index=False)\n\"\"\"\n## Random Forest Regression\n\"\"\"\nrf_model = RandomForestRegressor()\nrf_model.fit(X_train, y_train)\n\ntrain_pred_rf = rf_model.predict(X_train)\ntest_pred_rf = rf_model.predict(X_test)\nprint_r2_score(y_train, train_pred_rf, y_test, test_pred_rf)\n\nrf_main_pred = rf_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = rf_main_pred\nsub.to_csv('submission_rf.csv', index=False)\n\"\"\"\n## XGB (with tuning)\n\"\"\"\nparams = {  \n    \"n_estimators\": range(1, 500, 50),\n    \"max_depth\": range(1, 20, 2),\n    \"learning_rate\": st.uniform(0.1, 0.9)     \n}\n\nxgbreg = xgboost.XGBRegressor(nthread=-1, objective='reg:squarederror', seed=42)  \ngs = RandomizedSearchCV(xgbreg,params,n_jobs=-1, n_iter=15, cv=10, verbose=3, random_state=42)  \ngs.fit(X_train, y_train) \nrf_best_params = gs.best_params_\nprint(rf_best_params, end=\"\\n\\n\")\n\nlr_main_pred = gs.predict(clean_df_test)\n\n# \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nxgb_model = xgboost.XGBRegressor(\n    n_estimators=rf_best_params[\"n_estimators\"] , \n    max_depth=rf_best_params[\"max_depth\"] , \n    learning_rate=rf_best_params[\"learning_rate\"])\n\nxgb_model.fit(X_train, y_train)\n\ntrain_pred_xgb = xgb_model.predict(X_train)\ntest_pred_xgb = xgb_model.predict(X_test)\nprint_r2_score(y_train, train_pred_xgb, y_test, test_pred_xgb)\n\nxgb_main_pred = xgb_model.predict(clean_df_test)\n \nsub[\"Burn Rate\"] = lr_main_pred\nsub.to_csv('submission_xgb.csv', index=False)\n\"\"\"\n## AdaBoostRegressor\n\"\"\"\nabr_model = AdaBoostRegressor() \nabr_model.fit(X_train, y_train)\n\ntrain_pred_abr = abr_model.predict(X_train)\ntest_pred_abr = abr_model.predict(X_test)\nprint_r2_score(y_train, train_pred_abr, y_test, test_pred_abr)\n\nabr_main_pred = abr_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = abr_main_pred\nsub.to_csv('submission_abr.csv', index=False)\n\"\"\"\n## CatBoostRegressor\n\"\"\"\ncat_model = CatBoostRegressor()\ncat_model.fit(X_train, y_train)\n\ntrain_pred_cat = cat_model.predict(X_train)\ntest_pred_cat = cat_model.predict(X_test)\nprint_r2_score(y_train, train_pred_cat, y_test, test_pred_cat)\n\ncat_main_pred = cat_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = cat_main_pred\nsub.to_csv('submission_cat.csv', index=False)\n\"\"\"\n## GradientBoostingRegressor\n\"\"\"\ngbr_model = GradientBoostingRegressor() \ngbr_model.fit(X_train, y_train)\n\ntrain_pred_gbr = gbr_model.predict(X_train)\ntest_pred_gbr = gbr_model.predict(X_test)\nprint_r2_score(y_train, train_pred_gbr, y_test, test_pred_gbr)\n\ngbr_main_pred = gbr_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = gbr_main_pred\nsub.to_csv('submission_gbr.csv', index=False)\n\"\"\"\n## MLPRegressor\n\"\"\"\nmlp_model = MLPRegressor(random_state=42) \nmlp_model.fit(X_train, y_train)\n\ntrain_pred_mlp = mlp_model.predict(X_train)\ntest_pred_mlp = mlp_model.predict(X_test)\nprint_r2_score(y_train, train_pred_mlp, y_test, test_pred_mlp)\n\nmlp_main_pred = mlp_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = mlp_main_pred\nsub.to_csv('submission_mlp.csv', index=False)\n\"\"\"\n## StackingRegressor\n\"\"\"\nestimators = [('lr', LinearRegression()),\n              ('ridge', Ridge()), \n              ('rf', RandomForestRegressor()),\n              ('xgb', xgboost.XGBRegressor(nthread=-1, learning_rate=0.1185260448662222, max_depth=3, n_estimators=351)),\n              ('mlp', MLPRegressor()),\n              ('ada', AdaBoostRegressor()),\n              ('gbr', GradientBoostingRegressor()),\n              ('cat', CatBoostRegressor())]\n\n\nstacking_model = StackingRegressor(estimators=estimators, final_estimator=GradientBoostingRegressor(random_state=42))\nstacking_model.fit(X_train, y_train)\n\ntrain_pred_stacking = stacking_model.predict(X_train)\ntest_pred_stacking = stacking_model.predict(X_test)\nprint_r2_score(y_train, train_pred_stacking, y_test, test_pred_stacking)\n\nstacking_main_pred = stacking_model.predict(clean_df_test)\n\nsub[\"Burn Rate\"] = stacking_main_pred\nsub.to_csv('submission_stacking.csv', index=False)\n# !pip install tensor-dash\n\n# from tensordash.tensordash import Tensordash\n# histories = Tensordash(\n#     ModelName = 'burnout-1')\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nmodel = Sequential()\nmodel.add(Dense(4, input_dim=10, kernel_initializer='normal', activation='relu'))\nmodel.add(Dense(2670, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\nmodel.summary()\nmodel.compile(loss='mse', optimizer='adam', metrics=['mse','mae'])\nhistory=model.fit(clean_df.loc[:, clean_df.columns != \"Burn Rate\"], \n                  clean_df.loc[:, clean_df.columns == \"Burn Rate\"], \n                  epochs=100, \n                  batch_size=150, \n                  verbose=1, \n                  validation_split=0.08)\n\nneural_main_pred = model.predict(clean_df_test)\nsub[\"Burn Rate\"] = neural_main_pred\nsub.to_csv('submission_neural.csv', index=False)\nprint(history.history.keys())\n# \"Loss\"\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\n\"\"\"\n<center><h2>Project Under Development<\/h2><\/center>\n<img src=\"https:\/\/cdn1.iconfinder.com\/data\/icons\/construction-220\/64\/43-512.png\" width=100 height=100>\n<center><h4>I hope it was helpful!!<\/h4><\/center>\n\n\"\"\"","meta":"{'source': 'AI4Code', 'id': 'b00defe5c4b8d8'}"}
{"id":"43331","text":"\"\"\"\nThis is my first public Notebook. I'm still learning all the in-and-outs of ML and creating\/sharing notebooks.\nAll constructive feedback would be greatly appreciated.\n\"\"\"\n\"\"\"\n# Data discovery\n\"\"\"\n\"\"\"\nLet's first load the data into a Pandas Dataframe\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nrandom_seed = 297\n\nimport os\nclinical_data_filepath = \"..\/input\/heart-failure-clinical-data\/heart_failure_clinical_records_dataset.csv\"\nclinical_data = pd.read_csv(clinical_data_filepath)\n\"\"\"\nUsing Pandas Profiling we analyze the data to check if all data is nicely behaving, and already check for possible correlations with the predictor\n\"\"\"\nimport pandas_profiling\npandas_profile = pandas_profiling.ProfileReport(clinical_data)\npandas_profile.to_widgets()\n\"\"\"\n# Data engineering\n\"\"\"\n\"\"\"\nBased on the pandas profiling, we have several boolean columns which are not yet recognized as such (for example anaemia). We will convert these to booleans.\nIn addition, we can already see that \"Time\" seems to possive a significant negative correlation with \"Death_event\". We expect this will serve as a good predictor compared to the other features.\n\"\"\"\nclean_data = clinical_data.astype({'anaemia': 'bool', 'diabetes': 'bool', 'high_blood_pressure':'bool', 'smoking':'bool'})\nclean_data.head()\n\"\"\"\nNow we'll separate into a training\/test set\n\"\"\"\nfrom sklearn.model_selection import train_test_split\n\n# Split into X and y dataset\ny = clean_data.DEATH_EVENT\nall_features = ['age', 'anaemia', 'creatinine_phosphokinase', 'diabetes','ejection_fraction', 'high_blood_pressure', 'platelets','serum_creatinine', 'serum_sodium', 'sex', 'smoking', 'time']\nfeatures = all_features #For this initial version, we'll just take all features for input. Due to the low amount of samples compared to features, we do fear for overfitting\nX = clean_data[features]\n\n# Create train\/test set\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, test_size=0.2, random_state=random_seed)\n\"\"\"\n# Models\n\nWe'll use a RandomForestClassifier for the actual prediction model. We propose this model due to the low sample size and several boolean features (which mean \"easy\" yes\/no decision leaves).\nFor showing the importance of each feature we'll also train a XGBoost model and plot the importance of each of the features.\n\"\"\"\n\"\"\"\n# RandomForestClassifier\n\"\"\"\nfrom sklearn.ensemble import RandomForestClassifier\n# Specify Model\nhearth_failure_RFCmodel = RandomForestClassifier(random_state=random_seed)\n# Fit Model\nhearth_failure_RFCmodel.fit(train_X, train_y)\nfrom sklearn.metrics import plot_roc_curve\nplot_roc_curve(hearth_failure_RFCmodel, val_X, val_y)\n\"\"\"\n# XGBoost\n\"\"\"\nimport xgboost\n\n# Specify Model\nhearth_failure_XGBmodel = xgboost.XGBClassifier(random_state=random_seed)\n# Fit Model\nhearth_failure_XGBmodel.fit(train_X, train_y)\nfrom sklearn.metrics import plot_roc_curve\nplot_roc_curve(hearth_failure_XGBmodel, val_X, val_y)\n\"\"\"\nAlthough the XGBoost model performs slightly worse compared to the RandomForest (I assume due to overfitting considering the small amount of samples), let's use it to take a look at the importance of the different features.\nAlthough there are several downsides to this importance metric and it might be better to use SHAP values (see [TDS SHAP article](https:\/\/towardsdatascience.com\/explain-your-model-with-the-shap-values-bc36aac4de3d)), it does give us an easy quick overview.\n\"\"\"\nxgboost.plot_importance(hearth_failure_XGBmodel)\n\"\"\"\nAs you can see, this is aligned with our initial thinking that \"Time\" has a big correlation with \"Death_event\" and is hence also used as the primary predictor in the model.\n\"\"\"","meta":"{'source': 'AI4Code', 'id': '4fd6d653c83237'}"}
{"id":"5478","text":"\"\"\"\n# Installation\n\"\"\"\n# Install:\n# Kaggle environments.\n!git clone https:\/\/github.com\/Kaggle\/kaggle-environments.git\n!cd kaggle-environments && pip install .\n\n# GFootball environment.\n!apt-get update -y\n!apt-get install -y libsdl2-gfx-dev libsdl2-ttf-dev\n\n# Make sure that the Branch in git clone and in wget call matches !!\n!git clone -b v2.3 https:\/\/github.com\/google-research\/football.git\n!mkdir -p football\/third_party\/gfootball_engine\/lib\n\n!wget https:\/\/storage.googleapis.com\/gfootball\/prebuilt_gameplayfootball_v2.3.so -O football\/third_party\/gfootball_engine\/lib\/prebuilt_gameplayfootball.so\n!cd football && GFOOTBALL_USE_PREBUILT_SO=1 pip3 install .\n\"\"\"\n# Smart Control Strategy\n\n## Theory\n\nI'm glad to introduce some basic strategy that you may use as basis for your future super-strategy! The aim of this strategy is to move only to regions without enemy football players. That's what I call **smart controll strategy**. More details:\n\n1. Suggestion about distance of football step. You may use my [topic](https:\/\/www.kaggle.com\/c\/google-football\/discussion\/187794) about it, but I've used a suggestion that it takes 0.1 ($STEP\\_HARD\\_DIST$) and 0.05 ($STEP\\_EASY\\_DIST$) for running step and for usual step correspondingly. I do it, cause I've decided to count ball touches by players instead of game steps. It seems like we need about ten running step to achieve target from the middle of the football field (simple suggestion from the leaderboard).\n\n2. After first stage we can estimate, where we would be after each movement action. I call this points as $step\\_point$ (so, one $step\\_point$ for left action, one $step\\_point$ for right action, etc.)\n\n3. For each $step\\_point$ we can count distances for each of enemy football player. If the mininmum of this distances is less, than $SAFE\\_DIST$, we consider $step\\_point$ as safe point.\n\n4. From each $step\\_point$ we choose the nearest to the enemy target. Corresponding actions is a choosen action.\n\n5. Shoot in the last quarter of the football field.\n\"\"\"\n\"\"\"\n## Implementation\n\"\"\"\n%%writefile submission.py\nfrom kaggle_environments.envs.football.helpers import *\n\n@human_readable_agent\ndef agent(obs):\n    import numpy as np\n    import pandas as pd\n    from pandas import Series, DataFrame\n    \n    ###### 0. CONSTANTS ######\n    \n    ENEMY_TARGET = [ 1, 0]\n    OWN_TARGET   = [-1, 0]\n\n    STEP_HARD_DIST = 0.1\n    STEP_EASY_DIST = 0.5 * STEP_HARD_DIST\n    SAFE_DIST = 0.1\n\n    ###### 1. SMART CONTROL: FUNCTIONS ######\n\n    def get_action_steps(step_dist):\n        import numpy as np\n\n        return {\n            Action.Idle:          [                                0,                                 0],\n            Action.Left:          [step_dist * np.cos(        np.pi), step_dist * np.sin(        np.pi)],\n            Action.TopLeft:       [step_dist * np.cos( 0.75 * np.pi), step_dist * np.sin( 0.75 * np.pi)],\n            Action.Top:           [step_dist * np.cos( 0.5  * np.pi), step_dist * np.sin( 0.5  * np.pi)],\n            Action.TopRight:      [step_dist * np.cos( 0.25 * np.pi), step_dist * np.sin( 0.25 * np.pi)],\n            Action.Right:         [step_dist * np.cos(            0), step_dist * np.sin(            0)],\n            Action.BottomRight:   [step_dist * np.cos(-0.25 * np.pi), step_dist * np.sin(-0.25 * np.pi)],\n            Action.Bottom:        [step_dist * np.cos(-0.5  * np.pi), step_dist * np.sin(-0.5  * np.pi)],\n            Action.BottomLeft:    [step_dist * np.cos(-0.75 * np.pi), step_dist * np.sin(-0.75 * np.pi)]\n        }\n\n\n    def get_point_point_dist(point0, point):\n        import numpy as np\n\n        x0, y0 = point0[0], point0[1]\n        x, y = point[0], point[1]\n        return np.sqrt((x0 - x) ** 2 + (y0 - y) ** 2)\n\n\n    def correct_point(point0):\n        x, y = point0[0], point0[1]\n        return (-1 <= x <= 1) and (-1 <= y <= 1)\n\n\n    def get_move_action_info(point0, enemy_points, step_dist=STEP_EASY_DIST):\n        import numpy as np\n\n        target_dists = {}\n        for action, step in get_action_steps(step_dist).items():\n            step_point = [point0[0] + step[0], point0[1] + step[1]]\n            if correct_point(step_point):\n                ## 1. Enemy min distance\n                enemy_distances = [\n                    get_point_point_dist(step_point, enemy_point)\n                    for enemy_point in enemy_points\n                ]\n                enemy_dist = np.array(enemy_distances).min()\n\n                ## 2. Target distance\n                target_dist = get_point_point_dist(step_point, ENEMY_TARGET)\n\n                target_dists[action] = {\n                    \"target_dist\" : round(target_dist, 3),\n                    \"enemy_dist\" : round(enemy_dist, 3)\n                }\n\n        return target_dists\n\n\n    def get_best_move_action(get_move_action_info, safe_dist=SAFE_DIST):\n        from pandas import Series\n\n        safe_actions = {}\n        for action, info in get_move_action_info.items():\n            target_dist, enemy_dist = info[\"target_dist\"], info[\"enemy_dist\"]\n            if enemy_dist >= SAFE_DIST:\n                safe_actions[action] = target_dist\n\n        if len(safe_actions) == 0:\n            return Action.Right ### fix in the future\n\n        target_action = Series(safe_actions).idxmin()\n\n        return target_action\n\n\n    def make_decision(point0, move_action_info):\n        x0, y0 = point0[0], point0[1]\n\n        ## Shot decision\n        if x0 >= 0.5:\n            return Action.Shot\n\n        ## Move decision\n        best_move_action = get_best_move_action(move_action_info)\n        return best_move_action\n    \n    \n    ###### 2. GAME START ######\n    \n    own_points = obs['left_team']\n    enemy_points = obs['right_team']\n    point0 = obs['left_team'][obs['active']]\n    \n    if Action.Sprint not in obs['sticky_actions']:\n        return Action.Sprint\n\n    if obs['ball_owned_player'] == obs['active'] and obs['ball_owned_team'] == 0:\n        ###### OFFENSE: SMART CONTROL ######\n        move_action_info = get_move_action_info(point0, enemy_points)\n        return make_decision(point0, move_action_info)\n    else:\n        ###### DEFENCE: OLD STRATEGY ######\n        if obs['ball'][0] > point0[0] + 0.05:\n            return Action.Right\n        if obs['ball'][0] < point0[0] - 0.05:\n            return Action.Left\n        if obs['ball'][1] > point0[1] + 0.05:\n            return Action.Bottom\n        if obs['ball'][1] < point0[1] - 0.05:\n            return Action.Top\n        return Action.Slide\n# Set up the Environment.\nfrom kaggle_environments import make\n\nenv = make(\n    \"football\",\n    configuration={\n        \"save_video\": True,\n        \"scenario_name\": \"11_vs_11_kaggle\",\n        \"running_in_notebook\": True\n    }\n)\n\noutput = env.run([\"\/kaggle\/working\/submission.py\", \"\/kaggle\/working\/submission.py\"])[-1]\n\nprint('Left player: reward = %s, status = %s, info = %s' % (output[0]['reward'], output[0]['status'], output[0]['info']))\nprint('Right player: reward = %s, status = %s, info = %s' % (output[1]['reward'], output[1]['status'], output[1]['info']))\nenv.render(mode=\"human\", width=800, height=600)","meta":"{'source': 'AI4Code', 'id': '0a2a926c3a9918'}"}
{"id":"47867","text":"\"\"\"\n Import packages and Data\n\"\"\"\nfrom surprise import Reader, Dataset, SVD, evaluate\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\nratings = pd.read_csv('..\/input\/ml-100k\/u.data', sep='\\t', names=r_cols, index_col='movie_id', encoding='latin-1')\n\nm_cols = ['movie_id', 'title', 'release_date', 'video_release_date', 'imdb_url','unknown', 'Action', 'Adventure',\\\n          'Animation', 'Children\\'s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy','Film-Noir', 'Horror',\\\n          'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western']\nmovies = pd.read_csv('..\/input\/ml-100k\/u.item', sep='|', names=m_cols, index_col=0, encoding='latin-1')\n\nu_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']\nusers = pd.read_csv('..\/input\/ml-100k\/u.user', sep='|', names=u_cols, encoding='latin-1', parse_dates=True)\nfrom datetime import datetime\n\nratings['unix_timestamp'] = ratings['unix_timestamp'].apply(datetime.fromtimestamp)\nratings.columns = ['user_id', 'rating', 'time']\nratings.head(10)\n\"\"\"\nHere we can see how ratings distributed.\n\"\"\"\nratings['rating'].hist(bins=9)\n\"\"\"\nSo far we will only use the movie title from this DataFrame. We may need the types of the movie later in our model.\n\"\"\"\nmovies['release_date'] = pd.to_datetime(movies['release_date'])\nmovies.head(10)\nfor i in users['occupation'].unique():\n    users[i] = users['occupation'] == i\nusers.drop('occupation', axis=1, inplace=True)\nusers.head(10)\n\"\"\"\nFor each movie we count how many ratings it got, and what's the mean and standard deviation.\n\"\"\"\nratings_movie_summary = ratings.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\nratings_movie_summary.head(10)\n\"\"\"\nFor each user, we count how many ratings he or she gives, and the mean and standard deviation as well.\n\"\"\"\nratings_user_summary = ratings.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\nratings_user_summary.head(10)\nratings_movie_summary.sort_values(by='count')['count'].hist(bins=20)\nratings_movie_summary.sort_values(by='mean')['mean'].hist(bins=20)\nratings_user_summary.sort_values(by='count')['count'].hist(bins=20)\nratings_user_summary.sort_values(by='mean')['mean'].hist(bins=20)\n\"\"\"\nWe create a pivot table for ratings and store the total mean and standard deviation values.\n\"\"\"\nratings_p = pd.pivot_table(ratings, values='rating', index='user_id', columns='movie_id')\nratings_p.iloc[:10, :10]\nmean = ratings_p.stack().mean()\nstd = ratings_p.stack().std()\n\"\"\"\n**Notations:**\n\n$\\mu_i$ : The mean of all ratings received by movie i.\n\n$\\mu_u$ : The mean of all ratings from user u.\n\n$\\mu$ : The mean of all ratings.\n\n$\\sigma_i$ : The standard deviation of all ratings received by movie i.\n\n$\\sigma_u$ : The standard deviation of all ratings from user u.\n\n$r_{ui}$ : User u's rating on movie i.\n\n$\\hat{r}_{ui}$ : Prediction about user u's rating on movie i.\n\n$N^k_u(i)$ : k nearest neighbors of movie i, that are rated by user u.\n\"\"\"\n\"\"\"\n- **Baseline Model**\n\nIn the first baseline model, we predict the rating from a specific user on a specific movie, just by the average rating that a movie receives, with adjustment by how this user's average rating compared with the total average.\n\n$$\\hat{r}_{ui} = \\mu_u + \\mu_i - \\mu$$\n\"\"\"\nmovie_mean = np.ones(ratings_p.shape)\nmovie_mean = pd.DataFrame(movie_mean * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nuser_mean = np.ones(ratings_p.T.shape)\nuser_mean = pd.DataFrame(user_mean * np.array(ratings_user_summary['mean'])).T\npred = movie_mean + user_mean - mean\nscore = abs(np.array(ratings_p) - pred)\nscore_2 = score ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\nprint('MAE: {:.4f}'.format(score.stack().mean()))\n\"\"\"\nSince we don't have train-test-split in our prediction, we are actually using the mean of the data to predict every single data. Therefore, the score might be biased because of data leakage. So we do cross-validation on the model.\n\"\"\"\nfrom sklearn.model_selection import KFold\n\nkfolds = KFold(n_splits = 5, random_state = 13)\nrmse = []\nmae = []\ni = 0\nprint('Evaluating RMSE, MAE of the Baseline Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    movie_mean = np.ones(ratings_p.shape)\n    movie_mean = pd.DataFrame(movie_mean * np.array(train_movie_summary['mean']).reshape(1,1682))\n    user_mean = np.ones(ratings_p.T.shape)\n    user_mean = pd.DataFrame(user_mean * np.array(train_user_summary['mean'])).T\n    train_p = movie_mean + user_mean - mean\n    score = abs(np.array(test_p) - train_p)\n    score_2 = score ** 2\n    rmse += [np.sqrt(score_2.stack().mean())]\n    mae += [score.stack().mean()]\n    i += 1\n    print('Fold', i)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **Baseline_Plus Model**\n\nIn the second model, we want to do it slightly better using z-score.\n\n$$\\hat{r}_{ui} = \\mu_u + \\sigma_u * \\frac{(\\mu_i - \\mu)}{\\sigma}$$\n\"\"\"\nmovie_mean = np.ones(ratings_p.shape)\nmovie_mean = pd.DataFrame(movie_mean * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nuser_mean = np.ones(ratings_p.T.shape)\nuser_mean = pd.DataFrame(user_mean * np.array(ratings_user_summary['mean'])).T\nuser_std = np.ones(ratings_p.T.shape)\nuser_std = pd.DataFrame(user_std * np.array(ratings_user_summary['std'])).T\npred_plus = user_mean + (movie_mean - mean)\/std * user_std\nscore_plus = abs(np.array(ratings_p) - pred_plus)\nscore_2_plus = score_plus ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2_plus.stack().mean())))\nprint('MAE: {:.4f}'.format(score_plus.stack().mean()))\n\"\"\"\nUse our baseline model to recommend movies for user 196.\n\"\"\"\nuser_196 = movies[['title', 'release_date']]\nuser_196['Estimate_Score'] = np.array(pred_plus.loc[195])\nuser_196 = user_196.sort_values('Estimate_Score', ascending=False)\nprint(user_196.head(10))\n\"\"\"\nHere is the cross-validation score for our second model\n\"\"\"\nrmse_plus = []\nmae_plus = []\ni = 0\nprint('Evaluating RMSE, MAE of the Baseline_Plus Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    movie_mean = np.ones(ratings_p.shape)\n    movie_mean = pd.DataFrame(movie_mean * np.array(train_movie_summary['mean']).reshape(1,1682))\n    user_mean = np.ones(ratings_p.T.shape)\n    user_mean = pd.DataFrame(user_mean * np.array(train_user_summary['mean'])).T\n    user_std = np.ones(ratings_p.T.shape)\n    user_std = pd.DataFrame(user_std * np.array(train_user_summary['std'])).T\n    train_p = user_mean + (movie_mean - mean)\/std * user_std\n    score = abs(np.array(test_p) - train_p)\n    score_2 = score ** 2\n    rmse_plus += [np.sqrt(score_2.stack().mean())]\n    mae_plus += [score.stack().mean()]\n    i += 1\n    print('Fold', i)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_plus)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_plus)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **Baseline Model with SVM\/Gradient Boosting**\n\nWe can improve this model even more, by applying SVM regressor or Gradient Boosting on each approximation, instead of just using z-score.\n\"\"\"\n\"\"\"\n- SVM\n\"\"\"\nfrom sklearn.svm import SVR\n\nmovie_mean = np.ones(ratings_p.shape)\nmovie_mean = pd.DataFrame(movie_mean * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nX = np.array(ratings_p*0) + movie_mean\nsvm = SVR(gamma=1, C=1)\npred_svm = ratings_p.copy()\nfor i in range(ratings_p.shape[0]):\n    svm.fit(np.array(X.iloc[i].dropna()).reshape(-1,1), ratings_p.iloc[i].dropna())\n    pred_svm.iloc[i] = svm.predict(np.array(movie_mean.iloc[0]).reshape(-1,1))\nscore_svm = abs(np.array(ratings_p) - pred_svm)\nscore_2_svm = score_svm ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2_svm.stack().mean())))\nprint('MAE: {:.4f}'.format(score_svm.stack().mean()))\n\"\"\"\nUse our svm model to recommend movies for user 196.\n\"\"\"\nuser_196_svm = movies[['title', 'release_date']]\nuser_196_svm['Estimate_Score'] = np.array(pred_svm.loc[195])\nuser_196_svm = user_196_svm.sort_values('Estimate_Score', ascending=False)\nprint(user_196_svm.head(10))\n\"\"\"\nCross-Validation\n\"\"\"\nrmse_svm = []\nmae_svm = []\nfold = 0\nmovie_mean = pd.DataFrame(np.ones(ratings_p.shape) * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nprint('Evaluating RMSE, MAE of the Baseline_SVM Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    train_p = pd.pivot_table(train, values='rating', index='user_id', columns='movie_id', dropna=False)\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    train_mean = pd.DataFrame(np.ones(ratings_p.shape) * np.array(train_movie_summary['mean']).reshape(1,1682))\n    X = np.array(train_p*0) + train_mean\n    pred = ratings_p.copy()\n    for i in range(ratings_p.shape[0]):\n        svm.fit(np.array(X.iloc[i].dropna()).reshape(-1,1), train_p.iloc[i].dropna())\n        pred.iloc[i] = svm.predict(np.array(movie_mean.iloc[0]).reshape(-1,1))\n    score = abs(np.array(test_p) - pred)\n    score_2 = score ** 2\n    rmse_svm += [np.sqrt(score_2.stack().mean())]\n    mae_svm += [score.stack().mean()]\n    fold += 1\n    print('Fold', fold)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_svm)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_svm)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\nGradient Boosting\n\"\"\"\nfrom xgboost import XGBRegressor\n\nmovie_mean = np.ones(ratings_p.shape)\nmovie_mean = pd.DataFrame(movie_mean * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nX = np.array(ratings_p*0) + movie_mean\nxgb = XGBRegressor(learning_rate=0.1, max_depth=2, min_child_weight=10, gamma=1)\npred_xgb = ratings_p.copy()\nfor i in range(ratings_p.shape[0]):\n    xgb.fit(np.array(X.iloc[i].dropna()).reshape(-1,1), ratings_p.iloc[i].dropna())\n    pred_xgb.iloc[i] = xgb.predict(np.array(movie_mean.iloc[0]).reshape(-1,1))\nscore_xgb = abs(np.array(ratings_p) - pred_xgb)\nscore_2_xgb = score_xgb ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2_xgb.stack().mean())))\nprint('MAE: {:.4f}'.format(score_xgb.stack().mean()))\n\"\"\"\nCross-Validation\n\"\"\"\nrmse_xgb = []\nmae_xgb = []\nfold = 0\nmovie_mean = pd.DataFrame(np.ones(ratings_p.shape) * np.array(ratings_movie_summary['mean']).reshape(1,1682))\nprint('Evaluating RMSE, MAE of the Baseline_XGB Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    train_p = pd.pivot_table(train, values='rating', index='user_id', columns='movie_id', dropna=False)\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    train_mean = pd.DataFrame(np.ones(ratings_p.shape) * np.array(train_movie_summary['mean']).reshape(1,1682))\n    X = np.array(train_p*0) + train_mean\n    pred = ratings_p.copy()\n    for i in range(ratings_p.shape[0]):\n        xgb.fit(np.array(X.iloc[i].dropna()).reshape(-1,1), train_p.iloc[i].dropna())\n        pred.iloc[i] = xgb.predict(np.array(movie_mean.iloc[0]).reshape(-1,1))\n    score = abs(np.array(test_p) - pred)\n    score_2 = score ** 2\n    rmse_xgb += [np.sqrt(score_2.stack().mean())]\n    mae_xgb += [score.stack().mean()]\n    fold += 1\n    print('Fold', fold)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_xgb)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_xgb)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **Pearsons'R Correlation Model**\n\nWe might also want to recommend movies just for a specific movie. Like the recommendation list showed on the webpage of a specific movie.\n\nHere we recommend new movies based on the Pearsons'R correlation between movies.\n\"\"\"\ndef recommend(movie_title, min_count):\n    print(\"For movie ({})\".format(movie_title))\n    print(\"- Top 10 movies recommended based on Pearsons'R correlation - \")\n    i = movies[movies['title'] == movie_title].index[0]\n    target = ratings_p[i]\n    similar_to_target = ratings_p.corrwith(target)\n    corr_target = pd.DataFrame(similar_to_target, columns = ['PearsonR'])\n    corr_target.dropna(inplace = True)\n    corr_target = corr_target.sort_values('PearsonR', ascending = False)\n    corr_target.index = corr_target.index.map(int)\n    corr_target = corr_target.join(movies).join(ratings_movie_summary)\\\n                  [['PearsonR', 'title', 'count', 'mean']]\n    print (corr_target[corr_target['count']>min_count][:10].to_string(index=False))\nrecommend('Shawshank Redemption, The (1994)', 10)\n\"\"\"\n- **K-Nearest Neighbor (kNN) Model**\n\nWe can treat the **Pearsons' R Correlation** between movies as the distance, and using these distances to build a **K-Nearest Neighbor model**.\n\nNotations:\n\n$r_{ui}$ : User u's rating on movie i.\n\n$\\hat{r}_{ui}$ : Prediction about user u's rating on movie i.\n\n$N^k_u(i)$ : k nearest neighbors of movie i, that are rated by user u.\n\nThen we can have our kNN model as:\n\n$$\\hat{r}_{ui} = \\frac{\\sum_{j \\in N^k_u(i)} corr(i, j) * r_{uj}}{\\sum_{j \\in N^k_u(i)} corr(i, j)}$$\n\"\"\"\nsim = ratings_p.corr().abs()\nsim.iloc[:10, :10]\nknn_pred = ratings_p.copy()\nfor i in ratings_p.index:\n    if i % 10 == 0:\n        print(i)\n    N = sim.loc[ratings[ratings['user_id'] == i].index]\n    for j in ratings_p.columns:\n        try:\n            N_k = N[j].sort_values(ascending=False, kind='heapsort').drop(j)[:30]\n        except:\n            N_k = N[j].sort_values(ascending=False, kind='heapsort')[:30]\n        weighted_rating = N_k*ratings_p.loc[i, N_k.index]\n        knn_pred.loc[i, j] = weighted_rating.sum()\/N_k.sum()\n\nknn_pred.iloc[:10, :10]\nscore_knn = abs(np.array(ratings_p) - knn_pred)\nscore_2_knn = score_knn ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2_knn.stack().mean())))\nprint('MAE: {:.4f}'.format(score_knn.stack().mean()))\n\"\"\"\nCross-Validation on kNN\n\"\"\"\nrmse_knn = []\nmae_knn = []\nfold = 0\nprint('Evaluating RMSE, MAE of the Baseline_XGB Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    train_p = pd.pivot_table(train, values='rating', index='user_id', columns='movie_id', dropna=False)\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    knn_pred = ratings_p.copy()\n    for i in ratings_p.index:\n        N = sim.loc[train[train['user_id'] == i].index]\n        for j in ratings_p.columns:\n            try:\n                N_k = N[j].sort_values(ascending=False, kind='heapsort').drop(j)[:30]\n            except:\n                N_k = N[j].sort_values(ascending=False, kind='heapsort')[:30]\n            weighted_rating = N_k*train_p.loc[i, N_k.index]\n            knn_pred.loc[i, j] = weighted_rating.sum()\/N_k.sum()\n    score = abs(np.array(test_p) - knn_pred)\n    score_2 = score ** 2\n    rmse_knn += [np.sqrt(score_2.stack().mean())]\n    mae_knn += [score.stack().mean()]\n    fold += 1\n    print('Fold', fold)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_knn)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_knn)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **kNN_Plus Model**\n\nNow we can improve our KNN model just by the same trick we used on our baseline model: adjust by the z-score.\n\nNotation:\n\n$\\mu_i$ : The mean of all ratings received by movie i.\n\n$\\sigma_i$ : The standard deviation of all ratings received by movie i.\n\n$$\\hat{r}_{ui} = \\mu_i + \\sigma_i * \\frac{\\sum_{j \\in N^k_u(i)} corr(i, j) *( r_{uj} - \\mu_j) \/ \\sigma_j}{\\sum_{j \\in N^k_u(i)} corr(i, j)}$$\n\"\"\"\nknn_plus_pred = ratings_p.copy()\nfor i in ratings_p.index:\n    N = sim.loc[ratings[ratings['user_id'] == i].index]\n    for j in ratings_p.columns:\n        try:\n            N_k = N[j].sort_values(ascending=False, kind='heapsort').drop(j)[:30]\n        except:\n            N_k = N[j].sort_values(ascending=False, kind='heapsort')[:30]\n        weighted_rating = N_k*(ratings_p.loc[i, N_k.index] - ratings_movie_summary.loc[N_k.index, 'mean'])\/ ratings_movie_summary.loc[N_k.index, 'std']\n        knn_plus_pred.loc[i, j] = weighted_rating.sum()\/N_k.sum() * ratings_movie_summary.loc[j, 'std'] + ratings_movie_summary.loc[j, 'mean']\n\nknn_plus_pred.iloc[:10, :10]\nscore_knn_plus = abs(np.array(ratings_p) - knn_plus_pred)\nscore_2_knn_plus = score_knn ** 2\nprint('RMSE: {:.4f}'.format(np.sqrt(score_2_knn_plus.stack().mean())))\nprint('MAE: {:.4f}'.format(score_knn_plus.stack().mean()))\n\"\"\"\nCross-Validation on kNN_Plus\n\"\"\"\nrmse_knn_plus = []\nmae_knn_plus = []\nfold = 0\nprint('Evaluating RMSE, MAE of the Baseline_XGB Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    train = ratings.copy()\n    test = ratings.copy()\n    train['rating'].iloc[test_index] = np.NaN\n    test['rating'].iloc[train_index] = np.NaN\n    train_movie_summary = train.groupby('movie_id')['rating'].agg(['count', 'mean', 'std'])\n    train_user_summary = train.groupby('user_id')['rating'].agg(['count', 'mean', 'std'])\n    train_p = pd.pivot_table(train, values='rating', index='user_id', columns='movie_id', dropna=False)\n    test_p = pd.pivot_table(test, values='rating', index='user_id', columns='movie_id', dropna=False)\n    knn_plus_pred = ratings_p.copy()\n    for i in ratings_p.index:\n        if i % 100 == 0:\n            print(i)\n        N = sim.loc[train[train['user_id'] == i].index]\n        for j in ratings_p.columns:\n            try:\n                N_k = N[j].sort_values(ascending=False).drop(j)[:30]\n            except:\n                N_k = N[j].sort_values(ascending=False)[:30]\n            weighted_rating = N_k*(train_p.loc[i, N_k.index] - train_movie_summary.loc[N_k.index, 'mean'])\/ train_movie_summary.loc[N_k.index, 'std']\n            knn_plus_pred.loc[i, j] = weighted_rating.sum()\/N_k.sum() * train_movie_summary.loc[j, 'std'] + train_movie_summary.loc[j, 'mean']\n    score = abs(np.array(test_p) - knn_plus_pred)\n    score_2 = score ** 2\n    rmse_knn_plus += [np.sqrt(score_2.stack().mean())]\n    mae_knn_plus += [score.stack().mean()]\n    fold += 1\n    print('Fold', fold)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.stack().mean())))\n    print('MAE: {:.4f}'.format(score.stack().mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_knn_plus)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_knn_plus)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **SVD**\n\nAccording to Matrix Factorization Techniques for Recommender Systems, written by Yehoda Koren, Robert Bell, and Chris Volinsky, Our prediction looks like this:\n\n$$\\hat{r}_{ui} = \\mu + b_u + b_i + q_i^Tp_u$$\n\nWhere $q_i$ and $p_u$ are the corresponding factor vectors for movie $i$ and user $u$. So $q_i ^ T p_u$ term is the interaction factor between movie $i$ and user $u$.\n\nAnd $\\mu + b_u + b_i$ is the bias term. $b_u$ and $b_i$ represents the factor that depends solely on user $u$ or on movie $i$.\n\nHence, we want to minimize the following:\n\n$$\\min_{p^*, q^*, b^*} \\sum_{(u, i) \\in R} (r_{ui} - \\hat{r}_{ui})^2 + \\lambda (\\| p_u \\|^2 + \\| q_i \\|^2 + b_u ^2 + b_i ^2)$$\n\nAnd we achive this by doing stochastic gradient descent on $p_u, q_i, b_u, $ and $b_i$. Namely:\n\n$$b_u  \\leftarrow b_u + \\gamma (e_{ui} - \\lambda b_u)$$\n$$b_i  \\leftarrow b_i + \\gamma (e_{ui} - \\lambda b_i)$$\n$$p_u  \\leftarrow p_u + \\gamma (e_{ui} \\cdot q_i - \\lambda p_u)$$\n$$q_i  \\leftarrow q_i + \\gamma (e_{ui} \\cdot p_u - \\lambda q_i)$$\n\nWhere $\\gamma$ is the learning rate, and $\\lambda$ is the regularization, and we want to run this gradient descent by $n$ times. (So far we set $\\gamma = 0.005$, $\\lambda = 0.1$, and $n=100$. And we want number of factors as $k=70$.)\n\"\"\"\nfrom datetime import datetime\n\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\nratings = pd.read_csv('..\/input\/ml-100k\/u.data', sep='\\t', names=r_cols, encoding='latin-1')\nratings['unix_timestamp'] = ratings['unix_timestamp'].apply(datetime.fromtimestamp)\nratings.columns = ['user_id', 'movie_id', 'rating', 'time']\nratings.head(10)\nlr = 0.005 # Learning Rate(Gamma)\nreg = 0.1 # regularization(Lambda)\nn = 100 # Number of iterations\nk = 70 # Number of factors\nu = ratings_p.shape[0] # Number of users\ni = ratings_p.shape[1] # Number of movies\n\nbu = np.zeros(u) # A series of bias constant, one for each user\nbi = np.zeros(i) # A series of bias constant, one for each movie\npu = np.random.mtrand._rand.normal(0, 0.1, (u, k)) # A series of vectors(rows) with length k, one row for each user\nqi = np.random.mtrand._rand.normal(0, 0.1, (i, k)) # A series of vectors(rows) with length k, one row for each movie\nratings_array = np.array(ratings.drop('time', axis=1))\nfor i in range(n): # For each iteration\n    for row in ratings_array: # For each instance\n        user_id = row[0]-1\n        movie_id = row[1]-1\n        rating = row[2]\n        mult = 0\n        for j in range(k): # For each factor\n            mult += qi[movie_id, j] * pu[user_id, j] # Compute the dot product(interaction q_i^Tp_u)\n        error = rating - (mean + bu[user_id] + bi[movie_id] + mult) # error = rating - (prediction)\n        bu[user_id] += lr * (error - reg * bu[user_id]) # Update Bias on user\n        bi[movie_id] += lr * (error - reg * bi[movie_id]) # Update Bias on movie\n        for k in range(k): # Again for each factor\n            pu_k = pu[user_id, k]\n            qi_k = qi[movie_id, k]\n            pu[user_id, k] += 0.005 * (error * qi_k - 0.1 * pu_k) # Update this factor using the final error\n            qi[movie_id, k] += 0.005 * (error * pu_k - 0.1 * qi_k) # Update this factor\nU = ratings['user_id'].unique()\nI = ratings['movie_id'].unique()\ndef svd_pred(user_id, movie_id):\n    pred = mean\n    if user_id in U:\n        pred += bu[user_id]\n    if movie_id in I:\n        pred += bi[movie_id]\n    if (user_id in U) and (movie_id in I):\n        pred += np.dot(qi[movie_id], pu[user_id])\n    return pred\n\nsvd_pred_ratings = np.array(ratings)\nfor row in svd_pred_ratings:\n    row[3] = svd_pred(row[0]-1, row[1]-1)\nsvd_pred_ratings = pd.DataFrame(svd_pred_ratings, columns=['user_id', 'movie_id', 'rating', 'pred'])\n\nprint('RMSE: {:.4f}'.format(np.sqrt(((svd_pred_ratings['pred'] - svd_pred_ratings['rating']) ** 2).mean())))\nprint('MAE: {:.4f}'.format(abs(svd_pred_ratings['pred'] - svd_pred_ratings['rating']).mean()))\n\"\"\"\nCross-Validation for SVD\n\"\"\"\nrmse_svd = []\nmae_svd = []\nfold = 0\nprint('Evaluating RMSE, MAE of the SVD Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    \n    u = ratings_p.shape[0] # Number of users\n    i = ratings_p.shape[1] # Number of movies\n    bu = np.zeros(u) # A series of bias constant, one for each user\n    bi = np.zeros(i) # A series of bias constant, one for each movie\n    pu = np.random.mtrand._rand.normal(0, 0.1, (u, k)) # A series of vectors(rows) with length k, one row for each user\n    qi = np.random.mtrand._rand.normal(0, 0.1, (i, k)) # A series of vectors(rows) with length k, one row for each movie\n    \n    ratings_array = ratings.iloc[train_index]\n    ratings_array = np.array(ratings_array.drop('time', axis=1))\n    for i in range(n): # For each iteration\n        for row in ratings_array: # For each instance\n            user_id = row[0]-1\n            movie_id = row[1]-1\n            rating = row[2]\n            mult = 0\n            for j in range(k): # For each factor\n                mult += qi[movie_id, j] * pu[user_id, j] # Compute the dot product(interaction q_i^Tp_u)\n            error = rating - (mean + bu[user_id] + bi[movie_id] + mult) # error = rating - (prediction)\n            bu[user_id] += lr * (error - reg * bu[user_id]) # Update Bias on user\n            bi[movie_id] += lr * (error - reg * bi[movie_id]) # Update Bias on movie\n            for k in range(k): # Again for each factor\n                pu_k = pu[user_id, k]\n                qi_k = qi[movie_id, k]\n                pu[user_id, k] += 0.005 * (error * qi_k - 0.1 * pu_k) # Update this factor using the final error\n                qi[movie_id, k] += 0.005 * (error * pu_k - 0.1 * qi_k) # Update this factor\n    \n    svd_pred_ratings = np.array(ratings.iloc[test_index])\n    for row in svd_pred_ratings:\n        row[3] = svd_pred(row[0]-1, row[1]-1)\n    svd_pred_ratings = pd.DataFrame(svd_pred_ratings, columns=['user_id', 'movie_id', 'rating', 'pred'])\n    \n    score = abs(svd_pred_ratings['pred'] - svd_pred_ratings['rating'])\n    score_2 = score ** 2\n    rmse_svd += [np.sqrt(score_2.mean())]\n    mae_svd += [score.mean()]\n    fold += 1\n    print('Fold', fold)\n    print('RMSE: {:.4f}'.format(np.sqrt(score_2.mean())))\n    print('MAE: {:.4f}'.format(score.mean()))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_svd)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_svd)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\n- **Supervised Learning Model**\n\nGradient Boosting as supervised learning.\n\nI take each user-movie combination as one instance, and hence take full use of the features from the user and movie.\n\"\"\"\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\n#occupation = {'none': 0, 'administrator': 1, 'artist': 2, 'doctor': 3, 'educator': 4, 'engineer': 5, 'entertainment': 6,\\\n#              'executive': 7, 'healthcare': 8, 'homemaker': 9, 'lawyer': 10, 'librarian': 11, 'marketing': 12,\\\n#              'programmer': 13, 'salesman': 14, 'scientist': 15, 'student': 16, 'technician': 17, 'writer': 18,\\\n#              'retired': 19, 'other': 20}\ndf = ratings_p.stack(dropna=False).reset_index()\ndf.columns = ['user_id', 'movie_id', 'rating']\ndf = df.merge(users, on='user_id')\ndf = df.merge(movies, on='movie_id')\ndf['sex'] = df['sex'].replace(['F', 'M'], [1, 0])\n#df['occupation'] = df['occupation'].replace(occupation)\ndf.drop(['release_date', 'video_release_date', 'imdb_url', 'title', 'zip_code'], axis=1, inplace=True)\ndf_train = df.dropna()\ndf.head(10)\nrmse_reg = []\nmae_reg = []\ni = 0\nprint('Evaluating RMSE, MAE of the XGB_Reg Model. \\n')\nprint('-'*12)\nfor train_index, test_index in kfolds.split(ratings):\n    X_train = df_train.drop('rating', axis=1).iloc[train_index]\n    y_train = df_train['rating'].iloc[train_index]\n    X_test = df_train.drop('rating', axis=1).iloc[test_index]\n    y_test = df_train['rating'].iloc[test_index]\n    xgb = XGBRegressor(learning_rate=0.1, max_depth=10, min_child_weight=10, gamma=0.03).fit(X_train, y_train)\n    y_pred = xgb.predict(X_test)\n    score = abs(y_test - y_pred)\n    score_2 = score**2\n    rmse_reg += [np.sqrt(np.mean(score_2))]\n    mae_reg += [np.mean(score)]\n    i += 1\n    print('Fold', i)\n    print('RMSE: {:.4f}'.format(np.sqrt(np.mean(score_2))))\n    print('MAE: {:.4f}'.format(np.mean(score)))\n    print('-'*12)\nprint('-'*12)\nprint('Mean RMSE: {:.4f}'.format(np.mean(rmse_reg)))\nprint('Mean MAE: {:.4f}'.format(np.mean(mae_reg)))\nprint('-'*12)\nprint('-'*12)\n\"\"\"\nHere are the Cross Validation RMSE and MAE scores for all models in this notebook\n\"\"\"\nbaseline_results = {'Baseline': [np.mean(rmse), np.mean(mae)], 'Baseline_Plus': [np.mean(rmse_plus), np.mean(mae_plus)],\\\n                    'SVM': [np.mean(rmse_svm), np.mean(mae_svm)], 'XGradientBoosting': [np.mean(rmse_xgb), np.mean(mae_xgb)],\\\n                    'kNN': [np.mean(rmse_knn), np.mean(mae_knn)], 'kNN_Plus': [np.mean(rmse_knn_plus), np.mean(mae_knn_plus)],\\ \n                    'SVD': [np.mean(rmse_svd), np.mean(mae_svd)], 'Supervised_Learning': [np.mean(rmse_reg), np.mean(mae_reg)]}\nbaseline_results = pd.DataFrame(baseline_results, index=['RMSE', 'MAE']).T\nbaseline_results\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(10, 6))\nax = plt.subplot(111)\nax.set_axisbelow(True)\nplt.bar(np.arange(1, 3*baseline_results.shape[0], 3), baseline_results['RMSE']-0.7, width=1, label='RMSE')\nplt.bar(np.arange(2, 3*baseline_results.shape[0], 3), baseline_results['MAE']-0.7, width=1, label='MAE')\nplt.xticks(np.arange(1.5, 3*baseline_results.shape[0], 3), baseline_results.index)\nplt.yticks(np.arange(0, 0.5, 0.1), [0.7, 0.8, 0.9, 1.0, 1.1])\nplt.grid()\nplt.legend()\nplt.show()\n\"\"\"\nThe next model takes more than 6 hours to run. So I don't commit it this time. I'll move it into a seperate notebook.\n\"\"\"\n\"\"\"\n- **Improvement on Gradient Boosting Model (?)**\n\nIn the previous model, we use rating as the target variable, therefore the model knows nothing about what ratings that the movie has received, and what ratings the user has given. Now we might want to include all related ratings, both from the same user and for the same movie, as features in our model.\n\nThis model takes a much longer time than others.\n\nNotice that two of the slots on each row in these new features will actually contain the target value! However, I right now have no clue that this will result in data leakage since the model has no idea where these hidden correct ratings locate.\n\nIt makes sense that this model will beat all other models, since it contains more information like the age and gender of the user, genre of the movie, etc. However, it is still not safe to say that we are free of data leakage here. So I leave a question mark here.\n\"\"\"\n### BUG. Need Fix. ###\n\n#df = df.merge(ratings_p, left_on='user_id', right_index=True)\n#df = df.merge(ratings_p.T, left_on='movie_id', right_index=True)\n#df.head(10)\n#df_train = df_train.merge(ratings_p, left_on='user_id', right_index=True)\n#df_train = df_train.merge(ratings_p.T, left_on='movie_id', right_index=True)\n#df_train.head(10)\n#for i in range(df_train.shape[0]):\n#    if i % 1000 == 0:\n#        print(i)\n#    row = df_train.iloc[i]\n#    df_train.iloc[i][str(row[1])+'_x'] = np.NaN\n#    df_train.iloc[i][str(row[0])+'_y'] = np.NaN\n\"\"\"\nTrain-test-split score.\n\"\"\"\n#X_train, X_test, y_train, y_test = train_test_split(df_train.drop(['rating'], axis=1), df_train['rating'], random_state = 0)\n#xgb = XGBRegressor(learning_rate=0.1, max_depth=10, min_child_weight=10, gamma=0.03).fit(X_train, y_train)\n#y_pred = xgb.predict(X_test)\n#score = abs(y_test - y_pred)\n#score_2 = score**2\n#print('RMSE: {:.4f}'.format(np.sqrt(np.mean(score_2))))\n#print('MAE: {:.4f}'.format(np.mean(score)))\n\n# RMSE: 0.7401\n# MAE: 0.5674\n\"\"\"\nUse our model to recommond movie for user 196.\n\"\"\"\n\"\"\"\nHere is all movies rated by user 196.\n\"\"\"\n#pred_196 = df[df['user_id']==196]\n#pred_196 = pred_196.merge(ratings_p, left_on='user_id', right_index=True)\n#pred_196 = pred_196.merge(ratings_p.T, left_on='movie_id', right_index=True)\n#pred_196.head(10)\n\"\"\"\nHere is the recommendation to user 196.\n\"\"\"\n#xgb = XGBRegressor(learning_rate=0.1, max_depth=10, min_child_weight=10, gamma=0.03)\\\n#      .fit(df_train.drop(['rating'], axis=1), df_train['rating'])\n#pred_196['rating'] = xgb.predict(pred_196.drop('rating', axis=1))\n#user_196_reg = movies[['movie_id', 'title', 'release_date']]\n#user_196_reg['Estimate_Score'] = np.array(pred_196['rating'])\n#user_196_reg.drop('movie_id', axis=1, inplace=True)\n#user_196_reg = user_196_reg.sort_values('Estimate_Score', ascending=False)\n#print(user_196_reg.head(10))\n\"\"\"\nCross-Validation\n\"\"\"\n#rmse_reg_plus = []\n#mae_reg_plus = []\n#i = 0\n#print('Evaluating RMSE, MAE of the XGB_Reg_Plus Model. \\n')\n#print('-'*12)\n#for train_index, test_index in kfolds.split(ratings):\n#    X_train = df_train.drop('rating', axis=1).iloc[train_index]\n#    y_train = df_train['rating'].iloc[train_index]\n#    X_test = df_train.drop('rating', axis=1).iloc[test_index]\n#    y_test = df_train['rating'].iloc[test_index]\n#    xgb = XGBRegressor(learning_rate=0.1, max_depth=10, min_child_weight=10, gamma=0.03).fit(X_train, y_train)\n#    y_pred = xgb.predict(X_test)\n#    score = abs(y_test - y_pred)\n#    score_2 = score**2\n#    rmse_reg_plus += [np.sqrt(np.mean(score_2))]\n#    mae_reg_plus += [np.mean(score)]\n#    i += 1\n#    print('Fold', i)\n#    print('RMSE: {:.4f}'.format(np.sqrt(np.mean(score_2))))\n#    print('MAE: {:.4f}'.format(np.mean(score)))\n#    print('-'*12)\n#print('-'*12)\n#print('Mean RMSE: {:.4f}'.format(np.mean(rmse_reg_plus)))\n#print('Mean MAE: {:.4f}'.format(np.mean(mae_reg_plus)))\n#print('-'*12)\n#print('-'*12)","meta":"{'source': 'AI4Code', 'id': '582c5ad0871c64'}"}
